@christang/keel 5.84.0 → 5.85.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/README.md +22 -0
- package/README.zh-CN.md +21 -0
- package/assets/bootstrap/AGENTS.md +1 -1
- package/bin/keel.js +5 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/plugins/keel/.claude-plugin/plugin.json +1 -1
- package/plugins/keel/.codex-plugin/plugin.json +2 -1
- package/plugins/keel/hooks/codex.json +44 -0
- package/plugins/keel/scripts/codex-mail-hook.js +75 -0
- package/plugins/keel/scripts/mail-hook.js +11 -9
- package/scripts/fake_slack.py +277 -0
- package/scripts/validate_codex_receiving.py +296 -0
- package/scripts/validate_plugin.py +1476 -178
- package/src/core/chat/archive.js +234 -0
- package/src/core/chat/bridge.js +808 -0
- package/src/core/chat/cli.js +453 -0
- package/src/core/chat/config.js +64 -0
- package/src/core/chat/guards.js +96 -0
- package/src/core/chat/lifecycle.js +214 -0
- package/src/core/chat/migrate.js +142 -0
- package/src/core/chat/notice.js +179 -0
- package/src/core/chat/redact.js +37 -0
- package/src/core/chat/slack.js +104 -0
- package/src/core/chat/store.js +776 -0
- package/src/core/chat/view.js +165 -0
- package/src/core/mail.js +123 -433
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// How the Slack bridge lives on a machine (issue #187, design D17, D18):
|
|
4
|
+
// where its tokens come from, the user LaunchAgent that keeps it running, and
|
|
5
|
+
// the controls that pause, stop, start, or remove it.
|
|
6
|
+
//
|
|
7
|
+
// The owner runs `install`, `start`, `stop`, and `uninstall`: they change the
|
|
8
|
+
// machine's login items, which is system configuration, not project state.
|
|
9
|
+
// Tests replace the system boundary with doubles through KEEL_CHAT_LAUNCHCTL,
|
|
10
|
+
// KEEL_CHAT_SECURITY, and KEEL_CHAT_LAUNCH_AGENTS_DIR.
|
|
11
|
+
|
|
12
|
+
const fs = require("fs");
|
|
13
|
+
const os = require("os");
|
|
14
|
+
const path = require("path");
|
|
15
|
+
const { spawnSync } = require("child_process");
|
|
16
|
+
const { ChatError } = require("./store");
|
|
17
|
+
|
|
18
|
+
const LABEL = "dev.keel.chat-bridge";
|
|
19
|
+
const KEYCHAIN_SERVICE = "keel-chat-slack";
|
|
20
|
+
|
|
21
|
+
function keelHome() {
|
|
22
|
+
return process.env.KEEL_HOME || path.join(os.homedir(), ".keel");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function bridgeDir() {
|
|
26
|
+
return path.join(keelHome(), "chat", "bridge");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// --- tokens -----------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
function keychainToken(account) {
|
|
32
|
+
const security = process.env.KEEL_CHAT_SECURITY || (process.platform === "darwin" ? "security" : null);
|
|
33
|
+
if (!security) return null;
|
|
34
|
+
const result = spawnSync(security, ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", account, "-w"], {
|
|
35
|
+
encoding: "utf8",
|
|
36
|
+
timeout: 10000,
|
|
37
|
+
});
|
|
38
|
+
if (result.status !== 0) return null;
|
|
39
|
+
const token = String(result.stdout || "").trim();
|
|
40
|
+
return token || null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// The environment first, then the macOS Keychain. Tokens are held in memory
|
|
44
|
+
// only: never written to a file, a record, the status, or a log.
|
|
45
|
+
function tokens() {
|
|
46
|
+
const app = (process.env.KEEL_SLACK_APP_TOKEN || "").trim() || keychainToken("app");
|
|
47
|
+
const bot = (process.env.KEEL_SLACK_BOT_TOKEN || "").trim() || keychainToken("bot");
|
|
48
|
+
return { app: app || null, bot: bot || null };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function missingTokens(which) {
|
|
52
|
+
return new ChatError(
|
|
53
|
+
`No Slack ${which}: set KEEL_SLACK_APP_TOKEN and KEEL_SLACK_BOT_TOKEN, or store them in the macOS Keychain `
|
|
54
|
+
+ `as generic passwords of service ${KEYCHAIN_SERVICE}, accounts app and bot `
|
|
55
|
+
+ `(\`security add-generic-password -s ${KEYCHAIN_SERVICE} -a app -w\`).`
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// --- pause ------------------------------------------------------------------------
|
|
60
|
+
|
|
61
|
+
function controlFile() {
|
|
62
|
+
return path.join(bridgeDir(), "control.json");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function readControl() {
|
|
66
|
+
try {
|
|
67
|
+
return JSON.parse(fs.readFileSync(controlFile(), "utf8")) || {};
|
|
68
|
+
} catch {
|
|
69
|
+
return {};
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function pausedUntil(now = Date.now()) {
|
|
74
|
+
const until = Date.parse(readControl().paused_until || "");
|
|
75
|
+
return !Number.isNaN(until) && until > now ? until : null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function parseDuration(value) {
|
|
79
|
+
const match = String(value || "").trim().match(/^(\d+)([smhd])$/);
|
|
80
|
+
if (!match) return null;
|
|
81
|
+
return Number(match[1]) * { s: 1e3, m: 60e3, h: 3600e3, d: 86400e3 }[match[2]];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function pause(duration) {
|
|
85
|
+
const ms = parseDuration(duration);
|
|
86
|
+
if (!ms) throw new ChatError(`keel chat bridge pause needs a duration such as 30m, 2h, or 1d, not ${JSON.stringify(duration)}.`);
|
|
87
|
+
const until = new Date(Date.now() + ms);
|
|
88
|
+
fs.mkdirSync(bridgeDir(), { recursive: true });
|
|
89
|
+
fs.writeFileSync(controlFile(), `${JSON.stringify({ paused_until: until.toISOString() }, null, 2)}\n`);
|
|
90
|
+
return until;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function resume() {
|
|
94
|
+
try {
|
|
95
|
+
fs.rmSync(controlFile());
|
|
96
|
+
} catch {
|
|
97
|
+
// Not paused.
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// --- the LaunchAgent ----------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
function agentsDir() {
|
|
104
|
+
return process.env.KEEL_CHAT_LAUNCH_AGENTS_DIR || path.join(os.homedir(), "Library", "LaunchAgents");
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function plistPath() {
|
|
108
|
+
return path.join(agentsDir(), `${LABEL}.plist`);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function installed() {
|
|
112
|
+
return fs.existsSync(plistPath());
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function xml(text) {
|
|
116
|
+
return String(text).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function plistText() {
|
|
120
|
+
const cli = path.resolve(__dirname, "..", "..", "..", "bin", "keel.js");
|
|
121
|
+
const args = [process.execPath, cli, "chat", "bridge", "run"];
|
|
122
|
+
const environment = { PATH: process.env.PATH || "/usr/bin:/bin:/usr/sbin:/sbin" };
|
|
123
|
+
if (process.env.KEEL_HOME) environment.KEEL_HOME = process.env.KEEL_HOME;
|
|
124
|
+
if (process.env.KEEL_CHAT_MACHINE) environment.KEEL_CHAT_MACHINE = process.env.KEEL_CHAT_MACHINE;
|
|
125
|
+
const log = path.join(bridgeDir(), "bridge.log");
|
|
126
|
+
return [
|
|
127
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
128
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
129
|
+
'<plist version="1.0">',
|
|
130
|
+
"<dict>",
|
|
131
|
+
` <key>Label</key><string>${LABEL}</string>`,
|
|
132
|
+
" <key>ProgramArguments</key>",
|
|
133
|
+
" <array>",
|
|
134
|
+
...args.map((arg) => ` <string>${xml(arg)}</string>`),
|
|
135
|
+
" </array>",
|
|
136
|
+
" <key>EnvironmentVariables</key>",
|
|
137
|
+
" <dict>",
|
|
138
|
+
...Object.entries(environment).map(([key, value]) => ` <key>${xml(key)}</key><string>${xml(value)}</string>`),
|
|
139
|
+
" </dict>",
|
|
140
|
+
" <key>RunAtLoad</key><true/>",
|
|
141
|
+
" <key>KeepAlive</key><true/>",
|
|
142
|
+
" <key>ProcessType</key><string>Background</string>",
|
|
143
|
+
` <key>StandardOutPath</key><string>${xml(log)}</string>`,
|
|
144
|
+
` <key>StandardErrorPath</key><string>${xml(log)}</string>`,
|
|
145
|
+
"</dict>",
|
|
146
|
+
"</plist>",
|
|
147
|
+
"",
|
|
148
|
+
].join("\n");
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function launchctl(args) {
|
|
152
|
+
const command = process.env.KEEL_CHAT_LAUNCHCTL || "launchctl";
|
|
153
|
+
const result = spawnSync(command, args, { encoding: "utf8", timeout: 20000 });
|
|
154
|
+
return { ok: result.status === 0, output: `${result.stdout || ""}${result.stderr || ""}`.trim() };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function domain() {
|
|
158
|
+
return `gui/${typeof process.getuid === "function" ? process.getuid() : 0}`;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function install() {
|
|
162
|
+
if (process.platform !== "darwin" && !process.env.KEEL_CHAT_LAUNCHCTL) {
|
|
163
|
+
throw new ChatError("keel chat bridge install sets up a macOS LaunchAgent; on this system run `keel chat bridge run` under your own service manager.");
|
|
164
|
+
}
|
|
165
|
+
fs.mkdirSync(agentsDir(), { recursive: true });
|
|
166
|
+
fs.mkdirSync(bridgeDir(), { recursive: true });
|
|
167
|
+
fs.writeFileSync(plistPath(), plistText());
|
|
168
|
+
launchctl(["bootout", `${domain()}/${LABEL}`]);
|
|
169
|
+
const loaded = launchctl(["bootstrap", domain(), plistPath()]);
|
|
170
|
+
if (!loaded.ok) throw new ChatError(`launchctl could not load ${plistPath()}: ${loaded.output}`);
|
|
171
|
+
return plistPath();
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function uninstall() {
|
|
175
|
+
launchctl(["bootout", `${domain()}/${LABEL}`]);
|
|
176
|
+
try {
|
|
177
|
+
fs.rmSync(plistPath());
|
|
178
|
+
} catch {
|
|
179
|
+
// Already gone.
|
|
180
|
+
}
|
|
181
|
+
return plistPath();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function start() {
|
|
185
|
+
if (!installed()) throw new ChatError("The bridge is not installed: run `keel chat bridge install` first.");
|
|
186
|
+
resume();
|
|
187
|
+
const loaded = launchctl(["bootstrap", domain(), plistPath()]);
|
|
188
|
+
if (!loaded.ok && !/already|in progress|5:/i.test(loaded.output)) {
|
|
189
|
+
throw new ChatError(`launchctl could not start the bridge: ${loaded.output}`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Unloads the agent: it stays stopped until `start`, or until the next login
|
|
194
|
+
// loads it again.
|
|
195
|
+
function stop() {
|
|
196
|
+
launchctl(["bootout", `${domain()}/${LABEL}`]);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
module.exports = {
|
|
200
|
+
KEYCHAIN_SERVICE,
|
|
201
|
+
LABEL,
|
|
202
|
+
bridgeDir,
|
|
203
|
+
install,
|
|
204
|
+
installed,
|
|
205
|
+
missingTokens,
|
|
206
|
+
pause,
|
|
207
|
+
pausedUntil,
|
|
208
|
+
plistPath,
|
|
209
|
+
resume,
|
|
210
|
+
start,
|
|
211
|
+
stop,
|
|
212
|
+
tokens,
|
|
213
|
+
uninstall,
|
|
214
|
+
};
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// One-time migration of the 5.83 mailbox (issue #180) into chat direct groups
|
|
4
|
+
// (issue #187, design D7). Runs at the first `keel chat` or `keel mail`
|
|
5
|
+
// command in a repository whose `<git common dir>/keel-mailbox/` exists.
|
|
6
|
+
//
|
|
7
|
+
// Each 5.83 message becomes a `message` record in `dm-<from>--<to>`, keeping
|
|
8
|
+
// its original time; mail under `new/` stays unread for the recipient, mail
|
|
9
|
+
// under `done/` is read; `roles.json` bindings carry over. The old directory
|
|
10
|
+
// is renamed, never deleted, so nothing a user had is lost.
|
|
11
|
+
//
|
|
12
|
+
// Two processes may start at once. The first rename — `keel-mailbox` to a
|
|
13
|
+
// per-process staging name — is atomic, so exactly one of them migrates and
|
|
14
|
+
// the other finds nothing to do.
|
|
15
|
+
|
|
16
|
+
const fs = require("fs");
|
|
17
|
+
const path = require("path");
|
|
18
|
+
const store = require("./store");
|
|
19
|
+
|
|
20
|
+
function parseOld(text) {
|
|
21
|
+
const match = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
|
|
22
|
+
if (!match) return null;
|
|
23
|
+
const message = { refs: [] };
|
|
24
|
+
let inRefs = false;
|
|
25
|
+
for (const line of match[1].split("\n")) {
|
|
26
|
+
const item = line.match(/^\s+-\s+(.*)$/);
|
|
27
|
+
if (inRefs && item) {
|
|
28
|
+
message.refs.push(unquote(item[1]));
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
inRefs = false;
|
|
32
|
+
const field = line.match(/^([a-z_]+):\s?(.*)$/);
|
|
33
|
+
if (!field) continue;
|
|
34
|
+
if (field[1] === "refs") {
|
|
35
|
+
inRefs = true;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
message[field[1]] = unquote(field[2]);
|
|
39
|
+
}
|
|
40
|
+
message.body = match[2].replace(/^\n/, "").replace(/\s+$/, "");
|
|
41
|
+
return message;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function unquote(raw) {
|
|
45
|
+
const text = raw.trim();
|
|
46
|
+
if (!text.startsWith('"')) return text;
|
|
47
|
+
try {
|
|
48
|
+
return JSON.parse(text);
|
|
49
|
+
} catch {
|
|
50
|
+
return text;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function readOld(staging) {
|
|
55
|
+
const messages = [];
|
|
56
|
+
let roles = [];
|
|
57
|
+
try {
|
|
58
|
+
roles = fs.readdirSync(staging).filter((name) => /^[a-z0-9][a-z0-9-]{0,31}$/.test(name));
|
|
59
|
+
} catch {
|
|
60
|
+
return messages;
|
|
61
|
+
}
|
|
62
|
+
for (const role of roles) {
|
|
63
|
+
for (const state of ["new", "done"]) {
|
|
64
|
+
const dir = path.join(staging, role, state);
|
|
65
|
+
let names = [];
|
|
66
|
+
try {
|
|
67
|
+
names = fs.readdirSync(dir).filter((name) => name.endsWith(".md"));
|
|
68
|
+
} catch {
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
for (const name of names) {
|
|
72
|
+
let parsed = null;
|
|
73
|
+
try {
|
|
74
|
+
parsed = parseOld(fs.readFileSync(path.join(dir, name), "utf8"));
|
|
75
|
+
} catch {
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
const date = parsed ? new Date(Date.parse(parsed.created)) : null;
|
|
79
|
+
if (!parsed || !parsed.from || !date || Number.isNaN(date.getTime())) continue;
|
|
80
|
+
messages.push({ ...parsed, to: parsed.to || role, read: state === "done", date });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return messages.sort((a, b) => a.date - b.date);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function migrateIfNeeded(where) {
|
|
88
|
+
const old = path.join(where.common, "keel-mailbox");
|
|
89
|
+
if (!fs.existsSync(old)) return null;
|
|
90
|
+
const staging = path.join(where.common, `keel-mailbox.migrating-${process.pid}`);
|
|
91
|
+
try {
|
|
92
|
+
fs.renameSync(old, staging);
|
|
93
|
+
} catch {
|
|
94
|
+
return null; // Another process is migrating it.
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const roles = store.readJsonFile(path.join(staging, "roles.json"));
|
|
98
|
+
const current = store.readJsonFile(path.join(where.root, "roles.json"));
|
|
99
|
+
const merged = { ...roles, ...current };
|
|
100
|
+
if (Object.keys(merged).length) store.writeRoles(where, merged);
|
|
101
|
+
|
|
102
|
+
const messages = readOld(staging);
|
|
103
|
+
const ids = new Map();
|
|
104
|
+
const lastRead = new Map(); // `${group}\t${role}` -> id of the last read message before any unread
|
|
105
|
+
const blocked = new Set();
|
|
106
|
+
for (const message of messages) {
|
|
107
|
+
if (message.from === message.to) continue;
|
|
108
|
+
const group = store.directName(message.from, message.to);
|
|
109
|
+
if (!store.groupState(store.readLog(where, group)).exists) {
|
|
110
|
+
const before = new Date(message.date.getTime() - 1);
|
|
111
|
+
for (const member of [message.from, message.to]) {
|
|
112
|
+
store.writeRecord(where, { group, kind: "join", from: message.from, target: member }, before);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const text = message.subject ? `${message.subject}\n\n${message.body}` : message.body;
|
|
116
|
+
const record = store.writeRecord(where, {
|
|
117
|
+
group,
|
|
118
|
+
kind: "message",
|
|
119
|
+
from: message.from,
|
|
120
|
+
reply_to: ids.get(message.reply_to) || null,
|
|
121
|
+
refs: [...message.refs, `mail:${message.id}`],
|
|
122
|
+
origin: "migrated",
|
|
123
|
+
text,
|
|
124
|
+
}, message.date);
|
|
125
|
+
ids.set(message.id, record.id);
|
|
126
|
+
const key = `${group}\t${message.to}`;
|
|
127
|
+
if (!message.read) blocked.add(key);
|
|
128
|
+
else if (!blocked.has(key)) lastRead.set(key, record.id);
|
|
129
|
+
}
|
|
130
|
+
for (const [key, id] of lastRead) {
|
|
131
|
+
const [group, role] = key.split("\t");
|
|
132
|
+
store.advanceCursor(where, role, group, id);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
|
|
136
|
+
fs.renameSync(staging, path.join(where.common, `keel-mailbox.migrated-${stamp}`));
|
|
137
|
+
return { messages: messages.length };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
module.exports = {
|
|
141
|
+
migrateIfNeeded,
|
|
142
|
+
};
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// What a session is told about the chat, and when it is woken (issue #187,
|
|
4
|
+
// design D9, D10).
|
|
5
|
+
//
|
|
6
|
+
// Only a record that needs this role — a mention by name or alias, a todo
|
|
7
|
+
// assigned to it, a message in its direct group — touches `signal/<role>`,
|
|
8
|
+
// the file a host watches to wake an idle session. `@all` and plain messages
|
|
9
|
+
// are counted at the next prompt instead, so a busy group cannot keep every
|
|
10
|
+
// session awake.
|
|
11
|
+
//
|
|
12
|
+
// `keel chat notice` prints the notice for any host and always exits 0;
|
|
13
|
+
// `keel chat hook <event>` wraps the same text for Claude Code. Neither moves a
|
|
14
|
+
// cursor: a notice is a pointer that stays true until the role reads.
|
|
15
|
+
|
|
16
|
+
const fs = require("fs");
|
|
17
|
+
const path = require("path");
|
|
18
|
+
const store = require("./store");
|
|
19
|
+
const { relativeAge } = require("./view");
|
|
20
|
+
|
|
21
|
+
const NOTICE_LIMIT = 5;
|
|
22
|
+
|
|
23
|
+
function firstLine(text) {
|
|
24
|
+
const line = String(text || "").split("\n").find((part) => part.trim()) || "";
|
|
25
|
+
return line.length > 120 ? `${line.slice(0, 117)}...` : line;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function noticeText(where, role, now = Date.now()) {
|
|
29
|
+
const records = store.unread(where, role);
|
|
30
|
+
if (!records.length) return "";
|
|
31
|
+
const waking = records.filter((record) => store.wakes(record, role));
|
|
32
|
+
const others = new Map();
|
|
33
|
+
for (const record of records) {
|
|
34
|
+
if (waking.includes(record)) continue;
|
|
35
|
+
others.set(record.group, (others.get(record.group) || 0) + 1);
|
|
36
|
+
}
|
|
37
|
+
const lines = [
|
|
38
|
+
`keel chat: ${records.length} unread for role \`${role}\`, ${waking.length} addressed to you.`,
|
|
39
|
+
];
|
|
40
|
+
for (const record of waking.slice(0, NOTICE_LIMIT)) {
|
|
41
|
+
lines.push(`- ${record.id} in ${record.group} from \`${record.from}\`, ${relativeAge(record.created, now)}: ${firstLine(record.text)}`);
|
|
42
|
+
}
|
|
43
|
+
if (waking.length > NOTICE_LIMIT) lines.push(`- and ${waking.length - NOTICE_LIMIT} more addressed to you.`);
|
|
44
|
+
if (others.size) {
|
|
45
|
+
lines.push(`Other unread: ${[...others].map(([group, count]) => `${group}: ${count} unread`).join(", ")}.`);
|
|
46
|
+
}
|
|
47
|
+
lines.push(
|
|
48
|
+
"Read with `keel chat read` (everything) or `keel chat <group>`; reply with "
|
|
49
|
+
+ "`keel chat post <group> <text> --reply-to <id>`.",
|
|
50
|
+
store.DATA_NOTICE
|
|
51
|
+
);
|
|
52
|
+
return lines.join("\n");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function presenceFile(where, role) {
|
|
56
|
+
return path.join(where.root, "presence", `${role}.json`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Presence is written only by its own role, so it never conflicts (D1).
|
|
60
|
+
function touchPresence(where, role, state = "online", host = null) {
|
|
61
|
+
const previous = store.readJsonFile(presenceFile(where, role));
|
|
62
|
+
const record = {
|
|
63
|
+
state,
|
|
64
|
+
last_active: store.isoLocal(new Date()),
|
|
65
|
+
host: host || previous.host || null,
|
|
66
|
+
};
|
|
67
|
+
try {
|
|
68
|
+
store.writeJsonAtomic(where, presenceFile(where, role), record);
|
|
69
|
+
} catch {
|
|
70
|
+
// Presence is a convenience: failing to record it must not fail a command.
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const ONLINE_WINDOW_MS = 24 * 60 * 60 * 1000;
|
|
75
|
+
|
|
76
|
+
// `online`, `idle`, or `offline`, with the time of last activity (D10).
|
|
77
|
+
function presenceOf(where, role, now = Date.now()) {
|
|
78
|
+
const record = store.readJsonFile(presenceFile(where, role));
|
|
79
|
+
const time = Date.parse(record.last_active || "");
|
|
80
|
+
if (Number.isNaN(time)) return { state: "offline", last_active: null };
|
|
81
|
+
if (record.state === "offline") return { state: "offline", last_active: record.last_active };
|
|
82
|
+
return { state: now - time <= ONLINE_WINDOW_MS ? "online" : "idle", last_active: record.last_active };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function signalPath(where, role) {
|
|
86
|
+
return path.join(where.root, "signal", role);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function ensureSignal(where, role) {
|
|
90
|
+
const signal = signalPath(where, role);
|
|
91
|
+
fs.mkdirSync(path.dirname(signal), { recursive: true });
|
|
92
|
+
if (!fs.existsSync(signal)) fs.writeFileSync(signal, "");
|
|
93
|
+
return signal;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// For a Slack-enabled project, whether this machine's bridge is carrying the
|
|
97
|
+
// chat, so a session does not assume the owner's phone can reach it (D18).
|
|
98
|
+
function bridgeLine(where) {
|
|
99
|
+
let settings;
|
|
100
|
+
try {
|
|
101
|
+
settings = require("./config").slackSettings(where.worktree);
|
|
102
|
+
} catch {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
if (!settings.enabled) return null;
|
|
106
|
+
const status = require("./bridge").fullStatus();
|
|
107
|
+
if (!status.running) {
|
|
108
|
+
return "keel chat bridge: not running on this machine, so Slack messages are not reaching this session "
|
|
109
|
+
+ "(local chat still works). `keel chat bridge start`, or `keel chat bridge install` once, brings it up.";
|
|
110
|
+
}
|
|
111
|
+
if (status.paused) return `keel chat bridge: paused until ${status.paused_until}; messages wait until then.`;
|
|
112
|
+
return `keel chat bridge: running${status.connected ? " and connected" : ", reconnecting"}, serving ${status.projects.length} project${status.projects.length === 1 ? "" : "s"}.`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const HOST_EVENTS = {
|
|
116
|
+
"session-start": "SessionStart",
|
|
117
|
+
"user-prompt-submit": "UserPromptSubmit",
|
|
118
|
+
"file-changed": "FileChanged",
|
|
119
|
+
"session-end": "SessionEnd",
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
// Claude Code hook entry. Silent, and exit 0, wherever there is no role —
|
|
123
|
+
// including outside any repository — because exit 2 from FileChanged is the
|
|
124
|
+
// wake signal and must mean only "something addressed to you arrived".
|
|
125
|
+
const MAIL_POINTER = "Direct messages can also be read with the 5.83 `keel mail read`.";
|
|
126
|
+
|
|
127
|
+
function hook(event, input, { mail = false } = {}) {
|
|
128
|
+
if (!(event in HOST_EVENTS)) return { code: 0 };
|
|
129
|
+
let payload = {};
|
|
130
|
+
try {
|
|
131
|
+
payload = JSON.parse(input || "{}") || {};
|
|
132
|
+
} catch {
|
|
133
|
+
payload = {};
|
|
134
|
+
}
|
|
135
|
+
let where = null;
|
|
136
|
+
let role = null;
|
|
137
|
+
try {
|
|
138
|
+
where = store.locate(payload.cwd || process.cwd());
|
|
139
|
+
role = where ? store.currentRole(where) : null;
|
|
140
|
+
} catch {
|
|
141
|
+
role = null;
|
|
142
|
+
}
|
|
143
|
+
if (!where || !role) return { code: 0 };
|
|
144
|
+
if (event === "session-end") {
|
|
145
|
+
touchPresence(where, role, "offline");
|
|
146
|
+
return { code: 0 };
|
|
147
|
+
}
|
|
148
|
+
touchPresence(where, role, "online", mail ? null : "claude-code");
|
|
149
|
+
const chatText = noticeText(where, role);
|
|
150
|
+
const text = chatText && mail ? `${chatText}\n${MAIL_POINTER}` : chatText;
|
|
151
|
+
if (event === "session-start") {
|
|
152
|
+
const output = {
|
|
153
|
+
hookSpecificOutput: { hookEventName: "SessionStart", watchPaths: [ensureSignal(where, role)] },
|
|
154
|
+
};
|
|
155
|
+
const context = [bridgeLine(where), text].filter(Boolean).join("\n");
|
|
156
|
+
if (context) output.hookSpecificOutput.additionalContext = context;
|
|
157
|
+
return { code: 0, stdout: `${JSON.stringify(output)}\n` };
|
|
158
|
+
}
|
|
159
|
+
if (event === "user-prompt-submit") {
|
|
160
|
+
if (!text) return { code: 0 };
|
|
161
|
+
return {
|
|
162
|
+
code: 0,
|
|
163
|
+
stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: text } })}\n`,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
// file-changed
|
|
167
|
+
const waking = store.unread(where, role).some((record) => store.wakes(record, role));
|
|
168
|
+
return waking ? { code: 2, stderr: `${text}\n` } : { code: 0 };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
module.exports = {
|
|
172
|
+
NOTICE_LIMIT,
|
|
173
|
+
bridgeLine,
|
|
174
|
+
hook,
|
|
175
|
+
noticeText,
|
|
176
|
+
presenceOf,
|
|
177
|
+
signalPath,
|
|
178
|
+
touchPresence,
|
|
179
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// Secrets never leave the machine through the Slack bridge (issue #187,
|
|
4
|
+
// design D15). A message an agent writes can quote a log, an environment, or
|
|
5
|
+
// a config file; before any text is sent to Slack, these shapes are replaced
|
|
6
|
+
// with `[redacted]`. The local record keeps the original: it never left.
|
|
7
|
+
//
|
|
8
|
+
// This is a net for accidents, not a guarantee. It recognizes common token
|
|
9
|
+
// formats and `name = value` assignments of obviously secret names, and it
|
|
10
|
+
// cannot recognize a secret with no shape.
|
|
11
|
+
|
|
12
|
+
const REDACTED = "[redacted]";
|
|
13
|
+
|
|
14
|
+
const PATTERNS = [
|
|
15
|
+
/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g,
|
|
16
|
+
/\bxox[abeoprs]-[A-Za-z0-9-]{6,}/g,
|
|
17
|
+
/\bxapp-[A-Za-z0-9-]{6,}/g,
|
|
18
|
+
/\bgithub_pat_[A-Za-z0-9_]{20,}/g,
|
|
19
|
+
/\bgh[opsur]_[A-Za-z0-9]{16,}/g,
|
|
20
|
+
/\bsk-[A-Za-z0-9_-]{16,}/g,
|
|
21
|
+
/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
const ASSIGNMENT = /\b(password|passwd|pwd|token|secret|api[_-]?key|access[_-]?key|private[_-]?key)(\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi;
|
|
25
|
+
|
|
26
|
+
function redact(text) {
|
|
27
|
+
let result = String(text || "");
|
|
28
|
+
for (const pattern of PATTERNS) result = result.replace(pattern, REDACTED);
|
|
29
|
+
return result.replace(ASSIGNMENT, (match, name, separator, value) => (
|
|
30
|
+
value === REDACTED ? match : `${name}${separator}${REDACTED}`
|
|
31
|
+
));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
module.exports = {
|
|
35
|
+
REDACTED,
|
|
36
|
+
redact,
|
|
37
|
+
};
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// The Slack Web API client the bridge uses (issue #187, design D15–D17). It
|
|
4
|
+
// uses Node's built-in `fetch`, so the bridge adds no dependency.
|
|
5
|
+
//
|
|
6
|
+
// Write methods take a JSON body; read methods and connection setup take a
|
|
7
|
+
// form body, which every Web API method accepts. `KEEL_SLACK_API_BASE` points
|
|
8
|
+
// the client at a test server. A token is sent only in the Authorization
|
|
9
|
+
// header and is never part of an error message.
|
|
10
|
+
|
|
11
|
+
const DEFAULT_BASE = "https://slack.com/api";
|
|
12
|
+
const FORM_METHODS = new Set([
|
|
13
|
+
"auth.test",
|
|
14
|
+
"apps.connections.open",
|
|
15
|
+
"conversations.history",
|
|
16
|
+
"conversations.replies",
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
class SlackError extends Error {
|
|
20
|
+
constructor(method, error, { retryAfter = null, status = null } = {}) {
|
|
21
|
+
super(`Slack ${method} failed: ${error}${status ? ` (HTTP ${status})` : ""}`);
|
|
22
|
+
this.method = method;
|
|
23
|
+
this.error = error;
|
|
24
|
+
this.retryAfter = retryAfter;
|
|
25
|
+
this.status = status;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function apiBase() {
|
|
30
|
+
return (process.env.KEEL_SLACK_API_BASE || DEFAULT_BASE).replace(/\/+$/, "");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function sleep(ms) {
|
|
34
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function call(method, params, token) {
|
|
38
|
+
const headers = { Authorization: `Bearer ${token}` };
|
|
39
|
+
let body;
|
|
40
|
+
if (FORM_METHODS.has(method)) {
|
|
41
|
+
const form = new URLSearchParams();
|
|
42
|
+
for (const [key, value] of Object.entries(params || {})) {
|
|
43
|
+
if (value === undefined || value === null) continue;
|
|
44
|
+
form.set(key, typeof value === "object" ? JSON.stringify(value) : String(value));
|
|
45
|
+
}
|
|
46
|
+
headers["Content-Type"] = "application/x-www-form-urlencoded";
|
|
47
|
+
body = form.toString();
|
|
48
|
+
} else {
|
|
49
|
+
headers["Content-Type"] = "application/json; charset=utf-8";
|
|
50
|
+
body = JSON.stringify(params || {});
|
|
51
|
+
}
|
|
52
|
+
let response;
|
|
53
|
+
try {
|
|
54
|
+
response = await fetch(`${apiBase()}/${method}`, { method: "POST", headers, body });
|
|
55
|
+
} catch (error) {
|
|
56
|
+
throw new SlackError(method, `network error: ${error.cause ? error.cause.code || error.cause.message : error.message}`);
|
|
57
|
+
}
|
|
58
|
+
if (response.status === 429) {
|
|
59
|
+
const retryAfter = Number(response.headers.get("retry-after")) || 1;
|
|
60
|
+
throw new SlackError(method, "ratelimited", { retryAfter, status: 429 });
|
|
61
|
+
}
|
|
62
|
+
let parsed = null;
|
|
63
|
+
try {
|
|
64
|
+
parsed = await response.json();
|
|
65
|
+
} catch {
|
|
66
|
+
throw new SlackError(method, "response was not JSON", { status: response.status });
|
|
67
|
+
}
|
|
68
|
+
if (!parsed || parsed.ok !== true) {
|
|
69
|
+
throw new SlackError(method, (parsed && parsed.error) || "unknown_error", { status: response.status });
|
|
70
|
+
}
|
|
71
|
+
return parsed;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Waits out a 429 for as long as Slack asks; other failures retry with
|
|
75
|
+
// backoff up to `attempts` times and then throw.
|
|
76
|
+
async function callWithRetry(method, params, token, { attempts = 4, onWait = null } = {}) {
|
|
77
|
+
let failures = 0;
|
|
78
|
+
let backoff = 1000;
|
|
79
|
+
for (;;) {
|
|
80
|
+
try {
|
|
81
|
+
return await call(method, params, token);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (!(error instanceof SlackError)) throw error;
|
|
84
|
+
if (error.retryAfter !== null) {
|
|
85
|
+
if (onWait) onWait(method, error.retryAfter);
|
|
86
|
+
await sleep(error.retryAfter * 1000);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
failures += 1;
|
|
90
|
+
if (failures >= attempts || ["invalid_auth", "not_authed", "channel_not_found", "missing_scope", "account_inactive"].includes(error.error)) {
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
await sleep(backoff);
|
|
94
|
+
backoff = Math.min(backoff * 2, 5 * 60 * 1000);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
module.exports = {
|
|
100
|
+
SlackError,
|
|
101
|
+
call,
|
|
102
|
+
callWithRetry,
|
|
103
|
+
sleep,
|
|
104
|
+
};
|