@morkaai/runtime 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +13 -2
  3. package/bin/morka.cjs +57 -0
  4. package/dist/agent-actions/access.js +44 -0
  5. package/dist/agent-actions/manifest.js +52 -0
  6. package/dist/agent-actions/runner.js +69 -0
  7. package/dist/agents/account.js +42 -0
  8. package/dist/agents/acp-sandbox.js +118 -0
  9. package/dist/agents/activity.js +26 -0
  10. package/dist/agents/attachments.js +129 -0
  11. package/dist/agents/context.js +76 -0
  12. package/dist/agents/contracts.js +2 -0
  13. package/dist/agents/process.js +61 -0
  14. package/dist/agents/providers/acp.js +411 -0
  15. package/dist/agents/providers/claude.js +180 -0
  16. package/dist/agents/providers/codex.js +416 -0
  17. package/dist/agents/registry.js +76 -0
  18. package/dist/agents/sessions.js +331 -0
  19. package/dist/app-runtime/bridge.js +40 -0
  20. package/dist/app-runtime/starter/agents.json +1 -0
  21. package/dist/app-runtime/starter/index.html +11 -0
  22. package/dist/app-runtime/starter/main.js +0 -0
  23. package/dist/app-runtime/starter/package-lock.json +13 -0
  24. package/dist/app-runtime/starter/package.json +9 -0
  25. package/dist/app-runtime/starter/server.mjs +20 -0
  26. package/dist/app-runtime/starter/styles.css +0 -0
  27. package/dist/app-runtime/text-file.js +18 -0
  28. package/dist/branding/Morka.icns +0 -0
  29. package/dist/branding/README.md +24 -0
  30. package/dist/branding/generated-app-icon.png +0 -0
  31. package/dist/branding/morka-icon.png +0 -0
  32. package/dist/branding/morka-logo.png +0 -0
  33. package/dist/electron/main.js +802 -0
  34. package/dist/electron/preload.js +51 -0
  35. package/dist/instances/desktop.js +223 -0
  36. package/dist/instances/distribution.js +240 -0
  37. package/dist/instances/macos.js +62 -0
  38. package/dist/instances/repository.js +183 -0
  39. package/dist/instances/shadow-repository.js +95 -0
  40. package/dist/project/app-proxy.js +325 -0
  41. package/dist/project/bundle-toolchain.js +35 -0
  42. package/dist/project/drafts.js +27 -0
  43. package/dist/project/files.js +176 -0
  44. package/dist/project/live-preview.js +198 -0
  45. package/dist/project/managed-runtime.js +324 -0
  46. package/dist/project/node-lifecycle.js +45 -0
  47. package/dist/project/packages.js +302 -0
  48. package/dist/project/page-state.js +198 -0
  49. package/dist/project/project.js +112 -0
  50. package/dist/project/shadow-effects.js +156 -0
  51. package/dist/project/shadows.js +122 -0
  52. package/dist/project/toolchain.js +216 -0
  53. package/dist/renderer/activity.js +91 -0
  54. package/dist/renderer/app-setup.js +126 -0
  55. package/dist/renderer/chat-tools.css +83 -0
  56. package/dist/renderer/highlight.css +118 -0
  57. package/dist/renderer/icons/attach.png +0 -0
  58. package/dist/renderer/icons/brain-weight.png +0 -0
  59. package/dist/renderer/icons/brain.png +0 -0
  60. package/dist/renderer/icons/chat.png +0 -0
  61. package/dist/renderer/icons/chevron.png +0 -0
  62. package/dist/renderer/icons/clone.png +0 -0
  63. package/dist/renderer/icons/close.png +0 -0
  64. package/dist/renderer/icons/document.png +0 -0
  65. package/dist/renderer/icons/edit.png +0 -0
  66. package/dist/renderer/icons/folder.png +0 -0
  67. package/dist/renderer/icons/import.png +0 -0
  68. package/dist/renderer/icons/open-folder.png +0 -0
  69. package/dist/renderer/icons/play.png +0 -0
  70. package/dist/renderer/icons/plus.png +0 -0
  71. package/dist/renderer/icons/remove.png +0 -0
  72. package/dist/renderer/icons/search.png +0 -0
  73. package/dist/renderer/icons/send.png +0 -0
  74. package/dist/renderer/icons/shadow.png +0 -0
  75. package/dist/renderer/icons/stop.png +0 -0
  76. package/dist/renderer/icons/terminal.png +0 -0
  77. package/dist/renderer/index.html +130 -0
  78. package/dist/renderer/launcher/OFL.txt +93 -0
  79. package/dist/renderer/launcher/cell.js +322 -0
  80. package/dist/renderer/launcher/launcher.css +79 -0
  81. package/dist/renderer/launcher/lexend-caption-bold.ttf +0 -0
  82. package/dist/renderer/launcher.html +23 -0
  83. package/dist/renderer/licenses/dompurify.txt +202 -0
  84. package/dist/renderer/licenses/github-slugger.txt +5 -0
  85. package/dist/renderer/licenses/highlight.js.txt +29 -0
  86. package/dist/renderer/licenses/marked-footnote.txt +21 -0
  87. package/dist/renderer/licenses/marked-gfm-heading-id.txt +21 -0
  88. package/dist/renderer/licenses/marked.txt +44 -0
  89. package/dist/renderer/markdown.css +43 -0
  90. package/dist/renderer/markdown.js +74 -0
  91. package/dist/renderer/renderer.js +18902 -0
  92. package/dist/renderer/styles.css +351 -0
  93. package/dist/skills/morka-agent-action/SKILL.md +39 -0
  94. package/dist/skills/morka-app/SKILL.md +36 -0
  95. package/dist/skills/morka-shadow-authoring/SKILL.md +32 -0
  96. package/package.json +30 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mehrdad Farrokhmanesh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,14 @@
1
- # Temporary Holding Version
1
+ # @morkaai/runtime
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The desktop runtime for Morka apps. It runs the app's Node.js backend and opens its desktop window in Electron.
4
+
5
+ From a generated app repository, use Node.js 24 or later and npm:
6
+
7
+ ```sh
8
+ npm ci
9
+ npm start
10
+ ```
11
+
12
+ The project's start script invokes `morka run`. Run `npm run install:app` to add the app to the current user's application menu.
13
+
14
+ [Morka documentation](https://github.com/mithrisys/morka#readme)
package/bin/morka.cjs ADDED
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ const { spawn } = require("node:child_process");
3
+ const { existsSync, realpathSync } = require("node:fs");
4
+ const { homedir } = require("node:os");
5
+ const { join, resolve } = require("node:path");
6
+ const { createRequire } = require("node:module");
7
+
8
+ async function main() {
9
+ const [command = "launcher", ...args] = process.argv.slice(2);
10
+ const installing = command === "install";
11
+ if (!["run", "launcher", "install"].includes(command) ||
12
+ args.length > (command === "launcher" ? 0 : 1) ||
13
+ (installing && args.length && args[0] !== "--open")) {
14
+ throw new Error("Usage: morka launcher | morka run [repository] | morka install [--open]");
15
+ }
16
+ const repository = resolve(command === "run" && args[0] || process.cwd());
17
+ const installed = existsSync(join(__dirname, "../dist/electron/main.js"));
18
+ const engine = resolve(__dirname, installed ? ".." : "../../..");
19
+ const local = createRequire(join(engine, "package.json"));
20
+ const { npmEntry } = local("./dist/project/toolchain.js");
21
+ const env = {
22
+ ...process.env,
23
+ MORKA_LOCAL_NODE: realpathSync(process.execPath),
24
+ MORKA_LOCAL_NPM: await npmEntry(process.execPath, process.env.npm_execpath),
25
+ MORKA_NPM_REPOSITORY: command === "launcher" ? "" : repository,
26
+ MORKA_INSTALL_APP: installing ? args.length ? "open" : "1" : "",
27
+ MORKA_NPM_KIT: process.env.MORKA_NPM_KIT ?? (installed
28
+ ? local("./dist/instances/repository.js").repositoryFile(repository, "npm") : join(engine, "dist", "npm")),
29
+ };
30
+ delete env.ELECTRON_RUN_AS_NODE;
31
+ let executable = local("electron");
32
+ if (command === "run" && process.platform === "darwin") {
33
+ const { readRelease, repositoryFile } = local("./dist/instances/repository.js");
34
+ const { prepareMacProjectExecutable } = local("./dist/instances/distribution.js");
35
+ const root = realpathSync(repository);
36
+ executable = await prepareMacProjectExecutable(executable, join(homedir(), "Library", "Application Support"),
37
+ root, readRelease(repositoryFile(root, "release.json")));
38
+ }
39
+ const child = spawn(executable, [engine], { stdio: "inherit", env, windowsHide: true });
40
+ const stop = () => child.kill();
41
+ process.once("SIGINT", stop);
42
+ process.once("SIGTERM", stop);
43
+ try {
44
+ process.exitCode = await new Promise((done, fail) => {
45
+ child.once("error", fail);
46
+ child.once("exit", (code, signal) => done(code ?? (signal === "SIGTERM" ? 0 : 1)));
47
+ });
48
+ } finally {
49
+ process.removeListener("SIGINT", stop);
50
+ process.removeListener("SIGTERM", stop);
51
+ }
52
+ }
53
+
54
+ main().catch(error => {
55
+ console.error(error.message);
56
+ process.exitCode = 1;
57
+ });
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ActionAccess = void 0;
4
+ const promises_1 = require("node:fs/promises");
5
+ const text_file_1 = require("../app-runtime/text-file");
6
+ class ActionAccess {
7
+ file;
8
+ constructor(file) {
9
+ this.file = file;
10
+ }
11
+ async read() {
12
+ const value = JSON.parse(await (0, promises_1.readFile)(this.file, "utf8").catch(error => {
13
+ if (error.code === "ENOENT")
14
+ return "{}";
15
+ throw error;
16
+ }));
17
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
18
+ }
19
+ async current() {
20
+ const { fixed, preferred } = await this.read();
21
+ return [...new Set([...(Array.isArray(fixed) ? fixed : []), preferred]
22
+ .filter((id) => id === "codex" || id === "claude"))];
23
+ }
24
+ async choose(action, prompt) {
25
+ const choices = action.chooseProvider ? ["codex", "claude"] : [action.provider];
26
+ if (!choices.every(id => id === "codex" || id === "claude")) {
27
+ throw new Error("This action needs a supported local provider.");
28
+ }
29
+ const { fixed, preferred } = await this.read();
30
+ const allowed = Array.isArray(fixed) ? fixed.filter(id => id === "codex" || id === "claude") : [];
31
+ if (action.chooseProvider && typeof preferred === "string" && choices.some(id => id === preferred))
32
+ return preferred;
33
+ if (!action.chooseProvider && allowed.some(id => id === action.provider))
34
+ return action.provider;
35
+ const chosen = await prompt(choices);
36
+ if (!chosen || !choices.some(id => id === chosen))
37
+ throw new Error("AI access was declined. Open AI setup to check your connection.");
38
+ await (0, text_file_1.writeTextAtomically)(this.file, JSON.stringify(action.chooseProvider
39
+ ? { fixed: allowed, preferred: chosen } : { fixed: [...allowed, chosen], preferred }));
40
+ return chosen;
41
+ }
42
+ clear() { return (0, text_file_1.writeTextAtomically)(this.file, "{}"); }
43
+ }
44
+ exports.ActionAccess = ActionAccess;
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.actionName = void 0;
7
+ exports.compileActions = compileActions;
8
+ const ajv_1 = __importDefault(require("ajv"));
9
+ exports.actionName = /^[a-z0-9][a-z0-9-]{0,62}$/;
10
+ function schema(value) {
11
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
12
+ }
13
+ function compileActions(files) {
14
+ const actions = new Map();
15
+ if (files["agents.json"] === undefined)
16
+ return actions;
17
+ try {
18
+ const definitions = JSON.parse(files["agents.json"]);
19
+ if (!Array.isArray(definitions) || definitions.length > 16)
20
+ throw new Error("agents.json must be an array of up to 16 actions.");
21
+ const ajv = new ajv_1.default();
22
+ for (const value of definitions) {
23
+ const { id, provider = "codex", skill, session, instructions, inputSchema, outputSchema } = value ?? {};
24
+ if (typeof id !== "string" || !exports.actionName.test(id) || actions.has(id)) {
25
+ throw new Error("Each action needs a unique lowercase id containing only letters, numbers or hyphens.");
26
+ }
27
+ const invalid = (reason) => { throw new Error(`Action "${id}": ${reason}`); };
28
+ if (typeof skill !== "string" || !exports.actionName.test(skill))
29
+ invalid('Set "skill" to the execution skill directory name.');
30
+ if (!files[`skills/${skill}/SKILL.md`])
31
+ invalid(`Missing ${skill}/SKILL.md in the registered skills directory.`);
32
+ if (session !== "ephemeral")
33
+ invalid('Set "session" to "ephemeral".');
34
+ if (typeof instructions !== "string" || !instructions.trim() || instructions.length > 4000) {
35
+ invalid('Provide non-empty "instructions" of at most 4000 characters.');
36
+ }
37
+ if (typeof provider !== "string" || !exports.actionName.test(provider) || !schema(inputSchema) || !schema(outputSchema)) {
38
+ invalid("Check provider, inputSchema and outputSchema.");
39
+ }
40
+ const unexpected = Object.keys(value).find(key => !["id", "provider", "skill", "session", "instructions", "inputSchema", "outputSchema"].includes(key));
41
+ if (unexpected)
42
+ invalid(`Unknown field "${unexpected}".`);
43
+ actions.set(id, { id, provider, chooseProvider: value.provider === undefined,
44
+ skill, instructions, outputSchema,
45
+ validateInput: ajv.compile(inputSchema), validateOutput: ajv.compile(outputSchema) });
46
+ }
47
+ return actions;
48
+ }
49
+ catch (error) {
50
+ throw new Error(`The agent definition in agents.json is invalid. ${error instanceof Error ? error.message : String(error)}`);
51
+ }
52
+ }
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AgentRunner = void 0;
4
+ const promises_1 = require("node:fs/promises");
5
+ const node_path_1 = require("node:path");
6
+ class AgentRunner {
7
+ directory;
8
+ registry;
9
+ authorize;
10
+ active;
11
+ constructor(directory, registry, authorize) {
12
+ this.directory = directory;
13
+ this.registry = registry;
14
+ this.authorize = authorize;
15
+ }
16
+ async run(addon, id, input) {
17
+ const action = typeof id === "string" ? addon.actions.get(id) : undefined;
18
+ if (!action)
19
+ throw new Error("The agent action was not found in the active project.");
20
+ if (!action.validateInput(input))
21
+ throw new Error("The agent action input does not match its schema.");
22
+ if (this.active)
23
+ throw new Error("An agent action is already running.");
24
+ const controller = new AbortController();
25
+ this.active = controller;
26
+ let timer;
27
+ let work;
28
+ try {
29
+ const provider = this.authorize ? await this.authorize(action) : action.provider;
30
+ const agent = this.registry.get(provider);
31
+ if (!agent.connection.runAction)
32
+ throw new Error(`${agent.info.name} does not support in-app AI actions.`);
33
+ timer = AbortSignal.timeout(90_000);
34
+ const signal = AbortSignal.any([controller.signal, timer]);
35
+ signal.throwIfAborted();
36
+ await (0, promises_1.mkdir)(this.directory, { recursive: true, mode: 0o700 });
37
+ work = await (0, promises_1.mkdtemp)((0, node_path_1.join)(this.directory, "run-"));
38
+ // Codex reports canonical skill paths, including for macOS temporary directories.
39
+ work = await (0, promises_1.realpath)(work);
40
+ const cwd = (0, node_path_1.join)(work, "workspace");
41
+ const skills = (0, node_path_1.join)(work, "skills");
42
+ const skill = (0, node_path_1.join)(skills, action.skill);
43
+ await (0, promises_1.mkdir)(cwd);
44
+ await (0, promises_1.mkdir)(skill, { recursive: true });
45
+ await (0, promises_1.writeFile)((0, node_path_1.join)(skill, "SKILL.md"), addon.agentFiles[`skills/${action.skill}/SKILL.md`], "utf8");
46
+ signal.throwIfAborted();
47
+ const reply = await agent.connection.runAction({ cwd, skillRoot: skills, skill: action.skill,
48
+ text: `${action.instructions}\n\nInputs (JSON):\n${JSON.stringify(input)}`, schema: action.outputSchema, signal });
49
+ const result = JSON.parse(reply);
50
+ if (!action.validateOutput(result))
51
+ throw new Error("The agent action output does not match its schema.");
52
+ return result;
53
+ }
54
+ catch (error) {
55
+ if (timer?.aborted)
56
+ throw new Error("The agent action timed out. Try again.");
57
+ throw error;
58
+ }
59
+ finally {
60
+ if (work)
61
+ await (0, promises_1.rm)(work, { recursive: true, force: true }).catch(console.error);
62
+ this.active = undefined;
63
+ }
64
+ }
65
+ close() {
66
+ this.active?.abort();
67
+ }
68
+ }
69
+ exports.AgentRunner = AgentRunner;
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.localAccount = localAccount;
4
+ const node_child_process_1 = require("node:child_process");
5
+ const node_os_1 = require("node:os");
6
+ const process_1 = require("./process");
7
+ const providers = {
8
+ codex: { install: "npm install -g @openai/codex", login: "codex login", status: ["login", "status"] },
9
+ claude: { install: "npm install -g @anthropic-ai/claude-code", login: "claude auth login", status: ["auth", "status", "--json"] },
10
+ };
11
+ async function localAccount(provider) {
12
+ const { install, login, status } = providers[provider];
13
+ try {
14
+ const cli = await (0, process_1.agentLaunch)(provider, status);
15
+ return await new Promise(resolve => {
16
+ (0, node_child_process_1.execFile)(cli.command, cli.args, { cwd: (0, node_os_1.homedir)(), env: cli.env, timeout: 8000, maxBuffer: 64 * 1024, windowsHide: true }, (error, stdout, stderr) => {
17
+ let state = "unavailable";
18
+ if (provider === "codex") {
19
+ const message = stdout + "\n" + stderr;
20
+ if (!error && /\blogged in\b/i.test(message))
21
+ state = "ready";
22
+ else if (/\bnot logged in\b/i.test(message))
23
+ state = "signed-out";
24
+ }
25
+ else {
26
+ try {
27
+ const { loggedIn } = JSON.parse(stdout);
28
+ if (loggedIn === true && !error)
29
+ state = "ready";
30
+ else if (loggedIn === false)
31
+ state = "signed-out";
32
+ }
33
+ catch { /* Keep the status unavailable when the CLI does not return valid JSON. */ }
34
+ }
35
+ resolve({ state, install, login });
36
+ });
37
+ });
38
+ }
39
+ catch {
40
+ return { state: "missing", install, login };
41
+ }
42
+ }
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.spawnAcp = spawnAcp;
4
+ exports.stopAgent = stopAgent;
5
+ const node_child_process_1 = require("node:child_process");
6
+ const node_crypto_1 = require("node:crypto");
7
+ const node_fs_1 = require("node:fs");
8
+ const promises_1 = require("node:fs/promises");
9
+ const node_os_1 = require("node:os");
10
+ const node_path_1 = require("node:path");
11
+ const files_1 = require("../project/files");
12
+ const process_1 = require("./process");
13
+ async function findExecutable(command) {
14
+ const paths = (0, node_path_1.isAbsolute)(command) ? [command] : (0, process_1.agentPath)().split(node_path_1.delimiter).filter(node_path_1.isAbsolute).map(path => (0, node_path_1.join)(path, command));
15
+ for (const path of paths) {
16
+ if (await (0, promises_1.access)(path, node_fs_1.constants.X_OK).then(() => true, () => false))
17
+ return path;
18
+ }
19
+ throw new Error(`Agent executable not found: ${command}.`);
20
+ }
21
+ async function hermesScope(state, draft, catalog) {
22
+ const root = (0, node_path_1.join)(state, ".hermes");
23
+ const hash = (value) => (0, node_crypto_1.createHash)("sha256").update(value).digest("hex").slice(0, 16);
24
+ const name = catalog ? "catalog" : hash(draft);
25
+ const scopes = (0, node_path_1.join)(state, "hermes-workspaces");
26
+ const home = (0, node_path_1.join)(scopes, name);
27
+ for (const folder of [root, scopes, home]) {
28
+ await (0, promises_1.mkdir)(folder, { mode: 0o700 }).catch((error) => {
29
+ if (error.code !== "EEXIST")
30
+ throw error;
31
+ });
32
+ if (!(await (0, files_1.info)(folder))?.isDirectory())
33
+ throw new Error("Invalid Hermes profile directory.");
34
+ }
35
+ // Hermes shares a gateway across named profiles in a root. Each workspace
36
+ // needs its own root so the gateway inherits that workspace's write sandbox.
37
+ for (const file of ["config.yaml", ".env", "auth.json"]) {
38
+ const source = (0, node_path_1.join)(root, file);
39
+ const destination = (0, node_path_1.join)(home, file);
40
+ const from = await (0, files_1.info)(source);
41
+ const to = await (0, files_1.info)(destination);
42
+ if (from?.isFile() && (!to || (to.isFile() && from.mtimeMs > to.mtimeMs)))
43
+ await (0, promises_1.copyFile)(source, destination);
44
+ }
45
+ const sockets = (0, node_path_1.join)("/private/tmp", "morka-acp-" + hash(home));
46
+ await (0, promises_1.mkdir)(sockets, { mode: 0o700 }).catch((error) => {
47
+ if (error.code !== "EEXIST")
48
+ throw error;
49
+ });
50
+ const socketDir = await (0, files_1.info)(sockets);
51
+ if (!socketDir?.isDirectory() || socketDir.uid !== process.getuid?.() || (socketDir.mode & 0o077)) {
52
+ throw new Error("The Hermes control socket requires a private directory.");
53
+ }
54
+ return { home, sockets };
55
+ }
56
+ async function spawnAcp(profile, workspace, statePath, projectRoot, purpose = "chat", attachmentPaths = []) {
57
+ if (process.platform !== "darwin")
58
+ throw new Error("This build requires macOS to run ACP agents.");
59
+ const home = await (0, promises_1.realpath)((0, node_os_1.homedir)());
60
+ const executable = await findExecutable(profile.command);
61
+ const binary = await (0, promises_1.realpath)(executable);
62
+ const draft = await (0, promises_1.realpath)(workspace);
63
+ const privateName = "home";
64
+ await (0, promises_1.mkdir)((0, node_path_1.join)(statePath, privateName, "tmp"), { recursive: true, mode: 0o700 });
65
+ const state = await (0, promises_1.realpath)((0, node_path_1.join)(statePath, privateName));
66
+ const hermes = profile.id === "hermes" ? await hermesScope(state, draft, purpose === "catalog") : undefined;
67
+ const writable = [state, draft, ...(hermes ? [hermes.sockets] : [])];
68
+ const allowed = [...writable, ...profile.readPaths ?? [], ...attachmentPaths];
69
+ const readable = (await Promise.all(allowed.map(path => (0, promises_1.realpath)(path).catch(() => undefined))))
70
+ .filter((path) => Boolean(path && path !== "/" && path !== home));
71
+ const subpath = (path) => `(subpath ${JSON.stringify(path)})`;
72
+ const literal = (path) => `(literal ${JSON.stringify(path)})`;
73
+ const ancestors = new Set([home]);
74
+ for (const path of [...readable, executable, binary]) {
75
+ for (let parent = (0, node_path_1.dirname)(path); parent.startsWith(home + "/"); parent = (0, node_path_1.dirname)(parent)) {
76
+ ancestors.add(parent);
77
+ }
78
+ }
79
+ const draftSettings = files_1.agentConfigNames.map(name => subpath((0, node_path_1.join)(draft, name))).join(" ");
80
+ const rules = [
81
+ "(version 1)",
82
+ "(allow default)",
83
+ `(deny file-read* ${subpath(home)})`,
84
+ `(allow file-read-metadata ${[...ancestors].map(literal).join(" ")})`,
85
+ `(allow file-read* ${[...readable.map(subpath), literal(executable), literal(binary)].join(" ")})`,
86
+ `(deny file-read* ${subpath(projectRoot)} ${draftSettings})`,
87
+ "(deny file-write*)",
88
+ `(allow file-write* ${writable.map(subpath).join(" ")} ${literal("/dev/null")})`,
89
+ `(deny file-write* ${subpath(projectRoot)} ${draftSettings})`,
90
+ ].join("\n");
91
+ const forwarded = Object.fromEntries(["ANTHROPIC_API_KEY", "OPENAI_API_KEY", "OPENROUTER_API_KEY", "GEMINI_API_KEY",
92
+ "GOOGLE_API_KEY", "DEEPSEEK_API_KEY", "USER", "LOGNAME", "LANG", "LC_ALL", "TERM"]
93
+ .flatMap(name => process.env[name] ? [[name, process.env[name]]] : []));
94
+ return (0, node_child_process_1.spawn)("/usr/bin/sandbox-exec", ["-p", rules, executable, ...profile.args], {
95
+ cwd: draft,
96
+ env: {
97
+ ...forwarded, ...profile.env, HOME: state,
98
+ PATH: [profile.env?.PATH, (0, process_1.agentPath)()].filter(Boolean).join(node_path_1.delimiter), TMPDIR: (0, node_path_1.join)(state, "tmp"),
99
+ XDG_CONFIG_HOME: (0, node_path_1.join)(state, ".config"), XDG_DATA_HOME: (0, node_path_1.join)(state, ".local/share"),
100
+ XDG_STATE_HOME: (0, node_path_1.join)(state, ".local/state"), XDG_CACHE_HOME: (0, node_path_1.join)(state, ".cache"),
101
+ HERMES_HOME: hermes?.home ?? (0, node_path_1.join)(state, ".hermes"), PI_CODING_AGENT_DIR: (0, node_path_1.join)(state, ".pi/agent"),
102
+ ...(hermes ? { XDG_RUNTIME_DIR: hermes.sockets } : {}),
103
+ },
104
+ stdio: ["pipe", "pipe", "pipe"],
105
+ detached: true,
106
+ });
107
+ }
108
+ function stopAgent(pid, signal = "SIGTERM") {
109
+ if (!pid)
110
+ return;
111
+ try {
112
+ process.kill(-pid, signal);
113
+ }
114
+ catch (error) {
115
+ if (error.code !== "ESRCH")
116
+ throw error;
117
+ }
118
+ }
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.activityStatus = activityStatus;
4
+ exports.toolActivity = toolActivity;
5
+ const node_path_1 = require("node:path");
6
+ function activityStatus(status) {
7
+ if (["completed", "success", "succeeded"].includes(status ?? ""))
8
+ return "completed";
9
+ if (["failed", "error", "declined"].includes(status ?? ""))
10
+ return "failed";
11
+ if (["cancelled", "canceled", "interrupted"].includes(status ?? ""))
12
+ return "stopped";
13
+ return "running";
14
+ }
15
+ function toolActivity(name, input, status, output) {
16
+ const values = input && typeof input === "object" ? input : {};
17
+ const path = [values.file_path, values.path, values.filename].find(value => typeof value === "string");
18
+ const kind = /read|view|open/i.test(name) ? "read" : /edit|write|patch/i.test(name) ? "edit"
19
+ : /search|grep|glob|find/i.test(name) ? "search" : /command|bash|terminal|exec/i.test(name) ? "command"
20
+ : /plan/i.test(name) ? "plan" : "tool";
21
+ const labels = { read: "Read", edit: "Edit", search: "Search", command: "Run", plan: "Plan", tool: name };
22
+ const target = path ? (0, node_path_1.basename)(path) : [values.pattern, values.query, values.command].find(value => typeof value === "string");
23
+ const title = (labels[kind] + (target ? ` · ${target}` : "")).slice(0, 180);
24
+ const detail = [input === undefined ? undefined : JSON.stringify(input, null, 2), output].filter(Boolean).join("\n\n").slice(-32_000);
25
+ return { kind, status, title, detail: detail || undefined };
26
+ }
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AttachmentStore = void 0;
4
+ exports.attachmentContext = attachmentContext;
5
+ const node_fs_1 = require("node:fs");
6
+ const node_crypto_1 = require("node:crypto");
7
+ const promises_1 = require("node:fs/promises");
8
+ const node_path_1 = require("node:path");
9
+ const ignored = new Set([".git", "node_modules", ".DS_Store"]);
10
+ const imageTypes = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif" };
11
+ class AttachmentStore {
12
+ directory;
13
+ constructor(directory) {
14
+ this.directory = directory;
15
+ }
16
+ async import(paths) {
17
+ const imported = [];
18
+ try {
19
+ for (const path of [...new Set(paths)])
20
+ imported.push(await this.copy(path));
21
+ return imported;
22
+ }
23
+ catch (error) {
24
+ for (const attachment of imported)
25
+ await (0, promises_1.rm)((0, node_path_1.join)(this.directory, attachment.id), { recursive: true, force: true });
26
+ throw error;
27
+ }
28
+ }
29
+ async copy(source) {
30
+ const root = await (0, promises_1.realpath)(source);
31
+ const info = await (0, promises_1.lstat)(root);
32
+ if (!info.isFile() && !info.isDirectory())
33
+ throw new Error("Choose a regular file or folder.");
34
+ const id = (0, node_crypto_1.randomUUID)();
35
+ const directory = (0, node_path_1.join)(this.directory, id);
36
+ const stage = directory + ".pending";
37
+ const name = (0, node_path_1.basename)(root);
38
+ const files = [];
39
+ let size = 0;
40
+ let omitted = 0;
41
+ await (0, promises_1.mkdir)((0, node_path_1.join)(stage, "content"), { recursive: true, mode: 0o700 });
42
+ const copy = async (path, relative) => {
43
+ const stat = await (0, promises_1.lstat)(path);
44
+ if (stat.isSymbolicLink()) {
45
+ omitted++;
46
+ return;
47
+ }
48
+ if (stat.isDirectory()) {
49
+ await (0, promises_1.mkdir)((0, node_path_1.join)(stage, "content", relative), { recursive: true, mode: 0o700 });
50
+ for (const entry of await (0, promises_1.readdir)(path)) {
51
+ if (ignored.has(entry)) {
52
+ omitted++;
53
+ continue;
54
+ }
55
+ await copy((0, node_path_1.join)(path, entry), relative + "/" + entry);
56
+ }
57
+ }
58
+ else if (stat.isFile()) {
59
+ size += stat.size;
60
+ if (files.length >= 4000 || size > 96 * 1024 * 1024)
61
+ throw new Error(`The attachment ${name} exceeds 4,000 files or 96 MB.`);
62
+ const target = (0, node_path_1.join)(stage, "content", relative);
63
+ await (0, promises_1.mkdir)((0, node_path_1.dirname)(target), { recursive: true, mode: 0o700 });
64
+ await (0, promises_1.copyFile)(path, target, node_fs_1.constants.COPYFILE_FICLONE);
65
+ await (0, promises_1.chmod)(target, 0o400);
66
+ files.push({ name: relative, size: stat.size });
67
+ }
68
+ };
69
+ try {
70
+ await copy(root, name);
71
+ if (info.isDirectory())
72
+ await (0, promises_1.mkdir)((0, node_path_1.join)(stage, "content", name), { recursive: true, mode: 0o700 });
73
+ const metadata = { id, name, kind: info.isDirectory() ? "folder" : "file", size, fileCount: files.length, omitted, files };
74
+ await (0, promises_1.writeFile)((0, node_path_1.join)(stage, "metadata.json"), JSON.stringify(metadata), { mode: 0o600 });
75
+ await (0, promises_1.rename)(stage, directory);
76
+ const { files: _files, ...attachment } = metadata;
77
+ return attachment;
78
+ }
79
+ finally {
80
+ await (0, promises_1.rm)(stage, { recursive: true, force: true });
81
+ }
82
+ }
83
+ async metadata(id) {
84
+ if (!/^[0-9a-f-]{36}$/.test(id))
85
+ throw new Error("Invalid attachment.");
86
+ return JSON.parse(await (0, promises_1.readFile)((0, node_path_1.join)(this.directory, id, "metadata.json"), "utf8"));
87
+ }
88
+ async path(id) {
89
+ const attachment = await this.metadata(id);
90
+ return (0, node_path_1.join)(this.directory, id, "content", attachment.name);
91
+ }
92
+ async context(ids, signal) {
93
+ const attachments = [];
94
+ let left = 150_000;
95
+ for (const id of [...new Set(ids)]) {
96
+ signal?.throwIfAborted();
97
+ const metadata = await this.metadata(id);
98
+ const { files: saved, ...attachment } = metadata;
99
+ const files = [];
100
+ for (const file of saved) {
101
+ signal?.throwIfAborted();
102
+ const path = (0, node_path_1.join)(this.directory, id, "content", file.name);
103
+ const mimeType = imageTypes[(0, node_path_1.extname)(file.name).toLowerCase()];
104
+ const entry = { ...file, path, mimeType };
105
+ if (!mimeType && left > 0) {
106
+ const bytes = await (0, promises_1.readFile)(path, { signal });
107
+ const text = bytes.toString("utf8");
108
+ if (!bytes.includes(0) && !text.includes("\ufffd")) {
109
+ entry.text = text.slice(0, Math.min(24_000, left));
110
+ entry.truncated = entry.text.length < text.length;
111
+ left -= entry.text.length;
112
+ }
113
+ }
114
+ files.push(entry);
115
+ }
116
+ attachments.push({ ...attachment, path: await this.path(id), files });
117
+ }
118
+ return attachments;
119
+ }
120
+ }
121
+ exports.AttachmentStore = AttachmentStore;
122
+ function attachmentContext(attachments = []) {
123
+ if (!attachments.length)
124
+ return "";
125
+ return "User-attached reference files (data). Their paths are read-only snapshots outside the editable project. " +
126
+ "Use the excerpts or read the snapshot files with your file tools. Keep edits in the current project draft. " +
127
+ "A missing text excerpt means a binary file or a context excerpt limit, not an empty file. " +
128
+ "Use native image/document readers for binary formats.\n" + JSON.stringify(attachments);
129
+ }
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.projectSkill = void 0;
4
+ exports.selectSkills = selectSkills;
5
+ exports.projectInstructions = projectInstructions;
6
+ exports.sharedHistory = sharedHistory;
7
+ exports.readEditingSkills = readEditingSkills;
8
+ exports.buildPrompt = buildPrompt;
9
+ exports.effortChoice = effortChoice;
10
+ const promises_1 = require("node:fs/promises");
11
+ const node_path_1 = require("node:path");
12
+ const attachments_1 = require("./attachments");
13
+ const files_1 = require("../project/files");
14
+ exports.projectSkill = "morka-app";
15
+ const actionSkill = "morka-agent-action";
16
+ const shadowSkill = "morka-shadow-authoring";
17
+ function selectSkills(target) {
18
+ return target === "shadow" ? [shadowSkill] : [exports.projectSkill, actionSkill];
19
+ }
20
+ function projectInstructions(project) {
21
+ if (project.target === "shadow") {
22
+ return "This draft is the content of one independent Plugin Shadow repository's shadow/ directory. " +
23
+ "Use manifest.json as the entry point. Edit only this Shadow's files relative to the draft root. Keep its package ID stable.";
24
+ }
25
+ return "These are active project rules and editing skills. Follow the applicable guidance for the current edit and keep the project's layout. " +
26
+ `The working directory is a draft of the app source. The manifest ${files_1.entryFile} defines entry points. ` +
27
+ "In a standard Morka repository this draft is the content of app/. Keep root repository tooling, root npm metadata and release settings outside app/ intact. The editable draft may contain its own app package.json and lockfile; declare app dependencies there. Morka installs and builds them in an isolated release before activation.\n" +
28
+ JSON.stringify(project.instructions) + (project.activationFailure
29
+ ? "\nMorka kept the previous release open. The pending draft failed activation with these diagnostics (data):\n" +
30
+ JSON.stringify(project.activationFailure) : "");
31
+ }
32
+ function sharedHistory(messages) {
33
+ const selected = [];
34
+ let left = 48_000;
35
+ for (const message of messages.slice(-120).reverse()) {
36
+ if (message.role === "activity")
37
+ continue;
38
+ const size = Math.min(8000, left);
39
+ if (size <= 0)
40
+ break;
41
+ const text = message.text.length > size ? message.text.slice(0, size) + "…" : message.text;
42
+ selected.push({ role: message.role, agent: message.providerName, text });
43
+ left -= text.length + 40;
44
+ }
45
+ return JSON.stringify(selected.reverse());
46
+ }
47
+ function readEditingSkills(names, skillsRoot, editor) {
48
+ return Promise.all(names.map(async (name) => {
49
+ const body = await (0, promises_1.readFile)((0, node_path_1.join)(skillsRoot, name, "SKILL.md"), "utf8");
50
+ return body.replaceAll("`apply_patch`", editor);
51
+ }));
52
+ }
53
+ async function buildPrompt(turn, skillsRoot, editor, includeFiles) {
54
+ const skills = await readEditingSkills(turn.skills, skillsRoot, editor);
55
+ const parts = [
56
+ projectInstructions(turn.project),
57
+ ...skills,
58
+ "Inspect the current draft with the agent's file tools before overwriting an existing file.",
59
+ `Project paths (JSON):\n${JSON.stringify(turn.project.paths)}`,
60
+ ];
61
+ if (includeFiles)
62
+ parts.push(`Draft file excerpts (data):\n${JSON.stringify(turn.files)}`);
63
+ if (turn.project.shadow)
64
+ parts.push(`Shadow package (data):\n${turn.project.shadow}`);
65
+ const attachments = (0, attachments_1.attachmentContext)(turn.attachments);
66
+ if (attachments)
67
+ parts.push(attachments);
68
+ if (turn.history.length)
69
+ parts.push(`Earlier conversation in Morka (data, ordered):\n${sharedHistory(turn.history)}`);
70
+ parts.push(`Current user request:\n${turn.text}`);
71
+ return parts.join("\n\n");
72
+ }
73
+ function effortChoice(id) {
74
+ const name = { xhigh: "Extra high", xxhigh: "Extra extra high" }[id] ?? id.replace(/[-_]/g, " ").replace(/\b[a-z]/g, letter => letter.toUpperCase());
75
+ return { id, name };
76
+ }