@bunny-agent/daemon 0.9.29-beta.6 → 0.9.29-beta.7

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/nextjs.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() {
@@ -208380,7 +208380,7 @@ function createOpenCodeRunner(options2 = {}) {
208380
208380
 
208381
208381
  // ../../packages/runner-pi/dist/pi-runner.js
208382
208382
  import { appendFileSync as appendFileSync5, existsSync as existsSync28, unlinkSync as unlinkSync6 } from "node:fs";
208383
- import { join as join35 } from "node:path";
208383
+ import { join as join36 } from "node:path";
208384
208384
 
208385
208385
  // ../../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
208386
208386
  var dist_exports = {};
@@ -263366,8 +263366,8 @@ var generateImageSchema = {
263366
263366
  },
263367
263367
  quality: {
263368
263368
  type: "string",
263369
- enum: ["standard", "hd"],
263370
- description: "Image quality (OpenAI only). Defaults to standard."
263369
+ enum: ["low", "medium", "high", "auto"],
263370
+ description: "Image quality. Defaults to auto."
263371
263371
  }
263372
263372
  },
263373
263373
  required: ["prompt"],
@@ -263529,7 +263529,7 @@ function buildImageGenerateTool(cwd, imageModelId, baseUrl, apiKey) {
263529
263529
  const p = params;
263530
263530
  const prompt = p.prompt;
263531
263531
  const size = p.size ?? "1024x1024";
263532
- const quality = p.quality ?? "standard";
263532
+ const quality = p.quality ?? "auto";
263533
263533
  const rawFilename = p.filename;
263534
263534
  const filename = rawFilename ? extname2(rawFilename) ? rawFilename : `${rawFilename}.png` : `image_${Date.now()}.png`;
263535
263535
  const filePath = join34(cwd, filename.replace(/[^a-zA-Z0-9_\-./]/g, "_"));
@@ -263567,6 +263567,7 @@ function buildImageGenerateTool(cwd, imageModelId, baseUrl, apiKey) {
263567
263567
  ],
263568
263568
  details: {
263569
263569
  filePath: savedPath,
263570
+ ...json.usage != null ? { usage: { raw: { [imageModelId]: json.usage } } } : {},
263570
263571
  response: json
263571
263572
  }
263572
263573
  };
@@ -263754,6 +263755,7 @@ function buildImageEditTool(cwd, imageModelId, baseUrl, apiKey) {
263754
263755
  ],
263755
263756
  details: {
263756
263757
  filePath: savedPath,
263758
+ ...json.usage != null ? { usage: { raw: { [imageModelId]: json.usage } } } : {},
263757
263759
  response: json
263758
263760
  }
263759
263761
  };
@@ -263770,6 +263772,309 @@ function buildImageEditTool(cwd, imageModelId, baseUrl, apiKey) {
263770
263772
  };
263771
263773
  }
263772
263774
 
263775
+ // ../../packages/runner-pi/dist/session-utils.js
263776
+ import { closeSync as closeSync2, fstatSync, openSync as openSync2, readdirSync as readdirSync12, readSync as readSync2, statSync as statSync13 } from "node:fs";
263777
+ import { join as join35 } from "node:path";
263778
+ var MAX_SESSION_FILE_BYTES = Number(process.env.SANDAGENT_MAX_SESSION_BYTES) || 10 * 1024 * 1024;
263779
+ function resolveSessionPathById(cwd, sessionId) {
263780
+ const tempMgr = SessionManager.create(cwd);
263781
+ const sessionsDir = tempMgr.getSessionDir();
263782
+ try {
263783
+ const suffix = `_${sessionId}.jsonl`;
263784
+ const match2 = readdirSync12(sessionsDir).find((f3) => f3.endsWith(suffix));
263785
+ return match2 ? join35(sessionsDir, match2) : void 0;
263786
+ } catch {
263787
+ return void 0;
263788
+ }
263789
+ }
263790
+ function isSessionFileTooLarge(sessionPath2) {
263791
+ try {
263792
+ return statSync13(sessionPath2).size > MAX_SESSION_FILE_BYTES;
263793
+ } catch {
263794
+ return false;
263795
+ }
263796
+ }
263797
+ function readTailEntries(sessionPath2, tailBytes = 1024 * 1024) {
263798
+ let fd;
263799
+ try {
263800
+ fd = openSync2(sessionPath2, "r");
263801
+ } catch {
263802
+ return [];
263803
+ }
263804
+ try {
263805
+ const fileSize = fstatSync(fd).size;
263806
+ const readStart = Math.max(0, fileSize - tailBytes);
263807
+ const readLen = fileSize - readStart;
263808
+ const buf = Buffer.alloc(readLen);
263809
+ readSync2(fd, buf, 0, readLen, readStart);
263810
+ const tail = buf.toString("utf8");
263811
+ const entries = [];
263812
+ for (const line of tail.split("\n")) {
263813
+ const trimmed = line.trim();
263814
+ if (!trimmed)
263815
+ continue;
263816
+ try {
263817
+ entries.push(JSON.parse(trimmed));
263818
+ } catch {
263819
+ }
263820
+ }
263821
+ return entries;
263822
+ } finally {
263823
+ closeSync2(fd);
263824
+ }
263825
+ }
263826
+ function extractSessionContext(sessionPath2) {
263827
+ const entries = readTailEntries(sessionPath2);
263828
+ if (entries.length === 0)
263829
+ return void 0;
263830
+ for (let i2 = entries.length - 1; i2 >= 0; i2--) {
263831
+ const e2 = entries[i2];
263832
+ if (e2.type === "compaction" && typeof e2.summary === "string") {
263833
+ return e2.summary;
263834
+ }
263835
+ }
263836
+ const recentMessages = [];
263837
+ const MAX_MESSAGES = 6;
263838
+ for (let i2 = entries.length - 1; i2 >= 0 && recentMessages.length < MAX_MESSAGES; i2--) {
263839
+ const e2 = entries[i2];
263840
+ if (e2.type !== "message")
263841
+ continue;
263842
+ const msg = e2.message;
263843
+ if (!msg)
263844
+ continue;
263845
+ if (msg.role !== "user" && msg.role !== "assistant")
263846
+ continue;
263847
+ let text = "";
263848
+ if (typeof msg.content === "string") {
263849
+ text = msg.content;
263850
+ } else if (Array.isArray(msg.content)) {
263851
+ text = msg.content.filter((c) => c.type === "text" && c.text).map((c) => c.text).join("\n");
263852
+ }
263853
+ if (text) {
263854
+ recentMessages.unshift(`[${msg.role}]: ${text}`);
263855
+ }
263856
+ }
263857
+ if (recentMessages.length === 0)
263858
+ return void 0;
263859
+ return "## Previous Session Context (auto-extracted)\n\nThe following is the tail of the previous conversation:\n\n" + recentMessages.join("\n\n");
263860
+ }
263861
+
263862
+ // ../../packages/runner-pi/dist/usage-metadata.js
263863
+ function usageToMessageMetadata(usage) {
263864
+ return {
263865
+ input_tokens: usage.input,
263866
+ output_tokens: usage.output,
263867
+ cache_read_input_tokens: usage.cacheRead,
263868
+ cache_creation_input_tokens: usage.cacheWrite
263869
+ };
263870
+ }
263871
+ function accumulateToolUsage(tally, raw) {
263872
+ for (const [key, row] of Object.entries(raw)) {
263873
+ const existing = tally[key];
263874
+ if (existing) {
263875
+ for (const [field, val] of Object.entries(row)) {
263876
+ if (typeof val === "number")
263877
+ existing[field] = (existing[field] ?? 0) + val;
263878
+ }
263879
+ } else {
263880
+ const nums = {};
263881
+ for (const [field, val] of Object.entries(row)) {
263882
+ if (typeof val === "number")
263883
+ nums[field] = val;
263884
+ }
263885
+ tally[key] = nums;
263886
+ }
263887
+ }
263888
+ }
263889
+ function getUsageFromAgentEndMessages(messages) {
263890
+ for (let i2 = messages.length - 1; i2 >= 0; i2--) {
263891
+ const m2 = messages[i2];
263892
+ if (m2.role === "assistant" && m2.usage != null)
263893
+ return m2.usage;
263894
+ }
263895
+ return void 0;
263896
+ }
263897
+
263898
+ // ../../packages/runner-pi/dist/stream-converter.js
263899
+ function emitStreamError(errorText) {
263900
+ const errorLine = "data: " + JSON.stringify({ type: "error", errorText }) + "\n\n";
263901
+ const finishLine = "data: " + JSON.stringify({ type: "finish", finishReason: "error" }) + "\n\n";
263902
+ return [errorLine, finishLine, "data: [DONE]\n\n"];
263903
+ }
263904
+ function extractToolResultText(result) {
263905
+ if (result !== null && typeof result === "object") {
263906
+ const r2 = result;
263907
+ if (Array.isArray(r2.content) && r2.content.length > 0) {
263908
+ const text = r2.content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n");
263909
+ if (text.length > 0)
263910
+ return text;
263911
+ }
263912
+ }
263913
+ if (typeof result === "string")
263914
+ return result;
263915
+ try {
263916
+ return JSON.stringify(result);
263917
+ } catch {
263918
+ return String(result);
263919
+ }
263920
+ }
263921
+ function sseData(obj) {
263922
+ return "data: " + JSON.stringify(obj) + "\n\n";
263923
+ }
263924
+ var PiAISDKStreamConverter = class {
263925
+ constructor(options2) {
263926
+ this.options = options2;
263927
+ this.messageId = "msg_" + Date.now() + "_" + Math.random().toString(36).slice(2);
263928
+ this.toolUsageTally = {};
263929
+ this.activeTextPartId = null;
263930
+ this.hasStarted = false;
263931
+ this.hasFinished = false;
263932
+ }
263933
+ get finished() {
263934
+ return this.hasFinished;
263935
+ }
263936
+ forceError(errorText) {
263937
+ if (this.hasFinished)
263938
+ return [];
263939
+ return [...this.ensureStart(), ...this.finishError(errorText)];
263940
+ }
263941
+ handleEvent(event, aborted) {
263942
+ if (this.hasFinished)
263943
+ return [];
263944
+ const chunks = [...this.ensureStart()];
263945
+ if (event.type === "message_start") {
263946
+ const msg = event.message;
263947
+ if (msg?.role === "assistant")
263948
+ chunks.push(...this.endTextStreamIfOpen());
263949
+ return chunks;
263950
+ }
263951
+ if (event.type === "message_end")
263952
+ return chunks;
263953
+ if (event.type === "message_update") {
263954
+ const sub = event.assistantMessageEvent;
263955
+ if (sub.type === "text_start")
263956
+ chunks.push(...this.endTextStreamIfOpen(), ...this.openTextStream());
263957
+ else if (sub.type === "text_delta")
263958
+ chunks.push(...this.emitTextDelta(sub.delta));
263959
+ else if (sub.type === "toolcall_start")
263960
+ chunks.push(...this.endTextStreamIfOpen());
263961
+ return chunks;
263962
+ }
263963
+ if (event.type === "tool_execution_start") {
263964
+ chunks.push(...this.endTextStreamIfOpen());
263965
+ chunks.push(sseData({
263966
+ type: "tool-input-start",
263967
+ toolCallId: event.toolCallId,
263968
+ toolName: event.toolName,
263969
+ dynamic: true,
263970
+ providerExecuted: true
263971
+ }), sseData({
263972
+ type: "tool-input-available",
263973
+ toolCallId: event.toolCallId,
263974
+ toolName: event.toolName,
263975
+ input: event.args,
263976
+ dynamic: true,
263977
+ providerExecuted: true
263978
+ }));
263979
+ return chunks;
263980
+ }
263981
+ if (event.type === "tool_execution_end") {
263982
+ const output = this.options.redactText(this.options.normalizeToolOutput(event.result));
263983
+ const raw = event.result?.details?.usage?.raw;
263984
+ if (raw != null)
263985
+ accumulateToolUsage(this.toolUsageTally, raw);
263986
+ chunks.push(sseData({
263987
+ type: "tool-output-available",
263988
+ toolCallId: event.toolCallId,
263989
+ output,
263990
+ isError: event.isError,
263991
+ dynamic: true,
263992
+ providerExecuted: true
263993
+ }));
263994
+ return chunks;
263995
+ }
263996
+ if (event.type === "agent_end") {
263997
+ if (aborted) {
263998
+ chunks.push(...this.finishError("Run aborted by signal."));
263999
+ } else {
264000
+ const errorMsg = this.options.getErrorFromAgentEndMessages(event.messages);
264001
+ if (errorMsg)
264002
+ chunks.push(...this.finishError(errorMsg));
264003
+ else
264004
+ chunks.push(...this.finishSuccess(this.options.getUsageFromAgentEndMessages(event.messages)));
264005
+ }
264006
+ return chunks;
264007
+ }
264008
+ return chunks;
264009
+ }
264010
+ ensureStart() {
264011
+ if (this.hasStarted)
264012
+ return [];
264013
+ this.hasStarted = true;
264014
+ return [
264015
+ sseData({ type: "start", messageId: this.messageId }),
264016
+ sseData({
264017
+ type: "message-metadata",
264018
+ messageMetadata: { sessionId: this.options.sessionId }
264019
+ })
264020
+ ];
264021
+ }
264022
+ newTextPartId() {
264023
+ return "text_" + Date.now() + "_" + Math.random().toString(36).slice(2) + "_" + Math.random().toString(36).slice(2);
264024
+ }
264025
+ openTextStream() {
264026
+ this.activeTextPartId = this.newTextPartId();
264027
+ return [sseData({ type: "text-start", id: this.activeTextPartId })];
264028
+ }
264029
+ emitTextDelta(rawDelta) {
264030
+ const delta = rawDelta ? this.options.redactText(rawDelta) : void 0;
264031
+ if (!delta)
264032
+ return [];
264033
+ const startChunk = this.activeTextPartId == null ? this.openTextStream() : [];
264034
+ return [
264035
+ ...startChunk,
264036
+ sseData({ type: "text-delta", id: this.activeTextPartId, delta })
264037
+ ];
264038
+ }
264039
+ endTextStreamIfOpen() {
264040
+ if (this.activeTextPartId == null)
264041
+ return [];
264042
+ const id = this.activeTextPartId;
264043
+ this.activeTextPartId = null;
264044
+ return [sseData({ type: "text-end", id })];
264045
+ }
264046
+ finishSuccess(usage) {
264047
+ const chunks = [...this.endTextStreamIfOpen()];
264048
+ const raw = {};
264049
+ let chatUsage;
264050
+ if (usage) {
264051
+ const { id } = this.options.model;
264052
+ chatUsage = {
264053
+ type: "chat",
264054
+ ...usageToMessageMetadata(usage)
264055
+ };
264056
+ raw[id] = chatUsage;
264057
+ }
264058
+ for (const [key, tally] of Object.entries(this.toolUsageTally)) {
264059
+ raw[key] = { ...tally };
264060
+ }
264061
+ const finishPayload = {
264062
+ type: "finish",
264063
+ finishReason: "stop"
264064
+ };
264065
+ if (usage) {
264066
+ finishPayload.messageMetadata = { usage: { ...chatUsage, raw } };
264067
+ }
264068
+ chunks.push(sseData(finishPayload), "data: [DONE]\n\n");
264069
+ this.hasFinished = true;
264070
+ return chunks;
264071
+ }
264072
+ finishError(errorText) {
264073
+ this.hasFinished = true;
264074
+ return emitStreamError(errorText);
264075
+ }
264076
+ };
264077
+
263773
264078
  // ../../packages/runner-pi/dist/web-tools.js
263774
264079
  var braveProvider = {
263775
264080
  id: "brave",
@@ -263811,7 +264116,7 @@ ${body}`);
263811
264116
  });
263812
264117
  }
263813
264118
  }
263814
- return results;
264119
+ return { results };
263815
264120
  }
263816
264121
  };
263817
264122
  var tavilyProvider = {
@@ -263846,7 +264151,7 @@ ${body}`);
263846
264151
  });
263847
264152
  }
263848
264153
  }
263849
- return results;
264154
+ return { results };
263850
264155
  }
263851
264156
  };
263852
264157
  var AUTO_DETECT_ORDER = [braveProvider, tavilyProvider];
@@ -263993,7 +264298,7 @@ function buildWebSearchTool(env2) {
263993
264298
  let lastError;
263994
264299
  for (const { provider, apiKey } of providers) {
263995
264300
  try {
263996
- const results = await provider.search({
264301
+ const { results } = await provider.search({
263997
264302
  apiKey,
263998
264303
  query,
263999
264304
  count,
@@ -264001,11 +264306,21 @@ function buildWebSearchTool(env2) {
264001
264306
  freshness,
264002
264307
  signal
264003
264308
  });
264309
+ let fetchedPages = 0;
264004
264310
  if (shouldFetchContent) {
264005
264311
  for (const r2 of results) {
264006
264312
  r2.content = await fetchPageContent(r2.link, signal);
264313
+ fetchedPages += 1;
264007
264314
  }
264008
264315
  }
264316
+ const usage = {
264317
+ raw: {
264318
+ [provider.id]: {
264319
+ requests: 1,
264320
+ fetchedPages
264321
+ }
264322
+ }
264323
+ };
264009
264324
  return {
264010
264325
  content: [
264011
264326
  {
@@ -264013,7 +264328,9 @@ function buildWebSearchTool(env2) {
264013
264328
  text: formatSearchResults(results, provider.label)
264014
264329
  }
264015
264330
  ],
264016
- details: void 0
264331
+ details: {
264332
+ usage
264333
+ }
264017
264334
  };
264018
264335
  } catch (e2) {
264019
264336
  lastError = e2;
@@ -264196,52 +264513,6 @@ function applyModelOverrides(model, provider, optionsEnv) {
264196
264513
  model.baseUrl = anthropicBaseUrl;
264197
264514
  }
264198
264515
  }
264199
- function emitStreamError(errorText) {
264200
- return [
264201
- `data: ${JSON.stringify({ type: "error", errorText })}
264202
-
264203
- `,
264204
- `data: ${JSON.stringify({ type: "finish", finishReason: "error" })}
264205
-
264206
- `,
264207
- "data: [DONE]\n\n"
264208
- ];
264209
- }
264210
- function extractToolResultText(result) {
264211
- if (result !== null && typeof result === "object") {
264212
- const r2 = result;
264213
- if (Array.isArray(r2.content) && r2.content.length > 0) {
264214
- const text = r2.content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n");
264215
- if (text.length > 0) {
264216
- return text;
264217
- }
264218
- }
264219
- }
264220
- if (typeof result === "string")
264221
- return result;
264222
- try {
264223
- return JSON.stringify(result);
264224
- } catch {
264225
- return String(result);
264226
- }
264227
- }
264228
- function usageToMessageMetadata(usage) {
264229
- return {
264230
- input_tokens: usage.input,
264231
- output_tokens: usage.output,
264232
- cache_read_input_tokens: usage.cacheRead,
264233
- cache_creation_input_tokens: usage.cacheWrite
264234
- };
264235
- }
264236
- function getUsageFromAgentEndMessages(messages) {
264237
- for (let i2 = messages.length - 1; i2 >= 0; i2--) {
264238
- const m2 = messages[i2];
264239
- if (m2.role === "assistant" && m2.usage != null) {
264240
- return m2.usage;
264241
- }
264242
- }
264243
- return void 0;
264244
- }
264245
264516
  function getErrorFromAgentEndMessages(messages) {
264246
264517
  for (let i2 = messages.length - 1; i2 >= 0; i2--) {
264247
264518
  const m2 = messages[i2];
@@ -264257,7 +264528,7 @@ function traceRawMessage(debugCwd, data, reset = false, optionsEnv) {
264257
264528
  if (!enabled)
264258
264529
  return;
264259
264530
  try {
264260
- const file = join35(debugCwd, "pi-message-stream-debug.json");
264531
+ const file = join36(debugCwd, "pi-message-stream-debug.json");
264261
264532
  if (reset && existsSync28(file))
264262
264533
  unlinkSync6(file);
264263
264534
  const type = data !== null && typeof data === "object" ? data.type : void 0;
@@ -264326,9 +264597,22 @@ function createPiRunner(options2 = {}) {
264326
264597
  if (resume.includes("/")) {
264327
264598
  return SessionManager.open(resume);
264328
264599
  }
264329
- const sessions = await SessionManager.list(cwd);
264330
- const found = sessions.find((s2) => s2.id === resume);
264331
- return found ? SessionManager.open(found.path) : SessionManager.create(cwd);
264600
+ const sessionPath2 = resolveSessionPathById(cwd, resume);
264601
+ console.error(`${LOG_PREFIX2} resume: id=${resume} path=${sessionPath2 ?? "(not found)"}`);
264602
+ if (sessionPath2) {
264603
+ if (isSessionFileTooLarge(sessionPath2)) {
264604
+ const context = extractSessionContext(sessionPath2);
264605
+ console.error(`${LOG_PREFIX2} session file too large, starting fresh${context ? " (with context)" : ""}`);
264606
+ const newMgr = SessionManager.create(cwd);
264607
+ if (context) {
264608
+ const firstId = newMgr.getEntries()[0]?.id ?? "";
264609
+ newMgr.appendCompaction(context, firstId, 0);
264610
+ }
264611
+ return newMgr;
264612
+ }
264613
+ return SessionManager.open(sessionPath2);
264614
+ }
264615
+ return SessionManager.create(cwd);
264332
264616
  }
264333
264617
  return SessionManager.create(cwd);
264334
264618
  })();
@@ -264386,165 +264670,34 @@ function createPiRunner(options2 = {}) {
264386
264670
  }
264387
264671
  try {
264388
264672
  traceRawMessage(cwd, null, true, options2.env);
264389
- let promptText = userInput;
264390
- let images;
264391
- try {
264392
- if (userInput.startsWith("[") && userInput.endsWith("]")) {
264393
- const parsed = JSON.parse(userInput);
264394
- if (Array.isArray(parsed)) {
264395
- promptText = parsed.filter((p) => p.type === "text").map((p) => p.text).join("\n");
264396
- const imageParts = parsed.filter((p) => p.type === "image");
264397
- if (imageParts.length > 0) {
264398
- images = imageParts.map((p) => ({
264399
- type: "image",
264400
- data: p.data,
264401
- mimeType: p.mimeType
264402
- }));
264403
- }
264673
+ const promptText = userInput;
264674
+ const promptPromise = session.prompt(promptText);
264675
+ const streamConverter = new PiAISDKStreamConverter({
264676
+ sessionId: session.sessionId,
264677
+ model,
264678
+ redactText: (value2) => {
264679
+ if (options2.env && Object.keys(options2.env).length > 0) {
264680
+ return redactSecrets(value2, options2.env);
264404
264681
  }
264405
- }
264406
- } catch (_e2) {
264407
- }
264408
- const promptPromise = session.prompt(promptText, images ? { images } : void 0);
264409
- const messageId = `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`;
264410
- let hasStarted = false;
264411
- let hasFinished = false;
264412
- const imageToolUsage = { input_tokens: 0, output_tokens: 0 };
264413
- const newTextPartId = () => `text_${Date.now()}_${Math.random().toString(36).slice(2)}_${Math.random().toString(36).slice(2)}`;
264414
- let activeTextPartId = null;
264415
- let textStreamOpen = false;
264416
- const endTextStreamIfOpen = function* () {
264417
- if (textStreamOpen && activeTextPartId != null) {
264418
- yield `data: ${JSON.stringify({ type: "text-end", id: activeTextPartId })}
264419
-
264420
- `;
264421
- textStreamOpen = false;
264422
- activeTextPartId = null;
264423
- }
264424
- };
264425
- const beginTextStream = function* () {
264426
- activeTextPartId = newTextPartId();
264427
- yield `data: ${JSON.stringify({ type: "text-start", id: activeTextPartId })}
264428
-
264429
- `;
264430
- textStreamOpen = true;
264431
- };
264432
- const ensureStartEvent = async function* () {
264433
- if (!hasStarted) {
264434
- yield `data: ${JSON.stringify({ type: "start", messageId })}
264435
-
264436
- `;
264437
- yield `data: ${JSON.stringify({
264438
- type: "message-metadata",
264439
- messageMetadata: { sessionId: session.sessionId }
264440
- })}
264441
-
264442
- `;
264443
- hasStarted = true;
264444
- }
264445
- };
264446
- const finishSuccess = async function* (usage) {
264447
- yield* endTextStreamIfOpen();
264448
- const finishPayload = { type: "finish", finishReason: "stop" };
264449
- const hasImageUsage = imageToolUsage.input_tokens > 0 || imageToolUsage.output_tokens > 0;
264450
- if (usage != null || hasImageUsage) {
264451
- const base = usage != null ? usageToMessageMetadata(usage) : {};
264452
- finishPayload.messageMetadata = {
264453
- usage: {
264454
- ...base,
264455
- input_tokens: (base.input_tokens ?? 0) + imageToolUsage.input_tokens,
264456
- output_tokens: (base.output_tokens ?? 0) + imageToolUsage.output_tokens
264457
- }
264458
- };
264459
- }
264460
- yield `data: ${JSON.stringify(finishPayload)}
264461
-
264462
- `;
264463
- yield "data: [DONE]\n\n";
264464
- hasFinished = true;
264465
- };
264466
- const finishError = async function* (errorText) {
264467
- for (const chunk of emitStreamError(errorText)) {
264468
- yield chunk;
264469
- }
264470
- hasFinished = true;
264471
- };
264682
+ return value2;
264683
+ },
264684
+ normalizeToolOutput: extractToolResultText,
264685
+ getUsageFromAgentEndMessages,
264686
+ getErrorFromAgentEndMessages
264687
+ });
264472
264688
  while (!isComplete || eventQueue.length > 0) {
264473
264689
  while (eventQueue.length > 0) {
264474
264690
  const event = eventQueue.shift();
264475
264691
  traceRawMessage(cwd, event, false, options2.env);
264476
- yield* ensureStartEvent();
264477
- if (event.type === "message_start") {
264478
- const msg = event.message;
264479
- if (msg?.role === "assistant") {
264480
- yield* endTextStreamIfOpen();
264481
- }
264482
- } else if (event.type === "message_update") {
264483
- const sub = event.assistantMessageEvent;
264484
- if (sub.type === "text_start") {
264485
- yield* endTextStreamIfOpen();
264486
- yield* beginTextStream();
264487
- } else if (sub.type === "text_delta") {
264488
- let delta = sub.delta;
264489
- if (delta) {
264490
- if (options2.env && Object.keys(options2.env).length > 0) {
264491
- delta = redactSecrets(delta, options2.env);
264492
- }
264493
- if (!textStreamOpen) {
264494
- yield* beginTextStream();
264495
- }
264496
- yield `data: ${JSON.stringify({
264497
- type: "text-delta",
264498
- id: activeTextPartId,
264499
- delta
264500
- })}
264501
-
264502
- `;
264503
- }
264504
- } else if (sub.type === "toolcall_start") {
264505
- yield* endTextStreamIfOpen();
264506
- }
264507
- } else if (event.type === "tool_execution_start") {
264508
- yield* endTextStreamIfOpen();
264509
- yield `data: ${JSON.stringify({ type: "tool-input-start", toolCallId: event.toolCallId, toolName: event.toolName, dynamic: true, providerExecuted: true })}
264510
-
264511
- `;
264512
- yield `data: ${JSON.stringify({ type: "tool-input-available", toolCallId: event.toolCallId, toolName: event.toolName, input: event.args, dynamic: true, providerExecuted: true })}
264513
-
264514
- `;
264515
- } else if (event.type === "tool_execution_end") {
264516
- let output = extractToolResultText(event.result);
264517
- if (options2.env && Object.keys(options2.env).length > 0) {
264518
- output = redactSecrets(output, options2.env);
264519
- }
264520
- if ((event.toolName === "generate_image" || event.toolName === "edit_image") && event.result !== null && typeof event.result === "object") {
264521
- const details = event.result.details;
264522
- const u = details?.response?.usage;
264523
- if (u) {
264524
- imageToolUsage.input_tokens += u.input_tokens ?? 0;
264525
- imageToolUsage.output_tokens += u.output_tokens ?? 0;
264526
- }
264527
- }
264528
- yield `data: ${JSON.stringify({ type: "tool-output-available", toolCallId: event.toolCallId, output, isError: event.isError, dynamic: true, providerExecuted: true })}
264529
-
264530
- `;
264531
- } else if (event.type === "agent_end") {
264532
- if (aborted) {
264533
- yield* finishError("Run aborted by signal.");
264534
- } else {
264535
- const errorMsg = getErrorFromAgentEndMessages(event.messages);
264536
- if (errorMsg) {
264537
- yield* finishError(errorMsg);
264538
- } else {
264539
- const usage = getUsageFromAgentEndMessages(event.messages);
264540
- yield* finishSuccess(usage);
264541
- }
264542
- }
264692
+ const chunks = streamConverter.handleEvent(event, aborted);
264693
+ for (const chunk of chunks) {
264694
+ yield chunk;
264543
264695
  }
264544
264696
  }
264545
- if (aborted && !hasFinished) {
264546
- yield* ensureStartEvent();
264547
- yield* finishError("Run aborted by signal.");
264697
+ if (aborted && !streamConverter.finished) {
264698
+ for (const chunk of streamConverter.forceError("Run aborted by signal.")) {
264699
+ yield chunk;
264700
+ }
264548
264701
  break;
264549
264702
  }
264550
264703
  if (!isComplete && eventQueue.length === 0) {
@@ -264553,22 +264706,24 @@ function createPiRunner(options2 = {}) {
264553
264706
  });
264554
264707
  }
264555
264708
  }
264556
- if (hasFinished) {
264709
+ if (streamConverter.finished) {
264557
264710
  return;
264558
264711
  }
264559
264712
  try {
264560
264713
  await promptPromise;
264561
264714
  } catch (error) {
264562
- if (!hasFinished) {
264563
- yield* ensureStartEvent();
264715
+ if (!streamConverter.finished) {
264564
264716
  const message = error instanceof Error ? error.message : "Pi agent run failed.";
264565
- yield* finishError(message);
264717
+ for (const chunk of streamConverter.forceError(message)) {
264718
+ yield chunk;
264719
+ }
264566
264720
  }
264567
264721
  return;
264568
264722
  }
264569
- if (!hasFinished && session.agent.state.error) {
264570
- yield* ensureStartEvent();
264571
- yield* finishError(session.agent.state.error);
264723
+ if (!streamConverter.finished && session.agent.state.error) {
264724
+ for (const chunk of streamConverter.forceError(session.agent.state.error)) {
264725
+ yield chunk;
264726
+ }
264572
264727
  }
264573
264728
  } finally {
264574
264729
  if (abortSignal) {
@@ -264588,11 +264743,11 @@ function createPiRunner(options2 = {}) {
264588
264743
 
264589
264744
  // ../../packages/runner-harness/dist/session.js
264590
264745
  import { existsSync as existsSync29, mkdirSync as mkdirSync11, readFileSync as readFileSync23, writeFileSync as writeFileSync14 } from "node:fs";
264591
- import { join as join36 } from "node:path";
264746
+ import { join as join37 } from "node:path";
264592
264747
  var DIR = ".bunny-agent";
264593
264748
  var FILE = "session-id";
264594
264749
  function sessionPath(cwd) {
264595
- return join36(cwd, DIR, FILE);
264750
+ return join37(cwd, DIR, FILE);
264596
264751
  }
264597
264752
  function readSessionId(cwd) {
264598
264753
  try {
@@ -264606,28 +264761,28 @@ function readSessionId(cwd) {
264606
264761
  }
264607
264762
  function writeSessionId(cwd, id) {
264608
264763
  try {
264609
- mkdirSync11(join36(cwd, DIR), { recursive: true });
264764
+ mkdirSync11(join37(cwd, DIR), { recursive: true });
264610
264765
  writeFileSync14(sessionPath(cwd), id, "utf8");
264611
264766
  } catch {
264612
264767
  }
264613
264768
  }
264614
264769
 
264615
264770
  // ../../packages/runner-harness/dist/skills.js
264616
- import { existsSync as existsSync30, readdirSync as readdirSync12, statSync as statSync13 } from "node:fs";
264771
+ import { existsSync as existsSync30, readdirSync as readdirSync13, statSync as statSync14 } from "node:fs";
264617
264772
  import { homedir as homedir14 } from "node:os";
264618
- import { join as join37 } from "node:path";
264773
+ import { join as join38 } from "node:path";
264619
264774
  function discoverSkillPaths(cwd) {
264620
264775
  const paths = [];
264621
264776
  for (const base of [
264622
- join37(cwd, "skills"),
264623
- join37(homedir14(), ".bunny-agent", "skills")
264777
+ join38(cwd, "skills"),
264778
+ join38(homedir14(), ".bunny-agent", "skills")
264624
264779
  ]) {
264625
264780
  if (!existsSync30(base))
264626
264781
  continue;
264627
264782
  try {
264628
- for (const entry of readdirSync12(base)) {
264629
- const full = join37(base, entry);
264630
- if (statSync13(full).isDirectory() && existsSync30(join37(full, "SKILL.md"))) {
264783
+ for (const entry of readdirSync13(base)) {
264784
+ const full = join38(base, entry);
264785
+ if (statSync14(full).isDirectory() && existsSync30(join38(full, "SKILL.md"))) {
264631
264786
  paths.push(full);
264632
264787
  }
264633
264788
  }