bazilion 0.58.2 → 0.59.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.
Files changed (101) hide show
  1. package/dist/cli.js +16 -1
  2. package/dist/cli.js.map +1 -1
  3. package/dist/daemon.js +211 -77
  4. package/dist/daemon.js.map +1 -1
  5. package/dist/web/client/assets/AddProviderDialog-CbBtkgU7.js +1 -0
  6. package/dist/web/client/assets/{AgentTemplateParts-BaeuW_3n.js → AgentTemplateParts-Tx0RJoDa.js} +1 -1
  7. package/dist/web/client/assets/{ConfirmDialog-D8f2wI5x.js → ConfirmDialog-Du8-95Zj.js} +1 -1
  8. package/dist/web/client/assets/{ConnectionsView-BUZcfBHw.js → ConnectionsView-Dg9kLuab.js} +1 -1
  9. package/dist/web/client/assets/{SkillsParts-jMYdOiWh.js → SkillsParts-TYzEfrVu.js} +1 -1
  10. package/dist/web/client/assets/{SpawnTeamModal-Dq7D3Zlc.js → SpawnTeamModal-Dr98zpUf.js} +1 -1
  11. package/dist/web/client/assets/{TeamForm-Crz3mvXu.js → TeamForm-DaH5H-LF.js} +1 -1
  12. package/dist/web/client/assets/{TeamThread-qTkvxv27.js → TeamThread-DmtbrFq1.js} +1 -1
  13. package/dist/web/client/assets/{UnsavedChangesGuard-DGzP-x1t.js → UnsavedChangesGuard-fvP4Xr0R.js} +1 -1
  14. package/dist/web/client/assets/{_id-DsZBpW5G.js → _id--1i1fY0o.js} +1 -1
  15. package/dist/web/client/assets/{_id-CiqTBi2Q.js → _id-C_s4pMAk.js} +1 -1
  16. package/dist/web/client/assets/{access-ssWsYTEU.js → access-99X0FS-H.js} +1 -1
  17. package/dist/web/client/assets/{agents-BmkaQvWh.js → agents-CDJMwJL1.js} +1 -1
  18. package/dist/web/client/assets/{agents-D3tZ58Dh.js → agents-DVAJFWJI.js} +1 -1
  19. package/dist/web/client/assets/{attention-ChHdu7E8.js → attention-CDzRuQGN.js} +1 -1
  20. package/dist/web/client/assets/{config-DPsq6Zy9.js → config-9GESe8FI.js} +1 -1
  21. package/dist/web/client/assets/{index-CVVVmIFC.js → index-DkK2xZ2o.js} +2 -2
  22. package/dist/web/client/assets/{login-B-Kpyw9o.js → login-DUmrDZjN.js} +1 -1
  23. package/dist/web/client/assets/{manage-Dwe9yQl9.js → manage-D6zhY8hA.js} +1 -1
  24. package/dist/web/client/assets/{mcp-73AMOCv3.js → mcp-ByioWHXZ.js} +1 -1
  25. package/dist/web/client/assets/routes-DEMmBJiz.js +85 -0
  26. package/dist/web/client/assets/{skills-DmYDuDbl.js → skills-a52e5W9Z.js} +1 -1
  27. package/dist/web/client/assets/{style-B9Vy-99n.js → style-CiyV21dp.js} +1 -1
  28. package/dist/web/client/assets/styles-B-X0olFi.css +2 -0
  29. package/dist/web/client/assets/{system-t9hcqYBg.js → system-wJXOiU47.js} +1 -1
  30. package/dist/web/client/assets/{teams-5B2cyDin.js → teams-vRmMRnY_.js} +1 -1
  31. package/dist/web/client/assets/{teams-Nk_bHpr0.js → teams-wLJHtFW_.js} +1 -1
  32. package/dist/web/client/assets/telegram-CUsT8ZzL.js +1 -0
  33. package/dist/web/client/assets/{tools-mdAuMsYJ.js → tools-NMtdwKi0.js} +1 -1
  34. package/dist/web/client/assets/{usage-CWu7R8ZD.js → usage-DiIpfPPk.js} +1 -1
  35. package/dist/web/client/assets/{welcome-BuRNFxpc.js → welcome-BWN0jtZP.js} +1 -1
  36. package/dist/web/server/assets/{AddProviderDialog-Bqsz5NaL.js → AddProviderDialog-CxwjFPVY.js} +3 -3
  37. package/dist/web/server/assets/{AgentTemplateParts-D97gKNdN.js → AgentTemplateParts-CDDoX_bG.js} +5 -5
  38. package/dist/web/server/assets/{ConfigPage-CrxctbtN.js → ConfigPage-DwbP35aS.js} +2 -2
  39. package/dist/web/server/assets/{ConfirmDialog-CuD5HXTw.js → ConfirmDialog-CR_DTRpW.js} +1 -1
  40. package/dist/web/server/assets/{ConnectionsView-CSf83J-v.js → ConnectionsView-CplWLHII.js} +4 -4
  41. package/dist/web/server/assets/{Dialog-CwAfaXpM.js → Dialog-B2ZAk0JC.js} +1 -1
  42. package/dist/web/server/assets/{ManagePage-DGYNJ6XG.js → ManagePage-DSzEP6tP.js} +2 -2
  43. package/dist/web/server/assets/{ModelMenu-DEJoYASj.js → ModelMenu-BgIvpkO0.js} +1 -1
  44. package/dist/web/server/assets/{SectionTabs--vMBvaUz.js → SectionTabs-B56iIxRj.js} +1 -1
  45. package/dist/web/server/assets/{SkillsParts-hjS9a_Ht.js → SkillsParts-Bf5aGuER.js} +5 -5
  46. package/dist/web/server/assets/{SpawnDialog-BjVZl7xK.js → SpawnDialog-Fsdom-ur.js} +4 -4
  47. package/dist/web/server/assets/{SpawnTeamModal-BmBXqfFi.js → SpawnTeamModal-Zz03rkBZ.js} +4 -4
  48. package/dist/web/server/assets/{TeamForm-B4702hBg.js → TeamForm-DwXwjZWb.js} +4 -4
  49. package/dist/web/server/assets/{UnsavedChangesGuard-Be8EqfV_.js → UnsavedChangesGuard-BEtAdwza.js} +1 -1
  50. package/dist/web/server/assets/{_id-VqiN2zRR.js → _id-D1USZSkO.js} +9 -9
  51. package/dist/web/server/assets/{_id-BWtcQovD.js → _id-Dkx7QsM_.js} +1 -1
  52. package/dist/web/server/assets/{_id-DBhvSxVl.js → _id-R5F7ISnu.js} +1 -1
  53. package/dist/web/server/assets/{_id-TT_ZsaSc.js → _id-gh-ba9YO.js} +10 -10
  54. package/dist/web/server/assets/{_id-CKBQM7LH.js → _id-sS3ozDuV.js} +1 -1
  55. package/dist/web/server/assets/{_tanstack-start-manifest_v-gHDkHqeS.js → _tanstack-start-manifest_v-Be9mOSxg.js} +57 -57
  56. package/dist/web/server/assets/{access-Bog7dbtP.js → access-BcKK4G_w.js} +1 -1
  57. package/dist/web/server/assets/{access-C5lXP5JS.js → access-CftAsKX6.js} +5 -5
  58. package/dist/web/server/assets/{agents-DDUHE3eY.js → agents-BAlP1gc_.js} +8 -8
  59. package/dist/web/server/assets/{agents-8XZAjHh0.js → agents-BBQyhQz7.js} +7 -7
  60. package/dist/web/server/assets/{agents-Co6S2Ml9.js → agents-Bgo3LnIL.js} +1 -1
  61. package/dist/web/server/assets/{agents-BepbikC0.js → agents-CSMQtQCr.js} +1 -1
  62. package/dist/web/server/assets/{agents-DnUK-7qJ.js → agents-CvU8ljqt.js} +1 -1
  63. package/dist/web/server/assets/{agents-CKkMouJX.js → agents-DlxkPC-q.js} +1 -1
  64. package/dist/web/server/assets/{attention-n8edCJBL.js → attention-CHqUjESP.js} +5 -5
  65. package/dist/web/server/assets/{attention--1dBWt0c.js → attention-rfqLfyDE.js} +1 -1
  66. package/dist/web/server/assets/{config-BpwsF11b.js → config-CraGjaZB.js} +1 -1
  67. package/dist/web/server/assets/{config-UHRqSrh4.js → config-DSBJKiDX.js} +7 -7
  68. package/dist/web/server/assets/{form-Bwsyt9OY.js → form-BGif16IN.js} +2 -2
  69. package/dist/web/server/assets/{manage-C7ss0xG5.js → manage-CfDQUV7j.js} +1 -1
  70. package/dist/web/server/assets/{mcp-CUoF4jIO.js → mcp-RKq9Cj-h.js} +6 -6
  71. package/dist/web/server/assets/{mcp-COn047tO.js → mcp-VCW2SGMk.js} +1 -1
  72. package/dist/web/server/assets/{parts-B0wbj_yK.js → parts-BpwHijPN.js} +1 -1
  73. package/dist/web/server/assets/{router-yEsciAts.js → router-BER0FKkT.js} +21 -21
  74. package/dist/web/server/assets/{routes-BgjikzXy.js → routes-BYmi9O0B.js} +2 -0
  75. package/dist/web/server/assets/{routes-Bfkccvfb.js → routes-DSIwTrHI.js} +238 -91
  76. package/dist/web/server/assets/{routes-CjtC0rDs.js → routes-qtTyGHXK.js} +1 -1
  77. package/dist/web/server/assets/{skills-D5oN5ehC.js → skills-DM_Qcvqk.js} +7 -7
  78. package/dist/web/server/assets/{skills-DouMCq_2.js → skills-DZI56DdW.js} +1 -1
  79. package/dist/web/server/assets/{style-BgFXDhAR.js → style-DuiMhwn4.js} +1 -1
  80. package/dist/web/server/assets/{system-4WV2pOS4.js → system-Bx-_Vfss.js} +1 -1
  81. package/dist/web/server/assets/{system-DtGHi7X7.js → system-C_kmuned.js} +3 -3
  82. package/dist/web/server/assets/{teams-BnsbH4YW.js → teams-BL_lLFPd.js} +8 -8
  83. package/dist/web/server/assets/{teams-Blfyu8ej.js → teams-Bd6J6rHj.js} +1 -1
  84. package/dist/web/server/assets/{teams-QVxXJfo7.js → teams-CRGLRUp9.js} +1 -1
  85. package/dist/web/server/assets/{teams-gzY3tOtu.js → teams-fQEKru2G.js} +7 -7
  86. package/dist/web/server/assets/{telegram-CIbuQ5-U.js → telegram-CpHjomwG.js} +1 -1
  87. package/dist/web/server/assets/{telegram-Ctj5dqvs.js → telegram-Do0oUOXQ.js} +6 -6
  88. package/dist/web/server/assets/{tools-x_DQTQtE.js → tools-CMXn8htp.js} +5 -5
  89. package/dist/web/server/assets/{tools-Dn6RnOFu.js → tools-Ctckgev8.js} +1 -1
  90. package/dist/web/server/assets/{usage-CeiyPffw.js → usage-DaV-iwEz.js} +1 -1
  91. package/dist/web/server/assets/{usage-Dsi2V9Wh.js → usage-sZ4SFz36.js} +3 -3
  92. package/dist/web/server/assets/{welcome-C71pZOQ9.js → welcome-BhfLQBOr.js} +1 -1
  93. package/dist/web/server/assets/{welcome-A2Koo4HI.js → welcome-Dz5zfvV2.js} +3 -3
  94. package/dist/web/server/server.js +6 -6
  95. package/dist/worker.js +71 -16
  96. package/dist/worker.js.map +1 -1
  97. package/package.json +1 -1
  98. package/dist/web/client/assets/AddProviderDialog-BsUXLr-m.js +0 -1
  99. package/dist/web/client/assets/routes-Lj8n-RF7.js +0 -85
  100. package/dist/web/client/assets/styles-DyFDuWBI.css +0 -2
  101. package/dist/web/client/assets/telegram-BWfL_OIt.js +0 -1
package/dist/daemon.js CHANGED
@@ -728,6 +728,7 @@ var init_ssrf = __esm({
728
728
 
729
729
  // ../daemon/src/lib/browser/attach.ts
730
730
  import { readFileSync as readFileSync7 } from "node:fs";
731
+ import { rm } from "node:fs/promises";
731
732
  import { connect as connect2 } from "node:net";
732
733
  import { homedir as homedir2 } from "node:os";
733
734
  import { join as join11 } from "node:path";
@@ -793,6 +794,7 @@ async function openConnection(url) {
793
794
  try {
794
795
  browser = await chromium.connectOverCDP(target.endpoint, {
795
796
  timeout: CONNECT_MS,
797
+ noDefaults: true,
796
798
  ...url ? {} : { isLocal: true }
797
799
  });
798
800
  } catch (error) {
@@ -807,7 +809,32 @@ async function openConnection(url) {
807
809
  });
808
810
  throw new Error(`${target.name} has no browser window to work in`);
809
811
  }
810
- return { browser, context };
812
+ const agentFrames = /* @__PURE__ */ new Map();
813
+ try {
814
+ await refuseAgentDownloads(browser, agentFrames);
815
+ } catch (error) {
816
+ await browser.close().catch(() => {
817
+ });
818
+ throw error;
819
+ }
820
+ return { browser, context, agentFrames };
821
+ }
822
+ async function refuseAgentDownloads(browser, agentFrames) {
823
+ const cdp = await browser.newBrowserCDPSession();
824
+ const refused = /* @__PURE__ */ new Set();
825
+ cdp.on("Browser.downloadWillBegin", ({ guid, frameId }) => {
826
+ if (![...agentFrames.values()].some((frames) => frames.has(frameId))) return;
827
+ refused.add(guid);
828
+ cdp.send("Browser.cancelDownload", { guid }).catch(() => {
829
+ });
830
+ });
831
+ cdp.on("Browser.downloadProgress", ({ guid, state: state2, filePath }) => {
832
+ if (!refused.has(guid) || state2 === "inProgress") return;
833
+ refused.delete(guid);
834
+ if (state2 === "completed" && filePath) rm(filePath, { force: true }).catch(() => {
835
+ });
836
+ });
837
+ await cdp.send("Browser.setDownloadBehavior", { behavior: "default", eventsEnabled: true });
811
838
  }
812
839
  function acquire(url) {
813
840
  const key2 = url ?? "";
@@ -839,9 +866,19 @@ async function refusePrivateRequests(page) {
839
866
  }
840
867
  });
841
868
  }
842
- async function refuseDownloads(context, page) {
869
+ async function setUpAgentTab(context, page, agentFrames) {
870
+ const frames = /* @__PURE__ */ new Set();
871
+ agentFrames.set(page, frames);
872
+ page.once("close", () => agentFrames.delete(page));
843
873
  const cdp = await context.newCDPSession(page);
844
- await cdp.send("Page.setDownloadBehavior", { behavior: "deny" });
874
+ cdp.on("Page.frameAttached", ({ frameId }) => frames.add(frameId));
875
+ await cdp.send("Page.enable");
876
+ const add3 = (tree) => {
877
+ frames.add(tree.frame.id);
878
+ for (const child of tree.childFrames ?? []) add3(child);
879
+ };
880
+ add3((await cdp.send("Page.getFrameTree")).frameTree);
881
+ await cdp.send("Emulation.setFocusEmulationEnabled", { enabled: true });
845
882
  }
846
883
  async function attachBrowser(opts) {
847
884
  const shared = acquire(opts.url);
@@ -852,7 +889,7 @@ async function attachBrowser(opts) {
852
889
  await release(opts.url, shared);
853
890
  throw error;
854
891
  }
855
- const { browser, context } = connection2;
892
+ const { browser, context, agentFrames } = connection2;
856
893
  const owned = /* @__PURE__ */ new Set();
857
894
  const own = (page) => {
858
895
  owned.add(page);
@@ -862,7 +899,7 @@ async function attachBrowser(opts) {
862
899
  page.setDefaultTimeout(1e4);
863
900
  return Promise.all([
864
901
  opts.allowPrivate ? void 0 : refusePrivateRequests(page),
865
- refuseDownloads(context, page)
902
+ setUpAgentTab(context, page, agentFrames)
866
903
  ]).catch(() => {
867
904
  });
868
905
  };
@@ -7985,7 +8022,8 @@ function piMessagesToProviderView(messages, secrets = []) {
7985
8022
  toolCallId: tr.toolCallId,
7986
8023
  toolName: tr.toolName,
7987
8024
  results: extractResultReferences(m),
7988
- ...images.length > 0 ? { images } : {}
8025
+ ...images.length > 0 ? { images } : {},
8026
+ ...tr.isError ? { isError: true } : {}
7989
8027
  });
7990
8028
  break;
7991
8029
  }
@@ -8027,6 +8065,79 @@ import {
8027
8065
  // ../daemon/src/runtime/providers/pi-runtime.ts
8028
8066
  import { InMemoryCredentialStore } from "@earendil-works/pi-ai";
8029
8067
  import { ModelRuntime } from "@earendil-works/pi-coding-agent";
8068
+
8069
+ // ../daemon/src/runtime/providers/catalog.ts
8070
+ import { getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
8071
+ import { fetch as undiciFetch2 } from "undici";
8072
+ function listCatalogEntries(providerName) {
8073
+ const models = getBuiltinModels(
8074
+ piProviderName(providerName)
8075
+ );
8076
+ return (models ?? []).map((model) => {
8077
+ const input = model.cost?.input ?? 0;
8078
+ const output = model.cost?.output ?? 0;
8079
+ return {
8080
+ id: model.id,
8081
+ // Pi marks the undated alias "(latest)"; the dated copy is told apart by its id.
8082
+ name: (model.name ?? model.id).replace(/ \(latest\)$/, ""),
8083
+ contextWindow: model.contextWindow ?? 0,
8084
+ images: model.input?.includes("image") ?? false,
8085
+ reasoning: model.reasoning ?? false,
8086
+ // Subscription and free endpoints are priced at zero, which says nothing about cost.
8087
+ ...input > 0 || output > 0 ? { price: { input, output } } : {}
8088
+ };
8089
+ });
8090
+ }
8091
+ function catalogContextWindow(model) {
8092
+ try {
8093
+ const { providerName, modelId } = parseModelString(model);
8094
+ const entry = listCatalogEntries(providerName).find((candidate) => candidate.id === modelId);
8095
+ return entry && entry.contextWindow > 0 ? entry.contextWindow : null;
8096
+ } catch {
8097
+ return null;
8098
+ }
8099
+ }
8100
+ var DATED = /^(.+)-(\d{8}|\d{4}-\d{2}-\d{2})$/;
8101
+ function datedCopies(ids) {
8102
+ const all = new Set(ids);
8103
+ return new Set(
8104
+ ids.filter((id) => {
8105
+ const base = DATED.exec(id)?.[1];
8106
+ return base !== void 0 && all.has(base);
8107
+ })
8108
+ );
8109
+ }
8110
+ async function fetchLiveModels(baseUrl, apiKey2, signal) {
8111
+ try {
8112
+ const headers = { accept: "application/json" };
8113
+ if (apiKey2) headers.authorization = `Bearer ${apiKey2}`;
8114
+ const res = await undiciFetch2(`${baseUrl.replace(/\/$/, "")}/models`, { headers, signal });
8115
+ if (!res.ok) return { models: [], error: `${res.status} ${res.statusText}` };
8116
+ const body = await res.json();
8117
+ return { models: (body?.data ?? []).flatMap((model) => model.id ? [model.id] : []) };
8118
+ } catch (err) {
8119
+ const cause = err.cause;
8120
+ return { models: [], error: cause?.code ?? cause?.message ?? err.message };
8121
+ }
8122
+ }
8123
+ async function listLiveModels(providerName, env = process.env, signal) {
8124
+ const url = providerModelsUrl(providerName, env);
8125
+ if (!url) return void 0;
8126
+ return fetchLiveModels(url, providerApiKey(providerName, env), signal);
8127
+ }
8128
+
8129
+ // ../daemon/src/runtime/providers/pi-runtime.ts
8130
+ var ENDPOINT_CONTEXT_WINDOW = 32768;
8131
+ function turnContextWindow(model) {
8132
+ let providerName;
8133
+ try {
8134
+ providerName = parseModelString(model).providerName;
8135
+ } catch {
8136
+ return null;
8137
+ }
8138
+ if (findProvider(providerName)?.local) return ENDPOINT_CONTEXT_WINDOW;
8139
+ return catalogContextWindow(model) ?? ENDPOINT_CONTEXT_WINDOW;
8140
+ }
8030
8141
  function endpointModel(providerName, modelId, baseUrl) {
8031
8142
  return {
8032
8143
  id: modelId,
@@ -8037,7 +8148,7 @@ function endpointModel(providerName, modelId, baseUrl) {
8037
8148
  reasoning: false,
8038
8149
  input: ["text"],
8039
8150
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
8040
- contextWindow: 32768,
8151
+ contextWindow: ENDPOINT_CONTEXT_WINDOW,
8041
8152
  maxTokens: 4096
8042
8153
  };
8043
8154
  }
@@ -9030,6 +9141,57 @@ function readOnlyMount(source, target, root) {
9030
9141
  return { source: real, target };
9031
9142
  }
9032
9143
 
9144
+ // ../daemon/src/runtime/pi/history.ts
9145
+ import {
9146
+ calculateContextTokens
9147
+ } from "@earendil-works/pi-coding-agent";
9148
+ function branchOf(entries) {
9149
+ const all = entries.filter((entry) => entry.type !== "session");
9150
+ const byId = new Map(all.map((entry) => [entry.id, entry]));
9151
+ const path = [];
9152
+ const seen = /* @__PURE__ */ new Set();
9153
+ for (let entry = all.at(-1); entry && !seen.has(entry.id); ) {
9154
+ seen.add(entry.id);
9155
+ path.push(entry);
9156
+ entry = entry.parentId ? byId.get(entry.parentId) : void 0;
9157
+ }
9158
+ return path.reverse();
9159
+ }
9160
+ function conversationHistory(branch) {
9161
+ const messages = [];
9162
+ const position = /* @__PURE__ */ new Map();
9163
+ const compactions = [];
9164
+ for (const entry of branch) {
9165
+ position.set(entry.id, messages.length);
9166
+ if (entry.type === "message" && entry.message.role !== "system") {
9167
+ const message = entry.message;
9168
+ messages.push(
9169
+ "content" in message && message.content == null ? { ...message, content: [] } : message
9170
+ );
9171
+ } else if (entry.type === "compaction") {
9172
+ compactions.push({
9173
+ // The part kept verbatim starts at firstKeptEntryId; the summary stands for what precedes.
9174
+ index: position.get(entry.firstKeptEntryId) ?? messages.length,
9175
+ summary: entry.summary,
9176
+ tokensBefore: entry.tokensBefore,
9177
+ at: Date.parse(entry.timestamp) || 0
9178
+ });
9179
+ }
9180
+ }
9181
+ return { messages, compactions };
9182
+ }
9183
+ function contextUse(branch, window) {
9184
+ const latestCompaction = branch.findLastIndex((entry) => entry.type === "compaction");
9185
+ for (let i = branch.length - 1; i > latestCompaction; i--) {
9186
+ const entry = branch[i];
9187
+ if (entry?.type !== "message" || entry.message.role !== "assistant") continue;
9188
+ if (entry.message.stopReason === "aborted" || entry.message.stopReason === "error") continue;
9189
+ const tokens = calculateContextTokens(entry.message.usage);
9190
+ if (tokens > 0) return { tokens, window };
9191
+ }
9192
+ return { tokens: null, window };
9193
+ }
9194
+
9033
9195
  // ../daemon/src/runtime/pi/session-file.ts
9034
9196
  import { closeSync as closeSync3, constants as constants4, fstatSync as fstatSync3, openSync as openSync3, readSync as readSync2 } from "node:fs";
9035
9197
  import { join as join19 } from "node:path";
@@ -9835,7 +9997,7 @@ etag: ${etag}`;
9835
9997
  }
9836
9998
 
9837
9999
  // ../daemon/src/runtime/tools/web.ts
9838
- import { fetch as undiciFetch2 } from "undici";
10000
+ import { fetch as undiciFetch3 } from "undici";
9839
10001
 
9840
10002
  // ../daemon/src/runtime/tools/web-extract.ts
9841
10003
  import { Readability } from "@mozilla/readability";
@@ -10072,7 +10234,7 @@ function webSearchTool(host3) {
10072
10234
  };
10073
10235
  }
10074
10236
  function webFetchTool(opts) {
10075
- const fetchFn = opts?.fetchImpl ?? undiciFetch2;
10237
+ const fetchFn = opts?.fetchImpl ?? undiciFetch3;
10076
10238
  const env = opts?.env ?? process.env;
10077
10239
  const allowPrivate = opts?.allowPrivate ?? false;
10078
10240
  const cacheTtlMs = opts?.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
@@ -10236,10 +10398,11 @@ function createBazilionCustomTools(opts) {
10236
10398
  async function openPiSession(spec) {
10237
10399
  const { runtime: modelRuntime, model } = await createPiModel(spec.model);
10238
10400
  const settingsManager = SettingsManager.inMemory({
10239
- // Provider requests happen only for turns: no cache warming, and compaction runs only on
10240
- // request (/compact).
10401
+ // Provider requests happen only for turns: no cache warming. A turn compacts the
10402
+ // conversation when it nears the model's window (Pi's defaults: within 16,384 tokens of it,
10403
+ // keeping the last 20,000 verbatim), and redoes a reply the full window cut short.
10241
10404
  cacheWarming: "off",
10242
- compaction: { enabled: false },
10405
+ compaction: { enabled: true },
10243
10406
  retry: {
10244
10407
  enabled: true,
10245
10408
  maxRetries: 2,
@@ -10387,6 +10550,9 @@ function describeTurn(opts) {
10387
10550
  tools: [...hostTools, ...turn.tools]
10388
10551
  };
10389
10552
  }
10553
+ function conversationWindow(conversation, model) {
10554
+ return contextUse(conversation.getBranch(), turnContextWindow(model));
10555
+ }
10390
10556
  function conversationUsage(conversation) {
10391
10557
  const branch = conversation.getBranch();
10392
10558
  return {
@@ -10418,6 +10584,14 @@ function openConversation(agent, paths, target) {
10418
10584
  agent.team.path
10419
10585
  );
10420
10586
  }
10587
+ function loadConversation(agent, paths, target) {
10588
+ const window = turnContextWindow(agent.model);
10589
+ if (!target) return { messages: [], compactions: [], context: { tokens: null, window } };
10590
+ const branch = branchOf(
10591
+ readSessionFile(join22(paths.agentDir(agent.agent.id), "sessions"), target.id)
10592
+ );
10593
+ return { ...conversationHistory(branch), context: contextUse(branch, window) };
10594
+ }
10421
10595
  function loadInitialMessages(agent, paths, target) {
10422
10596
  if (!target) return [];
10423
10597
  const entries = readSessionFile(join22(paths.agentDir(agent.agent.id), "sessions"), target.id);
@@ -10452,57 +10626,6 @@ function explicitConversationFile(directory, target) {
10452
10626
  return join22(directory, `${target.id}.jsonl`);
10453
10627
  }
10454
10628
 
10455
- // ../daemon/src/runtime/providers/catalog.ts
10456
- import { getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
10457
- import { fetch as undiciFetch3 } from "undici";
10458
- function listCatalogEntries(providerName) {
10459
- const models = getBuiltinModels(
10460
- piProviderName(providerName)
10461
- );
10462
- return (models ?? []).map((model) => {
10463
- const input = model.cost?.input ?? 0;
10464
- const output = model.cost?.output ?? 0;
10465
- return {
10466
- id: model.id,
10467
- // Pi marks the undated alias "(latest)"; the dated copy is told apart by its id.
10468
- name: (model.name ?? model.id).replace(/ \(latest\)$/, ""),
10469
- contextWindow: model.contextWindow ?? 0,
10470
- images: model.input?.includes("image") ?? false,
10471
- reasoning: model.reasoning ?? false,
10472
- // Subscription and free endpoints are priced at zero, which says nothing about cost.
10473
- ...input > 0 || output > 0 ? { price: { input, output } } : {}
10474
- };
10475
- });
10476
- }
10477
- var DATED = /^(.+)-(\d{8}|\d{4}-\d{2}-\d{2})$/;
10478
- function datedCopies(ids) {
10479
- const all = new Set(ids);
10480
- return new Set(
10481
- ids.filter((id) => {
10482
- const base = DATED.exec(id)?.[1];
10483
- return base !== void 0 && all.has(base);
10484
- })
10485
- );
10486
- }
10487
- async function fetchLiveModels(baseUrl, apiKey2, signal) {
10488
- try {
10489
- const headers = { accept: "application/json" };
10490
- if (apiKey2) headers.authorization = `Bearer ${apiKey2}`;
10491
- const res = await undiciFetch3(`${baseUrl.replace(/\/$/, "")}/models`, { headers, signal });
10492
- if (!res.ok) return { models: [], error: `${res.status} ${res.statusText}` };
10493
- const body = await res.json();
10494
- return { models: (body?.data ?? []).flatMap((model) => model.id ? [model.id] : []) };
10495
- } catch (err) {
10496
- const cause = err.cause;
10497
- return { models: [], error: cause?.code ?? cause?.message ?? err.message };
10498
- }
10499
- }
10500
- async function listLiveModels(providerName, env = process.env, signal) {
10501
- const url = providerModelsUrl(providerName, env);
10502
- if (!url) return void 0;
10503
- return fetchLiveModels(url, providerApiKey(providerName, env), signal);
10504
- }
10505
-
10506
10629
  // ../daemon/src/runtime/worker/spawn.ts
10507
10630
  import { spawn as spawn4 } from "node:child_process";
10508
10631
  import { existsSync as existsSync16 } from "node:fs";
@@ -12487,6 +12610,10 @@ function renderFrame(frame, mode2) {
12487
12610
  return mode2 === "verbose" ? `\u2713 ${ev.name} \u2192 ${clip2(ev.result, 200)}` : null;
12488
12611
  case "tool_error":
12489
12612
  return mode2 === "verbose" ? `\u2715 ${ev.name}: ${ev.error}` : null;
12613
+ case "compaction":
12614
+ if (ev.state === "failed") return `\u26A0\uFE0F Could not summarize older messages: ${ev.error ?? ""}`;
12615
+ if (mode2 !== "verbose") return null;
12616
+ return ev.state === "running" ? "Summarizing older messages to make room\u2026" : "Older messages summarized to make room.";
12490
12617
  case "command_approval":
12491
12618
  return null;
12492
12619
  case "file":
@@ -13323,17 +13450,21 @@ agentChatRouter.get("/:id/sessions/messages", (c) => {
13323
13450
  const target = selectedConversationTarget(db, resolved.agent.id);
13324
13451
  const conversationId = target?.id ?? null;
13325
13452
  try {
13326
- const messages = piMessagesToProviderView(
13327
- loadInitialMessages(resolved, paths, target),
13328
- envSecretValues(mergeSecretsIntoEnv(db, authToken))
13329
- );
13453
+ const { messages, compactions, context } = loadConversation(resolved, paths, target);
13330
13454
  return c.json({
13331
- messages,
13455
+ messages: piMessagesToProviderView(
13456
+ messages,
13457
+ envSecretValues(mergeSecretsIntoEnv(db, authToken))
13458
+ ),
13459
+ compactions,
13460
+ context,
13332
13461
  head: { ...loadSessionHead(resolved, paths, target), conversationId }
13333
13462
  });
13334
13463
  } catch {
13335
13464
  return c.json({
13336
13465
  messages: [],
13466
+ compactions: [],
13467
+ context: { tokens: null, window: null },
13337
13468
  head: unavailableHead(target, conversationId)
13338
13469
  });
13339
13470
  }
@@ -13541,7 +13672,8 @@ agentChatRouter.get(
13541
13672
  path: resolved.team.path,
13542
13673
  userMdChars: resolved.team.userMd.length
13543
13674
  };
13544
- const history = conversationUsage(openConversation(resolved, paths, target));
13675
+ const conversation = openConversation(resolved, paths, target);
13676
+ const history = conversationUsage(conversation);
13545
13677
  const historyChars = history.tokens * 4;
13546
13678
  const cap = c.req.query("detail") === "1" ? Number.POSITIVE_INFINITY : 30;
13547
13679
  const totalsChars = systemPromptChars + toolsSchemaChars + historyChars;
@@ -13572,7 +13704,8 @@ agentChatRouter.get(
13572
13704
  bytes: loadSessionHead(resolved, paths, target).size,
13573
13705
  tokensEstimate: history.tokens
13574
13706
  },
13575
- totals: { chars: totalsChars, tokens: estimateTokens2(totalsChars) }
13707
+ totals: { chars: totalsChars, tokens: estimateTokens2(totalsChars) },
13708
+ window: conversationWindow(conversation, resolved.model)
13576
13709
  });
13577
13710
  })
13578
13711
  );
@@ -13589,11 +13722,13 @@ agentChatRouter.post("/:id/chat/truncate", async (c) => {
13589
13722
  }
13590
13723
  const { db, paths } = getCtx();
13591
13724
  const conversation = openConversation(resolveAgent(db, paths, id), paths, target);
13592
- const messageEntries = conversation.getBranch().filter((e) => e.type === "message" && e.message.role !== "system");
13725
+ const branch = conversation.getBranch();
13726
+ const messageEntries = branch.filter((e) => e.type === "message" && e.message.role !== "system");
13593
13727
  const before = messageEntries.length;
13594
13728
  const after = Math.max(0, Math.min(keep2, before));
13595
13729
  if (after === before) return c.json({ before, after });
13596
- const lastKept = messageEntries[after - 1];
13730
+ const firstDropped = messageEntries[after];
13731
+ const lastKept = firstDropped ? branch[branch.indexOf(firstDropped) - 1] : void 0;
13597
13732
  if (lastKept) conversation.branch(lastKept.id);
13598
13733
  else conversation.resetLeaf();
13599
13734
  conversation.appendCustomEntry("bazilion.truncate", { keep: after });
@@ -15365,7 +15500,6 @@ configRouter.delete("/fields/:envVar", (c) => {
15365
15500
 
15366
15501
  // ../daemon/src/lib/conversation-search.ts
15367
15502
  import { join as join32 } from "node:path";
15368
- import { buildSessionContext as buildSessionContext2 } from "@earendil-works/pi-coding-agent";
15369
15503
  var INBOX_WAKE_PREFIX = "[[bazilion:inbox-wake]]\n";
15370
15504
  var MAX_WORDS = 8;
15371
15505
  var MAX_SEARCH_HITS = 50;
@@ -15420,8 +15554,7 @@ async function searchConversations(db, paths, options) {
15420
15554
  if (!raw.every((word) => lower.includes(word))) continue;
15421
15555
  let messages;
15422
15556
  try {
15423
- const entries = parseSessionText(text4, row.id);
15424
- messages = buildSessionContext2(entries.filter((entry) => entry.type !== "session")).messages;
15557
+ messages = conversationHistory(branchOf(parseSessionText(text4, row.id))).messages;
15425
15558
  } catch {
15426
15559
  unreadable++;
15427
15560
  continue;
@@ -15851,14 +15984,15 @@ conversationsRouter.get("/:agentId/conversations/:id", (c) => {
15851
15984
  const conversation = get16(db, agentId, id);
15852
15985
  if (!conversation) return c.json({ error: "Conversation not found" }, 404);
15853
15986
  try {
15987
+ const history = loadConversation(resolveAgent(db, paths, agentId), paths, { id });
15854
15988
  const messages = piMessagesToProviderView(
15855
- loadInitialMessages(resolveAgent(db, paths, agentId), paths, { id }),
15989
+ history.messages,
15856
15990
  envSecretValues(mergeSecretsIntoEnv(db, authToken))
15857
15991
  );
15858
15992
  const usage = conversationUsage2(paths, agentId, planProviders(mergeSecretsIntoEnv(db, authToken))).get(
15859
15993
  id
15860
15994
  ) ?? null;
15861
- return c.json({ conversation, messages, usage });
15995
+ return c.json({ conversation, messages, compactions: history.compactions, usage });
15862
15996
  } catch {
15863
15997
  return c.json(
15864
15998
  {