owlmem 0.9.22 → 0.9.23
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/owlmem.mjs +218 -2
- package/package.json +1 -1
package/owlmem.mjs
CHANGED
|
@@ -42,8 +42,9 @@ import { homedir, hostname, userInfo } from "node:os";
|
|
|
42
42
|
import { join, dirname, basename, relative, isAbsolute } from "node:path";
|
|
43
43
|
import { fileURLToPath } from "node:url";
|
|
44
44
|
import { spawn, spawnSync } from "node:child_process";
|
|
45
|
+
import { createConnection } from "node:net";
|
|
45
46
|
|
|
46
|
-
export const VERSION = "0.9.
|
|
47
|
+
export const VERSION = "0.9.23";
|
|
47
48
|
const BASE = (process.env.OWLMEM_URL || "https://owlmem.com").replace(/\/$/, "");
|
|
48
49
|
const DIR = process.env.OWLMEM_HOME || join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "owlmem");
|
|
49
50
|
const enc = new TextEncoder(), dec = new TextDecoder();
|
|
@@ -1307,9 +1308,224 @@ const OUTSIDE_FULL_NOTE = `This came from outside the team (an alert source, the
|
|
|
1307
1308
|
// only the wording is about the outside case).
|
|
1308
1309
|
const limitedNote = (task) => (task.trust === TRUST_FULL ? (task.external ? OUTSIDE_FULL_NOTE : "") : EXTERNAL_NOTE);
|
|
1309
1310
|
|
|
1311
|
+
// ── foreground delivery (#1809/#1815): hand the job to a live foreground session first ──
|
|
1312
|
+
// When the wake program has a job for an AI, it first tries that AI's configured foreground delivery
|
|
1313
|
+
// methods, in order; the first method that succeeds counts as delivered and no headless session is
|
|
1314
|
+
// started. Only when every configured method fails does it fall back to starting a headless session
|
|
1315
|
+
// as before (and the failure is logged, one line in wake.log). Only full-trust jobs go to the
|
|
1316
|
+
// foreground: a job from outside the team is never relayed into a session that can do more than look
|
|
1317
|
+
// (same boundary as the in-prompt relay in foregroundFirst below).
|
|
1318
|
+
//
|
|
1319
|
+
// Two methods, both generic (not tied to any one CLI):
|
|
1320
|
+
// - {type: "claude-socket"}: deliver into the newest live Claude Code session on this machine, over
|
|
1321
|
+
// its cross-session-messaging socket (Claude Code 2.1.224+; the socket file name is the pid).
|
|
1322
|
+
// Implemented from Anthropic's public docs (code.claude.com/docs/en/cross-session-messaging) and
|
|
1323
|
+
// the socket protocol as shipped in Claude Code 2.1.325: each session registers in
|
|
1324
|
+
// ~/.claude/sessions/<pid>.json (messagingSocketPath) and takes newline-delimited JSON on its
|
|
1325
|
+
// socket — an optional {"type":"auth","token":"<peerToken>"} first line (the token lives in
|
|
1326
|
+
// ~/.claude/sessions/<pid>.<sha256(socket path)>.key), then one {"msgV":1,"msg_id":...,
|
|
1327
|
+
// "type":"user","message":{"role":"user","content":"<cross-session-message ...>...</cross-session-message>"},
|
|
1328
|
+
// "priority":"next"} line. The reference implementation (vpn-vps configs/ori/owlmem-fg-wake.py)
|
|
1329
|
+
// was not reachable from the machine this was built on, so this is a from-docs reimplementation;
|
|
1330
|
+
// live delivery on ori is still to be verified. A socket accept is "delivered" as far as this
|
|
1331
|
+
// program can tell: the session may still hold the message for approval when its
|
|
1332
|
+
// crossSessionInbound is not "accept" (see the docs). There is no SessionStart-hook registration
|
|
1333
|
+
// (#1809's original design): nothing is written when a session starts, sessions are found by
|
|
1334
|
+
// reading the registry Claude Code itself keeps. The registry directory is injectable
|
|
1335
|
+
// (OWLMEM_CLAUDE_SESSIONS_DIR, or CLAUDE_CONFIG_DIR); under the test suite the default is
|
|
1336
|
+
// refused, so tests can only ever read a directory they injected themselves (#1863).
|
|
1337
|
+
// - {type: "command", command: "..."}: run an arbitrary command (through the system shell) with the
|
|
1338
|
+
// wake note on stdin; exit code 0 means delivered, anything else means failed (try the next method).
|
|
1339
|
+
// Configuration lives in wake.json, per client: clients.<id>.foreground is an ordered list of methods.
|
|
1340
|
+
// Defaults: claude-code gets [{type: "claude-socket"}], every other client gets none (headless as
|
|
1341
|
+
// today). An explicit empty list turns foreground delivery off for that client.
|
|
1342
|
+
export const FOREGROUND_SOCKET_TIMEOUT_MS = 5000;
|
|
1343
|
+
export const FOREGROUND_COMMAND_TIMEOUT_MS = 30000;
|
|
1344
|
+
function validForegroundMethod(m) {
|
|
1345
|
+
if (!m || typeof m !== "object" || Array.isArray(m)) return false;
|
|
1346
|
+
if (m.type === "claude-socket") return true;
|
|
1347
|
+
if (m.type === "command" && typeof m.command === "string" && m.command.trim()) return true;
|
|
1348
|
+
return false;
|
|
1349
|
+
}
|
|
1350
|
+
export function foregroundMethods(client, cfg = {}) {
|
|
1351
|
+
const entry = ((cfg.clients || {})[client] || {}).foreground;
|
|
1352
|
+
if (Array.isArray(entry)) return entry.filter(validForegroundMethod);
|
|
1353
|
+
if (client === "claude-code") return [{ type: "claude-socket" }];
|
|
1354
|
+
return [];
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
// Short wake note for a foreground session: what arrived, and to read it with kb_inbox (that marks it
|
|
1358
|
+
// read). Not the full payload — the session reads the rest itself.
|
|
1359
|
+
export function foregroundNote(task, o = {}) {
|
|
1360
|
+
const mins = o.timeout_min || WAKE_DEFAULTS.timeout_min;
|
|
1361
|
+
if (isReply(task)) {
|
|
1362
|
+
const done = task.result === "done";
|
|
1363
|
+
if (task.zh) return `奥麦自动唤醒:回信 #${task.id}——你派的任务 #${task.task_id}「${task.task_title || ""}」有了结果:${shortName(task.by)}${done ? "完成" : "拒绝"}了。用 kb_inbox 看这封回信(会标成已读);需要接着做(换人派、把结果告诉站长、自己补做)就做,没有要做的就结束,不要发消息。`;
|
|
1364
|
+
return `OwlMem auto-wake: reply #${task.id} — the task you gave out, #${task.task_id} "${task.task_title || ""}", was ${done ? "finished" : "declined"} by ${shortName(task.by)}. Read it with kb_inbox (that marks it read); if something needs doing next, do it, otherwise just end and don't send any message.`;
|
|
1365
|
+
}
|
|
1366
|
+
if (isNote(task)) {
|
|
1367
|
+
if (task.zh) return `奥麦自动唤醒:留言 #${task.id}——${shortName(task.from)}:${task.title}。用 kb_inbox 看这条留言(会标成已读);要你做事就做完、用 kb_send 回结果,不用做就结束,不要发消息。`;
|
|
1368
|
+
return `OwlMem auto-wake: note #${task.id} from ${shortName(task.from)}: ${task.title}. Read it with kb_inbox (that marks it read); if it asks you to do something, do it and report back with kb_send, otherwise just end and don't send a message.`;
|
|
1369
|
+
}
|
|
1370
|
+
if (task.zh) return `奥麦自动唤醒:任务 #${task.id}「${task.title}」等你处理(${shortName(task.from)}派来)。用 kb_task_update 接(doing),做完标 done、做不了标 declined,结果写进 note。你有 ${mins} 分钟。`;
|
|
1371
|
+
return `OwlMem auto-wake: task #${task.id} "${task.title}" is waiting for you (from ${shortName(task.from)}). Take it with kb_task_update (doing), mark it done when finished or declined if you can't, with the result in the note. You have ${mins} minutes.`;
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
// Claude Code sessions on this machine, most recently active first: ~/.claude/sessions/<pid>.json
|
|
1375
|
+
// carries messagingSocketPath (and updatedAt). A record whose pid is gone, or whose socket is gone,
|
|
1376
|
+
// is stale and skipped. The directory is injectable: OWLMEM_CLAUDE_SESSIONS_DIR wins, then
|
|
1377
|
+
// CLAUDE_CONFIG_DIR (its sessions/ subdir), then <home>/.claude/sessions. home_ is injectable for
|
|
1378
|
+
// tests. Under the test suite (OWLMEM_TEST, set by cli/owlmem.test.mjs, or NODE_ENV=test) the
|
|
1379
|
+
// default is refused and null is returned: without an injected directory there is no registry to
|
|
1380
|
+
// read, so a test can never reach a real session by accident (#1863 — a test once delivered a fake
|
|
1381
|
+
// wake note into a live session on ori because an old runTask test called without home/sessionsDir).
|
|
1382
|
+
export function claudeSessionsDir(home_ = home()) {
|
|
1383
|
+
if (process.env.OWLMEM_CLAUDE_SESSIONS_DIR) return process.env.OWLMEM_CLAUDE_SESSIONS_DIR;
|
|
1384
|
+
if (process.env.CLAUDE_CONFIG_DIR) return join(process.env.CLAUDE_CONFIG_DIR, "sessions");
|
|
1385
|
+
if (process.env.OWLMEM_TEST || process.env.NODE_ENV === "test") return null;
|
|
1386
|
+
return join(home_, ".claude", "sessions");
|
|
1387
|
+
}
|
|
1388
|
+
const alivePid = (pid, o = {}) => {
|
|
1389
|
+
if (o.alive) return o.alive(pid);
|
|
1390
|
+
try { process.kill(pid, 0); return true; }
|
|
1391
|
+
catch (e) { return e?.code === "EPERM"; } // exists, but not ours
|
|
1392
|
+
};
|
|
1393
|
+
export function listClaudeSessions(o = {}) {
|
|
1394
|
+
const dir = o.sessionsDir || claudeSessionsDir(o.home);
|
|
1395
|
+
if (!dir) return []; // test suite without an injected directory: no registry, never the real one
|
|
1396
|
+
let names;
|
|
1397
|
+
try { names = readdirSync(dir); } catch { return []; }
|
|
1398
|
+
const out = [];
|
|
1399
|
+
for (const name of names) {
|
|
1400
|
+
if (!/^\d+\.json$/.test(name)) continue;
|
|
1401
|
+
let rec;
|
|
1402
|
+
try { rec = JSON.parse(readFileSync(join(dir, name), "utf8")); } catch { continue; }
|
|
1403
|
+
const sock = typeof rec.messagingSocketPath === "string" ? rec.messagingSocketPath : "";
|
|
1404
|
+
if (!sock || !existsSync(sock)) continue;
|
|
1405
|
+
const pid = Number(name.slice(0, -5));
|
|
1406
|
+
if (!pid || !alivePid(pid, o)) continue;
|
|
1407
|
+
let mtime = 0;
|
|
1408
|
+
try { mtime = statSync(sock).mtimeMs; } catch {}
|
|
1409
|
+
out.push({ pid, sock, name: typeof rec.name === "string" ? rec.name : "", updatedAt: Number(rec.updatedAt) || 0, mtime });
|
|
1410
|
+
}
|
|
1411
|
+
out.sort((a, b) => (b.updatedAt - a.updatedAt) || (b.mtime - a.mtime) || (b.pid - a.pid));
|
|
1412
|
+
return out;
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
// The session's peer token: ~/.claude/sessions/<pid>.<sha256(canonical socket path)>.key,
|
|
1416
|
+
// JSON {peerToken: "<32 hex>"}. Without it the message still arrives on Linux, but a session in
|
|
1417
|
+
// bypass-permissions mode holds it for approval instead of delivering it — so send it when present.
|
|
1418
|
+
export function claudeSocketToken(sock, o = {}) {
|
|
1419
|
+
const dir = o.sessionsDir || claudeSessionsDir(o.home);
|
|
1420
|
+
if (!dir) return null; // test suite without an injected directory: no registry, never the real one
|
|
1421
|
+
let canon = sock;
|
|
1422
|
+
try { canon = realpathSync(sock); } catch {}
|
|
1423
|
+
const hash = createHash("sha256").update(canon).digest("hex");
|
|
1424
|
+
let names;
|
|
1425
|
+
try { names = readdirSync(dir); } catch { return null; }
|
|
1426
|
+
const pid = basename(sock).replace(/\.sock$/, "");
|
|
1427
|
+
const cands = names.filter((n) => n.endsWith("." + hash + ".key"))
|
|
1428
|
+
.sort((a, b) => (b.startsWith(pid + ".") ? 1 : 0) - (a.startsWith(pid + ".") ? 1 : 0)); // the session's own key first
|
|
1429
|
+
for (const n of cands) {
|
|
1430
|
+
try {
|
|
1431
|
+
const tok = JSON.parse(readFileSync(join(dir, n), "utf8")).peerToken;
|
|
1432
|
+
if (typeof tok === "string" && /^[0-9a-f]{32}$/.test(tok)) return tok;
|
|
1433
|
+
} catch {}
|
|
1434
|
+
}
|
|
1435
|
+
return null;
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
// Escape the one tag the receiving session parses, so job text can't forge a cross-session wrapper.
|
|
1439
|
+
const escapeCrossSession = (s) => String(s).replace(/<\/?cross-session-message/g, (m) => "<\\" + m.slice(1));
|
|
1440
|
+
export function claudeSocketFrame(text, o = {}) {
|
|
1441
|
+
const name = String(o.fromName || "owlmem-wake").replace(/["<>\n\r]/g, "");
|
|
1442
|
+
const content = `<cross-session-message${name ? ` from-name="${name}"` : ""}>\n${escapeCrossSession(text)}\n</cross-session-message>`;
|
|
1443
|
+
return { msgV: 1, msg_id: crypto.randomUUID(), type: "user", message: { role: "user", content }, priority: "next" };
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
// One JSON-lines message into a Claude Code inbox socket: optional auth line, then the message line,
|
|
1447
|
+
// then half-close; the session closes the connection once it took the lines. "Delivered" here means
|
|
1448
|
+
// the socket took it — a held message (crossSessionInbound is not "accept") is still reported sent.
|
|
1449
|
+
export async function sendClaudeSocket(sock, text, o = {}) {
|
|
1450
|
+
const token = o.token !== undefined ? o.token : claudeSocketToken(sock, o);
|
|
1451
|
+
const frame = claudeSocketFrame(text, o);
|
|
1452
|
+
const lines = (token ? JSON.stringify({ type: "auth", token }) + "\n" : "") + JSON.stringify(frame) + "\n";
|
|
1453
|
+
const timeoutMs = o.timeoutMs ?? FOREGROUND_SOCKET_TIMEOUT_MS;
|
|
1454
|
+
return new Promise((res) => {
|
|
1455
|
+
let done = false;
|
|
1456
|
+
const finish = (r) => { if (!done) { done = true; res(r); } };
|
|
1457
|
+
let s;
|
|
1458
|
+
try { s = createConnection({ path: sock }); } catch (e) { finish({ ok: false, detail: e.message }); return; }
|
|
1459
|
+
const timer = setTimeout(() => { try { s.destroy(); } catch {} finish({ ok: false, detail: "timed out after " + timeoutMs + " ms" }); }, timeoutMs);
|
|
1460
|
+
timer.unref?.();
|
|
1461
|
+
s.on("error", (e) => { clearTimeout(timer); finish({ ok: false, detail: (e.code === "ENOENT" || e.code === "ECONNREFUSED") ? "no session at " + sock + " (" + e.code + ")" : e.message }); });
|
|
1462
|
+
s.on("close", () => { clearTimeout(timer); finish({ ok: true }); });
|
|
1463
|
+
s.on("connect", () => { s.end(lines); });
|
|
1464
|
+
});
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
// claude-socket: newest live session first, then the next if that socket won't take it.
|
|
1468
|
+
export async function deliverClaudeSocket(note, o = {}) {
|
|
1469
|
+
const sessions = listClaudeSessions(o);
|
|
1470
|
+
if (!sessions.length) return { ok: false, detail: "no live Claude Code session on this computer" };
|
|
1471
|
+
const tried = [];
|
|
1472
|
+
for (const s of sessions) {
|
|
1473
|
+
const r = await sendClaudeSocket(s.sock, note, o);
|
|
1474
|
+
if (r.ok) return { ok: true, detail: "Claude Code session " + (s.name || s.pid) };
|
|
1475
|
+
tried.push((s.name || s.pid) + ": " + r.detail);
|
|
1476
|
+
}
|
|
1477
|
+
return { ok: false, detail: tried.join("; ") };
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
// command: the configured command runs through the system shell with the note on stdin; exit 0 = delivered.
|
|
1481
|
+
export async function runForegroundCommand(method, text, o = {}) {
|
|
1482
|
+
const timeoutMs = o.timeoutMs ?? FOREGROUND_COMMAND_TIMEOUT_MS;
|
|
1483
|
+
const win = (o.platform || platform()) === "win32";
|
|
1484
|
+
return new Promise((res) => {
|
|
1485
|
+
let done = false;
|
|
1486
|
+
const finish = (r) => { if (!done) { done = true; res(r); } };
|
|
1487
|
+
let ch;
|
|
1488
|
+
try { ch = spawn(method.command, { shell: true, stdio: ["pipe", "ignore", "ignore"], windowsHide: true, detached: !win }); }
|
|
1489
|
+
catch (e) { finish({ ok: false, detail: "couldn't start: " + e.message }); return; }
|
|
1490
|
+
// Timeout kills the whole process group, not just the shell: a command that spawned a child
|
|
1491
|
+
// must not outlive the timeout and deliver late — the timeout already moved on to the next
|
|
1492
|
+
// method / headless, so a late delivery would deliver twice (#1870). Windows: taskkill /T
|
|
1493
|
+
// takes the tree. Same kill as the headless session in runTask below.
|
|
1494
|
+
const kill = (sig) => { try { if (win) spawnSync("taskkill", ["/T", "/F", "/PID", String(ch.pid)]); else process.kill(-ch.pid, sig); } catch { try { ch.kill(sig); } catch {} } };
|
|
1495
|
+
const timer = setTimeout(() => { kill("SIGKILL"); finish({ ok: false, detail: "timed out after " + timeoutMs + " ms" }); }, timeoutMs);
|
|
1496
|
+
timer.unref?.();
|
|
1497
|
+
ch.on("error", (e) => { clearTimeout(timer); finish({ ok: false, detail: e.message }); });
|
|
1498
|
+
ch.on("close", (code) => { clearTimeout(timer); finish(code === 0 ? { ok: true } : { ok: false, detail: "exit code " + (code ?? "signal") }); });
|
|
1499
|
+
ch.stdin.on("error", () => {});
|
|
1500
|
+
ch.stdin.end(text);
|
|
1501
|
+
});
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
// Try the configured foreground methods in order; the first success counts as delivered.
|
|
1505
|
+
export async function deliverForeground(task, cfg, o = {}) {
|
|
1506
|
+
const note = o.note ?? foregroundNote(task, { timeout_min: cfg.timeout_min });
|
|
1507
|
+
const tried = [];
|
|
1508
|
+
for (const m of foregroundMethods(task.client, cfg)) {
|
|
1509
|
+
const r = m.type === "claude-socket" ? await deliverClaudeSocket(note, o) : await runForegroundCommand(m, note, o);
|
|
1510
|
+
if (r.ok) return { ok: true, method: m.type, detail: r.detail || "" };
|
|
1511
|
+
tried.push(m.type + ": " + (r.detail || "failed"));
|
|
1512
|
+
}
|
|
1513
|
+
return { ok: false, detail: tried.join("; ") || "no foreground method configured" };
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1310
1516
|
// ── running a task ──
|
|
1311
1517
|
export async function runTask(task, cfg, o = {}) {
|
|
1312
1518
|
const dir = o.dir || DIR, cl = (cfg.clients || {})[task.client];
|
|
1519
|
+
const log = o.log || (() => {});
|
|
1520
|
+
if (task.trust === TRUST_FULL) { // full trust only: outside work is never relayed into a foreground session
|
|
1521
|
+
const methods = foregroundMethods(task.client, cfg);
|
|
1522
|
+
if (task.foreground_tried) log("Foreground delivery was already tried for " + jobLabel(task) + "; starting a headless session."); // #1870:前台送过一次没接,这次直接无头
|
|
1523
|
+
else if (methods.length) {
|
|
1524
|
+
const d = await deliverForeground(task, cfg, o);
|
|
1525
|
+
if (d.ok) return { outcome: "foreground", detail: "delivered to the foreground (" + d.method + (d.detail ? ": " + d.detail : "") + ")" };
|
|
1526
|
+
log("Foreground delivery failed for " + jobLabel(task) + " (" + d.detail + "); starting a headless session.");
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1313
1529
|
if (!cl || !Array.isArray(cl.command) || !cl.command.length) return { outcome: "error", detail: "no command for " + task.client + " on this computer (wake.json)" };
|
|
1314
1530
|
let place;
|
|
1315
1531
|
try { const plan = o.plan || planWorkdir(task, o.home || home(), o.git); place = prepareWorkdir(task, plan, dir, o.git); if (plan.kind === "scratch") place.scratch = true; }
|
|
@@ -1808,7 +2024,7 @@ async function wakeRun() {
|
|
|
1808
2024
|
await new Promise((ok) => setTimeout(ok, 5000 * (i + 1)));
|
|
1809
2025
|
}
|
|
1810
2026
|
};
|
|
1811
|
-
const sched = new Scheduler({ max: cfg.max_parallel || WAKE_DEFAULTS.max_parallel, start: (j) => runTask(j.task, cfg, { plan: j.plan }), onDone: (j, res) => { report(j, res); } });
|
|
2027
|
+
const sched = new Scheduler({ max: cfg.max_parallel || WAKE_DEFAULTS.max_parallel, start: (j) => runTask(j.task, cfg, { plan: j.plan, log }), onDone: (j, res) => { report(j, res); } });
|
|
1812
2028
|
log("OwlMem auto-wake " + VERSION + " running on " + (cfg.machine || hostname()) + ".");
|
|
1813
2029
|
const usage = () => usageTick(cfg, api, log).catch((e) => log("usage: " + e.message));
|
|
1814
2030
|
setTimeout(usage, 30000).unref(); setInterval(usage, USAGE_EVERY).unref();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "owlmem",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.23",
|
|
4
4
|
"description": "OwlMem command line: connect your AI apps to OwlMem in one command (npx -y owlmem install), an end-to-end encrypted vault for your AI agents, and a local MCP server.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": { "owlmem": "owlmem.mjs" },
|