rterm-backend 3.7.5 → 3.7.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bin/gybackend.cjs +1588 -604
  2. package/package.json +1 -1
package/bin/gybackend.cjs CHANGED
@@ -11,10 +11,10 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
11
  var __getOwnPropNames = Object.getOwnPropertyNames;
12
12
  var __getProtoOf = Object.getPrototypeOf;
13
13
  var __hasOwnProp = Object.prototype.hasOwnProperty;
14
- var __glob = (map3) => (path32) => {
15
- var fn = map3[path32];
14
+ var __glob = (map3) => (path33) => {
15
+ var fn = map3[path33];
16
16
  if (fn) return fn();
17
- throw new Error("Module not found in bundle: " + path32);
17
+ throw new Error("Module not found in bundle: " + path33);
18
18
  };
19
19
  var __esm = (fn, res) => function __init() {
20
20
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
@@ -9040,7 +9040,7 @@ var require_eventemitter3 = __commonJS({
9040
9040
  if (listeners.fn) return 1;
9041
9041
  return listeners.length;
9042
9042
  };
9043
- EventEmitter4.prototype.emit = function emit10(event, a1, a2, a3, a4, a5) {
9043
+ EventEmitter4.prototype.emit = function emit11(event, a1, a2, a3, a4, a5) {
9044
9044
  var evt = prefix ? prefix + event : event;
9045
9045
  if (!this._events[evt]) return false;
9046
9046
  var listeners = this._events[evt], len = arguments.length, args, i;
@@ -12024,8 +12024,8 @@ var init_parseUtil = __esm({
12024
12024
  init_errors();
12025
12025
  init_en();
12026
12026
  makeIssue = (params) => {
12027
- const { data, path: path32, errorMaps, issueData } = params;
12028
- const fullPath = [...path32, ...issueData.path || []];
12027
+ const { data, path: path33, errorMaps, issueData } = params;
12028
+ const fullPath = [...path33, ...issueData.path || []];
12029
12029
  const fullIssue = {
12030
12030
  ...issueData,
12031
12031
  path: fullPath
@@ -12333,11 +12333,11 @@ var init_types = __esm({
12333
12333
  init_parseUtil();
12334
12334
  init_util();
12335
12335
  ParseInputLazyPath = class {
12336
- constructor(parent, value, path32, key) {
12336
+ constructor(parent, value, path33, key) {
12337
12337
  this._cachedPath = [];
12338
12338
  this.parent = parent;
12339
12339
  this.data = value;
12340
- this._path = path32;
12340
+ this._path = path33;
12341
12341
  this._key = key;
12342
12342
  }
12343
12343
  get path() {
@@ -27268,11 +27268,11 @@ var require_pdf_worker = __commonJS({
27268
27268
  var nameTree = new NameTree(nameTreeRef, xref);
27269
27269
  var names = nameTree.getAll();
27270
27270
  for (var name in names) {
27271
- var fs23 = new FileSpec(names[name], xref);
27271
+ var fs24 = new FileSpec(names[name], xref);
27272
27272
  if (!attachments) {
27273
27273
  attachments = /* @__PURE__ */ Object.create(null);
27274
27274
  }
27275
- attachments[(0, _util.stringToPDFString)(name)] = fs23.serializable;
27275
+ attachments[(0, _util.stringToPDFString)(name)] = fs24.serializable;
27276
27276
  }
27277
27277
  }
27278
27278
  return (0, _util.shadow)(this, "attachments", attachments);
@@ -32572,8 +32572,8 @@ var require_pdf_worker = __commonJS({
32572
32572
  if (font.data && (isAddToPathSet || this.options.disableFontFace)) {
32573
32573
  var buildPath = function buildPath2(fontChar) {
32574
32574
  if (!font.renderer.hasBuiltPath(fontChar)) {
32575
- var path32 = font.renderer.getPathJs(fontChar);
32576
- _this5.handler.send("commonobj", [font.loadedName + "_path_" + fontChar, "FontPath", path32]);
32575
+ var path33 = font.renderer.getPathJs(fontChar);
32576
+ _this5.handler.send("commonobj", [font.loadedName + "_path_" + fontChar, "FontPath", path33]);
32577
32577
  }
32578
32578
  };
32579
32579
  for (var i = 0, ii = glyphs.length; i < ii; i++) {
@@ -75261,10 +75261,10 @@ var require_pdf = __commonJS({
75261
75261
  ctx.save();
75262
75262
  ctx.beginPath();
75263
75263
  for (var i = 0; i < paths.length; i++) {
75264
- var path32 = paths[i];
75265
- ctx.setTransform.apply(ctx, path32.transform);
75266
- ctx.translate(path32.x, path32.y);
75267
- path32.addToPath(ctx, path32.fontSize);
75264
+ var path33 = paths[i];
75265
+ ctx.setTransform.apply(ctx, path33.transform);
75266
+ ctx.translate(path33.x, path33.y);
75267
+ path33.addToPath(ctx, path33.fontSize);
75268
75268
  }
75269
75269
  ctx.restore();
75270
75270
  ctx.clip();
@@ -77124,7 +77124,7 @@ var require_pdf = __commonJS({
77124
77124
  throw new TypeError("Cannot call a class as a function");
77125
77125
  }
77126
77126
  }
77127
- var fs23 = require("fs");
77127
+ var fs24 = require("fs");
77128
77128
  var http2 = require("http");
77129
77129
  var https2 = require("https");
77130
77130
  var url2 = require("url");
@@ -77457,8 +77457,8 @@ var require_pdf = __commonJS({
77457
77457
  function PDFNodeStreamFsFullReader2(stream) {
77458
77458
  _classCallCheck(this, PDFNodeStreamFsFullReader2);
77459
77459
  var _this7 = _possibleConstructorReturn(this, (PDFNodeStreamFsFullReader2.__proto__ || Object.getPrototypeOf(PDFNodeStreamFsFullReader2)).call(this, stream));
77460
- var path32 = decodeURI(_this7._url.path);
77461
- fs23.lstat(path32, function(error40, stat) {
77460
+ var path33 = decodeURI(_this7._url.path);
77461
+ fs24.lstat(path33, function(error40, stat) {
77462
77462
  if (error40) {
77463
77463
  _this7._errored = true;
77464
77464
  _this7._reason = error40;
@@ -77466,7 +77466,7 @@ var require_pdf = __commonJS({
77466
77466
  return;
77467
77467
  }
77468
77468
  _this7._contentLength = stat.size;
77469
- _this7._setReadableStream(fs23.createReadStream(path32));
77469
+ _this7._setReadableStream(fs24.createReadStream(path33));
77470
77470
  _this7._headersCapability.resolve();
77471
77471
  });
77472
77472
  return _this7;
@@ -77478,7 +77478,7 @@ var require_pdf = __commonJS({
77478
77478
  function PDFNodeStreamFsRangeReader2(stream, start, end) {
77479
77479
  _classCallCheck(this, PDFNodeStreamFsRangeReader2);
77480
77480
  var _this8 = _possibleConstructorReturn(this, (PDFNodeStreamFsRangeReader2.__proto__ || Object.getPrototypeOf(PDFNodeStreamFsRangeReader2)).call(this, stream));
77481
- _this8._setReadableStream(fs23.createReadStream(decodeURI(_this8._url.path), {
77481
+ _this8._setReadableStream(fs24.createReadStream(decodeURI(_this8._url.path), {
77482
77482
  start,
77483
77483
  end: end - 1
77484
77484
  }));
@@ -89472,11 +89472,11 @@ var require_pdf_worker2 = __commonJS({
89472
89472
  var nameTree = new NameTree(nameTreeRef, xref);
89473
89473
  var names = nameTree.getAll();
89474
89474
  for (var name in names) {
89475
- var fs23 = new FileSpec(names[name], xref);
89475
+ var fs24 = new FileSpec(names[name], xref);
89476
89476
  if (!attachments) {
89477
89477
  attachments = /* @__PURE__ */ Object.create(null);
89478
89478
  }
89479
- attachments[(0, _util.stringToPDFString)(name)] = fs23.serializable;
89479
+ attachments[(0, _util.stringToPDFString)(name)] = fs24.serializable;
89480
89480
  }
89481
89481
  }
89482
89482
  return (0, _util.shadow)(this, "attachments", attachments);
@@ -94776,8 +94776,8 @@ var require_pdf_worker2 = __commonJS({
94776
94776
  if (font.data && (isAddToPathSet || this.options.disableFontFace)) {
94777
94777
  var buildPath = function buildPath2(fontChar) {
94778
94778
  if (!font.renderer.hasBuiltPath(fontChar)) {
94779
- var path32 = font.renderer.getPathJs(fontChar);
94780
- _this5.handler.send("commonobj", [font.loadedName + "_path_" + fontChar, "FontPath", path32]);
94779
+ var path33 = font.renderer.getPathJs(fontChar);
94780
+ _this5.handler.send("commonobj", [font.loadedName + "_path_" + fontChar, "FontPath", path33]);
94781
94781
  }
94782
94782
  };
94783
94783
  for (var i = 0, ii = glyphs.length; i < ii; i++) {
@@ -137573,10 +137573,10 @@ var require_pdf2 = __commonJS({
137573
137573
  ctx.save();
137574
137574
  ctx.beginPath();
137575
137575
  for (var i = 0; i < paths.length; i++) {
137576
- var path32 = paths[i];
137577
- ctx.setTransform.apply(ctx, path32.transform);
137578
- ctx.translate(path32.x, path32.y);
137579
- path32.addToPath(ctx, path32.fontSize);
137576
+ var path33 = paths[i];
137577
+ ctx.setTransform.apply(ctx, path33.transform);
137578
+ ctx.translate(path33.x, path33.y);
137579
+ path33.addToPath(ctx, path33.fontSize);
137580
137580
  }
137581
137581
  ctx.restore();
137582
137582
  ctx.clip();
@@ -138960,7 +138960,7 @@ var require_pdf2 = __commonJS({
138960
138960
  throw new TypeError("Cannot call a class as a function");
138961
138961
  }
138962
138962
  }
138963
- var fs23 = require("fs");
138963
+ var fs24 = require("fs");
138964
138964
  var http2 = require("http");
138965
138965
  var https2 = require("https");
138966
138966
  var url2 = require("url");
@@ -139293,8 +139293,8 @@ var require_pdf2 = __commonJS({
139293
139293
  function PDFNodeStreamFsFullReader2(stream) {
139294
139294
  _classCallCheck(this, PDFNodeStreamFsFullReader2);
139295
139295
  var _this7 = _possibleConstructorReturn(this, (PDFNodeStreamFsFullReader2.__proto__ || Object.getPrototypeOf(PDFNodeStreamFsFullReader2)).call(this, stream));
139296
- var path32 = decodeURI(_this7._url.path);
139297
- fs23.lstat(path32, function(error40, stat) {
139296
+ var path33 = decodeURI(_this7._url.path);
139297
+ fs24.lstat(path33, function(error40, stat) {
139298
139298
  if (error40) {
139299
139299
  _this7._errored = true;
139300
139300
  _this7._reason = error40;
@@ -139302,7 +139302,7 @@ var require_pdf2 = __commonJS({
139302
139302
  return;
139303
139303
  }
139304
139304
  _this7._contentLength = stat.size;
139305
- _this7._setReadableStream(fs23.createReadStream(path32));
139305
+ _this7._setReadableStream(fs24.createReadStream(path33));
139306
139306
  _this7._headersCapability.resolve();
139307
139307
  });
139308
139308
  return _this7;
@@ -139314,7 +139314,7 @@ var require_pdf2 = __commonJS({
139314
139314
  function PDFNodeStreamFsRangeReader2(stream, start, end) {
139315
139315
  _classCallCheck(this, PDFNodeStreamFsRangeReader2);
139316
139316
  var _this8 = _possibleConstructorReturn(this, (PDFNodeStreamFsRangeReader2.__proto__ || Object.getPrototypeOf(PDFNodeStreamFsRangeReader2)).call(this, stream));
139317
- _this8._setReadableStream(fs23.createReadStream(decodeURI(_this8._url.path), {
139317
+ _this8._setReadableStream(fs24.createReadStream(decodeURI(_this8._url.path), {
139318
139318
  start,
139319
139319
  end: end - 1
139320
139320
  }));
@@ -156879,8 +156879,8 @@ var require_pdf_worker3 = __commonJS({
156879
156879
  if (font.data && (isAddToPathSet || this.options.disableFontFace)) {
156880
156880
  var buildPath = function buildPath2(fontChar) {
156881
156881
  if (!font.renderer.hasBuiltPath(fontChar)) {
156882
- var path32 = font.renderer.getPathJs(fontChar);
156883
- _this5.handler.send("commonobj", [font.loadedName + "_path_" + fontChar, "FontPath", path32]);
156882
+ var path33 = font.renderer.getPathJs(fontChar);
156883
+ _this5.handler.send("commonobj", [font.loadedName + "_path_" + fontChar, "FontPath", path33]);
156884
156884
  }
156885
156885
  };
156886
156886
  for (var i = 0, ii = glyphs.length; i < ii; i++) {
@@ -161698,11 +161698,11 @@ var require_pdf_worker3 = __commonJS({
161698
161698
  var nameTree = new NameTree(nameTreeRef, xref);
161699
161699
  var names = nameTree.getAll();
161700
161700
  for (var name in names) {
161701
- var fs23 = new FileSpec(names[name], xref);
161701
+ var fs24 = new FileSpec(names[name], xref);
161702
161702
  if (!attachments) {
161703
161703
  attachments = /* @__PURE__ */ Object.create(null);
161704
161704
  }
161705
- attachments[(0, _util.stringToPDFString)(name)] = fs23.serializable;
161705
+ attachments[(0, _util.stringToPDFString)(name)] = fs24.serializable;
161706
161706
  }
161707
161707
  }
161708
161708
  return (0, _util.shadow)(this, "attachments", attachments);
@@ -191335,10 +191335,10 @@ var require_pdf3 = __commonJS({
191335
191335
  ctx.save();
191336
191336
  ctx.beginPath();
191337
191337
  for (var i = 0; i < paths.length; i++) {
191338
- var path32 = paths[i];
191339
- ctx.setTransform.apply(ctx, path32.transform);
191340
- ctx.translate(path32.x, path32.y);
191341
- path32.addToPath(ctx, path32.fontSize);
191338
+ var path33 = paths[i];
191339
+ ctx.setTransform.apply(ctx, path33.transform);
191340
+ ctx.translate(path33.x, path33.y);
191341
+ path33.addToPath(ctx, path33.fontSize);
191342
191342
  }
191343
191343
  ctx.restore();
191344
191344
  ctx.clip();
@@ -203583,11 +203583,11 @@ var require_pdf_worker4 = __commonJS({
203583
203583
  var nameTree = new NameTree(nameTreeRef, xref);
203584
203584
  var names = nameTree.getAll();
203585
203585
  for (var name in names) {
203586
- var fs23 = new FileSpec(names[name], xref);
203586
+ var fs24 = new FileSpec(names[name], xref);
203587
203587
  if (!attachments) {
203588
203588
  attachments = /* @__PURE__ */ Object.create(null);
203589
203589
  }
203590
- attachments[(0, _util.stringToPDFString)(name)] = fs23.serializable;
203590
+ attachments[(0, _util.stringToPDFString)(name)] = fs24.serializable;
203591
203591
  }
203592
203592
  }
203593
203593
  return (0, _util.shadow)(this, "attachments", attachments);
@@ -216733,8 +216733,8 @@ var require_pdf_worker4 = __commonJS({
216733
216733
  if (font.data && (isAddToPathSet || this.options.disableFontFace || state.fillColorSpace.name === "Pattern")) {
216734
216734
  var buildPath = function buildPath2(fontChar) {
216735
216735
  if (!font.renderer.hasBuiltPath(fontChar)) {
216736
- var path32 = font.renderer.getPathJs(fontChar);
216737
- _this5.handler.send("commonobj", [font.loadedName + "_path_" + fontChar, "FontPath", path32]);
216736
+ var path33 = font.renderer.getPathJs(fontChar);
216737
+ _this5.handler.send("commonobj", [font.loadedName + "_path_" + fontChar, "FontPath", path33]);
216738
216738
  }
216739
216739
  };
216740
216740
  for (var i = 0, ii = glyphs.length; i < ii; i++) {
@@ -248698,10 +248698,10 @@ var require_pdf4 = __commonJS({
248698
248698
  ctx.save();
248699
248699
  ctx.beginPath();
248700
248700
  for (var i = 0; i < paths.length; i++) {
248701
- var path32 = paths[i];
248702
- ctx.setTransform.apply(ctx, path32.transform);
248703
- ctx.translate(path32.x, path32.y);
248704
- path32.addToPath(ctx, path32.fontSize);
248701
+ var path33 = paths[i];
248702
+ ctx.setTransform.apply(ctx, path33.transform);
248703
+ ctx.translate(path33.x, path33.y);
248704
+ path33.addToPath(ctx, path33.fontSize);
248705
248705
  }
248706
248706
  ctx.restore();
248707
248707
  ctx.clip();
@@ -253970,7 +253970,7 @@ var require_pdf4 = __commonJS({
253970
253970
  throw new TypeError("Cannot call a class as a function");
253971
253971
  }
253972
253972
  }
253973
- var fs23 = require("fs");
253973
+ var fs24 = require("fs");
253974
253974
  var http2 = require("http");
253975
253975
  var https2 = require("https");
253976
253976
  var url2 = require("url");
@@ -254324,11 +254324,11 @@ var require_pdf4 = __commonJS({
254324
254324
  function PDFNodeStreamFsFullReader2(stream) {
254325
254325
  _classCallCheck(this, PDFNodeStreamFsFullReader2);
254326
254326
  var _this7 = _possibleConstructorReturn(this, (PDFNodeStreamFsFullReader2.__proto__ || Object.getPrototypeOf(PDFNodeStreamFsFullReader2)).call(this, stream));
254327
- var path32 = decodeURIComponent(_this7._url.path);
254327
+ var path33 = decodeURIComponent(_this7._url.path);
254328
254328
  if (fileUriRegex.test(_this7._url.href)) {
254329
- path32 = path32.replace(/^\//, "");
254329
+ path33 = path33.replace(/^\//, "");
254330
254330
  }
254331
- fs23.lstat(path32, function(error40, stat) {
254331
+ fs24.lstat(path33, function(error40, stat) {
254332
254332
  if (error40) {
254333
254333
  _this7._errored = true;
254334
254334
  _this7._reason = error40;
@@ -254336,7 +254336,7 @@ var require_pdf4 = __commonJS({
254336
254336
  return;
254337
254337
  }
254338
254338
  _this7._contentLength = stat.size;
254339
- _this7._setReadableStream(fs23.createReadStream(path32));
254339
+ _this7._setReadableStream(fs24.createReadStream(path33));
254340
254340
  _this7._headersCapability.resolve();
254341
254341
  });
254342
254342
  return _this7;
@@ -254348,11 +254348,11 @@ var require_pdf4 = __commonJS({
254348
254348
  function PDFNodeStreamFsRangeReader2(stream, start, end) {
254349
254349
  _classCallCheck(this, PDFNodeStreamFsRangeReader2);
254350
254350
  var _this8 = _possibleConstructorReturn(this, (PDFNodeStreamFsRangeReader2.__proto__ || Object.getPrototypeOf(PDFNodeStreamFsRangeReader2)).call(this, stream));
254351
- var path32 = decodeURIComponent(_this8._url.path);
254351
+ var path33 = decodeURIComponent(_this8._url.path);
254352
254352
  if (fileUriRegex.test(_this8._url.href)) {
254353
- path32 = path32.replace(/^\//, "");
254353
+ path33 = path33.replace(/^\//, "");
254354
254354
  }
254355
- _this8._setReadableStream(fs23.createReadStream(path32, {
254355
+ _this8._setReadableStream(fs24.createReadStream(path33, {
254356
254356
  start,
254357
254357
  end: end - 1
254358
254358
  }));
@@ -255457,6 +255457,299 @@ var require_pdf_parse2 = __commonJS({
255457
255457
  }
255458
255458
  });
255459
255459
 
255460
+ // ../../packages/backend/src/services/learning/compoundingKnowledge.ts
255461
+ var compoundingKnowledge_exports = {};
255462
+ __export(compoundingKnowledge_exports, {
255463
+ EXTRACTORS: () => EXTRACTORS,
255464
+ GATED_MUTATIONS: () => GATED_MUTATIONS,
255465
+ REVIEW_VERBS: () => REVIEW_VERBS,
255466
+ appendLessonsToMemory: () => appendLessonsToMemory,
255467
+ connectionIdentity: () => connectionIdentity,
255468
+ extractLessons: () => extractLessons,
255469
+ formatLessonMarkdown: () => formatLessonMarkdown,
255470
+ isTrivialRun: () => isTrivialRun,
255471
+ matchGatedMutation: () => matchGatedMutation,
255472
+ matchReviewVerb: () => matchReviewVerb,
255473
+ memoryHasFingerprint: () => memoryHasFingerprint
255474
+ });
255475
+ function isTrivialRun(inputPreview, error40) {
255476
+ const input = (inputPreview || "").trim();
255477
+ if (!input && !error40) return true;
255478
+ if (error40 && error40.trim()) return false;
255479
+ if (TRIVIAL_INPUT.test(input)) return true;
255480
+ if (input.length > 0 && input.length < 8 && !/[\\/]/.test(input) && !/\b(error|fail|join|install|patch)\b/i.test(input)) {
255481
+ return true;
255482
+ }
255483
+ return false;
255484
+ }
255485
+ function lesson(extractor, fingerprint, title, body, neverDo, instead, tags) {
255486
+ return { extractor, fingerprint, title, body, neverDo, instead, tags };
255487
+ }
255488
+ function extractLessons(...parts) {
255489
+ const haystack = parts.filter(Boolean).join("\n");
255490
+ if (!haystack.trim()) return [];
255491
+ const byFp = /* @__PURE__ */ new Map();
255492
+ for (const ex of EXTRACTORS) {
255493
+ const hit = ex.match(haystack);
255494
+ if (hit && !byFp.has(hit.fingerprint)) byFp.set(hit.fingerprint, hit);
255495
+ }
255496
+ return [...byFp.values()];
255497
+ }
255498
+ function formatLessonMarkdown(item, meta) {
255499
+ const at = meta.at || (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
255500
+ const occ = meta.occurrence && meta.occurrence > 1 ? ` (seen x${meta.occurrence})` : "";
255501
+ const run = meta.runId ? ` run ${meta.runId}` : "";
255502
+ return [
255503
+ `## LESSON (auto, ${at},${run})${occ}`,
255504
+ "",
255505
+ `**${item.title}**`,
255506
+ "",
255507
+ item.body,
255508
+ "",
255509
+ `- NEVER: ${item.neverDo}`,
255510
+ `- INSTEAD: ${item.instead}`,
255511
+ `- fingerprint: \`${item.fingerprint}\``,
255512
+ ""
255513
+ ].join("\n");
255514
+ }
255515
+ function memoryHasFingerprint(memory, fingerprint) {
255516
+ return memory.includes("`" + fingerprint + "`") || memory.includes("\n" + fingerprint + "\n");
255517
+ }
255518
+ function appendLessonsToMemory(current, lessons, meta) {
255519
+ let next = current.endsWith("\n") || current === "" ? current : current + "\n";
255520
+ if (!next.trim()) next = "# Memory\n\n- Add durable cross-session notes here.\n\n";
255521
+ const added = [];
255522
+ for (const item of lessons) {
255523
+ if (memoryHasFingerprint(next, item.fingerprint)) continue;
255524
+ next += formatLessonMarkdown(item, meta);
255525
+ added.push(item.fingerprint);
255526
+ }
255527
+ return { next, added };
255528
+ }
255529
+ function matchGatedMutation(command) {
255530
+ const c = command.trim();
255531
+ for (const g of GATED_MUTATIONS) {
255532
+ if (g.re.test(c)) return { id: g.id, requireProbeTag: g.requireProbeTag };
255533
+ }
255534
+ return null;
255535
+ }
255536
+ function matchReviewVerb(command) {
255537
+ for (const v of REVIEW_VERBS) {
255538
+ if (v.re.test(command)) return v.id;
255539
+ }
255540
+ return null;
255541
+ }
255542
+ function connectionIdentity(opts) {
255543
+ if (opts.name && opts.name.trim()) return opts.name.trim();
255544
+ const host = (opts.host || "").trim() || "unknown-host";
255545
+ const rest = [opts.transport, opts.auth, opts.domain].filter(Boolean).join("/");
255546
+ return rest ? `${host} (${rest})` : host;
255547
+ }
255548
+ var TRIVIAL_INPUT, EXTRACTORS, GATED_MUTATIONS, REVIEW_VERBS;
255549
+ var init_compoundingKnowledge = __esm({
255550
+ "../../packages/backend/src/services/learning/compoundingKnowledge.ts"() {
255551
+ "use strict";
255552
+ TRIVIAL_INPUT = /^(1\s*\+\s*1|hello|hi|hey|ok|thanks|ping|pong)\s*[.!?]*$/i;
255553
+ EXTRACTORS = [
255554
+ {
255555
+ name: "psrp-invalid-selectors",
255556
+ match: (h) => {
255557
+ if (!/invalidselectors/i.test(h)) return null;
255558
+ return lesson(
255559
+ "psrp-invalid-selectors",
255560
+ "psrp.invalid-selectors.dest-and-init",
255561
+ "PSRP Receive after Create returns w:InvalidSelectors",
255562
+ "Windows accepts Create (ShellId returned) then fails runspace init silently. The SOAP envelope is usually fine \u2014 the bug is inside the base64 creationXml PSRP fragments.",
255563
+ 'Do not tweak SOAP headers / xmlns prefixes / SessionId / OptionSet / keep-alive to "fix" InvalidSelectors after a successful Create.',
255564
+ "Decode creationXml: every client-to-server PSRP message Destination byte is 2 (server). INIT_RUNSPACEPOOL must send full PSThreadOptions/ApartmentState/HostInfo objects, not Nil. Byte-compare against a pypsrp 0.8.1 capture.",
255565
+ ["psrp", "winrm"]
255566
+ );
255567
+ }
255568
+ },
255569
+ {
255570
+ name: "netuseadd-64",
255571
+ match: (h) => {
255572
+ const netuse = /netuseadd/i.test(h) && (/64\b/.test(h) || /0x40/i.test(h) || /ipc\$/i.test(h));
255573
+ const named = /network name is no longer available/i.test(h) && /add-computer|netlogon|ipc\$|domain join/i.test(h);
255574
+ const err64 = /ERROR_NETNAME_DELETED/i.test(h);
255575
+ if (!netuse && !named && !err64) return null;
255576
+ return lesson(
255577
+ "netuseadd-64",
255578
+ "ad.join.netuseadd-64-use-djoin",
255579
+ "Domain join fails at NetUseAdd \\\\DC\\IPC$ (error 64 / 0x40)",
255580
+ "DNS, LDAP 389, Kerberos 88 and TCP 445 can all succeed while SMB IPC$/NETLOGON still fails from a workgroup host. Retrying Add-Computer will not fix it.",
255581
+ 'Do not retry Add-Computer after NetUseAdd 64 / "network name is no longer available". Do not keep flipping SMB signing as the next fix.',
255582
+ "Use offline domain join: djoin /provision on the DC, copy the blob without SMB, djoin /requestODJ /localos on the member, reboot. Confirm with Get-ADComputer after.",
255583
+ ["ad", "smb", "join"]
255584
+ );
255585
+ }
255586
+ },
255587
+ {
255588
+ name: "cli-dropped-bearer",
255589
+ match: (h) => {
255590
+ if (/missing access token/i.test(h)) {
255591
+ return lesson(
255592
+ "cli-dropped-bearer",
255593
+ "rterm-cli.native-ws.dropped-authorization",
255594
+ "rterm-cli remote gateway closes with missing access token",
255595
+ "On Node >= 21 the CLI used native WebSocket without the options object, so Authorization Bearer was never sent. Localhost (token-exempt) still worked, which looks like a server bug.",
255596
+ "Do not debug the remote daemon first when localhost ping works and remote ping dies with Connection closed before response.",
255597
+ "Send the token both as ?access_token= (query param) AND as the Authorization header on native WebSocket / ws.",
255598
+ ["cli", "gateway"]
255599
+ );
255600
+ }
255601
+ if (/connection closed before response/i.test(h) && /token|gateway|rterm-cli|websocket/i.test(h)) {
255602
+ return lesson(
255603
+ "cli-dropped-bearer",
255604
+ "rterm-cli.native-ws.dropped-authorization",
255605
+ "rterm-cli remote gateway closes with missing access token",
255606
+ "On Node >= 21 the CLI used native WebSocket without the options object, so Authorization Bearer was never sent.",
255607
+ "Do not debug the remote daemon first when localhost ping works and remote ping dies with Connection closed before response.",
255608
+ "Send the token both as ?access_token= AND as the Authorization header.",
255609
+ ["cli", "gateway"]
255610
+ );
255611
+ }
255612
+ return null;
255613
+ }
255614
+ },
255615
+ {
255616
+ name: "duplicate-tools",
255617
+ match: (h) => {
255618
+ if (!/duplicate tool/i.test(h)) return null;
255619
+ return lesson(
255620
+ "duplicate-tools",
255621
+ "agent.duplicate-tool-definitions",
255622
+ "Provider HTTP 400: duplicate tool definitions",
255623
+ "Plugin tool schemas were appended twice (session cache + bind-time). Strict providers (Grok, Fable) reject the request.",
255624
+ "Do not append plugin tools both at session-bind cache time and again at bindTools() time.",
255625
+ "Keep plugin schemas only at bind-time (freshest) and run dedupeToolsByName() on every bindTools() call.",
255626
+ ["agent", "tools"]
255627
+ );
255628
+ }
255629
+ },
255630
+ {
255631
+ name: "npm-eacces-root-cache",
255632
+ match: (h) => {
255633
+ if (!/eacces/i.test(h)) return null;
255634
+ if (!/root-owned|cache folder|npm/i.test(h)) return null;
255635
+ return lesson(
255636
+ "npm-eacces-root-cache",
255637
+ "npm.eacces.root-owned-cache",
255638
+ "npm install -g fails with EACCES on a root-owned cache",
255639
+ "A past sudo npm left root-owned files in ~/.npm-cache. Retrying with sudo is the wrong fix in an agent context.",
255640
+ "Do not sudo npm install to fix EACCES when the cache is root-owned.",
255641
+ "Retry once with npm install -g <pkg> --cache /tmp/npm-fresh (or the lifecycle script npmInstallG path).",
255642
+ ["npm"]
255643
+ );
255644
+ }
255645
+ },
255646
+ {
255647
+ name: "psrp-basic-401-after-dc",
255648
+ match: (h) => {
255649
+ const unauthorized = /\b401\b/.test(h) || /unauthorized/i.test(h);
255650
+ if (!unauthorized) return null;
255651
+ if (!/psrp|winrm|basic/i.test(h)) return null;
255652
+ const afterDc = /domain.?controller|addsforest|dcpromo|corp\.local|promoted|after promotion/i.test(h);
255653
+ if (!afterDc && !/basic/i.test(h)) return null;
255654
+ if (!afterDc && !(/basic/i.test(h) && /401|unauthorized/i.test(h) && /psrp|winrm/i.test(h))) {
255655
+ return null;
255656
+ }
255657
+ return lesson(
255658
+ "psrp-basic-401-after-dc",
255659
+ "ad.dc.basic-401-use-negotiate",
255660
+ "PSRP/WinRM Basic 401 after promoting a DC",
255661
+ "After Install-ADDSForest the machine is a DC. Basic auth to the same Administrator password often 401s; Negotiate/NTLMv2 with CORP\\Administrator still works.",
255662
+ "Do not keep using auth:basic against a box you just promoted to a DC.",
255663
+ "Switch the saved connection to transport:psrp auth:negotiate domain:CORP username:Administrator (as CORP-DC1).",
255664
+ ["ad", "psrp", "auth"]
255665
+ );
255666
+ }
255667
+ },
255668
+ {
255669
+ name: "winrm-dollar-mangle",
255670
+ match: (h) => {
255671
+ if (/was unexpected at this time/i.test(h)) {
255672
+ return lesson(
255673
+ "winrm-dollar-mangle",
255674
+ "winrm.cmd-wrapping.dollar-mangle",
255675
+ "WinRM cmd wrapping eats $variables in PowerShell",
255676
+ "HTTP WinRM tabs often wrap through cmd.exe, so $env:FOO is expanded/eaten before PowerShell sees it.",
255677
+ 'Do not send $env: / $foo on an HTTP WinRM tab and treat empty output as "the box has no env".',
255678
+ "Use PSRP (script in the message body) or Write-Output ((Get-CimInstance ...)) forms that avoid $.",
255679
+ ["winrm"]
255680
+ );
255681
+ }
255682
+ if (/\$env:COMPUTERNAME/.test(h) && /empty|undefined|mangle/i.test(h)) {
255683
+ return lesson(
255684
+ "winrm-dollar-mangle",
255685
+ "winrm.cmd-wrapping.dollar-mangle",
255686
+ "WinRM cmd wrapping eats $variables in PowerShell",
255687
+ "HTTP WinRM tabs often wrap through cmd.exe.",
255688
+ "Do not send $env: on an HTTP WinRM tab.",
255689
+ "Use PSRP or CIM cmdlets without $env:.",
255690
+ ["winrm"]
255691
+ );
255692
+ }
255693
+ return null;
255694
+ }
255695
+ },
255696
+ {
255697
+ name: "soap-guess-loop",
255698
+ match: (h) => {
255699
+ if (!/invalidselectors/i.test(h)) return null;
255700
+ if (!/optionset|xmlns:|sessionid|keep-alive|prefix/i.test(h)) return null;
255701
+ if (!/still fail|same fault|another.*probe|tweak/i.test(h)) return null;
255702
+ return lesson(
255703
+ "soap-guess-loop",
255704
+ "psrp.soap-guessing-vs-payload",
255705
+ "SOAP header tweaks do not fix PSRP InvalidSelectors",
255706
+ "When Create succeeds and Receive fails, the envelope is probably already fine. Further OptionSet/prefix/SessionId changes waste the session.",
255707
+ "Do not run another uninstrumented live SOAP probe after 2+ identical InvalidSelectors.",
255708
+ "Dump creationXml fragments (struct dest/type at bytes 0-8 of each PSRP message) and diff against pypsrp.",
255709
+ ["psrp"]
255710
+ );
255711
+ }
255712
+ },
255713
+ {
255714
+ name: "exec-command-multiline-poison",
255715
+ match: (h) => {
255716
+ if (/echo-mangled/i.test(h) || /only the first export/i.test(h) || /dquote prompt/i.test(h)) {
255717
+ return lesson(
255718
+ "exec-command-multiline-poison",
255719
+ "agent.exec_command.multiline-export",
255720
+ "Multi-line export/python -c in exec_command only runs the first line",
255721
+ "GyShell exec_command with separate export lines or inline python3 -c heredocs gets echo-mangled or only the first statement runs.",
255722
+ "Do not put multiple export X= lines on separate exec_command invocations expecting them to share a shell, and do not use inline python3 -c with nested quotes.",
255723
+ "One line with semicolons, or write_file a script then exec it. Password via stdin, never argv.",
255724
+ ["agent", "shell"]
255725
+ );
255726
+ }
255727
+ return null;
255728
+ }
255729
+ }
255730
+ ];
255731
+ GATED_MUTATIONS = [
255732
+ { id: "Add-Computer", re: /\bAdd-Computer\b/i, requireProbeTag: "ad-join" },
255733
+ { id: "Install-ADDSForest", re: /\bInstall-ADDSForest\b/i, requireProbeTag: "ad-promo" },
255734
+ { id: "djoin-provision", re: /\bdjoin(\.exe)?\s+\/provision\b/i, requireProbeTag: "ad-join" },
255735
+ { id: "Set-SmbServerConfiguration", re: /\bSet-SmbServerConfiguration\b/i, requireProbeTag: "smb" },
255736
+ { id: "sg-ingress", re: /\bauthorize-security-group-ingress\b/i, requireProbeTag: "aws-sg" },
255737
+ { id: "Remove-ADComputer", re: /\bRemove-ADComputer\b/i, requireProbeTag: "ad-join" },
255738
+ { id: "Format-Volume", re: /\bFormat-Volume\b/i, requireProbeTag: "disk" },
255739
+ { id: "Uninstall-WindowsFeature", re: /\bUninstall-WindowsFeature\b/i, requireProbeTag: "windows-feature" }
255740
+ ];
255741
+ REVIEW_VERBS = [
255742
+ { id: "Install-ADDSForest", re: /\bInstall-ADDSForest\b/i },
255743
+ { id: "Add-Computer", re: /\bAdd-Computer\b/i },
255744
+ { id: "djoin", re: /\bdjoin(\.exe)?\b/i },
255745
+ { id: "Set-SmbServerConfiguration", re: /\bSet-SmbServerConfiguration\b/i },
255746
+ { id: "authorize-security-group-ingress", re: /\bauthorize-security-group-ingress\b/i },
255747
+ { id: "Remove-Item -Recurse", re: /\bRemove-Item\b.*(-Recurse|-Force)/i },
255748
+ { id: "Format-Volume", re: /\bFormat-Volume\b/i }
255749
+ ];
255750
+ }
255751
+ });
255752
+
255460
255753
  // ../../packages/backend/src/services/AgentHelper/utils/subAgent.ts
255461
255754
  var subAgent_exports = {};
255462
255755
  __export(subAgent_exports, {
@@ -257341,7 +257634,7 @@ function playbookNeedsOrchestration(playbook) {
257341
257634
  (s) => s.dependsOn !== void 0 || s.desiredState || s.captureVar
257342
257635
  );
257343
257636
  }
257344
- function emit6(context2, toolName, input, output) {
257637
+ function emit7(context2, toolName, input, output) {
257345
257638
  context2.sendEvent(context2.sessionId, {
257346
257639
  messageId: context2.messageId,
257347
257640
  type: "tool_call",
@@ -257357,7 +257650,7 @@ async function managePlaybook(args, context2) {
257357
257650
  const m2 = context2.automationManager;
257358
257651
  if (!m2) {
257359
257652
  const msg2 = noStore2();
257360
- emit6(context2, "manage_playbook", args, msg2);
257653
+ emit7(context2, "manage_playbook", args, msg2);
257361
257654
  return msg2;
257362
257655
  }
257363
257656
  const { action } = args;
@@ -257365,7 +257658,7 @@ async function managePlaybook(args, context2) {
257365
257658
  const all = m2.listPlaybooks();
257366
257659
  if (!all.length) {
257367
257660
  const msg3 = "No playbooks. Create one with manage_playbook action=create.";
257368
- emit6(context2, "manage_playbook", args, msg3);
257661
+ emit7(context2, "manage_playbook", args, msg3);
257369
257662
  return msg3;
257370
257663
  }
257371
257664
  const body = all.map((p) => {
@@ -257374,20 +257667,20 @@ async function managePlaybook(args, context2) {
257374
257667
  }).join("\n");
257375
257668
  const msg2 = `Playbooks (${all.length}):
257376
257669
  ${body}`;
257377
- emit6(context2, "manage_playbook", args, msg2);
257670
+ emit7(context2, "manage_playbook", args, msg2);
257378
257671
  return msg2;
257379
257672
  }
257380
257673
  if (action === "get") {
257381
257674
  const key = args.id ?? args.name;
257382
257675
  if (!key) {
257383
257676
  const msg3 = "get requires id or name.";
257384
- emit6(context2, "manage_playbook", args, msg3);
257677
+ emit7(context2, "manage_playbook", args, msg3);
257385
257678
  return msg3;
257386
257679
  }
257387
257680
  const p = m2.getPlaybook(key);
257388
257681
  if (!p) {
257389
257682
  const msg3 = `No playbook "${key}".`;
257390
- emit6(context2, "manage_playbook", args, msg3);
257683
+ emit7(context2, "manage_playbook", args, msg3);
257391
257684
  return msg3;
257392
257685
  }
257393
257686
  const steps = p.steps.map((s, i) => {
@@ -257401,13 +257694,13 @@ Scope: ${scope}
257401
257694
  Default onError: ${p.onError ?? "stop"}${p.requireApproval ? "\nMOP mode: requires an approved change record (manage_change) to run" : ""}
257402
257695
  Steps:
257403
257696
  ${steps}`;
257404
- emit6(context2, "manage_playbook", args, msg2);
257697
+ emit7(context2, "manage_playbook", args, msg2);
257405
257698
  return msg2;
257406
257699
  }
257407
257700
  if (action === "create") {
257408
257701
  if (!args.name || !args.steps?.length) {
257409
257702
  const msg2 = "create requires name + at least one step.";
257410
- emit6(context2, "manage_playbook", args, msg2);
257703
+ emit7(context2, "manage_playbook", args, msg2);
257411
257704
  return msg2;
257412
257705
  }
257413
257706
  try {
@@ -257422,18 +257715,18 @@ ${steps}`;
257422
257715
  requireApproval: args.requireApproval
257423
257716
  });
257424
257717
  const msg2 = `Created playbook "${p.name}" (id=${p.id}, ${p.steps.length} step(s)). ${p.requireApproval ? "MOP mode: run it via manage_change (plan \u2192 approve \u2192 run)." : "Run it with run_playbook."}`;
257425
- emit6(context2, "manage_playbook", args, msg2);
257718
+ emit7(context2, "manage_playbook", args, msg2);
257426
257719
  return msg2;
257427
257720
  } catch (error40) {
257428
257721
  const msg2 = `Could not create playbook: ${error40 instanceof Error ? error40.message : error40}`;
257429
- emit6(context2, "manage_playbook", args, msg2);
257722
+ emit7(context2, "manage_playbook", args, msg2);
257430
257723
  return msg2;
257431
257724
  }
257432
257725
  }
257433
257726
  if (action === "update") {
257434
257727
  if (!args.id) {
257435
257728
  const msg2 = "update requires id.";
257436
- emit6(context2, "manage_playbook", args, msg2);
257729
+ emit7(context2, "manage_playbook", args, msg2);
257437
257730
  return msg2;
257438
257731
  }
257439
257732
  try {
@@ -257449,51 +257742,51 @@ ${steps}`;
257449
257742
  ...args.requireApproval !== void 0 ? { requireApproval: args.requireApproval } : {}
257450
257743
  });
257451
257744
  const msg2 = `Updated playbook "${p.name}" (${p.steps.length} step(s)).`;
257452
- emit6(context2, "manage_playbook", args, msg2);
257745
+ emit7(context2, "manage_playbook", args, msg2);
257453
257746
  return msg2;
257454
257747
  } catch (error40) {
257455
257748
  const msg2 = `Could not update playbook: ${error40 instanceof Error ? error40.message : error40}`;
257456
- emit6(context2, "manage_playbook", args, msg2);
257749
+ emit7(context2, "manage_playbook", args, msg2);
257457
257750
  return msg2;
257458
257751
  }
257459
257752
  }
257460
257753
  if (action === "delete") {
257461
257754
  if (!args.id) {
257462
257755
  const msg3 = "delete requires id.";
257463
- emit6(context2, "manage_playbook", args, msg3);
257756
+ emit7(context2, "manage_playbook", args, msg3);
257464
257757
  return msg3;
257465
257758
  }
257466
257759
  const removed = m2.deletePlaybook(args.id);
257467
257760
  const msg2 = removed ? `Deleted playbook ${args.id}.` : `No playbook ${args.id}.`;
257468
- emit6(context2, "manage_playbook", args, msg2);
257761
+ emit7(context2, "manage_playbook", args, msg2);
257469
257762
  return msg2;
257470
257763
  }
257471
257764
  const msg = `Unknown action "${action}".`;
257472
- emit6(context2, "manage_playbook", args, msg);
257765
+ emit7(context2, "manage_playbook", args, msg);
257473
257766
  return msg;
257474
257767
  }
257475
257768
  async function runPlaybook(args, context2) {
257476
257769
  const m2 = context2.automationManager;
257477
257770
  if (!m2) {
257478
257771
  const msg2 = noStore2();
257479
- emit6(context2, "run_playbook", args, msg2);
257772
+ emit7(context2, "run_playbook", args, msg2);
257480
257773
  return msg2;
257481
257774
  }
257482
257775
  const key = args.id ?? args.name;
257483
257776
  if (!key) {
257484
257777
  const msg2 = "run_playbook requires id or name.";
257485
- emit6(context2, "run_playbook", args, msg2);
257778
+ emit7(context2, "run_playbook", args, msg2);
257486
257779
  return msg2;
257487
257780
  }
257488
257781
  const playbook = m2.getPlaybook(key);
257489
257782
  if (!playbook) {
257490
257783
  const msg2 = `No playbook "${key}". Use manage_playbook action=list to see valid playbooks.`;
257491
- emit6(context2, "run_playbook", args, msg2);
257784
+ emit7(context2, "run_playbook", args, msg2);
257492
257785
  return msg2;
257493
257786
  }
257494
257787
  if (playbook.requireApproval) {
257495
257788
  const msg2 = `Playbook "${playbook.name}" is in MOP mode (requireApproval). Run it through a change record: manage_change action=plan name="${playbook.name}" \u2192 approve \u2192 run.`;
257496
- emit6(context2, "run_playbook", args, msg2);
257789
+ emit7(context2, "run_playbook", args, msg2);
257497
257790
  return msg2;
257498
257791
  }
257499
257792
  if (args.dryRun) {
@@ -257521,7 +257814,7 @@ Targets (${plan.targets.length}): ${targetList}
257521
257814
 
257522
257815
  Steps (${plan.steps.length}):
257523
257816
  ${stepList}${notes}`;
257524
- emit6(context2, "run_playbook", args, msg2);
257817
+ emit7(context2, "run_playbook", args, msg2);
257525
257818
  return msg2;
257526
257819
  }
257527
257820
  const settings = {
@@ -257561,7 +257854,7 @@ ${stepList}${notes}`;
257561
257854
  }
257562
257855
  } catch (error40) {
257563
257856
  const msg2 = `Playbook "${playbook.name}" could not run: ${error40 instanceof Error ? error40.message : error40}`;
257564
- emit6(context2, "run_playbook", args, msg2);
257857
+ emit7(context2, "run_playbook", args, msg2);
257565
257858
  return msg2;
257566
257859
  }
257567
257860
  const lines = [];
@@ -257576,7 +257869,7 @@ ${stepList}${notes}`;
257576
257869
  const okTargets = record2.targets.filter((t) => t.ok).length;
257577
257870
  const msg = `Playbook "${record2.playbookName}" ${record2.ok ? "completed OK" : "FAILED"} (runId=${record2.runId}, ${okTargets}/${record2.targets.length} target(s) ok):
257578
257871
  ${lines.join("\n")}`;
257579
- emit6(context2, "run_playbook", args, msg);
257872
+ emit7(context2, "run_playbook", args, msg);
257580
257873
  return msg;
257581
257874
  }
257582
257875
  var stepSchema, managePlaybookSchema, runPlaybookSchema;
@@ -258017,8 +258310,8 @@ function extractFields(message) {
258017
258310
  if (ip) fields.ip = ip[1];
258018
258311
  const port = message.match(/[Pp]ort[:\s]+(\d{1,5})/);
258019
258312
  if (port) fields.port = port[1];
258020
- const path32 = message.match(/([A-Za-z]:\\[^\s"',;]+)/);
258021
- if (path32) fields.path = path32[1];
258313
+ const path33 = message.match(/([A-Za-z]:\\[^\s"',;]+)/);
258314
+ if (path33) fields.path = path33[1];
258022
258315
  const key = message.match(/(HKLM|HKCU|HKCR|HKU)\\[^\s"',;]+/i);
258023
258316
  if (key) fields.key = key[0];
258024
258317
  const proc = message.match(/[Pp]rocess(?:Name)?[:\s]+([A-Za-z0-9_.-]+\.exe)/);
@@ -265576,8 +265869,8 @@ var require_utils2 = __commonJS({
265576
265869
  }
265577
265870
  return ind;
265578
265871
  }
265579
- function removeDotSegments(path32) {
265580
- let input = path32;
265872
+ function removeDotSegments(path33) {
265873
+ let input = path33;
265581
265874
  const output = [];
265582
265875
  let nextSlash = -1;
265583
265876
  let len = 0;
@@ -265776,8 +266069,8 @@ var require_schemes = __commonJS({
265776
266069
  wsComponent.secure = void 0;
265777
266070
  }
265778
266071
  if (wsComponent.resourceName) {
265779
- const [path32, query] = wsComponent.resourceName.split("?");
265780
- wsComponent.path = path32 && path32 !== "/" ? path32 : void 0;
266072
+ const [path33, query] = wsComponent.resourceName.split("?");
266073
+ wsComponent.path = path33 && path33 !== "/" ? path33 : void 0;
265781
266074
  wsComponent.query = query;
265782
266075
  wsComponent.resourceName = void 0;
265783
266076
  }
@@ -274816,12 +275109,12 @@ var require_dist2 = __commonJS({
274816
275109
  throw new Error(`Unknown format "${name}"`);
274817
275110
  return f;
274818
275111
  };
274819
- function addFormats(ajv, list, fs23, exportName) {
275112
+ function addFormats(ajv, list, fs24, exportName) {
274820
275113
  var _a3;
274821
275114
  var _b;
274822
275115
  (_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
274823
275116
  for (const f of list)
274824
- ajv.addFormat(f, fs23[f]);
275117
+ ajv.addFormat(f, fs24[f]);
274825
275118
  }
274826
275119
  module2.exports = exports2 = formatsPlugin;
274827
275120
  Object.defineProperty(exports2, "__esModule", { value: true });
@@ -274834,8 +275127,8 @@ var require_windows = __commonJS({
274834
275127
  "../../node_modules/isexe/windows.js"(exports2, module2) {
274835
275128
  module2.exports = isexe;
274836
275129
  isexe.sync = sync;
274837
- var fs23 = require("fs");
274838
- function checkPathExt(path32, options) {
275130
+ var fs24 = require("fs");
275131
+ function checkPathExt(path33, options) {
274839
275132
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
274840
275133
  if (!pathext) {
274841
275134
  return true;
@@ -274846,25 +275139,25 @@ var require_windows = __commonJS({
274846
275139
  }
274847
275140
  for (var i = 0; i < pathext.length; i++) {
274848
275141
  var p = pathext[i].toLowerCase();
274849
- if (p && path32.substr(-p.length).toLowerCase() === p) {
275142
+ if (p && path33.substr(-p.length).toLowerCase() === p) {
274850
275143
  return true;
274851
275144
  }
274852
275145
  }
274853
275146
  return false;
274854
275147
  }
274855
- function checkStat(stat, path32, options) {
275148
+ function checkStat(stat, path33, options) {
274856
275149
  if (!stat.isSymbolicLink() && !stat.isFile()) {
274857
275150
  return false;
274858
275151
  }
274859
- return checkPathExt(path32, options);
275152
+ return checkPathExt(path33, options);
274860
275153
  }
274861
- function isexe(path32, options, cb) {
274862
- fs23.stat(path32, function(er, stat) {
274863
- cb(er, er ? false : checkStat(stat, path32, options));
275154
+ function isexe(path33, options, cb) {
275155
+ fs24.stat(path33, function(er, stat) {
275156
+ cb(er, er ? false : checkStat(stat, path33, options));
274864
275157
  });
274865
275158
  }
274866
- function sync(path32, options) {
274867
- return checkStat(fs23.statSync(path32), path32, options);
275159
+ function sync(path33, options) {
275160
+ return checkStat(fs24.statSync(path33), path33, options);
274868
275161
  }
274869
275162
  }
274870
275163
  });
@@ -274874,14 +275167,14 @@ var require_mode = __commonJS({
274874
275167
  "../../node_modules/isexe/mode.js"(exports2, module2) {
274875
275168
  module2.exports = isexe;
274876
275169
  isexe.sync = sync;
274877
- var fs23 = require("fs");
274878
- function isexe(path32, options, cb) {
274879
- fs23.stat(path32, function(er, stat) {
275170
+ var fs24 = require("fs");
275171
+ function isexe(path33, options, cb) {
275172
+ fs24.stat(path33, function(er, stat) {
274880
275173
  cb(er, er ? false : checkStat(stat, options));
274881
275174
  });
274882
275175
  }
274883
- function sync(path32, options) {
274884
- return checkStat(fs23.statSync(path32), options);
275176
+ function sync(path33, options) {
275177
+ return checkStat(fs24.statSync(path33), options);
274885
275178
  }
274886
275179
  function checkStat(stat, options) {
274887
275180
  return stat.isFile() && checkMode(stat, options);
@@ -274905,7 +275198,7 @@ var require_mode = __commonJS({
274905
275198
  // ../../node_modules/isexe/index.js
274906
275199
  var require_isexe = __commonJS({
274907
275200
  "../../node_modules/isexe/index.js"(exports2, module2) {
274908
- var fs23 = require("fs");
275201
+ var fs24 = require("fs");
274909
275202
  var core2;
274910
275203
  if (process.platform === "win32" || global.TESTING_WINDOWS) {
274911
275204
  core2 = require_windows();
@@ -274914,7 +275207,7 @@ var require_isexe = __commonJS({
274914
275207
  }
274915
275208
  module2.exports = isexe;
274916
275209
  isexe.sync = sync;
274917
- function isexe(path32, options, cb) {
275210
+ function isexe(path33, options, cb) {
274918
275211
  if (typeof options === "function") {
274919
275212
  cb = options;
274920
275213
  options = {};
@@ -274924,7 +275217,7 @@ var require_isexe = __commonJS({
274924
275217
  throw new TypeError("callback not provided");
274925
275218
  }
274926
275219
  return new Promise(function(resolve2, reject) {
274927
- isexe(path32, options || {}, function(er, is) {
275220
+ isexe(path33, options || {}, function(er, is) {
274928
275221
  if (er) {
274929
275222
  reject(er);
274930
275223
  } else {
@@ -274933,7 +275226,7 @@ var require_isexe = __commonJS({
274933
275226
  });
274934
275227
  });
274935
275228
  }
274936
- core2(path32, options || {}, function(er, is) {
275229
+ core2(path33, options || {}, function(er, is) {
274937
275230
  if (er) {
274938
275231
  if (er.code === "EACCES" || options && options.ignoreErrors) {
274939
275232
  er = null;
@@ -274943,9 +275236,9 @@ var require_isexe = __commonJS({
274943
275236
  cb(er, is);
274944
275237
  });
274945
275238
  }
274946
- function sync(path32, options) {
275239
+ function sync(path33, options) {
274947
275240
  try {
274948
- return core2.sync(path32, options || {});
275241
+ return core2.sync(path33, options || {});
274949
275242
  } catch (er) {
274950
275243
  if (options && options.ignoreErrors || er.code === "EACCES") {
274951
275244
  return false;
@@ -274961,7 +275254,7 @@ var require_isexe = __commonJS({
274961
275254
  var require_which = __commonJS({
274962
275255
  "../../node_modules/which/which.js"(exports2, module2) {
274963
275256
  var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
274964
- var path32 = require("path");
275257
+ var path33 = require("path");
274965
275258
  var COLON = isWindows ? ";" : ":";
274966
275259
  var isexe = require_isexe();
274967
275260
  var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
@@ -274999,7 +275292,7 @@ var require_which = __commonJS({
274999
275292
  return opt.all && found.length ? resolve2(found) : reject(getNotFoundError(cmd));
275000
275293
  const ppRaw = pathEnv[i];
275001
275294
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
275002
- const pCmd = path32.join(pathPart, cmd);
275295
+ const pCmd = path33.join(pathPart, cmd);
275003
275296
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
275004
275297
  resolve2(subStep(p, i, 0));
275005
275298
  });
@@ -275026,7 +275319,7 @@ var require_which = __commonJS({
275026
275319
  for (let i = 0; i < pathEnv.length; i++) {
275027
275320
  const ppRaw = pathEnv[i];
275028
275321
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
275029
- const pCmd = path32.join(pathPart, cmd);
275322
+ const pCmd = path33.join(pathPart, cmd);
275030
275323
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
275031
275324
  for (let j = 0; j < pathExt.length; j++) {
275032
275325
  const cur = p + pathExt[j];
@@ -275074,7 +275367,7 @@ var require_path_key = __commonJS({
275074
275367
  var require_resolveCommand = __commonJS({
275075
275368
  "../../node_modules/cross-spawn/lib/util/resolveCommand.js"(exports2, module2) {
275076
275369
  "use strict";
275077
- var path32 = require("path");
275370
+ var path33 = require("path");
275078
275371
  var which = require_which();
275079
275372
  var getPathKey = require_path_key();
275080
275373
  function resolveCommandAttempt(parsed, withoutPathExt) {
@@ -275092,7 +275385,7 @@ var require_resolveCommand = __commonJS({
275092
275385
  try {
275093
275386
  resolved = which.sync(parsed.command, {
275094
275387
  path: env[getPathKey({ env })],
275095
- pathExt: withoutPathExt ? path32.delimiter : void 0
275388
+ pathExt: withoutPathExt ? path33.delimiter : void 0
275096
275389
  });
275097
275390
  } catch (e) {
275098
275391
  } finally {
@@ -275101,7 +275394,7 @@ var require_resolveCommand = __commonJS({
275101
275394
  }
275102
275395
  }
275103
275396
  if (resolved) {
275104
- resolved = path32.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
275397
+ resolved = path33.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
275105
275398
  }
275106
275399
  return resolved;
275107
275400
  }
@@ -275155,8 +275448,8 @@ var require_shebang_command = __commonJS({
275155
275448
  if (!match) {
275156
275449
  return null;
275157
275450
  }
275158
- const [path32, argument] = match[0].replace(/#! ?/, "").split(" ");
275159
- const binary2 = path32.split("/").pop();
275451
+ const [path33, argument] = match[0].replace(/#! ?/, "").split(" ");
275452
+ const binary2 = path33.split("/").pop();
275160
275453
  if (binary2 === "env") {
275161
275454
  return argument;
275162
275455
  }
@@ -275169,16 +275462,16 @@ var require_shebang_command = __commonJS({
275169
275462
  var require_readShebang = __commonJS({
275170
275463
  "../../node_modules/cross-spawn/lib/util/readShebang.js"(exports2, module2) {
275171
275464
  "use strict";
275172
- var fs23 = require("fs");
275465
+ var fs24 = require("fs");
275173
275466
  var shebangCommand = require_shebang_command();
275174
275467
  function readShebang(command) {
275175
275468
  const size = 150;
275176
275469
  const buffer = Buffer.alloc(size);
275177
275470
  let fd;
275178
275471
  try {
275179
- fd = fs23.openSync(command, "r");
275180
- fs23.readSync(fd, buffer, 0, size, 0);
275181
- fs23.closeSync(fd);
275472
+ fd = fs24.openSync(command, "r");
275473
+ fs24.readSync(fd, buffer, 0, size, 0);
275474
+ fs24.closeSync(fd);
275182
275475
  } catch (e) {
275183
275476
  }
275184
275477
  return shebangCommand(buffer.toString());
@@ -275191,7 +275484,7 @@ var require_readShebang = __commonJS({
275191
275484
  var require_parse2 = __commonJS({
275192
275485
  "../../node_modules/cross-spawn/lib/parse.js"(exports2, module2) {
275193
275486
  "use strict";
275194
- var path32 = require("path");
275487
+ var path33 = require("path");
275195
275488
  var resolveCommand = require_resolveCommand();
275196
275489
  var escape2 = require_escape();
275197
275490
  var readShebang = require_readShebang();
@@ -275216,7 +275509,7 @@ var require_parse2 = __commonJS({
275216
275509
  const needsShell = !isExecutableRegExp.test(commandFile);
275217
275510
  if (parsed.options.forceShell || needsShell) {
275218
275511
  const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
275219
- parsed.command = path32.normalize(parsed.command);
275512
+ parsed.command = path33.normalize(parsed.command);
275220
275513
  parsed.command = escape2.command(parsed.command);
275221
275514
  parsed.args = parsed.args.map((arg) => escape2.argument(arg, needsDoubleEscapeMetaChars));
275222
275515
  const shellCommand = [parsed.command].concat(parsed.args).join(" ");
@@ -276089,6 +276382,308 @@ var require_src = __commonJS({
276089
276382
  }
276090
276383
  });
276091
276384
 
276385
+ // ../../packages/backend/src/services/learning/compoundingStore.ts
276386
+ var compoundingStore_exports = {};
276387
+ __export(compoundingStore_exports, {
276388
+ COMPOUNDING_DB_FILE: () => COMPOUNDING_DB_FILE,
276389
+ CompoundingStore: () => CompoundingStore
276390
+ });
276391
+ var import_node_fs12, import_node_path28, COMPOUNDING_DB_FILE, CompoundingStore;
276392
+ var init_compoundingStore = __esm({
276393
+ "../../packages/backend/src/services/learning/compoundingStore.ts"() {
276394
+ "use strict";
276395
+ import_node_fs12 = __toESM(require("node:fs"), 1);
276396
+ import_node_path28 = __toESM(require("node:path"), 1);
276397
+ init_betterSqlite3Runtime();
276398
+ init_historyStoragePaths();
276399
+ COMPOUNDING_DB_FILE = "gyshell-compounding.sqlite";
276400
+ CompoundingStore = class _CompoundingStore {
276401
+ filePath;
276402
+ db;
276403
+ /** Avoid sync SQLite on every agent turn (desktop freeze). Invalidated on writes. */
276404
+ promptCache = null;
276405
+ static PROMPT_CACHE_MS = 2e3;
276406
+ constructor(options) {
276407
+ this.filePath = options?.filePath || import_node_path28.default.join(resolveHistoryStorageDir(), COMPOUNDING_DB_FILE);
276408
+ import_node_fs12.default.mkdirSync(import_node_path28.default.dirname(this.filePath), { recursive: true });
276409
+ this.db = openBetterSqlite3Database(this.filePath);
276410
+ this.db.pragma("journal_mode = WAL");
276411
+ this.db.exec(`
276412
+ CREATE TABLE IF NOT EXISTS lessons (
276413
+ fingerprint TEXT PRIMARY KEY,
276414
+ title TEXT NOT NULL,
276415
+ body TEXT NOT NULL,
276416
+ never_do TEXT NOT NULL,
276417
+ instead TEXT NOT NULL,
276418
+ tags TEXT NOT NULL DEFAULT '',
276419
+ extractor TEXT NOT NULL,
276420
+ occurrences INTEGER NOT NULL DEFAULT 1,
276421
+ first_seen_at INTEGER NOT NULL,
276422
+ last_seen_at INTEGER NOT NULL,
276423
+ last_run_id TEXT
276424
+ );
276425
+ CREATE TABLE IF NOT EXISTS estate_facts (
276426
+ identity TEXT PRIMARY KEY,
276427
+ host TEXT,
276428
+ role TEXT,
276429
+ domain TEXT,
276430
+ transport TEXT,
276431
+ auth TEXT,
276432
+ facts_json TEXT NOT NULL DEFAULT '{}',
276433
+ last_seen_at INTEGER NOT NULL
276434
+ );
276435
+ CREATE TABLE IF NOT EXISTS goals (
276436
+ id TEXT PRIMARY KEY,
276437
+ session_id TEXT NOT NULL,
276438
+ text TEXT NOT NULL,
276439
+ status TEXT NOT NULL,
276440
+ blocked_by TEXT,
276441
+ next_probe TEXT,
276442
+ updated_at INTEGER NOT NULL
276443
+ );
276444
+ CREATE INDEX IF NOT EXISTS idx_goals_session ON goals(session_id);
276445
+ CREATE TABLE IF NOT EXISTS probes (
276446
+ session_id TEXT NOT NULL,
276447
+ tag TEXT NOT NULL,
276448
+ hypothesis TEXT NOT NULL,
276449
+ command TEXT NOT NULL,
276450
+ ok INTEGER NOT NULL,
276451
+ at INTEGER NOT NULL,
276452
+ PRIMARY KEY (session_id, tag)
276453
+ );
276454
+ `);
276455
+ }
276456
+ recordLessons(lessons, runId) {
276457
+ const now = Date.now();
276458
+ const out = [];
276459
+ this.promptCache = null;
276460
+ try {
276461
+ const sel = this.db.prepare("SELECT * FROM lessons WHERE fingerprint = ?");
276462
+ const ins = this.db.prepare(
276463
+ `INSERT INTO lessons (fingerprint, title, body, never_do, instead, tags, extractor, occurrences, first_seen_at, last_seen_at, last_run_id)
276464
+ VALUES (@fingerprint, @title, @body, @neverDo, @instead, @tags, @extractor, 1, @now, @now, @runId)`
276465
+ );
276466
+ const upd = this.db.prepare(
276467
+ `UPDATE lessons SET occurrences = occurrences + 1, last_seen_at = @now, last_run_id = @runId,
276468
+ title = @title, body = @body, never_do = @neverDo, instead = @instead WHERE fingerprint = @fingerprint`
276469
+ );
276470
+ for (const l of lessons) {
276471
+ const existing = sel.get(l.fingerprint);
276472
+ if (existing) {
276473
+ upd.run({
276474
+ fingerprint: l.fingerprint,
276475
+ now,
276476
+ runId: runId ?? null,
276477
+ title: l.title,
276478
+ body: l.body,
276479
+ neverDo: l.neverDo,
276480
+ instead: l.instead
276481
+ });
276482
+ } else {
276483
+ ins.run({
276484
+ fingerprint: l.fingerprint,
276485
+ title: l.title,
276486
+ body: l.body,
276487
+ neverDo: l.neverDo,
276488
+ instead: l.instead,
276489
+ tags: l.tags.join(","),
276490
+ extractor: l.extractor,
276491
+ now,
276492
+ runId: runId ?? null
276493
+ });
276494
+ }
276495
+ const row = sel.get(l.fingerprint);
276496
+ if (row) out.push(this.mapLesson(row));
276497
+ }
276498
+ } catch (err) {
276499
+ console.warn("[CompoundingStore] recordLessons failed:", err);
276500
+ }
276501
+ return out;
276502
+ }
276503
+ listLessons(limit2 = 50) {
276504
+ try {
276505
+ const rows = this.db.prepare("SELECT * FROM lessons ORDER BY last_seen_at DESC LIMIT ?").all(limit2);
276506
+ return rows.map((r) => this.mapLesson(r));
276507
+ } catch (err) {
276508
+ console.warn("[CompoundingStore] listLessons failed:", err);
276509
+ return [];
276510
+ }
276511
+ }
276512
+ upsertEstateFact(input) {
276513
+ this.promptCache = null;
276514
+ try {
276515
+ const now = Date.now();
276516
+ this.db.prepare(
276517
+ `INSERT INTO estate_facts (identity, host, role, domain, transport, auth, facts_json, last_seen_at)
276518
+ VALUES (@identity, @host, @role, @domain, @transport, @auth, @facts, @now)
276519
+ ON CONFLICT(identity) DO UPDATE SET
276520
+ host = COALESCE(@host, host),
276521
+ role = COALESCE(@role, role),
276522
+ domain = COALESCE(@domain, domain),
276523
+ transport = COALESCE(@transport, transport),
276524
+ auth = COALESCE(@auth, auth),
276525
+ facts_json = CASE WHEN @facts = '{}' THEN facts_json ELSE @facts END,
276526
+ last_seen_at = @now`
276527
+ ).run({
276528
+ identity: input.identity,
276529
+ host: input.host ?? null,
276530
+ role: input.role ?? null,
276531
+ domain: input.domain ?? null,
276532
+ transport: input.transport ?? null,
276533
+ auth: input.auth ?? null,
276534
+ facts: JSON.stringify(input.facts || {}),
276535
+ now
276536
+ });
276537
+ } catch (err) {
276538
+ console.warn("[CompoundingStore] upsertEstateFact failed:", err);
276539
+ }
276540
+ }
276541
+ listEstateFacts() {
276542
+ try {
276543
+ const rows = this.db.prepare("SELECT * FROM estate_facts ORDER BY last_seen_at DESC").all();
276544
+ return rows.map((r) => ({
276545
+ identity: r.identity,
276546
+ host: r.host ?? void 0,
276547
+ role: r.role ?? void 0,
276548
+ domain: r.domain ?? void 0,
276549
+ transport: r.transport ?? void 0,
276550
+ auth: r.auth ?? void 0,
276551
+ factsJson: r.facts_json,
276552
+ lastSeenAt: r.last_seen_at
276553
+ }));
276554
+ } catch (err) {
276555
+ console.warn("[CompoundingStore] listEstateFacts failed:", err);
276556
+ return [];
276557
+ }
276558
+ }
276559
+ upsertGoal(input) {
276560
+ this.promptCache = null;
276561
+ try {
276562
+ this.db.prepare(
276563
+ `INSERT INTO goals (id, session_id, text, status, blocked_by, next_probe, updated_at)
276564
+ VALUES (@id, @sessionId, @text, @status, @blockedBy, @nextProbe, @now)
276565
+ ON CONFLICT(id) DO UPDATE SET
276566
+ text = @text, status = @status, blocked_by = @blockedBy, next_probe = @nextProbe, updated_at = @now`
276567
+ ).run({
276568
+ id: input.id,
276569
+ sessionId: input.sessionId,
276570
+ text: input.text,
276571
+ status: input.status,
276572
+ blockedBy: input.blockedBy ?? null,
276573
+ nextProbe: input.nextProbe ?? null,
276574
+ now: Date.now()
276575
+ });
276576
+ } catch (err) {
276577
+ console.warn("[CompoundingStore] upsertGoal failed:", err);
276578
+ }
276579
+ }
276580
+ listGoals(sessionId) {
276581
+ try {
276582
+ const rows = this.db.prepare("SELECT * FROM goals WHERE session_id = ? ORDER BY updated_at DESC").all(sessionId);
276583
+ return rows.map((r) => ({
276584
+ id: r.id,
276585
+ sessionId: r.session_id,
276586
+ text: r.text,
276587
+ status: r.status,
276588
+ blockedBy: r.blocked_by ?? void 0,
276589
+ nextProbe: r.next_probe ?? void 0,
276590
+ updatedAt: r.updated_at
276591
+ }));
276592
+ } catch (err) {
276593
+ console.warn("[CompoundingStore] listGoals failed:", err);
276594
+ return [];
276595
+ }
276596
+ }
276597
+ recordProbe(sessionId, tag, hypothesis, command, ok) {
276598
+ this.promptCache = null;
276599
+ try {
276600
+ this.db.prepare(
276601
+ `INSERT INTO probes (session_id, tag, hypothesis, command, ok, at)
276602
+ VALUES (@sessionId, @tag, @hypothesis, @command, @ok, @at)
276603
+ ON CONFLICT(session_id, tag) DO UPDATE SET hypothesis = @hypothesis, command = @command, ok = @ok, at = @at`
276604
+ ).run({
276605
+ sessionId,
276606
+ tag,
276607
+ hypothesis,
276608
+ command,
276609
+ ok: ok ? 1 : 0,
276610
+ at: Date.now()
276611
+ });
276612
+ } catch (err) {
276613
+ console.warn("[CompoundingStore] recordProbe failed:", err);
276614
+ }
276615
+ }
276616
+ hasProbe(sessionId, tag) {
276617
+ try {
276618
+ const row = this.db.prepare("SELECT 1 FROM probes WHERE session_id = ? AND tag = ?").get(sessionId, tag);
276619
+ return !!row;
276620
+ } catch (err) {
276621
+ console.warn("[CompoundingStore] hasProbe failed:", err);
276622
+ return false;
276623
+ }
276624
+ }
276625
+ /**
276626
+ * Prompt block: estate snapshot + never-do list from lessons (capped).
276627
+ */
276628
+ promptBlock(maxChars = 4e3) {
276629
+ try {
276630
+ const now = Date.now();
276631
+ if (this.promptCache && now - this.promptCache.at < _CompoundingStore.PROMPT_CACHE_MS) {
276632
+ const cached2 = this.promptCache.text;
276633
+ return cached2.length > maxChars ? cached2.slice(0, maxChars) + "\n\u2026" : cached2;
276634
+ }
276635
+ const lessons = this.listLessons(20);
276636
+ const facts = this.listEstateFacts();
276637
+ const lines = ["# Compounding knowledge (auto)"];
276638
+ if (facts.length) {
276639
+ lines.push("", "## Estate");
276640
+ for (const f of facts.slice(0, 12)) {
276641
+ const bits = [f.identity];
276642
+ if (f.role) bits.push(f.role);
276643
+ if (f.domain) bits.push(f.domain);
276644
+ if (f.transport || f.auth) bits.push([f.transport, f.auth].filter(Boolean).join("/"));
276645
+ lines.push(`- ${bits.join(" \xB7 ")}`);
276646
+ }
276647
+ }
276648
+ if (lessons.length) {
276649
+ lines.push("", "## Never-do (from prior failures)");
276650
+ for (const l of lessons.slice(0, 12)) {
276651
+ lines.push(`- [${l.fingerprint} \xD7${l.occurrences}] NEVER: ${l.neverDo}`);
276652
+ lines.push(` INSTEAD: ${l.instead}`);
276653
+ }
276654
+ }
276655
+ const text = lines.join("\n");
276656
+ this.promptCache = { at: now, text };
276657
+ return text.length > maxChars ? text.slice(0, maxChars) + "\n\u2026" : text;
276658
+ } catch {
276659
+ return "";
276660
+ }
276661
+ }
276662
+ close() {
276663
+ try {
276664
+ this.db.close();
276665
+ } catch {
276666
+ }
276667
+ }
276668
+ mapLesson(r) {
276669
+ return {
276670
+ fingerprint: r.fingerprint,
276671
+ title: r.title,
276672
+ body: r.body,
276673
+ neverDo: r.never_do,
276674
+ instead: r.instead,
276675
+ tags: r.tags,
276676
+ extractor: r.extractor,
276677
+ occurrences: r.occurrences,
276678
+ firstSeenAt: r.first_seen_at,
276679
+ lastSeenAt: r.last_seen_at,
276680
+ lastRunId: r.last_run_id ?? void 0
276681
+ };
276682
+ }
276683
+ };
276684
+ }
276685
+ });
276686
+
276092
276687
  // ../../node_modules/@nats-io/nats-core/lib/encoders.js
276093
276688
  var require_encoders = __commonJS({
276094
276689
  "../../node_modules/@nats-io/nats-core/lib/encoders.js"(exports2) {
@@ -284840,7 +285435,7 @@ var require_ws_transport = __commonJS({
284840
285435
  let protocol;
284841
285436
  let port;
284842
285437
  const host = url2.hostname;
284843
- const path32 = url2.pathname;
285438
+ const path33 = url2.pathname;
284844
285439
  const search = url2.search || "";
284845
285440
  switch (srcProto) {
284846
285441
  case "http:":
@@ -284860,7 +285455,7 @@ var require_ws_transport = __commonJS({
284860
285455
  protocol = encrypted === true ? "wss:" : "ws:";
284861
285456
  break;
284862
285457
  }
284863
- return `${protocol}//${host}:${port}${path32}${search}`;
285458
+ return `${protocol}//${host}:${port}${path33}${search}`;
284864
285459
  }
284865
285460
  function wsconnect(opts = {}) {
284866
285461
  (0, transport_1.setTransportFactory)({
@@ -286705,11 +287300,11 @@ var require_jsmconsumer_api = __commonJS({
286705
287300
  consumerName = cfg.name ?? cfg.durable_name ?? "";
286706
287301
  }
286707
287302
  if (consumerName !== "") {
286708
- let fs23 = cfg.filter_subject ?? void 0;
286709
- if (fs23 === ">") {
286710
- fs23 = void 0;
287303
+ let fs24 = cfg.filter_subject ?? void 0;
287304
+ if (fs24 === ">") {
287305
+ fs24 = void 0;
286711
287306
  }
286712
- subj = fs23 !== void 0 ? `${this.prefix}.CONSUMER.CREATE.${stream}.${consumerName}.${fs23}` : `${this.prefix}.CONSUMER.CREATE.${stream}.${consumerName}`;
287307
+ subj = fs24 !== void 0 ? `${this.prefix}.CONSUMER.CREATE.${stream}.${consumerName}.${fs24}` : `${this.prefix}.CONSUMER.CREATE.${stream}.${consumerName}`;
286713
287308
  } else {
286714
287309
  subj = cfg.durable_name ? `${this.prefix}.CONSUMER.DURABLE.CREATE.${stream}.${cfg.durable_name}` : `${this.prefix}.CONSUMER.CREATE.${stream}`;
286715
287310
  }
@@ -291259,8 +291854,8 @@ var init_natsEventBus = __esm({
291259
291854
  });
291260
291855
 
291261
291856
  // ../../packages/backend/src/runtimes/gybackend/startGyBackend.ts
291262
- var import_node_path28 = __toESM(require("node:path"), 1);
291263
- var import_node_fs12 = __toESM(require("node:fs"), 1);
291857
+ var import_node_path29 = __toESM(require("node:path"), 1);
291858
+ var import_node_fs13 = __toESM(require("node:fs"), 1);
291264
291859
  var import_node_process2 = __toESM(require("node:process"), 1);
291265
291860
 
291266
291861
  // ../../packages/backend/src/services/TerminalService.ts
@@ -293293,18 +293888,18 @@ var SSHBackend = class _SSHBackend {
293293
293888
  });
293294
293889
  return info.socket;
293295
293890
  }
293296
- async buildConnectSocketIfNeeded(sshConfig, emit10) {
293891
+ async buildConnectSocketIfNeeded(sshConfig, emit11) {
293297
293892
  if (sshConfig.jumpHost) {
293298
293893
  const jumpId = `[Jump:${sshConfig.jumpHost.host}]`;
293299
293894
  console.log(`${jumpId} Starting jump host connection flow...`);
293300
- emit10(
293895
+ emit11(
293301
293896
  `\x1B[36m\u25B9 ${jumpId} Establishing tunnel via jump host ${sshConfig.jumpHost.host}...\x1B[0m\r
293302
293897
  `
293303
293898
  );
293304
293899
  const jumpClient = new (loadSsh2()).Client();
293305
293900
  const jumpSock = await this.buildConnectSocketIfNeeded(
293306
293901
  sshConfig.jumpHost,
293307
- emit10
293902
+ emit11
293308
293903
  );
293309
293904
  if (jumpSock) {
293310
293905
  console.log(
@@ -293348,7 +293943,7 @@ var SSHBackend = class _SSHBackend {
293348
293943
  });
293349
293944
  jumpClient.connect(jumpConnectConfig);
293350
293945
  });
293351
- emit10(
293946
+ emit11(
293352
293947
  `\x1B[32m\u2714 ${jumpId} Jump host ready. Requesting forward to target ${sshConfig.host}:${sshConfig.port}...\x1B[0m\r
293353
293948
  `
293354
293949
  );
@@ -293664,25 +294259,25 @@ var SSHBackend = class _SSHBackend {
293664
294259
  };
293665
294260
  this.sessions.set(config2.id, instance);
293666
294261
  (async () => {
293667
- const emit10 = (data) => {
294262
+ const emit11 = (data) => {
293668
294263
  instance.dataCallbacks.forEach((cb) => cb(data));
293669
294264
  };
293670
294265
  const emitExit = (code) => {
293671
294266
  this.emitExitOnce(config2.id, instance, code);
293672
294267
  };
293673
294268
  client2.on("ready", async () => {
293674
- emit10("\x1B[2J\x1B[H\x1B[32m\u2714 Connection established.\x1B[0m\r\n");
294269
+ emit11("\x1B[2J\x1B[H\x1B[32m\u2714 Connection established.\x1B[0m\r\n");
293675
294270
  console.log(
293676
294271
  `[SSH] Connection ready for ${sshConfig.host}:${sshConfig.port}`
293677
294272
  );
293678
294273
  const rawShell = isRawShellPreset(sshConfig.algorithmsPreset);
293679
294274
  try {
293680
- emit10("\x1B[36m\u25B9 Setting up port forwards...\x1B[0m\r\n");
294275
+ emit11("\x1B[36m\u25B9 Setting up port forwards...\x1B[0m\r\n");
293681
294276
  console.log(`[SSH] Setting up port forwards...`);
293682
294277
  await this.setupPortForwards(instance, sshConfig);
293683
294278
  } catch (e) {
293684
294279
  console.error(`[SSH] Port forward setup failed:`, e);
293685
- emit10(`\x1B[31m\u2718 Port forward failed: ${e.message}\x1B[0m\r
294280
+ emit11(`\x1B[31m\u2718 Port forward failed: ${e.message}\x1B[0m\r
293686
294281
  `);
293687
294282
  }
293688
294283
  if (rawShell) {
@@ -293692,7 +294287,7 @@ var SSHBackend = class _SSHBackend {
293692
294287
  );
293693
294288
  } else {
293694
294289
  try {
293695
- emit10("\x1B[36m\u25B9 Detecting remote OS...\x1B[0m\r\n");
294290
+ emit11("\x1B[36m\u25B9 Detecting remote OS...\x1B[0m\r\n");
293696
294291
  console.log(`[SSH] Detecting remote OS...`);
293697
294292
  const uname = await this.execCollect(client2, "uname -s");
293698
294293
  const u = (uname.stdout || uname.stderr || "").toLowerCase();
@@ -293712,13 +294307,13 @@ var SSHBackend = class _SSHBackend {
293712
294307
  if (!instance.remoteOs) instance.remoteOs = "unix";
293713
294308
  console.log(`[SSH] Remote OS detected: ${instance.remoteOs}`);
293714
294309
  try {
293715
- emit10("\x1B[36m\u25B9 Initializing SFTP channel...\x1B[0m\r\n");
294310
+ emit11("\x1B[36m\u25B9 Initializing SFTP channel...\x1B[0m\r\n");
293716
294311
  await this.initializeSftp(instance);
293717
- emit10("\x1B[32m\u2714 SFTP channel ready.\x1B[0m\r\n");
294312
+ emit11("\x1B[32m\u2714 SFTP channel ready.\x1B[0m\r\n");
293718
294313
  } catch (error40) {
293719
294314
  const message = error40 instanceof Error ? error40.message : String(error40);
293720
294315
  instance.sftpInitError = message;
293721
- emit10(
294316
+ emit11(
293722
294317
  `\x1B[33m\u26A0 SFTP unavailable: ${message}. File panel features may be limited.\x1B[0m\r
293723
294318
  `
293724
294319
  );
@@ -293731,7 +294326,7 @@ var SSHBackend = class _SSHBackend {
293731
294326
  }
293732
294327
  }
293733
294328
  }
293734
- emit10("\x1B[36m\u25B9 Opening interactive shell...\x1B[0m\r\n");
294329
+ emit11("\x1B[36m\u25B9 Opening interactive shell...\x1B[0m\r\n");
293735
294330
  console.log(`[SSH] Opening interactive shell...`);
293736
294331
  const initialWindowSize = this.resolveRequestedWindowSize(instance, {
293737
294332
  cols: config2.cols,
@@ -293761,7 +294356,7 @@ var SSHBackend = class _SSHBackend {
293761
294356
  console.error(`[SSH] Failed to open shell:`, err);
293762
294357
  instance.initializationState = "failed";
293763
294358
  instance.isInitializing = false;
293764
- emit10(`\x1B[31m\u2718 Failed to open shell: ${err.message}\x1B[0m\r
294359
+ emit11(`\x1B[31m\u2718 Failed to open shell: ${err.message}\x1B[0m\r
293765
294360
  `);
293766
294361
  emitExit(-1);
293767
294362
  return;
@@ -293771,7 +294366,7 @@ var SSHBackend = class _SSHBackend {
293771
294366
  if (rawShell) {
293772
294367
  instance.initializationState = "ready";
293773
294368
  instance.isInitializing = false;
293774
- emit10("\x1B[32m\u2714 Shell ready.\x1B[0m\r\n");
294369
+ emit11("\x1B[32m\u2714 Shell ready.\x1B[0m\r\n");
293775
294370
  console.log(
293776
294371
  `[SSH] Raw-shell mode: shell ready immediately (preset=${sshConfig.algorithmsPreset}).`
293777
294372
  );
@@ -293779,14 +294374,14 @@ var SSHBackend = class _SSHBackend {
293779
294374
  const chunk2 = data.toString();
293780
294375
  const sanitizedChunk = this.stripReadyMarker(chunk2);
293781
294376
  this.consumeOscMarkers(instance, sanitizedChunk);
293782
- if (sanitizedChunk) emit10(sanitizedChunk);
294377
+ if (sanitizedChunk) emit11(sanitizedChunk);
293783
294378
  });
293784
294379
  stream.on("close", async (code) => {
293785
294380
  emitExit(typeof code === "number" ? code : 0);
293786
294381
  });
293787
294382
  return;
293788
294383
  }
293789
- emit10("\x1B[36m\u25B9 Initializing shell integration...\x1B[0m\r\n");
294384
+ emit11("\x1B[36m\u25B9 Initializing shell integration...\x1B[0m\r\n");
293790
294385
  console.log(
293791
294386
  `[SSH] Shell stream opened. Starting robust initialization...`
293792
294387
  );
@@ -293832,7 +294427,7 @@ var SSHBackend = class _SSHBackend {
293832
294427
  if (retryCount >= maxRetries) {
293833
294428
  instance.initializationState = "failed";
293834
294429
  instance.isInitializing = false;
293835
- emit10(
294430
+ emit11(
293836
294431
  "\x1B[31m\u2718 Initialization failed. Entering fallback mode.\x1B[0m\r\n"
293837
294432
  );
293838
294433
  console.error(
@@ -293841,7 +294436,7 @@ var SSHBackend = class _SSHBackend {
293841
294436
  clearInterval(watchdogInterval);
293842
294437
  return;
293843
294438
  }
293844
- emit10(
294439
+ emit11(
293845
294440
  `\x1B[33m\u26A0 Initialization timeout, retrying (${retryCount}/${maxRetries})...\x1B[0m\r
293846
294441
  `
293847
294442
  );
@@ -293855,7 +294450,7 @@ var SSHBackend = class _SSHBackend {
293855
294450
  if (instance.isInitializing) {
293856
294451
  instance.buffer += chunk2;
293857
294452
  if (instance.buffer.includes(GYSHELL_READY_MARKER2)) {
293858
- emit10("\x1B[2J\x1B[H");
294453
+ emit11("\x1B[2J\x1B[H");
293859
294454
  isReadySent = true;
293860
294455
  clearInterval(watchdogInterval);
293861
294456
  const sawContinuation = /(?:\r?\n)>>\s*\r?\n/.test(instance.buffer) || instance.buffer.trimEnd().endsWith("\n>>") || instance.buffer.trimEnd().endsWith("\r\n>>");
@@ -293866,7 +294461,7 @@ var SSHBackend = class _SSHBackend {
293866
294461
  const realContent = this.stripReadyMarker(
293867
294462
  parts.slice(1).join(GYSHELL_READY_MARKER2)
293868
294463
  ).trimStart();
293869
- if (realContent) emit10(realContent);
294464
+ if (realContent) emit11(realContent);
293870
294465
  }
293871
294466
  instance.buffer = "";
293872
294467
  if (sawContinuation && instance.remoteOs === "windows" && instance.stream) {
@@ -293882,7 +294477,7 @@ var SSHBackend = class _SSHBackend {
293882
294477
  const sanitizedChunk = this.stripReadyMarker(chunk2);
293883
294478
  this.consumeOscMarkers(instance, sanitizedChunk);
293884
294479
  if (sanitizedChunk) {
293885
- emit10(sanitizedChunk);
294480
+ emit11(sanitizedChunk);
293886
294481
  }
293887
294482
  }
293888
294483
  });
@@ -293896,7 +294491,7 @@ var SSHBackend = class _SSHBackend {
293896
294491
  console.error(`[SSH] Client error:`, err);
293897
294492
  instance.initializationState = "failed";
293898
294493
  instance.isInitializing = false;
293899
- emit10(`\x1B[31m\u2718 SSH Error: ${err.message}\x1B[0m\r
294494
+ emit11(`\x1B[31m\u2718 SSH Error: ${err.message}\x1B[0m\r
293900
294495
  `);
293901
294496
  emitExit(-1);
293902
294497
  });
@@ -293919,7 +294514,7 @@ var SSHBackend = class _SSHBackend {
293919
294514
  sshConfig.privateKeyPath
293920
294515
  );
293921
294516
  } catch (e) {
293922
- emit10(
294517
+ emit11(
293923
294518
  `\x1B[31m\u2718 Failed to read private key: ${e.message}\x1B[0m\r
293924
294519
  `
293925
294520
  );
@@ -293931,19 +294526,19 @@ var SSHBackend = class _SSHBackend {
293931
294526
  }
293932
294527
  try {
293933
294528
  await new Promise((r) => setTimeout(r, 50));
293934
- emit10(
294529
+ emit11(
293935
294530
  `\x1B[36m\u25B9 Connecting to ${sshConfig.host}:${sshConfig.port}...\x1B[0m\r
293936
294531
  `
293937
294532
  );
293938
294533
  console.log(
293939
294534
  `[SSH] Attempting to connect to ${sshConfig.host}:${sshConfig.port}...`
293940
294535
  );
293941
- const sock = await this.buildConnectSocketIfNeeded(sshConfig, emit10);
294536
+ const sock = await this.buildConnectSocketIfNeeded(sshConfig, emit11);
293942
294537
  if (sock) {
293943
294538
  console.log(
293944
294539
  `[SSH] SUCCESS: Connection to ${sshConfig.host} will be tunneled through sock (Jump Host/Proxy).`
293945
294540
  );
293946
- emit10(
294541
+ emit11(
293947
294542
  "\x1B[36m\u25B9 [Final] Using tunnel socket for target connection...\x1B[0m\r\n"
293948
294543
  );
293949
294544
  connectConfig.sock = sock;
@@ -293957,7 +294552,7 @@ var SSHBackend = class _SSHBackend {
293957
294552
  const errMsg = e instanceof Error ? e.message : String(e);
293958
294553
  instance.initializationState = "failed";
293959
294554
  instance.isInitializing = false;
293960
- emit10(`\x1B[31m\u2718 Connection failed: ${errMsg}\x1B[0m\r
294555
+ emit11(`\x1B[31m\u2718 Connection failed: ${errMsg}\x1B[0m\r
293961
294556
  `);
293962
294557
  emitExit(-1);
293963
294558
  }
@@ -296408,11 +297003,11 @@ Run commands with exec_command / run_fleet_command. Interactive TUI apps are not
296408
297003
  var import_node_crypto5 = require("node:crypto");
296409
297004
  var injectedSerial = null;
296410
297005
  var lazySerial;
296411
- function constructPort(Ctor, path32, opts) {
297006
+ function constructPort(Ctor, path33, opts) {
296412
297007
  try {
296413
- return new Ctor(path32, opts);
297008
+ return new Ctor(path33, opts);
296414
297009
  } catch (e) {
296415
- if (e instanceof TypeError) return new Ctor({ path: path32, ...opts });
297010
+ if (e instanceof TypeError) return new Ctor({ path: path33, ...opts });
296416
297011
  throw e;
296417
297012
  }
296418
297013
  }
@@ -296430,7 +297025,7 @@ var SerialBackend = class {
296430
297025
  try {
296431
297026
  const mod = require("serialport");
296432
297027
  const Ctor = typeof mod?.SerialPort === "function" ? mod.SerialPort : mod;
296433
- lazySerial = ((path32, opts) => constructPort(Ctor, path32, opts));
297028
+ lazySerial = ((path33, opts) => constructPort(Ctor, path33, opts));
296434
297029
  } catch {
296435
297030
  lazySerial = null;
296436
297031
  }
@@ -300884,8 +301479,8 @@ function shallowCopy(obj) {
300884
301479
  }
300885
301480
  function replaceSecrets(root, secretsMap) {
300886
301481
  const result = shallowCopy(root);
300887
- for (const [path32, secretId] of Object.entries(secretsMap)) {
300888
- const [last, ...partsReverse] = path32.split(".").reverse();
301482
+ for (const [path33, secretId] of Object.entries(secretsMap)) {
301483
+ const [last, ...partsReverse] = path33.split(".").reverse();
300889
301484
  let current = result;
300890
301485
  for (const part of partsReverse.reverse()) {
300891
301486
  if (current[part] === void 0) break;
@@ -305949,9 +306544,9 @@ var Client = class _Client {
305949
306544
  }
305950
306545
  return headers;
305951
306546
  }
305952
- _getPlatformEndpointPath(path32) {
306547
+ _getPlatformEndpointPath(path33) {
305953
306548
  const needsV1Prefix = this.apiUrl.slice(-3) !== "/v1" && this.apiUrl.slice(-4) !== "/v1/";
305954
- return needsV1Prefix ? `/v1/platform/${path32}` : `/platform/${path32}`;
306549
+ return needsV1Prefix ? `/v1/platform/${path33}` : `/platform/${path33}`;
305955
306550
  }
305956
306551
  async processInputs(inputs) {
305957
306552
  if (this.hideInputs === false) {
@@ -305987,9 +306582,9 @@ var Client = class _Client {
305987
306582
  }
305988
306583
  return runParams;
305989
306584
  }
305990
- async _getResponse(path32, queryParams) {
306585
+ async _getResponse(path33, queryParams) {
305991
306586
  const paramsString = queryParams?.toString() ?? "";
305992
- const url2 = `${this.apiUrl}${path32}?${paramsString}`;
306587
+ const url2 = `${this.apiUrl}${path33}?${paramsString}`;
305993
306588
  const response = await this.caller.call(async () => {
305994
306589
  const res = await this._fetch(url2, {
305995
306590
  method: "GET",
@@ -305997,22 +306592,22 @@ var Client = class _Client {
305997
306592
  signal: AbortSignal.timeout(this.timeout_ms),
305998
306593
  ...this.fetchOptions
305999
306594
  });
306000
- await raiseForStatus(res, `fetch ${path32}`);
306595
+ await raiseForStatus(res, `fetch ${path33}`);
306001
306596
  return res;
306002
306597
  });
306003
306598
  return response;
306004
306599
  }
306005
- async _get(path32, queryParams) {
306006
- const response = await this._getResponse(path32, queryParams);
306600
+ async _get(path33, queryParams) {
306601
+ const response = await this._getResponse(path33, queryParams);
306007
306602
  return response.json();
306008
306603
  }
306009
- async *_getPaginated(path32, queryParams = new URLSearchParams(), transform2) {
306604
+ async *_getPaginated(path33, queryParams = new URLSearchParams(), transform2) {
306010
306605
  let offset = Number(queryParams.get("offset")) || 0;
306011
306606
  const limit2 = Number(queryParams.get("limit")) || 100;
306012
306607
  while (true) {
306013
306608
  queryParams.set("offset", String(offset));
306014
306609
  queryParams.set("limit", String(limit2));
306015
- const url2 = `${this.apiUrl}${path32}?${queryParams}`;
306610
+ const url2 = `${this.apiUrl}${path33}?${queryParams}`;
306016
306611
  const response = await this.caller.call(async () => {
306017
306612
  const res = await this._fetch(url2, {
306018
306613
  method: "GET",
@@ -306020,7 +306615,7 @@ var Client = class _Client {
306020
306615
  signal: AbortSignal.timeout(this.timeout_ms),
306021
306616
  ...this.fetchOptions
306022
306617
  });
306023
- await raiseForStatus(res, `fetch ${path32}`);
306618
+ await raiseForStatus(res, `fetch ${path33}`);
306024
306619
  return res;
306025
306620
  });
306026
306621
  const items = transform2 ? transform2(await response.json()) : await response.json();
@@ -306034,19 +306629,19 @@ var Client = class _Client {
306034
306629
  offset += items.length;
306035
306630
  }
306036
306631
  }
306037
- async *_getCursorPaginatedList(path32, body = null, requestMethod = "POST", dataKey = "runs") {
306632
+ async *_getCursorPaginatedList(path33, body = null, requestMethod = "POST", dataKey = "runs") {
306038
306633
  const bodyParams = body ? { ...body } : {};
306039
306634
  while (true) {
306040
306635
  const body2 = JSON.stringify(bodyParams);
306041
306636
  const response = await this.caller.call(async () => {
306042
- const res = await this._fetch(`${this.apiUrl}${path32}`, {
306637
+ const res = await this._fetch(`${this.apiUrl}${path33}`, {
306043
306638
  method: requestMethod,
306044
306639
  headers: { ...this.headers, "Content-Type": "application/json" },
306045
306640
  signal: AbortSignal.timeout(this.timeout_ms),
306046
306641
  ...this.fetchOptions,
306047
306642
  body: body2
306048
306643
  });
306049
- await raiseForStatus(res, `fetch ${path32}`);
306644
+ await raiseForStatus(res, `fetch ${path33}`);
306050
306645
  return res;
306051
306646
  });
306052
306647
  const responseBody = await response.json();
@@ -306975,8 +307570,8 @@ Context: ${context2}`);
306975
307570
  limit: Number(limit2) || 100
306976
307571
  };
306977
307572
  let currentOffset = Number(offset) || 0;
306978
- const path32 = "/runs/group";
306979
- const url2 = `${this.apiUrl}${path32}`;
307573
+ const path33 = "/runs/group";
307574
+ const url2 = `${this.apiUrl}${path33}`;
306980
307575
  while (true) {
306981
307576
  const currentBody = {
306982
307577
  ...baseBody,
@@ -306992,7 +307587,7 @@ Context: ${context2}`);
306992
307587
  ...this.fetchOptions,
306993
307588
  body
306994
307589
  });
306995
- await raiseForStatus(res, `Failed to fetch ${path32}`);
307590
+ await raiseForStatus(res, `Failed to fetch ${path33}`);
306996
307591
  return res;
306997
307592
  });
306998
307593
  const items = await response.json();
@@ -307309,20 +307904,20 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307309
307904
  return result;
307310
307905
  }
307311
307906
  async hasProject({ projectId, projectName }) {
307312
- let path32 = "/sessions";
307907
+ let path33 = "/sessions";
307313
307908
  const params = new URLSearchParams();
307314
307909
  if (projectId !== void 0 && projectName !== void 0) {
307315
307910
  throw new Error("Must provide either projectName or projectId, not both");
307316
307911
  } else if (projectId !== void 0) {
307317
307912
  assertUuid(projectId);
307318
- path32 += `/${projectId}`;
307913
+ path33 += `/${projectId}`;
307319
307914
  } else if (projectName !== void 0) {
307320
307915
  params.append("name", projectName);
307321
307916
  } else {
307322
307917
  throw new Error("Must provide projectName or projectId");
307323
307918
  }
307324
307919
  const response = await this.caller.call(async () => {
307325
- const res = await this._fetch(`${this.apiUrl}${path32}?${params}`, {
307920
+ const res = await this._fetch(`${this.apiUrl}${path33}?${params}`, {
307326
307921
  method: "GET",
307327
307922
  headers: this.headers,
307328
307923
  signal: AbortSignal.timeout(this.timeout_ms),
@@ -307345,13 +307940,13 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307345
307940
  }
307346
307941
  }
307347
307942
  async readProject({ projectId, projectName, includeStats }) {
307348
- let path32 = "/sessions";
307943
+ let path33 = "/sessions";
307349
307944
  const params = new URLSearchParams();
307350
307945
  if (projectId !== void 0 && projectName !== void 0) {
307351
307946
  throw new Error("Must provide either projectName or projectId, not both");
307352
307947
  } else if (projectId !== void 0) {
307353
307948
  assertUuid(projectId);
307354
- path32 += `/${projectId}`;
307949
+ path33 += `/${projectId}`;
307355
307950
  } else if (projectName !== void 0) {
307356
307951
  params.append("name", projectName);
307357
307952
  } else {
@@ -307360,7 +307955,7 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307360
307955
  if (includeStats !== void 0) {
307361
307956
  params.append("include_stats", includeStats.toString());
307362
307957
  }
307363
- const response = await this._get(path32, params);
307958
+ const response = await this._get(path33, params);
307364
307959
  let result;
307365
307960
  if (Array.isArray(response)) {
307366
307961
  if (response.length === 0) {
@@ -307523,19 +308118,19 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307523
308118
  return result;
307524
308119
  }
307525
308120
  async readDataset({ datasetId, datasetName }) {
307526
- let path32 = "/datasets";
308121
+ let path33 = "/datasets";
307527
308122
  const params = new URLSearchParams({ limit: "1" });
307528
308123
  if (datasetId && datasetName) {
307529
308124
  throw new Error("Must provide either datasetName or datasetId, not both");
307530
308125
  } else if (datasetId) {
307531
308126
  assertUuid(datasetId);
307532
- path32 += `/${datasetId}`;
308127
+ path33 += `/${datasetId}`;
307533
308128
  } else if (datasetName) {
307534
308129
  params.append("name", datasetName);
307535
308130
  } else {
307536
308131
  throw new Error("Must provide datasetName or datasetId");
307537
308132
  }
307538
- const response = await this._get(path32, params);
308133
+ const response = await this._get(path33, params);
307539
308134
  let result;
307540
308135
  if (Array.isArray(response)) {
307541
308136
  if (response.length === 0) {
@@ -307579,20 +308174,20 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307579
308174
  return response;
307580
308175
  }
307581
308176
  async readDatasetOpenaiFinetuning({ datasetId, datasetName }) {
307582
- const path32 = "/datasets";
308177
+ const path33 = "/datasets";
307583
308178
  if (datasetId !== void 0) {
307584
308179
  } else if (datasetName !== void 0) {
307585
308180
  datasetId = (await this.readDataset({ datasetName })).id;
307586
308181
  } else {
307587
308182
  throw new Error("Must provide either datasetName or datasetId");
307588
308183
  }
307589
- const response = await this._getResponse(`${path32}/${datasetId}/openai_ft`);
308184
+ const response = await this._getResponse(`${path33}/${datasetId}/openai_ft`);
307590
308185
  const datasetText = await response.text();
307591
308186
  const dataset = datasetText.trim().split("\n").map((line) => JSON.parse(line));
307592
308187
  return dataset;
307593
308188
  }
307594
308189
  async *listDatasets({ limit: limit2 = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata } = {}) {
307595
- const path32 = "/datasets";
308190
+ const path33 = "/datasets";
307596
308191
  const params = new URLSearchParams({
307597
308192
  limit: limit2.toString(),
307598
308193
  offset: offset.toString()
@@ -307611,7 +308206,7 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307611
308206
  if (metadata !== void 0) {
307612
308207
  params.append("metadata", JSON.stringify(metadata));
307613
308208
  }
307614
- for await (const datasets of this._getPaginated(path32, params)) {
308209
+ for await (const datasets of this._getPaginated(path33, params)) {
307615
308210
  yield* datasets;
307616
308211
  }
307617
308212
  }
@@ -307680,7 +308275,7 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307680
308275
  });
307681
308276
  }
307682
308277
  async deleteDataset({ datasetId, datasetName }) {
307683
- let path32 = "/datasets";
308278
+ let path33 = "/datasets";
307684
308279
  let datasetId_ = datasetId;
307685
308280
  if (datasetId !== void 0 && datasetName !== void 0) {
307686
308281
  throw new Error("Must provide either datasetName or datasetId, not both");
@@ -307690,18 +308285,18 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307690
308285
  }
307691
308286
  if (datasetId_ !== void 0) {
307692
308287
  assertUuid(datasetId_);
307693
- path32 += `/${datasetId_}`;
308288
+ path33 += `/${datasetId_}`;
307694
308289
  } else {
307695
308290
  throw new Error("Must provide datasetName or datasetId");
307696
308291
  }
307697
308292
  await this.caller.call(async () => {
307698
- const res = await this._fetch(this.apiUrl + path32, {
308293
+ const res = await this._fetch(this.apiUrl + path33, {
307699
308294
  method: "DELETE",
307700
308295
  headers: this.headers,
307701
308296
  signal: AbortSignal.timeout(this.timeout_ms),
307702
308297
  ...this.fetchOptions
307703
308298
  });
307704
- await raiseForStatus(res, `delete ${path32}`, true);
308299
+ await raiseForStatus(res, `delete ${path33}`, true);
307705
308300
  return res;
307706
308301
  });
307707
308302
  }
@@ -307892,8 +308487,8 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307892
308487
  }
307893
308488
  async readExample(exampleId) {
307894
308489
  assertUuid(exampleId);
307895
- const path32 = `/examples/${exampleId}`;
307896
- const rawExample = await this._get(path32);
308490
+ const path33 = `/examples/${exampleId}`;
308491
+ const rawExample = await this._get(path33);
307897
308492
  const { attachment_urls, ...rest } = rawExample;
307898
308493
  const example = rest;
307899
308494
  if (attachment_urls) {
@@ -307976,15 +308571,15 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307976
308571
  }
307977
308572
  async deleteExample(exampleId) {
307978
308573
  assertUuid(exampleId);
307979
- const path32 = `/examples/${exampleId}`;
308574
+ const path33 = `/examples/${exampleId}`;
307980
308575
  await this.caller.call(async () => {
307981
- const res = await this._fetch(this.apiUrl + path32, {
308576
+ const res = await this._fetch(this.apiUrl + path33, {
307982
308577
  method: "DELETE",
307983
308578
  headers: this.headers,
307984
308579
  signal: AbortSignal.timeout(this.timeout_ms),
307985
308580
  ...this.fetchOptions
307986
308581
  });
307987
- await raiseForStatus(res, `delete ${path32}`, true);
308582
+ await raiseForStatus(res, `delete ${path33}`, true);
307988
308583
  return res;
307989
308584
  });
307990
308585
  }
@@ -307997,9 +308592,9 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307997
308592
  async deleteExamples(exampleIds, options) {
307998
308593
  exampleIds.forEach((id) => assertUuid(id));
307999
308594
  if (options?.hardDelete) {
308000
- const path32 = this._getPlatformEndpointPath("datasets/examples/delete");
308595
+ const path33 = this._getPlatformEndpointPath("datasets/examples/delete");
308001
308596
  await this.caller.call(async () => {
308002
- const res = await this._fetch(`${this.apiUrl}${path32}`, {
308597
+ const res = await this._fetch(`${this.apiUrl}${path33}`, {
308003
308598
  method: "POST",
308004
308599
  headers: { ...this.headers, "Content-Type": "application/json" },
308005
308600
  body: JSON.stringify({
@@ -308233,21 +308828,21 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
308233
308828
  }
308234
308829
  async readFeedback(feedbackId) {
308235
308830
  assertUuid(feedbackId);
308236
- const path32 = `/feedback/${feedbackId}`;
308237
- const response = await this._get(path32);
308831
+ const path33 = `/feedback/${feedbackId}`;
308832
+ const response = await this._get(path33);
308238
308833
  return response;
308239
308834
  }
308240
308835
  async deleteFeedback(feedbackId) {
308241
308836
  assertUuid(feedbackId);
308242
- const path32 = `/feedback/${feedbackId}`;
308837
+ const path33 = `/feedback/${feedbackId}`;
308243
308838
  await this.caller.call(async () => {
308244
- const res = await this._fetch(this.apiUrl + path32, {
308839
+ const res = await this._fetch(this.apiUrl + path33, {
308245
308840
  method: "DELETE",
308246
308841
  headers: this.headers,
308247
308842
  signal: AbortSignal.timeout(this.timeout_ms),
308248
308843
  ...this.fetchOptions
308249
308844
  });
308250
- await raiseForStatus(res, `delete ${path32}`, true);
308845
+ await raiseForStatus(res, `delete ${path33}`, true);
308251
308846
  return res;
308252
308847
  });
308253
308848
  }
@@ -311843,12 +312438,12 @@ function isInteger(str3) {
311843
312438
  }
311844
312439
  return true;
311845
312440
  }
311846
- function escapePathComponent(path32) {
311847
- if (path32.indexOf("/") === -1 && path32.indexOf("~") === -1) return path32;
311848
- return path32.replace(/~/g, "~0").replace(/\//g, "~1");
312441
+ function escapePathComponent(path33) {
312442
+ if (path33.indexOf("/") === -1 && path33.indexOf("~") === -1) return path33;
312443
+ return path33.replace(/~/g, "~0").replace(/\//g, "~1");
311849
312444
  }
311850
- function unescapePathComponent(path32) {
311851
- return path32.replace(/~1/g, "/").replace(/~0/g, "~");
312445
+ function unescapePathComponent(path33) {
312446
+ return path33.replace(/~1/g, "/").replace(/~0/g, "~");
311852
312447
  }
311853
312448
  function hasUndefined(obj) {
311854
312449
  if (obj === void 0) return true;
@@ -312042,8 +312637,8 @@ function applyOperation(document2, operation, validateOperation = false, mutateD
312042
312637
  else return returnValue;
312043
312638
  } else {
312044
312639
  if (!mutateDocument) document2 = _deepClone(document2);
312045
- const path32 = operation.path || "";
312046
- const keys = path32.split("/");
312640
+ const path33 = operation.path || "";
312641
+ const keys = path33.split("/");
312047
312642
  let obj = document2;
312048
312643
  let t = 1;
312049
312644
  let len = keys.length;
@@ -312166,7 +312761,7 @@ function _areEquals(a, b) {
312166
312761
  }
312167
312762
 
312168
312763
  // ../../node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js
312169
- function _generate(mirror, obj, patches, path32, invertible) {
312764
+ function _generate(mirror, obj, patches, path33, invertible) {
312170
312765
  if (obj === mirror) return;
312171
312766
  if (typeof obj.toJSON === "function") obj = obj.toJSON();
312172
312767
  var newKeys = _objectKeys(obj);
@@ -312178,40 +312773,40 @@ function _generate(mirror, obj, patches, path32, invertible) {
312178
312773
  var oldVal = mirror[key];
312179
312774
  if (hasOwnProperty(obj, key) && !(obj[key] === void 0 && oldVal !== void 0 && Array.isArray(obj) === false)) {
312180
312775
  var newVal = obj[key];
312181
- if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) _generate(oldVal, newVal, patches, path32 + "/" + escapePathComponent(key), invertible);
312776
+ if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) _generate(oldVal, newVal, patches, path33 + "/" + escapePathComponent(key), invertible);
312182
312777
  else if (oldVal !== newVal) {
312183
312778
  changed = true;
312184
312779
  if (invertible) patches.push({
312185
312780
  op: "test",
312186
- path: path32 + "/" + escapePathComponent(key),
312781
+ path: path33 + "/" + escapePathComponent(key),
312187
312782
  value: _deepClone(oldVal)
312188
312783
  });
312189
312784
  patches.push({
312190
312785
  op: "replace",
312191
- path: path32 + "/" + escapePathComponent(key),
312786
+ path: path33 + "/" + escapePathComponent(key),
312192
312787
  value: _deepClone(newVal)
312193
312788
  });
312194
312789
  }
312195
312790
  } else if (Array.isArray(mirror) === Array.isArray(obj)) {
312196
312791
  if (invertible) patches.push({
312197
312792
  op: "test",
312198
- path: path32 + "/" + escapePathComponent(key),
312793
+ path: path33 + "/" + escapePathComponent(key),
312199
312794
  value: _deepClone(oldVal)
312200
312795
  });
312201
312796
  patches.push({
312202
312797
  op: "remove",
312203
- path: path32 + "/" + escapePathComponent(key)
312798
+ path: path33 + "/" + escapePathComponent(key)
312204
312799
  });
312205
312800
  deleted = true;
312206
312801
  } else {
312207
312802
  if (invertible) patches.push({
312208
312803
  op: "test",
312209
- path: path32,
312804
+ path: path33,
312210
312805
  value: mirror
312211
312806
  });
312212
312807
  patches.push({
312213
312808
  op: "replace",
312214
- path: path32,
312809
+ path: path33,
312215
312810
  value: obj
312216
312811
  });
312217
312812
  changed = true;
@@ -312222,7 +312817,7 @@ function _generate(mirror, obj, patches, path32, invertible) {
312222
312817
  var key = newKeys[t];
312223
312818
  if (!hasOwnProperty(mirror, key) && obj[key] !== void 0) patches.push({
312224
312819
  op: "add",
312225
- path: path32 + "/" + escapePathComponent(key),
312820
+ path: path33 + "/" + escapePathComponent(key),
312226
312821
  value: _deepClone(obj[key])
312227
312822
  });
312228
312823
  }
@@ -313608,10 +314203,10 @@ function assignProp(target, prop, value) {
313608
314203
  configurable: true
313609
314204
  });
313610
314205
  }
313611
- function getElementAtPath(obj, path32) {
313612
- if (!path32)
314206
+ function getElementAtPath(obj, path33) {
314207
+ if (!path33)
313613
314208
  return obj;
313614
- return path32.reduce((acc, key) => acc?.[key], obj);
314209
+ return path33.reduce((acc, key) => acc?.[key], obj);
313615
314210
  }
313616
314211
  function promiseAllObject(promisesObj) {
313617
314212
  const keys = Object.keys(promisesObj);
@@ -313931,11 +314526,11 @@ function aborted(x, startIndex = 0) {
313931
314526
  }
313932
314527
  return false;
313933
314528
  }
313934
- function prefixIssues(path32, issues) {
314529
+ function prefixIssues(path33, issues) {
313935
314530
  return issues.map((iss) => {
313936
314531
  var _a3;
313937
314532
  (_a3 = iss).path ?? (_a3.path = []);
313938
- iss.path.unshift(path32);
314533
+ iss.path.unshift(path33);
313939
314534
  return iss;
313940
314535
  });
313941
314536
  }
@@ -314072,7 +314667,7 @@ function treeifyError(error40, _mapper) {
314072
314667
  return issue2.message;
314073
314668
  };
314074
314669
  const result = { errors: [] };
314075
- const processError = (error41, path32 = []) => {
314670
+ const processError = (error41, path33 = []) => {
314076
314671
  var _a3, _b;
314077
314672
  for (const issue2 of error41.issues) {
314078
314673
  if (issue2.code === "invalid_union" && issue2.errors.length) {
@@ -314082,7 +314677,7 @@ function treeifyError(error40, _mapper) {
314082
314677
  } else if (issue2.code === "invalid_element") {
314083
314678
  processError({ issues: issue2.issues }, issue2.path);
314084
314679
  } else {
314085
- const fullpath = [...path32, ...issue2.path];
314680
+ const fullpath = [...path33, ...issue2.path];
314086
314681
  if (fullpath.length === 0) {
314087
314682
  result.errors.push(mapper(issue2));
314088
314683
  continue;
@@ -314112,9 +314707,9 @@ function treeifyError(error40, _mapper) {
314112
314707
  processError(error40);
314113
314708
  return result;
314114
314709
  }
314115
- function toDotPath(path32) {
314710
+ function toDotPath(path33) {
314116
314711
  const segs = [];
314117
- for (const seg of path32) {
314712
+ for (const seg of path33) {
314118
314713
  if (typeof seg === "number")
314119
314714
  segs.push(`[${seg}]`);
314120
314715
  else if (typeof seg === "symbol")
@@ -326362,10 +326957,10 @@ var Runnable = class extends Serializable {
326362
326957
  }
326363
326958
  const paths = log.ops.filter((op) => op.path.startsWith("/logs/")).map((op) => op.path.split("/")[2]);
326364
326959
  const dedupedPaths = [...new Set(paths)];
326365
- for (const path32 of dedupedPaths) {
326960
+ for (const path33 of dedupedPaths) {
326366
326961
  let eventType;
326367
326962
  let data = {};
326368
- const logEntry = runLog.state.logs[path32];
326963
+ const logEntry = runLog.state.logs[path33];
326369
326964
  if (logEntry.end_time === void 0) if (logEntry.streamed_output.length > 0) eventType = "stream";
326370
326965
  else eventType = "start";
326371
326966
  else eventType = "end";
@@ -332058,7 +332653,7 @@ var initializeSax = function() {
332058
332653
  if (parser.opt.xmlns) parser.ns = Object.create(rootNS);
332059
332654
  parser.trackPosition = parser.opt.position !== false;
332060
332655
  if (parser.trackPosition) parser.position = parser.line = parser.column = 0;
332061
- emit10(parser, "onready");
332656
+ emit11(parser, "onready");
332062
332657
  }
332063
332658
  if (!Object.create) Object.create = function(o) {
332064
332659
  function F2() {
@@ -332524,16 +333119,16 @@ var initializeSax = function() {
332524
333119
  });
332525
333120
  for (var s in sax$1.STATE) sax$1.STATE[sax$1.STATE[s]] = s;
332526
333121
  S2 = sax$1.STATE;
332527
- function emit10(parser, event, data) {
333122
+ function emit11(parser, event, data) {
332528
333123
  parser[event] && parser[event](data);
332529
333124
  }
332530
333125
  function emitNode(parser, nodeType, data) {
332531
333126
  if (parser.textNode) closeText(parser);
332532
- emit10(parser, nodeType, data);
333127
+ emit11(parser, nodeType, data);
332533
333128
  }
332534
333129
  function closeText(parser) {
332535
333130
  parser.textNode = textopts(parser.opt, parser.textNode);
332536
- if (parser.textNode) emit10(parser, "ontext", parser.textNode);
333131
+ if (parser.textNode) emit11(parser, "ontext", parser.textNode);
332537
333132
  parser.textNode = "";
332538
333133
  }
332539
333134
  function textopts(opt, text) {
@@ -332546,7 +333141,7 @@ var initializeSax = function() {
332546
333141
  if (parser.trackPosition) er += "\nLine: " + parser.line + "\nColumn: " + parser.column + "\nChar: " + parser.c;
332547
333142
  er = new Error(er);
332548
333143
  parser.error = er;
332549
- emit10(parser, "onerror", er);
333144
+ emit11(parser, "onerror", er);
332550
333145
  return parser;
332551
333146
  }
332552
333147
  function end(parser) {
@@ -332555,7 +333150,7 @@ var initializeSax = function() {
332555
333150
  closeText(parser);
332556
333151
  parser.c = "";
332557
333152
  parser.closed = true;
332558
- emit10(parser, "onend");
333153
+ emit11(parser, "onend");
332559
333154
  SAXParser.call(parser, parser.strict, parser.opt);
332560
333155
  return parser;
332561
333156
  }
@@ -338430,13 +339025,13 @@ function combineAliasesAndInvert(constructor) {
338430
339025
  }, {});
338431
339026
  }
338432
339027
  async function reviver(value) {
338433
- const { optionalImportsMap, optionalImportEntrypoints: optionalImportEntrypoints$1, importMap, secretsMap, secretsFromEnv, path: path32, depth, maxDepth } = this;
338434
- const pathStr = path32.join(".");
339028
+ const { optionalImportsMap, optionalImportEntrypoints: optionalImportEntrypoints$1, importMap, secretsMap, secretsFromEnv, path: path33, depth, maxDepth } = this;
339029
+ const pathStr = path33.join(".");
338435
339030
  if (depth > maxDepth) throw new Error(`Maximum recursion depth (${maxDepth}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);
338436
339031
  if (typeof value !== "object" || value == null) return value;
338437
339032
  if (Array.isArray(value)) return Promise.all(value.map((v, i) => reviver.call({
338438
339033
  ...this,
338439
- path: [...path32, `${i}`],
339034
+ path: [...path33, `${i}`],
338440
339035
  depth: depth + 1
338441
339036
  }, v)));
338442
339037
  const record2 = value;
@@ -338491,7 +339086,7 @@ async function reviver(value) {
338491
339086
  if (typeof builder !== "function") throw new Error(`Invalid identifer: ${pathStr} -> ${str3}`);
338492
339087
  const kwargs = await reviver.call({
338493
339088
  ...this,
338494
- path: [...path32, "kwargs"],
339089
+ path: [...path33, "kwargs"],
338495
339090
  depth: depth + 1
338496
339091
  }, serialized.kwargs);
338497
339092
  const instance = new builder(mapKeys(kwargs, keyFromJson, combineAliasesAndInvert(builder)));
@@ -338501,7 +339096,7 @@ async function reviver(value) {
338501
339096
  const result = {};
338502
339097
  for (const [key, val] of Object.entries(record2)) result[key] = await reviver.call({
338503
339098
  ...this,
338504
- path: [...path32, key],
339099
+ path: [...path33, key],
338505
339100
  depth: depth + 1
338506
339101
  }, val);
338507
339102
  return result;
@@ -343629,10 +344224,10 @@ var Graph$1 = class {
343629
344224
  this.edges.add([startKey, endKey]);
343630
344225
  return this;
343631
344226
  }
343632
- addConditionalEdges(source, path32, pathMap) {
344227
+ addConditionalEdges(source, path33, pathMap) {
343633
344228
  const options = typeof source === "object" ? source : {
343634
344229
  source,
343635
- path: path32,
344230
+ path: path33,
343636
344231
  pathMap
343637
344232
  };
343638
344233
  this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");
@@ -345164,16 +345759,16 @@ var Diff = class {
345164
345759
  }
345165
345760
  }
345166
345761
  }
345167
- addToPath(path32, added, removed, oldPosInc, options) {
345168
- const last = path32.lastComponent;
345762
+ addToPath(path33, added, removed, oldPosInc, options) {
345763
+ const last = path33.lastComponent;
345169
345764
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
345170
345765
  return {
345171
- oldPos: path32.oldPos + oldPosInc,
345766
+ oldPos: path33.oldPos + oldPosInc,
345172
345767
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
345173
345768
  };
345174
345769
  } else {
345175
345770
  return {
345176
- oldPos: path32.oldPos + oldPosInc,
345771
+ oldPos: path33.oldPos + oldPosInc,
345177
345772
  lastComponent: { count: 1, added, removed, previousComponent: last }
345178
345773
  };
345179
345774
  }
@@ -346690,6 +347285,143 @@ function recallForPrompt(content, opts = {}) {
346690
347285
  return picked.join("\n");
346691
347286
  }
346692
347287
 
347288
+ // ../../packages/backend/src/services/AgentHelper/tools/learning_tools.ts
347289
+ init_zod();
347290
+ var import_node_crypto16 = require("node:crypto");
347291
+ init_compoundingKnowledge();
347292
+ function emit(context2, toolName, input, output) {
347293
+ context2.sendEvent(context2.sessionId, {
347294
+ messageId: context2.messageId,
347295
+ type: "tool_call",
347296
+ toolName,
347297
+ input: typeof input === "string" ? input : JSON.stringify(input),
347298
+ output
347299
+ });
347300
+ }
347301
+ var opsExperimentSchema = external_exports.object({
347302
+ hypothesis: external_exports.string().min(1).describe('What you think is true, e.g. "SMB IPC$ is blocked (NetUseAdd 64)".'),
347303
+ probe: external_exports.string().min(1).describe("One cheap command that would confirm or reject the hypothesis."),
347304
+ tag: external_exports.enum(["ad-join", "ad-promo", "smb", "aws-sg", "disk", "windows-feature", "psrp", "dns", "other"]).describe("Probe family. Gated mutations require a matching tag in this session (e.g. Add-Computer needs ad-join)."),
347305
+ expect: external_exports.string().optional().describe("Optional substring the probe output must contain to count as ok."),
347306
+ tabIdOrName: external_exports.string().optional().describe("Optional tab to run the probe on. If omitted, the experiment is recorded as a plan only.")
347307
+ });
347308
+ var manageGoalSchema = external_exports.object({
347309
+ action: external_exports.enum(["upsert", "list", "done", "abandon"]).describe("upsert a goal, list session goals, mark done, or abandon."),
347310
+ id: external_exports.string().optional().describe("Goal id (upsert/done/abandon). Generated if omitted on upsert."),
347311
+ text: external_exports.string().optional().describe("Goal text (upsert)."),
347312
+ status: external_exports.enum(["open", "blocked", "done", "abandoned"]).optional(),
347313
+ blockedBy: external_exports.string().optional(),
347314
+ nextProbe: external_exports.string().optional()
347315
+ });
347316
+ var estateFactsSchema = external_exports.object({
347317
+ action: external_exports.enum(["upsert", "list"]).describe("upsert a fact for a connection identity, or list the estate snapshot."),
347318
+ name: external_exports.string().optional().describe("Saved connection name (preferred identity)."),
347319
+ host: external_exports.string().optional(),
347320
+ role: external_exports.string().optional().describe("dc | member | workgroup | other"),
347321
+ domain: external_exports.string().optional(),
347322
+ transport: external_exports.string().optional(),
347323
+ auth: external_exports.string().optional(),
347324
+ facts: external_exports.record(external_exports.unknown()).optional()
347325
+ });
347326
+ async function opsExperiment(args, context2) {
347327
+ const store = context2.compoundingStore;
347328
+ if (!store) {
347329
+ const msg2 = "Compounding store is not wired in this runtime.";
347330
+ emit(context2, "ops_experiment", args, msg2);
347331
+ return msg2;
347332
+ }
347333
+ store.recordProbe(context2.sessionId, args.tag, args.hypothesis, args.probe, false);
347334
+ const msg = `Recorded experiment tag=${args.tag}
347335
+ hypothesis: ${args.hypothesis}
347336
+ probe: ${args.probe}
347337
+ ` + (args.expect ? `expect: ${args.expect}
347338
+ ` : "") + (args.tabIdOrName ? `Run the probe on tab "${args.tabIdOrName}" with exec_command, then treat a match of expect as confirmation. Do not retry the original mutation until the probe has been run.` : `Run the probe next. Gated mutations that require tag "${args.tag}" are now allowed in this session only AFTER you actually run the probe command.`);
347339
+ emit(context2, "ops_experiment", args, msg);
347340
+ return msg;
347341
+ }
347342
+ async function manageGoal(args, context2) {
347343
+ const store = context2.compoundingStore;
347344
+ if (!store) {
347345
+ const msg2 = "Compounding store is not wired in this runtime.";
347346
+ emit(context2, "manage_goal", args, msg2);
347347
+ return msg2;
347348
+ }
347349
+ if (args.action === "list") {
347350
+ const goals = store.listGoals(context2.sessionId);
347351
+ const msg2 = goals.length ? goals.map((g) => `- ${g.id} [${g.status}] ${g.text}${g.blockedBy ? ` blocked_by=${g.blockedBy}` : ""}`).join("\n") : "No goals in this session.";
347352
+ emit(context2, "manage_goal", args, msg2);
347353
+ return msg2;
347354
+ }
347355
+ const id = args.id || `goal-${(0, import_node_crypto16.randomUUID)().slice(0, 8)}`;
347356
+ if (args.action === "done" || args.action === "abandon") {
347357
+ const existing = store.listGoals(context2.sessionId).find((g) => g.id === id);
347358
+ store.upsertGoal({
347359
+ id,
347360
+ sessionId: context2.sessionId,
347361
+ text: existing?.text || args.text || id,
347362
+ status: args.action === "done" ? "done" : "abandoned"
347363
+ });
347364
+ const msg2 = `Goal ${id} marked ${args.action}.`;
347365
+ emit(context2, "manage_goal", args, msg2);
347366
+ return msg2;
347367
+ }
347368
+ if (!args.text) {
347369
+ const msg2 = "upsert requires text";
347370
+ emit(context2, "manage_goal", args, msg2);
347371
+ return msg2;
347372
+ }
347373
+ store.upsertGoal({
347374
+ id,
347375
+ sessionId: context2.sessionId,
347376
+ text: args.text,
347377
+ status: args.status || "open",
347378
+ blockedBy: args.blockedBy,
347379
+ nextProbe: args.nextProbe
347380
+ });
347381
+ const msg = `Goal ${id} [${args.status || "open"}] ${args.text}`;
347382
+ emit(context2, "manage_goal", args, msg);
347383
+ return msg;
347384
+ }
347385
+ async function estateFacts(args, context2) {
347386
+ const store = context2.compoundingStore;
347387
+ if (!store) {
347388
+ const msg2 = "Compounding store is not wired in this runtime.";
347389
+ emit(context2, "estate_facts", args, msg2);
347390
+ return msg2;
347391
+ }
347392
+ if (args.action === "list") {
347393
+ const facts = store.listEstateFacts();
347394
+ const msg2 = facts.length ? facts.map((f) => {
347395
+ const bits = [f.identity, f.role, f.domain, [f.transport, f.auth].filter(Boolean).join("/")].filter(Boolean);
347396
+ return `- ${bits.join(" \xB7 ")}`;
347397
+ }).join("\n") : "No estate facts recorded yet. Upsert after collect_facts / AD probes.";
347398
+ emit(context2, "estate_facts", args, msg2);
347399
+ return msg2;
347400
+ }
347401
+ const identity = connectionIdentity({
347402
+ name: args.name,
347403
+ host: args.host,
347404
+ transport: args.transport,
347405
+ auth: args.auth,
347406
+ domain: args.domain
347407
+ });
347408
+ store.upsertEstateFact({
347409
+ identity,
347410
+ host: args.host,
347411
+ role: args.role,
347412
+ domain: args.domain,
347413
+ transport: args.transport,
347414
+ auth: args.auth,
347415
+ facts: args.facts
347416
+ });
347417
+ const msg = `Upserted estate fact identity=${identity}`;
347418
+ emit(context2, "estate_facts", args, msg);
347419
+ return msg;
347420
+ }
347421
+ var OPS_EXPERIMENT_DESCRIPTION = "Record a named hypothesis + cheap probe BEFORE a destructive mutation (Add-Computer, Install-ADDSForest, djoin /provision, Set-SmbServerConfiguration, SG ingress). Gated commands refuse to run in this session until ops_experiment has been called with the matching tag (ad-join, ad-promo, smb, aws-sg, \u2026). If the probe fails, do NOT retry the original mutation \u2014 pick the INSTEAD from compounding lessons (e.g. djoin instead of Add-Computer).";
347422
+ var MANAGE_GOAL_DESCRIPTION = "Persistent operator intent for this chat session: upsert/list/done/abandon goals so a multi-step job (join server-2, wait for reboot) survives tool loops. Call upsert when the user states a job; list at the start of a turn if you might have forgotten.";
347423
+ var ESTATE_FACTS_DESCRIPTION = "Queryable snapshot of THIS estate keyed by connection NAME not IP (CORP-DC1 psrp+negotiate is not neuralos-win1 psrp+basic even on the same host). Upsert after collect_facts / Get-ADDomain; list to see dc vs member vs workgroup.";
347424
+
346693
347425
  // ../../packages/backend/src/services/AgentHelper/prompts.ts
346694
347426
  var SYS_INFO_MARKER = "CURRENT_SYSTEM_INFO_MSG:\n";
346695
347427
  var GYSHELL_BASE_SYSTEM_MARKER = "# Role: GyShell Assistant";
@@ -347089,6 +347821,21 @@ var BUILTIN_TOOL_INFO = [
347089
347821
  description: GET_RUN_LEDGER_DESCRIPTION,
347090
347822
  shortDescription: "Query agent run audit ledger"
347091
347823
  },
347824
+ {
347825
+ name: "ops_experiment",
347826
+ description: OPS_EXPERIMENT_DESCRIPTION,
347827
+ shortDescription: "Hypothesis + probe before mutations"
347828
+ },
347829
+ {
347830
+ name: "manage_goal",
347831
+ description: MANAGE_GOAL_DESCRIPTION,
347832
+ shortDescription: "Persistent session goals"
347833
+ },
347834
+ {
347835
+ name: "estate_facts",
347836
+ description: ESTATE_FACTS_DESCRIPTION,
347837
+ shortDescription: "Estate snapshot by connection name"
347838
+ },
347092
347839
  {
347093
347840
  name: "run_fleet_command",
347094
347841
  description: RUN_FLEET_COMMAND_DESCRIPTION,
@@ -347656,7 +348403,7 @@ function buildUnfinishedFileTransferContinueInstruction(transfers) {
347656
348403
  }
347657
348404
 
347658
348405
  // ../../packages/backend/src/services/AgentHelper/tools/terminal_tools.ts
347659
- var import_node_crypto16 = require("node:crypto");
348406
+ var import_node_crypto17 = require("node:crypto");
347660
348407
  var execCommandSchema = external_exports.object({
347661
348408
  tabIdOrName: external_exports.string().describe("The ID or Name of the terminal tab"),
347662
348409
  command: external_exports.string().describe("The shell command to execute"),
@@ -347708,7 +348455,7 @@ function sshEntryToTerminalConfig(entry, opts) {
347708
348455
  const jumpHost = entry.jumpHost;
347709
348456
  return {
347710
348457
  type: "ssh",
347711
- id: `ssh-${(0, import_node_crypto16.randomUUID)()}`,
348458
+ id: `ssh-${(0, import_node_crypto17.randomUUID)()}`,
347712
348459
  title: opts.title,
347713
348460
  cols: 80,
347714
348461
  rows: 24,
@@ -347738,7 +348485,7 @@ function resolveSavedWinrmConnection(context2, nameOrId) {
347738
348485
  function winrmEntryToTerminalConfig(entry, opts) {
347739
348486
  return {
347740
348487
  type: "winrm",
347741
- id: `winrm-${(0, import_node_crypto16.randomUUID)()}`,
348488
+ id: `winrm-${(0, import_node_crypto17.randomUUID)()}`,
347742
348489
  title: opts.title,
347743
348490
  cols: 80,
347744
348491
  rows: 24,
@@ -347763,7 +348510,7 @@ function resolveSavedSerialConnection(context2, nameOrId) {
347763
348510
  function serialEntryToTerminalConfig(entry, opts) {
347764
348511
  return {
347765
348512
  type: "serial",
347766
- id: `serial-${(0, import_node_crypto16.randomUUID)()}`,
348513
+ id: `serial-${(0, import_node_crypto17.randomUUID)()}`,
347767
348514
  title: opts.title,
347768
348515
  cols: 80,
347769
348516
  rows: 24,
@@ -347889,6 +348636,30 @@ async function runCommand(args, context2, options) {
347889
348636
  "run commands in this terminal"
347890
348637
  );
347891
348638
  }
348639
+ const { matchGatedMutation: matchGatedMutation2 } = await Promise.resolve().then(() => (init_compoundingKnowledge(), compoundingKnowledge_exports)).catch(() => ({ matchGatedMutation: () => null }));
348640
+ const gated = matchGatedMutation2(command);
348641
+ if (gated && context2.compoundingStore && !context2.compoundingStore.hasProbe(context2.sessionId, gated.requireProbeTag)) {
348642
+ const block = `Blocked gated mutation "${gated.id}" until ops_experiment runs with tag="${gated.requireProbeTag}" in this session. Call ops_experiment (hypothesis + cheap probe) first. If that probe already failed, do NOT retry ${gated.id} \u2014 use the INSTEAD from compounding lessons.`;
348643
+ abortIfNeeded(context2.signal);
348644
+ context2.sendEvent(sessionId, {
348645
+ messageId,
348646
+ type: "command_started",
348647
+ command,
348648
+ commandId: messageId,
348649
+ tabName: bestMatch.title || bestMatch.id,
348650
+ isNowait: false
348651
+ });
348652
+ context2.sendEvent(sessionId, {
348653
+ messageId,
348654
+ type: "command_finished",
348655
+ command,
348656
+ commandId: messageId,
348657
+ tabName: bestMatch.title || bestMatch.id,
348658
+ exitCode: -1,
348659
+ outputDelta: block
348660
+ });
348661
+ return block;
348662
+ }
347892
348663
  const allowed = await checkCommandPolicy(command, "run_command", context2);
347893
348664
  if (!allowed.allowed) {
347894
348665
  abortIfNeeded(context2.signal);
@@ -349304,7 +350075,7 @@ var manageWinrmConnectionSchema = external_exports.object({
349304
350075
  id: external_exports.string().optional().describe("ID for update/delete."),
349305
350076
  connection: winrmConnectionFieldsSchema.optional()
349306
350077
  });
349307
- function emit(context2, input, output) {
350078
+ function emit2(context2, input, output) {
349308
350079
  context2.sendEvent(context2.sessionId, {
349309
350080
  messageId: context2.messageId,
349310
350081
  type: "tool_call",
@@ -349342,7 +350113,7 @@ async function manageWinrmConnection(args, context2) {
349342
350113
  const cm = context2.connectionManager;
349343
350114
  if (!cm) {
349344
350115
  const msg2 = "Connection management is not available in this runtime (no connection manager wired).";
349345
- emit(context2, args, msg2);
350116
+ emit2(context2, args, msg2);
349346
350117
  return msg2;
349347
350118
  }
349348
350119
  const { action } = args;
@@ -349350,61 +350121,61 @@ async function manageWinrmConnection(args, context2) {
349350
350121
  const entries = cm.listWinrm();
349351
350122
  if (entries.length === 0) {
349352
350123
  const msg3 = 'No saved WinRM connections configured. Use action="create" to add one.';
349353
- emit(context2, args, msg3);
350124
+ emit2(context2, args, msg3);
349354
350125
  return msg3;
349355
350126
  }
349356
350127
  const msg2 = `Saved WinRM connections (${entries.length}):
349357
350128
  ${entries.map(summarize2).join("\n")}`;
349358
- emit(context2, args, msg2);
350129
+ emit2(context2, args, msg2);
349359
350130
  return msg2;
349360
350131
  }
349361
350132
  if (action === "create") {
349362
350133
  if (!args.connection) {
349363
350134
  const msg3 = "create requires a `connection` object with name, host, username, and password.";
349364
- emit(context2, args, msg3);
350135
+ emit2(context2, args, msg3);
349365
350136
  return msg3;
349366
350137
  }
349367
350138
  if (cm.listWinrm().some((e) => e.name === args.connection.name)) {
349368
350139
  const msg3 = `A saved WinRM connection named "${args.connection.name}" already exists. Choose a unique name or use action="update".`;
349369
- emit(context2, args, msg3);
350140
+ emit2(context2, args, msg3);
349370
350141
  return msg3;
349371
350142
  }
349372
350143
  const stored = cm.createWinrm(toEntry2(args.connection, randomId2()));
349373
350144
  const msg2 = `Created saved WinRM connection: ${summarize2(stored)}. Open a tab with open_terminal_tab using Name "${stored.name}", then run commands with exec_command (command/response mode).`;
349374
- emit(context2, args, msg2);
350145
+ emit2(context2, args, msg2);
349375
350146
  return msg2;
349376
350147
  }
349377
350148
  if (action === "update") {
349378
350149
  if (!args.id || !args.connection) {
349379
350150
  const msg3 = "update requires an `id` and a `connection` object with the fields to change.";
349380
- emit(context2, args, msg3);
350151
+ emit2(context2, args, msg3);
349381
350152
  return msg3;
349382
350153
  }
349383
350154
  const current = cm.listWinrm().find((e) => e.id === args.id);
349384
350155
  if (!current) {
349385
350156
  const msg3 = `No saved WinRM connection with id "${args.id}". Use action="list" to see valid ids.`;
349386
- emit(context2, args, msg3);
350157
+ emit2(context2, args, msg3);
349387
350158
  return msg3;
349388
350159
  }
349389
350160
  const merged = { ...current, ...toEntry2({ ...current, ...args.connection }, args.id) };
349390
350161
  const stored = cm.updateWinrm(merged);
349391
350162
  const msg2 = `Updated saved WinRM connection: ${summarize2(stored)}.`;
349392
- emit(context2, args, msg2);
350163
+ emit2(context2, args, msg2);
349393
350164
  return msg2;
349394
350165
  }
349395
350166
  if (action === "delete") {
349396
350167
  if (!args.id) {
349397
350168
  const msg3 = "delete requires an `id`.";
349398
- emit(context2, args, msg3);
350169
+ emit2(context2, args, msg3);
349399
350170
  return msg3;
349400
350171
  }
349401
350172
  const removed = cm.deleteWinrm(args.id);
349402
350173
  const msg2 = removed ? `Deleted saved WinRM connection id="${args.id}".` : `No saved WinRM connection with id="${args.id}" (nothing deleted).`;
349403
- emit(context2, args, msg2);
350174
+ emit2(context2, args, msg2);
349404
350175
  return msg2;
349405
350176
  }
349406
350177
  const msg = `Unknown action "${action}".`;
349407
- emit(context2, args, msg);
350178
+ emit2(context2, args, msg);
349408
350179
  return msg;
349409
350180
  }
349410
350181
 
@@ -349426,7 +350197,7 @@ var manageSerialConnectionSchema = external_exports.object({
349426
350197
  id: external_exports.string().optional(),
349427
350198
  connection: serialConnectionFieldsSchema.optional()
349428
350199
  });
349429
- function emit2(context2, input, output) {
350200
+ function emit3(context2, input, output) {
349430
350201
  context2.sendEvent(context2.sessionId, {
349431
350202
  messageId: context2.messageId,
349432
350203
  type: "tool_call",
@@ -349459,7 +350230,7 @@ async function manageSerialConnection(args, context2) {
349459
350230
  const cm = context2.connectionManager;
349460
350231
  if (!cm) {
349461
350232
  const msg2 = "Connection management is not available in this runtime (no connection manager wired).";
349462
- emit2(context2, args, msg2);
350233
+ emit3(context2, args, msg2);
349463
350234
  return msg2;
349464
350235
  }
349465
350236
  const { action } = args;
@@ -349467,61 +350238,61 @@ async function manageSerialConnection(args, context2) {
349467
350238
  const entries = cm.listSerial();
349468
350239
  if (!entries.length) {
349469
350240
  const msg3 = 'No saved serial connections configured. Use action="create" to add one.';
349470
- emit2(context2, args, msg3);
350241
+ emit3(context2, args, msg3);
349471
350242
  return msg3;
349472
350243
  }
349473
350244
  const msg2 = `Saved serial connections (${entries.length}):
349474
350245
  ${entries.map(summarize3).join("\n")}`;
349475
- emit2(context2, args, msg2);
350246
+ emit3(context2, args, msg2);
349476
350247
  return msg2;
349477
350248
  }
349478
350249
  if (action === "create") {
349479
350250
  if (!args.connection) {
349480
350251
  const msg3 = "create requires a `connection` object with name and path.";
349481
- emit2(context2, args, msg3);
350252
+ emit3(context2, args, msg3);
349482
350253
  return msg3;
349483
350254
  }
349484
350255
  if (cm.listSerial().some((e) => e.name === args.connection.name)) {
349485
350256
  const msg3 = `A saved serial connection named "${args.connection.name}" already exists. Choose a unique name or use action="update".`;
349486
- emit2(context2, args, msg3);
350257
+ emit3(context2, args, msg3);
349487
350258
  return msg3;
349488
350259
  }
349489
350260
  const stored = cm.createSerial(toEntry3(args.connection, randomId3()));
349490
350261
  const msg2 = `Created saved serial connection: ${summarize3(stored)}. Open a tab with open_terminal_tab using Name "${stored.name}", then interact with write_stdin / read_terminal_tab.`;
349491
- emit2(context2, args, msg2);
350262
+ emit3(context2, args, msg2);
349492
350263
  return msg2;
349493
350264
  }
349494
350265
  if (action === "update") {
349495
350266
  if (!args.id || !args.connection) {
349496
350267
  const msg3 = "update requires an `id` and a `connection` object with the fields to change.";
349497
- emit2(context2, args, msg3);
350268
+ emit3(context2, args, msg3);
349498
350269
  return msg3;
349499
350270
  }
349500
350271
  const current = cm.listSerial().find((e) => e.id === args.id);
349501
350272
  if (!current) {
349502
350273
  const msg3 = `No saved serial connection with id "${args.id}". Use action="list" to see valid ids.`;
349503
- emit2(context2, args, msg3);
350274
+ emit3(context2, args, msg3);
349504
350275
  return msg3;
349505
350276
  }
349506
350277
  const merged = { ...current, ...toEntry3({ ...current, ...args.connection }, args.id) };
349507
350278
  const stored = cm.updateSerial(merged);
349508
350279
  const msg2 = `Updated saved serial connection: ${summarize3(stored)}.`;
349509
- emit2(context2, args, msg2);
350280
+ emit3(context2, args, msg2);
349510
350281
  return msg2;
349511
350282
  }
349512
350283
  if (action === "delete") {
349513
350284
  if (!args.id) {
349514
350285
  const msg3 = "delete requires an `id`.";
349515
- emit2(context2, args, msg3);
350286
+ emit3(context2, args, msg3);
349516
350287
  return msg3;
349517
350288
  }
349518
350289
  const removed = cm.deleteSerial(args.id);
349519
350290
  const msg2 = removed ? `Deleted saved serial connection id="${args.id}".` : `No saved serial connection with id="${args.id}" (nothing deleted).`;
349520
- emit2(context2, args, msg2);
350291
+ emit3(context2, args, msg2);
349521
350292
  return msg2;
349522
350293
  }
349523
350294
  const msg = `Unknown action "${action}".`;
349524
- emit2(context2, args, msg);
350295
+ emit3(context2, args, msg);
349525
350296
  return msg;
349526
350297
  }
349527
350298
 
@@ -349542,7 +350313,7 @@ var searchSessionLogsSchema = external_exports.object({
349542
350313
  maxMatches: external_exports.number().int().min(1).max(500).optional().describe("Max matching lines to return (default 50)."),
349543
350314
  contextLines: external_exports.number().int().min(0).max(20).optional().describe("Lines of surrounding context per match (default 0).")
349544
350315
  });
349545
- function emit3(context2, toolName, input, output) {
350316
+ function emit4(context2, toolName, input, output) {
349546
350317
  context2.sendEvent(context2.sessionId, {
349547
350318
  messageId: context2.messageId,
349548
350319
  type: "tool_call",
@@ -349555,32 +350326,32 @@ async function listSessionLogs(args, context2) {
349555
350326
  const logger = context2.sessionLogger;
349556
350327
  if (!logger) {
349557
350328
  const msg2 = "Session logging is not available in this runtime (no session logger wired; enable sessionLogging.enabled in settings).";
349558
- emit3(context2, "list_session_logs", args, msg2);
350329
+ emit4(context2, "list_session_logs", args, msg2);
349559
350330
  return msg2;
349560
350331
  }
349561
350332
  const list = logger.list();
349562
350333
  if (!list.length) {
349563
350334
  const msg2 = "No recorded sessions yet. Sessions are recorded when sessionLogging is enabled and you open a terminal tab.";
349564
- emit3(context2, "list_session_logs", args, msg2);
350335
+ emit4(context2, "list_session_logs", args, msg2);
349565
350336
  return msg2;
349566
350337
  }
349567
350338
  const body = list.map((l) => `- ${l.title} (sessionId=${l.sessionId}, type=${l.type}, started=${l.startedAt}${l.endedAt ? `, ended=${l.endedAt}` : ""}, ${l.bytes} bytes)`).join("\n");
349568
350339
  const msg = `Recorded sessions (${list.length}):
349569
350340
  ${body}`;
349570
- emit3(context2, "list_session_logs", args, msg);
350341
+ emit4(context2, "list_session_logs", args, msg);
349571
350342
  return msg;
349572
350343
  }
349573
350344
  async function readSessionLog(args, context2) {
349574
350345
  const logger = context2.sessionLogger;
349575
350346
  if (!logger) {
349576
350347
  const msg2 = "Session logging is not available in this runtime (no session logger wired; enable sessionLogging.enabled in settings).";
349577
- emit3(context2, "read_session_log", args, msg2);
350348
+ emit4(context2, "read_session_log", args, msg2);
349578
350349
  return msg2;
349579
350350
  }
349580
350351
  const content = logger.read(args.sessionId);
349581
350352
  if (!content) {
349582
350353
  const msg2 = `No recorded log for sessionId="${args.sessionId}". Use list_session_logs to see valid ids.`;
349583
- emit3(context2, "read_session_log", args, msg2);
350354
+ emit4(context2, "read_session_log", args, msg2);
349584
350355
  return msg2;
349585
350356
  }
349586
350357
  const truncated = content.length > 8e3 ? `${content.slice(0, 4e3)}
@@ -349590,14 +350361,14 @@ ${content.slice(-4e3)}` : content;
349590
350361
  <session_log>
349591
350362
  ${truncated}
349592
350363
  </session_log>`;
349593
- emit3(context2, "read_session_log", args, msg);
350364
+ emit4(context2, "read_session_log", args, msg);
349594
350365
  return msg;
349595
350366
  }
349596
350367
  async function searchSessionLogs(args, context2) {
349597
350368
  const logger = context2.sessionLogger;
349598
350369
  if (!logger || typeof logger.search !== "function") {
349599
350370
  const msg2 = "Session logging is not available in this runtime (no session logger wired; enable sessionLogging.enabled in settings).";
349600
- emit3(context2, "search_session_logs", args, msg2);
350371
+ emit4(context2, "search_session_logs", args, msg2);
349601
350372
  return msg2;
349602
350373
  }
349603
350374
  const result = logger.search(args.query, {
@@ -349612,7 +350383,7 @@ async function searchSessionLogs(args, context2) {
349612
350383
  });
349613
350384
  if (result.totalMatches === 0) {
349614
350385
  const msg2 = `No matches for "${args.query}" across ${result.sessionsSearched} recorded session(s).`;
349615
- emit3(context2, "search_session_logs", args, msg2);
350386
+ emit4(context2, "search_session_logs", args, msg2);
349616
350387
  return msg2;
349617
350388
  }
349618
350389
  const lines = result.matches.map((m2) => {
@@ -349626,7 +350397,7 @@ ${ctx}`;
349626
350397
  });
349627
350398
  const msg = `Found ${result.totalMatches} match(es) for "${args.query}" across ${result.sessionsSearched} session(s):
349628
350399
  ${lines.join("\n")}`;
349629
- emit3(context2, "search_session_logs", args, msg);
350400
+ emit4(context2, "search_session_logs", args, msg);
349630
350401
  return msg;
349631
350402
  }
349632
350403
 
@@ -349640,7 +350411,7 @@ var getRunLedgerSchema = external_exports.object({
349640
350411
  limit: external_exports.number().int().min(1).max(200).optional().describe("Max runs for 'list' (default 20)."),
349641
350412
  sinceDays: external_exports.number().min(0).max(365).optional().describe("Optional: 'summary' only counts runs started within the last N days (default: all time).")
349642
350413
  });
349643
- function emit4(context2, toolName, input, output) {
350414
+ function emit5(context2, toolName, input, output) {
349644
350415
  context2.sendEvent(context2.sessionId, {
349645
350416
  messageId: context2.messageId,
349646
350417
  type: "tool_call",
@@ -349664,19 +350435,19 @@ async function getRunLedger(args, context2) {
349664
350435
  const ledger = context2.agentRunLedger;
349665
350436
  if (!ledger) {
349666
350437
  const msg2 = "Run ledger is not available in this runtime (no agent run ledger wired).";
349667
- emit4(context2, "get_run_ledger", args, msg2);
350438
+ emit5(context2, "get_run_ledger", args, msg2);
349668
350439
  return msg2;
349669
350440
  }
349670
350441
  if (args.action === "list") {
349671
350442
  const runs = ledger.listRuns({ limit: args.limit ?? 20, sessionId: args.sessionId, status: args.status });
349672
350443
  if (!runs.length) {
349673
350444
  const msg3 = "No agent runs recorded yet in the ledger.";
349674
- emit4(context2, "get_run_ledger", args, msg3);
350445
+ emit5(context2, "get_run_ledger", args, msg3);
349675
350446
  return msg3;
349676
350447
  }
349677
350448
  const msg2 = `Agent run ledger \u2014 ${runs.length} most recent run(s):
349678
350449
  ${runs.map(fmtRun).join("\n")}`;
349679
- emit4(context2, "get_run_ledger", args, msg2);
350450
+ emit5(context2, "get_run_ledger", args, msg2);
349680
350451
  return msg2;
349681
350452
  }
349682
350453
  if (args.action === "summary") {
@@ -349691,18 +350462,18 @@ ${runs.map(fmtRun).join("\n")}`;
349691
350462
  ` by model:`,
349692
350463
  models
349693
350464
  ].join("\n");
349694
- emit4(context2, "get_run_ledger", args, msg2);
350465
+ emit5(context2, "get_run_ledger", args, msg2);
349695
350466
  return msg2;
349696
350467
  }
349697
350468
  if (!args.runId) {
349698
350469
  const msg2 = "runId is required for action='get'. Use action='list' to find run ids.";
349699
- emit4(context2, "get_run_ledger", args, msg2);
350470
+ emit5(context2, "get_run_ledger", args, msg2);
349700
350471
  return msg2;
349701
350472
  }
349702
350473
  const got = ledger.getRun(args.runId);
349703
350474
  if (!got) {
349704
350475
  const msg2 = `No run with id "${args.runId}" in the ledger.`;
349705
- emit4(context2, "get_run_ledger", args, msg2);
350476
+ emit5(context2, "get_run_ledger", args, msg2);
349706
350477
  return msg2;
349707
350478
  }
349708
350479
  const usage = got.usage.length ? got.usage.map((u) => ` - ${new Date(u.at).toISOString()} model=${u.model ?? "?"} ${u.promptTokens} in / ${u.completionTokens} out${u.totalTokens ? ` (context=${u.totalTokens})` : ""}`).join("\n") : " (no usage events)";
@@ -349710,7 +350481,7 @@ ${runs.map(fmtRun).join("\n")}`;
349710
350481
  ${fmtRun(got.run)}
349711
350482
  usage events:
349712
350483
  ${usage}`;
349713
- emit4(context2, "get_run_ledger", args, msg);
350484
+ emit5(context2, "get_run_ledger", args, msg);
349714
350485
  return msg;
349715
350486
  }
349716
350487
 
@@ -350562,7 +351333,7 @@ function importPuttyReg(content, opts) {
350562
351333
  }
350563
351334
 
350564
351335
  // ../../packages/backend/src/services/AgentHelper/tools/automation_tools.ts
350565
- function emit5(context2, _toolName, input, output) {
351336
+ function emit6(context2, _toolName, input, output) {
350566
351337
  context2.sendEvent(context2.sessionId, {
350567
351338
  messageId: context2.messageId,
350568
351339
  type: "tool_call",
@@ -350589,7 +351360,7 @@ async function manageDeviceMemory(args, context2) {
350589
351360
  const m2 = context2.automationManager;
350590
351361
  if (!m2) {
350591
351362
  const msg2 = noStore();
350592
- emit5(context2, "manage_device_memory", args, msg2);
351363
+ emit6(context2, "manage_device_memory", args, msg2);
350593
351364
  return msg2;
350594
351365
  }
350595
351366
  const { action } = args;
@@ -350597,25 +351368,25 @@ async function manageDeviceMemory(args, context2) {
350597
351368
  const all = m2.listDeviceMemory();
350598
351369
  if (!all.length) {
350599
351370
  const msg3 = "No device memory entries.";
350600
- emit5(context2, "manage_device_memory", args, msg3);
351371
+ emit6(context2, "manage_device_memory", args, msg3);
350601
351372
  return msg3;
350602
351373
  }
350603
351374
  const body = all.map((e) => `${e.host} (role=${e.role || "unspecified"}, ${e.incidents.length} incident(s))`).join("\n");
350604
351375
  const msg2 = `Device memory (${all.length}):
350605
351376
  ${body}`;
350606
- emit5(context2, "manage_device_memory", args, msg2);
351377
+ emit6(context2, "manage_device_memory", args, msg2);
350607
351378
  return msg2;
350608
351379
  }
350609
351380
  if (!args.host) {
350610
351381
  const msg2 = `action="${action}" requires a host.`;
350611
- emit5(context2, "manage_device_memory", args, msg2);
351382
+ emit6(context2, "manage_device_memory", args, msg2);
350612
351383
  return msg2;
350613
351384
  }
350614
351385
  if (action === "get") {
350615
351386
  const mem = m2.getDeviceMemory(args.host);
350616
351387
  if (!mem) {
350617
351388
  const msg3 = `No device memory for host "${args.host}".`;
350618
- emit5(context2, "manage_device_memory", args, msg3);
351389
+ emit6(context2, "manage_device_memory", args, msg3);
350619
351390
  return msg3;
350620
351391
  }
350621
351392
  const msg2 = `Device memory for ${args.host}:
@@ -350623,18 +351394,18 @@ role: ${mem.role || "unspecified"}
350623
351394
  standing instructions: ${mem.standingInstructions || "(none)"}
350624
351395
  incidents (${mem.incidents.length}):
350625
351396
  ${mem.incidents.map((i) => `- [${i.at}] ${i.summary}${i.ticketId ? ` (ticket: ${i.ticketId})` : ""}${i.resolution ? ` \u2014 ${i.resolution}` : ""}`).join("\n")}`;
350626
- emit5(context2, "manage_device_memory", args, msg2);
351397
+ emit6(context2, "manage_device_memory", args, msg2);
350627
351398
  return msg2;
350628
351399
  }
350629
351400
  if (action === "add_incident") {
350630
351401
  if (!args.incident) {
350631
351402
  const msg3 = "add_incident requires an `incident` object.";
350632
- emit5(context2, "manage_device_memory", args, msg3);
351403
+ emit6(context2, "manage_device_memory", args, msg3);
350633
351404
  return msg3;
350634
351405
  }
350635
351406
  const inc = m2.addIncident(args.host, args.incident);
350636
351407
  const msg2 = `Recorded incident for ${args.host} at ${inc.at}: ${inc.summary}.`;
350637
- emit5(context2, "manage_device_memory", args, msg2);
351408
+ emit6(context2, "manage_device_memory", args, msg2);
350638
351409
  return msg2;
350639
351410
  }
350640
351411
  if (action === "upsert") {
@@ -350645,17 +351416,17 @@ ${mem.incidents.map((i) => `- [${i.at}] ${i.summary}${i.ticketId ? ` (ticket: ${
350645
351416
  incidents: []
350646
351417
  });
350647
351418
  const msg2 = `Saved device memory for ${mem.host} (role=${mem.role || "unspecified"}).`;
350648
- emit5(context2, "manage_device_memory", args, msg2);
351419
+ emit6(context2, "manage_device_memory", args, msg2);
350649
351420
  return msg2;
350650
351421
  }
350651
351422
  if (action === "delete") {
350652
351423
  const removed = m2.deleteDeviceMemory(args.host);
350653
351424
  const msg2 = removed ? `Deleted device memory for ${args.host}.` : `No device memory for ${args.host}.`;
350654
- emit5(context2, "manage_device_memory", args, msg2);
351425
+ emit6(context2, "manage_device_memory", args, msg2);
350655
351426
  return msg2;
350656
351427
  }
350657
351428
  const msg = `Unknown action "${action}".`;
350658
- emit5(context2, "manage_device_memory", args, msg);
351429
+ emit6(context2, "manage_device_memory", args, msg);
350659
351430
  return msg;
350660
351431
  }
350661
351432
  var manageScriptSchema = external_exports.object({
@@ -350671,7 +351442,7 @@ async function manageScript(args, context2) {
350671
351442
  const m2 = context2.automationManager;
350672
351443
  if (!m2) {
350673
351444
  const msg2 = noStore();
350674
- emit5(context2, "manage_script", args, msg2);
351445
+ emit6(context2, "manage_script", args, msg2);
350675
351446
  return msg2;
350676
351447
  }
350677
351448
  const { action } = args;
@@ -350679,56 +351450,56 @@ async function manageScript(args, context2) {
350679
351450
  const all = m2.listScripts();
350680
351451
  if (!all.length) {
350681
351452
  const msg3 = "No saved scripts.";
350682
- emit5(context2, "manage_script", args, msg3);
351453
+ emit6(context2, "manage_script", args, msg3);
350683
351454
  return msg3;
350684
351455
  }
350685
351456
  const body = all.map((s) => `- ${s.name} (id=${s.id}): ${s.command.split("\n")[0].slice(0, 60)}${s.command.length > 60 ? "\u2026" : ""}`).join("\n");
350686
351457
  const msg2 = `Saved scripts (${all.length}):
350687
351458
  ${body}`;
350688
- emit5(context2, "manage_script", args, msg2);
351459
+ emit6(context2, "manage_script", args, msg2);
350689
351460
  return msg2;
350690
351461
  }
350691
351462
  if (action === "create") {
350692
351463
  if (!args.name || !args.command) {
350693
351464
  const msg3 = "create requires name + command.";
350694
- emit5(context2, "manage_script", args, msg3);
351465
+ emit6(context2, "manage_script", args, msg3);
350695
351466
  return msg3;
350696
351467
  }
350697
351468
  const s = m2.createScript({ name: args.name, command: args.command, description: args.description, targets: args.targets, tags: args.tags });
350698
351469
  const msg2 = `Created script "${s.name}" (id=${s.id}). Run it on open tabs with run_fleet_command or exec_command using its command body.`;
350699
- emit5(context2, "manage_script", args, msg2);
351470
+ emit6(context2, "manage_script", args, msg2);
350700
351471
  return msg2;
350701
351472
  }
350702
351473
  if (action === "update") {
350703
351474
  if (!args.id) {
350704
351475
  const msg3 = "update requires id.";
350705
- emit5(context2, "manage_script", args, msg3);
351476
+ emit6(context2, "manage_script", args, msg3);
350706
351477
  return msg3;
350707
351478
  }
350708
351479
  const existing = m2.listScripts().find((s2) => s2.id === args.id);
350709
351480
  if (!existing) {
350710
351481
  const msg3 = `No script with id="${args.id}".`;
350711
- emit5(context2, "manage_script", args, msg3);
351482
+ emit6(context2, "manage_script", args, msg3);
350712
351483
  return msg3;
350713
351484
  }
350714
351485
  const s = m2.updateScript({ ...existing, name: args.name ?? existing.name, command: args.command ?? existing.command, description: args.description ?? existing.description, targets: args.targets ?? existing.targets, tags: args.tags ?? existing.tags });
350715
351486
  const msg2 = `Updated script "${s.name}".`;
350716
- emit5(context2, "manage_script", args, msg2);
351487
+ emit6(context2, "manage_script", args, msg2);
350717
351488
  return msg2;
350718
351489
  }
350719
351490
  if (action === "delete") {
350720
351491
  if (!args.id) {
350721
351492
  const msg3 = "delete requires id.";
350722
- emit5(context2, "manage_script", args, msg3);
351493
+ emit6(context2, "manage_script", args, msg3);
350723
351494
  return msg3;
350724
351495
  }
350725
351496
  const removed = m2.deleteScript(args.id);
350726
351497
  const msg2 = removed ? `Deleted script ${args.id}.` : `No script ${args.id}.`;
350727
- emit5(context2, "manage_script", args, msg2);
351498
+ emit6(context2, "manage_script", args, msg2);
350728
351499
  return msg2;
350729
351500
  }
350730
351501
  const msg = `Unknown action "${action}".`;
350731
- emit5(context2, "manage_script", args, msg);
351502
+ emit6(context2, "manage_script", args, msg);
350732
351503
  return msg;
350733
351504
  }
350734
351505
  var manageGroupSchema = external_exports.object({
@@ -350741,7 +351512,7 @@ async function manageGroup(args, context2) {
350741
351512
  const m2 = context2.automationManager;
350742
351513
  if (!m2) {
350743
351514
  const msg2 = noStore();
350744
- emit5(context2, "manage_group", args, msg2);
351515
+ emit6(context2, "manage_group", args, msg2);
350745
351516
  return msg2;
350746
351517
  }
350747
351518
  const { action } = args;
@@ -350749,49 +351520,49 @@ async function manageGroup(args, context2) {
350749
351520
  const all = m2.listGroups();
350750
351521
  if (!all.length) {
350751
351522
  const msg3 = "No groups.";
350752
- emit5(context2, "manage_group", args, msg3);
351523
+ emit6(context2, "manage_group", args, msg3);
350753
351524
  return msg3;
350754
351525
  }
350755
351526
  const msg2 = `Groups (${all.length}):
350756
351527
  ${all.map((g) => `- ${g.name} (id=${g.id}${g.parentId ? `, parent=${g.parentId}` : ""})`).join("\n")}`;
350757
- emit5(context2, "manage_group", args, msg2);
351528
+ emit6(context2, "manage_group", args, msg2);
350758
351529
  return msg2;
350759
351530
  }
350760
351531
  if (action === "create") {
350761
351532
  if (!args.name) {
350762
351533
  const msg3 = "create requires name.";
350763
- emit5(context2, "manage_group", args, msg3);
351534
+ emit6(context2, "manage_group", args, msg3);
350764
351535
  return msg3;
350765
351536
  }
350766
351537
  const g = m2.createGroup(args.name, args.parentId ?? null);
350767
351538
  const msg2 = `Created group "${g.name}" (id=${g.id}). Assign a connection by setting its groupId via manage_ssh_connection.update or the Connections panel.`;
350768
- emit5(context2, "manage_group", args, msg2);
351539
+ emit6(context2, "manage_group", args, msg2);
350769
351540
  return msg2;
350770
351541
  }
350771
351542
  if (action === "update") {
350772
351543
  if (!args.id) {
350773
351544
  const msg3 = "update requires id.";
350774
- emit5(context2, "manage_group", args, msg3);
351545
+ emit6(context2, "manage_group", args, msg3);
350775
351546
  return msg3;
350776
351547
  }
350777
351548
  const g = m2.updateGroup({ id: args.id, name: args.name ?? "", parentId: args.parentId });
350778
351549
  const msg2 = `Updated group "${g.name}".`;
350779
- emit5(context2, "manage_group", args, msg2);
351550
+ emit6(context2, "manage_group", args, msg2);
350780
351551
  return msg2;
350781
351552
  }
350782
351553
  if (action === "delete") {
350783
351554
  if (!args.id) {
350784
351555
  const msg3 = "delete requires id.";
350785
- emit5(context2, "manage_group", args, msg3);
351556
+ emit6(context2, "manage_group", args, msg3);
350786
351557
  return msg3;
350787
351558
  }
350788
351559
  const removed = m2.deleteGroup(args.id);
350789
351560
  const msg2 = removed ? `Deleted group ${args.id} (children reparented to root).` : `No group ${args.id}.`;
350790
- emit5(context2, "manage_group", args, msg2);
351561
+ emit6(context2, "manage_group", args, msg2);
350791
351562
  return msg2;
350792
351563
  }
350793
351564
  const msg = `Unknown action "${action}".`;
350794
- emit5(context2, "manage_group", args, msg);
351565
+ emit6(context2, "manage_group", args, msg);
350795
351566
  return msg;
350796
351567
  }
350797
351568
  var manageScheduledTaskSchema = external_exports.object({
@@ -350821,7 +351592,7 @@ async function manageScheduledTask(args, context2) {
350821
351592
  const m2 = context2.automationManager;
350822
351593
  if (!m2) {
350823
351594
  const msg2 = noStore();
350824
- emit5(context2, "manage_scheduled_task", args, msg2);
351595
+ emit6(context2, "manage_scheduled_task", args, msg2);
350825
351596
  return msg2;
350826
351597
  }
350827
351598
  const { action } = args;
@@ -350829,30 +351600,30 @@ async function manageScheduledTask(args, context2) {
350829
351600
  const all = m2.listScheduledTasks();
350830
351601
  if (!all.length) {
350831
351602
  const msg3 = "No scheduled tasks.";
350832
- emit5(context2, "manage_scheduled_task", args, msg3);
351603
+ emit6(context2, "manage_scheduled_task", args, msg3);
350833
351604
  return msg3;
350834
351605
  }
350835
351606
  const msg2 = `Scheduled tasks (${all.length}):
350836
351607
  ${all.map((t) => `- ${t.name} (id=${t.id}, cron="${t.cron}", enabled=${t.enabled}${t.lastRunAt ? `, lastRun=${t.lastRunAt}` : ""})`).join("\n")}`;
350837
- emit5(context2, "manage_scheduled_task", args, msg2);
351608
+ emit6(context2, "manage_scheduled_task", args, msg2);
350838
351609
  return msg2;
350839
351610
  }
350840
351611
  if (action === "create") {
350841
351612
  if (!args.name || !args.cron) {
350842
351613
  const msg3 = "create requires name + cron.";
350843
- emit5(context2, "manage_scheduled_task", args, msg3);
351614
+ emit6(context2, "manage_scheduled_task", args, msg3);
350844
351615
  return msg3;
350845
351616
  }
350846
351617
  if (!args.scriptId && !args.command && !args.playbookId) {
350847
351618
  const msg3 = "create requires scriptId, command, or playbookId.";
350848
- emit5(context2, "manage_scheduled_task", args, msg3);
351619
+ emit6(context2, "manage_scheduled_task", args, msg3);
350849
351620
  return msg3;
350850
351621
  }
350851
351622
  const { validateCron: validateCron2 } = await Promise.resolve().then(() => (init_schedulerService(), schedulerService_exports));
350852
351623
  const v = validateCron2(args.cron);
350853
351624
  if (!v.ok) {
350854
351625
  const msg3 = `Invalid cron "${args.cron}": ${v.reason}`;
350855
- emit5(context2, "manage_scheduled_task", args, msg3);
351626
+ emit6(context2, "manage_scheduled_task", args, msg3);
350856
351627
  return msg3;
350857
351628
  }
350858
351629
  const t = m2.createScheduledTask({
@@ -350876,47 +351647,47 @@ ${all.map((t) => `- ${t.name} (id=${t.id}, cron="${t.cron}", enabled=${t.enabled
350876
351647
  alertAfterFailures: args.alertAfterFailures
350877
351648
  });
350878
351649
  const msg2 = `Created scheduled task "${t.name}" (id=${t.id}, cron="${t.cron}"${args.timezone ? ` @ ${args.timezone}` : ""}). It will be evaluated by the local scheduler.`;
350879
- emit5(context2, "manage_scheduled_task", args, msg2);
351650
+ emit6(context2, "manage_scheduled_task", args, msg2);
350880
351651
  return msg2;
350881
351652
  }
350882
351653
  if (action === "update") {
350883
351654
  if (!args.id) {
350884
351655
  const msg3 = "update requires id.";
350885
- emit5(context2, "manage_scheduled_task", args, msg3);
351656
+ emit6(context2, "manage_scheduled_task", args, msg3);
350886
351657
  return msg3;
350887
351658
  }
350888
351659
  const existing = m2.listScheduledTasks().find((t2) => t2.id === args.id);
350889
351660
  if (!existing) {
350890
351661
  const msg3 = `No task ${args.id}.`;
350891
- emit5(context2, "manage_scheduled_task", args, msg3);
351662
+ emit6(context2, "manage_scheduled_task", args, msg3);
350892
351663
  return msg3;
350893
351664
  }
350894
351665
  const t = m2.updateScheduledTask({ ...existing, name: args.name ?? existing.name, cron: args.cron ?? existing.cron, scriptId: args.scriptId ?? existing.scriptId, command: args.command ?? existing.command, enabled: args.enabled ?? existing.enabled, groupId: args.groupId, tags: args.tags, targets: args.targets });
350895
351666
  const msg2 = `Updated task "${t.name}".`;
350896
- emit5(context2, "manage_scheduled_task", args, msg2);
351667
+ emit6(context2, "manage_scheduled_task", args, msg2);
350897
351668
  return msg2;
350898
351669
  }
350899
351670
  if (action === "delete") {
350900
351671
  if (!args.id) {
350901
351672
  const msg3 = "delete requires id.";
350902
- emit5(context2, "manage_scheduled_task", args, msg3);
351673
+ emit6(context2, "manage_scheduled_task", args, msg3);
350903
351674
  return msg3;
350904
351675
  }
350905
351676
  const removed = m2.deleteScheduledTask(args.id);
350906
351677
  const msg2 = removed ? `Deleted task ${args.id}.` : `No task ${args.id}.`;
350907
- emit5(context2, "manage_scheduled_task", args, msg2);
351678
+ emit6(context2, "manage_scheduled_task", args, msg2);
350908
351679
  return msg2;
350909
351680
  }
350910
351681
  if (action === "validate") {
350911
351682
  if (!args.cron) {
350912
351683
  const msg3 = "validate requires cron.";
350913
- emit5(context2, "manage_scheduled_task", args, msg3);
351684
+ emit6(context2, "manage_scheduled_task", args, msg3);
350914
351685
  return msg3;
350915
351686
  }
350916
351687
  const { validateCron: validateCron2 } = await Promise.resolve().then(() => (init_schedulerService(), schedulerService_exports));
350917
351688
  const v = validateCron2(args.cron);
350918
351689
  const msg2 = v.ok ? `Cron "${args.cron}" is valid.` : `Invalid cron "${args.cron}": ${v.reason}`;
350919
- emit5(context2, "manage_scheduled_task", args, msg2);
351690
+ emit6(context2, "manage_scheduled_task", args, msg2);
350920
351691
  return msg2;
350921
351692
  }
350922
351693
  if (action === "drift") {
@@ -350925,20 +351696,20 @@ ${all.map((t) => `- ${t.name} (id=${t.id}, cron="${t.cron}", enabled=${t.enabled
350925
351696
  const flagged = drift.filter((d) => d.drifted);
350926
351697
  const msg2 = flagged.length === 0 ? `No drift detected across ${drift.length} enabled task(s).` : `Drifted task(s) (${flagged.length}):
350927
351698
  ${flagged.map((d) => `- ${d.taskName} (id=${d.taskId}): ${Number.isFinite(d.minutesSinceLastRun) ? `${Math.round(d.minutesSinceLastRun)} min since last run` : "never ran"} vs expected \u2264${d.expectedIntervalMinutes} min`).join("\n")}`;
350928
- emit5(context2, "manage_scheduled_task", args, msg2);
351699
+ emit6(context2, "manage_scheduled_task", args, msg2);
350929
351700
  return msg2;
350930
351701
  }
350931
351702
  if (action === "history") {
350932
351703
  const sched = context2.scheduledTaskHistory;
350933
351704
  if (!sched) {
350934
351705
  const msg3 = "Run history is not available in this runtime (headless daemon exposes it via the gateway).";
350935
- emit5(context2, "manage_scheduled_task", args, msg3);
351706
+ emit6(context2, "manage_scheduled_task", args, msg3);
350936
351707
  return msg3;
350937
351708
  }
350938
351709
  const tasks = args.id ? m2.listScheduledTasks().filter((t) => t.id === args.id) : m2.listScheduledTasks();
350939
351710
  if (tasks.length === 0) {
350940
351711
  const msg3 = args.id ? `No task ${args.id}.` : "No scheduled tasks.";
350941
- emit5(context2, "manage_scheduled_task", args, msg3);
351712
+ emit6(context2, "manage_scheduled_task", args, msg3);
350942
351713
  return msg3;
350943
351714
  }
350944
351715
  const lines = tasks.map((t) => {
@@ -350951,34 +351722,34 @@ ${flagged.map((d) => `- ${d.taskName} (id=${d.taskId}): ${Number.isFinite(d.minu
350951
351722
  });
350952
351723
  const msg2 = `Scheduled task history:
350953
351724
  ${lines.join("\n")}`;
350954
- emit5(context2, "manage_scheduled_task", args, msg2);
351725
+ emit6(context2, "manage_scheduled_task", args, msg2);
350955
351726
  return msg2;
350956
351727
  }
350957
351728
  if (action === "runNow") {
350958
351729
  if (!args.id) {
350959
351730
  const msg3 = "runNow requires id.";
350960
- emit5(context2, "manage_scheduled_task", args, msg3);
351731
+ emit6(context2, "manage_scheduled_task", args, msg3);
350961
351732
  return msg3;
350962
351733
  }
350963
351734
  const task2 = m2.listScheduledTasks().find((t) => t.id === args.id);
350964
351735
  if (!task2) {
350965
351736
  const msg3 = `No task ${args.id}.`;
350966
- emit5(context2, "manage_scheduled_task", args, msg3);
351737
+ emit6(context2, "manage_scheduled_task", args, msg3);
350967
351738
  return msg3;
350968
351739
  }
350969
351740
  const sched = context2.scheduledTaskRunner;
350970
351741
  if (!sched) {
350971
351742
  const msg3 = "Run-now is not available in this runtime.";
350972
- emit5(context2, "manage_scheduled_task", args, msg3);
351743
+ emit6(context2, "manage_scheduled_task", args, msg3);
350973
351744
  return msg3;
350974
351745
  }
350975
351746
  const r = await sched(task2);
350976
351747
  const msg2 = r.ran ? `Task "${task2.name}" executed now.` : `Task "${task2.name}" not run: ${r.reason}.`;
350977
- emit5(context2, "manage_scheduled_task", args, msg2);
351748
+ emit6(context2, "manage_scheduled_task", args, msg2);
350978
351749
  return msg2;
350979
351750
  }
350980
351751
  const msg = `Unknown action "${action}".`;
350981
- emit5(context2, "manage_scheduled_task", args, msg);
351752
+ emit6(context2, "manage_scheduled_task", args, msg);
350982
351753
  return msg;
350983
351754
  }
350984
351755
  var manageTemplateSchema = external_exports.object({
@@ -350994,7 +351765,7 @@ async function manageTemplate(args, context2) {
350994
351765
  const m2 = context2.automationManager;
350995
351766
  if (!m2) {
350996
351767
  const msg2 = noStore();
350997
- emit5(context2, "manage_template", args, msg2);
351768
+ emit6(context2, "manage_template", args, msg2);
350998
351769
  return msg2;
350999
351770
  }
351000
351771
  const { action } = args;
@@ -351002,57 +351773,57 @@ async function manageTemplate(args, context2) {
351002
351773
  const all = m2.listTemplates();
351003
351774
  if (!all.length) {
351004
351775
  const msg3 = "No templates.";
351005
- emit5(context2, "manage_template", args, msg3);
351776
+ emit6(context2, "manage_template", args, msg3);
351006
351777
  return msg3;
351007
351778
  }
351008
351779
  const msg2 = `Templates (${all.length}):
351009
351780
  ${all.map((t) => `- ${t.name} (id=${t.id}, ${t.versions.length} version(s))`).join("\n")}`;
351010
- emit5(context2, "manage_template", args, msg2);
351781
+ emit6(context2, "manage_template", args, msg2);
351011
351782
  return msg2;
351012
351783
  }
351013
351784
  if (action === "create") {
351014
351785
  if (!args.name || !args.body) {
351015
351786
  const msg3 = "create requires name + body.";
351016
- emit5(context2, "manage_template", args, msg3);
351787
+ emit6(context2, "manage_template", args, msg3);
351017
351788
  return msg3;
351018
351789
  }
351019
351790
  const t = m2.createTemplate({ name: args.name, body: args.body, variables: args.variables ?? [] });
351020
351791
  const msg2 = `Created template "${t.name}" (id=${t.id}). Use action="render" to preview, action="version" to save a rendered version.`;
351021
- emit5(context2, "manage_template", args, msg2);
351792
+ emit6(context2, "manage_template", args, msg2);
351022
351793
  return msg2;
351023
351794
  }
351024
351795
  if (action === "update") {
351025
351796
  if (!args.id) {
351026
351797
  const msg3 = "update requires id.";
351027
- emit5(context2, "manage_template", args, msg3);
351798
+ emit6(context2, "manage_template", args, msg3);
351028
351799
  return msg3;
351029
351800
  }
351030
351801
  const t = m2.updateTemplate({ id: args.id, name: args.name, body: args.body, variables: args.variables });
351031
351802
  const msg2 = `Updated template "${t.name}".`;
351032
- emit5(context2, "manage_template", args, msg2);
351803
+ emit6(context2, "manage_template", args, msg2);
351033
351804
  return msg2;
351034
351805
  }
351035
351806
  if (action === "delete") {
351036
351807
  if (!args.id) {
351037
351808
  const msg3 = "delete requires id.";
351038
- emit5(context2, "manage_template", args, msg3);
351809
+ emit6(context2, "manage_template", args, msg3);
351039
351810
  return msg3;
351040
351811
  }
351041
351812
  const removed = m2.deleteTemplate(args.id);
351042
351813
  const msg2 = removed ? `Deleted template ${args.id}.` : `No template ${args.id}.`;
351043
- emit5(context2, "manage_template", args, msg2);
351814
+ emit6(context2, "manage_template", args, msg2);
351044
351815
  return msg2;
351045
351816
  }
351046
351817
  if (action === "render") {
351047
351818
  if (!args.id) {
351048
351819
  const msg3 = "render requires id.";
351049
- emit5(context2, "manage_template", args, msg3);
351820
+ emit6(context2, "manage_template", args, msg3);
351050
351821
  return msg3;
351051
351822
  }
351052
351823
  const t = m2.listTemplates().find((x) => x.id === args.id);
351053
351824
  if (!t) {
351054
351825
  const msg3 = `No template ${args.id}.`;
351055
- emit5(context2, "manage_template", args, msg3);
351826
+ emit6(context2, "manage_template", args, msg3);
351056
351827
  return msg3;
351057
351828
  }
351058
351829
  const defaults2 = {};
@@ -351063,19 +351834,19 @@ ${all.map((t) => `- ${t.name} (id=${t.id}, ${t.versions.length} version(s))`).jo
351063
351834
  <rendered>
351064
351835
  ${rendered}
351065
351836
  </rendered>`;
351066
- emit5(context2, "manage_template", args, msg2);
351837
+ emit6(context2, "manage_template", args, msg2);
351067
351838
  return msg2;
351068
351839
  }
351069
351840
  if (action === "version") {
351070
351841
  if (!args.id) {
351071
351842
  const msg3 = "version requires id.";
351072
- emit5(context2, "manage_template", args, msg3);
351843
+ emit6(context2, "manage_template", args, msg3);
351073
351844
  return msg3;
351074
351845
  }
351075
351846
  const t = m2.listTemplates().find((x) => x.id === args.id);
351076
351847
  if (!t) {
351077
351848
  const msg3 = `No template ${args.id}.`;
351078
- emit5(context2, "manage_template", args, msg3);
351849
+ emit6(context2, "manage_template", args, msg3);
351079
351850
  return msg3;
351080
351851
  }
351081
351852
  const defaults2 = {};
@@ -351089,11 +351860,11 @@ ${rendered}
351089
351860
  Diff vs previous version:
351090
351861
  ${diffStrings(prev.rendered, rendered)}` : "\n\n(first version)";
351091
351862
  const msg2 = `Saved version ${t.versions.length + 1} of "${t.name}" at ${v.at}.${diff}`;
351092
- emit5(context2, "manage_template", args, msg2);
351863
+ emit6(context2, "manage_template", args, msg2);
351093
351864
  return msg2;
351094
351865
  }
351095
351866
  const msg = `Unknown action "${action}".`;
351096
- emit5(context2, "manage_template", args, msg);
351867
+ emit6(context2, "manage_template", args, msg);
351097
351868
  return msg;
351098
351869
  }
351099
351870
  var importPuttySchema = external_exports.object({
@@ -351103,13 +351874,13 @@ async function importPutty(args, context2) {
351103
351874
  const cm = context2.connectionManager;
351104
351875
  if (!cm) {
351105
351876
  const msg2 = "Connection management is not available in this runtime.";
351106
- emit5(context2, "import_putty", args, msg2);
351877
+ emit6(context2, "import_putty", args, msg2);
351107
351878
  return msg2;
351108
351879
  }
351109
351880
  const entries = importPuttyReg(args.regContent);
351110
351881
  if (!entries.length) {
351111
351882
  const msg2 = "No SSH sessions found in the provided PuTTY export (only ssh-protocol sessions with a HostName are imported).";
351112
- emit5(context2, "import_putty", args, msg2);
351883
+ emit6(context2, "import_putty", args, msg2);
351113
351884
  return msg2;
351114
351885
  }
351115
351886
  let created = 0;
@@ -351120,7 +351891,7 @@ async function importPutty(args, context2) {
351120
351891
  created++;
351121
351892
  }
351122
351893
  const msg = `Imported ${created} SSH connection(s) from PuTTY${entries.length !== created ? ` (${entries.length - created} skipped as duplicates or non-ssh)` : ""}. Imported: ${entries.map((e) => e.name).join(", ")}. Open them with open_terminal_tab by Name.`;
351123
- emit5(context2, "import_putty", args, msg);
351894
+ emit6(context2, "import_putty", args, msg);
351124
351895
  return msg;
351125
351896
  }
351126
351897
 
@@ -351131,7 +351902,7 @@ init_playbook_tools();
351131
351902
  init_zod();
351132
351903
  init_playbookRunner();
351133
351904
  init_scheduledTaskRunner();
351134
- function emit7(context2, toolName, input, output) {
351905
+ function emit8(context2, toolName, input, output) {
351135
351906
  context2.sendEvent(context2.sessionId, {
351136
351907
  messageId: context2.messageId,
351137
351908
  type: "tool_call",
@@ -351171,12 +351942,12 @@ async function manageChange(args, context2) {
351171
351942
  const ledger = context2.changeLedger;
351172
351943
  if (!m2) {
351173
351944
  const msg2 = "Automation store is not available in this runtime.";
351174
- emit7(context2, "manage_change", args, msg2);
351945
+ emit8(context2, "manage_change", args, msg2);
351175
351946
  return msg2;
351176
351947
  }
351177
351948
  if (!ledger) {
351178
351949
  const msg2 = "Change ledger is not available in this runtime.";
351179
- emit7(context2, "manage_change", args, msg2);
351950
+ emit8(context2, "manage_change", args, msg2);
351180
351951
  return msg2;
351181
351952
  }
351182
351953
  const { action } = args;
@@ -351184,13 +351955,13 @@ async function manageChange(args, context2) {
351184
351955
  const key = args.playbookId ?? args.name;
351185
351956
  if (!key) {
351186
351957
  const msg3 = "plan requires playbookId or name.";
351187
- emit7(context2, "manage_change", args, msg3);
351958
+ emit8(context2, "manage_change", args, msg3);
351188
351959
  return msg3;
351189
351960
  }
351190
351961
  const playbook = m2.getPlaybook(key);
351191
351962
  if (!playbook) {
351192
351963
  const msg3 = `No playbook "${key}".`;
351193
- emit7(context2, "manage_change", args, msg3);
351964
+ emit8(context2, "manage_change", args, msg3);
351194
351965
  return msg3;
351195
351966
  }
351196
351967
  const settings = settingsFromContext(context2);
@@ -351210,58 +351981,58 @@ Targets (${targets.length || 1}): ${targets.length ? targets.map((t) => t.name).
351210
351981
  Steps:
351211
351982
  ${steps}
351212
351983
  Next: manage_change action=approve changeId=${changeId}, then action=run.`;
351213
- emit7(context2, "manage_change", args, msg2);
351984
+ emit8(context2, "manage_change", args, msg2);
351214
351985
  return msg2;
351215
351986
  }
351216
351987
  if (action === "approve") {
351217
351988
  if (!args.changeId) {
351218
351989
  const msg3 = "approve requires changeId.";
351219
- emit7(context2, "manage_change", args, msg3);
351990
+ emit8(context2, "manage_change", args, msg3);
351220
351991
  return msg3;
351221
351992
  }
351222
351993
  const existing = ledger.getChange(args.changeId);
351223
351994
  if (!existing) {
351224
351995
  const msg3 = `No change "${args.changeId}".`;
351225
- emit7(context2, "manage_change", args, msg3);
351996
+ emit8(context2, "manage_change", args, msg3);
351226
351997
  return msg3;
351227
351998
  }
351228
351999
  if (existing.change.status !== "planned") {
351229
352000
  const msg3 = `Change ${args.changeId} is ${existing.change.status} \u2014 only planned changes can be approved.`;
351230
- emit7(context2, "manage_change", args, msg3);
352001
+ emit8(context2, "manage_change", args, msg3);
351231
352002
  return msg3;
351232
352003
  }
351233
352004
  ledger.approveChange(args.changeId, args.approvedBy);
351234
352005
  const msg2 = `Change ${args.changeId} approved${args.approvedBy ? ` by ${args.approvedBy}` : ""}. Execute with manage_change action=run changeId=${args.changeId}.`;
351235
- emit7(context2, "manage_change", args, msg2);
352006
+ emit8(context2, "manage_change", args, msg2);
351236
352007
  return msg2;
351237
352008
  }
351238
352009
  if (action === "run") {
351239
352010
  if (!args.changeId) {
351240
352011
  const msg3 = "run requires changeId.";
351241
- emit7(context2, "manage_change", args, msg3);
352012
+ emit8(context2, "manage_change", args, msg3);
351242
352013
  return msg3;
351243
352014
  }
351244
352015
  const existing = ledger.getChange(args.changeId);
351245
352016
  if (!existing) {
351246
352017
  const msg3 = `No change "${args.changeId}". Plan one first with manage_change action=plan.`;
351247
- emit7(context2, "manage_change", args, msg3);
352018
+ emit8(context2, "manage_change", args, msg3);
351248
352019
  return msg3;
351249
352020
  }
351250
352021
  if (existing.change.status !== "approved") {
351251
352022
  const msg3 = `Change ${args.changeId} is ${existing.change.status} \u2014 it must be approved before execution (manage_change action=approve).`;
351252
- emit7(context2, "manage_change", args, msg3);
352023
+ emit8(context2, "manage_change", args, msg3);
351253
352024
  return msg3;
351254
352025
  }
351255
352026
  const playbook = m2.getPlaybook(existing.change.playbookId);
351256
352027
  if (!playbook) {
351257
352028
  ledger.finishChange(args.changeId, "failed", "playbook no longer exists");
351258
352029
  const msg3 = `Playbook ${existing.change.playbookId} no longer exists; change marked failed.`;
351259
- emit7(context2, "manage_change", args, msg3);
352030
+ emit8(context2, "manage_change", args, msg3);
351260
352031
  return msg3;
351261
352032
  }
351262
352033
  if (!ledger.markExecuting(args.changeId)) {
351263
352034
  const msg3 = `Change ${args.changeId} could not transition to executing (status=${existing.change.status}).`;
351264
- emit7(context2, "manage_change", args, msg3);
352035
+ emit8(context2, "manage_change", args, msg3);
351265
352036
  return msg3;
351266
352037
  }
351267
352038
  const settings = settingsFromContext(context2);
@@ -351283,7 +352054,7 @@ Next: manage_change action=approve changeId=${changeId}, then action=run.`;
351283
352054
  const errMsg = error40 instanceof Error ? error40.message : String(error40);
351284
352055
  ledger.finishChange(args.changeId, "failed", errMsg);
351285
352056
  const msg3 = `Change ${args.changeId} failed to execute: ${errMsg}`;
351286
- emit7(context2, "manage_change", args, msg3);
352057
+ emit8(context2, "manage_change", args, msg3);
351287
352058
  return msg3;
351288
352059
  }
351289
352060
  const finalStatus = deriveFinalStatus(record2);
@@ -351301,19 +352072,19 @@ Next: manage_change action=approve changeId=${changeId}, then action=run.`;
351301
352072
  }
351302
352073
  const msg2 = `Change ${args.changeId} finished with status=${finalStatus} (runId=${record2.runId}).
351303
352074
  ${lines.join("\n")}`;
351304
- emit7(context2, "manage_change", args, msg2);
352075
+ emit8(context2, "manage_change", args, msg2);
351305
352076
  return msg2;
351306
352077
  }
351307
352078
  if (action === "status") {
351308
352079
  if (!args.changeId) {
351309
352080
  const msg3 = "status requires changeId.";
351310
- emit7(context2, "manage_change", args, msg3);
352081
+ emit8(context2, "manage_change", args, msg3);
351311
352082
  return msg3;
351312
352083
  }
351313
352084
  const got = ledger.getChange(args.changeId);
351314
352085
  if (!got) {
351315
352086
  const msg3 = `No change "${args.changeId}".`;
351316
- emit7(context2, "manage_change", args, msg3);
352087
+ emit8(context2, "manage_change", args, msg3);
351317
352088
  return msg3;
351318
352089
  }
351319
352090
  const { change, steps } = got;
@@ -351332,14 +352103,14 @@ ${meta}
351332
352103
  Targets: ${change.targetsSnapshot ?? "n/a"}
351333
352104
  Events:
351334
352105
  ${body}`;
351335
- emit7(context2, "manage_change", args, msg2);
352106
+ emit8(context2, "manage_change", args, msg2);
351336
352107
  return msg2;
351337
352108
  }
351338
352109
  if (action === "list") {
351339
352110
  const rows = ledger.listChanges({ status: args.status, limit: args.limit ?? 20 });
351340
352111
  if (!rows.length) {
351341
352112
  const msg3 = "No changes recorded yet. Plan one with manage_change action=plan.";
351342
- emit7(context2, "manage_change", args, msg3);
352113
+ emit8(context2, "manage_change", args, msg3);
351343
352114
  return msg3;
351344
352115
  }
351345
352116
  const body = rows.map(
@@ -351347,18 +352118,18 @@ ${body}`;
351347
352118
  ).join("\n");
351348
352119
  const msg2 = `Changes (${rows.length}):
351349
352120
  ${body}`;
351350
- emit7(context2, "manage_change", args, msg2);
352121
+ emit8(context2, "manage_change", args, msg2);
351351
352122
  return msg2;
351352
352123
  }
351353
352124
  const msg = `Unknown action "${action}".`;
351354
- emit7(context2, "manage_change", args, msg);
352125
+ emit8(context2, "manage_change", args, msg);
351355
352126
  return msg;
351356
352127
  }
351357
352128
 
351358
352129
  // ../../packages/backend/src/services/AgentHelper/tools/trigger_tools.ts
351359
352130
  init_zod();
351360
352131
  var import_crypto6 = require("crypto");
351361
- function emit8(context2, name, input, output) {
352132
+ function emit9(context2, name, input, output) {
351362
352133
  context2.sendEvent(context2.sessionId, {
351363
352134
  messageId: context2.messageId,
351364
352135
  type: "tool_call",
@@ -351387,7 +352158,7 @@ async function manageTrigger(args, context2) {
351387
352158
  const m2 = context2.automationManager;
351388
352159
  if (!m2 || typeof m2.listTriggers !== "function") {
351389
352160
  const msg2 = "Automation store with trigger support is not available in this runtime.";
351390
- emit8(context2, "manage_trigger", args, msg2);
352161
+ emit9(context2, "manage_trigger", args, msg2);
351391
352162
  return msg2;
351392
352163
  }
351393
352164
  const engine = context2.triggerEngine;
@@ -351396,7 +352167,7 @@ async function manageTrigger(args, context2) {
351396
352167
  const all = m2.listTriggers();
351397
352168
  if (!all.length) {
351398
352169
  const msg3 = "No triggers configured.";
351399
- emit8(context2, "manage_trigger", args, msg3);
352170
+ emit9(context2, "manage_trigger", args, msg3);
351400
352171
  return msg3;
351401
352172
  }
351402
352173
  const body = all.map((t) => {
@@ -351405,14 +352176,14 @@ async function manageTrigger(args, context2) {
351405
352176
  }).join("\n");
351406
352177
  const msg2 = `Triggers (${all.length}):
351407
352178
  ${body}`;
351408
- emit8(context2, "manage_trigger", args, msg2);
352179
+ emit9(context2, "manage_trigger", args, msg2);
351409
352180
  return msg2;
351410
352181
  }
351411
352182
  if (action === "fires") {
351412
352183
  const fires = engine?.listFires?.() ?? [];
351413
352184
  if (!fires.length) {
351414
352185
  const msg3 = "No trigger firings recorded yet.";
351415
- emit8(context2, "manage_trigger", args, msg3);
352186
+ emit9(context2, "manage_trigger", args, msg3);
351416
352187
  return msg3;
351417
352188
  }
351418
352189
  const limit2 = args.limit ?? 20;
@@ -351421,23 +352192,23 @@ ${body}`;
351421
352192
  ).join("\n");
351422
352193
  const msg2 = `Recent trigger firings (${Math.min(limit2, fires.length)} of ${fires.length}):
351423
352194
  ${body}`;
351424
- emit8(context2, "manage_trigger", args, msg2);
352195
+ emit9(context2, "manage_trigger", args, msg2);
351425
352196
  return msg2;
351426
352197
  }
351427
352198
  if (action === "create") {
351428
352199
  if (!args.name) {
351429
352200
  const msg3 = "create requires a name.";
351430
- emit8(context2, "manage_trigger", args, msg3);
352201
+ emit9(context2, "manage_trigger", args, msg3);
351431
352202
  return msg3;
351432
352203
  }
351433
352204
  if (!args.kind) {
351434
352205
  const msg3 = "create requires a kind (pattern|threshold|webhook|schedule).";
351435
- emit8(context2, "manage_trigger", args, msg3);
352206
+ emit9(context2, "manage_trigger", args, msg3);
351436
352207
  return msg3;
351437
352208
  }
351438
352209
  if (!args.playbookId) {
351439
352210
  const msg3 = "create requires playbookId.";
351440
- emit8(context2, "manage_trigger", args, msg3);
352211
+ emit9(context2, "manage_trigger", args, msg3);
351441
352212
  return msg3;
351442
352213
  }
351443
352214
  const entry = {
@@ -351463,20 +352234,20 @@ ${body}`;
351463
352234
  } catch {
351464
352235
  }
351465
352236
  const msg2 = `Created trigger "${entry.name}" (${entry.id}) [${entry.kind}] \u2192 ${entry.action} ${entry.playbookId}.`;
351466
- emit8(context2, "manage_trigger", args, msg2);
352237
+ emit9(context2, "manage_trigger", args, msg2);
351467
352238
  return msg2;
351468
352239
  }
351469
352240
  if (action === "update") {
351470
352241
  const key = args.id ?? args.name;
351471
352242
  if (!key) {
351472
352243
  const msg3 = "update requires id or name.";
351473
- emit8(context2, "manage_trigger", args, msg3);
352244
+ emit9(context2, "manage_trigger", args, msg3);
351474
352245
  return msg3;
351475
352246
  }
351476
352247
  const existing = m2.listTriggers().find((t) => t.id === key || t.name.trim().toLowerCase() === key.trim().toLowerCase());
351477
352248
  if (!existing) {
351478
352249
  const msg3 = `No trigger "${key}".`;
351479
- emit8(context2, "manage_trigger", args, msg3);
352250
+ emit9(context2, "manage_trigger", args, msg3);
351480
352251
  return msg3;
351481
352252
  }
351482
352253
  const merged = {
@@ -351499,14 +352270,14 @@ ${body}`;
351499
352270
  } catch {
351500
352271
  }
351501
352272
  const msg2 = `Updated trigger "${merged.name}" (${merged.id}).`;
351502
- emit8(context2, "manage_trigger", args, msg2);
352273
+ emit9(context2, "manage_trigger", args, msg2);
351503
352274
  return msg2;
351504
352275
  }
351505
352276
  if (action === "delete") {
351506
352277
  const key = args.id ?? args.name;
351507
352278
  if (!key) {
351508
352279
  const msg3 = "delete requires id or name.";
351509
- emit8(context2, "manage_trigger", args, msg3);
352280
+ emit9(context2, "manage_trigger", args, msg3);
351510
352281
  return msg3;
351511
352282
  }
351512
352283
  const ok = m2.deleteTrigger(key);
@@ -351517,14 +352288,14 @@ ${body}`;
351517
352288
  }
351518
352289
  }
351519
352290
  const msg2 = ok ? `Deleted trigger "${key}".` : `No trigger "${key}".`;
351520
- emit8(context2, "manage_trigger", args, msg2);
352291
+ emit9(context2, "manage_trigger", args, msg2);
351521
352292
  return msg2;
351522
352293
  }
351523
352294
  if (action === "enable" || action === "disable") {
351524
352295
  const key = args.id ?? args.name;
351525
352296
  if (!key) {
351526
352297
  const msg3 = `${action} requires id or name.`;
351527
- emit8(context2, "manage_trigger", args, msg3);
352298
+ emit9(context2, "manage_trigger", args, msg3);
351528
352299
  return msg3;
351529
352300
  }
351530
352301
  const ok = m2.setTriggerEnabled(key, action === "enable");
@@ -351536,11 +352307,11 @@ ${body}`;
351536
352307
  }
351537
352308
  }
351538
352309
  const msg2 = ok ? `Trigger "${key}" ${action}d.` : `No trigger "${key}".`;
351539
- emit8(context2, "manage_trigger", args, msg2);
352310
+ emit9(context2, "manage_trigger", args, msg2);
351540
352311
  return msg2;
351541
352312
  }
351542
352313
  const msg = `Unknown action "${action}".`;
351543
- emit8(context2, "manage_trigger", args, msg);
352314
+ emit9(context2, "manage_trigger", args, msg);
351544
352315
  return msg;
351545
352316
  }
351546
352317
 
@@ -351898,10 +352669,10 @@ async function listGatewayMethods(args, context2) {
351898
352669
  const lines = methods.map((mm) => `- ${mm.name} [${mm.category}] ${mm.description}${mm.params ? " (params: " + Object.entries(mm.params).map(([k, v]) => `${k}${v.optional ? "?" : ""}:${v.type}`).join(", ") + ")" : ""}`);
351899
352670
  const out = `Gateway methods (${methods.length} of ${payload.count}, registry v${payload.version}):
351900
352671
  ${lines.join("\n")}`;
351901
- emit9(context2, "list_gateway_methods", args, out);
352672
+ emit10(context2, "list_gateway_methods", args, out);
351902
352673
  return out;
351903
352674
  }
351904
- function emit9(context2, toolName, input, output) {
352675
+ function emit10(context2, toolName, input, output) {
351905
352676
  context2.sendEvent(context2.sessionId, {
351906
352677
  messageId: context2.messageId,
351907
352678
  type: "tool_call",
@@ -351914,7 +352685,7 @@ function obs(context2, toolName, args) {
351914
352685
  const o = context2.observability;
351915
352686
  if (!o) {
351916
352687
  const msg = `${toolName} is not available in this runtime (observability not wired).`;
351917
- emit9(context2, toolName, args, msg);
352688
+ emit10(context2, toolName, args, msg);
351918
352689
  return { o: null, msg };
351919
352690
  }
351920
352691
  return { o, msg: null };
@@ -351926,7 +352697,7 @@ async function getMetrics(args, context2) {
351926
352697
  const { o, msg } = obs(context2, "get_metrics", args);
351927
352698
  if (!o) return msg;
351928
352699
  const out = args.format === "prometheus" ? o.metricsExport.renderPrometheus() || "# no host metrics recorded yet" : await o.dashboard.summary();
351929
- emit9(context2, "get_metrics", args, out);
352700
+ emit10(context2, "get_metrics", args, out);
351930
352701
  return out;
351931
352702
  }
351932
352703
  var manageSecretSchema = external_exports.object({
@@ -351941,7 +352712,7 @@ async function manageSecret(args, context2) {
351941
352712
  const v = o.secrets;
351942
352713
  if (!v.unlocked()) {
351943
352714
  const m2 = "Secrets vault is locked \u2014 start RTerm with RTERM_SECRETS_MASTER_KEY set.";
351944
- emit9(context2, "manage_secret", args, m2);
352715
+ emit10(context2, "manage_secret", args, m2);
351945
352716
  return m2;
351946
352717
  }
351947
352718
  let out;
@@ -351968,7 +352739,7 @@ async function manageSecret(args, context2) {
351968
352739
  out = v.has(args.key) ? `'${args.key}' exists.` : `'${args.key}' does not exist.`;
351969
352740
  }
351970
352741
  }
351971
- emit9(context2, "manage_secret", args, out);
352742
+ emit10(context2, "manage_secret", args, out);
351972
352743
  return out;
351973
352744
  }
351974
352745
  var manageOncallSchema = external_exports.object({
@@ -352020,7 +352791,7 @@ async function manageOncall(args, context2) {
352020
352791
  } catch (e) {
352021
352792
  out = `on-call error: ${e instanceof Error ? e.message : String(e)}`;
352022
352793
  }
352023
- emit9(context2, "manage_oncall", args, out);
352794
+ emit10(context2, "manage_oncall", args, out);
352024
352795
  return out;
352025
352796
  }
352026
352797
  var getCostSchema = external_exports.object({
@@ -352044,7 +352815,7 @@ async function getCost(args, context2) {
352044
352815
  const b = o.cost.listBudgets();
352045
352816
  out = b.length ? b.map((x) => `- ${x.id}: ${x.model ?? "*"}/${x.profileId ?? "*"} ${x.period} cap $${x.capUsd}`).join("\n") : "No budgets configured.";
352046
352817
  }
352047
- emit9(context2, "get_cost", args, out);
352818
+ emit10(context2, "get_cost", args, out);
352048
352819
  return out;
352049
352820
  }
352050
352821
  var manageRecordingSchema = external_exports.object({
@@ -352110,7 +352881,7 @@ async function manageRecording(args, context2) {
352110
352881
  } catch (e) {
352111
352882
  out = `recording error: ${e instanceof Error ? e.message : String(e)}`;
352112
352883
  }
352113
- emit9(context2, "manage_recording", args, out);
352884
+ emit10(context2, "manage_recording", args, out);
352114
352885
  return out;
352115
352886
  }
352116
352887
  var manageGitopsSchema = external_exports.object({
@@ -352142,7 +352913,7 @@ async function manageGitops(args, context2) {
352142
352913
  } catch (e) {
352143
352914
  out = `gitops error: ${e instanceof Error ? e.message : String(e)}`;
352144
352915
  }
352145
- emit9(context2, "manage_gitops", args, out);
352916
+ emit10(context2, "manage_gitops", args, out);
352146
352917
  return out;
352147
352918
  }
352148
352919
  var managePlaybookVersionSchema = external_exports.object({
@@ -352189,7 +352960,7 @@ async function managePlaybookVersion(args, context2) {
352189
352960
  } catch (e) {
352190
352961
  out = `playbook error: ${e instanceof Error ? e.message : String(e)}`;
352191
352962
  }
352192
- emit9(context2, "manage_playbook_version", args, out);
352963
+ emit10(context2, "manage_playbook_version", args, out);
352193
352964
  return out;
352194
352965
  }
352195
352966
  var getCloudInventorySchema = external_exports.object({
@@ -352216,7 +352987,7 @@ async function getCloudInventory(args, context2) {
352216
352987
  } catch (e) {
352217
352988
  out = `cloud error: ${e instanceof Error ? e.message : String(e)}`;
352218
352989
  }
352219
- emit9(context2, "get_cloud_inventory", args, out);
352990
+ emit10(context2, "get_cloud_inventory", args, out);
352220
352991
  return out;
352221
352992
  }
352222
352993
  var getMonitorStatusSchema = external_exports.object({
@@ -352231,7 +353002,7 @@ async function getMonitorStatus(args, context2) {
352231
353002
  } else {
352232
353003
  out = o.monitorStatus.summary();
352233
353004
  }
352234
- emit9(context2, "get_monitor_status", args, out);
353005
+ emit10(context2, "get_monitor_status", args, out);
352235
353006
  return out;
352236
353007
  }
352237
353008
  var getLiveDashboardSchema = external_exports.object({
@@ -352247,7 +353018,7 @@ async function getLiveDashboard(args, context2) {
352247
353018
  const s = await o.dashboard.summary();
352248
353019
  out = s;
352249
353020
  }
352250
- emit9(context2, "get_live_dashboard", args, out);
353021
+ emit10(context2, "get_live_dashboard", args, out);
352251
353022
  return out;
352252
353023
  }
352253
353024
  var ingestApmSpansSchema = external_exports.object({
@@ -352260,7 +353031,7 @@ async function ingestApmSpans(args, context2) {
352260
353031
  const { ingestOtlp: ingestOtlp2 } = await Promise.resolve().then(() => (init_spanLedger(), spanLedger_exports));
352261
353032
  const n2 = ingestOtlp2(o.spanLedger, args.payload, args.defaultService);
352262
353033
  const out = `Ingested ${n2} APM span(s) into the trace store.`;
352263
- emit9(context2, "ingest_apm_spans", args, out);
353034
+ emit10(context2, "ingest_apm_spans", args, out);
352264
353035
  return out;
352265
353036
  }
352266
353037
  var getApmSummarySchema = external_exports.object({});
@@ -352269,7 +353040,7 @@ async function getApmSummary(_args, context2) {
352269
353040
  if (!o) return msg;
352270
353041
  const stats = o.spanLedger.serviceStats();
352271
353042
  const out = stats.length ? `APM: ${o.spanLedger.size()} spans across ${stats.length} service(s). ` + stats.map((x) => `${x.service}(${x.spans}${x.errors ? ", " + x.errors + " err" : ""})`).join(", ") : "APM: no spans ingested yet.";
352272
- emit9(context2, "get_apm_summary", _args, out);
353043
+ emit10(context2, "get_apm_summary", _args, out);
352273
353044
  return out;
352274
353045
  }
352275
353046
  var ingestDemBeaconSchema = external_exports.object({
@@ -352280,7 +353051,7 @@ async function ingestDemBeacon(args, context2) {
352280
353051
  if (!o) return msg;
352281
353052
  const s = o.rumLedger.ingestBeacon(args.payload);
352282
353053
  const out = s ? `Ingested RUM beacon for ${s.page}${s.lcpMs ? ` (LCP ${s.lcpMs}ms)` : ""}.` : "Beacon ignored \u2014 needs a `page` field.";
352283
- emit9(context2, "ingest_dem_beacon", args, out);
353054
+ emit10(context2, "ingest_dem_beacon", args, out);
352284
353055
  return out;
352285
353056
  }
352286
353057
  var getDemSummarySchema = external_exports.object({});
@@ -352289,7 +353060,7 @@ async function getDemSummary(_args, context2) {
352289
353060
  if (!o) return msg;
352290
353061
  const pages = o.rumLedger.pageStats();
352291
353062
  const out = pages.length ? `DEM: ${o.rumLedger.size()} sessions across ${pages.length} page(s). ` + pages.map((p) => `${p.page}(${p.sessions}${p.errorRate ? `, ${(p.errorRate * 100).toFixed(0)}% err` : ""})`).join(", ") : "DEM: no RUM sessions ingested yet.";
352292
- emit9(context2, "get_dem_summary", _args, out);
353063
+ emit10(context2, "get_dem_summary", _args, out);
352293
353064
  return out;
352294
353065
  }
352295
353066
  var collectInfraSchema = external_exports.object({
@@ -352334,7 +353105,7 @@ async function collectInfra(args, context2) {
352334
353105
  } catch (e) {
352335
353106
  out = `infra collect failed (kubectl or cluster unavailable): ${e instanceof Error ? e.message : String(e)}`;
352336
353107
  }
352337
- emit9(context2, "collect_infra", args, out);
353108
+ emit10(context2, "collect_infra", args, out);
352338
353109
  return out;
352339
353110
  }
352340
353111
  var manageEtwSchema = external_exports.object({
@@ -352393,7 +353164,7 @@ ${buildStopCommands2(s).join("\n")}`;
352393
353164
  } catch (e) {
352394
353165
  out = `etw error: ${e instanceof Error ? e.message : String(e)}`;
352395
353166
  }
352396
- emit9(context2, "manage_etw", args, out);
353167
+ emit10(context2, "manage_etw", args, out);
352397
353168
  return out;
352398
353169
  }
352399
353170
 
@@ -352612,6 +353383,21 @@ function buildToolsForModel(readFileSupport) {
352612
353383
  description: BUILTIN_TOOL_INFO.find((t) => t.name === "get_run_ledger")?.description ?? "",
352613
353384
  schema: getRunLedgerSchema
352614
353385
  },
353386
+ {
353387
+ name: "ops_experiment",
353388
+ description: BUILTIN_TOOL_INFO.find((t) => t.name === "ops_experiment")?.description ?? "",
353389
+ schema: opsExperimentSchema
353390
+ },
353391
+ {
353392
+ name: "manage_goal",
353393
+ description: BUILTIN_TOOL_INFO.find((t) => t.name === "manage_goal")?.description ?? "",
353394
+ schema: manageGoalSchema
353395
+ },
353396
+ {
353397
+ name: "estate_facts",
353398
+ description: BUILTIN_TOOL_INFO.find((t) => t.name === "estate_facts")?.description ?? "",
353399
+ schema: estateFactsSchema
353400
+ },
352615
353401
  {
352616
353402
  name: "run_fleet_command",
352617
353403
  description: BUILTIN_TOOL_INFO.find((t) => t.name === "run_fleet_command")?.description ?? "",
@@ -352796,6 +353582,9 @@ var toolImplementations = {
352796
353582
  readSessionLog,
352797
353583
  searchSessionLogs,
352798
353584
  getRunLedger,
353585
+ opsExperiment,
353586
+ manageGoal,
353587
+ estateFacts,
352799
353588
  runFleetCommand,
352800
353589
  collectFacts,
352801
353590
  probeConnectivity,
@@ -354538,12 +355327,12 @@ function encodeURIPath(str3) {
354538
355327
  return str3.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
354539
355328
  }
354540
355329
  var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
354541
- var createPathTagFunction = (pathEncoder = encodeURIPath) => function path32(statics, ...params) {
355330
+ var createPathTagFunction = (pathEncoder = encodeURIPath) => function path33(statics, ...params) {
354542
355331
  if (statics.length === 1)
354543
355332
  return statics[0];
354544
355333
  let postPath = false;
354545
355334
  const invalidSegments = [];
354546
- const path33 = statics.reduce((previousValue, currentValue, index2) => {
355335
+ const path34 = statics.reduce((previousValue, currentValue, index2) => {
354547
355336
  if (/[?#]/.test(currentValue)) {
354548
355337
  postPath = true;
354549
355338
  }
@@ -354560,7 +355349,7 @@ var createPathTagFunction = (pathEncoder = encodeURIPath) => function path32(sta
354560
355349
  }
354561
355350
  return previousValue + currentValue + (index2 === params.length ? "" : encoded);
354562
355351
  }, "");
354563
- const pathOnly = path33.split(/[?#]/, 1)[0];
355352
+ const pathOnly = path34.split(/[?#]/, 1)[0];
354564
355353
  const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
354565
355354
  let match;
354566
355355
  while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
@@ -354581,10 +355370,10 @@ var createPathTagFunction = (pathEncoder = encodeURIPath) => function path32(sta
354581
355370
  }, "");
354582
355371
  throw new OpenAIError(`Path parameters result in path with invalid segments:
354583
355372
  ${invalidSegments.map((e) => e.error).join("\n")}
354584
- ${path33}
355373
+ ${path34}
354585
355374
  ${underline}`);
354586
355375
  }
354587
- return path33;
355376
+ return path34;
354588
355377
  };
354589
355378
  var path8 = /* @__PURE__ */ createPathTagFunction(encodeURIPath);
354590
355379
 
@@ -354957,11 +355746,11 @@ var AbstractChatCompletionRunner = class extends EventStream {
354957
355746
  this._addMessage(message);
354958
355747
  return chatCompletion;
354959
355748
  }
354960
- _addMessage(message, emit10 = true) {
355749
+ _addMessage(message, emit11 = true) {
354961
355750
  if (!("content" in message))
354962
355751
  message.content = null;
354963
355752
  this.messages.push(message);
354964
- if (emit10) {
355753
+ if (emit11) {
354965
355754
  this._emit("message", message);
354966
355755
  if (isToolMessage2(message) && message.content) {
354967
355756
  this._emit("functionToolCallResult", message.content);
@@ -355213,8 +356002,8 @@ var ChatCompletionRunner = class _ChatCompletionRunner extends AbstractChatCompl
355213
356002
  runner._run(() => runner._runTools(client2, params, opts));
355214
356003
  return runner;
355215
356004
  }
355216
- _addMessage(message, emit10 = true) {
355217
- super._addMessage(message, emit10);
356005
+ _addMessage(message, emit11 = true) {
356006
+ super._addMessage(message, emit11);
355218
356007
  if (isAssistantMessage(message) && message.content) {
355219
356008
  this._emit("content", message.content);
355220
356009
  }
@@ -359401,9 +360190,9 @@ var OpenAI = class {
359401
360190
  this.apiKey = token;
359402
360191
  return true;
359403
360192
  }
359404
- buildURL(path32, query, defaultBaseURL) {
360193
+ buildURL(path33, query, defaultBaseURL) {
359405
360194
  const baseURL = !__classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
359406
- const url2 = isAbsoluteURL(path32) ? new URL(path32) : new URL(baseURL + (baseURL.endsWith("/") && path32.startsWith("/") ? path32.slice(1) : path32));
360195
+ const url2 = isAbsoluteURL(path33) ? new URL(path33) : new URL(baseURL + (baseURL.endsWith("/") && path33.startsWith("/") ? path33.slice(1) : path33));
359407
360196
  const defaultQuery = this.defaultQuery();
359408
360197
  if (!isEmptyObj(defaultQuery)) {
359409
360198
  query = { ...defaultQuery, ...query };
@@ -359427,24 +360216,24 @@ var OpenAI = class {
359427
360216
  */
359428
360217
  async prepareRequest(request, { url: url2, options }) {
359429
360218
  }
359430
- get(path32, opts) {
359431
- return this.methodRequest("get", path32, opts);
360219
+ get(path33, opts) {
360220
+ return this.methodRequest("get", path33, opts);
359432
360221
  }
359433
- post(path32, opts) {
359434
- return this.methodRequest("post", path32, opts);
360222
+ post(path33, opts) {
360223
+ return this.methodRequest("post", path33, opts);
359435
360224
  }
359436
- patch(path32, opts) {
359437
- return this.methodRequest("patch", path32, opts);
360225
+ patch(path33, opts) {
360226
+ return this.methodRequest("patch", path33, opts);
359438
360227
  }
359439
- put(path32, opts) {
359440
- return this.methodRequest("put", path32, opts);
360228
+ put(path33, opts) {
360229
+ return this.methodRequest("put", path33, opts);
359441
360230
  }
359442
- delete(path32, opts) {
359443
- return this.methodRequest("delete", path32, opts);
360231
+ delete(path33, opts) {
360232
+ return this.methodRequest("delete", path33, opts);
359444
360233
  }
359445
- methodRequest(method, path32, opts) {
360234
+ methodRequest(method, path33, opts) {
359446
360235
  return this.request(Promise.resolve(opts).then((opts2) => {
359447
- return { method, path: path32, ...opts2 };
360236
+ return { method, path: path33, ...opts2 };
359448
360237
  }));
359449
360238
  }
359450
360239
  request(options, remainingRetries = null) {
@@ -359548,8 +360337,8 @@ var OpenAI = class {
359548
360337
  }));
359549
360338
  return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
359550
360339
  }
359551
- getAPIList(path32, Page2, opts) {
359552
- return this.requestAPIList(Page2, { method: "get", path: path32, ...opts });
360340
+ getAPIList(path33, Page2, opts) {
360341
+ return this.requestAPIList(Page2, { method: "get", path: path33, ...opts });
359553
360342
  }
359554
360343
  requestAPIList(Page2, options) {
359555
360344
  const request = this.makeRequest(options, null, void 0);
@@ -359627,8 +360416,8 @@ var OpenAI = class {
359627
360416
  }
359628
360417
  async buildRequest(inputOptions, { retryCount = 0 } = {}) {
359629
360418
  const options = { ...inputOptions };
359630
- const { method, path: path32, query, defaultBaseURL } = options;
359631
- const url2 = this.buildURL(path32, query, defaultBaseURL);
360419
+ const { method, path: path33, query, defaultBaseURL } = options;
360420
+ const url2 = this.buildURL(path33, query, defaultBaseURL);
359632
360421
  if ("timeout" in options)
359633
360422
  validatePositiveInteger("timeout", options.timeout);
359634
360423
  options.timeout = options.timeout ?? this.timeout;
@@ -361244,23 +362033,23 @@ function isNullable(schema2) {
361244
362033
  }
361245
362034
  return false;
361246
362035
  }
361247
- function ensureStrictJsonSchema(jsonSchema, path32, root) {
362036
+ function ensureStrictJsonSchema(jsonSchema, path33, root) {
361248
362037
  if (typeof jsonSchema === "boolean") {
361249
- throw new TypeError(`Expected object schema but got boolean; path=${path32.join("/")}`);
362038
+ throw new TypeError(`Expected object schema but got boolean; path=${path33.join("/")}`);
361250
362039
  }
361251
362040
  if (!isObject4(jsonSchema)) {
361252
- throw new TypeError(`Expected ${JSON.stringify(jsonSchema)} to be an object; path=${path32.join("/")}`);
362041
+ throw new TypeError(`Expected ${JSON.stringify(jsonSchema)} to be an object; path=${path33.join("/")}`);
361253
362042
  }
361254
362043
  const defs = jsonSchema.$defs;
361255
362044
  if (isObject4(defs)) {
361256
362045
  for (const [defName, defSchema] of Object.entries(defs)) {
361257
- ensureStrictJsonSchema(defSchema, [...path32, "$defs", defName], root);
362046
+ ensureStrictJsonSchema(defSchema, [...path33, "$defs", defName], root);
361258
362047
  }
361259
362048
  }
361260
362049
  const definitions = jsonSchema.definitions;
361261
362050
  if (isObject4(definitions)) {
361262
362051
  for (const [definitionName, definitionSchema] of Object.entries(definitions)) {
361263
- ensureStrictJsonSchema(definitionSchema, [...path32, "definitions", definitionName], root);
362052
+ ensureStrictJsonSchema(definitionSchema, [...path33, "definitions", definitionName], root);
361264
362053
  }
361265
362054
  }
361266
362055
  const typ = jsonSchema.type;
@@ -361272,31 +362061,31 @@ function ensureStrictJsonSchema(jsonSchema, path32, root) {
361272
362061
  if (isObject4(properties)) {
361273
362062
  for (const [key, value] of Object.entries(properties)) {
361274
362063
  if (!isNullable(value) && !required2.includes(key)) {
361275
- throw new Error(`Zod field at \`${[...path32, "properties", key].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);
362064
+ throw new Error(`Zod field at \`${[...path33, "properties", key].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);
361276
362065
  }
361277
362066
  }
361278
362067
  jsonSchema.required = Object.keys(properties);
361279
362068
  jsonSchema.properties = Object.fromEntries(Object.entries(properties).map(([key, propSchema]) => [
361280
362069
  key,
361281
- ensureStrictJsonSchema(propSchema, [...path32, "properties", key], root)
362070
+ ensureStrictJsonSchema(propSchema, [...path33, "properties", key], root)
361282
362071
  ]));
361283
362072
  }
361284
362073
  const items = jsonSchema.items;
361285
362074
  if (isObject4(items)) {
361286
- jsonSchema.items = ensureStrictJsonSchema(items, [...path32, "items"], root);
362075
+ jsonSchema.items = ensureStrictJsonSchema(items, [...path33, "items"], root);
361287
362076
  }
361288
362077
  const anyOf = jsonSchema.anyOf;
361289
362078
  if (Array.isArray(anyOf)) {
361290
- jsonSchema.anyOf = anyOf.map((variant, i) => ensureStrictJsonSchema(variant, [...path32, "anyOf", String(i)], root));
362079
+ jsonSchema.anyOf = anyOf.map((variant, i) => ensureStrictJsonSchema(variant, [...path33, "anyOf", String(i)], root));
361291
362080
  }
361292
362081
  const allOf = jsonSchema.allOf;
361293
362082
  if (Array.isArray(allOf)) {
361294
362083
  if (allOf.length === 1) {
361295
- const resolved = ensureStrictJsonSchema(allOf[0], [...path32, "allOf", "0"], root);
362084
+ const resolved = ensureStrictJsonSchema(allOf[0], [...path33, "allOf", "0"], root);
361296
362085
  Object.assign(jsonSchema, resolved);
361297
362086
  delete jsonSchema.allOf;
361298
362087
  } else {
361299
- jsonSchema.allOf = allOf.map((entry, i) => ensureStrictJsonSchema(entry, [...path32, "allOf", String(i)], root));
362088
+ jsonSchema.allOf = allOf.map((entry, i) => ensureStrictJsonSchema(entry, [...path33, "allOf", String(i)], root));
361300
362089
  }
361301
362090
  }
361302
362091
  if (jsonSchema.default === null) {
@@ -361305,7 +362094,7 @@ function ensureStrictJsonSchema(jsonSchema, path32, root) {
361305
362094
  const ref = jsonSchema.$ref;
361306
362095
  if (ref && hasMoreThanNKeys(jsonSchema, 1)) {
361307
362096
  if (typeof ref !== "string") {
361308
- throw new TypeError(`Received non-string $ref - ${ref}; path=${path32.join("/")}`);
362097
+ throw new TypeError(`Received non-string $ref - ${ref}; path=${path33.join("/")}`);
361309
362098
  }
361310
362099
  const resolved = resolveRef(root, ref);
361311
362100
  if (typeof resolved === "boolean") {
@@ -361316,7 +362105,7 @@ function ensureStrictJsonSchema(jsonSchema, path32, root) {
361316
362105
  }
361317
362106
  Object.assign(jsonSchema, { ...resolved, ...jsonSchema });
361318
362107
  delete jsonSchema.$ref;
361319
- return ensureStrictJsonSchema(jsonSchema, path32, root);
362108
+ return ensureStrictJsonSchema(jsonSchema, path33, root);
361320
362109
  }
361321
362110
  return jsonSchema;
361322
362111
  }
@@ -365722,7 +366511,7 @@ var import_node_fs4 = __toESM(require("node:fs"), 1);
365722
366511
  var import_promises6 = __toESM(require("node:fs/promises"), 1);
365723
366512
  var import_node_os2 = __toESM(require("node:os"), 1);
365724
366513
  var import_node_path6 = __toESM(require("node:path"), 1);
365725
- var import_node_crypto17 = __toESM(require("node:crypto"), 1);
366514
+ var import_node_crypto18 = __toESM(require("node:crypto"), 1);
365726
366515
  var DEFAULT_MAX_FILES = 50;
365727
366516
  var PassChatTempExportService = class {
365728
366517
  baseDir;
@@ -365849,7 +366638,7 @@ ${input.markdown}`
365849
366638
  return import_node_path6.default.join(this.baseDir, `pass-chat_${sessionHash}_${hash2}.md`);
365850
366639
  }
365851
366640
  hashText(input) {
365852
- return import_node_crypto17.default.createHash("sha256").update(input).digest("hex");
366641
+ return import_node_crypto18.default.createHash("sha256").update(input).digest("hex");
365853
366642
  }
365854
366643
  async ensurePrivateBaseDir() {
365855
366644
  await import_promises6.default.mkdir(this.baseDir, { recursive: true, mode: 448 });
@@ -366175,6 +366964,11 @@ function reconcileToolCalls(toolCalls) {
366175
366964
  }
366176
366965
  return result;
366177
366966
  }
366967
+ var TOOL_RESULT_MAX_CHARS = 32768;
366968
+ function stringifyToolResult(result) {
366969
+ const raw = typeof result === "string" ? result : JSON.stringify(result);
366970
+ return clipTextMiddle(raw, TOOL_RESULT_MAX_CHARS);
366971
+ }
366178
366972
  function clipTextMiddle(input, maxChars) {
366179
366973
  if (maxChars <= 0) return "";
366180
366974
  if (input.length <= maxChars) return input;
@@ -366218,6 +367012,7 @@ var AgentService_v2 = class {
366218
367012
  /** Optional run ledger — persisted audit + token-cost record of every
366219
367013
  * agent run (start/finish lifecycle + per-call token usage). */
366220
367014
  agentRunLedger;
367015
+ compoundingStore;
366221
367016
  changeLedger;
366222
367017
  mcpToolService;
366223
367018
  skillService;
@@ -366352,6 +367147,9 @@ var AgentService_v2 = class {
366352
367147
  setAgentRunLedger(ledger) {
366353
367148
  this.agentRunLedger = ledger ?? void 0;
366354
367149
  }
367150
+ setCompoundingStore(store) {
367151
+ this.compoundingStore = store ?? void 0;
367152
+ }
366355
367153
  setFeedbackWaiter(waiter) {
366356
367154
  this.waitForFeedback = waiter;
366357
367155
  }
@@ -366767,7 +367565,21 @@ var AgentService_v2 = class {
366767
367565
  );
366768
367566
  }
366769
367567
  }
366770
- const baseSystemText = createBaseSystemPromptText(memoryPrompt);
367568
+ let baseSystemText = createBaseSystemPromptText(memoryPrompt);
367569
+ if (this.compoundingStore) {
367570
+ const block = this.compoundingStore.promptBlock(3500);
367571
+ const goals = this.compoundingStore.listGoals(sessionId).filter((g) => g.status === "open" || g.status === "blocked");
367572
+ const extra = [];
367573
+ if (block) extra.push(block);
367574
+ if (goals.length) {
367575
+ extra.push(
367576
+ "# Open goals this session\n" + goals.map((g) => `- [${g.status}] ${g.text}${g.blockedBy ? ` (${g.blockedBy})` : ""}`).join("\n")
367577
+ );
367578
+ }
367579
+ if (extra.length) baseSystemText = `${baseSystemText}
367580
+
367581
+ ${extra.join("\n\n")}`;
367582
+ }
366771
367583
  const newMessages = upsertSingleSystemMessageByText(
366772
367584
  [...messages, humanMessage],
366773
367585
  baseSystemText
@@ -367701,6 +368513,33 @@ Actually, your intention might be different. Please re-read the description of t
367701
368513
  }
367702
368514
  break;
367703
368515
  }
368516
+ case "ops_experiment": {
368517
+ try {
368518
+ const validatedArgs = opsExperimentSchema.parse(toolCall.args || {});
368519
+ result = await toolImplementations.opsExperiment(validatedArgs, executionContext);
368520
+ } catch (err) {
368521
+ result = `Parameter validation error for ops_experiment: ${err.message}`;
368522
+ }
368523
+ break;
368524
+ }
368525
+ case "manage_goal": {
368526
+ try {
368527
+ const validatedArgs = manageGoalSchema.parse(toolCall.args || {});
368528
+ result = await toolImplementations.manageGoal(validatedArgs, executionContext);
368529
+ } catch (err) {
368530
+ result = `Parameter validation error for manage_goal: ${err.message}`;
368531
+ }
368532
+ break;
368533
+ }
368534
+ case "estate_facts": {
368535
+ try {
368536
+ const validatedArgs = estateFactsSchema.parse(toolCall.args || {});
368537
+ result = await toolImplementations.estateFacts(validatedArgs, executionContext);
368538
+ } catch (err) {
368539
+ result = `Parameter validation error for estate_facts: ${err.message}`;
368540
+ }
368541
+ break;
368542
+ }
367704
368543
  case "get_metrics": {
367705
368544
  try {
367706
368545
  const validatedArgs = getMetricsSchema.parse(toolCall.args || {});
@@ -368052,7 +368891,7 @@ Actually, your intention might be different. Please re-read the description of t
368052
368891
  try {
368053
368892
  const pluginArgs = typeof toolCall.args === "string" ? JSON.parse(toolCall.args) : toolCall.args || {};
368054
368893
  const pluginResult = await pluginHandler(pluginArgs);
368055
- result = typeof pluginResult === "string" ? pluginResult : JSON.stringify(pluginResult);
368894
+ result = stringifyToolResult(pluginResult);
368056
368895
  } catch (err) {
368057
368896
  result = `Plugin tool "${toolCall.name}" error: ${err.message}`;
368058
368897
  }
@@ -368307,6 +369146,12 @@ Actually, your intention might be different. Please re-read the description of t
368307
369146
  return ti.getCost(args, executionContext);
368308
369147
  case "get_run_ledger":
368309
369148
  return ti.getRunLedger(args, executionContext);
369149
+ case "ops_experiment":
369150
+ return ti.opsExperiment(args, executionContext);
369151
+ case "manage_goal":
369152
+ return ti.manageGoal(args, executionContext);
369153
+ case "estate_facts":
369154
+ return ti.estateFacts(args, executionContext);
368310
369155
  case "list_gateway_methods":
368311
369156
  return ti.listGatewayMethods(args, executionContext);
368312
369157
  case "collect_facts":
@@ -368334,7 +369179,7 @@ Actually, your intention might be different. Please re-read the description of t
368334
369179
  const pluginHandler = this.pluginTools.get(name);
368335
369180
  if (pluginHandler) {
368336
369181
  const result = await pluginHandler(args);
368337
- return typeof result === "string" ? result : JSON.stringify(result);
369182
+ return stringifyToolResult(result);
368338
369183
  }
368339
369184
  return `Tool "${name}" is not supported in parallel execution mode.`;
368340
369185
  }
@@ -368415,7 +369260,7 @@ Actually, your intention might be different. Please re-read the description of t
368415
369260
  args,
368416
369261
  signal
368417
369262
  );
368418
- resultText = typeof result === "string" ? result : JSON.stringify(result, null, 2);
369263
+ resultText = stringifyToolResult(result);
368419
369264
  } catch (err) {
368420
369265
  if (this.helpers.isAbortError(err)) throw err;
368421
369266
  resultText = err instanceof Error ? err.message : String(err);
@@ -368764,6 +369609,7 @@ ${reminder}`;
368764
369609
  automationManager: this.automationManager,
368765
369610
  sessionLogger: this.sessionLogger,
368766
369611
  agentRunLedger: this.agentRunLedger,
369612
+ compoundingStore: this.compoundingStore,
368767
369613
  changeLedger: this.changeLedger,
368768
369614
  triggerEngine: this.triggerEngine,
368769
369615
  observability: this.observability,
@@ -369724,9 +370570,50 @@ ${reminder}`;
369724
370570
  }
369725
370571
  this.currentRunIdBySession.delete(sessionId);
369726
370572
  this.agentRunLedger?.finishRun(ledgerRunId, ledgerExitStatus, ledgerExitError);
370573
+ void this.recordCompoundingLessons(sessionId, ledgerRunId, ledgerExitStatus, ledgerExitError);
369727
370574
  await this.clearCheckpoint(sessionId);
369728
370575
  }
369729
370576
  }
370577
+ /**
370578
+ * After every run, extract durable lessons from the error + input preview
370579
+ * and append them to memory.md (deduped by fingerprint). Best-effort: a
370580
+ * failure here must never throw out of the agent finally block.
370581
+ */
370582
+ async recordCompoundingLessons(_sessionId, ledgerRunId, status, error40) {
370583
+ try {
370584
+ if (!this.compoundingStore) return;
370585
+ const { extractLessons: extractLessons2, isTrivialRun: isTrivialRun2, appendLessonsToMemory: appendLessonsToMemory2, formatLessonMarkdown: formatLessonMarkdown2 } = await Promise.resolve().then(() => (init_compoundingKnowledge(), compoundingKnowledge_exports));
370586
+ const run = ledgerRunId ? this.agentRunLedger?.getRun(ledgerRunId) : null;
370587
+ const inputPreview = run?.run.inputPreview;
370588
+ if (isTrivialRun2(inputPreview, error40)) return;
370589
+ const lessons = extractLessons2(error40, inputPreview, status === "failed" ? status : "");
370590
+ if (!lessons.length) return;
370591
+ const rows = this.compoundingStore.recordLessons(lessons, ledgerRunId);
370592
+ const snapshot = await this.memoryService.getMemorySnapshot(this.getActiveMemoryProfileId());
370593
+ const { next, added } = appendLessonsToMemory2(snapshot.content, lessons, {
370594
+ runId: ledgerRunId,
370595
+ at: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)
370596
+ });
370597
+ if (added.length && this.memoryService.appendMemory) {
370598
+ const chunk2 = added.map((fp) => {
370599
+ const lesson2 = lessons.find((l) => l.fingerprint === fp);
370600
+ const row = rows.find((r) => r.fingerprint === fp);
370601
+ return lesson2 ? formatLessonMarkdown2(lesson2, {
370602
+ runId: ledgerRunId,
370603
+ at: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
370604
+ occurrence: row?.occurrences
370605
+ }) : "";
370606
+ }).join("");
370607
+ if (chunk2) {
370608
+ await this.memoryService.appendMemory(chunk2, this.getActiveMemoryProfileId());
370609
+ }
370610
+ } else if (added.length) {
370611
+ await this.memoryService.writeMemory(next, this.getActiveMemoryProfileId());
370612
+ }
370613
+ } catch (err) {
370614
+ console.warn("[AgentService_v2] compounding lesson write failed:", err);
370615
+ }
370616
+ }
369730
370617
  async clearCheckpoint(sessionId) {
369731
370618
  try {
369732
370619
  await this.checkpointer.deleteThread(sessionId);
@@ -372152,6 +373039,22 @@ var WebSocketRpcError = class extends Error {
372152
373039
  this.code = code;
372153
373040
  }
372154
373041
  };
373042
+ function httpRouteMatches(pattern, pathname) {
373043
+ if (pattern === pathname) return true;
373044
+ if (pattern.endsWith("/*")) {
373045
+ const prefix = pattern.slice(0, -1);
373046
+ const base = pattern.slice(0, -2);
373047
+ return pathname === base || pathname.startsWith(prefix) || pathname.startsWith(base + "/");
373048
+ }
373049
+ const a = pattern.split("/").filter(Boolean);
373050
+ const b = pathname.split("/").filter(Boolean);
373051
+ if (a.length !== b.length) return false;
373052
+ for (let i = 0; i < a.length; i++) {
373053
+ if (a[i].startsWith(":")) continue;
373054
+ if (a[i] !== b[i]) return false;
373055
+ }
373056
+ return true;
373057
+ }
372155
373058
  function createDefaultWebSocketServerFactory(httpRoutes) {
372156
373059
  return ({ host, port }) => {
372157
373060
  if (!httpRoutes || httpRoutes.length === 0) {
@@ -372174,7 +373077,7 @@ function createDefaultWebSocketServerFactory(httpRoutes) {
372174
373077
  ).pathname;
372175
373078
  } catch {
372176
373079
  }
372177
- const route = routes.find((r) => r.path === pathname);
373080
+ const route = routes.find((r) => httpRouteMatches(r.path, pathname));
372178
373081
  if (!route) {
372179
373082
  res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
372180
373083
  res.end("not found");
@@ -381848,6 +382751,14 @@ var FileMemoryStore = class {
381848
382751
  content
381849
382752
  };
381850
382753
  }
382754
+ /** Append text to memory.md (used by auto-lesson writer). */
382755
+ async appendMemory(chunk2) {
382756
+ const filePath = await this.ensureMemoryFile();
382757
+ const current = await import_promises10.default.readFile(filePath, "utf8");
382758
+ const next = current.endsWith("\n") || current === "" ? current + chunk2 : current + "\n" + chunk2;
382759
+ await import_promises10.default.writeFile(filePath, next, "utf8");
382760
+ return { filePath, content: next };
382761
+ }
381851
382762
  async getMemorySnapshot() {
381852
382763
  const filePath = await this.ensureMemoryFile();
381853
382764
  const content = await import_promises10.default.readFile(filePath, "utf8");
@@ -381895,6 +382806,9 @@ var NodeMemoryService = class {
381895
382806
  async writeMemory(content, profileId) {
381896
382807
  return await this.createStore(profileId).writeMemory(content);
381897
382808
  }
382809
+ async appendMemory(chunk2, profileId) {
382810
+ return await this.createStore(profileId).appendMemory(chunk2);
382811
+ }
381898
382812
  async copyMemory(sourceProfileId, targetProfileId) {
381899
382813
  const content = await this.readMemory(sourceProfileId);
381900
382814
  return await this.writeMemory(content, targetProfileId);
@@ -381908,8 +382822,8 @@ var import_node_path20 = __toESM(require("node:path"), 1);
381908
382822
  var import_promises11 = __toESM(require("node:fs/promises"), 1);
381909
382823
  var import_node_path19 = __toESM(require("node:path"), 1);
381910
382824
  var import_node_util = require("node:util");
381911
- var import_node_crypto18 = require("node:crypto");
381912
- var scrypt = (0, import_node_util.promisify)(import_node_crypto18.scrypt);
382825
+ var import_node_crypto19 = require("node:crypto");
382826
+ var scrypt = (0, import_node_util.promisify)(import_node_crypto19.scrypt);
381913
382827
  var FILE_SCHEMA_VERSION = 1;
381914
382828
  var HASH_KEY_LENGTH = 32;
381915
382829
  var TOKEN_NAME_MAX_LENGTH = 64;
@@ -381923,10 +382837,10 @@ function makeDefaultPayload() {
381923
382837
  };
381924
382838
  }
381925
382839
  function randomTokenId() {
381926
- return `atk_${(0, import_node_crypto18.randomBytes)(12).toString("base64url")}`;
382840
+ return `atk_${(0, import_node_crypto19.randomBytes)(12).toString("base64url")}`;
381927
382841
  }
381928
382842
  function randomAccessTokenValue() {
381929
- return `gys_at_${(0, import_node_crypto18.randomBytes)(24).toString("base64url")}`;
382843
+ return `gys_at_${(0, import_node_crypto19.randomBytes)(24).toString("base64url")}`;
381930
382844
  }
381931
382845
  async function deriveTokenHash(token, tokenSaltBase64) {
381932
382846
  const tokenSalt = Buffer.from(tokenSaltBase64, "base64");
@@ -381988,7 +382902,7 @@ var FileAccessTokenStore = class {
381988
382902
  throw new Error(`Token name already exists: ${normalizedName}`);
381989
382903
  }
381990
382904
  const token = randomAccessTokenValue();
381991
- const tokenSalt = (0, import_node_crypto18.randomBytes)(16).toString("base64");
382905
+ const tokenSalt = (0, import_node_crypto19.randomBytes)(16).toString("base64");
381992
382906
  const tokenHash = (await deriveTokenHash(token, tokenSalt)).toString("base64");
381993
382907
  const createdAt = Date.now();
381994
382908
  const record2 = {
@@ -382035,7 +382949,7 @@ var FileAccessTokenStore = class {
382035
382949
  try {
382036
382950
  const expected = Buffer.from(record2.tokenHash, "base64");
382037
382951
  const actual = await deriveTokenHash(token, record2.tokenSalt);
382038
- if (expected.length === actual.length && (0, import_node_crypto18.timingSafeEqual)(expected, actual)) {
382952
+ if (expected.length === actual.length && (0, import_node_crypto19.timingSafeEqual)(expected, actual)) {
382039
382953
  return true;
382040
382954
  }
382041
382955
  } catch {
@@ -382537,7 +383451,7 @@ function buildBuiltInToolStatusSummary(enabledMap) {
382537
383451
  // ../../packages/backend/src/services/ImageAttachmentService.ts
382538
383452
  var import_promises12 = __toESM(require("node:fs/promises"), 1);
382539
383453
  var import_node_path21 = __toESM(require("node:path"), 1);
382540
- var import_node_crypto19 = __toESM(require("node:crypto"), 1);
383454
+ var import_node_crypto20 = __toESM(require("node:crypto"), 1);
382541
383455
  var DEFAULT_INDEX = {
382542
383456
  records: {}
382543
383457
  };
@@ -382561,7 +383475,7 @@ var ImageAttachmentService = class {
382561
383475
  const normalizedMimeType = this.resolveMimeType(payload.mimeType, image.mimeType);
382562
383476
  const extension = this.resolveImageExtension(payload.fileName, normalizedMimeType);
382563
383477
  const safeName = this.safeFileName(payload.fileName);
382564
- const sha2562 = import_node_crypto19.default.createHash("sha256").update(bytes).digest("hex");
383478
+ const sha2562 = import_node_crypto20.default.createHash("sha256").update(bytes).digest("hex");
382565
383479
  const attachmentId = `img_${sha2562.slice(0, 24)}`;
382566
383480
  const filePath = import_node_path21.default.join(this.attachmentsDir, `${attachmentId}${extension}`);
382567
383481
  const existing = this.records[attachmentId];
@@ -384072,10 +384986,11 @@ var IdleTimeoutService = class {
384072
384986
  };
384073
384987
 
384074
384988
  // ../../packages/backend/src/services/Gateway/restApi.ts
384075
- function matchRestRoute(routes, method, path32) {
384076
- const normalized = path32.replace(/\/+$/, "") || "/";
384989
+ function matchRestRoute(routes, method, path33) {
384990
+ const normalized = path33.replace(/\/+$/, "") || "/";
384991
+ const verb = method.toUpperCase();
384077
384992
  for (const route of routes) {
384078
- if (route.method !== method.toUpperCase()) continue;
384993
+ if (route.method !== verb) continue;
384079
384994
  const patternParts = route.path.split("/").filter(Boolean);
384080
384995
  const pathParts = normalized.split("/").filter(Boolean);
384081
384996
  if (patternParts.length !== pathParts.length) continue;
@@ -384096,36 +385011,18 @@ function matchRestRoute(routes, method, path32) {
384096
385011
  }
384097
385012
  function defaultRestRoutes() {
384098
385013
  return [
385014
+ { method: "GET", path: "/api/v1/health", gatewayMethod: "gateway:ping", description: "Liveness check" },
385015
+ { method: "GET", path: "/api/v1/methods", gatewayMethod: "gateway:describe", description: "List all gateway RPC methods" },
385016
+ { method: "GET", path: "/api/v1/openapi.json", gatewayMethod: "__openapi", description: "OpenAPI 3 document for this REST overlay + RPC escape hatch" },
385017
+ { method: "GET", path: "/api/v1/terminals", gatewayMethod: "terminal:list", description: "List terminal tabs" },
385018
+ { method: "GET", path: "/api/v1/sessions", gatewayMethod: "session:list", description: "List chat sessions" },
384099
385019
  {
384100
- method: "GET",
384101
- path: "/api/v1/health",
384102
- gatewayMethod: "gateway:ping",
384103
- description: "Liveness check"
384104
- },
384105
- {
384106
- method: "GET",
384107
- path: "/api/v1/methods",
384108
- gatewayMethod: "gateway:describe",
384109
- description: "List all gateway methods (self-describing)"
384110
- },
384111
- {
384112
- method: "GET",
384113
- path: "/api/v1/terminals",
384114
- gatewayMethod: "terminal:list",
384115
- description: "List terminal tabs"
384116
- },
384117
- {
384118
- method: "GET",
385020
+ method: "POST",
384119
385021
  path: "/api/v1/sessions",
384120
- gatewayMethod: "session:list",
384121
- description: "List chat sessions"
384122
- },
384123
- {
384124
- method: "GET",
384125
- path: "/api/v1/skills",
384126
- gatewayMethod: "skills:getAll",
384127
- description: "List loaded skills"
385022
+ gatewayMethod: "gateway:createSession",
385023
+ description: "Create a chat/agent session"
384128
385024
  },
385025
+ { method: "GET", path: "/api/v1/skills", gatewayMethod: "skills:getAll", description: "List loaded skills" },
384129
385026
  {
384130
385027
  method: "GET",
384131
385028
  path: "/api/v1/observability/metrics",
@@ -384142,13 +385039,13 @@ function defaultRestRoutes() {
384142
385039
  method: "GET",
384143
385040
  path: "/api/v1/observability/apm",
384144
385041
  gatewayMethod: "observability:apmSummary",
384145
- description: "APM summary (LLM + app traces)"
385042
+ description: "APM summary"
384146
385043
  },
384147
385044
  {
384148
385045
  method: "GET",
384149
385046
  path: "/api/v1/history/search",
384150
385047
  gatewayMethod: "history:search",
384151
- description: "Cross-session history search (?q=...)",
385048
+ description: "Cross-session history search (?q=)",
384152
385049
  buildParams: (_p, body) => {
384153
385050
  const b = body ?? {};
384154
385051
  return { query: b.q ?? b.query ?? "" };
@@ -384168,17 +385065,18 @@ function defaultRestRoutes() {
384168
385065
  method: "GET",
384169
385066
  path: "/api/v1/terminals/:id/buffer",
384170
385067
  gatewayMethod: "terminal:getBufferDelta",
384171
- description: "Read a terminal tab output delta",
385068
+ description: "Read terminal output delta (?fromOffset=)",
384172
385069
  buildParams: (p, body) => {
384173
385070
  const b = body ?? {};
384174
- return { terminalId: p.id, fromOffset: b.fromOffset ?? 0 };
385071
+ const n2 = Number(b.fromOffset ?? 0);
385072
+ return { terminalId: p.id, fromOffset: Number.isFinite(n2) ? n2 : 0 };
384175
385073
  }
384176
385074
  },
384177
385075
  {
384178
385076
  method: "POST",
384179
385077
  path: "/api/v1/sessions/:id/chat",
384180
385078
  gatewayMethod: "agent:startTask",
384181
- description: "Send a message to the agent (blocking)",
385079
+ description: "Send a message (blocking until the run finishes \u2014 prefer chat-async)",
384182
385080
  buildParams: (p, body) => {
384183
385081
  const b = body ?? {};
384184
385082
  return { sessionId: p.id, userInput: b.message ?? b.userInput ?? "" };
@@ -384186,17 +385084,66 @@ function defaultRestRoutes() {
384186
385084
  },
384187
385085
  {
384188
385086
  method: "POST",
384189
- path: "/api/v1/rpc",
384190
- gatewayMethod: "",
384191
- description: "Escape hatch: dispatch any gateway method",
384192
- buildParams: (_p, body) => {
385087
+ path: "/api/v1/sessions/:id/chat-async",
385088
+ gatewayMethod: "agent:startTaskAsync",
385089
+ description: "Start an agent turn without waiting; subscribe to WS gateway:event for tokens",
385090
+ buildParams: (p, body) => {
384193
385091
  const b = body ?? {};
384194
- return { __rpcMethod: b.method ?? "", ...b.params ?? {} };
385092
+ return { sessionId: p.id, userInput: b.message ?? b.userInput ?? "" };
384195
385093
  }
385094
+ },
385095
+ {
385096
+ method: "POST",
385097
+ path: "/api/v1/rpc",
385098
+ gatewayMethod: "",
385099
+ description: "Escape hatch: any gateway method {method, params}"
384196
385100
  }
384197
385101
  ];
384198
385102
  }
385103
+ function buildOpenApiDocument() {
385104
+ const routes = defaultRestRoutes();
385105
+ const paths = {};
385106
+ for (const r of routes) {
385107
+ if (r.gatewayMethod === "__openapi") continue;
385108
+ const item = paths[r.path] || {};
385109
+ item[r.method.toLowerCase()] = {
385110
+ summary: r.description,
385111
+ operationId: `${r.method}_${r.path.replace(/[^a-zA-Z0-9]+/g, "_")}`,
385112
+ tags: ["rest"],
385113
+ ...r.method === "POST" ? {
385114
+ requestBody: {
385115
+ content: { "application/json": { schema: { type: "object" } } }
385116
+ }
385117
+ } : {},
385118
+ responses: { "200": { description: "OK" }, "401": { description: "Unauthorized" } }
385119
+ };
385120
+ paths[r.path] = item;
385121
+ }
385122
+ const rpcMethods = [...CORE_METHODS, DESCRIBE_METHOD].map((m2) => m2.name);
385123
+ return {
385124
+ openapi: "3.0.3",
385125
+ info: {
385126
+ title: "RTerm HTTP overlay",
385127
+ version: "1.0.0",
385128
+ description: `Thin REST on the same port as the WebSocket JSON-RPC gateway. Streaming agent/PTY traffic stays on ws://. POST /api/v1/rpc reaches every RPC method. Core RPC methods: ${rpcMethods.length}. Categories: ${METHOD_CATEGORIES.join(", ")}.`
385129
+ },
385130
+ paths,
385131
+ "x-gateway-rpc-methods": rpcMethods
385132
+ };
385133
+ }
384199
385134
  async function handleRestRequest(routes, dispatch, req) {
385135
+ const verb = req.method.toUpperCase();
385136
+ if (verb === "OPTIONS") {
385137
+ return {
385138
+ status: 204,
385139
+ body: "",
385140
+ headers: {
385141
+ "access-control-allow-origin": "*",
385142
+ "access-control-allow-methods": "GET, POST, OPTIONS",
385143
+ "access-control-allow-headers": "Authorization, Content-Type"
385144
+ }
385145
+ };
385146
+ }
384200
385147
  const match = matchRestRoute(routes, req.method, req.path);
384201
385148
  if (!match) {
384202
385149
  return {
@@ -384204,12 +385151,18 @@ async function handleRestRequest(routes, dispatch, req) {
384204
385151
  body: { error: "not_found", message: `No REST route for ${req.method} ${req.path}` }
384205
385152
  };
384206
385153
  }
385154
+ if (match.route.gatewayMethod === "__openapi") {
385155
+ return { status: 200, body: buildOpenApiDocument() };
385156
+ }
384207
385157
  let gatewayMethod = match.route.gatewayMethod;
384208
385158
  let params;
384209
385159
  if (gatewayMethod === "") {
384210
385160
  const raw = req.body ?? {};
384211
385161
  if (!raw.method) {
384212
- return { status: 400, body: { error: "bad_request", message: 'POST /api/v1/rpc needs {"method": "...", "params": {...}}' } };
385162
+ return {
385163
+ status: 400,
385164
+ body: { error: "bad_request", message: 'POST /api/v1/rpc needs {"method": "...", "params": {...}}' }
385165
+ };
384213
385166
  }
384214
385167
  gatewayMethod = raw.method;
384215
385168
  params = raw.params ?? {};
@@ -384225,6 +385178,52 @@ async function handleRestRequest(routes, dispatch, req) {
384225
385178
  return { status, body: { error: "gateway_error", message } };
384226
385179
  }
384227
385180
  }
385181
+ var JSON_HEADERS = { "content-type": "application/json; charset=utf-8" };
385182
+ function readJsonBody(req) {
385183
+ return new Promise((resolve2) => {
385184
+ let data = "";
385185
+ req.on?.("data", (d) => {
385186
+ data += String(d ?? "");
385187
+ if (data.length > 2e6) {
385188
+ resolve2({});
385189
+ }
385190
+ });
385191
+ req.on?.("end", () => {
385192
+ try {
385193
+ resolve2(data ? JSON.parse(data) : {});
385194
+ } catch {
385195
+ resolve2({});
385196
+ }
385197
+ });
385198
+ });
385199
+ }
385200
+ function makeRestCatchAllHandler(opts) {
385201
+ const routes = defaultRestRoutes();
385202
+ return async (req, res) => {
385203
+ const r = req;
385204
+ const s = res;
385205
+ try {
385206
+ if (!await opts.isAuthorized(r)) {
385207
+ s.writeHead?.(401, JSON_HEADERS);
385208
+ s.end?.(JSON.stringify({ error: "unauthorized" }));
385209
+ return;
385210
+ }
385211
+ const url2 = new URL(r.url ?? "/", "http://localhost");
385212
+ const body = r.method === "POST" || r.method === "PUT" ? await readJsonBody(r) : Object.fromEntries(url2.searchParams.entries());
385213
+ const result = await handleRestRequest(routes, opts.dispatch, {
385214
+ method: r.method ?? "GET",
385215
+ path: url2.pathname,
385216
+ body
385217
+ });
385218
+ s.writeHead?.(result.status, { ...JSON_HEADERS, ...result.headers ?? {} });
385219
+ if (result.body === "" || result.body === void 0) s.end?.();
385220
+ else s.end?.(typeof result.body === "string" ? result.body : JSON.stringify(result.body));
385221
+ } catch (e) {
385222
+ s.writeHead?.(500, JSON_HEADERS);
385223
+ s.end?.(JSON.stringify({ error: "internal", message: e instanceof Error ? e.message : String(e) }));
385224
+ }
385225
+ };
385226
+ }
384228
385227
 
384229
385228
  // ../../packages/backend/src/services/Gateway/gatewayRateLimit.ts
384230
385229
  var GatewayRateLimiter = class {
@@ -392117,11 +393116,11 @@ function createObservability(deps) {
392117
393116
  const policyEngine = new AgtPolicyEngine({
392118
393117
  loadPolicy: async () => {
392119
393118
  const req = (0, import_node_module5.createRequire)(typeof __filename !== "undefined" ? __filename : import_meta8.url);
392120
- const fs23 = req("node:fs");
392121
- const path32 = req("node:path");
392122
- const policyPath = path32.join(".", "policy.yaml");
392123
- if (fs23.existsSync(policyPath)) {
392124
- return parsePolicyYaml(fs23.readFileSync(policyPath, "utf8"));
393119
+ const fs24 = req("node:fs");
393120
+ const path33 = req("node:path");
393121
+ const policyPath = path33.join(".", "policy.yaml");
393122
+ if (fs24.existsSync(policyPath)) {
393123
+ return parsePolicyYaml(fs24.readFileSync(policyPath, "utf8"));
392125
393124
  }
392126
393125
  return {
392127
393126
  name: "rterm-default",
@@ -392163,18 +393162,18 @@ function createObservability(deps) {
392163
393162
  const scanRoots = [pluginScanRoot, "./plugins"];
392164
393163
  try {
392165
393164
  const req = (0, import_node_module5.createRequire)(typeof __filename !== "undefined" ? __filename : import_meta8.url);
392166
- const fs23 = req("node:fs");
392167
- if (fs23.existsSync(bundlePluginRoot)) scanRoots.push(bundlePluginRoot);
393165
+ const fs24 = req("node:fs");
393166
+ if (fs24.existsSync(bundlePluginRoot)) scanRoots.push(bundlePluginRoot);
392168
393167
  } catch {
392169
393168
  }
392170
393169
  try {
392171
393170
  const req = (0, import_node_module5.createRequire)(typeof __filename !== "undefined" ? __filename : import_meta8.url);
392172
- const fs23 = req("node:fs");
392173
- const path32 = req("node:path");
393171
+ const fs24 = req("node:fs");
393172
+ const path33 = req("node:path");
392174
393173
  const resourcesPath = process.resourcesPath;
392175
393174
  if (resourcesPath) {
392176
- const resourcesPlugins = path32.join(resourcesPath, "plugins");
392177
- if (fs23.existsSync(resourcesPlugins)) scanRoots.push(resourcesPlugins);
393175
+ const resourcesPlugins = path33.join(resourcesPath, "plugins");
393176
+ if (fs24.existsSync(resourcesPlugins)) scanRoots.push(resourcesPlugins);
392178
393177
  }
392179
393178
  } catch {
392180
393179
  }
@@ -394861,9 +395860,9 @@ function numberFromEnv(name, fallback) {
394861
395860
  function resolveDataDir() {
394862
395861
  const custom3 = (import_node_process2.default.env.GYBACKEND_DATA_DIR || "").trim();
394863
395862
  if (custom3) {
394864
- return import_node_path28.default.resolve(custom3);
395863
+ return import_node_path29.default.resolve(custom3);
394865
395864
  }
394866
- return import_node_path28.default.join(import_node_process2.default.cwd(), ".gybackend-data");
395865
+ return import_node_path29.default.join(import_node_process2.default.cwd(), ".gybackend-data");
394867
395866
  }
394868
395867
  async function startGyBackend() {
394869
395868
  const dataDir = resolveDataDir();
@@ -394896,7 +395895,7 @@ async function startGyBackend() {
394896
395895
  const modelCapabilityService = new ModelCapabilityService();
394897
395896
  const imageAttachmentService = new ImageAttachmentService(dataDir);
394898
395897
  const terminalStateStore = new TerminalStateStore(
394899
- import_node_path28.default.join(dataDir, "terminal-tabs-state.json")
395898
+ import_node_path29.default.join(dataDir, "terminal-tabs-state.json")
394900
395899
  );
394901
395900
  const terminalService = new TerminalService({
394902
395901
  terminalStateStore
@@ -394984,6 +395983,31 @@ async function startGyBackend() {
394984
395983
  const agentRunLedger = new AgentRunLedger();
394985
395984
  agentRunLedger.markStaleRunsAborted(Date.now());
394986
395985
  agentService.setAgentRunLedger(agentRunLedger);
395986
+ const { CompoundingStore: CompoundingStore2 } = await Promise.resolve().then(() => (init_compoundingStore(), compoundingStore_exports));
395987
+ const compoundingStore = new CompoundingStore2();
395988
+ agentService.setCompoundingStore(compoundingStore);
395989
+ try {
395990
+ const { connectionIdentity: connectionIdentity2 } = await Promise.resolve().then(() => (init_compoundingKnowledge(), compoundingKnowledge_exports));
395991
+ const winrm = settingsService.getSettings()?.connections?.winrm ?? [];
395992
+ for (const c of winrm) {
395993
+ compoundingStore.upsertEstateFact({
395994
+ identity: connectionIdentity2({
395995
+ name: c.name,
395996
+ host: c.host,
395997
+ transport: c.transport,
395998
+ auth: c.auth,
395999
+ domain: c.domain
396000
+ }),
396001
+ host: c.host,
396002
+ role: /dc/i.test(c.name || "") ? "dc" : void 0,
396003
+ domain: c.domain,
396004
+ transport: c.transport,
396005
+ auth: c.auth
396006
+ });
396007
+ }
396008
+ } catch (e) {
396009
+ console.warn(`[gybackend] compounding estate seed skipped: ${e instanceof Error ? e.message : String(e)}`);
396010
+ }
394987
396011
  const changeLedger = new ChangeLedger();
394988
396012
  changeLedger.markStaleChangesAborted(Date.now());
394989
396013
  agentService.setChangeLedger(changeLedger);
@@ -395087,7 +396111,7 @@ async function startGyBackend() {
395087
396111
  console.warn("[gybackend] Plugin tool wiring skipped:", e instanceof Error ? e.message : String(e));
395088
396112
  });
395089
396113
  if (settingsService.getSettings().sessionLogging?.enabled) {
395090
- const logDir = import_node_path28.default.join(
396114
+ const logDir = import_node_path29.default.join(
395091
396115
  import_node_process2.default.env.GYSHELL_STORE_DIR || "",
395092
396116
  "session-logs"
395093
396117
  );
@@ -395205,21 +396229,21 @@ async function startGyBackend() {
395205
396229
  authFailureLimit: 5,
395206
396230
  authLockoutMs: 6e4
395207
396231
  });
395208
- const settingsDir = import_node_path28.default.dirname(settingsService.getSettingsPath?.() ?? "");
395209
- const backupsDir = settingsDir ? import_node_path28.default.join(settingsDir, "backups") : "";
396232
+ const settingsDir = import_node_path29.default.dirname(settingsService.getSettingsPath?.() ?? "");
396233
+ const backupsDir = settingsDir ? import_node_path29.default.join(settingsDir, "backups") : "";
395210
396234
  const settingsBackupService = new SettingsBackupService(
395211
396235
  backupsDir ? {
395212
- read: () => import_node_fs12.default.readFileSync(settingsService.getSettingsPath(), "utf8"),
395213
- write: (c) => import_node_fs12.default.writeFileSync(settingsService.getSettingsPath(), c),
395214
- listBackups: () => import_node_fs12.default.existsSync(backupsDir) ? import_node_fs12.default.readdirSync(backupsDir) : [],
395215
- readBackup: (n2) => import_node_fs12.default.readFileSync(import_node_path28.default.join(backupsDir, n2), "utf8"),
396236
+ read: () => import_node_fs13.default.readFileSync(settingsService.getSettingsPath(), "utf8"),
396237
+ write: (c) => import_node_fs13.default.writeFileSync(settingsService.getSettingsPath(), c),
396238
+ listBackups: () => import_node_fs13.default.existsSync(backupsDir) ? import_node_fs13.default.readdirSync(backupsDir) : [],
396239
+ readBackup: (n2) => import_node_fs13.default.readFileSync(import_node_path29.default.join(backupsDir, n2), "utf8"),
395216
396240
  writeBackup: (n2, c) => {
395217
- import_node_fs12.default.mkdirSync(backupsDir, { recursive: true });
395218
- import_node_fs12.default.writeFileSync(import_node_path28.default.join(backupsDir, n2), c);
396241
+ import_node_fs13.default.mkdirSync(backupsDir, { recursive: true });
396242
+ import_node_fs13.default.writeFileSync(import_node_path29.default.join(backupsDir, n2), c);
395219
396243
  },
395220
396244
  deleteBackup: (n2) => {
395221
- const p = import_node_path28.default.join(backupsDir, n2);
395222
- if (import_node_fs12.default.existsSync(p)) import_node_fs12.default.unlinkSync(p);
396245
+ const p = import_node_path29.default.join(backupsDir, n2);
396246
+ if (import_node_fs13.default.existsSync(p)) import_node_fs13.default.unlinkSync(p);
395223
396247
  }
395224
396248
  } : { read: () => "", write: () => {
395225
396249
  }, listBackups: () => [], readBackup: () => "", writeBackup: () => {
@@ -395267,51 +396291,8 @@ async function startGyBackend() {
395267
396291
  return await target.handleRequest(method, params);
395268
396292
  };
395269
396293
  const buildRestHttpRoutesSync = (opts) => {
395270
- const routes = defaultRestRoutes();
395271
- const staticRoutes = routes.filter((r) => !r.path.includes(":")).map((route) => ({
395272
- path: route.path,
395273
- handler: makeRestHandler(routes, opts)
395274
- }));
395275
- return staticRoutes;
396294
+ return [{ path: "/api/v1/*", handler: makeRestCatchAllHandler(opts) }];
395276
396295
  };
395277
- const makeRestHandler = (routes, opts) => {
395278
- return async (req, res) => {
395279
- const r = req;
395280
- const s = res;
395281
- try {
395282
- if (!await opts.isAuthorized(r)) {
395283
- s.writeHead?.(401, { "content-type": "application/json" });
395284
- s.end?.(JSON.stringify({ error: "unauthorized" }));
395285
- return;
395286
- }
395287
- const url2 = new URL(r.url ?? "/", "http://localhost");
395288
- const body = r.method === "POST" ? await readJsonBody(r) : Object.fromEntries(url2.searchParams.entries());
395289
- const result = await handleRestRequest(routes, opts.dispatch, {
395290
- method: r.method ?? "GET",
395291
- path: url2.pathname,
395292
- body
395293
- });
395294
- s.writeHead?.(result.status, { "content-type": "application/json" });
395295
- s.end?.(JSON.stringify(result.body));
395296
- } catch (e) {
395297
- s.writeHead?.(500, { "content-type": "application/json" });
395298
- s.end?.(JSON.stringify({ error: "internal", message: e instanceof Error ? e.message : String(e) }));
395299
- }
395300
- };
395301
- };
395302
- const readJsonBody = (req) => new Promise((resolve2) => {
395303
- let data = "";
395304
- req.on?.("data", (d) => {
395305
- data += String(d ?? "");
395306
- });
395307
- req.on?.("end", () => {
395308
- try {
395309
- resolve2(data ? JSON.parse(data) : {});
395310
- } catch {
395311
- resolve2({});
395312
- }
395313
- });
395314
- });
395315
396296
  const wsGatewayControlService = new WebSocketGatewayControlService({
395316
396297
  createAdapter: (host, port, ipFilter) => {
395317
396298
  const adapter = new WebSocketGatewayAdapter(gatewayService, {
@@ -395807,6 +396788,9 @@ async function startGyBackend() {
395807
396788
  console.log(
395808
396789
  `[gybackend] Live dashboard: http://${wsState.host}:${wsState.port}/dashboard`
395809
396790
  );
396791
+ console.log(
396792
+ `[gybackend] REST API: http://${wsState.host}:${wsState.port}/api/v1/health (OpenAPI /api/v1/openapi.json)`
396793
+ );
395810
396794
  } else {
395811
396795
  console.log("[gybackend] WebSocket RPC endpoint: disabled");
395812
396796
  }