shadok-ai 0.19.91 → 0.19.92

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.
@@ -28,7 +28,8 @@ and automatically starts the shadok-ai server when it is not running (port
28
28
  | `freetext <id> <n> "text"` | the "Type something" option: a free answer |
29
29
  | `list [--cwd DIR]` | driven agents (local state + alive/dead) and resumable sessions. With `--peer X`: the agents running ON X (from X itself, tagged `peer`), plus X's resumable sessions only for a `--cwd` you name — a path on X |
30
30
  | `diff <id>` | the agent's changes (git status + diff against the worktree's base) |
31
- | `stop <id>` | ends the session (for ALL its clients) |
31
+ | `stop <id> [--force]` | ends the session (for ALL its clients), whether it is running or dormant — sent by id, nothing is resumed — and answers `stopped:true` only once the server confirms. Works over `--peer` with no local state (a restricted peer may close only what it spawned). A local agent this pilotctl never drove needs `--force` |
32
+ | `reap [--idle 30m] [--dry-run]` | closes every finished agent you spawned: not busy, nobody watching, idle for `--idle` (default 30m). Over a restricted `--peer` that is every agent the peer lists for you (its own, dormant ones included); anywhere else only the ids in your local state. Use it to clear a backlog |
32
33
  | `set-parent <id> <parent-id\|none>` | re-link an agent to a parent, or **detach** it with `none` (it then reports to nobody). The link is what makes the parent hear when the agent finishes, blocks or dies — set automatically at spawn, flipped here when a side task is done and you want it off a lead's back |
33
34
  | `screen <id>` | raw TUI screen (debug) |
34
35
  | `profile-prompt "<text>" [--name NAME] [--readonly]` | rewrites a profile's **system prompt**: your own by default; any of them (and creation with `--name`) under the lead profile |
@@ -190,7 +191,8 @@ pilotctl peer add brasdroit1 https://brasdroit1.example.com <token> # once
190
191
  pilotctl spawn --peer brasdroit1 --profile dev --cwd /workspace # spawn there
191
192
  pilotctl prompt <id> "run the migration" --peer brasdroit1 # drive it
192
193
  pilotctl diff <id> --peer brasdroit1 # read its work
193
- pilotctl stop <id> --peer brasdroit1
194
+ pilotctl stop <id> --peer brasdroit1 # close it when done
195
+ pilotctl reap --peer brasdroit1 --dry-run # what you left open there
194
196
  ```
195
197
 
196
198
  - The **token** is minted by the REMOTE instance's admin (a human, in its
@@ -200,8 +202,10 @@ pilotctl stop <id> --peer brasdroit1
200
202
  - What you may touch on X depends on the **scope** its admin gave you when they
201
203
  invited you:
202
204
  - **restricted** (the default) — only the agents YOU spawned on X; `--peer X
203
- list` and a diff of someone else's agent come back refused (`peer-scope` /
204
- `403`). Assume this one unless you were told otherwise.
205
+ list` shows those (dormant ones included) and nothing else, and a diff or
206
+ stop of someone else's agent comes back refused (`peer-scope` / `403`). An
207
+ older X refuses `list` outright. Assume this scope unless you were told
208
+ otherwise.
205
209
  - **member** — you act like an invited user: `list`, `diff`, resume/drive/stop
206
210
  **any** agent on X, spawn more, read its usage. You are not an admin (no
207
211
  account or peer management).
@@ -149,10 +149,10 @@ export function parseArgs(argv) {
149
149
  const pos = [];
150
150
  for (let i = 0; i < rest.length; i++) {
151
151
  const a = rest[i];
152
- if (a === "--worktree" || a === "--continue" || a === "--readonly") flags[a.slice(2)] = true;
152
+ if (a === "--worktree" || a === "--continue" || a === "--readonly" || a === "--force" || a === "--dry-run") flags[a.slice(2)] = true;
153
153
  else if (
154
154
  a === "--cwd" || a === "--resume" || a === "--timeout" || a === "--profile" || a === "--parent" ||
155
- a === "--name" || a === "--peer" || a === "--peer-url" || a === "--peer-token"
155
+ a === "--name" || a === "--peer" || a === "--peer-url" || a === "--peer-token" || a === "--idle"
156
156
  ) flags[a.slice(2)] = rest[++i];
157
157
  // Repeatable: a Skill Factory skill the new agent is born with, `name` or `name@N`.
158
158
  else if (a === "--skill") (flags.skill ||= []).push(rest[++i]);
@@ -565,45 +565,113 @@ async function cmdSetParent(id, parentArg, flags) {
565
565
  return { sessionId: id, parent: r.parent ?? null };
566
566
  }
567
567
 
568
- async function cmdStop(id) {
568
+ /**
569
+ * Send `stop` for `id` on a BARE socket — no `start`, so nothing is resumed —
570
+ * and wait for the server's `stop-result`. The old path went through the local
571
+ * holder: with the holder gone (it is, once a `prompt` over a peer link returns
572
+ * and its socket drops) it sent NOTHING and only cleared local state, so the
573
+ * agent stayed open on the other instance for ever. Whether the caller may stop
574
+ * it is the server's call (a restricted peer: only its own), not the holder's.
575
+ */
576
+ async function stopById(id) {
577
+ const ws = await connect();
578
+ try {
579
+ return await new Promise((resolve) => {
580
+ const t = setTimeout(() => resolve({ type: "timeout" }), 30_000);
581
+ ws.on("message", (raw) => {
582
+ let m;
583
+ try {
584
+ m = JSON.parse(String(raw));
585
+ } catch {
586
+ return;
587
+ }
588
+ if ((m.type === "stop-result" && m.sessionId === id) || m.type === "error") {
589
+ clearTimeout(t);
590
+ resolve(m);
591
+ }
592
+ });
593
+ ws.on("close", () => {
594
+ clearTimeout(t);
595
+ resolve({ type: "socket-closed" });
596
+ });
597
+ ws.send(JSON.stringify({ type: "stop", sessionId: id }));
598
+ });
599
+ } finally {
600
+ ws.close();
601
+ }
602
+ }
603
+
604
+ /** Pure: what a `stop-result` / refusal means for the caller. */
605
+ export function stopOutcome(id, reply) {
606
+ if (reply.type === "stop-result" && reply.ok) return { stopped: true, sessionId: id };
607
+ if (reply.type === "stop-result") return { stopped: false, sessionId: id, note: "the server kept it (the home agent is never closed)" };
608
+ if (reply.type === "error") return { stopped: false, sessionId: id, error: reply.message, ...(reply.code ? { code: reply.code } : {}) };
609
+ return {
610
+ stopped: false,
611
+ sessionId: id,
612
+ note: "the server did not confirm the stop within 30s (an older shadok-ai answers nothing) — check with `list`",
613
+ };
614
+ }
615
+
616
+ async function cmdStop(id, flags = {}) {
569
617
  await ensureServer();
570
618
  const st = readState(id);
571
- const holderLive = !!(st?.holderPid && pidAlive(st.holderPid));
572
- if (!holderLive) {
573
- // No holder → we never kept this session alive; don't resurrect it just
574
- // to stop it (it may belong to a browser client). Clear local state only.
575
- deleteState(id);
576
- return { stopped: false, sessionId: id, note: "no live holder; local state cleared" };
577
- }
578
- let client;
579
- try {
580
- client = await openSession({ resume: id, cwd: st?.cwd ?? undefined });
581
- } catch (err) {
582
- // Holder pid is alive but session is dead (zombie holder, dead server session).
583
- // Kill the holder and clean up state.
584
- if (st.holderPid !== process.pid && pidAlive(st.holderPid)) {
619
+ // A LOCAL agent this pilotctl never drove may be someone's in the web UI: ask
620
+ // for --force. Over a peer link the peer's own scope already decides (a
621
+ // restricted peer can only close what it spawned).
622
+ if (!st && !PEER && !flags.force)
623
+ return { stopped: false, sessionId: id, note: "not an agent this pilotctl drove — pass --force to stop it anyway" };
624
+ const out = stopOutcome(id, await stopById(id));
625
+ if (out.stopped) {
626
+ if (st?.holderPid && st.holderPid !== process.pid && pidAlive(st.holderPid)) {
585
627
  try {
586
628
  process.kill(st.holderPid);
587
629
  } catch {}
588
630
  }
589
631
  deleteState(id);
590
- const msg = err instanceof Error ? err.message : String(err);
591
- return { stopped: false, sessionId: id, note: `session not reattachable (${msg}); holder killed and local state cleared` };
592
- }
593
- client.send({ type: "stop" });
594
- const result = await client.waitFor(["stopped", "socket-closed"], 30_000);
595
- client.ws.close();
596
- if (result.type === "timeout") {
597
- // Stop was not confirmed within 30s; don't kill holder or delete state (leave for retry).
598
- return { stopped: false, sessionId: id, note: "stop not confirmed within 30s; session may still be running" };
599
632
  }
600
- if (st.holderPid !== process.pid && pidAlive(st.holderPid)) {
601
- try {
602
- process.kill(st.holderPid);
603
- } catch {}
604
- }
605
- deleteState(id);
606
- return { stopped: true, sessionId: id };
633
+ return out;
634
+ }
635
+
636
+ /**
637
+ * Pure: which agents `reap` closes. Never a busy one, never one with someone
638
+ * watching it, never one active more recently than `idleSec` (a non-running
639
+ * row, idleSec -1, is idle by definition). Over a RESTRICTED peer link the list
640
+ * is already narrowed to what this peer spawned, so every row is ours; anywhere
641
+ * else the list holds other people's agents too, so only the ids this pilotctl
642
+ * spawned (its state files) are eligible.
643
+ */
644
+ export function reapCandidates(rows, { restricted, ownIds, idleSec }) {
645
+ return rows
646
+ .filter((r) => restricted || ownIds.has(r.id))
647
+ .filter((r) => !r.busy && !(r.clients > 0) && (r.idleSec < 0 || r.idleSec >= idleSec))
648
+ .map((r) => r.id);
649
+ }
650
+
651
+ /** Parse `30m` / `2h` / `90s` / a bare number of minutes → seconds. */
652
+ export function parseIdle(v, dflt = 1800) {
653
+ if (v === undefined || v === true) return dflt;
654
+ const m = /^(\d+)\s*([smh]?)$/.exec(String(v).trim());
655
+ if (!m) throw new Error(`--idle: expected e.g. 30m, 2h, 90s — got "${v}"`);
656
+ return Number(m[1]) * ({ s: 1, m: 60, h: 3600 }[m[2] || "m"]);
657
+ }
658
+
659
+ /** Close every finished agent this caller spawned — the backlog `stop` left behind. */
660
+ async function cmdReap(flags) {
661
+ await ensureServer();
662
+ const r = await fetch(`${httpBase()}/live`, { headers: authHeaders() });
663
+ if (!r.ok) throw new Error(`${httpBase()} answered HTTP ${r.status} to /live`);
664
+ const rows = await r.json();
665
+ const dir = stateDir();
666
+ const ownIds = new Set(
667
+ fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -5)) : [],
668
+ );
669
+ const restricted = r.headers.get("x-shadok-peer-scope") === "restricted";
670
+ const ids = reapCandidates(rows, { restricted, ownIds, idleSec: parseIdle(flags.idle) });
671
+ if (flags["dry-run"]) return { wouldStop: ids };
672
+ const results = [];
673
+ for (const id of ids) results.push(await cmdStop(id, { force: true }));
674
+ return { stopped: results.filter((x) => x.stopped).map((x) => x.sessionId), failed: results.filter((x) => !x.stopped) };
607
675
  }
608
676
 
609
677
  /**
@@ -690,7 +758,7 @@ async function cmdScreen(id, flags) {
690
758
  }
691
759
 
692
760
  const HELP =
693
- "usage: pilotctl <spawn|prompt|dialog|choose|toggle|confirm|freetext|list|diff|stop|set-parent|screen|profile-prompt|talk|talk-handle|peer> …\n" +
761
+ "usage: pilotctl <spawn|prompt|dialog|choose|toggle|confirm|freetext|list|diff|stop|reap|set-parent|screen|profile-prompt|talk|talk-handle|peer> …\n" +
694
762
  " pilotctl set-parent <id> <parent-id|none> # re-link or detach an agent from its parent\n" +
695
763
  " add --peer <alias> to any command to run it against another instance's agents\n" +
696
764
  " pilotctl peer <add <alias> <url> <ticket> [--token]|list|rm <alias>>";
@@ -797,7 +865,9 @@ export async function run(argv) {
797
865
  case "diff":
798
866
  return cmdDiff(pos[0]);
799
867
  case "stop":
800
- return cmdStop(pos[0]);
868
+ return cmdStop(pos[0], flags);
869
+ case "reap":
870
+ return cmdReap(flags);
801
871
  case "set-parent":
802
872
  return cmdSetParent(pos[0], pos[1], flags);
803
873
  case "screen":
@@ -36,3 +36,25 @@ test("state: write, read, delete", () => {
36
36
  deleteState("abc");
37
37
  assert.equal(readState("abc"), null);
38
38
  });
39
+
40
+ test("reapCandidates: only our ids outside a restricted peer, never busy/watched/recent", async () => {
41
+ const { reapCandidates } = await import("../pilotctl.mjs");
42
+ const rows = [
43
+ { id: "mine-idle", busy: false, clients: 0, idleSec: 4000 },
44
+ { id: "theirs-idle", busy: false, clients: 0, idleSec: 4000 },
45
+ { id: "mine-busy", busy: true, clients: 0, idleSec: 4000 },
46
+ ];
47
+ const ownIds = new Set(["mine-idle", "mine-busy"]);
48
+ assert.deepEqual(reapCandidates(rows, { restricted: false, ownIds, idleSec: 1800 }), ["mine-idle"]);
49
+ assert.deepEqual(reapCandidates(rows, { restricted: true, ownIds: new Set(), idleSec: 1800 }), ["mine-idle", "theirs-idle"]);
50
+ });
51
+
52
+ test("parseIdle reads 30m / 2h / 90s / bare minutes", async () => {
53
+ const { parseIdle } = await import("../pilotctl.mjs");
54
+ assert.equal(parseIdle(undefined), 1800);
55
+ assert.equal(parseIdle("30m"), 1800);
56
+ assert.equal(parseIdle("2h"), 7200);
57
+ assert.equal(parseIdle("90s"), 90);
58
+ assert.equal(parseIdle("45"), 2700);
59
+ assert.throws(() => parseIdle("soon"));
60
+ });
@@ -130,32 +130,81 @@ test("the diff fallback includes untracked files", async () => {
130
130
  }
131
131
  });
132
132
 
133
- test("stop with no live holder cleans the state without reattaching", async () => {
134
- const mock = await startMockServer();
133
+ // `stop` used to go through the local holder: with the holder gone (always, once
134
+ // a `prompt` over a peer link returned) it sent nothing and only cleared local
135
+ // state, so peers piled up finished agents. It now sends `stop` by id on a bare
136
+ // socket — no `start`, nothing resumed — and trusts only the server's answer.
137
+ test("stop with no live holder still stops the agent, by id, without resuming it", async () => {
138
+ const mock = await startMockServer({ stop: [{ type: "stop-result", sessionId: "dead", ok: true }] });
135
139
  process.env.SHADOK_PORT = String(mock.port);
136
140
  writeState("dead", { sessionId: "dead", cwd: "/tmp/x", holderPid: 999999 });
137
141
  try {
138
142
  const r = await run(["stop", "dead"]);
139
- assert.equal(r.stopped, false);
143
+ assert.equal(r.stopped, true);
140
144
  assert.equal(readState("dead"), null);
141
- assert.equal(mock.received.length, 0); // no start sent
145
+ assert.deepEqual(mock.received.map((m) => m.type), ["stop"]); // no start → no resume
146
+ assert.equal(mock.received[0].sessionId, "dead");
147
+ } finally {
148
+ await mock.close();
149
+ }
150
+ });
151
+
152
+ test("stop over a peer link needs no local state and sends the stop to the peer", async () => {
153
+ const mock = await startMockServer({ stop: [{ type: "stop-result", sessionId: "w1", ok: true }] });
154
+ try {
155
+ const r = await run(["stop", "w1", "--peer-url", `http://127.0.0.1:${mock.port}`, "--peer-token", "T"]);
156
+ assert.equal(r.stopped, true);
157
+ assert.deepEqual(mock.received.map((m) => m.type), ["stop"]);
142
158
  } finally {
143
159
  await mock.close();
144
160
  }
145
161
  });
146
162
 
147
- test("stop with a live session sends stop and cleans up", async () => {
163
+ test("a refused stop keeps the local state and says why", async () => {
164
+ const mock = await startMockServer({ stop: [{ type: "error", message: "a restricted peer may only stop its own agents", code: "peer-scope" }] });
165
+ process.env.SHADOK_PORT = String(mock.port);
166
+ writeState("theirs", { sessionId: "theirs", cwd: "/tmp/x", holderPid: null });
167
+ try {
168
+ const r = await run(["stop", "theirs"]);
169
+ assert.equal(r.stopped, false);
170
+ assert.equal(r.code, "peer-scope");
171
+ assert.ok(readState("theirs"));
172
+ } finally {
173
+ await mock.close();
174
+ }
175
+ });
176
+
177
+ test("a local agent pilotctl never drove needs --force", async () => {
178
+ const mock = await startMockServer({ stop: [{ type: "stop-result", sessionId: "ui-1", ok: true }] });
179
+ process.env.SHADOK_PORT = String(mock.port);
180
+ try {
181
+ const r = await run(["stop", "ui-1"]);
182
+ assert.equal(r.stopped, false);
183
+ assert.match(r.note, /--force/);
184
+ assert.equal(mock.received.length, 0);
185
+ assert.equal((await run(["stop", "ui-1", "--force"])).stopped, true);
186
+ } finally {
187
+ await mock.close();
188
+ }
189
+ });
190
+
191
+ test("reap over a restricted peer closes its idle leftovers, never a busy or watched one", async () => {
148
192
  const mock = await startMockServer({
149
- start: [{ type: "ready", sessionId: "abc", cwd: "/tmp/x" }],
150
- stop: [{ type: "stopped" }],
193
+ live: [
194
+ { id: "done", busy: false, clients: 0, idleSec: 4000 },
195
+ { id: "dormant", busy: false, clients: 0, idleSec: -1, running: false },
196
+ { id: "working", busy: true, clients: 0, idleSec: 9000 },
197
+ { id: "watched", busy: false, clients: 1, idleSec: 9000 },
198
+ { id: "fresh", busy: false, clients: 0, idleSec: 60 },
199
+ ],
200
+ liveHeaders: { "x-shadok-peer-scope": "restricted" },
201
+ stop: [{ type: "stop-result", sessionId: "done", ok: true }],
151
202
  });
152
- process.env.SHADOK_PORT = String(mock.port);
153
- // the test process' pid: alive, simulates an active holder
154
- writeState("abc", { sessionId: "abc", cwd: "/tmp/x", holderPid: process.pid });
155
203
  try {
156
- const r = await run(["stop", "abc"]);
157
- assert.equal(r.stopped, true);
158
- assert.equal(readState("abc"), null);
204
+ const url = `http://127.0.0.1:${mock.port}`;
205
+ const dry = await run(["reap", "--peer-url", url, "--peer-token", "T", "--dry-run"]);
206
+ assert.deepEqual(dry.wouldStop, ["done", "dormant"]);
207
+ assert.equal(mock.received.length, 0);
159
208
  } finally {
160
209
  await mock.close();
161
210
  }
@@ -178,18 +227,3 @@ test("screen returns the last screen received", async () => {
178
227
  }
179
228
  });
180
229
 
181
- test("stop with a live holder but a dead session cleans up and reports stopped:false", async () => {
182
- const mock = await startMockServer({
183
- start: [{ type: "error", message: "no session" }],
184
- });
185
- process.env.SHADOK_PORT = String(mock.port);
186
- writeState("zombie", { sessionId: "zombie", cwd: "/tmp/x", holderPid: process.pid });
187
- try {
188
- const r = await run(["stop", "zombie"]);
189
- assert.equal(r.stopped, false);
190
- assert.match(r.note, /not reattachable/);
191
- assert.equal(readState("zombie"), null);
192
- } finally {
193
- await mock.close();
194
- }
195
- });
@@ -23,6 +23,7 @@ export function startMockServer(script = {}) {
23
23
  res.setHeader("content-type", "application/json");
24
24
  if (req.url.startsWith("/live")) {
25
25
  if (script.liveStatus) res.statusCode = script.liveStatus;
26
+ for (const [k, v] of Object.entries(script.liveHeaders ?? {})) res.setHeader(k, v);
26
27
  return res.end(JSON.stringify(script.live ?? []));
27
28
  }
28
29
  if (req.url.startsWith("/sessions")) return res.end(JSON.stringify(script.sessions ?? []));
package/dist/server.js CHANGED
@@ -1906,6 +1906,10 @@ app.use((req, res, next) => {
1906
1906
  // agents or the account routes. Its spawn/drive path is the WS (verifyClient).
1907
1907
  if (req.method === "GET" && req.path === "/diff" && peerName(req))
1908
1908
  return next();
1909
+ // And `GET /live`, so a peer can find the agents it left behind: the handler
1910
+ // narrows a restricted peer to the ones it spawned (`restrictedBoxOf`).
1911
+ if (req.method === "GET" && req.path === "/live" && peerName(req))
1912
+ return next();
1909
1913
  if (req.method === "GET" && (req.headers.accept ?? "").includes("text/html"))
1910
1914
  return sendLogin(req, res);
1911
1915
  return res.status(401).json({ error: "unauthorized" });
@@ -2144,7 +2148,7 @@ app.get("/live", (req, res) => {
2144
2148
  return false; // unresolvable → fail closed
2145
2149
  return canSeeGroup(g, viewer);
2146
2150
  };
2147
- res.json([...sessions.values()]
2151
+ const running = [...sessions.values()]
2148
2152
  .filter((s) => !s.pilot.hasExited && visible(s.id))
2149
2153
  .map((s) => ({
2150
2154
  id: s.id,
@@ -2152,8 +2156,26 @@ app.get("/live", (req, res) => {
2152
2156
  branch: s.worktree?.branch ?? null,
2153
2157
  busy: s.busy,
2154
2158
  clients: s.clients.size,
2159
+ // How long nothing has happened on it — what `pilotctl reap --idle` sorts by.
2160
+ idleSec: Math.round((Date.now() - Math.max(s.lastActivityAt ?? 0, s.lastContentAt ?? 0)) / 1000),
2155
2161
  lastPrompt: s.lastPrompt,
2156
- })));
2162
+ }));
2163
+ // A RESTRICTED PEER also gets the agents it spawned that are no longer
2164
+ // running: a process reclaimed after its idle window still leaves its channel
2165
+ // row in this cockpit, and this list is the only one such a peer can read —
2166
+ // without these rows its leftovers were invisible to the one caller entitled
2167
+ // to close them. Nobody else's list changes. The scope rides in a header so
2168
+ // the shape stays an array for every existing reader.
2169
+ if (box && peerName(req)) {
2170
+ res.setHeader("x-shadok-peer-scope", "restricted");
2171
+ const live = new Set(running.map((r) => r.id));
2172
+ for (const c of chans) {
2173
+ if (live.has(c.sessionId) || !ownedByPeer(c, box))
2174
+ continue;
2175
+ running.push({ id: c.sessionId, cwd: c.cwd, branch: c.branch ?? null, busy: false, clients: 0, idleSec: -1, running: false });
2176
+ }
2177
+ }
2178
+ res.json(running);
2157
2179
  });
2158
2180
  // Current 5-hour and 7-day subscription usage, each window enriched with how it
2159
2181
  // compares to the time already elapsed (for the quota gauges and the send guard).
@@ -12132,9 +12154,14 @@ wss.on("connection", (ws, req) => {
12132
12154
  if (!ownedByPeer(ch, callerPeer))
12133
12155
  return fail("a restricted peer may only stop its own agents", "peer-scope");
12134
12156
  }
12135
- await endChannel(id);
12157
+ const ended = await endChannel(id);
12136
12158
  if (session?.id === id)
12137
12159
  session = null;
12160
+ // Answer the SENDER, attached or not. `stopped` is broadcast only to the
12161
+ // viewers of a LIVE session, so a caller that stopped a dormant agent by
12162
+ // id (pilotctl, whose holder is long gone) heard nothing and could not
12163
+ // tell "gone" from "ignored". `ended: false` = the home base, kept.
12164
+ send({ type: "stop-result", sessionId: id, ok: ended });
12138
12165
  break;
12139
12166
  }
12140
12167
  }