duclaw-cli 1.8.14 → 1.8.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bundle.js CHANGED
@@ -115,7 +115,7 @@ var require_package = __commonJS({
115
115
  var require_main = __commonJS({
116
116
  "node_modules/.pnpm/dotenv@17.3.1/node_modules/dotenv/lib/main.js"(exports2, module2) {
117
117
  var fs3 = require("fs");
118
- var path18 = require("path");
118
+ var path19 = require("path");
119
119
  var os = require("os");
120
120
  var crypto2 = require("crypto");
121
121
  var packageJson = require_package();
@@ -261,7 +261,7 @@ var require_main = __commonJS({
261
261
  possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
262
262
  }
263
263
  } else {
264
- possibleVaultPath = path18.resolve(process.cwd(), ".env.vault");
264
+ possibleVaultPath = path19.resolve(process.cwd(), ".env.vault");
265
265
  }
266
266
  if (fs3.existsSync(possibleVaultPath)) {
267
267
  return possibleVaultPath;
@@ -269,7 +269,7 @@ var require_main = __commonJS({
269
269
  return null;
270
270
  }
271
271
  function _resolveHome(envPath) {
272
- return envPath[0] === "~" ? path18.join(os.homedir(), envPath.slice(1)) : envPath;
272
+ return envPath[0] === "~" ? path19.join(os.homedir(), envPath.slice(1)) : envPath;
273
273
  }
274
274
  function _configVault(options) {
275
275
  const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || options && options.debug);
@@ -286,7 +286,7 @@ var require_main = __commonJS({
286
286
  return { parsed };
287
287
  }
288
288
  function configDotenv(options) {
289
- const dotenvPath = path18.resolve(process.cwd(), ".env");
289
+ const dotenvPath = path19.resolve(process.cwd(), ".env");
290
290
  let encoding = "utf8";
291
291
  let processEnv = process.env;
292
292
  if (options && options.processEnv != null) {
@@ -314,13 +314,13 @@ var require_main = __commonJS({
314
314
  }
315
315
  let lastError;
316
316
  const parsedAll = {};
317
- for (const path19 of optionPaths) {
317
+ for (const path20 of optionPaths) {
318
318
  try {
319
- const parsed = DotenvModule.parse(fs3.readFileSync(path19, { encoding }));
319
+ const parsed = DotenvModule.parse(fs3.readFileSync(path20, { encoding }));
320
320
  DotenvModule.populate(parsedAll, parsed, options);
321
321
  } catch (e) {
322
322
  if (debug) {
323
- _debug(`Failed to load ${path19} ${e.message}`);
323
+ _debug(`Failed to load ${path20} ${e.message}`);
324
324
  }
325
325
  lastError = e;
326
326
  }
@@ -333,7 +333,7 @@ var require_main = __commonJS({
333
333
  const shortPaths = [];
334
334
  for (const filePath of optionPaths) {
335
335
  try {
336
- const relative4 = path18.relative(process.cwd(), filePath);
336
+ const relative4 = path19.relative(process.cwd(), filePath);
337
337
  shortPaths.push(relative4);
338
338
  } catch (e) {
339
339
  if (debug) {
@@ -8237,8 +8237,8 @@ var require_MODULE_LOAD = __commonJS({
8237
8237
  * @param moduleArguments - Optional arguments to pass to the module
8238
8238
  * @see https://redis.io/commands/module-load/
8239
8239
  */
8240
- parseCommand(parser, path18, moduleArguments) {
8241
- parser.push("MODULE", "LOAD", path18);
8240
+ parseCommand(parser, path19, moduleArguments) {
8241
+ parser.push("MODULE", "LOAD", path19);
8242
8242
  if (moduleArguments) {
8243
8243
  parser.push(...moduleArguments);
8244
8244
  }
@@ -23539,10 +23539,10 @@ var require_ARRAPPEND = __commonJS({
23539
23539
  * @param json - The first value to append
23540
23540
  * @param jsons - Additional values to append
23541
23541
  */
23542
- parseCommand(parser, key, path18, json, ...jsons) {
23542
+ parseCommand(parser, key, path19, json, ...jsons) {
23543
23543
  parser.push("JSON.ARRAPPEND");
23544
23544
  parser.pushKey(key);
23545
- parser.push(path18, (0, generic_transformers_1.transformRedisJsonArgument)(json));
23545
+ parser.push(path19, (0, generic_transformers_1.transformRedisJsonArgument)(json));
23546
23546
  for (let i = 0; i < jsons.length; i++) {
23547
23547
  parser.push((0, generic_transformers_1.transformRedisJsonArgument)(jsons[i]));
23548
23548
  }
@@ -23572,10 +23572,10 @@ var require_ARRINDEX = __commonJS({
23572
23572
  * @param options.range.start - Starting index for the search
23573
23573
  * @param options.range.stop - Optional ending index for the search
23574
23574
  */
23575
- parseCommand(parser, key, path18, json, options) {
23575
+ parseCommand(parser, key, path19, json, options) {
23576
23576
  parser.push("JSON.ARRINDEX");
23577
23577
  parser.pushKey(key);
23578
- parser.push(path18, (0, generic_transformers_1.transformRedisJsonArgument)(json));
23578
+ parser.push(path19, (0, generic_transformers_1.transformRedisJsonArgument)(json));
23579
23579
  if (options?.range) {
23580
23580
  parser.push(options.range.start.toString());
23581
23581
  if (options.range.stop !== void 0) {
@@ -23607,10 +23607,10 @@ var require_ARRINSERT = __commonJS({
23607
23607
  * @param json - The first value to insert
23608
23608
  * @param jsons - Additional values to insert
23609
23609
  */
23610
- parseCommand(parser, key, path18, index, json, ...jsons) {
23610
+ parseCommand(parser, key, path19, index, json, ...jsons) {
23611
23611
  parser.push("JSON.ARRINSERT");
23612
23612
  parser.pushKey(key);
23613
- parser.push(path18, index.toString(), (0, generic_transformers_1.transformRedisJsonArgument)(json));
23613
+ parser.push(path19, index.toString(), (0, generic_transformers_1.transformRedisJsonArgument)(json));
23614
23614
  for (let i = 0; i < jsons.length; i++) {
23615
23615
  parser.push((0, generic_transformers_1.transformRedisJsonArgument)(jsons[i]));
23616
23616
  }
@@ -23700,10 +23700,10 @@ var require_ARRTRIM = __commonJS({
23700
23700
  * @param start - Starting index (inclusive)
23701
23701
  * @param stop - Ending index (inclusive)
23702
23702
  */
23703
- parseCommand(parser, key, path18, start, stop) {
23703
+ parseCommand(parser, key, path19, start, stop) {
23704
23704
  parser.push("JSON.ARRTRIM");
23705
23705
  parser.pushKey(key);
23706
- parser.push(path18, start.toString(), stop.toString());
23706
+ parser.push(path19, start.toString(), stop.toString());
23707
23707
  },
23708
23708
  transformReply: void 0
23709
23709
  };
@@ -23868,10 +23868,10 @@ var require_MERGE3 = __commonJS({
23868
23868
  * @param path - Path to merge into
23869
23869
  * @param value - JSON value to merge
23870
23870
  */
23871
- parseCommand(parser, key, path18, value) {
23871
+ parseCommand(parser, key, path19, value) {
23872
23872
  parser.push("JSON.MERGE");
23873
23873
  parser.pushKey(key);
23874
- parser.push(path18, (0, generic_transformers_1.transformRedisJsonArgument)(value));
23874
+ parser.push(path19, (0, generic_transformers_1.transformRedisJsonArgument)(value));
23875
23875
  },
23876
23876
  transformReply: void 0
23877
23877
  };
@@ -23894,10 +23894,10 @@ var require_MGET2 = __commonJS({
23894
23894
  * @param keys - Array of keys containing JSON documents
23895
23895
  * @param path - Path to retrieve from each document
23896
23896
  */
23897
- parseCommand(parser, keys, path18) {
23897
+ parseCommand(parser, keys, path19) {
23898
23898
  parser.push("JSON.MGET");
23899
23899
  parser.pushKeys(keys);
23900
- parser.push(path18);
23900
+ parser.push(path19);
23901
23901
  },
23902
23902
  transformReply(reply) {
23903
23903
  return reply.map((json) => (0, generic_transformers_1.transformRedisJsonNullReply)(json));
@@ -23952,10 +23952,10 @@ var require_NUMINCRBY = __commonJS({
23952
23952
  * @param path - Path to the numeric value
23953
23953
  * @param by - Amount to increment by
23954
23954
  */
23955
- parseCommand(parser, key, path18, by) {
23955
+ parseCommand(parser, key, path19, by) {
23956
23956
  parser.push("JSON.NUMINCRBY");
23957
23957
  parser.pushKey(key);
23958
- parser.push(path18, by.toString());
23958
+ parser.push(path19, by.toString());
23959
23959
  },
23960
23960
  transformReply: {
23961
23961
  2: (reply) => {
@@ -23987,10 +23987,10 @@ var require_NUMMULTBY = __commonJS({
23987
23987
  * @param path - Path to the numeric value
23988
23988
  * @param by - Amount to multiply by
23989
23989
  */
23990
- parseCommand(parser, key, path18, by) {
23990
+ parseCommand(parser, key, path19, by) {
23991
23991
  parser.push("JSON.NUMMULTBY");
23992
23992
  parser.pushKey(key);
23993
- parser.push(path18, by.toString());
23993
+ parser.push(path19, by.toString());
23994
23994
  },
23995
23995
  transformReply: NUMINCRBY_1.default.transformReply
23996
23996
  };
@@ -24074,10 +24074,10 @@ var require_SET2 = __commonJS({
24074
24074
  * @deprecated options.NX - Use options.condition instead
24075
24075
  * @deprecated options.XX - Use options.condition instead
24076
24076
  */
24077
- parseCommand(parser, key, path18, json, options) {
24077
+ parseCommand(parser, key, path19, json, options) {
24078
24078
  parser.push("JSON.SET");
24079
24079
  parser.pushKey(key);
24080
- parser.push(path18, (0, generic_transformers_1.transformRedisJsonArgument)(json));
24080
+ parser.push(path19, (0, generic_transformers_1.transformRedisJsonArgument)(json));
24081
24081
  if (options?.condition) {
24082
24082
  parser.push(options?.condition);
24083
24083
  } else if (options?.NX) {
@@ -24165,10 +24165,10 @@ var require_TOGGLE = __commonJS({
24165
24165
  * @param key - The key containing the JSON document
24166
24166
  * @param path - Path to the boolean value
24167
24167
  */
24168
- parseCommand(parser, key, path18) {
24168
+ parseCommand(parser, key, path19) {
24169
24169
  parser.push("JSON.TOGGLE");
24170
24170
  parser.pushKey(key);
24171
- parser.push(path18);
24171
+ parser.push(path19);
24172
24172
  },
24173
24173
  transformReply: void 0
24174
24174
  };
@@ -30242,7 +30242,7 @@ function printHelp() {
30242
30242
  `);
30243
30243
  }
30244
30244
  function printVersion() {
30245
- console.log(`duclaw-cli v${true ? "1.8.14" : "unknown"}`);
30245
+ console.log(`duclaw-cli v${true ? "1.8.16" : "unknown"}`);
30246
30246
  }
30247
30247
  function getDuclawTemplate() {
30248
30248
  return {
@@ -30983,7 +30983,7 @@ var ReaddirpStream = class extends import_node_stream.Readable {
30983
30983
  this._directoryFilter = normalizeFilter(opts.directoryFilter);
30984
30984
  const statMethod = opts.lstat ? import_promises2.lstat : import_promises2.stat;
30985
30985
  if (wantBigintFsStats) {
30986
- this._stat = (path18) => statMethod(path18, { bigint: true });
30986
+ this._stat = (path19) => statMethod(path19, { bigint: true });
30987
30987
  } else {
30988
30988
  this._stat = statMethod;
30989
30989
  }
@@ -31008,8 +31008,8 @@ var ReaddirpStream = class extends import_node_stream.Readable {
31008
31008
  const par = this.parent;
31009
31009
  const fil = par && par.files;
31010
31010
  if (fil && fil.length > 0) {
31011
- const { path: path18, depth } = par;
31012
- const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path18));
31011
+ const { path: path19, depth } = par;
31012
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path19));
31013
31013
  const awaited = await Promise.all(slice);
31014
31014
  for (const entry of awaited) {
31015
31015
  if (!entry)
@@ -31049,20 +31049,20 @@ var ReaddirpStream = class extends import_node_stream.Readable {
31049
31049
  this.reading = false;
31050
31050
  }
31051
31051
  }
31052
- async _exploreDir(path18, depth) {
31052
+ async _exploreDir(path19, depth) {
31053
31053
  let files;
31054
31054
  try {
31055
- files = await (0, import_promises2.readdir)(path18, this._rdOptions);
31055
+ files = await (0, import_promises2.readdir)(path19, this._rdOptions);
31056
31056
  } catch (error) {
31057
31057
  this._onError(error);
31058
31058
  }
31059
- return { files, depth, path: path18 };
31059
+ return { files, depth, path: path19 };
31060
31060
  }
31061
- async _formatEntry(dirent, path18) {
31061
+ async _formatEntry(dirent, path19) {
31062
31062
  let entry;
31063
31063
  const basename4 = this._isDirent ? dirent.name : dirent;
31064
31064
  try {
31065
- const fullPath = (0, import_node_path2.resolve)((0, import_node_path2.join)(path18, basename4));
31065
+ const fullPath = (0, import_node_path2.resolve)((0, import_node_path2.join)(path19, basename4));
31066
31066
  entry = { path: (0, import_node_path2.relative)(this._root, fullPath), fullPath, basename: basename4 };
31067
31067
  entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
31068
31068
  } catch (err) {
@@ -31462,16 +31462,16 @@ var delFromSet = (main2, prop, item) => {
31462
31462
  };
31463
31463
  var isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
31464
31464
  var FsWatchInstances = /* @__PURE__ */ new Map();
31465
- function createFsWatchInstance(path18, options, listener, errHandler, emitRaw) {
31465
+ function createFsWatchInstance(path19, options, listener, errHandler, emitRaw) {
31466
31466
  const handleEvent = (rawEvent, evPath) => {
31467
- listener(path18);
31468
- emitRaw(rawEvent, evPath, { watchedPath: path18 });
31469
- if (evPath && path18 !== evPath) {
31470
- fsWatchBroadcast(sp.resolve(path18, evPath), KEY_LISTENERS, sp.join(path18, evPath));
31467
+ listener(path19);
31468
+ emitRaw(rawEvent, evPath, { watchedPath: path19 });
31469
+ if (evPath && path19 !== evPath) {
31470
+ fsWatchBroadcast(sp.resolve(path19, evPath), KEY_LISTENERS, sp.join(path19, evPath));
31471
31471
  }
31472
31472
  };
31473
31473
  try {
31474
- return (0, import_node_fs.watch)(path18, {
31474
+ return (0, import_node_fs.watch)(path19, {
31475
31475
  persistent: options.persistent
31476
31476
  }, handleEvent);
31477
31477
  } catch (error) {
@@ -31487,12 +31487,12 @@ var fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
31487
31487
  listener(val1, val2, val3);
31488
31488
  });
31489
31489
  };
31490
- var setFsWatchListener = (path18, fullPath, options, handlers) => {
31490
+ var setFsWatchListener = (path19, fullPath, options, handlers) => {
31491
31491
  const { listener, errHandler, rawEmitter } = handlers;
31492
31492
  let cont = FsWatchInstances.get(fullPath);
31493
31493
  let watcher;
31494
31494
  if (!options.persistent) {
31495
- watcher = createFsWatchInstance(path18, options, listener, errHandler, rawEmitter);
31495
+ watcher = createFsWatchInstance(path19, options, listener, errHandler, rawEmitter);
31496
31496
  if (!watcher)
31497
31497
  return;
31498
31498
  return watcher.close.bind(watcher);
@@ -31503,7 +31503,7 @@ var setFsWatchListener = (path18, fullPath, options, handlers) => {
31503
31503
  addAndConvert(cont, KEY_RAW, rawEmitter);
31504
31504
  } else {
31505
31505
  watcher = createFsWatchInstance(
31506
- path18,
31506
+ path19,
31507
31507
  options,
31508
31508
  fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
31509
31509
  errHandler,
@@ -31518,7 +31518,7 @@ var setFsWatchListener = (path18, fullPath, options, handlers) => {
31518
31518
  cont.watcherUnusable = true;
31519
31519
  if (isWindows && error.code === "EPERM") {
31520
31520
  try {
31521
- const fd = await (0, import_promises3.open)(path18, "r");
31521
+ const fd = await (0, import_promises3.open)(path19, "r");
31522
31522
  await fd.close();
31523
31523
  broadcastErr(error);
31524
31524
  } catch (err) {
@@ -31549,7 +31549,7 @@ var setFsWatchListener = (path18, fullPath, options, handlers) => {
31549
31549
  };
31550
31550
  };
31551
31551
  var FsWatchFileInstances = /* @__PURE__ */ new Map();
31552
- var setFsWatchFileListener = (path18, fullPath, options, handlers) => {
31552
+ var setFsWatchFileListener = (path19, fullPath, options, handlers) => {
31553
31553
  const { listener, rawEmitter } = handlers;
31554
31554
  let cont = FsWatchFileInstances.get(fullPath);
31555
31555
  const copts = cont && cont.options;
@@ -31571,7 +31571,7 @@ var setFsWatchFileListener = (path18, fullPath, options, handlers) => {
31571
31571
  });
31572
31572
  const currmtime = curr.mtimeMs;
31573
31573
  if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
31574
- foreach(cont.listeners, (listener2) => listener2(path18, curr));
31574
+ foreach(cont.listeners, (listener2) => listener2(path19, curr));
31575
31575
  }
31576
31576
  })
31577
31577
  };
@@ -31601,13 +31601,13 @@ var NodeFsHandler = class {
31601
31601
  * @param listener on fs change
31602
31602
  * @returns closer for the watcher instance
31603
31603
  */
31604
- _watchWithNodeFs(path18, listener) {
31604
+ _watchWithNodeFs(path19, listener) {
31605
31605
  const opts = this.fsw.options;
31606
- const directory = sp.dirname(path18);
31607
- const basename4 = sp.basename(path18);
31606
+ const directory = sp.dirname(path19);
31607
+ const basename4 = sp.basename(path19);
31608
31608
  const parent = this.fsw._getWatchedDir(directory);
31609
31609
  parent.add(basename4);
31610
- const absolutePath = sp.resolve(path18);
31610
+ const absolutePath = sp.resolve(path19);
31611
31611
  const options = {
31612
31612
  persistent: opts.persistent
31613
31613
  };
@@ -31617,12 +31617,12 @@ var NodeFsHandler = class {
31617
31617
  if (opts.usePolling) {
31618
31618
  const enableBin = opts.interval !== opts.binaryInterval;
31619
31619
  options.interval = enableBin && isBinaryPath(basename4) ? opts.binaryInterval : opts.interval;
31620
- closer = setFsWatchFileListener(path18, absolutePath, options, {
31620
+ closer = setFsWatchFileListener(path19, absolutePath, options, {
31621
31621
  listener,
31622
31622
  rawEmitter: this.fsw._emitRaw
31623
31623
  });
31624
31624
  } else {
31625
- closer = setFsWatchListener(path18, absolutePath, options, {
31625
+ closer = setFsWatchListener(path19, absolutePath, options, {
31626
31626
  listener,
31627
31627
  errHandler: this._boundHandleError,
31628
31628
  rawEmitter: this.fsw._emitRaw
@@ -31644,7 +31644,7 @@ var NodeFsHandler = class {
31644
31644
  let prevStats = stats;
31645
31645
  if (parent.has(basename4))
31646
31646
  return;
31647
- const listener = async (path18, newStats) => {
31647
+ const listener = async (path19, newStats) => {
31648
31648
  if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))
31649
31649
  return;
31650
31650
  if (!newStats || newStats.mtimeMs === 0) {
@@ -31658,11 +31658,11 @@ var NodeFsHandler = class {
31658
31658
  this.fsw._emit(EV.CHANGE, file, newStats2);
31659
31659
  }
31660
31660
  if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
31661
- this.fsw._closeFile(path18);
31661
+ this.fsw._closeFile(path19);
31662
31662
  prevStats = newStats2;
31663
31663
  const closer2 = this._watchWithNodeFs(file, listener);
31664
31664
  if (closer2)
31665
- this.fsw._addPathCloser(path18, closer2);
31665
+ this.fsw._addPathCloser(path19, closer2);
31666
31666
  } else {
31667
31667
  prevStats = newStats2;
31668
31668
  }
@@ -31694,7 +31694,7 @@ var NodeFsHandler = class {
31694
31694
  * @param item basename of this item
31695
31695
  * @returns true if no more processing is needed for this entry.
31696
31696
  */
31697
- async _handleSymlink(entry, directory, path18, item) {
31697
+ async _handleSymlink(entry, directory, path19, item) {
31698
31698
  if (this.fsw.closed) {
31699
31699
  return;
31700
31700
  }
@@ -31704,7 +31704,7 @@ var NodeFsHandler = class {
31704
31704
  this.fsw._incrReadyCount();
31705
31705
  let linkPath;
31706
31706
  try {
31707
- linkPath = await (0, import_promises3.realpath)(path18);
31707
+ linkPath = await (0, import_promises3.realpath)(path19);
31708
31708
  } catch (e) {
31709
31709
  this.fsw._emitReady();
31710
31710
  return true;
@@ -31714,12 +31714,12 @@ var NodeFsHandler = class {
31714
31714
  if (dir.has(item)) {
31715
31715
  if (this.fsw._symlinkPaths.get(full) !== linkPath) {
31716
31716
  this.fsw._symlinkPaths.set(full, linkPath);
31717
- this.fsw._emit(EV.CHANGE, path18, entry.stats);
31717
+ this.fsw._emit(EV.CHANGE, path19, entry.stats);
31718
31718
  }
31719
31719
  } else {
31720
31720
  dir.add(item);
31721
31721
  this.fsw._symlinkPaths.set(full, linkPath);
31722
- this.fsw._emit(EV.ADD, path18, entry.stats);
31722
+ this.fsw._emit(EV.ADD, path19, entry.stats);
31723
31723
  }
31724
31724
  this.fsw._emitReady();
31725
31725
  return true;
@@ -31749,9 +31749,9 @@ var NodeFsHandler = class {
31749
31749
  return;
31750
31750
  }
31751
31751
  const item = entry.path;
31752
- let path18 = sp.join(directory, item);
31752
+ let path19 = sp.join(directory, item);
31753
31753
  current.add(item);
31754
- if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path18, item)) {
31754
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path19, item)) {
31755
31755
  return;
31756
31756
  }
31757
31757
  if (this.fsw.closed) {
@@ -31760,8 +31760,8 @@ var NodeFsHandler = class {
31760
31760
  }
31761
31761
  if (item === target || !target && !previous.has(item)) {
31762
31762
  this.fsw._incrReadyCount();
31763
- path18 = sp.join(dir, sp.relative(dir, path18));
31764
- this._addToNodeFs(path18, initialAdd, wh, depth + 1);
31763
+ path19 = sp.join(dir, sp.relative(dir, path19));
31764
+ this._addToNodeFs(path19, initialAdd, wh, depth + 1);
31765
31765
  }
31766
31766
  }).on(EV.ERROR, this._boundHandleError);
31767
31767
  return new Promise((resolve11, reject) => {
@@ -31830,13 +31830,13 @@ var NodeFsHandler = class {
31830
31830
  * @param depth Child path actually targeted for watch
31831
31831
  * @param target Child path actually targeted for watch
31832
31832
  */
31833
- async _addToNodeFs(path18, initialAdd, priorWh, depth, target) {
31833
+ async _addToNodeFs(path19, initialAdd, priorWh, depth, target) {
31834
31834
  const ready = this.fsw._emitReady;
31835
- if (this.fsw._isIgnored(path18) || this.fsw.closed) {
31835
+ if (this.fsw._isIgnored(path19) || this.fsw.closed) {
31836
31836
  ready();
31837
31837
  return false;
31838
31838
  }
31839
- const wh = this.fsw._getWatchHelpers(path18);
31839
+ const wh = this.fsw._getWatchHelpers(path19);
31840
31840
  if (priorWh) {
31841
31841
  wh.filterPath = (entry) => priorWh.filterPath(entry);
31842
31842
  wh.filterDir = (entry) => priorWh.filterDir(entry);
@@ -31852,8 +31852,8 @@ var NodeFsHandler = class {
31852
31852
  const follow = this.fsw.options.followSymlinks;
31853
31853
  let closer;
31854
31854
  if (stats.isDirectory()) {
31855
- const absPath = sp.resolve(path18);
31856
- const targetPath = follow ? await (0, import_promises3.realpath)(path18) : path18;
31855
+ const absPath = sp.resolve(path19);
31856
+ const targetPath = follow ? await (0, import_promises3.realpath)(path19) : path19;
31857
31857
  if (this.fsw.closed)
31858
31858
  return;
31859
31859
  closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
@@ -31863,29 +31863,29 @@ var NodeFsHandler = class {
31863
31863
  this.fsw._symlinkPaths.set(absPath, targetPath);
31864
31864
  }
31865
31865
  } else if (stats.isSymbolicLink()) {
31866
- const targetPath = follow ? await (0, import_promises3.realpath)(path18) : path18;
31866
+ const targetPath = follow ? await (0, import_promises3.realpath)(path19) : path19;
31867
31867
  if (this.fsw.closed)
31868
31868
  return;
31869
31869
  const parent = sp.dirname(wh.watchPath);
31870
31870
  this.fsw._getWatchedDir(parent).add(wh.watchPath);
31871
31871
  this.fsw._emit(EV.ADD, wh.watchPath, stats);
31872
- closer = await this._handleDir(parent, stats, initialAdd, depth, path18, wh, targetPath);
31872
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path19, wh, targetPath);
31873
31873
  if (this.fsw.closed)
31874
31874
  return;
31875
31875
  if (targetPath !== void 0) {
31876
- this.fsw._symlinkPaths.set(sp.resolve(path18), targetPath);
31876
+ this.fsw._symlinkPaths.set(sp.resolve(path19), targetPath);
31877
31877
  }
31878
31878
  } else {
31879
31879
  closer = this._handleFile(wh.watchPath, stats, initialAdd);
31880
31880
  }
31881
31881
  ready();
31882
31882
  if (closer)
31883
- this.fsw._addPathCloser(path18, closer);
31883
+ this.fsw._addPathCloser(path19, closer);
31884
31884
  return false;
31885
31885
  } catch (error) {
31886
31886
  if (this.fsw._handleError(error)) {
31887
31887
  ready();
31888
- return path18;
31888
+ return path19;
31889
31889
  }
31890
31890
  }
31891
31891
  }
@@ -31928,24 +31928,24 @@ function createPattern(matcher) {
31928
31928
  }
31929
31929
  return () => false;
31930
31930
  }
31931
- function normalizePath(path18) {
31932
- if (typeof path18 !== "string")
31931
+ function normalizePath(path19) {
31932
+ if (typeof path19 !== "string")
31933
31933
  throw new Error("string expected");
31934
- path18 = sp2.normalize(path18);
31935
- path18 = path18.replace(/\\/g, "/");
31934
+ path19 = sp2.normalize(path19);
31935
+ path19 = path19.replace(/\\/g, "/");
31936
31936
  let prepend = false;
31937
- if (path18.startsWith("//"))
31937
+ if (path19.startsWith("//"))
31938
31938
  prepend = true;
31939
- path18 = path18.replace(DOUBLE_SLASH_RE, "/");
31939
+ path19 = path19.replace(DOUBLE_SLASH_RE, "/");
31940
31940
  if (prepend)
31941
- path18 = "/" + path18;
31942
- return path18;
31941
+ path19 = "/" + path19;
31942
+ return path19;
31943
31943
  }
31944
31944
  function matchPatterns(patterns, testString, stats) {
31945
- const path18 = normalizePath(testString);
31945
+ const path19 = normalizePath(testString);
31946
31946
  for (let index = 0; index < patterns.length; index++) {
31947
31947
  const pattern = patterns[index];
31948
- if (pattern(path18, stats)) {
31948
+ if (pattern(path19, stats)) {
31949
31949
  return true;
31950
31950
  }
31951
31951
  }
@@ -31983,19 +31983,19 @@ var toUnix = (string) => {
31983
31983
  }
31984
31984
  return str;
31985
31985
  };
31986
- var normalizePathToUnix = (path18) => toUnix(sp2.normalize(toUnix(path18)));
31987
- var normalizeIgnored = (cwd = "") => (path18) => {
31988
- if (typeof path18 === "string") {
31989
- return normalizePathToUnix(sp2.isAbsolute(path18) ? path18 : sp2.join(cwd, path18));
31986
+ var normalizePathToUnix = (path19) => toUnix(sp2.normalize(toUnix(path19)));
31987
+ var normalizeIgnored = (cwd = "") => (path19) => {
31988
+ if (typeof path19 === "string") {
31989
+ return normalizePathToUnix(sp2.isAbsolute(path19) ? path19 : sp2.join(cwd, path19));
31990
31990
  } else {
31991
- return path18;
31991
+ return path19;
31992
31992
  }
31993
31993
  };
31994
- var getAbsolutePath = (path18, cwd) => {
31995
- if (sp2.isAbsolute(path18)) {
31996
- return path18;
31994
+ var getAbsolutePath = (path19, cwd) => {
31995
+ if (sp2.isAbsolute(path19)) {
31996
+ return path19;
31997
31997
  }
31998
- return sp2.join(cwd, path18);
31998
+ return sp2.join(cwd, path19);
31999
31999
  };
32000
32000
  var EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
32001
32001
  var DirEntry = class {
@@ -32060,10 +32060,10 @@ var WatchHelper = class {
32060
32060
  dirParts;
32061
32061
  followSymlinks;
32062
32062
  statMethod;
32063
- constructor(path18, follow, fsw) {
32063
+ constructor(path19, follow, fsw) {
32064
32064
  this.fsw = fsw;
32065
- const watchPath = path18;
32066
- this.path = path18 = path18.replace(REPLACER_RE, "");
32065
+ const watchPath = path19;
32066
+ this.path = path19 = path19.replace(REPLACER_RE, "");
32067
32067
  this.watchPath = watchPath;
32068
32068
  this.fullWatchPath = sp2.resolve(watchPath);
32069
32069
  this.dirParts = [];
@@ -32203,20 +32203,20 @@ var FSWatcher = class extends import_node_events.EventEmitter {
32203
32203
  this._closePromise = void 0;
32204
32204
  let paths = unifyPaths(paths_);
32205
32205
  if (cwd) {
32206
- paths = paths.map((path18) => {
32207
- const absPath = getAbsolutePath(path18, cwd);
32206
+ paths = paths.map((path19) => {
32207
+ const absPath = getAbsolutePath(path19, cwd);
32208
32208
  return absPath;
32209
32209
  });
32210
32210
  }
32211
- paths.forEach((path18) => {
32212
- this._removeIgnoredPath(path18);
32211
+ paths.forEach((path19) => {
32212
+ this._removeIgnoredPath(path19);
32213
32213
  });
32214
32214
  this._userIgnored = void 0;
32215
32215
  if (!this._readyCount)
32216
32216
  this._readyCount = 0;
32217
32217
  this._readyCount += paths.length;
32218
- Promise.all(paths.map(async (path18) => {
32219
- const res = await this._nodeFsHandler._addToNodeFs(path18, !_internal, void 0, 0, _origAdd);
32218
+ Promise.all(paths.map(async (path19) => {
32219
+ const res = await this._nodeFsHandler._addToNodeFs(path19, !_internal, void 0, 0, _origAdd);
32220
32220
  if (res)
32221
32221
  this._emitReady();
32222
32222
  return res;
@@ -32238,17 +32238,17 @@ var FSWatcher = class extends import_node_events.EventEmitter {
32238
32238
  return this;
32239
32239
  const paths = unifyPaths(paths_);
32240
32240
  const { cwd } = this.options;
32241
- paths.forEach((path18) => {
32242
- if (!sp2.isAbsolute(path18) && !this._closers.has(path18)) {
32241
+ paths.forEach((path19) => {
32242
+ if (!sp2.isAbsolute(path19) && !this._closers.has(path19)) {
32243
32243
  if (cwd)
32244
- path18 = sp2.join(cwd, path18);
32245
- path18 = sp2.resolve(path18);
32244
+ path19 = sp2.join(cwd, path19);
32245
+ path19 = sp2.resolve(path19);
32246
32246
  }
32247
- this._closePath(path18);
32248
- this._addIgnoredPath(path18);
32249
- if (this._watched.has(path18)) {
32247
+ this._closePath(path19);
32248
+ this._addIgnoredPath(path19);
32249
+ if (this._watched.has(path19)) {
32250
32250
  this._addIgnoredPath({
32251
- path: path18,
32251
+ path: path19,
32252
32252
  recursive: true
32253
32253
  });
32254
32254
  }
@@ -32312,38 +32312,38 @@ var FSWatcher = class extends import_node_events.EventEmitter {
32312
32312
  * @param stats arguments to be passed with event
32313
32313
  * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
32314
32314
  */
32315
- async _emit(event, path18, stats) {
32315
+ async _emit(event, path19, stats) {
32316
32316
  if (this.closed)
32317
32317
  return;
32318
32318
  const opts = this.options;
32319
32319
  if (isWindows)
32320
- path18 = sp2.normalize(path18);
32320
+ path19 = sp2.normalize(path19);
32321
32321
  if (opts.cwd)
32322
- path18 = sp2.relative(opts.cwd, path18);
32323
- const args = [path18];
32322
+ path19 = sp2.relative(opts.cwd, path19);
32323
+ const args = [path19];
32324
32324
  if (stats != null)
32325
32325
  args.push(stats);
32326
32326
  const awf = opts.awaitWriteFinish;
32327
32327
  let pw;
32328
- if (awf && (pw = this._pendingWrites.get(path18))) {
32328
+ if (awf && (pw = this._pendingWrites.get(path19))) {
32329
32329
  pw.lastChange = /* @__PURE__ */ new Date();
32330
32330
  return this;
32331
32331
  }
32332
32332
  if (opts.atomic) {
32333
32333
  if (event === EVENTS.UNLINK) {
32334
- this._pendingUnlinks.set(path18, [event, ...args]);
32334
+ this._pendingUnlinks.set(path19, [event, ...args]);
32335
32335
  setTimeout(() => {
32336
- this._pendingUnlinks.forEach((entry, path19) => {
32336
+ this._pendingUnlinks.forEach((entry, path20) => {
32337
32337
  this.emit(...entry);
32338
32338
  this.emit(EVENTS.ALL, ...entry);
32339
- this._pendingUnlinks.delete(path19);
32339
+ this._pendingUnlinks.delete(path20);
32340
32340
  });
32341
32341
  }, typeof opts.atomic === "number" ? opts.atomic : 100);
32342
32342
  return this;
32343
32343
  }
32344
- if (event === EVENTS.ADD && this._pendingUnlinks.has(path18)) {
32344
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path19)) {
32345
32345
  event = EVENTS.CHANGE;
32346
- this._pendingUnlinks.delete(path18);
32346
+ this._pendingUnlinks.delete(path19);
32347
32347
  }
32348
32348
  }
32349
32349
  if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
@@ -32361,16 +32361,16 @@ var FSWatcher = class extends import_node_events.EventEmitter {
32361
32361
  this.emitWithAll(event, args);
32362
32362
  }
32363
32363
  };
32364
- this._awaitWriteFinish(path18, awf.stabilityThreshold, event, awfEmit);
32364
+ this._awaitWriteFinish(path19, awf.stabilityThreshold, event, awfEmit);
32365
32365
  return this;
32366
32366
  }
32367
32367
  if (event === EVENTS.CHANGE) {
32368
- const isThrottled = !this._throttle(EVENTS.CHANGE, path18, 50);
32368
+ const isThrottled = !this._throttle(EVENTS.CHANGE, path19, 50);
32369
32369
  if (isThrottled)
32370
32370
  return this;
32371
32371
  }
32372
32372
  if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
32373
- const fullPath = opts.cwd ? sp2.join(opts.cwd, path18) : path18;
32373
+ const fullPath = opts.cwd ? sp2.join(opts.cwd, path19) : path19;
32374
32374
  let stats2;
32375
32375
  try {
32376
32376
  stats2 = await (0, import_promises4.stat)(fullPath);
@@ -32401,23 +32401,23 @@ var FSWatcher = class extends import_node_events.EventEmitter {
32401
32401
  * @param timeout duration of time to suppress duplicate actions
32402
32402
  * @returns tracking object or false if action should be suppressed
32403
32403
  */
32404
- _throttle(actionType, path18, timeout) {
32404
+ _throttle(actionType, path19, timeout) {
32405
32405
  if (!this._throttled.has(actionType)) {
32406
32406
  this._throttled.set(actionType, /* @__PURE__ */ new Map());
32407
32407
  }
32408
32408
  const action = this._throttled.get(actionType);
32409
32409
  if (!action)
32410
32410
  throw new Error("invalid throttle");
32411
- const actionPath = action.get(path18);
32411
+ const actionPath = action.get(path19);
32412
32412
  if (actionPath) {
32413
32413
  actionPath.count++;
32414
32414
  return false;
32415
32415
  }
32416
32416
  let timeoutObject;
32417
32417
  const clear = () => {
32418
- const item = action.get(path18);
32418
+ const item = action.get(path19);
32419
32419
  const count = item ? item.count : 0;
32420
- action.delete(path18);
32420
+ action.delete(path19);
32421
32421
  clearTimeout(timeoutObject);
32422
32422
  if (item)
32423
32423
  clearTimeout(item.timeoutObject);
@@ -32425,7 +32425,7 @@ var FSWatcher = class extends import_node_events.EventEmitter {
32425
32425
  };
32426
32426
  timeoutObject = setTimeout(clear, timeout);
32427
32427
  const thr = { timeoutObject, clear, count: 0 };
32428
- action.set(path18, thr);
32428
+ action.set(path19, thr);
32429
32429
  return thr;
32430
32430
  }
32431
32431
  _incrReadyCount() {
@@ -32439,44 +32439,44 @@ var FSWatcher = class extends import_node_events.EventEmitter {
32439
32439
  * @param event
32440
32440
  * @param awfEmit Callback to be called when ready for event to be emitted.
32441
32441
  */
32442
- _awaitWriteFinish(path18, threshold, event, awfEmit) {
32442
+ _awaitWriteFinish(path19, threshold, event, awfEmit) {
32443
32443
  const awf = this.options.awaitWriteFinish;
32444
32444
  if (typeof awf !== "object")
32445
32445
  return;
32446
32446
  const pollInterval = awf.pollInterval;
32447
32447
  let timeoutHandler;
32448
- let fullPath = path18;
32449
- if (this.options.cwd && !sp2.isAbsolute(path18)) {
32450
- fullPath = sp2.join(this.options.cwd, path18);
32448
+ let fullPath = path19;
32449
+ if (this.options.cwd && !sp2.isAbsolute(path19)) {
32450
+ fullPath = sp2.join(this.options.cwd, path19);
32451
32451
  }
32452
32452
  const now = /* @__PURE__ */ new Date();
32453
32453
  const writes = this._pendingWrites;
32454
32454
  function awaitWriteFinishFn(prevStat) {
32455
32455
  (0, import_node_fs2.stat)(fullPath, (err, curStat) => {
32456
- if (err || !writes.has(path18)) {
32456
+ if (err || !writes.has(path19)) {
32457
32457
  if (err && err.code !== "ENOENT")
32458
32458
  awfEmit(err);
32459
32459
  return;
32460
32460
  }
32461
32461
  const now2 = Number(/* @__PURE__ */ new Date());
32462
32462
  if (prevStat && curStat.size !== prevStat.size) {
32463
- writes.get(path18).lastChange = now2;
32463
+ writes.get(path19).lastChange = now2;
32464
32464
  }
32465
- const pw = writes.get(path18);
32465
+ const pw = writes.get(path19);
32466
32466
  const df = now2 - pw.lastChange;
32467
32467
  if (df >= threshold) {
32468
- writes.delete(path18);
32468
+ writes.delete(path19);
32469
32469
  awfEmit(void 0, curStat);
32470
32470
  } else {
32471
32471
  timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
32472
32472
  }
32473
32473
  });
32474
32474
  }
32475
- if (!writes.has(path18)) {
32476
- writes.set(path18, {
32475
+ if (!writes.has(path19)) {
32476
+ writes.set(path19, {
32477
32477
  lastChange: now,
32478
32478
  cancelWait: () => {
32479
- writes.delete(path18);
32479
+ writes.delete(path19);
32480
32480
  clearTimeout(timeoutHandler);
32481
32481
  return event;
32482
32482
  }
@@ -32487,8 +32487,8 @@ var FSWatcher = class extends import_node_events.EventEmitter {
32487
32487
  /**
32488
32488
  * Determines whether user has asked to ignore this path.
32489
32489
  */
32490
- _isIgnored(path18, stats) {
32491
- if (this.options.atomic && DOT_RE.test(path18))
32490
+ _isIgnored(path19, stats) {
32491
+ if (this.options.atomic && DOT_RE.test(path19))
32492
32492
  return true;
32493
32493
  if (!this._userIgnored) {
32494
32494
  const { cwd } = this.options;
@@ -32498,17 +32498,17 @@ var FSWatcher = class extends import_node_events.EventEmitter {
32498
32498
  const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
32499
32499
  this._userIgnored = anymatch(list, void 0);
32500
32500
  }
32501
- return this._userIgnored(path18, stats);
32501
+ return this._userIgnored(path19, stats);
32502
32502
  }
32503
- _isntIgnored(path18, stat10) {
32504
- return !this._isIgnored(path18, stat10);
32503
+ _isntIgnored(path19, stat10) {
32504
+ return !this._isIgnored(path19, stat10);
32505
32505
  }
32506
32506
  /**
32507
32507
  * Provides a set of common helpers and properties relating to symlink handling.
32508
32508
  * @param path file or directory pattern being watched
32509
32509
  */
32510
- _getWatchHelpers(path18) {
32511
- return new WatchHelper(path18, this.options.followSymlinks, this);
32510
+ _getWatchHelpers(path19) {
32511
+ return new WatchHelper(path19, this.options.followSymlinks, this);
32512
32512
  }
32513
32513
  // Directory helpers
32514
32514
  // -----------------
@@ -32540,63 +32540,63 @@ var FSWatcher = class extends import_node_events.EventEmitter {
32540
32540
  * @param item base path of item/directory
32541
32541
  */
32542
32542
  _remove(directory, item, isDirectory) {
32543
- const path18 = sp2.join(directory, item);
32544
- const fullPath = sp2.resolve(path18);
32545
- isDirectory = isDirectory != null ? isDirectory : this._watched.has(path18) || this._watched.has(fullPath);
32546
- if (!this._throttle("remove", path18, 100))
32543
+ const path19 = sp2.join(directory, item);
32544
+ const fullPath = sp2.resolve(path19);
32545
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path19) || this._watched.has(fullPath);
32546
+ if (!this._throttle("remove", path19, 100))
32547
32547
  return;
32548
32548
  if (!isDirectory && this._watched.size === 1) {
32549
32549
  this.add(directory, item, true);
32550
32550
  }
32551
- const wp = this._getWatchedDir(path18);
32551
+ const wp = this._getWatchedDir(path19);
32552
32552
  const nestedDirectoryChildren = wp.getChildren();
32553
- nestedDirectoryChildren.forEach((nested) => this._remove(path18, nested));
32553
+ nestedDirectoryChildren.forEach((nested) => this._remove(path19, nested));
32554
32554
  const parent = this._getWatchedDir(directory);
32555
32555
  const wasTracked = parent.has(item);
32556
32556
  parent.remove(item);
32557
32557
  if (this._symlinkPaths.has(fullPath)) {
32558
32558
  this._symlinkPaths.delete(fullPath);
32559
32559
  }
32560
- let relPath = path18;
32560
+ let relPath = path19;
32561
32561
  if (this.options.cwd)
32562
- relPath = sp2.relative(this.options.cwd, path18);
32562
+ relPath = sp2.relative(this.options.cwd, path19);
32563
32563
  if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
32564
32564
  const event = this._pendingWrites.get(relPath).cancelWait();
32565
32565
  if (event === EVENTS.ADD)
32566
32566
  return;
32567
32567
  }
32568
- this._watched.delete(path18);
32568
+ this._watched.delete(path19);
32569
32569
  this._watched.delete(fullPath);
32570
32570
  const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
32571
- if (wasTracked && !this._isIgnored(path18))
32572
- this._emit(eventName, path18);
32573
- this._closePath(path18);
32571
+ if (wasTracked && !this._isIgnored(path19))
32572
+ this._emit(eventName, path19);
32573
+ this._closePath(path19);
32574
32574
  }
32575
32575
  /**
32576
32576
  * Closes all watchers for a path
32577
32577
  */
32578
- _closePath(path18) {
32579
- this._closeFile(path18);
32580
- const dir = sp2.dirname(path18);
32581
- this._getWatchedDir(dir).remove(sp2.basename(path18));
32578
+ _closePath(path19) {
32579
+ this._closeFile(path19);
32580
+ const dir = sp2.dirname(path19);
32581
+ this._getWatchedDir(dir).remove(sp2.basename(path19));
32582
32582
  }
32583
32583
  /**
32584
32584
  * Closes only file-specific watchers
32585
32585
  */
32586
- _closeFile(path18) {
32587
- const closers = this._closers.get(path18);
32586
+ _closeFile(path19) {
32587
+ const closers = this._closers.get(path19);
32588
32588
  if (!closers)
32589
32589
  return;
32590
32590
  closers.forEach((closer) => closer());
32591
- this._closers.delete(path18);
32591
+ this._closers.delete(path19);
32592
32592
  }
32593
- _addPathCloser(path18, closer) {
32593
+ _addPathCloser(path19, closer) {
32594
32594
  if (!closer)
32595
32595
  return;
32596
- let list = this._closers.get(path18);
32596
+ let list = this._closers.get(path19);
32597
32597
  if (!list) {
32598
32598
  list = [];
32599
- this._closers.set(path18, list);
32599
+ this._closers.set(path19, list);
32600
32600
  }
32601
32601
  list.push(closer);
32602
32602
  }
@@ -32629,8 +32629,8 @@ var chokidar_default = { watch, FSWatcher };
32629
32629
  var import_node_cron = __toESM(require_node_cron());
32630
32630
 
32631
32631
  // src/agent/createAgent.ts
32632
- var import_node_crypto10 = require("node:crypto");
32633
- var import_node_fs6 = require("node:fs");
32632
+ var import_node_crypto11 = require("node:crypto");
32633
+ var import_node_fs7 = require("node:fs");
32634
32634
 
32635
32635
  // src/background/BackgroundManager.ts
32636
32636
  var import_child_process = require("child_process");
@@ -34060,12 +34060,12 @@ function encodeURIPath(str) {
34060
34060
  return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
34061
34061
  }
34062
34062
  var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
34063
- var createPathTagFunction = (pathEncoder = encodeURIPath) => function path18(statics, ...params) {
34063
+ var createPathTagFunction = (pathEncoder = encodeURIPath) => function path19(statics, ...params) {
34064
34064
  if (statics.length === 1)
34065
34065
  return statics[0];
34066
34066
  let postPath = false;
34067
34067
  const invalidSegments = [];
34068
- const path19 = statics.reduce((previousValue, currentValue, index) => {
34068
+ const path20 = statics.reduce((previousValue, currentValue, index) => {
34069
34069
  if (/[?#]/.test(currentValue)) {
34070
34070
  postPath = true;
34071
34071
  }
@@ -34082,7 +34082,7 @@ var createPathTagFunction = (pathEncoder = encodeURIPath) => function path18(sta
34082
34082
  }
34083
34083
  return previousValue + currentValue + (index === params.length ? "" : encoded);
34084
34084
  }, "");
34085
- const pathOnly = path19.split(/[?#]/, 1)[0];
34085
+ const pathOnly = path20.split(/[?#]/, 1)[0];
34086
34086
  const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
34087
34087
  let match2;
34088
34088
  while ((match2 = invalidSegmentPattern.exec(pathOnly)) !== null) {
@@ -34103,10 +34103,10 @@ var createPathTagFunction = (pathEncoder = encodeURIPath) => function path18(sta
34103
34103
  }, "");
34104
34104
  throw new AnthropicError(`Path parameters result in path with invalid segments:
34105
34105
  ${invalidSegments.map((e) => e.error).join("\n")}
34106
- ${path19}
34106
+ ${path20}
34107
34107
  ${underline}`);
34108
34108
  }
34109
- return path19;
34109
+ return path20;
34110
34110
  };
34111
34111
  var path4 = /* @__PURE__ */ createPathTagFunction(encodeURIPath);
34112
34112
 
@@ -37217,9 +37217,9 @@ var BaseAnthropic = class {
37217
37217
  makeStatusError(status, error, message, headers) {
37218
37218
  return APIError.generate(status, error, message, headers);
37219
37219
  }
37220
- buildURL(path18, query, defaultBaseURL) {
37220
+ buildURL(path19, query, defaultBaseURL) {
37221
37221
  const baseURL = !__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
37222
- const url = isAbsoluteURL(path18) ? new URL(path18) : new URL(baseURL + (baseURL.endsWith("/") && path18.startsWith("/") ? path18.slice(1) : path18));
37222
+ const url = isAbsoluteURL(path19) ? new URL(path19) : new URL(baseURL + (baseURL.endsWith("/") && path19.startsWith("/") ? path19.slice(1) : path19));
37223
37223
  const defaultQuery = this.defaultQuery();
37224
37224
  if (!isEmptyObj(defaultQuery)) {
37225
37225
  query = { ...defaultQuery, ...query };
@@ -37250,24 +37250,24 @@ var BaseAnthropic = class {
37250
37250
  */
37251
37251
  async prepareRequest(request, { url, options }) {
37252
37252
  }
37253
- get(path18, opts) {
37254
- return this.methodRequest("get", path18, opts);
37253
+ get(path19, opts) {
37254
+ return this.methodRequest("get", path19, opts);
37255
37255
  }
37256
- post(path18, opts) {
37257
- return this.methodRequest("post", path18, opts);
37256
+ post(path19, opts) {
37257
+ return this.methodRequest("post", path19, opts);
37258
37258
  }
37259
- patch(path18, opts) {
37260
- return this.methodRequest("patch", path18, opts);
37259
+ patch(path19, opts) {
37260
+ return this.methodRequest("patch", path19, opts);
37261
37261
  }
37262
- put(path18, opts) {
37263
- return this.methodRequest("put", path18, opts);
37262
+ put(path19, opts) {
37263
+ return this.methodRequest("put", path19, opts);
37264
37264
  }
37265
- delete(path18, opts) {
37266
- return this.methodRequest("delete", path18, opts);
37265
+ delete(path19, opts) {
37266
+ return this.methodRequest("delete", path19, opts);
37267
37267
  }
37268
- methodRequest(method, path18, opts) {
37268
+ methodRequest(method, path19, opts) {
37269
37269
  return this.request(Promise.resolve(opts).then((opts2) => {
37270
- return { method, path: path18, ...opts2 };
37270
+ return { method, path: path19, ...opts2 };
37271
37271
  }));
37272
37272
  }
37273
37273
  request(options, remainingRetries = null) {
@@ -37371,8 +37371,8 @@ var BaseAnthropic = class {
37371
37371
  }));
37372
37372
  return { response, options, controller, requestLogID, retryOfRequestLogID, startTime: startTime2 };
37373
37373
  }
37374
- getAPIList(path18, Page2, opts) {
37375
- return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path18, ...opts2 })) : { method: "get", path: path18, ...opts });
37374
+ getAPIList(path19, Page2, opts) {
37375
+ return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path19, ...opts2 })) : { method: "get", path: path19, ...opts });
37376
37376
  }
37377
37377
  requestAPIList(Page2, options) {
37378
37378
  const request = this.makeRequest(options, null, void 0);
@@ -37460,8 +37460,8 @@ var BaseAnthropic = class {
37460
37460
  }
37461
37461
  async buildRequest(inputOptions, { retryCount = 0 } = {}) {
37462
37462
  const options = { ...inputOptions };
37463
- const { method, path: path18, query, defaultBaseURL } = options;
37464
- const url = this.buildURL(path18, query, defaultBaseURL);
37463
+ const { method, path: path19, query, defaultBaseURL } = options;
37464
+ const url = this.buildURL(path19, query, defaultBaseURL);
37465
37465
  if ("timeout" in options)
37466
37466
  validatePositiveInteger("timeout", options.timeout);
37467
37467
  options.timeout = options.timeout ?? this.timeout;
@@ -38248,6 +38248,38 @@ var clearMessages = async (storage, userId, date, cronTitle) => {
38248
38248
  await storage.del(key);
38249
38249
  };
38250
38250
 
38251
+ // src/runtime/activity.ts
38252
+ async function reportRuntimeActivity(input) {
38253
+ const baseUrl = process.env.DUCLAW_CONTROL_PLANE_BASE_URL?.replace(/\/$/, "");
38254
+ const token = process.env.DUCLAW_CONTROL_PLANE_METERING_TOKEN;
38255
+ const tenantId = process.env.DUCLAW_TENANT_ID;
38256
+ if (!baseUrl || !token || !tenantId) return;
38257
+ try {
38258
+ const response = await fetch(`${baseUrl}/internal/runtime/activity`, {
38259
+ method: "POST",
38260
+ signal: AbortSignal.timeout(2500),
38261
+ headers: {
38262
+ authorization: `Bearer ${token}`,
38263
+ "content-type": "application/json"
38264
+ },
38265
+ body: JSON.stringify({
38266
+ tenantId,
38267
+ kind: input.kind,
38268
+ status: input.status,
38269
+ toolName: input.toolName,
38270
+ toolCallId: input.toolCallId ?? null,
38271
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
38272
+ metadata: input.metadata ?? {}
38273
+ })
38274
+ });
38275
+ if (!response.ok) {
38276
+ console.warn(`[runtime-activity] \u4E0A\u62A5\u5931\u8D25: tool=${input.toolName} status=${input.status} http=${response.status}`);
38277
+ }
38278
+ } catch (err) {
38279
+ console.warn(`[runtime-activity] \u4E0A\u62A5\u5F02\u5E38: tool=${input.toolName} status=${input.status} error=${err.message}`);
38280
+ }
38281
+ }
38282
+
38251
38283
  // src/tools/ToolExecutor.ts
38252
38284
  var createToolExecutor = (registry2) => {
38253
38285
  return {
@@ -38260,10 +38292,46 @@ var createToolExecutor = (registry2) => {
38260
38292
  throw new Error(`[ToolExecutor] \u5DE5\u5177 ${name} \u7F3A\u5C11\u5FC5\u586B\u53C2\u6570: ${key}`);
38261
38293
  }
38262
38294
  }
38295
+ const toolCallId = typeof userRequest?.metadata?.toolCallId === "string" ? userRequest.metadata.toolCallId : null;
38296
+ await reportRuntimeActivity({
38297
+ kind: "tool_use",
38298
+ toolName: name,
38299
+ status: "started",
38300
+ toolCallId,
38301
+ metadata: {
38302
+ platform: userRequest?.platform,
38303
+ requestId: userRequest?.requestId,
38304
+ departmentAgentId: userRequest?.departmentAgentId
38305
+ }
38306
+ });
38263
38307
  try {
38264
- return await tool.execute(input ?? {}, userRequest);
38308
+ const result = await tool.execute(input ?? {}, userRequest);
38309
+ await reportRuntimeActivity({
38310
+ kind: "tool_use",
38311
+ toolName: name,
38312
+ status: "completed",
38313
+ toolCallId,
38314
+ metadata: {
38315
+ platform: userRequest?.platform,
38316
+ requestId: userRequest?.requestId,
38317
+ departmentAgentId: userRequest?.departmentAgentId
38318
+ }
38319
+ });
38320
+ return result;
38265
38321
  } catch (error) {
38266
38322
  const err = error;
38323
+ await reportRuntimeActivity({
38324
+ kind: "tool_use",
38325
+ toolName: name,
38326
+ status: "failed",
38327
+ toolCallId,
38328
+ metadata: {
38329
+ platform: userRequest?.platform,
38330
+ requestId: userRequest?.requestId,
38331
+ departmentAgentId: userRequest?.departmentAgentId,
38332
+ error: err.message
38333
+ }
38334
+ });
38267
38335
  return `\u5DE5\u5177\u6267\u884C\u5931\u8D25 [${name}], reason: ${err.message}`;
38268
38336
  }
38269
38337
  },
@@ -39476,13 +39544,13 @@ var Diff = class {
39476
39544
  editLength++;
39477
39545
  };
39478
39546
  if (callback) {
39479
- (function exec2() {
39547
+ (function exec() {
39480
39548
  setTimeout(function() {
39481
39549
  if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
39482
39550
  return callback(void 0);
39483
39551
  }
39484
39552
  if (!execEditLength()) {
39485
- exec2();
39553
+ exec();
39486
39554
  }
39487
39555
  }, 0);
39488
39556
  })();
@@ -39495,16 +39563,16 @@ var Diff = class {
39495
39563
  }
39496
39564
  }
39497
39565
  }
39498
- addToPath(path18, added, removed, oldPosInc, options) {
39499
- const last = path18.lastComponent;
39566
+ addToPath(path19, added, removed, oldPosInc, options) {
39567
+ const last = path19.lastComponent;
39500
39568
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
39501
39569
  return {
39502
- oldPos: path18.oldPos + oldPosInc,
39570
+ oldPos: path19.oldPos + oldPosInc,
39503
39571
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
39504
39572
  };
39505
39573
  } else {
39506
39574
  return {
39507
- oldPos: path18.oldPos + oldPosInc,
39575
+ oldPos: path19.oldPos + oldPosInc,
39508
39576
  lastComponent: { count: 1, added, removed, previousComponent: last }
39509
39577
  };
39510
39578
  }
@@ -42433,29 +42501,231 @@ ${replies}`;
42433
42501
  };
42434
42502
 
42435
42503
  // src/department/learning.ts
42504
+ var import_node_fs4 = require("node:fs");
42505
+ var import_node_path12 = __toESM(require("node:path"));
42506
+ var import_node_crypto6 = require("node:crypto");
42507
+
42508
+ // src/skill/SkillValidator.ts
42436
42509
  var import_node_fs3 = require("node:fs");
42437
42510
  var import_node_path11 = __toESM(require("node:path"));
42438
- var import_node_crypto6 = require("node:crypto");
42439
- var ensureDir = (dir) => (0, import_node_fs3.mkdirSync)(dir, { recursive: true });
42511
+ var SKILL_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
42512
+ var REQUIRED_SECTIONS = [
42513
+ /(^|\n)##\s+(when to use|何时使用|trigger|triggers)\b/i,
42514
+ /(^|\n)##\s+(steps|workflow|procedure|执行步骤|工作流)\b/i
42515
+ ];
42516
+ var stripYamlQuotes = (value) => {
42517
+ const trimmed = value.trim();
42518
+ if (trimmed.startsWith(`"`) && trimmed.endsWith(`"`) || trimmed.startsWith(`'`) && trimmed.endsWith(`'`)) {
42519
+ return trimmed.slice(1, -1).trim();
42520
+ }
42521
+ return trimmed;
42522
+ };
42523
+ var addError = (errors, code, message) => {
42524
+ errors.push({ code, message });
42525
+ };
42526
+ var addWarning = (warnings, code, message) => {
42527
+ warnings.push({ code, message });
42528
+ };
42529
+ var isValidSkillName = (name) => {
42530
+ return SKILL_NAME_PATTERN.test(name) && !name.includes(`--`);
42531
+ };
42532
+ var assertSafeSkillTarget = (rootDir, skillName) => {
42533
+ if (!isValidSkillName(skillName)) {
42534
+ throw new Error(`Invalid skill name "${skillName}". Use lowercase letters, digits, and single hyphens only.`);
42535
+ }
42536
+ const root = import_node_path11.default.resolve(rootDir);
42537
+ const target = import_node_path11.default.resolve(root, skillName);
42538
+ if (target !== import_node_path11.default.join(root, skillName) || !target.startsWith(root + import_node_path11.default.sep)) {
42539
+ throw new Error(`Invalid skill install target for "${skillName}".`);
42540
+ }
42541
+ return target;
42542
+ };
42543
+ var parseSkillDocument = (skillMd) => {
42544
+ const fmMatch = skillMd.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
42545
+ if (!fmMatch) return null;
42546
+ const frontmatter = {};
42547
+ for (const rawLine of fmMatch[1].split(/\r?\n/)) {
42548
+ const line = rawLine.trim();
42549
+ if (!line || line.startsWith(`#`)) continue;
42550
+ const match2 = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);
42551
+ if (!match2) {
42552
+ frontmatter[`__invalid__${Object.keys(frontmatter).length}`] = line;
42553
+ continue;
42554
+ }
42555
+ frontmatter[match2[1]] = stripYamlQuotes(match2[2]);
42556
+ }
42557
+ return {
42558
+ name: frontmatter.name ?? ``,
42559
+ description: frontmatter.description ?? ``,
42560
+ body: skillMd.slice(fmMatch[0].length).trim(),
42561
+ frontmatter
42562
+ };
42563
+ };
42564
+ var validateSkillDocument = (input) => {
42565
+ const errors = [];
42566
+ const warnings = [];
42567
+ const skillMd = input.skillMd;
42568
+ if (!skillMd || !skillMd.trim()) {
42569
+ addError(errors, `empty_skill_md`, `SKILL.md content is required.`);
42570
+ return { ok: false, errors, warnings };
42571
+ }
42572
+ const parsed = parseSkillDocument(skillMd);
42573
+ if (!parsed) {
42574
+ addError(errors, `missing_frontmatter`, `SKILL.md must start with YAML frontmatter delimited by "---".`);
42575
+ return { ok: false, errors, warnings };
42576
+ }
42577
+ const invalidFrontmatterLines = Object.keys(parsed.frontmatter).filter((key) => key.startsWith(`__invalid__`));
42578
+ if (invalidFrontmatterLines.length > 0) {
42579
+ addError(errors, `invalid_frontmatter`, `Frontmatter must contain simple "key: value" lines.`);
42580
+ }
42581
+ if (!parsed.name) {
42582
+ addError(errors, `missing_name`, `Frontmatter field "name" is required.`);
42583
+ } else if (!isValidSkillName(parsed.name)) {
42584
+ addError(errors, `invalid_name`, `Skill name "${parsed.name}" must be kebab-case, under 64 characters, and path-safe.`);
42585
+ }
42586
+ if (!parsed.description) {
42587
+ addError(errors, `missing_description`, `Frontmatter field "description" is required.`);
42588
+ } else if (parsed.description.length > 500) {
42589
+ addWarning(warnings, `long_description`, `Skill description is long; keep trigger metadata concise.`);
42590
+ }
42591
+ if (input.skillName && parsed.name && input.skillName !== parsed.name) {
42592
+ addError(errors, `name_mismatch`, `Input skillName "${input.skillName}" must match frontmatter name "${parsed.name}".`);
42593
+ }
42594
+ if (input.description && parsed.description && input.description !== parsed.description) {
42595
+ addError(errors, `description_mismatch`, `Input description must match frontmatter description.`);
42596
+ }
42597
+ if (!parsed.body) {
42598
+ addError(errors, `empty_body`, `SKILL.md body is required.`);
42599
+ } else {
42600
+ if (!/(^|\n)#\s+\S/.test(parsed.body)) {
42601
+ addWarning(warnings, `missing_title`, `Skill body should start with a Markdown H1 title.`);
42602
+ }
42603
+ for (const sectionPattern of REQUIRED_SECTIONS) {
42604
+ if (!sectionPattern.test(parsed.body)) {
42605
+ addWarning(warnings, `missing_recommended_section`, `Skill body should include when-to-use and execution workflow sections.`);
42606
+ break;
42607
+ }
42608
+ }
42609
+ }
42610
+ if (input.baseDir) {
42611
+ const normalizedBase = import_node_path11.default.resolve(input.baseDir);
42612
+ for (const match2 of parsed.body.matchAll(/\]\(([^)]+)\)/g)) {
42613
+ const href = match2[1].trim();
42614
+ if (!href || /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith(`#`)) continue;
42615
+ const target = import_node_path11.default.resolve(normalizedBase, href.split(`#`)[0]);
42616
+ if (!target.startsWith(normalizedBase + import_node_path11.default.sep) && target !== normalizedBase) {
42617
+ addError(errors, `unsafe_reference`, `Relative link "${href}" escapes the skill directory.`);
42618
+ } else if (!(0, import_node_fs3.existsSync)(target)) {
42619
+ addError(errors, `missing_reference`, `Relative link "${href}" does not exist in the skill directory.`);
42620
+ }
42621
+ }
42622
+ }
42623
+ return {
42624
+ ok: errors.length === 0,
42625
+ skill: parsed,
42626
+ errors,
42627
+ warnings
42628
+ };
42629
+ };
42630
+ var mergeIssues = (target, source) => {
42631
+ target.errors.push(...source.errors);
42632
+ target.warnings.push(...source.warnings);
42633
+ };
42634
+ var validateScriptsDirectory = (skillDir, warnings) => {
42635
+ const scriptsDir = import_node_path11.default.join(skillDir, `scripts`);
42636
+ if (!(0, import_node_fs3.existsSync)(scriptsDir)) return;
42637
+ const entries = (0, import_node_fs3.readdirSync)(scriptsDir, { withFileTypes: true }).filter((entry) => entry.isFile());
42638
+ if (entries.length === 0) {
42639
+ addWarning(warnings, `empty_scripts_dir`, `scripts/ exists but contains no files.`);
42640
+ }
42641
+ };
42642
+ var validateSkillDirectory = (skillDir, options = {}) => {
42643
+ const errors = [];
42644
+ const warnings = [];
42645
+ const normalizedSkillDir = import_node_path11.default.resolve(skillDir);
42646
+ const skillMdPath = import_node_path11.default.join(normalizedSkillDir, `SKILL.md`);
42647
+ if (!(0, import_node_fs3.existsSync)(normalizedSkillDir) || !(0, import_node_fs3.statSync)(normalizedSkillDir).isDirectory()) {
42648
+ addError(errors, `missing_skill_dir`, `Skill directory does not exist: ${normalizedSkillDir}`);
42649
+ return { ok: false, errors, warnings, skillDir: normalizedSkillDir, skillMdPath };
42650
+ }
42651
+ if (!(0, import_node_fs3.existsSync)(skillMdPath) || !(0, import_node_fs3.statSync)(skillMdPath).isFile()) {
42652
+ addError(errors, `missing_skill_md`, `Skill directory must contain SKILL.md.`);
42653
+ return { ok: false, errors, warnings, skillDir: normalizedSkillDir, skillMdPath };
42654
+ }
42655
+ const raw2 = (0, import_node_fs3.readFileSync)(skillMdPath, `utf-8`);
42656
+ const documentResult = validateSkillDocument({
42657
+ skillName: options.expectedName ?? import_node_path11.default.basename(normalizedSkillDir),
42658
+ skillMd: raw2,
42659
+ baseDir: normalizedSkillDir
42660
+ });
42661
+ mergeIssues({ errors, warnings }, documentResult);
42662
+ validateScriptsDirectory(normalizedSkillDir, warnings);
42663
+ return {
42664
+ ok: errors.length === 0,
42665
+ skill: documentResult.skill,
42666
+ errors,
42667
+ warnings,
42668
+ skillDir: normalizedSkillDir,
42669
+ skillMdPath
42670
+ };
42671
+ };
42672
+ var smokeTestSkillDirectory = (skillDir, options = {}) => {
42673
+ const directoryResult = validateSkillDirectory(skillDir, options);
42674
+ const errors = [...directoryResult.errors];
42675
+ const warnings = [...directoryResult.warnings];
42676
+ let detail;
42677
+ if (directoryResult.ok && directoryResult.skill) {
42678
+ detail = `Base directory for this skill: ${directoryResult.skillDir}
42679
+
42680
+ ${directoryResult.skill.body}`;
42681
+ if (!detail.includes(directoryResult.skillDir)) {
42682
+ addError(errors, `smoke_missing_base_dir`, `Skill detail does not include its base directory.`);
42683
+ }
42684
+ if (!detail.includes(directoryResult.skill.body)) {
42685
+ addError(errors, `smoke_missing_body`, `Skill detail does not include the SKILL.md body.`);
42686
+ }
42687
+ if (detail.length < 80) {
42688
+ addWarning(warnings, `smoke_short_detail`, `Skill detail is unusually short.`);
42689
+ }
42690
+ }
42691
+ return {
42692
+ ...directoryResult,
42693
+ ok: errors.length === 0,
42694
+ errors,
42695
+ warnings,
42696
+ detail
42697
+ };
42698
+ };
42699
+ var formatSkillValidationIssues = (result) => {
42700
+ const lines = [
42701
+ ...result.errors.map((issue) => `- [${issue.code}] ${issue.message}`),
42702
+ ...result.warnings.map((issue) => `- [warning:${issue.code}] ${issue.message}`)
42703
+ ];
42704
+ return lines.join(`
42705
+ `);
42706
+ };
42707
+
42708
+ // src/department/learning.ts
42709
+ var ensureDir = (dir) => (0, import_node_fs4.mkdirSync)(dir, { recursive: true });
42440
42710
  var readJsonArray = (filePath) => {
42441
- if (!(0, import_node_fs3.existsSync)(filePath)) return [];
42442
- return JSON.parse((0, import_node_fs3.readFileSync)(filePath, "utf-8"));
42711
+ if (!(0, import_node_fs4.existsSync)(filePath)) return [];
42712
+ return JSON.parse((0, import_node_fs4.readFileSync)(filePath, "utf-8"));
42443
42713
  };
42444
42714
  var writeJsonArray = (filePath, records) => {
42445
- ensureDir(import_node_path11.default.dirname(filePath));
42446
- (0, import_node_fs3.writeFileSync)(filePath, JSON.stringify(records, null, " "), "utf-8");
42715
+ ensureDir(import_node_path12.default.dirname(filePath));
42716
+ (0, import_node_fs4.writeFileSync)(filePath, JSON.stringify(records, null, " "), "utf-8");
42447
42717
  };
42448
42718
  var departmentMemoryPath = (departmentName) => {
42449
- return import_node_path11.default.join(getDepartmentWorkSpaceDir(departmentName), "department-memory.json");
42719
+ return import_node_path12.default.join(getDepartmentWorkSpaceDir(departmentName), "department-memory.json");
42450
42720
  };
42451
42721
  var departmentSkillPath = (departmentName) => {
42452
- return import_node_path11.default.join(getDepartmentWorkSpaceDir(departmentName), "department-skills.json");
42722
+ return import_node_path12.default.join(getDepartmentWorkSpaceDir(departmentName), "department-skills.json");
42453
42723
  };
42454
42724
  var departmentSkillDir = (departmentName, skillName) => {
42455
- return import_node_path11.default.join(getDepartmentWorkSpaceDir(departmentName), "skills", skillName);
42725
+ return assertSafeSkillTarget(import_node_path12.default.join(getDepartmentWorkSpaceDir(departmentName), "skills"), skillName);
42456
42726
  };
42457
42727
  var proposalsPath = () => {
42458
- return import_node_path11.default.join(getDepartmentBaseDir(), "department-proposals.json");
42728
+ return import_node_path12.default.join(getDepartmentBaseDir(), "department-proposals.json");
42459
42729
  };
42460
42730
  var getDepartmentNameForHead = (request) => {
42461
42731
  const mailboxId = request?.departmentAgentId;
@@ -42507,6 +42777,15 @@ var listDepartmentSkills = (departmentName) => {
42507
42777
  return readJsonArray(departmentSkillPath(departmentName)).sort((a, b) => b.updatedAt - a.updatedAt);
42508
42778
  };
42509
42779
  var proposeDepartmentSkill = (departmentName, input) => {
42780
+ const validation = validateSkillDocument({
42781
+ skillName: input.skillName,
42782
+ description: input.description,
42783
+ skillMd: input.skillMd
42784
+ });
42785
+ if (!validation.ok) {
42786
+ throw new Error(`[departmentSkill] Skill \u8349\u7A3F\u6821\u9A8C\u5931\u8D25\uFF1A
42787
+ ${formatSkillValidationIssues(validation)}`);
42788
+ }
42510
42789
  const records = listDepartmentSkills(departmentName);
42511
42790
  if (records.some((record) => record.skillName === input.skillName && record.status !== "dropped")) {
42512
42791
  return null;
@@ -42533,8 +42812,23 @@ var keepDepartmentSkill = (departmentName, id) => {
42533
42812
  if (idx < 0) return null;
42534
42813
  records[idx] = { ...records[idx], status: "active", updatedAt: Date.now() };
42535
42814
  const skillDir = departmentSkillDir(departmentName, records[idx].skillName);
42815
+ const validation = validateSkillDocument({
42816
+ skillName: records[idx].skillName,
42817
+ description: records[idx].description,
42818
+ skillMd: records[idx].skillMd,
42819
+ baseDir: skillDir
42820
+ });
42821
+ if (!validation.ok) {
42822
+ throw new Error(`[departmentSkill] Skill \u8349\u7A3F\u6821\u9A8C\u5931\u8D25\uFF0C\u62D2\u7EDD\u4FDD\u7559\uFF1A
42823
+ ${formatSkillValidationIssues(validation)}`);
42824
+ }
42536
42825
  ensureDir(skillDir);
42537
- (0, import_node_fs3.writeFileSync)(import_node_path11.default.join(skillDir, "SKILL.md"), records[idx].skillMd, "utf-8");
42826
+ (0, import_node_fs4.writeFileSync)(import_node_path12.default.join(skillDir, "SKILL.md"), records[idx].skillMd, "utf-8");
42827
+ const smokeTest = smokeTestSkillDirectory(skillDir, { expectedName: records[idx].skillName });
42828
+ if (!smokeTest.ok) {
42829
+ throw new Error(`[departmentSkill] Skill smoke test \u5931\u8D25\uFF1A
42830
+ ${formatSkillValidationIssues(smokeTest)}`);
42831
+ }
42538
42832
  writeJsonArray(departmentSkillPath(departmentName), records);
42539
42833
  return records[idx];
42540
42834
  };
@@ -42695,14 +42989,18 @@ var departmentSkillPropose = {
42695
42989
  async execute(input, userRequest) {
42696
42990
  const departmentName = requireDepartmentHead(userRequest);
42697
42991
  if (!departmentName) return `[departmentSkillPropose] \u53EA\u6709 Department Head \u53EF\u4EE5\u63D0\u4EA4\u90E8\u95E8 Skill \u8349\u7A3F`;
42698
- const skill = proposeDepartmentSkill(departmentName, {
42699
- skillName: input.skillName,
42700
- description: input.description,
42701
- skillMd: input.skillMd,
42702
- createdByMailboxId: userRequest?.departmentAgentId
42703
- });
42704
- if (!skill) return `[departmentSkillPropose] \u540C\u540D\u90E8\u95E8 Skill \u5DF2\u5B58\u5728\u6216\u5F85\u786E\u8BA4: ${input.skillName}`;
42705
- return `[departmentSkillPropose] \u5DF2\u63D0\u4EA4\u90E8\u95E8 Skill \u8349\u7A3F: ${JSON.stringify(skill)}`;
42992
+ try {
42993
+ const skill = proposeDepartmentSkill(departmentName, {
42994
+ skillName: input.skillName,
42995
+ description: input.description,
42996
+ skillMd: input.skillMd,
42997
+ createdByMailboxId: userRequest?.departmentAgentId
42998
+ });
42999
+ if (!skill) return `[departmentSkillPropose] \u540C\u540D\u90E8\u95E8 Skill \u5DF2\u5B58\u5728\u6216\u5F85\u786E\u8BA4: ${input.skillName}`;
43000
+ return `[departmentSkillPropose] \u5DF2\u63D0\u4EA4\u90E8\u95E8 Skill \u8349\u7A3F: ${JSON.stringify(skill)}`;
43001
+ } catch (err) {
43002
+ return `[departmentSkillPropose] ${err.message}`;
43003
+ }
42706
43004
  }
42707
43005
  };
42708
43006
  var departmentSkillKeep = {
@@ -42718,9 +43016,13 @@ var departmentSkillKeep = {
42718
43016
  async execute(input, userRequest) {
42719
43017
  const departmentName = requireDepartmentHead(userRequest);
42720
43018
  if (!departmentName) return `[departmentSkillKeep] \u53EA\u6709 Department Head \u53EF\u4EE5\u4FDD\u7559\u90E8\u95E8 Skill`;
42721
- const skill = keepDepartmentSkill(departmentName, input.id);
42722
- if (!skill) return `[departmentSkillKeep] \u672A\u627E\u5230\u90E8\u95E8 Skill: ${input.id}`;
42723
- return `[departmentSkillKeep] \u5DF2\u4FDD\u7559\u90E8\u95E8 Skill: ${JSON.stringify(skill)}`;
43019
+ try {
43020
+ const skill = keepDepartmentSkill(departmentName, input.id);
43021
+ if (!skill) return `[departmentSkillKeep] \u672A\u627E\u5230\u90E8\u95E8 Skill: ${input.id}`;
43022
+ return `[departmentSkillKeep] \u5DF2\u4FDD\u7559\u90E8\u95E8 Skill: ${JSON.stringify(skill)}`;
43023
+ } catch (err) {
43024
+ return `[departmentSkillKeep] ${err.message}`;
43025
+ }
42724
43026
  }
42725
43027
  };
42726
43028
  var departmentSkillDrop = {
@@ -42873,7 +43175,8 @@ var mailboxFollowup = {
42873
43175
 
42874
43176
  // src/tools/tools/Bash.ts
42875
43177
  var import_node_child_process = require("node:child_process");
42876
- var import_node_fs4 = require("node:fs");
43178
+ var import_node_crypto7 = require("node:crypto");
43179
+ var import_node_fs5 = require("node:fs");
42877
43180
  var DESCRIPTION29 = `\u5728\u7CFB\u7EDF shell \u4E2D\u6267\u884C\u547D\u4EE4\u3002
42878
43181
 
42879
43182
  \u7528\u9014\uFF1A
@@ -42888,21 +43191,28 @@ var DESCRIPTION29 = `\u5728\u7CFB\u7EDF shell \u4E2D\u6267\u884C\u547D\u4EE4\u30
42888
43191
  - Bash \u53EF\u4EE5\u7528\u6765\u8FD0\u884C\u6D4B\u8BD5\u3001\u683C\u5F0F\u5316\u3001\u8BAD\u7EC3\u3001\u63A8\u7406\u3001\u67E5\u770B\u76EE\u5F55\u3001\u6267\u884C\u5DF2\u7ECF\u5199\u597D\u7684\u811A\u672C\u3002
42889
43192
 
42890
43193
  \u53C2\u6570\uFF1A
43194
+ - action: \u64CD\u4F5C\u7C7B\u578B\uFF08\u53EF\u9009\uFF0Crun/check/write/stop\uFF0C\u9ED8\u8BA4 run\uFF09
42891
43195
  - command: \u8981\u6267\u884C\u7684 shell \u547D\u4EE4
42892
43196
  - cwd: \u547D\u4EE4\u6267\u884C\u7684\u5DE5\u4F5C\u76EE\u5F55\uFF08\u53EF\u9009\uFF0C\u9ED8\u8BA4\u4E3A\u5F53\u524D\u76EE\u5F55\uFF09
42893
- - timeout: \u8D85\u65F6\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF0C\u53EF\u9009\uFF0C\u9ED8\u8BA4 30000ms\uFF09
43197
+ - timeout: \u7B49\u5F85\u547D\u4EE4\u5B8C\u6210\u7684\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF0C\u53EF\u9009\uFF0C\u9ED8\u8BA4 30000ms\uFF09\u3002\u8D85\u8FC7\u540E\u547D\u4EE4\u7EE7\u7EED\u5728\u540E\u53F0\u8FD0\u884C\uFF0C\u5E76\u8FD4\u56DE session_id
43198
+ - session_id: \u540E\u53F0\u8FD0\u884C\u4E2D\u7684 Bash \u4F1A\u8BDD ID\uFF08check/write/stop \u65F6\u4F7F\u7528\uFF09
43199
+ - input: \u5199\u5165\u540E\u53F0\u4F1A\u8BDD stdin \u7684\u5185\u5BB9\uFF08write \u65F6\u4F7F\u7528\uFF09
42894
43200
 
42895
43201
  \u6CE8\u610F\u4E8B\u9879\uFF1A
42896
43202
  - \u4E0D\u8981\u6267\u884C\u7834\u574F\u6027\u547D\u4EE4\uFF08\u5982 rm -rf /\uFF09
42897
- - \u957F\u65F6\u95F4\u8FD0\u884C\u7684\u547D\u4EE4\uFF08\u5982\u542F\u52A8\u670D\u52A1\u5668\uFF09\u4F1A\u5728\u8D85\u65F6\u540E\u88AB\u7EC8\u6B62
43203
+ - \u957F\u65F6\u95F4\u8FD0\u884C\u7684\u547D\u4EE4\uFF08\u5982\u542F\u52A8\u670D\u52A1\u5668\uFF09\u8D85\u8FC7\u7B49\u5F85\u65F6\u95F4\u540E\u4F1A\u4FDD\u7559\u4F1A\u8BDD\uFF0C\u53EF\u7528 session_id \u67E5\u8BE2\u589E\u91CF\u8F93\u51FA
42898
43204
  - \u5982\u679C\u4F60\u5904\u4E8E\u90E8\u95E8\u5DE5\u4F5C\u533A\u6A21\u5F0F\uFF0Ccwd \u5FC5\u987B\u5728\u5DE5\u4F5C\u533A\u8303\u56F4\u5185
42899
43205
  `;
42900
43206
  var MAX_OUTPUT_LENGTH = 1e4;
43207
+ var MAX_SESSION_OUTPUT_LENGTH = 5e4;
43208
+ var DEFAULT_TIMEOUT_MS = 3e4;
43209
+ var DEFAULT_SESSION_TTL_MS = 30 * 60 * 1e3;
42901
43210
  var SHELL_CANDIDATES2 = ["/bin/sh", "/usr/bin/sh", "/bin/bash"];
43211
+ var sessions = /* @__PURE__ */ new Map();
42902
43212
  function findExecutableShell2() {
42903
43213
  for (const shell of SHELL_CANDIDATES2) {
42904
43214
  try {
42905
- (0, import_node_fs4.accessSync)(shell, import_node_fs4.constants.X_OK);
43215
+ (0, import_node_fs5.accessSync)(shell, import_node_fs5.constants.X_OK);
42906
43216
  return shell;
42907
43217
  } catch {
42908
43218
  }
@@ -42911,11 +43221,11 @@ function findExecutableShell2() {
42911
43221
  }
42912
43222
  function validateCwd(cwd) {
42913
43223
  try {
42914
- const stat10 = (0, import_node_fs4.statSync)(cwd);
43224
+ const stat10 = (0, import_node_fs5.statSync)(cwd);
42915
43225
  if (!stat10.isDirectory()) {
42916
43226
  return `[bash] \u9519\u8BEF: cwd \u4E0D\u662F\u76EE\u5F55: ${cwd}`;
42917
43227
  }
42918
- (0, import_node_fs4.accessSync)(cwd, import_node_fs4.constants.R_OK | import_node_fs4.constants.X_OK);
43228
+ (0, import_node_fs5.accessSync)(cwd, import_node_fs5.constants.R_OK | import_node_fs5.constants.X_OK);
42919
43229
  return null;
42920
43230
  } catch (err) {
42921
43231
  const code = err.code;
@@ -42928,12 +43238,70 @@ function validateCwd(cwd) {
42928
43238
  return `[bash] \u9519\u8BEF: cwd \u4E0D\u53EF\u7528: ${cwd} (${err.message})`;
42929
43239
  }
42930
43240
  }
43241
+ function truncateOutput(output, limit = MAX_OUTPUT_LENGTH) {
43242
+ if (output.length <= limit) return output;
43243
+ return output.slice(0, limit) + `
43244
+ ... (\u8F93\u51FA\u622A\u65AD\uFF0C\u5171 ${output.length} \u5B57\u7B26)`;
43245
+ }
43246
+ function appendSessionOutput(session, chunk, source) {
43247
+ const text2 = chunk.toString();
43248
+ session.output += source === "stderr" ? `[stderr]
43249
+ ${text2}` : text2;
43250
+ if (session.output.length > MAX_SESSION_OUTPUT_LENGTH) {
43251
+ const removed = session.output.length - MAX_SESSION_OUTPUT_LENGTH;
43252
+ session.output = session.output.slice(removed);
43253
+ session.readOffset = Math.max(0, session.readOffset - removed);
43254
+ }
43255
+ }
43256
+ function finishSession(session, status, exitCode, signal) {
43257
+ if (session.status !== "running") return;
43258
+ session.status = status;
43259
+ session.exitCode = exitCode;
43260
+ session.signal = signal;
43261
+ session.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
43262
+ if (status === "failed") {
43263
+ const prefix = session.output ? "\n" : "";
43264
+ session.output += `${prefix}[bash] \u547D\u4EE4\u9000\u51FA\u7801: ${exitCode ?? "unknown"}${signal ? `, signal: ${signal}` : ""}`;
43265
+ }
43266
+ }
43267
+ function renderSessionDelta(session, prefix) {
43268
+ const delta = session.output.slice(session.readOffset);
43269
+ session.readOffset = session.output.length;
43270
+ const body = delta ? truncateOutput(delta) : "[bash] \u6682\u65E0\u65B0\u8F93\u51FA";
43271
+ const state = session.status === "running" ? `\u4ECD\u5728\u8FD0\u884C` : `\u5DF2\u7ED3\u675F\uFF08status=${session.status}${session.exitCode === void 0 ? "" : `, exitCode=${session.exitCode}`}\uFF09`;
43272
+ return `${prefix}
43273
+ [bash] session_id=${session.id} ${state}
43274
+ ${body}`;
43275
+ }
43276
+ function waitForClose(session, waitMs) {
43277
+ if (session.status !== "running") return Promise.resolve("closed");
43278
+ return new Promise((resolve11) => {
43279
+ const timer = setTimeout(() => {
43280
+ cleanup();
43281
+ resolve11("timeout");
43282
+ }, waitMs);
43283
+ const onClose = () => {
43284
+ cleanup();
43285
+ resolve11("closed");
43286
+ };
43287
+ const cleanup = () => {
43288
+ clearTimeout(timer);
43289
+ session.child.off("close", onClose);
43290
+ };
43291
+ session.child.once("close", onClose);
43292
+ });
43293
+ }
42931
43294
  var bashTool = {
42932
43295
  name: `bash`,
42933
43296
  description: DESCRIPTION29,
42934
43297
  input_schema: {
42935
43298
  type: `object`,
42936
43299
  properties: {
43300
+ action: {
43301
+ type: `string`,
43302
+ enum: [`run`, `check`, `write`, `stop`],
43303
+ description: `\u64CD\u4F5C\u7C7B\u578B\uFF1Arun \u6267\u884C\u547D\u4EE4\uFF1Bcheck \u8BFB\u53D6\u540E\u53F0\u4F1A\u8BDD\u589E\u91CF\u8F93\u51FA\uFF1Bwrite \u5411\u540E\u53F0\u4F1A\u8BDD stdin \u5199\u5165\u5185\u5BB9\uFF1Bstop \u505C\u6B62\u540E\u53F0\u4F1A\u8BDD\u3002\u9ED8\u8BA4 run`
43304
+ },
42937
43305
  command: {
42938
43306
  type: `string`,
42939
43307
  description: `\u8981\u6267\u884C\u7684 shell \u547D\u4EE4`
@@ -42944,15 +43312,50 @@ var bashTool = {
42944
43312
  },
42945
43313
  timeout: {
42946
43314
  type: `number`,
42947
- description: `\u8D85\u65F6\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09\uFF0C\u9ED8\u8BA4 30000`
43315
+ description: `run \u65F6\u7B49\u5F85\u547D\u4EE4\u5B8C\u6210\u7684\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09\uFF0C\u9ED8\u8BA4 30000\u3002\u8D85\u8FC7\u540E\u8FD4\u56DE session_id\uFF0C\u547D\u4EE4\u7EE7\u7EED\u8FD0\u884C`
43316
+ },
43317
+ session_id: {
43318
+ type: `string`,
43319
+ description: `\u540E\u53F0 Bash \u4F1A\u8BDD ID\uFF0C\u7528\u4E8E check/write/stop`
43320
+ },
43321
+ input: {
43322
+ type: `string`,
43323
+ description: `write \u65F6\u5199\u5165 stdin \u7684\u5185\u5BB9`
42948
43324
  }
42949
43325
  },
42950
- required: [`command`]
43326
+ required: []
42951
43327
  },
42952
43328
  async execute(input, userRequest) {
43329
+ const action = input.action || "run";
43330
+ const sessionId = input.session_id;
43331
+ if (action === "check" || action === "write" || action === "stop") {
43332
+ if (!sessionId) return `[bash] \u9519\u8BEF: ${action} \u9700\u8981 session_id`;
43333
+ const session = sessions.get(sessionId);
43334
+ if (!session) return `[bash] \u9519\u8BEF: \u672A\u627E\u5230 session_id: ${sessionId}`;
43335
+ if (action === "write") {
43336
+ if (session.status !== "running") {
43337
+ return renderSessionDelta(session, `[bash] session ${session.id} \u5DF2\u4E0D\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u5199\u5165 stdin`);
43338
+ }
43339
+ const stdin = input.input;
43340
+ if (stdin === void 0) return `[bash] \u9519\u8BEF: write \u9700\u8981 input`;
43341
+ session.child.stdin.write(stdin);
43342
+ return renderSessionDelta(session, `[bash] \u5DF2\u5199\u5165 session ${session.id} stdin`);
43343
+ }
43344
+ if (action === "stop") {
43345
+ if (session.status === "running") {
43346
+ session.child.kill("SIGTERM");
43347
+ finishSession(session, "stopped", null, "SIGTERM");
43348
+ }
43349
+ return renderSessionDelta(session, `[bash] \u5DF2\u505C\u6B62 session ${session.id}`);
43350
+ }
43351
+ return renderSessionDelta(session, `[bash] \u5DF2\u68C0\u67E5 session ${session.id}`);
43352
+ }
43353
+ if (action !== "run") {
43354
+ return `[bash] \u9519\u8BEF: \u4E0D\u652F\u6301\u7684 action: ${action}`;
43355
+ }
42953
43356
  const command = input.command;
42954
43357
  const explicitCwd = input.cwd || void 0;
42955
- const timeout = input.timeout || 3e4;
43358
+ const timeout = input.timeout || DEFAULT_TIMEOUT_MS;
42956
43359
  if (!command || command.trim() === "") {
42957
43360
  return `[bash] \u9519\u8BEF: command \u4E0D\u80FD\u4E3A\u7A7A`;
42958
43361
  }
@@ -42967,41 +43370,56 @@ var bashTool = {
42967
43370
  if (!shell) {
42968
43371
  return `[bash] \u9519\u8BEF: \u6267\u884C\u73AF\u5883\u7F3A\u5C11\u53EF\u7528 shell\uFF08\u5DF2\u68C0\u67E5 ${SHELL_CANDIDATES2.join(", ")}\uFF09\u3002\u8BF7\u5148\u68C0\u67E5\u5BB9\u5668\u955C\u50CF/rootfs/\u6302\u8F7D\u662F\u5426\u521D\u59CB\u5316\u5B8C\u6210\u3002`;
42969
43372
  }
42970
- return new Promise((resolve11) => {
43373
+ return new Promise(async (resolve11) => {
42971
43374
  const options = {
42972
- timeout,
42973
- maxBuffer: 1024 * 1024,
42974
- // 1MB
42975
- env: { ...process.env, PAGER: "cat" },
42976
- shell
43375
+ env: { ...process.env, PAGER: "cat" }
42977
43376
  };
42978
43377
  if (cwd) options.cwd = cwd;
42979
- (0, import_node_child_process.exec)(command, options, (error, stdout, stderr) => {
42980
- let output = "";
42981
- if (stdout) {
42982
- const trimmed = stdout.length > MAX_OUTPUT_LENGTH ? stdout.slice(0, MAX_OUTPUT_LENGTH) + `
42983
- ... (\u8F93\u51FA\u622A\u65AD\uFF0C\u5171 ${stdout.length} \u5B57\u7B26)` : stdout;
42984
- output += trimmed;
42985
- }
42986
- if (stderr) {
42987
- const trimmed = stderr.length > MAX_OUTPUT_LENGTH ? stderr.slice(0, MAX_OUTPUT_LENGTH) + `
42988
- ... (stderr \u622A\u65AD\uFF0C\u5171 ${stderr.length} \u5B57\u7B26)` : stderr;
42989
- output += (output ? "\n" : "") + `[stderr]
42990
- ${trimmed}`;
42991
- }
42992
- if (error) {
42993
- if (error.killed) {
42994
- output += `
42995
- [bash] \u547D\u4EE4\u8D85\u65F6\uFF08${timeout}ms\uFF09\uFF0C\u5DF2\u7EC8\u6B62`;
42996
- } else if (!stderr) {
42997
- output += (output ? "\n" : "") + `[bash] \u9519\u8BEF: ${error.message}`;
42998
- }
42999
- }
43000
- if (!output) {
43001
- output = "[bash] \u547D\u4EE4\u6267\u884C\u6210\u529F\uFF08\u65E0\u8F93\u51FA\uFF09";
43002
- }
43003
- resolve11(output);
43378
+ const child = (0, import_node_child_process.spawn)(shell, ["-c", command], {
43379
+ ...options,
43380
+ stdio: ["pipe", "pipe", "pipe"]
43381
+ });
43382
+ const id = (0, import_node_crypto7.randomUUID)().slice(0, 8);
43383
+ const session = {
43384
+ id,
43385
+ command,
43386
+ child,
43387
+ output: "",
43388
+ readOffset: 0,
43389
+ status: "running",
43390
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
43391
+ cleanupTimer: setTimeout(() => {
43392
+ const current = sessions.get(id);
43393
+ if (!current) return;
43394
+ if (current.status === "running") {
43395
+ current.child.kill("SIGTERM");
43396
+ finishSession(current, "stopped", null, "SIGTERM");
43397
+ }
43398
+ sessions.delete(id);
43399
+ }, DEFAULT_SESSION_TTL_MS)
43400
+ };
43401
+ sessions.set(id, session);
43402
+ child.stdout.on("data", (chunk) => appendSessionOutput(session, chunk, "stdout"));
43403
+ child.stderr.on("data", (chunk) => appendSessionOutput(session, chunk, "stderr"));
43404
+ child.on("error", (err) => {
43405
+ session.output += `[bash] \u9519\u8BEF: ${err.message}`;
43406
+ finishSession(session, "failed");
43407
+ });
43408
+ child.on("close", (code, signal) => {
43409
+ finishSession(session, code === 0 ? "completed" : "failed", code, signal);
43004
43410
  });
43411
+ const waitResult = await waitForClose(session, Math.max(0, timeout));
43412
+ if (waitResult === "timeout" && session.status === "running") {
43413
+ resolve11(renderSessionDelta(session, `[bash] \u547D\u4EE4\u4ECD\u5728\u8FD0\u884C\uFF0C\u5DF2\u4FDD\u7559\u540E\u53F0\u4F1A\u8BDD\u3002\u540E\u7EED\u4F7F\u7528 action=check \u548C session_id=${session.id} \u8BFB\u53D6\u8FDB\u5C55\uFF1B\u4F7F\u7528 action=stop \u53EF\u505C\u6B62\u3002`));
43414
+ return;
43415
+ }
43416
+ clearTimeout(session.cleanupTimer);
43417
+ sessions.delete(id);
43418
+ let output = session.output;
43419
+ if (!output) {
43420
+ output = session.status === "completed" ? "[bash] \u547D\u4EE4\u6267\u884C\u6210\u529F\uFF08\u65E0\u8F93\u51FA\uFF09" : "[bash] \u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF08\u65E0\u8F93\u51FA\uFF09";
43421
+ }
43422
+ resolve11(truncateOutput(output));
43005
43423
  });
43006
43424
  }
43007
43425
  };
@@ -43572,10 +43990,10 @@ var readDreamHistoryLimit = () => {
43572
43990
  };
43573
43991
 
43574
43992
  // src/skillForge/SkillForgeEngine.ts
43575
- var import_node_fs5 = require("node:fs");
43993
+ var import_node_fs6 = require("node:fs");
43576
43994
  var import_node_os2 = require("node:os");
43577
- var import_node_path12 = require("node:path");
43578
- var import_node_crypto7 = require("node:crypto");
43995
+ var import_node_path13 = require("node:path");
43996
+ var import_node_crypto8 = require("node:crypto");
43579
43997
  var SkillForgeEngine = class {
43580
43998
  proposalStorage;
43581
43999
  draftRoot;
@@ -43583,8 +44001,8 @@ var SkillForgeEngine = class {
43583
44001
  constructor(deps) {
43584
44002
  this.proposalStorage = deps.proposalStorage;
43585
44003
  const opt = deps.options ?? {};
43586
- this.draftRoot = opt.draftRoot ?? (0, import_node_path12.join)((0, import_node_os2.homedir)(), ".duclaw", "skill-proposals");
43587
- this.skillsInstallDir = opt.skillsInstallDir ?? (0, import_node_path12.join)((0, import_node_os2.homedir)(), ".agents", "skills");
44004
+ this.draftRoot = opt.draftRoot ?? (0, import_node_path13.join)((0, import_node_os2.homedir)(), ".duclaw", "skill-proposals");
44005
+ this.skillsInstallDir = opt.skillsInstallDir ?? (0, import_node_path13.join)((0, import_node_os2.homedir)(), ".agents", "skills");
43588
44006
  }
43589
44007
  // ---------- 公开方法 ----------
43590
44008
  /**
@@ -43596,6 +44014,11 @@ var SkillForgeEngine = class {
43596
44014
  if (!skillName || !description || !skillMd) {
43597
44015
  throw new Error(`[skillForge] propose \u53C2\u6570\u4E0D\u5B8C\u6574\uFF1AskillName/description/skillMd \u5747\u5FC5\u586B`);
43598
44016
  }
44017
+ const validation = validateSkillDocument({ skillName, description, skillMd });
44018
+ if (!validation.ok) {
44019
+ throw new Error(`[skillForge] Skill \u8349\u7A3F\u6821\u9A8C\u5931\u8D25\uFF1A
44020
+ ${formatSkillValidationIssues(validation)}`);
44021
+ }
43599
44022
  const existingSkills = SkillRegistry_default();
43600
44023
  if (existingSkills.some((s) => s.name === skillName)) {
43601
44024
  return null;
@@ -43604,10 +44027,19 @@ var SkillForgeEngine = class {
43604
44027
  if (pending.some((p) => p.skillName === skillName)) {
43605
44028
  return null;
43606
44029
  }
43607
- const id = (0, import_node_crypto7.randomBytes)(4).toString("hex");
43608
- const draftDir = (0, import_node_path12.join)(this.draftRoot, userId, id);
43609
- (0, import_node_fs5.mkdirSync)(draftDir, { recursive: true });
43610
- (0, import_node_fs5.writeFileSync)((0, import_node_path12.join)(draftDir, "SKILL.md"), skillMd, "utf-8");
44030
+ const id = (0, import_node_crypto8.randomBytes)(4).toString("hex");
44031
+ const draftDir = (0, import_node_path13.join)(this.draftRoot, userId, id);
44032
+ (0, import_node_fs6.mkdirSync)(draftDir, { recursive: true });
44033
+ (0, import_node_fs6.writeFileSync)((0, import_node_path13.join)(draftDir, "SKILL.md"), skillMd, "utf-8");
44034
+ const directoryValidation = validateSkillDirectory(draftDir, { expectedName: skillName });
44035
+ if (!directoryValidation.ok) {
44036
+ try {
44037
+ (0, import_node_fs6.rmSync)(draftDir, { recursive: true, force: true });
44038
+ } catch {
44039
+ }
44040
+ throw new Error(`[skillForge] Skill \u76EE\u5F55\u6821\u9A8C\u5931\u8D25\uFF1A
44041
+ ${formatSkillValidationIssues(directoryValidation)}`);
44042
+ }
43611
44043
  const proposal = {
43612
44044
  id,
43613
44045
  userId,
@@ -43625,17 +44057,38 @@ var SkillForgeEngine = class {
43625
44057
  const list = await this.proposalStorage.get(this.proposalKey(userId)) ?? [];
43626
44058
  const proposal = list.find((p) => p.id === proposalId);
43627
44059
  if (!proposal) return null;
43628
- const target = (0, import_node_path12.join)(this.skillsInstallDir, proposal.skillName);
43629
- if ((0, import_node_fs5.existsSync)(target)) {
44060
+ const validation = validateSkillDocument({
44061
+ skillName: proposal.skillName,
44062
+ description: proposal.description,
44063
+ skillMd: proposal.skillMd,
44064
+ baseDir: proposal.draftDir
44065
+ });
44066
+ if (!validation.ok) {
44067
+ throw new Error(`[skillForge] Skill \u8349\u7A3F\u6821\u9A8C\u5931\u8D25\uFF0C\u62D2\u7EDD\u843D\u5730\uFF1A
44068
+ ${formatSkillValidationIssues(validation)}`);
44069
+ }
44070
+ const target = assertSafeSkillTarget(this.skillsInstallDir, proposal.skillName);
44071
+ let installedTarget = target;
44072
+ if ((0, import_node_fs6.existsSync)(target)) {
43630
44073
  const alt = target + "-" + proposalId;
43631
- (0, import_node_fs5.mkdirSync)(alt, { recursive: true });
43632
- (0, import_node_fs5.cpSync)(proposal.draftDir, alt, { recursive: true });
44074
+ (0, import_node_fs6.mkdirSync)(alt, { recursive: true });
44075
+ (0, import_node_fs6.cpSync)(proposal.draftDir, alt, { recursive: true });
44076
+ installedTarget = alt;
43633
44077
  } else {
43634
- (0, import_node_fs5.mkdirSync)(target, { recursive: true });
43635
- (0, import_node_fs5.cpSync)(proposal.draftDir, target, { recursive: true });
44078
+ (0, import_node_fs6.mkdirSync)(target, { recursive: true });
44079
+ (0, import_node_fs6.cpSync)(proposal.draftDir, target, { recursive: true });
44080
+ }
44081
+ const smokeTest = smokeTestSkillDirectory(installedTarget, { expectedName: proposal.skillName });
44082
+ if (!smokeTest.ok) {
44083
+ try {
44084
+ (0, import_node_fs6.rmSync)(installedTarget, { recursive: true, force: true });
44085
+ } catch {
44086
+ }
44087
+ throw new Error(`[skillForge] Skill smoke test \u5931\u8D25\uFF0C\u5DF2\u56DE\u6EDA\u843D\u5730\u76EE\u5F55\uFF1A
44088
+ ${formatSkillValidationIssues(smokeTest)}`);
43636
44089
  }
43637
44090
  try {
43638
- (0, import_node_fs5.rmSync)(proposal.draftDir, { recursive: true, force: true });
44091
+ (0, import_node_fs6.rmSync)(proposal.draftDir, { recursive: true, force: true });
43639
44092
  } catch {
43640
44093
  }
43641
44094
  await this.removeProposal(userId, proposalId);
@@ -43647,7 +44100,7 @@ var SkillForgeEngine = class {
43647
44100
  const proposal = list.find((p) => p.id === proposalId);
43648
44101
  if (!proposal) return null;
43649
44102
  try {
43650
- (0, import_node_fs5.rmSync)(proposal.draftDir, { recursive: true, force: true });
44103
+ (0, import_node_fs6.rmSync)(proposal.draftDir, { recursive: true, force: true });
43651
44104
  } catch {
43652
44105
  }
43653
44106
  await this.removeProposal(userId, proposalId);
@@ -43796,9 +44249,13 @@ var skillForgeKeep = (engine) => ({
43796
44249
  return `\u672A\u80FD\u5B9A\u4F4D\u5230\u5177\u4F53\u7684\u8349\u7A3F\uFF0C\u8BF7\u8BA9\u7528\u6237\u8865\u5145\u8349\u7A3F\u540D\u79F0\u6216 id\u3002\u5F53\u524D pending \u5217\u8868\uFF1A
43797
44250
  ` + pending.map((p) => `- ${p.id} ${p.skillName}`).join("\n");
43798
44251
  }
43799
- const approved = await engine.approve(userId, target.id);
43800
- if (!approved) return `\u4FDD\u7559\u5931\u8D25\uFF1A\u8349\u7A3F ${target.id} \u5DF2\u88AB\u5904\u7406\u6216\u4E0D\u5B58\u5728\u3002`;
43801
- return `\u2705 \u5DF2\u4FDD\u7559\u6280\u80FD\u300C${approved.skillName}\u300D\u5230 ~/.agents/skills/\uFF0C\u4E0B\u6B21\u7C7B\u4F3C\u4EFB\u52A1\u5C06\u81EA\u52A8\u590D\u7528\u3002`;
44252
+ try {
44253
+ const approved = await engine.approve(userId, target.id);
44254
+ if (!approved) return `\u4FDD\u7559\u5931\u8D25\uFF1A\u8349\u7A3F ${target.id} \u5DF2\u88AB\u5904\u7406\u6216\u4E0D\u5B58\u5728\u3002`;
44255
+ return `\u2705 \u5DF2\u4FDD\u7559\u6280\u80FD\u300C${approved.skillName}\u300D\u5230 ~/.agents/skills/\uFF0C\u4E0B\u6B21\u7C7B\u4F3C\u4EFB\u52A1\u5C06\u81EA\u52A8\u590D\u7528\u3002`;
44256
+ } catch (err) {
44257
+ return `\u4FDD\u7559\u5931\u8D25\uFF1A${err.message}`;
44258
+ }
43802
44259
  }
43803
44260
  });
43804
44261
 
@@ -43852,7 +44309,7 @@ var skillForgeDrop = (engine) => ({
43852
44309
  });
43853
44310
 
43854
44311
  // src/memory/MemoryEngine.ts
43855
- var import_node_crypto8 = require("node:crypto");
44312
+ var import_node_crypto9 = require("node:crypto");
43856
44313
  var MemoryEngine = class {
43857
44314
  storage;
43858
44315
  recallIndexStorage;
@@ -43880,7 +44337,7 @@ var MemoryEngine = class {
43880
44337
  }
43881
44338
  const now = Date.now();
43882
44339
  const memory = {
43883
- id: (0, import_node_crypto8.randomBytes)(4).toString("hex"),
44340
+ id: (0, import_node_crypto9.randomBytes)(4).toString("hex"),
43884
44341
  userId,
43885
44342
  title,
43886
44343
  content,
@@ -44533,7 +44990,7 @@ var microCompactMessages = (messages, config2) => {
44533
44990
  };
44534
44991
 
44535
44992
  // src/agent/events.ts
44536
- var import_node_crypto9 = require("node:crypto");
44993
+ var import_node_crypto10 = require("node:crypto");
44537
44994
  var rowToEvent = (row) => ({
44538
44995
  id: row.id,
44539
44996
  userId: row.userId,
@@ -44550,7 +45007,7 @@ var rowToEvent = (row) => ({
44550
45007
  var recordAgentEvent = (input) => {
44551
45008
  const db3 = createSqliteDB();
44552
45009
  const now = Date.now();
44553
- const id = `evt_${(0, import_node_crypto9.randomUUID)().slice(0, 12)}`;
45010
+ const id = `evt_${(0, import_node_crypto10.randomUUID)().slice(0, 12)}`;
44554
45011
  const payloadJson = JSON.stringify(input.payload);
44555
45012
  db3.prepare(`
44556
45013
  INSERT INTO agent_events (
@@ -44682,12 +45139,12 @@ var assistantMessageFromResponse = (response) => ({
44682
45139
  ...response.model ? { model: response.model } : {}
44683
45140
  });
44684
45141
  var llmRequestIdForTurn = (request, messages, system, tools) => {
44685
- const hash = (0, import_node_crypto10.createHash)("sha256").update(request.requestId).update("\0").update(system).update("\0").update(JSON.stringify(messages)).update("\0").update(JSON.stringify(tools.map((tool) => tool.name).sort())).digest("hex").slice(0, 40);
45142
+ const hash = (0, import_node_crypto11.createHash)("sha256").update(request.requestId).update("\0").update(system).update("\0").update(JSON.stringify(messages)).update("\0").update(JSON.stringify(tools.map((tool) => tool.name).sort())).digest("hex").slice(0, 40);
44686
45143
  return `dreq_${hash}`;
44687
45144
  };
44688
45145
  var getDefaultAgentConfig = (tools, systemPrompt) => {
44689
45146
  loadEnv();
44690
- (0, import_node_fs6.mkdirSync)(DEFAULT_WORKSPACE_PATH, { recursive: true });
45147
+ (0, import_node_fs7.mkdirSync)(DEFAULT_WORKSPACE_PATH, { recursive: true });
44691
45148
  let system = ``;
44692
45149
  if (!systemPrompt) {
44693
45150
  system = `
@@ -46329,26 +46786,26 @@ var handleParsingNestedValues = (form, key, value) => {
46329
46786
  };
46330
46787
 
46331
46788
  // node_modules/.pnpm/hono@4.12.9/node_modules/hono/dist/utils/url.js
46332
- var splitPath = (path18) => {
46333
- const paths = path18.split("/");
46789
+ var splitPath = (path19) => {
46790
+ const paths = path19.split("/");
46334
46791
  if (paths[0] === "") {
46335
46792
  paths.shift();
46336
46793
  }
46337
46794
  return paths;
46338
46795
  };
46339
46796
  var splitRoutingPath = (routePath) => {
46340
- const { groups, path: path18 } = extractGroupsFromPath(routePath);
46341
- const paths = splitPath(path18);
46797
+ const { groups, path: path19 } = extractGroupsFromPath(routePath);
46798
+ const paths = splitPath(path19);
46342
46799
  return replaceGroupMarks(paths, groups);
46343
46800
  };
46344
- var extractGroupsFromPath = (path18) => {
46801
+ var extractGroupsFromPath = (path19) => {
46345
46802
  const groups = [];
46346
- path18 = path18.replace(/\{[^}]+\}/g, (match2, index) => {
46803
+ path19 = path19.replace(/\{[^}]+\}/g, (match2, index) => {
46347
46804
  const mark = `@${index}`;
46348
46805
  groups.push([mark, match2]);
46349
46806
  return mark;
46350
46807
  });
46351
- return { groups, path: path18 };
46808
+ return { groups, path: path19 };
46352
46809
  };
46353
46810
  var replaceGroupMarks = (paths, groups) => {
46354
46811
  for (let i = groups.length - 1; i >= 0; i--) {
@@ -46405,8 +46862,8 @@ var getPath = (request) => {
46405
46862
  const queryIndex = url.indexOf("?", i);
46406
46863
  const hashIndex = url.indexOf("#", i);
46407
46864
  const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
46408
- const path18 = url.slice(start, end);
46409
- return tryDecodeURI(path18.includes("%25") ? path18.replace(/%25/g, "%2525") : path18);
46865
+ const path19 = url.slice(start, end);
46866
+ return tryDecodeURI(path19.includes("%25") ? path19.replace(/%25/g, "%2525") : path19);
46410
46867
  } else if (charCode === 63 || charCode === 35) {
46411
46868
  break;
46412
46869
  }
@@ -46423,11 +46880,11 @@ var mergePath = (base, sub, ...rest) => {
46423
46880
  }
46424
46881
  return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
46425
46882
  };
46426
- var checkOptionalParameter = (path18) => {
46427
- if (path18.charCodeAt(path18.length - 1) !== 63 || !path18.includes(":")) {
46883
+ var checkOptionalParameter = (path19) => {
46884
+ if (path19.charCodeAt(path19.length - 1) !== 63 || !path19.includes(":")) {
46428
46885
  return null;
46429
46886
  }
46430
- const segments = path18.split("/");
46887
+ const segments = path19.split("/");
46431
46888
  const results = [];
46432
46889
  let basePath = "";
46433
46890
  segments.forEach((segment) => {
@@ -46568,9 +47025,9 @@ var HonoRequest = class {
46568
47025
  */
46569
47026
  path;
46570
47027
  bodyCache = {};
46571
- constructor(request, path18 = "/", matchResult = [[]]) {
47028
+ constructor(request, path19 = "/", matchResult = [[]]) {
46572
47029
  this.raw = request;
46573
- this.path = path18;
47030
+ this.path = path19;
46574
47031
  this.#matchResult = matchResult;
46575
47032
  this.#validatedData = {};
46576
47033
  }
@@ -47307,8 +47764,8 @@ var Hono = class _Hono {
47307
47764
  return this;
47308
47765
  };
47309
47766
  });
47310
- this.on = (method, path18, ...handlers) => {
47311
- for (const p of [path18].flat()) {
47767
+ this.on = (method, path19, ...handlers) => {
47768
+ for (const p of [path19].flat()) {
47312
47769
  this.#path = p;
47313
47770
  for (const m of [method].flat()) {
47314
47771
  handlers.map((handler) => {
@@ -47365,8 +47822,8 @@ var Hono = class _Hono {
47365
47822
  * app.route("/api", app2) // GET /api/user
47366
47823
  * ```
47367
47824
  */
47368
- route(path18, app) {
47369
- const subApp = this.basePath(path18);
47825
+ route(path19, app) {
47826
+ const subApp = this.basePath(path19);
47370
47827
  app.routes.map((r) => {
47371
47828
  let handler;
47372
47829
  if (app.errorHandler === errorHandler) {
@@ -47392,9 +47849,9 @@ var Hono = class _Hono {
47392
47849
  * const api = new Hono().basePath('/api')
47393
47850
  * ```
47394
47851
  */
47395
- basePath(path18) {
47852
+ basePath(path19) {
47396
47853
  const subApp = this.#clone();
47397
- subApp._basePath = mergePath(this._basePath, path18);
47854
+ subApp._basePath = mergePath(this._basePath, path19);
47398
47855
  return subApp;
47399
47856
  }
47400
47857
  /**
@@ -47468,7 +47925,7 @@ var Hono = class _Hono {
47468
47925
  * })
47469
47926
  * ```
47470
47927
  */
47471
- mount(path18, applicationHandler, options) {
47928
+ mount(path19, applicationHandler, options) {
47472
47929
  let replaceRequest;
47473
47930
  let optionHandler;
47474
47931
  if (options) {
@@ -47495,7 +47952,7 @@ var Hono = class _Hono {
47495
47952
  return [c.env, executionContext];
47496
47953
  };
47497
47954
  replaceRequest ||= (() => {
47498
- const mergedPath = mergePath(this._basePath, path18);
47955
+ const mergedPath = mergePath(this._basePath, path19);
47499
47956
  const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
47500
47957
  return (request) => {
47501
47958
  const url = new URL(request.url);
@@ -47510,14 +47967,14 @@ var Hono = class _Hono {
47510
47967
  }
47511
47968
  await next();
47512
47969
  };
47513
- this.#addRoute(METHOD_NAME_ALL, mergePath(path18, "*"), handler);
47970
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path19, "*"), handler);
47514
47971
  return this;
47515
47972
  }
47516
- #addRoute(method, path18, handler) {
47973
+ #addRoute(method, path19, handler) {
47517
47974
  method = method.toUpperCase();
47518
- path18 = mergePath(this._basePath, path18);
47519
- const r = { basePath: this._basePath, path: path18, method, handler };
47520
- this.router.add(method, path18, [handler, r]);
47975
+ path19 = mergePath(this._basePath, path19);
47976
+ const r = { basePath: this._basePath, path: path19, method, handler };
47977
+ this.router.add(method, path19, [handler, r]);
47521
47978
  this.routes.push(r);
47522
47979
  }
47523
47980
  #handleError(err, c) {
@@ -47530,10 +47987,10 @@ var Hono = class _Hono {
47530
47987
  if (method === "HEAD") {
47531
47988
  return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
47532
47989
  }
47533
- const path18 = this.getPath(request, { env });
47534
- const matchResult = this.router.match(method, path18);
47990
+ const path19 = this.getPath(request, { env });
47991
+ const matchResult = this.router.match(method, path19);
47535
47992
  const c = new Context(request, {
47536
- path: path18,
47993
+ path: path19,
47537
47994
  matchResult,
47538
47995
  env,
47539
47996
  executionCtx,
@@ -47633,7 +48090,7 @@ var Hono = class _Hono {
47633
48090
 
47634
48091
  // node_modules/.pnpm/hono@4.12.9/node_modules/hono/dist/router/reg-exp-router/matcher.js
47635
48092
  var emptyParam = [];
47636
- function match(method, path18) {
48093
+ function match(method, path19) {
47637
48094
  const matchers = this.buildAllMatchers();
47638
48095
  const match2 = ((method2, path22) => {
47639
48096
  const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
@@ -47649,7 +48106,7 @@ function match(method, path18) {
47649
48106
  return [matcher[1][index], match3];
47650
48107
  });
47651
48108
  this.match = match2;
47652
- return match2(method, path18);
48109
+ return match2(method, path19);
47653
48110
  }
47654
48111
 
47655
48112
  // node_modules/.pnpm/hono@4.12.9/node_modules/hono/dist/router/reg-exp-router/node.js
@@ -47764,12 +48221,12 @@ var Node = class _Node {
47764
48221
  var Trie = class {
47765
48222
  #context = { varIndex: 0 };
47766
48223
  #root = new Node();
47767
- insert(path18, index, pathErrorCheckOnly) {
48224
+ insert(path19, index, pathErrorCheckOnly) {
47768
48225
  const paramAssoc = [];
47769
48226
  const groups = [];
47770
48227
  for (let i = 0; ; ) {
47771
48228
  let replaced = false;
47772
- path18 = path18.replace(/\{[^}]+\}/g, (m) => {
48229
+ path19 = path19.replace(/\{[^}]+\}/g, (m) => {
47773
48230
  const mark = `@\\${i}`;
47774
48231
  groups[i] = [mark, m];
47775
48232
  i++;
@@ -47780,7 +48237,7 @@ var Trie = class {
47780
48237
  break;
47781
48238
  }
47782
48239
  }
47783
- const tokens = path18.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
48240
+ const tokens = path19.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
47784
48241
  for (let i = groups.length - 1; i >= 0; i--) {
47785
48242
  const [mark] = groups[i];
47786
48243
  for (let j = tokens.length - 1; j >= 0; j--) {
@@ -47819,9 +48276,9 @@ var Trie = class {
47819
48276
  // node_modules/.pnpm/hono@4.12.9/node_modules/hono/dist/router/reg-exp-router/router.js
47820
48277
  var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
47821
48278
  var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
47822
- function buildWildcardRegExp(path18) {
47823
- return wildcardRegExpCache[path18] ??= new RegExp(
47824
- path18 === "*" ? "" : `^${path18.replace(
48279
+ function buildWildcardRegExp(path19) {
48280
+ return wildcardRegExpCache[path19] ??= new RegExp(
48281
+ path19 === "*" ? "" : `^${path19.replace(
47825
48282
  /\/\*$|([.\\+*[^\]$()])/g,
47826
48283
  (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
47827
48284
  )}$`
@@ -47843,17 +48300,17 @@ function buildMatcherFromPreprocessedRoutes(routes) {
47843
48300
  );
47844
48301
  const staticMap = /* @__PURE__ */ Object.create(null);
47845
48302
  for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
47846
- const [pathErrorCheckOnly, path18, handlers] = routesWithStaticPathFlag[i];
48303
+ const [pathErrorCheckOnly, path19, handlers] = routesWithStaticPathFlag[i];
47847
48304
  if (pathErrorCheckOnly) {
47848
- staticMap[path18] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
48305
+ staticMap[path19] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
47849
48306
  } else {
47850
48307
  j++;
47851
48308
  }
47852
48309
  let paramAssoc;
47853
48310
  try {
47854
- paramAssoc = trie.insert(path18, j, pathErrorCheckOnly);
48311
+ paramAssoc = trie.insert(path19, j, pathErrorCheckOnly);
47855
48312
  } catch (e) {
47856
- throw e === PATH_ERROR ? new UnsupportedPathError(path18) : e;
48313
+ throw e === PATH_ERROR ? new UnsupportedPathError(path19) : e;
47857
48314
  }
47858
48315
  if (pathErrorCheckOnly) {
47859
48316
  continue;
@@ -47887,12 +48344,12 @@ function buildMatcherFromPreprocessedRoutes(routes) {
47887
48344
  }
47888
48345
  return [regexp, handlerMap, staticMap];
47889
48346
  }
47890
- function findMiddleware(middleware, path18) {
48347
+ function findMiddleware(middleware, path19) {
47891
48348
  if (!middleware) {
47892
48349
  return void 0;
47893
48350
  }
47894
48351
  for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
47895
- if (buildWildcardRegExp(k).test(path18)) {
48352
+ if (buildWildcardRegExp(k).test(path19)) {
47896
48353
  return [...middleware[k]];
47897
48354
  }
47898
48355
  }
@@ -47906,7 +48363,7 @@ var RegExpRouter = class {
47906
48363
  this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
47907
48364
  this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
47908
48365
  }
47909
- add(method, path18, handler) {
48366
+ add(method, path19, handler) {
47910
48367
  const middleware = this.#middleware;
47911
48368
  const routes = this.#routes;
47912
48369
  if (!middleware || !routes) {
@@ -47921,18 +48378,18 @@ var RegExpRouter = class {
47921
48378
  });
47922
48379
  });
47923
48380
  }
47924
- if (path18 === "/*") {
47925
- path18 = "*";
48381
+ if (path19 === "/*") {
48382
+ path19 = "*";
47926
48383
  }
47927
- const paramCount = (path18.match(/\/:/g) || []).length;
47928
- if (/\*$/.test(path18)) {
47929
- const re = buildWildcardRegExp(path18);
48384
+ const paramCount = (path19.match(/\/:/g) || []).length;
48385
+ if (/\*$/.test(path19)) {
48386
+ const re = buildWildcardRegExp(path19);
47930
48387
  if (method === METHOD_NAME_ALL) {
47931
48388
  Object.keys(middleware).forEach((m) => {
47932
- middleware[m][path18] ||= findMiddleware(middleware[m], path18) || findMiddleware(middleware[METHOD_NAME_ALL], path18) || [];
48389
+ middleware[m][path19] ||= findMiddleware(middleware[m], path19) || findMiddleware(middleware[METHOD_NAME_ALL], path19) || [];
47933
48390
  });
47934
48391
  } else {
47935
- middleware[method][path18] ||= findMiddleware(middleware[method], path18) || findMiddleware(middleware[METHOD_NAME_ALL], path18) || [];
48392
+ middleware[method][path19] ||= findMiddleware(middleware[method], path19) || findMiddleware(middleware[METHOD_NAME_ALL], path19) || [];
47936
48393
  }
47937
48394
  Object.keys(middleware).forEach((m) => {
47938
48395
  if (method === METHOD_NAME_ALL || method === m) {
@@ -47950,7 +48407,7 @@ var RegExpRouter = class {
47950
48407
  });
47951
48408
  return;
47952
48409
  }
47953
- const paths = checkOptionalParameter(path18) || [path18];
48410
+ const paths = checkOptionalParameter(path19) || [path19];
47954
48411
  for (let i = 0, len = paths.length; i < len; i++) {
47955
48412
  const path22 = paths[i];
47956
48413
  Object.keys(routes).forEach((m) => {
@@ -47977,13 +48434,13 @@ var RegExpRouter = class {
47977
48434
  const routes = [];
47978
48435
  let hasOwnRoute = method === METHOD_NAME_ALL;
47979
48436
  [this.#middleware, this.#routes].forEach((r) => {
47980
- const ownRoute = r[method] ? Object.keys(r[method]).map((path18) => [path18, r[method][path18]]) : [];
48437
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path19) => [path19, r[method][path19]]) : [];
47981
48438
  if (ownRoute.length !== 0) {
47982
48439
  hasOwnRoute ||= true;
47983
48440
  routes.push(...ownRoute);
47984
48441
  } else if (method !== METHOD_NAME_ALL) {
47985
48442
  routes.push(
47986
- ...Object.keys(r[METHOD_NAME_ALL]).map((path18) => [path18, r[METHOD_NAME_ALL][path18]])
48443
+ ...Object.keys(r[METHOD_NAME_ALL]).map((path19) => [path19, r[METHOD_NAME_ALL][path19]])
47987
48444
  );
47988
48445
  }
47989
48446
  });
@@ -48003,13 +48460,13 @@ var SmartRouter = class {
48003
48460
  constructor(init) {
48004
48461
  this.#routers = init.routers;
48005
48462
  }
48006
- add(method, path18, handler) {
48463
+ add(method, path19, handler) {
48007
48464
  if (!this.#routes) {
48008
48465
  throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
48009
48466
  }
48010
- this.#routes.push([method, path18, handler]);
48467
+ this.#routes.push([method, path19, handler]);
48011
48468
  }
48012
- match(method, path18) {
48469
+ match(method, path19) {
48013
48470
  if (!this.#routes) {
48014
48471
  throw new Error("Fatal error");
48015
48472
  }
@@ -48024,7 +48481,7 @@ var SmartRouter = class {
48024
48481
  for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
48025
48482
  router.add(...routes[i2]);
48026
48483
  }
48027
- res = router.match(method, path18);
48484
+ res = router.match(method, path19);
48028
48485
  } catch (e) {
48029
48486
  if (e instanceof UnsupportedPathError) {
48030
48487
  continue;
@@ -48074,10 +48531,10 @@ var Node2 = class _Node2 {
48074
48531
  }
48075
48532
  this.#patterns = [];
48076
48533
  }
48077
- insert(method, path18, handler) {
48534
+ insert(method, path19, handler) {
48078
48535
  this.#order = ++this.#order;
48079
48536
  let curNode = this;
48080
- const parts = splitRoutingPath(path18);
48537
+ const parts = splitRoutingPath(path19);
48081
48538
  const possibleKeys = [];
48082
48539
  for (let i = 0, len = parts.length; i < len; i++) {
48083
48540
  const p = parts[i];
@@ -48126,12 +48583,12 @@ var Node2 = class _Node2 {
48126
48583
  }
48127
48584
  }
48128
48585
  }
48129
- search(method, path18) {
48586
+ search(method, path19) {
48130
48587
  const handlerSets = [];
48131
48588
  this.#params = emptyParams;
48132
48589
  const curNode = this;
48133
48590
  let curNodes = [curNode];
48134
- const parts = splitPath(path18);
48591
+ const parts = splitPath(path19);
48135
48592
  const curNodesQueue = [];
48136
48593
  const len = parts.length;
48137
48594
  let partOffsets = null;
@@ -48173,13 +48630,13 @@ var Node2 = class _Node2 {
48173
48630
  if (matcher instanceof RegExp) {
48174
48631
  if (partOffsets === null) {
48175
48632
  partOffsets = new Array(len);
48176
- let offset = path18[0] === "/" ? 1 : 0;
48633
+ let offset = path19[0] === "/" ? 1 : 0;
48177
48634
  for (let p = 0; p < len; p++) {
48178
48635
  partOffsets[p] = offset;
48179
48636
  offset += parts[p].length + 1;
48180
48637
  }
48181
48638
  }
48182
- const restPathString = path18.substring(partOffsets[i]);
48639
+ const restPathString = path19.substring(partOffsets[i]);
48183
48640
  const m = matcher.exec(restPathString);
48184
48641
  if (m) {
48185
48642
  params[name] = m[0];
@@ -48232,18 +48689,18 @@ var TrieRouter = class {
48232
48689
  constructor() {
48233
48690
  this.#node = new Node2();
48234
48691
  }
48235
- add(method, path18, handler) {
48236
- const results = checkOptionalParameter(path18);
48692
+ add(method, path19, handler) {
48693
+ const results = checkOptionalParameter(path19);
48237
48694
  if (results) {
48238
48695
  for (let i = 0, len = results.length; i < len; i++) {
48239
48696
  this.#node.insert(method, results[i], handler);
48240
48697
  }
48241
48698
  return;
48242
48699
  }
48243
- this.#node.insert(method, path18, handler);
48700
+ this.#node.insert(method, path19, handler);
48244
48701
  }
48245
- match(method, path18) {
48246
- return this.#node.search(method, path18);
48702
+ match(method, path19) {
48703
+ return this.#node.search(method, path19);
48247
48704
  }
48248
48705
  };
48249
48706
 
@@ -48945,10 +49402,10 @@ var createStreamBody = (stream) => {
48945
49402
  });
48946
49403
  return body;
48947
49404
  };
48948
- var getStats = (path18) => {
49405
+ var getStats = (path19) => {
48949
49406
  let stats;
48950
49407
  try {
48951
- stats = (0, import_fs15.statSync)(path18);
49408
+ stats = (0, import_fs15.statSync)(path19);
48952
49409
  } catch {
48953
49410
  }
48954
49411
  return stats;
@@ -48991,21 +49448,21 @@ var serveStatic = (options = { root: "" }) => {
48991
49448
  return next();
48992
49449
  }
48993
49450
  }
48994
- let path18 = (0, import_path20.join)(
49451
+ let path19 = (0, import_path20.join)(
48995
49452
  root,
48996
49453
  !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename
48997
49454
  );
48998
- let stats = getStats(path18);
49455
+ let stats = getStats(path19);
48999
49456
  if (stats && stats.isDirectory()) {
49000
49457
  const indexFile = options.index ?? "index.html";
49001
- path18 = (0, import_path20.join)(path18, indexFile);
49002
- stats = getStats(path18);
49458
+ path19 = (0, import_path20.join)(path19, indexFile);
49459
+ stats = getStats(path19);
49003
49460
  }
49004
49461
  if (!stats) {
49005
- await options.onNotFound?.(path18, c);
49462
+ await options.onNotFound?.(path19, c);
49006
49463
  return next();
49007
49464
  }
49008
- const mimeType = getMimeType(path18);
49465
+ const mimeType = getMimeType(path19);
49009
49466
  c.header("Content-Type", mimeType || "application/octet-stream");
49010
49467
  if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
49011
49468
  const acceptEncodingSet = new Set(
@@ -49015,12 +49472,12 @@ var serveStatic = (options = { root: "" }) => {
49015
49472
  if (!acceptEncodingSet.has(encoding)) {
49016
49473
  continue;
49017
49474
  }
49018
- const precompressedStats = getStats(path18 + ENCODINGS[encoding]);
49475
+ const precompressedStats = getStats(path19 + ENCODINGS[encoding]);
49019
49476
  if (precompressedStats) {
49020
49477
  c.header("Content-Encoding", encoding);
49021
49478
  c.header("Vary", "Accept-Encoding", { append: true });
49022
49479
  stats = precompressedStats;
49023
- path18 = path18 + ENCODINGS[encoding];
49480
+ path19 = path19 + ENCODINGS[encoding];
49024
49481
  break;
49025
49482
  }
49026
49483
  }
@@ -49034,7 +49491,7 @@ var serveStatic = (options = { root: "" }) => {
49034
49491
  result = c.body(null);
49035
49492
  } else if (!range) {
49036
49493
  c.header("Content-Length", size.toString());
49037
- result = c.body(createStreamBody((0, import_fs15.createReadStream)(path18)), 200);
49494
+ result = c.body(createStreamBody((0, import_fs15.createReadStream)(path19)), 200);
49038
49495
  } else {
49039
49496
  c.header("Accept-Ranges", "bytes");
49040
49497
  c.header("Date", stats.birthtime.toUTCString());
@@ -49045,12 +49502,12 @@ var serveStatic = (options = { root: "" }) => {
49045
49502
  end = size - 1;
49046
49503
  }
49047
49504
  const chunksize = end - start + 1;
49048
- const stream = (0, import_fs15.createReadStream)(path18, { start, end });
49505
+ const stream = (0, import_fs15.createReadStream)(path19, { start, end });
49049
49506
  c.header("Content-Length", chunksize.toString());
49050
49507
  c.header("Content-Range", `bytes ${start}-${end}/${stats.size}`);
49051
49508
  result = c.body(createStreamBody(stream), 206);
49052
49509
  }
49053
- await options.onFound?.(path18, c);
49510
+ await options.onFound?.(path19, c);
49054
49511
  return result;
49055
49512
  };
49056
49513
  };
@@ -49145,7 +49602,7 @@ var cors = (options) => {
49145
49602
 
49146
49603
  // src/server/index.ts
49147
49604
  var import_promises11 = require("node:fs/promises");
49148
- var import_node_path14 = __toESM(require("node:path"));
49605
+ var import_node_path15 = __toESM(require("node:path"));
49149
49606
 
49150
49607
  // src/git/worktree.ts
49151
49608
  var import_child_process2 = require("child_process");
@@ -50376,8 +50833,8 @@ mailboxRoutes.get("/mailbox/summary", (c) => {
50376
50833
 
50377
50834
  // src/server/routes/memory.ts
50378
50835
  var import_redis4 = __toESM(require_dist2());
50379
- var import_node_fs7 = require("node:fs");
50380
- var import_node_path13 = __toESM(require("node:path"));
50836
+ var import_node_fs8 = require("node:fs");
50837
+ var import_node_path14 = __toESM(require("node:path"));
50381
50838
  var memoryEngineSingleton = null;
50382
50839
  var dreamStorageSingleton = null;
50383
50840
  var dreamHistoryStorageSingleton = null;
@@ -50477,12 +50934,12 @@ var addPlausibleUserId = (set, userId) => {
50477
50934
  if (normalized && isPlausibleUserId(normalized)) set.add(normalized);
50478
50935
  };
50479
50936
  var readJsonFilesFromDir = (dir) => {
50480
- if (!(0, import_node_fs7.existsSync)(dir)) return [];
50937
+ if (!(0, import_node_fs8.existsSync)(dir)) return [];
50481
50938
  const result = [];
50482
- for (const file of (0, import_node_fs7.readdirSync)(dir)) {
50939
+ for (const file of (0, import_node_fs8.readdirSync)(dir)) {
50483
50940
  if (!file.endsWith(".json")) continue;
50484
50941
  try {
50485
- result.push(JSON.parse((0, import_node_fs7.readFileSync)(import_node_path13.default.join(dir, file), "utf-8")));
50942
+ result.push(JSON.parse((0, import_node_fs8.readFileSync)(import_node_path14.default.join(dir, file), "utf-8")));
50486
50943
  } catch (err) {
50487
50944
  console.warn(`[memoryRoutes] \u8DF3\u8FC7\u65E0\u6CD5\u89E3\u6790\u7684\u672C\u5730\u4E0A\u4E0B\u6587\u6587\u4EF6 ${file}: ${err.message}`);
50488
50945
  }
@@ -50490,13 +50947,13 @@ var readJsonFilesFromDir = (dir) => {
50490
50947
  return result;
50491
50948
  };
50492
50949
  var extractFileBackedStorageKeysForTest = (dataDir) => {
50493
- const kvRoot = import_node_path13.default.join(dataDir, "kv");
50494
- if (!(0, import_node_fs7.existsSync)(kvRoot)) return [];
50950
+ const kvRoot = import_node_path14.default.join(dataDir, "kv");
50951
+ if (!(0, import_node_fs8.existsSync)(kvRoot)) return [];
50495
50952
  const keys = [];
50496
- for (const prefixDir of (0, import_node_fs7.readdirSync)(kvRoot)) {
50497
- const absolutePrefixDir = import_node_path13.default.join(kvRoot, prefixDir);
50498
- if (!(0, import_node_fs7.existsSync)(absolutePrefixDir)) continue;
50499
- for (const file of (0, import_node_fs7.readdirSync)(absolutePrefixDir)) {
50953
+ for (const prefixDir of (0, import_node_fs8.readdirSync)(kvRoot)) {
50954
+ const absolutePrefixDir = import_node_path14.default.join(kvRoot, prefixDir);
50955
+ if (!(0, import_node_fs8.existsSync)(absolutePrefixDir)) continue;
50956
+ for (const file of (0, import_node_fs8.readdirSync)(absolutePrefixDir)) {
50500
50957
  if (!file.endsWith(".json")) continue;
50501
50958
  try {
50502
50959
  const logicalKey = Buffer.from(file.replace(/\.json$/, ""), "base64url").toString("utf8");
@@ -50514,12 +50971,12 @@ var collectLocalConversationUserIds = () => {
50514
50971
  };
50515
50972
  var extractLocalConversationUserIdsForTest = (homeDir) => {
50516
50973
  const userIds = /* @__PURE__ */ new Set();
50517
- for (const context of readJsonFilesFromDir(import_node_path13.default.join(homeDir, "goal-context"))) {
50974
+ for (const context of readJsonFilesFromDir(import_node_path14.default.join(homeDir, "goal-context"))) {
50518
50975
  addPlausibleUserId(userIds, context.threadId);
50519
50976
  addPlausibleUserId(userIds, context.originUserId);
50520
50977
  if (context.goalId) addPlausibleUserId(userIds, `kanban:goal:${context.goalId}`);
50521
50978
  }
50522
- for (const goal of readJsonFilesFromDir(import_node_path13.default.join(homeDir, "tasks"))) {
50979
+ for (const goal of readJsonFilesFromDir(import_node_path14.default.join(homeDir, "tasks"))) {
50523
50980
  if (goal.id) addPlausibleUserId(userIds, `kanban:goal:${goal.id}`);
50524
50981
  }
50525
50982
  return userIds;
@@ -50651,6 +51108,13 @@ var dateKeyInShanghai = (timestamp) => new Date(timestamp).toLocaleString("sv-SE
50651
51108
  month: "2-digit",
50652
51109
  day: "2-digit"
50653
51110
  }).replace(/-/g, "");
51111
+ var recentDateKeysInShanghaiForTest = (now, days = 7) => {
51112
+ const keys = [];
51113
+ for (let i = days - 1; i >= 0; i--) {
51114
+ keys.push(dateKeyInShanghai(now - i * 864e5));
51115
+ }
51116
+ return keys;
51117
+ };
50654
51118
  var messageToAgentLogEntry = (message, index) => ({
50655
51119
  index,
50656
51120
  role: message.role,
@@ -50679,8 +51143,7 @@ var collectConversationMessages = async (userId, limit = 300) => {
50679
51143
  const storage = createRuntimeStorage(storageConf);
50680
51144
  const now = Date.now();
50681
51145
  const byDate = [];
50682
- for (let i = 0; i < 7; i++) {
50683
- const dateStr = dateKeyInShanghai(now - i * 864e5);
51146
+ for (const dateStr of recentDateKeysInShanghaiForTest(now, 7)) {
50684
51147
  const messages = await getMessages(storage, userId, limit, dateStr);
50685
51148
  if (messages.length > 0) {
50686
51149
  byDate.push(...messages.map((message) => ({ message, sourceKey: dateStr })));
@@ -50973,7 +51436,7 @@ var systemRoutes = new Hono2();
50973
51436
  var startTime = Date.now();
50974
51437
  systemRoutes.get("/system/info", (c) => {
50975
51438
  return c.json({
50976
- version: true ? "1.8.14" : "unknown",
51439
+ version: true ? "1.8.16" : "unknown",
50977
51440
  uptime: Math.floor((Date.now() - startTime) / 1e3),
50978
51441
  env: process.env.NODE_ENV || "development",
50979
51442
  nodeVersion: process.version
@@ -50997,7 +51460,7 @@ function createServer() {
50997
51460
  app.route("/api", systemRoutes);
50998
51461
  app.use("/*", serveStatic({ root: webDistRoot }));
50999
51462
  app.get("/*", async (c) => {
51000
- const indexHtml = await (0, import_promises11.readFile)(import_node_path14.default.join(webDistRoot, "index.html"), "utf8");
51463
+ const indexHtml = await (0, import_promises11.readFile)(import_node_path15.default.join(webDistRoot, "index.html"), "utf8");
51001
51464
  const tenantId = c.req.header("x-tenant-id");
51002
51465
  const assetBase = tenantId ? `/t/${tenantId}` : "";
51003
51466
  const html = indexHtml.replaceAll('"./', `"${assetBase}/`);
@@ -51024,10 +51487,10 @@ function shouldStartCoreChannelGateways(env = process.env) {
51024
51487
  }
51025
51488
 
51026
51489
  // src/runtime/saasAssets.ts
51027
- var import_node_fs8 = require("node:fs");
51490
+ var import_node_fs9 = require("node:fs");
51028
51491
  var import_promises12 = require("node:fs/promises");
51029
51492
  var import_node_os3 = require("node:os");
51030
- var import_node_path15 = __toESM(require("node:path"));
51493
+ var import_node_path16 = __toESM(require("node:path"));
51031
51494
  var MAX_CONTEXT_ASSETS = Number(process.env.DUCLAW_SAAS_ASSET_CONTEXT_LIMIT ?? 1e3);
51032
51495
  var MAX_SKILL_ASSETS = Number(process.env.DUCLAW_SAAS_ASSET_SKILL_LIMIT ?? 200);
51033
51496
  async function restoreSaasRuntimeAssets(reason) {
@@ -51057,8 +51520,8 @@ async function restoreSaasRuntimeAssets(reason) {
51057
51520
  async function restoreContextAsset(context, overwrite) {
51058
51521
  const target = contextPathForSourceKey(context.sourceKey);
51059
51522
  if (!target) return false;
51060
- if (!overwrite && (0, import_node_fs8.existsSync)(target)) return false;
51061
- await (0, import_promises12.mkdir)(import_node_path15.default.dirname(target), { recursive: true });
51523
+ if (!overwrite && (0, import_node_fs9.existsSync)(target)) return false;
51524
+ await (0, import_promises12.mkdir)(import_node_path16.default.dirname(target), { recursive: true });
51062
51525
  await (0, import_promises12.writeFile)(target, JSON.stringify(context.payload), "utf8");
51063
51526
  return true;
51064
51527
  }
@@ -51066,8 +51529,8 @@ async function restoreSkillAsset(skill, overwrite) {
51066
51529
  if (!skill.skillMd) return false;
51067
51530
  const target = safeSkillTargetPath(skill.sourcePath, skill.skillName);
51068
51531
  if (!target) return false;
51069
- if (!overwrite && (0, import_node_fs8.existsSync)(target)) return false;
51070
- await (0, import_promises12.mkdir)(import_node_path15.default.dirname(target), { recursive: true });
51532
+ if (!overwrite && (0, import_node_fs9.existsSync)(target)) return false;
51533
+ await (0, import_promises12.mkdir)(import_node_path16.default.dirname(target), { recursive: true });
51071
51534
  await (0, import_promises12.writeFile)(target, skill.skillMd, "utf8");
51072
51535
  return true;
51073
51536
  }
@@ -51100,30 +51563,30 @@ function runtimeAssetClient() {
51100
51563
  function contextPathForSourceKey(sourceKey) {
51101
51564
  if (sourceKey.startsWith("agent:")) {
51102
51565
  const logicalKey = sourceKey.slice("agent:".length);
51103
- return import_node_path15.default.join(getDuclawDataDir(), "kv", "agent", `${Buffer.from(logicalKey).toString("base64url")}.json`);
51566
+ return import_node_path16.default.join(getDuclawDataDir(), "kv", "agent", `${Buffer.from(logicalKey).toString("base64url")}.json`);
51104
51567
  }
51105
51568
  if (sourceKey.startsWith("goal-context:")) {
51106
- return import_node_path15.default.join(getDuclawHomeDir(), "goal-context", `${sourceKey.slice("goal-context:".length)}.json`);
51569
+ return import_node_path16.default.join(getDuclawHomeDir(), "goal-context", `${sourceKey.slice("goal-context:".length)}.json`);
51107
51570
  }
51108
51571
  if (sourceKey.startsWith("tasks:")) {
51109
- return import_node_path15.default.join(getDuclawHomeDir(), "tasks", `${sourceKey.slice("tasks:".length)}.json`);
51572
+ return import_node_path16.default.join(getDuclawHomeDir(), "tasks", `${sourceKey.slice("tasks:".length)}.json`);
51110
51573
  }
51111
51574
  return null;
51112
51575
  }
51113
51576
  function safeSkillTargetPath(sourcePath, skillName) {
51114
- const allowedRoots = skillRoots().map((root) => import_node_path15.default.resolve(root));
51115
- const normalized = import_node_path15.default.resolve(sourcePath);
51116
- if (allowedRoots.some((root) => normalized === import_node_path15.default.join(root, import_node_path15.default.basename(import_node_path15.default.dirname(normalized)), "SKILL.md"))) {
51577
+ const allowedRoots = skillRoots().map((root) => import_node_path16.default.resolve(root));
51578
+ const normalized = import_node_path16.default.resolve(sourcePath);
51579
+ if (allowedRoots.some((root) => normalized === import_node_path16.default.join(root, import_node_path16.default.basename(import_node_path16.default.dirname(normalized)), "SKILL.md"))) {
51117
51580
  return normalized;
51118
51581
  }
51119
51582
  const safeName = skillName.replace(/[^a-zA-Z0-9._-]/g, "-").slice(0, 120) || "imported-skill";
51120
- return import_node_path15.default.join("/home/user/app/skills", safeName, "SKILL.md");
51583
+ return import_node_path16.default.join("/home/user/app/skills", safeName, "SKILL.md");
51121
51584
  }
51122
51585
  function skillRoots() {
51123
51586
  return [
51124
51587
  "/home/user/app/skills",
51125
- import_node_path15.default.join(getDuclawHomeDir(), "skills"),
51126
- import_node_path15.default.join((0, import_node_os3.homedir)(), ".agents", "skills")
51588
+ import_node_path16.default.join(getDuclawHomeDir(), "skills"),
51589
+ import_node_path16.default.join((0, import_node_os3.homedir)(), ".agents", "skills")
51127
51590
  ];
51128
51591
  }
51129
51592