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.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Harden Windows runtime flows
wyt0f01e3944bc5
diff --git a/src/core-agent/src/sandbox/executor.ts b/src/core-agent/src/sandbox/executor.tsindex 231db6a8..e345bc32 100644--- a/src/core-agent/src/sandbox/executor.ts+++ b/src/core-agent/src/sandbox/executor.ts@@ -6,6 +6,7 @@*/import { spawn } from "node:child_process";import path from "node:path";+import { TextDecoder } from "node:util";import { createLogger } from "../shared/logger.js";const log = createLogger("sandbox");@@ -26,7 +27,7 @@ export interface SandboxConfig {allowNetwork?: boolean;/** Environment variables to pass through. */env?: Record<string, string>;- /** Shell to use (default: /bin/sh). */+ /** Shell to use (default: /bin/sh on POSIX, PowerShell on Windows). */shell?: string;}@@ -46,6 +47,21 @@ export interface SandboxResult {durationMs: number;}+type ShellKind = "posix" | "cmd" | "powershell";++export interface ShellInvocation {+ command: string;+ args: string[];+ kind: ShellKind;+}++type OutputEncodingEnv = {+ LANG?: string;+ LC_ALL?: string;+ ORKAS_UI_LANG?: string;+ [key: string]: string | undefined;+};+/** Default blocked commands — destructive or dangerous operations. */const DEFAULT_BLOCKED_COMMANDS = ["rm -rf /",@@ -62,6 +78,184 @@ const DEFAULT_BLOCKED_COMMANDS = ["init 6",];+function shellBaseName(shell: string): string {+ return (shell.split(/[\\/]/).pop() || shell).toLowerCase();+}++function inferShellKind(shell: string, platform: NodeJS.Platform = process.platform): ShellKind {+ const base = shellBaseName(shell).replace(/\.exe$/i, "");+ if (platform !== "win32") return "posix";+ if (base === "cmd" || base === "comspec") return "cmd";+ if (base === "powershell" || base === "pwsh") return "powershell";+ return "posix";+}++export function defaultShellForPlatform(platform: NodeJS.Platform = process.platform): string {+ if (platform === "win32") {+ return process.env.ORKAS_WINDOWS_SHELL || "powershell.exe";+ }+ return "/bin/sh";+}++export function buildShellInvocation(+ shell: string,+ command: string,+ platform: NodeJS.Platform = process.platform,+): ShellInvocation {+ const kind = inferShellKind(shell, platform);+ if (platform === "win32" && kind === "powershell") {+ return {+ command: shell,+ args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", command],+ kind,+ };+ }+ if (platform === "win32" && kind === "cmd") {+ return {+ command: shell,+ args: ["/d", "/s", "/c", command],+ kind,+ };+ }+ return {+ command: shell,+ args: [platform === "win32" ? "-lc" : "-c", command],+ kind,+ };+}++function countMatches(input: string, re: RegExp): number {+ const matches = input.match(re);+ return matches ? matches.length : 0;+}++function decodeWithEncoding(bytes: Buffer, encoding: string): string | null {+ try {+ return new TextDecoder(encoding).decode(bytes);+ } catch {+ return null;+ }+}++function decodedTextScore(text: string): number {+ if (!text) return 0;+ let score = countMatches(text, /\uFFFD/g) * 100;+ score += countMatches(text, /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g) * 20;+ // Common mojibake produced when UTF-8 text is decoded with a legacy ANSI+ // code page. Keep this as a light penalty so valid English/ASCII remains+ // neutral while obviously broken mixed output loses ties.+ score += countMatches(text, /(?:Ã.|Â.|å.|æ.|ç.|ä.)/g) * 2;+ return score;+}++function windowsFallbackEncodings(env: OutputEncodingEnv = process.env): string[] {+ const lang = String(env.ORKAS_UI_LANG || env.LC_ALL || env.LANG || "").toLowerCase();+ const preferred = lang.startsWith("ja")+ ? ["shift_jis"]+ : lang.startsWith("ko")+ ? ["euc-kr"]+ : lang.includes("tw") || lang.includes("hk") || lang.includes("hant")+ ? ["big5", "gb18030"]+ : ["gb18030", "big5"];+ const out: string[] = [];+ for (const encoding of [...preferred, "shift_jis", "euc-kr", "windows-1252"]) {+ if (!out.includes(encoding)) out.push(encoding);+ }+ return out;+}++export function decodeProcessOutput(+ bytes: Buffer,+ platform: NodeJS.Platform = process.platform,+ env: OutputEncodingEnv = process.env,+): string {+ if (bytes.length === 0) return "";+ const utf8 = decodeWithEncoding(bytes, "utf-8") ?? bytes.toString("utf8");+ if (platform !== "win32") return utf8;++ const utf8Score = decodedTextScore(utf8);+ if (utf8Score === 0) return utf8;++ let best = utf8;+ let bestScore = utf8Score;+ for (const encoding of windowsFallbackEncodings(env)) {+ const decoded = decodeWithEncoding(bytes, encoding);+ if (decoded == null) continue;+ const score = decodedTextScore(decoded);+ if (score < bestScore) {+ best = decoded;+ bestScore = score;+ }+ }+ return best;+}++function buildWindowsCanonicalPathEntries(env: NodeJS.ProcessEnv): string[] {+ const root = getEnvValue(env, ["SystemRoot", "WINDIR"]) || "C:\\Windows";+ return [+ path.win32.join(root, "System32"),+ root,+ path.win32.join(root, "System32", "WindowsPowerShell", "v1.0"),+ ];+}++function getEnvValue(env: NodeJS.ProcessEnv, names: string[]): string | undefined {+ for (const name of names) {+ const value = env[name];+ if (typeof value === "string") return value;+ }+ const wanted = new Set(names.map((n) => n.toLowerCase()));+ for (const [key, value] of Object.entries(env)) {+ if (wanted.has(key.toLowerCase()) && typeof value === "string") return value;+ }+ return undefined;+}++function windowsHostEnv(env: NodeJS.ProcessEnv): Record<string, string> {+ const out: Record<string, string> = {};+ for (const key of [+ "SystemRoot",+ "WINDIR",+ "COMSPEC",+ "ComSpec",+ "PATHEXT",+ "TEMP",+ "TMP",+ "USERPROFILE",+ "APPDATA",+ "LOCALAPPDATA",+ "ProgramData",+ "ProgramFiles",+ "ProgramFiles(x86)",+ ]) {+ const value = getEnvValue(env, [key]);+ if (value) out[key] = value;+ }+ return out;+}++export function buildSandboxEnv(+ injected: Record<string, string> | undefined,+ platform: NodeJS.Platform = process.platform,+): Record<string, string> {+ const hostPath = getEnvValue(process.env, ["PATH", "Path"]);+ const env: Record<string, string> = {+ ...(platform === "win32" ? windowsHostEnv(process.env) : {}),+ HOME: process.env.HOME ?? process.env.USERPROFILE ?? (platform === "win32" ? "C:\\" : "/tmp"),+ PATH: augmentPath(hostPath, platform, process.env),+ TERM: "dumb",+ LANG: process.env.LANG ?? "en_US.UTF-8",+ ...(injected ?? {}),+ };++ if (env.ORKAS_PATH_PREPEND) {+ const delimiter = platform === "win32" ? ";" : ":";+ env.PATH = `${env.ORKAS_PATH_PREPEND}${delimiter}${env.PATH}`;+ }++ return env;+}+/*** SandboxExecutor wraps command execution with safety controls.*@@ -81,11 +275,7 @@ export class SandboxExecutor {this.config = {timeoutMs: 30_000,maxOutputBytes: 1024 * 1024, // 1MB- // Windows uses cmd.exe (resolved via the COMSPEC env var);- // POSIX uses /bin/sh.- shell: process.platform === "win32"- ? (process.env.COMSPEC || "cmd.exe")- : "/bin/sh",+ shell: defaultShellForPlatform(),...config,workingDir: path.resolve(config.workingDir),allowedDirs: config.allowedDirs?.map((d) => path.resolve(d)),@@ -126,36 +316,17 @@ export class SandboxExecutor {const cwd = this.config.workingDir;return new Promise<SandboxResult>((resolve) => {- let stdout = "";- let stderr = "";+ const stdoutChunks: Buffer[] = [];+ const stderrChunks: Buffer[] = [];+ let stdoutBytes = 0;+ let stderrBytes = 0;let timedOut = false;let outputLimitExceeded = false;let killed = false;+ let stdoutTruncated = false;+ let stderrTruncated = false;- // Build environment.- // PATH: Electron apps launched from Finder / the dock inherit a minimal- // PATH that often excludes brew-installed locations (especially- // `/opt/homebrew/bin` on Apple Silicon). Without augmentation, agents- // that try `brew install pandoc` or `pip --version` would hit "command- // not found" even when the CLI is installed. Prepend the canonical- // locations that don't already appear.- const env: Record<string, string> = {- HOME: process.env.HOME ?? "/tmp",- PATH: augmentPath(process.env.PATH),- TERM: "dumb",- LANG: process.env.LANG ?? "en_US.UTF-8",- ...(this.config.env ?? {}),- };-- // ORKAS_PATH_PREPEND: host-supplied dirs (e.g. the per-user external- // packages `.bin/` shim dir) that must rank ahead of the augmented- // PATH. A plain `PATH` override via config.env would *replace* the- // augmentation above and lose brew/system locations, so the host- // passes a prepend list instead and we compose here. The marker stays- // in the child env for debuggability.- if (env.ORKAS_PATH_PREPEND) {- env.PATH = `${env.ORKAS_PATH_PREPEND}${path.delimiter}${env.PATH}`;- }+ const env = buildSandboxEnv(this.config.env);// Restrict network if configuredif (this.config.allowNetwork === false) {@@ -164,10 +335,12 @@ export class SandboxExecutor {env.SANDBOX_NO_NETWORK = "1";}- const child = spawn(this.config.shell, ["-c", command], {+ const invocation = buildShellInvocation(this.config.shell, command);+ const child = spawn(invocation.command, invocation.args, {cwd,env,stdio: ["pipe", "pipe", "pipe"],+ windowsHide: true,});// Close stdin immediately — no interactive input@@ -176,25 +349,31 @@ export class SandboxExecutor {// Collect stdout with size limitchild.stdout.on("data", (data: Buffer) => {if (outputLimitExceeded) return;- stdout += data.toString("utf-8");- if (stdout.length > this.config.maxOutputBytes) {+ stdoutBytes += data.length;+ if (stdoutBytes > this.config.maxOutputBytes) {outputLimitExceeded = true;- stdout = stdout.slice(0, this.config.maxOutputBytes) +- "\n... [output truncated by sandbox]";+ stdoutTruncated = true;+ const allowed = Math.max(0, data.length - (stdoutBytes - this.config.maxOutputBytes));+ if (allowed > 0) stdoutChunks.push(data.subarray(0, allowed));killChild();+ return;}+ stdoutChunks.push(data);});// Collect stderr with size limitchild.stderr.on("data", (data: Buffer) => {if (outputLimitExceeded) return;- stderr += data.toString("utf-8");- if (stderr.length > this.config.maxOutputBytes) {+ stderrBytes += data.length;+ if (stderrBytes > this.config.maxOutputBytes) {outputLimitExceeded = true;- stderr = stderr.slice(0, this.config.maxOutputBytes) +- "\n... [stderr truncated by sandbox]";+ stderrTruncated = true;+ const allowed = Math.max(0, data.length - (stderrBytes - this.config.maxOutputBytes));+ if (allowed > 0) stderrChunks.push(data.subarray(0, allowed));killChild();+ return;}+ stderrChunks.push(data);});// Timeout handler@@ -219,6 +398,10 @@ export class SandboxExecutor {child.on("close", (code) => {clearTimeout(timeoutId);+ let stdout = decodeProcessOutput(Buffer.concat(stdoutChunks), process.platform, env);+ let stderr = decodeProcessOutput(Buffer.concat(stderrChunks), process.platform, env);+ if (stdoutTruncated) stdout += "\n... [output truncated by sandbox]";+ if (stderrTruncated) stderr += "\n... [stderr truncated by sandbox]";resolve({stdout,stderr,@@ -231,6 +414,7 @@ export class SandboxExecutor {child.on("error", (err) => {clearTimeout(timeoutId);+ const stdout = decodeProcessOutput(Buffer.concat(stdoutChunks), process.platform, env);resolve({stdout,stderr: err.message,@@ -256,16 +440,7 @@ export class SandboxExecutor {if (violation) {return { pid: null, error: `Command blocked by sandbox policy: ${violation}` };}- const env: Record<string, string> = {- HOME: process.env.HOME ?? "/tmp",- PATH: augmentPath(process.env.PATH),- TERM: "dumb",- LANG: process.env.LANG ?? "en_US.UTF-8",- ...(this.config.env ?? {}),- };- if (env.ORKAS_PATH_PREPEND) {- env.PATH = `${env.ORKAS_PATH_PREPEND}${path.delimiter}${env.PATH}`;- }+ const env = buildSandboxEnv(this.config.env);let logFd: number;try {// eslint-disable-next-line @typescript-eslint/no-require-imports@@ -276,7 +451,8 @@ export class SandboxExecutor {return { pid: null, error: `cannot open log file: ${(err as Error).message}` };}try {- const child = spawn(this.config.shell, ["-c", command], {+ const invocation = buildShellInvocation(this.config.shell, command);+ const child = spawn(invocation.command, invocation.args, {cwd: this.config.workingDir,env,detached: process.platform !== "win32",@@ -328,10 +504,18 @@ const CANONICAL_PATH_ENTRIES = ["/sbin",];-export function augmentPath(input: string | undefined): string {- const existing = (input ?? "").split(":").filter(Boolean);+export function augmentPath(+ input: string | undefined,+ platform: NodeJS.Platform = process.platform,+ env: NodeJS.ProcessEnv = process.env,+): string {+ const delimiter = platform === "win32" ? ";" : ":";+ const canonical = platform === "win32"+ ? buildWindowsCanonicalPathEntries(env)+ : CANONICAL_PATH_ENTRIES;+ const existing = (input ?? "").split(delimiter).filter(Boolean);const existingSet = new Set(existing);- const missing = CANONICAL_PATH_ENTRIES.filter((p) => !existingSet.has(p));+ const missing = canonical.filter((p) => !existingSet.has(p));const merged = [...missing, ...existing];- return merged.length ? merged.join(":") : CANONICAL_PATH_ENTRIES.join(":");+ return merged.length ? merged.join(delimiter) : canonical.join(delimiter);}diff --git a/src/core-agent/test/sandbox.test.ts b/src/core-agent/test/sandbox.test.tsindex fed2b684..5449b19c 100644--- a/src/core-agent/test/sandbox.test.ts+++ b/src/core-agent/test/sandbox.test.ts@@ -2,7 +2,13 @@ import { describe, it, expect } from "vitest";import os from "node:os";import path from "node:path";import fs from "node:fs/promises";-import { SandboxExecutor, augmentPath } from "../src/sandbox/executor.js";+import {+ SandboxExecutor,+ augmentPath,+ buildShellInvocation,+ decodeProcessOutput,+ defaultShellForPlatform,+} from "../src/sandbox/executor.js";describe("SandboxExecutor", () => {it("executes a simple command", async () => {@@ -126,6 +132,49 @@ describe("augmentPath", () => {expect(out.indexOf("/Users/me/tools/bin")).toBeLessThan(out.indexOf("/usr/bin"));});+ it("uses Windows PATH delimiters without splitting drive letters", () => {+ const input = "D:\\Tools\\bin;C:\\Windows\\System32";+ const out = augmentPath(input, "win32", { SystemRoot: "C:\\Windows" });+ const parts = out.split(";");+ expect(parts).toContain("D:\\Tools\\bin");+ expect(parts).toContain("C:\\Windows\\System32");+ expect(parts).not.toContain("D");+ expect(parts).not.toContain("\\Tools\\bin");+ });++ describe("Windows shell selection", () => {+ it("defaults Windows to PowerShell instead of a POSIX-incompatible cmd -c path", () => {+ expect(defaultShellForPlatform("win32")).toBe("powershell.exe");+ });++ it("uses cmd.exe /d /s /c when cmd is explicitly selected", () => {+ const inv = buildShellInvocation("cmd.exe", "echo hi", "win32");+ expect(inv.kind).toBe("cmd");+ expect(inv.args).toEqual(["/d", "/s", "/c", "echo hi"]);+ });++ it("passes PowerShell commands through without bash-syntax rewriting", () => {+ const command = '$ORKAS_NODE "$ORKAS_PC_DIR/bin/run-skill.cjs" calculator eval';+ const inv = buildShellInvocation("powershell.exe", command, "win32");+ expect(inv.kind).toBe("powershell");+ expect(inv.args).toEqual([+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-ExecutionPolicy",+ "Bypass",+ "-Command",+ command,+ ]);+ });++ it("keeps explicit Git Bash-style shells POSIX-shaped on Windows", () => {+ const inv = buildShellInvocation("bash.exe", "echo $ORKAS_UID", "win32");+ expect(inv.kind).toBe("posix");+ expect(inv.args).toEqual(["-lc", "echo $ORKAS_UID"]);+ });+ });+describe("executeBackground", () => {it("returns a pid immediately and writes output to the log file", async () => {const dir = await fs.mkdtemp(path.join(os.tmpdir(), "sandbox-bg-"));@@ -160,3 +209,15 @@ describe("augmentPath", () => {});});});++describe("decodeProcessOutput", () => {+ it("falls back to GB18030 for Chinese Windows console output", () => {+ const gbkVersion = Buffer.from([0xb0, 0xe6, 0xb1, 0xbe]);+ expect(decodeProcessOutput(gbkVersion, "win32", { ORKAS_UI_LANG: "zh" })).toBe("版本");+ });++ it("keeps valid UTF-8 output unchanged on Windows", () => {+ const utf8 = Buffer.from("版本", "utf8");+ expect(decodeProcessOutput(utf8, "win32", { ORKAS_UI_LANG: "zh" })).toBe("版本");+ });+});diff --git a/src/main/features/marketplace.ts b/src/main/features/marketplace.tsindex 1e8a6ef8..870599c3 100644--- a/src/main/features/marketplace.ts+++ b/src/main/features/marketplace.ts@@ -465,8 +465,13 @@ export async function getSkillDetail(async function _fetchAndCacheSkill(skillId: string, meta: { bundle_url: string; version: string; published_at: number; updated_at?: number },): Promise<void> {- const res = await fetchWithRetry(`marketplace:skill-bundle:${skillId}`, meta.bundle_url);- if (!res.ok) throw new Error(`download bundle failed (${res.status})`);+ let res: Response;+ try {+ res = await fetchWithRetry(`marketplace:skill-bundle:${skillId}`, meta.bundle_url);+ } catch (err) {+ throw new Error(`download bundle failed from ${_bundleHost(meta.bundle_url)}: ${(err as Error)?.message || String(err)}`);+ }+ if (!res.ok) throw new Error(`download bundle failed from ${_bundleHost(meta.bundle_url)} (${res.status})`);const ab = await res.arrayBuffer();const zipBuf = Buffer.from(ab);await writeSkillCache(skillId, async (dir) => {@@ -474,6 +479,14 @@ async function _fetchAndCacheSkill(}, { version: meta.version, published_at: meta.published_at, updated_at: meta.updated_at });}+function _bundleHost(bundleUrl: string): string {+ try {+ return new URL(bundleUrl).host || 'bundle host';+ } catch {+ return 'bundle host';+ }+}+// zip-bomb defense, mirrored at server (see `api/marketplace.py::_validate_skill_bundle`).// Server already enforces these caps on upload, but a corrupted COS blob or downgrade attack// could deliver a different payload to the client — re-check on the unpack side too.diff --git a/src/main/locales/en.json b/src/main/locales/en.jsonindex e967e5e0..92a7c936 100644--- a/src/main/locales/en.json+++ b/src/main/locales/en.json@@ -94,9 +94,18 @@"errors.network.overloaded": "Service overloaded","errors.network.refused": "Connection refused","errors.network.unreachable": "Network unreachable",+ "bash.error.timeout": "Command timed out after {ms}ms",+ "bash.error.exit_code": "Exit code: {code}",+ "bash.error.blocked": "Command blocked by sandbox policy: {reason}",+ "bash.error.background_start_failed": "Failed to start background command: {error}",+ "bash.error.start_failed": "Failed to start {command}: {error}","model.call_failed": "⚠️ Model call failed: {message}","model.retrying": "Retrying","model.retrying_n": "Retry attempt {attempt}",+ "model.tool_loop_limit_reached": "(Tool loop limit reached)",+ "model.run_aborted": "Run aborted",+ "model.max_retries_exceeded": "Max retries exceeded",+ "model.empty_response": "empty response","model.aborted": "(stopped)","cli_agent.missing": "⚠️ Agent “{name}” needs the local CLI “{cli}” which isn’t installed. Install it and retry, or switch the agent to another type.","cli_agent.slash_no_output": "Sent command `{cmd}`.",diff --git a/src/main/locales/ja.json b/src/main/locales/ja.jsonindex ceddc4ad..76f9cd3d 100644--- a/src/main/locales/ja.json+++ b/src/main/locales/ja.json@@ -94,9 +94,18 @@"errors.network.overloaded": "サービスが混雑しています","errors.network.refused": "接続が拒否されました","errors.network.unreachable": "ネットワークに到達できません",+ "bash.error.timeout": "コマンドがタイムアウトしました({ms}ms)",+ "bash.error.exit_code": "終了コード: {code}",+ "bash.error.blocked": "サンドボックスポリシーによりコマンドがブロックされました: {reason}",+ "bash.error.background_start_failed": "バックグラウンドコマンドの起動に失敗しました: {error}",+ "bash.error.start_failed": "{command} の起動に失敗しました: {error}","model.call_failed": "⚠️ モデル呼び出しに失敗しました: {message}","model.retrying": "再試行中","model.retrying_n": "再試行 {attempt} 回目",+ "model.tool_loop_limit_reached": "(ツール呼び出し回数が上限に達しました)",+ "model.run_aborted": "実行を中断しました",+ "model.max_retries_exceeded": "再試行回数が上限に達しました",+ "model.empty_response": "モデルから応答がありません","model.aborted": "(停止しました)","cli_agent.missing": "⚠️ エージェント「{name}」にはローカル CLI「{cli}」が必要ですが、インストールされていません。インストールして再試行するか、別のタイプへ切り替えてください。","cli_agent.slash_no_output": "コマンド `{cmd}` を送信しました。",diff --git a/src/main/locales/zh.json b/src/main/locales/zh.jsonindex 21401f30..cb5bb341 100644--- a/src/main/locales/zh.json+++ b/src/main/locales/zh.json@@ -94,9 +94,18 @@"errors.network.overloaded": "服务繁忙","errors.network.refused": "连接被拒绝","errors.network.unreachable": "网络不可达",+ "bash.error.timeout": "命令执行超时({ms}ms)",+ "bash.error.exit_code": "退出码:{code}",+ "bash.error.blocked": "命令已被沙箱策略拦截:{reason}",+ "bash.error.background_start_failed": "后台命令启动失败:{error}",+ "bash.error.start_failed": "{command} 启动失败:{error}","model.call_failed": "⚠️ 模型调用失败:{message}","model.retrying": "正在重试","model.retrying_n": "正在第 {attempt} 次重试",+ "model.tool_loop_limit_reached": "(工具调用次数已达上限)",+ "model.run_aborted": "运行已中断",+ "model.max_retries_exceeded": "重试次数已达上限",+ "model.empty_response": "模型未返回内容","model.aborted": "(已中断)","cli_agent.missing": "⚠️ 智能体「{name}」依赖的本地 CLI「{cli}」未安装。请安装该 CLI 后重试,或在编辑面板换成其他类型。","cli_agent.slash_no_output": "已发送命令 `{cmd}`。",diff --git a/src/main/model/core-agent/client.ts b/src/main/model/core-agent/client.tsindex a07662dc..90483039 100644--- a/src/main/model/core-agent/client.ts+++ b/src/main/model/core-agent/client.ts@@ -35,6 +35,7 @@ import { mapCoreAgentEvents } from './event-mapper';import { getSession as _getCachedSession } from './session-store';import { app } from 'electron';import * as paths from '../../paths';+import { getCurrentLang } from '../../i18n';interface NoopRecorder {record(event: unknown): void;@@ -97,6 +98,7 @@ function buildSkillSandboxEnvStatic(): Record<string, string> {*/export function buildSkillSandboxEnv(userId?: string): Record<string, string> {const env = { ...buildSkillSandboxEnvStatic() };+ env.ORKAS_UI_LANG = getCurrentLang();if (userId) {env.ORKAS_UID = userId;try {diff --git a/src/main/model/core-agent/event-mapper.ts b/src/main/model/core-agent/event-mapper.tsindex 82312ac3..4b0901a5 100644--- a/src/main/model/core-agent/event-mapper.ts+++ b/src/main/model/core-agent/event-mapper.ts@@ -144,6 +144,15 @@ export function friendlyRetryReason(reason: string): string {return t('errors.network');}+function localizeKnownRunnerText(text: string): string {+ const trimmed = String(text || '').trim();+ if (trimmed === '(Tool loop limit reached)') return t('model.tool_loop_limit_reached');+ if (trimmed === 'Run aborted') return t('model.run_aborted');+ if (trimmed === 'Max retries exceeded') return t('model.max_retries_exceeded');+ if (trimmed === 'empty response') return t('model.empty_response');+ return text;+}+function toolInputPath(input: unknown): string {if (!input) return '';if (typeof input === 'string') return input;@@ -433,7 +442,7 @@ export async function* mapCoreAgentEvents(};}if (result.meta.error) {- error = result.meta.error.message || 'unknown error';+ error = localizeKnownRunnerText(result.meta.error.message || 'unknown error');// meta.error is `{kind, message}` — cause/stack live on the// ProviderError that runner.ts already logged via `log.warn(...)`// on the retry path. Keep this line focused on what survives.@@ -447,7 +456,7 @@ export async function* mapCoreAgentEvents(} else {// Prefer the explicit `result.text` over our accumulated delta —// the runner may have trimmed trailing whitespace etc.- if (result.text) finalText = result.text;+ if (result.text) finalText = localizeKnownRunnerText(result.text);}break;}@@ -464,7 +473,7 @@ export async function* mapCoreAgentEvents(} else if (finalText) {yield { type: 'final', text: finalText };} else {- yield { type: 'error', text: 'empty response' };+ yield { type: 'error', text: localizeKnownRunnerText('empty response') };}return { finalText, error };diff --git a/src/main/model/core-agent/local-tools.ts b/src/main/model/core-agent/local-tools.tsindex 0cb12816..3b467827 100644--- a/src/main/model/core-agent/local-tools.ts+++ b/src/main/model/core-agent/local-tools.ts@@ -43,9 +43,11 @@import * as fs from 'node:fs';import * as path from 'node:path';+import { spawn } from 'node:child_process';import type { AgentTool, ToolContext, ToolResult } from '#core-agent';import { bashTool as coreBashTool, writeFileTool as coreWriteFileTool } from '../../../core-agent/src/tools/builtin';+import { buildSandboxEnv, decodeProcessOutput } from '../../../core-agent/src/sandbox/executor';import { getLocalExecGranted, getLocalExecMode } from '../../features/permissions';import { classifyBashCommand } from './bash-risk';import { requestBashDecision } from './bash-permissions';@@ -59,6 +61,7 @@ import * as chatArtifacts from '../../features/chat_artifacts';import { readDisabledSets } from '../../features/component_enabled';import { requestConfirmation as requestDeleteConfirmation, consumeGrantedConfirmation } from './delete-file-confirm';import { createLogger } from '../../logger';+import { t } from '../../i18n';const log = createLogger('local-tools');@@ -150,6 +153,29 @@ function errText(code: string, msg: string): string {return `${code}: ${msg}`;}+function bashMsg(key: string, vars?: Record<string, string | number>): string {+ return t(`bash.error.${key}`, vars);+}++function translateFixedBashError(result: ToolResult): ToolResult {+ const content = result.content || '';+ if (!content) return result;++ let m = /^Command timed out after (\d+)ms$/.exec(content);+ if (m) return { ...result, content: bashMsg('timeout', { ms: m[1] }) };++ m = /^Exit code: (.+)$/.exec(content);+ if (m) return { ...result, content: bashMsg('exit_code', { code: m[1] }) };++ m = /^Failed to start background command: (.+)$/.exec(content);+ if (m) return { ...result, content: bashMsg('background_start_failed', { error: m[1] }) };++ m = /^Command blocked by sandbox policy: (.+)$/.exec(content);+ if (m) return { ...result, content: bashMsg('blocked', { reason: m[1] }) };++ return result;+}+const BASH_PRODUCED_SCAN_LIMIT = 5000;const BASH_PRODUCED_SKIP_DIRS = new Set(['.cache',@@ -277,6 +303,225 @@ function withBashOutputEnv(ctx: ToolContext, outputDir: string): () => void {};}+type OrkasCliInvocation = {+ script: 'run-skill.cjs' | 'orkas-pkg.cjs';+ nodePath: string;+ scriptPath: string;+ args: string[];+ stdin?: string;+};++const ORKAS_DIRECT_CLI_SCRIPTS = new Set(['run-skill.cjs', 'orkas-pkg.cjs']);+const ORKAS_DIRECT_OUTPUT_LIMIT = 1024 * 1024;++function splitTrailingHeredoc(command: string): { command: string; stdin: string } | null {+ const open = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?\s*\r?\n/.exec(command);+ if (!open) return null;+ const marker = open[1];+ const bodyAndEnd = command.slice(open.index + open[0].length);+ const endRe = new RegExp(`\\r?\\n${marker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[ \\t]*(?:\\r?\\n)?$`);+ const end = endRe.exec(bodyAndEnd);+ if (!end) return null;+ return {+ command: command.slice(0, open.index).trimEnd(),+ stdin: bodyAndEnd.slice(0, end.index),+ };+}++function shellWords(input: string): string[] | null {+ const words: string[] = [];+ let cur = '';+ let quote: "'" | '"' | null = null;+ let hasCur = false;+ const push = () => {+ if (!hasCur) return;+ words.push(cur);+ cur = '';+ hasCur = false;+ };++ for (let i = 0; i < input.length; i++) {+ const ch = input[i];+ if (quote === "'") {+ if (ch === "'") quote = null;+ else { cur += ch; hasCur = true; }+ continue;+ }+ if (quote === '"') {+ if (ch === '"') { quote = null; continue; }+ if (ch === '\\' && i + 1 < input.length) {+ cur += input[++i];+ } else {+ cur += ch;+ }+ hasCur = true;+ continue;+ }+ if (ch === "'" || ch === '"') {+ quote = ch;+ hasCur = true;+ continue;+ }+ if (ch === '\\' && i + 1 < input.length) {+ cur += input[++i];+ hasCur = true;+ continue;+ }+ if (/\s/.test(ch)) {+ push();+ continue;+ }+ cur += ch;+ hasCur = true;+ }+ if (quote) return null;+ push();+ return words;+}++function expandOrkasEnvToken(token: string, env: Record<string, string>): string {+ return token+ .replace(/\$\{ORKAS_NODE\}/g, env.ORKAS_NODE || '')+ .replace(/\$ORKAS_NODE/g, env.ORKAS_NODE || '')+ .replace(/\$\{ORKAS_PC_DIR\}/g, env.ORKAS_PC_DIR || '')+ .replace(/\$ORKAS_PC_DIR/g, env.ORKAS_PC_DIR || '');+}++function sameResolvedPath(a: string, b: string): boolean {+ const ra = path.resolve(a);+ const rb = path.resolve(b);+ return process.platform === 'win32'+ ? ra.toLowerCase() === rb.toLowerCase()+ : ra === rb;+}++function parseOrkasCliInvocation(+ input: Record<string, unknown>,+ ctx: ToolContext,+): OrkasCliInvocation | null {+ if (input.run_in_background === true) return null;+ const rawCommand = String(input.command ?? '');+ const heredoc = splitTrailingHeredoc(rawCommand);+ const command = heredoc?.command ?? rawCommand;+ const words = shellWords(command);+ if (!words || words.length < 2) return null;++ const sandboxEnv = (ctx.state.sandboxEnv ?? {}) as Record<string, string>;+ const nodePath = sandboxEnv.ORKAS_NODE;+ const pcDir = sandboxEnv.ORKAS_PC_DIR;+ if (!nodePath || !pcDir) return null;++ const resolvedNode = expandOrkasEnvToken(words[0], sandboxEnv);+ if (!sameResolvedPath(resolvedNode, nodePath)) return null;++ const scriptPath = expandOrkasEnvToken(words[1], sandboxEnv);+ const script = path.basename(scriptPath) as OrkasCliInvocation['script'];+ if (!ORKAS_DIRECT_CLI_SCRIPTS.has(script)) return null;+ if (!sameResolvedPath(scriptPath, path.join(pcDir, 'bin', script))) return null;++ return {+ script,+ nodePath,+ scriptPath: path.resolve(scriptPath),+ args: words.slice(2),+ ...(heredoc ? { stdin: heredoc.stdin } : {}),+ };+}++async function executeDirectOrkasCli(+ invocation: OrkasCliInvocation,+ input: Record<string, unknown>,+ ctx: ToolContext,+ workingDir: string,+): Promise<ToolResult> {+ const timeoutMs = (input.timeoutMs as number | undefined) ?? 300_000;+ const sandboxEnv = (ctx.state.sandboxEnv ?? {}) as Record<string, string>;+ const env = buildSandboxEnv(sandboxEnv);++ return await new Promise<ToolResult>((resolve) => {+ const stdoutChunks: Buffer[] = [];+ const stderrChunks: Buffer[] = [];+ let totalBytes = 0;+ let timedOut = false;+ let outputLimitExceeded = false;+ let truncatedKind: 'stdout' | 'stderr' | null = null;+ let settled = false;++ const child = spawn(invocation.nodePath, [invocation.scriptPath, ...invocation.args], {+ cwd: workingDir,+ env,+ stdio: ['pipe', 'pipe', 'pipe'],+ windowsHide: true,+ });++ const finish = (result: ToolResult) => {+ if (settled) return;+ settled = true;+ clearTimeout(timeout);+ resolve(result);+ };++ const killChild = () => {+ try { child.kill('SIGTERM'); } catch { /* already gone */ }+ setTimeout(() => {+ try { child.kill('SIGKILL'); } catch { /* already gone */ }+ }, 5000);+ };++ const append = (kind: 'stdout' | 'stderr', data: Buffer) => {+ if (outputLimitExceeded) return;+ totalBytes += data.length;+ if (totalBytes > ORKAS_DIRECT_OUTPUT_LIMIT) {+ outputLimitExceeded = true;+ truncatedKind = kind;+ const allowed = Math.max(0, data.length - (totalBytes - ORKAS_DIRECT_OUTPUT_LIMIT));+ if (allowed > 0) {+ (kind === 'stdout' ? stdoutChunks : stderrChunks).push(data.subarray(0, allowed));+ }+ killChild();+ return;+ }+ (kind === 'stdout' ? stdoutChunks : stderrChunks).push(data);+ };++ child.stdout.on('data', (data: Buffer) => append('stdout', data));+ child.stderr.on('data', (data: Buffer) => append('stderr', data));++ const timeout = setTimeout(() => {+ timedOut = true;+ killChild();+ }, timeoutMs);+ if (typeof timeout.unref === 'function') timeout.unref();++ child.on('error', (err) => {+ finish({ content: bashMsg('start_failed', { command: invocation.script, error: err.message }), isError: true });+ });+ child.on('close', (code) => {+ let stdout = decodeProcessOutput(Buffer.concat(stdoutChunks), process.platform, env);+ let stderr = decodeProcessOutput(Buffer.concat(stderrChunks), process.platform, env);+ if (outputLimitExceeded) {+ if (truncatedKind === 'stdout') stdout += '\n... [output truncated by sandbox]';+ else stderr += '\n... [output truncated by sandbox]';+ }+ if (timedOut) {+ finish({ content: bashMsg('timeout', { ms: timeoutMs }), isError: true });+ return;+ }+ if (outputLimitExceeded) {+ finish({ content: stderr || stdout, isError: code !== 0 });+ return;+ }+ if (code !== 0) {+ finish({ content: stderr || stdout || bashMsg('exit_code', { code: code ?? 'null' }), isError: true });+ return;+ }+ finish({ content: stdout });+ });++ child.stdin.end(invocation.stdin ?? '');+ });+}+async function executeCoreBashWithOutputTracking(opts: LocalToolsOpts,input: Record<string, unknown>,@@ -287,9 +532,12 @@ async function executeCoreBashWithOutputTracking(const before = opts.onFileWritten ? collectBashFileSnapshot(outputDir) : new Map<string, BashFileSnapshotEntry>();const restoreEnv = withBashOutputEnv(ctx, outputDir);try {- const result = await coreBashTool.execute(input, ctx);+ const direct = parseOrkasCliInvocation(input, ctx);+ const result = direct+ ? await executeDirectOrkasCli(direct, input, ctx, workingDir)+ : await coreBashTool.execute(input, ctx);if (!result.isError) emitBashProducedFiles(opts, before, outputDir);- return result;+ return translateFixedBashError(result);} finally {restoreEnv();}@@ -483,7 +731,7 @@ function createBashTool(opts: LocalToolsOpts): AgentTool {// Best-effort cleanup: any rmdir failure (concurrent// bash on same cwd, ENOTEMPTY, EACCES) is silently// swallowed.- if (!ctx.workingDir) return coreBashTool.execute(input, ctx);+ if (!ctx.workingDir) return translateFixedBashError(await coreBashTool.execute(input, ctx));const workingDir = path.resolve(ctx.workingDir);if (fs.existsSync(workingDir)) {return executeCoreBashWithOutputTracking(opts, input, ctx, workingDir);diff --git a/src/main/storage.ts b/src/main/storage.tsindex e6671c2f..4fa4eab5 100644--- a/src/main/storage.ts+++ b/src/main/storage.ts@@ -66,22 +66,100 @@ export function readJsonSync<T = Record<string, any>>(filePath: string): T {}}+const RENAME_RETRY_DELAYS_MS = [10, 25, 50, 100, 200, 400, 800];+const RENAME_RETRY_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']);++function atomicTmpPath(filePath: string): string {+ return `${filePath}.${process.pid}.${Date.now()}.${crypto.randomBytes(4).toString('hex')}.tmp`;+}++function isRetryableRenameError(err: unknown): boolean {+ const code = (err as NodeJS.ErrnoException | undefined)?.code;+ return typeof code === 'string' && RENAME_RETRY_CODES.has(code);+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++function sleepSync(ms: number): void {+ const buffer = new SharedArrayBuffer(4);+ const view = new Int32Array(buffer);+ Atomics.wait(view, 0, 0, ms);+}++async function renameWithRetryUsing(+ tmp: string,+ filePath: string,+ renameFn: (oldPath: string, newPath: string) => Promise<void>,+): Promise<void> {+ for (let attempt = 0; ; attempt++) {+ try {+ await renameFn(tmp, filePath);+ return;+ } catch (err) {+ if (!isRetryableRenameError(err) || attempt >= RENAME_RETRY_DELAYS_MS.length) throw err;+ await sleep(RENAME_RETRY_DELAYS_MS[attempt]);+ }+ }+}++function renameWithRetry(tmp: string, filePath: string): Promise<void> {+ return renameWithRetryUsing(tmp, filePath, fsp.rename);+}++function renameWithRetrySyncUsing(+ tmp: string,+ filePath: string,+ renameFn: (oldPath: string, newPath: string) => void,+): void {+ for (let attempt = 0; ; attempt++) {+ try {+ renameFn(tmp, filePath);+ return;+ } catch (err) {+ if (!isRetryableRenameError(err) || attempt >= RENAME_RETRY_DELAYS_MS.length) throw err;+ sleepSync(RENAME_RETRY_DELAYS_MS[attempt]);+ }+ }+}++function renameWithRetrySync(tmp: string, filePath: string): void {+ return renameWithRetrySyncUsing(tmp, filePath, fs.renameSync);+}++export const __storageTestHooks = {+ renameWithRetryUsing,+ renameWithRetrySyncUsing,+};+/*** Atomically write JSON with UTF-8 and 2-space indent.- * Writes to <path>.tmp then renames over the target to prevent torn reads.+ * Writes to a same-directory temp file then renames over the target to+ * prevent torn reads.*/export async function writeJson(filePath: string, data: unknown): Promise<void> {await fsp.mkdir(path.dirname(filePath), { recursive: true });- const tmp = `${filePath}.tmp`;+ const tmp = atomicTmpPath(filePath);await fsp.writeFile(tmp, JSON.stringify(data, null, 2), 'utf8');- await fsp.rename(tmp, filePath);+ try {+ await renameWithRetry(tmp, filePath);+ } catch (err) {+ await fsp.rm(tmp, { force: true }).catch(() => {});+ throw err;+ }}export function writeJsonSync(filePath: string, data: unknown): void {fs.mkdirSync(path.dirname(filePath), { recursive: true });- const tmp = `${filePath}.tmp`;+ const tmp = atomicTmpPath(filePath);fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8');- fs.renameSync(tmp, filePath);+ try {+ renameWithRetrySync(tmp, filePath);+ } catch (err) {+ try { fs.rmSync(tmp, { force: true }); } catch {}+ throw err;+ }}/**@@ -92,9 +170,14 @@ export function writeJsonSync(filePath: string, data: unknown): void {*/export function writeTextAtomicSync(filePath: string, text: string, encoding: BufferEncoding = 'utf8'): void {fs.mkdirSync(path.dirname(filePath), { recursive: true });- const tmp = `${filePath}.tmp`;+ const tmp = atomicTmpPath(filePath);fs.writeFileSync(tmp, text, { encoding });- fs.renameSync(tmp, filePath);+ try {+ renameWithRetrySync(tmp, filePath);+ } catch (err) {+ try { fs.rmSync(tmp, { force: true }); } catch {}+ throw err;+ }}/** Append one JSON record as a single line. */@@ -209,9 +292,14 @@ export async function rewriteJsonlLine<T extends object>(const out = body.join('\n') + '\n';// Write to tmp + rename — rewrite is a "full file" op; we can't use// append here. Line count stays the same.- const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;+ const tmp = atomicTmpPath(filePath);await fsp.writeFile(tmp, out, 'utf8');- await fsp.rename(tmp, filePath);+ try {+ await renameWithRetry(tmp, filePath);+ } catch (err) {+ await fsp.rm(tmp, { force: true }).catch(() => {});+ throw err;+ }return { ok: true, record: next };});}diff --git a/src/main/system_skills/skill-creator/SKILL.md b/src/main/system_skills/skill-creator/SKILL.mdindex b245727b..27133623 100644--- a/src/main/system_skills/skill-creator/SKILL.md+++ b/src/main/system_skills/skill-creator/SKILL.md@@ -246,7 +246,7 @@ Add implementation-specific subsections only when they are needed:**Default preference: guide-type (no script)**.- If the task can be done with main-conversation generic tools (file IO / `kb_search` / `web_fetch` / `bash` / etc.), the body lists 3–7 actionable steps and `scripts/` is empty.-- Add `scripts/<basename>.<ext>` ONLY when the task needs dedicated code (complex parsing, local state, third-party API state, signature verification). **No placeholder skeletons** — `{"ok": true}` + empty data is not an implementation; if you can't write the real thing this turn, fall back to guide-type and tell the user "the interface is in place; once we agree on the implementation direction, I'll add the script next message".+- Add `scripts/<basename>.<ext>` ONLY when the task needs dedicated code (complex parsing, local state, third-party API state, signature verification). Prefer `.py`, `.js`, `.mjs`, or `.ts` for new scripts; do not author new `.sh` scripts unless preserving an existing source skill that already uses shell. **No placeholder skeletons** — `{"ok": true}` + empty data is not an implementation; if you can't write the real thing this turn, fall back to guide-type and tell the user "the interface is in place; once we agree on the implementation direction, I'll add the script next message".## Script invocation (when there is a script)@@ -258,10 +258,12 @@ $ORKAS_NODE $ORKAS_PC_DIR/bin/run-skill.cjs <skill-id> <script-basename> [-- arg**Do NOT prefix with `bash`** — the bash tool runs `command` itself as a shell command; a `bash` prefix tells the shell to execute the Electron binary as a script and produces "cannot execute binary file". The command starts with `$ORKAS_NODE`. The `<script-basename>` does NOT include the extension — only one file per basename per directory.+Use this exact Orkas runner shape for cross-platform skill execution. Orkas can dispatch this standard command directly on Windows without requiring Bash; generic Unix shell pipelines remain OS/shell-specific and should not be the primary implementation of a new skill.+The runner picks the runtime by file extension:- `.py` → `python3` (Windows automatically tries `py -3` → `python`). **Default language; broadest coverage**.- `.ts` / `.mjs` / `.js` → require + default export. **`.ts` scripts MUST `export default async function(args)`**, return JSON-serializable result, runner auto-`JSON.stringify`s it to stdout.-- `.sh` → `bash`.+- `.sh` → `bash` / a POSIX-compatible shell. Use only for preserved upstream shell scripts; do not choose it for newly authored Orkas skills.- `.rb` → `ruby`.In subprocess mode, stdio is passed through, exit code propagated, the script handles argv / stdout / errors itself. The runner injects `ORKAS_SKILL_ID` / `ORKAS_SKILL_DIR` (pointing at the skill root) so the script can address its bundled resource files.diff --git a/src/renderer/modules/marketplace.js b/src/renderer/modules/marketplace.jsindex a60c9109..4043f19a 100644--- a/src/renderer/modules/marketplace.js+++ b/src/renderer/modules/marketplace.js@@ -283,6 +283,8 @@ function openMarketplace(initialTab = 'agent', opts = {}) {detailSkillFiles: [],detailSkillSelected: 'SKILL.md',detailSkillFileText: '',+ detailSkillLoadError: '',+ detailSkillSourceOpen: false,};if (!_mpBound) {@@ -1288,6 +1290,7 @@ async function _mpOpenDetail(kind, item, opts = {}) {_mpState.detailSkillFiles = [];_mpState.detailSkillSelected = prevSelected;_mpState.detailSkillFileText = '';+ _mpState.detailSkillLoadError = '';_mpState.detailSkillSourceOpen = prevSourceOpen;_mpShowDetailView();_mpRenderDetail();@@ -1301,20 +1304,24 @@ async function _mpOpenDetail(kind, item, opts = {}) {if (!detail || detail.ok === false) throw new Error((detail && detail.error) || 'detail failed');_mpState.detailAgentJson = detail.agent_json;} else {- const detail = await window.orkas.invoke('marketplace.detailSkill', {- id: item.id, version: item.version,- published_at: item.published_at, updated_at: item.updated_at,- });- if (!detail || detail.ok === false) throw new Error((detail && detail.error) || 'detail failed');- const files = await window.orkas.invoke('marketplace.cacheSkillFiles', { id: item.id });- _mpState.detailSkillFiles = (files && files.list) || [];- const selected = _mpState.detailSkillFiles.find((f) => f.path === _mpState.detailSkillSelected)- ? _mpState.detailSkillSelected- : 'SKILL.md';- _mpState.detailSkillSelected = selected;- if (_mpState.detailSkillFiles.find((f) => f.path === selected)) {- const r = await window.orkas.invoke('marketplace.cacheSkillRead', { id: item.id, file: selected });- _mpState.detailSkillFileText = (r && r.content) || '';+ try {+ const detail = await window.orkas.invoke('marketplace.detailSkill', {+ id: item.id, version: item.version,+ published_at: item.published_at, updated_at: item.updated_at,+ });+ if (!detail || detail.ok === false) throw new Error((detail && detail.error) || 'detail failed');+ const files = await window.orkas.invoke('marketplace.cacheSkillFiles', { id: item.id });+ _mpState.detailSkillFiles = (files && files.list) || [];+ const selected = _mpState.detailSkillFiles.find((f) => f.path === _mpState.detailSkillSelected)+ ? _mpState.detailSkillSelected+ : 'SKILL.md';+ _mpState.detailSkillSelected = selected;+ if (_mpState.detailSkillFiles.find((f) => f.path === selected)) {+ const r = await window.orkas.invoke('marketplace.cacheSkillRead', { id: item.id, file: selected });+ _mpState.detailSkillFileText = (r && r.content) || '';+ }+ } catch (err) {+ _mpState.detailSkillLoadError = (err && err.message) || String(err);}}} catch (err) {@@ -1492,19 +1499,30 @@ function _mpSkillDetailHtml() {const files = _mpState.detailSkillFiles || [];const selected = _mpState.detailSkillSelected;const text = _mpState.detailSkillFileText || '';+ const loadError = _mpState.detailSkillLoadError || '';- const treeHtml = files.map((f) => {- const active = f.path === selected ? ' active' : '';- return `<div class="skill-tree-node skill-tree-file${active}" data-mp-skill-file="${escapeHtml(f.path)}">- <span class="skill-tree-label">${escapeHtml(f.path)}</span>- <span class="muted" style="margin-left:auto;font-size:11px">${_fmtBytes(f.bytes)}</span>- </div>`;- }).join('');+ let treeHtml = '';+ if (loadError && !files.length) {+ treeHtml = `<div class="empty">${escapeHtml(t('marketplace.load_failed'))}: ${escapeHtml(loadError)}</div>`;+ } else {+ treeHtml = files.map((f) => {+ const active = f.path === selected ? ' active' : '';+ return `<div class="skill-tree-node skill-tree-file${active}" data-mp-skill-file="${escapeHtml(f.path)}">+ <span class="skill-tree-label">${escapeHtml(f.path)}</span>+ <span class="muted" style="margin-left:auto;font-size:11px">${_fmtBytes(f.bytes)}</span>+ </div>`;+ }).join('');+ }const isMd = selected.toLowerCase().endsWith('.md');- const bodyHtml = isMd- ? renderMarkdownFull(text)- : `<pre class="code-view"><code>${escapeHtml(text)}</code></pre>`;+ let bodyHtml = '';+ if (loadError) {+ bodyHtml = `<div class="empty">${escapeHtml(t('marketplace.load_failed'))}: ${escapeHtml(loadError)}</div>`;+ } else if (isMd) {+ bodyHtml = renderMarkdownFull(text);+ } else {+ bodyHtml = `<pre class="code-view"><code>${escapeHtml(text)}</code></pre>`;+ }const placeholderHtml = `<span class="agents-detail-placeholder">${escapeHtml(t('agents.placeholder_unset'))}</span>`;return `diff --git a/test/main/model/event-mapper.test.ts b/test/main/model/event-mapper.test.tsindex efe7e4fb..f22bd6d3 100644--- a/test/main/model/event-mapper.test.ts+++ b/test/main/model/event-mapper.test.ts@@ -7,6 +7,7 @@ import {agentReadMetadataForToolStart,} from '../../../src/main/model/core-agent/event-mapper';import { userMarketplaceAgentsDir, userMarketplaceSkillsDir } from '../../../src/main/paths';+import { setCurrentLang } from '../../../src/main/i18n';type AgentRunEvent =| { type: 'text_delta'; text: string }@@ -245,6 +246,18 @@ describe('event-mapper › tool_start / tool_end emit a single structured event'// duplicating the (potentially large) marker text on the wire.expect(endEvent.event.data.output).toBeUndefined();});++ it('localizes known runner fallback text', async () => {+ setCurrentLang('zh');+ try {+ const out = await collect([+ { type: 'done', result: { text: '(Tool loop limit reached)', meta: { error: null } } },+ ]);+ expect(out).toEqual([{ type: 'final', text: '(工具调用次数已达上限)' }]);+ } finally {+ setCurrentLang('en');+ }+ });});describe('event-mapper › extractPersistedOutputPath', () => {diff --git a/test/main/model/local-tools.test.ts b/test/main/model/local-tools.test.tsindex 63b5dcad..f977a44a 100644--- a/test/main/model/local-tools.test.ts+++ b/test/main/model/local-tools.test.ts@@ -112,6 +112,21 @@ describe('local-tools › bash permission gate', () => {expect(res.content).toContain('orkas-test-sentinel-42');});+ it('localizes fixed bash errors with the current UI language', async () => {+ const { lt, perm } = await loadModules();+ const i18n = await import('../../../src/main/i18n');+ perm.grantLocalExec();+ i18n.setCurrentLang('zh');+ try {+ const bash = lt.createLocalTools({}).find((t) => t.name === 'bash')!;+ const res = await bash.execute({ command: 'exit 7', timeoutMs: 5000 }, makeCtx());+ expect(res.isError).toBe(true);+ expect(res.content).toBe('退出码:7');+ } finally {+ i18n.setCurrentLang('en');+ }+ });+it('re-checks permission per-call (revoke mid-run blocks the next call)', async () => {const { lt, perm } = await loadModules();perm.grantLocalExec();@@ -125,6 +140,70 @@ describe('local-tools › bash permission gate', () => {});});+describe('local-tools › Orkas CLI direct execution', () => {+ function writeFakePcScript(name: 'run-skill.cjs' | 'orkas-pkg.cjs', source: string): string {+ const binDir = path.join(tmpDir, 'fake-pc', 'bin');+ fs.mkdirSync(binDir, { recursive: true });+ const script = path.join(binDir, name);+ fs.writeFileSync(script, source, 'utf8');+ return path.join(tmpDir, 'fake-pc');+ }++ function makeOrkasCtx(pcDir: string): any {+ return {+ workingDir: tmpDir,+ state: {+ sandboxEnv: {+ ORKAS_NODE: process.execPath,+ ORKAS_PC_DIR: pcDir,+ ELECTRON_RUN_AS_NODE: '1',+ },+ },+ };+ }++ it('runs the standard run-skill.cjs command without requiring shell expansion', async () => {+ const { lt, perm } = await loadModules();+ perm.grantLocalExec();+ const pcDir = writeFakePcScript(+ 'run-skill.cjs',+ "process.stdout.write(JSON.stringify({ argv: process.argv.slice(2), out: process.env.ORKAS_OUTPUT_DIR }));",+ );+ const bash = lt.createLocalTools({}).find((t) => t.name === 'bash')!;++ const res = await bash.execute({+ command: '$ORKAS_NODE "$ORKAS_PC_DIR/bin/run-skill.cjs" calculator eval -- 1+1',+ timeoutMs: 5000,+ }, makeOrkasCtx(pcDir));++ expect(res.isError).toBeFalsy();+ const parsed = JSON.parse(String(res.content));+ expect(parsed.argv).toEqual(['calculator', 'eval', '--', '1+1']);+ expect(parsed.out).toBe(tmpDir);+ });++ it('pipes heredoc stdin into the standard orkas-pkg.cjs command', async () => {+ const { lt, perm } = await loadModules();+ perm.grantLocalExec();+ const pcDir = writeFakePcScript(+ 'orkas-pkg.cjs',+ "let body=''; process.stdin.on('data', d => body += d); process.stdin.on('end', () => process.stdout.write(JSON.stringify({ argv: process.argv.slice(2), body })));",+ );+ const bash = lt.createLocalTools({}).find((t) => t.name === 'bash')!;+ const body = "---\nname: Demo\n---\n\n# Demo";++ const res = await bash.execute({+ command: `$ORKAS_NODE "$ORKAS_PC_DIR/bin/orkas-pkg.cjs" skill-write demo <<'SKILL'\n${body}\nSKILL`,+ timeoutMs: 5000,+ }, makeOrkasCtx(pcDir));++ expect(res.isError).toBeFalsy();+ const parsed = JSON.parse(String(res.content));+ expect(parsed.argv).toEqual(['skill-write', 'demo']);+ expect(parsed.body).toBe(body);+ });+});+// ── End-to-end: risk_prompt mode drives the real bash tool ────────────────describe('local-tools › bash risk_prompt mode (e2e)', () => {diff --git a/test/main/storage.test.ts b/test/main/storage.test.tsindex 88694db1..e2a76df5 100644--- a/test/main/storage.test.ts+++ b/test/main/storage.test.ts@@ -6,7 +6,7 @@ import {nowIso, genUserId, genId12, safeId,readJson, readJsonSync, writeJson, writeJsonSync,writeTextAtomicSync, appendJsonl, appendJsonlAtomic,- invalidateLineCount, readJsonl,+ invalidateLineCount, readJsonl, __storageTestHooks,} from '../../src/main/storage';let tmpDir: string;@@ -19,6 +19,12 @@ afterEach(() => {fs.rmSync(tmpDir, { recursive: true, force: true });});+function eperm(): NodeJS.ErrnoException {+ const err = new Error('locked by another process') as NodeJS.ErrnoException;+ err.code = 'EPERM';+ return err;+}+describe('storage › timestamps & ids', () => {it('nowIso renders local time as YYYY-MM-DDTHH:MM:SS without TZ', () => {expect(nowIso()).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/);@@ -87,6 +93,21 @@ describe('storage › JSON IO', () => {expect(fs.existsSync(p)).toBe(true);});+ it('writeJson retries transient EPERM rename failures', async () => {+ const p = path.join(tmpDir, 'retry.json');+ let calls = 0;+ fs.writeFileSync(`${p}.tmp`, '{"ok":true}', 'utf8');++ await __storageTestHooks.renameWithRetryUsing(`${p}.tmp`, p, async (from, to) => {+ calls += 1;+ if (calls <= 2) throw eperm();+ await fs.promises.rename(from, to);+ });++ expect(await readJson(p)).toEqual({ ok: true });+ expect(calls).toBe(3);+ });+it('readJson returns {} on missing file', async () => {expect(await readJson(path.join(tmpDir, 'missing.json'))).toEqual({});});@@ -109,6 +130,21 @@ describe('storage › JSON IO', () => {writeJsonSync(p, { ok: 1 });expect(fs.existsSync(p)).toBe(true);});++ it('writeJsonSync retries transient EPERM rename failures', () => {+ const p = path.join(tmpDir, 'sync-retry.json');+ let calls = 0;+ fs.writeFileSync(`${p}.tmp`, '{"ok":true}', 'utf8');++ __storageTestHooks.renameWithRetrySyncUsing(`${p}.tmp`, p, (from, to) => {+ calls += 1;+ if (calls <= 2) throw eperm();+ fs.renameSync(from, to);+ });++ expect(readJsonSync(p)).toEqual({ ok: true });+ expect(calls).toBe(3);+ });});describe('storage › writeTextAtomicSync', () => {