@vibedeckx/darwin-arm64 0.3.43 → 0.3.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bin.js +1612 -343
  2. package/package.json +1 -1
package/dist/bin.js CHANGED
@@ -13356,12 +13356,12 @@ var require_semver = __commonJS({
13356
13356
  }
13357
13357
  function replaceHyphen(comp, options) {
13358
13358
  const r = HYPHENRANGE_REGEXP;
13359
- return comp.replace(r, (_3, from, fM, fm, fp37, fpr, fb, to, tM, tm, tp, tpr) => {
13359
+ return comp.replace(r, (_3, from, fM, fm, fp38, fpr, fb, to, tM, tm, tp, tpr) => {
13360
13360
  if (isX(fM)) {
13361
13361
  from = "";
13362
13362
  } else if (isX(fm)) {
13363
13363
  from = `>=${fM}.0.0${options?.includePrerelease ? "-0" : ""}`;
13364
- } else if (isX(fp37)) {
13364
+ } else if (isX(fp38)) {
13365
13365
  from = `>=${fM}.${fm}.0${options?.includePrerelease ? "-0" : ""}`;
13366
13366
  } else if (fpr) {
13367
13367
  from = `>=${from}`;
@@ -87525,12 +87525,12 @@ var require_range = __commonJS({
87525
87525
  debug("replaceGTE0", comp, options);
87526
87526
  return comp.trim().replace(re2[options.includePrerelease ? t.GTE0PRE : t.GTE0], "");
87527
87527
  };
87528
- var hyphenReplace = (incPr) => ($0, from, fM, fm, fp37, fpr, fb, to, tM, tm, tp, tpr) => {
87528
+ var hyphenReplace = (incPr) => ($0, from, fM, fm, fp38, fpr, fb, to, tM, tm, tp, tpr) => {
87529
87529
  if (isX(fM)) {
87530
87530
  from = "";
87531
87531
  } else if (isX(fm)) {
87532
87532
  from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
87533
- } else if (isX(fp37)) {
87533
+ } else if (isX(fp38)) {
87534
87534
  from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
87535
87535
  } else if (fpr) {
87536
87536
  from = `>=${from}`;
@@ -90111,8 +90111,8 @@ var require_pretty_print = __commonJS({
90111
90111
  serializedRoute += serializeMetaData(route.metaData);
90112
90112
  return serializedRoute;
90113
90113
  }
90114
- function mergeSimilarRoutes(routes36) {
90115
- return routes36.reduce((mergedRoutes, route) => {
90114
+ function mergeSimilarRoutes(routes37) {
90115
+ return routes37.reduce((mergedRoutes, route) => {
90116
90116
  for (const nodeRoute of mergedRoutes) {
90117
90117
  if (deepEqual(route.opts.constraints, nodeRoute.opts.constraints) && deepEqual(route.metaData, nodeRoute.metaData)) {
90118
90118
  nodeRoute.method += ", " + route.method;
@@ -90124,18 +90124,18 @@ var require_pretty_print = __commonJS({
90124
90124
  }, []);
90125
90125
  }
90126
90126
  function serializeNode(node, prefix, options) {
90127
- let routes36 = node.routes;
90127
+ let routes37 = node.routes;
90128
90128
  if (options.method === void 0) {
90129
- routes36 = routes36.map(normalizeRoute);
90129
+ routes37 = routes37.map(normalizeRoute);
90130
90130
  }
90131
- routes36 = routes36.map((route) => {
90131
+ routes37 = routes37.map((route) => {
90132
90132
  route.metaData = getRouteMetaData(route, options);
90133
90133
  return route;
90134
90134
  });
90135
90135
  if (options.method === void 0) {
90136
- routes36 = mergeSimilarRoutes(routes36);
90136
+ routes37 = mergeSimilarRoutes(routes37);
90137
90137
  }
90138
- return routes36.map(serializeRoute).join(`
90138
+ return routes37.map(serializeRoute).join(`
90139
90139
  ${prefix}`);
90140
90140
  }
90141
90141
  function buildObjectTree(node, tree, prefix, options) {
@@ -91402,9 +91402,9 @@ var require_find_my_way = __commonJS({
91402
91402
  pathIndex = paramEndIndex;
91403
91403
  }
91404
91404
  };
91405
- Router.prototype._rebuild = function(routes36) {
91405
+ Router.prototype._rebuild = function(routes37) {
91406
91406
  this.reset();
91407
- for (const route of routes36) {
91407
+ for (const route of routes37) {
91408
91408
  const { method, path: path26, opts, handler, store } = route;
91409
91409
  this._on(method, path26, opts, handler, store);
91410
91410
  }
@@ -93806,7 +93806,7 @@ var require_form_data = __commonJS({
93806
93806
  "../../node_modules/.pnpm/light-my-request@6.6.0/node_modules/light-my-request/lib/form-data.js"(exports, module) {
93807
93807
  "use strict";
93808
93808
  var { randomUUID: randomUUID31 } = __require("node:crypto");
93809
- var { Readable: Readable4 } = __require("node:stream");
93809
+ var { Readable: Readable5 } = __require("node:stream");
93810
93810
  var textEncoder;
93811
93811
  function isFormDataLike(payload) {
93812
93812
  return payload && typeof payload === "object" && typeof payload.append === "function" && typeof payload.delete === "function" && typeof payload.get === "function" && typeof payload.getAll === "function" && typeof payload.has === "function" && typeof payload.set === "function" && payload[Symbol.toStringTag] === "FormData";
@@ -93845,7 +93845,7 @@ Content-Type: ${value.type || "application/octet-stream"}\r
93845
93845
  }
93846
93846
  yield textEncoder.encode(`--${boundary}--`);
93847
93847
  }
93848
- const stream = Readable4.from(asyncIterator());
93848
+ const stream = Readable5.from(asyncIterator());
93849
93849
  return {
93850
93850
  stream,
93851
93851
  contentType: `multipart/form-data; boundary=${boundary}`
@@ -93860,7 +93860,7 @@ Content-Type: ${value.type || "application/octet-stream"}\r
93860
93860
  var require_request2 = __commonJS({
93861
93861
  "../../node_modules/.pnpm/light-my-request@6.6.0/node_modules/light-my-request/lib/request.js"(exports, module) {
93862
93862
  "use strict";
93863
- var { Readable: Readable4, addAbortSignal } = __require("node:stream");
93863
+ var { Readable: Readable5, addAbortSignal } = __require("node:stream");
93864
93864
  var util2 = __require("node:util");
93865
93865
  var cookie = require_dist5();
93866
93866
  var assert2 = __require("node:assert");
@@ -93898,7 +93898,7 @@ var require_request2 = __commonJS({
93898
93898
  }
93899
93899
  }
93900
93900
  function Request2(options) {
93901
- Readable4.call(this, {
93901
+ Readable5.call(this, {
93902
93902
  autoDestroy: false
93903
93903
  });
93904
93904
  const parsedURL = parseURL(options.url || options.path, options.query);
@@ -94030,7 +94030,7 @@ var require_request2 = __commonJS({
94030
94030
  }
94031
94031
  });
94032
94032
  }
94033
- util2.inherits(Request2, Readable4);
94033
+ util2.inherits(Request2, Readable5);
94034
94034
  util2.inherits(CustomRequest, Request2);
94035
94035
  Request2.prototype.destroy = function(error48) {
94036
94036
  if (this.destroyed || this._lightMyRequest.isDone) return;
@@ -94235,14 +94235,14 @@ var require_response = __commonJS({
94235
94235
  "../../node_modules/.pnpm/light-my-request@6.6.0/node_modules/light-my-request/lib/response.js"(exports, module) {
94236
94236
  "use strict";
94237
94237
  var http = __require("node:http");
94238
- var { Writable: Writable2, Readable: Readable4, addAbortSignal } = __require("node:stream");
94238
+ var { Writable: Writable2, Readable: Readable5, addAbortSignal } = __require("node:stream");
94239
94239
  var util2 = __require("node:util");
94240
94240
  var setCookie = require_set_cookie();
94241
94241
  function Response2(req, onEnd, reject) {
94242
94242
  http.ServerResponse.call(this, req);
94243
94243
  if (req._lightMyRequest?.payloadAsStream) {
94244
94244
  const read = this.emit.bind(this, "drain");
94245
- this._lightMyRequest = { headers: null, trailers: {}, stream: new Readable4({ read }) };
94245
+ this._lightMyRequest = { headers: null, trailers: {}, stream: new Readable5({ read }) };
94246
94246
  const signal = req._lightMyRequest.signal;
94247
94247
  if (signal) {
94248
94248
  addAbortSignal(signal, this._lightMyRequest.stream);
@@ -94388,7 +94388,7 @@ var require_response = __commonJS({
94388
94388
  if (response._lightMyRequest.stream) {
94389
94389
  return response._lightMyRequest.stream;
94390
94390
  }
94391
- return Readable4.from(response._lightMyRequest.payloadChunks);
94391
+ return Readable5.from(response._lightMyRequest.payloadChunks);
94392
94392
  };
94393
94393
  return res;
94394
94394
  }
@@ -100612,8 +100612,8 @@ var require_commonjs6 = __commonJS({
100612
100612
  return this.#fullpath = this.name;
100613
100613
  }
100614
100614
  const pv = p2.fullpath();
100615
- const fp37 = pv + (!p2.parent ? "" : this.sep) + name25;
100616
- return this.#fullpath = fp37;
100615
+ const fp38 = pv + (!p2.parent ? "" : this.sep) + name25;
100616
+ return this.#fullpath = fp38;
100617
100617
  }
100618
100618
  /**
100619
100619
  * On platforms other than windows, this is identical to fullpath.
@@ -104310,7 +104310,7 @@ var require_send = __commonJS({
104310
104310
  var normalize = path26.normalize;
104311
104311
  var resolve3 = path26.resolve;
104312
104312
  var sep2 = path26.sep;
104313
- var Readable4 = stream.Readable;
104313
+ var Readable5 = stream.Readable;
104314
104314
  var BYTES_RANGE_REGEXP = /^ *bytes=/;
104315
104315
  var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1e3;
104316
104316
  var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
@@ -104517,7 +104517,7 @@ var require_send = __commonJS({
104517
104517
  return {
104518
104518
  statusCode,
104519
104519
  headers,
104520
- stream: Readable4.from(doc[0]),
104520
+ stream: Readable5.from(doc[0]),
104521
104521
  // metadata
104522
104522
  type: "error",
104523
104523
  metadata: { error: createHttpError(statusCode, err) }
@@ -104543,7 +104543,7 @@ var require_send = __commonJS({
104543
104543
  return {
104544
104544
  statusCode: 304,
104545
104545
  headers,
104546
- stream: Readable4.from(""),
104546
+ stream: Readable5.from(""),
104547
104547
  // metadata
104548
104548
  type: "file",
104549
104549
  metadata: { path: path27, stat: stat3 }
@@ -104631,7 +104631,7 @@ var require_send = __commonJS({
104631
104631
  return {
104632
104632
  statusCode,
104633
104633
  headers,
104634
- stream: Readable4.from(""),
104634
+ stream: Readable5.from(""),
104635
104635
  // metadata
104636
104636
  type: "file",
104637
104637
  metadata: { path: path27, stat: stat3 }
@@ -104666,7 +104666,7 @@ var require_send = __commonJS({
104666
104666
  return {
104667
104667
  statusCode: 301,
104668
104668
  headers,
104669
- stream: Readable4.from(doc[0]),
104669
+ stream: Readable5.from(doc[0]),
104670
104670
  // metadata
104671
104671
  type: "directory",
104672
104672
  metadata: { requestPath: options.path, path: path27 }
@@ -105329,7 +105329,7 @@ var require_static = __commonJS({
105329
105329
  var { fileURLToPath: fileURLToPath4 } = __require("node:url");
105330
105330
  var { statSync: statSync3 } = __require("node:fs");
105331
105331
  var { glob } = require_commonjs7();
105332
- var fp37 = require_plugin2();
105332
+ var fp38 = require_plugin2();
105333
105333
  var send = require_send2();
105334
105334
  var encodingNegotiator = require_accept_negotiator();
105335
105335
  var contentDisposition = require_content_disposition();
@@ -105433,7 +105433,7 @@ var require_static = __commonJS({
105433
105433
  } else {
105434
105434
  const indexes = new Set(opts.index === void 0 ? ["index.html"] : [].concat(opts.index));
105435
105435
  const indexDirs = /* @__PURE__ */ new Map();
105436
- const routes36 = /* @__PURE__ */ new Set();
105436
+ const routes37 = /* @__PURE__ */ new Set();
105437
105437
  const roots = Array.isArray(sendOptions.root) ? sendOptions.root : [sendOptions.root];
105438
105438
  for (let rootPath of roots) {
105439
105439
  rootPath = rootPath.split(path26.win32.sep).join(path26.posix.sep);
@@ -105449,10 +105449,10 @@ var require_static = __commonJS({
105449
105449
  for (let file2 of files) {
105450
105450
  file2 = file2.split(path26.win32.sep).join(path26.posix.sep);
105451
105451
  const route = prefix + file2;
105452
- if (routes36.has(route)) {
105452
+ if (routes37.has(route)) {
105453
105453
  continue;
105454
105454
  }
105455
- routes36.add(route);
105455
+ routes37.add(route);
105456
105456
  setUpHeadAndGet(routeOpts, route, `/${file2}`, rootPath);
105457
105457
  const key2 = path26.posix.basename(route);
105458
105458
  if (indexes.has(key2) && !indexDirs.has(key2)) {
@@ -105747,7 +105747,7 @@ var require_static = __commonJS({
105747
105747
  throw err;
105748
105748
  }
105749
105749
  }
105750
- module.exports = fp37(fastifyStatic2, {
105750
+ module.exports = fp38(fastifyStatic2, {
105751
105751
  fastify: "5.x",
105752
105752
  name: "@fastify/static"
105753
105753
  });
@@ -107959,8 +107959,8 @@ var require_websocket = __commonJS({
107959
107959
  var http = __require("http");
107960
107960
  var net2 = __require("net");
107961
107961
  var tls = __require("tls");
107962
- var { randomBytes: randomBytes5, createHash: createHash11 } = __require("crypto");
107963
- var { Duplex, Readable: Readable4 } = __require("stream");
107962
+ var { randomBytes: randomBytes5, createHash: createHash12 } = __require("crypto");
107963
+ var { Duplex, Readable: Readable5 } = __require("stream");
107964
107964
  var { URL: URL2 } = __require("url");
107965
107965
  var PerMessageDeflate = require_permessage_deflate();
107966
107966
  var Receiver2 = require_receiver();
@@ -108619,7 +108619,7 @@ var require_websocket = __commonJS({
108619
108619
  abortHandshake(websocket, socket, "Invalid Upgrade header");
108620
108620
  return;
108621
108621
  }
108622
- const digest = createHash11("sha1").update(key2 + GUID).digest("base64");
108622
+ const digest = createHash12("sha1").update(key2 + GUID).digest("base64");
108623
108623
  if (res.headers["sec-websocket-accept"] !== digest) {
108624
108624
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
108625
108625
  return;
@@ -108986,7 +108986,7 @@ var require_websocket_server = __commonJS({
108986
108986
  var EventEmitter3 = __require("events");
108987
108987
  var http = __require("http");
108988
108988
  var { Duplex } = __require("stream");
108989
- var { createHash: createHash11 } = __require("crypto");
108989
+ var { createHash: createHash12 } = __require("crypto");
108990
108990
  var extension = require_extension();
108991
108991
  var PerMessageDeflate = require_permessage_deflate();
108992
108992
  var subprotocol = require_subprotocol();
@@ -109287,7 +109287,7 @@ var require_websocket_server = __commonJS({
109287
109287
  );
109288
109288
  }
109289
109289
  if (this._state > RUNNING) return abortHandshake(socket, 503);
109290
- const digest = createHash11("sha1").update(key2 + GUID).digest("base64");
109290
+ const digest = createHash12("sha1").update(key2 + GUID).digest("base64");
109291
109291
  const headers = [
109292
109292
  "HTTP/1.1 101 Switching Protocols",
109293
109293
  "Upgrade: websocket",
@@ -110338,9 +110338,9 @@ var require_stream_duplex = __commonJS({
110338
110338
  return keys2;
110339
110339
  };
110340
110340
  module.exports = Duplex;
110341
- var Readable4 = require_stream_readable();
110341
+ var Readable5 = require_stream_readable();
110342
110342
  var Writable2 = require_stream_writable();
110343
- require_inherits()(Duplex, Readable4);
110343
+ require_inherits()(Duplex, Readable5);
110344
110344
  {
110345
110345
  keys = objectKeys(Writable2.prototype);
110346
110346
  for (v2 = 0; v2 < keys.length; v2++) {
@@ -110353,7 +110353,7 @@ var require_stream_duplex = __commonJS({
110353
110353
  var v2;
110354
110354
  function Duplex(options) {
110355
110355
  if (!(this instanceof Duplex)) return new Duplex(options);
110356
- Readable4.call(this, options);
110356
+ Readable5.call(this, options);
110357
110357
  Writable2.call(this, options);
110358
110358
  this.allowHalfOpen = true;
110359
110359
  if (options) {
@@ -111009,14 +111009,14 @@ var require_from = __commonJS({
111009
111009
  return (hint === "string" ? String : Number)(input);
111010
111010
  }
111011
111011
  var ERR_INVALID_ARG_TYPE = require_errors6().codes.ERR_INVALID_ARG_TYPE;
111012
- function from(Readable4, iterable, opts) {
111012
+ function from(Readable5, iterable, opts) {
111013
111013
  var iterator;
111014
111014
  if (iterable && typeof iterable.next === "function") {
111015
111015
  iterator = iterable;
111016
111016
  } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();
111017
111017
  else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();
111018
111018
  else throw new ERR_INVALID_ARG_TYPE("iterable", ["Iterable"], iterable);
111019
- var readable = new Readable4(_objectSpread({
111019
+ var readable = new Readable5(_objectSpread({
111020
111020
  objectMode: true
111021
111021
  }, opts));
111022
111022
  var reading = false;
@@ -111056,9 +111056,9 @@ var require_from = __commonJS({
111056
111056
  var require_stream_readable = __commonJS({
111057
111057
  "../../node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_readable.js"(exports, module) {
111058
111058
  "use strict";
111059
- module.exports = Readable4;
111059
+ module.exports = Readable5;
111060
111060
  var Duplex;
111061
- Readable4.ReadableState = ReadableState;
111061
+ Readable5.ReadableState = ReadableState;
111062
111062
  var EE = __require("events").EventEmitter;
111063
111063
  var EElistenerCount = function EElistenerCount2(emitter, type) {
111064
111064
  return emitter.listeners(type).length;
@@ -111093,7 +111093,7 @@ var require_stream_readable = __commonJS({
111093
111093
  var StringDecoder;
111094
111094
  var createReadableStreamAsyncIterator;
111095
111095
  var from;
111096
- require_inherits()(Readable4, Stream);
111096
+ require_inherits()(Readable5, Stream);
111097
111097
  var errorOrDestroy = destroyImpl.errorOrDestroy;
111098
111098
  var kProxyEvents = ["error", "close", "destroy", "pause", "resume"];
111099
111099
  function prependListener(emitter, event, fn) {
@@ -111137,9 +111137,9 @@ var require_stream_readable = __commonJS({
111137
111137
  this.encoding = options.encoding;
111138
111138
  }
111139
111139
  }
111140
- function Readable4(options) {
111140
+ function Readable5(options) {
111141
111141
  Duplex = Duplex || require_stream_duplex();
111142
- if (!(this instanceof Readable4)) return new Readable4(options);
111142
+ if (!(this instanceof Readable5)) return new Readable5(options);
111143
111143
  var isDuplex = this instanceof Duplex;
111144
111144
  this._readableState = new ReadableState(options, this, isDuplex);
111145
111145
  this.readable = true;
@@ -111149,7 +111149,7 @@ var require_stream_readable = __commonJS({
111149
111149
  }
111150
111150
  Stream.call(this);
111151
111151
  }
111152
- Object.defineProperty(Readable4.prototype, "destroyed", {
111152
+ Object.defineProperty(Readable5.prototype, "destroyed", {
111153
111153
  // making it explicit this property is not enumerable
111154
111154
  // because otherwise some prototype manipulation in
111155
111155
  // userland will fail
@@ -111167,12 +111167,12 @@ var require_stream_readable = __commonJS({
111167
111167
  this._readableState.destroyed = value;
111168
111168
  }
111169
111169
  });
111170
- Readable4.prototype.destroy = destroyImpl.destroy;
111171
- Readable4.prototype._undestroy = destroyImpl.undestroy;
111172
- Readable4.prototype._destroy = function(err, cb) {
111170
+ Readable5.prototype.destroy = destroyImpl.destroy;
111171
+ Readable5.prototype._undestroy = destroyImpl.undestroy;
111172
+ Readable5.prototype._destroy = function(err, cb) {
111173
111173
  cb(err);
111174
111174
  };
111175
- Readable4.prototype.push = function(chunk2, encoding) {
111175
+ Readable5.prototype.push = function(chunk2, encoding) {
111176
111176
  var state = this._readableState;
111177
111177
  var skipChunkCheck;
111178
111178
  if (!state.objectMode) {
@@ -111189,7 +111189,7 @@ var require_stream_readable = __commonJS({
111189
111189
  }
111190
111190
  return readableAddChunk(this, chunk2, encoding, false, skipChunkCheck);
111191
111191
  };
111192
- Readable4.prototype.unshift = function(chunk2) {
111192
+ Readable5.prototype.unshift = function(chunk2) {
111193
111193
  return readableAddChunk(this, chunk2, null, true, false);
111194
111194
  };
111195
111195
  function readableAddChunk(stream, chunk2, encoding, addToFront, skipChunkCheck) {
@@ -111250,10 +111250,10 @@ var require_stream_readable = __commonJS({
111250
111250
  }
111251
111251
  return er;
111252
111252
  }
111253
- Readable4.prototype.isPaused = function() {
111253
+ Readable5.prototype.isPaused = function() {
111254
111254
  return this._readableState.flowing === false;
111255
111255
  };
111256
- Readable4.prototype.setEncoding = function(enc) {
111256
+ Readable5.prototype.setEncoding = function(enc) {
111257
111257
  if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder;
111258
111258
  var decoder = new StringDecoder(enc);
111259
111259
  this._readableState.decoder = decoder;
@@ -111299,7 +111299,7 @@ var require_stream_readable = __commonJS({
111299
111299
  }
111300
111300
  return state.length;
111301
111301
  }
111302
- Readable4.prototype.read = function(n) {
111302
+ Readable5.prototype.read = function(n) {
111303
111303
  debug("read", n);
111304
111304
  n = parseInt(n, 10);
111305
111305
  var state = this._readableState;
@@ -111408,10 +111408,10 @@ var require_stream_readable = __commonJS({
111408
111408
  }
111409
111409
  state.readingMore = false;
111410
111410
  }
111411
- Readable4.prototype._read = function(n) {
111411
+ Readable5.prototype._read = function(n) {
111412
111412
  errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()"));
111413
111413
  };
111414
- Readable4.prototype.pipe = function(dest, pipeOpts) {
111414
+ Readable5.prototype.pipe = function(dest, pipeOpts) {
111415
111415
  var src = this;
111416
111416
  var state = this._readableState;
111417
111417
  switch (state.pipesCount) {
@@ -111514,7 +111514,7 @@ var require_stream_readable = __commonJS({
111514
111514
  }
111515
111515
  };
111516
111516
  }
111517
- Readable4.prototype.unpipe = function(dest) {
111517
+ Readable5.prototype.unpipe = function(dest) {
111518
111518
  var state = this._readableState;
111519
111519
  var unpipeInfo = {
111520
111520
  hasUnpiped: false
@@ -111548,7 +111548,7 @@ var require_stream_readable = __commonJS({
111548
111548
  dest.emit("unpipe", this, unpipeInfo);
111549
111549
  return this;
111550
111550
  };
111551
- Readable4.prototype.on = function(ev, fn) {
111551
+ Readable5.prototype.on = function(ev, fn) {
111552
111552
  var res = Stream.prototype.on.call(this, ev, fn);
111553
111553
  var state = this._readableState;
111554
111554
  if (ev === "data") {
@@ -111569,15 +111569,15 @@ var require_stream_readable = __commonJS({
111569
111569
  }
111570
111570
  return res;
111571
111571
  };
111572
- Readable4.prototype.addListener = Readable4.prototype.on;
111573
- Readable4.prototype.removeListener = function(ev, fn) {
111572
+ Readable5.prototype.addListener = Readable5.prototype.on;
111573
+ Readable5.prototype.removeListener = function(ev, fn) {
111574
111574
  var res = Stream.prototype.removeListener.call(this, ev, fn);
111575
111575
  if (ev === "readable") {
111576
111576
  process.nextTick(updateReadableListening, this);
111577
111577
  }
111578
111578
  return res;
111579
111579
  };
111580
- Readable4.prototype.removeAllListeners = function(ev) {
111580
+ Readable5.prototype.removeAllListeners = function(ev) {
111581
111581
  var res = Stream.prototype.removeAllListeners.apply(this, arguments);
111582
111582
  if (ev === "readable" || ev === void 0) {
111583
111583
  process.nextTick(updateReadableListening, this);
@@ -111597,7 +111597,7 @@ var require_stream_readable = __commonJS({
111597
111597
  debug("readable nexttick read 0");
111598
111598
  self2.read(0);
111599
111599
  }
111600
- Readable4.prototype.resume = function() {
111600
+ Readable5.prototype.resume = function() {
111601
111601
  var state = this._readableState;
111602
111602
  if (!state.flowing) {
111603
111603
  debug("resume");
@@ -111623,7 +111623,7 @@ var require_stream_readable = __commonJS({
111623
111623
  flow(stream);
111624
111624
  if (state.flowing && !state.reading) stream.read(0);
111625
111625
  }
111626
- Readable4.prototype.pause = function() {
111626
+ Readable5.prototype.pause = function() {
111627
111627
  debug("call pause flowing=%j", this._readableState.flowing);
111628
111628
  if (this._readableState.flowing !== false) {
111629
111629
  debug("pause");
@@ -111638,7 +111638,7 @@ var require_stream_readable = __commonJS({
111638
111638
  debug("flow", state.flowing);
111639
111639
  while (state.flowing && stream.read() !== null) ;
111640
111640
  }
111641
- Readable4.prototype.wrap = function(stream) {
111641
+ Readable5.prototype.wrap = function(stream) {
111642
111642
  var _this = this;
111643
111643
  var state = this._readableState;
111644
111644
  var paused = false;
@@ -111683,14 +111683,14 @@ var require_stream_readable = __commonJS({
111683
111683
  return this;
111684
111684
  };
111685
111685
  if (typeof Symbol === "function") {
111686
- Readable4.prototype[Symbol.asyncIterator] = function() {
111686
+ Readable5.prototype[Symbol.asyncIterator] = function() {
111687
111687
  if (createReadableStreamAsyncIterator === void 0) {
111688
111688
  createReadableStreamAsyncIterator = require_async_iterator();
111689
111689
  }
111690
111690
  return createReadableStreamAsyncIterator(this);
111691
111691
  };
111692
111692
  }
111693
- Object.defineProperty(Readable4.prototype, "readableHighWaterMark", {
111693
+ Object.defineProperty(Readable5.prototype, "readableHighWaterMark", {
111694
111694
  // making it explicit this property is not enumerable
111695
111695
  // because otherwise some prototype manipulation in
111696
111696
  // userland will fail
@@ -111699,7 +111699,7 @@ var require_stream_readable = __commonJS({
111699
111699
  return this._readableState.highWaterMark;
111700
111700
  }
111701
111701
  });
111702
- Object.defineProperty(Readable4.prototype, "readableBuffer", {
111702
+ Object.defineProperty(Readable5.prototype, "readableBuffer", {
111703
111703
  // making it explicit this property is not enumerable
111704
111704
  // because otherwise some prototype manipulation in
111705
111705
  // userland will fail
@@ -111708,7 +111708,7 @@ var require_stream_readable = __commonJS({
111708
111708
  return this._readableState && this._readableState.buffer;
111709
111709
  }
111710
111710
  });
111711
- Object.defineProperty(Readable4.prototype, "readableFlowing", {
111711
+ Object.defineProperty(Readable5.prototype, "readableFlowing", {
111712
111712
  // making it explicit this property is not enumerable
111713
111713
  // because otherwise some prototype manipulation in
111714
111714
  // userland will fail
@@ -111722,8 +111722,8 @@ var require_stream_readable = __commonJS({
111722
111722
  }
111723
111723
  }
111724
111724
  });
111725
- Readable4._fromList = fromList;
111726
- Object.defineProperty(Readable4.prototype, "readableLength", {
111725
+ Readable5._fromList = fromList;
111726
+ Object.defineProperty(Readable5.prototype, "readableLength", {
111727
111727
  // making it explicit this property is not enumerable
111728
111728
  // because otherwise some prototype manipulation in
111729
111729
  // userland will fail
@@ -111769,11 +111769,11 @@ var require_stream_readable = __commonJS({
111769
111769
  }
111770
111770
  }
111771
111771
  if (typeof Symbol === "function") {
111772
- Readable4.from = function(iterable, opts) {
111772
+ Readable5.from = function(iterable, opts) {
111773
111773
  if (from === void 0) {
111774
111774
  from = require_from();
111775
111775
  }
111776
- return from(Readable4, iterable, opts);
111776
+ return from(Readable5, iterable, opts);
111777
111777
  };
111778
111778
  }
111779
111779
  function indexOf(xs, x2) {
@@ -112390,7 +112390,7 @@ var require_websocket2 = __commonJS({
112390
112390
  var { ServerResponse } = __require("node:http");
112391
112391
  var { PassThrough } = __require("node:stream");
112392
112392
  var { randomBytes: randomBytes5 } = __require("node:crypto");
112393
- var fp37 = require_plugin2();
112393
+ var fp38 = require_plugin2();
112394
112394
  var WebSocket2 = require_ws();
112395
112395
  var Duplexify = require_duplexify();
112396
112396
  var kWs = /* @__PURE__ */ Symbol("ws-socket");
@@ -112576,7 +112576,7 @@ var require_websocket2 = __commonJS({
112576
112576
  }
112577
112577
  next();
112578
112578
  }
112579
- module.exports = fp37(fastifyWebsocket2, {
112579
+ module.exports = fp38(fastifyWebsocket2, {
112580
112580
  fastify: "5.x",
112581
112581
  name: "@fastify/websocket"
112582
112582
  });
@@ -113826,7 +113826,7 @@ var require_basename = __commonJS({
113826
113826
  var require_multipart = __commonJS({
113827
113827
  "../../node_modules/.pnpm/@fastify+busboy@3.2.0/node_modules/@fastify/busboy/lib/types/multipart.js"(exports, module) {
113828
113828
  "use strict";
113829
- var { Readable: Readable4 } = __require("node:stream");
113829
+ var { Readable: Readable5 } = __require("node:stream");
113830
113830
  var { inherits } = __require("node:util");
113831
113831
  var Dicer = require_Dicer();
113832
113832
  var parseParams = require_parseParams();
@@ -114091,11 +114091,11 @@ var require_multipart = __commonJS({
114091
114091
  part.resume();
114092
114092
  }
114093
114093
  function FileStream(opts) {
114094
- Readable4.call(this, opts);
114094
+ Readable5.call(this, opts);
114095
114095
  this.bytesRead = 0;
114096
114096
  this.truncated = false;
114097
114097
  }
114098
- inherits(FileStream, Readable4);
114098
+ inherits(FileStream, Readable5);
114099
114099
  FileStream.prototype._read = function(n) {
114100
114100
  };
114101
114101
  module.exports = Multipart;
@@ -115020,7 +115020,7 @@ var require_multipart2 = __commonJS({
115020
115020
  "use strict";
115021
115021
  var Busboy = require_main();
115022
115022
  var os3 = __require("node:os");
115023
- var fp37 = require_plugin2();
115023
+ var fp38 = require_plugin2();
115024
115024
  var { createWriteStream: createWriteStream2 } = __require("node:fs");
115025
115025
  var { unlink: unlink2 } = __require("node:fs/promises");
115026
115026
  var path26 = __require("node:path");
@@ -115028,7 +115028,7 @@ var require_multipart2 = __commonJS({
115028
115028
  var createError = require_error2();
115029
115029
  var streamToNull = require_stream_consumer();
115030
115030
  var deepmergeAll = require_deepmerge()({ all: true });
115031
- var { PassThrough, Readable: Readable4 } = __require("node:stream");
115031
+ var { PassThrough, Readable: Readable5 } = __require("node:stream");
115032
115032
  var { pipeline: pump } = __require("node:stream/promises");
115033
115033
  var secureJSON = require_secure_json_parse();
115034
115034
  var kMultipart = /* @__PURE__ */ Symbol("multipart");
@@ -115407,7 +115407,7 @@ var require_multipart2 = __commonJS({
115407
115407
  if (!field._buf) {
115408
115408
  throw new FileBufferNotFoundError();
115409
115409
  }
115410
- field.file = Readable4.from(field._buf);
115410
+ field.file = Readable5.from(field._buf);
115411
115411
  yield field;
115412
115412
  }
115413
115413
  } catch (err) {
@@ -115469,7 +115469,7 @@ var require_multipart2 = __commonJS({
115469
115469
  }
115470
115470
  });
115471
115471
  }
115472
- module.exports = fp37(fastifyMultipart2, {
115472
+ module.exports = fp38(fastifyMultipart2, {
115473
115473
  fastify: "5.x",
115474
115474
  name: "@fastify/multipart"
115475
115475
  });
@@ -126452,7 +126452,7 @@ var require_readable2 = __commonJS({
126452
126452
  "../../node_modules/.pnpm/undici@7.22.0/node_modules/undici/lib/api/readable.js"(exports, module) {
126453
126453
  "use strict";
126454
126454
  var assert2 = __require("node:assert");
126455
- var { Readable: Readable4 } = __require("node:stream");
126455
+ var { Readable: Readable5 } = __require("node:stream");
126456
126456
  var { RequestAbortedError, NotSupportedError, InvalidArgumentError: InvalidArgumentError4, AbortError } = require_errors7();
126457
126457
  var util2 = require_util7();
126458
126458
  var { ReadableStreamFrom } = require_util7();
@@ -126466,7 +126466,7 @@ var require_readable2 = __commonJS({
126466
126466
  var kBytesRead = /* @__PURE__ */ Symbol("kBytesRead");
126467
126467
  var noop4 = () => {
126468
126468
  };
126469
- var BodyReadable = class extends Readable4 {
126469
+ var BodyReadable = class extends Readable5 {
126470
126470
  /**
126471
126471
  * @param {object} opts
126472
126472
  * @param {(this: Readable, size: number) => void} opts.resume
@@ -126855,7 +126855,7 @@ var require_api_request = __commonJS({
126855
126855
  "use strict";
126856
126856
  var assert2 = __require("node:assert");
126857
126857
  var { AsyncResource } = __require("node:async_hooks");
126858
- var { Readable: Readable4 } = require_readable2();
126858
+ var { Readable: Readable5 } = require_readable2();
126859
126859
  var { InvalidArgumentError: InvalidArgumentError4, RequestAbortedError } = require_errors7();
126860
126860
  var util2 = require_util7();
126861
126861
  function noop4() {
@@ -126936,7 +126936,7 @@ var require_api_request = __commonJS({
126936
126936
  const parsedHeaders = responseHeaders === "raw" ? util2.parseHeaders(rawHeaders) : headers;
126937
126937
  const contentType2 = parsedHeaders["content-type"];
126938
126938
  const contentLength = parsedHeaders["content-length"];
126939
- const res = new Readable4({
126939
+ const res = new Readable5({
126940
126940
  resume,
126941
126941
  abort,
126942
126942
  contentType: contentType2,
@@ -127245,7 +127245,7 @@ var require_api_pipeline = __commonJS({
127245
127245
  "../../node_modules/.pnpm/undici@7.22.0/node_modules/undici/lib/api/api-pipeline.js"(exports, module) {
127246
127246
  "use strict";
127247
127247
  var {
127248
- Readable: Readable4,
127248
+ Readable: Readable5,
127249
127249
  Duplex,
127250
127250
  PassThrough
127251
127251
  } = __require("node:stream");
@@ -127261,7 +127261,7 @@ var require_api_pipeline = __commonJS({
127261
127261
  function noop4() {
127262
127262
  }
127263
127263
  var kResume = /* @__PURE__ */ Symbol("resume");
127264
- var PipelineRequest = class extends Readable4 {
127264
+ var PipelineRequest = class extends Readable5 {
127265
127265
  constructor() {
127266
127266
  super({ autoDestroy: true });
127267
127267
  this[kResume] = null;
@@ -127278,7 +127278,7 @@ var require_api_pipeline = __commonJS({
127278
127278
  callback(err);
127279
127279
  }
127280
127280
  };
127281
- var PipelineResponse = class extends Readable4 {
127281
+ var PipelineResponse = class extends Readable5 {
127282
127282
  constructor(resume) {
127283
127283
  super({ autoDestroy: true });
127284
127284
  this[kResume] = resume;
@@ -131776,7 +131776,7 @@ var require_cache2 = __commonJS({
131776
131776
  "../../node_modules/.pnpm/undici@7.22.0/node_modules/undici/lib/interceptor/cache.js"(exports, module) {
131777
131777
  "use strict";
131778
131778
  var assert2 = __require("node:assert");
131779
- var { Readable: Readable4 } = __require("node:stream");
131779
+ var { Readable: Readable5 } = __require("node:stream");
131780
131780
  var util2 = require_util7();
131781
131781
  var CacheHandler = require_cache_handler();
131782
131782
  var MemoryCacheStore = require_memory_cache_store();
@@ -131865,7 +131865,7 @@ var require_cache2 = __commonJS({
131865
131865
  return dispatch(opts, new CacheHandler(globalOpts, cacheKey2, handler));
131866
131866
  }
131867
131867
  function sendCachedValue(handler, opts, result, age, context2, isStale2) {
131868
- const stream = util2.isStream(result.body) ? result.body : Readable4.from(result.body ?? []);
131868
+ const stream = util2.isStream(result.body) ? result.body : Readable5.from(result.body ?? []);
131869
131869
  assert2(!stream.destroyed, "stream should not be destroyed");
131870
131870
  assert2(!stream.readableDidRead, "stream should not be readableDidRead");
131871
131871
  const controller = {
@@ -134791,7 +134791,7 @@ var require_fetch2 = __commonJS({
134791
134791
  subresourceSet
134792
134792
  } = require_constants9();
134793
134793
  var EE = __require("node:events");
134794
- var { Readable: Readable4, pipeline, finished, isErrored, isReadable } = __require("node:stream");
134794
+ var { Readable: Readable5, pipeline, finished, isErrored, isReadable } = __require("node:stream");
134795
134795
  var { addAbortListener, bufferToLowerCasedHeaderName } = require_util7();
134796
134796
  var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url();
134797
134797
  var { getGlobalDispatcher } = require_global2();
@@ -135717,7 +135717,7 @@ var require_fetch2 = __commonJS({
135717
135717
  headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString("latin1"), true);
135718
135718
  }
135719
135719
  const location = headersList.get("location", true);
135720
- this.body = new Readable4({ read: resume });
135720
+ this.body = new Readable5({ read: resume });
135721
135721
  const willFollow = location && request.redirect === "follow" && redirectStatusSet.has(status);
135722
135722
  const decoders = [];
135723
135723
  if (request.method !== "HEAD" && request.method !== "CONNECT" && !nullBodyStatus.includes(status) && !willFollow) {
@@ -169126,11 +169126,11 @@ function buildCommand(builderArgs) {
169126
169126
  }
169127
169127
  };
169128
169128
  }
169129
- function* generateRouteMapHelpLines(routes36, docs, args) {
169129
+ function* generateRouteMapHelpLines(routes37, docs, args) {
169130
169130
  const { brief, fullDescription, hideRoute } = docs;
169131
169131
  const { headers } = args.text;
169132
169132
  yield args.ansiColor ? `\x1B[1m${headers.usage}\x1B[22m` : headers.usage;
169133
- for (const [name25, route] of Object.entries(routes36)) {
169133
+ for (const [name25, route] of Object.entries(routes37)) {
169134
169134
  if (!hideRoute || !hideRoute[name25] || args.includeHidden) {
169135
169135
  const externalRouteName = args.config.caseStyle === "convert-camel-to-kebab" ? convertCamelCaseToKebabCase(name25) : name25;
169136
169136
  yield ` ${route.formatUsageLine({
@@ -169160,7 +169160,7 @@ function* generateRouteMapHelpLines(routes36, docs, args) {
169160
169160
  }
169161
169161
  yield "";
169162
169162
  yield args.ansiColor ? `\x1B[1m${headers.commands}\x1B[22m` : headers.commands;
169163
- const visibleRoutes = Object.entries(routes36).filter(
169163
+ const visibleRoutes = Object.entries(routes37).filter(
169164
169164
  ([name25]) => !hideRoute || !hideRoute[name25] || args.includeHidden
169165
169165
  );
169166
169166
  const rows = visibleRoutes.map(([internalRouteName, route]) => {
@@ -169188,24 +169188,24 @@ function* generateRouteMapHelpLines(routes36, docs, args) {
169188
169188
  }
169189
169189
  }
169190
169190
  function buildRouteMap({
169191
- routes: routes36,
169191
+ routes: routes37,
169192
169192
  defaultCommand: defaultCommandRoute,
169193
169193
  docs,
169194
169194
  aliases
169195
169195
  }) {
169196
- if (Object.entries(routes36).length === 0) {
169196
+ if (Object.entries(routes37).length === 0) {
169197
169197
  throw new InternalError("Route map must contain at least one route");
169198
169198
  }
169199
169199
  const activeAliases = aliases ?? {};
169200
169200
  const aliasesByRoute = /* @__PURE__ */ new Map();
169201
169201
  for (const [alias, routeName] of Object.entries(activeAliases)) {
169202
- if (alias in routes36) {
169202
+ if (alias in routes37) {
169203
169203
  throw new InternalError(`Cannot use "${alias}" as an alias when a route with that name already exists`);
169204
169204
  }
169205
169205
  const routeAliases = aliasesByRoute.get(routeName) ?? [];
169206
169206
  aliasesByRoute.set(routeName, [...routeAliases, alias]);
169207
169207
  }
169208
- const defaultCommand = defaultCommandRoute ? routes36[defaultCommandRoute] : void 0;
169208
+ const defaultCommand = defaultCommandRoute ? routes37[defaultCommandRoute] : void 0;
169209
169209
  if (defaultCommand && defaultCommand.kind === RouteMapSymbol) {
169210
169210
  throw new InternalError(
169211
169211
  `Cannot use "${defaultCommandRoute}" as the default command because it is not a Command`
@@ -169214,7 +169214,7 @@ function buildRouteMap({
169214
169214
  const resolveRouteName = (input) => {
169215
169215
  if (input in activeAliases) {
169216
169216
  return activeAliases[input];
169217
- } else if (input in routes36) {
169217
+ } else if (input in routes37) {
169218
169218
  return input;
169219
169219
  }
169220
169220
  };
@@ -169232,7 +169232,7 @@ function buildRouteMap({
169232
169232
  return `${args.prefix.join(" ")} ${routeNames.join("|")} ...`;
169233
169233
  },
169234
169234
  formatHelp: (config2) => {
169235
- const lines = [...generateRouteMapHelpLines(routes36, docs, config2)];
169235
+ const lines = [...generateRouteMapHelpLines(routes37, docs, config2)];
169236
169236
  const text2 = lines.join("\n");
169237
169237
  return text2 + "\n";
169238
169238
  },
@@ -169275,11 +169275,11 @@ function buildRouteMap({
169275
169275
  },
169276
169276
  getRoutingTargetForInput: (input) => {
169277
169277
  const routeName = input in activeAliases ? activeAliases[input] : input;
169278
- return routes36[routeName];
169278
+ return routes37[routeName];
169279
169279
  },
169280
169280
  getAllEntries() {
169281
169281
  const hiddenRoutes = docs.hideRoute;
169282
- return Object.entries(routes36).map(([originalRouteName, target]) => {
169282
+ return Object.entries(routes37).map(([originalRouteName, target]) => {
169283
169283
  return {
169284
169284
  name: {
169285
169285
  original: originalRouteName,
@@ -185779,6 +185779,10 @@ var createScheduledRepos = (kdb, h) => ({
185779
185779
  const row = await kdb.selectFrom("scheduled_tasks").selectAll().where("project_id", "=", projectId).where("source_session_id", "=", sessionId).where("source_tool_use_id", "=", toolUseId).executeTakeFirst();
185780
185780
  return row ? mapTask(row) : void 0;
185781
185781
  },
185782
+ listIdsBySourceSession: async (sessionId) => {
185783
+ const rows = await kdb.selectFrom("scheduled_tasks").select("id").where("source_session_id", "=", sessionId).where("source_tool_use_id", "is not", null).orderBy("id", "asc").execute();
185784
+ return rows.map((row) => row.id);
185785
+ },
185782
185786
  getByProjectId: async (projectId) => {
185783
185787
  const rows = await kdb.selectFrom("scheduled_tasks").selectAll().where("project_id", "=", projectId).orderBy("created_at", "asc").orderBy("id", "asc").execute();
185784
185788
  return rows.map(mapTask);
@@ -186099,6 +186103,15 @@ var createScheduledRepos = (kdb, h) => ({
186099
186103
  }
186100
186104
  });
186101
186105
 
186106
+ // src/storage/repositories/session-side-rows.ts
186107
+ async function deleteSessionSideRows(trx, sessionIds) {
186108
+ if (sessionIds.length === 0) return;
186109
+ const ids = [...sessionIds];
186110
+ await trx.deleteFrom("agent_session_remote_grants").where("session_id", "in", ids).execute();
186111
+ await trx.deleteFrom("agent_session_remote_touches").where("session_id", "in", ids).execute();
186112
+ await trx.deleteFrom("agent_session_retention_holds").where("session_id", "in", ids).execute();
186113
+ }
186114
+
186102
186115
  // src/storage/repositories/core.ts
186103
186116
  var mapProject = (row) => ({
186104
186117
  id: row.id,
@@ -186180,7 +186193,12 @@ var createCoreRepos = (kdb, h) => ({
186180
186193
  let scope = trx.selectFrom("projects").select("id").where("id", "=", id);
186181
186194
  if (userId) scope = scope.where("user_id", "=", userId);
186182
186195
  if (!await scope.executeTakeFirst()) return;
186183
- const mappings = await trx.selectFrom("remote_session_mappings").select(["remote_server_id", "remote_session_id"]).where("project_id", "=", id).execute();
186196
+ const mappings = await trx.selectFrom("remote_session_mappings").select(["local_session_id", "remote_server_id", "remote_session_id"]).where("project_id", "=", id).execute();
186197
+ const localSessions = await trx.selectFrom("agent_sessions").select("id").where("project_id", "=", id).execute();
186198
+ await deleteSessionSideRows(trx, [
186199
+ ...localSessions.map((row) => row.id),
186200
+ ...mappings.map((row) => row.local_session_id)
186201
+ ]);
186184
186202
  for (const mapping of mappings) {
186185
186203
  await trx.deleteFrom("notification_sync_cursors").where("remote_server_id", "=", mapping.remote_server_id).where("remote_session_id", "=", mapping.remote_session_id).execute();
186186
186204
  }
@@ -187072,6 +187090,10 @@ var retentionPredicate = (cutoff) => sql`
187072
187090
  AND favorited_at IS NULL
187073
187091
  AND status <> 'running'
187074
187092
  AND ${visibleLifecycle}
187093
+ AND NOT EXISTS (
187094
+ SELECT 1 FROM agent_session_retention_holds h
187095
+ WHERE h.session_id = agent_sessions.id
187096
+ )
187075
187097
  AND NOT EXISTS (
187076
187098
  SELECT 1 FROM workflow_runs wr
187077
187099
  WHERE wr.status IN (${sql.join(WORKFLOW_ACTIVE_STATUSES.map((s3) => sql`${s3}`))})
@@ -187319,7 +187341,7 @@ var createAgentSessionRepos = (kdb, h) => ({
187319
187341
  delete: async (id) => {
187320
187342
  await kdb.transaction().execute(async (trx) => {
187321
187343
  await trx.deleteFrom("agent_sessions").where("id", "=", id).execute();
187322
- await trx.deleteFrom("agent_session_remote_grants").where("session_id", "=", id).execute();
187344
+ await deleteSessionSideRows(trx, [id]);
187323
187345
  });
187324
187346
  },
187325
187347
  // The original inline statement is `INSERT ... ON CONFLICT(session_id,
@@ -187375,19 +187397,25 @@ var createAgentSessionRepos = (kdb, h) => ({
187375
187397
  return query.orderBy("activity_at", "asc").orderBy("id", "asc").limit(limit).execute();
187376
187398
  },
187377
187399
  deleteIfExpired: async (id, cutoff) => {
187378
- const result = await kdb.deleteFrom("agent_sessions").where("id", "=", id).where(retentionPredicate(cutoff)).executeTakeFirst();
187379
- return (result.numDeletedRows ?? 0n) > 0n;
187400
+ return kdb.transaction().execute(async (trx) => {
187401
+ const result = await trx.deleteFrom("agent_sessions").where("id", "=", id).where(retentionPredicate(cutoff)).executeTakeFirst();
187402
+ const deleted = (result.numDeletedRows ?? 0n) > 0n;
187403
+ if (deleted) await deleteSessionSideRows(trx, [id]);
187404
+ return deleted;
187405
+ });
187380
187406
  },
187381
187407
  // Legacy compensation only ever targets rows the legacy `/new` path
187382
187408
  // created, i.e. `active` ones. Pending identities and tombstones belong
187383
187409
  // to the lifecycle service; deleting them here would break its replay.
187384
- deleteIfEmpty: async (id) => {
187385
- const result = await kdb.deleteFrom("agent_sessions").where("id", "=", id).where("lifecycle_state", "=", "active").where(sql`NOT EXISTS (
187410
+ deleteIfEmpty: async (id) => kdb.transaction().execute(async (trx) => {
187411
+ const result = await trx.deleteFrom("agent_sessions").where("id", "=", id).where("lifecycle_state", "=", "active").where(sql`NOT EXISTS (
187386
187412
  SELECT 1 FROM agent_session_entries entry
187387
187413
  WHERE entry.session_id = agent_sessions.id
187388
187414
  )`).executeTakeFirst();
187389
- return (result.numDeletedRows ?? 0n) > 0n;
187390
- },
187415
+ const deleted = (result.numDeletedRows ?? 0n) > 0n;
187416
+ if (deleted) await deleteSessionSideRows(trx, [id]);
187417
+ return deleted;
187418
+ }),
187391
187419
  listIdsByProject: async (projectId) => {
187392
187420
  const rows = await kdb.selectFrom("agent_sessions").select("id").where("project_id", "=", projectId).where(visibleLifecycle).orderBy("id", "asc").execute();
187393
187421
  return rows.map((r) => r.id);
@@ -187556,8 +187584,11 @@ var createAgentSessionRepos = (kdb, h) => ({
187556
187584
  deleteExpiredTombstones: async ({ cutoff, limit }) => {
187557
187585
  const victims = await kdb.selectFrom("agent_sessions").select("id").where("lifecycle_state", "=", "expired").where("expired_at", "is not", null).where("expired_at", "<", cutoff).orderBy("expired_at", "asc").limit(limit).execute();
187558
187586
  if (victims.length === 0) return 0;
187559
- const result = await kdb.deleteFrom("agent_sessions").where("id", "in", victims.map((r) => r.id)).where("lifecycle_state", "=", "expired").where("expired_at", "<", cutoff).executeTakeFirst();
187560
- return Number(result.numDeletedRows ?? 0n);
187587
+ return kdb.transaction().execute(async (trx) => {
187588
+ const deleted = await trx.deleteFrom("agent_sessions").where("id", "in", victims.map((r) => r.id)).where("lifecycle_state", "=", "expired").where("expired_at", "<", cutoff).returning("id").execute();
187589
+ await deleteSessionSideRows(trx, deleted.map((r) => r.id));
187590
+ return deleted.length;
187591
+ });
187561
187592
  },
187562
187593
  clearActivationPayloads: async ({ cutoff, limit }) => {
187563
187594
  const rows = await kdb.selectFrom("agent_sessions").select("id").where("lifecycle_state", "=", "active").where("activation_content_json", "is not", null).where("activated_at", "is not", null).where("activated_at", "<", cutoff).limit(limit).execute();
@@ -187663,6 +187694,12 @@ var createAgentSessionRepos = (kdb, h) => ({
187663
187694
  const rows = await kdb.selectFrom("remote_session_mappings").selectAll().execute();
187664
187695
  return rows.map(mapRemoteSessionMapping);
187665
187696
  },
187697
+ // Same link test as projectRemotes.getByProjectAndServer: the
187698
+ // project_remotes row AND its remote_servers row (that lookup inner-joins).
187699
+ getAllWithLinkState: async () => {
187700
+ const rows = await kdb.selectFrom("remote_session_mappings as mapping").leftJoin("project_remotes as link", (join2) => join2.onRef("link.project_id", "=", "mapping.project_id").onRef("link.remote_server_id", "=", "mapping.remote_server_id")).leftJoin("remote_servers as server", "server.id", "link.remote_server_id").selectAll("mapping").select("server.id as linked_server_id").execute();
187701
+ return rows.map((row) => ({ ...mapRemoteSessionMapping(row), linked: row.linked_server_id != null }));
187702
+ },
187666
187703
  listByProject: async (projectId, limit, consumer) => {
187667
187704
  const rows = await projectedRemoteMappingBase(kdb).where(sql`case when mapping.workspace_checkout_id is null then mapping.project_id else workspace.project_id end = ${projectId}`).orderBy("mapping.local_session_id", "asc").limit(limit).execute();
187668
187705
  rows.forEach((row) => observeProjectedRemoteMapping(consumer, row));
@@ -187748,7 +187785,7 @@ var createAgentSessionRepos = (kdb, h) => ({
187748
187785
  if (row) {
187749
187786
  await trx.deleteFrom("notification_sync_cursors").where("remote_server_id", "=", row.remote_server_id).where("remote_session_id", "=", row.remote_session_id).execute();
187750
187787
  }
187751
- await trx.deleteFrom("agent_session_remote_grants").where("session_id", "=", localSessionId).execute();
187788
+ await deleteSessionSideRows(trx, [localSessionId]);
187752
187789
  return (result.numDeletedRows ?? 0n) > 0n;
187753
187790
  });
187754
187791
  },
@@ -188167,15 +188204,18 @@ var createCrossRemoteAuditRepo = (kdb) => ({
188167
188204
  insert: async (entry) => {
188168
188205
  await kdb.insertInto("cross_remote_audit").values({ id: crypto3.randomUUID(), created_at: (/* @__PURE__ */ new Date()).toISOString(), ...entry }).execute();
188169
188206
  },
188170
- listSessionTargets: async (sessionId, userId, limit = 8) => {
188171
- let query = kdb.selectFrom("cross_remote_audit").select(["target_remote_id"]).select((eb) => eb.fn.max("seq").as("last_seq")).where("session_id", "=", sessionId).where("status", "not in", ["denied", "offline"]);
188172
- if (userId) query = query.where("user_id", "=", userId);
188173
- const rows = await query.groupBy("target_remote_id").orderBy("last_seq", "desc").limit(limit).execute();
188174
- return rows.map((row) => row.target_remote_id);
188175
- },
188176
188207
  listByTarget: async (targetRemoteId, limit = 100) => {
188177
188208
  const rows = await kdb.selectFrom("cross_remote_audit").selectAll().where("target_remote_id", "=", targetRemoteId).orderBy("seq", "desc").limit(limit).execute();
188178
188209
  return rows.map(mapRow);
188210
+ },
188211
+ pruneBefore: async (cutoff, limit) => {
188212
+ const firstKept = await kdb.selectFrom("cross_remote_audit").select("seq").where("created_at", ">=", cutoff.toISOString()).orderBy("seq", "asc").limit(1).executeTakeFirst();
188213
+ const result = await kdb.deleteFrom("cross_remote_audit").where("seq", "in", (eb) => {
188214
+ let batch = eb.selectFrom("cross_remote_audit").select("seq");
188215
+ if (firstKept) batch = batch.where("seq", "<", firstKept.seq);
188216
+ return batch.orderBy("seq", "asc").limit(limit);
188217
+ }).executeTakeFirst();
188218
+ return Number(result.numDeletedRows ?? 0n);
188179
188219
  }
188180
188220
  }
188181
188221
  });
@@ -188207,6 +188247,52 @@ var createSessionRemoteGrantRepo = (kdb) => ({
188207
188247
  }
188208
188248
  });
188209
188249
 
188250
+ // src/storage/repositories/session-remote-touches.ts
188251
+ var createSessionRemoteTouchRepo = (kdb) => ({
188252
+ sessionRemoteTouches: {
188253
+ record: async (sessionId, userId, remoteServerId) => {
188254
+ const now3 = (/* @__PURE__ */ new Date()).toISOString();
188255
+ await kdb.insertInto("agent_session_remote_touches").values({ session_id: sessionId, remote_server_id: remoteServerId, user_id: userId, last_used_at: now3 }).onConflict((oc) => oc.columns(["session_id", "remote_server_id"]).doUpdateSet({ last_used_at: now3 })).execute();
188256
+ },
188257
+ list: async (sessionId, userId, limit = 8) => {
188258
+ let query = kdb.selectFrom("agent_session_remote_touches").select("remote_server_id").where("session_id", "=", sessionId);
188259
+ if (userId) query = query.where("user_id", "=", userId);
188260
+ const rows = await query.orderBy("last_used_at", "desc").orderBy("remote_server_id", "asc").limit(limit).execute();
188261
+ return rows.map((row) => row.remote_server_id);
188262
+ }
188263
+ }
188264
+ });
188265
+
188266
+ // src/storage/repositories/session-retention-holds.ts
188267
+ var createSessionRetentionHoldRepo = (kdb) => ({
188268
+ sessionRetentionHolds: {
188269
+ list: async (sessionId) => {
188270
+ const rows = await kdb.selectFrom("agent_session_retention_holds").select(["holder_kind", "holder_id"]).where("session_id", "=", sessionId).orderBy("holder_kind", "asc").orderBy("holder_id", "asc").execute();
188271
+ return rows.map((row) => ({ kind: row.holder_kind, id: row.holder_id }));
188272
+ },
188273
+ listSessionIds: async () => {
188274
+ const rows = await kdb.selectFrom("agent_session_retention_holds").select("session_id").distinct().orderBy("session_id", "asc").execute();
188275
+ return rows.map((row) => row.session_id);
188276
+ },
188277
+ replace: async (sessionId, holds) => {
188278
+ const unique = /* @__PURE__ */ new Map();
188279
+ for (const hold of holds) unique.set(`${hold.kind}\0${hold.id}`, hold);
188280
+ const createdAt = (/* @__PURE__ */ new Date()).toISOString();
188281
+ await kdb.transaction().execute(async (trx) => {
188282
+ await trx.deleteFrom("agent_session_retention_holds").where("session_id", "=", sessionId).execute();
188283
+ if (unique.size > 0) {
188284
+ await trx.insertInto("agent_session_retention_holds").values([...unique.values()].map((hold) => ({
188285
+ session_id: sessionId,
188286
+ holder_kind: hold.kind,
188287
+ holder_id: hold.id,
188288
+ created_at: createdAt
188289
+ }))).execute();
188290
+ }
188291
+ });
188292
+ }
188293
+ }
188294
+ });
188295
+
188210
188296
  // src/storage/repositories/merge-targets.ts
188211
188297
  var createMergeTargetsRepo = (kdb) => ({
188212
188298
  mergeTargets: {
@@ -188557,6 +188643,13 @@ var createSearchCacheRepos = (kdb, _h) => ({
188557
188643
  if (projectIds.length === 0) return [];
188558
188644
  return kdb.selectFrom("search_catalog_sync_state").select(["project_id", "target_id", "last_success_at", "last_attempt_at", "last_error"]).where("project_id", "in", projectIds).execute();
188559
188645
  },
188646
+ getCachedSessionTitles: async (localSessionIds) => {
188647
+ const titles = /* @__PURE__ */ new Map();
188648
+ if (localSessionIds.length === 0) return titles;
188649
+ const rows = await kdb.selectFrom("session_search_cache").select(["local_session_id", "title"]).where("local_session_id", "in", [...localSessionIds]).where("deleted_at", "is", null).execute();
188650
+ for (const row of rows) titles.set(row.local_session_id, row.title);
188651
+ return titles;
188652
+ },
188560
188653
  // Opportunistic freshness: called where a title transits the server
188561
188654
  // anyway (remote title PATCH proxy + local AI title generation).
188562
188655
  // UPDATE-only — a title alone must not fabricate a session's existence.
@@ -188806,15 +188899,14 @@ var createSearchCacheRepos = (kdb, _h) => ({
188806
188899
  favorited: false,
188807
188900
  recency: 0
188808
188901
  })), limitPerGroup);
188809
- const wsRows = await kdb.selectFrom("workspace_search_cache as w").leftJoin("project_remotes as pr", (join2) => join2.onRef("pr.project_id", "=", "w.project_id").onRef("pr.remote_server_id", "=", "w.target_id")).select(["w.project_id", "w.target_id", "w.branch"]).where("w.project_id", "in", projectIds).where("w.deleted_at", "is", null).where((eb) => eb.or([
188902
+ const wsRows = await kdb.selectFrom("workspace_search_cache as w").leftJoin("project_remotes as pr", (join2) => join2.onRef("pr.project_id", "=", "w.project_id").onRef("pr.remote_server_id", "=", "w.target_id")).select(["w.project_id", "w.branch"]).where("w.project_id", "in", projectIds).where("w.deleted_at", "is", null).where((eb) => eb.or([
188810
188903
  eb("w.target_id", "=", "local"),
188811
188904
  eb("pr.id", "is not", null)
188812
- ])).execute();
188905
+ ])).groupBy(["w.project_id", "w.branch"]).execute();
188813
188906
  const workspaces = rankAndCap(wsRows.map((w2) => ({
188814
188907
  item: {
188815
188908
  projectId: w2.project_id,
188816
188909
  projectName: nameById.get(w2.project_id) ?? "",
188817
- targetId: w2.target_id,
188818
188910
  branch: fromDbBranch(w2.branch)
188819
188911
  },
188820
188912
  tier: matchTier(fromDbBranch(w2.branch) ?? "main", q),
@@ -188883,6 +188975,10 @@ var createWorkflowRunRepos = (kdb) => ({
188883
188975
  const row = await kdb.selectFrom("workflow_runs").selectAll().where("loop_id", "=", loopId).where("round", "=", round).orderBy("created_at", "desc").orderBy(sql`rowid`, "desc").executeTakeFirst();
188884
188976
  return row ? asRun(row) : void 0;
188885
188977
  },
188978
+ getLatestLoopRunByReviewer: async (reviewerSessionId) => {
188979
+ const row = await kdb.selectFrom("workflow_runs").selectAll().where("reviewer_session_id", "=", reviewerSessionId).where("loop_id", "is not", null).where("kind", "=", "review").orderBy("created_at", "desc").orderBy(sql`rowid`, "desc").executeTakeFirst();
188980
+ return row ? asRun(row) : void 0;
188981
+ },
188886
188982
  listReviewedSourceSessions: async (projectId, branch) => {
188887
188983
  const rows = await kdb.selectFrom("workflow_runs").select("source_session_id").distinct().where("project_id", "=", projectId).where("branch", "is", branch).where("status", "=", "completed").where("reviewer_session_id", "is not", null).execute();
188888
188984
  return rows.map((r) => r.source_session_id);
@@ -188960,10 +189056,11 @@ var createWorkflowRunRepos = (kdb) => ({
188960
189056
  await sql`
188961
189057
  INSERT INTO workflow_runs
188962
189058
  (id, project_id, branch, source_session_id, source_turn_end_index, reviewer_session_id,
188963
- review_focus, review_target, review_span, status, loop_id, round, max_rounds)
189059
+ review_focus, review_target, review_span, status, loop_id, round, max_rounds, loop_manual)
188964
189060
  SELECT ${nextRun.id}, ${nextRun.project_id}, ${nextRun.branch}, ${nextRun.source_session_id},
188965
189061
  ${nextRun.source_turn_end_index}, NULL, ${nextRun.review_focus}, ${nextRun.review_target},
188966
- 'this_turn', 'waiting_rereview', ${nextRun.loop_id}, ${nextRun.round}, ${nextRun.max_rounds}
189062
+ 'this_turn', 'waiting_rereview', ${nextRun.loop_id}, ${nextRun.round}, ${nextRun.max_rounds},
189063
+ ${nextRun.loop_manual}
188967
189064
  WHERE NOT EXISTS (
188968
189065
  SELECT 1 FROM workflow_runs
188969
189066
  WHERE status IN (${sql.join(ACTIVE)})
@@ -203220,6 +203317,19 @@ function assertProjectChatMessageWithinByteLimit(type, content) {
203220
203317
 
203221
203318
  // src/storage/repositories/project-chat.ts
203222
203319
  var now = () => sql`strftime('%Y-%m-%d %H:%M:%f', 'now')`;
203320
+ async function backfillMissingThreadTitles(kdb, projectId, userId, threadId) {
203321
+ let query = kdb.updateTable("project_chat_threads").set({ title: sql`(
203322
+ select substr(trim(m.content), 1, 60)
203323
+ from project_chat_messages as m
203324
+ where m.thread_id = project_chat_threads.id and m.type = 'user'
203325
+ order by m.sequence asc limit 1
203326
+ )` }).where("project_id", "=", projectId).where("user_id", "=", userId).where("title", "is", null).where(sql`exists (
203327
+ select 1 from project_chat_messages as m
203328
+ where m.thread_id = project_chat_threads.id and m.type = 'user'
203329
+ )`);
203330
+ if (threadId) query = query.where("id", "=", threadId);
203331
+ await query.execute();
203332
+ }
203223
203333
  var mapThread = (row) => {
203224
203334
  const {
203225
203335
  create_request_id: _requestId,
@@ -203407,12 +203517,14 @@ var createProjectChatRepos = (kdb) => ({
203407
203517
  return { thread: mapThread(existing), created: false };
203408
203518
  }),
203409
203519
  listByProject: async (projectId, userId, limit, opts) => {
203520
+ await backfillMissingThreadTitles(kdb, projectId, userId);
203410
203521
  let query = kdb.selectFrom("project_chat_threads").selectAll().where("project_id", "=", projectId).where("user_id", "=", userId);
203411
203522
  if (!opts?.includeArchived) query = query.where("archived_at", "is", null);
203412
203523
  const rows = await query.orderBy("updated_at", "desc").orderBy("id", "desc").limit(limit).execute();
203413
203524
  return rows.map(mapThread);
203414
203525
  },
203415
203526
  listPageByProject: async (projectId, userId, limit, opts) => {
203527
+ await backfillMissingThreadTitles(kdb, projectId, userId);
203416
203528
  let query = kdb.selectFrom("project_chat_threads").selectAll().where("project_id", "=", projectId).where("user_id", "=", userId);
203417
203529
  if (!opts?.includeArchived) query = query.where("archived_at", "is", null);
203418
203530
  if (opts?.query) {
@@ -203441,7 +203553,11 @@ var createProjectChatRepos = (kdb) => ({
203441
203553
  },
203442
203554
  getById: async (id, projectId, userId) => {
203443
203555
  if (!userId) return void 0;
203444
- const row = await kdb.selectFrom("project_chat_threads").selectAll().where("id", "=", id).where("project_id", "=", projectId).where("user_id", "=", userId).executeTakeFirst();
203556
+ let row = await kdb.selectFrom("project_chat_threads").selectAll().where("id", "=", id).where("project_id", "=", projectId).where("user_id", "=", userId).executeTakeFirst();
203557
+ if (row?.title === null) {
203558
+ await backfillMissingThreadTitles(kdb, projectId, userId, id);
203559
+ row = await kdb.selectFrom("project_chat_threads").selectAll().where("id", "=", id).where("project_id", "=", projectId).where("user_id", "=", userId).executeTakeFirst();
203560
+ }
203445
203561
  return row ? mapThread(row) : void 0;
203446
203562
  },
203447
203563
  update: async (id, projectId, userId, patch) => {
@@ -203457,6 +203573,14 @@ var createProjectChatRepos = (kdb) => ({
203457
203573
  const row = await kdb.selectFrom("project_chat_threads").selectAll().where("id", "=", id).where("project_id", "=", projectId).where("user_id", "=", userId).executeTakeFirst();
203458
203574
  return row ? mapThread(row) : void 0;
203459
203575
  },
203576
+ setTitleIfMissing: async (id, projectId, userId, title) => {
203577
+ const row = await kdb.updateTable("project_chat_threads").set({ title }).where("id", "=", id).where("project_id", "=", projectId).where("user_id", "=", userId).where("title", "is", null).returningAll().executeTakeFirst();
203578
+ return row ? mapThread(row) : void 0;
203579
+ },
203580
+ replaceTitleIfCurrent: async (id, projectId, userId, currentTitle, title) => {
203581
+ const row = await kdb.updateTable("project_chat_threads").set({ title }).where("id", "=", id).where("project_id", "=", projectId).where("user_id", "=", userId).where("title", "=", currentTitle).returningAll().executeTakeFirst();
203582
+ return row ? mapThread(row) : void 0;
203583
+ },
203460
203584
  archive: async (id, projectId, userId) => {
203461
203585
  await kdb.updateTable("project_chat_threads").set({ archived_at: Date.now(), updated_at: now() }).where("id", "=", id).where("project_id", "=", projectId).where("user_id", "=", userId).execute();
203462
203586
  const row = await kdb.selectFrom("project_chat_threads").selectAll().where("id", "=", id).where("project_id", "=", projectId).where("user_id", "=", userId).executeTakeFirst();
@@ -204831,11 +204955,41 @@ var initializeSchema = (db) => {
204831
204955
 
204832
204956
  CREATE INDEX IF NOT EXISTS idx_cross_remote_audit_target ON cross_remote_audit(target_remote_id, seq);
204833
204957
 
204834
- -- listSessionTargets asks "which machines has this session touched?" on the
204835
- -- path of every artifact hover, so it must not scan a table that grows with
204836
- -- every gateway call ever made. seq trails session_id to serve the
204837
- -- most-recent-first ordering from the index.
204838
- CREATE INDEX IF NOT EXISTS idx_cross_remote_audit_session ON cross_remote_audit(session_id, seq);
204958
+ -- Briefly served "which machines has this session touched?" before that
204959
+ -- moved to agent_session_remote_touches; the audit is time-pruned now and
204960
+ -- no longer read by session.
204961
+ DROP INDEX IF EXISTS idx_cross_remote_audit_session;
204962
+
204963
+ -- Which machines a session's calls actually ran on through the cross-remote
204964
+ -- gateway: one row per (session, machine), refreshed on every call. The
204965
+ -- grants table above says where the agent MAY go; this says where it WENT,
204966
+ -- which is where its artifacts (a screenshot in another box's /tmp) live \u2014
204967
+ -- artifact-read-targets.ts reads it on every artifact hover. Kept apart from
204968
+ -- cross_remote_audit because the lifetimes differ: the audit is pruned by
204969
+ -- age, while this lives exactly as long as its session (every session
204970
+ -- delete path calls deleteSessionSideRows). No FK on session_id, for the
204971
+ -- same reason as the grants table.
204972
+ CREATE TABLE IF NOT EXISTS agent_session_remote_touches (
204973
+ session_id TEXT NOT NULL,
204974
+ remote_server_id TEXT NOT NULL REFERENCES remote_servers(id) ON DELETE CASCADE,
204975
+ user_id TEXT NOT NULL,
204976
+ last_used_at TEXT NOT NULL,
204977
+ PRIMARY KEY (session_id, remote_server_id)
204978
+ );
204979
+
204980
+ -- What keeps a session out of the retention sweep besides a star: one row
204981
+ -- per (session, holder) \u2014 today a schedule proposed from that session.
204982
+ -- Owned by the machine the session lives on (the hub pushes the whole set
204983
+ -- to a worker), since retention runs there. Retention-only: a manual
204984
+ -- delete still goes through and removes the rows via deleteSessionSideRows.
204985
+ -- No FK on session_id, for the same reason as the grants table.
204986
+ CREATE TABLE IF NOT EXISTS agent_session_retention_holds (
204987
+ session_id TEXT NOT NULL,
204988
+ holder_kind TEXT NOT NULL,
204989
+ holder_id TEXT NOT NULL,
204990
+ created_at TEXT NOT NULL,
204991
+ PRIMARY KEY (session_id, holder_kind, holder_id)
204992
+ );
204839
204993
  `);
204840
204994
  const workspaceCheckoutsTable = db.prepare(
204841
204995
  "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'workspace_checkouts'"
@@ -205870,6 +206024,7 @@ var initializeSchema = (db) => {
205870
206024
  loop_id TEXT,
205871
206025
  round INTEGER NOT NULL DEFAULT 1,
205872
206026
  max_rounds INTEGER,
206027
+ loop_manual INTEGER NOT NULL DEFAULT 0,
205873
206028
  verdict TEXT,
205874
206029
  kind TEXT NOT NULL DEFAULT 'review',
205875
206030
  params TEXT,
@@ -206063,7 +206218,9 @@ var initializeSchema = (db) => {
206063
206218
  // Repeat-until-done loops: every earlier row is a review.
206064
206219
  ["kind", "kind TEXT NOT NULL DEFAULT 'review'"],
206065
206220
  ["params", "params TEXT"],
206066
- ["outcome_status", "outcome_status TEXT"]
206221
+ ["outcome_status", "outcome_status TEXT"],
206222
+ // Unattended review loops: set once the user steps in.
206223
+ ["loop_manual", "loop_manual INTEGER NOT NULL DEFAULT 0"]
206067
206224
  ]) {
206068
206225
  if (!workflowRunsInfo.some((col) => col.name === name25)) {
206069
206226
  db.exec(`ALTER TABLE workflow_runs ADD COLUMN ${ddl}`);
@@ -206213,6 +206370,8 @@ var createSqliteStorage = async (dbPath) => {
206213
206370
  ...createWorkspaceRepos(kdb, h),
206214
206371
  ...createCrossRemoteAuditRepo(kdb),
206215
206372
  ...createSessionRemoteGrantRepo(kdb),
206373
+ ...createSessionRemoteTouchRepo(kdb),
206374
+ ...createSessionRetentionHoldRepo(kdb),
206216
206375
  ...createMergeTargetsRepo(kdb),
206217
206376
  ...createSearchCacheRepos(kdb, h),
206218
206377
  ...createWorkflowRunRepos(kdb),
@@ -207886,6 +208045,214 @@ ${GREEN}Done${info}${RESET}
207886
208045
  }
207887
208046
  };
207888
208047
 
208048
+ // src/trace-context.ts
208049
+ import { AsyncLocalStorage } from "node:async_hooks";
208050
+ import { randomBytes as randomBytes2 } from "node:crypto";
208051
+ var VERSION3 = "00";
208052
+ var INVALID_VERSION = "ff";
208053
+ var ZERO_TRACE_ID = "0".repeat(32);
208054
+ var ZERO_SPAN_ID = "0".repeat(16);
208055
+ var HEX_2 = /^[0-9a-f]{2}$/;
208056
+ var HEX_16 = /^[0-9a-f]{16}$/;
208057
+ var HEX_32 = /^[0-9a-f]{32}$/;
208058
+ function parseTraceparent(value) {
208059
+ const raw = Array.isArray(value) ? value[0] : value;
208060
+ if (typeof raw !== "string") return null;
208061
+ const parts = raw.split("-");
208062
+ if (parts.length < 4) return null;
208063
+ const [version2, traceId, spanId, flags] = parts;
208064
+ if (!HEX_2.test(version2) || version2 === INVALID_VERSION) return null;
208065
+ if (version2 === VERSION3 && parts.length !== 4) return null;
208066
+ if (!HEX_32.test(traceId) || traceId === ZERO_TRACE_ID) return null;
208067
+ if (!HEX_16.test(spanId) || spanId === ZERO_SPAN_ID) return null;
208068
+ if (!HEX_2.test(flags)) return null;
208069
+ return { traceId, spanId, flags };
208070
+ }
208071
+ function formatTraceparent(ctx) {
208072
+ return `${VERSION3}-${ctx.traceId}-${ctx.spanId}-${ctx.sampled ? "01" : "00"}`;
208073
+ }
208074
+ function newTraceId() {
208075
+ return randomBytes2(16).toString("hex");
208076
+ }
208077
+ function newSpanId() {
208078
+ return randomBytes2(8).toString("hex");
208079
+ }
208080
+ function newTraceContext(incoming) {
208081
+ const parsed = parseTraceparent(incoming);
208082
+ if (parsed) {
208083
+ return {
208084
+ traceId: parsed.traceId,
208085
+ spanId: newSpanId(),
208086
+ parentSpanId: parsed.spanId,
208087
+ sampled: (parseInt(parsed.flags, 16) & 1) === 1,
208088
+ continued: true
208089
+ };
208090
+ }
208091
+ return {
208092
+ traceId: newTraceId(),
208093
+ spanId: newSpanId(),
208094
+ sampled: true,
208095
+ continued: false
208096
+ };
208097
+ }
208098
+ var storage = new AsyncLocalStorage();
208099
+ function runWithTraceContext(ctx, fn) {
208100
+ return storage.run(ctx, fn);
208101
+ }
208102
+ function getTraceContext() {
208103
+ return storage.getStore();
208104
+ }
208105
+ function outboundTraceparent() {
208106
+ const ctx = storage.getStore();
208107
+ return ctx ? formatTraceparent(ctx) : void 0;
208108
+ }
208109
+
208110
+ // src/utils/remote-proxy.ts
208111
+ function proxyStatus(result, fallback = 502) {
208112
+ return result.status > 0 ? result.status : fallback;
208113
+ }
208114
+ async function proxyToRemoteAuto(remoteServerId, method, apiPath, body, options) {
208115
+ const rcm = options?.reverseConnectManager;
208116
+ if (rcm && rcm.isConnected(remoteServerId)) {
208117
+ const traceparent = outboundTraceparent();
208118
+ const headers = {
208119
+ ...traceparent ? { traceparent } : {},
208120
+ ...options?.headers
208121
+ };
208122
+ return rcm.sendHttpRequest(remoteServerId, method, apiPath, body, options?.timeoutMs, headers);
208123
+ }
208124
+ return {
208125
+ ok: false,
208126
+ status: 0,
208127
+ data: { error: "Remote server is not connected" },
208128
+ errorCode: "network_error",
208129
+ requestId: options?.requestId
208130
+ };
208131
+ }
208132
+
208133
+ // src/retention-holds.ts
208134
+ var TIMEOUT_MS = 1e4;
208135
+ var RELEASE_STALE_MAX_SESSIONS = 1e4;
208136
+ var RetentionHoldSync = class {
208137
+ constructor(deps) {
208138
+ this.deps = deps;
208139
+ }
208140
+ deps;
208141
+ tails = /* @__PURE__ */ new Map();
208142
+ releasing = /* @__PURE__ */ new Map();
208143
+ /**
208144
+ * Recompute `sessionId`'s holds and write them where the session lives.
208145
+ * Rejects when the write did not land (worker offline); the caller decides
208146
+ * whether that blocks.
208147
+ */
208148
+ sync(sessionId) {
208149
+ return this.exclusive(sessionId, (syncNow) => syncNow());
208150
+ }
208151
+ /**
208152
+ * Run `fn` with this session's slot held: no other sync or exclusive block
208153
+ * for the session starts until it settles. `syncNow` syncs inside the slot
208154
+ * (calling `sync` from `fn` would wait on itself).
208155
+ */
208156
+ exclusive(sessionId, fn) {
208157
+ const prev = this.tails.get(sessionId) ?? Promise.resolve();
208158
+ const run2 = prev.then(() => fn(() => this.syncNow(sessionId)));
208159
+ const tail = run2.catch(() => void 0);
208160
+ this.tails.set(sessionId, tail);
208161
+ void tail.then(() => {
208162
+ if (this.tails.get(sessionId) === tail) this.tails.delete(sessionId);
208163
+ });
208164
+ return run2;
208165
+ }
208166
+ /**
208167
+ * Recompute every session that holds on `remoteServerId` reports. A hold
208168
+ * only ever outlives its schedules when a release failed (worker away, or a
208169
+ * rolled-back create whose push landed after its timeout); this is what
208170
+ * eventually frees those sessions. It only re-derives sessions that already
208171
+ * have holds — schedules that predate holds are deliberately not backfilled.
208172
+ * Never throws; returns how many sessions could not be synced. A call while
208173
+ * one for the same worker is running joins it.
208174
+ */
208175
+ releaseStale(remoteServerId) {
208176
+ const running = this.releasing.get(remoteServerId);
208177
+ if (running) return running;
208178
+ const run2 = this.releaseStaleNow(remoteServerId).finally(() => this.releasing.delete(remoteServerId));
208179
+ this.releasing.set(remoteServerId, run2);
208180
+ return run2;
208181
+ }
208182
+ async releaseStaleNow(remoteServerId) {
208183
+ const proxy = this.deps.proxy ?? proxyToRemoteAuto;
208184
+ const listed = await proxy(
208185
+ remoteServerId,
208186
+ "GET",
208187
+ "/api/path/retention-holds",
208188
+ void 0,
208189
+ { reverseConnectManager: this.deps.reverseConnectManager, timeoutMs: TIMEOUT_MS }
208190
+ );
208191
+ const sessionIds = listed.data?.sessionIds;
208192
+ if (!listed.ok || !Array.isArray(sessionIds)) return 1;
208193
+ if (sessionIds.length > RELEASE_STALE_MAX_SESSIONS) {
208194
+ console.warn(`[RetentionHolds] ${remoteServerId} listed ${sessionIds.length} held sessions; checking the first ${RELEASE_STALE_MAX_SESSIONS}`);
208195
+ }
208196
+ let failed = 0;
208197
+ for (const remoteSessionId of sessionIds.slice(0, RELEASE_STALE_MAX_SESSIONS)) {
208198
+ if (typeof remoteSessionId !== "string") continue;
208199
+ try {
208200
+ const mapping = await this.deps.storage.remoteSessionMappings.getByRemote(remoteServerId, remoteSessionId);
208201
+ if (mapping) {
208202
+ await this.sync(mapping.local_session_id);
208203
+ } else {
208204
+ await this.push({ remoteServerId, remoteSessionId }, []);
208205
+ }
208206
+ } catch {
208207
+ failed++;
208208
+ }
208209
+ }
208210
+ return failed;
208211
+ }
208212
+ async syncNow(sessionId) {
208213
+ const holds = [];
208214
+ for (const source of this.deps.sources) {
208215
+ for (const id of await source.listHolders(sessionId)) holds.push({ kind: source.kind, id });
208216
+ }
208217
+ if (!sessionId.startsWith("remote-")) {
208218
+ if (!await this.deps.storage.agentSessions.getById(sessionId)) return;
208219
+ await this.deps.storage.sessionRetentionHolds.replace(sessionId, holds);
208220
+ return;
208221
+ }
208222
+ const remote = await this.resolveRemote(sessionId);
208223
+ if (!remote) return;
208224
+ await this.push(remote, holds);
208225
+ }
208226
+ async push(remote, holds) {
208227
+ const proxy = this.deps.proxy ?? proxyToRemoteAuto;
208228
+ const result = await proxy(
208229
+ remote.remoteServerId,
208230
+ "PUT",
208231
+ `/api/path/retention-holds/${remote.remoteSessionId}`,
208232
+ { holds },
208233
+ { reverseConnectManager: this.deps.reverseConnectManager, timeoutMs: TIMEOUT_MS }
208234
+ );
208235
+ if (result.status === 404) return;
208236
+ if (!result.ok) {
208237
+ throw new Error(
208238
+ result.status === 0 ? "The session's machine is not connected" : `Worker responded ${result.status}`
208239
+ );
208240
+ }
208241
+ }
208242
+ async resolveRemote(sessionId) {
208243
+ const live = this.deps.remoteSessionMap.get(sessionId);
208244
+ if (live) return live;
208245
+ const mapping = await this.deps.storage.remoteSessionMappings.getByLocal(sessionId);
208246
+ return mapping ? { remoteServerId: mapping.remote_server_id, remoteSessionId: mapping.remote_session_id } : null;
208247
+ }
208248
+ };
208249
+ function scheduleHoldSource(storage2) {
208250
+ return {
208251
+ kind: "schedule",
208252
+ listHolders: (sessionId) => storage2.scheduledTasks.listIdsBySourceSession(sessionId)
208253
+ };
208254
+ }
208255
+
207889
208256
  // src/agent-session-manager.ts
207890
208257
  import { spawn as spawn3 } from "child_process";
207891
208258
  import { randomUUID } from "crypto";
@@ -208609,7 +208976,7 @@ function getAllProviders() {
208609
208976
  }
208610
208977
 
208611
208978
  // src/utils/cross-remote-token.ts
208612
- import { createHmac as createHmac2, randomBytes as randomBytes2, timingSafeEqual as timingSafeEqual2 } from "crypto";
208979
+ import { createHmac as createHmac2, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual2 } from "crypto";
208613
208980
  var CROSS_REMOTE_SECRET_SETTING = "cross_remote_token_secret";
208614
208981
  var CROSS_REMOTE_TOKEN_TTL_MS = 7 * 864e5;
208615
208982
  var sign2 = (secret, body) => createHmac2("sha256", secret).update(body).digest("base64url");
@@ -208681,7 +209048,7 @@ function verifyCrossRemoteTokenDetailed(secret, token, nowMs) {
208681
209048
  async function getCrossRemoteSecret(storage2) {
208682
209049
  return storage2.settings.getOrCreate(
208683
209050
  CROSS_REMOTE_SECRET_SETTING,
208684
- () => randomBytes2(32).toString("hex")
209051
+ () => randomBytes3(32).toString("hex")
208685
209052
  );
208686
209053
  }
208687
209054
 
@@ -214074,7 +214441,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
214074
214441
  );
214075
214442
  return Object.fromEntries(normalizedHeaders.entries());
214076
214443
  }
214077
- var VERSION3 = true ? "4.0.15" : "0.0.0-test";
214444
+ var VERSION4 = true ? "4.0.15" : "0.0.0-test";
214078
214445
  var getOriginalFetch = () => globalThis.fetch;
214079
214446
  var getFromApi = async ({
214080
214447
  url: url2,
@@ -214089,7 +214456,7 @@ var getFromApi = async ({
214089
214456
  method: "GET",
214090
214457
  headers: withUserAgentSuffix(
214091
214458
  headers,
214092
- `ai-sdk/provider-utils/${VERSION3}`,
214459
+ `ai-sdk/provider-utils/${VERSION4}`,
214093
214460
  getRuntimeEnvironmentUserAgent()
214094
214461
  ),
214095
214462
  signal: abortSignal
@@ -215637,7 +216004,7 @@ var postToApi = async ({
215637
216004
  method: "POST",
215638
216005
  headers: withUserAgentSuffix(
215639
216006
  headers,
215640
- `ai-sdk/provider-utils/${VERSION3}`,
216007
+ `ai-sdk/provider-utils/${VERSION4}`,
215641
216008
  getRuntimeEnvironmentUserAgent()
215642
216009
  ),
215643
216010
  body: body.content,
@@ -217073,7 +217440,7 @@ async function getVercelRequestId() {
217073
217440
  var _a94;
217074
217441
  return (_a94 = (0, import_oidc.getContext)().headers) == null ? void 0 : _a94["x-vercel-id"];
217075
217442
  }
217076
- var VERSION4 = true ? "3.0.55" : "0.0.0-test";
217443
+ var VERSION5 = true ? "3.0.55" : "0.0.0-test";
217077
217444
  var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
217078
217445
  function createGatewayProvider(options = {}) {
217079
217446
  var _a94, _b93;
@@ -217092,7 +217459,7 @@ function createGatewayProvider(options = {}) {
217092
217459
  [GATEWAY_AUTH_METHOD_HEADER]: auth2.authMethod,
217093
217460
  ...options.headers
217094
217461
  },
217095
- `ai-sdk/gateway/${VERSION4}`
217462
+ `ai-sdk/gateway/${VERSION5}`
217096
217463
  );
217097
217464
  } catch (error48) {
217098
217465
  throw GatewayAuthenticationError.createContextualError({
@@ -217839,7 +218206,7 @@ function detectMediaType({
217839
218206
  }
217840
218207
  return void 0;
217841
218208
  }
217842
- var VERSION5 = true ? "6.0.99" : "0.0.0-test";
218209
+ var VERSION6 = true ? "6.0.99" : "0.0.0-test";
217843
218210
  var download = async ({
217844
218211
  url: url2,
217845
218212
  maxBytes,
@@ -217851,7 +218218,7 @@ var download = async ({
217851
218218
  const response = await fetch(urlText, {
217852
218219
  headers: withUserAgentSuffix(
217853
218220
  {},
217854
- `ai-sdk/${VERSION5}`,
218221
+ `ai-sdk/${VERSION6}`,
217855
218222
  getRuntimeEnvironmentUserAgent()
217856
218223
  ),
217857
218224
  signal: abortSignal
@@ -220524,7 +220891,7 @@ async function generateText({
220524
220891
  const callSettings = prepareCallSettings(settings);
220525
220892
  const headersWithUserAgent = withUserAgentSuffix(
220526
220893
  headers != null ? headers : {},
220527
- `ai/${VERSION5}`
220894
+ `ai/${VERSION6}`
220528
220895
  );
220529
220896
  const baseTelemetryAttributes = getBaseTelemetryAttributes({
220530
220897
  model,
@@ -225367,7 +225734,7 @@ var DeepSeekChatLanguageModel = class {
225367
225734
  };
225368
225735
  }
225369
225736
  };
225370
- var VERSION6 = true ? "2.0.20" : "0.0.0-test";
225737
+ var VERSION7 = true ? "2.0.20" : "0.0.0-test";
225371
225738
  function createDeepSeek(options = {}) {
225372
225739
  var _a26;
225373
225740
  const baseURL = withoutTrailingSlash(
@@ -225382,7 +225749,7 @@ function createDeepSeek(options = {}) {
225382
225749
  })}`,
225383
225750
  ...options.headers
225384
225751
  },
225385
- `ai-sdk/deepseek/${VERSION6}`
225752
+ `ai-sdk/deepseek/${VERSION7}`
225386
225753
  );
225387
225754
  const createLanguageModel = (modelId) => {
225388
225755
  return new DeepSeekChatLanguageModel(modelId, {
@@ -226025,7 +226392,7 @@ function withUserAgentSuffix2(headers, ...userAgentSuffixParts) {
226025
226392
  );
226026
226393
  return Object.fromEntries(normalizedHeaders.entries());
226027
226394
  }
226028
- var VERSION7 = true ? "4.0.1" : "0.0.0-test";
226395
+ var VERSION8 = true ? "4.0.1" : "0.0.0-test";
226029
226396
  function loadApiKey2({
226030
226397
  apiKey,
226031
226398
  environmentVariableName,
@@ -227415,7 +227782,7 @@ var postToApi2 = async ({
227415
227782
  method: "POST",
227416
227783
  headers: withUserAgentSuffix2(
227417
227784
  headers,
227418
- `ai-sdk/provider-utils/${VERSION7}`,
227785
+ `ai-sdk/provider-utils/${VERSION8}`,
227419
227786
  getRuntimeEnvironmentUserAgent2()
227420
227787
  ),
227421
227788
  body: body.content,
@@ -230302,8 +230669,9 @@ async function appendRemoteGrantContext(storage2, sessionId, userId, content) {
230302
230669
  return appendContextBlock(content, await buildRemoteGrantContext(storage2, sessionId, userId));
230303
230670
  }
230304
230671
 
230305
- // src/utils/session-title.ts
230672
+ // src/utils/conversation-title.ts
230306
230673
  var TITLE_MAX_CHARS = 60;
230674
+ var VSCHEDULE_BLOCK_RE = /<vschedule(?:\s[^>]*)?>[\s\S]*?<\/vschedule>/g;
230307
230675
  var AI_TIMEOUT_MS = 15e3;
230308
230676
  var MAX_INPUT_CHARS = 2e3;
230309
230677
  var SYSTEM_PROMPT = "You write very short, descriptive titles for chat conversations. Reply with the title only \u2014 no quotes, no trailing punctuation, no markdown, no prefixes like 'Title:'. Use the same language as the user's message. Keep it under 8 words and 50 characters.";
@@ -230320,7 +230688,7 @@ async function isChatModelConfigured(storage2, userId) {
230320
230688
  }
230321
230689
  function extractUserText(content) {
230322
230690
  const text2 = typeof content === "string" ? content : content.filter((p2) => p2.type === "text").map((p2) => p2.text).join(" ");
230323
- return stripRemoteGrantContext(text2);
230691
+ return stripRemoteGrantContext(text2.replace(VSCHEDULE_BLOCK_RE, ""));
230324
230692
  }
230325
230693
  function snippetTitle(text2) {
230326
230694
  const trimmed = text2.trim();
@@ -230338,14 +230706,14 @@ function sanitizeTitle(raw) {
230338
230706
  }
230339
230707
  return t;
230340
230708
  }
230341
- async function generateSessionTitleWithModel(model, userMessage, options = {}) {
230709
+ async function generateConversationTitleWithModel(model, userMessage, options = {}) {
230342
230710
  if (userMessage.trim().length === 0) return null;
230343
230711
  const telemetry = options.userId ? {
230344
230712
  isEnabled: true,
230345
- functionId: "session-title",
230713
+ functionId: "conversation-title",
230346
230714
  metadata: {
230347
230715
  userId: options.userId,
230348
- tags: ["vibedeckx", "session-title"]
230716
+ tags: ["vibedeckx", "conversation-title"]
230349
230717
  }
230350
230718
  } : void 0;
230351
230719
  try {
@@ -230360,13 +230728,13 @@ async function generateSessionTitleWithModel(model, userMessage, options = {}) {
230360
230728
  const sanitized = sanitizeTitle(text2);
230361
230729
  return sanitized.length > 0 ? sanitized : null;
230362
230730
  } catch (error48) {
230363
- console.warn("[SessionTitle] AI generation failed:", error48.message);
230731
+ console.warn("[ConversationTitle] AI generation failed:", error48.message);
230364
230732
  return null;
230365
230733
  }
230366
230734
  }
230367
- async function generateSessionTitle(storage2, userMessage, userId) {
230735
+ async function generateConversationTitle(storage2, userMessage, userId) {
230368
230736
  if (!await isChatModelConfigured(storage2, userId)) return null;
230369
- return generateSessionTitleWithModel(await resolveFastChatModel(storage2, userId), userMessage, { userId });
230737
+ return generateConversationTitleWithModel(await resolveFastChatModel(storage2, userId), userMessage, { userId });
230370
230738
  }
230371
230739
 
230372
230740
  // src/utils/review-snapshot.ts
@@ -234214,7 +234582,7 @@ var AgentSessionManager = class {
234214
234582
  const fallback = snippetTitle(userText);
234215
234583
  let title = null;
234216
234584
  try {
234217
- title = await generateSessionTitle(this.storage, userText, userId);
234585
+ title = await generateConversationTitle(this.storage, userText, userId);
234218
234586
  } catch (error48) {
234219
234587
  console.warn(`[AgentSession] Title generation threw for ${session.id}:`, error48);
234220
234588
  }
@@ -234263,91 +234631,6 @@ var AgentSessionManager = class {
234263
234631
  // src/chat-session-manager.ts
234264
234632
  import { randomUUID as randomUUID3 } from "crypto";
234265
234633
 
234266
- // src/trace-context.ts
234267
- import { AsyncLocalStorage } from "node:async_hooks";
234268
- import { randomBytes as randomBytes3 } from "node:crypto";
234269
- var VERSION8 = "00";
234270
- var INVALID_VERSION = "ff";
234271
- var ZERO_TRACE_ID = "0".repeat(32);
234272
- var ZERO_SPAN_ID = "0".repeat(16);
234273
- var HEX_2 = /^[0-9a-f]{2}$/;
234274
- var HEX_16 = /^[0-9a-f]{16}$/;
234275
- var HEX_32 = /^[0-9a-f]{32}$/;
234276
- function parseTraceparent(value) {
234277
- const raw = Array.isArray(value) ? value[0] : value;
234278
- if (typeof raw !== "string") return null;
234279
- const parts = raw.split("-");
234280
- if (parts.length < 4) return null;
234281
- const [version2, traceId, spanId, flags] = parts;
234282
- if (!HEX_2.test(version2) || version2 === INVALID_VERSION) return null;
234283
- if (version2 === VERSION8 && parts.length !== 4) return null;
234284
- if (!HEX_32.test(traceId) || traceId === ZERO_TRACE_ID) return null;
234285
- if (!HEX_16.test(spanId) || spanId === ZERO_SPAN_ID) return null;
234286
- if (!HEX_2.test(flags)) return null;
234287
- return { traceId, spanId, flags };
234288
- }
234289
- function formatTraceparent(ctx) {
234290
- return `${VERSION8}-${ctx.traceId}-${ctx.spanId}-${ctx.sampled ? "01" : "00"}`;
234291
- }
234292
- function newTraceId() {
234293
- return randomBytes3(16).toString("hex");
234294
- }
234295
- function newSpanId() {
234296
- return randomBytes3(8).toString("hex");
234297
- }
234298
- function newTraceContext(incoming) {
234299
- const parsed = parseTraceparent(incoming);
234300
- if (parsed) {
234301
- return {
234302
- traceId: parsed.traceId,
234303
- spanId: newSpanId(),
234304
- parentSpanId: parsed.spanId,
234305
- sampled: (parseInt(parsed.flags, 16) & 1) === 1,
234306
- continued: true
234307
- };
234308
- }
234309
- return {
234310
- traceId: newTraceId(),
234311
- spanId: newSpanId(),
234312
- sampled: true,
234313
- continued: false
234314
- };
234315
- }
234316
- var storage = new AsyncLocalStorage();
234317
- function runWithTraceContext(ctx, fn) {
234318
- return storage.run(ctx, fn);
234319
- }
234320
- function getTraceContext() {
234321
- return storage.getStore();
234322
- }
234323
- function outboundTraceparent() {
234324
- const ctx = storage.getStore();
234325
- return ctx ? formatTraceparent(ctx) : void 0;
234326
- }
234327
-
234328
- // src/utils/remote-proxy.ts
234329
- function proxyStatus(result, fallback = 502) {
234330
- return result.status > 0 ? result.status : fallback;
234331
- }
234332
- async function proxyToRemoteAuto(remoteServerId, method, apiPath, body, options) {
234333
- const rcm = options?.reverseConnectManager;
234334
- if (rcm && rcm.isConnected(remoteServerId)) {
234335
- const traceparent = outboundTraceparent();
234336
- const headers = {
234337
- ...traceparent ? { traceparent } : {},
234338
- ...options?.headers
234339
- };
234340
- return rcm.sendHttpRequest(remoteServerId, method, apiPath, body, options?.timeoutMs, headers);
234341
- }
234342
- return {
234343
- ok: false,
234344
- status: 0,
234345
- data: { error: "Remote server is not connected" },
234346
- errorCode: "network_error",
234347
- requestId: options?.requestId
234348
- };
234349
- }
234350
-
234351
234634
  // ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/wrapper.mjs
234352
234635
  var import_stream3 = __toESM(require_stream(), 1);
234353
234636
  var import_receiver = __toESM(require_receiver(), 1);
@@ -235869,7 +236152,7 @@ async function generateAndPushRemoteSessionTitle(deps, localSessionId, userText,
235869
236152
  if (await deps.storage.remoteSessionMappings.isTitleResolved(localSessionId)) return;
235870
236153
  let aiTitle = null;
235871
236154
  try {
235872
- aiTitle = await generateSessionTitle(deps.storage, userText, userId);
236155
+ aiTitle = await generateConversationTitle(deps.storage, userText, userId);
235873
236156
  } catch (error48) {
235874
236157
  console.warn(
235875
236158
  `[SessionTitle] AI title generation threw for ${localSessionId}:`,
@@ -239437,6 +239720,38 @@ async function createProjectChatTools(options) {
239437
239720
  };
239438
239721
  })
239439
239722
  },
239723
+ list_starred_sessions: {
239724
+ description: "List sessions the user starred in this project, local and remote, newest star first. Use this instead of list_agent_sessions when looking for starred sessions: old starred sessions may be missing from the recent-activity list.",
239725
+ inputSchema: emptySchema,
239726
+ execute: readInScope(async () => {
239727
+ const [localRows, remoteRows] = await Promise.all([
239728
+ storage2.agentSessions.listFavoritedActivityByProject(projectId, LIST_LIMIT + 1, "project-chat"),
239729
+ remoteSessions ? storage2.searchCache.listRemoteSessionFavoritesByProject(projectId, LIST_LIMIT + 1, "project-chat") : Promise.resolve([])
239730
+ ]);
239731
+ const byId = /* @__PURE__ */ new Map();
239732
+ for (const row of [...localRows, ...remoteRows]) {
239733
+ if (row.favoritedAt === null || row.projectId !== projectId || !isToolSelectorId(row.id)) continue;
239734
+ if (!byId.has(row.id)) byId.set(row.id, row);
239735
+ }
239736
+ const merged = [...byId.values()].sort((left, right) => (right.favoritedAt ?? 0) - (left.favoritedAt ?? 0) || left.id.localeCompare(right.id));
239737
+ const rows = merged.slice(0, LIST_LIMIT);
239738
+ await touchAll("agent_session", rows.map((row) => row.id));
239739
+ return {
239740
+ items: rows.map((row) => ({
239741
+ id: preview(row.id, ID_CHAR_LIMIT),
239742
+ projectId: preview(row.projectId, ID_CHAR_LIMIT),
239743
+ branch: nullablePreview(row.branch, LIST_BRANCH_CHAR_LIMIT),
239744
+ title: nullablePreview(row.title, LIST_NAME_CHAR_LIMIT),
239745
+ status: preview(row.status, ENUM_CHAR_LIMIT),
239746
+ target: preview(row.target, LIST_TARGET_CHAR_LIMIT),
239747
+ agentType: nullablePreview(row.agentType, ENUM_CHAR_LIMIT),
239748
+ model: nullablePreview(row.model, LIST_MODEL_CHAR_LIMIT),
239749
+ starredAt: new Date(row.favoritedAt ?? 0).toISOString()
239750
+ })),
239751
+ truncated: merged.length > LIST_LIMIT
239752
+ };
239753
+ })
239754
+ },
239440
239755
  get_agent_session: {
239441
239756
  description: "Return status and a server-bounded recent transcript for one project agent session.",
239442
239757
  inputSchema: external_exports.object({ sessionId: external_exports.string().min(1).max(MAX_TOOL_SELECTOR_ID) }).strict(),
@@ -239587,7 +239902,9 @@ var PROJECT_CHAT_SYSTEM_PROMPT = [
239587
239902
  "Project Chat does not belong to a branch or workspace; never assume one workspace is the whole project.",
239588
239903
  "You may create a task, update a task, create an agent session in an explicitly selected existing workspace, select a requested workspace, send an agent instruction, and run an existing schedule now.",
239589
239904
  "Use supplied tools for factual context and report mutations only from successful tool results.",
239590
- "There is no delete capability, no worktree creation, no schedule configuration, no agent-session stop, and no Git capability."
239905
+ "There is no delete capability, no worktree creation, no schedule configuration, no agent-session stop, and no Git capability.",
239906
+ "When you mention a task, workspace, agent session, schedule, or schedule run whose id a tool returned, write it as a Markdown link so the user can click to open it: [label](#ref:<type>:<id>), where <type> is task, workspace, agent_session, schedule, or schedule_run and <id> is the exact id from the tool result (for example [Fix login bug](#ref:agent_session:abc123)).",
239907
+ "Never invent ids or link items no tool returned."
239591
239908
  ].join(" ");
239592
239909
  var PROJECT_CHAT_TOOL_CALL_LIMIT = 8;
239593
239910
  var PROJECT_CHAT_TOOL_RESULT_BYTE_LIMIT = 64 * 1024;
@@ -239790,6 +240107,7 @@ var ProjectChatManager = class {
239790
240107
  constructor(storage2, runner, options = {}) {
239791
240108
  this.storage = storage2;
239792
240109
  this.runner = runner ?? new DefaultProjectChatModelRunner(storage2);
240110
+ this.titleGenerator = options.titleGenerator ?? generateConversationTitle;
239793
240111
  this.drainTimeoutMs = options.drainTimeoutMs ?? 2e3;
239794
240112
  this.idleEvictionMs = options.idleEvictionMs ?? 3e4;
239795
240113
  this.terminalRetryDelayMs = options.terminalRetryDelayMs ?? 100;
@@ -239830,6 +240148,7 @@ var ProjectChatManager = class {
239830
240148
  outstandingOperations = /* @__PURE__ */ new Set();
239831
240149
  operationReconciliationFlights = /* @__PURE__ */ new Map();
239832
240150
  runner;
240151
+ titleGenerator;
239833
240152
  drainTimeoutMs;
239834
240153
  idleEvictionMs;
239835
240154
  terminalRetryDelayMs;
@@ -239994,12 +240313,69 @@ var ProjectChatManager = class {
239994
240313
  content: trimmed
239995
240314
  });
239996
240315
  this.assertLifecycle(threadId, generation, true);
240316
+ if (live.thread.title === null) {
240317
+ try {
240318
+ const fallbackTitle = snippetTitle(trimmed);
240319
+ const written = await this.storage.projectChatThreads.setTitleIfMissing(
240320
+ threadId,
240321
+ live.thread.project_id,
240322
+ userId,
240323
+ fallbackTitle
240324
+ );
240325
+ const updated = written ?? await this.storage.projectChatThreads.getById(
240326
+ threadId,
240327
+ live.thread.project_id,
240328
+ userId
240329
+ );
240330
+ if (updated && updated.title !== live.thread.title) {
240331
+ live.thread = updated;
240332
+ this.broadcast(live, { JsonPatch: [{
240333
+ op: "replace",
240334
+ path: "/thread",
240335
+ value: { type: "THREAD", content: updated }
240336
+ }] });
240337
+ }
240338
+ if (updated?.title === fallbackTitle) {
240339
+ void this.generateTitle(threadId, userId, trimmed, fallbackTitle);
240340
+ }
240341
+ } catch (error48) {
240342
+ console.warn("[ProjectChat] Could not set conversation title:", error48);
240343
+ }
240344
+ }
239997
240345
  if (accepted.acceptedMessage) this.publishMessage(live, accepted.acceptedMessage);
239998
240346
  if (this.shuttingDown) return;
239999
240347
  live.queue.push(accepted);
240000
240348
  this.broadcastStatus(live);
240001
240349
  this.pump(live);
240002
240350
  }
240351
+ /** Best-effort AI refinement of the first-message fallback title. */
240352
+ async generateTitle(threadId, userId, firstMessage, fallbackTitle) {
240353
+ try {
240354
+ const generated = await this.titleGenerator(this.storage, firstMessage, userId);
240355
+ if (!generated || generated === fallbackTitle) return;
240356
+ const owned = await this.findAuthorized(threadId, userId);
240357
+ if (!owned) return;
240358
+ const updated = await this.storage.projectChatThreads.replaceTitleIfCurrent(
240359
+ threadId,
240360
+ owned.project_id,
240361
+ userId,
240362
+ fallbackTitle,
240363
+ generated
240364
+ );
240365
+ if (!updated) return;
240366
+ const live = this.liveThreads.get(threadId);
240367
+ if (live && live.thread.project_id === updated.project_id && live.thread.user_id === updated.user_id) {
240368
+ live.thread = updated;
240369
+ this.broadcast(live, { JsonPatch: [{
240370
+ op: "replace",
240371
+ path: "/thread",
240372
+ value: { type: "THREAD", content: updated }
240373
+ }] });
240374
+ }
240375
+ } catch (error48) {
240376
+ console.warn("[ProjectChat] Could not generate conversation title:", error48);
240377
+ }
240378
+ }
240003
240379
  /** Authorization requires storage I/O, so stopping is deliberately async. */
240004
240380
  async stopGeneration(threadId, userId, expectedActiveTurnId) {
240005
240381
  const thread = await this.findAuthorized(threadId, userId);
@@ -241577,6 +241953,8 @@ var CHECK_OUTPUT_TAIL = 600;
241577
241953
  var ABNORMAL_END_RECHECK_MS = 1500;
241578
241954
  var STOP_NOTE = {
241579
241955
  itemDone: "Loop: this iteration finished its item; the session was closed. The next item runs in a fresh session.",
241956
+ finished: "Loop finished: this session reported nothing left to process (Status: done). The loop is complete; no further sessions will start.",
241957
+ paused: "Loop paused after this item; the session was closed. The loop is waiting for you \u2014 resume or end it from the loop card.",
241580
241958
  cancelled: "Loop ended; the session was closed.",
241581
241959
  timeCap: "Loop: time cap reached; the session was stopped.",
241582
241960
  resumed: "Loop resumed in a fresh session; this one was closed."
@@ -241878,7 +242256,10 @@ ${TASK_STATUS_INSTRUCTIONS}`;
241878
242256
  this.host.emitRunUpdated(done);
241879
242257
  if (outbox) this.host.milestoneCreated();
241880
242258
  const keepSession = settlement.next === "gate" && (status === "blocked" || status === null || checkFailure !== null);
241881
- if (!keepSession) await this.stop(run2.source_session_id, STOP_NOTE.itemDone);
242259
+ if (!keepSession) {
242260
+ const note = settlement.next === "finished" ? STOP_NOTE.finished : settlement.next === "gate" ? STOP_NOTE.paused : STOP_NOTE.itemDone;
242261
+ await this.stop(run2.source_session_id, note);
242262
+ }
241882
242263
  if (!insertRun) return;
241883
242264
  const next = await this.storage.workflowRuns.getById(insertRun.id);
241884
242265
  this.host.track(next);
@@ -242133,6 +242514,7 @@ var WorkflowError = class extends Error {
242133
242514
  code;
242134
242515
  };
242135
242516
  var LOOP_DEADLINE_CHECK_MS = 6e4;
242517
+ var HANDED_OVER = "handed over to the user";
242136
242518
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "cancelled", "failed"]);
242137
242519
  var DELIVERY_UNKNOWN_PREFIX = "\u6295\u9012\u7ED3\u679C\u672A\u77E5";
242138
242520
  var REREVIEW_DELIVERY_UNKNOWN = `${DELIVERY_UNKNOWN_PREFIX}\uFF1A\u590D\u5BA1\u4EFB\u52A1\u53EF\u80FD\u5DF2\u9001\u8FBE reviewer\u3002\u82E5\u5176\u5B8C\u6210\uFF0C\u7ED3\u679C\u4F1A\u81EA\u52A8\u5F52\u5C5E\uFF1B\u5426\u5219\u8BF7\u7ED3\u675F\u672C\u6B21 review \u540E\u91CD\u65B0\u53D1\u8D77\u3002`;
@@ -242383,6 +242765,13 @@ var WorkflowEngine = class {
242383
242765
  eventBus;
242384
242766
  /** sessionId → participation in an active run (rebuilt on boot). */
242385
242767
  participants = /* @__PURE__ */ new Map();
242768
+ /**
242769
+ * Source session → the loop run whose automatic next hop (relaying the
242770
+ * feedback, or starting the re-review) waits for the source to go idle. The
242771
+ * completion event fires before the source's status leaves `running`, so a
242772
+ * first attempt can land too early.
242773
+ */
242774
+ autoWaiting = /* @__PURE__ */ new Map();
242386
242775
  /** runId → prompt inputs captured at prepare time (see PendingActivation). */
242387
242776
  pendingActivations = /* @__PURE__ */ new Map();
242388
242777
  /** runId → armed preparation-timeout timer. */
@@ -242396,6 +242785,10 @@ var WorkflowEngine = class {
242396
242785
  void this.handleTaskCompleted(event).catch(
242397
242786
  (err) => console.error("[WorkflowEngine] handleTaskCompleted failed:", err)
242398
242787
  );
242788
+ } else if (event.type === "session:status" && event.status !== "running" && this.autoWaiting.has(event.sessionId)) {
242789
+ const { runId, action } = this.autoWaiting.get(event.sessionId);
242790
+ this.autoWaiting.delete(event.sessionId);
242791
+ void (action === "relay" ? this.autoRelay(runId, true) : this.autoRereview(runId, true));
242399
242792
  } else if (event.type === "session:status" && event.status !== "running" && this.participants.get(event.sessionId)?.role === "task") {
242400
242793
  void this.repeat.onSessionIdle(event.sessionId).catch(
242401
242794
  (err) => console.error("[WorkflowEngine] repeat-loop idle check failed:", err)
@@ -242467,6 +242860,8 @@ var WorkflowEngine = class {
242467
242860
  error: "\u53D1\u9001\u72B6\u6001\u672A\u77E5\uFF1A\u670D\u52A1\u5728\u53D1\u9001\u53CD\u9988\u671F\u95F4\u91CD\u542F\u3002\u8BF7\u68C0\u67E5 source session \u662F\u5426\u5DF2\u6536\u5230\u53CD\u9988\uFF0C\u518D\u51B3\u5B9A\u91CD\u53D1\u6216\u7ED3\u675F\u3002"
242468
242861
  });
242469
242862
  run2.status = "waiting_feedback";
242863
+ } else if (run2.status === "waiting_feedback" && run2.loop_id) {
242864
+ await this.notifyFeedbackGate(run2);
242470
242865
  } else if (run2.status === "waiting_reviewer") {
242471
242866
  await this.storage.workflowRuns.update(run2.id, {
242472
242867
  error: "\u670D\u52A1\u91CD\u542F\uFF0C\u53EF\u80FD\u9519\u8FC7 reviewer \u5B8C\u6210\u4E8B\u4EF6\u3002\u82E5 reviewer \u5DF2\u5B8C\u6210\uFF0C\u8BF7\u6253\u5F00\u5176\u7A97\u53E3\u67E5\u770B\uFF0C\u6216\u7ED3\u675F\u672C\u6B21 review\u3002"
@@ -242534,7 +242929,7 @@ var WorkflowEngine = class {
242534
242929
  const outcome = turnEnd.outcome ?? "completed";
242535
242930
  const completed = outcome === "completed" || outcome === "completed_with_pending_tasks";
242536
242931
  if (completed && findTurnOpeningUserEntryIndex(entries, turnEndIndex) === entryIndex) {
242537
- await this.claimStep(step, entries, turnEndIndex);
242932
+ await this.claimStep(step, entries, turnEndIndex, { live: false });
242538
242933
  settled.add(run2.id);
242539
242934
  continue;
242540
242935
  }
@@ -242694,16 +243089,126 @@ var WorkflowEngine = class {
242694
243089
  review_target: null,
242695
243090
  loop_id: run2.loop_id,
242696
243091
  round: run2.round + 1,
242697
- max_rounds: run2.max_rounds
243092
+ max_rounds: run2.max_rounds,
243093
+ loop_manual: run2.loop_manual
242698
243094
  };
242699
243095
  }
242700
- /** The insert is conditional (see claimStepAndTransition); read it back to know. */
242701
- async announceNextRoundGate(nextRunId) {
243096
+ /**
243097
+ * The insert is conditional (see claimStepAndTransition); read it back to know.
243098
+ * With `auto`, the next round starts by itself (see `autoRereview`).
243099
+ */
243100
+ async announceNextRoundGate(nextRunId, auto = false) {
242702
243101
  if (!nextRunId) return;
242703
243102
  const gate = await this.storage.workflowRuns.getById(nextRunId);
242704
243103
  if (!gate) return;
242705
243104
  this.trackParticipants(gate);
242706
243105
  this.emitRunUpdated(gate);
243106
+ if (auto) await this.autoRereview(gate.id);
243107
+ }
243108
+ // ---------- unattended review loops ----------
243109
+ //
243110
+ // Inside the round cap a loop runs by itself while the reviewer says a clear
243111
+ // `needs-changes`: its feedback goes to the source as-is, and the source's
243112
+ // fix is re-reviewed. The cap is the hand-over point — the LAST round's
243113
+ // feedback waits for the user, and so does every round past it. Anything
243114
+ // else stops at the gate it reached, which is exactly the manual path:
243115
+ // another verdict, a drift note, a claim found by restart reconciliation, a
243116
+ // failed attempt, or the user stepping in (`loop_manual`).
243117
+ /**
243118
+ * Whether a round's feedback goes out without the user. `live` = claimed
243119
+ * from a completion event, not by restart reconciliation.
243120
+ */
243121
+ shouldAutoRelay(run2, verdict, driftNote, live) {
243122
+ return live && run2.loop_id !== null && !run2.loop_manual && verdict === "needs-changes" && driftNote === null && run2.max_rounds !== null && run2.round < run2.max_rounds;
243123
+ }
243124
+ /**
243125
+ * Park an automatic hop until `sessionId` goes idle. False when it already
243126
+ * is — the status event may have gone out before the entry was written — and
243127
+ * the caller should retry now.
243128
+ */
243129
+ async waitForIdle(sessionId, runId, action) {
243130
+ this.autoWaiting.set(sessionId, { runId, action });
243131
+ const session = await this.storage.agentSessions.getById(sessionId);
243132
+ if (session?.status === "running") return true;
243133
+ if (this.autoWaiting.get(sessionId)?.runId !== runId) return true;
243134
+ this.autoWaiting.delete(sessionId);
243135
+ return false;
243136
+ }
243137
+ async isStillAutomatic(runId) {
243138
+ return !(await this.storage.workflowRuns.getById(runId))?.loop_manual;
243139
+ }
243140
+ /** `approveFeedback` with nobody to report to: a failure stays at the gate, and rings. */
243141
+ async autoRelay(runId, retried = false) {
243142
+ const run2 = await this.storage.workflowRuns.getById(runId);
243143
+ if (run2?.status !== "waiting_feedback") return;
243144
+ if (!run2.loop_manual) {
243145
+ try {
243146
+ await this.approveFeedback(runId, void 0, { auto: true });
243147
+ return;
243148
+ } catch (err) {
243149
+ const back = await this.storage.workflowRuns.getById(runId);
243150
+ if (back?.status !== "waiting_feedback") return;
243151
+ if (!retried && err instanceof WorkflowError && err.code === "session-busy") {
243152
+ if (await this.waitForIdle(back.source_session_id, runId, "relay")) return;
243153
+ return this.autoRelay(runId, true);
243154
+ }
243155
+ if (!back.error && !back.loop_manual) {
243156
+ const reason = err instanceof Error ? err.message : String(err);
243157
+ const noted = await this.storage.workflowRuns.update(runId, { error: `\u81EA\u52A8\u8F6C\u53D1\u672A\u80FD\u53D1\u51FA\uFF1A${reason}` });
243158
+ if (noted) this.emitRunUpdated(noted);
243159
+ }
243160
+ }
243161
+ }
243162
+ await this.notifyFeedbackGate(run2);
243163
+ }
243164
+ /**
243165
+ * The review_ready milestone an automatic relay skipped, for a gate that
243166
+ * ends up waiting for the user after all. Same deterministic id as the one
243167
+ * the claim would have written, so it rings at most once.
243168
+ */
243169
+ async notifyFeedbackGate(run2) {
243170
+ const step = (await this.storage.workflowRunSteps.listByRun(run2.id)).filter((st) => st.role === "reviewer" && st.status === "claimed" && st.turn_end_index !== null).at(-1);
243171
+ if (!step) return;
243172
+ const { inserted } = await this.storage.notificationOutbox.insert(
243173
+ this.reviewReadyOutbox(run2, step.session_id, step.turn_end_index)
243174
+ );
243175
+ if (inserted) this.onMilestoneCreated?.();
243176
+ }
243177
+ /**
243178
+ * `approveRereview` with nobody to report to. Only a clear `needs-changes`
243179
+ * within the cap qualifies — the caller checks the verdict; failures land on
243180
+ * the gate and ring.
243181
+ */
243182
+ async autoRereview(gateId, retried = false) {
243183
+ const gate = await this.storage.workflowRuns.getById(gateId);
243184
+ if (gate?.status !== "waiting_rereview" || gate.loop_manual) return;
243185
+ if (gate.max_rounds === null || gate.round > gate.max_rounds) return;
243186
+ try {
243187
+ await this.approveRereview(gateId, { auto: true });
243188
+ } catch (err) {
243189
+ const back = await this.storage.workflowRuns.getById(gateId);
243190
+ if (back?.status !== "waiting_rereview") return;
243191
+ if (!retried && err instanceof WorkflowError && err.code === "source-running") {
243192
+ if (await this.waitForIdle(back.source_session_id, gateId, "rereview")) return;
243193
+ return this.autoRereview(gateId, true);
243194
+ }
243195
+ if (back.loop_manual) return;
243196
+ if (!back.error) {
243197
+ const reason = err instanceof Error ? err.message : String(err);
243198
+ const noted = await this.storage.workflowRuns.update(gateId, { error: `\u81EA\u52A8\u590D\u5BA1\u672A\u80FD\u53D1\u8D77\uFF1A${reason}` });
243199
+ if (noted) this.emitRunUpdated(noted);
243200
+ }
243201
+ const { inserted } = await this.storage.notificationOutbox.insert({
243202
+ id: workflowFailedId(gateId, "auto-rereview"),
243203
+ kind: "workflow_failed",
243204
+ project_id: back.project_id,
243205
+ branch: back.branch,
243206
+ session_id: back.source_session_id,
243207
+ workflow_run_id: back.id,
243208
+ created_at: Date.now()
243209
+ });
243210
+ if (inserted) this.onMilestoneCreated?.();
243211
+ }
242707
243212
  }
242708
243213
  /** The reviewer the loop continues with: the previous round's. */
242709
243214
  async loopReviewerSessionId(gate) {
@@ -242787,11 +243292,13 @@ var WorkflowEngine = class {
242787
243292
  project: { id: project.id, path: project.path },
242788
243293
  entries,
242789
243294
  turnEndIndex,
242790
- target
243295
+ target,
243296
+ stillAutomatic: opts.auto ? () => this.isStillAutomatic(gate.id) : void 0
242791
243297
  });
242792
243298
  if (outcome.kind === "mode-switch-failed" || outcome.kind === "no_side_effect") {
242793
243299
  const busy = outcome.kind === "no_side_effect" && outcome.busy;
242794
- const reason = outcome.kind === "mode-switch-failed" ? "\u65E0\u6CD5\u5C06 reviewer \u6062\u590D\u4E3A\u53EA\u8BFB plan \u6A21\u5F0F\uFF0C\u590D\u5BA1\u672A\u53D1\u51FA\u3002\u53EF\u91CD\u8BD5\uFF0C\u6216\u7ED3\u675F\u5FAA\u73AF\u3002" : busy ? "reviewer \u6B63\u5728\u56DE\u590D\u4E2D\uFF0C\u590D\u5BA1\u672A\u53D1\u51FA\u3002\u8BF7\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u91CD\u8BD5\u3002" : "\u590D\u5BA1\u4EFB\u52A1\u672A\u9001\u8FBE reviewer\uFF08\u5176 session \u53EF\u80FD\u672A\u8FD0\u884C\uFF09\u3002\u53EF\u91CD\u8BD5\uFF0C\u6216\u7ED3\u675F\u5FAA\u73AF\u3002";
243300
+ const handedOver = outcome.kind === "no_side_effect" && outcome.reason === HANDED_OVER;
243301
+ const reason = handedOver ? "\u4F60\u5DF2\u4ECB\u5165\u8FD9\u4E2A\u5FAA\u73AF\uFF0C\u590D\u5BA1\u6539\u4E3A\u7531\u4F60\u786E\u8BA4\u3002" : outcome.kind === "mode-switch-failed" ? "\u65E0\u6CD5\u5C06 reviewer \u6062\u590D\u4E3A\u53EA\u8BFB plan \u6A21\u5F0F\uFF0C\u590D\u5BA1\u672A\u53D1\u51FA\u3002\u53EF\u91CD\u8BD5\uFF0C\u6216\u7ED3\u675F\u5FAA\u73AF\u3002" : busy ? "reviewer \u6B63\u5728\u56DE\u590D\u4E2D\uFF0C\u590D\u5BA1\u672A\u53D1\u51FA\u3002\u8BF7\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u91CD\u8BD5\u3002" : "\u590D\u5BA1\u4EFB\u52A1\u672A\u9001\u8FBE reviewer\uFF08\u5176 session \u53EF\u80FD\u672A\u8FD0\u884C\uFF09\u3002\u53EF\u91CD\u8BD5\uFF0C\u6216\u7ED3\u675F\u5FAA\u73AF\u3002";
242795
243302
  const back = await this.storage.workflowRuns.transition(gate.id, "waiting_reviewer", "waiting_rereview", {
242796
243303
  reviewer_session_id: null,
242797
243304
  error: reason
@@ -242878,7 +243385,8 @@ var WorkflowEngine = class {
242878
243385
  sessionId: opts.reviewerSession.id,
242879
243386
  payload: prompt,
242880
243387
  projectPath: opts.project.path,
242881
- turn: REVIEWER_TURN
243388
+ turn: REVIEWER_TURN,
243389
+ stillAutomatic: opts.stillAutomatic
242882
243390
  });
242883
243391
  }
242884
243392
  // ---------- dispatch identity (Phase 2 prerequisite design §2) ----------
@@ -242936,6 +243444,10 @@ var WorkflowEngine = class {
242936
243444
  if (!reused) await steps.abandon(step.id, "target session busy");
242937
243445
  return { kind: "no_side_effect", busy: true, reason: "target session is mid-turn" };
242938
243446
  }
243447
+ if (opts.stillAutomatic && !await opts.stillAutomatic()) {
243448
+ if (!reused) await steps.abandon(step.id, "handed over to the user");
243449
+ return { kind: "no_side_effect", busy: false, reason: HANDED_OVER };
243450
+ }
242939
243451
  let runtimeAccepted = false;
242940
243452
  try {
242941
243453
  const result = await deliverInstruction({
@@ -243436,7 +243948,7 @@ var WorkflowEngine = class {
243436
243948
  * completion event and restart reconciliation, so a late claim goes through
243437
243949
  * exactly the transaction a live one does.
243438
243950
  */
243439
- async claimStep(step, entries, boundary) {
243951
+ async claimStep(step, entries, boundary, opts = { live: true }) {
243440
243952
  const output = extractLastAssistantInTurn(entries, boundary);
243441
243953
  if (step.kind === "task_prompt") {
243442
243954
  await this.repeat.onTaskTurnCompleted(step, entries, boundary, output);
@@ -243445,6 +243957,7 @@ var WorkflowEngine = class {
243445
243957
  if (step.kind === "feedback") {
243446
243958
  const run3 = await this.storage.workflowRuns.getById(step.run_id);
243447
243959
  const nextRun = run3 ? this.nextRoundGate(run3, boundary) : void 0;
243960
+ const auto = opts.live && run3?.verdict === "needs-changes" && !run3.loop_manual;
243448
243961
  if (run3 && (run3.status === "sending_feedback" || run3.status === "waiting_feedback")) {
243449
243962
  const completed = await this.storage.workflowRuns.claimStepAndTransition({
243450
243963
  stepId: step.id,
@@ -243459,7 +243972,7 @@ var WorkflowEngine = class {
243459
243972
  this.untrackRun(done);
243460
243973
  this.emitRunUpdated(done);
243461
243974
  }
243462
- await this.announceNextRoundGate(nextRun?.id);
243975
+ await this.announceNextRoundGate(nextRun?.id, auto);
243463
243976
  return;
243464
243977
  }
243465
243978
  }
@@ -243469,13 +243982,15 @@ var WorkflowEngine = class {
243469
243982
  outputSnapshot: output,
243470
243983
  nextRun
243471
243984
  });
243472
- if (claimed) await this.announceNextRoundGate(nextRun?.id);
243985
+ if (claimed) await this.announceNextRoundGate(nextRun?.id, auto);
243473
243986
  return;
243474
243987
  }
243475
243988
  const run2 = await this.storage.workflowRuns.getById(step.run_id);
243476
243989
  if (!run2 || run2.status !== "waiting_reviewer") return;
243477
243990
  const feedback = output ?? "(reviewer \u6CA1\u6709\u8F93\u51FA\u53EF\u7528\u7684\u53CD\u9988\u6587\u672C)";
243478
243991
  const driftNote = await this.computeDriftNote(run2);
243992
+ const verdict = parseVerdict(output);
243993
+ const relay = this.shouldAutoRelay(run2, verdict, driftNote, opts.live);
243479
243994
  const ok = await this.storage.workflowRuns.claimStepAndTransition({
243480
243995
  stepId: step.id,
243481
243996
  turnEndIndex: boundary,
@@ -243487,14 +244002,15 @@ var WorkflowEngine = class {
243487
244002
  // `error: null` also clears a "delivery outcome unknown" note: the
243488
244003
  // completion just answered it.
243489
244004
  // Parsed by exact match; null = unrecognised = the human decides.
243490
- patch: { feedback_snapshot: feedback, error: driftNote, verdict: parseVerdict(output) },
243491
- outbox: this.reviewReadyOutbox(run2, step.session_id, boundary)
244005
+ patch: { feedback_snapshot: feedback, error: driftNote, verdict },
244006
+ outbox: relay ? void 0 : this.reviewReadyOutbox(run2, step.session_id, boundary)
243492
244007
  }
243493
244008
  });
243494
244009
  if (!ok) return;
243495
- this.onMilestoneCreated?.();
244010
+ if (!relay) this.onMilestoneCreated?.();
243496
244011
  const updated = await this.storage.workflowRuns.getById(run2.id);
243497
244012
  if (updated) this.emitRunUpdated(updated);
244013
+ if (relay) await this.autoRelay(run2.id);
243498
244014
  }
243499
244015
  async computeDriftNote(run2) {
243500
244016
  try {
@@ -243552,7 +244068,7 @@ var WorkflowEngine = class {
243552
244068
  const updated = await this.storage.workflowRuns.getById(run2.id);
243553
244069
  if (updated) this.emitRunUpdated(updated);
243554
244070
  }
243555
- async approveFeedback(runId, editedPayload) {
244071
+ async approveFeedback(runId, editedPayload, opts = {}) {
243556
244072
  const run2 = await this.storage.workflowRuns.getById(runId);
243557
244073
  if (!run2 || run2.status !== "waiting_feedback") {
243558
244074
  throw new WorkflowError("bad-state", "run \u4E0D\u5728\u7B49\u5F85\u53CD\u9988\u786E\u8BA4\u7684\u72B6\u6001");
@@ -243578,10 +244094,11 @@ var WorkflowEngine = class {
243578
244094
  sessionId: run2.source_session_id,
243579
244095
  payload,
243580
244096
  projectPath: project?.path ?? void 0,
243581
- turn: FEEDBACK_TURN
244097
+ turn: FEEDBACK_TURN,
244098
+ stillAutomatic: opts.auto ? () => this.isStillAutomatic(runId) : void 0
243582
244099
  });
243583
244100
  if (outcome.kind !== "accepted") {
243584
- const error48 = outcome.kind === "unknown" ? `${DELIVERY_UNKNOWN_PREFIX}\uFF1A\u53CD\u9988\u53EF\u80FD\u5DF2\u9001\u8FBE source session\u3002\u8BF7\u68C0\u67E5\u5176\u7A97\u53E3\uFF1B\u518D\u6B21\u786E\u8BA4\u4F1A\u6309\u539F\u6587\u91CD\u8BD5\uFF08\u5DF2\u9001\u8FBE\u5219\u4E0D\u4F1A\u91CD\u590D\u53D1\u9001\uFF09\u3002` : outcome.busy ? "source session \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u53D1\u9001\u53CD\u9988\u3002" : "\u53D1\u9001\u5931\u8D25\uFF1A\u76EE\u6807 session \u53EF\u80FD\u672A\u8FD0\u884C\u3002\u8BF7\u5728\u5176\u7A97\u53E3\u4E2D\u5524\u9192\u540E\u91CD\u8BD5\uFF0C\u6216\u7ED3\u675F\u672C\u6B21 review\u3002";
244101
+ const error48 = outcome.kind === "unknown" ? `${DELIVERY_UNKNOWN_PREFIX}\uFF1A\u53CD\u9988\u53EF\u80FD\u5DF2\u9001\u8FBE source session\u3002\u8BF7\u68C0\u67E5\u5176\u7A97\u53E3\uFF1B\u518D\u6B21\u786E\u8BA4\u4F1A\u6309\u539F\u6587\u91CD\u8BD5\uFF08\u5DF2\u9001\u8FBE\u5219\u4E0D\u4F1A\u91CD\u590D\u53D1\u9001\uFF09\u3002` : outcome.reason === HANDED_OVER ? null : outcome.busy ? "source session \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u53D1\u9001\u53CD\u9988\u3002" : "\u53D1\u9001\u5931\u8D25\uFF1A\u76EE\u6807 session \u53EF\u80FD\u672A\u8FD0\u884C\u3002\u8BF7\u5728\u5176\u7A97\u53E3\u4E2D\u5524\u9192\u540E\u91CD\u8BD5\uFF0C\u6216\u7ED3\u675F\u672C\u6B21 review\u3002";
243585
244102
  await this.storage.workflowRuns.transition(runId, "sending_feedback", "waiting_feedback", { error: error48 });
243586
244103
  const rolled = await this.storage.workflowRuns.getById(runId);
243587
244104
  if (rolled) this.emitRunUpdated(rolled);
@@ -243694,6 +244211,7 @@ var WorkflowEngine = class {
243694
244211
  */
243695
244212
  async handleExternalUserMessage(sessionId) {
243696
244213
  const p2 = this.participants.get(sessionId);
244214
+ await this.handOverLoop(sessionId, p2);
243697
244215
  if (!p2) return;
243698
244216
  if (p2.role === "reviewer") {
243699
244217
  try {
@@ -243712,6 +244230,39 @@ var WorkflowEngine = class {
243712
244230
  return;
243713
244231
  }
243714
244232
  }
244233
+ /**
244234
+ * Stepping into a review loop — to either side — hands the rest of it to the
244235
+ * user: every later gate waits for them. Besides the run holding the
244236
+ * session, that covers a source busy with feedback already sent: its round
244237
+ * has completed and holds nothing, but its open feedback step still names
244238
+ * the loop, and the next gate copies the flag from it. The reviewer is held
244239
+ * by nothing between rounds either: its last loop run finds the loop, and
244240
+ * both that run (the next gate copies from it) and the loop's active run, if
244241
+ * a gate already exists, are marked. Never throws (see
244242
+ * handleExternalUserMessage).
244243
+ */
244244
+ async handOverLoop(sessionId, p2) {
244245
+ try {
244246
+ const runIds = new Set(p2 ? [p2.runId] : []);
244247
+ for (const step of await this.storage.workflowRunSteps.getOpenBySession(sessionId)) {
244248
+ if (step.kind === "feedback") runIds.add(step.run_id);
244249
+ }
244250
+ const reviewed = await this.storage.workflowRuns.getLatestLoopRunByReviewer(sessionId);
244251
+ if (reviewed?.loop_id) {
244252
+ runIds.add(reviewed.id);
244253
+ const active = await this.storage.workflowRuns.getActiveInLoop(reviewed.loop_id);
244254
+ if (active) runIds.add(active.id);
244255
+ }
244256
+ for (const runId of runIds) {
244257
+ const run2 = await this.storage.workflowRuns.getById(runId);
244258
+ if (run2?.kind !== "review" || !run2.loop_id || run2.loop_manual) continue;
244259
+ const updated = await this.storage.workflowRuns.update(run2.id, { loop_manual: 1 });
244260
+ if (updated && !(p2?.role === "reviewer" && p2.runId === run2.id)) this.emitRunUpdated(updated);
244261
+ }
244262
+ } catch (err) {
244263
+ console.error(`[WorkflowEngine] handleExternalUserMessage: failed handing loop over for ${sessionId}; swallowed`, err);
244264
+ }
244265
+ }
243715
244266
  emitRunUpdated(run2) {
243716
244267
  this.eventBus?.emit({ type: "workflow:run-updated", projectId: run2.project_id, branch: run2.branch, run: run2 });
243717
244268
  const streams = /* @__PURE__ */ new Set([run2.source_session_id, run2.reviewer_session_id]);
@@ -244251,6 +244802,10 @@ var ReverseConnectManager = class {
244251
244802
  this.cleanupConnection(remoteServerId, conn);
244252
244803
  this.connections.delete(remoteServerId);
244253
244804
  }
244805
+ /** Ids of every worker currently connected. */
244806
+ connectedServerIds() {
244807
+ return [...this.connections.keys()];
244808
+ }
244254
244809
  isConnected(remoteServerId) {
244255
244810
  const conn = this.connections.get(this.resolveId(remoteServerId));
244256
244811
  return conn !== void 0 && conn.ws.readyState === 1;
@@ -245821,6 +246376,28 @@ var SessionRetentionSweeper = class {
245821
246376
  }
245822
246377
  };
245823
246378
 
246379
+ // src/cross-remote-retention.ts
246380
+ var CROSS_REMOTE_AUDIT_RETENTION_ENV = "VIBEDECKX_CROSS_REMOTE_AUDIT_RETENTION_DAYS";
246381
+ var DEFAULT_AUDIT_RETENTION_DAYS = 90;
246382
+ var AUDIT_PRUNE_BATCH = 1e3;
246383
+ function auditRetentionDays(raw = process.env[CROSS_REMOTE_AUDIT_RETENTION_ENV]) {
246384
+ return parseRetentionDays(raw) ?? DEFAULT_AUDIT_RETENTION_DAYS;
246385
+ }
246386
+ async function pruneCrossRemoteAudit(storage2, opts = {}) {
246387
+ const now3 = opts.now ?? Date.now();
246388
+ const cutoff = new Date(now3 - (opts.auditDays ?? auditRetentionDays()) * MS_PER_DAY);
246389
+ const batchSize = opts.batchSize ?? AUDIT_PRUNE_BATCH;
246390
+ let removed = 0;
246391
+ for (; ; ) {
246392
+ const deleted = await storage2.crossRemoteAudit.pruneBefore(cutoff, batchSize);
246393
+ removed += deleted;
246394
+ if (deleted < batchSize) break;
246395
+ await new Promise((resolve3) => setImmediate(resolve3));
246396
+ }
246397
+ if (removed > 0) console.log(`[CrossRemoteRetention] pruned ${removed} audit row(s)`);
246398
+ return removed;
246399
+ }
246400
+
245824
246401
  // src/agent-session-lifecycle.ts
245825
246402
  import { createHash as createHash6, randomUUID as randomUUID12 } from "node:crypto";
245826
246403
  function lifecycleHttpStatus(kind) {
@@ -247242,6 +247819,12 @@ var RemoteSessionReconciler = class {
247242
247819
  // src/remote-liveness-reconcile.ts
247243
247820
  var RemoteLivenessTracker = class {
247244
247821
  byProject = /* @__PURE__ */ new Map();
247822
+ /**
247823
+ * Newest read id whose answer was acted on, per project — baseline or not. A
247824
+ * reconcile of a project the hub never served must still be ordered against
247825
+ * an overlapping one, without inventing a death baseline for it.
247826
+ */
247827
+ answeredSeq = /* @__PURE__ */ new Map();
247245
247828
  seqCounter = 0;
247246
247829
  eventBus;
247247
247830
  constructor(eventBus = null) {
@@ -247263,6 +247846,7 @@ var RemoteLivenessTracker = class {
247263
247846
  const previous = this.byProject.get(projectId);
247264
247847
  if (previous && seq < previous.seq) return [];
247265
247848
  this.byProject.set(projectId, { remoteServerId, remotePath, sessions, seq });
247849
+ this.markAnswered(projectId, seq);
247266
247850
  if (!previous) return [];
247267
247851
  const live = new Set(sessions.map((session) => session.remoteSessionId));
247268
247852
  const retired = previous.sessions.filter((session) => !live.has(session.remoteSessionId));
@@ -247294,6 +247878,45 @@ var RemoteLivenessTracker = class {
247294
247878
  }).filter((session) => session !== null);
247295
247879
  return this.accept(projectId, remoteServerId, remotePath, sessions, seq);
247296
247880
  }
247881
+ /**
247882
+ * True when an answer claimed with `seq` has been overtaken by a newer
247883
+ * accepted one for this project — it must decide nothing, deaths or status.
247884
+ */
247885
+ isOvertaken(projectId, seq) {
247886
+ const current = Math.max(this.byProject.get(projectId)?.seq ?? 0, this.answeredSeq.get(projectId) ?? 0);
247887
+ return seq < current;
247888
+ }
247889
+ /** Record that the answer read with `seq` was acted on, without touching the baseline. */
247890
+ markAnswered(projectId, seq) {
247891
+ if (seq > (this.answeredSeq.get(projectId) ?? 0)) this.answeredSeq.set(projectId, seq);
247892
+ }
247893
+ /** Whether a browser read has given this project a death baseline. */
247894
+ hasBaseline(projectId) {
247895
+ return this.byProject.has(projectId);
247896
+ }
247897
+ /**
247898
+ * Announce each session's current status as the worker reports it.
247899
+ *
247900
+ * The worker sends status changes only on each session's own stream, so a
247901
+ * turn that ended while the hub held no stream for it (a hub restart, a
247902
+ * tunnel outage) leaves every browser showing "running" forever. An
247903
+ * authoritative alive answer carries the status, so re-announcing it repairs
247904
+ * those rows. Deliberately independent of stream restoration: once status
247905
+ * moves to a project-level channel this stays as the post-reconnect repair,
247906
+ * while per-session streams only carry conversation content.
247907
+ */
247908
+ announceStatuses(projectId, sessions) {
247909
+ for (const session of sessions) {
247910
+ if (!session.status) continue;
247911
+ this.eventBus?.emit({
247912
+ type: "session:status",
247913
+ projectId,
247914
+ branch: session.branch,
247915
+ sessionId: session.localSessionId,
247916
+ status: session.status
247917
+ });
247918
+ }
247919
+ }
247297
247920
  entriesFor(remoteServerId) {
247298
247921
  const rows = [];
247299
247922
  for (const [projectId, tracked] of this.byProject) {
@@ -247312,40 +247935,58 @@ function parseAliveAnswer(data) {
247312
247935
  if (!entry || typeof entry !== "object") continue;
247313
247936
  const row = entry;
247314
247937
  if (typeof row.id !== "string") continue;
247315
- rows.push({ id: row.id, branch: typeof row.branch === "string" ? row.branch : null });
247938
+ const status = row.status === "running" || row.status === "stopped" || row.status === "error" ? row.status : null;
247939
+ rows.push({ id: row.id, branch: typeof row.branch === "string" ? row.branch : null, status });
247316
247940
  }
247317
247941
  return rows;
247318
247942
  }
247319
247943
  async function reconcileRemoteLiveness(remoteServerId, deps) {
247320
247944
  const dead = [];
247321
- const tracked = deps.tracker.entriesFor(remoteServerId);
247945
+ const answers = [];
247946
+ const targets = /* @__PURE__ */ new Map();
247947
+ for (const entry of deps.tracker.entriesFor(remoteServerId)) targets.set(entry.projectId, entry.remotePath);
247948
+ if (deps.listProjects) {
247949
+ try {
247950
+ for (const project of await deps.listProjects(remoteServerId)) {
247951
+ if (!targets.has(project.projectId)) targets.set(project.projectId, project.remotePath);
247952
+ }
247953
+ } catch (error48) {
247954
+ console.warn(`[RemoteLiveness] project listing failed for ${remoteServerId}:`, error48);
247955
+ }
247956
+ }
247322
247957
  let projects = 0;
247323
- for (const entry of tracked) {
247324
- if (entry.sessions.length === 0) continue;
247958
+ for (const [projectId, remotePath] of targets) {
247325
247959
  const seq = deps.tracker.nextReadSeq();
247326
247960
  let result;
247327
247961
  try {
247328
- result = await deps.proxy(remoteServerId, entry.remotePath);
247962
+ result = await deps.proxy(remoteServerId, remotePath);
247329
247963
  } catch (error48) {
247330
- console.warn(`[RemoteLiveness] alive query failed for ${entry.projectId}:`, error48);
247964
+ console.warn(`[RemoteLiveness] alive query failed for ${projectId}:`, error48);
247331
247965
  continue;
247332
247966
  }
247333
247967
  if (!result.ok) continue;
247334
247968
  const rows = parseAliveAnswer(result.data);
247335
247969
  if (!rows) continue;
247970
+ if (deps.tracker.isOvertaken(projectId, seq)) continue;
247336
247971
  projects += 1;
247337
- dead.push(...deps.tracker.acceptRemoteIds(
247338
- entry.projectId,
247339
- remoteServerId,
247340
- entry.remotePath,
247341
- rows,
247342
- seq
247343
- ));
247972
+ const sessions = rows.map((row) => ({
247973
+ localSessionId: `remote-${remoteServerId}-${projectId}-${row.id}`,
247974
+ remoteSessionId: row.id,
247975
+ branch: row.branch,
247976
+ status: row.status
247977
+ }));
247978
+ if (deps.tracker.hasBaseline(projectId)) {
247979
+ dead.push(...deps.tracker.acceptRemoteIds(projectId, remoteServerId, remotePath, rows, seq));
247980
+ } else {
247981
+ deps.tracker.markAnswered(projectId, seq);
247982
+ }
247983
+ deps.tracker.announceStatuses(projectId, sessions);
247984
+ answers.push({ projectId, sessions });
247344
247985
  }
247345
247986
  if (dead.length > 0) {
247346
247987
  console.log(`[RemoteLiveness] ${remoteServerId}: ${dead.length} session(s) lost their process while unobserved`);
247347
247988
  }
247348
- return { projects, dead };
247989
+ return { projects, dead, answers };
247349
247990
  }
247350
247991
 
247351
247992
  // src/logger.ts
@@ -248158,12 +248799,8 @@ var sharedServices = async (fastify2, opts) => {
248158
248799
  await agentSessionManager.restoreSessionsFromDb();
248159
248800
  const remoteExecutorMap = /* @__PURE__ */ new Map();
248160
248801
  const remoteSessionMap = /* @__PURE__ */ new Map();
248161
- for (const row of await opts.storage.remoteSessionMappings.getAll()) {
248162
- const remote = await opts.storage.projectRemotes.getByProjectAndServer(
248163
- row.project_id,
248164
- row.remote_server_id
248165
- );
248166
- if (!remote) {
248802
+ for (const row of await opts.storage.remoteSessionMappings.getAllWithLinkState()) {
248803
+ if (!row.linked) {
248167
248804
  console.warn(`[SharedServices] Skipping remote_session_mappings row ${row.local_session_id}: project_remotes(${row.project_id}, ${row.remote_server_id}) not found`);
248168
248805
  continue;
248169
248806
  }
@@ -248448,6 +249085,25 @@ var sharedServices = async (fastify2, opts) => {
248448
249085
  fastify2.decorate("reverseConnectManager", reverseConnectManager);
248449
249086
  fastify2.decorate("browserManager", browserManager);
248450
249087
  fastify2.decorate("scheduler", scheduler);
249088
+ const retentionHolds = new RetentionHoldSync({
249089
+ storage: opts.storage,
249090
+ reverseConnectManager,
249091
+ remoteSessionMap,
249092
+ sources: [scheduleHoldSource(opts.storage)]
249093
+ });
249094
+ fastify2.decorate("retentionHolds", retentionHolds);
249095
+ const releaseStaleHolds = (remoteServerId) => {
249096
+ void retentionHolds.releaseStale(remoteServerId).then((failed) => {
249097
+ if (failed > 0) console.warn(`[RetentionHolds] ${failed} session(s) on ${remoteServerId} not re-synced`);
249098
+ });
249099
+ };
249100
+ reverseConnectManager.setStatusChangeHandler((remoteServerId, status) => {
249101
+ if (status === "online") releaseStaleHolds(remoteServerId);
249102
+ });
249103
+ const retentionHoldTimer = setInterval(() => {
249104
+ for (const remoteServerId of reverseConnectManager.connectedServerIds()) releaseStaleHolds(remoteServerId);
249105
+ }, 60 * 60 * 1e3);
249106
+ retentionHoldTimer.unref();
248451
249107
  agentSessionManager.setEventBus(eventBus);
248452
249108
  void recoverPendingRemoteAgentSessions({
248453
249109
  remoteSessionMap,
@@ -248520,6 +249176,9 @@ var sharedServices = async (fastify2, opts) => {
248520
249176
  storage: opts.storage,
248521
249177
  deleteIfExpired: (sessionId, cutoff) => agentSessionManager.deleteDormantSessionIfExpired(sessionId, cutoff),
248522
249178
  maintenance: async () => {
249179
+ await pruneCrossRemoteAudit(opts.storage).catch((error48) => {
249180
+ console.error("[CrossRemoteRetention] prune failed:", error48);
249181
+ });
248523
249182
  await agentSessionLifecycle.maintain();
248524
249183
  await opts.storage.remoteSessionCreationIntents.discardStaleLifecycleIntents({
248525
249184
  cutoff: Date.now() - 7 * 24 * 60 * 6e4,
@@ -248565,6 +249224,7 @@ var sharedServices = async (fastify2, opts) => {
248565
249224
  memoryStatsReporter.start();
248566
249225
  fastify2.addHook("onClose", async () => {
248567
249226
  memoryStatsReporter.close();
249227
+ clearInterval(retentionHoldTimer);
248568
249228
  await sessionRetention.close();
248569
249229
  await remoteSessionReconciler.close();
248570
249230
  scheduler.shutdown();
@@ -251097,6 +251757,52 @@ import { readFileSync as readFileSync4 } from "fs";
251097
251757
  import { execFileSync as execFileSync6 } from "child_process";
251098
251758
 
251099
251759
  // src/utils/diff-parser.ts
251760
+ var C_ESCAPES = {
251761
+ a: 7,
251762
+ b: 8,
251763
+ f: 12,
251764
+ n: 10,
251765
+ r: 13,
251766
+ t: 9,
251767
+ v: 11,
251768
+ "\\": 92,
251769
+ '"': 34
251770
+ };
251771
+ function unquoteGitPath(token) {
251772
+ if (token.length < 2 || !token.startsWith('"') || !token.endsWith('"')) return token;
251773
+ const body = token.slice(1, -1);
251774
+ const bytes = [];
251775
+ for (let i = 0; i < body.length; i++) {
251776
+ if (body[i] !== "\\") {
251777
+ bytes.push(...Buffer.from(body[i], "utf-8"));
251778
+ continue;
251779
+ }
251780
+ const next = body[i + 1];
251781
+ if (next === void 0) {
251782
+ bytes.push(92);
251783
+ continue;
251784
+ }
251785
+ if (next >= "0" && next <= "7") {
251786
+ const octal = body.slice(i + 1, i + 4).match(/^[0-7]{1,3}/)[0];
251787
+ bytes.push(parseInt(octal, 8) & 255);
251788
+ i += octal.length;
251789
+ continue;
251790
+ }
251791
+ const simple = C_ESCAPES[next];
251792
+ if (simple !== void 0) {
251793
+ bytes.push(simple);
251794
+ i += 1;
251795
+ continue;
251796
+ }
251797
+ bytes.push(92, ...Buffer.from(next, "utf-8"));
251798
+ i += 1;
251799
+ }
251800
+ return Buffer.from(bytes).toString("utf-8");
251801
+ }
251802
+ var DIFF_HEADER = /^("a\/(?:[^"\\]|\\.)*"|a\/.+?) ("b\/(?:[^"\\]|\\.)*"|b\/.+)$/;
251803
+ function headerPath(token) {
251804
+ return unquoteGitPath(token).slice(2);
251805
+ }
251100
251806
  function parseDiffOutput(diffOutput) {
251101
251807
  const files = [];
251102
251808
  if (!diffOutput.trim()) {
@@ -251106,10 +251812,10 @@ function parseDiffOutput(diffOutput) {
251106
251812
  for (const fileDiff of fileDiffs) {
251107
251813
  const lines = fileDiff.split("\n");
251108
251814
  if (lines.length === 0) continue;
251109
- const headerMatch = lines[0].match(/a\/(.+?) b\/(.+)/);
251815
+ const headerMatch = lines[0].match(DIFF_HEADER);
251110
251816
  if (!headerMatch) continue;
251111
- const oldPath = headerMatch[1];
251112
- const newPath = headerMatch[2];
251817
+ const oldPath = headerPath(headerMatch[1]);
251818
+ const newPath = headerPath(headerMatch[2]);
251113
251819
  let status = "modified";
251114
251820
  let finalPath = newPath;
251115
251821
  let finalOldPath;
@@ -251356,21 +252062,21 @@ async function getUntrackedFiles(cwd) {
251356
252062
  try {
251357
252063
  const { execSync: execSync2 } = await import("child_process");
251358
252064
  untrackedOutput = execSync2(
251359
- "git ls-files --others --exclude-standard",
252065
+ "git ls-files --others --exclude-standard -z",
251360
252066
  { cwd, encoding: "utf-8", maxBuffer: 10 * 1024 * 1024 }
251361
- ).trim();
252067
+ );
251362
252068
  } catch {
251363
252069
  return [];
251364
252070
  }
251365
- if (!untrackedOutput) return [];
251366
- const untrackedPaths = untrackedOutput.split("\n");
252071
+ const untrackedPaths = untrackedOutput.split("\0").filter(Boolean);
252072
+ if (untrackedPaths.length === 0) return [];
251367
252073
  const files = [];
251368
252074
  for (const filePath of untrackedPaths) {
251369
252075
  try {
251370
252076
  const fullPath = path12.join(cwd, filePath);
251371
252077
  const buffer = readFileSync4(fullPath);
251372
252078
  if (buffer.includes(0)) {
251373
- files.push({ path: filePath, status: "added", hunks: [] });
252079
+ files.push({ path: filePath, status: "added", hunks: [], binary: true });
251374
252080
  continue;
251375
252081
  }
251376
252082
  const content = buffer.toString("utf-8");
@@ -251623,7 +252329,7 @@ async function resolveArtifactReadTargets(deps, opts) {
251623
252329
  const sessionServerId = deps.remoteSessionMap.get(sessionId)?.remoteServerId;
251624
252330
  if (sessionServerId) candidates.push(sessionServerId);
251625
252331
  candidates.push(
251626
- ...await deps.storage.crossRemoteAudit.listSessionTargets(sessionId, opts.userId)
252332
+ ...await deps.storage.sessionRemoteTouches.list(sessionId, opts.userId)
251627
252333
  );
251628
252334
  }
251629
252335
  const targets = [];
@@ -255330,6 +256036,21 @@ var sessionInventoryRoutes = async (fastify2) => {
255330
256036
  return reply.code(200).send({ sessionIds, complete: true });
255331
256037
  }
255332
256038
  );
256039
+ fastify2.get("/api/path/retention-holds", async (_req, reply) => {
256040
+ return reply.code(200).send({ sessionIds: await fastify2.storage.sessionRetentionHolds.listSessionIds() });
256041
+ });
256042
+ fastify2.put("/api/path/retention-holds/:sessionId", async (req, reply) => {
256043
+ const raw = req.body?.holds;
256044
+ const validPart = (v2) => typeof v2 === "string" && v2.length > 0 && v2.length <= 200;
256045
+ if (!Array.isArray(raw) || raw.length > 1e3 || !raw.every((h) => h && typeof h === "object" && validPart(h.kind) && validPart(h.id))) {
256046
+ return reply.code(400).send({ error: "holds must be an array of { kind, id }" });
256047
+ }
256048
+ const session = await fastify2.storage.agentSessions.getById(req.params.sessionId);
256049
+ if (!session) return reply.code(404).send({ error: "Session not found" });
256050
+ const holds = raw.map((h) => ({ kind: h.kind, id: h.id }));
256051
+ await fastify2.storage.sessionRetentionHolds.replace(req.params.sessionId, holds);
256052
+ return reply.code(204).send();
256053
+ });
255333
256054
  };
255334
256055
  var session_inventory_routes_default = sessionInventoryRoutes;
255335
256056
 
@@ -255942,7 +256663,7 @@ var routes16 = async (fastify2) => {
255942
256663
  id: randomUUID21(),
255943
256664
  project_id: projectId,
255944
256665
  user_id: userId,
255945
- title: null,
256666
+ title: body.message ? snippetTitle(body.message) : null,
255946
256667
  create_request_id: createRequestId,
255947
256668
  create_payload_hash: createPayloadHash,
255948
256669
  ...body.message !== void 0 ? { initialTurn: {
@@ -255964,6 +256685,12 @@ var routes16 = async (fastify2) => {
255964
256685
  } catch (error48) {
255965
256686
  req.log.warn({ err: error48, threadId: thread.id }, "Project Chat initial turn will resume later");
255966
256687
  }
256688
+ void fastify2.projectChatManager.generateTitle(
256689
+ thread.id,
256690
+ userId,
256691
+ body.message,
256692
+ thread.title ?? snippetTitle(body.message)
256693
+ );
255967
256694
  }
255968
256695
  return reply.code(201).send({ thread });
255969
256696
  });
@@ -257735,7 +258462,7 @@ var routes22 = async (fastify2) => {
257735
258462
  for (const id of PROVIDER_IDS) masked[id] = maskApiKey(keys[id]);
257736
258463
  return masked;
257737
258464
  }
257738
- function serializeConfig(config2) {
258465
+ function serializeConfig2(config2) {
257739
258466
  return {
257740
258467
  apiKeys: maskApiKeys(config2.apiKeys),
257741
258468
  main: config2.main,
@@ -257759,7 +258486,7 @@ var routes22 = async (fastify2) => {
257759
258486
  const userId = requireSettingsUser(req, reply);
257760
258487
  if (userId === null) return;
257761
258488
  const config2 = await getChatProviderConfig(fastify2.storage, userId);
257762
- return reply.code(200).send(serializeConfig(config2));
258489
+ return reply.code(200).send(serializeConfig2(config2));
257763
258490
  });
257764
258491
  fastify2.put("/api/settings/chat-provider", async (req, reply) => {
257765
258492
  const userId = requireSettingsUser(req, reply);
@@ -257800,7 +258527,7 @@ var routes22 = async (fastify2) => {
257800
258527
  console.log(
257801
258528
  `[Settings] Chat provider updated: main=${updated.main.provider}/${updated.main.model}, fast=${updated.fast.provider}/${updated.fast.model}`
257802
258529
  );
257803
- return reply.code(200).send(serializeConfig(updated));
258530
+ return reply.code(200).send(serializeConfig2(updated));
257804
258531
  });
257805
258532
  fastify2.get("/api/settings/terminal", async (req, reply) => {
257806
258533
  const userId = requireSettingsUser(req, reply);
@@ -257949,8 +258676,452 @@ ${text2}`,
257949
258676
  };
257950
258677
  var translate_routes_default = (0, import_fastify_plugin24.default)(routes23, { name: "translate-routes" });
257951
258678
 
257952
- // src/routes/websocket-routes.ts
258679
+ // src/routes/tts-routes.ts
257953
258680
  var import_fastify_plugin25 = __toESM(require_plugin2(), 1);
258681
+ import { createHash as createHash10 } from "crypto";
258682
+ import { Readable as Readable2 } from "stream";
258683
+
258684
+ // src/tts/types.ts
258685
+ var TtsProviderError = class extends Error {
258686
+ constructor(kind, message) {
258687
+ super(message);
258688
+ this.kind = kind;
258689
+ this.name = "TtsProviderError";
258690
+ }
258691
+ kind;
258692
+ };
258693
+
258694
+ // src/tts/azure.ts
258695
+ var OUTPUT_FORMAT = "audio-24khz-48kbitrate-mono-mp3";
258696
+ var REGION_RE = /^[a-z0-9]+$/;
258697
+ var VOICE_RE = /^[A-Za-z]{2,3}-[A-Za-z0-9]{2,4}-[A-Za-z0-9_:-]+$/;
258698
+ function isHdVoice(voice) {
258699
+ return /:DragonHD/i.test(voice);
258700
+ }
258701
+ function escapeXml(text2) {
258702
+ return text2.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
258703
+ }
258704
+ function voiceLocale(voice) {
258705
+ const [lang, region] = voice.split("-");
258706
+ return lang && region ? `${lang}-${region}` : "en-US";
258707
+ }
258708
+ function buildSsml({ text: text2, voice }) {
258709
+ return `<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="${voiceLocale(voice)}"><voice name="${escapeXml(voice)}">${escapeXml(text2)}</voice></speak>`;
258710
+ }
258711
+ function regionOf(creds) {
258712
+ const region = (creds.region ?? "").trim().toLowerCase();
258713
+ if (!REGION_RE.test(region)) throw new TtsProviderError("bad_request", "Invalid Azure region");
258714
+ return region;
258715
+ }
258716
+ function statusError(status, voice) {
258717
+ if (status === 401 || status === 403) return new TtsProviderError("auth", `Azure rejected the key (HTTP ${status})`);
258718
+ if (status === 429) return new TtsProviderError("quota", "Azure rate limit or quota exceeded");
258719
+ if (status === 400) {
258720
+ const hint = voice && isHdVoice(voice) ? " HD voices are only available in some Azure regions \u2014 check your resource's region, or pick a non-HD voice." : "";
258721
+ return new TtsProviderError("bad_request", `Azure rejected the request (HTTP 400).${hint}`);
258722
+ }
258723
+ return new TtsProviderError("upstream", `Azure returned HTTP ${status}`);
258724
+ }
258725
+ async function azureFetch(url2, init) {
258726
+ try {
258727
+ return await fetch(url2, init);
258728
+ } catch (err) {
258729
+ const name25 = err?.name;
258730
+ if (name25 === "AbortError" || name25 === "TimeoutError") throw err;
258731
+ throw new TtsProviderError("network", `Could not reach Azure: ${err?.message ?? err}`);
258732
+ }
258733
+ }
258734
+ var OMNI_GROUP = "HD Omni (recommended)";
258735
+ var MULTILINGUAL_GROUP = "Multilingual";
258736
+ function mapAzureVoices(rows) {
258737
+ const voices = [];
258738
+ for (const row of rows) {
258739
+ const id = row.ShortName;
258740
+ if (!id) continue;
258741
+ const omni = /:DragonHDOmni/i.test(id);
258742
+ const multilingual = !isHdVoice(id) && row.VoiceType === "Neural" && /Multilingual/i.test(id);
258743
+ if (!omni && !multilingual) continue;
258744
+ voices.push({
258745
+ id,
258746
+ label: `${row.LocalName || row.DisplayName || id} (${row.Locale ?? voiceLocale(id)})`,
258747
+ locale: row.Locale,
258748
+ multilingual: true,
258749
+ group: omni ? OMNI_GROUP : MULTILINGUAL_GROUP
258750
+ });
258751
+ }
258752
+ voices.sort((a, b2) => Number(b2.group === OMNI_GROUP) - Number(a.group === OMNI_GROUP) || a.id.localeCompare(b2.id));
258753
+ return voices;
258754
+ }
258755
+ var azureProvider = {
258756
+ id: "azure",
258757
+ label: "Azure Speech",
258758
+ credentialFields: [
258759
+ { key: "apiKey", label: "API key", secret: true, envKey: "AZURE_SPEECH_KEY" },
258760
+ { key: "region", label: "Region", secret: false, envKey: "AZURE_SPEECH_REGION", placeholder: "southeastasia" }
258761
+ ],
258762
+ defaultVoice: "zh-CN-Xiaoxiao:DragonHDOmniLatestNeural",
258763
+ maxCharsPerRequest: 1500,
258764
+ isValidVoice: (voice) => VOICE_RE.test(voice),
258765
+ async listVoices(creds, { signal, dispatcher }) {
258766
+ const res = await azureFetch(
258767
+ `https://${regionOf(creds)}.tts.speech.microsoft.com/cognitiveservices/voices/list`,
258768
+ { headers: { "Ocp-Apim-Subscription-Key": creds.apiKey ?? "" }, signal, dispatcher }
258769
+ );
258770
+ if (!res.ok) throw statusError(res.status);
258771
+ const rows = await res.json();
258772
+ return mapAzureVoices(Array.isArray(rows) ? rows : []);
258773
+ },
258774
+ async synthesize(creds, { text: text2, voice, signal, dispatcher }) {
258775
+ const res = await azureFetch(
258776
+ `https://${regionOf(creds)}.tts.speech.microsoft.com/cognitiveservices/v1`,
258777
+ {
258778
+ method: "POST",
258779
+ headers: {
258780
+ "Ocp-Apim-Subscription-Key": creds.apiKey ?? "",
258781
+ "Content-Type": "application/ssml+xml",
258782
+ "X-Microsoft-OutputFormat": OUTPUT_FORMAT,
258783
+ "User-Agent": "vibedeckx"
258784
+ },
258785
+ body: buildSsml({ text: text2, voice }),
258786
+ signal,
258787
+ dispatcher
258788
+ }
258789
+ );
258790
+ if (!res.ok || !res.body) {
258791
+ await res.body?.cancel().catch(() => {
258792
+ });
258793
+ throw statusError(res.ok ? 502 : res.status, voice);
258794
+ }
258795
+ return { audio: res.body, contentType: "audio/mpeg" };
258796
+ }
258797
+ };
258798
+
258799
+ // src/tts/providers.ts
258800
+ var TTS_PROVIDERS = {
258801
+ azure: azureProvider
258802
+ };
258803
+ var TTS_PROVIDER_IDS = Object.keys(TTS_PROVIDERS);
258804
+ var DEFAULT_TTS_PROVIDER = "azure";
258805
+ function isTtsProviderId(value) {
258806
+ return typeof value === "string" && Object.prototype.hasOwnProperty.call(TTS_PROVIDERS, value);
258807
+ }
258808
+
258809
+ // src/tts/config.ts
258810
+ var TTS_SETTING_KEY = "tts";
258811
+ var TTS_RATE_MIN = 0.5;
258812
+ var TTS_RATE_MAX = 2;
258813
+ function clampRate(value, fallback = 1) {
258814
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
258815
+ return Math.min(TTS_RATE_MAX, Math.max(TTS_RATE_MIN, Math.round(value * 100) / 100));
258816
+ }
258817
+ function normalizeVoice(provider, voice) {
258818
+ const def = TTS_PROVIDERS[provider];
258819
+ return typeof voice === "string" && def.isValidVoice(voice) ? voice : def.defaultVoice;
258820
+ }
258821
+ function normalizeCredentials(raw) {
258822
+ const out = {};
258823
+ if (!raw || typeof raw !== "object") return out;
258824
+ for (const id of TTS_PROVIDER_IDS) {
258825
+ const entry = raw[id];
258826
+ if (!entry || typeof entry !== "object") continue;
258827
+ const creds = {};
258828
+ for (const field of TTS_PROVIDERS[id].credentialFields) {
258829
+ const value = entry[field.key];
258830
+ if (typeof value === "string") creds[field.key] = value;
258831
+ }
258832
+ out[id] = creds;
258833
+ }
258834
+ return out;
258835
+ }
258836
+ function defaultTtsConfig() {
258837
+ return {
258838
+ provider: DEFAULT_TTS_PROVIDER,
258839
+ credentials: {},
258840
+ voice: TTS_PROVIDERS[DEFAULT_TTS_PROVIDER].defaultVoice,
258841
+ rate: 1
258842
+ };
258843
+ }
258844
+ function parseTtsConfig(raw) {
258845
+ if (!raw) return defaultTtsConfig();
258846
+ try {
258847
+ const parsed = JSON.parse(raw);
258848
+ if (!parsed || typeof parsed !== "object") return defaultTtsConfig();
258849
+ const provider = isTtsProviderId(parsed.provider) ? parsed.provider : DEFAULT_TTS_PROVIDER;
258850
+ return {
258851
+ provider,
258852
+ credentials: normalizeCredentials(parsed.credentials),
258853
+ voice: normalizeVoice(provider, parsed.voice),
258854
+ rate: clampRate(parsed.rate)
258855
+ };
258856
+ } catch {
258857
+ return defaultTtsConfig();
258858
+ }
258859
+ }
258860
+ async function getTtsConfig(storage2, userId) {
258861
+ return parseTtsConfig(await storage2.userSettings.get(userId, TTS_SETTING_KEY));
258862
+ }
258863
+ function resolveCredentials(config2, provider = config2.provider) {
258864
+ const stored = config2.credentials[provider] ?? {};
258865
+ const creds = {};
258866
+ for (const field of TTS_PROVIDERS[provider].credentialFields) {
258867
+ const value = stored[field.key]?.trim() || (field.envKey ? process.env[field.envKey]?.trim() : "") || "";
258868
+ creds[field.key] = value;
258869
+ }
258870
+ return creds;
258871
+ }
258872
+ function isTtsConfigured(config2, provider = config2.provider) {
258873
+ const creds = resolveCredentials(config2, provider);
258874
+ return TTS_PROVIDERS[provider].credentialFields.every((field) => creds[field.key].length > 0);
258875
+ }
258876
+ function maskSecret(value) {
258877
+ if (!value) return "";
258878
+ if (value.length <= 4) return "****";
258879
+ return "****" + value.slice(-4);
258880
+ }
258881
+
258882
+ // src/routes/tts-routes.ts
258883
+ var TtsValidationError = class extends Error {
258884
+ };
258885
+ var TTS_MAX_CONCURRENT_PER_USER = 2;
258886
+ var VOICE_CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
258887
+ var VOICE_CACHE_MAX = 50;
258888
+ var SYNTHESIZE_TIMEOUT_MS = 6e4;
258889
+ function requireTtsUser(req, reply) {
258890
+ const auth2 = requireAuth(req, reply);
258891
+ if (auth2 === null) return null;
258892
+ return resolveUserId(auth2);
258893
+ }
258894
+ function serializeConfig(config2) {
258895
+ const credentials = {};
258896
+ for (const id of TTS_PROVIDER_IDS) {
258897
+ const stored = config2.credentials[id] ?? {};
258898
+ const out = {};
258899
+ for (const field of TTS_PROVIDERS[id].credentialFields) {
258900
+ const value = stored[field.key] ?? "";
258901
+ out[field.key] = field.secret ? maskSecret(value) : value;
258902
+ }
258903
+ credentials[id] = out;
258904
+ }
258905
+ return {
258906
+ provider: config2.provider,
258907
+ voice: config2.voice,
258908
+ rate: config2.rate,
258909
+ configured: isTtsConfigured(config2),
258910
+ credentials,
258911
+ rateRange: { min: TTS_RATE_MIN, max: TTS_RATE_MAX },
258912
+ providers: TTS_PROVIDER_IDS.map((id) => {
258913
+ const def = TTS_PROVIDERS[id];
258914
+ return {
258915
+ id,
258916
+ label: def.label,
258917
+ defaultVoice: def.defaultVoice,
258918
+ maxCharsPerRequest: def.maxCharsPerRequest,
258919
+ configured: isTtsConfigured(config2, id),
258920
+ credentialFields: def.credentialFields.map((field) => ({
258921
+ key: field.key,
258922
+ label: field.label,
258923
+ secret: field.secret,
258924
+ placeholder: field.placeholder,
258925
+ // Lets the UI say "using the server default" without revealing the value.
258926
+ fromEnv: Boolean(field.envKey && process.env[field.envKey]?.trim())
258927
+ }))
258928
+ };
258929
+ })
258930
+ };
258931
+ }
258932
+ function errorReply(reply, err) {
258933
+ switch (err.kind) {
258934
+ // Not 401: the client would read that as its own session having expired.
258935
+ case "auth":
258936
+ return reply.code(502).send({ code: "tts_auth_failed", error: err.message });
258937
+ case "quota":
258938
+ return reply.code(429).send({ code: "tts_quota", error: err.message });
258939
+ case "bad_request":
258940
+ return reply.code(400).send({ code: "tts_bad_request", error: err.message });
258941
+ default:
258942
+ return reply.code(502).send({ code: "tts_upstream", error: err.message });
258943
+ }
258944
+ }
258945
+ var routes24 = async (fastify2) => {
258946
+ const inFlight = /* @__PURE__ */ new Map();
258947
+ const voiceCache = /* @__PURE__ */ new Map();
258948
+ const dispatcher = () => fastify2.proxyManager?.getFetchDispatcher();
258949
+ fastify2.get("/api/settings/tts", async (req, reply) => {
258950
+ const userId = requireTtsUser(req, reply);
258951
+ if (userId === null) return;
258952
+ return reply.code(200).send(serializeConfig(await getTtsConfig(fastify2.storage, userId)));
258953
+ });
258954
+ fastify2.put("/api/settings/tts", async (req, reply) => {
258955
+ const userId = requireTtsUser(req, reply);
258956
+ if (userId === null) return;
258957
+ const body = req.body ?? {};
258958
+ let updated;
258959
+ try {
258960
+ await fastify2.storage.userSettings.update(userId, TTS_SETTING_KEY, (current) => {
258961
+ const existing = parseTtsConfig(current);
258962
+ let provider = existing.provider;
258963
+ if (body.provider !== void 0) {
258964
+ if (!isTtsProviderId(body.provider)) {
258965
+ throw new TtsValidationError(`provider must be one of: ${TTS_PROVIDER_IDS.join(", ")}`);
258966
+ }
258967
+ provider = body.provider;
258968
+ }
258969
+ const credentials = { ...existing.credentials };
258970
+ if (body.credentials !== void 0) {
258971
+ if (!body.credentials || typeof body.credentials !== "object") {
258972
+ throw new TtsValidationError("credentials must be an object");
258973
+ }
258974
+ for (const id of TTS_PROVIDER_IDS) {
258975
+ const incoming = body.credentials[id];
258976
+ if (incoming === void 0) continue;
258977
+ if (!incoming || typeof incoming !== "object") {
258978
+ throw new TtsValidationError(`credentials.${id} must be an object`);
258979
+ }
258980
+ const merged = { ...existing.credentials[id] ?? {} };
258981
+ for (const field of TTS_PROVIDERS[id].credentialFields) {
258982
+ const value = incoming[field.key];
258983
+ if (value === void 0) continue;
258984
+ if (typeof value !== "string") {
258985
+ throw new TtsValidationError(`credentials.${id}.${field.key} must be a string`);
258986
+ }
258987
+ if (field.secret && value !== "" && value === maskSecret(merged[field.key] ?? "")) continue;
258988
+ merged[field.key] = value.trim();
258989
+ }
258990
+ credentials[id] = merged;
258991
+ }
258992
+ }
258993
+ let voice;
258994
+ if (body.voice !== void 0) {
258995
+ if (typeof body.voice !== "string" || !TTS_PROVIDERS[provider].isValidVoice(body.voice)) {
258996
+ throw new TtsValidationError(`voice is not a valid ${TTS_PROVIDERS[provider].label} voice`);
258997
+ }
258998
+ voice = body.voice;
258999
+ } else {
259000
+ voice = normalizeVoice(provider, provider === existing.provider ? existing.voice : void 0);
259001
+ }
259002
+ let rate = existing.rate;
259003
+ if (body.rate !== void 0) {
259004
+ if (typeof body.rate !== "number" || !Number.isFinite(body.rate) || body.rate < TTS_RATE_MIN || body.rate > TTS_RATE_MAX) {
259005
+ throw new TtsValidationError(`rate must be a number between ${TTS_RATE_MIN} and ${TTS_RATE_MAX}`);
259006
+ }
259007
+ rate = clampRate(body.rate);
259008
+ }
259009
+ updated = { provider, credentials, voice, rate };
259010
+ return JSON.stringify(updated);
259011
+ });
259012
+ } catch (err) {
259013
+ if (err instanceof TtsValidationError) return reply.code(400).send({ error: err.message });
259014
+ throw err;
259015
+ }
259016
+ console.log(`[Settings] TTS updated: provider=${updated.provider}, voice=${updated.voice}, rate=${updated.rate}`);
259017
+ return reply.code(200).send(serializeConfig(updated));
259018
+ });
259019
+ fastify2.get("/api/tts/voices", async (req, reply) => {
259020
+ const userId = requireTtsUser(req, reply);
259021
+ if (userId === null) return;
259022
+ const config2 = await getTtsConfig(fastify2.storage, userId);
259023
+ const requested = req.query.provider;
259024
+ if (requested !== void 0 && !isTtsProviderId(requested)) {
259025
+ return reply.code(400).send({ error: `provider must be one of: ${TTS_PROVIDER_IDS.join(", ")}` });
259026
+ }
259027
+ const provider = requested ?? config2.provider;
259028
+ if (!isTtsConfigured(config2, provider)) {
259029
+ return reply.code(409).send({ code: "tts_not_configured", error: "Text-to-speech is not configured" });
259030
+ }
259031
+ const creds = resolveCredentials(config2, provider);
259032
+ const cacheKey2 = createHash10("sha256").update(provider).update("\0").update(JSON.stringify(creds)).digest("hex");
259033
+ const cached2 = voiceCache.get(cacheKey2);
259034
+ if (cached2 && Date.now() - cached2.at < VOICE_CACHE_TTL_MS) {
259035
+ return reply.code(200).send({ provider, voices: cached2.voices });
259036
+ }
259037
+ try {
259038
+ const voices = await TTS_PROVIDERS[provider].listVoices(creds, {
259039
+ signal: AbortSignal.timeout(15e3),
259040
+ dispatcher: dispatcher()
259041
+ });
259042
+ if (voiceCache.size >= VOICE_CACHE_MAX) voiceCache.delete(voiceCache.keys().next().value);
259043
+ voiceCache.set(cacheKey2, { at: Date.now(), voices });
259044
+ return reply.code(200).send({ provider, voices });
259045
+ } catch (err) {
259046
+ if (err instanceof TtsProviderError) return errorReply(reply, err);
259047
+ if (err?.name === "TimeoutError") {
259048
+ return reply.code(504).send({ code: "tts_upstream", error: "Voice list request timed out" });
259049
+ }
259050
+ throw err;
259051
+ }
259052
+ });
259053
+ fastify2.post(
259054
+ "/api/tts/synthesize",
259055
+ async (req, reply) => {
259056
+ const userId = requireTtsUser(req, reply);
259057
+ if (userId === null) return;
259058
+ const config2 = await getTtsConfig(fastify2.storage, userId);
259059
+ const def = TTS_PROVIDERS[config2.provider];
259060
+ const body = req.body ?? {};
259061
+ const text2 = typeof body.text === "string" ? body.text.trim() : "";
259062
+ if (!text2) return reply.code(400).send({ error: "text is required" });
259063
+ if (text2.length > def.maxCharsPerRequest) {
259064
+ return reply.code(400).send({ error: `text must be at most ${def.maxCharsPerRequest} characters` });
259065
+ }
259066
+ if (body.voice !== void 0 && (typeof body.voice !== "string" || !def.isValidVoice(body.voice))) {
259067
+ return reply.code(400).send({ error: "invalid voice" });
259068
+ }
259069
+ if (!isTtsConfigured(config2)) {
259070
+ return reply.code(409).send({ code: "tts_not_configured", error: "Text-to-speech is not configured" });
259071
+ }
259072
+ const active = inFlight.get(userId) ?? 0;
259073
+ if (active >= TTS_MAX_CONCURRENT_PER_USER) {
259074
+ return reply.code(429).send({ code: "tts_busy", error: "Too many concurrent speech requests" });
259075
+ }
259076
+ inFlight.set(userId, active + 1);
259077
+ let released = false;
259078
+ const release = () => {
259079
+ if (released) return;
259080
+ released = true;
259081
+ const n = (inFlight.get(userId) ?? 1) - 1;
259082
+ if (n <= 0) inFlight.delete(userId);
259083
+ else inFlight.set(userId, n);
259084
+ };
259085
+ const controller = new AbortController();
259086
+ reply.raw.once("close", () => {
259087
+ if (!reply.raw.writableFinished) controller.abort();
259088
+ release();
259089
+ });
259090
+ const startedAt = Date.now();
259091
+ let result;
259092
+ try {
259093
+ result = await def.synthesize(resolveCredentials(config2), {
259094
+ text: text2,
259095
+ voice: typeof body.voice === "string" ? body.voice : config2.voice,
259096
+ signal: AbortSignal.any([controller.signal, AbortSignal.timeout(SYNTHESIZE_TIMEOUT_MS)]),
259097
+ dispatcher: dispatcher()
259098
+ });
259099
+ } catch (err) {
259100
+ release();
259101
+ if (err instanceof TtsProviderError) {
259102
+ console.warn(`[tts] ${config2.provider} synthesize failed (${err.kind}): ${err.message}`);
259103
+ return errorReply(reply, err);
259104
+ }
259105
+ if (controller.signal.aborted) return reply.code(499).send();
259106
+ if (err?.name === "TimeoutError") {
259107
+ return reply.code(504).send({ code: "tts_upstream", error: "Speech synthesis timed out" });
259108
+ }
259109
+ throw err;
259110
+ }
259111
+ console.log(`[tts] ${config2.provider} chars=${text2.length} ttfb=${Date.now() - startedAt}ms`);
259112
+ const audio = Readable2.fromWeb(result.audio);
259113
+ audio.once("close", release);
259114
+ audio.once("error", (err) => {
259115
+ if (!controller.signal.aborted) console.warn(`[tts] audio stream error: ${err.message}`);
259116
+ });
259117
+ return reply.code(200).header("Content-Type", result.contentType).header("Cache-Control", "no-store").send(audio);
259118
+ }
259119
+ );
259120
+ };
259121
+ var tts_routes_default = (0, import_fastify_plugin25.default)(routes24, { name: "tts-routes" });
259122
+
259123
+ // src/routes/websocket-routes.ts
259124
+ var import_fastify_plugin26 = __toESM(require_plugin2(), 1);
257954
259125
 
257955
259126
  // src/routes/executor-stream-handlers.ts
257956
259127
  import { randomUUID as randomUUID26 } from "crypto";
@@ -258264,7 +259435,14 @@ function resolveRemoteReplayCursor(clientEpoch, cachedEpoch, afterEntryIndex) {
258264
259435
  replayAfter: epochMatches ? afterEntryIndex ?? -1 : -1
258265
259436
  };
258266
259437
  }
258267
- var routes24 = async (fastify2) => {
259438
+ function restoreRunningRemoteStreams(answers, ensure) {
259439
+ for (const { sessions } of answers) {
259440
+ for (const session of sessions) {
259441
+ if (session.status === "running") ensure(session.localSessionId);
259442
+ }
259443
+ }
259444
+ }
259445
+ var routes25 = async (fastify2) => {
258268
259446
  fastify2.reverseConnectManager.setStatusChangeHandler((remoteServerId, status) => {
258269
259447
  if (status !== "online") return;
258270
259448
  const cache2 = fastify2.remotePatchCache;
@@ -258293,8 +259471,29 @@ var routes24 = async (fastify2) => {
258293
259471
  `/api/path/agent-sessions/alive?path=${encodeURIComponent(remotePath)}`,
258294
259472
  void 0,
258295
259473
  { reverseConnectManager: fastify2.reverseConnectManager }
258296
- )
258297
- }).catch((error48) => console.warn("[RemoteLiveness] reconcile failed:", error48));
259474
+ ),
259475
+ // Same scope as the project `/alive` route: projects whose agent runs on
259476
+ // this worker. No user filter — this is server maintenance.
259477
+ listProjects: async (serverId) => {
259478
+ const projects = (await fastify2.storage.projects.getAll()).filter((project) => project.agent_mode === serverId);
259479
+ const rows = [];
259480
+ for (const project of projects) {
259481
+ const remote = await fastify2.storage.projectRemotes.getByProjectAndServer(project.id, serverId);
259482
+ if (remote) rows.push({ projectId: project.id, remotePath: remote.remote_path });
259483
+ }
259484
+ return rows;
259485
+ }
259486
+ }).then(({ answers }) => restoreRunningRemoteStreams(
259487
+ answers,
259488
+ (localSessionId) => ensureRemoteAgentStream(localSessionId, {
259489
+ remoteSessionMap: fastify2.remoteSessionMap,
259490
+ remotePatchCache: fastify2.remotePatchCache,
259491
+ reverseConnectManager: fastify2.reverseConnectManager,
259492
+ eventBus: fastify2.eventBus,
259493
+ agentSessionManager: fastify2.agentSessionManager,
259494
+ storage: fastify2.storage
259495
+ })
259496
+ )).catch((error48) => console.warn("[RemoteLiveness] reconcile failed:", error48));
258298
259497
  });
258299
259498
  fastify2.after(() => {
258300
259499
  fastify2.get(
@@ -258784,11 +259983,11 @@ var routes24 = async (fastify2) => {
258784
259983
  );
258785
259984
  });
258786
259985
  };
258787
- var websocket_routes_default = (0, import_fastify_plugin25.default)(routes24, { name: "websocket-routes" });
259986
+ var websocket_routes_default = (0, import_fastify_plugin26.default)(routes25, { name: "websocket-routes" });
258788
259987
 
258789
259988
  // src/routes/reverse-connect-routes.ts
258790
- var import_fastify_plugin26 = __toESM(require_plugin2(), 1);
258791
- import { randomBytes as randomBytes4, createHash as createHash10, verify as cryptoVerify } from "crypto";
259989
+ var import_fastify_plugin27 = __toESM(require_plugin2(), 1);
259990
+ import { randomBytes as randomBytes4, createHash as createHash11, verify as cryptoVerify } from "crypto";
258792
259991
 
258793
259992
  // src/utils/rate-limited-warn.ts
258794
259993
  function createRateLimitedWarn(windowMs, maxKeys) {
@@ -258832,7 +260031,7 @@ function extractReportedVersion(frame) {
258832
260031
  var MACHINE_HANDSHAKE_TIMEOUT_MS = 5e3;
258833
260032
  var REJECT_LOG_WINDOW_MS = 3e4;
258834
260033
  var REJECT_LOG_MAX_KEYS = 500;
258835
- var routes25 = async (fastify2) => {
260034
+ var routes26 = async (fastify2) => {
258836
260035
  const logRejectedUpgrade = createRateLimitedWarn(REJECT_LOG_WINDOW_MS, REJECT_LOG_MAX_KEYS);
258837
260036
  fastify2.get("/api/reverse-connect/identity", async (req, reply) => {
258838
260037
  const token = req.headers["x-vibedeckx-connect-token"];
@@ -258938,7 +260137,7 @@ var routes25 = async (fastify2) => {
258938
260137
  socket.close(4003, "Bad machine signature");
258939
260138
  return;
258940
260139
  }
258941
- const fingerprint = createHash10("sha256").update(publicKey).digest("hex");
260140
+ const fingerprint = createHash11("sha256").update(publicKey).digest("hex");
258942
260141
  const { owned, created } = await fastify2.storage.machineIdentity.claimOrVerify(fingerprint, publicKey, ownerId);
258943
260142
  if (!owned) {
258944
260143
  console.warn(`[ReverseConnect] Machine ${fingerprint.slice(0, 12)} owner mismatch \u2014 rejecting ${serverId}`);
@@ -258966,10 +260165,10 @@ var routes25 = async (fastify2) => {
258966
260165
  );
258967
260166
  });
258968
260167
  };
258969
- var reverse_connect_routes_default = (0, import_fastify_plugin26.default)(routes25, { name: "reverse-connect-routes" });
260168
+ var reverse_connect_routes_default = (0, import_fastify_plugin27.default)(routes26, { name: "reverse-connect-routes" });
258970
260169
 
258971
260170
  // src/routes/event-routes.ts
258972
- var import_fastify_plugin27 = __toESM(require_plugin2(), 1);
260171
+ var import_fastify_plugin28 = __toESM(require_plugin2(), 1);
258973
260172
  function toWireEvent(event) {
258974
260173
  if (event.type === "executor:stopped" && (event.tailOutput !== void 0 || event.finalResult !== void 0)) {
258975
260174
  const { tailOutput: _tailOutput, finalResult: _finalResult, ...rest } = event;
@@ -258977,7 +260176,7 @@ function toWireEvent(event) {
258977
260176
  }
258978
260177
  return event;
258979
260178
  }
258980
- var routes26 = async (fastify2) => {
260179
+ var routes27 = async (fastify2) => {
258981
260180
  fastify2.get("/api/events", async (req, reply) => {
258982
260181
  let userId = null;
258983
260182
  if (fastify2.authEnabled) {
@@ -259037,10 +260236,10 @@ var routes26 = async (fastify2) => {
259037
260236
  await reply;
259038
260237
  });
259039
260238
  };
259040
- var event_routes_default = (0, import_fastify_plugin27.default)(routes26, { name: "event-routes" });
260239
+ var event_routes_default = (0, import_fastify_plugin28.default)(routes27, { name: "event-routes" });
259041
260240
 
259042
260241
  // src/routes/terminal-routes.ts
259043
- var import_fastify_plugin28 = __toESM(require_plugin2(), 1);
260242
+ var import_fastify_plugin29 = __toESM(require_plugin2(), 1);
259044
260243
  import path17 from "path";
259045
260244
  async function getRemoteConfig5(fastify2, project, remoteServerId) {
259046
260245
  const remotes = await fastify2.storage.projectRemotes.getByProject(project.id);
@@ -259051,7 +260250,7 @@ async function getRemoteConfig5(fastify2, project, remoteServerId) {
259051
260250
  remotePath: target.remote_path
259052
260251
  };
259053
260252
  }
259054
- var routes27 = async (fastify2) => {
260253
+ var routes28 = async (fastify2) => {
259055
260254
  fastify2.post("/api/path/terminals", async (req, reply) => {
259056
260255
  const { path: projectPath, branch } = req.body;
259057
260256
  if (!projectPath) {
@@ -259226,11 +260425,11 @@ var routes27 = async (fastify2) => {
259226
260425
  }
259227
260426
  );
259228
260427
  };
259229
- var terminal_routes_default = (0, import_fastify_plugin28.default)(routes27, { name: "terminal-routes" });
260428
+ var terminal_routes_default = (0, import_fastify_plugin29.default)(routes28, { name: "terminal-routes" });
259230
260429
 
259231
260430
  // src/routes/browser-routes.ts
259232
- var import_fastify_plugin29 = __toESM(require_plugin2(), 1);
259233
- var routes28 = async (fastify2) => {
260431
+ var import_fastify_plugin30 = __toESM(require_plugin2(), 1);
260432
+ var routes29 = async (fastify2) => {
259234
260433
  const ensureProjectAccess = async (req, reply) => {
259235
260434
  const userId = requireUserFacingUserId(req, reply);
259236
260435
  if (userId === null) return null;
@@ -259301,10 +260500,10 @@ var routes28 = async (fastify2) => {
259301
260500
  return reply.code(200).send({ ok: true });
259302
260501
  });
259303
260502
  };
259304
- var browser_routes_default = (0, import_fastify_plugin29.default)(routes28, { name: "browser-routes" });
260503
+ var browser_routes_default = (0, import_fastify_plugin30.default)(routes29, { name: "browser-routes" });
259305
260504
 
259306
260505
  // src/routes/browser-proxy-routes.ts
259307
- var import_fastify_plugin30 = __toESM(require_plugin2(), 1);
260506
+ var import_fastify_plugin31 = __toESM(require_plugin2(), 1);
259308
260507
  import { randomUUID as randomUUID27 } from "crypto";
259309
260508
 
259310
260509
  // src/utils/ssrf-guard.ts
@@ -259800,7 +260999,7 @@ function generateInjectedScript(projectId, targetOrigin, proxyWsPrefix) {
259800
260999
  })();
259801
261000
  </script>`;
259802
261001
  }
259803
- var routes29 = async (fastify2) => {
261002
+ var routes30 = async (fastify2) => {
259804
261003
  fastify2.get("/api/projects/:id/browser/proxy/*", async (req, reply) => {
259805
261004
  const userId = requireUserFacingOrTrustedProxyUserId(req, reply);
259806
261005
  if (userId === null) return;
@@ -259972,10 +261171,10 @@ var routes29 = async (fastify2) => {
259972
261171
  });
259973
261172
  });
259974
261173
  };
259975
- var browser_proxy_routes_default = (0, import_fastify_plugin30.default)(routes29, { name: "browser-proxy-routes" });
261174
+ var browser_proxy_routes_default = (0, import_fastify_plugin31.default)(routes30, { name: "browser-proxy-routes" });
259976
261175
 
259977
261176
  // src/routes/cross-remote-target-routes.ts
259978
- var import_fastify_plugin31 = __toESM(require_plugin2(), 1);
261177
+ var import_fastify_plugin32 = __toESM(require_plugin2(), 1);
259979
261178
  import path19 from "path";
259980
261179
  import { promises as fs4 } from "fs";
259981
261180
 
@@ -265222,7 +266421,7 @@ var clampTimeoutMs = (timeoutSec) => {
265222
266421
  const requested = typeof timeoutSec === "number" && Number.isFinite(timeoutSec) && timeoutSec > 0 ? timeoutSec : DEFAULT_TIMEOUT_SEC;
265223
266422
  return Math.min(requested, MAX_TIMEOUT_SEC) * 1e3;
265224
266423
  };
265225
- var routes30 = async (fastify2) => {
266424
+ var routes31 = async (fastify2) => {
265226
266425
  const mcpSessions = new RemoteMcpSessionManager();
265227
266426
  fastify2.decorate("remoteMcpSessionManager", mcpSessions);
265228
266427
  fastify2.addHook("onClose", async () => mcpSessions.shutdown());
@@ -265386,10 +266585,10 @@ var routes30 = async (fastify2) => {
265386
266585
  return reply.send({ closed: await mcpSessions.close(request.body?.workerHandle ?? "") });
265387
266586
  });
265388
266587
  };
265389
- var cross_remote_target_routes_default = (0, import_fastify_plugin31.default)(routes30, { name: "cross-remote-target-routes" });
266588
+ var cross_remote_target_routes_default = (0, import_fastify_plugin32.default)(routes31, { name: "cross-remote-target-routes" });
265390
266589
 
265391
266590
  // src/routes/cross-remote-mcp-routes.ts
265392
- var import_fastify_plugin32 = __toESM(require_plugin2(), 1);
266591
+ var import_fastify_plugin33 = __toESM(require_plugin2(), 1);
265393
266592
  var PROTOCOL_VERSION = "2024-11-05";
265394
266593
  var AUDIT_ARGS_MAX = 1024;
265395
266594
  var NOT_ACCESSIBLE = "remote not found or not accessible";
@@ -265613,7 +266812,7 @@ var textResult = (text2, isError = false) => ({
265613
266812
  content: [{ type: "text", text: text2 }],
265614
266813
  ...isError ? { isError: true } : {}
265615
266814
  });
265616
- var routes31 = async (fastify2) => {
266815
+ var routes32 = async (fastify2) => {
265617
266816
  const guard = new SessionConcurrencyGuard();
265618
266817
  let cachedSecret;
265619
266818
  const getSecret = () => {
@@ -265699,6 +266898,12 @@ var routes31 = async (fastify2) => {
265699
266898
  } catch (err) {
265700
266899
  console.error("[CrossRemoteMCP] Failed to write audit row:", err);
265701
266900
  }
266901
+ if (status === "denied" || status === "offline") return;
266902
+ try {
266903
+ await fastify2.storage.sessionRemoteTouches.record(payload.sessionId, payload.userId, targetRemoteId);
266904
+ } catch (err) {
266905
+ console.error("[CrossRemoteMCP] Failed to record session touch:", err);
266906
+ }
265702
266907
  };
265703
266908
  const callTool = async (payload, toolName, args) => {
265704
266909
  if (toolName === "list_accessible_remotes") {
@@ -265837,10 +267042,10 @@ var routes31 = async (fastify2) => {
265837
267042
  }
265838
267043
  });
265839
267044
  };
265840
- var cross_remote_mcp_routes_default = (0, import_fastify_plugin32.default)(routes31, { name: "cross-remote-mcp-routes" });
267045
+ var cross_remote_mcp_routes_default = (0, import_fastify_plugin33.default)(routes32, { name: "cross-remote-mcp-routes" });
265841
267046
 
265842
267047
  // src/routes/session-mcp-routes.ts
265843
- var import_fastify_plugin33 = __toESM(require_plugin2(), 1);
267048
+ var import_fastify_plugin34 = __toESM(require_plugin2(), 1);
265844
267049
  var PROTOCOL_VERSION2 = "2024-11-05";
265845
267050
  var TOOLS2 = [
265846
267051
  {
@@ -265853,7 +267058,7 @@ var textResult2 = (text2, isError = false) => ({
265853
267058
  content: [{ type: "text", text: text2 }],
265854
267059
  ...isError ? { isError: true } : {}
265855
267060
  });
265856
- var routes32 = async (fastify2) => {
267061
+ var routes33 = async (fastify2) => {
265857
267062
  let cachedSecret;
265858
267063
  const getSecret = () => {
265859
267064
  if (!cachedSecret) cachedSecret = getSessionToolsSecret(fastify2.storage);
@@ -265913,10 +267118,10 @@ var routes32 = async (fastify2) => {
265913
267118
  }
265914
267119
  });
265915
267120
  };
265916
- var session_mcp_routes_default = (0, import_fastify_plugin33.default)(routes32, { name: "session-mcp-routes" });
267121
+ var session_mcp_routes_default = (0, import_fastify_plugin34.default)(routes33, { name: "session-mcp-routes" });
265917
267122
 
265918
267123
  // src/routes/schedule-routes.ts
265919
- var import_fastify_plugin34 = __toESM(require_plugin2(), 1);
267124
+ var import_fastify_plugin35 = __toESM(require_plugin2(), 1);
265920
267125
  import { randomUUID as randomUUID29 } from "crypto";
265921
267126
  import path20 from "path";
265922
267127
  var RUN_TYPES = ["command", "prompt"];
@@ -265937,7 +267142,7 @@ function validateResolved(b2) {
265937
267142
  if (cronError) return `Invalid cron expression: ${cronError}`;
265938
267143
  return null;
265939
267144
  }
265940
- var routes33 = async (fastify2) => {
267145
+ var routes34 = async (fastify2) => {
265941
267146
  const sendTerminalManualOutcome = (reply, request, replay) => {
265942
267147
  if (!request.terminalStatus || request.terminalResponseStatus === null) return null;
265943
267148
  const common = { runId: request.runId, status: request.terminalStatus, durable: true, replay };
@@ -265962,6 +267167,32 @@ var routes33 = async (fastify2) => {
265962
267167
  }
265963
267168
  return schedule;
265964
267169
  };
267170
+ const resolveSourceSessions = async (ids) => {
267171
+ const unique = [...new Set(ids)];
267172
+ const remoteIds = unique.filter((id) => id.startsWith("remote-"));
267173
+ const remoteTitles = await fastify2.storage.searchCache.getCachedSessionTitles(remoteIds);
267174
+ const branchOf2 = async (row) => {
267175
+ if (!row) return null;
267176
+ const registered = row.workspace_checkout_id ? await fastify2.storage.workspaceRegistry.getCheckoutById(row.workspace_checkout_id) : void 0;
267177
+ return (registered ? registered.workspace.branch : row.branch) || null;
267178
+ };
267179
+ const out = /* @__PURE__ */ new Map();
267180
+ await Promise.all(unique.map(async (id) => {
267181
+ if (id.startsWith("remote-")) {
267182
+ const mapping = await fastify2.storage.remoteSessionMappings.getByLocal(id);
267183
+ out.set(id, {
267184
+ id,
267185
+ exists: !!mapping,
267186
+ branch: await branchOf2(mapping),
267187
+ title: remoteTitles.get(id) ?? null
267188
+ });
267189
+ return;
267190
+ }
267191
+ const session = await fastify2.storage.agentSessions.getById(id);
267192
+ out.set(id, { id, exists: !!session, branch: await branchOf2(session), title: session?.title ?? null });
267193
+ }));
267194
+ return out;
267195
+ };
265965
267196
  fastify2.get(
265966
267197
  "/api/projects/:projectId/schedules",
265967
267198
  async (req, reply) => {
@@ -265971,9 +267202,13 @@ var routes33 = async (fastify2) => {
265971
267202
  if (!project) return reply.code(404).send({ error: "Project not found" });
265972
267203
  const schedules = await fastify2.storage.scheduledTasks.getByProjectId(req.params.projectId);
265973
267204
  const lastRuns = await fastify2.storage.scheduledTaskRuns.getLastByScheduleIds(schedules.map((s3) => s3.id));
267205
+ const sources = await resolveSourceSessions(
267206
+ schedules.flatMap((s3) => s3.source_session_id ? [s3.source_session_id] : [])
267207
+ );
265974
267208
  return reply.code(200).send({
265975
267209
  schedules: schedules.map((s3) => ({
265976
267210
  ...s3,
267211
+ source_session: s3.source_session_id ? sources.get(s3.source_session_id) ?? null : null,
265977
267212
  last_run: lastRuns[s3.id] ?? null,
265978
267213
  next_run_at: fastify2.scheduler.nextRunAt(s3.id),
265979
267214
  running: fastify2.scheduler.isRunning(s3.id)
@@ -266021,10 +267256,11 @@ var routes33 = async (fastify2) => {
266021
267256
  source = { session_id: b2.source.session_id, tool_use_id: b2.source.tool_use_id };
266022
267257
  }
266023
267258
  const newId = randomUUID29();
266024
- const schedule = await fastify2.storage.scheduledTasks.create({
267259
+ const name25 = b2.name.trim();
267260
+ const insert = () => fastify2.storage.scheduledTasks.create({
266025
267261
  id: newId,
266026
267262
  project_id: req.params.projectId,
266027
- name: b2.name.trim(),
267263
+ name: name25,
266028
267264
  cron_expr: resolved.cron_expr,
266029
267265
  timezone: resolved.timezone,
266030
267266
  run_type: resolved.run_type,
@@ -266038,8 +267274,31 @@ var routes33 = async (fastify2) => {
266038
267274
  target,
266039
267275
  source
266040
267276
  });
266041
- await fastify2.scheduler.reschedule(schedule.id);
267277
+ let schedule;
267278
+ if (source) {
267279
+ try {
267280
+ schedule = await fastify2.retentionHolds.exclusive(source.session_id, async (syncNow) => {
267281
+ const row = await insert();
267282
+ try {
267283
+ await syncNow();
267284
+ return row;
267285
+ } catch (error49) {
267286
+ if (row.id === newId) {
267287
+ await fastify2.storage.scheduledTasks.delete(row.id);
267288
+ await syncNow().catch(() => void 0);
267289
+ }
267290
+ throw error49;
267291
+ }
267292
+ });
267293
+ } catch (error49) {
267294
+ const message = error49 instanceof Error ? error49.message : String(error49);
267295
+ return reply.code(502).send({ error: `Could not protect the source session from retention: ${message}` });
267296
+ }
267297
+ } else {
267298
+ schedule = await insert();
267299
+ }
266042
267300
  const created = schedule.id === newId;
267301
+ await fastify2.scheduler.reschedule(schedule.id);
266043
267302
  if (created) {
266044
267303
  fastify2.eventBus.emit({
266045
267304
  type: "schedule:changed",
@@ -266117,6 +267376,11 @@ var routes33 = async (fastify2) => {
266117
267376
  scheduleId: req.params.id,
266118
267377
  change: "deleted"
266119
267378
  });
267379
+ if (existing.source_session_id) {
267380
+ await fastify2.retentionHolds.sync(existing.source_session_id).catch((error48) => {
267381
+ console.warn(`[RetentionHolds] release for ${existing.source_session_id} deferred:`, error48);
267382
+ });
267383
+ }
266120
267384
  return reply.code(204).send();
266121
267385
  }
266122
267386
  );
@@ -266204,7 +267468,7 @@ var routes33 = async (fastify2) => {
266204
267468
  }
266205
267469
  );
266206
267470
  };
266207
- var schedule_routes_default = (0, import_fastify_plugin34.default)(routes33, { name: "schedule-routes" });
267471
+ var schedule_routes_default = (0, import_fastify_plugin35.default)(routes34, { name: "schedule-routes" });
266208
267472
 
266209
267473
  // src/search/catalog.ts
266210
267474
  var parseDbTimestamp5 = (ts) => {
@@ -266381,10 +267645,10 @@ var searchRoutes = async (fastify2) => {
266381
267645
  var search_routes_default = searchRoutes;
266382
267646
 
266383
267647
  // src/routes/notification-routes.ts
266384
- var import_fastify_plugin35 = __toESM(require_plugin2(), 1);
267648
+ var import_fastify_plugin36 = __toESM(require_plugin2(), 1);
266385
267649
  var MAX_LIMIT = 500;
266386
267650
  var DEFAULT_LIMIT = 100;
266387
- var routes34 = async (fastify2) => {
267651
+ var routes35 = async (fastify2) => {
266388
267652
  fastify2.get(
266389
267653
  "/api/notifications",
266390
267654
  async (req, reply) => {
@@ -266416,10 +267680,10 @@ var routes34 = async (fastify2) => {
266416
267680
  return reply.code(200).send({ ok: true });
266417
267681
  });
266418
267682
  };
266419
- var notification_routes_default = (0, import_fastify_plugin35.default)(routes34, { name: "notification-routes" });
267683
+ var notification_routes_default = (0, import_fastify_plugin36.default)(routes35, { name: "notification-routes" });
266420
267684
 
266421
267685
  // ../../node_modules/.pnpm/@clerk+fastify@3.1.2_fastify@5.7.2_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@clerk/fastify/dist/chunk-RY4T2JMQ.mjs
266422
- import { Readable as Readable2 } from "stream";
267686
+ import { Readable as Readable3 } from "stream";
266423
267687
  var fastifyRequestToRequest = (req) => {
266424
267688
  const headers = new Headers(
266425
267689
  Object.keys(req.headers).reduce((acc, key2) => {
@@ -266460,7 +267724,7 @@ var requestToProxyRequest = (req) => {
266460
267724
  return new Request(url2.toString(), {
266461
267725
  method: req.method,
266462
267726
  headers,
266463
- body: hasBody ? Readable2.toWeb(req.raw) : void 0,
267727
+ body: hasBody ? Readable3.toWeb(req.raw) : void 0,
266464
267728
  // @ts-expect-error - duplex required for streaming bodies but not in all TS definitions
266465
267729
  duplex: hasBody ? "half" : void 0
266466
267730
  });
@@ -266468,7 +267732,7 @@ var requestToProxyRequest = (req) => {
266468
267732
 
266469
267733
  // ../../node_modules/.pnpm/@clerk+fastify@3.1.2_fastify@5.7.2_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@clerk/fastify/dist/index.mjs
266470
267734
  init_dist();
266471
- var import_fastify_plugin36 = __toESM(require_plugin2(), 1);
267735
+ var import_fastify_plugin37 = __toESM(require_plugin2(), 1);
266472
267736
 
266473
267737
  // ../../node_modules/.pnpm/@clerk+backend@3.2.0_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@clerk/backend/dist/internal.mjs
266474
267738
  init_chunk_JW73PKED();
@@ -266641,7 +267905,7 @@ async function clerkFrontendApiProxy(request, options) {
266641
267905
 
266642
267906
  // ../../node_modules/.pnpm/@clerk+fastify@3.1.2_fastify@5.7.2_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@clerk/fastify/dist/index.mjs
266643
267907
  init_dist();
266644
- import { Readable as Readable3 } from "stream";
267908
+ import { Readable as Readable4 } from "stream";
266645
267909
 
266646
267910
  // ../../node_modules/.pnpm/@clerk+shared@4.3.0_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@clerk/shared/dist/runtime/apiUrlFromPublishableKey.mjs
266647
267911
  init_constants_Bta24VLk();
@@ -266706,7 +267970,7 @@ var withClerkMiddleware = (options) => {
266706
267970
  });
266707
267971
  if (proxyResponse.body) {
266708
267972
  const reader = proxyResponse.body.getReader();
266709
- const stream = new Readable3({
267973
+ const stream = new Readable4({
266710
267974
  async read() {
266711
267975
  try {
266712
267976
  const { done, value } = await reader.read();
@@ -266756,7 +268020,7 @@ var plugin = (instance, opts, done) => {
266756
268020
  instance.addHook(hookName, withClerkMiddleware(opts));
266757
268021
  done();
266758
268022
  };
266759
- var clerkPlugin = (0, import_fastify_plugin36.default)(plugin, {
268023
+ var clerkPlugin = (0, import_fastify_plugin37.default)(plugin, {
266760
268024
  name: "@clerk/fastify",
266761
268025
  fastify: "5.x"
266762
268026
  });
@@ -267020,6 +268284,7 @@ var createServer = async (opts) => {
267020
268284
  server.register(workflow_run_routes_default);
267021
268285
  server.register(settings_routes_default);
267022
268286
  server.register(translate_routes_default);
268287
+ server.register(tts_routes_default);
267023
268288
  server.register(event_routes_default);
267024
268289
  server.register(notification_routes_default);
267025
268290
  server.register(notification_outbox_routes_default);
@@ -267360,6 +268625,10 @@ var WORKER_CAPABILITIES = {
267360
268625
  // NOTHING, so an old worker can never look like it deleted its sessions.
267361
268626
  "http:PUT /api/settings/session-retention/apply": { since: "0.3.14", summary: "\u4E0B\u53D1\u4F1A\u8BDD\u4FDD\u7559\u5929\u6570" },
267362
268627
  "http:GET /api/path/session-ids": { since: "0.3.14", summary: "\u4F1A\u8BDD id \u5168\u91CF\u6E05\u5355(\u5BF9\u8D26\u7528)" },
268628
+ // Hub-computed hold set (schedules proposed from the session) that keeps a
268629
+ // session out of the worker's own retention sweep — retention-holds.ts.
268630
+ "http:PUT /api/path/retention-holds/:param": { since: "0.3.45", summary: "\u4E0B\u53D1\u4F1A\u8BDD\u4FDD\u7559\u9501(\u9632\u4FDD\u7559\u671F\u6E05\u7406)" },
268631
+ "http:GET /api/path/retention-holds": { since: "0.3.45", summary: "\u5217\u51FA\u6301\u6709\u4FDD\u7559\u9501\u7684\u4F1A\u8BDD(\u91CA\u653E\u8FC7\u671F\u9501)" },
267363
268632
  // --- Search / notifications / cross-remote ---
267364
268633
  "http:GET /api/path/search-catalog": { since: "0.2.0", summary: "\u641C\u7D22\u76EE\u5F55\u5FEB\u7167" },
267365
268634
  // Empirically probed: 0.2.15 → 404, 0.2.16 → 400 (route exists).
@@ -269593,7 +270862,7 @@ var connectRoutes = buildRouteMap({
269593
270862
  defaultCommand: "run",
269594
270863
  docs: { brief: "Connect to a Vibedeckx server as an inbound node" }
269595
270864
  });
269596
- var routes35 = buildRouteMap({
270865
+ var routes36 = buildRouteMap({
269597
270866
  routes: {
269598
270867
  start: startCommand,
269599
270868
  connect: connectRoutes
@@ -269603,7 +270872,7 @@ var routes35 = buildRouteMap({
269603
270872
  brief: "Vibedeckx - AI-powered app generator"
269604
270873
  }
269605
270874
  });
269606
- var program = buildApplication(routes35, {
270875
+ var program = buildApplication(routes36, {
269607
270876
  name: "vibedeckx",
269608
270877
  versionInfo: {
269609
270878
  currentVersion: readPackageVersion()