@inetafrica/open-claudia 3.5.13 → 3.5.16
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/CHANGELOG.md +34 -0
- package/Dockerfile +3 -1
- package/channels/kazee/adapter.js +186 -34
- package/channels/kazee/bot-handoffs.js +230 -0
- package/core/browser-view.js +200 -0
- package/core/cards.js +296 -18
- package/core/loopback.js +6 -2
- package/core/passive-replies.js +4 -2
- package/core/providers/codex-hook.js +5 -1
- package/core/runner.js +5 -2
- package/core/system-prompt.js +9 -0
- package/package.json +2 -2
- package/test-fixtures/fake-agent-cli.js +13 -0
- package/test-provider-language.js +19 -1
- package/test-provider-tool-hooks.js +17 -0
- package/test-thread-lanes.js +12 -3
- package/web.js +45 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
// Live view of the bot's own browser (agent-browser) for the web dashboard and Agent Space.
|
|
2
|
+
//
|
|
3
|
+
// agent-browser runs one daemon per session and records it in its socket folder as
|
|
4
|
+
// <session>.pid, <session>.stream (port of the session's screen-stream WebSocket) and
|
|
5
|
+
// <session>.target (current tab and page address). The agent's commands run with HOME but
|
|
6
|
+
// without XDG_RUNTIME_DIR (core/providers/env.js), so their sessions land in ~/.agent-browser
|
|
7
|
+
// (/data/.agent-browser in a pod); the other folders cover a bot started with
|
|
8
|
+
// AGENT_BROWSER_SOCKET_DIR or XDG_RUNTIME_DIR.
|
|
9
|
+
//
|
|
10
|
+
// listSessions() finds the sessions that are running and streaming. serveStream() sends one
|
|
11
|
+
// session's frames and page-address updates to a viewer as server-sent events, the same
|
|
12
|
+
// transport as /api/chat/stream, so it passes through Agent Space's bot proxy unchanged.
|
|
13
|
+
// Watch-only by design: there is no path from a viewer to the browser, so watching can never
|
|
14
|
+
// click or type. Page addresses are cut to origin + path so tokens in query strings never
|
|
15
|
+
// reach a viewer.
|
|
16
|
+
|
|
17
|
+
const fs = require("fs");
|
|
18
|
+
const os = require("os");
|
|
19
|
+
const path = require("path");
|
|
20
|
+
const WebSocket = require("ws");
|
|
21
|
+
|
|
22
|
+
const SESSION_NAME = /^[A-Za-z0-9._-]{1,64}$/;
|
|
23
|
+
const DEFAULT_FPS = 5;
|
|
24
|
+
const MAX_FPS = 10;
|
|
25
|
+
const KEEPALIVE_MS = 25000; // static pages send no frames; comments keep proxies from closing the stream
|
|
26
|
+
|
|
27
|
+
function socketDirs(env = process.env, home = os.homedir()) {
|
|
28
|
+
const dirs = [];
|
|
29
|
+
if (env.AGENT_BROWSER_SOCKET_DIR) dirs.push(env.AGENT_BROWSER_SOCKET_DIR);
|
|
30
|
+
if (env.XDG_RUNTIME_DIR) dirs.push(path.join(env.XDG_RUNTIME_DIR, "agent-browser"));
|
|
31
|
+
if (home) dirs.push(path.join(home, ".agent-browser"));
|
|
32
|
+
return [...new Set(dirs)];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function readSmall(file) {
|
|
36
|
+
try {
|
|
37
|
+
return fs.readFileSync(file, "utf8").slice(0, 4096).trim();
|
|
38
|
+
} catch (_) {
|
|
39
|
+
return "";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// In a pod the session files sit on /data and outlive a restart, and pid numbers get reused, so on
|
|
44
|
+
// Linux the pid must also belong to an agent-browser process.
|
|
45
|
+
function processAlive(pid) {
|
|
46
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
47
|
+
try {
|
|
48
|
+
process.kill(pid, 0);
|
|
49
|
+
} catch (err) {
|
|
50
|
+
if (!err || err.code !== "EPERM") return false;
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
return fs.readFileSync(`/proc/${pid}/cmdline`, "utf8").includes("agent-browser");
|
|
54
|
+
} catch (_) {
|
|
55
|
+
return true; // no /proc (macOS): the signal check is all there is
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Origin + path only: no credentials, query string or fragment.
|
|
60
|
+
function safePageAddress(raw) {
|
|
61
|
+
if (!raw) return null;
|
|
62
|
+
try {
|
|
63
|
+
const u = new URL(String(raw));
|
|
64
|
+
if (u.protocol === "about:") return u.href.split(/[?#]/)[0];
|
|
65
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") return null;
|
|
66
|
+
return `${u.origin}${u.pathname}`;
|
|
67
|
+
} catch (_) {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function listSessions({ dirs = socketDirs(), alive = processAlive } = {}) {
|
|
73
|
+
const seen = new Set();
|
|
74
|
+
const sessions = [];
|
|
75
|
+
for (const dir of dirs) {
|
|
76
|
+
let files;
|
|
77
|
+
try {
|
|
78
|
+
files = fs.readdirSync(dir);
|
|
79
|
+
} catch (_) {
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
for (const file of files) {
|
|
83
|
+
if (!file.endsWith(".stream")) continue;
|
|
84
|
+
const name = file.slice(0, -".stream".length);
|
|
85
|
+
if (!SESSION_NAME.test(name) || seen.has(name)) continue;
|
|
86
|
+
const port = Number(readSmall(path.join(dir, file)));
|
|
87
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) continue;
|
|
88
|
+
if (!alive(Number(readSmall(path.join(dir, `${name}.pid`))))) continue;
|
|
89
|
+
let page = null;
|
|
90
|
+
try {
|
|
91
|
+
page = safePageAddress(JSON.parse(readSmall(path.join(dir, `${name}.target`))).url);
|
|
92
|
+
} catch (_) { /* no target yet */ }
|
|
93
|
+
let updatedAt = null;
|
|
94
|
+
for (const f of [`${name}.target`, file]) {
|
|
95
|
+
try {
|
|
96
|
+
updatedAt = fs.statSync(path.join(dir, f)).mtime.toISOString();
|
|
97
|
+
break;
|
|
98
|
+
} catch (_) { /* try the next file */ }
|
|
99
|
+
}
|
|
100
|
+
seen.add(name);
|
|
101
|
+
sessions.push({ name, port, page, updatedAt });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return sessions.sort((a, b) => String(b.updatedAt || "").localeCompare(String(a.updatedAt || "")));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Public view of a session: the stream port stays inside the bot.
|
|
108
|
+
function describeSessions(options) {
|
|
109
|
+
return listSessions(options).map(({ name, page, updatedAt }) => ({ name, page, updatedAt }));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function clampFps(value) {
|
|
113
|
+
const n = Math.round(Number(value));
|
|
114
|
+
if (!Number.isFinite(n) || n < 1) return DEFAULT_FPS;
|
|
115
|
+
return Math.min(n, MAX_FPS);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Open one session's screen stream. onMessage gets {type: "frame"|"url", ...}; onEnd(reason) runs
|
|
119
|
+
// once when the session is not running, ends, or cannot be reached. close() stops it quietly.
|
|
120
|
+
function openStream(sessionName, { fps, sessions, connect = (url) => new WebSocket(url), onMessage, onEnd }) {
|
|
121
|
+
const session = (sessions || listSessions()).find((s) => s.name === sessionName);
|
|
122
|
+
if (!session) {
|
|
123
|
+
onEnd("not-running");
|
|
124
|
+
return { close() {} };
|
|
125
|
+
}
|
|
126
|
+
const upstream = connect(`ws://127.0.0.1:${session.port}/?maxFps=${clampFps(fps)}`);
|
|
127
|
+
let done = false;
|
|
128
|
+
const stop = () => {
|
|
129
|
+
if (done) return false;
|
|
130
|
+
done = true;
|
|
131
|
+
try { upstream.close(); } catch (_) { /* already closed */ }
|
|
132
|
+
return true;
|
|
133
|
+
};
|
|
134
|
+
if (session.page) onMessage({ type: "url", url: session.page });
|
|
135
|
+
upstream.on("message", (data) => {
|
|
136
|
+
if (done) return;
|
|
137
|
+
let msg;
|
|
138
|
+
try {
|
|
139
|
+
msg = JSON.parse(String(data));
|
|
140
|
+
} catch (_) {
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (msg && msg.type === "frame" && typeof msg.data === "string") {
|
|
144
|
+
onMessage({ type: "frame", seq: msg.seq, data: msg.data, metadata: msg.metadata || {} });
|
|
145
|
+
} else if (msg && msg.type === "url") {
|
|
146
|
+
onMessage({ type: "url", url: safePageAddress(msg.url) });
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
upstream.on("close", () => { if (stop()) onEnd("ended"); });
|
|
150
|
+
upstream.on("error", () => { if (stop()) onEnd("unavailable"); });
|
|
151
|
+
return { close: stop };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Server-sent events for one session: "frame" and "url" events, a final "end" event with the
|
|
155
|
+
// reason, and ": ping" comments while the page is still. Every payload also carries its type,
|
|
156
|
+
// for readers that only look at data lines. Frames are skipped, never queued, while a slow
|
|
157
|
+
// viewer's connection is backed up.
|
|
158
|
+
function serveStream(res, sessionName, { fps, sessions, connect, keepaliveMs = KEEPALIVE_MS } = {}) {
|
|
159
|
+
res.writeHead(200, {
|
|
160
|
+
"Content-Type": "text/event-stream",
|
|
161
|
+
"Cache-Control": "no-cache, no-store",
|
|
162
|
+
"Connection": "keep-alive",
|
|
163
|
+
"X-Accel-Buffering": "no",
|
|
164
|
+
});
|
|
165
|
+
const write = (event, obj) => {
|
|
166
|
+
try { res.write(`event: ${event}\ndata: ${JSON.stringify(obj)}\n\n`); } catch (_) { /* viewer gone */ }
|
|
167
|
+
};
|
|
168
|
+
const heartbeat = setInterval(() => { try { res.write(": ping\n\n"); } catch (_) { /* viewer gone */ } }, keepaliveMs);
|
|
169
|
+
const stream = openStream(sessionName, {
|
|
170
|
+
fps,
|
|
171
|
+
sessions,
|
|
172
|
+
connect,
|
|
173
|
+
onMessage: (msg) => {
|
|
174
|
+
if (msg.type === "frame" && res.writableNeedDrain) return;
|
|
175
|
+
write(msg.type, msg);
|
|
176
|
+
},
|
|
177
|
+
onEnd: (reason) => {
|
|
178
|
+
clearInterval(heartbeat);
|
|
179
|
+
write("end", { type: "end", reason });
|
|
180
|
+
try { res.end(); } catch (_) { /* viewer gone */ }
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
res.on("close", () => {
|
|
184
|
+
clearInterval(heartbeat);
|
|
185
|
+
stream.close();
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
module.exports = {
|
|
190
|
+
DEFAULT_FPS,
|
|
191
|
+
MAX_FPS,
|
|
192
|
+
clampFps,
|
|
193
|
+
describeSessions,
|
|
194
|
+
listSessions,
|
|
195
|
+
openStream,
|
|
196
|
+
processAlive,
|
|
197
|
+
safePageAddress,
|
|
198
|
+
serveStream,
|
|
199
|
+
socketDirs,
|
|
200
|
+
};
|
package/core/cards.js
CHANGED
|
@@ -12,6 +12,12 @@
|
|
|
12
12
|
// rest wait; Later snoozes, Tell me more asks the origin
|
|
13
13
|
// conversation for a voice explainer
|
|
14
14
|
//
|
|
15
|
+
// Open decisions must not sink and go stale (Sumeet, 5 Oct 2026): the ledger
|
|
16
|
+
// keeps each card's state current, the turn's prompt lists the decisions
|
|
17
|
+
// still open in that conversation so the bot closes the ones that no longer
|
|
18
|
+
// apply, a decision left overnight gets one reminder in its own thread, and a
|
|
19
|
+
// late answer wakes with "check this still applies".
|
|
20
|
+
//
|
|
15
21
|
// Safety: an answer wakes the conversation that sent the card, which runs as
|
|
16
22
|
// that card's sender. Anything a person typed (a rating comment) is quoted as
|
|
17
23
|
// their words, never as instructions. Cards that anyone in a group may answer
|
|
@@ -29,6 +35,19 @@ const CARD_KEEP_MS = 45 * 24 * 60 * 60 * 1000;
|
|
|
29
35
|
const CARD_KEEP_MAX = 2000;
|
|
30
36
|
const SNOOZE_MS = Number(process.env.OC_DECISION_SNOOZE_MS || 3 * 60 * 60 * 1000);
|
|
31
37
|
const COMMENT_MAX = 500;
|
|
38
|
+
const HOUR_MS = 60 * 60 * 1000;
|
|
39
|
+
const DAY_MS = 24 * HOUR_MS;
|
|
40
|
+
const OPEN_DECISION_MAX_AGE_MS = 14 * DAY_MS;
|
|
41
|
+
const REMIND_MAX_AGE_MS = 7 * DAY_MS;
|
|
42
|
+
const REMIND_MIN_WAIT_MS = 8 * HOUR_MS;
|
|
43
|
+
const REMIND_HOUR = 9;
|
|
44
|
+
const REMIND_LAST_HOUR = 18;
|
|
45
|
+
const LATE_ANSWER_MS = 6 * HOUR_MS;
|
|
46
|
+
const PROMPT_DECISIONS_MAX = 5;
|
|
47
|
+
const PROMPT_TITLE_MAX = 80;
|
|
48
|
+
const PROMPT_TITLE_MIN = 20;
|
|
49
|
+
const PROMPT_SECTION_MAX = 600;
|
|
50
|
+
const timeZone = () => process.env.OC_TIMEZONE || "Africa/Nairobi";
|
|
32
51
|
|
|
33
52
|
function readJson(file, fallback) {
|
|
34
53
|
try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch (_) { return fallback; }
|
|
@@ -77,6 +96,97 @@ function updateCardRecord(messageId, patch) {
|
|
|
77
96
|
return cards[String(messageId)];
|
|
78
97
|
}
|
|
79
98
|
|
|
99
|
+
/** A card is open unless the server (or the bot) closed or decided it. */
|
|
100
|
+
function cardIsOpen(state) {
|
|
101
|
+
if (!state) return true;
|
|
102
|
+
if (state.decided) return false;
|
|
103
|
+
return !["closed", "decided", "expired"].includes(state.status);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The bot changed one of its own cards (PUT /message/:id/card): keep the
|
|
108
|
+
* ledger's lastState current. `view` is the server's answer when there is one.
|
|
109
|
+
*/
|
|
110
|
+
function noteCardUpdate(messageId, patch = {}, view = null) {
|
|
111
|
+
const cur = getCard(messageId);
|
|
112
|
+
if (!cur) return null;
|
|
113
|
+
const at = new Date().toISOString();
|
|
114
|
+
let lastState;
|
|
115
|
+
if (view && view.state) {
|
|
116
|
+
lastState = { ...view.state, at };
|
|
117
|
+
} else {
|
|
118
|
+
lastState = { ...(cur.lastState || {}), status: patch.status || cur.lastState?.status || "open", at };
|
|
119
|
+
if (patch.note !== undefined && patch.note !== null) {
|
|
120
|
+
const note = String(patch.note).trim();
|
|
121
|
+
if (note) lastState.note = note;
|
|
122
|
+
else delete lastState.note;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return updateCardRecord(messageId, { lastState, ...(patch.card?.title ? { title: patch.card.title } : {}) });
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Where a card was posted: a queued decision's home, else the conversation that sent it. */
|
|
129
|
+
function placeOf(rec) {
|
|
130
|
+
return rec.home || rec.origin || {};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The bot's own decision cards still waiting for an answer, oldest first.
|
|
135
|
+
* With channelId: only those asked in that conversation (its thread, or the
|
|
136
|
+
* main timeline when threadId is empty).
|
|
137
|
+
*/
|
|
138
|
+
function openDecisions({ adapterId = null, channelId, threadId = null, now = Date.now() } = {}) {
|
|
139
|
+
const queue = new Map(loadDecisions().map((d) => [d.id, d]));
|
|
140
|
+
return Object.values(loadCards())
|
|
141
|
+
.filter((c) => c && c.kind === "decision" && !c.answeredAt && cardIsOpen(c.lastState))
|
|
142
|
+
.filter((c) => now - Date.parse(c.sentAt || 0) <= OPEN_DECISION_MAX_AGE_MS)
|
|
143
|
+
.filter((c) => !c.decisionId || !queue.has(c.decisionId) || ["queued", "asked", "snoozed"].includes(queue.get(c.decisionId).status))
|
|
144
|
+
.filter((c) => {
|
|
145
|
+
if (channelId === undefined || channelId === null) return true;
|
|
146
|
+
const p = placeOf(c);
|
|
147
|
+
return String(p.channelId || "") === String(channelId)
|
|
148
|
+
&& String(p.threadId || "") === String(threadId || "")
|
|
149
|
+
&& (!adapterId || !p.adapter || p.adapter === adapterId);
|
|
150
|
+
})
|
|
151
|
+
.sort((a, b) => Date.parse(a.sentAt) - Date.parse(b.sentAt));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function plural(n, word) {
|
|
155
|
+
return `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** "5 minutes", "3 hours", "2 days". */
|
|
159
|
+
function ageWords(ms) {
|
|
160
|
+
if (ms < HOUR_MS) return plural(Math.max(1, Math.floor(ms / 60000)), "minute");
|
|
161
|
+
if (ms < 2 * DAY_MS) return plural(Math.floor(ms / HOUR_MS), "hour");
|
|
162
|
+
return plural(Math.floor(ms / DAY_MS), "day");
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function shortTitle(title, max) {
|
|
166
|
+
const t = String(title || "a decision").replace(/\s+/g, " ").trim().replace(/"/g, "'");
|
|
167
|
+
return t.length > max ? `${t.slice(0, max - 1)}…` : t;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* The per-turn prompt section listing the decisions this bot asked in this
|
|
172
|
+
* conversation that are still open, so it closes the ones answered in words
|
|
173
|
+
* or no longer needed. "" when there are none. Titles are cut to keep the
|
|
174
|
+
* whole section under PROMPT_SECTION_MAX characters.
|
|
175
|
+
*/
|
|
176
|
+
function openDecisionsPromptSection({ adapterId = null, channelId, threadId = null, now = Date.now() } = {}) {
|
|
177
|
+
if (!channelId) return "";
|
|
178
|
+
const open = openDecisions({ adapterId, channelId, threadId, now });
|
|
179
|
+
if (!open.length) return "";
|
|
180
|
+
const shown = open.slice(0, PROMPT_DECISIONS_MAX);
|
|
181
|
+
const head = "## Open decisions you asked here";
|
|
182
|
+
const more = open.length > shown.length ? [`- and ${open.length - shown.length} more`] : [];
|
|
183
|
+
const tail = "If the latest message answers one, or it no longer applies, close it: `open-claudia card update <messageId> --close --note \"<why, in plain words>\"`. Never leave an answered or moot decision open.";
|
|
184
|
+
const line = (c, title) => `- [${c.messageId}] "${title}" — asked ${ageWords(now - Date.parse(c.sentAt))} ago`;
|
|
185
|
+
const fixed = [head, ...shown.map((c) => line(c, "")), ...more, tail].join("\n").length;
|
|
186
|
+
const titleMax = Math.max(PROMPT_TITLE_MIN, Math.min(PROMPT_TITLE_MAX, Math.floor((PROMPT_SECTION_MAX - fixed) / shown.length)));
|
|
187
|
+
return [head, ...shown.map((c) => line(c, shortTitle(c.title, titleMax))), ...more, tail].join("\n");
|
|
188
|
+
}
|
|
189
|
+
|
|
80
190
|
/** Default wake policy: one person's card wakes on each answer; open polls don't. */
|
|
81
191
|
function defaultWake(card) {
|
|
82
192
|
const responders = card?.policy?.responders;
|
|
@@ -117,11 +227,20 @@ function totalsLine(card) {
|
|
|
117
227
|
return parts.join("; ");
|
|
118
228
|
}
|
|
119
229
|
|
|
120
|
-
|
|
230
|
+
/** For a wake-up: a card answered long after it was asked may be out of date. */
|
|
231
|
+
function lateAnswerLine(sentAt, now = Date.now()) {
|
|
232
|
+
const age = now - Date.parse(sentAt || 0);
|
|
233
|
+
if (!sentAt || !Number.isFinite(age) || age <= LATE_ANSWER_MS) return "";
|
|
234
|
+
return `This was asked ${ageWords(age)} ago. Before acting on it, check it still applies; if things have moved on, say so briefly instead of acting.`;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function describeResponse(rec, payload, now = Date.now()) {
|
|
121
238
|
const who = payload.userName || (payload.userId ? `user ${payload.userId}` : "Someone (anonymous card)");
|
|
122
239
|
const title = rec.title || payload.card?.title || "your card";
|
|
240
|
+
const late = lateAnswerLine(rec.sentAt, now);
|
|
123
241
|
if (payload.action) {
|
|
124
|
-
|
|
242
|
+
const tapped = `[Card ${payload.messageId}] ${who} tapped "${payload.label || payload.action}" on "${title}".`;
|
|
243
|
+
return late ? `${tapped}\n${late}` : tapped;
|
|
125
244
|
}
|
|
126
245
|
const comment = payload.answer && payload.answer.comment ? quote(payload.answer.comment) : "";
|
|
127
246
|
const lines = [`[Card ${payload.messageId}] ${who} answered "${title}": ${answerLabel(payload)}.`];
|
|
@@ -129,6 +248,7 @@ function describeResponse(rec, payload) {
|
|
|
129
248
|
const totals = totalsLine(payload.card);
|
|
130
249
|
if (totals) lines.push(`Totals: ${totals}.`);
|
|
131
250
|
lines.push("This is their reply to the card you sent. Act on it if your work was waiting for it; otherwise just note it.");
|
|
251
|
+
if (late) lines.push(late);
|
|
132
252
|
return lines.join("\n");
|
|
133
253
|
}
|
|
134
254
|
|
|
@@ -179,7 +299,12 @@ async function handleCardResponse(envelope, deps = {}) {
|
|
|
179
299
|
console.log(`[cards] answer on unknown card ${messageId} (sent before this bot kept a ledger, or by another bot)`);
|
|
180
300
|
return { handled: false, reason: "unknown card" };
|
|
181
301
|
}
|
|
182
|
-
|
|
302
|
+
const at = new Date().toISOString();
|
|
303
|
+
updateCardRecord(messageId, {
|
|
304
|
+
lastState: payload.card?.state ? { ...payload.card.state, at } : rec.lastState || null,
|
|
305
|
+
lastResponseAt: at,
|
|
306
|
+
...(payload.answer ? { answeredAt: rec.answeredAt || at } : {}),
|
|
307
|
+
});
|
|
183
308
|
|
|
184
309
|
if (rec.decisionId) return handleDecisionResponse(rec, payload, envelope, deps);
|
|
185
310
|
|
|
@@ -248,11 +373,19 @@ function decisionCard(d, position, total) {
|
|
|
248
373
|
return card;
|
|
249
374
|
}
|
|
250
375
|
|
|
376
|
+
/** The one reply that brings an open decision back to the top of the chat. */
|
|
377
|
+
function reminderText(title) {
|
|
378
|
+
return `⏳ Still waiting on you: ${title || "a decision"}`;
|
|
379
|
+
}
|
|
380
|
+
|
|
251
381
|
/**
|
|
252
382
|
* Ask the next decision in a home chat when none is out. `send` posts a card
|
|
253
|
-
* and returns its message id: (home, card) => Promise<string>.
|
|
383
|
+
* and returns its message id: (home, card) => Promise<string>. `remind`
|
|
384
|
+
* posts a plain reply: (home, text, { threadId, replyTo }) => Promise. A
|
|
385
|
+
* snoozed decision keeps its card open; when its time is up it gets one
|
|
386
|
+
* reply on that card (not a new card) and counts as asked again.
|
|
254
387
|
*/
|
|
255
|
-
async function pumpDecisions({ send, now = Date.now(), homeKey = null } = {}) {
|
|
388
|
+
async function pumpDecisions({ send, remind = null, updateCard = null, now = Date.now(), homeKey = null } = {}) {
|
|
256
389
|
const list = loadDecisions();
|
|
257
390
|
const homes = new Map();
|
|
258
391
|
for (const d of list) {
|
|
@@ -264,8 +397,37 @@ async function pumpDecisions({ send, now = Date.now(), homeKey = null } = {}) {
|
|
|
264
397
|
}
|
|
265
398
|
const asked = [];
|
|
266
399
|
for (const [key, ds] of homes) {
|
|
267
|
-
|
|
268
|
-
|
|
400
|
+
const isDue = (d) => d.status === "snoozed" && Date.parse(d.notBefore || 0) <= now;
|
|
401
|
+
let remindedHere = false;
|
|
402
|
+
for (const d of ds.filter((x) => isDue(x) && x.keptCard && x.askedMessageId)) {
|
|
403
|
+
if (!remind) continue;
|
|
404
|
+
try {
|
|
405
|
+
await remind(d.home, reminderText(d.title), { threadId: d.home.threadId || null, replyTo: d.askedMessageId });
|
|
406
|
+
} catch (e) {
|
|
407
|
+
console.error(`[cards] snoozed decision ${d.id} reminder failed:`, e.message);
|
|
408
|
+
continue;
|
|
409
|
+
}
|
|
410
|
+
const fresh = loadDecisions();
|
|
411
|
+
const target = fresh.find((x) => x.id === d.id);
|
|
412
|
+
if (!target || target.status !== "snoozed") continue;
|
|
413
|
+
target.status = "asked";
|
|
414
|
+
target.remindedAt = new Date(now).toISOString();
|
|
415
|
+
saveDecisions(fresh);
|
|
416
|
+
// This reply is the card's one reminder: the overnight pass skips it.
|
|
417
|
+
updateCardRecord(d.askedMessageId, { remindedAt: target.remindedAt });
|
|
418
|
+
if (updateCard) {
|
|
419
|
+
try {
|
|
420
|
+
const view = await updateCard(d.askedMessageId, { note: "" });
|
|
421
|
+
noteCardUpdate(d.askedMessageId, { note: "" }, view);
|
|
422
|
+
} catch (_) { /* the reminder is out; a stale note is harmless */ }
|
|
423
|
+
}
|
|
424
|
+
d.status = "asked";
|
|
425
|
+
remindedHere = true;
|
|
426
|
+
asked.push({ key, decisionId: d.id, messageId: d.askedMessageId, reminded: true });
|
|
427
|
+
}
|
|
428
|
+
if (remindedHere || ds.some((d) => d.status === "asked")) continue;
|
|
429
|
+
// A decision snoozed before cards stayed open had its card closed: ask it again as a new card.
|
|
430
|
+
const due = ds.filter((d) => d.status === "queued" || (isDue(d) && !d.keptCard));
|
|
269
431
|
if (!due.length) continue;
|
|
270
432
|
const next = due.sort((a, b) => (a.status === "queued") - (b.status === "queued") || a.seq - b.seq)[0];
|
|
271
433
|
const open = ds.filter((d) => d.status !== "snoozed" || d === next).length;
|
|
@@ -299,15 +461,22 @@ async function handleDecisionResponse(rec, payload, envelope, deps = {}) {
|
|
|
299
461
|
if (!d) return { handled: false, reason: "unknown decision" };
|
|
300
462
|
const updateCard = deps.updateCard || ((messageId, patch) => envelope.adapter?.updateCard?.(messageId, patch));
|
|
301
463
|
const send = deps.sendCard || ((home, card) => envelope.adapter?.sendCard?.(home.channelId, card, { threadId: home.threadId || null }));
|
|
464
|
+
const remind = deps.remind || ((home, text, opts) => envelope.adapter?.send?.(home.channelId, text, opts));
|
|
465
|
+
const pump = () => pumpDecisions({ send, remind, updateCard, homeKey: `${d.home.adapter}|${d.home.channelId}` });
|
|
302
466
|
|
|
303
467
|
if (payload.action === "later") {
|
|
468
|
+
// The card stays open where it is (no closing it and posting a new one
|
|
469
|
+
// later); a note on it says when it comes back. A note-only change just
|
|
470
|
+
// redraws the card: no new message, no notification.
|
|
304
471
|
d.status = "snoozed";
|
|
472
|
+
d.keptCard = true;
|
|
305
473
|
d.notBefore = new Date(Date.now() + SNOOZE_MS).toISOString();
|
|
306
474
|
d.snoozes = (d.snoozes || 0) + 1;
|
|
307
475
|
saveDecisions(list);
|
|
308
|
-
const until = new Date(d.notBefore).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit", timeZone:
|
|
309
|
-
|
|
310
|
-
|
|
476
|
+
const until = new Date(d.notBefore).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit", timeZone: timeZone() });
|
|
477
|
+
const patch = { note: `⏰ Later: I'll remind you at ${until}.` };
|
|
478
|
+
try { noteCardUpdate(rec.messageId, patch, await updateCard(rec.messageId, patch)); } catch (e) { console.error("[cards] snooze note failed:", e.message); }
|
|
479
|
+
await pump();
|
|
311
480
|
return { handled: true, snoozed: true };
|
|
312
481
|
}
|
|
313
482
|
if (payload.action === "more") {
|
|
@@ -320,18 +489,23 @@ async function handleDecisionResponse(rec, payload, envelope, deps = {}) {
|
|
|
320
489
|
return { handled: true, explained: true };
|
|
321
490
|
}
|
|
322
491
|
if (payload.answer) {
|
|
492
|
+
const wasSnoozed = d.status === "snoozed" && d.keptCard;
|
|
323
493
|
d.status = "decided";
|
|
324
494
|
d.answer = payload.answer;
|
|
325
495
|
d.answerLabel = answerLabel(payload);
|
|
326
496
|
d.decidedAt = new Date().toISOString();
|
|
327
497
|
saveDecisions(list);
|
|
498
|
+
if (wasSnoozed) {
|
|
499
|
+
try { noteCardUpdate(rec.messageId, { note: "" }, await updateCard(rec.messageId, { note: "" })); } catch (_) { /* only clears the "remind you at" note */ }
|
|
500
|
+
}
|
|
501
|
+
const late = lateAnswerLine(rec.sentAt);
|
|
328
502
|
wakeOrigin(
|
|
329
503
|
d.origin,
|
|
330
|
-
`[Decision ${d.id}] Sumeet decided "${d.title}": ${d.answerLabel}.\nThis was queued from this conversation. Carry on with the work that was waiting for it, and tell him briefly what happens next
|
|
504
|
+
`[Decision ${d.id}] Sumeet decided "${d.title}": ${d.answerLabel}.\nThis was queued from this conversation. Carry on with the work that was waiting for it, and tell him briefly what happens next.${late ? `\n${late}` : ""}`,
|
|
331
505
|
`Decided: ${d.title}`,
|
|
332
506
|
deps,
|
|
333
507
|
);
|
|
334
|
-
await
|
|
508
|
+
await pump();
|
|
335
509
|
return { handled: true, decided: true };
|
|
336
510
|
}
|
|
337
511
|
return { handled: false, reason: "nothing to do" };
|
|
@@ -342,18 +516,94 @@ async function cancelDecision(id, { updateCard } = {}) {
|
|
|
342
516
|
const d = list.find((x) => x.id === id);
|
|
343
517
|
if (!d) return null;
|
|
344
518
|
if (!["queued", "asked", "snoozed"].includes(d.status)) return d;
|
|
345
|
-
const
|
|
519
|
+
const cardOpen = d.status === "asked" || (d.status === "snoozed" && d.keptCard);
|
|
346
520
|
d.status = "cancelled";
|
|
347
521
|
d.cancelledAt = new Date().toISOString();
|
|
348
522
|
saveDecisions(list);
|
|
349
|
-
if (
|
|
350
|
-
|
|
523
|
+
if (cardOpen && d.askedMessageId && updateCard) {
|
|
524
|
+
const patch = { status: "closed", note: "Withdrawn: no longer needed." };
|
|
525
|
+
try { noteCardUpdate(d.askedMessageId, patch, await updateCard(d.askedMessageId, patch)); } catch (_) {}
|
|
351
526
|
}
|
|
352
527
|
return d;
|
|
353
528
|
}
|
|
354
529
|
|
|
355
|
-
//
|
|
356
|
-
//
|
|
530
|
+
// ---------------------------------------------------------------------------
|
|
531
|
+
// One reminder for a decision left waiting overnight
|
|
532
|
+
|
|
533
|
+
function zonedParts(t, tz) {
|
|
534
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
535
|
+
timeZone: tz, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit",
|
|
536
|
+
}).formatToParts(new Date(t));
|
|
537
|
+
const p = Object.fromEntries(parts.map((x) => [x.type, Number(x.value)]));
|
|
538
|
+
return { year: p.year, month: p.month, day: p.day, hour: p.hour % 24, minute: p.minute, second: p.second };
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* The instant of hour:00 on a local calendar day (day may overflow; Date.UTC
|
|
543
|
+
* rolls it). One offset lookup is enough for a morning hour: clocks change
|
|
544
|
+
* in the small hours, never within a few hours of 09:00.
|
|
545
|
+
*/
|
|
546
|
+
function zonedTime(year, month, day, hour, tz) {
|
|
547
|
+
const guess = Date.UTC(year, month - 1, day, hour);
|
|
548
|
+
const p = zonedParts(guess, tz);
|
|
549
|
+
const offset = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second) - guess;
|
|
550
|
+
return guess - offset;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** The first 09:00 local at least 8 hours after the decision was asked. */
|
|
554
|
+
function reminderDueAt(sentAt, tz = timeZone()) {
|
|
555
|
+
const earliest = Date.parse(sentAt) + REMIND_MIN_WAIT_MS;
|
|
556
|
+
const p = zonedParts(earliest, tz);
|
|
557
|
+
const sameDay = zonedTime(p.year, p.month, p.day, REMIND_HOUR, tz);
|
|
558
|
+
return sameDay >= earliest ? sameDay : zonedTime(p.year, p.month, p.day + 1, REMIND_HOUR, tz);
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/**
|
|
562
|
+
* Post the one reminder each open decision card is due, as a plain reply to
|
|
563
|
+
* the card in its own chat and thread. `readState(rec)` asks the server for
|
|
564
|
+
* the card's current state; only a card the server shows as open gets the
|
|
565
|
+
* reminder (the ledger misses answers the bot never received), and a failed
|
|
566
|
+
* or empty read is tried again on a later tick. Without `readState` the
|
|
567
|
+
* ledger decides. Reminders go out between 09:00 and 18:00 local only, so a
|
|
568
|
+
* restart at night never posts a batch of them.
|
|
569
|
+
* `send(place, text, { threadId, replyTo })` posts the reply.
|
|
570
|
+
*/
|
|
571
|
+
async function remindOpenDecisions({ send, readState = null, now = Date.now(), tz = timeZone() } = {}) {
|
|
572
|
+
const localHour = zonedParts(now, tz).hour;
|
|
573
|
+
if (localHour < REMIND_HOUR || localHour >= REMIND_LAST_HOUR) return [];
|
|
574
|
+
const queue = new Map(loadDecisions().map((d) => [d.id, d]));
|
|
575
|
+
const due = openDecisions({ now }).filter((c) => !c.remindedAt
|
|
576
|
+
&& now - Date.parse(c.sentAt) <= REMIND_MAX_AGE_MS
|
|
577
|
+
&& now >= reminderDueAt(c.sentAt, tz)
|
|
578
|
+
// a snoozed decision comes back through the queue at its own time
|
|
579
|
+
&& !(c.decisionId && queue.get(c.decisionId)?.status === "snoozed"));
|
|
580
|
+
const reminded = [];
|
|
581
|
+
for (const c of due) {
|
|
582
|
+
if (readState) {
|
|
583
|
+
let state = null;
|
|
584
|
+
try { state = await readState(c); } catch (e) { console.error(`[cards] reading card ${c.messageId} failed, trying again later:`, e.message); }
|
|
585
|
+
if (!state) continue;
|
|
586
|
+
updateCardRecord(c.messageId, { lastState: { ...state, at: new Date(now).toISOString() } });
|
|
587
|
+
if (!cardIsOpen(state)) continue;
|
|
588
|
+
}
|
|
589
|
+
// Claimed before sending: a reminder is never posted twice, even if the
|
|
590
|
+
// send fails half way.
|
|
591
|
+
updateCardRecord(c.messageId, { remindedAt: new Date(now).toISOString() });
|
|
592
|
+
const place = placeOf(c);
|
|
593
|
+
try {
|
|
594
|
+
await send(place, reminderText(c.title), { threadId: place.threadId || null, replyTo: c.messageId });
|
|
595
|
+
reminded.push(c.messageId);
|
|
596
|
+
} catch (e) {
|
|
597
|
+
updateCardRecord(c.messageId, { remindFailed: String(e.message || e).slice(0, 200) });
|
|
598
|
+
console.error(`[cards] reminder for card ${c.messageId} failed:`, e.message);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
return reminded;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
// Snoozed decisions come back when their time is up, and decisions left
|
|
605
|
+
// overnight get their one reminder; nothing else would, so the bot looks
|
|
606
|
+
// every few minutes.
|
|
357
607
|
let pumpTimer = null;
|
|
358
608
|
function startDecisionPump(registry, intervalMs = 5 * 60 * 1000) {
|
|
359
609
|
if (pumpTimer) return pumpTimer;
|
|
@@ -362,7 +612,27 @@ function startDecisionPump(registry, intervalMs = 5 * 60 * 1000) {
|
|
|
362
612
|
if (!adapter || typeof adapter.sendCard !== "function") return null;
|
|
363
613
|
return adapter.sendCard(home.channelId, card, { threadId: home.threadId || null });
|
|
364
614
|
};
|
|
365
|
-
const
|
|
615
|
+
const remind = (place, text, opts) => {
|
|
616
|
+
const adapter = registry.findAdapter(place.adapter);
|
|
617
|
+
if (!adapter || typeof adapter.send !== "function") throw new Error(`no adapter ${place.adapter}`);
|
|
618
|
+
return adapter.send(place.channelId, text, opts);
|
|
619
|
+
};
|
|
620
|
+
const updateCard = (messageId, patch) => {
|
|
621
|
+
const rec = getCard(messageId);
|
|
622
|
+
const adapter = rec && registry.findAdapter(placeOf(rec).adapter);
|
|
623
|
+
return adapter && typeof adapter.updateCard === "function" ? adapter.updateCard(messageId, patch) : null;
|
|
624
|
+
};
|
|
625
|
+
const readState = async (rec) => {
|
|
626
|
+
const place = placeOf(rec);
|
|
627
|
+
const adapter = registry.findAdapter(place.adapter);
|
|
628
|
+
if (!adapter || typeof adapter.readCard !== "function") return null;
|
|
629
|
+
const card = await adapter.readCard(place.channelId, rec.messageId);
|
|
630
|
+
return card?.state || null;
|
|
631
|
+
};
|
|
632
|
+
const tick = async () => {
|
|
633
|
+
await pumpDecisions({ send, remind, updateCard }).catch((e) => console.error("[cards] decision pump failed:", e.message));
|
|
634
|
+
await remindOpenDecisions({ send: remind, readState }).catch((e) => console.error("[cards] decision reminders failed:", e.message));
|
|
635
|
+
};
|
|
366
636
|
pumpTimer = setInterval(tick, intervalMs);
|
|
367
637
|
if (pumpTimer.unref) pumpTimer.unref();
|
|
368
638
|
const first = setTimeout(tick, 30 * 1000);
|
|
@@ -377,6 +647,14 @@ module.exports = {
|
|
|
377
647
|
recordSentCard,
|
|
378
648
|
getCard,
|
|
379
649
|
updateCardRecord,
|
|
650
|
+
noteCardUpdate,
|
|
651
|
+
cardIsOpen,
|
|
652
|
+
openDecisions,
|
|
653
|
+
openDecisionsPromptSection,
|
|
654
|
+
ageWords,
|
|
655
|
+
lateAnswerLine,
|
|
656
|
+
reminderDueAt,
|
|
657
|
+
remindOpenDecisions,
|
|
380
658
|
defaultWake,
|
|
381
659
|
describeResponse,
|
|
382
660
|
handleCardResponse,
|
package/core/loopback.js
CHANGED
|
@@ -234,7 +234,7 @@ async function handleCardKind(res, kind, payload, { channelId, adapterId, adapte
|
|
|
234
234
|
}
|
|
235
235
|
try {
|
|
236
236
|
const view = await target.updateCard(String(payload.messageId), patch);
|
|
237
|
-
cards.
|
|
237
|
+
cards.noteCardUpdate(payload.messageId, patch, view);
|
|
238
238
|
return reply(res, 200, { ok: true, card: view });
|
|
239
239
|
} catch (e) {
|
|
240
240
|
return reply(res, 400, { error: e.message });
|
|
@@ -282,7 +282,11 @@ async function handleCardKind(res, kind, payload, { channelId, adapterId, adapte
|
|
|
282
282
|
});
|
|
283
283
|
let asked = [];
|
|
284
284
|
try {
|
|
285
|
-
asked = await cards.pumpDecisions({
|
|
285
|
+
asked = await cards.pumpDecisions({
|
|
286
|
+
send: (home, card) => ((registry.findAdapter(home.adapter) || own).sendCard(home.channelId, card, { threadId: home.threadId || null })),
|
|
287
|
+
remind: (home, text, opts) => ((registry.findAdapter(home.adapter) || own).send(home.channelId, text, opts)),
|
|
288
|
+
updateCard: (messageId, patch) => (typeof own.updateCard === "function" ? own.updateCard(messageId, patch) : null),
|
|
289
|
+
});
|
|
286
290
|
} catch (e) {
|
|
287
291
|
const waiting = cards.loadDecisions().filter((x) => ["queued", "asked", "snoozed"].includes(x.status)).length;
|
|
288
292
|
return reply(res, 200, { ok: true, decision: d, askedNow: false, waiting, warning: `queued, but asking failed: ${e.message}` });
|
package/core/passive-replies.js
CHANGED
|
@@ -66,9 +66,11 @@ function clip(text, limit) {
|
|
|
66
66
|
|
|
67
67
|
// A message to the bot that only asks it to go quiet ("snooze") or to speak
|
|
68
68
|
// again ("resume"), with its @-mention and the bot's name taken out; null for
|
|
69
|
-
// anything else, so "@Maya stop the build" is never mistaken for one.
|
|
69
|
+
// anything else, so "@Maya stop the build" is never mistaken for one. The
|
|
70
|
+
// Kazee apps write a tag as @[Name](userId) (5 Oct 2026: "@sales-bot be
|
|
71
|
+
// quiet" from the app was never recognised): such tags are taken out first.
|
|
70
72
|
function quietCommand(text, botName = "") {
|
|
71
|
-
let t = String(text || "").toLowerCase();
|
|
73
|
+
let t = String(text || "").replace(/@\[[^\]\n]{1,120}\]\([^)\s]{1,64}\)/g, " ").toLowerCase();
|
|
72
74
|
const name = String(botName || "").trim().toLowerCase();
|
|
73
75
|
if (name) t = t.split(`@${name}`).join(" ");
|
|
74
76
|
t = t.replace(/@\S+/g, " ").replace(/[^\p{L}\p{N}\s']/gu, " ").replace(/\s+/g, " ").trim();
|