ai-collab 0.0.0-stage → 0.9.0
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/.claude-plugin/marketplace.json +14 -0
- package/.claude-plugin/plugin.json +16 -0
- package/.codex-plugin/plugin.json +22 -0
- package/.cursor-plugin/plugin.json +15 -0
- package/.mcp.json +11 -0
- package/LICENSE +202 -0
- package/README.md +53 -2
- package/commands/afk.md +17 -0
- package/deploy/compose.yaml +31 -0
- package/hooks/codex-hooks.json +14 -0
- package/hooks/cursor-hooks.json +13 -0
- package/hooks/hooks.json +19 -0
- package/lib/activity.mjs +183 -0
- package/lib/agents.mjs +115 -0
- package/lib/approvals.mjs +210 -0
- package/lib/attachment.mjs +41 -0
- package/lib/cli.mjs +230 -0
- package/lib/codex-compact.mjs +124 -0
- package/lib/config.mjs +236 -0
- package/lib/controls.mjs +166 -0
- package/lib/family.mjs +50 -0
- package/lib/format.mjs +73 -0
- package/lib/inbox.mjs +250 -0
- package/lib/install-cursor.mjs +94 -0
- package/lib/install-opencode.mjs +80 -0
- package/lib/mode.mjs +158 -0
- package/lib/models.mjs +100 -0
- package/lib/names.mjs +60 -0
- package/lib/ntfy.mjs +182 -0
- package/lib/opencode-plugin.mjs +253 -0
- package/lib/process.mjs +42 -0
- package/lib/questions.mjs +115 -0
- package/lib/receipts.mjs +61 -0
- package/lib/sessions.mjs +161 -0
- package/lib/setup.mjs +195 -0
- package/lib/start.mjs +227 -0
- package/lib/state.mjs +65 -0
- package/lib/stop.mjs +191 -0
- package/lib/transcript.mjs +85 -0
- package/lib/usage.mjs +74 -0
- package/package.json +67 -4
- package/scripts/ai-collab +3 -0
- package/scripts/ai-collab-hook +3 -0
- package/scripts/ai-collab-hook.mjs +176 -0
- package/scripts/ai-collab-mcp.mjs +249 -0
- package/scripts/ai-collab.mjs +4 -0
- package/scripts/install-cursor.mjs +11 -0
- package/scripts/install-opencode.mjs +11 -0
- package/skills/ai-collab/SKILL.md +81 -0
- package/web/app/activity.jsx +171 -0
- package/web/app/api/[action]/route.js +8 -0
- package/web/app/api/auth/[step]/route.js +12 -0
- package/web/app/api/events/route.js +8 -0
- package/web/app/api/file/[name]/route.js +8 -0
- package/web/app/api/push/key/route.js +8 -0
- package/web/app/api/push/subscribe/route.js +12 -0
- package/web/app/api/push/test/route.js +8 -0
- package/web/app/api/version/route.js +6 -0
- package/web/app/cards.jsx +116 -0
- package/web/app/chat.jsx +764 -0
- package/web/app/globals.css +133 -0
- package/web/app/home.jsx +138 -0
- package/web/app/icon.svg +1 -0
- package/web/app/layout.jsx +16 -0
- package/web/app/logos.jsx +16 -0
- package/web/app/manifest.js +8 -0
- package/web/app/notify.jsx +136 -0
- package/web/app/page.jsx +9 -0
- package/web/app/providers.jsx +11 -0
- package/web/app/shadcn.css +638 -0
- package/web/components/ui/avatar.jsx +115 -0
- package/web/components/ui/badge.jsx +47 -0
- package/web/components/ui/button.jsx +63 -0
- package/web/components/ui/chat-container.jsx +52 -0
- package/web/components/ui/code-block.jsx +60 -0
- package/web/components/ui/dropdown-menu.jsx +257 -0
- package/web/components/ui/markdown.jsx +106 -0
- package/web/components/ui/message.jsx +92 -0
- package/web/components/ui/prompt-input.jsx +198 -0
- package/web/components/ui/scroll-button.jsx +34 -0
- package/web/components/ui/select.jsx +189 -0
- package/web/components/ui/sheet.jsx +152 -0
- package/web/components/ui/sonner.jsx +10 -0
- package/web/components/ui/tabs.jsx +88 -0
- package/web/components/ui/textarea.jsx +20 -0
- package/web/components/ui/tooltip.jsx +56 -0
- package/web/components.json +24 -0
- package/web/instrumentation.js +6 -0
- package/web/jsconfig.json +6 -0
- package/web/lib/activity-rows.js +215 -0
- package/web/lib/highlight.js +45 -0
- package/web/lib/session-state.js +64 -0
- package/web/lib/utils.js +6 -0
- package/web/next.config.mjs +26 -0
- package/web/postcss.config.mjs +1 -0
- package/web/proxy.js +25 -0
- package/web/public/sw.js +39 -0
- package/web/server/auth.mjs +154 -0
- package/web/server/hub.mjs +97 -0
- package/web/server/instance.js +5 -0
- package/web/server/push.mjs +139 -0
- package/web/server/ui.mjs +868 -0
package/lib/agents.mjs
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pulsar-style agent messaging on the existing primitives: inbox (claimInbox plus read receipts), wait (the Stop hook's
|
|
3
|
+
* ntfy stream waiter), respond (a msg envelope with replyTo and state), and send with await_reply.
|
|
4
|
+
*/
|
|
5
|
+
import { broadcastTopic, inboxTopic } from "./config.mjs";
|
|
6
|
+
import { RESPOND_STATES, claimInbox, parseEnvelope, replyToOperator, sendMessage } from "./inbox.mjs";
|
|
7
|
+
import { pollCached } from "./ntfy.mjs";
|
|
8
|
+
import { sendReceipts, settleReceipts } from "./receipts.mjs";
|
|
9
|
+
import { streamWaiter } from "./stop.mjs";
|
|
10
|
+
import { cleanBody } from "./format.mjs";
|
|
11
|
+
|
|
12
|
+
export const AGENT_WAIT_MAX_S = 45;
|
|
13
|
+
const HISTORY_TAIL_BYTES = 512 * 1024;
|
|
14
|
+
const MESSAGE_ID = /^[a-zA-Z0-9-]{1,64}$/;
|
|
15
|
+
|
|
16
|
+
function checkSeconds(seconds) {
|
|
17
|
+
if (!Number.isInteger(seconds) || seconds < 0 || seconds > AGENT_WAIT_MAX_S) {
|
|
18
|
+
throw new Error(`Wait must be an integer from 0 to ${AGENT_WAIT_MAX_S} seconds`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A claimed message as tool output: the body cleaned and capped, plus how to answer it. */
|
|
23
|
+
export function messageView(m) {
|
|
24
|
+
const respond = m.operatorThread ? "reply_to_operator or respond" : m.from === "ntfy" ? "send to all with reply_to" : "respond";
|
|
25
|
+
return { ...m, body: cleanBody(m.body), answer_with: `${respond} message_id=${m.id}` };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Claims new messages for this session (peek leaves them unread) and publishes read receipts for claimed ones. */
|
|
29
|
+
export async function readInbox(cfg, { peek = false, strict = true, claim = claimInbox } = {}) {
|
|
30
|
+
const messages = await claim(cfg, { commit: !peek, strict });
|
|
31
|
+
if (!peek) {
|
|
32
|
+
sendReceipts(cfg, messages.map((m) => m.id));
|
|
33
|
+
await settleReceipts();
|
|
34
|
+
}
|
|
35
|
+
return messages;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Blocks up to seconds for new messages to this session; returns {status:"messages"|"timeout", messages}. */
|
|
39
|
+
export async function waitForMessages(cfg, { seconds = 25, signal, claim = claimInbox, wait } = {}) {
|
|
40
|
+
checkSeconds(seconds);
|
|
41
|
+
const deadline = Date.now() + seconds * 1000;
|
|
42
|
+
const waitFor = wait ?? streamWaiter(cfg, Date.now());
|
|
43
|
+
for (let first = true; ; first = false) {
|
|
44
|
+
signal?.throwIfAborted();
|
|
45
|
+
const messages = await readInbox(cfg, { strict: first, claim });
|
|
46
|
+
if (messages.length) return { status: "messages", messages };
|
|
47
|
+
const remaining = deadline - Date.now();
|
|
48
|
+
if (remaining <= 0) return { status: "timeout", messages: [] };
|
|
49
|
+
if ((await waitFor(remaining, signal)) === "aborted") signal?.throwIfAborted();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Sends to an address, a peer, or all ("*"). With awaitSeconds > 0, blocks until a reply, done or declined answer to
|
|
55
|
+
* the sent message arrives, then claims the inbox and returns it with every other new message, so none is lost.
|
|
56
|
+
*/
|
|
57
|
+
export async function sendAndAwait(cfg, to, body, { awaitSeconds = 0, urgent, replyTo, attachment, signal, claim = claimInbox, wait } = {}) {
|
|
58
|
+
checkSeconds(awaitSeconds);
|
|
59
|
+
const target = to === "*" ? "all" : to;
|
|
60
|
+
const sent = await sendMessage(cfg, target, body, { urgent, replyTo, attachment });
|
|
61
|
+
const out = { sent: true, to: target, ...(sent.id ? { id: sent.id } : {}) };
|
|
62
|
+
if (!awaitSeconds) return out;
|
|
63
|
+
if (!sent.id) return { ...out, status: "pending", note: "ntfy returned no message id, so no reply can be matched." };
|
|
64
|
+
const deadline = Date.now() + awaitSeconds * 1000;
|
|
65
|
+
const waitFor = wait ?? streamWaiter(cfg, Date.now());
|
|
66
|
+
const final = (m) => m.replyTo === sent.id && m.state !== "working";
|
|
67
|
+
for (;;) {
|
|
68
|
+
signal?.throwIfAborted();
|
|
69
|
+
const peeked = await claim(cfg, { commit: false }).catch(() => []);
|
|
70
|
+
if (peeked.some(final)) {
|
|
71
|
+
const messages = await readInbox(cfg, { strict: false, claim });
|
|
72
|
+
const reply = messages.find(final);
|
|
73
|
+
if (reply) return { ...out, status: "replied", reply, messages: messages.filter((m) => m !== reply) };
|
|
74
|
+
}
|
|
75
|
+
const remaining = deadline - Date.now();
|
|
76
|
+
if (remaining <= 0) return { ...out, status: "pending", note: "No reply yet; call wait to keep listening." };
|
|
77
|
+
if ((await waitFor(remaining, signal)) === "aborted") signal?.throwIfAborted();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// The envelope (or plain phone text) of a message this session received, found in the newest history of its topics.
|
|
82
|
+
async function findReceived(cfg, id) {
|
|
83
|
+
for (const topic of [inboxTopic(cfg.project, cfg.peer), broadcastTopic(cfg.project)]) {
|
|
84
|
+
const events = await pollCached(cfg, topic, "all", undefined, { tailBytes: HISTORY_TAIL_BYTES });
|
|
85
|
+
const event = events.find((ev) => ev.id === id);
|
|
86
|
+
if (!event) continue;
|
|
87
|
+
const m = parseEnvelope(event.message);
|
|
88
|
+
if (!m) return topic === inboxTopic(cfg.project, cfg.peer) ? null : { broadcast: true, plain: true };
|
|
89
|
+
if (m.kind !== "msg") return null;
|
|
90
|
+
const toMe = topic === broadcastTopic(cfg.project) ? m.to === "all" : m.to === cfg.peer && (m.toSession === undefined || m.toSession === cfg.session);
|
|
91
|
+
return toMe ? { broadcast: topic === broadcastTopic(cfg.project), envelope: m } : null;
|
|
92
|
+
}
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Answers a received message with state working | reply | done | declined: an operator direct chat in its thread,
|
|
98
|
+
* a broadcast or operator message on the shared channel, a peer message to its sender's session.
|
|
99
|
+
*/
|
|
100
|
+
export async function respond(cfg, id, state, body = "") {
|
|
101
|
+
if (!cfg.session) throw new Error("Pass the session label supplied by the ai-collab hook");
|
|
102
|
+
if (typeof id !== "string" || !MESSAGE_ID.test(id)) throw new Error("Invalid message ID");
|
|
103
|
+
if (!RESPOND_STATES.includes(state)) throw new Error("state must be working, reply, done or declined");
|
|
104
|
+
const text = typeof body === "string" && body.trim() ? body : state;
|
|
105
|
+
const found = await findReceived(cfg, id);
|
|
106
|
+
if (!found) throw new Error("That message is unavailable for your session");
|
|
107
|
+
const m = found.envelope;
|
|
108
|
+
if (m?.from === "operator" && m.operatorThread === true) {
|
|
109
|
+
await replyToOperator(cfg, id, text, { state });
|
|
110
|
+
return { sent: true, to: "operator", state };
|
|
111
|
+
}
|
|
112
|
+
const to = found.broadcast || m.from === "operator" ? "all" : (typeof m.session === "string" && m.session ? `${m.from}#${m.session}` : m.from);
|
|
113
|
+
await sendMessage(cfg, to, text, { replyTo: id, state });
|
|
114
|
+
return { sent: true, to, state };
|
|
115
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phone approvals: a permission prompt (or Claude's AskUserQuestion) turned into a question on the broadcast topic
|
|
3
|
+
* that the operator answers from the UI or the ntfy app, only while AFK mode is on or quiet.
|
|
4
|
+
* Contract: {v:1, kind:"approval", from, session, harness, id, tool, summary, questions?, expiresAt, ts} asks;
|
|
5
|
+
* "reply <id> allow|deny" (or the answers as JSON, for a choice) answers; {v:1, kind:"approval-end", id, reason} closes.
|
|
6
|
+
* No answer, AFK turned off by the operator, the hook being killed, or any failure returns no decision,
|
|
7
|
+
* so the harness shows its own terminal prompt. Nothing here ever allows or denies on its own.
|
|
8
|
+
*/
|
|
9
|
+
import { randomBytes } from "node:crypto";
|
|
10
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
11
|
+
import { NTFY_MESSAGE_MAX_BYTES, broadcastTopic } from "./config.mjs";
|
|
12
|
+
import { publish, streamEvents } from "./ntfy.mjs";
|
|
13
|
+
import { stripControl } from "./format.mjs";
|
|
14
|
+
import { currentMode, parseMode, storedMode } from "./mode.mjs";
|
|
15
|
+
import { parsePhoneReply } from "./questions.mjs";
|
|
16
|
+
import { sendReceipts } from "./receipts.mjs";
|
|
17
|
+
import { summarize } from "../web/lib/activity-rows.js";
|
|
18
|
+
|
|
19
|
+
export const APPROVAL_ID = /^[a-f0-9]{12}$/;
|
|
20
|
+
export const END_REASONS = ["allowed", "denied", "answered", "timeout", "afk-off", "cancelled"];
|
|
21
|
+
const SUMMARY_MAX = 300;
|
|
22
|
+
const TOOL_MAX = 128;
|
|
23
|
+
const QUESTION_MAX = 500;
|
|
24
|
+
const HEADER_MAX = 40;
|
|
25
|
+
const LABEL_MAX = 100;
|
|
26
|
+
const QUESTIONS_MAX = 4;
|
|
27
|
+
const OPTIONS_MAX = 6;
|
|
28
|
+
const ALLOW = /^(allow|approve|yes|y|ok)$/i;
|
|
29
|
+
const DENY = /^(deny|reject|no|n)$/i;
|
|
30
|
+
const END_TIMEOUT_MS = 1500;
|
|
31
|
+
const RETRY_MAX_MS = 30_000;
|
|
32
|
+
const DENY_MESSAGE = "The operator denied this from the AI Collab phone UI.";
|
|
33
|
+
|
|
34
|
+
const text = (value, max) => typeof value === "string" ? stripControl(value).slice(0, max) : "";
|
|
35
|
+
|
|
36
|
+
/** AskUserQuestion questions with every field type-checked and capped, or null when the shape is wrong. */
|
|
37
|
+
export function cleanQuestions(raw, { descriptionMax = 300, previewMax = 2000 } = {}) {
|
|
38
|
+
if (!Array.isArray(raw) || !raw.length || raw.length > QUESTIONS_MAX) return null;
|
|
39
|
+
const out = [];
|
|
40
|
+
for (const q of raw) {
|
|
41
|
+
if (!q || typeof q.question !== "string" || !q.question.trim() || !Array.isArray(q.options) || !q.options.length) return null;
|
|
42
|
+
const options = q.options.slice(0, OPTIONS_MAX).map((o) => ({
|
|
43
|
+
label: text(o?.label, LABEL_MAX),
|
|
44
|
+
...(descriptionMax && text(o?.description, descriptionMax) ? { description: text(o.description, descriptionMax) } : {}),
|
|
45
|
+
...(previewMax && text(o?.preview, previewMax) ? { preview: text(o.preview, previewMax) } : {}),
|
|
46
|
+
}));
|
|
47
|
+
if (options.some((o) => !o.label)) return null;
|
|
48
|
+
out.push({ question: text(q.question, QUESTION_MAX), header: text(q.header, HEADER_MAX), multiSelect: q.multiSelect === true, options });
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Tool input as the one-line summary the Activity view shows; a command array is joined first.
|
|
54
|
+
function inputSummary(input) {
|
|
55
|
+
if (input === undefined || input === null) return "";
|
|
56
|
+
const value = input && typeof input === "object" && Array.isArray(input.command) ? { ...input, command: input.command.join(" ") } : input;
|
|
57
|
+
return text(summarize(typeof value === "string" ? value : JSON.stringify(value)), SUMMARY_MAX);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The request a hook input asks the operator for: {tool, summary, input, questions?}, or null. */
|
|
61
|
+
export function approvalRequest(host, key, msg) {
|
|
62
|
+
if (host === "cursor") {
|
|
63
|
+
if (key === "beforeshellexecution" && typeof msg.command === "string") return { tool: "Shell", summary: inputSummary({ command: msg.command }), input: msg };
|
|
64
|
+
if (key === "beforemcpexecution") return { tool: text(msg.tool_name, TOOL_MAX) || "MCP", summary: inputSummary(msg.tool_input), input: msg };
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
if (key !== "permissionrequest" || typeof msg.tool_name !== "string") return null;
|
|
68
|
+
const tool = text(msg.tool_name, TOOL_MAX);
|
|
69
|
+
if (host === "claude" && tool === "AskUserQuestion") {
|
|
70
|
+
const questions = cleanQuestions(msg.tool_input?.questions);
|
|
71
|
+
return questions ? { tool, summary: text(questions[0].question, SUMMARY_MAX), input: msg.tool_input, questions } : null;
|
|
72
|
+
}
|
|
73
|
+
return { tool, summary: inputSummary(msg.tool_input), input: msg.tool_input };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The approval envelope within ntfy's limit: long choice previews and descriptions shrink first; null if it cannot fit. */
|
|
77
|
+
export function approvalMessage(cfg, host, req, { id, expiresAt, ts = new Date().toISOString() }) {
|
|
78
|
+
const base = { v: 1, kind: "approval", from: cfg.peer, ...(cfg.session ? { session: cfg.session } : {}), harness: host, id, tool: req.tool, summary: req.summary, expiresAt, ts };
|
|
79
|
+
const tries = req.questions ? [[300, 2000], [200, 400], [100, 0], [0, 0]] : [[0, 0]];
|
|
80
|
+
for (const [descriptionMax, previewMax] of tries) {
|
|
81
|
+
const questions = req.questions ? cleanQuestions(req.questions, { descriptionMax, previewMax }) : undefined;
|
|
82
|
+
const message = JSON.stringify(questions ? { ...base, questions } : base);
|
|
83
|
+
if (Buffer.byteLength(message) <= NTFY_MESSAGE_MAX_BYTES) return message;
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// One option label matched case-insensitively, else the text itself (the "Other" answer).
|
|
89
|
+
function matchLabel(question, value) {
|
|
90
|
+
const found = question.options.find((o) => o.label.toLowerCase() === value.trim().toLowerCase());
|
|
91
|
+
return found ? found.label : value.trim();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Answers for a choice from a reply: JSON {question: answer}, or plain text for a single question; null when incomplete. */
|
|
95
|
+
export function parseChoice(questions, answer) {
|
|
96
|
+
let map = null;
|
|
97
|
+
try {
|
|
98
|
+
const value = JSON.parse(answer);
|
|
99
|
+
if (value && typeof value === "object" && !Array.isArray(value)) map = value;
|
|
100
|
+
} catch { /* plain text */ }
|
|
101
|
+
if (!map) {
|
|
102
|
+
if (questions.length !== 1) return null;
|
|
103
|
+
map = { [questions[0].question]: answer };
|
|
104
|
+
}
|
|
105
|
+
const answers = {};
|
|
106
|
+
for (const q of questions) {
|
|
107
|
+
const value = map[q.question];
|
|
108
|
+
if (typeof value !== "string" || !value.trim()) return null;
|
|
109
|
+
const parts = q.multiSelect ? value.split(",").filter((part) => part.trim()) : [value];
|
|
110
|
+
answers[q.question] = parts.map((part) => matchLabel(q, part)).join(", ");
|
|
111
|
+
}
|
|
112
|
+
return answers;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** A phone reply as a decision: {behavior:"allow"|"deny"} or {behavior:"allow", answers} for a choice; null when unusable. */
|
|
116
|
+
export function replyDecision(req, answer) {
|
|
117
|
+
if (req.questions) {
|
|
118
|
+
const answers = parseChoice(req.questions, answer);
|
|
119
|
+
return answers ? { behavior: "allow", answers } : null;
|
|
120
|
+
}
|
|
121
|
+
if (ALLOW.test(answer.trim())) return { behavior: "allow" };
|
|
122
|
+
if (DENY.test(answer.trim())) return { behavior: "deny" };
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Hook output for a decision; null means no decision (the harness's own prompt). */
|
|
127
|
+
export function approvalOutput(host, decision, req) {
|
|
128
|
+
if (host === "cursor") {
|
|
129
|
+
if (!decision) return { permission: "ask" };
|
|
130
|
+
return decision.behavior === "allow"
|
|
131
|
+
? { permission: "allow", user_message: "Allowed from the AI Collab phone UI.", agent_message: "The operator allowed this from their phone." }
|
|
132
|
+
: { permission: "deny", user_message: "Denied from the AI Collab phone UI.", agent_message: DENY_MESSAGE };
|
|
133
|
+
}
|
|
134
|
+
if (!decision) return {};
|
|
135
|
+
let body = decision.behavior === "allow" ? { behavior: "allow" } : { behavior: "deny", message: DENY_MESSAGE };
|
|
136
|
+
// Claude's AskUserQuestion takes the answers in updatedInput, next to the original questions.
|
|
137
|
+
if (host === "claude" && decision.answers) body = { behavior: "allow", updatedInput: { ...req.input, answers: decision.answers } };
|
|
138
|
+
return { hookSpecificOutput: { hookEventName: "PermissionRequest", decision: body } };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Streams the broadcast topic until the reply for id, a mode-off envelope newer than baseTs, the deadline, or an abort. Returns {decision, messageId} or {reason}. Stream failures reconnect with backoff.
|
|
143
|
+
*/
|
|
144
|
+
async function waitForReply(cfg, req, { id, deadline, baseTs, signal, stream, startS }) {
|
|
145
|
+
const ctrl = new AbortController();
|
|
146
|
+
let reason = "timeout";
|
|
147
|
+
const stop = (why) => { if (!ctrl.signal.aborted) { reason = why; ctrl.abort(); } };
|
|
148
|
+
const timer = setTimeout(() => stop("timeout"), Math.max(0, deadline - Date.now()));
|
|
149
|
+
const onAbort = () => stop("cancelled");
|
|
150
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
151
|
+
if (signal?.aborted) stop("cancelled");
|
|
152
|
+
let since = String(startS);
|
|
153
|
+
let backoff = cfg.stopPollMs;
|
|
154
|
+
try {
|
|
155
|
+
while (!ctrl.signal.aborted) {
|
|
156
|
+
try {
|
|
157
|
+
for await (const ev of stream(cfg, [broadcastTopic(cfg.project)], { since, signal: ctrl.signal, onOpen: () => { backoff = cfg.stopPollMs; } })) {
|
|
158
|
+
since = ev.id;
|
|
159
|
+
const mode = parseMode(ev.message);
|
|
160
|
+
if (mode?.mode === "off" && mode.ts > baseTs) return { reason: "afk-off" };
|
|
161
|
+
const reply = parsePhoneReply(ev.message);
|
|
162
|
+
const decision = reply?.id === id ? replyDecision(req, reply.answer) : null;
|
|
163
|
+
if (decision) return { decision, messageId: ev.id };
|
|
164
|
+
}
|
|
165
|
+
} catch { /* outage, idle timeout, or abort */ }
|
|
166
|
+
if (ctrl.signal.aborted) break;
|
|
167
|
+
await delay(backoff, undefined, { signal: ctrl.signal }).catch(() => {});
|
|
168
|
+
backoff = Math.min(backoff * 2, RETRY_MAX_MS);
|
|
169
|
+
}
|
|
170
|
+
return { reason };
|
|
171
|
+
} finally {
|
|
172
|
+
clearTimeout(timer);
|
|
173
|
+
signal?.removeEventListener("abort", onAbort);
|
|
174
|
+
ctrl.abort();
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Asks the operator's phone about one permission request and returns the hook output.
|
|
180
|
+
* Returns the no-decision output immediately when AFK mode is off, approvals are disabled, or the request is unknown.
|
|
181
|
+
*/
|
|
182
|
+
export async function decideApproval(cfg, {
|
|
183
|
+
host, key, input = {}, signal, now = Date.now, stream = streamEvents, send = publish,
|
|
184
|
+
mode = host === "cursor" ? storedMode : currentMode,
|
|
185
|
+
} = {}) {
|
|
186
|
+
const none = approvalOutput(host, null);
|
|
187
|
+
const req = approvalRequest(host, key, input);
|
|
188
|
+
if (!cfg.enabled || !req || cfg.approvalS <= 0) return none;
|
|
189
|
+
// Cursor fires this before every shell command, so it reads the mode recorded locally instead of polling ntfy.
|
|
190
|
+
const base = await Promise.resolve(mode(cfg)).catch(() => ({ mode: "off", ts: 0 }));
|
|
191
|
+
if (base.mode === "off") return none;
|
|
192
|
+
const id = randomBytes(6).toString("hex");
|
|
193
|
+
const t0 = now();
|
|
194
|
+
const deadline = t0 + cfg.approvalS * 1000;
|
|
195
|
+
const message = approvalMessage(cfg, host, req, { id, expiresAt: deadline });
|
|
196
|
+
if (!message) return none;
|
|
197
|
+
const sender = cfg.session ? `${cfg.peer}#${cfg.session}` : cfg.peer;
|
|
198
|
+
const title = (req.questions ? `Question from ${sender}: ${req.summary}` : `Approve ${req.tool} for ${sender}: ${req.summary}`).slice(0, 200);
|
|
199
|
+
try {
|
|
200
|
+
await send(cfg, broadcastTopic(cfg.project), message, { title, priority: 4 });
|
|
201
|
+
} catch {
|
|
202
|
+
return none;
|
|
203
|
+
}
|
|
204
|
+
const result = await waitForReply(cfg, req, { id, deadline, baseTs: base.ts, signal, stream, startS: Math.floor(t0 / 1000) });
|
|
205
|
+
if (result.messageId) sendReceipts(cfg, [result.messageId]);
|
|
206
|
+
const reason = result.decision ? (req.questions ? "answered" : result.decision.behavior === "allow" ? "allowed" : "denied") : result.reason;
|
|
207
|
+
const end = JSON.stringify({ v: 1, kind: "approval-end", from: cfg.peer, ...(cfg.session ? { session: cfg.session } : {}), id, reason, ts: new Date().toISOString() });
|
|
208
|
+
await send(cfg, broadcastTopic(cfg.project), end, { title: `ai-collab approval ${reason}`, priority: 1, signal: AbortSignal.timeout(END_TIMEOUT_MS) }).catch(() => {});
|
|
209
|
+
return result.decision ? approvalOutput(host, result.decision, req) : none;
|
|
210
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** Image attachments for operator messages: absolute path, image extension, matching magic bytes, ≤ 15 MB. */
|
|
2
|
+
import { closeSync, fstatSync, openSync, readSync } from "node:fs";
|
|
3
|
+
import { basename, extname, isAbsolute } from "node:path";
|
|
4
|
+
|
|
5
|
+
export const ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
|
|
6
|
+
export const TEXT_ATTACHMENT_MAX_BYTES = 1024 * 1024;
|
|
7
|
+
const SIGNATURES = {
|
|
8
|
+
".png": [[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]],
|
|
9
|
+
".jpg": [[0xff, 0xd8, 0xff]],
|
|
10
|
+
".jpeg": [[0xff, 0xd8, 0xff]],
|
|
11
|
+
".gif": [[0x47, 0x49, 0x46, 0x38]],
|
|
12
|
+
".webp": [[0x52, 0x49, 0x46, 0x46]],
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** Reads an image for upload; throws with a reason the agent can act on. */
|
|
16
|
+
export function readAttachment(path) {
|
|
17
|
+
if (typeof path !== "string" || !isAbsolute(path)) throw new Error("attachment must be an absolute file path");
|
|
18
|
+
const ext = extname(path).toLowerCase();
|
|
19
|
+
if (!SIGNATURES[ext]) throw new Error("attachment must be a .png, .jpg, .jpeg, .gif or .webp image");
|
|
20
|
+
let fd;
|
|
21
|
+
try { fd = openSync(path, "r"); } catch { throw new Error("attachment file is unreadable"); }
|
|
22
|
+
try {
|
|
23
|
+
const stat = fstatSync(fd);
|
|
24
|
+
if (!stat.isFile()) throw new Error("attachment must be a regular file");
|
|
25
|
+
if (stat.size > ATTACHMENT_MAX_BYTES) throw new Error("attachment is over 15 MB");
|
|
26
|
+
const data = Buffer.alloc(stat.size);
|
|
27
|
+
readSync(fd, data, 0, stat.size, 0);
|
|
28
|
+
if (!SIGNATURES[ext].some(sig => sig.every((byte, i) => data[i] === byte))) throw new Error(`attachment content is not a ${ext.slice(1)} image`);
|
|
29
|
+
return { filename: basename(path), data };
|
|
30
|
+
} finally {
|
|
31
|
+
closeSync(fd);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Hook-generated text (a large tool result) as a .txt upload; reads no file, so the image-only rule above still holds. */
|
|
36
|
+
export function textAttachment(text, filename = "output.txt") {
|
|
37
|
+
const data = Buffer.from(String(text), "utf8");
|
|
38
|
+
if (data.length <= TEXT_ATTACHMENT_MAX_BYTES) return { filename, data };
|
|
39
|
+
const marker = `\n…[truncated ${data.length - TEXT_ATTACHMENT_MAX_BYTES} bytes]`;
|
|
40
|
+
return { filename, data: Buffer.from(data.subarray(0, TEXT_ATTACHMENT_MAX_BYTES).toString("utf8") + marker) };
|
|
41
|
+
}
|
package/lib/cli.mjs
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shell/CLI front end. runCli returns an exit code and never calls process.exit,
|
|
3
|
+
* so tests can drive it with fake stdio.
|
|
4
|
+
*/
|
|
5
|
+
import { loadConfig } from "./config.mjs";
|
|
6
|
+
import { claimInbox, readStatuses, sendMessage } from "./inbox.mjs";
|
|
7
|
+
import { formatInbox } from "./format.mjs";
|
|
8
|
+
import { sendReceipts, settleReceipts } from "./receipts.mjs";
|
|
9
|
+
import { MODES, currentMode, operatorConfigs, publishMode } from "./mode.mjs";
|
|
10
|
+
import { agentDirectory, sessionDirectory, setIdentity } from "./sessions.mjs";
|
|
11
|
+
import { respond, sendAndAwait, waitForMessages } from "./agents.mjs";
|
|
12
|
+
import { setup } from "./setup.mjs";
|
|
13
|
+
|
|
14
|
+
export const USAGE = `usage: ai-collab <command>
|
|
15
|
+
setup [--agent claude,codex,cursor,opencode] [--port N] [--no-ui]
|
|
16
|
+
start ntfy in Docker, install the plugin for each agent (default: every one on PATH) and the UI service
|
|
17
|
+
peers list AI_COLLAB_PEERS with the last status each reported
|
|
18
|
+
send <peer|peer#session|all> [message] [--file /abs/image.png] [--urgent] [--await SECONDS]
|
|
19
|
+
send one message (or pipe the body on stdin), optionally with an image;
|
|
20
|
+
--urgent delivers at the recipient's next hook, --await waits for its answer
|
|
21
|
+
inbox [--peek] show new messages and mark them read (--peek leaves them unread)
|
|
22
|
+
wait [SECONDS] block up to SECONDS (default 25, max 45) for a new message, then show it
|
|
23
|
+
respond <id> <working|reply|done|declined> [message]
|
|
24
|
+
answer a message by id
|
|
25
|
+
identity [--name N] [--activity TEXT] [--tag T]...
|
|
26
|
+
set this session's name, activity line and tags for agents (no flags: show them)
|
|
27
|
+
agents [--all] live sessions with their identity (--all includes offline ones)
|
|
28
|
+
sessions sessions on this machine: address, harness, online, last active, parent, cwd, resume command
|
|
29
|
+
afk [on|off|quiet] set the operator AFK mode in every project in projects.json (no argument: show it)
|
|
30
|
+
help
|
|
31
|
+
|
|
32
|
+
Required: AI_COLLAB_PROJECT, AI_COLLAB_PEER. Optional: AI_COLLAB_URL (default http://127.0.0.1:8794),
|
|
33
|
+
AI_COLLAB_TOKEN, AI_COLLAB_PEERS. See README.md.`;
|
|
34
|
+
|
|
35
|
+
// Reads a piped body. Gives up after 2s so an open-but-silent stdin cannot hang the CLI.
|
|
36
|
+
function readStdinDefault(limitMs = 2000) {
|
|
37
|
+
if (process.stdin.isTTY) return Promise.resolve("");
|
|
38
|
+
return new Promise((resolve) => {
|
|
39
|
+
const chunks = [];
|
|
40
|
+
const timer = setTimeout(() => resolve(Buffer.concat(chunks).toString("utf8")), limitMs);
|
|
41
|
+
process.stdin.on("data", (c) => chunks.push(c));
|
|
42
|
+
process.stdin.on("end", () => {
|
|
43
|
+
clearTimeout(timer);
|
|
44
|
+
resolve(Buffer.concat(chunks).toString("utf8"));
|
|
45
|
+
});
|
|
46
|
+
process.stdin.on("error", () => {
|
|
47
|
+
clearTimeout(timer);
|
|
48
|
+
resolve("");
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function afk([mode, ...extra], { env, out, err, now }) {
|
|
54
|
+
const cfgs = operatorConfigs(env);
|
|
55
|
+
if (!cfgs.length) {
|
|
56
|
+
err.write("ai-collab: afk: no enabled project in projects.json or the environment\n");
|
|
57
|
+
return 2;
|
|
58
|
+
}
|
|
59
|
+
if (mode === undefined) {
|
|
60
|
+
for (const cfg of cfgs) out.write(`${cfg.project}\t${(await currentMode(cfg)).mode}\n`);
|
|
61
|
+
return 0;
|
|
62
|
+
}
|
|
63
|
+
if (!MODES.includes(mode) || extra.length) {
|
|
64
|
+
err.write(`ai-collab: usage: afk ${MODES.join("|")}\n`);
|
|
65
|
+
return 1;
|
|
66
|
+
}
|
|
67
|
+
const results = await publishMode(cfgs, mode, now ? { now: now() } : {});
|
|
68
|
+
for (const r of results) out.write(r.ok ? `afk ${mode}: ${r.project}\n` : "");
|
|
69
|
+
for (const r of results) if (!r.ok) err.write(`ai-collab: afk ${mode}: ${r.project}: ${r.error}\n`);
|
|
70
|
+
return results.every((r) => r.ok) ? 0 : 1;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Live and recent sessions of this project on this machine; needs only the project, not a peer name.
|
|
74
|
+
function sessions(env, { out, err }) {
|
|
75
|
+
const cfg = loadConfig({ ...env, AI_COLLAB_PEER: env.AI_COLLAB_PEER || "operator" });
|
|
76
|
+
if (!cfg.enabled) {
|
|
77
|
+
err.write(`ai-collab: disabled: ${cfg.reason}\n`);
|
|
78
|
+
return 2;
|
|
79
|
+
}
|
|
80
|
+
const list = sessionDirectory(cfg);
|
|
81
|
+
if (!list.length) out.write("no sessions recorded on this machine\n");
|
|
82
|
+
for (const s of list) {
|
|
83
|
+
out.write(`${s.address}\t${s.harness}\t${s.online ? "online" : "offline"}\tactive ${s.lastActive || "?"}\t${s.parent ? `parent ${s.parent}` : "-"}\t${s.cwd}${s.resume ? `\t${s.resume}` : ""}\n`);
|
|
84
|
+
}
|
|
85
|
+
return 0;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Splits argv into flags (spec: name → arity 0, 1, or "many") and words; flags.bad marks a missing value. */
|
|
89
|
+
function parseFlags(argv, spec) {
|
|
90
|
+
const flags = {};
|
|
91
|
+
const words = [];
|
|
92
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
93
|
+
const arity = spec[argv[i]];
|
|
94
|
+
if (arity === undefined) { words.push(argv[i]); continue; }
|
|
95
|
+
if (arity === 0) { flags[argv[i]] = true; continue; }
|
|
96
|
+
const value = argv[i + 1];
|
|
97
|
+
if (value === undefined) { flags.bad = true; break; }
|
|
98
|
+
if (arity === "many") (flags[argv[i]] ||= []).push(value);
|
|
99
|
+
else flags[argv[i]] = value;
|
|
100
|
+
i += 1;
|
|
101
|
+
}
|
|
102
|
+
return { flags, words };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Live sessions with their set_identity fields; needs only the project, like sessions.
|
|
106
|
+
function agents(env, rest, { out, err }) {
|
|
107
|
+
const cfg = loadConfig({ ...env, AI_COLLAB_PEER: env.AI_COLLAB_PEER || "operator" });
|
|
108
|
+
if (!cfg.enabled) {
|
|
109
|
+
err.write(`ai-collab: disabled: ${cfg.reason}\n`);
|
|
110
|
+
return 2;
|
|
111
|
+
}
|
|
112
|
+
const list = agentDirectory(cfg, { all: rest.includes("--all") });
|
|
113
|
+
if (!list.length) out.write("no live sessions recorded on this machine\n");
|
|
114
|
+
for (const a of list) {
|
|
115
|
+
out.write(`${a.address}\t${a.harness}\t${a.online ? "online" : "offline"}\tactive ${a.lastActive || "?"}\t${a.name || "-"}\t${a.activity || "-"}\t${(a.tags || []).join(",") || "-"}${a.parent ? `\tparent ${a.parent}` : ""}\n`);
|
|
116
|
+
}
|
|
117
|
+
return 0;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export async function runCli(argv, io = {}) {
|
|
121
|
+
const env = io.env || process.env;
|
|
122
|
+
const out = io.stdout || process.stdout;
|
|
123
|
+
const err = io.stderr || process.stderr;
|
|
124
|
+
const [cmd = "help", ...rest] = argv;
|
|
125
|
+
|
|
126
|
+
if (cmd === "help" || cmd === "--help" || cmd === "-h") {
|
|
127
|
+
out.write(`${USAGE}\n`);
|
|
128
|
+
return 0;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (cmd === "setup") return setup(rest, { env, out });
|
|
132
|
+
if (cmd === "afk") return afk(rest, { env, out, err, now: io.now });
|
|
133
|
+
if (cmd === "sessions") return sessions(env, { out, err });
|
|
134
|
+
if (cmd === "agents") return agents(env, rest, { out, err });
|
|
135
|
+
|
|
136
|
+
const cfg = loadConfig(env);
|
|
137
|
+
if (!cfg.enabled) {
|
|
138
|
+
err.write(`ai-collab: disabled: ${cfg.reason}\n`);
|
|
139
|
+
return 2;
|
|
140
|
+
}
|
|
141
|
+
if (cfg.peers.length && !cfg.peers.includes(cfg.peer)) {
|
|
142
|
+
err.write(`ai-collab: warning: ${cfg.peer} is not listed in AI_COLLAB_PEERS\n`);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
try {
|
|
146
|
+
if (cmd === "peers") {
|
|
147
|
+
const statuses = await readStatuses(cfg);
|
|
148
|
+
const names = [...new Set([...cfg.peers, ...statuses.keys()])];
|
|
149
|
+
if (!names.length) out.write("no peers listed (set AI_COLLAB_PEERS)\n");
|
|
150
|
+
for (const name of names) {
|
|
151
|
+
const s = statuses.get(name);
|
|
152
|
+
const label = name === cfg.peer ? `${name} (you)` : name;
|
|
153
|
+
out.write(`${label}\t${s ? `${s.event} ${s.harness} ${s.ts}` : "no status seen"}\n`);
|
|
154
|
+
}
|
|
155
|
+
return 0;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (cmd === "send") {
|
|
159
|
+
const { flags, words: [target, ...words] } = parseFlags(rest, { "--file": 1, "--await": 1, "--urgent": 0 });
|
|
160
|
+
const attachment = flags["--file"];
|
|
161
|
+
const awaitSeconds = flags["--await"] === undefined ? 0 : Number(flags["--await"]);
|
|
162
|
+
if (!target || flags.bad) {
|
|
163
|
+
err.write("ai-collab: usage: send <peer|all> [message] [--file /abs/image.png] [--urgent] [--await SECONDS]\n");
|
|
164
|
+
return 1;
|
|
165
|
+
}
|
|
166
|
+
let body = words.join(" ");
|
|
167
|
+
if (!body) body = ((await (io.readStdin || readStdinDefault)()) || "").trim();
|
|
168
|
+
const urgent = flags["--urgent"] === true;
|
|
169
|
+
if (!awaitSeconds) {
|
|
170
|
+
await sendMessage(cfg, target, body, { attachment, urgent });
|
|
171
|
+
out.write(`sent to ${target}\n`);
|
|
172
|
+
return 0;
|
|
173
|
+
}
|
|
174
|
+
const sent = await sendAndAwait(cfg, target, body, { awaitSeconds, attachment, urgent });
|
|
175
|
+
out.write(`sent to ${sent.to}${sent.id ? ` (id ${sent.id})` : ""}\n`);
|
|
176
|
+
if (sent.reply) out.write(`${formatInbox([sent.reply, ...sent.messages])}\n`);
|
|
177
|
+
else out.write("no reply yet\n");
|
|
178
|
+
return 0;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (cmd === "wait") {
|
|
182
|
+
const seconds = rest[0] === undefined ? 25 : Number(rest[0]);
|
|
183
|
+
const got = await waitForMessages(cfg, { seconds });
|
|
184
|
+
out.write(got.messages.length ? `${formatInbox(got.messages)}\n` : "no new messages\n");
|
|
185
|
+
return 0;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (cmd === "respond") {
|
|
189
|
+
const [id, state, ...words] = rest;
|
|
190
|
+
if (!id || !state) {
|
|
191
|
+
err.write("ai-collab: usage: respond <id> <working|reply|done|declined> [message]\n");
|
|
192
|
+
return 1;
|
|
193
|
+
}
|
|
194
|
+
let body = words.join(" ");
|
|
195
|
+
if (!body) body = ((await (io.readStdin || readStdinDefault)()) || "").trim();
|
|
196
|
+
const r = await respond(cfg, id, state, body);
|
|
197
|
+
out.write(`${r.state} sent to ${r.to}\n`);
|
|
198
|
+
return 0;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (cmd === "identity") {
|
|
202
|
+
const { flags, words } = parseFlags(rest, { "--name": 1, "--activity": 1, "--tag": "many" });
|
|
203
|
+
if (flags.bad || words.length) {
|
|
204
|
+
err.write("ai-collab: usage: identity [--name N] [--activity TEXT] [--tag T]...\n");
|
|
205
|
+
return 1;
|
|
206
|
+
}
|
|
207
|
+
const own = agentDirectory(cfg, { all: true }).find((a) => a.address === `${cfg.peer}#${cfg.session}`);
|
|
208
|
+
const identity = Object.keys(flags).length
|
|
209
|
+
? await setIdentity(cfg, { name: flags["--name"], activity: flags["--activity"], tags: flags["--tag"] })
|
|
210
|
+
: own || {};
|
|
211
|
+
out.write(`${JSON.stringify(identity)}\n`);
|
|
212
|
+
return 0;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (cmd === "inbox") {
|
|
216
|
+
const peek = rest.includes("--peek");
|
|
217
|
+
const messages = await claimInbox(cfg, { commit: !peek, strict: true });
|
|
218
|
+
sendReceipts(cfg, messages.map((m) => m.id));
|
|
219
|
+
await settleReceipts();
|
|
220
|
+
out.write(messages.length ? `${formatInbox(messages)}\n` : "no new messages\n");
|
|
221
|
+
return 0;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
err.write(`ai-collab: unknown command "${cmd}"\n${USAGE}\n`);
|
|
225
|
+
return 1;
|
|
226
|
+
} catch (e) {
|
|
227
|
+
err.write(`ai-collab: ${e.message}\n`);
|
|
228
|
+
return 1;
|
|
229
|
+
}
|
|
230
|
+
}
|