Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

docs/prompts: hoist runtime injections to a single trailing section to keep KV-cache prefix stable

aiservice83fb19674553
diff --git a/CLAUDE.md b/CLAUDE.md
index 0155d93e..ffbc531e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -13,6 +13,7 @@ Single-process Electron desktop app: main = Node backend, renderer = vanilla HTM
- The renderer talks through the `contextBridge`-exposed `window.orkas.{invoke, stream}` allow-list API; **do not introduce** TS / JSX / webpack / vite.
- Preload **must be `.js`** (the preload loader does not run the tsx hook); path is `src/main/preload.js`.
- All LLM calls go through the in-process `core-agent` (`import('#core-agent')` dynamic load); no subprocesses. **Why:** avoid IPC serialization; locks / cancellation / event streams share memory.
+- **Local CLI agents are the one explicit exception** — agents whose spec carries `runtime.kind === 'cli'` (claude code / codex / openclaw / opencode / hermes) are spawned as child processes by `features/local_agents/runner.ts`. **`features/local_agents/` is the sole `child_process.spawn` entry point for CLI dispatches**; `bus.ts` routes here, every other `features/*` module is forbidden from spawning these CLIs directly. **Why:** a single spawn entry guarantees uniform persistence (`<uid>/local/file_cache/local-agent-runs/<runId>/`), cancellation (AbortSignal → SIGTERM → 10s grace → SIGKILL), and 5-CLI fanout discipline — bypassing it leaks zombies and forks the run-history schema.
- Storage is JSON / JSONL primarily; sqlite is used in exactly one place — the KB vector store. **Why:** user data must stay readable, portable, and friendly to cloud sync (single file = single sync unit).
- **skill / agent / contexts are three first-class citizens**; multi-agent collaboration follows the §5 group-chat architecture, with **no more "main agent calls subagent over RPC"**.
- npm dependency allow-list is in `PC/package.json` (key entries: `electron / pi-ai / better-sqlite3 / sqlite-vec / fastembed / onnxruntime-node / pdfjs-dist / pdf-lib / mammoth / jimp`). **New dependencies require a discussion first.**
@@ -63,6 +64,7 @@ util/ Pure-function utilities (stdlib only or single third-party d
- `index.ts` / `ipc/` → `features/` / `storage` / `paths` / `prompts`
- `features/` → `storage` / `paths` / `prompts` / `model` / `util` / sibling features
- `model/core-agent/` → dynamic `import('#core-agent')`; locks via `util/locks`; **never read or write business data under data/** (only session jsonl). **Why:** the model layer is stateless; orchestration of business state lives only in features. The model layer touching business data = double-write = state desync.
+- `features/local_agents/` is the **only feature module allowed to import `child_process`**. Other features must call `local_agents/runner.run(...)` for CLI dispatches; never spawn a coding CLI from anywhere else.
**Key model/core-agent constraints** (each *-tool.ts has a header comment with the implementation details):
- **Adding a new tool** = entry in `tool-catalog.ts::TOOL_CATALOG` (the anti-drift test relies on this) + register with the runner; system-prompt order is fixed `[systemPrompt → skillsBlock]` (KV-cache stable prefix first). **Tool descriptions go only through the SDK tool-use protocol's API tools field** (full description + JSON schema); **do not inject a "## Available tools" block into the prompt** — that's both duplication and a variable prefix that pollutes the cache.
@@ -82,7 +84,9 @@ util/ Pure-function utilities (stdlib only or single third-party d
Exception: env-var names with the project prefix (`ORKAS_NODE` / `ORKAS_PC_DIR`) are allowed when actually referenced in bash. Before adding/changing a prompt, `grep "Orkas\|/Users/\|/home/\|PC/data\|PC/src" src/main/prompts/*.md` should come back clean.
-**Cross-prompt sync constraint for shared core rules**: when the same domain concept appears across multiple prompt mds (typical example: `<agent>` container creation appears in both `chat_agent_setup.md` (iterative editing) and `chat_commander.md` (one-shot finalization)), pick one authoritative prompt as the source of truth (e.g. `<agent>` truth source = `chat_agent_setup.md`); downstream sites carry only the shared principles (workflow split into "input → action → output" / tool priority / `<interactive>` decision rules / forbidden prose tokens), and **do not** copy field details / schema tables / full translation tables. **Before touching the truth source**, run `grep -E "<agent>|<workflow>|<skills>|<inputs>|<interactive>|<description_zh>|<description_en>|<<<skill-file>>>|agent-input-form|agent-input-submission" src/main/prompts/*.md` to find downstream sites and reconcile; new rules that affect downstream must be propagated. The loader does not do template composition (only `$variable` substitution), so consistency relies on the caller actively syncing + git review catching gaps.
+**Cross-prompt sync constraint for shared core rules**: when the same domain concept appears across multiple prompt mds (typical example: `<agent>` container creation appears in both `chat_agent_setup.md` (iterative editing), `chat_agent_setup_cli.md` (CLI-backed agent editing — no `<workflow>`/`<skills>`/`<runtime>` sub-tags), and `chat_commander.md` (one-shot finalization)), pick one authoritative prompt as the source of truth (e.g. `<agent>` truth source = `chat_agent_setup.md`); downstream sites carry only the shared principles (workflow split into "input → action → output" / tool priority / `<interactive>` decision rules / forbidden prose tokens), and **do not** copy field details / schema tables / full translation tables. **Before touching the truth source**, run `grep -E "<agent>|<workflow>|<skills>|<inputs>|<interactive>|<runtime>|<description_zh>|<description_en>|<<<skill-file>>>|agent-input-form|agent-input-submission" src/main/prompts/*.md` to find downstream sites and reconcile; new rules that affect downstream must be propagated. The loader does not do template composition (only `$variable` substitution), so consistency relies on the caller actively syncing + git review catching gaps.
+
+**Prompt-md cache layout** (KV-cache prefix discipline): every `src/main/prompts/<name>.md` is split into two halves — **static rules first, then a single trailing `## Runtime injection` section that collects every `$variable` substitution** (with the most volatile field at the bottom of that section). Final assembled order = `<role>.md` static body → `chat_shared_rules.md` (when applicable) → `<role>.md` `## Runtime injection` → `buildLanguageDirective()`. The shared block is wedged in front of the runtime block by `bus.ts::concatSharedRules`; the language directive is appended last by `appendLanguageDirective`. **No `## Current xxx` / "current state" block at the top of the file** — anything the LLM itself rewrites mid-session (`<agent>` writeback / `<<<skill-file>>>` / `plan_set` / form submissions: `$name` / `$description*` / `$workflow` / `$skill_dir` / `$skill_files` / `$plan_state` / `$agents_index` / `$inputs_schema` / `$interactive`) goes only into the trailing runtime section. **Why:** putting volatile fields up front means the very next turn rewrites the cache prefix and we eat a full re-prefill; `chat_agent_setup.md` / `chat_agent_setup_cli.md` / `chat_skill_setup.md` shipped with a top-of-file `## Current agent` / `## Current skill` block, every edit turn invalidated the cache, and the fix was to consolidate those into the trailing `## Runtime injection` section. Same applies to any new prompt md added under `src/main/prompts/`. Path-constants that are fixed for the lifetime of a session (`$builtin_*_dir` / `$custom_*_dir` / `$working_dir`) are session-stable and may stay inline in the body; only fields that the LLM or bus mutate within a session are forbidden in the prefix.
---
@@ -133,10 +137,11 @@ PC/data/
| Skill editing | `<uid>/cloud/chats/skill/<sid>/chat.jsonl` | `<uid>-skill-<sid>` |
| Agent editing | `<uid>/cloud/chats/agent/<aid>/chat.jsonl` | `<uid>-agent-<aid>` |
| KB image understanding | (no UI) | `<uid>-extract-img-<hex>` |
+| CLI agent dispatch | (no jsonl — per-run files only) | `<uid>-cli-<cli>-<runId>` |
session jsonl files land at `<uid>/cloud/sessions/<session_id>.jsonl` — they are **two independent files** from the UI message list.
-**Security invariant**: `session_id` must be `<uid>-<kind>-<tail>`, with the uid in the first segment, and `<kind>` ∈ `gconv | gmember | skill | agent | extract-img | reflect | memory-extract | anon` (`sub` / `organizer` / `conv` are legacy kinds; new code does not generate them, but `migrate-session-ids` preserves these older files). `session-store.ts::sessionFileFor()` enforces this with hard assertions to prevent cross-uid leakage. **Do not** encode brand names (`orkas-` / `aiteam-` / any app name) into session_id — we hit the renaming-breaks-history pitfall once, the startup `migrateLegacySessionIds(uid)` strips legacy prefixes once, and new code never adds them again. Adding a new kind requires extending this table.
+**Security invariant**: `session_id` must be `<uid>-<kind>-<tail>`, with the uid in the first segment, and `<kind>` ∈ `gconv | gmember | skill | agent | extract-img | reflect | memory-extract | anon | cli` (`sub` / `organizer` / `conv` are legacy kinds; new code does not generate them, but `migrate-session-ids` preserves these older files). `session-store.ts::sessionFileFor()` enforces this with hard assertions to prevent cross-uid leakage. **Do not** encode brand names (`orkas-` / `aiteam-` / any app name) into session_id — we hit the renaming-breaks-history pitfall once, the startup `migrateLegacySessionIds(uid)` strips legacy prefixes once, and new code never adds them again. Adding a new kind requires extending this table. The `cli` kind has no `sessions/*.jsonl` (CLI dispatches do not run through core-agent); the id exists purely to give per-run records a stable, kind-tagged identifier.
**Skill injection policy**: edit conversations + group-chat commander = no filtering (inject all); group-chat agent worker = filter by `agent.skill_list` three-state (see §6).
@@ -155,7 +160,7 @@ Members = `commander` + `user` + N `agent` actors (any agent first targeted by `
- **`@<name>` written into prose by commander / agents is NOT recognized as a dispatch signal** (LLM training tends to use `@` as markdown decoration; this used to mis-trigger and produced recurring bugs).
- `dispatch_to` calls only stage; the recipient worker is woken up only after the commander turn fully wraps up (avoiding races; same `pendingPlanAnnouncement` + delayed reconcile pattern as `plan_set`).
-**Single dispatch primitive**: `bus.ts::enqueue(uid, cid, fromActorId, text, [forceTo], ...)` is the only external control-flow entry point for group_chat. `dispatch_to` / `plan_executor` / text @ (user only) all funnel into this single enqueue. **Do not** introduce parallel enqueue functions; new dispatch paths must go through it.
+**Single dispatch primitive**: `bus.ts::enqueue(uid, cid, fromActorId, text, [forceTo], ...)` is the only external control-flow entry point for group_chat. `dispatch_to` / `plan_executor` / text @ (user only) / **CLI-backed agent worker turns** (their post-CLI reply still goes back through `bus.enqueue`, no shortcut) all funnel into this single enqueue. **Do not** introduce parallel enqueue functions; new dispatch paths must go through it.
**Key constraints**:
- **Visibility slice** (security invariant): agent X sees only messages where `from==X ∨ to∋X ∨ mentions∋X`; workers must go through `visibility.readSlice` and **never read the full `<cid>.jsonl`** (which would leak other actors' private context).
@@ -195,6 +200,8 @@ Sources = `src/builtin/skills/` (git-tracked, hash-synced into `data/builtin/ski
**`agent.skill_list` three-state**: `undefined` = no filtering (legacy compatibility) / `[]` = zero skills / non-empty = a strict subset. `updateCustomAgent` only does "filter unknown ids" before saving; it does not expand a closure. The field is auto-maintained by the agent-edit LLM via the `<agent><skills>` sub-tag; **the frontend does not expose hand-editing**.
+**CLI-backed agents (`runtime.kind === 'cli'`) bypass SkillLoader entirely** — `skill_list` is ignored at dispatch time, the system prompt isn't built (the CLI brings its own prompt), and the edit chat uses `chat_agent_setup_cli.md` which forbids the LLM from authoring `<workflow>` / `<skills>` / `<runtime>` sub-tags. The runtime itself (cli + model + custom_args) is owned by the create modal + edit-form, not by the LLM.
+
**Skill scripts default to `.py`** (Python 3, broadest coverage); also allowed: `.ts / .mjs / .js` (via tsx + Node), `.sh` (bash), `.rb` (ruby). **Why:** the vast majority of external-ecosystem skills are written in py; forcing rewrites is a high bar and bug-prone; py ships with macOS/Linux and Windows installs once. **All invocation goes through** `bin/run-skill.cjs <id> <basename>` (no extension); the runner dispatches by extension: `.py` → `python3` (Win: `py -3` → `python`); `.ts/.mjs/.js` → require + default export; `.sh` → `bash`; `.rb` → `ruby`. The subprocess gets `ORKAS_SKILL_ID` / `ORKAS_SKILL_DIR` env injected; stdio passthrough; exit code propagated. Skill directories must not contain `node_modules / package.json / requirements.txt / Gemfile` or other package-manager artifacts; `.ts` may use the existing PC npm allow-list (new deps follow §1), other languages use only the corresponding runtime stdlib.
**Per-user enable/disable** (shared by agent + skill, stored at `<uid>/cloud/config/component-enabled.json`, **only `false` is recorded**): the single resolver entrypoint is `features/component_enabled.ts::isAgentEnabled / isSkillEnabled`. **Only 4 filter application sites** (do not add filtering elsewhere):
@@ -333,6 +340,6 @@ The commit message is **about the change**, not about how it got here. Sync prov
**Logging** is `src/main/logger.ts` (a thin wrapper over electron-log): main + renderer both write `data/logs/YYYY-MM-DD.log` (rolls to `.old.log` past 10 MB; startup `sweepLogs()` cleans up by ≥7 days / ≤100 MB; today's file is never deleted). The renderer forwards via IPC and lands as `renderer/<module>` scope. Redaction hook + `REDACT_KEYS` list live in `logger.ts`. Set log level via `ORKAS_LOG_LEVEL=debug`.
-**New code must**: use `createLogger('<module>')` instead of `console.log`; key entry points in main flows emit `log.info` (start + key fields userId/path/ms); **before catch / failure return, you must `log.warn` (recoverable) or `log.error` (invariant broken)** — only returning `{ok:false}` without a log = the upstream can't locate the issue; sensitive fields go through `REDACT_KEYS`.
+**New code must**: use `createLogger('<module>')` instead of `console.log`; key entry points in main flows emit `log.info` (start + key fields userId/path/ms); **before catch / failure return, you must `log.warn` (recoverable) or `log.error` (invariant broken)** — only returning `{ok:false}` without a log = the upstream can't locate the issue; sensitive fields go through `REDACT_KEYS`. The local CLI agent stack uses `local-agents` for the registry / runner and per-backend scopes (`local-agents:claude` / `:codex` / `:openclaw` / `:opencode` / `:hermes`); spawn failures, missing-CLI hits, non-zero exit codes, and ACP parse errors must each emit a `log.warn` so dispatched-task issues are diagnosable from `data/logs/` alone.
The open-source build has **no built-in remote telemetry / third-party analytics, and no in-app debug panel**; diagnose via logs + Chromium DevTools (F12).
diff --git a/src/main/prompts/chat_agent_setup.md b/src/main/prompts/chat_agent_setup.md
index f105010c..019eaa55 100644
--- a/src/main/prompts/chat_agent_setup.md
+++ b/src/main/prompts/chat_agent_setup.md
@@ -3,18 +3,6 @@ You are working with the user to refine a custom agent — polish its "name / de
---
-## Current agent
-- **Name**: $name
-- **Description (Chinese)**: $description_zh
-- **Description (English)**: $description_en
-- **Interactive mode**: $interactive
-- **Workflow**:
-```
-$workflow
-```
-
----
-
## What to focus on
1. **Understand the user's intent**: what does the user want this agent to do? Whose problem does it solve? Is it one-shot or repeated runs? When info is insufficient, list questions in one batch and have the user fill them — don't guess or spin in place.
@@ -201,3 +189,16 @@ This field decides whether, when the agent is dispatched, the input box **automa
## Other
- If the user asks something unrelated to the agent, just answer normally; afterwards, ask if they want to keep refining the agent.
- Keep replies concise; advance step by step; don't dump huge content all at once.
+
+---
+
+## Runtime injection
+
+- **Name**: $name
+- **Description (Chinese)**: $description_zh
+- **Description (English)**: $description_en
+- **Interactive mode**: $interactive
+- **Workflow**:
+```
+$workflow
+```
diff --git a/src/main/prompts/chat_agent_setup_cli.md b/src/main/prompts/chat_agent_setup_cli.md
index 626f432b..dc441568 100644
--- a/src/main/prompts/chat_agent_setup_cli.md
+++ b/src/main/prompts/chat_agent_setup_cli.md
@@ -7,14 +7,6 @@ This agent does **not** run inside this system. When dispatched, it spawns a loc
---
-## Current agent
-- **Name**: $name
-- **Description (Chinese)**: $description_zh
-- **Description (English)**: $description_en
-- **Interactive mode**: $interactive
-
----
-
## What to focus on
1. **Understand the user's intent**: what does the user want this agent to do? What kind of coding task does it own (review / scaffolding / migration / quick prototyping / debugging…)? Whose problem does it solve? When info is insufficient, list questions in one batch and have the user fill them — don't guess.
@@ -146,3 +138,12 @@ Decides whether, when the agent is dispatched, the input box auto-retargets to t
## Other
- If the user asks something unrelated to the agent, just answer normally; afterwards, ask if they want to keep refining.
- Keep replies concise; advance step by step.
+
+---
+
+## Runtime injection
+
+- **Name**: $name
+- **Description (Chinese)**: $description_zh
+- **Description (English)**: $description_en
+- **Interactive mode**: $interactive
diff --git a/src/main/prompts/chat_skill_setup.md b/src/main/prompts/chat_skill_setup.md
index 1c923945..ee46b230 100644
--- a/src/main/prompts/chat_skill_setup.md
+++ b/src/main/prompts/chat_skill_setup.md
@@ -1,15 +1,6 @@
## Core task
Help the user **design a high-quality, self-contained skill** that an LLM can stably select and invoke in the right scenarios.
-## Current skill
-- Name: $skill_name
-- Description (Chinese): $skill_description_zh
-- Description (English): $skill_description_en
-- Skill directory: $skill_dir
-
-## Files currently in the skill directory
-$skill_files
-
## 1. What a skill is (core mental model)
**A skill is not a tutorial, not a documentation snippet. A skill is "an independent tool capability"**: when the LLM sees a matching user request, it picks this skill, invokes it once or a few times per the interface described in `SKILL.md`, takes the result, and folds it into the answer.
@@ -75,7 +66,7 @@ The URL might be clawhub / GitHub / a skill-introduction blog post / raw SKILL.m
All files in the directory **have already been copied into this skill's directory**. Flow:
-1. First do `bash ls -R` or `search_files` to inspect the current state (don't ask the user "where is that file?" — they're under `$skill_dir/`).
+1. First do `bash ls -R` or `search_files` to inspect the current state (don't ask the user "where is that file?" — they're under the current skill directory).
2. Read the main files (SKILL.md, scripts, config) to understand the capability.
3. Follow the "**Import optimization rules**" below to organize SKILL.md and the scripts.
4. When done, summarize: what the source directory was, which files you kept / rewrote / deleted, and what SKILL.md says.
@@ -207,3 +198,15 @@ Wrong example:
Right example:
> I've written `SKILL.md`: this skill is invoked when the user asks "scrape data from platform X". The script `scripts/fetch.py` takes a keyword argument and outputs JSON.
+
+---
+
+## Runtime injection
+
+- Name: $skill_name
+- Description (Chinese): $skill_description_zh
+- Description (English): $skill_description_en
+- Skill directory: $skill_dir
+
+### Files currently in the skill directory
+$skill_files