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 bundled runtime tool execution
wytf158c272613c
diff --git a/bin/ensure-runtime.cjs b/bin/ensure-runtime.cjsindex 2a51231c..bd3a3fea 100755--- a/bin/ensure-runtime.cjs+++ b/bin/ensure-runtime.cjs@@ -314,7 +314,60 @@ function preparePayload(kind, extractDir, payloadDir, asset) {copyTree(extractDir, payloadDir);}-function doctorDir(dir, kind, asset, opts) {+function pythonVersionSuffix(spec) {+ const m = /^(\d+)\.(\d+)/.exec(String(spec.version || ''));+ return m ? `${m[1]}.${m[2]}` : '';+}++function writeFileIfChanged(file, content, mode) {+ try {+ if (fs.readFileSync(file, 'utf8') === content) {+ if (mode != null) {+ try { fs.chmodSync(file, mode); } catch { /* best-effort */ }+ }+ return;+ }+ } catch {+ /* missing or unreadable -> write below */+ }+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, content, 'utf8');+ if (mode != null) {+ try { fs.chmodSync(file, mode); } catch { /* best-effort */ }+ }+}++function createPythonPipShims(dir, spec, asset, opts) {+ const pythonExe = relPath(dir, asset.executable);+ if (!isFile(pythonExe)) return;+ const suffix = pythonVersionSuffix(spec);+ const names = ['pip', 'pip3', ...(suffix ? [`pip${suffix}`] : [])];++ if (opts.platform === 'win32') {+ const shimDir = path.join(path.dirname(pythonExe), 'Scripts');+ const relPython = path.relative(shimDir, pythonExe).split(path.sep).join('\\');+ for (const name of names) {+ writeFileIfChanged(+ path.join(shimDir, `${name}.cmd`),+ `@echo off\r\nsetlocal\r\n"%~dp0${relPython}" -m pip %*\r\n`,+ null,+ );+ }+ return;+ }++ const shimDir = path.dirname(pythonExe);+ const relPython = path.relative(shimDir, pythonExe).split(path.sep).join('/');+ for (const name of names) {+ writeFileIfChanged(+ path.join(shimDir, name),+ `#!/bin/sh\nSCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)\nexec "$SCRIPT_DIR/${relPython}" -m pip "$@"\n`,+ 0o755,+ );+ }+}++function doctorDir(dir, kind, spec, asset, opts) {const executable = relPath(dir, asset.executable);if (isFile(executable)) {try { fs.chmodSync(executable, 0o755); } catch { /* best-effort */ }@@ -326,6 +379,7 @@ function doctorDir(dir, kind, asset, opts) {try { fs.chmodSync(p, 0o755); } catch { /* best-effort */ }}}+ createPythonPipShims(dir, spec, asset, opts);}if (opts.platform === 'darwin') {runCommand('xattr', ['-dr', 'com.apple.quarantine', dir], { ...opts, quiet: true, timeoutMs: 30_000 });@@ -395,7 +449,10 @@ function selfCheck(kind, dir, asset, key, opts) {async function ensureInRoot(root, kind, key, spec, asset, opts) {fs.mkdirSync(root, { recursive: true });const current = statusInRoot(root, kind, key, spec, asset);- if (current.ok) return { kind, key, ...current };+ if (current.ok) {+ if (!opts.check) doctorDir(current.dir, kind, spec, asset, opts);+ return { kind, key, ...current };+ }if (opts.check || opts.noDownload) return { kind, key, ...current };const dest = runtimeDir(root, kind, key);@@ -416,7 +473,7 @@ async function ensureInRoot(root, kind, key, spec, asset, opts) {}extractArchive(archive, extractDir, asset, opts);preparePayload(kind, extractDir, payloadDir, asset);- doctorDir(payloadDir, kind, asset, opts);+ doctorDir(payloadDir, kind, spec, asset, opts);writeMarker(payloadDir, kind, key, spec, asset);replaceDir(dest, payloadDir);fs.rmSync(tmp, { recursive: true, force: true });diff --git a/resources/runtime/README.md b/resources/runtime/README.mdindex 13b6ed52..7345a4df 100644--- a/resources/runtime/README.md+++ b/resources/runtime/README.md@@ -45,3 +45,7 @@ runtime/The app resolves `current` first, then `<platform>-<arch>`, and injects`ORKAS_PYTHON` / `ORKAS_UV` into command execution when binaries are present.Resolution checks an explicit `ORKAS_RUNTIME_DIR`, then packaged resources.++`ensure-runtime.cjs` also writes lightweight `pip` / `pip3` shims for the+bundled Python. They forward to `python -m pip`, because the standalone Python+asset includes the pip module but may not ship `Scripts/pip.exe`.diff --git a/scripts/codesign-adhoc.cjs b/scripts/codesign-adhoc.cjsindex 81e1d98a..ecff52ac 100644--- a/scripts/codesign-adhoc.cjs+++ b/scripts/codesign-adhoc.cjs@@ -10,7 +10,7 @@*/'use strict';-const { execSync } = require('node:child_process');+const { execFileSync, execSync } = require('node:child_process');const fs = require('node:fs');const path = require('node:path');@@ -259,6 +259,105 @@ function appNodeModules(context, appPath) {return path.join(context.appOutDir, 'resources', 'app.asar.unpacked', 'node_modules');}+function appResourcesDir(context, appPath) {+ if (context.electronPlatformName === 'darwin') {+ return path.join(appPath, 'Contents', 'Resources');+ }+ return path.join(context.appOutDir, 'resources');+}++function readJsonFile(label, file) {+ requiredFile(label, file);+ try {+ return JSON.parse(fs.readFileSync(file, 'utf8'));+ } catch (err) {+ throw new Error(`[native-deps-gate] invalid ${label}: ${file}: ${err.message}`);+ }+}++function runtimeAsset(manifest, kind, platformKey) {+ const spec = manifest[kind];+ const asset = spec && spec.assets && spec.assets[platformKey];+ if (!spec || !asset) {+ throw new Error(`[native-deps-gate] missing runtime manifest entry for ${kind}/${platformKey}`);+ }+ return { spec, asset };+}++function markerMatches(marker, kind, platformKey, spec, asset) {+ return marker+ && marker.kind === kind+ && marker.platformKey === platformKey+ && marker.version === spec.version+ && marker.asset === asset.name+ && marker.sha256 === asset.sha256+ && marker.size === asset.size;+}++function pythonVersionSuffix(spec) {+ const m = /^(\d+)\.(\d+)/.exec(String(spec.version || ''));+ return m ? `${m[1]}.${m[2]}` : '';+}++function verifyPythonPipShims(executable, targetPlatform, spec) {+ const suffix = pythonVersionSuffix(spec);+ const names = ['pip', 'pip3', ...(suffix ? [`pip${suffix}`] : [])];+ const shimDir = targetPlatform === 'win32'+ ? path.join(path.dirname(executable), 'Scripts')+ : path.dirname(executable);+ for (const name of names) {+ requiredFile(+ `python runtime ${name} shim`,+ path.join(shimDir, targetPlatform === 'win32' ? `${name}.cmd` : name),+ );+ }+}++function requireOnlyRuntimeDirs(runtimeRoot, kind, allowedKey) {+ const kindDir = path.join(runtimeRoot, kind);+ if (!fs.existsSync(kindDir) || !fs.statSync(kindDir).isDirectory()) {+ throw new Error(`[native-deps-gate] missing runtime ${kind} directory: ${kindDir}`);+ }+ for (const dirName of listDirs(kindDir)) {+ if (dirName !== allowedKey) {+ throw new Error(`[native-deps-gate] unexpected runtime ${kind} payload for target: ${path.join(kindDir, dirName)}`);+ }+ }+}++function assertDarwinExecutableArch(file, targetArch) {+ const expected = targetArch === 'x64' ? 'x86_64' : targetArch;+ if (!expected || !fs.existsSync('/usr/bin/file')) return;+ const out = execFileSync('/usr/bin/file', [file], { encoding: 'utf8' });+ if (!out.includes(expected)) {+ throw new Error(`[native-deps-gate] runtime binary arch mismatch: expected ${expected}, file=${file}, output=${out.trim()}`);+ }+}++function verifyPackedRuntimePayload(context, appPath, targetPlatform, targetArch) {+ const runtimeRoot = path.join(appResourcesDir(context, appPath), 'runtime');+ const manifest = readJsonFile('runtime manifest', path.join(runtimeRoot, 'manifest.json'));+ const key = `${targetPlatform}-${targetArch}`;+ const verified = [];++ for (const kind of ['python', 'uv']) {+ const { spec, asset } = runtimeAsset(manifest, kind, key);+ requireOnlyRuntimeDirs(runtimeRoot, kind, key);+ const dir = path.join(runtimeRoot, kind, key);+ const executable = path.join(dir, ...String(asset.executable || '').split(/[\\/]/).filter(Boolean));+ const marker = readJsonFile(`${kind} runtime marker`, path.join(dir, '.orkas-runtime.json'));+ if (!markerMatches(marker, kind, key, spec, asset)) {+ throw new Error(`[native-deps-gate] runtime marker mismatch for ${kind}/${key}: ${path.join(dir, '.orkas-runtime.json')}`);+ }+ requiredFile(`${kind} runtime executable`, executable);+ if (kind === 'python') verifyPythonPipShims(executable, targetPlatform, spec);+ if (targetPlatform === 'darwin') assertDarwinExecutableArch(executable, targetArch);+ verified.push(`runtime:${kind}:${key}`);+ }++ return verified;+}+function prunePackedNativePayload(context, appPath, targetPlatform, targetArch) {const nodeModules = appNodeModules(context, appPath);if (!fs.existsSync(nodeModules)) return [];@@ -307,7 +406,10 @@ module.exports = async function afterPack(context) {console.log('==== Native dependency gate: post-package/pre-sign ====');console.log(`[native-deps-gate] target=${targetPlatform}/${targetArch}`);- const verified = prunePackedNativePayload(context, appPath, targetPlatform, targetArch);+ const verified = [+ ...prunePackedNativePayload(context, appPath, targetPlatform, targetArch),+ ...verifyPackedRuntimePayload(context, appPath, targetPlatform, targetArch),+ ];writeNativeGateMarker(context, targetPlatform, targetArch, verified);console.log(`[native-deps-gate] verified: ${verified.join(', ')}`);console.log('[native-deps-gate] result=passed; signing may continue');diff --git a/src/core-agent/src/agent/runner.ts b/src/core-agent/src/agent/runner.tsindex 12b7bb1c..8e5f4829 100644--- a/src/core-agent/src/agent/runner.ts+++ b/src/core-agent/src/agent/runner.ts@@ -391,16 +391,36 @@ export class AgentRunner {if (call.name === "skill_manage" && call.input && (call.input as any).action === "read" && (call.input as any).id) {skillsLoadedSet.add((call.input as any).id as string);}+ let toolResultRecorded = false;+ const addToolResultOnce = (content: string, images?: ToolResult["images"], isError?: boolean): boolean => {+ if (toolResultRecorded) return false;+ this.session.addToolResult(call.id, content, images, isError);+ toolResultRecorded = true;+ return true;+ };+ const abortedToolMessage = "Tool execution aborted: Run aborted";try {- if (params.signal?.aborted) throw new Error("Run aborted");+ if (params.signal?.aborted) {+ addToolResultOnce(abortedToolMessage, undefined, true);+ yield {+ type: "tool_end",+ id: call.id,+ name: call.name,+ result: abortedToolMessage,+ isError: true,+ };+ throw new Error("Run aborted");+ }log.debug(`Executing tool: ${call.name}`);const progressQueue: Array<Extract<AgentRunEvent, { type: "tool_progress" }>> = [];let notifyProgress: (() => void) | null = null;+ let acceptingProgress = true;const toolCtx: ToolContext = {workingDir: params.workingDir,signal: params.signal,state: toolState,emitProgress: (progress) => {+ if (!acceptingProgress) return;const message = String(progress?.message || "").trim();if (!message) return;progressQueue.push({@@ -441,39 +461,63 @@ export class AgentRunner {if (abortWait.promise) waits.push(abortWait.promise);const raced = await Promise.race(waits);if (raced === "progress") continue;- if (raced === "abort") throw new Error("Run aborted");+ if (raced === "abort") {+ addToolResultOnce(abortedToolMessage, undefined, true);+ yield {+ type: "tool_end",+ id: call.id,+ name: call.name,+ result: abortedToolMessage,+ isError: true,+ };+ throw new Error("Run aborted");+ }completed = raced;notifyProgress = null;}} finally {abortWait.cleanup();notifyProgress = null;+ acceptingProgress = false;}while (progressQueue.length) {yield progressQueue.shift()!;}if (completed.ok !== true) throw completed.err;const toolResult = completed.result;- this.session.addToolResult(call.id, toolResult.content, toolResult.images, toolResult.isError);- yield {- type: "tool_end",- id: call.id,- name: call.name,- result: toolResult.content,- isError: toolResult.isError,- };+ if (addToolResultOnce(toolResult.content, toolResult.images, toolResult.isError)) {+ yield {+ type: "tool_end",+ id: call.id,+ name: call.name,+ result: toolResult.content,+ isError: toolResult.isError,+ };+ }if (toolResult.isError) {permanentToolErrors++;log.warn(`Tool ${call.name} returned error: ${toolResult.content.slice(0, 150)}`);}} catch (err) {- if (params.signal?.aborted) throw err;+ if (params.signal?.aborted) {+ if (addToolResultOnce(abortedToolMessage, undefined, true)) {+ yield {+ type: "tool_end",+ id: call.id,+ name: call.name,+ result: abortedToolMessage,+ isError: true,+ };+ }+ throw err;+ }const errMsg = formatError(err);const isTransient = isRetryableError(err);log.error(`Tool ${call.name} failed (${isTransient ? 'transient' : 'permanent'}): ${errMsg}`);const msg = `Tool execution error: ${errMsg}`;- this.session.addToolResult(call.id, msg, undefined, true);- yield { type: "tool_end", id: call.id, name: call.name, result: msg, isError: true };+ if (addToolResultOnce(msg, undefined, true)) {+ yield { type: "tool_end", id: call.id, name: call.name, result: msg, isError: true };+ }if (isTransient) transientToolErrors++;else permanentToolErrors++;}diff --git a/src/core-agent/src/sandbox/executor.ts b/src/core-agent/src/sandbox/executor.tsindex 718e9605..8ed11915 100644--- a/src/core-agent/src/sandbox/executor.ts+++ b/src/core-agent/src/sandbox/executor.ts@@ -4,7 +4,7 @@* Provides resource limits, directory restrictions, command filtering,* and timeout enforcement. Inspired by OpenClaw's sandbox execution layer.*/-import { spawn } from "node:child_process";+import { spawn, type ChildProcess } from "node:child_process";import fs from "node:fs";import path from "node:path";import { TextDecoder } from "node:util";@@ -16,7 +16,7 @@ const log = createLogger("sandbox");export interface SandboxConfig {/** Working directory for commands. */workingDir: string;- /** Maximum execution time in milliseconds (default: 30000). */+ /** Maximum execution time in milliseconds (default: 30 min). */timeoutMs?: number;/** Maximum output buffer size in bytes (default: 1MB). */maxOutputBytes?: number;@@ -49,6 +49,13 @@ export interface SandboxResult {}type ShellKind = "posix" | "cmd" | "powershell";+type KillableChild = Pick<ChildProcess, "kill" | "pid">;+type ProcessKiller = typeof process.kill;+type SpawnFn = typeof spawn;++export const DEFAULT_SANDBOX_TIMEOUT_MS = 30 * 60_000;+const KILL_GRACE_MS = 5_000;+const KILL_SETTLE_GRACE_MS = KILL_GRACE_MS + 1_000;export interface ShellInvocation {command: string;@@ -56,6 +63,56 @@ export interface ShellInvocation {kind: ShellKind;}+function windowsSystem32Tool(name: string): string {+ const root = process.env.SystemRoot || process.env.WINDIR || "C:\\Windows";+ return path.win32.join(root, "System32", name);+}++export function killProcessTree(+ child: KillableChild,+ signal: NodeJS.Signals = "SIGTERM",+ opts: {+ platform?: NodeJS.Platform;+ processKill?: ProcessKiller;+ spawnFn?: SpawnFn;+ } = {},+): void {+ const platform = opts.platform ?? process.platform;+ if (platform === "win32" && child.pid) {+ try {+ const killer = (opts.spawnFn ?? spawn)(windowsSystem32Tool("taskkill.exe"), ["/pid", String(child.pid), "/t", "/f"], {+ stdio: "ignore",+ windowsHide: true,+ });+ const fallback = () => {+ try { child.kill(signal); } catch { /* Process may already be dead. */ }+ };+ killer.once("error", fallback);+ killer.once("exit", (code) => {+ if (code !== 0) fallback();+ });+ if (typeof killer.unref === "function") killer.unref();+ return;+ } catch {+ // Fall back to killing the direct child below.+ }+ }++ try {+ if (platform !== "win32" && child.pid) {+ (opts.processKill ?? process.kill)(-child.pid, signal);+ return;+ }+ } catch {+ // Fall back to killing the shell process below.+ }+ try {+ child.kill(signal);+ } catch {+ // Process may already be dead.+ }+}+type OutputEncodingEnv = {LANG?: string;LC_ALL?: string;@@ -301,6 +358,10 @@ export function buildSandboxEnv(PATH: augmentPath(hostPath, platform, process.env),TERM: "dumb",LANG: process.env.LANG ?? "en_US.UTF-8",+ ...(platform === "win32" ? {+ PYTHONIOENCODING: process.env.PYTHONIOENCODING ?? "utf-8",+ PYTHONUTF8: process.env.PYTHONUTF8 ?? "1",+ } : {}),...(injected ?? {}),};@@ -329,7 +390,7 @@ export class SandboxExecutor {constructor(config: SandboxConfig) {this.config = {- timeoutMs: 30_000,+ timeoutMs: DEFAULT_SANDBOX_TIMEOUT_MS,maxOutputBytes: 1024 * 1024, // 1MBshell: defaultShellForPlatform(),...config,@@ -381,6 +442,8 @@ export class SandboxExecutor {let killed = false;let stdoutTruncated = false;let stderrTruncated = false;+ let settled = false;+ let forceSettleTimer: NodeJS.Timeout | null = null;const env = buildSandboxEnv(this.config.env);@@ -439,33 +502,11 @@ export class SandboxExecutor {killChild();}, this.config.timeoutMs);- function killChild() {- if (killed) return;- killed = true;- killChildWithSignal("SIGTERM");- // Escalate to SIGKILL after 5 seconds- const killTimer = setTimeout(() => killChildWithSignal("SIGKILL"), 5000);- if (typeof killTimer.unref === "function") killTimer.unref();- }-- function killChildWithSignal(signal: NodeJS.Signals) {- try {- if (process.platform !== "win32" && child.pid) {- process.kill(-child.pid, signal);- return;- }- } catch {- // Fall back to killing the shell process below.- }- try {- child.kill(signal);- } catch {- // Process may already be dead.- }- }-- child.on("close", (code) => {+ const finish = (code: number | null) => {+ if (settled) return;+ settled = true;clearTimeout(timeoutId);+ if (forceSettleTimer) clearTimeout(forceSettleTimer);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]";@@ -478,10 +519,28 @@ export class SandboxExecutor {outputLimitExceeded,durationMs: Date.now() - startTime,});+ };++ function killChild() {+ if (killed) return;+ killed = true;+ killProcessTree(child, "SIGTERM");+ // Escalate to SIGKILL after 5 seconds+ const killTimer = setTimeout(() => killProcessTree(child, "SIGKILL"), KILL_GRACE_MS);+ if (typeof killTimer.unref === "function") killTimer.unref();+ forceSettleTimer = setTimeout(() => finish(null), KILL_SETTLE_GRACE_MS);+ if (typeof forceSettleTimer.unref === "function") forceSettleTimer.unref();+ }++ child.on("close", (code) => {+ finish(code);});child.on("error", (err) => {+ if (settled) return;clearTimeout(timeoutId);+ if (forceSettleTimer) clearTimeout(forceSettleTimer);+ settled = true;const stdout = decodeProcessOutput(Buffer.concat(stdoutChunks), process.platform, env);resolve({stdout,diff --git a/src/core-agent/src/tools/builtin.ts b/src/core-agent/src/tools/builtin.tsindex 4302975a..2f86e163 100644--- a/src/core-agent/src/tools/builtin.ts+++ b/src/core-agent/src/tools/builtin.ts@@ -68,6 +68,17 @@ export const writeFileTool: AgentTool = defineTool({*/export const DEFAULT_BASH_TIMEOUT_MS = 30 * 60_000;export const BASH_PROGRESS_INTERVAL_MS = 60_000;+const LEGACY_DEFAULT_BASH_TIMEOUTS_MS = new Set([30_000, 300_000]);++export function normalizeBashTimeoutMs(value: unknown): number {+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {+ return DEFAULT_BASH_TIMEOUT_MS;+ }+ const timeoutMs = Math.round(value);+ return LEGACY_DEFAULT_BASH_TIMEOUTS_MS.has(timeoutMs)+ ? DEFAULT_BASH_TIMEOUT_MS+ : timeoutMs;+}export const bashTool: AgentTool = defineTool({name: "bash",@@ -86,7 +97,7 @@ export const bashTool: AgentTool = defineTool({},async execute(input, ctx) {const command = input.command as string;- const timeoutMs = (input.timeoutMs as number) ?? DEFAULT_BASH_TIMEOUT_MS;+ const timeoutMs = normalizeBashTimeoutMs(input.timeoutMs);const sandbox = new SandboxExecutor({workingDir: ctx.workingDir ?? ".",diff --git a/src/core-agent/test/agent-runner.test.ts b/src/core-agent/test/agent-runner.test.tsindex 994315c2..8938d83f 100644--- a/src/core-agent/test/agent-runner.test.ts+++ b/src/core-agent/test/agent-runner.test.ts@@ -481,7 +481,24 @@ describe("AgentRunner", () => {const done = collected[collected.length - 1] as { type: string; result?: { meta?: { aborted?: boolean } } };expect(done.type).toBe("done");expect(done.result?.meta?.aborted).toBe(true);- expect(collected.some((e) => e.type === "tool_end")).toBe(false);+ const toolEnd = collected.find((e) => e.type === "tool_end");+ expect(toolEnd).toMatchObject({+ type: "tool_end",+ id: "call_1",+ name: "wedged_tool",+ isError: true,+ result: "Tool execution aborted: Run aborted",+ });+ const toolResults = runner.getSession().getMessages().flatMap((msg) =>+ msg.content.filter((content) => content.type === "tool_result"),+ );+ expect(toolResults).toHaveLength(1);+ expect(toolResults[0]).toMatchObject({+ type: "tool_result",+ toolUseId: "call_1",+ content: "Tool execution aborted: Run aborted",+ isError: true,+ });});it("runStream forwards tool input deltas before tool execution", async () => {diff --git a/src/core-agent/test/sandbox.test.ts b/src/core-agent/test/sandbox.test.tsindex 6f679ba3..2adb5a7a 100644--- a/src/core-agent/test/sandbox.test.ts+++ b/src/core-agent/test/sandbox.test.ts@@ -1,16 +1,23 @@-import { describe, it, expect } from "vitest";+import { describe, it, expect, vi } from "vitest";import os from "node:os";import path from "node:path";import fs from "node:fs/promises";import {SandboxExecutor,augmentPath,+ buildSandboxEnv,buildShellInvocation,decodeProcessOutput,+ DEFAULT_SANDBOX_TIMEOUT_MS,defaultShellForPlatform,+ killProcessTree,} from "../src/sandbox/executor.js";describe("SandboxExecutor", () => {+ it("defaults command execution to the long bash timeout", () => {+ expect(DEFAULT_SANDBOX_TIMEOUT_MS).toBe(30 * 60_000);+ });+it("executes a simple command", async () => {const sandbox = new SandboxExecutor({ workingDir: os.tmpdir() });const result = await sandbox.execute("echo hello");@@ -114,6 +121,50 @@ describe("SandboxExecutor", () => {});});+describe("killProcessTree", () => {+ it("uses taskkill to terminate Windows child process trees", () => {+ const callbacks = new Map<string, (...args: any[]) => void>();+ const killer = {+ once: vi.fn((event: string, cb: (...args: any[]) => void) => {+ callbacks.set(event, cb);+ return killer;+ }),+ unref: vi.fn(),+ };+ const spawnFn = vi.fn(() => killer);+ const child = { pid: 1234, kill: vi.fn() };++ killProcessTree(child as any, "SIGTERM", {+ platform: "win32",+ spawnFn: spawnFn as any,+ });++ expect(String(spawnFn.mock.calls[0][0]).toLowerCase()).toMatch(/taskkill\.exe$/);+ expect(spawnFn).toHaveBeenCalledWith(expect.any(String), ["/pid", "1234", "/t", "/f"], {+ stdio: "ignore",+ windowsHide: true,+ });+ expect(killer.unref).toHaveBeenCalled();+ expect(child.kill).not.toHaveBeenCalled();++ callbacks.get("exit")?.(1);+ expect(child.kill).toHaveBeenCalledWith("SIGTERM");+ });++ it("kills POSIX process groups when a pid is available", () => {+ const child = { pid: 4321, kill: vi.fn() };+ const processKill = vi.fn();++ killProcessTree(child as any, "SIGKILL", {+ platform: "linux",+ processKill: processKill as any,+ });++ expect(processKill).toHaveBeenCalledWith(-4321, "SIGKILL");+ expect(child.kill).not.toHaveBeenCalled();+ });+});+describe("augmentPath", () => {it("prepends /opt/homebrew/bin when it's missing (Apple Silicon case)", () => {const out = augmentPath("/usr/bin:/bin");@@ -180,6 +231,16 @@ describe("augmentPath", () => {expect(parts).toContain("C:\\Users\\me\\AppData\\Local\\Programs\\OpenAI\\Codex\\bin");});+ it("defaults Windows Python subprocesses to UTF-8 stdio", () => {+ const env = buildSandboxEnv(undefined, "win32");+ expect(env.PYTHONIOENCODING).toBe("utf-8");+ expect(env.PYTHONUTF8).toBe("1");++ const overridden = buildSandboxEnv({ PYTHONIOENCODING: "gb18030", PYTHONUTF8: "0" }, "win32");+ expect(overridden.PYTHONIOENCODING).toBe("gb18030");+ expect(overridden.PYTHONUTF8).toBe("0");+ });+describe("Windows shell selection", () => {it("defaults Windows to PowerShell instead of a POSIX-incompatible cmd -c path", () => {expect(defaultShellForPlatform("win32")).toBe("powershell.exe");diff --git a/src/core-agent/test/tools.test.ts b/src/core-agent/test/tools.test.tsindex 288f34e7..93f4f77c 100644--- a/src/core-agent/test/tools.test.ts+++ b/src/core-agent/test/tools.test.ts@@ -3,6 +3,7 @@ import path from "node:path";import fs from "node:fs/promises";import os from "node:os";import { defineTool, toToolDefinition, getBuiltinTools } from "../src/tools/index.js";+import { DEFAULT_BASH_TIMEOUT_MS, normalizeBashTimeoutMs } from "../src/tools/builtin.js";import type { ToolContext } from "../src/tools/index.js";describe("Tools", () => {@@ -117,6 +118,13 @@ describe("Tools", () => {});describe("bash tool", () => {+ it("normalizes legacy default timeout values to the long bash timeout", () => {+ expect(normalizeBashTimeoutMs(undefined)).toBe(DEFAULT_BASH_TIMEOUT_MS);+ expect(normalizeBashTimeoutMs(30_000)).toBe(DEFAULT_BASH_TIMEOUT_MS);+ expect(normalizeBashTimeoutMs(300_000)).toBe(DEFAULT_BASH_TIMEOUT_MS);+ expect(normalizeBashTimeoutMs(5_000)).toBe(5_000);+ });+it("executes a shell command", async () => {const tools = getBuiltinTools();const bash = tools.find((t) => t.name === "bash")!;diff --git a/src/main/model/core-agent/client.ts b/src/main/model/core-agent/client.tsindex 3f92d519..f2394e77 100644--- a/src/main/model/core-agent/client.ts+++ b/src/main/model/core-agent/client.ts@@ -36,7 +36,7 @@ import { getSession as _getCachedSession } from './session-store';import { app } from 'electron';import * as paths from '../../paths';import { getCurrentLang } from '../../i18n';-import { bundledRuntimeEnv } from '../../util/bundled-runtime';+import { bundledRuntimeEnv, bundledRuntimePathEntries } from '../../util/bundled-runtime';interface NoopRecorder {record(event: unknown): void;@@ -130,13 +130,14 @@ function buildSkillSandboxEnvStatic(): Record<string, string> {* bash-driven CLIs) resolve the right per-user data tree without* parsing users.json.* - `ORKAS_PATH_PREPEND` = `<uid>/local/packages/.bin` when an enabled- * external package ships CLI shims. Composed into PATH by the sandbox- * executor (see core-agent sandbox/executor.ts) so the augmented- * brew/system PATH is preserved.+ * external package ships CLI shims, plus bundled runtime bins when+ * present. Composed into PATH by the sandbox executor (see core-agent+ * sandbox/executor.ts) so the augmented brew/system PATH is preserved.*/export function buildSkillSandboxEnv(userId?: string): Record<string, string> {const env = { ...buildSkillSandboxEnvStatic(), ...bundledRuntimeEnv() };env.ORKAS_UI_LANG = getCurrentLang();+ const pathEntries = bundledRuntimePathEntries();if (userId) {env.ORKAS_UID = userId;try {@@ -146,9 +147,12 @@ export function buildSkillSandboxEnv(userId?: string): Record<string, string> {// eslint-disable-next-line @typescript-eslint/no-require-imports, global-requireconst pkgs = require('../../features/packages') as typeof import('../../features/packages');const binDir = pkgs.packagesBinDirIfActive(userId);- if (binDir) env.ORKAS_PATH_PREPEND = binDir;+ if (binDir) pathEntries.push(binDir);} catch { /* packages feature unavailable → no shim PATH this turn */ }}+ if (pathEntries.length) {+ env.ORKAS_PATH_PREPEND = pathEntries.join(process.platform === 'win32' ? ';' : ':');+ }return env;}diff --git a/src/main/model/core-agent/local-tools.ts b/src/main/model/core-agent/local-tools.tsindex 02f436d3..774fe323 100644--- a/src/main/model/core-agent/local-tools.ts+++ b/src/main/model/core-agent/local-tools.ts@@ -48,11 +48,11 @@ import { spawn } from 'node:child_process';import type { AgentTool, ToolContext, ToolResult } from '#core-agent';import {BASH_PROGRESS_INTERVAL_MS,- DEFAULT_BASH_TIMEOUT_MS,bashTool as coreBashTool,+ normalizeBashTimeoutMs,writeFileTool as coreWriteFileTool,} from '../../../core-agent/src/tools/builtin';-import { buildSandboxEnv, decodeProcessOutput } from '../../../core-agent/src/sandbox/executor';+import { buildSandboxEnv, decodeProcessOutput, killProcessTree } from '../../../core-agent/src/sandbox/executor';import { getLocalExecGranted, getLocalExecMode } from '../../features/permissions';import { classifyBashCommand } from './bash-risk';import { requestBashDecision } from './bash-permissions';@@ -439,7 +439,7 @@ async function executeDirectOrkasCli(ctx: ToolContext,workingDir: string,): Promise<ToolResult> {- const timeoutMs = (input.timeoutMs as number | undefined) ?? DEFAULT_BASH_TIMEOUT_MS;+ const timeoutMs = normalizeBashTimeoutMs(input.timeoutMs);const sandboxEnv = (ctx.state.sandboxEnv ?? {}) as Record<string, string>;const env = buildSandboxEnv(sandboxEnv);@@ -451,12 +451,15 @@ async function executeDirectOrkasCli(let outputLimitExceeded = false;let truncatedKind: 'stdout' | 'stderr' | null = null;let settled = false;+ let killed = false;const startedAt = Date.now();let heartbeat: NodeJS.Timeout | null = null;+ let settleTimer: NodeJS.Timeout | null = null;const child = spawn(invocation.nodePath, [invocation.scriptPath, ...invocation.args], {cwd: workingDir,env,+ detached: process.platform !== 'win32',stdio: ['pipe', 'pipe', 'pipe'],windowsHide: true,});@@ -466,14 +469,40 @@ async function executeDirectOrkasCli(settled = true;clearTimeout(timeout);if (heartbeat) clearInterval(heartbeat);+ if (settleTimer) clearTimeout(settleTimer);resolve(result);};+ const finishFromChunks = (code: number | null) => {+ 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 });+ };+const killChild = () => {- try { child.kill('SIGTERM'); } catch { /* already gone */ }- setTimeout(() => {- try { child.kill('SIGKILL'); } catch { /* already gone */ }- }, 5000);+ if (killed) return;+ killed = true;+ killProcessTree(child, 'SIGTERM');+ const killTimer = setTimeout(() => killProcessTree(child, 'SIGKILL'), 5000);+ if (typeof killTimer.unref === 'function') killTimer.unref();+ settleTimer = setTimeout(() => finishFromChunks(null), 6000);+ if (typeof settleTimer.unref === 'function') settleTimer.unref();};const append = (kind: 'stdout' | 'stderr', data: Buffer) => {@@ -517,25 +546,7 @@ async function executeDirectOrkasCli(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 });+ finishFromChunks(code);});child.stdin.end(invocation.stdin ?? '');diff --git a/src/main/util/bundled-runtime.ts b/src/main/util/bundled-runtime.tsindex 64953635..f9d123c8 100644--- a/src/main/util/bundled-runtime.ts+++ b/src/main/util/bundled-runtime.ts@@ -9,6 +9,12 @@ function isFile(p: string | undefined): p is string {catch { return false; }}+function isDir(p: string | undefined): p is string {+ if (!p) return false;+ try { return fs.statSync(p).isDirectory(); }+ catch { return false; }+}+function platformKey(platform = process.platform, arch = process.arch): string {return `${platform}-${arch}`;}@@ -74,6 +80,30 @@ function resolveUvExecutable(): string | undefined {return undefined;}+function pushPathDir(out: string[], seen: Set<string>, dir: string | undefined): void {+ if (!isDir(dir)) return;+ const resolved = path.resolve(dir);+ const key = process.platform === 'win32' ? resolved.toLowerCase() : resolved;+ if (seen.has(key)) return;+ seen.add(key);+ out.push(resolved);+}++export function bundledRuntimePathEntries(): string[] {+ const entries: string[] = [];+ const seen = new Set<string>();+ const python = resolvePythonExecutable();+ if (python) {+ const pythonDir = path.dirname(python);+ pushPathDir(entries, seen, pythonDir);+ pushPathDir(entries, seen, path.join(pythonDir, 'Scripts'));+ pushPathDir(entries, seen, path.join(pythonDir, 'bin'));+ }+ const uv = resolveUvExecutable();+ if (uv) pushPathDir(entries, seen, path.dirname(uv));+ return entries;+}+export function bundledRuntimeEnv(): Record<string, string> {const env: Record<string, string> = {};const python = resolvePythonExecutable();diff --git a/test/main/model/local-tools.test.ts b/test/main/model/local-tools.test.tsindex f977a44a..a32ade1f 100644--- a/test/main/model/local-tools.test.ts+++ b/test/main/model/local-tools.test.ts@@ -202,6 +202,30 @@ describe('local-tools › Orkas CLI direct execution', () => {expect(parsed.argv).toEqual(['skill-write', 'demo']);expect(parsed.body).toBe(body);});++ it('times out direct Orkas CLI commands whose child keeps stdout open', async () => {+ const { lt, perm } = await loadModules();+ perm.grantLocalExec();+ const pcDir = writeFakePcScript(+ 'run-skill.cjs',+ [+ "const { spawn } = require('node:child_process');",+ "spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'inherit' });",+ "console.log('parent done');",+ ].join(''),+ );+ const bash = lt.createLocalTools({}).find((t) => t.name === 'bash')!;++ const started = Date.now();+ const res = await bash.execute({+ command: '$ORKAS_NODE "$ORKAS_PC_DIR/bin/run-skill.cjs" calculator eval -- 1+1',+ timeoutMs: 500,+ }, makeOrkasCtx(pcDir));++ expect(res.isError).toBe(true);+ expect(String(res.content)).toMatch(/timed out|超时/i);+ expect(Date.now() - started).toBeLessThan(7000);+ }, 10000);});// ── End-to-end: risk_prompt mode drives the real bash tool ────────────────diff --git a/test/main/util/bundled-runtime.test.ts b/test/main/util/bundled-runtime.test.tsnew file mode 100644index 00000000..60feeddb--- /dev/null+++ b/test/main/util/bundled-runtime.test.ts@@ -0,0 +1,50 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++let tmpDir: string;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-bundled-runtime-'));+ process.env.ORKAS_RUNTIME_DIR = path.join(tmpDir, 'runtime');+ process.env.ORKAS_WORKSPACE_ROOT ||= path.join(tmpDir, 'data');+});++afterEach(() => {+ delete process.env.ORKAS_RUNTIME_DIR;+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++describe('bundled-runtime', () => {+ it('exposes bundled runtime executable directories for sandbox PATH precedence', async () => {+ const key = `${process.platform}-${process.arch}`;+ const runtimeRoot = process.env.ORKAS_RUNTIME_DIR!;+ const pythonRel = process.platform === 'win32'+ ? path.join('python', key, 'python', 'python.exe')+ : path.join('python', key, 'python', 'bin', 'python3');+ const uvRel = process.platform === 'win32'+ ? path.join('uv', key, 'uv.exe')+ : path.join('uv', key, 'uv');+ const pythonExe = path.join(runtimeRoot, pythonRel);+ const uvExe = path.join(runtimeRoot, uvRel);+ fs.mkdirSync(path.dirname(pythonExe), { recursive: true });+ fs.mkdirSync(path.dirname(uvExe), { recursive: true });+ fs.writeFileSync(pythonExe, '');+ fs.writeFileSync(uvExe, '');+ if (process.platform === 'win32') {+ fs.mkdirSync(path.join(path.dirname(pythonExe), 'Scripts'), { recursive: true });+ }++ const runtime = await import('../../../src/main/util/bundled-runtime');++ expect(runtime.bundledRuntimeEnv().ORKAS_PYTHON).toBe(pythonExe);+ expect(runtime.bundledRuntimeEnv().ORKAS_UV).toBe(uvExe);+ const entries = runtime.bundledRuntimePathEntries();+ expect(entries[0]).toBe(path.dirname(pythonExe));+ expect(entries).toContain(path.dirname(uvExe));+ if (process.platform === 'win32') {+ expect(entries).toContain(path.join(path.dirname(pythonExe), 'Scripts'));+ }+ });+});diff --git a/test/main/util/codesign-runtime-gate.test.ts b/test/main/util/codesign-runtime-gate.test.tsnew file mode 100644index 00000000..0cbac82c--- /dev/null+++ b/test/main/util/codesign-runtime-gate.test.ts@@ -0,0 +1,105 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { createRequire } from 'node:module';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++const require = createRequire(import.meta.url);+const afterPack = require('../../../scripts/codesign-adhoc.cjs') as (context: any) => Promise<void>;++let tmpDir: string;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-afterpack-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++function writeRuntime(kind: 'python' | 'uv', key: string, executable: string): void {+ const dir = path.join(tmpDir, 'resources', 'runtime', kind, key);+ const exe = path.join(dir, ...executable.split('/'));+ fs.mkdirSync(path.dirname(exe), { recursive: true });+ fs.writeFileSync(exe, '');+ if (kind === 'python') {+ const scriptsDir = path.join(path.dirname(exe), 'Scripts');+ fs.mkdirSync(scriptsDir, { recursive: true });+ for (const name of ['pip', 'pip3', 'pip3.12']) {+ fs.writeFileSync(path.join(scriptsDir, `${name}.cmd`), '@echo off\r\n');+ }+ }+ fs.writeFileSync(path.join(dir, '.orkas-runtime.json'), JSON.stringify({+ schema: 1,+ kind,+ platformKey: key,+ version: kind === 'python' ? 'test-python' : 'test-uv',+ source: 'test',+ release: 'test',+ asset: `${kind}.zip`,+ sha256: `${kind}-sha`,+ size: kind === 'python' ? 101 : 202,+ }, null, 2));+}++function writeManifest(key: string): void {+ const runtimeRoot = path.join(tmpDir, 'resources', 'runtime');+ fs.mkdirSync(runtimeRoot, { recursive: true });+ fs.writeFileSync(path.join(runtimeRoot, 'manifest.json'), JSON.stringify({+ schema: 1,+ python: {+ version: 'test-python',+ source: 'test',+ release: 'test',+ assets: {+ [key]: {+ name: 'python.zip',+ url: 'https://example.invalid/python.zip',+ sha256: 'python-sha',+ size: 101,+ archive: 'zip',+ executable: 'python/python.exe',+ },+ },+ },+ uv: {+ version: 'test-uv',+ source: 'test',+ release: 'test',+ assets: {+ [key]: {+ name: 'uv.zip',+ url: 'https://example.invalid/uv.zip',+ sha256: 'uv-sha',+ size: 202,+ archive: 'zip',+ executable: 'uv.exe',+ },+ },+ },+ }, null, 2));+}++describe('codesign-adhoc runtime gate', () => {+ it('verifies packed runtime payload before signing can continue', async () => {+ const key = 'win32-x64';+ writeManifest(key);+ writeRuntime('python', key, 'python/python.exe');+ writeRuntime('uv', key, 'uv.exe');++ await afterPack({+ electronPlatformName: 'win32',+ arch: 1,+ appOutDir: tmpDir,+ packager: {+ appInfo: { productFilename: 'Orkas' },+ config: {},+ },+ });++ const marker = JSON.parse(fs.readFileSync(path.join(tmpDir, '.orkas-native-deps-verified.json'), 'utf8'));+ expect(marker.status).toBe('passed');+ expect(marker.verified).toContain('runtime:python:win32-x64');+ expect(marker.verified).toContain('runtime:uv:win32-x64');+ });+});diff --git a/test/main/util/ensure-runtime.test.ts b/test/main/util/ensure-runtime.test.tsindex 6b6ad5aa..e7b87775 100644--- a/test/main/util/ensure-runtime.test.ts+++ b/test/main/util/ensure-runtime.test.ts@@ -60,6 +60,22 @@ function runEnsure(root: string, manifest: string, key: string) {});}+function runEnsureMutable(root: string, manifest: string, key: string) {+ const [platform, arch] = key.split('-');+ return spawnSync(process.execPath, [+ path.join(process.cwd(), 'bin', 'ensure-runtime.cjs'),+ '--root', root,+ '--manifest', manifest,+ '--platform', platform,+ '--arch', arch,+ '--kind', 'python',+ '--no-download',+ ], {+ cwd: process.cwd(),+ encoding: 'utf8',+ });+}+describe('ensure-runtime.cjs', () => {it('accepts a runtime dir with a matching marker and executable', () => {const key = `${process.platform}-${process.arch}`;@@ -141,4 +157,34 @@ describe('ensure-runtime.cjs', () => {expect(out.results[0].status).toBe('ready');expect(out.results[0].dir).toBe(dir);});++ it('repairs ready Windows Python runtimes with pip command shims', () => {+ const key = 'win32-x64';+ const executable = 'python/python.exe';+ const manifest = writeManifest(key, executable);+ const root = path.join(tmpDir, 'runtime');+ const dir = path.join(root, 'python', key);+ const exe = path.join(dir, ...executable.split('/'));+ fs.mkdirSync(path.dirname(exe), { recursive: true });+ fs.writeFileSync(exe, '');+ fs.writeFileSync(path.join(dir, '.orkas-runtime.json'), JSON.stringify({+ schema: 1,+ kind: 'python',+ platformKey: key,+ version: 'test-python',+ source: 'test',+ release: 'test',+ asset: 'python-test.tar.gz',+ sha256: 'abc123',+ size: 123,+ }, null, 2));++ const r = runEnsureMutable(root, manifest, key);++ expect(r.status).toBe(0);+ for (const name of ['pip', 'pip3']) {+ const shim = path.join(dir, 'python', 'Scripts', `${name}.cmd`);+ expect(fs.readFileSync(shim, 'utf8')).toContain('-m pip');+ }+ });});