owlmem 0.7.6 → 0.7.7

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.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/owlmem.mjs +119 -11
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -29,7 +29,7 @@ page, where you sign in and click **Allow**. AI agents can read the setup guide
29
29
 
30
30
  An AI on your computer normally sees a task only when someone opens it. Auto-wake starts it as soon as it gets one:
31
31
  a small background program long-polls OwlMem and runs that AI's command line unattended — Claude Code with
32
- `claude -p`, Codex with `codex exec`, Antigravity with `agy -p`, Hermes with `hermes -z` (for Codex and Antigravity, which refuse tool calls when nobody is watching, auto-wake approves just the two OwlMem tools used to report back: in `~/.codex/config.toml` and `~/.gemini/antigravity-cli/settings.json`; for Hermes, only if OwlMem is marked `trust: untrusted`, under `command_allowlist` in `~/.hermes/config.yaml`) — with the task as the prompt. The AI marks the task done or declined as usual.
32
+ `claude -p`, Codex with `codex exec`, Antigravity with `agy -p`, Hermes with `hermes -z` (for Codex and Antigravity, which refuse tool calls when nobody is watching, auto-wake approves just the two OwlMem tools used to report back: in `~/.codex/config.toml` and `~/.gemini/antigravity-cli/settings.json`; for Hermes, only if OwlMem is marked `trust: untrusted`, under `command_allowlist` in `~/.hermes/config.yaml`) — with the task as the prompt. The AI marks the task done or declined as usual. When a task it gave out is done or declined, it is woken too, to read the result. The program updates itself (from npm, when nothing is running).
33
33
 
34
34
  When someone turns auto-wake on for an AI in the console and no computer runs it yet, that AI is told so the next time it connects:
35
35
  with your OK it runs `npx -y owlmem wake enable` itself and sends you the pairing link to approve.
package/owlmem.mjs CHANGED
@@ -33,14 +33,15 @@
33
33
  // a command (`owlmem run`, vault_run) or is shown (`vault get`, vault_get). A token copied to another machine has no
34
34
  // device key there, so standing grants don't apply. Viewing, writing, deleting and exporting always need approval.
35
35
 
36
- import { webcrypto as crypto } from "node:crypto";
37
- import { readFileSync, writeFileSync, mkdirSync, existsSync, chmodSync, copyFileSync, rmSync, statSync, realpathSync, openSync, closeSync, appendFileSync } from "node:fs";
36
+ import { webcrypto as crypto, createHash } from "node:crypto";
37
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, chmodSync, copyFileSync, rmSync, statSync, realpathSync, openSync, closeSync, appendFileSync, renameSync } from "node:fs";
38
+ import { gunzipSync } from "node:zlib";
38
39
  import { homedir, hostname, userInfo } from "node:os";
39
40
  import { join, dirname, basename, relative, isAbsolute } from "node:path";
40
41
  import { fileURLToPath } from "node:url";
41
42
  import { spawn, spawnSync } from "node:child_process";
42
43
 
43
- export const VERSION = "0.7.6";
44
+ export const VERSION = "0.7.7";
44
45
  const BASE = (process.env.OWLMEM_URL || "https://owlmem.com").replace(/\/$/, "");
45
46
  const DIR = process.env.OWLMEM_HOME || join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "owlmem");
46
47
  const enc = new TextEncoder(), dec = new TextDecoder();
@@ -797,7 +798,8 @@ function nextSteps(items, out) {
797
798
  // logon task) long-polls OwlMem. When an agent paired with this computer gets a task, it runs that agent's command line
798
799
  // unattended (`claude -p`, `codex exec`) with the task as the prompt. The woken AI uses its own OwlMem connection (the one
799
800
  // `owlmem install` set up), so it acts as itself. It gets no extra permissions: no --dangerously-* flags; anything that
800
- // needs a person, it declines with what the person has to do.
801
+ // needs a person, it declines with what the person has to do. When a task the agent gave out is done or declined, it is
802
+ // woken too, to read the result (OwlMem sends those only to 0.7.7 and later).
801
803
  // This computer is identified by its device key (device.json); the pairing is approved in the console, where each AI has an
802
804
  // auto-wake switch and the computer can be removed. If OwlMem answers 401 (computer removed, AI disconnected, account gone)
803
805
  // the program removes its own autostart entry and exits.
@@ -1056,7 +1058,7 @@ export function planWorkdir(task, h = home(), git = gitRun) {
1056
1058
  }
1057
1059
  export function prepareWorkdir(task, plan, dir = DIR, git = gitRun) {
1058
1060
  if (plan.kind === "missing") throw new Fail("the task's directory doesn't exist on this computer: " + plan.dir);
1059
- if (plan.kind === "scratch") { const cwd = join(wakeDir(dir), "scratch", "task-" + task.id); mkdirSync(cwd, { recursive: true }); return { cwd }; }
1061
+ if (plan.kind === "scratch") { const cwd = join(wakeDir(dir), "scratch", jobName(task)); mkdirSync(cwd, { recursive: true }); return { cwd }; }
1060
1062
  if (plan.kind === "dir") return { cwd: plan.dir };
1061
1063
  const branch = "owlmem/task-" + task.id, wt = join(wakeDir(dir), "worktrees", basename(plan.top) + "-task-" + task.id);
1062
1064
  if (!existsSync(wt)) {
@@ -1069,7 +1071,33 @@ export function prepareWorkdir(task, plan, dir = DIR, git = gitRun) {
1069
1071
  return { cwd: rel ? join(wt, rel) : wt, worktree: wt, branch, repo: plan.top };
1070
1072
  }
1071
1073
 
1074
+ // A job from OwlMem is a task given to this AI (type "task"), or the result of a task this AI gave someone else (type "reply":
1075
+ // the automatic note sent when that task was done or declined). Older OwlMem servers send no type: a task.
1076
+ const isReply = (t) => t?.type === "reply";
1077
+ const jobName = (t) => (isReply(t) ? "reply-" : "task-") + t.id;
1078
+ const shortName = (who) => { who = String(who || ""); return who.startsWith("user:") ? who.slice(5) : who.includes("/") ? who.split("/").slice(1).join("/") : who; };
1079
+
1080
+ // Woken for a reply: read it (kb_inbox marks it read; that's how OwlMem knows it was handled), act on it only if needed.
1081
+ export function replyPrompt(r, o = {}) {
1082
+ const by = shortName(r.by), done = r.result === "done", note = String(r.note || "").trim(), mins = o.timeout_min || WAKE_DEFAULTS.timeout_min;
1083
+ if (r.zh) return `奥麦自动唤醒在 ${o.machine || "这台电脑"} 上启动了你(${r.agent})。没有人在看这个会话,也没人能回答问题。
1084
+
1085
+ 你派的任务 #${r.task_id}「${r.task_title || ""}」有了结果:${by} ${done ? "完成" : "拒绝"}了,${done ? "结果" : "原因"}:${note || "(没写)"}
1086
+
1087
+ 先用 kb_inbox 看这封回信(#${r.id},会标成已读);需要接着做(换人派、把结果告诉站长、自己补做)就做;没有要做的就直接结束,不要发任何消息。
1088
+ 不要把密码、令牌、密钥写进任何消息。你有 ${mins} 分钟。
1089
+ `;
1090
+ return `OwlMem auto-wake started you (${r.agent}) on ${o.machine || "this computer"}. Nobody is watching this session and nobody can answer questions.
1091
+
1092
+ The task you gave out, #${r.task_id} "${r.task_title || ""}", has a result: ${by} ${done ? "finished it" : "declined it"}. ${done ? "Result" : "Reason"}: ${note || "(none given)"}
1093
+
1094
+ First read this reply with kb_inbox (#${r.id}; that marks it read). If something needs doing next (hand it to someone else, tell your user the result, do it yourself), do it. If nothing does, just end here and don't send any message.
1095
+ Never put passwords, tokens, keys or other secrets in any message. You have ${mins} minutes.
1096
+ `;
1097
+ }
1098
+
1072
1099
  export function wakePrompt(task, place, o = {}) {
1100
+ if (isReply(task)) return replyPrompt(task, o);
1073
1101
  const id = task.id, mins = o.timeout_min || WAKE_DEFAULTS.timeout_min;
1074
1102
  const where = place.worktree
1075
1103
  ? `Work in ${place.cwd}. It is a separate git worktree of ${place.repo} on the branch ${place.branch}, made for this task so it doesn't collide with other work. Commit your changes on this branch only. Don't merge, rebase or push other branches, and don't touch ${place.repo} itself. Put the branch name in your result so a person can review and merge it.`
@@ -1102,7 +1130,7 @@ export async function runTask(task, cfg, o = {}) {
1102
1130
  const prompt = wakePrompt(task, place, { machine: cfg.machine, timeout_min: cfg.timeout_min });
1103
1131
  const argv = [...cl.command, ...(cl.prompt === "arg" ? [prompt] : [])];
1104
1132
  mkdirSync(join(wakeDir(dir), "logs"), { recursive: true });
1105
- const logPath = join(wakeDir(dir), "logs", "task-" + task.id + ".log");
1133
+ const logPath = join(wakeDir(dir), "logs", jobName(task) + ".log");
1106
1134
  const fd = openSync(logPath, "a");
1107
1135
  const win = (o.platform || platform()) === "win32";
1108
1136
  const ms = o.timeoutMs ?? (cfg.timeout_min || WAKE_DEFAULTS.timeout_min) * 60000;
@@ -1111,7 +1139,7 @@ export async function runTask(task, cfg, o = {}) {
1111
1139
  let ch, timedOut = false, killer = null;
1112
1140
  try {
1113
1141
  ch = spawn(argv[0], argv.slice(1), { cwd: place.cwd, stdio: ["pipe", fd, fd], detached: !win, shell: win, windowsHide: true,
1114
- env: { ...process.env, OWLMEM_NO_BROWSER: "1", OWLMEM_WAKE_TASK: String(task.id) } });
1142
+ env: { ...process.env, OWLMEM_NO_BROWSER: "1", [isReply(task) ? "OWLMEM_WAKE_REPLY" : "OWLMEM_WAKE_TASK"]: String(task.id) } });
1115
1143
  } catch (e) { res({ outcome: "error", detail: "couldn't start " + argv[0] + ": " + e.message }); return; }
1116
1144
  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 {} } };
1117
1145
  const timer = setTimeout(() => { timedOut = true; kill("SIGTERM"); killer = setTimeout(() => kill("SIGKILL"), 10000); }, ms);
@@ -1168,15 +1196,93 @@ export async function wakeLoop(o) {
1168
1196
  }
1169
1197
  backoff = 0;
1170
1198
  for (const t of r.data.tasks || []) {
1171
- const plan = o.plan ? o.plan(t) : planWorkdir(t);
1172
- log("Task #" + t.id + " for " + t.agent + ": starting " + t.client + (plan.dir ? " in " + plan.dir : "") + ".");
1199
+ const plan = isReply(t) ? { kind: "scratch" } : o.plan ? o.plan(t) : planWorkdir(t); // a reply is read in an empty folder
1200
+ log((isReply(t) ? "Reply #" + t.id + " (task #" + t.task_id + ")" : "Task #" + t.id) + " for " + t.agent + ": starting " + t.client + (plan.dir ? " in " + plan.dir : "") + ".");
1173
1201
  sched.add({ id: t.id, agent: t.agent, lock: plan.lock || null, task: t, plan });
1174
1202
  }
1203
+ // OwlMem says a newer version is out: update only while nothing runs or waits (no task is cut off), then restart
1204
+ if (o.update && newer(r.data.latest, VERSION) && !(r.data.tasks || []).length && sched.size === 0) {
1205
+ if ((await o.update(r.data.latest)) === "restart") return "updated";
1206
+ }
1175
1207
  if (once) return r.data.status;
1176
1208
  if (Date.now() - t0 < 1000 && !(r.data.tasks || []).length) await sleep(1000); // never spin
1177
1209
  }
1178
1210
  }
1179
1211
 
1212
+ // ── auto-wake updates itself ──
1213
+ // The program runs its own copy (wake/owlmem.mjs). When OwlMem's poll answer names a newer version (latest), and nothing is
1214
+ // running: download that version's package from the npm registry, check it against the registry's sha512, take owlmem.mjs
1215
+ // out of it, check that it runs and says it is that version, then swap it in (rename in the same folder, so it's all or
1216
+ // nothing) and restart. If anything fails the old copy keeps running, and that version isn't tried again for 24 hours.
1217
+ // Restart: on Linux and macOS the program exits with WAKE_RESTART_CODE; the systemd unit (Restart=on-failure) and the
1218
+ // LaunchAgent (KeepAlive unless the exit was successful) start it again 30 s later. On Windows nothing watches it, so it
1219
+ // starts the new copy itself (detached, like the logon launcher) and then exits.
1220
+ export const WAKE_RESTART_CODE = 75;
1221
+ const UPDATE_RETRY = 24 * 3600 * 1000;
1222
+ const REGISTRY = () => String(process.env.npm_config_registry || "https://registry.npmjs.org").replace(/\/+$/, "");
1223
+ export function newer(a, b) {
1224
+ const p = (v) => (/^\d+\.\d+\.\d+$/.test(String(v || "")) ? String(v).split(".").map(Number) : null);
1225
+ const x = p(a), y = p(b);
1226
+ if (!x || !y) return false;
1227
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
1228
+ return false;
1229
+ }
1230
+ // The one file we need from an npm package (.tgz): plain ustar, read in memory.
1231
+ export function tarFile(tgz, want = "package/owlmem.mjs") {
1232
+ const t = gunzipSync(tgz);
1233
+ for (let off = 0; off + 512 <= t.length;) {
1234
+ const h = t.subarray(off, off + 512);
1235
+ if (h.every((b) => b === 0)) break;
1236
+ const str = (a, b) => h.subarray(a, b).toString("utf8").replace(/\0.*$/s, "");
1237
+ const name = (str(345, 500) ? str(345, 500) + "/" : "") + str(0, 100), size = parseInt(str(124, 136).trim() || "0", 8), type = str(156, 157);
1238
+ if ((type === "0" || type === "") && name === want) return t.subarray(off + 512, off + 512 + size);
1239
+ off += 512 + Math.ceil(size / 512) * 512;
1240
+ }
1241
+ return null;
1242
+ }
1243
+ // → "restart" (new copy in place) | "skip" (tried that version less than 24 h ago) | "failed" (old copy stays)
1244
+ export async function wakeUpdate(latest, o = {}) {
1245
+ const dir = o.dir || DIR, log = o.log || (() => {}), now = o.now || Date.now, get = o.fetch || fetch;
1246
+ const wd = wakeDir(dir), state = join(wd, "update.json"), target = join(wd, "owlmem.mjs"), tmpFile = join(wd, "owlmem.update.mjs");
1247
+ let st = {}; try { st = JSON.parse(readFileSync(state, "utf8")); } catch {}
1248
+ if (st.version === latest && now() - (st.at || 0) < UPDATE_RETRY) return "skip";
1249
+ try { mkdirSync(wd, { recursive: true }); writeFileSync(state, JSON.stringify({ version: latest, at: now() }) + "\n"); } catch {}
1250
+ log("Updating auto-wake from " + VERSION + " to " + latest + ".");
1251
+ try {
1252
+ const meta = await get(REGISTRY() + "/owlmem/" + encodeURIComponent(latest), { signal: AbortSignal.timeout(60000) });
1253
+ if (!meta.ok) throw new Error("registry answered HTTP " + meta.status);
1254
+ const dist = (await meta.json())?.dist || {};
1255
+ const m = /^sha512-(.+)$/.exec(String(dist.integrity || ""));
1256
+ if (!dist.tarball || !m) throw new Error("the registry gave no package or checksum");
1257
+ const res = await get(dist.tarball, { signal: AbortSignal.timeout(120000) });
1258
+ if (!res.ok) throw new Error("download answered HTTP " + res.status);
1259
+ const tgz = Buffer.from(await res.arrayBuffer());
1260
+ if (createHash("sha512").update(tgz).digest("base64") !== m[1]) throw new Error("the download doesn't match the registry's checksum");
1261
+ const file = tarFile(tgz);
1262
+ if (!file) throw new Error("owlmem.mjs isn't in the package");
1263
+ writeFileSync(tmpFile, file);
1264
+ const check = (o.check || ((f) => { const r = spawnSync(process.execPath, [f, "--version"], { encoding: "utf8", timeout: 30000, env: { ...process.env, OWLMEM_NO_BROWSER: "1" } }); return (r.stdout || "").trim(); }))(tmpFile);
1265
+ if (check !== latest) throw new Error("the new copy says it is " + JSON.stringify(check) + ", not " + latest);
1266
+ renameSync(tmpFile, target);
1267
+ } catch (e) {
1268
+ rmSync(tmpFile, { force: true });
1269
+ log("Update to " + latest + " failed (" + (e?.message || e) + "); keeping " + VERSION + " and not trying " + latest + " again for 24 hours.");
1270
+ return "failed";
1271
+ }
1272
+ log("Updated auto-wake to " + latest + "; restarting.");
1273
+ return "restart";
1274
+ }
1275
+ // After an update: come back as the new copy (see above).
1276
+ export function wakeRestart(o = {}) {
1277
+ const p = o.platform || platform(), exit = o.exit || ((c) => process.exit(c));
1278
+ if (p === "win32") {
1279
+ const run = o.spawn || ((argv) => spawn(argv[0], argv.slice(1), { stdio: "ignore", detached: true, windowsHide: true, env: process.env }).on("error", () => {}).unref());
1280
+ run([process.execPath, join(wakeDir(o.dir || DIR), "owlmem.mjs"), "wake", "run"]);
1281
+ return exit(0);
1282
+ }
1283
+ return exit(WAKE_RESTART_CODE);
1284
+ }
1285
+
1180
1286
  function wakeApi() {
1181
1287
  return async (sub, body) => {
1182
1288
  const url = BASE + "/v1/wake/" + sub;
@@ -1204,7 +1310,7 @@ async function wakeRun() {
1204
1310
  if (!cfg) throw new Fail("Auto-wake isn't set up on this computer. Run: npx -y owlmem wake enable");
1205
1311
  const log = wakeLogger(), api = wakeApi();
1206
1312
  const report = async (j, res) => {
1207
- log("Task #" + j.id + ": " + res.outcome + (res.code != null ? " (exit code " + res.code + ")" : "") + (res.detail ? " — " + res.detail : ""));
1313
+ log((isReply(j.task) ? "Reply #" : "Task #") + j.id + ": " + res.outcome + (res.code != null ? " (exit code " + res.code + ")" : "") + (res.detail ? " — " + res.detail : ""));
1208
1314
  for (let i = 0; i < 5; i++) {
1209
1315
  const r = await api("report", { id: j.id, outcome: res.outcome, code: res.code ?? null, detail: res.detail || "" });
1210
1316
  if (r.status === 200 || r.status === 404 || r.status === 401) return;
@@ -1213,8 +1319,10 @@ async function wakeRun() {
1213
1319
  };
1214
1320
  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); } });
1215
1321
  log("OwlMem auto-wake " + VERSION + " running on " + (cfg.machine || hostname()) + ".");
1216
- const out = await wakeLoop({ cfg, api, sched, log, cleanup: () => { try { wakeUninstall(autostartOpts(), wakeRunCmd, true); } catch (e) { log("cleanup: " + e.message); } } });
1322
+ const out = await wakeLoop({ cfg, api, sched, log, update: (v) => wakeUpdate(v, { log }),
1323
+ cleanup: () => { try { wakeUninstall(autostartOpts(), wakeRunCmd, true); } catch (e) { log("cleanup: " + e.message); } } });
1217
1324
  if (out === "revoked") process.exit(0);
1325
+ if (out === "updated") wakeRestart();
1218
1326
  }
1219
1327
 
1220
1328
  // No command line auto-wake can start: tell OwlMem support which AI apps this computer has, so it can add them. Only the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "owlmem",
3
- "version": "0.7.6",
3
+ "version": "0.7.7",
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" },