pi-straw-boss 0.111.2 → 0.111.3
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/dist/server/cli.mjs +3 -3
- package/dist/server/main.mjs +243 -50
- package/package.json +1 -1
- package/src/server/main.ts +2 -2
- package/src/server/runs.ts +4 -0
- package/src/server/standing.ts +9 -1
- package/src/server/towers.ts +17 -16
- package/src/server/towerstow.ts +251 -0
- package/src/towerprompt/prompt.ts +1 -1
- package/src/towerprompt/serversource.ts +2 -2
- package/src/towerprompt/source.ts +2 -2
package/dist/server/cli.mjs
CHANGED
|
@@ -2186,7 +2186,7 @@ ${now.words}`;
|
|
|
2186
2186
|
if (finished) return;
|
|
2187
2187
|
polling = true;
|
|
2188
2188
|
try {
|
|
2189
|
-
const polled = await source.poll(cards?.answering() ?? false).catch((cause) => ({ kind: "wait", why: cause.message }));
|
|
2189
|
+
const polled = await source.poll(cards?.answering() ?? false, Boolean(rl && !closed && ((rl.line ?? "") !== "" || batch.length || pasting || posting || pick.active() || cards?.engaged()))).catch((cause) => ({ kind: "wait", why: cause.message }));
|
|
2190
2190
|
if (finished || !await handle(polled)) return;
|
|
2191
2191
|
} finally {
|
|
2192
2192
|
polling = false;
|
|
@@ -2437,10 +2437,10 @@ function serverSource(ctx, workspace, pid = process.pid, pane = process.env.HERD
|
|
|
2437
2437
|
};
|
|
2438
2438
|
return {
|
|
2439
2439
|
pick,
|
|
2440
|
-
async poll(answering = false) {
|
|
2440
|
+
async poll(answering = false, draft = false) {
|
|
2441
2441
|
let reply;
|
|
2442
2442
|
try {
|
|
2443
|
-
reply = await ask({ cmd: "prompt-poll", workspace, pid, ...answering ? { answering: true } : {}, ...cursor !== void 0 ? { cursor } : {} }, POLL_MS3);
|
|
2443
|
+
reply = await ask({ cmd: "prompt-poll", workspace, pid, ...answering ? { answering: true } : {}, ...draft ? { draft: true } : {}, ...cursor !== void 0 ? { cursor } : {} }, POLL_MS3);
|
|
2444
2444
|
} catch (cause) {
|
|
2445
2445
|
return { kind: "wait", why: cause.message };
|
|
2446
2446
|
}
|
package/dist/server/main.mjs
CHANGED
|
@@ -1932,9 +1932,9 @@ var LinkStore = class {
|
|
|
1932
1932
|
const size2 = statSync2(file3, { throwIfNoEntry: false })?.size ?? 0;
|
|
1933
1933
|
if (size2 > this.logMax) {
|
|
1934
1934
|
const audit = this.audits();
|
|
1935
|
-
const
|
|
1936
|
-
if (size2 >
|
|
1937
|
-
for (let n =
|
|
1935
|
+
const keep3 = audit ? this.auditLog : { max: this.logMax, copies: 1 };
|
|
1936
|
+
if (size2 > keep3.max) {
|
|
1937
|
+
for (let n = keep3.copies - 1; n >= 1; n--) if (existsSync2(`${file3}.${n}`)) renameSync2(`${file3}.${n}`, `${file3}.${n + 1}`);
|
|
1938
1938
|
renameSync2(file3, `${file3}.1`);
|
|
1939
1939
|
}
|
|
1940
1940
|
}
|
|
@@ -2855,7 +2855,7 @@ function addRoute(slot, workspace, row2, now, live, panes3) {
|
|
|
2855
2855
|
const rest = [...was.filter((r) => !(r.to === row2.to && r.device === row2.device)), row2], dead = (r) => live !== void 0 && !live.has(r.to) && !(r.pane !== void 0 && (panes3 === void 0 || panes3.has(r.pane)));
|
|
2856
2856
|
const order2 = (a, b) => Number(a.stop !== void 0) - Number(b.stop !== void 0) || Number(dead(b)) - Number(dead(a)) || a.at - b.at;
|
|
2857
2857
|
const gone = new Set(rest.filter((r) => r.kind === "opened" && r !== row2 && dead(r) && now - r.at > DEAD_GRACE_MS));
|
|
2858
|
-
const trim = (rows,
|
|
2858
|
+
const trim = (rows, keep3) => rows.filter((r) => r !== row2 && dead(r)).sort(order2).slice(0, Math.max(0, rows.length - keep3)).forEach((r) => gone.add(r));
|
|
2859
2859
|
const kept = () => rest.filter((r) => r.kind === "opened" && !gone.has(r));
|
|
2860
2860
|
for (const device of new Set(kept().map((r) => r.device))) trim(kept().filter((r) => r.device === device), MAX_OPENED_PER_DEVICE);
|
|
2861
2861
|
trim(kept(), MAX_OPENED);
|
|
@@ -6776,7 +6776,7 @@ function openReader(file3, pollMs = 1e3) {
|
|
|
6776
6776
|
}
|
|
6777
6777
|
};
|
|
6778
6778
|
}
|
|
6779
|
-
function readers(
|
|
6779
|
+
function readers(keep3 = 8, make = openReader) {
|
|
6780
6780
|
const all = /* @__PURE__ */ new Map();
|
|
6781
6781
|
return {
|
|
6782
6782
|
acquire(file3) {
|
|
@@ -6791,7 +6791,7 @@ function readers(keep2 = 8, make = openReader) {
|
|
|
6791
6791
|
const held2 = all.get(file3);
|
|
6792
6792
|
if (!held2 || --held2.users > 0) return;
|
|
6793
6793
|
held2.reader.stop();
|
|
6794
|
-
for (const [name2, other] of all) if (all.size >
|
|
6794
|
+
for (const [name2, other] of all) if (all.size > keep3 && !other.users) all.delete(name2);
|
|
6795
6795
|
}
|
|
6796
6796
|
};
|
|
6797
6797
|
}
|
|
@@ -8762,12 +8762,13 @@ function createStanding(o) {
|
|
|
8762
8762
|
await unreport(m);
|
|
8763
8763
|
},
|
|
8764
8764
|
/** The prompt's poll: it is there; the answer is what its screen shows and whether it must leave. */
|
|
8765
|
-
poll(workspace, pid) {
|
|
8765
|
+
poll(workspace, pid, draft = false) {
|
|
8766
8766
|
const m = mines.get(workspace);
|
|
8767
8767
|
if (!m) return { ok: false, error: `The sb server stands in for no tower of workspace ${workspace}`, gone: true };
|
|
8768
8768
|
const status = m.target.status(), answer = (leave) => ({ ok: true, label: m.target.label(), state: status?.state ?? "standing", queued: status?.queued ?? 0, leave, ...m.target.agent === STANDIN_HEAD ? { head: true } : {} });
|
|
8769
8769
|
if (pollGate({ parked: m.parked, parkedBy: m.parkedBy, pid }) === "left") return answer(true);
|
|
8770
8770
|
m.seen = { pid, at: now() };
|
|
8771
|
+
m.draft = draft;
|
|
8771
8772
|
m.polled = true;
|
|
8772
8773
|
if (m.leaver !== void 0 && m.leaver !== pid) m.leaver = void 0;
|
|
8773
8774
|
m.typings = 0;
|
|
@@ -8857,6 +8858,11 @@ function createStanding(o) {
|
|
|
8857
8858
|
m.failures = 0;
|
|
8858
8859
|
void tick(workspace);
|
|
8859
8860
|
},
|
|
8861
|
+
/** What the stow look (towerstow.ts) asks of the pane: whether the tower prompt polls there (not leaving), whether its line holds the boss's words, and whether the boss took the shell with Ctrl+D. */
|
|
8862
|
+
here(workspace) {
|
|
8863
|
+
const m = mines.get(workspace);
|
|
8864
|
+
return m && { prompt: present3(m) && !m.leaving, draft: present3(m) && m.draft === true, parked: m.parked, ...m.seen ? { pid: m.seen.pid } : {} };
|
|
8865
|
+
},
|
|
8860
8866
|
/** Whether the command was typed into the pane in this terminal (a typing in flight counts); where Herdr lists no terminal, whether it was at or after `at`. */
|
|
8861
8867
|
typedSince: (pane, terminal, at) => {
|
|
8862
8868
|
const record2 = typingIn(pane, terminal);
|
|
@@ -9417,7 +9423,7 @@ var HEADERS = {
|
|
|
9417
9423
|
var REPLACED = "This address does not work here (the sb server may have restarted, or the link expired): on this computer open /boss gui; on a phone scan a new QR code.";
|
|
9418
9424
|
var REPLACED_ZH = "\u9019\u500B\u7DB2\u5740\u5728\u9019\u88E1\u7121\u6CD5\u4F7F\u7528\uFF08sb server \u53EF\u80FD\u91CD\u65B0\u555F\u52D5\u904E\uFF0C\u6216\u9023\u7D50\u5DF2\u904E\u671F\uFF09\uFF1A\u5728\u9019\u53F0\u96FB\u8166\u8ACB\u958B\u555F /boss gui\uFF1B\u5728\u624B\u6A5F\u8ACB\u91CD\u65B0\u6383\u63CF\u65B0\u7684 QR code\u3002";
|
|
9419
9425
|
async function startGui({ auto, board, read: read4, net, call, hub, answered = createAnswered({ load: () => void 0, save: () => {
|
|
9420
|
-
} }), dir = BUNDLE, paired, port: port2 = 0, remotePort = 0, pollMs = 2e3, idleMs = 1e4, pingMs = 15e3, onStop, refuseTake, onRemote, onRemoteOff, onSaveFailed, spawn: spawn3, close, trust, link, server: panel, tower, bindWaitMs = 0, keep:
|
|
9426
|
+
} }), dir = BUNDLE, paired, port: port2 = 0, remotePort = 0, pollMs = 2e3, idleMs = 1e4, pingMs = 15e3, onStop, refuseTake, onRemote, onRemoteOff, onSaveFailed, spawn: spawn3, close, trust, link, server: panel, tower, bindWaitMs = 0, keep: keep3, desk = false, lan, view: firstView = "auto", music, operateHost: host }) {
|
|
9421
9427
|
try {
|
|
9422
9428
|
if (!statSync7(join25(dir, "index.html")).isFile()) throw new Error();
|
|
9423
9429
|
} catch {
|
|
@@ -9457,8 +9463,8 @@ async function startGui({ auto, board, read: read4, net, call, hub, answered = c
|
|
|
9457
9463
|
server.close();
|
|
9458
9464
|
throw error;
|
|
9459
9465
|
}
|
|
9460
|
-
const kept = Boolean(
|
|
9461
|
-
const token = kept ?
|
|
9466
|
+
const kept = Boolean(keep3 && keep3.port === bound && keep3.remotePort === boundRemote);
|
|
9467
|
+
const token = kept ? keep3.token : randomBytes11(16).toString("hex"), csrf = kept ? keep3.csrf : randomBytes11(16).toString("hex");
|
|
9462
9468
|
let view = firstView;
|
|
9463
9469
|
const pageOf = () => themes.page(html.toString("utf8"), view).replace("<head>", `<head>
|
|
9464
9470
|
<base href="/${token}/">
|
|
@@ -9653,8 +9659,8 @@ async function startGui({ auto, board, read: read4, net, call, hub, answered = c
|
|
|
9653
9659
|
if (file3 === "manifest.webmanifest" && who2.remote && remoteManifest) return void res.writeHead(200, { ...HEADERS, "content-type": TYPES3[".webmanifest"] }).end(remoteManifest);
|
|
9654
9660
|
const body2 = themes.fileOf(file3);
|
|
9655
9661
|
if (!body2) return void fail2(404);
|
|
9656
|
-
const
|
|
9657
|
-
res.writeHead(200, { ...HEADERS, ...
|
|
9662
|
+
const keep4 = /\.(woff2|mp3)$|^themes\//.test(file3) ? { "cache-control": "private, max-age=31536000, immutable" } : {};
|
|
9663
|
+
res.writeHead(200, { ...HEADERS, ...keep4, "content-type": TYPES3[extname3(file3)] ?? "application/octet-stream" }).end(body2);
|
|
9658
9664
|
};
|
|
9659
9665
|
const lanHandler = handler("lan", () => server);
|
|
9660
9666
|
routes = { local: handler("local", () => server), remote: handler("remote", () => remoteServer) };
|
|
@@ -9713,7 +9719,7 @@ import { basename as basename5, join as join26, sep as sep4 } from "node:path";
|
|
|
9713
9719
|
|
|
9714
9720
|
// src/nethead.ts
|
|
9715
9721
|
var serviceMark = (service, towerMark) => !service ? towerMark : service.run ? towerMark === "idle" || towerMark === "unknown" ? service.conversation?.idle && !service.conversation.closing ? "idle" : "working" : towerMark : towerMark === "commanding" ? towerMark : "idle";
|
|
9716
|
-
function headUnit({ all, sessions, ps, services, seam, readable: readable2, keep:
|
|
9722
|
+
function headUnit({ all, sessions, ps, services, seam, readable: readable2, keep: keep3 }) {
|
|
9717
9723
|
const workspace = headTowerOf(all), me = sessions.find((s2) => s2.id === seam.key), pane = ps.find((p) => p.pane_id === me?.herdrLocation?.paneId);
|
|
9718
9724
|
const view = workspace ? services?.(workspace.workspace_id) : void 0, { queue, file: runFile, allyFiles: _a, eventFiles: _e, ...rest } = view ?? {};
|
|
9719
9725
|
const chapters = seam.chapters().flatMap((c) => {
|
|
@@ -9721,7 +9727,7 @@ function headUnit({ all, sessions, ps, services, seam, readable: readable2, keep
|
|
|
9721
9727
|
return file4 ? [{ ...c, file: file4 }] : [];
|
|
9722
9728
|
});
|
|
9723
9729
|
const file3 = chapters.at(-1)?.file ?? (view ? readable2(runFile) : void 0), name2 = me?.name ?? "head tower";
|
|
9724
|
-
|
|
9730
|
+
keep3({ key: seam.key, base: workspace?.workspace_id ?? HEAD_KEY, name: name2, role: "head", file: file3, pane: pane?.pane_id, chapters });
|
|
9725
9731
|
const service = view ? rest : void 0, said2 = seam.said(file3), line4 = seam.line(file3);
|
|
9726
9732
|
return { head: { key: seam.key, name: name2, mark: service ? serviceMark(service, me ? sessionMark(me, pane) : "unknown") : "idle", state: service?.state ?? "absent", ...service ? { service: { ...service, allyRuns: [] } } : {}, ...queue?.length ? { queued: queue } : {}, asks: seam.asks(), ...said2 !== void 0 ? { said: said2 } : {}, ...line4 ? { line: line4 } : {} } };
|
|
9727
9733
|
}
|
|
@@ -9780,11 +9786,11 @@ function buildNet({ sessions, panes: ps, workspaces: all, children: children2, s
|
|
|
9780
9786
|
const rowsOf2 = new Map([...joined, ...towers.map((s2) => ({ s: s2, pane: paneOf2(s2) }))].map(({ s: s2, pane }) => [s2.id, children2(pane)]));
|
|
9781
9787
|
const claimed2 = new Set([...rowsOf2.values()].flat().map((r) => r.workspace));
|
|
9782
9788
|
const held2 = /* @__PURE__ */ new Set([...joined.map((j) => j.pane?.pane_id), ...[...rowsOf2.values()].flat().map((r) => r.pane)]);
|
|
9783
|
-
const
|
|
9789
|
+
const keep3 = (r) => (refs.set(r.key, r), r.key);
|
|
9784
9790
|
const outsideKids = new Map(ps.filter((p) => p.agent === "pi" && !held2.has(p.pane_id)).map((p) => [p.pane_id, children2(p)]));
|
|
9785
9791
|
for (const rows of outsideKids.values()) for (const r of rows) if (r.pane) held2.add(r.pane);
|
|
9786
9792
|
const unitsOf3 = (rows, launcher, base) => rows.map((r) => {
|
|
9787
|
-
const key2 =
|
|
9793
|
+
const key2 = keep3({ key: r.id ?? `${launcher}/${r.text}`, base, name: r.text, role: "subagent", file: readable2(r.file), pane: r.pane });
|
|
9788
9794
|
return { id: key2, key: key2, control: Boolean(r.pane), name: r.text, ...r.alias ? { alias: r.alias } : {}, role: "subagent", ...r.duty ? { duty: r.duty } : {}, mark: r.mark, note: r.note, subs: [], ...r.ended && { ended: true } };
|
|
9789
9795
|
});
|
|
9790
9796
|
const subsOf = (launcher, base) => unitsOf3(rowsOf2.get(launcher) ?? [], launcher, base);
|
|
@@ -9796,7 +9802,7 @@ function buildNet({ sessions, panes: ps, workspaces: all, children: children2, s
|
|
|
9796
9802
|
label: group2[0].tab.label,
|
|
9797
9803
|
units: group2.toSorted((a, b) => Number(b.role === "main") - Number(a.role === "main")).map(({ s: s2, pane, role }) => {
|
|
9798
9804
|
const subs = subsOf(s2.id, w.workspace_id), mark3 = commanding(sessionMark(s2, pane), subs.map((c) => c.mark));
|
|
9799
|
-
const key2 =
|
|
9805
|
+
const key2 = keep3({ key: s2.id, base: w.workspace_id, name: s2.name ?? s2.id, role, file: piFile(pane, s2.id), pane: pane?.pane_id }), train = role === "train" ? trainFromToken(pane?.tokens?.sb_train) : void 0, duty = role === "main" && isCoordinatorDuty(pane?.tokens?.sb_duty) ? pane.tokens.sb_duty : void 0;
|
|
9800
9806
|
return { id: key2, key: key2, control: pane?.agent === "pi", name: s2.name ?? s2.id, role, ...train ? { train } : {}, ...duty ? { duty } : {}, mark: mark3, note: note(mark3, s2.status), subs };
|
|
9801
9807
|
})
|
|
9802
9808
|
}));
|
|
@@ -9807,27 +9813,27 @@ function buildNet({ sessions, panes: ps, workspaces: all, children: children2, s
|
|
|
9807
9813
|
const key2 = s2?.id ?? (file3 && basename5(file3, ".jsonl").split("_").pop());
|
|
9808
9814
|
if (!key2) return [];
|
|
9809
9815
|
const subs = unitsOf3(outsideKids.get(p.pane_id) ?? [], key2, w.workspace_id), name2 = s2?.name ?? p.label ?? key2.slice(0, 8), mark3 = commanding(s2 ? sessionMark(s2, p) : markOf(p.agent_status), subs.map((c) => c.mark));
|
|
9810
|
-
|
|
9816
|
+
keep3({ key: key2, base: w.workspace_id, name: name2, role: "outside", file: readable2(file3, s2?.id), pane: p.pane_id });
|
|
9811
9817
|
return [{ id: key2, key: key2, control: true, name: name2, role: "outside", mark: mark3, note: note(mark3, s2?.status), subs }];
|
|
9812
9818
|
});
|
|
9813
9819
|
const marks2 = [...towerSubs.map((c) => c.mark), ...tabs2.flatMap((t) => t.units.flatMap((u) => [u.mark, ...u.subs.map((c) => c.mark)])), ...outposts.map((o) => o.mark)];
|
|
9814
9820
|
const mark2 = ["waiting", "working"].find((m) => marks2.includes(m)) ?? markOf(w.agent_status);
|
|
9815
9821
|
if (!tower && !tabs2.length) return [];
|
|
9816
9822
|
const view = tower ? services?.(w.workspace_id) : void 0, { queue, file: runFile, allyFiles, eventFiles, ...service } = view ?? {};
|
|
9817
|
-
const named = tower &&
|
|
9823
|
+
const named = tower && keep3({ key: tower.id, base: w.workspace_id, name: tower.name ?? tower.id, role: "tower", file: view ? readable2(runFile) : piFile(towerPane, tower.id), pane: towerPane?.pane_id });
|
|
9818
9824
|
if (tower && named) towerKeys.set(tower.id, named);
|
|
9819
9825
|
const allyRuns = (service.allyRuns ?? []).map((a) => {
|
|
9820
9826
|
const file3 = readable2(allyFiles?.[a.id]);
|
|
9821
|
-
return file3 ? { ...a, key:
|
|
9827
|
+
return file3 ? { ...a, key: keep3({ key: `ally-${a.id}`, base: w.workspace_id, name: a.label, role: "ally", file: file3 }) } : a;
|
|
9822
9828
|
});
|
|
9823
9829
|
const localRuns = (service.localRuns ?? []).map((r) => {
|
|
9824
9830
|
const file3 = r.kind === "event" ? readable2(eventFiles?.[r.id]) : void 0;
|
|
9825
|
-
return file3 ? { ...r, key:
|
|
9831
|
+
return file3 ? { ...r, key: keep3({ key: `run-${r.id}`, base: w.workspace_id, name: `${r.id.slice(0, 8)}`, role: "run", file: file3 }) } : r;
|
|
9826
9832
|
});
|
|
9827
9833
|
const towerMark = tower ? commanding(sessionMark(tower, towerPane), towerSubs.map((c) => c.mark)) : "unknown";
|
|
9828
9834
|
return [{ id: w.workspace_id, label: w.label, mark: mark2, tower: tower && named ? { name: tower.name ?? tower.id, mark: serviceMark(view ? service : void 0, towerMark), key: named, control: view ? true : towerPane?.agent === "pi", ...view ? { service: { ...service, allyRuns, ...localRuns.length ? { localRuns } : {} }, ...queue?.length ? { queued: queue } : {} } : {}, subs: towerSubs } : null, tabs: tabs2, outposts, outside }];
|
|
9829
9835
|
});
|
|
9830
|
-
const headed = head ? headUnit({ all, sessions, ps, services, seam: head, readable: (file3) => readable2(file3), keep:
|
|
9836
|
+
const headed = head ? headUnit({ all, sessions, ps, services, seam: head, readable: (file3) => readable2(file3), keep: keep3 }) : void 0;
|
|
9831
9837
|
const keys = new Map(towerKeys);
|
|
9832
9838
|
for (const b of bases) for (const u of [...b.tabs.flatMap((t) => t.units), ...b.outside]) keys.set(u.id, u.key);
|
|
9833
9839
|
const holders2 = [...bases.flatMap((b) => b.tower?.service?.memory ? [b.tower.service] : []), ...headed?.head.service?.memory ? [headed.head.service] : []];
|
|
@@ -10043,7 +10049,7 @@ async function makeDir(parent, name2, home = homedir7(), hidden = platformHidden
|
|
|
10043
10049
|
}
|
|
10044
10050
|
function createSpawn({ run: run2, sleep: sleep2, call, live, sessionAt, home = homedir7(), hidden = platformHidden, deploys = createDeploys(), trustDir: trustDir2, openings = createOpenings(), intents, note, lock = { busy: false } }) {
|
|
10045
10051
|
const pick3 = (path) => pickable(path, home, hidden);
|
|
10046
|
-
const
|
|
10052
|
+
const keep3 = (id2, opening3) => {
|
|
10047
10053
|
try {
|
|
10048
10054
|
openings.set(id2, opening3);
|
|
10049
10055
|
} catch (error) {
|
|
@@ -10066,14 +10072,14 @@ function createSpawn({ run: run2, sleep: sleep2, call, live, sessionAt, home = h
|
|
|
10066
10072
|
};
|
|
10067
10073
|
const places = async () => {
|
|
10068
10074
|
const root = await realpath2(home).catch(() => home), seen = /* @__PURE__ */ new Set(), recent = [];
|
|
10069
|
-
const
|
|
10075
|
+
const keep4 = async (path) => {
|
|
10070
10076
|
const dir = await pick3(path);
|
|
10071
10077
|
if (dir && dir !== root && !seen.has(dir)) seen.add(dir), recent.push(dir);
|
|
10072
10078
|
};
|
|
10073
10079
|
for (const ws of await workspaces(run2).catch(() => [])) {
|
|
10074
10080
|
if (isSub(ws) || isHead(ws)) continue;
|
|
10075
|
-
await
|
|
10076
|
-
for (const pane of await panes(run2, ws.workspace_id).catch(() => [])) await
|
|
10081
|
+
await keep4(ws.worktree?.checkout_path);
|
|
10082
|
+
for (const pane of await panes(run2, ws.workspace_id).catch(() => [])) await keep4(pane.cwd);
|
|
10077
10083
|
}
|
|
10078
10084
|
const named = await Promise.all(["Desktop", "Documents"].map(async (name2) => [name2, await pick3(join28(root, name2))]));
|
|
10079
10085
|
return { home: root, sep: sep5, places: named.flatMap(([name2, path]) => path ? [{ name: name2, path }] : []), recent: recent.slice(0, 10) };
|
|
@@ -10179,7 +10185,7 @@ function createSpawn({ run: run2, sleep: sleep2, call, live, sessionAt, home = h
|
|
|
10179
10185
|
await awaitJoin(d, pane.pane_id, joinWaitMs);
|
|
10180
10186
|
let delivery = had.delivery;
|
|
10181
10187
|
if (prompt && (delivery === "none" || delivery === "pending")) {
|
|
10182
|
-
const failed3 = await deliver(d, pane.pane_id, prompt, (state) => void
|
|
10188
|
+
const failed3 = await deliver(d, pane.pane_id, prompt, (state) => void keep3(id2, { ...had, delivery: delivery = state }));
|
|
10183
10189
|
if (failed3) return failed3;
|
|
10184
10190
|
} else if (prompt) d.go("deliver");
|
|
10185
10191
|
return opened(had.workspace, pane.tab_id, pane.pane_id, delivered(d, delivery, Boolean(prompt)));
|
|
@@ -10195,9 +10201,9 @@ function createSpawn({ run: run2, sleep: sleep2, call, live, sessionAt, home = h
|
|
|
10195
10201
|
let delivery = prompt ? "pending" : "none";
|
|
10196
10202
|
const failed3 = await orClose(["workspace", "close", workspaceId], async () => {
|
|
10197
10203
|
if (id2) {
|
|
10198
|
-
|
|
10204
|
+
keep3(id2, { ...record2, delivery });
|
|
10199
10205
|
}
|
|
10200
|
-
return boot(d, paneId, `member \xB7 ${basename6(dir) || dir}`, prompt, void 0, joinWaitMs, id2 ? (state) => void
|
|
10206
|
+
return boot(d, paneId, `member \xB7 ${basename6(dir) || dir}`, prompt, void 0, joinWaitMs, id2 ? (state) => void keep3(id2, { ...record2, delivery: delivery = state }) : (state) => void (delivery = state), dir);
|
|
10201
10207
|
}).catch((error) => {
|
|
10202
10208
|
if (id2) try {
|
|
10203
10209
|
openings.drop(id2);
|
|
@@ -12681,9 +12687,9 @@ function createGuiHost(o) {
|
|
|
12681
12687
|
const recorded = () => {
|
|
12682
12688
|
const record2 = readRecord(slot), seen = readRecord2(dir), was = record2?.gui, read4 = readSecrets(dir);
|
|
12683
12689
|
const stored = "secrets" in read4 && [was?.token, seen?.token].some((t) => t !== void 0 && t !== read4.secrets.token) ? { lost: "stale" } : read4;
|
|
12684
|
-
const
|
|
12685
|
-
const port2 = was?.port ?? seen?.port ??
|
|
12686
|
-
return { port: port2, remotePort: (seen && seen.port === port2 ? seen.remotePort : void 0) ?? (
|
|
12690
|
+
const keep3 = "secrets" in stored ? stored.secrets : void 0;
|
|
12691
|
+
const port2 = was?.port ?? seen?.port ?? keep3?.port;
|
|
12692
|
+
return { port: port2, remotePort: (seen && seen.port === port2 ? seen.remotePort : void 0) ?? (keep3 && keep3.port === port2 ? keep3.remotePort : void 0), keep: keep3, lost: "lost" in stored ? stored.lost : void 0, stopped: Boolean(was?.stopped) };
|
|
12687
12693
|
};
|
|
12688
12694
|
const mark2 = (change) => updateRecord(slot, (r) => {
|
|
12689
12695
|
if (r.pid !== pid) return void 0;
|
|
@@ -13401,8 +13407,8 @@ ${dialogId}`;
|
|
|
13401
13407
|
return this.views.get(this.key(device, dialogId));
|
|
13402
13408
|
}
|
|
13403
13409
|
/** Those of devices `keep` still counts as members; an ended one only until `CLOSED_MS` after it ended, and an open one only until `OPEN_STALE_MS` after the device last sent it. */
|
|
13404
|
-
list(
|
|
13405
|
-
for (const [k, v] of this.views) if (!
|
|
13410
|
+
list(keep3, now) {
|
|
13411
|
+
for (const [k, v] of this.views) if (!keep3(v) || (v.closed ? now - v.closed.at > CLOSED_MS : now - v.at > OPEN_STALE_MS)) this.views.delete(k);
|
|
13406
13412
|
return [...this.views.values()];
|
|
13407
13413
|
}
|
|
13408
13414
|
};
|
|
@@ -20127,8 +20133,8 @@ var PAST = "#";
|
|
|
20127
20133
|
var changedAt = (held2) => held2.file.states.at(-1)?.at ?? "";
|
|
20128
20134
|
var newestFiles = (list2) => {
|
|
20129
20135
|
if (list2.length <= MAX_FILES) return list2;
|
|
20130
|
-
const
|
|
20131
|
-
return list2.filter((h) =>
|
|
20136
|
+
const keep3 = new Set([...list2].sort((a, b) => changedAt(a) < changedAt(b) ? 1 : changedAt(a) > changedAt(b) ? -1 : 0).slice(0, MAX_FILES));
|
|
20137
|
+
return list2.filter((h) => keep3.has(h));
|
|
20132
20138
|
};
|
|
20133
20139
|
var blankUser = (text14) => text14.replace(/\/\/[^/@\s'"]+@/g, "//***@");
|
|
20134
20140
|
var firstLine2 = (error) => blankUser(String(error.stderr || error.message).trim().split("\n")[0]).slice(0, 200);
|
|
@@ -26295,6 +26301,158 @@ function runApprover(o) {
|
|
|
26295
26301
|
};
|
|
26296
26302
|
}
|
|
26297
26303
|
|
|
26304
|
+
// src/server/towerstow.ts
|
|
26305
|
+
var STOW = { intervalMs: 3e3, idleMs: 3e4 };
|
|
26306
|
+
var keep2 = (why2) => ({ stow: false, why: why2 });
|
|
26307
|
+
function idleGate(f) {
|
|
26308
|
+
if (f.head) return keep2("head");
|
|
26309
|
+
if (f.headless) return keep2("headless");
|
|
26310
|
+
if (!f.ready) return keep2("unready");
|
|
26311
|
+
if (f.cards > 0) return keep2("cards");
|
|
26312
|
+
if (f.run || f.state === "waking" || f.state === "running" || f.state === "closing") return keep2("run");
|
|
26313
|
+
if (f.state === "held") return keep2("held");
|
|
26314
|
+
if (f.queued > 0) return keep2("queued");
|
|
26315
|
+
if (f.soon) return keep2("soon");
|
|
26316
|
+
if (f.idleFor < f.idleMs) return keep2("recent");
|
|
26317
|
+
return { stow: true };
|
|
26318
|
+
}
|
|
26319
|
+
function paneGate(f) {
|
|
26320
|
+
if (!f.pane) return keep2("gone");
|
|
26321
|
+
if (f.pane.agent && !isStandin(f.pane)) return keep2("agent");
|
|
26322
|
+
if (f.inTab > 1) return keep2("tab");
|
|
26323
|
+
if (f.inWorkspace <= f.inTab) return keep2("last");
|
|
26324
|
+
if (f.parked) return keep2("parked");
|
|
26325
|
+
if (!f.prompt) return keep2("prompt");
|
|
26326
|
+
if (f.draft) return keep2("draft");
|
|
26327
|
+
if (f.foreground !== "clean") return keep2(f.foreground);
|
|
26328
|
+
return { stow: true };
|
|
26329
|
+
}
|
|
26330
|
+
function foregroundOf(info, workspace, promptPid) {
|
|
26331
|
+
const list2 = Array.isArray(info?.foreground_processes) ? info.foreground_processes : [];
|
|
26332
|
+
if (!list2.length) return "unknown";
|
|
26333
|
+
const shell2 = typeof info?.shell_pid === "number" ? info.shell_pid : void 0, prompt = new RegExp(`\\bprompt --workspace ${workspace.replace(/[^\w.:-]/g, "")}(\\s|$)`);
|
|
26334
|
+
return list2.every((p) => (shell2 !== void 0 ? p.pid === shell2 : list2.length === 1 && SHELLS2.has(nameOf2(p))) || promptPid !== void 0 && p.pid === promptPid || prompt.test(p.cmdline ?? "")) ? "clean" : "program";
|
|
26335
|
+
}
|
|
26336
|
+
function seatOpen(f) {
|
|
26337
|
+
if (f.label === void 0) return "gone";
|
|
26338
|
+
return f.seated || f.label === f.record ? "open" : "stranger";
|
|
26339
|
+
}
|
|
26340
|
+
function createStow(o) {
|
|
26341
|
+
const t = { ...STOW, ...o.timers };
|
|
26342
|
+
const { run: run2, log } = o;
|
|
26343
|
+
const since = /* @__PURE__ */ new Map(), said2 = /* @__PURE__ */ new Map();
|
|
26344
|
+
const opening3 = /* @__PURE__ */ new Map();
|
|
26345
|
+
let timer, looking = Promise.resolve(), stopped = false;
|
|
26346
|
+
const error = (code, text14) => log.line("error", { code, text: text14.slice(0, 300) });
|
|
26347
|
+
const processInfo = (pane) => run2(["pane", "process-info", "--pane", pane]).then((x) => JSON.parse(x).result?.process_info, () => void 0);
|
|
26348
|
+
const idleOf = (l, at) => {
|
|
26349
|
+
const ws = o.record(l).workspace, status = o.status(ws), from = since.get(ws);
|
|
26350
|
+
return idleGate({ head: o.head(l), headless: o.headless(), ready: o.ready(l), cards: o.cards(l), state: status?.state, run: Boolean(status?.run) || (status?.allyRuns.length ?? 0) > 0, queued: o.queued(ws), soon: o.soon(ws, t.idleMs), idleFor: from ? at - from.at : 0, idleMs: t.idleMs });
|
|
26351
|
+
};
|
|
26352
|
+
const said1 = (ws, why2) => {
|
|
26353
|
+
if (said2.get(ws) === why2) return;
|
|
26354
|
+
said2.set(ws, why2);
|
|
26355
|
+
log.line("tower-stow-kept", { workspace: ws, why: why2 });
|
|
26356
|
+
};
|
|
26357
|
+
const close = async (l, record2) => {
|
|
26358
|
+
const ws = record2.workspace, undo = o.hold(l);
|
|
26359
|
+
const bare2 = { ...record2, pane: "", tab: "" };
|
|
26360
|
+
o.place(l, bare2);
|
|
26361
|
+
try {
|
|
26362
|
+
await run2(["pane", "close", record2.pane]);
|
|
26363
|
+
} catch (cause) {
|
|
26364
|
+
o.place(l, record2);
|
|
26365
|
+
undo();
|
|
26366
|
+
return error("tower-stow", `${ws}: ${cause.message}`);
|
|
26367
|
+
}
|
|
26368
|
+
since.delete(ws);
|
|
26369
|
+
said2.delete(ws);
|
|
26370
|
+
log.line("tower-stowed", { workspace: ws, pane: record2.pane });
|
|
26371
|
+
await o.reseat(l, bare2, false);
|
|
26372
|
+
};
|
|
26373
|
+
const lookAt = async (l) => {
|
|
26374
|
+
const record2 = o.record(l), ws = record2.workspace;
|
|
26375
|
+
if (o.head(l) || o.headless() || opening3.has(ws)) return;
|
|
26376
|
+
if (!record2.pane) {
|
|
26377
|
+
if (!o.seated(l)) {
|
|
26378
|
+
const listed = await workspaces(run2).catch(() => void 0), seat = listed && seatOpen({ seated: false, label: listed.find((w) => w.workspace_id === ws)?.label, record: record2.label });
|
|
26379
|
+
if (seat === "open") await o.seat(l);
|
|
26380
|
+
else if (seat === "stranger" && !o.recovering()) return void await o.lose(l, "its workspace carries another label after a Herdr restart", true);
|
|
26381
|
+
}
|
|
26382
|
+
if (o.ready(l) && o.cards(l) > 0) await open9(ws, "cards");
|
|
26383
|
+
return;
|
|
26384
|
+
}
|
|
26385
|
+
const at = o.now();
|
|
26386
|
+
if (since.get(ws)?.pane !== record2.pane) since.set(ws, { pane: record2.pane, at });
|
|
26387
|
+
const idle = idleOf(l, at);
|
|
26388
|
+
if (!idle.stow) {
|
|
26389
|
+
if (idle.why !== "recent") since.set(ws, { pane: record2.pane, at });
|
|
26390
|
+
return;
|
|
26391
|
+
}
|
|
26392
|
+
const all = await panes(run2, ws).catch(() => void 0);
|
|
26393
|
+
if (!all) return;
|
|
26394
|
+
const pane = all.find((p) => p.pane_id === record2.pane), here = o.prompt(ws);
|
|
26395
|
+
const v = paneGate({ ...pane ? { pane } : {}, inTab: pane ? all.filter((p) => p.tab_id === pane.tab_id).length : 0, inWorkspace: all.length, parked: here?.parked === true, prompt: here?.prompt === true, draft: here?.draft === true, foreground: pane ? foregroundOf(await processInfo(record2.pane), ws, here?.pid) : "unknown" });
|
|
26396
|
+
if (!v.stow) {
|
|
26397
|
+
if (v.why === "draft") since.set(ws, { pane: record2.pane, at: o.now() });
|
|
26398
|
+
return said1(ws, v.why);
|
|
26399
|
+
}
|
|
26400
|
+
if (stopped || o.current(ws) !== l || o.record(l) !== record2 || !idleOf(l, o.now()).stow || o.prompt(ws)?.draft) return;
|
|
26401
|
+
await close(l, record2);
|
|
26402
|
+
};
|
|
26403
|
+
const look2 = () => looking = looking.then(async () => {
|
|
26404
|
+
for (const l of o.list()) {
|
|
26405
|
+
if (stopped) return;
|
|
26406
|
+
await lookAt(l).catch((cause) => error("tower-stow", cause.message));
|
|
26407
|
+
}
|
|
26408
|
+
});
|
|
26409
|
+
const open9 = (workspace, why2) => {
|
|
26410
|
+
const pending = opening3.get(workspace) ?? (async () => {
|
|
26411
|
+
const l = o.current(workspace);
|
|
26412
|
+
if (!l || o.record(l).pane) return l;
|
|
26413
|
+
const record2 = o.record(l), target2 = (await workspaces(run2)).find((w) => w.workspace_id === workspace);
|
|
26414
|
+
const verdict = seatOpen({ seated: o.seated(l), label: target2?.label, record: record2.label });
|
|
26415
|
+
if (verdict === "gone") throw new Error(`the workspace of ${record2.id} is gone`);
|
|
26416
|
+
if (verdict === "stranger") return void await o.lose(l, "its workspace carries another label after a Herdr restart", true);
|
|
26417
|
+
const undo = o.hold(l);
|
|
26418
|
+
let made;
|
|
26419
|
+
try {
|
|
26420
|
+
const dir = record2.cwd ?? target2.worktree?.checkout_path ?? o.stateDir;
|
|
26421
|
+
made = await createTab(run2, workspace, dir, [], TOWER_LABEL);
|
|
26422
|
+
if (o.current(workspace) !== l) throw new Error("the service ended while its tab was made");
|
|
26423
|
+
await report(run2, "pane", made.paneId, { sb_role: "tower" });
|
|
26424
|
+
await o.api("tab.move", { tab_id: made.tabId, insert_index: 0 }).catch((cause) => error("tab-move", cause.message));
|
|
26425
|
+
log.line("tower-unstowed", { workspace, pane: made.paneId, why: why2 });
|
|
26426
|
+
return await o.reseat(l, { ...record2, pane: made.paneId, tab: made.tabId, cwd: dir }, true);
|
|
26427
|
+
} catch (cause) {
|
|
26428
|
+
undo();
|
|
26429
|
+
if (made) await run2(["pane", "close", made.paneId]).catch(() => {
|
|
26430
|
+
});
|
|
26431
|
+
throw cause;
|
|
26432
|
+
}
|
|
26433
|
+
})().finally(() => opening3.delete(workspace));
|
|
26434
|
+
opening3.set(workspace, pending);
|
|
26435
|
+
return pending;
|
|
26436
|
+
};
|
|
26437
|
+
return {
|
|
26438
|
+
look: look2,
|
|
26439
|
+
open: open9,
|
|
26440
|
+
start() {
|
|
26441
|
+
timer ??= setInterval(() => void look2(), t.intervalMs);
|
|
26442
|
+
timer.unref();
|
|
26443
|
+
},
|
|
26444
|
+
async stop() {
|
|
26445
|
+
stopped = true;
|
|
26446
|
+
clearInterval(timer);
|
|
26447
|
+
timer = void 0;
|
|
26448
|
+
await looking.catch(() => {
|
|
26449
|
+
});
|
|
26450
|
+
await Promise.all([...opening3.values()].map((p) => p.catch(() => {
|
|
26451
|
+
})));
|
|
26452
|
+
}
|
|
26453
|
+
};
|
|
26454
|
+
}
|
|
26455
|
+
|
|
26298
26456
|
// src/server/runchild.ts
|
|
26299
26457
|
import { execFile as execFile2, spawn as nodeSpawn } from "node:child_process";
|
|
26300
26458
|
import { randomBytes as randomBytes25 } from "node:crypto";
|
|
@@ -27067,6 +27225,7 @@ function createRuns2(o) {
|
|
|
27067
27225
|
const begin = async (svc) => {
|
|
27068
27226
|
if (stopped || svc.run || svc.state !== "standing" || !o.enabled() || !waitingOf(svc).some((e) => !e.quiet)) return;
|
|
27069
27227
|
if (!svc.ref.live()) return;
|
|
27228
|
+
if (!headlessOn() && !svc.ref.record().pane) return void svc.ref.seat?.("run");
|
|
27070
27229
|
if (slots >= o.max()) return void blocked.add(svc);
|
|
27071
27230
|
slots++;
|
|
27072
27231
|
svc.state = "waking";
|
|
@@ -27274,6 +27433,7 @@ function createRuns2(o) {
|
|
|
27274
27433
|
for (const { device, items } of devicesWaiting(svc)) {
|
|
27275
27434
|
if (stopped || !o.enabled() || svc.refusedAt !== void 0 && now() - svc.refusedAt < t.refuse) return;
|
|
27276
27435
|
if (!svc.ref.live()) return;
|
|
27436
|
+
if (!headlessOn() && !svc.ref.record().pane) return void svc.ref.seat?.("ally");
|
|
27277
27437
|
if (slots >= o.max()) return void blocked.add(svc);
|
|
27278
27438
|
await beginAlly(svc, device, items).catch((cause) => error("ally-begin", cause.message));
|
|
27279
27439
|
}
|
|
@@ -28720,6 +28880,7 @@ function createTowers(o) {
|
|
|
28720
28880
|
clearDigest: (keys) => digest.drop(l.record.workspace, keys),
|
|
28721
28881
|
renewPane: (runId) => renew(l, runId),
|
|
28722
28882
|
renewing: () => l.renewing === true,
|
|
28883
|
+
seat: (why2) => void stow.open(l.record.workspace, why2).catch((cause) => error("tower-seat", cause.message)),
|
|
28723
28884
|
// The run that was shown an expired wait has polled: it will not be shown again (towermemory.ts).
|
|
28724
28885
|
shown: (ids) => {
|
|
28725
28886
|
try {
|
|
@@ -28884,8 +29045,8 @@ function createTowers(o) {
|
|
|
28884
29045
|
const tell2 = (to, text14, wait2) => l.reach ? l.reach.post(to, text14, "link_wait_state", "session", false, void 0, void 0, { ...wait2 ? { wait: wait2 } : {}, peer: { label: route.label, short: route.short } }) : Promise.resolve();
|
|
28885
29046
|
void forwardOpenedWait({ ws, now, identity: l.record.id, log: (event, facts) => log.line(event, facts), tell: tell2, ...o.link ? { link: o.link } : {}, ...o.asks ? { asks: o.asks } : {}, ...o.waits ? { waits: o.waits } : {} }, route, { id: from.id, name: phrase9(from.name ?? from.id, 40) }, message.id, message.content.text).catch((cause) => error("ally-wait", cause.message));
|
|
28886
29047
|
} else if (route && (!local || route.at >= local.at)) {
|
|
28887
|
-
const
|
|
28888
|
-
if (!workerReport({ slot, workspace: ws, now, log: (event, facts) => log.line(event, facts), sweep: () => void workerEnds.sweep(), send: (device, text14, ask) => o.link ? o.link({ op: "send", device, text: text14, reply: false, inReplyTo: ask }, l.record.id, true) : Promise.reject(new Error("no link holder")) }, route, message.content.text,
|
|
29048
|
+
const keep3 = () => addAnswer(slot, ws, { id: `${Date.now().toString(36)}-${message.id}`.slice(0, 80), device: route.device, label: route.label, short: route.short, team: route.team, teamName: route.teamName, from: { id: from.id, name: phrase9(from.name ?? from.id, 40) }, text: message.content.text, at: now(), ...route.ask ? { ask: route.ask } : {} }, now());
|
|
29049
|
+
if (!workerReport({ slot, workspace: ws, now, log: (event, facts) => log.line(event, facts), sweep: () => void workerEnds.sweep(), send: (device, text14, ask) => o.link ? o.link({ op: "send", device, text: text14, reply: false, inReplyTo: ask }, l.record.id, true) : Promise.reject(new Error("no link holder")) }, route, message.content.text, keep3)) keep3();
|
|
28889
29050
|
spendRoute(slot, ws, route, now());
|
|
28890
29051
|
seen.add(from.id, message.id, message.content.text);
|
|
28891
29052
|
log.line("tower-ally-answer", { workspace: ws, from: from.id });
|
|
@@ -29215,6 +29376,40 @@ function createTowers(o) {
|
|
|
29215
29376
|
if (l.client) await release(l).then(() => services.set(l.record.workspace, adopt(l.record, false, true)));
|
|
29216
29377
|
};
|
|
29217
29378
|
const look2 = () => looking = looking.then(reconcile).catch((cause) => error("reconcile", cause.message));
|
|
29379
|
+
const reseat = async (l, record2, fresh) => {
|
|
29380
|
+
l.record = record2;
|
|
29381
|
+
writeService(slot, record2);
|
|
29382
|
+
await release(l);
|
|
29383
|
+
await standing2.detach(record2.workspace);
|
|
29384
|
+
if (services.get(record2.workspace) === l) services.delete(record2.workspace);
|
|
29385
|
+
return adopt(record2, fresh, true);
|
|
29386
|
+
};
|
|
29387
|
+
const stow = createStow({
|
|
29388
|
+
run: run2,
|
|
29389
|
+
api: cfg.api,
|
|
29390
|
+
log,
|
|
29391
|
+
now,
|
|
29392
|
+
stateDir: slot.stateDir,
|
|
29393
|
+
...o.stow ? { timers: o.stow } : {},
|
|
29394
|
+
list: () => [...services.values()].filter((l) => !l.stopped),
|
|
29395
|
+
current: (ws) => ((l) => l && !l.stopped ? l : void 0)(services.get(ws)),
|
|
29396
|
+
record: (l) => l.record,
|
|
29397
|
+
place: (l, record2) => void (l.record = record2),
|
|
29398
|
+
head: isHeadL,
|
|
29399
|
+
seated: (l) => l.seated,
|
|
29400
|
+
recovering: () => now() < recoverUntil,
|
|
29401
|
+
ready: (l) => l.state === "live" && l.seated && !l.stopped && !l.renewing && Boolean(l.client?.isConnected()),
|
|
29402
|
+
seat: async (l) => void (l.seated = true, await publish(l)),
|
|
29403
|
+
hold: (l) => ((was) => (l.state = "registering", l.renewing = true, () => void (l.state = was, l.renewing = false)))(l.state),
|
|
29404
|
+
headless,
|
|
29405
|
+
status: (ws) => runs2.status(ws),
|
|
29406
|
+
queued: (ws) => runs2.queue(ws).filter((e) => !e.quiet).length,
|
|
29407
|
+
soon: (ws, ms4) => runs2.startsWithin(ws, ms4),
|
|
29408
|
+
cards: (l) => cardsFor(l),
|
|
29409
|
+
prompt: (ws) => standing2.here(ws),
|
|
29410
|
+
reseat,
|
|
29411
|
+
lose
|
|
29412
|
+
});
|
|
29218
29413
|
const residentOf = async (l) => {
|
|
29219
29414
|
if (isHeadL(l)) return void 0;
|
|
29220
29415
|
const all = await workspaces(run2).catch(() => void 0);
|
|
@@ -29349,6 +29544,7 @@ function createTowers(o) {
|
|
|
29349
29544
|
}, poll));
|
|
29350
29545
|
timers.forEach((t) => t.unref());
|
|
29351
29546
|
standing2.start();
|
|
29547
|
+
stow.start();
|
|
29352
29548
|
await Promise.race([Promise.all([...adopted, ...adoptedHead].map((l) => l.starting)), sleep2(o.registerMs ?? REGISTER_WAIT_MS)]);
|
|
29353
29549
|
await look2();
|
|
29354
29550
|
loadedAll = true;
|
|
@@ -29406,6 +29602,10 @@ function createTowers(o) {
|
|
|
29406
29602
|
},
|
|
29407
29603
|
typed: () => standing2.typedSince(claim.pane, seen.terminal, claim.at)
|
|
29408
29604
|
});
|
|
29605
|
+
if (existing && !existing.stopped && tabless(existing) && !hint && !claim) {
|
|
29606
|
+
const l2 = await stow.open(ws, "ensure");
|
|
29607
|
+
if (l2) return await Promise.race([l2.starting, sleep2(o.registerMs ?? REGISTER_WAIT_MS)]), answer(l2, false);
|
|
29608
|
+
}
|
|
29409
29609
|
if (existing && !existing.stopped) {
|
|
29410
29610
|
const here2 = await locate(existing, false);
|
|
29411
29611
|
const stranger = here2 && !existing.seated && await prove(existing, here2) === "stranger";
|
|
@@ -29465,14 +29665,7 @@ function createTowers(o) {
|
|
|
29465
29665
|
await cfg.api("tab.move", { tab_id: tab.tabId, insert_index: 0 }).catch((cause) => error("tab-move", cause.message));
|
|
29466
29666
|
record2 = { ...record2, pane: tab.paneId, tab: tab.tabId };
|
|
29467
29667
|
}
|
|
29468
|
-
writeService(slot, record2);
|
|
29469
|
-
if (existing) {
|
|
29470
|
-
existing.record = record2;
|
|
29471
|
-
await release(existing);
|
|
29472
|
-
await standing2.detach(ws);
|
|
29473
|
-
services.delete(ws);
|
|
29474
|
-
}
|
|
29475
|
-
const l = adopt(record2, view, true);
|
|
29668
|
+
const l = existing ? await reseat(existing, record2, view) : (writeService(slot, record2), adopt(record2, view, true));
|
|
29476
29669
|
log.line(existing ? "tower-viewer" : "tower-opened", { workspace: ws, id: record2.id, ...view ? { pane: record2.pane, tab: record2.tab } : { tab: "none" } });
|
|
29477
29670
|
await Promise.race([l.starting, sleep2(o.registerMs ?? REGISTER_WAIT_MS)]);
|
|
29478
29671
|
return answer(l, !existing);
|
|
@@ -29889,9 +30082,9 @@ ${d.message}`, at: new Date(now()).toISOString(), messageId: `quiet:${createHash
|
|
|
29889
30082
|
}
|
|
29890
30083
|
},
|
|
29891
30084
|
runs: runs2,
|
|
29892
|
-
async prompt(cmd, workspace, pid, answering = false) {
|
|
30085
|
+
async prompt(cmd, workspace, pid, answering = false, draft = false) {
|
|
29893
30086
|
if (cmd === "prompt-poll") {
|
|
29894
|
-
const polled = standing2.poll(workspace, pid);
|
|
30087
|
+
const polled = standing2.poll(workspace, pid, draft);
|
|
29895
30088
|
return polled.ok ? { ...polled, ...api2.waitDigest(workspace), ...runs2.answering(workspace, answering && !polled.leave) ? { holding: true } : {} } : polled;
|
|
29896
30089
|
}
|
|
29897
30090
|
return cmd === "prompt-leave" ? standing2.leave(workspace, pid) : standing2.gone(workspace, pid);
|
|
@@ -29899,7 +30092,7 @@ ${d.message}`, at: new Date(now()).toISOString(), messageId: `quiet:${createHash
|
|
|
29899
30092
|
async stop(opts) {
|
|
29900
30093
|
stopped = true;
|
|
29901
30094
|
offAuto?.();
|
|
29902
|
-
await standing2.stop();
|
|
30095
|
+
await Promise.all([standing2.stop(), stow.stop()]);
|
|
29903
30096
|
await runs2.stop(opts);
|
|
29904
30097
|
timers.forEach(clearInterval);
|
|
29905
30098
|
clearTimeout(republishTimer);
|
|
@@ -30508,7 +30701,7 @@ async function runServer(o) {
|
|
|
30508
30701
|
const pid2 = request.pid;
|
|
30509
30702
|
if (!towers || !towers.loaded()) return Promise.resolve({ ok: false, error: "the server is still starting" });
|
|
30510
30703
|
if (!workspace || typeof pid2 !== "number" || !Number.isInteger(pid2) || pid2 <= 0) return Promise.resolve({ ok: false, error: `${request.cmd} needs a workspace and the prompt's pid` });
|
|
30511
|
-
return towers.prompt(request.cmd, workspace, pid2, request.answering === true && !unattended()).then((reply3) => withLines(towers, workspace, request.cursor, unattended() && "label" in reply3 ? { ...reply3, unattended: true } : reply3));
|
|
30704
|
+
return towers.prompt(request.cmd, workspace, pid2, request.answering === true && !unattended(), request.draft === true).then((reply3) => withLines(towers, workspace, request.cursor, unattended() && "label" in reply3 ? { ...reply3, unattended: true } : reply3));
|
|
30512
30705
|
}
|
|
30513
30706
|
// The boss's memory (towermemory.ts `memoryRequest`): `/boss memory` in a pi session is the GUI panel's request on the same function. A run's token never gets here (rungate.ts refuses it).
|
|
30514
30707
|
// `via: "ask"` is the press of a dialog sb drew for an agent's `boss_wait_ask` (waitask.ts); the GUI's door is its own route's, never a client's word (`doorOf`).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-straw-boss",
|
|
3
|
-
"version": "0.111.
|
|
3
|
+
"version": "0.111.3",
|
|
4
4
|
"description": "Straw Boss coordination for pi in Herdr: sessions join a tab's net by choice, the first joiner is its main agent, a workspace tower opens on demand with a live monitoring dashboard, and boss_broadcast reaches the rest",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/src/server/main.ts
CHANGED
|
@@ -544,8 +544,8 @@ export async function runServer(o: ServerOptions): Promise<ServerHandle> {
|
|
|
544
544
|
const pid = request.pid;
|
|
545
545
|
if (!towers || !towers.loaded()) return Promise.resolve({ ok: false, error: "the server is still starting" });
|
|
546
546
|
if (!workspace || typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return Promise.resolve({ ok: false, error: `${request.cmd} needs a workspace and the prompt's pid` });
|
|
547
|
-
// `answering`: the boss is at the prompt's wait cards, so the tower's wake is held (runs.ts). An unattended device has no boss at it: its prompt is told, and shows no card on its own.
|
|
548
|
-
return towers.prompt(request.cmd, workspace, pid, request.answering === true && !unattended()).then((reply) => withLines(towers!, workspace, request.cursor, unattended() && "label" in reply ? { ...reply, unattended: true } : reply));
|
|
547
|
+
// `answering`: the boss is at the prompt's wait cards, so the tower's wake is held (runs.ts). An unattended device has no boss at it: its prompt is told, and shows no card on its own. `draft`: words on its line keep the pane (towerstow.ts).
|
|
548
|
+
return towers.prompt(request.cmd, workspace, pid, request.answering === true && !unattended(), request.draft === true).then((reply) => withLines(towers!, workspace, request.cursor, unattended() && "label" in reply ? { ...reply, unattended: true } : reply));
|
|
549
549
|
}
|
|
550
550
|
// The boss's memory (towermemory.ts `memoryRequest`): `/boss memory` in a pi session is the GUI panel's request on the same function. A run's token never gets here (rungate.ts refuses it).
|
|
551
551
|
// `via: "ask"` is the press of a dialog sb drew for an agent's `boss_wait_ask` (waitask.ts); the GUI's door is its own route's, never a client's word (`doorOf`).
|
package/src/server/runs.ts
CHANGED
|
@@ -200,6 +200,8 @@ export interface ServiceRef {
|
|
|
200
200
|
renewPane?(runId: string): Promise<string | undefined>;
|
|
201
201
|
/** Whether the standing pane is being replaced: a pi that turns up in it meanwhile is not admitted. */
|
|
202
202
|
renewing?(): boolean;
|
|
203
|
+
/** A service whose pane closed between runs (towerstow.ts) gets it made again before a run starts: once its identity has registered with the new pane, it pokes again. */
|
|
204
|
+
seat?(why: "run" | "ally"): void;
|
|
203
205
|
/** The tower's memory in counts for the GUI's snapshot (towermemory.ts). */
|
|
204
206
|
memory?(): MemorySummary;
|
|
205
207
|
}
|
|
@@ -476,6 +478,7 @@ export function createRuns(o: RunsOptions) {
|
|
|
476
478
|
const begin = async (svc: Svc) => {
|
|
477
479
|
if (stopped || svc.run || svc.state !== "standing" || !o.enabled() || !waitingOf(svc).some((e) => !e.quiet)) return;
|
|
478
480
|
if (!svc.ref.live()) return; // the identity registers first: runs reply under it. The service pokes again when it is live.
|
|
481
|
+
if (!headlessOn() && !svc.ref.record().pane) return void svc.ref.seat?.("run"); // its pane closed between runs: made first
|
|
479
482
|
if (slots >= o.max()) return void blocked.add(svc);
|
|
480
483
|
slots++;
|
|
481
484
|
svc.state = "waking";
|
|
@@ -725,6 +728,7 @@ export function createRuns(o: RunsOptions) {
|
|
|
725
728
|
for (const { device, items } of devicesWaiting(svc)) {
|
|
726
729
|
if (stopped || !o.enabled() || svc.refusedAt !== undefined && now() - svc.refusedAt < t.refuse) return;
|
|
727
730
|
if (!svc.ref.live()) return; // the identity registers first; the service pokes again when it is live
|
|
731
|
+
if (!headlessOn() && !svc.ref.record().pane) return void svc.ref.seat?.("ally"); // the ally pane is split off the standing pane, which is made first
|
|
728
732
|
if (slots >= o.max()) return void blocked.add(svc);
|
|
729
733
|
await beginAlly(svc, device, items).catch((cause: Error) => error("ally-begin", cause.message));
|
|
730
734
|
}
|
package/src/server/standing.ts
CHANGED
|
@@ -105,6 +105,8 @@ export type PromptReply = { ok: true; label: string; state: ServiceStatus["state
|
|
|
105
105
|
interface Mine {
|
|
106
106
|
target: StandingTarget;
|
|
107
107
|
seen?: { pid: number; at: number };
|
|
108
|
+
/** The prompt's last poll said the boss has words on its line (towerstow.ts keeps the pane open for them). */
|
|
109
|
+
draft?: boolean;
|
|
108
110
|
/** The prompt that announced it is leaving (`gone`): its process may not have exited yet. */
|
|
109
111
|
leaver?: number;
|
|
110
112
|
/** A run is about to start or holds the pane: the prompt is told to leave. */
|
|
@@ -394,13 +396,14 @@ export function createStanding(o: StandingOptions) {
|
|
|
394
396
|
await unreport(m);
|
|
395
397
|
},
|
|
396
398
|
/** The prompt's poll: it is there; the answer is what its screen shows and whether it must leave. */
|
|
397
|
-
poll(workspace: string, pid: number): PromptReply {
|
|
399
|
+
poll(workspace: string, pid: number, draft = false): PromptReply {
|
|
398
400
|
const m = mines.get(workspace);
|
|
399
401
|
if (!m) return { ok: false, error: `The sb server stands in for no tower of workspace ${workspace}`, gone: true };
|
|
400
402
|
const status = m.target.status(), answer = (leave: boolean): PromptReply => ({ ok: true, label: m.target.label(), state: status?.state ?? "standing", queued: status?.queued ?? 0, leave, ...(m.target.agent === STANDIN_HEAD ? { head: true as const } : {}) });
|
|
401
403
|
// The last poll of the prompt that took the boss's Ctrl+D, read after its leave, is no prompt there: it changes nothing and is told to leave.
|
|
402
404
|
if (pollGate({ parked: m.parked, parkedBy: m.parkedBy, pid }) === "left") return answer(true);
|
|
403
405
|
m.seen = { pid, at: now() };
|
|
406
|
+
m.draft = draft;
|
|
404
407
|
m.polled = true;
|
|
405
408
|
// A prompt that polls is the current one: the pid of an earlier prompt that left is no longer the one to wait for.
|
|
406
409
|
if (m.leaver !== undefined && m.leaver !== pid) m.leaver = undefined;
|
|
@@ -494,6 +497,11 @@ export function createStanding(o: StandingOptions) {
|
|
|
494
497
|
m.failures = 0;
|
|
495
498
|
void tick(workspace);
|
|
496
499
|
},
|
|
500
|
+
/** What the stow look (towerstow.ts) asks of the pane: whether the tower prompt polls there (not leaving), whether its line holds the boss's words, and whether the boss took the shell with Ctrl+D. */
|
|
501
|
+
here(workspace: string): { prompt: boolean; draft: boolean; parked: boolean; pid?: number } | undefined {
|
|
502
|
+
const m = mines.get(workspace);
|
|
503
|
+
return m && { prompt: present(m) && !m.leaving, draft: present(m) && m.draft === true, parked: m.parked, ...(m.seen ? { pid: m.seen.pid } : {}) };
|
|
504
|
+
},
|
|
497
505
|
/** Whether the command was typed into the pane in this terminal (a typing in flight counts); where Herdr lists no terminal, whether it was at or after `at`. */
|
|
498
506
|
typedSince: (pane: string, terminal: string | undefined, at: number): boolean => {
|
|
499
507
|
const record = typingIn(pane, terminal);
|
package/src/server/towers.ts
CHANGED
|
@@ -32,6 +32,7 @@ import { runApprover } from "./runapprove.ts";
|
|
|
32
32
|
import type { Asks } from "./asks.ts";
|
|
33
33
|
import { ageOf, allyTools, buildAllyBrief, buildBrief, gatherMains, heldFlag, localTools } from "./towerbrief.ts";
|
|
34
34
|
import { createStanding, type PromptReply, type StandingTimers } from "./standing.ts";
|
|
35
|
+
import { createStow, type StowTimers } from "./towerstow.ts";
|
|
35
36
|
import { createKids, type KidsPort } from "./runkids.ts";
|
|
36
37
|
import { resolvePi } from "./runchild.ts";
|
|
37
38
|
import { digestOf, headLabel, openCards, type WaitDigest, type WaitList, waitList, waitRows } from "./waitlist.ts";
|
|
@@ -120,8 +121,8 @@ export interface TowersOptions {
|
|
|
120
121
|
promptCommand?: (workspace: string) => string | undefined;
|
|
121
122
|
/** Whether this device has no boss at it (main.ts): its stand-ins stay idle whatever cards wait. */
|
|
122
123
|
unattended?: () => boolean;
|
|
123
|
-
/** The timers of the standing pane (standing.ts), for tests, and `standingWait`: */
|
|
124
|
-
standing?: Partial<StandingTimers>; standingWait?: /* the clock of a run's wait for the prompt's exit (tests) */ { now: () => number; sleep: (ms: number) => Promise<void> };
|
|
124
|
+
/** The timers of the standing pane (standing.ts) and of the look that closes it between runs (towerstow.ts), for tests, and `standingWait`: */
|
|
125
|
+
standing?: Partial<StandingTimers>; stow?: Partial<StowTimers>; standingWait?: /* the clock of a run's wait for the prompt's exit (tests) */ { now: () => number; sleep: (ms: number) => Promise<void> };
|
|
125
126
|
/** A request to the link holder as a tower identity (main.ts; absent in a world without one). `served`: the server's own request as that identity, as the link service's `request` takes it. */
|
|
126
127
|
link?: (body: unknown, from: string, served?: boolean) => Promise<unknown>;
|
|
127
128
|
/** The server's own part of `boss_server` for a run. */
|
|
@@ -188,7 +189,7 @@ export interface Towers extends Returns {
|
|
|
188
189
|
event(text: string, requester?: Requester, door?: "pane" | "viewer" | "page"): Promise<{ workspace: string; id: string }>;
|
|
189
190
|
};
|
|
190
191
|
/** The tower prompt in a standing pane (standing.ts): its poll, Ctrl+D, and exit. */
|
|
191
|
-
prompt(cmd: "prompt-poll" | "prompt-leave" | "prompt-gone", workspace: string, pid: number, answering?: boolean): Promise<PromptReply | { ok: true }>;
|
|
192
|
+
prompt(cmd: "prompt-poll" | "prompt-leave" | "prompt-gone", workspace: string, pid: number, answering?: boolean, draft?: boolean): Promise<PromptReply | { ok: true }>;
|
|
192
193
|
/** Messages wait in the link inbox for this tower identity: ally runs are started for them. */
|
|
193
194
|
allyWaiting(identity: string): void;
|
|
194
195
|
/** The GUI panel's request on a workspace's memory (`POST tower/<workspace>/memory`, towermemory.ts `memoryRequest`). */
|
|
@@ -305,7 +306,7 @@ export function createTowers(o: TowersOptions): Towers {
|
|
|
305
306
|
freed: (over) => standing.freed(l.record.workspace, over?.fresh, over?.keepParked),
|
|
306
307
|
clearDigest: (keys) => digest.drop(l.record.workspace, keys),
|
|
307
308
|
renewPane: (runId) => renew(l, runId),
|
|
308
|
-
renewing: () => l.renewing === true,
|
|
309
|
+
renewing: () => l.renewing === true, seat: (why) => void stow.open(l.record.workspace, why).catch((cause: Error) => error("tower-seat", cause.message)),
|
|
309
310
|
// The run that was shown an expired wait has polled: it will not be shown again (towermemory.ts).
|
|
310
311
|
shown: (ids) => { try { markShown(slot, l.record.workspace, now(), ids); } catch (cause) { error("memory", (cause as Error).message); } },
|
|
311
312
|
memory: () => {
|
|
@@ -820,6 +821,11 @@ export function createTowers(o: TowersOptions): Towers {
|
|
|
820
821
|
if (l.client) await release(l).then(() => services.set(l.record.workspace, adopt(l.record, false, true)));
|
|
821
822
|
};
|
|
822
823
|
const look = () => (looking = looking.then(reconcile).catch((cause: Error) => error("reconcile", cause.message)));
|
|
824
|
+
/** The service moves to another record (its pane closed or made between runs, a viewer made): written, its identity registered again with it, and the standing pane's state begun anew. `fresh`: the pane was just made. */
|
|
825
|
+
const reseat = async (l: Live, record: ServiceRecord, fresh: boolean): Promise<Live> => { l.record = record; writeService(slot, record); await release(l); await standing.detach(record.workspace); if (services.get(record.workspace) === l) services.delete(record.workspace); return adopt(record, fresh, true); };
|
|
826
|
+
const stow = createStow<Live>({ run, api: cfg.api, log, now, stateDir: slot.stateDir, ...(o.stow ? { timers: o.stow } : {}), list: () => [...services.values()].filter((l) => !l.stopped), current: (ws) => ((l) => (l && !l.stopped ? l : undefined))(services.get(ws)), record: (l) => l.record, place: (l, record) => void (l.record = record), head: isHeadL, seated: (l) => l.seated, recovering: () => now() < recoverUntil,
|
|
827
|
+
ready: (l) => l.state === "live" && l.seated && !l.stopped && !l.renewing && Boolean(l.client?.isConnected()), seat: async (l) => void ((l.seated = true), await publish(l)), hold: (l) => ((was) => ((l.state = "registering"), (l.renewing = true), () => void ((l.state = was), (l.renewing = false))))(l.state),
|
|
828
|
+
headless, status: (ws) => runs.status(ws), queued: (ws) => runs.queue(ws).filter((e) => !e.quiet).length, soon: (ws, ms) => runs.startsWithin(ws, ms), cards: (l) => cardsFor(l), prompt: (ws) => standing.here(ws), reseat, lose });
|
|
823
829
|
|
|
824
830
|
// --- the start ------------------------------------------------------------------------------------------------------------------------------------------------------------
|
|
825
831
|
|
|
@@ -971,7 +977,7 @@ export function createTowers(o: TowersOptions): Towers {
|
|
|
971
977
|
const poll = o.recoverPollMs ?? RECOVER_POLL_MS;
|
|
972
978
|
timers.push(setInterval(() => { if (now() < recoverUntil + poll) look(); }, poll));
|
|
973
979
|
timers.forEach((t) => t.unref());
|
|
974
|
-
standing.start();
|
|
980
|
+
standing.start(); stow.start();
|
|
975
981
|
await Promise.race([Promise.all([...adopted, ...adoptedHead].map((l) => l.starting)), sleep(o.registerMs ?? REGISTER_WAIT_MS)]);
|
|
976
982
|
await look();
|
|
977
983
|
loadedAll = true;
|
|
@@ -1045,6 +1051,8 @@ export function createTowers(o: TowersOptions): Towers {
|
|
|
1045
1051
|
},
|
|
1046
1052
|
typed: () => standing.typedSince(claim!.pane, seen.terminal, claim!.at),
|
|
1047
1053
|
});
|
|
1054
|
+
// A tower whose pane closed between runs (towerstow.ts) gets it again; one whose workspace proved a stranger's ended, and a tower is made anew below.
|
|
1055
|
+
if (existing && !existing.stopped && tabless(existing) && !hint && !claim) { const l = await stow.open(ws, "ensure"); if (l) return (await Promise.race([l.starting, sleep(o.registerMs ?? REGISTER_WAIT_MS)]), answer(l, false)); }
|
|
1048
1056
|
if (existing && !existing.stopped) {
|
|
1049
1057
|
// A pane list that fails is unknown: the ask fails, the service stays.
|
|
1050
1058
|
const here = await locate(existing, false);
|
|
@@ -1116,14 +1124,7 @@ export function createTowers(o: TowersOptions): Towers {
|
|
|
1116
1124
|
await cfg.api("tab.move", { tab_id: tab.tabId, insert_index: 0 }).catch((cause: Error) => error("tab-move", cause.message));
|
|
1117
1125
|
record = { ...record, pane: tab.paneId, tab: tab.tabId };
|
|
1118
1126
|
}
|
|
1119
|
-
writeService(slot, record);
|
|
1120
|
-
if (existing) {
|
|
1121
|
-
existing.record = record;
|
|
1122
|
-
await release(existing);
|
|
1123
|
-
await standing.detach(ws);
|
|
1124
|
-
services.delete(ws);
|
|
1125
|
-
}
|
|
1126
|
-
const l = adopt(record, view, true);
|
|
1127
|
+
const l = existing ? await reseat(existing, record, view) : (writeService(slot, record), adopt(record, view, true));
|
|
1127
1128
|
log.line(existing ? "tower-viewer" : "tower-opened", { workspace: ws, id: record.id, ...(view ? { pane: record.pane, tab: record.tab } : { tab: "none" }) });
|
|
1128
1129
|
await Promise.race([l.starting, sleep(o.registerMs ?? REGISTER_WAIT_MS)]);
|
|
1129
1130
|
return answer(l, !existing);
|
|
@@ -1458,9 +1459,9 @@ export function createTowers(o: TowersOptions): Towers {
|
|
|
1458
1459
|
},
|
|
1459
1460
|
},
|
|
1460
1461
|
runs,
|
|
1461
|
-
async prompt(cmd, workspace, pid, answering = false) {
|
|
1462
|
+
async prompt(cmd, workspace, pid, answering = false, draft = false) {
|
|
1462
1463
|
if (cmd === "prompt-poll") {
|
|
1463
|
-
const polled = standing.poll(workspace, pid);
|
|
1464
|
+
const polled = standing.poll(workspace, pid, draft);
|
|
1464
1465
|
// The boss answers wait cards at this prompt (its poll says so): the tower's wake is held meanwhile (runs.ts `answering`). A prompt that is told to leave holds nothing.
|
|
1465
1466
|
return polled.ok ? { ...polled, ...api.waitDigest(workspace), ...(runs.answering(workspace, answering && !polled.leave) ? { holding: true as const } : {}) } : polled;
|
|
1466
1467
|
}
|
|
@@ -1469,7 +1470,7 @@ export function createTowers(o: TowersOptions): Towers {
|
|
|
1469
1470
|
async stop(opts) {
|
|
1470
1471
|
stopped = true;
|
|
1471
1472
|
offAuto?.();
|
|
1472
|
-
await standing.stop();
|
|
1473
|
+
await Promise.all([standing.stop(), stow.stop()]);
|
|
1473
1474
|
await runs.stop(opts);
|
|
1474
1475
|
timers.forEach(clearInterval);
|
|
1475
1476
|
clearTimeout(republishTimer);
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { createTab, type HerdrApi, type HerdrRun, isStandin, type Pane, panes, report, TOWER_LABEL, workspaces } from "../herdr.ts";
|
|
2
|
+
import type { Log } from "./log.ts";
|
|
3
|
+
import type { ServiceState, ServiceStatus } from "./runs.ts";
|
|
4
|
+
import type { ServiceRecord } from "./towerstore.ts";
|
|
5
|
+
import { nameOf, SHELLS } from "./typegate.ts";
|
|
6
|
+
|
|
7
|
+
// A tower's standing pane between runs (docs/how-it-works.md, The standing pane, When the pane closes). The boss's order of 2026-11-28 (「只在有卡片等我時才留」): the pane stays only while a card waits for him. Once no run
|
|
8
|
+
// is live, nothing waits to wake one, no card of the tower waits, and that has held for `idleMs`, the pane closes (only the pane: Herdr drops the emptied tab itself) and the service goes on with no pane, as a headless
|
|
9
|
+
// service does: its identity stays registered and its token written, so mains still reach it. The next run, ally run, card, or ensure-tower makes the tab again, as the first open made it.
|
|
10
|
+
// What keeps the pane is decided here alone (`idleGate`, `paneGate`, `seatOpen`; their table test is tests/towerstow.test.ts); the look gathers the facts and acts on the answer.
|
|
11
|
+
// The head tower's pane is never closed: it is its workspace's only pane, so closing it would close the head workspace and take the head's record with it (`lose`). A pane that is the last of its workspace is kept for the
|
|
12
|
+
// same reason: the queue, the memory, and the ledgers are kept under the workspace's id, which a workspace made again does not get.
|
|
13
|
+
|
|
14
|
+
export interface StowTimers {
|
|
15
|
+
/** How often the look runs. */
|
|
16
|
+
intervalMs: number;
|
|
17
|
+
/** How long nothing may have kept the pane before it closes: a burst of events, or a milestone's 30 s wait, reuses it. */
|
|
18
|
+
idleMs: number;
|
|
19
|
+
}
|
|
20
|
+
export const STOW: StowTimers = { intervalMs: 3000, idleMs: 30_000 };
|
|
21
|
+
|
|
22
|
+
/** Why a standing pane stays. */
|
|
23
|
+
export type Keep = "head" | "headless" | "unready" | "cards" | "run" | "held" | "queued" | "soon" | "recent" | "gone" | "agent" | "tab" | "last" | "parked" | "prompt" | "draft" | "program" | "unknown";
|
|
24
|
+
export type StowVerdict = { stow: true } | { stow: false; why: Keep };
|
|
25
|
+
const keep = (why: Keep): StowVerdict => ({ stow: false, why });
|
|
26
|
+
|
|
27
|
+
export interface IdleFacts {
|
|
28
|
+
head: boolean;
|
|
29
|
+
/** `towerRuns.headless`: a viewer has its own life (it ends by itself). */
|
|
30
|
+
headless: boolean;
|
|
31
|
+
/** The identity is registered, the seat proven, and no pane change is under way. */
|
|
32
|
+
ready: boolean;
|
|
33
|
+
/** The tower's own wait cards that wait for the boss. */
|
|
34
|
+
cards: number;
|
|
35
|
+
state?: ServiceState;
|
|
36
|
+
/** A local run or an ally run is live. */
|
|
37
|
+
run: boolean;
|
|
38
|
+
/** Events that wake a run (a quiet one wakes none). */
|
|
39
|
+
queued: number;
|
|
40
|
+
/** A wake is due within `idleMs` (a milestone's hold). */
|
|
41
|
+
soon: boolean;
|
|
42
|
+
idleFor: number;
|
|
43
|
+
idleMs: number;
|
|
44
|
+
}
|
|
45
|
+
/** The facts of the service, cheap to read: asked before the pane's facts, which cost Herdr calls. */
|
|
46
|
+
export function idleGate(f: IdleFacts): StowVerdict {
|
|
47
|
+
if (f.head) return keep("head");
|
|
48
|
+
if (f.headless) return keep("headless");
|
|
49
|
+
if (!f.ready) return keep("unready");
|
|
50
|
+
if (f.cards > 0) return keep("cards");
|
|
51
|
+
if (f.run || f.state === "waking" || f.state === "running" || f.state === "closing") return keep("run");
|
|
52
|
+
if (f.state === "held") return keep("held"); // its notices, and the pane's last lines, are what the boss reads
|
|
53
|
+
if (f.queued > 0) return keep("queued");
|
|
54
|
+
if (f.soon) return keep("soon");
|
|
55
|
+
if (f.idleFor < f.idleMs) return keep("recent");
|
|
56
|
+
return { stow: true };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface PaneFacts {
|
|
60
|
+
pane?: Pick<Pane, "agent">;
|
|
61
|
+
/** The panes in the standing pane's tab, and in its workspace, itself included. */
|
|
62
|
+
inTab: number;
|
|
63
|
+
inWorkspace: number;
|
|
64
|
+
/** The boss took the shell with Ctrl+D (standing.ts). */
|
|
65
|
+
parked: boolean;
|
|
66
|
+
/** The tower prompt polls in the pane, and its last poll said the boss has words on its line (or a card's field, or the picker). */
|
|
67
|
+
prompt: boolean;
|
|
68
|
+
draft: boolean;
|
|
69
|
+
foreground: "clean" | "program" | "unknown";
|
|
70
|
+
}
|
|
71
|
+
/** The pane as Herdr lists it now: only a lone standing pane that holds the tower prompt at rest, in a workspace that keeps another pane, closes. */
|
|
72
|
+
export function paneGate(f: PaneFacts): StowVerdict {
|
|
73
|
+
if (!f.pane) return keep("gone");
|
|
74
|
+
if (f.pane.agent && !isStandin(f.pane)) return keep("agent"); // a pi the boss started there by hand
|
|
75
|
+
if (f.inTab > 1) return keep("tab"); // a split of the boss's, or an ally run's pane
|
|
76
|
+
if (f.inWorkspace <= f.inTab) return keep("last");
|
|
77
|
+
if (f.parked) return keep("parked");
|
|
78
|
+
if (!f.prompt) return keep("prompt"); // only the prompt's own polls prove what the pane holds, on every platform
|
|
79
|
+
if (f.draft) return keep("draft");
|
|
80
|
+
if (f.foreground !== "clean") return keep(f.foreground);
|
|
81
|
+
return { stow: true };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Whether the pane's foreground holds nothing but its shell and this tower's prompt (`promptPid`: the pid that polls). Windows lists the shell alone under any program, which is why `paneGate` asks the prompt's polls first. */
|
|
85
|
+
export function foregroundOf(info: { shell_pid?: unknown; foreground_processes?: unknown } | undefined, workspace: string, promptPid?: number): PaneFacts["foreground"] {
|
|
86
|
+
const list = Array.isArray(info?.foreground_processes) ? (info!.foreground_processes as { pid?: number; name?: string; argv0?: string; cmdline?: string }[]) : [];
|
|
87
|
+
if (!list.length) return "unknown";
|
|
88
|
+
const shell = typeof info?.shell_pid === "number" ? info.shell_pid : undefined, prompt = new RegExp(`\\bprompt --workspace ${workspace.replace(/[^\w.:-]/g, "")}(\\s|$)`);
|
|
89
|
+
return list.every((p) => (shell !== undefined ? p.pid === shell : list.length === 1 && SHELLS.has(nameOf(p))) || (promptPid !== undefined && p.pid === promptPid) || prompt.test(p.cmdline ?? "")) ? "clean" : "program";
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Whether a tower with no pane may make its tab in the workspace under its id: after a Herdr restart (`seated` false) only one that still carries the label it had is its own (ids repeat across Herdr servers). */
|
|
93
|
+
export function seatOpen(f: { seated: boolean; label: string | undefined; record: string }): "open" | "stranger" | "gone" {
|
|
94
|
+
if (f.label === undefined) return "gone";
|
|
95
|
+
return f.seated || f.label === f.record ? "open" : "stranger";
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** What the look needs of the tower service (towers.ts). `L` is its live service. */
|
|
99
|
+
export interface StowPort<L> {
|
|
100
|
+
run: HerdrRun;
|
|
101
|
+
api: HerdrApi;
|
|
102
|
+
log: Log;
|
|
103
|
+
now(): number;
|
|
104
|
+
stateDir: string;
|
|
105
|
+
timers?: Partial<StowTimers>;
|
|
106
|
+
list(): L[];
|
|
107
|
+
current(workspace: string): L | undefined;
|
|
108
|
+
record(l: L): ServiceRecord;
|
|
109
|
+
/** The record in memory only, before the pane closes: Herdr's `pane.closed` then finds a service with no pane, not one whose tab is gone. */
|
|
110
|
+
place(l: L, record: ServiceRecord): void;
|
|
111
|
+
head(l: L): boolean;
|
|
112
|
+
ready(l: L): boolean;
|
|
113
|
+
seated(l: L): boolean;
|
|
114
|
+
/** The minute after a Herdr restart (or the server's start), in which nothing is judged a stranger's yet. */
|
|
115
|
+
recovering(): boolean;
|
|
116
|
+
/** The workspace under the id still carries the label: a stowed service is seated again after a Herdr restart (its token is written again). */
|
|
117
|
+
seat(l: L): Promise<void>;
|
|
118
|
+
/** The service is not live while its pane changes (no run begins, no pi is admitted); returns the undo. */
|
|
119
|
+
hold(l: L): () => void;
|
|
120
|
+
headless(): boolean;
|
|
121
|
+
status(workspace: string): ServiceStatus | undefined;
|
|
122
|
+
queued(workspace: string): number;
|
|
123
|
+
soon(workspace: string, ms: number): boolean;
|
|
124
|
+
cards(l: L): number;
|
|
125
|
+
prompt(workspace: string): { prompt: boolean; draft: boolean; parked: boolean; pid?: number } | undefined;
|
|
126
|
+
/** The record is written and the identity registers again with it; `fresh`: the pane was just made. */
|
|
127
|
+
reseat(l: L, record: ServiceRecord, fresh: boolean): Promise<L>;
|
|
128
|
+
lose(l: L, why: string, stranger: boolean): Promise<void>;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function createStow<L>(o: StowPort<L>) {
|
|
132
|
+
const t: StowTimers = { ...STOW, ...o.timers };
|
|
133
|
+
const { run, log } = o;
|
|
134
|
+
/** Since when nothing kept each workspace's pane (the clock starts again with every reason that means work), and the pane-side reason last logged. */
|
|
135
|
+
const since = new Map<string, { pane: string; at: number }>(), said = new Map<string, Keep>();
|
|
136
|
+
const opening = new Map<string, Promise<L | undefined>>();
|
|
137
|
+
let timer: ReturnType<typeof setInterval> | undefined, looking: Promise<void> = Promise.resolve(), stopped = false;
|
|
138
|
+
const error = (code: string, text: string) => log.line("error", { code, text: text.slice(0, 300) });
|
|
139
|
+
const processInfo = (pane: string) => run(["pane", "process-info", "--pane", pane]).then((x) => JSON.parse(x).result?.process_info, () => undefined);
|
|
140
|
+
const idleOf = (l: L, at: number) => {
|
|
141
|
+
const ws = o.record(l).workspace, status = o.status(ws), from = since.get(ws);
|
|
142
|
+
return idleGate({ head: o.head(l), headless: o.headless(), ready: o.ready(l), cards: o.cards(l), state: status?.state, run: Boolean(status?.run) || (status?.allyRuns.length ?? 0) > 0, queued: o.queued(ws), soon: o.soon(ws, t.idleMs), idleFor: from ? at - from.at : 0, idleMs: t.idleMs });
|
|
143
|
+
};
|
|
144
|
+
const said1 = (ws: string, why: Keep) => {
|
|
145
|
+
if (said.get(ws) === why) return;
|
|
146
|
+
said.set(ws, why);
|
|
147
|
+
log.line("tower-stow-kept", { workspace: ws, why });
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
/** The pane closes and the service goes on with no pane. Every fact is asked again after the last await; a close Herdr refuses leaves everything as it was. */
|
|
151
|
+
const close = async (l: L, record: ServiceRecord) => {
|
|
152
|
+
const ws = record.workspace, undo = o.hold(l);
|
|
153
|
+
const bare: ServiceRecord = { ...record, pane: "", tab: "" };
|
|
154
|
+
o.place(l, bare);
|
|
155
|
+
try {
|
|
156
|
+
await run(["pane", "close", record.pane]);
|
|
157
|
+
} catch (cause) {
|
|
158
|
+
o.place(l, record);
|
|
159
|
+
undo();
|
|
160
|
+
return error("tower-stow", `${ws}: ${(cause as Error).message}`);
|
|
161
|
+
}
|
|
162
|
+
since.delete(ws);
|
|
163
|
+
said.delete(ws);
|
|
164
|
+
log.line("tower-stowed", { workspace: ws, pane: record.pane });
|
|
165
|
+
await o.reseat(l, bare, false);
|
|
166
|
+
};
|
|
167
|
+
const lookAt = async (l: L) => {
|
|
168
|
+
const record = o.record(l), ws = record.workspace;
|
|
169
|
+
if (o.head(l) || o.headless() || opening.has(ws)) return;
|
|
170
|
+
if (!record.pane) {
|
|
171
|
+
// A service seated before a Herdr restart is seated again by its workspace's label: its token is written again, and a card or a run makes its tab. A workspace under its id with another label is a stranger's, once the minute is over.
|
|
172
|
+
if (!o.seated(l)) {
|
|
173
|
+
const listed = await workspaces(run).catch(() => undefined), seat = listed && seatOpen({ seated: false, label: listed.find((w) => w.workspace_id === ws)?.label, record: record.label });
|
|
174
|
+
if (seat === "open") await o.seat(l);
|
|
175
|
+
else if (seat === "stranger" && !o.recovering()) return void (await o.lose(l, "its workspace carries another label after a Herdr restart", true));
|
|
176
|
+
}
|
|
177
|
+
if (o.ready(l) && o.cards(l) > 0) await open(ws, "cards");
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
const at = o.now();
|
|
181
|
+
if (since.get(ws)?.pane !== record.pane) since.set(ws, { pane: record.pane, at });
|
|
182
|
+
const idle = idleOf(l, at);
|
|
183
|
+
if (!idle.stow) {
|
|
184
|
+
if (idle.why !== "recent") since.set(ws, { pane: record.pane, at });
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const all = await panes(run, ws).catch(() => undefined);
|
|
188
|
+
if (!all) return;
|
|
189
|
+
const pane = all.find((p) => p.pane_id === record.pane), here = o.prompt(ws);
|
|
190
|
+
const v = paneGate({ ...(pane ? { pane } : {}), inTab: pane ? all.filter((p) => p.tab_id === pane.tab_id).length : 0, inWorkspace: all.length, parked: here?.parked === true, prompt: here?.prompt === true, draft: here?.draft === true, foreground: pane ? foregroundOf(await processInfo(record.pane), ws, here?.pid) : "unknown" });
|
|
191
|
+
if (!v.stow) {
|
|
192
|
+
if (v.why === "draft") since.set(ws, { pane: record.pane, at: o.now() });
|
|
193
|
+
return said1(ws, v.why);
|
|
194
|
+
}
|
|
195
|
+
// Asked again after the reads: an event, a card, or a run that came meanwhile keeps the pane.
|
|
196
|
+
if (stopped || o.current(ws) !== l || o.record(l) !== record || !idleOf(l, o.now()).stow || o.prompt(ws)?.draft) return;
|
|
197
|
+
await close(l, record);
|
|
198
|
+
};
|
|
199
|
+
const look = () => (looking = looking.then(async () => {
|
|
200
|
+
for (const l of o.list()) {
|
|
201
|
+
if (stopped) return;
|
|
202
|
+
await lookAt(l).catch((cause: Error) => error("tower-stow", cause.message));
|
|
203
|
+
}
|
|
204
|
+
}));
|
|
205
|
+
|
|
206
|
+
/** Makes the tab of a tower with no pane again, as the first open made it (the tower glyph, first, the pane marked `sb_role=tower`), and seats the service in it. Undefined when the workspace proved a stranger's and the service ended. */
|
|
207
|
+
const open = (workspace: string, why: "run" | "ally" | "cards" | "ensure"): Promise<L | undefined> => {
|
|
208
|
+
const pending = opening.get(workspace) ?? (async () => {
|
|
209
|
+
const l = o.current(workspace);
|
|
210
|
+
if (!l || o.record(l).pane) return l;
|
|
211
|
+
const record = o.record(l), target = (await workspaces(run)).find((w) => w.workspace_id === workspace);
|
|
212
|
+
const verdict = seatOpen({ seated: o.seated(l), label: target?.label, record: record.label });
|
|
213
|
+
if (verdict === "gone") throw new Error(`the workspace of ${record.id} is gone`);
|
|
214
|
+
if (verdict === "stranger") return void (await o.lose(l, "its workspace carries another label after a Herdr restart", true));
|
|
215
|
+
const undo = o.hold(l);
|
|
216
|
+
let made: { tabId: string; paneId: string } | undefined;
|
|
217
|
+
try {
|
|
218
|
+
const dir = record.cwd ?? target!.worktree?.checkout_path ?? o.stateDir;
|
|
219
|
+
made = await createTab(run, workspace, dir, [], TOWER_LABEL);
|
|
220
|
+
if (o.current(workspace) !== l) throw new Error("the service ended while its tab was made");
|
|
221
|
+
await report(run, "pane", made.paneId, { sb_role: "tower" });
|
|
222
|
+
await o.api("tab.move", { tab_id: made.tabId, insert_index: 0 }).catch((cause: Error) => error("tab-move", cause.message));
|
|
223
|
+
log.line("tower-unstowed", { workspace, pane: made.paneId, why });
|
|
224
|
+
return await o.reseat(l, { ...record, pane: made.paneId, tab: made.tabId, cwd: dir }, true);
|
|
225
|
+
} catch (cause) {
|
|
226
|
+
undo();
|
|
227
|
+
if (made) await run(["pane", "close", made.paneId]).catch(() => {}); // the pane it made, never the tab
|
|
228
|
+
throw cause;
|
|
229
|
+
}
|
|
230
|
+
})().finally(() => opening.delete(workspace));
|
|
231
|
+
opening.set(workspace, pending);
|
|
232
|
+
return pending;
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
look,
|
|
237
|
+
open,
|
|
238
|
+
start() {
|
|
239
|
+
timer ??= setInterval(() => void look(), t.intervalMs);
|
|
240
|
+
timer.unref();
|
|
241
|
+
},
|
|
242
|
+
async stop() {
|
|
243
|
+
stopped = true;
|
|
244
|
+
clearInterval(timer);
|
|
245
|
+
timer = undefined;
|
|
246
|
+
await looking.catch(() => {});
|
|
247
|
+
await Promise.all([...opening.values()].map((p) => p.catch(() => {})));
|
|
248
|
+
},
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
export type Stow<L> = ReturnType<typeof createStow<L>>;
|
|
@@ -295,7 +295,7 @@ export async function runPrompt(o: PromptOptions): Promise<number> {
|
|
|
295
295
|
if (finished) return;
|
|
296
296
|
polling = true;
|
|
297
297
|
try {
|
|
298
|
-
const polled = await source.poll(cards?.answering() ?? false).catch((cause: Error) => ({ kind: "wait" as const, why: cause.message }));
|
|
298
|
+
const polled = await source.poll(cards?.answering() ?? false, Boolean(rl && !closed && ((rl.line ?? "") !== "" || batch.length || pasting || posting || pick.active() || cards?.engaged()))).catch((cause: Error) => ({ kind: "wait" as const, why: cause.message }));
|
|
299
299
|
if (finished || !(await handle(polled))) return;
|
|
300
300
|
} finally {
|
|
301
301
|
polling = false;
|
|
@@ -75,10 +75,10 @@ export function serverSource(ctx: Ctx, workspace: string, pid: number = process.
|
|
|
75
75
|
};
|
|
76
76
|
return {
|
|
77
77
|
pick,
|
|
78
|
-
async poll(answering = false): Promise<Polled> {
|
|
78
|
+
async poll(answering = false, draft = false): Promise<Polled> {
|
|
79
79
|
let reply;
|
|
80
80
|
try {
|
|
81
|
-
reply = await ask({ cmd: "prompt-poll", workspace, pid, ...(answering ? { answering: true } : {}), ...(cursor !== undefined ? { cursor } : {}) }, POLL_MS);
|
|
81
|
+
reply = await ask({ cmd: "prompt-poll", workspace, pid, ...(answering ? { answering: true } : {}), ...(draft ? { draft: true } : {}), ...(cursor !== undefined ? { cursor } : {}) }, POLL_MS);
|
|
82
82
|
} catch (cause) {
|
|
83
83
|
return { kind: "wait", why: (cause as Error).message };
|
|
84
84
|
}
|
|
@@ -45,8 +45,8 @@ export interface PickSource {
|
|
|
45
45
|
export interface PromptSource {
|
|
46
46
|
/** The picker's source; a source with none cannot press cards. */
|
|
47
47
|
pick?: PickSource;
|
|
48
|
-
/** `answering`: the boss is at the card view's keys (cardview.ts); the server holds the tower's wake while the polls say so. */
|
|
49
|
-
poll(answering?: boolean): Promise<Polled>;
|
|
48
|
+
/** `answering`: the boss is at the card view's keys (cardview.ts); the server holds the tower's wake while the polls say so. `draft`: the boss has words on the line (or in a card's field, or the picker): the server keeps the pane open (towerstow.ts). */
|
|
49
|
+
poll(answering?: boolean, draft?: boolean): Promise<Polled>;
|
|
50
50
|
/** Posts the boss's words to the tower as a `boss` event; rejects with the server's own words when it does not take them. */
|
|
51
51
|
post(text: string): Promise<void>;
|
|
52
52
|
/** The boss typed `/new`: the next boss conversation is a new session (the server's `tower-new`, the function `/boss tower new` and the GUI's New reach); rejects with the server's own words. */
|