Skip to content

armgit / Orkas

Public Imported from GitHub
0

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

Bundle pinned Python runtime tooling

wyt9d047682639a
diff --git a/bin/ensure-runtime.cjs b/bin/ensure-runtime.cjs
new file mode 100755
index 00000000..2a51231c
--- /dev/null
+++ b/bin/ensure-runtime.cjs
@@ -0,0 +1,484 @@
+#!/usr/bin/env node
+/**
+ * Ensure Orkas' pinned Python/uv runtime exists.
+ *
+ * Build-time use:
+ * node bin/ensure-runtime.cjs --root resources/runtime --platform darwin --arch arm64
+ *
+ * The production app never calls this script at runtime. Dev launchers and
+ * electron-builder hooks call it before boot/packaging so packaged apps only
+ * consume already-present resources.
+ */
+
+'use strict';
+
+const fs = require('node:fs');
+const path = require('node:path');
+const https = require('node:https');
+const crypto = require('node:crypto');
+const { spawnSync } = require('node:child_process');
+
+const MARKER = '.orkas-runtime.json';
+const KINDS = ['python', 'uv'];
+const DOWNLOAD_TIMEOUT_MS = 10 * 60 * 1000;
+
+function die(message, extra) {
+ const payload = { ok: false, error: message };
+ if (extra) Object.assign(payload, extra);
+ process.stderr.write(JSON.stringify(payload, null, 2) + '\n');
+ process.exit(1);
+}
+
+function parseArgs(argv) {
+ const opts = {
+ platform: process.platform,
+ arch: process.arch,
+ root: '',
+ manifest: '',
+ check: false,
+ noDownload: false,
+ quiet: false,
+ all: false,
+ kinds: KINDS.slice(),
+ };
+ for (let i = 2; i < argv.length; i += 1) {
+ const arg = argv[i];
+ if (arg === '--platform') opts.platform = argv[++i] || '';
+ else if (arg === '--arch') opts.arch = argv[++i] || '';
+ else if (arg === '--root') opts.root = path.resolve(argv[++i] || '');
+ else if (arg === '--manifest') opts.manifest = path.resolve(argv[++i] || '');
+ else if (arg === '--check') opts.check = true;
+ else if (arg === '--no-download') opts.noDownload = true;
+ else if (arg === '--quiet') opts.quiet = true;
+ else if (arg === '--all') opts.all = true;
+ else if (arg === '--kind') {
+ const kind = argv[++i] || '';
+ if (!KINDS.includes(kind)) die(`unsupported runtime kind: ${kind}`);
+ opts.kinds = [kind];
+ } else if (arg === '--help' || arg === '-h') {
+ process.stdout.write([
+ 'Usage: ensure-runtime.cjs [--platform p --arch a] [--root dir]',
+ ' [--check] [--no-download] [--quiet]',
+ ' [--kind python|uv] [--all]',
+ '',
+ 'Default --root is resources/runtime. Production app startup must not',
+ 'call this script; dev launchers and packaging hooks call it before boot.',
+ '',
+ ].join('\n'));
+ process.exit(0);
+ } else {
+ die(`unknown argument: ${arg}`);
+ }
+ }
+ if (!opts.platform || !opts.arch) die('platform and arch are required');
+ return opts;
+}
+
+function pcRoot() {
+ return path.resolve(__dirname, '..');
+}
+
+function defaultResourceRoot() {
+ if (process.env.ORKAS_RUNTIME_DIR) return path.resolve(process.env.ORKAS_RUNTIME_DIR);
+ const rp = process.resourcesPath;
+ if (rp && !rp.includes(`${path.sep}node_modules${path.sep}electron${path.sep}`)) {
+ return path.join(rp, 'runtime');
+ }
+ return path.join(pcRoot(), 'resources', 'runtime');
+}
+
+function manifestPath(opts) {
+ const candidates = [
+ opts.manifest,
+ path.join(defaultResourceRoot(), 'manifest.json'),
+ path.join(pcRoot(), 'resources', 'runtime', 'manifest.json'),
+ ].filter(Boolean);
+ for (const candidate of candidates) {
+ try {
+ if (fs.statSync(candidate).isFile()) return candidate;
+ } catch {
+ /* try next */
+ }
+ }
+ die('runtime manifest not found', { candidates });
+}
+
+function readManifest(opts) {
+ const file = manifestPath(opts);
+ try {
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
+ return { file, manifest: parsed };
+ } catch (err) {
+ die('failed to read runtime manifest', { file, error: err.message });
+ }
+}
+
+function platformKey(platform, arch) {
+ return `${platform}-${arch}`;
+}
+
+function assetFor(manifest, kind, key) {
+ return manifest[kind] && manifest[kind].assets && manifest[kind].assets[key];
+}
+
+function runtimeDir(root, kind, key) {
+ return path.join(root, kind, key);
+}
+
+function currentDir(root, kind) {
+ return path.join(root, kind, 'current');
+}
+
+function markerFile(dir) {
+ return path.join(dir, MARKER);
+}
+
+function relPath(root, rel) {
+ return path.join(root, ...String(rel || '').split(/[\\/]/).filter(Boolean));
+}
+
+function isFile(p) {
+ try { return fs.statSync(p).isFile(); } catch { return false; }
+}
+
+function isDir(p) {
+ try { return fs.statSync(p).isDirectory(); } catch { return false; }
+}
+
+function readMarker(dir) {
+ try { return JSON.parse(fs.readFileSync(markerFile(dir), 'utf8')); } catch { return null; }
+}
+
+function markerMatches(marker, kind, key, spec, asset) {
+ return !!marker
+ && marker.kind === kind
+ && marker.platformKey === key
+ && marker.version === spec.version
+ && marker.asset === asset.name
+ && marker.sha256 === asset.sha256
+ && marker.size === asset.size;
+}
+
+function statusInRoot(root, kind, key, spec, asset) {
+ let unverified = null;
+ for (const dir of [currentDir(root, kind), runtimeDir(root, kind, key)]) {
+ const executable = relPath(dir, asset.executable);
+ const marker = readMarker(dir);
+ if (isFile(executable) && markerMatches(marker, kind, key, spec, asset)) {
+ return { ok: true, status: 'ready', root, dir, executable, verified: true };
+ }
+ if (isFile(executable)) {
+ unverified ||= { ok: false, status: 'unverified', root, dir, executable, verified: false };
+ }
+ }
+ if (unverified) return unverified;
+ return { ok: false, status: 'missing', root, dir: runtimeDir(root, kind, key), executable: relPath(runtimeDir(root, kind, key), asset.executable), verified: false };
+}
+
+function log(opts, msg, meta) {
+ if (opts.quiet) return;
+ if (meta) process.stderr.write(`${msg} ${JSON.stringify(meta)}\n`);
+ else process.stderr.write(`${msg}\n`);
+}
+
+function sha256File(file) {
+ const hash = crypto.createHash('sha256');
+ hash.update(fs.readFileSync(file));
+ return hash.digest('hex');
+}
+
+function downloadFile(url, dest) {
+ return new Promise((resolve, reject) => {
+ const started = Date.now();
+ const request = (currentUrl, redirectsLeft) => {
+ const req = https.get(currentUrl, { headers: { 'User-Agent': 'OrkasRuntime/1.0' } }, (res) => {
+ const code = res.statusCode || 0;
+ if (code >= 300 && code < 400 && res.headers.location) {
+ res.resume();
+ if (redirectsLeft <= 0) {
+ reject(new Error('too many redirects'));
+ return;
+ }
+ request(new URL(res.headers.location, currentUrl).toString(), redirectsLeft - 1);
+ return;
+ }
+ if (code !== 200) {
+ res.resume();
+ reject(new Error(`download failed with HTTP ${code}`));
+ return;
+ }
+ const out = fs.createWriteStream(dest);
+ res.pipe(out);
+ out.on('finish', () => out.close(resolve));
+ out.on('error', reject);
+ });
+ req.setTimeout(DOWNLOAD_TIMEOUT_MS, () => {
+ req.destroy(new Error('download timed out'));
+ });
+ req.on('error', reject);
+ const timer = setInterval(() => {
+ if (Date.now() - started > DOWNLOAD_TIMEOUT_MS) {
+ clearInterval(timer);
+ req.destroy(new Error('download timed out'));
+ }
+ }, 1_000);
+ timer.unref?.();
+ req.on('close', () => clearInterval(timer));
+ };
+ request(url, 5);
+ });
+}
+
+function runCommand(cmd, args, opts) {
+ const res = spawnSync(cmd, args, {
+ encoding: 'utf8',
+ stdio: opts.quiet ? ['ignore', 'pipe', 'pipe'] : 'inherit',
+ timeout: opts.timeoutMs || 5 * 60 * 1000,
+ });
+ if (res.error) return { ok: false, error: res.error.message, status: null, stderr: res.stderr || '' };
+ if (res.status !== 0) return { ok: false, error: `${cmd} exited ${res.status}`, status: res.status, stderr: res.stderr || '' };
+ return { ok: true, stdout: res.stdout || '', stderr: res.stderr || '' };
+}
+
+function extractArchive(archive, extractDir, asset, opts) {
+ fs.mkdirSync(extractDir, { recursive: true });
+ const tarArgs = asset.archive === 'tar.gz'
+ ? ['-xzf', archive, '-C', extractDir]
+ : ['-xf', archive, '-C', extractDir];
+ let res = runCommand('tar', tarArgs, opts);
+ if (res.ok) return;
+
+ if (asset.archive === 'zip') {
+ if (process.platform === 'win32') {
+ const command = [
+ 'Expand-Archive',
+ '-LiteralPath', JSON.stringify(archive),
+ '-DestinationPath', JSON.stringify(extractDir),
+ '-Force',
+ ].join(' ');
+ res = runCommand('powershell.exe', ['-NoLogo', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', command], opts);
+ if (res.ok) return;
+ } else {
+ res = runCommand('unzip', ['-q', archive, '-d', extractDir], opts);
+ if (res.ok) return;
+ }
+ }
+
+ die('failed to extract runtime archive', { archive, error: res.error, stderr: String(res.stderr || '').slice(-1200) });
+}
+
+function findByBasename(root, names) {
+ const wanted = new Set(names);
+ const stack = [root];
+ while (stack.length) {
+ const dir = stack.pop();
+ let entries = [];
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { continue; }
+ for (const entry of entries) {
+ const p = path.join(dir, entry.name);
+ if (entry.isDirectory()) stack.push(p);
+ else if (entry.isFile() && wanted.has(entry.name)) return p;
+ }
+ }
+ return '';
+}
+
+function copyTree(src, dest) {
+ fs.rmSync(dest, { recursive: true, force: true });
+ fs.cpSync(src, dest, { recursive: true, dereference: true });
+}
+
+function preparePayload(kind, extractDir, payloadDir, asset) {
+ fs.rmSync(payloadDir, { recursive: true, force: true });
+ fs.mkdirSync(payloadDir, { recursive: true });
+
+ if (kind === 'uv') {
+ const exeName = path.basename(asset.executable);
+ const exe = findByBasename(extractDir, [exeName]);
+ if (!exe) die('uv executable missing from archive', { archiveAsset: asset.name, executable: exeName });
+ const dest = relPath(payloadDir, asset.executable);
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
+ fs.copyFileSync(exe, dest);
+ try { fs.chmodSync(dest, 0o755); } catch { /* chmod is best-effort on Windows */ }
+
+ const uvxName = exeName === 'uv.exe' ? 'uvx.exe' : 'uvx';
+ const uvx = findByBasename(extractDir, [uvxName]);
+ if (uvx) {
+ const uvxDest = path.join(payloadDir, uvxName);
+ fs.copyFileSync(uvx, uvxDest);
+ try { fs.chmodSync(uvxDest, 0o755); } catch { /* best-effort */ }
+ }
+ return;
+ }
+
+ copyTree(extractDir, payloadDir);
+}
+
+function doctorDir(dir, kind, asset, opts) {
+ const executable = relPath(dir, asset.executable);
+ if (isFile(executable)) {
+ try { fs.chmodSync(executable, 0o755); } catch { /* best-effort */ }
+ }
+ if (kind === 'python') {
+ for (const rel of ['python/bin/python', 'python/bin/python3', 'bin/python', 'bin/python3']) {
+ const p = relPath(dir, rel);
+ if (isFile(p)) {
+ try { fs.chmodSync(p, 0o755); } catch { /* best-effort */ }
+ }
+ }
+ }
+ if (opts.platform === 'darwin') {
+ runCommand('xattr', ['-dr', 'com.apple.quarantine', dir], { ...opts, quiet: true, timeoutMs: 30_000 });
+ }
+}
+
+function writeMarker(dir, kind, key, spec, asset) {
+ fs.writeFileSync(markerFile(dir), JSON.stringify({
+ schema: 1,
+ kind,
+ platformKey: key,
+ version: spec.version,
+ source: spec.source,
+ release: spec.release,
+ asset: asset.name,
+ sha256: asset.sha256,
+ size: asset.size,
+ installedAt: new Date().toISOString(),
+ }, null, 2));
+}
+
+function replaceDir(dest, payloadDir) {
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
+ const backup = `${dest}.bak-${process.pid}-${Date.now()}`;
+ const hadDest = isDir(dest);
+ if (hadDest) fs.renameSync(dest, backup);
+ try {
+ fs.renameSync(payloadDir, dest);
+ if (hadDest) fs.rmSync(backup, { recursive: true, force: true });
+ } catch (err) {
+ try { fs.rmSync(dest, { recursive: true, force: true }); } catch { /* ignore */ }
+ if (hadDest && isDir(backup)) {
+ try { fs.renameSync(backup, dest); } catch { /* ignore */ }
+ }
+ throw err;
+ }
+}
+
+function shouldRunSelfCheck(key) {
+ return key === platformKey(process.platform, process.arch);
+}
+
+function selfCheck(kind, dir, asset, key, opts) {
+ if (!shouldRunSelfCheck(key)) return '';
+ const executable = relPath(dir, asset.executable);
+ if (!isFile(executable)) die('runtime executable missing after install', { kind, executable });
+ const args = ['--version'];
+ const res = spawnSync(executable, args, {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ timeout: 30_000,
+ });
+ if (res.error || res.status !== 0) {
+ die('runtime executable failed self-check', {
+ kind,
+ executable,
+ error: res.error && res.error.message,
+ status: res.status,
+ stderr: String(res.stderr || '').slice(-1200),
+ });
+ }
+ const version = String(res.stdout || res.stderr || '').trim();
+ log(opts, `runtime ${kind} self-check ok`, { version });
+ return version;
+}
+
+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 (opts.check || opts.noDownload) return { kind, key, ...current };
+
+ const dest = runtimeDir(root, kind, key);
+ const tmp = fs.mkdtempSync(path.join(root, `.${kind}-${key}-`));
+ const archive = path.join(tmp, asset.name);
+ const extractDir = path.join(tmp, 'extract');
+ const payloadDir = path.join(tmp, 'payload');
+ try {
+ log(opts, `runtime ${kind}: downloading`, { key, asset: asset.name });
+ await downloadFile(asset.url, archive);
+ const st = fs.statSync(archive);
+ if (st.size !== asset.size) {
+ die('runtime archive size mismatch', { kind, key, expected: asset.size, actual: st.size, asset: asset.name });
+ }
+ const digest = sha256File(archive);
+ if (digest !== asset.sha256) {
+ die('runtime archive sha256 mismatch', { kind, key, expected: asset.sha256, actual: digest, asset: asset.name });
+ }
+ extractArchive(archive, extractDir, asset, opts);
+ preparePayload(kind, extractDir, payloadDir, asset);
+ doctorDir(payloadDir, kind, asset, opts);
+ writeMarker(payloadDir, kind, key, spec, asset);
+ replaceDir(dest, payloadDir);
+ fs.rmSync(tmp, { recursive: true, force: true });
+ const versionOutput = selfCheck(kind, dest, asset, key, opts);
+ return {
+ kind,
+ key,
+ ok: true,
+ status: 'downloaded',
+ root,
+ dir: dest,
+ executable: relPath(dest, asset.executable),
+ verified: true,
+ versionOutput,
+ };
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+}
+
+function targetKeys(opts, manifest) {
+ if (!opts.all) return [platformKey(opts.platform, opts.arch)];
+ const keys = new Set();
+ for (const kind of opts.kinds) {
+ for (const key of Object.keys((manifest[kind] && manifest[kind].assets) || {})) keys.add(key);
+ }
+ return Array.from(keys).sort();
+}
+
+async function main() {
+ const opts = parseArgs(process.argv);
+ if (!opts.root) opts.root = defaultResourceRoot();
+ const { file: manifestFile, manifest } = readManifest(opts);
+ const results = [];
+ let ok = true;
+
+ for (const key of targetKeys(opts, manifest)) {
+ for (const kind of opts.kinds) {
+ const spec = manifest[kind];
+ const asset = assetFor(manifest, kind, key);
+ if (!spec || !asset) {
+ ok = false;
+ results.push({ kind, key, ok: false, status: 'unsupported' });
+ continue;
+ }
+
+ const res = await ensureInRoot(opts.root, kind, key, spec, asset, opts);
+ if (!res.ok) ok = false;
+ results.push(res);
+ }
+ }
+
+ const summary = {
+ ok,
+ manifest: manifestFile,
+ platform: opts.platform,
+ arch: opts.arch,
+ root: opts.root,
+ results,
+ };
+ if (!opts.quiet) process.stdout.write(JSON.stringify(summary, null, 2) + '\n');
+ if (!ok) process.exit(1);
+}
+
+main().catch((err) => die('runtime ensure failed', { error: err && err.message }));
diff --git a/bin/orkas-pkg.cjs b/bin/orkas-pkg.cjs
index 7207111b..dac20538 100644
--- a/bin/orkas-pkg.cjs
+++ b/bin/orkas-pkg.cjs
@@ -46,6 +46,10 @@
* current_user_id, then 'anonymous'.
* ORKAS_WORKSPACE_ROOT — data root (ORKAS_WS_ROOT honoured as alias;
* default ~/.orkas/data).
+ * ORKAS_PYTHON — optional bundled Python executable used for
+ * Python package venv creation.
+ * ORKAS_UV — optional bundled uv executable used for Python
+ * package dependency installs.
*/
'use strict';
@@ -189,6 +193,39 @@ function runOrDie(cmd, args, opts, what) {
function isFile(p) { try { return fs.statSync(p).isFile(); } catch { return false; } }
function isDir(p) { try { return fs.statSync(p).isDirectory(); } catch { return false; } }
+function commandFromEnv(value) {
+ if (!value) return null;
+ if (path.isAbsolute(value) || value.includes('/') || value.includes('\\')) {
+ return isFile(value) ? value : null;
+ }
+ return value;
+}
+
+function pythonCommand() {
+ const configured = commandFromEnv(process.env.ORKAS_PYTHON);
+ if (configured) return { cmd: configured, args: [], label: '$ORKAS_PYTHON' };
+ if (process.platform === 'win32') return { cmd: 'python', args: [], label: 'python' };
+ return { cmd: 'python3', args: [], label: 'python3' };
+}
+
+function uvCommand() {
+ const configured = commandFromEnv(process.env.ORKAS_UV);
+ if (configured) return configured;
+ return null;
+}
+
+function venvPythonPath(pkgDir) {
+ return process.platform === 'win32'
+ ? path.join(pkgDir, '.venv', 'Scripts', 'python.exe')
+ : path.join(pkgDir, '.venv', 'bin', 'python');
+}
+
+function venvPipPath(pkgDir) {
+ return process.platform === 'win32'
+ ? path.join(pkgDir, '.venv', 'Scripts', 'pip.exe')
+ : path.join(pkgDir, '.venv', 'bin', 'pip');
+}
+
/** Candidate rel dirs whose children (or, for '.', the dir itself) hold SKILL.md. */
const SKILL_ROOT_CANDIDATES = ['skills', path.join('.claude', 'skills')];
@@ -283,7 +320,17 @@ function hasPythonProject(pkgDir) {
function describeDepCommands(pkgDir) {
const cmds = [];
if (hasNodeDeps(pkgDir)) cmds.push('npm install --omit=dev');
- if (hasPythonProject(pkgDir)) cmds.push('python3 -m venv .venv && .venv/bin/pip install -e .');
+ if (hasPythonProject(pkgDir)) {
+ const uv = uvCommand();
+ if (uv) {
+ const venvCmd = process.env.ORKAS_PYTHON
+ ? '$ORKAS_UV venv --python $ORKAS_PYTHON .venv'
+ : '$ORKAS_UV venv .venv';
+ cmds.push(`${venvCmd} && $ORKAS_UV pip install --python .venv -e .`);
+ } else {
+ cmds.push(`${pythonCommand().label} -m venv .venv && ${process.platform === 'win32' ? '.venv\\Scripts\\pip.exe' : '.venv/bin/pip'} install -e .`);
+ }
+ }
return cmds;
}
@@ -295,13 +342,22 @@ function installDeps(pkgDir) {
}
if (hasPythonProject(pkgDir)) {
const venv = path.join(pkgDir, '.venv');
- const py = process.platform === 'win32' ? 'python' : 'python3';
- if (!isDir(venv)) runOrDie(py, ['-m', 'venv', '.venv'], { cwd: pkgDir }, 'venv creation');
- const pip = process.platform === 'win32'
- ? path.join(venv, 'Scripts', 'pip.exe')
- : path.join(venv, 'bin', 'pip');
- runOrDie(pip, ['install', '-e', '.'], { cwd: pkgDir }, 'pip install');
- performed.push('pip install -e .');
+ const uv = uvCommand();
+ if (uv) {
+ if (!isDir(venv)) {
+ const args = ['venv'];
+ if (process.env.ORKAS_PYTHON) args.push('--python', process.env.ORKAS_PYTHON);
+ args.push('.venv');
+ runOrDie(uv, args, { cwd: pkgDir }, 'uv venv');
+ }
+ runOrDie(uv, ['pip', 'install', '--python', venvPythonPath(pkgDir), '-e', '.'], { cwd: pkgDir }, 'uv pip install');
+ performed.push('uv pip install -e .');
+ } else {
+ const py = pythonCommand();
+ if (!isDir(venv)) runOrDie(py.cmd, [...py.args, '-m', 'venv', '.venv'], { cwd: pkgDir }, 'venv creation');
+ runOrDie(venvPipPath(pkgDir), ['install', '-e', '.'], { cwd: pkgDir }, 'pip install');
+ performed.push('pip install -e .');
+ }
}
return performed;
}
diff --git a/bin/run-skill.cjs b/bin/run-skill.cjs
index ee6bed7d..59b8691d 100755
--- a/bin/run-skill.cjs
+++ b/bin/run-skill.cjs
@@ -9,8 +9,9 @@
* of skill language:
* .ts / .mjs / .js — require() with tsx/cjs hook, call default export as
* `async (args) => result`, JSON.stringify result to stdout.
- * .py — spawn `python3` (Windows: `py -3` then `python`),
- * inherit stdio, exit with child's code.
+ * .py — spawn nearest package `.venv`, else `ORKAS_PYTHON`,
+ * else system Python (`python3`; Windows: `py -3`
+ * then `python`), inherit stdio, exit with child code.
* .ps1 — spawn PowerShell (Windows-native script).
* .cmd / .bat — spawn `cmd.exe` (Windows-native batch script).
* .sh — spawn `bash` (Windows: Git Bash only; WSL is not
@@ -43,6 +44,9 @@
* platform default ~/.orkas/data is used.
* ORKAS_RUN_SKILL_DIR — optional trusted caller allow-list override:
* resolve only inside this concrete skill dir.
+ * ORKAS_PYTHON — optional bundled Python executable injected by
+ * the main process when resources/runtime is
+ * available.
* ELECTRON_RUN_AS_NODE — set to 1 when running through Electron binary.
*
* This file is CommonJS so it can be required directly without import-hook
@@ -329,11 +333,12 @@ function existingFile(p) {
function findOnPath(names, env = process.env) {
const pathValue = env.PATH || env.Path || env.path || '';
const dirs = pathValue.split(path.delimiter).filter(Boolean);
- const rawPathext = env.PATHEXT || '.COM;.EXE;.BAT;.CMD';
- const pathext = rawPathext.split(';').map((x) => x.trim()).filter(Boolean);
+ const pathext = process.platform === 'win32'
+ ? String(env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').map((x) => x.trim()).filter(Boolean)
+ : [''];
for (const dir of dirs) {
for (const name of names) {
- const variants = path.extname(name) ? [name] : [name, ...pathext.map((ext) => `${name}${ext}`)];
+ const variants = path.extname(name) ? [name] : pathext.map((ext) => `${name}${ext}`);
for (const variant of variants) {
const candidate = path.join(dir, variant);
if (existingFile(candidate)) return candidate;
@@ -376,6 +381,25 @@ function findPowerShell() {
return process.platform === 'win32' ? 'powershell.exe' : 'pwsh';
}
+function commandFromEnv(value) {
+ if (!value) return null;
+ if (path.isAbsolute(value) || value.includes('/') || value.includes('\\')) {
+ return existingFile(value) ? value : null;
+ }
+ return value;
+}
+
+function findPython(isWin) {
+ const configured = commandFromEnv(process.env.ORKAS_PYTHON);
+ if (configured) return { cmd: configured, args: [] };
+ if (isWin) {
+ const pyLauncher = findOnPath(['py.exe', 'py']);
+ if (pyLauncher) return { cmd: pyLauncher, args: ['-3'] };
+ return { cmd: 'python', args: [] };
+ }
+ return { cmd: 'python3', args: [] };
+}
+
function registerTsxLoader() {
if (!process.env.ORKAS_PC_DIR) {
die(69, 'ORKAS_PC_DIR env not set — cannot locate tsx for .ts transpile');
@@ -411,15 +435,13 @@ function runViaSubprocess(scriptPath, scriptArgs, skillId) {
if (venvPython) {
cmd = venvPython;
} else if (isWin) {
- const pyLauncher = findOnPath(['py.exe', 'py']);
- if (pyLauncher) {
- cmd = pyLauncher;
- argv0Args = ['-3'];
- } else {
- cmd = 'python';
- }
+ const py = findPython(isWin);
+ cmd = py.cmd;
+ argv0Args = py.args;
} else {
- cmd = 'python3';
+ const py = findPython(isWin);
+ cmd = py.cmd;
+ argv0Args = py.args;
}
} else if (ext === 'sh') {
if (isWin) {
diff --git a/package.json b/package.json
index 2b3a0841..b2821a76 100644
--- a/package.json
+++ b/package.json
@@ -10,17 +10,18 @@
"#core-agent": "./src/core-agent/src/index.ts"
},
"scripts": {
- "start": "electron .",
+ "start": "node bin/ensure-runtime.cjs --root resources/runtime && electron .",
"stop": "pkill -9 -f \"$PWD/node_modules/electron/dist\" || true",
"smoke": "tsx src/main/smoke.ts",
"typecheck": "tsc --noEmit",
"test": "node scripts/run-tests.mjs run",
"test:watch": "node scripts/run-tests.mjs",
+ "runtime:ensure": "node bin/ensure-runtime.cjs --root resources/runtime",
"rebuild:sqlite:electron": "node scripts/swap-sqlite-abi.mjs electron",
"rebuild:sqlite:node": "node scripts/swap-sqlite-abi.mjs node",
"postinstall": "node scripts/swap-sqlite-abi.mjs electron && node scripts/fetch-embedding-model.mjs",
"prepare": "node scripts/install-git-hooks.mjs",
- "prepack": "node scripts/swap-sqlite-abi.mjs electron"
+ "prepack": "node bin/ensure-runtime.cjs --root resources/runtime && node scripts/swap-sqlite-abi.mjs electron"
},
"devDependencies": {
"@types/adm-zip": "^0.5.7",
@@ -106,6 +107,13 @@
"!*.tar.gz"
]
},
+ {
+ "from": "resources/runtime",
+ "to": "runtime",
+ "filter": [
+ "**/*"
+ ]
+ },
{
"from": "resources/mac-locales",
"to": ".",
@@ -114,6 +122,7 @@
]
}
],
+ "beforePack": "scripts/ensure-runtime-before-pack.cjs",
"afterPack": "scripts/codesign-adhoc.cjs",
"mac": {
"category": "public.app-category.productivity",
diff --git a/resources/runtime/README.md b/resources/runtime/README.md
new file mode 100644
index 00000000..13b6ed52
--- /dev/null
+++ b/resources/runtime/README.md
@@ -0,0 +1,47 @@
+Bundled runtime drop-in directory.
+
+This directory is the packaged runtime source. Dev launchers and build hooks run
+`bin/ensure-runtime.cjs --root resources/runtime` before boot/packaging. The
+script downloads the pinned assets from `manifest.json`, verifies `sha256`/size,
+extracts them, and writes a `.orkas-runtime.json` marker under each platform
+directory.
+
+The production app does not invoke the downloader at runtime. Packaging must
+finish with the required Python/uv directories already present under
+`resources/runtime`, and the app only injects `ORKAS_PYTHON` / `ORKAS_UV` when
+those binaries are present in packaged resources. `ORKAS_RUNTIME_DIR` is an
+explicit developer override, not an automatic repair cache.
+
+Version policy:
+
+- Python is pinned to CPython 3.12 for broad third-party wheel compatibility in
+ skill/package scripts. The current lock is Python 3.12.13 from Python's 3.12
+ security line, using `astral-sh/python-build-standalone` release `20260610`.
+- uv is pinned to `0.11.21`, the upstream uv release checked on 2026-06-18.
+- Updating either version requires refreshing all asset URLs, sizes and
+ sha256 digests in `manifest.json`, then running runtime and package-install
+ smoke tests across macOS, Windows, and Linux targets.
+
+Expected layout:
+
+```
+runtime/
+ python/
+ current/
+ python/bin/python3 # macOS/Linux python-build-standalone
+ python/python.exe # Windows python-build-standalone
+ darwin-arm64/
+ darwin-x64/
+ win32-x64/
+ uv/
+ current/
+ uv
+ uv.exe
+ darwin-arm64/
+ darwin-x64/
+ win32-x64/
+```
+
+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.
diff --git a/resources/runtime/manifest.json b/resources/runtime/manifest.json
new file mode 100644
index 00000000..4aad4047
--- /dev/null
+++ b/resources/runtime/manifest.json
@@ -0,0 +1,123 @@
+{
+ "schema": 1,
+ "lockedAt": "2026-06-18",
+ "selectionPolicy": {
+ "python": "Pin CPython 3.12 as Orkas' conservative skill/runtime baseline for broad third-party wheel compatibility. 3.12.13 is the Python.org 3.12 security release available in python-build-standalone 20260610. Move to a newer Python minor only after package smoke tests pass on macOS, Windows, and Linux.",
+ "uv": "Pin the upstream uv release used to create and install Python package venvs. 0.11.21 was the latest astral-sh/uv GitHub release checked on 2026-06-18. Move only with manifest digest refresh and package install smoke tests.",
+ "sources": [
+ "https://www.python.org/downloads/release/python-31213/",
+ "https://github.com/astral-sh/python-build-standalone/releases/tag/20260610",
+ "https://github.com/astral-sh/uv/releases/tag/0.11.21"
+ ]
+ },
+ "python": {
+ "version": "3.12.13+20260610",
+ "source": "astral-sh/python-build-standalone",
+ "release": "20260610",
+ "assets": {
+ "darwin-arm64": {
+ "name": "cpython-3.12.13+20260610-aarch64-apple-darwin-install_only_stripped.tar.gz",
+ "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260610/cpython-3.12.13%2B20260610-aarch64-apple-darwin-install_only_stripped.tar.gz",
+ "sha256": "f0a7fa7decc75df2b1a789329a44f657c4a15c0a683f197ce46a5cb621bc6ef4",
+ "size": 25000199,
+ "archive": "tar.gz",
+ "executable": "python/bin/python3"
+ },
+ "darwin-x64": {
+ "name": "cpython-3.12.13+20260610-x86_64-apple-darwin-install_only_stripped.tar.gz",
+ "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260610/cpython-3.12.13%2B20260610-x86_64-apple-darwin-install_only_stripped.tar.gz",
+ "sha256": "c56c2dfe3fb5569430f4eabcff1fc1334c66db708bf17c103eef3dd237f3e3ab",
+ "size": 24690110,
+ "archive": "tar.gz",
+ "executable": "python/bin/python3"
+ },
+ "win32-arm64": {
+ "name": "cpython-3.12.13+20260610-aarch64-pc-windows-msvc-install_only_stripped.tar.gz",
+ "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260610/cpython-3.12.13%2B20260610-aarch64-pc-windows-msvc-install_only_stripped.tar.gz",
+ "sha256": "45cef3d23be2bbf950e33f1ed2517aaab5b5efb2f1bf2ae5b2c16ad9a7acc176",
+ "size": 20655217,
+ "archive": "tar.gz",
+ "executable": "python/python.exe"
+ },
+ "win32-x64": {
+ "name": "cpython-3.12.13+20260610-x86_64-pc-windows-msvc-install_only_stripped.tar.gz",
+ "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260610/cpython-3.12.13%2B20260610-x86_64-pc-windows-msvc-install_only_stripped.tar.gz",
+ "sha256": "99dce0b23bf3c3b28d350cdd7bfe3cd3be51cc4f285faae7c0df110d106d1a8d",
+ "size": 21932694,
+ "archive": "tar.gz",
+ "executable": "python/python.exe"
+ },
+ "linux-arm64": {
+ "name": "cpython-3.12.13+20260610-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz",
+ "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260610/cpython-3.12.13%2B20260610-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz",
+ "sha256": "eb85c6903552b1cb40b183a119681a9326fa97e31cf0e4b8c78bf26735ff1552",
+ "size": 29197829,
+ "archive": "tar.gz",
+ "executable": "python/bin/python3"
+ },
+ "linux-x64": {
+ "name": "cpython-3.12.13+20260610-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz",
+ "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260610/cpython-3.12.13%2B20260610-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz",
+ "sha256": "6682afef6b510037a0ad84e61150e5121af2e2785c9ca27b047e029270a840fe",
+ "size": 34145919,
+ "archive": "tar.gz",
+ "executable": "python/bin/python3"
+ }
+ }
+ },
+ "uv": {
+ "version": "0.11.21",
+ "source": "astral-sh/uv",
+ "release": "0.11.21",
+ "assets": {
+ "darwin-arm64": {
+ "name": "uv-aarch64-apple-darwin.tar.gz",
+ "url": "https://github.com/astral-sh/uv/releases/download/0.11.21/uv-aarch64-apple-darwin.tar.gz",
+ "sha256": "1f921d491ba5ffeea774eb04d6681ecee379101341cbb1500394993b541bf3f4",
+ "size": 20835123,
+ "archive": "tar.gz",
+ "executable": "uv"
+ },
+ "darwin-x64": {
+ "name": "uv-x86_64-apple-darwin.tar.gz",
+ "url": "https://github.com/astral-sh/uv/releases/download/0.11.21/uv-x86_64-apple-darwin.tar.gz",
+ "sha256": "f3c8e5708a84b920c18b691214d54d2b0da6b984789caae95d47c95120cb7765",
+ "size": 22349034,
+ "archive": "tar.gz",
+ "executable": "uv"
+ },
+ "win32-arm64": {
+ "name": "uv-aarch64-pc-windows-msvc.zip",
+ "url": "https://github.com/astral-sh/uv/releases/download/0.11.21/uv-aarch64-pc-windows-msvc.zip",
+ "sha256": "74e443f8004022dde57a1bd0d10c097830f9ea8feb4ec927db52cd5d805c2f48",
+ "size": 21936792,
+ "archive": "zip",
+ "executable": "uv.exe"
+ },
+ "win32-x64": {
+ "name": "uv-x86_64-pc-windows-msvc.zip",
+ "url": "https://github.com/astral-sh/uv/releases/download/0.11.21/uv-x86_64-pc-windows-msvc.zip",
+ "sha256": "ace861f360c6de2babedc1607d0f454b6b09a820dbc8182dc15af927e4df9589",
+ "size": 23452481,
+ "archive": "zip",
+ "executable": "uv.exe"
+ },
+ "linux-arm64": {
+ "name": "uv-aarch64-unknown-linux-gnu.tar.gz",
+ "url": "https://github.com/astral-sh/uv/releases/download/0.11.21/uv-aarch64-unknown-linux-gnu.tar.gz",
+ "sha256": "88e800834007cc5efd4675f166eb2a51e7e3ad19876d85fa8805a6fb5c922397",
+ "size": 22805727,
+ "archive": "tar.gz",
+ "executable": "uv"
+ },
+ "linux-x64": {
+ "name": "uv-x86_64-unknown-linux-gnu.tar.gz",
+ "url": "https://github.com/astral-sh/uv/releases/download/0.11.21/uv-x86_64-unknown-linux-gnu.tar.gz",
+ "sha256": "8c88519b0ef0af9801fcdee419bbb12116bd9e6b18e162ae093c932d8b264050",
+ "size": 24437894,
+ "archive": "tar.gz",
+ "executable": "uv"
+ }
+ }
+ }
+}
diff --git a/run.cmd b/run.cmd
index 2a203c8b..77fd7a38 100644
--- a/run.cmd
+++ b/run.cmd
@@ -14,6 +14,8 @@ echo [Orkas] 启动 Orkas (global prod)
call node "%APP_DIR%\scripts\ensure-deps.cjs"
if errorlevel 1 exit /b 1
+call node "%APP_DIR%\bin\ensure-runtime.cjs" --root "%APP_DIR%\resources\runtime"
+if errorlevel 1 exit /b 1
pushd "%APP_DIR%"
taskkill /F /IM electron.exe >nul 2>nul
diff --git a/run.sh b/run.sh
index cb4edbe1..ea93c2a5 100755
--- a/run.sh
+++ b/run.sh
@@ -40,6 +40,7 @@ fi
echo "[Orkas] Starting Orkas (global prod)"
node "$APP_DIR/scripts/ensure-deps.cjs"
+node "$APP_DIR/bin/ensure-runtime.cjs" --root "$APP_DIR/resources/runtime"
cd "$APP_DIR"
pkill -9 -f "$APP_DIR/node_modules/electron/dist" >/dev/null 2>&1 || true
diff --git a/scripts/ensure-runtime-before-pack.cjs b/scripts/ensure-runtime-before-pack.cjs
new file mode 100755
index 00000000..6fdf7da5
--- /dev/null
+++ b/scripts/ensure-runtime-before-pack.cjs
@@ -0,0 +1,49 @@
+#!/usr/bin/env node
+'use strict';
+
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const ARCH_MAP = new Map([
+ ['0', 'ia32'],
+ ['1', 'x64'],
+ ['2', 'armv7l'],
+ ['3', 'arm64'],
+ ['4', 'universal'],
+ ['ia32', 'ia32'],
+ ['x64', 'x64'],
+ ['armv7l', 'armv7l'],
+ ['arm64', 'arm64'],
+ ['universal', 'universal'],
+]);
+
+function normalizeArch(value) {
+ return ARCH_MAP.get(String(value)) || String(value || process.arch);
+}
+
+module.exports = async function ensureRuntimeBeforePack(context) {
+ const pcRoot = path.resolve(__dirname, '..');
+ const platform = context && context.electronPlatformName
+ ? String(context.electronPlatformName)
+ : process.platform;
+ const arch = normalizeArch(context && context.arch);
+ const arches = arch === 'universal' ? ['x64', 'arm64'] : [arch];
+
+ for (const targetArch of arches) {
+ const res = spawnSync(process.execPath, [
+ path.join(pcRoot, 'bin', 'ensure-runtime.cjs'),
+ '--root', path.join(pcRoot, 'resources', 'runtime'),
+ '--platform', platform,
+ '--arch', targetArch,
+ ], {
+ cwd: pcRoot,
+ encoding: 'utf8',
+ stdio: 'inherit',
+ env: process.env,
+ });
+ if (res.error) throw res.error;
+ if (res.status !== 0) {
+ throw new Error(`ensure-runtime failed for ${platform}-${targetArch} with status ${res.status}`);
+ }
+ }
+};
diff --git a/src/main/features/local_agents/bridge.ts b/src/main/features/local_agents/bridge.ts
index 50b700e5..5965c520 100644
--- a/src/main/features/local_agents/bridge.ts
+++ b/src/main/features/local_agents/bridge.ts
@@ -68,8 +68,9 @@ export interface StartBridgeOpts {
/** Where to write the per-run mcp-config file (the persist run dir). */
configDir: string;
/** Static skill-sandbox env (ORKAS_NODE / ORKAS_PC_DIR /
- * ORKAS_WORKSPACE_ROOT / ELECTRON_RUN_AS_NODE) — reused so the bridge
- * server resolves the SDK and run-skill.cjs exactly like bash does. */
+ * ORKAS_WORKSPACE_ROOT / ELECTRON_RUN_AS_NODE plus optional bundled
+ * ORKAS_PYTHON / ORKAS_UV) — reused so the bridge server resolves the
+ * SDK and run-skill.cjs exactly like command execution does. */
sandboxEnv: Record<string, string>;
}
diff --git a/src/main/model/core-agent/client.ts b/src/main/model/core-agent/client.ts
index 550c55b7..3f92d519 100644
--- a/src/main/model/core-agent/client.ts
+++ b/src/main/model/core-agent/client.ts
@@ -36,6 +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';
interface NoopRecorder {
record(event: unknown): void;
@@ -95,6 +96,8 @@ export async function* stopStreamOnAbort<T>(
* packaged mode so `bin/run-skill.cjs` + tsx + skills resolve on real disk
* - `ORKAS_WORKSPACE_ROOT` = canonical data root so `run-skill.cjs` can
* find installed per-user skills under `<uid>/local/marketplace/skills`
+ * - `ORKAS_PYTHON` / `ORKAS_UV` = optional bundled Python runtime and uv
+ * binary under resources/runtime, used for `.py` skills and package deps
* - `ELECTRON_RUN_AS_NODE` = makes the Electron binary boot as Node
*
* Injected via `AgentRunParams.sandboxEnv` → `ToolContext.state.sandboxEnv`
@@ -132,7 +135,7 @@ function buildSkillSandboxEnvStatic(): Record<string, string> {
* brew/system PATH is preserved.
*/
export function buildSkillSandboxEnv(userId?: string): Record<string, string> {
- const env = { ...buildSkillSandboxEnvStatic() };
+ const env = { ...buildSkillSandboxEnvStatic(), ...bundledRuntimeEnv() };
env.ORKAS_UI_LANG = getCurrentLang();
if (userId) {
env.ORKAS_UID = userId;
diff --git a/src/main/paths.ts b/src/main/paths.ts
index cff3b020..5dced3cc 100644
--- a/src/main/paths.ts
+++ b/src/main/paths.ts
@@ -524,6 +524,20 @@ export function embeddingModelDir(): string {
return path.join(PC_ROOT, 'resources', 'embedding-model');
}
+/** Runtime binaries shipped via electron-builder `extraResources`.
+ *
+ * dev: PC/resources/runtime/
+ * packed: <app>/Contents/Resources/runtime/ (darwin)
+ * <app>/resources/runtime/ (win/linux)
+ */
+export function runtimeResourcesDir(): string {
+ const rp = (process as unknown as { resourcesPath?: string }).resourcesPath;
+ if (rp && !rp.includes(`${path.sep}node_modules${path.sep}electron${path.sep}`)) {
+ return path.join(rp, 'runtime');
+ }
+ return path.join(PC_ROOT, 'resources', 'runtime');
+}
+
// (No shipped builtin source tree anymore. The marketplace is the only source for
// platform agents/skills, fetched at install time and reconciled from the cloud manifest.)
diff --git a/src/main/util/bundled-runtime.ts b/src/main/util/bundled-runtime.ts
new file mode 100644
index 00000000..64953635
--- /dev/null
+++ b/src/main/util/bundled-runtime.ts
@@ -0,0 +1,84 @@
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+import { runtimeResourcesDir } from '../paths';
+
+function isFile(p: string | undefined): p is string {
+ if (!p) return false;
+ try { return fs.statSync(p).isFile(); }
+ catch { return false; }
+}
+
+function platformKey(platform = process.platform, arch = process.arch): string {
+ return `${platform}-${arch}`;
+}
+
+function pushUnique(out: string[], seen: Set<string>, value: string | undefined): void {
+ if (!value) return;
+ const resolved = path.resolve(value);
+ if (seen.has(resolved)) return;
+ seen.add(resolved);
+ out.push(resolved);
+}
+
+function runtimeRoots(): string[] {
+ const roots: string[] = [];
+ const seen = new Set<string>();
+ pushUnique(roots, seen, process.env.ORKAS_RUNTIME_DIR);
+ pushUnique(roots, seen, runtimeResourcesDir());
+ return roots;
+}
+
+function runtimeVariantDirs(kind: 'python' | 'uv'): string[] {
+ const dirs: string[] = [];
+ for (const runtimeRoot of runtimeRoots()) {
+ const root = path.join(runtimeRoot, kind);
+ dirs.push(path.join(root, 'current'), path.join(root, platformKey()));
+ }
+ return [
+ ...dirs,
+ ];
+}
+
+function resolvePythonExecutable(): string | undefined {
+ const configured = process.env.ORKAS_BUNDLED_PYTHON || process.env.ORKAS_PYTHON;
+ if (isFile(configured)) return configured;
+
+ const names = process.platform === 'win32'
+ ? ['python.exe', path.join('python', 'python.exe')]
+ : [
+ path.join('python', 'bin', 'python3'),
+ path.join('python', 'bin', 'python'),
+ path.join('bin', 'python3'),
+ path.join('bin', 'python'),
+ ];
+
+ for (const dir of runtimeVariantDirs('python')) {
+ for (const name of names) {
+ const candidate = path.join(dir, name);
+ if (isFile(candidate)) return candidate;
+ }
+ }
+ return undefined;
+}
+
+function resolveUvExecutable(): string | undefined {
+ const configured = process.env.ORKAS_BUNDLED_UV || process.env.ORKAS_UV;
+ if (isFile(configured)) return configured;
+
+ const name = process.platform === 'win32' ? 'uv.exe' : 'uv';
+ for (const dir of runtimeVariantDirs('uv')) {
+ const candidate = path.join(dir, name);
+ if (isFile(candidate)) return candidate;
+ }
+ return undefined;
+}
+
+export function bundledRuntimeEnv(): Record<string, string> {
+ const env: Record<string, string> = {};
+ const python = resolvePythonExecutable();
+ const uv = resolveUvExecutable();
+ if (python) env.ORKAS_PYTHON = python;
+ if (uv) env.ORKAS_UV = uv;
+ return env;
+}
diff --git a/test/main/util/ensure-runtime.test.ts b/test/main/util/ensure-runtime.test.ts
new file mode 100644
index 00000000..6b6ad5aa
--- /dev/null
+++ b/test/main/util/ensure-runtime.test.ts
@@ -0,0 +1,144 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { spawnSync } from 'node:child_process';
+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-runtime-'));
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+function writeManifest(key: string, executable: string): string {
+ const manifest = {
+ schema: 1,
+ python: {
+ version: 'test-python',
+ source: 'test',
+ release: 'test',
+ assets: {
+ [key]: {
+ name: 'python-test.tar.gz',
+ url: 'https://example.invalid/python-test.tar.gz',
+ sha256: 'abc123',
+ size: 123,
+ archive: 'tar.gz',
+ executable,
+ },
+ },
+ },
+ uv: {
+ version: 'test-uv',
+ source: 'test',
+ release: 'test',
+ assets: {},
+ },
+ };
+ const file = path.join(tmpDir, 'manifest.json');
+ fs.writeFileSync(file, JSON.stringify(manifest, null, 2));
+ return file;
+}
+
+function runEnsure(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',
+ '--check',
+ ], {
+ 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}`;
+ const executable = process.platform === 'win32' ? 'python/python.exe' : 'python/bin/python3';
+ 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 = runEnsure(root, manifest, key);
+
+ expect(r.status).toBe(0);
+ const out = JSON.parse(r.stdout);
+ expect(out.ok).toBe(true);
+ expect(out.results[0].status).toBe('ready');
+ expect(out.results[0].verified).toBe(true);
+ });
+
+ it('reports an executable without a marker as unverified in check mode', () => {
+ const key = `${process.platform}-${process.arch}`;
+ const executable = process.platform === 'win32' ? 'python/python.exe' : 'python/bin/python3';
+ const manifest = writeManifest(key, executable);
+ const root = path.join(tmpDir, 'runtime');
+ const exe = path.join(root, 'python', key, ...executable.split('/'));
+ fs.mkdirSync(path.dirname(exe), { recursive: true });
+ fs.writeFileSync(exe, '');
+
+ const r = runEnsure(root, manifest, key);
+
+ expect(r.status).toBe(1);
+ const out = JSON.parse(r.stdout);
+ expect(out.ok).toBe(false);
+ expect(out.results[0].status).toBe('unverified');
+ });
+
+ it('prefers a verified platform directory over an unverified current directory', () => {
+ const key = `${process.platform}-${process.arch}`;
+ const executable = process.platform === 'win32' ? 'python/python.exe' : 'python/bin/python3';
+ const manifest = writeManifest(key, executable);
+ const root = path.join(tmpDir, 'runtime');
+ const currentExe = path.join(root, 'python', 'current', ...executable.split('/'));
+ fs.mkdirSync(path.dirname(currentExe), { recursive: true });
+ fs.writeFileSync(currentExe, '');
+
+ 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 = runEnsure(root, manifest, key);
+
+ expect(r.status).toBe(0);
+ const out = JSON.parse(r.stdout);
+ expect(out.ok).toBe(true);
+ expect(out.results[0].status).toBe('ready');
+ expect(out.results[0].dir).toBe(dir);
+ });
+});
diff --git a/test/main/util/orkas-pkg.test.ts b/test/main/util/orkas-pkg.test.ts
index 9d18790d..42a2e06e 100644
--- a/test/main/util/orkas-pkg.test.ts
+++ b/test/main/util/orkas-pkg.test.ts
@@ -14,6 +14,7 @@ let tmpDir: string;
let wsRoot: string;
const gitAvailable = spawnSync('git', ['--version'], { encoding: 'utf8' }).status === 0;
+const itOnNonWindows = process.platform === 'win32' ? it.skip : it;
function pkgsDir(): string {
return path.join(wsRoot, TEST_UID, 'local', 'packages');
@@ -47,13 +48,14 @@ function makeRepo(name: string, files: Record<string, string>): string {
return repo;
}
-function runPkg(...args: string[]) {
+function runPkgWithEnv(extraEnv: Record<string, string>, ...args: string[]) {
const pcRoot = process.cwd();
const r = spawnSync(process.execPath, [path.join(pcRoot, 'bin', 'orkas-pkg.cjs'), ...args], {
cwd: pcRoot,
encoding: 'utf8',
env: {
...process.env,
+ ...extraEnv,
ORKAS_WORKSPACE_ROOT: wsRoot,
ORKAS_UID: TEST_UID,
ORKAS_PC_DIR: pcRoot,
@@ -70,6 +72,10 @@ function runPkg(...args: string[]) {
return { status: r.status, json, stdout: r.stdout, stderr: r.stderr };
}
+function runPkg(...args: string[]) {
+ return runPkgWithEnv({}, ...args);
+}
+
function runPkgInput(input: string, ...args: string[]) {
const pcRoot = process.cwd();
const r = spawnSync(process.execPath, [path.join(pcRoot, 'bin', 'orkas-pkg.cjs'), ...args], {
@@ -193,6 +199,55 @@ describe.skipIf(!gitAvailable)('orkas-pkg.cjs', () => {
expect(fs.existsSync(path.join(pkgsDir(), '.bin', 'real-entry'))).toBe(false);
});
+ itOnNonWindows('uses ORKAS_UV and ORKAS_PYTHON for Python package dependency consent', () => {
+ const repo = makeRepo('pyuv', {
+ 'pyproject.toml': [
+ '[build-system]',
+ 'requires = ["setuptools"]',
+ '',
+ '[project.scripts]',
+ 'real-entry = "pkg.cli:main"',
+ ].join('\n'),
+ 'pkg/__init__.py': '',
+ });
+ const fakePython = path.join(tmpDir, 'fake-python');
+ fs.writeFileSync(fakePython, '#!/bin/sh\nexit 0\n');
+ fs.chmodSync(fakePython, 0o755);
+ const fakeUv = path.join(tmpDir, 'fake-uv');
+ fs.writeFileSync(fakeUv, [
+ '#!/bin/sh',
+ 'set -eu',
+ 'if [ "$1" = "venv" ]; then',
+ ' mkdir -p .venv/bin',
+ ' printf "#!/bin/sh\\nexit 0\\n" > .venv/bin/python',
+ ' chmod +x .venv/bin/python',
+ 'elif [ "$1" = "pip" ]; then',
+ ' mkdir -p .venv/bin',
+ ' printf "#!/bin/sh\\necho real-entry\\n" > .venv/bin/real-entry',
+ ' chmod +x .venv/bin/real-entry',
+ 'else',
+ ' exit 2',
+ 'fi',
+ '',
+ ].join('\n'));
+ fs.chmodSync(fakeUv, 0o755);
+ const env = { ORKAS_UV: fakeUv, ORKAS_PYTHON: fakePython };
+
+ const install = runPkgWithEnv(env, 'install', repo);
+ expect(install.status).toBe(0);
+ expect(install.json.deps_pending_consent).toEqual([
+ '$ORKAS_UV venv --python $ORKAS_PYTHON .venv && $ORKAS_UV pip install --python .venv -e .',
+ ]);
+ expect(fs.existsSync(path.join(pkgsDir(), '.bin', 'real-entry'))).toBe(false);
+
+ const consent = runPkgWithEnv(env, 'consent-deps', 'pyuv');
+ expect(consent.status).toBe(0);
+ expect(consent.json.deps_installed).toEqual(['uv pip install -e .']);
+ expect(consent.json.shims).toEqual(['real-entry']);
+ expect(fs.existsSync(path.join(pkgsDir(), 'pyuv', '.venv', 'bin', 'real-entry'))).toBe(true);
+ expect(fs.existsSync(path.join(pkgsDir(), '.bin', 'real-entry'))).toBe(true);
+ });
+
it('refuses duplicate install and supports remove', () => {
const repo = makeRepo('dup', { 'SKILL.md': '---\nname: dup\n---\nx' });
expect(runPkg('install', repo).status).toBe(0);
diff --git a/test/main/util/run-skill.test.ts b/test/main/util/run-skill.test.ts
index b2f33078..8818aafe 100644
--- a/test/main/util/run-skill.test.ts
+++ b/test/main/util/run-skill.test.ts
@@ -29,7 +29,7 @@ function writeMarketplaceSkill(dirId: string, displayName: string, scriptBase: s
);
}
-function runSkill(skillRef: string, scriptBase: string, args: string[] = []) {
+function runSkill(skillRef: string, scriptBase: string, args: string[] = [], extraEnv: Record<string, string> = {}) {
const pcRoot = process.cwd();
return spawnSync(process.execPath, [
path.join(pcRoot, 'bin', 'run-skill.cjs'),
@@ -42,6 +42,7 @@ function runSkill(skillRef: string, scriptBase: string, args: string[] = []) {
encoding: 'utf8',
env: {
...process.env,
+ ...extraEnv,
ORKAS_WORKSPACE_ROOT: tmpDir,
ORKAS_PC_DIR: pcRoot,
},
@@ -86,4 +87,32 @@ describe('run-skill.cjs', () => {
expect(r.stderr).toBe('');
expect(JSON.parse(r.stdout.trim())).toEqual({ runner: 'sh' });
});
+
+ itOnNonWindows('uses ORKAS_PYTHON for plain Python skill scripts', () => {
+ const skillDir = path.join(tmpDir, 'u1', 'local', 'marketplace', 'skills', 'py-skill');
+ const scriptsDir = path.join(skillDir, 'scripts');
+ fs.mkdirSync(scriptsDir, { recursive: true });
+ fs.writeFileSync(
+ path.join(skillDir, 'SKILL.md'),
+ '---\nname: py-skill\ndescription: test\n---\n\nbody\n',
+ );
+ fs.writeFileSync(path.join(scriptsDir, 'run.py'), 'print("system python should not run this")\n');
+
+ const fakePython = path.join(tmpDir, 'fake-python');
+ fs.writeFileSync(fakePython, [
+ '#!/bin/sh',
+ 'printf \'{"python":"bundled","script":"%s","argv":"%s"}\\n\' "$1" "$2"',
+ '',
+ ].join('\n'));
+ fs.chmodSync(fakePython, 0o755);
+
+ const r = runSkill('py-skill', 'run', ['arg1'], { ORKAS_PYTHON: fakePython });
+
+ expect(r.status).toBe(0);
+ expect(r.stderr).toBe('');
+ const out = JSON.parse(r.stdout.trim());
+ expect(out.python).toBe('bundled');
+ expect(out.script).toMatch(/run\.py$/);
+ expect(out.argv).toBe('arg1');
+ });
});