@todoforai/edge 0.12.7 → 0.12.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1839 -153
  2. package/package.json +5 -2
package/dist/index.js CHANGED
@@ -2900,8 +2900,8 @@ var require_utils = __commonJS((exports) => {
2900
2900
  var lastError;
2901
2901
  for (var _i = 0, dirs_1 = dirs;_i < dirs_1.length; _i++) {
2902
2902
  var d = dirs_1[_i];
2903
- for (var _a = 0, relative_1 = relative;_a < relative_1.length; _a++) {
2904
- var r = relative_1[_a];
2903
+ for (var _a2 = 0, relative_1 = relative;_a2 < relative_1.length; _a2++) {
2904
+ var r = relative_1[_a2];
2905
2905
  var dir = r + "/" + d + "/";
2906
2906
  try {
2907
2907
  return { dir, module: __require(dir + "/" + name + ".node") };
@@ -2931,9 +2931,9 @@ var require_eventEmitter2 = __commonJS((exports) => {
2931
2931
  _this._listeners.push(listener);
2932
2932
  var disposable = {
2933
2933
  dispose: function() {
2934
- for (var i = 0;i < _this._listeners.length; i++) {
2935
- if (_this._listeners[i] === listener) {
2936
- _this._listeners.splice(i, 1);
2934
+ for (var i2 = 0;i2 < _this._listeners.length; i2++) {
2935
+ if (_this._listeners[i2] === listener) {
2936
+ _this._listeners.splice(i2, 1);
2937
2937
  return;
2938
2938
  }
2939
2939
  }
@@ -2949,11 +2949,11 @@ var require_eventEmitter2 = __commonJS((exports) => {
2949
2949
  });
2950
2950
  EventEmitter22.prototype.fire = function(data) {
2951
2951
  var queue = [];
2952
- for (var i = 0;i < this._listeners.length; i++) {
2953
- queue.push(this._listeners[i]);
2952
+ for (var i2 = 0;i2 < this._listeners.length; i2++) {
2953
+ queue.push(this._listeners[i2]);
2954
2954
  }
2955
- for (var i = 0;i < queue.length; i++) {
2956
- queue[i].call(undefined, data);
2955
+ for (var i2 = 0;i2 < queue.length; i2++) {
2956
+ queue[i2].call(undefined, data);
2957
2957
  }
2958
2958
  };
2959
2959
  return EventEmitter22;
@@ -3063,9 +3063,9 @@ var require_terminal = __commonJS((exports) => {
3063
3063
  }
3064
3064
  if (allowArray) {
3065
3065
  if (Array.isArray(value)) {
3066
- value.forEach(function(v, i) {
3066
+ value.forEach(function(v, i2) {
3067
3067
  if (typeof v !== type) {
3068
- throw new Error(name + "[" + i + "] must be a " + type + " (not a " + typeof v[i] + ")");
3068
+ throw new Error(name + "[" + i2 + "] must be a " + type + " (not a " + typeof v[i2] + ")");
3069
3069
  }
3070
3070
  });
3071
3071
  return;
@@ -3137,11 +3137,11 @@ var require_terminal = __commonJS((exports) => {
3137
3137
  Terminal2.prototype._parseEnv = function(env) {
3138
3138
  var keys = Object.keys(env || {});
3139
3139
  var pairs = [];
3140
- for (var i = 0;i < keys.length; i++) {
3141
- if (keys[i] === undefined) {
3140
+ for (var i2 = 0;i2 < keys.length; i2++) {
3141
+ if (keys[i2] === undefined) {
3142
3142
  continue;
3143
3143
  }
3144
- pairs.push(keys[i] + "=" + env[keys[i]]);
3144
+ pairs.push(keys[i2] + "=" + env[keys[i2]]);
3145
3145
  }
3146
3146
  return pairs;
3147
3147
  };
@@ -3323,12 +3323,12 @@ var require_windowsConoutConnection = __commonJS((exports) => {
3323
3323
  };
3324
3324
  ConoutConnection2.prototype._destroySocket = function() {
3325
3325
  return __awaiter(this, undefined, undefined, function() {
3326
- return __generator(this, function(_a) {
3327
- switch (_a.label) {
3326
+ return __generator(this, function(_a2) {
3327
+ switch (_a2.label) {
3328
3328
  case 0:
3329
3329
  return [4, this._worker.terminate()];
3330
3330
  case 1:
3331
- _a.sent();
3331
+ _a2.sent();
3332
3332
  return [2];
3333
3333
  }
3334
3334
  });
@@ -3344,7 +3344,7 @@ var require_windowsPtyAgent = __commonJS((exports) => {
3344
3344
  var __dirname = "/home/runner/work/edge/edge/bun/node_modules/node-pty/lib";
3345
3345
  Object.defineProperty(exports, "__esModule", { value: true });
3346
3346
  exports.argsToCommandLine = exports.WindowsPtyAgent = undefined;
3347
- var fs4 = __require("fs");
3347
+ var fs5 = __require("fs");
3348
3348
  var os3 = __require("os");
3349
3349
  var path5 = __require("path");
3350
3350
  var child_process_1 = __require("child_process");
@@ -3401,7 +3401,7 @@ var require_windowsPtyAgent = __commonJS((exports) => {
3401
3401
  this._outSocket.on("connect", function() {
3402
3402
  _this._outSocket.emit("ready_datapipe");
3403
3403
  });
3404
- var inSocketFD = fs4.openSync(term.conin, "w");
3404
+ var inSocketFD = fs5.openSync(term.conin, "w");
3405
3405
  this._inSocket = new net_1.Socket({
3406
3406
  fd: inSocketFD,
3407
3407
  readable: false,
@@ -3588,8 +3588,8 @@ var require_windowsPtyAgent = __commonJS((exports) => {
3588
3588
  result += '"';
3589
3589
  }
3590
3590
  var bsCount = 0;
3591
- for (var i = 0;i < arg.length; i++) {
3592
- var p = arg[i];
3591
+ for (var i2 = 0;i2 < arg.length; i2++) {
3592
+ var p = arg[i2];
3593
3593
  if (p === "\\") {
3594
3594
  bsCount++;
3595
3595
  } else if (p === '"') {
@@ -3617,7 +3617,7 @@ var require_windowsPtyAgent = __commonJS((exports) => {
3617
3617
  }
3618
3618
  function repeatText(text, count) {
3619
3619
  var result = "";
3620
- for (var i = 0;i < count; i++) {
3620
+ for (var i2 = 0;i2 < count; i2++) {
3621
3621
  result += text;
3622
3622
  }
3623
3623
  return result;
@@ -3631,12 +3631,12 @@ var require_windowsPtyAgent = __commonJS((exports) => {
3631
3631
  var require_windowsTerminal = __commonJS((exports) => {
3632
3632
  var __extends = exports && exports.__extends || function() {
3633
3633
  var extendStatics = function(d, b) {
3634
- extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
3635
- d2.__proto__ = b2;
3636
- } || function(d2, b2) {
3637
- for (var p in b2)
3638
- if (b2.hasOwnProperty(p))
3639
- d2[p] = b2[p];
3634
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b3) {
3635
+ d2.__proto__ = b3;
3636
+ } || function(d2, b3) {
3637
+ for (var p in b3)
3638
+ if (b3.hasOwnProperty(p))
3639
+ d2[p] = b3[p];
3640
3640
  };
3641
3641
  return extendStatics(d, b);
3642
3642
  };
@@ -3690,14 +3690,14 @@ var require_windowsTerminal = __commonJS((exports) => {
3690
3690
  _this._deferreds = [];
3691
3691
  }
3692
3692
  });
3693
- _this._socket.on("error", function(err) {
3693
+ _this._socket.on("error", function(err2) {
3694
3694
  _this._close();
3695
- if (err.code) {
3696
- if (~err.code.indexOf("errno 5") || ~err.code.indexOf("EIO"))
3695
+ if (err2.code) {
3696
+ if (~err2.code.indexOf("errno 5") || ~err2.code.indexOf("EIO"))
3697
3697
  return;
3698
3698
  }
3699
3699
  if (_this.listeners("error").length < 2) {
3700
- throw err;
3700
+ throw err2;
3701
3701
  }
3702
3702
  });
3703
3703
  _this._socket.on("close", function() {
@@ -3809,12 +3809,12 @@ var require_unixTerminal = __commonJS((exports) => {
3809
3809
  var __dirname = "/home/runner/work/edge/edge/bun/node_modules/node-pty/lib";
3810
3810
  var __extends = exports && exports.__extends || function() {
3811
3811
  var extendStatics = function(d, b) {
3812
- extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
3813
- d2.__proto__ = b2;
3814
- } || function(d2, b2) {
3815
- for (var p in b2)
3816
- if (b2.hasOwnProperty(p))
3817
- d2[p] = b2[p];
3812
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b3) {
3813
+ d2.__proto__ = b3;
3814
+ } || function(d2, b3) {
3815
+ for (var p in b3)
3816
+ if (b3.hasOwnProperty(p))
3817
+ d2[p] = b3[p];
3818
3818
  };
3819
3819
  return extendStatics(d, b);
3820
3820
  };
@@ -3828,7 +3828,7 @@ var require_unixTerminal = __commonJS((exports) => {
3828
3828
  }();
3829
3829
  Object.defineProperty(exports, "__esModule", { value: true });
3830
3830
  exports.UnixTerminal = undefined;
3831
- var fs4 = __require("fs");
3831
+ var fs5 = __require("fs");
3832
3832
  var path5 = __require("path");
3833
3833
  var tty = __require("tty");
3834
3834
  var terminal_1 = require_terminal();
@@ -3845,7 +3845,7 @@ var require_unixTerminal = __commonJS((exports) => {
3845
3845
  var UnixTerminal = function(_super) {
3846
3846
  __extends(UnixTerminal2, _super);
3847
3847
  function UnixTerminal2(file, args, opt) {
3848
- var _a, _b;
3848
+ var _a2, _b2;
3849
3849
  var _this = _super.call(this, opt) || this;
3850
3850
  _this._boundClose = false;
3851
3851
  _this._emittedClose = false;
@@ -3858,8 +3858,8 @@ var require_unixTerminal = __commonJS((exports) => {
3858
3858
  opt.env = opt.env || process.env;
3859
3859
  _this._cols = opt.cols || terminal_1.DEFAULT_COLS;
3860
3860
  _this._rows = opt.rows || terminal_1.DEFAULT_ROWS;
3861
- var uid = (_a = opt.uid) !== null && _a !== undefined ? _a : -1;
3862
- var gid = (_b = opt.gid) !== null && _b !== undefined ? _b : -1;
3861
+ var uid = (_a2 = opt.uid) !== null && _a2 !== undefined ? _a2 : -1;
3862
+ var gid = (_b2 = opt.gid) !== null && _b2 !== undefined ? _b2 : -1;
3863
3863
  var env = utils_1.assign({}, opt.env);
3864
3864
  if (opt.env === process.env) {
3865
3865
  _this._sanitizeEnv(env);
@@ -3896,9 +3896,9 @@ var require_unixTerminal = __commonJS((exports) => {
3896
3896
  _this._socket.setEncoding(encoding);
3897
3897
  }
3898
3898
  _this._writeStream = new CustomWriteStream(term.fd, encoding || undefined);
3899
- _this._socket.on("error", function(err) {
3900
- if (err.code) {
3901
- if (~err.code.indexOf("EAGAIN")) {
3899
+ _this._socket.on("error", function(err2) {
3900
+ if (err2.code) {
3901
+ if (~err2.code.indexOf("EAGAIN")) {
3902
3902
  return;
3903
3903
  }
3904
3904
  }
@@ -3907,13 +3907,13 @@ var require_unixTerminal = __commonJS((exports) => {
3907
3907
  _this._emittedClose = true;
3908
3908
  _this.emit("close");
3909
3909
  }
3910
- if (err.code) {
3911
- if (~err.code.indexOf("errno 5") || ~err.code.indexOf("EIO")) {
3910
+ if (err2.code) {
3911
+ if (~err2.code.indexOf("errno 5") || ~err2.code.indexOf("EIO")) {
3912
3912
  return;
3913
3913
  }
3914
3914
  }
3915
3915
  if (_this.listeners("error").length < 2) {
3916
- throw err;
3916
+ throw err2;
3917
3917
  }
3918
3918
  });
3919
3919
  _this._pid = term.pid;
@@ -3996,10 +3996,10 @@ var require_unixTerminal = __commonJS((exports) => {
3996
3996
  self._name = process.env.TERM || "";
3997
3997
  self._readable = true;
3998
3998
  self._writable = true;
3999
- self._socket.on("error", function(err) {
3999
+ self._socket.on("error", function(err2) {
4000
4000
  self._close();
4001
4001
  if (self.listeners("error").length < 2) {
4002
- throw err;
4002
+ throw err2;
4003
4003
  }
4004
4004
  });
4005
4005
  self._socket.on("close", function() {
@@ -4080,15 +4080,15 @@ var require_unixTerminal = __commonJS((exports) => {
4080
4080
  return;
4081
4081
  }
4082
4082
  var task = this._writeQueue[0];
4083
- fs4.write(this._fd, task.buffer, task.offset, function(err, written) {
4084
- if (err) {
4085
- if ("code" in err && err.code === "EAGAIN") {
4083
+ fs5.write(this._fd, task.buffer, task.offset, function(err2, written) {
4084
+ if (err2) {
4085
+ if ("code" in err2 && err2.code === "EAGAIN") {
4086
4086
  _this._writeImmediate = setImmediate(function() {
4087
4087
  return _this._processWriteQueue();
4088
4088
  });
4089
4089
  } else {
4090
4090
  _this._writeQueue.length = 0;
4091
- console.error("Unhandled pty write error", err);
4091
+ console.error("Unhandled pty write error", err2);
4092
4092
  }
4093
4093
  return;
4094
4094
  }
@@ -4133,6 +4133,333 @@ var require_lib = __commonJS((exports) => {
4133
4133
  exports.native = process.platform !== "win32" ? utils_1.loadNativeModule("pty").module : null;
4134
4134
  });
4135
4135
 
4136
+ // node_modules/ignore/index.js
4137
+ var require_ignore = __commonJS((exports, module) => {
4138
+ function makeArray(subject) {
4139
+ return Array.isArray(subject) ? subject : [subject];
4140
+ }
4141
+ var UNDEFINED = undefined;
4142
+ var EMPTY = "";
4143
+ var SPACE = " ";
4144
+ var ESCAPE = "\\";
4145
+ var REGEX_TEST_BLANK_LINE = /^\s+$/;
4146
+ var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
4147
+ var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
4148
+ var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
4149
+ var REGEX_SPLITALL_CRLF = /\r?\n/g;
4150
+ var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
4151
+ var REGEX_TEST_TRAILING_SLASH = /\/$/;
4152
+ var SLASH = "/";
4153
+ var TMP_KEY_IGNORE = "node-ignore";
4154
+ if (typeof Symbol !== "undefined") {
4155
+ TMP_KEY_IGNORE = Symbol.for("node-ignore");
4156
+ }
4157
+ var KEY_IGNORE = TMP_KEY_IGNORE;
4158
+ var define = (object, key, value) => {
4159
+ Object.defineProperty(object, key, { value });
4160
+ return value;
4161
+ };
4162
+ var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
4163
+ var RETURN_FALSE = () => false;
4164
+ var sanitizeRange = (range) => range.replace(REGEX_REGEXP_RANGE, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY);
4165
+ var cleanRangeBackSlash = (slashes) => {
4166
+ const { length } = slashes;
4167
+ return slashes.slice(0, length - length % 2);
4168
+ };
4169
+ var REPLACERS = [
4170
+ [
4171
+ /^\uFEFF/,
4172
+ () => EMPTY
4173
+ ],
4174
+ [
4175
+ /((?:\\\\)*?)(\\?\s+)$/,
4176
+ (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY)
4177
+ ],
4178
+ [
4179
+ /(\\+?)\s/g,
4180
+ (_, m1) => {
4181
+ const { length } = m1;
4182
+ return m1.slice(0, length - length % 2) + SPACE;
4183
+ }
4184
+ ],
4185
+ [
4186
+ /[\\$.|*+(){^]/g,
4187
+ (match) => `\\${match}`
4188
+ ],
4189
+ [
4190
+ /(?!\\)\?/g,
4191
+ () => "[^/]"
4192
+ ],
4193
+ [
4194
+ /^\//,
4195
+ () => "^"
4196
+ ],
4197
+ [
4198
+ /\//g,
4199
+ () => "\\/"
4200
+ ],
4201
+ [
4202
+ /^\^*\\\*\\\*\\\//,
4203
+ () => "^(?:.*\\/)?"
4204
+ ],
4205
+ [
4206
+ /^(?=[^^])/,
4207
+ function startingReplacer() {
4208
+ return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
4209
+ }
4210
+ ],
4211
+ [
4212
+ /\\\/\\\*\\\*(?=\\\/|$)/g,
4213
+ (_, index, str) => index + 6 < str.length ? "(?:\\/[^\\/]+)*" : "\\/.+"
4214
+ ],
4215
+ [
4216
+ /(^|[^\\]+)(\\\*)+(?=.+)/g,
4217
+ (_, p1, p2) => {
4218
+ const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
4219
+ return p1 + unescaped;
4220
+ }
4221
+ ],
4222
+ [
4223
+ /\\\\\\(?=[$.|*+(){^])/g,
4224
+ () => ESCAPE
4225
+ ],
4226
+ [
4227
+ /\\\\/g,
4228
+ () => ESCAPE
4229
+ ],
4230
+ [
4231
+ /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
4232
+ (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]"
4233
+ ],
4234
+ [
4235
+ /(?:[^*])$/,
4236
+ (match) => /\/$/.test(match) ? `${match}$` : `${match}(?=$|\\/$)`
4237
+ ]
4238
+ ];
4239
+ var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\\\*$/;
4240
+ var MODE_IGNORE = "regex";
4241
+ var MODE_CHECK_IGNORE = "checkRegex";
4242
+ var UNDERSCORE = "_";
4243
+ var TRAILING_WILD_CARD_REPLACERS = {
4244
+ [MODE_IGNORE](_, p1) {
4245
+ const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
4246
+ return `${prefix}(?=$|\\/$)`;
4247
+ },
4248
+ [MODE_CHECK_IGNORE](_, p1) {
4249
+ const prefix = p1 ? `${p1}[^/]*` : "[^/]*";
4250
+ return `${prefix}(?=$|\\/$)`;
4251
+ }
4252
+ };
4253
+ var makeRegexPrefix = (pattern) => REPLACERS.reduce((prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern)), pattern);
4254
+ var isString = (subject) => typeof subject === "string";
4255
+ var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
4256
+ var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);
4257
+
4258
+ class IgnoreRule {
4259
+ constructor(pattern, mark, body, ignoreCase, negative, prefix) {
4260
+ this.pattern = pattern;
4261
+ this.mark = mark;
4262
+ this.negative = negative;
4263
+ define(this, "body", body);
4264
+ define(this, "ignoreCase", ignoreCase);
4265
+ define(this, "regexPrefix", prefix);
4266
+ }
4267
+ get regex() {
4268
+ const key = UNDERSCORE + MODE_IGNORE;
4269
+ if (this[key]) {
4270
+ return this[key];
4271
+ }
4272
+ return this._make(MODE_IGNORE, key);
4273
+ }
4274
+ get checkRegex() {
4275
+ const key = UNDERSCORE + MODE_CHECK_IGNORE;
4276
+ if (this[key]) {
4277
+ return this[key];
4278
+ }
4279
+ return this._make(MODE_CHECK_IGNORE, key);
4280
+ }
4281
+ _make(mode, key) {
4282
+ const str = this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD, TRAILING_WILD_CARD_REPLACERS[mode]);
4283
+ const regex = this.ignoreCase ? new RegExp(str, "i") : new RegExp(str);
4284
+ return define(this, key, regex);
4285
+ }
4286
+ }
4287
+ var createRule = ({
4288
+ pattern,
4289
+ mark
4290
+ }, ignoreCase) => {
4291
+ let negative = false;
4292
+ let body = pattern;
4293
+ if (body.indexOf("!") === 0) {
4294
+ negative = true;
4295
+ body = body.substr(1);
4296
+ }
4297
+ body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
4298
+ const regexPrefix = makeRegexPrefix(body);
4299
+ return new IgnoreRule(pattern, mark, body, ignoreCase, negative, regexPrefix);
4300
+ };
4301
+
4302
+ class RuleManager {
4303
+ constructor(ignoreCase) {
4304
+ this._ignoreCase = ignoreCase;
4305
+ this._rules = [];
4306
+ }
4307
+ _add(pattern) {
4308
+ if (pattern && pattern[KEY_IGNORE]) {
4309
+ this._rules = this._rules.concat(pattern._rules._rules);
4310
+ this._added = true;
4311
+ return;
4312
+ }
4313
+ if (isString(pattern)) {
4314
+ pattern = {
4315
+ pattern
4316
+ };
4317
+ }
4318
+ if (checkPattern(pattern.pattern)) {
4319
+ const rule = createRule(pattern, this._ignoreCase);
4320
+ this._added = true;
4321
+ this._rules.push(rule);
4322
+ }
4323
+ }
4324
+ add(pattern) {
4325
+ this._added = false;
4326
+ makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._add, this);
4327
+ return this._added;
4328
+ }
4329
+ test(path6, checkUnignored, mode) {
4330
+ let ignored = false;
4331
+ let unignored = false;
4332
+ let matchedRule;
4333
+ this._rules.forEach((rule) => {
4334
+ const { negative } = rule;
4335
+ if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
4336
+ return;
4337
+ }
4338
+ const matched = rule[mode].test(path6);
4339
+ if (!matched) {
4340
+ return;
4341
+ }
4342
+ ignored = !negative;
4343
+ unignored = negative;
4344
+ matchedRule = negative ? UNDEFINED : rule;
4345
+ });
4346
+ const ret = {
4347
+ ignored,
4348
+ unignored
4349
+ };
4350
+ if (matchedRule) {
4351
+ ret.rule = matchedRule;
4352
+ }
4353
+ return ret;
4354
+ }
4355
+ }
4356
+ var throwError = (message, Ctor) => {
4357
+ throw new Ctor(message);
4358
+ };
4359
+ var checkPath = (path6, originalPath, doThrow) => {
4360
+ if (!isString(path6)) {
4361
+ return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
4362
+ }
4363
+ if (!path6) {
4364
+ return doThrow(`path must not be empty`, TypeError);
4365
+ }
4366
+ if (checkPath.isNotRelative(path6)) {
4367
+ const r = "`path.relative()`d";
4368
+ return doThrow(`path should be a ${r} string, but got "${originalPath}"`, RangeError);
4369
+ }
4370
+ return true;
4371
+ };
4372
+ var isNotRelative = (path6) => REGEX_TEST_INVALID_PATH.test(path6);
4373
+ checkPath.isNotRelative = isNotRelative;
4374
+ checkPath.convert = (p) => p;
4375
+
4376
+ class Ignore {
4377
+ constructor({
4378
+ ignorecase = true,
4379
+ ignoreCase = ignorecase,
4380
+ allowRelativePaths = false
4381
+ } = {}) {
4382
+ define(this, KEY_IGNORE, true);
4383
+ this._rules = new RuleManager(ignoreCase);
4384
+ this._strictPathCheck = !allowRelativePaths;
4385
+ this._initCache();
4386
+ }
4387
+ _initCache() {
4388
+ this._ignoreCache = Object.create(null);
4389
+ this._testCache = Object.create(null);
4390
+ }
4391
+ add(pattern) {
4392
+ if (this._rules.add(pattern)) {
4393
+ this._initCache();
4394
+ }
4395
+ return this;
4396
+ }
4397
+ addPattern(pattern) {
4398
+ return this.add(pattern);
4399
+ }
4400
+ _test(originalPath, cache, checkUnignored, slices) {
4401
+ const path6 = originalPath && checkPath.convert(originalPath);
4402
+ checkPath(path6, originalPath, this._strictPathCheck ? throwError : RETURN_FALSE);
4403
+ return this._t(path6, cache, checkUnignored, slices);
4404
+ }
4405
+ checkIgnore(path6) {
4406
+ if (!REGEX_TEST_TRAILING_SLASH.test(path6)) {
4407
+ return this.test(path6);
4408
+ }
4409
+ const slices = path6.split(SLASH).filter(Boolean);
4410
+ slices.pop();
4411
+ if (slices.length) {
4412
+ const parent = this._t(slices.join(SLASH) + SLASH, this._testCache, true, slices);
4413
+ if (parent.ignored) {
4414
+ return parent;
4415
+ }
4416
+ }
4417
+ return this._rules.test(path6, false, MODE_CHECK_IGNORE);
4418
+ }
4419
+ _t(path6, cache, checkUnignored, slices) {
4420
+ if (path6 in cache) {
4421
+ return cache[path6];
4422
+ }
4423
+ if (!slices) {
4424
+ slices = path6.split(SLASH).filter(Boolean);
4425
+ }
4426
+ slices.pop();
4427
+ if (!slices.length) {
4428
+ return cache[path6] = this._rules.test(path6, checkUnignored, MODE_IGNORE);
4429
+ }
4430
+ const parent = this._t(slices.join(SLASH) + SLASH, cache, checkUnignored, slices);
4431
+ return cache[path6] = parent.ignored ? parent : this._rules.test(path6, checkUnignored, MODE_IGNORE);
4432
+ }
4433
+ ignores(path6) {
4434
+ return this._test(path6, this._ignoreCache, false).ignored;
4435
+ }
4436
+ createFilter() {
4437
+ return (path6) => !this.ignores(path6);
4438
+ }
4439
+ filter(paths) {
4440
+ return makeArray(paths).filter(this.createFilter());
4441
+ }
4442
+ test(path6) {
4443
+ return this._test(path6, this._testCache, true);
4444
+ }
4445
+ }
4446
+ var factory = (options) => new Ignore(options);
4447
+ var isPathValid = (path6) => checkPath(path6 && checkPath.convert(path6), path6, RETURN_FALSE);
4448
+ var setupWindows = () => {
4449
+ const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
4450
+ checkPath.convert = makePosix;
4451
+ const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
4452
+ checkPath.isNotRelative = (path6) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path6) || isNotRelative(path6);
4453
+ };
4454
+ if (typeof process !== "undefined" && process.platform === "win32") {
4455
+ setupWindows();
4456
+ }
4457
+ module.exports = factory;
4458
+ factory.default = factory;
4459
+ module.exports.isPathValid = isPathValid;
4460
+ define(module.exports, Symbol.for("setupWindows"), setupWindows);
4461
+ });
4462
+
4136
4463
  // src/config.ts
4137
4464
  import { parseArgs } from "util";
4138
4465
  import path from "path";
@@ -4202,6 +4529,9 @@ var FE = {
4202
4529
  TASK_ACTION_NEW: "task_action:new",
4203
4530
  EDGE_CD: "edge:cd",
4204
4531
  GET_FOLDERS: "edge:get_folders",
4532
+ EDGE_CREATE_FOLDER: "edge:create_folder",
4533
+ EDGE_DELETE_PATH: "edge:delete_path",
4534
+ EDGE_WRITE_FILE: "edge:write_file",
4205
4535
  BLOCK_EXECUTE: "block:execute",
4206
4536
  BLOCK_SAVE: "block:save",
4207
4537
  BLOCK_KEYBOARD: "block:keyboard",
@@ -4225,6 +4555,9 @@ var EF = {
4225
4555
  EDGE_STATUS: "edge:status",
4226
4556
  EDGE_CD_RESPONSE: "edge:cd_response",
4227
4557
  EDGE_GET_FOLDERS_RESPONSE: "edge:get_folders_response",
4558
+ EDGE_CREATE_FOLDER_RESPONSE: "edge:create_folder_response",
4559
+ EDGE_DELETE_PATH_RESPONSE: "edge:delete_path_response",
4560
+ EDGE_WRITE_FILE_RESPONSE: "edge:write_file_response",
4228
4561
  BLOCK_SAVE_RESULT: "block:save_result",
4229
4562
  BLOCK_ERROR_RESULT: "block:error_result",
4230
4563
  BLOCK_META_RESULT: "block:meta_result",
@@ -4304,6 +4637,24 @@ var msg = {
4304
4637
  payload.error = error;
4305
4638
  return { type: EA.FUNCTION_CALL_RESULT_AGENT, payload };
4306
4639
  },
4640
+ createFolderResponse(requestId, edgeId, success, error) {
4641
+ const payload = { requestId, edgeId, success };
4642
+ if (error)
4643
+ payload.error = error;
4644
+ return { type: EF.EDGE_CREATE_FOLDER_RESPONSE, payload };
4645
+ },
4646
+ deletePathResponse(requestId, edgeId, success, error) {
4647
+ const payload = { requestId, edgeId, success };
4648
+ if (error)
4649
+ payload.error = error;
4650
+ return { type: EF.EDGE_DELETE_PATH_RESPONSE, payload };
4651
+ },
4652
+ writeFileResponse(requestId, edgeId, success, error) {
4653
+ const payload = { requestId, edgeId, success };
4654
+ if (error)
4655
+ payload.error = error;
4656
+ return { type: EF.EDGE_WRITE_FILE_RESPONSE, payload };
4657
+ },
4307
4658
  functionCallResultFront(requestId, edgeId, success, result, error, blockInfo) {
4308
4659
  const payload = { requestId, edgeId, success };
4309
4660
  if (result != null)
@@ -4385,8 +4736,14 @@ class ApiClient {
4385
4736
  updateTodoStatus(todoId, status) {
4386
4737
  return this.request("PUT", `/api/v1/todos/${todoId}`, { status });
4387
4738
  }
4388
- listAgentSettings() {
4389
- return this.request("GET", "/api/v1/agents");
4739
+ listAgentSettings(filters) {
4740
+ const params = new URLSearchParams;
4741
+ if (filters?.workspacePath)
4742
+ params.set("workspacePath", filters.workspacePath);
4743
+ if (filters?.name)
4744
+ params.set("name", filters.name);
4745
+ const qs = params.toString();
4746
+ return this.request("GET", `/api/v1/agents${qs ? `?${qs}` : ""}`);
4390
4747
  }
4391
4748
  getAgentSettings(id) {
4392
4749
  return this.request("GET", `/api/v1/agents/${id}`);
@@ -4428,6 +4785,8 @@ class FrontendWebSocket {
4428
4785
  callbacks = new Map;
4429
4786
  completionEvents = new Map;
4430
4787
  completionResults = new Map;
4788
+ pendingBlocks = new Map;
4789
+ lastReadyPayload = new Map;
4431
4790
  constructor(apiUrl, apiKey) {
4432
4791
  this.apiUrl = apiUrl;
4433
4792
  this.apiKey = apiKey;
@@ -4476,6 +4835,8 @@ class FrontendWebSocket {
4476
4835
  this.callbacks.clear();
4477
4836
  this.completionEvents.clear();
4478
4837
  this.completionResults.clear();
4838
+ this.pendingBlocks.clear();
4839
+ this.lastReadyPayload.clear();
4479
4840
  }
4480
4841
  handleMessage(data) {
4481
4842
  const msgType = data.type || "";
@@ -4488,9 +4849,38 @@ class FrontendWebSocket {
4488
4849
  this.callbacks.get(todoId)(msgType, payload);
4489
4850
  } catch {}
4490
4851
  }
4491
- if (msgType === "todo:msg_done" && todoId) {
4492
- this.completionResults.set(todoId, { type: msgType, payload, success: true });
4493
- this.completionEvents.get(todoId)?.resolve(this.completionResults.get(todoId));
4852
+ if (msgType === "BLOCK_UPDATE" && todoId && payload.blockId && payload.updates?.status === "AWAITING_APPROVAL") {
4853
+ if (!this.pendingBlocks.has(todoId))
4854
+ this.pendingBlocks.set(todoId, new Set);
4855
+ this.pendingBlocks.get(todoId).add(payload.blockId);
4856
+ }
4857
+ if (msgType === "BLOCK_UPDATE" && todoId && payload.blockId) {
4858
+ const status = payload.updates?.status;
4859
+ if (["COMPLETED", "DENIED", "FAILED", "ERROR"].includes(status)) {
4860
+ this.pendingBlocks.get(todoId)?.delete(payload.blockId);
4861
+ const pending = this.pendingBlocks.get(todoId);
4862
+ if (!pending || pending.size === 0) {
4863
+ this.lastReadyPayload.delete(todoId);
4864
+ }
4865
+ }
4866
+ }
4867
+ if (msgType === "todo:status" && todoId) {
4868
+ const status = payload.status;
4869
+ if (status === "RUNNING") {
4870
+ this.lastReadyPayload.delete(todoId);
4871
+ } else if (status === "READY" || status === "READY_CHECKED") {
4872
+ const pending = this.pendingBlocks.get(todoId);
4873
+ if (!pending || pending.size === 0) {
4874
+ this.completionResults.set(todoId, { type: msgType, payload, success: true });
4875
+ this.completionEvents.get(todoId)?.resolve(this.completionResults.get(todoId));
4876
+ } else {
4877
+ this.lastReadyPayload.set(todoId, payload);
4878
+ }
4879
+ } else if (["DONE", "CANCELLED", "CANCELLED_CHECKED", "ERROR", "ERROR_CHECKED"].includes(status)) {
4880
+ const success = status === "DONE";
4881
+ this.completionResults.set(todoId, { type: msgType, payload, success });
4882
+ this.completionEvents.get(todoId)?.resolve(this.completionResults.get(todoId));
4883
+ }
4494
4884
  }
4495
4885
  }
4496
4886
  async subscribe(todoId, callback) {
@@ -4574,7 +4964,8 @@ class FrontendWebSocket {
4574
4964
  }
4575
4965
 
4576
4966
  // src/handlers.ts
4577
- import fs6 from "fs";
4967
+ import fs7 from "fs";
4968
+ import { mkdir, rm, writeFile } from "fs/promises";
4578
4969
  import path7 from "path";
4579
4970
 
4580
4971
  // src/path-utils.ts
@@ -4672,30 +5063,1077 @@ function getPathOrDefault(p) {
4672
5063
  }
4673
5064
 
4674
5065
  // src/files.ts
4675
- import fs2 from "fs";
5066
+ import fs3 from "fs";
4676
5067
  import path3 from "path";
5068
+
5069
+ // src/docx-handler.ts
5070
+ import fs2 from "fs";
5071
+
5072
+ // node_modules/fflate/esm/index.mjs
5073
+ import { createRequire as createRequire2 } from "module";
5074
+ var require2 = createRequire2("/");
5075
+ var Worker;
5076
+ try {
5077
+ Worker = require2("worker_threads").Worker;
5078
+ } catch (e) {}
5079
+ var u8 = Uint8Array;
5080
+ var u16 = Uint16Array;
5081
+ var i32 = Int32Array;
5082
+ var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0, 0]);
5083
+ var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0]);
5084
+ var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
5085
+ var freb = function(eb, start) {
5086
+ var b = new u16(31);
5087
+ for (var i = 0;i < 31; ++i) {
5088
+ b[i] = start += 1 << eb[i - 1];
5089
+ }
5090
+ var r = new i32(b[30]);
5091
+ for (var i = 1;i < 30; ++i) {
5092
+ for (var j = b[i];j < b[i + 1]; ++j) {
5093
+ r[j] = j - b[i] << 5 | i;
5094
+ }
5095
+ }
5096
+ return { b, r };
5097
+ };
5098
+ var _a = freb(fleb, 2);
5099
+ var fl = _a.b;
5100
+ var revfl = _a.r;
5101
+ fl[28] = 258, revfl[258] = 28;
5102
+ var _b = freb(fdeb, 0);
5103
+ var fd = _b.b;
5104
+ var revfd = _b.r;
5105
+ var rev = new u16(32768);
5106
+ for (i = 0;i < 32768; ++i) {
5107
+ x = (i & 43690) >> 1 | (i & 21845) << 1;
5108
+ x = (x & 52428) >> 2 | (x & 13107) << 2;
5109
+ x = (x & 61680) >> 4 | (x & 3855) << 4;
5110
+ rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1;
5111
+ }
5112
+ var x;
5113
+ var i;
5114
+ var hMap = function(cd, mb, r) {
5115
+ var s = cd.length;
5116
+ var i2 = 0;
5117
+ var l = new u16(mb);
5118
+ for (;i2 < s; ++i2) {
5119
+ if (cd[i2])
5120
+ ++l[cd[i2] - 1];
5121
+ }
5122
+ var le = new u16(mb);
5123
+ for (i2 = 1;i2 < mb; ++i2) {
5124
+ le[i2] = le[i2 - 1] + l[i2 - 1] << 1;
5125
+ }
5126
+ var co;
5127
+ if (r) {
5128
+ co = new u16(1 << mb);
5129
+ var rvb = 15 - mb;
5130
+ for (i2 = 0;i2 < s; ++i2) {
5131
+ if (cd[i2]) {
5132
+ var sv = i2 << 4 | cd[i2];
5133
+ var r_1 = mb - cd[i2];
5134
+ var v = le[cd[i2] - 1]++ << r_1;
5135
+ for (var m = v | (1 << r_1) - 1;v <= m; ++v) {
5136
+ co[rev[v] >> rvb] = sv;
5137
+ }
5138
+ }
5139
+ }
5140
+ } else {
5141
+ co = new u16(s);
5142
+ for (i2 = 0;i2 < s; ++i2) {
5143
+ if (cd[i2]) {
5144
+ co[i2] = rev[le[cd[i2] - 1]++] >> 15 - cd[i2];
5145
+ }
5146
+ }
5147
+ }
5148
+ return co;
5149
+ };
5150
+ var flt = new u8(288);
5151
+ for (i = 0;i < 144; ++i)
5152
+ flt[i] = 8;
5153
+ var i;
5154
+ for (i = 144;i < 256; ++i)
5155
+ flt[i] = 9;
5156
+ var i;
5157
+ for (i = 256;i < 280; ++i)
5158
+ flt[i] = 7;
5159
+ var i;
5160
+ for (i = 280;i < 288; ++i)
5161
+ flt[i] = 8;
5162
+ var i;
5163
+ var fdt = new u8(32);
5164
+ for (i = 0;i < 32; ++i)
5165
+ fdt[i] = 5;
5166
+ var i;
5167
+ var flm = /* @__PURE__ */ hMap(flt, 9, 0);
5168
+ var flrm = /* @__PURE__ */ hMap(flt, 9, 1);
5169
+ var fdm = /* @__PURE__ */ hMap(fdt, 5, 0);
5170
+ var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
5171
+ var max = function(a) {
5172
+ var m = a[0];
5173
+ for (var i2 = 1;i2 < a.length; ++i2) {
5174
+ if (a[i2] > m)
5175
+ m = a[i2];
5176
+ }
5177
+ return m;
5178
+ };
5179
+ var bits = function(d, p, m) {
5180
+ var o = p / 8 | 0;
5181
+ return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
5182
+ };
5183
+ var bits16 = function(d, p) {
5184
+ var o = p / 8 | 0;
5185
+ return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
5186
+ };
5187
+ var shft = function(p) {
5188
+ return (p + 7) / 8 | 0;
5189
+ };
5190
+ var slc = function(v, s, e) {
5191
+ if (s == null || s < 0)
5192
+ s = 0;
5193
+ if (e == null || e > v.length)
5194
+ e = v.length;
5195
+ return new u8(v.subarray(s, e));
5196
+ };
5197
+ var ec = [
5198
+ "unexpected EOF",
5199
+ "invalid block type",
5200
+ "invalid length/literal",
5201
+ "invalid distance",
5202
+ "stream finished",
5203
+ "no stream handler",
5204
+ ,
5205
+ "no callback",
5206
+ "invalid UTF-8 data",
5207
+ "extra field too long",
5208
+ "date not in range 1980-2099",
5209
+ "filename too long",
5210
+ "stream finishing",
5211
+ "invalid zip data"
5212
+ ];
5213
+ var err = function(ind, msg2, nt) {
5214
+ var e = new Error(msg2 || ec[ind]);
5215
+ e.code = ind;
5216
+ if (Error.captureStackTrace)
5217
+ Error.captureStackTrace(e, err);
5218
+ if (!nt)
5219
+ throw e;
5220
+ return e;
5221
+ };
5222
+ var inflt = function(dat, st, buf, dict) {
5223
+ var sl = dat.length, dl = dict ? dict.length : 0;
5224
+ if (!sl || st.f && !st.l)
5225
+ return buf || new u8(0);
5226
+ var noBuf = !buf;
5227
+ var resize = noBuf || st.i != 2;
5228
+ var noSt = st.i;
5229
+ if (noBuf)
5230
+ buf = new u8(sl * 3);
5231
+ var cbuf = function(l2) {
5232
+ var bl = buf.length;
5233
+ if (l2 > bl) {
5234
+ var nbuf = new u8(Math.max(bl * 2, l2));
5235
+ nbuf.set(buf);
5236
+ buf = nbuf;
5237
+ }
5238
+ };
5239
+ var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
5240
+ var tbts = sl * 8;
5241
+ do {
5242
+ if (!lm) {
5243
+ final = bits(dat, pos, 1);
5244
+ var type = bits(dat, pos + 1, 3);
5245
+ pos += 3;
5246
+ if (!type) {
5247
+ var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l;
5248
+ if (t > sl) {
5249
+ if (noSt)
5250
+ err(0);
5251
+ break;
5252
+ }
5253
+ if (resize)
5254
+ cbuf(bt + l);
5255
+ buf.set(dat.subarray(s, t), bt);
5256
+ st.b = bt += l, st.p = pos = t * 8, st.f = final;
5257
+ continue;
5258
+ } else if (type == 1)
5259
+ lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
5260
+ else if (type == 2) {
5261
+ var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
5262
+ var tl = hLit + bits(dat, pos + 5, 31) + 1;
5263
+ pos += 14;
5264
+ var ldt = new u8(tl);
5265
+ var clt = new u8(19);
5266
+ for (var i2 = 0;i2 < hcLen; ++i2) {
5267
+ clt[clim[i2]] = bits(dat, pos + i2 * 3, 7);
5268
+ }
5269
+ pos += hcLen * 3;
5270
+ var clb = max(clt), clbmsk = (1 << clb) - 1;
5271
+ var clm = hMap(clt, clb, 1);
5272
+ for (var i2 = 0;i2 < tl; ) {
5273
+ var r = clm[bits(dat, pos, clbmsk)];
5274
+ pos += r & 15;
5275
+ var s = r >> 4;
5276
+ if (s < 16) {
5277
+ ldt[i2++] = s;
5278
+ } else {
5279
+ var c = 0, n = 0;
5280
+ if (s == 16)
5281
+ n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i2 - 1];
5282
+ else if (s == 17)
5283
+ n = 3 + bits(dat, pos, 7), pos += 3;
5284
+ else if (s == 18)
5285
+ n = 11 + bits(dat, pos, 127), pos += 7;
5286
+ while (n--)
5287
+ ldt[i2++] = c;
5288
+ }
5289
+ }
5290
+ var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
5291
+ lbt = max(lt);
5292
+ dbt = max(dt);
5293
+ lm = hMap(lt, lbt, 1);
5294
+ dm = hMap(dt, dbt, 1);
5295
+ } else
5296
+ err(1);
5297
+ if (pos > tbts) {
5298
+ if (noSt)
5299
+ err(0);
5300
+ break;
5301
+ }
5302
+ }
5303
+ if (resize)
5304
+ cbuf(bt + 131072);
5305
+ var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
5306
+ var lpos = pos;
5307
+ for (;; lpos = pos) {
5308
+ var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
5309
+ pos += c & 15;
5310
+ if (pos > tbts) {
5311
+ if (noSt)
5312
+ err(0);
5313
+ break;
5314
+ }
5315
+ if (!c)
5316
+ err(2);
5317
+ if (sym < 256)
5318
+ buf[bt++] = sym;
5319
+ else if (sym == 256) {
5320
+ lpos = pos, lm = null;
5321
+ break;
5322
+ } else {
5323
+ var add = sym - 254;
5324
+ if (sym > 264) {
5325
+ var i2 = sym - 257, b = fleb[i2];
5326
+ add = bits(dat, pos, (1 << b) - 1) + fl[i2];
5327
+ pos += b;
5328
+ }
5329
+ var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
5330
+ if (!d)
5331
+ err(3);
5332
+ pos += d & 15;
5333
+ var dt = fd[dsym];
5334
+ if (dsym > 3) {
5335
+ var b = fdeb[dsym];
5336
+ dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
5337
+ }
5338
+ if (pos > tbts) {
5339
+ if (noSt)
5340
+ err(0);
5341
+ break;
5342
+ }
5343
+ if (resize)
5344
+ cbuf(bt + 131072);
5345
+ var end = bt + add;
5346
+ if (bt < dt) {
5347
+ var shift = dl - dt, dend = Math.min(dt, end);
5348
+ if (shift + bt < 0)
5349
+ err(3);
5350
+ for (;bt < dend; ++bt)
5351
+ buf[bt] = dict[shift + bt];
5352
+ }
5353
+ for (;bt < end; ++bt)
5354
+ buf[bt] = buf[bt - dt];
5355
+ }
5356
+ }
5357
+ st.l = lm, st.p = lpos, st.b = bt, st.f = final;
5358
+ if (lm)
5359
+ final = 1, st.m = lbt, st.d = dm, st.n = dbt;
5360
+ } while (!final);
5361
+ return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
5362
+ };
5363
+ var wbits = function(d, p, v) {
5364
+ v <<= p & 7;
5365
+ var o = p / 8 | 0;
5366
+ d[o] |= v;
5367
+ d[o + 1] |= v >> 8;
5368
+ };
5369
+ var wbits16 = function(d, p, v) {
5370
+ v <<= p & 7;
5371
+ var o = p / 8 | 0;
5372
+ d[o] |= v;
5373
+ d[o + 1] |= v >> 8;
5374
+ d[o + 2] |= v >> 16;
5375
+ };
5376
+ var hTree = function(d, mb) {
5377
+ var t = [];
5378
+ for (var i2 = 0;i2 < d.length; ++i2) {
5379
+ if (d[i2])
5380
+ t.push({ s: i2, f: d[i2] });
5381
+ }
5382
+ var s = t.length;
5383
+ var t2 = t.slice();
5384
+ if (!s)
5385
+ return { t: et, l: 0 };
5386
+ if (s == 1) {
5387
+ var v = new u8(t[0].s + 1);
5388
+ v[t[0].s] = 1;
5389
+ return { t: v, l: 1 };
5390
+ }
5391
+ t.sort(function(a, b) {
5392
+ return a.f - b.f;
5393
+ });
5394
+ t.push({ s: -1, f: 25001 });
5395
+ var l = t[0], r = t[1], i0 = 0, i1 = 1, i22 = 2;
5396
+ t[0] = { s: -1, f: l.f + r.f, l, r };
5397
+ while (i1 != s - 1) {
5398
+ l = t[t[i0].f < t[i22].f ? i0++ : i22++];
5399
+ r = t[i0 != i1 && t[i0].f < t[i22].f ? i0++ : i22++];
5400
+ t[i1++] = { s: -1, f: l.f + r.f, l, r };
5401
+ }
5402
+ var maxSym = t2[0].s;
5403
+ for (var i2 = 1;i2 < s; ++i2) {
5404
+ if (t2[i2].s > maxSym)
5405
+ maxSym = t2[i2].s;
5406
+ }
5407
+ var tr = new u16(maxSym + 1);
5408
+ var mbt = ln(t[i1 - 1], tr, 0);
5409
+ if (mbt > mb) {
5410
+ var i2 = 0, dt = 0;
5411
+ var lft = mbt - mb, cst = 1 << lft;
5412
+ t2.sort(function(a, b) {
5413
+ return tr[b.s] - tr[a.s] || a.f - b.f;
5414
+ });
5415
+ for (;i2 < s; ++i2) {
5416
+ var i2_1 = t2[i2].s;
5417
+ if (tr[i2_1] > mb) {
5418
+ dt += cst - (1 << mbt - tr[i2_1]);
5419
+ tr[i2_1] = mb;
5420
+ } else
5421
+ break;
5422
+ }
5423
+ dt >>= lft;
5424
+ while (dt > 0) {
5425
+ var i2_2 = t2[i2].s;
5426
+ if (tr[i2_2] < mb)
5427
+ dt -= 1 << mb - tr[i2_2]++ - 1;
5428
+ else
5429
+ ++i2;
5430
+ }
5431
+ for (;i2 >= 0 && dt; --i2) {
5432
+ var i2_3 = t2[i2].s;
5433
+ if (tr[i2_3] == mb) {
5434
+ --tr[i2_3];
5435
+ ++dt;
5436
+ }
5437
+ }
5438
+ mbt = mb;
5439
+ }
5440
+ return { t: new u8(tr), l: mbt };
5441
+ };
5442
+ var ln = function(n, l, d) {
5443
+ return n.s == -1 ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) : l[n.s] = d;
5444
+ };
5445
+ var lc = function(c) {
5446
+ var s = c.length;
5447
+ while (s && !c[--s])
5448
+ ;
5449
+ var cl = new u16(++s);
5450
+ var cli = 0, cln = c[0], cls = 1;
5451
+ var w = function(v) {
5452
+ cl[cli++] = v;
5453
+ };
5454
+ for (var i2 = 1;i2 <= s; ++i2) {
5455
+ if (c[i2] == cln && i2 != s)
5456
+ ++cls;
5457
+ else {
5458
+ if (!cln && cls > 2) {
5459
+ for (;cls > 138; cls -= 138)
5460
+ w(32754);
5461
+ if (cls > 2) {
5462
+ w(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305);
5463
+ cls = 0;
5464
+ }
5465
+ } else if (cls > 3) {
5466
+ w(cln), --cls;
5467
+ for (;cls > 6; cls -= 6)
5468
+ w(8304);
5469
+ if (cls > 2)
5470
+ w(cls - 3 << 5 | 8208), cls = 0;
5471
+ }
5472
+ while (cls--)
5473
+ w(cln);
5474
+ cls = 1;
5475
+ cln = c[i2];
5476
+ }
5477
+ }
5478
+ return { c: cl.subarray(0, cli), n: s };
5479
+ };
5480
+ var clen = function(cf, cl) {
5481
+ var l = 0;
5482
+ for (var i2 = 0;i2 < cl.length; ++i2)
5483
+ l += cf[i2] * cl[i2];
5484
+ return l;
5485
+ };
5486
+ var wfblk = function(out, pos, dat) {
5487
+ var s = dat.length;
5488
+ var o = shft(pos + 2);
5489
+ out[o] = s & 255;
5490
+ out[o + 1] = s >> 8;
5491
+ out[o + 2] = out[o] ^ 255;
5492
+ out[o + 3] = out[o + 1] ^ 255;
5493
+ for (var i2 = 0;i2 < s; ++i2)
5494
+ out[o + i2 + 4] = dat[i2];
5495
+ return (o + 4 + s) * 8;
5496
+ };
5497
+ var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
5498
+ wbits(out, p++, final);
5499
+ ++lf[256];
5500
+ var _a2 = hTree(lf, 15), dlt = _a2.t, mlb = _a2.l;
5501
+ var _b2 = hTree(df, 15), ddt = _b2.t, mdb = _b2.l;
5502
+ var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
5503
+ var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
5504
+ var lcfreq = new u16(19);
5505
+ for (var i2 = 0;i2 < lclt.length; ++i2)
5506
+ ++lcfreq[lclt[i2] & 31];
5507
+ for (var i2 = 0;i2 < lcdt.length; ++i2)
5508
+ ++lcfreq[lcdt[i2] & 31];
5509
+ var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
5510
+ var nlcc = 19;
5511
+ for (;nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
5512
+ ;
5513
+ var flen = bl + 5 << 3;
5514
+ var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
5515
+ var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
5516
+ if (bs >= 0 && flen <= ftlen && flen <= dtlen)
5517
+ return wfblk(out, p, dat.subarray(bs, bs + bl));
5518
+ var lm, ll, dm, dl;
5519
+ wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
5520
+ if (dtlen < ftlen) {
5521
+ lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
5522
+ var llm = hMap(lct, mlcb, 0);
5523
+ wbits(out, p, nlc - 257);
5524
+ wbits(out, p + 5, ndc - 1);
5525
+ wbits(out, p + 10, nlcc - 4);
5526
+ p += 14;
5527
+ for (var i2 = 0;i2 < nlcc; ++i2)
5528
+ wbits(out, p + 3 * i2, lct[clim[i2]]);
5529
+ p += 3 * nlcc;
5530
+ var lcts = [lclt, lcdt];
5531
+ for (var it = 0;it < 2; ++it) {
5532
+ var clct = lcts[it];
5533
+ for (var i2 = 0;i2 < clct.length; ++i2) {
5534
+ var len = clct[i2] & 31;
5535
+ wbits(out, p, llm[len]), p += lct[len];
5536
+ if (len > 15)
5537
+ wbits(out, p, clct[i2] >> 5 & 127), p += clct[i2] >> 12;
5538
+ }
5539
+ }
5540
+ } else {
5541
+ lm = flm, ll = flt, dm = fdm, dl = fdt;
5542
+ }
5543
+ for (var i2 = 0;i2 < li; ++i2) {
5544
+ var sym = syms[i2];
5545
+ if (sym > 255) {
5546
+ var len = sym >> 18 & 31;
5547
+ wbits16(out, p, lm[len + 257]), p += ll[len + 257];
5548
+ if (len > 7)
5549
+ wbits(out, p, sym >> 23 & 31), p += fleb[len];
5550
+ var dst = sym & 31;
5551
+ wbits16(out, p, dm[dst]), p += dl[dst];
5552
+ if (dst > 3)
5553
+ wbits16(out, p, sym >> 5 & 8191), p += fdeb[dst];
5554
+ } else {
5555
+ wbits16(out, p, lm[sym]), p += ll[sym];
5556
+ }
5557
+ }
5558
+ wbits16(out, p, lm[256]);
5559
+ return p + ll[256];
5560
+ };
5561
+ var deo = /* @__PURE__ */ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
5562
+ var et = /* @__PURE__ */ new u8(0);
5563
+ var dflt = function(dat, lvl, plvl, pre, post, st) {
5564
+ var s = st.z || dat.length;
5565
+ var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);
5566
+ var w = o.subarray(pre, o.length - post);
5567
+ var lst = st.l;
5568
+ var pos = (st.r || 0) & 7;
5569
+ if (lvl) {
5570
+ if (pos)
5571
+ w[0] = st.r >> 3;
5572
+ var opt = deo[lvl - 1];
5573
+ var n = opt >> 13, c = opt & 8191;
5574
+ var msk_1 = (1 << plvl) - 1;
5575
+ var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
5576
+ var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
5577
+ var hsh = function(i3) {
5578
+ return (dat[i3] ^ dat[i3 + 1] << bs1_1 ^ dat[i3 + 2] << bs2_1) & msk_1;
5579
+ };
5580
+ var syms = new i32(25000);
5581
+ var lf = new u16(288), df = new u16(32);
5582
+ var lc_1 = 0, eb = 0, i2 = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
5583
+ for (;i2 + 2 < s; ++i2) {
5584
+ var hv = hsh(i2);
5585
+ var imod = i2 & 32767, pimod = head[hv];
5586
+ prev[imod] = pimod;
5587
+ head[hv] = imod;
5588
+ if (wi <= i2) {
5589
+ var rem = s - i2;
5590
+ if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) {
5591
+ pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i2 - bs, pos);
5592
+ li = lc_1 = eb = 0, bs = i2;
5593
+ for (var j = 0;j < 286; ++j)
5594
+ lf[j] = 0;
5595
+ for (var j = 0;j < 30; ++j)
5596
+ df[j] = 0;
5597
+ }
5598
+ var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;
5599
+ if (rem > 2 && hv == hsh(i2 - dif)) {
5600
+ var maxn = Math.min(n, rem) - 1;
5601
+ var maxd = Math.min(32767, i2);
5602
+ var ml = Math.min(258, rem);
5603
+ while (dif <= maxd && --ch_1 && imod != pimod) {
5604
+ if (dat[i2 + l] == dat[i2 + l - dif]) {
5605
+ var nl = 0;
5606
+ for (;nl < ml && dat[i2 + nl] == dat[i2 + nl - dif]; ++nl)
5607
+ ;
5608
+ if (nl > l) {
5609
+ l = nl, d = dif;
5610
+ if (nl > maxn)
5611
+ break;
5612
+ var mmd = Math.min(dif, nl - 2);
5613
+ var md = 0;
5614
+ for (var j = 0;j < mmd; ++j) {
5615
+ var ti = i2 - dif + j & 32767;
5616
+ var pti = prev[ti];
5617
+ var cd = ti - pti & 32767;
5618
+ if (cd > md)
5619
+ md = cd, pimod = ti;
5620
+ }
5621
+ }
5622
+ }
5623
+ imod = pimod, pimod = prev[imod];
5624
+ dif += imod - pimod & 32767;
5625
+ }
5626
+ }
5627
+ if (d) {
5628
+ syms[li++] = 268435456 | revfl[l] << 18 | revfd[d];
5629
+ var lin = revfl[l] & 31, din = revfd[d] & 31;
5630
+ eb += fleb[lin] + fdeb[din];
5631
+ ++lf[257 + lin];
5632
+ ++df[din];
5633
+ wi = i2 + l;
5634
+ ++lc_1;
5635
+ } else {
5636
+ syms[li++] = dat[i2];
5637
+ ++lf[dat[i2]];
5638
+ }
5639
+ }
5640
+ }
5641
+ for (i2 = Math.max(i2, wi);i2 < s; ++i2) {
5642
+ syms[li++] = dat[i2];
5643
+ ++lf[dat[i2]];
5644
+ }
5645
+ pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i2 - bs, pos);
5646
+ if (!lst) {
5647
+ st.r = pos & 7 | w[pos / 8 | 0] << 3;
5648
+ pos -= 7;
5649
+ st.h = head, st.p = prev, st.i = i2, st.w = wi;
5650
+ }
5651
+ } else {
5652
+ for (var i2 = st.w || 0;i2 < s + lst; i2 += 65535) {
5653
+ var e = i2 + 65535;
5654
+ if (e >= s) {
5655
+ w[pos / 8 | 0] = lst;
5656
+ e = s;
5657
+ }
5658
+ pos = wfblk(w, pos + 1, dat.subarray(i2, e));
5659
+ }
5660
+ st.i = s;
5661
+ }
5662
+ return slc(o, 0, pre + shft(pos) + post);
5663
+ };
5664
+ var crct = /* @__PURE__ */ function() {
5665
+ var t = new Int32Array(256);
5666
+ for (var i2 = 0;i2 < 256; ++i2) {
5667
+ var c = i2, k = 9;
5668
+ while (--k)
5669
+ c = (c & 1 && -306674912) ^ c >>> 1;
5670
+ t[i2] = c;
5671
+ }
5672
+ return t;
5673
+ }();
5674
+ var crc = function() {
5675
+ var c = -1;
5676
+ return {
5677
+ p: function(d) {
5678
+ var cr = c;
5679
+ for (var i2 = 0;i2 < d.length; ++i2)
5680
+ cr = crct[cr & 255 ^ d[i2]] ^ cr >>> 8;
5681
+ c = cr;
5682
+ },
5683
+ d: function() {
5684
+ return ~c;
5685
+ }
5686
+ };
5687
+ };
5688
+ var dopt = function(dat, opt, pre, post, st) {
5689
+ if (!st) {
5690
+ st = { l: 1 };
5691
+ if (opt.dictionary) {
5692
+ var dict = opt.dictionary.subarray(-32768);
5693
+ var newDat = new u8(dict.length + dat.length);
5694
+ newDat.set(dict);
5695
+ newDat.set(dat, dict.length);
5696
+ dat = newDat;
5697
+ st.w = dict.length;
5698
+ }
5699
+ }
5700
+ return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20 : 12 + opt.mem, pre, post, st);
5701
+ };
5702
+ var mrg = function(a, b) {
5703
+ var o = {};
5704
+ for (var k in a)
5705
+ o[k] = a[k];
5706
+ for (var k in b)
5707
+ o[k] = b[k];
5708
+ return o;
5709
+ };
5710
+ var b2 = function(d, b) {
5711
+ return d[b] | d[b + 1] << 8;
5712
+ };
5713
+ var b4 = function(d, b) {
5714
+ return (d[b] | d[b + 1] << 8 | d[b + 2] << 16 | d[b + 3] << 24) >>> 0;
5715
+ };
5716
+ var b8 = function(d, b) {
5717
+ return b4(d, b) + b4(d, b + 4) * 4294967296;
5718
+ };
5719
+ var wbytes = function(d, b, v) {
5720
+ for (;v; ++b)
5721
+ d[b] = v, v >>>= 8;
5722
+ };
5723
+ function deflateSync(data, opts) {
5724
+ return dopt(data, opts || {}, 0, 0);
5725
+ }
5726
+ function inflateSync(data, opts) {
5727
+ return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
5728
+ }
5729
+ var fltn = function(d, p, t, o) {
5730
+ for (var k in d) {
5731
+ var val = d[k], n = p + k, op = o;
5732
+ if (Array.isArray(val))
5733
+ op = mrg(o, val[1]), val = val[0];
5734
+ if (val instanceof u8)
5735
+ t[n] = [val, op];
5736
+ else {
5737
+ t[n += "/"] = [new u8(0), op];
5738
+ fltn(val, n, t, o);
5739
+ }
5740
+ }
5741
+ };
5742
+ var te = typeof TextEncoder != "undefined" && /* @__PURE__ */ new TextEncoder;
5743
+ var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder;
5744
+ var tds = 0;
5745
+ try {
5746
+ td.decode(et, { stream: true });
5747
+ tds = 1;
5748
+ } catch (e) {}
5749
+ var dutf8 = function(d) {
5750
+ for (var r = "", i2 = 0;; ) {
5751
+ var c = d[i2++];
5752
+ var eb = (c > 127) + (c > 223) + (c > 239);
5753
+ if (i2 + eb > d.length)
5754
+ return { s: r, r: slc(d, i2 - 1) };
5755
+ if (!eb)
5756
+ r += String.fromCharCode(c);
5757
+ else if (eb == 3) {
5758
+ c = ((c & 15) << 18 | (d[i2++] & 63) << 12 | (d[i2++] & 63) << 6 | d[i2++] & 63) - 65536, r += String.fromCharCode(55296 | c >> 10, 56320 | c & 1023);
5759
+ } else if (eb & 1)
5760
+ r += String.fromCharCode((c & 31) << 6 | d[i2++] & 63);
5761
+ else
5762
+ r += String.fromCharCode((c & 15) << 12 | (d[i2++] & 63) << 6 | d[i2++] & 63);
5763
+ }
5764
+ };
5765
+ function strToU8(str, latin1) {
5766
+ if (latin1) {
5767
+ var ar_1 = new u8(str.length);
5768
+ for (var i2 = 0;i2 < str.length; ++i2)
5769
+ ar_1[i2] = str.charCodeAt(i2);
5770
+ return ar_1;
5771
+ }
5772
+ if (te)
5773
+ return te.encode(str);
5774
+ var l = str.length;
5775
+ var ar = new u8(str.length + (str.length >> 1));
5776
+ var ai = 0;
5777
+ var w = function(v) {
5778
+ ar[ai++] = v;
5779
+ };
5780
+ for (var i2 = 0;i2 < l; ++i2) {
5781
+ if (ai + 5 > ar.length) {
5782
+ var n = new u8(ai + 8 + (l - i2 << 1));
5783
+ n.set(ar);
5784
+ ar = n;
5785
+ }
5786
+ var c = str.charCodeAt(i2);
5787
+ if (c < 128 || latin1)
5788
+ w(c);
5789
+ else if (c < 2048)
5790
+ w(192 | c >> 6), w(128 | c & 63);
5791
+ else if (c > 55295 && c < 57344)
5792
+ c = 65536 + (c & 1023 << 10) | str.charCodeAt(++i2) & 1023, w(240 | c >> 18), w(128 | c >> 12 & 63), w(128 | c >> 6 & 63), w(128 | c & 63);
5793
+ else
5794
+ w(224 | c >> 12), w(128 | c >> 6 & 63), w(128 | c & 63);
5795
+ }
5796
+ return slc(ar, 0, ai);
5797
+ }
5798
+ function strFromU8(dat, latin1) {
5799
+ if (latin1) {
5800
+ var r = "";
5801
+ for (var i2 = 0;i2 < dat.length; i2 += 16384)
5802
+ r += String.fromCharCode.apply(null, dat.subarray(i2, i2 + 16384));
5803
+ return r;
5804
+ } else if (td) {
5805
+ return td.decode(dat);
5806
+ } else {
5807
+ var _a2 = dutf8(dat), s = _a2.s, r = _a2.r;
5808
+ if (r.length)
5809
+ err(8);
5810
+ return s;
5811
+ }
5812
+ }
5813
+ var slzh = function(d, b) {
5814
+ return b + 30 + b2(d, b + 26) + b2(d, b + 28);
5815
+ };
5816
+ var zh = function(d, b, z) {
5817
+ var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);
5818
+ var _a2 = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a2[0], su = _a2[1], off = _a2[2];
5819
+ return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];
5820
+ };
5821
+ var z64e = function(d, b) {
5822
+ for (;b2(d, b) != 1; b += 4 + b2(d, b + 2))
5823
+ ;
5824
+ return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];
5825
+ };
5826
+ var exfl = function(ex) {
5827
+ var le = 0;
5828
+ if (ex) {
5829
+ for (var k in ex) {
5830
+ var l = ex[k].length;
5831
+ if (l > 65535)
5832
+ err(9);
5833
+ le += l + 4;
5834
+ }
5835
+ }
5836
+ return le;
5837
+ };
5838
+ var wzh = function(d, b, f, fn, u, c, ce, co) {
5839
+ var fl2 = fn.length, ex = f.extra, col = co && co.length;
5840
+ var exl = exfl(ex);
5841
+ wbytes(d, b, ce != null ? 33639248 : 67324752), b += 4;
5842
+ if (ce != null)
5843
+ d[b++] = 20, d[b++] = f.os;
5844
+ d[b] = 20, b += 2;
5845
+ d[b++] = f.flag << 1 | (c < 0 && 8), d[b++] = u && 8;
5846
+ d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
5847
+ var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
5848
+ if (y < 0 || y > 119)
5849
+ err(10);
5850
+ wbytes(d, b, y << 25 | dt.getMonth() + 1 << 21 | dt.getDate() << 16 | dt.getHours() << 11 | dt.getMinutes() << 5 | dt.getSeconds() >> 1), b += 4;
5851
+ if (c != -1) {
5852
+ wbytes(d, b, f.crc);
5853
+ wbytes(d, b + 4, c < 0 ? -c - 2 : c);
5854
+ wbytes(d, b + 8, f.size);
5855
+ }
5856
+ wbytes(d, b + 12, fl2);
5857
+ wbytes(d, b + 14, exl), b += 16;
5858
+ if (ce != null) {
5859
+ wbytes(d, b, col);
5860
+ wbytes(d, b + 6, f.attrs);
5861
+ wbytes(d, b + 10, ce), b += 14;
5862
+ }
5863
+ d.set(fn, b);
5864
+ b += fl2;
5865
+ if (exl) {
5866
+ for (var k in ex) {
5867
+ var exf = ex[k], l = exf.length;
5868
+ wbytes(d, b, +k);
5869
+ wbytes(d, b + 2, l);
5870
+ d.set(exf, b + 4), b += 4 + l;
5871
+ }
5872
+ }
5873
+ if (col)
5874
+ d.set(co, b), b += col;
5875
+ return b;
5876
+ };
5877
+ var wzf = function(o, b, c, d, e) {
5878
+ wbytes(o, b, 101010256);
5879
+ wbytes(o, b + 8, c);
5880
+ wbytes(o, b + 10, c);
5881
+ wbytes(o, b + 12, d);
5882
+ wbytes(o, b + 16, e);
5883
+ };
5884
+ function zipSync(data, opts) {
5885
+ if (!opts)
5886
+ opts = {};
5887
+ var r = {};
5888
+ var files = [];
5889
+ fltn(data, "", r, opts);
5890
+ var o = 0;
5891
+ var tot = 0;
5892
+ for (var fn in r) {
5893
+ var _a2 = r[fn], file = _a2[0], p = _a2[1];
5894
+ var compression = p.level == 0 ? 0 : 8;
5895
+ var f = strToU8(fn), s = f.length;
5896
+ var com = p.comment, m = com && strToU8(com), ms = m && m.length;
5897
+ var exl = exfl(p.extra);
5898
+ if (s > 65535)
5899
+ err(11);
5900
+ var d = compression ? deflateSync(file, p) : file, l = d.length;
5901
+ var c = crc();
5902
+ c.p(file);
5903
+ files.push(mrg(p, {
5904
+ size: file.length,
5905
+ crc: c.d(),
5906
+ c: d,
5907
+ f,
5908
+ m,
5909
+ u: s != fn.length || m && com.length != ms,
5910
+ o,
5911
+ compression
5912
+ }));
5913
+ o += 30 + s + exl + l;
5914
+ tot += 76 + 2 * (s + exl) + (ms || 0) + l;
5915
+ }
5916
+ var out = new u8(tot + 22), oe = o, cdl = tot - o;
5917
+ for (var i2 = 0;i2 < files.length; ++i2) {
5918
+ var f = files[i2];
5919
+ wzh(out, f.o, f, f.f, f.u, f.c.length);
5920
+ var badd = 30 + f.f.length + exfl(f.extra);
5921
+ out.set(f.c, f.o + badd);
5922
+ wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
5923
+ }
5924
+ wzf(out, o, files.length, cdl, oe);
5925
+ return out;
5926
+ }
5927
+ function unzipSync(data, opts) {
5928
+ var files = {};
5929
+ var e = data.length - 22;
5930
+ for (;b4(data, e) != 101010256; --e) {
5931
+ if (!e || data.length - e > 65558)
5932
+ err(13);
5933
+ }
5934
+ var c = b2(data, e + 8);
5935
+ if (!c)
5936
+ return {};
5937
+ var o = b4(data, e + 16);
5938
+ var z = o == 4294967295 || c == 65535;
5939
+ if (z) {
5940
+ var ze = b4(data, e - 12);
5941
+ z = b4(data, ze) == 101075792;
5942
+ if (z) {
5943
+ c = b4(data, ze + 32);
5944
+ o = b4(data, ze + 48);
5945
+ }
5946
+ }
5947
+ var fltr = opts && opts.filter;
5948
+ for (var i2 = 0;i2 < c; ++i2) {
5949
+ var _a2 = zh(data, o, z), c_2 = _a2[0], sc = _a2[1], su = _a2[2], fn = _a2[3], no = _a2[4], off = _a2[5], b = slzh(data, off);
5950
+ o = no;
5951
+ if (!fltr || fltr({
5952
+ name: fn,
5953
+ size: sc,
5954
+ originalSize: su,
5955
+ compression: c_2
5956
+ })) {
5957
+ if (!c_2)
5958
+ files[fn] = slc(data, b, b + sc);
5959
+ else if (c_2 == 8)
5960
+ files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });
5961
+ else
5962
+ err(14, "unknown compression type " + c_2);
5963
+ }
5964
+ }
5965
+ return files;
5966
+ }
5967
+
5968
+ // src/docx-handler.ts
5969
+ function prettyPrintXml(xml) {
5970
+ let formatted = "";
5971
+ let indent = 0;
5972
+ const parts = xml.replace(/>\s*</g, "><").split(/(<[^>]+>)/);
5973
+ for (const part of parts) {
5974
+ if (!part.trim())
5975
+ continue;
5976
+ if (part.startsWith("</")) {
5977
+ indent = Math.max(indent - 1, 0);
5978
+ formatted += " ".repeat(indent) + part + `
5979
+ `;
5980
+ } else if (part.startsWith("<?")) {
5981
+ formatted += part + `
5982
+ `;
5983
+ } else if (part.startsWith("<") && !part.endsWith("/>") && !part.startsWith("<!")) {
5984
+ formatted += " ".repeat(indent) + part + `
5985
+ `;
5986
+ indent++;
5987
+ } else if (part.endsWith("/>")) {
5988
+ formatted += " ".repeat(indent) + part + `
5989
+ `;
5990
+ } else {
5991
+ formatted += " ".repeat(indent) + part + `
5992
+ `;
5993
+ }
5994
+ }
5995
+ return formatted;
5996
+ }
5997
+ function parseMultiFileContent(content) {
5998
+ const result = {};
5999
+ const parts = content.split("=== FILE: ");
6000
+ for (const part of parts.slice(1)) {
6001
+ const endIdx = part.indexOf(" ===");
6002
+ if (endIdx === -1)
6003
+ continue;
6004
+ const filename = part.slice(0, endIdx);
6005
+ const xmlContent = part.slice(endIdx + 4).trim();
6006
+ if (filename && xmlContent)
6007
+ result[filename] = xmlContent;
6008
+ }
6009
+ return result;
6010
+ }
6011
+ function dumpMultiFileContent(filesMap) {
6012
+ const parts = [];
6013
+ for (const [key, content] of Object.entries(filesMap)) {
6014
+ parts.push(`=== FILE: ${key} ===`);
6015
+ parts.push(content.trim());
6016
+ }
6017
+ return parts.join(`
6018
+
6019
+ `);
6020
+ }
6021
+ function cleanHeaderFromXml(xmlContent) {
6022
+ const lines = xmlContent.split(`
6023
+ `);
6024
+ for (let i2 = 0;i2 < lines.length; i2++) {
6025
+ if (lines[i2].trim().startsWith("<?xml")) {
6026
+ return lines.slice(i2).join(`
6027
+ `);
6028
+ }
6029
+ }
6030
+ return xmlContent;
6031
+ }
6032
+ function extractDocxContent(docxPath) {
6033
+ const data = new Uint8Array(fs2.readFileSync(docxPath));
6034
+ const zip = unzipSync(data);
6035
+ const docXml = zip["word/document.xml"];
6036
+ if (!docXml)
6037
+ throw new Error("Invalid DOCX: 'word/document.xml' not found");
6038
+ const xml = new TextDecoder().decode(docXml);
6039
+ return prettyPrintXml(xml);
6040
+ }
6041
+ function saveDocxContent(docxPath, xmlContent) {
6042
+ const data = new Uint8Array(fs2.readFileSync(docxPath));
6043
+ const zip = unzipSync(data);
6044
+ if (!zip["word/document.xml"]) {
6045
+ throw new Error("Invalid DOCX: 'word/document.xml' not found");
6046
+ }
6047
+ const cleanXml = cleanHeaderFromXml(xmlContent);
6048
+ zip["word/document.xml"] = new TextEncoder().encode(cleanXml);
6049
+ const out = zipSync(zip);
6050
+ const tmpPath = docxPath + ".tmp";
6051
+ try {
6052
+ fs2.writeFileSync(tmpPath, out);
6053
+ fs2.renameSync(tmpPath, docxPath);
6054
+ } catch (e) {
6055
+ try {
6056
+ fs2.unlinkSync(tmpPath);
6057
+ } catch {}
6058
+ throw e;
6059
+ }
6060
+ }
6061
+ function extractXlsxContent(xlsxPath) {
6062
+ const data = new Uint8Array(fs2.readFileSync(xlsxPath));
6063
+ const zip = unzipSync(data);
6064
+ const result = {};
6065
+ for (const name of Object.keys(zip)) {
6066
+ if (name.startsWith("xl/worksheets/") && name.endsWith(".xml")) {
6067
+ const key = name.replace("xl/", "");
6068
+ result[key] = prettyPrintXml(new TextDecoder().decode(zip[name]));
6069
+ }
6070
+ }
6071
+ if (zip["xl/sharedStrings.xml"]) {
6072
+ result["sharedStrings.xml"] = prettyPrintXml(new TextDecoder().decode(zip["xl/sharedStrings.xml"]));
6073
+ }
6074
+ if (zip["xl/styles.xml"]) {
6075
+ result["styles.xml"] = prettyPrintXml(new TextDecoder().decode(zip["xl/styles.xml"]));
6076
+ }
6077
+ return dumpMultiFileContent(result);
6078
+ }
6079
+ function saveXlsxContent(xlsxPath, multiFileContent) {
6080
+ const xmlFiles = parseMultiFileContent(multiFileContent);
6081
+ const data = new Uint8Array(fs2.readFileSync(xlsxPath));
6082
+ const zip = unzipSync(data);
6083
+ for (const [key, xmlContent] of Object.entries(xmlFiles)) {
6084
+ const fullPath = `xl/${key}`;
6085
+ const cleanXml = cleanHeaderFromXml(xmlContent);
6086
+ zip[fullPath] = new TextEncoder().encode(cleanXml);
6087
+ }
6088
+ const out = zipSync(zip);
6089
+ const tmpPath = xlsxPath + ".tmp";
6090
+ try {
6091
+ fs2.writeFileSync(tmpPath, out);
6092
+ fs2.renameSync(tmpPath, xlsxPath);
6093
+ } catch (e) {
6094
+ try {
6095
+ fs2.unlinkSync(tmpPath);
6096
+ } catch {}
6097
+ throw e;
6098
+ }
6099
+ }
6100
+
6101
+ // src/files.ts
4677
6102
  var MAX_FILE_SIZE = 1e5;
6103
+ var MAX_OFFICE_FILE_SIZE = 500000;
6104
+ var OFFICE_EXTENSIONS = new Set([".docx", ".xlsx"]);
4678
6105
  async function readFileContent(filePath, rootPath, fallbackRootPaths) {
4679
6106
  try {
4680
6107
  const fullPath = path3.resolve(resolveFilePath(filePath, rootPath, fallbackRootPaths));
4681
- if (!fs2.existsSync(fullPath)) {
6108
+ if (!fs3.existsSync(fullPath)) {
4682
6109
  const roots = rootPath ? [rootPath, ...fallbackRootPaths] : fallbackRootPaths;
4683
6110
  return { success: false, error: `File not found: ${filePath} (roots: ${JSON.stringify(roots)})` };
4684
6111
  }
4685
- const stat = fs2.statSync(fullPath);
6112
+ const stat = fs3.statSync(fullPath);
4686
6113
  if (stat.isDirectory()) {
4687
- const names = fs2.readdirSync(fullPath).sort();
4688
- const content2 = names.map((n) => fs2.statSync(path3.join(fullPath, n)).isDirectory() ? n + "/" : n).join(`
6114
+ const names = fs3.readdirSync(fullPath).sort();
6115
+ const content2 = names.map((n) => fs3.statSync(path3.join(fullPath, n)).isDirectory() ? n + "/" : n).join(`
4689
6116
  `);
4690
6117
  return { success: true, content: content2, fullPath, contentType: "text", isDirectory: true };
4691
6118
  }
4692
- if (stat.size > MAX_FILE_SIZE) {
6119
+ const ext = path3.extname(fullPath).toLowerCase();
6120
+ const isOffice = OFFICE_EXTENSIONS.has(ext);
6121
+ const sizeLimit = isOffice ? MAX_OFFICE_FILE_SIZE : MAX_FILE_SIZE;
6122
+ if (stat.size > sizeLimit) {
4693
6123
  return {
4694
6124
  success: false,
4695
- error: `File too large: ${fullPath} (${stat.size.toLocaleString()} bytes, max ${MAX_FILE_SIZE.toLocaleString()})`
6125
+ error: `File too large: ${fullPath} (${stat.size.toLocaleString()} bytes, max ${sizeLimit.toLocaleString()})`
4696
6126
  };
4697
6127
  }
4698
- const content = fs2.readFileSync(fullPath, "utf-8");
6128
+ if (ext === ".docx") {
6129
+ const content2 = extractDocxContent(fullPath);
6130
+ return { success: true, content: content2, fullPath, contentType: "docx-xml" };
6131
+ }
6132
+ if (ext === ".xlsx") {
6133
+ const content2 = extractXlsxContent(fullPath);
6134
+ return { success: true, content: content2, fullPath, contentType: "xlsx-xml" };
6135
+ }
6136
+ const content = fs3.readFileSync(fullPath, "utf-8");
4699
6137
  return { success: true, content, fullPath, contentType: "text" };
4700
6138
  } catch (e) {
4701
6139
  if (e instanceof WorkspacePathNotFoundError) {
@@ -4708,11 +6146,11 @@ async function readFileContent(filePath, rootPath, fallbackRootPaths) {
4708
6146
  // src/shell.ts
4709
6147
  import { spawn } from "child_process";
4710
6148
  import os3 from "os";
4711
- import fs4 from "fs";
6149
+ import fs5 from "fs";
4712
6150
  import path5 from "path";
4713
6151
 
4714
6152
  // src/tool-registry.ts
4715
- import fs3 from "fs";
6153
+ import fs4 from "fs";
4716
6154
  import os2 from "os";
4717
6155
  import path4 from "path";
4718
6156
  import { execSync, spawnSync } from "child_process";
@@ -4970,7 +6408,7 @@ function whichWithTools(name) {
4970
6408
  for (const ext of exts) {
4971
6409
  const full = path4.join(dir, name + ext);
4972
6410
  try {
4973
- fs3.accessSync(full, fs3.constants.X_OK);
6411
+ fs4.accessSync(full, fs4.constants.X_OK);
4974
6412
  return full;
4975
6413
  } catch {}
4976
6414
  }
@@ -4979,7 +6417,8 @@ function whichWithTools(name) {
4979
6417
  }
4980
6418
  function findReferencedTools(content) {
4981
6419
  return Object.keys(TOOL_REGISTRY).filter((name) => {
4982
- const re = new RegExp("\\b" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
6420
+ const esc = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6421
+ const re = new RegExp(String.raw`(?:^|[|;&\n]|&&|\|\||` + String.raw`\$\(|` + "`" + String.raw`|xargs\s+|sudo\s+|env\s+)\s*` + esc + String.raw`\b`, "m");
4983
6422
  return re.test(content);
4984
6423
  });
4985
6424
  }
@@ -4993,7 +6432,7 @@ async function installBinary(name) {
4993
6432
  return false;
4994
6433
  }
4995
6434
  const dir = binDir();
4996
- fs3.mkdirSync(dir, { recursive: true });
6435
+ fs4.mkdirSync(dir, { recursive: true });
4997
6436
  const [url, isArchive] = await urlFunc();
4998
6437
  const destName = os2.platform() === "win32" ? `${name}.exe` : name;
4999
6438
  const dest = path4.join(dir, destName);
@@ -5003,7 +6442,7 @@ async function installBinary(name) {
5003
6442
  if (!res.ok)
5004
6443
  throw new Error(`Download failed: ${res.status}`);
5005
6444
  const data = Buffer.from(await res.arrayBuffer());
5006
- fs3.writeFileSync(tmpPath, data);
6445
+ fs4.writeFileSync(tmpPath, data);
5007
6446
  if (isArchive) {
5008
6447
  const expectedNames = new Set([name, `${name}.exe`]);
5009
6448
  if (url.endsWith(".tar.gz") || url.endsWith(".tgz")) {
@@ -5013,41 +6452,41 @@ async function installBinary(name) {
5013
6452
  } else {
5014
6453
  throw new Error(`Unsupported archive: ${url}`);
5015
6454
  }
5016
- fs3.unlinkSync(tmpPath);
6455
+ fs4.unlinkSync(tmpPath);
5017
6456
  } else {
5018
- fs3.renameSync(tmpPath, dest);
6457
+ fs4.renameSync(tmpPath, dest);
5019
6458
  }
5020
- fs3.chmodSync(dest, 493);
6459
+ fs4.chmodSync(dest, 493);
5021
6460
  return true;
5022
6461
  }
5023
6462
  async function extractTarBinary(archivePath, dest, expectedNames) {
5024
6463
  const tmpDir = dest + ".extract";
5025
- fs3.mkdirSync(tmpDir, { recursive: true });
6464
+ fs4.mkdirSync(tmpDir, { recursive: true });
5026
6465
  try {
5027
6466
  execSync(`tar xzf "${archivePath}" -C "${tmpDir}"`, { stdio: "pipe" });
5028
6467
  const found = findFileRecursive(tmpDir, expectedNames);
5029
6468
  if (!found)
5030
6469
  throw new Error(`Binary not found in tar archive`);
5031
- fs3.copyFileSync(found, dest);
6470
+ fs4.copyFileSync(found, dest);
5032
6471
  } finally {
5033
- fs3.rmSync(tmpDir, { recursive: true, force: true });
6472
+ fs4.rmSync(tmpDir, { recursive: true, force: true });
5034
6473
  }
5035
6474
  }
5036
6475
  async function extractZipBinary(archivePath, dest, expectedNames) {
5037
6476
  const tmpDir = dest + ".extract";
5038
- fs3.mkdirSync(tmpDir, { recursive: true });
6477
+ fs4.mkdirSync(tmpDir, { recursive: true });
5039
6478
  try {
5040
6479
  execSync(`unzip -o "${archivePath}" -d "${tmpDir}"`, { stdio: "pipe" });
5041
6480
  const found = findFileRecursive(tmpDir, expectedNames);
5042
6481
  if (!found)
5043
6482
  throw new Error(`Binary not found in zip archive`);
5044
- fs3.copyFileSync(found, dest);
6483
+ fs4.copyFileSync(found, dest);
5045
6484
  } finally {
5046
- fs3.rmSync(tmpDir, { recursive: true, force: true });
6485
+ fs4.rmSync(tmpDir, { recursive: true, force: true });
5047
6486
  }
5048
6487
  }
5049
6488
  function findFileRecursive(dir, names) {
5050
- for (const entry of fs3.readdirSync(dir, { withFileTypes: true })) {
6489
+ for (const entry of fs4.readdirSync(dir, { withFileTypes: true })) {
5051
6490
  const full = path4.join(dir, entry.name);
5052
6491
  if (entry.isDirectory()) {
5053
6492
  const found = findFileRecursive(full, names);
@@ -5070,7 +6509,7 @@ function installWithNpm(name, pkg) {
5070
6509
  function installWithPip(name, pkg) {
5071
6510
  const venvDir = path4.join(TOOLS_DIR, "venv");
5072
6511
  const python = os2.platform() === "win32" ? path4.join(venvDir, "Scripts", "python.exe") : path4.join(venvDir, "bin", "python");
5073
- if (!fs3.existsSync(python)) {
6512
+ if (!fs4.existsSync(python)) {
5074
6513
  log2("info", `Creating venv at ${venvDir}`);
5075
6514
  const py = whichWithTools("python3") || whichWithTools("python") || "python3";
5076
6515
  spawnSync(py, ["-m", "venv", venvDir], { stdio: "pipe" });
@@ -5105,7 +6544,7 @@ async function ensureTool(name) {
5105
6544
  return false;
5106
6545
  }
5107
6546
  log2("info", `Installing tool: ${name} (${pkg})`);
5108
- fs3.mkdirSync(TOOLS_DIR, { recursive: true });
6547
+ fs4.mkdirSync(TOOLS_DIR, { recursive: true });
5109
6548
  await installFn(name, pkg);
5110
6549
  log2("info", `Successfully installed ${name}`);
5111
6550
  return true;
@@ -5118,6 +6557,38 @@ async function ensureTool(name) {
5118
6557
  }
5119
6558
 
5120
6559
  // src/shell.ts
6560
+ var IS_WIN = os3.platform() === "win32";
6561
+ function whichSync(name) {
6562
+ const dirs = (process.env.PATH || "").split(path5.delimiter);
6563
+ const exts = IS_WIN ? ["", ".exe", ".cmd", ".bat"] : [""];
6564
+ for (const dir of dirs) {
6565
+ for (const ext of exts) {
6566
+ const full = path5.join(dir, name + ext);
6567
+ try {
6568
+ fs5.accessSync(full, fs5.constants.X_OK);
6569
+ return full;
6570
+ } catch {}
6571
+ }
6572
+ }
6573
+ return null;
6574
+ }
6575
+ function getShellCommand(content) {
6576
+ if (!IS_WIN)
6577
+ return { shell: "/bin/bash", args: ["-c", content], prefix: "" };
6578
+ const gitBash = "C:\\Program Files\\Git\\bin\\bash.exe";
6579
+ if (fs5.existsSync(gitBash))
6580
+ return { shell: gitBash, args: ["-c", content], prefix: "" };
6581
+ const bashPath = whichSync("bash");
6582
+ if (bashPath)
6583
+ return { shell: bashPath, args: ["-c", content], prefix: "" };
6584
+ const psPath = whichSync("powershell") || whichSync("pwsh");
6585
+ if (psPath) {
6586
+ const psPrefix = `[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $OutputEncoding = [System.Text.Encoding]::UTF8;
6587
+ `;
6588
+ return { shell: psPath, args: ["-NoProfile", "-Command", psPrefix + content], prefix: "" };
6589
+ }
6590
+ return { shell: "cmd.exe", args: ["/c", "chcp 65001>nul && " + content], prefix: "" };
6591
+ }
5121
6592
  var ptySpawn = null;
5122
6593
  try {
5123
6594
  ptySpawn = require_lib().spawn;
@@ -5206,12 +6677,12 @@ async function executeBlock(blockId, content, send, todoId, messageId, timeout,
5206
6677
  outputBuffers.set(blockId, buf);
5207
6678
  try {
5208
6679
  const tmpDir = path5.join(os3.tmpdir(), "todoforai");
5209
- if (!fs4.existsSync(tmpDir))
5210
- fs4.mkdirSync(tmpDir, { recursive: true });
6680
+ if (!fs5.existsSync(tmpDir))
6681
+ fs5.mkdirSync(tmpDir, { recursive: true });
5211
6682
  let cwd = tmpDir;
5212
6683
  if (rootPath) {
5213
6684
  const expanded = rootPath.replace(/^~/, process.env.HOME || "~");
5214
- if (fs4.existsSync(expanded) && fs4.statSync(expanded).isDirectory())
6685
+ if (fs5.existsSync(expanded) && fs5.statSync(expanded).isDirectory())
5215
6686
  cwd = expanded;
5216
6687
  }
5217
6688
  const missing = findMissingTools(content);
@@ -5272,8 +6743,9 @@ async function executeBlock(blockId, content, send, todoId, messageId, timeout,
5272
6743
  if (toStream)
5273
6744
  await send(msg.shellBlockResult(todoId, blockId, toStream, messageId));
5274
6745
  };
6746
+ const sc = getShellCommand(content);
5275
6747
  if (ptySpawn) {
5276
- const pty = ptySpawn("/bin/bash", ["-c", content], {
6748
+ const pty = ptySpawn(sc.shell, sc.args, {
5277
6749
  name: "xterm",
5278
6750
  cols: 200,
5279
6751
  rows: 50,
@@ -5286,10 +6758,10 @@ async function executeBlock(blockId, content, send, todoId, messageId, timeout,
5286
6758
  const timer = startTimeout();
5287
6759
  pty.onExit(async ({ exitCode }) => onExit(exitCode ?? -1, timer));
5288
6760
  } else {
5289
- const proc = spawn("/bin/bash", ["-c", content], {
6761
+ const proc = spawn(sc.shell, sc.args, {
5290
6762
  cwd,
5291
6763
  stdio: ["pipe", "pipe", "pipe"],
5292
- detached: true,
6764
+ detached: !IS_WIN,
5293
6765
  env
5294
6766
  });
5295
6767
  const handle = { child: proc, pid: proc.pid };
@@ -5298,8 +6770,8 @@ async function executeBlock(blockId, content, send, todoId, messageId, timeout,
5298
6770
  proc.stderr?.on("data", (d) => onData(d.toString("utf-8")));
5299
6771
  const timer = startTimeout();
5300
6772
  proc.on("close", (code) => onExit(code ?? -1, timer));
5301
- proc.on("error", (err) => {
5302
- send(msg.shellBlockResult(todoId, blockId, `Process error: ${err.message}`, messageId));
6773
+ proc.on("error", (err2) => {
6774
+ send(msg.shellBlockResult(todoId, blockId, `Process error: ${err2.message}`, messageId));
5303
6775
  onExit(-1, timer);
5304
6776
  });
5305
6777
  }
@@ -5349,6 +6821,8 @@ function interruptBlock(blockId) {
5349
6821
  } catch {}
5350
6822
  }, 500);
5351
6823
  }, 1000);
6824
+ } else if (IS_WIN) {
6825
+ handle.child?.kill();
5352
6826
  } else {
5353
6827
  process.kill(-handle.pid, "SIGINT");
5354
6828
  }
@@ -5383,7 +6857,7 @@ function clearBlockOutput(blockId) {
5383
6857
  }
5384
6858
 
5385
6859
  // src/functions.ts
5386
- import fs5 from "fs";
6860
+ import fs6 from "fs";
5387
6861
  import path6 from "path";
5388
6862
  import os4 from "os";
5389
6863
  var FUNCTION_REGISTRY = new Map;
@@ -5405,7 +6879,7 @@ register("get_system_info", async () => {
5405
6879
  system2 = "macOS";
5406
6880
  else if (system2 === "linux") {
5407
6881
  try {
5408
- const release = fs5.readFileSync("/etc/os-release", "utf-8");
6882
+ const release = fs6.readFileSync("/etc/os-release", "utf-8");
5409
6883
  const m = release.match(/PRETTY_NAME="(.+?)"/);
5410
6884
  if (m)
5411
6885
  system2 = m[1];
@@ -5420,6 +6894,113 @@ register("get_system_info", async () => {
5420
6894
  const shell = process.env.SHELL ? path6.basename(process.env.SHELL) : "unknown";
5421
6895
  return { system: system2, shell };
5422
6896
  });
6897
+ register("get_available_tools", async () => {
6898
+ const tools = {};
6899
+ for (const [name, [, type]] of Object.entries(TOOL_REGISTRY)) {
6900
+ tools[name] = type;
6901
+ }
6902
+ return { tools };
6903
+ });
6904
+ register("get_workspace_tree", async (args) => {
6905
+ const { path: p, max_depth = 2 } = args;
6906
+ const root = path6.resolve(p.replace(/^~/, process.env.HOME || "~"));
6907
+ if (!fs6.existsSync(root) || !fs6.statSync(root).isDirectory()) {
6908
+ return { tree: "", is_git: false };
6909
+ }
6910
+ const isGit = fs6.existsSync(path6.join(root, ".git"));
6911
+ if (process.platform !== "win32") {
6912
+ try {
6913
+ const { execSync: execSync2 } = await import("child_process");
6914
+ execSync2("which tree", { encoding: "utf-8", stdio: "pipe" });
6915
+ const cmd = ["tree", "-L", String(max_depth), "--dirsfirst"];
6916
+ if (isGit)
6917
+ cmd.push("--gitignore", "-I", ".git");
6918
+ const result = execSync2(cmd.join(" "), {
6919
+ cwd: root,
6920
+ encoding: "utf-8",
6921
+ timeout: 5000,
6922
+ maxBuffer: 1048576,
6923
+ stdio: ["pipe", "pipe", "pipe"]
6924
+ }).trim();
6925
+ if (result)
6926
+ return { tree: result, is_git: isGit };
6927
+ } catch {}
6928
+ }
6929
+ const ignore = (await Promise.resolve().then(() => __toESM(require_ignore(), 1))).default;
6930
+ const ig = ignore();
6931
+ if (isGit) {
6932
+ let scanGitignores = function(dir) {
6933
+ const giPath = path6.join(dir, ".gitignore");
6934
+ if (fs6.existsSync(giPath)) {
6935
+ try {
6936
+ const relDir = path6.relative(root, dir).replace(/\\/g, "/");
6937
+ const prefix = relDir === "" || relDir === "." ? "" : relDir + "/";
6938
+ for (let line of fs6.readFileSync(giPath, "utf-8").split(`
6939
+ `)) {
6940
+ line = line.trim();
6941
+ if (!line || line.startsWith("#"))
6942
+ continue;
6943
+ if (prefix) {
6944
+ ig.add(line.startsWith("!") ? "!" + prefix + line.slice(1) : prefix + line);
6945
+ } else {
6946
+ ig.add(line);
6947
+ }
6948
+ }
6949
+ } catch {}
6950
+ }
6951
+ try {
6952
+ for (const e of fs6.readdirSync(dir, { withFileTypes: true })) {
6953
+ if (e.isDirectory() && e.name !== ".git")
6954
+ scanGitignores(path6.join(dir, e.name));
6955
+ }
6956
+ } catch {}
6957
+ };
6958
+ scanGitignores(root);
6959
+ }
6960
+ const lines = [path6.basename(root) + "/"];
6961
+ function walk(dirPath, prefix, depth) {
6962
+ if (depth > max_depth)
6963
+ return;
6964
+ let entries;
6965
+ try {
6966
+ entries = fs6.readdirSync(dirPath, { withFileTypes: true });
6967
+ } catch {
6968
+ return;
6969
+ }
6970
+ const visible = entries.filter((e) => {
6971
+ if (e.name === ".git")
6972
+ return false;
6973
+ if (isGit) {
6974
+ let rel = path6.relative(root, path6.join(dirPath, e.name)).replace(/\\/g, "/");
6975
+ if (e.isDirectory())
6976
+ rel += "/";
6977
+ if (ig.ignores(rel))
6978
+ return false;
6979
+ }
6980
+ return true;
6981
+ }).sort((a, b) => {
6982
+ const aDir = a.isDirectory() ? 0 : 1;
6983
+ const bDir = b.isDirectory() ? 0 : 1;
6984
+ if (aDir !== bDir)
6985
+ return aDir - bDir;
6986
+ return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
6987
+ });
6988
+ for (let i2 = 0;i2 < visible.length; i2++) {
6989
+ const entry = visible[i2];
6990
+ const isLast = i2 === visible.length - 1;
6991
+ const connector = isLast ? "└── " : "├── ";
6992
+ const suffix = entry.isDirectory() ? "/" : "";
6993
+ lines.push(`${prefix}${connector}${entry.name}${suffix}`);
6994
+ if (entry.isDirectory()) {
6995
+ const extension = isLast ? " " : "│ ";
6996
+ walk(path6.join(dirPath, entry.name), prefix + extension, depth + 1);
6997
+ }
6998
+ }
6999
+ }
7000
+ walk(root, "", 1);
7001
+ return { tree: lines.join(`
7002
+ `), is_git: isGit };
7003
+ });
5423
7004
  register("get_os_aware_default_path", async () => {
5424
7005
  let p = getPlatformDefaultDirectory();
5425
7006
  if (!p.endsWith(path6.sep))
@@ -5434,8 +7015,8 @@ register("create_directory", async (args) => {
5434
7015
  let target = path6.resolve(name.replace(/^~/, process.env.HOME || "~"));
5435
7016
  if (!path6.isAbsolute(name))
5436
7017
  target = path6.join(baseDir, name.trim());
5437
- const existed = fs5.existsSync(target);
5438
- fs5.mkdirSync(target, { recursive: true });
7018
+ const existed = fs6.existsSync(target);
7019
+ fs6.mkdirSync(target, { recursive: true });
5439
7020
  let full = target;
5440
7021
  if (!full.endsWith(path6.sep))
5441
7022
  full += path6.sep;
@@ -5455,22 +7036,28 @@ register("execute_shell_command", async (args, client) => {
5455
7036
  });
5456
7037
  return { cmd, result };
5457
7038
  }
5458
- const send = (m) => client.sendResponse(m);
5459
- await send(msg.shellBlockStart(todoId, blockId, "execute", messageId));
5460
- await executeBlock(blockId, cmd, send, todoId, messageId, timeout, root_path, false, "internal");
5461
- if (pendingToolApprovals.has(blockId)) {
5462
- return { __awaiting_approval__: true };
5463
- }
5464
- await waitForCompletion(blockId, (timeout + 5) * 1000);
5465
- const output = getBlockOutput(blockId);
5466
- clearBlockOutput(blockId);
5467
- return { cmd, result: output };
7039
+ try {
7040
+ const send = (m) => client.sendResponse(m);
7041
+ await send(msg.shellBlockStart(todoId, blockId, "execute", messageId));
7042
+ await executeBlock(blockId, cmd, send, todoId, messageId, timeout, root_path, false, "internal");
7043
+ if (pendingToolApprovals.has(blockId)) {
7044
+ return { __awaiting_approval__: true };
7045
+ }
7046
+ await waitForCompletion(blockId, (timeout + 5) * 1000);
7047
+ const output = getBlockOutput(blockId);
7048
+ clearBlockOutput(blockId);
7049
+ return { cmd, result: output };
7050
+ } catch (e) {
7051
+ throw e;
7052
+ } finally {
7053
+ clearBlockOutput(blockId);
7054
+ }
5468
7055
  });
5469
7056
  register("read_file", async (args) => {
5470
7057
  const { path: p, rootPath = "", fallbackRootPaths = [] } = args;
5471
7058
  const result = await readFileContent(p, rootPath, fallbackRootPaths);
5472
7059
  if (!result.success)
5473
- throw new Error(result.error);
7060
+ throw new Error(result.error || "Unknown read error");
5474
7061
  const { success, ...rest } = result;
5475
7062
  return rest;
5476
7063
  });
@@ -5479,23 +7066,23 @@ register("create_file", async (args) => {
5479
7066
  const fullPath = resolveFilePath(p, rootPath, fallbackRootPaths);
5480
7067
  const dir = path6.dirname(fullPath);
5481
7068
  if (dir)
5482
- fs5.mkdirSync(dir, { recursive: true });
5483
- fs5.writeFileSync(fullPath, content, "utf-8");
7069
+ fs6.mkdirSync(dir, { recursive: true });
7070
+ fs6.writeFileSync(fullPath, content, "utf-8");
5484
7071
  return { path: fullPath, bytes: Buffer.byteLength(content, "utf-8") };
5485
7072
  });
5486
7073
  register("read_file_base64", async (args) => {
5487
7074
  const { path: p, rootPath = "", fallbackRootPaths = [] } = args;
5488
7075
  const fullPath = resolveFilePath(p, rootPath, fallbackRootPaths);
5489
- if (!fs5.existsSync(fullPath))
7076
+ if (!fs6.existsSync(fullPath))
5490
7077
  throw new Error(`File not found: ${fullPath}`);
5491
- const stat = fs5.statSync(fullPath);
7078
+ const stat = fs6.statSync(fullPath);
5492
7079
  if (stat.size > 50000000)
5493
7080
  throw new Error(`File too large: ${stat.size.toLocaleString()} bytes (max 50MB)`);
5494
- const data = fs5.readFileSync(fullPath);
7081
+ const data = fs6.readFileSync(fullPath);
5495
7082
  return { path: fullPath, base64: data.toString("base64"), bytes: data.length };
5496
7083
  });
5497
7084
  register("search_files", async (args) => {
5498
- const { pattern, path: p = ".", root_path = "", max_results = 100, glob: globPattern = "", ignore_case = true } = args;
7085
+ const { pattern, path: p = ".", root_path = "", head = 100, max_count = 5, glob: globPattern = "", ignore_case = true } = args;
5499
7086
  const { execSync: execWhich } = await import("child_process");
5500
7087
  const which = (bin) => {
5501
7088
  try {
@@ -5515,30 +7102,39 @@ register("search_files", async (args) => {
5515
7102
  if (!path6.isAbsolute(searchPath) && root_path)
5516
7103
  searchPath = path6.join(root_path, searchPath);
5517
7104
  searchPath = path6.resolve(searchPath);
5518
- if (!fs5.existsSync(searchPath))
7105
+ if (!fs6.existsSync(searchPath))
5519
7106
  throw new Error(`Search path does not exist: ${searchPath}`);
5520
- const cmd = [rgPath, "--no-heading", "--line-number", "--color=never", `--max-count=${max_results}`];
7107
+ const cmd = [rgPath, "--no-heading", "--line-number", "--color=never"];
5521
7108
  if (ignore_case)
5522
7109
  cmd.push("--ignore-case");
7110
+ if (max_count > 0)
7111
+ cmd.push(`--max-count=${max_count}`);
5523
7112
  if (globPattern)
5524
7113
  cmd.push("--glob", globPattern);
5525
7114
  cmd.push(pattern, searchPath);
5526
7115
  const { spawn: spawnChild } = await import("child_process");
5527
7116
  const { stdout, stderr, code } = await new Promise((resolve) => {
5528
7117
  const child = spawnChild(cmd[0], cmd.slice(1));
5529
- let out = "", err = "";
7118
+ let out = "", err2 = "";
5530
7119
  child.stdout?.on("data", (d) => {
5531
7120
  out += d.toString();
5532
7121
  });
5533
7122
  child.stderr?.on("data", (d) => {
5534
- err += d.toString();
7123
+ err2 += d.toString();
5535
7124
  });
5536
- child.on("close", (exitCode) => resolve({ stdout: out, stderr: err, code: exitCode ?? 1 }));
7125
+ child.on("close", (exitCode) => resolve({ stdout: out, stderr: err2, code: exitCode ?? 1 }));
5537
7126
  });
5538
7127
  if (code === 0) {
5539
7128
  let output = stdout;
7129
+ const lines = output.split(`
7130
+ `).filter((l) => l.trim());
7131
+ if (lines.length > head) {
7132
+ output = lines.slice(0, head).join(`
7133
+ `) + `
7134
+ ... (${lines.length - head} more matches truncated)`;
7135
+ }
5540
7136
  if (root_path && output) {
5541
- const lines = output.split(`
7137
+ const lines2 = output.split(`
5542
7138
  `).map((line) => {
5543
7139
  if (line.includes(":")) {
5544
7140
  const colonIdx = line.indexOf(":");
@@ -5559,7 +7155,7 @@ register("search_files", async (args) => {
5559
7155
  }
5560
7156
  return line;
5561
7157
  });
5562
- output = lines.join(`
7158
+ output = lines2.join(`
5563
7159
  `);
5564
7160
  }
5565
7161
  if (output.length > 1e5)
@@ -5588,20 +7184,30 @@ register("download_attachment", async (args, client) => {
5588
7184
  if (!path6.isAbsolute(target))
5589
7185
  target = path6.join(base, target);
5590
7186
  target = path6.resolve(target);
5591
- fs5.mkdirSync(path6.dirname(target), { recursive: true });
5592
- const data = Buffer.from(await res.arrayBuffer());
5593
- fs5.writeFileSync(target, data);
5594
- return { path: target, bytes: data.length };
7187
+ fs6.mkdirSync(path6.dirname(target), { recursive: true });
7188
+ try {
7189
+ const data = Buffer.from(await res.arrayBuffer());
7190
+ fs6.writeFileSync(target, data);
7191
+ return { path: target, bytes: data.length };
7192
+ } catch (e) {
7193
+ throw new Error(`Download failed: ${e.message}`);
7194
+ }
5595
7195
  });
5596
7196
  register("download_chat", async (args, client) => {
5597
7197
  if (!client)
5598
7198
  throw new Error("Client instance required");
5599
- const res = await fetch(`${client.apiUrl.replace(/\/+$/, "")}/api/v1/todos/${args.todoId}`, {
5600
- headers: { "x-api-key": client.apiKey }
5601
- });
5602
- if (!res.ok)
5603
- throw new Error(`Backend responded with ${res.status}`);
5604
- return { todo: await res.json() };
7199
+ try {
7200
+ const res = await fetch(`${client.apiUrl.replace(/\/+$/, "")}/api/v1/todos/${args.todoId}`, {
7201
+ headers: { "x-api-key": client.apiKey }
7202
+ });
7203
+ if (!res.ok)
7204
+ throw new Error(`Backend responded with ${res.status}: ${await res.text()}`);
7205
+ return { todo: await res.json() };
7206
+ } catch (e) {
7207
+ if (e instanceof Error)
7208
+ throw e;
7209
+ throw new Error(`Download chat failed: ${e.message}`);
7210
+ }
5605
7211
  });
5606
7212
  register("register_attachment", async (args, client) => {
5607
7213
  if (!client)
@@ -5612,10 +7218,10 @@ register("register_attachment", async (args, client) => {
5612
7218
  if (!path6.isAbsolute(target))
5613
7219
  target = path6.join(base, target);
5614
7220
  target = path6.resolve(target);
5615
- if (!fs5.existsSync(target))
7221
+ if (!fs6.existsSync(target))
5616
7222
  throw new Error(`File not found: ${target}`);
5617
7223
  const form = new FormData;
5618
- form.append("file", new Blob([fs5.readFileSync(target)]), path6.basename(target));
7224
+ form.append("file", new Blob([fs6.readFileSync(target)]), path6.basename(target));
5619
7225
  if (userId)
5620
7226
  form.append("userId", userId);
5621
7227
  if (agentSettingsId)
@@ -5629,7 +7235,7 @@ register("register_attachment", async (args, client) => {
5629
7235
  body: form
5630
7236
  });
5631
7237
  if (!res.ok)
5632
- throw new Error(`Backend responded with ${res.status}`);
7238
+ throw new Error(`Backend responded with ${res.status}: ${await res.text()}`);
5633
7239
  const payload = await res.json().catch(() => ({}));
5634
7240
  return { attachmentId: payload.attachmentId, response: payload };
5635
7241
  });
@@ -5656,10 +7262,21 @@ async function handleBlockSave(payload, send) {
5656
7262
  const { blockId, todoId, filepath, rootPath, fallbackRootPaths = [], content, requestId } = payload;
5657
7263
  try {
5658
7264
  const resolved = resolveFilePath(filepath, rootPath, fallbackRootPaths);
5659
- const dir = path7.dirname(resolved);
5660
- if (dir)
5661
- fs6.mkdirSync(dir, { recursive: true });
5662
- fs6.writeFileSync(resolved, content, "utf-8");
7265
+ const ext = path7.extname(resolved).toLowerCase();
7266
+ if (ext === ".docx" || ext === ".xlsx") {
7267
+ if (!fs7.existsSync(resolved)) {
7268
+ throw new Error(`Cannot create new ${ext} file from XML — file must already exist: ${filepath}`);
7269
+ }
7270
+ if (ext === ".docx")
7271
+ saveDocxContent(resolved, content);
7272
+ else
7273
+ saveXlsxContent(resolved, content);
7274
+ } else {
7275
+ const dir = path7.dirname(resolved);
7276
+ if (dir)
7277
+ fs7.mkdirSync(dir, { recursive: true });
7278
+ fs7.writeFileSync(resolved, content, "utf-8");
7279
+ }
5663
7280
  await send(msg.blockSaveResult(blockId, todoId, "SUCCESS", requestId));
5664
7281
  } catch (e) {
5665
7282
  await send(msg.blockSaveResult(blockId, todoId, `ERROR: ${e.message}`, requestId));
@@ -5669,22 +7286,22 @@ async function handleGetFolders(payload, send) {
5669
7286
  const { requestId, edgeId } = payload;
5670
7287
  const rawPath = getPathOrDefault(payload.path);
5671
7288
  try {
7289
+ const expandedPath = path7.resolve(rawPath.replace(/^~/, process.env.HOME || "~"));
5672
7290
  let targetPath;
5673
- if (rawPath.endsWith(path7.sep)) {
5674
- targetPath = rawPath.replace(/^~/, process.env.HOME || "~");
7291
+ if (fs7.existsSync(expandedPath) && fs7.statSync(expandedPath).isDirectory()) {
7292
+ targetPath = expandedPath;
5675
7293
  } else {
5676
- targetPath = path7.dirname(rawPath.replace(/^~/, process.env.HOME || "~"));
7294
+ targetPath = path7.dirname(expandedPath);
5677
7295
  }
5678
- targetPath = path7.resolve(targetPath);
5679
- if (!fs6.existsSync(targetPath) || !fs6.statSync(targetPath).isDirectory()) {
7296
+ if (!fs7.existsSync(targetPath) || !fs7.statSync(targetPath).isDirectory()) {
5680
7297
  throw new Error(`No existing ancestor for path: ${rawPath}`);
5681
7298
  }
5682
7299
  const folders = [];
5683
7300
  const files = [];
5684
- for (const item of fs6.readdirSync(targetPath)) {
7301
+ for (const item of fs7.readdirSync(targetPath)) {
5685
7302
  const full = path7.join(targetPath, item);
5686
7303
  try {
5687
- if (fs6.statSync(full).isDirectory())
7304
+ if (fs7.statSync(full).isDirectory())
5688
7305
  folders.push(full);
5689
7306
  else
5690
7307
  files.push(full);
@@ -5697,13 +7314,53 @@ async function handleGetFolders(payload, send) {
5697
7314
  await send(msg.getFoldersResponse(requestId, edgeId, [], [], e.message));
5698
7315
  }
5699
7316
  }
7317
+ async function handleCreateFolder(payload, send) {
7318
+ const { requestId, edgeId, path: folderPath } = payload;
7319
+ try {
7320
+ await mkdir(folderPath, { recursive: true });
7321
+ await send(msg.createFolderResponse(requestId, edgeId, true));
7322
+ } catch (e) {
7323
+ await send(msg.createFolderResponse(requestId, edgeId, false, e.message));
7324
+ }
7325
+ }
7326
+ async function handleDeletePath(payload, send) {
7327
+ const { requestId, edgeId, path: targetPath } = payload;
7328
+ try {
7329
+ await rm(targetPath, { recursive: true });
7330
+ await send(msg.deletePathResponse(requestId, edgeId, true));
7331
+ } catch (e) {
7332
+ await send(msg.deletePathResponse(requestId, edgeId, false, e.message));
7333
+ }
7334
+ }
7335
+ async function handleWriteFile(payload, send, pendingBinaries) {
7336
+ const { requestId, edgeId, path: dirPath, fileName, binaryId, dataBase64 } = payload;
7337
+ try {
7338
+ const filePath = path7.join(dirPath, fileName);
7339
+ const dir = path7.dirname(filePath);
7340
+ if (dir)
7341
+ fs7.mkdirSync(dir, { recursive: true });
7342
+ let buffer;
7343
+ if (binaryId && pendingBinaries?.has(binaryId)) {
7344
+ buffer = pendingBinaries.get(binaryId);
7345
+ pendingBinaries.delete(binaryId);
7346
+ } else if (dataBase64) {
7347
+ buffer = Buffer.from(dataBase64, "base64");
7348
+ } else {
7349
+ throw new Error("No file data provided (neither binaryId nor dataBase64)");
7350
+ }
7351
+ await writeFile(filePath, buffer);
7352
+ await send(msg.writeFileResponse(requestId, edgeId, true));
7353
+ } catch (e) {
7354
+ await send(msg.writeFileResponse(requestId, edgeId, false, e.message));
7355
+ }
7356
+ }
5700
7357
  var FORBIDDEN_PATHS = new Set(["/", "/tmp", "C:\\", "C:/"]);
5701
7358
  async function handleCd(payload, send, edgeConfig, onConfigChange) {
5702
7359
  const { requestId, edgeId } = payload;
5703
7360
  const rawPath = getPathOrDefault(payload.path);
5704
7361
  try {
5705
7362
  const resolved = path7.resolve(rawPath.replace(/^~/, process.env.HOME || "~"));
5706
- if (!fs6.existsSync(resolved) || !fs6.statSync(resolved).isDirectory()) {
7363
+ if (!fs7.existsSync(resolved) || !fs7.statSync(resolved).isDirectory()) {
5707
7364
  throw new Error(`Path does not exist or is not a directory: ${rawPath}`);
5708
7365
  }
5709
7366
  const normalized = resolved.replace(/\/+$/, "");
@@ -5741,7 +7398,7 @@ async function handleFunctionCall(payload, send, client) {
5741
7398
  blockInfo = { todoId: args.todoId, messageId: args.messageId, blockId: args.blockId };
5742
7399
  }
5743
7400
  const makeSuccess = (result) => isAgent ? msg.functionCallResult(requestId, edgeId, true, result, undefined, agentId) : msg.functionCallResultFront(requestId, edgeId, true, result, undefined, blockInfo);
5744
- const makeError = (err) => isAgent ? msg.functionCallResult(requestId, edgeId, false, undefined, err, agentId) : msg.functionCallResultFront(requestId, edgeId, false, undefined, err, blockInfo);
7401
+ const makeError = (err2) => isAgent ? msg.functionCallResult(requestId, edgeId, false, undefined, err2, agentId) : msg.functionCallResultFront(requestId, edgeId, false, undefined, err2, blockInfo);
5745
7402
  try {
5746
7403
  const fn = FUNCTION_REGISTRY.get(functionName);
5747
7404
  if (!fn) {
@@ -5761,11 +7418,11 @@ async function handleFunctionCall(payload, send, client) {
5761
7418
  // src/edge.ts
5762
7419
  function generateFingerprint() {
5763
7420
  const os5 = __require("os");
5764
- const fs7 = __require("fs");
7421
+ const fs8 = __require("fs");
5765
7422
  const identifiers = {};
5766
7423
  if (process.platform === "linux") {
5767
7424
  try {
5768
- const mid = fs7.readFileSync("/etc/machine-id", "utf-8").trim();
7425
+ const mid = fs8.readFileSync("/etc/machine-id", "utf-8").trim();
5769
7426
  if (mid)
5770
7427
  identifiers.machine_id = mid;
5771
7428
  } catch {}
@@ -5860,6 +7517,10 @@ class TODOforAIEdge {
5860
7517
  const frontendUrl = this.api.apiUrl.replace("://api.", "://");
5861
7518
  console.log(`\x1B[33mPlease provide your API key\x1B[0m`);
5862
7519
  console.log(`\x1B[36mGet one at: ${frontendUrl}/apikey\x1B[0m`);
7520
+ if (!process.stdin.isTTY) {
7521
+ console.error("No API key provided and stdin is not interactive. Set TODOFORAI_API_KEY or pass --api-key.");
7522
+ process.exit(1);
7523
+ }
5863
7524
  const rl = __require("readline").createInterface({ input: process.stdin, output: process.stdout });
5864
7525
  return new Promise((resolve) => {
5865
7526
  const ask = () => {
@@ -5923,6 +7584,17 @@ class TODOforAIEdge {
5923
7584
  }
5924
7585
  }
5925
7586
  }
7587
+ pendingBinaries = new Map;
7588
+ storeBinaryFrame(frame) {
7589
+ if (frame.length < 36)
7590
+ return;
7591
+ let id = "";
7592
+ for (let i2 = 0;i2 < 36; i2++)
7593
+ id += String.fromCharCode(frame[i2]);
7594
+ const data = frame.slice(36);
7595
+ this.pendingBinaries.set(id, data);
7596
+ setTimeout(() => this.pendingBinaries.delete(id), 60000);
7597
+ }
5926
7598
  async handleMessage(raw) {
5927
7599
  let data;
5928
7600
  try {
@@ -5986,6 +7658,15 @@ class TODOforAIEdge {
5986
7658
  case FE.GET_FOLDERS:
5987
7659
  run(() => handleGetFolders(payload, send));
5988
7660
  break;
7661
+ case FE.EDGE_CREATE_FOLDER:
7662
+ run(() => handleCreateFolder(payload, send));
7663
+ break;
7664
+ case FE.EDGE_DELETE_PATH:
7665
+ run(() => handleDeletePath(payload, send));
7666
+ break;
7667
+ case FE.EDGE_WRITE_FILE:
7668
+ run(() => handleWriteFile(payload, send, this.pendingBinaries));
7669
+ break;
5989
7670
  case AE.FUNCTION_CALL_REQUEST_AGENT:
5990
7671
  case FE.FUNCTION_CALL_REQUEST_FRONT:
5991
7672
  run(() => handleFunctionCall(payload, send, this));
@@ -6008,7 +7689,12 @@ class TODOforAIEdge {
6008
7689
  this.connected = true;
6009
7690
  console.log("[info] WebSocket connected");
6010
7691
  });
6011
- this.ws.on("message", (data) => {
7692
+ this.ws.on("message", (data, isBinary) => {
7693
+ if (isBinary) {
7694
+ const frame = data instanceof Buffer ? new Uint8Array(data) : new Uint8Array(data);
7695
+ this.storeBinaryFrame(frame);
7696
+ return;
7697
+ }
6012
7698
  this.handleMessage(data.toString()).catch((e) => {
6013
7699
  if (e instanceof AuthenticationError || e instanceof ServerError) {
6014
7700
  this.ws?.close();
@@ -6023,10 +7709,10 @@ class TODOforAIEdge {
6023
7709
  this.ws = null;
6024
7710
  resolve();
6025
7711
  });
6026
- this.ws.on("error", (err) => {
7712
+ this.ws.on("error", (err2) => {
6027
7713
  this.connected = false;
6028
7714
  this.ws = null;
6029
- reject(err);
7715
+ reject(err2);
6030
7716
  });
6031
7717
  });
6032
7718
  }