@bunny-agent/daemon 0.9.29-beta.0 → 0.9.29-beta.11

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/bundle.mjs CHANGED
@@ -116839,7 +116839,7 @@ var require_core3 = __commonJS({
116839
116839
  return match2 && match2.index === 0;
116840
116840
  }
116841
116841
  var BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
116842
- function join38(regexps, separator = "|") {
116842
+ function join39(regexps, separator = "|") {
116843
116843
  let numCaptures = 0;
116844
116844
  return regexps.map((regex2) => {
116845
116845
  numCaptures += 1;
@@ -117143,7 +117143,7 @@ var require_core3 = __commonJS({
117143
117143
  this.exec = () => null;
117144
117144
  }
117145
117145
  const terminators = this.regexes.map((el) => el[1]);
117146
- this.matcherRe = langRe(join38(terminators), true);
117146
+ this.matcherRe = langRe(join39(terminators), true);
117147
117147
  this.lastIndex = 0;
117148
117148
  }
117149
117149
  /** @param {string} s */
@@ -168061,14 +168061,14 @@ var require_graceful_fs = __commonJS({
168061
168061
  return close;
168062
168062
  })(fs16.close);
168063
168063
  fs16.closeSync = (function(fs$closeSync) {
168064
- function closeSync2(fd) {
168064
+ function closeSync3(fd) {
168065
168065
  fs$closeSync.apply(fs16, arguments);
168066
168066
  resetQueue();
168067
168067
  }
168068
- Object.defineProperty(closeSync2, previousSymbol, {
168068
+ Object.defineProperty(closeSync3, previousSymbol, {
168069
168069
  value: fs$closeSync
168070
168070
  });
168071
- return closeSync2;
168071
+ return closeSync3;
168072
168072
  })(fs16.closeSync);
168073
168073
  if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
168074
168074
  process.on("exit", function() {
@@ -206500,10 +206500,15 @@ async function fsStat(state, q2) {
206500
206500
  const root2 = resolveVolumeRoot(state, q2.volume);
206501
206501
  const target = resolveUnderRoot(root2, q2.path);
206502
206502
  const stat6 = await fs2.stat(target);
206503
+ const created_at = msToIsoOrNull(stat6.birthtimeMs) ?? msToIsoOrNull(stat6.ctimeMs);
206503
206504
  return ok({
206504
206505
  path: target,
206505
206506
  is_dir: stat6.isDirectory(),
206506
- size: stat6.isFile() ? stat6.size : 0
206507
+ size: stat6.isFile() ? stat6.size : 0,
206508
+ created_at,
206509
+ modified_at: msToIsoOrNull(
206510
+ stat6.mtimeMs
206511
+ )
206507
206512
  });
206508
206513
  }
206509
206514
  async function fsExists(state, q2) {
@@ -208383,7 +208388,7 @@ function createOpenCodeRunner(options2 = {}) {
208383
208388
 
208384
208389
  // ../../packages/runner-pi/dist/pi-runner.js
208385
208390
  import { appendFileSync as appendFileSync5, existsSync as existsSync28, unlinkSync as unlinkSync6 } from "node:fs";
208386
- import { join as join35 } from "node:path";
208391
+ import { join as join36 } from "node:path";
208387
208392
 
208388
208393
  // ../../node_modules/.pnpm/@mariozechner+pi-ai@0.64.0_ws@8.19.0_zod@4.3.6/node_modules/@mariozechner/pi-ai/dist/index.js
208389
208394
  var dist_exports = {};
@@ -263369,8 +263374,8 @@ var generateImageSchema = {
263369
263374
  },
263370
263375
  quality: {
263371
263376
  type: "string",
263372
- enum: ["standard", "hd"],
263373
- description: "Image quality (OpenAI only). Defaults to standard."
263377
+ enum: ["low", "medium", "high", "auto"],
263378
+ description: "Image quality. Defaults to auto."
263374
263379
  }
263375
263380
  },
263376
263381
  required: ["prompt"],
@@ -263528,11 +263533,11 @@ function buildImageGenerateTool(cwd, imageModelId, baseUrl, apiKey) {
263528
263533
  ],
263529
263534
  // biome-ignore lint/suspicious/noExplicitAny: plain JSON Schema compatible with TypeBox TSchema
263530
263535
  parameters: generateImageSchema,
263531
- async execute(_toolCallId, params, _signal, _onUpdate) {
263536
+ async execute(_toolCallId, params, signal, _onUpdate) {
263532
263537
  const p = params;
263533
263538
  const prompt = p.prompt;
263534
263539
  const size = p.size ?? "1024x1024";
263535
- const quality = p.quality ?? "standard";
263540
+ const quality = p.quality ?? "auto";
263536
263541
  const rawFilename = p.filename;
263537
263542
  const filename = rawFilename ? extname2(rawFilename) ? rawFilename : `${rawFilename}.png` : `image_${Date.now()}.png`;
263538
263543
  const filePath = join34(cwd, filename.replace(/[^a-zA-Z0-9_\-./]/g, "_"));
@@ -263552,7 +263557,8 @@ function buildImageGenerateTool(cwd, imageModelId, baseUrl, apiKey) {
263552
263557
  quality,
263553
263558
  response_format: "b64_json",
263554
263559
  output_format: "png"
263555
- })
263560
+ }),
263561
+ signal
263556
263562
  });
263557
263563
  if (!res.ok) {
263558
263564
  throw new Error(`Image generation failed (${res.status}): ${await res.text()}`);
@@ -263569,6 +263575,7 @@ function buildImageGenerateTool(cwd, imageModelId, baseUrl, apiKey) {
263569
263575
  ],
263570
263576
  details: {
263571
263577
  filePath: savedPath,
263578
+ ...json.usage != null ? { usage: { raw: { [imageModelId]: json.usage } } } : {},
263572
263579
  response: json
263573
263580
  }
263574
263581
  };
@@ -263657,7 +263664,7 @@ function buildImageEditTool(cwd, imageModelId, baseUrl, apiKey) {
263657
263664
  ],
263658
263665
  // biome-ignore lint/suspicious/noExplicitAny: plain JSON Schema compatible with TypeBox TSchema
263659
263666
  parameters: editImageSchema,
263660
- async execute(_toolCallId, params, _signal, _onUpdate) {
263667
+ async execute(_toolCallId, params, signal, _onUpdate) {
263661
263668
  const { readFileSync: readFileSync24, existsSync: existsSync31 } = await import("node:fs");
263662
263669
  const { resolve: resolve14, basename: basename12 } = await import("node:path");
263663
263670
  const p = params;
@@ -263725,7 +263732,8 @@ function buildImageEditTool(cwd, imageModelId, baseUrl, apiKey) {
263725
263732
  "Content-Type": type,
263726
263733
  Authorization: `Bearer ${apiKey}`
263727
263734
  },
263728
- body
263735
+ body,
263736
+ signal
263729
263737
  });
263730
263738
  if (!res.ok) {
263731
263739
  throw new Error(`Image edit failed (${res.status}): ${await res.text()}`);
@@ -263755,6 +263763,7 @@ function buildImageEditTool(cwd, imageModelId, baseUrl, apiKey) {
263755
263763
  ],
263756
263764
  details: {
263757
263765
  filePath: savedPath,
263766
+ ...json.usage != null ? { usage: { raw: { [imageModelId]: json.usage } } } : {},
263758
263767
  response: json
263759
263768
  }
263760
263769
  };
@@ -263771,12 +263780,315 @@ function buildImageEditTool(cwd, imageModelId, baseUrl, apiKey) {
263771
263780
  };
263772
263781
  }
263773
263782
 
263783
+ // ../../packages/runner-pi/dist/session-utils.js
263784
+ import { closeSync as closeSync2, fstatSync, openSync as openSync2, readdirSync as readdirSync12, readSync as readSync2, statSync as statSync13 } from "node:fs";
263785
+ import { join as join35 } from "node:path";
263786
+ var MAX_SESSION_FILE_BYTES = Number(process.env.SANDAGENT_MAX_SESSION_BYTES) || 10 * 1024 * 1024;
263787
+ function resolveSessionPathById(cwd, sessionId) {
263788
+ const tempMgr = SessionManager.create(cwd);
263789
+ const sessionsDir = tempMgr.getSessionDir();
263790
+ try {
263791
+ const suffix = `_${sessionId}.jsonl`;
263792
+ const match2 = readdirSync12(sessionsDir).find((f3) => f3.endsWith(suffix));
263793
+ return match2 ? join35(sessionsDir, match2) : void 0;
263794
+ } catch {
263795
+ return void 0;
263796
+ }
263797
+ }
263798
+ function isSessionFileTooLarge(sessionPath2) {
263799
+ try {
263800
+ return statSync13(sessionPath2).size > MAX_SESSION_FILE_BYTES;
263801
+ } catch {
263802
+ return false;
263803
+ }
263804
+ }
263805
+ function readTailEntries(sessionPath2, tailBytes = 1024 * 1024) {
263806
+ let fd;
263807
+ try {
263808
+ fd = openSync2(sessionPath2, "r");
263809
+ } catch {
263810
+ return [];
263811
+ }
263812
+ try {
263813
+ const fileSize = fstatSync(fd).size;
263814
+ const readStart = Math.max(0, fileSize - tailBytes);
263815
+ const readLen = fileSize - readStart;
263816
+ const buf = Buffer.alloc(readLen);
263817
+ readSync2(fd, buf, 0, readLen, readStart);
263818
+ const tail = buf.toString("utf8");
263819
+ const entries = [];
263820
+ for (const line of tail.split("\n")) {
263821
+ const trimmed = line.trim();
263822
+ if (!trimmed)
263823
+ continue;
263824
+ try {
263825
+ entries.push(JSON.parse(trimmed));
263826
+ } catch {
263827
+ }
263828
+ }
263829
+ return entries;
263830
+ } finally {
263831
+ closeSync2(fd);
263832
+ }
263833
+ }
263834
+ function extractSessionContext(sessionPath2) {
263835
+ const entries = readTailEntries(sessionPath2);
263836
+ if (entries.length === 0)
263837
+ return void 0;
263838
+ for (let i2 = entries.length - 1; i2 >= 0; i2--) {
263839
+ const e2 = entries[i2];
263840
+ if (e2.type === "compaction" && typeof e2.summary === "string") {
263841
+ return e2.summary;
263842
+ }
263843
+ }
263844
+ const recentMessages = [];
263845
+ const MAX_MESSAGES = 6;
263846
+ for (let i2 = entries.length - 1; i2 >= 0 && recentMessages.length < MAX_MESSAGES; i2--) {
263847
+ const e2 = entries[i2];
263848
+ if (e2.type !== "message")
263849
+ continue;
263850
+ const msg = e2.message;
263851
+ if (!msg)
263852
+ continue;
263853
+ if (msg.role !== "user" && msg.role !== "assistant")
263854
+ continue;
263855
+ let text = "";
263856
+ if (typeof msg.content === "string") {
263857
+ text = msg.content;
263858
+ } else if (Array.isArray(msg.content)) {
263859
+ text = msg.content.filter((c) => c.type === "text" && c.text).map((c) => c.text).join("\n");
263860
+ }
263861
+ if (text) {
263862
+ recentMessages.unshift(`[${msg.role}]: ${text}`);
263863
+ }
263864
+ }
263865
+ if (recentMessages.length === 0)
263866
+ return void 0;
263867
+ return "## Previous Session Context (auto-extracted)\n\nThe following is the tail of the previous conversation:\n\n" + recentMessages.join("\n\n");
263868
+ }
263869
+
263870
+ // ../../packages/runner-pi/dist/usage-metadata.js
263871
+ function usageToMessageMetadata(usage) {
263872
+ return {
263873
+ input_tokens: usage.input,
263874
+ output_tokens: usage.output,
263875
+ cache_read_input_tokens: usage.cacheRead,
263876
+ cache_creation_input_tokens: usage.cacheWrite
263877
+ };
263878
+ }
263879
+ function accumulateToolUsage(tally, raw) {
263880
+ for (const [key, row] of Object.entries(raw)) {
263881
+ const existing = tally[key];
263882
+ if (existing) {
263883
+ for (const [field, val] of Object.entries(row)) {
263884
+ if (typeof val === "number")
263885
+ existing[field] = (existing[field] ?? 0) + val;
263886
+ }
263887
+ } else {
263888
+ const nums = {};
263889
+ for (const [field, val] of Object.entries(row)) {
263890
+ if (typeof val === "number")
263891
+ nums[field] = val;
263892
+ }
263893
+ tally[key] = nums;
263894
+ }
263895
+ }
263896
+ }
263897
+ function getUsageFromAgentEndMessages(messages) {
263898
+ for (let i2 = messages.length - 1; i2 >= 0; i2--) {
263899
+ const m2 = messages[i2];
263900
+ if (m2.role === "assistant" && m2.usage != null)
263901
+ return m2.usage;
263902
+ }
263903
+ return void 0;
263904
+ }
263905
+
263906
+ // ../../packages/runner-pi/dist/stream-converter.js
263907
+ function emitStreamError(errorText) {
263908
+ const errorLine = "data: " + JSON.stringify({ type: "error", errorText }) + "\n\n";
263909
+ const finishLine = "data: " + JSON.stringify({ type: "finish", finishReason: "error" }) + "\n\n";
263910
+ return [errorLine, finishLine, "data: [DONE]\n\n"];
263911
+ }
263912
+ function extractToolResultText(result) {
263913
+ if (result !== null && typeof result === "object") {
263914
+ const r2 = result;
263915
+ if (Array.isArray(r2.content) && r2.content.length > 0) {
263916
+ const text = r2.content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n");
263917
+ if (text.length > 0)
263918
+ return text;
263919
+ }
263920
+ }
263921
+ if (typeof result === "string")
263922
+ return result;
263923
+ try {
263924
+ return JSON.stringify(result);
263925
+ } catch {
263926
+ return String(result);
263927
+ }
263928
+ }
263929
+ function sseData(obj) {
263930
+ return "data: " + JSON.stringify(obj) + "\n\n";
263931
+ }
263932
+ var PiAISDKStreamConverter = class {
263933
+ constructor(options2) {
263934
+ this.options = options2;
263935
+ this.messageId = "msg_" + Date.now() + "_" + Math.random().toString(36).slice(2);
263936
+ this.toolUsageTally = {};
263937
+ this.activeTextPartId = null;
263938
+ this.hasStarted = false;
263939
+ this.hasFinished = false;
263940
+ }
263941
+ get finished() {
263942
+ return this.hasFinished;
263943
+ }
263944
+ forceError(errorText) {
263945
+ if (this.hasFinished)
263946
+ return [];
263947
+ return [...this.ensureStart(), ...this.finishError(errorText)];
263948
+ }
263949
+ handleEvent(event, aborted) {
263950
+ if (this.hasFinished)
263951
+ return [];
263952
+ const chunks = [...this.ensureStart()];
263953
+ if (event.type === "message_start") {
263954
+ const msg = event.message;
263955
+ if (msg?.role === "assistant")
263956
+ chunks.push(...this.endTextStreamIfOpen());
263957
+ return chunks;
263958
+ }
263959
+ if (event.type === "message_end")
263960
+ return chunks;
263961
+ if (event.type === "message_update") {
263962
+ const sub = event.assistantMessageEvent;
263963
+ if (sub.type === "text_start")
263964
+ chunks.push(...this.endTextStreamIfOpen(), ...this.openTextStream());
263965
+ else if (sub.type === "text_delta")
263966
+ chunks.push(...this.emitTextDelta(sub.delta));
263967
+ else if (sub.type === "toolcall_start")
263968
+ chunks.push(...this.endTextStreamIfOpen());
263969
+ return chunks;
263970
+ }
263971
+ if (event.type === "tool_execution_start") {
263972
+ chunks.push(...this.endTextStreamIfOpen());
263973
+ chunks.push(sseData({
263974
+ type: "tool-input-start",
263975
+ toolCallId: event.toolCallId,
263976
+ toolName: event.toolName,
263977
+ dynamic: true,
263978
+ providerExecuted: true
263979
+ }), sseData({
263980
+ type: "tool-input-available",
263981
+ toolCallId: event.toolCallId,
263982
+ toolName: event.toolName,
263983
+ input: event.args,
263984
+ dynamic: true,
263985
+ providerExecuted: true
263986
+ }));
263987
+ return chunks;
263988
+ }
263989
+ if (event.type === "tool_execution_end") {
263990
+ const output = this.options.redactText(this.options.normalizeToolOutput(event.result));
263991
+ const raw = event.result?.details?.usage?.raw;
263992
+ if (raw != null)
263993
+ accumulateToolUsage(this.toolUsageTally, raw);
263994
+ chunks.push(sseData({
263995
+ type: "tool-output-available",
263996
+ toolCallId: event.toolCallId,
263997
+ output,
263998
+ isError: event.isError,
263999
+ dynamic: true,
264000
+ providerExecuted: true
264001
+ }));
264002
+ return chunks;
264003
+ }
264004
+ if (event.type === "agent_end") {
264005
+ if (aborted) {
264006
+ chunks.push(...this.finishError("Run aborted by signal."));
264007
+ } else {
264008
+ const errorMsg = this.options.getErrorFromAgentEndMessages(event.messages);
264009
+ if (errorMsg)
264010
+ chunks.push(...this.finishError(errorMsg));
264011
+ else
264012
+ chunks.push(...this.finishSuccess(this.options.getUsageFromAgentEndMessages(event.messages)));
264013
+ }
264014
+ return chunks;
264015
+ }
264016
+ return chunks;
264017
+ }
264018
+ ensureStart() {
264019
+ if (this.hasStarted)
264020
+ return [];
264021
+ this.hasStarted = true;
264022
+ return [
264023
+ sseData({ type: "start", messageId: this.messageId }),
264024
+ sseData({
264025
+ type: "message-metadata",
264026
+ messageMetadata: { sessionId: this.options.sessionId }
264027
+ })
264028
+ ];
264029
+ }
264030
+ newTextPartId() {
264031
+ return "text_" + Date.now() + "_" + Math.random().toString(36).slice(2) + "_" + Math.random().toString(36).slice(2);
264032
+ }
264033
+ openTextStream() {
264034
+ this.activeTextPartId = this.newTextPartId();
264035
+ return [sseData({ type: "text-start", id: this.activeTextPartId })];
264036
+ }
264037
+ emitTextDelta(rawDelta) {
264038
+ const delta = rawDelta ? this.options.redactText(rawDelta) : void 0;
264039
+ if (!delta)
264040
+ return [];
264041
+ const startChunk = this.activeTextPartId == null ? this.openTextStream() : [];
264042
+ return [
264043
+ ...startChunk,
264044
+ sseData({ type: "text-delta", id: this.activeTextPartId, delta })
264045
+ ];
264046
+ }
264047
+ endTextStreamIfOpen() {
264048
+ if (this.activeTextPartId == null)
264049
+ return [];
264050
+ const id = this.activeTextPartId;
264051
+ this.activeTextPartId = null;
264052
+ return [sseData({ type: "text-end", id })];
264053
+ }
264054
+ finishSuccess(usage) {
264055
+ const chunks = [...this.endTextStreamIfOpen()];
264056
+ const raw = {};
264057
+ let chatUsage;
264058
+ if (usage) {
264059
+ const { id } = this.options.model;
264060
+ chatUsage = {
264061
+ type: "chat",
264062
+ ...usageToMessageMetadata(usage)
264063
+ };
264064
+ raw[id] = chatUsage;
264065
+ }
264066
+ for (const [key, tally] of Object.entries(this.toolUsageTally)) {
264067
+ raw[key] = { ...tally };
264068
+ }
264069
+ const finishPayload = {
264070
+ type: "finish",
264071
+ finishReason: "stop"
264072
+ };
264073
+ if (usage) {
264074
+ finishPayload.messageMetadata = { usage: { ...chatUsage, raw } };
264075
+ }
264076
+ chunks.push(sseData(finishPayload), "data: [DONE]\n\n");
264077
+ this.hasFinished = true;
264078
+ return chunks;
264079
+ }
264080
+ finishError(errorText) {
264081
+ this.hasFinished = true;
264082
+ return emitStreamError(errorText);
264083
+ }
264084
+ };
264085
+
263774
264086
  // ../../packages/runner-pi/dist/web-tools.js
263775
264087
  var braveProvider = {
263776
264088
  id: "brave",
263777
264089
  label: "Brave Search",
263778
264090
  envKeys: ["BRAVE_API_KEY"],
263779
- async search({ apiKey, query, count, country, freshness }) {
264091
+ async search({ apiKey, query, count, country, freshness, signal }) {
263780
264092
  const params = new URLSearchParams({
263781
264093
  q: query,
263782
264094
  count: String(Math.min(count, 20))
@@ -263790,7 +264102,8 @@ var braveProvider = {
263790
264102
  Accept: "application/json",
263791
264103
  "Accept-Encoding": "gzip",
263792
264104
  "X-Subscription-Token": apiKey
263793
- }
264105
+ },
264106
+ signal
263794
264107
  });
263795
264108
  if (!res.ok) {
263796
264109
  const body = await res.text().catch(() => "");
@@ -263811,14 +264124,14 @@ ${body}`);
263811
264124
  });
263812
264125
  }
263813
264126
  }
263814
- return results;
264127
+ return { results };
263815
264128
  }
263816
264129
  };
263817
264130
  var tavilyProvider = {
263818
264131
  id: "tavily",
263819
264132
  label: "Tavily",
263820
264133
  envKeys: ["TAVILY_API_KEY"],
263821
- async search({ apiKey, query, count }) {
264134
+ async search({ apiKey, query, count, signal }) {
263822
264135
  const res = await fetch("https://api.tavily.com/search", {
263823
264136
  method: "POST",
263824
264137
  headers: { "Content-Type": "application/json" },
@@ -263827,7 +264140,8 @@ var tavilyProvider = {
263827
264140
  query,
263828
264141
  max_results: Math.min(count, 10),
263829
264142
  include_answer: false
263830
- })
264143
+ }),
264144
+ signal
263831
264145
  });
263832
264146
  if (!res.ok) {
263833
264147
  const body = await res.text().catch(() => "");
@@ -263845,7 +264159,7 @@ ${body}`);
263845
264159
  });
263846
264160
  }
263847
264161
  }
263848
- return results;
264162
+ return { results };
263849
264163
  }
263850
264164
  };
263851
264165
  var AUTO_DETECT_ORDER = [braveProvider, tavilyProvider];
@@ -263880,9 +264194,12 @@ var BROWSER_UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/53
263880
264194
  function htmlToText(html2) {
263881
264195
  return html2.replace(/<(script|style|noscript)[^>]*>[\s\S]*?<\/\1>/gi, "").replace(/<br\s*\/?>/gi, "\n").replace(/<\/(p|div|h[1-6]|li|tr)>/gi, "\n").replace(/<(p|div|h[1-6]|li|tr)[^>]*>/gi, "\n").replace(/<[^>]+>/g, "").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&nbsp;/g, " ").replace(/[ \t]+/g, " ").replace(/\n{3,}/g, "\n\n").trim();
263882
264196
  }
263883
- async function fetchPageContent(url) {
264197
+ async function fetchPageContent(url, externalSignal) {
263884
264198
  const controller = new AbortController();
263885
264199
  const timeout = setTimeout(() => controller.abort(), 15e3);
264200
+ externalSignal?.addEventListener("abort", () => controller.abort(), {
264201
+ once: true
264202
+ });
263886
264203
  try {
263887
264204
  const res = await fetch(url, {
263888
264205
  headers: {
@@ -263979,7 +264296,7 @@ function buildWebSearchTool(env2) {
263979
264296
  ],
263980
264297
  // biome-ignore lint/suspicious/noExplicitAny: plain JSON Schema compatible with TypeBox TSchema
263981
264298
  parameters: webSearchSchema,
263982
- async execute(_toolCallId, params, _signal, _onUpdate) {
264299
+ async execute(_toolCallId, params, signal, _onUpdate) {
263983
264300
  const p = params;
263984
264301
  const query = p.query;
263985
264302
  const count = p.count ?? 5;
@@ -263989,18 +264306,29 @@ function buildWebSearchTool(env2) {
263989
264306
  let lastError;
263990
264307
  for (const { provider, apiKey } of providers) {
263991
264308
  try {
263992
- const results = await provider.search({
264309
+ const { results } = await provider.search({
263993
264310
  apiKey,
263994
264311
  query,
263995
264312
  count,
263996
264313
  country,
263997
- freshness
264314
+ freshness,
264315
+ signal
263998
264316
  });
264317
+ let fetchedPages = 0;
263999
264318
  if (shouldFetchContent) {
264000
264319
  for (const r2 of results) {
264001
- r2.content = await fetchPageContent(r2.link);
264320
+ r2.content = await fetchPageContent(r2.link, signal);
264321
+ fetchedPages += 1;
264002
264322
  }
264003
264323
  }
264324
+ const usage = {
264325
+ raw: {
264326
+ [provider.id]: {
264327
+ requests: 1,
264328
+ fetchedPages
264329
+ }
264330
+ }
264331
+ };
264004
264332
  return {
264005
264333
  content: [
264006
264334
  {
@@ -264008,7 +264336,9 @@ function buildWebSearchTool(env2) {
264008
264336
  text: formatSearchResults(results, provider.label)
264009
264337
  }
264010
264338
  ],
264011
- details: void 0
264339
+ details: {
264340
+ usage
264341
+ }
264012
264342
  };
264013
264343
  } catch (e2) {
264014
264344
  lastError = e2;
@@ -264044,11 +264374,11 @@ function buildWebFetchTool() {
264044
264374
  ],
264045
264375
  // biome-ignore lint/suspicious/noExplicitAny: plain JSON Schema compatible with TypeBox TSchema
264046
264376
  parameters: webFetchSchema,
264047
- async execute(_toolCallId, params, _signal, _onUpdate) {
264377
+ async execute(_toolCallId, params, signal, _onUpdate) {
264048
264378
  const p = params;
264049
264379
  const url = p.url;
264050
264380
  try {
264051
- const content = await fetchPageContent(url);
264381
+ const content = await fetchPageContent(url, signal);
264052
264382
  return {
264053
264383
  content: [{ type: "text", text: content }],
264054
264384
  details: void 0
@@ -264191,52 +264521,6 @@ function applyModelOverrides(model, provider, optionsEnv) {
264191
264521
  model.baseUrl = anthropicBaseUrl;
264192
264522
  }
264193
264523
  }
264194
- function emitStreamError(errorText) {
264195
- return [
264196
- `data: ${JSON.stringify({ type: "error", errorText })}
264197
-
264198
- `,
264199
- `data: ${JSON.stringify({ type: "finish", finishReason: "error" })}
264200
-
264201
- `,
264202
- "data: [DONE]\n\n"
264203
- ];
264204
- }
264205
- function extractToolResultText(result) {
264206
- if (result !== null && typeof result === "object") {
264207
- const r2 = result;
264208
- if (Array.isArray(r2.content) && r2.content.length > 0) {
264209
- const text = r2.content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n");
264210
- if (text.length > 0) {
264211
- return text;
264212
- }
264213
- }
264214
- }
264215
- if (typeof result === "string")
264216
- return result;
264217
- try {
264218
- return JSON.stringify(result);
264219
- } catch {
264220
- return String(result);
264221
- }
264222
- }
264223
- function usageToMessageMetadata(usage) {
264224
- return {
264225
- input_tokens: usage.input,
264226
- output_tokens: usage.output,
264227
- cache_read_input_tokens: usage.cacheRead,
264228
- cache_creation_input_tokens: usage.cacheWrite
264229
- };
264230
- }
264231
- function getUsageFromAgentEndMessages(messages) {
264232
- for (let i2 = messages.length - 1; i2 >= 0; i2--) {
264233
- const m2 = messages[i2];
264234
- if (m2.role === "assistant" && m2.usage != null) {
264235
- return m2.usage;
264236
- }
264237
- }
264238
- return void 0;
264239
- }
264240
264524
  function getErrorFromAgentEndMessages(messages) {
264241
264525
  for (let i2 = messages.length - 1; i2 >= 0; i2--) {
264242
264526
  const m2 = messages[i2];
@@ -264252,7 +264536,7 @@ function traceRawMessage(debugCwd, data, reset = false, optionsEnv) {
264252
264536
  if (!enabled)
264253
264537
  return;
264254
264538
  try {
264255
- const file = join35(debugCwd, "pi-message-stream-debug.json");
264539
+ const file = join36(debugCwd, "pi-message-stream-debug.json");
264256
264540
  if (reset && existsSync28(file))
264257
264541
  unlinkSync6(file);
264258
264542
  const type = data !== null && typeof data === "object" ? data.type : void 0;
@@ -264321,9 +264605,22 @@ function createPiRunner(options2 = {}) {
264321
264605
  if (resume.includes("/")) {
264322
264606
  return SessionManager.open(resume);
264323
264607
  }
264324
- const sessions = await SessionManager.list(cwd);
264325
- const found = sessions.find((s2) => s2.id === resume);
264326
- return found ? SessionManager.open(found.path) : SessionManager.create(cwd);
264608
+ const sessionPath2 = resolveSessionPathById(cwd, resume);
264609
+ console.error(`${LOG_PREFIX2} resume: id=${resume} path=${sessionPath2 ?? "(not found)"}`);
264610
+ if (sessionPath2) {
264611
+ if (isSessionFileTooLarge(sessionPath2)) {
264612
+ const context = extractSessionContext(sessionPath2);
264613
+ console.error(`${LOG_PREFIX2} session file too large, starting fresh${context ? " (with context)" : ""}`);
264614
+ const newMgr = SessionManager.create(cwd);
264615
+ if (context) {
264616
+ const firstId = newMgr.getEntries()[0]?.id ?? "";
264617
+ newMgr.appendCompaction(context, firstId, 0);
264618
+ }
264619
+ return newMgr;
264620
+ }
264621
+ return SessionManager.open(sessionPath2);
264622
+ }
264623
+ return SessionManager.create(cwd);
264327
264624
  }
264328
264625
  return SessionManager.create(cwd);
264329
264626
  })();
@@ -264381,165 +264678,34 @@ function createPiRunner(options2 = {}) {
264381
264678
  }
264382
264679
  try {
264383
264680
  traceRawMessage(cwd, null, true, options2.env);
264384
- let promptText = userInput;
264385
- let images;
264386
- try {
264387
- if (userInput.startsWith("[") && userInput.endsWith("]")) {
264388
- const parsed = JSON.parse(userInput);
264389
- if (Array.isArray(parsed)) {
264390
- promptText = parsed.filter((p) => p.type === "text").map((p) => p.text).join("\n");
264391
- const imageParts = parsed.filter((p) => p.type === "image");
264392
- if (imageParts.length > 0) {
264393
- images = imageParts.map((p) => ({
264394
- type: "image",
264395
- data: p.data,
264396
- mimeType: p.mimeType
264397
- }));
264398
- }
264681
+ const promptText = userInput;
264682
+ const promptPromise = session.prompt(promptText);
264683
+ const streamConverter = new PiAISDKStreamConverter({
264684
+ sessionId: session.sessionId,
264685
+ model,
264686
+ redactText: (value2) => {
264687
+ if (options2.env && Object.keys(options2.env).length > 0) {
264688
+ return redactSecrets(value2, options2.env);
264399
264689
  }
264400
- }
264401
- } catch (_e2) {
264402
- }
264403
- const promptPromise = session.prompt(promptText, images ? { images } : void 0);
264404
- const messageId = `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`;
264405
- let hasStarted = false;
264406
- let hasFinished = false;
264407
- const imageToolUsage = { input_tokens: 0, output_tokens: 0 };
264408
- const newTextPartId = () => `text_${Date.now()}_${Math.random().toString(36).slice(2)}_${Math.random().toString(36).slice(2)}`;
264409
- let activeTextPartId = null;
264410
- let textStreamOpen = false;
264411
- const endTextStreamIfOpen = function* () {
264412
- if (textStreamOpen && activeTextPartId != null) {
264413
- yield `data: ${JSON.stringify({ type: "text-end", id: activeTextPartId })}
264414
-
264415
- `;
264416
- textStreamOpen = false;
264417
- activeTextPartId = null;
264418
- }
264419
- };
264420
- const beginTextStream = function* () {
264421
- activeTextPartId = newTextPartId();
264422
- yield `data: ${JSON.stringify({ type: "text-start", id: activeTextPartId })}
264423
-
264424
- `;
264425
- textStreamOpen = true;
264426
- };
264427
- const ensureStartEvent = async function* () {
264428
- if (!hasStarted) {
264429
- yield `data: ${JSON.stringify({ type: "start", messageId })}
264430
-
264431
- `;
264432
- yield `data: ${JSON.stringify({
264433
- type: "message-metadata",
264434
- messageMetadata: { sessionId: session.sessionId }
264435
- })}
264436
-
264437
- `;
264438
- hasStarted = true;
264439
- }
264440
- };
264441
- const finishSuccess = async function* (usage) {
264442
- yield* endTextStreamIfOpen();
264443
- const finishPayload = { type: "finish", finishReason: "stop" };
264444
- const hasImageUsage = imageToolUsage.input_tokens > 0 || imageToolUsage.output_tokens > 0;
264445
- if (usage != null || hasImageUsage) {
264446
- const base = usage != null ? usageToMessageMetadata(usage) : {};
264447
- finishPayload.messageMetadata = {
264448
- usage: {
264449
- ...base,
264450
- input_tokens: (base.input_tokens ?? 0) + imageToolUsage.input_tokens,
264451
- output_tokens: (base.output_tokens ?? 0) + imageToolUsage.output_tokens
264452
- }
264453
- };
264454
- }
264455
- yield `data: ${JSON.stringify(finishPayload)}
264456
-
264457
- `;
264458
- yield "data: [DONE]\n\n";
264459
- hasFinished = true;
264460
- };
264461
- const finishError = async function* (errorText) {
264462
- for (const chunk of emitStreamError(errorText)) {
264463
- yield chunk;
264464
- }
264465
- hasFinished = true;
264466
- };
264690
+ return value2;
264691
+ },
264692
+ normalizeToolOutput: extractToolResultText,
264693
+ getUsageFromAgentEndMessages,
264694
+ getErrorFromAgentEndMessages
264695
+ });
264467
264696
  while (!isComplete || eventQueue.length > 0) {
264468
264697
  while (eventQueue.length > 0) {
264469
264698
  const event = eventQueue.shift();
264470
264699
  traceRawMessage(cwd, event, false, options2.env);
264471
- yield* ensureStartEvent();
264472
- if (event.type === "message_start") {
264473
- const msg = event.message;
264474
- if (msg?.role === "assistant") {
264475
- yield* endTextStreamIfOpen();
264476
- }
264477
- } else if (event.type === "message_update") {
264478
- const sub = event.assistantMessageEvent;
264479
- if (sub.type === "text_start") {
264480
- yield* endTextStreamIfOpen();
264481
- yield* beginTextStream();
264482
- } else if (sub.type === "text_delta") {
264483
- let delta = sub.delta;
264484
- if (delta) {
264485
- if (options2.env && Object.keys(options2.env).length > 0) {
264486
- delta = redactSecrets(delta, options2.env);
264487
- }
264488
- if (!textStreamOpen) {
264489
- yield* beginTextStream();
264490
- }
264491
- yield `data: ${JSON.stringify({
264492
- type: "text-delta",
264493
- id: activeTextPartId,
264494
- delta
264495
- })}
264496
-
264497
- `;
264498
- }
264499
- } else if (sub.type === "toolcall_start") {
264500
- yield* endTextStreamIfOpen();
264501
- }
264502
- } else if (event.type === "tool_execution_start") {
264503
- yield* endTextStreamIfOpen();
264504
- yield `data: ${JSON.stringify({ type: "tool-input-start", toolCallId: event.toolCallId, toolName: event.toolName, dynamic: true, providerExecuted: true })}
264505
-
264506
- `;
264507
- yield `data: ${JSON.stringify({ type: "tool-input-available", toolCallId: event.toolCallId, toolName: event.toolName, input: event.args, dynamic: true, providerExecuted: true })}
264508
-
264509
- `;
264510
- } else if (event.type === "tool_execution_end") {
264511
- let output = extractToolResultText(event.result);
264512
- if (options2.env && Object.keys(options2.env).length > 0) {
264513
- output = redactSecrets(output, options2.env);
264514
- }
264515
- if ((event.toolName === "generate_image" || event.toolName === "edit_image") && event.result !== null && typeof event.result === "object") {
264516
- const details = event.result.details;
264517
- const u = details?.response?.usage;
264518
- if (u) {
264519
- imageToolUsage.input_tokens += u.input_tokens ?? 0;
264520
- imageToolUsage.output_tokens += u.output_tokens ?? 0;
264521
- }
264522
- }
264523
- yield `data: ${JSON.stringify({ type: "tool-output-available", toolCallId: event.toolCallId, output, isError: event.isError, dynamic: true, providerExecuted: true })}
264524
-
264525
- `;
264526
- } else if (event.type === "agent_end") {
264527
- if (aborted) {
264528
- yield* finishError("Run aborted by signal.");
264529
- } else {
264530
- const errorMsg = getErrorFromAgentEndMessages(event.messages);
264531
- if (errorMsg) {
264532
- yield* finishError(errorMsg);
264533
- } else {
264534
- const usage = getUsageFromAgentEndMessages(event.messages);
264535
- yield* finishSuccess(usage);
264536
- }
264537
- }
264700
+ const chunks = streamConverter.handleEvent(event, aborted);
264701
+ for (const chunk of chunks) {
264702
+ yield chunk;
264538
264703
  }
264539
264704
  }
264540
- if (aborted && !hasFinished) {
264541
- yield* ensureStartEvent();
264542
- yield* finishError("Run aborted by signal.");
264705
+ if (aborted && !streamConverter.finished) {
264706
+ for (const chunk of streamConverter.forceError("Run aborted by signal.")) {
264707
+ yield chunk;
264708
+ }
264543
264709
  break;
264544
264710
  }
264545
264711
  if (!isComplete && eventQueue.length === 0) {
@@ -264548,22 +264714,24 @@ function createPiRunner(options2 = {}) {
264548
264714
  });
264549
264715
  }
264550
264716
  }
264551
- if (hasFinished) {
264717
+ if (streamConverter.finished) {
264552
264718
  return;
264553
264719
  }
264554
264720
  try {
264555
264721
  await promptPromise;
264556
264722
  } catch (error) {
264557
- if (!hasFinished) {
264558
- yield* ensureStartEvent();
264723
+ if (!streamConverter.finished) {
264559
264724
  const message = error instanceof Error ? error.message : "Pi agent run failed.";
264560
- yield* finishError(message);
264725
+ for (const chunk of streamConverter.forceError(message)) {
264726
+ yield chunk;
264727
+ }
264561
264728
  }
264562
264729
  return;
264563
264730
  }
264564
- if (!hasFinished && session.agent.state.error) {
264565
- yield* ensureStartEvent();
264566
- yield* finishError(session.agent.state.error);
264731
+ if (!streamConverter.finished && session.agent.state.error) {
264732
+ for (const chunk of streamConverter.forceError(session.agent.state.error)) {
264733
+ yield chunk;
264734
+ }
264567
264735
  }
264568
264736
  } finally {
264569
264737
  if (abortSignal) {
@@ -264583,11 +264751,11 @@ function createPiRunner(options2 = {}) {
264583
264751
 
264584
264752
  // ../../packages/runner-harness/dist/session.js
264585
264753
  import { existsSync as existsSync29, mkdirSync as mkdirSync11, readFileSync as readFileSync23, writeFileSync as writeFileSync14 } from "node:fs";
264586
- import { join as join36 } from "node:path";
264754
+ import { join as join37 } from "node:path";
264587
264755
  var DIR = ".bunny-agent";
264588
264756
  var FILE = "session-id";
264589
264757
  function sessionPath(cwd) {
264590
- return join36(cwd, DIR, FILE);
264758
+ return join37(cwd, DIR, FILE);
264591
264759
  }
264592
264760
  function readSessionId(cwd) {
264593
264761
  try {
@@ -264601,28 +264769,28 @@ function readSessionId(cwd) {
264601
264769
  }
264602
264770
  function writeSessionId(cwd, id) {
264603
264771
  try {
264604
- mkdirSync11(join36(cwd, DIR), { recursive: true });
264772
+ mkdirSync11(join37(cwd, DIR), { recursive: true });
264605
264773
  writeFileSync14(sessionPath(cwd), id, "utf8");
264606
264774
  } catch {
264607
264775
  }
264608
264776
  }
264609
264777
 
264610
264778
  // ../../packages/runner-harness/dist/skills.js
264611
- import { existsSync as existsSync30, readdirSync as readdirSync12, statSync as statSync13 } from "node:fs";
264779
+ import { existsSync as existsSync30, readdirSync as readdirSync13, statSync as statSync14 } from "node:fs";
264612
264780
  import { homedir as homedir14 } from "node:os";
264613
- import { join as join37 } from "node:path";
264781
+ import { join as join38 } from "node:path";
264614
264782
  function discoverSkillPaths(cwd) {
264615
264783
  const paths = [];
264616
264784
  for (const base of [
264617
- join37(cwd, "skills"),
264618
- join37(homedir14(), ".bunny-agent", "skills")
264785
+ join38(cwd, "skills"),
264786
+ join38(homedir14(), ".bunny-agent", "skills")
264619
264787
  ]) {
264620
264788
  if (!existsSync30(base))
264621
264789
  continue;
264622
264790
  try {
264623
- for (const entry of readdirSync12(base)) {
264624
- const full = join37(base, entry);
264625
- if (statSync13(full).isDirectory() && existsSync30(join37(full, "SKILL.md"))) {
264791
+ for (const entry of readdirSync13(base)) {
264792
+ const full = join38(base, entry);
264793
+ if (statSync14(full).isDirectory() && existsSync30(join38(full, "SKILL.md"))) {
264626
264794
  paths.push(full);
264627
264795
  }
264628
264796
  }