slopcode 0.2.140 → 0.2.141

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bundle/index.js CHANGED
@@ -46,6 +46,39 @@ var __export = (target, all) => {
46
46
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
47
47
  var __promiseAll = (args2) => Promise.all(args2);
48
48
  var __require = import.meta.require;
49
+ var __using = (stack, value, async) => {
50
+ if (value != null) {
51
+ if (typeof value !== "object" && typeof value !== "function")
52
+ throw TypeError('Object expected to be assigned to "using" declaration');
53
+ let dispose;
54
+ if (async)
55
+ dispose = value[Symbol.asyncDispose];
56
+ if (dispose === undefined)
57
+ dispose = value[Symbol.dispose];
58
+ if (typeof dispose !== "function")
59
+ throw TypeError("Object not disposable");
60
+ stack.push([async, dispose, value]);
61
+ } else if (async) {
62
+ stack.push([async]);
63
+ }
64
+ return value;
65
+ };
66
+ var __callDispose = (stack, error, hasError) => {
67
+ let fail = (e) => error = hasError ? new SuppressedError(e, error, "An error was suppressed during disposal") : (hasError = true, e), next = (it) => {
68
+ while (it = stack.pop()) {
69
+ try {
70
+ var result = it[1] && it[1].call(it[2]);
71
+ if (it[0])
72
+ return Promise.resolve(result).then(next, (e) => (fail(e), next()));
73
+ } catch (e) {
74
+ fail(e);
75
+ }
76
+ }
77
+ if (hasError)
78
+ throw error;
79
+ };
80
+ return next();
81
+ };
49
82
 
50
83
  // ../../node_modules/.bun/ansi-regex@6.2.2/node_modules/ansi-regex/index.js
51
84
  function ansiRegex({ onlyFirst = false } = {}) {
@@ -10580,7 +10613,7 @@ class JSONSchemaGenerator {
10580
10613
  if (val === undefined) {
10581
10614
  if (this.unrepresentable === "throw") {
10582
10615
  throw new Error("Literal `undefined` cannot be represented in JSON Schema");
10583
- }
10616
+ } else {}
10584
10617
  } else if (typeof val === "bigint") {
10585
10618
  if (this.unrepresentable === "throw") {
10586
10619
  throw new Error("BigInt literals cannot be represented in JSON Schema");
@@ -25315,7 +25348,8 @@ var init_index_qr7b6cvh = __esm(async () => {
25315
25348
  worker_path = env2.OTUI_TREE_SITTER_WORKER_PATH;
25316
25349
  } else if (true) {
25317
25350
  worker_path = 'new URL("./parser.worker.js", import.meta.url).href';
25318
- }
25351
+ } else
25352
+ ;
25319
25353
  this.worker = new Worker(worker_path);
25320
25354
  this.worker.onmessage = this.handleWorkerMessage.bind(this);
25321
25355
  this.worker.onerror = (error45) => {
@@ -56350,7 +56384,7 @@ var init_installation = __esm(async () => {
56350
56384
  await $2`${process.execPath} --version`.nothrow().quiet().text();
56351
56385
  }
56352
56386
  Installation.upgrade = upgrade;
56353
- Installation.VERSION = "0.2.140";
56387
+ Installation.VERSION = "0.2.141";
56354
56388
  Installation.CHANNEL = "latest";
56355
56389
  Installation.USER_AGENT = `${product.id}/${Installation.CHANNEL}/${Installation.VERSION}/${Flag.SLOPCODE_CLIENT}`;
56356
56390
  async function latest(installMethod) {
@@ -66999,57 +67033,64 @@ var init_bun = __esm(async () => {
66999
67033
  version: zod_default.string()
67000
67034
  }));
67001
67035
  async function install(pkg, version3 = "latest") {
67002
- using _4 = await Lock.write("bun-install");
67003
- const mod = path14.join(Global.Path.cache, "node_modules", pkg);
67004
- const pkgjsonPath = path14.join(Global.Path.cache, "package.json");
67005
- const parsed = await Filesystem.readJson(pkgjsonPath).catch(async () => {
67006
- const result = { dependencies: {} };
67007
- await Filesystem.writeJson(pkgjsonPath, result);
67008
- return result;
67009
- });
67010
- if (!parsed.dependencies)
67011
- parsed.dependencies = {};
67012
- const dependencies = parsed.dependencies;
67013
- const modExists = await Filesystem.exists(mod);
67014
- const cachedVersion = dependencies[pkg];
67015
- if (!modExists || !cachedVersion) {} else if (version3 !== "latest" && cachedVersion === version3) {
67016
- return mod;
67017
- } else if (version3 === "latest") {
67018
- const isOutdated = await PackageRegistry.isOutdated(pkg, cachedVersion, Global.Path.cache);
67019
- if (!isOutdated)
67036
+ let __stack = [];
67037
+ try {
67038
+ const _4 = __using(__stack, await Lock.write("bun-install"), 0);
67039
+ const mod = path14.join(Global.Path.cache, "node_modules", pkg);
67040
+ const pkgjsonPath = path14.join(Global.Path.cache, "package.json");
67041
+ const parsed = await Filesystem.readJson(pkgjsonPath).catch(async () => {
67042
+ const result = { dependencies: {} };
67043
+ await Filesystem.writeJson(pkgjsonPath, result);
67044
+ return result;
67045
+ });
67046
+ if (!parsed.dependencies)
67047
+ parsed.dependencies = {};
67048
+ const dependencies = parsed.dependencies;
67049
+ const modExists = await Filesystem.exists(mod);
67050
+ const cachedVersion = dependencies[pkg];
67051
+ if (!modExists || !cachedVersion) {} else if (version3 !== "latest" && cachedVersion === version3) {
67020
67052
  return mod;
67021
- log2.info("Cached version is outdated, proceeding with install", { pkg, cachedVersion });
67022
- }
67023
- const args2 = [
67024
- "add",
67025
- "--force",
67026
- "--exact",
67027
- ...proxied() || process.env.CI ? ["--no-cache"] : [],
67028
- "--cwd",
67029
- Global.Path.cache,
67030
- pkg + "@" + version3
67031
- ];
67032
- log2.info("installing package using Bun's default registry resolution", {
67033
- pkg,
67034
- version: version3
67035
- });
67036
- await BunProc.run(args2, {
67037
- cwd: Global.Path.cache
67038
- }).catch((e3) => {
67039
- throw new BunProc.InstallFailedError({ pkg, version: version3 }, {
67040
- cause: e3
67053
+ } else if (version3 === "latest") {
67054
+ const isOutdated = await PackageRegistry.isOutdated(pkg, cachedVersion, Global.Path.cache);
67055
+ if (!isOutdated)
67056
+ return mod;
67057
+ log2.info("Cached version is outdated, proceeding with install", { pkg, cachedVersion });
67058
+ }
67059
+ const args2 = [
67060
+ "add",
67061
+ "--force",
67062
+ "--exact",
67063
+ ...proxied() || process.env.CI ? ["--no-cache"] : [],
67064
+ "--cwd",
67065
+ Global.Path.cache,
67066
+ pkg + "@" + version3
67067
+ ];
67068
+ log2.info("installing package using Bun's default registry resolution", {
67069
+ pkg,
67070
+ version: version3
67041
67071
  });
67042
- });
67043
- let resolvedVersion = version3;
67044
- if (version3 === "latest") {
67045
- const installedPkg = await Filesystem.readJson(path14.join(mod, "package.json")).catch(() => null);
67046
- if (installedPkg?.version) {
67047
- resolvedVersion = installedPkg.version;
67072
+ await BunProc.run(args2, {
67073
+ cwd: Global.Path.cache
67074
+ }).catch((e3) => {
67075
+ throw new BunProc.InstallFailedError({ pkg, version: version3 }, {
67076
+ cause: e3
67077
+ });
67078
+ });
67079
+ let resolvedVersion = version3;
67080
+ if (version3 === "latest") {
67081
+ const installedPkg = await Filesystem.readJson(path14.join(mod, "package.json")).catch(() => null);
67082
+ if (installedPkg?.version) {
67083
+ resolvedVersion = installedPkg.version;
67084
+ }
67048
67085
  }
67086
+ parsed.dependencies[pkg] = resolvedVersion;
67087
+ await Filesystem.writeJson(pkgjsonPath, parsed);
67088
+ return mod;
67089
+ } catch (_catch3) {
67090
+ var _err = _catch3, _hasErr = 1;
67091
+ } finally {
67092
+ __callDispose(__stack, _err, _hasErr);
67049
67093
  }
67050
- parsed.dependencies[pkg] = resolvedVersion;
67051
- await Filesystem.writeJson(pkgjsonPath, parsed);
67052
- return mod;
67053
67094
  }
67054
67095
  BunProc.install = install;
67055
67096
  })(BunProc ||= {});
@@ -76010,9 +76051,16 @@ var init_storage = __esm(async () => {
76010
76051
  const dir = await state2().then((x4) => x4.dir);
76011
76052
  const target = path20.join(dir, ...key) + ".json";
76012
76053
  return withErrorHandling(async () => {
76013
- using _4 = await Lock.read(target);
76014
- const result = await Filesystem.readJson(target);
76015
- return result;
76054
+ let __stack = [];
76055
+ try {
76056
+ const _4 = __using(__stack, await Lock.read(target), 0);
76057
+ const result = await Filesystem.readJson(target);
76058
+ return result;
76059
+ } catch (_catch3) {
76060
+ var _err = _catch3, _hasErr = 1;
76061
+ } finally {
76062
+ __callDispose(__stack, _err, _hasErr);
76063
+ }
76016
76064
  });
76017
76065
  }
76018
76066
  Storage.read = read;
@@ -76020,11 +76068,18 @@ var init_storage = __esm(async () => {
76020
76068
  const dir = await state2().then((x4) => x4.dir);
76021
76069
  const target = path20.join(dir, ...key) + ".json";
76022
76070
  return withErrorHandling(async () => {
76023
- using _4 = await Lock.write(target);
76024
- const content = await Filesystem.readJson(target);
76025
- fn2(content);
76026
- await Filesystem.writeJson(target, content);
76027
- return content;
76071
+ let __stack = [];
76072
+ try {
76073
+ const _4 = __using(__stack, await Lock.write(target), 0);
76074
+ const content = await Filesystem.readJson(target);
76075
+ fn2(content);
76076
+ await Filesystem.writeJson(target, content);
76077
+ return content;
76078
+ } catch (_catch3) {
76079
+ var _err = _catch3, _hasErr = 1;
76080
+ } finally {
76081
+ __callDispose(__stack, _err, _hasErr);
76082
+ }
76028
76083
  });
76029
76084
  }
76030
76085
  Storage.update = update;
@@ -76032,8 +76087,15 @@ var init_storage = __esm(async () => {
76032
76087
  const dir = await state2().then((x4) => x4.dir);
76033
76088
  const target = path20.join(dir, ...key) + ".json";
76034
76089
  return withErrorHandling(async () => {
76035
- using _4 = await Lock.write(target);
76036
- await Filesystem.writeJson(target, content);
76090
+ let __stack = [];
76091
+ try {
76092
+ const _4 = __using(__stack, await Lock.write(target), 0);
76093
+ await Filesystem.writeJson(target, content);
76094
+ } catch (_catch3) {
76095
+ var _err = _catch3, _hasErr = 1;
76096
+ } finally {
76097
+ __callDispose(__stack, _err, _hasErr);
76098
+ }
76037
76099
  });
76038
76100
  }
76039
76101
  Storage.write = write;
@@ -84184,7 +84246,7 @@ var require_tracestate_impl = __commonJS((exports) => {
84184
84246
  const value = listMember.slice(i8 + 1, part.length);
84185
84247
  if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) {
84186
84248
  agg.set(key, value);
84187
- }
84249
+ } else {}
84188
84250
  }
84189
84251
  return agg;
84190
84252
  }, new Map);
@@ -162698,11 +162760,11 @@ var init_types3 = () => {};
162698
162760
  var exports_dist_es = {};
162699
162761
  __export(exports_dist_es, {
162700
162762
  providerConfigFromInit: () => providerConfigFromInit,
162701
- httpRequest: () => httpRequest,
162702
- getInstanceMetadataEndpoint: () => getInstanceMetadataEndpoint,
162763
+ httpRequest: () => httpRequest2,
162764
+ getInstanceMetadataEndpoint: () => getInstanceMetadataEndpoint2,
162703
162765
  fromInstanceMetadata: () => fromInstanceMetadata,
162704
162766
  fromContainerMetadata: () => fromContainerMetadata,
162705
- Endpoint: () => Endpoint,
162767
+ Endpoint: () => Endpoint2,
162706
162768
  ENV_CMDS_RELATIVE_URI: () => ENV_CMDS_RELATIVE_URI,
162707
162769
  ENV_CMDS_FULL_URI: () => ENV_CMDS_FULL_URI,
162708
162770
  ENV_CMDS_AUTH_TOKEN: () => ENV_CMDS_AUTH_TOKEN,
@@ -162710,9 +162772,6 @@ __export(exports_dist_es, {
162710
162772
  DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES
162711
162773
  });
162712
162774
  var init_dist_es4 = __esm(() => {
162713
- init_httpRequest();
162714
- init_getInstanceMetadataEndpoint();
162715
- init_Endpoint();
162716
162775
  init_fromContainerMetadata();
162717
162776
  init_fromInstanceMetadata();
162718
162777
  init_types3();
@@ -163123,7 +163182,7 @@ var require_dist_cjs14 = __commonJS((exports) => {
163123
163182
  return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME);
163124
163183
  };
163125
163184
  var MIN_WAIT_TIME = 6000;
163126
- async function writeRequestBody(httpRequest2, request3, maxContinueTimeoutMs = MIN_WAIT_TIME, externalAgent = false) {
163185
+ async function writeRequestBody(httpRequest3, request3, maxContinueTimeoutMs = MIN_WAIT_TIME, externalAgent = false) {
163127
163186
  const headers = request3.headers ?? {};
163128
163187
  const expect = headers.Expect || headers.expect;
163129
163188
  let timeoutId = -1;
@@ -163134,15 +163193,15 @@ var require_dist_cjs14 = __commonJS((exports) => {
163134
163193
  timeoutId = Number(timing.setTimeout(() => resolve10(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)));
163135
163194
  }),
163136
163195
  new Promise((resolve10) => {
163137
- httpRequest2.on("continue", () => {
163196
+ httpRequest3.on("continue", () => {
163138
163197
  timing.clearTimeout(timeoutId);
163139
163198
  resolve10(true);
163140
163199
  });
163141
- httpRequest2.on("response", () => {
163200
+ httpRequest3.on("response", () => {
163142
163201
  timing.clearTimeout(timeoutId);
163143
163202
  resolve10(false);
163144
163203
  });
163145
- httpRequest2.on("error", () => {
163204
+ httpRequest3.on("error", () => {
163146
163205
  timing.clearTimeout(timeoutId);
163147
163206
  resolve10(false);
163148
163207
  });
@@ -163150,12 +163209,12 @@ var require_dist_cjs14 = __commonJS((exports) => {
163150
163209
  ]);
163151
163210
  }
163152
163211
  if (sendBody) {
163153
- writeBody(httpRequest2, request3.body);
163212
+ writeBody(httpRequest3, request3.body);
163154
163213
  }
163155
163214
  }
163156
- function writeBody(httpRequest2, body2) {
163215
+ function writeBody(httpRequest3, body2) {
163157
163216
  if (body2 instanceof stream.Readable) {
163158
- body2.pipe(httpRequest2);
163217
+ body2.pipe(httpRequest3);
163159
163218
  return;
163160
163219
  }
163161
163220
  if (body2) {
@@ -163163,21 +163222,21 @@ var require_dist_cjs14 = __commonJS((exports) => {
163163
163222
  const isString = typeof body2 === "string";
163164
163223
  if (isBuffer || isString) {
163165
163224
  if (isBuffer && body2.byteLength === 0) {
163166
- httpRequest2.end();
163225
+ httpRequest3.end();
163167
163226
  } else {
163168
- httpRequest2.end(body2);
163227
+ httpRequest3.end(body2);
163169
163228
  }
163170
163229
  return;
163171
163230
  }
163172
163231
  const uint8 = body2;
163173
163232
  if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") {
163174
- httpRequest2.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));
163233
+ httpRequest3.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));
163175
163234
  return;
163176
163235
  }
163177
- httpRequest2.end(Buffer.from(body2));
163236
+ httpRequest3.end(Buffer.from(body2));
163178
163237
  return;
163179
163238
  }
163180
- httpRequest2.end();
163239
+ httpRequest3.end();
163181
163240
  }
163182
163241
  var DEFAULT_REQUEST_TIMEOUT = 0;
163183
163242
 
@@ -168777,7 +168836,7 @@ var require_dist_cjs26 = __commonJS((exports) => {
168777
168836
  }
168778
168837
 
168779
168838
  class HttpApiKeyAuthSigner {
168780
- async sign(httpRequest2, identity, signingProperties) {
168839
+ async sign(httpRequest3, identity, signingProperties) {
168781
168840
  if (!signingProperties) {
168782
168841
  throw new Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing");
168783
168842
  }
@@ -168790,7 +168849,7 @@ var require_dist_cjs26 = __commonJS((exports) => {
168790
168849
  if (!identity.apiKey) {
168791
168850
  throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined");
168792
168851
  }
168793
- const clonedRequest = protocolHttp.HttpRequest.clone(httpRequest2);
168852
+ const clonedRequest = protocolHttp.HttpRequest.clone(httpRequest3);
168794
168853
  if (signingProperties.in === types5.HttpApiKeyAuthLocation.QUERY) {
168795
168854
  clonedRequest.query[signingProperties.name] = identity.apiKey;
168796
168855
  } else if (signingProperties.in === types5.HttpApiKeyAuthLocation.HEADER) {
@@ -168803,8 +168862,8 @@ var require_dist_cjs26 = __commonJS((exports) => {
168803
168862
  }
168804
168863
 
168805
168864
  class HttpBearerAuthSigner {
168806
- async sign(httpRequest2, identity, signingProperties) {
168807
- const clonedRequest = protocolHttp.HttpRequest.clone(httpRequest2);
168865
+ async sign(httpRequest3, identity, signingProperties) {
168866
+ const clonedRequest = protocolHttp.HttpRequest.clone(httpRequest3);
168808
168867
  if (!identity.token) {
168809
168868
  throw new Error("request could not be signed with `token` since the `token` is not defined");
168810
168869
  }
@@ -168814,8 +168873,8 @@ var require_dist_cjs26 = __commonJS((exports) => {
168814
168873
  }
168815
168874
 
168816
168875
  class NoAuthSigner {
168817
- async sign(httpRequest2, identity, signingProperties) {
168818
- return httpRequest2;
168876
+ async sign(httpRequest3, identity, signingProperties) {
168877
+ return httpRequest3;
168819
168878
  }
168820
168879
  }
168821
168880
  var createIsIdentityExpiredFunction = (expirationMs) => function isIdentityExpired2(identity) {
@@ -172576,8 +172635,8 @@ More information can be found at: https://a.co/c895JFp`);
172576
172635
  };
172577
172636
 
172578
172637
  class AwsSdkSigV4Signer {
172579
- async sign(httpRequest2, identity, signingProperties) {
172580
- if (!protocolHttp.HttpRequest.isInstance(httpRequest2)) {
172638
+ async sign(httpRequest3, identity, signingProperties) {
172639
+ if (!protocolHttp.HttpRequest.isInstance(httpRequest3)) {
172581
172640
  throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
172582
172641
  }
172583
172642
  const validatedProps = await validateSigningProperties(signingProperties);
@@ -172591,7 +172650,7 @@ More information can be found at: https://a.co/c895JFp`);
172591
172650
  signingName = second?.signingName ?? signingName;
172592
172651
  }
172593
172652
  }
172594
- const signedRequest = await signer.sign(httpRequest2, {
172653
+ const signedRequest = await signer.sign(httpRequest3, {
172595
172654
  signingDate: getSkewCorrectedDate(config4.systemClockOffset),
172596
172655
  signingRegion,
172597
172656
  signingService: signingName
@@ -172624,14 +172683,14 @@ More information can be found at: https://a.co/c895JFp`);
172624
172683
  var AWSSDKSigV4Signer = AwsSdkSigV4Signer;
172625
172684
 
172626
172685
  class AwsSdkSigV4ASigner extends AwsSdkSigV4Signer {
172627
- async sign(httpRequest2, identity, signingProperties) {
172628
- if (!protocolHttp.HttpRequest.isInstance(httpRequest2)) {
172686
+ async sign(httpRequest3, identity, signingProperties) {
172687
+ if (!protocolHttp.HttpRequest.isInstance(httpRequest3)) {
172629
172688
  throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
172630
172689
  }
172631
172690
  const { config: config4, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties);
172632
172691
  const configResolvedSigningRegionSet = await config4.sigv4aSigningRegionSet?.();
172633
172692
  const multiRegionOverride = (configResolvedSigningRegionSet ?? signingRegionSet ?? [signingRegion]).join(",");
172634
- const signedRequest = await signer.sign(httpRequest2, {
172693
+ const signedRequest = await signer.sign(httpRequest3, {
172635
172694
  signingDate: getSkewCorrectedDate(config4.systemClockOffset),
172636
172695
  signingRegion: multiRegionOverride,
172637
172696
  signingService: signingName
@@ -176387,9 +176446,9 @@ var require_dist_cjs44 = __commonJS((exports) => {
176387
176446
  }
176388
176447
  if (!process.env[ENV_IMDS_DISABLED]) {
176389
176448
  try {
176390
- const { getInstanceMetadataEndpoint: getInstanceMetadataEndpoint2, httpRequest: httpRequest2 } = await Promise.resolve().then(() => (init_dist_es4(), exports_dist_es));
176391
- const endpoint = await getInstanceMetadataEndpoint2();
176392
- return (await httpRequest2({ ...endpoint, path: IMDS_REGION_PATH })).toString();
176449
+ const { getInstanceMetadataEndpoint: getInstanceMetadataEndpoint3, httpRequest: httpRequest3 } = await Promise.resolve().then(() => (init_dist_es4(), exports_dist_es));
176450
+ const endpoint = await getInstanceMetadataEndpoint3();
176451
+ return (await httpRequest3({ ...endpoint, path: IMDS_REGION_PATH })).toString();
176393
176452
  } catch (e3) {}
176394
176453
  }
176395
176454
  };
@@ -184587,256 +184646,263 @@ var init_provider = __esm(async () => {
184587
184646
  }
184588
184647
  Provider.fromModelsDevProvider = fromModelsDevProvider;
184589
184648
  const state2 = Instance.state(async () => {
184590
- using _4 = log4.time("state");
184591
- const config4 = await Config.get();
184592
- const modelsDev = await ModelsDev.get();
184593
- const database = i4(modelsDev, fromModelsDevProvider);
184594
- const disabled = new Set(config4.disabled_providers ?? []);
184595
- const enabled = config4.enabled_providers ? new Set(config4.enabled_providers) : null;
184596
- function isProviderAllowed(providerID) {
184597
- if (enabled && !enabled.has(providerID))
184598
- return false;
184599
- if (disabled.has(providerID))
184600
- return false;
184601
- return true;
184602
- }
184603
- const providers2 = {};
184604
- const languages = new Map;
184605
- const modelLoaders = {};
184606
- const sdk = new Map;
184607
- log4.info("init");
184608
- const configProviders = Object.entries(config4.provider ?? {});
184609
- if (database["github-copilot"]) {
184610
- const githubCopilot = database["github-copilot"];
184611
- database["github-copilot-enterprise"] = {
184612
- ...githubCopilot,
184613
- id: "github-copilot-enterprise",
184614
- name: "GitHub Copilot Enterprise",
184615
- models: i4(githubCopilot.models, (model) => ({
184616
- ...model,
184617
- providerID: "github-copilot-enterprise"
184618
- }))
184619
- };
184620
- }
184621
- function mergeProvider(providerID, provider) {
184622
- const existing = providers2[providerID];
184623
- if (existing) {
184624
- providers2[providerID] = D3(existing, provider);
184625
- return;
184649
+ let __stack = [];
184650
+ try {
184651
+ const _4 = __using(__stack, log4.time("state"), 0);
184652
+ const config4 = await Config.get();
184653
+ const modelsDev = await ModelsDev.get();
184654
+ const database = i4(modelsDev, fromModelsDevProvider);
184655
+ const disabled = new Set(config4.disabled_providers ?? []);
184656
+ const enabled = config4.enabled_providers ? new Set(config4.enabled_providers) : null;
184657
+ function isProviderAllowed(providerID) {
184658
+ if (enabled && !enabled.has(providerID))
184659
+ return false;
184660
+ if (disabled.has(providerID))
184661
+ return false;
184662
+ return true;
184626
184663
  }
184627
- const match2 = database[providerID];
184628
- if (!match2)
184629
- return;
184630
- providers2[providerID] = D3(match2, provider);
184631
- }
184632
- for (const [providerID, provider] of configProviders) {
184633
- const existing = database[providerID];
184634
- const parsed = {
184635
- id: providerID,
184636
- name: provider.name ?? existing?.name ?? providerID,
184637
- env: provider.env ?? existing?.env ?? [],
184638
- options: D3(existing?.options ?? {}, provider.options ?? {}),
184639
- source: "config",
184640
- models: existing?.models ?? {}
184641
- };
184642
- for (const [modelID, model] of Object.entries(provider.models ?? {})) {
184643
- const existingModel = parsed.models[model.id ?? modelID];
184644
- const name19 = iife2(() => {
184645
- if (model.name)
184646
- return model.name;
184647
- if (model.id && model.id !== modelID)
184648
- return modelID;
184649
- return existingModel?.name ?? modelID;
184650
- });
184651
- const parsedModel = {
184652
- id: modelID,
184653
- api: {
184654
- id: model.id ?? existingModel?.api.id ?? modelID,
184655
- npm: model.provider?.npm ?? provider.npm ?? existingModel?.api.npm ?? modelsDev[providerID]?.npm ?? "@ai-sdk/openai-compatible",
184656
- url: model.provider?.api ?? provider?.api ?? existingModel?.api.url ?? modelsDev[providerID]?.api
184657
- },
184658
- status: model.status ?? existingModel?.status ?? "active",
184659
- name: name19,
184660
- providerID,
184661
- capabilities: {
184662
- temperature: model.temperature ?? existingModel?.capabilities.temperature ?? false,
184663
- reasoning: model.reasoning ?? existingModel?.capabilities.reasoning ?? false,
184664
- attachment: model.attachment ?? existingModel?.capabilities.attachment ?? false,
184665
- toolcall: model.tool_call ?? existingModel?.capabilities.toolcall ?? true,
184666
- input: {
184667
- text: model.modalities?.input?.includes("text") ?? existingModel?.capabilities.input.text ?? true,
184668
- audio: model.modalities?.input?.includes("audio") ?? existingModel?.capabilities.input.audio ?? false,
184669
- image: model.modalities?.input?.includes("image") ?? existingModel?.capabilities.input.image ?? false,
184670
- video: model.modalities?.input?.includes("video") ?? existingModel?.capabilities.input.video ?? false,
184671
- pdf: model.modalities?.input?.includes("pdf") ?? existingModel?.capabilities.input.pdf ?? false
184664
+ const providers2 = {};
184665
+ const languages = new Map;
184666
+ const modelLoaders = {};
184667
+ const sdk = new Map;
184668
+ log4.info("init");
184669
+ const configProviders = Object.entries(config4.provider ?? {});
184670
+ if (database["github-copilot"]) {
184671
+ const githubCopilot = database["github-copilot"];
184672
+ database["github-copilot-enterprise"] = {
184673
+ ...githubCopilot,
184674
+ id: "github-copilot-enterprise",
184675
+ name: "GitHub Copilot Enterprise",
184676
+ models: i4(githubCopilot.models, (model) => ({
184677
+ ...model,
184678
+ providerID: "github-copilot-enterprise"
184679
+ }))
184680
+ };
184681
+ }
184682
+ function mergeProvider(providerID, provider) {
184683
+ const existing = providers2[providerID];
184684
+ if (existing) {
184685
+ providers2[providerID] = D3(existing, provider);
184686
+ return;
184687
+ }
184688
+ const match2 = database[providerID];
184689
+ if (!match2)
184690
+ return;
184691
+ providers2[providerID] = D3(match2, provider);
184692
+ }
184693
+ for (const [providerID, provider] of configProviders) {
184694
+ const existing = database[providerID];
184695
+ const parsed = {
184696
+ id: providerID,
184697
+ name: provider.name ?? existing?.name ?? providerID,
184698
+ env: provider.env ?? existing?.env ?? [],
184699
+ options: D3(existing?.options ?? {}, provider.options ?? {}),
184700
+ source: "config",
184701
+ models: existing?.models ?? {}
184702
+ };
184703
+ for (const [modelID, model] of Object.entries(provider.models ?? {})) {
184704
+ const existingModel = parsed.models[model.id ?? modelID];
184705
+ const name19 = iife2(() => {
184706
+ if (model.name)
184707
+ return model.name;
184708
+ if (model.id && model.id !== modelID)
184709
+ return modelID;
184710
+ return existingModel?.name ?? modelID;
184711
+ });
184712
+ const parsedModel = {
184713
+ id: modelID,
184714
+ api: {
184715
+ id: model.id ?? existingModel?.api.id ?? modelID,
184716
+ npm: model.provider?.npm ?? provider.npm ?? existingModel?.api.npm ?? modelsDev[providerID]?.npm ?? "@ai-sdk/openai-compatible",
184717
+ url: model.provider?.api ?? provider?.api ?? existingModel?.api.url ?? modelsDev[providerID]?.api
184672
184718
  },
184673
- output: {
184674
- text: model.modalities?.output?.includes("text") ?? existingModel?.capabilities.output.text ?? true,
184675
- audio: model.modalities?.output?.includes("audio") ?? existingModel?.capabilities.output.audio ?? false,
184676
- image: model.modalities?.output?.includes("image") ?? existingModel?.capabilities.output.image ?? false,
184677
- video: model.modalities?.output?.includes("video") ?? existingModel?.capabilities.output.video ?? false,
184678
- pdf: model.modalities?.output?.includes("pdf") ?? existingModel?.capabilities.output.pdf ?? false
184719
+ status: model.status ?? existingModel?.status ?? "active",
184720
+ name: name19,
184721
+ providerID,
184722
+ capabilities: {
184723
+ temperature: model.temperature ?? existingModel?.capabilities.temperature ?? false,
184724
+ reasoning: model.reasoning ?? existingModel?.capabilities.reasoning ?? false,
184725
+ attachment: model.attachment ?? existingModel?.capabilities.attachment ?? false,
184726
+ toolcall: model.tool_call ?? existingModel?.capabilities.toolcall ?? true,
184727
+ input: {
184728
+ text: model.modalities?.input?.includes("text") ?? existingModel?.capabilities.input.text ?? true,
184729
+ audio: model.modalities?.input?.includes("audio") ?? existingModel?.capabilities.input.audio ?? false,
184730
+ image: model.modalities?.input?.includes("image") ?? existingModel?.capabilities.input.image ?? false,
184731
+ video: model.modalities?.input?.includes("video") ?? existingModel?.capabilities.input.video ?? false,
184732
+ pdf: model.modalities?.input?.includes("pdf") ?? existingModel?.capabilities.input.pdf ?? false
184733
+ },
184734
+ output: {
184735
+ text: model.modalities?.output?.includes("text") ?? existingModel?.capabilities.output.text ?? true,
184736
+ audio: model.modalities?.output?.includes("audio") ?? existingModel?.capabilities.output.audio ?? false,
184737
+ image: model.modalities?.output?.includes("image") ?? existingModel?.capabilities.output.image ?? false,
184738
+ video: model.modalities?.output?.includes("video") ?? existingModel?.capabilities.output.video ?? false,
184739
+ pdf: model.modalities?.output?.includes("pdf") ?? existingModel?.capabilities.output.pdf ?? false
184740
+ },
184741
+ interleaved: model.interleaved ?? false
184679
184742
  },
184680
- interleaved: model.interleaved ?? false
184681
- },
184682
- cost: {
184683
- input: model?.cost?.input ?? existingModel?.cost?.input ?? 0,
184684
- output: model?.cost?.output ?? existingModel?.cost?.output ?? 0,
184685
- cache: {
184686
- read: model?.cost?.cache_read ?? existingModel?.cost?.cache.read ?? 0,
184687
- write: model?.cost?.cache_write ?? existingModel?.cost?.cache.write ?? 0
184688
- }
184689
- },
184690
- options: D3(existingModel?.options ?? {}, model.options ?? {}),
184691
- limit: {
184692
- context: model.limit?.context ?? existingModel?.limit?.context ?? 0,
184693
- output: model.limit?.output ?? existingModel?.limit?.output ?? 0
184694
- },
184695
- headers: D3(existingModel?.headers ?? {}, model.headers ?? {}),
184696
- family: model.family ?? existingModel?.family ?? "",
184697
- release_date: model.release_date ?? existingModel?.release_date ?? "",
184698
- variants: {}
184699
- };
184700
- const merged = D3(ProviderTransform.variants(parsedModel), model.variants ?? {});
184701
- parsedModel.variants = i4(d4(merged, (v5) => !v5.disabled), (v5) => y5(v5, ["disabled"]));
184702
- parsed.models[modelID] = parsedModel;
184743
+ cost: {
184744
+ input: model?.cost?.input ?? existingModel?.cost?.input ?? 0,
184745
+ output: model?.cost?.output ?? existingModel?.cost?.output ?? 0,
184746
+ cache: {
184747
+ read: model?.cost?.cache_read ?? existingModel?.cost?.cache.read ?? 0,
184748
+ write: model?.cost?.cache_write ?? existingModel?.cost?.cache.write ?? 0
184749
+ }
184750
+ },
184751
+ options: D3(existingModel?.options ?? {}, model.options ?? {}),
184752
+ limit: {
184753
+ context: model.limit?.context ?? existingModel?.limit?.context ?? 0,
184754
+ output: model.limit?.output ?? existingModel?.limit?.output ?? 0
184755
+ },
184756
+ headers: D3(existingModel?.headers ?? {}, model.headers ?? {}),
184757
+ family: model.family ?? existingModel?.family ?? "",
184758
+ release_date: model.release_date ?? existingModel?.release_date ?? "",
184759
+ variants: {}
184760
+ };
184761
+ const merged = D3(ProviderTransform.variants(parsedModel), model.variants ?? {});
184762
+ parsedModel.variants = i4(d4(merged, (v5) => !v5.disabled), (v5) => y5(v5, ["disabled"]));
184763
+ parsed.models[modelID] = parsedModel;
184764
+ }
184765
+ database[providerID] = parsed;
184703
184766
  }
184704
- database[providerID] = parsed;
184705
- }
184706
- const env5 = Env.all();
184707
- for (const [providerID, provider] of Object.entries(database)) {
184708
- if (disabled.has(providerID))
184709
- continue;
184710
- const apiKey = provider.env.map((item) => env5[item]).find(Boolean);
184711
- if (!apiKey)
184712
- continue;
184713
- mergeProvider(providerID, {
184714
- source: "env",
184715
- key: provider.env.length === 1 ? apiKey : undefined
184716
- });
184717
- }
184718
- for (const [providerID, provider] of Object.entries(await Auth.all())) {
184719
- if (disabled.has(providerID))
184720
- continue;
184721
- if (provider.type === "api") {
184767
+ const env5 = Env.all();
184768
+ for (const [providerID, provider] of Object.entries(database)) {
184769
+ if (disabled.has(providerID))
184770
+ continue;
184771
+ const apiKey = provider.env.map((item) => env5[item]).find(Boolean);
184772
+ if (!apiKey)
184773
+ continue;
184722
184774
  mergeProvider(providerID, {
184723
- source: "api",
184724
- key: provider.key
184775
+ source: "env",
184776
+ key: provider.env.length === 1 ? apiKey : undefined
184725
184777
  });
184726
184778
  }
184727
- }
184728
- for (const plugin of await Plugin.list()) {
184729
- if (!plugin.auth)
184730
- continue;
184731
- const providerID = plugin.auth.provider;
184732
- if (disabled.has(providerID))
184733
- continue;
184734
- let hasAuth = false;
184735
- const auth = await Auth.get(providerID);
184736
- if (auth)
184737
- hasAuth = true;
184738
- if (providerID === "github-copilot" && !hasAuth) {
184739
- const enterpriseAuth = await Auth.get("github-copilot-enterprise");
184740
- if (enterpriseAuth)
184741
- hasAuth = true;
184742
- }
184743
- if (!hasAuth)
184744
- continue;
184745
- if (!plugin.auth.loader)
184746
- continue;
184747
- if (auth) {
184748
- const options2 = await plugin.auth.loader(() => Auth.get(providerID), database[plugin.auth.provider]);
184749
- const opts = options2 ?? {};
184750
- const patch = providers2[providerID] ? { options: opts } : { source: "custom", options: opts };
184751
- mergeProvider(providerID, patch);
184779
+ for (const [providerID, provider] of Object.entries(await Auth.all())) {
184780
+ if (disabled.has(providerID))
184781
+ continue;
184782
+ if (provider.type === "api") {
184783
+ mergeProvider(providerID, {
184784
+ source: "api",
184785
+ key: provider.key
184786
+ });
184787
+ }
184752
184788
  }
184753
- if (providerID === "github-copilot") {
184754
- const enterpriseProviderID = "github-copilot-enterprise";
184755
- if (!disabled.has(enterpriseProviderID)) {
184756
- const enterpriseAuth = await Auth.get(enterpriseProviderID);
184757
- if (enterpriseAuth) {
184758
- const enterpriseOptions = await plugin.auth.loader(() => Auth.get(enterpriseProviderID), database[enterpriseProviderID]);
184759
- const opts = enterpriseOptions ?? {};
184760
- const patch = providers2[enterpriseProviderID] ? { options: opts } : { source: "custom", options: opts };
184761
- mergeProvider(enterpriseProviderID, patch);
184789
+ for (const plugin of await Plugin.list()) {
184790
+ if (!plugin.auth)
184791
+ continue;
184792
+ const providerID = plugin.auth.provider;
184793
+ if (disabled.has(providerID))
184794
+ continue;
184795
+ let hasAuth = false;
184796
+ const auth = await Auth.get(providerID);
184797
+ if (auth)
184798
+ hasAuth = true;
184799
+ if (providerID === "github-copilot" && !hasAuth) {
184800
+ const enterpriseAuth = await Auth.get("github-copilot-enterprise");
184801
+ if (enterpriseAuth)
184802
+ hasAuth = true;
184803
+ }
184804
+ if (!hasAuth)
184805
+ continue;
184806
+ if (!plugin.auth.loader)
184807
+ continue;
184808
+ if (auth) {
184809
+ const options2 = await plugin.auth.loader(() => Auth.get(providerID), database[plugin.auth.provider]);
184810
+ const opts = options2 ?? {};
184811
+ const patch = providers2[providerID] ? { options: opts } : { source: "custom", options: opts };
184812
+ mergeProvider(providerID, patch);
184813
+ }
184814
+ if (providerID === "github-copilot") {
184815
+ const enterpriseProviderID = "github-copilot-enterprise";
184816
+ if (!disabled.has(enterpriseProviderID)) {
184817
+ const enterpriseAuth = await Auth.get(enterpriseProviderID);
184818
+ if (enterpriseAuth) {
184819
+ const enterpriseOptions = await plugin.auth.loader(() => Auth.get(enterpriseProviderID), database[enterpriseProviderID]);
184820
+ const opts = enterpriseOptions ?? {};
184821
+ const patch = providers2[enterpriseProviderID] ? { options: opts } : { source: "custom", options: opts };
184822
+ mergeProvider(enterpriseProviderID, patch);
184823
+ }
184762
184824
  }
184763
184825
  }
184764
184826
  }
184765
- }
184766
- for (const [providerID, fn3] of Object.entries(CUSTOM_LOADERS)) {
184767
- if (disabled.has(providerID))
184768
- continue;
184769
- const data2 = database[providerID];
184770
- if (!data2) {
184771
- log4.debug("skipping custom loader for missing provider", { providerID });
184772
- continue;
184773
- }
184774
- const result = await fn3(data2);
184775
- if (result && (result.autoload || providers2[providerID])) {
184776
- if (result.getModel)
184777
- modelLoaders[providerID] = result.getModel;
184778
- const opts = result.options ?? {};
184779
- const patch = providers2[providerID] ? { options: opts } : { source: "custom", options: opts };
184780
- mergeProvider(providerID, patch);
184781
- }
184782
- }
184783
- for (const [providerID, provider] of configProviders) {
184784
- const partial2 = { source: "config" };
184785
- if (provider.env)
184786
- partial2.env = provider.env;
184787
- if (provider.name)
184788
- partial2.name = provider.name;
184789
- if (provider.options)
184790
- partial2.options = provider.options;
184791
- mergeProvider(providerID, partial2);
184792
- }
184793
- for (const plugin of await Plugin.list()) {
184794
- if (!plugin.provider?.models)
184795
- continue;
184796
- const providerID = plugin.provider.id;
184797
- const provider = providers2[providerID];
184798
- if (!provider || !isProviderAllowed(providerID))
184799
- continue;
184800
- const models = await plugin.provider.models(provider, { auth: await Auth.get(providerID) });
184801
- if (models) {
184802
- provider.models = D3(provider.models, models);
184803
- }
184804
- }
184805
- for (const [providerID, provider] of Object.entries(providers2)) {
184806
- if (!isProviderAllowed(providerID)) {
184807
- delete providers2[providerID];
184808
- continue;
184827
+ for (const [providerID, fn3] of Object.entries(CUSTOM_LOADERS)) {
184828
+ if (disabled.has(providerID))
184829
+ continue;
184830
+ const data2 = database[providerID];
184831
+ if (!data2) {
184832
+ log4.debug("skipping custom loader for missing provider", { providerID });
184833
+ continue;
184834
+ }
184835
+ const result = await fn3(data2);
184836
+ if (result && (result.autoload || providers2[providerID])) {
184837
+ if (result.getModel)
184838
+ modelLoaders[providerID] = result.getModel;
184839
+ const opts = result.options ?? {};
184840
+ const patch = providers2[providerID] ? { options: opts } : { source: "custom", options: opts };
184841
+ mergeProvider(providerID, patch);
184842
+ }
184843
+ }
184844
+ for (const [providerID, provider] of configProviders) {
184845
+ const partial2 = { source: "config" };
184846
+ if (provider.env)
184847
+ partial2.env = provider.env;
184848
+ if (provider.name)
184849
+ partial2.name = provider.name;
184850
+ if (provider.options)
184851
+ partial2.options = provider.options;
184852
+ mergeProvider(providerID, partial2);
184853
+ }
184854
+ for (const plugin of await Plugin.list()) {
184855
+ if (!plugin.provider?.models)
184856
+ continue;
184857
+ const providerID = plugin.provider.id;
184858
+ const provider = providers2[providerID];
184859
+ if (!provider || !isProviderAllowed(providerID))
184860
+ continue;
184861
+ const models = await plugin.provider.models(provider, { auth: await Auth.get(providerID) });
184862
+ if (models) {
184863
+ provider.models = D3(provider.models, models);
184864
+ }
184809
184865
  }
184810
- const configProvider = config4.provider?.[providerID];
184811
- for (const [modelID, model] of Object.entries(provider.models)) {
184812
- model.api.id = model.api.id ?? model.id ?? modelID;
184813
- if (modelID === "gpt-5-chat-latest" || providerID === "openrouter" && modelID === "openai/gpt-5-chat")
184814
- delete provider.models[modelID];
184815
- if (model.status === "alpha" && !Flag.SLOPCODE_ENABLE_EXPERIMENTAL_MODELS)
184816
- delete provider.models[modelID];
184817
- if (model.status === "deprecated")
184818
- delete provider.models[modelID];
184819
- if (configProvider?.blacklist && configProvider.blacklist.includes(modelID) || configProvider?.whitelist && !configProvider.whitelist.includes(modelID))
184820
- delete provider.models[modelID];
184821
- model.variants = i4(ProviderTransform.variants(model), (v5) => v5);
184822
- const configVariants = configProvider?.models?.[modelID]?.variants;
184823
- if (configVariants && model.variants) {
184824
- const merged = D3(model.variants, configVariants);
184825
- model.variants = i4(d4(merged, (v5) => !v5.disabled), (v5) => y5(v5, ["disabled"]));
184826
- }
184827
- }
184828
- if (Object.keys(provider.models).length === 0) {
184829
- delete providers2[providerID];
184830
- continue;
184866
+ for (const [providerID, provider] of Object.entries(providers2)) {
184867
+ if (!isProviderAllowed(providerID)) {
184868
+ delete providers2[providerID];
184869
+ continue;
184870
+ }
184871
+ const configProvider = config4.provider?.[providerID];
184872
+ for (const [modelID, model] of Object.entries(provider.models)) {
184873
+ model.api.id = model.api.id ?? model.id ?? modelID;
184874
+ if (modelID === "gpt-5-chat-latest" || providerID === "openrouter" && modelID === "openai/gpt-5-chat")
184875
+ delete provider.models[modelID];
184876
+ if (model.status === "alpha" && !Flag.SLOPCODE_ENABLE_EXPERIMENTAL_MODELS)
184877
+ delete provider.models[modelID];
184878
+ if (model.status === "deprecated")
184879
+ delete provider.models[modelID];
184880
+ if (configProvider?.blacklist && configProvider.blacklist.includes(modelID) || configProvider?.whitelist && !configProvider.whitelist.includes(modelID))
184881
+ delete provider.models[modelID];
184882
+ model.variants = i4(ProviderTransform.variants(model), (v5) => v5);
184883
+ const configVariants = configProvider?.models?.[modelID]?.variants;
184884
+ if (configVariants && model.variants) {
184885
+ const merged = D3(model.variants, configVariants);
184886
+ model.variants = i4(d4(merged, (v5) => !v5.disabled), (v5) => y5(v5, ["disabled"]));
184887
+ }
184888
+ }
184889
+ if (Object.keys(provider.models).length === 0) {
184890
+ delete providers2[providerID];
184891
+ continue;
184892
+ }
184893
+ log4.info("found", { providerID });
184831
184894
  }
184832
- log4.info("found", { providerID });
184895
+ return {
184896
+ models: languages,
184897
+ providers: providers2,
184898
+ sdk,
184899
+ modelLoaders
184900
+ };
184901
+ } catch (_catch3) {
184902
+ var _err = _catch3, _hasErr = 1;
184903
+ } finally {
184904
+ __callDispose(__stack, _err, _hasErr);
184833
184905
  }
184834
- return {
184835
- models: languages,
184836
- providers: providers2,
184837
- sdk,
184838
- modelLoaders
184839
- };
184840
184906
  });
184841
184907
  async function list() {
184842
184908
  return state2().then((state3) => state3.providers);
@@ -184844,113 +184910,120 @@ var init_provider = __esm(async () => {
184844
184910
  Provider.list = list;
184845
184911
  async function getSDK(model) {
184846
184912
  try {
184847
- using _4 = log4.time("getSDK", {
184848
- providerID: model.providerID
184849
- });
184850
- const s7 = await state2();
184851
- const provider = s7.providers[model.providerID];
184852
- const options2 = { ...provider.options };
184853
- if (model.providerID === "google-vertex" && !model.api.npm.includes("@ai-sdk/openai-compatible")) {
184854
- delete options2.fetch;
184855
- }
184856
- if (model.api.npm.includes("@ai-sdk/openai-compatible") && options2["includeUsage"] !== false) {
184857
- options2["includeUsage"] = true;
184858
- }
184859
- const baseURL = loadBaseURL(model, options2);
184860
- if (baseURL !== undefined)
184861
- options2["baseURL"] = baseURL;
184862
- if (options2["apiKey"] === undefined && provider.key)
184863
- options2["apiKey"] = provider.key;
184864
- if (model.headers)
184865
- options2["headers"] = {
184866
- ...options2["headers"],
184867
- ...model.headers
184868
- };
184869
- const key = Bun.hash.xxHash32(JSON.stringify({ providerID: model.providerID, npm: model.api.npm, options: options2 }));
184870
- const existing = s7.sdk.get(key);
184871
- if (existing)
184872
- return existing;
184873
- const customFetch = options2["fetch"];
184874
- options2["fetch"] = async (input, init2) => {
184875
- const fetchFn = customFetch ?? fetch;
184876
- const opts = init2 ?? {};
184877
- if (options2["timeout"] !== undefined && options2["timeout"] !== null) {
184878
- const signals = [];
184879
- if (opts.signal)
184880
- signals.push(opts.signal);
184881
- if (options2["timeout"] !== false)
184882
- signals.push(AbortSignal.timeout(options2["timeout"]));
184883
- const combined = signals.length > 1 ? AbortSignal.any(signals) : signals[0];
184884
- opts.signal = combined;
184885
- }
184886
- if (opts.method === "POST" && typeof opts.body === "string") {
184887
- const url3 = new URL(input instanceof Request ? input.url : input.toString());
184888
- if (model.api.npm === "@ai-sdk/openai") {
184889
- const body2 = JSON.parse(opts.body);
184890
- const isAzure = model.providerID.includes("azure");
184891
- const keepIds = isAzure && body2.store === true;
184892
- if (!keepIds && Array.isArray(body2.input)) {
184893
- for (const item of body2.input) {
184894
- if ("id" in item) {
184895
- delete item.id;
184913
+ let __stack = [];
184914
+ try {
184915
+ const _4 = __using(__stack, log4.time("getSDK", {
184916
+ providerID: model.providerID
184917
+ }), 0);
184918
+ const s7 = await state2();
184919
+ const provider = s7.providers[model.providerID];
184920
+ const options2 = { ...provider.options };
184921
+ if (model.providerID === "google-vertex" && !model.api.npm.includes("@ai-sdk/openai-compatible")) {
184922
+ delete options2.fetch;
184923
+ }
184924
+ if (model.api.npm.includes("@ai-sdk/openai-compatible") && options2["includeUsage"] !== false) {
184925
+ options2["includeUsage"] = true;
184926
+ }
184927
+ const baseURL = loadBaseURL(model, options2);
184928
+ if (baseURL !== undefined)
184929
+ options2["baseURL"] = baseURL;
184930
+ if (options2["apiKey"] === undefined && provider.key)
184931
+ options2["apiKey"] = provider.key;
184932
+ if (model.headers)
184933
+ options2["headers"] = {
184934
+ ...options2["headers"],
184935
+ ...model.headers
184936
+ };
184937
+ const key = Bun.hash.xxHash32(JSON.stringify({ providerID: model.providerID, npm: model.api.npm, options: options2 }));
184938
+ const existing = s7.sdk.get(key);
184939
+ if (existing)
184940
+ return existing;
184941
+ const customFetch = options2["fetch"];
184942
+ options2["fetch"] = async (input, init2) => {
184943
+ const fetchFn = customFetch ?? fetch;
184944
+ const opts = init2 ?? {};
184945
+ if (options2["timeout"] !== undefined && options2["timeout"] !== null) {
184946
+ const signals = [];
184947
+ if (opts.signal)
184948
+ signals.push(opts.signal);
184949
+ if (options2["timeout"] !== false)
184950
+ signals.push(AbortSignal.timeout(options2["timeout"]));
184951
+ const combined = signals.length > 1 ? AbortSignal.any(signals) : signals[0];
184952
+ opts.signal = combined;
184953
+ }
184954
+ if (opts.method === "POST" && typeof opts.body === "string") {
184955
+ const url3 = new URL(input instanceof Request ? input.url : input.toString());
184956
+ if (model.api.npm === "@ai-sdk/openai") {
184957
+ const body2 = JSON.parse(opts.body);
184958
+ const isAzure = model.providerID.includes("azure");
184959
+ const keepIds = isAzure && body2.store === true;
184960
+ if (!keepIds && Array.isArray(body2.input)) {
184961
+ for (const item of body2.input) {
184962
+ if ("id" in item) {
184963
+ delete item.id;
184964
+ }
184896
184965
  }
184966
+ opts.body = JSON.stringify(body2);
184897
184967
  }
184898
- opts.body = JSON.stringify(body2);
184899
184968
  }
184900
- }
184901
- if (LlamaCppSessionCache.isEnabled(provider.options) && (url3.pathname.endsWith("/chat/completions") || url3.pathname.endsWith("/completions"))) {
184902
- const sessionID = new Headers(opts.headers).get("x-slopcode-session");
184903
- if (sessionID) {
184904
- const body2 = JSON.parse(opts.body);
184905
- const injected = await LlamaCppSessionCache.prepareRequest({
184906
- sessionID,
184907
- providerID: model.providerID,
184908
- modelID: model.id,
184909
- providerOptions: provider.options,
184910
- baseURL: String(baseURL ?? model.api.url),
184911
- fetch: fetchFn,
184912
- signal: opts.signal ?? undefined
184913
- });
184914
- if (injected) {
184915
- opts.body = JSON.stringify({ ...body2, ...injected });
184969
+ if (LlamaCppSessionCache.isEnabled(provider.options) && (url3.pathname.endsWith("/chat/completions") || url3.pathname.endsWith("/completions"))) {
184970
+ const sessionID = new Headers(opts.headers).get("x-slopcode-session");
184971
+ if (sessionID) {
184972
+ const body2 = JSON.parse(opts.body);
184973
+ const injected = await LlamaCppSessionCache.prepareRequest({
184974
+ sessionID,
184975
+ providerID: model.providerID,
184976
+ modelID: model.id,
184977
+ providerOptions: provider.options,
184978
+ baseURL: String(baseURL ?? model.api.url),
184979
+ fetch: fetchFn,
184980
+ signal: opts.signal ?? undefined
184981
+ });
184982
+ if (injected) {
184983
+ opts.body = JSON.stringify({ ...body2, ...injected });
184984
+ }
184916
184985
  }
184917
184986
  }
184918
184987
  }
184988
+ const response = await fetchFn(input, {
184989
+ ...opts,
184990
+ timeout: false
184991
+ });
184992
+ if (response.ok) {
184993
+ ProviderLimit.capture(response.headers);
184994
+ }
184995
+ return response;
184996
+ };
184997
+ const bundledFn = BUNDLED_PROVIDERS[model.api.npm];
184998
+ if (bundledFn) {
184999
+ log4.info("using bundled provider", { providerID: model.providerID, pkg: model.api.npm });
185000
+ const loaded2 = bundledFn({
185001
+ name: model.providerID,
185002
+ ...options2
185003
+ });
185004
+ s7.sdk.set(key, loaded2);
185005
+ return loaded2;
184919
185006
  }
184920
- const response = await fetchFn(input, {
184921
- ...opts,
184922
- timeout: false
184923
- });
184924
- if (response.ok) {
184925
- ProviderLimit.capture(response.headers);
185007
+ let installedPath;
185008
+ if (!model.api.npm.startsWith("file://")) {
185009
+ installedPath = await BunProc.install(model.api.npm, "latest");
185010
+ } else {
185011
+ log4.info("loading local provider", { pkg: model.api.npm });
185012
+ installedPath = model.api.npm;
184926
185013
  }
184927
- return response;
184928
- };
184929
- const bundledFn = BUNDLED_PROVIDERS[model.api.npm];
184930
- if (bundledFn) {
184931
- log4.info("using bundled provider", { providerID: model.providerID, pkg: model.api.npm });
184932
- const loaded2 = bundledFn({
185014
+ const mod2 = await import(installedPath);
185015
+ const fn3 = mod2[Object.keys(mod2).find((key2) => key2.startsWith("create"))];
185016
+ const loaded = fn3({
184933
185017
  name: model.providerID,
184934
185018
  ...options2
184935
185019
  });
184936
- s7.sdk.set(key, loaded2);
184937
- return loaded2;
184938
- }
184939
- let installedPath;
184940
- if (!model.api.npm.startsWith("file://")) {
184941
- installedPath = await BunProc.install(model.api.npm, "latest");
184942
- } else {
184943
- log4.info("loading local provider", { pkg: model.api.npm });
184944
- installedPath = model.api.npm;
185020
+ s7.sdk.set(key, loaded);
185021
+ return loaded;
185022
+ } catch (_catch3) {
185023
+ var _err = _catch3, _hasErr = 1;
185024
+ } finally {
185025
+ __callDispose(__stack, _err, _hasErr);
184945
185026
  }
184946
- const mod2 = await import(installedPath);
184947
- const fn3 = mod2[Object.keys(mod2).find((key2) => key2.startsWith("create"))];
184948
- const loaded = fn3({
184949
- name: model.providerID,
184950
- ...options2
184951
- });
184952
- s7.sdk.set(key, loaded);
184953
- return loaded;
184954
185027
  } catch (e4) {
184955
185028
  throw new Provider.InitError({ providerID: model.providerID }, { cause: e4 });
184956
185029
  }
@@ -200205,7 +200278,7 @@ ${JSON.stringify(symbolNames, null, 2)}`);
200205
200278
  throw new Error(response.status + " : " + response.url);
200206
200279
  }, "readAsync");
200207
200280
  }
200208
- }
200281
+ } else {}
200209
200282
  var out = Module["print"] || console.log.bind(console);
200210
200283
  var err = Module["printErr"] || console.error.bind(console);
200211
200284
  Object.assign(Module, moduleOverrides);
@@ -204225,54 +204298,61 @@ var init_file = __esm(async () => {
204225
204298
  }
204226
204299
  File.status = status;
204227
204300
  async function read(file2) {
204228
- using _4 = log6.time("read", { file: file2 });
204229
- const project = Instance.project;
204230
- const full = path43.join(Instance.directory, file2);
204231
- if (!Instance.containsPath(full)) {
204232
- throw new Error(`Access denied: path escapes project directory`);
204233
- }
204234
- if (isImageByExtension(file2)) {
204235
- if (await Filesystem.exists(full)) {
204301
+ let __stack = [];
204302
+ try {
204303
+ const _4 = __using(__stack, log6.time("read", { file: file2 }), 0);
204304
+ const project = Instance.project;
204305
+ const full = path43.join(Instance.directory, file2);
204306
+ if (!Instance.containsPath(full)) {
204307
+ throw new Error(`Access denied: path escapes project directory`);
204308
+ }
204309
+ if (isImageByExtension(file2)) {
204310
+ if (await Filesystem.exists(full)) {
204311
+ const buffer2 = await Filesystem.readBytes(full).catch(() => Buffer.from([]));
204312
+ const content2 = buffer2.toString("base64");
204313
+ const mimeType2 = getImageMimeType(file2);
204314
+ return { type: "text", content: content2, mimeType: mimeType2, encoding: "base64" };
204315
+ }
204316
+ return { type: "text", content: "" };
204317
+ }
204318
+ const text9 = isTextByExtension(file2) || isTextByName(file2);
204319
+ if (isBinaryByExtension(file2) && !text9) {
204320
+ return { type: "binary", content: "" };
204321
+ }
204322
+ if (!await Filesystem.exists(full)) {
204323
+ return { type: "text", content: "" };
204324
+ }
204325
+ const mimeType = Filesystem.mimeType(full);
204326
+ const encode4 = text9 ? false : await shouldEncode(mimeType);
204327
+ if (encode4 && !isImage(mimeType)) {
204328
+ return { type: "binary", content: "", mimeType };
204329
+ }
204330
+ if (encode4) {
204236
204331
  const buffer2 = await Filesystem.readBytes(full).catch(() => Buffer.from([]));
204237
204332
  const content2 = buffer2.toString("base64");
204238
- const mimeType2 = getImageMimeType(file2);
204239
- return { type: "text", content: content2, mimeType: mimeType2, encoding: "base64" };
204333
+ return { type: "text", content: content2, mimeType, encoding: "base64" };
204240
204334
  }
204241
- return { type: "text", content: "" };
204242
- }
204243
- const text9 = isTextByExtension(file2) || isTextByName(file2);
204244
- if (isBinaryByExtension(file2) && !text9) {
204245
- return { type: "binary", content: "" };
204246
- }
204247
- if (!await Filesystem.exists(full)) {
204248
- return { type: "text", content: "" };
204249
- }
204250
- const mimeType = Filesystem.mimeType(full);
204251
- const encode4 = text9 ? false : await shouldEncode(mimeType);
204252
- if (encode4 && !isImage(mimeType)) {
204253
- return { type: "binary", content: "", mimeType };
204254
- }
204255
- if (encode4) {
204256
- const buffer2 = await Filesystem.readBytes(full).catch(() => Buffer.from([]));
204257
- const content2 = buffer2.toString("base64");
204258
- return { type: "text", content: content2, mimeType, encoding: "base64" };
204259
- }
204260
- const content = (await Filesystem.readText(full).catch(() => "")).trim();
204261
- if (project.vcs === "git") {
204262
- let diff = await $10`git diff ${file2}`.cwd(Instance.directory).quiet().nothrow().text();
204263
- if (!diff.trim())
204264
- diff = await $10`git diff --staged ${file2}`.cwd(Instance.directory).quiet().nothrow().text();
204265
- if (diff.trim()) {
204266
- const original = await $10`git show HEAD:${file2}`.cwd(Instance.directory).quiet().nothrow().text();
204267
- const patch = structuredPatch(file2, file2, original, content, "old", "new", {
204268
- context: Infinity,
204269
- ignoreWhitespace: true
204270
- });
204271
- const diff2 = formatPatch(patch);
204272
- return { type: "text", content, patch, diff: diff2 };
204335
+ const content = (await Filesystem.readText(full).catch(() => "")).trim();
204336
+ if (project.vcs === "git") {
204337
+ let diff = await $10`git diff ${file2}`.cwd(Instance.directory).quiet().nothrow().text();
204338
+ if (!diff.trim())
204339
+ diff = await $10`git diff --staged ${file2}`.cwd(Instance.directory).quiet().nothrow().text();
204340
+ if (diff.trim()) {
204341
+ const original = await $10`git show HEAD:${file2}`.cwd(Instance.directory).quiet().nothrow().text();
204342
+ const patch = structuredPatch(file2, file2, original, content, "old", "new", {
204343
+ context: Infinity,
204344
+ ignoreWhitespace: true
204345
+ });
204346
+ const diff2 = formatPatch(patch);
204347
+ return { type: "text", content, patch, diff: diff2 };
204348
+ }
204273
204349
  }
204350
+ return { type: "text", content };
204351
+ } catch (_catch3) {
204352
+ var _err = _catch3, _hasErr = 1;
204353
+ } finally {
204354
+ __callDispose(__stack, _err, _hasErr);
204274
204355
  }
204275
- return { type: "text", content };
204276
204356
  }
204277
204357
  File.read = read;
204278
204358
  async function list(dir) {
@@ -209798,134 +209878,141 @@ var init_task2 = __esm(async () => {
209798
209878
  description,
209799
209879
  parameters,
209800
209880
  async execute(params, ctx2) {
209801
- const config5 = await Config.get();
209802
- if (params.background && !Flag.SLOPCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS) {
209803
- throw new Error("Background subagents require SLOPCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true");
209804
- }
209805
- if (!ctx2.extra?.bypassAgentCheck) {
209806
- await ctx2.ask({
209807
- permission: "task",
209808
- patterns: [params.subagent_type],
209809
- always: ["*"],
209810
- metadata: {
209811
- description: params.description,
209812
- subagent_type: params.subagent_type
209813
- }
209814
- });
209815
- }
209816
- const agent = await Agent.get(params.subagent_type);
209817
- if (!agent)
209818
- throw new Error(`Unknown agent type: ${params.subagent_type} is not a valid agent type`);
209819
- const hasTaskPermission = agent.permission.some((rule) => rule.permission === "task");
209820
- const hasTodoWritePermission = agent.permission.some((rule) => rule.permission === "todowrite");
209821
- const hasTodoReadPermission = agent.permission.some((rule) => rule.permission === "todoread");
209822
- const session = await iife2(async () => {
209823
- if (params.task_id) {
209824
- const found = await Session.get(params.task_id).catch(() => {});
209825
- if (found)
209826
- return found;
209827
- }
209828
- return await Session.create({
209829
- parentID: ctx2.sessionID,
209830
- title: params.description + ` (@${agent.name} subagent)`,
209831
- permission: [
209832
- ...hasTodoWritePermission ? [] : [
209833
- {
209834
- permission: "todowrite",
209835
- pattern: "*",
209836
- action: "deny"
209837
- }
209838
- ],
209839
- ...hasTodoReadPermission ? [] : [
209840
- {
209841
- permission: "todoread",
209842
- pattern: "*",
209843
- action: "deny"
209844
- }
209845
- ],
209846
- ...hasTaskPermission ? [] : [
209847
- {
209848
- permission: "task",
209881
+ let __stack = [];
209882
+ try {
209883
+ const config5 = await Config.get();
209884
+ if (params.background && !Flag.SLOPCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS) {
209885
+ throw new Error("Background subagents require SLOPCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true");
209886
+ }
209887
+ if (!ctx2.extra?.bypassAgentCheck) {
209888
+ await ctx2.ask({
209889
+ permission: "task",
209890
+ patterns: [params.subagent_type],
209891
+ always: ["*"],
209892
+ metadata: {
209893
+ description: params.description,
209894
+ subagent_type: params.subagent_type
209895
+ }
209896
+ });
209897
+ }
209898
+ const agent = await Agent.get(params.subagent_type);
209899
+ if (!agent)
209900
+ throw new Error(`Unknown agent type: ${params.subagent_type} is not a valid agent type`);
209901
+ const hasTaskPermission = agent.permission.some((rule) => rule.permission === "task");
209902
+ const hasTodoWritePermission = agent.permission.some((rule) => rule.permission === "todowrite");
209903
+ const hasTodoReadPermission = agent.permission.some((rule) => rule.permission === "todoread");
209904
+ const session = await iife2(async () => {
209905
+ if (params.task_id) {
209906
+ const found = await Session.get(params.task_id).catch(() => {});
209907
+ if (found)
209908
+ return found;
209909
+ }
209910
+ return await Session.create({
209911
+ parentID: ctx2.sessionID,
209912
+ title: params.description + ` (@${agent.name} subagent)`,
209913
+ permission: [
209914
+ ...hasTodoWritePermission ? [] : [
209915
+ {
209916
+ permission: "todowrite",
209917
+ pattern: "*",
209918
+ action: "deny"
209919
+ }
209920
+ ],
209921
+ ...hasTodoReadPermission ? [] : [
209922
+ {
209923
+ permission: "todoread",
209924
+ pattern: "*",
209925
+ action: "deny"
209926
+ }
209927
+ ],
209928
+ ...hasTaskPermission ? [] : [
209929
+ {
209930
+ permission: "task",
209931
+ pattern: "*",
209932
+ action: "deny"
209933
+ }
209934
+ ],
209935
+ ...config5.experimental?.primary_tools?.map((t5) => ({
209849
209936
  pattern: "*",
209850
- action: "deny"
209851
- }
209852
- ],
209853
- ...config5.experimental?.primary_tools?.map((t5) => ({
209854
- pattern: "*",
209855
- action: "allow",
209856
- permission: t5
209857
- })) ?? []
209858
- ]
209859
- });
209860
- });
209861
- const msg = await MessageV2.get({ sessionID: ctx2.sessionID, messageID: ctx2.messageID });
209862
- if (msg.info.role !== "assistant")
209863
- throw new Error("Not an assistant message");
209864
- const model = agent.model ?? {
209865
- modelID: msg.info.modelID,
209866
- providerID: msg.info.providerID
209867
- };
209868
- const metadata2 = {
209869
- sessionId: session.id,
209870
- model,
209871
- ...params.background ? { background: true } : {}
209872
- };
209873
- ctx2.metadata({
209874
- title: params.description,
209875
- metadata: metadata2
209876
- });
209877
- async function runTask() {
209878
- const promptParts = await SessionPrompt.resolvePromptParts(params.prompt);
209879
- const result = await SessionPrompt.prompt({
209880
- messageID: Identifier.ascending("message"),
209881
- sessionID: session.id,
209882
- model: {
209883
- modelID: model.modelID,
209884
- providerID: model.providerID
209885
- },
209886
- agent: agent.name,
209887
- tools: {
209888
- ...hasTodoWritePermission ? {} : { todowrite: false },
209889
- ...hasTodoReadPermission ? {} : { todoread: false },
209890
- ...hasTaskPermission ? {} : { task: false },
209891
- ...Object.fromEntries((config5.experimental?.primary_tools ?? []).map((t5) => [t5, false]))
209892
- },
209893
- parts: promptParts
209937
+ action: "allow",
209938
+ permission: t5
209939
+ })) ?? []
209940
+ ]
209941
+ });
209894
209942
  });
209895
- return result.parts.findLast((x5) => x5.type === "text")?.text ?? "";
209896
- }
209897
- if (params.background) {
209898
- const existing = BackgroundJob.get(session.id);
209899
- if (existing?.status === "running") {
209900
- throw new Error(`Task ${session.id} is already running. Use task_status to check progress.`);
209901
- }
209902
- const info3 = await BackgroundJob.start({
209903
- id: session.id,
209904
- type: "task",
209943
+ const msg = await MessageV2.get({ sessionID: ctx2.sessionID, messageID: ctx2.messageID });
209944
+ if (msg.info.role !== "assistant")
209945
+ throw new Error("Not an assistant message");
209946
+ const model = agent.model ?? {
209947
+ modelID: msg.info.modelID,
209948
+ providerID: msg.info.providerID
209949
+ };
209950
+ const metadata2 = {
209951
+ sessionId: session.id,
209952
+ model,
209953
+ ...params.background ? { background: true } : {}
209954
+ };
209955
+ ctx2.metadata({
209905
209956
  title: params.description,
209906
- metadata: metadata2,
209907
- run: runTask
209957
+ metadata: metadata2
209908
209958
  });
209959
+ async function runTask() {
209960
+ const promptParts = await SessionPrompt.resolvePromptParts(params.prompt);
209961
+ const result = await SessionPrompt.prompt({
209962
+ messageID: Identifier.ascending("message"),
209963
+ sessionID: session.id,
209964
+ model: {
209965
+ modelID: model.modelID,
209966
+ providerID: model.providerID
209967
+ },
209968
+ agent: agent.name,
209969
+ tools: {
209970
+ ...hasTodoWritePermission ? {} : { todowrite: false },
209971
+ ...hasTodoReadPermission ? {} : { todoread: false },
209972
+ ...hasTaskPermission ? {} : { task: false },
209973
+ ...Object.fromEntries((config5.experimental?.primary_tools ?? []).map((t5) => [t5, false]))
209974
+ },
209975
+ parts: promptParts
209976
+ });
209977
+ return result.parts.findLast((x5) => x5.type === "text")?.text ?? "";
209978
+ }
209979
+ if (params.background) {
209980
+ const existing = BackgroundJob.get(session.id);
209981
+ if (existing?.status === "running") {
209982
+ throw new Error(`Task ${session.id} is already running. Use task_status to check progress.`);
209983
+ }
209984
+ const info3 = await BackgroundJob.start({
209985
+ id: session.id,
209986
+ type: "task",
209987
+ title: params.description,
209988
+ metadata: metadata2,
209989
+ run: runTask
209990
+ });
209991
+ return {
209992
+ title: params.description,
209993
+ metadata: {
209994
+ ...metadata2,
209995
+ jobId: info3.id
209996
+ },
209997
+ output: backgroundOutput(session.id)
209998
+ };
209999
+ }
210000
+ function cancel() {
210001
+ SessionPrompt.cancel(session.id);
210002
+ }
210003
+ ctx2.abort.addEventListener("abort", cancel);
210004
+ const _4 = __using(__stack, defer(() => ctx2.abort.removeEventListener("abort", cancel)), 0);
210005
+ const text10 = await runTask();
209909
210006
  return {
209910
210007
  title: params.description,
209911
- metadata: {
209912
- ...metadata2,
209913
- jobId: info3.id
209914
- },
209915
- output: backgroundOutput(session.id)
210008
+ metadata: metadata2,
210009
+ output: formatOutput(session.id, text10)
209916
210010
  };
210011
+ } catch (_catch3) {
210012
+ var _err = _catch3, _hasErr = 1;
210013
+ } finally {
210014
+ __callDispose(__stack, _err, _hasErr);
209917
210015
  }
209918
- function cancel() {
209919
- SessionPrompt.cancel(session.id);
209920
- }
209921
- ctx2.abort.addEventListener("abort", cancel);
209922
- using _4 = defer(() => ctx2.abort.removeEventListener("abort", cancel));
209923
- const text10 = await runTask();
209924
- return {
209925
- title: params.description,
209926
- metadata: metadata2,
209927
- output: formatOutput(session.id, text10)
209928
- };
209929
210016
  }
209930
210017
  };
209931
210018
  });
@@ -229235,19 +229322,26 @@ var init_registry2 = __esm(async () => {
229235
229322
  return !usePatch;
229236
229323
  return true;
229237
229324
  }).map(async (t5) => {
229238
- using _4 = log6.time(t5.id);
229239
- const tool3 = await t5.init({ agent });
229240
- const output2 = {
229241
- description: tool3.description,
229242
- parameters: tool3.parameters
229243
- };
229244
- await Plugin.trigger("tool.definition", { toolID: t5.id }, output2);
229245
- return {
229246
- id: t5.id,
229247
- ...tool3,
229248
- description: output2.description,
229249
- parameters: output2.parameters
229250
- };
229325
+ let __stack = [];
229326
+ try {
229327
+ const _4 = __using(__stack, log6.time(t5.id), 0);
229328
+ const tool3 = await t5.init({ agent });
229329
+ const output2 = {
229330
+ description: tool3.description,
229331
+ parameters: tool3.parameters
229332
+ };
229333
+ await Plugin.trigger("tool.definition", { toolID: t5.id }, output2);
229334
+ return {
229335
+ id: t5.id,
229336
+ ...tool3,
229337
+ description: output2.description,
229338
+ parameters: output2.parameters
229339
+ };
229340
+ } catch (_catch3) {
229341
+ var _err = _catch3, _hasErr = 1;
229342
+ } finally {
229343
+ __callDispose(__stack, _err, _hasErr);
229344
+ }
229251
229345
  }));
229252
229346
  return result;
229253
229347
  }
@@ -243355,404 +243449,411 @@ var init_prompt = __esm(async () => {
243355
243449
  let step = 0;
243356
243450
  const session = await Session.get(sessionID);
243357
243451
  while (true) {
243358
- SessionStatus.busy(sessionID, "starting");
243359
- log8.info("loop", { step, sessionID });
243360
- if (abort2.aborted) {
243361
- if (held(state2()[sessionID], state2()[sessionID]?.current)) {
243362
- next2 = "hold";
243363
- return;
243364
- }
243365
- break;
243366
- }
243367
- let msgs = filterQueuedMessages(await MessageV2.filterCompacted(MessageV2.stream(sessionID)), state2()[sessionID], mode2);
243368
- const current2 = mode2 === "serial" ? state2()[sessionID]?.current : undefined;
243369
- const currentVisible = current2 ? msgs.some((msg) => msg.info.role === "user" && msg.info.id === current2) : false;
243370
- let currentMsg;
243371
- let lastUser;
243372
- let lastAssistant;
243373
- let lastFinished;
243374
- let lastComplete;
243375
- let tasks = [];
243376
- for (let i9 = msgs.length - 1;i9 >= 0; i9--) {
243377
- const msg = msgs[i9];
243378
- if (!lastUser && msg.info.role === "user" && (!current2 || msg.info.id === current2 || !currentVisible)) {
243379
- lastUser = msg.info;
243380
- currentMsg = msg;
243381
- }
243382
- if (!lastAssistant && msg.info.role === "assistant")
243383
- lastAssistant = msg.info;
243384
- if (!lastFinished && msg.info.role === "assistant" && msg.info.finish) {
243385
- lastFinished = msg.info;
243386
- }
243387
- if (!lastComplete && msg.info.role === "assistant" && msg.info.finish && !["tool-calls", "unknown"].includes(msg.info.finish)) {
243388
- lastComplete = msg.info;
243389
- }
243390
- if (lastUser && lastComplete)
243452
+ let __stack = [];
243453
+ try {
243454
+ SessionStatus.busy(sessionID, "starting");
243455
+ log8.info("loop", { step, sessionID });
243456
+ if (abort2.aborted) {
243457
+ if (held(state2()[sessionID], state2()[sessionID]?.current)) {
243458
+ next2 = "hold";
243459
+ return;
243460
+ }
243391
243461
  break;
243392
- const task2 = msg.parts.filter((part) => part.type === "compaction" || part.type === "subtask");
243393
- if (task2 && !lastComplete && (!current2 || msg.info.id !== current2)) {
243394
- tasks.push(...task2);
243395
243462
  }
243396
- }
243397
- if (currentMsg && !lastComplete) {
243398
- const processed = msgs.filter((msg) => msg.info.role === "assistant" && msg.info.parentID === currentMsg.info.id && msg.parts.some((part) => part.type === "tool" && part.tool === TaskTool.id)).length;
243399
- const remaining = currentMsg.parts.filter((part) => part.type === "subtask").slice(processed);
243400
- tasks.push(...remaining);
243401
- }
243402
- if (!lastUser)
243403
- throw new Error("No user message found in stream. This should never happen.");
243404
- if (shouldExitLoop(lastUser, lastAssistant)) {
243405
- log8.info("exiting loop", { sessionID });
243406
- break;
243407
- }
243408
- step++;
243409
- const model = await Provider.getModel(lastUser.model.providerID, lastUser.model.modelID).catch((e5) => {
243410
- if (Provider.ModelNotFoundError.isInstance(e5)) {
243411
- const hint = e5.data.suggestions?.length ? ` Did you mean: ${e5.data.suggestions.join(", ")}?` : "";
243412
- Bus.publish(Session.Event.Error, {
243413
- sessionID,
243414
- error: new NamedError.Unknown({
243415
- message: `Model not found: ${e5.data.providerID}/${e5.data.modelID}.${hint}`
243416
- }).toObject(),
243417
- viewID: Instance.viewID
243418
- });
243463
+ let msgs = filterQueuedMessages(await MessageV2.filterCompacted(MessageV2.stream(sessionID)), state2()[sessionID], mode2);
243464
+ const current2 = mode2 === "serial" ? state2()[sessionID]?.current : undefined;
243465
+ const currentVisible = current2 ? msgs.some((msg) => msg.info.role === "user" && msg.info.id === current2) : false;
243466
+ let currentMsg;
243467
+ let lastUser;
243468
+ let lastAssistant;
243469
+ let lastFinished;
243470
+ let lastComplete;
243471
+ let tasks = [];
243472
+ for (let i9 = msgs.length - 1;i9 >= 0; i9--) {
243473
+ const msg = msgs[i9];
243474
+ if (!lastUser && msg.info.role === "user" && (!current2 || msg.info.id === current2 || !currentVisible)) {
243475
+ lastUser = msg.info;
243476
+ currentMsg = msg;
243477
+ }
243478
+ if (!lastAssistant && msg.info.role === "assistant")
243479
+ lastAssistant = msg.info;
243480
+ if (!lastFinished && msg.info.role === "assistant" && msg.info.finish) {
243481
+ lastFinished = msg.info;
243482
+ }
243483
+ if (!lastComplete && msg.info.role === "assistant" && msg.info.finish && !["tool-calls", "unknown"].includes(msg.info.finish)) {
243484
+ lastComplete = msg.info;
243485
+ }
243486
+ if (lastUser && lastComplete)
243487
+ break;
243488
+ const task2 = msg.parts.filter((part) => part.type === "compaction" || part.type === "subtask");
243489
+ if (task2 && !lastComplete && (!current2 || msg.info.id !== current2)) {
243490
+ tasks.push(...task2);
243491
+ }
243419
243492
  }
243420
- throw e5;
243421
- });
243422
- const task = tasks.pop();
243423
- const taskMsg = task && msgs.find((msg) => msg.info.role === "user" && msg.parts.some((part) => part.id === task.id));
243424
- const taskUser = taskMsg?.info.role === "user" ? taskMsg.info : lastUser;
243425
- if (task?.type === "subtask") {
243426
- const taskTool = await TaskTool.init();
243427
- const taskModel = task.model ? await Provider.getModel(task.model.providerID, task.model.modelID) : model;
243428
- const assistantMessage = await Session.updateMessage({
243429
- id: Identifier.ascending("message"),
243430
- role: "assistant",
243431
- parentID: taskUser.id,
243432
- sessionID,
243433
- mode: task.agent,
243434
- agent: task.agent,
243435
- variant: taskUser.variant,
243436
- path: {
243437
- cwd: Instance.directory,
243438
- root: Instance.worktree
243439
- },
243440
- cost: 0,
243441
- tokens: {
243442
- input: 0,
243443
- output: 0,
243444
- reasoning: 0,
243445
- cache: { read: 0, write: 0 }
243446
- },
243447
- modelID: taskModel.id,
243448
- providerID: taskModel.providerID,
243449
- time: {
243450
- created: Date.now()
243493
+ if (currentMsg && !lastComplete) {
243494
+ const processed = msgs.filter((msg) => msg.info.role === "assistant" && msg.info.parentID === currentMsg.info.id && msg.parts.some((part) => part.type === "tool" && part.tool === TaskTool.id)).length;
243495
+ const remaining = currentMsg.parts.filter((part) => part.type === "subtask").slice(processed);
243496
+ tasks.push(...remaining);
243497
+ }
243498
+ if (!lastUser)
243499
+ throw new Error("No user message found in stream. This should never happen.");
243500
+ if (shouldExitLoop(lastUser, lastAssistant)) {
243501
+ log8.info("exiting loop", { sessionID });
243502
+ break;
243503
+ }
243504
+ step++;
243505
+ const model = await Provider.getModel(lastUser.model.providerID, lastUser.model.modelID).catch((e5) => {
243506
+ if (Provider.ModelNotFoundError.isInstance(e5)) {
243507
+ const hint = e5.data.suggestions?.length ? ` Did you mean: ${e5.data.suggestions.join(", ")}?` : "";
243508
+ Bus.publish(Session.Event.Error, {
243509
+ sessionID,
243510
+ error: new NamedError.Unknown({
243511
+ message: `Model not found: ${e5.data.providerID}/${e5.data.modelID}.${hint}`
243512
+ }).toObject(),
243513
+ viewID: Instance.viewID
243514
+ });
243451
243515
  }
243516
+ throw e5;
243452
243517
  });
243453
- let part = await Session.updatePart({
243454
- id: Identifier.ascending("part"),
243455
- messageID: assistantMessage.id,
243456
- sessionID: assistantMessage.sessionID,
243457
- type: "tool",
243458
- callID: ulid3(),
243459
- tool: TaskTool.id,
243460
- state: {
243461
- status: "running",
243462
- input: {
243463
- prompt: task.prompt,
243464
- description: task.description,
243465
- subagent_type: task.agent,
243466
- command: task.command
243518
+ const task = tasks.pop();
243519
+ const taskMsg = task && msgs.find((msg) => msg.info.role === "user" && msg.parts.some((part) => part.id === task.id));
243520
+ const taskUser = taskMsg?.info.role === "user" ? taskMsg.info : lastUser;
243521
+ if (task?.type === "subtask") {
243522
+ const taskTool = await TaskTool.init();
243523
+ const taskModel = task.model ? await Provider.getModel(task.model.providerID, task.model.modelID) : model;
243524
+ const assistantMessage = await Session.updateMessage({
243525
+ id: Identifier.ascending("message"),
243526
+ role: "assistant",
243527
+ parentID: taskUser.id,
243528
+ sessionID,
243529
+ mode: task.agent,
243530
+ agent: task.agent,
243531
+ variant: taskUser.variant,
243532
+ path: {
243533
+ cwd: Instance.directory,
243534
+ root: Instance.worktree
243467
243535
  },
243536
+ cost: 0,
243537
+ tokens: {
243538
+ input: 0,
243539
+ output: 0,
243540
+ reasoning: 0,
243541
+ cache: { read: 0, write: 0 }
243542
+ },
243543
+ modelID: taskModel.id,
243544
+ providerID: taskModel.providerID,
243468
243545
  time: {
243469
- start: Date.now()
243546
+ created: Date.now()
243547
+ }
243548
+ });
243549
+ let part = await Session.updatePart({
243550
+ id: Identifier.ascending("part"),
243551
+ messageID: assistantMessage.id,
243552
+ sessionID: assistantMessage.sessionID,
243553
+ type: "tool",
243554
+ callID: ulid3(),
243555
+ tool: TaskTool.id,
243556
+ state: {
243557
+ status: "running",
243558
+ input: {
243559
+ prompt: task.prompt,
243560
+ description: task.description,
243561
+ subagent_type: task.agent,
243562
+ command: task.command
243563
+ },
243564
+ time: {
243565
+ start: Date.now()
243566
+ }
243470
243567
  }
243568
+ });
243569
+ const taskArgs = {
243570
+ prompt: task.prompt,
243571
+ description: task.description,
243572
+ subagent_type: task.agent,
243573
+ command: task.command
243574
+ };
243575
+ await abortable(Plugin.trigger("tool.execute.before", {
243576
+ tool: "task",
243577
+ sessionID,
243578
+ callID: part.id
243579
+ }, { args: taskArgs }), abort2);
243580
+ let executionError;
243581
+ const taskAgent = await Agent.get(task.agent);
243582
+ const taskCtx = {
243583
+ agent: task.agent,
243584
+ messageID: assistantMessage.id,
243585
+ sessionID,
243586
+ abort: abort2,
243587
+ callID: part.callID,
243588
+ extra: { bypassAgentCheck: true },
243589
+ messages: msgs,
243590
+ async metadata(input2) {
243591
+ await Session.updatePart({
243592
+ ...part,
243593
+ type: "tool",
243594
+ state: {
243595
+ ...part.state,
243596
+ ...input2
243597
+ }
243598
+ });
243599
+ },
243600
+ async ask(req) {
243601
+ await PermissionNext.ask({
243602
+ ...req,
243603
+ sessionID,
243604
+ ruleset: PermissionNext.merge(taskAgent.permission, session.permission ?? [])
243605
+ });
243606
+ }
243607
+ };
243608
+ const result2 = await abortable(taskTool.execute(taskArgs, taskCtx), abort2).catch((error47) => {
243609
+ executionError = error47;
243610
+ log8.error("subtask execution failed", { error: error47, agent: task.agent, description: task.description });
243611
+ return;
243612
+ });
243613
+ const attachments = result2?.attachments?.map((attachment) => ({
243614
+ ...attachment,
243615
+ id: Identifier.ascending("part"),
243616
+ sessionID,
243617
+ messageID: assistantMessage.id
243618
+ }));
243619
+ await abortable(Plugin.trigger("tool.execute.after", {
243620
+ tool: "task",
243621
+ sessionID,
243622
+ callID: part.id,
243623
+ args: taskArgs
243624
+ }, result2), abort2);
243625
+ assistantMessage.finish = "tool-calls";
243626
+ assistantMessage.time.completed = Date.now();
243627
+ await Session.updateMessage(assistantMessage);
243628
+ if (result2 && part.state.status === "running") {
243629
+ await Session.updatePart({
243630
+ ...part,
243631
+ state: {
243632
+ status: "completed",
243633
+ input: part.state.input,
243634
+ title: result2.title,
243635
+ metadata: result2.metadata,
243636
+ output: result2.output,
243637
+ attachments,
243638
+ time: {
243639
+ ...part.state.time,
243640
+ end: Date.now()
243641
+ }
243642
+ }
243643
+ });
243471
243644
  }
243472
- });
243473
- const taskArgs = {
243474
- prompt: task.prompt,
243475
- description: task.description,
243476
- subagent_type: task.agent,
243477
- command: task.command
243478
- };
243479
- await abortable(Plugin.trigger("tool.execute.before", {
243480
- tool: "task",
243481
- sessionID,
243482
- callID: part.id
243483
- }, { args: taskArgs }), abort2);
243484
- let executionError;
243485
- const taskAgent = await Agent.get(task.agent);
243486
- const taskCtx = {
243487
- agent: task.agent,
243488
- messageID: assistantMessage.id,
243489
- sessionID,
243490
- abort: abort2,
243491
- callID: part.callID,
243492
- extra: { bypassAgentCheck: true },
243493
- messages: msgs,
243494
- async metadata(input2) {
243645
+ if (!result2) {
243495
243646
  await Session.updatePart({
243496
243647
  ...part,
243497
- type: "tool",
243498
243648
  state: {
243499
- ...part.state,
243500
- ...input2
243649
+ status: "error",
243650
+ error: executionError ? `Tool execution failed: ${executionError.message}` : "Tool execution failed",
243651
+ time: {
243652
+ start: part.state.status === "running" ? part.state.time.start : Date.now(),
243653
+ end: Date.now()
243654
+ },
243655
+ metadata: part.metadata,
243656
+ input: part.state.input
243501
243657
  }
243502
243658
  });
243503
- },
243504
- async ask(req) {
243505
- await PermissionNext.ask({
243506
- ...req,
243659
+ }
243660
+ if (task.command) {
243661
+ const summaryUserMsg = {
243662
+ id: Identifier.ascending("message"),
243663
+ sessionID,
243664
+ role: "user",
243665
+ time: {
243666
+ created: Date.now()
243667
+ },
243668
+ agent: taskUser.agent,
243669
+ model: taskUser.model
243670
+ };
243671
+ await Session.updateMessage(summaryUserMsg);
243672
+ await Session.updatePart({
243673
+ id: Identifier.ascending("part"),
243674
+ messageID: summaryUserMsg.id,
243507
243675
  sessionID,
243508
- ruleset: PermissionNext.merge(taskAgent.permission, session.permission ?? [])
243676
+ type: "text",
243677
+ text: "Summarize the task tool output above and continue with your task.",
243678
+ synthetic: true
243509
243679
  });
243510
243680
  }
243511
- };
243512
- const result2 = await abortable(taskTool.execute(taskArgs, taskCtx), abort2).catch((error47) => {
243513
- executionError = error47;
243514
- log8.error("subtask execution failed", { error: error47, agent: task.agent, description: task.description });
243515
- return;
243516
- });
243517
- const attachments = result2?.attachments?.map((attachment) => ({
243518
- ...attachment,
243519
- id: Identifier.ascending("part"),
243520
- sessionID,
243521
- messageID: assistantMessage.id
243522
- }));
243523
- await abortable(Plugin.trigger("tool.execute.after", {
243524
- tool: "task",
243525
- sessionID,
243526
- callID: part.id,
243527
- args: taskArgs
243528
- }, result2), abort2);
243529
- assistantMessage.finish = "tool-calls";
243530
- assistantMessage.time.completed = Date.now();
243531
- await Session.updateMessage(assistantMessage);
243532
- if (result2 && part.state.status === "running") {
243533
- await Session.updatePart({
243534
- ...part,
243535
- state: {
243536
- status: "completed",
243537
- input: part.state.input,
243538
- title: result2.title,
243539
- metadata: result2.metadata,
243540
- output: result2.output,
243541
- attachments,
243542
- time: {
243543
- ...part.state.time,
243544
- end: Date.now()
243545
- }
243546
- }
243547
- });
243681
+ continue;
243548
243682
  }
243549
- if (!result2) {
243550
- await Session.updatePart({
243551
- ...part,
243552
- state: {
243553
- status: "error",
243554
- error: executionError ? `Tool execution failed: ${executionError.message}` : "Tool execution failed",
243555
- time: {
243556
- start: part.state.status === "running" ? part.state.time.start : Date.now(),
243557
- end: Date.now()
243558
- },
243559
- metadata: part.metadata,
243560
- input: part.state.input
243561
- }
243683
+ if (task?.type === "compaction") {
243684
+ SessionStatus.busy(sessionID, "compacting");
243685
+ const result2 = await SessionCompaction.process({
243686
+ messages: msgs,
243687
+ parentID: taskUser.id,
243688
+ abort: abort2,
243689
+ sessionID,
243690
+ auto: task.auto,
243691
+ overflow: task.overflow
243562
243692
  });
243693
+ if (result2 === "stop")
243694
+ break;
243695
+ continue;
243563
243696
  }
243564
- if (task.command) {
243565
- const summaryUserMsg = {
243566
- id: Identifier.ascending("message"),
243567
- sessionID,
243568
- role: "user",
243569
- time: {
243570
- created: Date.now()
243571
- },
243572
- agent: taskUser.agent,
243573
- model: taskUser.model
243574
- };
243575
- await Session.updateMessage(summaryUserMsg);
243576
- await Session.updatePart({
243577
- id: Identifier.ascending("part"),
243578
- messageID: summaryUserMsg.id,
243697
+ if (lastFinished && lastFinished.summary !== true && await SessionCompaction.isOverflow({ tokens: lastFinished.tokens, model })) {
243698
+ SessionStatus.busy(sessionID, "compacting");
243699
+ await SessionCompaction.create({
243579
243700
  sessionID,
243580
- type: "text",
243581
- text: "Summarize the task tool output above and continue with your task.",
243582
- synthetic: true
243701
+ agent: lastUser.agent,
243702
+ model: lastUser.model,
243703
+ auto: true
243583
243704
  });
243705
+ continue;
243584
243706
  }
243585
- continue;
243586
- }
243587
- if (task?.type === "compaction") {
243588
- SessionStatus.busy(sessionID, "compacting");
243589
- const result2 = await SessionCompaction.process({
243707
+ const agent = await Agent.get(lastUser.agent);
243708
+ const maxSteps = agent.steps ?? Infinity;
243709
+ const isLastStep = step >= maxSteps;
243710
+ msgs = await insertReminders({
243590
243711
  messages: msgs,
243591
- parentID: taskUser.id,
243592
- abort: abort2,
243593
- sessionID,
243594
- auto: task.auto,
243595
- overflow: task.overflow
243712
+ agent,
243713
+ session
243596
243714
  });
243597
- if (result2 === "stop")
243598
- break;
243599
- continue;
243600
- }
243601
- if (lastFinished && lastFinished.summary !== true && await SessionCompaction.isOverflow({ tokens: lastFinished.tokens, model })) {
243602
- SessionStatus.busy(sessionID, "compacting");
243603
- await SessionCompaction.create({
243715
+ const processor = SessionProcessor.create({
243716
+ assistantMessage: await Session.updateMessage({
243717
+ id: Identifier.ascending("message"),
243718
+ parentID: lastUser.id,
243719
+ role: "assistant",
243720
+ mode: agent.name,
243721
+ agent: agent.name,
243722
+ variant: lastUser.variant,
243723
+ path: {
243724
+ cwd: Instance.directory,
243725
+ root: Instance.worktree
243726
+ },
243727
+ cost: 0,
243728
+ tokens: {
243729
+ input: 0,
243730
+ output: 0,
243731
+ reasoning: 0,
243732
+ cache: { read: 0, write: 0 }
243733
+ },
243734
+ modelID: model.id,
243735
+ providerID: model.providerID,
243736
+ time: {
243737
+ created: Date.now()
243738
+ },
243739
+ sessionID
243740
+ }),
243604
243741
  sessionID,
243605
- agent: lastUser.agent,
243606
- model: lastUser.model,
243607
- auto: true
243608
- });
243609
- continue;
243610
- }
243611
- const agent = await Agent.get(lastUser.agent);
243612
- const maxSteps = agent.steps ?? Infinity;
243613
- const isLastStep = step >= maxSteps;
243614
- msgs = await insertReminders({
243615
- messages: msgs,
243616
- agent,
243617
- session
243618
- });
243619
- const processor = SessionProcessor.create({
243620
- assistantMessage: await Session.updateMessage({
243621
- id: Identifier.ascending("message"),
243622
- parentID: lastUser.id,
243623
- role: "assistant",
243624
- mode: agent.name,
243625
- agent: agent.name,
243626
- variant: lastUser.variant,
243627
- path: {
243628
- cwd: Instance.directory,
243629
- root: Instance.worktree
243630
- },
243631
- cost: 0,
243632
- tokens: {
243633
- input: 0,
243634
- output: 0,
243635
- reasoning: 0,
243636
- cache: { read: 0, write: 0 }
243637
- },
243638
- modelID: model.id,
243639
- providerID: model.providerID,
243640
- time: {
243641
- created: Date.now()
243642
- },
243643
- sessionID
243644
- }),
243645
- sessionID,
243646
- model,
243647
- abort: abort2
243648
- });
243649
- using _4 = defer(() => InstructionPrompt.clear(processor.message.id));
243650
- const lastUserMsg = current2 ? msgs.find((m7) => m7.info.role === "user" && m7.info.id === current2) : msgs.findLast((m7) => m7.info.role === "user");
243651
- const bypassAgentCheck = lastUserMsg?.parts.some((p5) => p5.type === "agent") ?? false;
243652
- const tools = await resolveTools({
243653
- agent,
243654
- session,
243655
- model,
243656
- tools: lastUser.tools,
243657
- processor,
243658
- bypassAgentCheck,
243659
- messages: msgs
243660
- });
243661
- if (lastUser.format?.type === "json_schema") {
243662
- tools["StructuredOutput"] = createStructuredOutputTool({
243663
- schema: lastUser.format.schema,
243664
- onSuccess(output2) {
243665
- structuredOutput = output2;
243666
- }
243742
+ model,
243743
+ abort: abort2
243667
243744
  });
243668
- }
243669
- if (step === 1) {
243670
- SessionSummary.summarize({
243671
- sessionID,
243672
- messageID: lastUser.id
243673
- }).catch((error47) => {
243674
- log8.error("failed to summarize session", { sessionID, error: error47 });
243745
+ const _4 = __using(__stack, defer(() => InstructionPrompt.clear(processor.message.id)), 0);
243746
+ const lastUserMsg = current2 ? msgs.find((m7) => m7.info.role === "user" && m7.info.id === current2) : msgs.findLast((m7) => m7.info.role === "user");
243747
+ const bypassAgentCheck = lastUserMsg?.parts.some((p5) => p5.type === "agent") ?? false;
243748
+ const tools = await resolveTools({
243749
+ agent,
243750
+ session,
243751
+ model,
243752
+ tools: lastUser.tools,
243753
+ processor,
243754
+ bypassAgentCheck,
243755
+ messages: msgs
243675
243756
  });
243676
- }
243677
- if (mode2 === "injection" && step > 1 && lastFinished) {
243678
- for (const msg of msgs) {
243679
- if (msg.info.role !== "user" || msg.info.id <= lastFinished.id)
243680
- continue;
243681
- for (const part of msg.parts) {
243682
- if (part.type !== "text" || part.ignored || part.synthetic)
243683
- continue;
243684
- if (!part.text.trim())
243757
+ if (lastUser.format?.type === "json_schema") {
243758
+ tools["StructuredOutput"] = createStructuredOutputTool({
243759
+ schema: lastUser.format.schema,
243760
+ onSuccess(output2) {
243761
+ structuredOutput = output2;
243762
+ }
243763
+ });
243764
+ }
243765
+ if (step === 1) {
243766
+ SessionSummary.summarize({
243767
+ sessionID,
243768
+ messageID: lastUser.id
243769
+ }).catch((error47) => {
243770
+ log8.error("failed to summarize session", { sessionID, error: error47 });
243771
+ });
243772
+ }
243773
+ if (mode2 === "injection" && step > 1 && lastFinished) {
243774
+ for (const msg of msgs) {
243775
+ if (msg.info.role !== "user" || msg.info.id <= lastFinished.id)
243685
243776
  continue;
243686
- part.text = [
243687
- "<system-reminder>",
243688
- "The user sent the following message:",
243689
- part.text,
243690
- "",
243691
- "Please address this message and continue with your tasks.",
243692
- "</system-reminder>"
243693
- ].join(`
243777
+ for (const part of msg.parts) {
243778
+ if (part.type !== "text" || part.ignored || part.synthetic)
243779
+ continue;
243780
+ if (!part.text.trim())
243781
+ continue;
243782
+ part.text = [
243783
+ "<system-reminder>",
243784
+ "The user sent the following message:",
243785
+ part.text,
243786
+ "",
243787
+ "Please address this message and continue with your tasks.",
243788
+ "</system-reminder>"
243789
+ ].join(`
243694
243790
  `);
243791
+ }
243695
243792
  }
243696
243793
  }
243697
- }
243698
- await Plugin.trigger("experimental.chat.messages.transform", {}, { messages: msgs });
243699
- const system = [...await SystemPrompt.environment(model), ...await InstructionPrompt.system()];
243700
- const format5 = lastUser.format ?? { type: "text" };
243701
- if (format5.type === "json_schema") {
243702
- system.push(STRUCTURED_OUTPUT_SYSTEM_PROMPT);
243703
- }
243704
- const result = await processor.process({
243705
- user: lastUser,
243706
- agent,
243707
- abort: abort2,
243708
- sessionID,
243709
- system,
243710
- messages: [
243711
- ...MessageV2.toModelMessages(msgs, model),
243712
- ...isLastStep ? [
243713
- {
243714
- role: "assistant",
243715
- content: max_steps_default
243716
- }
243717
- ] : []
243718
- ],
243719
- tools,
243720
- model,
243721
- toolChoice: format5.type === "json_schema" ? "required" : undefined
243722
- });
243723
- if (structuredOutput !== undefined) {
243724
- processor.message.structured = structuredOutput;
243725
- processor.message.finish = processor.message.finish ?? "stop";
243726
- await Session.updateMessage(processor.message);
243727
- break;
243728
- }
243729
- const modelFinished = processor.message.finish && !["tool-calls", "unknown"].includes(processor.message.finish);
243730
- if (modelFinished && !processor.message.error) {
243794
+ await Plugin.trigger("experimental.chat.messages.transform", {}, { messages: msgs });
243795
+ const system = [...await SystemPrompt.environment(model), ...await InstructionPrompt.system()];
243796
+ const format5 = lastUser.format ?? { type: "text" };
243731
243797
  if (format5.type === "json_schema") {
243732
- processor.message.error = new MessageV2.StructuredOutputError({
243733
- message: "Model did not produce structured output",
243734
- retries: 0
243735
- }).toObject();
243736
- await Session.updateMessage(processor.message);
243737
- break;
243798
+ system.push(STRUCTURED_OUTPUT_SYSTEM_PROMPT);
243738
243799
  }
243739
- }
243740
- if (held(state2()[sessionID], lastUser?.id)) {
243741
- next2 = "hold";
243742
- return;
243743
- }
243744
- if (result === "stop")
243745
- break;
243746
- if (result === "compact") {
243747
- await SessionCompaction.create({
243800
+ const result = await processor.process({
243801
+ user: lastUser,
243802
+ agent,
243803
+ abort: abort2,
243748
243804
  sessionID,
243749
- agent: lastUser.agent,
243750
- model: lastUser.model,
243751
- auto: true,
243752
- overflow: !processor.message.finish
243805
+ system,
243806
+ messages: [
243807
+ ...MessageV2.toModelMessages(msgs, model),
243808
+ ...isLastStep ? [
243809
+ {
243810
+ role: "assistant",
243811
+ content: max_steps_default
243812
+ }
243813
+ ] : []
243814
+ ],
243815
+ tools,
243816
+ model,
243817
+ toolChoice: format5.type === "json_schema" ? "required" : undefined
243753
243818
  });
243819
+ if (structuredOutput !== undefined) {
243820
+ processor.message.structured = structuredOutput;
243821
+ processor.message.finish = processor.message.finish ?? "stop";
243822
+ await Session.updateMessage(processor.message);
243823
+ break;
243824
+ }
243825
+ const modelFinished = processor.message.finish && !["tool-calls", "unknown"].includes(processor.message.finish);
243826
+ if (modelFinished && !processor.message.error) {
243827
+ if (format5.type === "json_schema") {
243828
+ processor.message.error = new MessageV2.StructuredOutputError({
243829
+ message: "Model did not produce structured output",
243830
+ retries: 0
243831
+ }).toObject();
243832
+ await Session.updateMessage(processor.message);
243833
+ break;
243834
+ }
243835
+ }
243836
+ if (held(state2()[sessionID], lastUser?.id)) {
243837
+ next2 = "hold";
243838
+ return;
243839
+ }
243840
+ if (result === "stop")
243841
+ break;
243842
+ if (result === "compact") {
243843
+ await SessionCompaction.create({
243844
+ sessionID,
243845
+ agent: lastUser.agent,
243846
+ model: lastUser.model,
243847
+ auto: true,
243848
+ overflow: !processor.message.finish
243849
+ });
243850
+ }
243851
+ continue;
243852
+ } catch (_catch3) {
243853
+ var _err = _catch3, _hasErr = 1;
243854
+ } finally {
243855
+ __callDispose(__stack, _err, _hasErr);
243754
243856
  }
243755
- continue;
243756
243857
  }
243757
243858
  SessionCompaction.prune({ sessionID });
243758
243859
  const item = await latestAssistant(sessionID);
@@ -243827,155 +243928,162 @@ var init_prompt = __esm(async () => {
243827
243928
  });
243828
243929
  }
243829
243930
  async function resolveTools(input) {
243830
- using _4 = log8.time("resolveTools");
243831
- const tools = {};
243832
- const context2 = (args2, options2) => ({
243833
- sessionID: input.session.id,
243834
- abort: options2.abortSignal,
243835
- messageID: input.processor.message.id,
243836
- callID: options2.toolCallId,
243837
- extra: { model: input.model, bypassAgentCheck: input.bypassAgentCheck },
243838
- agent: input.agent.name,
243839
- messages: input.messages,
243840
- metadata: async (val) => {
243841
- const match2 = input.processor.partFromToolCall(options2.toolCallId);
243842
- if (match2 && match2.state.status === "running") {
243843
- await Session.updatePart({
243844
- ...match2,
243845
- state: {
243846
- title: val.title,
243847
- metadata: val.metadata,
243848
- status: "running",
243849
- input: args2,
243850
- time: {
243851
- start: Date.now()
243931
+ let __stack = [];
243932
+ try {
243933
+ const _4 = __using(__stack, log8.time("resolveTools"), 0);
243934
+ const tools = {};
243935
+ const context2 = (args2, options2) => ({
243936
+ sessionID: input.session.id,
243937
+ abort: options2.abortSignal,
243938
+ messageID: input.processor.message.id,
243939
+ callID: options2.toolCallId,
243940
+ extra: { model: input.model, bypassAgentCheck: input.bypassAgentCheck },
243941
+ agent: input.agent.name,
243942
+ messages: input.messages,
243943
+ metadata: async (val) => {
243944
+ const match2 = input.processor.partFromToolCall(options2.toolCallId);
243945
+ if (match2 && match2.state.status === "running") {
243946
+ await Session.updatePart({
243947
+ ...match2,
243948
+ state: {
243949
+ title: val.title,
243950
+ metadata: val.metadata,
243951
+ status: "running",
243952
+ input: args2,
243953
+ time: {
243954
+ start: Date.now()
243955
+ }
243852
243956
  }
243853
- }
243957
+ });
243958
+ }
243959
+ },
243960
+ async ask(req) {
243961
+ await PermissionNext.ask({
243962
+ ...req,
243963
+ sessionID: input.session.id,
243964
+ tool: { messageID: input.processor.message.id, callID: options2.toolCallId },
243965
+ ruleset: PermissionNext.merge(input.agent.permission, input.session.permission ?? [])
243854
243966
  });
243855
243967
  }
243856
- },
243857
- async ask(req) {
243858
- await PermissionNext.ask({
243859
- ...req,
243860
- sessionID: input.session.id,
243861
- tool: { messageID: input.processor.message.id, callID: options2.toolCallId },
243862
- ruleset: PermissionNext.merge(input.agent.permission, input.session.permission ?? [])
243968
+ });
243969
+ for (const item of await ToolRegistry.tools({ modelID: input.model.api.id, providerID: input.model.providerID }, input.agent)) {
243970
+ const schema3 = ProviderTransform.schema(input.model, zod_default.toJSONSchema(item.parameters));
243971
+ tools[item.id] = tool({
243972
+ id: item.id,
243973
+ description: item.description,
243974
+ inputSchema: jsonSchema(schema3),
243975
+ async execute(args2, options2) {
243976
+ const ctx = context2(args2, options2);
243977
+ await abortable(Plugin.trigger("tool.execute.before", {
243978
+ tool: item.id,
243979
+ sessionID: ctx.sessionID,
243980
+ callID: ctx.callID
243981
+ }, {
243982
+ args: args2
243983
+ }), ctx.abort);
243984
+ const result = await abortable(item.execute(args2, ctx), ctx.abort);
243985
+ const output2 = {
243986
+ ...result,
243987
+ attachments: result.attachments?.map((attachment) => ({
243988
+ ...attachment,
243989
+ id: Identifier.ascending("part"),
243990
+ sessionID: ctx.sessionID,
243991
+ messageID: input.processor.message.id
243992
+ }))
243993
+ };
243994
+ await abortable(Plugin.trigger("tool.execute.after", {
243995
+ tool: item.id,
243996
+ sessionID: ctx.sessionID,
243997
+ callID: ctx.callID,
243998
+ args: args2
243999
+ }, output2), ctx.abort);
244000
+ return output2;
244001
+ }
243863
244002
  });
243864
244003
  }
243865
- });
243866
- for (const item of await ToolRegistry.tools({ modelID: input.model.api.id, providerID: input.model.providerID }, input.agent)) {
243867
- const schema3 = ProviderTransform.schema(input.model, zod_default.toJSONSchema(item.parameters));
243868
- tools[item.id] = tool({
243869
- id: item.id,
243870
- description: item.description,
243871
- inputSchema: jsonSchema(schema3),
243872
- async execute(args2, options2) {
243873
- const ctx = context2(args2, options2);
244004
+ for (const [key, item] of Object.entries(await MCP.tools())) {
244005
+ const execute = item.execute;
244006
+ if (!execute)
244007
+ continue;
244008
+ const transformed = ProviderTransform.schema(input.model, asSchema(item.inputSchema).jsonSchema);
244009
+ item.inputSchema = jsonSchema(transformed);
244010
+ item.execute = async (args2, opts) => {
244011
+ const ctx = context2(args2, opts);
243874
244012
  await abortable(Plugin.trigger("tool.execute.before", {
243875
- tool: item.id,
244013
+ tool: key,
243876
244014
  sessionID: ctx.sessionID,
243877
- callID: ctx.callID
244015
+ callID: opts.toolCallId
243878
244016
  }, {
243879
244017
  args: args2
243880
244018
  }), ctx.abort);
243881
- const result = await abortable(item.execute(args2, ctx), ctx.abort);
243882
- const output2 = {
243883
- ...result,
243884
- attachments: result.attachments?.map((attachment) => ({
243885
- ...attachment,
243886
- id: Identifier.ascending("part"),
243887
- sessionID: ctx.sessionID,
243888
- messageID: input.processor.message.id
243889
- }))
243890
- };
244019
+ await ctx.ask({
244020
+ permission: key,
244021
+ metadata: {},
244022
+ patterns: ["*"],
244023
+ always: ["*"]
244024
+ });
244025
+ const result = await abortable(execute(args2, opts), ctx.abort);
243891
244026
  await abortable(Plugin.trigger("tool.execute.after", {
243892
- tool: item.id,
244027
+ tool: key,
243893
244028
  sessionID: ctx.sessionID,
243894
- callID: ctx.callID,
244029
+ callID: opts.toolCallId,
243895
244030
  args: args2
243896
- }, output2), ctx.abort);
243897
- return output2;
243898
- }
243899
- });
243900
- }
243901
- for (const [key, item] of Object.entries(await MCP.tools())) {
243902
- const execute = item.execute;
243903
- if (!execute)
243904
- continue;
243905
- const transformed = ProviderTransform.schema(input.model, asSchema(item.inputSchema).jsonSchema);
243906
- item.inputSchema = jsonSchema(transformed);
243907
- item.execute = async (args2, opts) => {
243908
- const ctx = context2(args2, opts);
243909
- await abortable(Plugin.trigger("tool.execute.before", {
243910
- tool: key,
243911
- sessionID: ctx.sessionID,
243912
- callID: opts.toolCallId
243913
- }, {
243914
- args: args2
243915
- }), ctx.abort);
243916
- await ctx.ask({
243917
- permission: key,
243918
- metadata: {},
243919
- patterns: ["*"],
243920
- always: ["*"]
243921
- });
243922
- const result = await abortable(execute(args2, opts), ctx.abort);
243923
- await abortable(Plugin.trigger("tool.execute.after", {
243924
- tool: key,
243925
- sessionID: ctx.sessionID,
243926
- callID: opts.toolCallId,
243927
- args: args2
243928
- }, result), ctx.abort);
243929
- const textParts = [];
243930
- const attachments = [];
243931
- for (const contentItem of result.content) {
243932
- if (contentItem.type === "text") {
243933
- textParts.push(contentItem.text);
243934
- } else if (contentItem.type === "image") {
243935
- attachments.push({
243936
- type: "file",
243937
- mime: contentItem.mimeType,
243938
- url: `data:${contentItem.mimeType};base64,${contentItem.data}`
243939
- });
243940
- } else if (contentItem.type === "resource") {
243941
- const { resource } = contentItem;
243942
- if (resource.text) {
243943
- textParts.push(resource.text);
243944
- }
243945
- if (resource.blob) {
244031
+ }, result), ctx.abort);
244032
+ const textParts = [];
244033
+ const attachments = [];
244034
+ for (const contentItem of result.content) {
244035
+ if (contentItem.type === "text") {
244036
+ textParts.push(contentItem.text);
244037
+ } else if (contentItem.type === "image") {
243946
244038
  attachments.push({
243947
244039
  type: "file",
243948
- mime: resource.mimeType ?? "application/octet-stream",
243949
- url: `data:${resource.mimeType ?? "application/octet-stream"};base64,${resource.blob}`,
243950
- filename: resource.uri
244040
+ mime: contentItem.mimeType,
244041
+ url: `data:${contentItem.mimeType};base64,${contentItem.data}`
243951
244042
  });
244043
+ } else if (contentItem.type === "resource") {
244044
+ const { resource } = contentItem;
244045
+ if (resource.text) {
244046
+ textParts.push(resource.text);
244047
+ }
244048
+ if (resource.blob) {
244049
+ attachments.push({
244050
+ type: "file",
244051
+ mime: resource.mimeType ?? "application/octet-stream",
244052
+ url: `data:${resource.mimeType ?? "application/octet-stream"};base64,${resource.blob}`,
244053
+ filename: resource.uri
244054
+ });
244055
+ }
243952
244056
  }
243953
244057
  }
243954
- }
243955
- const truncated = await Truncate.output(textParts.join(`
244058
+ const truncated = await Truncate.output(textParts.join(`
243956
244059
 
243957
244060
  `), {}, input.agent);
243958
- const metadata2 = {
243959
- ...result.metadata ?? {},
243960
- truncated: truncated.truncated,
243961
- ...truncated.truncated && { outputPath: truncated.outputPath }
243962
- };
243963
- return {
243964
- title: "",
243965
- metadata: metadata2,
243966
- output: truncated.content,
243967
- attachments: attachments.map((attachment) => ({
243968
- ...attachment,
243969
- id: Identifier.ascending("part"),
243970
- sessionID: ctx.sessionID,
243971
- messageID: input.processor.message.id
243972
- })),
243973
- content: result.content
244061
+ const metadata2 = {
244062
+ ...result.metadata ?? {},
244063
+ truncated: truncated.truncated,
244064
+ ...truncated.truncated && { outputPath: truncated.outputPath }
244065
+ };
244066
+ return {
244067
+ title: "",
244068
+ metadata: metadata2,
244069
+ output: truncated.content,
244070
+ attachments: attachments.map((attachment) => ({
244071
+ ...attachment,
244072
+ id: Identifier.ascending("part"),
244073
+ sessionID: ctx.sessionID,
244074
+ messageID: input.processor.message.id
244075
+ })),
244076
+ content: result.content
244077
+ };
243974
244078
  };
243975
- };
243976
- tools[key] = item;
244079
+ tools[key] = item;
244080
+ }
244081
+ return tools;
244082
+ } catch (_catch3) {
244083
+ var _err = _catch3, _hasErr = 1;
244084
+ } finally {
244085
+ __callDispose(__stack, _err, _hasErr);
243977
244086
  }
243978
- return tools;
243979
244087
  }
243980
244088
  SessionPrompt.resolveTools = resolveTools;
243981
244089
  function createStructuredOutputTool(input) {
@@ -244002,321 +244110,328 @@ var init_prompt = __esm(async () => {
244002
244110
  }
244003
244111
  SessionPrompt.createStructuredOutputTool = createStructuredOutputTool;
244004
244112
  async function createUserMessage(input) {
244005
- const agent = await Agent.get(input.agent ?? await Agent.defaultAgent());
244006
- const model = input.model ?? agent.model ?? await lastModel(input.sessionID);
244007
- const full = !input.variant && agent.variant ? await Provider.getModel(model.providerID, model.modelID).catch(() => {
244008
- return;
244009
- }) : undefined;
244010
- const variant = input.variant ?? (agent.variant && full?.variants?.[agent.variant] ? agent.variant : undefined);
244011
- const info3 = {
244012
- id: input.messageID ?? Identifier.ascending("message"),
244013
- role: "user",
244014
- sessionID: input.sessionID,
244015
- time: {
244016
- created: Date.now()
244017
- },
244018
- tools: input.tools,
244019
- agent: agent.name,
244020
- model,
244021
- system: input.system,
244022
- format: input.format,
244023
- variant
244024
- };
244025
- using _4 = defer(() => InstructionPrompt.clear(info3.id));
244026
- const assign = (part) => ({
244027
- ...part,
244028
- id: part.id ?? Identifier.ascending("part")
244029
- });
244030
- const parts2 = await Promise.all(input.parts.map(async (part) => {
244031
- if (part.type === "file") {
244032
- if (part.source?.type === "resource") {
244033
- const { clientName, uri } = part.source;
244034
- log8.info("mcp resource", { clientName, uri, mime: part.mime });
244035
- const pieces = [
244036
- {
244037
- messageID: info3.id,
244038
- sessionID: input.sessionID,
244039
- type: "text",
244040
- synthetic: true,
244041
- text: `Reading MCP resource: ${part.filename} (${uri})`
244042
- }
244043
- ];
244044
- try {
244045
- const resourceContent = await MCP.readResource(clientName, uri);
244046
- if (!resourceContent) {
244047
- throw new Error(`Resource not found: ${clientName}/${uri}`);
244048
- }
244049
- const contents = Array.isArray(resourceContent.contents) ? resourceContent.contents : [resourceContent.contents];
244050
- for (const content of contents) {
244051
- if ("text" in content && content.text) {
244052
- pieces.push({
244053
- messageID: info3.id,
244054
- sessionID: input.sessionID,
244055
- type: "text",
244056
- synthetic: true,
244057
- text: content.text
244058
- });
244059
- } else if ("blob" in content && content.blob) {
244060
- const mimeType = "mimeType" in content ? content.mimeType : part.mime;
244061
- pieces.push({
244062
- messageID: info3.id,
244063
- sessionID: input.sessionID,
244064
- type: "text",
244065
- synthetic: true,
244066
- text: `[Binary content: ${mimeType}]`
244067
- });
244113
+ let __stack = [];
244114
+ try {
244115
+ const agent = await Agent.get(input.agent ?? await Agent.defaultAgent());
244116
+ const model = input.model ?? agent.model ?? await lastModel(input.sessionID);
244117
+ const full = !input.variant && agent.variant ? await Provider.getModel(model.providerID, model.modelID).catch(() => {
244118
+ return;
244119
+ }) : undefined;
244120
+ const variant = input.variant ?? (agent.variant && full?.variants?.[agent.variant] ? agent.variant : undefined);
244121
+ const info3 = {
244122
+ id: input.messageID ?? Identifier.ascending("message"),
244123
+ role: "user",
244124
+ sessionID: input.sessionID,
244125
+ time: {
244126
+ created: Date.now()
244127
+ },
244128
+ tools: input.tools,
244129
+ agent: agent.name,
244130
+ model,
244131
+ system: input.system,
244132
+ format: input.format,
244133
+ variant
244134
+ };
244135
+ const _4 = __using(__stack, defer(() => InstructionPrompt.clear(info3.id)), 0);
244136
+ const assign = (part) => ({
244137
+ ...part,
244138
+ id: part.id ?? Identifier.ascending("part")
244139
+ });
244140
+ const parts2 = await Promise.all(input.parts.map(async (part) => {
244141
+ if (part.type === "file") {
244142
+ if (part.source?.type === "resource") {
244143
+ const { clientName, uri } = part.source;
244144
+ log8.info("mcp resource", { clientName, uri, mime: part.mime });
244145
+ const pieces = [
244146
+ {
244147
+ messageID: info3.id,
244148
+ sessionID: input.sessionID,
244149
+ type: "text",
244150
+ synthetic: true,
244151
+ text: `Reading MCP resource: ${part.filename} (${uri})`
244068
244152
  }
244069
- }
244070
- pieces.push({
244071
- ...part,
244072
- messageID: info3.id,
244073
- sessionID: input.sessionID
244074
- });
244075
- } catch (error47) {
244076
- log8.error("failed to read MCP resource", { error: error47, clientName, uri });
244077
- const message = error47 instanceof Error ? error47.message : String(error47);
244078
- pieces.push({
244079
- messageID: info3.id,
244080
- sessionID: input.sessionID,
244081
- type: "text",
244082
- synthetic: true,
244083
- text: `Failed to read MCP resource ${part.filename}: ${message}`
244084
- });
244085
- }
244086
- return pieces;
244087
- }
244088
- const url3 = new URL(part.url);
244089
- switch (url3.protocol) {
244090
- case "data:":
244091
- if (part.mime === "text/plain") {
244092
- return [
244093
- {
244094
- messageID: info3.id,
244095
- sessionID: input.sessionID,
244096
- type: "text",
244097
- synthetic: true,
244098
- text: `Called the Read tool with the following input: ${JSON.stringify({ filePath: part.filename })}`
244099
- },
244100
- {
244101
- messageID: info3.id,
244102
- sessionID: input.sessionID,
244103
- type: "text",
244104
- synthetic: true,
244105
- text: Buffer.from(part.url, "base64url").toString()
244106
- },
244107
- {
244108
- ...part,
244109
- messageID: info3.id,
244110
- sessionID: input.sessionID
244153
+ ];
244154
+ try {
244155
+ const resourceContent = await MCP.readResource(clientName, uri);
244156
+ if (!resourceContent) {
244157
+ throw new Error(`Resource not found: ${clientName}/${uri}`);
244158
+ }
244159
+ const contents = Array.isArray(resourceContent.contents) ? resourceContent.contents : [resourceContent.contents];
244160
+ for (const content of contents) {
244161
+ if ("text" in content && content.text) {
244162
+ pieces.push({
244163
+ messageID: info3.id,
244164
+ sessionID: input.sessionID,
244165
+ type: "text",
244166
+ synthetic: true,
244167
+ text: content.text
244168
+ });
244169
+ } else if ("blob" in content && content.blob) {
244170
+ const mimeType = "mimeType" in content ? content.mimeType : part.mime;
244171
+ pieces.push({
244172
+ messageID: info3.id,
244173
+ sessionID: input.sessionID,
244174
+ type: "text",
244175
+ synthetic: true,
244176
+ text: `[Binary content: ${mimeType}]`
244177
+ });
244111
244178
  }
244112
- ];
244113
- }
244114
- break;
244115
- case "file:":
244116
- log8.info("file", { mime: part.mime });
244117
- const filepath = fileURLToPath9(part.url);
244118
- const s7 = Filesystem.stat(filepath);
244119
- if (s7?.isDirectory()) {
244120
- part.mime = "application/x-directory";
244179
+ }
244180
+ pieces.push({
244181
+ ...part,
244182
+ messageID: info3.id,
244183
+ sessionID: input.sessionID
244184
+ });
244185
+ } catch (error47) {
244186
+ log8.error("failed to read MCP resource", { error: error47, clientName, uri });
244187
+ const message = error47 instanceof Error ? error47.message : String(error47);
244188
+ pieces.push({
244189
+ messageID: info3.id,
244190
+ sessionID: input.sessionID,
244191
+ type: "text",
244192
+ synthetic: true,
244193
+ text: `Failed to read MCP resource ${part.filename}: ${message}`
244194
+ });
244121
244195
  }
244122
- if (part.mime === "text/plain") {
244123
- let offset = undefined;
244124
- let limit2 = undefined;
244125
- const range2 = {
244126
- start: url3.searchParams.get("start"),
244127
- end: url3.searchParams.get("end")
244128
- };
244129
- if (range2.start != null) {
244130
- const filePathURI = part.url.split("?")[0];
244131
- let start3 = parseInt(range2.start);
244132
- let end = range2.end ? parseInt(range2.end) : undefined;
244133
- if (start3 === end) {
244134
- const symbols = await LSP.documentSymbol(filePathURI).catch(() => []);
244135
- for (const symbol16 of symbols) {
244136
- let range3;
244137
- if ("range" in symbol16) {
244138
- range3 = symbol16.range;
244139
- } else if ("location" in symbol16) {
244140
- range3 = symbol16.location.range;
244141
- }
244142
- if (range3?.start?.line && range3?.start?.line === start3) {
244143
- start3 = range3.start.line;
244144
- end = range3?.end?.line ?? start3;
244145
- break;
244196
+ return pieces;
244197
+ }
244198
+ const url3 = new URL(part.url);
244199
+ switch (url3.protocol) {
244200
+ case "data:":
244201
+ if (part.mime === "text/plain") {
244202
+ return [
244203
+ {
244204
+ messageID: info3.id,
244205
+ sessionID: input.sessionID,
244206
+ type: "text",
244207
+ synthetic: true,
244208
+ text: `Called the Read tool with the following input: ${JSON.stringify({ filePath: part.filename })}`
244209
+ },
244210
+ {
244211
+ messageID: info3.id,
244212
+ sessionID: input.sessionID,
244213
+ type: "text",
244214
+ synthetic: true,
244215
+ text: Buffer.from(part.url, "base64url").toString()
244216
+ },
244217
+ {
244218
+ ...part,
244219
+ messageID: info3.id,
244220
+ sessionID: input.sessionID
244221
+ }
244222
+ ];
244223
+ }
244224
+ break;
244225
+ case "file:":
244226
+ log8.info("file", { mime: part.mime });
244227
+ const filepath = fileURLToPath9(part.url);
244228
+ const s7 = Filesystem.stat(filepath);
244229
+ if (s7?.isDirectory()) {
244230
+ part.mime = "application/x-directory";
244231
+ }
244232
+ if (part.mime === "text/plain") {
244233
+ let offset = undefined;
244234
+ let limit2 = undefined;
244235
+ const range2 = {
244236
+ start: url3.searchParams.get("start"),
244237
+ end: url3.searchParams.get("end")
244238
+ };
244239
+ if (range2.start != null) {
244240
+ const filePathURI = part.url.split("?")[0];
244241
+ let start3 = parseInt(range2.start);
244242
+ let end = range2.end ? parseInt(range2.end) : undefined;
244243
+ if (start3 === end) {
244244
+ const symbols = await LSP.documentSymbol(filePathURI).catch(() => []);
244245
+ for (const symbol16 of symbols) {
244246
+ let range3;
244247
+ if ("range" in symbol16) {
244248
+ range3 = symbol16.range;
244249
+ } else if ("location" in symbol16) {
244250
+ range3 = symbol16.location.range;
244251
+ }
244252
+ if (range3?.start?.line && range3?.start?.line === start3) {
244253
+ start3 = range3.start.line;
244254
+ end = range3?.end?.line ?? start3;
244255
+ break;
244256
+ }
244146
244257
  }
244147
244258
  }
244259
+ offset = Math.max(start3, 1);
244260
+ if (end) {
244261
+ limit2 = end - (offset - 1);
244262
+ }
244148
244263
  }
244149
- offset = Math.max(start3, 1);
244150
- if (end) {
244151
- limit2 = end - (offset - 1);
244152
- }
244264
+ const args2 = { filePath: filepath, offset, limit: limit2 };
244265
+ const pieces = [
244266
+ {
244267
+ messageID: info3.id,
244268
+ sessionID: input.sessionID,
244269
+ type: "text",
244270
+ synthetic: true,
244271
+ text: `Called the Read tool with the following input: ${JSON.stringify(args2)}`
244272
+ }
244273
+ ];
244274
+ await ReadTool.init().then(async (t5) => {
244275
+ const model2 = await Provider.getModel(info3.model.providerID, info3.model.modelID);
244276
+ const readCtx = {
244277
+ sessionID: input.sessionID,
244278
+ abort: new AbortController().signal,
244279
+ agent: input.agent,
244280
+ messageID: info3.id,
244281
+ extra: { bypassCwdCheck: true, model: model2 },
244282
+ messages: [],
244283
+ metadata: async () => {},
244284
+ ask: async () => {}
244285
+ };
244286
+ const result = await t5.execute(args2, readCtx);
244287
+ pieces.push({
244288
+ messageID: info3.id,
244289
+ sessionID: input.sessionID,
244290
+ type: "text",
244291
+ synthetic: true,
244292
+ text: result.output
244293
+ });
244294
+ if (result.attachments?.length) {
244295
+ pieces.push(...result.attachments.map((attachment) => ({
244296
+ ...attachment,
244297
+ synthetic: true,
244298
+ filename: attachment.filename ?? part.filename,
244299
+ messageID: info3.id,
244300
+ sessionID: input.sessionID
244301
+ })));
244302
+ } else {
244303
+ pieces.push({
244304
+ ...part,
244305
+ messageID: info3.id,
244306
+ sessionID: input.sessionID
244307
+ });
244308
+ }
244309
+ }).catch((error47) => {
244310
+ log8.error("failed to read file", { error: error47 });
244311
+ const message = error47 instanceof Error ? error47.message : error47.toString();
244312
+ Bus.publish(Session.Event.Error, {
244313
+ sessionID: input.sessionID,
244314
+ error: new NamedError.Unknown({
244315
+ message
244316
+ }).toObject(),
244317
+ viewID: Instance.viewID
244318
+ });
244319
+ pieces.push({
244320
+ messageID: info3.id,
244321
+ sessionID: input.sessionID,
244322
+ type: "text",
244323
+ synthetic: true,
244324
+ text: `Read tool failed to read ${filepath} with the following error: ${message}`
244325
+ });
244326
+ });
244327
+ return pieces;
244153
244328
  }
244154
- const args2 = { filePath: filepath, offset, limit: limit2 };
244155
- const pieces = [
244156
- {
244157
- messageID: info3.id,
244158
- sessionID: input.sessionID,
244159
- type: "text",
244160
- synthetic: true,
244161
- text: `Called the Read tool with the following input: ${JSON.stringify(args2)}`
244162
- }
244163
- ];
244164
- await ReadTool.init().then(async (t5) => {
244165
- const model2 = await Provider.getModel(info3.model.providerID, info3.model.modelID);
244166
- const readCtx = {
244329
+ if (part.mime === "application/x-directory") {
244330
+ const args2 = { filePath: filepath };
244331
+ const listCtx = {
244167
244332
  sessionID: input.sessionID,
244168
244333
  abort: new AbortController().signal,
244169
244334
  agent: input.agent,
244170
244335
  messageID: info3.id,
244171
- extra: { bypassCwdCheck: true, model: model2 },
244336
+ extra: { bypassCwdCheck: true },
244172
244337
  messages: [],
244173
244338
  metadata: async () => {},
244174
244339
  ask: async () => {}
244175
244340
  };
244176
- const result = await t5.execute(args2, readCtx);
244177
- pieces.push({
244178
- messageID: info3.id,
244179
- sessionID: input.sessionID,
244180
- type: "text",
244181
- synthetic: true,
244182
- text: result.output
244183
- });
244184
- if (result.attachments?.length) {
244185
- pieces.push(...result.attachments.map((attachment) => ({
244186
- ...attachment,
244341
+ const result = await ReadTool.init().then((t5) => t5.execute(args2, listCtx));
244342
+ return [
244343
+ {
244344
+ messageID: info3.id,
244345
+ sessionID: input.sessionID,
244346
+ type: "text",
244187
244347
  synthetic: true,
244188
- filename: attachment.filename ?? part.filename,
244348
+ text: `Called the Read tool with the following input: ${JSON.stringify(args2)}`
244349
+ },
244350
+ {
244189
244351
  messageID: info3.id,
244190
- sessionID: input.sessionID
244191
- })));
244192
- } else {
244193
- pieces.push({
244352
+ sessionID: input.sessionID,
244353
+ type: "text",
244354
+ synthetic: true,
244355
+ text: result.output
244356
+ },
244357
+ {
244194
244358
  ...part,
244195
244359
  messageID: info3.id,
244196
244360
  sessionID: input.sessionID
244197
- });
244198
- }
244199
- }).catch((error47) => {
244200
- log8.error("failed to read file", { error: error47 });
244201
- const message = error47 instanceof Error ? error47.message : error47.toString();
244202
- Bus.publish(Session.Event.Error, {
244203
- sessionID: input.sessionID,
244204
- error: new NamedError.Unknown({
244205
- message
244206
- }).toObject(),
244207
- viewID: Instance.viewID
244208
- });
244209
- pieces.push({
244210
- messageID: info3.id,
244211
- sessionID: input.sessionID,
244212
- type: "text",
244213
- synthetic: true,
244214
- text: `Read tool failed to read ${filepath} with the following error: ${message}`
244215
- });
244216
- });
244217
- return pieces;
244218
- }
244219
- if (part.mime === "application/x-directory") {
244220
- const args2 = { filePath: filepath };
244221
- const listCtx = {
244222
- sessionID: input.sessionID,
244223
- abort: new AbortController().signal,
244224
- agent: input.agent,
244225
- messageID: info3.id,
244226
- extra: { bypassCwdCheck: true },
244227
- messages: [],
244228
- metadata: async () => {},
244229
- ask: async () => {}
244230
- };
244231
- const result = await ReadTool.init().then((t5) => t5.execute(args2, listCtx));
244361
+ }
244362
+ ];
244363
+ }
244364
+ FileTime.read(input.sessionID, filepath);
244232
244365
  return [
244233
244366
  {
244234
244367
  messageID: info3.id,
244235
244368
  sessionID: input.sessionID,
244236
244369
  type: "text",
244237
- synthetic: true,
244238
- text: `Called the Read tool with the following input: ${JSON.stringify(args2)}`
244370
+ text: `Called the Read tool with the following input: {"filePath":"${filepath}"}`,
244371
+ synthetic: true
244239
244372
  },
244240
244373
  {
244374
+ id: part.id,
244241
244375
  messageID: info3.id,
244242
244376
  sessionID: input.sessionID,
244243
- type: "text",
244244
- synthetic: true,
244245
- text: result.output
244246
- },
244247
- {
244248
- ...part,
244249
- messageID: info3.id,
244250
- sessionID: input.sessionID
244377
+ type: "file",
244378
+ url: `data:${part.mime};base64,` + (await Filesystem.readBytes(filepath)).toString("base64"),
244379
+ mime: part.mime,
244380
+ filename: part.filename,
244381
+ source: part.source
244251
244382
  }
244252
244383
  ];
244384
+ }
244385
+ }
244386
+ if (part.type === "agent") {
244387
+ const perm = PermissionNext.evaluate("task", part.name, agent.permission);
244388
+ const hint = perm.action === "deny" ? " . Invoked by user; guaranteed to exist." : "";
244389
+ return [
244390
+ {
244391
+ ...part,
244392
+ messageID: info3.id,
244393
+ sessionID: input.sessionID
244394
+ },
244395
+ {
244396
+ messageID: info3.id,
244397
+ sessionID: input.sessionID,
244398
+ type: "text",
244399
+ synthetic: true,
244400
+ text: " Use the above message and context to generate a prompt and call the task tool with subagent: " + part.name + hint
244253
244401
  }
244254
- FileTime.read(input.sessionID, filepath);
244255
- return [
244256
- {
244257
- messageID: info3.id,
244258
- sessionID: input.sessionID,
244259
- type: "text",
244260
- text: `Called the Read tool with the following input: {"filePath":"${filepath}"}`,
244261
- synthetic: true
244262
- },
244263
- {
244264
- id: part.id,
244265
- messageID: info3.id,
244266
- sessionID: input.sessionID,
244267
- type: "file",
244268
- url: `data:${part.mime};base64,` + (await Filesystem.readBytes(filepath)).toString("base64"),
244269
- mime: part.mime,
244270
- filename: part.filename,
244271
- source: part.source
244272
- }
244273
- ];
244402
+ ];
244274
244403
  }
244275
- }
244276
- if (part.type === "agent") {
244277
- const perm = PermissionNext.evaluate("task", part.name, agent.permission);
244278
- const hint = perm.action === "deny" ? " . Invoked by user; guaranteed to exist." : "";
244279
244404
  return [
244280
244405
  {
244281
244406
  ...part,
244282
244407
  messageID: info3.id,
244283
244408
  sessionID: input.sessionID
244284
- },
244285
- {
244286
- messageID: info3.id,
244287
- sessionID: input.sessionID,
244288
- type: "text",
244289
- synthetic: true,
244290
- text: " Use the above message and context to generate a prompt and call the task tool with subagent: " + part.name + hint
244291
244409
  }
244292
244410
  ];
244411
+ })).then((x5) => x5.flat().map(assign));
244412
+ await Plugin.trigger("chat.message", {
244413
+ sessionID: input.sessionID,
244414
+ agent: input.agent,
244415
+ model: input.model,
244416
+ messageID: input.messageID,
244417
+ variant: input.variant
244418
+ }, {
244419
+ message: info3,
244420
+ parts: parts2
244421
+ });
244422
+ await Session.updateMessage(info3);
244423
+ for (const part of parts2) {
244424
+ await Session.updatePart(part);
244293
244425
  }
244294
- return [
244295
- {
244296
- ...part,
244297
- messageID: info3.id,
244298
- sessionID: input.sessionID
244299
- }
244300
- ];
244301
- })).then((x5) => x5.flat().map(assign));
244302
- await Plugin.trigger("chat.message", {
244303
- sessionID: input.sessionID,
244304
- agent: input.agent,
244305
- model: input.model,
244306
- messageID: input.messageID,
244307
- variant: input.variant
244308
- }, {
244309
- message: info3,
244310
- parts: parts2
244311
- });
244312
- await Session.updateMessage(info3);
244313
- for (const part of parts2) {
244314
- await Session.updatePart(part);
244426
+ return {
244427
+ info: info3,
244428
+ parts: parts2
244429
+ };
244430
+ } catch (_catch3) {
244431
+ var _err = _catch3, _hasErr = 1;
244432
+ } finally {
244433
+ __callDispose(__stack, _err, _hasErr);
244315
244434
  }
244316
- return {
244317
- info: info3,
244318
- parts: parts2
244319
- };
244320
244435
  }
244321
244436
  async function insertReminders(input) {
244322
244437
  const userMessage = input.messages.findLast((msg) => msg.info.role === "user");
@@ -244473,279 +244588,286 @@ NOTE: At any point in time through this workflow you should feel free to ask the
244473
244588
  command: zod_default.string()
244474
244589
  });
244475
244590
  async function shell(input) {
244476
- const abort2 = start2(input.sessionID);
244477
- if (!abort2) {
244478
- throw new Session.BusyError(input.sessionID);
244479
- }
244480
- using _4 = defer(() => {
244481
- const entry = state2()[input.sessionID];
244482
- const hasQueuedWork = !!entry && (entry.callbacks.length > 0 || entry.queued.length > 0);
244483
- if (!hasQueuedWork) {
244484
- cancel(input.sessionID);
244485
- } else {
244486
- SessionPrompt.loop({ sessionID: input.sessionID, resume_existing: true }).catch((error48) => {
244487
- log8.error("session loop failed to resume after shell command", { sessionID: input.sessionID, error: error48 });
244488
- cancel(input.sessionID, error48);
244489
- });
244591
+ let __stack = [];
244592
+ try {
244593
+ const abort2 = start2(input.sessionID);
244594
+ if (!abort2) {
244595
+ throw new Session.BusyError(input.sessionID);
244596
+ }
244597
+ const _4 = __using(__stack, defer(() => {
244598
+ const entry = state2()[input.sessionID];
244599
+ const hasQueuedWork = !!entry && (entry.callbacks.length > 0 || entry.queued.length > 0);
244600
+ if (!hasQueuedWork) {
244601
+ cancel(input.sessionID);
244602
+ } else {
244603
+ SessionPrompt.loop({ sessionID: input.sessionID, resume_existing: true }).catch((error48) => {
244604
+ log8.error("session loop failed to resume after shell command", { sessionID: input.sessionID, error: error48 });
244605
+ cancel(input.sessionID, error48);
244606
+ });
244607
+ }
244608
+ }), 0);
244609
+ const session = await Session.get(input.sessionID);
244610
+ if (session.revert) {
244611
+ await SessionRevert.cleanup(session);
244490
244612
  }
244491
- });
244492
- const session = await Session.get(input.sessionID);
244493
- if (session.revert) {
244494
- await SessionRevert.cleanup(session);
244495
- }
244496
- const agent = await Agent.get(input.agent);
244497
- const model = input.model ?? agent.model ?? await lastModel(input.sessionID);
244498
- const userMsg = {
244499
- id: Identifier.ascending("message"),
244500
- sessionID: input.sessionID,
244501
- time: {
244502
- created: Date.now()
244503
- },
244504
- role: "user",
244505
- agent: input.agent,
244506
- model: {
244613
+ const agent = await Agent.get(input.agent);
244614
+ const model = input.model ?? agent.model ?? await lastModel(input.sessionID);
244615
+ const userMsg = {
244616
+ id: Identifier.ascending("message"),
244617
+ sessionID: input.sessionID,
244618
+ time: {
244619
+ created: Date.now()
244620
+ },
244621
+ role: "user",
244622
+ agent: input.agent,
244623
+ model: {
244624
+ providerID: model.providerID,
244625
+ modelID: model.modelID
244626
+ }
244627
+ };
244628
+ await Session.updateMessage(userMsg);
244629
+ const userPart = {
244630
+ type: "text",
244631
+ id: Identifier.ascending("part"),
244632
+ messageID: userMsg.id,
244633
+ sessionID: input.sessionID,
244634
+ text: "The following tool was executed by the user",
244635
+ synthetic: true
244636
+ };
244637
+ await Session.updatePart(userPart);
244638
+ queueTitle({
244639
+ sessionID: input.sessionID,
244507
244640
  providerID: model.providerID,
244508
- modelID: model.modelID
244509
- }
244510
- };
244511
- await Session.updateMessage(userMsg);
244512
- const userPart = {
244513
- type: "text",
244514
- id: Identifier.ascending("part"),
244515
- messageID: userMsg.id,
244516
- sessionID: input.sessionID,
244517
- text: "The following tool was executed by the user",
244518
- synthetic: true
244519
- };
244520
- await Session.updatePart(userPart);
244521
- queueTitle({
244522
- sessionID: input.sessionID,
244523
- providerID: model.providerID,
244524
- modelID: model.modelID,
244525
- text: input.command
244526
- });
244527
- const msg = {
244528
- id: Identifier.ascending("message"),
244529
- sessionID: input.sessionID,
244530
- parentID: userMsg.id,
244531
- mode: input.agent,
244532
- agent: input.agent,
244533
- cost: 0,
244534
- path: {
244535
- cwd: Instance.directory,
244536
- root: Instance.worktree
244537
- },
244538
- time: {
244539
- created: Date.now()
244540
- },
244541
- role: "assistant",
244542
- tokens: {
244543
- input: 0,
244544
- output: 0,
244545
- reasoning: 0,
244546
- cache: { read: 0, write: 0 }
244547
- },
244548
- modelID: model.modelID,
244549
- providerID: model.providerID
244550
- };
244551
- await Session.updateMessage(msg);
244552
- const part = {
244553
- type: "tool",
244554
- id: Identifier.ascending("part"),
244555
- messageID: msg.id,
244556
- sessionID: input.sessionID,
244557
- tool: "bash",
244558
- callID: ulid3(),
244559
- state: {
244560
- status: "running",
244641
+ modelID: model.modelID,
244642
+ text: input.command
244643
+ });
244644
+ const msg = {
244645
+ id: Identifier.ascending("message"),
244646
+ sessionID: input.sessionID,
244647
+ parentID: userMsg.id,
244648
+ mode: input.agent,
244649
+ agent: input.agent,
244650
+ cost: 0,
244651
+ path: {
244652
+ cwd: Instance.directory,
244653
+ root: Instance.worktree
244654
+ },
244561
244655
  time: {
244562
- start: Date.now()
244656
+ created: Date.now()
244563
244657
  },
244564
- input: {
244565
- command: input.command
244658
+ role: "assistant",
244659
+ tokens: {
244660
+ input: 0,
244661
+ output: 0,
244662
+ reasoning: 0,
244663
+ cache: { read: 0, write: 0 }
244664
+ },
244665
+ modelID: model.modelID,
244666
+ providerID: model.providerID
244667
+ };
244668
+ await Session.updateMessage(msg);
244669
+ const part = {
244670
+ type: "tool",
244671
+ id: Identifier.ascending("part"),
244672
+ messageID: msg.id,
244673
+ sessionID: input.sessionID,
244674
+ tool: "bash",
244675
+ callID: ulid3(),
244676
+ state: {
244677
+ status: "running",
244678
+ time: {
244679
+ start: Date.now()
244680
+ },
244681
+ input: {
244682
+ command: input.command
244683
+ }
244566
244684
  }
244567
- }
244568
- };
244569
- await Session.updatePart(part);
244570
- const cfg = await Config.get();
244571
- const shell2 = Shell.preferred(cfg.shell?.program);
244572
- const shellName = Shell.name(shell2);
244573
- const invocations = {
244574
- nu: {
244575
- args: ["-c", input.command]
244576
- },
244577
- fish: {
244578
- args: ["-c", input.command]
244579
- },
244580
- zsh: {
244581
- args: [
244582
- "-c",
244583
- "-l",
244584
- `
244685
+ };
244686
+ await Session.updatePart(part);
244687
+ const cfg = await Config.get();
244688
+ const shell2 = Shell.preferred(cfg.shell?.program);
244689
+ const shellName = Shell.name(shell2);
244690
+ const invocations = {
244691
+ nu: {
244692
+ args: ["-c", input.command]
244693
+ },
244694
+ fish: {
244695
+ args: ["-c", input.command]
244696
+ },
244697
+ zsh: {
244698
+ args: [
244699
+ "-c",
244700
+ "-l",
244701
+ `
244585
244702
  [[ -f ~/.zshenv ]] && source ~/.zshenv >/dev/null 2>&1 || true
244586
244703
  [[ -f "\${ZDOTDIR:-$HOME}/.zshrc" ]] && source "\${ZDOTDIR:-$HOME}/.zshrc" >/dev/null 2>&1 || true
244587
244704
  eval ${JSON.stringify(input.command)}
244588
244705
  `
244589
- ]
244590
- },
244591
- bash: {
244592
- args: [
244593
- "-c",
244594
- "-l",
244595
- `
244706
+ ]
244707
+ },
244708
+ bash: {
244709
+ args: [
244710
+ "-c",
244711
+ "-l",
244712
+ `
244596
244713
  shopt -s expand_aliases
244597
244714
  [[ -f ~/.bashrc ]] && source ~/.bashrc >/dev/null 2>&1 || true
244598
244715
  eval ${JSON.stringify(input.command)}
244599
244716
  `
244600
- ]
244601
- },
244602
- cmd: {
244603
- args: ["/c", input.command]
244604
- },
244605
- powershell: {
244606
- args: ["-NoProfile", "-Command", input.command]
244607
- },
244608
- pwsh: {
244609
- args: ["-NoProfile", "-Command", input.command]
244610
- },
244611
- "": {
244612
- args: ["-c", `${input.command}`]
244613
- }
244614
- };
244615
- const matchingInvocation = invocations[shellName] ?? invocations[""];
244616
- const args2 = matchingInvocation?.args;
244617
- const cwd = Instance.directory;
244618
- const shellEnv = await Plugin.trigger("shell.env", { cwd, sessionID: input.sessionID, callID: part.callID }, { env: {} });
244619
- const proc = spawn7(shell2, args2, {
244620
- cwd,
244621
- detached: process.platform !== "win32",
244622
- stdio: ["ignore", "pipe", "pipe"],
244623
- env: {
244624
- ...Env.all({ sessionID: input.sessionID }),
244625
- ...shellEnv.env,
244626
- TERM: "dumb"
244627
- }
244628
- });
244629
- const timeout = cfg.shell?.timeout_ms ?? SHELL_TIMEOUT;
244630
- const decoder2 = new TextDecoder;
244631
- let output2 = "";
244632
- let clipped = 0;
244633
- const format5 = (notes2 = []) => {
244634
- const meta = [
244635
- ...clipped > 0 ? [`Output truncated after ${SHELL_OUTPUT_LIMIT} characters; ${clipped} additional characters omitted.`] : [],
244636
- ...notes2
244637
- ];
244638
- const suffix = meta.length ? `
244717
+ ]
244718
+ },
244719
+ cmd: {
244720
+ args: ["/c", input.command]
244721
+ },
244722
+ powershell: {
244723
+ args: ["-NoProfile", "-Command", input.command]
244724
+ },
244725
+ pwsh: {
244726
+ args: ["-NoProfile", "-Command", input.command]
244727
+ },
244728
+ "": {
244729
+ args: ["-c", `${input.command}`]
244730
+ }
244731
+ };
244732
+ const matchingInvocation = invocations[shellName] ?? invocations[""];
244733
+ const args2 = matchingInvocation?.args;
244734
+ const cwd = Instance.directory;
244735
+ const shellEnv = await Plugin.trigger("shell.env", { cwd, sessionID: input.sessionID, callID: part.callID }, { env: {} });
244736
+ const proc = spawn7(shell2, args2, {
244737
+ cwd,
244738
+ detached: process.platform !== "win32",
244739
+ stdio: ["ignore", "pipe", "pipe"],
244740
+ env: {
244741
+ ...Env.all({ sessionID: input.sessionID }),
244742
+ ...shellEnv.env,
244743
+ TERM: "dumb"
244744
+ }
244745
+ });
244746
+ const timeout = cfg.shell?.timeout_ms ?? SHELL_TIMEOUT;
244747
+ const decoder2 = new TextDecoder;
244748
+ let output2 = "";
244749
+ let clipped = 0;
244750
+ const format5 = (notes2 = []) => {
244751
+ const meta = [
244752
+ ...clipped > 0 ? [`Output truncated after ${SHELL_OUTPUT_LIMIT} characters; ${clipped} additional characters omitted.`] : [],
244753
+ ...notes2
244754
+ ];
244755
+ const suffix = meta.length ? `
244639
244756
 
244640
244757
  <shell_metadata>
244641
244758
  ${meta.join(`
244642
244759
  `)}
244643
244760
  </shell_metadata>` : "";
244644
- const text11 = output2 + suffix;
244645
- if (text11.length <= SHELL_METADATA_LIMIT)
244646
- return text11;
244647
- return text11.slice(0, SHELL_METADATA_LIMIT) + `
244761
+ const text11 = output2 + suffix;
244762
+ if (text11.length <= SHELL_METADATA_LIMIT)
244763
+ return text11;
244764
+ return text11.slice(0, SHELL_METADATA_LIMIT) + `
244648
244765
 
244649
244766
  ...`;
244650
- };
244651
- const append2 = (chunk2) => {
244652
- const text11 = typeof chunk2 === "string" ? chunk2 : decoder2.decode(chunk2);
244653
- if (clipped > 0) {
244654
- clipped += text11.length;
244655
- } else {
244656
- const remaining = SHELL_OUTPUT_LIMIT - output2.length;
244657
- if (text11.length <= remaining) {
244658
- output2 += text11;
244767
+ };
244768
+ const append2 = (chunk2) => {
244769
+ const text11 = typeof chunk2 === "string" ? chunk2 : decoder2.decode(chunk2);
244770
+ if (clipped > 0) {
244771
+ clipped += text11.length;
244659
244772
  } else {
244660
- output2 += text11.slice(0, remaining);
244661
- clipped += text11.length - remaining;
244773
+ const remaining = SHELL_OUTPUT_LIMIT - output2.length;
244774
+ if (text11.length <= remaining) {
244775
+ output2 += text11;
244776
+ } else {
244777
+ output2 += text11.slice(0, remaining);
244778
+ clipped += text11.length - remaining;
244779
+ }
244662
244780
  }
244663
- }
244664
- if (part.state.status !== "running")
244665
- return;
244666
- part.state.metadata = {
244667
- output: format5(),
244668
- description: ""
244781
+ if (part.state.status !== "running")
244782
+ return;
244783
+ part.state.metadata = {
244784
+ output: format5(),
244785
+ description: ""
244786
+ };
244787
+ Session.updatePart(part);
244669
244788
  };
244670
- Session.updatePart(part);
244671
- };
244672
- proc.stdout?.on("data", append2);
244673
- proc.stderr?.on("data", append2);
244674
- let timedOut = false;
244675
- let aborted3 = false;
244676
- let exited = false;
244677
- const kill = () => Shell.killTree(proc, { exited: () => exited });
244678
- if (abort2.aborted) {
244679
- aborted3 = true;
244680
- await kill();
244681
- }
244682
- const abortHandler = () => {
244683
- aborted3 = true;
244684
- kill();
244685
- };
244686
- const timeoutTimer = setTimeout(() => {
244687
- timedOut = true;
244688
- kill();
244689
- }, timeout + 100);
244690
- abort2.addEventListener("abort", abortHandler, { once: true });
244691
- const error47 = await new Promise((resolve13) => {
244692
- const cleanup = () => {
244693
- clearTimeout(timeoutTimer);
244694
- abort2.removeEventListener("abort", abortHandler);
244695
- proc.stdout?.off("data", append2);
244696
- proc.stderr?.off("data", append2);
244789
+ proc.stdout?.on("data", append2);
244790
+ proc.stderr?.on("data", append2);
244791
+ let timedOut = false;
244792
+ let aborted3 = false;
244793
+ let exited = false;
244794
+ const kill = () => Shell.killTree(proc, { exited: () => exited });
244795
+ if (abort2.aborted) {
244796
+ aborted3 = true;
244797
+ await kill();
244798
+ }
244799
+ const abortHandler = () => {
244800
+ aborted3 = true;
244801
+ kill();
244697
244802
  };
244698
- proc.once("close", () => {
244699
- exited = true;
244700
- cleanup();
244701
- resolve13(undefined);
244702
- });
244703
- proc.once("error", (error48) => {
244704
- exited = true;
244705
- cleanup();
244706
- resolve13(error48);
244803
+ const timeoutTimer = setTimeout(() => {
244804
+ timedOut = true;
244805
+ kill();
244806
+ }, timeout + 100);
244807
+ abort2.addEventListener("abort", abortHandler, { once: true });
244808
+ const error47 = await new Promise((resolve13) => {
244809
+ const cleanup = () => {
244810
+ clearTimeout(timeoutTimer);
244811
+ abort2.removeEventListener("abort", abortHandler);
244812
+ proc.stdout?.off("data", append2);
244813
+ proc.stderr?.off("data", append2);
244814
+ };
244815
+ proc.once("close", () => {
244816
+ exited = true;
244817
+ cleanup();
244818
+ resolve13(undefined);
244819
+ });
244820
+ proc.once("error", (error48) => {
244821
+ exited = true;
244822
+ cleanup();
244823
+ resolve13(error48);
244824
+ });
244707
244825
  });
244708
- });
244709
- msg.time.completed = Date.now();
244710
- await Session.updateMessage(msg);
244711
- if (error47) {
244826
+ msg.time.completed = Date.now();
244827
+ await Session.updateMessage(msg);
244828
+ if (error47) {
244829
+ if (part.state.status === "running") {
244830
+ part.state = {
244831
+ status: "error",
244832
+ input: part.state.input,
244833
+ error: error47.toString(),
244834
+ time: {
244835
+ ...part.state.time,
244836
+ end: Date.now()
244837
+ }
244838
+ };
244839
+ await Session.updatePart(part);
244840
+ }
244841
+ throw error47;
244842
+ }
244843
+ const notes = [
244844
+ ...timedOut ? [`shell command terminated after exceeding timeout ${timeout} ms`] : [],
244845
+ ...aborted3 ? ["User aborted the command"] : []
244846
+ ];
244847
+ const text10 = format5(notes);
244712
244848
  if (part.state.status === "running") {
244713
244849
  part.state = {
244714
- status: "error",
244715
- input: part.state.input,
244716
- error: error47.toString(),
244850
+ status: "completed",
244717
244851
  time: {
244718
244852
  ...part.state.time,
244719
244853
  end: Date.now()
244720
- }
244854
+ },
244855
+ input: part.state.input,
244856
+ title: "",
244857
+ metadata: {
244858
+ output: text10,
244859
+ description: ""
244860
+ },
244861
+ output: text10
244721
244862
  };
244722
244863
  await Session.updatePart(part);
244723
244864
  }
244724
- throw error47;
244725
- }
244726
- const notes = [
244727
- ...timedOut ? [`shell command terminated after exceeding timeout ${timeout} ms`] : [],
244728
- ...aborted3 ? ["User aborted the command"] : []
244729
- ];
244730
- const text10 = format5(notes);
244731
- if (part.state.status === "running") {
244732
- part.state = {
244733
- status: "completed",
244734
- time: {
244735
- ...part.state.time,
244736
- end: Date.now()
244737
- },
244738
- input: part.state.input,
244739
- title: "",
244740
- metadata: {
244741
- output: text10,
244742
- description: ""
244743
- },
244744
- output: text10
244745
- };
244746
- await Session.updatePart(part);
244865
+ return { info: msg, parts: [part] };
244866
+ } catch (_catch3) {
244867
+ var _err = _catch3, _hasErr = 1;
244868
+ } finally {
244869
+ __callDispose(__stack, _err, _hasErr);
244747
244870
  }
244748
- return { info: msg, parts: [part] };
244749
244871
  }
244750
244872
  SessionPrompt.shell = shell;
244751
244873
  SessionPrompt.CommandInput = zod_default.object({
@@ -293677,7 +293799,7 @@ function toIntArray(seed) {
293677
293799
  buffer4.push(unicode >>> 6 & 63 | 128);
293678
293800
  buffer4.push(unicode >>> 0 & 63 | 128);
293679
293801
  index3++;
293680
- }
293802
+ } else {}
293681
293803
  if (buffer4.length > 3) {
293682
293804
  result6.push(buffer4.shift() << 0 | buffer4.shift() << 8 | buffer4.shift() << 16 | buffer4.shift() << 24);
293683
293805
  }
@@ -304271,7 +304393,8 @@ function createSurfaceManifest(input = {}) {
304271
304393
  version: TUI_SURFACE_VERSION,
304272
304394
  renderer: {
304273
304395
  linux: "opentui/solid",
304274
- android: "ratatui/crossterm"
304396
+ android: "ratatui/crossterm",
304397
+ frame: "shared/terminal-frame"
304275
304398
  },
304276
304399
  capabilities: {
304277
304400
  "android.runtime": input.android ?? false,
@@ -304408,7 +304531,166 @@ function createSurfaceSnapshot(input) {
304408
304531
  }
304409
304532
  };
304410
304533
  }
304411
- var TUI_SURFACE_VERSION = 1, TuiSurfaceCommand, TuiSurfaceManifest, TuiSurfaceAction, TuiSurfaceSnapshot, command2 = (input) => input, surfaceCommands;
304534
+ function cellWidth(char2) {
304535
+ const code = char2.codePointAt(0) ?? 0;
304536
+ if (code === 0)
304537
+ return 0;
304538
+ if (code < 32 || code >= 127 && code < 160)
304539
+ return 0;
304540
+ return code >= 4352 ? 2 : 1;
304541
+ }
304542
+ function visibleWidth(text11) {
304543
+ let width = 0;
304544
+ for (const char2 of text11)
304545
+ width += cellWidth(char2);
304546
+ return width;
304547
+ }
304548
+ function fit(text11, width) {
304549
+ if (width <= 0)
304550
+ return "";
304551
+ let out2 = "";
304552
+ let size24 = 0;
304553
+ for (const char2 of text11.replace(/\s+/g, " ")) {
304554
+ const next4 = cellWidth(char2);
304555
+ if (size24 + next4 > width)
304556
+ break;
304557
+ out2 += char2;
304558
+ size24 += next4;
304559
+ }
304560
+ return out2 + " ".repeat(Math.max(0, width - size24));
304561
+ }
304562
+ function wrap2(text11, width) {
304563
+ if (width <= 0)
304564
+ return [""];
304565
+ const words = text11.split(/\s+/).filter(Boolean);
304566
+ if (words.length === 0)
304567
+ return [""];
304568
+ const lines = [];
304569
+ let line2 = "";
304570
+ for (const word of words) {
304571
+ const candidate = line2 ? `${line2} ${word}` : word;
304572
+ if (visibleWidth(candidate) <= width) {
304573
+ line2 = candidate;
304574
+ continue;
304575
+ }
304576
+ if (line2)
304577
+ lines.push(line2);
304578
+ if (visibleWidth(word) <= width) {
304579
+ line2 = word;
304580
+ continue;
304581
+ }
304582
+ let chunk2 = "";
304583
+ let size24 = 0;
304584
+ for (const char2 of word) {
304585
+ const next4 = cellWidth(char2);
304586
+ if (size24 + next4 > width) {
304587
+ lines.push(chunk2);
304588
+ chunk2 = "";
304589
+ size24 = 0;
304590
+ }
304591
+ chunk2 += char2;
304592
+ size24 += next4;
304593
+ }
304594
+ line2 = chunk2;
304595
+ }
304596
+ if (line2)
304597
+ lines.push(line2);
304598
+ return lines;
304599
+ }
304600
+ function clampDimension(value8, fallback, min13, max13) {
304601
+ if (!Number.isFinite(value8))
304602
+ return fallback;
304603
+ return Math.max(min13, Math.min(max13, Math.floor(value8)));
304604
+ }
304605
+ function tabLine(snapshot4) {
304606
+ const tabs = snapshot4.tabs.length ? snapshot4.tabs.map((item) => `${item.active ? "[*]" : "[ ]"} ${item.title} ${item.status}`).join(" ") : "[ ] new session idle";
304607
+ return tabs;
304608
+ }
304609
+ function transcriptLines(snapshot4, width) {
304610
+ const lines = [];
304611
+ if (snapshot4.transcript.length === 0) {
304612
+ lines.push("Start a conversation or type /help for commands.");
304613
+ return lines;
304614
+ }
304615
+ for (const message of snapshot4.transcript) {
304616
+ const label = message.role === "user" ? "You" : "Assistant";
304617
+ if (message.text)
304618
+ lines.push(...wrap2(`${label}: ${message.text}`, width));
304619
+ for (const tool3 of message.tools) {
304620
+ lines.push(...wrap2(`tool ${tool3.tool} ${tool3.status}`, width));
304621
+ for (const row of tool3.preview)
304622
+ lines.push(...wrap2(`output ${row}`, width));
304623
+ for (const row of tool3.diff)
304624
+ lines.push(...wrap2(`diff ${row}`, width));
304625
+ if (tool3.expandable)
304626
+ lines.push("more output available");
304627
+ }
304628
+ if (message.text || message.tools.length > 0)
304629
+ lines.push("");
304630
+ }
304631
+ while (lines.at(-1) === "")
304632
+ lines.pop();
304633
+ return lines.length ? lines : ["No transcript yet."];
304634
+ }
304635
+ function sidebarLines(snapshot4, width) {
304636
+ const title = snapshot4.sidebar.mode === "files" ? "Files" : "Modified Files";
304637
+ const rows = snapshot4.sidebar.rows.length ? snapshot4.sidebar.rows : ["No changed files"];
304638
+ return [title, ...rows.flatMap((row) => wrap2(row, width))];
304639
+ }
304640
+ function createSurfaceFrame(input) {
304641
+ const width = clampDimension(input.width, 80, 20, 240);
304642
+ const height = clampDimension(input.height, 24, 8, 100);
304643
+ const snapshot4 = input.snapshot;
304644
+ const header = `SlopCode | ${snapshot4.header.title} | ${snapshot4.status}`;
304645
+ const footer = [
304646
+ snapshot4.footer.directory,
304647
+ snapshot4.footer.workspaceID ? `workspace ${snapshot4.footer.workspaceID}` : undefined,
304648
+ `lsp ${snapshot4.footer.lsp}`,
304649
+ `mcp ${snapshot4.footer.mcp}${snapshot4.footer.mcpFailed ? "!" : ""}`,
304650
+ snapshot4.footer.permissions ? `perm ${snapshot4.footer.permissions}` : undefined
304651
+ ].filter(Boolean).join(" | ");
304652
+ const prompt = "> ";
304653
+ const bodyHeight = Math.max(1, height - 4);
304654
+ const useSidebar = width >= 90;
304655
+ const body2 = [];
304656
+ if (useSidebar) {
304657
+ const sidebarWidth = Math.min(32, Math.max(24, Math.floor(width * 0.3)));
304658
+ const mainWidth = width - sidebarWidth - 3;
304659
+ const main2 = transcriptLines(snapshot4, mainWidth);
304660
+ const side = sidebarLines(snapshot4, sidebarWidth);
304661
+ for (let index3 = 0;index3 < bodyHeight; index3++) {
304662
+ body2.push(`${fit(main2[index3] ?? "", mainWidth)} | ${fit(side[index3] ?? "", sidebarWidth)}`);
304663
+ }
304664
+ } else {
304665
+ const main2 = [...transcriptLines(snapshot4, width), "", ...sidebarLines(snapshot4, width)];
304666
+ for (let index3 = 0;index3 < bodyHeight; index3++)
304667
+ body2.push(fit(main2[index3] ?? "", width));
304668
+ }
304669
+ const lines = [
304670
+ fit(header, width),
304671
+ fit(tabLine(snapshot4), width),
304672
+ ...body2,
304673
+ fit(prompt, width),
304674
+ fit(footer, width)
304675
+ ].slice(0, height);
304676
+ while (lines.length < height)
304677
+ lines.push(" ".repeat(width));
304678
+ return {
304679
+ version: TUI_SURFACE_VERSION,
304680
+ renderer: "shared/terminal-frame",
304681
+ width,
304682
+ height,
304683
+ sessionID: snapshot4.sessionID,
304684
+ title: snapshot4.title,
304685
+ status: snapshot4.status,
304686
+ lines,
304687
+ rows: lines.map((line2, y7) => ({
304688
+ y: y7,
304689
+ spans: [{ x: 0, text: line2 }]
304690
+ }))
304691
+ };
304692
+ }
304693
+ var TUI_SURFACE_VERSION = 2, TuiSurfaceCommand, TuiSurfaceManifest, TuiSurfaceAction, TuiSurfaceSnapshot, TuiSurfaceFrameStyle, TuiSurfaceFrameSpan, TuiSurfaceFrame, command2 = (input) => input, surfaceCommands;
304412
304694
  var init_surface = __esm(async () => {
304413
304695
  init_zod();
304414
304696
  init_keybind();
@@ -304430,7 +304712,8 @@ var init_surface = __esm(async () => {
304430
304712
  version: zod_default.literal(TUI_SURFACE_VERSION),
304431
304713
  renderer: zod_default.object({
304432
304714
  linux: zod_default.literal("opentui/solid"),
304433
- android: zod_default.literal("ratatui/crossterm")
304715
+ android: zod_default.literal("ratatui/crossterm"),
304716
+ frame: zod_default.literal("shared/terminal-frame")
304434
304717
  }),
304435
304718
  capabilities: zod_default.record(zod_default.string(), zod_default.boolean()),
304436
304719
  commands: TuiSurfaceCommand.array(),
@@ -304538,6 +304821,33 @@ var init_surface = __esm(async () => {
304538
304821
  rows: zod_default.string().array()
304539
304822
  })
304540
304823
  });
304824
+ TuiSurfaceFrameStyle = zod_default.object({
304825
+ fg: zod_default.string().optional(),
304826
+ bg: zod_default.string().optional(),
304827
+ bold: zod_default.boolean().optional(),
304828
+ dim: zod_default.boolean().optional(),
304829
+ underline: zod_default.boolean().optional(),
304830
+ reverse: zod_default.boolean().optional()
304831
+ });
304832
+ TuiSurfaceFrameSpan = zod_default.object({
304833
+ x: zod_default.number(),
304834
+ text: zod_default.string(),
304835
+ style: TuiSurfaceFrameStyle.optional()
304836
+ });
304837
+ TuiSurfaceFrame = zod_default.object({
304838
+ version: zod_default.literal(TUI_SURFACE_VERSION),
304839
+ renderer: zod_default.literal("shared/terminal-frame"),
304840
+ width: zod_default.number(),
304841
+ height: zod_default.number(),
304842
+ sessionID: zod_default.string().optional(),
304843
+ title: zod_default.string(),
304844
+ status: zod_default.string(),
304845
+ lines: zod_default.string().array(),
304846
+ rows: zod_default.object({
304847
+ y: zod_default.number(),
304848
+ spans: TuiSurfaceFrameSpan.array()
304849
+ }).array()
304850
+ });
304541
304851
  surfaceCommands = [
304542
304852
  command2({
304543
304853
  id: "help.show",
@@ -305315,6 +305625,32 @@ var init_tui2 = __esm(async () => {
305315
305625
  sessionID: zod_default.string().optional()
305316
305626
  })), async (c4) => {
305317
305627
  return c4.json(await snapshot4(c4.req.valid("query").sessionID));
305628
+ }).get("/frame", describeRoute({
305629
+ summary: "Get shared TUI terminal frame",
305630
+ description: "Return a deterministic terminal-cell frame that native renderers can paint exactly across Linux and Android.",
305631
+ operationId: "tui.frame",
305632
+ responses: {
305633
+ 200: {
305634
+ description: "Shared TUI terminal frame",
305635
+ content: {
305636
+ "application/json": {
305637
+ schema: resolver(TuiSurfaceFrame)
305638
+ }
305639
+ }
305640
+ },
305641
+ ...errors6(400, 404)
305642
+ }
305643
+ }), validator5("query", zod_default.object({
305644
+ sessionID: zod_default.string().optional(),
305645
+ width: zod_default.coerce.number().optional(),
305646
+ height: zod_default.coerce.number().optional()
305647
+ })), async (c4) => {
305648
+ const query2 = c4.req.valid("query");
305649
+ return c4.json(createSurfaceFrame({
305650
+ snapshot: await snapshot4(query2.sessionID),
305651
+ width: query2.width ?? 80,
305652
+ height: query2.height ?? 24
305653
+ }));
305318
305654
  }).post("/action", describeRoute({
305319
305655
  summary: "Dispatch shared TUI action",
305320
305656
  description: "Dispatch a typed action from a native TUI renderer through the shared TUI surface contract.",
@@ -307208,7 +307544,7 @@ var CAPTURING_REGEX_SOURCE, RegexSource = class {
307208
307544
  let localIncludedRule = repository[reference.ruleName];
307209
307545
  if (localIncludedRule) {
307210
307546
  ruleId = _RuleFactory.getCompiledRuleId(localIncludedRule, helper, repository);
307211
- }
307547
+ } else {}
307212
307548
  break;
307213
307549
  case 3:
307214
307550
  case 4:
@@ -307220,11 +307556,11 @@ var CAPTURING_REGEX_SOURCE, RegexSource = class {
307220
307556
  let externalIncludedRule = externalGrammar.repository[externalGrammarInclude];
307221
307557
  if (externalIncludedRule) {
307222
307558
  ruleId = _RuleFactory.getCompiledRuleId(externalIncludedRule, helper, externalGrammar.repository);
307223
- }
307559
+ } else {}
307224
307560
  } else {
307225
307561
  ruleId = _RuleFactory.getCompiledRuleId(externalGrammar.repository.$self, helper, externalGrammar.repository);
307226
307562
  }
307227
- }
307563
+ } else {}
307228
307564
  break;
307229
307565
  }
307230
307566
  } else {
@@ -327111,12 +327447,19 @@ var init_config3 = __esm(async () => {
327111
327447
  }
327112
327448
  }
327113
327449
  }), async (c4) => {
327114
- using _4 = log15.time("providers");
327115
- const providers2 = await Provider.list().then((x5) => i4(x5, (item) => item));
327116
- return c4.json({
327117
- providers: Object.values(providers2),
327118
- default: i4(providers2, (item) => Provider.sort(Object.values(item.models))[0].id)
327119
- });
327450
+ let __stack = [];
327451
+ try {
327452
+ const _4 = __using(__stack, log15.time("providers"), 0);
327453
+ const providers2 = await Provider.list().then((x5) => i4(x5, (item) => item));
327454
+ return c4.json({
327455
+ providers: Object.values(providers2),
327456
+ default: i4(providers2, (item) => Provider.sort(Object.values(item.models))[0].id)
327457
+ });
327458
+ } catch (_catch3) {
327459
+ var _err = _catch3, _hasErr = 1;
327460
+ } finally {
327461
+ __callDispose(__stack, _err, _hasErr);
327462
+ }
327120
327463
  }));
327121
327464
  });
327122
327465
 
@@ -336890,6 +337233,23 @@ var init_sdk_gen2 = __esm(() => {
336890
337233
  ...params
336891
337234
  });
336892
337235
  }
337236
+ frame(parameters5, options2) {
337237
+ const params = buildClientParams2([parameters5], [
337238
+ {
337239
+ args: [
337240
+ { in: "query", key: "directory" },
337241
+ { in: "query", key: "sessionID" },
337242
+ { in: "query", key: "width" },
337243
+ { in: "query", key: "height" }
337244
+ ]
337245
+ }
337246
+ ]);
337247
+ return (options2?.client ?? this.client).get({
337248
+ url: "/tui/frame",
337249
+ ...options2,
337250
+ ...params
337251
+ });
337252
+ }
336893
337253
  action(parameters5, options2) {
336894
337254
  const params = buildClientParams2([parameters5], [
336895
337255
  {
@@ -366551,7 +366911,7 @@ function clip(input, width) {
366551
366911
  return "\u2026";
366552
366912
  return hard(text14, width - 1).trimEnd() + "\u2026";
366553
366913
  }
366554
- function wrap2(input, width, limit2) {
366914
+ function wrap3(input, width, limit2) {
366555
366915
  const text14 = input.replace(/\s+/g, " ").trim();
366556
366916
  if (!text14)
366557
366917
  return [];
@@ -366578,14 +366938,14 @@ function wrap2(input, width, limit2) {
366578
366938
  function autocompleteLines(option8, width) {
366579
366939
  const limit2 = Math.max(6, Math.floor(width));
366580
366940
  const lines = [];
366581
- for (const text14 of wrap2(option8.display, limit2, 2)) {
366941
+ for (const text14 of wrap3(option8.display, limit2, 2)) {
366582
366942
  lines.push({
366583
366943
  text: text14,
366584
366944
  tone: "title"
366585
366945
  });
366586
366946
  }
366587
366947
  if (option8.description) {
366588
- for (const text14 of wrap2(option8.description, limit2, 2)) {
366948
+ for (const text14 of wrap3(option8.description, limit2, 2)) {
366589
366949
  lines.push({
366590
366950
  text: text14,
366591
366951
  tone: "description"
@@ -367259,26 +367619,34 @@ var init_editor4 = __esm(() => {
367259
367619
  init_process();
367260
367620
  ((Editor) => {
367261
367621
  async function open4(opts) {
367262
- const editor = process.env["VISUAL"] || process.env["EDITOR"];
367263
- if (!editor)
367264
- return;
367265
- const filepath = join22(tmpdir2(), `${Date.now()}.md`);
367266
- await using _5 = defer(async () => rm3(filepath, { force: true }));
367267
- await Filesystem.write(filepath, opts.value);
367268
- opts.renderer.suspend();
367269
- opts.renderer.currentRenderBuffer.clear();
367270
- const parts3 = editor.split(" ");
367271
- const proc = Process.spawn([...parts3, filepath], {
367272
- stdin: "inherit",
367273
- stdout: "inherit",
367274
- stderr: "inherit"
367275
- });
367276
- await proc.exited;
367277
- const content = await Filesystem.readText(filepath);
367278
- opts.renderer.currentRenderBuffer.clear();
367279
- opts.renderer.resume();
367280
- opts.renderer.requestRender();
367281
- return content || undefined;
367622
+ let __stack = [];
367623
+ try {
367624
+ const editor = process.env["VISUAL"] || process.env["EDITOR"];
367625
+ if (!editor)
367626
+ return;
367627
+ const filepath = join22(tmpdir2(), `${Date.now()}.md`);
367628
+ const _5 = __using(__stack, defer(async () => rm3(filepath, { force: true })), 1);
367629
+ await Filesystem.write(filepath, opts.value);
367630
+ opts.renderer.suspend();
367631
+ opts.renderer.currentRenderBuffer.clear();
367632
+ const parts3 = editor.split(" ");
367633
+ const proc = Process.spawn([...parts3, filepath], {
367634
+ stdin: "inherit",
367635
+ stdout: "inherit",
367636
+ stderr: "inherit"
367637
+ });
367638
+ await proc.exited;
367639
+ const content = await Filesystem.readText(filepath);
367640
+ opts.renderer.currentRenderBuffer.clear();
367641
+ opts.renderer.resume();
367642
+ opts.renderer.requestRender();
367643
+ return content || undefined;
367644
+ } catch (_catch3) {
367645
+ var _err = _catch3, _hasErr = 1;
367646
+ } finally {
367647
+ var _promise2 = __callDispose(__stack, _err, _hasErr);
367648
+ _promise2 && await _promise2;
367649
+ }
367282
367650
  }
367283
367651
  Editor.open = open4;
367284
367652
  })(Editor2 ||= {});
@@ -371064,53 +371432,60 @@ function patchName(kind) {
371064
371432
  return "tui";
371065
371433
  }
371066
371434
  async function patchOne(dir2, target2, spec3, force, dep) {
371067
- const name19 = patchName(target2.kind);
371068
- using _5 = await Lock.write(`plug-config:${dir2}:${name19}`);
371069
- const files = dep.files(dir2, name19);
371070
- let cfg = files[0];
371071
- for (const file2 of files) {
371072
- if (!await dep.exists(file2))
371073
- continue;
371074
- cfg = file2;
371075
- break;
371076
- }
371077
- const src2 = await dep.readText(cfg).catch((err2) => {
371078
- if (typeof err2 === "object" && err2 && "code" in err2 && err2.code === "ENOENT")
371079
- return "{}";
371080
- if (err2 instanceof Error)
371081
- return err2;
371082
- return new Error(String(err2));
371083
- });
371084
- if (src2 instanceof Error) {
371085
- return { ok: false, code: "patch_failed", kind: target2.kind, error: src2 };
371086
- }
371087
- const text14 = src2.trim() ? src2 : "{}";
371088
- const errs = [];
371089
- const data3 = parse8(text14, errs, { allowTrailingComma: true });
371090
- if (errs.length) {
371091
- const err2 = errs[0];
371092
- const lines = text14.substring(0, err2.offset).split(`
371435
+ let __stack = [];
371436
+ try {
371437
+ const name19 = patchName(target2.kind);
371438
+ const _5 = __using(__stack, await Lock.write(`plug-config:${dir2}:${name19}`), 0);
371439
+ const files = dep.files(dir2, name19);
371440
+ let cfg = files[0];
371441
+ for (const file2 of files) {
371442
+ if (!await dep.exists(file2))
371443
+ continue;
371444
+ cfg = file2;
371445
+ break;
371446
+ }
371447
+ const src2 = await dep.readText(cfg).catch((err2) => {
371448
+ if (typeof err2 === "object" && err2 && "code" in err2 && err2.code === "ENOENT")
371449
+ return "{}";
371450
+ if (err2 instanceof Error)
371451
+ return err2;
371452
+ return new Error(String(err2));
371453
+ });
371454
+ if (src2 instanceof Error) {
371455
+ return { ok: false, code: "patch_failed", kind: target2.kind, error: src2 };
371456
+ }
371457
+ const text14 = src2.trim() ? src2 : "{}";
371458
+ const errs = [];
371459
+ const data3 = parse8(text14, errs, { allowTrailingComma: true });
371460
+ if (errs.length) {
371461
+ const err2 = errs[0];
371462
+ const lines = text14.substring(0, err2.offset).split(`
371093
371463
  `);
371094
- return {
371095
- ok: false,
371096
- code: "invalid_json",
371097
- kind: target2.kind,
371098
- file: cfg,
371099
- line: lines.length,
371100
- col: lines[lines.length - 1].length + 1,
371101
- parse: printParseErrorCode(err2.error)
371102
- };
371103
- }
371104
- const item2 = target2.opts ? [spec3, target2.opts] : spec3;
371105
- const out2 = patchPluginList(text14, pluginList(data3), spec3, item2, force);
371106
- if (out2.mode === "noop") {
371464
+ return {
371465
+ ok: false,
371466
+ code: "invalid_json",
371467
+ kind: target2.kind,
371468
+ file: cfg,
371469
+ line: lines.length,
371470
+ col: lines[lines.length - 1].length + 1,
371471
+ parse: printParseErrorCode(err2.error)
371472
+ };
371473
+ }
371474
+ const item2 = target2.opts ? [spec3, target2.opts] : spec3;
371475
+ const out2 = patchPluginList(text14, pluginList(data3), spec3, item2, force);
371476
+ if (out2.mode === "noop") {
371477
+ return { ok: true, item: { kind: target2.kind, mode: out2.mode, file: cfg } };
371478
+ }
371479
+ const write3 = await dep.write(cfg, out2.text).catch((error48) => error48);
371480
+ if (write3 instanceof Error) {
371481
+ return { ok: false, code: "patch_failed", kind: target2.kind, error: write3 };
371482
+ }
371107
371483
  return { ok: true, item: { kind: target2.kind, mode: out2.mode, file: cfg } };
371484
+ } catch (_catch3) {
371485
+ var _err = _catch3, _hasErr = 1;
371486
+ } finally {
371487
+ __callDispose(__stack, _err, _hasErr);
371108
371488
  }
371109
- const write3 = await dep.write(cfg, out2.text).catch((error48) => error48);
371110
- if (write3 instanceof Error) {
371111
- return { ok: false, code: "patch_failed", kind: target2.kind, error: write3 };
371112
- }
371113
- return { ok: true, item: { kind: target2.kind, mode: out2.mode, file: cfg } };
371114
371489
  }
371115
371490
  async function installPlugin(spec3, dep = installDep) {
371116
371491
  const target2 = await dep.resolve(spec3).then((item2) => ({ ok: true, item: item2 }), (error48) => ({ ok: false, error: error48 }));
@@ -386887,7 +387262,7 @@ var require_TraceState = __commonJS((exports) => {
386887
387262
  const value8 = listMember.slice(i9 + 1, part2.length);
386888
387263
  if ((0, validators_1.validateKey)(key4) && (0, validators_1.validateValue)(value8)) {
386889
387264
  agg.set(key4, value8);
386890
- }
387265
+ } else {}
386891
387266
  }
386892
387267
  return agg;
386893
387268
  }, new Map);
@@ -398833,9 +399208,16 @@ var SymbolsCommand = cmd({
398833
399208
  builder: (yargs) => yargs.positional("query", { type: "string", demandOption: true }),
398834
399209
  async handler(args3) {
398835
399210
  await bootstrap(process.cwd(), async () => {
398836
- using _5 = Log.Default.time("symbols");
398837
- const results = await LSP.workspaceSymbol(args3.query);
398838
- process.stdout.write(JSON.stringify(results, null, 2) + EOL7);
399211
+ let __stack = [];
399212
+ try {
399213
+ const _5 = __using(__stack, Log.Default.time("symbols"), 0);
399214
+ const results = await LSP.workspaceSymbol(args3.query);
399215
+ process.stdout.write(JSON.stringify(results, null, 2) + EOL7);
399216
+ } catch (_catch3) {
399217
+ var _err = _catch3, _hasErr = 1;
399218
+ } finally {
399219
+ __callDispose(__stack, _err, _hasErr);
399220
+ }
398839
399221
  });
398840
399222
  }
398841
399223
  });
@@ -398845,9 +399227,16 @@ var DocumentSymbolsCommand = cmd({
398845
399227
  builder: (yargs) => yargs.positional("uri", { type: "string", demandOption: true }),
398846
399228
  async handler(args3) {
398847
399229
  await bootstrap(process.cwd(), async () => {
398848
- using _5 = Log.Default.time("document-symbols");
398849
- const results = await LSP.documentSymbol(args3.uri);
398850
- process.stdout.write(JSON.stringify(results, null, 2) + EOL7);
399230
+ let __stack = [];
399231
+ try {
399232
+ const _5 = __using(__stack, Log.Default.time("document-symbols"), 0);
399233
+ const results = await LSP.documentSymbol(args3.uri);
399234
+ process.stdout.write(JSON.stringify(results, null, 2) + EOL7);
399235
+ } catch (_catch3) {
399236
+ var _err = _catch3, _hasErr = 1;
399237
+ } finally {
399238
+ __callDispose(__stack, _err, _hasErr);
399239
+ }
398851
399240
  });
398852
399241
  }
398853
399242
  });
@@ -405619,44 +406008,52 @@ var DaemonLauncher;
405619
406008
  return status2.clients > 0 || status2.busy || status2.permissions > 0 || status2.questions > 0 || status2.pty > 0;
405620
406009
  }
405621
406010
  async function ensure3(input2) {
405622
- const directory = DaemonRegistry.normalize(input2.directory);
405623
- const next4 = await wanted2(directory);
405624
- const ready2 = await current2(directory, input2.viewID);
405625
- if (ready2 && (!stale(ready2.health, next4) || active(ready2.health))) {
405626
- return {
405627
- url: ready2.info.url,
405628
- headers: headers(ready2.info.token)
405629
- };
405630
- }
405631
- if (ready2) {
405632
- await shutdown6(ready2.info);
405633
- await Bun.sleep(150);
405634
- }
405635
- await using _5 = await DaemonRegistry.acquire(directory, input2.viewID);
405636
- const second = await current2(directory, input2.viewID);
405637
- if (second && (!stale(second.health, next4) || active(second.health))) {
406011
+ let __stack = [];
406012
+ try {
406013
+ const directory = DaemonRegistry.normalize(input2.directory);
406014
+ const next4 = await wanted2(directory);
406015
+ const ready2 = await current2(directory, input2.viewID);
406016
+ if (ready2 && (!stale(ready2.health, next4) || active(ready2.health))) {
406017
+ return {
406018
+ url: ready2.info.url,
406019
+ headers: headers(ready2.info.token)
406020
+ };
406021
+ }
406022
+ if (ready2) {
406023
+ await shutdown6(ready2.info);
406024
+ await Bun.sleep(150);
406025
+ }
406026
+ const _5 = __using(__stack, await DaemonRegistry.acquire(directory, input2.viewID), 1);
406027
+ const second = await current2(directory, input2.viewID);
406028
+ if (second && (!stale(second.health, next4) || active(second.health))) {
406029
+ return {
406030
+ url: second.info.url,
406031
+ headers: headers(second.info.token)
406032
+ };
406033
+ }
406034
+ if (second) {
406035
+ await shutdown6(second.info);
406036
+ await Bun.sleep(150);
406037
+ }
406038
+ const token2 = randomUUID2();
406039
+ launch3({
406040
+ directory,
406041
+ viewID: input2.viewID,
406042
+ token: token2,
406043
+ idle_timeout_ms: next4.idle_timeout_ms,
406044
+ network: input2.network
406045
+ });
406046
+ const started = await wait2(directory, input2.viewID, android2() ? 45000 : 1e4);
405638
406047
  return {
405639
- url: second.info.url,
405640
- headers: headers(second.info.token)
406048
+ url: started.info.url,
406049
+ headers: headers(started.info.token)
405641
406050
  };
406051
+ } catch (_catch3) {
406052
+ var _err = _catch3, _hasErr = 1;
406053
+ } finally {
406054
+ var _promise2 = __callDispose(__stack, _err, _hasErr);
406055
+ _promise2 && await _promise2;
405642
406056
  }
405643
- if (second) {
405644
- await shutdown6(second.info);
405645
- await Bun.sleep(150);
405646
- }
405647
- const token2 = randomUUID2();
405648
- launch3({
405649
- directory,
405650
- viewID: input2.viewID,
405651
- token: token2,
405652
- idle_timeout_ms: next4.idle_timeout_ms,
405653
- network: input2.network
405654
- });
405655
- const started = await wait2(directory, input2.viewID, android2() ? 45000 : 1e4);
405656
- return {
405657
- url: started.info.url,
405658
- headers: headers(started.info.token)
405659
- };
405660
406057
  }
405661
406058
  DaemonLauncher.ensure = ensure3;
405662
406059
  })(DaemonLauncher ||= {});