@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.
- package/LICENSE +21 -0
- package/README.md +13 -2
- package/bin/morka.cjs +57 -0
- package/dist/agent-actions/access.js +44 -0
- package/dist/agent-actions/manifest.js +52 -0
- package/dist/agent-actions/runner.js +69 -0
- package/dist/agents/account.js +42 -0
- package/dist/agents/acp-sandbox.js +118 -0
- package/dist/agents/activity.js +26 -0
- package/dist/agents/attachments.js +129 -0
- package/dist/agents/context.js +76 -0
- package/dist/agents/contracts.js +2 -0
- package/dist/agents/process.js +61 -0
- package/dist/agents/providers/acp.js +411 -0
- package/dist/agents/providers/claude.js +180 -0
- package/dist/agents/providers/codex.js +416 -0
- package/dist/agents/registry.js +76 -0
- package/dist/agents/sessions.js +331 -0
- package/dist/app-runtime/bridge.js +40 -0
- package/dist/app-runtime/starter/agents.json +1 -0
- package/dist/app-runtime/starter/index.html +11 -0
- package/dist/app-runtime/starter/main.js +0 -0
- package/dist/app-runtime/starter/package-lock.json +13 -0
- package/dist/app-runtime/starter/package.json +9 -0
- package/dist/app-runtime/starter/server.mjs +20 -0
- package/dist/app-runtime/starter/styles.css +0 -0
- package/dist/app-runtime/text-file.js +18 -0
- package/dist/branding/Morka.icns +0 -0
- package/dist/branding/README.md +24 -0
- package/dist/branding/generated-app-icon.png +0 -0
- package/dist/branding/morka-icon.png +0 -0
- package/dist/branding/morka-logo.png +0 -0
- package/dist/electron/main.js +802 -0
- package/dist/electron/preload.js +51 -0
- package/dist/instances/desktop.js +223 -0
- package/dist/instances/distribution.js +240 -0
- package/dist/instances/macos.js +62 -0
- package/dist/instances/repository.js +183 -0
- package/dist/instances/shadow-repository.js +95 -0
- package/dist/project/app-proxy.js +325 -0
- package/dist/project/bundle-toolchain.js +35 -0
- package/dist/project/drafts.js +27 -0
- package/dist/project/files.js +176 -0
- package/dist/project/live-preview.js +198 -0
- package/dist/project/managed-runtime.js +324 -0
- package/dist/project/node-lifecycle.js +45 -0
- package/dist/project/packages.js +302 -0
- package/dist/project/page-state.js +198 -0
- package/dist/project/project.js +112 -0
- package/dist/project/shadow-effects.js +156 -0
- package/dist/project/shadows.js +122 -0
- package/dist/project/toolchain.js +216 -0
- package/dist/renderer/activity.js +91 -0
- package/dist/renderer/app-setup.js +126 -0
- package/dist/renderer/chat-tools.css +83 -0
- package/dist/renderer/highlight.css +118 -0
- package/dist/renderer/icons/attach.png +0 -0
- package/dist/renderer/icons/brain-weight.png +0 -0
- package/dist/renderer/icons/brain.png +0 -0
- package/dist/renderer/icons/chat.png +0 -0
- package/dist/renderer/icons/chevron.png +0 -0
- package/dist/renderer/icons/clone.png +0 -0
- package/dist/renderer/icons/close.png +0 -0
- package/dist/renderer/icons/document.png +0 -0
- package/dist/renderer/icons/edit.png +0 -0
- package/dist/renderer/icons/folder.png +0 -0
- package/dist/renderer/icons/import.png +0 -0
- package/dist/renderer/icons/open-folder.png +0 -0
- package/dist/renderer/icons/play.png +0 -0
- package/dist/renderer/icons/plus.png +0 -0
- package/dist/renderer/icons/remove.png +0 -0
- package/dist/renderer/icons/search.png +0 -0
- package/dist/renderer/icons/send.png +0 -0
- package/dist/renderer/icons/shadow.png +0 -0
- package/dist/renderer/icons/stop.png +0 -0
- package/dist/renderer/icons/terminal.png +0 -0
- package/dist/renderer/index.html +130 -0
- package/dist/renderer/launcher/OFL.txt +93 -0
- package/dist/renderer/launcher/cell.js +322 -0
- package/dist/renderer/launcher/launcher.css +79 -0
- package/dist/renderer/launcher/lexend-caption-bold.ttf +0 -0
- package/dist/renderer/launcher.html +23 -0
- package/dist/renderer/licenses/dompurify.txt +202 -0
- package/dist/renderer/licenses/github-slugger.txt +5 -0
- package/dist/renderer/licenses/highlight.js.txt +29 -0
- package/dist/renderer/licenses/marked-footnote.txt +21 -0
- package/dist/renderer/licenses/marked-gfm-heading-id.txt +21 -0
- package/dist/renderer/licenses/marked.txt +44 -0
- package/dist/renderer/markdown.css +43 -0
- package/dist/renderer/markdown.js +74 -0
- package/dist/renderer/renderer.js +18902 -0
- package/dist/renderer/styles.css +351 -0
- package/dist/skills/morka-agent-action/SKILL.md +39 -0
- package/dist/skills/morka-app/SKILL.md +36 -0
- package/dist/skills/morka-shadow-authoring/SKILL.md +32 -0
- package/package.json +30 -4
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.agentPath = agentPath;
|
|
4
|
+
exports.agentLaunch = agentLaunch;
|
|
5
|
+
const promises_1 = require("node:fs/promises");
|
|
6
|
+
const node_os_1 = require("node:os");
|
|
7
|
+
const node_path_1 = require("node:path");
|
|
8
|
+
function agentPath() {
|
|
9
|
+
const paths = (process.env.PATH || process.env.Path || "").split(node_path_1.delimiter)
|
|
10
|
+
.filter(path => (0, node_path_1.isAbsolute)(path) && !((0, node_path_1.basename)(path) === ".bin" && (0, node_path_1.basename)((0, node_path_1.dirname)(path)) === "node_modules"));
|
|
11
|
+
const defaults = process.platform === "win32"
|
|
12
|
+
? [(0, node_path_1.join)((0, node_os_1.homedir)(), ".local", "bin"), process.env.APPDATA && (0, node_path_1.join)(process.env.APPDATA, "npm"),
|
|
13
|
+
process.env.LOCALAPPDATA && (0, node_path_1.join)(process.env.LOCALAPPDATA, "Microsoft", "WinGet", "Links")]
|
|
14
|
+
: [(0, node_path_1.join)((0, node_os_1.homedir)(), ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"];
|
|
15
|
+
return [...new Set([...paths, ...defaults.filter(Boolean)])].join(node_path_1.delimiter);
|
|
16
|
+
}
|
|
17
|
+
const packages = {
|
|
18
|
+
codex: ["@openai", "codex", "bin", "codex.js"],
|
|
19
|
+
claude: ["@anthropic-ai", "claude-code", "cli.js"],
|
|
20
|
+
};
|
|
21
|
+
async function agentLaunch(provider, args) {
|
|
22
|
+
const override = process.env[provider === "codex" ? "CODEX_BIN" : "CLAUDE_BIN"];
|
|
23
|
+
const windows = process.platform === "win32";
|
|
24
|
+
const path = agentPath();
|
|
25
|
+
const env = { ...process.env, PATH: path };
|
|
26
|
+
if (windows)
|
|
27
|
+
delete env.Path;
|
|
28
|
+
const paths = path.split(node_path_1.delimiter).filter(Boolean);
|
|
29
|
+
const executable = override || provider;
|
|
30
|
+
const candidates = (0, node_path_1.isAbsolute)(executable) ? [executable] : paths.map(directory => (0, node_path_1.join)(directory, executable));
|
|
31
|
+
const exists = (file) => (0, promises_1.access)(file).then(() => true, () => false);
|
|
32
|
+
for (const candidate of candidates) {
|
|
33
|
+
if (!windows) {
|
|
34
|
+
if (await exists(candidate))
|
|
35
|
+
return { command: candidate, args, env };
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
const extension = (0, node_path_1.extname)(candidate).toLowerCase();
|
|
39
|
+
const native = extension ? candidate : candidate + ".exe";
|
|
40
|
+
if ((!extension || extension === ".exe" || extension === ".com") && await exists(native)) {
|
|
41
|
+
return { command: native, args, env };
|
|
42
|
+
}
|
|
43
|
+
// npm's .cmd wrappers require a command shell. Run the known JavaScript
|
|
44
|
+
// entry point directly so project paths and prompts stay literal arguments.
|
|
45
|
+
if (extension !== ".js" && extension !== "" && extension !== ".cmd" && extension !== ".bat")
|
|
46
|
+
continue;
|
|
47
|
+
if (extension !== ".js" && !(await exists(extension ? candidate : candidate + ".cmd")))
|
|
48
|
+
continue;
|
|
49
|
+
const directory = (0, node_path_1.dirname)(candidate);
|
|
50
|
+
const modules = (0, node_path_1.basename)(directory) === ".bin" ? (0, node_path_1.dirname)(directory) : (0, node_path_1.join)(directory, "node_modules");
|
|
51
|
+
const entry = extension === ".js" ? candidate : (0, node_path_1.join)(modules, ...packages[provider]);
|
|
52
|
+
if (!(await exists(entry)))
|
|
53
|
+
continue;
|
|
54
|
+
for (const node of [process.env.MORKA_LOCAL_NODE, ...paths.map(directory => (0, node_path_1.join)(directory, "node.exe"))]) {
|
|
55
|
+
if (node && (0, node_path_1.isAbsolute)(node) && await exists(node))
|
|
56
|
+
return { command: node, args: [entry, ...args], env };
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const name = provider === "codex" ? "Codex" : "Claude Code";
|
|
60
|
+
throw new Error(`${name} was not found. Open AI setup or set ${provider === "codex" ? "CODEX_BIN" : "CLAUDE_BIN"} to the CLI path.`);
|
|
61
|
+
}
|
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AcpConnection = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const promises_1 = require("node:fs/promises");
|
|
6
|
+
const node_path_1 = require("node:path");
|
|
7
|
+
const node_readline_1 = require("node:readline");
|
|
8
|
+
const node_url_1 = require("node:url");
|
|
9
|
+
const promises_2 = require("node:timers/promises");
|
|
10
|
+
const text_file_1 = require("../../app-runtime/text-file");
|
|
11
|
+
const files_1 = require("../../project/files");
|
|
12
|
+
const context_1 = require("../context");
|
|
13
|
+
const acp_sandbox_1 = require("../acp-sandbox");
|
|
14
|
+
const activity_1 = require("../activity");
|
|
15
|
+
class AcpError extends Error {
|
|
16
|
+
code;
|
|
17
|
+
details;
|
|
18
|
+
constructor(code, message, details) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.code = code;
|
|
21
|
+
this.details = details;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function config(setup, category) {
|
|
25
|
+
return setup.configOptions?.find(item => item.category === category && Array.isArray(item.options));
|
|
26
|
+
}
|
|
27
|
+
function choices(option) {
|
|
28
|
+
return (option?.options ?? []).flatMap(value => "options" in value ? value.options : [value])
|
|
29
|
+
.map(value => ({ id: value.value, name: value.name }));
|
|
30
|
+
}
|
|
31
|
+
class AcpProcess {
|
|
32
|
+
child;
|
|
33
|
+
turn;
|
|
34
|
+
updateConfig;
|
|
35
|
+
pending = new Map();
|
|
36
|
+
nextId = 0;
|
|
37
|
+
failure;
|
|
38
|
+
stderr = "";
|
|
39
|
+
session;
|
|
40
|
+
replyId = (0, node_crypto_1.randomUUID)();
|
|
41
|
+
exited;
|
|
42
|
+
closed = false;
|
|
43
|
+
tools = new Map();
|
|
44
|
+
constructor(child, turn, updateConfig) {
|
|
45
|
+
this.child = child;
|
|
46
|
+
this.turn = turn;
|
|
47
|
+
this.updateConfig = updateConfig;
|
|
48
|
+
child.stderr.setEncoding("utf8").on("data", text => { this.stderr = (this.stderr + text).slice(-2000); });
|
|
49
|
+
child.on("error", error => this.fail(error));
|
|
50
|
+
child.stdin.on("error", error => this.fail(error));
|
|
51
|
+
this.exited = new Promise(resolve => child.once("close", code => {
|
|
52
|
+
this.closed = true;
|
|
53
|
+
this.fail(new Error(this.stderr.trim() || `The ACP connection closed (${code}).`));
|
|
54
|
+
resolve();
|
|
55
|
+
}));
|
|
56
|
+
(0, node_readline_1.createInterface)({ input: child.stdout, crlfDelay: Infinity }).on("line", line => {
|
|
57
|
+
try {
|
|
58
|
+
this.receive(JSON.parse(line));
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
this.fail(new Error("The ACP response is not valid JSON-RPC."));
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
write(message) {
|
|
66
|
+
if (!this.failure)
|
|
67
|
+
this.child.stdin.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\n");
|
|
68
|
+
}
|
|
69
|
+
request(method, params, timeout = 25_000) {
|
|
70
|
+
if (this.failure)
|
|
71
|
+
return Promise.reject(this.failure);
|
|
72
|
+
return new Promise((resolve, reject) => {
|
|
73
|
+
const id = ++this.nextId;
|
|
74
|
+
const timer = setTimeout(() => this.fail(new Error(`The ACP agent did not respond to ${method}.${this.stderr.trim() ? "\n" + this.stderr.trim() : ""}`)), timeout);
|
|
75
|
+
this.pending.set(id, {
|
|
76
|
+
resolve: result => { clearTimeout(timer); resolve(result); },
|
|
77
|
+
reject: error => { clearTimeout(timer); reject(error); },
|
|
78
|
+
});
|
|
79
|
+
this.write({ id, method, params });
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
async prompt(id, prompt, images = false) {
|
|
83
|
+
this.session = id;
|
|
84
|
+
const signal = this.turn.signal;
|
|
85
|
+
let timeout;
|
|
86
|
+
const cancel = () => {
|
|
87
|
+
this.write({ method: "session/cancel", params: { sessionId: id } });
|
|
88
|
+
timeout ??= setTimeout(() => this.fail(new Error("The ACP turn was stopped.")), 1500);
|
|
89
|
+
};
|
|
90
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
91
|
+
try {
|
|
92
|
+
signal.throwIfAborted();
|
|
93
|
+
const content = [{ type: "text", text: prompt }];
|
|
94
|
+
for (const attachment of this.turn.attachments ?? []) {
|
|
95
|
+
for (const file of attachment.files) {
|
|
96
|
+
content.push({ type: "resource_link", name: file.name, uri: (0, node_url_1.pathToFileURL)(file.path).href, ...(file.mimeType ? { mimeType: file.mimeType } : {}) });
|
|
97
|
+
if (images && file.mimeType)
|
|
98
|
+
content.push({ type: "image", mimeType: file.mimeType, data: (await (0, promises_1.readFile)(file.path)).toString("base64") });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return await this.request("session/prompt", { sessionId: id, prompt: content }, 150_000);
|
|
102
|
+
}
|
|
103
|
+
finally {
|
|
104
|
+
clearTimeout(timeout);
|
|
105
|
+
signal.removeEventListener("abort", cancel);
|
|
106
|
+
this.session = undefined;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
receive(message) {
|
|
110
|
+
if (message.method) {
|
|
111
|
+
if (message.id !== undefined)
|
|
112
|
+
void this.respond(message);
|
|
113
|
+
else if (message.method === "session/update")
|
|
114
|
+
this.update(message.params);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (typeof message.id !== "number")
|
|
118
|
+
return;
|
|
119
|
+
const entry = this.pending.get(message.id);
|
|
120
|
+
this.pending.delete(message.id);
|
|
121
|
+
if (message.error)
|
|
122
|
+
entry?.reject(new AcpError(message.error.code, message.error.message, message.error.data?.details));
|
|
123
|
+
else
|
|
124
|
+
entry?.resolve(message.result);
|
|
125
|
+
}
|
|
126
|
+
update(message) {
|
|
127
|
+
const item = message?.update;
|
|
128
|
+
if (!this.session || message?.sessionId !== this.session || !item)
|
|
129
|
+
return;
|
|
130
|
+
if (item.sessionUpdate === "agent_message_chunk" && item.content?.type === "text" && item.content.text) {
|
|
131
|
+
this.turn?.onMessage({ id: this.replyId, role: "assistant", text: item.content.text }, true);
|
|
132
|
+
}
|
|
133
|
+
else if (["tool_call", "tool_call_update"].includes(item.sessionUpdate ?? "") && item.toolCallId) {
|
|
134
|
+
const update = { ...this.tools.get(item.toolCallId), ...Object.fromEntries(Object.entries(item).filter(([, value]) => value != null)) };
|
|
135
|
+
this.tools.set(item.toolCallId, update);
|
|
136
|
+
const activity = (0, activity_1.toolActivity)(update.kind ?? update.title ?? "Tool", update.rawInput, (0, activity_1.activityStatus)(update.status), JSON.stringify(update.rawOutput ?? update.content));
|
|
137
|
+
activity.title = update.title ?? activity.title;
|
|
138
|
+
this.turn?.onMessage({ id: item.toolCallId, role: "activity", text: activity.title, activity });
|
|
139
|
+
}
|
|
140
|
+
else if (item.sessionUpdate === "config_option_update" && item.configOptions) {
|
|
141
|
+
this.updateConfig?.(item.configOptions);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
async respond(message) {
|
|
145
|
+
try {
|
|
146
|
+
const params = message.params;
|
|
147
|
+
if (!this.turn || !this.session || params?.sessionId !== this.session || this.turn.signal.aborted) {
|
|
148
|
+
throw new AcpError(-32602, "Invalid ACP session");
|
|
149
|
+
}
|
|
150
|
+
let result;
|
|
151
|
+
switch (message.method) {
|
|
152
|
+
case "session/request_permission":
|
|
153
|
+
result = await this.permission(params);
|
|
154
|
+
break;
|
|
155
|
+
case "fs/read_text_file":
|
|
156
|
+
case "fs/write_text_file": {
|
|
157
|
+
if (typeof params.path !== "string" || !(0, node_path_1.isAbsolute)(params.path))
|
|
158
|
+
throw new AcpError(-32602, "Expected absolute draft path");
|
|
159
|
+
const requested = (0, node_path_1.resolve)(params.path);
|
|
160
|
+
const attachment = this.turn.attachments?.flatMap(item => item.files).find(file => file.path === requested);
|
|
161
|
+
if (attachment && message.method === "fs/write_text_file")
|
|
162
|
+
throw new AcpError(-32602, "Attachments are read-only.");
|
|
163
|
+
const path = attachment?.path ?? await (0, files_1.checkedPath)(this.turn.cwd, (0, files_1.projectPath)((0, node_path_1.relative)(this.turn.cwd, requested)));
|
|
164
|
+
if (message.method === "fs/write_text_file") {
|
|
165
|
+
if (typeof params.text !== "string" || Buffer.byteLength(params.text) > 4 * 1024 * 1024)
|
|
166
|
+
throw new AcpError(-32602, "Invalid file content");
|
|
167
|
+
await (0, text_file_1.writeTextAtomically)(path, params.text);
|
|
168
|
+
result = {};
|
|
169
|
+
}
|
|
170
|
+
else {
|
|
171
|
+
const file = await (0, files_1.info)(path);
|
|
172
|
+
if (!file?.isFile() || file.size > 4 * 1024 * 1024)
|
|
173
|
+
throw new AcpError(-32602, "Invalid draft file");
|
|
174
|
+
const text = await (0, promises_1.readFile)(path, "utf8");
|
|
175
|
+
const start = Math.max(0, (params.line ?? 1) - 1);
|
|
176
|
+
result = { content: text.split("\n").slice(start, params.limit === undefined ? undefined : start + params.limit).join("\n") };
|
|
177
|
+
}
|
|
178
|
+
break;
|
|
179
|
+
}
|
|
180
|
+
default:
|
|
181
|
+
throw new AcpError(-32601, "Unsupported ACP client method");
|
|
182
|
+
}
|
|
183
|
+
this.write({ id: message.id, result });
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
this.write({ id: message.id, error: { code: error instanceof AcpError ? error.code : -32602,
|
|
187
|
+
message: error instanceof Error ? error.message : "Rejected by Morka" } });
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
async permission(request) {
|
|
191
|
+
const locations = request.toolCall?.locations;
|
|
192
|
+
const once = request.options?.find(option => option.kind === "allow_once");
|
|
193
|
+
const reject = request.options?.find(option => option.kind === "reject_once");
|
|
194
|
+
let selected = reject;
|
|
195
|
+
if (once && request.toolCall?.kind === "edit" && locations?.length) {
|
|
196
|
+
const scoped = await Promise.all(locations.map(async ({ path }) => {
|
|
197
|
+
if (typeof path !== "string" || !(0, node_path_1.isAbsolute)(path))
|
|
198
|
+
return false;
|
|
199
|
+
try {
|
|
200
|
+
const { cwd } = this.turn;
|
|
201
|
+
await (0, files_1.checkedPath)(cwd, (0, files_1.projectPath)((0, node_path_1.relative)(cwd, (0, node_path_1.resolve)(path))));
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
}));
|
|
208
|
+
if (scoped.every(Boolean))
|
|
209
|
+
selected = once;
|
|
210
|
+
}
|
|
211
|
+
// A declined request should settle agents' approval wait. "Cancelled" means
|
|
212
|
+
// the client has detached or the turn is being cancelled.
|
|
213
|
+
return { outcome: selected ? { outcome: "selected", optionId: selected.optionId } : { outcome: "cancelled" } };
|
|
214
|
+
}
|
|
215
|
+
fail(error) {
|
|
216
|
+
if (this.failure)
|
|
217
|
+
return;
|
|
218
|
+
this.failure = error;
|
|
219
|
+
for (const pending of this.pending.values())
|
|
220
|
+
pending.reject(error);
|
|
221
|
+
this.pending.clear();
|
|
222
|
+
if (!this.closed)
|
|
223
|
+
(0, acp_sandbox_1.stopAgent)(this.child.pid);
|
|
224
|
+
}
|
|
225
|
+
abort() { this.fail(new Error("The ACP connection was closed.")); }
|
|
226
|
+
async close() {
|
|
227
|
+
this.abort();
|
|
228
|
+
if (this.closed)
|
|
229
|
+
return;
|
|
230
|
+
await Promise.race([this.exited, (0, promises_2.setTimeout)(900, undefined, { ref: false })]);
|
|
231
|
+
if (!this.closed) {
|
|
232
|
+
(0, acp_sandbox_1.stopAgent)(this.child.pid, "SIGKILL");
|
|
233
|
+
await Promise.race([this.exited, (0, promises_2.setTimeout)(900, undefined, { ref: false })]);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
class AcpConnection {
|
|
238
|
+
profile;
|
|
239
|
+
skills;
|
|
240
|
+
state;
|
|
241
|
+
projectRoot;
|
|
242
|
+
process;
|
|
243
|
+
discovery;
|
|
244
|
+
discoveryProcess;
|
|
245
|
+
setup = {};
|
|
246
|
+
discovered = false;
|
|
247
|
+
constructor(profile, skills, state, projectRoot) {
|
|
248
|
+
this.profile = profile;
|
|
249
|
+
this.skills = skills;
|
|
250
|
+
this.state = state;
|
|
251
|
+
this.projectRoot = projectRoot;
|
|
252
|
+
}
|
|
253
|
+
get setupTimeout() { return this.profile.id === "hermes" ? 120_000 : 25_000; }
|
|
254
|
+
async initialize(process) {
|
|
255
|
+
const hello = await process.request("initialize", {
|
|
256
|
+
protocolVersion: 1,
|
|
257
|
+
clientInfo: { name: "morka", version: "0.1.0" },
|
|
258
|
+
clientCapabilities: { fs: { readTextFile: true, writeTextFile: true }, terminal: false },
|
|
259
|
+
}, this.setupTimeout);
|
|
260
|
+
if (hello.protocolVersion !== 1)
|
|
261
|
+
throw new Error(`Unsupported ACP version: ${hello.protocolVersion}.`);
|
|
262
|
+
return hello;
|
|
263
|
+
}
|
|
264
|
+
async options() {
|
|
265
|
+
if (!this.discovered && !this.process) {
|
|
266
|
+
this.discovery ??= this.discover().finally(() => { this.discovery = undefined; });
|
|
267
|
+
await this.discovery;
|
|
268
|
+
}
|
|
269
|
+
const model = config(this.setup, "model");
|
|
270
|
+
const effort = config(this.setup, "thought_level");
|
|
271
|
+
return {
|
|
272
|
+
models: model ? choices(model) : this.setup.models?.availableModels?.map(item => ({ id: item.modelId, name: item.name })) ?? [],
|
|
273
|
+
defaultModel: model?.currentValue ?? this.setup.models?.currentModelId,
|
|
274
|
+
efforts: choices(effort).map(choice => choice.name === choice.id || /^Thinking: /i.test(choice.name)
|
|
275
|
+
? (0, context_1.effortChoice)(choice.id) : choice),
|
|
276
|
+
defaultEffort: effort?.currentValue,
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
async discover() {
|
|
280
|
+
await (0, promises_1.mkdir)(this.state, { recursive: true, mode: 0o700 });
|
|
281
|
+
const cwd = await (0, promises_1.mkdtemp)((0, node_path_1.join)(this.state, "model-options-"));
|
|
282
|
+
let process;
|
|
283
|
+
try {
|
|
284
|
+
process = new AcpProcess(await (0, acp_sandbox_1.spawnAcp)(this.profile, cwd, this.state, this.projectRoot, "catalog"));
|
|
285
|
+
this.discoveryProcess = process;
|
|
286
|
+
const hello = await this.initialize(process);
|
|
287
|
+
const setup = await process.request("session/new", { cwd, mcpServers: [] }, this.setupTimeout);
|
|
288
|
+
if (!setup.sessionId)
|
|
289
|
+
throw new Error("The ACP agent did not return a session ID.");
|
|
290
|
+
this.setup = setup;
|
|
291
|
+
this.discovered = true;
|
|
292
|
+
if (hello.agentCapabilities?.sessionCapabilities?.close) {
|
|
293
|
+
await process.request("session/close", { sessionId: setup.sessionId }, 3500).catch(() => { });
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
finally {
|
|
297
|
+
await process?.close();
|
|
298
|
+
this.discoveryProcess = undefined;
|
|
299
|
+
await (0, promises_1.rm)(cwd, { recursive: true, force: true });
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
async applyOptions(process, id, setup, turn) {
|
|
303
|
+
const current = { ...this.setup, ...setup,
|
|
304
|
+
models: setup?.models ?? this.setup.models,
|
|
305
|
+
configOptions: setup?.configOptions ?? this.setup.configOptions };
|
|
306
|
+
const model = config(current, "model");
|
|
307
|
+
if (turn.model) {
|
|
308
|
+
if (model && choices(model).some(item => item.id === turn.model)) {
|
|
309
|
+
if (config(setup ?? {}, "model")?.currentValue !== turn.model) {
|
|
310
|
+
const updated = await process.request("session/set_config_option", { sessionId: id, configId: model.id, value: turn.model });
|
|
311
|
+
current.configOptions = updated?.configOptions ?? current.configOptions;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
else if (!model && current.models?.availableModels?.some(item => item.modelId === turn.model)) {
|
|
315
|
+
if (setup?.models?.currentModelId !== turn.model) {
|
|
316
|
+
await process.request("session/set_model", { sessionId: id, modelId: turn.model });
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
else
|
|
320
|
+
throw new Error("The selected model is unavailable for this ACP session.");
|
|
321
|
+
}
|
|
322
|
+
const effort = config(current, "thought_level");
|
|
323
|
+
if (turn.effort) {
|
|
324
|
+
if (!effort || !choices(effort).some(item => item.id === turn.effort)) {
|
|
325
|
+
throw new Error("The selected reasoning effort is unavailable for this ACP session.");
|
|
326
|
+
}
|
|
327
|
+
if ((setup?.configOptions ? effort.currentValue : undefined) !== turn.effort) {
|
|
328
|
+
const updated = await process.request("session/set_config_option", { sessionId: id, configId: effort.id, value: turn.effort });
|
|
329
|
+
current.configOptions = updated?.configOptions ?? current.configOptions;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
this.setup = current;
|
|
333
|
+
this.discovered = true;
|
|
334
|
+
}
|
|
335
|
+
async prompt(turn) {
|
|
336
|
+
turn.signal.throwIfAborted();
|
|
337
|
+
if (this.discovery) {
|
|
338
|
+
const abortProbe = () => this.discoveryProcess?.abort();
|
|
339
|
+
turn.signal.addEventListener("abort", abortProbe, { once: true });
|
|
340
|
+
try {
|
|
341
|
+
await this.discovery.catch(() => { });
|
|
342
|
+
}
|
|
343
|
+
finally {
|
|
344
|
+
turn.signal.removeEventListener("abort", abortProbe);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
turn.signal.throwIfAborted();
|
|
348
|
+
if (this.process)
|
|
349
|
+
throw new Error("The ACP agent is already responding.");
|
|
350
|
+
const child = await (0, acp_sandbox_1.spawnAcp)(this.profile, turn.cwd, this.state, this.projectRoot, "chat", turn.attachments?.map(attachment => attachment.path));
|
|
351
|
+
const process = new AcpProcess(child, turn, configOptions => { this.setup = { ...this.setup, configOptions }; });
|
|
352
|
+
this.process = process;
|
|
353
|
+
const setupTimeout = this.profile.id === "hermes" ? 120_000 : 25_000;
|
|
354
|
+
const abortSetup = () => process.abort();
|
|
355
|
+
turn.signal.addEventListener("abort", abortSetup, { once: true });
|
|
356
|
+
try {
|
|
357
|
+
turn.signal.throwIfAborted();
|
|
358
|
+
const hello = await this.initialize(process);
|
|
359
|
+
const native = hello.agentCapabilities?.loadSession ? turn.sessionId : undefined;
|
|
360
|
+
const args = { cwd: turn.cwd, mcpServers: [] };
|
|
361
|
+
let loaded = false;
|
|
362
|
+
let setup;
|
|
363
|
+
if (native) {
|
|
364
|
+
try {
|
|
365
|
+
setup = await process.request("session/load", { ...args, sessionId: native }, setupTimeout);
|
|
366
|
+
loaded = true;
|
|
367
|
+
}
|
|
368
|
+
catch (error) {
|
|
369
|
+
if (!(error instanceof AcpError) || !([-32601, -32602, -32002].includes(error.code) ||
|
|
370
|
+
(this.profile.id === "hermes" && error.details === "not_found")))
|
|
371
|
+
throw error;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
if (!loaded)
|
|
375
|
+
setup = await process.request("session/new", args, setupTimeout);
|
|
376
|
+
const id = loaded ? native : setup?.sessionId;
|
|
377
|
+
if (!id)
|
|
378
|
+
throw new Error("The ACP agent did not return a session ID.");
|
|
379
|
+
if (hello.agentCapabilities?.loadSession && !loaded)
|
|
380
|
+
await turn.storeSession(id);
|
|
381
|
+
const edits = setup?.modes?.availableModes?.find(mode => ["accept_edits", "acceptEdits"].includes(mode.id));
|
|
382
|
+
if (edits && edits.id !== setup?.modes?.currentModeId) {
|
|
383
|
+
await process.request("session/set_mode", { sessionId: id, modeId: edits.id }, setupTimeout);
|
|
384
|
+
}
|
|
385
|
+
await this.applyOptions(process, id, setup, turn);
|
|
386
|
+
const prompt = await (0, context_1.buildPrompt)({ ...turn, history: loaded ? turn.historySinceSession : turn.history }, this.skills, "the project file editing tools", true);
|
|
387
|
+
turn.signal.removeEventListener("abort", abortSetup);
|
|
388
|
+
const result = await process.prompt(id, prompt, hello.agentCapabilities?.promptCapabilities?.image === true);
|
|
389
|
+
if (turn.signal.aborted || result.stopReason === "cancelled")
|
|
390
|
+
return "interrupted";
|
|
391
|
+
if (result.stopReason !== "end_turn")
|
|
392
|
+
throw new Error(`The ACP turn ended with status ${result.stopReason}.`);
|
|
393
|
+
return "completed";
|
|
394
|
+
}
|
|
395
|
+
catch (error) {
|
|
396
|
+
if (turn.signal.aborted)
|
|
397
|
+
return "interrupted";
|
|
398
|
+
throw error;
|
|
399
|
+
}
|
|
400
|
+
finally {
|
|
401
|
+
turn.signal.removeEventListener("abort", abortSetup);
|
|
402
|
+
await process.close();
|
|
403
|
+
this.process = undefined;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
close() {
|
|
407
|
+
void this.discoveryProcess?.close();
|
|
408
|
+
void this.process?.close();
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
exports.AcpConnection = AcpConnection;
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ClaudeConnection = void 0;
|
|
4
|
+
const node_child_process_1 = require("node:child_process");
|
|
5
|
+
const node_crypto_1 = require("node:crypto");
|
|
6
|
+
const promises_1 = require("node:fs/promises");
|
|
7
|
+
const node_path_1 = require("node:path");
|
|
8
|
+
const node_readline_1 = require("node:readline");
|
|
9
|
+
const context_1 = require("../context");
|
|
10
|
+
const process_1 = require("../process");
|
|
11
|
+
const activity_1 = require("../activity");
|
|
12
|
+
const efforts = ["low", "medium", "high", "xhigh", "max"];
|
|
13
|
+
const models = ["default", "sonnet", "opus", "haiku"].map(id => ({
|
|
14
|
+
id, name: id === "default" ? "Claude default" : id[0].toUpperCase() + id.slice(1), efforts: efforts.map(context_1.effortChoice),
|
|
15
|
+
}));
|
|
16
|
+
class ClaudeConnection {
|
|
17
|
+
skillsRoot;
|
|
18
|
+
children = new Set();
|
|
19
|
+
constructor(skillsRoot) {
|
|
20
|
+
this.skillsRoot = skillsRoot;
|
|
21
|
+
}
|
|
22
|
+
async options() { return { models, defaultModel: "default" }; }
|
|
23
|
+
async prompt(turn) {
|
|
24
|
+
if (turn.model && !models.some(model => model.id === turn.model))
|
|
25
|
+
throw new Error("The selected Claude Code model is unavailable.");
|
|
26
|
+
if (turn.effort && !efforts.includes(turn.effort))
|
|
27
|
+
throw new Error("The selected reasoning effort is unavailable for Claude Code.");
|
|
28
|
+
const prompt = await (0, context_1.buildPrompt)(turn, this.skillsRoot, "Claude Code’s Edit and Write tools", false);
|
|
29
|
+
const result = await this.run(turn.cwd, prompt, turn.signal, turn);
|
|
30
|
+
return result ? "completed" : "interrupted";
|
|
31
|
+
}
|
|
32
|
+
async runAction(turn) {
|
|
33
|
+
const skill = await (0, promises_1.readFile)((0, node_path_1.join)(turn.skillRoot, turn.skill, "SKILL.md"), "utf8");
|
|
34
|
+
const output = await this.run(turn.cwd, skill + "\n\n" + turn.text, turn.signal, undefined, turn.schema);
|
|
35
|
+
if (!output || output.structured_output === undefined)
|
|
36
|
+
throw new Error("Claude Code did not return structured output.");
|
|
37
|
+
return JSON.stringify(output.structured_output);
|
|
38
|
+
}
|
|
39
|
+
async run(cwd, prompt, signal, turn, schema) {
|
|
40
|
+
signal.throwIfAborted();
|
|
41
|
+
const args = [
|
|
42
|
+
"--print", "--verbose", "--output-format", "stream-json", "--include-partial-messages",
|
|
43
|
+
"--no-session-persistence", "--safe-mode", "--restricted", "--strict-mcp-config",
|
|
44
|
+
"--mcp-config", '{"mcpServers":{}}', "--permission-prompts", "none",
|
|
45
|
+
"--permission-mode", turn ? "acceptEdits" : "dontAsk",
|
|
46
|
+
"--tools", turn ? "Read,Glob,Grep,Edit,Write" : "",
|
|
47
|
+
];
|
|
48
|
+
if (turn?.model && turn.model !== "default")
|
|
49
|
+
args.push("--model", turn.model);
|
|
50
|
+
if (turn?.effort)
|
|
51
|
+
args.push("--effort", turn.effort);
|
|
52
|
+
if (schema)
|
|
53
|
+
args.push("--json-schema", JSON.stringify(schema));
|
|
54
|
+
const attachments = turn?.attachments?.map(attachment => attachment.kind === "folder" ? attachment.path : (0, node_path_1.dirname)(attachment.path)) ?? [];
|
|
55
|
+
for (const path of attachments)
|
|
56
|
+
args.push("--add-dir", path);
|
|
57
|
+
const cli = await (0, process_1.agentLaunch)("claude", args);
|
|
58
|
+
signal.throwIfAborted();
|
|
59
|
+
return new Promise((resolve, reject) => {
|
|
60
|
+
const repositories = process.platform === "darwin" ? [turn?.repository, turn?.otherRepository, ...attachments].filter(Boolean) : [];
|
|
61
|
+
const denied = repositories.map(path => `(subpath ${JSON.stringify(path)})`).join(" ");
|
|
62
|
+
const sandbox = denied && `(version 1) (allow default) (deny file-write* ${denied})`;
|
|
63
|
+
const child = (0, node_child_process_1.spawn)(sandbox ? "/usr/bin/sandbox-exec" : cli.command, sandbox ? ["-p", sandbox, cli.command, ...cli.args] : cli.args, {
|
|
64
|
+
cwd, env: cli.env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true,
|
|
65
|
+
});
|
|
66
|
+
this.children.add(child);
|
|
67
|
+
let finalText = "";
|
|
68
|
+
let stderr = "";
|
|
69
|
+
let settled = false;
|
|
70
|
+
const replyId = (0, node_crypto_1.randomUUID)();
|
|
71
|
+
const tools = new Map();
|
|
72
|
+
const blocks = new Map();
|
|
73
|
+
const reportTool = (id, status, output) => {
|
|
74
|
+
const tool = tools.get(id);
|
|
75
|
+
if (tool)
|
|
76
|
+
turn?.onMessage({ id, role: "activity", text: tool.name,
|
|
77
|
+
activity: (0, activity_1.toolActivity)(tool.name, tool.input, status, typeof output === "string" ? output : JSON.stringify(output, null, 2)) });
|
|
78
|
+
};
|
|
79
|
+
const stop = () => {
|
|
80
|
+
child.kill("SIGTERM");
|
|
81
|
+
finish();
|
|
82
|
+
};
|
|
83
|
+
const finish = (output, error) => {
|
|
84
|
+
if (settled)
|
|
85
|
+
return;
|
|
86
|
+
settled = true;
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
signal.removeEventListener("abort", stop);
|
|
89
|
+
if (error)
|
|
90
|
+
reject(error);
|
|
91
|
+
else
|
|
92
|
+
resolve(output);
|
|
93
|
+
};
|
|
94
|
+
const timer = setTimeout(() => {
|
|
95
|
+
child.kill();
|
|
96
|
+
finish(undefined, new Error("Claude Code did not respond."));
|
|
97
|
+
}, 120_000);
|
|
98
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
99
|
+
child.stderr.setEncoding("utf8").on("data", chunk => { stderr = (stderr + chunk).slice(-1500); });
|
|
100
|
+
child.stdin.on("error", () => { });
|
|
101
|
+
child.on("error", (error) => {
|
|
102
|
+
finish(undefined, error.code === "ENOENT" ? new Error("Claude Code was not found. Set CLAUDE_BIN to the CLI path.") : error);
|
|
103
|
+
});
|
|
104
|
+
child.on("close", code => {
|
|
105
|
+
this.children.delete(child);
|
|
106
|
+
finish(undefined, new Error(stderr.trim() || `Claude Code exited before responding (${code}).`));
|
|
107
|
+
});
|
|
108
|
+
(0, node_readline_1.createInterface)({ input: child.stdout, crlfDelay: Infinity }).on("line", line => {
|
|
109
|
+
if (settled)
|
|
110
|
+
return;
|
|
111
|
+
let output;
|
|
112
|
+
try {
|
|
113
|
+
output = JSON.parse(line);
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
timer.refresh();
|
|
119
|
+
const event = output.event;
|
|
120
|
+
if (output.type === "stream_event") {
|
|
121
|
+
if (event?.type === "content_block_delta" && event.delta?.type === "text_delta" && event.delta.text) {
|
|
122
|
+
turn?.onMessage({ id: replyId, role: "assistant", text: event.delta.text }, true);
|
|
123
|
+
}
|
|
124
|
+
if (event?.type === "content_block_start" && event.content_block?.type === "tool_use") {
|
|
125
|
+
const id = event.content_block.id ?? (0, node_crypto_1.randomUUID)();
|
|
126
|
+
tools.set(id, { name: event.content_block.name ?? "Tool", input: event.content_block.input, json: "" });
|
|
127
|
+
blocks.set(event.index ?? 0, id);
|
|
128
|
+
reportTool(id, "running");
|
|
129
|
+
}
|
|
130
|
+
const toolId = blocks.get(event?.index ?? -1);
|
|
131
|
+
const tool = toolId && tools.get(toolId);
|
|
132
|
+
if (tool && event?.delta?.type === "input_json_delta")
|
|
133
|
+
tool.json += event.delta.partial_json ?? "";
|
|
134
|
+
if (tool && event?.type === "content_block_stop") {
|
|
135
|
+
try {
|
|
136
|
+
tool.input = JSON.parse(tool.json);
|
|
137
|
+
}
|
|
138
|
+
catch { /* The full assistant message can supply the input. */ }
|
|
139
|
+
reportTool(toolId, "running");
|
|
140
|
+
blocks.delete(event.index ?? 0);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
else if (output.type === "assistant") {
|
|
144
|
+
const blocks = output.message?.content ?? [];
|
|
145
|
+
for (const block of blocks.filter(block => block.type === "tool_use" && block.id)) {
|
|
146
|
+
tools.set(block.id, { name: block.name ?? "Tool", input: block.input, json: "" });
|
|
147
|
+
reportTool(block.id, "running");
|
|
148
|
+
}
|
|
149
|
+
const text = blocks.filter(block => block.type === "text").map(block => block.text ?? "").join("");
|
|
150
|
+
if (text)
|
|
151
|
+
finalText = text;
|
|
152
|
+
}
|
|
153
|
+
else if (output.type === "user") {
|
|
154
|
+
for (const block of output.message?.content ?? []) {
|
|
155
|
+
if (block.type === "tool_result" && block.tool_use_id)
|
|
156
|
+
reportTool(block.tool_use_id, block.is_error ? "failed" : "completed", block.content);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
else if (output.type === "result") {
|
|
160
|
+
const error = output.is_error ? output.errors?.join("\n") || output.result || finalText || "Claude Code could not complete the response." : undefined;
|
|
161
|
+
const reply = output.result || finalText;
|
|
162
|
+
if (reply && !error)
|
|
163
|
+
turn?.onMessage({ id: replyId, role: "assistant", text: reply });
|
|
164
|
+
finish(output, error ? new Error(error) : undefined);
|
|
165
|
+
const exitTimer = setTimeout(() => child.kill(), 5000).unref();
|
|
166
|
+
child.once("close", () => clearTimeout(exitTimer));
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
if (signal.aborted)
|
|
170
|
+
stop();
|
|
171
|
+
else
|
|
172
|
+
child.stdin.end(prompt);
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
close() {
|
|
176
|
+
for (const child of this.children)
|
|
177
|
+
child.kill("SIGTERM");
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
exports.ClaudeConnection = ClaudeConnection;
|