@popcraft/cli 0.41.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/popcraft.mjs +1725 -852
  2. package/package.json +2 -2
package/dist/popcraft.mjs CHANGED
@@ -1196,7 +1196,7 @@ function operations(spec = openapi) {
1196
1196
  }
1197
1197
  async function call(target2, method, path, opts = {}) {
1198
1198
  const qs = new URLSearchParams(opts.query ?? {}).toString();
1199
- const headers = { "user-agent": `popcraft-cli/${"0.41.0"}`, ...opts.headers };
1199
+ const headers = { "user-agent": `popcraft-cli/${"0.42.0"}`, ...opts.headers };
1200
1200
  if (target2.token) headers.authorization = `Bearer ${target2.token}`;
1201
1201
  if (opts.contentType) headers["content-type"] = opts.contentType;
1202
1202
  try {
@@ -1532,7 +1532,8 @@ __export(registry_exports, {
1532
1532
  isNeverReachable: () => isNeverReachable,
1533
1533
  listCommands: () => listCommands,
1534
1534
  listCommandsForSurface: () => listCommandsForSurface,
1535
- registerCommand: () => registerCommand
1535
+ registerCommand: () => registerCommand,
1536
+ unregisterCommand: () => unregisterCommand
1536
1537
  });
1537
1538
  function unindex(existing) {
1538
1539
  if (existing.expose.agent) byAgentName.delete(existing.expose.agent.name);
@@ -1562,6 +1563,14 @@ function registerCommand(...commands2) {
1562
1563
  if (method) byPluginMethod.set(method, command);
1563
1564
  }
1564
1565
  }
1566
+ function unregisterCommand(...ids2) {
1567
+ for (const id3 of ids2) {
1568
+ const existing = byId.get(id3);
1569
+ if (!existing) continue;
1570
+ unindex(existing);
1571
+ byId.delete(id3);
1572
+ }
1573
+ }
1565
1574
  function getCommand(id3) {
1566
1575
  return byId.get(id3);
1567
1576
  }
@@ -4770,15 +4779,15 @@ function formatCounter(c2, v) {
4770
4779
  const fixed = (Number.isFinite(v) ? steppedCounterValue(c2, v) : 0).toFixed(decimals);
4771
4780
  const negative = fixed.startsWith("-") && /[1-9]/.test(fixed);
4772
4781
  const [int3, frac2] = fixed.replace("-", "").split(".");
4773
- let grouped2 = int3;
4782
+ let grouped3 = int3;
4774
4783
  if (sep2) {
4775
- grouped2 = "";
4784
+ grouped3 = "";
4776
4785
  for (let i2 = 0; i2 < int3.length; i2++) {
4777
- if (i2 && (int3.length - i2) % 3 === 0) grouped2 += sep2;
4778
- grouped2 += int3[i2];
4786
+ if (i2 && (int3.length - i2) % 3 === 0) grouped3 += sep2;
4787
+ grouped3 += int3[i2];
4779
4788
  }
4780
4789
  }
4781
- return `${c2.prefix ?? ""}${negative ? "-" : ""}${grouped2}${frac2 ? `.${frac2}` : ""}${c2.suffix ?? ""}`;
4790
+ return `${c2.prefix ?? ""}${negative ? "-" : ""}${grouped3}${frac2 ? `.${frac2}` : ""}${c2.suffix ?? ""}`;
4782
4791
  }
4783
4792
  function counterFromText(chars) {
4784
4793
  const m = /^(\D*?)(-?\d[\d,]*(?:\.\d+)?)(\D*)$/.exec(chars.trim());
@@ -11362,9 +11371,9 @@ function partPattern(schema) {
11362
11371
  return own2;
11363
11372
  }
11364
11373
  if (def.options) {
11365
- const sources2 = def.options.map(partPattern);
11366
- if (sources2.every(Boolean))
11367
- return `^(${sources2.map((s) => cleanRegex(s)).join("|")})$`;
11374
+ const sources3 = def.options.map(partPattern);
11375
+ if (sources3.every(Boolean))
11376
+ return `^(${sources3.map((s) => cleanRegex(s)).join("|")})$`;
11368
11377
  }
11369
11378
  return leafPattern(schema);
11370
11379
  }
@@ -24183,8 +24192,8 @@ var init_api2 = __esm({
24183
24192
  });
24184
24193
 
24185
24194
  // node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/to-json-schema.js
24186
- function assignProps(target2, ...sources2) {
24187
- for (const source3 of sources2) {
24195
+ function assignProps(target2, ...sources3) {
24196
+ for (const source3 of sources3) {
24188
24197
  for (const key5 of Reflect.ownKeys(source3)) {
24189
24198
  if (Object.prototype.propertyIsEnumerable.call(source3, key5)) {
24190
24199
  assignProp(target2, key5, source3[key5]);
@@ -34410,7 +34419,9 @@ var init_en2 = __esm({
34410
34419
  "mentionInput.addReaction": "Add reaction",
34411
34420
  "mentionInput.someone": "Someone",
34412
34421
  "mentionMenu.removeMention": "Remove mention",
34422
+ "messageParts.fromPlugin": "From the {plugin} plugin",
34413
34423
  "messageParts.plan": "Plan",
34424
+ "messageParts.pluginTool": "{plugin} \xB7 {tool}",
34414
34425
  "messageParts.renderedView": "Rendered view",
34415
34426
  "messageParts.thinking": "Thinking",
34416
34427
  "minimap.minimapTapOrDragTo": "Minimap \u2014 tap or drag to move the view, double-tap to fit the page",
@@ -35085,6 +35096,8 @@ var init_en2 = __esm({
35085
35096
  "pluginImport.noImporterIsInstalledFor": "No importer is installed for \u201C{name}\u201D",
35086
35097
  "pluginImport.openAFileToImport": "Open a file to import into",
35087
35098
  "pluginImport.producedNoLayers": "\u201C{name}\u201D produced no layers",
35099
+ "pluginOverlays.addAgentTools": "Give the AI agent {count, plural, one {# tool} other {# tools}} that run this plugin",
35100
+ "pluginOverlays.addsAgentTools": "Adds {count, plural, one {# agent tool} other {# agent tools}}",
35088
35101
  "pluginOverlays.addsExport": "Adds File \u203A Export \u203A {label}",
35089
35102
  "pluginOverlays.allowAndRun": "Allow and run",
35090
35103
  "pluginOverlays.allowTo": "Allow \u201C{name}\u201D to:",
@@ -94349,7 +94362,6 @@ function hasMessage(key5) {
94349
94362
  var current2, loading, listeners, formats, asts;
94350
94363
  var init_runtime = __esm({
94351
94364
  "lib/i18n/runtime.ts"() {
94352
- "use strict";
94353
94365
  init_intl_messageformat();
94354
94366
  init_icu_messageformat_parser();
94355
94367
  init_catalogs();
@@ -98852,10 +98864,10 @@ function interpolate(a, b, t3) {
98852
98864
  return out;
98853
98865
  }
98854
98866
  function staggeredProgress(s, i2, n) {
98855
- const delay = Math.max(0, Math.min(s.delay, n > 1 ? s.duration / n : s.delay));
98856
- const span3 = s.duration - delay * Math.max(0, n - 1);
98867
+ const delay3 = Math.max(0, Math.min(s.delay, n > 1 ? s.duration / n : s.delay));
98868
+ const span3 = s.duration - delay3 * Math.max(0, n - 1);
98857
98869
  if (span3 <= 0) return s.ease(s.raw >= 1 ? 1 : 0);
98858
- return s.ease(Math.min(1, Math.max(0, (s.raw * s.duration - i2 * delay) / span3)));
98870
+ return s.ease(Math.min(1, Math.max(0, (s.raw * s.duration - i2 * delay3) / span3)));
98859
98871
  }
98860
98872
  function sharedUnder(nodes, rootId) {
98861
98873
  const out = /* @__PURE__ */ new Map();
@@ -247849,6 +247861,7 @@ function resyncText(doc2, ids2) {
247849
247861
  var isVirtualId;
247850
247862
  var init_invariants2 = __esm({
247851
247863
  "lib/document/invariants.ts"() {
247864
+ "use strict";
247852
247865
  init_auto_layout();
247853
247866
  init_scene_graph();
247854
247867
  init_text_bounds();
@@ -252284,6 +252297,7 @@ function resizeWindow(doc2, target2, rect) {
252284
252297
  }
252285
252298
  var init_crop = __esm({
252286
252299
  "lib/editor/crop.ts"() {
252300
+ "use strict";
252287
252301
  init_dist_node();
252288
252302
  init_scene_graph();
252289
252303
  init_photo_frames();
@@ -256772,6 +256786,7 @@ function followPeers(peers) {
256772
256786
  var PALETTE, usePresence, awareness, CURSOR_SEND_MS, VIEWPORT_SEND_MS, cursorTimer, pendingCursor, sentCursor, EMOTE_MS, lastFollowCamera;
256773
256787
  var init_presence = __esm({
256774
256788
  "lib/collab/presence.ts"() {
256789
+ "use strict";
256775
256790
  init_esm();
256776
256791
  init_editor_store();
256777
256792
  init_status_announcements();
@@ -259061,9 +259076,9 @@ function applyPresetToDocument(doc2, ids2, presetId, opts = {}) {
259061
259076
  const places = opts.stagger && !liveParent ? staggerPlaces(nodes, targets, opts.stagger.order, opts.stagger.seed) : null;
259062
259077
  let out = { ...nodes };
259063
259078
  if (liveParent && opts.stagger) {
259064
- const { delay, order: order2 = "index", seed: seed2 } = opts.stagger;
259079
+ const { delay: delay3, order: order2 = "index", seed: seed2 } = opts.stagger;
259065
259080
  const parent = out[liveParent];
259066
- out[liveParent] = { ...parent, motion: { tracks: {}, ...parent.motion, stagger: { delay, order: order2 === "selection" ? { ids: [...targets] } : order2, ...order2 === "random" && seed2 !== void 0 ? { seed: seed2 } : {} } } };
259081
+ out[liveParent] = { ...parent, motion: { tracks: {}, ...parent.motion, stagger: { delay: delay3, order: order2 === "selection" ? { ids: [...targets] } : order2, ...order2 === "random" && seed2 !== void 0 ? { seed: seed2 } : {} } } };
259067
259082
  }
259068
259083
  for (const id3 of targets) {
259069
259084
  const frameId = hosts.get(id3);
@@ -260200,10 +260215,10 @@ function retargetPath(node2, parent, path) {
260200
260215
  return propertiesOf(node2, parent).find((p2) => patternOf(p2.path) === pattern)?.path ?? null;
260201
260216
  }
260202
260217
  function pasteKeys(nodes, frameId, clip, targets, at4) {
260203
- const sources2 = [];
260204
- for (const tr of clip.tracks) if (!sources2.includes(tr.source)) sources2.push(tr.source);
260218
+ const sources3 = [];
260219
+ for (const tr of clip.tracks) if (!sources3.includes(tr.source)) sources3.push(tr.source);
260205
260220
  const onto = targets.filter((id3) => nodes[id3]);
260206
- const plan2 = !onto.length ? sources2.filter((id3) => nodes[id3]).map((id3) => [id3, id3]) : sources2.length === 1 ? onto.map((id3) => [sources2[0], id3]) : sources2.slice(0, onto.length).map((s, i2) => [s, onto[i2]]);
260221
+ const plan2 = !onto.length ? sources3.filter((id3) => nodes[id3]).map((id3) => [id3, id3]) : sources3.length === 1 ? onto.map((id3) => [sources3[0], id3]) : sources3.slice(0, onto.length).map((s, i2) => [s, onto[i2]]);
260207
260222
  const result = { edits: [], keys: [] };
260208
260223
  for (const [source3, targetId] of plan2) {
260209
260224
  const rest = nodes[targetId];
@@ -260340,9 +260355,9 @@ function poseAt(doc2, target2, t3) {
260340
260355
  }
260341
260356
  function frameSchedule(stretches, fps, hold) {
260342
260357
  const out = [];
260343
- const delay = Math.round(1e3 / fps);
260358
+ const delay3 = Math.round(1e3 / fps);
260344
260359
  for (const [from2, to] of stretches) {
260345
- for (let i2 = 0; frameTime(i2, fps, from2) < to; i2++) out.push({ t: frameTime(i2, fps, from2), delay });
260360
+ for (let i2 = 0; frameTime(i2, fps, from2) < to; i2++) out.push({ t: frameTime(i2, fps, from2), delay: delay3 });
260346
260361
  out.push({ t: to, delay: hold });
260347
260362
  }
260348
260363
  return out;
@@ -269469,10 +269484,10 @@ var init_yjs = __esm({
269469
269484
  * @public
269470
269485
  */
269471
269486
  toDOM(_document = document, hooks = {}, binding) {
269472
- const hook = hooks[this.hookName];
269487
+ const hook2 = hooks[this.hookName];
269473
269488
  let dom;
269474
- if (hook !== void 0) {
269475
- dom = hook.createDom(this);
269489
+ if (hook2 !== void 0) {
269490
+ dom = hook2.createDom(this);
269476
269491
  } else {
269477
269492
  dom = document.createElement(this.hookName);
269478
269493
  }
@@ -272162,11 +272177,11 @@ var init_client = __esm({
272162
272177
  }
272163
272178
  scheduleReconnect(min2 = 0) {
272164
272179
  if (this.destroyed || this.reconnectTimer) return;
272165
- const delay = Math.max(min2, Math.min(3e4, 500 * 2 ** this.attempts++)) * (0.8 + Math.random() * 0.4);
272180
+ const delay3 = Math.max(min2, Math.min(3e4, 500 * 2 ** this.attempts++)) * (0.8 + Math.random() * 0.4);
272166
272181
  this.reconnectTimer = setTimeout(() => {
272167
272182
  this.reconnectTimer = null;
272168
272183
  void this.connect();
272169
- }, delay);
272184
+ }, delay3);
272170
272185
  }
272171
272186
  /**
272172
272187
  * Send media to the room now (MSG_MEDIA). Call it BEFORE the document change that references it: the socket keeps
@@ -273717,7 +273732,7 @@ var require_gifenc = __commonJS({
273717
273732
  const {
273718
273733
  transparent = false,
273719
273734
  transparentIndex = 0,
273720
- delay = 0,
273735
+ delay: delay3 = 0,
273721
273736
  palette: palette2 = null,
273722
273737
  repeat = 0,
273723
273738
  colorDepth = 8,
@@ -273745,7 +273760,7 @@ var require_gifenc = __commonJS({
273745
273760
  encodeNetscapeExt(stream, repeat);
273746
273761
  }
273747
273762
  }
273748
- const delayTime = Math.round(delay / 10);
273763
+ const delayTime = Math.round(delay3 / 10);
273749
273764
  encodeGraphicControlExt(stream, dispose, delayTime, transparent, transparentIndex);
273750
273765
  const useLocalColorTable = Boolean(palette2) && !first2;
273751
273766
  encodeImageDescriptor(stream, width, height, useLocalColorTable ? palette2 : null);
@@ -273758,7 +273773,7 @@ var require_gifenc = __commonJS({
273758
273773
  writeUTFBytes(stream, "GIF89a");
273759
273774
  }
273760
273775
  }
273761
- function encodeGraphicControlExt(stream, dispose, delay, transparent, transparentIndex) {
273776
+ function encodeGraphicControlExt(stream, dispose, delay3, transparent, transparentIndex) {
273762
273777
  stream.writeByte(33);
273763
273778
  stream.writeByte(249);
273764
273779
  stream.writeByte(4);
@@ -273780,7 +273795,7 @@ var require_gifenc = __commonJS({
273780
273795
  disp <<= 2;
273781
273796
  const userInput = 0;
273782
273797
  stream.writeByte(0 | disp | userInput | transp);
273783
- writeUInt16(stream, delay);
273798
+ writeUInt16(stream, delay3);
273784
273799
  stream.writeByte(transparentIndex || 0);
273785
273800
  stream.writeByte(0);
273786
273801
  }
@@ -273914,7 +273929,7 @@ function createGifEncoder(width, height, opts, shared) {
273914
273929
  return out;
273915
273930
  };
273916
273931
  return {
273917
- frame(rgba, delay) {
273932
+ frame(rgba, delay3) {
273918
273933
  let palette2 = shared;
273919
273934
  if (mode === "per-frame" || !palette2) {
273920
273935
  const c2 = new PaletteCounter();
@@ -273926,7 +273941,7 @@ function createGifEncoder(width, height, opts, shared) {
273926
273941
  if (incremental && pending8 && canvas) {
273927
273942
  const box2 = changedBox(canvas, idx, width);
273928
273943
  if (!box2) {
273929
- pending8.delay += delay;
273944
+ pending8.delay += delay3;
273930
273945
  return new Uint8Array(0);
273931
273946
  }
273932
273947
  if (solid5 && opaque) {
@@ -273939,13 +273954,13 @@ function createGifEncoder(width, height, opts, shared) {
273939
273954
  }
273940
273955
  }
273941
273956
  const out2 = flush(true);
273942
- pending8 = { idx: sub2, ...box2, delay, palette: palette2 };
273957
+ pending8 = { idx: sub2, ...box2, delay: delay3, palette: palette2 };
273943
273958
  canvas = idx;
273944
273959
  return out2;
273945
273960
  }
273946
273961
  }
273947
273962
  const out = flush(false);
273948
- pending8 = { idx, x: 0, y: 0, w: width, h: height, delay, palette: palette2 };
273963
+ pending8 = { idx, x: 0, y: 0, w: width, h: height, delay: delay3, palette: palette2 };
273949
273964
  canvas = incremental ? idx : null;
273950
273965
  opaque = solid5;
273951
273966
  return out;
@@ -305367,13 +305382,13 @@ var init_output = __esm({
305367
305382
  * prefer the `'target'` event for those cases.
305368
305383
  */
305369
305384
  get target() {
305370
- const errorMessage = "Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";
305385
+ const errorMessage3 = "Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";
305371
305386
  if (this._rootTargetPromise) {
305372
- throw new TypeError(errorMessage);
305387
+ throw new TypeError(errorMessage3);
305373
305388
  }
305374
305389
  const rootTargetResult = this._getRootTarget();
305375
305390
  if (isThenable(rootTargetResult)) {
305376
- throw new TypeError(errorMessage);
305391
+ throw new TypeError(errorMessage3);
305377
305392
  }
305378
305393
  return rootTargetResult;
305379
305394
  }
@@ -310337,11 +310352,11 @@ function usePageThumbnail(frame2, doc2) {
310337
310352
  if (prev && prev !== next2) URL.revokeObjectURL(prev);
310338
310353
  setUrl(next2);
310339
310354
  };
310340
- const delay = hit ? SETTLE_MS : 0;
310355
+ const delay3 = hit ? SETTLE_MS : 0;
310341
310356
  const timer = setTimeout(() => {
310342
310357
  if (typeof requestIdleCallback === "function") requestIdleCallback(() => void run4(), { timeout: 3e3 });
310343
310358
  else void run4();
310344
- }, delay);
310359
+ }, delay3);
310345
310360
  return () => {
310346
310361
  cancelled = true;
310347
310362
  clearTimeout(timer);
@@ -310807,7 +310822,7 @@ async function pushThumbnail(key5, docId) {
310807
310822
  await putThumbnail(key5, blob);
310808
310823
  uploadedThumbs.set(key5, at4);
310809
310824
  }
310810
- function schedulePush(delay = 3e3) {
310825
+ function schedulePush(delay3 = 3e3) {
310811
310826
  dirty = true;
310812
310827
  if (!activeLink || !canEdit(activeLink.role) || !cloudUser()) return;
310813
310828
  if (pushTimer) clearTimeout(pushTimer);
@@ -310816,7 +310831,7 @@ function schedulePush(delay = 3e3) {
310816
310831
  pushing = (pushing ?? Promise.resolve()).then(push).finally(() => {
310817
310832
  pushing = null;
310818
310833
  });
310819
- }, delay);
310834
+ }, delay3);
310820
310835
  }
310821
310836
  async function openCloudFile(key5, opts = {}) {
310822
310837
  const running4 = !opts.replaceLocal && openingFiles.get(key5);
@@ -311142,7 +311157,6 @@ function startCloudSync() {
311142
311157
  var status, readOnlyDoc, activeLink, statusListeners, notice, urlArmed, opening, syncStatus, canEdit, uploaded, MEDIA_UPLOAD_PARALLEL, pushTimer, pushing, dirty, pendingMedia, collab, collabSession, collabAnonymous, uploadedThumbs, thumbCheckedAt, THUMB_EVERY_MS, THUMB_MIN_GAP_MS, putThumbnail, openingFiles, mediaHealed, started2;
311143
311158
  var init_sync2 = __esm({
311144
311159
  "lib/client/cloud/sync.ts"() {
311145
- "use strict";
311146
311160
  init_paint_repair();
311147
311161
  init_migrate();
311148
311162
  init_view();
@@ -311349,6 +311363,7 @@ async function dispatchShaped(key5, options) {
311349
311363
  var onViolation;
311350
311364
  var init_dispatch = __esm({
311351
311365
  "lib/commands/dispatch.ts"() {
311366
+ "use strict";
311352
311367
  init_errors();
311353
311368
  init_registry();
311354
311369
  init_confirm();
@@ -312527,6 +312542,7 @@ function areaBounds(rings) {
312527
312542
  }
312528
312543
  var init_text_area = __esm({
312529
312544
  "lib/engine/text/text-area.ts"() {
312545
+ "use strict";
312530
312546
  }
312531
312547
  });
312532
312548
 
@@ -317316,7 +317332,6 @@ function videoPixelSize(resolution, aspect) {
317316
317332
  var VIDEO_ASPECTS, VIDEO_RESOLUTIONS, SEEDANCE_ASPECTS, range, VIDEO_MODELS, DEFAULT_VIDEO_MODEL, videoModel, VIDEO_LIMITS;
317317
317333
  var init_video_models = __esm({
317318
317334
  "lib/ai/video-models.ts"() {
317319
- "use strict";
317320
317335
  VIDEO_ASPECTS = ["16:9", "9:16", "1:1", "4:3", "3:4", "21:9"];
317321
317336
  VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"];
317322
317337
  SEEDANCE_ASPECTS = ["16:9", "9:16", "1:1", "4:3", "3:4", "21:9"];
@@ -317805,7 +317820,6 @@ function agentToolList() {
317805
317820
  var AGENT_CAPABILITIES, legacyCommandId, legacyTools, blobToDataUrl3, provided, legacyTool, legacyToolList;
317806
317821
  var init_agent = __esm({
317807
317822
  "lib/commands/agent.ts"() {
317808
- "use strict";
317809
317823
  init_types5();
317810
317824
  init_registry();
317811
317825
  init_errors();
@@ -327669,7 +327683,7 @@ var init_package = __esm({
327669
327683
  "packages/runtime/package.json"() {
327670
327684
  package_default = {
327671
327685
  name: "@popcraft/runtime",
327672
- version: "0.41.0",
327686
+ version: "0.42.0",
327673
327687
  description: "What code exported from PopCraft shares: the meaning of expressions (operators and functions) and, as it grows, the parts of a design's behaviour that are common code rather than generated React.",
327674
327688
  license: "MIT",
327675
327689
  homepage: "https://popcraft.app/docs/exporting/nextjs",
@@ -342187,7 +342201,7 @@ var require_trace_mapping_umd = __commonJS({
342187
342201
  return a[COLUMN] - b[COLUMN];
342188
342202
  }
342189
342203
  function buildBySources(decoded, memos) {
342190
- const sources2 = memos.map(() => []);
342204
+ const sources3 = memos.map(() => []);
342191
342205
  for (let i2 = 0; i2 < decoded.length; i2++) {
342192
342206
  const line = decoded[i2];
342193
342207
  for (let j = 0; j < line.length; j++) {
@@ -342196,19 +342210,19 @@ var require_trace_mapping_umd = __commonJS({
342196
342210
  const sourceIndex2 = seg[SOURCES_INDEX];
342197
342211
  const sourceLine = seg[SOURCE_LINE];
342198
342212
  const sourceColumn = seg[SOURCE_COLUMN];
342199
- const source3 = sources2[sourceIndex2];
342213
+ const source3 = sources3[sourceIndex2];
342200
342214
  const segs = source3[sourceLine] || (source3[sourceLine] = []);
342201
342215
  segs.push([sourceColumn, i2, seg[COLUMN]]);
342202
342216
  }
342203
342217
  }
342204
- for (let i2 = 0; i2 < sources2.length; i2++) {
342205
- const source3 = sources2[i2];
342218
+ for (let i2 = 0; i2 < sources3.length; i2++) {
342219
+ const source3 = sources3[i2];
342206
342220
  for (let j = 0; j < source3.length; j++) {
342207
342221
  const line = source3[j];
342208
342222
  if (line) line.sort(sortComparator);
342209
342223
  }
342210
342224
  }
342211
- return sources2;
342225
+ return sources3;
342212
342226
  }
342213
342227
  var found = false;
342214
342228
  function binarySearch(haystack, needle, low, high) {
@@ -342275,7 +342289,7 @@ var require_trace_mapping_umd = __commonJS({
342275
342289
  return new TraceMap(parsed2, mapUrl);
342276
342290
  }
342277
342291
  const mappings = [];
342278
- const sources2 = [];
342292
+ const sources3 = [];
342279
342293
  const sourcesContent = [];
342280
342294
  const names = [];
342281
342295
  const ignoreList = [];
@@ -342283,7 +342297,7 @@ var require_trace_mapping_umd = __commonJS({
342283
342297
  parsed2,
342284
342298
  mapUrl,
342285
342299
  mappings,
342286
- sources2,
342300
+ sources3,
342287
342301
  sourcesContent,
342288
342302
  names,
342289
342303
  ignoreList,
@@ -342296,14 +342310,14 @@ var require_trace_mapping_umd = __commonJS({
342296
342310
  version: 3,
342297
342311
  file: parsed2.file,
342298
342312
  names,
342299
- sources: sources2,
342313
+ sources: sources3,
342300
342314
  sourcesContent,
342301
342315
  mappings,
342302
342316
  ignoreList
342303
342317
  };
342304
342318
  return presortedDecodedMap(joined);
342305
342319
  };
342306
- function recurse(input2, mapUrl, mappings, sources2, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
342320
+ function recurse(input2, mapUrl, mappings, sources3, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
342307
342321
  const { sections } = input2;
342308
342322
  for (let i2 = 0; i2 < sections.length; i2++) {
342309
342323
  const { map: map2, offset } = sections[i2];
@@ -342322,7 +342336,7 @@ var require_trace_mapping_umd = __commonJS({
342322
342336
  map2,
342323
342337
  mapUrl,
342324
342338
  mappings,
342325
- sources2,
342339
+ sources3,
342326
342340
  sourcesContent,
342327
342341
  names,
342328
342342
  ignoreList,
@@ -342333,15 +342347,15 @@ var require_trace_mapping_umd = __commonJS({
342333
342347
  );
342334
342348
  }
342335
342349
  }
342336
- function addSection(input2, mapUrl, mappings, sources2, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
342350
+ function addSection(input2, mapUrl, mappings, sources3, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
342337
342351
  const parsed2 = parse7(input2);
342338
342352
  if ("sections" in parsed2) return recurse(...arguments);
342339
342353
  const map2 = new TraceMap(parsed2, mapUrl);
342340
- const sourcesOffset = sources2.length;
342354
+ const sourcesOffset = sources3.length;
342341
342355
  const namesOffset = names.length;
342342
342356
  const decoded = decodedMappings(map2);
342343
342357
  const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map2;
342344
- append(sources2, resolvedSources);
342358
+ append(sources3, resolvedSources);
342345
342359
  append(names, map2.names);
342346
342360
  if (contents) append(sourcesContent, contents);
342347
342361
  else for (let i2 = 0; i2 < resolvedSources.length; i2++) sourcesContent.push(null);
@@ -342385,16 +342399,16 @@ var require_trace_mapping_umd = __commonJS({
342385
342399
  const isString2 = typeof map2 === "string";
342386
342400
  if (!isString2 && map2._decodedMemo) return map2;
342387
342401
  const parsed2 = parse7(map2);
342388
- const { version: version7, file: file2, names, sourceRoot, sources: sources2, sourcesContent } = parsed2;
342402
+ const { version: version7, file: file2, names, sourceRoot, sources: sources3, sourcesContent } = parsed2;
342389
342403
  this.version = version7;
342390
342404
  this.file = file2;
342391
342405
  this.names = names || [];
342392
342406
  this.sourceRoot = sourceRoot;
342393
- this.sources = sources2;
342407
+ this.sources = sources3;
342394
342408
  this.sourcesContent = sourcesContent;
342395
342409
  this.ignoreList = parsed2.ignoreList || parsed2.x_google_ignoreList || void 0;
342396
342410
  const resolve7 = resolver(mapUrl, sourceRoot);
342397
- this.resolvedSources = sources2.map(resolve7);
342411
+ this.resolvedSources = sources3.map(resolve7);
342398
342412
  const { mappings } = parsed2;
342399
342413
  if (typeof mappings === "string") {
342400
342414
  this._encoded = mappings;
@@ -342501,8 +342515,8 @@ var require_trace_mapping_umd = __commonJS({
342501
342515
  }
342502
342516
  }
342503
342517
  function sourceIndex(map2, source3) {
342504
- const { sources: sources2, resolvedSources } = map2;
342505
- let index2 = sources2.indexOf(source3);
342518
+ const { sources: sources3, resolvedSources } = map2;
342519
+ let index2 = sources3.indexOf(source3);
342506
342520
  if (index2 === -1) index2 = resolvedSources.indexOf(source3);
342507
342521
  return index2;
342508
342522
  }
@@ -342574,11 +342588,11 @@ var require_trace_mapping_umd = __commonJS({
342574
342588
  line--;
342575
342589
  if (line < 0) throw new Error(LINE_GTR_ZERO);
342576
342590
  if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
342577
- const { sources: sources2, resolvedSources } = map2;
342578
- let sourceIndex2 = sources2.indexOf(source3);
342591
+ const { sources: sources3, resolvedSources } = map2;
342592
+ let sourceIndex2 = sources3.indexOf(source3);
342579
342593
  if (sourceIndex2 === -1) sourceIndex2 = resolvedSources.indexOf(source3);
342580
342594
  if (sourceIndex2 === -1) return all4 ? [] : GMapping(null, null);
342581
- const bySourceMemos = (_a4 = cast(map2))._bySourceMemos || (_a4._bySourceMemos = sources2.map(memoizedState));
342595
+ const bySourceMemos = (_a4 = cast(map2))._bySourceMemos || (_a4._bySourceMemos = sources3.map(memoizedState));
342582
342596
  const generated = (_b2 = cast(map2))._bySources || (_b2._bySources = buildBySources(decodedMappings(map2), bySourceMemos));
342583
342597
  const segments = generated[sourceIndex2][line];
342584
342598
  if (segments == null) return all4 ? [] : GMapping(null, null);
@@ -342758,21 +342772,21 @@ var require_gen_mapping_umd = __commonJS({
342758
342772
  };
342759
342773
  function setSourceContent(map2, source3, content) {
342760
342774
  const {
342761
- _sources: sources2,
342775
+ _sources: sources3,
342762
342776
  _sourcesContent: sourcesContent
342763
342777
  // _originalScopes: originalScopes,
342764
342778
  } = cast2(map2);
342765
- const index2 = put3(sources2, source3);
342779
+ const index2 = put3(sources3, source3);
342766
342780
  sourcesContent[index2] = content;
342767
342781
  }
342768
342782
  function setIgnore(map2, source3, ignore = true) {
342769
342783
  const {
342770
- _sources: sources2,
342784
+ _sources: sources3,
342771
342785
  _sourcesContent: sourcesContent,
342772
342786
  _ignoreList: ignoreList
342773
342787
  // _originalScopes: originalScopes,
342774
342788
  } = cast2(map2);
342775
- const index2 = put3(sources2, source3);
342789
+ const index2 = put3(sources3, source3);
342776
342790
  if (index2 === sourcesContent.length) sourcesContent[index2] = null;
342777
342791
  if (ignore) put3(ignoreList, index2);
342778
342792
  else remove(ignoreList, index2);
@@ -342780,7 +342794,7 @@ var require_gen_mapping_umd = __commonJS({
342780
342794
  function toDecodedMap(map2) {
342781
342795
  const {
342782
342796
  _mappings: mappings,
342783
- _sources: sources2,
342797
+ _sources: sources3,
342784
342798
  _sourcesContent: sourcesContent,
342785
342799
  _names: names,
342786
342800
  _ignoreList: ignoreList
@@ -342793,7 +342807,7 @@ var require_gen_mapping_umd = __commonJS({
342793
342807
  file: map2.file || void 0,
342794
342808
  names: names.array,
342795
342809
  sourceRoot: map2.sourceRoot || void 0,
342796
- sources: sources2.array,
342810
+ sources: sources3.array,
342797
342811
  sourcesContent,
342798
342812
  mappings,
342799
342813
  // originalScopes,
@@ -342821,7 +342835,7 @@ var require_gen_mapping_umd = __commonJS({
342821
342835
  }
342822
342836
  function allMappings(map2) {
342823
342837
  const out = [];
342824
- const { _mappings: mappings, _sources: sources2, _names: names } = cast2(map2);
342838
+ const { _mappings: mappings, _sources: sources3, _names: names } = cast2(map2);
342825
342839
  for (let i2 = 0; i2 < mappings.length; i2++) {
342826
342840
  const line = mappings[i2];
342827
342841
  for (let j = 0; j < line.length; j++) {
@@ -342831,7 +342845,7 @@ var require_gen_mapping_umd = __commonJS({
342831
342845
  let original = void 0;
342832
342846
  let name2 = void 0;
342833
342847
  if (seg.length !== 1) {
342834
- source3 = sources2.array[seg[SOURCES_INDEX]];
342848
+ source3 = sources3.array[seg[SOURCES_INDEX]];
342835
342849
  original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] };
342836
342850
  if (seg.length === 5) name2 = names.array[seg[NAMES_INDEX]];
342837
342851
  }
@@ -342843,7 +342857,7 @@ var require_gen_mapping_umd = __commonJS({
342843
342857
  function addSegmentInternal(skipable, map2, genLine, genColumn, source3, sourceLine, sourceColumn, name2, content) {
342844
342858
  const {
342845
342859
  _mappings: mappings,
342846
- _sources: sources2,
342860
+ _sources: sources3,
342847
342861
  _sourcesContent: sourcesContent,
342848
342862
  _names: names
342849
342863
  // _originalScopes: originalScopes,
@@ -342856,7 +342870,7 @@ var require_gen_mapping_umd = __commonJS({
342856
342870
  }
342857
342871
  assert4(sourceLine);
342858
342872
  assert4(sourceColumn);
342859
- const sourcesIndex = put3(sources2, source3);
342873
+ const sourcesIndex = put3(sources3, source3);
342860
342874
  const namesIndex = name2 ? put3(names, name2) : NO_NAME;
342861
342875
  if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null;
342862
342876
  if (skipable && skipSource(line, index2, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
@@ -352335,6 +352349,7 @@ function exportsOf(source3) {
352335
352349
  var CODE_LIMITS, packageOf;
352336
352350
  var init_source2 = __esm({
352337
352351
  "lib/code/source.ts"() {
352352
+ "use strict";
352338
352353
  CODE_LIMITS = { modules: 100, sourceLength: 2e5, packages: 12 };
352339
352354
  packageOf = (spec) => spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
352340
352355
  }
@@ -352377,6 +352392,7 @@ function compileModule(module2) {
352377
352392
  var import_sucrase, BUILT_IN, memo4;
352378
352393
  var init_compile2 = __esm({
352379
352394
  "lib/code/compile.ts"() {
352395
+ "use strict";
352380
352396
  import_sucrase = __toESM(require_dist2());
352381
352397
  init_source2();
352382
352398
  init_source2();
@@ -361417,6 +361433,7 @@ var init_delete_current_file = __esm({
361417
361433
  var storeOpsSeam;
361418
361434
  var init_seams = __esm({
361419
361435
  "lib/commands/seams.ts"() {
361436
+ "use strict";
361420
361437
  storeOpsSeam = (st) => ({
361421
361438
  booleanOperation: (op4) => st().booleanOperation(op4),
361422
361439
  flatten: () => st().flattenSelection(),
@@ -364521,607 +364538,1379 @@ var init_open_intent = __esm({
364521
364538
  }
364522
364539
  });
364523
364540
 
364524
- // node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/types.js
364525
- var init_types9 = __esm({
364526
- "node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/types.js"() {
364541
+ // node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/hypery-model.js
364542
+ function agentModelError(message, code, status3) {
364543
+ {
364544
+ return { name: "AgentModelError", message, code: code ?? "ai_upstream", status: ((__v) => __v == null ? "null" : typeof __v)(status3) === "number" ? status3 : 502 };
364545
+ }
364546
+ }
364547
+ async function resolve2(v) {
364548
+ {
364549
+ if (((__v) => __v == null ? "null" : typeof __v)(v) === "function") {
364550
+ return await (v() ?? null);
364551
+ }
364552
+ return v ?? null;
364553
+ }
364554
+ }
364555
+ function errorCodeFor(status3, payload) {
364556
+ {
364557
+ if (payload != null && ((__v) => __v == null ? "null" : typeof __v)(payload) === "object" && payload.error != null && ((__v) => __v == null ? "null" : typeof __v)(payload.error) === "object" && ((__v) => __v == null ? "null" : typeof __v)(payload.error.code) === "string") {
364558
+ return payload.error.code;
364559
+ }
364560
+ if (status3 === 401) {
364561
+ return "ai_reauth";
364562
+ }
364563
+ if (status3 === 402) {
364564
+ return "ai_credits";
364565
+ }
364566
+ if (status3 === 403) {
364567
+ return "ai_scope";
364568
+ }
364569
+ if (status3 === 429) {
364570
+ return "ai_rate_limited";
364571
+ }
364572
+ return "ai_upstream";
364573
+ }
364574
+ }
364575
+ function streamErrorMessage(payload, fallback2) {
364576
+ {
364577
+ let otherwise = fallback2 ?? "The AI request failed.";
364578
+ if (payload == null || ((__v) => __v == null ? "null" : typeof __v)(payload) !== "object") {
364579
+ return otherwise;
364580
+ }
364581
+ let err2 = payload.error ?? null;
364582
+ if (((__v) => __v == null ? "null" : typeof __v)(err2) === "string" && (err2.trim() ?? null) !== "") {
364583
+ return err2;
364584
+ }
364585
+ let message = err2 != null && ((__v) => __v == null ? "null" : typeof __v)(err2) === "object" ? err2.message ?? null : null;
364586
+ if (message == null) {
364587
+ message = payload.message ?? null;
364588
+ }
364589
+ return ((__v) => __v == null ? "null" : typeof __v)(message) === "string" && (message.trim() ?? null) !== "" ? message : otherwise;
364590
+ }
364591
+ }
364592
+ function createStreamAccumulator() {
364593
+ {
364594
+ let buffer = "";
364595
+ let text = "";
364596
+ let reasoning = "";
364597
+ let sawDone = false;
364598
+ let calls = /* @__PURE__ */ new Map() ?? null;
364599
+ let order2 = [];
364600
+ return { push: (part) => {
364601
+ {
364602
+ buffer = buffer + part;
364603
+ let out = [];
364604
+ let nl = buffer.indexOf("\n") ?? null;
364605
+ while (nl >= 0) {
364606
+ let line = (buffer.slice(0, nl) ?? null).trim() ?? null;
364607
+ buffer = buffer.slice(nl + 1) ?? null;
364608
+ nl = buffer.indexOf("\n") ?? null;
364609
+ if (!(line.startsWith("data:") ?? null)) {
364610
+ continue;
364611
+ }
364612
+ let data = (line.slice(5) ?? null).trim() ?? null;
364613
+ if (data === "") {
364614
+ continue;
364615
+ }
364616
+ if (data === "[DONE]") {
364617
+ sawDone = true;
364618
+ continue;
364619
+ }
364620
+ let chunk3 = null;
364621
+ try {
364622
+ {
364623
+ chunk3 = JSON.parse(data) ?? null;
364624
+ }
364625
+ } catch (e) {
364626
+ {
364627
+ continue;
364628
+ }
364629
+ }
364630
+ if (chunk3 == null || ((__v) => __v == null ? "null" : typeof __v)(chunk3) !== "object") {
364631
+ continue;
364632
+ }
364633
+ if (chunk3.error) {
364634
+ let code = ((__v) => __v == null ? "null" : typeof __v)(chunk3.error) === "object" && ((__v) => __v == null ? "null" : typeof __v)(chunk3.error.code) === "string" ? chunk3.error.code : "ai_upstream";
364635
+ throw agentModelError(streamErrorMessage(chunk3, null) ?? null, code, 502) ?? null;
364636
+ }
364637
+ let choice = (Array.isArray(chunk3.choices) ?? null) && chunk3.choices.length > 0 ? chunk3.choices[0] ?? null : null;
364638
+ let delta = choice != null ? choice.delta ?? null : null;
364639
+ if (delta == null) {
364640
+ continue;
364641
+ }
364642
+ if (((__v) => __v == null ? "null" : typeof __v)(delta.content) === "string" && delta.content !== "") {
364643
+ text = text + delta.content;
364644
+ out.push({ textDelta: delta.content }) ?? null;
364645
+ }
364646
+ let r = ((__v) => __v == null ? "null" : typeof __v)(delta.reasoning) === "string" ? delta.reasoning : ((__v) => __v == null ? "null" : typeof __v)(delta.reasoning_content) === "string" ? delta.reasoning_content : "";
364647
+ if (r !== "") {
364648
+ reasoning = reasoning + r;
364649
+ out.push({ reasoningDelta: r }) ?? null;
364650
+ }
364651
+ for (const tc of Array.isArray(delta.tool_calls) ?? null ? delta.tool_calls : []) {
364652
+ let i2 = ((__v) => __v == null ? "null" : typeof __v)(tc.index) === "number" ? tc.index : order2.length > 0 ? order2[order2.length - 1] ?? null : 0;
364653
+ if (!(calls.has(i2) ?? null)) {
364654
+ calls.set(i2, { id: null, name: "", arguments: "" }) ?? null;
364655
+ order2.push(i2) ?? null;
364656
+ }
364657
+ let call2 = calls.get(i2) ?? null;
364658
+ if (((__v) => __v == null ? "null" : typeof __v)(tc.id) === "string" && tc.id !== "") {
364659
+ call2.id = tc.id;
364660
+ }
364661
+ let f2 = tc["function"] ?? null ?? null;
364662
+ if (f2 != null && ((__v) => __v == null ? "null" : typeof __v)(f2.name) === "string") {
364663
+ call2.name = call2.name + f2.name;
364664
+ }
364665
+ if (f2 != null && ((__v) => __v == null ? "null" : typeof __v)(f2.arguments) === "string" && f2.arguments !== "") {
364666
+ call2.arguments = call2.arguments + f2.arguments;
364667
+ out.push({ toolProgress: { index: i2, name: call2.name, bytes: call2.arguments.length, arguments: call2.arguments } }) ?? null;
364668
+ }
364669
+ }
364670
+ }
364671
+ return out;
364672
+ }
364673
+ }, result: () => {
364674
+ {
364675
+ let toolCalls = [];
364676
+ let n = 0;
364677
+ for (const i2 of order2) {
364678
+ let c2 = calls.get(i2) ?? null;
364679
+ if (c2.name !== "") {
364680
+ toolCalls.push({ id: c2.id ?? "call_" + (String(n) ?? null), name: c2.name, arguments: c2.arguments }) ?? null;
364681
+ }
364682
+ n = n + 1;
364683
+ }
364684
+ return { text, reasoning, sawDone, toolCalls };
364685
+ }
364686
+ } };
364687
+ }
364688
+ }
364689
+ function appendBytes(pending8, chunk3) {
364690
+ {
364691
+ let out = pending8.slice() ?? null;
364692
+ let i2 = 0;
364693
+ while (i2 < chunk3.length) {
364694
+ out.push(chunk3[i2] ?? null) ?? null;
364695
+ i2 = i2 + 1;
364696
+ }
364697
+ return out;
364698
+ }
364699
+ }
364700
+ function callHook(hooks, name2, value3) {
364701
+ {
364702
+ if (hooks == null || ((__v) => __v == null ? "null" : typeof __v)(hooks) !== "object") {
364703
+ return;
364704
+ }
364705
+ let h = hooks[name2] ?? null;
364706
+ if (((__v) => __v == null ? "null" : typeof __v)(h) === "function") {
364707
+ h(value3) ?? null;
364708
+ }
364709
+ }
364710
+ }
364711
+ function createHyperyModel(opts) {
364712
+ {
364713
+ let idleMs = ((__v) => __v == null ? "null" : typeof __v)(opts.idleTimeoutMs) === "number" ? opts.idleTimeoutMs : DEFAULT_IDLE_TIMEOUT_MS;
364714
+ let limit = ((__v) => __v == null ? "null" : typeof __v)(opts.maxRequestBytes) === "number" ? opts.maxRequestBytes : MAX_REQUEST_BYTES;
364715
+ let base = ((__v) => __v == null ? "null" : typeof __v)(opts.gatewayUrl) === "string" && opts.gatewayUrl !== "" ? opts.gatewayUrl : "https://hypery.ai";
364716
+ if (base.endsWith("/") ?? null) {
364717
+ base = base.slice(0, base.length - 1) ?? null;
364718
+ }
364719
+ return async (messages, tools, hooks, signal) => {
364720
+ {
364721
+ let token = await (resolve2(opts.token) ?? null);
364722
+ if (((__v) => __v == null ? "null" : typeof __v)(token) !== "string" || token === "") {
364723
+ throw agentModelError("Sign in to Hypery to use the agent.", "ai_reauth", 401) ?? null;
364724
+ }
364725
+ let model = await (resolve2(opts.model) ?? null);
364726
+ let team = await (resolve2(opts.team) ?? null);
364727
+ let paymentSource = await (resolve2(opts.paymentSource) ?? null);
364728
+ let hasTools = (Array.isArray(tools) ?? null) && tools.length > 0;
364729
+ let request2 = { model, messages, stream: true, max_tokens: ((__v) => __v == null ? "null" : typeof __v)(opts.maxTokens) === "number" ? opts.maxTokens : hasTools ? 16384 : 4096 };
364730
+ if (((__v) => __v == null ? "null" : typeof __v)(opts.temperature) === "number") {
364731
+ request2.temperature = opts.temperature;
364732
+ }
364733
+ if (hasTools) {
364734
+ request2.tools = tools;
364735
+ request2.tool_choice = "auto";
364736
+ }
364737
+ let body = JSON.stringify(request2) ?? null;
364738
+ if (body.length > limit) {
364739
+ throw agentModelError("This message is too large to send (" + ((body.length / 1e6).toFixed(1) ?? null) + " MB with its images). Send fewer or smaller images.", "too_large", 413) ?? null;
364740
+ }
364741
+ let headers = { Authorization: "Bearer " + token, "Content-Type": "application/json", Accept: "text/event-stream" };
364742
+ if (((__v) => __v == null ? "null" : typeof __v)(team) === "string" && team !== "") {
364743
+ headers[HYPERY_TEAM_HEADER2] = team;
364744
+ }
364745
+ if (((__v) => __v == null ? "null" : typeof __v)(paymentSource) === "string" && paymentSource !== "") {
364746
+ headers[HYPERY_PAYMENT_SOURCE_HEADER2] = paymentSource;
364747
+ }
364748
+ let init = { method: "POST", headers, body };
364749
+ if (signal != null && ((__v) => __v == null ? "null" : typeof __v)(signal.addEventListener) === "function") {
364750
+ init.signal = signal;
364751
+ }
364752
+ let res = null;
364753
+ try {
364754
+ {
364755
+ res = await (opts.fetch(base + "/api/v1/chat/completions", init) ?? null);
364756
+ }
364757
+ } catch (err2) {
364758
+ {
364759
+ if (err2 != null && ((__v) => __v == null ? "null" : typeof __v)(err2) === "object" && err2.name === "AbortError") {
364760
+ throw err2;
364761
+ }
364762
+ throw agentModelError("Could not reach Hypery. Check your connection.", "network", 0) ?? null;
364763
+ }
364764
+ }
364765
+ if (res.ok !== true || res.body == null) {
364766
+ let text = "";
364767
+ try {
364768
+ {
364769
+ text = await (res.text() ?? null);
364770
+ }
364771
+ } catch (e) {
364772
+ {
364773
+ text = "";
364774
+ }
364775
+ }
364776
+ let payload = text;
364777
+ try {
364778
+ {
364779
+ payload = JSON.parse(text) ?? null;
364780
+ }
364781
+ } catch (e) {
364782
+ {
364783
+ payload = text;
364784
+ }
364785
+ }
364786
+ throw agentModelError(streamErrorMessage(payload, "The AI request failed (" + (String(res.status) ?? null) + ").") ?? null, errorCodeFor(res.status, payload) ?? null, res.status) ?? null;
364787
+ }
364788
+ let acc = createStreamAccumulator() ?? null;
364789
+ let reader = res.body.getReader() ?? null;
364790
+ let pending8 = [];
364791
+ let stopReading = () => {
364792
+ {
364793
+ if (((__v) => __v == null ? "null" : typeof __v)(reader.cancel) === "function") {
364794
+ try {
364795
+ {
364796
+ reader.cancel() ?? null;
364797
+ }
364798
+ } catch (e) {
364799
+ {
364800
+ }
364801
+ }
364802
+ }
364803
+ }
364804
+ };
364805
+ while (true) {
364806
+ if (signal != null && signal.aborted === true) {
364807
+ stopReading() ?? null;
364808
+ throw { name: "AbortError", message: "The request was stopped." };
364809
+ }
364810
+ let next2 = await (Promise.race([reader.read() ?? null, delay(idleMs) ?? null]) ?? null);
364811
+ if (next2 == null) {
364812
+ stopReading() ?? null;
364813
+ throw agentModelError("The model stopped responding.", "ai_timeout", 504) ?? null;
364814
+ }
364815
+ if (next2.done === true) {
364816
+ break;
364817
+ }
364818
+ if (next2.value == null) {
364819
+ continue;
364820
+ }
364821
+ let bytes2 = appendBytes(pending8, next2.value) ?? null;
364822
+ let whole = utf8Complete(bytes2) ?? null;
364823
+ pending8 = bytes2.slice(whole) ?? null;
364824
+ let events = [];
364825
+ try {
364826
+ {
364827
+ events = acc.push(utf8Decode(bytes2.slice(0, whole) ?? null) ?? null) ?? null;
364828
+ }
364829
+ } catch (err2) {
364830
+ {
364831
+ stopReading() ?? null;
364832
+ throw err2;
364833
+ }
364834
+ }
364835
+ for (const e of events) {
364836
+ if (((__v) => __v == null ? "null" : typeof __v)(e.textDelta) === "string") {
364837
+ callHook(hooks, "onTextDelta", e.textDelta) ?? null;
364838
+ }
364839
+ if (((__v) => __v == null ? "null" : typeof __v)(e.reasoningDelta) === "string") {
364840
+ callHook(hooks, "onReasoningDelta", e.reasoningDelta) ?? null;
364841
+ }
364842
+ if (e.toolProgress != null) {
364843
+ callHook(hooks, "onToolProgress", e.toolProgress) ?? null;
364844
+ }
364845
+ }
364846
+ }
364847
+ if (pending8.length > 0) {
364848
+ acc.push(utf8Decode(pending8) ?? null) ?? null;
364849
+ }
364850
+ acc.push("\n") ?? null;
364851
+ let r = acc.result() ?? null;
364852
+ if (!r.sawDone && r.text === "" && r.toolCalls.length === 0) {
364853
+ throw agentModelError("The response was cut off before it started. Try again.", "ai_upstream", 502) ?? null;
364854
+ }
364855
+ return { text: r.text, reasoning: r.reasoning, toolCalls: r.toolCalls };
364856
+ }
364857
+ };
364858
+ }
364859
+ }
364860
+ var delay, utf8Complete, utf8Decode, MAX_REQUEST_BYTES, DEFAULT_IDLE_TIMEOUT_MS, HYPERY_TEAM_HEADER2, HYPERY_PAYMENT_SOURCE_HEADER2;
364861
+ var init_hypery_model = __esm({
364862
+ "node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/hypery-model.js"() {
364863
+ delay = ((ms2) => new Promise((settle4) => setTimeout(() => settle4(null), Math.max(0, Number(ms2) || 0))));
364864
+ utf8Complete = ((b) => {
364865
+ if (!Array.isArray(b)) return null;
364866
+ const n = b.length;
364867
+ for (let i2 = n - 1; i2 >= Math.max(0, n - 3); i2--) {
364868
+ const c2 = b[i2];
364869
+ if ((c2 & 192) === 128) continue;
364870
+ const len3 = c2 <= 127 ? 1 : c2 >= 194 && c2 <= 223 ? 2 : c2 >= 224 && c2 <= 239 ? 3 : c2 >= 240 && c2 <= 244 ? 4 : 1;
364871
+ return n - i2 < len3 ? i2 : n;
364872
+ }
364873
+ return n;
364874
+ });
364875
+ utf8Decode = ((b) => typeof b === "string" ? b : Array.isArray(b) ? new TextDecoder().decode(Uint8Array.from(b)) : null);
364876
+ MAX_REQUEST_BYTES = 44e5;
364877
+ DEFAULT_IDLE_TIMEOUT_MS = 18e4;
364878
+ HYPERY_TEAM_HEADER2 = "x-hypery-active-organization-id";
364879
+ HYPERY_PAYMENT_SOURCE_HEADER2 = "x-hypery-payment-source";
364527
364880
  }
364528
364881
  });
364529
364882
 
364530
- // node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/context.js
364531
- function pruneOldImages(messages, keep = KEEP_IMAGE_TURNS) {
364532
- let seen = 0;
364533
- for (let i2 = messages.length - 1; i2 >= 0; i2--) {
364534
- const m = messages[i2];
364535
- if (!isRenderTurn(m) || !Array.isArray(m.content) || !m.content.some((p2) => p2.type === "image_url"))
364536
- continue;
364537
- if (++seen <= keep)
364538
- continue;
364539
- const images = m.content.filter((p2) => p2.type === "image_url").length;
364540
- const text = m.content.flatMap((p2) => p2.type === "text" && p2.text ? [p2.text] : []).join(" ");
364541
- messages[i2] = { ...m, content: `${text} [${images === 1 ? "image" : `${images} images`} omitted: superseded by a later view.]`.trim() };
364883
+ // node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/context.js
364884
+ function sizeOf2(messages) {
364885
+ {
364886
+ return (JSON.stringify(messages) ?? null).length;
364887
+ }
364888
+ }
364889
+ function isRenderTurn(m) {
364890
+ {
364891
+ if (m.role !== "user" || !(Array.isArray(m.content) ?? null) || m.content.length === 0) {
364892
+ return false;
364893
+ }
364894
+ let first2 = m.content[0] ?? null;
364895
+ return first2.type === "text" && ((__v) => __v == null ? "null" : typeof __v)(first2.text) === "string" && (first2.text.startsWith(RENDER_TURN_PREFIX) ?? null);
364896
+ }
364897
+ }
364898
+ function countImages(parts) {
364899
+ {
364900
+ return (parts.filter((p2) => {
364901
+ {
364902
+ return p2.type === "image_url";
364903
+ }
364904
+ }) ?? null).length;
364905
+ }
364906
+ }
364907
+ function textOf2(parts) {
364908
+ {
364909
+ return ((parts.filter((p2) => {
364910
+ {
364911
+ return p2.type === "text" && ((__v) => __v == null ? "null" : typeof __v)(p2.text) === "string" && p2.text !== "";
364912
+ }
364913
+ }) ?? null).map((p2) => {
364914
+ {
364915
+ return p2.text;
364916
+ }
364917
+ }) ?? null).join(" ") ?? null;
364918
+ }
364919
+ }
364920
+ function imagesLabel(n) {
364921
+ {
364922
+ return n === 1 ? "image" : (String(n) ?? null) + " images";
364923
+ }
364924
+ }
364925
+ function pruneOldImages(messages, keep) {
364926
+ {
364927
+ let limit = ((__v) => __v == null ? "null" : typeof __v)(keep) === "number" ? keep : KEEP_IMAGE_TURNS;
364928
+ let seen = 0;
364929
+ let i2 = messages.length - 1;
364930
+ while (i2 >= 0) {
364931
+ let m = messages[i2] ?? null;
364932
+ if ((isRenderTurn(m) ?? null) && (countImages(m.content) ?? null) > 0) {
364933
+ seen = seen + 1;
364934
+ if (seen > limit) {
364935
+ let note2 = (textOf2(m.content) ?? null) + " [" + (imagesLabel(countImages(m.content) ?? null) ?? null) + " omitted: superseded by a later view.]";
364936
+ messages[i2] = { ...m, content: note2.trim() ?? null };
364937
+ }
364938
+ }
364939
+ i2 = i2 - 1;
364940
+ }
364542
364941
  }
364543
364942
  }
364544
364943
  function fitImagesToBudget(messages, budget) {
364545
- if (sizeOf2(messages) <= budget)
364546
- return;
364547
- for (let i2 = 0; i2 < messages.length && sizeOf2(messages) > budget; i2++) {
364548
- const m = messages[i2];
364549
- if (!isRenderTurn(m) || !Array.isArray(m.content))
364550
- continue;
364551
- const parts = [...m.content];
364552
- let dropped = 0;
364553
- for (let j = parts.length - 1; j >= 0 && sizeOf2(messages) > budget; j--) {
364554
- if (parts[j].type !== "image_url")
364555
- continue;
364556
- parts.splice(j, 1);
364557
- dropped++;
364558
- messages[i2] = { ...m, content: [...parts] };
364944
+ {
364945
+ if ((sizeOf2(messages) ?? null) <= budget) {
364946
+ return;
364559
364947
  }
364560
- if (dropped) {
364561
- const note2 = `[${dropped === 1 ? "1 image" : `${dropped} images`} omitted to keep the request under the size limit.]`;
364562
- messages[i2] = { ...m, content: `${parts.flatMap((p2) => p2.type === "text" && p2.text ? [p2.text] : []).join(" ")} ${note2}`.trim() };
364948
+ let i2 = 0;
364949
+ while (i2 < messages.length && (sizeOf2(messages) ?? null) > budget) {
364950
+ let m = messages[i2] ?? null;
364951
+ if (isRenderTurn(m) ?? null) {
364952
+ let parts = m.content.slice() ?? null;
364953
+ let dropped = 0;
364954
+ let j = parts.length - 1;
364955
+ while (j >= 0 && (sizeOf2(messages) ?? null) > budget) {
364956
+ if ((parts[j] ?? null).type === "image_url") {
364957
+ parts.splice(j, 1) ?? null;
364958
+ dropped = dropped + 1;
364959
+ messages[i2] = { ...m, content: parts.slice() ?? null };
364960
+ }
364961
+ j = j - 1;
364962
+ }
364963
+ if (dropped > 0) {
364964
+ let label3 = dropped === 1 ? "1 image" : (String(dropped) ?? null) + " images";
364965
+ let note2 = (textOf2(parts) ?? null) + " [" + label3 + " omitted to keep the request under the size limit.]";
364966
+ messages[i2] = { ...m, content: note2.trim() ?? null };
364967
+ }
364968
+ }
364969
+ i2 = i2 + 1;
364563
364970
  }
364564
364971
  }
364565
364972
  }
364566
364973
  function safeTailStart(messages, want) {
364567
- let i2 = Math.max(1, messages.length - want);
364568
- while (i2 < messages.length && messages[i2].role === "tool")
364569
- i2++;
364570
- return i2;
364974
+ {
364975
+ let i2 = Math.max(1, messages.length - want) ?? null;
364976
+ while (i2 < messages.length && (messages[i2] ?? null).role === "tool") {
364977
+ i2 = i2 + 1;
364978
+ }
364979
+ return i2;
364980
+ }
364571
364981
  }
364572
364982
  async function compactTranscript(messages, opts) {
364573
- if (sizeOf2(messages) <= opts.maxChars)
364574
- return false;
364575
- const head2 = messages[0]?.role === "system" ? 1 : 0;
364576
- const firstUser = messages.findIndex((m, i2) => i2 >= head2 && m.role === "user");
364577
- const keepFrom = firstUser >= 0 ? firstUser + 1 : head2;
364578
- const tail = safeTailStart(messages, opts.keepRecent ?? 12);
364579
- if (tail <= keepFrom)
364580
- return false;
364581
- const dropped = messages.slice(keepFrom, tail);
364582
- const summary = opts.summarize ? await opts.summarize(dropped).catch(() => "") : "";
364583
- const note2 = {
364584
- role: "user",
364585
- content: summary ? `Summary of the earlier work in this session (the details were compacted to save space):
364586
- ${summary}` : `[${dropped.length} earlier messages were compacted to save space. Look again at anything you need from them.]`
364587
- };
364588
- messages.splice(keepFrom, dropped.length, note2);
364589
- return true;
364983
+ {
364984
+ if ((sizeOf2(messages) ?? null) <= opts.maxChars) {
364985
+ return false;
364986
+ }
364987
+ let head2 = messages.length > 0 && (messages[0] ?? null).role === "system" ? 1 : 0;
364988
+ let firstUser = -1;
364989
+ let k2 = head2;
364990
+ while (k2 < messages.length && firstUser < 0) {
364991
+ if ((messages[k2] ?? null).role === "user") {
364992
+ firstUser = k2;
364993
+ }
364994
+ k2 = k2 + 1;
364995
+ }
364996
+ let keepFrom = firstUser >= 0 ? firstUser + 1 : head2;
364997
+ let tail = safeTailStart(messages, ((__v) => __v == null ? "null" : typeof __v)(opts.keepRecent) === "number" ? opts.keepRecent : 12) ?? null;
364998
+ if (tail <= keepFrom) {
364999
+ return false;
365000
+ }
365001
+ let dropped = messages.slice(keepFrom, tail) ?? null;
365002
+ let summary = "";
365003
+ if (((__v) => __v == null ? "null" : typeof __v)(opts.summarize) === "function") {
365004
+ try {
365005
+ {
365006
+ summary = await (opts.summarize(dropped) ?? null);
365007
+ }
365008
+ } catch (e) {
365009
+ {
365010
+ summary = "";
365011
+ }
365012
+ }
365013
+ }
365014
+ let content = summary !== "" ? "Summary of the earlier work in this session (the details were compacted to save space):\n" + summary : "[" + (String(dropped.length) ?? null) + " earlier messages were compacted to save space. Look again at anything you need from them.]";
365015
+ messages.splice(keepFrom, dropped.length, { role: "user", content }) ?? null;
365016
+ return true;
365017
+ }
364590
365018
  }
364591
- var RENDER_TURN_PREFIX, KEEP_IMAGE_TURNS, sizeOf2, isRenderTurn;
365019
+ var RENDER_TURN_PREFIX, KEEP_IMAGE_TURNS;
364592
365020
  var init_context2 = __esm({
364593
- "node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/context.js"() {
365021
+ "node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/context.js"() {
364594
365022
  RENDER_TURN_PREFIX = "Result of ";
364595
365023
  KEEP_IMAGE_TURNS = 2;
364596
- sizeOf2 = (messages) => JSON.stringify(messages).length;
364597
- isRenderTurn = (m) => m.role === "user" && Array.isArray(m.content) && m.content[0]?.type === "text" && !!m.content[0].text?.startsWith(RENDER_TURN_PREFIX);
364598
365024
  }
364599
365025
  });
364600
365026
 
364601
- // node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/loop.js
365027
+ // node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/loop.js
364602
365028
  function batchCalls(calls, isParallel, max3) {
364603
- const batches = [];
364604
- for (const call2 of calls) {
364605
- const last3 = batches[batches.length - 1];
364606
- const parallel = isParallel(call2.name);
364607
- if (parallel && last3 && last3.length < max3 && isParallel(last3[0].name))
364608
- last3.push(call2);
364609
- else
364610
- batches.push([call2]);
365029
+ {
365030
+ let batches = [];
365031
+ for (const call2 of calls) {
365032
+ let last3 = batches.length > 0 ? batches[batches.length - 1] ?? null : null;
365033
+ let parallel = isParallel(call2.name) ?? null;
365034
+ if (parallel && last3 != null && last3.length < max3 && (isParallel((last3[0] ?? null).name) ?? null)) {
365035
+ last3.push(call2) ?? null;
365036
+ } else {
365037
+ batches.push([call2]) ?? null;
365038
+ }
365039
+ }
365040
+ return batches;
364611
365041
  }
364612
- return batches;
364613
365042
  }
364614
365043
  function truncateResult(text, max3) {
364615
- return text.length <= max3 ? text : `${text.slice(0, max3)}
364616
- \u2026[truncated ${text.length - max3} characters]`;
365044
+ {
365045
+ if (text.length <= max3) {
365046
+ return text;
365047
+ }
365048
+ return (text.slice(0, max3) ?? null) + "\n\u2026[truncated " + (String(text.length - max3) ?? null) + " characters]";
365049
+ }
364617
365050
  }
364618
365051
  function defaultIsRecoverable(err2) {
364619
- const e = err2;
364620
- if (!e)
364621
- return false;
364622
- if (typeof e.status === "number")
364623
- return e.status >= 500 || e.status === 408 || e.status === 429;
364624
- const text = `${e.name ?? ""} ${e.code ?? ""} ${e.message ?? ""}`.toLowerCase();
364625
- return /timeout|timed out|stalled|network|fetch failed|econnreset|socket|stream/.test(text);
365052
+ {
365053
+ if (err2 == null || ((__v) => __v == null ? "null" : typeof __v)(err2) !== "object") {
365054
+ return false;
365055
+ }
365056
+ if (((__v) => __v == null ? "null" : typeof __v)(err2.status) === "number") {
365057
+ return err2.status >= 500 || err2.status === 408 || err2.status === 429;
365058
+ }
365059
+ let text = ((String(err2.name ?? "") ?? null) + " " + (String(err2.code ?? "") ?? null) + " " + (String(err2.message ?? "") ?? null)).toLowerCase() ?? null;
365060
+ return RECOVERABLE_WORDS.some((w) => {
365061
+ {
365062
+ return text.includes(w) ?? null;
365063
+ }
365064
+ }) ?? null;
365065
+ }
365066
+ }
365067
+ function errorMessage(err2) {
365068
+ {
365069
+ if (err2 != null && ((__v) => __v == null ? "null" : typeof __v)(err2) === "object" && ((__v) => __v == null ? "null" : typeof __v)(err2.message) === "string") {
365070
+ return err2.message;
365071
+ }
365072
+ return String(err2) ?? null;
365073
+ }
365074
+ }
365075
+ function repairTranscript(messages) {
365076
+ {
365077
+ let i2 = 0;
365078
+ while (i2 < messages.length) {
365079
+ let m = messages[i2] ?? null;
365080
+ if (m.role === "assistant" && (Array.isArray(m.tool_calls) ?? null) && m.tool_calls.length > 0) {
365081
+ let j = i2 + 1;
365082
+ let answered = /* @__PURE__ */ new Set() ?? null;
365083
+ while (j < messages.length && (messages[j] ?? null).role === "tool") {
365084
+ answered.add((messages[j] ?? null).tool_call_id ?? "") ?? null;
365085
+ j = j + 1;
365086
+ }
365087
+ let missing = m.tool_calls.filter((c2) => {
365088
+ {
365089
+ return !(answered.has(c2.id) ?? null);
365090
+ }
365091
+ }) ?? null;
365092
+ if (missing.length > 0) {
365093
+ let fillers = missing.map((c2) => {
365094
+ {
365095
+ return { role: "tool", tool_call_id: c2.id, name: (c2["function"] ?? null).name, content: JSON.stringify({ error: "interrupted: this call did not finish (the session was interrupted). Check its effect and run it again if needed." }) ?? null };
365096
+ }
365097
+ }) ?? null;
365098
+ messages.splice(j, 0, ...fillers) ?? null;
365099
+ i2 = j + missing.length - 1;
365100
+ }
365101
+ }
365102
+ i2 = i2 + 1;
365103
+ }
365104
+ return messages;
365105
+ }
365106
+ }
365107
+ function hook(hooks, name2) {
365108
+ {
365109
+ if (hooks == null || ((__v) => __v == null ? "null" : typeof __v)(hooks) !== "object") {
365110
+ return null;
365111
+ }
365112
+ let h = hooks[name2] ?? null;
365113
+ return ((__v) => __v == null ? "null" : typeof __v)(h) === "function" ? h : null;
365114
+ }
364626
365115
  }
364627
365116
  async function runAgentLoop(opts) {
364628
- const maxRounds = opts.maxRounds ?? DEFAULT_MAX_ROUNDS;
364629
- const maxResultChars = opts.maxResultChars ?? 8e3;
364630
- const specs = opts.tools.map((t3) => t3.spec);
364631
- const parallelNames = new Set(opts.tools.filter((t3) => t3.readOnly).map((t3) => t3.spec.function.name));
364632
- const actingNames = new Set(opts.tools.filter((t3) => t3.acts ?? !t3.readOnly).map((t3) => t3.spec.function.name));
364633
- const require3 = opts.requireAction ? typeof opts.requireAction === "object" ? opts.requireAction : {} : null;
364634
- let nudgesLeft = opts.resumeState?.nudgesLeft ?? (require3 ? require3.nudges ?? 2 : 0);
364635
- const isStopped = () => opts.signal?.aborted === true || opts.stopped?.() === true;
364636
- const messages = repairTranscript([...opts.messages]);
364637
- let text = "";
364638
- let acted = opts.resumeState?.acted ?? false;
364639
- const save = (round5, done) => opts.checkpoint?.({ messages: [...messages], round: round5, acted, nudgesLeft, done });
364640
- const fit2 = async () => {
364641
- const c2 = opts.context ?? {};
364642
- pruneOldImages(messages, c2.keepImageTurns);
364643
- if (c2.compact)
364644
- await compactTranscript(messages, c2.compact);
364645
- fitImagesToBudget(messages, (c2.maxRequestChars ?? 43e5) - JSON.stringify(specs).length);
364646
- };
364647
- const call2 = async (msgs, tools) => {
364648
- const retries = opts.modelRetries ?? 2;
364649
- const recoverable = opts.isRecoverable ?? defaultIsRecoverable;
364650
- for (let attempt = 0; ; attempt++) {
364651
- try {
364652
- return await opts.callModel(msgs, tools, {
364653
- onTextDelta: opts.hooks?.onTextDelta,
364654
- onReasoningDelta: opts.hooks?.onReasoningDelta,
364655
- onToolProgress: opts.hooks?.onToolProgress
364656
- }, opts.signal);
364657
- } catch (err2) {
364658
- if (isStopped() || attempt >= retries || !recoverable(err2))
364659
- throw err2;
365117
+ {
365118
+ let maxRounds = ((__v) => __v == null ? "null" : typeof __v)(opts.maxRounds) === "number" ? opts.maxRounds : DEFAULT_MAX_ROUNDS;
365119
+ let maxResultChars = ((__v) => __v == null ? "null" : typeof __v)(opts.maxResultChars) === "number" ? opts.maxResultChars : 8e3;
365120
+ let maxParallel = ((__v) => __v == null ? "null" : typeof __v)(opts.maxParallel) === "number" ? opts.maxParallel : DEFAULT_MAX_PARALLEL;
365121
+ let hooks = opts.hooks ?? null;
365122
+ let specs = opts.tools.map((t3) => {
365123
+ {
365124
+ return t3.spec;
365125
+ }
365126
+ }) ?? null;
365127
+ let parallelNames = new Set((opts.tools.filter((t3) => {
365128
+ {
365129
+ return t3.readOnly === true;
365130
+ }
365131
+ }) ?? null).map((t3) => {
365132
+ {
365133
+ return (t3.spec["function"] ?? null).name;
365134
+ }
365135
+ }) ?? null) ?? null;
365136
+ let actingNames = new Set((opts.tools.filter((t3) => {
365137
+ {
365138
+ return ((__v) => __v == null ? "null" : typeof __v)(t3.acts) === "boolean" ? t3.acts : t3.readOnly !== true;
365139
+ }
365140
+ }) ?? null).map((t3) => {
365141
+ {
365142
+ return (t3.spec["function"] ?? null).name;
364660
365143
  }
365144
+ }) ?? null) ?? null;
365145
+ let require3 = null;
365146
+ if (opts.requireAction === true) {
365147
+ require3 = {};
364661
365148
  }
364662
- };
364663
- for (let round5 = opts.resumeState?.round ?? 0; maxRounds === 0 || round5 < maxRounds; round5++) {
364664
- if (isStopped()) {
364665
- await save(round5, true);
364666
- return { messages, text, rounds: round5, exhausted: false, stopped: true, acted };
364667
- }
364668
- for (const note2 of opts.drainNotifications?.() ?? [])
364669
- messages.push({ role: "user", content: note2 });
364670
- await fit2();
364671
- opts.hooks?.onAssistantStart?.(round5);
364672
- const turn = await call2(messages, specs);
364673
- text = turn.text;
364674
- messages.push({
364675
- role: "assistant",
364676
- content: turn.text,
364677
- ...turn.toolCalls.length ? { tool_calls: turn.toolCalls.map((c2) => ({ id: c2.id, type: "function", function: { name: c2.name, arguments: c2.arguments } })) } : {}
364678
- });
364679
- if (!turn.toolCalls.length) {
364680
- opts.hooks?.onRoundEnd?.(round5);
364681
- const late = opts.drainNotifications?.() ?? [];
364682
- if (late.length) {
364683
- for (const note2 of late)
364684
- messages.push({ role: "user", content: note2 });
364685
- continue;
365149
+ if (opts.requireAction != null && ((__v) => __v == null ? "null" : typeof __v)(opts.requireAction) === "object") {
365150
+ require3 = opts.requireAction;
365151
+ }
365152
+ let resume = opts.resumeState ?? {};
365153
+ let nudgesLeft = ((__v) => __v == null ? "null" : typeof __v)(resume.nudgesLeft) === "number" ? resume.nudgesLeft : require3 != null ? ((__v) => __v == null ? "null" : typeof __v)(require3.nudges) === "number" ? require3.nudges : 2 : 0;
365154
+ let signal = opts.signal ?? null;
365155
+ let isStopped = () => {
365156
+ {
365157
+ if (signal != null && signal.aborted === true) {
365158
+ return true;
365159
+ }
365160
+ return ((__v) => __v == null ? "null" : typeof __v)(opts.stopped) === "function" && (opts.stopped() ?? null) === true;
364686
365161
  }
364687
- if (require3 && !acted && nudgesLeft > 0 && actingNames.size > 0) {
364688
- nudgesLeft--;
364689
- const nudge = require3.message ?? DEFAULT_ACTION_NUDGE;
364690
- opts.hooks?.onNudge?.(nudge);
364691
- messages.push({ role: "user", content: nudge });
364692
- await save(round5 + 1, false);
364693
- continue;
365162
+ };
365163
+ let messages = repairTranscript(opts.messages.slice() ?? null) ?? null;
365164
+ let text = "";
365165
+ let acted = resume.acted === true;
365166
+ let retries = ((__v) => __v == null ? "null" : typeof __v)(opts.modelRetries) === "number" ? opts.modelRetries : 2;
365167
+ let recoverable = ((__v) => __v == null ? "null" : typeof __v)(opts.isRecoverable) === "function" ? opts.isRecoverable : defaultIsRecoverable;
365168
+ let ctx2 = opts.context ?? {};
365169
+ let maxRequestChars = ((__v) => __v == null ? "null" : typeof __v)(ctx2.maxRequestChars) === "number" ? ctx2.maxRequestChars : 43e5;
365170
+ let save = async (round6, done) => {
365171
+ {
365172
+ if (((__v) => __v == null ? "null" : typeof __v)(opts.checkpoint) === "function") {
365173
+ await (opts.checkpoint({ messages: messages.slice() ?? null, round: round6, acted, nudgesLeft, done }) ?? null);
365174
+ }
364694
365175
  }
364695
- await save(round5 + 1, true);
364696
- return { messages, text, rounds: round5 + 1, exhausted: false, stopped: false, acted };
364697
- }
364698
- const calls = turn.toolCalls.map((c2) => ({ id: c2.id, name: c2.name, argsText: c2.arguments }));
364699
- const imageTurns = [];
364700
- for (const batch of batchCalls(calls, (n) => parallelNames.has(n), opts.maxParallel ?? DEFAULT_MAX_PARALLEL)) {
364701
- if (isStopped()) {
364702
- for (const c2 of calls)
364703
- if (!messages.some((m) => m.role === "tool" && m.tool_call_id === c2.id))
364704
- messages.push({ role: "tool", tool_call_id: c2.id, name: c2.name, content: JSON.stringify({ error: "stopped" }) });
364705
- await save(round5 + 1, true);
364706
- return { messages, text, rounds: round5 + 1, exhausted: false, stopped: true, acted };
364707
- }
364708
- for (const info2 of batch)
364709
- opts.hooks?.onToolStart?.(info2);
364710
- const runs = await Promise.all(batch.map(async (info2) => {
364711
- try {
364712
- return await opts.execTool(info2);
364713
- } catch (err2) {
364714
- const message = err2?.message ?? String(err2);
364715
- return { ...info2, ok: false, summary: message, content: JSON.stringify({ error: message }) };
365176
+ };
365177
+ let drain = () => {
365178
+ {
365179
+ if (((__v) => __v == null ? "null" : typeof __v)(opts.drainNotifications) !== "function") {
365180
+ return [];
364716
365181
  }
364717
- }));
364718
- for (const run4 of runs) {
364719
- if (run4.ok && (run4.acted ?? actingNames.has(run4.name)))
364720
- acted = true;
364721
- opts.hooks?.onToolEnd?.(run4);
364722
- messages.push({ role: "tool", tool_call_id: run4.id, name: run4.name, content: truncateResult(run4.content, maxResultChars) });
364723
- if (run4.images?.length) {
364724
- imageTurns.push({
364725
- role: "user",
364726
- content: [
364727
- { type: "text", text: `${RENDER_TURN_PREFIX2}${run4.name}: ${run4.images.length === 1 ? "the rendered view" : `${run4.images.length} rendered views`}.` },
364728
- ...run4.images.map((url4) => ({ type: "image_url", image_url: { url: url4 } }))
364729
- ]
364730
- });
365182
+ let notes = opts.drainNotifications() ?? null;
365183
+ return Array.isArray(notes) ?? null ? notes : [];
365184
+ }
365185
+ };
365186
+ let modelHooks = { onTextDelta: hook(hooks, "onTextDelta") ?? null, onReasoningDelta: hook(hooks, "onReasoningDelta") ?? null, onToolProgress: hook(hooks, "onToolProgress") ?? null };
365187
+ let call2 = async (msgs, tools) => {
365188
+ {
365189
+ let attempt = 0;
365190
+ while (true) {
365191
+ try {
365192
+ {
365193
+ return await (opts.callModel(msgs, tools, modelHooks, signal) ?? null);
365194
+ }
365195
+ } catch (err2) {
365196
+ {
365197
+ if ((isStopped() ?? null) || attempt >= retries || !(recoverable(err2) ?? null)) {
365198
+ throw err2;
365199
+ }
365200
+ }
365201
+ }
365202
+ attempt = attempt + 1;
364731
365203
  }
364732
365204
  }
365205
+ };
365206
+ let round5 = ((__v) => __v == null ? "null" : typeof __v)(resume.round) === "number" ? resume.round : 0;
365207
+ while (maxRounds === 0 || round5 < maxRounds) {
365208
+ if (isStopped() ?? null) {
365209
+ await (save(round5, true) ?? null);
365210
+ return { messages, text, rounds: round5, exhausted: false, stopped: true, acted };
365211
+ }
365212
+ for (const note2 of drain() ?? null) {
365213
+ messages.push({ role: "user", content: note2 }) ?? null;
365214
+ }
365215
+ pruneOldImages(messages, ctx2.keepImageTurns ?? null) ?? null;
365216
+ if (ctx2.compact != null && ((__v) => __v == null ? "null" : typeof __v)(ctx2.compact) === "object") {
365217
+ await (compactTranscript(messages, ctx2.compact) ?? null);
365218
+ }
365219
+ fitImagesToBudget(messages, maxRequestChars - (JSON.stringify(specs) ?? null).length) ?? null;
365220
+ let onStart = hook(hooks, "onAssistantStart") ?? null;
365221
+ if (onStart != null) {
365222
+ onStart(round5) ?? null;
365223
+ }
365224
+ let turn = await (call2(messages, specs) ?? null);
365225
+ text = turn.text;
365226
+ let toolCalls = Array.isArray(turn.toolCalls) ?? null ? turn.toolCalls : [];
365227
+ if (toolCalls.length > 0) {
365228
+ messages.push({ role: "assistant", content: turn.text, tool_calls: toolCalls.map((c2) => {
365229
+ {
365230
+ return { id: c2.id, type: "function", function: { name: c2.name, arguments: c2.arguments } };
365231
+ }
365232
+ }) ?? null }) ?? null;
365233
+ } else {
365234
+ messages.push({ role: "assistant", content: turn.text }) ?? null;
365235
+ }
365236
+ if (toolCalls.length === 0) {
365237
+ let onEnd = hook(hooks, "onRoundEnd") ?? null;
365238
+ if (onEnd != null) {
365239
+ onEnd(round5) ?? null;
365240
+ }
365241
+ let late = drain() ?? null;
365242
+ if (late.length > 0) {
365243
+ for (const note2 of late) {
365244
+ messages.push({ role: "user", content: note2 }) ?? null;
365245
+ }
365246
+ round5 = round5 + 1;
365247
+ continue;
365248
+ }
365249
+ if (require3 != null && !acted && nudgesLeft > 0 && actingNames.size > 0) {
365250
+ nudgesLeft = nudgesLeft - 1;
365251
+ let nudge = ((__v) => __v == null ? "null" : typeof __v)(require3.message) === "string" ? require3.message : DEFAULT_ACTION_NUDGE;
365252
+ let onNudge = hook(hooks, "onNudge") ?? null;
365253
+ if (onNudge != null) {
365254
+ onNudge(nudge) ?? null;
365255
+ }
365256
+ messages.push({ role: "user", content: nudge }) ?? null;
365257
+ await (save(round5 + 1, false) ?? null);
365258
+ round5 = round5 + 1;
365259
+ continue;
365260
+ }
365261
+ await (save(round5 + 1, true) ?? null);
365262
+ return { messages, text, rounds: round5 + 1, exhausted: false, stopped: false, acted };
365263
+ }
365264
+ let calls = toolCalls.map((c2) => {
365265
+ {
365266
+ return { id: c2.id, name: c2.name, argsText: c2.arguments };
365267
+ }
365268
+ }) ?? null;
365269
+ let imageTurns = [];
365270
+ for (const batch of batchCalls(calls, (n) => {
365271
+ {
365272
+ return parallelNames.has(n) ?? null;
365273
+ }
365274
+ }, maxParallel) ?? null) {
365275
+ if (isStopped() ?? null) {
365276
+ for (const c2 of calls) {
365277
+ let answered = messages.some((m) => {
365278
+ {
365279
+ return m.role === "tool" && m.tool_call_id === c2.id;
365280
+ }
365281
+ }) ?? null;
365282
+ if (!answered) {
365283
+ messages.push({ role: "tool", tool_call_id: c2.id, name: c2.name, content: JSON.stringify({ error: "stopped" }) ?? null }) ?? null;
365284
+ }
365285
+ }
365286
+ await (save(round5 + 1, true) ?? null);
365287
+ return { messages, text, rounds: round5 + 1, exhausted: false, stopped: true, acted };
365288
+ }
365289
+ let onToolStart = hook(hooks, "onToolStart") ?? null;
365290
+ if (onToolStart != null) {
365291
+ for (const info2 of batch) {
365292
+ onToolStart(info2) ?? null;
365293
+ }
365294
+ }
365295
+ let runs = await (Promise.all(batch.map(async (info2) => {
365296
+ {
365297
+ try {
365298
+ {
365299
+ return await (opts.execTool(info2) ?? null);
365300
+ }
365301
+ } catch (err2) {
365302
+ {
365303
+ let message = errorMessage(err2) ?? null;
365304
+ return { id: info2.id, name: info2.name, argsText: info2.argsText, ok: false, summary: message, content: JSON.stringify({ error: message }) ?? null };
365305
+ }
365306
+ }
365307
+ }
365308
+ }) ?? null) ?? null);
365309
+ let onToolEnd = hook(hooks, "onToolEnd") ?? null;
365310
+ for (const run4 of runs) {
365311
+ let actedHere = ((__v) => __v == null ? "null" : typeof __v)(run4.acted) === "boolean" ? run4.acted : actingNames.has(run4.name) ?? null;
365312
+ if (run4.ok === true && actedHere) {
365313
+ acted = true;
365314
+ }
365315
+ if (onToolEnd != null) {
365316
+ onToolEnd(run4) ?? null;
365317
+ }
365318
+ messages.push({ role: "tool", tool_call_id: run4.id, name: run4.name, content: truncateResult(run4.content, maxResultChars) ?? null }) ?? null;
365319
+ if ((Array.isArray(run4.images) ?? null) && run4.images.length > 0) {
365320
+ let label3 = run4.images.length === 1 ? "the rendered view" : (String(run4.images.length) ?? null) + " rendered views";
365321
+ let parts = [{ type: "text", text: RENDER_TURN_PREFIX2 + run4.name + ": " + label3 + "." }];
365322
+ for (const url4 of run4.images) {
365323
+ parts.push({ type: "image_url", image_url: { url: url4 } }) ?? null;
365324
+ }
365325
+ imageTurns.push({ role: "user", content: parts }) ?? null;
365326
+ }
365327
+ }
365328
+ }
365329
+ for (const m of imageTurns) {
365330
+ messages.push(m) ?? null;
365331
+ }
365332
+ let onRoundEnd = hook(hooks, "onRoundEnd") ?? null;
365333
+ if (onRoundEnd != null) {
365334
+ onRoundEnd(round5) ?? null;
365335
+ }
365336
+ await (save(round5 + 1, false) ?? null);
365337
+ round5 = round5 + 1;
364733
365338
  }
364734
- for (const m of imageTurns)
364735
- messages.push(m);
364736
- opts.hooks?.onRoundEnd?.(round5);
364737
- await save(round5 + 1, false);
364738
- }
364739
- messages.push({ role: "user", content: "You have reached the tool limit for this turn. Summarise what you changed and what is left, without calling more tools." });
364740
- const final = await call2(messages, []);
364741
- messages.push({ role: "assistant", content: final.text });
364742
- await save(maxRounds, true);
364743
- return { messages, text: final.text, rounds: maxRounds, exhausted: true, stopped: false, acted };
364744
- }
364745
- function repairTranscript(messages) {
364746
- for (let i2 = 0; i2 < messages.length; i2++) {
364747
- const m = messages[i2];
364748
- if (m.role !== "assistant" || !m.tool_calls?.length)
364749
- continue;
364750
- let j = i2 + 1;
364751
- const answered = /* @__PURE__ */ new Set();
364752
- while (j < messages.length && messages[j].role === "tool") {
364753
- answered.add(messages[j].tool_call_id ?? "");
364754
- j++;
364755
- }
364756
- const missing = m.tool_calls.filter((c2) => !answered.has(c2.id));
364757
- if (!missing.length)
364758
- continue;
364759
- messages.splice(j, 0, ...missing.map((c2) => ({
364760
- role: "tool",
364761
- tool_call_id: c2.id,
364762
- name: c2.function.name,
364763
- content: JSON.stringify({ error: "interrupted: this call did not finish (the session was interrupted). Check its effect and run it again if needed." })
364764
- })));
364765
- i2 = j + missing.length - 1;
365339
+ messages.push({ role: "user", content: "You have reached the tool limit for this turn. Summarise what you changed and what is left, without calling more tools." }) ?? null;
365340
+ let final = await (call2(messages, []) ?? null);
365341
+ messages.push({ role: "assistant", content: final.text }) ?? null;
365342
+ await (save(maxRounds, true) ?? null);
365343
+ return { messages, text: final.text, rounds: maxRounds, exhausted: true, stopped: false, acted };
364766
365344
  }
364767
- return messages;
364768
365345
  }
364769
- var DEFAULT_MAX_ROUNDS, DEFAULT_MAX_PARALLEL, DEFAULT_ACTION_NUDGE, RENDER_TURN_PREFIX2;
365346
+ var DEFAULT_MAX_ROUNDS, DEFAULT_MAX_PARALLEL, DEFAULT_ACTION_NUDGE, RENDER_TURN_PREFIX2, RECOVERABLE_WORDS;
364770
365347
  var init_loop = __esm({
364771
- "node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/loop.js"() {
365348
+ "node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/loop.js"() {
364772
365349
  init_context2();
364773
365350
  DEFAULT_MAX_ROUNDS = 40;
364774
365351
  DEFAULT_MAX_PARALLEL = 4;
364775
365352
  DEFAULT_ACTION_NUDGE = "You have not changed anything yet. Stop reading and do what was asked now, with the tools that make changes. If you truly cannot, say exactly what is blocking you.";
364776
365353
  RENDER_TURN_PREFIX2 = "Result of ";
365354
+ RECOVERABLE_WORDS = ["timeout", "timed out", "stalled", "network", "fetch failed", "econnreset", "socket", "stream"];
364777
365355
  }
364778
365356
  });
364779
365357
 
364780
- // node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/runtime.js
364781
- var REPORT_TOOL, reportSpec, AgentRuntime;
364782
- var init_runtime5 = __esm({
364783
- "node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/runtime.js"() {
364784
- init_loop();
364785
- REPORT_TOOL = "report_to_parent";
364786
- reportSpec = {
364787
- readOnly: true,
364788
- acts: false,
364789
- spec: {
364790
- type: "function",
364791
- function: {
364792
- name: REPORT_TOOL,
364793
- description: "Send the main agent a progress update, or a question (set question) when you need a decision you cannot make yourself. It arrives between its steps and it answers with a message you read at your next step \u2014 keep working on what you can meanwhile. Your final answer still goes back by itself when you finish.",
364794
- parameters: { type: "object", properties: { message: { type: "string", description: "What to tell the main agent." }, question: { type: "boolean", description: "This needs an answer." } }, required: ["message"] }
364795
- }
364796
- }
364797
- };
364798
- AgentRuntime = class {
364799
- constructor(host) {
364800
- this.host = host;
364801
- this.sessions = /* @__PURE__ */ new Map();
364802
- this.controllers = /* @__PURE__ */ new Map();
364803
- this.parentQueue = [];
364804
- this.loaded = null;
364805
- this.waiting = [];
364806
- this.activeBackground = 0;
364807
- this.listeners = /* @__PURE__ */ new Set();
364808
- this.pendingSaves = /* @__PURE__ */ new Set();
364809
- }
364810
- /** Bring back the store's sessions (any left "running" by a reload are marked stopped: their run is gone). */
364811
- load() {
364812
- this.loaded ?? (this.loaded = (async () => {
364813
- for (const s of await this.host.store?.load() ?? []) {
364814
- if (s.status === "running")
364815
- Object.assign(s, { status: "stopped", endedAt: s.endedAt ?? this.now() });
364816
- this.sessions.set(s.id, s);
364817
- }
364818
- this.changed();
364819
- })());
364820
- return this.loaded;
364821
- }
364822
- /** Wait until every session change has reached the store (before a process exits or a page unloads). */
364823
- async flush() {
364824
- while (this.pendingSaves.size)
364825
- await Promise.all([...this.pendingSaves]);
364826
- }
364827
- /** Called whenever sessions change (spawned, queued, finished, messaged, stopped). Returns the unsubscribe. */
364828
- subscribe(fn) {
364829
- this.listeners.add(fn);
364830
- return () => {
364831
- this.listeners.delete(fn);
364832
- };
364833
- }
364834
- list() {
364835
- return [...this.sessions.values()].sort((a, b) => a.startedAt - b.startedAt);
364836
- }
364837
- get(id3) {
364838
- return this.sessions.get(id3);
365358
+ // node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/runtime.js
365359
+ function isBusy(s) {
365360
+ {
365361
+ return s != null && (s.status === "running" || s.status === "queued");
365362
+ }
365363
+ }
365364
+ function plainStopControl() {
365365
+ {
365366
+ let flag = { aborted: false };
365367
+ return { signal: flag, stop: () => {
365368
+ {
365369
+ flag.aborted = true;
364839
365370
  }
364840
- /**
364841
- * Resolves once the agent is no longer queued or running, or when `timeoutMs` passes or `signal` aborts (then with
364842
- * the session as it is). `undefined` for an unknown id.
364843
- */
364844
- wait(id3, opts = {}) {
364845
- const busy = (s) => s?.status === "running" || s?.status === "queued";
364846
- if (!busy(this.get(id3)))
364847
- return Promise.resolve(this.get(id3));
364848
- return new Promise((resolve7) => {
364849
- const finish3 = () => {
364850
- unsubscribe();
364851
- clearTimeout(timer);
364852
- opts.signal?.removeEventListener("abort", finish3);
364853
- resolve7(this.get(id3));
364854
- };
364855
- const unsubscribe = this.subscribe(() => {
364856
- if (!busy(this.get(id3)))
364857
- finish3();
364858
- });
364859
- const timer = setTimeout(finish3, opts.timeoutMs ?? 12e4);
364860
- opts.signal?.addEventListener("abort", finish3, { once: true });
364861
- });
365371
+ } };
365372
+ }
365373
+ }
365374
+ function allSessions(sessions) {
365375
+ {
365376
+ let out = [];
365377
+ for (const s of sessions.values() ?? null) {
365378
+ out.push(s) ?? null;
365379
+ }
365380
+ return out;
365381
+ }
365382
+ }
365383
+ function errorMessage2(err2) {
365384
+ {
365385
+ if (err2 != null && ((__v) => __v == null ? "null" : typeof __v)(err2) === "object" && ((__v) => __v == null ? "null" : typeof __v)(err2.message) === "string") {
365386
+ return err2.message;
365387
+ }
365388
+ return String(err2) ?? null;
365389
+ }
365390
+ }
365391
+ function createAgentRuntime(host) {
365392
+ {
365393
+ let sessions = /* @__PURE__ */ new Map() ?? null;
365394
+ let controls = /* @__PURE__ */ new Map() ?? null;
365395
+ let parentQueue = [];
365396
+ let loaded2 = false;
365397
+ let loading3 = null;
365398
+ let active3 = 0;
365399
+ let waiting3 = [];
365400
+ let listeners8 = [];
365401
+ let pendingSaves = 0;
365402
+ let maxConcurrent = ((__v) => __v == null ? "null" : typeof __v)(host.maxConcurrent) === "number" ? host.maxConcurrent : 4;
365403
+ let now2 = () => {
365404
+ {
365405
+ return ((__v) => __v == null ? "null" : typeof __v)(host.now) === "function" ? host.now() ?? null : Date.now() ?? null;
364862
365406
  }
364863
- /** Drop the queued "finished" notice for `id`: the parent already has its answer (await_agent handed it over). */
364864
- dismissFinished(id3) {
364865
- for (let i2 = this.parentQueue.length - 1; i2 >= 0; i2--)
364866
- if (this.parentQueue[i2].startsWith(`Agent ${id3} (`))
364867
- this.parentQueue.splice(i2, 1);
364868
- }
364869
- /** Everything queued for the parent (reports, finished background children), taken. */
364870
- drainParentNotifications() {
364871
- return this.parentQueue.splice(0, this.parentQueue.length);
364872
- }
364873
- hasPendingNotifications() {
364874
- return this.parentQueue.length > 0;
364875
- }
364876
- async spawn(req) {
364877
- const profile = this.host.profiles().find((p2) => p2.id === req.profileId);
364878
- if (!profile)
364879
- return { kind: "refused", reason: `No agent type "${req.profileId}". Available: ${this.host.profiles().map((p2) => p2.id).join(", ")}.` };
364880
- const prompt2 = req.prompt?.trim();
364881
- if (!prompt2)
364882
- return { kind: "refused", reason: "A task needs a self-contained prompt \u2014 the agent cannot see this conversation." };
364883
- const background = req.background ?? profile.background ?? false;
364884
- const session3 = {
364885
- id: this.host.newId?.() ?? `agent-${this.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
364886
- profile: profile.id,
364887
- description: req.description ?? prompt2.slice(0, 80),
364888
- status: "running",
364889
- background,
364890
- transcript: [],
364891
- inbox: [],
364892
- startedAt: this.now(),
364893
- rounds: 0,
364894
- readOnly: req.readOnly === true || profile.readOnly === true,
364895
- ...req.parentCallId ? { parentCallId: req.parentCallId } : {}
364896
- };
364897
- this.sessions.set(session3.id, session3);
364898
- this.changed();
364899
- this.emit({ type: "session", sessionId: session3.id, status: "running", profile: session3.profile, description: session3.description });
364900
- if (background) {
364901
- void this.slot(session3).then(async () => {
364902
- try {
364903
- if (session3.status !== "stopped")
364904
- await this.run(session3, profile, prompt2, req.readOnly === true, req.signal, true);
364905
- } finally {
364906
- this.release();
364907
- }
364908
- }).catch(() => {
364909
- });
364910
- return { kind: "started", id: session3.id };
365407
+ };
365408
+ let changed = () => {
365409
+ {
365410
+ if (((__v) => __v == null ? "null" : typeof __v)(host.onChange) === "function") {
365411
+ host.onChange() ?? null;
364911
365412
  }
364912
- const run4 = this.run(session3, profile, prompt2, req.readOnly === true, req.signal, true);
364913
- const out = await run4;
364914
- return { kind: "done", id: session3.id, ok: out.ok, summary: out.summary, rounds: out.rounds };
364915
- }
364916
- /**
364917
- * Message a child. Running: queued for its next round. Finished: resumed with its whole context and this message —
364918
- * in the background (its answer reaches the parent as a notification) unless `wait` is set.
364919
- */
364920
- async message(id3, text, opts = {}) {
364921
- await this.load();
364922
- const session3 = this.sessions.get(id3);
364923
- if (!session3)
364924
- return { kind: "unknown", id: id3 };
364925
- if (session3.status === "running") {
364926
- session3.inbox.push(text);
364927
- this.persist(session3);
364928
- return { kind: "queued", id: id3 };
365413
+ for (const l of listeners8.slice() ?? null) {
365414
+ l() ?? null;
364929
365415
  }
364930
- const profile = this.host.profiles().find((p2) => p2.id === session3.profile);
364931
- if (!profile)
364932
- return { kind: "unknown", id: id3 };
364933
- Object.assign(session3, { status: "running", endedAt: void 0, background: !opts.wait });
364934
- this.changed();
364935
- if (!opts.wait) {
364936
- void this.slot(session3).then(async () => {
364937
- try {
364938
- if (session3.status !== "stopped")
364939
- await this.run(session3, profile, text, false, opts.signal, false);
364940
- } finally {
364941
- this.release();
364942
- }
364943
- }).catch(() => {
364944
- });
364945
- return { kind: "resumed", id: id3 };
365416
+ }
365417
+ };
365418
+ let emit6 = (e) => {
365419
+ {
365420
+ if (((__v) => __v == null ? "null" : typeof __v)(host.onEvent) === "function") {
365421
+ host.onEvent(e) ?? null;
364946
365422
  }
364947
- const out = await this.run(session3, profile, text, false, opts.signal, false);
364948
- return { kind: "done", id: id3, ok: out.ok, summary: out.summary };
364949
365423
  }
364950
- /** Stop one child. */
364951
- stop(id3) {
364952
- const session3 = this.sessions.get(id3);
364953
- if (!session3 || session3.status !== "running" && session3.status !== "queued")
364954
- return false;
364955
- this.controllers.get(id3)?.abort();
364956
- Object.assign(session3, { status: "stopped", endedAt: this.now() });
364957
- this.persist(session3);
364958
- return true;
365424
+ };
365425
+ let sessionEvent = (s) => {
365426
+ {
365427
+ emit6({ type: "session", sessionId: s.id, status: s.status, profile: s.profile, description: s.description }) ?? null;
364959
365428
  }
364960
- /** Stop every running child (the user pressed Stop); their queued notifications are dropped. */
364961
- stopAll() {
364962
- for (const s of this.sessions.values())
364963
- this.stop(s.id);
364964
- this.parentQueue.length = 0;
364965
- }
364966
- /** A child's report to the parent (also what `report_to_parent` does). A question asks for an answer. */
364967
- report(fromId, text, question = false) {
364968
- const s = this.sessions.get(fromId);
364969
- const who = `agent ${fromId}${s ? ` (${s.profile})` : ""}`;
364970
- this.parentQueue.push(question ? `QUESTION from ${who} \u2014 it needs your answer (send_message ${fromId}):
364971
- ${text}` : `Report from ${who}:
364972
- ${text}`);
364973
- this.emit({ type: "report", sessionId: fromId, message: text, question });
364974
- this.changed();
364975
- }
364976
- /** Take a background slot (maxConcurrent); the session shows 'queued' while it waits. */
364977
- async slot(session3) {
364978
- const max3 = this.host.maxConcurrent ?? 4;
364979
- if (this.activeBackground < max3) {
364980
- this.activeBackground++;
365429
+ };
365430
+ let persist3 = (s) => {
365431
+ {
365432
+ changed() ?? null;
365433
+ if (host.store == null || ((__v) => __v == null ? "null" : typeof __v)(host.store) !== "object") {
364981
365434
  return;
364982
365435
  }
364983
- session3.status = "queued";
364984
- this.emit({ type: "session", sessionId: session3.id, status: "queued", profile: session3.profile, description: session3.description });
364985
- this.changed();
364986
- await new Promise((res) => this.waiting.push(res));
364987
- if (session3.status === "queued")
364988
- session3.status = "running";
364989
- }
364990
- /** A background run ended: give its slot to the next queued agent, or free it. */
364991
- release() {
364992
- const next2 = this.waiting.shift();
364993
- if (next2)
364994
- next2();
364995
- else
364996
- this.activeBackground = Math.max(0, this.activeBackground - 1);
365436
+ pendingSaves = pendingSaves + 1;
365437
+ let save = async () => {
365438
+ {
365439
+ try {
365440
+ {
365441
+ await (host.store.save(s) ?? null);
365442
+ }
365443
+ } catch (e) {
365444
+ {
365445
+ }
365446
+ }
365447
+ pendingSaves = pendingSaves - 1;
365448
+ }
365449
+ };
365450
+ save() ?? null;
364997
365451
  }
364998
- emit(e) {
364999
- this.host.onEvent?.(e);
365452
+ };
365453
+ let profileById = (id3) => {
365454
+ {
365455
+ let found = (host.profiles() ?? null).filter((p2) => {
365456
+ {
365457
+ return p2.id === id3;
365458
+ }
365459
+ }) ?? null;
365460
+ return found.length > 0 ? found[0] ?? null : null;
365000
365461
  }
365001
- async run(session3, profile, prompt2, forceReadOnly, parentSignal, fresh) {
365002
- const controller = new AbortController();
365003
- this.controllers.set(session3.id, controller);
365004
- const abort = () => controller.abort();
365005
- if (parentSignal?.aborted)
365006
- controller.abort();
365007
- else
365008
- parentSignal?.addEventListener("abort", abort, { once: true });
365009
- const ctx2 = { session: session3, profile, readOnly: forceReadOnly || profile.readOnly === true, signal: controller.signal };
365010
- const tools = [...this.host.childTools(ctx2), reportSpec];
365011
- const messages = fresh ? [{ role: "system", content: this.host.childSystemPrompt(ctx2) }, { role: "user", content: prompt2 }] : [...session3.transcript, { role: "user", content: `Message from the main agent:
365012
- ${prompt2}` }];
365462
+ };
365463
+ let report2 = (fromId, text, question) => {
365464
+ {
365465
+ let s = sessions.get(fromId) ?? null ?? null;
365466
+ let who = "agent " + fromId + (s != null ? " (" + s.profile + ")" : "");
365467
+ let asks = question === true;
365468
+ parentQueue.push(asks ? "QUESTION from " + who + " \u2014 it needs your answer (send_message " + fromId + "):\n" + text : "Report from " + who + ":\n" + text) ?? null;
365469
+ emit6({ type: "report", sessionId: fromId, message: text, question: asks }) ?? null;
365470
+ changed() ?? null;
365471
+ }
365472
+ };
365473
+ let run4 = async (session3, profile, prompt2, forceReadOnly, parentSignal, fresh) => {
365474
+ {
365475
+ let control = ((__v) => __v == null ? "null" : typeof __v)(host.createSignal) === "function" ? host.createSignal() ?? null : plainStopControl() ?? null;
365476
+ controls.set(session3.id, control) ?? null;
365477
+ if (parentSignal != null) {
365478
+ if (parentSignal.aborted === true) {
365479
+ control.stop() ?? null;
365480
+ } else if (((__v) => __v == null ? "null" : typeof __v)(parentSignal.addEventListener) === "function") {
365481
+ parentSignal.addEventListener("abort", () => {
365482
+ {
365483
+ control.stop() ?? null;
365484
+ }
365485
+ }) ?? null;
365486
+ }
365487
+ }
365488
+ let ctx2 = { session: session3, profile, readOnly: forceReadOnly || profile.readOnly === true, signal: control.signal };
365489
+ let tools = (host.childTools(ctx2) ?? null).concat([REPORT_SPEC]) ?? null;
365490
+ let messages = fresh ? [{ role: "system", content: host.childSystemPrompt(ctx2) ?? null }, { role: "user", content: prompt2 }] : session3.transcript.concat([{ role: "user", content: "Message from the main agent:\n" + prompt2 }]) ?? null;
365491
+ let childModel = ((__v) => __v == null ? "null" : typeof __v)(host.childModel) === "function" ? host.childModel(ctx2) ?? null : null;
365492
+ let budget = ((__v) => __v == null ? "null" : typeof __v)(profile.maxRounds) === "number" && profile.maxRounds > 0 ? profile.maxRounds : ((__v) => __v == null ? "null" : typeof __v)(host.maxRounds) === "number" && host.maxRounds > 0 ? host.maxRounds : 30;
365013
365493
  let ok2 = true;
365014
365494
  let summary = "";
365015
365495
  let rounds = 0;
365016
365496
  try {
365017
- const outcome = await runAgentLoop({
365018
- messages,
365019
- tools,
365020
- callModel: this.host.childModel?.(ctx2) ?? this.host.callModel,
365021
- signal: controller.signal,
365022
- maxRounds: profile.maxRounds || this.host.maxRounds || 30,
365023
- drainNotifications: () => session3.inbox.splice(0, session3.inbox.length).map((t3) => `Message from the main agent:
365024
- ${t3}`),
365025
- execTool: async (call2) => {
365026
- if (call2.name === REPORT_TOOL) {
365027
- let args2 = {};
365028
- try {
365029
- args2 = JSON.parse(call2.argsText || "{}");
365030
- } catch {
365497
+ {
365498
+ let outcome = await (runAgentLoop({ messages, tools, callModel: ((__v) => __v == null ? "null" : typeof __v)(childModel) === "function" ? childModel : host.callModel, signal: control.signal, stopped: () => {
365499
+ {
365500
+ return parentSignal != null && parentSignal.aborted === true;
365501
+ }
365502
+ }, maxRounds: budget, drainNotifications: () => {
365503
+ {
365504
+ return (session3.inbox.splice(0, session3.inbox.length) ?? null).map((t3) => {
365505
+ {
365506
+ return "Message from the main agent:\n" + t3;
365507
+ }
365508
+ }) ?? null;
365509
+ }
365510
+ }, execTool: async (call2) => {
365511
+ {
365512
+ if (call2.name === REPORT_TOOL) {
365513
+ let args2 = {};
365514
+ try {
365515
+ {
365516
+ args2 = JSON.parse(call2.argsText === "" ? "{}" : call2.argsText) ?? null;
365517
+ }
365518
+ } catch (e) {
365519
+ {
365520
+ args2 = {};
365521
+ }
365522
+ }
365523
+ report2(session3.id, String(args2.message ?? "") ?? null, args2.question === true) ?? null;
365524
+ return { id: call2.id, name: call2.name, argsText: call2.argsText, ok: true, summary: "reported", content: JSON.stringify({ ok: true }) ?? null };
365031
365525
  }
365032
- this.report(session3.id, String(args2.message ?? ""), args2.question === true);
365033
- return { ...call2, ok: true, summary: "reported", content: JSON.stringify({ ok: true }) };
365526
+ return await (host.execChildTool(call2, ctx2) ?? null);
365034
365527
  }
365035
- return this.host.execChildTool(call2, ctx2);
365036
- },
365037
- // A building agent asked to change something keeps going until it has (read-only types just answer).
365038
- requireAction: fresh && !ctx2.readOnly,
365039
- hooks: {
365040
- onToolStart: (c2) => this.emit({ type: "tool-start", sessionId: session3.id, name: c2.name }),
365041
- onToolEnd: (r) => this.emit({ type: "tool-end", sessionId: session3.id, name: r.name, ok: r.ok, summary: r.summary }),
365042
- onTextDelta: (d) => this.emit({ type: "text", sessionId: session3.id, delta: d }),
365043
- onNudge: (m) => this.emit({ type: "nudge", sessionId: session3.id, message: m })
365044
- }
365045
- });
365046
- session3.transcript = outcome.messages;
365047
- rounds = outcome.rounds;
365048
- summary = outcome.text.trim() || (outcome.stopped ? "(stopped)" : "(finished without a summary)");
365049
- ok2 = !outcome.stopped;
365528
+ }, requireAction: fresh && !ctx2.readOnly, hooks: { onToolStart: (c2) => {
365529
+ {
365530
+ emit6({ type: "tool-start", sessionId: session3.id, name: c2.name }) ?? null;
365531
+ }
365532
+ }, onToolEnd: (r) => {
365533
+ {
365534
+ emit6({ type: "tool-end", sessionId: session3.id, name: r.name, ok: r.ok, summary: r.summary }) ?? null;
365535
+ }
365536
+ }, onTextDelta: (d) => {
365537
+ {
365538
+ emit6({ type: "text", sessionId: session3.id, delta: d }) ?? null;
365539
+ }
365540
+ }, onNudge: (m) => {
365541
+ {
365542
+ emit6({ type: "nudge", sessionId: session3.id, message: m }) ?? null;
365543
+ }
365544
+ } } }) ?? null);
365545
+ session3.transcript = outcome.messages;
365546
+ rounds = outcome.rounds;
365547
+ let said = outcome.text.trim() ?? null;
365548
+ summary = said !== "" ? said : outcome.stopped ? "(stopped)" : "(finished without a summary)";
365549
+ ok2 = !outcome.stopped;
365550
+ }
365050
365551
  } catch (err2) {
365051
- ok2 = false;
365052
- summary = `(agent error: ${err2?.message ?? String(err2)})`;
365053
- } finally {
365054
- parentSignal?.removeEventListener("abort", abort);
365055
- this.controllers.delete(session3.id);
365552
+ {
365553
+ ok2 = false;
365554
+ summary = "(agent error: " + (errorMessage2(err2) ?? null) + ")";
365555
+ }
365056
365556
  }
365057
- session3.rounds += rounds;
365058
- if (session3.status === "running")
365059
- Object.assign(session3, { status: ok2 ? "done" : "error", summary, endedAt: this.now() });
365060
- else
365557
+ controls.delete(session3.id) ?? null;
365558
+ session3.rounds = session3.rounds + rounds;
365559
+ if (session3.status === "running") {
365560
+ session3.status = ok2 ? "done" : "error";
365061
365561
  session3.summary = summary;
365562
+ session3.endedAt = now2() ?? null;
365563
+ } else {
365564
+ session3.summary = summary;
365565
+ }
365062
365566
  if (session3.background && session3.status !== "stopped") {
365063
- this.parentQueue.push(`Agent ${session3.id} (${session3.profile}) ${ok2 ? "finished" : "failed"}:
365064
- ${summary}`);
365567
+ parentQueue.push("Agent " + session3.id + " (" + session3.profile + ") " + (ok2 ? "finished" : "failed") + ":\n" + summary) ?? null;
365065
365568
  }
365066
- this.emit({ type: "session", sessionId: session3.id, status: session3.status, profile: session3.profile, description: session3.description });
365067
- this.persist(session3);
365569
+ sessionEvent(session3) ?? null;
365570
+ persist3(session3) ?? null;
365068
365571
  return { ok: ok2, summary, rounds };
365069
365572
  }
365070
- now() {
365071
- return this.host.now?.() ?? Date.now();
365573
+ };
365574
+ let takeNext = () => {
365575
+ {
365576
+ while (waiting3.length > 0) {
365577
+ let next2 = waiting3.shift() ?? null;
365578
+ if (next2.session.status === "queued") {
365579
+ next2.session.status = "running";
365580
+ sessionEvent(next2.session) ?? null;
365581
+ changed() ?? null;
365582
+ return next2;
365583
+ }
365584
+ }
365585
+ return null;
365072
365586
  }
365073
- changed() {
365074
- this.host.onChange?.();
365075
- for (const l of this.listeners)
365076
- l();
365587
+ };
365588
+ let runSlot = (first2) => {
365589
+ {
365590
+ ((f2) => Promise.resolve().then(() => f2()))(async () => {
365591
+ {
365592
+ let job = first2;
365593
+ while (job != null) {
365594
+ try {
365595
+ {
365596
+ if (job.session.status !== "stopped") {
365597
+ await (job.go() ?? null);
365598
+ }
365599
+ }
365600
+ } catch (e) {
365601
+ {
365602
+ }
365603
+ }
365604
+ job = takeNext() ?? null;
365605
+ if (job == null) {
365606
+ active3 = Math.max(0, active3 - 1) ?? null;
365607
+ if (waiting3.length > 0 && active3 < maxConcurrent) {
365608
+ active3 = active3 + 1;
365609
+ job = takeNext() ?? null;
365610
+ if (job == null) {
365611
+ active3 = Math.max(0, active3 - 1) ?? null;
365612
+ }
365613
+ }
365614
+ }
365615
+ }
365616
+ }
365617
+ }) ?? null;
365077
365618
  }
365078
- persist(s) {
365079
- this.changed();
365080
- if (!this.host.store)
365619
+ };
365620
+ let startBackground = (session3, go) => {
365621
+ {
365622
+ if (active3 < maxConcurrent) {
365623
+ active3 = active3 + 1;
365624
+ runSlot({ session: session3, go }) ?? null;
365081
365625
  return;
365082
- const p2 = this.host.store.save(s).catch(() => {
365083
- });
365084
- this.pendingSaves.add(p2);
365085
- void p2.finally(() => this.pendingSaves.delete(p2));
365626
+ }
365627
+ session3.status = "queued";
365628
+ sessionEvent(session3) ?? null;
365629
+ changed() ?? null;
365630
+ waiting3.push({ session: session3, go }) ?? null;
365086
365631
  }
365087
365632
  };
365633
+ let stop2 = (id3) => {
365634
+ {
365635
+ let s = sessions.get(id3) ?? null ?? null;
365636
+ if (s == null || s.status !== "running" && s.status !== "queued") {
365637
+ return false;
365638
+ }
365639
+ let control = controls.get(id3) ?? null ?? null;
365640
+ if (control != null) {
365641
+ control.stop() ?? null;
365642
+ }
365643
+ s.status = "stopped";
365644
+ s.endedAt = now2() ?? null;
365645
+ persist3(s) ?? null;
365646
+ return true;
365647
+ }
365648
+ };
365649
+ let load2 = async () => {
365650
+ {
365651
+ if (loaded2) {
365652
+ return;
365653
+ }
365654
+ loaded2 = true;
365655
+ if (host.store != null && ((__v) => __v == null ? "null" : typeof __v)(host.store) === "object") {
365656
+ let saved = await (host.store.load() ?? null);
365657
+ for (const s of Array.isArray(saved) ?? null ? saved : []) {
365658
+ if (s.status === "running" || s.status === "queued") {
365659
+ s.status = "stopped";
365660
+ if (((__v) => __v == null ? "null" : typeof __v)(s.endedAt) !== "number") {
365661
+ s.endedAt = now2() ?? null;
365662
+ }
365663
+ }
365664
+ sessions.set(s.id, s) ?? null;
365665
+ }
365666
+ }
365667
+ changed() ?? null;
365668
+ }
365669
+ };
365670
+ let get4 = (id3) => {
365671
+ {
365672
+ return sessions.get(id3) ?? null ?? null;
365673
+ }
365674
+ };
365675
+ return { load: load2, flush: async () => {
365676
+ {
365677
+ while (pendingSaves > 0) {
365678
+ await (delay2(WAIT_STEP_MS) ?? null);
365679
+ }
365680
+ }
365681
+ }, subscribe: (l) => {
365682
+ {
365683
+ listeners8.push(l) ?? null;
365684
+ return () => {
365685
+ {
365686
+ let i2 = listeners8.indexOf(l) ?? null;
365687
+ if (i2 >= 0) {
365688
+ listeners8.splice(i2, 1) ?? null;
365689
+ }
365690
+ }
365691
+ };
365692
+ }
365693
+ }, list: () => {
365694
+ {
365695
+ return (allSessions(sessions) ?? null).sort((a, b) => {
365696
+ {
365697
+ return a.startedAt - b.startedAt;
365698
+ }
365699
+ }) ?? null;
365700
+ }
365701
+ }, get: get4, wait: async (id3, opts) => {
365702
+ {
365703
+ let o = opts ?? {};
365704
+ let deadline = (now2() ?? null) + (((__v) => __v == null ? "null" : typeof __v)(o.timeoutMs) === "number" ? o.timeoutMs : 12e4);
365705
+ let signal = o.signal ?? null;
365706
+ while ((isBusy(get4(id3) ?? null) ?? null) && (now2() ?? null) < deadline && !(signal != null && signal.aborted === true)) {
365707
+ await (delay2(Math.min(WAIT_STEP_MS, Math.max(1, deadline - (now2() ?? null)) ?? null) ?? null) ?? null);
365708
+ }
365709
+ return get4(id3) ?? null;
365710
+ }
365711
+ }, dismissFinished: (id3) => {
365712
+ {
365713
+ let prefix = "Agent " + id3 + " (";
365714
+ let i2 = parentQueue.length - 1;
365715
+ while (i2 >= 0) {
365716
+ if ((parentQueue[i2] ?? null).startsWith(prefix) ?? null) {
365717
+ parentQueue.splice(i2, 1) ?? null;
365718
+ }
365719
+ i2 = i2 - 1;
365720
+ }
365721
+ }
365722
+ }, drainParentNotifications: () => {
365723
+ {
365724
+ return parentQueue.splice(0, parentQueue.length) ?? null;
365725
+ }
365726
+ }, hasPendingNotifications: () => {
365727
+ {
365728
+ return parentQueue.length > 0;
365729
+ }
365730
+ }, spawn: async (req) => {
365731
+ {
365732
+ let profile = profileById(req.profileId) ?? null;
365733
+ if (profile == null) {
365734
+ let ids2 = ((host.profiles() ?? null).map((p2) => {
365735
+ {
365736
+ return p2.id;
365737
+ }
365738
+ }) ?? null).join(", ") ?? null;
365739
+ return { kind: "refused", reason: 'No agent type "' + req.profileId + '". Available: ' + ids2 + "." };
365740
+ }
365741
+ let prompt2 = ((__v) => __v == null ? "null" : typeof __v)(req.prompt) === "string" ? req.prompt.trim() ?? null : "";
365742
+ if (prompt2 === "") {
365743
+ return { kind: "refused", reason: "A task needs a self-contained prompt \u2014 the agent cannot see this conversation." };
365744
+ }
365745
+ let background = ((__v) => __v == null ? "null" : typeof __v)(req.background) === "boolean" ? req.background : profile.background === true;
365746
+ let id3 = ((__v) => __v == null ? "null" : typeof __v)(host.newId) === "function" ? host.newId() ?? null : "agent-" + ((now2() ?? null).toString(36) ?? null) + "-" + (((Math.random() ?? null).toString(36) ?? null).slice(2, 7) ?? null);
365747
+ let session3 = { id: id3, profile: profile.id, description: ((__v) => __v == null ? "null" : typeof __v)(req.description) === "string" && req.description !== "" ? req.description : prompt2.slice(0, 80) ?? null, status: "running", background, transcript: [], inbox: [], startedAt: now2() ?? null, rounds: 0, readOnly: req.readOnly === true || profile.readOnly === true };
365748
+ if (((__v) => __v == null ? "null" : typeof __v)(req.parentCallId) === "string" && req.parentCallId !== "") {
365749
+ session3.parentCallId = req.parentCallId;
365750
+ }
365751
+ sessions.set(session3.id, session3) ?? null;
365752
+ changed() ?? null;
365753
+ sessionEvent(session3) ?? null;
365754
+ let forceReadOnly = req.readOnly === true;
365755
+ let parentSignal = req.signal ?? null;
365756
+ if (background) {
365757
+ startBackground(session3, async () => {
365758
+ {
365759
+ return await (run4(session3, profile, prompt2, forceReadOnly, parentSignal, true) ?? null);
365760
+ }
365761
+ }) ?? null;
365762
+ return { kind: "started", id: session3.id };
365763
+ }
365764
+ let out = await (run4(session3, profile, prompt2, forceReadOnly, parentSignal, true) ?? null);
365765
+ return { kind: "done", id: session3.id, ok: out.ok, summary: out.summary, rounds: out.rounds };
365766
+ }
365767
+ }, message: async (id3, text, opts) => {
365768
+ {
365769
+ await (load2() ?? null);
365770
+ let o = opts ?? {};
365771
+ let session3 = sessions.get(id3) ?? null ?? null;
365772
+ if (session3 == null) {
365773
+ return { kind: "unknown", id: id3 };
365774
+ }
365775
+ if (session3.status === "running" || session3.status === "queued") {
365776
+ session3.inbox.push(text) ?? null;
365777
+ persist3(session3) ?? null;
365778
+ return { kind: "queued", id: id3 };
365779
+ }
365780
+ let profile = profileById(session3.profile) ?? null;
365781
+ if (profile == null) {
365782
+ return { kind: "unknown", id: id3 };
365783
+ }
365784
+ let wait2 = o.wait === true;
365785
+ let parentSignal = o.signal ?? null;
365786
+ session3.status = "running";
365787
+ session3.endedAt = null;
365788
+ session3.background = !wait2;
365789
+ changed() ?? null;
365790
+ if (!wait2) {
365791
+ startBackground(session3, async () => {
365792
+ {
365793
+ return await (run4(session3, profile, text, false, parentSignal, false) ?? null);
365794
+ }
365795
+ }) ?? null;
365796
+ return { kind: "resumed", id: id3 };
365797
+ }
365798
+ let out = await (run4(session3, profile, text, false, parentSignal, false) ?? null);
365799
+ return { kind: "done", id: id3, ok: out.ok, summary: out.summary };
365800
+ }
365801
+ }, stop: stop2, stopAll: () => {
365802
+ {
365803
+ for (const s of allSessions(sessions) ?? null) {
365804
+ stop2(s.id) ?? null;
365805
+ }
365806
+ parentQueue.splice(0, parentQueue.length) ?? null;
365807
+ }
365808
+ }, report: report2 };
365809
+ }
365810
+ }
365811
+ var delay2, REPORT_TOOL, REPORT_SPEC, WAIT_STEP_MS;
365812
+ var init_runtime5 = __esm({
365813
+ "node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/runtime.js"() {
365814
+ init_loop();
365815
+ delay2 = ((ms2) => new Promise((settle4) => setTimeout(() => settle4(null), Math.max(0, Number(ms2) || 0))));
365816
+ REPORT_TOOL = "report_to_parent";
365817
+ REPORT_SPEC = { readOnly: true, acts: false, spec: { type: "function", function: { name: REPORT_TOOL, description: "Send the main agent a progress update, or a question (set question) when you need a decision you cannot make yourself. It arrives between its steps and it answers with a message you read at your next step \u2014 keep working on what you can meanwhile. Your final answer still goes back by itself when you finish.", parameters: { type: "object", properties: { message: { type: "string", description: "What to tell the main agent." }, question: { type: "boolean", description: "This needs an answer." } }, required: ["message"] } } } };
365818
+ WAIT_STEP_MS = 25;
365819
+ }
365820
+ });
365821
+
365822
+ // node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/types.js
365823
+ var init_types9 = __esm({
365824
+ "node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/types.js"() {
365088
365825
  }
365089
365826
  });
365090
365827
 
365091
- // node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/orchestration.js
365828
+ // node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/orchestration.js
365092
365829
  var init_orchestration = __esm({
365093
- "node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/orchestration.js"() {
365830
+ "node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/orchestration.js"() {
365094
365831
  }
365095
365832
  });
365096
365833
 
365097
- // node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/profiles.js
365834
+ // node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/profiles.js
365098
365835
  var ORCHESTRATOR_GUIDANCE;
365099
365836
  var init_profiles2 = __esm({
365100
- "node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/profiles.js"() {
365101
- ORCHESTRATOR_GUIDANCE = [
365102
- "You orchestrate agents. For anything beyond a small edit:",
365103
- "1. Plan: break the request into steps (a planner agent for big requests).",
365104
- "2. Do: hand independent steps to agents in parallel (builder for changes, explorer to find things); do small steps yourself.",
365105
- "3. Check: when the work is done, have a reviewer agent check it against the request.",
365106
- "4. Repeat: on FAIL, send the fixes to the agent that built it (send_message keeps its context) and review again \u2014 at most three rounds \u2014 then report honestly what is still wrong.",
365107
- "Steer running agents with send_message, stop ones going wrong with stop_agent, and answer their reports. Finish only when the work is done and checked."
365108
- ].join("\n");
365837
+ "node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/profiles.js"() {
365838
+ ORCHESTRATOR_GUIDANCE = ["You orchestrate agents. For anything beyond a small edit:", "1. Plan: break the request into steps (a planner agent for big requests).", "2. Do: hand independent steps to agents in parallel (builder for changes, explorer to find things); do small steps yourself.", "3. Check: when the work is done, have a reviewer agent check it against the request.", "4. Repeat: on FAIL, send the fixes to the agent that built it (send_message keeps its context) and review again \u2014 at most three rounds \u2014 then report honestly what is still wrong.", "Steer running agents with send_message, stop ones going wrong with stop_agent, and answer their reports. Finish only when the work is done and checked."].join("\n") ?? null;
365109
365839
  }
365110
365840
  });
365111
365841
 
365112
- // node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/supervisor.js
365842
+ // node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/supervisor.js
365113
365843
  var init_supervisor = __esm({
365114
- "node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/supervisor.js"() {
365844
+ "node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/supervisor.js"() {
365115
365845
  }
365116
365846
  });
365117
365847
 
365118
- // node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/todos.js
365848
+ // node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/todos.js
365119
365849
  var init_todos = __esm({
365120
- "node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/todos.js"() {
365850
+ "node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/todos.js"() {
365121
365851
  }
365122
365852
  });
365123
365853
 
365124
- // node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/store.js
365854
+ // node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/store.js
365855
+ async function loadAll(kv, prefix) {
365856
+ {
365857
+ let out = [];
365858
+ for (const k2 of await (kv.keys(prefix) ?? null)) {
365859
+ let v = await (kv.get(k2) ?? null);
365860
+ if (v != null) {
365861
+ out.push(v) ?? null;
365862
+ }
365863
+ }
365864
+ return out;
365865
+ }
365866
+ }
365867
+ function sessionStore(kv, scope) {
365868
+ {
365869
+ let prefix = (scope ?? "default") + ":session:";
365870
+ return { load: async () => {
365871
+ {
365872
+ return await (loadAll(kv, prefix) ?? null);
365873
+ }
365874
+ }, save: async (s) => {
365875
+ {
365876
+ await (kv.set(prefix + s.id, s) ?? null);
365877
+ }
365878
+ }, remove: async (id3) => {
365879
+ {
365880
+ await ((kv["delete"] ?? null)(prefix + id3) ?? null);
365881
+ }
365882
+ } };
365883
+ }
365884
+ }
365885
+ var init_store = __esm({
365886
+ "node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/store.js"() {
365887
+ }
365888
+ });
365889
+
365890
+ // node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/run.js
365891
+ var init_run = __esm({
365892
+ "node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/run.js"() {
365893
+ }
365894
+ });
365895
+
365896
+ // node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/index.js
365897
+ var init_core3 = __esm({
365898
+ "node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/core/index.js"() {
365899
+ init_types9();
365900
+ init_loop();
365901
+ init_context2();
365902
+ init_runtime5();
365903
+ init_orchestration();
365904
+ init_profiles2();
365905
+ init_supervisor();
365906
+ init_todos();
365907
+ init_store();
365908
+ init_run();
365909
+ init_hypery_model();
365910
+ }
365911
+ });
365912
+
365913
+ // node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/indexeddb.js
365125
365914
  function indexedDbStore(name2 = "hypery-agents") {
365126
365915
  let db3 = null;
365127
365916
  const open4 = () => db3 ?? (db3 = new Promise((res, rej) => {
@@ -365141,7 +365930,8 @@ function indexedDbStore(name2 = "hypery-agents") {
365141
365930
  });
365142
365931
  };
365143
365932
  return {
365144
- get: async (k2) => await tx2("readonly", (s) => s.get(k2)),
365933
+ // A missing key reads as null, as the core's stores do.
365934
+ get: async (k2) => await tx2("readonly", (s) => s.get(k2)) ?? null,
365145
365935
  set: async (k2, v) => {
365146
365936
  await tx2("readwrite", (s) => s.put(structuredClone(v), k2));
365147
365937
  },
@@ -365151,232 +365941,32 @@ function indexedDbStore(name2 = "hypery-agents") {
365151
365941
  keys: async (prefix) => (await tx2("readonly", (s) => s.getAllKeys())).map(String).filter((k2) => k2.startsWith(prefix))
365152
365942
  };
365153
365943
  }
365154
- function sessionStore(kv, scope = "default") {
365155
- const prefix = `${scope}:session:`;
365156
- return {
365157
- load: async () => (await Promise.all((await kv.keys(prefix)).map((k2) => kv.get(k2)))).filter((s) => !!s),
365158
- save: (s) => kv.set(prefix + s.id, s),
365159
- remove: (id3) => kv.delete(prefix + id3)
365160
- };
365161
- }
365162
- var init_store = __esm({
365163
- "node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/store.js"() {
365944
+ var init_indexeddb2 = __esm({
365945
+ "node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/indexeddb.js"() {
365164
365946
  }
365165
365947
  });
365166
365948
 
365167
- // node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/run.js
365168
- var init_run = __esm({
365169
- "node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/run.js"() {
365170
- }
365171
- });
365172
-
365173
- // node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/hypery-model.js
365174
- function createHyperyModel(opts) {
365175
- const doFetch = opts.fetch ?? fetch;
365176
- return async (messages, tools, hooks, signal) => {
365177
- const token = await resolve2(opts.token);
365178
- if (!token)
365179
- throw new AgentModelError("Sign in to Hypery to use the agent.", "ai_reauth", 401);
365180
- const [model, team, paymentSource] = await Promise.all([resolve2(opts.model), resolve2(opts.team ?? null), resolve2(opts.paymentSource ?? null)]);
365181
- const body = JSON.stringify({
365182
- model,
365183
- messages,
365184
- stream: true,
365185
- max_tokens: opts.maxTokens ?? (tools.length ? 16384 : 4096),
365186
- ...opts.temperature !== void 0 ? { temperature: opts.temperature } : {},
365187
- ...tools.length ? { tools, tool_choice: "auto" } : {}
365188
- });
365189
- const limit = opts.maxRequestBytes ?? MAX_REQUEST_BYTES;
365190
- if (body.length > limit) {
365191
- throw new AgentModelError(`This message is too large to send (${(body.length / 1e6).toFixed(1)} MB with its images). Send fewer or smaller images.`, "too_large", 413);
365192
- }
365193
- const res = await doFetch(`${(opts.gatewayUrl ?? "https://hypery.ai").replace(/\/$/, "")}/api/v1/chat/completions`, {
365194
- method: "POST",
365195
- signal,
365196
- body,
365197
- headers: {
365198
- Authorization: `Bearer ${token}`,
365199
- "Content-Type": "application/json",
365200
- Accept: "text/event-stream",
365201
- ...team ? { [HYPERY_TEAM_HEADER2]: team } : {},
365202
- ...paymentSource ? { [HYPERY_PAYMENT_SOURCE_HEADER2]: paymentSource } : {}
365203
- }
365204
- }).catch((err2) => {
365205
- if (err2?.name === "AbortError")
365206
- throw err2;
365207
- throw new AgentModelError("Could not reach Hypery. Check your connection.", "network", 0);
365208
- });
365209
- if (!res.ok || !res.body) {
365210
- const text = await res.text().catch(() => "");
365211
- let payload = text;
365212
- try {
365213
- payload = JSON.parse(text);
365214
- } catch {
365215
- }
365216
- throw new AgentModelError(streamErrorMessage(payload, `The AI request failed (${res.status}).`), errorCodeFor(res.status, payload), res.status);
365217
- }
365218
- const acc = createStreamAccumulator();
365219
- const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
365220
- let idle2;
365221
- try {
365222
- await new Promise((done, fail3) => {
365223
- const arm = () => {
365224
- clearTimeout(idle2);
365225
- idle2 = setTimeout(() => fail3(new AgentModelError("The model stopped responding.", "ai_timeout", 504)), opts.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS);
365226
- };
365227
- arm();
365228
- const pump = async () => {
365229
- const { value: value3, done: finished2 } = await reader.read();
365230
- if (finished2)
365231
- return done();
365232
- arm();
365233
- for (const e of acc.push(value3)) {
365234
- if (e.textDelta)
365235
- hooks.onTextDelta?.(e.textDelta);
365236
- if (e.reasoningDelta)
365237
- hooks.onReasoningDelta?.(e.reasoningDelta);
365238
- if (e.toolProgress)
365239
- hooks.onToolProgress?.(e.toolProgress);
365240
- }
365241
- return pump();
365242
- };
365243
- pump().catch(fail3);
365244
- });
365245
- } finally {
365246
- clearTimeout(idle2);
365247
- reader.cancel().catch(() => {
365248
- });
365249
- }
365250
- const r = acc.result();
365251
- if (!r.sawDone && !r.text && !r.toolCalls.length)
365252
- throw new AgentModelError("The response was cut off before it started. Try again.", "ai_upstream", 502);
365253
- return { text: r.text, reasoning: r.reasoning, toolCalls: r.toolCalls };
365254
- };
365949
+ // node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/index.js
365950
+ function createHyperyModel2(opts) {
365951
+ return createHyperyModel({ ...opts, fetch: opts.fetch ?? ((url4, init) => fetch(url4, init)) });
365255
365952
  }
365256
- function errorCodeFor(status3, payload) {
365257
- const code = payload?.error?.code;
365258
- if (typeof code === "string")
365259
- return code;
365260
- if (status3 === 401)
365261
- return "ai_reauth";
365262
- if (status3 === 402)
365263
- return "ai_credits";
365264
- if (status3 === 403)
365265
- return "ai_scope";
365266
- if (status3 === 429)
365267
- return "ai_rate_limited";
365268
- return "ai_upstream";
365269
- }
365270
- function streamErrorMessage(payload, fallback2 = "The AI request failed.") {
365271
- const err2 = payload?.error;
365272
- if (typeof err2 === "string" && err2.trim())
365273
- return err2;
365274
- const message = err2?.message ?? payload?.message;
365275
- return typeof message === "string" && message.trim() ? message : fallback2;
365276
- }
365277
- function createStreamAccumulator() {
365278
- let buffer = "";
365279
- let text = "";
365280
- let reasoning = "";
365281
- let sawDone = false;
365282
- const calls = [];
365283
- return {
365284
- push(part) {
365285
- buffer += part;
365286
- const out = [];
365287
- let nl;
365288
- while ((nl = buffer.indexOf("\n")) >= 0) {
365289
- const line = buffer.slice(0, nl).trim();
365290
- buffer = buffer.slice(nl + 1);
365291
- if (!line.startsWith("data:"))
365292
- continue;
365293
- const data = line.slice(5).trim();
365294
- if (!data)
365295
- continue;
365296
- if (data === "[DONE]") {
365297
- sawDone = true;
365298
- continue;
365299
- }
365300
- let chunk3;
365301
- try {
365302
- chunk3 = JSON.parse(data);
365303
- } catch {
365304
- continue;
365305
- }
365306
- if (chunk3.error) {
365307
- const code = chunk3.error?.code;
365308
- throw new AgentModelError(streamErrorMessage(chunk3), typeof code === "string" ? code : "ai_upstream");
365309
- }
365310
- const delta = chunk3.choices?.[0]?.delta;
365311
- if (!delta)
365312
- continue;
365313
- if (typeof delta.content === "string" && delta.content) {
365314
- text += delta.content;
365315
- out.push({ textDelta: delta.content });
365316
- }
365317
- const r = typeof delta.reasoning === "string" ? delta.reasoning : typeof delta.reasoning_content === "string" ? delta.reasoning_content : "";
365318
- if (r) {
365319
- reasoning += r;
365320
- out.push({ reasoningDelta: r });
365321
- }
365322
- for (const tc of delta.tool_calls ?? []) {
365323
- const i2 = typeof tc.index === "number" ? tc.index : Math.max(0, calls.length - 1);
365324
- const call2 = calls[i2] ?? (calls[i2] = { name: "", arguments: "" });
365325
- if (tc.id)
365326
- call2.id = tc.id;
365327
- if (tc.function?.name)
365328
- call2.name += tc.function.name;
365329
- if (tc.function?.arguments) {
365330
- call2.arguments += tc.function.arguments;
365331
- out.push({ toolProgress: { index: i2, name: call2.name, bytes: call2.arguments.length, arguments: call2.arguments } });
365332
- }
365333
- }
365334
- }
365335
- return out;
365336
- },
365337
- result() {
365338
- return {
365339
- text,
365340
- reasoning,
365341
- sawDone,
365342
- toolCalls: calls.filter((c2) => c2 && c2.name).map((c2, i2) => ({ id: c2.id ?? `call_${i2}`, name: c2.name, arguments: c2.arguments }))
365343
- };
365344
- }
365345
- };
365953
+ function createAgentRuntime2(host) {
365954
+ return createAgentRuntime({
365955
+ ...host,
365956
+ createSignal: host.createSignal ?? (() => {
365957
+ const controller = new AbortController();
365958
+ return { signal: controller.signal, stop: () => controller.abort() };
365959
+ })
365960
+ // The core types a child's signal as anything with `aborted`; here every one comes from `createSignal`, whose
365961
+ // signals are AbortSignals — so the host's callbacks may rely on that.
365962
+ });
365346
365963
  }
365347
- var AgentModelError, MAX_REQUEST_BYTES, DEFAULT_IDLE_TIMEOUT_MS, HYPERY_TEAM_HEADER2, HYPERY_PAYMENT_SOURCE_HEADER2, resolve2;
365348
- var init_hypery_model = __esm({
365349
- "node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/hypery-model.js"() {
365350
- AgentModelError = class extends Error {
365351
- constructor(message, code = "ai_upstream", status3 = 502) {
365352
- super(message);
365353
- this.code = code;
365354
- this.status = status3;
365355
- this.name = "AgentModelError";
365356
- }
365357
- };
365358
- MAX_REQUEST_BYTES = 44e5;
365359
- DEFAULT_IDLE_TIMEOUT_MS = 18e4;
365360
- HYPERY_TEAM_HEADER2 = "x-hypery-active-organization-id";
365361
- HYPERY_PAYMENT_SOURCE_HEADER2 = "x-hypery-payment-source";
365362
- resolve2 = async (v) => typeof v === "function" ? await v() : v;
365363
- }
365364
- });
365365
-
365366
- // node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/index.js
365367
365964
  var init_agents = __esm({
365368
- "node_modules/.pnpm/@hyperyai+sdk@1.6.0_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_7e5d1696c3869532d33b29d7658baea1/node_modules/@hyperyai/sdk/dist/agents/index.js"() {
365369
- init_types9();
365370
- init_loop();
365371
- init_context2();
365372
- init_runtime5();
365373
- init_orchestration();
365374
- init_profiles2();
365375
- init_supervisor();
365376
- init_todos();
365377
- init_store();
365378
- init_run();
365965
+ "node_modules/.pnpm/@hyperyai+sdk@2.0.1_@types+react-dom@19.3.0_@types+react@19.3.0__@types+react@19.3.0_re_9c6c02ef59997b8628e41c6dcc5668a2/node_modules/@hyperyai/sdk/dist/agents/index.js"() {
365379
365966
  init_hypery_model();
365967
+ init_runtime5();
365968
+ init_core3();
365969
+ init_indexeddb2();
365380
365970
  }
365381
365971
  });
365382
365972
 
@@ -365390,7 +365980,7 @@ var init_stream_parse = __esm({
365390
365980
 
365391
365981
  // lib/agent/gateway.ts
365392
365982
  async function streamChat(opts, handlers = {}, signal) {
365393
- const call2 = createHyperyModel({ ...session2, model: opts.model, maxTokens: opts.maxTokens, temperature: opts.temperature });
365983
+ const call2 = createHyperyModel2({ ...session2, model: opts.model, maxTokens: opts.maxTokens, temperature: opts.temperature });
365394
365984
  const turn = await call2(opts.messages, opts.tools ?? [], handlers, signal);
365395
365985
  return { text: turn.text, reasoning: turn.reasoning ?? "", toolCalls: turn.toolCalls };
365396
365986
  }
@@ -365411,11 +366001,11 @@ var init_gateway = __esm({
365411
366001
  paymentSource: async () => (await paymentSourceHeaders())[HYPERY_PAYMENT_SOURCE_HEADER] === "credits" ? "credits" : null,
365412
366002
  gatewayUrl: HYPERY_GATEWAY_URL
365413
366003
  };
365414
- agentModel = (model) => createHyperyModel({
366004
+ agentModel = (model) => createHyperyModel2({
365415
366005
  ...session2,
365416
366006
  model: () => {
365417
366007
  const id3 = model();
365418
- if (!id3) throw new AgentModelError("Pick a chat model for the agent first.", "no_model", 400);
366008
+ if (!id3) throw agentModelError("Pick a chat model for the agent first.", "no_model", 400);
365419
366009
  return id3;
365420
366010
  }
365421
366011
  });
@@ -365607,11 +366197,12 @@ function subagentHost(deps = {}) {
365607
366197
  }
365608
366198
  function recordStep(event) {
365609
366199
  if (event.type !== "tool-start" && event.type !== "tool-end") return;
366200
+ const name2 = event.name ?? "";
365610
366201
  const steps = [...activity.get(event.sessionId) ?? []];
365611
- if (event.type === "tool-start") steps.push({ name: event.name, status: "running" });
366202
+ if (event.type === "tool-start") steps.push({ name: name2, status: "running" });
365612
366203
  else {
365613
- const i2 = steps.findLastIndex((s) => s.name === event.name && s.status === "running");
365614
- const step3 = { name: event.name, status: event.ok ? "done" : "error", summary: event.summary };
366204
+ const i2 = steps.findLastIndex((s) => s.name === name2 && s.status === "running");
366205
+ const step3 = { name: name2, status: event.ok ? "done" : "error", summary: event.summary ?? void 0 };
365615
366206
  if (i2 >= 0) steps[i2] = step3;
365616
366207
  else steps.push(step3);
365617
366208
  }
@@ -365626,17 +366217,17 @@ function reportChildTool(runtime, event) {
365626
366217
  const jobId = session3.background ? session3.id : void 0;
365627
366218
  childToolListener({
365628
366219
  profile: session3.profile,
365629
- toolCallId: session3.parentCallId,
366220
+ toolCallId: session3.parentCallId ?? void 0,
365630
366221
  jobId,
365631
366222
  job: jobId,
365632
- name: event.name,
366223
+ name: event.name ?? "",
365633
366224
  status: event.type === "tool-start" ? "running" : event.ok ? "done" : "error",
365634
- summary: event.type === "tool-end" ? event.summary : void 0
366225
+ summary: event.type === "tool-end" ? event.summary ?? void 0 : void 0
365635
366226
  });
365636
366227
  }
365637
366228
  function agentRuntime() {
365638
366229
  if (!runtimeRef) {
365639
- runtimeRef = new AgentRuntime(subagentHost());
366230
+ runtimeRef = createAgentRuntime2(subagentHost());
365640
366231
  void runtimeRef.load();
365641
366232
  }
365642
366233
  return runtimeRef;
@@ -365709,7 +366300,7 @@ function subagentDelegate(deps = {}) {
365709
366300
  case "list":
365710
366301
  return {
365711
366302
  kind: "list",
365712
- agents: rt.list().map((s) => ({ id: s.id, profile: s.profile, description: s.description, status: s.status, summary: s.summary }))
366303
+ agents: rt.list().map((s) => ({ id: s.id, profile: s.profile, description: s.description, status: s.status, summary: s.summary ?? void 0 }))
365713
366304
  };
365714
366305
  }
365715
366306
  };
@@ -367182,6 +367773,11 @@ function validateManifest(raw) {
367182
367773
  contributes = { ...contributes, exporters };
367183
367774
  }
367184
367775
  }
367776
+ if (m.contributes !== void 0) {
367777
+ const c2 = m.contributes;
367778
+ if (c2.agentTools !== void 0) contributes = { ...contributes, agentTools: validateAgentTools(c2.agentTools) };
367779
+ }
367780
+ if (contributes?.agentTools?.length && !m.main) throw new PluginPackageError("manifest.main is required for a plugin with agent tools: the tools run in it");
367185
367781
  if (contributes?.panels?.length && !m.ui) throw new PluginPackageError("manifest.ui is required for a plugin with panels: the panel shows its UI");
367186
367782
  if (contributes?.importers?.length && !m.main) throw new PluginPackageError("manifest.main is required for a plugin with importers");
367187
367783
  if (contributes?.exporters?.length && !m.main) throw new PluginPackageError("manifest.main is required for a plugin with exporters");
@@ -367207,6 +367803,44 @@ function validateManifest(raw) {
367207
367803
  contributes
367208
367804
  };
367209
367805
  }
367806
+ function validateAgentTools(raw) {
367807
+ const L = AGENT_TOOL_LIMITS;
367808
+ if (!Array.isArray(raw)) throw new PluginPackageError("manifest.contributes.agentTools must be a list");
367809
+ if (raw.length > L.maxTools) throw new PluginPackageError(`manifest.contributes.agentTools may list at most ${L.maxTools} tools`);
367810
+ const seen = /* @__PURE__ */ new Set();
367811
+ return raw.map((entry, i2) => {
367812
+ const tt = entry;
367813
+ const at4 = `manifest.contributes.agentTools[${i2}]`;
367814
+ if (typeof tt?.name !== "string" || !AGENT_TOOL_NAME_RE.test(tt.name)) throw new PluginPackageError(`${at4}.name must start with a lowercase letter and use only lowercase letters, digits and "_" (at most 40)`);
367815
+ if (seen.has(tt.name)) throw new PluginPackageError(`${at4}.name "${tt.name}" is listed twice`);
367816
+ seen.add(tt.name);
367817
+ if (typeof tt.description !== "string" || !tt.description.trim()) throw new PluginPackageError(`${at4}.description must be a non-empty string`);
367818
+ if (tt.description.length > L.maxDescription) throw new PluginPackageError(`${at4}.description may be at most ${L.maxDescription} characters`);
367819
+ const params2 = tt.parameters ?? { type: "object", properties: {} };
367820
+ if (!params2 || typeof params2 !== "object" || Array.isArray(params2) || params2.type !== "object") {
367821
+ throw new PluginPackageError(`${at4}.parameters must be a JSON Schema with "type": "object"`);
367822
+ }
367823
+ let text;
367824
+ try {
367825
+ text = JSON.stringify(params2);
367826
+ } catch {
367827
+ throw new PluginPackageError(`${at4}.parameters must be plain JSON`);
367828
+ }
367829
+ if (new TextEncoder().encode(text).byteLength > L.maxSchemaBytes) throw new PluginPackageError(`${at4}.parameters may be at most ${L.maxSchemaBytes / 1024} KB as JSON`);
367830
+ try {
367831
+ external_exports.fromJSONSchema(JSON.parse(text));
367832
+ } catch (e) {
367833
+ throw new PluginPackageError(`${at4}.parameters is not a usable JSON Schema: ${e instanceof Error ? e.message : String(e)}`);
367834
+ }
367835
+ if (tt.readOnly !== void 0 && typeof tt.readOnly !== "boolean") throw new PluginPackageError(`${at4}.readOnly must be true or false`);
367836
+ return {
367837
+ name: tt.name,
367838
+ description: tt.description.trim(),
367839
+ parameters: JSON.parse(text),
367840
+ ...tt.readOnly === true && { readOnly: true }
367841
+ };
367842
+ });
367843
+ }
367210
367844
  function parseContributedTheme(manifest2, index2, text) {
367211
367845
  const entry = manifest2.contributes.themes[index2];
367212
367846
  let raw = text;
@@ -367316,12 +367950,14 @@ function parsePluginBundle(text) {
367316
367950
  return { manifest: manifest2, mainCode: manifest2.main ? raw.main : "", uiHtml: manifest2.ui ? raw.ui : void 0, themes };
367317
367951
  }
367318
367952
  function pluginContentKey(p2) {
367319
- return JSON.stringify({ main: p2.mainCode ?? "", ui: p2.uiHtml ?? null, themes: p2.themes ?? null });
367953
+ const tools = p2.manifest?.contributes?.agentTools ?? null;
367954
+ return JSON.stringify({ main: p2.mainCode ?? "", ui: p2.uiHtml ?? null, themes: p2.themes ?? null, ...tools ? { tools } : {} });
367320
367955
  }
367321
- var PluginPackageError, ID_RE2, VERSION_RE, MAX_VERSION_LENGTH, PANEL_ID_RE, MAX_PANELS, DATA_ICON_RE, ICON_PATH_RE, MAX_ICON_BYTES, EXTENSION_RE, ZIP_LIMITS;
367956
+ var PluginPackageError, ID_RE2, VERSION_RE, MAX_VERSION_LENGTH, PANEL_ID_RE, MAX_PANELS, DATA_ICON_RE, ICON_PATH_RE, MAX_ICON_BYTES, EXTENSION_RE, AGENT_TOOL_LIMITS, AGENT_TOOL_NAME_RE, ZIP_LIMITS;
367322
367957
  var init_package2 = __esm({
367323
367958
  "lib/plugins/package.ts"() {
367324
367959
  init_esm2();
367960
+ init_zod();
367325
367961
  init_schema();
367326
367962
  init_listing();
367327
367963
  init_types11();
@@ -367336,6 +367972,8 @@ var init_package2 = __esm({
367336
367972
  ICON_PATH_RE = /^(\.\/)?[\w./-]+\.(svg|png|webp)$/i;
367337
367973
  MAX_ICON_BYTES = 64 * 1024;
367338
367974
  EXTENSION_RE = /^\.[a-z0-9]{1,15}$/i;
367975
+ AGENT_TOOL_LIMITS = { maxTools: 16, maxDescription: 1024, maxSchemaBytes: 8 * 1024 };
367976
+ AGENT_TOOL_NAME_RE = /^[a-z][a-z0-9_]{0,39}$/;
367339
367977
  ZIP_LIMITS = { maxEntries: 500, maxEntryBytes: 10 * 1024 * 1024, maxTotalBytes: 25 * 1024 * 1024 };
367340
367978
  }
367341
367979
  });
@@ -367414,6 +368052,195 @@ var init_panels = __esm({
367414
368052
  }
367415
368053
  });
367416
368054
 
368055
+ // lib/plugins/agent-tools.ts
368056
+ function setPluginToolBridge(next2) {
368057
+ bridge2 = next2;
368058
+ }
368059
+ function hash6(s) {
368060
+ let h = 2166136261;
368061
+ for (let i2 = 0; i2 < s.length; i2++) h = Math.imul(h ^ s.charCodeAt(i2), 16777619);
368062
+ return (h >>> 0).toString(36).padStart(6, "0").slice(-6);
368063
+ }
368064
+ function pluginToolName(pluginId, tool2) {
368065
+ const slug4 = pluginId.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
368066
+ const room = MAX_TOOL_NAME - NAME_PREFIX.length - 2 - tool2.length;
368067
+ const fitted = slug4.length <= room ? slug4 : `${slug4.slice(0, Math.max(1, room - 7))}_${hash6(pluginId)}`;
368068
+ return `${NAME_PREFIX}${fitted}__${tool2}`;
368069
+ }
368070
+ function pluginToolIsReadOnly(plugin, tool2) {
368071
+ return tool2.readOnly === true && !(plugin.granted ?? plugin.manifest.permissions).includes("write");
368072
+ }
368073
+ function toolResultFromReply(plugin, tool2, reply) {
368074
+ const images = (reply.images ?? []).filter(isImageDataUrl2).slice(0, MAX_RESULT_IMAGES);
368075
+ const data = reply.text !== void 0 ? { text: String(reply.text), ...reply.data !== void 0 ? { data: reply.data } : {} } : reply.data;
368076
+ const size6 = new TextEncoder().encode(JSON.stringify(data ?? null)).byteLength + images.reduce((n, s) => n + s.length, 0);
368077
+ if (size6 > PLUGIN_TOOL_MAX_RESULT_BYTES) throw new ToolError(`${plugin.manifest.name}: the result of ${tool2} is too large (${Math.round(size6 / 1024)} KB)`, "failed");
368078
+ const summary = typeof reply.summary === "string" && reply.summary.trim() ? reply.summary.trim().slice(0, 200) : `${plugin.manifest.name}: ${tool2}`;
368079
+ return { summary, ...data !== void 0 ? { data } : {}, ...images.length ? { images } : {} };
368080
+ }
368081
+ function pluginToolCommand(plugin, tool2) {
368082
+ const name2 = pluginToolName(plugin.manifest.id, tool2.name);
368083
+ const readOnly = pluginToolIsReadOnly(plugin, tool2);
368084
+ return defineCommand({
368085
+ id: pluginToolCommandId(plugin.manifest.id, tool2.name),
368086
+ title: `${plugin.manifest.name}: ${tool2.name}`,
368087
+ domain: "plugin",
368088
+ params: external_exports.fromJSONSchema(tool2.parameters),
368089
+ effect: readOnly ? "none" : "document",
368090
+ // The gate is the plugin's own: every call it makes back into the file is checked against its grant by the
368091
+ // plugin surface. The tool itself is consent the user already gave when they granted the plugin.
368092
+ permission: null,
368093
+ expose: { agent: { name: name2, description: `[${plugin.manifest.name} plugin] ${tool2.description}`, readOnly } },
368094
+ run: async (args2, ctx2) => {
368095
+ if (!bridge2) throw new ToolError(`${plugin.manifest.name} cannot run here: plugins need the editor.`, "unsupported");
368096
+ const historyGroup = `plugin-tool:${plugin.manifest.id}:${ctx2.callId ?? ++callSeq}`;
368097
+ const reply = await bridge2.call(plugin, tool2.name, args2, { signal: ctx2.signal, historyGroup });
368098
+ return toolResultFromReply(plugin, name2, reply);
368099
+ }
368100
+ });
368101
+ }
368102
+ function syncPluginAgentTools(installed3) {
368103
+ const want = /* @__PURE__ */ new Map();
368104
+ const nextSources = /* @__PURE__ */ new Map();
368105
+ for (const plugin of installed3) {
368106
+ if (!pluginToolsActive(plugin)) continue;
368107
+ for (const tool2 of plugin.manifest.contributes.agentTools) {
368108
+ try {
368109
+ const command = pluginToolCommand(plugin, tool2);
368110
+ want.set(command.id, command);
368111
+ nextSources.set(command.expose.agent.name, { pluginId: plugin.manifest.id, pluginName: plugin.manifest.name, tool: tool2.name });
368112
+ } catch (err2) {
368113
+ console.warn(`[plugins] ${plugin.manifest.id}: agent tool ${tool2.name} was not registered`, err2);
368114
+ }
368115
+ }
368116
+ }
368117
+ const stale = listCommands().filter((c2) => c2.id.startsWith(COMMAND_PREFIX) && !want.has(c2.id)).map((c2) => c2.id);
368118
+ unregisterCommand(...stale);
368119
+ const names = [];
368120
+ for (const command of want.values()) {
368121
+ try {
368122
+ registerCommand(command);
368123
+ names.push(command.expose.agent.name);
368124
+ } catch (err2) {
368125
+ nextSources.delete(command.expose.agent.name);
368126
+ console.warn(`[plugins] ${command.id} was not registered`, err2);
368127
+ }
368128
+ }
368129
+ sources2.clear();
368130
+ for (const [k2, v] of nextSources) if (names.includes(k2)) sources2.set(k2, v);
368131
+ return names;
368132
+ }
368133
+ function createToolChannel(send, label3) {
368134
+ const pending8 = /* @__PURE__ */ new Map();
368135
+ let seq4 = 0;
368136
+ return {
368137
+ call(tool2, args2, options = {}) {
368138
+ if (options.signal?.aborted) return Promise.reject(new ToolError(`${label3}: ${tool2} was stopped`, "failed"));
368139
+ const callId = `t${++seq4}`;
368140
+ return new Promise((resolve7, reject) => {
368141
+ const done = () => {
368142
+ pending8.delete(callId);
368143
+ clearTimeout(timer);
368144
+ options.signal?.removeEventListener("abort", onAbort);
368145
+ };
368146
+ const onAbort = () => {
368147
+ done();
368148
+ send("agenttoolcancel", { callId });
368149
+ reject(new ToolError(`${label3}: ${tool2} was stopped`, "failed"));
368150
+ };
368151
+ const ms2 = options.timeoutMs ?? PLUGIN_TOOL_TIMEOUT_MS;
368152
+ const timer = setTimeout(() => {
368153
+ done();
368154
+ send("agenttoolcancel", { callId });
368155
+ reject(new ToolError(`${label3}: ${tool2} did not answer within ${Math.round(ms2 / 1e3)} s`, "failed"));
368156
+ }, ms2);
368157
+ options.signal?.addEventListener("abort", onAbort, { once: true });
368158
+ pending8.set(callId, {
368159
+ resolve: (r) => {
368160
+ done();
368161
+ resolve7(r);
368162
+ },
368163
+ reject: (e) => {
368164
+ done();
368165
+ reject(e);
368166
+ }
368167
+ });
368168
+ send("agenttool", { callId, tool: tool2, args: args2 });
368169
+ });
368170
+ },
368171
+ receive(message) {
368172
+ const p2 = pending8.get(message.callId);
368173
+ if (!p2) return;
368174
+ if (typeof message.error === "string") p2.reject(new ToolError(`${label3}: ${message.error}`, "failed"));
368175
+ else p2.resolve(message.result && typeof message.result === "object" ? message.result : {});
368176
+ },
368177
+ /** The session closed: every outstanding call fails. */
368178
+ close(reason) {
368179
+ for (const p2 of [...pending8.values()]) p2.reject(new ToolError(`${label3}: ${reason}`, "failed"));
368180
+ pending8.clear();
368181
+ },
368182
+ get size() {
368183
+ return pending8.size;
368184
+ }
368185
+ };
368186
+ }
368187
+ function withAgentToolsShim(html) {
368188
+ return html.replace("</head>", () => `<script>${AGENT_TOOLS_SHIM}</script></head>`);
368189
+ }
368190
+ var PLUGIN_TOOL_TIMEOUT_MS, PLUGIN_TOOL_MAX_RESULT_BYTES, MAX_RESULT_IMAGES, COMMAND_PREFIX, NAME_PREFIX, MAX_TOOL_NAME, bridge2, pluginToolCommandId, sources2, isImageDataUrl2, callSeq, pluginToolsActive, AGENT_TOOLS_SHIM;
368191
+ var init_agent_tools = __esm({
368192
+ "lib/plugins/agent-tools.ts"() {
368193
+ "use strict";
368194
+ init_zod();
368195
+ init_types5();
368196
+ init_registry();
368197
+ init_errors();
368198
+ PLUGIN_TOOL_TIMEOUT_MS = 6e4;
368199
+ PLUGIN_TOOL_MAX_RESULT_BYTES = 256 * 1024;
368200
+ MAX_RESULT_IMAGES = 8;
368201
+ COMMAND_PREFIX = "pluginTool.";
368202
+ NAME_PREFIX = "plugin_";
368203
+ MAX_TOOL_NAME = 64;
368204
+ bridge2 = null;
368205
+ pluginToolCommandId = (pluginId, tool2) => `${COMMAND_PREFIX}${pluginId}.${tool2}`;
368206
+ sources2 = /* @__PURE__ */ new Map();
368207
+ isImageDataUrl2 = (v) => typeof v === "string" && /^data:image\/(png|jpe?g|webp|gif);base64,/i.test(v);
368208
+ callSeq = 0;
368209
+ pluginToolsActive = (p2) => p2.enabled && p2.granted !== null && !!p2.manifest.main && !!p2.manifest.contributes?.agentTools?.length;
368210
+ AGENT_TOOLS_SHIM = `(function () {
368211
+ var rpc = window.__popcraftRpc, api = window.popcraft;
368212
+ if (!rpc || !api || api.agent) return;
368213
+ var handlers = {}, queue = [], controllers = {};
368214
+ function run(e) {
368215
+ var ac = typeof AbortController === 'function' ? new AbortController() : null;
368216
+ if (ac) controllers[e.callId] = ac;
368217
+ Promise.resolve().then(function () {
368218
+ var h = handlers[e.tool];
368219
+ if (typeof h !== 'function') throw new Error('No handler for tool "' + e.tool + '"');
368220
+ return h(e.args || {}, { callId: e.callId, tool: e.tool, signal: ac ? ac.signal : undefined });
368221
+ }).then(function (r) {
368222
+ var out = r && r.$popcraftToolResult ? { summary: r.summary, data: r.data, text: r.text, images: r.images } : { data: r };
368223
+ rpc.send({ kind: 'toolResult', callId: e.callId, result: JSON.parse(JSON.stringify(out)) });
368224
+ }, function (err) {
368225
+ rpc.send({ kind: 'toolResult', callId: e.callId, error: String((err && err.message) || err) });
368226
+ }).then(function () { delete controllers[e.callId]; });
368227
+ }
368228
+ rpc.on('agenttool', function (e) { if (handlers[e.tool]) run(e); else queue.push(e); });
368229
+ rpc.on('agenttoolcancel', function (e) { var ac = controllers[e.callId]; if (ac) ac.abort(); });
368230
+ api.agent = {
368231
+ onTool: function (name, handler) {
368232
+ if (typeof name !== 'string' || typeof handler !== 'function') throw new Error('popcraft.agent.onTool needs a tool name and a handler');
368233
+ handlers[name] = handler;
368234
+ var rest = [];
368235
+ queue.splice(0).forEach(function (e) { if (e.tool === name) run(e); else rest.push(e); });
368236
+ queue.push.apply(queue, rest);
368237
+ },
368238
+ result: function (r) { var o = Object.assign({}, r || {}); o.$popcraftToolResult = true; return o; }
368239
+ };
368240
+ })();`;
368241
+ }
368242
+ });
368243
+
367417
368244
  // lib/print/print-prefs.ts
367418
368245
  var print_prefs_exports = {};
367419
368246
  __export(print_prefs_exports, {
@@ -384264,9 +385091,9 @@ fn fs_main(in : VertexOutput) -> @location(0) vec4<f32> {
384264
385091
  return;
384265
385092
  }
384266
385093
  if (reason instanceof RenderingCancelledException) {
384267
- let delay = RENDERING_CANCELLED_TIMEOUT;
385094
+ let delay3 = RENDERING_CANCELLED_TIMEOUT;
384268
385095
  if (reason.extraDelay > 0 && reason.extraDelay < 1e3) {
384269
- delay += reason.extraDelay;
385096
+ delay3 += reason.extraDelay;
384270
385097
  }
384271
385098
  intentState.streamReaderCancelTimeout = setTimeout(() => {
384272
385099
  intentState.streamReaderCancelTimeout = null;
@@ -384275,7 +385102,7 @@ fn fs_main(in : VertexOutput) -> @location(0) vec4<f32> {
384275
385102
  reason,
384276
385103
  force: true
384277
385104
  });
384278
- }, delay);
385105
+ }, delay3);
384279
385106
  return;
384280
385107
  }
384281
385108
  }
@@ -396847,6 +397674,7 @@ async function refreshInstalledPlugins() {
396847
397674
  syncPluginTabs(installed3);
396848
397675
  usePluginStore.getState().setInstalled(installed3);
396849
397676
  syncPluginThemes(installed3);
397677
+ syncPluginAgentTools(installed3);
396850
397678
  }
396851
397679
  function syncPluginThemes(installed3) {
396852
397680
  const themes = useThemeStore.getState();
@@ -396901,7 +397729,7 @@ async function runPlugin(pluginId, commandId, opts = {}) {
396901
397729
  iframe.setAttribute("aria-hidden", "true");
396902
397730
  iframe.style.display = "none";
396903
397731
  iframe.dataset.popcraftPlugin = pluginId;
396904
- iframe.srcdoc = withWasmEvalCsp(buildMainDocument(plugin.mainCode, granted.includes("network")));
397732
+ iframe.srcdoc = withAgentToolsShim(withWasmEvalCsp(buildMainDocument(plugin.mainCode, granted.includes("network"))));
396905
397733
  const channel3 = new MessageChannel();
396906
397734
  const session3 = {
396907
397735
  sessionId,
@@ -396916,7 +397744,11 @@ async function runPlugin(pluginId, commandId, opts = {}) {
396916
397744
  idleTimer: null,
396917
397745
  importMode: opts.importMode ?? null,
396918
397746
  importFile: opts.importFile ?? null,
396919
- exportRequest: opts.exportRequest ?? null
397747
+ exportRequest: opts.exportRequest ?? null,
397748
+ env: null,
397749
+ tools: createToolChannel((event, data) => {
397750
+ if (running3.has(sessionId)) channel3.port1.postMessage({ kind: "event", event, data });
397751
+ }, plugin.manifest.name)
396920
397752
  };
396921
397753
  running3.set(sessionId, session3);
396922
397754
  const dockTitle = opts.dock ? plugin.manifest.contributes?.panels?.find((p2) => opts.dock.endsWith(`:${p2.id}`))?.title : void 0;
@@ -396997,6 +397829,7 @@ async function runPlugin(pluginId, commandId, opts = {}) {
396997
397829
  }
396998
397830
  }
396999
397831
  };
397832
+ session3.env = env;
397000
397833
  channel3.port1.onmessage = async (ev) => {
397001
397834
  const m = ev.data;
397002
397835
  if (!running3.has(sessionId)) return;
@@ -397010,6 +397843,8 @@ async function runPlugin(pluginId, commandId, opts = {}) {
397010
397843
  } else if (m.kind === "toUI") {
397011
397844
  if (session3.uiPort) session3.uiPort.postMessage({ kind: "event", event: "message", data: m.data });
397012
397845
  else if (session3.pendingToUI.length < 500) session3.pendingToUI.push(m.data);
397846
+ } else if (m.kind === "toolResult") {
397847
+ session3.tools.receive(m);
397013
397848
  } else if (m.kind === "error") {
397014
397849
  usePluginStore.getState().toast(`${plugin.manifest.name}: ${m.message}`, { error: true, source: plugin.manifest.name });
397015
397850
  }
@@ -397065,6 +397900,43 @@ function pluginUIDocument(sessionId) {
397065
397900
  if (!s?.plugin.uiHtml) return null;
397066
397901
  return withPluginTheme(withWasmEvalCsp(buildUIDocument(s.plugin.uiHtml, s.granted.includes("network"))));
397067
397902
  }
397903
+ async function ensureBackgroundSession(pluginId, command) {
397904
+ let session3 = runningSessionFor(pluginId);
397905
+ if (!session3) {
397906
+ await runPlugin(pluginId, command, { background: true });
397907
+ session3 = runningSessionFor(pluginId);
397908
+ if (!session3) return void 0;
397909
+ }
397910
+ if (session3.background) {
397911
+ if (session3.idleTimer) clearTimeout(session3.idleTimer);
397912
+ const id3 = session3.sessionId;
397913
+ const idle2 = () => {
397914
+ const s = running3.get(id3);
397915
+ if (!s) return;
397916
+ if (s.tools.size) {
397917
+ s.idleTimer = setTimeout(idle2, 6e4);
397918
+ return;
397919
+ }
397920
+ if (!usePluginStore.getState().sessions.find((x2) => x2.sessionId === id3)?.ui) closeSession(id3);
397921
+ };
397922
+ session3.idleTimer = setTimeout(idle2, 6e4);
397923
+ }
397924
+ return session3;
397925
+ }
397926
+ async function callPluginTool(plugin, tool2, args2, options) {
397927
+ const id3 = plugin.manifest.id;
397928
+ const current4 = await getPlugin(id3);
397929
+ if (!current4?.enabled || current4.granted === null) throw new Error(`${plugin.manifest.name} is disabled or has not been allowed to run`);
397930
+ const session3 = await ensureBackgroundSession(id3, "agent");
397931
+ if (!session3?.env) throw new Error(`${plugin.manifest.name} could not start`);
397932
+ const env = session3.env;
397933
+ env.historyGroup = options.historyGroup;
397934
+ try {
397935
+ return await session3.tools.call(tool2, args2, options);
397936
+ } finally {
397937
+ if (env.historyGroup === options.historyGroup) env.historyGroup = null;
397938
+ }
397939
+ }
397068
397940
  async function dispatchWidgetClick(nodeId2, handler) {
397069
397941
  const store6 = usePluginStore.getState();
397070
397942
  const node2 = useEditorStore.getState().document.nodes[nodeId2];
@@ -397074,31 +397946,20 @@ async function dispatchWidgetClick(nodeId2, handler) {
397074
397946
  store6.toast(t2("host.youCanViewThisFile"));
397075
397947
  return;
397076
397948
  }
397077
- let session3 = [...running3.values()].find((s) => s.plugin.manifest.id === node2.pluginId);
397078
- if (!session3) {
397079
- const plugin = await getPlugin(node2.pluginId);
397080
- if (!plugin) {
397081
- store6.toast(t2("host.installFromThePluginMarketplace", { pluginName: node2.pluginName }));
397082
- return;
397083
- }
397084
- await runPlugin(node2.pluginId, "widget", { background: true });
397085
- session3 = [...running3.values()].find((s) => s.plugin.manifest.id === node2.pluginId);
397086
- if (!session3) return;
397087
- }
397088
- if (session3.background) {
397089
- if (session3.idleTimer) clearTimeout(session3.idleTimer);
397090
- const id3 = session3.sessionId;
397091
- session3.idleTimer = setTimeout(() => {
397092
- const s = running3.get(id3);
397093
- if (s && !usePluginStore.getState().sessions.find((x2) => x2.sessionId === id3)?.ui) closeSession(id3);
397094
- }, 6e4);
397949
+ const plugin = await getPlugin(node2.pluginId);
397950
+ if (!plugin) {
397951
+ store6.toast(t2("host.installFromThePluginMarketplace", { pluginName: node2.pluginName }));
397952
+ return;
397095
397953
  }
397954
+ const session3 = await ensureBackgroundSession(node2.pluginId, "widget");
397955
+ if (!session3) return;
397096
397956
  post(session3, "widgetclick", { nodeId: nodeId2, handler, state: node2.widgetState ?? {} });
397097
397957
  }
397098
397958
  function closeSession(sessionId) {
397099
397959
  const s = running3.get(sessionId);
397100
397960
  if (!s) return;
397101
397961
  running3.delete(sessionId);
397962
+ s.tools.close("the plugin closed before it answered");
397102
397963
  if (s.idleTimer) clearTimeout(s.idleTimer);
397103
397964
  s.unsubscribers.forEach((u) => u());
397104
397965
  s.port.close();
@@ -397124,7 +397985,9 @@ var init_host3 = __esm({
397124
397985
  init_theme_store();
397125
397986
  init_panels();
397126
397987
  init_open_link();
397988
+ init_agent_tools();
397127
397989
  running3 = /* @__PURE__ */ new Map();
397990
+ setPluginToolBridge({ call: callPluginTool });
397128
397991
  if (typeof window !== "undefined" && false) {
397129
397992
  window.__vpPlugins = { installPluginPayload, runPlugin, dispatchWidgetClick, closeSession, removePlugin, setEnabled, running: running3 };
397130
397993
  }
@@ -397208,6 +398071,13 @@ function bytesToDataUrl(bytes2, format) {
397208
398071
  for (const byte2 of bytes2) binary += String.fromCharCode(byte2);
397209
398072
  return `data:${MIME2[format.toUpperCase()] ?? "application/octet-stream"};base64,${btoa(binary)}`;
397210
398073
  }
398074
+ function grouped2(env, seam) {
398075
+ const out = {};
398076
+ for (const [k2, v] of Object.entries(seam)) {
398077
+ out[k2] = typeof v === "function" ? (...args2) => withHistoryGroup(env.historyGroup, () => v(...args2)) : v;
398078
+ }
398079
+ return out;
398080
+ }
397211
398081
  function pluginContext(env) {
397212
398082
  const have = new Set(PLUGIN_CAPABILITIES);
397213
398083
  const capabilities = {
@@ -397233,7 +398103,7 @@ function pluginContext(env) {
397233
398103
  return {
397234
398104
  doc: () => st().document,
397235
398105
  commit: (next2, label3) => {
397236
- st().commitDocument(next2, label3 ?? env.manifest.name);
398106
+ withHistoryGroup(env.historyGroup, () => st().commitDocument(next2, label3 ?? env.manifest.name));
397237
398107
  },
397238
398108
  pageId: () => st().currentPageId,
397239
398109
  selection: () => [...st().selection],
@@ -397246,16 +398116,17 @@ function pluginContext(env) {
397246
398116
  actor: { kind: "plugin", id: env.manifest.id, label: env.manifest.name, host: env },
397247
398117
  can: (name2) => have.has(name2),
397248
398118
  use: (name2) => capabilities[name2],
397249
- pages: {
398119
+ pages: grouped2(env, {
397250
398120
  setCurrent: (id3) => st().setCurrentPage(id3),
397251
398121
  create: (name2) => {
397252
398122
  st().addPage(name2);
397253
398123
  return st().currentPageId;
397254
398124
  },
397255
398125
  rename: (id3, name2) => st().renamePage(id3, name2)
397256
- },
397257
- // Boolean ops, flatten, outline stroke, masks and the shape builder are store actions (they push their own undo step).
397258
- ops: storeOpsSeam(st)
398126
+ }),
398127
+ // Boolean ops, flatten, outline stroke, masks and the shape builder are store actions (they push their own undo
398128
+ // step), grouped like `commit` while an agent tool call is running.
398129
+ ops: grouped2(env, storeOpsSeam(st))
397259
398130
  };
397260
398131
  }
397261
398132
  function dispatchPluginCall(env, method, params2 = {}) {
@@ -397286,6 +398157,7 @@ var init_plugin = __esm({
397286
398157
  init_plugin_shim();
397287
398158
  init_plugin_widget();
397288
398159
  init_seams();
398160
+ init_history_group();
397289
398161
  PLUGIN_CAPABILITIES = ["render", "storage", "panel"];
397290
398162
  pluginCommandId = (method) => `plugin.${method}`;
397291
398163
  empty = external_exports.object({});
@@ -398919,11 +399791,11 @@ function upsertToolPart(parts, part) {
398919
399791
  next2[i2] = { ...next2[i2], ...part };
398920
399792
  return next2;
398921
399793
  }
398922
- var textOf2;
399794
+ var textOf3;
398923
399795
  var init_parts = __esm({
398924
399796
  "lib/agent/parts.ts"() {
398925
399797
  "use strict";
398926
- textOf2 = (m) => m.parts.filter((p2) => p2.type === "text").map((p2) => p2.text).join("");
399798
+ textOf3 = (m) => m.parts.filter((p2) => p2.type === "text").map((p2) => p2.text).join("");
398927
399799
  }
398928
399800
  });
398929
399801
 
@@ -399410,6 +400282,7 @@ function designRecorder() {
399410
400282
  var installed;
399411
400283
  var init_recorders = __esm({
399412
400284
  "lib/agent/design-script/recorders.ts"() {
400285
+ "use strict";
399413
400286
  installed = null;
399414
400287
  }
399415
400288
  });
@@ -399635,7 +400508,7 @@ function guardEdit(name2) {
399635
400508
  if (reason) throw new ToolError(`${name2} cannot run: ${reason}`);
399636
400509
  }
399637
400510
  function historyMessages() {
399638
- return activeMessages().slice(-MAX_HISTORY_MESSAGES).map((m) => ({ role: m.role, content: textOf2(m).trim() })).filter((m) => !!m.content);
400511
+ return activeMessages().slice(-MAX_HISTORY_MESSAGES).map((m) => ({ role: m.role, content: textOf3(m).trim() })).filter((m) => !!m.content);
399639
400512
  }
399640
400513
  function systemMessage(skillId, mentions = []) {
399641
400514
  const st = useEditorStore.getState();
@@ -403349,8 +404222,8 @@ var init_import2 = __esm({
403349
404222
  run: async (args2, ctx2) => {
403350
404223
  const ext = (args2.name.match(/\.[^.]+$/)?.[0] ?? "").toLowerCase();
403351
404224
  if (!EXTENSIONS2.includes(ext)) throw new ToolError(`import_file takes ${EXTENSIONS2.join(", ")} files, not "${args2.name}".`);
403352
- const sources2 = [args2.text, args2.base64, args2.url].filter((v) => v !== void 0).length;
403353
- if (sources2 !== 1) throw new ToolError("Pass exactly one of text, base64 or url.");
404225
+ const sources3 = [args2.text, args2.base64, args2.url].filter((v) => v !== void 0).length;
404226
+ if (sources3 !== 1) throw new ToolError("Pass exactly one of text, base64 or url.");
403354
404227
  let body;
403355
404228
  if (args2.text !== void 0) body = args2.text;
403356
404229
  else if (args2.base64 !== void 0) body = Uint8Array.from(atob(args2.base64), (c2) => c2.charCodeAt(0));
@@ -404035,8 +404908,8 @@ var init_presentation_audio = __esm({
404035
404908
  },
404036
404909
  run: async (args2, ctx2) => {
404037
404910
  const page = pageOf3(ctx2, args2.pageId);
404038
- const sources2 = [args2.mediaHash, args2.url, args2.bytes].filter((v) => v !== void 0).length;
404039
- if (sources2 !== 1) throw new ToolError("Pass exactly one of mediaHash, url or bytes.");
404911
+ const sources3 = [args2.mediaHash, args2.url, args2.bytes].filter((v) => v !== void 0).length;
404912
+ if (sources3 !== 1) throw new ToolError("Pass exactly one of mediaHash, url or bytes.");
404040
404913
  if (args2.role === "voice" && !args2.frameId) throw new ToolError("Name the slide (frameId) whose narration this is.");
404041
404914
  let base = ctx2.doc();
404042
404915
  if (!soundtrackOf(base, page)) base = doc(() => configure(base, page, {}));
@@ -411819,7 +412692,7 @@ init_resources();
411819
412692
  init_desktop();
411820
412693
  init_hypery();
411821
412694
  import { createInterface } from "node:readline";
411822
- var VERSION2 = "0.41.0";
412695
+ var VERSION2 = "0.42.0";
411823
412696
  var HELP = `popcraft ${VERSION2} \u2014 the PopCraft command line
411824
412697
 
411825
412698
  Files (headless, on .popcraft files):