bazilion 0.27.0 → 0.50.0
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/cli.js +405 -243
- package/dist/cli.js.map +1 -1
- package/dist/daemon.js +1077 -623
- package/dist/daemon.js.map +1 -1
- package/dist/web/client/assets/ConfigPage-_FY--9PB.js +1 -0
- package/dist/web/client/assets/ConfirmDialog-BblXqMVb.js +1 -0
- package/dist/web/client/assets/ConnectionsView-BZHJysCa.js +1 -0
- package/dist/web/client/assets/FieldRow-k05wfDy9.js +1 -0
- package/dist/web/client/assets/SectionTabs-DlfXtepS.js +1 -0
- package/dist/web/client/assets/{SkillFindings-8LX6bYf_.js → SkillFindings-CHf5ZGY0.js} +1 -1
- package/dist/web/client/assets/SpawnDialog-C-Ujb4bC.js +1 -0
- package/dist/web/client/assets/TeamForm-D6EAAF7m.js +1 -0
- package/dist/web/client/assets/TeamThread-DpUOwMoi.js +1 -0
- package/dist/web/client/assets/UnsavedChangesGuard-DTUP7hwu.js +1 -0
- package/dist/web/client/assets/_id-C94dgBDe.js +1 -0
- package/dist/web/client/assets/_id-CxmEfoEp.js +1 -0
- package/dist/web/client/assets/agents-C-bJ5R_0.js +1 -0
- package/dist/web/client/assets/agents-odqBNx-A.js +1 -0
- package/dist/web/client/assets/api-CPzQ_z9m.js +1 -0
- package/dist/web/client/assets/arrow-right-Dyta3p06.js +1 -0
- package/dist/web/client/assets/attention-D0e7o7fh.js +1 -0
- package/dist/web/client/assets/chevron-right-B2YEg9rw.js +1 -0
- package/dist/web/client/assets/config-B7Y5MtpM.js +3 -0
- package/dist/web/client/assets/createLucideIcon-Cgab8gqu.js +1 -0
- package/dist/web/client/assets/index-CNVw44IE.js +54 -0
- package/dist/web/client/assets/link-ClwtaO_E.js +1 -0
- package/dist/web/client/assets/login-Br1F4rQx.js +1 -0
- package/dist/web/client/assets/mcp-B8bIAY6k.js +1 -0
- package/dist/web/client/assets/routes-BZdlkRdC.js +76 -0
- package/dist/web/client/assets/save-ZqeB_I-c.js +1 -0
- package/dist/web/client/assets/{services-B2f7e5jV.js → services-CPJxDrVG.js} +1 -1
- package/dist/web/client/assets/skills-DE_kQQGj.js +1 -0
- package/dist/web/client/assets/style-BWShXY3e.js +7 -0
- package/dist/web/client/assets/styles-Tney8jZq.css +2 -0
- package/dist/web/client/assets/teams-AcuSLc3I.js +1 -0
- package/dist/web/client/assets/teams-tRamPg7O.js +1 -0
- package/dist/web/client/assets/telegram-Ku69-GAv.js +1 -0
- package/dist/web/client/assets/tokens-DuLNZMgi.js +1 -0
- package/dist/web/client/assets/welcome-CrQk6n6I.js +1 -0
- package/dist/web/server/assets/{ConfigPage-CGld_wCK.js → ConfigPage-DSLM5CLw.js} +2 -2
- package/dist/web/server/assets/{ConfirmDialog-LdVlEanK.js → ConfirmDialog-CvLZgbfY.js} +1 -1
- package/dist/web/server/assets/ConnectionsView-DVLNH81Y.js +708 -0
- package/dist/web/server/assets/{FieldRow-Dah2KKqo.js → FieldRow-DQBzMtcR.js} +4 -4
- package/dist/web/server/assets/{Page-CMSYKXWJ.js → Page-KIL1CsME.js} +1 -1
- package/dist/web/server/assets/Rail-D8LhjS38.js +756 -0
- package/dist/web/server/assets/{SectionTabs-CqFg9Vwx.js → SectionTabs-CNcvxbR8.js} +1 -16
- package/dist/web/server/assets/{SkillFindings-Bd6e81Wu.js → SkillFindings-DX8lCMG7.js} +1 -1
- package/dist/web/server/assets/{SpawnDialog-BGNaMfFb.js → SpawnDialog-Brmkl_ll.js} +24 -6
- package/dist/web/server/assets/{TeamForm-C93tpn9r.js → TeamForm-CvQAs2FA.js} +1 -1
- package/dist/web/server/assets/TeamThread-BNJi6gPM.js +205 -0
- package/dist/web/server/assets/{UnsavedChangesGuard-Dm4a27_5.js → UnsavedChangesGuard-B3Lpl08z.js} +8 -4
- package/dist/web/server/assets/{TeamPolicyEditor-BHS3J0R9.js → _id-BH1631a8.js} +114 -263
- package/dist/web/server/assets/{_id-sW6zXrTP.js → _id-CA3QO7J5.js} +1 -1
- package/dist/web/server/assets/{_id-lOVnT5sS.js → _id-CO1PgvyG.js} +5 -5
- package/dist/web/server/assets/{_id-B0x1ffz3.js → _id-DIXUiIaB.js} +1 -1
- package/dist/web/server/assets/{_id-ByiXeIPS.js → _id-E2N4gZ4O.js} +2 -2
- package/dist/web/server/assets/{_id-Bdf_Rg62.js → _id-TVruGcOd.js} +1 -1
- package/dist/web/server/assets/_tanstack-start-manifest_v-BVfrV7LQ.js +191 -0
- package/dist/web/server/assets/{agents-BNPkidbH.js → agents-BnWgFo6o.js} +1 -1
- package/dist/web/server/assets/{agents-BK8OmB8g.js → agents-C63VycUw.js} +2 -2
- package/dist/web/server/assets/{agents-D4tqK1kH.js → agents-CalSKogx.js} +14 -15
- package/dist/web/server/assets/{agents-Cn9GkXFX.js → agents-CdZvooeQ.js} +1 -1
- package/dist/web/server/assets/{agents-lOqc6VGd.js → agents-DPZVni4Q.js} +1 -1
- package/dist/web/server/assets/{agents-DycxHDt8.js → agents-DrkEwIpR.js} +8 -8
- package/dist/web/server/assets/{attention-DULVjdmF.js → attention-BbE4yc-V.js} +1 -1
- package/dist/web/server/assets/{attention-YWnLKA2E.js → attention-Cr7puThv.js} +1 -1
- package/dist/web/server/assets/{attention-BIm455bC.js → attention-DIyX3VMB.js} +6 -6
- package/dist/web/server/assets/{auth-DiN92ydD.js → auth-dJnrFW6y.js} +1 -1
- package/dist/web/server/assets/{config-C1VB28se.js → config-3tPtOmPE.js} +1 -1
- package/dist/web/server/assets/{config-BNEgu7WG.js → config-DJGZiPBJ.js} +13 -13
- package/dist/web/server/assets/{config-TdVqnqNL.js → config-rUqhMjIs.js} +1 -1
- package/dist/web/server/assets/{daemon-client-DL2ik2Em.js → daemon-client-B_ZRIIrT.js} +2 -1
- package/dist/web/server/assets/{mcp-BwmpNQPN.js → mcp-C97uAZe1.js} +1 -1
- package/dist/web/server/assets/{mcp-B09_O05r.js → mcp-Cf7KzOJ9.js} +9 -9
- package/dist/web/server/assets/{mcp-CqdTfXcn.js → mcp-DE14q5c0.js} +1 -1
- package/dist/web/server/assets/{router-BI9gmY3S.js → router-w2yPgmC1.js} +412 -259
- package/dist/web/server/assets/routes-1FEodTRm.js +16 -0
- package/dist/web/server/assets/routes-B6AO0LjK.js +57 -0
- package/dist/web/server/assets/routes-D1NHwz6f.js +7644 -0
- package/dist/web/server/assets/{services-tCfB1B83.js → services-BjroGXgC.js} +4 -4
- package/dist/web/server/assets/{services-Q9HYQXXB.js → services-Cdk40QHq.js} +1 -1
- package/dist/web/server/assets/{services-BLvAvb8g.js → services-DsHRLL8q.js} +1 -1
- package/dist/web/server/assets/{skills-BZg_txbf.js → skills-CA17GjuZ.js} +1 -1
- package/dist/web/server/assets/{skills-C7fqRPna.js → skills-DC1OTc8n.js} +11 -11
- package/dist/web/server/assets/{skills-C_g8IKag.js → skills-h5aHa7Q8.js} +1 -1
- package/dist/web/server/assets/style-GYDODk2F.js +178 -0
- package/dist/web/server/assets/{teams-D4CaU76n.js → teams-Bm63mbTt.js} +1 -1
- package/dist/web/server/assets/{teams-DX2HmKqi.js → teams-BxnvFTyn.js} +1 -1
- package/dist/web/server/assets/{teams-BS-oweRl.js → teams-Cg-QQWpH.js} +23 -15
- package/dist/web/server/assets/{teams-BHkhnt6b.js → teams-D6Tx-Jyn.js} +1 -1
- package/dist/web/server/assets/{teams-BSflKBP8.js → teams-OzHTyVi9.js} +6 -6
- package/dist/web/server/assets/{teams-CNyB5nM9.js → teams-YrmyutM4.js} +1 -1
- package/dist/web/server/assets/{telegram-CrJiygCX.js → telegram-BJ4l_TA_.js} +6 -6
- package/dist/web/server/assets/{telegram-C4v1HhyJ.js → telegram-Gy7_9yih.js} +1 -1
- package/dist/web/server/assets/{telegram-BUdnc8oF.js → telegram-xU-vXgef.js} +1 -1
- package/dist/web/server/assets/{tokens-DqldzPUq.js → tokens-ByPTGFBQ.js} +1 -1
- package/dist/web/server/assets/{tokens-B1twAJdd.js → tokens-CEdl8puR.js} +1 -1
- package/dist/web/server/assets/{tokens-DdjEyALj.js → tokens-CsqoRt5T.js} +10 -10
- package/dist/web/server/assets/{welcome-D0d38Pzx.js → welcome-O6Rjd7yO.js} +1 -1
- package/dist/web/server/assets/workspace-DeEYMPDX.js +658 -0
- package/dist/web/server/server.js +20 -72
- package/dist/worker.js +1 -1
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/dist/web/client/assets/AgentAvatar-DWx-bM6n.js +0 -1
- package/dist/web/client/assets/ChatPane-DOV_HJg-.js +0 -72
- package/dist/web/client/assets/ConfigPage-Dfu9DzFX.js +0 -1
- package/dist/web/client/assets/ConfirmDialog-536ziJ5P.js +0 -1
- package/dist/web/client/assets/FieldRow-z1JqCdqn.js +0 -1
- package/dist/web/client/assets/ResultCard-X4nTbjYY.js +0 -1
- package/dist/web/client/assets/SectionTabs-DXHzXmmb.js +0 -1
- package/dist/web/client/assets/SpawnDialog-DoZl-yes.js +0 -1
- package/dist/web/client/assets/SpawnTeamModal-C638hEoN.js +0 -1
- package/dist/web/client/assets/TeamForm-C-WzvOl4.js +0 -1
- package/dist/web/client/assets/TeamPolicyEditor-CSKBx0oK.js +0 -7
- package/dist/web/client/assets/UnsavedChangesGuard-GC-vzw7h.js +0 -1
- package/dist/web/client/assets/_id-BKLynswT.js +0 -1
- package/dist/web/client/assets/_id-BYM_NORr.js +0 -1
- package/dist/web/client/assets/_id-Cxa98a9m.js +0 -1
- package/dist/web/client/assets/_id-D4hV1U1t.js +0 -1
- package/dist/web/client/assets/agent-actions-CXQCoxKO.js +0 -1
- package/dist/web/client/assets/agents-BxPS1_Bp.js +0 -1
- package/dist/web/client/assets/agents-GozAWW-l.js +0 -1
- package/dist/web/client/assets/attention-Cz9rZcrr.js +0 -1
- package/dist/web/client/assets/chevron-right-CPAb1zac.js +0 -1
- package/dist/web/client/assets/config-9vv9Lipb.js +0 -3
- package/dist/web/client/assets/inbox-DHLArXxl.js +0 -1
- package/dist/web/client/assets/index-1YXquAq8.js +0 -52
- package/dist/web/client/assets/learning-PvtXm8Ne.js +0 -1
- package/dist/web/client/assets/login-DIJpNQFo.js +0 -1
- package/dist/web/client/assets/mcp-pKBL0xIf.js +0 -1
- package/dist/web/client/assets/members-DHWsgsEs.js +0 -1
- package/dist/web/client/assets/memory-CEVppPyU.js +0 -1
- package/dist/web/client/assets/plus-BaIRdB10.js +0 -1
- package/dist/web/client/assets/policy-DEh4BLSw.js +0 -1
- package/dist/web/client/assets/preload-helper-eUUcpe2S.js +0 -1
- package/dist/web/client/assets/results-DgJPjEZF.js +0 -1
- package/dist/web/client/assets/review-BbshafTQ.js +0 -1
- package/dist/web/client/assets/route-Ccb8v41z.js +0 -1
- package/dist/web/client/assets/route-D1d6kCEV.js +0 -1
- package/dist/web/client/assets/routes-g7V4ru7T.js +0 -1
- package/dist/web/client/assets/settings-B6elpcYm.js +0 -1
- package/dist/web/client/assets/skills-CngE7TF8.js +0 -1
- package/dist/web/client/assets/styles-xUnZ-ep_.css +0 -2
- package/dist/web/client/assets/teams-BdJZXOan.js +0 -1
- package/dist/web/client/assets/teams-c496ISsT.js +0 -1
- package/dist/web/client/assets/telegram-B_-hK6EC.js +0 -1
- package/dist/web/client/assets/tokens-CKz8gx4-.js +0 -1
- package/dist/web/client/assets/triggers-DCEPciGW.js +0 -1
- package/dist/web/client/assets/welcome-D-zVOLGA.js +0 -1
- package/dist/web/server/assets/AgentAvatar-8gTAy_tP.js +0 -37
- package/dist/web/server/assets/ChatPane-De_FPEoD.js +0 -1887
- package/dist/web/server/assets/ResultCard-CZn1w4KA.js +0 -97
- package/dist/web/server/assets/Sidebar-puq47KyR.js +0 -430
- package/dist/web/server/assets/SpawnTeamModal-C6GbfScI.js +0 -97
- package/dist/web/server/assets/_id-BR6tnR6I.js +0 -23
- package/dist/web/server/assets/_id-Bm611NQz.js +0 -13
- package/dist/web/server/assets/_id-D5UCoyES.js +0 -359
- package/dist/web/server/assets/_id-DHx5UmmL.js +0 -12
- package/dist/web/server/assets/_id-DLpGmOVm.js +0 -19
- package/dist/web/server/assets/_id-Y5ctILG2.js +0 -13
- package/dist/web/server/assets/_id-dDA0pdVo.js +0 -54
- package/dist/web/server/assets/_tanstack-start-manifest_v-B8u80HjK.js +0 -292
- package/dist/web/server/assets/agent-actions-BBdFVdoa.js +0 -20
- package/dist/web/server/assets/api-WWxPqx67.js +0 -85
- package/dist/web/server/assets/inbox-4Vj5jTT8.js +0 -245
- package/dist/web/server/assets/inbox-D4IqUv3l.js +0 -38
- package/dist/web/server/assets/inbox-Dle24AfV.js +0 -23
- package/dist/web/server/assets/learning-BScq7VbO.js +0 -12
- package/dist/web/server/assets/learning-CBWFEnhg.js +0 -263
- package/dist/web/server/assets/learning-DWAKevhF.js +0 -25
- package/dist/web/server/assets/members-B8QBF6TF.js +0 -12
- package/dist/web/server/assets/members-DsF02Wp7.js +0 -12
- package/dist/web/server/assets/members-tWZA9b15.js +0 -36
- package/dist/web/server/assets/memory-BNN0b-0x.js +0 -12
- package/dist/web/server/assets/memory-CTl1E1Rm.js +0 -267
- package/dist/web/server/assets/memory-CV5uCBb2.js +0 -12
- package/dist/web/server/assets/policy-C9M6zV6w.js +0 -79
- package/dist/web/server/assets/policy-h-6NpU3m.js +0 -19
- package/dist/web/server/assets/policy-xEw9X0DK.js +0 -12
- package/dist/web/server/assets/results-D3A3UA4d.js +0 -182
- package/dist/web/server/assets/results-D6Ui5S8D.js +0 -12
- package/dist/web/server/assets/results-DWmxvfyn.js +0 -15
- package/dist/web/server/assets/review-CyQky-WQ.js +0 -40
- package/dist/web/server/assets/review-Sq0GGcPV.js +0 -322
- package/dist/web/server/assets/review-XWbSF8cF.js +0 -12
- package/dist/web/server/assets/route-BErtkz6t.js +0 -19
- package/dist/web/server/assets/route-CLoV-An_.js +0 -48
- package/dist/web/server/assets/route-WQ19JkBa.js +0 -19
- package/dist/web/server/assets/route-dEK_2GLj.js +0 -203
- package/dist/web/server/assets/route-iHTkhO81.js +0 -16
- package/dist/web/server/assets/route-zs8uUQtB.js +0 -16
- package/dist/web/server/assets/routes-081s4n24.js +0 -45
- package/dist/web/server/assets/routes-CWo5WPsr.js +0 -15
- package/dist/web/server/assets/routes-Cqp1ufHm.js +0 -56
- package/dist/web/server/assets/settings-CVaGv-xF.js +0 -12
- package/dist/web/server/assets/settings-D9viV-86.js +0 -561
- package/dist/web/server/assets/settings-DaZNZ_CC.js +0 -27
- package/dist/web/server/assets/triggers-B7LW784F.js +0 -214
- package/dist/web/server/assets/triggers-C5sMCZXv2.js +0 -12
- package/dist/web/server/assets/triggers-DMfVdImD.js +0 -12
- package/dist/web/client/assets/{TeamPolicyEditor-DLioOiRN.css → style-DLioOiRN.css} +0 -0
- package/dist/web/server/assets/{start-DTX6aKCi.js → start-DhW7sy23.js} +1 -1
package/dist/daemon.js
CHANGED
|
@@ -359,7 +359,7 @@ function onRequest(req, res) {
|
|
|
359
359
|
}
|
|
360
360
|
function getSsrfProxy() {
|
|
361
361
|
if (proxyUrl) return Promise.resolve(proxyUrl);
|
|
362
|
-
starting ??= new Promise((
|
|
362
|
+
starting ??= new Promise((resolve9, reject2) => {
|
|
363
363
|
const s = createServer(onRequest);
|
|
364
364
|
s.on("connect", onConnect);
|
|
365
365
|
s.on("connection", track);
|
|
@@ -371,7 +371,7 @@ function getSsrfProxy() {
|
|
|
371
371
|
s.unref();
|
|
372
372
|
server = s;
|
|
373
373
|
proxyUrl = `http://127.0.0.1:${s.address().port}`;
|
|
374
|
-
|
|
374
|
+
resolve9(proxyUrl);
|
|
375
375
|
});
|
|
376
376
|
}).finally(() => {
|
|
377
377
|
starting = null;
|
|
@@ -385,7 +385,7 @@ async function closeSsrfProxy() {
|
|
|
385
385
|
if (!s) return;
|
|
386
386
|
for (const socket of sockets) socket.destroy();
|
|
387
387
|
sockets.clear();
|
|
388
|
-
await new Promise((
|
|
388
|
+
await new Promise((resolve9) => s.close(() => resolve9()));
|
|
389
389
|
}
|
|
390
390
|
var server, proxyUrl, starting, sockets;
|
|
391
391
|
var init_proxy = __esm({
|
|
@@ -425,8 +425,8 @@ function withTimeout(promise, ms) {
|
|
|
425
425
|
() => {
|
|
426
426
|
}
|
|
427
427
|
),
|
|
428
|
-
new Promise((
|
|
429
|
-
timer = setTimeout(
|
|
428
|
+
new Promise((resolve9) => {
|
|
429
|
+
timer = setTimeout(resolve9, ms);
|
|
430
430
|
})
|
|
431
431
|
]).finally(() => clearTimeout(timer));
|
|
432
432
|
}
|
|
@@ -513,10 +513,10 @@ function connection(server3, connect3, signal) {
|
|
|
513
513
|
if (!signal) return getMcpConnection(server3, connect3);
|
|
514
514
|
if (signal.aborted) return Promise.reject(new McpAbortError());
|
|
515
515
|
const ready = getMcpConnection(server3, connect3);
|
|
516
|
-
return new Promise((
|
|
516
|
+
return new Promise((resolve9, reject2) => {
|
|
517
517
|
const abort = () => reject2(new McpAbortError());
|
|
518
518
|
signal.addEventListener("abort", abort, { once: true });
|
|
519
|
-
ready.then(
|
|
519
|
+
ready.then(resolve9, reject2).finally(() => signal.removeEventListener("abort", abort));
|
|
520
520
|
});
|
|
521
521
|
}
|
|
522
522
|
async function listMcpTools(server3, connect3, signal) {
|
|
@@ -611,7 +611,7 @@ var init_pool = __esm({
|
|
|
611
611
|
}
|
|
612
612
|
const deadline = Date.now() + KILL_WAIT_MS;
|
|
613
613
|
while (Date.now() < deadline) {
|
|
614
|
-
await new Promise((
|
|
614
|
+
await new Promise((resolve9) => setTimeout(resolve9, 20));
|
|
615
615
|
try {
|
|
616
616
|
process.kill(-group, 0);
|
|
617
617
|
} catch {
|
|
@@ -720,24 +720,24 @@ var init_ssrf = __esm({
|
|
|
720
720
|
import { readFileSync as readFileSync6 } from "node:fs";
|
|
721
721
|
import { connect as connect2 } from "node:net";
|
|
722
722
|
import { homedir as homedir2 } from "node:os";
|
|
723
|
-
import { join as
|
|
723
|
+
import { join as join11 } from "node:path";
|
|
724
724
|
function runningBrowserDirs(platform = process.platform, home = homedir2()) {
|
|
725
725
|
if (platform === "darwin") {
|
|
726
|
-
const root2 =
|
|
726
|
+
const root2 = join11(home, "Library", "Application Support");
|
|
727
727
|
return [
|
|
728
|
-
{ name: "Google Chrome", dir:
|
|
729
|
-
{ name: "Google Chrome Beta", dir:
|
|
730
|
-
{ name: "Google Chrome Canary", dir:
|
|
731
|
-
{ name: "Chromium", dir:
|
|
728
|
+
{ name: "Google Chrome", dir: join11(root2, "Google", "Chrome") },
|
|
729
|
+
{ name: "Google Chrome Beta", dir: join11(root2, "Google", "Chrome Beta") },
|
|
730
|
+
{ name: "Google Chrome Canary", dir: join11(root2, "Google", "Chrome Canary") },
|
|
731
|
+
{ name: "Chromium", dir: join11(root2, "Chromium") }
|
|
732
732
|
];
|
|
733
733
|
}
|
|
734
|
-
const root = process.env.XDG_CONFIG_HOME ||
|
|
734
|
+
const root = process.env.XDG_CONFIG_HOME || join11(home, ".config");
|
|
735
735
|
return [
|
|
736
|
-
{ name: "Google Chrome", dir:
|
|
737
|
-
{ name: "Google Chrome Beta", dir:
|
|
738
|
-
{ name: "Google Chrome Dev", dir:
|
|
739
|
-
{ name: "Chromium", dir:
|
|
740
|
-
{ name: "Chromium", dir:
|
|
736
|
+
{ name: "Google Chrome", dir: join11(root, "google-chrome") },
|
|
737
|
+
{ name: "Google Chrome Beta", dir: join11(root, "google-chrome-beta") },
|
|
738
|
+
{ name: "Google Chrome Dev", dir: join11(root, "google-chrome-unstable") },
|
|
739
|
+
{ name: "Chromium", dir: join11(root, "chromium") },
|
|
740
|
+
{ name: "Chromium", dir: join11(home, "snap", "chromium", "common", "chromium") }
|
|
741
741
|
];
|
|
742
742
|
}
|
|
743
743
|
function parseDevToolsActivePort(content) {
|
|
@@ -747,11 +747,11 @@ function parseDevToolsActivePort(content) {
|
|
|
747
747
|
return `ws://127.0.0.1:${port2}${path}`;
|
|
748
748
|
}
|
|
749
749
|
function isListening(endpoint2) {
|
|
750
|
-
return new Promise((
|
|
750
|
+
return new Promise((resolve9) => {
|
|
751
751
|
const socket = connect2({ host: "127.0.0.1", port: Number(new URL(endpoint2).port) });
|
|
752
752
|
const done = (listening) => {
|
|
753
753
|
socket.destroy();
|
|
754
|
-
|
|
754
|
+
resolve9(listening);
|
|
755
755
|
};
|
|
756
756
|
socket.setTimeout(1e3, () => done(false));
|
|
757
757
|
socket.once("connect", () => done(true));
|
|
@@ -763,7 +763,7 @@ async function findRunningBrowser(dirs = runningBrowserDirs()) {
|
|
|
763
763
|
for (const { name, dir } of dirs) {
|
|
764
764
|
let content;
|
|
765
765
|
try {
|
|
766
|
-
content = readFileSync6(
|
|
766
|
+
content = readFileSync6(join11(dir, "DevToolsActivePort"), "utf8");
|
|
767
767
|
} catch (error) {
|
|
768
768
|
const code = error.code;
|
|
769
769
|
if (code === "EPERM" || code === "EACCES") denied = dir;
|
|
@@ -891,21 +891,21 @@ var init_attach = __esm({
|
|
|
891
891
|
});
|
|
892
892
|
|
|
893
893
|
// ../daemon/src/lib/browser/executable.ts
|
|
894
|
-
import { accessSync, constants, readdirSync as readdirSync3, statSync as
|
|
894
|
+
import { accessSync, constants, readdirSync as readdirSync3, statSync as statSync4 } from "node:fs";
|
|
895
895
|
import { homedir as homedir3 } from "node:os";
|
|
896
|
-
import { basename as basename3, isAbsolute, join as
|
|
896
|
+
import { basename as basename3, isAbsolute, join as join12 } from "node:path";
|
|
897
897
|
function installedBrowserPaths(platform = process.platform, home = homedir3()) {
|
|
898
898
|
if (platform !== "darwin") return LINUX_INSTALLED;
|
|
899
|
-
return ["/Applications",
|
|
899
|
+
return ["/Applications", join12(home, "Applications")].flatMap(
|
|
900
900
|
(root) => MAC_APPS.map(({ app: app2, name }) => ({
|
|
901
|
-
path:
|
|
901
|
+
path: join12(root, `${app2}.app`, "Contents", "MacOS", app2),
|
|
902
902
|
name
|
|
903
903
|
}))
|
|
904
904
|
);
|
|
905
905
|
}
|
|
906
906
|
function isExecutableFile(path) {
|
|
907
907
|
try {
|
|
908
|
-
if (!
|
|
908
|
+
if (!statSync4(path).isFile()) return false;
|
|
909
909
|
accessSync(path, constants.X_OK);
|
|
910
910
|
return true;
|
|
911
911
|
} catch {
|
|
@@ -913,7 +913,7 @@ function isExecutableFile(path) {
|
|
|
913
913
|
}
|
|
914
914
|
}
|
|
915
915
|
function playwrightCacheDir(platform = process.platform, home = homedir3()) {
|
|
916
|
-
return process.env.PLAYWRIGHT_BROWSERS_PATH || (platform === "darwin" ?
|
|
916
|
+
return process.env.PLAYWRIGHT_BROWSERS_PATH || (platform === "darwin" ? join12(home, "Library", "Caches", "ms-playwright") : join12(home, ".cache", "ms-playwright"));
|
|
917
917
|
}
|
|
918
918
|
function bundledChromium(root = playwrightCacheDir()) {
|
|
919
919
|
let entries;
|
|
@@ -925,7 +925,7 @@ function bundledChromium(root = playwrightCacheDir()) {
|
|
|
925
925
|
const revisions = entries.filter((entry) => /^chromium-\d+$/.test(entry)).sort((a, b) => Number(b.slice("chromium-".length)) - Number(a.slice("chromium-".length)));
|
|
926
926
|
for (const revision of revisions) {
|
|
927
927
|
for (const layout of BUNDLED_LAYOUTS) {
|
|
928
|
-
const path =
|
|
928
|
+
const path = join12(root, revision, ...layout);
|
|
929
929
|
if (isExecutableFile(path)) return { path, name: "Chromium (Playwright)" };
|
|
930
930
|
}
|
|
931
931
|
}
|
|
@@ -987,14 +987,14 @@ var init_executable = __esm({
|
|
|
987
987
|
// ../daemon/src/lib/browser/install.ts
|
|
988
988
|
import { spawn } from "node:child_process";
|
|
989
989
|
import { createRequire } from "node:module";
|
|
990
|
-
import { dirname as dirname3, join as
|
|
990
|
+
import { dirname as dirname3, join as join13 } from "node:path";
|
|
991
991
|
function downloadAllowed() {
|
|
992
992
|
const skip2 = process.env.PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD?.trim().toLowerCase();
|
|
993
993
|
return !skip2 || skip2 === "0" || skip2 === "false";
|
|
994
994
|
}
|
|
995
995
|
function runInstaller() {
|
|
996
|
-
return new Promise((
|
|
997
|
-
const cli =
|
|
996
|
+
return new Promise((resolve9, reject2) => {
|
|
997
|
+
const cli = join13(
|
|
998
998
|
dirname3(createRequire(import.meta.url).resolve("playwright/package.json")),
|
|
999
999
|
"cli.js"
|
|
1000
1000
|
);
|
|
@@ -1017,7 +1017,7 @@ function runInstaller() {
|
|
|
1017
1017
|
child.stderr.on("data", keep);
|
|
1018
1018
|
child.once("error", reject2);
|
|
1019
1019
|
child.once("exit", (code, signal) => {
|
|
1020
|
-
if (code === 0)
|
|
1020
|
+
if (code === 0) resolve9();
|
|
1021
1021
|
else reject2(new Error(output.trim() || `the installer ended with ${signal ?? code}`));
|
|
1022
1022
|
});
|
|
1023
1023
|
});
|
|
@@ -1081,13 +1081,13 @@ var init_install = __esm({
|
|
|
1081
1081
|
// ../daemon/src/lib/browser/launch.ts
|
|
1082
1082
|
import { execFileSync, spawn as spawn2 } from "node:child_process";
|
|
1083
1083
|
import { mkdirSync as mkdirSync5, readFileSync as readFileSync7, readlinkSync, writeFileSync as writeFileSync4 } from "node:fs";
|
|
1084
|
-
import { join as
|
|
1084
|
+
import { join as join14 } from "node:path";
|
|
1085
1085
|
function launchArgs(opts) {
|
|
1086
1086
|
const wayland = !opts.headless && !process.env.DISPLAY && !!process.env.WAYLAND_DISPLAY;
|
|
1087
1087
|
return [
|
|
1088
1088
|
// Chromium picks the port and prints the endpoint on stderr.
|
|
1089
1089
|
"--remote-debugging-port=0",
|
|
1090
|
-
`--user-data-dir=${
|
|
1090
|
+
`--user-data-dir=${join14(opts.dir, "user-data")}`,
|
|
1091
1091
|
"--no-first-run",
|
|
1092
1092
|
"--no-default-browser-check",
|
|
1093
1093
|
"--disable-sync",
|
|
@@ -1113,7 +1113,7 @@ function launchArgs(opts) {
|
|
|
1113
1113
|
function browserEnv(opts) {
|
|
1114
1114
|
const env = {
|
|
1115
1115
|
PATH: process.env.PATH ?? "/usr/bin:/bin",
|
|
1116
|
-
HOME:
|
|
1116
|
+
HOME: join14(opts.dir, "home"),
|
|
1117
1117
|
LANG: "C.UTF-8"
|
|
1118
1118
|
};
|
|
1119
1119
|
if (!opts.headless) {
|
|
@@ -1150,10 +1150,10 @@ function runsOnProfile(pid, userDataDir) {
|
|
|
1150
1150
|
}
|
|
1151
1151
|
}
|
|
1152
1152
|
async function killOrphanBrowser(dir) {
|
|
1153
|
-
const userDataDir =
|
|
1153
|
+
const userDataDir = join14(dir, "user-data");
|
|
1154
1154
|
let pid;
|
|
1155
1155
|
try {
|
|
1156
|
-
pid = Number(/-(\d+)$/.exec(readlinkSync(
|
|
1156
|
+
pid = Number(/-(\d+)$/.exec(readlinkSync(join14(userDataDir, "SingletonLock")))?.[1]);
|
|
1157
1157
|
if (!runsOnProfile(pid, userDataDir)) return;
|
|
1158
1158
|
} catch {
|
|
1159
1159
|
return;
|
|
@@ -1166,8 +1166,8 @@ async function killOrphanBrowser(dir) {
|
|
|
1166
1166
|
for (let i = 0; i < 40 && isAlive(pid); i++) await sleep(50);
|
|
1167
1167
|
}
|
|
1168
1168
|
function skipSessionRestore(userDataDir) {
|
|
1169
|
-
const dir =
|
|
1170
|
-
const file =
|
|
1169
|
+
const dir = join14(userDataDir, "Default");
|
|
1170
|
+
const file = join14(dir, "Preferences");
|
|
1171
1171
|
let prefs = {};
|
|
1172
1172
|
try {
|
|
1173
1173
|
const parsed = JSON.parse(readFileSync7(file, "utf8"));
|
|
@@ -1190,9 +1190,9 @@ function trackGroup(pid) {
|
|
|
1190
1190
|
});
|
|
1191
1191
|
}
|
|
1192
1192
|
async function launchBrowser(opts) {
|
|
1193
|
-
const userDataDir =
|
|
1193
|
+
const userDataDir = join14(opts.dir, "user-data");
|
|
1194
1194
|
mkdirSync5(userDataDir, { recursive: true, mode: 448 });
|
|
1195
|
-
mkdirSync5(
|
|
1195
|
+
mkdirSync5(join14(opts.dir, "home"), { recursive: true, mode: 448 });
|
|
1196
1196
|
await killOrphanBrowser(opts.dir);
|
|
1197
1197
|
skipSessionRestore(userDataDir);
|
|
1198
1198
|
const child = spawn2(opts.executablePath, launchArgs(opts), {
|
|
@@ -1210,7 +1210,7 @@ async function launchBrowser(opts) {
|
|
|
1210
1210
|
liveGroups.delete(pid);
|
|
1211
1211
|
});
|
|
1212
1212
|
}
|
|
1213
|
-
const exited = new Promise((
|
|
1213
|
+
const exited = new Promise((resolve9) => child.once("exit", () => resolve9(true)));
|
|
1214
1214
|
const waitForExit = (ms) => Promise.race([exited, sleep(ms).then(() => false)]);
|
|
1215
1215
|
const running = () => child.exitCode === null && child.signalCode === null;
|
|
1216
1216
|
let browser;
|
|
@@ -1233,7 +1233,7 @@ async function launchBrowser(opts) {
|
|
|
1233
1233
|
})();
|
|
1234
1234
|
let stderr = "";
|
|
1235
1235
|
try {
|
|
1236
|
-
const endpoint2 = await new Promise((
|
|
1236
|
+
const endpoint2 = await new Promise((resolve9, reject2) => {
|
|
1237
1237
|
const fail2 = (message) => {
|
|
1238
1238
|
clearTimeout(timer);
|
|
1239
1239
|
reject2(new Error(stderr.trim() ? `${message}:
|
|
@@ -1263,7 +1263,7 @@ ${stderr.trim()}` : message));
|
|
|
1263
1263
|
);
|
|
1264
1264
|
if (match?.[1]) {
|
|
1265
1265
|
clearTimeout(timer);
|
|
1266
|
-
|
|
1266
|
+
resolve9(match[1]);
|
|
1267
1267
|
}
|
|
1268
1268
|
}
|
|
1269
1269
|
});
|
|
@@ -1301,7 +1301,7 @@ var init_launch = __esm({
|
|
|
1301
1301
|
NO_WEBRTC_SCRIPT = `for (const name of ['RTCPeerConnection', 'webkitRTCPeerConnection', 'mozRTCPeerConnection']) {
|
|
1302
1302
|
Object.defineProperty(window, name, { configurable: false, get() { return undefined } })
|
|
1303
1303
|
}`;
|
|
1304
|
-
sleep = (ms) => new Promise((
|
|
1304
|
+
sleep = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
|
|
1305
1305
|
liveGroups = /* @__PURE__ */ new Set();
|
|
1306
1306
|
exitHookInstalled = false;
|
|
1307
1307
|
}
|
|
@@ -1587,7 +1587,7 @@ function browserStatus(agentId, config, paths, enabled) {
|
|
|
1587
1587
|
}
|
|
1588
1588
|
return status2;
|
|
1589
1589
|
}
|
|
1590
|
-
function
|
|
1590
|
+
function text2(value) {
|
|
1591
1591
|
return [{ type: "text", text: capText(value) }];
|
|
1592
1592
|
}
|
|
1593
1593
|
function firstLine(error) {
|
|
@@ -1647,7 +1647,7 @@ async function act(session, refs, action) {
|
|
|
1647
1647
|
const page = await activePage(session);
|
|
1648
1648
|
for (const ref of refs) {
|
|
1649
1649
|
if (await page.locator(`aria-ref=${ref}`).count() === 0) {
|
|
1650
|
-
return
|
|
1650
|
+
return text2(
|
|
1651
1651
|
`Ref "${ref}" is not on the page any more, so nothing was done. Use a ref from this fresh snapshot:
|
|
1652
1652
|
|
|
1653
1653
|
${await freshSnapshot(session, page)}`
|
|
@@ -1657,14 +1657,14 @@ ${await freshSnapshot(session, page)}`
|
|
|
1657
1657
|
try {
|
|
1658
1658
|
await action(page);
|
|
1659
1659
|
} catch (error) {
|
|
1660
|
-
return
|
|
1660
|
+
return text2(
|
|
1661
1661
|
`Could not act on ref "${refs.join(", ")}": ${firstLine(error)}
|
|
1662
1662
|
The action may still have taken effect: check the page below before trying again, and never repeat a submission blindly.
|
|
1663
1663
|
|
|
1664
1664
|
` + await freshSnapshot(session, page)
|
|
1665
1665
|
);
|
|
1666
1666
|
}
|
|
1667
|
-
return
|
|
1667
|
+
return text2(await freshSnapshot(session, page));
|
|
1668
1668
|
}
|
|
1669
1669
|
async function runAction(session, action, args, config) {
|
|
1670
1670
|
switch (action) {
|
|
@@ -1673,14 +1673,14 @@ async function runAction(session, action, args, config) {
|
|
|
1673
1673
|
await checkUrl(url, config);
|
|
1674
1674
|
const page = await activePage(session);
|
|
1675
1675
|
await page.goto(url, { waitUntil: "domcontentloaded" });
|
|
1676
|
-
return
|
|
1676
|
+
return text2(await freshSnapshot(session, page));
|
|
1677
1677
|
}
|
|
1678
1678
|
case "snapshot": {
|
|
1679
|
-
if (args.page !== void 0) return
|
|
1679
|
+
if (args.page !== void 0) return text2(snapshotPage(session, args.page));
|
|
1680
1680
|
const page = await activePage(session);
|
|
1681
|
-
if (isBlank(page)) return
|
|
1681
|
+
if (isBlank(page)) return text2(NO_PAGE_HINT);
|
|
1682
1682
|
const ref = args.ref === void 0 ? void 0 : elementRef(args.ref);
|
|
1683
|
-
return
|
|
1683
|
+
return text2(await snapshot(session, page, ref));
|
|
1684
1684
|
}
|
|
1685
1685
|
case "click": {
|
|
1686
1686
|
const ref = elementRef(args.ref);
|
|
@@ -1727,18 +1727,18 @@ async function runAction(session, action, args, config) {
|
|
|
1727
1727
|
const key2 = stringArg(args, "key");
|
|
1728
1728
|
const page = await activePage(session);
|
|
1729
1729
|
await page.keyboard.press(key2);
|
|
1730
|
-
return
|
|
1730
|
+
return text2(await freshSnapshot(session, page));
|
|
1731
1731
|
}
|
|
1732
1732
|
case "go_back": {
|
|
1733
1733
|
const page = await activePage(session);
|
|
1734
1734
|
await page.goBack({ waitUntil: "domcontentloaded" });
|
|
1735
|
-
return
|
|
1735
|
+
return text2(await freshSnapshot(session, page));
|
|
1736
1736
|
}
|
|
1737
1737
|
case "tabs":
|
|
1738
1738
|
return tabs(session, args, config);
|
|
1739
1739
|
case "take_screenshot": {
|
|
1740
1740
|
const page = await activePage(session);
|
|
1741
|
-
if (isBlank(page)) return
|
|
1741
|
+
if (isBlank(page)) return text2(NO_PAGE_HINT);
|
|
1742
1742
|
const png = await page.screenshot({
|
|
1743
1743
|
type: "png",
|
|
1744
1744
|
fullPage: args.full_page === true,
|
|
@@ -1755,9 +1755,9 @@ async function runAction(session, action, args, config) {
|
|
|
1755
1755
|
];
|
|
1756
1756
|
}
|
|
1757
1757
|
case "console":
|
|
1758
|
-
return
|
|
1758
|
+
return text2(session.console.join("\n") || "no console messages");
|
|
1759
1759
|
case "network":
|
|
1760
|
-
return
|
|
1760
|
+
return text2(
|
|
1761
1761
|
session.network.map((r) => `${r.method} ${r.status ?? "..."} ${r.url}`).join("\n") || "no network requests recorded"
|
|
1762
1762
|
);
|
|
1763
1763
|
default:
|
|
@@ -1772,7 +1772,7 @@ async function tabs(session, args, config) {
|
|
|
1772
1772
|
const id2 = tabId(session, page2);
|
|
1773
1773
|
return `${id2 === session.activeTab ? "*" : " "} ${id2} ${clip(page2.url())}`;
|
|
1774
1774
|
}).join("\n");
|
|
1775
|
-
return
|
|
1775
|
+
return text2(lines || "No tabs are open.");
|
|
1776
1776
|
}
|
|
1777
1777
|
if (op === "new") {
|
|
1778
1778
|
if (browser.pages().length >= MAX_TABS) {
|
|
@@ -1782,9 +1782,9 @@ async function tabs(session, args, config) {
|
|
|
1782
1782
|
if (url) await checkUrl(url, config);
|
|
1783
1783
|
const page2 = await browser.newPage();
|
|
1784
1784
|
session.activeTab = tabId(session, page2);
|
|
1785
|
-
if (!url) return
|
|
1785
|
+
if (!url) return text2(`Opened ${session.activeTab} (about:blank).`);
|
|
1786
1786
|
await page2.goto(url, { waitUntil: "domcontentloaded" });
|
|
1787
|
-
return
|
|
1787
|
+
return text2(await freshSnapshot(session, page2));
|
|
1788
1788
|
}
|
|
1789
1789
|
const id = stringArg(args, "tabId");
|
|
1790
1790
|
const page = browser.pages().find((p) => tabId(session, p) === id);
|
|
@@ -1792,14 +1792,14 @@ async function tabs(session, args, config) {
|
|
|
1792
1792
|
if (!page) throw new Error(`No open tab "${id}"; browser_tabs {"op":"list"} lists them.`);
|
|
1793
1793
|
await page.bringToFront();
|
|
1794
1794
|
session.activeTab = id;
|
|
1795
|
-
return
|
|
1795
|
+
return text2(
|
|
1796
1796
|
isBlank(page) ? `Selected ${id} (about:blank).` : await freshSnapshot(session, page)
|
|
1797
1797
|
);
|
|
1798
1798
|
}
|
|
1799
1799
|
if (op === "close") {
|
|
1800
|
-
if (!page) return
|
|
1800
|
+
if (!page) return text2(`Tab "${id}" is not open.`);
|
|
1801
1801
|
await page.close();
|
|
1802
|
-
return
|
|
1802
|
+
return text2(`Closed ${id}.`);
|
|
1803
1803
|
}
|
|
1804
1804
|
throw new Error(`unknown tabs op "${op}" (expected list, new, select or close)`);
|
|
1805
1805
|
}
|
|
@@ -3155,6 +3155,11 @@ var ATTENTION_KINDS = [
|
|
|
3155
3155
|
"queue_interrupted"
|
|
3156
3156
|
];
|
|
3157
3157
|
var bounded = (value, fallback) => (value?.trim() || fallback).replace(/(authorization:\s*bearer\s+)[^\s,;]+/gi, "$1[redacted]").replace(/\bsk-[a-z0-9_-]{8,}\b/gi, "[redacted]").replace(/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/gi, "$1[redacted]@").slice(0, 500);
|
|
3158
|
+
function agentHref(agentId, section) {
|
|
3159
|
+
const query = new URLSearchParams({ agent: agentId ?? "" });
|
|
3160
|
+
if (section) query.set("section", section);
|
|
3161
|
+
return `/?${query}`;
|
|
3162
|
+
}
|
|
3158
3163
|
var sources = [
|
|
3159
3164
|
{
|
|
3160
3165
|
kind: "lesson_proposal",
|
|
@@ -3169,7 +3174,7 @@ var sources = [
|
|
|
3169
3174
|
severity: "action_required",
|
|
3170
3175
|
title: "Lesson proposal ready",
|
|
3171
3176
|
diagnostic: "A reviewed-learning proposal is waiting for approval or rejection.",
|
|
3172
|
-
href:
|
|
3177
|
+
href: agentHref(r.agentId, "learning"),
|
|
3173
3178
|
acknowledgeable: false
|
|
3174
3179
|
})
|
|
3175
3180
|
)
|
|
@@ -3188,7 +3193,7 @@ var sources = [
|
|
|
3188
3193
|
severity: "error",
|
|
3189
3194
|
title: r.status === "cancelled" ? "Agent review cancelled" : "Agent review failed",
|
|
3190
3195
|
diagnostic: bounded(r.diagnostic, "The review stopped without completing."),
|
|
3191
|
-
href:
|
|
3196
|
+
href: agentHref(r.agentId, "learning"),
|
|
3192
3197
|
acknowledgeable: true
|
|
3193
3198
|
})
|
|
3194
3199
|
)
|
|
@@ -3208,7 +3213,7 @@ var sources = [
|
|
|
3208
3213
|
severity: "error",
|
|
3209
3214
|
title: "Scheduled trigger failed",
|
|
3210
3215
|
diagnostic: bounded(r.diagnostic, "The scheduled Agent turn failed."),
|
|
3211
|
-
href:
|
|
3216
|
+
href: agentHref(r.agentId, "schedules"),
|
|
3212
3217
|
acknowledgeable: true
|
|
3213
3218
|
})
|
|
3214
3219
|
)
|
|
@@ -3226,7 +3231,7 @@ var sources = [
|
|
|
3226
3231
|
severity: "warning",
|
|
3227
3232
|
title: "Agent message loop stopped",
|
|
3228
3233
|
diagnostic: `Message chain stopped at hop ${r.attempted_hop} (limit ${r.max_hops}).`,
|
|
3229
|
-
href:
|
|
3234
|
+
href: agentHref(r.agentId, "mailbox"),
|
|
3230
3235
|
acknowledgeable: true
|
|
3231
3236
|
})
|
|
3232
3237
|
)
|
|
@@ -3255,7 +3260,7 @@ var sources = [
|
|
|
3255
3260
|
severity: "action_required",
|
|
3256
3261
|
title: "Agent queue paused after a daemon restart",
|
|
3257
3262
|
diagnostic: `The daemon restarted during a follow-up, which was not run again (${r.interrupted_count} interrupted). ${r.waiting_count} follow-up${r.waiting_count === 1 ? " waits" : "s wait"} in the paused queue: check them, then resume the queue.`,
|
|
3258
|
-
href:
|
|
3263
|
+
href: agentHref(r.agentId),
|
|
3259
3264
|
acknowledgeable: false
|
|
3260
3265
|
})
|
|
3261
3266
|
)
|
|
@@ -4683,7 +4688,7 @@ var SERVICES = [
|
|
|
4683
4688
|
displayName: "Browser Automation",
|
|
4684
4689
|
category: "service",
|
|
4685
4690
|
team: "Browser",
|
|
4686
|
-
hint: 'Each Agent gets its own persistent browser profile (cookies, logins), kept across turns and Team moves and excluded from backups. Reset
|
|
4691
|
+
hint: 'Each Agent gets its own persistent browser profile (cookies, logins), kept across turns and Team moves and excluded from backups. Reset under Browser in the web workspace, or deleting the Agent, removes it. With "Use my running browser" on, Agents work in your own Chrome or Chromium instead.',
|
|
4687
4692
|
fields: [
|
|
4688
4693
|
{
|
|
4689
4694
|
envVar: "BROWSER_ENABLED",
|
|
@@ -4950,6 +4955,7 @@ var messages_exports = {};
|
|
|
4950
4955
|
__export(messages_exports, {
|
|
4951
4956
|
drainUnreadForAgent: () => drainUnreadForAgent,
|
|
4952
4957
|
get: () => get10,
|
|
4958
|
+
listForTeam: () => listForTeam,
|
|
4953
4959
|
listInbox: () => listInbox,
|
|
4954
4960
|
listRecipientsWithUnread: () => listRecipientsWithUnread,
|
|
4955
4961
|
markRead: () => markRead,
|
|
@@ -5001,6 +5007,14 @@ function listInbox(db, agentId, opts) {
|
|
|
5001
5007
|
const sql = opts?.unreadOnly ? "SELECT * FROM messages WHERE to_agent_id = ? AND read_at IS NULL ORDER BY created_at ASC" : "SELECT * FROM messages WHERE to_agent_id = ? ORDER BY created_at ASC";
|
|
5002
5008
|
return db.raw.query(sql).all(agentId).map(toMessage);
|
|
5003
5009
|
}
|
|
5010
|
+
function listForTeam(db, teamId, limit) {
|
|
5011
|
+
return db.raw.query(
|
|
5012
|
+
`SELECT m.* FROM messages m
|
|
5013
|
+
WHERE m.from_agent_id IN (SELECT id FROM agents WHERE team_id = ?)
|
|
5014
|
+
OR m.to_agent_id IN (SELECT id FROM agents WHERE team_id = ?)
|
|
5015
|
+
ORDER BY m.created_at DESC, m.id DESC LIMIT ?`
|
|
5016
|
+
).all(teamId, teamId, limit).map(toMessage);
|
|
5017
|
+
}
|
|
5004
5018
|
function markRead(db, id) {
|
|
5005
5019
|
db.raw.run("UPDATE messages SET read_at = ? WHERE id = ? AND read_at IS NULL", [Date.now(), id]);
|
|
5006
5020
|
}
|
|
@@ -6193,6 +6207,214 @@ async function authMiddleware(c, next) {
|
|
|
6193
6207
|
await next();
|
|
6194
6208
|
}
|
|
6195
6209
|
|
|
6210
|
+
// ../daemon/src/lib/activity.ts
|
|
6211
|
+
import { statSync as statSync3 } from "node:fs";
|
|
6212
|
+
import { join as join10 } from "node:path";
|
|
6213
|
+
|
|
6214
|
+
// ../daemon/src/core/repos/conversations.ts
|
|
6215
|
+
var columns = "id, agent_id AS agentId, title, created_at AS createdAt, updated_at AS updatedAt";
|
|
6216
|
+
var ConversationChangedError = class extends DomainError {
|
|
6217
|
+
constructor() {
|
|
6218
|
+
super(409, "The Agent switched to another conversation. Reload before trying again.");
|
|
6219
|
+
}
|
|
6220
|
+
};
|
|
6221
|
+
function selectedId(db, agentId) {
|
|
6222
|
+
return db.raw.query(
|
|
6223
|
+
"SELECT conversation_id AS id FROM agent_conversation_selection WHERE agent_id = ?"
|
|
6224
|
+
).get(agentId)?.id ?? null;
|
|
6225
|
+
}
|
|
6226
|
+
function get16(db, agentId, id) {
|
|
6227
|
+
return db.raw.query(
|
|
6228
|
+
`SELECT ${columns} FROM agent_conversations WHERE agent_id = ? AND id = ?`
|
|
6229
|
+
).get(agentId, id);
|
|
6230
|
+
}
|
|
6231
|
+
function list11(db, agentId, limit = 20, offset = 0) {
|
|
6232
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !Number.isSafeInteger(offset) || offset < 0)
|
|
6233
|
+
throw new DomainError(400, "Invalid conversation pagination");
|
|
6234
|
+
const conversations = db.raw.query(
|
|
6235
|
+
`SELECT ${columns} FROM agent_conversations WHERE agent_id = ? ORDER BY created_at DESC, id LIMIT ? OFFSET ?`
|
|
6236
|
+
).all(agentId, limit, offset);
|
|
6237
|
+
const total = db.raw.query(
|
|
6238
|
+
"SELECT COUNT(*) AS n FROM agent_conversations WHERE agent_id = ?"
|
|
6239
|
+
).get(agentId)?.n ?? 0;
|
|
6240
|
+
return { conversations, selectedId: selectedId(db, agentId), total, offset, limit };
|
|
6241
|
+
}
|
|
6242
|
+
function validTitle(value) {
|
|
6243
|
+
if (typeof value !== "string" || !value.trim() || value.length > 200 || Array.from(value).some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127))
|
|
6244
|
+
throw new DomainError(
|
|
6245
|
+
400,
|
|
6246
|
+
"Conversation title must be 1\u2013200 characters without control characters"
|
|
6247
|
+
);
|
|
6248
|
+
return value.trim();
|
|
6249
|
+
}
|
|
6250
|
+
function create5(db, agentId, id, title) {
|
|
6251
|
+
const displayTitle = title === void 0 ? void 0 : validTitle(title);
|
|
6252
|
+
return db.raw.transaction(() => {
|
|
6253
|
+
const now = Date.now();
|
|
6254
|
+
db.raw.run(
|
|
6255
|
+
`INSERT INTO agent_conversations (id, agent_id, title, created_at, updated_at)
|
|
6256
|
+
VALUES (?, ?, ?, ?, ?)`,
|
|
6257
|
+
[id, agentId, displayTitle ?? `Conversation ${list11(db, agentId, 1).total + 1}`, now, now]
|
|
6258
|
+
);
|
|
6259
|
+
db.raw.run(
|
|
6260
|
+
`INSERT INTO agent_conversation_selection (agent_id, conversation_id) VALUES (?, ?)
|
|
6261
|
+
ON CONFLICT(agent_id) DO UPDATE SET conversation_id = excluded.conversation_id`,
|
|
6262
|
+
[agentId, id]
|
|
6263
|
+
);
|
|
6264
|
+
const conversation = get16(db, agentId, id);
|
|
6265
|
+
if (!conversation) throw new Error("Conversation not found");
|
|
6266
|
+
return conversation;
|
|
6267
|
+
})();
|
|
6268
|
+
}
|
|
6269
|
+
function select(db, agentId, id) {
|
|
6270
|
+
const conversation = get16(db, agentId, id);
|
|
6271
|
+
if (!conversation) throw new DomainError(404, "Conversation not found");
|
|
6272
|
+
db.raw.run(
|
|
6273
|
+
`INSERT INTO agent_conversation_selection (agent_id, conversation_id) VALUES (?, ?)
|
|
6274
|
+
ON CONFLICT(agent_id) DO UPDATE SET conversation_id = excluded.conversation_id`,
|
|
6275
|
+
[agentId, id]
|
|
6276
|
+
);
|
|
6277
|
+
return conversation;
|
|
6278
|
+
}
|
|
6279
|
+
function hasDefaultTitle(conversation) {
|
|
6280
|
+
return /^Conversation \d+$/.test(conversation.title);
|
|
6281
|
+
}
|
|
6282
|
+
function rename(db, agentId, id, title) {
|
|
6283
|
+
db.raw.run(
|
|
6284
|
+
"UPDATE agent_conversations SET title = ?, updated_at = ? WHERE agent_id = ? AND id = ?",
|
|
6285
|
+
[validTitle(title), Date.now(), agentId, id]
|
|
6286
|
+
);
|
|
6287
|
+
const conversation = get16(db, agentId, id);
|
|
6288
|
+
if (!conversation) throw new DomainError(404, "Conversation not found");
|
|
6289
|
+
return conversation;
|
|
6290
|
+
}
|
|
6291
|
+
|
|
6292
|
+
// ../daemon/src/core/repos/results.ts
|
|
6293
|
+
import { createHash as createHash3, randomUUID as randomUUID13 } from "node:crypto";
|
|
6294
|
+
|
|
6295
|
+
// ../daemon/src/core/tool-call-id.ts
|
|
6296
|
+
function isToolCallId(value) {
|
|
6297
|
+
return typeof value === "string" && value.length <= 256 && // A true end assertion also rejects a trailing newline (unlike JavaScript '$').
|
|
6298
|
+
/^[A-Za-z0-9._:-]+(?:\|[A-Za-z0-9._:-]+)?$(?![\s\S])/.test(value);
|
|
6299
|
+
}
|
|
6300
|
+
|
|
6301
|
+
// ../daemon/src/core/repos/results.ts
|
|
6302
|
+
var MAX_RESULT_BYTES = 25 * 1024 * 1024;
|
|
6303
|
+
var MAX_RETAINED_RESULT_BYTES = 1024 * 1024 * 1024;
|
|
6304
|
+
var columns2 = `id, team_id AS teamId, agent_id AS agentId, session_id AS sessionId,
|
|
6305
|
+
tool_call_id AS toolCallId, source_index AS sourceIndex, name, mime_type AS mimeType,
|
|
6306
|
+
byte_length AS byteLength, sha256, image_model AS imageModel, created_at AS createdAt`;
|
|
6307
|
+
function get17(db, id) {
|
|
6308
|
+
return db.raw.query(`SELECT ${columns2} FROM agent_results WHERE id = ?`).get(id);
|
|
6309
|
+
}
|
|
6310
|
+
function publish(db, input) {
|
|
6311
|
+
if (!isToolCallId(input.toolCallId)) throw new Error("Invalid result tool call");
|
|
6312
|
+
if (typeof input.name !== "string" || !input.name || input.name.length > 255 || /[/\\]/.test(input.name) || [...input.name].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) || input.name === "." || input.name === "..")
|
|
6313
|
+
throw new Error("Invalid result filename");
|
|
6314
|
+
if (typeof input.mimeType !== "string" || !/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(input.mimeType))
|
|
6315
|
+
throw new Error("Invalid result media type");
|
|
6316
|
+
if (input.bytes.byteLength > MAX_RESULT_BYTES)
|
|
6317
|
+
throw new Error("Result exceeds the 25 MiB per-file limit");
|
|
6318
|
+
const bytes = Buffer.from(input.bytes);
|
|
6319
|
+
const sourceIndex = input.sourceIndex ?? 0;
|
|
6320
|
+
return db.raw.transaction(() => {
|
|
6321
|
+
const existing = db.raw.query(
|
|
6322
|
+
`SELECT id FROM agent_results
|
|
6323
|
+
WHERE agent_id = ? AND session_id = ? AND tool_call_id = ? AND source_index = ?`
|
|
6324
|
+
).get(input.agentId, input.sessionId, input.toolCallId, sourceIndex);
|
|
6325
|
+
if (existing) return get17(db, existing.id);
|
|
6326
|
+
const retained = db.raw.query(
|
|
6327
|
+
"SELECT coalesce(sum(byte_length), 0) AS bytes FROM agent_results"
|
|
6328
|
+
).get()?.bytes ?? 0;
|
|
6329
|
+
if (retained + bytes.byteLength > MAX_RETAINED_RESULT_BYTES)
|
|
6330
|
+
throw new Error(
|
|
6331
|
+
"Result storage is full (1 GiB). Delete saved results before delivering more files."
|
|
6332
|
+
);
|
|
6333
|
+
const id = randomUUID13();
|
|
6334
|
+
db.raw.run(
|
|
6335
|
+
`INSERT INTO agent_results
|
|
6336
|
+
(id, team_id, agent_id, session_id, tool_call_id, source_index, name, mime_type,
|
|
6337
|
+
byte_length, sha256, image_model, created_at, bytes)
|
|
6338
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
6339
|
+
[
|
|
6340
|
+
id,
|
|
6341
|
+
input.teamId,
|
|
6342
|
+
input.agentId,
|
|
6343
|
+
input.sessionId,
|
|
6344
|
+
input.toolCallId,
|
|
6345
|
+
sourceIndex,
|
|
6346
|
+
input.name,
|
|
6347
|
+
input.mimeType,
|
|
6348
|
+
bytes.byteLength,
|
|
6349
|
+
createHash3("sha256").update(bytes).digest("hex"),
|
|
6350
|
+
input.imageModel ?? null,
|
|
6351
|
+
Date.now(),
|
|
6352
|
+
bytes
|
|
6353
|
+
]
|
|
6354
|
+
);
|
|
6355
|
+
return get17(db, id);
|
|
6356
|
+
})();
|
|
6357
|
+
}
|
|
6358
|
+
function whereClause(filter) {
|
|
6359
|
+
const where = [];
|
|
6360
|
+
const params = [];
|
|
6361
|
+
for (const [column, value] of [
|
|
6362
|
+
["team_id", filter.teamId],
|
|
6363
|
+
["agent_id", filter.agentId],
|
|
6364
|
+
["session_id", filter.sessionId]
|
|
6365
|
+
]) {
|
|
6366
|
+
if (value === void 0) continue;
|
|
6367
|
+
where.push(`${column} = ?`);
|
|
6368
|
+
params.push(value);
|
|
6369
|
+
}
|
|
6370
|
+
return { sql: where.length ? `WHERE ${where.join(" AND ")}` : "", params };
|
|
6371
|
+
}
|
|
6372
|
+
function list12(db, opts = {}) {
|
|
6373
|
+
const limit = Math.max(1, Math.min(100, Math.floor(opts.limit ?? 50)));
|
|
6374
|
+
const offset = Math.max(0, Math.floor(opts.offset ?? 0));
|
|
6375
|
+
const { sql: filter, params } = whereClause(opts);
|
|
6376
|
+
const total = db.raw.query(`SELECT count(*) AS total FROM agent_results ${filter}`).get(...params)?.total ?? 0;
|
|
6377
|
+
const results = db.raw.query(
|
|
6378
|
+
`SELECT ${columns2} FROM agent_results ${filter} ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?`
|
|
6379
|
+
).all(...params, limit, offset);
|
|
6380
|
+
return { results, total, limit, offset };
|
|
6381
|
+
}
|
|
6382
|
+
function read(db, id) {
|
|
6383
|
+
const row = db.raw.query(
|
|
6384
|
+
"SELECT bytes, sha256 FROM agent_results WHERE id = ?"
|
|
6385
|
+
).get(id);
|
|
6386
|
+
if (!row) throw new Error("Result not found");
|
|
6387
|
+
const bytes = Buffer.from(row.bytes);
|
|
6388
|
+
if (createHash3("sha256").update(bytes).digest("hex") !== row.sha256)
|
|
6389
|
+
throw new Error("Saved file failed its integrity check");
|
|
6390
|
+
return bytes;
|
|
6391
|
+
}
|
|
6392
|
+
function summaryByAgent(db) {
|
|
6393
|
+
const rows = db.raw.query(
|
|
6394
|
+
`SELECT agent_id AS agentId, count(*) AS count, max(created_at) AS lastAt
|
|
6395
|
+
FROM agent_results GROUP BY agent_id`
|
|
6396
|
+
).all();
|
|
6397
|
+
return new Map(rows.map((row) => [row.agentId, { count: row.count, lastAt: row.lastAt }]));
|
|
6398
|
+
}
|
|
6399
|
+
function listForArchive(db, filter, maxBytes) {
|
|
6400
|
+
const { sql, params } = whereClause(filter);
|
|
6401
|
+
const all = db.raw.query(
|
|
6402
|
+
// Oldest first; files saved in the same millisecond keep the order they were saved in.
|
|
6403
|
+
`SELECT ${columns2} FROM agent_results ${sql} ORDER BY created_at, rowid`
|
|
6404
|
+
).all(...params);
|
|
6405
|
+
const results = [];
|
|
6406
|
+
let bytes = 0;
|
|
6407
|
+
for (const result of all) {
|
|
6408
|
+
if (bytes + result.byteLength > maxBytes) return { results, truncated: true };
|
|
6409
|
+
bytes += result.byteLength;
|
|
6410
|
+
results.push(result);
|
|
6411
|
+
}
|
|
6412
|
+
return { results, truncated: false };
|
|
6413
|
+
}
|
|
6414
|
+
function remove10(db, id) {
|
|
6415
|
+
return db.raw.run("DELETE FROM agent_results WHERE id = ?", [id]).changes === 1;
|
|
6416
|
+
}
|
|
6417
|
+
|
|
6196
6418
|
// ../daemon/src/lib/agent-cancel.ts
|
|
6197
6419
|
var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("bazilion.agent-cancel.registry");
|
|
6198
6420
|
var AgentTurnActiveError = class extends DomainError {
|
|
@@ -6224,7 +6446,7 @@ function unregisterAgent(agentId) {
|
|
|
6224
6446
|
if (!state2.active.delete(agentId)) return;
|
|
6225
6447
|
const waiters = state2.idleWaiters.get(agentId);
|
|
6226
6448
|
state2.idleWaiters.delete(agentId);
|
|
6227
|
-
for (const
|
|
6449
|
+
for (const resolve9 of waiters ?? []) resolve9();
|
|
6228
6450
|
}
|
|
6229
6451
|
function cancelAgent(agentId) {
|
|
6230
6452
|
const { active } = registry();
|
|
@@ -6252,9 +6474,9 @@ function stopAgentTurns() {
|
|
|
6252
6474
|
function waitForAgentIdle(agentId) {
|
|
6253
6475
|
const state2 = registry();
|
|
6254
6476
|
if (!state2.active.has(agentId)) return Promise.resolve();
|
|
6255
|
-
return new Promise((
|
|
6477
|
+
return new Promise((resolve9) => {
|
|
6256
6478
|
const waiters = state2.idleWaiters.get(agentId) ?? /* @__PURE__ */ new Set();
|
|
6257
|
-
waiters.add(
|
|
6479
|
+
waiters.add(resolve9);
|
|
6258
6480
|
state2.idleWaiters.set(agentId, waiters);
|
|
6259
6481
|
});
|
|
6260
6482
|
}
|
|
@@ -6273,35 +6495,252 @@ function isShuttingDownError(error) {
|
|
|
6273
6495
|
return error instanceof Error && error.message === SHUTTING_DOWN;
|
|
6274
6496
|
}
|
|
6275
6497
|
|
|
6276
|
-
// ../daemon/src/lib/
|
|
6277
|
-
var
|
|
6278
|
-
|
|
6279
|
-
|
|
6280
|
-
|
|
6281
|
-
|
|
6282
|
-
|
|
6283
|
-
|
|
6284
|
-
|
|
6498
|
+
// ../daemon/src/lib/bash-approval.ts
|
|
6499
|
+
var DEFAULT_TIMEOUT_MS = 12e4;
|
|
6500
|
+
var CommandApprovalRegistry = class {
|
|
6501
|
+
#pending = /* @__PURE__ */ new Map();
|
|
6502
|
+
#timeoutMs;
|
|
6503
|
+
constructor(timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
6504
|
+
this.#timeoutMs = timeoutMs;
|
|
6505
|
+
}
|
|
6506
|
+
begin(input, signal) {
|
|
6507
|
+
const approval = {
|
|
6508
|
+
id: input.id,
|
|
6509
|
+
turnId: input.turnId,
|
|
6510
|
+
toolCallId: input.toolCallId,
|
|
6511
|
+
agentId: input.agentId,
|
|
6512
|
+
teamId: input.teamId,
|
|
6513
|
+
command: input.command,
|
|
6514
|
+
risks: input.risks,
|
|
6515
|
+
status: "pending",
|
|
6516
|
+
expiresAt: Date.now() + this.#timeoutMs
|
|
6517
|
+
};
|
|
6518
|
+
const immediate = input.mode === "auto_deny" ? "auto_denied" : signal?.aborted ? "cancelled" : void 0;
|
|
6519
|
+
if (immediate) {
|
|
6520
|
+
const settled2 = logged({ ...approval, status: immediate });
|
|
6521
|
+
return { approval: settled2, settled: Promise.resolve(settled2) };
|
|
6522
|
+
}
|
|
6523
|
+
if (this.#pending.has(approval.id))
|
|
6524
|
+
throw new Error(`duplicate shell approval id: ${approval.id}`);
|
|
6525
|
+
const settled = new Promise((resolve9) => {
|
|
6526
|
+
const settle = (status2) => {
|
|
6527
|
+
this.#pending.delete(approval.id);
|
|
6528
|
+
clearTimeout(timer);
|
|
6529
|
+
signal?.removeEventListener("abort", onAbort);
|
|
6530
|
+
const result = logged({ ...approval, status: status2 });
|
|
6531
|
+
resolve9(result);
|
|
6532
|
+
return result;
|
|
6533
|
+
};
|
|
6534
|
+
const onAbort = () => settle("cancelled");
|
|
6535
|
+
const timer = setTimeout(() => settle("expired"), this.#timeoutMs);
|
|
6536
|
+
timer.unref();
|
|
6537
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
6538
|
+
this.#pending.set(approval.id, { approval, settle });
|
|
6539
|
+
});
|
|
6540
|
+
return { approval, settled };
|
|
6541
|
+
}
|
|
6542
|
+
list(agentId) {
|
|
6543
|
+
return Array.from(this.#pending.values(), (entry) => entry.approval).filter((approval) => agentId === void 0 || approval.agentId === agentId).sort((a, b) => a.expiresAt - b.expiresAt || a.id.localeCompare(b.id));
|
|
6544
|
+
}
|
|
6545
|
+
/** Answer a pending approval; undefined when there is none (unknown, or already settled). */
|
|
6546
|
+
respond(id, decision) {
|
|
6547
|
+
return this.#pending.get(id)?.settle(decision === "allow" ? "allowed" : "denied");
|
|
6548
|
+
}
|
|
6549
|
+
};
|
|
6550
|
+
function logged(approval) {
|
|
6551
|
+
console.info("bash approval decision", {
|
|
6552
|
+
approvalId: approval.id,
|
|
6553
|
+
agentId: approval.agentId,
|
|
6554
|
+
teamId: approval.teamId,
|
|
6555
|
+
riskCodes: [...new Set(approval.risks.map((risk) => risk.code))],
|
|
6556
|
+
status: approval.status
|
|
6557
|
+
});
|
|
6558
|
+
return approval;
|
|
6285
6559
|
}
|
|
6286
|
-
|
|
6287
|
-
|
|
6560
|
+
var commandApprovalRegistry = new CommandApprovalRegistry();
|
|
6561
|
+
|
|
6562
|
+
// ../daemon/src/lib/questions.ts
|
|
6563
|
+
import { randomUUID as randomUUID14 } from "node:crypto";
|
|
6564
|
+
var QUESTION_WAIT_MS = 5 * 6e4;
|
|
6565
|
+
var QUESTION_LIMITS = Object.freeze({
|
|
6566
|
+
promptChars: 2e3,
|
|
6567
|
+
labelChars: 120,
|
|
6568
|
+
descriptionChars: 500,
|
|
6569
|
+
answerChars: 4096
|
|
6570
|
+
});
|
|
6571
|
+
function text(value, limit, what) {
|
|
6572
|
+
if (typeof value !== "string" || !value.trim()) throw new Error(`${what} must be non-empty text`);
|
|
6573
|
+
if (value.length > limit) throw new Error(`${what} is longer than ${limit} characters`);
|
|
6574
|
+
return value;
|
|
6288
6575
|
}
|
|
6289
|
-
function
|
|
6290
|
-
const
|
|
6291
|
-
const
|
|
6292
|
-
|
|
6293
|
-
|
|
6294
|
-
|
|
6295
|
-
|
|
6296
|
-
|
|
6297
|
-
|
|
6298
|
-
|
|
6299
|
-
|
|
6300
|
-
|
|
6576
|
+
function parseQuestionInput(value) {
|
|
6577
|
+
const input = value ?? {};
|
|
6578
|
+
const prompt = text(input.prompt, QUESTION_LIMITS.promptChars, "The prompt");
|
|
6579
|
+
if (!Array.isArray(input.choices) || input.choices.length < 2 || input.choices.length > 4)
|
|
6580
|
+
throw new Error("ask_user needs 2 to 4 choices");
|
|
6581
|
+
const labels = /* @__PURE__ */ new Set();
|
|
6582
|
+
const choices = input.choices.map((raw, index) => {
|
|
6583
|
+
const choice = raw ?? {};
|
|
6584
|
+
const label = text(choice.label, QUESTION_LIMITS.labelChars, `Choice ${index + 1} label`);
|
|
6585
|
+
const key2 = label.normalize("NFKC").trim().toLowerCase();
|
|
6586
|
+
if (labels.has(key2)) throw new Error("Choice labels must be distinct");
|
|
6587
|
+
labels.add(key2);
|
|
6588
|
+
if (choice.description === void 0) return { label };
|
|
6589
|
+
const description = text(
|
|
6590
|
+
choice.description,
|
|
6591
|
+
QUESTION_LIMITS.descriptionChars,
|
|
6592
|
+
`Choice ${index + 1} description`
|
|
6593
|
+
);
|
|
6594
|
+
return { label, description };
|
|
6595
|
+
});
|
|
6596
|
+
const recommended = input.recommendedIndex;
|
|
6597
|
+
if (recommended === void 0) return { prompt, choices };
|
|
6598
|
+
if (typeof recommended !== "number" || !Number.isInteger(recommended))
|
|
6599
|
+
throw new Error("recommendedIndex must be a choice index");
|
|
6600
|
+
if (recommended < 0 || recommended >= choices.length)
|
|
6601
|
+
throw new Error("recommendedIndex must be a choice index");
|
|
6602
|
+
return { prompt, choices, recommendedIndex: recommended };
|
|
6301
6603
|
}
|
|
6604
|
+
function parseQuestionAnswer(value, question) {
|
|
6605
|
+
const answer = value ?? {};
|
|
6606
|
+
if (answer.kind === "skip") return { kind: "skip" };
|
|
6607
|
+
if (answer.kind === "text")
|
|
6608
|
+
return { kind: "text", text: text(answer.text, QUESTION_LIMITS.answerChars, "The answer") };
|
|
6609
|
+
const index = answer.index;
|
|
6610
|
+
if (answer.kind === "choice" && typeof index === "number" && Number.isInteger(index)) {
|
|
6611
|
+
if (index >= 0 && index < question.choices.length) return { kind: "choice", index };
|
|
6612
|
+
throw new Error(
|
|
6613
|
+
`Choice ${index + 1} does not exist; this question has ${question.choices.length} choices`
|
|
6614
|
+
);
|
|
6615
|
+
}
|
|
6616
|
+
throw new Error("An answer is a choice index, text or skip");
|
|
6617
|
+
}
|
|
6618
|
+
var QuestionRegistry = class {
|
|
6619
|
+
#pending = /* @__PURE__ */ new Map();
|
|
6620
|
+
#waitMs;
|
|
6621
|
+
constructor(waitMs = QUESTION_WAIT_MS) {
|
|
6622
|
+
this.#waitMs = waitMs;
|
|
6623
|
+
}
|
|
6624
|
+
/** Register a question. `result` settles on the first answer, the timeout or `signal`. */
|
|
6625
|
+
ask(context, input, signal) {
|
|
6626
|
+
const prompt = parseQuestionInput(input);
|
|
6627
|
+
if (this.list(context.agentId).length > 0)
|
|
6628
|
+
throw new Error("Another question from this Agent is still waiting for an answer");
|
|
6629
|
+
if (signal?.aborted) throw new Error("The turn has ended");
|
|
6630
|
+
const now = Date.now();
|
|
6631
|
+
const question = {
|
|
6632
|
+
id: randomUUID14(),
|
|
6633
|
+
agentId: context.agentId,
|
|
6634
|
+
conversationId: context.conversationId,
|
|
6635
|
+
question: prompt,
|
|
6636
|
+
createdAt: now,
|
|
6637
|
+
expiresAt: now + this.#waitMs
|
|
6638
|
+
};
|
|
6639
|
+
const { promise, resolve: resolve9 } = Promise.withResolvers();
|
|
6640
|
+
const cancel3 = () => finish3({ kind: "no_answer", reason: "cancelled" });
|
|
6641
|
+
const timer = setTimeout(() => finish3({ kind: "no_answer", reason: "expired" }), this.#waitMs);
|
|
6642
|
+
timer.unref();
|
|
6643
|
+
const finish3 = (outcome) => {
|
|
6644
|
+
if (!this.#pending.delete(question.id)) return false;
|
|
6645
|
+
clearTimeout(timer);
|
|
6646
|
+
signal?.removeEventListener("abort", cancel3);
|
|
6647
|
+
resolve9({ questionId: question.id, question: prompt, ...outcome });
|
|
6648
|
+
return true;
|
|
6649
|
+
};
|
|
6650
|
+
this.#pending.set(question.id, { question, result: promise, finish: finish3 });
|
|
6651
|
+
signal?.addEventListener("abort", cancel3, { once: true });
|
|
6652
|
+
return { question, result: promise };
|
|
6653
|
+
}
|
|
6654
|
+
list(agentId) {
|
|
6655
|
+
return [...this.#pending.values()].map((entry) => entry.question).filter((question) => agentId === void 0 || question.agentId === agentId);
|
|
6656
|
+
}
|
|
6657
|
+
get(id) {
|
|
6658
|
+
return this.#pending.get(id)?.question;
|
|
6659
|
+
}
|
|
6660
|
+
/** The outcome of a waiting question; undefined once it has settled. */
|
|
6661
|
+
settled(id) {
|
|
6662
|
+
return this.#pending.get(id)?.result;
|
|
6663
|
+
}
|
|
6664
|
+
/** Answer a waiting question. False when it is no longer waiting; throws on an invalid answer. */
|
|
6665
|
+
answer(agentId, id, value) {
|
|
6666
|
+
const entry = this.#pending.get(id);
|
|
6667
|
+
if (!entry || entry.question.agentId !== agentId) return false;
|
|
6668
|
+
const answer = parseQuestionAnswer(value, entry.question.question);
|
|
6669
|
+
return entry.finish(
|
|
6670
|
+
answer.kind === "skip" ? { kind: "no_answer", reason: "skipped" } : { kind: "answer", answer }
|
|
6671
|
+
);
|
|
6672
|
+
}
|
|
6673
|
+
};
|
|
6674
|
+
var questionRegistry = new QuestionRegistry();
|
|
6302
6675
|
|
|
6303
|
-
// ../daemon/src/
|
|
6304
|
-
|
|
6676
|
+
// ../daemon/src/lib/activity.ts
|
|
6677
|
+
var TARGET_CHARS = 160;
|
|
6678
|
+
var TARGET_KEYS = ["path", "command", "url", "query", "to", "key", "file"];
|
|
6679
|
+
var STEPS_KEY = /* @__PURE__ */ Symbol.for("bazilion.activity.steps");
|
|
6680
|
+
function steps() {
|
|
6681
|
+
const holder = globalThis;
|
|
6682
|
+
let map = holder[STEPS_KEY];
|
|
6683
|
+
if (!map) {
|
|
6684
|
+
map = /* @__PURE__ */ new Map();
|
|
6685
|
+
holder[STEPS_KEY] = map;
|
|
6686
|
+
}
|
|
6687
|
+
return map;
|
|
6688
|
+
}
|
|
6689
|
+
function stepTarget(rawArguments) {
|
|
6690
|
+
let args;
|
|
6691
|
+
try {
|
|
6692
|
+
args = JSON.parse(rawArguments);
|
|
6693
|
+
} catch {
|
|
6694
|
+
return null;
|
|
6695
|
+
}
|
|
6696
|
+
if (!args || typeof args !== "object") return null;
|
|
6697
|
+
for (const key2 of TARGET_KEYS) {
|
|
6698
|
+
const value = args[key2];
|
|
6699
|
+
if (typeof value === "string" && value.trim()) {
|
|
6700
|
+
const line = value.trim().split("\n")[0] ?? "";
|
|
6701
|
+
return line.length > TARGET_CHARS ? `${line.slice(0, TARGET_CHARS - 1)}\u2026` : line;
|
|
6702
|
+
}
|
|
6703
|
+
}
|
|
6704
|
+
return null;
|
|
6705
|
+
}
|
|
6706
|
+
function noteTurnFrame(agentId, frame) {
|
|
6707
|
+
if (frame.kind !== "event" || frame.event.type !== "tool_call") return;
|
|
6708
|
+
steps().set(agentId, { tool: frame.event.name, target: stepTarget(frame.event.arguments) });
|
|
6709
|
+
}
|
|
6710
|
+
function noteTurnEnd(agentId) {
|
|
6711
|
+
steps().delete(agentId);
|
|
6712
|
+
}
|
|
6713
|
+
function lastActivityAt(db, paths, agentId) {
|
|
6714
|
+
const conversationId = selectedId(db, agentId);
|
|
6715
|
+
if (!conversationId) return null;
|
|
6716
|
+
try {
|
|
6717
|
+
const file = join10(paths.agentDir(agentId), "sessions", `${conversationId}.jsonl`);
|
|
6718
|
+
return Math.floor(statSync3(file).mtimeMs);
|
|
6719
|
+
} catch {
|
|
6720
|
+
return null;
|
|
6721
|
+
}
|
|
6722
|
+
}
|
|
6723
|
+
function readActivity(db, paths) {
|
|
6724
|
+
const saved = summaryByAgent(db);
|
|
6725
|
+
const questions = questionRegistry.list();
|
|
6726
|
+
const approvals = commandApprovalRegistry.list();
|
|
6727
|
+
return list(db).map((agent) => {
|
|
6728
|
+
const working = isActiveAgent(agent.id);
|
|
6729
|
+
const produced = saved.get(agent.id);
|
|
6730
|
+
return {
|
|
6731
|
+
agentId: agent.id,
|
|
6732
|
+
teamId: agent.teamId,
|
|
6733
|
+
working,
|
|
6734
|
+
step: working ? steps().get(agent.id) ?? null : null,
|
|
6735
|
+
questions: questions.filter((question) => question.agentId === agent.id).length,
|
|
6736
|
+
approvals: approvals.filter((approval) => approval.agentId === agent.id).length,
|
|
6737
|
+
queuePaused: isPaused(db, agent.id) && pendingCount(db, agent.id) > 0,
|
|
6738
|
+
lastActivityAt: lastActivityAt(db, paths, agent.id),
|
|
6739
|
+
results: produced?.count ?? 0,
|
|
6740
|
+
lastResultAt: produced?.lastAt ?? null
|
|
6741
|
+
};
|
|
6742
|
+
});
|
|
6743
|
+
}
|
|
6305
6744
|
|
|
6306
6745
|
// ../daemon/src/routes/http.ts
|
|
6307
6746
|
import { Hono } from "hono";
|
|
@@ -6344,7 +6783,42 @@ async function jsonBody(c) {
|
|
|
6344
6783
|
return body !== null && typeof body === "object" && !Array.isArray(body) ? body : null;
|
|
6345
6784
|
}
|
|
6346
6785
|
|
|
6786
|
+
// ../daemon/src/routes/activity.ts
|
|
6787
|
+
var activityRouter = newRouter();
|
|
6788
|
+
activityRouter.get("/", (c) => {
|
|
6789
|
+
const { db, paths } = getCtx();
|
|
6790
|
+
return c.json({ agents: readActivity(db, paths) });
|
|
6791
|
+
});
|
|
6792
|
+
|
|
6793
|
+
// ../daemon/src/lib/browser/config.ts
|
|
6794
|
+
var FALSEY = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
|
|
6795
|
+
function envBool(value, fallback) {
|
|
6796
|
+
if (value === void 0 || value.trim() === "") return fallback;
|
|
6797
|
+
return !FALSEY.has(value.trim().toLowerCase());
|
|
6798
|
+
}
|
|
6799
|
+
function envInt(value, fallback) {
|
|
6800
|
+
const n = Number.parseInt(value ?? "", 10);
|
|
6801
|
+
return Number.isFinite(n) && n > 0 ? n : fallback;
|
|
6802
|
+
}
|
|
6803
|
+
function isBrowserEnabled(env) {
|
|
6804
|
+
return envBool(env.BROWSER_ENABLED, true);
|
|
6805
|
+
}
|
|
6806
|
+
function resolveBrowserConfig(env) {
|
|
6807
|
+
const executablePath = env.BROWSER_EXECUTABLE_PATH?.trim();
|
|
6808
|
+
const attachUrl = env.BROWSER_ATTACH_URL?.trim();
|
|
6809
|
+
return {
|
|
6810
|
+
headless: envBool(env.BROWSER_HEADLESS, true),
|
|
6811
|
+
...executablePath ? { executablePath } : {},
|
|
6812
|
+
allowPrivate: envBool(env.BROWSER_ALLOW_PRIVATE_NETWORK, false),
|
|
6813
|
+
attach: envBool(env.BROWSER_ATTACH, false),
|
|
6814
|
+
...attachUrl ? { attachUrl } : {},
|
|
6815
|
+
idleMs: envInt(env.BROWSER_IDLE_MS, 9e5),
|
|
6816
|
+
maxSessions: envInt(env.BROWSER_MAX_SESSIONS, 4)
|
|
6817
|
+
};
|
|
6818
|
+
}
|
|
6819
|
+
|
|
6347
6820
|
// ../daemon/src/routes/agent-browser.ts
|
|
6821
|
+
init_pool2();
|
|
6348
6822
|
var agentBrowserRouter = newRouter();
|
|
6349
6823
|
agentBrowserRouter.get("/:id/browser", (c) => {
|
|
6350
6824
|
const { db, paths, authToken } = getCtx();
|
|
@@ -6366,72 +6840,7 @@ agentBrowserRouter.delete("/:id/browser/profile", async (c) => {
|
|
|
6366
6840
|
// ../daemon/src/routes/agent-chat.ts
|
|
6367
6841
|
import { randomUUID as randomUUID19 } from "node:crypto";
|
|
6368
6842
|
import { existsSync as existsSync16, readFileSync as readFileSync10 } from "node:fs";
|
|
6369
|
-
import { join as
|
|
6370
|
-
|
|
6371
|
-
// ../daemon/src/core/repos/conversations.ts
|
|
6372
|
-
var columns = "id, agent_id AS agentId, title, created_at AS createdAt, updated_at AS updatedAt";
|
|
6373
|
-
var ConversationChangedError = class extends DomainError {
|
|
6374
|
-
constructor() {
|
|
6375
|
-
super(409, "The Agent switched to another conversation. Reload before trying again.");
|
|
6376
|
-
}
|
|
6377
|
-
};
|
|
6378
|
-
function selectedId(db, agentId) {
|
|
6379
|
-
return db.raw.query(
|
|
6380
|
-
"SELECT conversation_id AS id FROM agent_conversation_selection WHERE agent_id = ?"
|
|
6381
|
-
).get(agentId)?.id ?? null;
|
|
6382
|
-
}
|
|
6383
|
-
function get16(db, agentId, id) {
|
|
6384
|
-
return db.raw.query(
|
|
6385
|
-
`SELECT ${columns} FROM agent_conversations WHERE agent_id = ? AND id = ?`
|
|
6386
|
-
).get(agentId, id);
|
|
6387
|
-
}
|
|
6388
|
-
function list11(db, agentId, limit = 20, offset = 0) {
|
|
6389
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !Number.isSafeInteger(offset) || offset < 0)
|
|
6390
|
-
throw new DomainError(400, "Invalid conversation pagination");
|
|
6391
|
-
const conversations = db.raw.query(
|
|
6392
|
-
`SELECT ${columns} FROM agent_conversations WHERE agent_id = ? ORDER BY created_at DESC, id LIMIT ? OFFSET ?`
|
|
6393
|
-
).all(agentId, limit, offset);
|
|
6394
|
-
const total = db.raw.query(
|
|
6395
|
-
"SELECT COUNT(*) AS n FROM agent_conversations WHERE agent_id = ?"
|
|
6396
|
-
).get(agentId)?.n ?? 0;
|
|
6397
|
-
return { conversations, selectedId: selectedId(db, agentId), total, offset, limit };
|
|
6398
|
-
}
|
|
6399
|
-
function validTitle(value) {
|
|
6400
|
-
if (typeof value !== "string" || !value.trim() || value.length > 200 || Array.from(value).some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127))
|
|
6401
|
-
throw new DomainError(
|
|
6402
|
-
400,
|
|
6403
|
-
"Conversation title must be 1\u2013200 characters without control characters"
|
|
6404
|
-
);
|
|
6405
|
-
return value.trim();
|
|
6406
|
-
}
|
|
6407
|
-
function create5(db, agentId, id, title) {
|
|
6408
|
-
const displayTitle = title === void 0 ? void 0 : validTitle(title);
|
|
6409
|
-
return db.raw.transaction(() => {
|
|
6410
|
-
const now = Date.now();
|
|
6411
|
-
db.raw.run(
|
|
6412
|
-
`INSERT INTO agent_conversations (id, agent_id, title, created_at, updated_at)
|
|
6413
|
-
VALUES (?, ?, ?, ?, ?)`,
|
|
6414
|
-
[id, agentId, displayTitle ?? `Conversation ${list11(db, agentId, 1).total + 1}`, now, now]
|
|
6415
|
-
);
|
|
6416
|
-
db.raw.run(
|
|
6417
|
-
`INSERT INTO agent_conversation_selection (agent_id, conversation_id) VALUES (?, ?)
|
|
6418
|
-
ON CONFLICT(agent_id) DO UPDATE SET conversation_id = excluded.conversation_id`,
|
|
6419
|
-
[agentId, id]
|
|
6420
|
-
);
|
|
6421
|
-
const conversation = get16(db, agentId, id);
|
|
6422
|
-
if (!conversation) throw new Error("Conversation not found");
|
|
6423
|
-
return conversation;
|
|
6424
|
-
})();
|
|
6425
|
-
}
|
|
6426
|
-
function rename(db, agentId, id, title) {
|
|
6427
|
-
db.raw.run(
|
|
6428
|
-
"UPDATE agent_conversations SET title = ?, updated_at = ? WHERE agent_id = ? AND id = ?",
|
|
6429
|
-
[validTitle(title), Date.now(), agentId, id]
|
|
6430
|
-
);
|
|
6431
|
-
const conversation = get16(db, agentId, id);
|
|
6432
|
-
if (!conversation) throw new DomainError(404, "Conversation not found");
|
|
6433
|
-
return conversation;
|
|
6434
|
-
}
|
|
6843
|
+
import { join as join27 } from "node:path";
|
|
6435
6844
|
|
|
6436
6845
|
// ../daemon/src/runtime/auth/openai-codex.ts
|
|
6437
6846
|
import { openaiCodexProvider } from "@earendil-works/pi-ai/providers/openai-codex";
|
|
@@ -6563,7 +6972,7 @@ import {
|
|
|
6563
6972
|
rmSync as rmSync9,
|
|
6564
6973
|
writeFileSync as writeFileSync5
|
|
6565
6974
|
} from "node:fs";
|
|
6566
|
-
import { dirname as dirname4, isAbsolute as isAbsolute2, join as
|
|
6975
|
+
import { dirname as dirname4, isAbsolute as isAbsolute2, join as join15, relative, resolve as resolve4, sep as sep2 } from "node:path";
|
|
6567
6976
|
import { createStore, extractSnippet } from "@tobilu/qmd";
|
|
6568
6977
|
|
|
6569
6978
|
// ../daemon/src/lib/native-module-error.ts
|
|
@@ -6609,7 +7018,7 @@ function getStore(dir, storeFactory) {
|
|
|
6609
7018
|
if (!p) {
|
|
6610
7019
|
p = withNativeModuleErrorBoundary(
|
|
6611
7020
|
() => storeFactory({
|
|
6612
|
-
dbPath:
|
|
7021
|
+
dbPath: join15(dir, INDEX_FILENAME),
|
|
6613
7022
|
config: {
|
|
6614
7023
|
collections: {
|
|
6615
7024
|
[COLLECTION_NAME]: { path: dir, pattern: PATTERN }
|
|
@@ -6687,7 +7096,7 @@ function inspectSafePath(root, path) {
|
|
|
6687
7096
|
let current2 = root;
|
|
6688
7097
|
const components = rel.split(sep2).filter(Boolean);
|
|
6689
7098
|
for (let index = 0; index < components.length; index += 1) {
|
|
6690
|
-
current2 =
|
|
7099
|
+
current2 = join15(current2, components[index]);
|
|
6691
7100
|
const info = lstatIfPresent(current2);
|
|
6692
7101
|
if (!info) return void 0;
|
|
6693
7102
|
if (info.isSymbolicLink()) {
|
|
@@ -6706,7 +7115,7 @@ function ensureSafeParentDirectories(root, path) {
|
|
|
6706
7115
|
const rel = relative(root, parent);
|
|
6707
7116
|
let current2 = root;
|
|
6708
7117
|
for (const component2 of rel.split(sep2).filter(Boolean)) {
|
|
6709
|
-
current2 =
|
|
7118
|
+
current2 = join15(current2, component2);
|
|
6710
7119
|
let info = lstatIfPresent(current2);
|
|
6711
7120
|
if (!info) {
|
|
6712
7121
|
mkdirSync6(current2);
|
|
@@ -6772,7 +7181,7 @@ function writeSafeFile(root, path, content) {
|
|
|
6772
7181
|
function assertSafeTree(root, dir = root) {
|
|
6773
7182
|
assertContained(root, realpathSync2(dir));
|
|
6774
7183
|
for (const entry of readdirSync4(dir, { withFileTypes: true })) {
|
|
6775
|
-
const full =
|
|
7184
|
+
const full = join15(dir, entry.name);
|
|
6776
7185
|
const info = lstatSync(full);
|
|
6777
7186
|
if (info.isSymbolicLink()) {
|
|
6778
7187
|
throw unsafeMemoryPath(full, "symbolic links are not allowed in memory storage");
|
|
@@ -6786,7 +7195,7 @@ function assertSafeTree(root, dir = root) {
|
|
|
6786
7195
|
}
|
|
6787
7196
|
function walkMd(root, dir, prefix, out) {
|
|
6788
7197
|
for (const entry of readdirSync4(dir, { withFileTypes: true })) {
|
|
6789
|
-
const full =
|
|
7198
|
+
const full = join15(dir, entry.name);
|
|
6790
7199
|
const info = lstatSync(full);
|
|
6791
7200
|
if (info.isSymbolicLink()) {
|
|
6792
7201
|
throw unsafeMemoryPath(full, "symbolic links are not allowed in memory storage");
|
|
@@ -6893,17 +7302,17 @@ function qmdBackend(root, options = {}) {
|
|
|
6893
7302
|
// ../daemon/src/runtime/worker/runtime.ts
|
|
6894
7303
|
import { mkdirSync as mkdirSync7, mkdtempSync as mkdtempSync2, rmSync as rmSync10 } from "node:fs";
|
|
6895
7304
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
6896
|
-
import { join as
|
|
7305
|
+
import { join as join16 } from "node:path";
|
|
6897
7306
|
var REDACTED_VALUE = "[REDACTED]";
|
|
6898
7307
|
function createMinimalWorkerScratch(parentDir = tmpdir2()) {
|
|
6899
|
-
const root = mkdtempSync2(
|
|
7308
|
+
const root = mkdtempSync2(join16(parentDir, "bazilion-worker-"));
|
|
6900
7309
|
const scratch = {
|
|
6901
7310
|
root,
|
|
6902
|
-
homeDir:
|
|
6903
|
-
tempDir:
|
|
6904
|
-
piAgentDir:
|
|
6905
|
-
reviewCwd:
|
|
6906
|
-
reviewSessionDir:
|
|
7311
|
+
homeDir: join16(root, "home"),
|
|
7312
|
+
tempDir: join16(root, "tmp"),
|
|
7313
|
+
piAgentDir: join16(root, "pi"),
|
|
7314
|
+
reviewCwd: join16(root, "review-work"),
|
|
7315
|
+
reviewSessionDir: join16(root, "review-session")
|
|
6907
7316
|
};
|
|
6908
7317
|
try {
|
|
6909
7318
|
for (const path of Object.values(scratch).slice(1)) {
|
|
@@ -7121,8 +7530,8 @@ function extractResultReferences(value) {
|
|
|
7121
7530
|
}
|
|
7122
7531
|
|
|
7123
7532
|
// ../daemon/src/runtime/pi/session.ts
|
|
7124
|
-
import { existsSync as existsSync14, mkdirSync as mkdirSync10, statSync as
|
|
7125
|
-
import { basename as basename5, join as
|
|
7533
|
+
import { existsSync as existsSync14, mkdirSync as mkdirSync10, statSync as statSync7, writeFileSync as writeFileSync7 } from "node:fs";
|
|
7534
|
+
import { basename as basename5, join as join22 } from "node:path";
|
|
7126
7535
|
import {
|
|
7127
7536
|
buildSessionContext,
|
|
7128
7537
|
createAgentSession,
|
|
@@ -7226,7 +7635,7 @@ async function testProviderModel(spec) {
|
|
|
7226
7635
|
|
|
7227
7636
|
// ../daemon/src/runtime/session/prompt.ts
|
|
7228
7637
|
import { existsSync as existsSync11, readdirSync as readdirSync5 } from "node:fs";
|
|
7229
|
-
import { join as
|
|
7638
|
+
import { join as join17 } from "node:path";
|
|
7230
7639
|
|
|
7231
7640
|
// ../daemon/src/runtime/safe-files.ts
|
|
7232
7641
|
import {
|
|
@@ -7240,7 +7649,7 @@ import {
|
|
|
7240
7649
|
readlinkSync as readlinkSync2,
|
|
7241
7650
|
readSync,
|
|
7242
7651
|
realpathSync as realpathSync3,
|
|
7243
|
-
statSync as
|
|
7652
|
+
statSync as statSync5
|
|
7244
7653
|
} from "node:fs";
|
|
7245
7654
|
import { dirname as dirname5, isAbsolute as isAbsolute3, relative as relative2, resolve as resolve5, sep as sep3 } from "node:path";
|
|
7246
7655
|
var ContainedFileError = class extends Error {
|
|
@@ -7254,7 +7663,7 @@ var ContainedFileError = class extends Error {
|
|
|
7254
7663
|
function readContainedFile(path, realRoot, maxBytes) {
|
|
7255
7664
|
const real = realpathSync3(path);
|
|
7256
7665
|
if (!isContained2(realRoot, real)) throw new ContainedFileError("outside");
|
|
7257
|
-
const checked =
|
|
7666
|
+
const checked = statSync5(real);
|
|
7258
7667
|
if (!checked.isFile()) throw new ContainedFileError("not_file");
|
|
7259
7668
|
if (checked.size > maxBytes) throw new ContainedFileError("too_large");
|
|
7260
7669
|
const fd = openSync2(real, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
|
|
@@ -7372,9 +7781,9 @@ function loadPromptSkills(skillsDir, attachedNames) {
|
|
|
7372
7781
|
const discovered = readdirSync5(skillsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && attached.has(entry.name)).sort((a, b) => a.name.localeCompare(b.name));
|
|
7373
7782
|
const loaded = [];
|
|
7374
7783
|
for (const entry of discovered) {
|
|
7375
|
-
const hostDir =
|
|
7784
|
+
const hostDir = join17(skillsDir, entry.name);
|
|
7376
7785
|
try {
|
|
7377
|
-
const parsed = parseSkillContent(readRegularFileNoFollow(
|
|
7786
|
+
const parsed = parseSkillContent(readRegularFileNoFollow(join17(hostDir, "SKILL.md")));
|
|
7378
7787
|
const safeLabel = entry.name.replace(/[^A-Za-z0-9._-]/g, "_") || "skill";
|
|
7379
7788
|
loaded.push({
|
|
7380
7789
|
name: entry.name,
|
|
@@ -7393,7 +7802,7 @@ function loadHomeDocuments(agentDir2) {
|
|
|
7393
7802
|
const root = resolveRealDirectory(agentDir2);
|
|
7394
7803
|
const read2 = (file) => {
|
|
7395
7804
|
try {
|
|
7396
|
-
return readRegularFileNoFollow(
|
|
7805
|
+
return readRegularFileNoFollow(join17(root, file));
|
|
7397
7806
|
} catch (error) {
|
|
7398
7807
|
if (error.code === "ENOENT") return null;
|
|
7399
7808
|
throw new Error(`private Agent home is unsafe at ${file}`);
|
|
@@ -7563,7 +7972,7 @@ function boundReviewedLessons(lessons, maxCharacters = 8e3) {
|
|
|
7563
7972
|
|
|
7564
7973
|
// ../daemon/src/runtime/shell/docker.ts
|
|
7565
7974
|
import { spawn as spawn3 } from "node:child_process";
|
|
7566
|
-
import { createHash as
|
|
7975
|
+
import { createHash as createHash4, randomUUID as randomUUID15 } from "node:crypto";
|
|
7567
7976
|
var CONTAINER_WORKSPACE = "/workspace";
|
|
7568
7977
|
var DOCKER_CALL_TIMEOUT_MS = 5e3;
|
|
7569
7978
|
var MAX_TIMER_MS = 2147483647;
|
|
@@ -7626,9 +8035,9 @@ function createDockerBashOperations(sandbox) {
|
|
|
7626
8035
|
throw new Error("Invalid timeout: must be a positive number of seconds");
|
|
7627
8036
|
if (signal?.aborted) throw new Error("aborted");
|
|
7628
8037
|
const current2 = sandbox();
|
|
7629
|
-
const name = `${current2.containerPrefix}${
|
|
8038
|
+
const name = `${current2.containerPrefix}${randomUUID15().replaceAll("-", "").slice(0, 12)}`;
|
|
7630
8039
|
const args = dockerRunArgs(current2, name, command);
|
|
7631
|
-
return new Promise((
|
|
8040
|
+
return new Promise((resolve9, reject2) => {
|
|
7632
8041
|
const child = spawn3("docker", args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
7633
8042
|
let stopped;
|
|
7634
8043
|
let settled = false;
|
|
@@ -7651,7 +8060,7 @@ function createDockerBashOperations(sandbox) {
|
|
|
7651
8060
|
await removeContainers([name]);
|
|
7652
8061
|
reject2(stopped);
|
|
7653
8062
|
} else if (error) reject2(dockerError(error));
|
|
7654
|
-
else
|
|
8063
|
+
else resolve9({ exitCode });
|
|
7655
8064
|
};
|
|
7656
8065
|
child.stdout.on("data", onData);
|
|
7657
8066
|
child.stderr.on("data", onData);
|
|
@@ -7670,10 +8079,10 @@ async function checkDockerImage(image) {
|
|
|
7670
8079
|
}
|
|
7671
8080
|
}
|
|
7672
8081
|
function homeContainerPrefix(home) {
|
|
7673
|
-
return `bazilion-${
|
|
8082
|
+
return `bazilion-${createHash4("sha256").update(home).digest("hex").slice(0, 12)}-`;
|
|
7674
8083
|
}
|
|
7675
8084
|
function turnContainerPrefix(home) {
|
|
7676
|
-
return `${homeContainerPrefix(home)}${
|
|
8085
|
+
return `${homeContainerPrefix(home)}${randomUUID15().replaceAll("-", "").slice(0, 12)}-`;
|
|
7677
8086
|
}
|
|
7678
8087
|
async function removeDockerContainers(prefix) {
|
|
7679
8088
|
try {
|
|
@@ -7697,7 +8106,7 @@ async function removeContainers(names) {
|
|
|
7697
8106
|
});
|
|
7698
8107
|
}
|
|
7699
8108
|
function docker(args) {
|
|
7700
|
-
return new Promise((
|
|
8109
|
+
return new Promise((resolve9, reject2) => {
|
|
7701
8110
|
const child = spawn3("docker", args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
7702
8111
|
let stdout = "";
|
|
7703
8112
|
let stderr = "";
|
|
@@ -7717,7 +8126,7 @@ function docker(args) {
|
|
|
7717
8126
|
});
|
|
7718
8127
|
child.once("close", (code) => {
|
|
7719
8128
|
clearTimeout(timer);
|
|
7720
|
-
if (code === 0)
|
|
8129
|
+
if (code === 0) resolve9(stdout.trim());
|
|
7721
8130
|
else reject2(new Error(stderr.trim() || `docker ${args[0]} exited with status ${code}`));
|
|
7722
8131
|
});
|
|
7723
8132
|
});
|
|
@@ -7727,8 +8136,8 @@ function dockerError(error) {
|
|
|
7727
8136
|
}
|
|
7728
8137
|
|
|
7729
8138
|
// ../daemon/src/runtime/shell/tooling.ts
|
|
7730
|
-
import { existsSync as existsSync12, lstatSync as lstatSync3, mkdirSync as mkdirSync9, realpathSync as realpathSync4, statSync as
|
|
7731
|
-
import { dirname as dirname6, isAbsolute as isAbsolute4, join as
|
|
8139
|
+
import { existsSync as existsSync12, lstatSync as lstatSync3, mkdirSync as mkdirSync9, realpathSync as realpathSync4, statSync as statSync6 } from "node:fs";
|
|
8140
|
+
import { dirname as dirname6, isAbsolute as isAbsolute4, join as join18, relative as relative3, sep as sep4 } from "node:path";
|
|
7732
8141
|
import {
|
|
7733
8142
|
createBashToolDefinition,
|
|
7734
8143
|
createLocalBashOperations,
|
|
@@ -8050,15 +8459,15 @@ function createSessionShellTools(cwd, env, options = {}) {
|
|
|
8050
8459
|
};
|
|
8051
8460
|
const sandbox = () => {
|
|
8052
8461
|
const workspace = realpathSync4(cwd);
|
|
8053
|
-
if (turn.cwd !== "." && !
|
|
8462
|
+
if (turn.cwd !== "." && !statSync6(join18(workspace, turn.cwd), { throwIfNoEntry: false })?.isDirectory())
|
|
8054
8463
|
throw new Error(`Working directory does not exist: ${containerWorkdir(turn.cwd)}`);
|
|
8055
|
-
mkdirSync9(
|
|
8464
|
+
mkdirSync9(join18(workspace, "memory"), { recursive: true });
|
|
8056
8465
|
return {
|
|
8057
8466
|
image: turn.image,
|
|
8058
8467
|
workspace,
|
|
8059
8468
|
workdir: containerWorkdir(turn.cwd),
|
|
8060
8469
|
readOnlyMounts: [
|
|
8061
|
-
readOnlyMount(
|
|
8470
|
+
readOnlyMount(join18(workspace, "memory"), SANDBOX_MEMORY_DIR, workspace),
|
|
8062
8471
|
...options.inputsDir && existsSync12(options.inputsDir) ? [readOnlyMount(options.inputsDir, SANDBOX_INPUTS_DIR, dirname6(options.inputsDir))] : [],
|
|
8063
8472
|
...(options.skillMounts ?? []).map(
|
|
8064
8473
|
(mount) => readOnlyMount(mount.source, mount.target, dirname6(mount.source))
|
|
@@ -8094,13 +8503,13 @@ function readOnlyMount(source, target, root) {
|
|
|
8094
8503
|
|
|
8095
8504
|
// ../daemon/src/runtime/pi/session-file.ts
|
|
8096
8505
|
import { closeSync as closeSync3, constants as constants4, fstatSync as fstatSync3, openSync as openSync3, readSync as readSync2 } from "node:fs";
|
|
8097
|
-
import { join as
|
|
8506
|
+
import { join as join19 } from "node:path";
|
|
8098
8507
|
var MAX_SESSION_BYTES = 64 * 1024 * 1024;
|
|
8099
8508
|
var MAX_HEADER_BYTES = 64 * 1024;
|
|
8100
8509
|
function readStart(directory, id, limit) {
|
|
8101
8510
|
if (!/^[0-9a-f-]{36}$/i.test(id)) throw new Error("Invalid conversation id");
|
|
8102
8511
|
const fd = openSync3(
|
|
8103
|
-
|
|
8512
|
+
join19(directory, `${id}.jsonl`),
|
|
8104
8513
|
constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK
|
|
8105
8514
|
);
|
|
8106
8515
|
try {
|
|
@@ -8130,6 +8539,13 @@ function readSessionFile(directory, id) {
|
|
|
8130
8539
|
checkHeader(entries[0], id);
|
|
8131
8540
|
return entries;
|
|
8132
8541
|
}
|
|
8542
|
+
function sessionHasEntries(directory, id) {
|
|
8543
|
+
const { bytes, size } = readStart(directory, id, MAX_HEADER_BYTES);
|
|
8544
|
+
if (size > bytes.length) return true;
|
|
8545
|
+
const text4 = bytes.toString("utf8");
|
|
8546
|
+
const end = text4.indexOf("\n");
|
|
8547
|
+
return end >= 0 && text4.slice(end + 1).trim().length > 0;
|
|
8548
|
+
}
|
|
8133
8549
|
function readSessionHeader(directory, id) {
|
|
8134
8550
|
const text4 = readStart(directory, id, MAX_HEADER_BYTES).bytes.toString("utf8");
|
|
8135
8551
|
const end = text4.indexOf("\n");
|
|
@@ -8178,7 +8594,7 @@ function askUserTool(ask) {
|
|
|
8178
8594
|
|
|
8179
8595
|
// ../daemon/src/runtime/tools/bootstrap.ts
|
|
8180
8596
|
import { existsSync as existsSync13, rmSync as rmSync11 } from "node:fs";
|
|
8181
|
-
import { join as
|
|
8597
|
+
import { join as join20 } from "node:path";
|
|
8182
8598
|
function bootstrapTool(agentDir2) {
|
|
8183
8599
|
return {
|
|
8184
8600
|
def: {
|
|
@@ -8187,7 +8603,7 @@ function bootstrapTool(agentDir2) {
|
|
|
8187
8603
|
parameters: { type: "object", properties: {} }
|
|
8188
8604
|
},
|
|
8189
8605
|
async invoke() {
|
|
8190
|
-
const path =
|
|
8606
|
+
const path = join20(agentDir2, "BOOTSTRAP.md");
|
|
8191
8607
|
if (existsSync13(path)) {
|
|
8192
8608
|
rmSync11(path);
|
|
8193
8609
|
return "BOOTSTRAP.md removed. Bootstrap is complete.";
|
|
@@ -8320,10 +8736,10 @@ function isWithin(root, candidate) {
|
|
|
8320
8736
|
return rel === "" || rel !== ".." && !rel.startsWith(`..${sep5}`) && !isAbsolute5(rel);
|
|
8321
8737
|
}
|
|
8322
8738
|
function deliverFileTool(cwd, sink) {
|
|
8323
|
-
const
|
|
8739
|
+
const workspacePath2 = resolve6(cwd);
|
|
8324
8740
|
let workspaceRealPath = null;
|
|
8325
8741
|
try {
|
|
8326
|
-
workspaceRealPath = realpathSync5(
|
|
8742
|
+
workspaceRealPath = realpathSync5(workspacePath2);
|
|
8327
8743
|
} catch {
|
|
8328
8744
|
}
|
|
8329
8745
|
return {
|
|
@@ -8348,8 +8764,8 @@ function deliverFileTool(cwd, sink) {
|
|
|
8348
8764
|
if (isAbsolute5(p)) {
|
|
8349
8765
|
throw new Error(`deliver_file: path must stay within the workspace: ${p}`);
|
|
8350
8766
|
}
|
|
8351
|
-
const abs = resolve6(
|
|
8352
|
-
if (!isWithin(
|
|
8767
|
+
const abs = resolve6(workspacePath2, p);
|
|
8768
|
+
if (!isWithin(workspacePath2, abs)) {
|
|
8353
8769
|
throw new Error(`deliver_file: path must stay within the workspace: ${p}`);
|
|
8354
8770
|
}
|
|
8355
8771
|
if (!workspaceRealPath) {
|
|
@@ -8387,7 +8803,7 @@ import {
|
|
|
8387
8803
|
readdirSync as readdirSync6,
|
|
8388
8804
|
writeFileSync as writeFileSync6
|
|
8389
8805
|
} from "node:fs";
|
|
8390
|
-
import { join as
|
|
8806
|
+
import { join as join21 } from "node:path";
|
|
8391
8807
|
var HOME_FILES_READABLE = [
|
|
8392
8808
|
"IDENTITY.md",
|
|
8393
8809
|
"SOUL.md",
|
|
@@ -8508,7 +8924,7 @@ function resolvePrivateHomeRoot(agentDir2) {
|
|
|
8508
8924
|
}
|
|
8509
8925
|
}
|
|
8510
8926
|
function privateHomeFile(homeRoot, file) {
|
|
8511
|
-
return
|
|
8927
|
+
return join21(homeRoot, file);
|
|
8512
8928
|
}
|
|
8513
8929
|
function rejectSymlinkOrNonFile(path) {
|
|
8514
8930
|
const entry = lstatSync4(path);
|
|
@@ -8916,7 +9332,7 @@ var DEFAULT_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7_2) AppleWe
|
|
|
8916
9332
|
var DEFAULT_CACHE_TTL_MS = 15 * 6e4;
|
|
8917
9333
|
var DEFAULT_CACHE_MAX = 100;
|
|
8918
9334
|
var DEFAULT_MAX_LENGTH = 2e4;
|
|
8919
|
-
var
|
|
9335
|
+
var DEFAULT_TIMEOUT_MS2 = 3e4;
|
|
8920
9336
|
var DEFAULT_MAX_BODY_BYTES = 3 * 1024 * 1024;
|
|
8921
9337
|
var FIRECRAWL_FALLBACK_THRESHOLD = 200;
|
|
8922
9338
|
var FIRECRAWL_DEFAULT_URL = "https://api.firecrawl.dev";
|
|
@@ -9073,7 +9489,7 @@ function webFetchTool(opts) {
|
|
|
9073
9489
|
const allowPrivate = opts?.allowPrivate ?? false;
|
|
9074
9490
|
const cacheTtlMs = opts?.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
|
|
9075
9491
|
const cacheMax = opts?.cacheMax ?? DEFAULT_CACHE_MAX;
|
|
9076
|
-
const timeoutMs = opts?.timeoutMs ??
|
|
9492
|
+
const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
|
|
9077
9493
|
const maxBodyBytes = opts?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
|
|
9078
9494
|
const cache = /* @__PURE__ */ new Map();
|
|
9079
9495
|
return {
|
|
@@ -9291,7 +9707,7 @@ function turnSurface(opts) {
|
|
|
9291
9707
|
const shellTools = createSessionShellTools(cwd, env, {
|
|
9292
9708
|
docker: opts.docker,
|
|
9293
9709
|
containerPrefix: homeContainerPrefix(paths.home),
|
|
9294
|
-
inputsDir:
|
|
9710
|
+
inputsDir: join22(agent.agent.dir, "uploads"),
|
|
9295
9711
|
skillMounts: promptSkills.map((skill) => ({ source: skill.hostDir, target: skill.sandboxDir })),
|
|
9296
9712
|
approvalHost: opts.bashApprovalHost
|
|
9297
9713
|
});
|
|
@@ -9332,7 +9748,7 @@ async function createBazilionSession(opts) {
|
|
|
9332
9748
|
const { agent, paths } = opts;
|
|
9333
9749
|
const { providerName, modelId } = parseModelString(agent.model);
|
|
9334
9750
|
if (!existsSync14(agent.team.path)) mkdirSync10(agent.team.path, { recursive: true });
|
|
9335
|
-
mkdirSync10(
|
|
9751
|
+
mkdirSync10(join22(paths.agentDir(agent.agent.id), "sessions"), { recursive: true });
|
|
9336
9752
|
const sessionManager = openConversation(agent, paths, opts.conversation);
|
|
9337
9753
|
const turn = turnSurface(opts);
|
|
9338
9754
|
return openPiSession({
|
|
@@ -9344,7 +9760,7 @@ async function createBazilionSession(opts) {
|
|
|
9344
9760
|
},
|
|
9345
9761
|
reasoningLevel: agent.reasoningLevel,
|
|
9346
9762
|
cwd: turn.modelCwd,
|
|
9347
|
-
piAgentDir:
|
|
9763
|
+
piAgentDir: join22(paths.home, "pi"),
|
|
9348
9764
|
sessionManager,
|
|
9349
9765
|
appendSystemPrompt: buildSystemPrompt(agent, turn.promptOptions),
|
|
9350
9766
|
agentsFiles: (opts.repositoryInstructions ?? []).map((file) => ({
|
|
@@ -9402,7 +9818,7 @@ function toPiThinkingLevel(level) {
|
|
|
9402
9818
|
}
|
|
9403
9819
|
}
|
|
9404
9820
|
function openConversation(agent, paths, target) {
|
|
9405
|
-
const sessionDir =
|
|
9821
|
+
const sessionDir = join22(paths.agentDir(agent.agent.id), "sessions");
|
|
9406
9822
|
return SessionManager.open(
|
|
9407
9823
|
explicitConversationFile(sessionDir, target),
|
|
9408
9824
|
sessionDir,
|
|
@@ -9411,13 +9827,13 @@ function openConversation(agent, paths, target) {
|
|
|
9411
9827
|
}
|
|
9412
9828
|
function loadInitialMessages(agent, paths, target) {
|
|
9413
9829
|
if (!target) return [];
|
|
9414
|
-
const entries = readSessionFile(
|
|
9830
|
+
const entries = readSessionFile(join22(paths.agentDir(agent.agent.id), "sessions"), target.id);
|
|
9415
9831
|
return buildSessionContext(entries.filter((entry) => entry.type !== "session")).messages;
|
|
9416
9832
|
}
|
|
9417
9833
|
function loadSessionMessages(agent, paths, sessionId) {
|
|
9418
9834
|
if (!/^[A-Za-z0-9._-]+$/.test(sessionId)) return [];
|
|
9419
|
-
const sessionDir =
|
|
9420
|
-
const file =
|
|
9835
|
+
const sessionDir = join22(paths.agentDir(agent.agent.id), "sessions");
|
|
9836
|
+
const file = join22(sessionDir, `${sessionId}.jsonl`);
|
|
9421
9837
|
if (!existsSync14(file) || !existsSync14(agent.team.path)) return [];
|
|
9422
9838
|
try {
|
|
9423
9839
|
return SessionManager.open(file, sessionDir).buildSessionContext().messages;
|
|
@@ -9426,12 +9842,12 @@ function loadSessionMessages(agent, paths, sessionId) {
|
|
|
9426
9842
|
}
|
|
9427
9843
|
}
|
|
9428
9844
|
function loadSessionHead(agent, paths, target) {
|
|
9429
|
-
const sessionDir =
|
|
9845
|
+
const sessionDir = join22(paths.agentDir(agent.agent.id), "sessions");
|
|
9430
9846
|
if (!existsSync14(sessionDir)) return { file: null, size: 0 };
|
|
9431
9847
|
const recent = target ? explicitConversationFile(sessionDir, target) : null;
|
|
9432
9848
|
if (!recent) return { file: null, size: 0 };
|
|
9433
9849
|
try {
|
|
9434
|
-
const s =
|
|
9850
|
+
const s = statSync7(recent);
|
|
9435
9851
|
return { file: basename5(recent), size: s.size };
|
|
9436
9852
|
} catch {
|
|
9437
9853
|
return { file: null, size: 0 };
|
|
@@ -9440,7 +9856,7 @@ function loadSessionHead(agent, paths, target) {
|
|
|
9440
9856
|
function explicitConversationFile(directory, target) {
|
|
9441
9857
|
if (!target) throw new Error("Explicit conversation target is required");
|
|
9442
9858
|
readSessionHeader(directory, target.id);
|
|
9443
|
-
return
|
|
9859
|
+
return join22(directory, `${target.id}.jsonl`);
|
|
9444
9860
|
}
|
|
9445
9861
|
|
|
9446
9862
|
// ../daemon/src/runtime/providers/catalog.ts
|
|
@@ -9496,10 +9912,10 @@ async function refreshApiKeyForTurn(requestedProvider, turnProvider, host3, sign
|
|
|
9496
9912
|
}
|
|
9497
9913
|
function waitForRefresh(pending, signal) {
|
|
9498
9914
|
if (!signal) return pending;
|
|
9499
|
-
return new Promise((
|
|
9915
|
+
return new Promise((resolve9, reject2) => {
|
|
9500
9916
|
const onAbort = () => reject2(refreshCancelledError());
|
|
9501
9917
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
9502
|
-
pending.then(
|
|
9918
|
+
pending.then(resolve9, reject2).finally(() => signal.removeEventListener("abort", onAbort));
|
|
9503
9919
|
});
|
|
9504
9920
|
}
|
|
9505
9921
|
var ApiKeyRefreshCancelledError = class extends Error {
|
|
@@ -9617,10 +10033,10 @@ async function* runWorker(run) {
|
|
|
9617
10033
|
child.stderr?.destroy();
|
|
9618
10034
|
}, EXIT_DRAIN_MS).unref();
|
|
9619
10035
|
});
|
|
9620
|
-
const exit = new Promise((
|
|
10036
|
+
const exit = new Promise((resolve9) => {
|
|
9621
10037
|
if (child.exitCode !== null || child.signalCode !== null) {
|
|
9622
|
-
|
|
9623
|
-
} else child.once("close", (code, signal) =>
|
|
10038
|
+
resolve9({ code: child.exitCode, signal: child.signalCode });
|
|
10039
|
+
} else child.once("close", (code, signal) => resolve9({ code, signal }));
|
|
9624
10040
|
});
|
|
9625
10041
|
try {
|
|
9626
10042
|
if (!child.stdout) throw new Error("worker spawn: stdout pipe missing");
|
|
@@ -9764,7 +10180,7 @@ var AsyncFrameQueue = class {
|
|
|
9764
10180
|
const frame = this.#frames.shift();
|
|
9765
10181
|
if (frame) return Promise.resolve({ done: false, value: frame });
|
|
9766
10182
|
if (this.#ended) return Promise.resolve({ done: true, value: void 0 });
|
|
9767
|
-
return new Promise((
|
|
10183
|
+
return new Promise((resolve9) => this.#waiters.push(resolve9));
|
|
9768
10184
|
}
|
|
9769
10185
|
};
|
|
9770
10186
|
}
|
|
@@ -9858,208 +10274,44 @@ function assertProviderReady(db, authToken, model) {
|
|
|
9858
10274
|
throw new ExecutionUnavailableError(error.message);
|
|
9859
10275
|
}
|
|
9860
10276
|
if (!findProvider(providerName)) {
|
|
9861
|
-
throw new ExecutionUnavailableError(`unknown provider: ${providerName}`);
|
|
9862
|
-
}
|
|
9863
|
-
if (!providerState_exports.listEnabled(db).has(providerName)) {
|
|
9864
|
-
throw new ExecutionUnavailableError(
|
|
9865
|
-
`${providerName} provider is disabled \u2014 enable it on the /config page`
|
|
9866
|
-
);
|
|
9867
|
-
}
|
|
9868
|
-
if (providerName === "openai-codex" && !hasCredentials(db, authToken)) {
|
|
9869
|
-
throw new ExecutionUnavailableError(
|
|
9870
|
-
"openai-codex is not connected \u2014 run `bazilion auth openai login` or click Connect on /config"
|
|
9871
|
-
);
|
|
9872
|
-
}
|
|
9873
|
-
}
|
|
9874
|
-
async function resolveAgentApiKey(db, authToken, agent) {
|
|
9875
|
-
if (parseModelString(agent.model).providerName !== "openai-codex") return {};
|
|
9876
|
-
return {
|
|
9877
|
-
apiKey: await loadAccessToken(db, authToken),
|
|
9878
|
-
refreshApiKey: async (requestedProvider) => {
|
|
9879
|
-
if (requestedProvider !== "openai-codex") {
|
|
9880
|
-
throw new Error(`unexpected refresh request for ${requestedProvider}`);
|
|
9881
|
-
}
|
|
9882
|
-
return loadAccessToken(db, authToken);
|
|
9883
|
-
}
|
|
9884
|
-
};
|
|
9885
|
-
}
|
|
9886
|
-
|
|
9887
|
-
// ../daemon/src/lib/bash-approval.ts
|
|
9888
|
-
var DEFAULT_TIMEOUT_MS2 = 12e4;
|
|
9889
|
-
var CommandApprovalRegistry = class {
|
|
9890
|
-
#pending = /* @__PURE__ */ new Map();
|
|
9891
|
-
#timeoutMs;
|
|
9892
|
-
constructor(timeoutMs = DEFAULT_TIMEOUT_MS2) {
|
|
9893
|
-
this.#timeoutMs = timeoutMs;
|
|
9894
|
-
}
|
|
9895
|
-
begin(input, signal) {
|
|
9896
|
-
const approval = {
|
|
9897
|
-
id: input.id,
|
|
9898
|
-
turnId: input.turnId,
|
|
9899
|
-
toolCallId: input.toolCallId,
|
|
9900
|
-
agentId: input.agentId,
|
|
9901
|
-
teamId: input.teamId,
|
|
9902
|
-
command: input.command,
|
|
9903
|
-
risks: input.risks,
|
|
9904
|
-
status: "pending",
|
|
9905
|
-
expiresAt: Date.now() + this.#timeoutMs
|
|
9906
|
-
};
|
|
9907
|
-
const immediate = input.mode === "auto_deny" ? "auto_denied" : signal?.aborted ? "cancelled" : void 0;
|
|
9908
|
-
if (immediate) {
|
|
9909
|
-
const settled2 = logged({ ...approval, status: immediate });
|
|
9910
|
-
return { approval: settled2, settled: Promise.resolve(settled2) };
|
|
9911
|
-
}
|
|
9912
|
-
if (this.#pending.has(approval.id))
|
|
9913
|
-
throw new Error(`duplicate shell approval id: ${approval.id}`);
|
|
9914
|
-
const settled = new Promise((resolve8) => {
|
|
9915
|
-
const settle = (status2) => {
|
|
9916
|
-
this.#pending.delete(approval.id);
|
|
9917
|
-
clearTimeout(timer);
|
|
9918
|
-
signal?.removeEventListener("abort", onAbort);
|
|
9919
|
-
const result = logged({ ...approval, status: status2 });
|
|
9920
|
-
resolve8(result);
|
|
9921
|
-
return result;
|
|
9922
|
-
};
|
|
9923
|
-
const onAbort = () => settle("cancelled");
|
|
9924
|
-
const timer = setTimeout(() => settle("expired"), this.#timeoutMs);
|
|
9925
|
-
timer.unref();
|
|
9926
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
9927
|
-
this.#pending.set(approval.id, { approval, settle });
|
|
9928
|
-
});
|
|
9929
|
-
return { approval, settled };
|
|
9930
|
-
}
|
|
9931
|
-
list(agentId) {
|
|
9932
|
-
return Array.from(this.#pending.values(), (entry) => entry.approval).filter((approval) => agentId === void 0 || approval.agentId === agentId).sort((a, b) => a.expiresAt - b.expiresAt || a.id.localeCompare(b.id));
|
|
9933
|
-
}
|
|
9934
|
-
/** Answer a pending approval; undefined when there is none (unknown, or already settled). */
|
|
9935
|
-
respond(id, decision) {
|
|
9936
|
-
return this.#pending.get(id)?.settle(decision === "allow" ? "allowed" : "denied");
|
|
9937
|
-
}
|
|
9938
|
-
};
|
|
9939
|
-
function logged(approval) {
|
|
9940
|
-
console.info("bash approval decision", {
|
|
9941
|
-
approvalId: approval.id,
|
|
9942
|
-
agentId: approval.agentId,
|
|
9943
|
-
teamId: approval.teamId,
|
|
9944
|
-
riskCodes: [...new Set(approval.risks.map((risk) => risk.code))],
|
|
9945
|
-
status: approval.status
|
|
9946
|
-
});
|
|
9947
|
-
return approval;
|
|
9948
|
-
}
|
|
9949
|
-
var commandApprovalRegistry = new CommandApprovalRegistry();
|
|
9950
|
-
|
|
9951
|
-
// ../daemon/src/lib/browser/host.ts
|
|
9952
|
-
init_pool2();
|
|
9953
|
-
function createBrowserHost(config, turn) {
|
|
9954
|
-
return {
|
|
9955
|
-
invoke: (_workerAgentId, action, args) => invokeBrowserAction(turn.agentId, action, args, config, turn.paths, turn.signal)
|
|
9956
|
-
};
|
|
9957
|
-
}
|
|
9958
|
-
|
|
9959
|
-
// ../daemon/src/lib/image-generation.ts
|
|
9960
|
-
import { createModels } from "@earendil-works/pi-ai";
|
|
9961
|
-
import { openrouterProvider } from "@earendil-works/pi-ai/providers/openrouter";
|
|
9962
|
-
|
|
9963
|
-
// ../daemon/src/core/repos/results.ts
|
|
9964
|
-
import { createHash as createHash4, randomUUID as randomUUID14 } from "node:crypto";
|
|
9965
|
-
|
|
9966
|
-
// ../daemon/src/core/tool-call-id.ts
|
|
9967
|
-
function isToolCallId(value) {
|
|
9968
|
-
return typeof value === "string" && value.length <= 256 && // A true end assertion also rejects a trailing newline (unlike JavaScript '$').
|
|
9969
|
-
/^[A-Za-z0-9._:-]+(?:\|[A-Za-z0-9._:-]+)?$(?![\s\S])/.test(value);
|
|
9970
|
-
}
|
|
9971
|
-
|
|
9972
|
-
// ../daemon/src/core/repos/results.ts
|
|
9973
|
-
var MAX_RESULT_BYTES = 25 * 1024 * 1024;
|
|
9974
|
-
var MAX_RETAINED_RESULT_BYTES = 1024 * 1024 * 1024;
|
|
9975
|
-
var columns2 = `id, team_id AS teamId, agent_id AS agentId, session_id AS sessionId,
|
|
9976
|
-
tool_call_id AS toolCallId, source_index AS sourceIndex, name, mime_type AS mimeType,
|
|
9977
|
-
byte_length AS byteLength, sha256, image_model AS imageModel, created_at AS createdAt`;
|
|
9978
|
-
function get17(db, id) {
|
|
9979
|
-
return db.raw.query(`SELECT ${columns2} FROM agent_results WHERE id = ?`).get(id);
|
|
9980
|
-
}
|
|
9981
|
-
function publish(db, input) {
|
|
9982
|
-
if (!isToolCallId(input.toolCallId)) throw new Error("Invalid result tool call");
|
|
9983
|
-
if (typeof input.name !== "string" || !input.name || input.name.length > 255 || /[/\\]/.test(input.name) || [...input.name].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) || input.name === "." || input.name === "..")
|
|
9984
|
-
throw new Error("Invalid result filename");
|
|
9985
|
-
if (typeof input.mimeType !== "string" || !/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(input.mimeType))
|
|
9986
|
-
throw new Error("Invalid result media type");
|
|
9987
|
-
if (input.bytes.byteLength > MAX_RESULT_BYTES)
|
|
9988
|
-
throw new Error("Result exceeds the 25 MiB per-file limit");
|
|
9989
|
-
const bytes = Buffer.from(input.bytes);
|
|
9990
|
-
const sourceIndex = input.sourceIndex ?? 0;
|
|
9991
|
-
return db.raw.transaction(() => {
|
|
9992
|
-
const existing = db.raw.query(
|
|
9993
|
-
`SELECT id FROM agent_results
|
|
9994
|
-
WHERE agent_id = ? AND session_id = ? AND tool_call_id = ? AND source_index = ?`
|
|
9995
|
-
).get(input.agentId, input.sessionId, input.toolCallId, sourceIndex);
|
|
9996
|
-
if (existing) return get17(db, existing.id);
|
|
9997
|
-
const retained = db.raw.query(
|
|
9998
|
-
"SELECT coalesce(sum(byte_length), 0) AS bytes FROM agent_results"
|
|
9999
|
-
).get()?.bytes ?? 0;
|
|
10000
|
-
if (retained + bytes.byteLength > MAX_RETAINED_RESULT_BYTES)
|
|
10001
|
-
throw new Error(
|
|
10002
|
-
"Result storage is full (1 GiB). Delete saved results before delivering more files."
|
|
10003
|
-
);
|
|
10004
|
-
const id = randomUUID14();
|
|
10005
|
-
db.raw.run(
|
|
10006
|
-
`INSERT INTO agent_results
|
|
10007
|
-
(id, team_id, agent_id, session_id, tool_call_id, source_index, name, mime_type,
|
|
10008
|
-
byte_length, sha256, image_model, created_at, bytes)
|
|
10009
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
10010
|
-
[
|
|
10011
|
-
id,
|
|
10012
|
-
input.teamId,
|
|
10013
|
-
input.agentId,
|
|
10014
|
-
input.sessionId,
|
|
10015
|
-
input.toolCallId,
|
|
10016
|
-
sourceIndex,
|
|
10017
|
-
input.name,
|
|
10018
|
-
input.mimeType,
|
|
10019
|
-
bytes.byteLength,
|
|
10020
|
-
createHash4("sha256").update(bytes).digest("hex"),
|
|
10021
|
-
input.imageModel ?? null,
|
|
10022
|
-
Date.now(),
|
|
10023
|
-
bytes
|
|
10024
|
-
]
|
|
10025
|
-
);
|
|
10026
|
-
return get17(db, id);
|
|
10027
|
-
})();
|
|
10028
|
-
}
|
|
10029
|
-
function list12(db, opts = {}) {
|
|
10030
|
-
const limit = Math.max(1, Math.min(100, Math.floor(opts.limit ?? 50)));
|
|
10031
|
-
const offset = Math.max(0, Math.floor(opts.offset ?? 0));
|
|
10032
|
-
const where = [];
|
|
10033
|
-
const params = [];
|
|
10034
|
-
if (opts.teamId !== void 0) {
|
|
10035
|
-
where.push("team_id = ?");
|
|
10036
|
-
params.push(opts.teamId);
|
|
10277
|
+
throw new ExecutionUnavailableError(`unknown provider: ${providerName}`);
|
|
10037
10278
|
}
|
|
10038
|
-
if (
|
|
10039
|
-
|
|
10040
|
-
|
|
10279
|
+
if (!providerState_exports.listEnabled(db).has(providerName)) {
|
|
10280
|
+
throw new ExecutionUnavailableError(
|
|
10281
|
+
`${providerName} provider is disabled \u2014 enable it on the /config page`
|
|
10282
|
+
);
|
|
10283
|
+
}
|
|
10284
|
+
if (providerName === "openai-codex" && !hasCredentials(db, authToken)) {
|
|
10285
|
+
throw new ExecutionUnavailableError(
|
|
10286
|
+
"openai-codex is not connected \u2014 run `bazilion auth openai login` or click Connect on /config"
|
|
10287
|
+
);
|
|
10041
10288
|
}
|
|
10042
|
-
const filter = where.length ? `WHERE ${where.join(" AND ")}` : "";
|
|
10043
|
-
const total = db.raw.query(`SELECT count(*) AS total FROM agent_results ${filter}`).get(...params)?.total ?? 0;
|
|
10044
|
-
const results = db.raw.query(
|
|
10045
|
-
`SELECT ${columns2} FROM agent_results ${filter} ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?`
|
|
10046
|
-
).all(...params, limit, offset);
|
|
10047
|
-
return { results, total, limit, offset };
|
|
10048
10289
|
}
|
|
10049
|
-
function
|
|
10050
|
-
|
|
10051
|
-
|
|
10052
|
-
|
|
10053
|
-
|
|
10054
|
-
|
|
10055
|
-
|
|
10056
|
-
|
|
10057
|
-
|
|
10290
|
+
async function resolveAgentApiKey(db, authToken, agent) {
|
|
10291
|
+
if (parseModelString(agent.model).providerName !== "openai-codex") return {};
|
|
10292
|
+
return {
|
|
10293
|
+
apiKey: await loadAccessToken(db, authToken),
|
|
10294
|
+
refreshApiKey: async (requestedProvider) => {
|
|
10295
|
+
if (requestedProvider !== "openai-codex") {
|
|
10296
|
+
throw new Error(`unexpected refresh request for ${requestedProvider}`);
|
|
10297
|
+
}
|
|
10298
|
+
return loadAccessToken(db, authToken);
|
|
10299
|
+
}
|
|
10300
|
+
};
|
|
10058
10301
|
}
|
|
10059
|
-
|
|
10060
|
-
|
|
10302
|
+
|
|
10303
|
+
// ../daemon/src/lib/browser/host.ts
|
|
10304
|
+
init_pool2();
|
|
10305
|
+
function createBrowserHost(config, turn) {
|
|
10306
|
+
return {
|
|
10307
|
+
invoke: (_workerAgentId, action, args) => invokeBrowserAction(turn.agentId, action, args, config, turn.paths, turn.signal)
|
|
10308
|
+
};
|
|
10061
10309
|
}
|
|
10062
10310
|
|
|
10311
|
+
// ../daemon/src/lib/image-generation.ts
|
|
10312
|
+
import { createModels } from "@earendil-works/pi-ai";
|
|
10313
|
+
import { openrouterProvider } from "@earendil-works/pi-ai/providers/openrouter";
|
|
10314
|
+
|
|
10063
10315
|
// ../daemon/src/lib/openai-responses.ts
|
|
10064
10316
|
var OPENAI_RESPONSES_URL = "https://api.openai.com/v1/responses";
|
|
10065
10317
|
var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
|
|
@@ -10340,7 +10592,7 @@ async function resolveMcpForTurn(db, authToken, signal) {
|
|
|
10340
10592
|
}
|
|
10341
10593
|
|
|
10342
10594
|
// ../daemon/src/lib/agent-loop-guard.ts
|
|
10343
|
-
import { randomUUID as
|
|
10595
|
+
import { randomUUID as randomUUID16 } from "node:crypto";
|
|
10344
10596
|
var DEFAULT_MAX_HOPS = 8;
|
|
10345
10597
|
function toEvent(row) {
|
|
10346
10598
|
return {
|
|
@@ -10390,8 +10642,8 @@ function enforceMessageCausality(db, input) {
|
|
|
10390
10642
|
const target = agents_exports.get(db, input.to);
|
|
10391
10643
|
if (!source || !target) return null;
|
|
10392
10644
|
const event = {
|
|
10393
|
-
id:
|
|
10394
|
-
causalChainId: input.causality.causalChainId ?? input.causality.parentMessageId ??
|
|
10645
|
+
id: randomUUID16(),
|
|
10646
|
+
causalChainId: input.causality.causalChainId ?? input.causality.parentMessageId ?? randomUUID16(),
|
|
10395
10647
|
parentMessageId: input.causality.parentMessageId,
|
|
10396
10648
|
fromAgentId: input.from,
|
|
10397
10649
|
toAgentId: input.to,
|
|
@@ -10513,120 +10765,6 @@ function createDbMessagingHost(db, opts = {}) {
|
|
|
10513
10765
|
};
|
|
10514
10766
|
}
|
|
10515
10767
|
|
|
10516
|
-
// ../daemon/src/lib/questions.ts
|
|
10517
|
-
import { randomUUID as randomUUID16 } from "node:crypto";
|
|
10518
|
-
var QUESTION_WAIT_MS = 5 * 6e4;
|
|
10519
|
-
var QUESTION_LIMITS = Object.freeze({
|
|
10520
|
-
promptChars: 2e3,
|
|
10521
|
-
labelChars: 120,
|
|
10522
|
-
descriptionChars: 500,
|
|
10523
|
-
answerChars: 4096
|
|
10524
|
-
});
|
|
10525
|
-
function text2(value, limit, what) {
|
|
10526
|
-
if (typeof value !== "string" || !value.trim()) throw new Error(`${what} must be non-empty text`);
|
|
10527
|
-
if (value.length > limit) throw new Error(`${what} is longer than ${limit} characters`);
|
|
10528
|
-
return value;
|
|
10529
|
-
}
|
|
10530
|
-
function parseQuestionInput(value) {
|
|
10531
|
-
const input = value ?? {};
|
|
10532
|
-
const prompt = text2(input.prompt, QUESTION_LIMITS.promptChars, "The prompt");
|
|
10533
|
-
if (!Array.isArray(input.choices) || input.choices.length < 2 || input.choices.length > 4)
|
|
10534
|
-
throw new Error("ask_user needs 2 to 4 choices");
|
|
10535
|
-
const labels = /* @__PURE__ */ new Set();
|
|
10536
|
-
const choices = input.choices.map((raw, index) => {
|
|
10537
|
-
const choice = raw ?? {};
|
|
10538
|
-
const label = text2(choice.label, QUESTION_LIMITS.labelChars, `Choice ${index + 1} label`);
|
|
10539
|
-
const key2 = label.normalize("NFKC").trim().toLowerCase();
|
|
10540
|
-
if (labels.has(key2)) throw new Error("Choice labels must be distinct");
|
|
10541
|
-
labels.add(key2);
|
|
10542
|
-
if (choice.description === void 0) return { label };
|
|
10543
|
-
const description = text2(
|
|
10544
|
-
choice.description,
|
|
10545
|
-
QUESTION_LIMITS.descriptionChars,
|
|
10546
|
-
`Choice ${index + 1} description`
|
|
10547
|
-
);
|
|
10548
|
-
return { label, description };
|
|
10549
|
-
});
|
|
10550
|
-
const recommended = input.recommendedIndex;
|
|
10551
|
-
if (recommended === void 0) return { prompt, choices };
|
|
10552
|
-
if (typeof recommended !== "number" || !Number.isInteger(recommended))
|
|
10553
|
-
throw new Error("recommendedIndex must be a choice index");
|
|
10554
|
-
if (recommended < 0 || recommended >= choices.length)
|
|
10555
|
-
throw new Error("recommendedIndex must be a choice index");
|
|
10556
|
-
return { prompt, choices, recommendedIndex: recommended };
|
|
10557
|
-
}
|
|
10558
|
-
function parseQuestionAnswer(value, question) {
|
|
10559
|
-
const answer = value ?? {};
|
|
10560
|
-
if (answer.kind === "skip") return { kind: "skip" };
|
|
10561
|
-
if (answer.kind === "text")
|
|
10562
|
-
return { kind: "text", text: text2(answer.text, QUESTION_LIMITS.answerChars, "The answer") };
|
|
10563
|
-
const index = answer.index;
|
|
10564
|
-
if (answer.kind === "choice" && typeof index === "number" && Number.isInteger(index)) {
|
|
10565
|
-
if (index >= 0 && index < question.choices.length) return { kind: "choice", index };
|
|
10566
|
-
throw new Error(
|
|
10567
|
-
`Choice ${index + 1} does not exist; this question has ${question.choices.length} choices`
|
|
10568
|
-
);
|
|
10569
|
-
}
|
|
10570
|
-
throw new Error("An answer is a choice index, text or skip");
|
|
10571
|
-
}
|
|
10572
|
-
var QuestionRegistry = class {
|
|
10573
|
-
#pending = /* @__PURE__ */ new Map();
|
|
10574
|
-
#waitMs;
|
|
10575
|
-
constructor(waitMs = QUESTION_WAIT_MS) {
|
|
10576
|
-
this.#waitMs = waitMs;
|
|
10577
|
-
}
|
|
10578
|
-
/** Register a question. `result` settles on the first answer, the timeout or `signal`. */
|
|
10579
|
-
ask(context, input, signal) {
|
|
10580
|
-
const prompt = parseQuestionInput(input);
|
|
10581
|
-
if (this.list(context.agentId).length > 0)
|
|
10582
|
-
throw new Error("Another question from this Agent is still waiting for an answer");
|
|
10583
|
-
if (signal?.aborted) throw new Error("The turn has ended");
|
|
10584
|
-
const now = Date.now();
|
|
10585
|
-
const question = {
|
|
10586
|
-
id: randomUUID16(),
|
|
10587
|
-
agentId: context.agentId,
|
|
10588
|
-
conversationId: context.conversationId,
|
|
10589
|
-
question: prompt,
|
|
10590
|
-
createdAt: now,
|
|
10591
|
-
expiresAt: now + this.#waitMs
|
|
10592
|
-
};
|
|
10593
|
-
const { promise, resolve: resolve8 } = Promise.withResolvers();
|
|
10594
|
-
const cancel3 = () => finish3({ kind: "no_answer", reason: "cancelled" });
|
|
10595
|
-
const timer = setTimeout(() => finish3({ kind: "no_answer", reason: "expired" }), this.#waitMs);
|
|
10596
|
-
timer.unref();
|
|
10597
|
-
const finish3 = (outcome) => {
|
|
10598
|
-
if (!this.#pending.delete(question.id)) return false;
|
|
10599
|
-
clearTimeout(timer);
|
|
10600
|
-
signal?.removeEventListener("abort", cancel3);
|
|
10601
|
-
resolve8({ questionId: question.id, question: prompt, ...outcome });
|
|
10602
|
-
return true;
|
|
10603
|
-
};
|
|
10604
|
-
this.#pending.set(question.id, { question, result: promise, finish: finish3 });
|
|
10605
|
-
signal?.addEventListener("abort", cancel3, { once: true });
|
|
10606
|
-
return { question, result: promise };
|
|
10607
|
-
}
|
|
10608
|
-
list(agentId) {
|
|
10609
|
-
return [...this.#pending.values()].map((entry) => entry.question).filter((question) => agentId === void 0 || question.agentId === agentId);
|
|
10610
|
-
}
|
|
10611
|
-
get(id) {
|
|
10612
|
-
return this.#pending.get(id)?.question;
|
|
10613
|
-
}
|
|
10614
|
-
/** The outcome of a waiting question; undefined once it has settled. */
|
|
10615
|
-
settled(id) {
|
|
10616
|
-
return this.#pending.get(id)?.result;
|
|
10617
|
-
}
|
|
10618
|
-
/** Answer a waiting question. False when it is no longer waiting; throws on an invalid answer. */
|
|
10619
|
-
answer(agentId, id, value) {
|
|
10620
|
-
const entry = this.#pending.get(id);
|
|
10621
|
-
if (!entry || entry.question.agentId !== agentId) return false;
|
|
10622
|
-
const answer = parseQuestionAnswer(value, entry.question.question);
|
|
10623
|
-
return entry.finish(
|
|
10624
|
-
answer.kind === "skip" ? { kind: "no_answer", reason: "skipped" } : { kind: "answer", answer }
|
|
10625
|
-
);
|
|
10626
|
-
}
|
|
10627
|
-
};
|
|
10628
|
-
var questionRegistry = new QuestionRegistry();
|
|
10629
|
-
|
|
10630
10768
|
// ../daemon/src/lib/result-host.ts
|
|
10631
10769
|
function createResultHost(db, agent, conversationId, signal) {
|
|
10632
10770
|
return {
|
|
@@ -11266,7 +11404,7 @@ function mirrorTypingStop(agentId) {
|
|
|
11266
11404
|
// ../daemon/src/lib/attachments.ts
|
|
11267
11405
|
import { randomUUID as randomUUID17 } from "node:crypto";
|
|
11268
11406
|
import { closeSync as closeSync5, constants as constants6, fstatSync as fstatSync5, openSync as openSync5, writeFileSync as writeFileSync8 } from "node:fs";
|
|
11269
|
-
import { join as
|
|
11407
|
+
import { join as join23, posix as posix2 } from "node:path";
|
|
11270
11408
|
var MAX_FILE_BYTES = 25 * 1024 * 1024;
|
|
11271
11409
|
function safeName(name) {
|
|
11272
11410
|
const base = name.split(/[\\/]/).pop() ?? "file";
|
|
@@ -11278,7 +11416,7 @@ function fmtBytes(n) {
|
|
|
11278
11416
|
return `${(n / (1024 * 1024)).toFixed(1)} MB`;
|
|
11279
11417
|
}
|
|
11280
11418
|
function prepareInputFilesDirectory(agentDir2) {
|
|
11281
|
-
return ensureContainedRealDirectory(
|
|
11419
|
+
return ensureContainedRealDirectory(join23(agentDir2, "uploads"), agentDir2, { create: true });
|
|
11282
11420
|
}
|
|
11283
11421
|
function saveInputFiles(agentDir2, files, options = {}) {
|
|
11284
11422
|
if (!files || files.length === 0) return "";
|
|
@@ -11292,7 +11430,7 @@ function saveInputFiles(agentDir2, files, options = {}) {
|
|
|
11292
11430
|
continue;
|
|
11293
11431
|
}
|
|
11294
11432
|
const filename = `${randomUUID17().slice(0, 8)}-${safeName(label)}`;
|
|
11295
|
-
const path =
|
|
11433
|
+
const path = join23(dir, filename);
|
|
11296
11434
|
let fd;
|
|
11297
11435
|
try {
|
|
11298
11436
|
fd = openSync5(
|
|
@@ -11315,7 +11453,7 @@ function saveInputFiles(agentDir2, files, options = {}) {
|
|
|
11315
11453
|
|
|
11316
11454
|
// ../daemon/src/lib/coding-environment.ts
|
|
11317
11455
|
import { lstatSync as lstatSync5 } from "node:fs";
|
|
11318
|
-
import { join as
|
|
11456
|
+
import { join as join24 } from "node:path";
|
|
11319
11457
|
|
|
11320
11458
|
// ../daemon/src/core/coding-environment/config.ts
|
|
11321
11459
|
var CodingEnvironmentValidationError = class extends DomainError {
|
|
@@ -11372,7 +11510,7 @@ function setTeamCodingEnvironment(db, team, input, env = process.env) {
|
|
|
11372
11510
|
const environment = validateCodingEnvironment(input);
|
|
11373
11511
|
let path = team.path;
|
|
11374
11512
|
for (const part of environment.cwd === "." ? [] : environment.cwd.split("/")) {
|
|
11375
|
-
path =
|
|
11513
|
+
path = join24(path, part);
|
|
11376
11514
|
if (!lstatSync5(path, { throwIfNoEntry: false })?.isDirectory())
|
|
11377
11515
|
throw new CodingEnvironmentValidationError(
|
|
11378
11516
|
"The directory must be an existing directory inside the Team"
|
|
@@ -11393,17 +11531,17 @@ function dockerTurn(db, paths, agent, env) {
|
|
|
11393
11531
|
// ../daemon/src/lib/conversation-target.ts
|
|
11394
11532
|
import { randomUUID as randomUUID18 } from "node:crypto";
|
|
11395
11533
|
import { writeFileSync as writeFileSync9 } from "node:fs";
|
|
11396
|
-
import { join as
|
|
11534
|
+
import { join as join25 } from "node:path";
|
|
11397
11535
|
import { SessionManager as SessionManager2 } from "@earendil-works/pi-coding-agent";
|
|
11398
11536
|
function sessionsDir(paths, agentId) {
|
|
11399
|
-
return
|
|
11537
|
+
return join25(paths.agentDir(agentId), "sessions");
|
|
11400
11538
|
}
|
|
11401
11539
|
function startConversation(db, paths, agentId, title) {
|
|
11402
11540
|
const agent = resolveAgent(db, paths, agentId);
|
|
11403
11541
|
if (title !== void 0) validTitle(title);
|
|
11404
11542
|
const id = randomUUID18();
|
|
11405
11543
|
const header = SessionManager2.inMemory(agent.team.path, { id }).getHeader();
|
|
11406
|
-
writeFileSync9(
|
|
11544
|
+
writeFileSync9(join25(sessionsDir(paths, agentId), `${id}.jsonl`), `${JSON.stringify(header)}
|
|
11407
11545
|
`, {
|
|
11408
11546
|
flag: "wx",
|
|
11409
11547
|
mode: 384
|
|
@@ -11416,6 +11554,34 @@ function resolveConversationTarget(db, paths, agentId, pinnedId) {
|
|
|
11416
11554
|
readSessionHeader(sessionsDir(paths, agentId), id);
|
|
11417
11555
|
return { id };
|
|
11418
11556
|
}
|
|
11557
|
+
function selectConversation(db, paths, agentId, id) {
|
|
11558
|
+
if (!get16(db, agentId, id)) throw new DomainError(404, "Conversation not found");
|
|
11559
|
+
try {
|
|
11560
|
+
readSessionHeader(sessionsDir(paths, agentId), id);
|
|
11561
|
+
} catch {
|
|
11562
|
+
throw new DomainError(409, "That conversation has no readable history, so it cannot continue.");
|
|
11563
|
+
}
|
|
11564
|
+
return select(db, agentId, id);
|
|
11565
|
+
}
|
|
11566
|
+
var TITLE_CHARS = 60;
|
|
11567
|
+
function titleFromMessage(message) {
|
|
11568
|
+
const line = message.split("\n").map((part) => part.replace(/\s+/g, " ").trim()).find((part) => part.length > 0);
|
|
11569
|
+
if (!line) return null;
|
|
11570
|
+
const clean = Array.from(line).filter((char) => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127).join("").trim();
|
|
11571
|
+
if (!clean) return null;
|
|
11572
|
+
if (clean.length <= TITLE_CHARS) return clean;
|
|
11573
|
+
const cut = clean.slice(0, TITLE_CHARS);
|
|
11574
|
+
const space = cut.lastIndexOf(" ");
|
|
11575
|
+
return `${(space > TITLE_CHARS / 2 ? cut.slice(0, space) : cut).trimEnd()}\u2026`;
|
|
11576
|
+
}
|
|
11577
|
+
function titleConversationFromMessage(db, paths, agentId, conversationId, message) {
|
|
11578
|
+
const conversation = get16(db, agentId, conversationId);
|
|
11579
|
+
if (!conversation || !hasDefaultTitle(conversation)) return;
|
|
11580
|
+
if (conversation.updatedAt !== conversation.createdAt) return;
|
|
11581
|
+
if (sessionHasEntries(sessionsDir(paths, agentId), conversationId)) return;
|
|
11582
|
+
const title = titleFromMessage(message);
|
|
11583
|
+
if (title) rename(db, agentId, conversationId, title);
|
|
11584
|
+
}
|
|
11419
11585
|
function selectedConversationTarget(db, agentId) {
|
|
11420
11586
|
const id = selectedId(db, agentId);
|
|
11421
11587
|
return id ? { id } : null;
|
|
@@ -11423,7 +11589,7 @@ function selectedConversationTarget(db, agentId) {
|
|
|
11423
11589
|
|
|
11424
11590
|
// ../daemon/src/lib/repository-instructions.ts
|
|
11425
11591
|
import { realpathSync as realpathSync6 } from "node:fs";
|
|
11426
|
-
import { join as
|
|
11592
|
+
import { join as join26 } from "node:path";
|
|
11427
11593
|
var MAX_FILE_BYTES2 = 128 * 1024;
|
|
11428
11594
|
var SKIPPED = {
|
|
11429
11595
|
outside: "it resolves outside the Team workspace",
|
|
@@ -11443,7 +11609,7 @@ function loadRepositoryInstructions(root, cwd = ".") {
|
|
|
11443
11609
|
for (let depth = 0; depth <= parts.length; depth++) {
|
|
11444
11610
|
const path = [...parts.slice(0, depth), "AGENTS.md"].join("/");
|
|
11445
11611
|
try {
|
|
11446
|
-
const content = readContainedFile(
|
|
11612
|
+
const content = readContainedFile(join26(realRoot, path), realRoot, MAX_FILE_BYTES2);
|
|
11447
11613
|
instructions.push({ path, content: content.toString("utf8") });
|
|
11448
11614
|
} catch (error) {
|
|
11449
11615
|
if (error instanceof ContainedFileError) {
|
|
@@ -11476,6 +11642,9 @@ async function prepareAgentTurn(request) {
|
|
|
11476
11642
|
registerAgent(agentId, controller);
|
|
11477
11643
|
registered = true;
|
|
11478
11644
|
}
|
|
11645
|
+
if (request.origin === "http" || request.origin === "telegram") {
|
|
11646
|
+
titleConversationFromMessage(db, paths, agentId, conversation.id, request.message);
|
|
11647
|
+
}
|
|
11479
11648
|
const env = mergeSecretsIntoEnv(db, authToken);
|
|
11480
11649
|
const docker2 = resolveShellSecurityConfig(env).sandboxMode === "docker" ? dockerTurn(db, paths, agent, env) : void 0;
|
|
11481
11650
|
const repositoryInstructions = loadRepositoryInstructions(agent.team.path, docker2?.cwd ?? ".");
|
|
@@ -11727,12 +11896,14 @@ async function* runAgentTurn(turn) {
|
|
|
11727
11896
|
);
|
|
11728
11897
|
});
|
|
11729
11898
|
if (frame.kind === "done") completed = true;
|
|
11899
|
+
noteTurnFrame(agentId, frame);
|
|
11730
11900
|
yield frame;
|
|
11731
11901
|
}
|
|
11732
11902
|
if (completed && (turn.request.origin === "http" || turn.request.origin === "telegram")) {
|
|
11733
11903
|
agentReviews_exports.recordSuccessfulUserTurn(db, agentId);
|
|
11734
11904
|
}
|
|
11735
11905
|
} finally {
|
|
11906
|
+
noteTurnEnd(agentId);
|
|
11736
11907
|
mirrorTypingStop(agentId);
|
|
11737
11908
|
if (turn.docker) await removeDockerContainers(turn.docker.containerPrefix);
|
|
11738
11909
|
releasePreparedAgentTurn(turn);
|
|
@@ -12081,7 +12252,7 @@ agentChatRouter.post("/:id/chat/compact", async (c) => {
|
|
|
12081
12252
|
const { db, paths, authToken } = getCtx();
|
|
12082
12253
|
const resolved = resolveAgent(db, paths, id);
|
|
12083
12254
|
assertProviderReady(db, authToken, resolved.model);
|
|
12084
|
-
const memory = qmdBackend(
|
|
12255
|
+
const memory = qmdBackend(join27(resolved.team.path, "memory"));
|
|
12085
12256
|
await memory.init();
|
|
12086
12257
|
const handle12 = await createBazilionSession({
|
|
12087
12258
|
agent: resolved,
|
|
@@ -12139,7 +12310,7 @@ agentChatRouter.get(
|
|
|
12139
12310
|
const env = mergeSecretsIntoEnv(db, authToken);
|
|
12140
12311
|
const files = [];
|
|
12141
12312
|
for (const file of CONTEXT_FILE_ORDER2) {
|
|
12142
|
-
const path =
|
|
12313
|
+
const path = join27(resolved.agent.dir, file);
|
|
12143
12314
|
if (!existsSync16(path)) continue;
|
|
12144
12315
|
const content = readFileSync10(path, "utf8").trimEnd();
|
|
12145
12316
|
if (!content) continue;
|
|
@@ -12154,7 +12325,7 @@ agentChatRouter.get(
|
|
|
12154
12325
|
agent: resolved,
|
|
12155
12326
|
paths,
|
|
12156
12327
|
env,
|
|
12157
|
-
memory: qmdBackend(
|
|
12328
|
+
memory: qmdBackend(join27(resolved.team.path, "memory")),
|
|
12158
12329
|
messagingHost: createDbMessagingHost(db),
|
|
12159
12330
|
userMdHost: createDbUserMdHost(db, paths),
|
|
12160
12331
|
fileSink: reportOnly,
|
|
@@ -12258,7 +12429,7 @@ agentChatRouter.post("/:id/chat/truncate", async (c) => {
|
|
|
12258
12429
|
});
|
|
12259
12430
|
|
|
12260
12431
|
// ../daemon/src/routes/agent-learning.ts
|
|
12261
|
-
import { join as
|
|
12432
|
+
import { join as join28 } from "node:path";
|
|
12262
12433
|
|
|
12263
12434
|
// ../daemon/src/lib/lesson-decisions.ts
|
|
12264
12435
|
var LessonProposalConflictError = class extends DomainError {
|
|
@@ -12457,7 +12628,7 @@ for (const decision of ["approve", "reject", "revoke"]) {
|
|
|
12457
12628
|
const team = teams_exports.get(db, agent.teamId, paths);
|
|
12458
12629
|
if (!team) return c.json({ error: `team not found: ${agent.teamId}` }, 404);
|
|
12459
12630
|
const proposal = await runAgentLifecycleMutation(agent.id, async () => {
|
|
12460
|
-
const memory = qmdBackend(
|
|
12631
|
+
const memory = qmdBackend(join28(team.path, "memory"));
|
|
12461
12632
|
if (decision === "approve") return approveLessonProposal(db, memory, current2.id, version);
|
|
12462
12633
|
if (decision === "reject") return rejectLessonProposal(db, current2.id, version);
|
|
12463
12634
|
return revokeLessonProposal(db, memory, current2.id, version);
|
|
@@ -12485,7 +12656,7 @@ function withEvidenceExcerpts(proposals, agent, paths) {
|
|
|
12485
12656
|
}
|
|
12486
12657
|
|
|
12487
12658
|
// ../daemon/src/routes/agents.ts
|
|
12488
|
-
import { join as
|
|
12659
|
+
import { join as join29 } from "node:path";
|
|
12489
12660
|
init_pool2();
|
|
12490
12661
|
|
|
12491
12662
|
// ../daemon/src/lib/telegram/config.ts
|
|
@@ -12760,7 +12931,7 @@ agentsRouter.get("/", (c) => {
|
|
|
12760
12931
|
const includeArchived = c.req.query("includeArchived") === "true";
|
|
12761
12932
|
const agents = agents_exports.list(getCtx().db, { includeArchived }).map((agent) => ({
|
|
12762
12933
|
...agent,
|
|
12763
|
-
identity: loadIdentityFromFile(
|
|
12934
|
+
identity: loadIdentityFromFile(join29(agent.dir, "IDENTITY.md"))
|
|
12764
12935
|
}));
|
|
12765
12936
|
return c.json(agents);
|
|
12766
12937
|
});
|
|
@@ -12902,9 +13073,9 @@ var DEVICE_CODE_FALLBACK = "`bazilion auth openai login --device-code` in a term
|
|
|
12902
13073
|
async function preflightOpenAICodexCallback(host3 = process.env.PI_OAUTH_CALLBACK_HOST?.trim() || "127.0.0.1", port2 = OPENAI_CODEX_CALLBACK_PORT) {
|
|
12903
13074
|
const server3 = createServer2();
|
|
12904
13075
|
try {
|
|
12905
|
-
await new Promise((
|
|
13076
|
+
await new Promise((resolve9, reject2) => {
|
|
12906
13077
|
server3.once("error", reject2);
|
|
12907
|
-
server3.listen({ host: host3, port: port2, exclusive: true },
|
|
13078
|
+
server3.listen({ host: host3, port: port2, exclusive: true }, resolve9);
|
|
12908
13079
|
});
|
|
12909
13080
|
} catch (error) {
|
|
12910
13081
|
const code = error.code;
|
|
@@ -12913,7 +13084,7 @@ async function preflightOpenAICodexCallback(host3 = process.env.PI_OAUTH_CALLBAC
|
|
|
12913
13084
|
code === "EADDRINUSE" ? `OpenAI browser login cannot start because callback address ${address} is already in use. Stop the process using that port and try again, or run ${DEVICE_CODE_FALLBACK}.` : `OpenAI browser login cannot bind callback address ${address}${code ? ` (${code})` : ""}. Check PI_OAUTH_CALLBACK_HOST and try again, or run ${DEVICE_CODE_FALLBACK}.`
|
|
12914
13085
|
);
|
|
12915
13086
|
} finally {
|
|
12916
|
-
await new Promise((
|
|
13087
|
+
await new Promise((resolve9) => server3.close(() => resolve9()));
|
|
12917
13088
|
}
|
|
12918
13089
|
}
|
|
12919
13090
|
function openAICodexBrowserCommand(platform = process.platform) {
|
|
@@ -13331,6 +13502,17 @@ conversationsRouter.get("/:agentId/conversations/:id", (c) => {
|
|
|
13331
13502
|
);
|
|
13332
13503
|
}
|
|
13333
13504
|
});
|
|
13505
|
+
conversationsRouter.post("/:agentId/conversations/:id/select", async (c) => {
|
|
13506
|
+
const agentId = c.get("agentId");
|
|
13507
|
+
const id = c.req.param("id");
|
|
13508
|
+
const { db, paths } = getCtx();
|
|
13509
|
+
return c.json({
|
|
13510
|
+
conversation: await runAgentLifecycleMutation(
|
|
13511
|
+
agentId,
|
|
13512
|
+
() => selectConversation(db, paths, agentId, id)
|
|
13513
|
+
)
|
|
13514
|
+
});
|
|
13515
|
+
});
|
|
13334
13516
|
conversationsRouter.patch("/:agentId/conversations/:id", async (c) => {
|
|
13335
13517
|
const input = await jsonBody(c);
|
|
13336
13518
|
return c.json({
|
|
@@ -13466,6 +13648,13 @@ mcpRouter.post("/:id/test", async (c) => {
|
|
|
13466
13648
|
|
|
13467
13649
|
// ../daemon/src/routes/messages.ts
|
|
13468
13650
|
var messagesRouter = newRouter();
|
|
13651
|
+
var teamMessagesRouter = newRouter();
|
|
13652
|
+
teamMessagesRouter.get("/:id/messages", (c) => {
|
|
13653
|
+
const limit = Math.min(Math.max(Number(c.req.query("limit")) || 100, 1), 500);
|
|
13654
|
+
return c.json({
|
|
13655
|
+
messages: messages_exports.listForTeam(getCtx().db, routeTeam(c).id, limit)
|
|
13656
|
+
});
|
|
13657
|
+
});
|
|
13469
13658
|
messagesRouter.get("/:id", (c) => {
|
|
13470
13659
|
const msg = messages_exports.get(getCtx().db, c.req.param("id"));
|
|
13471
13660
|
if (!msg) return c.json({ error: `message not found: ${c.req.param("id")}` }, 404);
|
|
@@ -13521,23 +13710,23 @@ agentMessagesRouter.post("/:id/messages", async (c) => {
|
|
|
13521
13710
|
// ../daemon/src/routes/misc.ts
|
|
13522
13711
|
import { existsSync as existsSync17 } from "node:fs";
|
|
13523
13712
|
import { homedir as homedir4 } from "node:os";
|
|
13524
|
-
import { join as
|
|
13713
|
+
import { join as join32 } from "node:path";
|
|
13525
13714
|
|
|
13526
13715
|
// ../daemon/src/lib/backup.ts
|
|
13527
13716
|
import { mkdtempSync as mkdtempSync3, rmSync as rmSync13 } from "node:fs";
|
|
13528
13717
|
import { tmpdir as tmpdir3 } from "node:os";
|
|
13529
|
-
import { join as
|
|
13718
|
+
import { join as join31, resolve as resolve7 } from "node:path";
|
|
13530
13719
|
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
13531
13720
|
import { create as create6 } from "tar";
|
|
13532
13721
|
|
|
13533
13722
|
// ../daemon/src/lib/daemon-liveness.ts
|
|
13534
13723
|
import { mkdirSync as mkdirSync11, readFileSync as readFileSync11, rmSync as rmSync12, writeFileSync as writeFileSync10 } from "node:fs";
|
|
13535
|
-
import { join as
|
|
13724
|
+
import { join as join30 } from "node:path";
|
|
13536
13725
|
var DAEMON_PID_FILE = "daemon.pid";
|
|
13537
13726
|
function runningDaemonPid(home) {
|
|
13538
13727
|
let pid;
|
|
13539
13728
|
try {
|
|
13540
|
-
pid = Number.parseInt(readFileSync11(
|
|
13729
|
+
pid = Number.parseInt(readFileSync11(join30(home, DAEMON_PID_FILE), "utf8"), 10);
|
|
13541
13730
|
} catch (error) {
|
|
13542
13731
|
if (error.code === "ENOENT") return null;
|
|
13543
13732
|
throw error;
|
|
@@ -13554,12 +13743,12 @@ function assertDaemonStopped(home) {
|
|
|
13554
13743
|
const pid = runningDaemonPid(home);
|
|
13555
13744
|
if (pid !== null) {
|
|
13556
13745
|
throw new Error(
|
|
13557
|
-
`a bazilion daemon (pid ${pid}) is running on ${home}; stop it first (if none is running, delete ${
|
|
13746
|
+
`a bazilion daemon (pid ${pid}) is running on ${home}; stop it first (if none is running, delete ${join30(home, DAEMON_PID_FILE)})`
|
|
13558
13747
|
);
|
|
13559
13748
|
}
|
|
13560
13749
|
}
|
|
13561
13750
|
function claimDaemonPidFile(home) {
|
|
13562
|
-
const path =
|
|
13751
|
+
const path = join30(home, DAEMON_PID_FILE);
|
|
13563
13752
|
const content = `${process.pid}
|
|
13564
13753
|
`;
|
|
13565
13754
|
mkdirSync11(home, { recursive: true });
|
|
@@ -13588,10 +13777,10 @@ function createBackupSnapshot(db) {
|
|
|
13588
13777
|
return snapshot2;
|
|
13589
13778
|
}
|
|
13590
13779
|
async function takeSnapshot(db) {
|
|
13591
|
-
const directory = mkdtempSync3(
|
|
13780
|
+
const directory = mkdtempSync3(join31(tmpdir3(), "bazilion-backup-"));
|
|
13592
13781
|
const cleanup = () => rmSync13(directory, { recursive: true, force: true });
|
|
13593
13782
|
try {
|
|
13594
|
-
const database =
|
|
13783
|
+
const database = join31(directory, "bazilion.snapshot");
|
|
13595
13784
|
await db.backupTo(database);
|
|
13596
13785
|
const snapshot2 = new DatabaseSync2(database, { readOnly: true });
|
|
13597
13786
|
try {
|
|
@@ -13690,7 +13879,7 @@ miscRouter.get("/health/details", async (c) => {
|
|
|
13690
13879
|
} catch {
|
|
13691
13880
|
}
|
|
13692
13881
|
}
|
|
13693
|
-
const openclawSkillsDir =
|
|
13882
|
+
const openclawSkillsDir = join32(homedir4(), ".openclaw", "skills");
|
|
13694
13883
|
const providerSection = {
|
|
13695
13884
|
// Hosted providers with credentials; local servers are reported below.
|
|
13696
13885
|
configured: PROVIDERS.filter(
|
|
@@ -14099,7 +14288,7 @@ notificationsRouter.put("/", async (c) => {
|
|
|
14099
14288
|
|
|
14100
14289
|
// ../daemon/src/routes/profiles.ts
|
|
14101
14290
|
import { existsSync as existsSync18, readFileSync as readFileSync12, writeFileSync as writeFileSync11 } from "node:fs";
|
|
14102
|
-
import { join as
|
|
14291
|
+
import { join as join33 } from "node:path";
|
|
14103
14292
|
var profilesRouter = newRouter();
|
|
14104
14293
|
profilesRouter.get("/", (c) => {
|
|
14105
14294
|
const { db } = getCtx();
|
|
@@ -14182,7 +14371,7 @@ function profileFile(c) {
|
|
|
14182
14371
|
if (!PROFILE_FILES.includes(file)) {
|
|
14183
14372
|
return c.json({ error: `unsupported file: ${file}` }, 400);
|
|
14184
14373
|
}
|
|
14185
|
-
return
|
|
14374
|
+
return join33(paths.profilesDir, id, file);
|
|
14186
14375
|
}
|
|
14187
14376
|
profilesRouter.get("/:id/files/:file", (c) => {
|
|
14188
14377
|
const path = profileFile(c);
|
|
@@ -14222,8 +14411,97 @@ questionsRouter.post("/:agentId/questions/:id/answer", async (c) => {
|
|
|
14222
14411
|
return c.json({ ok: true });
|
|
14223
14412
|
});
|
|
14224
14413
|
|
|
14414
|
+
// ../daemon/src/lib/zip.ts
|
|
14415
|
+
import { crc32 } from "node:zlib";
|
|
14416
|
+
var UTF8_NAMES = 2048;
|
|
14417
|
+
function dosDateTime(epochMs) {
|
|
14418
|
+
const d = new Date(epochMs);
|
|
14419
|
+
const year = Math.max(1980, d.getFullYear());
|
|
14420
|
+
return {
|
|
14421
|
+
time: d.getHours() << 11 | d.getMinutes() << 5 | d.getSeconds() >> 1,
|
|
14422
|
+
date: year - 1980 << 9 | d.getMonth() + 1 << 5 | d.getDate()
|
|
14423
|
+
};
|
|
14424
|
+
}
|
|
14425
|
+
function uniqueNames(names) {
|
|
14426
|
+
const seen = /* @__PURE__ */ new Map();
|
|
14427
|
+
return names.map((name) => {
|
|
14428
|
+
const count = (seen.get(name) ?? 0) + 1;
|
|
14429
|
+
seen.set(name, count);
|
|
14430
|
+
if (count === 1) return name;
|
|
14431
|
+
const dot = name.lastIndexOf(".");
|
|
14432
|
+
return dot > 0 ? `${name.slice(0, dot)} (${count})${name.slice(dot)}` : `${name} (${count})`;
|
|
14433
|
+
});
|
|
14434
|
+
}
|
|
14435
|
+
function localHeader(name, bytes, crc, epochMs) {
|
|
14436
|
+
const { time, date } = dosDateTime(epochMs);
|
|
14437
|
+
const header = Buffer.alloc(30);
|
|
14438
|
+
header.writeUInt32LE(67324752, 0);
|
|
14439
|
+
header.writeUInt16LE(20, 4);
|
|
14440
|
+
header.writeUInt16LE(UTF8_NAMES, 6);
|
|
14441
|
+
header.writeUInt16LE(0, 8);
|
|
14442
|
+
header.writeUInt16LE(time, 10);
|
|
14443
|
+
header.writeUInt16LE(date, 12);
|
|
14444
|
+
header.writeUInt32LE(crc, 14);
|
|
14445
|
+
header.writeUInt32LE(bytes.byteLength, 18);
|
|
14446
|
+
header.writeUInt32LE(bytes.byteLength, 22);
|
|
14447
|
+
header.writeUInt16LE(name.byteLength, 26);
|
|
14448
|
+
header.writeUInt16LE(0, 28);
|
|
14449
|
+
return Buffer.concat([header, name]);
|
|
14450
|
+
}
|
|
14451
|
+
function centralHeader(name, size, crc, epochMs, offset) {
|
|
14452
|
+
const { time, date } = dosDateTime(epochMs);
|
|
14453
|
+
const header = Buffer.alloc(46);
|
|
14454
|
+
header.writeUInt32LE(33639248, 0);
|
|
14455
|
+
header.writeUInt16LE(20, 4);
|
|
14456
|
+
header.writeUInt16LE(20, 6);
|
|
14457
|
+
header.writeUInt16LE(UTF8_NAMES, 8);
|
|
14458
|
+
header.writeUInt16LE(0, 10);
|
|
14459
|
+
header.writeUInt16LE(time, 12);
|
|
14460
|
+
header.writeUInt16LE(date, 14);
|
|
14461
|
+
header.writeUInt32LE(crc, 16);
|
|
14462
|
+
header.writeUInt32LE(size, 20);
|
|
14463
|
+
header.writeUInt32LE(size, 24);
|
|
14464
|
+
header.writeUInt16LE(name.byteLength, 28);
|
|
14465
|
+
header.writeUInt32LE(offset, 42);
|
|
14466
|
+
return Buffer.concat([header, name]);
|
|
14467
|
+
}
|
|
14468
|
+
function zipStream(entries) {
|
|
14469
|
+
const names = uniqueNames(entries.map((entry) => entry.name));
|
|
14470
|
+
const directory = [];
|
|
14471
|
+
let offset = 0;
|
|
14472
|
+
let index = 0;
|
|
14473
|
+
return new ReadableStream({
|
|
14474
|
+
pull(controller) {
|
|
14475
|
+
const entry = entries[index];
|
|
14476
|
+
if (entry) {
|
|
14477
|
+
const name = Buffer.from(names[index] ?? entry.name, "utf8");
|
|
14478
|
+
const bytes = entry.read();
|
|
14479
|
+
const crc = crc32(bytes);
|
|
14480
|
+
const header = localHeader(name, bytes, crc, entry.modifiedAt);
|
|
14481
|
+
directory.push(centralHeader(name, bytes.byteLength, crc, entry.modifiedAt, offset));
|
|
14482
|
+
offset += header.byteLength + bytes.byteLength;
|
|
14483
|
+
index++;
|
|
14484
|
+
controller.enqueue(header);
|
|
14485
|
+
controller.enqueue(bytes);
|
|
14486
|
+
return;
|
|
14487
|
+
}
|
|
14488
|
+
const central = Buffer.concat(directory);
|
|
14489
|
+
const end = Buffer.alloc(22);
|
|
14490
|
+
end.writeUInt32LE(101010256, 0);
|
|
14491
|
+
end.writeUInt16LE(entries.length, 8);
|
|
14492
|
+
end.writeUInt16LE(entries.length, 10);
|
|
14493
|
+
end.writeUInt32LE(central.byteLength, 12);
|
|
14494
|
+
end.writeUInt32LE(offset, 16);
|
|
14495
|
+
controller.enqueue(central);
|
|
14496
|
+
controller.enqueue(end);
|
|
14497
|
+
controller.close();
|
|
14498
|
+
}
|
|
14499
|
+
});
|
|
14500
|
+
}
|
|
14501
|
+
|
|
14225
14502
|
// ../daemon/src/routes/results.ts
|
|
14226
14503
|
var resultsRouter = newRouter();
|
|
14504
|
+
var MAX_ARCHIVE_BYTES = 512 * 1024 * 1024;
|
|
14227
14505
|
resultsRouter.use("*", async (c, next) => {
|
|
14228
14506
|
c.header("X-Content-Type-Options", "nosniff");
|
|
14229
14507
|
await next();
|
|
@@ -14238,11 +14516,45 @@ resultsRouter.get("/", (c) => {
|
|
|
14238
14516
|
list12(getCtx().db, {
|
|
14239
14517
|
teamId: c.req.query("teamId"),
|
|
14240
14518
|
agentId: c.req.query("agentId"),
|
|
14519
|
+
sessionId: c.req.query("sessionId"),
|
|
14241
14520
|
limit,
|
|
14242
14521
|
offset
|
|
14243
14522
|
})
|
|
14244
14523
|
);
|
|
14245
14524
|
});
|
|
14525
|
+
resultsRouter.get("/archive", (c) => {
|
|
14526
|
+
const db = getCtx().db;
|
|
14527
|
+
const filter = {
|
|
14528
|
+
teamId: c.req.query("teamId"),
|
|
14529
|
+
agentId: c.req.query("agentId"),
|
|
14530
|
+
sessionId: c.req.query("sessionId")
|
|
14531
|
+
};
|
|
14532
|
+
if (!filter.teamId && !filter.agentId && !filter.sessionId) {
|
|
14533
|
+
return c.json({ error: "teamId, agentId or sessionId is required" }, 400);
|
|
14534
|
+
}
|
|
14535
|
+
const selected = listForArchive(db, filter, MAX_ARCHIVE_BYTES);
|
|
14536
|
+
if (selected.truncated) {
|
|
14537
|
+
return c.json(
|
|
14538
|
+
{ error: "These files are larger than 512 MiB together. Narrow the selection." },
|
|
14539
|
+
413
|
|
14540
|
+
);
|
|
14541
|
+
}
|
|
14542
|
+
if (selected.results.length === 0) return c.json({ error: "No saved files match" }, 404);
|
|
14543
|
+
const name = `bazilion-${filter.teamId ?? "files"}.zip`.replace(/[^\w.-]/g, "-");
|
|
14544
|
+
c.header("Content-Type", "application/zip");
|
|
14545
|
+
c.header("Content-Disposition", `attachment; filename="${name}"`);
|
|
14546
|
+
c.header("Content-Security-Policy", "default-src 'none'; sandbox");
|
|
14547
|
+
return c.body(
|
|
14548
|
+
zipStream(
|
|
14549
|
+
selected.results.map((result) => ({
|
|
14550
|
+
name: result.name,
|
|
14551
|
+
modifiedAt: result.createdAt,
|
|
14552
|
+
// Read when the stream reaches the file; a failed integrity check ends the download.
|
|
14553
|
+
read: () => new Uint8Array(read(db, result.id))
|
|
14554
|
+
}))
|
|
14555
|
+
)
|
|
14556
|
+
);
|
|
14557
|
+
});
|
|
14246
14558
|
resultsRouter.get("/:id", (c) => {
|
|
14247
14559
|
const result = get17(getCtx().db, c.req.param("id"));
|
|
14248
14560
|
if (!result) return c.json({ error: "Result not found" }, 404);
|
|
@@ -14292,6 +14604,7 @@ resultsRouter.get("/:id/preview", (c) => {
|
|
|
14292
14604
|
return c.json({ error: "File content does not match its image type. Use Download." }, 415);
|
|
14293
14605
|
c.header("Content-Type", text4 ? "text/plain; charset=utf-8" : result.mimeType);
|
|
14294
14606
|
c.header("Content-Security-Policy", "default-src 'none'; sandbox");
|
|
14607
|
+
c.header("Cache-Control", "private, max-age=3600");
|
|
14295
14608
|
return c.body(new Uint8Array(bytes));
|
|
14296
14609
|
} catch {
|
|
14297
14610
|
return c.json({ error: "Saved file failed integrity verification" }, 409);
|
|
@@ -14323,7 +14636,7 @@ shellApprovalsRouter.post("/:id", async (c) => {
|
|
|
14323
14636
|
// ../daemon/src/routes/skills.ts
|
|
14324
14637
|
import { mkdtempSync as mkdtempSync4, rmSync as rmSync14, writeFileSync as writeFileSync12 } from "node:fs";
|
|
14325
14638
|
import { homedir as homedir5, tmpdir as tmpdir4 } from "node:os";
|
|
14326
|
-
import { join as
|
|
14639
|
+
import { join as join34 } from "node:path";
|
|
14327
14640
|
var MAX_ZIP_BYTES = 50 * 1024 * 1024;
|
|
14328
14641
|
var skillsRouter = newRouter();
|
|
14329
14642
|
skillsRouter.get("/", (c) => {
|
|
@@ -14416,8 +14729,8 @@ async function parseImportInput(request) {
|
|
|
14416
14729
|
if (!filename.toLowerCase().endsWith(".zip")) {
|
|
14417
14730
|
throw new Error("uploaded file must be a .zip archive");
|
|
14418
14731
|
}
|
|
14419
|
-
const tmpDir = mkdtempSync4(
|
|
14420
|
-
const zipPath =
|
|
14732
|
+
const tmpDir = mkdtempSync4(join34(tmpdir4(), "bazilion-skill-upload-"));
|
|
14733
|
+
const zipPath = join34(tmpDir, filename.replace(/[^\w.-]+/g, "_"));
|
|
14421
14734
|
const buf = Buffer.from(await file.arrayBuffer());
|
|
14422
14735
|
writeFileSync12(zipPath, buf);
|
|
14423
14736
|
const forceField = form.get("force");
|
|
@@ -14433,7 +14746,7 @@ async function parseImportInput(request) {
|
|
|
14433
14746
|
const { source } = body;
|
|
14434
14747
|
if (typeof source !== "string" || !source) throw new Error("source is required");
|
|
14435
14748
|
return {
|
|
14436
|
-
source: source === "openclaw" ?
|
|
14749
|
+
source: source === "openclaw" ? join34(homedir5(), ".openclaw", "skills") : source,
|
|
14437
14750
|
force: Boolean(body.force),
|
|
14438
14751
|
tempZipPath: null,
|
|
14439
14752
|
sourceLabel: source
|
|
@@ -14503,7 +14816,7 @@ teamCodingEnvironmentRouter.put("/:id/coding-environment", async (c) => {
|
|
|
14503
14816
|
});
|
|
14504
14817
|
|
|
14505
14818
|
// ../daemon/src/routes/team-memory.ts
|
|
14506
|
-
import { join as
|
|
14819
|
+
import { join as join35 } from "node:path";
|
|
14507
14820
|
var teamMemoryRouter = newRouter();
|
|
14508
14821
|
teamMemoryRouter.onError((error, c) => {
|
|
14509
14822
|
const safe = sanitizeNativeModuleError(error, { subject: "Bazilion memory" });
|
|
@@ -14511,7 +14824,7 @@ teamMemoryRouter.onError((error, c) => {
|
|
|
14511
14824
|
return onRouteError(safe, c);
|
|
14512
14825
|
});
|
|
14513
14826
|
async function openMemory(c) {
|
|
14514
|
-
const mem = qmdBackend(
|
|
14827
|
+
const mem = qmdBackend(join35(routeTeam(c).path, "memory"));
|
|
14515
14828
|
await mem.init();
|
|
14516
14829
|
return mem;
|
|
14517
14830
|
}
|
|
@@ -14577,7 +14890,7 @@ import {
|
|
|
14577
14890
|
readSync as readSync3,
|
|
14578
14891
|
realpathSync as realpathSync7
|
|
14579
14892
|
} from "node:fs";
|
|
14580
|
-
import { join as
|
|
14893
|
+
import { join as join36 } from "node:path";
|
|
14581
14894
|
var hash = (value) => createHash6("sha256").update(value).digest("hex");
|
|
14582
14895
|
var ContextReadError = class extends Error {
|
|
14583
14896
|
code;
|
|
@@ -14615,12 +14928,12 @@ var ContextDirectory = class _ContextDirectory {
|
|
|
14615
14928
|
this.parent = parent;
|
|
14616
14929
|
if (parent) component(registeredPath);
|
|
14617
14930
|
parent?.assertOpen();
|
|
14618
|
-
const canonicalPath = parent ?
|
|
14931
|
+
const canonicalPath = parent ? join36(parent.canonicalPath, registeredPath) : realpathSync7(registeredPath);
|
|
14619
14932
|
this.canonicalPath = canonicalPath;
|
|
14620
14933
|
let fd;
|
|
14621
14934
|
try {
|
|
14622
14935
|
fd = openSync6(
|
|
14623
|
-
parent ?
|
|
14936
|
+
parent ? join36(parent.path, registeredPath) : canonicalPath,
|
|
14624
14937
|
constants7.O_RDONLY | constants7.O_DIRECTORY | constants7.O_NOFOLLOW
|
|
14625
14938
|
);
|
|
14626
14939
|
const stat = fstatSync6(fd, { bigint: true });
|
|
@@ -14658,7 +14971,7 @@ var ContextDirectory = class _ContextDirectory {
|
|
|
14658
14971
|
component(name);
|
|
14659
14972
|
this.assertOpen();
|
|
14660
14973
|
try {
|
|
14661
|
-
return lstatSync6(
|
|
14974
|
+
return lstatSync6(join36(this.path, name));
|
|
14662
14975
|
} catch (error) {
|
|
14663
14976
|
if (error.code === "ENOENT") return null;
|
|
14664
14977
|
throw new ContextReadError("unreadable");
|
|
@@ -14666,7 +14979,7 @@ var ContextDirectory = class _ContextDirectory {
|
|
|
14666
14979
|
}
|
|
14667
14980
|
observe(name) {
|
|
14668
14981
|
try {
|
|
14669
|
-
return lstatSync6(
|
|
14982
|
+
return lstatSync6(join36(this.path, name), { bigint: true });
|
|
14670
14983
|
} catch (error) {
|
|
14671
14984
|
if (error.code === "ENOENT") return null;
|
|
14672
14985
|
throw new ContextReadError("unreadable");
|
|
@@ -14707,7 +15020,7 @@ var ContextDirectory = class _ContextDirectory {
|
|
|
14707
15020
|
let fd;
|
|
14708
15021
|
try {
|
|
14709
15022
|
fd = openSync6(
|
|
14710
|
-
|
|
15023
|
+
join36(this.path, name),
|
|
14711
15024
|
constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK
|
|
14712
15025
|
);
|
|
14713
15026
|
const before = fstatSync6(fd, { bigint: true });
|
|
@@ -14733,7 +15046,7 @@ var ContextDirectory = class _ContextDirectory {
|
|
|
14733
15046
|
}
|
|
14734
15047
|
validate(skipGit = false, names) {
|
|
14735
15048
|
this.assertOpen();
|
|
14736
|
-
const currentPath = this.parent ?
|
|
15049
|
+
const currentPath = this.parent ? join36(this.parent.path, this.registeredPath) : realpathSync7(this.registeredPath);
|
|
14737
15050
|
const stat = lstatSync6(currentPath, { bigint: true });
|
|
14738
15051
|
if (!stat.isDirectory() || identity(stat) !== identity(this.originalIdentity))
|
|
14739
15052
|
throw new ContextReadError("root_changed");
|
|
@@ -15161,7 +15474,7 @@ async function readOrNull(captured, args) {
|
|
|
15161
15474
|
import { execFile } from "node:child_process";
|
|
15162
15475
|
import { mkdirSync as mkdirSync12, mkdtempSync as mkdtempSync5, rmSync as rmSync15, writeFileSync as writeFileSync13 } from "node:fs";
|
|
15163
15476
|
import { tmpdir as tmpdir5 } from "node:os";
|
|
15164
|
-
import { join as
|
|
15477
|
+
import { join as join37 } from "node:path";
|
|
15165
15478
|
var INSPECTION_BUDGET_MS = 5e3;
|
|
15166
15479
|
var METADATA_BUDGET_MS = 2500;
|
|
15167
15480
|
var METADATA_BYTES = 64 * 1024 * 1024;
|
|
@@ -15190,7 +15503,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
|
|
|
15190
15503
|
const dir = git.directory("info");
|
|
15191
15504
|
if (dir.entry("sparse-checkout")) throw new ContextReadError("unsupported_git_metadata");
|
|
15192
15505
|
}
|
|
15193
|
-
const scratch = mkdtempSync5(
|
|
15506
|
+
const scratch = mkdtempSync5(join37(tmpdir5(), "bazilion-context-git-"));
|
|
15194
15507
|
let cleaned = false;
|
|
15195
15508
|
const cleanup = () => {
|
|
15196
15509
|
if (cleaned) return;
|
|
@@ -15201,7 +15514,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
|
|
|
15201
15514
|
if (Date.now() - start2 >= budgetMs) throw new ContextReadError("git_timeout");
|
|
15202
15515
|
};
|
|
15203
15516
|
try {
|
|
15204
|
-
const rawGit = (args) => new Promise((
|
|
15517
|
+
const rawGit = (args) => new Promise((resolve9, reject2) => {
|
|
15205
15518
|
if (cleaned) throw new ContextReadError("unreadable");
|
|
15206
15519
|
checkBudget();
|
|
15207
15520
|
execFile(
|
|
@@ -15224,7 +15537,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
|
|
|
15224
15537
|
maxBuffer: RUN_MAX_BUFFER,
|
|
15225
15538
|
encoding: "utf8"
|
|
15226
15539
|
},
|
|
15227
|
-
(error, stdout) => error ? reject2(error) :
|
|
15540
|
+
(error, stdout) => error ? reject2(error) : resolve9(stdout)
|
|
15228
15541
|
);
|
|
15229
15542
|
});
|
|
15230
15543
|
const inspectionArgs = (args) => [
|
|
@@ -15251,7 +15564,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
|
|
|
15251
15564
|
if (capturedConfig) {
|
|
15252
15565
|
bytes += capturedConfig.length;
|
|
15253
15566
|
count++;
|
|
15254
|
-
const configPath =
|
|
15567
|
+
const configPath = join37(scratch, "captured-config");
|
|
15255
15568
|
writeFileSync13(configPath, capturedConfig, { mode: 384 });
|
|
15256
15569
|
const config = await rawGit([
|
|
15257
15570
|
"config",
|
|
@@ -15304,8 +15617,8 @@ objectformat = ${value}`
|
|
|
15304
15617
|
const exclude = git.directory("info").read("exclude", METADATA_READ);
|
|
15305
15618
|
if (exclude) {
|
|
15306
15619
|
bytes += exclude.length;
|
|
15307
|
-
mkdirSync12(
|
|
15308
|
-
writeFileSync13(
|
|
15620
|
+
mkdirSync12(join37(scratch, "info"), { mode: 448 });
|
|
15621
|
+
writeFileSync13(join37(scratch, "info", "exclude"), exclude, { mode: 384 });
|
|
15309
15622
|
}
|
|
15310
15623
|
}
|
|
15311
15624
|
const copy = (source, destination, depth) => {
|
|
@@ -15318,13 +15631,13 @@ objectformat = ${value}`
|
|
|
15318
15631
|
if (name === "alternates" || name === "http-alternates")
|
|
15319
15632
|
throw new ContextReadError("unsupported_git_metadata");
|
|
15320
15633
|
if (entry.isDirectory()) {
|
|
15321
|
-
mkdirSync12(
|
|
15322
|
-
copy(source.directory(name),
|
|
15634
|
+
mkdirSync12(join37(destination, name), { mode: 448 });
|
|
15635
|
+
copy(source.directory(name), join37(destination, name), depth + 1);
|
|
15323
15636
|
} else {
|
|
15324
15637
|
const content = source.read(name, METADATA_BYTES - bytes);
|
|
15325
15638
|
if (!content) throw new ContextReadError("source_changed");
|
|
15326
15639
|
bytes += content.length;
|
|
15327
|
-
writeFileSync13(
|
|
15640
|
+
writeFileSync13(join37(destination, name), content, { mode: 384 });
|
|
15328
15641
|
}
|
|
15329
15642
|
}
|
|
15330
15643
|
};
|
|
@@ -15333,16 +15646,16 @@ objectformat = ${value}`
|
|
|
15333
15646
|
if (content) {
|
|
15334
15647
|
count++;
|
|
15335
15648
|
bytes += content.length;
|
|
15336
|
-
writeFileSync13(
|
|
15649
|
+
writeFileSync13(join37(scratch, name), content, { mode: 384 });
|
|
15337
15650
|
}
|
|
15338
15651
|
}
|
|
15339
15652
|
for (const name of ["refs", "objects"]) {
|
|
15340
|
-
mkdirSync12(
|
|
15341
|
-
if (git.entry(name)) copy(git.directory(name),
|
|
15653
|
+
mkdirSync12(join37(scratch, name), { mode: 448 });
|
|
15654
|
+
if (git.entry(name)) copy(git.directory(name), join37(scratch, name), 0);
|
|
15342
15655
|
}
|
|
15343
15656
|
if (git.list().some((name) => name.startsWith("sharedindex.")))
|
|
15344
15657
|
throw new ContextReadError("unsupported_git_metadata");
|
|
15345
|
-
writeFileSync13(
|
|
15658
|
+
writeFileSync13(join37(scratch, "config"), `${configLines.join("\n")}
|
|
15346
15659
|
`, { mode: 384 });
|
|
15347
15660
|
const validate2 = () => git.validate();
|
|
15348
15661
|
validate2();
|
|
@@ -15353,6 +15666,77 @@ objectformat = ${value}`
|
|
|
15353
15666
|
}
|
|
15354
15667
|
}
|
|
15355
15668
|
|
|
15669
|
+
// ../daemon/src/lib/git-review/authors.ts
|
|
15670
|
+
import { realpathSync as realpathSync8 } from "node:fs";
|
|
15671
|
+
import { isAbsolute as isAbsolute7, join as join38, relative as relative5, resolve as resolve8, sep as sep6 } from "node:path";
|
|
15672
|
+
var FILE_TOOLS = /* @__PURE__ */ new Set(["write", "edit"]);
|
|
15673
|
+
var CONVERSATIONS_PER_AGENT = 5;
|
|
15674
|
+
var SANDBOX_ROOT = "/workspace";
|
|
15675
|
+
function workspacePath(path, cwd, roots) {
|
|
15676
|
+
const absolute = isAbsolute7(path) ? path : resolve8(cwd, path);
|
|
15677
|
+
for (const root of roots) {
|
|
15678
|
+
const inside = relative5(root, absolute);
|
|
15679
|
+
if (inside && !inside.startsWith("..") && !isAbsolute7(inside)) {
|
|
15680
|
+
return inside.split(sep6).join("/");
|
|
15681
|
+
}
|
|
15682
|
+
}
|
|
15683
|
+
return null;
|
|
15684
|
+
}
|
|
15685
|
+
function readChangeAuthors(db, paths, team, changedPaths) {
|
|
15686
|
+
const wanted = new Set(changedPaths);
|
|
15687
|
+
const authors = {};
|
|
15688
|
+
if (wanted.size === 0) return authors;
|
|
15689
|
+
const roots = [team.path, SANDBOX_ROOT];
|
|
15690
|
+
try {
|
|
15691
|
+
roots.push(realpathSync8(team.path));
|
|
15692
|
+
} catch {
|
|
15693
|
+
}
|
|
15694
|
+
const members = list(db, { includeArchived: true }).filter((agent) => agent.teamId === team.id);
|
|
15695
|
+
for (const agent of members) {
|
|
15696
|
+
const directory = join38(paths.agentDir(agent.id), "sessions");
|
|
15697
|
+
const recent = list11(db, agent.id, CONVERSATIONS_PER_AGENT, 0).conversations;
|
|
15698
|
+
for (const conversation of recent) {
|
|
15699
|
+
let lines;
|
|
15700
|
+
try {
|
|
15701
|
+
lines = readSessionFile(directory, conversation.id);
|
|
15702
|
+
} catch {
|
|
15703
|
+
continue;
|
|
15704
|
+
}
|
|
15705
|
+
const cwd = lines[0]?.cwd ?? team.path;
|
|
15706
|
+
const failed = /* @__PURE__ */ new Set();
|
|
15707
|
+
for (const line of lines) {
|
|
15708
|
+
const message = line.message;
|
|
15709
|
+
if (message?.role === "toolResult" && message.isError && message.toolCallId) {
|
|
15710
|
+
failed.add(message.toolCallId);
|
|
15711
|
+
}
|
|
15712
|
+
}
|
|
15713
|
+
for (const line of lines) {
|
|
15714
|
+
if (line.type !== "message" || line.message?.role !== "assistant") continue;
|
|
15715
|
+
if (!Array.isArray(line.message.content)) continue;
|
|
15716
|
+
const at = Date.parse(line.timestamp ?? "");
|
|
15717
|
+
if (!Number.isFinite(at)) continue;
|
|
15718
|
+
for (const part of line.message.content) {
|
|
15719
|
+
if (part?.type !== "toolCall" || !part.name || !FILE_TOOLS.has(part.name)) continue;
|
|
15720
|
+
if (part.id && failed.has(part.id)) continue;
|
|
15721
|
+
const target = part.arguments?.path;
|
|
15722
|
+
if (typeof target !== "string") continue;
|
|
15723
|
+
const path = workspacePath(target, cwd, roots);
|
|
15724
|
+
if (!path || !wanted.has(path)) continue;
|
|
15725
|
+
const known = authors[path];
|
|
15726
|
+
if (known && known.at >= at) continue;
|
|
15727
|
+
authors[path] = {
|
|
15728
|
+
agentId: agent.id,
|
|
15729
|
+
agentName: agent.name,
|
|
15730
|
+
conversationId: conversation.id,
|
|
15731
|
+
at
|
|
15732
|
+
};
|
|
15733
|
+
}
|
|
15734
|
+
}
|
|
15735
|
+
}
|
|
15736
|
+
}
|
|
15737
|
+
return authors;
|
|
15738
|
+
}
|
|
15739
|
+
|
|
15356
15740
|
// ../daemon/src/lib/git-review/service.ts
|
|
15357
15741
|
var ReviewUnavailableError = class extends DomainError {
|
|
15358
15742
|
constructor(code, message) {
|
|
@@ -15405,12 +15789,20 @@ async function readTeamReview(db, paths, teamId, input = {}) {
|
|
|
15405
15789
|
const listed = await listChanges(captured, base, identity2, input.limits);
|
|
15406
15790
|
return input.patches ? attachPatches(captured, listed, input.limits, input.patchPath) : listed;
|
|
15407
15791
|
});
|
|
15408
|
-
return { teamId: team.id, changes };
|
|
15792
|
+
if (!input.authors) return { teamId: team.id, changes };
|
|
15793
|
+
const changedPaths = changes.changes.map((change) => change.path);
|
|
15794
|
+
return {
|
|
15795
|
+
teamId: team.id,
|
|
15796
|
+
changes,
|
|
15797
|
+
authors: readChangeAuthors(db, paths, team, changedPaths)
|
|
15798
|
+
};
|
|
15409
15799
|
}
|
|
15410
15800
|
|
|
15411
15801
|
// ../daemon/src/lib/git-review/feedback.ts
|
|
15412
15802
|
var FEEDBACK_NOTE_CHARS = 2e3;
|
|
15803
|
+
var FEEDBACK_COMMENTS = 20;
|
|
15413
15804
|
var EXCERPT_CHARS = 4e3;
|
|
15805
|
+
var EXCERPT_CHARS_EACH = 1600;
|
|
15414
15806
|
async function queueReviewFeedback(db, paths, teamId, request) {
|
|
15415
15807
|
const team = requireTeam(db, paths, teamId);
|
|
15416
15808
|
const agent = get(db, request.agentId);
|
|
@@ -15419,31 +15811,77 @@ async function queueReviewFeedback(db, paths, teamId, request) {
|
|
|
15419
15811
|
const message = await withRepository(team.path, async (captured) => {
|
|
15420
15812
|
const base = await resolveComparisonBase(captured, request.base ?? "HEAD");
|
|
15421
15813
|
const listed = await listChanges(captured, base, await readRepositoryIdentity(captured));
|
|
15422
|
-
const
|
|
15423
|
-
|
|
15424
|
-
|
|
15425
|
-
|
|
15814
|
+
const changes = /* @__PURE__ */ new Map();
|
|
15815
|
+
for (const { path } of request.comments) {
|
|
15816
|
+
if (changes.has(path)) continue;
|
|
15817
|
+
const withPatch = await attachPatches(captured, listed, void 0, path);
|
|
15818
|
+
const change = withPatch.changes.find((entry) => entry.path === path);
|
|
15819
|
+
if (!change) throw new DomainError(400, "That path is not changed since this baseline.");
|
|
15820
|
+
changes.set(path, change);
|
|
15821
|
+
}
|
|
15822
|
+
return composeFeedbackMessage(request, changes, base);
|
|
15426
15823
|
});
|
|
15427
15824
|
const item = await enqueueUserInput(agent.id, { message, attachments: [] }, { db, paths });
|
|
15428
15825
|
return { message, item };
|
|
15429
15826
|
}
|
|
15430
|
-
function
|
|
15827
|
+
function hunkForLine(patch, line) {
|
|
15828
|
+
const lines = patch.split("\n");
|
|
15829
|
+
const starts = [];
|
|
15830
|
+
lines.forEach((text4, index) => {
|
|
15831
|
+
if (text4.startsWith("@@")) starts.push(index);
|
|
15832
|
+
});
|
|
15833
|
+
for (const [position, start2] of starts.entries()) {
|
|
15834
|
+
const header = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(lines[start2] ?? "");
|
|
15835
|
+
if (!header) continue;
|
|
15836
|
+
const first = Number(header[1]);
|
|
15837
|
+
const count = header[2] === void 0 ? 1 : Number(header[2]);
|
|
15838
|
+
if (line < first || line >= first + Math.max(count, 1)) continue;
|
|
15839
|
+
return lines.slice(start2, starts[position + 1] ?? lines.length).join("\n");
|
|
15840
|
+
}
|
|
15841
|
+
return null;
|
|
15842
|
+
}
|
|
15843
|
+
function place(comment, change) {
|
|
15431
15844
|
const file = change.previousPath ? `${change.previousPath} -> ${change.path}` : change.path;
|
|
15432
|
-
|
|
15433
|
-
|
|
15434
|
-
|
|
15435
|
-
const
|
|
15436
|
-
|
|
15845
|
+
return comment.line === void 0 ? file : `${file}, line ${comment.line}`;
|
|
15846
|
+
}
|
|
15847
|
+
function commentBody(comment, change, room) {
|
|
15848
|
+
const lines = [];
|
|
15849
|
+
const note = comment.note?.trim();
|
|
15850
|
+
if (note) lines.push("", note.slice(0, FEEDBACK_NOTE_CHARS));
|
|
15437
15851
|
if (change.patch === null) {
|
|
15438
15852
|
lines.push("", `No diff text (${change.contentOmitted ?? "unavailable"}).`);
|
|
15439
|
-
|
|
15440
|
-
|
|
15441
|
-
|
|
15442
|
-
|
|
15443
|
-
|
|
15444
|
-
|
|
15445
|
-
|
|
15853
|
+
return lines;
|
|
15854
|
+
}
|
|
15855
|
+
const source = comment.line === void 0 ? change.patch : hunkForLine(change.patch, comment.line) ?? change.patch;
|
|
15856
|
+
const excerpt = source.slice(0, room);
|
|
15857
|
+
const fence = "`".repeat(
|
|
15858
|
+
Math.max(3, ...(excerpt.match(/`+/g) ?? []).map((run) => run.length + 1))
|
|
15859
|
+
);
|
|
15860
|
+
lines.push("", `${fence}diff`, excerpt.trimEnd(), fence);
|
|
15861
|
+
if (source.length > room) lines.push("(diff excerpt truncated)");
|
|
15862
|
+
return lines;
|
|
15863
|
+
}
|
|
15864
|
+
function composeFeedbackMessage(request, changes, base) {
|
|
15865
|
+
const since = `since ${base.requestedRef}, ${base.resolvedOid.slice(0, 12)}`;
|
|
15866
|
+
const overall = request.note?.trim();
|
|
15867
|
+
const [only] = request.comments;
|
|
15868
|
+
if (request.comments.length === 1 && only && !overall) {
|
|
15869
|
+
const change = changes.get(only.path);
|
|
15870
|
+
return [
|
|
15871
|
+
`Review feedback on ${place(only, change)} (${change.status} ${since}).`,
|
|
15872
|
+
...commentBody(only, change, EXCERPT_CHARS)
|
|
15873
|
+
].join("\n");
|
|
15446
15874
|
}
|
|
15875
|
+
const lines = [`Review feedback: ${request.comments.length} comments (${since}).`];
|
|
15876
|
+
if (overall) lines.push("", overall.slice(0, FEEDBACK_NOTE_CHARS));
|
|
15877
|
+
request.comments.forEach((comment, index) => {
|
|
15878
|
+
const change = changes.get(comment.path);
|
|
15879
|
+
lines.push(
|
|
15880
|
+
"",
|
|
15881
|
+
`${index + 1}. ${place(comment, change)} (${change.status})`,
|
|
15882
|
+
...commentBody(comment, change, EXCERPT_CHARS_EACH)
|
|
15883
|
+
);
|
|
15884
|
+
});
|
|
15447
15885
|
return lines.join("\n");
|
|
15448
15886
|
}
|
|
15449
15887
|
|
|
@@ -15459,25 +15897,39 @@ teamReviewRouter.get("/:id/review", async (c) => {
|
|
|
15459
15897
|
const review = await readTeamReview(db, paths, c.req.param("id"), {
|
|
15460
15898
|
...base === void 0 ? {} : { base },
|
|
15461
15899
|
patches: c.req.query("patches") === "1",
|
|
15462
|
-
...patchPath === void 0 ? {} : { patchPath }
|
|
15900
|
+
...patchPath === void 0 ? {} : { patchPath },
|
|
15901
|
+
authors: c.req.query("authors") === "1"
|
|
15463
15902
|
});
|
|
15464
15903
|
return c.json(review);
|
|
15465
15904
|
});
|
|
15905
|
+
var validNote = (note) => note === void 0 || typeof note === "string" && note.length <= FEEDBACK_NOTE_CHARS;
|
|
15906
|
+
function validComment(value) {
|
|
15907
|
+
const comment = value ?? {};
|
|
15908
|
+
return typeof comment.path === "string" && comment.path.length > 0 && comment.path.length <= 4096 && (comment.line === void 0 || Number.isSafeInteger(comment.line) && comment.line > 0) && validNote(comment.note);
|
|
15909
|
+
}
|
|
15466
15910
|
teamReviewRouter.post("/:id/review/feedback", async (c) => {
|
|
15467
15911
|
const body = await jsonBody(c);
|
|
15468
|
-
if (!body || typeof body.
|
|
15469
|
-
return c.json({ error: "
|
|
15912
|
+
if (!body || typeof body.agentId !== "string" || body.agentId.length === 0) {
|
|
15913
|
+
return c.json({ error: "agentId is required" }, 400);
|
|
15470
15914
|
}
|
|
15471
|
-
if (body.
|
|
15472
|
-
return c.json(
|
|
15915
|
+
if (!Array.isArray(body.comments) || body.comments.length === 0 || body.comments.length > FEEDBACK_COMMENTS || !body.comments.every(validComment)) {
|
|
15916
|
+
return c.json(
|
|
15917
|
+
{ error: `comments must be 1 to ${FEEDBACK_COMMENTS} entries of { path, line?, note? }` },
|
|
15918
|
+
400
|
|
15919
|
+
);
|
|
15473
15920
|
}
|
|
15921
|
+
if (!validNote(body.note)) return c.json({ error: "Invalid feedback note" }, 400);
|
|
15474
15922
|
if (body.base !== void 0 && typeof body.base !== "string") {
|
|
15475
15923
|
return c.json({ error: "Invalid comparison base" }, 400);
|
|
15476
15924
|
}
|
|
15477
15925
|
const { db, paths } = getCtx();
|
|
15478
15926
|
const queued = await queueReviewFeedback(db, paths, c.req.param("id"), {
|
|
15479
|
-
path: body.path,
|
|
15480
15927
|
agentId: body.agentId,
|
|
15928
|
+
comments: body.comments.map((comment) => ({
|
|
15929
|
+
path: comment.path,
|
|
15930
|
+
...comment.line === void 0 ? {} : { line: comment.line },
|
|
15931
|
+
...comment.note === void 0 ? {} : { note: comment.note }
|
|
15932
|
+
})),
|
|
15481
15933
|
...body.note === void 0 ? {} : { note: body.note },
|
|
15482
15934
|
...body.base === void 0 ? {} : { base: body.base }
|
|
15483
15935
|
});
|
|
@@ -17525,11 +17977,13 @@ function createApp() {
|
|
|
17525
17977
|
app2.route("/api/teams", teamMemoryRouter);
|
|
17526
17978
|
app2.route("/api/teams", teamPolicyRouter);
|
|
17527
17979
|
app2.route("/api/teams", teamReviewRouter);
|
|
17980
|
+
app2.route("/api/teams", teamMessagesRouter);
|
|
17528
17981
|
app2.route("/api/teams", teamCodingEnvironmentRouter);
|
|
17529
17982
|
app2.route("/api/teams", teamTelegramRouter);
|
|
17530
17983
|
app2.route("/api/team-templates", teamTemplatesRouter);
|
|
17531
17984
|
app2.route("/api/results", resultsRouter);
|
|
17532
17985
|
app2.route("/api/attention", attentionRouter);
|
|
17986
|
+
app2.route("/api/activity", activityRouter);
|
|
17533
17987
|
app2.route("/api/notifications", notificationsRouter);
|
|
17534
17988
|
app2.route("/api/shell-approvals", shellApprovalsRouter);
|
|
17535
17989
|
app2.route("/api/profiles", profilesRouter);
|