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