@umage.ai/redline-agent 0.1.0 → 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/README.md +95 -48
- package/dist/index.cjs +1974 -264
- package/dist/panel.js +156 -46
- package/dist/terminal.js +18 -18
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -226,7 +226,7 @@ var require_xterm_headless = __commonJS({
|
|
|
226
226
|
};
|
|
227
227
|
Object.defineProperty(t2, "__esModule", { value: true }), t2.InputHandler = t2.WindowsOptionsReportType = void 0, t2.isValidColorIndex = k;
|
|
228
228
|
const n2 = s2(3534), o = s2(6760), a = s2(6717), h = s2(7150), c = s2(726), l = s2(6107), u = s2(8938), d = s2(3055), f = s2(5451), _ = s2(6501), p = s2(6415), g2 = s2(1346), v = s2(9823), m = s2(8693), b = s2(802), S = { "(": 0, ")": 1, "*": 2, "+": 3, "-": 1, ".": 2 }, y = 131072;
|
|
229
|
-
function
|
|
229
|
+
function C2(e3, t3) {
|
|
230
230
|
if (e3 > 24) return t3.setWinLines || false;
|
|
231
231
|
switch (e3) {
|
|
232
232
|
case 1:
|
|
@@ -361,7 +361,7 @@ var require_xterm_headless = __commonJS({
|
|
|
361
361
|
this._parser.precedingJoinState = g3, this._activeBuffer.x < a2 && s3 - t3 > 0 && 0 === _2.getWidth(this._activeBuffer.x) && !_2.hasContent(this._activeBuffer.x) && _2.setCellFromCodepoint(this._activeBuffer.x, 0, 1, f2), this._dirtyRowTracker.markDirty(this._activeBuffer.y);
|
|
362
362
|
}
|
|
363
363
|
registerCsiHandler(e3, t3) {
|
|
364
|
-
return "t" !== e3.final || e3.prefix || e3.intermediates ? this._parser.registerCsiHandler(e3, t3) : this._parser.registerCsiHandler(e3, ((e4) => !
|
|
364
|
+
return "t" !== e3.final || e3.prefix || e3.intermediates ? this._parser.registerCsiHandler(e3, t3) : this._parser.registerCsiHandler(e3, ((e4) => !C2(e4.params[0], this._optionsService.rawOptions.windowOptions) || t3(e4)));
|
|
365
365
|
}
|
|
366
366
|
registerDcsHandler(e3, t3) {
|
|
367
367
|
return this._parser.registerDcsHandler(e3, new v.DcsHandler(t3));
|
|
@@ -875,7 +875,7 @@ var require_xterm_headless = __commonJS({
|
|
|
875
875
|
return (e3.length < 2 || (s3 = e3.params[1]) > this._bufferService.rows || 0 === s3) && (s3 = this._bufferService.rows), s3 > t3 && (this._activeBuffer.scrollTop = t3 - 1, this._activeBuffer.scrollBottom = s3 - 1, this._setCursor(0, 0)), true;
|
|
876
876
|
}
|
|
877
877
|
windowOptions(e3) {
|
|
878
|
-
if (!
|
|
878
|
+
if (!C2(e3.params[0], this._optionsService.rawOptions.windowOptions)) return true;
|
|
879
879
|
const t3 = e3.length > 1 ? e3.params[1] : 0;
|
|
880
880
|
switch (e3.params[0]) {
|
|
881
881
|
case 14:
|
|
@@ -5083,28 +5083,32 @@ ${i3.join("\n")}
|
|
|
5083
5083
|
// agent/src/index.ts
|
|
5084
5084
|
var src_exports = {};
|
|
5085
5085
|
__export(src_exports, {
|
|
5086
|
-
|
|
5086
|
+
adapterFor: () => adapterFor,
|
|
5087
|
+
agent: () => agent,
|
|
5088
|
+
claudeCode: () => claudeCode,
|
|
5089
|
+
openCode: () => openCode
|
|
5087
5090
|
});
|
|
5088
5091
|
module.exports = __toCommonJS(src_exports);
|
|
5089
5092
|
|
|
5090
5093
|
// agent/src/server.ts
|
|
5091
|
-
var
|
|
5092
|
-
var
|
|
5093
|
-
var
|
|
5094
|
-
var
|
|
5095
|
-
var
|
|
5096
|
-
|
|
5097
|
-
|
|
5094
|
+
var import_node_crypto3 = require("node:crypto");
|
|
5095
|
+
var import_node_fs7 = require("node:fs");
|
|
5096
|
+
var import_promises4 = require("node:fs/promises");
|
|
5097
|
+
var import_node_url2 = require("node:url");
|
|
5098
|
+
var import_node_path7 = __toESM(require("node:path"), 1);
|
|
5099
|
+
|
|
5100
|
+
// agent-bridge/src/handler.ts
|
|
5101
|
+
var import_node_path6 = __toESM(require("node:path"), 1);
|
|
5102
|
+
var import_node_fs6 = require("node:fs");
|
|
5098
5103
|
|
|
5099
|
-
// src/
|
|
5100
|
-
|
|
5101
|
-
|
|
5102
|
-
res.statusCode = status;
|
|
5104
|
+
// agent-bridge/src/http.ts
|
|
5105
|
+
function json(res, status2, body) {
|
|
5106
|
+
res.statusCode = status2;
|
|
5103
5107
|
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
5104
5108
|
res.setHeader("cache-control", "no-store");
|
|
5105
5109
|
res.end(JSON.stringify(body));
|
|
5106
5110
|
}
|
|
5107
|
-
function readBody(req, max
|
|
5111
|
+
function readBody(req, max) {
|
|
5108
5112
|
return new Promise((resolve, reject) => {
|
|
5109
5113
|
const chunks = [];
|
|
5110
5114
|
let size = 0;
|
|
@@ -5121,8 +5125,565 @@ function readBody(req, max = MAX_BODY) {
|
|
|
5121
5125
|
req.on("error", reject);
|
|
5122
5126
|
});
|
|
5123
5127
|
}
|
|
5128
|
+
var LOOPBACK = /^(127\.|::1$|::ffff:127\.)/;
|
|
5129
|
+
var LOCAL_HOST = /^(localhost|[^:/]+\.localhost|127(\.\d+){3}|\[::1\])(:\d+)?$/i;
|
|
5130
|
+
function isLocal(req) {
|
|
5131
|
+
if (!LOOPBACK.test(req.socket?.remoteAddress ?? "")) return false;
|
|
5132
|
+
const h = req.headers;
|
|
5133
|
+
const host = String(h["x-forwarded-host"] ?? h.host ?? "").split(",")[0].trim();
|
|
5134
|
+
return LOCAL_HOST.test(host);
|
|
5135
|
+
}
|
|
5136
|
+
function foreignOrigin(req) {
|
|
5137
|
+
const origin = req.headers.origin;
|
|
5138
|
+
if (!origin || origin === "null") return false;
|
|
5139
|
+
try {
|
|
5140
|
+
return new URL(origin).host !== req.headers.host;
|
|
5141
|
+
} catch {
|
|
5142
|
+
return true;
|
|
5143
|
+
}
|
|
5144
|
+
}
|
|
5145
|
+
|
|
5146
|
+
// agent-bridge/src/attachments.ts
|
|
5147
|
+
var import_node_child_process2 = require("node:child_process");
|
|
5148
|
+
var import_node_fs2 = require("node:fs");
|
|
5149
|
+
var import_node_os = __toESM(require("node:os"), 1);
|
|
5150
|
+
var import_node_path2 = __toESM(require("node:path"), 1);
|
|
5124
5151
|
|
|
5125
|
-
// agent/src/
|
|
5152
|
+
// agent-bridge/src/worktrees.ts
|
|
5153
|
+
var import_node_child_process = require("node:child_process");
|
|
5154
|
+
var import_node_fs = require("node:fs");
|
|
5155
|
+
var import_node_path = __toESM(require("node:path"), 1);
|
|
5156
|
+
function git(cwd, args, timeout = 3e4) {
|
|
5157
|
+
return new Promise((resolve, reject) => {
|
|
5158
|
+
(0, import_node_child_process.execFile)("git", args, { cwd, timeout, windowsHide: true, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" } }, (err, stdout, stderr) => {
|
|
5159
|
+
if (err) reject(Object.assign(new Error(String(stderr || err.message).trim().split("\n").pop() || "git failed"), { code: err.code }));
|
|
5160
|
+
else resolve(String(stdout));
|
|
5161
|
+
});
|
|
5162
|
+
});
|
|
5163
|
+
}
|
|
5164
|
+
async function gitTop(root) {
|
|
5165
|
+
try {
|
|
5166
|
+
return { top: import_node_path.default.resolve((await git(root, ["rev-parse", "--show-toplevel"])).trim()) };
|
|
5167
|
+
} catch (e) {
|
|
5168
|
+
const code = e.code;
|
|
5169
|
+
return { why: code === "ENOENT" ? "git is not installed" : "not a git repository" };
|
|
5170
|
+
}
|
|
5171
|
+
}
|
|
5172
|
+
var slug = (s) => s.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, "");
|
|
5173
|
+
async function addWorktree(o) {
|
|
5174
|
+
const t = await gitTop(o.root);
|
|
5175
|
+
if ("why" in t) throw new Error(`no worktree: ${t.why}`);
|
|
5176
|
+
const base = await headName(t.top);
|
|
5177
|
+
const taken = new Set((await git(t.top, ["for-each-ref", "--format=%(refname:short)", "refs/heads/"])).split("\n").map((s) => s.trim()));
|
|
5178
|
+
const stem = `${o.prefix}${slug(o.name) || "session"}`;
|
|
5179
|
+
let branch = stem;
|
|
5180
|
+
for (let n = 2; taken.has(branch) || (0, import_node_fs.existsSync)(import_node_path.default.join(o.dir, branch.split("/").pop())); n++) branch = `${stem}-${n}`;
|
|
5181
|
+
(0, import_node_fs.mkdirSync)(o.dir, { recursive: true });
|
|
5182
|
+
const ignore = import_node_path.default.join(o.dir, ".gitignore");
|
|
5183
|
+
if (!(0, import_node_fs.existsSync)(ignore)) (0, import_node_fs.writeFileSync)(ignore, "# Agent session worktrees (D64): never part of the main tree.\n*\n");
|
|
5184
|
+
const dir = import_node_path.default.join(o.dir, branch.split("/").pop());
|
|
5185
|
+
await git(t.top, ["worktree", "add", "-b", branch, dir, "HEAD"]);
|
|
5186
|
+
const within = (p) => {
|
|
5187
|
+
const sub = import_node_path.default.relative(t.top, p);
|
|
5188
|
+
return sub && !sub.startsWith("..") && !import_node_path.default.isAbsolute(sub) ? import_node_path.default.join(dir, sub) : dir;
|
|
5189
|
+
};
|
|
5190
|
+
return { branch, base, dir, cwd: within(o.cwd), home: within(o.root), top: t.top, path: rel(o.root, dir) };
|
|
5191
|
+
}
|
|
5192
|
+
async function headName(top) {
|
|
5193
|
+
const name = (await git(top, ["rev-parse", "--abbrev-ref", "HEAD"]).catch(() => "HEAD")).trim();
|
|
5194
|
+
return name !== "HEAD" ? name : (await git(top, ["rev-parse", "--short", "HEAD"]).catch(() => "HEAD")).trim();
|
|
5195
|
+
}
|
|
5196
|
+
var isBranch = (top, name) => git(top, ["show-ref", "--verify", "--quiet", `refs/heads/${name}`]).then(() => true, () => false);
|
|
5197
|
+
var rel = (root, p) => import_node_path.default.relative(root, p).split(import_node_path.default.sep).join("/");
|
|
5198
|
+
async function status(w) {
|
|
5199
|
+
if (!(0, import_node_fs.existsSync)(w.dir)) return { dirty: false, ahead: await ahead(w).catch(() => 0), gone: true };
|
|
5200
|
+
const [porcelain, n] = await Promise.all([git(w.dir, ["status", "--porcelain"]).catch(() => ""), ahead(w).catch(() => 0)]);
|
|
5201
|
+
return { dirty: porcelain.trim() !== "", ahead: n };
|
|
5202
|
+
}
|
|
5203
|
+
var ahead = async (w) => Number((await git(w.top, ["rev-list", "--count", `${w.base}..${w.branch}`])).trim()) || 0;
|
|
5204
|
+
async function act(w, action, confirm = false) {
|
|
5205
|
+
const s = await status(w);
|
|
5206
|
+
if (action === "keep") {
|
|
5207
|
+
if (s.dirty) return { ok: true, kept: true, message: `Kept ${w.branch} and its folder ${w.path} (it has uncommitted changes)` };
|
|
5208
|
+
if (!s.gone) await git(w.top, ["worktree", "remove", w.dir]);
|
|
5209
|
+
return { ok: true, kept: false, message: `Kept the branch ${w.branch}` };
|
|
5210
|
+
}
|
|
5211
|
+
if (action === "discard") {
|
|
5212
|
+
if ((s.dirty || s.ahead) && !confirm) {
|
|
5213
|
+
const what = [s.dirty && "uncommitted changes", s.ahead && `${s.ahead} commit${s.ahead === 1 ? "" : "s"} not on ${w.base}`].filter(Boolean).join(" and ");
|
|
5214
|
+
return { ok: false, kept: true, confirm: true, message: `${w.branch} has ${what}: discarding deletes them` };
|
|
5215
|
+
}
|
|
5216
|
+
if (!s.gone) await git(w.top, ["worktree", "remove", "--force", w.dir]);
|
|
5217
|
+
await git(w.top, ["worktree", "prune"]).catch(() => "");
|
|
5218
|
+
await git(w.top, ["branch", "-D", w.branch]).catch(() => "");
|
|
5219
|
+
return { ok: true, kept: false, message: `Discarded ${w.branch}` };
|
|
5220
|
+
}
|
|
5221
|
+
if (s.dirty) return { ok: false, kept: true, message: `${w.branch} has uncommitted changes: commit them in ${w.path} (or ask the agent to), then merge` };
|
|
5222
|
+
if (!s.ahead) {
|
|
5223
|
+
if (!s.gone) await git(w.top, ["worktree", "remove", w.dir]);
|
|
5224
|
+
await git(w.top, ["branch", "-d", w.branch]).catch(() => "");
|
|
5225
|
+
return { ok: true, kept: false, message: `${w.branch} had nothing to merge: removed` };
|
|
5226
|
+
}
|
|
5227
|
+
if (!await isBranch(w.top, w.base)) return { ok: false, kept: true, message: `${w.branch} came from a detached HEAD (${w.base}): check out a branch, then merge ${w.branch} by hand` };
|
|
5228
|
+
const head = (await git(w.top, ["rev-parse", "--abbrev-ref", "HEAD"])).trim();
|
|
5229
|
+
if (head !== w.base) return { ok: false, kept: true, message: `The project is on ${head}, not ${w.base}: check out ${w.base} to merge ${w.branch}` };
|
|
5230
|
+
const ff = await git(w.top, ["merge-base", "--is-ancestor", w.base, w.branch]).then(() => true, () => false);
|
|
5231
|
+
if (!ff) {
|
|
5232
|
+
const clean = await git(w.top, ["merge-tree", "--write-tree", w.base, w.branch]).then(() => true, () => false);
|
|
5233
|
+
if (!clean) return { ok: false, kept: true, message: `${w.branch} doesn't merge cleanly into ${w.base}: merge it by hand` };
|
|
5234
|
+
}
|
|
5235
|
+
try {
|
|
5236
|
+
await git(w.top, ["merge", ff ? "--ff-only" : "--no-edit", w.branch]);
|
|
5237
|
+
} catch (e) {
|
|
5238
|
+
await git(w.top, ["merge", "--abort"]).catch(() => "");
|
|
5239
|
+
return { ok: false, kept: true, message: `Merging ${w.branch} failed: ${e.message}` };
|
|
5240
|
+
}
|
|
5241
|
+
if (!s.gone) await git(w.top, ["worktree", "remove", w.dir]).catch(() => "");
|
|
5242
|
+
await git(w.top, ["branch", "-d", w.branch]).catch(() => "");
|
|
5243
|
+
return { ok: true, kept: false, message: `Merged ${w.branch} into ${w.base}${ff ? " (fast-forward)" : ""}` };
|
|
5244
|
+
}
|
|
5245
|
+
async function leftover(o) {
|
|
5246
|
+
const t = await gitTop(o.root);
|
|
5247
|
+
if ("why" in t || !(0, import_node_fs.existsSync)(o.dir)) return [];
|
|
5248
|
+
const out = [];
|
|
5249
|
+
const list = await git(t.top, ["worktree", "list", "--porcelain"]).catch(() => "");
|
|
5250
|
+
const base = await headName(t.top);
|
|
5251
|
+
for (const block of list.split(/\n\n+/)) {
|
|
5252
|
+
const dir = /^worktree (.+)$/m.exec(block)?.[1];
|
|
5253
|
+
const branch = /^branch refs\/heads\/(.+)$/m.exec(block)?.[1];
|
|
5254
|
+
if (!dir || !branch || !branch.startsWith(o.prefix)) continue;
|
|
5255
|
+
const abs = import_node_path.default.resolve(dir);
|
|
5256
|
+
if (import_node_path.default.relative(import_node_path.default.resolve(o.dir), abs).startsWith("..")) continue;
|
|
5257
|
+
out.push({ branch, base, dir: abs, cwd: abs, home: abs, top: t.top, path: rel(o.root, abs) });
|
|
5258
|
+
}
|
|
5259
|
+
return out;
|
|
5260
|
+
}
|
|
5261
|
+
|
|
5262
|
+
// agent-bridge/src/attachments.ts
|
|
5263
|
+
var MAX_FILE = 5 * 1024 * 1024;
|
|
5264
|
+
var MAX_PER_ROUND = 200;
|
|
5265
|
+
var MAX_ROUNDS = 50;
|
|
5266
|
+
var IMAGE = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".avif": "image/avif", ".svg": "image/svg+xml" };
|
|
5267
|
+
var TEXT = /* @__PURE__ */ new Set([
|
|
5268
|
+
".txt",
|
|
5269
|
+
".md",
|
|
5270
|
+
".markdown",
|
|
5271
|
+
".json",
|
|
5272
|
+
".jsonc",
|
|
5273
|
+
".csv",
|
|
5274
|
+
".log",
|
|
5275
|
+
".yml",
|
|
5276
|
+
".yaml",
|
|
5277
|
+
".toml",
|
|
5278
|
+
".xml",
|
|
5279
|
+
".html",
|
|
5280
|
+
".htm",
|
|
5281
|
+
".css",
|
|
5282
|
+
".scss",
|
|
5283
|
+
".less",
|
|
5284
|
+
".js",
|
|
5285
|
+
".mjs",
|
|
5286
|
+
".cjs",
|
|
5287
|
+
".ts",
|
|
5288
|
+
".tsx",
|
|
5289
|
+
".jsx",
|
|
5290
|
+
".vue",
|
|
5291
|
+
".svelte",
|
|
5292
|
+
".astro",
|
|
5293
|
+
".py",
|
|
5294
|
+
".rb",
|
|
5295
|
+
".go",
|
|
5296
|
+
".rs",
|
|
5297
|
+
".java",
|
|
5298
|
+
".kt",
|
|
5299
|
+
".cs",
|
|
5300
|
+
".cshtml",
|
|
5301
|
+
".razor",
|
|
5302
|
+
".php",
|
|
5303
|
+
".sh",
|
|
5304
|
+
".ps1",
|
|
5305
|
+
".sql",
|
|
5306
|
+
".diff",
|
|
5307
|
+
".patch"
|
|
5308
|
+
]);
|
|
5309
|
+
function fileType(p) {
|
|
5310
|
+
const ext = import_node_path2.default.extname(p).toLowerCase();
|
|
5311
|
+
if (IMAGE[ext]) return { type: IMAGE[ext], image: true };
|
|
5312
|
+
if (TEXT.has(ext) || /(^|[\\/])(readme|license|changelog|dockerfile|makefile)$/i.test(p)) return { type: "text/plain; charset=utf-8", image: false };
|
|
5313
|
+
return null;
|
|
5314
|
+
}
|
|
5315
|
+
function inside(base, p) {
|
|
5316
|
+
if (!p || p.includes("\0")) return null;
|
|
5317
|
+
let realBase, real;
|
|
5318
|
+
try {
|
|
5319
|
+
realBase = import_node_fs2.realpathSync.native(base);
|
|
5320
|
+
real = import_node_fs2.realpathSync.native(import_node_path2.default.resolve(base, p));
|
|
5321
|
+
} catch {
|
|
5322
|
+
return null;
|
|
5323
|
+
}
|
|
5324
|
+
const rel2 = import_node_path2.default.relative(realBase, real);
|
|
5325
|
+
if (!rel2 || rel2.startsWith("..") || import_node_path2.default.isAbsolute(rel2)) return null;
|
|
5326
|
+
return { abs: real, rel: rel2.split(import_node_path2.default.sep).join("/") };
|
|
5327
|
+
}
|
|
5328
|
+
var OSC8 = /\x1b\]8;[^;\x07\x1b]*;([^\x07\x1b]*)(?:\x07|\x1b\\)([\s\S]*?)\x1b\]8;[^;\x07\x1b]*;(?:\x07|\x1b\\)/g;
|
|
5329
|
+
function osc8Links(output) {
|
|
5330
|
+
const out = [], seen = /* @__PURE__ */ new Set();
|
|
5331
|
+
for (const m of output.matchAll(OSC8)) {
|
|
5332
|
+
const uri = m[1].trim();
|
|
5333
|
+
if (!uri || seen.has(uri) || uri.length > 2048) continue;
|
|
5334
|
+
seen.add(uri);
|
|
5335
|
+
out.push({ uri, text: stripAnsi(m[2]).trim().slice(0, 200) });
|
|
5336
|
+
}
|
|
5337
|
+
return out;
|
|
5338
|
+
}
|
|
5339
|
+
function stripAnsi(s) {
|
|
5340
|
+
return s.replace(/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g, "").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, " ").replace(/\x1b[@-Z\\-_]/g, "").replace(/[\x00-\x08\x0b-\x1f\x7f]/g, " ");
|
|
5341
|
+
}
|
|
5342
|
+
var URL_RE = /\bhttps?:\/\/[^\s<>"'`)\]}|]+/g;
|
|
5343
|
+
var PATH_RE = /(?:^|[\s"'`(\[{<])((?:[A-Za-z]:[\\/]|\.{1,2}[\\/]|[\\/])?(?:[\w@.+-]+[\\/])*[\w@+-][\w@.+-]*\.[A-Za-z0-9]{1,8})(?::\d+(?::\d+)?)?(?=$|[\s"'`)\]}>,;:!?]|\.(?:\s|$))/gm;
|
|
5344
|
+
function mentions(text, base, cwd = base, max = 50) {
|
|
5345
|
+
const urls = [], paths = [], seenU = /* @__PURE__ */ new Set(), seenP = /* @__PURE__ */ new Set();
|
|
5346
|
+
for (const m of text.matchAll(URL_RE)) {
|
|
5347
|
+
const u = m[0].replace(/[.,;:!?]+$/, "");
|
|
5348
|
+
if (!seenU.has(u) && urls.length < max) {
|
|
5349
|
+
seenU.add(u);
|
|
5350
|
+
urls.push(u);
|
|
5351
|
+
}
|
|
5352
|
+
}
|
|
5353
|
+
const noUrls = text.replace(URL_RE, " ");
|
|
5354
|
+
for (const m of noUrls.matchAll(PATH_RE)) {
|
|
5355
|
+
if (paths.length >= max) break;
|
|
5356
|
+
const raw = m[1];
|
|
5357
|
+
if (seenP.has(raw)) continue;
|
|
5358
|
+
seenP.add(raw);
|
|
5359
|
+
const hit = [cwd, base].map((b) => inside(base, import_node_path2.default.resolve(b, raw))).find(Boolean);
|
|
5360
|
+
if (!hit || seenP.has("@" + hit.rel)) continue;
|
|
5361
|
+
try {
|
|
5362
|
+
if (!(0, import_node_fs2.statSync)(hit.abs).isFile()) continue;
|
|
5363
|
+
} catch {
|
|
5364
|
+
continue;
|
|
5365
|
+
}
|
|
5366
|
+
seenP.add("@" + hit.rel);
|
|
5367
|
+
paths.push(hit.rel);
|
|
5368
|
+
}
|
|
5369
|
+
return { urls, paths };
|
|
5370
|
+
}
|
|
5371
|
+
async function snapshot(cwd) {
|
|
5372
|
+
let index;
|
|
5373
|
+
try {
|
|
5374
|
+
index = import_node_path2.default.resolve(cwd, (await git(cwd, ["rev-parse", "--git-path", "index"])).trim());
|
|
5375
|
+
} catch {
|
|
5376
|
+
return null;
|
|
5377
|
+
}
|
|
5378
|
+
const tmp = import_node_path2.default.join(import_node_os.default.tmpdir(), `agent-bridge-index-${process.pid}-${Math.random().toString(36).slice(2)}`);
|
|
5379
|
+
try {
|
|
5380
|
+
await import_node_fs2.promises.copyFile(index, tmp).catch(() => {
|
|
5381
|
+
});
|
|
5382
|
+
const env = { ...process.env, GIT_INDEX_FILE: tmp, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" };
|
|
5383
|
+
const run = (args) => new Promise((resolve, reject) => (0, import_node_child_process2.execFile)("git", args, { cwd, env, windowsHide: true, maxBuffer: 16 * 1024 * 1024, timeout: 6e4 }, (e, out, err) => e ? reject(new Error(String(err || e.message))) : resolve(String(out))));
|
|
5384
|
+
await run(["add", "-A", "--", ":/"]);
|
|
5385
|
+
return (await run(["write-tree"])).trim() || null;
|
|
5386
|
+
} catch {
|
|
5387
|
+
return null;
|
|
5388
|
+
} finally {
|
|
5389
|
+
await import_node_fs2.promises.rm(tmp, { force: true }).catch(() => {
|
|
5390
|
+
});
|
|
5391
|
+
}
|
|
5392
|
+
}
|
|
5393
|
+
async function changedFiles(cwd, before, after) {
|
|
5394
|
+
if (before === after) return [];
|
|
5395
|
+
const [numstat, names] = await Promise.all([
|
|
5396
|
+
git(cwd, ["diff", "--numstat", "-z", "--no-renames", before, after]),
|
|
5397
|
+
git(cwd, ["diff", "--name-status", "-z", "--no-renames", before, after])
|
|
5398
|
+
]);
|
|
5399
|
+
const status2 = /* @__PURE__ */ new Map();
|
|
5400
|
+
const ns = names.split("\0");
|
|
5401
|
+
for (let i = 0; i + 1 < ns.length; i += 2) if (ns[i]) status2.set(ns[i + 1], ns[i][0]);
|
|
5402
|
+
const out = [];
|
|
5403
|
+
for (const rec of numstat.split("\0")) {
|
|
5404
|
+
const m = /^(-|\d+)\t(-|\d+)\t(.+)$/s.exec(rec);
|
|
5405
|
+
if (!m) continue;
|
|
5406
|
+
out.push({ path: m[3], added: m[1] === "-" ? 0 : +m[1], removed: m[2] === "-" ? 0 : +m[2], status: status2.get(m[3]) ?? "M" });
|
|
5407
|
+
}
|
|
5408
|
+
return out.slice(0, MAX_PER_ROUND);
|
|
5409
|
+
}
|
|
5410
|
+
async function fileDiff(cwd, before, after, file, max = 2e5) {
|
|
5411
|
+
const d = await git(cwd, ["diff", "--no-color", "--no-renames", before, after, "--", file]);
|
|
5412
|
+
return d.length > max ? d.slice(0, max) + "\n\u2026 (cut)\n" : d;
|
|
5413
|
+
}
|
|
5414
|
+
var Rounds = class {
|
|
5415
|
+
list = [];
|
|
5416
|
+
output = "";
|
|
5417
|
+
/** The session's folder (its worktree, or the project root): paths are relative to it. */
|
|
5418
|
+
base;
|
|
5419
|
+
cwd;
|
|
5420
|
+
onChange;
|
|
5421
|
+
constructor(base, cwd, onChange) {
|
|
5422
|
+
this.base = base;
|
|
5423
|
+
this.cwd = cwd;
|
|
5424
|
+
this.onChange = onChange;
|
|
5425
|
+
}
|
|
5426
|
+
get current() {
|
|
5427
|
+
return this.list[this.list.length - 1];
|
|
5428
|
+
}
|
|
5429
|
+
/** Attachments worth a count on the tab: everything but mere mentions. */
|
|
5430
|
+
get count() {
|
|
5431
|
+
return this.list.reduce((n, r) => n + r.items.filter((i) => i.source !== "mentioned").length, 0);
|
|
5432
|
+
}
|
|
5433
|
+
async begin(task) {
|
|
5434
|
+
if (this.current && !this.current.done && !this.current.finishing) await this.finish();
|
|
5435
|
+
const r = { n: (this.current?.n ?? 0) + 1, task, at: Date.now(), done: false, items: [] };
|
|
5436
|
+
this.list.push(r);
|
|
5437
|
+
if (this.list.length > MAX_ROUNDS) this.list.shift();
|
|
5438
|
+
this.output = "";
|
|
5439
|
+
r.before = await snapshot(this.cwd);
|
|
5440
|
+
this.onChange();
|
|
5441
|
+
}
|
|
5442
|
+
/** CLI output during the round (PTY data, ACP text): scanned for links and mentions when it finishes. */
|
|
5443
|
+
feed(text) {
|
|
5444
|
+
if (!this.current || this.current.done || this.current.finishing) return;
|
|
5445
|
+
this.output += text;
|
|
5446
|
+
if (this.output.length > 512 * 1024) this.output = this.output.slice(-512 * 1024);
|
|
5447
|
+
}
|
|
5448
|
+
/** An attachment for the current round (a new one is started when there is none); repeats are dropped. */
|
|
5449
|
+
add(a) {
|
|
5450
|
+
if (!this.current) {
|
|
5451
|
+
const r2 = { n: 1, at: Date.now(), done: false, items: [] };
|
|
5452
|
+
this.list.push(r2);
|
|
5453
|
+
}
|
|
5454
|
+
const r = this.current;
|
|
5455
|
+
const key = (x) => `${x.kind === "image" ? "file" : x.kind}:${x.path ?? x.url}`;
|
|
5456
|
+
const dupe = r.items.find((x) => key(x) === key(a));
|
|
5457
|
+
if (dupe) {
|
|
5458
|
+
const rank = { explicit: 3, changed: 2, link: 1, mentioned: 0 };
|
|
5459
|
+
if (rank[a.source] > rank[dupe.source]) dupe.source = a.source;
|
|
5460
|
+
if (a.title && !dupe.title) dupe.title = a.title;
|
|
5461
|
+
this.onChange();
|
|
5462
|
+
return dupe;
|
|
5463
|
+
}
|
|
5464
|
+
if (r.items.length >= MAX_PER_ROUND) return null;
|
|
5465
|
+
const item = { ...a, id: `${r.n}-${r.items.length + 1}`, round: r.n };
|
|
5466
|
+
r.items.push(item);
|
|
5467
|
+
this.onChange();
|
|
5468
|
+
return item;
|
|
5469
|
+
}
|
|
5470
|
+
/** A file the agent named (MCP `attach`, ACP): kept only inside the session's folder. */
|
|
5471
|
+
addFile(p, source, title) {
|
|
5472
|
+
const hit = inside(this.base, import_node_path2.default.resolve(this.cwd, p)) ?? inside(this.base, p);
|
|
5473
|
+
if (!hit) return null;
|
|
5474
|
+
return this.add({ source, kind: fileType(hit.rel)?.image ? "image" : "file", path: hit.rel, ...title ? { title } : {} });
|
|
5475
|
+
}
|
|
5476
|
+
/** A URL the agent named; only http(s). */
|
|
5477
|
+
addUrl(u, source, title) {
|
|
5478
|
+
try {
|
|
5479
|
+
if (!/^https?:$/.test(new URL(u).protocol)) return null;
|
|
5480
|
+
} catch {
|
|
5481
|
+
return null;
|
|
5482
|
+
}
|
|
5483
|
+
return this.add({ source, kind: "url", url: u, ...title ? { title } : {} });
|
|
5484
|
+
}
|
|
5485
|
+
/** The turn is done: changed files from git, then OSC 8 links and mentions from its output. */
|
|
5486
|
+
async finish() {
|
|
5487
|
+
const r = this.current;
|
|
5488
|
+
if (!r || r.done || r.finishing) return;
|
|
5489
|
+
r.finishing = true;
|
|
5490
|
+
const text = this.output;
|
|
5491
|
+
this.output = "";
|
|
5492
|
+
if (r.before) {
|
|
5493
|
+
r.after = await snapshot(this.cwd);
|
|
5494
|
+
if (r.after) {
|
|
5495
|
+
const top = await this.top();
|
|
5496
|
+
for (const f of await changedFiles(this.cwd, r.before, r.after).catch(() => [])) {
|
|
5497
|
+
const rel2 = import_node_path2.default.relative(this.base, import_node_path2.default.join(top, f.path));
|
|
5498
|
+
if (rel2.startsWith("..") || import_node_path2.default.isAbsolute(rel2)) continue;
|
|
5499
|
+
this.add({ source: "changed", kind: "diff", path: rel2.split(import_node_path2.default.sep).join("/"), added: f.added, removed: f.removed, status: f.status });
|
|
5500
|
+
}
|
|
5501
|
+
}
|
|
5502
|
+
}
|
|
5503
|
+
for (const l of osc8Links(text)) {
|
|
5504
|
+
if (l.uri.startsWith("file://")) {
|
|
5505
|
+
try {
|
|
5506
|
+
this.addFile(decodeURIComponent(new URL(l.uri).pathname.replace(/^\/([A-Za-z]:)/, "$1")), "link", l.text || void 0);
|
|
5507
|
+
} catch {
|
|
5508
|
+
}
|
|
5509
|
+
} else this.addUrl(l.uri, "link", l.text && l.text !== l.uri ? l.text : void 0);
|
|
5510
|
+
}
|
|
5511
|
+
const m = mentions(stripAnsi(text), this.base, this.cwd);
|
|
5512
|
+
for (const u of m.urls) this.addUrl(u, "mentioned");
|
|
5513
|
+
for (const p of m.paths) this.addFile(p, "mentioned");
|
|
5514
|
+
r.done = true;
|
|
5515
|
+
this.onChange();
|
|
5516
|
+
}
|
|
5517
|
+
gitTop;
|
|
5518
|
+
/** The repo's top folder (git names files from there). */
|
|
5519
|
+
async top() {
|
|
5520
|
+
return this.gitTop ??= import_node_path2.default.resolve((await git(this.cwd, ["rev-parse", "--show-toplevel"]).catch(() => this.cwd)).trim());
|
|
5521
|
+
}
|
|
5522
|
+
/** A changed file's diff in round `n` (its path as listed: relative to the session's folder). */
|
|
5523
|
+
async diff(n, rel2) {
|
|
5524
|
+
const r = this.list.find((x) => x.n === n);
|
|
5525
|
+
const item = r?.items.find((i) => i.kind === "diff" && i.path === rel2);
|
|
5526
|
+
if (!r?.before || !r.after || !item) return null;
|
|
5527
|
+
const top = await this.top();
|
|
5528
|
+
return fileDiff(this.cwd, r.before, r.after, ":(top)" + import_node_path2.default.relative(top, import_node_path2.default.join(this.base, rel2)).split(import_node_path2.default.sep).join("/"));
|
|
5529
|
+
}
|
|
5530
|
+
/** For /attachments: newest round first. */
|
|
5531
|
+
view() {
|
|
5532
|
+
return [...this.list].reverse().map((r) => ({ n: r.n, task: r.task, at: r.at, done: r.done, items: r.items }));
|
|
5533
|
+
}
|
|
5534
|
+
};
|
|
5535
|
+
|
|
5536
|
+
// agent-bridge/src/adapters.ts
|
|
5537
|
+
var import_node_crypto = require("node:crypto");
|
|
5538
|
+
var import_node_fs3 = require("node:fs");
|
|
5539
|
+
var import_promises = require("node:fs/promises");
|
|
5540
|
+
var import_node_os2 = __toESM(require("node:os"), 1);
|
|
5541
|
+
var import_node_path3 = __toESM(require("node:path"), 1);
|
|
5542
|
+
var import_node_fs4 = require("node:fs");
|
|
5543
|
+
var MCP_FILES = /* @__PURE__ */ new Set();
|
|
5544
|
+
var cleanup = false;
|
|
5545
|
+
async function mcpConfigFile(servers, name) {
|
|
5546
|
+
const file = import_node_path3.default.join(import_node_os2.default.tmpdir(), `agent-bridge-mcp-${process.pid}-${name.replace(/[^\w-]/g, "")}.json`);
|
|
5547
|
+
const mcpServers = Object.fromEntries(servers.map((s) => [s.name, { type: "http", url: s.url, ...s.headers ? { headers: s.headers } : {} }]));
|
|
5548
|
+
await (0, import_promises.writeFile)(file, JSON.stringify({ mcpServers }, null, 2), { mode: 384 });
|
|
5549
|
+
MCP_FILES.add(file);
|
|
5550
|
+
if (!cleanup) {
|
|
5551
|
+
cleanup = true;
|
|
5552
|
+
process.once("exit", () => {
|
|
5553
|
+
for (const f of MCP_FILES) {
|
|
5554
|
+
try {
|
|
5555
|
+
(0, import_node_fs4.unlinkSync)(f);
|
|
5556
|
+
} catch {
|
|
5557
|
+
}
|
|
5558
|
+
}
|
|
5559
|
+
});
|
|
5560
|
+
}
|
|
5561
|
+
return file;
|
|
5562
|
+
}
|
|
5563
|
+
var baseName = (command) => (command.split(/[\\/]/).pop() ?? "").replace(/\.(exe|cmd|bat|com)$/i, "").toLowerCase();
|
|
5564
|
+
var preamble = (o, name) => {
|
|
5565
|
+
const ignored = [o.model && `model "${o.model}"`, o.effort && `effort "${o.effort}"`].filter(Boolean).join(", ");
|
|
5566
|
+
return {
|
|
5567
|
+
args: o.args,
|
|
5568
|
+
preamble: o.instructions.text,
|
|
5569
|
+
...ignored ? { warning: `${name} takes no model or effort flag: it uses its own config (agent option ${ignored} ignored)` } : {}
|
|
5570
|
+
};
|
|
5571
|
+
};
|
|
5572
|
+
function choices(list) {
|
|
5573
|
+
const out = [], seen = /* @__PURE__ */ new Set();
|
|
5574
|
+
for (const c of list ?? []) {
|
|
5575
|
+
const value = typeof c === "string" ? c : c?.value;
|
|
5576
|
+
if (typeof value !== "string" || !value || seen.has(value)) continue;
|
|
5577
|
+
seen.add(value);
|
|
5578
|
+
out.push(typeof c === "string" || !c.name ? { value } : { value, name: String(c.name) });
|
|
5579
|
+
}
|
|
5580
|
+
return out;
|
|
5581
|
+
}
|
|
5582
|
+
var claudeCode = {
|
|
5583
|
+
id: "claude-code",
|
|
5584
|
+
name: "Claude Code",
|
|
5585
|
+
command: "claude",
|
|
5586
|
+
matches: (command, app) => baseName(command) === "claude" || /^claude/i.test(app ?? ""),
|
|
5587
|
+
menus: true,
|
|
5588
|
+
// `claude --help`: --model takes an alias for the latest model ("fable", "opus", "sonnet") or a full
|
|
5589
|
+
// name (the `model` option); --effort low, medium, high, xhigh or max.
|
|
5590
|
+
models: [{ value: "fable", name: "Fable" }, { value: "opus", name: "Opus" }, { value: "sonnet", name: "Sonnet" }],
|
|
5591
|
+
efforts: [{ value: "low", name: "Low" }, { value: "medium", name: "Medium" }, { value: "high", name: "High" }, { value: "xhigh", name: "Extra high" }, { value: "max", name: "Max" }],
|
|
5592
|
+
async start({ args, model, effort, instructions, mcp }) {
|
|
5593
|
+
const out = [...args];
|
|
5594
|
+
if (model && !args.includes("--model")) out.push("--model", model);
|
|
5595
|
+
if (effort && !args.includes("--effort")) out.push("--effort", effort);
|
|
5596
|
+
if (mcp?.length) out.push("--mcp-config", await mcpConfigFile(mcp, (0, import_node_crypto.createHash)("sha1").update(JSON.stringify(mcp)).digest("hex").slice(0, 12)));
|
|
5597
|
+
if (!instructions.text) return { args: out };
|
|
5598
|
+
let file = instructions.file;
|
|
5599
|
+
if (!file) {
|
|
5600
|
+
file = import_node_path3.default.join(import_node_os2.default.tmpdir(), `agent-bridge-${(0, import_node_crypto.createHash)("sha1").update(instructions.text).digest("hex").slice(0, 12)}.md`);
|
|
5601
|
+
await (0, import_promises.writeFile)(file, instructions.text);
|
|
5602
|
+
}
|
|
5603
|
+
return { args: [...out, "--append-system-prompt-file", file] };
|
|
5604
|
+
}
|
|
5605
|
+
};
|
|
5606
|
+
var openCode = {
|
|
5607
|
+
id: "opencode",
|
|
5608
|
+
name: "OpenCode",
|
|
5609
|
+
command: "opencode",
|
|
5610
|
+
matches: (command, app) => baseName(command) === "opencode" || app === "opencode",
|
|
5611
|
+
// OpenCode 2.2 reports working and idle, never done (anomalyco/opencode#60411), and reports idle
|
|
5612
|
+
// before its input box takes keys (a prompt typed then is lost).
|
|
5613
|
+
doneOnIdle: true,
|
|
5614
|
+
settleMs: 1e3,
|
|
5615
|
+
start: (o) => preamble(o, "OpenCode"),
|
|
5616
|
+
// `opencode acp` (D58): its permission requests become the card's menu, status without screen reading.
|
|
5617
|
+
acp: ["acp"]
|
|
5618
|
+
};
|
|
5619
|
+
var generic = {
|
|
5620
|
+
id: "generic",
|
|
5621
|
+
name: "",
|
|
5622
|
+
command: "claude",
|
|
5623
|
+
matches: () => true,
|
|
5624
|
+
start: (o) => preamble(o, "This CLI")
|
|
5625
|
+
};
|
|
5626
|
+
var BUILT_IN = [claudeCode, openCode];
|
|
5627
|
+
function adapterFor(command, app, extra = [], args) {
|
|
5628
|
+
return [...extra, ...BUILT_IN].find((a) => a.matches(command, app, args)) ?? generic;
|
|
5629
|
+
}
|
|
5630
|
+
function onPath(command, env = process.env, platform = process.platform) {
|
|
5631
|
+
const sep = platform === "win32" ? ";" : ":";
|
|
5632
|
+
const exts = platform === "win32" ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""];
|
|
5633
|
+
const dirs = (env.PATH ?? env.Path ?? "").split(sep).filter(Boolean);
|
|
5634
|
+
return dirs.some((d) => exts.some((e) => {
|
|
5635
|
+
try {
|
|
5636
|
+
return (0, import_node_fs3.statSync)(import_node_path3.default.join(d, command + e)).isFile();
|
|
5637
|
+
} catch {
|
|
5638
|
+
return false;
|
|
5639
|
+
}
|
|
5640
|
+
}));
|
|
5641
|
+
}
|
|
5642
|
+
var commandName = (opts) => opts.label ?? [opts.command ?? "claude", ...opts.args ?? []].map((a, i) => i === 0 || /[\\/]/.test(a) ? import_node_path3.default.basename(a).replace(/\.(exe|cmd|bat|com)$/i, "") : a).join(" ");
|
|
5643
|
+
var installed = (command) => /[\\/]/.test(command) ? (0, import_node_fs3.existsSync)(command) : onPath(command);
|
|
5644
|
+
var MISSING = /* @__PURE__ */ new Set();
|
|
5645
|
+
function cliChoices(opts, has = installed) {
|
|
5646
|
+
const known = [...opts.adapters ?? [], ...BUILT_IN];
|
|
5647
|
+
const args = opts.args ?? [];
|
|
5648
|
+
let list;
|
|
5649
|
+
if (opts.clis?.length) {
|
|
5650
|
+
const given = opts.clis.filter((c) => typeof c === "string" ? !!c : !!c && typeof c.command === "string" && !!c.command).map((c) => typeof c === "string" ? { command: known.find((a) => a.id === c || a.command === c)?.command ?? c, args } : c);
|
|
5651
|
+
list = given.filter((c) => has(c.command));
|
|
5652
|
+
const missing = given.filter((c) => !list.includes(c)).map((c) => c.command).join(", ");
|
|
5653
|
+
if (missing && !MISSING.has(missing)) {
|
|
5654
|
+
MISSING.add(missing);
|
|
5655
|
+
console.warn(`[agent-bridge] clis: not installed, left out of the picker: ${missing}`);
|
|
5656
|
+
}
|
|
5657
|
+
if (!list.length) list = given.slice(0, 1);
|
|
5658
|
+
} else if (opts.command) list = [{ command: opts.command, args, label: opts.label }];
|
|
5659
|
+
else list = known.filter((a) => has(a.command)).map((a) => ({ command: a.command, args }));
|
|
5660
|
+
if (!list.length) list = [{ command: "claude", args }];
|
|
5661
|
+
const out = [], ids = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set();
|
|
5662
|
+
for (const c of list) {
|
|
5663
|
+
const a = c.args ?? [];
|
|
5664
|
+
const key = JSON.stringify([c.command, a]);
|
|
5665
|
+
if (seen.has(key)) continue;
|
|
5666
|
+
seen.add(key);
|
|
5667
|
+
const adapter = adapterFor(c.command, void 0, opts.adapters, a);
|
|
5668
|
+
const base = c.id || (adapter !== generic ? adapter.id : baseName(c.command) || "cli");
|
|
5669
|
+
let id = base;
|
|
5670
|
+
for (let n = 2; ids.has(id); n++) id = `${base}-${n}`;
|
|
5671
|
+
ids.add(id);
|
|
5672
|
+
const name = c.label ?? (adapter !== generic ? adapter.name : commandName({ command: c.command, args: a }));
|
|
5673
|
+
out.push({ id, name, command: c.command, args: a, ...c.label ? { label: c.label } : {}, ...c.env ? { env: c.env } : {} });
|
|
5674
|
+
}
|
|
5675
|
+
return out;
|
|
5676
|
+
}
|
|
5677
|
+
|
|
5678
|
+
// agent-bridge/src/sessions.ts
|
|
5679
|
+
var import_node_crypto2 = require("node:crypto");
|
|
5680
|
+
var import_node_fs5 = require("node:fs");
|
|
5681
|
+
var import_promises3 = require("node:fs/promises");
|
|
5682
|
+
var import_node_url = require("node:url");
|
|
5683
|
+
var import_node_module = require("node:module");
|
|
5684
|
+
var import_node_path5 = __toESM(require("node:path"), 1);
|
|
5685
|
+
|
|
5686
|
+
// agent-bridge/src/program-status.ts
|
|
5126
5687
|
var PROBE_REPLY = "\x1B]7501;?\x1B\\";
|
|
5127
5688
|
var MAX_SEQUENCE = 4096;
|
|
5128
5689
|
var MAX_KEY = 16;
|
|
@@ -5282,7 +5843,7 @@ var OscScanner = class {
|
|
|
5282
5843
|
}
|
|
5283
5844
|
};
|
|
5284
5845
|
|
|
5285
|
-
// agent/src/screen.ts
|
|
5846
|
+
// agent-bridge/src/screen.ts
|
|
5286
5847
|
var import_headless = __toESM(require_xterm_headless(), 1);
|
|
5287
5848
|
var { Terminal } = import_headless.default;
|
|
5288
5849
|
var OPTION = /^(\s*)([❯›▶>]\s*)?(\d{1,2})[.)]\s+(.*\S)\s*$/;
|
|
@@ -5346,158 +5907,952 @@ function numbered(L, end) {
|
|
|
5346
5907
|
desc.push(t.trim());
|
|
5347
5908
|
continue;
|
|
5348
5909
|
}
|
|
5349
|
-
break;
|
|
5910
|
+
break;
|
|
5911
|
+
}
|
|
5912
|
+
return rows.length >= 2 && rows[0].n === 1 && rows.some((r) => r.selected) ? rows : null;
|
|
5913
|
+
}
|
|
5914
|
+
function unnumbered(L, hintAt) {
|
|
5915
|
+
let c = -1;
|
|
5916
|
+
for (let i = hintAt - 1; i >= Math.max(0, hintAt - 12); i--) if (/^\s*[❯›]\s+\S/.test(L[i].text)) {
|
|
5917
|
+
c = i;
|
|
5918
|
+
break;
|
|
5919
|
+
}
|
|
5920
|
+
if (c < 0) return null;
|
|
5921
|
+
const mark = L[c].text.search(/[❯›]/), col = mark + 1 + L[c].text.slice(mark + 1).search(/\S/);
|
|
5922
|
+
const isRow = (i) => i === c || !!L[i].text.trim() && L[i].text.search(/\S/) === col;
|
|
5923
|
+
let a = c, b = c;
|
|
5924
|
+
while (a > 0 && isRow(a - 1)) a--;
|
|
5925
|
+
while (b + 1 < hintAt && isRow(b + 1)) b++;
|
|
5926
|
+
if (b === a) return null;
|
|
5927
|
+
return L.slice(a, b + 1).map((l, k) => ({ i: a + k, label: (k + a === c ? l.text.slice(col) : l.text).trim(), selected: k + a === c, desc: [] }));
|
|
5928
|
+
}
|
|
5929
|
+
function parseSteps(line) {
|
|
5930
|
+
const inner = STEPS.exec(line.text)[1];
|
|
5931
|
+
const parts = inner.split(/\s{2,}/).filter(Boolean);
|
|
5932
|
+
const lit = (line.spans ?? []).filter((s) => s.bg && s.t.trim()).map((s) => s.t.trim());
|
|
5933
|
+
return parts.map((p) => {
|
|
5934
|
+
const state = p.startsWith("\u2612") ? "done" : p.startsWith("\u2714") ? "submit" : "todo";
|
|
5935
|
+
const label = p.replace(/^[☐☒✔✓]\s*/, "");
|
|
5936
|
+
return { label, state, current: lit.some((t) => t.includes(label)) };
|
|
5937
|
+
});
|
|
5938
|
+
}
|
|
5939
|
+
function trimEnd(lines) {
|
|
5940
|
+
let n = lines.length;
|
|
5941
|
+
while (n && !lines[n - 1].text.trim()) n--;
|
|
5942
|
+
return lines.slice(0, n);
|
|
5943
|
+
}
|
|
5944
|
+
var Screen = class {
|
|
5945
|
+
term;
|
|
5946
|
+
constructor(cols, rows) {
|
|
5947
|
+
this.term = new Terminal({ cols, rows, scrollback: 200, allowProposedApi: true });
|
|
5948
|
+
}
|
|
5949
|
+
pending = 0;
|
|
5950
|
+
waiters = [];
|
|
5951
|
+
/** Parsed asynchronously: `settled()` waits until everything written so far is on the screen. */
|
|
5952
|
+
write(d) {
|
|
5953
|
+
this.pending++;
|
|
5954
|
+
this.term.write(d, () => {
|
|
5955
|
+
if (--this.pending === 0) this.waiters.splice(0).forEach((w) => w());
|
|
5956
|
+
});
|
|
5957
|
+
}
|
|
5958
|
+
settled() {
|
|
5959
|
+
return this.pending ? new Promise((r) => this.waiters.push(r)) : Promise.resolve();
|
|
5960
|
+
}
|
|
5961
|
+
/** Writes not on the screen yet. */
|
|
5962
|
+
get busy() {
|
|
5963
|
+
return this.pending > 0;
|
|
5964
|
+
}
|
|
5965
|
+
resize(cols, rows) {
|
|
5966
|
+
try {
|
|
5967
|
+
this.term.resize(cols, rows);
|
|
5968
|
+
} catch {
|
|
5969
|
+
}
|
|
5970
|
+
}
|
|
5971
|
+
reset() {
|
|
5972
|
+
this.term.reset();
|
|
5973
|
+
}
|
|
5974
|
+
dispose() {
|
|
5975
|
+
this.term.dispose();
|
|
5976
|
+
}
|
|
5977
|
+
/** The visible rows, with colour runs. */
|
|
5978
|
+
lines() {
|
|
5979
|
+
const b = this.term.buffer.active, out = [];
|
|
5980
|
+
const cell = b.getNullCell();
|
|
5981
|
+
for (let y = b.baseY; y < b.baseY + this.term.rows; y++) {
|
|
5982
|
+
const line = b.getLine(y);
|
|
5983
|
+
if (!line) {
|
|
5984
|
+
out.push({ text: "" });
|
|
5985
|
+
continue;
|
|
5986
|
+
}
|
|
5987
|
+
const text = line.translateToString(true);
|
|
5988
|
+
const spans = [];
|
|
5989
|
+
let cur = null;
|
|
5990
|
+
for (let x = 0; x < text.length && x < line.length; x++) {
|
|
5991
|
+
line.getCell(x, cell);
|
|
5992
|
+
const ch = cell.getChars() || (cell.getWidth() === 0 ? "" : " ");
|
|
5993
|
+
if (!ch && cell.getWidth() === 0) continue;
|
|
5994
|
+
let fg = colour(cell.isFgRGB(), cell.isFgPalette(), cell.getFgColor());
|
|
5995
|
+
let bg = colour(cell.isBgRGB(), cell.isBgPalette(), cell.getBgColor());
|
|
5996
|
+
if (cell.isInverse()) [fg, bg] = [bg ?? "#131316", fg ?? "#ececf1"];
|
|
5997
|
+
const s = { t: ch, ...fg ? { fg } : {}, ...bg ? { bg } : {}, ...cell.isBold() ? { b: true } : {}, ...cell.isDim() ? { dim: true } : {} };
|
|
5998
|
+
if (cur && cur.fg === s.fg && cur.bg === s.bg && cur.b === s.b && cur.dim === s.dim) cur.t += ch;
|
|
5999
|
+
else {
|
|
6000
|
+
cur = s;
|
|
6001
|
+
spans.push(s);
|
|
6002
|
+
}
|
|
6003
|
+
}
|
|
6004
|
+
out.push({ text, spans });
|
|
6005
|
+
}
|
|
6006
|
+
return out;
|
|
6007
|
+
}
|
|
6008
|
+
/** The menu on screen now, if any. */
|
|
6009
|
+
prompt() {
|
|
6010
|
+
return parsePrompt(this.lines());
|
|
6011
|
+
}
|
|
6012
|
+
};
|
|
6013
|
+
var ANSI = [
|
|
6014
|
+
"#1c1c21",
|
|
6015
|
+
"#ff5c57",
|
|
6016
|
+
"#5af78e",
|
|
6017
|
+
"#f3f99d",
|
|
6018
|
+
"#57c7ff",
|
|
6019
|
+
"#ff6ac1",
|
|
6020
|
+
"#9aedfe",
|
|
6021
|
+
"#c7c7cf",
|
|
6022
|
+
"#686868",
|
|
6023
|
+
"#ff6e67",
|
|
6024
|
+
"#5ffa68",
|
|
6025
|
+
"#fffc67",
|
|
6026
|
+
"#6871ff",
|
|
6027
|
+
"#ff77ff",
|
|
6028
|
+
"#60fdff",
|
|
6029
|
+
"#ffffff"
|
|
6030
|
+
];
|
|
6031
|
+
function colour(rgb, palette, v) {
|
|
6032
|
+
if (rgb) return `#${v.toString(16).padStart(6, "0")}`;
|
|
6033
|
+
if (!palette) return void 0;
|
|
6034
|
+
if (v < 16) return ANSI[v];
|
|
6035
|
+
if (v < 232) {
|
|
6036
|
+
const c = v - 16, k = [0, 95, 135, 175, 215, 255];
|
|
6037
|
+
return `rgb(${k[Math.floor(c / 36)]},${k[Math.floor(c / 6) % 6]},${k[c % 6]})`;
|
|
6038
|
+
}
|
|
6039
|
+
const g2 = 8 + (v - 232) * 10;
|
|
6040
|
+
return `rgb(${g2},${g2},${g2})`;
|
|
6041
|
+
}
|
|
6042
|
+
|
|
6043
|
+
// agent-bridge/src/acp.ts
|
|
6044
|
+
var import_node_child_process3 = require("node:child_process");
|
|
6045
|
+
var import_promises2 = require("node:fs/promises");
|
|
6046
|
+
var import_node_path4 = __toESM(require("node:path"), 1);
|
|
6047
|
+
var ACP_PROTOCOL_VERSION = 1;
|
|
6048
|
+
var CLIENT_INFO = { name: "agent-bridge", title: "Agent bridge", version: "0" };
|
|
6049
|
+
var MAX_SCROLLBACK = 512 * 1024;
|
|
6050
|
+
var MAX_SENT = 500;
|
|
6051
|
+
var HANDSHAKE_MS = 6e4;
|
|
6052
|
+
var JsonRpc = class {
|
|
6053
|
+
next = 1;
|
|
6054
|
+
pending = /* @__PURE__ */ new Map();
|
|
6055
|
+
buf = "";
|
|
6056
|
+
closed = false;
|
|
6057
|
+
onRequest = () => {
|
|
6058
|
+
throw Object.assign(new Error("method not found"), { code: -32601 });
|
|
6059
|
+
};
|
|
6060
|
+
onNotification = () => {
|
|
6061
|
+
};
|
|
6062
|
+
write;
|
|
6063
|
+
constructor(write) {
|
|
6064
|
+
this.write = write;
|
|
6065
|
+
}
|
|
6066
|
+
feed(chunk) {
|
|
6067
|
+
this.buf += chunk;
|
|
6068
|
+
let i;
|
|
6069
|
+
while ((i = this.buf.indexOf("\n")) >= 0) {
|
|
6070
|
+
const line = this.buf.slice(0, i).trim();
|
|
6071
|
+
this.buf = this.buf.slice(i + 1);
|
|
6072
|
+
if (line) this.message(line);
|
|
6073
|
+
}
|
|
6074
|
+
if (this.buf.length > 16 * 1024 * 1024) this.buf = "";
|
|
6075
|
+
}
|
|
6076
|
+
message(line) {
|
|
6077
|
+
let m;
|
|
6078
|
+
try {
|
|
6079
|
+
m = JSON.parse(line);
|
|
6080
|
+
} catch {
|
|
6081
|
+
return;
|
|
6082
|
+
}
|
|
6083
|
+
if (!m || typeof m !== "object") return;
|
|
6084
|
+
const hasId = m.id !== void 0 && m.id !== null;
|
|
6085
|
+
if (typeof m.method === "string") {
|
|
6086
|
+
if (!hasId) {
|
|
6087
|
+
try {
|
|
6088
|
+
this.onNotification(m.method, m.params ?? {});
|
|
6089
|
+
} catch {
|
|
6090
|
+
}
|
|
6091
|
+
return;
|
|
6092
|
+
}
|
|
6093
|
+
void (async () => {
|
|
6094
|
+
try {
|
|
6095
|
+
this.send({ jsonrpc: "2.0", id: m.id, result: await this.onRequest(m.method, m.params ?? {}, m.id) ?? null });
|
|
6096
|
+
} catch (e) {
|
|
6097
|
+
this.send({ jsonrpc: "2.0", id: m.id, error: { code: e.code ?? -32603, message: e.message } });
|
|
6098
|
+
}
|
|
6099
|
+
})();
|
|
6100
|
+
return;
|
|
6101
|
+
}
|
|
6102
|
+
if (!hasId) return;
|
|
6103
|
+
const p = this.pending.get(m.id);
|
|
6104
|
+
if (!p) return;
|
|
6105
|
+
this.pending.delete(m.id);
|
|
6106
|
+
if (m.error) p.reject(Object.assign(new Error(String(m.error.message ?? "error")), { code: m.error.code, data: m.error.data }));
|
|
6107
|
+
else p.resolve(m.result);
|
|
6108
|
+
}
|
|
6109
|
+
request(method, params, timeoutMs = 0) {
|
|
6110
|
+
if (this.closed) return Promise.reject(new Error("the agent has exited"));
|
|
6111
|
+
const id = this.next++;
|
|
6112
|
+
return new Promise((resolve, reject) => {
|
|
6113
|
+
let timer;
|
|
6114
|
+
if (timeoutMs) timer = setTimeout(() => {
|
|
6115
|
+
this.pending.delete(id);
|
|
6116
|
+
reject(new Error(`no answer to ${method} in ${Math.round(timeoutMs / 1e3)} s`));
|
|
6117
|
+
}, timeoutMs);
|
|
6118
|
+
this.pending.set(id, { resolve: (v) => {
|
|
6119
|
+
clearTimeout(timer);
|
|
6120
|
+
resolve(v);
|
|
6121
|
+
}, reject: (e) => {
|
|
6122
|
+
clearTimeout(timer);
|
|
6123
|
+
reject(e);
|
|
6124
|
+
} });
|
|
6125
|
+
this.send({ jsonrpc: "2.0", id, method, params });
|
|
6126
|
+
});
|
|
6127
|
+
}
|
|
6128
|
+
notify(method, params) {
|
|
6129
|
+
if (!this.closed) this.send({ jsonrpc: "2.0", method, params });
|
|
6130
|
+
}
|
|
6131
|
+
send(m) {
|
|
6132
|
+
try {
|
|
6133
|
+
this.write(JSON.stringify(m) + "\n");
|
|
6134
|
+
} catch {
|
|
6135
|
+
}
|
|
6136
|
+
}
|
|
6137
|
+
/** The agent exited: every request still waiting fails. */
|
|
6138
|
+
close(reason) {
|
|
6139
|
+
this.closed = true;
|
|
6140
|
+
for (const p of this.pending.values()) p.reject(new Error(reason));
|
|
6141
|
+
this.pending.clear();
|
|
6142
|
+
}
|
|
6143
|
+
};
|
|
6144
|
+
var C = { dim: "\x1B[2m", bold: "\x1B[1m", cyan: "\x1B[36m", yellow: "\x1B[33m", green: "\x1B[32m", red: "\x1B[31m", orange: "\x1B[38;5;214m", reset: "\x1B[0m" };
|
|
6145
|
+
var crlf = (s) => s.replace(/\r?\n/g, "\r\n");
|
|
6146
|
+
var oneLine = (s, max = 200) => {
|
|
6147
|
+
const t = s.replace(/\s+/g, " ").trim();
|
|
6148
|
+
return t.length > max ? t.slice(0, max - 1) + "\u2026" : t;
|
|
6149
|
+
};
|
|
6150
|
+
var CONTROL = /[\x00-\x08\x0b-\x1f\x7f]/g;
|
|
6151
|
+
function usesAcp(opts) {
|
|
6152
|
+
if (opts.protocol) return opts.protocol === "acp";
|
|
6153
|
+
return !!adapterFor(opts.command ?? "claude", void 0, opts.adapters, opts.args).acp;
|
|
6154
|
+
}
|
|
6155
|
+
function permissionView(params) {
|
|
6156
|
+
const tc = params.toolCall ?? {};
|
|
6157
|
+
const lines = [];
|
|
6158
|
+
const raw = tc.rawInput && typeof tc.rawInput === "object" ? tc.rawInput : {};
|
|
6159
|
+
for (const c of Array.isArray(tc.content) ? tc.content : []) {
|
|
6160
|
+
if (c?.type === "diff" && typeof c.path === "string") {
|
|
6161
|
+
lines.push([{ t: c.path, b: true }]);
|
|
6162
|
+
for (const l of String(c.oldText ?? "").split("\n").slice(0, 12)) if (c.oldText) lines.push([{ t: `- ${l}`, fg: "#ffb3b3", bg: "#4b1d1d" }]);
|
|
6163
|
+
for (const l of String(c.newText ?? "").split("\n").slice(0, 12)) lines.push([{ t: `+ ${l}`, fg: "#b3f0c8", bg: "#173b25" }]);
|
|
6164
|
+
} else if (c?.type === "content" && c.content?.type === "text" && c.content.text) {
|
|
6165
|
+
for (const l of String(c.content.text).split("\n").slice(0, 12)) lines.push([{ t: l }]);
|
|
6166
|
+
}
|
|
6167
|
+
}
|
|
6168
|
+
if (!lines.length && typeof raw.command === "string") lines.push([{ t: `$ ${raw.command}` }]);
|
|
6169
|
+
for (const loc of Array.isArray(tc.locations) ? tc.locations.slice(0, 3) : []) if (typeof loc?.path === "string" && !lines.length) lines.push([{ t: loc.path, dim: true }]);
|
|
6170
|
+
const kind = typeof tc.kind === "string" && tc.kind !== "other" ? tc.kind : "";
|
|
6171
|
+
const title = typeof tc.title === "string" && tc.title ? tc.title : typeof tc.name === "string" ? tc.name : "a tool";
|
|
6172
|
+
const options = (Array.isArray(params.options) ? params.options : []).map((o) => ({
|
|
6173
|
+
label: String(o.name ?? o.optionId),
|
|
6174
|
+
selected: false,
|
|
6175
|
+
...o.kind === "allow_always" ? { description: "Allowed from now on in this session" } : o.kind === "reject_always" ? { description: "Refused from now on in this session" } : {}
|
|
6176
|
+
}));
|
|
6177
|
+
return { lines: lines.slice(0, 30), question: `Allow ${kind ? `${kind}: ` : ""}${title}?`, options, hint: "Cancel ends the turn" };
|
|
6178
|
+
}
|
|
6179
|
+
var AcpSession = class {
|
|
6180
|
+
child = null;
|
|
6181
|
+
rpc = null;
|
|
6182
|
+
starting = null;
|
|
6183
|
+
sessionId = "";
|
|
6184
|
+
scrollback = "";
|
|
6185
|
+
viewers = /* @__PURE__ */ new Set();
|
|
6186
|
+
lastStatus = "";
|
|
6187
|
+
state = "idle";
|
|
6188
|
+
msg;
|
|
6189
|
+
exitCode;
|
|
6190
|
+
stopping = false;
|
|
6191
|
+
stderr = "";
|
|
6192
|
+
queued = [];
|
|
6193
|
+
turn = null;
|
|
6194
|
+
permission = null;
|
|
6195
|
+
tools = /* @__PURE__ */ new Map();
|
|
6196
|
+
said = "";
|
|
6197
|
+
// the agent's text this turn (the done message is its last line)
|
|
6198
|
+
atLineStart = true;
|
|
6199
|
+
line = "";
|
|
6200
|
+
// typed in the CLI window, sent on Enter
|
|
6201
|
+
sent = /* @__PURE__ */ new Set();
|
|
6202
|
+
preamble = "";
|
|
6203
|
+
agentName;
|
|
6204
|
+
opts;
|
|
6205
|
+
/** Where the agent runs: the project's cwd, or the same folder in its worktree (D64). */
|
|
6206
|
+
cwd;
|
|
6207
|
+
/** Set up before the CLI first starts (D64: its worktree, which also moves `cwd`). */
|
|
6208
|
+
prepare;
|
|
6209
|
+
/** Its git worktree (D64), once prepared. */
|
|
6210
|
+
worktree;
|
|
6211
|
+
/** The host's MCP servers for this session (D66), asked for at start. */
|
|
6212
|
+
mcp;
|
|
6213
|
+
/** What it says it is on now (D66: MCP `working_on`); cleared when its turn is done. */
|
|
6214
|
+
focus;
|
|
6215
|
+
/** Its rounds and what it pointed at in each (D56). */
|
|
6216
|
+
rounds;
|
|
6217
|
+
/** The label of the next round (the prompt's `task`). */
|
|
6218
|
+
nextTask;
|
|
6219
|
+
root;
|
|
6220
|
+
id;
|
|
6221
|
+
label;
|
|
6222
|
+
/** The CLI's id in the picker (D59). */
|
|
6223
|
+
cli;
|
|
6224
|
+
/** What the agent offered in `session/new` (its models and effort levels, D62): the toolbar's settings list them. */
|
|
6225
|
+
onOffer;
|
|
6226
|
+
/** The tab's name and the prompt that started it (D62), set by the first prompt that names them. */
|
|
6227
|
+
title;
|
|
6228
|
+
task;
|
|
6229
|
+
onChange;
|
|
6230
|
+
constructor(opts, cwd, root, n, onChange, cli = "") {
|
|
6231
|
+
this.opts = opts;
|
|
6232
|
+
this.cwd = cwd;
|
|
6233
|
+
this.root = root;
|
|
6234
|
+
this.id = `s${n}`;
|
|
6235
|
+
this.label = `#${n}`;
|
|
6236
|
+
this.onChange = onChange;
|
|
6237
|
+
this.cli = cli;
|
|
6238
|
+
this.rounds = new Rounds(root, cwd, () => this.pushStatus());
|
|
6239
|
+
}
|
|
6240
|
+
get running() {
|
|
6241
|
+
return !!this.child || !!this.starting;
|
|
6242
|
+
}
|
|
6243
|
+
get resting() {
|
|
6244
|
+
return !!this.child && !this.turn && !this.queued.length && this.state !== "working" && this.state !== "blocked";
|
|
6245
|
+
}
|
|
6246
|
+
get command() {
|
|
6247
|
+
return commandName(this.opts);
|
|
6248
|
+
}
|
|
6249
|
+
get adapter() {
|
|
6250
|
+
return adapterFor(this.opts.command ?? "claude", void 0, this.opts.adapters, this.opts.args);
|
|
6251
|
+
}
|
|
6252
|
+
info() {
|
|
6253
|
+
const status2 = {
|
|
6254
|
+
state: this.state,
|
|
6255
|
+
...this.state === "blocked" ? { kind: "permission" } : {},
|
|
6256
|
+
...this.msg ? { msg: this.msg } : {},
|
|
6257
|
+
records: this.child ? 1 : 0,
|
|
6258
|
+
source: this.child ? "acp" : "none"
|
|
6259
|
+
};
|
|
6260
|
+
return {
|
|
6261
|
+
id: this.id,
|
|
6262
|
+
label: this.label,
|
|
6263
|
+
running: !!this.child,
|
|
6264
|
+
...this.agentName ? { app: this.agentName } : {},
|
|
6265
|
+
command: this.command,
|
|
6266
|
+
cli: this.cli,
|
|
6267
|
+
exitCode: this.exitCode,
|
|
6268
|
+
status: status2,
|
|
6269
|
+
sent: [...this.sent],
|
|
6270
|
+
...this.child && this.permission ? { prompt: this.permission.view } : {},
|
|
6271
|
+
protocol: "acp",
|
|
6272
|
+
...meta(this)
|
|
6273
|
+
};
|
|
6274
|
+
}
|
|
6275
|
+
/** The `instructions` option's text, read at every start (a file's edits apply to the next session). */
|
|
6276
|
+
async instructions() {
|
|
6277
|
+
const o = this.opts.instructions;
|
|
6278
|
+
if (!o) return "";
|
|
6279
|
+
if (typeof o === "string") return o.trim();
|
|
6280
|
+
const file = import_node_path4.default.resolve(this.root, o.file);
|
|
6281
|
+
try {
|
|
6282
|
+
return (await (0, import_promises2.readFile)(file, "utf8")).trim();
|
|
6283
|
+
} catch {
|
|
6284
|
+
console.warn(`[agent-bridge] instructions: can't read ${file}`);
|
|
6285
|
+
return "";
|
|
6286
|
+
}
|
|
6287
|
+
}
|
|
6288
|
+
/** Spawn the agent, `initialize`, `session/new`, and the model when asked for. */
|
|
6289
|
+
async start(_cols, _rows) {
|
|
6290
|
+
if (this.child) return;
|
|
6291
|
+
if (this.starting) return this.starting;
|
|
6292
|
+
this.starting = (async () => {
|
|
6293
|
+
await this.prepare?.();
|
|
6294
|
+
const command = this.opts.command ?? "claude";
|
|
6295
|
+
const args = [...this.adapter.acp ?? [], ...this.opts.args ?? []];
|
|
6296
|
+
const env = { ...process.env, ...this.opts.env };
|
|
6297
|
+
const target = resolveCommand(command, args, env);
|
|
6298
|
+
if (!target) throw new Error(`"${command}" was not found on PATH`);
|
|
6299
|
+
this.preamble = await this.instructions();
|
|
6300
|
+
this.scrollback = "";
|
|
6301
|
+
this.stderr = "";
|
|
6302
|
+
this.exitCode = void 0;
|
|
6303
|
+
this.stopping = false;
|
|
6304
|
+
this.state = "idle";
|
|
6305
|
+
this.msg = void 0;
|
|
6306
|
+
this.tools.clear();
|
|
6307
|
+
this.permission = null;
|
|
6308
|
+
this.atLineStart = true;
|
|
6309
|
+
this.line = "";
|
|
6310
|
+
const child = (0, import_node_child_process3.spawn)(target.file, target.args, { cwd: this.cwd, env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, detached: process.platform !== "win32" });
|
|
6311
|
+
const rpc = new JsonRpc((line) => child.stdin.write(line));
|
|
6312
|
+
this.child = child;
|
|
6313
|
+
this.rpc = rpc;
|
|
6314
|
+
child.stdout.setEncoding("utf8");
|
|
6315
|
+
child.stdout.on("data", (d) => rpc.feed(d));
|
|
6316
|
+
child.stderr.setEncoding("utf8");
|
|
6317
|
+
child.stderr.on("data", (d) => {
|
|
6318
|
+
this.stderr = (this.stderr + d).slice(-4e3);
|
|
6319
|
+
});
|
|
6320
|
+
child.stdin.on("error", () => {
|
|
6321
|
+
});
|
|
6322
|
+
const spawned = new Promise((resolve, reject) => {
|
|
6323
|
+
child.once("spawn", resolve);
|
|
6324
|
+
child.once("error", reject);
|
|
6325
|
+
});
|
|
6326
|
+
child.on("error", () => {
|
|
6327
|
+
});
|
|
6328
|
+
child.once("exit", (code) => this.exited(child, code));
|
|
6329
|
+
rpc.onNotification = (method, params) => {
|
|
6330
|
+
if (method === "session/update" && params.sessionId === this.sessionId) this.update(params.update ?? {});
|
|
6331
|
+
};
|
|
6332
|
+
rpc.onRequest = (method, params) => this.request(method, params);
|
|
6333
|
+
this.broadcast("start", this.info());
|
|
6334
|
+
this.print(`${C.dim}${this.command}: Agent Client Protocol, starting\u2026${C.reset}\r
|
|
6335
|
+
`);
|
|
6336
|
+
try {
|
|
6337
|
+
await spawned;
|
|
6338
|
+
const init = await rpc.request("initialize", {
|
|
6339
|
+
protocolVersion: ACP_PROTOCOL_VERSION,
|
|
6340
|
+
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
|
6341
|
+
clientInfo: CLIENT_INFO
|
|
6342
|
+
}, HANDSHAKE_MS);
|
|
6343
|
+
const ai = init?.agentInfo;
|
|
6344
|
+
this.agentName = typeof ai?.name === "string" ? ai.name : void 0;
|
|
6345
|
+
const servers = init?.agentCapabilities?.mcpCapabilities?.http ? (this.mcp?.() ?? []).map((m) => ({ type: "http", name: m.name, url: m.url, headers: Object.entries(m.headers ?? {}).map(([name, value]) => ({ name, value })) })) : [];
|
|
6346
|
+
const s = await rpc.request("session/new", { cwd: this.cwd, mcpServers: servers }, HANDSHAKE_MS);
|
|
6347
|
+
if (typeof s?.sessionId !== "string") throw new Error("session/new returned no sessionId");
|
|
6348
|
+
this.sessionId = s.sessionId;
|
|
6349
|
+
this.onOffer?.(offerOf(s));
|
|
6350
|
+
await this.setModel(s);
|
|
6351
|
+
this.print(`${C.dim}${[this.agentName, ai?.version].filter(Boolean).join(" ") || this.command} ready. Type a prompt and press Enter.${C.reset}\r
|
|
6352
|
+
`);
|
|
6353
|
+
this.pushStatus();
|
|
6354
|
+
} catch (e) {
|
|
6355
|
+
const err = e;
|
|
6356
|
+
const why = err.code === -32e3 ? `${err.message} (log the CLI in first, in a terminal)` : err.message;
|
|
6357
|
+
this.fail(child, why);
|
|
6358
|
+
throw new Error(`${this.command} (ACP): ${why}`);
|
|
6359
|
+
}
|
|
6360
|
+
})();
|
|
6361
|
+
try {
|
|
6362
|
+
await this.starting;
|
|
6363
|
+
} finally {
|
|
6364
|
+
this.starting = null;
|
|
6365
|
+
}
|
|
6366
|
+
}
|
|
6367
|
+
/**
|
|
6368
|
+
* The `model` and `effort` options (D62): the agent's `model` and `thought_level` config options
|
|
6369
|
+
* (`session/set_config_option`), or for the model the older `models` list (`session/set_model`); a
|
|
6370
|
+
* value it doesn't offer, or an agent with neither: a warning.
|
|
6371
|
+
*/
|
|
6372
|
+
async setModel(s) {
|
|
6373
|
+
const warn = (w) => {
|
|
6374
|
+
console.warn(`[agent-bridge] ${w}`);
|
|
6375
|
+
this.print(`${C.yellow}${w}${C.reset}\r
|
|
6376
|
+
`);
|
|
6377
|
+
};
|
|
6378
|
+
for (const [what, value] of [["model", this.opts.model], ["effort", this.opts.effort]]) {
|
|
6379
|
+
if (!value || !this.rpc) continue;
|
|
6380
|
+
const cfg = configOption(s.configOptions, what);
|
|
6381
|
+
try {
|
|
6382
|
+
if (cfg) {
|
|
6383
|
+
const opt = flatOptions(cfg).find((o) => o?.value === value || o?.name === value);
|
|
6384
|
+
if (!opt) {
|
|
6385
|
+
warn(`${this.command} doesn't offer the ${what} "${value}" (it uses ${cfg.currentValue})`);
|
|
6386
|
+
continue;
|
|
6387
|
+
}
|
|
6388
|
+
if (opt.value !== cfg.currentValue) await this.rpc.request("session/set_config_option", { sessionId: this.sessionId, configId: cfg.id, value: opt.value }, HANDSHAKE_MS);
|
|
6389
|
+
continue;
|
|
6390
|
+
}
|
|
6391
|
+
const models = s.models;
|
|
6392
|
+
if (what === "model" && Array.isArray(models?.availableModels)) {
|
|
6393
|
+
const m = models.availableModels.find((x) => x?.modelId === value || x?.name === value);
|
|
6394
|
+
if (!m) {
|
|
6395
|
+
warn(`${this.command} doesn't offer the model "${value}" (it uses ${models.currentModelId})`);
|
|
6396
|
+
continue;
|
|
6397
|
+
}
|
|
6398
|
+
if (m.modelId !== models.currentModelId) await this.rpc.request("session/set_model", { sessionId: this.sessionId, modelId: m.modelId }, HANDSHAKE_MS);
|
|
6399
|
+
continue;
|
|
6400
|
+
}
|
|
6401
|
+
warn(`${this.command} offers no ${what} choice over ACP: it uses its own config (agent option ${what} "${value}" ignored)`);
|
|
6402
|
+
} catch (e) {
|
|
6403
|
+
warn(`couldn't set the ${what} "${value}": ${e.message}`);
|
|
6404
|
+
}
|
|
6405
|
+
}
|
|
6406
|
+
}
|
|
6407
|
+
/** The agent's requests to the client: permission only (no fs or terminal capabilities were offered). */
|
|
6408
|
+
request(method, params) {
|
|
6409
|
+
if (method !== "session/request_permission") throw Object.assign(new Error(`${method} is not supported by this client`), { code: -32601 });
|
|
6410
|
+
const options = Array.isArray(params.options) ? params.options : [];
|
|
6411
|
+
if (!this.turn || !options.length) return { outcome: { outcome: "cancelled" } };
|
|
6412
|
+
const view = permissionView(params);
|
|
6413
|
+
this.print(`\r
|
|
6414
|
+
${C.orange}? ${view.question}${C.reset} ${C.dim}(${options.map((o) => o.name).join(" / ")})${C.reset}\r
|
|
6415
|
+
`);
|
|
6416
|
+
this.permission?.resolve({ outcome: "cancelled" });
|
|
6417
|
+
return new Promise((resolve) => {
|
|
6418
|
+
this.permission = {
|
|
6419
|
+
view,
|
|
6420
|
+
options,
|
|
6421
|
+
resolve: (outcome) => {
|
|
6422
|
+
if (this.permission?.view !== view) return;
|
|
6423
|
+
this.permission = null;
|
|
6424
|
+
if (this.state === "blocked") {
|
|
6425
|
+
this.state = "working";
|
|
6426
|
+
this.msg = view.question;
|
|
6427
|
+
}
|
|
6428
|
+
resolve({ outcome });
|
|
6429
|
+
this.pushStatus();
|
|
6430
|
+
}
|
|
6431
|
+
};
|
|
6432
|
+
this.state = "blocked";
|
|
6433
|
+
this.msg = view.question;
|
|
6434
|
+
this.pushStatus();
|
|
6435
|
+
});
|
|
6436
|
+
}
|
|
6437
|
+
/** `session/update`: the transcript, and the message the toolbar shows while it works. */
|
|
6438
|
+
update(u) {
|
|
6439
|
+
switch (u.sessionUpdate) {
|
|
6440
|
+
case "agent_message_chunk": {
|
|
6441
|
+
this.content(u.content);
|
|
6442
|
+
const t = u.content?.type === "text" ? String(u.content.text ?? "") : "";
|
|
6443
|
+
if (!t) return;
|
|
6444
|
+
this.said += t;
|
|
6445
|
+
this.rounds.feed(t);
|
|
6446
|
+
this.text(t);
|
|
6447
|
+
return;
|
|
6448
|
+
}
|
|
6449
|
+
case "agent_thought_chunk": {
|
|
6450
|
+
const t = u.content?.type === "text" ? String(u.content.text ?? "") : "";
|
|
6451
|
+
if (t) this.text(t, C.dim);
|
|
6452
|
+
return;
|
|
6453
|
+
}
|
|
6454
|
+
case "tool_call":
|
|
6455
|
+
case "tool_call_update": {
|
|
6456
|
+
const id = String(u.toolCallId ?? "");
|
|
6457
|
+
const was = this.tools.get(id);
|
|
6458
|
+
const title = typeof u.title === "string" && u.title ? u.title : was?.title ?? "tool";
|
|
6459
|
+
const status2 = typeof u.status === "string" ? u.status : was?.status ?? "pending";
|
|
6460
|
+
this.tools.set(id, { title, status: status2 });
|
|
6461
|
+
for (const loc of Array.isArray(u.locations) ? u.locations.slice(0, 20) : []) if (typeof loc?.path === "string") this.rounds.addFile(loc.path, "explicit");
|
|
6462
|
+
for (const c of Array.isArray(u.content) ? u.content.slice(0, 20) : []) {
|
|
6463
|
+
if (c?.type === "diff" && typeof c.path === "string") this.rounds.addFile(c.path, "explicit");
|
|
6464
|
+
else if (c?.type === "content") this.content(c.content);
|
|
6465
|
+
}
|
|
6466
|
+
if (this.tools.size > 200) this.tools.delete(this.tools.keys().next().value);
|
|
6467
|
+
if (was && was.title === title && was.status === status2) return;
|
|
6468
|
+
if (status2 === "completed" || status2 === "failed") {
|
|
6469
|
+
if (was && (was.status === "completed" || was.status === "failed")) return;
|
|
6470
|
+
this.newline();
|
|
6471
|
+
this.print(status2 === "failed" ? `${C.red}\u2717 ${title}${C.reset}\r
|
|
6472
|
+
` : `${C.green}\u2713${C.reset} ${C.dim}${title}${C.reset}\r
|
|
6473
|
+
`);
|
|
6474
|
+
} else if (!was || was.title !== title) {
|
|
6475
|
+
this.newline();
|
|
6476
|
+
this.print(`${C.yellow}\u23FA ${title}${C.reset}\r
|
|
6477
|
+
`);
|
|
6478
|
+
}
|
|
6479
|
+
if (this.state === "working") {
|
|
6480
|
+
this.msg = oneLine(title, 120);
|
|
6481
|
+
this.pushStatus();
|
|
6482
|
+
}
|
|
6483
|
+
return;
|
|
6484
|
+
}
|
|
6485
|
+
case "plan": {
|
|
6486
|
+
const entries = Array.isArray(u.entries) ? u.entries : [];
|
|
6487
|
+
if (!entries.length) return;
|
|
6488
|
+
this.newline();
|
|
6489
|
+
this.print(`${C.bold}Plan${C.reset}\r
|
|
6490
|
+
` + entries.map((e) => ` ${e.status === "completed" ? `${C.green}\u2612` : e.status === "in_progress" ? `${C.cyan}\u25B8` : `${C.dim}\u2610`} ${oneLine(String(e.content ?? ""), 160)}${C.reset}`).join("\r\n") + "\r\n");
|
|
6491
|
+
return;
|
|
6492
|
+
}
|
|
6493
|
+
}
|
|
6494
|
+
}
|
|
6495
|
+
/** ACP content that points somewhere (D56): a resource link (file:// or http), an image or resource with a URI. */
|
|
6496
|
+
content(c) {
|
|
6497
|
+
const uri = typeof c?.uri === "string" ? c.uri : typeof c?.resource?.uri === "string" ? c.resource.uri : "";
|
|
6498
|
+
if (!c || !uri || !["resource_link", "image", "resource"].includes(c.type)) return;
|
|
6499
|
+
const title = typeof c.title === "string" ? c.title : typeof c.name === "string" ? c.name : void 0;
|
|
6500
|
+
if (uri.startsWith("file://")) {
|
|
6501
|
+
try {
|
|
6502
|
+
this.rounds.addFile(decodeURIComponent(new URL(uri).pathname.replace(/^\/([A-Za-z]:)/, "$1")), "explicit", title);
|
|
6503
|
+
} catch {
|
|
6504
|
+
}
|
|
6505
|
+
} else this.rounds.addUrl(uri, "explicit", title);
|
|
6506
|
+
}
|
|
6507
|
+
text(t, style = "") {
|
|
6508
|
+
this.print(style + crlf(t) + (style ? C.reset : ""));
|
|
6509
|
+
this.atLineStart = /\n$/.test(t);
|
|
6510
|
+
}
|
|
6511
|
+
newline() {
|
|
6512
|
+
if (!this.atLineStart) {
|
|
6513
|
+
this.print("\r\n");
|
|
6514
|
+
this.atLineStart = true;
|
|
6515
|
+
}
|
|
6516
|
+
}
|
|
6517
|
+
/** A prompt from a panel button: started when needed; queued while a turn runs (one turn at a time). */
|
|
6518
|
+
async send(text, notes = [], about = {}) {
|
|
6519
|
+
const clean = text.replace(CONTROL, "");
|
|
6520
|
+
if (!clean.trim()) return;
|
|
6521
|
+
this.remember(notes);
|
|
6522
|
+
nameSession(this, about);
|
|
6523
|
+
if (typeof about.task === "string" && about.task.trim()) this.nextTask = about.task.trim().slice(0, 80);
|
|
6524
|
+
this.queued.push(clean);
|
|
6525
|
+
if (!this.child) await this.start();
|
|
6526
|
+
this.pump();
|
|
6527
|
+
}
|
|
6528
|
+
pump() {
|
|
6529
|
+
if (this.turn || !this.queued.length || !this.rpc || !this.sessionId) return;
|
|
6530
|
+
const text = this.queued.splice(0).join("\n\n");
|
|
6531
|
+
const full = this.preamble ? `${this.preamble}
|
|
6532
|
+
|
|
6533
|
+
${text}` : text;
|
|
6534
|
+
this.preamble = "";
|
|
6535
|
+
const rpc = this.rpc;
|
|
6536
|
+
this.said = "";
|
|
6537
|
+
this.state = "working";
|
|
6538
|
+
this.msg = void 0;
|
|
6539
|
+
this.newline();
|
|
6540
|
+
this.print(`\r
|
|
6541
|
+
${C.cyan}${C.bold}\u203A ${C.reset}${C.cyan}${crlf(text)}${C.reset}\r
|
|
6542
|
+
`);
|
|
6543
|
+
this.pushStatus();
|
|
6544
|
+
const task = this.nextTask ?? firstLine(text);
|
|
6545
|
+
this.nextTask = void 0;
|
|
6546
|
+
this.rounds.base = this.worktree?.home ?? this.root;
|
|
6547
|
+
this.rounds.cwd = this.cwd;
|
|
6548
|
+
this.turn = (async () => {
|
|
6549
|
+
await this.rounds.begin(task).catch(() => {
|
|
6550
|
+
});
|
|
6551
|
+
try {
|
|
6552
|
+
const r = await rpc.request("session/prompt", { sessionId: this.sessionId, prompt: [{ type: "text", text: full }] });
|
|
6553
|
+
if (this.rpc !== rpc) return;
|
|
6554
|
+
const reason = String(r?.stopReason ?? "end_turn");
|
|
6555
|
+
const last = this.said.trim().split("\n").map((l) => l.trim()).filter(Boolean).pop();
|
|
6556
|
+
this.newline();
|
|
6557
|
+
if (reason === "cancelled") {
|
|
6558
|
+
this.state = "idle";
|
|
6559
|
+
this.msg = "cancelled";
|
|
6560
|
+
} else {
|
|
6561
|
+
this.state = "done";
|
|
6562
|
+
this.msg = reason === "end_turn" ? last ? oneLine(last) : void 0 : reason.replace(/_/g, " ");
|
|
6563
|
+
}
|
|
6564
|
+
this.print(`${C.dim}\u2500\u2500 ${reason === "end_turn" ? "done" : reason.replace(/_/g, " ")}${C.reset}\r
|
|
6565
|
+
`);
|
|
6566
|
+
} catch (e) {
|
|
6567
|
+
if (this.rpc !== rpc) return;
|
|
6568
|
+
this.state = "error";
|
|
6569
|
+
this.msg = oneLine(e.message);
|
|
6570
|
+
this.newline();
|
|
6571
|
+
this.print(`${C.red}${e.message}${C.reset}\r
|
|
6572
|
+
`);
|
|
6573
|
+
} finally {
|
|
6574
|
+
await this.rounds.finish().catch(() => {
|
|
6575
|
+
});
|
|
6576
|
+
this.focus = void 0;
|
|
6577
|
+
if (this.rpc === rpc) {
|
|
6578
|
+
this.turn = null;
|
|
6579
|
+
this.permission?.resolve({ outcome: "cancelled" });
|
|
6580
|
+
this.pushStatus();
|
|
6581
|
+
this.pump();
|
|
6582
|
+
}
|
|
6583
|
+
}
|
|
6584
|
+
})();
|
|
6585
|
+
}
|
|
6586
|
+
/**
|
|
6587
|
+
* Keys from the CLI window: a line editor. Enter sends the line as a prompt; Backspace; Esc or
|
|
6588
|
+
* Ctrl+C cancels the turn (a pending permission answered "cancelled").
|
|
6589
|
+
*/
|
|
6590
|
+
write(data) {
|
|
6591
|
+
if (!this.child) return;
|
|
6592
|
+
if (data.startsWith("\x1B[200~")) data = data.replace(/\x1b\[20[01]~/g, "");
|
|
6593
|
+
if (data === "\x1B" || data === "") {
|
|
6594
|
+
this.cancel();
|
|
6595
|
+
return;
|
|
6596
|
+
}
|
|
6597
|
+
data = data.replace(/\x1b\[[0-9;?]*[A-Za-z~]/g, "");
|
|
6598
|
+
for (const ch of data) {
|
|
6599
|
+
if (ch === "\r" || ch === "\n") {
|
|
6600
|
+
const line = this.line;
|
|
6601
|
+
this.line = "";
|
|
6602
|
+
this.print("\r\n");
|
|
6603
|
+
this.atLineStart = true;
|
|
6604
|
+
if (line.trim()) void this.send(line);
|
|
6605
|
+
} else if (ch === "\x7F" || ch === "\b") {
|
|
6606
|
+
if (this.line) {
|
|
6607
|
+
this.line = [...this.line].slice(0, -1).join("");
|
|
6608
|
+
this.print("\b \b");
|
|
6609
|
+
}
|
|
6610
|
+
} else if (ch >= " ") {
|
|
6611
|
+
this.line += ch;
|
|
6612
|
+
this.print(ch);
|
|
6613
|
+
this.atLineStart = false;
|
|
6614
|
+
}
|
|
6615
|
+
}
|
|
6616
|
+
}
|
|
6617
|
+
/** Stops the turn in flight (`session/cancel`), answering a pending permission "cancelled". */
|
|
6618
|
+
cancel() {
|
|
6619
|
+
if (!this.turn || !this.rpc) return;
|
|
6620
|
+
this.queued = [];
|
|
6621
|
+
this.rpc.notify("session/cancel", { sessionId: this.sessionId });
|
|
6622
|
+
this.permission?.resolve({ outcome: "cancelled" });
|
|
6623
|
+
}
|
|
6624
|
+
resize(_cols, _rows) {
|
|
6625
|
+
}
|
|
6626
|
+
/** Allow or Deny: the agent's first allow / reject option. */
|
|
6627
|
+
answer(_key, choice) {
|
|
6628
|
+
const p = this.permission;
|
|
6629
|
+
if (!p || choice !== "allow" && choice !== "deny") return false;
|
|
6630
|
+
const want = choice === "allow" ? ["allow_once", "allow_always"] : ["reject_once", "reject_always"];
|
|
6631
|
+
const o = want.map((k) => p.options.find((x) => x.kind === k)).find(Boolean);
|
|
6632
|
+
if (!o) return false;
|
|
6633
|
+
this.pick(o);
|
|
6634
|
+
return true;
|
|
6635
|
+
}
|
|
6636
|
+
/** An option of the card: the agent's own option, by its index. */
|
|
6637
|
+
async choose(index, _text) {
|
|
6638
|
+
const o = this.permission?.options[index];
|
|
6639
|
+
if (!o) return false;
|
|
6640
|
+
this.pick(o);
|
|
6641
|
+
return true;
|
|
6642
|
+
}
|
|
6643
|
+
pick(o) {
|
|
6644
|
+
this.print(`${C.dim}\u2192 ${o.name ?? o.optionId}${C.reset}\r
|
|
6645
|
+
`);
|
|
6646
|
+
this.permission?.resolve({ outcome: "selected", optionId: o.optionId });
|
|
6647
|
+
}
|
|
6648
|
+
stop() {
|
|
6649
|
+
const child = this.child;
|
|
6650
|
+
if (!child || this.stopping) return;
|
|
6651
|
+
this.stopping = true;
|
|
6652
|
+
this.cancel();
|
|
6653
|
+
try {
|
|
6654
|
+
child.stdin.end();
|
|
6655
|
+
} catch {
|
|
6656
|
+
}
|
|
6657
|
+
kill(child);
|
|
6658
|
+
}
|
|
6659
|
+
acknowledge() {
|
|
6660
|
+
if (this.state === "done" || this.state === "error" && this.child) {
|
|
6661
|
+
this.state = "idle";
|
|
6662
|
+
this.msg = void 0;
|
|
6663
|
+
}
|
|
6664
|
+
this.pushStatus();
|
|
6665
|
+
}
|
|
6666
|
+
attach(res) {
|
|
6667
|
+
res.writeHead(200, { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-store", connection: "keep-alive", "x-accel-buffering": "no" });
|
|
6668
|
+
res.write("retry: 2000\n\n");
|
|
6669
|
+
this.viewers.add(res);
|
|
6670
|
+
sse(res, "hello", { ...this.info(), scrollback: this.scrollback });
|
|
6671
|
+
const beat = setInterval(() => res.write(": keep-alive\n\n"), 25e3);
|
|
6672
|
+
res.on("close", () => {
|
|
6673
|
+
clearInterval(beat);
|
|
6674
|
+
this.viewers.delete(res);
|
|
6675
|
+
});
|
|
6676
|
+
}
|
|
6677
|
+
/** The end of its transcript (D66), as plain text. */
|
|
6678
|
+
tail(lines) {
|
|
6679
|
+
return stripAnsi(this.scrollback).split(/\r?\n/).map((l) => l.trimEnd()).filter(Boolean).slice(-lines).join("\n");
|
|
6680
|
+
}
|
|
6681
|
+
dispose() {
|
|
6682
|
+
this.stop();
|
|
6683
|
+
for (const r of this.viewers) r.end();
|
|
6684
|
+
this.viewers.clear();
|
|
6685
|
+
}
|
|
6686
|
+
remember(notes) {
|
|
6687
|
+
for (const id of notes) {
|
|
6688
|
+
if (typeof id !== "string" || !/^[\w-]{1,64}$/.test(id)) continue;
|
|
6689
|
+
this.sent.delete(id);
|
|
6690
|
+
this.sent.add(id);
|
|
6691
|
+
}
|
|
6692
|
+
for (const id of this.sent) {
|
|
6693
|
+
if (this.sent.size <= MAX_SENT) break;
|
|
6694
|
+
this.sent.delete(id);
|
|
6695
|
+
}
|
|
6696
|
+
}
|
|
6697
|
+
/** A failed start: the process goes, the status says why. */
|
|
6698
|
+
fail(child, why) {
|
|
6699
|
+
this.state = "error";
|
|
6700
|
+
this.msg = oneLine(why);
|
|
6701
|
+
this.print(`${C.red}${why}${C.reset}\r
|
|
6702
|
+
`);
|
|
6703
|
+
this.stopping = true;
|
|
6704
|
+
kill(child);
|
|
6705
|
+
if (!child.pid) this.exited(child, null);
|
|
6706
|
+
}
|
|
6707
|
+
exited(child, code) {
|
|
6708
|
+
if (this.child !== child) return;
|
|
6709
|
+
const rpc = this.rpc;
|
|
6710
|
+
this.child = null;
|
|
6711
|
+
this.rpc = null;
|
|
6712
|
+
this.sessionId = "";
|
|
6713
|
+
this.turn = null;
|
|
6714
|
+
this.queued = [];
|
|
6715
|
+
this.permission = null;
|
|
6716
|
+
this.exitCode = code;
|
|
6717
|
+
const tail = this.stderr.trim().split("\n").pop()?.trim();
|
|
6718
|
+
rpc?.close(`${this.command} exited${code !== null ? ` (${code})` : ""}`);
|
|
6719
|
+
if (!this.stopping) {
|
|
6720
|
+
this.state = "error";
|
|
6721
|
+
this.msg = oneLine(`exited${code !== null ? ` with code ${code}` : ""}${tail ? `: ${tail}` : ""}`);
|
|
6722
|
+
this.newline();
|
|
6723
|
+
this.print(`${C.red}${this.command} ${this.msg}${C.reset}\r
|
|
6724
|
+
`);
|
|
6725
|
+
} else if (this.state !== "error") {
|
|
6726
|
+
this.state = "idle";
|
|
6727
|
+
this.msg = void 0;
|
|
6728
|
+
}
|
|
6729
|
+
this.broadcast("exit", { exitCode: code });
|
|
6730
|
+
this.pushStatus();
|
|
6731
|
+
}
|
|
6732
|
+
print(s) {
|
|
6733
|
+
this.scrollback += s;
|
|
6734
|
+
if (this.scrollback.length > MAX_SCROLLBACK) {
|
|
6735
|
+
const cut = this.scrollback.indexOf("\n", this.scrollback.length - MAX_SCROLLBACK);
|
|
6736
|
+
this.scrollback = this.scrollback.slice(cut < 0 ? this.scrollback.length - MAX_SCROLLBACK : cut + 1);
|
|
6737
|
+
}
|
|
6738
|
+
this.broadcast("data", s);
|
|
5350
6739
|
}
|
|
5351
|
-
|
|
5352
|
-
|
|
5353
|
-
function unnumbered(L, hintAt) {
|
|
5354
|
-
let c = -1;
|
|
5355
|
-
for (let i = hintAt - 1; i >= Math.max(0, hintAt - 12); i--) if (/^\s*[❯›]\s+\S/.test(L[i].text)) {
|
|
5356
|
-
c = i;
|
|
5357
|
-
break;
|
|
6740
|
+
broadcast(event, data) {
|
|
6741
|
+
for (const r of this.viewers) sse(r, event, data);
|
|
5358
6742
|
}
|
|
5359
|
-
|
|
5360
|
-
|
|
5361
|
-
|
|
5362
|
-
|
|
5363
|
-
|
|
5364
|
-
|
|
5365
|
-
|
|
5366
|
-
|
|
6743
|
+
pushStatus() {
|
|
6744
|
+
const info = this.info(), key = JSON.stringify(info);
|
|
6745
|
+
if (key === this.lastStatus) return;
|
|
6746
|
+
this.lastStatus = key;
|
|
6747
|
+
this.broadcast("status", info);
|
|
6748
|
+
this.onChange();
|
|
6749
|
+
}
|
|
6750
|
+
};
|
|
6751
|
+
var meta = (s) => ({
|
|
6752
|
+
...s.rounds?.list.length ? { rounds: s.rounds.list.length, attachments: s.rounds.count } : {},
|
|
6753
|
+
...s.title ? { title: s.title } : {},
|
|
6754
|
+
...s.task ? { task: s.task } : {},
|
|
6755
|
+
...s.worktree ? { worktree: { branch: s.worktree.branch, path: s.worktree.path, base: s.worktree.base } } : {},
|
|
6756
|
+
...s.focus ? { focus: s.focus } : {},
|
|
6757
|
+
...s.opts.model ? { model: s.opts.model } : {},
|
|
6758
|
+
...s.opts.effort ? { effort: s.opts.effort } : {}
|
|
6759
|
+
});
|
|
6760
|
+
var firstLine = (t) => oneLine(t.split("\n").find((l) => l.trim()) ?? "", 60);
|
|
6761
|
+
function nameSession(s, about) {
|
|
6762
|
+
const clean = (v) => typeof v === "string" ? v.replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 80) : "";
|
|
6763
|
+
if (!s.title && clean(about.title)) s.title = clean(about.title);
|
|
6764
|
+
if (!s.task && clean(about.task)) s.task = clean(about.task);
|
|
5367
6765
|
}
|
|
5368
|
-
function
|
|
5369
|
-
const
|
|
5370
|
-
|
|
5371
|
-
const lit = (line.spans ?? []).filter((s) => s.bg && s.t.trim()).map((s) => s.t.trim());
|
|
5372
|
-
return parts.map((p) => {
|
|
5373
|
-
const state = p.startsWith("\u2612") ? "done" : p.startsWith("\u2714") ? "submit" : "todo";
|
|
5374
|
-
const label = p.replace(/^[☐☒✔✓]\s*/, "");
|
|
5375
|
-
return { label, state, current: lit.some((t) => t.includes(label)) };
|
|
5376
|
-
});
|
|
6766
|
+
function configOption(list, what) {
|
|
6767
|
+
const all = Array.isArray(list) ? list : [];
|
|
6768
|
+
return what === "model" ? all.find((o) => o?.category === "model" || o?.id === "model") : all.find((o) => o?.category === "thought_level" || o?.id === "effort" || o?.id === "thought_level");
|
|
5377
6769
|
}
|
|
5378
|
-
|
|
5379
|
-
|
|
5380
|
-
|
|
5381
|
-
|
|
6770
|
+
var flatOptions = (cfg) => (Array.isArray(cfg.options) ? cfg.options : []).flatMap((o) => Array.isArray(o?.options) ? o.options : [o]);
|
|
6771
|
+
function offerOf(s) {
|
|
6772
|
+
const list = (what) => {
|
|
6773
|
+
const cfg = configOption(s?.configOptions, what);
|
|
6774
|
+
const opts = cfg ? flatOptions(cfg) : what === "model" && Array.isArray(s?.models?.availableModels) ? s.models.availableModels.map((m) => ({ value: m?.modelId, name: m?.name })) : [];
|
|
6775
|
+
const seen = /* @__PURE__ */ new Set();
|
|
6776
|
+
return opts.filter((o) => typeof o?.value === "string" && o.value && o.value !== "default" && !seen.has(o.value) && !!seen.add(o.value)).slice(0, 500).map((o) => ({ value: String(o.value).slice(0, 200), ...typeof o.name === "string" && o.name !== o.value ? { name: o.name.slice(0, 200) } : {} }));
|
|
6777
|
+
};
|
|
6778
|
+
return { models: list("model"), efforts: list("effort") };
|
|
5382
6779
|
}
|
|
5383
|
-
|
|
5384
|
-
|
|
5385
|
-
|
|
5386
|
-
|
|
5387
|
-
|
|
5388
|
-
|
|
5389
|
-
|
|
5390
|
-
|
|
5391
|
-
|
|
5392
|
-
|
|
5393
|
-
|
|
5394
|
-
|
|
5395
|
-
});
|
|
5396
|
-
}
|
|
5397
|
-
settled() {
|
|
5398
|
-
return this.pending ? new Promise((r) => this.waiters.push(r)) : Promise.resolve();
|
|
5399
|
-
}
|
|
5400
|
-
/** Writes not on the screen yet. */
|
|
5401
|
-
get busy() {
|
|
5402
|
-
return this.pending > 0;
|
|
6780
|
+
async function probeAcp(opts, cwd, ms = 3e4) {
|
|
6781
|
+
const command = opts.command ?? "claude";
|
|
6782
|
+
const args = [...adapterFor(command, void 0, opts.adapters, opts.args).acp ?? [], ...opts.args ?? []];
|
|
6783
|
+
const env = { ...process.env, ...opts.env };
|
|
6784
|
+
const target = resolveCommand(command, args, env);
|
|
6785
|
+
const none = { models: [], efforts: [] };
|
|
6786
|
+
if (!target) return none;
|
|
6787
|
+
let child;
|
|
6788
|
+
try {
|
|
6789
|
+
child = (0, import_node_child_process3.spawn)(target.file, target.args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, detached: process.platform !== "win32" });
|
|
6790
|
+
} catch {
|
|
6791
|
+
return none;
|
|
5403
6792
|
}
|
|
5404
|
-
|
|
6793
|
+
const rpc = new JsonRpc((line) => child.stdin.write(line));
|
|
6794
|
+
child.stdout.setEncoding("utf8");
|
|
6795
|
+
child.stdout.on("data", (d) => rpc.feed(d));
|
|
6796
|
+
child.stderr.on("data", () => {
|
|
6797
|
+
});
|
|
6798
|
+
child.stdin.on("error", () => {
|
|
6799
|
+
});
|
|
6800
|
+
child.on("error", () => rpc.close("failed"));
|
|
6801
|
+
child.once("exit", () => rpc.close("exited"));
|
|
6802
|
+
try {
|
|
6803
|
+
await rpc.request("initialize", { protocolVersion: ACP_PROTOCOL_VERSION, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false }, clientInfo: CLIENT_INFO }, ms);
|
|
6804
|
+
return offerOf(await rpc.request("session/new", { cwd, mcpServers: [] }, ms));
|
|
6805
|
+
} catch {
|
|
6806
|
+
return none;
|
|
6807
|
+
} finally {
|
|
6808
|
+
rpc.close("done");
|
|
5405
6809
|
try {
|
|
5406
|
-
|
|
6810
|
+
child.stdin.end();
|
|
5407
6811
|
} catch {
|
|
5408
6812
|
}
|
|
6813
|
+
kill(child);
|
|
5409
6814
|
}
|
|
5410
|
-
|
|
5411
|
-
|
|
5412
|
-
|
|
5413
|
-
|
|
5414
|
-
|
|
5415
|
-
|
|
5416
|
-
|
|
5417
|
-
|
|
5418
|
-
const
|
|
5419
|
-
|
|
5420
|
-
|
|
5421
|
-
|
|
5422
|
-
|
|
5423
|
-
out.push({ text: "" });
|
|
5424
|
-
continue;
|
|
5425
|
-
}
|
|
5426
|
-
const text = line.translateToString(true);
|
|
5427
|
-
const spans = [];
|
|
5428
|
-
let cur = null;
|
|
5429
|
-
for (let x = 0; x < text.length && x < line.length; x++) {
|
|
5430
|
-
line.getCell(x, cell);
|
|
5431
|
-
const ch = cell.getChars() || (cell.getWidth() === 0 ? "" : " ");
|
|
5432
|
-
if (!ch && cell.getWidth() === 0) continue;
|
|
5433
|
-
let fg = colour(cell.isFgRGB(), cell.isFgPalette(), cell.getFgColor());
|
|
5434
|
-
let bg = colour(cell.isBgRGB(), cell.isBgPalette(), cell.getBgColor());
|
|
5435
|
-
if (cell.isInverse()) [fg, bg] = [bg ?? "#131316", fg ?? "#ececf1"];
|
|
5436
|
-
const s = { t: ch, ...fg ? { fg } : {}, ...bg ? { bg } : {}, ...cell.isBold() ? { b: true } : {}, ...cell.isDim() ? { dim: true } : {} };
|
|
5437
|
-
if (cur && cur.fg === s.fg && cur.bg === s.bg && cur.b === s.b && cur.dim === s.dim) cur.t += ch;
|
|
5438
|
-
else {
|
|
5439
|
-
cur = s;
|
|
5440
|
-
spans.push(s);
|
|
5441
|
-
}
|
|
6815
|
+
}
|
|
6816
|
+
var sse = (res, event, data) => res.write(`event: ${event}
|
|
6817
|
+
data: ${JSON.stringify(data)}
|
|
6818
|
+
|
|
6819
|
+
`);
|
|
6820
|
+
function kill(child) {
|
|
6821
|
+
if (child.exitCode !== null || child.signalCode !== null || !child.pid) return;
|
|
6822
|
+
if (process.platform === "win32") {
|
|
6823
|
+
const r = (0, import_node_child_process3.spawnSync)("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true, timeout: 5e3 });
|
|
6824
|
+
if (r.error || r.status !== 0) {
|
|
6825
|
+
try {
|
|
6826
|
+
child.kill();
|
|
6827
|
+
} catch {
|
|
5442
6828
|
}
|
|
5443
|
-
out.push({ text, spans });
|
|
5444
6829
|
}
|
|
5445
|
-
return
|
|
5446
|
-
}
|
|
5447
|
-
/** The menu on screen now, if any. */
|
|
5448
|
-
prompt() {
|
|
5449
|
-
return parsePrompt(this.lines());
|
|
6830
|
+
return;
|
|
5450
6831
|
}
|
|
5451
|
-
|
|
5452
|
-
|
|
5453
|
-
|
|
5454
|
-
|
|
5455
|
-
|
|
5456
|
-
|
|
5457
|
-
|
|
5458
|
-
"#ff6ac1",
|
|
5459
|
-
"#9aedfe",
|
|
5460
|
-
"#c7c7cf",
|
|
5461
|
-
"#686868",
|
|
5462
|
-
"#ff6e67",
|
|
5463
|
-
"#5ffa68",
|
|
5464
|
-
"#fffc67",
|
|
5465
|
-
"#6871ff",
|
|
5466
|
-
"#ff77ff",
|
|
5467
|
-
"#60fdff",
|
|
5468
|
-
"#ffffff"
|
|
5469
|
-
];
|
|
5470
|
-
function colour(rgb, palette, v) {
|
|
5471
|
-
if (rgb) return `#${v.toString(16).padStart(6, "0")}`;
|
|
5472
|
-
if (!palette) return void 0;
|
|
5473
|
-
if (v < 16) return ANSI[v];
|
|
5474
|
-
if (v < 232) {
|
|
5475
|
-
const c = v - 16, k = [0, 95, 135, 175, 215, 255];
|
|
5476
|
-
return `rgb(${k[Math.floor(c / 36)]},${k[Math.floor(c / 6) % 6]},${k[c % 6]})`;
|
|
6832
|
+
try {
|
|
6833
|
+
process.kill(-child.pid, "SIGTERM");
|
|
6834
|
+
} catch {
|
|
6835
|
+
try {
|
|
6836
|
+
child.kill("SIGTERM");
|
|
6837
|
+
} catch {
|
|
6838
|
+
}
|
|
5477
6839
|
}
|
|
5478
|
-
const g2 = 8 + (v - 232) * 10;
|
|
5479
|
-
return `rgb(${g2},${g2},${g2})`;
|
|
5480
6840
|
}
|
|
5481
6841
|
|
|
5482
|
-
// agent/src/
|
|
5483
|
-
var HERE = typeof __dirname === "string" ? __dirname :
|
|
5484
|
-
var DIST = import_node_path.default.basename(HERE) === "dist" ? HERE : import_node_path.default.join(HERE, "../dist");
|
|
5485
|
-
var DEFAULT_COMMANDS = [
|
|
5486
|
-
{ label: "Apply notes", title: "Ask the agent to apply the open notes on this page", prompt: "Apply the open Redline notes {ids} on page {page}, following the redline skill. Mark each one done when it is applied." }
|
|
5487
|
-
];
|
|
6842
|
+
// agent-bridge/src/sessions.ts
|
|
6843
|
+
var HERE = typeof __dirname === "string" ? __dirname : import_node_path5.default.dirname((0, import_node_url.fileURLToPath)(void 0));
|
|
5488
6844
|
var DEFAULT_KEYS = { allow: "\r", deny: "\x1B" };
|
|
5489
|
-
var
|
|
6845
|
+
var MAX_SENT2 = 500;
|
|
5490
6846
|
var KEEP_ENDED = 4;
|
|
5491
|
-
var
|
|
5492
|
-
var MAX_SCROLLBACK = 512 * 1024;
|
|
6847
|
+
var MAX_SCROLLBACK2 = 512 * 1024;
|
|
5493
6848
|
var ACTIVE_MS = 1500;
|
|
5494
6849
|
function loadPty(root) {
|
|
5495
|
-
for (const from of [
|
|
6850
|
+
for (const from of [import_node_path5.default.join(root, "package.json"), import_node_path5.default.join(HERE, "index.cjs")]) {
|
|
5496
6851
|
const req = (0, import_node_module.createRequire)(from);
|
|
5497
6852
|
for (const name of ["node-pty", "@lydell/node-pty"]) {
|
|
5498
6853
|
try {
|
|
5499
6854
|
const m = req(name);
|
|
5500
|
-
if (process.platform === "darwin") ensureSpawnHelper(
|
|
6855
|
+
if (process.platform === "darwin") ensureSpawnHelper(import_node_path5.default.dirname(req.resolve(`${name}/package.json`)));
|
|
5501
6856
|
return m;
|
|
5502
6857
|
} catch {
|
|
5503
6858
|
}
|
|
@@ -5506,9 +6861,9 @@ function loadPty(root) {
|
|
|
5506
6861
|
return null;
|
|
5507
6862
|
}
|
|
5508
6863
|
function ensureSpawnHelper(pkgDir) {
|
|
5509
|
-
for (const f of [
|
|
6864
|
+
for (const f of [import_node_path5.default.join(pkgDir, "prebuilds", `darwin-${process.arch}`, "spawn-helper"), import_node_path5.default.join(pkgDir, "build", "Release", "spawn-helper")]) {
|
|
5510
6865
|
try {
|
|
5511
|
-
if ((0,
|
|
6866
|
+
if ((0, import_node_fs5.existsSync)(f) && !((0, import_node_fs5.statSync)(f).mode & 73)) (0, import_node_fs5.chmodSync)(f, 493);
|
|
5512
6867
|
} catch {
|
|
5513
6868
|
}
|
|
5514
6869
|
}
|
|
@@ -5517,35 +6872,31 @@ function resolveCommand(command, args, env, platform = process.platform) {
|
|
|
5517
6872
|
if (platform !== "win32") return { file: command, args };
|
|
5518
6873
|
const isFile = (f) => {
|
|
5519
6874
|
try {
|
|
5520
|
-
return (0,
|
|
6875
|
+
return (0, import_node_fs5.statSync)(f).isFile();
|
|
5521
6876
|
} catch {
|
|
5522
6877
|
return false;
|
|
5523
6878
|
}
|
|
5524
6879
|
};
|
|
5525
6880
|
const exts = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map((e) => e.toLowerCase());
|
|
5526
|
-
const has =
|
|
5527
|
-
const dirs =
|
|
6881
|
+
const has = import_node_path5.default.extname(command) !== "";
|
|
6882
|
+
const dirs = import_node_path5.default.isAbsolute(command) || command.includes("\\") || command.includes("/") ? [""] : [process.cwd(), ...(env.PATH ?? env.Path ?? "").split(";").filter(Boolean)];
|
|
5528
6883
|
for (const dir of dirs) {
|
|
5529
6884
|
for (const ext of has ? [""] : exts) {
|
|
5530
|
-
const f = dir ?
|
|
6885
|
+
const f = dir ? import_node_path5.default.join(dir, command + ext) : command + ext;
|
|
5531
6886
|
if (!isFile(f)) continue;
|
|
5532
|
-
const e =
|
|
6887
|
+
const e = import_node_path5.default.extname(f).toLowerCase();
|
|
5533
6888
|
if (e === ".cmd" || e === ".bat") return { file: env.ComSpec ?? "cmd.exe", args: ["/d", "/c", f, ...args] };
|
|
5534
6889
|
return { file: f, args };
|
|
5535
6890
|
}
|
|
5536
6891
|
}
|
|
5537
6892
|
return null;
|
|
5538
6893
|
}
|
|
5539
|
-
async function withInstructions(command, args, extra) {
|
|
5540
|
-
|
|
5541
|
-
|
|
5542
|
-
|
|
5543
|
-
if (!file) {
|
|
5544
|
-
file = import_node_path.default.join(import_node_os.default.tmpdir(), `redline-agent-${(0, import_node_crypto.createHash)("sha1").update(extra.text).digest("hex").slice(0, 12)}.md`);
|
|
5545
|
-
await (0, import_promises.writeFile)(file, extra.text);
|
|
5546
|
-
}
|
|
5547
|
-
return { args: [...args, "--append-system-prompt-file", file], preamble: "" };
|
|
6894
|
+
async function withInstructions(command, args, extra, model, adapters, effort, mcp) {
|
|
6895
|
+
const a = adapterFor(command, void 0, adapters, args);
|
|
6896
|
+
const r = a.start ? await a.start({ args, model, ...effort ? { effort } : {}, instructions: extra, ...mcp?.length ? { mcp } : {} }) : { args, preamble: extra.text };
|
|
6897
|
+
return { args: r.args, preamble: r.preamble ?? "", ...r.warning ? { warning: r.warning } : {} };
|
|
5548
6898
|
}
|
|
6899
|
+
var WARNED = /* @__PURE__ */ new Set();
|
|
5549
6900
|
var AgentSession = class {
|
|
5550
6901
|
pty = null;
|
|
5551
6902
|
starting = null;
|
|
@@ -5575,19 +6926,45 @@ var AgentSession = class {
|
|
|
5575
6926
|
// from the program's 7501 reports
|
|
5576
6927
|
preamble = "";
|
|
5577
6928
|
// instructions still to go ahead of the first prompt (a CLI without a flag for them)
|
|
6929
|
+
worked = false;
|
|
6930
|
+
// working was reported since the last prompt (doneOnIdle adapters: idle after it is done)
|
|
6931
|
+
/** The tab's name and the prompt that started it (D62), set by the first prompt that names them. */
|
|
6932
|
+
title;
|
|
6933
|
+
task;
|
|
5578
6934
|
opts;
|
|
6935
|
+
/** Where the CLI runs: the project's cwd, or the same folder in its worktree (D64). */
|
|
5579
6936
|
cwd;
|
|
5580
6937
|
root;
|
|
5581
6938
|
id;
|
|
5582
6939
|
label;
|
|
6940
|
+
/** Set up before the CLI first starts (D64: its worktree, which also moves `cwd`). */
|
|
6941
|
+
prepare;
|
|
6942
|
+
/** Its git worktree (D64), once prepared. */
|
|
6943
|
+
worktree;
|
|
6944
|
+
/** Its rounds and what it pointed at in each (D56). */
|
|
6945
|
+
rounds;
|
|
6946
|
+
/** The label of the next round (the prompt's `task`). */
|
|
6947
|
+
nextTask;
|
|
6948
|
+
/** The host's MCP servers for this session (D66), asked for at start. */
|
|
6949
|
+
mcp;
|
|
6950
|
+
/** What it says it is on now (D66: MCP `working_on`); cleared when its turn is done. */
|
|
6951
|
+
focus;
|
|
6952
|
+
roundWorked = false;
|
|
6953
|
+
// the round's turn has been seen working: resting again ends it
|
|
6954
|
+
roundLive = false;
|
|
6955
|
+
// its prompt has been typed: only then does working count (not a CLI still starting up)
|
|
6956
|
+
/** The CLI's id (D59); `opts` has its command, arguments and environment. */
|
|
6957
|
+
cli;
|
|
5583
6958
|
onChange;
|
|
5584
|
-
constructor(opts, cwd, root, n, onChange) {
|
|
6959
|
+
constructor(opts, cwd, root, n, onChange, cli = "") {
|
|
5585
6960
|
this.opts = opts;
|
|
5586
6961
|
this.cwd = cwd;
|
|
5587
6962
|
this.root = root;
|
|
5588
6963
|
this.id = `s${n}`;
|
|
5589
6964
|
this.label = `#${n}`;
|
|
5590
6965
|
this.onChange = onChange;
|
|
6966
|
+
this.cli = cli;
|
|
6967
|
+
this.rounds = new Rounds(root, cwd, () => this.pushStatus());
|
|
5591
6968
|
}
|
|
5592
6969
|
get running() {
|
|
5593
6970
|
return !!this.pty || !!this.starting;
|
|
@@ -5598,21 +6975,25 @@ var AgentSession = class {
|
|
|
5598
6975
|
const s = this.info().status.state;
|
|
5599
6976
|
return s === "idle" || s === "done" || s === "error";
|
|
5600
6977
|
}
|
|
5601
|
-
/**
|
|
6978
|
+
/** The CLI's adapter (D55): by command, or by the `app` its 7501 reports name. */
|
|
6979
|
+
get adapter() {
|
|
6980
|
+
return adapterFor(this.opts.command ?? "claude", this.app, this.opts.adapters, this.opts.args);
|
|
6981
|
+
}
|
|
6982
|
+
/** Menus are read off the screen for CLIs whose menus `screen.ts` knows (Claude Code), or when asked to (`menus`). */
|
|
5602
6983
|
get menus() {
|
|
5603
6984
|
const m = this.opts.menus ?? "auto";
|
|
5604
|
-
return m === true || m === "auto" &&
|
|
6985
|
+
return m === true || m === "auto" && !!this.adapter.menus;
|
|
5605
6986
|
}
|
|
5606
6987
|
/** The `instructions` option's text ('' for none); a file is read at every start, so edits apply to the next session. */
|
|
5607
6988
|
async instructions() {
|
|
5608
6989
|
const o = this.opts.instructions;
|
|
5609
6990
|
if (!o) return { text: "" };
|
|
5610
6991
|
if (typeof o === "string") return { text: o.trim() };
|
|
5611
|
-
const file =
|
|
6992
|
+
const file = import_node_path5.default.resolve(this.root, o.file);
|
|
5612
6993
|
try {
|
|
5613
|
-
return { text: (await (0,
|
|
6994
|
+
return { text: (await (0, import_promises3.readFile)(file, "utf8")).trim(), file };
|
|
5614
6995
|
} catch {
|
|
5615
|
-
console.warn(`[
|
|
6996
|
+
console.warn(`[agent-bridge] instructions: can't read ${file}`);
|
|
5616
6997
|
return { text: "" };
|
|
5617
6998
|
}
|
|
5618
6999
|
}
|
|
@@ -5621,19 +7002,22 @@ var AgentSession = class {
|
|
|
5621
7002
|
return commandName(this.opts);
|
|
5622
7003
|
}
|
|
5623
7004
|
info() {
|
|
5624
|
-
|
|
7005
|
+
let s = this.records.status();
|
|
7006
|
+
if (this.reported && this.worked && s.state === "idle" && this.adapter.doneOnIdle) s = { ...s, state: "done" };
|
|
5625
7007
|
const source = this.reported ? "7501" : this.pty ? "activity" : "none";
|
|
5626
|
-
const
|
|
7008
|
+
const status2 = source === "activity" ? { ...s, state: Date.now() - this.lastOutput < ACTIVE_MS ? "working" : "idle" } : s;
|
|
5627
7009
|
return {
|
|
5628
7010
|
id: this.id,
|
|
5629
7011
|
label: this.label,
|
|
5630
7012
|
running: !!this.pty,
|
|
5631
7013
|
...this.app ? { app: this.app } : {},
|
|
5632
7014
|
command: this.command,
|
|
7015
|
+
cli: this.cli,
|
|
5633
7016
|
exitCode: this.exitCode,
|
|
5634
|
-
status: { ...
|
|
7017
|
+
status: { ...status2, source },
|
|
5635
7018
|
sent: [...this.sent],
|
|
5636
|
-
...this.pty && this.view ? { prompt: this.view } : {}
|
|
7019
|
+
...this.pty && this.view ? { prompt: this.view } : {},
|
|
7020
|
+
...meta(this)
|
|
5637
7021
|
};
|
|
5638
7022
|
}
|
|
5639
7023
|
async start(cols, rows) {
|
|
@@ -5644,20 +7028,26 @@ var AgentSession = class {
|
|
|
5644
7028
|
this.cols = clampSize(cols, 20, 400);
|
|
5645
7029
|
this.rows = clampSize(rows, 5, 200);
|
|
5646
7030
|
}
|
|
5647
|
-
|
|
5648
|
-
|
|
7031
|
+
await this.prepare?.();
|
|
7032
|
+
const pty = loadPty(this.root);
|
|
7033
|
+
if (!pty) throw new Error("the agent bridge needs node-pty: npm i -D node-pty (Linux without build tools: @lydell/node-pty)");
|
|
5649
7034
|
const env = { ...process.env, ...this.opts.env, TERM: "xterm-256color", COLORTERM: "truecolor" };
|
|
5650
7035
|
const command = this.opts.command ?? "claude";
|
|
5651
|
-
const { args, preamble } = await withInstructions(command, this.opts.args ?? [], await this.instructions());
|
|
5652
|
-
|
|
5653
|
-
|
|
5654
|
-
|
|
5655
|
-
|
|
7036
|
+
const { args, preamble: preamble2, warning } = await withInstructions(command, this.opts.args ?? [], await this.instructions(), this.opts.model, this.opts.adapters, this.opts.effort, this.mcp?.());
|
|
7037
|
+
if (warning && !WARNED.has(warning)) {
|
|
7038
|
+
WARNED.add(warning);
|
|
7039
|
+
console.warn(`[agent-bridge]: ${warning}`);
|
|
7040
|
+
}
|
|
7041
|
+
this.preamble = preamble2;
|
|
7042
|
+
const spawn2 = resolveCommand(command, args, env);
|
|
7043
|
+
if (!spawn2) throw new Error(`"${command}" was not found on PATH`);
|
|
7044
|
+
const p = pty.spawn(spawn2.file, spawn2.args, { name: "xterm-256color", cols: this.cols, rows: this.rows, cwd: this.cwd, env, useConptyDll: true });
|
|
5656
7045
|
this.pty = p;
|
|
5657
7046
|
this.startedAt = Date.now();
|
|
5658
7047
|
this.exitCode = void 0;
|
|
5659
7048
|
this.reported = false;
|
|
5660
7049
|
this.records.clear();
|
|
7050
|
+
this.worked = false;
|
|
5661
7051
|
this.scrollback = "";
|
|
5662
7052
|
this.screen?.dispose();
|
|
5663
7053
|
this.screen = new Screen(this.cols, this.rows);
|
|
@@ -5670,6 +7060,7 @@ var AgentSession = class {
|
|
|
5670
7060
|
this.pty = null;
|
|
5671
7061
|
this.exitCode = exitCode;
|
|
5672
7062
|
this.records.dropTransient();
|
|
7063
|
+
void this.rounds.finish();
|
|
5673
7064
|
this.broadcast("exit", { exitCode });
|
|
5674
7065
|
this.pushStatus();
|
|
5675
7066
|
release(p);
|
|
@@ -5695,18 +7086,20 @@ var AgentSession = class {
|
|
|
5695
7086
|
this.reported = true;
|
|
5696
7087
|
this.records.apply(ev.report);
|
|
5697
7088
|
if (ev.report.app) this.app = ev.report.app;
|
|
7089
|
+
if (this.records.status().state === "working") this.worked = true;
|
|
5698
7090
|
}
|
|
5699
7091
|
}
|
|
5700
7092
|
const on = d.lastIndexOf("\x1B[?2004h"), off = d.lastIndexOf("\x1B[?2004l");
|
|
5701
7093
|
if (on > off) this.bracketedPaste = true;
|
|
5702
7094
|
else if (off > on) this.bracketedPaste = false;
|
|
5703
7095
|
this.lastOutput = Date.now();
|
|
7096
|
+
this.rounds.feed(d);
|
|
5704
7097
|
this.scrollback += d;
|
|
5705
7098
|
this.screen?.write(d);
|
|
5706
7099
|
this.screenDirty = true;
|
|
5707
|
-
if (this.scrollback.length >
|
|
5708
|
-
const cut = this.scrollback.indexOf("\n", this.scrollback.length -
|
|
5709
|
-
this.scrollback = this.scrollback.slice(cut < 0 ? this.scrollback.length -
|
|
7100
|
+
if (this.scrollback.length > MAX_SCROLLBACK2) {
|
|
7101
|
+
const cut = this.scrollback.indexOf("\n", this.scrollback.length - MAX_SCROLLBACK2);
|
|
7102
|
+
this.scrollback = this.scrollback.slice(cut < 0 ? this.scrollback.length - MAX_SCROLLBACK2 : cut + 1);
|
|
5710
7103
|
}
|
|
5711
7104
|
this.broadcast("data", d);
|
|
5712
7105
|
this.pushStatus();
|
|
@@ -5718,10 +7111,12 @@ var AgentSession = class {
|
|
|
5718
7111
|
* A prompt from a panel button. Not running: started, and the prompt waits until the program is
|
|
5719
7112
|
* ready for input (it reported idle/done, or its output has been quiet for a moment, up to 30 s).
|
|
5720
7113
|
*/
|
|
5721
|
-
async send(text, notes = []) {
|
|
7114
|
+
async send(text, notes = [], about = {}) {
|
|
5722
7115
|
const clean = text.replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "");
|
|
5723
7116
|
if (!clean.trim()) return;
|
|
5724
7117
|
this.remember(notes);
|
|
7118
|
+
nameSession(this, about);
|
|
7119
|
+
if (typeof about.task === "string" && about.task.trim()) this.nextTask = about.task.trim().slice(0, 80);
|
|
5725
7120
|
if (!this.pty || !this.ready()) {
|
|
5726
7121
|
this.queued.push(clean);
|
|
5727
7122
|
await this.start();
|
|
@@ -5737,7 +7132,7 @@ var AgentSession = class {
|
|
|
5737
7132
|
if (now - this.startedAt > 3e4) return true;
|
|
5738
7133
|
if (this.reported) {
|
|
5739
7134
|
const s = this.records.status().state;
|
|
5740
|
-
return s === "idle" || s === "done" || s === "error";
|
|
7135
|
+
return (s === "idle" || s === "done" || s === "error") && now - this.lastOutput >= (this.adapter.settleMs ?? 0);
|
|
5741
7136
|
}
|
|
5742
7137
|
return this.lastOutput > this.startedAt && now - this.lastOutput > 1200;
|
|
5743
7138
|
}
|
|
@@ -5753,10 +7148,22 @@ var AgentSession = class {
|
|
|
5753
7148
|
|
|
5754
7149
|
${text}` : text;
|
|
5755
7150
|
this.preamble = "";
|
|
5756
|
-
|
|
5757
|
-
|
|
5758
|
-
|
|
5759
|
-
|
|
7151
|
+
this.worked = false;
|
|
7152
|
+
const task = this.nextTask ?? firstLine(text);
|
|
7153
|
+
this.nextTask = void 0;
|
|
7154
|
+
this.rounds.base = this.worktree?.home ?? this.root;
|
|
7155
|
+
this.rounds.cwd = this.cwd;
|
|
7156
|
+
this.roundWorked = false;
|
|
7157
|
+
this.roundLive = false;
|
|
7158
|
+
void this.rounds.begin(task).catch(() => {
|
|
7159
|
+
}).then(() => {
|
|
7160
|
+
if (this.pty !== p) return;
|
|
7161
|
+
this.roundLive = true;
|
|
7162
|
+
p.write(this.bracketedPaste ? `\x1B[200~${clean}\x1B[201~` : clean);
|
|
7163
|
+
setTimeout(() => {
|
|
7164
|
+
if (this.pty === p) p.write("\r");
|
|
7165
|
+
}, 80);
|
|
7166
|
+
});
|
|
5760
7167
|
}
|
|
5761
7168
|
/** The notes a prompt named: the panel tags them "sent to the agent" until they are done. */
|
|
5762
7169
|
remember(notes) {
|
|
@@ -5768,13 +7175,13 @@ ${text}` : text;
|
|
|
5768
7175
|
changed = true;
|
|
5769
7176
|
}
|
|
5770
7177
|
for (const id of this.sent) {
|
|
5771
|
-
if (this.sent.size <=
|
|
7178
|
+
if (this.sent.size <= MAX_SENT2) break;
|
|
5772
7179
|
this.sent.delete(id);
|
|
5773
7180
|
}
|
|
5774
7181
|
if (changed) this.pushStatus();
|
|
5775
7182
|
}
|
|
5776
7183
|
/** Allow or Deny from the agent toolbar: the configured key, only while it waits for approval. */
|
|
5777
|
-
answer(key) {
|
|
7184
|
+
answer(key, _choice) {
|
|
5778
7185
|
if (!this.pty || this.info().status.state !== "blocked") return false;
|
|
5779
7186
|
this.pty.write(key);
|
|
5780
7187
|
return true;
|
|
@@ -5844,6 +7251,7 @@ ${text}` : text;
|
|
|
5844
7251
|
}
|
|
5845
7252
|
acknowledge() {
|
|
5846
7253
|
this.records.acknowledge();
|
|
7254
|
+
if (this.adapter.doneOnIdle && this.records.status().state === "idle") this.worked = false;
|
|
5847
7255
|
this.pushStatus();
|
|
5848
7256
|
}
|
|
5849
7257
|
/** A terminal viewer: output and status. */
|
|
@@ -5863,6 +7271,20 @@ ${text}` : text;
|
|
|
5863
7271
|
}
|
|
5864
7272
|
pushStatus() {
|
|
5865
7273
|
const info = this.info();
|
|
7274
|
+
const st = info.status.state, r = this.rounds.current;
|
|
7275
|
+
if (r && !r.done) {
|
|
7276
|
+
if (!this.roundLive) {
|
|
7277
|
+
} else if (st === "working" || st === "blocked") this.roundWorked = true;
|
|
7278
|
+
else if (this.roundWorked && !this.queued.length) {
|
|
7279
|
+
this.roundWorked = false;
|
|
7280
|
+
this.focus = void 0;
|
|
7281
|
+
void this.rounds.finish();
|
|
7282
|
+
}
|
|
7283
|
+
} else if (st === "working" && this.pty && this.reported) {
|
|
7284
|
+
this.roundWorked = true;
|
|
7285
|
+
this.roundLive = true;
|
|
7286
|
+
void this.rounds.begin("typed in the CLI window");
|
|
7287
|
+
}
|
|
5866
7288
|
const key = JSON.stringify(info);
|
|
5867
7289
|
if (key === this.lastStatus) return;
|
|
5868
7290
|
this.lastStatus = key;
|
|
@@ -5874,6 +7296,12 @@ ${text}` : text;
|
|
|
5874
7296
|
this.queued = [];
|
|
5875
7297
|
}
|
|
5876
7298
|
}
|
|
7299
|
+
/** The end of what it shows (D66): the screen now (a TUI redraws in place), else the output's last lines. */
|
|
7300
|
+
tail(lines) {
|
|
7301
|
+
const screen = this.screen?.lines().map((l) => l.text.trimEnd());
|
|
7302
|
+
if (screen?.some((l) => l)) return screen.join("\n").trim();
|
|
7303
|
+
return stripAnsi(this.scrollback).split(/\r?\n/).map((l) => l.trimEnd()).filter(Boolean).slice(-lines).join("\n");
|
|
7304
|
+
}
|
|
5877
7305
|
dispose() {
|
|
5878
7306
|
this.stop();
|
|
5879
7307
|
for (const r of this.viewers) r.end();
|
|
@@ -5895,13 +7323,23 @@ function release(p) {
|
|
|
5895
7323
|
} catch {
|
|
5896
7324
|
}
|
|
5897
7325
|
}
|
|
7326
|
+
function checkPick(body, offer, cli) {
|
|
7327
|
+
const out = {};
|
|
7328
|
+
for (const [key, list] of [["model", offer.models], ["effort", offer.efforts]]) {
|
|
7329
|
+
const v = body[key];
|
|
7330
|
+
if (v === void 0 || v === null || v === "") continue;
|
|
7331
|
+
if (typeof v !== "string" || !list.some((c) => c.value === v)) return { error: `${cli} offers no ${key} ${JSON.stringify(String(v).slice(0, 80))}` };
|
|
7332
|
+
out[key] = v;
|
|
7333
|
+
}
|
|
7334
|
+
return out;
|
|
7335
|
+
}
|
|
5898
7336
|
var clampSize = (n, lo, hi) => Math.max(lo, Math.min(hi, Math.round(Number(n) || lo)));
|
|
5899
7337
|
var send = (res, event, data) => res.write(`event: ${event}
|
|
5900
7338
|
data: ${JSON.stringify(data)}
|
|
5901
7339
|
|
|
5902
7340
|
`);
|
|
5903
7341
|
var AgentGroup = class {
|
|
5904
|
-
token = (0,
|
|
7342
|
+
token = (0, import_node_crypto2.randomBytes)(18).toString("base64url");
|
|
5905
7343
|
sessions = [];
|
|
5906
7344
|
mode;
|
|
5907
7345
|
n = 0;
|
|
@@ -5910,11 +7348,35 @@ var AgentGroup = class {
|
|
|
5910
7348
|
opts;
|
|
5911
7349
|
cwd;
|
|
5912
7350
|
root;
|
|
5913
|
-
|
|
7351
|
+
/** The CLIs a session can run (D59), the default first. */
|
|
7352
|
+
clis;
|
|
7353
|
+
/** Worktrees (D64): on for new fresh sessions; where they go and their branches' prefix; the repo, or why there is none. */
|
|
7354
|
+
wt;
|
|
7355
|
+
/** Worktrees of ended sessions, waiting for keep, merge or discard (D64). */
|
|
7356
|
+
left = [];
|
|
7357
|
+
/** Per session (D66): the environment variable that names it, and the host's MCP servers. */
|
|
7358
|
+
sessionEnv;
|
|
7359
|
+
mcpFor;
|
|
7360
|
+
/** Hooks a host sets once (createBridge): see BridgeSetup `sessionEnv` and `mcp`. */
|
|
7361
|
+
configure(o) {
|
|
7362
|
+
this.sessionEnv = o.sessionEnv;
|
|
7363
|
+
this.mcpFor = o.mcp;
|
|
7364
|
+
}
|
|
7365
|
+
constructor(opts, cwd, root, clis, wt = {}) {
|
|
5914
7366
|
this.opts = opts;
|
|
5915
7367
|
this.cwd = cwd;
|
|
5916
7368
|
this.root = root;
|
|
5917
|
-
this.
|
|
7369
|
+
this.clis = clis;
|
|
7370
|
+
this.mode = opts.sessions === "shared" ? "shared" : "fresh";
|
|
7371
|
+
this.wt = { on: !!opts.worktrees, dir: wt.dir ?? import_node_path5.default.join(root, ".agent-worktrees"), prefix: wt.prefix ?? "agent/", git: null };
|
|
7372
|
+
void gitTop(root).then(async (g2) => {
|
|
7373
|
+
this.wt.git = g2;
|
|
7374
|
+
if ("top" in g2) {
|
|
7375
|
+
for (const w of await leftover({ root, dir: this.wt.dir, prefix: this.wt.prefix })) if (!this.left.some((x) => x.dir === w.dir)) this.left.push(w);
|
|
7376
|
+
}
|
|
7377
|
+
for (const w of this.left) await this.refresh(w);
|
|
7378
|
+
this.push();
|
|
7379
|
+
});
|
|
5918
7380
|
}
|
|
5919
7381
|
get max() {
|
|
5920
7382
|
return clampSize(this.opts.maxSessions ?? 3, 1, 8);
|
|
@@ -5923,40 +7385,176 @@ var AgentGroup = class {
|
|
|
5923
7385
|
get(id) {
|
|
5924
7386
|
return typeof id === "string" && id ? this.sessions.find((s) => s.id === id) : this.sessions[this.sessions.length - 1];
|
|
5925
7387
|
}
|
|
5926
|
-
/**
|
|
5927
|
-
|
|
7388
|
+
/**
|
|
7389
|
+
* A new session of a CLI (default: the first), over ACP when its options say so (D58), with the
|
|
7390
|
+
* viewer's model and effort (D62; checked against `offer` by the route) over the options'; ended
|
|
7391
|
+
* ones past KEEP_ENDED are dropped, oldest first.
|
|
7392
|
+
*/
|
|
7393
|
+
create(cli = this.clis[0], pick = {}) {
|
|
5928
7394
|
const ended = this.sessions.filter((s2) => !s2.running);
|
|
5929
7395
|
for (const s2 of ended.slice(0, Math.max(0, ended.length - KEEP_ENDED + 1))) this.drop(s2);
|
|
5930
7396
|
if (!this.sessions.length) this.n = 0;
|
|
5931
|
-
const
|
|
7397
|
+
const n = ++this.n;
|
|
7398
|
+
const env = { ...this.opts.env, ...cli.env, ...this.sessionEnv ? { [this.sessionEnv]: `s${n}` } : {} };
|
|
7399
|
+
const opts = { ...this.opts, command: cli.command, args: cli.args, label: cli.label, env, ...pick };
|
|
7400
|
+
const s = new (usesAcp(opts) ? AcpSession : AgentSession)(opts, this.cwd, this.root, n, () => this.push(), cli.id);
|
|
7401
|
+
if (this.mcpFor) {
|
|
7402
|
+
const mcpFor = this.mcpFor;
|
|
7403
|
+
s.mcp = () => mcpFor(s.id);
|
|
7404
|
+
}
|
|
7405
|
+
if (s instanceof AcpSession) s.onOffer = (o) => this.offered(cli, o);
|
|
7406
|
+
if (this.mode === "fresh" && this.wt.on && this.wt.git && "top" in this.wt.git) {
|
|
7407
|
+
s.prepare = async () => {
|
|
7408
|
+
if (s.worktree) return;
|
|
7409
|
+
const w = await addWorktree({ root: this.root, cwd: this.cwd, dir: this.wt.dir, prefix: this.wt.prefix, name: s.title || s.id });
|
|
7410
|
+
s.worktree = w;
|
|
7411
|
+
s.cwd = w.cwd;
|
|
7412
|
+
};
|
|
7413
|
+
}
|
|
5932
7414
|
this.sessions.push(s);
|
|
5933
7415
|
this.push();
|
|
5934
7416
|
return s;
|
|
5935
7417
|
}
|
|
5936
|
-
/**
|
|
5937
|
-
|
|
5938
|
-
|
|
7418
|
+
/**
|
|
7419
|
+
* The session for a prompt or a start: 'shared' reuses `id` (or the newest), 'fresh' makes room and
|
|
7420
|
+
* starts a new one. `cli` (D59): 'fresh' starts that CLI; 'shared' switching to another CLI stops the
|
|
7421
|
+
* shared session (refused while it works or asks) and starts the new one, so one session still runs.
|
|
7422
|
+
*/
|
|
7423
|
+
forPrompt(id, cli, pick = {}) {
|
|
7424
|
+
if (this.mode === "shared") {
|
|
7425
|
+
const s = this.get(id);
|
|
7426
|
+
if (s && (!cli || s.cli === cli.id)) return s;
|
|
7427
|
+
if (s?.running) {
|
|
7428
|
+
if (!s.resting) throw Object.assign(new Error(`${s.command} is busy: wait until it is done, or end it, to switch to ${cli.name}`), { status: 409 });
|
|
7429
|
+
s.stop();
|
|
7430
|
+
}
|
|
7431
|
+
return this.create(cli, pick);
|
|
7432
|
+
}
|
|
5939
7433
|
const running = this.sessions.filter((s) => s.running);
|
|
5940
7434
|
if (running.length >= this.max) {
|
|
5941
7435
|
const done = running.find((s) => s.resting);
|
|
5942
7436
|
if (!done) throw Object.assign(new Error(`${running.length} sessions are busy: stop one, or wait until one is done`), { status: 409 });
|
|
5943
7437
|
done.stop();
|
|
5944
7438
|
}
|
|
5945
|
-
return this.create();
|
|
7439
|
+
return this.create(cli, pick);
|
|
7440
|
+
}
|
|
7441
|
+
/** The CLI a prompt or start goes to: the one named, else the shared session's, else the default. */
|
|
7442
|
+
target(id, cli) {
|
|
7443
|
+
const s = this.mode === "shared" || typeof id === "string" && id ? this.get(id) : void 0;
|
|
7444
|
+
return cli ?? this.clis.find((c) => c.id === s?.cli) ?? this.clis[0];
|
|
7445
|
+
}
|
|
7446
|
+
// What the settings offer per CLI (D62): an adapter's own lists, or what an ACP agent says in
|
|
7447
|
+
// session/new (asked once in the background, `probeAcp`; a real session's reply updates it).
|
|
7448
|
+
offers = /* @__PURE__ */ new Map();
|
|
7449
|
+
offer(cli) {
|
|
7450
|
+
const known = this.offers.get(cli.id);
|
|
7451
|
+
if (known) return known;
|
|
7452
|
+
const opts = { ...this.opts, command: cli.command, args: cli.args, env: { ...this.opts.env, ...cli.env } };
|
|
7453
|
+
if (!usesAcp(opts)) {
|
|
7454
|
+
const a = adapterFor(cli.command, void 0, this.opts.adapters, cli.args);
|
|
7455
|
+
const o = { models: choices(a.models), efforts: choices(a.efforts) };
|
|
7456
|
+
this.offers.set(cli.id, o);
|
|
7457
|
+
return o;
|
|
7458
|
+
}
|
|
7459
|
+
const pending = { models: [], efforts: [], pending: true };
|
|
7460
|
+
this.offers.set(cli.id, pending);
|
|
7461
|
+
void probeAcp(opts, this.cwd).then((o) => {
|
|
7462
|
+
if (this.offers.get(cli.id) === pending) this.offered(cli, o);
|
|
7463
|
+
});
|
|
7464
|
+
return pending;
|
|
7465
|
+
}
|
|
7466
|
+
offered(cli, o) {
|
|
7467
|
+
const was = this.offers.get(cli.id);
|
|
7468
|
+
if (was && !was.pending && JSON.stringify(was) === JSON.stringify(o)) return;
|
|
7469
|
+
this.offers.set(cli.id, o);
|
|
7470
|
+
const info = this.clisInfo();
|
|
7471
|
+
for (const r of this.watchers) send(r, "clis", info);
|
|
7472
|
+
}
|
|
7473
|
+
/** The CLIs for /agent/info and the feed: names and what each offers. */
|
|
7474
|
+
clisInfo() {
|
|
7475
|
+
return this.clis.map((c) => {
|
|
7476
|
+
const o = this.offer(c);
|
|
7477
|
+
return { id: c.id, name: c.name, command: commandName(c), models: o.models, efforts: o.efforts, ...o.pending ? { pending: true } : {} };
|
|
7478
|
+
});
|
|
5946
7479
|
}
|
|
5947
7480
|
drop(s) {
|
|
5948
7481
|
const i = this.sessions.indexOf(s);
|
|
5949
7482
|
if (i < 0) return;
|
|
5950
7483
|
this.sessions.splice(i, 1);
|
|
5951
7484
|
s.dispose();
|
|
7485
|
+
if (s.worktree && !this.left.some((w) => w.dir === s.worktree.dir)) {
|
|
7486
|
+
const w = { ...s.worktree, session: s.label, ...s.title ? { title: s.title } : {} };
|
|
7487
|
+
this.left.push(w);
|
|
7488
|
+
void this.refresh(w).then(() => this.push());
|
|
7489
|
+
}
|
|
5952
7490
|
this.push();
|
|
5953
7491
|
}
|
|
5954
7492
|
setMode(mode) {
|
|
5955
7493
|
this.mode = mode;
|
|
5956
7494
|
this.push();
|
|
5957
7495
|
}
|
|
7496
|
+
/** New fresh sessions get a worktree (D64); refused when the project isn't a git repo. */
|
|
7497
|
+
setWorktrees(on) {
|
|
7498
|
+
const g2 = this.wt.git;
|
|
7499
|
+
if (on && g2 && "why" in g2) throw Object.assign(new Error(`worktrees need a git repository: ${g2.why}`), { status: 409 });
|
|
7500
|
+
this.wt.on = on;
|
|
7501
|
+
this.push();
|
|
7502
|
+
}
|
|
7503
|
+
/**
|
|
7504
|
+
* An attachment the agent points at (D56: Redline's MCP `attach`, the /attach route): a file inside the
|
|
7505
|
+
* session's folder (relative to where it runs, or absolute) or an http(s) URL, with an optional title.
|
|
7506
|
+
*/
|
|
7507
|
+
attach(id, a) {
|
|
7508
|
+
const s = this.get(id);
|
|
7509
|
+
if (!s || s.id !== id) return { error: `no agent session ${id}` };
|
|
7510
|
+
const title = typeof a.title === "string" && a.title.trim() ? a.title.replace(/[\x00-\x1f\x7f]/g, " ").trim().slice(0, 200) : void 0;
|
|
7511
|
+
if (typeof a.url === "string" && a.url) {
|
|
7512
|
+
const item2 = s.rounds.addUrl(a.url.trim(), "explicit", title);
|
|
7513
|
+
return item2 ? { ok: true, attachment: item2 } : { error: "url must be http or https" };
|
|
7514
|
+
}
|
|
7515
|
+
if (typeof a.path !== "string" || !a.path) return { error: "give path (a file in the project) or url" };
|
|
7516
|
+
const item = s.rounds.addFile(a.path, "explicit", title);
|
|
7517
|
+
return item ? { ok: true, attachment: item } : { error: `${a.path} is not a file inside the project${s.worktree ? ` (this session works in ${s.worktree.path})` : ""}` };
|
|
7518
|
+
}
|
|
7519
|
+
/** The note (or other item) a session says it is on (D66); null clears it. False: no such session. */
|
|
7520
|
+
focusOn(id, item) {
|
|
7521
|
+
const s = this.sessions.find((x) => x.id === id);
|
|
7522
|
+
if (!s) return false;
|
|
7523
|
+
s.focus = item ? item.slice(0, 64) : void 0;
|
|
7524
|
+
this.push();
|
|
7525
|
+
return true;
|
|
7526
|
+
}
|
|
7527
|
+
/** Keep, merge or discard an ended session's worktree (D64); see worktrees.ts `act`. */
|
|
7528
|
+
async worktree(branch, action, confirm = false) {
|
|
7529
|
+
const w = this.left.find((x) => x.branch === branch);
|
|
7530
|
+
if (!w) throw Object.assign(new Error(`no ended session's worktree on ${branch}`), { status: 404 });
|
|
7531
|
+
const r = await act(w, action, confirm);
|
|
7532
|
+
if (!r.kept || action === "keep") this.left.splice(this.left.indexOf(w), 1);
|
|
7533
|
+
else await this.refresh(w);
|
|
7534
|
+
this.push();
|
|
7535
|
+
return r;
|
|
7536
|
+
}
|
|
7537
|
+
async refresh(w) {
|
|
7538
|
+
try {
|
|
7539
|
+
const st = await status(w);
|
|
7540
|
+
w.dirty = st.dirty;
|
|
7541
|
+
w.ahead = st.ahead;
|
|
7542
|
+
} catch {
|
|
7543
|
+
}
|
|
7544
|
+
}
|
|
5958
7545
|
info() {
|
|
5959
|
-
|
|
7546
|
+
const g2 = this.wt.git;
|
|
7547
|
+
return {
|
|
7548
|
+
mode: this.mode,
|
|
7549
|
+
max: this.max,
|
|
7550
|
+
worktrees: {
|
|
7551
|
+
on: this.wt.on && !(g2 && "why" in g2),
|
|
7552
|
+
git: !!g2 && "top" in g2,
|
|
7553
|
+
...g2 && "why" in g2 ? { why: g2.why } : !g2 ? { why: "checking\u2026" } : {},
|
|
7554
|
+
left: this.left.map((w) => ({ branch: w.branch, path: w.path, base: w.base, ...w.dirty !== void 0 ? { dirty: w.dirty } : {}, ...w.ahead !== void 0 ? { ahead: w.ahead } : {}, ...w.session ? { session: w.session } : {}, ...w.title ? { title: w.title } : {} }))
|
|
7555
|
+
},
|
|
7556
|
+
sessions: this.sessions.map((s) => s.info())
|
|
7557
|
+
};
|
|
5960
7558
|
}
|
|
5961
7559
|
/** The toolbar's feed: every session's status, whenever one changes. */
|
|
5962
7560
|
watch(res) {
|
|
@@ -5982,9 +7580,9 @@ var AgentGroup = class {
|
|
|
5982
7580
|
this.watchers.clear();
|
|
5983
7581
|
}
|
|
5984
7582
|
};
|
|
5985
|
-
var GROUPS = /* @__PURE__ */ Symbol.for("umage.
|
|
7583
|
+
var GROUPS = /* @__PURE__ */ Symbol.for("umage.agentBridge.groups");
|
|
5986
7584
|
var g = globalThis;
|
|
5987
|
-
function groupFor(opts, cwd, root) {
|
|
7585
|
+
function groupFor(opts, cwd, root, clis, wt = {}) {
|
|
5988
7586
|
const map = g[GROUPS] ??= (() => {
|
|
5989
7587
|
const m = /* @__PURE__ */ new Map();
|
|
5990
7588
|
process.once("exit", () => {
|
|
@@ -5992,58 +7590,49 @@ function groupFor(opts, cwd, root) {
|
|
|
5992
7590
|
});
|
|
5993
7591
|
return m;
|
|
5994
7592
|
})();
|
|
5995
|
-
const key = JSON.stringify([cwd,
|
|
7593
|
+
const key = JSON.stringify([cwd, clis.map((c) => [c.command, c.args, usesAcp({ ...opts, command: c.command })])]);
|
|
5996
7594
|
let s = map.get(key);
|
|
5997
7595
|
if (!s) {
|
|
5998
|
-
s = new AgentGroup(opts, cwd, root);
|
|
7596
|
+
s = new AgentGroup(opts, cwd, root, clis, wt);
|
|
5999
7597
|
map.set(key, s);
|
|
6000
7598
|
}
|
|
6001
7599
|
return s;
|
|
6002
7600
|
}
|
|
6003
|
-
|
|
6004
|
-
|
|
6005
|
-
|
|
6006
|
-
|
|
6007
|
-
|
|
6008
|
-
const
|
|
6009
|
-
const
|
|
6010
|
-
const
|
|
6011
|
-
const
|
|
6012
|
-
|
|
6013
|
-
const
|
|
7601
|
+
|
|
7602
|
+
// agent-bridge/src/handler.ts
|
|
7603
|
+
var TOKEN_HEADER = "x-agent-token";
|
|
7604
|
+
function createBridge(setup) {
|
|
7605
|
+
const { root, info: extra, worktreeDir, branchPrefix, sessionEnv, mcp, ...options } = setup;
|
|
7606
|
+
const clis = cliChoices(options);
|
|
7607
|
+
const opts = { ...options, command: clis[0].command, args: clis[0].args, label: clis[0].label ?? options.label };
|
|
7608
|
+
const cwd = opts.cwd ? import_node_path6.default.resolve(root, opts.cwd) : root;
|
|
7609
|
+
const group = groupFor(opts, cwd, root, clis, { dir: worktreeDir ? import_node_path6.default.resolve(root, worktreeDir) : void 0, prefix: branchPrefix });
|
|
7610
|
+
group.configure({ sessionEnv, mcp });
|
|
7611
|
+
const keysFor = (s) => opts.keys === false ? false : { ...DEFAULT_KEYS, ...s.adapter.keys, ...opts.keys };
|
|
7612
|
+
const info = () => ({
|
|
7613
|
+
...group.info(),
|
|
7614
|
+
command: commandName(opts),
|
|
7615
|
+
clis: group.clisInfo(),
|
|
7616
|
+
cli: group.clis[0].id,
|
|
7617
|
+
token: group.token,
|
|
7618
|
+
approve: opts.keys !== false,
|
|
7619
|
+
// The project's settings (D62): what a viewer's "reset" goes back to.
|
|
7620
|
+
defaults: { sessions: opts.sessions === "shared" ? "shared" : "fresh", worktrees: !!opts.worktrees, ...opts.model ? { model: opts.model } : {}, ...opts.effort ? { effort: opts.effort } : {} },
|
|
7621
|
+
...extra?.()
|
|
7622
|
+
});
|
|
6014
7623
|
return {
|
|
6015
|
-
|
|
6016
|
-
|
|
7624
|
+
token: group.token,
|
|
7625
|
+
group,
|
|
7626
|
+
info,
|
|
7627
|
+
async handle(req, res, p, { allowed = true } = {}) {
|
|
6017
7628
|
const method = req.method ?? "GET";
|
|
6018
|
-
if (!allowed) return json(res, 403, { error: "the agent
|
|
6019
|
-
|
|
6020
|
-
if (
|
|
6021
|
-
try {
|
|
6022
|
-
return new URL(origin).host !== req.headers.host;
|
|
6023
|
-
} catch {
|
|
6024
|
-
return true;
|
|
6025
|
-
}
|
|
6026
|
-
})()) return json(res, 403, { error: "cross-origin agent request" });
|
|
6027
|
-
const asset = method === "GET" && (p === "/agent/panel.js" ? "panel.js" : p === "/agent/terminal.js" ? "terminal.js" : null);
|
|
6028
|
-
if (asset) {
|
|
6029
|
-
const file = import_node_path.default.join(DIST, asset);
|
|
6030
|
-
if (!(0, import_node_fs.existsSync)(file)) return json(res, 404, { error: "agent panel not built" });
|
|
6031
|
-
res.setHeader("content-type", "text/javascript; charset=utf-8");
|
|
6032
|
-
res.setHeader("cache-control", "no-store");
|
|
6033
|
-
res.end(await (0, import_promises.readFile)(file));
|
|
6034
|
-
return;
|
|
6035
|
-
}
|
|
6036
|
-
if (method === "GET" && p === "/agent/terminal") {
|
|
6037
|
-
res.setHeader("content-type", "text/html; charset=utf-8");
|
|
6038
|
-
res.setHeader("cache-control", "no-store");
|
|
6039
|
-
res.end(terminalPage(base));
|
|
6040
|
-
return;
|
|
6041
|
-
}
|
|
6042
|
-
if (method === "GET" && p === "/agent/info") return json(res, 200, { ...group.info(), command: commandName(opts), token: group.token, commands, approve: !!keys, hotkey, key });
|
|
7629
|
+
if (!allowed || !isLocal(req)) return json(res, 403, { error: "the agent bridge answers this machine only" });
|
|
7630
|
+
if (foreignOrigin(req)) return json(res, 403, { error: "cross-origin agent request" });
|
|
7631
|
+
if (method === "GET" && p === "/info") return json(res, 200, info());
|
|
6043
7632
|
const url = new URL(req.url ?? "", "http://x");
|
|
6044
|
-
const token = method === "GET" ? url.searchParams.get("token") : req.headers[
|
|
7633
|
+
const token = method === "GET" ? url.searchParams.get("token") : req.headers[TOKEN_HEADER];
|
|
6045
7634
|
if (token !== group.token) return json(res, 403, { error: "missing or stale agent token" });
|
|
6046
|
-
if (method === "GET" && p === "/
|
|
7635
|
+
if (method === "GET" && p === "/stream") {
|
|
6047
7636
|
if (url.searchParams.get("status") === "1") {
|
|
6048
7637
|
group.watch(res);
|
|
6049
7638
|
return;
|
|
@@ -6053,47 +7642,103 @@ function agentRoutes(opts, root, base) {
|
|
|
6053
7642
|
s.attach(res);
|
|
6054
7643
|
return;
|
|
6055
7644
|
}
|
|
7645
|
+
if (method === "GET" && (p === "/attachments" || p === "/file" || p === "/diff")) {
|
|
7646
|
+
const s = group.get(url.searchParams.get("id") || void 0);
|
|
7647
|
+
if (!s || !url.searchParams.get("id")) return json(res, 404, { error: "no such agent session" });
|
|
7648
|
+
if (p === "/attachments") return json(res, 200, { id: s.id, rounds: s.rounds.view() });
|
|
7649
|
+
const rel2 = url.searchParams.get("path") ?? "";
|
|
7650
|
+
if (p === "/diff") {
|
|
7651
|
+
const d = await s.rounds.diff(Number(url.searchParams.get("round")), rel2).catch(() => null);
|
|
7652
|
+
if (d === null) return json(res, 404, { error: "no such changed file in that round" });
|
|
7653
|
+
res.writeHead(200, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", "x-content-type-options": "nosniff" });
|
|
7654
|
+
res.end(d);
|
|
7655
|
+
return;
|
|
7656
|
+
}
|
|
7657
|
+
const hit = inside(s.rounds.base, rel2), type = hit && fileType(hit.rel);
|
|
7658
|
+
if (!hit || !type) return json(res, 404, { error: "not a served file: images and text inside the session's folder only" });
|
|
7659
|
+
const st = await import_node_fs6.promises.stat(hit.abs).catch(() => null);
|
|
7660
|
+
if (!st?.isFile()) return json(res, 404, { error: "no such file" });
|
|
7661
|
+
if (st.size > MAX_FILE) return json(res, 413, { error: `over ${MAX_FILE / 1024 / 1024} MB` });
|
|
7662
|
+
res.writeHead(200, {
|
|
7663
|
+
"content-type": type.type,
|
|
7664
|
+
"cache-control": "no-store",
|
|
7665
|
+
"x-content-type-options": "nosniff",
|
|
7666
|
+
// Opened in a tab, an SVG or HTML file runs nothing.
|
|
7667
|
+
"content-security-policy": "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox"
|
|
7668
|
+
});
|
|
7669
|
+
res.end(await import_node_fs6.promises.readFile(hit.abs));
|
|
7670
|
+
return;
|
|
7671
|
+
}
|
|
6056
7672
|
if (method !== "POST") return json(res, 405, { error: "POST" });
|
|
6057
|
-
if (req.headers["x-redline"] !== "1") return json(res, 403, { error: "missing x-redline header" });
|
|
6058
7673
|
let body = {};
|
|
6059
7674
|
try {
|
|
6060
7675
|
body = JSON.parse(await readBody(req, 1024 * 1024) || "{}");
|
|
6061
7676
|
} catch {
|
|
6062
7677
|
return json(res, 400, { error: "bad JSON" });
|
|
6063
7678
|
}
|
|
7679
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "expected a JSON object" });
|
|
6064
7680
|
const failed = (e) => json(res, e.status ?? 500, { error: e.message });
|
|
6065
7681
|
const named = typeof body.id === "string" && !!body.id;
|
|
6066
7682
|
const session = group.get(body.id);
|
|
6067
7683
|
if (named && !session) return json(res, 404, { error: "no such agent session" });
|
|
7684
|
+
const cli = typeof body.cli === "string" && body.cli ? group.clis.find((c) => c.id === body.cli) : void 0;
|
|
7685
|
+
if (body.cli !== void 0 && body.cli !== "" && !cli) return json(res, 400, { error: `no such agent CLI: ${String(body.cli)}` });
|
|
7686
|
+
let pick = {};
|
|
7687
|
+
if (p === "/start" || p === "/send") {
|
|
7688
|
+
const target = group.target(body.id, cli);
|
|
7689
|
+
const r = checkPick(body, group.offer(target), target.name);
|
|
7690
|
+
if ("error" in r) return json(res, 400, { error: r.error });
|
|
7691
|
+
pick = r;
|
|
7692
|
+
}
|
|
6068
7693
|
switch (p) {
|
|
6069
|
-
case "/
|
|
7694
|
+
case "/start": {
|
|
6070
7695
|
try {
|
|
6071
|
-
const s = named ? session : group.forPrompt();
|
|
7696
|
+
const s = named ? session : group.forPrompt(void 0, cli, pick);
|
|
6072
7697
|
await s.start(Number(body.cols), Number(body.rows));
|
|
6073
7698
|
return json(res, 200, s.info());
|
|
6074
7699
|
} catch (e) {
|
|
6075
7700
|
return failed(e);
|
|
6076
7701
|
}
|
|
6077
7702
|
}
|
|
6078
|
-
case "/
|
|
7703
|
+
case "/send": {
|
|
6079
7704
|
if (typeof body.text !== "string" || !body.text.trim()) return json(res, 400, { error: "text is required" });
|
|
6080
7705
|
try {
|
|
6081
|
-
const s = group.forPrompt(body.id);
|
|
6082
|
-
await s.send(body.text, Array.isArray(body.notes) ? body.notes.slice(0, 200) : []);
|
|
7706
|
+
const s = group.forPrompt(body.id, cli, pick);
|
|
7707
|
+
await s.send(body.text, Array.isArray(body.notes) ? body.notes.slice(0, 200) : [], { title: body.title, task: body.task });
|
|
6083
7708
|
return json(res, 200, { ok: true, id: s.id });
|
|
6084
7709
|
} catch (e) {
|
|
6085
7710
|
return failed(e);
|
|
6086
7711
|
}
|
|
6087
7712
|
}
|
|
6088
|
-
case "/
|
|
7713
|
+
case "/mode":
|
|
6089
7714
|
if (body.mode !== "shared" && body.mode !== "fresh") return json(res, 400, { error: "mode must be shared or fresh" });
|
|
6090
7715
|
group.setMode(body.mode);
|
|
6091
7716
|
return json(res, 200, group.info());
|
|
6092
|
-
case "/
|
|
7717
|
+
case "/end":
|
|
7718
|
+
for (const s of named ? [session] : [...group.sessions]) group.drop(s);
|
|
7719
|
+
return json(res, 200, { ok: true });
|
|
7720
|
+
case "/stop":
|
|
6093
7721
|
if (named) session.stop();
|
|
6094
7722
|
else for (const s of group.sessions) s.stop();
|
|
6095
7723
|
return json(res, 200, { ok: true });
|
|
6096
|
-
case "/
|
|
7724
|
+
case "/worktrees":
|
|
7725
|
+
if (typeof body.on !== "boolean") return json(res, 400, { error: "on must be true or false" });
|
|
7726
|
+
try {
|
|
7727
|
+
group.setWorktrees(body.on);
|
|
7728
|
+
return json(res, 200, group.info());
|
|
7729
|
+
} catch (e) {
|
|
7730
|
+
return failed(e);
|
|
7731
|
+
}
|
|
7732
|
+
case "/worktree": {
|
|
7733
|
+
if (typeof body.branch !== "string" || !["keep", "merge", "discard"].includes(body.action)) return json(res, 400, { error: "branch and action (keep, merge or discard) are required" });
|
|
7734
|
+
try {
|
|
7735
|
+
const r = await group.worktree(body.branch, body.action, body.confirm === true);
|
|
7736
|
+
return json(res, r.ok ? 200 : 409, r);
|
|
7737
|
+
} catch (e) {
|
|
7738
|
+
return failed(e);
|
|
7739
|
+
}
|
|
7740
|
+
}
|
|
7741
|
+
case "/dismiss":
|
|
6097
7742
|
if (!named) return json(res, 400, { error: "id is required" });
|
|
6098
7743
|
if (session.running) return json(res, 409, { error: "stop the session first" });
|
|
6099
7744
|
group.drop(session);
|
|
@@ -6101,38 +7746,103 @@ function agentRoutes(opts, root, base) {
|
|
|
6101
7746
|
}
|
|
6102
7747
|
if (!session) return json(res, 409, { error: "no agent session" });
|
|
6103
7748
|
switch (p) {
|
|
6104
|
-
case "/
|
|
7749
|
+
case "/input":
|
|
6105
7750
|
if (typeof body.data === "string") session.write(body.data);
|
|
6106
7751
|
return json(res, 200, { ok: true });
|
|
6107
|
-
case "/
|
|
7752
|
+
case "/resize":
|
|
6108
7753
|
session.resize(Number(body.cols), Number(body.rows));
|
|
6109
7754
|
return json(res, 200, { ok: true });
|
|
6110
|
-
case "/
|
|
6111
|
-
const
|
|
6112
|
-
if (!
|
|
6113
|
-
if (!session.answer(
|
|
7755
|
+
case "/answer": {
|
|
7756
|
+
const keys = keysFor(session), key = keys && (body.choice === "allow" ? keys.allow : body.choice === "deny" ? keys.deny : void 0);
|
|
7757
|
+
if (!key) return json(res, 400, { error: "choice must be allow or deny" });
|
|
7758
|
+
if (!session.answer(key, body.choice)) return json(res, 409, { error: "the agent is not waiting for approval" });
|
|
6114
7759
|
return json(res, 200, { ok: true });
|
|
6115
7760
|
}
|
|
6116
|
-
case "/
|
|
7761
|
+
case "/choose": {
|
|
6117
7762
|
const index = Number(body.index);
|
|
6118
7763
|
if (!Number.isInteger(index) || index < 0) return json(res, 400, { error: "index is required" });
|
|
6119
7764
|
if (!await session.choose(index, typeof body.text === "string" ? body.text.slice(0, 4e3) : void 0)) return json(res, 409, { error: "no such option on the agent's screen" });
|
|
6120
7765
|
return json(res, 200, { ok: true });
|
|
6121
7766
|
}
|
|
6122
|
-
case "/
|
|
7767
|
+
case "/ack":
|
|
6123
7768
|
session.acknowledge();
|
|
6124
7769
|
return json(res, 200, { ok: true });
|
|
7770
|
+
case "/attach": {
|
|
7771
|
+
const r = group.attach(session.id, { path: body.path, url: body.url, title: body.title });
|
|
7772
|
+
return "error" in r ? json(res, 400, r) : json(res, 200, r);
|
|
7773
|
+
}
|
|
6125
7774
|
}
|
|
6126
7775
|
return json(res, 404, { error: "unknown agent endpoint" });
|
|
6127
7776
|
}
|
|
6128
7777
|
};
|
|
6129
7778
|
}
|
|
6130
7779
|
|
|
7780
|
+
// agent/src/server.ts
|
|
7781
|
+
var HERE2 = typeof __dirname === "string" ? __dirname : import_node_path7.default.dirname((0, import_node_url2.fileURLToPath)(void 0));
|
|
7782
|
+
var DIST = import_node_path7.default.basename(HERE2) === "dist" ? HERE2 : import_node_path7.default.join(HERE2, "../dist");
|
|
7783
|
+
var DEFAULT_COMMANDS = [
|
|
7784
|
+
{ label: "Apply notes", title: "Ask the agent to apply the open notes", prompt: "Apply the open Redline notes {ids} on {pages}, following the redline skill. Mark each one done when it is applied." }
|
|
7785
|
+
];
|
|
7786
|
+
var MCP_TOKEN = (0, import_node_crypto3.randomBytes)(24).toString("base64url");
|
|
7787
|
+
var terminalPage = (base) => `<!doctype html><html><head><meta charset="utf-8"><title>Agent</title>
|
|
7788
|
+
<style>html,body{margin:0;height:100%;background:#131316;overflow:hidden}#t{position:absolute;inset:4px 2px 2px 8px}</style></head>
|
|
7789
|
+
<body><div id="t"></div><script type="module" src="${base}/agent/terminal.js"></script></body></html>`;
|
|
7790
|
+
function agentRoutes(opts, root, base, dir = ".redline") {
|
|
7791
|
+
const { commands: given, hotkey: hk, key: k, ...bridgeOpts } = opts;
|
|
7792
|
+
const commands = (given ?? DEFAULT_COMMANDS).filter((c) => c && typeof c.label === "string" && typeof c.prompt === "string");
|
|
7793
|
+
const hotkey = hk === false ? false : typeof hk === "string" && hk ? hk : "alt+shift+a";
|
|
7794
|
+
const key = k === false ? false : typeof k === "string" && k.length === 1 ? k.toLowerCase() : "a";
|
|
7795
|
+
let origin = "";
|
|
7796
|
+
const bridge = createBridge({
|
|
7797
|
+
...bridgeOpts,
|
|
7798
|
+
root,
|
|
7799
|
+
info: () => ({ commands, hotkey, key }),
|
|
7800
|
+
worktreeDir: import_node_path7.default.join(import_node_path7.default.resolve(root, dir), "worktrees"),
|
|
7801
|
+
branchPrefix: "redline/",
|
|
7802
|
+
sessionEnv: "REDLINE_AGENT_SESSION",
|
|
7803
|
+
mcp: (id) => origin ? [{ name: "redline", url: `${origin}${base}/mcp`, headers: { authorization: `Bearer ${MCP_TOKEN}`, "x-redline-agent-session": id } }] : []
|
|
7804
|
+
});
|
|
7805
|
+
const group = bridge.group;
|
|
7806
|
+
return {
|
|
7807
|
+
panel: `${base}/agent/panel.js`,
|
|
7808
|
+
mcp: {
|
|
7809
|
+
token: MCP_TOKEN,
|
|
7810
|
+
sessions: () => group.info().sessions,
|
|
7811
|
+
tail: (id, lines) => group.sessions.find((s) => s.id === id)?.tail(lines) ?? null,
|
|
7812
|
+
attach: (id, a) => group.attach(id, a),
|
|
7813
|
+
focus: (id, note) => group.focusOn(id, note)
|
|
7814
|
+
},
|
|
7815
|
+
async handle(req, res, p, allowed) {
|
|
7816
|
+
const method = req.method ?? "GET";
|
|
7817
|
+
if (allowed && typeof req.headers.host === "string" && /^[\w.:[\]-]+$/.test(req.headers.host)) origin = `${req.socket.encrypted ? "https" : "http"}://${req.headers.host}`;
|
|
7818
|
+
const asset = method === "GET" && (p === "/agent/panel.js" ? "panel.js" : p === "/agent/terminal.js" ? "terminal.js" : null);
|
|
7819
|
+
if (asset || method === "GET" && p === "/agent/terminal") {
|
|
7820
|
+
if (!allowed) return json(res, 403, { error: "the agent panel answers this machine only" });
|
|
7821
|
+
res.setHeader("cache-control", "no-store");
|
|
7822
|
+
if (!asset) {
|
|
7823
|
+
res.setHeader("content-type", "text/html; charset=utf-8");
|
|
7824
|
+
res.end(terminalPage(base));
|
|
7825
|
+
return;
|
|
7826
|
+
}
|
|
7827
|
+
const file = import_node_path7.default.join(DIST, asset);
|
|
7828
|
+
if (!(0, import_node_fs7.existsSync)(file)) return json(res, 404, { error: "agent panel not built" });
|
|
7829
|
+
res.setHeader("content-type", "text/javascript; charset=utf-8");
|
|
7830
|
+
res.end(await (0, import_promises4.readFile)(file));
|
|
7831
|
+
return;
|
|
7832
|
+
}
|
|
7833
|
+
return bridge.handle(req, res, p.slice("/agent".length), { allowed });
|
|
7834
|
+
}
|
|
7835
|
+
};
|
|
7836
|
+
}
|
|
7837
|
+
|
|
6131
7838
|
// agent/src/index.ts
|
|
6132
7839
|
function agent(opts = {}) {
|
|
6133
|
-
return { routes: ({ root, base }) => agentRoutes(opts, root, base) };
|
|
7840
|
+
return { routes: ({ root, base, dir }) => agentRoutes(opts, root, base, dir) };
|
|
6134
7841
|
}
|
|
6135
7842
|
// Annotate the CommonJS export names for ESM import in node:
|
|
6136
7843
|
0 && (module.exports = {
|
|
6137
|
-
|
|
7844
|
+
adapterFor,
|
|
7845
|
+
agent,
|
|
7846
|
+
claudeCode,
|
|
7847
|
+
openCode
|
|
6138
7848
|
});
|