@opennous/cli 0.16.0 → 0.17.1

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 CHANGED
@@ -1,5 +1,23 @@
1
1
  # @opennous/cli changelog
2
2
 
3
+ ## 0.17.1
4
+
5
+ ### Fixed: a sign-out or an outage no longer fails your reads
6
+
7
+ Signed out of Claude or Codex, or the model not answering: `runner` and `backfill` now wait instead
8
+ of marking every conversation unreadable, and tell you what to run. At your plan's limit they wait
9
+ until the reset time the limit message names, not a fixed 30 minutes (GET-1303).
10
+
11
+ ## 0.17.0
12
+
13
+ ### Added: `runner`, reading on your own plan all the time
14
+
15
+ `backfill` reads your history once. `runner` keeps going: it reads your new calls and email on your
16
+ own Claude or ChatGPT plan as they come in, with the same no-tools sandbox. `runner install` starts it
17
+ now and every time you log in (launchd on macOS, systemd on Linux); `runner status` and
18
+ `runner uninstall` check on it and remove it. When your plan hits its limit it waits and carries on
19
+ by itself. The app's Settings → Your plan shows it as connected (GET-1289).
20
+
3
21
  ## 0.16.0
4
22
 
5
23
  ### Added: your Intelligence report after `backfill`
package/README.md CHANGED
@@ -12,6 +12,17 @@ npx @opennous/cli@latest init
12
12
 
13
13
  Then tell your agent *"set up my Ownable workspace"* — it reads your project, finds your ICP (or drafts one), and syncs it. On self-host, add `--url https://api.yourdomain.com`.
14
14
 
15
+ ## Read on your own plan
16
+
17
+ Reading your calls and email runs on your own Claude Code or Codex plan, not on credits:
18
+
19
+ ```bash
20
+ npx @opennous/cli@latest backfill # your history, once
21
+ npx @opennous/cli@latest runner install # what's new, from now on; starts at login
22
+ ```
23
+
24
+ `runner status` says whether it's running, `runner uninstall` stops it. Settings → AI subscription in the app shows each runner and what's waiting to be read.
25
+
15
26
  ## Event tracking
16
27
 
17
28
  `nous track init` detects your stack (Next.js, Node, Python), writes a small `nous.js` (or `nous.py`) module with three helpers, and updates your `.env`:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opennous/cli",
3
- "version": "0.16.0",
3
+ "version": "0.17.1",
4
4
  "description": "Ownable CLI — set up Ownable, connect it to your coding agent, and read the Context API from your terminal",
5
5
  "type": "module",
6
6
  "bin": {
package/src/backfill.js CHANGED
@@ -53,14 +53,16 @@ export function parseAnswer(agent, out) {
53
53
  if (j.is_error) throw new Error(String(j.result));
54
54
  return { text: j.result, usage: { input_tokens: j.usage?.input_tokens ?? 0, output_tokens: j.usage?.output_tokens ?? 0 } };
55
55
  }
56
- let text = "", usage = null;
56
+ let text = "", usage = null, error = null;
57
57
  for (const line of out.split("\n")) {
58
58
  let e;
59
59
  try { e = JSON.parse(line); } catch { continue; }
60
60
  if (e.item?.type === "agent_message") text = e.item.text;
61
61
  if (e.usage) usage = e.usage;
62
+ // An error event says why (a limit, a sign-out), which the runner needs (GET-1303).
63
+ if (e.type === "error" || e.type === "turn.failed") error = e.message ?? e.error?.message ?? error;
62
64
  }
63
- if (!text) throw new Error("codex gave no answer");
65
+ if (!text) throw new Error(error || "codex gave no answer");
64
66
  return { text, usage: { input_tokens: usage?.input_tokens ?? 0, output_tokens: usage?.output_tokens ?? 0 } };
65
67
  }
66
68
 
@@ -69,6 +71,55 @@ export function isPlanLimit(message) {
69
71
  return /usage limit|rate.?limit|hit your .*limit|limit reached|too many requests|\b429\b|quota/i.test(String(message));
70
72
  }
71
73
 
74
+ /**
75
+ * What an error says about the plan, not the call (GET-1303): 'limit' (passes at its reset),
76
+ * 'signed_out' (passes when the person signs in again), 'outage' (the model is down; passes by
77
+ * itself), or null for a bad call. A call that fails for any of these is not unreadable, so it must
78
+ * not be marked failed. Pure.
79
+ */
80
+ export function troubleOf(message) {
81
+ const m = String(message ?? "");
82
+ if (isPlanLimit(m)) return "limit";
83
+ if (/not logged in|please (run )?\/?login|log ?in again|sign ?in again|invalid api key|authentication[_ ](error|failed)|oauth token|token (has )?expired|unauthori[sz]ed|\b401\b|codex login/i.test(m)) return "signed_out";
84
+ if (/overloaded|\b529\b|\b503\b|\b502\b|service unavailable|internal server error|api error: 5\d\d|econnreset|etimedout|enotfound|network error|socket hang up|stream disconnected/i.test(m)) return "outage";
85
+ return null;
86
+ }
87
+
88
+ const MIN_WAIT_MS = 60_000;
89
+ const MAX_WAIT_MS = 7 * 86_400_000;
90
+
91
+ /**
92
+ * When the plan's limit lifts, from its own message (GET-1303), or null when it doesn't say.
93
+ * Claude: "…limit reached|1731470400" or "resets 3pm" / "resets 3:30pm". Codex: "try again in 2 hours
94
+ * 5 minutes" or "try again at 3:04 PM". Clock times are this machine's local time, the next one to
95
+ * come. A minute is added, so the retry lands after the reset, not on it. Pure.
96
+ */
97
+ export function resetAt(message, now = Date.now()) {
98
+ const m = String(message ?? "");
99
+ const clamp = (t) => (Number.isFinite(t) && t > now ? Math.min(now + MAX_WAIT_MS, Math.max(now + MIN_WAIT_MS, t + 60_000)) : null);
100
+ const unix = /\|(\d{10})\b/.exec(m);
101
+ if (unix) return clamp(Number(unix[1]) * 1000);
102
+ const inMatch = /try again in\s+(?:(\d+)\s*d(?:ays?)?\s*)?(?:(\d+)\s*h(?:ours?|rs?)?\s*)?(?:(\d+)\s*m(?:in(?:utes?)?)?)?/i.exec(m);
103
+ if (inMatch && (inMatch[1] || inMatch[2] || inMatch[3])) {
104
+ const ms = ((+inMatch[1] || 0) * 24 * 60 + (+inMatch[2] || 0) * 60 + (+inMatch[3] || 0)) * 60_000;
105
+ return clamp(now + ms);
106
+ }
107
+ const clock = /(?:resets?|try again at)\s+(?:at\s+)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)?/i.exec(m);
108
+ if (clock) {
109
+ let h = Number(clock[1]);
110
+ const min = Number(clock[2] ?? 0);
111
+ const ap = clock[3]?.toLowerCase();
112
+ if (h > 23 || min > 59 || (ap && (h < 1 || h > 12))) return null;
113
+ if (ap === "pm" && h < 12) h += 12;
114
+ if (ap === "am" && h === 12) h = 0;
115
+ const d = new Date(now);
116
+ d.setHours(h, min, 0, 0);
117
+ if (d.getTime() <= now) d.setDate(d.getDate() + 1);
118
+ return clamp(d.getTime());
119
+ }
120
+ return null;
121
+ }
122
+
72
123
  export function detectAgents(run = spawnSync) {
73
124
  const found = [];
74
125
  if (run("claude", ["auth", "status"], { encoding: "utf8" }).status === 0) found.push("claude");
@@ -167,9 +218,19 @@ export async function runBackfill({ api, agent, jobId, run, sleep, log, now = Da
167
218
  answered++;
168
219
  return;
169
220
  } catch (err) {
170
- if (isPlanLimit(err.message)) {
171
- if (now() >= waitUntil) log(`Your ${agent} plan hit its limit. Waiting ${Math.round(limitWaitMs / 60000)} minutes, then carrying on. You can stop now and run this again later instead.`);
172
- waitUntil = Math.max(waitUntil, now() + limitWaitMs);
221
+ // A limit, a sign-out or an outage (GET-1303) is not this call's fault: wait, then try it again.
222
+ const trouble = troubleOf(err.message);
223
+ if (trouble) {
224
+ const until = trouble === "limit" ? (resetAt(err.message, now()) ?? now() + limitWaitMs) : now() + 5 * 60_000;
225
+ if (now() >= waitUntil) {
226
+ const mins = Math.max(1, Math.round((until - now()) / 60000));
227
+ log(trouble === "signed_out"
228
+ ? `You're signed out of ${agent}. Run \`${agent === "codex" ? "codex login" : "claude"}\` in another terminal and sign in; this carries on by itself.`
229
+ : trouble === "outage"
230
+ ? `${agent} isn't answering right now. Trying again in ${mins} minutes.`
231
+ : `Your ${agent} plan hit its limit. Waiting ${mins} minutes, until it resets, then carrying on. You can stop now and run this again later instead.`);
232
+ }
233
+ waitUntil = Math.max(waitUntil, until);
173
234
  continue;
174
235
  }
175
236
  if (attempt >= RETRIES) { await api.answer(call.id, { error: err.message }); return; }
package/src/index.js CHANGED
@@ -650,6 +650,118 @@ program
650
650
  if (reportUrl) console.log(`Your Intelligence report is ready: ${reportUrl}`);
651
651
  });
652
652
 
653
+ // `nous runner` (GET-1293): keeps reading your new calls and email on your own plan. `install`
654
+ // starts it at login; the app's "Your plan" page shows it as connected once it has polled.
655
+ const runnerCmd = program
656
+ .command("runner")
657
+ .description("Keep reading your new calls and email on your own Claude or ChatGPT plan")
658
+ .option("--agent <agent>", "claude or codex (default: whichever you're signed in to)")
659
+ .option("--workspace <id>", "the workspace to read; the app's command fills this in")
660
+ .option("--url <url>", "API base URL (default: https://api.opennous.cloud)")
661
+ .action(async (opts) => {
662
+ const { detectAgents, liveRun, NO_AGENT } = await import("./backfill.js");
663
+ const { runRunner } = await import("./runner.js");
664
+ const agent = await pickAgent(opts.agent, detectAgents, NO_AGENT);
665
+ const key = await runnerKey(opts);
666
+ const api = apiClient(key);
667
+ const service = process.env.NOUS_RUNNER_SERVICE === "1";
668
+ const stamp = (line) => (service ? `${new Date().toISOString()} ${line}` : line);
669
+ console.log(stamp(`Reading on your ${agent} plan. ${service ? "" : "Stop with Ctrl-C; `nous runner install` keeps it going on its own."}`.trim()));
670
+ await runRunner({
671
+ agent, version, run: liveRun(), log: (l) => console.log(stamp(l)),
672
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
673
+ api: {
674
+ poll: (body) => api.softPost("/v2/runner/poll", body),
675
+ answer: (id, body) => api.softPost(`/v2/runner/calls/${id}`, body),
676
+ },
677
+ });
678
+ });
679
+
680
+ runnerCmd
681
+ .command("install")
682
+ .description("Start the runner now and every time you log in")
683
+ .option("--agent <agent>", "claude or codex (default: whichever you're signed in to)")
684
+ .option("--workspace <id>", "the workspace to read; the app's command fills this in")
685
+ .option("--url <url>", "API base URL (default: https://api.opennous.cloud)")
686
+ .action(async (opts) => {
687
+ const { detectAgents, NO_AGENT } = await import("./backfill.js");
688
+ const { installService } = await import("./runner.js");
689
+ const agent = await pickAgent(opts.agent, detectAgents, NO_AGENT);
690
+ const key = await runnerKey(opts);
691
+ // One poll before installing, so a bad key or plan fails here and not silently in the background.
692
+ try {
693
+ await apiClient(key).softPost("/v2/runner/poll", { agent, host: hostname(), version, limit: 0 });
694
+ } catch (e) {
695
+ console.error(`Couldn't connect: ${e.message}`);
696
+ process.exit(1);
697
+ }
698
+ try {
699
+ const where = installService({ agent, workspace: opts.workspace ?? null });
700
+ console.log(`Connected. The runner reads on your ${agent} plan and starts every time you log in.`);
701
+ if (where.log) console.log(`Log: ${where.log}`);
702
+ console.log("Check on it with `npx @opennous/cli@latest runner status`. Stop it with `npx @opennous/cli@latest runner uninstall`.");
703
+ } catch (e) {
704
+ console.error(e.message);
705
+ process.exit(1);
706
+ }
707
+ });
708
+
709
+ runnerCmd
710
+ .command("uninstall")
711
+ .description("Stop the runner and stop it starting at login")
712
+ .action(async () => {
713
+ const { uninstallService } = await import("./runner.js");
714
+ console.log(uninstallService() ? "Stopped. It won't start at login any more." : "No runner is installed on this machine.");
715
+ });
716
+
717
+ runnerCmd
718
+ .command("status")
719
+ .description("Whether the runner is installed and running on this machine")
720
+ .action(async () => {
721
+ const { serviceStatus } = await import("./runner.js");
722
+ const s = serviceStatus();
723
+ if (!s.installed) { console.log("Not installed. Run `npx @opennous/cli@latest runner install`."); return; }
724
+ console.log(s.running ? "Running." : "Installed, but not running right now.");
725
+ if (s.log) console.log(`Log: ${s.log}`);
726
+ });
727
+
728
+ /** The agent to read with: the one asked for, or whichever is signed in. Exits with what to do. */
729
+ async function pickAgent(asked, detectAgents, noAgent) {
730
+ const agents = detectAgents();
731
+ const agent = asked ?? agents[0];
732
+ if (!agent || !agents.includes(agent)) {
733
+ console.error(asked ? `You're not signed in to ${asked}. Run \`${asked === "codex" ? "codex login" : "claude"}\` first.` : noAgent);
734
+ process.exit(1);
735
+ }
736
+ return agent;
737
+ }
738
+
739
+ /** The key the runner reads with: for --workspace when given (signing in to it if needed), else the saved one. */
740
+ async function runnerKey(opts) {
741
+ if (opts.url) writeConfig({ ...readConfig(), apiUrl: opts.url });
742
+ if (!hasKey()) await browserLogin(opts.url);
743
+ const cfg = readConfig();
744
+ const apiUrl = opts.url || process.env.NOUS_API_URL || cfg.apiUrl || "https://api.opennous.cloud";
745
+ let key = process.env.NOUS_API_KEY || cfg.apiKey;
746
+ if (!opts.workspace) return key;
747
+ const kept = cfg.workspaceKeys?.[opts.workspace];
748
+ for (const k of [key, kept].filter(Boolean)) {
749
+ if ((await fetchWhoami(apiUrl, k))?.workspace?.id === opts.workspace) {
750
+ if (k !== kept) writeConfig({ ...cfg, workspaceKeys: { ...cfg.workspaceKeys, [opts.workspace]: k } });
751
+ return k;
752
+ }
753
+ }
754
+ console.log("Sign in to the workspace this runner is for.");
755
+ key = await browserLogin(opts.url, { save: false });
756
+ if ((await fetchWhoami(apiUrl, key))?.workspace?.id !== opts.workspace) {
757
+ console.error("That sign-in is for another workspace. Open the right workspace in the app, then run this again.");
758
+ process.exit(1);
759
+ }
760
+ const saved = readConfig();
761
+ writeConfig({ ...saved, workspaceKeys: { ...saved.workspaceKeys, [opts.workspace]: key } });
762
+ return key;
763
+ }
764
+
653
765
  program
654
766
  .command("logout")
655
767
  .description("Sign out — remove the saved API key")
package/src/runner.js ADDED
@@ -0,0 +1,224 @@
1
+ // `nous runner` (GET-1293): reads your new calls and email on your own Claude or ChatGPT plan, all
2
+ // the time. It is `nous backfill`'s loop that never ends: it polls the server, answers each model
3
+ // call with the `claude` or `codex` CLI you are signed in to (no tools, the same sandbox as backfill:
4
+ // a call's prompt holds other people's words), and posts the answer back. The server decides what to
5
+ // read; this only answers. `nous runner install` starts it at login, so it keeps going on its own.
6
+
7
+ import { spawnSync } from "node:child_process";
8
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
9
+ import { homedir, hostname, platform } from "node:os";
10
+ import { dirname, join } from "node:path";
11
+ import { commandFor, parseAnswer, troubleOf, resetAt } from "./backfill.js";
12
+
13
+ export const WORKERS = 3;
14
+ /** Busy: there is a read going, so ask again soon. */
15
+ export const BUSY_MS = 2000;
16
+ /** Idle: nothing going. A heartbeat still has to land well inside the server's two minutes. */
17
+ export const IDLE_MS = 20_000;
18
+ /** At the plan's limit: take nothing, keep the heartbeat. */
19
+ export const LIMITED_POLL_MS = 60_000;
20
+ /** A limit whose message gives no reset time is tried again after this. */
21
+ export const LIMIT_WAIT_MS = 30 * 60_000;
22
+ /** Signed out, or the model down: look again after this (GET-1303). */
23
+ export const RECHECK_MS = 5 * 60_000;
24
+ const RETRIES = 2;
25
+ const ERROR_BACKOFF_MS = 30_000;
26
+
27
+ export const LABEL = "cloud.opennous.runner";
28
+ export const RUN_COMMAND = "npx -y @opennous/cli@latest runner";
29
+
30
+ /** What the status line says about the read in progress, or null. Pure. */
31
+ export function readingLine(reading) {
32
+ if (!reading) return null;
33
+ const what = reading.live ? "Reading what's new" : "Reading your history";
34
+ if (reading.status === "paused_own_model") return `${what}: picking it back up.`;
35
+ if (reading.finished) return `${what}: wrapping up.`;
36
+ if (reading.total) return `${what}: ${reading.done ?? 0} of ${reading.total}.`;
37
+ return `${what}.`;
38
+ }
39
+
40
+ /** What the log says when reading stops for a while, by why. Pure. */
41
+ export function pauseLine(agent, reason, until, now = Date.now()) {
42
+ const name = agent === "codex" ? "Codex" : "Claude";
43
+ const at = new Date(until).toLocaleString([], until - now > 20 * 3_600_000
44
+ ? { weekday: "short", hour: "2-digit", minute: "2-digit" } : { hour: "2-digit", minute: "2-digit" });
45
+ if (reason === "signed_out") return `You're signed out of ${name}. Run \`${agent === "codex" ? "codex login" : "claude"}\` and sign in; reading carries on by itself. Nothing is lost meanwhile.`;
46
+ if (reason === "outage") return `${name} isn't answering right now. Trying again at ${at}. Nothing is lost meanwhile.`;
47
+ return `Your ${name} plan hit its limit. Reading carries on at ${at}, when it resets. Nothing is lost meanwhile.`;
48
+ }
49
+
50
+ /**
51
+ * The loop. Injected: `api` ({ poll, answer }), `run` (one command → stdout), `sleep`, `log`.
52
+ * `stop()` → true ends it (tests; the real one runs until the process is stopped).
53
+ */
54
+ export async function runRunner({ api, agent, host = hostname(), version = null, run, sleep, log, now = Date.now,
55
+ workers = WORKERS, limitWaitMs = LIMIT_WAIT_MS, stop = () => false }) {
56
+ let limitedUntil = 0, limitReason = null, answered = 0, lastLine = null, lastError = null, toldBackfill = false;
57
+ const answerOne = async (call, models) => {
58
+ for (let attempt = 0; ; attempt++) {
59
+ try {
60
+ const { text, usage } = parseAnswer(agent, await run(commandFor(agent, models[agent], call)));
61
+ await api.answer(call.id, { answer: text, model: models[agent].model, usage });
62
+ answered++;
63
+ if (limitReason) { log(limitReason === "signed_out" ? "Signed in again. Reading." : "Reading again."); limitReason = null; }
64
+ return;
65
+ } catch (err) {
66
+ // The plan's limit, a sign-out or an outage (GET-1303): none of them is the call's fault, so
67
+ // it is dropped, not failed (its lease runs out and it comes back), and nothing more is taken
68
+ // until it passes. The heartbeat keeps going, so the app shows why.
69
+ const reason = troubleOf(err.message);
70
+ if (reason) {
71
+ const until = reason === "limit" ? (resetAt(err.message, now()) ?? now() + limitWaitMs) : now() + RECHECK_MS;
72
+ if (now() >= limitedUntil || reason !== limitReason) log(pauseLine(agent, reason, until, now()));
73
+ limitedUntil = Math.max(limitedUntil, until);
74
+ limitReason = reason;
75
+ return;
76
+ }
77
+ if (attempt >= RETRIES) { await api.answer(call.id, { error: err.message }).catch(() => {}); return; }
78
+ }
79
+ }
80
+ };
81
+ while (!stop()) {
82
+ let page;
83
+ try {
84
+ page = await api.poll({ agent, host, version, answered, limit: workers,
85
+ limited_until: limitedUntil > now() ? new Date(limitedUntil).toISOString() : null,
86
+ limit_reason: limitedUntil > now() ? limitReason : null });
87
+ if (lastError) { log("Back online."); lastError = null; }
88
+ } catch (err) {
89
+ if (err.message !== lastError) log(`Waiting on Ownable: ${err.message}. Trying again every ${ERROR_BACKOFF_MS / 1000} seconds.`);
90
+ lastError = err.message;
91
+ await sleep(ERROR_BACKOFF_MS);
92
+ continue;
93
+ }
94
+ if (page.needs_backfill && !toldBackfill) {
95
+ toldBackfill = true;
96
+ log("Your history hasn't been read yet. Run `npx @opennous/cli@latest backfill` once; after that this keeps it current.");
97
+ }
98
+ const line = readingLine(page.reading);
99
+ if (line && line !== lastLine) { log(line); }
100
+ lastLine = line;
101
+ const calls = page.calls ?? [];
102
+ if (!calls.length) { await sleep(limitedUntil > now() ? LIMITED_POLL_MS : page.reading ? BUSY_MS : IDLE_MS); continue; }
103
+ await Promise.all(calls.map((c) => answerOne(c, page.models)));
104
+ }
105
+ return { answered };
106
+ }
107
+
108
+ // ── Start at login ───────────────────────────────────────────────────────────────────────────
109
+
110
+ /** The absolute path of a command, or null. */
111
+ export function which(cmd, run = spawnSync) {
112
+ const r = run("/bin/sh", ["-c", `command -v ${cmd}`], { encoding: "utf8" });
113
+ const p = r.status === 0 ? String(r.stdout).trim().split("\n")[0] : "";
114
+ return p.startsWith("/") ? p : null;
115
+ }
116
+
117
+ /** PATH for the service: where node, npx and the agent CLIs live, then the usual places. Pure. */
118
+ export function servicePath(binaries) {
119
+ const dirs = [...new Set(binaries.filter(Boolean).map((b) => dirname(b)))];
120
+ for (const d of ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"]) if (!dirs.includes(d)) dirs.push(d);
121
+ return dirs.join(":");
122
+ }
123
+
124
+ const xml = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
125
+
126
+ /** The launchd agent for macOS. Pure. */
127
+ export function launchdPlist({ npx, agent, workspace = null, path, log }) {
128
+ const args = [npx, "-y", "@opennous/cli@latest", "runner", "--agent", agent, ...(workspace ? ["--workspace", workspace] : [])];
129
+ return `<?xml version="1.0" encoding="UTF-8"?>
130
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
131
+ <plist version="1.0">
132
+ <dict>
133
+ <key>Label</key><string>${LABEL}</string>
134
+ <key>ProgramArguments</key>
135
+ <array>
136
+ ${args.map((a) => ` <string>${xml(a)}</string>`).join("\n")}
137
+ </array>
138
+ <key>EnvironmentVariables</key>
139
+ <dict>
140
+ <key>PATH</key><string>${xml(path)}</string>
141
+ <key>NOUS_RUNNER_SERVICE</key><string>1</string>
142
+ </dict>
143
+ <key>RunAtLoad</key><true/>
144
+ <key>KeepAlive</key><true/>
145
+ <key>ThrottleInterval</key><integer>30</integer>
146
+ <key>StandardOutPath</key><string>${xml(log)}</string>
147
+ <key>StandardErrorPath</key><string>${xml(log)}</string>
148
+ </dict>
149
+ </plist>
150
+ `;
151
+ }
152
+
153
+ /** The systemd user unit for Linux. Pure. */
154
+ export function systemdUnit({ npx, agent, workspace = null, path }) {
155
+ const args = [npx, "-y", "@opennous/cli@latest", "runner", "--agent", agent, ...(workspace ? ["--workspace", workspace] : [])];
156
+ return `[Unit]
157
+ Description=Ownable runner: reads on your own ${agent === "codex" ? "ChatGPT" : "Claude"} plan
158
+ After=network-online.target
159
+
160
+ [Service]
161
+ ExecStart=${args.join(" ")}
162
+ Environment=PATH=${path}
163
+ Environment=NOUS_RUNNER_SERVICE=1
164
+ Restart=always
165
+ RestartSec=30
166
+
167
+ [Install]
168
+ WantedBy=default.target
169
+ `;
170
+ }
171
+
172
+ /** Where the service files live on this machine. Pure. */
173
+ export function servicePaths(os = platform(), home = homedir()) {
174
+ if (os === "darwin") return { kind: "launchd", file: join(home, "Library", "LaunchAgents", `${LABEL}.plist`), log: join(home, "Library", "Logs", "opennous-runner.log") };
175
+ if (os === "linux") return { kind: "systemd", file: join(home, ".config", "systemd", "user", "opennous-runner.service"), log: null };
176
+ return null;
177
+ }
178
+
179
+ /** Install and start the runner as a service. Returns { kind, file, log } or throws with what to do. */
180
+ export function installService({ agent, workspace = null, run = spawnSync, os = platform(), home = homedir() } = {}) {
181
+ const where = servicePaths(os, home);
182
+ if (!where) throw new Error(`Starting at login isn't supported on ${os} yet. Run \`${RUN_COMMAND}\` in a terminal you keep open instead.`);
183
+ const npx = which("npx", run);
184
+ if (!npx) throw new Error("Couldn't find npx. Install Node.js 20 or later, then run this again.");
185
+ const path = servicePath([npx, which("node", run), which(agent, run)]);
186
+ mkdirSync(dirname(where.file), { recursive: true });
187
+ if (where.kind === "launchd") {
188
+ mkdirSync(dirname(where.log), { recursive: true });
189
+ writeFileSync(where.file, launchdPlist({ npx, agent, workspace, path, log: where.log }));
190
+ run("launchctl", ["unload", where.file], { stdio: "ignore" });
191
+ const r = run("launchctl", ["load", "-w", where.file], { encoding: "utf8" });
192
+ if (r.status !== 0) throw new Error(`launchctl couldn't start it: ${(r.stderr || "").trim()}`);
193
+ } else {
194
+ writeFileSync(where.file, systemdUnit({ npx, agent, workspace, path }));
195
+ run("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
196
+ const r = run("systemctl", ["--user", "enable", "--now", "opennous-runner.service"], { encoding: "utf8" });
197
+ if (r.status !== 0) throw new Error(`systemd couldn't start it: ${(r.stderr || "").trim()}`);
198
+ // Keeps it running after logout, where the machine allows it. Best effort.
199
+ run("loginctl", ["enable-linger"], { stdio: "ignore" });
200
+ }
201
+ return where;
202
+ }
203
+
204
+ /** Stop and remove the service. True when there was one. */
205
+ export function uninstallService({ run = spawnSync, os = platform(), home = homedir() } = {}) {
206
+ const where = servicePaths(os, home);
207
+ if (!where || !existsSync(where.file)) return false;
208
+ if (where.kind === "launchd") run("launchctl", ["unload", "-w", where.file], { stdio: "ignore" });
209
+ else {
210
+ run("systemctl", ["--user", "disable", "--now", "opennous-runner.service"], { stdio: "ignore" });
211
+ }
212
+ rmSync(where.file, { force: true });
213
+ return true;
214
+ }
215
+
216
+ /** Whether the service is installed, and running as far as the OS says. */
217
+ export function serviceStatus({ run = spawnSync, os = platform(), home = homedir() } = {}) {
218
+ const where = servicePaths(os, home);
219
+ if (!where || !existsSync(where.file)) return { installed: false, running: false, ...(where ?? {}) };
220
+ const r = where.kind === "launchd"
221
+ ? run("launchctl", ["list", LABEL], { encoding: "utf8" })
222
+ : run("systemctl", ["--user", "is-active", "opennous-runner.service"], { encoding: "utf8" });
223
+ return { installed: true, running: r.status === 0, ...where };
224
+ }