@bunny-agent/daemon 0.9.29-beta.5 → 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/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"],
@@ -263528,7 +263533,7 @@ function buildImageGenerateTool(cwd, imageModelId, baseUrl, apiKey) {
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, "_"));
@@ -263566,6 +263571,7 @@ function buildImageGenerateTool(cwd, imageModelId, baseUrl, apiKey) {
263566
263571
  ],
263567
263572
  details: {
263568
263573
  filePath: savedPath,
263574
+ ...json.usage != null ? { usage: { raw: { [imageModelId]: json.usage } } } : {},
263569
263575
  response: json
263570
263576
  }
263571
263577
  };
@@ -263753,6 +263759,7 @@ function buildImageEditTool(cwd, imageModelId, baseUrl, apiKey) {
263753
263759
  ],
263754
263760
  details: {
263755
263761
  filePath: savedPath,
263762
+ ...json.usage != null ? { usage: { raw: { [imageModelId]: json.usage } } } : {},
263756
263763
  response: json
263757
263764
  }
263758
263765
  };
@@ -263769,6 +263776,309 @@ function buildImageEditTool(cwd, imageModelId, baseUrl, apiKey) {
263769
263776
  };
263770
263777
  }
263771
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
+
263772
264082
  // ../../packages/runner-pi/dist/web-tools.js
263773
264083
  var braveProvider = {
263774
264084
  id: "brave",
@@ -263810,7 +264120,7 @@ ${body}`);
263810
264120
  });
263811
264121
  }
263812
264122
  }
263813
- return results;
264123
+ return { results };
263814
264124
  }
263815
264125
  };
263816
264126
  var tavilyProvider = {
@@ -263845,7 +264155,7 @@ ${body}`);
263845
264155
  });
263846
264156
  }
263847
264157
  }
263848
- return results;
264158
+ return { results };
263849
264159
  }
263850
264160
  };
263851
264161
  var AUTO_DETECT_ORDER = [braveProvider, tavilyProvider];
@@ -263992,7 +264302,7 @@ function buildWebSearchTool(env2) {
263992
264302
  let lastError;
263993
264303
  for (const { provider, apiKey } of providers) {
263994
264304
  try {
263995
- const results = await provider.search({
264305
+ const { results } = await provider.search({
263996
264306
  apiKey,
263997
264307
  query,
263998
264308
  count,
@@ -264000,11 +264310,21 @@ function buildWebSearchTool(env2) {
264000
264310
  freshness,
264001
264311
  signal
264002
264312
  });
264313
+ let fetchedPages = 0;
264003
264314
  if (shouldFetchContent) {
264004
264315
  for (const r2 of results) {
264005
264316
  r2.content = await fetchPageContent(r2.link, signal);
264317
+ fetchedPages += 1;
264006
264318
  }
264007
264319
  }
264320
+ const usage = {
264321
+ raw: {
264322
+ [provider.id]: {
264323
+ requests: 1,
264324
+ fetchedPages
264325
+ }
264326
+ }
264327
+ };
264008
264328
  return {
264009
264329
  content: [
264010
264330
  {
@@ -264012,7 +264332,9 @@ function buildWebSearchTool(env2) {
264012
264332
  text: formatSearchResults(results, provider.label)
264013
264333
  }
264014
264334
  ],
264015
- details: void 0
264335
+ details: {
264336
+ usage
264337
+ }
264016
264338
  };
264017
264339
  } catch (e2) {
264018
264340
  lastError = e2;
@@ -264195,52 +264517,6 @@ function applyModelOverrides(model, provider, optionsEnv) {
264195
264517
  model.baseUrl = anthropicBaseUrl;
264196
264518
  }
264197
264519
  }
264198
- function emitStreamError(errorText) {
264199
- return [
264200
- `data: ${JSON.stringify({ type: "error", errorText })}
264201
-
264202
- `,
264203
- `data: ${JSON.stringify({ type: "finish", finishReason: "error" })}
264204
-
264205
- `,
264206
- "data: [DONE]\n\n"
264207
- ];
264208
- }
264209
- function extractToolResultText(result) {
264210
- if (result !== null && typeof result === "object") {
264211
- const r2 = result;
264212
- if (Array.isArray(r2.content) && r2.content.length > 0) {
264213
- const text = r2.content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n");
264214
- if (text.length > 0) {
264215
- return text;
264216
- }
264217
- }
264218
- }
264219
- if (typeof result === "string")
264220
- return result;
264221
- try {
264222
- return JSON.stringify(result);
264223
- } catch {
264224
- return String(result);
264225
- }
264226
- }
264227
- function usageToMessageMetadata(usage) {
264228
- return {
264229
- input_tokens: usage.input,
264230
- output_tokens: usage.output,
264231
- cache_read_input_tokens: usage.cacheRead,
264232
- cache_creation_input_tokens: usage.cacheWrite
264233
- };
264234
- }
264235
- function getUsageFromAgentEndMessages(messages) {
264236
- for (let i2 = messages.length - 1; i2 >= 0; i2--) {
264237
- const m2 = messages[i2];
264238
- if (m2.role === "assistant" && m2.usage != null) {
264239
- return m2.usage;
264240
- }
264241
- }
264242
- return void 0;
264243
- }
264244
264520
  function getErrorFromAgentEndMessages(messages) {
264245
264521
  for (let i2 = messages.length - 1; i2 >= 0; i2--) {
264246
264522
  const m2 = messages[i2];
@@ -264256,7 +264532,7 @@ function traceRawMessage(debugCwd, data, reset = false, optionsEnv) {
264256
264532
  if (!enabled)
264257
264533
  return;
264258
264534
  try {
264259
- const file = join35(debugCwd, "pi-message-stream-debug.json");
264535
+ const file = join36(debugCwd, "pi-message-stream-debug.json");
264260
264536
  if (reset && existsSync28(file))
264261
264537
  unlinkSync6(file);
264262
264538
  const type = data !== null && typeof data === "object" ? data.type : void 0;
@@ -264325,9 +264601,22 @@ function createPiRunner(options2 = {}) {
264325
264601
  if (resume.includes("/")) {
264326
264602
  return SessionManager.open(resume);
264327
264603
  }
264328
- const sessions = await SessionManager.list(cwd);
264329
- const found = sessions.find((s2) => s2.id === resume);
264330
- 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);
264331
264620
  }
264332
264621
  return SessionManager.create(cwd);
264333
264622
  })();
@@ -264385,165 +264674,34 @@ function createPiRunner(options2 = {}) {
264385
264674
  }
264386
264675
  try {
264387
264676
  traceRawMessage(cwd, null, true, options2.env);
264388
- let promptText = userInput;
264389
- let images;
264390
- try {
264391
- if (userInput.startsWith("[") && userInput.endsWith("]")) {
264392
- const parsed = JSON.parse(userInput);
264393
- if (Array.isArray(parsed)) {
264394
- promptText = parsed.filter((p) => p.type === "text").map((p) => p.text).join("\n");
264395
- const imageParts = parsed.filter((p) => p.type === "image");
264396
- if (imageParts.length > 0) {
264397
- images = imageParts.map((p) => ({
264398
- type: "image",
264399
- data: p.data,
264400
- mimeType: p.mimeType
264401
- }));
264402
- }
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);
264403
264685
  }
264404
- }
264405
- } catch (_e2) {
264406
- }
264407
- const promptPromise = session.prompt(promptText, images ? { images } : void 0);
264408
- const messageId = `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`;
264409
- let hasStarted = false;
264410
- let hasFinished = false;
264411
- const imageToolUsage = { input_tokens: 0, output_tokens: 0 };
264412
- const newTextPartId = () => `text_${Date.now()}_${Math.random().toString(36).slice(2)}_${Math.random().toString(36).slice(2)}`;
264413
- let activeTextPartId = null;
264414
- let textStreamOpen = false;
264415
- const endTextStreamIfOpen = function* () {
264416
- if (textStreamOpen && activeTextPartId != null) {
264417
- yield `data: ${JSON.stringify({ type: "text-end", id: activeTextPartId })}
264418
-
264419
- `;
264420
- textStreamOpen = false;
264421
- activeTextPartId = null;
264422
- }
264423
- };
264424
- const beginTextStream = function* () {
264425
- activeTextPartId = newTextPartId();
264426
- yield `data: ${JSON.stringify({ type: "text-start", id: activeTextPartId })}
264427
-
264428
- `;
264429
- textStreamOpen = true;
264430
- };
264431
- const ensureStartEvent = async function* () {
264432
- if (!hasStarted) {
264433
- yield `data: ${JSON.stringify({ type: "start", messageId })}
264434
-
264435
- `;
264436
- yield `data: ${JSON.stringify({
264437
- type: "message-metadata",
264438
- messageMetadata: { sessionId: session.sessionId }
264439
- })}
264440
-
264441
- `;
264442
- hasStarted = true;
264443
- }
264444
- };
264445
- const finishSuccess = async function* (usage) {
264446
- yield* endTextStreamIfOpen();
264447
- const finishPayload = { type: "finish", finishReason: "stop" };
264448
- const hasImageUsage = imageToolUsage.input_tokens > 0 || imageToolUsage.output_tokens > 0;
264449
- if (usage != null || hasImageUsage) {
264450
- const base = usage != null ? usageToMessageMetadata(usage) : {};
264451
- finishPayload.messageMetadata = {
264452
- usage: {
264453
- ...base,
264454
- input_tokens: (base.input_tokens ?? 0) + imageToolUsage.input_tokens,
264455
- output_tokens: (base.output_tokens ?? 0) + imageToolUsage.output_tokens
264456
- }
264457
- };
264458
- }
264459
- yield `data: ${JSON.stringify(finishPayload)}
264460
-
264461
- `;
264462
- yield "data: [DONE]\n\n";
264463
- hasFinished = true;
264464
- };
264465
- const finishError = async function* (errorText) {
264466
- for (const chunk of emitStreamError(errorText)) {
264467
- yield chunk;
264468
- }
264469
- hasFinished = true;
264470
- };
264686
+ return value2;
264687
+ },
264688
+ normalizeToolOutput: extractToolResultText,
264689
+ getUsageFromAgentEndMessages,
264690
+ getErrorFromAgentEndMessages
264691
+ });
264471
264692
  while (!isComplete || eventQueue.length > 0) {
264472
264693
  while (eventQueue.length > 0) {
264473
264694
  const event = eventQueue.shift();
264474
264695
  traceRawMessage(cwd, event, false, options2.env);
264475
- yield* ensureStartEvent();
264476
- if (event.type === "message_start") {
264477
- const msg = event.message;
264478
- if (msg?.role === "assistant") {
264479
- yield* endTextStreamIfOpen();
264480
- }
264481
- } else if (event.type === "message_update") {
264482
- const sub = event.assistantMessageEvent;
264483
- if (sub.type === "text_start") {
264484
- yield* endTextStreamIfOpen();
264485
- yield* beginTextStream();
264486
- } else if (sub.type === "text_delta") {
264487
- let delta = sub.delta;
264488
- if (delta) {
264489
- if (options2.env && Object.keys(options2.env).length > 0) {
264490
- delta = redactSecrets(delta, options2.env);
264491
- }
264492
- if (!textStreamOpen) {
264493
- yield* beginTextStream();
264494
- }
264495
- yield `data: ${JSON.stringify({
264496
- type: "text-delta",
264497
- id: activeTextPartId,
264498
- delta
264499
- })}
264500
-
264501
- `;
264502
- }
264503
- } else if (sub.type === "toolcall_start") {
264504
- yield* endTextStreamIfOpen();
264505
- }
264506
- } else if (event.type === "tool_execution_start") {
264507
- yield* endTextStreamIfOpen();
264508
- yield `data: ${JSON.stringify({ type: "tool-input-start", toolCallId: event.toolCallId, toolName: event.toolName, dynamic: true, providerExecuted: true })}
264509
-
264510
- `;
264511
- yield `data: ${JSON.stringify({ type: "tool-input-available", toolCallId: event.toolCallId, toolName: event.toolName, input: event.args, dynamic: true, providerExecuted: true })}
264512
-
264513
- `;
264514
- } else if (event.type === "tool_execution_end") {
264515
- let output = extractToolResultText(event.result);
264516
- if (options2.env && Object.keys(options2.env).length > 0) {
264517
- output = redactSecrets(output, options2.env);
264518
- }
264519
- if ((event.toolName === "generate_image" || event.toolName === "edit_image") && event.result !== null && typeof event.result === "object") {
264520
- const details = event.result.details;
264521
- const u = details?.response?.usage;
264522
- if (u) {
264523
- imageToolUsage.input_tokens += u.input_tokens ?? 0;
264524
- imageToolUsage.output_tokens += u.output_tokens ?? 0;
264525
- }
264526
- }
264527
- yield `data: ${JSON.stringify({ type: "tool-output-available", toolCallId: event.toolCallId, output, isError: event.isError, dynamic: true, providerExecuted: true })}
264528
-
264529
- `;
264530
- } else if (event.type === "agent_end") {
264531
- if (aborted) {
264532
- yield* finishError("Run aborted by signal.");
264533
- } else {
264534
- const errorMsg = getErrorFromAgentEndMessages(event.messages);
264535
- if (errorMsg) {
264536
- yield* finishError(errorMsg);
264537
- } else {
264538
- const usage = getUsageFromAgentEndMessages(event.messages);
264539
- yield* finishSuccess(usage);
264540
- }
264541
- }
264696
+ const chunks = streamConverter.handleEvent(event, aborted);
264697
+ for (const chunk of chunks) {
264698
+ yield chunk;
264542
264699
  }
264543
264700
  }
264544
- if (aborted && !hasFinished) {
264545
- yield* ensureStartEvent();
264546
- 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
+ }
264547
264705
  break;
264548
264706
  }
264549
264707
  if (!isComplete && eventQueue.length === 0) {
@@ -264552,22 +264710,24 @@ function createPiRunner(options2 = {}) {
264552
264710
  });
264553
264711
  }
264554
264712
  }
264555
- if (hasFinished) {
264713
+ if (streamConverter.finished) {
264556
264714
  return;
264557
264715
  }
264558
264716
  try {
264559
264717
  await promptPromise;
264560
264718
  } catch (error) {
264561
- if (!hasFinished) {
264562
- yield* ensureStartEvent();
264719
+ if (!streamConverter.finished) {
264563
264720
  const message = error instanceof Error ? error.message : "Pi agent run failed.";
264564
- yield* finishError(message);
264721
+ for (const chunk of streamConverter.forceError(message)) {
264722
+ yield chunk;
264723
+ }
264565
264724
  }
264566
264725
  return;
264567
264726
  }
264568
- if (!hasFinished && session.agent.state.error) {
264569
- yield* ensureStartEvent();
264570
- 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
+ }
264571
264731
  }
264572
264732
  } finally {
264573
264733
  if (abortSignal) {
@@ -264587,11 +264747,11 @@ function createPiRunner(options2 = {}) {
264587
264747
 
264588
264748
  // ../../packages/runner-harness/dist/session.js
264589
264749
  import { existsSync as existsSync29, mkdirSync as mkdirSync11, readFileSync as readFileSync23, writeFileSync as writeFileSync14 } from "node:fs";
264590
- import { join as join36 } from "node:path";
264750
+ import { join as join37 } from "node:path";
264591
264751
  var DIR = ".bunny-agent";
264592
264752
  var FILE = "session-id";
264593
264753
  function sessionPath(cwd) {
264594
- return join36(cwd, DIR, FILE);
264754
+ return join37(cwd, DIR, FILE);
264595
264755
  }
264596
264756
  function readSessionId(cwd) {
264597
264757
  try {
@@ -264605,28 +264765,28 @@ function readSessionId(cwd) {
264605
264765
  }
264606
264766
  function writeSessionId(cwd, id) {
264607
264767
  try {
264608
- mkdirSync11(join36(cwd, DIR), { recursive: true });
264768
+ mkdirSync11(join37(cwd, DIR), { recursive: true });
264609
264769
  writeFileSync14(sessionPath(cwd), id, "utf8");
264610
264770
  } catch {
264611
264771
  }
264612
264772
  }
264613
264773
 
264614
264774
  // ../../packages/runner-harness/dist/skills.js
264615
- 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";
264616
264776
  import { homedir as homedir14 } from "node:os";
264617
- import { join as join37 } from "node:path";
264777
+ import { join as join38 } from "node:path";
264618
264778
  function discoverSkillPaths(cwd) {
264619
264779
  const paths = [];
264620
264780
  for (const base of [
264621
- join37(cwd, "skills"),
264622
- join37(homedir14(), ".bunny-agent", "skills")
264781
+ join38(cwd, "skills"),
264782
+ join38(homedir14(), ".bunny-agent", "skills")
264623
264783
  ]) {
264624
264784
  if (!existsSync30(base))
264625
264785
  continue;
264626
264786
  try {
264627
- for (const entry of readdirSync12(base)) {
264628
- const full = join37(base, entry);
264629
- 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"))) {
264630
264790
  paths.push(full);
264631
264791
  }
264632
264792
  }