@plume-canvas/plugin-agent 0.1.16 → 0.1.17

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/server.js CHANGED
@@ -9672,14 +9672,14 @@ var require_parser = __commonJS({
9672
9672
  case "scalar":
9673
9673
  case "single-quoted-scalar":
9674
9674
  case "double-quoted-scalar": {
9675
- const fs20 = this.flowScalar(this.type);
9675
+ const fs19 = this.flowScalar(this.type);
9676
9676
  if (atNextItem || it.value) {
9677
- map3.items.push({ start, key: fs20, sep: [] });
9677
+ map3.items.push({ start, key: fs19, sep: [] });
9678
9678
  this.onKeyLine = true;
9679
9679
  } else if (it.sep) {
9680
- this.stack.push(fs20);
9680
+ this.stack.push(fs19);
9681
9681
  } else {
9682
- Object.assign(it, { key: fs20, sep: [] });
9682
+ Object.assign(it, { key: fs19, sep: [] });
9683
9683
  this.onKeyLine = true;
9684
9684
  }
9685
9685
  return;
@@ -9807,13 +9807,13 @@ var require_parser = __commonJS({
9807
9807
  case "scalar":
9808
9808
  case "single-quoted-scalar":
9809
9809
  case "double-quoted-scalar": {
9810
- const fs20 = this.flowScalar(this.type);
9810
+ const fs19 = this.flowScalar(this.type);
9811
9811
  if (!it || it.value)
9812
- fc.items.push({ start: [], key: fs20, sep: [] });
9812
+ fc.items.push({ start: [], key: fs19, sep: [] });
9813
9813
  else if (it.sep)
9814
- this.stack.push(fs20);
9814
+ this.stack.push(fs19);
9815
9815
  else
9816
- Object.assign(it, { key: fs20, sep: [] });
9816
+ Object.assign(it, { key: fs19, sep: [] });
9817
9817
  return;
9818
9818
  }
9819
9819
  case "flow-map-end":
@@ -12601,8 +12601,8 @@ var require_node = __commonJS({
12601
12601
  }
12602
12602
  break;
12603
12603
  case "FILE":
12604
- var fs20 = __require("fs");
12605
- stream3 = new fs20.SyncWriteStream(fd2, { autoClose: false });
12604
+ var fs19 = __require("fs");
12605
+ stream3 = new fs19.SyncWriteStream(fd2, { autoClose: false });
12606
12606
  stream3._type = "fs";
12607
12607
  break;
12608
12608
  case "PIPE":
@@ -29812,7 +29812,7 @@ var require_view = __commonJS({
29812
29812
  "use strict";
29813
29813
  var debug = require_src()("express:view");
29814
29814
  var path37 = __require("path");
29815
- var fs20 = __require("fs");
29815
+ var fs19 = __require("fs");
29816
29816
  var dirname2 = path37.dirname;
29817
29817
  var basename2 = path37.basename;
29818
29818
  var extname = path37.extname;
@@ -29878,7 +29878,7 @@ var require_view = __commonJS({
29878
29878
  function tryStat(path38) {
29879
29879
  debug('stat "%s"', path38);
29880
29880
  try {
29881
- return fs20.statSync(path38);
29881
+ return fs19.statSync(path38);
29882
29882
  } catch (e7) {
29883
29883
  return void 0;
29884
29884
  }
@@ -30233,7 +30233,7 @@ var require_types = __commonJS({
30233
30233
  var require_mime = __commonJS({
30234
30234
  "../../../node_modules/.pnpm/mime@1.6.0/node_modules/mime/mime.js"(exports, module) {
30235
30235
  var path37 = __require("path");
30236
- var fs20 = __require("fs");
30236
+ var fs19 = __require("fs");
30237
30237
  function Mime() {
30238
30238
  this.types = /* @__PURE__ */ Object.create(null);
30239
30239
  this.extensions = /* @__PURE__ */ Object.create(null);
@@ -30254,7 +30254,7 @@ var require_mime = __commonJS({
30254
30254
  };
30255
30255
  Mime.prototype.load = function(file) {
30256
30256
  this._loading = file;
30257
- var map3 = {}, content = fs20.readFileSync(file, "ascii"), lines = content.split(/[\r\n]+/);
30257
+ var map3 = {}, content = fs19.readFileSync(file, "ascii"), lines = content.split(/[\r\n]+/);
30258
30258
  lines.forEach(function(line) {
30259
30259
  var fields = line.replace(/\s*#.*|^\s*|\s*$/g, "").split(/\s+/);
30260
30260
  map3[fields.shift()] = fields;
@@ -30492,7 +30492,7 @@ var require_send = __commonJS({
30492
30492
  var escapeHtml = require_escape_html();
30493
30493
  var etag = require_etag();
30494
30494
  var fresh = require_fresh();
30495
- var fs20 = __require("fs");
30495
+ var fs19 = __require("fs");
30496
30496
  var mime = require_mime();
30497
30497
  var ms = require_ms2();
30498
30498
  var onFinished = require_on_finished();
@@ -30825,7 +30825,7 @@ var require_send = __commonJS({
30825
30825
  var i7 = 0;
30826
30826
  var self2 = this;
30827
30827
  debug('stat "%s"', path38);
30828
- fs20.stat(path38, function onstat(err, stat6) {
30828
+ fs19.stat(path38, function onstat(err, stat6) {
30829
30829
  if (err && err.code === "ENOENT" && !extname(path38) && path38[path38.length - 1] !== sep2) {
30830
30830
  return next(err);
30831
30831
  }
@@ -30840,7 +30840,7 @@ var require_send = __commonJS({
30840
30840
  }
30841
30841
  var p3 = path38 + "." + self2._extensions[i7++];
30842
30842
  debug('stat "%s"', p3);
30843
- fs20.stat(p3, function(err2, stat6) {
30843
+ fs19.stat(p3, function(err2, stat6) {
30844
30844
  if (err2) return next(err2);
30845
30845
  if (stat6.isDirectory()) return next();
30846
30846
  self2.emit("file", p3, stat6);
@@ -30858,7 +30858,7 @@ var require_send = __commonJS({
30858
30858
  }
30859
30859
  var p3 = join6(path38, self2._index[i7]);
30860
30860
  debug('stat "%s"', p3);
30861
- fs20.stat(p3, function(err2, stat6) {
30861
+ fs19.stat(p3, function(err2, stat6) {
30862
30862
  if (err2) return next(err2);
30863
30863
  if (stat6.isDirectory()) return next();
30864
30864
  self2.emit("file", p3, stat6);
@@ -30870,7 +30870,7 @@ var require_send = __commonJS({
30870
30870
  SendStream.prototype.stream = function stream2(path38, options) {
30871
30871
  var self2 = this;
30872
30872
  var res = this.res;
30873
- var stream3 = fs20.createReadStream(path38, options);
30873
+ var stream3 = fs19.createReadStream(path38, options);
30874
30874
  this.emit("stream", stream3);
30875
30875
  stream3.pipe(res);
30876
30876
  function cleanup() {
@@ -34039,7 +34039,7 @@ var require_tracer = __commonJS({
34039
34039
  };
34040
34040
  Object.defineProperty(exports, "__esModule", { value: true });
34041
34041
  exports.Tracer = void 0;
34042
- var fs20 = __importStar2(__require("fs"));
34042
+ var fs19 = __importStar2(__require("fs"));
34043
34043
  var path37 = __importStar2(__require("path"));
34044
34044
  var express_1 = __importDefault2(require_express2());
34045
34045
  var Tracer = class {
@@ -34058,8 +34058,8 @@ var require_tracer = __commonJS({
34058
34058
  * @param dirPath - Directory path to create
34059
34059
  */
34060
34060
  _ensureDirectoryExists(dirPath) {
34061
- if (!fs20.existsSync(dirPath)) {
34062
- fs20.mkdirSync(dirPath, { recursive: true });
34061
+ if (!fs19.existsSync(dirPath)) {
34062
+ fs19.mkdirSync(dirPath, { recursive: true });
34063
34063
  }
34064
34064
  }
34065
34065
  /**
@@ -34241,10 +34241,10 @@ var require_tracer = __commonJS({
34241
34241
  config: this._serializeForJson(configWithModel),
34242
34242
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
34243
34243
  };
34244
- fs20.writeFileSync(jsonPath, JSON.stringify(jsonData, null, 2), "utf-8");
34244
+ fs19.writeFileSync(jsonPath, JSON.stringify(jsonData, null, 2), "utf-8");
34245
34245
  const txtPath = filePathBase + ".txt";
34246
34246
  const formattedContent = this._formatHistory(history, configWithModel);
34247
- fs20.writeFileSync(txtPath, formattedContent, "utf-8");
34247
+ fs19.writeFileSync(txtPath, formattedContent, "utf-8");
34248
34248
  }
34249
34249
  /**
34250
34250
  * Format conversation history in a readable text format.
@@ -34455,10 +34455,10 @@ Finish Reason: ${message.finish_reason}`);
34455
34455
  if (!fullPath.startsWith(path37.resolve(this.cacheDir))) {
34456
34456
  return res.status(403).send("Access denied");
34457
34457
  }
34458
- if (!fs20.existsSync(fullPath)) {
34458
+ if (!fs19.existsSync(fullPath)) {
34459
34459
  return res.status(404).send("Path not found");
34460
34460
  }
34461
- if (fs20.statSync(fullPath).isFile()) {
34461
+ if (fs19.statSync(fullPath).isFile()) {
34462
34462
  try {
34463
34463
  const parts = subpath ? subpath.split("/") : [];
34464
34464
  const breadcrumbParts = [
@@ -34474,7 +34474,7 @@ Finish Reason: ${message.finish_reason}`);
34474
34474
  const breadcrumb = breadcrumbParts.join(" / ");
34475
34475
  const backUrl = this._prefixUrl(basePath, parts.length > 1 ? "/" + parts.slice(0, -1).join("/") : "/");
34476
34476
  if (fullPath.endsWith(".json")) {
34477
- const data = JSON.parse(fs20.readFileSync(fullPath, "utf-8"));
34477
+ const data = JSON.parse(fs19.readFileSync(fullPath, "utf-8"));
34478
34478
  const configItems = Object.entries(data.config || {}).filter(([key]) => key !== "trace_id").map(([key, value]) => {
34479
34479
  if (key === "system_prompt" && value != null) {
34480
34480
  return {
@@ -34622,7 +34622,7 @@ Finish Reason: ${message.finish_reason}`);
34622
34622
  const html = JSON_VIEWER_TEMPLATE(path37.basename(fullPath), breadcrumb, backUrl, configHtml, historyHtml, history.length, sidebarHtml);
34623
34623
  return res.send(html);
34624
34624
  } else {
34625
- const content = fs20.readFileSync(fullPath, "utf-8");
34625
+ const content = fs19.readFileSync(fullPath, "utf-8");
34626
34626
  const html = TEXT_VIEWER_TEMPLATE(path37.basename(fullPath), breadcrumb, backUrl, this._escapeHtml(content));
34627
34627
  return res.send(html);
34628
34628
  }
@@ -34632,10 +34632,10 @@ Finish Reason: ${message.finish_reason}`);
34632
34632
  }
34633
34633
  try {
34634
34634
  const sortBy = req.query["sort"] === "mtime" ? "mtime" : "name";
34635
- const entries = fs20.readdirSync(fullPath, { withFileTypes: true }).filter((entry) => entry.name !== ".DS_Store");
34635
+ const entries = fs19.readdirSync(fullPath, { withFileTypes: true }).filter((entry) => entry.name !== ".DS_Store");
34636
34636
  const entryStats = /* @__PURE__ */ new Map();
34637
34637
  for (const entry of entries) {
34638
- entryStats.set(entry.name, fs20.statSync(path37.join(fullPath, entry.name)));
34638
+ entryStats.set(entry.name, fs19.statSync(path37.join(fullPath, entry.name)));
34639
34639
  }
34640
34640
  entries.sort((a6, b6) => {
34641
34641
  const aIsDir = a6.isDirectory();
@@ -47013,7 +47013,7 @@ var require_util2 = __commonJS({
47013
47013
  exports.removeUndefinedValuesInObject = removeUndefinedValuesInObject;
47014
47014
  exports.isValidFile = isValidFile;
47015
47015
  exports.getWellKnownCertificateConfigFileLocation = getWellKnownCertificateConfigFileLocation;
47016
- var fs20 = __require("fs");
47016
+ var fs19 = __require("fs");
47017
47017
  var os5 = __require("os");
47018
47018
  var path37 = __require("path");
47019
47019
  var WELL_KNOWN_CERTIFICATE_CONFIG_FILE = "certificate_config.json";
@@ -47101,7 +47101,7 @@ var require_util2 = __commonJS({
47101
47101
  }
47102
47102
  async function isValidFile(filePath) {
47103
47103
  try {
47104
- const stats = await fs20.promises.lstat(filePath);
47104
+ const stats = await fs19.promises.lstat(filePath);
47105
47105
  return stats.isFile();
47106
47106
  } catch (e7) {
47107
47107
  return false;
@@ -49056,10 +49056,10 @@ var require_getCredentials = __commonJS({
49056
49056
  Object.defineProperty(exports, "__esModule", { value: true });
49057
49057
  exports.getCredentials = getCredentials;
49058
49058
  var path37 = __require("path");
49059
- var fs20 = __require("fs");
49059
+ var fs19 = __require("fs");
49060
49060
  var util_1 = __require("util");
49061
49061
  var errorWithCode_1 = require_errorWithCode();
49062
- var readFile6 = fs20.readFile ? (0, util_1.promisify)(fs20.readFile) : async () => {
49062
+ var readFile6 = fs19.readFile ? (0, util_1.promisify)(fs19.readFile) : async () => {
49063
49063
  throw new errorWithCode_1.ErrorWithCode("use key rather than keyFile.", "MISSING_CREDENTIALS");
49064
49064
  };
49065
49065
  var ExtensionFiles;
@@ -50736,12 +50736,12 @@ var require_filesubjecttokensupplier = __commonJS({
50736
50736
  Object.defineProperty(exports, "__esModule", { value: true });
50737
50737
  exports.FileSubjectTokenSupplier = void 0;
50738
50738
  var util_1 = __require("util");
50739
- var fs20 = __require("fs");
50740
- var readFile6 = (0, util_1.promisify)(fs20.readFile ?? (() => {
50739
+ var fs19 = __require("fs");
50740
+ var readFile6 = (0, util_1.promisify)(fs19.readFile ?? (() => {
50741
50741
  }));
50742
- var realpath3 = (0, util_1.promisify)(fs20.realpath ?? (() => {
50742
+ var realpath3 = (0, util_1.promisify)(fs19.realpath ?? (() => {
50743
50743
  }));
50744
- var lstat = (0, util_1.promisify)(fs20.lstat ?? (() => {
50744
+ var lstat = (0, util_1.promisify)(fs19.lstat ?? (() => {
50745
50745
  }));
50746
50746
  var FileSubjectTokenSupplier = class {
50747
50747
  filePath;
@@ -50859,7 +50859,7 @@ var require_certificatesubjecttokensupplier = __commonJS({
50859
50859
  Object.defineProperty(exports, "__esModule", { value: true });
50860
50860
  exports.CertificateSubjectTokenSupplier = exports.InvalidConfigurationError = exports.CertificateSourceUnavailableError = exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = void 0;
50861
50861
  var util_1 = require_util2();
50862
- var fs20 = __require("fs");
50862
+ var fs19 = __require("fs");
50863
50863
  var crypto_1 = __require("crypto");
50864
50864
  var https2 = __require("https");
50865
50865
  exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = "GOOGLE_API_CERTIFICATE_CONFIG";
@@ -50953,7 +50953,7 @@ var require_certificatesubjecttokensupplier = __commonJS({
50953
50953
  const configPath = this.certificateConfigPath;
50954
50954
  let fileContents;
50955
50955
  try {
50956
- fileContents = await fs20.promises.readFile(configPath, "utf8");
50956
+ fileContents = await fs19.promises.readFile(configPath, "utf8");
50957
50957
  } catch (err) {
50958
50958
  throw new CertificateSourceUnavailableError(`Failed to read certificate config file at: ${configPath}`);
50959
50959
  }
@@ -50978,14 +50978,14 @@ var require_certificatesubjecttokensupplier = __commonJS({
50978
50978
  async #getKeyAndCert(certPath, keyPath) {
50979
50979
  let cert, key;
50980
50980
  try {
50981
- cert = await fs20.promises.readFile(certPath);
50981
+ cert = await fs19.promises.readFile(certPath);
50982
50982
  new crypto_1.X509Certificate(cert);
50983
50983
  } catch (err) {
50984
50984
  const message = err instanceof Error ? err.message : String(err);
50985
50985
  throw new CertificateSourceUnavailableError(`Failed to read certificate file at ${certPath}: ${message}`);
50986
50986
  }
50987
50987
  try {
50988
- key = await fs20.promises.readFile(keyPath);
50988
+ key = await fs19.promises.readFile(keyPath);
50989
50989
  (0, crypto_1.createPrivateKey)(key);
50990
50990
  } catch (err) {
50991
50991
  const message = err instanceof Error ? err.message : String(err);
@@ -51004,7 +51004,7 @@ var require_certificatesubjecttokensupplier = __commonJS({
51004
51004
  return JSON.stringify([leafCert.raw.toString("base64")]);
51005
51005
  }
51006
51006
  try {
51007
- const chainPems = await fs20.promises.readFile(this.trustChainPath, "utf8");
51007
+ const chainPems = await fs19.promises.readFile(this.trustChainPath, "utf8");
51008
51008
  const pemBlocks = chainPems.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g) ?? [];
51009
51009
  const chainCerts = pemBlocks.map((pem, index) => {
51010
51010
  try {
@@ -51706,7 +51706,7 @@ var require_pluggable_auth_handler = __commonJS({
51706
51706
  exports.PluggableAuthHandler = exports.ExecutableError = void 0;
51707
51707
  var executable_response_1 = require_executable_response();
51708
51708
  var childProcess = __require("child_process");
51709
- var fs20 = __require("fs");
51709
+ var fs19 = __require("fs");
51710
51710
  var ExecutableError = class extends Error {
51711
51711
  /**
51712
51712
  * The exit code returned by the executable.
@@ -51791,14 +51791,14 @@ var require_pluggable_auth_handler = __commonJS({
51791
51791
  }
51792
51792
  let filePath;
51793
51793
  try {
51794
- filePath = await fs20.promises.realpath(this.outputFile);
51794
+ filePath = await fs19.promises.realpath(this.outputFile);
51795
51795
  } catch {
51796
51796
  return void 0;
51797
51797
  }
51798
- if (!(await fs20.promises.lstat(filePath)).isFile()) {
51798
+ if (!(await fs19.promises.lstat(filePath)).isFile()) {
51799
51799
  return void 0;
51800
51800
  }
51801
- const responseString = await fs20.promises.readFile(filePath, {
51801
+ const responseString = await fs19.promises.readFile(filePath, {
51802
51802
  encoding: "utf8"
51803
51803
  });
51804
51804
  if (responseString === "") {
@@ -52209,7 +52209,7 @@ var require_gdchclient = __commonJS({
52209
52209
  Object.defineProperty(exports, "__esModule", { value: true });
52210
52210
  exports.GdchClient = exports.GDCH_SERVICE_ACCOUNT_TYPE = void 0;
52211
52211
  var crypto3 = __require("crypto");
52212
- var fs20 = __require("fs");
52212
+ var fs19 = __require("fs");
52213
52213
  var https2 = __require("https");
52214
52214
  var oauth2client_1 = require_oauth2client();
52215
52215
  var DEFAULT_LIFETIME_IN_SECONDS = 3600;
@@ -52432,7 +52432,7 @@ var require_gdchclient = __commonJS({
52432
52432
  const currentPath = this.caCertPath;
52433
52433
  this.caAgentPromise = (async () => {
52434
52434
  try {
52435
- const ca = await fs20.promises.readFile(currentPath);
52435
+ const ca = await fs19.promises.readFile(currentPath);
52436
52436
  return new https2.Agent({ ca });
52437
52437
  } catch (err) {
52438
52438
  if (this.cachedCaCertPath === currentPath) {
@@ -52492,7 +52492,7 @@ var require_googleauth = __commonJS({
52492
52492
  Object.defineProperty(exports, "__esModule", { value: true });
52493
52493
  exports.GoogleAuth = exports.GoogleAuthExceptionMessages = void 0;
52494
52494
  var child_process_1 = __require("child_process");
52495
- var fs20 = __require("fs");
52495
+ var fs19 = __require("fs");
52496
52496
  var gaxios_1 = require_src3();
52497
52497
  var gcpMetadata = require_src5();
52498
52498
  var os5 = __require("os");
@@ -52794,7 +52794,7 @@ var require_googleauth = __commonJS({
52794
52794
  return null;
52795
52795
  }
52796
52796
  const location = path37.join(configDir, "application_default_credentials.json");
52797
- if (!fs20.existsSync(location)) {
52797
+ if (!fs19.existsSync(location)) {
52798
52798
  return null;
52799
52799
  }
52800
52800
  const client = await this._getApplicationCredentialsFromFilePath(location, options);
@@ -52811,8 +52811,8 @@ var require_googleauth = __commonJS({
52811
52811
  throw new Error("The file path is invalid.");
52812
52812
  }
52813
52813
  try {
52814
- filePath = fs20.realpathSync(filePath);
52815
- if (!fs20.lstatSync(filePath).isFile()) {
52814
+ filePath = fs19.realpathSync(filePath);
52815
+ if (!fs19.lstatSync(filePath).isFile()) {
52816
52816
  throw new Error();
52817
52817
  }
52818
52818
  } catch (err) {
@@ -52821,7 +52821,7 @@ var require_googleauth = __commonJS({
52821
52821
  }
52822
52822
  throw err;
52823
52823
  }
52824
- const readStream = fs20.createReadStream(filePath);
52824
+ const readStream = fs19.createReadStream(filePath);
52825
52825
  return this.fromStream(readStream, options);
52826
52826
  }
52827
52827
  /**
@@ -53149,7 +53149,7 @@ var require_googleauth = __commonJS({
53149
53149
  return this._cacheClientFromJSON(this.jsonContent, this.clientOptions);
53150
53150
  } else if (this.keyFilename) {
53151
53151
  const filePath = path37.resolve(this.keyFilename);
53152
- const stream2 = fs20.createReadStream(filePath);
53152
+ const stream2 = fs19.createReadStream(filePath);
53153
53153
  return await this.fromStreamAsync(stream2, this.clientOptions);
53154
53154
  } else if (this.apiKey) {
53155
53155
  const client = await this.fromAPIKey(this.apiKey, this.clientOptions);
@@ -57409,7 +57409,7 @@ var require_node3 = __commonJS({
57409
57409
  "use strict";
57410
57410
  var pRetry = require_p_retry();
57411
57411
  var googleAuthLibrary = require_src6();
57412
- var fs20 = __require("fs");
57412
+ var fs19 = __require("fs");
57413
57413
  var fs$1 = __require("fs/promises");
57414
57414
  var node_stream = __require("node:stream");
57415
57415
  var promises = __require("node:stream/promises");
@@ -74032,7 +74032,7 @@ ${underline}`);
74032
74032
  if (params.downloadPath) {
74033
74033
  const response = await downloadFile(params, apiClient);
74034
74034
  if (response instanceof HttpResponse2) {
74035
- const writer = fs20.createWriteStream(params.downloadPath);
74035
+ const writer = fs19.createWriteStream(params.downloadPath);
74036
74036
  const body = node_stream.Readable.fromWeb(response.responseInternal.body);
74037
74037
  body.pipe(writer);
74038
74038
  await promises.finished(writer);
@@ -106417,7 +106417,7 @@ var require_dist_cjs20 = __commonJS({
106417
106417
  var { setCredentialFeature: setCredentialFeature2 } = (init_client3(), __toCommonJS(client_exports2));
106418
106418
  var { CredentialsProviderError: CredentialsProviderError2 } = (init_config2(), __toCommonJS(config_exports));
106419
106419
  var { NodeHttpHandler } = require_dist_cjs15();
106420
- var fs20 = __require("node:fs/promises");
106420
+ var fs19 = __require("node:fs/promises");
106421
106421
  var { HttpRequest: HttpRequest2 } = (init_protocols(), __toCommonJS(protocols_exports));
106422
106422
  var { sdkStreamMixin: sdkStreamMixin4, parseRfc3339DateTime: parseRfc3339DateTime2 } = (init_serde(), __toCommonJS(serde_exports));
106423
106423
  var ECS_CONTAINER_HOST = "169.254.170.2";
@@ -106541,7 +106541,7 @@ Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
106541
106541
  const provider = retryWrapper(async () => {
106542
106542
  const request = createGetRequest(url2);
106543
106543
  if (tokenFile) {
106544
- request.headers.Authorization = validateToken((await fs20.readFile(tokenFile)).toString());
106544
+ request.headers.Authorization = validateToken((await fs19.readFile(tokenFile)).toString());
106545
106545
  } else if (token) {
106546
106546
  request.headers.Authorization = validateToken(token);
106547
106547
  }
@@ -159490,11 +159490,11 @@ var init_ajvProvider_97rDpkRx = __esm({
159490
159490
  if (!f8) throw new Error(`Unknown format "${name2}"`);
159491
159491
  return f8;
159492
159492
  };
159493
- function addFormats2(ajv, list2, fs20, exportName) {
159493
+ function addFormats2(ajv, list2, fs19, exportName) {
159494
159494
  var _a4;
159495
159495
  var _b;
159496
159496
  (_a4 = (_b = ajv.opts.code).formats) !== null && _a4 !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`);
159497
- for (const f8 of list2) ajv.addFormat(f8, fs20[f8]);
159497
+ for (const f8 of list2) ajv.addFormat(f8, fs19[f8]);
159498
159498
  }
159499
159499
  module.exports = exports = formatsPlugin;
159500
159500
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -164150,7 +164150,7 @@ var require_windows = __commonJS({
164150
164150
  "../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(exports, module) {
164151
164151
  module.exports = isexe;
164152
164152
  isexe.sync = sync;
164153
- var fs20 = __require("fs");
164153
+ var fs19 = __require("fs");
164154
164154
  function checkPathExt(path37, options) {
164155
164155
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
164156
164156
  if (!pathext) {
@@ -164175,12 +164175,12 @@ var require_windows = __commonJS({
164175
164175
  return checkPathExt(path37, options);
164176
164176
  }
164177
164177
  function isexe(path37, options, cb) {
164178
- fs20.stat(path37, function(er, stat6) {
164178
+ fs19.stat(path37, function(er, stat6) {
164179
164179
  cb(er, er ? false : checkStat(stat6, path37, options));
164180
164180
  });
164181
164181
  }
164182
164182
  function sync(path37, options) {
164183
- return checkStat(fs20.statSync(path37), path37, options);
164183
+ return checkStat(fs19.statSync(path37), path37, options);
164184
164184
  }
164185
164185
  }
164186
164186
  });
@@ -164190,14 +164190,14 @@ var require_mode = __commonJS({
164190
164190
  "../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(exports, module) {
164191
164191
  module.exports = isexe;
164192
164192
  isexe.sync = sync;
164193
- var fs20 = __require("fs");
164193
+ var fs19 = __require("fs");
164194
164194
  function isexe(path37, options, cb) {
164195
- fs20.stat(path37, function(er, stat6) {
164195
+ fs19.stat(path37, function(er, stat6) {
164196
164196
  cb(er, er ? false : checkStat(stat6, options));
164197
164197
  });
164198
164198
  }
164199
164199
  function sync(path37, options) {
164200
- return checkStat(fs20.statSync(path37), options);
164200
+ return checkStat(fs19.statSync(path37), options);
164201
164201
  }
164202
164202
  function checkStat(stat6, options) {
164203
164203
  return stat6.isFile() && checkMode(stat6, options);
@@ -164221,7 +164221,7 @@ var require_mode = __commonJS({
164221
164221
  // ../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
164222
164222
  var require_isexe = __commonJS({
164223
164223
  "../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(exports, module) {
164224
- var fs20 = __require("fs");
164224
+ var fs19 = __require("fs");
164225
164225
  var core;
164226
164226
  if (process.platform === "win32" || global.TESTING_WINDOWS) {
164227
164227
  core = require_windows();
@@ -164485,16 +164485,16 @@ var require_shebang_command = __commonJS({
164485
164485
  var require_readShebang = __commonJS({
164486
164486
  "../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
164487
164487
  "use strict";
164488
- var fs20 = __require("fs");
164488
+ var fs19 = __require("fs");
164489
164489
  var shebangCommand = require_shebang_command();
164490
164490
  function readShebang(command6) {
164491
164491
  const size = 150;
164492
164492
  const buffer = Buffer.alloc(size);
164493
164493
  let fd;
164494
164494
  try {
164495
- fd = fs20.openSync(command6, "r");
164496
- fs20.readSync(fd, buffer, 0, size, 0);
164497
- fs20.closeSync(fd);
164495
+ fd = fs19.openSync(command6, "r");
164496
+ fs19.readSync(fd, buffer, 0, size, 0);
164497
+ fs19.closeSync(fd);
164498
164498
  } catch (e7) {
164499
164499
  }
164500
164500
  return shebangCommand(buffer.toString());
@@ -176848,6 +176848,392 @@ ${record2}` : record2);
176848
176848
  }
176849
176849
  });
176850
176850
 
176851
+ // src/server/agent/goalState.ts
176852
+ import { promises as fs14 } from "node:fs";
176853
+ import path30 from "node:path";
176854
+ async function readGoalState(scratchpadDir2) {
176855
+ for (const name2 of [GOAL_FILE, GOAL_FILE_PAUSED]) {
176856
+ const parsed = await readGoalFile(path30.join(scratchpadDir2, name2));
176857
+ if (parsed) return parsed;
176858
+ }
176859
+ return null;
176860
+ }
176861
+ async function endGoalFile(scratchpadDir2) {
176862
+ const live = path30.join(scratchpadDir2, GOAL_FILE);
176863
+ const paused = path30.join(scratchpadDir2, GOAL_FILE_PAUSED);
176864
+ const hadLive = await exists(live);
176865
+ const hadPaused = await exists(paused);
176866
+ await fs14.rm(live, { force: true });
176867
+ await fs14.rm(paused, { force: true });
176868
+ return hadLive || hadPaused;
176869
+ }
176870
+ async function updateGoalFile(scratchpadDir2, patch) {
176871
+ const livePath = path30.join(scratchpadDir2, GOAL_FILE);
176872
+ const pausedPath = path30.join(scratchpadDir2, GOAL_FILE_PAUSED);
176873
+ const target = await exists(livePath) ? livePath : await exists(pausedPath) ? pausedPath : null;
176874
+ if (!target) return null;
176875
+ const current = await readGoalFile(target) ?? {
176876
+ objective: "",
176877
+ status: "active",
176878
+ budget: -1,
176879
+ round: 0,
176880
+ tokensUsed: 0
176881
+ };
176882
+ const next = { ...current };
176883
+ if (typeof patch.objective === "string" && patch.objective.trim()) next.objective = patch.objective.trim();
176884
+ if (typeof patch.tokensUsed === "number" && Number.isFinite(patch.tokensUsed)) {
176885
+ next.tokensUsed = Math.max(0, Math.round(patch.tokensUsed));
176886
+ }
176887
+ if (typeof patch.deltaBudget === "number" && Number.isFinite(patch.deltaBudget)) {
176888
+ next.budget = Math.max(0, Math.round(next.tokensUsed + patch.deltaBudget));
176889
+ } else if (typeof patch.budget === "number" && Number.isFinite(patch.budget)) {
176890
+ next.budget = patch.budget > 0 ? Math.round(patch.budget) : -1;
176891
+ }
176892
+ await writeGoalFile(target, next);
176893
+ return next;
176894
+ }
176895
+ async function readGoalFile(file) {
176896
+ try {
176897
+ const raw2 = await fs14.readFile(file, "utf8");
176898
+ const parsed = JSON.parse(raw2);
176899
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
176900
+ return {
176901
+ objective: typeof parsed.objective === "string" ? parsed.objective : "",
176902
+ status: typeof parsed.status === "string" ? parsed.status : "blocked",
176903
+ budget: Number.isFinite(parsed.budget) ? Number(parsed.budget) : -1,
176904
+ round: Number.isFinite(parsed.round) ? Number(parsed.round) : 0,
176905
+ tokensUsed: Number.isFinite(parsed.tokens_used) ? Number(parsed.tokens_used) : 0,
176906
+ ...parsed.ended === true ? { ended: true } : {}
176907
+ };
176908
+ } catch {
176909
+ return null;
176910
+ }
176911
+ }
176912
+ async function writeGoalFile(file, state2) {
176913
+ const payload2 = {
176914
+ objective: state2.objective,
176915
+ status: state2.status,
176916
+ budget: state2.budget,
176917
+ round: state2.round,
176918
+ tokens_used: state2.tokensUsed,
176919
+ ...state2.ended ? { ended: true } : {}
176920
+ };
176921
+ const tmp = file + ".tmp-" + process.pid + "-" + Date.now();
176922
+ await fs14.writeFile(tmp, JSON.stringify(payload2, null, 2) + "\n", "utf8");
176923
+ await fs14.rename(tmp, file);
176924
+ }
176925
+ async function exists(file) {
176926
+ try {
176927
+ await fs14.access(file);
176928
+ return true;
176929
+ } catch {
176930
+ return false;
176931
+ }
176932
+ }
176933
+ var GOAL_FILE, GOAL_FILE_PAUSED;
176934
+ var init_goalState = __esm({
176935
+ "src/server/agent/goalState.ts"() {
176936
+ "use strict";
176937
+ GOAL_FILE = "GOAL.json";
176938
+ GOAL_FILE_PAUSED = "GOAL.json.paused";
176939
+ }
176940
+ });
176941
+
176942
+ // src/server/agent/vendorPlugins.ts
176943
+ import { promises as fs15, existsSync as existsSync3 } from "node:fs";
176944
+ import path31 from "node:path";
176945
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
176946
+ function defaultVendorDir() {
176947
+ try {
176948
+ const near = path31.resolve(path31.dirname(fileURLToPath3(import.meta.url)), "vendor-plugins");
176949
+ if (existsSync3(near)) return near;
176950
+ return path31.resolve(path31.dirname(fileURLToPath3(import.meta.url)), "..", "..", "..", "vendor-plugins");
176951
+ } catch {
176952
+ return "";
176953
+ }
176954
+ }
176955
+ function setVendorPluginsDir(dir) {
176956
+ vendorDir = dir;
176957
+ }
176958
+ function vendorPluginsDir() {
176959
+ return vendorDir || defaultVendorDir();
176960
+ }
176961
+ async function readVendoredPlugin(name2) {
176962
+ const dir = path31.join(vendorPluginsDir(), name2);
176963
+ try {
176964
+ const raw2 = JSON.parse(await fs15.readFile(path31.join(dir, "plugin.json"), "utf8"));
176965
+ const version2 = typeof raw2.version === "string" ? raw2.version : "";
176966
+ if (!version2) return null;
176967
+ const files = await readDirText(path31.join(dir, "hooks"));
176968
+ if (!Object.keys(files).length) return null;
176969
+ const manifest = {
176970
+ name: name2,
176971
+ description: typeof raw2.description === "string" ? raw2.description : name2,
176972
+ ...typeof raw2.description_zh === "string" ? { description_zh: raw2.description_zh } : {},
176973
+ version: version2,
176974
+ // 只透传 SDK 认的三个 hook 点(plugin.json 里可能还有 category 等其它字段)
176975
+ stop: asCommandList(raw2.hooks?.stop),
176976
+ pre_tool_use: asCommandList(raw2.hooks?.pre_tool_use),
176977
+ user_prompt: asCommandList(raw2.hooks?.user_prompt)
176978
+ };
176979
+ let icon;
176980
+ try {
176981
+ icon = await fs15.readFile(path31.join(dir, "icon.svg"), "utf8");
176982
+ } catch {
176983
+ }
176984
+ return { name: name2, version: version2, manifest, files, ...icon !== void 0 ? { icon } : {} };
176985
+ } catch {
176986
+ return null;
176987
+ }
176988
+ }
176989
+ function asCommandList(raw2) {
176990
+ if (!Array.isArray(raw2)) return [];
176991
+ return raw2.flatMap((c6) => {
176992
+ const o3 = c6;
176993
+ if (!o3 || typeof o3.command !== "string" || !o3.command) return [];
176994
+ return [{ command: o3.command, ...typeof o3.timeout === "number" ? { timeout: o3.timeout } : {} }];
176995
+ });
176996
+ }
176997
+ async function readDirText(dir) {
176998
+ const out = {};
176999
+ const walk2 = async (abs, rel) => {
177000
+ const entries = await fs15.readdir(abs, { withFileTypes: true });
177001
+ for (const e7 of entries) {
177002
+ const childRel = rel ? rel + "/" + e7.name : e7.name;
177003
+ if (e7.isDirectory()) await walk2(path31.join(abs, e7.name), childRel);
177004
+ else if (e7.isFile()) out[childRel] = await fs15.readFile(path31.join(abs, e7.name), "utf8");
177005
+ }
177006
+ };
177007
+ try {
177008
+ await walk2(dir, "");
177009
+ } catch {
177010
+ return {};
177011
+ }
177012
+ return out;
177013
+ }
177014
+ var vendorDir;
177015
+ var init_vendorPlugins = __esm({
177016
+ "src/server/agent/vendorPlugins.ts"() {
177017
+ "use strict";
177018
+ vendorDir = "";
177019
+ }
177020
+ });
177021
+
177022
+ // src/server/agent/goal.ts
177023
+ var goal_exports = {};
177024
+ __export(goal_exports, {
177025
+ GOAL_HOOK_NAME: () => GOAL_HOOK_NAME,
177026
+ GoalFiles: () => GoalFiles,
177027
+ askGoalStop: () => askGoalStop,
177028
+ ensureGoalInstalled: () => ensureGoalInstalled,
177029
+ makeScriptRunner: () => makeScriptRunner
177030
+ });
177031
+ import { promises as fs16 } from "node:fs";
177032
+ import path32 from "node:path";
177033
+ function sameVersion(installed, library) {
177034
+ return typeof installed === "string" && installed === library;
177035
+ }
177036
+ function withHostTrigger(manifest) {
177037
+ const userPrompt = manifest.user_prompt.map((cmd) => ({ ...cmd, trigger: "host" }));
177038
+ return { ...manifest, user_prompt: userPrompt };
177039
+ }
177040
+ async function goalSdkPorts(deps) {
177041
+ const { libraryPlugin: libraryPlugin2, listInstalledHooks: listInstalledHooks2, installHook: installHook2 } = deps;
177042
+ const vendoredPlugin = deps.vendoredPlugin ?? readVendoredPlugin;
177043
+ if (libraryPlugin2 && listInstalledHooks2 && installHook2) {
177044
+ return { libraryPlugin: libraryPlugin2, listInstalledHooks: listInstalledHooks2, installHook: installHook2, vendoredPlugin };
177045
+ }
177046
+ const sdk = await Promise.resolve().then(() => (init_dist6(), dist_exports));
177047
+ return {
177048
+ vendoredPlugin,
177049
+ libraryPlugin: libraryPlugin2 ?? ((name2) => sdk.libraryPlugin(name2)),
177050
+ listInstalledHooks: listInstalledHooks2 ?? ((root6, projectId, agentId) => sdk.listInstalledHooks(root6, projectId, agentId)),
177051
+ installHook: installHook2 ?? ((root6, projectId, agentId, manifest, files, icon) => sdk.installHook(root6, projectId, agentId, manifest, files, icon))
177052
+ };
177053
+ }
177054
+ function unavailable(reason) {
177055
+ console.warn("[agent] goal hook \u672A\u5B89\u88C5\uFF1A" + reason);
177056
+ return { installed: false, status: "unavailable", reason };
177057
+ }
177058
+ async function ensureGoalInstalled(root6, projectId, agentId, deps = {}) {
177059
+ try {
177060
+ const sdk = await goalSdkPorts(deps);
177061
+ const vendored = await sdk.vendoredPlugin(GOAL_HOOK_NAME);
177062
+ const fromSdk = vendored ? null : sdk.libraryPlugin(GOAL_HOOK_NAME);
177063
+ const manifest = vendored?.manifest ?? fromSdk?.hooks?.manifest;
177064
+ if (!manifest) {
177065
+ if (!fromSdk) return unavailable(`\u63D2\u4EF6\u5E93\u91CC\u6CA1\u6709 ${GOAL_HOOK_NAME}\uFF08libraryPlugin \u8FD4\u56DE\u7A7A\uFF09`);
177066
+ return unavailable(`${GOAL_HOOK_NAME} \u63D2\u4EF6\u4E0D\u5E26 hook \u5305`);
177067
+ }
177068
+ const files = vendored?.files ?? fromSdk?.hooks?.files ?? {};
177069
+ const icon = vendored?.icon ?? fromSdk?.icon;
177070
+ const installed = (await sdk.listInstalledHooks(root6, projectId, agentId)).find(
177071
+ (hook) => hook.name === GOAL_HOOK_NAME
177072
+ );
177073
+ if (installed && sameVersion(installed.version, manifest.version)) {
177074
+ return {
177075
+ installed: true,
177076
+ status: "up-to-date",
177077
+ reason: `\u5DF2\u88C5 v${manifest.version}\uFF0C\u65E0\u9700\u91CD\u5199`,
177078
+ version: manifest.version
177079
+ };
177080
+ }
177081
+ await sdk.installHook(root6, projectId, agentId, withHostTrigger(manifest), files, icon);
177082
+ const status = installed ? "updated" : "installed";
177083
+ return {
177084
+ installed: true,
177085
+ status,
177086
+ reason: `${status === "updated" ? "\u7248\u672C\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u91CD\u88C5" : "\u5DF2\u5B89\u88C5"} v${manifest.version}`,
177087
+ version: manifest.version
177088
+ };
177089
+ } catch (err) {
177090
+ const reason = err instanceof Error ? err.message : String(err);
177091
+ console.warn("[agent] goal hook \u5B89\u88C5\u5931\u8D25\uFF1A" + reason);
177092
+ return { installed: false, status: "failed", reason };
177093
+ }
177094
+ }
177095
+ function makeScriptRunner(hooksDir2) {
177096
+ return async (scriptPath, input) => {
177097
+ const { spawn: spawn3 } = await import("node:child_process");
177098
+ return new Promise((resolve, reject) => {
177099
+ const child = spawn3(process.execPath, [path32.join(hooksDir2, scriptPath)], {
177100
+ stdio: ["pipe", "pipe", "pipe"]
177101
+ });
177102
+ let out = "";
177103
+ let err = "";
177104
+ child.stdout.on("data", (d6) => out += String(d6));
177105
+ child.stderr.on("data", (d6) => err += String(d6));
177106
+ child.on("error", reject);
177107
+ child.on("close", (code) => {
177108
+ if (code === 0) resolve(out);
177109
+ else reject(new Error("hook \u811A\u672C\u9000\u51FA\u7801 " + code + "\uFF1A" + err.slice(0, 200)));
177110
+ });
177111
+ child.stdin.end(JSON.stringify(input));
177112
+ });
177113
+ };
177114
+ }
177115
+ async function askGoalStop(run3, sessionId, tracePath) {
177116
+ const raw2 = (await run3("stop.mjs", { hook: "stop", session_id: sessionId, trace_path: tracePath })).trim();
177117
+ if (!raw2) return null;
177118
+ try {
177119
+ const parsed = JSON.parse(raw2);
177120
+ const decision = parsed.decision === "continue" || parsed.decision === "stop" ? parsed.decision : null;
177121
+ if (!decision) return null;
177122
+ return {
177123
+ decision,
177124
+ ...typeof parsed.reason === "string" ? { reason: parsed.reason } : {},
177125
+ ...typeof parsed.input === "string" ? { input: parsed.input } : {},
177126
+ ...parsed.output && typeof parsed.output === "object" ? { output: parsed.output } : {}
177127
+ };
177128
+ } catch {
177129
+ return null;
177130
+ }
177131
+ }
177132
+ async function fileExists2(file) {
177133
+ try {
177134
+ await fs16.access(file);
177135
+ return true;
177136
+ } catch {
177137
+ return false;
177138
+ }
177139
+ }
177140
+ var GOAL_HOOK_NAME, REALLY_FINISHED, GoalFiles;
177141
+ var init_goal = __esm({
177142
+ "src/server/agent/goal.ts"() {
177143
+ "use strict";
177144
+ init_goalState();
177145
+ init_vendorPlugins();
177146
+ GOAL_HOOK_NAME = "goal";
177147
+ REALLY_FINISHED = /* @__PURE__ */ new Set(["complete", "blocked", "budget_limited"]);
177148
+ GoalFiles = class {
177149
+ constructor(scratchpadDir2) {
177150
+ this.scratchpadDir = scratchpadDir2;
177151
+ }
177152
+ scratchpadDir;
177153
+ get live() {
177154
+ return path32.join(this.scratchpadDir, GOAL_FILE);
177155
+ }
177156
+ get paused() {
177157
+ return path32.join(this.scratchpadDir, GOAL_FILE_PAUSED);
177158
+ }
177159
+ read() {
177160
+ return readGoalState(this.scratchpadDir);
177161
+ }
177162
+ async exists() {
177163
+ for (const f8 of [this.live, this.paused]) {
177164
+ try {
177165
+ await fs16.access(f8);
177166
+ return true;
177167
+ } catch {
177168
+ }
177169
+ }
177170
+ return false;
177171
+ }
177172
+ /**
177173
+ * 暂停:把文件改名挪走(内容原样)。
177174
+ *
177175
+ * 为什么不是改 status:插件只认 active / wrapping_up / complete / blocked,
177176
+ * 写别的值会被判成"协议外的坏通道" ⇒ 直接 blocked 收场(不是暂停,是搞砸)。
177177
+ * 文件缺席则下一轮结束时 stop.mjs 读不到 ⇒ 静默退出 ⇒ 官方自动连播自然停住。
177178
+ */
177179
+ async pause() {
177180
+ if (!await fileExists2(this.live)) return false;
177181
+ await fs16.rm(this.paused, { force: true });
177182
+ await fs16.rename(this.live, this.paused);
177183
+ return true;
177184
+ }
177185
+ /** 启动:文件改回原名(status / round / tokens_used 原样接上) */
177186
+ async resume() {
177187
+ if (!await fileExists2(this.paused)) return false;
177188
+ await fs16.rm(this.live, { force: true });
177189
+ await fs16.rename(this.paused, this.live);
177190
+ return true;
177191
+ }
177192
+ /**
177193
+ * 把「被中止」的目标**重新打开**(用户口径 2026-10-11)。
177194
+ *
177195
+ * 为什么需要:用户在界面上点「终止」时,插件的 stop hook 会把 GOAL.json 写成
177196
+ * `status:'aborted' + ended:true` —— 那是「**这一轮**结束了,别再自动续轮」,
177197
+ * 不是「目标作废」。文件仍以 **live 名**躺着(不是 .paused),所以只调 resume()
177198
+ * 什么也做不了(它只认 .paused)。
177199
+ *
177200
+ * 这里的口径:把终态标记清掉(`ended` 去掉、`status` 回 active),让插件下一轮
177201
+ * 重新把它当成进行中的目标。**只处理"中止"这一种**:真完成 / 受阻 / 预算用尽
177202
+ * 属于真收尾,不在这里复活(调用方负责判断)。
177203
+ *
177204
+ * 返回 true = 确实改写了文件(原本就是可续跑状态时返回 false,调用方按"无需重开"处理)。
177205
+ */
177206
+ async reopen() {
177207
+ const current = await this.read();
177208
+ if (!current) return false;
177209
+ if (!await fileExists2(this.live)) return false;
177210
+ if (REALLY_FINISHED.has(current.status)) return false;
177211
+ const next = { ...current, status: "active" };
177212
+ delete next.ended;
177213
+ await writeGoalFile(this.live, next);
177214
+ return true;
177215
+ }
177216
+ /** 结束目标:两份状态文件都删掉(与「暂停」不同,不留可恢复的副本) */
177217
+ end() {
177218
+ return endGoalFile(this.scratchpadDir);
177219
+ }
177220
+ /**
177221
+ * 暂停态下"守住缺席":当前轮里模型可能自己写回 GOAL.json(比如它认为完成了),
177222
+ * 那样文件就"复活"、官方循环会继续 —— 暂停失效。
177223
+ *
177224
+ * 所以每轮结束都调一次:发现 live 又出现了就再挪走(保留最新内容,状态仍是暂停)。
177225
+ * 返回 true = 这次真的收走了一个复活的文件。
177226
+ */
177227
+ async enforcePaused() {
177228
+ if (!await fileExists2(this.live)) return false;
177229
+ await fs16.rm(this.paused, { force: true });
177230
+ await fs16.rename(this.live, this.paused);
177231
+ return true;
177232
+ }
177233
+ };
177234
+ }
177235
+ });
177236
+
176851
177237
  // src/server/agent/chatCompletion.ts
176852
177238
  var chatCompletion_exports = {};
176853
177239
  __export(chatCompletion_exports, {
@@ -177074,11 +177460,11 @@ var AGENT_ID = "canvas-agent";
177074
177460
  function agentRoot(root6) {
177075
177461
  return path25.join(root6, "agent");
177076
177462
  }
177077
- function agentDirPath(root6) {
177078
- return path25.join(agentRoot(root6), AGENT_PROJECT_ID, "agents", AGENT_ID);
177463
+ function agentDirPath(root6, agentId = AGENT_ID) {
177464
+ return path25.join(agentRoot(root6), AGENT_PROJECT_ID, "agents", agentId);
177079
177465
  }
177080
- function agentStateDir2(root6) {
177081
- return path25.join(agentDirPath(root6), "agent_state");
177466
+ function agentStateDir2(root6, agentId = AGENT_ID) {
177467
+ return path25.join(agentDirPath(root6, agentId), "agent_state");
177082
177468
  }
177083
177469
  function agentSkillSources() {
177084
177470
  const home = process.env.USERPROFILE ?? process.env.HOME ?? os3.homedir();
@@ -177104,9 +177490,12 @@ function canvasSessionFile(root6, canvasId, sessionId) {
177104
177490
  function canvasWorkspaceDir(root6, canvasId) {
177105
177491
  return path25.join(canvasAgentDir(root6, canvasId), "workspace");
177106
177492
  }
177107
- function sessionScratchpadPath(root6, sessionId) {
177493
+ function sessionScratchpadPath(root6, sessionId, agentId = AGENT_ID) {
177108
177494
  if (!isSafeSessionId(sessionId)) throw new Error("[agentPaths] \u975E\u6CD5\u4F1A\u8BDD id: " + sessionId);
177109
- return path25.join(root6, AGENT_PROJECT_ID, "agents", AGENT_ID, "scratchpad", sessionId);
177495
+ return path25.join(root6, AGENT_PROJECT_ID, "agents", agentId, "scratchpad", sessionId);
177496
+ }
177497
+ function sharedSkillsDir(dataRoot) {
177498
+ return path25.join(dataRoot, "skills");
177110
177499
  }
177111
177500
 
177112
177501
  // src/server/agent/configShared.ts
@@ -177120,7 +177509,8 @@ import path26 from "node:path";
177120
177509
  function buildRuntimeContext(deps) {
177121
177510
  const dataRoot = deps.dataRoot;
177122
177511
  const root6 = agentRoot(dataRoot);
177123
- const stateDir = path26.join(root6, AGENT_PROJECT_ID, "agents", AGENT_ID, "agent_state");
177512
+ const agentId = deps.agentId ?? AGENT_ID;
177513
+ const stateDir = path26.join(root6, AGENT_PROJECT_ID, "agents", agentId, "agent_state");
177124
177514
  return {
177125
177515
  baseUrl: (deps.baseUrl ?? "").replace(/\/+$/, ""),
177126
177516
  dataRoot,
@@ -177129,7 +177519,8 @@ function buildRuntimeContext(deps) {
177129
177519
  taskScriptsDir: path26.join(dataRoot, "task-scripts"),
177130
177520
  agentStateDir: stateDir,
177131
177521
  skillsDir: path26.join(stateDir, "skills"),
177132
- scratchpadRoot: path26.join(root6, AGENT_PROJECT_ID, "agents", AGENT_ID, "scratchpad")
177522
+ scratchpadRoot: path26.join(root6, AGENT_PROJECT_ID, "agents", agentId, "scratchpad"),
177523
+ agentId
177133
177524
  };
177134
177525
  }
177135
177526
  function slash(p3) {
@@ -177163,7 +177554,7 @@ function agentContextPlaceholders(ctx) {
177163
177554
  { token: "{{CWD}}", value: "", description: "\u672C\u4F1A\u8BDD\u7684\u5DE5\u4F5C\u76EE\u5F55\uFF08\u6BCF\u4E2A\u753B\u5E03\u4E00\u4E2A\uFF09", source: "harness" },
177164
177555
  { token: "{{SESSION_ID}}", value: "", description: "\u672C\u4F1A\u8BDD\u7684 id", source: "harness" },
177165
177556
  { token: "{{PROJECT_DIR}}", value: "", description: "App Data Dir\uFF08\u5373\u6570\u636E\u6839\uFF09", source: "harness" },
177166
- { token: "{{AGENT_ID}}", value: AGENT_ID, description: "Agent id", source: "harness" },
177557
+ { token: "{{AGENT_ID}}", value: ctx.agentId ?? AGENT_ID, description: "Agent id", source: "harness" },
177167
177558
  { token: "{{DATE}}", value: today(), description: "\u4ECA\u5929\uFF08\u672C\u5730\u65E5\u671F\uFF09", source: "harness" },
177168
177559
  { token: "{{PLATFORM}}", value: process.platform, description: "\u8FD0\u884C\u5E73\u53F0", source: "harness" },
177169
177560
  { token: "{{OS_VERSION}}", value: osVersion(), description: "\u64CD\u4F5C\u7CFB\u7EDF\u7248\u672C", source: "harness" },
@@ -177195,6 +177586,7 @@ function agentContextInfo(ctx) {
177195
177586
  { label: "\u540E\u53F0\u529F\u80FD\u811A\u672C", path: slash(ctx.taskScriptsDir) },
177196
177587
  { label: "Agent \u72B6\u6001", path: slash(ctx.agentStateDir) },
177197
177588
  { label: "\u6280\u80FD", path: slash(ctx.skillsDir) },
177589
+ { label: "\u5171\u4EAB\u6280\u80FD\u5E93", path: slash(path26.join(ctx.dataRoot, "skills")) },
177198
177590
  { label: "\u4F1A\u8BDD\u8349\u7A3F", path: slash(ctx.scratchpadRoot) }
177199
177591
  ],
177200
177592
  placeholders: agentContextPlaceholders(ctx)
@@ -177278,13 +177670,13 @@ async function walk(dir, prefix = "") {
177278
177670
  }
177279
177671
  return out;
177280
177672
  }
177281
- async function loadSystemConfig(root6) {
177282
- const state2 = await loadAgentState({ agentId: AGENT_ID, projectId: AGENT_PROJECT_ID, root: root6 });
177673
+ async function loadSystemConfig(root6, agentId = AGENT_ID) {
177674
+ const state2 = await loadAgentState({ agentId, projectId: AGENT_PROJECT_ID, root: root6 });
177283
177675
  return state2.systemConfig;
177284
177676
  }
177285
- async function writeSystemConfig(root6, cfg) {
177677
+ async function writeSystemConfig(root6, cfg, agentId = AGENT_ID) {
177286
177678
  const yaml = await Promise.resolve().then(() => __toESM(require_dist(), 1));
177287
- const target = systemConfigPath(root6, AGENT_PROJECT_ID, AGENT_ID);
177679
+ const target = systemConfigPath(root6, AGENT_PROJECT_ID, agentId);
177288
177680
  await fs10.mkdir(path27.dirname(target), { recursive: true });
177289
177681
  await fs10.writeFile(target, yaml.stringify(cfg, { lineWidth: 0 }), "utf8");
177290
177682
  }
@@ -177325,7 +177717,7 @@ function templateMissing(template) {
177325
177717
  }
177326
177718
 
177327
177719
  // src/server/agent/configShared.ts
177328
- var AgentConfigBase = class {
177720
+ var AgentConfigBase = class _AgentConfigBase {
177329
177721
  /**
177330
177722
  * @param deps.kv 宿主注入的小数据 KV(与 /api/kv 同一份 settings.json)。
177331
177723
  * 必须注入,不给默认实现:默认一份内存 KV 会让「提示词改完重启就没了」这种坑
@@ -177338,11 +177730,46 @@ var AgentConfigBase = class {
177338
177730
  }
177339
177731
  dataRoot;
177340
177732
  deps;
177733
+ /**
177734
+ * 共享技能名 → Agent 技能目录名。
177735
+ *
177736
+ * SDK 的 skill_name 只允许字母 / 数字 / `_` / `-`(`seedance-2.0` 里的点会让 installSkill 直接抛错)。
177737
+ * 共享库保留用户看得懂的原名(`.plume/skills/seedance-2.0`),挂到 Agent 时把不合法字符换成 `_`,
177738
+ * 并在目录里写一份 `link.json` 记住原名 —— 读列表 / 卸载 / 引用都靠它还原。
177739
+ */
177740
+ static linkIdOf(sharedName) {
177741
+ return sharedName.replace(/[^A-Za-z0-9_-]/g, "_");
177742
+ }
177743
+ /**
177744
+ * 当前配置作用于哪个 Agent 目录。
177745
+ *
177746
+ * 为什么是一个可切换字段而不是常量:设置页要在多个 Agent 之间切换;
177747
+ * 每切一次,技能 / MCP / 提示词 / 模板读写都应落到那一个 agent_state 下。
177748
+ * 模型表不在这里 —— 它按 Project 共享(见 config.ts)。
177749
+ */
177750
+ agentId = AGENT_ID;
177751
+ /** 切换当前 Agent(调用方负责做合法性校验) */
177752
+ setAgentId(agentId) {
177753
+ if (agentId === this.agentId) return;
177754
+ this.agentId = agentId;
177755
+ this.initPromise = void 0;
177756
+ }
177757
+ getAgentId() {
177758
+ return this.agentId;
177759
+ }
177760
+ /**
177761
+ * 当前 Agent 的配置根(`.../agents/<agentId>`)。引导 / Trace 等按 Agent 分家的数据要用它。
177762
+ *
177763
+ * 返回 SDK 口径的 root + agentId,调用方别再自己拼 `agents/<id>` —— 路径规则只留一份。
177764
+ */
177765
+ sdkAgent() {
177766
+ return { root: this.sdkRoot, projectId: AGENT_PROJECT_ID, agentId: this.agentId };
177767
+ }
177341
177768
  /** Agent 的系统提示词(agent_state/AGENTS.md) */
177342
177769
  async systemPrompt() {
177343
177770
  await this.ensureInit();
177344
177771
  try {
177345
- const raw2 = await fs11.readFile(agentsMdPath(this.sdkRoot, AGENT_PROJECT_ID, AGENT_ID), "utf8");
177772
+ const raw2 = await fs11.readFile(agentsMdPath(this.sdkRoot, AGENT_PROJECT_ID, this.agentId), "utf8");
177346
177773
  return raw2;
177347
177774
  } catch {
177348
177775
  return "";
@@ -177357,7 +177784,7 @@ var AgentConfigBase = class {
177357
177784
  await this.ensureInit();
177358
177785
  const release2 = await this.acquirePromptLock();
177359
177786
  try {
177360
- const target = agentsMdPath(this.sdkRoot, AGENT_PROJECT_ID, AGENT_ID);
177787
+ const target = agentsMdPath(this.sdkRoot, AGENT_PROJECT_ID, this.agentId);
177361
177788
  await fs11.mkdir(path28.dirname(target), { recursive: true });
177362
177789
  await fs11.writeFile(target, text, "utf8");
177363
177790
  } finally {
@@ -177382,7 +177809,7 @@ var AgentConfigBase = class {
177382
177809
  await this.ensureInit();
177383
177810
  const release2 = await this.acquirePromptLock();
177384
177811
  let previous = "";
177385
- const target = agentsMdPath(this.sdkRoot, AGENT_PROJECT_ID, AGENT_ID);
177812
+ const target = agentsMdPath(this.sdkRoot, AGENT_PROJECT_ID, this.agentId);
177386
177813
  let templateRaw = "";
177387
177814
  let templateExpanded = "";
177388
177815
  try {
@@ -177390,12 +177817,12 @@ var AgentConfigBase = class {
177390
177817
  await fs11.mkdir(path28.dirname(target), { recursive: true });
177391
177818
  const combined = [previous.trim(), text].filter(Boolean).join("\n\n");
177392
177819
  await fs11.writeFile(target, this.expandContext(combined), "utf8");
177393
- const cfg = await loadSystemConfig(this.sdkRoot);
177820
+ const cfg = await loadSystemConfig(this.sdkRoot, this.agentId);
177394
177821
  templateRaw = String(cfg.system_prompt ?? "");
177395
177822
  templateExpanded = this.expandContext(templateRaw);
177396
177823
  if (templateExpanded !== templateRaw) {
177397
177824
  await this.withConfigLock(
177398
- () => writeSystemConfig(this.sdkRoot, { ...cfg, system_prompt: templateExpanded })
177825
+ () => writeSystemConfig(this.sdkRoot, { ...cfg, system_prompt: templateExpanded }, this.agentId)
177399
177826
  );
177400
177827
  }
177401
177828
  } catch (err) {
@@ -177414,9 +177841,9 @@ var AgentConfigBase = class {
177414
177841
  try {
177415
177842
  if (templateExpanded && templateExpanded !== templateRaw) {
177416
177843
  await this.withConfigLock(async () => {
177417
- const fresh = await loadSystemConfig(this.sdkRoot);
177844
+ const fresh = await loadSystemConfig(this.sdkRoot, this.agentId);
177418
177845
  if (String(fresh.system_prompt ?? "") !== templateExpanded) return;
177419
- await writeSystemConfig(this.sdkRoot, { ...fresh, system_prompt: templateRaw });
177846
+ await writeSystemConfig(this.sdkRoot, { ...fresh, system_prompt: templateRaw }, this.agentId);
177420
177847
  });
177421
177848
  }
177422
177849
  } catch {
@@ -177580,7 +178007,7 @@ var AgentConfigBase = class {
177580
178007
  */
177581
178008
  async templateHealth() {
177582
178009
  await this.ensureInit();
177583
- const cfg = await loadSystemConfig(this.sdkRoot);
178010
+ const cfg = await loadSystemConfig(this.sdkRoot, this.agentId);
177584
178011
  const template = String(cfg.system_prompt ?? "");
177585
178012
  const missing = templateMissing(template);
177586
178013
  return { ok: missing.length === 0, missing, template };
@@ -177610,9 +178037,9 @@ var AgentConfigBase = class {
177610
178037
  async restoreTemplate() {
177611
178038
  await this.ensureInit();
177612
178039
  await this.withConfigLock(async () => {
177613
- const cfg = await loadSystemConfig(this.sdkRoot);
178040
+ const cfg = await loadSystemConfig(this.sdkRoot, this.agentId);
177614
178041
  const next = { ...cfg, system_prompt: defaultSystemConfig().system_prompt };
177615
- await writeSystemConfig(this.sdkRoot, next);
178042
+ await writeSystemConfig(this.sdkRoot, next, this.agentId);
177616
178043
  });
177617
178044
  return { ok: true, missing: [] };
177618
178045
  }
@@ -177634,8 +178061,8 @@ var AgentConfigBase = class {
177634
178061
  throw new Error("\u6A21\u677F\u91CC\u5FC5\u987B\u6709 {{AGENTS_MD}}\uFF0C\u5426\u5219 Agent \u63D0\u793A\u8BCD\u548C\u6A21\u5F0F\u63D0\u793A\u8BCD\u90FD\u8FDB\u4E0D\u53BB\u6A21\u578B");
177635
178062
  }
177636
178063
  await this.withConfigLock(async () => {
177637
- const cfg = await loadSystemConfig(this.sdkRoot);
177638
- await writeSystemConfig(this.sdkRoot, { ...cfg, system_prompt: next });
178064
+ const cfg = await loadSystemConfig(this.sdkRoot, this.agentId);
178065
+ await writeSystemConfig(this.sdkRoot, { ...cfg, system_prompt: next }, this.agentId);
177639
178066
  });
177640
178067
  return { ok: missing.length === 0, missing };
177641
178068
  }
@@ -177692,7 +178119,7 @@ var AgentConfigBase = class {
177692
178119
  /** 保证 Agent 已经初始化(幂等、串行),之后所有读都可以安全并行 */
177693
178120
  ensureInit() {
177694
178121
  this.initPromise ??= loadAgentState({
177695
- agentId: AGENT_ID,
178122
+ agentId: this.agentId,
177696
178123
  projectId: AGENT_PROJECT_ID,
177697
178124
  root: this.sdkRoot,
177698
178125
  init: {}
@@ -177705,8 +178132,8 @@ var AgentConfigBase = class {
177705
178132
  // ------------------------------------------------------------------- 技能
177706
178133
  async skills() {
177707
178134
  await this.ensureInit();
177708
- const installed = await listInstalledSkills(this.sdkRoot, AGENT_PROJECT_ID, AGENT_ID);
177709
- const dir = skillsDir(this.sdkRoot, AGENT_PROJECT_ID, AGENT_ID);
178135
+ const installed = await listInstalledSkills(this.sdkRoot, AGENT_PROJECT_ID, this.agentId);
178136
+ const dir = skillsDir(this.sdkRoot, AGENT_PROJECT_ID, this.agentId);
177710
178137
  const out = [];
177711
178138
  for (const s3 of installed) {
177712
178139
  let size = 0;
@@ -177718,7 +178145,19 @@ var AgentConfigBase = class {
177718
178145
  size = md ? (await fs11.stat(md.abs)).size : 0;
177719
178146
  } catch {
177720
178147
  }
177721
- out.push({ name: s3.name, description: s3.description ?? "", size, fileCount, dir: path28.join(dir, s3.name) });
178148
+ const linkFile = path28.join(dir, s3.name, "link.json");
178149
+ const link = await fs11.readFile(linkFile, "utf8").then((t2) => JSON.parse(t2)).catch(() => void 0);
178150
+ const sharedName = typeof link?.sharedName === "string" ? link.sharedName : s3.name;
178151
+ const shared = typeof link?.sharedDir === "string" && link.sharedDir ? link.sharedDir : path28.join(sharedSkillsDir(this.dataRoot), sharedName);
178152
+ const linked = typeof link?.sharedDir === "string" && !!link.sharedDir;
178153
+ out.push({
178154
+ name: sharedName,
178155
+ description: s3.description ?? "",
178156
+ size,
178157
+ fileCount,
178158
+ dir: path28.join(dir, s3.name),
178159
+ ...linked ? { sharedDir: shared } : {}
178160
+ });
177722
178161
  }
177723
178162
  return out;
177724
178163
  }
@@ -177772,17 +178211,118 @@ var AgentConfigBase = class {
177772
178211
  if (f8.rel.toLowerCase() === "skill.md") continue;
177773
178212
  aux[f8.rel] = (await fs11.readFile(f8.abs)).toString("utf8");
177774
178213
  }
177775
- await installSkill(this.sdkRoot, AGENT_PROJECT_ID, AGENT_ID, { name: name2, content, files: aux });
178214
+ await installSkill(this.sdkRoot, AGENT_PROJECT_ID, this.agentId, { name: name2, content, files: aux });
177776
178215
  return name2;
177777
178216
  }
177778
178217
  async removeSkill(name2) {
177779
- await removeSkill(this.sdkRoot, AGENT_PROJECT_ID, AGENT_ID, name2);
178218
+ await removeSkill(this.sdkRoot, AGENT_PROJECT_ID, this.agentId, _AgentConfigBase.linkIdOf(name2));
178219
+ }
178220
+ /**
178221
+ * 把一个**共享库里的技能**挂到当前 Agent。
178222
+ *
178223
+ * 不复制真实内容:只写一份 `SKILL.md` 指路文件,正文告诉模型
178224
+ * 「完整说明书与附属文件在 <共享目录>,用 read_file 去读」。
178225
+ *
178226
+ * 为什么不能用系统快捷方式:SDK 用 `Dirent.isDirectory()` 判断技能目录,
178227
+ * 链接 / junction 会被跳过(见 listInstalledSkills);必须是一个普通目录。
178228
+ * 为什么不用 installSkill 复制:那会为每个 Agent 复制整包(含 28 个子技能),
178229
+ * 用户明确不要这种复制。
178230
+ */
178231
+ async linkSharedSkill(name2) {
178232
+ await this.ensureInit();
178233
+ if (!/^[A-Za-z0-9_.-]{1,64}$/.test(name2)) throw new Error("\u6280\u80FD\u540D\u4E0D\u5408\u6CD5\uFF1A" + name2);
178234
+ const sharedDir = path28.join(sharedSkillsDir(this.dataRoot), name2);
178235
+ const raw2 = await fs11.readFile(path28.join(sharedDir, "SKILL.md"), "utf8").catch(() => "");
178236
+ if (!raw2) throw new Error("\u5171\u4EAB\u5E93\u91CC\u6CA1\u6709\u8FD9\u4E2A\u6280\u80FD\uFF1A" + name2);
178237
+ const meta2 = parseSkillFrontmatter(raw2);
178238
+ const description = (meta2?.description ?? "").trim().replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1") || "\u5171\u4EAB\u6280\u80FD\uFF1A" + name2;
178239
+ const front = [
178240
+ "---",
178241
+ "name: " + name2,
178242
+ "description: " + JSON.stringify(description),
178243
+ "---",
178244
+ ""
178245
+ ].join("\n");
178246
+ const body = [
178247
+ "# " + name2,
178248
+ "",
178249
+ "\u8FD9\u4E2A\u6280\u80FD\u7684\u5B8C\u6574\u8BF4\u660E\u4E66\u4E0E\u9644\u5C5E\u6587\u4EF6\u5728\u5171\u4EAB\u6280\u80FD\u5E93\uFF1A",
178250
+ "",
178251
+ "- \u5171\u4EAB\u76EE\u5F55\uFF1A" + sharedDir.split(/[\\/]/).join("/"),
178252
+ "- \u5165\u53E3\u6587\u4EF6\uFF1A" + path28.join(sharedDir, "SKILL.md").split(/[\\/]/).join("/"),
178253
+ "",
178254
+ "\u9700\u8981\u6309\u5B83\u505A\u4E8B\u65F6\uFF0C\u5148\u7528 read_file \u8BFB\u5165\u53E3\u6587\u4EF6\uFF0C\u518D\u6309\u91CC\u9762\u7684\u8BF4\u660E\u53BB\u8BFB\u5171\u4EAB\u76EE\u5F55\u4E0B\u7684\u5176\u5B83\u6587\u4EF6\u3002",
178255
+ "\u4E0D\u8981\u628A\u8FD9\u4E2A\u76EE\u5F55\u5F53\u6210\u672C\u6280\u80FD\u7684\u526F\u672C\uFF1A\u672C\u76EE\u5F55\u53EA\u6709\u8FD9\u4EFD\u6307\u8DEF\u6587\u4EF6\u3002"
178256
+ ].join("\n");
178257
+ const linkId = _AgentConfigBase.linkIdOf(name2);
178258
+ await installSkill(this.sdkRoot, AGENT_PROJECT_ID, this.agentId, {
178259
+ name: linkId,
178260
+ content: front + body,
178261
+ files: { "link.json": JSON.stringify({ sharedName: name2, sharedDir }, null, 2) }
178262
+ });
178263
+ return this.skills();
178264
+ }
178265
+ /** 列出共享技能库(设置页「把技能挂给这个 Agent」的下拉) */
178266
+ async sharedSkills() {
178267
+ const root6 = sharedSkillsDir(this.dataRoot);
178268
+ let entries;
178269
+ try {
178270
+ entries = await fs11.readdir(root6, { withFileTypes: true });
178271
+ } catch {
178272
+ return [];
178273
+ }
178274
+ const out = [];
178275
+ for (const e7 of entries) {
178276
+ if (!e7.isDirectory() || e7.name.startsWith(".")) continue;
178277
+ const dir = path28.join(root6, e7.name);
178278
+ const raw2 = await fs11.readFile(path28.join(dir, "SKILL.md"), "utf8").catch(() => "");
178279
+ if (!raw2) continue;
178280
+ const meta2 = parseSkillFrontmatter(raw2);
178281
+ const desc = (meta2?.description ?? "").trim();
178282
+ out.push({
178283
+ name: e7.name,
178284
+ description: desc.replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1"),
178285
+ dir
178286
+ });
178287
+ }
178288
+ return out.sort((a6, b6) => a6.name.localeCompare(b6.name));
178289
+ }
178290
+ /**
178291
+ * 把共享库里的技能**从磁盘删掉**(设置页的「删除共享技能」)。
178292
+ *
178293
+ * 先摘掉所有 Agent 的指路文件,再删共享目录 —— 否则会留下「说明书不见了、
178294
+ * Agent 还挂着一个死人链接」的中间态。
178295
+ */
178296
+ async removeSharedSkill(name2) {
178297
+ if (!/^[A-Za-z0-9_.-]{1,64}$/.test(name2)) throw new Error("\u6280\u80FD\u540D\u4E0D\u5408\u6CD5\uFF1A" + name2);
178298
+ const shared = path28.join(sharedSkillsDir(this.dataRoot), name2);
178299
+ const st = await fs11.stat(shared).catch(() => null);
178300
+ if (!st?.isDirectory()) throw new Error("\u5171\u4EAB\u5E93\u91CC\u6CA1\u6709\u8FD9\u4E2A\u6280\u80FD\uFF1A" + name2);
178301
+ const agentsRoot = path28.join(agentRoot(this.dataRoot), AGENT_PROJECT_ID, "agents");
178302
+ const agents = await fs11.readdir(agentsRoot, { withFileTypes: true }).catch(() => []);
178303
+ for (const a6 of agents) {
178304
+ if (!a6.isDirectory()) continue;
178305
+ const skillsRoot2 = path28.join(agentsRoot, a6.name, "agent_state", "skills");
178306
+ const links = await fs11.readdir(skillsRoot2, { withFileTypes: true }).catch(() => []);
178307
+ for (const l4 of links) {
178308
+ if (!l4.isDirectory()) continue;
178309
+ const raw2 = await fs11.readFile(path28.join(skillsRoot2, l4.name, "link.json"), "utf8").catch(() => "");
178310
+ if (!raw2) continue;
178311
+ try {
178312
+ if (JSON.parse(raw2).sharedName !== name2) continue;
178313
+ } catch {
178314
+ continue;
178315
+ }
178316
+ await fs11.rm(path28.join(skillsRoot2, l4.name), { recursive: true, force: true });
178317
+ }
178318
+ }
178319
+ await fs11.rm(shared, { recursive: true, force: true });
177780
178320
  }
177781
178321
  /** 读某个技能的 SKILL.md 全文(界面选了技能时要塞进 [use_skills] 块) */
177782
178322
  async readSkillFile(name2) {
177783
178323
  try {
177784
- const dir = skillsDir(this.sdkRoot, AGENT_PROJECT_ID, AGENT_ID);
177785
- return await fs11.readFile(path28.join(dir, name2, "SKILL.md"), "utf8");
178324
+ const dir = skillsDir(this.sdkRoot, AGENT_PROJECT_ID, this.agentId);
178325
+ return await fs11.readFile(path28.join(dir, _AgentConfigBase.linkIdOf(name2), "SKILL.md"), "utf8");
177786
178326
  } catch {
177787
178327
  return void 0;
177788
178328
  }
@@ -177796,22 +178336,22 @@ var AgentConfigBase = class {
177796
178336
  async subsetMcp(names) {
177797
178337
  await this.ensureInit();
177798
178338
  const cfg = await this.withConfigLock(async () => {
177799
- const current = await loadSystemConfig(this.sdkRoot);
178339
+ const current = await loadSystemConfig(this.sdkRoot, this.agentId);
177800
178340
  const all = current.tools?.mcpServers ?? [];
177801
178341
  const kept = all.filter((e7) => names.includes(e7.name));
177802
- await writeSystemConfig(this.sdkRoot, { ...current, tools: { ...current.tools ?? {}, mcpServers: kept } });
178342
+ await writeSystemConfig(this.sdkRoot, { ...current, tools: { ...current.tools ?? {}, mcpServers: kept } }, this.agentId);
177803
178343
  return current;
177804
178344
  });
177805
178345
  return async () => {
177806
- await this.withConfigLock(() => writeSystemConfig(this.sdkRoot, cfg));
178346
+ await this.withConfigLock(() => writeSystemConfig(this.sdkRoot, cfg, this.agentId));
177807
178347
  };
177808
178348
  }
177809
178349
  /** 设置页要显示这层数据落在哪(诊断用) */
177810
178350
  systemConfigPath() {
177811
- return systemConfigPath(this.sdkRoot, AGENT_PROJECT_ID, AGENT_ID);
178351
+ return systemConfigPath(this.sdkRoot, AGENT_PROJECT_ID, this.agentId);
177812
178352
  }
177813
178353
  stateDir() {
177814
- return agentStateDir(this.sdkRoot, AGENT_PROJECT_ID, AGENT_ID);
178354
+ return agentStateDir(this.sdkRoot, AGENT_PROJECT_ID, this.agentId);
177815
178355
  }
177816
178356
  };
177817
178357
 
@@ -178319,7 +178859,7 @@ var AgentConfigService = class extends AgentConfigBase {
178319
178859
  // -------------------------------------------------------------------- MCP
178320
178860
  async mcpServers() {
178321
178861
  await this.ensureInit();
178322
- const cfg = await this.healBuiltinCanvasMcp(await loadSystemConfig(this.sdkRoot));
178862
+ const cfg = await this.healBuiltinCanvasMcp(await loadSystemConfig(this.sdkRoot, this.getAgentId()));
178323
178863
  const isBuiltin = (name2) => !!this.builtinCanvasUrl && name2 === this.BUILTIN_CANVAS_MCP;
178324
178864
  const entries = cfg.tools?.mcpServers ?? [];
178325
178865
  return entries.map((e7) => {
@@ -178351,10 +178891,10 @@ var AgentConfigService = class extends AgentConfigBase {
178351
178891
  const entry = this.buildMcpEntry(input);
178352
178892
  const name2 = entry.name;
178353
178893
  resolveMCPServer(entry);
178354
- const cfg = await loadSystemConfig(this.sdkRoot);
178894
+ const cfg = await loadSystemConfig(this.sdkRoot, this.getAgentId());
178355
178895
  const existing = cfg.tools?.mcpServers ?? [];
178356
178896
  const next = [...existing.filter((e7) => e7.name !== name2), entry];
178357
- await writeSystemConfig(this.sdkRoot, { ...cfg, tools: { ...cfg.tools ?? {}, mcpServers: next } });
178897
+ await writeSystemConfig(this.sdkRoot, { ...cfg, tools: { ...cfg.tools ?? {}, mcpServers: next } }, this.getAgentId());
178358
178898
  }
178359
178899
  /** 把添加表单变成 SDK 认的 MCP 条目;检测与保存共用这一份校验 */
178360
178900
  buildMcpEntry(input, fallbackName = "") {
@@ -178386,11 +178926,11 @@ var AgentConfigService = class extends AgentConfigBase {
178386
178926
  if (name2 === this.BUILTIN_CANVAS_MCP && this.builtinCanvasUrl) {
178387
178927
  throw new Error("\u300C" + this.BUILTIN_CANVAS_MCP + "\u300D\u662F\u81EA\u5E26\u753B\u5E03 MCP\uFF0C\u4E0D\u80FD\u5220\u9664");
178388
178928
  }
178389
- const cfg = await loadSystemConfig(this.sdkRoot);
178929
+ const cfg = await loadSystemConfig(this.sdkRoot, this.getAgentId());
178390
178930
  const existing = cfg.tools?.mcpServers ?? [];
178391
178931
  const next = existing.filter((e7) => e7.name !== name2);
178392
178932
  if (next.length === existing.length) throw new Error("\u6CA1\u6709\u540D\u4E3A\u300C" + name2 + "\u300D\u7684 MCP \u670D\u52A1");
178393
- await writeSystemConfig(this.sdkRoot, { ...cfg, tools: { ...cfg.tools ?? {}, mcpServers: next } });
178933
+ await writeSystemConfig(this.sdkRoot, { ...cfg, tools: { ...cfg.tools ?? {}, mcpServers: next } }, this.getAgentId());
178394
178934
  }
178395
178935
  /** 内置画布 MCP 的服务名(system_config.yaml 里的条目名) */
178396
178936
  BUILTIN_CANVAS_MCP = "canvas";
@@ -178416,7 +178956,7 @@ var AgentConfigService = class extends AgentConfigBase {
178416
178956
  if (!trimmed) return;
178417
178957
  this.builtinCanvasUrl = trimmed;
178418
178958
  await this.withConfigLock(async () => {
178419
- const cfg = await loadSystemConfig(this.sdkRoot);
178959
+ const cfg = await loadSystemConfig(this.sdkRoot, this.getAgentId());
178420
178960
  const existing = cfg.tools?.mcpServers ?? [];
178421
178961
  const current = existing.find((e7) => e7.name === this.BUILTIN_CANVAS_MCP);
178422
178962
  if (current && current.config.url === trimmed && current.config.type === "http") {
@@ -178425,7 +178965,7 @@ var AgentConfigService = class extends AgentConfigBase {
178425
178965
  const entry = { name: this.BUILTIN_CANVAS_MCP, config: { type: "http", url: trimmed } };
178426
178966
  resolveMCPServer(entry);
178427
178967
  const next = [...existing.filter((e7) => e7.name !== this.BUILTIN_CANVAS_MCP), entry];
178428
- await writeSystemConfig(this.sdkRoot, { ...cfg, tools: { ...cfg.tools ?? {}, mcpServers: next } });
178968
+ await writeSystemConfig(this.sdkRoot, { ...cfg, tools: { ...cfg.tools ?? {}, mcpServers: next } }, this.getAgentId());
178429
178969
  });
178430
178970
  }
178431
178971
  /**
@@ -178442,14 +178982,14 @@ var AgentConfigService = class extends AgentConfigBase {
178442
178982
  const current = existing.find((e7) => e7.name === this.BUILTIN_CANVAS_MCP);
178443
178983
  if (current && current.config.url === url2) return cfg;
178444
178984
  return this.withConfigLock(async () => {
178445
- const fresh = await loadSystemConfig(this.sdkRoot);
178985
+ const fresh = await loadSystemConfig(this.sdkRoot, this.getAgentId());
178446
178986
  const list2 = fresh.tools?.mcpServers ?? [];
178447
178987
  const now = list2.find((e7) => e7.name === this.BUILTIN_CANVAS_MCP);
178448
178988
  if (now && now.config.url === url2) return fresh;
178449
178989
  const entry = { name: this.BUILTIN_CANVAS_MCP, config: { type: "http", url: url2 } };
178450
178990
  const next = now ? list2.map((e7) => e7.name === this.BUILTIN_CANVAS_MCP ? entry : e7) : [...list2, entry];
178451
178991
  const healed = { ...fresh, tools: { ...fresh.tools ?? {}, mcpServers: next } };
178452
- await writeSystemConfig(this.sdkRoot, healed).catch(
178992
+ await writeSystemConfig(this.sdkRoot, healed, this.getAgentId()).catch(
178453
178993
  (err) => console.warn("[agent] \u81EA\u52A8\u8865\u56DE\u753B\u5E03 MCP \u843D\u76D8\u5931\u8D25\uFF1A" + String(err))
178454
178994
  );
178455
178995
  return healed;
@@ -178535,7 +179075,7 @@ var AgentConfigService = class extends AgentConfigBase {
178535
179075
  /** 一次装配会真正拿到哪些工具(界面显示 + 规则列表用) */
178536
179076
  async resolvedTools() {
178537
179077
  await this.ensureInit();
178538
- const state2 = await loadAgentState({ agentId: AGENT_ID, projectId: AGENT_PROJECT_ID, root: this.sdkRoot });
179078
+ const state2 = await loadAgentState({ agentId: this.getAgentId(), projectId: AGENT_PROJECT_ID, root: this.sdkRoot });
178539
179079
  const toolConfig = buildToolConfig(state2);
178540
179080
  const warnings = [];
178541
179081
  const mcp = [];
@@ -178636,6 +179176,17 @@ var AgentSessionStore = class {
178636
179176
  * 串行链让同一会话的所有写排队执行,链与链之间互不影响(不同会话不互相等)。
178637
179177
  */
178638
179178
  chains = /* @__PURE__ */ new Map();
179179
+ /**
179180
+ * 内存里的「会话 → Agent」小表。
179181
+ *
179182
+ * 为什么要它:GoalRuntime 的 scratchpadOf 是同步签名,不能每次都读文件。
179183
+ * 这张表在读取会话记录时顺带填,**不当真身**(真身仍是会话文件里的 agentId)。
179184
+ */
179185
+ agentOfSession = /* @__PURE__ */ new Map();
179186
+ /** 同步取会话所属 Agent(没读过就 undefined,调用方回落当前配置) */
179187
+ cachedAgentId(canvasId, sessionId) {
179188
+ return this.agentOfSession.get(this.key(canvasId, sessionId));
179189
+ }
178639
179190
  serialize(key, task) {
178640
179191
  const prev = this.chains.get(key) ?? Promise.resolve();
178641
179192
  const next = prev.then(task, task);
@@ -178654,7 +179205,9 @@ var AgentSessionStore = class {
178654
179205
  return [...idx.sessions].sort((a6, b6) => b6.updatedAt - a6.updatedAt);
178655
179206
  }
178656
179207
  async get(canvasId, sessionId) {
178657
- return readJson(canvasSessionFile(this.root, canvasId, sessionId));
179208
+ const rec = await readJson(canvasSessionFile(this.root, canvasId, sessionId));
179209
+ if (rec?.agentId) this.agentOfSession.set(this.key(canvasId, sessionId), rec.agentId);
179210
+ return rec;
178658
179211
  }
178659
179212
  /**
178660
179213
  * 落一份带元信息的转录文件;已存在则原样返回(不覆盖转录)。
@@ -178858,7 +179411,9 @@ var AgentSessionStore = class {
178858
179411
  title,
178859
179412
  createdAt: Date.now(),
178860
179413
  provider: parent.provider,
178861
- modelId: parent.modelId
179414
+ modelId: parent.modelId,
179415
+ // 分支留在**父会话那一套 Agent** 里:技能 / 提示词 / Trace 目录都跟它走
179416
+ ...parent.agentId ? { agentId: parent.agentId } : {}
178862
179417
  });
178863
179418
  for (const t2 of copied) await this.appendTurn(canvasId, sessionId, t2);
178864
179419
  return { sessionId, parentId: parentSessionId, copied: copied.length, point: "turn:" + at };
@@ -178884,7 +179439,8 @@ var AgentSessionStore = class {
178884
179439
  title: opts.title?.trim() || parent.title,
178885
179440
  createdAt: Date.now(),
178886
179441
  provider: opts.provider ?? parent.provider,
178887
- modelId: opts.modelId ?? parent.modelId
179442
+ modelId: opts.modelId ?? parent.modelId,
179443
+ ...parent.agentId ? { agentId: parent.agentId } : {}
178888
179444
  });
178889
179445
  for (const t2 of copied) await this.appendTurn(canvasId, sessionId, t2);
178890
179446
  if (opts.modelSegments?.length) {
@@ -179441,15 +179997,18 @@ var AgentRuntime = class {
179441
179997
  /** 拿一个可用的会话:内存里有就复用,没有就续或建 */
179442
179998
  async ensureSession(canvasId, opts = {}) {
179443
179999
  const prefs = opts.prefs ?? {};
180000
+ const wantedAgent = () => prefs.agentId ?? this.deps.agentIdForCanvas?.(canvasId) ?? this.deps.defaultAgentId?.();
180001
+ let sessionAgentId = wantedAgent();
179444
180002
  if (opts.sessionId) {
179445
180003
  const cached3 = this.live.get(this.key(canvasId, opts.sessionId));
179446
180004
  if (cached3) return { id: cached3.id, resumed: true };
179447
180005
  const record2 = await this.deps.store.get(canvasId, opts.sessionId);
179448
180006
  if (record2) {
179449
- const agent2 = await this.deps.agent();
180007
+ sessionAgentId = record2.agentId ?? sessionAgentId;
180008
+ const agent2 = await this.deps.agent(sessionAgentId);
179450
180009
  try {
179451
180010
  const session2 = await agent2.resumeSession({ sessionId: opts.sessionId });
179452
- this.attach(canvasId, session2, prefs);
180011
+ this.attach(canvasId, session2, { ...prefs, ...sessionAgentId ? { agentId: sessionAgentId } : {} });
179453
180012
  return { id: opts.sessionId, resumed: true };
179454
180013
  } catch (err) {
179455
180014
  this.log("resume failed, falling back to new session", {
@@ -179464,7 +180023,7 @@ var AgentRuntime = class {
179464
180023
  const pluginSections = (this.deps.promptSections?.() ?? []).filter((s3) => s3.text.trim()).map((s3) => renderSection(s3.title, s3.text)).join("\n\n");
179465
180024
  const promptText = [prefs.systemPrompt, pluginSections].filter(Boolean).join("\n\n");
179466
180025
  const restorePrompt = this.deps.withSystemPrompt ? await this.deps.withSystemPrompt(promptText) : async () => void 0;
179467
- const agent = await this.deps.agent();
180026
+ const agent = await this.deps.agent(sessionAgentId);
179468
180027
  let session;
179469
180028
  try {
179470
180029
  session = await agent.createSession({
@@ -179482,7 +180041,8 @@ var AgentRuntime = class {
179482
180041
  title: opts.title?.trim() || "\u65B0\u4F1A\u8BDD",
179483
180042
  createdAt: Date.now(),
179484
180043
  provider: session.provider ?? prefs.provider ?? "default",
179485
- modelId: session.modelId ?? prefs.modelId ?? "default"
180044
+ modelId: session.modelId ?? prefs.modelId ?? "default",
180045
+ ...sessionAgentId ? { agentId: sessionAgentId } : {}
179486
180046
  });
179487
180047
  this.attach(canvasId, session, prefs);
179488
180048
  return { id, resumed: false };
@@ -180202,370 +180762,9 @@ var QueueScheduler = class _QueueScheduler {
180202
180762
  };
180203
180763
 
180204
180764
  // src/server/agent/goalRuntime.ts
180205
- import { promises as fs17 } from "node:fs";
180765
+ init_goal();
180766
+ init_goalState();
180206
180767
  import path33 from "node:path";
180207
-
180208
- // src/server/agent/goal.ts
180209
- import { promises as fs16 } from "node:fs";
180210
- import path32 from "node:path";
180211
-
180212
- // src/server/agent/goalState.ts
180213
- import { promises as fs14 } from "node:fs";
180214
- import path30 from "node:path";
180215
- var GOAL_FILE = "GOAL.json";
180216
- var GOAL_FILE_PAUSED = "GOAL.json.paused";
180217
- async function readGoalState(scratchpadDir2) {
180218
- for (const name2 of [GOAL_FILE, GOAL_FILE_PAUSED]) {
180219
- const parsed = await readGoalFile(path30.join(scratchpadDir2, name2));
180220
- if (parsed) return parsed;
180221
- }
180222
- return null;
180223
- }
180224
- async function endGoalFile(scratchpadDir2) {
180225
- const live = path30.join(scratchpadDir2, GOAL_FILE);
180226
- const paused = path30.join(scratchpadDir2, GOAL_FILE_PAUSED);
180227
- const hadLive = await exists(live);
180228
- const hadPaused = await exists(paused);
180229
- await fs14.rm(live, { force: true });
180230
- await fs14.rm(paused, { force: true });
180231
- return hadLive || hadPaused;
180232
- }
180233
- async function updateGoalFile(scratchpadDir2, patch) {
180234
- const livePath = path30.join(scratchpadDir2, GOAL_FILE);
180235
- const pausedPath = path30.join(scratchpadDir2, GOAL_FILE_PAUSED);
180236
- const target = await exists(livePath) ? livePath : await exists(pausedPath) ? pausedPath : null;
180237
- if (!target) return null;
180238
- const current = await readGoalFile(target) ?? {
180239
- objective: "",
180240
- status: "active",
180241
- budget: -1,
180242
- round: 0,
180243
- tokensUsed: 0
180244
- };
180245
- const next = { ...current };
180246
- if (typeof patch.objective === "string" && patch.objective.trim()) next.objective = patch.objective.trim();
180247
- if (typeof patch.tokensUsed === "number" && Number.isFinite(patch.tokensUsed)) {
180248
- next.tokensUsed = Math.max(0, Math.round(patch.tokensUsed));
180249
- }
180250
- if (typeof patch.deltaBudget === "number" && Number.isFinite(patch.deltaBudget)) {
180251
- next.budget = Math.max(0, Math.round(next.tokensUsed + patch.deltaBudget));
180252
- } else if (typeof patch.budget === "number" && Number.isFinite(patch.budget)) {
180253
- next.budget = patch.budget > 0 ? Math.round(patch.budget) : -1;
180254
- }
180255
- await writeGoalFile(target, next);
180256
- return next;
180257
- }
180258
- async function readGoalFile(file) {
180259
- try {
180260
- const raw2 = await fs14.readFile(file, "utf8");
180261
- const parsed = JSON.parse(raw2);
180262
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
180263
- return {
180264
- objective: typeof parsed.objective === "string" ? parsed.objective : "",
180265
- status: typeof parsed.status === "string" ? parsed.status : "blocked",
180266
- budget: Number.isFinite(parsed.budget) ? Number(parsed.budget) : -1,
180267
- round: Number.isFinite(parsed.round) ? Number(parsed.round) : 0,
180268
- tokensUsed: Number.isFinite(parsed.tokens_used) ? Number(parsed.tokens_used) : 0,
180269
- ...parsed.ended === true ? { ended: true } : {}
180270
- };
180271
- } catch {
180272
- return null;
180273
- }
180274
- }
180275
- async function writeGoalFile(file, state2) {
180276
- const payload2 = {
180277
- objective: state2.objective,
180278
- status: state2.status,
180279
- budget: state2.budget,
180280
- round: state2.round,
180281
- tokens_used: state2.tokensUsed,
180282
- ...state2.ended ? { ended: true } : {}
180283
- };
180284
- const tmp = file + ".tmp-" + process.pid + "-" + Date.now();
180285
- await fs14.writeFile(tmp, JSON.stringify(payload2, null, 2) + "\n", "utf8");
180286
- await fs14.rename(tmp, file);
180287
- }
180288
- async function exists(file) {
180289
- try {
180290
- await fs14.access(file);
180291
- return true;
180292
- } catch {
180293
- return false;
180294
- }
180295
- }
180296
-
180297
- // src/server/agent/vendorPlugins.ts
180298
- import { promises as fs15, existsSync as existsSync3 } from "node:fs";
180299
- import path31 from "node:path";
180300
- import { fileURLToPath as fileURLToPath3 } from "node:url";
180301
- var vendorDir = "";
180302
- function defaultVendorDir() {
180303
- try {
180304
- const near = path31.resolve(path31.dirname(fileURLToPath3(import.meta.url)), "vendor-plugins");
180305
- if (existsSync3(near)) return near;
180306
- return path31.resolve(path31.dirname(fileURLToPath3(import.meta.url)), "..", "..", "..", "vendor-plugins");
180307
- } catch {
180308
- return "";
180309
- }
180310
- }
180311
- function setVendorPluginsDir(dir) {
180312
- vendorDir = dir;
180313
- }
180314
- function vendorPluginsDir() {
180315
- return vendorDir || defaultVendorDir();
180316
- }
180317
- async function readVendoredPlugin(name2) {
180318
- const dir = path31.join(vendorPluginsDir(), name2);
180319
- try {
180320
- const raw2 = JSON.parse(await fs15.readFile(path31.join(dir, "plugin.json"), "utf8"));
180321
- const version2 = typeof raw2.version === "string" ? raw2.version : "";
180322
- if (!version2) return null;
180323
- const files = await readDirText(path31.join(dir, "hooks"));
180324
- if (!Object.keys(files).length) return null;
180325
- const manifest = {
180326
- name: name2,
180327
- description: typeof raw2.description === "string" ? raw2.description : name2,
180328
- ...typeof raw2.description_zh === "string" ? { description_zh: raw2.description_zh } : {},
180329
- version: version2,
180330
- // 只透传 SDK 认的三个 hook 点(plugin.json 里可能还有 category 等其它字段)
180331
- stop: asCommandList(raw2.hooks?.stop),
180332
- pre_tool_use: asCommandList(raw2.hooks?.pre_tool_use),
180333
- user_prompt: asCommandList(raw2.hooks?.user_prompt)
180334
- };
180335
- let icon;
180336
- try {
180337
- icon = await fs15.readFile(path31.join(dir, "icon.svg"), "utf8");
180338
- } catch {
180339
- }
180340
- return { name: name2, version: version2, manifest, files, ...icon !== void 0 ? { icon } : {} };
180341
- } catch {
180342
- return null;
180343
- }
180344
- }
180345
- function asCommandList(raw2) {
180346
- if (!Array.isArray(raw2)) return [];
180347
- return raw2.flatMap((c6) => {
180348
- const o3 = c6;
180349
- if (!o3 || typeof o3.command !== "string" || !o3.command) return [];
180350
- return [{ command: o3.command, ...typeof o3.timeout === "number" ? { timeout: o3.timeout } : {} }];
180351
- });
180352
- }
180353
- async function readDirText(dir) {
180354
- const out = {};
180355
- const walk2 = async (abs, rel) => {
180356
- const entries = await fs15.readdir(abs, { withFileTypes: true });
180357
- for (const e7 of entries) {
180358
- const childRel = rel ? rel + "/" + e7.name : e7.name;
180359
- if (e7.isDirectory()) await walk2(path31.join(abs, e7.name), childRel);
180360
- else if (e7.isFile()) out[childRel] = await fs15.readFile(path31.join(abs, e7.name), "utf8");
180361
- }
180362
- };
180363
- try {
180364
- await walk2(dir, "");
180365
- } catch {
180366
- return {};
180367
- }
180368
- return out;
180369
- }
180370
-
180371
- // src/server/agent/goal.ts
180372
- var GOAL_HOOK_NAME = "goal";
180373
- var REALLY_FINISHED = /* @__PURE__ */ new Set(["complete", "blocked", "budget_limited"]);
180374
- function sameVersion(installed, library) {
180375
- return typeof installed === "string" && installed === library;
180376
- }
180377
- function withHostTrigger(manifest) {
180378
- const userPrompt = manifest.user_prompt.map((cmd) => ({ ...cmd, trigger: "host" }));
180379
- return { ...manifest, user_prompt: userPrompt };
180380
- }
180381
- async function goalSdkPorts(deps) {
180382
- const { libraryPlugin: libraryPlugin2, listInstalledHooks: listInstalledHooks2, installHook: installHook2 } = deps;
180383
- const vendoredPlugin = deps.vendoredPlugin ?? readVendoredPlugin;
180384
- if (libraryPlugin2 && listInstalledHooks2 && installHook2) {
180385
- return { libraryPlugin: libraryPlugin2, listInstalledHooks: listInstalledHooks2, installHook: installHook2, vendoredPlugin };
180386
- }
180387
- const sdk = await Promise.resolve().then(() => (init_dist6(), dist_exports));
180388
- return {
180389
- vendoredPlugin,
180390
- libraryPlugin: libraryPlugin2 ?? ((name2) => sdk.libraryPlugin(name2)),
180391
- listInstalledHooks: listInstalledHooks2 ?? ((root6, projectId, agentId) => sdk.listInstalledHooks(root6, projectId, agentId)),
180392
- installHook: installHook2 ?? ((root6, projectId, agentId, manifest, files, icon) => sdk.installHook(root6, projectId, agentId, manifest, files, icon))
180393
- };
180394
- }
180395
- function unavailable(reason) {
180396
- console.warn("[agent] goal hook \u672A\u5B89\u88C5\uFF1A" + reason);
180397
- return { installed: false, status: "unavailable", reason };
180398
- }
180399
- async function ensureGoalInstalled(root6, projectId, agentId, deps = {}) {
180400
- try {
180401
- const sdk = await goalSdkPorts(deps);
180402
- const vendored = await sdk.vendoredPlugin(GOAL_HOOK_NAME);
180403
- const fromSdk = vendored ? null : sdk.libraryPlugin(GOAL_HOOK_NAME);
180404
- const manifest = vendored?.manifest ?? fromSdk?.hooks?.manifest;
180405
- if (!manifest) {
180406
- if (!fromSdk) return unavailable(`\u63D2\u4EF6\u5E93\u91CC\u6CA1\u6709 ${GOAL_HOOK_NAME}\uFF08libraryPlugin \u8FD4\u56DE\u7A7A\uFF09`);
180407
- return unavailable(`${GOAL_HOOK_NAME} \u63D2\u4EF6\u4E0D\u5E26 hook \u5305`);
180408
- }
180409
- const files = vendored?.files ?? fromSdk?.hooks?.files ?? {};
180410
- const icon = vendored?.icon ?? fromSdk?.icon;
180411
- const installed = (await sdk.listInstalledHooks(root6, projectId, agentId)).find(
180412
- (hook) => hook.name === GOAL_HOOK_NAME
180413
- );
180414
- if (installed && sameVersion(installed.version, manifest.version)) {
180415
- return {
180416
- installed: true,
180417
- status: "up-to-date",
180418
- reason: `\u5DF2\u88C5 v${manifest.version}\uFF0C\u65E0\u9700\u91CD\u5199`,
180419
- version: manifest.version
180420
- };
180421
- }
180422
- await sdk.installHook(root6, projectId, agentId, withHostTrigger(manifest), files, icon);
180423
- const status = installed ? "updated" : "installed";
180424
- return {
180425
- installed: true,
180426
- status,
180427
- reason: `${status === "updated" ? "\u7248\u672C\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u91CD\u88C5" : "\u5DF2\u5B89\u88C5"} v${manifest.version}`,
180428
- version: manifest.version
180429
- };
180430
- } catch (err) {
180431
- const reason = err instanceof Error ? err.message : String(err);
180432
- console.warn("[agent] goal hook \u5B89\u88C5\u5931\u8D25\uFF1A" + reason);
180433
- return { installed: false, status: "failed", reason };
180434
- }
180435
- }
180436
- function makeScriptRunner(hooksDir2) {
180437
- return async (scriptPath, input) => {
180438
- const { spawn: spawn3 } = await import("node:child_process");
180439
- return new Promise((resolve, reject) => {
180440
- const child = spawn3(process.execPath, [path32.join(hooksDir2, scriptPath)], {
180441
- stdio: ["pipe", "pipe", "pipe"]
180442
- });
180443
- let out = "";
180444
- let err = "";
180445
- child.stdout.on("data", (d6) => out += String(d6));
180446
- child.stderr.on("data", (d6) => err += String(d6));
180447
- child.on("error", reject);
180448
- child.on("close", (code) => {
180449
- if (code === 0) resolve(out);
180450
- else reject(new Error("hook \u811A\u672C\u9000\u51FA\u7801 " + code + "\uFF1A" + err.slice(0, 200)));
180451
- });
180452
- child.stdin.end(JSON.stringify(input));
180453
- });
180454
- };
180455
- }
180456
- async function askGoalStop(run3, sessionId, tracePath) {
180457
- const raw2 = (await run3("stop.mjs", { hook: "stop", session_id: sessionId, trace_path: tracePath })).trim();
180458
- if (!raw2) return null;
180459
- try {
180460
- const parsed = JSON.parse(raw2);
180461
- const decision = parsed.decision === "continue" || parsed.decision === "stop" ? parsed.decision : null;
180462
- if (!decision) return null;
180463
- return {
180464
- decision,
180465
- ...typeof parsed.reason === "string" ? { reason: parsed.reason } : {},
180466
- ...typeof parsed.input === "string" ? { input: parsed.input } : {},
180467
- ...parsed.output && typeof parsed.output === "object" ? { output: parsed.output } : {}
180468
- };
180469
- } catch {
180470
- return null;
180471
- }
180472
- }
180473
- var GoalFiles = class {
180474
- constructor(scratchpadDir2) {
180475
- this.scratchpadDir = scratchpadDir2;
180476
- }
180477
- scratchpadDir;
180478
- get live() {
180479
- return path32.join(this.scratchpadDir, GOAL_FILE);
180480
- }
180481
- get paused() {
180482
- return path32.join(this.scratchpadDir, GOAL_FILE_PAUSED);
180483
- }
180484
- read() {
180485
- return readGoalState(this.scratchpadDir);
180486
- }
180487
- async exists() {
180488
- for (const f8 of [this.live, this.paused]) {
180489
- try {
180490
- await fs16.access(f8);
180491
- return true;
180492
- } catch {
180493
- }
180494
- }
180495
- return false;
180496
- }
180497
- /**
180498
- * 暂停:把文件改名挪走(内容原样)。
180499
- *
180500
- * 为什么不是改 status:插件只认 active / wrapping_up / complete / blocked,
180501
- * 写别的值会被判成"协议外的坏通道" ⇒ 直接 blocked 收场(不是暂停,是搞砸)。
180502
- * 文件缺席则下一轮结束时 stop.mjs 读不到 ⇒ 静默退出 ⇒ 官方自动连播自然停住。
180503
- */
180504
- async pause() {
180505
- if (!await fileExists2(this.live)) return false;
180506
- await fs16.rm(this.paused, { force: true });
180507
- await fs16.rename(this.live, this.paused);
180508
- return true;
180509
- }
180510
- /** 启动:文件改回原名(status / round / tokens_used 原样接上) */
180511
- async resume() {
180512
- if (!await fileExists2(this.paused)) return false;
180513
- await fs16.rm(this.live, { force: true });
180514
- await fs16.rename(this.paused, this.live);
180515
- return true;
180516
- }
180517
- /**
180518
- * 把「被中止」的目标**重新打开**(用户口径 2026-10-11)。
180519
- *
180520
- * 为什么需要:用户在界面上点「终止」时,插件的 stop hook 会把 GOAL.json 写成
180521
- * `status:'aborted' + ended:true` —— 那是「**这一轮**结束了,别再自动续轮」,
180522
- * 不是「目标作废」。文件仍以 **live 名**躺着(不是 .paused),所以只调 resume()
180523
- * 什么也做不了(它只认 .paused)。
180524
- *
180525
- * 这里的口径:把终态标记清掉(`ended` 去掉、`status` 回 active),让插件下一轮
180526
- * 重新把它当成进行中的目标。**只处理"中止"这一种**:真完成 / 受阻 / 预算用尽
180527
- * 属于真收尾,不在这里复活(调用方负责判断)。
180528
- *
180529
- * 返回 true = 确实改写了文件(原本就是可续跑状态时返回 false,调用方按"无需重开"处理)。
180530
- */
180531
- async reopen() {
180532
- const current = await this.read();
180533
- if (!current) return false;
180534
- if (!await fileExists2(this.live)) return false;
180535
- if (REALLY_FINISHED.has(current.status)) return false;
180536
- const next = { ...current, status: "active" };
180537
- delete next.ended;
180538
- await writeGoalFile(this.live, next);
180539
- return true;
180540
- }
180541
- /** 结束目标:两份状态文件都删掉(与「暂停」不同,不留可恢复的副本) */
180542
- end() {
180543
- return endGoalFile(this.scratchpadDir);
180544
- }
180545
- /**
180546
- * 暂停态下"守住缺席":当前轮里模型可能自己写回 GOAL.json(比如它认为完成了),
180547
- * 那样文件就"复活"、官方循环会继续 —— 暂停失效。
180548
- *
180549
- * 所以每轮结束都调一次:发现 live 又出现了就再挪走(保留最新内容,状态仍是暂停)。
180550
- * 返回 true = 这次真的收走了一个复活的文件。
180551
- */
180552
- async enforcePaused() {
180553
- if (!await fileExists2(this.live)) return false;
180554
- await fs16.rm(this.paused, { force: true });
180555
- await fs16.rename(this.live, this.paused);
180556
- return true;
180557
- }
180558
- };
180559
- async function fileExists2(file) {
180560
- try {
180561
- await fs16.access(file);
180562
- return true;
180563
- } catch {
180564
- return false;
180565
- }
180566
- }
180567
-
180568
- // src/server/agent/goalRuntime.ts
180569
180768
  import { promises as fsp } from "node:fs";
180570
180769
  var GoalRuntime = class {
180571
180770
  constructor(deps) {
@@ -180686,16 +180885,50 @@ var GoalRuntime = class {
180686
180885
  function goalHooksDir(agentRoot2, projectId, agentId) {
180687
180886
  return path33.join(agentRoot2, projectId, "agents", agentId, "agent_state", "hooks", "goal");
180688
180887
  }
180689
- async function findSessionTrace(tracesDir2, sessionId) {
180690
- let best = null;
180888
+ async function writeInitialGoal(scratchpadDir2, objective, budget) {
180889
+ await fsp.mkdir(scratchpadDir2, { recursive: true });
180890
+ await writeGoalFile(path33.join(scratchpadDir2, GOAL_FILE), {
180891
+ objective,
180892
+ status: "active",
180893
+ // 预算口径:> 0 用给定值;否则 -1(不限)—— 与插件 start.mjs 的 Number.isFinite 判定一致
180894
+ budget: Number.isFinite(budget) && budget > 0 ? Math.round(budget) : -1,
180895
+ round: 1,
180896
+ tokensUsed: 0
180897
+ });
180898
+ }
180899
+
180900
+ // src/server/agent/traceFork.ts
180901
+ import { promises as fs17 } from "node:fs";
180902
+ import path34 from "node:path";
180903
+ function tracesDirOf(root6, agentId = AGENT_ID) {
180904
+ return path34.join(agentRoot(root6), AGENT_PROJECT_ID, "agents", agentId, "traces");
180905
+ }
180906
+ async function findTraceAcrossAgents(root6, agentIds, sessionId) {
180907
+ for (const id of agentIds) {
180908
+ const hit = await findTraceIn(tracesDirOf(root6, id), sessionId);
180909
+ if (hit) return hit;
180910
+ }
180911
+ return null;
180912
+ }
180913
+ async function listAgentIds(root6) {
180914
+ const dir = path34.join(agentRoot(root6), AGENT_PROJECT_ID, "agents");
180915
+ try {
180916
+ const entries = await fs17.readdir(dir, { withFileTypes: true });
180917
+ return entries.filter((e7) => e7.isDirectory() && !e7.name.startsWith(".")).map((e7) => e7.name);
180918
+ } catch {
180919
+ return [];
180920
+ }
180921
+ }
180922
+ async function findTraceIn(tracesDir2, sessionId) {
180691
180923
  let days;
180692
180924
  try {
180693
180925
  days = await fs17.readdir(tracesDir2);
180694
180926
  } catch {
180695
180927
  return null;
180696
180928
  }
180929
+ let best = null;
180697
180930
  for (const day of days) {
180698
- const dir = path33.join(tracesDir2, day);
180931
+ const dir = path34.join(tracesDir2, day);
180699
180932
  let files;
180700
180933
  try {
180701
180934
  files = await fs17.readdir(dir);
@@ -180704,33 +180937,12 @@ async function findSessionTrace(tracesDir2, sessionId) {
180704
180937
  }
180705
180938
  for (const f8 of files) {
180706
180939
  if (!f8.startsWith(sessionId + "_") || !f8.endsWith(".jsonl")) continue;
180707
- const m5 = /_(\d+)\.jsonl$/.exec(f8);
180708
- const index = m5 ? Number(m5[1]) : 0;
180709
- if (!best || index > best.index || index === best.index && f8 > path33.basename(best.file)) {
180710
- best = { file: path33.join(dir, f8), index };
180711
- }
180940
+ const idx = Number(/_([0-9]+)\.jsonl$/.exec(f8)?.[1] ?? 0);
180941
+ if (!best || idx > best.index) best = { file: path34.join(dir, f8), index: idx };
180712
180942
  }
180713
180943
  }
180714
180944
  return best?.file ?? null;
180715
180945
  }
180716
- async function writeInitialGoal(scratchpadDir2, objective, budget) {
180717
- await fsp.mkdir(scratchpadDir2, { recursive: true });
180718
- await writeGoalFile(path33.join(scratchpadDir2, GOAL_FILE), {
180719
- objective,
180720
- status: "active",
180721
- // 预算口径:> 0 用给定值;否则 -1(不限)—— 与插件 start.mjs 的 Number.isFinite 判定一致
180722
- budget: Number.isFinite(budget) && budget > 0 ? Math.round(budget) : -1,
180723
- round: 1,
180724
- tokensUsed: 0
180725
- });
180726
- }
180727
-
180728
- // src/server/agent/traceFork.ts
180729
- import { promises as fs18 } from "node:fs";
180730
- import path34 from "node:path";
180731
- function tracesDirOf(root6) {
180732
- return path34.join(agentRoot(root6), AGENT_PROJECT_ID, "agents", AGENT_ID, "traces");
180733
- }
180734
180946
  function dateDirOf(sessionId) {
180735
180947
  const m5 = /^session-(\d{4}-\d{2}-\d{2})/.exec(sessionId);
180736
180948
  return m5 ? m5[1] : (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
@@ -180738,12 +180950,12 @@ function dateDirOf(sessionId) {
180738
180950
  async function readParentMeta(tracesDir2, parentSessionId) {
180739
180951
  let located = null;
180740
180952
  try {
180741
- const dates = await fs18.readdir(tracesDir2);
180953
+ const dates = await fs17.readdir(tracesDir2);
180742
180954
  for (const date5 of dates) {
180743
180955
  const dir = path34.join(tracesDir2, date5);
180744
180956
  let files = [];
180745
180957
  try {
180746
- files = await fs18.readdir(dir);
180958
+ files = await fs17.readdir(dir);
180747
180959
  } catch {
180748
180960
  continue;
180749
180961
  }
@@ -180755,7 +180967,7 @@ async function readParentMeta(tracesDir2, parentSessionId) {
180755
180967
  }
180756
180968
  if (!located) return null;
180757
180969
  try {
180758
- const text = await fs18.readFile(located, "utf8");
180970
+ const text = await fs17.readFile(located, "utf8");
180759
180971
  for (const line of text.split("\n")) {
180760
180972
  const s3 = line.trim();
180761
180973
  if (!s3) continue;
@@ -180815,7 +181027,8 @@ function toolOutputMessage(t2) {
180815
181027
  };
180816
181028
  }
180817
181029
  async function seedForkTrace(root6, seed) {
180818
- const tracesDir2 = tracesDirOf(root6);
181030
+ const agentId = seed.agentId ?? AGENT_ID;
181031
+ const tracesDir2 = tracesDirOf(root6, agentId);
180819
181032
  const parent = await readParentMeta(tracesDir2, seed.parentSessionId);
180820
181033
  let meta2;
180821
181034
  if (parent) {
@@ -180828,7 +181041,7 @@ async function seedForkTrace(root6, seed) {
180828
181041
  session_id: seed.forkSessionId,
180829
181042
  ...seed.provider ? { provider: seed.provider } : {},
180830
181043
  ...seed.modelId ? { model_id: seed.modelId } : {},
180831
- agent_state: agentStateDir2(root6),
181044
+ agent_state: agentStateDir2(root6, agentId),
180832
181045
  workspace: canvasWorkspaceDir(root6, seed.canvasId)
180833
181046
  };
180834
181047
  }
@@ -180860,11 +181073,14 @@ async function seedForkTrace(root6, seed) {
180860
181073
  closeRequest();
180861
181074
  const dir = path34.join(tracesDir2, dateDirOf(seed.forkSessionId));
180862
181075
  const file = path34.join(dir, seed.forkSessionId + "_001.jsonl");
180863
- await fs18.mkdir(dir, { recursive: true });
180864
- await fs18.writeFile(file, lines.join("\n") + "\n", { flag: "wx" });
181076
+ await fs17.mkdir(dir, { recursive: true });
181077
+ await fs17.writeFile(file, lines.join("\n") + "\n", { flag: "wx" });
180865
181078
  return file;
180866
181079
  }
180867
181080
 
181081
+ // src/server/agent/assembleAgent.ts
181082
+ init_goal();
181083
+
180868
181084
  // src/server/agent/commandEncoding.ts
180869
181085
  var POWERSHELL_UTF8_PREFIX = "[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8; [Console]::InputEncoding=[Text.Encoding]::UTF8; $env:PYTHONUTF8='1'; $env:PYTHONIOENCODING='utf-8'; ";
180870
181086
  var CMD_UTF8_PREFIX = "chcp 65001>nul & ";
@@ -180900,13 +181116,34 @@ function utf8SpawnConfiner() {
180900
181116
  }
180901
181117
 
180902
181118
  // src/server/agent/assembleAgent.ts
181119
+ init_vendorPlugins();
180903
181120
  async function assembleAgentServices(opts) {
180904
181121
  const ports = opts.ports;
180905
181122
  const dataDir = ports.dataDir;
180906
181123
  const log = ports.log ?? ((m5, extra) => console.log("[agent] " + m5, extra ?? ""));
180907
181124
  if (ports.vendorPluginsDir) setVendorPluginsDir(ports.vendorPluginsDir);
180908
181125
  const config2 = new AgentConfigService(dataDir, { kv: ports.kv, skillSources: ports.skillSources });
181126
+ if (ports.agentId) config2.setAgentId(ports.agentId);
180909
181127
  const sessions = new AgentSessionStore(dataDir);
181128
+ const agents = /* @__PURE__ */ new Map();
181129
+ const agentFor = async (agentId) => {
181130
+ const id = agentId || ports.agentId || AGENT_ID;
181131
+ const hit = agents.get(id);
181132
+ if (hit) return hit;
181133
+ const p3 = (async () => {
181134
+ const sdk = await loadSdk();
181135
+ return sdk.createAgent({
181136
+ root: agentRoot(dataDir),
181137
+ projectId: AGENT_PROJECT_ID,
181138
+ agentId: id,
181139
+ controlEnv: () => PYTHON_UTF8_ENV,
181140
+ confineSpawn: () => utf8SpawnConfiner()
181141
+ });
181142
+ })();
181143
+ agents.set(id, p3);
181144
+ void p3.catch(() => agents.delete(id));
181145
+ return p3;
181146
+ };
180910
181147
  let sdkPromise;
180911
181148
  const loadSdk = () => sdkPromise ??= Promise.resolve().then(() => (init_dist6(), dist_exports));
180912
181149
  let sdkRef;
@@ -180928,16 +181165,9 @@ async function assembleAgentServices(opts) {
180928
181165
  root: dataDir,
180929
181166
  store: sessions,
180930
181167
  hub,
180931
- agent: async () => {
180932
- const sdk = await loadSdk();
180933
- return sdk.createAgent({
180934
- root: agentRoot(dataDir),
180935
- projectId: AGENT_PROJECT_ID,
180936
- agentId: AGENT_ID,
180937
- controlEnv: () => PYTHON_UTF8_ENV,
180938
- confineSpawn: () => utf8SpawnConfiner()
180939
- });
180940
- },
181168
+ agent: (agentId) => agentFor(agentId),
181169
+ defaultAgentId: () => config2.getAgentId(),
181170
+ agentIdForCanvas: (canvasId) => ports.resolveCanvasAgent?.(canvasId),
180941
181171
  /** 每次建会话现读:插件可热装热卸,运行期地址 / 端口也在变,快照会把旧值冻进提示词。 */
180942
181172
  promptSections: () => ports.promptSections().map((s3) => ({ title: s3.title, text: s3.text })),
180943
181173
  makeUserMessage: (text, images) => {
@@ -180986,9 +181216,21 @@ async function assembleAgentServices(opts) {
180986
181216
  });
180987
181217
  queueRef = queue;
180988
181218
  const goal = new GoalRuntime({
180989
- scratchpadOf: (_canvasId, sessionId) => sessionScratchpadPath(agentRoot(dataDir), sessionId),
180990
- hooksDir: goalHooksDir(agentRoot(dataDir), AGENT_PROJECT_ID, AGENT_ID),
180991
- latestTraceOf: (sessionId) => findSessionTrace(tracesDirOf(agentRoot(dataDir)), sessionId),
181219
+ // 这三个回调按**会话自己的 Agent** 取;找不到记录就回落当前配置。
181220
+ scratchpadOf: (canvasId, sessionId) => sessionScratchpadPath(agentRoot(dataDir), sessionId, sessions.cachedAgentId(canvasId, sessionId) ?? config2.getAgentId()),
181221
+ /**
181222
+ * goal hook 的脚本目录。
181223
+ *
181224
+ * 已知限制:GoalRuntime 只收一个 hooksDir(不是按会话回调),所以这里取「当前配置」。
181225
+ * 只有「恢复一个在**别套配置**里暂停的目标」这一种情况会看错目录;
181226
+ * 找下一轮文本失败时 GoalRuntime 有兜底文本(目标照样继续),不会静默卡死。
181227
+ * 启动目标的会话用的是当前选中/绑定的配置,那条路径是对的。
181228
+ */
181229
+ hooksDir: goalHooksDir(agentRoot(dataDir), AGENT_PROJECT_ID, config2.getAgentId()),
181230
+ latestTraceOf: async (sessionId) => {
181231
+ const ids = await listAgentIds(agentRoot(dataDir));
181232
+ return findTraceAcrossAgents(agentRoot(dataDir), ids.length ? ids : [config2.getAgentId()], sessionId);
181233
+ },
180992
181234
  startRun: async (canvasId, sessionId, text, harnessText) => {
180993
181235
  const r7 = await runtime.startRun(canvasId, {
180994
181236
  canvasId,
@@ -181006,7 +181248,7 @@ async function assembleAgentServices(opts) {
181006
181248
  log: (message, extra) => log("[goal] " + message, extra)
181007
181249
  });
181008
181250
  goalRef = goal;
181009
- await ensureGoalInstalled(agentRoot(dataDir), AGENT_PROJECT_ID, AGENT_ID);
181251
+ await ensureGoalInstalled(agentRoot(dataDir), AGENT_PROJECT_ID, config2.getAgentId());
181010
181252
  return {
181011
181253
  config: config2,
181012
181254
  sessions,
@@ -181015,9 +181257,10 @@ async function assembleAgentServices(opts) {
181015
181257
  queue,
181016
181258
  goal,
181017
181259
  loadSdk,
181018
- dispose: () => {
181260
+ dispose: async () => {
181019
181261
  runtime.disposeAll();
181020
181262
  hub.disposeAll();
181263
+ await new Promise((r7) => setTimeout(r7, 50));
181021
181264
  }
181022
181265
  };
181023
181266
  }
@@ -183082,7 +183325,7 @@ var Hono2 = class extends Hono {
183082
183325
  };
183083
183326
 
183084
183327
  // src/server/routes/agent.ts
183085
- import { promises as fs19 } from "node:fs";
183328
+ import { promises as fs18 } from "node:fs";
183086
183329
  import path35 from "node:path";
183087
183330
 
183088
183331
  // src/ui/render/modelBrandIcons.ts
@@ -183394,8 +183637,16 @@ function iconRoutes() {
183394
183637
  }
183395
183638
 
183396
183639
  // src/server/routes/agent.ts
183397
- function agentRoutes(config2, runtime) {
183640
+ function agentRoutes(config2, runtime, agentProfiles, onCanvasAgentChange) {
183398
183641
  const app = new Hono2();
183642
+ async function installGoalHookFor(agentId) {
183643
+ try {
183644
+ const { ensureGoalInstalled: ensureGoalInstalled2 } = await Promise.resolve().then(() => (init_goal(), goal_exports));
183645
+ await ensureGoalInstalled2(agentRoot(config2.dataDir), AGENT_PROJECT_ID, agentId);
183646
+ } catch (err) {
183647
+ console.warn("[agent] \u76EE\u6807 hook \u5B89\u88C5\u5931\u8D25\uFF1A" + String(err));
183648
+ }
183649
+ }
183399
183650
  const IMAGE_MIME = {
183400
183651
  ".png": "image/png",
183401
183652
  ".jpg": "image/jpeg",
@@ -183421,10 +183672,10 @@ function agentRoutes(config2, runtime) {
183421
183672
  if (!rel || rel.startsWith("..") || path35.isAbsolute(rel)) {
183422
183673
  return c6.json({ ok: false, error: "\u6587\u4EF6\u4E0D\u5728 Agent \u6570\u636E\u76EE\u5F55\u5185" }, 400);
183423
183674
  }
183424
- const stat6 = await fs19.stat(target).catch(() => null);
183675
+ const stat6 = await fs18.stat(target).catch(() => null);
183425
183676
  if (!stat6?.isFile()) return c6.json({ ok: false, error: "\u6587\u4EF6\u4E0D\u5B58\u5728" }, 404);
183426
183677
  if (stat6.size > MAX_IMAGE_BYTES2) return c6.json({ ok: false, error: "\u56FE\u7247\u8FC7\u5927" }, 413);
183427
- const bytes = await fs19.readFile(target).catch(() => null);
183678
+ const bytes = await fs18.readFile(target).catch(() => null);
183428
183679
  if (!bytes) return c6.json({ ok: false, error: "\u8BFB\u53D6\u5931\u8D25" }, 500);
183429
183680
  return c6.body(bytes, 200, {
183430
183681
  "content-type": mime,
@@ -183541,6 +183792,117 @@ function agentRoutes(config2, runtime) {
183541
183792
  modelRefRoute("default", (p3, m5) => config2.setDefaultModel(p3, m5));
183542
183793
  modelRefRoute("vision", (p3, m5) => config2.setVisionModel(p3, m5));
183543
183794
  app.get("/api/agent/skills", async (c6) => c6.json({ ok: true, skills: await config2.skills() }));
183795
+ app.get("/api/agent/skills/shared", async (c6) => {
183796
+ const r7 = await guard(() => config2.sharedSkills());
183797
+ if (!r7.ok) return c6.json({ ok: false, error: r7.message }, 400);
183798
+ return c6.json({ ok: true, skills: r7.value });
183799
+ });
183800
+ app.get("/api/agent/profiles", async (c6) => {
183801
+ const r7 = await guard(async () => {
183802
+ const port = agentProfiles;
183803
+ if (!port) {
183804
+ return {
183805
+ profiles: [{ id: config2.getAgentId(), name: config2.getAgentId(), initialized: true, builtin: true }],
183806
+ activeId: config2.getAgentId(),
183807
+ canvasId: "",
183808
+ canvasBinding: ""
183809
+ };
183810
+ }
183811
+ const canvasId = String(c6.req.query("canvasId") ?? "");
183812
+ return {
183813
+ profiles: await port.list(),
183814
+ // activeId = **当前编辑面**(config 切到谁就是谁)。
183815
+ // 为什么不用 port.activeId():那是持久化的「全局默认」,open 切换不写盘 ——
183816
+ // 如果这里返回 KV 默认,前端 refresh() 一拉就会把用户刚点的配置盖回去
183817
+ //(用户实测:点 writer 后立刻弹回 canvas-agent)。
183818
+ activeId: config2.getAgentId(),
183819
+ canvasId,
183820
+ canvasBinding: canvasId ? await port.bindingOf(canvasId) : ""
183821
+ };
183822
+ });
183823
+ if (!r7.ok) return c6.json({ ok: false, error: r7.message }, 400);
183824
+ return c6.json({ ok: true, ...r7.value });
183825
+ });
183826
+ app.post("/api/agent/profiles", async (c6) => {
183827
+ const body = await safeJson(c6);
183828
+ if (!body || typeof body.agentId !== "string" || !body.agentId.trim()) {
183829
+ return c6.json({ ok: false, error: "\u9700\u8981 agentId" }, 400);
183830
+ }
183831
+ const agentId = body.agentId.trim();
183832
+ const r7 = await guard(async () => {
183833
+ if (!agentProfiles) throw new Error("\u8FD9\u53F0\u670D\u52A1\u53EA\u652F\u6301\u4E00\u4E2A Agent \u914D\u7F6E");
183834
+ const created = await agentProfiles.create(agentId);
183835
+ await installGoalHookFor(agentId);
183836
+ return { profiles: await agentProfiles.list(), created };
183837
+ });
183838
+ if (!r7.ok) return c6.json({ ok: false, error: r7.message }, 400);
183839
+ return c6.json({ ok: true, ...r7.value });
183840
+ });
183841
+ app.put("/api/agent/profiles/active", async (c6) => {
183842
+ const body = await safeJson(c6);
183843
+ if (!body || typeof body.agentId !== "string" || !body.agentId.trim()) {
183844
+ return c6.json({ ok: false, error: "\u9700\u8981 agentId" }, 400);
183845
+ }
183846
+ const agentId = body.agentId.trim();
183847
+ const r7 = await guard(async () => {
183848
+ if (!agentProfiles) throw new Error("\u8FD9\u53F0\u670D\u52A1\u53EA\u652F\u6301\u4E00\u4E2A Agent \u914D\u7F6E");
183849
+ await agentProfiles.setActive(agentId);
183850
+ config2.setAgentId(agentId);
183851
+ await installGoalHookFor(agentId);
183852
+ return { activeId: config2.getAgentId() };
183853
+ });
183854
+ if (!r7.ok) return c6.json({ ok: false, error: r7.message }, 400);
183855
+ return c6.json({ ok: true, ...r7.value });
183856
+ });
183857
+ app.put("/api/agent/profiles/open", async (c6) => {
183858
+ const body = await safeJson(c6);
183859
+ if (!body || typeof body.agentId !== "string" || !body.agentId.trim()) {
183860
+ return c6.json({ ok: false, error: "\u9700\u8981 agentId" }, 400);
183861
+ }
183862
+ const agentId = body.agentId.trim();
183863
+ const r7 = await guard(async () => {
183864
+ if (!agentProfiles) throw new Error("\u8FD9\u53F0\u670D\u52A1\u53EA\u652F\u6301\u4E00\u4E2A Agent \u914D\u7F6E");
183865
+ await agentProfiles.setActive(agentId);
183866
+ config2.setAgentId(agentId);
183867
+ await installGoalHookFor(agentId);
183868
+ return { activeId: config2.getAgentId() };
183869
+ });
183870
+ if (!r7.ok) return c6.json({ ok: false, error: r7.message }, 400);
183871
+ return c6.json({ ok: true, ...r7.value });
183872
+ });
183873
+ app.put("/api/agent/profiles/canvas", async (c6) => {
183874
+ const body = await safeJson(c6);
183875
+ if (!body || typeof body.canvasId !== "string" || !body.canvasId.trim()) {
183876
+ return c6.json({ ok: false, error: "\u9700\u8981 canvasId" }, 400);
183877
+ }
183878
+ const canvasId = body.canvasId.trim();
183879
+ const agentId = typeof body.agentId === "string" && body.agentId.trim() ? body.agentId.trim() : null;
183880
+ const r7 = await guard(async () => {
183881
+ if (!agentProfiles) throw new Error("\u8FD9\u53F0\u670D\u52A1\u53EA\u652F\u6301\u4E00\u4E2A Agent \u914D\u7F6E");
183882
+ await agentProfiles.bindCanvas(canvasId, agentId);
183883
+ if (agentId) await installGoalHookFor(agentId);
183884
+ onCanvasAgentChange?.(canvasId);
183885
+ return { canvasId, canvasBinding: await agentProfiles.bindingOf(canvasId) };
183886
+ });
183887
+ if (!r7.ok) return c6.json({ ok: false, error: r7.message }, 400);
183888
+ return c6.json({ ok: true, ...r7.value });
183889
+ });
183890
+ app.post("/api/agent/skills/link", async (c6) => {
183891
+ const body = await safeJson(c6);
183892
+ if (!body || typeof body.name !== "string" || !body.name.trim()) {
183893
+ return c6.json({ ok: false, error: "\u9700\u8981 name\uFF08\u5171\u4EAB\u5E93\u91CC\u7684\u6280\u80FD\u540D\uFF09" }, 400);
183894
+ }
183895
+ const name2 = body.name.trim();
183896
+ const r7 = await guard(() => config2.linkSharedSkill(name2));
183897
+ if (!r7.ok) return c6.json({ ok: false, error: r7.message }, 400);
183898
+ return c6.json({ ok: true, skills: r7.value });
183899
+ });
183900
+ app.delete("/api/agent/skills/shared/:name", async (c6) => {
183901
+ const name2 = decodeURIComponent(c6.req.param("name"));
183902
+ const r7 = await guard(() => config2.removeSharedSkill(name2));
183903
+ if (!r7.ok) return c6.json({ ok: false, error: r7.message }, 400);
183904
+ return c6.json({ ok: true, removed: name2 });
183905
+ });
183544
183906
  app.get(
183545
183907
  "/api/agent/skills/sources",
183546
183908
  async (c6) => c6.json({ ok: true, candidates: await config2.skillCandidates() })
@@ -183900,6 +184262,9 @@ var streamSSE = (c6, cb, onError) => {
183900
184262
  return c6.newResponse(stream2.responseReadable);
183901
184263
  };
183902
184264
 
184265
+ // src/server/routes/agentSessions.ts
184266
+ init_goalState();
184267
+
183903
184268
  // src/server/routes/agentSessionsShared.ts
183904
184269
  function guardParams(c6) {
183905
184270
  const canvasId = c6.req.param("canvasId") ?? "";
@@ -183919,6 +184284,7 @@ async function readPrefs(config2, body) {
183919
184284
  if (typeof body.modelId === "string" && body.modelId) prefs.modelId = body.modelId;
183920
184285
  if (Array.isArray(body.mcpServers)) prefs.mcpServers = body.mcpServers.map(String);
183921
184286
  if (Array.isArray(body.skills)) prefs.skills = body.skills.map(String);
184287
+ if (typeof body.agentId === "string" && body.agentId.trim()) prefs.agentId = body.agentId.trim();
183922
184288
  if (typeof body.systemPrompt === "string" && body.systemPrompt.trim()) prefs.systemPrompt = body.systemPrompt;
183923
184289
  const window2 = await config2.modelContextWindow(prefs.provider, prefs.modelId);
183924
184290
  if (window2) prefs.contextWindow = window2;
@@ -183926,6 +184292,7 @@ async function readPrefs(config2, body) {
183926
184292
  }
183927
184293
 
183928
184294
  // src/server/routes/agentSessionsMessages.ts
184295
+ init_goalState();
183929
184296
  function registerMessageRoute(app, deps) {
183930
184297
  const { store, runtime, config: config2, preTurn, hub, onQueueChanged, goalRuntime, guardParams: guardParams2, readPrefs: readPrefs2 } = deps;
183931
184298
  app.post("/api/agent/canvases/:canvasId/sessions/:sessionId/messages", async (c6) => {
@@ -184004,7 +184371,8 @@ function registerMessageRoute(app, deps) {
184004
184371
  }
184005
184372
  const goalImages = Array.isArray(body?.images) ? body.images.map(String).filter(Boolean) : [];
184006
184373
  void store.setGoalImages(p3.canvasId, p3.sessionId, goalImages).catch(() => void 0);
184007
- void readGoalState(sessionScratchpadPath(agentRoot(config2.dataDir), p3.sessionId)).then((g6) => {
184374
+ const goalAgentId = deps.store.cachedAgentId(p3.canvasId, p3.sessionId);
184375
+ void readGoalState(sessionScratchpadPath(agentRoot(config2.dataDir), p3.sessionId, goalAgentId)).then((g6) => {
184008
184376
  if (g6) hub?.append(p3.canvasId, p3.sessionId, { type: "goal_state", goal: g6 });
184009
184377
  }).catch(() => void 0);
184010
184378
  return streamSSE(c6, async (stream2) => {
@@ -184176,7 +184544,7 @@ function agentSessionRoutes(store, runtime, config2, branches, preTurn, hub, onQ
184176
184544
  turns = turns.slice(start, end2);
184177
184545
  }
184178
184546
  const turnsHaveBefore = turnsLimit > 0 ? haveBefore : false;
184179
- const goal = await readGoalForSession(config2, p3.sessionId);
184547
+ const goal = await readGoalForSession(config2, p3.sessionId, store, p3.canvasId);
184180
184548
  return c6.json({
184181
184549
  ok: true,
184182
184550
  session: turnsLimit > 0 ? { ...session, turns } : session,
@@ -184479,7 +184847,8 @@ function agentSessionRoutes(store, runtime, config2, branches, preTurn, hub, onQ
184479
184847
  forkSessionId: fork.sessionId,
184480
184848
  canvasId: p3.canvasId,
184481
184849
  turns: (await store.get(p3.canvasId, fork.sessionId))?.turns ?? [],
184482
- ...parentRecord ? { provider: parentRecord.provider, modelId: parentRecord.modelId } : {}
184850
+ ...parentRecord ? { provider: parentRecord.provider, modelId: parentRecord.modelId } : {},
184851
+ ...parentRecord?.agentId ? { agentId: parentRecord.agentId } : {}
184483
184852
  });
184484
184853
  } catch (err) {
184485
184854
  await store.remove(p3.canvasId, fork.sessionId).catch(() => void 0);
@@ -184541,7 +184910,8 @@ function agentSessionRoutes(store, runtime, config2, branches, preTurn, hub, onQ
184541
184910
  canvasId: p3.canvasId,
184542
184911
  turns: created2?.turns ?? [],
184543
184912
  provider,
184544
- modelId
184913
+ modelId,
184914
+ ...created2?.agentId ? { agentId: created2.agentId } : {}
184545
184915
  });
184546
184916
  } catch (err) {
184547
184917
  await store.remove(p3.canvasId, branched.sessionId).catch(() => void 0);
@@ -184655,9 +185025,13 @@ function agentSessionRoutes(store, runtime, config2, branches, preTurn, hub, onQ
184655
185025
  });
184656
185026
  return app;
184657
185027
  }
184658
- async function readGoalForSession(config2, sessionId) {
185028
+ async function readGoalForSession(config2, sessionId, store, canvasId = "") {
184659
185029
  try {
184660
- const scratch = sessionScratchpadPath(agentRoot(config2.dataDir), sessionId);
185030
+ let agentId;
185031
+ if (store && canvasId) {
185032
+ agentId = (await store.get(canvasId, sessionId))?.agentId;
185033
+ }
185034
+ const scratch = sessionScratchpadPath(agentRoot(config2.dataDir), sessionId, agentId);
184661
185035
  const state2 = await readGoalState(scratch);
184662
185036
  return state2 ?? void 0;
184663
185037
  } catch {
@@ -184877,7 +185251,9 @@ var AGENT_SERVICES = {
184877
185251
  hub: "agentHub",
184878
185252
  queue: "agentQueue",
184879
185253
  goal: "agentGoal",
184880
- loadSdk: "agentLoadSdk"
185254
+ loadSdk: "agentLoadSdk",
185255
+ profiles: "agentProfiles",
185256
+ canvasChange: "agentCanvasAgentChange"
184881
185257
  };
184882
185258
  function need(ctx, name2) {
184883
185259
  const v = ctx.tryGet(name2);
@@ -184890,7 +185266,14 @@ var agentConfigPlugin = {
184890
185266
  name: "agent-routes",
184891
185267
  inject: [AGENT_SERVICES.config, AGENT_SERVICES.runtime],
184892
185268
  apply(ctx) {
184893
- routesOf(ctx).adopt(agentRoutes(need(ctx, AGENT_SERVICES.config), need(ctx, AGENT_SERVICES.runtime)));
185269
+ routesOf(ctx).adopt(
185270
+ agentRoutes(
185271
+ need(ctx, AGENT_SERVICES.config),
185272
+ need(ctx, AGENT_SERVICES.runtime),
185273
+ ctx.tryGet(AGENT_SERVICES.profiles),
185274
+ ctx.tryGet(AGENT_SERVICES.canvasChange)
185275
+ )
185276
+ );
184894
185277
  }
184895
185278
  };
184896
185279
  var agentChatPlugin = {
@@ -184979,6 +185362,8 @@ async function assemble(ctx, ports) {
184979
185362
  ctx.inject(AGENT_SERVICES.queue, services.queue);
184980
185363
  ctx.inject(AGENT_SERVICES.goal, services.goal);
184981
185364
  ctx.inject(AGENT_SERVICES.loadSdk, services.loadSdk);
185365
+ if (ports.agentProfiles) ctx.inject(AGENT_SERVICES.profiles, ports.agentProfiles);
185366
+ if (ports.onCanvasAgentChange) ctx.inject(AGENT_SERVICES.canvasChange, ports.onCanvasAgentChange);
184982
185367
  services.config.setPromptSectionViews(() => ports.promptSections());
184983
185368
  const initialContext = ports.runtimeContext?.();
184984
185369
  if (initialContext) services.config.setRuntimeContext(initialContext);