agentmast 0.0.0-stage → 0.1.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/dist/bin.js +153 -0
- package/dist/bot-HTAE3OOZ.js +215 -0
- package/dist/bus-6EDCL6C2.js +168 -0
- package/dist/chunk-FRKDGPVA.js +216 -0
- package/dist/chunk-LOCISTVR.js +125 -0
- package/dist/chunk-QCSXSHRA.js +16 -0
- package/dist/chunk-SNKD4OK2.js +67 -0
- package/dist/chunk-TV3CPBRC.js +62 -0
- package/dist/chunk-UZGN4SDK.js +153 -0
- package/dist/chunk-XFF5UE5F.js +40 -0
- package/dist/config-MJRV3XTY.js +12 -0
- package/dist/hook-transport-RECZISPK.js +11 -0
- package/dist/hook.js +11 -0
- package/dist/hooks-GYQZJCWH.js +231 -0
- package/dist/local-state-K2T7BJTT.js +17 -0
- package/dist/pairing-RQBLIMDP.js +119 -0
- package/dist/replay-4LHZWBSJ.js +81 -0
- package/dist/server-NJK23UFH.js +487 -0
- package/dist/video-RJZII4N6.js +153 -0
- package/dist/web/assets/index-CMw6GB5R.css +1 -0
- package/dist/web/assets/index-CiSHj7dg.js +48 -0
- package/dist/web/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
- package/dist/web/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
- package/dist/web/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
- package/dist/web/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
- package/dist/web/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
- package/dist/web/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
- package/dist/web/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
- package/dist/web/index.html +14 -0
- package/dist/web/licenses/Inter.txt +93 -0
- package/dist/web/licenses/JetBrains-Mono.txt +93 -0
- package/package.json +34 -4
- package/README.md +0 -3
package/dist/bin.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/bin.ts
|
|
4
|
+
import { spawn } from "child_process";
|
|
5
|
+
import { existsSync } from "fs";
|
|
6
|
+
import { dirname, join, resolve } from "path";
|
|
7
|
+
import { fileURLToPath } from "url";
|
|
8
|
+
var VERSION = "0.1.1";
|
|
9
|
+
var here = dirname(fileURLToPath(import.meta.url));
|
|
10
|
+
function parseArgs(argv) {
|
|
11
|
+
const [cmd2 = "help", ...rest] = argv;
|
|
12
|
+
const flags2 = {};
|
|
13
|
+
const positional2 = [];
|
|
14
|
+
for (let i = 0; i < rest.length; i++) {
|
|
15
|
+
const a = rest[i];
|
|
16
|
+
if (a === "--") {
|
|
17
|
+
positional2.push(...rest.slice(i + 1));
|
|
18
|
+
break;
|
|
19
|
+
}
|
|
20
|
+
if (a.startsWith("--")) {
|
|
21
|
+
const [k, v] = a.slice(2).split("=");
|
|
22
|
+
if (v !== void 0) flags2[k] = v;
|
|
23
|
+
else if (rest[i + 1] && !rest[i + 1].startsWith("--")) flags2[k] = rest[++i];
|
|
24
|
+
else flags2[k] = true;
|
|
25
|
+
} else positional2.push(a);
|
|
26
|
+
}
|
|
27
|
+
return { cmd: cmd2, flags: flags2, positional: positional2 };
|
|
28
|
+
}
|
|
29
|
+
function webDir() {
|
|
30
|
+
const candidates = [join(here, "web"), resolve(here, "../../web/dist")];
|
|
31
|
+
return candidates.find((d) => existsSync(join(d, "index.html")));
|
|
32
|
+
}
|
|
33
|
+
function openBrowser(url) {
|
|
34
|
+
const cmd2 = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
|
|
35
|
+
const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
36
|
+
try {
|
|
37
|
+
spawn(cmd2, args, { stdio: "ignore", detached: true }).unref();
|
|
38
|
+
} catch {
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
var banner = (url, extra = "") => console.log(`
|
|
42
|
+
\u25A3 AgentMast v${VERSION}${extra}
|
|
43
|
+
\u279C ${url}
|
|
44
|
+
`);
|
|
45
|
+
async function cmdUp(flags2) {
|
|
46
|
+
const [{ Bus }, { startServer }, { DEFAULT_PORT, loadOrCreateToken, stateDir, writeAtomically }] = await Promise.all([
|
|
47
|
+
import("./bus-6EDCL6C2.js"),
|
|
48
|
+
import("./server-NJK23UFH.js"),
|
|
49
|
+
import("./local-state-K2T7BJTT.js")
|
|
50
|
+
]);
|
|
51
|
+
const port = Number(flags2.port ?? DEFAULT_PORT);
|
|
52
|
+
if (flags2.port === true || !Number.isInteger(port) || port < 0 || port > 65535) throw new Error("Invalid port");
|
|
53
|
+
const token = loadOrCreateToken();
|
|
54
|
+
const bus = new Bus({ mode: "live", persist: true });
|
|
55
|
+
const approvalTimeoutSec = flags2["approval-timeout"] === void 0 ? void 0 : Number(flags2["approval-timeout"]);
|
|
56
|
+
if (flags2["approval-timeout"] === true) throw new Error("Expected seconds after --approval-timeout");
|
|
57
|
+
const srv = await startServer({ bus, port, token, approvalTimeoutSec, webDir: webDir() });
|
|
58
|
+
try {
|
|
59
|
+
writeAtomically(join(stateDir(), "port"), `${new URL(srv.url).port}
|
|
60
|
+
`);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
srv.close();
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
banner(srv.url, " \u2014 live mode");
|
|
66
|
+
if (!flags2["no-open"]) openBrowser(srv.url);
|
|
67
|
+
void import("./config-MJRV3XTY.js").then(async ({ loadTelegramConfig }) => {
|
|
68
|
+
const telegram = loadTelegramConfig();
|
|
69
|
+
if (telegram) await (await import("./bot-HTAE3OOZ.js")).runTelegram(telegram, bus);
|
|
70
|
+
}).catch((error) => console.warn(error instanceof Error ? error.message : "Telegram integration stopped."));
|
|
71
|
+
}
|
|
72
|
+
async function cmdDemo(flags2) {
|
|
73
|
+
const [{ Bus }, { startServer }, { ScenarioPlayer }, { scenarios }] = await Promise.all([
|
|
74
|
+
import("./bus-6EDCL6C2.js"),
|
|
75
|
+
import("./server-NJK23UFH.js"),
|
|
76
|
+
import("./replay-4LHZWBSJ.js"),
|
|
77
|
+
import("./video-RJZII4N6.js")
|
|
78
|
+
]);
|
|
79
|
+
const port = Number(flags2.port ?? 7788);
|
|
80
|
+
const name = String(flags2.scenario ?? "video");
|
|
81
|
+
const scenario = scenarios[name];
|
|
82
|
+
if (!scenario) {
|
|
83
|
+
console.error(`Unknown scenario "${name}". Available: ${Object.keys(scenarios).join(", ")}`);
|
|
84
|
+
process.exit(1);
|
|
85
|
+
}
|
|
86
|
+
const bus = new Bus({ mode: "demo" });
|
|
87
|
+
const player = new ScenarioPlayer(bus, scenario, {
|
|
88
|
+
loop: Boolean(flags2.loop),
|
|
89
|
+
speed: Number(flags2.speed ?? 1)
|
|
90
|
+
});
|
|
91
|
+
const delayMs = Number(flags2.delay ?? 1.5) * 1e3;
|
|
92
|
+
const srv = await startServer({
|
|
93
|
+
bus,
|
|
94
|
+
port,
|
|
95
|
+
webDir: webDir(),
|
|
96
|
+
// start the timeline once a browser is watching, so recordings begin cleanly
|
|
97
|
+
onFirstWebClient: () => setTimeout(() => player.start(), delayMs),
|
|
98
|
+
onClientMessage: (msg) => {
|
|
99
|
+
if (msg.type === "demo_restart") player.start();
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
banner(srv.url, ` \u2014 demo "${scenario.id}" (press R in the page to restart)`);
|
|
103
|
+
if (!flags2["no-open"]) openBrowser(srv.url);
|
|
104
|
+
}
|
|
105
|
+
async function cmdHooks(flags2, install) {
|
|
106
|
+
const { updateClaudeHooks, updateCodexHooks, updateZCodeHooks, updateAntigravityHooks } = await import("./hooks-GYQZJCWH.js");
|
|
107
|
+
const installers = { codex: updateCodexHooks, zcode: updateZCodeHooks, antigravity: updateAntigravityHooks };
|
|
108
|
+
const selected = Object.keys(installers).filter((provider2) => flags2[provider2]);
|
|
109
|
+
if (selected.length > 1) throw new Error("Choose one hook provider per command.");
|
|
110
|
+
const provider = selected[0];
|
|
111
|
+
const hookPath = install ? [join(here, "hook.js"), resolve(here, "../dist/hook.js")].find((path) => existsSync(path)) : void 0;
|
|
112
|
+
if (install && !hookPath) throw new Error("AgentMast hook executable is missing. Run npm run build first.");
|
|
113
|
+
const update = provider ? installers[provider] : updateClaudeHooks;
|
|
114
|
+
console.log(update(Boolean(flags2.project), hookPath));
|
|
115
|
+
if (install && provider === "codex") console.log("Open /hooks in a new Codex session to review and trust the AgentMast hooks.");
|
|
116
|
+
if (install && provider === "zcode") console.log("Check Settings \u2192 Hooks in ZCode and review workspace hooks before starting a new session.");
|
|
117
|
+
if (install && provider === "antigravity") console.log("Start a new Antigravity conversation. Use /hooks in the CLI to check the installed hooks.");
|
|
118
|
+
}
|
|
119
|
+
function help() {
|
|
120
|
+
console.log(`AgentMast v${VERSION}
|
|
121
|
+
|
|
122
|
+
Usage:
|
|
123
|
+
agentmast demo [--scenario video] [--loop] [--speed 1] [--delay 1.5] [--port 7788] [--no-open]
|
|
124
|
+
agentmast up [--port 7788] [--approval-timeout 300] [--no-open]
|
|
125
|
+
agentmast install-hooks [--codex|--zcode|--antigravity] [--project]
|
|
126
|
+
agentmast uninstall-hooks [--codex|--zcode|--antigravity] [--project]
|
|
127
|
+
agentmast telegram setup pair a private Telegram chat
|
|
128
|
+
|
|
129
|
+
Coming next: policy test, run -- <cmd>, bench
|
|
130
|
+
`);
|
|
131
|
+
}
|
|
132
|
+
var { cmd, flags, positional } = parseArgs(process.argv.slice(2));
|
|
133
|
+
var commands = {
|
|
134
|
+
up: () => cmdUp(flags),
|
|
135
|
+
demo: () => cmdDemo(flags),
|
|
136
|
+
"install-hooks": () => cmdHooks(flags, true),
|
|
137
|
+
"uninstall-hooks": () => cmdHooks(flags, false),
|
|
138
|
+
telegram: async () => {
|
|
139
|
+
if (positional[0] !== "setup") return help();
|
|
140
|
+
await (await import("./pairing-RQBLIMDP.js")).setupTelegram();
|
|
141
|
+
},
|
|
142
|
+
hook: async () => (await import("./hook-transport-RECZISPK.js")).runHook(positional),
|
|
143
|
+
help,
|
|
144
|
+
"--help": help,
|
|
145
|
+
"-h": help,
|
|
146
|
+
"--version": () => console.log(VERSION)
|
|
147
|
+
};
|
|
148
|
+
Promise.resolve((commands[cmd] ?? help)()).catch((err) => {
|
|
149
|
+
if (err.code === "EADDRINUSE") {
|
|
150
|
+
console.error(`Port already in use. Try --port ${Number(flags.port ?? 7788) + 1}`);
|
|
151
|
+
} else console.error(err);
|
|
152
|
+
process.exit(1);
|
|
153
|
+
});
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
botApiSignal,
|
|
4
|
+
createTelegramBot,
|
|
5
|
+
pollTelegram,
|
|
6
|
+
retryableTelegramError,
|
|
7
|
+
telegramFailure
|
|
8
|
+
} from "./chunk-TV3CPBRC.js";
|
|
9
|
+
import {
|
|
10
|
+
MAX_APPROVAL_REPLY_LENGTH
|
|
11
|
+
} from "./chunk-LOCISTVR.js";
|
|
12
|
+
|
|
13
|
+
// src/telegram/bot.ts
|
|
14
|
+
import { GrammyError } from "grammy";
|
|
15
|
+
|
|
16
|
+
// src/telegram/render.ts
|
|
17
|
+
var MESSAGE_BUDGET = 3700;
|
|
18
|
+
function approvalText(approval) {
|
|
19
|
+
const { detail } = approval;
|
|
20
|
+
if (approval.origin === "zcode") {
|
|
21
|
+
if (detail.tool !== "Read" || typeof detail.filePath !== "string" || !detail.filePath.trim() || detail.filePath.length > 512 || /[\p{Cc}\p{Cf}]/u.test(detail.filePath)) return;
|
|
22
|
+
return `NATIVE \xB7 ZCode permission request
|
|
23
|
+
Read
|
|
24
|
+
${detail.filePath}`;
|
|
25
|
+
}
|
|
26
|
+
return [
|
|
27
|
+
`${approval.origin ? "NATIVE" : approval.risk.toUpperCase()} \xB7 ${approval.summary}`,
|
|
28
|
+
detail.tool,
|
|
29
|
+
detail.description,
|
|
30
|
+
detail.command,
|
|
31
|
+
detail.filePath,
|
|
32
|
+
detail.diffPreview,
|
|
33
|
+
detail.context
|
|
34
|
+
].filter(Boolean).join("\n");
|
|
35
|
+
}
|
|
36
|
+
function resultText(item) {
|
|
37
|
+
const d = item.decision;
|
|
38
|
+
if (!d) return "Awaiting decision";
|
|
39
|
+
const destination = item.request.origin === "zcode" ? "ZCode" : item.request.origin === "codex" ? "Codex" : "the terminal";
|
|
40
|
+
if (d.by === "timeout") return `Timed out \xB7 Continue in ${destination}`;
|
|
41
|
+
if (d.by === "session_end") return "Session ended";
|
|
42
|
+
if (d.by === "cancelled") return "Approval cancelled";
|
|
43
|
+
if (d.action === "defer") return `Continue in ${destination}`;
|
|
44
|
+
const via = d.by === "telegram" ? " \xB7 via Telegram" : d.by === "web" ? " \xB7 via Web" : "";
|
|
45
|
+
return { approve: "Approved", reject: "Rejected", reply: "Reply sent" }[d.action] + via;
|
|
46
|
+
}
|
|
47
|
+
function renderApprovals(header, items) {
|
|
48
|
+
const text = items.map((item) => {
|
|
49
|
+
const body = item.actionable ? item.fullText : "Open AgentMast to review the complete permission request.";
|
|
50
|
+
return `${body}
|
|
51
|
+
${resultText(item)}`;
|
|
52
|
+
});
|
|
53
|
+
return {
|
|
54
|
+
text: [header, ...text].join("\n\n"),
|
|
55
|
+
reply_markup: {
|
|
56
|
+
inline_keyboard: items.filter((item) => item.actionable && !item.decision).map(({ request }) => [
|
|
57
|
+
{ text: "Approve", callback_data: `a:${request.id}:approve` },
|
|
58
|
+
{ text: "Reject", callback_data: `a:${request.id}:reject` },
|
|
59
|
+
{ text: "Reply", callback_data: `a:${request.id}:reply` }
|
|
60
|
+
])
|
|
61
|
+
},
|
|
62
|
+
link_preview_options: { is_disabled: true }
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// src/telegram/bot.ts
|
|
67
|
+
function installTelegramApprovals(bot, config, bus, report = console.warn) {
|
|
68
|
+
const { chatId, userId } = config;
|
|
69
|
+
const active = /* @__PURE__ */ new Map();
|
|
70
|
+
const groups = /* @__PURE__ */ new Set();
|
|
71
|
+
const pending = /* @__PURE__ */ new Map();
|
|
72
|
+
const replies = /* @__PURE__ */ new Map();
|
|
73
|
+
const delivery = new AbortController();
|
|
74
|
+
function forget(group) {
|
|
75
|
+
groups.delete(group);
|
|
76
|
+
if (active.get(group.sessionId) === group) active.delete(group.sessionId);
|
|
77
|
+
}
|
|
78
|
+
async function publish(group) {
|
|
79
|
+
if (delivery.signal.aborted || group.busy || group.retry) return;
|
|
80
|
+
group.busy = true;
|
|
81
|
+
const version = group.revision;
|
|
82
|
+
const { text, ...options } = renderApprovals(group.header, group.items);
|
|
83
|
+
try {
|
|
84
|
+
if (group.messageId === void 0) {
|
|
85
|
+
const sent = await bot.api.sendMessage(chatId, text, options, botApiSignal(delivery.signal));
|
|
86
|
+
group.messageId = sent.message_id;
|
|
87
|
+
} else {
|
|
88
|
+
await bot.api.editMessageText(chatId, group.messageId, text, options, botApiSignal(delivery.signal));
|
|
89
|
+
}
|
|
90
|
+
group.backoff = 1e3;
|
|
91
|
+
group.warned = false;
|
|
92
|
+
} catch (error) {
|
|
93
|
+
if (delivery.signal.aborted) return;
|
|
94
|
+
if (error instanceof GrammyError && error.error_code === 400 && error.description.includes("message is not modified")) {
|
|
95
|
+
} else {
|
|
96
|
+
if (!group.warned) report(telegramFailure(error));
|
|
97
|
+
group.warned = true;
|
|
98
|
+
if (retryableTelegramError(error) && Date.now() < group.items.at(-1).request.expiresAt + 12e4) {
|
|
99
|
+
const wait = error instanceof GrammyError && error.parameters.retry_after ? error.parameters.retry_after * 1e3 : group.backoff;
|
|
100
|
+
group.backoff = Math.min(15e3, group.backoff * 2);
|
|
101
|
+
group.retry = setTimeout(() => {
|
|
102
|
+
group.retry = void 0;
|
|
103
|
+
void publish(group);
|
|
104
|
+
}, wait);
|
|
105
|
+
group.retry.unref();
|
|
106
|
+
} else {
|
|
107
|
+
forget(group);
|
|
108
|
+
}
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
} finally {
|
|
112
|
+
group.busy = false;
|
|
113
|
+
}
|
|
114
|
+
if (group.revision !== version) void publish(group);
|
|
115
|
+
else if (group.items.every((item) => item.decision)) forget(group);
|
|
116
|
+
}
|
|
117
|
+
function created(request) {
|
|
118
|
+
if (request.risk === "low" || pending.has(request.id) || request.expiresAt <= Date.now()) return;
|
|
119
|
+
const session = bus.snapshot().sessions.find((item2) => item2.id === request.sessionId);
|
|
120
|
+
const title = session?.title ?? request.sessionId;
|
|
121
|
+
const fullHeader = `AgentMast \xB7 ${title}${session?.cwd ? `
|
|
122
|
+
${session.cwd}` : ""}`;
|
|
123
|
+
const fullText = approvalText(request);
|
|
124
|
+
const actionable = fullText !== void 0 && /^[\w-]+$/.test(request.id) && Buffer.byteLength(`a:${request.id}:approve`) <= 64 && fullHeader.length + fullText.length + 100 <= MESSAGE_BUDGET;
|
|
125
|
+
const header = actionable ? fullHeader : `AgentMast \xB7 ${title.slice(0, 120)}`;
|
|
126
|
+
const item = { request, fullText: fullText ?? "", actionable };
|
|
127
|
+
let group = active.get(request.sessionId);
|
|
128
|
+
if (!group || group.header !== header || request.createdAt - group.createdAt > 1e4 || group.items.every((entry) => entry.decision) || renderApprovals(group.header, [...group.items, item]).text.length + (group.items.length + 1) * 80 > MESSAGE_BUDGET) {
|
|
129
|
+
group = { sessionId: request.sessionId, header, createdAt: request.createdAt, items: [], revision: 0, busy: false, backoff: 1e3, warned: false };
|
|
130
|
+
active.set(request.sessionId, group);
|
|
131
|
+
groups.add(group);
|
|
132
|
+
}
|
|
133
|
+
group.items.push(item);
|
|
134
|
+
pending.set(request.id, { item, group });
|
|
135
|
+
group.revision++;
|
|
136
|
+
void publish(group);
|
|
137
|
+
}
|
|
138
|
+
function resolved(decision) {
|
|
139
|
+
const target = pending.get(decision.approvalId);
|
|
140
|
+
if (!target) return;
|
|
141
|
+
pending.delete(decision.approvalId);
|
|
142
|
+
for (const [messageId, approvalId] of replies) if (approvalId === decision.approvalId) replies.delete(messageId);
|
|
143
|
+
const { item, group } = target;
|
|
144
|
+
item.decision = decision;
|
|
145
|
+
group.revision++;
|
|
146
|
+
if (groups.has(group)) void publish(group);
|
|
147
|
+
}
|
|
148
|
+
bot.use(async (ctx, next) => {
|
|
149
|
+
if (ctx.chat?.type === "private" && ctx.chat.id === chatId && ctx.from?.id === userId && !ctx.from.is_bot) await next();
|
|
150
|
+
else report("Ignored an update from an unpaired Telegram chat.");
|
|
151
|
+
});
|
|
152
|
+
bot.command("start", async (ctx) => {
|
|
153
|
+
if (!ctx.match.trim()) await ctx.reply("AgentMast is paired to this chat. New approval requests will appear here.");
|
|
154
|
+
});
|
|
155
|
+
bot.callbackQuery(/^a:([\w-]+):(approve|reject|reply)$/, async (ctx) => {
|
|
156
|
+
const [, approvalId, action] = ctx.match;
|
|
157
|
+
const target = pending.get(approvalId);
|
|
158
|
+
const request = bus.getApproval(approvalId);
|
|
159
|
+
if (!target?.item.actionable || !request || request.expiresAt <= Date.now() || ctx.callbackQuery.message?.message_id !== target.group.messageId || target.group.messageId === void 0) {
|
|
160
|
+
await ctx.answerCallbackQuery("This approval is no longer available here.");
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (action === "reply") {
|
|
164
|
+
const alreadyPrompted = [...replies.values()].includes(approvalId);
|
|
165
|
+
await ctx.answerCallbackQuery(alreadyPrompted ? "Reply to the existing AgentMast prompt." : "Send a reply to AgentMast.");
|
|
166
|
+
if (!alreadyPrompted) {
|
|
167
|
+
const prompt = await ctx.reply("Reply with feedback. This will decline the current request and send your reason to the agent.", {
|
|
168
|
+
reply_markup: { force_reply: true, input_field_placeholder: "Tell the agent what to change" },
|
|
169
|
+
reply_parameters: { message_id: target.group.messageId, allow_sending_without_reply: true }
|
|
170
|
+
});
|
|
171
|
+
if (pending.has(approvalId)) replies.set(prompt.message_id, approvalId);
|
|
172
|
+
}
|
|
173
|
+
} else {
|
|
174
|
+
const applied = bus.decide({ approvalId, action: action === "approve" ? "approve" : "reject", by: "telegram" });
|
|
175
|
+
await ctx.answerCallbackQuery(applied ? action === "approve" ? "Approved" : "Rejected" : "This approval is no longer pending.");
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
bot.on("message:text", async (ctx) => {
|
|
179
|
+
const replyTo = ctx.message.reply_to_message?.message_id;
|
|
180
|
+
const approvalId = replyTo === void 0 ? void 0 : replies.get(replyTo);
|
|
181
|
+
if (!approvalId) return;
|
|
182
|
+
const raw = ctx.message.text;
|
|
183
|
+
if (!raw.trim() || raw.length > MAX_APPROVAL_REPLY_LENGTH) {
|
|
184
|
+
await ctx.reply(`Enter feedback of up to ${MAX_APPROVAL_REPLY_LENGTH} characters.`);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const applied = bus.decide({ approvalId, action: "reply", text: raw.trim(), by: "telegram" });
|
|
188
|
+
await ctx.reply(applied ? "Reply sent." : "This approval is no longer pending.");
|
|
189
|
+
});
|
|
190
|
+
const unsubscribe = bus.subscribe((msg) => {
|
|
191
|
+
if (msg.type === "approval_created") created(msg.approval);
|
|
192
|
+
if (msg.type === "approval_resolved") resolved(msg.decision);
|
|
193
|
+
});
|
|
194
|
+
for (const approval of bus.snapshot().approvals) created(approval);
|
|
195
|
+
return () => {
|
|
196
|
+
delivery.abort();
|
|
197
|
+
unsubscribe();
|
|
198
|
+
for (const group of groups) clearTimeout(group.retry);
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
async function runTelegram(config, bus) {
|
|
202
|
+
const bot = createTelegramBot(config.token);
|
|
203
|
+
const controller = new AbortController();
|
|
204
|
+
const dispose = installTelegramApprovals(bot, config, bus);
|
|
205
|
+
try {
|
|
206
|
+
await pollTelegram(bot, ["message", "callback_query"], controller.signal, console.warn);
|
|
207
|
+
} finally {
|
|
208
|
+
controller.abort();
|
|
209
|
+
dispose();
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
export {
|
|
213
|
+
installTelegramApprovals,
|
|
214
|
+
runTelegram
|
|
215
|
+
};
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
DEFAULT_APPROVAL_TIMEOUT_SEC
|
|
4
|
+
} from "./chunk-QCSXSHRA.js";
|
|
5
|
+
import {
|
|
6
|
+
stateDir
|
|
7
|
+
} from "./chunk-SNKD4OK2.js";
|
|
8
|
+
import {
|
|
9
|
+
reduceSession
|
|
10
|
+
} from "./chunk-LOCISTVR.js";
|
|
11
|
+
|
|
12
|
+
// src/daemon/bus.ts
|
|
13
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
14
|
+
import { join } from "path";
|
|
15
|
+
var Bus = class {
|
|
16
|
+
mode;
|
|
17
|
+
sessions = /* @__PURE__ */ new Map();
|
|
18
|
+
approvals = /* @__PURE__ */ new Map();
|
|
19
|
+
interruptedTurns = /* @__PURE__ */ new Map();
|
|
20
|
+
datasets = /* @__PURE__ */ new Map();
|
|
21
|
+
listeners = /* @__PURE__ */ new Set();
|
|
22
|
+
logFile;
|
|
23
|
+
constructor(opts) {
|
|
24
|
+
this.mode = opts.mode;
|
|
25
|
+
if (opts.persist) {
|
|
26
|
+
const dir = stateDir();
|
|
27
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
28
|
+
this.logFile = join(dir, "events.jsonl");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
subscribe(fn) {
|
|
32
|
+
this.listeners.add(fn);
|
|
33
|
+
return () => this.listeners.delete(fn);
|
|
34
|
+
}
|
|
35
|
+
broadcast(msg) {
|
|
36
|
+
for (const fn of this.listeners) fn(msg);
|
|
37
|
+
}
|
|
38
|
+
snapshot() {
|
|
39
|
+
return {
|
|
40
|
+
type: "snapshot",
|
|
41
|
+
mode: this.mode,
|
|
42
|
+
sessions: [...this.sessions.values()],
|
|
43
|
+
approvals: [...this.approvals.values()].map((p) => p.req)
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
listDatasets() {
|
|
47
|
+
return [...this.datasets.values()];
|
|
48
|
+
}
|
|
49
|
+
addDataset(ds) {
|
|
50
|
+
this.datasets.set(ds.id, ds);
|
|
51
|
+
this.broadcast({ type: "token_dataset", dataset: ds });
|
|
52
|
+
}
|
|
53
|
+
ingest(ev) {
|
|
54
|
+
if (ev.type === "interrupt" && ev.turnId) this.interruptedTurns.set(ev.sessionId, ev.turnId);
|
|
55
|
+
if (ev.type === "session_end" || ev.type === "interrupt") {
|
|
56
|
+
for (const [id, pending] of this.approvals) {
|
|
57
|
+
if (pending.req.sessionId !== ev.sessionId) continue;
|
|
58
|
+
if (ev.type === "session_end" || !ev.turnId || !pending.turnId || ev.turnId === pending.turnId) {
|
|
59
|
+
this.decide({ approvalId: id, action: "reject", by: ev.type === "session_end" ? "session_end" : "cancelled" });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const next = reduceSession(this.sessions.get(ev.sessionId), ev);
|
|
64
|
+
this.sessions.set(ev.sessionId, next);
|
|
65
|
+
if (this.logFile) {
|
|
66
|
+
try {
|
|
67
|
+
appendFileSync(this.logFile, JSON.stringify(ev) + "\n", { mode: 384 });
|
|
68
|
+
} catch {
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
this.broadcast({ type: "session_update", session: next });
|
|
72
|
+
return next;
|
|
73
|
+
}
|
|
74
|
+
/** Registers an approval and resolves when someone (web / telegram / timeout) decides. */
|
|
75
|
+
requestApproval(req, tool) {
|
|
76
|
+
const now = Date.now();
|
|
77
|
+
const timeoutMs = (req.timeoutSec ?? DEFAULT_APPROVAL_TIMEOUT_SEC) * 1e3;
|
|
78
|
+
const session = this.sessions.get(req.sessionId);
|
|
79
|
+
if (req.origin) {
|
|
80
|
+
const interrupted = req.turnId && this.interruptedTurns.get(req.sessionId) === req.turnId;
|
|
81
|
+
if (session?.status === "done" || interrupted) {
|
|
82
|
+
return Promise.resolve({ approvalId: req.id, action: "reject", by: interrupted ? "cancelled" : "session_end" });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const full = {
|
|
86
|
+
id: req.id,
|
|
87
|
+
sessionId: req.sessionId,
|
|
88
|
+
risk: req.risk,
|
|
89
|
+
ruleId: req.ruleId,
|
|
90
|
+
origin: req.origin,
|
|
91
|
+
summary: req.summary,
|
|
92
|
+
detail: req.detail,
|
|
93
|
+
createdAt: now,
|
|
94
|
+
expiresAt: now + timeoutMs
|
|
95
|
+
};
|
|
96
|
+
return new Promise((resolve) => {
|
|
97
|
+
const timer = setTimeout(
|
|
98
|
+
() => this.decide({ approvalId: full.id, action: "reject", by: "timeout" }),
|
|
99
|
+
timeoutMs
|
|
100
|
+
);
|
|
101
|
+
this.approvals.set(full.id, { req: full, turnId: req.turnId, resolve, timer });
|
|
102
|
+
this.ingest({
|
|
103
|
+
sessionId: req.sessionId,
|
|
104
|
+
kind: req.origin ?? session?.kind ?? "claude-code",
|
|
105
|
+
ts: now,
|
|
106
|
+
type: "approval_request",
|
|
107
|
+
approvalId: full.id,
|
|
108
|
+
title: req.title,
|
|
109
|
+
cwd: req.cwd,
|
|
110
|
+
tool
|
|
111
|
+
});
|
|
112
|
+
this.broadcast({ type: "approval_created", approval: full });
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
/** Returns false if the approval does not exist (already handled / expired). */
|
|
116
|
+
decide(d) {
|
|
117
|
+
const p = this.approvals.get(d.approvalId);
|
|
118
|
+
if (!p || d.action === "defer" && (d.by !== "web" || !p.req.origin)) return false;
|
|
119
|
+
const resolvedAt = Date.now();
|
|
120
|
+
if ((d.by === "web" || d.by === "telegram" || d.by === "replay") && resolvedAt >= p.req.expiresAt) {
|
|
121
|
+
this.decide({ approvalId: d.approvalId, action: "reject", by: "timeout" });
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
this.approvals.delete(d.approvalId);
|
|
125
|
+
clearTimeout(p.timer);
|
|
126
|
+
const session = this.sessions.get(p.req.sessionId);
|
|
127
|
+
this.ingest({
|
|
128
|
+
sessionId: p.req.sessionId,
|
|
129
|
+
kind: session?.kind ?? "claude-code",
|
|
130
|
+
ts: resolvedAt,
|
|
131
|
+
type: "approval_resolved",
|
|
132
|
+
approvalId: d.approvalId,
|
|
133
|
+
approvalFallback: !!p.req.origin && (d.by === "timeout" || d.action === "defer"),
|
|
134
|
+
text: describeDecision(d, p.req.origin)
|
|
135
|
+
});
|
|
136
|
+
this.broadcast({ type: "approval_resolved", decision: { ...d, resolvedAt } });
|
|
137
|
+
p.resolve(d);
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
140
|
+
getApproval(id) {
|
|
141
|
+
return this.approvals.get(id)?.req;
|
|
142
|
+
}
|
|
143
|
+
/** Clears everything (used when a demo scenario loops). */
|
|
144
|
+
reset() {
|
|
145
|
+
for (const id of [...this.approvals.keys()]) this.decide({ approvalId: id, action: "reject", by: "session_end" });
|
|
146
|
+
this.sessions.clear();
|
|
147
|
+
this.interruptedTurns.clear();
|
|
148
|
+
this.broadcast(this.snapshot());
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
function describeDecision(d, origin) {
|
|
152
|
+
if (d.by === "cancelled") return "Approval cancelled";
|
|
153
|
+
const via = d.by === "telegram" ? " via Telegram" : d.by === "web" ? " via Web" : "";
|
|
154
|
+
switch (d.action) {
|
|
155
|
+
case "approve":
|
|
156
|
+
return `\u2705 Approved${via}`;
|
|
157
|
+
case "reject":
|
|
158
|
+
return d.by === "timeout" ? "\u23F1 Timed out \u2192 native prompt" : `\u26D4 Rejected${via}`;
|
|
159
|
+
case "reply":
|
|
160
|
+
return `\u{1F4AC} ${d.text ?? ""}`.trim();
|
|
161
|
+
case "defer":
|
|
162
|
+
return origin === "zcode" ? "Continue in ZCode" : "Continue in Codex";
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
export {
|
|
166
|
+
Bus,
|
|
167
|
+
describeDecision
|
|
168
|
+
};
|