rterm-backend 3.7.5 → 3.7.6

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 +1422 -517
  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,295 @@ 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 {
276401
+ filePath;
276402
+ db;
276403
+ constructor(options) {
276404
+ this.filePath = options?.filePath || import_node_path28.default.join(resolveHistoryStorageDir(), COMPOUNDING_DB_FILE);
276405
+ import_node_fs12.default.mkdirSync(import_node_path28.default.dirname(this.filePath), { recursive: true });
276406
+ this.db = openBetterSqlite3Database(this.filePath);
276407
+ this.db.pragma("journal_mode = WAL");
276408
+ this.db.exec(`
276409
+ CREATE TABLE IF NOT EXISTS lessons (
276410
+ fingerprint TEXT PRIMARY KEY,
276411
+ title TEXT NOT NULL,
276412
+ body TEXT NOT NULL,
276413
+ never_do TEXT NOT NULL,
276414
+ instead TEXT NOT NULL,
276415
+ tags TEXT NOT NULL DEFAULT '',
276416
+ extractor TEXT NOT NULL,
276417
+ occurrences INTEGER NOT NULL DEFAULT 1,
276418
+ first_seen_at INTEGER NOT NULL,
276419
+ last_seen_at INTEGER NOT NULL,
276420
+ last_run_id TEXT
276421
+ );
276422
+ CREATE TABLE IF NOT EXISTS estate_facts (
276423
+ identity TEXT PRIMARY KEY,
276424
+ host TEXT,
276425
+ role TEXT,
276426
+ domain TEXT,
276427
+ transport TEXT,
276428
+ auth TEXT,
276429
+ facts_json TEXT NOT NULL DEFAULT '{}',
276430
+ last_seen_at INTEGER NOT NULL
276431
+ );
276432
+ CREATE TABLE IF NOT EXISTS goals (
276433
+ id TEXT PRIMARY KEY,
276434
+ session_id TEXT NOT NULL,
276435
+ text TEXT NOT NULL,
276436
+ status TEXT NOT NULL,
276437
+ blocked_by TEXT,
276438
+ next_probe TEXT,
276439
+ updated_at INTEGER NOT NULL
276440
+ );
276441
+ CREATE INDEX IF NOT EXISTS idx_goals_session ON goals(session_id);
276442
+ CREATE TABLE IF NOT EXISTS probes (
276443
+ session_id TEXT NOT NULL,
276444
+ tag TEXT NOT NULL,
276445
+ hypothesis TEXT NOT NULL,
276446
+ command TEXT NOT NULL,
276447
+ ok INTEGER NOT NULL,
276448
+ at INTEGER NOT NULL,
276449
+ PRIMARY KEY (session_id, tag)
276450
+ );
276451
+ `);
276452
+ }
276453
+ recordLessons(lessons, runId) {
276454
+ const now = Date.now();
276455
+ const out = [];
276456
+ try {
276457
+ const sel = this.db.prepare("SELECT * FROM lessons WHERE fingerprint = ?");
276458
+ const ins = this.db.prepare(
276459
+ `INSERT INTO lessons (fingerprint, title, body, never_do, instead, tags, extractor, occurrences, first_seen_at, last_seen_at, last_run_id)
276460
+ VALUES (@fingerprint, @title, @body, @neverDo, @instead, @tags, @extractor, 1, @now, @now, @runId)`
276461
+ );
276462
+ const upd = this.db.prepare(
276463
+ `UPDATE lessons SET occurrences = occurrences + 1, last_seen_at = @now, last_run_id = @runId,
276464
+ title = @title, body = @body, never_do = @neverDo, instead = @instead WHERE fingerprint = @fingerprint`
276465
+ );
276466
+ for (const l of lessons) {
276467
+ const existing = sel.get(l.fingerprint);
276468
+ if (existing) {
276469
+ upd.run({
276470
+ fingerprint: l.fingerprint,
276471
+ now,
276472
+ runId: runId ?? null,
276473
+ title: l.title,
276474
+ body: l.body,
276475
+ neverDo: l.neverDo,
276476
+ instead: l.instead
276477
+ });
276478
+ } else {
276479
+ ins.run({
276480
+ fingerprint: l.fingerprint,
276481
+ title: l.title,
276482
+ body: l.body,
276483
+ neverDo: l.neverDo,
276484
+ instead: l.instead,
276485
+ tags: l.tags.join(","),
276486
+ extractor: l.extractor,
276487
+ now,
276488
+ runId: runId ?? null
276489
+ });
276490
+ }
276491
+ const row = sel.get(l.fingerprint);
276492
+ if (row) out.push(this.mapLesson(row));
276493
+ }
276494
+ } catch (err) {
276495
+ console.warn("[CompoundingStore] recordLessons failed:", err);
276496
+ }
276497
+ return out;
276498
+ }
276499
+ listLessons(limit2 = 50) {
276500
+ try {
276501
+ const rows = this.db.prepare("SELECT * FROM lessons ORDER BY last_seen_at DESC LIMIT ?").all(limit2);
276502
+ return rows.map((r) => this.mapLesson(r));
276503
+ } catch (err) {
276504
+ console.warn("[CompoundingStore] listLessons failed:", err);
276505
+ return [];
276506
+ }
276507
+ }
276508
+ upsertEstateFact(input) {
276509
+ try {
276510
+ const now = Date.now();
276511
+ this.db.prepare(
276512
+ `INSERT INTO estate_facts (identity, host, role, domain, transport, auth, facts_json, last_seen_at)
276513
+ VALUES (@identity, @host, @role, @domain, @transport, @auth, @facts, @now)
276514
+ ON CONFLICT(identity) DO UPDATE SET
276515
+ host = COALESCE(@host, host),
276516
+ role = COALESCE(@role, role),
276517
+ domain = COALESCE(@domain, domain),
276518
+ transport = COALESCE(@transport, transport),
276519
+ auth = COALESCE(@auth, auth),
276520
+ facts_json = CASE WHEN @facts = '{}' THEN facts_json ELSE @facts END,
276521
+ last_seen_at = @now`
276522
+ ).run({
276523
+ identity: input.identity,
276524
+ host: input.host ?? null,
276525
+ role: input.role ?? null,
276526
+ domain: input.domain ?? null,
276527
+ transport: input.transport ?? null,
276528
+ auth: input.auth ?? null,
276529
+ facts: JSON.stringify(input.facts || {}),
276530
+ now
276531
+ });
276532
+ } catch (err) {
276533
+ console.warn("[CompoundingStore] upsertEstateFact failed:", err);
276534
+ }
276535
+ }
276536
+ listEstateFacts() {
276537
+ try {
276538
+ const rows = this.db.prepare("SELECT * FROM estate_facts ORDER BY last_seen_at DESC").all();
276539
+ return rows.map((r) => ({
276540
+ identity: r.identity,
276541
+ host: r.host ?? void 0,
276542
+ role: r.role ?? void 0,
276543
+ domain: r.domain ?? void 0,
276544
+ transport: r.transport ?? void 0,
276545
+ auth: r.auth ?? void 0,
276546
+ factsJson: r.facts_json,
276547
+ lastSeenAt: r.last_seen_at
276548
+ }));
276549
+ } catch (err) {
276550
+ console.warn("[CompoundingStore] listEstateFacts failed:", err);
276551
+ return [];
276552
+ }
276553
+ }
276554
+ upsertGoal(input) {
276555
+ try {
276556
+ this.db.prepare(
276557
+ `INSERT INTO goals (id, session_id, text, status, blocked_by, next_probe, updated_at)
276558
+ VALUES (@id, @sessionId, @text, @status, @blockedBy, @nextProbe, @now)
276559
+ ON CONFLICT(id) DO UPDATE SET
276560
+ text = @text, status = @status, blocked_by = @blockedBy, next_probe = @nextProbe, updated_at = @now`
276561
+ ).run({
276562
+ id: input.id,
276563
+ sessionId: input.sessionId,
276564
+ text: input.text,
276565
+ status: input.status,
276566
+ blockedBy: input.blockedBy ?? null,
276567
+ nextProbe: input.nextProbe ?? null,
276568
+ now: Date.now()
276569
+ });
276570
+ } catch (err) {
276571
+ console.warn("[CompoundingStore] upsertGoal failed:", err);
276572
+ }
276573
+ }
276574
+ listGoals(sessionId) {
276575
+ try {
276576
+ const rows = this.db.prepare("SELECT * FROM goals WHERE session_id = ? ORDER BY updated_at DESC").all(sessionId);
276577
+ return rows.map((r) => ({
276578
+ id: r.id,
276579
+ sessionId: r.session_id,
276580
+ text: r.text,
276581
+ status: r.status,
276582
+ blockedBy: r.blocked_by ?? void 0,
276583
+ nextProbe: r.next_probe ?? void 0,
276584
+ updatedAt: r.updated_at
276585
+ }));
276586
+ } catch (err) {
276587
+ console.warn("[CompoundingStore] listGoals failed:", err);
276588
+ return [];
276589
+ }
276590
+ }
276591
+ recordProbe(sessionId, tag, hypothesis, command, ok) {
276592
+ try {
276593
+ this.db.prepare(
276594
+ `INSERT INTO probes (session_id, tag, hypothesis, command, ok, at)
276595
+ VALUES (@sessionId, @tag, @hypothesis, @command, @ok, @at)
276596
+ ON CONFLICT(session_id, tag) DO UPDATE SET hypothesis = @hypothesis, command = @command, ok = @ok, at = @at`
276597
+ ).run({
276598
+ sessionId,
276599
+ tag,
276600
+ hypothesis,
276601
+ command,
276602
+ ok: ok ? 1 : 0,
276603
+ at: Date.now()
276604
+ });
276605
+ } catch (err) {
276606
+ console.warn("[CompoundingStore] recordProbe failed:", err);
276607
+ }
276608
+ }
276609
+ hasProbe(sessionId, tag) {
276610
+ try {
276611
+ const row = this.db.prepare("SELECT 1 FROM probes WHERE session_id = ? AND tag = ?").get(sessionId, tag);
276612
+ return !!row;
276613
+ } catch (err) {
276614
+ console.warn("[CompoundingStore] hasProbe failed:", err);
276615
+ return false;
276616
+ }
276617
+ }
276618
+ /**
276619
+ * Prompt block: estate snapshot + never-do list from lessons (capped).
276620
+ */
276621
+ promptBlock(maxChars = 4e3) {
276622
+ try {
276623
+ const lessons = this.listLessons(20);
276624
+ const facts = this.listEstateFacts();
276625
+ const lines = ["# Compounding knowledge (auto)"];
276626
+ if (facts.length) {
276627
+ lines.push("", "## Estate");
276628
+ for (const f of facts.slice(0, 12)) {
276629
+ const bits = [f.identity];
276630
+ if (f.role) bits.push(f.role);
276631
+ if (f.domain) bits.push(f.domain);
276632
+ if (f.transport || f.auth) bits.push([f.transport, f.auth].filter(Boolean).join("/"));
276633
+ lines.push(`- ${bits.join(" \xB7 ")}`);
276634
+ }
276635
+ }
276636
+ if (lessons.length) {
276637
+ lines.push("", "## Never-do (from prior failures)");
276638
+ for (const l of lessons.slice(0, 12)) {
276639
+ lines.push(`- [${l.fingerprint} \xD7${l.occurrences}] NEVER: ${l.neverDo}`);
276640
+ lines.push(` INSTEAD: ${l.instead}`);
276641
+ }
276642
+ }
276643
+ const text = lines.join("\n");
276644
+ return text.length > maxChars ? text.slice(0, maxChars) + "\n\u2026" : text;
276645
+ } catch {
276646
+ return "";
276647
+ }
276648
+ }
276649
+ close() {
276650
+ try {
276651
+ this.db.close();
276652
+ } catch {
276653
+ }
276654
+ }
276655
+ mapLesson(r) {
276656
+ return {
276657
+ fingerprint: r.fingerprint,
276658
+ title: r.title,
276659
+ body: r.body,
276660
+ neverDo: r.never_do,
276661
+ instead: r.instead,
276662
+ tags: r.tags,
276663
+ extractor: r.extractor,
276664
+ occurrences: r.occurrences,
276665
+ firstSeenAt: r.first_seen_at,
276666
+ lastSeenAt: r.last_seen_at,
276667
+ lastRunId: r.last_run_id ?? void 0
276668
+ };
276669
+ }
276670
+ };
276671
+ }
276672
+ });
276673
+
276092
276674
  // ../../node_modules/@nats-io/nats-core/lib/encoders.js
276093
276675
  var require_encoders = __commonJS({
276094
276676
  "../../node_modules/@nats-io/nats-core/lib/encoders.js"(exports2) {
@@ -284840,7 +285422,7 @@ var require_ws_transport = __commonJS({
284840
285422
  let protocol;
284841
285423
  let port;
284842
285424
  const host = url2.hostname;
284843
- const path32 = url2.pathname;
285425
+ const path33 = url2.pathname;
284844
285426
  const search = url2.search || "";
284845
285427
  switch (srcProto) {
284846
285428
  case "http:":
@@ -284860,7 +285442,7 @@ var require_ws_transport = __commonJS({
284860
285442
  protocol = encrypted === true ? "wss:" : "ws:";
284861
285443
  break;
284862
285444
  }
284863
- return `${protocol}//${host}:${port}${path32}${search}`;
285445
+ return `${protocol}//${host}:${port}${path33}${search}`;
284864
285446
  }
284865
285447
  function wsconnect(opts = {}) {
284866
285448
  (0, transport_1.setTransportFactory)({
@@ -286705,11 +287287,11 @@ var require_jsmconsumer_api = __commonJS({
286705
287287
  consumerName = cfg.name ?? cfg.durable_name ?? "";
286706
287288
  }
286707
287289
  if (consumerName !== "") {
286708
- let fs23 = cfg.filter_subject ?? void 0;
286709
- if (fs23 === ">") {
286710
- fs23 = void 0;
287290
+ let fs24 = cfg.filter_subject ?? void 0;
287291
+ if (fs24 === ">") {
287292
+ fs24 = void 0;
286711
287293
  }
286712
- subj = fs23 !== void 0 ? `${this.prefix}.CONSUMER.CREATE.${stream}.${consumerName}.${fs23}` : `${this.prefix}.CONSUMER.CREATE.${stream}.${consumerName}`;
287294
+ subj = fs24 !== void 0 ? `${this.prefix}.CONSUMER.CREATE.${stream}.${consumerName}.${fs24}` : `${this.prefix}.CONSUMER.CREATE.${stream}.${consumerName}`;
286713
287295
  } else {
286714
287296
  subj = cfg.durable_name ? `${this.prefix}.CONSUMER.DURABLE.CREATE.${stream}.${cfg.durable_name}` : `${this.prefix}.CONSUMER.CREATE.${stream}`;
286715
287297
  }
@@ -291259,8 +291841,8 @@ var init_natsEventBus = __esm({
291259
291841
  });
291260
291842
 
291261
291843
  // ../../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);
291844
+ var import_node_path29 = __toESM(require("node:path"), 1);
291845
+ var import_node_fs13 = __toESM(require("node:fs"), 1);
291264
291846
  var import_node_process2 = __toESM(require("node:process"), 1);
291265
291847
 
291266
291848
  // ../../packages/backend/src/services/TerminalService.ts
@@ -293293,18 +293875,18 @@ var SSHBackend = class _SSHBackend {
293293
293875
  });
293294
293876
  return info.socket;
293295
293877
  }
293296
- async buildConnectSocketIfNeeded(sshConfig, emit10) {
293878
+ async buildConnectSocketIfNeeded(sshConfig, emit11) {
293297
293879
  if (sshConfig.jumpHost) {
293298
293880
  const jumpId = `[Jump:${sshConfig.jumpHost.host}]`;
293299
293881
  console.log(`${jumpId} Starting jump host connection flow...`);
293300
- emit10(
293882
+ emit11(
293301
293883
  `\x1B[36m\u25B9 ${jumpId} Establishing tunnel via jump host ${sshConfig.jumpHost.host}...\x1B[0m\r
293302
293884
  `
293303
293885
  );
293304
293886
  const jumpClient = new (loadSsh2()).Client();
293305
293887
  const jumpSock = await this.buildConnectSocketIfNeeded(
293306
293888
  sshConfig.jumpHost,
293307
- emit10
293889
+ emit11
293308
293890
  );
293309
293891
  if (jumpSock) {
293310
293892
  console.log(
@@ -293348,7 +293930,7 @@ var SSHBackend = class _SSHBackend {
293348
293930
  });
293349
293931
  jumpClient.connect(jumpConnectConfig);
293350
293932
  });
293351
- emit10(
293933
+ emit11(
293352
293934
  `\x1B[32m\u2714 ${jumpId} Jump host ready. Requesting forward to target ${sshConfig.host}:${sshConfig.port}...\x1B[0m\r
293353
293935
  `
293354
293936
  );
@@ -293664,25 +294246,25 @@ var SSHBackend = class _SSHBackend {
293664
294246
  };
293665
294247
  this.sessions.set(config2.id, instance);
293666
294248
  (async () => {
293667
- const emit10 = (data) => {
294249
+ const emit11 = (data) => {
293668
294250
  instance.dataCallbacks.forEach((cb) => cb(data));
293669
294251
  };
293670
294252
  const emitExit = (code) => {
293671
294253
  this.emitExitOnce(config2.id, instance, code);
293672
294254
  };
293673
294255
  client2.on("ready", async () => {
293674
- emit10("\x1B[2J\x1B[H\x1B[32m\u2714 Connection established.\x1B[0m\r\n");
294256
+ emit11("\x1B[2J\x1B[H\x1B[32m\u2714 Connection established.\x1B[0m\r\n");
293675
294257
  console.log(
293676
294258
  `[SSH] Connection ready for ${sshConfig.host}:${sshConfig.port}`
293677
294259
  );
293678
294260
  const rawShell = isRawShellPreset(sshConfig.algorithmsPreset);
293679
294261
  try {
293680
- emit10("\x1B[36m\u25B9 Setting up port forwards...\x1B[0m\r\n");
294262
+ emit11("\x1B[36m\u25B9 Setting up port forwards...\x1B[0m\r\n");
293681
294263
  console.log(`[SSH] Setting up port forwards...`);
293682
294264
  await this.setupPortForwards(instance, sshConfig);
293683
294265
  } catch (e) {
293684
294266
  console.error(`[SSH] Port forward setup failed:`, e);
293685
- emit10(`\x1B[31m\u2718 Port forward failed: ${e.message}\x1B[0m\r
294267
+ emit11(`\x1B[31m\u2718 Port forward failed: ${e.message}\x1B[0m\r
293686
294268
  `);
293687
294269
  }
293688
294270
  if (rawShell) {
@@ -293692,7 +294274,7 @@ var SSHBackend = class _SSHBackend {
293692
294274
  );
293693
294275
  } else {
293694
294276
  try {
293695
- emit10("\x1B[36m\u25B9 Detecting remote OS...\x1B[0m\r\n");
294277
+ emit11("\x1B[36m\u25B9 Detecting remote OS...\x1B[0m\r\n");
293696
294278
  console.log(`[SSH] Detecting remote OS...`);
293697
294279
  const uname = await this.execCollect(client2, "uname -s");
293698
294280
  const u = (uname.stdout || uname.stderr || "").toLowerCase();
@@ -293712,13 +294294,13 @@ var SSHBackend = class _SSHBackend {
293712
294294
  if (!instance.remoteOs) instance.remoteOs = "unix";
293713
294295
  console.log(`[SSH] Remote OS detected: ${instance.remoteOs}`);
293714
294296
  try {
293715
- emit10("\x1B[36m\u25B9 Initializing SFTP channel...\x1B[0m\r\n");
294297
+ emit11("\x1B[36m\u25B9 Initializing SFTP channel...\x1B[0m\r\n");
293716
294298
  await this.initializeSftp(instance);
293717
- emit10("\x1B[32m\u2714 SFTP channel ready.\x1B[0m\r\n");
294299
+ emit11("\x1B[32m\u2714 SFTP channel ready.\x1B[0m\r\n");
293718
294300
  } catch (error40) {
293719
294301
  const message = error40 instanceof Error ? error40.message : String(error40);
293720
294302
  instance.sftpInitError = message;
293721
- emit10(
294303
+ emit11(
293722
294304
  `\x1B[33m\u26A0 SFTP unavailable: ${message}. File panel features may be limited.\x1B[0m\r
293723
294305
  `
293724
294306
  );
@@ -293731,7 +294313,7 @@ var SSHBackend = class _SSHBackend {
293731
294313
  }
293732
294314
  }
293733
294315
  }
293734
- emit10("\x1B[36m\u25B9 Opening interactive shell...\x1B[0m\r\n");
294316
+ emit11("\x1B[36m\u25B9 Opening interactive shell...\x1B[0m\r\n");
293735
294317
  console.log(`[SSH] Opening interactive shell...`);
293736
294318
  const initialWindowSize = this.resolveRequestedWindowSize(instance, {
293737
294319
  cols: config2.cols,
@@ -293761,7 +294343,7 @@ var SSHBackend = class _SSHBackend {
293761
294343
  console.error(`[SSH] Failed to open shell:`, err);
293762
294344
  instance.initializationState = "failed";
293763
294345
  instance.isInitializing = false;
293764
- emit10(`\x1B[31m\u2718 Failed to open shell: ${err.message}\x1B[0m\r
294346
+ emit11(`\x1B[31m\u2718 Failed to open shell: ${err.message}\x1B[0m\r
293765
294347
  `);
293766
294348
  emitExit(-1);
293767
294349
  return;
@@ -293771,7 +294353,7 @@ var SSHBackend = class _SSHBackend {
293771
294353
  if (rawShell) {
293772
294354
  instance.initializationState = "ready";
293773
294355
  instance.isInitializing = false;
293774
- emit10("\x1B[32m\u2714 Shell ready.\x1B[0m\r\n");
294356
+ emit11("\x1B[32m\u2714 Shell ready.\x1B[0m\r\n");
293775
294357
  console.log(
293776
294358
  `[SSH] Raw-shell mode: shell ready immediately (preset=${sshConfig.algorithmsPreset}).`
293777
294359
  );
@@ -293779,14 +294361,14 @@ var SSHBackend = class _SSHBackend {
293779
294361
  const chunk2 = data.toString();
293780
294362
  const sanitizedChunk = this.stripReadyMarker(chunk2);
293781
294363
  this.consumeOscMarkers(instance, sanitizedChunk);
293782
- if (sanitizedChunk) emit10(sanitizedChunk);
294364
+ if (sanitizedChunk) emit11(sanitizedChunk);
293783
294365
  });
293784
294366
  stream.on("close", async (code) => {
293785
294367
  emitExit(typeof code === "number" ? code : 0);
293786
294368
  });
293787
294369
  return;
293788
294370
  }
293789
- emit10("\x1B[36m\u25B9 Initializing shell integration...\x1B[0m\r\n");
294371
+ emit11("\x1B[36m\u25B9 Initializing shell integration...\x1B[0m\r\n");
293790
294372
  console.log(
293791
294373
  `[SSH] Shell stream opened. Starting robust initialization...`
293792
294374
  );
@@ -293832,7 +294414,7 @@ var SSHBackend = class _SSHBackend {
293832
294414
  if (retryCount >= maxRetries) {
293833
294415
  instance.initializationState = "failed";
293834
294416
  instance.isInitializing = false;
293835
- emit10(
294417
+ emit11(
293836
294418
  "\x1B[31m\u2718 Initialization failed. Entering fallback mode.\x1B[0m\r\n"
293837
294419
  );
293838
294420
  console.error(
@@ -293841,7 +294423,7 @@ var SSHBackend = class _SSHBackend {
293841
294423
  clearInterval(watchdogInterval);
293842
294424
  return;
293843
294425
  }
293844
- emit10(
294426
+ emit11(
293845
294427
  `\x1B[33m\u26A0 Initialization timeout, retrying (${retryCount}/${maxRetries})...\x1B[0m\r
293846
294428
  `
293847
294429
  );
@@ -293855,7 +294437,7 @@ var SSHBackend = class _SSHBackend {
293855
294437
  if (instance.isInitializing) {
293856
294438
  instance.buffer += chunk2;
293857
294439
  if (instance.buffer.includes(GYSHELL_READY_MARKER2)) {
293858
- emit10("\x1B[2J\x1B[H");
294440
+ emit11("\x1B[2J\x1B[H");
293859
294441
  isReadySent = true;
293860
294442
  clearInterval(watchdogInterval);
293861
294443
  const sawContinuation = /(?:\r?\n)>>\s*\r?\n/.test(instance.buffer) || instance.buffer.trimEnd().endsWith("\n>>") || instance.buffer.trimEnd().endsWith("\r\n>>");
@@ -293866,7 +294448,7 @@ var SSHBackend = class _SSHBackend {
293866
294448
  const realContent = this.stripReadyMarker(
293867
294449
  parts.slice(1).join(GYSHELL_READY_MARKER2)
293868
294450
  ).trimStart();
293869
- if (realContent) emit10(realContent);
294451
+ if (realContent) emit11(realContent);
293870
294452
  }
293871
294453
  instance.buffer = "";
293872
294454
  if (sawContinuation && instance.remoteOs === "windows" && instance.stream) {
@@ -293882,7 +294464,7 @@ var SSHBackend = class _SSHBackend {
293882
294464
  const sanitizedChunk = this.stripReadyMarker(chunk2);
293883
294465
  this.consumeOscMarkers(instance, sanitizedChunk);
293884
294466
  if (sanitizedChunk) {
293885
- emit10(sanitizedChunk);
294467
+ emit11(sanitizedChunk);
293886
294468
  }
293887
294469
  }
293888
294470
  });
@@ -293896,7 +294478,7 @@ var SSHBackend = class _SSHBackend {
293896
294478
  console.error(`[SSH] Client error:`, err);
293897
294479
  instance.initializationState = "failed";
293898
294480
  instance.isInitializing = false;
293899
- emit10(`\x1B[31m\u2718 SSH Error: ${err.message}\x1B[0m\r
294481
+ emit11(`\x1B[31m\u2718 SSH Error: ${err.message}\x1B[0m\r
293900
294482
  `);
293901
294483
  emitExit(-1);
293902
294484
  });
@@ -293919,7 +294501,7 @@ var SSHBackend = class _SSHBackend {
293919
294501
  sshConfig.privateKeyPath
293920
294502
  );
293921
294503
  } catch (e) {
293922
- emit10(
294504
+ emit11(
293923
294505
  `\x1B[31m\u2718 Failed to read private key: ${e.message}\x1B[0m\r
293924
294506
  `
293925
294507
  );
@@ -293931,19 +294513,19 @@ var SSHBackend = class _SSHBackend {
293931
294513
  }
293932
294514
  try {
293933
294515
  await new Promise((r) => setTimeout(r, 50));
293934
- emit10(
294516
+ emit11(
293935
294517
  `\x1B[36m\u25B9 Connecting to ${sshConfig.host}:${sshConfig.port}...\x1B[0m\r
293936
294518
  `
293937
294519
  );
293938
294520
  console.log(
293939
294521
  `[SSH] Attempting to connect to ${sshConfig.host}:${sshConfig.port}...`
293940
294522
  );
293941
- const sock = await this.buildConnectSocketIfNeeded(sshConfig, emit10);
294523
+ const sock = await this.buildConnectSocketIfNeeded(sshConfig, emit11);
293942
294524
  if (sock) {
293943
294525
  console.log(
293944
294526
  `[SSH] SUCCESS: Connection to ${sshConfig.host} will be tunneled through sock (Jump Host/Proxy).`
293945
294527
  );
293946
- emit10(
294528
+ emit11(
293947
294529
  "\x1B[36m\u25B9 [Final] Using tunnel socket for target connection...\x1B[0m\r\n"
293948
294530
  );
293949
294531
  connectConfig.sock = sock;
@@ -293957,7 +294539,7 @@ var SSHBackend = class _SSHBackend {
293957
294539
  const errMsg = e instanceof Error ? e.message : String(e);
293958
294540
  instance.initializationState = "failed";
293959
294541
  instance.isInitializing = false;
293960
- emit10(`\x1B[31m\u2718 Connection failed: ${errMsg}\x1B[0m\r
294542
+ emit11(`\x1B[31m\u2718 Connection failed: ${errMsg}\x1B[0m\r
293961
294543
  `);
293962
294544
  emitExit(-1);
293963
294545
  }
@@ -296408,11 +296990,11 @@ Run commands with exec_command / run_fleet_command. Interactive TUI apps are not
296408
296990
  var import_node_crypto5 = require("node:crypto");
296409
296991
  var injectedSerial = null;
296410
296992
  var lazySerial;
296411
- function constructPort(Ctor, path32, opts) {
296993
+ function constructPort(Ctor, path33, opts) {
296412
296994
  try {
296413
- return new Ctor(path32, opts);
296995
+ return new Ctor(path33, opts);
296414
296996
  } catch (e) {
296415
- if (e instanceof TypeError) return new Ctor({ path: path32, ...opts });
296997
+ if (e instanceof TypeError) return new Ctor({ path: path33, ...opts });
296416
296998
  throw e;
296417
296999
  }
296418
297000
  }
@@ -296430,7 +297012,7 @@ var SerialBackend = class {
296430
297012
  try {
296431
297013
  const mod = require("serialport");
296432
297014
  const Ctor = typeof mod?.SerialPort === "function" ? mod.SerialPort : mod;
296433
- lazySerial = ((path32, opts) => constructPort(Ctor, path32, opts));
297015
+ lazySerial = ((path33, opts) => constructPort(Ctor, path33, opts));
296434
297016
  } catch {
296435
297017
  lazySerial = null;
296436
297018
  }
@@ -300884,8 +301466,8 @@ function shallowCopy(obj) {
300884
301466
  }
300885
301467
  function replaceSecrets(root, secretsMap) {
300886
301468
  const result = shallowCopy(root);
300887
- for (const [path32, secretId] of Object.entries(secretsMap)) {
300888
- const [last, ...partsReverse] = path32.split(".").reverse();
301469
+ for (const [path33, secretId] of Object.entries(secretsMap)) {
301470
+ const [last, ...partsReverse] = path33.split(".").reverse();
300889
301471
  let current = result;
300890
301472
  for (const part of partsReverse.reverse()) {
300891
301473
  if (current[part] === void 0) break;
@@ -305949,9 +306531,9 @@ var Client = class _Client {
305949
306531
  }
305950
306532
  return headers;
305951
306533
  }
305952
- _getPlatformEndpointPath(path32) {
306534
+ _getPlatformEndpointPath(path33) {
305953
306535
  const needsV1Prefix = this.apiUrl.slice(-3) !== "/v1" && this.apiUrl.slice(-4) !== "/v1/";
305954
- return needsV1Prefix ? `/v1/platform/${path32}` : `/platform/${path32}`;
306536
+ return needsV1Prefix ? `/v1/platform/${path33}` : `/platform/${path33}`;
305955
306537
  }
305956
306538
  async processInputs(inputs) {
305957
306539
  if (this.hideInputs === false) {
@@ -305987,9 +306569,9 @@ var Client = class _Client {
305987
306569
  }
305988
306570
  return runParams;
305989
306571
  }
305990
- async _getResponse(path32, queryParams) {
306572
+ async _getResponse(path33, queryParams) {
305991
306573
  const paramsString = queryParams?.toString() ?? "";
305992
- const url2 = `${this.apiUrl}${path32}?${paramsString}`;
306574
+ const url2 = `${this.apiUrl}${path33}?${paramsString}`;
305993
306575
  const response = await this.caller.call(async () => {
305994
306576
  const res = await this._fetch(url2, {
305995
306577
  method: "GET",
@@ -305997,22 +306579,22 @@ var Client = class _Client {
305997
306579
  signal: AbortSignal.timeout(this.timeout_ms),
305998
306580
  ...this.fetchOptions
305999
306581
  });
306000
- await raiseForStatus(res, `fetch ${path32}`);
306582
+ await raiseForStatus(res, `fetch ${path33}`);
306001
306583
  return res;
306002
306584
  });
306003
306585
  return response;
306004
306586
  }
306005
- async _get(path32, queryParams) {
306006
- const response = await this._getResponse(path32, queryParams);
306587
+ async _get(path33, queryParams) {
306588
+ const response = await this._getResponse(path33, queryParams);
306007
306589
  return response.json();
306008
306590
  }
306009
- async *_getPaginated(path32, queryParams = new URLSearchParams(), transform2) {
306591
+ async *_getPaginated(path33, queryParams = new URLSearchParams(), transform2) {
306010
306592
  let offset = Number(queryParams.get("offset")) || 0;
306011
306593
  const limit2 = Number(queryParams.get("limit")) || 100;
306012
306594
  while (true) {
306013
306595
  queryParams.set("offset", String(offset));
306014
306596
  queryParams.set("limit", String(limit2));
306015
- const url2 = `${this.apiUrl}${path32}?${queryParams}`;
306597
+ const url2 = `${this.apiUrl}${path33}?${queryParams}`;
306016
306598
  const response = await this.caller.call(async () => {
306017
306599
  const res = await this._fetch(url2, {
306018
306600
  method: "GET",
@@ -306020,7 +306602,7 @@ var Client = class _Client {
306020
306602
  signal: AbortSignal.timeout(this.timeout_ms),
306021
306603
  ...this.fetchOptions
306022
306604
  });
306023
- await raiseForStatus(res, `fetch ${path32}`);
306605
+ await raiseForStatus(res, `fetch ${path33}`);
306024
306606
  return res;
306025
306607
  });
306026
306608
  const items = transform2 ? transform2(await response.json()) : await response.json();
@@ -306034,19 +306616,19 @@ var Client = class _Client {
306034
306616
  offset += items.length;
306035
306617
  }
306036
306618
  }
306037
- async *_getCursorPaginatedList(path32, body = null, requestMethod = "POST", dataKey = "runs") {
306619
+ async *_getCursorPaginatedList(path33, body = null, requestMethod = "POST", dataKey = "runs") {
306038
306620
  const bodyParams = body ? { ...body } : {};
306039
306621
  while (true) {
306040
306622
  const body2 = JSON.stringify(bodyParams);
306041
306623
  const response = await this.caller.call(async () => {
306042
- const res = await this._fetch(`${this.apiUrl}${path32}`, {
306624
+ const res = await this._fetch(`${this.apiUrl}${path33}`, {
306043
306625
  method: requestMethod,
306044
306626
  headers: { ...this.headers, "Content-Type": "application/json" },
306045
306627
  signal: AbortSignal.timeout(this.timeout_ms),
306046
306628
  ...this.fetchOptions,
306047
306629
  body: body2
306048
306630
  });
306049
- await raiseForStatus(res, `fetch ${path32}`);
306631
+ await raiseForStatus(res, `fetch ${path33}`);
306050
306632
  return res;
306051
306633
  });
306052
306634
  const responseBody = await response.json();
@@ -306975,8 +307557,8 @@ Context: ${context2}`);
306975
307557
  limit: Number(limit2) || 100
306976
307558
  };
306977
307559
  let currentOffset = Number(offset) || 0;
306978
- const path32 = "/runs/group";
306979
- const url2 = `${this.apiUrl}${path32}`;
307560
+ const path33 = "/runs/group";
307561
+ const url2 = `${this.apiUrl}${path33}`;
306980
307562
  while (true) {
306981
307563
  const currentBody = {
306982
307564
  ...baseBody,
@@ -306992,7 +307574,7 @@ Context: ${context2}`);
306992
307574
  ...this.fetchOptions,
306993
307575
  body
306994
307576
  });
306995
- await raiseForStatus(res, `Failed to fetch ${path32}`);
307577
+ await raiseForStatus(res, `Failed to fetch ${path33}`);
306996
307578
  return res;
306997
307579
  });
306998
307580
  const items = await response.json();
@@ -307309,20 +307891,20 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307309
307891
  return result;
307310
307892
  }
307311
307893
  async hasProject({ projectId, projectName }) {
307312
- let path32 = "/sessions";
307894
+ let path33 = "/sessions";
307313
307895
  const params = new URLSearchParams();
307314
307896
  if (projectId !== void 0 && projectName !== void 0) {
307315
307897
  throw new Error("Must provide either projectName or projectId, not both");
307316
307898
  } else if (projectId !== void 0) {
307317
307899
  assertUuid(projectId);
307318
- path32 += `/${projectId}`;
307900
+ path33 += `/${projectId}`;
307319
307901
  } else if (projectName !== void 0) {
307320
307902
  params.append("name", projectName);
307321
307903
  } else {
307322
307904
  throw new Error("Must provide projectName or projectId");
307323
307905
  }
307324
307906
  const response = await this.caller.call(async () => {
307325
- const res = await this._fetch(`${this.apiUrl}${path32}?${params}`, {
307907
+ const res = await this._fetch(`${this.apiUrl}${path33}?${params}`, {
307326
307908
  method: "GET",
307327
307909
  headers: this.headers,
307328
307910
  signal: AbortSignal.timeout(this.timeout_ms),
@@ -307345,13 +307927,13 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307345
307927
  }
307346
307928
  }
307347
307929
  async readProject({ projectId, projectName, includeStats }) {
307348
- let path32 = "/sessions";
307930
+ let path33 = "/sessions";
307349
307931
  const params = new URLSearchParams();
307350
307932
  if (projectId !== void 0 && projectName !== void 0) {
307351
307933
  throw new Error("Must provide either projectName or projectId, not both");
307352
307934
  } else if (projectId !== void 0) {
307353
307935
  assertUuid(projectId);
307354
- path32 += `/${projectId}`;
307936
+ path33 += `/${projectId}`;
307355
307937
  } else if (projectName !== void 0) {
307356
307938
  params.append("name", projectName);
307357
307939
  } else {
@@ -307360,7 +307942,7 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307360
307942
  if (includeStats !== void 0) {
307361
307943
  params.append("include_stats", includeStats.toString());
307362
307944
  }
307363
- const response = await this._get(path32, params);
307945
+ const response = await this._get(path33, params);
307364
307946
  let result;
307365
307947
  if (Array.isArray(response)) {
307366
307948
  if (response.length === 0) {
@@ -307523,19 +308105,19 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307523
308105
  return result;
307524
308106
  }
307525
308107
  async readDataset({ datasetId, datasetName }) {
307526
- let path32 = "/datasets";
308108
+ let path33 = "/datasets";
307527
308109
  const params = new URLSearchParams({ limit: "1" });
307528
308110
  if (datasetId && datasetName) {
307529
308111
  throw new Error("Must provide either datasetName or datasetId, not both");
307530
308112
  } else if (datasetId) {
307531
308113
  assertUuid(datasetId);
307532
- path32 += `/${datasetId}`;
308114
+ path33 += `/${datasetId}`;
307533
308115
  } else if (datasetName) {
307534
308116
  params.append("name", datasetName);
307535
308117
  } else {
307536
308118
  throw new Error("Must provide datasetName or datasetId");
307537
308119
  }
307538
- const response = await this._get(path32, params);
308120
+ const response = await this._get(path33, params);
307539
308121
  let result;
307540
308122
  if (Array.isArray(response)) {
307541
308123
  if (response.length === 0) {
@@ -307579,20 +308161,20 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307579
308161
  return response;
307580
308162
  }
307581
308163
  async readDatasetOpenaiFinetuning({ datasetId, datasetName }) {
307582
- const path32 = "/datasets";
308164
+ const path33 = "/datasets";
307583
308165
  if (datasetId !== void 0) {
307584
308166
  } else if (datasetName !== void 0) {
307585
308167
  datasetId = (await this.readDataset({ datasetName })).id;
307586
308168
  } else {
307587
308169
  throw new Error("Must provide either datasetName or datasetId");
307588
308170
  }
307589
- const response = await this._getResponse(`${path32}/${datasetId}/openai_ft`);
308171
+ const response = await this._getResponse(`${path33}/${datasetId}/openai_ft`);
307590
308172
  const datasetText = await response.text();
307591
308173
  const dataset = datasetText.trim().split("\n").map((line) => JSON.parse(line));
307592
308174
  return dataset;
307593
308175
  }
307594
308176
  async *listDatasets({ limit: limit2 = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata } = {}) {
307595
- const path32 = "/datasets";
308177
+ const path33 = "/datasets";
307596
308178
  const params = new URLSearchParams({
307597
308179
  limit: limit2.toString(),
307598
308180
  offset: offset.toString()
@@ -307611,7 +308193,7 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307611
308193
  if (metadata !== void 0) {
307612
308194
  params.append("metadata", JSON.stringify(metadata));
307613
308195
  }
307614
- for await (const datasets of this._getPaginated(path32, params)) {
308196
+ for await (const datasets of this._getPaginated(path33, params)) {
307615
308197
  yield* datasets;
307616
308198
  }
307617
308199
  }
@@ -307680,7 +308262,7 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307680
308262
  });
307681
308263
  }
307682
308264
  async deleteDataset({ datasetId, datasetName }) {
307683
- let path32 = "/datasets";
308265
+ let path33 = "/datasets";
307684
308266
  let datasetId_ = datasetId;
307685
308267
  if (datasetId !== void 0 && datasetName !== void 0) {
307686
308268
  throw new Error("Must provide either datasetName or datasetId, not both");
@@ -307690,18 +308272,18 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307690
308272
  }
307691
308273
  if (datasetId_ !== void 0) {
307692
308274
  assertUuid(datasetId_);
307693
- path32 += `/${datasetId_}`;
308275
+ path33 += `/${datasetId_}`;
307694
308276
  } else {
307695
308277
  throw new Error("Must provide datasetName or datasetId");
307696
308278
  }
307697
308279
  await this.caller.call(async () => {
307698
- const res = await this._fetch(this.apiUrl + path32, {
308280
+ const res = await this._fetch(this.apiUrl + path33, {
307699
308281
  method: "DELETE",
307700
308282
  headers: this.headers,
307701
308283
  signal: AbortSignal.timeout(this.timeout_ms),
307702
308284
  ...this.fetchOptions
307703
308285
  });
307704
- await raiseForStatus(res, `delete ${path32}`, true);
308286
+ await raiseForStatus(res, `delete ${path33}`, true);
307705
308287
  return res;
307706
308288
  });
307707
308289
  }
@@ -307892,8 +308474,8 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307892
308474
  }
307893
308475
  async readExample(exampleId) {
307894
308476
  assertUuid(exampleId);
307895
- const path32 = `/examples/${exampleId}`;
307896
- const rawExample = await this._get(path32);
308477
+ const path33 = `/examples/${exampleId}`;
308478
+ const rawExample = await this._get(path33);
307897
308479
  const { attachment_urls, ...rest } = rawExample;
307898
308480
  const example = rest;
307899
308481
  if (attachment_urls) {
@@ -307976,15 +308558,15 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307976
308558
  }
307977
308559
  async deleteExample(exampleId) {
307978
308560
  assertUuid(exampleId);
307979
- const path32 = `/examples/${exampleId}`;
308561
+ const path33 = `/examples/${exampleId}`;
307980
308562
  await this.caller.call(async () => {
307981
- const res = await this._fetch(this.apiUrl + path32, {
308563
+ const res = await this._fetch(this.apiUrl + path33, {
307982
308564
  method: "DELETE",
307983
308565
  headers: this.headers,
307984
308566
  signal: AbortSignal.timeout(this.timeout_ms),
307985
308567
  ...this.fetchOptions
307986
308568
  });
307987
- await raiseForStatus(res, `delete ${path32}`, true);
308569
+ await raiseForStatus(res, `delete ${path33}`, true);
307988
308570
  return res;
307989
308571
  });
307990
308572
  }
@@ -307997,9 +308579,9 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
307997
308579
  async deleteExamples(exampleIds, options) {
307998
308580
  exampleIds.forEach((id) => assertUuid(id));
307999
308581
  if (options?.hardDelete) {
308000
- const path32 = this._getPlatformEndpointPath("datasets/examples/delete");
308582
+ const path33 = this._getPlatformEndpointPath("datasets/examples/delete");
308001
308583
  await this.caller.call(async () => {
308002
- const res = await this._fetch(`${this.apiUrl}${path32}`, {
308584
+ const res = await this._fetch(`${this.apiUrl}${path33}`, {
308003
308585
  method: "POST",
308004
308586
  headers: { ...this.headers, "Content-Type": "application/json" },
308005
308587
  body: JSON.stringify({
@@ -308233,21 +308815,21 @@ Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecifie
308233
308815
  }
308234
308816
  async readFeedback(feedbackId) {
308235
308817
  assertUuid(feedbackId);
308236
- const path32 = `/feedback/${feedbackId}`;
308237
- const response = await this._get(path32);
308818
+ const path33 = `/feedback/${feedbackId}`;
308819
+ const response = await this._get(path33);
308238
308820
  return response;
308239
308821
  }
308240
308822
  async deleteFeedback(feedbackId) {
308241
308823
  assertUuid(feedbackId);
308242
- const path32 = `/feedback/${feedbackId}`;
308824
+ const path33 = `/feedback/${feedbackId}`;
308243
308825
  await this.caller.call(async () => {
308244
- const res = await this._fetch(this.apiUrl + path32, {
308826
+ const res = await this._fetch(this.apiUrl + path33, {
308245
308827
  method: "DELETE",
308246
308828
  headers: this.headers,
308247
308829
  signal: AbortSignal.timeout(this.timeout_ms),
308248
308830
  ...this.fetchOptions
308249
308831
  });
308250
- await raiseForStatus(res, `delete ${path32}`, true);
308832
+ await raiseForStatus(res, `delete ${path33}`, true);
308251
308833
  return res;
308252
308834
  });
308253
308835
  }
@@ -311843,12 +312425,12 @@ function isInteger(str3) {
311843
312425
  }
311844
312426
  return true;
311845
312427
  }
311846
- function escapePathComponent(path32) {
311847
- if (path32.indexOf("/") === -1 && path32.indexOf("~") === -1) return path32;
311848
- return path32.replace(/~/g, "~0").replace(/\//g, "~1");
312428
+ function escapePathComponent(path33) {
312429
+ if (path33.indexOf("/") === -1 && path33.indexOf("~") === -1) return path33;
312430
+ return path33.replace(/~/g, "~0").replace(/\//g, "~1");
311849
312431
  }
311850
- function unescapePathComponent(path32) {
311851
- return path32.replace(/~1/g, "/").replace(/~0/g, "~");
312432
+ function unescapePathComponent(path33) {
312433
+ return path33.replace(/~1/g, "/").replace(/~0/g, "~");
311852
312434
  }
311853
312435
  function hasUndefined(obj) {
311854
312436
  if (obj === void 0) return true;
@@ -312042,8 +312624,8 @@ function applyOperation(document2, operation, validateOperation = false, mutateD
312042
312624
  else return returnValue;
312043
312625
  } else {
312044
312626
  if (!mutateDocument) document2 = _deepClone(document2);
312045
- const path32 = operation.path || "";
312046
- const keys = path32.split("/");
312627
+ const path33 = operation.path || "";
312628
+ const keys = path33.split("/");
312047
312629
  let obj = document2;
312048
312630
  let t = 1;
312049
312631
  let len = keys.length;
@@ -312166,7 +312748,7 @@ function _areEquals(a, b) {
312166
312748
  }
312167
312749
 
312168
312750
  // ../../node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js
312169
- function _generate(mirror, obj, patches, path32, invertible) {
312751
+ function _generate(mirror, obj, patches, path33, invertible) {
312170
312752
  if (obj === mirror) return;
312171
312753
  if (typeof obj.toJSON === "function") obj = obj.toJSON();
312172
312754
  var newKeys = _objectKeys(obj);
@@ -312178,40 +312760,40 @@ function _generate(mirror, obj, patches, path32, invertible) {
312178
312760
  var oldVal = mirror[key];
312179
312761
  if (hasOwnProperty(obj, key) && !(obj[key] === void 0 && oldVal !== void 0 && Array.isArray(obj) === false)) {
312180
312762
  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);
312763
+ 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
312764
  else if (oldVal !== newVal) {
312183
312765
  changed = true;
312184
312766
  if (invertible) patches.push({
312185
312767
  op: "test",
312186
- path: path32 + "/" + escapePathComponent(key),
312768
+ path: path33 + "/" + escapePathComponent(key),
312187
312769
  value: _deepClone(oldVal)
312188
312770
  });
312189
312771
  patches.push({
312190
312772
  op: "replace",
312191
- path: path32 + "/" + escapePathComponent(key),
312773
+ path: path33 + "/" + escapePathComponent(key),
312192
312774
  value: _deepClone(newVal)
312193
312775
  });
312194
312776
  }
312195
312777
  } else if (Array.isArray(mirror) === Array.isArray(obj)) {
312196
312778
  if (invertible) patches.push({
312197
312779
  op: "test",
312198
- path: path32 + "/" + escapePathComponent(key),
312780
+ path: path33 + "/" + escapePathComponent(key),
312199
312781
  value: _deepClone(oldVal)
312200
312782
  });
312201
312783
  patches.push({
312202
312784
  op: "remove",
312203
- path: path32 + "/" + escapePathComponent(key)
312785
+ path: path33 + "/" + escapePathComponent(key)
312204
312786
  });
312205
312787
  deleted = true;
312206
312788
  } else {
312207
312789
  if (invertible) patches.push({
312208
312790
  op: "test",
312209
- path: path32,
312791
+ path: path33,
312210
312792
  value: mirror
312211
312793
  });
312212
312794
  patches.push({
312213
312795
  op: "replace",
312214
- path: path32,
312796
+ path: path33,
312215
312797
  value: obj
312216
312798
  });
312217
312799
  changed = true;
@@ -312222,7 +312804,7 @@ function _generate(mirror, obj, patches, path32, invertible) {
312222
312804
  var key = newKeys[t];
312223
312805
  if (!hasOwnProperty(mirror, key) && obj[key] !== void 0) patches.push({
312224
312806
  op: "add",
312225
- path: path32 + "/" + escapePathComponent(key),
312807
+ path: path33 + "/" + escapePathComponent(key),
312226
312808
  value: _deepClone(obj[key])
312227
312809
  });
312228
312810
  }
@@ -313608,10 +314190,10 @@ function assignProp(target, prop, value) {
313608
314190
  configurable: true
313609
314191
  });
313610
314192
  }
313611
- function getElementAtPath(obj, path32) {
313612
- if (!path32)
314193
+ function getElementAtPath(obj, path33) {
314194
+ if (!path33)
313613
314195
  return obj;
313614
- return path32.reduce((acc, key) => acc?.[key], obj);
314196
+ return path33.reduce((acc, key) => acc?.[key], obj);
313615
314197
  }
313616
314198
  function promiseAllObject(promisesObj) {
313617
314199
  const keys = Object.keys(promisesObj);
@@ -313931,11 +314513,11 @@ function aborted(x, startIndex = 0) {
313931
314513
  }
313932
314514
  return false;
313933
314515
  }
313934
- function prefixIssues(path32, issues) {
314516
+ function prefixIssues(path33, issues) {
313935
314517
  return issues.map((iss) => {
313936
314518
  var _a3;
313937
314519
  (_a3 = iss).path ?? (_a3.path = []);
313938
- iss.path.unshift(path32);
314520
+ iss.path.unshift(path33);
313939
314521
  return iss;
313940
314522
  });
313941
314523
  }
@@ -314072,7 +314654,7 @@ function treeifyError(error40, _mapper) {
314072
314654
  return issue2.message;
314073
314655
  };
314074
314656
  const result = { errors: [] };
314075
- const processError = (error41, path32 = []) => {
314657
+ const processError = (error41, path33 = []) => {
314076
314658
  var _a3, _b;
314077
314659
  for (const issue2 of error41.issues) {
314078
314660
  if (issue2.code === "invalid_union" && issue2.errors.length) {
@@ -314082,7 +314664,7 @@ function treeifyError(error40, _mapper) {
314082
314664
  } else if (issue2.code === "invalid_element") {
314083
314665
  processError({ issues: issue2.issues }, issue2.path);
314084
314666
  } else {
314085
- const fullpath = [...path32, ...issue2.path];
314667
+ const fullpath = [...path33, ...issue2.path];
314086
314668
  if (fullpath.length === 0) {
314087
314669
  result.errors.push(mapper(issue2));
314088
314670
  continue;
@@ -314112,9 +314694,9 @@ function treeifyError(error40, _mapper) {
314112
314694
  processError(error40);
314113
314695
  return result;
314114
314696
  }
314115
- function toDotPath(path32) {
314697
+ function toDotPath(path33) {
314116
314698
  const segs = [];
314117
- for (const seg of path32) {
314699
+ for (const seg of path33) {
314118
314700
  if (typeof seg === "number")
314119
314701
  segs.push(`[${seg}]`);
314120
314702
  else if (typeof seg === "symbol")
@@ -326362,10 +326944,10 @@ var Runnable = class extends Serializable {
326362
326944
  }
326363
326945
  const paths = log.ops.filter((op) => op.path.startsWith("/logs/")).map((op) => op.path.split("/")[2]);
326364
326946
  const dedupedPaths = [...new Set(paths)];
326365
- for (const path32 of dedupedPaths) {
326947
+ for (const path33 of dedupedPaths) {
326366
326948
  let eventType;
326367
326949
  let data = {};
326368
- const logEntry = runLog.state.logs[path32];
326950
+ const logEntry = runLog.state.logs[path33];
326369
326951
  if (logEntry.end_time === void 0) if (logEntry.streamed_output.length > 0) eventType = "stream";
326370
326952
  else eventType = "start";
326371
326953
  else eventType = "end";
@@ -332058,7 +332640,7 @@ var initializeSax = function() {
332058
332640
  if (parser.opt.xmlns) parser.ns = Object.create(rootNS);
332059
332641
  parser.trackPosition = parser.opt.position !== false;
332060
332642
  if (parser.trackPosition) parser.position = parser.line = parser.column = 0;
332061
- emit10(parser, "onready");
332643
+ emit11(parser, "onready");
332062
332644
  }
332063
332645
  if (!Object.create) Object.create = function(o) {
332064
332646
  function F2() {
@@ -332524,16 +333106,16 @@ var initializeSax = function() {
332524
333106
  });
332525
333107
  for (var s in sax$1.STATE) sax$1.STATE[sax$1.STATE[s]] = s;
332526
333108
  S2 = sax$1.STATE;
332527
- function emit10(parser, event, data) {
333109
+ function emit11(parser, event, data) {
332528
333110
  parser[event] && parser[event](data);
332529
333111
  }
332530
333112
  function emitNode(parser, nodeType, data) {
332531
333113
  if (parser.textNode) closeText(parser);
332532
- emit10(parser, nodeType, data);
333114
+ emit11(parser, nodeType, data);
332533
333115
  }
332534
333116
  function closeText(parser) {
332535
333117
  parser.textNode = textopts(parser.opt, parser.textNode);
332536
- if (parser.textNode) emit10(parser, "ontext", parser.textNode);
333118
+ if (parser.textNode) emit11(parser, "ontext", parser.textNode);
332537
333119
  parser.textNode = "";
332538
333120
  }
332539
333121
  function textopts(opt, text) {
@@ -332546,7 +333128,7 @@ var initializeSax = function() {
332546
333128
  if (parser.trackPosition) er += "\nLine: " + parser.line + "\nColumn: " + parser.column + "\nChar: " + parser.c;
332547
333129
  er = new Error(er);
332548
333130
  parser.error = er;
332549
- emit10(parser, "onerror", er);
333131
+ emit11(parser, "onerror", er);
332550
333132
  return parser;
332551
333133
  }
332552
333134
  function end(parser) {
@@ -332555,7 +333137,7 @@ var initializeSax = function() {
332555
333137
  closeText(parser);
332556
333138
  parser.c = "";
332557
333139
  parser.closed = true;
332558
- emit10(parser, "onend");
333140
+ emit11(parser, "onend");
332559
333141
  SAXParser.call(parser, parser.strict, parser.opt);
332560
333142
  return parser;
332561
333143
  }
@@ -338430,13 +339012,13 @@ function combineAliasesAndInvert(constructor) {
338430
339012
  }, {});
338431
339013
  }
338432
339014
  async function reviver(value) {
338433
- const { optionalImportsMap, optionalImportEntrypoints: optionalImportEntrypoints$1, importMap, secretsMap, secretsFromEnv, path: path32, depth, maxDepth } = this;
338434
- const pathStr = path32.join(".");
339015
+ const { optionalImportsMap, optionalImportEntrypoints: optionalImportEntrypoints$1, importMap, secretsMap, secretsFromEnv, path: path33, depth, maxDepth } = this;
339016
+ const pathStr = path33.join(".");
338435
339017
  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
339018
  if (typeof value !== "object" || value == null) return value;
338437
339019
  if (Array.isArray(value)) return Promise.all(value.map((v, i) => reviver.call({
338438
339020
  ...this,
338439
- path: [...path32, `${i}`],
339021
+ path: [...path33, `${i}`],
338440
339022
  depth: depth + 1
338441
339023
  }, v)));
338442
339024
  const record2 = value;
@@ -338491,7 +339073,7 @@ async function reviver(value) {
338491
339073
  if (typeof builder !== "function") throw new Error(`Invalid identifer: ${pathStr} -> ${str3}`);
338492
339074
  const kwargs = await reviver.call({
338493
339075
  ...this,
338494
- path: [...path32, "kwargs"],
339076
+ path: [...path33, "kwargs"],
338495
339077
  depth: depth + 1
338496
339078
  }, serialized.kwargs);
338497
339079
  const instance = new builder(mapKeys(kwargs, keyFromJson, combineAliasesAndInvert(builder)));
@@ -338501,7 +339083,7 @@ async function reviver(value) {
338501
339083
  const result = {};
338502
339084
  for (const [key, val] of Object.entries(record2)) result[key] = await reviver.call({
338503
339085
  ...this,
338504
- path: [...path32, key],
339086
+ path: [...path33, key],
338505
339087
  depth: depth + 1
338506
339088
  }, val);
338507
339089
  return result;
@@ -343629,10 +344211,10 @@ var Graph$1 = class {
343629
344211
  this.edges.add([startKey, endKey]);
343630
344212
  return this;
343631
344213
  }
343632
- addConditionalEdges(source, path32, pathMap) {
344214
+ addConditionalEdges(source, path33, pathMap) {
343633
344215
  const options = typeof source === "object" ? source : {
343634
344216
  source,
343635
- path: path32,
344217
+ path: path33,
343636
344218
  pathMap
343637
344219
  };
343638
344220
  this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");
@@ -345164,16 +345746,16 @@ var Diff = class {
345164
345746
  }
345165
345747
  }
345166
345748
  }
345167
- addToPath(path32, added, removed, oldPosInc, options) {
345168
- const last = path32.lastComponent;
345749
+ addToPath(path33, added, removed, oldPosInc, options) {
345750
+ const last = path33.lastComponent;
345169
345751
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
345170
345752
  return {
345171
- oldPos: path32.oldPos + oldPosInc,
345753
+ oldPos: path33.oldPos + oldPosInc,
345172
345754
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
345173
345755
  };
345174
345756
  } else {
345175
345757
  return {
345176
- oldPos: path32.oldPos + oldPosInc,
345758
+ oldPos: path33.oldPos + oldPosInc,
345177
345759
  lastComponent: { count: 1, added, removed, previousComponent: last }
345178
345760
  };
345179
345761
  }
@@ -346690,6 +347272,143 @@ function recallForPrompt(content, opts = {}) {
346690
347272
  return picked.join("\n");
346691
347273
  }
346692
347274
 
347275
+ // ../../packages/backend/src/services/AgentHelper/tools/learning_tools.ts
347276
+ init_zod();
347277
+ var import_node_crypto16 = require("node:crypto");
347278
+ init_compoundingKnowledge();
347279
+ function emit(context2, toolName, input, output) {
347280
+ context2.sendEvent(context2.sessionId, {
347281
+ messageId: context2.messageId,
347282
+ type: "tool_call",
347283
+ toolName,
347284
+ input: typeof input === "string" ? input : JSON.stringify(input),
347285
+ output
347286
+ });
347287
+ }
347288
+ var opsExperimentSchema = external_exports.object({
347289
+ hypothesis: external_exports.string().min(1).describe('What you think is true, e.g. "SMB IPC$ is blocked (NetUseAdd 64)".'),
347290
+ probe: external_exports.string().min(1).describe("One cheap command that would confirm or reject the hypothesis."),
347291
+ 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)."),
347292
+ expect: external_exports.string().optional().describe("Optional substring the probe output must contain to count as ok."),
347293
+ tabIdOrName: external_exports.string().optional().describe("Optional tab to run the probe on. If omitted, the experiment is recorded as a plan only.")
347294
+ });
347295
+ var manageGoalSchema = external_exports.object({
347296
+ action: external_exports.enum(["upsert", "list", "done", "abandon"]).describe("upsert a goal, list session goals, mark done, or abandon."),
347297
+ id: external_exports.string().optional().describe("Goal id (upsert/done/abandon). Generated if omitted on upsert."),
347298
+ text: external_exports.string().optional().describe("Goal text (upsert)."),
347299
+ status: external_exports.enum(["open", "blocked", "done", "abandoned"]).optional(),
347300
+ blockedBy: external_exports.string().optional(),
347301
+ nextProbe: external_exports.string().optional()
347302
+ });
347303
+ var estateFactsSchema = external_exports.object({
347304
+ action: external_exports.enum(["upsert", "list"]).describe("upsert a fact for a connection identity, or list the estate snapshot."),
347305
+ name: external_exports.string().optional().describe("Saved connection name (preferred identity)."),
347306
+ host: external_exports.string().optional(),
347307
+ role: external_exports.string().optional().describe("dc | member | workgroup | other"),
347308
+ domain: external_exports.string().optional(),
347309
+ transport: external_exports.string().optional(),
347310
+ auth: external_exports.string().optional(),
347311
+ facts: external_exports.record(external_exports.unknown()).optional()
347312
+ });
347313
+ async function opsExperiment(args, context2) {
347314
+ const store = context2.compoundingStore;
347315
+ if (!store) {
347316
+ const msg2 = "Compounding store is not wired in this runtime.";
347317
+ emit(context2, "ops_experiment", args, msg2);
347318
+ return msg2;
347319
+ }
347320
+ store.recordProbe(context2.sessionId, args.tag, args.hypothesis, args.probe, false);
347321
+ const msg = `Recorded experiment tag=${args.tag}
347322
+ hypothesis: ${args.hypothesis}
347323
+ probe: ${args.probe}
347324
+ ` + (args.expect ? `expect: ${args.expect}
347325
+ ` : "") + (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.`);
347326
+ emit(context2, "ops_experiment", args, msg);
347327
+ return msg;
347328
+ }
347329
+ async function manageGoal(args, context2) {
347330
+ const store = context2.compoundingStore;
347331
+ if (!store) {
347332
+ const msg2 = "Compounding store is not wired in this runtime.";
347333
+ emit(context2, "manage_goal", args, msg2);
347334
+ return msg2;
347335
+ }
347336
+ if (args.action === "list") {
347337
+ const goals = store.listGoals(context2.sessionId);
347338
+ 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.";
347339
+ emit(context2, "manage_goal", args, msg2);
347340
+ return msg2;
347341
+ }
347342
+ const id = args.id || `goal-${(0, import_node_crypto16.randomUUID)().slice(0, 8)}`;
347343
+ if (args.action === "done" || args.action === "abandon") {
347344
+ const existing = store.listGoals(context2.sessionId).find((g) => g.id === id);
347345
+ store.upsertGoal({
347346
+ id,
347347
+ sessionId: context2.sessionId,
347348
+ text: existing?.text || args.text || id,
347349
+ status: args.action === "done" ? "done" : "abandoned"
347350
+ });
347351
+ const msg2 = `Goal ${id} marked ${args.action}.`;
347352
+ emit(context2, "manage_goal", args, msg2);
347353
+ return msg2;
347354
+ }
347355
+ if (!args.text) {
347356
+ const msg2 = "upsert requires text";
347357
+ emit(context2, "manage_goal", args, msg2);
347358
+ return msg2;
347359
+ }
347360
+ store.upsertGoal({
347361
+ id,
347362
+ sessionId: context2.sessionId,
347363
+ text: args.text,
347364
+ status: args.status || "open",
347365
+ blockedBy: args.blockedBy,
347366
+ nextProbe: args.nextProbe
347367
+ });
347368
+ const msg = `Goal ${id} [${args.status || "open"}] ${args.text}`;
347369
+ emit(context2, "manage_goal", args, msg);
347370
+ return msg;
347371
+ }
347372
+ async function estateFacts(args, context2) {
347373
+ const store = context2.compoundingStore;
347374
+ if (!store) {
347375
+ const msg2 = "Compounding store is not wired in this runtime.";
347376
+ emit(context2, "estate_facts", args, msg2);
347377
+ return msg2;
347378
+ }
347379
+ if (args.action === "list") {
347380
+ const facts = store.listEstateFacts();
347381
+ const msg2 = facts.length ? facts.map((f) => {
347382
+ const bits = [f.identity, f.role, f.domain, [f.transport, f.auth].filter(Boolean).join("/")].filter(Boolean);
347383
+ return `- ${bits.join(" \xB7 ")}`;
347384
+ }).join("\n") : "No estate facts recorded yet. Upsert after collect_facts / AD probes.";
347385
+ emit(context2, "estate_facts", args, msg2);
347386
+ return msg2;
347387
+ }
347388
+ const identity = connectionIdentity({
347389
+ name: args.name,
347390
+ host: args.host,
347391
+ transport: args.transport,
347392
+ auth: args.auth,
347393
+ domain: args.domain
347394
+ });
347395
+ store.upsertEstateFact({
347396
+ identity,
347397
+ host: args.host,
347398
+ role: args.role,
347399
+ domain: args.domain,
347400
+ transport: args.transport,
347401
+ auth: args.auth,
347402
+ facts: args.facts
347403
+ });
347404
+ const msg = `Upserted estate fact identity=${identity}`;
347405
+ emit(context2, "estate_facts", args, msg);
347406
+ return msg;
347407
+ }
347408
+ 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).";
347409
+ 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.";
347410
+ 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.";
347411
+
346693
347412
  // ../../packages/backend/src/services/AgentHelper/prompts.ts
346694
347413
  var SYS_INFO_MARKER = "CURRENT_SYSTEM_INFO_MSG:\n";
346695
347414
  var GYSHELL_BASE_SYSTEM_MARKER = "# Role: GyShell Assistant";
@@ -347089,6 +347808,21 @@ var BUILTIN_TOOL_INFO = [
347089
347808
  description: GET_RUN_LEDGER_DESCRIPTION,
347090
347809
  shortDescription: "Query agent run audit ledger"
347091
347810
  },
347811
+ {
347812
+ name: "ops_experiment",
347813
+ description: OPS_EXPERIMENT_DESCRIPTION,
347814
+ shortDescription: "Hypothesis + probe before mutations"
347815
+ },
347816
+ {
347817
+ name: "manage_goal",
347818
+ description: MANAGE_GOAL_DESCRIPTION,
347819
+ shortDescription: "Persistent session goals"
347820
+ },
347821
+ {
347822
+ name: "estate_facts",
347823
+ description: ESTATE_FACTS_DESCRIPTION,
347824
+ shortDescription: "Estate snapshot by connection name"
347825
+ },
347092
347826
  {
347093
347827
  name: "run_fleet_command",
347094
347828
  description: RUN_FLEET_COMMAND_DESCRIPTION,
@@ -347656,7 +348390,7 @@ function buildUnfinishedFileTransferContinueInstruction(transfers) {
347656
348390
  }
347657
348391
 
347658
348392
  // ../../packages/backend/src/services/AgentHelper/tools/terminal_tools.ts
347659
- var import_node_crypto16 = require("node:crypto");
348393
+ var import_node_crypto17 = require("node:crypto");
347660
348394
  var execCommandSchema = external_exports.object({
347661
348395
  tabIdOrName: external_exports.string().describe("The ID or Name of the terminal tab"),
347662
348396
  command: external_exports.string().describe("The shell command to execute"),
@@ -347708,7 +348442,7 @@ function sshEntryToTerminalConfig(entry, opts) {
347708
348442
  const jumpHost = entry.jumpHost;
347709
348443
  return {
347710
348444
  type: "ssh",
347711
- id: `ssh-${(0, import_node_crypto16.randomUUID)()}`,
348445
+ id: `ssh-${(0, import_node_crypto17.randomUUID)()}`,
347712
348446
  title: opts.title,
347713
348447
  cols: 80,
347714
348448
  rows: 24,
@@ -347738,7 +348472,7 @@ function resolveSavedWinrmConnection(context2, nameOrId) {
347738
348472
  function winrmEntryToTerminalConfig(entry, opts) {
347739
348473
  return {
347740
348474
  type: "winrm",
347741
- id: `winrm-${(0, import_node_crypto16.randomUUID)()}`,
348475
+ id: `winrm-${(0, import_node_crypto17.randomUUID)()}`,
347742
348476
  title: opts.title,
347743
348477
  cols: 80,
347744
348478
  rows: 24,
@@ -347763,7 +348497,7 @@ function resolveSavedSerialConnection(context2, nameOrId) {
347763
348497
  function serialEntryToTerminalConfig(entry, opts) {
347764
348498
  return {
347765
348499
  type: "serial",
347766
- id: `serial-${(0, import_node_crypto16.randomUUID)()}`,
348500
+ id: `serial-${(0, import_node_crypto17.randomUUID)()}`,
347767
348501
  title: opts.title,
347768
348502
  cols: 80,
347769
348503
  rows: 24,
@@ -347889,6 +348623,30 @@ async function runCommand(args, context2, options) {
347889
348623
  "run commands in this terminal"
347890
348624
  );
347891
348625
  }
348626
+ const { matchGatedMutation: matchGatedMutation2 } = await Promise.resolve().then(() => (init_compoundingKnowledge(), compoundingKnowledge_exports)).catch(() => ({ matchGatedMutation: () => null }));
348627
+ const gated = matchGatedMutation2(command);
348628
+ if (gated && context2.compoundingStore && !context2.compoundingStore.hasProbe(context2.sessionId, gated.requireProbeTag)) {
348629
+ 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.`;
348630
+ abortIfNeeded(context2.signal);
348631
+ context2.sendEvent(sessionId, {
348632
+ messageId,
348633
+ type: "command_started",
348634
+ command,
348635
+ commandId: messageId,
348636
+ tabName: bestMatch.title || bestMatch.id,
348637
+ isNowait: false
348638
+ });
348639
+ context2.sendEvent(sessionId, {
348640
+ messageId,
348641
+ type: "command_finished",
348642
+ command,
348643
+ commandId: messageId,
348644
+ tabName: bestMatch.title || bestMatch.id,
348645
+ exitCode: -1,
348646
+ outputDelta: block
348647
+ });
348648
+ return block;
348649
+ }
347892
348650
  const allowed = await checkCommandPolicy(command, "run_command", context2);
347893
348651
  if (!allowed.allowed) {
347894
348652
  abortIfNeeded(context2.signal);
@@ -349304,7 +350062,7 @@ var manageWinrmConnectionSchema = external_exports.object({
349304
350062
  id: external_exports.string().optional().describe("ID for update/delete."),
349305
350063
  connection: winrmConnectionFieldsSchema.optional()
349306
350064
  });
349307
- function emit(context2, input, output) {
350065
+ function emit2(context2, input, output) {
349308
350066
  context2.sendEvent(context2.sessionId, {
349309
350067
  messageId: context2.messageId,
349310
350068
  type: "tool_call",
@@ -349342,7 +350100,7 @@ async function manageWinrmConnection(args, context2) {
349342
350100
  const cm = context2.connectionManager;
349343
350101
  if (!cm) {
349344
350102
  const msg2 = "Connection management is not available in this runtime (no connection manager wired).";
349345
- emit(context2, args, msg2);
350103
+ emit2(context2, args, msg2);
349346
350104
  return msg2;
349347
350105
  }
349348
350106
  const { action } = args;
@@ -349350,61 +350108,61 @@ async function manageWinrmConnection(args, context2) {
349350
350108
  const entries = cm.listWinrm();
349351
350109
  if (entries.length === 0) {
349352
350110
  const msg3 = 'No saved WinRM connections configured. Use action="create" to add one.';
349353
- emit(context2, args, msg3);
350111
+ emit2(context2, args, msg3);
349354
350112
  return msg3;
349355
350113
  }
349356
350114
  const msg2 = `Saved WinRM connections (${entries.length}):
349357
350115
  ${entries.map(summarize2).join("\n")}`;
349358
- emit(context2, args, msg2);
350116
+ emit2(context2, args, msg2);
349359
350117
  return msg2;
349360
350118
  }
349361
350119
  if (action === "create") {
349362
350120
  if (!args.connection) {
349363
350121
  const msg3 = "create requires a `connection` object with name, host, username, and password.";
349364
- emit(context2, args, msg3);
350122
+ emit2(context2, args, msg3);
349365
350123
  return msg3;
349366
350124
  }
349367
350125
  if (cm.listWinrm().some((e) => e.name === args.connection.name)) {
349368
350126
  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);
350127
+ emit2(context2, args, msg3);
349370
350128
  return msg3;
349371
350129
  }
349372
350130
  const stored = cm.createWinrm(toEntry2(args.connection, randomId2()));
349373
350131
  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);
350132
+ emit2(context2, args, msg2);
349375
350133
  return msg2;
349376
350134
  }
349377
350135
  if (action === "update") {
349378
350136
  if (!args.id || !args.connection) {
349379
350137
  const msg3 = "update requires an `id` and a `connection` object with the fields to change.";
349380
- emit(context2, args, msg3);
350138
+ emit2(context2, args, msg3);
349381
350139
  return msg3;
349382
350140
  }
349383
350141
  const current = cm.listWinrm().find((e) => e.id === args.id);
349384
350142
  if (!current) {
349385
350143
  const msg3 = `No saved WinRM connection with id "${args.id}". Use action="list" to see valid ids.`;
349386
- emit(context2, args, msg3);
350144
+ emit2(context2, args, msg3);
349387
350145
  return msg3;
349388
350146
  }
349389
350147
  const merged = { ...current, ...toEntry2({ ...current, ...args.connection }, args.id) };
349390
350148
  const stored = cm.updateWinrm(merged);
349391
350149
  const msg2 = `Updated saved WinRM connection: ${summarize2(stored)}.`;
349392
- emit(context2, args, msg2);
350150
+ emit2(context2, args, msg2);
349393
350151
  return msg2;
349394
350152
  }
349395
350153
  if (action === "delete") {
349396
350154
  if (!args.id) {
349397
350155
  const msg3 = "delete requires an `id`.";
349398
- emit(context2, args, msg3);
350156
+ emit2(context2, args, msg3);
349399
350157
  return msg3;
349400
350158
  }
349401
350159
  const removed = cm.deleteWinrm(args.id);
349402
350160
  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);
350161
+ emit2(context2, args, msg2);
349404
350162
  return msg2;
349405
350163
  }
349406
350164
  const msg = `Unknown action "${action}".`;
349407
- emit(context2, args, msg);
350165
+ emit2(context2, args, msg);
349408
350166
  return msg;
349409
350167
  }
349410
350168
 
@@ -349426,7 +350184,7 @@ var manageSerialConnectionSchema = external_exports.object({
349426
350184
  id: external_exports.string().optional(),
349427
350185
  connection: serialConnectionFieldsSchema.optional()
349428
350186
  });
349429
- function emit2(context2, input, output) {
350187
+ function emit3(context2, input, output) {
349430
350188
  context2.sendEvent(context2.sessionId, {
349431
350189
  messageId: context2.messageId,
349432
350190
  type: "tool_call",
@@ -349459,7 +350217,7 @@ async function manageSerialConnection(args, context2) {
349459
350217
  const cm = context2.connectionManager;
349460
350218
  if (!cm) {
349461
350219
  const msg2 = "Connection management is not available in this runtime (no connection manager wired).";
349462
- emit2(context2, args, msg2);
350220
+ emit3(context2, args, msg2);
349463
350221
  return msg2;
349464
350222
  }
349465
350223
  const { action } = args;
@@ -349467,61 +350225,61 @@ async function manageSerialConnection(args, context2) {
349467
350225
  const entries = cm.listSerial();
349468
350226
  if (!entries.length) {
349469
350227
  const msg3 = 'No saved serial connections configured. Use action="create" to add one.';
349470
- emit2(context2, args, msg3);
350228
+ emit3(context2, args, msg3);
349471
350229
  return msg3;
349472
350230
  }
349473
350231
  const msg2 = `Saved serial connections (${entries.length}):
349474
350232
  ${entries.map(summarize3).join("\n")}`;
349475
- emit2(context2, args, msg2);
350233
+ emit3(context2, args, msg2);
349476
350234
  return msg2;
349477
350235
  }
349478
350236
  if (action === "create") {
349479
350237
  if (!args.connection) {
349480
350238
  const msg3 = "create requires a `connection` object with name and path.";
349481
- emit2(context2, args, msg3);
350239
+ emit3(context2, args, msg3);
349482
350240
  return msg3;
349483
350241
  }
349484
350242
  if (cm.listSerial().some((e) => e.name === args.connection.name)) {
349485
350243
  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);
350244
+ emit3(context2, args, msg3);
349487
350245
  return msg3;
349488
350246
  }
349489
350247
  const stored = cm.createSerial(toEntry3(args.connection, randomId3()));
349490
350248
  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);
350249
+ emit3(context2, args, msg2);
349492
350250
  return msg2;
349493
350251
  }
349494
350252
  if (action === "update") {
349495
350253
  if (!args.id || !args.connection) {
349496
350254
  const msg3 = "update requires an `id` and a `connection` object with the fields to change.";
349497
- emit2(context2, args, msg3);
350255
+ emit3(context2, args, msg3);
349498
350256
  return msg3;
349499
350257
  }
349500
350258
  const current = cm.listSerial().find((e) => e.id === args.id);
349501
350259
  if (!current) {
349502
350260
  const msg3 = `No saved serial connection with id "${args.id}". Use action="list" to see valid ids.`;
349503
- emit2(context2, args, msg3);
350261
+ emit3(context2, args, msg3);
349504
350262
  return msg3;
349505
350263
  }
349506
350264
  const merged = { ...current, ...toEntry3({ ...current, ...args.connection }, args.id) };
349507
350265
  const stored = cm.updateSerial(merged);
349508
350266
  const msg2 = `Updated saved serial connection: ${summarize3(stored)}.`;
349509
- emit2(context2, args, msg2);
350267
+ emit3(context2, args, msg2);
349510
350268
  return msg2;
349511
350269
  }
349512
350270
  if (action === "delete") {
349513
350271
  if (!args.id) {
349514
350272
  const msg3 = "delete requires an `id`.";
349515
- emit2(context2, args, msg3);
350273
+ emit3(context2, args, msg3);
349516
350274
  return msg3;
349517
350275
  }
349518
350276
  const removed = cm.deleteSerial(args.id);
349519
350277
  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);
350278
+ emit3(context2, args, msg2);
349521
350279
  return msg2;
349522
350280
  }
349523
350281
  const msg = `Unknown action "${action}".`;
349524
- emit2(context2, args, msg);
350282
+ emit3(context2, args, msg);
349525
350283
  return msg;
349526
350284
  }
349527
350285
 
@@ -349542,7 +350300,7 @@ var searchSessionLogsSchema = external_exports.object({
349542
350300
  maxMatches: external_exports.number().int().min(1).max(500).optional().describe("Max matching lines to return (default 50)."),
349543
350301
  contextLines: external_exports.number().int().min(0).max(20).optional().describe("Lines of surrounding context per match (default 0).")
349544
350302
  });
349545
- function emit3(context2, toolName, input, output) {
350303
+ function emit4(context2, toolName, input, output) {
349546
350304
  context2.sendEvent(context2.sessionId, {
349547
350305
  messageId: context2.messageId,
349548
350306
  type: "tool_call",
@@ -349555,32 +350313,32 @@ async function listSessionLogs(args, context2) {
349555
350313
  const logger = context2.sessionLogger;
349556
350314
  if (!logger) {
349557
350315
  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);
350316
+ emit4(context2, "list_session_logs", args, msg2);
349559
350317
  return msg2;
349560
350318
  }
349561
350319
  const list = logger.list();
349562
350320
  if (!list.length) {
349563
350321
  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);
350322
+ emit4(context2, "list_session_logs", args, msg2);
349565
350323
  return msg2;
349566
350324
  }
349567
350325
  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
350326
  const msg = `Recorded sessions (${list.length}):
349569
350327
  ${body}`;
349570
- emit3(context2, "list_session_logs", args, msg);
350328
+ emit4(context2, "list_session_logs", args, msg);
349571
350329
  return msg;
349572
350330
  }
349573
350331
  async function readSessionLog(args, context2) {
349574
350332
  const logger = context2.sessionLogger;
349575
350333
  if (!logger) {
349576
350334
  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);
350335
+ emit4(context2, "read_session_log", args, msg2);
349578
350336
  return msg2;
349579
350337
  }
349580
350338
  const content = logger.read(args.sessionId);
349581
350339
  if (!content) {
349582
350340
  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);
350341
+ emit4(context2, "read_session_log", args, msg2);
349584
350342
  return msg2;
349585
350343
  }
349586
350344
  const truncated = content.length > 8e3 ? `${content.slice(0, 4e3)}
@@ -349590,14 +350348,14 @@ ${content.slice(-4e3)}` : content;
349590
350348
  <session_log>
349591
350349
  ${truncated}
349592
350350
  </session_log>`;
349593
- emit3(context2, "read_session_log", args, msg);
350351
+ emit4(context2, "read_session_log", args, msg);
349594
350352
  return msg;
349595
350353
  }
349596
350354
  async function searchSessionLogs(args, context2) {
349597
350355
  const logger = context2.sessionLogger;
349598
350356
  if (!logger || typeof logger.search !== "function") {
349599
350357
  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);
350358
+ emit4(context2, "search_session_logs", args, msg2);
349601
350359
  return msg2;
349602
350360
  }
349603
350361
  const result = logger.search(args.query, {
@@ -349612,7 +350370,7 @@ async function searchSessionLogs(args, context2) {
349612
350370
  });
349613
350371
  if (result.totalMatches === 0) {
349614
350372
  const msg2 = `No matches for "${args.query}" across ${result.sessionsSearched} recorded session(s).`;
349615
- emit3(context2, "search_session_logs", args, msg2);
350373
+ emit4(context2, "search_session_logs", args, msg2);
349616
350374
  return msg2;
349617
350375
  }
349618
350376
  const lines = result.matches.map((m2) => {
@@ -349626,7 +350384,7 @@ ${ctx}`;
349626
350384
  });
349627
350385
  const msg = `Found ${result.totalMatches} match(es) for "${args.query}" across ${result.sessionsSearched} session(s):
349628
350386
  ${lines.join("\n")}`;
349629
- emit3(context2, "search_session_logs", args, msg);
350387
+ emit4(context2, "search_session_logs", args, msg);
349630
350388
  return msg;
349631
350389
  }
349632
350390
 
@@ -349640,7 +350398,7 @@ var getRunLedgerSchema = external_exports.object({
349640
350398
  limit: external_exports.number().int().min(1).max(200).optional().describe("Max runs for 'list' (default 20)."),
349641
350399
  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
350400
  });
349643
- function emit4(context2, toolName, input, output) {
350401
+ function emit5(context2, toolName, input, output) {
349644
350402
  context2.sendEvent(context2.sessionId, {
349645
350403
  messageId: context2.messageId,
349646
350404
  type: "tool_call",
@@ -349664,19 +350422,19 @@ async function getRunLedger(args, context2) {
349664
350422
  const ledger = context2.agentRunLedger;
349665
350423
  if (!ledger) {
349666
350424
  const msg2 = "Run ledger is not available in this runtime (no agent run ledger wired).";
349667
- emit4(context2, "get_run_ledger", args, msg2);
350425
+ emit5(context2, "get_run_ledger", args, msg2);
349668
350426
  return msg2;
349669
350427
  }
349670
350428
  if (args.action === "list") {
349671
350429
  const runs = ledger.listRuns({ limit: args.limit ?? 20, sessionId: args.sessionId, status: args.status });
349672
350430
  if (!runs.length) {
349673
350431
  const msg3 = "No agent runs recorded yet in the ledger.";
349674
- emit4(context2, "get_run_ledger", args, msg3);
350432
+ emit5(context2, "get_run_ledger", args, msg3);
349675
350433
  return msg3;
349676
350434
  }
349677
350435
  const msg2 = `Agent run ledger \u2014 ${runs.length} most recent run(s):
349678
350436
  ${runs.map(fmtRun).join("\n")}`;
349679
- emit4(context2, "get_run_ledger", args, msg2);
350437
+ emit5(context2, "get_run_ledger", args, msg2);
349680
350438
  return msg2;
349681
350439
  }
349682
350440
  if (args.action === "summary") {
@@ -349691,18 +350449,18 @@ ${runs.map(fmtRun).join("\n")}`;
349691
350449
  ` by model:`,
349692
350450
  models
349693
350451
  ].join("\n");
349694
- emit4(context2, "get_run_ledger", args, msg2);
350452
+ emit5(context2, "get_run_ledger", args, msg2);
349695
350453
  return msg2;
349696
350454
  }
349697
350455
  if (!args.runId) {
349698
350456
  const msg2 = "runId is required for action='get'. Use action='list' to find run ids.";
349699
- emit4(context2, "get_run_ledger", args, msg2);
350457
+ emit5(context2, "get_run_ledger", args, msg2);
349700
350458
  return msg2;
349701
350459
  }
349702
350460
  const got = ledger.getRun(args.runId);
349703
350461
  if (!got) {
349704
350462
  const msg2 = `No run with id "${args.runId}" in the ledger.`;
349705
- emit4(context2, "get_run_ledger", args, msg2);
350463
+ emit5(context2, "get_run_ledger", args, msg2);
349706
350464
  return msg2;
349707
350465
  }
349708
350466
  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 +350468,7 @@ ${runs.map(fmtRun).join("\n")}`;
349710
350468
  ${fmtRun(got.run)}
349711
350469
  usage events:
349712
350470
  ${usage}`;
349713
- emit4(context2, "get_run_ledger", args, msg);
350471
+ emit5(context2, "get_run_ledger", args, msg);
349714
350472
  return msg;
349715
350473
  }
349716
350474
 
@@ -350562,7 +351320,7 @@ function importPuttyReg(content, opts) {
350562
351320
  }
350563
351321
 
350564
351322
  // ../../packages/backend/src/services/AgentHelper/tools/automation_tools.ts
350565
- function emit5(context2, _toolName, input, output) {
351323
+ function emit6(context2, _toolName, input, output) {
350566
351324
  context2.sendEvent(context2.sessionId, {
350567
351325
  messageId: context2.messageId,
350568
351326
  type: "tool_call",
@@ -350589,7 +351347,7 @@ async function manageDeviceMemory(args, context2) {
350589
351347
  const m2 = context2.automationManager;
350590
351348
  if (!m2) {
350591
351349
  const msg2 = noStore();
350592
- emit5(context2, "manage_device_memory", args, msg2);
351350
+ emit6(context2, "manage_device_memory", args, msg2);
350593
351351
  return msg2;
350594
351352
  }
350595
351353
  const { action } = args;
@@ -350597,25 +351355,25 @@ async function manageDeviceMemory(args, context2) {
350597
351355
  const all = m2.listDeviceMemory();
350598
351356
  if (!all.length) {
350599
351357
  const msg3 = "No device memory entries.";
350600
- emit5(context2, "manage_device_memory", args, msg3);
351358
+ emit6(context2, "manage_device_memory", args, msg3);
350601
351359
  return msg3;
350602
351360
  }
350603
351361
  const body = all.map((e) => `${e.host} (role=${e.role || "unspecified"}, ${e.incidents.length} incident(s))`).join("\n");
350604
351362
  const msg2 = `Device memory (${all.length}):
350605
351363
  ${body}`;
350606
- emit5(context2, "manage_device_memory", args, msg2);
351364
+ emit6(context2, "manage_device_memory", args, msg2);
350607
351365
  return msg2;
350608
351366
  }
350609
351367
  if (!args.host) {
350610
351368
  const msg2 = `action="${action}" requires a host.`;
350611
- emit5(context2, "manage_device_memory", args, msg2);
351369
+ emit6(context2, "manage_device_memory", args, msg2);
350612
351370
  return msg2;
350613
351371
  }
350614
351372
  if (action === "get") {
350615
351373
  const mem = m2.getDeviceMemory(args.host);
350616
351374
  if (!mem) {
350617
351375
  const msg3 = `No device memory for host "${args.host}".`;
350618
- emit5(context2, "manage_device_memory", args, msg3);
351376
+ emit6(context2, "manage_device_memory", args, msg3);
350619
351377
  return msg3;
350620
351378
  }
350621
351379
  const msg2 = `Device memory for ${args.host}:
@@ -350623,18 +351381,18 @@ role: ${mem.role || "unspecified"}
350623
351381
  standing instructions: ${mem.standingInstructions || "(none)"}
350624
351382
  incidents (${mem.incidents.length}):
350625
351383
  ${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);
351384
+ emit6(context2, "manage_device_memory", args, msg2);
350627
351385
  return msg2;
350628
351386
  }
350629
351387
  if (action === "add_incident") {
350630
351388
  if (!args.incident) {
350631
351389
  const msg3 = "add_incident requires an `incident` object.";
350632
- emit5(context2, "manage_device_memory", args, msg3);
351390
+ emit6(context2, "manage_device_memory", args, msg3);
350633
351391
  return msg3;
350634
351392
  }
350635
351393
  const inc = m2.addIncident(args.host, args.incident);
350636
351394
  const msg2 = `Recorded incident for ${args.host} at ${inc.at}: ${inc.summary}.`;
350637
- emit5(context2, "manage_device_memory", args, msg2);
351395
+ emit6(context2, "manage_device_memory", args, msg2);
350638
351396
  return msg2;
350639
351397
  }
350640
351398
  if (action === "upsert") {
@@ -350645,17 +351403,17 @@ ${mem.incidents.map((i) => `- [${i.at}] ${i.summary}${i.ticketId ? ` (ticket: ${
350645
351403
  incidents: []
350646
351404
  });
350647
351405
  const msg2 = `Saved device memory for ${mem.host} (role=${mem.role || "unspecified"}).`;
350648
- emit5(context2, "manage_device_memory", args, msg2);
351406
+ emit6(context2, "manage_device_memory", args, msg2);
350649
351407
  return msg2;
350650
351408
  }
350651
351409
  if (action === "delete") {
350652
351410
  const removed = m2.deleteDeviceMemory(args.host);
350653
351411
  const msg2 = removed ? `Deleted device memory for ${args.host}.` : `No device memory for ${args.host}.`;
350654
- emit5(context2, "manage_device_memory", args, msg2);
351412
+ emit6(context2, "manage_device_memory", args, msg2);
350655
351413
  return msg2;
350656
351414
  }
350657
351415
  const msg = `Unknown action "${action}".`;
350658
- emit5(context2, "manage_device_memory", args, msg);
351416
+ emit6(context2, "manage_device_memory", args, msg);
350659
351417
  return msg;
350660
351418
  }
350661
351419
  var manageScriptSchema = external_exports.object({
@@ -350671,7 +351429,7 @@ async function manageScript(args, context2) {
350671
351429
  const m2 = context2.automationManager;
350672
351430
  if (!m2) {
350673
351431
  const msg2 = noStore();
350674
- emit5(context2, "manage_script", args, msg2);
351432
+ emit6(context2, "manage_script", args, msg2);
350675
351433
  return msg2;
350676
351434
  }
350677
351435
  const { action } = args;
@@ -350679,56 +351437,56 @@ async function manageScript(args, context2) {
350679
351437
  const all = m2.listScripts();
350680
351438
  if (!all.length) {
350681
351439
  const msg3 = "No saved scripts.";
350682
- emit5(context2, "manage_script", args, msg3);
351440
+ emit6(context2, "manage_script", args, msg3);
350683
351441
  return msg3;
350684
351442
  }
350685
351443
  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
351444
  const msg2 = `Saved scripts (${all.length}):
350687
351445
  ${body}`;
350688
- emit5(context2, "manage_script", args, msg2);
351446
+ emit6(context2, "manage_script", args, msg2);
350689
351447
  return msg2;
350690
351448
  }
350691
351449
  if (action === "create") {
350692
351450
  if (!args.name || !args.command) {
350693
351451
  const msg3 = "create requires name + command.";
350694
- emit5(context2, "manage_script", args, msg3);
351452
+ emit6(context2, "manage_script", args, msg3);
350695
351453
  return msg3;
350696
351454
  }
350697
351455
  const s = m2.createScript({ name: args.name, command: args.command, description: args.description, targets: args.targets, tags: args.tags });
350698
351456
  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);
351457
+ emit6(context2, "manage_script", args, msg2);
350700
351458
  return msg2;
350701
351459
  }
350702
351460
  if (action === "update") {
350703
351461
  if (!args.id) {
350704
351462
  const msg3 = "update requires id.";
350705
- emit5(context2, "manage_script", args, msg3);
351463
+ emit6(context2, "manage_script", args, msg3);
350706
351464
  return msg3;
350707
351465
  }
350708
351466
  const existing = m2.listScripts().find((s2) => s2.id === args.id);
350709
351467
  if (!existing) {
350710
351468
  const msg3 = `No script with id="${args.id}".`;
350711
- emit5(context2, "manage_script", args, msg3);
351469
+ emit6(context2, "manage_script", args, msg3);
350712
351470
  return msg3;
350713
351471
  }
350714
351472
  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
351473
  const msg2 = `Updated script "${s.name}".`;
350716
- emit5(context2, "manage_script", args, msg2);
351474
+ emit6(context2, "manage_script", args, msg2);
350717
351475
  return msg2;
350718
351476
  }
350719
351477
  if (action === "delete") {
350720
351478
  if (!args.id) {
350721
351479
  const msg3 = "delete requires id.";
350722
- emit5(context2, "manage_script", args, msg3);
351480
+ emit6(context2, "manage_script", args, msg3);
350723
351481
  return msg3;
350724
351482
  }
350725
351483
  const removed = m2.deleteScript(args.id);
350726
351484
  const msg2 = removed ? `Deleted script ${args.id}.` : `No script ${args.id}.`;
350727
- emit5(context2, "manage_script", args, msg2);
351485
+ emit6(context2, "manage_script", args, msg2);
350728
351486
  return msg2;
350729
351487
  }
350730
351488
  const msg = `Unknown action "${action}".`;
350731
- emit5(context2, "manage_script", args, msg);
351489
+ emit6(context2, "manage_script", args, msg);
350732
351490
  return msg;
350733
351491
  }
350734
351492
  var manageGroupSchema = external_exports.object({
@@ -350741,7 +351499,7 @@ async function manageGroup(args, context2) {
350741
351499
  const m2 = context2.automationManager;
350742
351500
  if (!m2) {
350743
351501
  const msg2 = noStore();
350744
- emit5(context2, "manage_group", args, msg2);
351502
+ emit6(context2, "manage_group", args, msg2);
350745
351503
  return msg2;
350746
351504
  }
350747
351505
  const { action } = args;
@@ -350749,49 +351507,49 @@ async function manageGroup(args, context2) {
350749
351507
  const all = m2.listGroups();
350750
351508
  if (!all.length) {
350751
351509
  const msg3 = "No groups.";
350752
- emit5(context2, "manage_group", args, msg3);
351510
+ emit6(context2, "manage_group", args, msg3);
350753
351511
  return msg3;
350754
351512
  }
350755
351513
  const msg2 = `Groups (${all.length}):
350756
351514
  ${all.map((g) => `- ${g.name} (id=${g.id}${g.parentId ? `, parent=${g.parentId}` : ""})`).join("\n")}`;
350757
- emit5(context2, "manage_group", args, msg2);
351515
+ emit6(context2, "manage_group", args, msg2);
350758
351516
  return msg2;
350759
351517
  }
350760
351518
  if (action === "create") {
350761
351519
  if (!args.name) {
350762
351520
  const msg3 = "create requires name.";
350763
- emit5(context2, "manage_group", args, msg3);
351521
+ emit6(context2, "manage_group", args, msg3);
350764
351522
  return msg3;
350765
351523
  }
350766
351524
  const g = m2.createGroup(args.name, args.parentId ?? null);
350767
351525
  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);
351526
+ emit6(context2, "manage_group", args, msg2);
350769
351527
  return msg2;
350770
351528
  }
350771
351529
  if (action === "update") {
350772
351530
  if (!args.id) {
350773
351531
  const msg3 = "update requires id.";
350774
- emit5(context2, "manage_group", args, msg3);
351532
+ emit6(context2, "manage_group", args, msg3);
350775
351533
  return msg3;
350776
351534
  }
350777
351535
  const g = m2.updateGroup({ id: args.id, name: args.name ?? "", parentId: args.parentId });
350778
351536
  const msg2 = `Updated group "${g.name}".`;
350779
- emit5(context2, "manage_group", args, msg2);
351537
+ emit6(context2, "manage_group", args, msg2);
350780
351538
  return msg2;
350781
351539
  }
350782
351540
  if (action === "delete") {
350783
351541
  if (!args.id) {
350784
351542
  const msg3 = "delete requires id.";
350785
- emit5(context2, "manage_group", args, msg3);
351543
+ emit6(context2, "manage_group", args, msg3);
350786
351544
  return msg3;
350787
351545
  }
350788
351546
  const removed = m2.deleteGroup(args.id);
350789
351547
  const msg2 = removed ? `Deleted group ${args.id} (children reparented to root).` : `No group ${args.id}.`;
350790
- emit5(context2, "manage_group", args, msg2);
351548
+ emit6(context2, "manage_group", args, msg2);
350791
351549
  return msg2;
350792
351550
  }
350793
351551
  const msg = `Unknown action "${action}".`;
350794
- emit5(context2, "manage_group", args, msg);
351552
+ emit6(context2, "manage_group", args, msg);
350795
351553
  return msg;
350796
351554
  }
350797
351555
  var manageScheduledTaskSchema = external_exports.object({
@@ -350821,7 +351579,7 @@ async function manageScheduledTask(args, context2) {
350821
351579
  const m2 = context2.automationManager;
350822
351580
  if (!m2) {
350823
351581
  const msg2 = noStore();
350824
- emit5(context2, "manage_scheduled_task", args, msg2);
351582
+ emit6(context2, "manage_scheduled_task", args, msg2);
350825
351583
  return msg2;
350826
351584
  }
350827
351585
  const { action } = args;
@@ -350829,30 +351587,30 @@ async function manageScheduledTask(args, context2) {
350829
351587
  const all = m2.listScheduledTasks();
350830
351588
  if (!all.length) {
350831
351589
  const msg3 = "No scheduled tasks.";
350832
- emit5(context2, "manage_scheduled_task", args, msg3);
351590
+ emit6(context2, "manage_scheduled_task", args, msg3);
350833
351591
  return msg3;
350834
351592
  }
350835
351593
  const msg2 = `Scheduled tasks (${all.length}):
350836
351594
  ${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);
351595
+ emit6(context2, "manage_scheduled_task", args, msg2);
350838
351596
  return msg2;
350839
351597
  }
350840
351598
  if (action === "create") {
350841
351599
  if (!args.name || !args.cron) {
350842
351600
  const msg3 = "create requires name + cron.";
350843
- emit5(context2, "manage_scheduled_task", args, msg3);
351601
+ emit6(context2, "manage_scheduled_task", args, msg3);
350844
351602
  return msg3;
350845
351603
  }
350846
351604
  if (!args.scriptId && !args.command && !args.playbookId) {
350847
351605
  const msg3 = "create requires scriptId, command, or playbookId.";
350848
- emit5(context2, "manage_scheduled_task", args, msg3);
351606
+ emit6(context2, "manage_scheduled_task", args, msg3);
350849
351607
  return msg3;
350850
351608
  }
350851
351609
  const { validateCron: validateCron2 } = await Promise.resolve().then(() => (init_schedulerService(), schedulerService_exports));
350852
351610
  const v = validateCron2(args.cron);
350853
351611
  if (!v.ok) {
350854
351612
  const msg3 = `Invalid cron "${args.cron}": ${v.reason}`;
350855
- emit5(context2, "manage_scheduled_task", args, msg3);
351613
+ emit6(context2, "manage_scheduled_task", args, msg3);
350856
351614
  return msg3;
350857
351615
  }
350858
351616
  const t = m2.createScheduledTask({
@@ -350876,47 +351634,47 @@ ${all.map((t) => `- ${t.name} (id=${t.id}, cron="${t.cron}", enabled=${t.enabled
350876
351634
  alertAfterFailures: args.alertAfterFailures
350877
351635
  });
350878
351636
  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);
351637
+ emit6(context2, "manage_scheduled_task", args, msg2);
350880
351638
  return msg2;
350881
351639
  }
350882
351640
  if (action === "update") {
350883
351641
  if (!args.id) {
350884
351642
  const msg3 = "update requires id.";
350885
- emit5(context2, "manage_scheduled_task", args, msg3);
351643
+ emit6(context2, "manage_scheduled_task", args, msg3);
350886
351644
  return msg3;
350887
351645
  }
350888
351646
  const existing = m2.listScheduledTasks().find((t2) => t2.id === args.id);
350889
351647
  if (!existing) {
350890
351648
  const msg3 = `No task ${args.id}.`;
350891
- emit5(context2, "manage_scheduled_task", args, msg3);
351649
+ emit6(context2, "manage_scheduled_task", args, msg3);
350892
351650
  return msg3;
350893
351651
  }
350894
351652
  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
351653
  const msg2 = `Updated task "${t.name}".`;
350896
- emit5(context2, "manage_scheduled_task", args, msg2);
351654
+ emit6(context2, "manage_scheduled_task", args, msg2);
350897
351655
  return msg2;
350898
351656
  }
350899
351657
  if (action === "delete") {
350900
351658
  if (!args.id) {
350901
351659
  const msg3 = "delete requires id.";
350902
- emit5(context2, "manage_scheduled_task", args, msg3);
351660
+ emit6(context2, "manage_scheduled_task", args, msg3);
350903
351661
  return msg3;
350904
351662
  }
350905
351663
  const removed = m2.deleteScheduledTask(args.id);
350906
351664
  const msg2 = removed ? `Deleted task ${args.id}.` : `No task ${args.id}.`;
350907
- emit5(context2, "manage_scheduled_task", args, msg2);
351665
+ emit6(context2, "manage_scheduled_task", args, msg2);
350908
351666
  return msg2;
350909
351667
  }
350910
351668
  if (action === "validate") {
350911
351669
  if (!args.cron) {
350912
351670
  const msg3 = "validate requires cron.";
350913
- emit5(context2, "manage_scheduled_task", args, msg3);
351671
+ emit6(context2, "manage_scheduled_task", args, msg3);
350914
351672
  return msg3;
350915
351673
  }
350916
351674
  const { validateCron: validateCron2 } = await Promise.resolve().then(() => (init_schedulerService(), schedulerService_exports));
350917
351675
  const v = validateCron2(args.cron);
350918
351676
  const msg2 = v.ok ? `Cron "${args.cron}" is valid.` : `Invalid cron "${args.cron}": ${v.reason}`;
350919
- emit5(context2, "manage_scheduled_task", args, msg2);
351677
+ emit6(context2, "manage_scheduled_task", args, msg2);
350920
351678
  return msg2;
350921
351679
  }
350922
351680
  if (action === "drift") {
@@ -350925,20 +351683,20 @@ ${all.map((t) => `- ${t.name} (id=${t.id}, cron="${t.cron}", enabled=${t.enabled
350925
351683
  const flagged = drift.filter((d) => d.drifted);
350926
351684
  const msg2 = flagged.length === 0 ? `No drift detected across ${drift.length} enabled task(s).` : `Drifted task(s) (${flagged.length}):
350927
351685
  ${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);
351686
+ emit6(context2, "manage_scheduled_task", args, msg2);
350929
351687
  return msg2;
350930
351688
  }
350931
351689
  if (action === "history") {
350932
351690
  const sched = context2.scheduledTaskHistory;
350933
351691
  if (!sched) {
350934
351692
  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);
351693
+ emit6(context2, "manage_scheduled_task", args, msg3);
350936
351694
  return msg3;
350937
351695
  }
350938
351696
  const tasks = args.id ? m2.listScheduledTasks().filter((t) => t.id === args.id) : m2.listScheduledTasks();
350939
351697
  if (tasks.length === 0) {
350940
351698
  const msg3 = args.id ? `No task ${args.id}.` : "No scheduled tasks.";
350941
- emit5(context2, "manage_scheduled_task", args, msg3);
351699
+ emit6(context2, "manage_scheduled_task", args, msg3);
350942
351700
  return msg3;
350943
351701
  }
350944
351702
  const lines = tasks.map((t) => {
@@ -350951,34 +351709,34 @@ ${flagged.map((d) => `- ${d.taskName} (id=${d.taskId}): ${Number.isFinite(d.minu
350951
351709
  });
350952
351710
  const msg2 = `Scheduled task history:
350953
351711
  ${lines.join("\n")}`;
350954
- emit5(context2, "manage_scheduled_task", args, msg2);
351712
+ emit6(context2, "manage_scheduled_task", args, msg2);
350955
351713
  return msg2;
350956
351714
  }
350957
351715
  if (action === "runNow") {
350958
351716
  if (!args.id) {
350959
351717
  const msg3 = "runNow requires id.";
350960
- emit5(context2, "manage_scheduled_task", args, msg3);
351718
+ emit6(context2, "manage_scheduled_task", args, msg3);
350961
351719
  return msg3;
350962
351720
  }
350963
351721
  const task2 = m2.listScheduledTasks().find((t) => t.id === args.id);
350964
351722
  if (!task2) {
350965
351723
  const msg3 = `No task ${args.id}.`;
350966
- emit5(context2, "manage_scheduled_task", args, msg3);
351724
+ emit6(context2, "manage_scheduled_task", args, msg3);
350967
351725
  return msg3;
350968
351726
  }
350969
351727
  const sched = context2.scheduledTaskRunner;
350970
351728
  if (!sched) {
350971
351729
  const msg3 = "Run-now is not available in this runtime.";
350972
- emit5(context2, "manage_scheduled_task", args, msg3);
351730
+ emit6(context2, "manage_scheduled_task", args, msg3);
350973
351731
  return msg3;
350974
351732
  }
350975
351733
  const r = await sched(task2);
350976
351734
  const msg2 = r.ran ? `Task "${task2.name}" executed now.` : `Task "${task2.name}" not run: ${r.reason}.`;
350977
- emit5(context2, "manage_scheduled_task", args, msg2);
351735
+ emit6(context2, "manage_scheduled_task", args, msg2);
350978
351736
  return msg2;
350979
351737
  }
350980
351738
  const msg = `Unknown action "${action}".`;
350981
- emit5(context2, "manage_scheduled_task", args, msg);
351739
+ emit6(context2, "manage_scheduled_task", args, msg);
350982
351740
  return msg;
350983
351741
  }
350984
351742
  var manageTemplateSchema = external_exports.object({
@@ -350994,7 +351752,7 @@ async function manageTemplate(args, context2) {
350994
351752
  const m2 = context2.automationManager;
350995
351753
  if (!m2) {
350996
351754
  const msg2 = noStore();
350997
- emit5(context2, "manage_template", args, msg2);
351755
+ emit6(context2, "manage_template", args, msg2);
350998
351756
  return msg2;
350999
351757
  }
351000
351758
  const { action } = args;
@@ -351002,57 +351760,57 @@ async function manageTemplate(args, context2) {
351002
351760
  const all = m2.listTemplates();
351003
351761
  if (!all.length) {
351004
351762
  const msg3 = "No templates.";
351005
- emit5(context2, "manage_template", args, msg3);
351763
+ emit6(context2, "manage_template", args, msg3);
351006
351764
  return msg3;
351007
351765
  }
351008
351766
  const msg2 = `Templates (${all.length}):
351009
351767
  ${all.map((t) => `- ${t.name} (id=${t.id}, ${t.versions.length} version(s))`).join("\n")}`;
351010
- emit5(context2, "manage_template", args, msg2);
351768
+ emit6(context2, "manage_template", args, msg2);
351011
351769
  return msg2;
351012
351770
  }
351013
351771
  if (action === "create") {
351014
351772
  if (!args.name || !args.body) {
351015
351773
  const msg3 = "create requires name + body.";
351016
- emit5(context2, "manage_template", args, msg3);
351774
+ emit6(context2, "manage_template", args, msg3);
351017
351775
  return msg3;
351018
351776
  }
351019
351777
  const t = m2.createTemplate({ name: args.name, body: args.body, variables: args.variables ?? [] });
351020
351778
  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);
351779
+ emit6(context2, "manage_template", args, msg2);
351022
351780
  return msg2;
351023
351781
  }
351024
351782
  if (action === "update") {
351025
351783
  if (!args.id) {
351026
351784
  const msg3 = "update requires id.";
351027
- emit5(context2, "manage_template", args, msg3);
351785
+ emit6(context2, "manage_template", args, msg3);
351028
351786
  return msg3;
351029
351787
  }
351030
351788
  const t = m2.updateTemplate({ id: args.id, name: args.name, body: args.body, variables: args.variables });
351031
351789
  const msg2 = `Updated template "${t.name}".`;
351032
- emit5(context2, "manage_template", args, msg2);
351790
+ emit6(context2, "manage_template", args, msg2);
351033
351791
  return msg2;
351034
351792
  }
351035
351793
  if (action === "delete") {
351036
351794
  if (!args.id) {
351037
351795
  const msg3 = "delete requires id.";
351038
- emit5(context2, "manage_template", args, msg3);
351796
+ emit6(context2, "manage_template", args, msg3);
351039
351797
  return msg3;
351040
351798
  }
351041
351799
  const removed = m2.deleteTemplate(args.id);
351042
351800
  const msg2 = removed ? `Deleted template ${args.id}.` : `No template ${args.id}.`;
351043
- emit5(context2, "manage_template", args, msg2);
351801
+ emit6(context2, "manage_template", args, msg2);
351044
351802
  return msg2;
351045
351803
  }
351046
351804
  if (action === "render") {
351047
351805
  if (!args.id) {
351048
351806
  const msg3 = "render requires id.";
351049
- emit5(context2, "manage_template", args, msg3);
351807
+ emit6(context2, "manage_template", args, msg3);
351050
351808
  return msg3;
351051
351809
  }
351052
351810
  const t = m2.listTemplates().find((x) => x.id === args.id);
351053
351811
  if (!t) {
351054
351812
  const msg3 = `No template ${args.id}.`;
351055
- emit5(context2, "manage_template", args, msg3);
351813
+ emit6(context2, "manage_template", args, msg3);
351056
351814
  return msg3;
351057
351815
  }
351058
351816
  const defaults2 = {};
@@ -351063,19 +351821,19 @@ ${all.map((t) => `- ${t.name} (id=${t.id}, ${t.versions.length} version(s))`).jo
351063
351821
  <rendered>
351064
351822
  ${rendered}
351065
351823
  </rendered>`;
351066
- emit5(context2, "manage_template", args, msg2);
351824
+ emit6(context2, "manage_template", args, msg2);
351067
351825
  return msg2;
351068
351826
  }
351069
351827
  if (action === "version") {
351070
351828
  if (!args.id) {
351071
351829
  const msg3 = "version requires id.";
351072
- emit5(context2, "manage_template", args, msg3);
351830
+ emit6(context2, "manage_template", args, msg3);
351073
351831
  return msg3;
351074
351832
  }
351075
351833
  const t = m2.listTemplates().find((x) => x.id === args.id);
351076
351834
  if (!t) {
351077
351835
  const msg3 = `No template ${args.id}.`;
351078
- emit5(context2, "manage_template", args, msg3);
351836
+ emit6(context2, "manage_template", args, msg3);
351079
351837
  return msg3;
351080
351838
  }
351081
351839
  const defaults2 = {};
@@ -351089,11 +351847,11 @@ ${rendered}
351089
351847
  Diff vs previous version:
351090
351848
  ${diffStrings(prev.rendered, rendered)}` : "\n\n(first version)";
351091
351849
  const msg2 = `Saved version ${t.versions.length + 1} of "${t.name}" at ${v.at}.${diff}`;
351092
- emit5(context2, "manage_template", args, msg2);
351850
+ emit6(context2, "manage_template", args, msg2);
351093
351851
  return msg2;
351094
351852
  }
351095
351853
  const msg = `Unknown action "${action}".`;
351096
- emit5(context2, "manage_template", args, msg);
351854
+ emit6(context2, "manage_template", args, msg);
351097
351855
  return msg;
351098
351856
  }
351099
351857
  var importPuttySchema = external_exports.object({
@@ -351103,13 +351861,13 @@ async function importPutty(args, context2) {
351103
351861
  const cm = context2.connectionManager;
351104
351862
  if (!cm) {
351105
351863
  const msg2 = "Connection management is not available in this runtime.";
351106
- emit5(context2, "import_putty", args, msg2);
351864
+ emit6(context2, "import_putty", args, msg2);
351107
351865
  return msg2;
351108
351866
  }
351109
351867
  const entries = importPuttyReg(args.regContent);
351110
351868
  if (!entries.length) {
351111
351869
  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);
351870
+ emit6(context2, "import_putty", args, msg2);
351113
351871
  return msg2;
351114
351872
  }
351115
351873
  let created = 0;
@@ -351120,7 +351878,7 @@ async function importPutty(args, context2) {
351120
351878
  created++;
351121
351879
  }
351122
351880
  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);
351881
+ emit6(context2, "import_putty", args, msg);
351124
351882
  return msg;
351125
351883
  }
351126
351884
 
@@ -351131,7 +351889,7 @@ init_playbook_tools();
351131
351889
  init_zod();
351132
351890
  init_playbookRunner();
351133
351891
  init_scheduledTaskRunner();
351134
- function emit7(context2, toolName, input, output) {
351892
+ function emit8(context2, toolName, input, output) {
351135
351893
  context2.sendEvent(context2.sessionId, {
351136
351894
  messageId: context2.messageId,
351137
351895
  type: "tool_call",
@@ -351171,12 +351929,12 @@ async function manageChange(args, context2) {
351171
351929
  const ledger = context2.changeLedger;
351172
351930
  if (!m2) {
351173
351931
  const msg2 = "Automation store is not available in this runtime.";
351174
- emit7(context2, "manage_change", args, msg2);
351932
+ emit8(context2, "manage_change", args, msg2);
351175
351933
  return msg2;
351176
351934
  }
351177
351935
  if (!ledger) {
351178
351936
  const msg2 = "Change ledger is not available in this runtime.";
351179
- emit7(context2, "manage_change", args, msg2);
351937
+ emit8(context2, "manage_change", args, msg2);
351180
351938
  return msg2;
351181
351939
  }
351182
351940
  const { action } = args;
@@ -351184,13 +351942,13 @@ async function manageChange(args, context2) {
351184
351942
  const key = args.playbookId ?? args.name;
351185
351943
  if (!key) {
351186
351944
  const msg3 = "plan requires playbookId or name.";
351187
- emit7(context2, "manage_change", args, msg3);
351945
+ emit8(context2, "manage_change", args, msg3);
351188
351946
  return msg3;
351189
351947
  }
351190
351948
  const playbook = m2.getPlaybook(key);
351191
351949
  if (!playbook) {
351192
351950
  const msg3 = `No playbook "${key}".`;
351193
- emit7(context2, "manage_change", args, msg3);
351951
+ emit8(context2, "manage_change", args, msg3);
351194
351952
  return msg3;
351195
351953
  }
351196
351954
  const settings = settingsFromContext(context2);
@@ -351210,58 +351968,58 @@ Targets (${targets.length || 1}): ${targets.length ? targets.map((t) => t.name).
351210
351968
  Steps:
351211
351969
  ${steps}
351212
351970
  Next: manage_change action=approve changeId=${changeId}, then action=run.`;
351213
- emit7(context2, "manage_change", args, msg2);
351971
+ emit8(context2, "manage_change", args, msg2);
351214
351972
  return msg2;
351215
351973
  }
351216
351974
  if (action === "approve") {
351217
351975
  if (!args.changeId) {
351218
351976
  const msg3 = "approve requires changeId.";
351219
- emit7(context2, "manage_change", args, msg3);
351977
+ emit8(context2, "manage_change", args, msg3);
351220
351978
  return msg3;
351221
351979
  }
351222
351980
  const existing = ledger.getChange(args.changeId);
351223
351981
  if (!existing) {
351224
351982
  const msg3 = `No change "${args.changeId}".`;
351225
- emit7(context2, "manage_change", args, msg3);
351983
+ emit8(context2, "manage_change", args, msg3);
351226
351984
  return msg3;
351227
351985
  }
351228
351986
  if (existing.change.status !== "planned") {
351229
351987
  const msg3 = `Change ${args.changeId} is ${existing.change.status} \u2014 only planned changes can be approved.`;
351230
- emit7(context2, "manage_change", args, msg3);
351988
+ emit8(context2, "manage_change", args, msg3);
351231
351989
  return msg3;
351232
351990
  }
351233
351991
  ledger.approveChange(args.changeId, args.approvedBy);
351234
351992
  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);
351993
+ emit8(context2, "manage_change", args, msg2);
351236
351994
  return msg2;
351237
351995
  }
351238
351996
  if (action === "run") {
351239
351997
  if (!args.changeId) {
351240
351998
  const msg3 = "run requires changeId.";
351241
- emit7(context2, "manage_change", args, msg3);
351999
+ emit8(context2, "manage_change", args, msg3);
351242
352000
  return msg3;
351243
352001
  }
351244
352002
  const existing = ledger.getChange(args.changeId);
351245
352003
  if (!existing) {
351246
352004
  const msg3 = `No change "${args.changeId}". Plan one first with manage_change action=plan.`;
351247
- emit7(context2, "manage_change", args, msg3);
352005
+ emit8(context2, "manage_change", args, msg3);
351248
352006
  return msg3;
351249
352007
  }
351250
352008
  if (existing.change.status !== "approved") {
351251
352009
  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);
352010
+ emit8(context2, "manage_change", args, msg3);
351253
352011
  return msg3;
351254
352012
  }
351255
352013
  const playbook = m2.getPlaybook(existing.change.playbookId);
351256
352014
  if (!playbook) {
351257
352015
  ledger.finishChange(args.changeId, "failed", "playbook no longer exists");
351258
352016
  const msg3 = `Playbook ${existing.change.playbookId} no longer exists; change marked failed.`;
351259
- emit7(context2, "manage_change", args, msg3);
352017
+ emit8(context2, "manage_change", args, msg3);
351260
352018
  return msg3;
351261
352019
  }
351262
352020
  if (!ledger.markExecuting(args.changeId)) {
351263
352021
  const msg3 = `Change ${args.changeId} could not transition to executing (status=${existing.change.status}).`;
351264
- emit7(context2, "manage_change", args, msg3);
352022
+ emit8(context2, "manage_change", args, msg3);
351265
352023
  return msg3;
351266
352024
  }
351267
352025
  const settings = settingsFromContext(context2);
@@ -351283,7 +352041,7 @@ Next: manage_change action=approve changeId=${changeId}, then action=run.`;
351283
352041
  const errMsg = error40 instanceof Error ? error40.message : String(error40);
351284
352042
  ledger.finishChange(args.changeId, "failed", errMsg);
351285
352043
  const msg3 = `Change ${args.changeId} failed to execute: ${errMsg}`;
351286
- emit7(context2, "manage_change", args, msg3);
352044
+ emit8(context2, "manage_change", args, msg3);
351287
352045
  return msg3;
351288
352046
  }
351289
352047
  const finalStatus = deriveFinalStatus(record2);
@@ -351301,19 +352059,19 @@ Next: manage_change action=approve changeId=${changeId}, then action=run.`;
351301
352059
  }
351302
352060
  const msg2 = `Change ${args.changeId} finished with status=${finalStatus} (runId=${record2.runId}).
351303
352061
  ${lines.join("\n")}`;
351304
- emit7(context2, "manage_change", args, msg2);
352062
+ emit8(context2, "manage_change", args, msg2);
351305
352063
  return msg2;
351306
352064
  }
351307
352065
  if (action === "status") {
351308
352066
  if (!args.changeId) {
351309
352067
  const msg3 = "status requires changeId.";
351310
- emit7(context2, "manage_change", args, msg3);
352068
+ emit8(context2, "manage_change", args, msg3);
351311
352069
  return msg3;
351312
352070
  }
351313
352071
  const got = ledger.getChange(args.changeId);
351314
352072
  if (!got) {
351315
352073
  const msg3 = `No change "${args.changeId}".`;
351316
- emit7(context2, "manage_change", args, msg3);
352074
+ emit8(context2, "manage_change", args, msg3);
351317
352075
  return msg3;
351318
352076
  }
351319
352077
  const { change, steps } = got;
@@ -351332,14 +352090,14 @@ ${meta}
351332
352090
  Targets: ${change.targetsSnapshot ?? "n/a"}
351333
352091
  Events:
351334
352092
  ${body}`;
351335
- emit7(context2, "manage_change", args, msg2);
352093
+ emit8(context2, "manage_change", args, msg2);
351336
352094
  return msg2;
351337
352095
  }
351338
352096
  if (action === "list") {
351339
352097
  const rows = ledger.listChanges({ status: args.status, limit: args.limit ?? 20 });
351340
352098
  if (!rows.length) {
351341
352099
  const msg3 = "No changes recorded yet. Plan one with manage_change action=plan.";
351342
- emit7(context2, "manage_change", args, msg3);
352100
+ emit8(context2, "manage_change", args, msg3);
351343
352101
  return msg3;
351344
352102
  }
351345
352103
  const body = rows.map(
@@ -351347,18 +352105,18 @@ ${body}`;
351347
352105
  ).join("\n");
351348
352106
  const msg2 = `Changes (${rows.length}):
351349
352107
  ${body}`;
351350
- emit7(context2, "manage_change", args, msg2);
352108
+ emit8(context2, "manage_change", args, msg2);
351351
352109
  return msg2;
351352
352110
  }
351353
352111
  const msg = `Unknown action "${action}".`;
351354
- emit7(context2, "manage_change", args, msg);
352112
+ emit8(context2, "manage_change", args, msg);
351355
352113
  return msg;
351356
352114
  }
351357
352115
 
351358
352116
  // ../../packages/backend/src/services/AgentHelper/tools/trigger_tools.ts
351359
352117
  init_zod();
351360
352118
  var import_crypto6 = require("crypto");
351361
- function emit8(context2, name, input, output) {
352119
+ function emit9(context2, name, input, output) {
351362
352120
  context2.sendEvent(context2.sessionId, {
351363
352121
  messageId: context2.messageId,
351364
352122
  type: "tool_call",
@@ -351387,7 +352145,7 @@ async function manageTrigger(args, context2) {
351387
352145
  const m2 = context2.automationManager;
351388
352146
  if (!m2 || typeof m2.listTriggers !== "function") {
351389
352147
  const msg2 = "Automation store with trigger support is not available in this runtime.";
351390
- emit8(context2, "manage_trigger", args, msg2);
352148
+ emit9(context2, "manage_trigger", args, msg2);
351391
352149
  return msg2;
351392
352150
  }
351393
352151
  const engine = context2.triggerEngine;
@@ -351396,7 +352154,7 @@ async function manageTrigger(args, context2) {
351396
352154
  const all = m2.listTriggers();
351397
352155
  if (!all.length) {
351398
352156
  const msg3 = "No triggers configured.";
351399
- emit8(context2, "manage_trigger", args, msg3);
352157
+ emit9(context2, "manage_trigger", args, msg3);
351400
352158
  return msg3;
351401
352159
  }
351402
352160
  const body = all.map((t) => {
@@ -351405,14 +352163,14 @@ async function manageTrigger(args, context2) {
351405
352163
  }).join("\n");
351406
352164
  const msg2 = `Triggers (${all.length}):
351407
352165
  ${body}`;
351408
- emit8(context2, "manage_trigger", args, msg2);
352166
+ emit9(context2, "manage_trigger", args, msg2);
351409
352167
  return msg2;
351410
352168
  }
351411
352169
  if (action === "fires") {
351412
352170
  const fires = engine?.listFires?.() ?? [];
351413
352171
  if (!fires.length) {
351414
352172
  const msg3 = "No trigger firings recorded yet.";
351415
- emit8(context2, "manage_trigger", args, msg3);
352173
+ emit9(context2, "manage_trigger", args, msg3);
351416
352174
  return msg3;
351417
352175
  }
351418
352176
  const limit2 = args.limit ?? 20;
@@ -351421,23 +352179,23 @@ ${body}`;
351421
352179
  ).join("\n");
351422
352180
  const msg2 = `Recent trigger firings (${Math.min(limit2, fires.length)} of ${fires.length}):
351423
352181
  ${body}`;
351424
- emit8(context2, "manage_trigger", args, msg2);
352182
+ emit9(context2, "manage_trigger", args, msg2);
351425
352183
  return msg2;
351426
352184
  }
351427
352185
  if (action === "create") {
351428
352186
  if (!args.name) {
351429
352187
  const msg3 = "create requires a name.";
351430
- emit8(context2, "manage_trigger", args, msg3);
352188
+ emit9(context2, "manage_trigger", args, msg3);
351431
352189
  return msg3;
351432
352190
  }
351433
352191
  if (!args.kind) {
351434
352192
  const msg3 = "create requires a kind (pattern|threshold|webhook|schedule).";
351435
- emit8(context2, "manage_trigger", args, msg3);
352193
+ emit9(context2, "manage_trigger", args, msg3);
351436
352194
  return msg3;
351437
352195
  }
351438
352196
  if (!args.playbookId) {
351439
352197
  const msg3 = "create requires playbookId.";
351440
- emit8(context2, "manage_trigger", args, msg3);
352198
+ emit9(context2, "manage_trigger", args, msg3);
351441
352199
  return msg3;
351442
352200
  }
351443
352201
  const entry = {
@@ -351463,20 +352221,20 @@ ${body}`;
351463
352221
  } catch {
351464
352222
  }
351465
352223
  const msg2 = `Created trigger "${entry.name}" (${entry.id}) [${entry.kind}] \u2192 ${entry.action} ${entry.playbookId}.`;
351466
- emit8(context2, "manage_trigger", args, msg2);
352224
+ emit9(context2, "manage_trigger", args, msg2);
351467
352225
  return msg2;
351468
352226
  }
351469
352227
  if (action === "update") {
351470
352228
  const key = args.id ?? args.name;
351471
352229
  if (!key) {
351472
352230
  const msg3 = "update requires id or name.";
351473
- emit8(context2, "manage_trigger", args, msg3);
352231
+ emit9(context2, "manage_trigger", args, msg3);
351474
352232
  return msg3;
351475
352233
  }
351476
352234
  const existing = m2.listTriggers().find((t) => t.id === key || t.name.trim().toLowerCase() === key.trim().toLowerCase());
351477
352235
  if (!existing) {
351478
352236
  const msg3 = `No trigger "${key}".`;
351479
- emit8(context2, "manage_trigger", args, msg3);
352237
+ emit9(context2, "manage_trigger", args, msg3);
351480
352238
  return msg3;
351481
352239
  }
351482
352240
  const merged = {
@@ -351499,14 +352257,14 @@ ${body}`;
351499
352257
  } catch {
351500
352258
  }
351501
352259
  const msg2 = `Updated trigger "${merged.name}" (${merged.id}).`;
351502
- emit8(context2, "manage_trigger", args, msg2);
352260
+ emit9(context2, "manage_trigger", args, msg2);
351503
352261
  return msg2;
351504
352262
  }
351505
352263
  if (action === "delete") {
351506
352264
  const key = args.id ?? args.name;
351507
352265
  if (!key) {
351508
352266
  const msg3 = "delete requires id or name.";
351509
- emit8(context2, "manage_trigger", args, msg3);
352267
+ emit9(context2, "manage_trigger", args, msg3);
351510
352268
  return msg3;
351511
352269
  }
351512
352270
  const ok = m2.deleteTrigger(key);
@@ -351517,14 +352275,14 @@ ${body}`;
351517
352275
  }
351518
352276
  }
351519
352277
  const msg2 = ok ? `Deleted trigger "${key}".` : `No trigger "${key}".`;
351520
- emit8(context2, "manage_trigger", args, msg2);
352278
+ emit9(context2, "manage_trigger", args, msg2);
351521
352279
  return msg2;
351522
352280
  }
351523
352281
  if (action === "enable" || action === "disable") {
351524
352282
  const key = args.id ?? args.name;
351525
352283
  if (!key) {
351526
352284
  const msg3 = `${action} requires id or name.`;
351527
- emit8(context2, "manage_trigger", args, msg3);
352285
+ emit9(context2, "manage_trigger", args, msg3);
351528
352286
  return msg3;
351529
352287
  }
351530
352288
  const ok = m2.setTriggerEnabled(key, action === "enable");
@@ -351536,11 +352294,11 @@ ${body}`;
351536
352294
  }
351537
352295
  }
351538
352296
  const msg2 = ok ? `Trigger "${key}" ${action}d.` : `No trigger "${key}".`;
351539
- emit8(context2, "manage_trigger", args, msg2);
352297
+ emit9(context2, "manage_trigger", args, msg2);
351540
352298
  return msg2;
351541
352299
  }
351542
352300
  const msg = `Unknown action "${action}".`;
351543
- emit8(context2, "manage_trigger", args, msg);
352301
+ emit9(context2, "manage_trigger", args, msg);
351544
352302
  return msg;
351545
352303
  }
351546
352304
 
@@ -351898,10 +352656,10 @@ async function listGatewayMethods(args, context2) {
351898
352656
  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
352657
  const out = `Gateway methods (${methods.length} of ${payload.count}, registry v${payload.version}):
351900
352658
  ${lines.join("\n")}`;
351901
- emit9(context2, "list_gateway_methods", args, out);
352659
+ emit10(context2, "list_gateway_methods", args, out);
351902
352660
  return out;
351903
352661
  }
351904
- function emit9(context2, toolName, input, output) {
352662
+ function emit10(context2, toolName, input, output) {
351905
352663
  context2.sendEvent(context2.sessionId, {
351906
352664
  messageId: context2.messageId,
351907
352665
  type: "tool_call",
@@ -351914,7 +352672,7 @@ function obs(context2, toolName, args) {
351914
352672
  const o = context2.observability;
351915
352673
  if (!o) {
351916
352674
  const msg = `${toolName} is not available in this runtime (observability not wired).`;
351917
- emit9(context2, toolName, args, msg);
352675
+ emit10(context2, toolName, args, msg);
351918
352676
  return { o: null, msg };
351919
352677
  }
351920
352678
  return { o, msg: null };
@@ -351926,7 +352684,7 @@ async function getMetrics(args, context2) {
351926
352684
  const { o, msg } = obs(context2, "get_metrics", args);
351927
352685
  if (!o) return msg;
351928
352686
  const out = args.format === "prometheus" ? o.metricsExport.renderPrometheus() || "# no host metrics recorded yet" : await o.dashboard.summary();
351929
- emit9(context2, "get_metrics", args, out);
352687
+ emit10(context2, "get_metrics", args, out);
351930
352688
  return out;
351931
352689
  }
351932
352690
  var manageSecretSchema = external_exports.object({
@@ -351941,7 +352699,7 @@ async function manageSecret(args, context2) {
351941
352699
  const v = o.secrets;
351942
352700
  if (!v.unlocked()) {
351943
352701
  const m2 = "Secrets vault is locked \u2014 start RTerm with RTERM_SECRETS_MASTER_KEY set.";
351944
- emit9(context2, "manage_secret", args, m2);
352702
+ emit10(context2, "manage_secret", args, m2);
351945
352703
  return m2;
351946
352704
  }
351947
352705
  let out;
@@ -351968,7 +352726,7 @@ async function manageSecret(args, context2) {
351968
352726
  out = v.has(args.key) ? `'${args.key}' exists.` : `'${args.key}' does not exist.`;
351969
352727
  }
351970
352728
  }
351971
- emit9(context2, "manage_secret", args, out);
352729
+ emit10(context2, "manage_secret", args, out);
351972
352730
  return out;
351973
352731
  }
351974
352732
  var manageOncallSchema = external_exports.object({
@@ -352020,7 +352778,7 @@ async function manageOncall(args, context2) {
352020
352778
  } catch (e) {
352021
352779
  out = `on-call error: ${e instanceof Error ? e.message : String(e)}`;
352022
352780
  }
352023
- emit9(context2, "manage_oncall", args, out);
352781
+ emit10(context2, "manage_oncall", args, out);
352024
352782
  return out;
352025
352783
  }
352026
352784
  var getCostSchema = external_exports.object({
@@ -352044,7 +352802,7 @@ async function getCost(args, context2) {
352044
352802
  const b = o.cost.listBudgets();
352045
352803
  out = b.length ? b.map((x) => `- ${x.id}: ${x.model ?? "*"}/${x.profileId ?? "*"} ${x.period} cap $${x.capUsd}`).join("\n") : "No budgets configured.";
352046
352804
  }
352047
- emit9(context2, "get_cost", args, out);
352805
+ emit10(context2, "get_cost", args, out);
352048
352806
  return out;
352049
352807
  }
352050
352808
  var manageRecordingSchema = external_exports.object({
@@ -352110,7 +352868,7 @@ async function manageRecording(args, context2) {
352110
352868
  } catch (e) {
352111
352869
  out = `recording error: ${e instanceof Error ? e.message : String(e)}`;
352112
352870
  }
352113
- emit9(context2, "manage_recording", args, out);
352871
+ emit10(context2, "manage_recording", args, out);
352114
352872
  return out;
352115
352873
  }
352116
352874
  var manageGitopsSchema = external_exports.object({
@@ -352142,7 +352900,7 @@ async function manageGitops(args, context2) {
352142
352900
  } catch (e) {
352143
352901
  out = `gitops error: ${e instanceof Error ? e.message : String(e)}`;
352144
352902
  }
352145
- emit9(context2, "manage_gitops", args, out);
352903
+ emit10(context2, "manage_gitops", args, out);
352146
352904
  return out;
352147
352905
  }
352148
352906
  var managePlaybookVersionSchema = external_exports.object({
@@ -352189,7 +352947,7 @@ async function managePlaybookVersion(args, context2) {
352189
352947
  } catch (e) {
352190
352948
  out = `playbook error: ${e instanceof Error ? e.message : String(e)}`;
352191
352949
  }
352192
- emit9(context2, "manage_playbook_version", args, out);
352950
+ emit10(context2, "manage_playbook_version", args, out);
352193
352951
  return out;
352194
352952
  }
352195
352953
  var getCloudInventorySchema = external_exports.object({
@@ -352216,7 +352974,7 @@ async function getCloudInventory(args, context2) {
352216
352974
  } catch (e) {
352217
352975
  out = `cloud error: ${e instanceof Error ? e.message : String(e)}`;
352218
352976
  }
352219
- emit9(context2, "get_cloud_inventory", args, out);
352977
+ emit10(context2, "get_cloud_inventory", args, out);
352220
352978
  return out;
352221
352979
  }
352222
352980
  var getMonitorStatusSchema = external_exports.object({
@@ -352231,7 +352989,7 @@ async function getMonitorStatus(args, context2) {
352231
352989
  } else {
352232
352990
  out = o.monitorStatus.summary();
352233
352991
  }
352234
- emit9(context2, "get_monitor_status", args, out);
352992
+ emit10(context2, "get_monitor_status", args, out);
352235
352993
  return out;
352236
352994
  }
352237
352995
  var getLiveDashboardSchema = external_exports.object({
@@ -352247,7 +353005,7 @@ async function getLiveDashboard(args, context2) {
352247
353005
  const s = await o.dashboard.summary();
352248
353006
  out = s;
352249
353007
  }
352250
- emit9(context2, "get_live_dashboard", args, out);
353008
+ emit10(context2, "get_live_dashboard", args, out);
352251
353009
  return out;
352252
353010
  }
352253
353011
  var ingestApmSpansSchema = external_exports.object({
@@ -352260,7 +353018,7 @@ async function ingestApmSpans(args, context2) {
352260
353018
  const { ingestOtlp: ingestOtlp2 } = await Promise.resolve().then(() => (init_spanLedger(), spanLedger_exports));
352261
353019
  const n2 = ingestOtlp2(o.spanLedger, args.payload, args.defaultService);
352262
353020
  const out = `Ingested ${n2} APM span(s) into the trace store.`;
352263
- emit9(context2, "ingest_apm_spans", args, out);
353021
+ emit10(context2, "ingest_apm_spans", args, out);
352264
353022
  return out;
352265
353023
  }
352266
353024
  var getApmSummarySchema = external_exports.object({});
@@ -352269,7 +353027,7 @@ async function getApmSummary(_args, context2) {
352269
353027
  if (!o) return msg;
352270
353028
  const stats = o.spanLedger.serviceStats();
352271
353029
  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);
353030
+ emit10(context2, "get_apm_summary", _args, out);
352273
353031
  return out;
352274
353032
  }
352275
353033
  var ingestDemBeaconSchema = external_exports.object({
@@ -352280,7 +353038,7 @@ async function ingestDemBeacon(args, context2) {
352280
353038
  if (!o) return msg;
352281
353039
  const s = o.rumLedger.ingestBeacon(args.payload);
352282
353040
  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);
353041
+ emit10(context2, "ingest_dem_beacon", args, out);
352284
353042
  return out;
352285
353043
  }
352286
353044
  var getDemSummarySchema = external_exports.object({});
@@ -352289,7 +353047,7 @@ async function getDemSummary(_args, context2) {
352289
353047
  if (!o) return msg;
352290
353048
  const pages = o.rumLedger.pageStats();
352291
353049
  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);
353050
+ emit10(context2, "get_dem_summary", _args, out);
352293
353051
  return out;
352294
353052
  }
352295
353053
  var collectInfraSchema = external_exports.object({
@@ -352334,7 +353092,7 @@ async function collectInfra(args, context2) {
352334
353092
  } catch (e) {
352335
353093
  out = `infra collect failed (kubectl or cluster unavailable): ${e instanceof Error ? e.message : String(e)}`;
352336
353094
  }
352337
- emit9(context2, "collect_infra", args, out);
353095
+ emit10(context2, "collect_infra", args, out);
352338
353096
  return out;
352339
353097
  }
352340
353098
  var manageEtwSchema = external_exports.object({
@@ -352393,7 +353151,7 @@ ${buildStopCommands2(s).join("\n")}`;
352393
353151
  } catch (e) {
352394
353152
  out = `etw error: ${e instanceof Error ? e.message : String(e)}`;
352395
353153
  }
352396
- emit9(context2, "manage_etw", args, out);
353154
+ emit10(context2, "manage_etw", args, out);
352397
353155
  return out;
352398
353156
  }
352399
353157
 
@@ -352612,6 +353370,21 @@ function buildToolsForModel(readFileSupport) {
352612
353370
  description: BUILTIN_TOOL_INFO.find((t) => t.name === "get_run_ledger")?.description ?? "",
352613
353371
  schema: getRunLedgerSchema
352614
353372
  },
353373
+ {
353374
+ name: "ops_experiment",
353375
+ description: BUILTIN_TOOL_INFO.find((t) => t.name === "ops_experiment")?.description ?? "",
353376
+ schema: opsExperimentSchema
353377
+ },
353378
+ {
353379
+ name: "manage_goal",
353380
+ description: BUILTIN_TOOL_INFO.find((t) => t.name === "manage_goal")?.description ?? "",
353381
+ schema: manageGoalSchema
353382
+ },
353383
+ {
353384
+ name: "estate_facts",
353385
+ description: BUILTIN_TOOL_INFO.find((t) => t.name === "estate_facts")?.description ?? "",
353386
+ schema: estateFactsSchema
353387
+ },
352615
353388
  {
352616
353389
  name: "run_fleet_command",
352617
353390
  description: BUILTIN_TOOL_INFO.find((t) => t.name === "run_fleet_command")?.description ?? "",
@@ -352796,6 +353569,9 @@ var toolImplementations = {
352796
353569
  readSessionLog,
352797
353570
  searchSessionLogs,
352798
353571
  getRunLedger,
353572
+ opsExperiment,
353573
+ manageGoal,
353574
+ estateFacts,
352799
353575
  runFleetCommand,
352800
353576
  collectFacts,
352801
353577
  probeConnectivity,
@@ -354538,12 +355314,12 @@ function encodeURIPath(str3) {
354538
355314
  return str3.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
354539
355315
  }
354540
355316
  var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
354541
- var createPathTagFunction = (pathEncoder = encodeURIPath) => function path32(statics, ...params) {
355317
+ var createPathTagFunction = (pathEncoder = encodeURIPath) => function path33(statics, ...params) {
354542
355318
  if (statics.length === 1)
354543
355319
  return statics[0];
354544
355320
  let postPath = false;
354545
355321
  const invalidSegments = [];
354546
- const path33 = statics.reduce((previousValue, currentValue, index2) => {
355322
+ const path34 = statics.reduce((previousValue, currentValue, index2) => {
354547
355323
  if (/[?#]/.test(currentValue)) {
354548
355324
  postPath = true;
354549
355325
  }
@@ -354560,7 +355336,7 @@ var createPathTagFunction = (pathEncoder = encodeURIPath) => function path32(sta
354560
355336
  }
354561
355337
  return previousValue + currentValue + (index2 === params.length ? "" : encoded);
354562
355338
  }, "");
354563
- const pathOnly = path33.split(/[?#]/, 1)[0];
355339
+ const pathOnly = path34.split(/[?#]/, 1)[0];
354564
355340
  const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
354565
355341
  let match;
354566
355342
  while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
@@ -354581,10 +355357,10 @@ var createPathTagFunction = (pathEncoder = encodeURIPath) => function path32(sta
354581
355357
  }, "");
354582
355358
  throw new OpenAIError(`Path parameters result in path with invalid segments:
354583
355359
  ${invalidSegments.map((e) => e.error).join("\n")}
354584
- ${path33}
355360
+ ${path34}
354585
355361
  ${underline}`);
354586
355362
  }
354587
- return path33;
355363
+ return path34;
354588
355364
  };
354589
355365
  var path8 = /* @__PURE__ */ createPathTagFunction(encodeURIPath);
354590
355366
 
@@ -354957,11 +355733,11 @@ var AbstractChatCompletionRunner = class extends EventStream {
354957
355733
  this._addMessage(message);
354958
355734
  return chatCompletion;
354959
355735
  }
354960
- _addMessage(message, emit10 = true) {
355736
+ _addMessage(message, emit11 = true) {
354961
355737
  if (!("content" in message))
354962
355738
  message.content = null;
354963
355739
  this.messages.push(message);
354964
- if (emit10) {
355740
+ if (emit11) {
354965
355741
  this._emit("message", message);
354966
355742
  if (isToolMessage2(message) && message.content) {
354967
355743
  this._emit("functionToolCallResult", message.content);
@@ -355213,8 +355989,8 @@ var ChatCompletionRunner = class _ChatCompletionRunner extends AbstractChatCompl
355213
355989
  runner._run(() => runner._runTools(client2, params, opts));
355214
355990
  return runner;
355215
355991
  }
355216
- _addMessage(message, emit10 = true) {
355217
- super._addMessage(message, emit10);
355992
+ _addMessage(message, emit11 = true) {
355993
+ super._addMessage(message, emit11);
355218
355994
  if (isAssistantMessage(message) && message.content) {
355219
355995
  this._emit("content", message.content);
355220
355996
  }
@@ -359401,9 +360177,9 @@ var OpenAI = class {
359401
360177
  this.apiKey = token;
359402
360178
  return true;
359403
360179
  }
359404
- buildURL(path32, query, defaultBaseURL) {
360180
+ buildURL(path33, query, defaultBaseURL) {
359405
360181
  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));
360182
+ const url2 = isAbsoluteURL(path33) ? new URL(path33) : new URL(baseURL + (baseURL.endsWith("/") && path33.startsWith("/") ? path33.slice(1) : path33));
359407
360183
  const defaultQuery = this.defaultQuery();
359408
360184
  if (!isEmptyObj(defaultQuery)) {
359409
360185
  query = { ...defaultQuery, ...query };
@@ -359427,24 +360203,24 @@ var OpenAI = class {
359427
360203
  */
359428
360204
  async prepareRequest(request, { url: url2, options }) {
359429
360205
  }
359430
- get(path32, opts) {
359431
- return this.methodRequest("get", path32, opts);
360206
+ get(path33, opts) {
360207
+ return this.methodRequest("get", path33, opts);
359432
360208
  }
359433
- post(path32, opts) {
359434
- return this.methodRequest("post", path32, opts);
360209
+ post(path33, opts) {
360210
+ return this.methodRequest("post", path33, opts);
359435
360211
  }
359436
- patch(path32, opts) {
359437
- return this.methodRequest("patch", path32, opts);
360212
+ patch(path33, opts) {
360213
+ return this.methodRequest("patch", path33, opts);
359438
360214
  }
359439
- put(path32, opts) {
359440
- return this.methodRequest("put", path32, opts);
360215
+ put(path33, opts) {
360216
+ return this.methodRequest("put", path33, opts);
359441
360217
  }
359442
- delete(path32, opts) {
359443
- return this.methodRequest("delete", path32, opts);
360218
+ delete(path33, opts) {
360219
+ return this.methodRequest("delete", path33, opts);
359444
360220
  }
359445
- methodRequest(method, path32, opts) {
360221
+ methodRequest(method, path33, opts) {
359446
360222
  return this.request(Promise.resolve(opts).then((opts2) => {
359447
- return { method, path: path32, ...opts2 };
360223
+ return { method, path: path33, ...opts2 };
359448
360224
  }));
359449
360225
  }
359450
360226
  request(options, remainingRetries = null) {
@@ -359548,8 +360324,8 @@ var OpenAI = class {
359548
360324
  }));
359549
360325
  return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
359550
360326
  }
359551
- getAPIList(path32, Page2, opts) {
359552
- return this.requestAPIList(Page2, { method: "get", path: path32, ...opts });
360327
+ getAPIList(path33, Page2, opts) {
360328
+ return this.requestAPIList(Page2, { method: "get", path: path33, ...opts });
359553
360329
  }
359554
360330
  requestAPIList(Page2, options) {
359555
360331
  const request = this.makeRequest(options, null, void 0);
@@ -359627,8 +360403,8 @@ var OpenAI = class {
359627
360403
  }
359628
360404
  async buildRequest(inputOptions, { retryCount = 0 } = {}) {
359629
360405
  const options = { ...inputOptions };
359630
- const { method, path: path32, query, defaultBaseURL } = options;
359631
- const url2 = this.buildURL(path32, query, defaultBaseURL);
360406
+ const { method, path: path33, query, defaultBaseURL } = options;
360407
+ const url2 = this.buildURL(path33, query, defaultBaseURL);
359632
360408
  if ("timeout" in options)
359633
360409
  validatePositiveInteger("timeout", options.timeout);
359634
360410
  options.timeout = options.timeout ?? this.timeout;
@@ -361244,23 +362020,23 @@ function isNullable(schema2) {
361244
362020
  }
361245
362021
  return false;
361246
362022
  }
361247
- function ensureStrictJsonSchema(jsonSchema, path32, root) {
362023
+ function ensureStrictJsonSchema(jsonSchema, path33, root) {
361248
362024
  if (typeof jsonSchema === "boolean") {
361249
- throw new TypeError(`Expected object schema but got boolean; path=${path32.join("/")}`);
362025
+ throw new TypeError(`Expected object schema but got boolean; path=${path33.join("/")}`);
361250
362026
  }
361251
362027
  if (!isObject4(jsonSchema)) {
361252
- throw new TypeError(`Expected ${JSON.stringify(jsonSchema)} to be an object; path=${path32.join("/")}`);
362028
+ throw new TypeError(`Expected ${JSON.stringify(jsonSchema)} to be an object; path=${path33.join("/")}`);
361253
362029
  }
361254
362030
  const defs = jsonSchema.$defs;
361255
362031
  if (isObject4(defs)) {
361256
362032
  for (const [defName, defSchema] of Object.entries(defs)) {
361257
- ensureStrictJsonSchema(defSchema, [...path32, "$defs", defName], root);
362033
+ ensureStrictJsonSchema(defSchema, [...path33, "$defs", defName], root);
361258
362034
  }
361259
362035
  }
361260
362036
  const definitions = jsonSchema.definitions;
361261
362037
  if (isObject4(definitions)) {
361262
362038
  for (const [definitionName, definitionSchema] of Object.entries(definitions)) {
361263
- ensureStrictJsonSchema(definitionSchema, [...path32, "definitions", definitionName], root);
362039
+ ensureStrictJsonSchema(definitionSchema, [...path33, "definitions", definitionName], root);
361264
362040
  }
361265
362041
  }
361266
362042
  const typ = jsonSchema.type;
@@ -361272,31 +362048,31 @@ function ensureStrictJsonSchema(jsonSchema, path32, root) {
361272
362048
  if (isObject4(properties)) {
361273
362049
  for (const [key, value] of Object.entries(properties)) {
361274
362050
  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`);
362051
+ 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
362052
  }
361277
362053
  }
361278
362054
  jsonSchema.required = Object.keys(properties);
361279
362055
  jsonSchema.properties = Object.fromEntries(Object.entries(properties).map(([key, propSchema]) => [
361280
362056
  key,
361281
- ensureStrictJsonSchema(propSchema, [...path32, "properties", key], root)
362057
+ ensureStrictJsonSchema(propSchema, [...path33, "properties", key], root)
361282
362058
  ]));
361283
362059
  }
361284
362060
  const items = jsonSchema.items;
361285
362061
  if (isObject4(items)) {
361286
- jsonSchema.items = ensureStrictJsonSchema(items, [...path32, "items"], root);
362062
+ jsonSchema.items = ensureStrictJsonSchema(items, [...path33, "items"], root);
361287
362063
  }
361288
362064
  const anyOf = jsonSchema.anyOf;
361289
362065
  if (Array.isArray(anyOf)) {
361290
- jsonSchema.anyOf = anyOf.map((variant, i) => ensureStrictJsonSchema(variant, [...path32, "anyOf", String(i)], root));
362066
+ jsonSchema.anyOf = anyOf.map((variant, i) => ensureStrictJsonSchema(variant, [...path33, "anyOf", String(i)], root));
361291
362067
  }
361292
362068
  const allOf = jsonSchema.allOf;
361293
362069
  if (Array.isArray(allOf)) {
361294
362070
  if (allOf.length === 1) {
361295
- const resolved = ensureStrictJsonSchema(allOf[0], [...path32, "allOf", "0"], root);
362071
+ const resolved = ensureStrictJsonSchema(allOf[0], [...path33, "allOf", "0"], root);
361296
362072
  Object.assign(jsonSchema, resolved);
361297
362073
  delete jsonSchema.allOf;
361298
362074
  } else {
361299
- jsonSchema.allOf = allOf.map((entry, i) => ensureStrictJsonSchema(entry, [...path32, "allOf", String(i)], root));
362075
+ jsonSchema.allOf = allOf.map((entry, i) => ensureStrictJsonSchema(entry, [...path33, "allOf", String(i)], root));
361300
362076
  }
361301
362077
  }
361302
362078
  if (jsonSchema.default === null) {
@@ -361305,7 +362081,7 @@ function ensureStrictJsonSchema(jsonSchema, path32, root) {
361305
362081
  const ref = jsonSchema.$ref;
361306
362082
  if (ref && hasMoreThanNKeys(jsonSchema, 1)) {
361307
362083
  if (typeof ref !== "string") {
361308
- throw new TypeError(`Received non-string $ref - ${ref}; path=${path32.join("/")}`);
362084
+ throw new TypeError(`Received non-string $ref - ${ref}; path=${path33.join("/")}`);
361309
362085
  }
361310
362086
  const resolved = resolveRef(root, ref);
361311
362087
  if (typeof resolved === "boolean") {
@@ -361316,7 +362092,7 @@ function ensureStrictJsonSchema(jsonSchema, path32, root) {
361316
362092
  }
361317
362093
  Object.assign(jsonSchema, { ...resolved, ...jsonSchema });
361318
362094
  delete jsonSchema.$ref;
361319
- return ensureStrictJsonSchema(jsonSchema, path32, root);
362095
+ return ensureStrictJsonSchema(jsonSchema, path33, root);
361320
362096
  }
361321
362097
  return jsonSchema;
361322
362098
  }
@@ -365722,7 +366498,7 @@ var import_node_fs4 = __toESM(require("node:fs"), 1);
365722
366498
  var import_promises6 = __toESM(require("node:fs/promises"), 1);
365723
366499
  var import_node_os2 = __toESM(require("node:os"), 1);
365724
366500
  var import_node_path6 = __toESM(require("node:path"), 1);
365725
- var import_node_crypto17 = __toESM(require("node:crypto"), 1);
366501
+ var import_node_crypto18 = __toESM(require("node:crypto"), 1);
365726
366502
  var DEFAULT_MAX_FILES = 50;
365727
366503
  var PassChatTempExportService = class {
365728
366504
  baseDir;
@@ -365849,7 +366625,7 @@ ${input.markdown}`
365849
366625
  return import_node_path6.default.join(this.baseDir, `pass-chat_${sessionHash}_${hash2}.md`);
365850
366626
  }
365851
366627
  hashText(input) {
365852
- return import_node_crypto17.default.createHash("sha256").update(input).digest("hex");
366628
+ return import_node_crypto18.default.createHash("sha256").update(input).digest("hex");
365853
366629
  }
365854
366630
  async ensurePrivateBaseDir() {
365855
366631
  await import_promises6.default.mkdir(this.baseDir, { recursive: true, mode: 448 });
@@ -366218,6 +366994,7 @@ var AgentService_v2 = class {
366218
366994
  /** Optional run ledger — persisted audit + token-cost record of every
366219
366995
  * agent run (start/finish lifecycle + per-call token usage). */
366220
366996
  agentRunLedger;
366997
+ compoundingStore;
366221
366998
  changeLedger;
366222
366999
  mcpToolService;
366223
367000
  skillService;
@@ -366352,6 +367129,9 @@ var AgentService_v2 = class {
366352
367129
  setAgentRunLedger(ledger) {
366353
367130
  this.agentRunLedger = ledger ?? void 0;
366354
367131
  }
367132
+ setCompoundingStore(store) {
367133
+ this.compoundingStore = store ?? void 0;
367134
+ }
366355
367135
  setFeedbackWaiter(waiter) {
366356
367136
  this.waitForFeedback = waiter;
366357
367137
  }
@@ -366767,7 +367547,21 @@ var AgentService_v2 = class {
366767
367547
  );
366768
367548
  }
366769
367549
  }
366770
- const baseSystemText = createBaseSystemPromptText(memoryPrompt);
367550
+ let baseSystemText = createBaseSystemPromptText(memoryPrompt);
367551
+ if (this.compoundingStore) {
367552
+ const block = this.compoundingStore.promptBlock(3500);
367553
+ const goals = this.compoundingStore.listGoals(sessionId).filter((g) => g.status === "open" || g.status === "blocked");
367554
+ const extra = [];
367555
+ if (block) extra.push(block);
367556
+ if (goals.length) {
367557
+ extra.push(
367558
+ "# Open goals this session\n" + goals.map((g) => `- [${g.status}] ${g.text}${g.blockedBy ? ` (${g.blockedBy})` : ""}`).join("\n")
367559
+ );
367560
+ }
367561
+ if (extra.length) baseSystemText = `${baseSystemText}
367562
+
367563
+ ${extra.join("\n\n")}`;
367564
+ }
366771
367565
  const newMessages = upsertSingleSystemMessageByText(
366772
367566
  [...messages, humanMessage],
366773
367567
  baseSystemText
@@ -367701,6 +368495,33 @@ Actually, your intention might be different. Please re-read the description of t
367701
368495
  }
367702
368496
  break;
367703
368497
  }
368498
+ case "ops_experiment": {
368499
+ try {
368500
+ const validatedArgs = opsExperimentSchema.parse(toolCall.args || {});
368501
+ result = await toolImplementations.opsExperiment(validatedArgs, executionContext);
368502
+ } catch (err) {
368503
+ result = `Parameter validation error for ops_experiment: ${err.message}`;
368504
+ }
368505
+ break;
368506
+ }
368507
+ case "manage_goal": {
368508
+ try {
368509
+ const validatedArgs = manageGoalSchema.parse(toolCall.args || {});
368510
+ result = await toolImplementations.manageGoal(validatedArgs, executionContext);
368511
+ } catch (err) {
368512
+ result = `Parameter validation error for manage_goal: ${err.message}`;
368513
+ }
368514
+ break;
368515
+ }
368516
+ case "estate_facts": {
368517
+ try {
368518
+ const validatedArgs = estateFactsSchema.parse(toolCall.args || {});
368519
+ result = await toolImplementations.estateFacts(validatedArgs, executionContext);
368520
+ } catch (err) {
368521
+ result = `Parameter validation error for estate_facts: ${err.message}`;
368522
+ }
368523
+ break;
368524
+ }
367704
368525
  case "get_metrics": {
367705
368526
  try {
367706
368527
  const validatedArgs = getMetricsSchema.parse(toolCall.args || {});
@@ -368307,6 +369128,12 @@ Actually, your intention might be different. Please re-read the description of t
368307
369128
  return ti.getCost(args, executionContext);
368308
369129
  case "get_run_ledger":
368309
369130
  return ti.getRunLedger(args, executionContext);
369131
+ case "ops_experiment":
369132
+ return ti.opsExperiment(args, executionContext);
369133
+ case "manage_goal":
369134
+ return ti.manageGoal(args, executionContext);
369135
+ case "estate_facts":
369136
+ return ti.estateFacts(args, executionContext);
368310
369137
  case "list_gateway_methods":
368311
369138
  return ti.listGatewayMethods(args, executionContext);
368312
369139
  case "collect_facts":
@@ -368764,6 +369591,7 @@ ${reminder}`;
368764
369591
  automationManager: this.automationManager,
368765
369592
  sessionLogger: this.sessionLogger,
368766
369593
  agentRunLedger: this.agentRunLedger,
369594
+ compoundingStore: this.compoundingStore,
368767
369595
  changeLedger: this.changeLedger,
368768
369596
  triggerEngine: this.triggerEngine,
368769
369597
  observability: this.observability,
@@ -369724,9 +370552,50 @@ ${reminder}`;
369724
370552
  }
369725
370553
  this.currentRunIdBySession.delete(sessionId);
369726
370554
  this.agentRunLedger?.finishRun(ledgerRunId, ledgerExitStatus, ledgerExitError);
370555
+ void this.recordCompoundingLessons(sessionId, ledgerRunId, ledgerExitStatus, ledgerExitError);
369727
370556
  await this.clearCheckpoint(sessionId);
369728
370557
  }
369729
370558
  }
370559
+ /**
370560
+ * After every run, extract durable lessons from the error + input preview
370561
+ * and append them to memory.md (deduped by fingerprint). Best-effort: a
370562
+ * failure here must never throw out of the agent finally block.
370563
+ */
370564
+ async recordCompoundingLessons(_sessionId, ledgerRunId, status, error40) {
370565
+ try {
370566
+ if (!this.compoundingStore) return;
370567
+ const { extractLessons: extractLessons2, isTrivialRun: isTrivialRun2, appendLessonsToMemory: appendLessonsToMemory2, formatLessonMarkdown: formatLessonMarkdown2 } = await Promise.resolve().then(() => (init_compoundingKnowledge(), compoundingKnowledge_exports));
370568
+ const run = ledgerRunId ? this.agentRunLedger?.getRun(ledgerRunId) : null;
370569
+ const inputPreview = run?.run.inputPreview;
370570
+ if (isTrivialRun2(inputPreview, error40)) return;
370571
+ const lessons = extractLessons2(error40, inputPreview, status === "failed" ? status : "");
370572
+ if (!lessons.length) return;
370573
+ const rows = this.compoundingStore.recordLessons(lessons, ledgerRunId);
370574
+ const snapshot = await this.memoryService.getMemorySnapshot(this.getActiveMemoryProfileId());
370575
+ const { next, added } = appendLessonsToMemory2(snapshot.content, lessons, {
370576
+ runId: ledgerRunId,
370577
+ at: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)
370578
+ });
370579
+ if (added.length && this.memoryService.appendMemory) {
370580
+ const chunk2 = added.map((fp) => {
370581
+ const lesson2 = lessons.find((l) => l.fingerprint === fp);
370582
+ const row = rows.find((r) => r.fingerprint === fp);
370583
+ return lesson2 ? formatLessonMarkdown2(lesson2, {
370584
+ runId: ledgerRunId,
370585
+ at: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
370586
+ occurrence: row?.occurrences
370587
+ }) : "";
370588
+ }).join("");
370589
+ if (chunk2) {
370590
+ await this.memoryService.appendMemory(chunk2, this.getActiveMemoryProfileId());
370591
+ }
370592
+ } else if (added.length) {
370593
+ await this.memoryService.writeMemory(next, this.getActiveMemoryProfileId());
370594
+ }
370595
+ } catch (err) {
370596
+ console.warn("[AgentService_v2] compounding lesson write failed:", err);
370597
+ }
370598
+ }
369730
370599
  async clearCheckpoint(sessionId) {
369731
370600
  try {
369732
370601
  await this.checkpointer.deleteThread(sessionId);
@@ -381848,6 +382717,14 @@ var FileMemoryStore = class {
381848
382717
  content
381849
382718
  };
381850
382719
  }
382720
+ /** Append text to memory.md (used by auto-lesson writer). */
382721
+ async appendMemory(chunk2) {
382722
+ const filePath = await this.ensureMemoryFile();
382723
+ const current = await import_promises10.default.readFile(filePath, "utf8");
382724
+ const next = current.endsWith("\n") || current === "" ? current + chunk2 : current + "\n" + chunk2;
382725
+ await import_promises10.default.writeFile(filePath, next, "utf8");
382726
+ return { filePath, content: next };
382727
+ }
381851
382728
  async getMemorySnapshot() {
381852
382729
  const filePath = await this.ensureMemoryFile();
381853
382730
  const content = await import_promises10.default.readFile(filePath, "utf8");
@@ -381895,6 +382772,9 @@ var NodeMemoryService = class {
381895
382772
  async writeMemory(content, profileId) {
381896
382773
  return await this.createStore(profileId).writeMemory(content);
381897
382774
  }
382775
+ async appendMemory(chunk2, profileId) {
382776
+ return await this.createStore(profileId).appendMemory(chunk2);
382777
+ }
381898
382778
  async copyMemory(sourceProfileId, targetProfileId) {
381899
382779
  const content = await this.readMemory(sourceProfileId);
381900
382780
  return await this.writeMemory(content, targetProfileId);
@@ -381908,8 +382788,8 @@ var import_node_path20 = __toESM(require("node:path"), 1);
381908
382788
  var import_promises11 = __toESM(require("node:fs/promises"), 1);
381909
382789
  var import_node_path19 = __toESM(require("node:path"), 1);
381910
382790
  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);
382791
+ var import_node_crypto19 = require("node:crypto");
382792
+ var scrypt = (0, import_node_util.promisify)(import_node_crypto19.scrypt);
381913
382793
  var FILE_SCHEMA_VERSION = 1;
381914
382794
  var HASH_KEY_LENGTH = 32;
381915
382795
  var TOKEN_NAME_MAX_LENGTH = 64;
@@ -381923,10 +382803,10 @@ function makeDefaultPayload() {
381923
382803
  };
381924
382804
  }
381925
382805
  function randomTokenId() {
381926
- return `atk_${(0, import_node_crypto18.randomBytes)(12).toString("base64url")}`;
382806
+ return `atk_${(0, import_node_crypto19.randomBytes)(12).toString("base64url")}`;
381927
382807
  }
381928
382808
  function randomAccessTokenValue() {
381929
- return `gys_at_${(0, import_node_crypto18.randomBytes)(24).toString("base64url")}`;
382809
+ return `gys_at_${(0, import_node_crypto19.randomBytes)(24).toString("base64url")}`;
381930
382810
  }
381931
382811
  async function deriveTokenHash(token, tokenSaltBase64) {
381932
382812
  const tokenSalt = Buffer.from(tokenSaltBase64, "base64");
@@ -381988,7 +382868,7 @@ var FileAccessTokenStore = class {
381988
382868
  throw new Error(`Token name already exists: ${normalizedName}`);
381989
382869
  }
381990
382870
  const token = randomAccessTokenValue();
381991
- const tokenSalt = (0, import_node_crypto18.randomBytes)(16).toString("base64");
382871
+ const tokenSalt = (0, import_node_crypto19.randomBytes)(16).toString("base64");
381992
382872
  const tokenHash = (await deriveTokenHash(token, tokenSalt)).toString("base64");
381993
382873
  const createdAt = Date.now();
381994
382874
  const record2 = {
@@ -382035,7 +382915,7 @@ var FileAccessTokenStore = class {
382035
382915
  try {
382036
382916
  const expected = Buffer.from(record2.tokenHash, "base64");
382037
382917
  const actual = await deriveTokenHash(token, record2.tokenSalt);
382038
- if (expected.length === actual.length && (0, import_node_crypto18.timingSafeEqual)(expected, actual)) {
382918
+ if (expected.length === actual.length && (0, import_node_crypto19.timingSafeEqual)(expected, actual)) {
382039
382919
  return true;
382040
382920
  }
382041
382921
  } catch {
@@ -382537,7 +383417,7 @@ function buildBuiltInToolStatusSummary(enabledMap) {
382537
383417
  // ../../packages/backend/src/services/ImageAttachmentService.ts
382538
383418
  var import_promises12 = __toESM(require("node:fs/promises"), 1);
382539
383419
  var import_node_path21 = __toESM(require("node:path"), 1);
382540
- var import_node_crypto19 = __toESM(require("node:crypto"), 1);
383420
+ var import_node_crypto20 = __toESM(require("node:crypto"), 1);
382541
383421
  var DEFAULT_INDEX = {
382542
383422
  records: {}
382543
383423
  };
@@ -382561,7 +383441,7 @@ var ImageAttachmentService = class {
382561
383441
  const normalizedMimeType = this.resolveMimeType(payload.mimeType, image.mimeType);
382562
383442
  const extension = this.resolveImageExtension(payload.fileName, normalizedMimeType);
382563
383443
  const safeName = this.safeFileName(payload.fileName);
382564
- const sha2562 = import_node_crypto19.default.createHash("sha256").update(bytes).digest("hex");
383444
+ const sha2562 = import_node_crypto20.default.createHash("sha256").update(bytes).digest("hex");
382565
383445
  const attachmentId = `img_${sha2562.slice(0, 24)}`;
382566
383446
  const filePath = import_node_path21.default.join(this.attachmentsDir, `${attachmentId}${extension}`);
382567
383447
  const existing = this.records[attachmentId];
@@ -384072,8 +384952,8 @@ var IdleTimeoutService = class {
384072
384952
  };
384073
384953
 
384074
384954
  // ../../packages/backend/src/services/Gateway/restApi.ts
384075
- function matchRestRoute(routes, method, path32) {
384076
- const normalized = path32.replace(/\/+$/, "") || "/";
384955
+ function matchRestRoute(routes, method, path33) {
384956
+ const normalized = path33.replace(/\/+$/, "") || "/";
384077
384957
  for (const route of routes) {
384078
384958
  if (route.method !== method.toUpperCase()) continue;
384079
384959
  const patternParts = route.path.split("/").filter(Boolean);
@@ -392117,11 +392997,11 @@ function createObservability(deps) {
392117
392997
  const policyEngine = new AgtPolicyEngine({
392118
392998
  loadPolicy: async () => {
392119
392999
  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"));
393000
+ const fs24 = req("node:fs");
393001
+ const path33 = req("node:path");
393002
+ const policyPath = path33.join(".", "policy.yaml");
393003
+ if (fs24.existsSync(policyPath)) {
393004
+ return parsePolicyYaml(fs24.readFileSync(policyPath, "utf8"));
392125
393005
  }
392126
393006
  return {
392127
393007
  name: "rterm-default",
@@ -392163,18 +393043,18 @@ function createObservability(deps) {
392163
393043
  const scanRoots = [pluginScanRoot, "./plugins"];
392164
393044
  try {
392165
393045
  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);
393046
+ const fs24 = req("node:fs");
393047
+ if (fs24.existsSync(bundlePluginRoot)) scanRoots.push(bundlePluginRoot);
392168
393048
  } catch {
392169
393049
  }
392170
393050
  try {
392171
393051
  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");
393052
+ const fs24 = req("node:fs");
393053
+ const path33 = req("node:path");
392174
393054
  const resourcesPath = process.resourcesPath;
392175
393055
  if (resourcesPath) {
392176
- const resourcesPlugins = path32.join(resourcesPath, "plugins");
392177
- if (fs23.existsSync(resourcesPlugins)) scanRoots.push(resourcesPlugins);
393056
+ const resourcesPlugins = path33.join(resourcesPath, "plugins");
393057
+ if (fs24.existsSync(resourcesPlugins)) scanRoots.push(resourcesPlugins);
392178
393058
  }
392179
393059
  } catch {
392180
393060
  }
@@ -394861,9 +395741,9 @@ function numberFromEnv(name, fallback) {
394861
395741
  function resolveDataDir() {
394862
395742
  const custom3 = (import_node_process2.default.env.GYBACKEND_DATA_DIR || "").trim();
394863
395743
  if (custom3) {
394864
- return import_node_path28.default.resolve(custom3);
395744
+ return import_node_path29.default.resolve(custom3);
394865
395745
  }
394866
- return import_node_path28.default.join(import_node_process2.default.cwd(), ".gybackend-data");
395746
+ return import_node_path29.default.join(import_node_process2.default.cwd(), ".gybackend-data");
394867
395747
  }
394868
395748
  async function startGyBackend() {
394869
395749
  const dataDir = resolveDataDir();
@@ -394896,7 +395776,7 @@ async function startGyBackend() {
394896
395776
  const modelCapabilityService = new ModelCapabilityService();
394897
395777
  const imageAttachmentService = new ImageAttachmentService(dataDir);
394898
395778
  const terminalStateStore = new TerminalStateStore(
394899
- import_node_path28.default.join(dataDir, "terminal-tabs-state.json")
395779
+ import_node_path29.default.join(dataDir, "terminal-tabs-state.json")
394900
395780
  );
394901
395781
  const terminalService = new TerminalService({
394902
395782
  terminalStateStore
@@ -394984,6 +395864,31 @@ async function startGyBackend() {
394984
395864
  const agentRunLedger = new AgentRunLedger();
394985
395865
  agentRunLedger.markStaleRunsAborted(Date.now());
394986
395866
  agentService.setAgentRunLedger(agentRunLedger);
395867
+ const { CompoundingStore: CompoundingStore2 } = await Promise.resolve().then(() => (init_compoundingStore(), compoundingStore_exports));
395868
+ const compoundingStore = new CompoundingStore2();
395869
+ agentService.setCompoundingStore(compoundingStore);
395870
+ try {
395871
+ const { connectionIdentity: connectionIdentity2 } = await Promise.resolve().then(() => (init_compoundingKnowledge(), compoundingKnowledge_exports));
395872
+ const winrm = settingsService.getSettings()?.connections?.winrm ?? [];
395873
+ for (const c of winrm) {
395874
+ compoundingStore.upsertEstateFact({
395875
+ identity: connectionIdentity2({
395876
+ name: c.name,
395877
+ host: c.host,
395878
+ transport: c.transport,
395879
+ auth: c.auth,
395880
+ domain: c.domain
395881
+ }),
395882
+ host: c.host,
395883
+ role: /dc/i.test(c.name || "") ? "dc" : void 0,
395884
+ domain: c.domain,
395885
+ transport: c.transport,
395886
+ auth: c.auth
395887
+ });
395888
+ }
395889
+ } catch (e) {
395890
+ console.warn(`[gybackend] compounding estate seed skipped: ${e instanceof Error ? e.message : String(e)}`);
395891
+ }
394987
395892
  const changeLedger = new ChangeLedger();
394988
395893
  changeLedger.markStaleChangesAborted(Date.now());
394989
395894
  agentService.setChangeLedger(changeLedger);
@@ -395087,7 +395992,7 @@ async function startGyBackend() {
395087
395992
  console.warn("[gybackend] Plugin tool wiring skipped:", e instanceof Error ? e.message : String(e));
395088
395993
  });
395089
395994
  if (settingsService.getSettings().sessionLogging?.enabled) {
395090
- const logDir = import_node_path28.default.join(
395995
+ const logDir = import_node_path29.default.join(
395091
395996
  import_node_process2.default.env.GYSHELL_STORE_DIR || "",
395092
395997
  "session-logs"
395093
395998
  );
@@ -395205,21 +396110,21 @@ async function startGyBackend() {
395205
396110
  authFailureLimit: 5,
395206
396111
  authLockoutMs: 6e4
395207
396112
  });
395208
- const settingsDir = import_node_path28.default.dirname(settingsService.getSettingsPath?.() ?? "");
395209
- const backupsDir = settingsDir ? import_node_path28.default.join(settingsDir, "backups") : "";
396113
+ const settingsDir = import_node_path29.default.dirname(settingsService.getSettingsPath?.() ?? "");
396114
+ const backupsDir = settingsDir ? import_node_path29.default.join(settingsDir, "backups") : "";
395210
396115
  const settingsBackupService = new SettingsBackupService(
395211
396116
  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"),
396117
+ read: () => import_node_fs13.default.readFileSync(settingsService.getSettingsPath(), "utf8"),
396118
+ write: (c) => import_node_fs13.default.writeFileSync(settingsService.getSettingsPath(), c),
396119
+ listBackups: () => import_node_fs13.default.existsSync(backupsDir) ? import_node_fs13.default.readdirSync(backupsDir) : [],
396120
+ readBackup: (n2) => import_node_fs13.default.readFileSync(import_node_path29.default.join(backupsDir, n2), "utf8"),
395216
396121
  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);
396122
+ import_node_fs13.default.mkdirSync(backupsDir, { recursive: true });
396123
+ import_node_fs13.default.writeFileSync(import_node_path29.default.join(backupsDir, n2), c);
395219
396124
  },
395220
396125
  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);
396126
+ const p = import_node_path29.default.join(backupsDir, n2);
396127
+ if (import_node_fs13.default.existsSync(p)) import_node_fs13.default.unlinkSync(p);
395223
396128
  }
395224
396129
  } : { read: () => "", write: () => {
395225
396130
  }, listBackups: () => [], readBackup: () => "", writeBackup: () => {