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.

Unify data root and remove dev-vs-prod behavior split

wyte8d6193d0389
diff --git a/CLAUDE.md b/CLAUDE.md
index 18bf7d65..e51e77a2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -43,7 +43,7 @@ PC/ Electron project root, sole dev and packaging entry
└── src/builtin/skills/ Built-in skill source (synced by hash to data/builtin/skills/ on startup)
```
-**Runtime data location**: dev = `PC/data/` + `PC/userWorkSpace/`; packaged = `<container>/{data,userWorkSpace}/`, where the container is chosen as macOS/Linux → `~/.orkas/`, Windows → the lowest-letter non-system fixed drive `<drive>:\.orkas\` (falling back to `C:\` if none). Full drive selection logic lives in `src/main/packaged-data-root.ts`.
+**Runtime data location**: dev source-run and packaged builds use the SAME `<container>/{data,userWorkSpace}/` tree — no dev-vs-packaged data split. Container = `~/.orkas/` on macOS/Linux; on Windows it's the drive recorded in `%LOCALAPPDATA%\Orkas\install-pin.json` — chosen on first launch (lowest-letter non-system fixed drive, fallback `C:`) and reused on subsequent launches. The pin lives in LocalAppData (machine-private), not Roaming, because it records a drive choice on this specific machine. Full container resolution + pin handling logic lives in `src/main/install-data-root.cjs`. Pre-unification source-run `<repoRoot>/data` + `<repoRoot>/userWorkSpace` are migrated into the container by `src/main/util/migrate-source-data-root.cjs` on first launch (overlay merge: src wins per-file conflict, target-only paths preserved, `users.json::users[]` unioned with a `current_user_id` dangling-pointer guard).
---
@@ -334,6 +334,9 @@ The renderer evaluates `<script>`-loaded files where `module` is undefined, so t
### Don't do
+**Dev environment / OSS strip**:
+- Branch business behavior on `app.isPackaged` / `process.env.NODE_ENV` / `isDevMode` / `isDevEnv`. Dev (source-run via `./run.sh`) and packaged builds must be functionally identical; the only `app.isPackaged` branches allowed are pure-infrastructure (data-root path, devTools toggle, `app.asar.unpacked` rewrite). **Why:** OrkasOpen ships from a synced upstream tree where the closed-source dev-only branches were stripped; reintroducing a dev branch here re-creates the divergence the strip rules exist to prevent. Enforcement: forbidden symbols + `isPackaged_allowed_files` allowlist live in `OpenSource/SyncCode/strip-rules.json`; `node OpenSource/SyncCode/bin/oss-sync-postcheck.mjs` must exit 0 after every sync.
+
**Layering / paths**:
- Write business in `ipc/` (skipping a layer); call core-agent directly / spawn processes from `features/`.
- Storage paths missing the `<uid>` segment; session_id where the second segment isn't the uid.
diff --git a/bootstrap.cjs b/bootstrap.cjs
index f43188a7..0fed8e91 100644
--- a/bootstrap.cjs
+++ b/bootstrap.cjs
@@ -1,28 +1,23 @@
// Electron entry shim: register tsx so the main process can
// `require('./src/main')` and resolve to src/main/index.ts (Node folder →
// index.ts rule + tsx/cjs transpilation). Keeps __dirname semantics identical
-// to running plain JS — no compile step in dev.
+// to running plain JS — no compile step.
//
// 两件事必须在 tsx 注册前完成:
-// 1. Hooks:`tsx/cjs` 处理 src/main/**/*.ts 的同步 require;`tsx/esm/api`
+// 1. **WS_ROOT env 注入**:require('./src/main/install-data-root.cjs') 的
+// 模块加载副作用解析容器目录、跑一次性 source-run → container 迁移、
+// mkdir、写入 process.env.ORKAS_WORKSPACE_ROOT。**必须在 tsx 加载任何
+// .ts 前完成** —— paths.ts 把 ORKAS_WORKSPACE_ROOT 在 import 时
+// snapshot 成 WS_ROOT,任何先加载 paths.ts 的路径都会读到空。CJS require
+// 没有 hoist 问题,这层在 .cjs 里做最稳。
+// 2. Hooks:`tsx/cjs` 处理 src/main/**/*.ts 的同步 require;`tsx/esm/api`
// 处理动态 `import()`(尤其 `import('#core-agent')`)。
-// 2. **packaged 模式 WS_ROOT env 重定向**:必须在任何 TS 加载前完成 ——
-// TypeScript 把 `import * as paths from './paths'` 提升到所有非 import
-// 语句之前,index.ts 内"先 set env 再 import paths"的写法在编译后会被
-// 打乱顺序,paths.ts 在 env 还没设置时就快照了空值,WS_ROOT 落到
-// .app 包内。CJS 的 require 没有提升问题,所以这层必须在 .cjs 里做。
+//
+// dev (源码运行) 和 packaged 走同一条路径 —— 无 isPackaged 分叉,容器解析、
+// 迁移、env 注入对两种入口形态行为完全一致。
'use strict';
-(function pinPackagedWorkspaceRoot() {
- const { app } = require('electron');
- if (!app.isPackaged || process.env.ORKAS_WORKSPACE_ROOT) return;
- const path = require('path');
- const fs = require('fs');
- const { resolvePackagedContainer } = require('./src/main/packaged-data-root.cjs');
- const ws = path.join(resolvePackagedContainer(), 'data');
- fs.mkdirSync(ws, { recursive: true });
- process.env.ORKAS_WORKSPACE_ROOT = ws;
-})();
+require('./src/main/install-data-root.cjs');
require('tsx/cjs');
require('tsx/esm/api').register();
diff --git a/src/main/features/local_agents/runner.ts b/src/main/features/local_agents/runner.ts
index 68ee69ea..c708340a 100644
--- a/src/main/features/local_agents/runner.ts
+++ b/src/main/features/local_agents/runner.ts
@@ -164,10 +164,8 @@ export async function run(opts: RunCliAgentOpts): Promise<RunCliAgentResult> {
log.info('end', {
runId: handle.runId, cli: opts.cli, status: terminal.status, bytes: finalOutput?.length ?? 0,
});
- // The PC build also archives the run into the in-app debug panel
- // (`devtools.archiveLlmCall`); the open-source build has no debug
- // panel, so the per-run jsonl under `local-agent-runs/<runId>/`
- // (written by `persist`) is the only artifact.
+ // The per-run jsonl under `local-agent-runs/<runId>/` (written by
+ // `persist`) is the only post-run artifact.
return { runId: handle.runId, status: terminal.status, output: finalOutput, error: terminal.error };
}
diff --git a/src/main/i18n.ts b/src/main/i18n.ts
index 1e87b4a5..313d8020 100644
--- a/src/main/i18n.ts
+++ b/src/main/i18n.ts
@@ -9,8 +9,8 @@
* UI instead of going silently blank).
*
* Used by features/* to produce localized `error` fields returned to the
- * renderer. LLM prompts, logs, and telemetry remain in their source language
- * and are NOT routed through here.
+ * renderer. LLM prompts and logs remain in their source language and are
+ * NOT routed through here.
*/
import * as path from 'node:path';
diff --git a/src/main/index.ts b/src/main/index.ts
index aa3d86fb..be43476f 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -55,12 +55,13 @@ protocol.registerSchemesAsPrivileged([
},
]);
-// Packaged-mode WS_ROOT redirect (`~/.orkas/data` or a Windows container
-// drive) is already done in `bootstrap.cjs`, and **must** happen there —
-// TypeScript's import hoisting would pull `paths.ts`'s require ahead of
-// any env-setting block here, so doing it later is too late. Drive
-// selection rules live in `packaged-data-root.cjs`, required directly by
-// `bootstrap.cjs`.
+// WS_ROOT env injection (`~/.orkas/data` on mac/linux; Windows pinned
+// drive's `<drive>:\.orkas\data`) is already done in `bootstrap.cjs` via
+// `install-data-root.cjs`, and **must** happen there — TypeScript's
+// import hoisting would pull `paths.ts`'s require ahead of any
+// env-setting block here, so doing it later is too late. Container
+// resolution + Windows pin + source-run migration logic lives in
+// `src/main/install-data-root.cjs`.
import * as paths from './paths';
// `CORE_AGENT_AUTH_DIR` is pinned per-uid by `features/users.activateUser()`
@@ -84,9 +85,9 @@ const log = createLogger('orkas');
import { installSdkTimeoutPatch } from './model/core-agent/sdk-timeout-patch';
installSdkTimeoutPatch();
-// Opt-in provider-fetch diagnostics (gated by ORKAS_FETCH_DIAG=1).
-// Default off — zero overhead for end users. Set the env var when
-// investigating fetch-level failures to dump the real undici cause chain.
+// Provider-fetch diagnostics — always on. Dumps the real undici cause
+// chain (the cause that pi-ai's internal retry loop would otherwise
+// swallow) into data/logs/. See fetch-diag.ts.
import { installFetchDiag } from './model/core-agent/fetch-diag';
installFetchDiag();
diff --git a/src/main/install-data-root.cjs b/src/main/install-data-root.cjs
new file mode 100644
index 00000000..4613b66c
--- /dev/null
+++ b/src/main/install-data-root.cjs
@@ -0,0 +1,248 @@
+/**
+ * Platform-aware resolution of the install data root + boot-time env-var
+ * initialization. Source-run (dev) and packaged builds resolve to the SAME
+ * container — no dev-vs-prod data split.
+ *
+ * Two responsibilities packed in one file:
+ *
+ * 1. `resolveInstallContainer()` (exported, pure) — returns the
+ * container directory (without the trailing `/data`); callers append
+ * `/data` and `/userWorkSpace` themselves (the latter is derived
+ * automatically by `paths.ts::DEFAULT_USER_WORKSPACE` via the
+ * `WS_ROOT/../userWorkSpace` sibling convention).
+ *
+ * - macOS / Linux: `~/.orkas`
+ * - Windows: drive recorded in `%LOCALAPPDATA%\Orkas\install-pin.json`
+ * (chosen on first launch — lowest-letter non-system fixed drive,
+ * fallback `C:`). The pin file lives in LocalAppData
+ * (machine-private), not Roaming (cross-machine), because it
+ * records a drive choice on THIS machine.
+ *
+ * 2. **Module-load side effect** — the `_initInstallRoot()` IIFE at the
+ * bottom resolves the container, runs the one-shot source-run
+ * `<repoRoot>/data` → `<container>/data` migration, and sets
+ * `process.env.ORKAS_WORKSPACE_ROOT`. **This MUST be a `.cjs` file
+ * called from `bootstrap.cjs` BEFORE `tsx/cjs` is registered:** any
+ * TypeScript module that touches `paths.ts` reads `WS_ROOT` from the
+ * env var at module-load time, and TS import hoisting would otherwise
+ * let `paths.ts` snapshot an unset env var before `index.ts` body
+ * could set it. CJS require has no hoisting; doing this in
+ * bootstrap.cjs's pre-tsx phase keeps the contract simple.
+ *
+ * `ORKAS_WORKSPACE_ROOT` already set → short-circuit, letting tests
+ * (`test/setup-env.ts`) and power users override the whole flow.
+ */
+
+'use strict';
+
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+
+// Early-boot diagnostics buffer. This file runs before logger.ts can be
+// loaded (logger imports paths.ts, which depends on the env var THIS file
+// sets), so logger calls aren't available yet. Warnings are buffered here
+// and `flushEarlyDiagnostics` replays them into the daily log after
+// `initLogger()`, so post-mortem on pin / migration decisions doesn't
+// require attaching terminal output.
+const _earlyDiagnostics = [];
+function _earlyWarn(msg) {
+ _earlyDiagnostics.push(msg);
+ process.stderr.write(msg);
+}
+
+function flushEarlyDiagnostics(sink) {
+ for (const m of _earlyDiagnostics) sink(m.replace(/\n+$/, ''));
+ _earlyDiagnostics.length = 0;
+}
+
+function resolveInstallContainer() {
+ if (process.platform === 'win32') return resolveWindowsContainer();
+ return path.join(os.homedir(), '.orkas');
+}
+
+// ── Windows pin file ─────────────────────────────────────────────────────
+
+function localAppDataDir() {
+ // %LOCALAPPDATA% is set on Win 7+; fallback constructs the canonical path.
+ return process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
+}
+
+function pinFilePath() {
+ return path.join(localAppDataDir(), 'Orkas', 'install-pin.json');
+}
+
+function readPin() {
+ try {
+ const raw = fs.readFileSync(pinFilePath(), 'utf8');
+ const obj = JSON.parse(raw);
+ if (obj && typeof obj.container === 'string' && obj.container) {
+ return { container: obj.container, chosenAt: String(obj.chosenAt || '') };
+ }
+ } catch {
+ /* missing or malformed → null */
+ }
+ return null;
+}
+
+/**
+ * Write the pin atomically (`wx` flag = exclusive create). If another
+ * process raced and won, defer to its decision when the pinned container
+ * is live; overwrite when the existing pin is dead (drive unreachable).
+ * Returns the container the caller should actually use.
+ *
+ * Why: install-data-root.cjs runs at boot, BEFORE
+ * `app.requestSingleInstanceLock()` can take effect. Two simultaneous
+ * launches both decide a container, both `writePin`, then both `mkdir +
+ * migrate` — picking different drives is rare but destructive (user data
+ * lands on the wrong drive). `wx` makes the first writer the authority.
+ */
+function writePin(container) {
+ const pinPath = pinFilePath();
+ const body = { container, chosenAt: new Date().toISOString() };
+ fs.mkdirSync(path.dirname(pinPath), { recursive: true });
+ try {
+ fs.writeFileSync(pinPath, JSON.stringify(body, null, 2), { flag: 'wx' });
+ return container;
+ } catch (err) {
+ if (err && err.code === 'EEXIST') {
+ const winner = readPin();
+ if (winner && pinIsLive(winner)) {
+ _earlyWarn(
+ `[install-data-root] pin race: deferring to existing pin ${winner.container}\n`,
+ );
+ return winner.container;
+ }
+ // Stale / dead / unreadable pin — overwrite with our decision.
+ try {
+ fs.writeFileSync(pinPath, JSON.stringify(body, null, 2), 'utf8');
+ } catch (err2) {
+ _earlyWarn(
+ `[install-data-root] failed to overwrite stale pin: ${err2.message}\n`,
+ );
+ }
+ return container;
+ }
+ _earlyWarn(`[install-data-root] failed to write pin: ${err.message}\n`);
+ return container;
+ }
+}
+
+function pinIsLive(pin) {
+ // The pin records a container path like "D:\.orkas". Consider it live
+ // if the drive root is reachable. The container directory itself may
+ // not yet exist (first-launch race: pin written, process killed before
+ // mkdir of <container>/data) — drive-level reachability is the right
+ // signal.
+ try {
+ const driveRoot = path.parse(pin.container).root;
+ if (!driveRoot) return false;
+ return fs.existsSync(driveRoot);
+ } catch {
+ return false;
+ }
+}
+
+function resolveWindowsContainer() {
+ // 1. Pin present + drive reachable → use it.
+ const pin = readPin();
+ if (pin && pinIsLive(pin)) return pin.container;
+ if (pin) {
+ _earlyWarn(
+ `[install-data-root] pinned container ${pin.container} unreachable; re-deciding\n`,
+ );
+ }
+
+ // 2. Pin missing / dead → first-launch decision.
+ const systemDrive = normalizeDrive(process.env.SystemDrive || 'C:');
+ const fixed = listFixedDrivesWin();
+ const nonSystem = fixed.filter((d) => d !== systemDrive).sort();
+
+ // 2a. Existing install present → keep it in place.
+ for (const d of nonSystem) {
+ if (hasExistingInstall(d)) return writePin(containerFor(d));
+ }
+ if (hasExistingInstall(systemDrive)) return writePin(containerFor(systemDrive));
+
+ // 2b. Fresh install: lowest-letter non-system fixed drive; system drive
+ // fallback when only one fixed drive exists.
+ const chosen =
+ nonSystem.length > 0 ? containerFor(nonSystem[0]) : containerFor(systemDrive);
+ return writePin(chosen);
+}
+
+function containerFor(drive) {
+ return path.join(drive + '\\', '.orkas');
+}
+
+function hasExistingInstall(drive) {
+ try {
+ return fs.existsSync(path.join(drive + '\\', '.orkas', 'data'));
+ } catch {
+ return false;
+ }
+}
+
+function normalizeDrive(s) {
+ const m = String(s).toUpperCase().match(/^([A-Z]:)/);
+ return m ? m[1] : 'C:';
+}
+
+function listFixedDrivesWin() {
+ // First choice is PowerShell's Win32_LogicalDisk (built into Win7+);
+ // DriveType=3 = DRIVE_FIXED. On failure we'd rather fall back to "system
+ // drive only" than use fsutil to list every drive — fsutil can't
+ // distinguish fixed / removable / network drives, and we explicitly want
+ // the latter two excluded.
+ try {
+ const out = execFileSync(
+ 'powershell.exe',
+ [
+ '-NoProfile',
+ '-NonInteractive',
+ '-Command',
+ "Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' | Select-Object -ExpandProperty DeviceID",
+ ],
+ { encoding: 'utf8', timeout: 5000, windowsHide: true },
+ );
+ const drives = out
+ .split(/\r?\n/)
+ .map((s) => s.trim().toUpperCase())
+ .filter((s) => /^[A-Z]:$/.test(s));
+ if (drives.length > 0) return drives;
+ } catch {
+ /* fall through */
+ }
+ return [normalizeDrive(process.env.SystemDrive || 'C:')];
+}
+
+// ── Module-load setup ────────────────────────────────────────────────────
+// IIFE: resolve the container, migrate any pre-unification source-run data
+// into it, and set `ORKAS_WORKSPACE_ROOT`. Runs once at require time. The
+// `ORKAS_WORKSPACE_ROOT` short-circuit lets tests / power users override
+// the whole flow by pre-setting the env var.
+(function _initInstallRoot() {
+ if (process.env.ORKAS_WORKSPACE_ROOT) return;
+
+ const container = resolveInstallContainer();
+
+ // Migration is best-effort: a failure here should not block boot. The
+ // source-run `<repoRoot>/data` is left in place for retry;
+ // `<container>/data` is still mkdir'd below so paths.ts has a usable
+ // WS_ROOT either way.
+ try {
+ const { migrateSourceDataRoot } = require('./util/migrate-source-data-root.cjs');
+ migrateSourceDataRoot(container);
+ } catch (err) {
+ _earlyWarn(
+ `[install-data-root] source-run data migration failed: ${err.message}\n`,
+ );
+ }
+
+ const ws = path.join(container, 'data');
+ fs.mkdirSync(ws, { recursive: true });
+ process.env.ORKAS_WORKSPACE_ROOT = ws;
+})();
+
+module.exports = { resolveInstallContainer, flushEarlyDiagnostics };
diff --git a/src/main/model/core-agent/fetch-diag.ts b/src/main/model/core-agent/fetch-diag.ts
index d77a7329..e8b8b9af 100644
--- a/src/main/model/core-agent/fetch-diag.ts
+++ b/src/main/model/core-agent/fetch-diag.ts
@@ -8,26 +8,16 @@
* UND_ERR_SOCKET, ECONNRESET, ENOTFOUND, …) is on `err.cause` / `err
* .cause.cause`.
* - pi-ai catches those errors internally, keeps only `error.message`,
- * and retries up to 3 times. By the time the error reaches Orkas, the
- * cause chain is long gone — so the `fetch failed` the user sees has
- * no actionable signal.
- *
- * When it runs:
- * - **dev mode** (`!app.isPackaged`): always on — `./run.sh` auto-installs
- * so failures during local debugging surface their real cause.
- * - **packaged**: opt-in via `ORKAS_FETCH_DIAG=1` — zero overhead for
- * regular users.
+ * and retries up to 3 times. By the time the error reaches the host,
+ * the cause chain is long gone — so the `fetch failed` the user sees
+ * has no actionable signal.
*
* Scope:
- * - Wraps `globalThis.fetch` once.
+ * - Wraps `globalThis.fetch` once at boot, unconditionally.
* - Filters by URL so only LLM-provider traffic is logged — not
- * arbitrary `web_fetch`, KB embedder downloads, or telemetry pings.
- *
- * Usage in packaged builds:
- * ORKAS_FETCH_DIAG=1 <launch the app>
- * grep "fetch-diag" data/logs/YYYY-MM-DD.log
+ * arbitrary `web_fetch` or KB embedder downloads.
+ * - Output lands in `data/logs/YYYY-MM-DD.log`; grep for `fetch-diag`.
*/
-import { app } from 'electron';
import { createLogger } from '../../logger';
const log = createLogger('fetch-diag');
@@ -35,9 +25,6 @@ const log = createLogger('fetch-diag');
const PROVIDER_HOST_RE = /\b(openai\.com|anthropic\.com|chatgpt\.com|googleapis\.com|moonshot\.cn|api\.moonshot|bedrock|codex)\b/i;
export function installFetchDiag(): void {
- // Dev: auto-on. Packaged: opt-in via env var.
- const isDev = !app.isPackaged;
- if (!isDev && process.env.ORKAS_FETCH_DIAG !== '1') return;
const original = globalThis.fetch;
if (!original || (original as any).__orkasFetchDiag) return;
@@ -46,8 +33,8 @@ export function installFetchDiag(): void {
typeof input === 'string' ? input :
input?.url ? String(input.url) :
String(input);
- // Only watch provider traffic. Skip everything else so dev-mode KB
- // model downloads etc. don't flood the log.
+ // Only watch provider traffic. Skip everything else so KB model
+ // downloads etc. don't flood the log.
if (!PROVIDER_HOST_RE.test(url)) return original(input, init);
const t0 = Date.now();
@@ -80,5 +67,5 @@ export function installFetchDiag(): void {
};
(wrapped as any).__orkasFetchDiag = true;
globalThis.fetch = wrapped;
- log.info(isDev ? 'installed (dev auto-on)' : 'installed (ORKAS_FETCH_DIAG=1)');
+ log.info('installed');
}
diff --git a/src/main/packaged-data-root.cjs b/src/main/packaged-data-root.cjs
deleted file mode 100644
index 74b4c85d..00000000
--- a/src/main/packaged-data-root.cjs
+++ /dev/null
@@ -1,92 +0,0 @@
-/**
- * Packaged 模式下 data 根目录的平台相关解析(CommonJS)。
- *
- * 返回"容器目录"(不含 `/data` 尾段),调用方自行拼接 `/data` 与
- * `/userWorkSpace`(后者由 `paths.ts::DEFAULT_USER_WORKSPACE` 按
- * `WS_ROOT/../userWorkSpace` 的 sibling 约定自动得出)。
- *
- * - macOS / Linux:`~/.orkas`
- * - Windows:优先字母最小的非系统固定盘(DriveType=3,即 DRIVE_FIXED,
- * 排除可移动盘与网络盘),无非系统固定盘时回落系统盘。
- * 如任一固定盘上已存在 `<drive>:\.orkas\data`,优先保留该盘,避免
- * 后插新盘导致数据"迁移"错位。
- *
- * **CJS 而非 TS 是必须的**:`bootstrap.cjs` 必须在 tsx 注册前完成 WS_ROOT
- * env 设置(否则 TypeScript 的 import 提升会让 paths.ts 在 env 设置前
- * 就快照了空值,WS_ROOT 落到 .app 包内)。bootstrap.cjs 不能 require .ts。
- *
- * 仅 `app.isPackaged` 分支调用;dev 仍走 `PC/data`。
- */
-
-'use strict';
-
-const fs = require('node:fs');
-const os = require('node:os');
-const path = require('node:path');
-const { execFileSync } = require('node:child_process');
-
-function resolvePackagedContainer() {
- if (process.platform === 'win32') return resolveWindowsContainer();
- return path.join(os.homedir(), '.orkas');
-}
-
-function resolveWindowsContainer() {
- const systemDrive = normalizeDrive(process.env.SystemDrive || 'C:');
- const fixed = listFixedDrivesWin();
- const nonSystem = fixed.filter((d) => d !== systemDrive).sort();
-
- // 1) 已有历史安装 → 原地保留(非系统盘优先,系统盘其次)
- for (const d of nonSystem) {
- if (hasExistingInstall(d)) return containerFor(d);
- }
- if (hasExistingInstall(systemDrive)) return containerFor(systemDrive);
-
- // 2) 新装:字母最小的非系统固定盘;单盘回落系统盘
- if (nonSystem.length > 0) return containerFor(nonSystem[0]);
- return containerFor(systemDrive);
-}
-
-function containerFor(drive) {
- return path.join(drive + '\\', '.orkas');
-}
-
-function hasExistingInstall(drive) {
- try {
- return fs.existsSync(path.join(drive + '\\', '.orkas', 'data'));
- } catch {
- return false;
- }
-}
-
-function normalizeDrive(s) {
- const m = String(s).toUpperCase().match(/^([A-Z]:)/);
- return m ? m[1] : 'C:';
-}
-
-function listFixedDrivesWin() {
- // 首选 PowerShell 的 Win32_LogicalDisk(Win7+ 自带);DriveType=3 = DRIVE_FIXED。
- // 失败时宁可回落到"只用系统盘",也不用 fsutil 列全盘 —— 后者无法区分固定 / 可移动 /
- // 网络盘,用户明确要求排除后两者。
- try {
- const out = execFileSync(
- 'powershell.exe',
- [
- '-NoProfile',
- '-NonInteractive',
- '-Command',
- "Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' | Select-Object -ExpandProperty DeviceID",
- ],
- { encoding: 'utf8', timeout: 5000, windowsHide: true },
- );
- const drives = out
- .split(/\r?\n/)
- .map((s) => s.trim().toUpperCase())
- .filter((s) => /^[A-Z]:$/.test(s));
- if (drives.length > 0) return drives;
- } catch {
- /* fall through */
- }
- return [normalizeDrive(process.env.SystemDrive || 'C:')];
-}
-
-module.exports = { resolvePackagedContainer };
diff --git a/src/main/paths.ts b/src/main/paths.ts
index b8204025..bd329e2f 100644
--- a/src/main/paths.ts
+++ b/src/main/paths.ts
@@ -3,52 +3,70 @@
*
* All path constants live here — never hardcode paths elsewhere.
*
- * Layout (dev and packaged both use this tree; only WS_ROOT differs):
+ * Layout (dev source-run and packaged builds both use the same tree —
+ * `WS_ROOT` is identical in both modes, pinned by `install-data-root.cjs`):
*
- * PC_ROOT/ ← source + per-install binaries (asar-packed in prod)
+ * APP_ROOT/ ← source + per-install binaries (asar-packed in prod)
* bootstrap.cjs package.json node_modules/ test/ docs/
* src/
* main/ ← index.ts + preload.js + features/...
* renderer/ builtin/ resources/ core-agent/
- * data/ ← WS_ROOT (dev default); userData/data in prod
- * users.json ← Local uid registry + current_user_id
- * logs/ ← Local logs (rolled daily, global)
- * builtin/ ← Local public builtin runtime copy (hash-synced from src/builtin/ at startup)
- * agents/<agent_id>/
- * skills/<skill_id>/
- * <user_id>/
- * cloud/ ← Cloud-sync domain (synced per uid / org / team once accounts are integrated)
- * chats/ chat_attachments/ sessions/ contexts/ memory/
- * agents/<agent_id>/ skills/<skill_id>/ meta/<agent_id>/
- * config/preferences.json
- * local/ ← Machine-private domain (never synced)
- * config/ ← auth-profiles.json + web-search-cache.json
- * search/ ← contexts / chats inverted idx (agent / skill bodies queried in-memory at request time)
+ *
+ * WS_ROOT (= <container>/data) ← `<container>` = `~/.orkas` on mac/linux,
+ * pinned drive `<drive>:\.orkas` on win
+ * users.json ← Local uid registry + current_user_id
+ * logs/ ← Local logs (rolled daily, global)
+ * builtin/ ← Builtin runtime copy (hash-synced from src/builtin/ at startup)
+ * agents/<agent_id>/
+ * skills/<skill_id>/
+ * <user_id>/
+ * cloud/ ← Cloud-sync domain (synced per uid / org / team once accounts are integrated)
+ * chats/ chat_attachments/ sessions/ contexts/ memory/
+ * agents/<agent_id>/ skills/<skill_id>/ meta/<agent_id>/
+ * config/preferences.json
+ * local/ ← Machine-private domain (never synced)
+ * config/ ← auth-profiles.json + web-search-cache.json
+ * search/ ← contexts / chats inverted idx (agent / skill bodies queried in-memory at request time)
*
* Runtime overrides:
- * ORKAS_WORKSPACE_ROOT point data root elsewhere (src/main/index.ts sets this in packaged builds; env var name predates the dir rename — kept for stability)
+ * ORKAS_WORKSPACE_ROOT point data root elsewhere; tests pre-set this in setup-env.ts.
+ * In normal boot, `install-data-root.cjs` sets it from bootstrap.cjs
+ * before any TS module loads (`paths.ts` reads it at import time —
+ * the env var MUST be set before the first `import * as paths` call).
* ORKAS_BUILTIN_ROOT optional override for the builtin source dir
- * CORE_AGENT_AUTH_DIR pinned by `activateUser()` to the active user's `<uid>/local/config/`
+ * CORE_AGENT_AUTH_DIR pinned by `activateUser()` to the active user's `<uid>/local/config/`
*/
import * as path from 'node:path';
import * as fs from 'node:fs';
// ── Roots ────────────────────────────────────────────────────────────────
-// __dirname = PC/src/main → parents[0]=main, [1]=src, [2]=PC.
-export const SRC_ROOT = path.resolve(__dirname, '..'); // PC/src
-export const PC_ROOT = path.resolve(__dirname, '..', '..'); // PC
+// __dirname = <app-root>/src/main → parents[0]=main, [1]=src, [2]=app-root.
+export const SRC_ROOT = path.resolve(__dirname, '..'); // <app-root>/src
+export const PC_ROOT = path.resolve(__dirname, '..', '..'); // <app-root> — name predates OrkasOpen rename, kept as internal symbol
export const APP_ROOT = PC_ROOT;
-export const PROJECT_ROOT = path.resolve(PC_ROOT, '..'); // Orkas
-
-// ── Data root (env > dev default) ────────────────────────────────────────
-// The on-disk directory name is `data/`; the constant is still named WS_ROOT
-// (a historical abbreviation of "workspace root" — it's an internal TS symbol
-// and not part of any user-facing naming). The env var `ORKAS_WORKSPACE_ROOT`
-// likewise keeps its old name so deployments upgrade transparently.
-export const WS_ROOT = process.env.ORKAS_WORKSPACE_ROOT
- ? path.resolve(process.env.ORKAS_WORKSPACE_ROOT)
- : path.join(PC_ROOT, 'data');
+export const PROJECT_ROOT = path.resolve(PC_ROOT, '..');
+
+// ── Data root (env required) ─────────────────────────────────────────────
+// `ORKAS_WORKSPACE_ROOT` is set unconditionally by `install-data-root.cjs`
+// before any TS module loads (see bootstrap.cjs). Tests pre-set it in
+// setup-env.ts. The on-disk directory name is `data/`; the constant is
+// still named WS_ROOT (a historical abbreviation of "workspace root" —
+// internal TS symbol, not user-facing). The env var name likewise keeps
+// its old form so deployments upgrade transparently.
+//
+// If the env var is missing here, something has gone wrong in the boot
+// sequence (e.g. a TS module was loaded before bootstrap.cjs's
+// install-data-root.cjs require). Fail loudly rather than silently
+// falling back to `<app-root>/data` and forking dev vs packaged data.
+if (!process.env.ORKAS_WORKSPACE_ROOT) {
+ throw new Error(
+ 'paths.ts: ORKAS_WORKSPACE_ROOT is not set. ' +
+ 'bootstrap.cjs must require install-data-root.cjs before any .ts module loads. ' +
+ 'Tests must use test/setup-env.ts.',
+ );
+}
+export const WS_ROOT = path.resolve(process.env.ORKAS_WORKSPACE_ROOT);
// ── Top-level (machine-global, shared across uids) ───────────────────────
// Machine-local uid registry: { current_user_id, users: [{user_id, created_at}, ...] }
diff --git a/src/main/util/migrate-source-data-root.cjs b/src/main/util/migrate-source-data-root.cjs
new file mode 100644
index 00000000..436da285
--- /dev/null
+++ b/src/main/util/migrate-source-data-root.cjs
@@ -0,0 +1,200 @@
+/**
+ * One-shot migration: move pre-unification source-run `<repoRoot>/data`
+ * and `<repoRoot>/userWorkSpace` into the unified install container
+ * (`<container>/data` + `<container>/userWorkSpace`).
+ *
+ * Before the data-root unification, source-run (`./run.sh`) wrote into
+ * `OpenSource/OrkasOpen/data/`, while packaged builds wrote into
+ * `~/.orkas/data/`. This migration runs once at boot to fold the
+ * source-run tree into the container, so dev and packaged share data
+ * going forward.
+ *
+ * Runs at boot, BEFORE `paths.ts` is loaded — paths.ts reads
+ * `ORKAS_WORKSPACE_ROOT` at module-load time, so the env var must be set
+ * and the data must be in place before any feature module loads.
+ *
+ * Strategy: overlay merge. Per-file conflicts resolve to src
+ * (`<repoRoot>/data` wins); target-only paths are preserved (e.g. a uid
+ * subtree from an existing packaged run survives). The single special
+ * case is the top-level `users.json` — a strict src-wins overwrite would
+ * orphan target uids (their `<uid>/` subtree survives but they vanish
+ * from the registry). So `users.json` is unioned: `users[]` = de-duped
+ * union of both sides, `current_user_id` = src's (the dev side is the
+ * active side); if src's pointer is dangling, fall back to dst's, then
+ * to any uid in the union.
+ *
+ * Idempotent via stamp file `<container>/data/.migrated-from-source`.
+ *
+ * Cannot import from `paths.ts` (paths.ts loads later in the boot sequence
+ * and depends on the env var this util's caller will set). Repo root is
+ * resolved from `__dirname` directly.
+ */
+
+'use strict';
+
+const fs = require('node:fs');
+const path = require('node:path');
+
+const STAMP_FILENAME = '.migrated-from-source';
+
+function migrateSourceDataRoot(targetContainer, repoRootOverride) {
+ // __dirname = OrkasOpen/src/main/util → up three for OrkasOpen/.
+ const repoRoot = repoRootOverride || path.resolve(__dirname, '..', '..', '..');
+ const srcData = path.join(repoRoot, 'data');
+ const srcWs = path.join(repoRoot, 'userWorkSpace');
+ const tgtData = path.join(targetContainer, 'data');
+ const tgtWs = path.join(targetContainer, 'userWorkSpace');
+ const stamp = path.join(tgtData, STAMP_FILENAME);
+
+ if (existsAndStampPresent(stamp)) return;
+
+ // ── data ──
+ if (existsAndNonEmpty(srcData)) {
+ fs.mkdirSync(tgtData, { recursive: true });
+ overlayCopyData(srcData, tgtData);
+ safeRm(srcData);
+ }
+
+ // ── userWorkSpace ──
+ if (existsAndNonEmpty(srcWs)) {
+ fs.mkdirSync(tgtWs, { recursive: true });
+ fs.cpSync(srcWs, tgtWs, { recursive: true, force: true });
+ safeRm(srcWs);
+ }
+
+ // Defensive cleanup: if a source dir exists but is empty (so the branch
+ // above didn't fire), still remove it so the repo root stays clean.
+ rmDirIfExists(srcData);
+ rmDirIfExists(srcWs);
+
+ // Stamp the target so subsequent boots short-circuit.
+ fs.mkdirSync(path.dirname(stamp), { recursive: true });
+ fs.writeFileSync(
+ stamp,
+ JSON.stringify({ at: new Date().toISOString() }, null, 2),
+ 'utf8',
+ );
+}
+
+function existsAndStampPresent(stamp) {
+ try {
+ return fs.statSync(stamp).isFile();
+ } catch {
+ return false;
+ }
+}
+
+function existsAndNonEmpty(dir) {
+ try {
+ const st = fs.statSync(dir);
+ if (!st.isDirectory()) return false;
+ return fs.readdirSync(dir).length > 0;
+ } catch {
+ return false;
+ }
+}
+
+function rmDirIfExists(dir) {
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {
+ /* best-effort */
+ }
+}
+
+function safeRm(dir) {
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch (err) {
+ process.stderr.write(
+ `[migrate-source-data-root] failed to remove ${dir}: ${err.message}\n`,
+ );
+ }
+}
+
+/**
+ * Overlay-copy `src` onto `dst` with `users.json` unioned at the top level.
+ *
+ * Sequence matters: `fs.cpSync(force:true)` would overwrite `<dst>/users.json`
+ * with src's plain users.json, undoing any union we computed beforehand. So:
+ * 1. cpSync EXCLUDING the top-level users.json (filter callback).
+ * 2. Compute the union and write it explicitly.
+ *
+ * Both target-only and src-only files survive after this — that's the
+ * default cpSync behaviour (no `--delete` flag).
+ */
+function overlayCopyData(src, dst) {
+ const srcUsers = path.join(src, 'users.json');
+
+ fs.cpSync(src, dst, {
+ recursive: true,
+ force: true,
+ filter: (s) => s !== srcUsers,
+ });
+
+ unionUsersJson(srcUsers, path.join(dst, 'users.json'));
+}
+
+function unionUsersJson(srcFile, dstFile) {
+ const srcDoc = readUsersJsonOrNull(srcFile);
+ const dstDoc = readUsersJsonOrNull(dstFile);
+
+ if (!srcDoc) return; // Nothing to merge (no src users.json).
+ if (!dstDoc) {
+ // Target had no users.json → just write src's verbatim.
+ fs.writeFileSync(dstFile, JSON.stringify(srcDoc, null, 2), 'utf8');
+ return;
+ }
+
+ // Union by user_id. Target first (preserves target-only uids),
+ // src wins on per-uid metadata if duplicates ever occur.
+ const byId = new Map();
+ for (const u of dstDoc.users) byId.set(u.user_id, u);
+ for (const u of srcDoc.users) byId.set(u.user_id, u);
+
+ // current_user_id: src wins by default (dev side is the active side).
+ // Fall back to dst's, then to any uid in the union, if src's points at
+ // a uid missing from users[] — e.g. a mid-creation crash on the dev
+ // side left a dangling current_user_id. Without this guard
+ // `initActiveUser` would silently create a third uid via the
+ // not-found fallback path, hiding both real uids from the user.
+ let chosen = srcDoc.current_user_id;
+ if (!byId.has(chosen)) {
+ if (dstDoc.current_user_id && byId.has(dstDoc.current_user_id)) {
+ chosen = dstDoc.current_user_id;
+ } else {
+ chosen = byId.size > 0 ? Array.from(byId.values())[0].user_id : '';
+ }
+ }
+
+ const merged = {
+ current_user_id: chosen,
+ users: Array.from(byId.values()).sort((a, b) =>
+ String(a.created_at).localeCompare(String(b.created_at)),
+ ),
+ };
+ fs.writeFileSync(dstFile, JSON.stringify(merged, null, 2), 'utf8');
+}
+
+function readUsersJsonOrNull(file) {
+ try {
+ const raw = fs.readFileSync(file, 'utf8');
+ const obj = JSON.parse(raw);
+ if (!obj || typeof obj !== 'object') return null;
+ const cur = typeof obj.current_user_id === 'string' ? obj.current_user_id : '';
+ const users = Array.isArray(obj.users)
+ ? obj.users.filter(
+ (r) =>
+ !!r &&
+ typeof r === 'object' &&
+ typeof r.user_id === 'string' &&
+ typeof r.created_at === 'string',
+ )
+ : [];
+ return { current_user_id: cur, users };
+ } catch {
+ return null;
+ }
+}
+
+module.exports = { migrateSourceDataRoot, unionUsersJson };
diff --git a/src/renderer/index.html b/src/renderer/index.html
index 60bd8c75..e11392dc 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -199,7 +199,6 @@
</button>
<button class="btn btn-sm" id="skill-edit-btn" data-i18n="skills.edit">Edit</button>
<button class="btn btn-sm" id="skill-enabled-btn" data-i18n="component.disable">Disable</button>
- <button class="btn btn-sm" id="skill-promote-btn" style="display:none" data-i18n="skills.promote_to_builtin">Make built-in (dev)</button>
<button class="btn btn-sm btn-danger" id="skill-delete-btn" data-i18n="skills.delete">Delete</button>
</div>
</div>
@@ -295,7 +294,6 @@
</button>
<button class="btn btn-sm" id="agent-edit-btn" data-i18n="agents.edit_btn_edit">Edit</button>
<button class="btn btn-sm" id="agent-enabled-btn" data-i18n="component.disable">Disable</button>
- <button class="btn btn-sm" id="agent-promote-btn" style="display:none" data-i18n="agents.promote_to_builtin">Make built-in (dev)</button>
<button class="btn btn-sm btn-danger" id="agent-delete-btn" data-i18n="agents.delete">Delete</button>
</div>
</div>
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index b20a78ca..f245219a 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -218,9 +218,6 @@
"skills.save_failed": "Save failed",
"skills.delete_confirm": "Delete the skill \"{name}\" and all its files?",
"skills.delete_failed_with": "Delete failed: {reason}",
- "skills.promote_to_builtin": "Make built-in (dev)",
- "skills.promote_confirm": "Promote the custom skill \"{name}\" to built-in? This writes to both src/builtin and data/builtin and removes the custom copy.",
- "skills.promote_failed_with": "Promote to built-in failed: {reason}",
"agents.title": "Agents",
"agents.create_btn": "+ Create",
"agents.empty": "No agents yet",
@@ -257,9 +254,6 @@
"agents.delete_confirm": "Delete this agent? Related conversations will also be removed.",
"agents.delete_failed": "Delete failed",
"agents.delete_failed_with": "Delete failed: {reason}",
- "agents.promote_to_builtin": "Make built-in (dev)",
- "agents.promote_confirm": "Promote the custom agent \"{name}\" to built-in? Only agent.json is copied to src/builtin and data/builtin (meta/ and self-evolved skills/ are dropped); the custom copy is removed.",
- "agents.promote_failed_with": "Promote to built-in failed: {reason}",
"agents.edit_chat_empty": "Tell me how you'd like to adjust this agent",
"agents.clear_confirm": "Clear the edit chat for this agent?",
"agents.agent_not_found": "Agent not found",
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index ba6a534c..50c6761f 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -218,9 +218,6 @@
"skills.save_failed": "保存失败",
"skills.delete_confirm": "确认删除技能 \"{name}\" 及其所有文件?",
"skills.delete_failed_with": "删除失败:{reason}",
- "skills.promote_to_builtin": "设为内置(开发)",
- "skills.promote_confirm": "确认把自定义技能 \"{name}\" 提升为内置?会同步写入 src/builtin 与 data/builtin,并删除原自定义目录。",
- "skills.promote_failed_with": "提升为内置失败:{reason}",
"agents.title": "智能体",
"agents.create_btn": "+ 创建",
"agents.empty": "暂无智能体",
@@ -257,9 +254,6 @@
"agents.delete_confirm": "确认删除这个智能体?相关对话会一并删除。",
"agents.delete_failed": "删除失败",
"agents.delete_failed_with": "删除失败:{reason}",
- "agents.promote_to_builtin": "设为内置(开发)",
- "agents.promote_confirm": "确认把自定义智能体 \"{name}\" 提升为内置?只复制 agent.json 到 src/builtin 与 data/builtin(meta/ 与自演化 skills/ 会丢弃),并删除原自定义目录。",
- "agents.promote_failed_with": "提升为内置失败:{reason}",
"agents.edit_chat_empty": "跟我说你想怎么调整这个智能体",
"agents.clear_confirm": "确认清空当前智能体的编辑对话记录?",
"agents.agent_not_found": "智能体不存在",
diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.js
index 9acd1b15..f6b210fa 100644
--- a/src/renderer/modules/agents.js
+++ b/src/renderer/modules/agents.js
@@ -338,17 +338,12 @@ function _renderAgentRowMenuItems(menu, agentId) {
const a = _agentsCache?.find((x) => x.agent_id === agentId);
const enabled = a ? a.enabled !== false : true;
const isCustom = a?.source === 'custom';
- // Dev mode lifts the source guard for built-in edit / delete; custom adds
- // a "promote to built-in" item too.
- const canEdit = isCustom || (a?.source === 'builtin' && isDevMode());
+ const canEdit = isCustom;
const toggleLabel = enabled ? t('component.disable') : t('component.enable');
const items = [];
if (canEdit) {
items.push(`<div class="agent-row-menu-item" data-action="edit">${escapeHtml(t('agents.edit'))}</div>`);
}
- if (isCustom && isDevMode()) {
- items.push(`<div class="agent-row-menu-item" data-action="promote">${escapeHtml(t('agents.promote_to_builtin'))}</div>`);
- }
items.push(`<div class="agent-row-menu-item" data-action="toggle-enabled">${escapeHtml(toggleLabel)}</div>`);
if (canEdit) {
items.push(`<div class="agent-row-menu-item is-danger" data-action="delete">${escapeHtml(t('agents.delete'))}</div>`);
@@ -367,8 +362,6 @@ function _renderAgentRowMenuItems(menu, agentId) {
} else if (action === 'delete') {
if (_selectedAgent?.id !== aid) await selectAgent(aid);
await deleteSelectedAgent();
- } else if (action === 'promote') {
- await promoteCustomAgent(aid);
} else if (action === 'toggle-enabled') {
await _flipAgentEnabledFromMenu(aid);
}
@@ -376,25 +369,6 @@ function _renderAgentRowMenuItems(menu, agentId) {
}
}
-/** Dev-only: promote a custom agent to built-in. Copies agent.json to
- * src+data trees, removes the custom dir (meta/ + skills/ dropped),
- * refreshes the grid. */
-async function promoteCustomAgent(agentId) {
- if (!isDevMode()) return;
- const cached = _agentsCache?.find((x) => x.agent_id === agentId);
- if (!(await uiConfirm(t('agents.promote_confirm', { name: cached?.name || agentId })))) return;
- try {
- const result = await window.orkas.invoke('agents.promoteToBuiltin', { agent_id: agentId });
- if (!result.ok) {
- await uiAlert(t('agents.promote_failed_with', { reason: result.error || '' }));
- return;
- }
- await loadAgents(true);
- } catch (e) {
- await uiAlert(t('agents.promote_failed_with', { reason: e.message || e }));
- }
-}
-
async function _flipAgentEnabledFromMenu(agentId) {
const cached = _agentsCache?.find((x) => x.agent_id === agentId);
const next = !(cached?.enabled !== false);
@@ -467,20 +441,16 @@ function _renderAgentDetail(agent, editing) {
}
if (!editing && !localizedDesc) descEl.innerHTML = unsetHtml;
- // Detail header actions, fixed order:
- // use (icon) / edit / enable-disable / promote-to-builtin
- // (custom + dev) / delete
+ // Detail header actions, fixed order: use (icon) / edit / enable-disable / delete.
// Edit mode hides everything except the "done" button (the relabeled
// "edit" button).
const useBtn = document.getElementById('agent-use-btn');
const enableBtn = document.getElementById('agent-enabled-btn');
- const promoteBtn = document.getElementById('agent-promote-btn');
const delBtn = document.getElementById('agent-delete-btn');
const isCustom = agent.source === 'custom';
- const canEdit = isCustom || (agent.source === 'builtin' && isDevMode());
+ const canEdit = isCustom;
if (useBtn) useBtn.style.display = editing ? 'none' : '';
if (enableBtn) enableBtn.style.display = editing ? 'none' : '';
- if (promoteBtn) promoteBtn.style.display = (isCustom && isDevMode() && !editing) ? '' : 'none';
if (delBtn) delBtn.style.display = (canEdit && !editing) ? '' : 'none';
if (editBtn) {
editBtn.style.display = canEdit ? '' : 'none';
@@ -686,8 +656,7 @@ function _toggleAgentFieldEditable(on) {
async function toggleAgentEditMode() {
if (!_selectedAgent) return;
- // Built-in editing is dev-only; lift the source guard accordingly.
- if (_selectedAgent.source === 'builtin' && !isDevMode()) return;
+ if (_selectedAgent.source === 'builtin') return;
if (_agentEditing) {
await _exitAgentEditMode();
} else {
diff --git a/src/renderer/modules/boot.js b/src/renderer/modules/boot.js
index a71bf61b..36a7f1b1 100644
--- a/src/renderer/modules/boot.js
+++ b/src/renderer/modules/boot.js
@@ -31,13 +31,6 @@ async function _stampSettingsVersion() {
} catch (_) { /* ignore — non-critical */ }
}
-// Dev-mode editing of built-in skills / agents is stripped from the
-// open-source build (the underlying `isDevEnv()` / built-in dual-write IPC
-// stack lives in the in-app debug panel that's only present in PC).
-// Renderer modules still branch on `isDevMode()` for those entry points,
-// so we stub it to false here.
-function isDevMode() { return false; }
-
// One-shot rename of legacy brand-prefixed localStorage keys
// (`orkas_*` / `orkas.*`) to the unprefixed form. After stamping,
// subsequent boots are no-ops. Placed at the very start of boot so no
diff --git a/src/renderer/modules/skills.js b/src/renderer/modules/skills.js
index 18f298ae..75acd9e9 100644
--- a/src/renderer/modules/skills.js
+++ b/src/renderer/modules/skills.js
@@ -285,12 +285,12 @@ function _openSkillRowMenu(anchorBtn, id, source) {
_closeSkillRowMenu();
menu.dataset.skillId = id;
menu.dataset.source = source;
- // Edit/delete are gated: custom always allowed; built-in only in dev mode.
+ // Edit/delete are gated: custom always allowed; built-ins are read-only.
// Enable/disable is always shown (lives in this menu now since cards no
// longer carry a toggle).
const cached = _skillsCache?.find((s) => s.id === id && s.source === source);
const enabled = cached ? cached.enabled !== false : true;
- const canEdit = source === 'custom' || (source === 'builtin' && isDevMode());
+ const canEdit = source === 'custom';
const items = [];
if (canEdit) {
items.push(`<div class="skill-row-menu-item" data-action="edit">${escapeHtml(t('skills.edit'))}</div>`);
@@ -298,11 +298,6 @@ function _openSkillRowMenu(anchorBtn, id, source) {
items.push(
`<div class="skill-row-menu-item" data-action="toggle-enabled">${escapeHtml(enabled ? t('component.disable') : t('component.enable'))}</div>`,
);
- if (source === 'custom' && isDevMode()) {
- items.push(
- `<div class="skill-row-menu-item" data-action="promote">${escapeHtml(t('skills.promote_to_builtin'))}</div>`,
- );
- }
if (canEdit) {
items.push(`<div class="skill-row-menu-item is-danger" data-action="delete">${escapeHtml(t('skills.delete'))}</div>`);
}
@@ -325,8 +320,6 @@ function _openSkillRowMenu(anchorBtn, id, source) {
// Mimic the existing delete flow (from detail page) but for any card.
_selectedSkill = { source, id, filepath: 'SKILL.md', name: '' };
await deleteSelectedSkill();
- } else if (action === 'promote') {
- await promoteCustomSkill(id);
} else if (action === 'toggle-enabled') {
const cur = _skillsCache?.find((s) => s.id === id && s.source === source);
const nextEnabled = !(cur ? cur.enabled !== false : true);
@@ -545,11 +538,10 @@ async function selectSkillFile(source, id, filepath, nodeEl) {
_renderSkillSections(seedDesc ? [['description', seedDesc]] : []);
// Actions bar: visible when a skill is selected.
- // Order: use (icon) / edit / enable-disable / promote-to-builtin
- // (custom + dev) / delete.
+ // Order: use (icon) / edit / enable-disable / delete.
// In edit mode only the "done" button (the relabeled "edit") is
// shown; everything else hides.
- const canEditThisSkill = source === 'custom' || (source === 'builtin' && isDevMode());
+ const canEditThisSkill = source === 'custom';
const editingThis = _skillEditMode && _skillEditSkillId === id && canEditThisSkill;
const actions = document.getElementById('skills-detail-actions');
if (actions) {
@@ -557,21 +549,16 @@ async function selectSkillFile(source, id, filepath, nodeEl) {
const useBtn = document.getElementById('skill-use-btn');
const editBtn = document.getElementById('skill-edit-btn');
const enableBtn = document.getElementById('skill-enabled-btn');
- const promoteBtn = document.getElementById('skill-promote-btn');
const delBtn = document.getElementById('skill-delete-btn');
if (useBtn) useBtn.style.display = editingThis ? 'none' : '';
if (editBtn) editBtn.style.display = canEditThisSkill ? '' : 'none';
if (enableBtn) enableBtn.style.display = editingThis ? 'none' : '';
- if (promoteBtn) promoteBtn.style.display = (source === 'custom' && isDevMode() && !editingThis) ? '' : 'none';
if (delBtn) delBtn.style.display = (canEditThisSkill && !editingThis) ? '' : 'none';
}
// Wire name editability (edit mode + custom only) and hide the
// description section while editing (req #3: edit description by editing
- // the `description_*:` frontmatter in SKILL.md, not via a separate UI
- // block). Built-in skills' name is **never** directly editable here even
- // under dev mode — direct rename would skip the dual-tree dir rename +
- // per-user chat dir migration that LLM-driven SKILL.md edits go through.
+ // the `description_*:` frontmatter in SKILL.md, not via a separate UI block).
const nameEditable = editingThis && source === 'custom';
_toggleSkillNameEditable(nameEl, nameEditable);
const summarySection = document.getElementById('skills-section-summary');
@@ -986,9 +973,7 @@ function _updateEditButtonLabel() {
// automatically — the user drives the conversation from a blank input.
async function toggleSkillEditMode(opts = {}) {
if (!_selectedSkill) return;
- // Built-in editing is dev-only; lift the source guard accordingly.
- if (_selectedSkill.source !== 'custom'
- && !(_selectedSkill.source === 'builtin' && isDevMode())) return;
+ if (_selectedSkill.source !== 'custom') return;
if (_skillEditMode && _skillEditSkillId === _selectedSkill.id) {
// Abort any in-flight reply so "done" means "stop + exit", not
// "exit but keep streaming". The chat controller is a singleton;
@@ -1380,15 +1365,12 @@ function editSelectedSkill() {
async function deleteSelectedSkill() {
if (!_selectedSkill) return;
- const src = _selectedSkill.source;
- if (src !== 'custom' && !(src === 'builtin' && isDevMode())) return;
+ if (_selectedSkill.source !== 'custom') return;
const sid = _selectedSkill.id;
- const cached = _skillsCache?.find(s => s.id === sid && s.source === src);
+ const cached = _skillsCache?.find(s => s.id === sid && s.source === 'custom');
if (!(await uiConfirm(t('skills.delete_confirm', { name: cached?.name || sid })))) return;
try {
- const result = src === 'builtin'
- ? await window.orkas.invoke('skills.builtin.delete', { id: sid })
- : await (await apiFetch(`/api/skills/${sid}`, { method: 'DELETE' })).json();
+ const result = await (await apiFetch(`/api/skills/${sid}`, { method: 'DELETE' })).json();
if (!result.ok) {
await uiAlert(t('skills.delete_failed_with', { reason: result.error || '' }));
return;
@@ -1405,26 +1387,6 @@ async function deleteSelectedSkill() {
}
}
-/** Dev-only: promote a custom skill to built-in. Copies to src+data trees,
- * removes the custom dir, refreshes the grid. */
-async function promoteCustomSkill(id) {
- if (!isDevMode()) return;
- const cached = _skillsCache?.find(s => s.id === id && s.source === 'custom');
- if (!(await uiConfirm(t('skills.promote_confirm', { name: cached?.name || id })))) return;
- try {
- const result = await window.orkas.invoke('skills.promoteToBuiltin', { id });
- if (!result.ok) {
- await uiAlert(t('skills.promote_failed_with', { reason: result.error || '' }));
- return;
- }
- _skillsCache = null;
- _skillTreeCache.clear();
- await loadSkills();
- } catch (e) {
- await uiAlert(t('skills.promote_failed_with', { reason: e.message || e }));
- }
-}
-
/**
* Per-skill enable / disable button in the detail header.
* Clone-replace the node each render to drop any prior click handler