pi-straw-boss 0.117.1 → 0.117.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/main.mjs +366 -276
- package/package.json +2 -2
- package/src/reach.ts +11 -11
- package/src/runmode.ts +8 -1
- package/src/server/confirmsend.ts +58 -0
- package/src/server/kit.ts +12 -5
- package/src/server/runevents.ts +43 -3
- package/src/server/runs.ts +4 -0
- package/src/server/runtools.ts +39 -14
- package/src/server/towergate.ts +1 -1
- package/src/server/towers.ts +2 -2
package/dist/server/main.mjs
CHANGED
|
@@ -880,6 +880,44 @@ function createKit(pi, cfg) {
|
|
|
880
880
|
};
|
|
881
881
|
}
|
|
882
882
|
|
|
883
|
+
// src/server/confirmsend.ts
|
|
884
|
+
var RECEIPT_MS = 2e3;
|
|
885
|
+
var receiptSleep = (ms4) => new Promise((resolve11) => void setTimeout(resolve11, ms4).unref?.());
|
|
886
|
+
var epochOf = (session) => session?.endpointEpoch;
|
|
887
|
+
async function confirmSend(active, target2, requestId, send, sleep2 = receiptSleep) {
|
|
888
|
+
const from = [];
|
|
889
|
+
let heard;
|
|
890
|
+
const off = active.onBrokerMessage((m) => {
|
|
891
|
+
const receipt = m.receipt, by = m.from;
|
|
892
|
+
if (m.type === "message_receipt" && receipt?.messageId === requestId && typeof by?.id === "string") from.push(by.id), heard?.();
|
|
893
|
+
});
|
|
894
|
+
try {
|
|
895
|
+
const sent = await send();
|
|
896
|
+
if (!sent.delivered) return { id: sent.id, status: "failed", code: "delivery_failed", detail: sent.reason ?? "Delivery failed" };
|
|
897
|
+
if (sent.delivery === "queued") {
|
|
898
|
+
const withdrawn = await (active.cancelMessage?.(sent.id) ?? Promise.resolve({ delivered: false })).then((x) => x.delivered, () => false);
|
|
899
|
+
return { id: sent.id, status: "failed", code: "target_offline", detail: `Session "${target2.id}" went offline before delivery; the broker's queued copy ${withdrawn ? "was withdrawn" : "could not be withdrawn and may reach it when it reconnects"}` };
|
|
900
|
+
}
|
|
901
|
+
const heardFrom = () => {
|
|
902
|
+
const other = from.find((x) => x !== target2.id);
|
|
903
|
+
if (other) return { id: sent.id, status: "failed", code: "redirected", detail: `The broker handed it to session ${other}, not to ${target2.id}: it did not reach the session it was for` };
|
|
904
|
+
return from.length ? { id: sent.id, status: "sent" } : void 0;
|
|
905
|
+
};
|
|
906
|
+
if (!from.length) await Promise.race([sleep2(RECEIPT_MS), new Promise((resolve11) => heard = resolve11)]);
|
|
907
|
+
const early = heardFrom();
|
|
908
|
+
if (early) return early;
|
|
909
|
+
const now = (await active.listSessions().catch(() => [])).find((x) => x.id === target2.id);
|
|
910
|
+
const late = heardFrom();
|
|
911
|
+
if (late) return late;
|
|
912
|
+
const gone = `Session ${target2.id} sent no receipt and is no longer the same live session after the send: the broker may have handed the message to another session`;
|
|
913
|
+
if (!now) return { id: sent.id, status: "failed", code: "unconfirmed", detail: gone };
|
|
914
|
+
if (epochOf(target2) === void 0 || epochOf(now) === void 0) return { id: sent.id, status: "failed", code: "unconfirmed", detail: `Session ${target2.id} sent no receipt, and no endpoint epoch shows it is the same live session after the send: the broker may have handed the message to another session` };
|
|
915
|
+
return epochOf(now) === epochOf(target2) ? { id: sent.id, status: "sent" } : { id: sent.id, status: "failed", code: "unconfirmed", detail: gone };
|
|
916
|
+
} finally {
|
|
917
|
+
off();
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
|
|
883
921
|
// src/server/kit.ts
|
|
884
922
|
var OUTBOX = "intercom:outbox-request";
|
|
885
923
|
var OUTBOX_RESULT = "intercom:outbox-result";
|
|
@@ -887,7 +925,7 @@ var BUS = "extension-bus-v1";
|
|
|
887
925
|
var NAMESPACE = /^[a-z0-9][a-z0-9._/-]{0,63}$/;
|
|
888
926
|
var text = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
889
927
|
function createHeadlessKit({ client, env, cfg, log = () => {
|
|
890
|
-
} }) {
|
|
928
|
+
}, receiptWait }) {
|
|
891
929
|
const handlers = /* @__PURE__ */ new Map(), locals = /* @__PURE__ */ new Map(), pending = /* @__PURE__ */ new Set(), used = /* @__PURE__ */ new Set();
|
|
892
930
|
let current = client, off;
|
|
893
931
|
const events = {
|
|
@@ -955,12 +993,14 @@ function createHeadlessKit({ client, env, cfg, log = () => {
|
|
|
955
993
|
try {
|
|
956
994
|
if (!active.isConnected() || !active.sessionId) return settle2(trace, "failed", { code: "session_unavailable", detail: "Intercom is not connected" });
|
|
957
995
|
const sessions = await active.listSessions();
|
|
958
|
-
const byId = sessions.find((x) => x.id === to), byName2 = byId ? [] : sessions.filter((x) => x.name?.toLowerCase() === to.toLowerCase());
|
|
959
|
-
const matches2 = byId ? [byId] : byName2.length ? byName2 : sessions.filter((x) => x.id.startsWith(to));
|
|
996
|
+
const exact2 = r.exact === true || r.confirm === true, byId = sessions.find((x) => x.id === to), byName2 = byId || exact2 ? [] : sessions.filter((x) => x.name?.toLowerCase() === to.toLowerCase());
|
|
997
|
+
const matches2 = byId ? [byId] : exact2 ? [] : byName2.length ? byName2 : sessions.filter((x) => x.id.startsWith(to));
|
|
960
998
|
if (!matches2.length) return settle2(trace, "blocked", { code: "target_not_found", detail: `Session "${to}" is not currently connected.` });
|
|
961
999
|
if (matches2.length > 1) return settle2(trace, "blocked", { code: "target_ambiguous", detail: `Multiple sessions match "${to}".` });
|
|
962
1000
|
if (matches2[0].id === active.sessionId) return settle2(trace, "blocked", { code: "self_target", detail: "Cannot message the current session." });
|
|
963
|
-
const
|
|
1001
|
+
const send = () => active.send(matches2[0].id, { messageId: requestId, text: message, provenance: { type: "extension_outbox", extensionId, extensionName, requestId } });
|
|
1002
|
+
if (r.confirm === true) return ((got) => settle2(trace, got.status, { messageId: got.id, ...got.code ? { code: got.code } : {}, ...got.detail ? { detail: got.detail } : {} }))(await confirmSend(active, matches2[0], requestId, send, receiptWait));
|
|
1003
|
+
const sent = await send();
|
|
964
1004
|
settle2(trace, sent.delivered ? "sent" : "failed", sent.delivered ? { messageId: sent.id } : { code: "delivery_failed", messageId: sent.id, detail: sent.reason ?? "Delivery failed" });
|
|
965
1005
|
} catch (error) {
|
|
966
1006
|
settle2(trace, "failed", { code: "session_unavailable", detail: error.message });
|
|
@@ -3777,7 +3817,7 @@ function createReach({ pi, cfg, s: s2, guiDir, me, role, tell: tell2 }, server =
|
|
|
3777
3817
|
const { run: run2, api: api2, sleep: sleep2 } = cfg;
|
|
3778
3818
|
const nonce = randomUUID4().slice(0, 8);
|
|
3779
3819
|
let requests = 0, toldStopped = false;
|
|
3780
|
-
const sendOnce = (to, message, requestId) => new Promise((resolve11) => {
|
|
3820
|
+
const sendOnce = (to, message, requestId, exact2, confirm2) => new Promise((resolve11) => {
|
|
3781
3821
|
const done2 = (result2) => {
|
|
3782
3822
|
off();
|
|
3783
3823
|
clearTimeout(timeout);
|
|
@@ -3785,7 +3825,7 @@ function createReach({ pi, cfg, s: s2, guiDir, me, role, tell: tell2 }, server =
|
|
|
3785
3825
|
};
|
|
3786
3826
|
const off = pi.events.on(OUTBOX_RESULT2, (data) => data.requestId === requestId && done2(data));
|
|
3787
3827
|
const timeout = setTimeout(() => done2({ status: "failed", detail: `no result within ${SEND_MS / 1e3} s` }), SEND_MS);
|
|
3788
|
-
pi.events.emit(OUTBOX2, { version: 1, requestId, extensionId: "pi-straw-boss", extensionName: "Pi Straw Boss", to, message });
|
|
3828
|
+
pi.events.emit(OUTBOX2, { version: 1, requestId, extensionId: "pi-straw-boss", extensionName: "Pi Straw Boss", to, message, ...exact2 ? { exact: true } : {}, ...confirm2 ? { confirm: true } : {} });
|
|
3789
3829
|
});
|
|
3790
3830
|
const live = async (id2) => {
|
|
3791
3831
|
try {
|
|
@@ -3794,10 +3834,10 @@ function createReach({ pi, cfg, s: s2, guiDir, me, role, tell: tell2 }, server =
|
|
|
3794
3834
|
return false;
|
|
3795
3835
|
}
|
|
3796
3836
|
};
|
|
3797
|
-
const send = async (to, message) => {
|
|
3837
|
+
const send = async (to, message, exact2 = false, confirm2 = false) => {
|
|
3798
3838
|
const requestId = `straw-boss-${me()}-${nonce}-${++requests}`;
|
|
3799
3839
|
const began = limits.retryCapMs === void 0 ? 0 : cfg.now(), capped = () => limits.retryCapMs !== void 0 && cfg.now() - began >= limits.retryCapMs;
|
|
3800
|
-
let result2 = await sendOnce(to, message, requestId);
|
|
3840
|
+
let result2 = await sendOnce(to, message, requestId, exact2, confirm2);
|
|
3801
3841
|
if (!to.startsWith("sb-tower-") && !to.startsWith("sb-head")) return result2;
|
|
3802
3842
|
for (let n = 1, waited = 0; n <= TOWER_RETRY_AT.length && (result2.status === "failed" || result2.status === "blocked") && !capped(); n++) {
|
|
3803
3843
|
const at = TOWER_RETRY_AT[n - 1];
|
|
@@ -3808,7 +3848,7 @@ function createReach({ pi, cfg, s: s2, guiDir, me, role, tell: tell2 }, server =
|
|
|
3808
3848
|
if (await live(to)) break;
|
|
3809
3849
|
}
|
|
3810
3850
|
if (capped()) break;
|
|
3811
|
-
result2 = await sendOnce(to, message, `${requestId}~r${n}
|
|
3851
|
+
result2 = await sendOnce(to, message, `${requestId}~r${n}`, exact2, confirm2);
|
|
3812
3852
|
}
|
|
3813
3853
|
return result2;
|
|
3814
3854
|
};
|
|
@@ -3887,13 +3927,13 @@ function createReach({ pi, cfg, s: s2, guiDir, me, role, tell: tell2 }, server =
|
|
|
3887
3927
|
const mine = net.sessions.find((x) => x.id === me()), workspace = net.all.find((w) => w.workspace_id === s2.at.workspaceId), head = me() === headIdOf(net.all);
|
|
3888
3928
|
return { name: nameOf(mine) || s2.ownName || me(), id: me(), role: role() ?? "session", ...head ? { head: true } : {}, ...head ? { workspace: "head" } : workspace ? { workspace: workspace.label } : {} };
|
|
3889
3929
|
};
|
|
3890
|
-
const deliver = async (targets, message, kind, scope, reply3, net, origin, why2, extra = {}) => {
|
|
3930
|
+
const deliver = async (targets, message, kind, scope, reply3, net, origin, why2, extra = {}, confirm2 = false) => {
|
|
3891
3931
|
const line4 = stamp({ from: selfParty(net), kind, scope, to: targets.map((x) => partyOf(x, net)), reply: reply3, ...origin ?? s2.remoteOrigin ? { origin: origin ?? s2.remoteOrigin } : {}, ...why2 ? { why: why2 } : {}, ...extra }, message);
|
|
3892
|
-
return Promise.all(targets.map(async (x) => ({ id: x.id, name: nameOf(x), ...await send(x.id, line4) })));
|
|
3932
|
+
return Promise.all(targets.map(async (x) => ({ id: x.id, name: nameOf(x), ...await send(x.id, line4, true, confirm2) })));
|
|
3893
3933
|
};
|
|
3894
|
-
const post = async (to, message, kind, scope, reply3, origin, why2, extra = {}) => {
|
|
3934
|
+
const post = async (to, message, kind, scope, reply3, origin, why2, extra = {}, confirm2 = false) => {
|
|
3895
3935
|
const net = await read4();
|
|
3896
|
-
const [result2] = await deliver([net.sessions.find((x) => x.id === to) ?? { id: to }], message, kind, scope, reply3, net, origin, why2, extra);
|
|
3936
|
+
const [result2] = await deliver([net.sessions.find((x) => x.id === to) ?? { id: to }], message, kind, scope, reply3, net, origin, why2, extra, confirm2);
|
|
3897
3937
|
return result2;
|
|
3898
3938
|
};
|
|
3899
3939
|
const callTower = async (message, workspace, reply3 = true, why2, extra = {}) => {
|
|
@@ -3969,7 +4009,7 @@ ${summary}`, details: { scope, results } };
|
|
|
3969
4009
|
}
|
|
3970
4010
|
}
|
|
3971
4011
|
const targets = chosen.flatMap((st) => st.sessions.map((x) => (noTower(st) && notes.set(x.id, noTower(st)), x)));
|
|
3972
|
-
return report4(await deliver(targets, message, "tower_send", workspace === void 0 ? "towers" : "tower", reply3, net, void 0, void 0, stamped), notes, workspace === void 0 ? "towers" : "tower");
|
|
4012
|
+
return report4(await deliver(targets, message, "tower_send", workspace === void 0 ? "towers" : "tower", reply3, net, void 0, void 0, stamped, stamped.fwd !== void 0), notes, workspace === void 0 ? "towers" : "tower");
|
|
3973
4013
|
};
|
|
3974
4014
|
const { forward: forward2, answerHead: answerHead2 } = createHeadReach({ read: read4, deliver });
|
|
3975
4015
|
const handOver = (workspace, pane) => ensureTowerVia(server.ctx(), { workspace, pane, cwd: process.cwd(), pid: process.pid });
|
|
@@ -10220,7 +10260,7 @@ function createSpawn({ run: run2, sleep: sleep2, call, live, sessionAt, home = h
|
|
|
10220
10260
|
}
|
|
10221
10261
|
};
|
|
10222
10262
|
const opened = async (workspace, tab, pane, delivery) => ({ status: 200, body: { workspace, tab, pane, ...delivery && { delivery }, ...sessionAt && { session: await sessionAt(pane) } } });
|
|
10223
|
-
const
|
|
10263
|
+
const delivered2 = (d, state, asked3) => {
|
|
10224
10264
|
const said2 = state === "sent" ? "sent" : state === "sending" ? "unknown" : state === "pending" && !asked3 ? "not_sent" : void 0;
|
|
10225
10265
|
d.delivery = said2;
|
|
10226
10266
|
return said2;
|
|
@@ -10350,7 +10390,7 @@ function createSpawn({ run: run2, sleep: sleep2, call, live, sessionAt, home = h
|
|
|
10350
10390
|
const failed3 = await deliver(d, pane.pane_id, prompt, (state) => void keep3(id2, { ...had, delivery: delivery = state }));
|
|
10351
10391
|
if (failed3) return failed3;
|
|
10352
10392
|
} else if (prompt) d.go("deliver");
|
|
10353
|
-
return opened(had.workspace, pane.tab_id, pane.pane_id,
|
|
10393
|
+
return opened(had.workspace, pane.tab_id, pane.pane_id, delivered2(d, delivery, Boolean(prompt)));
|
|
10354
10394
|
}
|
|
10355
10395
|
async function openBase(d, dir, label, prompt, id2, joinWaitMs) {
|
|
10356
10396
|
d.go("create");
|
|
@@ -10373,7 +10413,7 @@ function createSpawn({ run: run2, sleep: sleep2, call, live, sessionAt, home = h
|
|
|
10373
10413
|
}
|
|
10374
10414
|
return Promise.reject(error);
|
|
10375
10415
|
});
|
|
10376
|
-
return failed3 ?? opened(workspaceId, created.tab.tab_id, paneId,
|
|
10416
|
+
return failed3 ?? opened(workspaceId, created.tab.tab_id, paneId, delivered2(d, delivery, Boolean(prompt)));
|
|
10377
10417
|
}
|
|
10378
10418
|
const failed2 = (d, reply3) => {
|
|
10379
10419
|
if (reply3.status < 400) return d.finish(), reply3;
|
|
@@ -26414,7 +26454,236 @@ function remoteTowers(teams) {
|
|
|
26414
26454
|
}
|
|
26415
26455
|
|
|
26416
26456
|
// src/server/runtools.ts
|
|
26457
|
+
import { randomBytes as randomBytes26 } from "node:crypto";
|
|
26458
|
+
|
|
26459
|
+
// src/server/towergate.ts
|
|
26417
26460
|
import { randomBytes as randomBytes25 } from "node:crypto";
|
|
26461
|
+
import { join as join69 } from "node:path";
|
|
26462
|
+
|
|
26463
|
+
// src/carslip.ts
|
|
26464
|
+
var SLIP = /\b(?:car|app):[ \t]*[A-Za-z0-9._-]+[ \t]*\|[ \t]*(?:tickets|car):/i;
|
|
26465
|
+
var carriesSlip = (text14) => SLIP.test(text14) || slipLines(text14).split(/\r?\n/).some(startsSlip);
|
|
26466
|
+
|
|
26467
|
+
// src/server/towerseen.ts
|
|
26468
|
+
import { createHash as createHash22 } from "node:crypto";
|
|
26469
|
+
import { appendFileSync as appendFileSync6, readFileSync as readFileSync46 } from "node:fs";
|
|
26470
|
+
import { join as join68 } from "node:path";
|
|
26471
|
+
var SEEN_KEEP_MS = 48 * 36e5;
|
|
26472
|
+
var SEEN_MAX = 5e3;
|
|
26473
|
+
var SLACK = 500;
|
|
26474
|
+
var FILE = "seen.jsonl";
|
|
26475
|
+
var baseId = (messageId) => messageId.replace(/~r\d+$/, "");
|
|
26476
|
+
var hashOf2 = (text14) => createHash22("sha256").update(text14).digest("hex");
|
|
26477
|
+
var key = (from, base) => `${from}
|
|
26478
|
+
${base}`;
|
|
26479
|
+
var parse6 = (line4) => {
|
|
26480
|
+
try {
|
|
26481
|
+
const v = JSON.parse(line4);
|
|
26482
|
+
return typeof v.from === "string" && typeof v.base === "string" && typeof v.hash === "string" && typeof v.at === "number" ? { from: v.from, base: v.base, hash: v.hash, at: v.at } : void 0;
|
|
26483
|
+
} catch {
|
|
26484
|
+
return void 0;
|
|
26485
|
+
}
|
|
26486
|
+
};
|
|
26487
|
+
function openSeen(slot, workspace, now) {
|
|
26488
|
+
const file3 = join68(towerDir(slot, workspace), FILE);
|
|
26489
|
+
const rows = /* @__PURE__ */ new Map();
|
|
26490
|
+
let text14 = "", lines = 0;
|
|
26491
|
+
try {
|
|
26492
|
+
text14 = readFileSync46(file3, "utf8");
|
|
26493
|
+
} catch {
|
|
26494
|
+
}
|
|
26495
|
+
for (const line4 of text14.split("\n")) {
|
|
26496
|
+
const row2 = line4 ? parse6(line4) : void 0;
|
|
26497
|
+
if (row2) rows.set(key(row2.from, row2.base), row2), lines++;
|
|
26498
|
+
}
|
|
26499
|
+
let added = false;
|
|
26500
|
+
for (const event of [...readQueue(slot, workspace), ...readQueue(slot, workspace, true)]) {
|
|
26501
|
+
if (event.kind !== "intercom" || !event.messageId || !event.from) continue;
|
|
26502
|
+
const base = baseId(event.messageId), k = key(event.from.id, base);
|
|
26503
|
+
if (rows.has(k)) continue;
|
|
26504
|
+
rows.set(k, { from: event.from.id, base, hash: hashOf2(event.text), at: Date.parse(event.at) || now() });
|
|
26505
|
+
added = true;
|
|
26506
|
+
}
|
|
26507
|
+
const trim = () => {
|
|
26508
|
+
let dropped = false;
|
|
26509
|
+
for (const [k, row2] of rows) if (now() - row2.at > SEEN_KEEP_MS) rows.delete(k), dropped = true;
|
|
26510
|
+
while (rows.size > SEEN_MAX) rows.delete(rows.keys().next().value), dropped = true;
|
|
26511
|
+
return dropped;
|
|
26512
|
+
};
|
|
26513
|
+
const rewrite2 = () => {
|
|
26514
|
+
ensureDir(towerDir(slot, workspace));
|
|
26515
|
+
writeDurableText(file3, [...rows.values()].map((r) => JSON.stringify(r)).join("\n") + (rows.size ? "\n" : ""));
|
|
26516
|
+
lines = rows.size;
|
|
26517
|
+
};
|
|
26518
|
+
if (trim() || added) {
|
|
26519
|
+
try {
|
|
26520
|
+
rewrite2();
|
|
26521
|
+
} catch {
|
|
26522
|
+
}
|
|
26523
|
+
}
|
|
26524
|
+
return {
|
|
26525
|
+
check(from, messageId, body2) {
|
|
26526
|
+
const found = rows.get(key(from, baseId(messageId)));
|
|
26527
|
+
return !found ? "new" : found.hash === hashOf2(body2) ? "seen" : "conflict";
|
|
26528
|
+
},
|
|
26529
|
+
add(from, messageId, body2, at = now()) {
|
|
26530
|
+
const row2 = { from, base: baseId(messageId), hash: hashOf2(body2), at };
|
|
26531
|
+
rows.delete(key(from, row2.base));
|
|
26532
|
+
rows.set(key(from, row2.base), row2);
|
|
26533
|
+
trim();
|
|
26534
|
+
if (lines >= SEEN_MAX + SLACK) return rewrite2();
|
|
26535
|
+
lines++;
|
|
26536
|
+
ensureDir(towerDir(slot, workspace));
|
|
26537
|
+
appendFileSync6(file3, `${JSON.stringify(row2)}
|
|
26538
|
+
`, { mode: 384 });
|
|
26539
|
+
},
|
|
26540
|
+
size: () => rows.size
|
|
26541
|
+
};
|
|
26542
|
+
}
|
|
26543
|
+
|
|
26544
|
+
// src/server/towergate.ts
|
|
26545
|
+
var ROUTED = ["waits-on", "ask", "relay", "in-reply-to", "fwd", "origin", "remote", "handed-to"];
|
|
26546
|
+
var TRAIN_LINE = /^[ \t>*-]*["']?train["']?[ \t]*:/im;
|
|
26547
|
+
var TRAIN_BLOCK = /^[ \t>*-]*["']?train["']?[ \t]*:[ \t]*(?:\{.*)?$/im;
|
|
26548
|
+
var MANIFEST_KEY = /^[ \t>*-]*["']?(?:project|code)["']?[ \t]*[:=]/im;
|
|
26549
|
+
var isManifest = (body2) => TRAIN_BLOCK.test(body2) || TRAIN_LINE.test(body2) && MANIFEST_KEY.test(body2);
|
|
26550
|
+
var escaped = (s2) => s2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
26551
|
+
var handedBefore = (body2, from) => new RegExp(`^\\s*Straw Boss: main [^\\n]*? \\(session ${escaped(from)}\\) handed over to its successor in tab \\S+ \\(session \\S+\\), which took the handoff\\. `).test(body2);
|
|
26552
|
+
function sortCall(text14, from, asked3) {
|
|
26553
|
+
const f = fieldsOf(text14);
|
|
26554
|
+
if (f?.kind !== "call_tower" || ROUTED.some((k) => f[k] !== void 0) || f.why !== "milestone" && f.why !== "shared") return { book: false };
|
|
26555
|
+
const body2 = bodyOf(text14), train = trainFromRequest(body2);
|
|
26556
|
+
if (isManifest(body2)) return "refusal" in train ? { book: "reject", why: train.refusal } : { book: false };
|
|
26557
|
+
if (carriesSlip(body2) || !("refusal" in train) || handedBefore(body2, from)) return { book: false };
|
|
26558
|
+
if (asked3.expects(from)) return { book: f.why === "milestone" ? "milestone" : "heads-up", wake: true };
|
|
26559
|
+
return f.why === "milestone" ? { book: "milestone", wake: asked3.opened(from) } : { book: "heads-up", wake: false };
|
|
26560
|
+
}
|
|
26561
|
+
var hhmm3 = (ms4) => ((d) => `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`)(new Date(ms4));
|
|
26562
|
+
var who2 = (e) => `${fenced(e.from.name, 40)} (${e.from.id}) of ${cutText(e.label, 40)}`;
|
|
26563
|
+
var words2 = (text14) => fenced(text14, 200);
|
|
26564
|
+
var CHECK = "These are the mains' own words. If they really collide, tell both with tower_reply (another workspace's main through its tower, tower_send); a shared name alone may be no clash.";
|
|
26565
|
+
var LOCK_NAME = "logbook";
|
|
26566
|
+
var LOCK_POLL_MS = 25;
|
|
26567
|
+
var LOCK_WAIT_MS2 = 3e3;
|
|
26568
|
+
var logbookLockDir = (stateDir) => join69(stateDir, "logbook-lock");
|
|
26569
|
+
function createGate(d) {
|
|
26570
|
+
const inflight = /* @__PURE__ */ new Map();
|
|
26571
|
+
const sleep2 = d.sleep ?? ((ms4) => new Promise((done2) => setTimeout(done2, ms4)));
|
|
26572
|
+
let own;
|
|
26573
|
+
const lock = async () => {
|
|
26574
|
+
const until = d.now() + LOCK_WAIT_MS2;
|
|
26575
|
+
for (; ; ) {
|
|
26576
|
+
let taken;
|
|
26577
|
+
try {
|
|
26578
|
+
own ??= (d.lock?.startOf ?? startOf)(process.pid);
|
|
26579
|
+
taken = takeLock(logbookLockDir(d.slot.stateDir), LOCK_NAME, { train: LOCK_NAME, step: 0, ...own ? { started: own } : {} }, d.lock);
|
|
26580
|
+
} catch (cause) {
|
|
26581
|
+
return { busy: `the logbook lock could not be taken: ${cutText(cause.message, 80)}` };
|
|
26582
|
+
}
|
|
26583
|
+
if (taken.ok) return taken;
|
|
26584
|
+
if (d.now() >= until) return { busy: `the logbook lock stayed ${taken.why}${taken.holder ? ` by pid ${taken.holder.pid}` : ""} for ${LOCK_WAIT_MS2 / 1e3} s` };
|
|
26585
|
+
await sleep2(LOCK_POLL_MS);
|
|
26586
|
+
}
|
|
26587
|
+
};
|
|
26588
|
+
const reply3 = async (i, from, fields, text14, wake = fields.reply === "expected") => {
|
|
26589
|
+
const role = ROLE_WORDS.includes(fields.role ?? "") ? fields.role : "session";
|
|
26590
|
+
const line4 = stamp({ from: { name: i.record.name, id: i.record.id, role: "tower", workspace: i.record.label }, kind: "tower_reply", scope: "session", to: [{ name: from.name ?? from.id, id: from.id, role, ...fields.workspace ? { workspace: fields.workspace } : {} }], reply: false }, text14);
|
|
26591
|
+
const sent = await i.client?.send(from.id, { text: line4, messageId: `sb-gate-${randomBytes25(8).toString("hex")}`, ...wake ? {} : { noWake: true } });
|
|
26592
|
+
if (!sent?.delivered) d.log("tower-gate-reply", { workspace: i.record.workspace, to: from.id, why: sent?.reason ?? "no connection" });
|
|
26593
|
+
};
|
|
26594
|
+
const headsUpClash = (e) => {
|
|
26595
|
+
for (const o of openHeadsUps(allEntries(d.slot.stateDir, d.now()), d.now())) {
|
|
26596
|
+
const on2 = o.from.id === e.from.id ? [] : shared(e.resources ?? [], o.resources ?? []);
|
|
26597
|
+
if (on2.length) return { short: `the heads-up of ${fenced(o.from.name, 40)} (${o.from.id.slice(0, 8)}) on ${fenced(on2.slice(0, 3).join(", "), 60)}`, notice: `Heads-up clash, seen by sb: ${who2(e)}: ${words2(e.text)} overlaps the heads-up of ${who2(o)}, open until ${hhmm3(o.until ?? o.at)}: ${words2(o.text)}, on ${fenced(on2.slice(0, 5).join(", "), 120)}. ${CHECK}` };
|
|
26598
|
+
}
|
|
26599
|
+
return void 0;
|
|
26600
|
+
};
|
|
26601
|
+
const boardClash = (net, e) => {
|
|
26602
|
+
const ws = net.sessions.find((s2) => s2.id === e.from.id)?.herdrLocation?.workspace?.id ?? e.workspace;
|
|
26603
|
+
const mains = new Map(net.sessions.filter((s2) => s2.id !== e.from.id && s2.herdrLocation?.workspace?.id === ws && /* @__PURE__ */ ((r) => r === "main" || r === "train")(net.ps.find((p) => p.pane_id === s2.herdrLocation?.paneId)?.tokens?.sb_role)).map((s2) => [s2.id, s2]));
|
|
26604
|
+
for (const entry of readEntries(join69(d.slot.stateDir, "board"))) {
|
|
26605
|
+
const main = mains.get(entry.session), text14 = [entry.now, ...entry.items.filter((x) => !x.done).map((x) => x.t)].join(" \xB7 ");
|
|
26606
|
+
const on2 = main ? shared(e.resources ?? [], resourcesOf(text14)) : [];
|
|
26607
|
+
if (on2.length) return { short: `the board of ${fenced(main.name ?? main.id, 40)} (${main.id.slice(0, 8)}) on ${fenced(on2.slice(0, 3).join(", "), 60)}`, notice: `Heads-up clash, seen by sb: ${who2(e)}: ${words2(e.text)} overlaps the board of ${fenced(main.name ?? main.id, 40)} (${main.id}), a main of the sender's workspace: ${words2(text14)}, on ${fenced(on2.slice(0, 5).join(", "), 120)}. ${CHECK}` };
|
|
26608
|
+
}
|
|
26609
|
+
return void 0;
|
|
26610
|
+
};
|
|
26611
|
+
const netOf = (i) => (i.read ? i.read() : Promise.reject(new Error("no net reader"))).catch((cause) => cause);
|
|
26612
|
+
const classify = async (i, from, sort, e) => {
|
|
26613
|
+
if (sort.book === "milestone") {
|
|
26614
|
+
if (sort.wake) return { wake: true, why: "it answers the tower's request" };
|
|
26615
|
+
const net2 = await netOf(i);
|
|
26616
|
+
if (net2 instanceof Error) return { wake: true, why: `the net could not be read: ${cutText(net2.message, 80)}` };
|
|
26617
|
+
return net2.ps.find((p) => p.pane_id === net2.sessions.find((s2) => s2.id === from.id)?.herdrLocation?.paneId)?.tokens?.sb_opened_by ? { wake: true, why: "a main a tower opened" } : { wake: false };
|
|
26618
|
+
}
|
|
26619
|
+
if (sort.wake) return { wake: true, why: "a session this tower asked" };
|
|
26620
|
+
if (!e.resources?.length) return { wake: false };
|
|
26621
|
+
const net = await netOf(i);
|
|
26622
|
+
if (net instanceof Error) return { wake: true, why: `the boards could not be read: ${cutText(net.message, 80)}` };
|
|
26623
|
+
const board = boardClash(net, e);
|
|
26624
|
+
return board ? { wake: true, why: "board", clash: board } : { wake: false };
|
|
26625
|
+
};
|
|
26626
|
+
const answer = (i, from, fields, e) => e.kind === "milestone" ? fields.reply === "expected" ? reply3(i, from, fields, "sb: recorded your milestone in the tower's logbook; a milestone wakes no tower run, so no answer comes. If you need one, call_tower again with why blocked.") : Promise.resolve() : reply3(i, from, fields, e.resources?.length ? `sb: recorded your heads-up for the tower (open until ${hhmm3(e.until)}); no clash seen with the open heads-ups or your workspace's boards, so no tower run woke. Go ahead.` : `sb: recorded your heads-up for the tower (open until ${hhmm3(e.until)}); it names nothing sb can compare (a port, branch, database, host, or deploy target), so no clash can be seen and no tower run woke. Go ahead.`);
|
|
26627
|
+
const settle2 = async (i, from, message, sort, hash3) => {
|
|
26628
|
+
const ws = i.record.workspace, text14 = message.content.text, now = d.now(), fields = fieldsOf(text14), body2 = bodyOf(text14);
|
|
26629
|
+
const fail2 = (cause) => d.log("tower-gate-error", { workspace: ws, from: from.id, error: cutText(cause.message, 200) });
|
|
26630
|
+
if (sort.book === "reject") {
|
|
26631
|
+
i.seen();
|
|
26632
|
+
d.log("tower-gate-refused", { workspace: ws, from: from.id, why: cutText(sort.why, 200) });
|
|
26633
|
+
void reply3(i, from, fields, `sb: your message reads as a train manifest, and it is refused: ${cutText(sort.why, 200)}. Nothing was recorded or opened: fix it and send it again with call_tower (why shared).`, true).catch(fail2);
|
|
26634
|
+
return true;
|
|
26635
|
+
}
|
|
26636
|
+
const base = { kind: sort.book, workspace: ws, label: i.record.label, at: now, from: { id: from.id, name: cutText(from.name ?? from.id, 80) }, text: cutText(body2), msg: baseId(message.id), hash: hash3, ...fields.reply === "expected" ? { reply: true } : {} };
|
|
26637
|
+
const draft = sort.book === "heads-up" ? { ...base, resources: resourcesOf(body2), until: untilOf2(body2, now) } : base;
|
|
26638
|
+
const read4 = await classify(i, from, sort, draft), held2 = sort.book === "heads-up" ? await lock() : void 0;
|
|
26639
|
+
let verdict, e;
|
|
26640
|
+
try {
|
|
26641
|
+
const hit = sort.book === "heads-up" ? headsUpClash(draft) : void 0;
|
|
26642
|
+
verdict = hit ? { wake: true, why: "heads-up", clash: hit } : !read4.wake && held2 && "busy" in held2 ? { wake: true, why: held2.busy } : read4;
|
|
26643
|
+
e = addEntry2(d.slot.dir, { ...draft, ...verdict.wake ? { woke: true, ...verdict.clash ? { clash: verdict.clash.short } : {} } : {} }, now);
|
|
26644
|
+
} finally {
|
|
26645
|
+
if (held2 && "release" in held2) held2.release();
|
|
26646
|
+
}
|
|
26647
|
+
if (e.hash !== void 0 && e.hash !== hash3) {
|
|
26648
|
+
d.log("tower-dropped", { workspace: ws, from: from.id, why: "the same message id with other content" });
|
|
26649
|
+
return false;
|
|
26650
|
+
}
|
|
26651
|
+
const why2 = verdict.wake ? verdict.why : "recorded so before";
|
|
26652
|
+
d.log("tower-recorded", { workspace: ws, kind: e.kind, from: from.id, seq: String(e.seq), wake: e.woke ? why2 : "no" });
|
|
26653
|
+
if (e.woke) {
|
|
26654
|
+
if (verdict.wake && verdict.clash) d.notice(ws, verdict.clash.notice, `clash:${ws}:${e.seq}`);
|
|
26655
|
+
d.log("tower-gate-wake", { workspace: ws, kind: e.kind, from: from.id, seq: String(e.seq), why: why2 });
|
|
26656
|
+
i.queue();
|
|
26657
|
+
return true;
|
|
26658
|
+
}
|
|
26659
|
+
i.seen();
|
|
26660
|
+
d.log("tower-gate-quiet", { workspace: ws, kind: e.kind, from: from.id, seq: String(e.seq) });
|
|
26661
|
+
void answer(i, from, fields, e).catch(fail2);
|
|
26662
|
+
return true;
|
|
26663
|
+
};
|
|
26664
|
+
return {
|
|
26665
|
+
/**
|
|
26666
|
+
* False when the intake queues the message as before; else the gate's work on it, which ends once the call is recorded and queued or seen, true when the intake receipts it then: a retry of a call in flight
|
|
26667
|
+
* (its base id) shares that call's end when its text is the same, and is dropped, unreceipted, when it is not.
|
|
26668
|
+
*/
|
|
26669
|
+
take(i, from, message) {
|
|
26670
|
+
const ws = i.record.workspace, now = d.now();
|
|
26671
|
+
const hash3 = hashOf2(message.content.text), key2 = `${i.record.id}
|
|
26672
|
+
${from.id}
|
|
26673
|
+
${baseId(message.id)}`, running = inflight.get(key2);
|
|
26674
|
+
if (running?.hash === hash3) return running.job;
|
|
26675
|
+
if (running) {
|
|
26676
|
+
d.log("tower-dropped", { workspace: ws, from: from.id, why: "the same message id with other content" });
|
|
26677
|
+
return Promise.resolve(false);
|
|
26678
|
+
}
|
|
26679
|
+
const sort = sortCall(message.content.text, from.id, { opened: (id2) => readLedger(d.slot, ws, now).some((r) => r.outcome === "opened" && r.opened?.main === id2), expects: (id2) => readExpects(d.slot, ws, now).some((x) => x.to === id2) });
|
|
26680
|
+
if (!sort.book) return false;
|
|
26681
|
+
const job = settle2(i, from, message, sort, hash3).finally(() => inflight.delete(key2));
|
|
26682
|
+
inflight.set(key2, { hash: hash3, job });
|
|
26683
|
+
return job;
|
|
26684
|
+
}
|
|
26685
|
+
};
|
|
26686
|
+
}
|
|
26418
26687
|
|
|
26419
26688
|
// src/server/runevents.ts
|
|
26420
26689
|
var phrase7 = (value, max) => typeof value === "string" ? value.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max) : "";
|
|
@@ -26424,10 +26693,22 @@ var markHandled = (run2, event) => {
|
|
|
26424
26693
|
for (const key2 of handled.keys()) if (handled.size > 200) handled.delete(key2);
|
|
26425
26694
|
else break;
|
|
26426
26695
|
};
|
|
26696
|
+
var delivered = /* @__PURE__ */ new Map();
|
|
26697
|
+
var markDelivered = (run2, event) => {
|
|
26698
|
+
delivered.set(run2, (delivered.get(run2) ?? /* @__PURE__ */ new Set()).add(event));
|
|
26699
|
+
for (const key2 of delivered.keys()) if (delivered.size > 200) delivered.delete(key2);
|
|
26700
|
+
else break;
|
|
26701
|
+
};
|
|
26427
26702
|
var waitOf2 = (e) => {
|
|
26428
26703
|
const f = fieldsOf(e.text);
|
|
26429
26704
|
return f?.kind === "call_tower" && f["waits-on"] && f["waits-cancel"] !== "yes" && e.from ? { id: e.id, from: e.from, short: f["waits-on"], owner: f["waits-owner"] ?? "", what: f["waits-what"] ?? "" } : void 0;
|
|
26430
26705
|
};
|
|
26706
|
+
var slipCallOf = (e) => {
|
|
26707
|
+
const f = fieldsOf(e.text), body2 = bodyOf(e.text);
|
|
26708
|
+
if (f?.kind !== "call_tower" || f.why !== "shared" || !e.from || isManifest(body2)) return void 0;
|
|
26709
|
+
const slips = slipsInText(body2);
|
|
26710
|
+
return slips.length ? { id: e.id, from: e.from, app: slips[0].app, tickets: slips.flatMap((s2) => s2.tickets), heads: slips.map((s2) => s2.head), body: body2.replace(/\r\n?/g, "\n").split("\n").map((l) => l.trimEnd()).join("\n").trim() } : void 0;
|
|
26711
|
+
};
|
|
26431
26712
|
function runEvents(d) {
|
|
26432
26713
|
const taken = () => readQueue(d.slot, d.ws).filter((e) => e.taken?.run === d.who.id && e.kind === "intercom" && e.from);
|
|
26433
26714
|
const callers = () => new Set(taken().filter((e) => ((f) => f?.kind === "call_tower" && f.reply === "expected")(fieldsOf(e.text))).map((e) => e.from.id));
|
|
@@ -26454,7 +26735,7 @@ function runEvents(d) {
|
|
|
26454
26735
|
},
|
|
26455
26736
|
/** The waits-on calls this run took: `tower_send` names one by id and takes device, owner, what, and the raiser from it. */
|
|
26456
26737
|
waitEvents: () => taken().map(waitOf2).filter((e) => e !== void 0),
|
|
26457
|
-
/** A `tower_reply` to a raiser answers its waits-on events in this run: the guard lets the run end. */
|
|
26738
|
+
/** A `tower_reply` to a raiser answers its waits-on events in this run: the guard lets the run end. A car slip is settled by a reply that names it (runtools.ts `slip`), one at a time (FWD-F004). */
|
|
26458
26739
|
replied: (to) => taken().flatMap((e) => e.from?.id === to && waitOf2(e) ? [e.id] : []).forEach((id2) => markHandled(d.who.id, id2))
|
|
26459
26740
|
};
|
|
26460
26741
|
}
|
|
@@ -26475,15 +26756,40 @@ ${w.short}`);
|
|
|
26475
26756
|
}
|
|
26476
26757
|
return void 0;
|
|
26477
26758
|
}
|
|
26759
|
+
function unforwardedSlip(slot, ws, run2, o = {}) {
|
|
26760
|
+
const took = readQueue(slot, ws).filter((e) => e.taken?.run === run2 && e.kind === "intercom").flatMap((e) => ((c) => c ? [{ c, at: Date.parse(e.taken.at) }] : [])(slipCallOf(e)));
|
|
26761
|
+
const sent = (id2) => delivered.get(run2)?.has(id2) === true, settled = (id2) => sent(id2) || handled.get(run2)?.has(id2) === true;
|
|
26762
|
+
for (const [i, { c, at }] of took.entries()) {
|
|
26763
|
+
if (settled(c.id)) continue;
|
|
26764
|
+
const copied = took.slice(i + 1).some(({ c: d }) => sent(d.id) && d.from.id === c.from.id && d.body === c.body);
|
|
26765
|
+
const why2 = copied ? "same-slip" : o.live?.size && !o.live.has(c.from.id) ? "sender-gone" : o.startedAt !== void 0 && at < o.startedAt ? "restart" : void 0;
|
|
26766
|
+
if (why2) {
|
|
26767
|
+
markHandled(run2, c.id);
|
|
26768
|
+
o.log?.("slip-guard-released", { workspace: ws, run: run2, event: c.id, why: why2 });
|
|
26769
|
+
continue;
|
|
26770
|
+
}
|
|
26771
|
+
o.log?.("slip-guard-held", { workspace: ws, run: run2, event: c.id });
|
|
26772
|
+
const name2 = phrase7(c.from.name ?? c.from.id, 40) || c.from.id;
|
|
26773
|
+
return `Car slip ${c.tickets.map((t) => phrase7(t, 40)).join(", ")} (${phrase7(c.app, 40)}, head ${c.heads[0].slice(0, 12)}) from ${name2} came in event ${c.id}, and no integrator took it from this run: forward it with boss_open_main {role: "integrator", request: the slip as it came, sender: "${c.from.id}"} (where the door names the integrators but opens none, with tower_reply to one of them and forward: "${c.id}"), or tell ${name2} why it does not go with tower_reply {to: "${c.from.id}", slip: "${c.id}", message}, then call tower_done again`;
|
|
26774
|
+
}
|
|
26775
|
+
return void 0;
|
|
26776
|
+
}
|
|
26478
26777
|
|
|
26479
26778
|
// src/server/runtools.ts
|
|
26480
26779
|
var NO_TARGET = "tower_reply has no such target: no session of this computer that an ally run may write to has that name or id";
|
|
26481
26780
|
async function refuseTarget(host, query) {
|
|
26482
26781
|
const net = await host.reach.read(), named = net.sessions.filter((s2) => s2.id === query || s2.name === query);
|
|
26483
|
-
if (named.length
|
|
26484
|
-
|
|
26782
|
+
if (named.length === 1) refuseHeld(host, net, named[0]);
|
|
26783
|
+
}
|
|
26784
|
+
function refuseHeld(host, net, target2) {
|
|
26785
|
+
const token = net.ps.find((p) => p.pane_id === target2.herdrLocation?.paneId)?.tokens?.sb_opened_by;
|
|
26485
26786
|
const byToken = typeof token === "string" && token.startsWith("link:") ? token.replace(/^(link:)+/, "") : void 0;
|
|
26486
|
-
for (const held2 of [byToken, host.openedFor?.(
|
|
26787
|
+
for (const held2 of [byToken, host.openedFor?.(target2.id)]) if (held2 !== void 0 && held2 !== host.who.device) throw new Error(NO_TARGET);
|
|
26788
|
+
}
|
|
26789
|
+
var TO_TOWER = "An ally run may not write to a tower identity of this computer: it would carry a peer's text into a local run";
|
|
26790
|
+
async function refuseFinal(host, net, target2) {
|
|
26791
|
+
if (/^sb-tower-/.test(target2.id) || net.ps.find((p) => p.pane_id === target2.herdrLocation?.paneId)?.tokens?.sb_role === "tower" || await host.isTower(target2.id)) throw new Error(TO_TOWER);
|
|
26792
|
+
refuseHeld(host, net, target2);
|
|
26487
26793
|
}
|
|
26488
26794
|
var NO_CLOSE = "boss_close_main has no such target: no main opened for this run's device has that name or id";
|
|
26489
26795
|
async function refuseClose(host, query) {
|
|
@@ -26520,6 +26826,7 @@ async function forwardOf(host, args, to) {
|
|
|
26520
26826
|
return { fwd: event.id, fwdFrom: event.from, body: bodyOf(event.text) };
|
|
26521
26827
|
}
|
|
26522
26828
|
var sentTo = (details) => (details?.results ?? []).filter((r) => r.status === "sent").map((r) => r.id);
|
|
26829
|
+
var forwarded = (host, f) => void (f.to.length && (markDelivered(host.who.id, f.fwd), host.noteForward?.(f)));
|
|
26523
26830
|
async function runTool(host, kind, name2, args, extra = {}) {
|
|
26524
26831
|
if (!TOOLS.includes(name2)) throw new Error(`No such tool: ${name2}`);
|
|
26525
26832
|
if (kind === "ally") return allyTool(host, name2, args, extra);
|
|
@@ -26559,7 +26866,7 @@ async function allyTool(host, name2, args, extra) {
|
|
|
26559
26866
|
}
|
|
26560
26867
|
if (name2 === "tower_reply") {
|
|
26561
26868
|
const to = str12(args, "to", 200);
|
|
26562
|
-
if (await host.isTower(to)) throw new Error(
|
|
26869
|
+
if (await host.isTower(to)) throw new Error(TO_TOWER);
|
|
26563
26870
|
await refuseTarget(host, to);
|
|
26564
26871
|
}
|
|
26565
26872
|
if (name2 === "boss_close_main" && (args.pane !== void 0 || args.main === void 0)) throw new Error("An ally run closes only a main opened for its own device: dead panes are the local tower's");
|
|
@@ -26676,9 +26983,9 @@ async function openIntegrator(host, args, ally) {
|
|
|
26676
26983
|
const body2 = bodyOf(event.text), stamped = { fwd: event.fwd, fwdFrom: event.from.id };
|
|
26677
26984
|
const opened = await askOpener(host, slip, ally), named = opened.integrator ?? project ?? "";
|
|
26678
26985
|
if ((host.openedAnywhere ?? host.openedFor)?.(opened.main) !== void 0) throw new Error(`The main that answers as the integrator of project ${named} (session ${opened.main}) was opened for a teammate's device, so no slip goes to it; a project's integrator is this computer's own. The boss closes it or renames it.`);
|
|
26679
|
-
const result2 = await host.reach.post(opened.main, body2, "tower_reply", "session", false, ally && host.who.device ? `remote:${host.who.device}` : void 0, void 0, stamped);
|
|
26986
|
+
const result2 = await host.reach.post(opened.main, body2, "tower_reply", "session", false, ally && host.who.device ? `remote:${host.who.device}` : void 0, void 0, stamped, true);
|
|
26680
26987
|
if (result2.status !== "sent") throw new Error(`The integrator of project ${named} (session ${opened.main}) ${opened.repeated ? "runs" : "was opened"} but did not take the slip: ${result2.status} ${result2.code ?? ""} ${result2.detail ?? ""}`.trim());
|
|
26681
|
-
host
|
|
26988
|
+
forwarded(host, { fwd: stamped.fwd, from: stamped.fwdFrom, to: [opened.main], text: body2 });
|
|
26682
26989
|
const text14 = `${opened.repeated ? `The integrator of project ${named} already runs (session ${opened.main}); nothing opened.` : `Opened tab ${opened.tab} with the integrator of project ${named} (session ${opened.main}), this tower's own main.`} The slip of ${clean(event.from.name ?? event.from.id, 40)} was forwarded to it as it came, stamped with its sender. The sb server tells the sender what becomes of the car; relay nothing back.`;
|
|
26683
26990
|
return { text: text14, details: { ...opened, fwd: stamped.fwd } };
|
|
26684
26991
|
}
|
|
@@ -26702,7 +27009,7 @@ async function towerSendDevice(host, args, forced, ally = false) {
|
|
|
26702
27009
|
else if (forWho !== void 0) main = await host.mainOf(forWho);
|
|
26703
27010
|
else if (requester) main = requester;
|
|
26704
27011
|
const reply3 = args.reply === true || args.reply === void 0 && main !== void 0;
|
|
26705
|
-
if (main) ask =
|
|
27012
|
+
if (main) ask = randomBytes26(16).toString("hex");
|
|
26706
27013
|
const wait2 = event && host.waits ? { id: host.waits.newId(), state: "open", owner: waitOwner(event.owner), what: waitWhat(event.what) || "(no summary)", handle: host.waits.handleOf(event.from.id) } : void 0;
|
|
26707
27014
|
const answer = await host.link({ op: "send", device, text: message, reply: reply3, ...opt3(args, "workspace") ? { workspace: opt3(args, "workspace") } : {}, ...ask ? { awaitsReply: ask } : {}, ...inReplyTo ? { inReplyTo } : {}, ...wait2 ? { wait: wait2 } : {} });
|
|
26708
27015
|
if (!answer.ok) throw new Error(String(answer.error));
|
|
@@ -26774,24 +27081,33 @@ async function localTool(host, name2, args, extra, ally = false) {
|
|
|
26774
27081
|
if (opt3(args, "for") !== void 0 || opt3(args, "inReplyTo") !== void 0) throw new Error("for and inReplyTo go with a device");
|
|
26775
27082
|
const stamped = await forwardOf(host, args), message = stamped?.body ?? str12(args, "message");
|
|
26776
27083
|
const done2 = await reach.towerSend(message, opt3(args, "workspace"), args.reply === true, stamped ? { fwd: stamped.fwd, fwdFrom: stamped.fwdFrom } : {});
|
|
26777
|
-
if (stamped)
|
|
27084
|
+
if (stamped && !sentTo(done2.details).length) throw new Error(`forward ${stamped.fwd} reached no session: nothing was forwarded, since no other workspace has a tower or a joined session to hear it. Forward the slip with boss_open_main {role: "integrator"}, or name the workspace whose tower takes it`);
|
|
27085
|
+
if (stamped) forwarded(host, { fwd: stamped.fwd, from: stamped.fwdFrom, to: sentTo(done2.details), text: message });
|
|
26778
27086
|
for (const id2 of sentTo(done2.details)) host.decided?.(id2, message, args.basis);
|
|
26779
27087
|
return done2;
|
|
26780
27088
|
}
|
|
26781
27089
|
case "tower_reply": {
|
|
26782
|
-
const to = str12(args, "to", 200), message = str12(args, "message", 16384);
|
|
26783
|
-
if (
|
|
27090
|
+
const to = str12(args, "to", 200), message = str12(args, "message", 16384), slipId = opt3(args, "slip");
|
|
27091
|
+
if (slipId !== void 0 && args.forward !== void 0) throw new Error("Give slip or forward, not both: forward sends the slip on, slip tells its sender why it does not go");
|
|
27092
|
+
if (slipId !== void 0 && ally) throw new Error("An ally run answers no car slip: slip is for the tower runs of this computer");
|
|
26784
27093
|
const net = await reach.read();
|
|
26785
|
-
const
|
|
27094
|
+
const exact2 = net.sessions.filter((s2) => s2.id === to || s2.name === to);
|
|
27095
|
+
const prefixed = exact2.length || ally || to.length < 8 ? [] : net.sessions.filter((s2) => s2.id.startsWith(to));
|
|
27096
|
+
if (prefixed.length > 1) throw new Error(`Several live sessions have an id that starts with "${to}": give the whole id`);
|
|
27097
|
+
const named = prefixed.length ? prefixed : exact2;
|
|
26786
27098
|
const kept = named.length === 0 && !ally ? await host.missed?.(to, message) : void 0;
|
|
26787
27099
|
if (kept) throw new Error(kept);
|
|
26788
27100
|
if (named.length !== 1) throw new Error(`${named.length ? "Several sessions are named" : "No live session is named or has the id"} "${to}"`);
|
|
26789
27101
|
const target2 = named[0], shown3 = clean(target2.name ?? target2.id, 40);
|
|
27102
|
+
if (ally) await refuseFinal(host, net, target2);
|
|
27103
|
+
const answered = slipId === void 0 ? void 0 : host.forwardEvent?.(slipId);
|
|
27104
|
+
if (slipId !== void 0 && (!answered || answered.from !== target2.id || !slipsInText(bodyOf(answered.text)).length)) throw new Error(`slip ${slipId.slice(0, 40)} is no car slip that ${shown3} sent this run: give the [event id: \u2026] of a call_tower (why=shared) with a car slip that ${shown3} sent`);
|
|
26790
27105
|
if (!ally && target2.id === headIdOf(net.all)) throw new Error('Not delivered: the head tower takes no tower_reply. Answer it with tower_send {head: true, inReplyTo: "H<n>", message} (H<n> is the ask id in the header of its message).');
|
|
26791
27106
|
const stamped = await forwardOf(host, args, target2.id), sent = stamped?.body ?? message;
|
|
26792
|
-
const result2 = await reach.post(target2.id, sent, "tower_reply", "session", args.reply === true, ally && host.who.device ? `remote:${host.who.device}` : void 0, void 0, stamped ? { fwd: stamped.fwd, fwdFrom: stamped.fwdFrom } : {});
|
|
27107
|
+
const result2 = await reach.post(target2.id, sent, "tower_reply", "session", args.reply === true, ally && host.who.device ? `remote:${host.who.device}` : void 0, void 0, stamped ? { fwd: stamped.fwd, fwdFrom: stamped.fwdFrom } : {}, stamped !== void 0 || answered !== void 0);
|
|
26793
27108
|
if (result2.status !== "sent") throw new Error(`${shown3} did not take the message: ${result2.status} ${result2.code ?? ""} ${result2.detail ?? ""}`.trim());
|
|
26794
|
-
if (
|
|
27109
|
+
if (answered) markHandled(host.who.id, answered.id);
|
|
27110
|
+
if (stamped) forwarded(host, { fwd: stamped.fwd, from: stamped.fwdFrom, to: [target2.id], text: sent });
|
|
26795
27111
|
host.decided?.(target2.id, message, args.basis);
|
|
26796
27112
|
if (args.reply === true) host.expect(target2.id, shown3, message);
|
|
26797
27113
|
return { text: `Sent to ${shown3}.${stamped ? " The slip went as its sender wrote it, from the event: nothing of your message was sent." : ""}`, details: { to: target2.id, status: result2.status } };
|
|
@@ -27169,9 +27485,9 @@ function createStow(o) {
|
|
|
27169
27485
|
|
|
27170
27486
|
// src/server/runchild.ts
|
|
27171
27487
|
import { execFile as execFile2, spawn as nodeSpawn } from "node:child_process";
|
|
27172
|
-
import { randomBytes as
|
|
27173
|
-
import { appendFileSync as
|
|
27174
|
-
import { delimiter, dirname as dirname19, join as
|
|
27488
|
+
import { randomBytes as randomBytes27 } from "node:crypto";
|
|
27489
|
+
import { appendFileSync as appendFileSync7, mkdirSync as mkdirSync20, readFileSync as readFileSync47, readdirSync as readdirSync17, realpathSync as realpathSync11, rmSync as rmSync16, statSync as statSync17 } from "node:fs";
|
|
27490
|
+
import { delimiter, dirname as dirname19, join as join70, win32 as win323 } from "node:path";
|
|
27175
27491
|
var STDIN_ALLOWED = ["abort", "extension_ui_response", "get_state"];
|
|
27176
27492
|
var STDERR_CAP = 256 * 1024;
|
|
27177
27493
|
var STDERR_KEEP = 20;
|
|
@@ -27185,12 +27501,12 @@ function runEnv(env, nonce, herdr) {
|
|
|
27185
27501
|
out[NONCE_ENV] = nonce;
|
|
27186
27502
|
return out;
|
|
27187
27503
|
}
|
|
27188
|
-
var newNonce = () =>
|
|
27504
|
+
var newNonce = () => randomBytes27(16).toString("hex");
|
|
27189
27505
|
function which(name2, path, platform, ext = ".COM;.EXE;.BAT;.CMD") {
|
|
27190
27506
|
const ends = platform === "win32" ? ["", ...ext.split(";").map((e) => e.toLowerCase())] : [""];
|
|
27191
27507
|
for (const dir of path.split(platform === "win32" ? ";" : delimiter).filter(Boolean)) {
|
|
27192
27508
|
for (const end of ends) {
|
|
27193
|
-
const file3 =
|
|
27509
|
+
const file3 = join70(dir, name2 + end);
|
|
27194
27510
|
try {
|
|
27195
27511
|
if (statSync17(file3).isFile()) return file3;
|
|
27196
27512
|
} catch {
|
|
@@ -27215,7 +27531,7 @@ function resolvePi(env, configured, platform = process.platform) {
|
|
|
27215
27531
|
const pi = which("pi", path, platform, env.PATHEXT);
|
|
27216
27532
|
if (!pi) throw new Error(`pi is not on the PATH the sb server has (${path.slice(0, 200)}); set towerRuns.pi in config.json to pi's dist/cli.js`);
|
|
27217
27533
|
if (platform === "win32" && /\.cmd$/i.test(pi)) {
|
|
27218
|
-
const target2 = shimTarget(pi,
|
|
27534
|
+
const target2 = shimTarget(pi, readFileSync47(pi, "utf8"));
|
|
27219
27535
|
if (!target2) throw new Error(`${pi} is not an npm shim the sb server can read; set towerRuns.pi in config.json to pi's dist/cli.js`);
|
|
27220
27536
|
return { node, cli: target2 };
|
|
27221
27537
|
}
|
|
@@ -27256,13 +27572,13 @@ function pruneStderr(dir, now) {
|
|
|
27256
27572
|
}
|
|
27257
27573
|
const rows = names2.flatMap((n) => {
|
|
27258
27574
|
try {
|
|
27259
|
-
return [{ n, at: statSync17(
|
|
27575
|
+
return [{ n, at: statSync17(join70(dir, n)).mtimeMs }];
|
|
27260
27576
|
} catch {
|
|
27261
27577
|
return [];
|
|
27262
27578
|
}
|
|
27263
27579
|
}).sort((a, b) => b.at - a.at);
|
|
27264
27580
|
rows.forEach((r, i) => {
|
|
27265
|
-
if (i >= STDERR_KEEP || now - r.at > STDERR_KEEP_MS) rmSync16(
|
|
27581
|
+
if (i >= STDERR_KEEP || now - r.at > STDERR_KEEP_MS) rmSync16(join70(dir, r.n), { force: true });
|
|
27266
27582
|
});
|
|
27267
27583
|
}
|
|
27268
27584
|
function startChild(o) {
|
|
@@ -27299,7 +27615,7 @@ function startChild(o) {
|
|
|
27299
27615
|
const piece = c.subarray(0, STDERR_CAP - written);
|
|
27300
27616
|
written += piece.length;
|
|
27301
27617
|
try {
|
|
27302
|
-
|
|
27618
|
+
appendFileSync7(o.stderr, piece);
|
|
27303
27619
|
} catch {
|
|
27304
27620
|
}
|
|
27305
27621
|
});
|
|
@@ -27337,7 +27653,7 @@ function startChild(o) {
|
|
|
27337
27653
|
}
|
|
27338
27654
|
};
|
|
27339
27655
|
}
|
|
27340
|
-
var stderrFile = (towerDir2, run2) =>
|
|
27656
|
+
var stderrFile = (towerDir2, run2) => join70(towerDir2, "runs", `${run2.slice(0, 8)}.stderr`);
|
|
27341
27657
|
|
|
27342
27658
|
// src/server/runring.ts
|
|
27343
27659
|
var RING_MAX = 300;
|
|
@@ -27686,7 +28002,7 @@ function createRevoker(d) {
|
|
|
27686
28002
|
}
|
|
27687
28003
|
|
|
27688
28004
|
// src/server/deadwatch.ts
|
|
27689
|
-
import { join as
|
|
28005
|
+
import { join as join71 } from "node:path";
|
|
27690
28006
|
function createDeadWatch(d) {
|
|
27691
28007
|
const seen = /* @__PURE__ */ new Map();
|
|
27692
28008
|
const last = /* @__PURE__ */ new Map();
|
|
@@ -27736,11 +28052,11 @@ function createDeadWatch(d) {
|
|
|
27736
28052
|
busy = false;
|
|
27737
28053
|
}
|
|
27738
28054
|
}
|
|
27739
|
-
return { sweep: sweep3, rows: (workspace) => last.get(workspace) ?? [], ledgerDir:
|
|
28055
|
+
return { sweep: sweep3, rows: (workspace) => last.get(workspace) ?? [], ledgerDir: join71(d.stateDir, "revive") };
|
|
27740
28056
|
}
|
|
27741
28057
|
|
|
27742
28058
|
// src/server/runs.ts
|
|
27743
|
-
import { randomBytes as
|
|
28059
|
+
import { randomBytes as randomBytes28 } from "node:crypto";
|
|
27744
28060
|
import { lstatSync as lstatSync12, realpathSync as realpathSync12 } from "node:fs";
|
|
27745
28061
|
import { basename as basename16, resolve as resolve10, sep as sep9 } from "node:path";
|
|
27746
28062
|
|
|
@@ -27894,7 +28210,7 @@ function createRuns2(o) {
|
|
|
27894
28210
|
const start = o.startPi ?? startPi, settings = o.settings ?? ((dirs) => assertSettingsSafe(dirs)), append = o.append ?? appendEvent;
|
|
27895
28211
|
const startedLater2 = o.startedLater ?? (o.startOf ? (pid) => Promise.resolve(startOf2(pid)) : startedLater);
|
|
27896
28212
|
const procs = o.procs ?? readProcs();
|
|
27897
|
-
const newId = o.newId ?? (() =>
|
|
28213
|
+
const newId = o.newId ?? (() => randomBytes28(8).toString("hex"));
|
|
27898
28214
|
const services = /* @__PURE__ */ new Map(), byToken = /* @__PURE__ */ new Map(), byRun = /* @__PURE__ */ new Map(), blocked = /* @__PURE__ */ new Set();
|
|
27899
28215
|
const confirms = /* @__PURE__ */ new Map(), confirmCalls = /* @__PURE__ */ new Map();
|
|
27900
28216
|
let slots = 0, pendingTakeovers = 0, herdrLostAt, watcher, stopped = false;
|
|
@@ -28636,7 +28952,7 @@ function createRuns2(o) {
|
|
|
28636
28952
|
a.digestKeys = built.digestKeys;
|
|
28637
28953
|
a.expired = built.expired?.length ? built.expired : void 0;
|
|
28638
28954
|
a.briefV = ally ? void 0 : svc.ref.briefVersion?.(a.split);
|
|
28639
|
-
a.token =
|
|
28955
|
+
a.token = randomBytes28(24).toString("hex");
|
|
28640
28956
|
a.lastPoll = now();
|
|
28641
28957
|
a.recovering = void 0;
|
|
28642
28958
|
if (a.left) {
|
|
@@ -28791,6 +29107,8 @@ Its .pi settings, extensions, skills, and prompts load only if you trust it. Yes
|
|
|
28791
29107
|
if (outstanding) return { ok: false, error: `${outstanding} event${outstanding > 1 ? "s" : ""} still for you: they come to you at your next idle moment; handle them, then call tower_done again` };
|
|
28792
29108
|
const waits = a.rec.kind === "local" ? await o.unforwarded?.(a.rec.id, a.rec.workspace) : void 0;
|
|
28793
29109
|
if (waits) return { ok: false, error: `Event ${waits.id} (call_tower from ${waits.from.name ?? waits.from.id}) waits on device ${waits.short}: forward it with tower_send {device: "${waits.short}", message, waitsOn: {event: "${waits.id}"}}, or answer its raiser with tower_reply, then call tower_done again` };
|
|
29110
|
+
const slip = a.rec.kind === "local" ? await o.unforwardedSlip?.(a.rec.id, a.rec.workspace) : void 0;
|
|
29111
|
+
if (slip) return { ok: false, error: slip };
|
|
28794
29112
|
addNote(slot, a.rec.workspace, { kind: a.rec.kind, ...a.rec.device ? { device: a.rec.device } : {}, run: a.rec.id, at: iso5(now()), note });
|
|
28795
29113
|
if (a.rec.kind === "local") await a.svc.ref.clearDigest(a.digestKeys).catch(() => {
|
|
28796
29114
|
});
|
|
@@ -29310,7 +29628,7 @@ Its .pi settings, extensions, skills, and prompts load only if you trust it. Yes
|
|
|
29310
29628
|
const svc = services.get(workspace);
|
|
29311
29629
|
if (!svc) throw new Error(`The sb server stands in for no tower of workspace ${workspace}`);
|
|
29312
29630
|
const rec = { id: newId(), workspace, kind: who3.kind, ...who3.device ? { device: who3.device } : {}, ...who3.level ? { level: who3.level } : {}, ...who3.team ? { team: who3.team } : {}, pane: svc.ref.record().pane, agent: "minted", startedAt: iso5(now()), events: [] };
|
|
29313
|
-
const a = { rec, svc, commands: [], lastPoll: now(), started: now(), digestKeys: [], offered: /* @__PURE__ */ new Map(), token:
|
|
29631
|
+
const a = { rec, svc, commands: [], lastPoll: now(), started: now(), digestKeys: [], offered: /* @__PURE__ */ new Map(), token: randomBytes28(24).toString("hex") };
|
|
29314
29632
|
byToken.set(a.token, a);
|
|
29315
29633
|
return a.token;
|
|
29316
29634
|
},
|
|
@@ -29411,83 +29729,6 @@ function allyReceipts(d) {
|
|
|
29411
29729
|
};
|
|
29412
29730
|
}
|
|
29413
29731
|
|
|
29414
|
-
// src/server/towerseen.ts
|
|
29415
|
-
import { createHash as createHash22 } from "node:crypto";
|
|
29416
|
-
import { appendFileSync as appendFileSync7, readFileSync as readFileSync47 } from "node:fs";
|
|
29417
|
-
import { join as join70 } from "node:path";
|
|
29418
|
-
var SEEN_KEEP_MS = 48 * 36e5;
|
|
29419
|
-
var SEEN_MAX = 5e3;
|
|
29420
|
-
var SLACK = 500;
|
|
29421
|
-
var FILE = "seen.jsonl";
|
|
29422
|
-
var baseId = (messageId) => messageId.replace(/~r\d+$/, "");
|
|
29423
|
-
var hashOf2 = (text14) => createHash22("sha256").update(text14).digest("hex");
|
|
29424
|
-
var key = (from, base) => `${from}
|
|
29425
|
-
${base}`;
|
|
29426
|
-
var parse6 = (line4) => {
|
|
29427
|
-
try {
|
|
29428
|
-
const v = JSON.parse(line4);
|
|
29429
|
-
return typeof v.from === "string" && typeof v.base === "string" && typeof v.hash === "string" && typeof v.at === "number" ? { from: v.from, base: v.base, hash: v.hash, at: v.at } : void 0;
|
|
29430
|
-
} catch {
|
|
29431
|
-
return void 0;
|
|
29432
|
-
}
|
|
29433
|
-
};
|
|
29434
|
-
function openSeen(slot, workspace, now) {
|
|
29435
|
-
const file3 = join70(towerDir(slot, workspace), FILE);
|
|
29436
|
-
const rows = /* @__PURE__ */ new Map();
|
|
29437
|
-
let text14 = "", lines = 0;
|
|
29438
|
-
try {
|
|
29439
|
-
text14 = readFileSync47(file3, "utf8");
|
|
29440
|
-
} catch {
|
|
29441
|
-
}
|
|
29442
|
-
for (const line4 of text14.split("\n")) {
|
|
29443
|
-
const row2 = line4 ? parse6(line4) : void 0;
|
|
29444
|
-
if (row2) rows.set(key(row2.from, row2.base), row2), lines++;
|
|
29445
|
-
}
|
|
29446
|
-
let added = false;
|
|
29447
|
-
for (const event of [...readQueue(slot, workspace), ...readQueue(slot, workspace, true)]) {
|
|
29448
|
-
if (event.kind !== "intercom" || !event.messageId || !event.from) continue;
|
|
29449
|
-
const base = baseId(event.messageId), k = key(event.from.id, base);
|
|
29450
|
-
if (rows.has(k)) continue;
|
|
29451
|
-
rows.set(k, { from: event.from.id, base, hash: hashOf2(event.text), at: Date.parse(event.at) || now() });
|
|
29452
|
-
added = true;
|
|
29453
|
-
}
|
|
29454
|
-
const trim = () => {
|
|
29455
|
-
let dropped = false;
|
|
29456
|
-
for (const [k, row2] of rows) if (now() - row2.at > SEEN_KEEP_MS) rows.delete(k), dropped = true;
|
|
29457
|
-
while (rows.size > SEEN_MAX) rows.delete(rows.keys().next().value), dropped = true;
|
|
29458
|
-
return dropped;
|
|
29459
|
-
};
|
|
29460
|
-
const rewrite2 = () => {
|
|
29461
|
-
ensureDir(towerDir(slot, workspace));
|
|
29462
|
-
writeDurableText(file3, [...rows.values()].map((r) => JSON.stringify(r)).join("\n") + (rows.size ? "\n" : ""));
|
|
29463
|
-
lines = rows.size;
|
|
29464
|
-
};
|
|
29465
|
-
if (trim() || added) {
|
|
29466
|
-
try {
|
|
29467
|
-
rewrite2();
|
|
29468
|
-
} catch {
|
|
29469
|
-
}
|
|
29470
|
-
}
|
|
29471
|
-
return {
|
|
29472
|
-
check(from, messageId, body2) {
|
|
29473
|
-
const found = rows.get(key(from, baseId(messageId)));
|
|
29474
|
-
return !found ? "new" : found.hash === hashOf2(body2) ? "seen" : "conflict";
|
|
29475
|
-
},
|
|
29476
|
-
add(from, messageId, body2, at = now()) {
|
|
29477
|
-
const row2 = { from, base: baseId(messageId), hash: hashOf2(body2), at };
|
|
29478
|
-
rows.delete(key(from, row2.base));
|
|
29479
|
-
rows.set(key(from, row2.base), row2);
|
|
29480
|
-
trim();
|
|
29481
|
-
if (lines >= SEEN_MAX + SLACK) return rewrite2();
|
|
29482
|
-
lines++;
|
|
29483
|
-
ensureDir(towerDir(slot, workspace));
|
|
29484
|
-
appendFileSync7(file3, `${JSON.stringify(row2)}
|
|
29485
|
-
`, { mode: 384 });
|
|
29486
|
-
},
|
|
29487
|
-
size: () => rows.size
|
|
29488
|
-
};
|
|
29489
|
-
}
|
|
29490
|
-
|
|
29491
29732
|
// src/server/trainnote.ts
|
|
29492
29733
|
function noteTrains(open9, d) {
|
|
29493
29734
|
return async (input) => {
|
|
@@ -29513,158 +29754,6 @@ function noteTrains(open9, d) {
|
|
|
29513
29754
|
};
|
|
29514
29755
|
}
|
|
29515
29756
|
|
|
29516
|
-
// src/server/towergate.ts
|
|
29517
|
-
import { randomBytes as randomBytes28 } from "node:crypto";
|
|
29518
|
-
import { join as join71 } from "node:path";
|
|
29519
|
-
|
|
29520
|
-
// src/carslip.ts
|
|
29521
|
-
var SLIP = /\b(?:car|app):[ \t]*[A-Za-z0-9._-]+[ \t]*\|[ \t]*(?:tickets|car):/i;
|
|
29522
|
-
var carriesSlip = (text14) => SLIP.test(text14) || slipLines(text14).split(/\r?\n/).some(startsSlip);
|
|
29523
|
-
|
|
29524
|
-
// src/server/towergate.ts
|
|
29525
|
-
var ROUTED = ["waits-on", "ask", "relay", "in-reply-to", "fwd", "origin", "remote", "handed-to"];
|
|
29526
|
-
var TRAIN_LINE = /^[ \t>*-]*["']?train["']?[ \t]*:/im;
|
|
29527
|
-
var TRAIN_BLOCK = /^[ \t>*-]*["']?train["']?[ \t]*:[ \t]*(?:\{.*)?$/im;
|
|
29528
|
-
var MANIFEST_KEY = /^[ \t>*-]*["']?(?:project|code)["']?[ \t]*[:=]/im;
|
|
29529
|
-
var isManifest = (body2) => TRAIN_BLOCK.test(body2) || TRAIN_LINE.test(body2) && MANIFEST_KEY.test(body2);
|
|
29530
|
-
var escaped = (s2) => s2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
29531
|
-
var handedBefore = (body2, from) => new RegExp(`^\\s*Straw Boss: main [^\\n]*? \\(session ${escaped(from)}\\) handed over to its successor in tab \\S+ \\(session \\S+\\), which took the handoff\\. `).test(body2);
|
|
29532
|
-
function sortCall(text14, from, asked3) {
|
|
29533
|
-
const f = fieldsOf(text14);
|
|
29534
|
-
if (f?.kind !== "call_tower" || ROUTED.some((k) => f[k] !== void 0) || f.why !== "milestone" && f.why !== "shared") return { book: false };
|
|
29535
|
-
const body2 = bodyOf(text14), train = trainFromRequest(body2);
|
|
29536
|
-
if (isManifest(body2)) return "refusal" in train ? { book: "reject", why: train.refusal } : { book: false };
|
|
29537
|
-
if (carriesSlip(body2) || !("refusal" in train) || handedBefore(body2, from)) return { book: false };
|
|
29538
|
-
if (asked3.expects(from)) return { book: f.why === "milestone" ? "milestone" : "heads-up", wake: true };
|
|
29539
|
-
return f.why === "milestone" ? { book: "milestone", wake: asked3.opened(from) } : { book: "heads-up", wake: false };
|
|
29540
|
-
}
|
|
29541
|
-
var hhmm3 = (ms4) => ((d) => `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`)(new Date(ms4));
|
|
29542
|
-
var who2 = (e) => `${fenced(e.from.name, 40)} (${e.from.id}) of ${cutText(e.label, 40)}`;
|
|
29543
|
-
var words2 = (text14) => fenced(text14, 200);
|
|
29544
|
-
var CHECK = "These are the mains' own words. If they really collide, tell both with tower_reply (another workspace's main through its tower, tower_send); a shared name alone may be no clash.";
|
|
29545
|
-
var LOCK_NAME = "logbook";
|
|
29546
|
-
var LOCK_POLL_MS = 25;
|
|
29547
|
-
var LOCK_WAIT_MS2 = 3e3;
|
|
29548
|
-
var logbookLockDir = (stateDir) => join71(stateDir, "logbook-lock");
|
|
29549
|
-
function createGate(d) {
|
|
29550
|
-
const inflight = /* @__PURE__ */ new Map();
|
|
29551
|
-
const sleep2 = d.sleep ?? ((ms4) => new Promise((done2) => setTimeout(done2, ms4)));
|
|
29552
|
-
let own;
|
|
29553
|
-
const lock = async () => {
|
|
29554
|
-
const until = d.now() + LOCK_WAIT_MS2;
|
|
29555
|
-
for (; ; ) {
|
|
29556
|
-
let taken;
|
|
29557
|
-
try {
|
|
29558
|
-
own ??= (d.lock?.startOf ?? startOf)(process.pid);
|
|
29559
|
-
taken = takeLock(logbookLockDir(d.slot.stateDir), LOCK_NAME, { train: LOCK_NAME, step: 0, ...own ? { started: own } : {} }, d.lock);
|
|
29560
|
-
} catch (cause) {
|
|
29561
|
-
return { busy: `the logbook lock could not be taken: ${cutText(cause.message, 80)}` };
|
|
29562
|
-
}
|
|
29563
|
-
if (taken.ok) return taken;
|
|
29564
|
-
if (d.now() >= until) return { busy: `the logbook lock stayed ${taken.why}${taken.holder ? ` by pid ${taken.holder.pid}` : ""} for ${LOCK_WAIT_MS2 / 1e3} s` };
|
|
29565
|
-
await sleep2(LOCK_POLL_MS);
|
|
29566
|
-
}
|
|
29567
|
-
};
|
|
29568
|
-
const reply3 = async (i, from, fields, text14, wake = fields.reply === "expected") => {
|
|
29569
|
-
const role = ROLE_WORDS.includes(fields.role ?? "") ? fields.role : "session";
|
|
29570
|
-
const line4 = stamp({ from: { name: i.record.name, id: i.record.id, role: "tower", workspace: i.record.label }, kind: "tower_reply", scope: "session", to: [{ name: from.name ?? from.id, id: from.id, role, ...fields.workspace ? { workspace: fields.workspace } : {} }], reply: false }, text14);
|
|
29571
|
-
const sent = await i.client?.send(from.id, { text: line4, messageId: `sb-gate-${randomBytes28(8).toString("hex")}`, ...wake ? {} : { noWake: true } });
|
|
29572
|
-
if (!sent?.delivered) d.log("tower-gate-reply", { workspace: i.record.workspace, to: from.id, why: sent?.reason ?? "no connection" });
|
|
29573
|
-
};
|
|
29574
|
-
const headsUpClash = (e) => {
|
|
29575
|
-
for (const o of openHeadsUps(allEntries(d.slot.stateDir, d.now()), d.now())) {
|
|
29576
|
-
const on2 = o.from.id === e.from.id ? [] : shared(e.resources ?? [], o.resources ?? []);
|
|
29577
|
-
if (on2.length) return { short: `the heads-up of ${fenced(o.from.name, 40)} (${o.from.id.slice(0, 8)}) on ${fenced(on2.slice(0, 3).join(", "), 60)}`, notice: `Heads-up clash, seen by sb: ${who2(e)}: ${words2(e.text)} overlaps the heads-up of ${who2(o)}, open until ${hhmm3(o.until ?? o.at)}: ${words2(o.text)}, on ${fenced(on2.slice(0, 5).join(", "), 120)}. ${CHECK}` };
|
|
29578
|
-
}
|
|
29579
|
-
return void 0;
|
|
29580
|
-
};
|
|
29581
|
-
const boardClash = (net, e) => {
|
|
29582
|
-
const ws = net.sessions.find((s2) => s2.id === e.from.id)?.herdrLocation?.workspace?.id ?? e.workspace;
|
|
29583
|
-
const mains = new Map(net.sessions.filter((s2) => s2.id !== e.from.id && s2.herdrLocation?.workspace?.id === ws && /* @__PURE__ */ ((r) => r === "main" || r === "train")(net.ps.find((p) => p.pane_id === s2.herdrLocation?.paneId)?.tokens?.sb_role)).map((s2) => [s2.id, s2]));
|
|
29584
|
-
for (const entry of readEntries(join71(d.slot.stateDir, "board"))) {
|
|
29585
|
-
const main = mains.get(entry.session), text14 = [entry.now, ...entry.items.filter((x) => !x.done).map((x) => x.t)].join(" \xB7 ");
|
|
29586
|
-
const on2 = main ? shared(e.resources ?? [], resourcesOf(text14)) : [];
|
|
29587
|
-
if (on2.length) return { short: `the board of ${fenced(main.name ?? main.id, 40)} (${main.id.slice(0, 8)}) on ${fenced(on2.slice(0, 3).join(", "), 60)}`, notice: `Heads-up clash, seen by sb: ${who2(e)}: ${words2(e.text)} overlaps the board of ${fenced(main.name ?? main.id, 40)} (${main.id}), a main of the sender's workspace: ${words2(text14)}, on ${fenced(on2.slice(0, 5).join(", "), 120)}. ${CHECK}` };
|
|
29588
|
-
}
|
|
29589
|
-
return void 0;
|
|
29590
|
-
};
|
|
29591
|
-
const netOf = (i) => (i.read ? i.read() : Promise.reject(new Error("no net reader"))).catch((cause) => cause);
|
|
29592
|
-
const classify = async (i, from, sort, e) => {
|
|
29593
|
-
if (sort.book === "milestone") {
|
|
29594
|
-
if (sort.wake) return { wake: true, why: "it answers the tower's request" };
|
|
29595
|
-
const net2 = await netOf(i);
|
|
29596
|
-
if (net2 instanceof Error) return { wake: true, why: `the net could not be read: ${cutText(net2.message, 80)}` };
|
|
29597
|
-
return net2.ps.find((p) => p.pane_id === net2.sessions.find((s2) => s2.id === from.id)?.herdrLocation?.paneId)?.tokens?.sb_opened_by ? { wake: true, why: "a main a tower opened" } : { wake: false };
|
|
29598
|
-
}
|
|
29599
|
-
if (sort.wake) return { wake: true, why: "a session this tower asked" };
|
|
29600
|
-
if (!e.resources?.length) return { wake: false };
|
|
29601
|
-
const net = await netOf(i);
|
|
29602
|
-
if (net instanceof Error) return { wake: true, why: `the boards could not be read: ${cutText(net.message, 80)}` };
|
|
29603
|
-
const board = boardClash(net, e);
|
|
29604
|
-
return board ? { wake: true, why: "board", clash: board } : { wake: false };
|
|
29605
|
-
};
|
|
29606
|
-
const answer = (i, from, fields, e) => e.kind === "milestone" ? fields.reply === "expected" ? reply3(i, from, fields, "sb: recorded your milestone in the tower's logbook; a milestone wakes no tower run, so no answer comes. If you need one, call_tower again with why blocked.") : Promise.resolve() : reply3(i, from, fields, e.resources?.length ? `sb: recorded your heads-up for the tower (open until ${hhmm3(e.until)}); no clash seen with the open heads-ups or your workspace's boards, so no tower run woke. Go ahead.` : `sb: recorded your heads-up for the tower (open until ${hhmm3(e.until)}); it names nothing sb can compare (a port, branch, database, host, or deploy target), so no clash can be seen and no tower run woke. Go ahead.`);
|
|
29607
|
-
const settle2 = async (i, from, message, sort, hash3) => {
|
|
29608
|
-
const ws = i.record.workspace, text14 = message.content.text, now = d.now(), fields = fieldsOf(text14), body2 = bodyOf(text14);
|
|
29609
|
-
const fail2 = (cause) => d.log("tower-gate-error", { workspace: ws, from: from.id, error: cutText(cause.message, 200) });
|
|
29610
|
-
if (sort.book === "reject") {
|
|
29611
|
-
i.seen();
|
|
29612
|
-
d.log("tower-gate-refused", { workspace: ws, from: from.id, why: cutText(sort.why, 200) });
|
|
29613
|
-
void reply3(i, from, fields, `sb: your message reads as a train manifest, and it is refused: ${cutText(sort.why, 200)}. Nothing was recorded or opened: fix it and send it again with call_tower (why shared).`, true).catch(fail2);
|
|
29614
|
-
return true;
|
|
29615
|
-
}
|
|
29616
|
-
const base = { kind: sort.book, workspace: ws, label: i.record.label, at: now, from: { id: from.id, name: cutText(from.name ?? from.id, 80) }, text: cutText(body2), msg: baseId(message.id), hash: hash3, ...fields.reply === "expected" ? { reply: true } : {} };
|
|
29617
|
-
const draft = sort.book === "heads-up" ? { ...base, resources: resourcesOf(body2), until: untilOf2(body2, now) } : base;
|
|
29618
|
-
const read4 = await classify(i, from, sort, draft), held2 = sort.book === "heads-up" ? await lock() : void 0;
|
|
29619
|
-
let verdict, e;
|
|
29620
|
-
try {
|
|
29621
|
-
const hit = sort.book === "heads-up" ? headsUpClash(draft) : void 0;
|
|
29622
|
-
verdict = hit ? { wake: true, why: "heads-up", clash: hit } : !read4.wake && held2 && "busy" in held2 ? { wake: true, why: held2.busy } : read4;
|
|
29623
|
-
e = addEntry2(d.slot.dir, { ...draft, ...verdict.wake ? { woke: true, ...verdict.clash ? { clash: verdict.clash.short } : {} } : {} }, now);
|
|
29624
|
-
} finally {
|
|
29625
|
-
if (held2 && "release" in held2) held2.release();
|
|
29626
|
-
}
|
|
29627
|
-
if (e.hash !== void 0 && e.hash !== hash3) {
|
|
29628
|
-
d.log("tower-dropped", { workspace: ws, from: from.id, why: "the same message id with other content" });
|
|
29629
|
-
return false;
|
|
29630
|
-
}
|
|
29631
|
-
const why2 = verdict.wake ? verdict.why : "recorded so before";
|
|
29632
|
-
d.log("tower-recorded", { workspace: ws, kind: e.kind, from: from.id, seq: String(e.seq), wake: e.woke ? why2 : "no" });
|
|
29633
|
-
if (e.woke) {
|
|
29634
|
-
if (verdict.wake && verdict.clash) d.notice(ws, verdict.clash.notice, `clash:${ws}:${e.seq}`);
|
|
29635
|
-
d.log("tower-gate-wake", { workspace: ws, kind: e.kind, from: from.id, seq: String(e.seq), why: why2 });
|
|
29636
|
-
i.queue();
|
|
29637
|
-
return true;
|
|
29638
|
-
}
|
|
29639
|
-
i.seen();
|
|
29640
|
-
d.log("tower-gate-quiet", { workspace: ws, kind: e.kind, from: from.id, seq: String(e.seq) });
|
|
29641
|
-
void answer(i, from, fields, e).catch(fail2);
|
|
29642
|
-
return true;
|
|
29643
|
-
};
|
|
29644
|
-
return {
|
|
29645
|
-
/**
|
|
29646
|
-
* False when the intake queues the message as before; else the gate's work on it, which ends once the call is recorded and queued or seen, true when the intake receipts it then: a retry of a call in flight
|
|
29647
|
-
* (its base id) shares that call's end when its text is the same, and is dropped, unreceipted, when it is not.
|
|
29648
|
-
*/
|
|
29649
|
-
take(i, from, message) {
|
|
29650
|
-
const ws = i.record.workspace, now = d.now();
|
|
29651
|
-
const hash3 = hashOf2(message.content.text), key2 = `${i.record.id}
|
|
29652
|
-
${from.id}
|
|
29653
|
-
${baseId(message.id)}`, running = inflight.get(key2);
|
|
29654
|
-
if (running?.hash === hash3) return running.job;
|
|
29655
|
-
if (running) {
|
|
29656
|
-
d.log("tower-dropped", { workspace: ws, from: from.id, why: "the same message id with other content" });
|
|
29657
|
-
return Promise.resolve(false);
|
|
29658
|
-
}
|
|
29659
|
-
const sort = sortCall(message.content.text, from.id, { opened: (id2) => readLedger(d.slot, ws, now).some((r) => r.outcome === "opened" && r.opened?.main === id2), expects: (id2) => readExpects(d.slot, ws, now).some((x) => x.to === id2) });
|
|
29660
|
-
if (!sort.book) return false;
|
|
29661
|
-
const job = settle2(i, from, message, sort, hash3).finally(() => inflight.delete(key2));
|
|
29662
|
-
inflight.set(key2, { hash: hash3, job });
|
|
29663
|
-
return job;
|
|
29664
|
-
}
|
|
29665
|
-
};
|
|
29666
|
-
}
|
|
29667
|
-
|
|
29668
29757
|
// src/server/towers.ts
|
|
29669
29758
|
var UNKNOWN = "(unknown)";
|
|
29670
29759
|
var RUN_SEND_CAP_MS = 2e4;
|
|
@@ -29881,6 +29970,7 @@ function createTowers(o) {
|
|
|
29881
29970
|
headModel: () => headModel(slot.stateDir),
|
|
29882
29971
|
...allyPort2 ? { ally: allyPort2 } : {},
|
|
29883
29972
|
unforwarded: async (run3, ws) => unforwardedWait(slot, ws, run3, await o.sessions().then((x) => new Set(x.map((s2) => s2.id)), () => void 0), (event, facts) => log.line(event, facts)),
|
|
29973
|
+
unforwardedSlip: async (run3, ws) => unforwardedSlip(slot, ws, run3, { live: await o.sessions().then((x) => new Set(x.map((s2) => s2.id)), () => void 0), startedAt: o.startedAt, log: (event, facts) => log.line(event, facts) }),
|
|
29884
29974
|
kids: createKids({ port: { on: () => readTowerRuns(slot.stateDir).headless, pi: () => resolvePi(o.env, readTowerRuns(slot.stateDir).pi), env: o.env, herdr: slot.herdr, dir: (ws) => towerDir(slot, ws), ...o.kidsPort }, log, now }),
|
|
29885
29975
|
allyEnded: (end) => allyReceipts({ slot, now, unattended: () => o.unattended?.() === true, answered: (run3, ask) => answered.has(run3, ask), label: () => o.ally?.selfLabel?.() ?? "the box", log: (event, facts) => log.line(event, facts), send: (ws, device, text14, inReplyTo) => o.link ? o.link({ op: "send", device, text: text14, reply: false, inReplyTo }, services.get(ws)?.record.id ?? "", true) : Promise.reject(new Error("no link holder")) })(end),
|
|
29886
29976
|
...o.runs
|