@bobannomi/client 0.0.0-stage → 0.1.0-next.1

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.
@@ -0,0 +1,4921 @@
1
+ import { createRequire as __sdkCreateRequire } from 'node:module'; const require = __sdkCreateRequire(import.meta.url);
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined") return require.apply(this, arguments);
12
+ throw Error('Dynamic require of "' + x + '" is not supported');
13
+ });
14
+ var __commonJS = (cb, mod) => function __require2() {
15
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
+ // If the importer is in node compatibility mode or this is not an ESM
27
+ // file that has been converted to a CommonJS file using a Babel-
28
+ // compatible transform (i.e. "__esModule" has not been set), then set
29
+ // "default" to the CommonJS "module.exports" for node compatibility.
30
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
31
+ mod
32
+ ));
33
+
34
+ // ../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/polyfills.js
35
+ var require_polyfills = __commonJS({
36
+ "../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/polyfills.js"(exports, module) {
37
+ var constants = __require("constants");
38
+ var origCwd = process.cwd;
39
+ var cwd = null;
40
+ var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
41
+ process.cwd = function() {
42
+ if (!cwd)
43
+ cwd = origCwd.call(process);
44
+ return cwd;
45
+ };
46
+ try {
47
+ process.cwd();
48
+ } catch (er) {
49
+ }
50
+ if (typeof process.chdir === "function") {
51
+ chdir = process.chdir;
52
+ process.chdir = function(d) {
53
+ cwd = null;
54
+ chdir.call(process, d);
55
+ };
56
+ if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
57
+ }
58
+ var chdir;
59
+ module.exports = patch;
60
+ function patch(fs) {
61
+ if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
62
+ patchLchmod(fs);
63
+ }
64
+ if (!fs.lutimes) {
65
+ patchLutimes(fs);
66
+ }
67
+ fs.chown = chownFix(fs.chown);
68
+ fs.fchown = chownFix(fs.fchown);
69
+ fs.lchown = chownFix(fs.lchown);
70
+ fs.chmod = chmodFix(fs.chmod);
71
+ fs.fchmod = chmodFix(fs.fchmod);
72
+ fs.lchmod = chmodFix(fs.lchmod);
73
+ fs.chownSync = chownFixSync(fs.chownSync);
74
+ fs.fchownSync = chownFixSync(fs.fchownSync);
75
+ fs.lchownSync = chownFixSync(fs.lchownSync);
76
+ fs.chmodSync = chmodFixSync(fs.chmodSync);
77
+ fs.fchmodSync = chmodFixSync(fs.fchmodSync);
78
+ fs.lchmodSync = chmodFixSync(fs.lchmodSync);
79
+ fs.stat = statFix(fs.stat);
80
+ fs.fstat = statFix(fs.fstat);
81
+ fs.lstat = statFix(fs.lstat);
82
+ fs.statSync = statFixSync(fs.statSync);
83
+ fs.fstatSync = statFixSync(fs.fstatSync);
84
+ fs.lstatSync = statFixSync(fs.lstatSync);
85
+ if (fs.chmod && !fs.lchmod) {
86
+ fs.lchmod = function(path2, mode, cb) {
87
+ if (cb) process.nextTick(cb);
88
+ };
89
+ fs.lchmodSync = function() {
90
+ };
91
+ }
92
+ if (fs.chown && !fs.lchown) {
93
+ fs.lchown = function(path2, uid, gid, cb) {
94
+ if (cb) process.nextTick(cb);
95
+ };
96
+ fs.lchownSync = function() {
97
+ };
98
+ }
99
+ if (platform === "win32") {
100
+ fs.rename = typeof fs.rename !== "function" ? fs.rename : (function(fs$rename) {
101
+ function rename(from, to, cb) {
102
+ var start = Date.now();
103
+ var backoff = 0;
104
+ fs$rename(from, to, function CB(er) {
105
+ if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 6e4) {
106
+ setTimeout(function() {
107
+ fs.stat(to, function(stater, st) {
108
+ if (stater && stater.code === "ENOENT")
109
+ fs$rename(from, to, CB);
110
+ else
111
+ cb(er);
112
+ });
113
+ }, backoff);
114
+ if (backoff < 100)
115
+ backoff += 10;
116
+ return;
117
+ }
118
+ if (cb) cb(er);
119
+ });
120
+ }
121
+ if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
122
+ return rename;
123
+ })(fs.rename);
124
+ }
125
+ fs.read = typeof fs.read !== "function" ? fs.read : (function(fs$read) {
126
+ function read(fd, buffer, offset, length, position, callback_) {
127
+ var callback;
128
+ if (callback_ && typeof callback_ === "function") {
129
+ var eagCounter = 0;
130
+ callback = function(er, _, __) {
131
+ if (er && er.code === "EAGAIN" && eagCounter < 10) {
132
+ eagCounter++;
133
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
134
+ }
135
+ callback_.apply(this, arguments);
136
+ };
137
+ }
138
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
139
+ }
140
+ if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read);
141
+ return read;
142
+ })(fs.read);
143
+ fs.readSync = typeof fs.readSync !== "function" ? fs.readSync : /* @__PURE__ */ (function(fs$readSync) {
144
+ return function(fd, buffer, offset, length, position) {
145
+ var eagCounter = 0;
146
+ while (true) {
147
+ try {
148
+ return fs$readSync.call(fs, fd, buffer, offset, length, position);
149
+ } catch (er) {
150
+ if (er.code === "EAGAIN" && eagCounter < 10) {
151
+ eagCounter++;
152
+ continue;
153
+ }
154
+ throw er;
155
+ }
156
+ }
157
+ };
158
+ })(fs.readSync);
159
+ function patchLchmod(fs2) {
160
+ fs2.lchmod = function(path2, mode, callback) {
161
+ fs2.open(
162
+ path2,
163
+ constants.O_WRONLY | constants.O_SYMLINK,
164
+ mode,
165
+ function(err, fd) {
166
+ if (err) {
167
+ if (callback) callback(err);
168
+ return;
169
+ }
170
+ fs2.fchmod(fd, mode, function(err2) {
171
+ fs2.close(fd, function(err22) {
172
+ if (callback) callback(err2 || err22);
173
+ });
174
+ });
175
+ }
176
+ );
177
+ };
178
+ fs2.lchmodSync = function(path2, mode) {
179
+ var fd = fs2.openSync(path2, constants.O_WRONLY | constants.O_SYMLINK, mode);
180
+ var threw = true;
181
+ var ret;
182
+ try {
183
+ ret = fs2.fchmodSync(fd, mode);
184
+ threw = false;
185
+ } finally {
186
+ if (threw) {
187
+ try {
188
+ fs2.closeSync(fd);
189
+ } catch (er) {
190
+ }
191
+ } else {
192
+ fs2.closeSync(fd);
193
+ }
194
+ }
195
+ return ret;
196
+ };
197
+ }
198
+ function patchLutimes(fs2) {
199
+ if (constants.hasOwnProperty("O_SYMLINK") && fs2.futimes) {
200
+ fs2.lutimes = function(path2, at, mt, cb) {
201
+ fs2.open(path2, constants.O_SYMLINK, function(er, fd) {
202
+ if (er) {
203
+ if (cb) cb(er);
204
+ return;
205
+ }
206
+ fs2.futimes(fd, at, mt, function(er2) {
207
+ fs2.close(fd, function(er22) {
208
+ if (cb) cb(er2 || er22);
209
+ });
210
+ });
211
+ });
212
+ };
213
+ fs2.lutimesSync = function(path2, at, mt) {
214
+ var fd = fs2.openSync(path2, constants.O_SYMLINK);
215
+ var ret;
216
+ var threw = true;
217
+ try {
218
+ ret = fs2.futimesSync(fd, at, mt);
219
+ threw = false;
220
+ } finally {
221
+ if (threw) {
222
+ try {
223
+ fs2.closeSync(fd);
224
+ } catch (er) {
225
+ }
226
+ } else {
227
+ fs2.closeSync(fd);
228
+ }
229
+ }
230
+ return ret;
231
+ };
232
+ } else if (fs2.futimes) {
233
+ fs2.lutimes = function(_a, _b, _c, cb) {
234
+ if (cb) process.nextTick(cb);
235
+ };
236
+ fs2.lutimesSync = function() {
237
+ };
238
+ }
239
+ }
240
+ function chmodFix(orig) {
241
+ if (!orig) return orig;
242
+ return function(target, mode, cb) {
243
+ return orig.call(fs, target, mode, function(er) {
244
+ if (chownErOk(er)) er = null;
245
+ if (cb) cb.apply(this, arguments);
246
+ });
247
+ };
248
+ }
249
+ function chmodFixSync(orig) {
250
+ if (!orig) return orig;
251
+ return function(target, mode) {
252
+ try {
253
+ return orig.call(fs, target, mode);
254
+ } catch (er) {
255
+ if (!chownErOk(er)) throw er;
256
+ }
257
+ };
258
+ }
259
+ function chownFix(orig) {
260
+ if (!orig) return orig;
261
+ return function(target, uid, gid, cb) {
262
+ return orig.call(fs, target, uid, gid, function(er) {
263
+ if (chownErOk(er)) er = null;
264
+ if (cb) cb.apply(this, arguments);
265
+ });
266
+ };
267
+ }
268
+ function chownFixSync(orig) {
269
+ if (!orig) return orig;
270
+ return function(target, uid, gid) {
271
+ try {
272
+ return orig.call(fs, target, uid, gid);
273
+ } catch (er) {
274
+ if (!chownErOk(er)) throw er;
275
+ }
276
+ };
277
+ }
278
+ function statFix(orig) {
279
+ if (!orig) return orig;
280
+ return function(target, options, cb) {
281
+ if (typeof options === "function") {
282
+ cb = options;
283
+ options = null;
284
+ }
285
+ function callback(er, stats) {
286
+ if (stats) {
287
+ if (stats.uid < 0) stats.uid += 4294967296;
288
+ if (stats.gid < 0) stats.gid += 4294967296;
289
+ }
290
+ if (cb) cb.apply(this, arguments);
291
+ }
292
+ return options ? orig.call(fs, target, options, callback) : orig.call(fs, target, callback);
293
+ };
294
+ }
295
+ function statFixSync(orig) {
296
+ if (!orig) return orig;
297
+ return function(target, options) {
298
+ var stats = options ? orig.call(fs, target, options) : orig.call(fs, target);
299
+ if (stats) {
300
+ if (stats.uid < 0) stats.uid += 4294967296;
301
+ if (stats.gid < 0) stats.gid += 4294967296;
302
+ }
303
+ return stats;
304
+ };
305
+ }
306
+ function chownErOk(er) {
307
+ if (!er)
308
+ return true;
309
+ if (er.code === "ENOSYS")
310
+ return true;
311
+ var nonroot = !process.getuid || process.getuid() !== 0;
312
+ if (nonroot) {
313
+ if (er.code === "EINVAL" || er.code === "EPERM")
314
+ return true;
315
+ }
316
+ return false;
317
+ }
318
+ }
319
+ }
320
+ });
321
+
322
+ // ../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/legacy-streams.js
323
+ var require_legacy_streams = __commonJS({
324
+ "../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/legacy-streams.js"(exports, module) {
325
+ var Stream = __require("stream").Stream;
326
+ module.exports = legacy;
327
+ function legacy(fs) {
328
+ return {
329
+ ReadStream,
330
+ WriteStream
331
+ };
332
+ function ReadStream(path2, options) {
333
+ if (!(this instanceof ReadStream)) return new ReadStream(path2, options);
334
+ Stream.call(this);
335
+ var self = this;
336
+ this.path = path2;
337
+ this.fd = null;
338
+ this.readable = true;
339
+ this.paused = false;
340
+ this.flags = "r";
341
+ this.mode = 438;
342
+ this.bufferSize = 64 * 1024;
343
+ options = options || {};
344
+ var keys = Object.keys(options);
345
+ for (var index = 0, length = keys.length; index < length; index++) {
346
+ var key = keys[index];
347
+ this[key] = options[key];
348
+ }
349
+ if (this.encoding) this.setEncoding(this.encoding);
350
+ if (this.start !== void 0) {
351
+ if ("number" !== typeof this.start) {
352
+ throw TypeError("start must be a Number");
353
+ }
354
+ if (this.end === void 0) {
355
+ this.end = Infinity;
356
+ } else if ("number" !== typeof this.end) {
357
+ throw TypeError("end must be a Number");
358
+ }
359
+ if (this.start > this.end) {
360
+ throw new Error("start must be <= end");
361
+ }
362
+ this.pos = this.start;
363
+ }
364
+ if (this.fd !== null) {
365
+ process.nextTick(function() {
366
+ self._read();
367
+ });
368
+ return;
369
+ }
370
+ fs.open(this.path, this.flags, this.mode, function(err, fd) {
371
+ if (err) {
372
+ self.emit("error", err);
373
+ self.readable = false;
374
+ return;
375
+ }
376
+ self.fd = fd;
377
+ self.emit("open", fd);
378
+ self._read();
379
+ });
380
+ }
381
+ function WriteStream(path2, options) {
382
+ if (!(this instanceof WriteStream)) return new WriteStream(path2, options);
383
+ Stream.call(this);
384
+ this.path = path2;
385
+ this.fd = null;
386
+ this.writable = true;
387
+ this.flags = "w";
388
+ this.encoding = "binary";
389
+ this.mode = 438;
390
+ this.bytesWritten = 0;
391
+ options = options || {};
392
+ var keys = Object.keys(options);
393
+ for (var index = 0, length = keys.length; index < length; index++) {
394
+ var key = keys[index];
395
+ this[key] = options[key];
396
+ }
397
+ if (this.start !== void 0) {
398
+ if ("number" !== typeof this.start) {
399
+ throw TypeError("start must be a Number");
400
+ }
401
+ if (this.start < 0) {
402
+ throw new Error("start must be >= zero");
403
+ }
404
+ this.pos = this.start;
405
+ }
406
+ this.busy = false;
407
+ this._queue = [];
408
+ if (this.fd === null) {
409
+ this._open = fs.open;
410
+ this._queue.push([this._open, this.path, this.flags, this.mode, void 0]);
411
+ this.flush();
412
+ }
413
+ }
414
+ }
415
+ }
416
+ });
417
+
418
+ // ../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/clone.js
419
+ var require_clone = __commonJS({
420
+ "../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/clone.js"(exports, module) {
421
+ "use strict";
422
+ module.exports = clone;
423
+ var getPrototypeOf = Object.getPrototypeOf || function(obj) {
424
+ return obj.__proto__;
425
+ };
426
+ function clone(obj) {
427
+ if (obj === null || typeof obj !== "object")
428
+ return obj;
429
+ if (obj instanceof Object)
430
+ var copy = { __proto__: getPrototypeOf(obj) };
431
+ else
432
+ var copy = /* @__PURE__ */ Object.create(null);
433
+ Object.getOwnPropertyNames(obj).forEach(function(key) {
434
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
435
+ });
436
+ return copy;
437
+ }
438
+ }
439
+ });
440
+
441
+ // ../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/graceful-fs.js
442
+ var require_graceful_fs = __commonJS({
443
+ "../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/graceful-fs.js"(exports, module) {
444
+ var fs = __require("fs");
445
+ var polyfills = require_polyfills();
446
+ var legacy = require_legacy_streams();
447
+ var clone = require_clone();
448
+ var util = __require("util");
449
+ var gracefulQueue;
450
+ var previousSymbol;
451
+ if (typeof Symbol === "function" && typeof Symbol.for === "function") {
452
+ gracefulQueue = /* @__PURE__ */ Symbol.for("graceful-fs.queue");
453
+ previousSymbol = /* @__PURE__ */ Symbol.for("graceful-fs.previous");
454
+ } else {
455
+ gracefulQueue = "___graceful-fs.queue";
456
+ previousSymbol = "___graceful-fs.previous";
457
+ }
458
+ function noop() {
459
+ }
460
+ function publishQueue(context, queue2) {
461
+ Object.defineProperty(context, gracefulQueue, {
462
+ get: function() {
463
+ return queue2;
464
+ }
465
+ });
466
+ }
467
+ var debug = noop;
468
+ if (util.debuglog)
469
+ debug = util.debuglog("gfs4");
470
+ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
471
+ debug = function() {
472
+ var m = util.format.apply(util, arguments);
473
+ m = "GFS4: " + m.split(/\n/).join("\nGFS4: ");
474
+ console.error(m);
475
+ };
476
+ if (!fs[gracefulQueue]) {
477
+ queue = global[gracefulQueue] || [];
478
+ publishQueue(fs, queue);
479
+ fs.close = (function(fs$close) {
480
+ function close(fd, cb) {
481
+ return fs$close.call(fs, fd, function(err) {
482
+ if (!err) {
483
+ resetQueue();
484
+ }
485
+ if (typeof cb === "function")
486
+ cb.apply(this, arguments);
487
+ });
488
+ }
489
+ Object.defineProperty(close, previousSymbol, {
490
+ value: fs$close
491
+ });
492
+ return close;
493
+ })(fs.close);
494
+ fs.closeSync = (function(fs$closeSync) {
495
+ function closeSync(fd) {
496
+ fs$closeSync.apply(fs, arguments);
497
+ resetQueue();
498
+ }
499
+ Object.defineProperty(closeSync, previousSymbol, {
500
+ value: fs$closeSync
501
+ });
502
+ return closeSync;
503
+ })(fs.closeSync);
504
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
505
+ process.on("exit", function() {
506
+ debug(fs[gracefulQueue]);
507
+ __require("assert").equal(fs[gracefulQueue].length, 0);
508
+ });
509
+ }
510
+ }
511
+ var queue;
512
+ if (!global[gracefulQueue]) {
513
+ publishQueue(global, fs[gracefulQueue]);
514
+ }
515
+ module.exports = patch(clone(fs));
516
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
517
+ module.exports = patch(fs);
518
+ fs.__patched = true;
519
+ }
520
+ function patch(fs2) {
521
+ polyfills(fs2);
522
+ fs2.gracefulify = patch;
523
+ fs2.createReadStream = createReadStream;
524
+ fs2.createWriteStream = createWriteStream;
525
+ var fs$readFile = fs2.readFile;
526
+ fs2.readFile = readFile3;
527
+ function readFile3(path2, options, cb) {
528
+ if (typeof options === "function")
529
+ cb = options, options = null;
530
+ return go$readFile(path2, options, cb);
531
+ function go$readFile(path3, options2, cb2, startTime) {
532
+ return fs$readFile(path3, options2, function(err) {
533
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
534
+ enqueue([go$readFile, [path3, options2, cb2], err, startTime || Date.now(), Date.now()]);
535
+ else {
536
+ if (typeof cb2 === "function")
537
+ cb2.apply(this, arguments);
538
+ }
539
+ });
540
+ }
541
+ }
542
+ var fs$writeFile = fs2.writeFile;
543
+ fs2.writeFile = writeFile;
544
+ function writeFile(path2, data, options, cb) {
545
+ if (typeof options === "function")
546
+ cb = options, options = null;
547
+ return go$writeFile(path2, data, options, cb);
548
+ function go$writeFile(path3, data2, options2, cb2, startTime) {
549
+ return fs$writeFile(path3, data2, options2, function(err) {
550
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
551
+ enqueue([go$writeFile, [path3, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
552
+ else {
553
+ if (typeof cb2 === "function")
554
+ cb2.apply(this, arguments);
555
+ }
556
+ });
557
+ }
558
+ }
559
+ var fs$appendFile = fs2.appendFile;
560
+ if (fs$appendFile)
561
+ fs2.appendFile = appendFile;
562
+ function appendFile(path2, data, options, cb) {
563
+ if (typeof options === "function")
564
+ cb = options, options = null;
565
+ return go$appendFile(path2, data, options, cb);
566
+ function go$appendFile(path3, data2, options2, cb2, startTime) {
567
+ return fs$appendFile(path3, data2, options2, function(err) {
568
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
569
+ enqueue([go$appendFile, [path3, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
570
+ else {
571
+ if (typeof cb2 === "function")
572
+ cb2.apply(this, arguments);
573
+ }
574
+ });
575
+ }
576
+ }
577
+ var fs$copyFile = fs2.copyFile;
578
+ if (fs$copyFile)
579
+ fs2.copyFile = copyFile;
580
+ function copyFile(src, dest, flags, cb) {
581
+ if (typeof flags === "function") {
582
+ cb = flags;
583
+ flags = 0;
584
+ }
585
+ return go$copyFile(src, dest, flags, cb);
586
+ function go$copyFile(src2, dest2, flags2, cb2, startTime) {
587
+ return fs$copyFile(src2, dest2, flags2, function(err) {
588
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
589
+ enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]);
590
+ else {
591
+ if (typeof cb2 === "function")
592
+ cb2.apply(this, arguments);
593
+ }
594
+ });
595
+ }
596
+ }
597
+ var fs$readdir = fs2.readdir;
598
+ fs2.readdir = readdir;
599
+ var noReaddirOptionVersions = /^v[0-5]\./;
600
+ function readdir(path2, options, cb) {
601
+ if (typeof options === "function")
602
+ cb = options, options = null;
603
+ var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path3, options2, cb2, startTime) {
604
+ return fs$readdir(path3, fs$readdirCallback(
605
+ path3,
606
+ options2,
607
+ cb2,
608
+ startTime
609
+ ));
610
+ } : function go$readdir2(path3, options2, cb2, startTime) {
611
+ return fs$readdir(path3, options2, fs$readdirCallback(
612
+ path3,
613
+ options2,
614
+ cb2,
615
+ startTime
616
+ ));
617
+ };
618
+ return go$readdir(path2, options, cb);
619
+ function fs$readdirCallback(path3, options2, cb2, startTime) {
620
+ return function(err, files) {
621
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
622
+ enqueue([
623
+ go$readdir,
624
+ [path3, options2, cb2],
625
+ err,
626
+ startTime || Date.now(),
627
+ Date.now()
628
+ ]);
629
+ else {
630
+ if (files && files.sort)
631
+ files.sort();
632
+ if (typeof cb2 === "function")
633
+ cb2.call(this, err, files);
634
+ }
635
+ };
636
+ }
637
+ }
638
+ if (process.version.substr(0, 4) === "v0.8") {
639
+ var legStreams = legacy(fs2);
640
+ ReadStream = legStreams.ReadStream;
641
+ WriteStream = legStreams.WriteStream;
642
+ }
643
+ var fs$ReadStream = fs2.ReadStream;
644
+ if (fs$ReadStream) {
645
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
646
+ ReadStream.prototype.open = ReadStream$open;
647
+ }
648
+ var fs$WriteStream = fs2.WriteStream;
649
+ if (fs$WriteStream) {
650
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
651
+ WriteStream.prototype.open = WriteStream$open;
652
+ }
653
+ Object.defineProperty(fs2, "ReadStream", {
654
+ get: function() {
655
+ return ReadStream;
656
+ },
657
+ set: function(val) {
658
+ ReadStream = val;
659
+ },
660
+ enumerable: true,
661
+ configurable: true
662
+ });
663
+ Object.defineProperty(fs2, "WriteStream", {
664
+ get: function() {
665
+ return WriteStream;
666
+ },
667
+ set: function(val) {
668
+ WriteStream = val;
669
+ },
670
+ enumerable: true,
671
+ configurable: true
672
+ });
673
+ var FileReadStream = ReadStream;
674
+ Object.defineProperty(fs2, "FileReadStream", {
675
+ get: function() {
676
+ return FileReadStream;
677
+ },
678
+ set: function(val) {
679
+ FileReadStream = val;
680
+ },
681
+ enumerable: true,
682
+ configurable: true
683
+ });
684
+ var FileWriteStream = WriteStream;
685
+ Object.defineProperty(fs2, "FileWriteStream", {
686
+ get: function() {
687
+ return FileWriteStream;
688
+ },
689
+ set: function(val) {
690
+ FileWriteStream = val;
691
+ },
692
+ enumerable: true,
693
+ configurable: true
694
+ });
695
+ function ReadStream(path2, options) {
696
+ if (this instanceof ReadStream)
697
+ return fs$ReadStream.apply(this, arguments), this;
698
+ else
699
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments);
700
+ }
701
+ function ReadStream$open() {
702
+ var that = this;
703
+ open(that.path, that.flags, that.mode, function(err, fd) {
704
+ if (err) {
705
+ if (that.autoClose)
706
+ that.destroy();
707
+ that.emit("error", err);
708
+ } else {
709
+ that.fd = fd;
710
+ that.emit("open", fd);
711
+ that.read();
712
+ }
713
+ });
714
+ }
715
+ function WriteStream(path2, options) {
716
+ if (this instanceof WriteStream)
717
+ return fs$WriteStream.apply(this, arguments), this;
718
+ else
719
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments);
720
+ }
721
+ function WriteStream$open() {
722
+ var that = this;
723
+ open(that.path, that.flags, that.mode, function(err, fd) {
724
+ if (err) {
725
+ that.destroy();
726
+ that.emit("error", err);
727
+ } else {
728
+ that.fd = fd;
729
+ that.emit("open", fd);
730
+ }
731
+ });
732
+ }
733
+ function createReadStream(path2, options) {
734
+ return new fs2.ReadStream(path2, options);
735
+ }
736
+ function createWriteStream(path2, options) {
737
+ return new fs2.WriteStream(path2, options);
738
+ }
739
+ var fs$open = fs2.open;
740
+ fs2.open = open;
741
+ function open(path2, flags, mode, cb) {
742
+ if (typeof mode === "function")
743
+ cb = mode, mode = null;
744
+ return go$open(path2, flags, mode, cb);
745
+ function go$open(path3, flags2, mode2, cb2, startTime) {
746
+ return fs$open(path3, flags2, mode2, function(err, fd) {
747
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
748
+ enqueue([go$open, [path3, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
749
+ else {
750
+ if (typeof cb2 === "function")
751
+ cb2.apply(this, arguments);
752
+ }
753
+ });
754
+ }
755
+ }
756
+ return fs2;
757
+ }
758
+ function enqueue(elem) {
759
+ debug("ENQUEUE", elem[0].name, elem[1]);
760
+ fs[gracefulQueue].push(elem);
761
+ retry();
762
+ }
763
+ var retryTimer;
764
+ function resetQueue() {
765
+ var now = Date.now();
766
+ for (var i = 0; i < fs[gracefulQueue].length; ++i) {
767
+ if (fs[gracefulQueue][i].length > 2) {
768
+ fs[gracefulQueue][i][3] = now;
769
+ fs[gracefulQueue][i][4] = now;
770
+ }
771
+ }
772
+ retry();
773
+ }
774
+ function retry() {
775
+ clearTimeout(retryTimer);
776
+ retryTimer = void 0;
777
+ if (fs[gracefulQueue].length === 0)
778
+ return;
779
+ var elem = fs[gracefulQueue].shift();
780
+ var fn = elem[0];
781
+ var args = elem[1];
782
+ var err = elem[2];
783
+ var startTime = elem[3];
784
+ var lastTime = elem[4];
785
+ if (startTime === void 0) {
786
+ debug("RETRY", fn.name, args);
787
+ fn.apply(null, args);
788
+ } else if (Date.now() - startTime >= 6e4) {
789
+ debug("TIMEOUT", fn.name, args);
790
+ var cb = args.pop();
791
+ if (typeof cb === "function")
792
+ cb.call(null, err);
793
+ } else {
794
+ var sinceAttempt = Date.now() - lastTime;
795
+ var sinceStart = Math.max(lastTime - startTime, 1);
796
+ var desiredDelay = Math.min(sinceStart * 1.2, 100);
797
+ if (sinceAttempt >= desiredDelay) {
798
+ debug("RETRY", fn.name, args);
799
+ fn.apply(null, args.concat([startTime]));
800
+ } else {
801
+ fs[gracefulQueue].push(elem);
802
+ }
803
+ }
804
+ if (retryTimer === void 0) {
805
+ retryTimer = setTimeout(retry, 0);
806
+ }
807
+ }
808
+ }
809
+ });
810
+
811
+ // ../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/lib/retry_operation.js
812
+ var require_retry_operation = __commonJS({
813
+ "../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/lib/retry_operation.js"(exports, module) {
814
+ function RetryOperation(timeouts, options) {
815
+ if (typeof options === "boolean") {
816
+ options = { forever: options };
817
+ }
818
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
819
+ this._timeouts = timeouts;
820
+ this._options = options || {};
821
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
822
+ this._fn = null;
823
+ this._errors = [];
824
+ this._attempts = 1;
825
+ this._operationTimeout = null;
826
+ this._operationTimeoutCb = null;
827
+ this._timeout = null;
828
+ this._operationStart = null;
829
+ if (this._options.forever) {
830
+ this._cachedTimeouts = this._timeouts.slice(0);
831
+ }
832
+ }
833
+ module.exports = RetryOperation;
834
+ RetryOperation.prototype.reset = function() {
835
+ this._attempts = 1;
836
+ this._timeouts = this._originalTimeouts;
837
+ };
838
+ RetryOperation.prototype.stop = function() {
839
+ if (this._timeout) {
840
+ clearTimeout(this._timeout);
841
+ }
842
+ this._timeouts = [];
843
+ this._cachedTimeouts = null;
844
+ };
845
+ RetryOperation.prototype.retry = function(err) {
846
+ if (this._timeout) {
847
+ clearTimeout(this._timeout);
848
+ }
849
+ if (!err) {
850
+ return false;
851
+ }
852
+ var currentTime = (/* @__PURE__ */ new Date()).getTime();
853
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
854
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
855
+ return false;
856
+ }
857
+ this._errors.push(err);
858
+ var timeout2 = this._timeouts.shift();
859
+ if (timeout2 === void 0) {
860
+ if (this._cachedTimeouts) {
861
+ this._errors.splice(this._errors.length - 1, this._errors.length);
862
+ this._timeouts = this._cachedTimeouts.slice(0);
863
+ timeout2 = this._timeouts.shift();
864
+ } else {
865
+ return false;
866
+ }
867
+ }
868
+ var self = this;
869
+ var timer = setTimeout(function() {
870
+ self._attempts++;
871
+ if (self._operationTimeoutCb) {
872
+ self._timeout = setTimeout(function() {
873
+ self._operationTimeoutCb(self._attempts);
874
+ }, self._operationTimeout);
875
+ if (self._options.unref) {
876
+ self._timeout.unref();
877
+ }
878
+ }
879
+ self._fn(self._attempts);
880
+ }, timeout2);
881
+ if (this._options.unref) {
882
+ timer.unref();
883
+ }
884
+ return true;
885
+ };
886
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
887
+ this._fn = fn;
888
+ if (timeoutOps) {
889
+ if (timeoutOps.timeout) {
890
+ this._operationTimeout = timeoutOps.timeout;
891
+ }
892
+ if (timeoutOps.cb) {
893
+ this._operationTimeoutCb = timeoutOps.cb;
894
+ }
895
+ }
896
+ var self = this;
897
+ if (this._operationTimeoutCb) {
898
+ this._timeout = setTimeout(function() {
899
+ self._operationTimeoutCb();
900
+ }, self._operationTimeout);
901
+ }
902
+ this._operationStart = (/* @__PURE__ */ new Date()).getTime();
903
+ this._fn(this._attempts);
904
+ };
905
+ RetryOperation.prototype.try = function(fn) {
906
+ console.log("Using RetryOperation.try() is deprecated");
907
+ this.attempt(fn);
908
+ };
909
+ RetryOperation.prototype.start = function(fn) {
910
+ console.log("Using RetryOperation.start() is deprecated");
911
+ this.attempt(fn);
912
+ };
913
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
914
+ RetryOperation.prototype.errors = function() {
915
+ return this._errors;
916
+ };
917
+ RetryOperation.prototype.attempts = function() {
918
+ return this._attempts;
919
+ };
920
+ RetryOperation.prototype.mainError = function() {
921
+ if (this._errors.length === 0) {
922
+ return null;
923
+ }
924
+ var counts = {};
925
+ var mainError = null;
926
+ var mainErrorCount = 0;
927
+ for (var i = 0; i < this._errors.length; i++) {
928
+ var error = this._errors[i];
929
+ var message = error.message;
930
+ var count3 = (counts[message] || 0) + 1;
931
+ counts[message] = count3;
932
+ if (count3 >= mainErrorCount) {
933
+ mainError = error;
934
+ mainErrorCount = count3;
935
+ }
936
+ }
937
+ return mainError;
938
+ };
939
+ }
940
+ });
941
+
942
+ // ../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/lib/retry.js
943
+ var require_retry = __commonJS({
944
+ "../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/lib/retry.js"(exports) {
945
+ var RetryOperation = require_retry_operation();
946
+ exports.operation = function(options) {
947
+ var timeouts = exports.timeouts(options);
948
+ return new RetryOperation(timeouts, {
949
+ forever: options && options.forever,
950
+ unref: options && options.unref,
951
+ maxRetryTime: options && options.maxRetryTime
952
+ });
953
+ };
954
+ exports.timeouts = function(options) {
955
+ if (options instanceof Array) {
956
+ return [].concat(options);
957
+ }
958
+ var opts = {
959
+ retries: 10,
960
+ factor: 2,
961
+ minTimeout: 1 * 1e3,
962
+ maxTimeout: Infinity,
963
+ randomize: false
964
+ };
965
+ for (var key in options) {
966
+ opts[key] = options[key];
967
+ }
968
+ if (opts.minTimeout > opts.maxTimeout) {
969
+ throw new Error("minTimeout is greater than maxTimeout");
970
+ }
971
+ var timeouts = [];
972
+ for (var i = 0; i < opts.retries; i++) {
973
+ timeouts.push(this.createTimeout(i, opts));
974
+ }
975
+ if (options && options.forever && !timeouts.length) {
976
+ timeouts.push(this.createTimeout(i, opts));
977
+ }
978
+ timeouts.sort(function(a, b) {
979
+ return a - b;
980
+ });
981
+ return timeouts;
982
+ };
983
+ exports.createTimeout = function(attempt, opts) {
984
+ var random = opts.randomize ? Math.random() + 1 : 1;
985
+ var timeout2 = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
986
+ timeout2 = Math.min(timeout2, opts.maxTimeout);
987
+ return timeout2;
988
+ };
989
+ exports.wrap = function(obj, options, methods) {
990
+ if (options instanceof Array) {
991
+ methods = options;
992
+ options = null;
993
+ }
994
+ if (!methods) {
995
+ methods = [];
996
+ for (var key in obj) {
997
+ if (typeof obj[key] === "function") {
998
+ methods.push(key);
999
+ }
1000
+ }
1001
+ }
1002
+ for (var i = 0; i < methods.length; i++) {
1003
+ var method = methods[i];
1004
+ var original = obj[method];
1005
+ obj[method] = function retryWrapper(original2) {
1006
+ var op = exports.operation(options);
1007
+ var args = Array.prototype.slice.call(arguments, 1);
1008
+ var callback = args.pop();
1009
+ args.push(function(err) {
1010
+ if (op.retry(err)) {
1011
+ return;
1012
+ }
1013
+ if (err) {
1014
+ arguments[0] = op.mainError();
1015
+ }
1016
+ callback.apply(this, arguments);
1017
+ });
1018
+ op.attempt(function() {
1019
+ original2.apply(obj, args);
1020
+ });
1021
+ }.bind(obj, original);
1022
+ obj[method].options = options;
1023
+ }
1024
+ };
1025
+ }
1026
+ });
1027
+
1028
+ // ../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/index.js
1029
+ var require_retry2 = __commonJS({
1030
+ "../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/index.js"(exports, module) {
1031
+ module.exports = require_retry();
1032
+ }
1033
+ });
1034
+
1035
+ // ../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/signals.js
1036
+ var require_signals = __commonJS({
1037
+ "../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/signals.js"(exports, module) {
1038
+ module.exports = [
1039
+ "SIGABRT",
1040
+ "SIGALRM",
1041
+ "SIGHUP",
1042
+ "SIGINT",
1043
+ "SIGTERM"
1044
+ ];
1045
+ if (process.platform !== "win32") {
1046
+ module.exports.push(
1047
+ "SIGVTALRM",
1048
+ "SIGXCPU",
1049
+ "SIGXFSZ",
1050
+ "SIGUSR2",
1051
+ "SIGTRAP",
1052
+ "SIGSYS",
1053
+ "SIGQUIT",
1054
+ "SIGIOT"
1055
+ // should detect profiler and enable/disable accordingly.
1056
+ // see #21
1057
+ // 'SIGPROF'
1058
+ );
1059
+ }
1060
+ if (process.platform === "linux") {
1061
+ module.exports.push(
1062
+ "SIGIO",
1063
+ "SIGPOLL",
1064
+ "SIGPWR",
1065
+ "SIGSTKFLT",
1066
+ "SIGUNUSED"
1067
+ );
1068
+ }
1069
+ }
1070
+ });
1071
+
1072
+ // ../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/index.js
1073
+ var require_signal_exit = __commonJS({
1074
+ "../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/index.js"(exports, module) {
1075
+ var process2 = global.process;
1076
+ var processOk = function(process3) {
1077
+ return process3 && typeof process3 === "object" && typeof process3.removeListener === "function" && typeof process3.emit === "function" && typeof process3.reallyExit === "function" && typeof process3.listeners === "function" && typeof process3.kill === "function" && typeof process3.pid === "number" && typeof process3.on === "function";
1078
+ };
1079
+ if (!processOk(process2)) {
1080
+ module.exports = function() {
1081
+ return function() {
1082
+ };
1083
+ };
1084
+ } else {
1085
+ assert = __require("assert");
1086
+ signals = require_signals();
1087
+ isWin = /^win/i.test(process2.platform);
1088
+ EE = __require("events");
1089
+ if (typeof EE !== "function") {
1090
+ EE = EE.EventEmitter;
1091
+ }
1092
+ if (process2.__signal_exit_emitter__) {
1093
+ emitter = process2.__signal_exit_emitter__;
1094
+ } else {
1095
+ emitter = process2.__signal_exit_emitter__ = new EE();
1096
+ emitter.count = 0;
1097
+ emitter.emitted = {};
1098
+ }
1099
+ if (!emitter.infinite) {
1100
+ emitter.setMaxListeners(Infinity);
1101
+ emitter.infinite = true;
1102
+ }
1103
+ module.exports = function(cb, opts) {
1104
+ if (!processOk(global.process)) {
1105
+ return function() {
1106
+ };
1107
+ }
1108
+ assert.equal(typeof cb, "function", "a callback must be provided for exit handler");
1109
+ if (loaded === false) {
1110
+ load();
1111
+ }
1112
+ var ev = "exit";
1113
+ if (opts && opts.alwaysLast) {
1114
+ ev = "afterexit";
1115
+ }
1116
+ var remove = function() {
1117
+ emitter.removeListener(ev, cb);
1118
+ if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
1119
+ unload();
1120
+ }
1121
+ };
1122
+ emitter.on(ev, cb);
1123
+ return remove;
1124
+ };
1125
+ unload = function unload2() {
1126
+ if (!loaded || !processOk(global.process)) {
1127
+ return;
1128
+ }
1129
+ loaded = false;
1130
+ signals.forEach(function(sig) {
1131
+ try {
1132
+ process2.removeListener(sig, sigListeners[sig]);
1133
+ } catch (er) {
1134
+ }
1135
+ });
1136
+ process2.emit = originalProcessEmit;
1137
+ process2.reallyExit = originalProcessReallyExit;
1138
+ emitter.count -= 1;
1139
+ };
1140
+ module.exports.unload = unload;
1141
+ emit = function emit2(event, code, signal) {
1142
+ if (emitter.emitted[event]) {
1143
+ return;
1144
+ }
1145
+ emitter.emitted[event] = true;
1146
+ emitter.emit(event, code, signal);
1147
+ };
1148
+ sigListeners = {};
1149
+ signals.forEach(function(sig) {
1150
+ sigListeners[sig] = function listener() {
1151
+ if (!processOk(global.process)) {
1152
+ return;
1153
+ }
1154
+ var listeners = process2.listeners(sig);
1155
+ if (listeners.length === emitter.count) {
1156
+ unload();
1157
+ emit("exit", null, sig);
1158
+ emit("afterexit", null, sig);
1159
+ if (isWin && sig === "SIGHUP") {
1160
+ sig = "SIGINT";
1161
+ }
1162
+ process2.kill(process2.pid, sig);
1163
+ }
1164
+ };
1165
+ });
1166
+ module.exports.signals = function() {
1167
+ return signals;
1168
+ };
1169
+ loaded = false;
1170
+ load = function load2() {
1171
+ if (loaded || !processOk(global.process)) {
1172
+ return;
1173
+ }
1174
+ loaded = true;
1175
+ emitter.count += 1;
1176
+ signals = signals.filter(function(sig) {
1177
+ try {
1178
+ process2.on(sig, sigListeners[sig]);
1179
+ return true;
1180
+ } catch (er) {
1181
+ return false;
1182
+ }
1183
+ });
1184
+ process2.emit = processEmit;
1185
+ process2.reallyExit = processReallyExit;
1186
+ };
1187
+ module.exports.load = load;
1188
+ originalProcessReallyExit = process2.reallyExit;
1189
+ processReallyExit = function processReallyExit2(code) {
1190
+ if (!processOk(global.process)) {
1191
+ return;
1192
+ }
1193
+ process2.exitCode = code || /* istanbul ignore next */
1194
+ 0;
1195
+ emit("exit", process2.exitCode, null);
1196
+ emit("afterexit", process2.exitCode, null);
1197
+ originalProcessReallyExit.call(process2, process2.exitCode);
1198
+ };
1199
+ originalProcessEmit = process2.emit;
1200
+ processEmit = function processEmit2(ev, arg) {
1201
+ if (ev === "exit" && processOk(global.process)) {
1202
+ if (arg !== void 0) {
1203
+ process2.exitCode = arg;
1204
+ }
1205
+ var ret = originalProcessEmit.apply(this, arguments);
1206
+ emit("exit", process2.exitCode, null);
1207
+ emit("afterexit", process2.exitCode, null);
1208
+ return ret;
1209
+ } else {
1210
+ return originalProcessEmit.apply(this, arguments);
1211
+ }
1212
+ };
1213
+ }
1214
+ var assert;
1215
+ var signals;
1216
+ var isWin;
1217
+ var EE;
1218
+ var emitter;
1219
+ var unload;
1220
+ var emit;
1221
+ var sigListeners;
1222
+ var loaded;
1223
+ var load;
1224
+ var originalProcessReallyExit;
1225
+ var processReallyExit;
1226
+ var originalProcessEmit;
1227
+ var processEmit;
1228
+ }
1229
+ });
1230
+
1231
+ // ../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/mtime-precision.js
1232
+ var require_mtime_precision = __commonJS({
1233
+ "../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/mtime-precision.js"(exports, module) {
1234
+ "use strict";
1235
+ var cacheSymbol = /* @__PURE__ */ Symbol();
1236
+ function probe2(file, fs, callback) {
1237
+ const cachedPrecision = fs[cacheSymbol];
1238
+ if (cachedPrecision) {
1239
+ return fs.stat(file, (err, stat) => {
1240
+ if (err) {
1241
+ return callback(err);
1242
+ }
1243
+ callback(null, stat.mtime, cachedPrecision);
1244
+ });
1245
+ }
1246
+ const mtime = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5);
1247
+ fs.utimes(file, mtime, mtime, (err) => {
1248
+ if (err) {
1249
+ return callback(err);
1250
+ }
1251
+ fs.stat(file, (err2, stat) => {
1252
+ if (err2) {
1253
+ return callback(err2);
1254
+ }
1255
+ const precision = stat.mtime.getTime() % 1e3 === 0 ? "s" : "ms";
1256
+ Object.defineProperty(fs, cacheSymbol, { value: precision });
1257
+ callback(null, stat.mtime, precision);
1258
+ });
1259
+ });
1260
+ }
1261
+ function getMtime(precision) {
1262
+ let now = Date.now();
1263
+ if (precision === "s") {
1264
+ now = Math.ceil(now / 1e3) * 1e3;
1265
+ }
1266
+ return new Date(now);
1267
+ }
1268
+ module.exports.probe = probe2;
1269
+ module.exports.getMtime = getMtime;
1270
+ }
1271
+ });
1272
+
1273
+ // ../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/lockfile.js
1274
+ var require_lockfile = __commonJS({
1275
+ "../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/lockfile.js"(exports, module) {
1276
+ "use strict";
1277
+ var path2 = __require("path");
1278
+ var fs = require_graceful_fs();
1279
+ var retry = require_retry2();
1280
+ var onExit = require_signal_exit();
1281
+ var mtimePrecision = require_mtime_precision();
1282
+ var locks = {};
1283
+ function getLockFile(file, options) {
1284
+ return options.lockfilePath || `${file}.lock`;
1285
+ }
1286
+ function resolveCanonicalPath(file, options, callback) {
1287
+ if (!options.realpath) {
1288
+ return callback(null, path2.resolve(file));
1289
+ }
1290
+ options.fs.realpath(file, callback);
1291
+ }
1292
+ function acquireLock(file, options, callback) {
1293
+ const lockfilePath = getLockFile(file, options);
1294
+ options.fs.mkdir(lockfilePath, (err) => {
1295
+ if (!err) {
1296
+ return mtimePrecision.probe(lockfilePath, options.fs, (err2, mtime, mtimePrecision2) => {
1297
+ if (err2) {
1298
+ options.fs.rmdir(lockfilePath, () => {
1299
+ });
1300
+ return callback(err2);
1301
+ }
1302
+ callback(null, mtime, mtimePrecision2);
1303
+ });
1304
+ }
1305
+ if (err.code !== "EEXIST") {
1306
+ return callback(err);
1307
+ }
1308
+ if (options.stale <= 0) {
1309
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1310
+ }
1311
+ options.fs.stat(lockfilePath, (err2, stat) => {
1312
+ if (err2) {
1313
+ if (err2.code === "ENOENT") {
1314
+ return acquireLock(file, { ...options, stale: 0 }, callback);
1315
+ }
1316
+ return callback(err2);
1317
+ }
1318
+ if (!isLockStale(stat, options)) {
1319
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1320
+ }
1321
+ removeLock(file, options, (err3) => {
1322
+ if (err3) {
1323
+ return callback(err3);
1324
+ }
1325
+ acquireLock(file, { ...options, stale: 0 }, callback);
1326
+ });
1327
+ });
1328
+ });
1329
+ }
1330
+ function isLockStale(stat, options) {
1331
+ return stat.mtime.getTime() < Date.now() - options.stale;
1332
+ }
1333
+ function removeLock(file, options, callback) {
1334
+ options.fs.rmdir(getLockFile(file, options), (err) => {
1335
+ if (err && err.code !== "ENOENT") {
1336
+ return callback(err);
1337
+ }
1338
+ callback();
1339
+ });
1340
+ }
1341
+ function updateLock(file, options) {
1342
+ const lock3 = locks[file];
1343
+ if (lock3.updateTimeout) {
1344
+ return;
1345
+ }
1346
+ lock3.updateDelay = lock3.updateDelay || options.update;
1347
+ lock3.updateTimeout = setTimeout(() => {
1348
+ lock3.updateTimeout = null;
1349
+ options.fs.stat(lock3.lockfilePath, (err, stat) => {
1350
+ const isOverThreshold = lock3.lastUpdate + options.stale < Date.now();
1351
+ if (err) {
1352
+ if (err.code === "ENOENT" || isOverThreshold) {
1353
+ return setLockAsCompromised(file, lock3, Object.assign(err, { code: "ECOMPROMISED" }));
1354
+ }
1355
+ lock3.updateDelay = 1e3;
1356
+ return updateLock(file, options);
1357
+ }
1358
+ const isMtimeOurs = lock3.mtime.getTime() === stat.mtime.getTime();
1359
+ if (!isMtimeOurs) {
1360
+ return setLockAsCompromised(
1361
+ file,
1362
+ lock3,
1363
+ Object.assign(
1364
+ new Error("Unable to update lock within the stale threshold"),
1365
+ { code: "ECOMPROMISED" }
1366
+ )
1367
+ );
1368
+ }
1369
+ const mtime = mtimePrecision.getMtime(lock3.mtimePrecision);
1370
+ options.fs.utimes(lock3.lockfilePath, mtime, mtime, (err2) => {
1371
+ const isOverThreshold2 = lock3.lastUpdate + options.stale < Date.now();
1372
+ if (lock3.released) {
1373
+ return;
1374
+ }
1375
+ if (err2) {
1376
+ if (err2.code === "ENOENT" || isOverThreshold2) {
1377
+ return setLockAsCompromised(file, lock3, Object.assign(err2, { code: "ECOMPROMISED" }));
1378
+ }
1379
+ lock3.updateDelay = 1e3;
1380
+ return updateLock(file, options);
1381
+ }
1382
+ lock3.mtime = mtime;
1383
+ lock3.lastUpdate = Date.now();
1384
+ lock3.updateDelay = null;
1385
+ updateLock(file, options);
1386
+ });
1387
+ });
1388
+ }, lock3.updateDelay);
1389
+ if (lock3.updateTimeout.unref) {
1390
+ lock3.updateTimeout.unref();
1391
+ }
1392
+ }
1393
+ function setLockAsCompromised(file, lock3, err) {
1394
+ lock3.released = true;
1395
+ if (lock3.updateTimeout) {
1396
+ clearTimeout(lock3.updateTimeout);
1397
+ }
1398
+ if (locks[file] === lock3) {
1399
+ delete locks[file];
1400
+ }
1401
+ lock3.options.onCompromised(err);
1402
+ }
1403
+ function lock2(file, options, callback) {
1404
+ options = {
1405
+ stale: 1e4,
1406
+ update: null,
1407
+ realpath: true,
1408
+ retries: 0,
1409
+ fs,
1410
+ onCompromised: (err) => {
1411
+ throw err;
1412
+ },
1413
+ ...options
1414
+ };
1415
+ options.retries = options.retries || 0;
1416
+ options.retries = typeof options.retries === "number" ? { retries: options.retries } : options.retries;
1417
+ options.stale = Math.max(options.stale || 0, 2e3);
1418
+ options.update = options.update == null ? options.stale / 2 : options.update || 0;
1419
+ options.update = Math.max(Math.min(options.update, options.stale / 2), 1e3);
1420
+ resolveCanonicalPath(file, options, (err, file2) => {
1421
+ if (err) {
1422
+ return callback(err);
1423
+ }
1424
+ const operation = retry.operation(options.retries);
1425
+ operation.attempt(() => {
1426
+ acquireLock(file2, options, (err2, mtime, mtimePrecision2) => {
1427
+ if (operation.retry(err2)) {
1428
+ return;
1429
+ }
1430
+ if (err2) {
1431
+ return callback(operation.mainError());
1432
+ }
1433
+ const lock3 = locks[file2] = {
1434
+ lockfilePath: getLockFile(file2, options),
1435
+ mtime,
1436
+ mtimePrecision: mtimePrecision2,
1437
+ options,
1438
+ lastUpdate: Date.now()
1439
+ };
1440
+ updateLock(file2, options);
1441
+ callback(null, (releasedCallback) => {
1442
+ if (lock3.released) {
1443
+ return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" }));
1444
+ }
1445
+ unlock(file2, { ...options, realpath: false }, releasedCallback);
1446
+ });
1447
+ });
1448
+ });
1449
+ });
1450
+ }
1451
+ function unlock(file, options, callback) {
1452
+ options = {
1453
+ fs,
1454
+ realpath: true,
1455
+ ...options
1456
+ };
1457
+ resolveCanonicalPath(file, options, (err, file2) => {
1458
+ if (err) {
1459
+ return callback(err);
1460
+ }
1461
+ const lock3 = locks[file2];
1462
+ if (!lock3) {
1463
+ return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" }));
1464
+ }
1465
+ lock3.updateTimeout && clearTimeout(lock3.updateTimeout);
1466
+ lock3.released = true;
1467
+ delete locks[file2];
1468
+ removeLock(file2, options, callback);
1469
+ });
1470
+ }
1471
+ function check(file, options, callback) {
1472
+ options = {
1473
+ stale: 1e4,
1474
+ realpath: true,
1475
+ fs,
1476
+ ...options
1477
+ };
1478
+ options.stale = Math.max(options.stale || 0, 2e3);
1479
+ resolveCanonicalPath(file, options, (err, file2) => {
1480
+ if (err) {
1481
+ return callback(err);
1482
+ }
1483
+ options.fs.stat(getLockFile(file2, options), (err2, stat) => {
1484
+ if (err2) {
1485
+ return err2.code === "ENOENT" ? callback(null, false) : callback(err2);
1486
+ }
1487
+ return callback(null, !isLockStale(stat, options));
1488
+ });
1489
+ });
1490
+ }
1491
+ function getLocks() {
1492
+ return locks;
1493
+ }
1494
+ onExit(() => {
1495
+ for (const file in locks) {
1496
+ const options = locks[file].options;
1497
+ try {
1498
+ options.fs.rmdirSync(getLockFile(file, options));
1499
+ } catch (e) {
1500
+ }
1501
+ }
1502
+ });
1503
+ module.exports.lock = lock2;
1504
+ module.exports.unlock = unlock;
1505
+ module.exports.check = check;
1506
+ module.exports.getLocks = getLocks;
1507
+ }
1508
+ });
1509
+
1510
+ // ../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/adapter.js
1511
+ var require_adapter = __commonJS({
1512
+ "../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/adapter.js"(exports, module) {
1513
+ "use strict";
1514
+ var fs = require_graceful_fs();
1515
+ function createSyncFs(fs2) {
1516
+ const methods = ["mkdir", "realpath", "stat", "rmdir", "utimes"];
1517
+ const newFs = { ...fs2 };
1518
+ methods.forEach((method) => {
1519
+ newFs[method] = (...args) => {
1520
+ const callback = args.pop();
1521
+ let ret;
1522
+ try {
1523
+ ret = fs2[`${method}Sync`](...args);
1524
+ } catch (err) {
1525
+ return callback(err);
1526
+ }
1527
+ callback(null, ret);
1528
+ };
1529
+ });
1530
+ return newFs;
1531
+ }
1532
+ function toPromise(method) {
1533
+ return (...args) => new Promise((resolve5, reject) => {
1534
+ args.push((err, result) => {
1535
+ if (err) {
1536
+ reject(err);
1537
+ } else {
1538
+ resolve5(result);
1539
+ }
1540
+ });
1541
+ method(...args);
1542
+ });
1543
+ }
1544
+ function toSync(method) {
1545
+ return (...args) => {
1546
+ let err;
1547
+ let result;
1548
+ args.push((_err, _result) => {
1549
+ err = _err;
1550
+ result = _result;
1551
+ });
1552
+ method(...args);
1553
+ if (err) {
1554
+ throw err;
1555
+ }
1556
+ return result;
1557
+ };
1558
+ }
1559
+ function toSyncOptions(options) {
1560
+ options = { ...options };
1561
+ options.fs = createSyncFs(options.fs || fs);
1562
+ if (typeof options.retries === "number" && options.retries > 0 || options.retries && typeof options.retries.retries === "number" && options.retries.retries > 0) {
1563
+ throw Object.assign(new Error("Cannot use retries with the sync api"), { code: "ESYNC" });
1564
+ }
1565
+ return options;
1566
+ }
1567
+ module.exports = {
1568
+ toPromise,
1569
+ toSync,
1570
+ toSyncOptions
1571
+ };
1572
+ }
1573
+ });
1574
+
1575
+ // ../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/index.js
1576
+ var require_proper_lockfile = __commonJS({
1577
+ "../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/index.js"(exports, module) {
1578
+ "use strict";
1579
+ var lockfile = require_lockfile();
1580
+ var { toPromise, toSync, toSyncOptions } = require_adapter();
1581
+ async function lock2(file, options) {
1582
+ const release = await toPromise(lockfile.lock)(file, options);
1583
+ return toPromise(release);
1584
+ }
1585
+ function lockSync(file, options) {
1586
+ const release = toSync(lockfile.lock)(file, toSyncOptions(options));
1587
+ return toSync(release);
1588
+ }
1589
+ function unlock(file, options) {
1590
+ return toPromise(lockfile.unlock)(file, options);
1591
+ }
1592
+ function unlockSync(file, options) {
1593
+ return toSync(lockfile.unlock)(file, toSyncOptions(options));
1594
+ }
1595
+ function check(file, options) {
1596
+ return toPromise(lockfile.check)(file, options);
1597
+ }
1598
+ function checkSync(file, options) {
1599
+ return toSync(lockfile.check)(file, toSyncOptions(options));
1600
+ }
1601
+ module.exports = lock2;
1602
+ module.exports.lock = lock2;
1603
+ module.exports.unlock = unlock;
1604
+ module.exports.lockSync = lockSync;
1605
+ module.exports.unlockSync = unlockSync;
1606
+ module.exports.check = check;
1607
+ module.exports.checkSync = checkSync;
1608
+ }
1609
+ });
1610
+
1611
+ // src/service/service.ts
1612
+ import { access, realpath, unlink } from "node:fs/promises";
1613
+ import { basename as basename2, dirname as dirname3, join as join2, resolve as resolve4 } from "node:path";
1614
+ import { setTimeout as sleep2 } from "node:timers/promises";
1615
+
1616
+ // ../host-config/src/storage/paths.ts
1617
+ import { basename, isAbsolute, join, parse, resolve } from "node:path";
1618
+ import { userInfo } from "node:os";
1619
+ var PROJECT_CONFIG_DIR_NAME = ".bobannomi";
1620
+ function requireAbsoluteDataRoot(path2, source = "dataRoot") {
1621
+ const incompleteWindowsPath = process.platform === "win32" && (parse(path2).root.length === 1 || /^[\\/]{2}[?.][\\/]/.test(path2));
1622
+ if (!isAbsolute(path2) || incompleteWindowsPath) {
1623
+ throw new Error(`${source} \u5FC5\u987B\u662F\u5B8C\u6574\u7EDD\u5BF9\u8DEF\u5F84\u3002`);
1624
+ }
1625
+ return resolve(path2);
1626
+ }
1627
+ function selectDataRoot(explicit, env = process.env) {
1628
+ if (explicit !== void 0) return requireAbsoluteDataRoot(explicit, "--data-root");
1629
+ if (env.BOBANNOMI_CONFIG_DIR !== void 0) return requireAbsoluteDataRoot(env.BOBANNOMI_CONFIG_DIR, "BOBANNOMI_CONFIG_DIR");
1630
+ const home = (process.platform === "win32" ? env.USERPROFILE : env.HOME) ?? userInfo().homedir;
1631
+ return join(requireAbsoluteDataRoot(home, "\u7528\u6237\u4E3B\u76EE\u5F55"), PROJECT_CONFIG_DIR_NAME);
1632
+ }
1633
+ function resolveUserDataPaths(dataRoot) {
1634
+ const dataDir = join(dataRoot, "data");
1635
+ const workspacesDir = join(dataDir, "workspaces");
1636
+ return {
1637
+ dataRoot,
1638
+ configDir: dataRoot,
1639
+ dataDir,
1640
+ logsDir: join(dataDir, "logs"),
1641
+ sessionsDir: join(dataDir, "sessions"),
1642
+ pluginsDir: join(dataRoot, "plugins"),
1643
+ skillsDir: join(dataRoot, "skills"),
1644
+ tasksDir: join(dataDir, "tasks"),
1645
+ feedbackDir: join(dataDir, "feedback"),
1646
+ configFilePath: join(dataRoot, "settings.json"),
1647
+ credentialsFilePath: join(dataRoot, "credentials.json"),
1648
+ mcpOAuthFilePath: join(dataRoot, "mcp-oauth.json"),
1649
+ channelCredentialsFilePath: join(dataRoot, "channel-credentials.json"),
1650
+ runtimeSecretsFilePath: join(dataRoot, "runtime-environment-secrets.json"),
1651
+ userProfilePath: join(dataRoot, "USER.md"),
1652
+ soulFilePath: join(dataRoot, "SOUL.md"),
1653
+ outputStylesDir: join(dataRoot, "output_styles"),
1654
+ localRulesDir: join(dataRoot, "local_rules"),
1655
+ frecencyFilePath: join(dataRoot, "frecency.json"),
1656
+ desktopDir: join(dataRoot, "desktop"),
1657
+ desktopSessionDir: join(dataRoot, "desktop", "session"),
1658
+ platformDir: join(dataDir, "app-platform"),
1659
+ tempDir: join(dataRoot, "cache", "tmp"),
1660
+ channelsDir: join(dataRoot, "channels"),
1661
+ workspacesDir,
1662
+ privateSessionsDir: join(workspacesDir, "private-sessions"),
1663
+ worktreesDir: join(dataRoot, "worktrees"),
1664
+ sessionsDatabasePath: join(dataDir, "session-runtime", "sessions.db"),
1665
+ daemonRegistryPath: join(dataDir, "daemon", "registry.json"),
1666
+ imageAttachmentCacheDir: join(dataDir, "attachments", "images")
1667
+ };
1668
+ }
1669
+ function splitStoragePaths(paths) {
1670
+ return {
1671
+ BOBANNOMI_DATA_DIR: paths.dataDir,
1672
+ BOBANNOMI_DAEMON_STORE_PATH: paths.sessionsDatabasePath,
1673
+ BOBANNOMI_CHANNELS_DIR: paths.channelsDir,
1674
+ BOBANNOMI_IMAGE_ATTACHMENT_CACHE_DIR: paths.imageAttachmentCacheDir
1675
+ };
1676
+ }
1677
+ function assertUnifiedDataRoot(paths, env = process.env) {
1678
+ const key = (path2) => process.platform === "win32" ? path2.toLowerCase() : path2;
1679
+ for (const [name, expected] of Object.entries(splitStoragePaths(paths))) {
1680
+ const value = env[name];
1681
+ if (value !== void 0 && key(requireAbsoluteDataRoot(value, name)) !== key(expected)) {
1682
+ throw new Error(`${name} \u6307\u5411\u6240\u9009 dataRoot \u4E4B\u5916\u7684\u4F4D\u7F6E\u3002\u8BF7\u68C0\u67E5\u914D\u7F6E\uFF0C\u9884\u671F\u8DEF\u5F84\u4E3A ${expected}\u3002`);
1683
+ }
1684
+ }
1685
+ }
1686
+
1687
+ // src/resources/schedule-resource.ts
1688
+ var ScheduleResource = class {
1689
+ constructor(transport) {
1690
+ this.transport = transport;
1691
+ }
1692
+ transport;
1693
+ async getStatus(options = {}) {
1694
+ return await this.transport.request("/schedules/status", {
1695
+ signal: options.signal
1696
+ });
1697
+ }
1698
+ async listTasks(options = {}) {
1699
+ const { signal, ...query } = options;
1700
+ const response = await this.transport.request(
1701
+ this.transport.path("/schedules/tasks", query),
1702
+ { signal }
1703
+ );
1704
+ return response.tasks;
1705
+ }
1706
+ async getTask(id2, options = {}) {
1707
+ const response = await this.transport.request(
1708
+ `/schedules/tasks/${encodeURIComponent(id2)}`,
1709
+ { signal: options.signal }
1710
+ );
1711
+ return response.task;
1712
+ }
1713
+ async createTask(input, options = {}) {
1714
+ const response = await this.transport.request(
1715
+ "/schedules/tasks",
1716
+ {
1717
+ method: "POST",
1718
+ body: input,
1719
+ signal: options.signal
1720
+ }
1721
+ );
1722
+ return response.task;
1723
+ }
1724
+ async updateTask(id2, input, options = {}) {
1725
+ const response = await this.transport.request(
1726
+ `/schedules/tasks/${encodeURIComponent(id2)}`,
1727
+ { method: "PATCH", body: input, signal: options.signal }
1728
+ );
1729
+ return response.task;
1730
+ }
1731
+ async removeTask(id2, options = {}) {
1732
+ await this.transport.request(
1733
+ `/schedules/tasks/${encodeURIComponent(id2)}`,
1734
+ {
1735
+ method: "DELETE",
1736
+ signal: options.signal
1737
+ }
1738
+ );
1739
+ }
1740
+ async triggerTask(id2, options = {}) {
1741
+ const response = await this.transport.request(
1742
+ this.transport.path(`/schedules/tasks/${encodeURIComponent(id2)}/run`, { requestId: options.requestId }),
1743
+ { method: "POST", signal: options.signal }
1744
+ );
1745
+ return response.run;
1746
+ }
1747
+ async listRuns(options = {}) {
1748
+ const { signal, ...query } = options;
1749
+ const response = await this.transport.request(
1750
+ this.transport.path("/schedules/runs", query),
1751
+ { signal }
1752
+ );
1753
+ return response.runs;
1754
+ }
1755
+ async setRunUnread(id2, unread, options = {}) {
1756
+ const response = await this.transport.request(
1757
+ `/schedules/runs/${encodeURIComponent(id2)}/read`,
1758
+ { method: "PATCH", body: { unread }, signal: options.signal }
1759
+ );
1760
+ return response.run;
1761
+ }
1762
+ };
1763
+
1764
+ // ../domain-contracts/src/validation-error.ts
1765
+ var DomainValidationError = class extends Error {
1766
+ constructor(message, field, reason) {
1767
+ super(message);
1768
+ this.field = field;
1769
+ this.reason = reason;
1770
+ this.name = "DomainValidationError";
1771
+ }
1772
+ field;
1773
+ reason;
1774
+ code = "invalid_request";
1775
+ };
1776
+
1777
+ // ../domain-contracts/src/sessions/resource-actions.ts
1778
+ var record = (v) => !!v && typeof v === "object" && !Array.isArray(v) && [Object.prototype, null].includes(Object.getPrototypeOf(v));
1779
+ var exact = (v, required, optional = []) => record(v) && required.every((k) => Object.hasOwn(v, k)) && Reflect.ownKeys(v).every((k) => {
1780
+ const d = Object.getOwnPropertyDescriptor(v, k);
1781
+ return typeof k === "string" && [...required, ...optional].includes(k) && d.enumerable && Object.hasOwn(d, "value");
1782
+ });
1783
+ var text = (v) => typeof v === "string" && v.trim().length > 0 && v.length <= 1024;
1784
+ var count = (v) => Number.isSafeInteger(v) && v >= 0;
1785
+ var uuid = (v) => typeof v === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v);
1786
+ var invalid = () => {
1787
+ throw new DomainValidationError("Invalid session resource request");
1788
+ };
1789
+ function parseSessionManagementAction(v) {
1790
+ if (!["rename", "pin", "archive", "delete"].includes(v)) invalid();
1791
+ return v;
1792
+ }
1793
+ function parseSessionResourceMutation(action, value) {
1794
+ const required = ["requestId", ...action === "rename" ? ["title", "expectedRevision"] : action === "pin" ? ["pinned", "expectedRevision"] : ["expectedTreeRevision"]];
1795
+ if (!exact(value, required) || !uuid(value.requestId)) return invalid();
1796
+ if (action === "rename" && (typeof value.title !== "string" || value.title.length > 2e3 || !count(value.expectedRevision)) || action === "pin" && (typeof value.pinned !== "boolean" || !count(value.expectedRevision)) || ["archive", "delete"].includes(action) && !text(value.expectedTreeRevision)) invalid();
1797
+ return value;
1798
+ }
1799
+ function decodeSessionResourceRevision(v) {
1800
+ if (!exact(v, ["revision"], ["treeRevision"]) || !count(v.revision) || Object.hasOwn(v, "treeRevision") && !text(v.treeRevision)) return invalid();
1801
+ return v;
1802
+ }
1803
+ function decodeSessionMutationReceipt(v) {
1804
+ if (!exact(v, ["dataScopeId", "sessionId", "requestId", "result"]) || !text(v.dataScopeId) || !text(v.sessionId) || !uuid(v.requestId) || !exact(v.result, ["sessionId", "action"], ["revision", "deletedSessionIds"]) || v.result.sessionId !== v.sessionId) return invalid();
1805
+ parseSessionManagementAction(v.result.action);
1806
+ if (Object.hasOwn(v.result, "revision") && !count(v.result.revision)) invalid();
1807
+ if (Object.hasOwn(v.result, "deletedSessionIds") && (!Array.isArray(v.result.deletedSessionIds) || v.result.deletedSessionIds.length > 1e4 || !v.result.deletedSessionIds.every(text) || new Set(v.result.deletedSessionIds).size !== v.result.deletedSessionIds.length)) invalid();
1808
+ return v;
1809
+ }
1810
+
1811
+ // ../domain-contracts/src/request-fields.ts
1812
+ function record2(value) {
1813
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1814
+ throw new DomainValidationError("Request body must be a JSON object");
1815
+ }
1816
+ return value;
1817
+ }
1818
+ function requiredString(body, field) {
1819
+ const value = body[field];
1820
+ if (typeof value !== "string") {
1821
+ throw new DomainValidationError(`${field} is required`, field);
1822
+ }
1823
+ return value;
1824
+ }
1825
+ function optionalString(body, field) {
1826
+ const value = body[field];
1827
+ if (value === void 0) return void 0;
1828
+ if (typeof value !== "string") {
1829
+ throw new DomainValidationError(`${field} must be a string`, field);
1830
+ }
1831
+ return value;
1832
+ }
1833
+ function optionalNumber(body, field, options = {}) {
1834
+ const value = body[field];
1835
+ if (value === void 0) return void 0;
1836
+ if (value === null && options.nullable) return null;
1837
+ if (typeof value !== "number" || !Number.isFinite(value) || options.integer && !Number.isInteger(value) || options.minimum !== void 0 && value < options.minimum) {
1838
+ throw new DomainValidationError(`${field} must be a valid number`, field);
1839
+ }
1840
+ return value;
1841
+ }
1842
+ function optionalBoolean(body, field) {
1843
+ const value = body[field];
1844
+ if (value === void 0) return void 0;
1845
+ if (typeof value !== "boolean") {
1846
+ throw new DomainValidationError(`${field} must be a boolean`, field);
1847
+ }
1848
+ return value;
1849
+ }
1850
+ function optionalStringArray(body, field) {
1851
+ const value = body[field];
1852
+ if (value === void 0) return void 0;
1853
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
1854
+ throw new DomainValidationError(
1855
+ `${field} must be an array of strings`,
1856
+ field
1857
+ );
1858
+ }
1859
+ return [...value];
1860
+ }
1861
+ function optionalEnum(body, field, values) {
1862
+ const value = body[field];
1863
+ if (value === void 0) return void 0;
1864
+ if (typeof value !== "string" || !values.includes(value)) {
1865
+ throw new DomainValidationError(
1866
+ `${field} must be one of: ${values.join(", ")}`,
1867
+ field
1868
+ );
1869
+ }
1870
+ return value;
1871
+ }
1872
+ function fields(body, allowed) {
1873
+ for (const key of Object.keys(body)) if (!allowed.includes(key)) throw new DomainValidationError(`Unknown field ${key}`, key);
1874
+ }
1875
+
1876
+ // ../domain-contracts/src/sessions/configuration-validation.ts
1877
+ function parseSessionConfiguration(value) {
1878
+ const body = record2(value);
1879
+ fields(body, ["model", "roleId", "systemPrompt", "executionInstructions", "effort", "workMode", "maxTurns", "sessionMode", "replyStyle", "approvalMode", "tools", "pluginsEnabled", "pluginAutoSelectionEnabled", "activePluginId", "pluginIds", "serviceBindings", "memory"]);
1880
+ for (const key of ["roleId", "systemPrompt", "effort", "activePluginId"]) if (body[key] !== null) optionalString(body, key);
1881
+ for (const key of ["pluginsEnabled", "pluginAutoSelectionEnabled"]) optionalBoolean(body, key);
1882
+ optionalEnum(body, "workMode", ["execute", "plan"]);
1883
+ optionalEnum(body, "sessionMode", ["direct", "coordinator"]);
1884
+ optionalEnum(body, "replyStyle", ["collaborative", "direct", "explanatory"]);
1885
+ optionalEnum(body, "approvalMode", ["ask", "auto_review", "full_access"]);
1886
+ optionalNumber(body, "maxTurns", { integer: true, minimum: 0 });
1887
+ for (const key of ["pluginIds", "serviceBindings"]) optionalStringArray(body, key);
1888
+ if (body.model !== void 0) {
1889
+ const model = record2(body.model);
1890
+ fields(model, ["provider", "model"]);
1891
+ for (const key of ["provider", "model"]) if (!requiredString(model, key).trim()) throw new DomainValidationError(`${key} cannot be empty`, `model.${key}`);
1892
+ }
1893
+ if (body.executionInstructions !== void 0 && body.executionInstructions !== null) {
1894
+ const instructions = record2(body.executionInstructions);
1895
+ fields(instructions, ["revision", "content"]);
1896
+ if (optionalNumber(instructions, "revision", { integer: true, minimum: 0 }) === void 0) throw new DomainValidationError("revision required", "executionInstructions.revision");
1897
+ requiredString(instructions, "content");
1898
+ }
1899
+ if (body.tools !== void 0) {
1900
+ const tools = record2(body.tools);
1901
+ fields(tools, ["allowed", "denied"]);
1902
+ optionalStringArray(tools, "allowed");
1903
+ optionalStringArray(tools, "denied");
1904
+ }
1905
+ if (body.memory !== void 0) {
1906
+ const memory = record2(body.memory);
1907
+ fields(memory, ["enabled"]);
1908
+ if (optionalBoolean(memory, "enabled") === void 0) throw new DomainValidationError("enabled required", "memory.enabled");
1909
+ }
1910
+ return structuredClone(body);
1911
+ }
1912
+
1913
+ // ../domain-contracts/src/inputs/items.ts
1914
+ var SESSION_INPUT_LIMITS = {
1915
+ maxItems: 256,
1916
+ maxSkills: 32,
1917
+ maxTextBytes: 1024 * 1024,
1918
+ maxNameChars: 128,
1919
+ maxDisplayNameChars: 256
1920
+ };
1921
+
1922
+ // ../domain-contracts/src/inputs/metadata.ts
1923
+ function assertPromptMetadataAllowed(input) {
1924
+ for (const namespace of ["metadata", "runMetadata"]) {
1925
+ const metadata = input[namespace];
1926
+ if (!metadata || typeof metadata !== "object") continue;
1927
+ if (Object.hasOwn(metadata, "outputSchema")) {
1928
+ const field = `${namespace}.outputSchema`;
1929
+ throw new DomainValidationError(`${field} is a stored snapshot; use explicit outputSchema`, field);
1930
+ }
1931
+ for (const name of ["pluginUi", "uiAction", "pluginUiSubmission", "pluginAppAction", "pluginAppSubmission", "pluginAppSource", "consumedForkHistory", "executionBinding", "configurationBinding", "initialConfigurationBinding", "steeredRunId", "sessionObservationGrant", "sessionObservationAccess"]) {
1932
+ if (Object.hasOwn(metadata, name)) {
1933
+ const field = `${namespace}.${name}`;
1934
+ throw new DomainValidationError(
1935
+ `${field} is reserved for the host`,
1936
+ field
1937
+ );
1938
+ }
1939
+ }
1940
+ }
1941
+ }
1942
+
1943
+ // ../domain-contracts/src/approvals/auto-review.ts
1944
+ var AUTO_REVIEW_MODES = ["off", "risk_based"];
1945
+ var AUTO_REVIEW_RISK_LEVELS = ["none", "low", "medium", "high", "unknown"];
1946
+ var AUTO_REVIEW_STATUSES = [
1947
+ "disabled",
1948
+ "captured",
1949
+ "skipped",
1950
+ "pending",
1951
+ "passed",
1952
+ "findings",
1953
+ "partial",
1954
+ "failed",
1955
+ "timed_out",
1956
+ "unavailable"
1957
+ ];
1958
+ var AUTO_REVIEW_VERDICTS = ["pass", "fail", "partial"];
1959
+ var AUTO_REVIEW_SEVERITIES = ["critical", "important", "minor"];
1960
+ var AUTO_REVIEW_REASONS = [
1961
+ "mode_off",
1962
+ "no_changes",
1963
+ "low_risk_change",
1964
+ "source_change",
1965
+ "large_change",
1966
+ "many_files",
1967
+ "sensitive_path",
1968
+ "sensitive_content_path",
1969
+ "production_delete_or_rename",
1970
+ "patch_truncated",
1971
+ "not_git_repository",
1972
+ "preexisting_dirty_overlap",
1973
+ "non_linear_head_change",
1974
+ "post_commit_worktree_changed",
1975
+ "git_inspection_failed",
1976
+ "review_output_invalid",
1977
+ "review_child_failed",
1978
+ "review_child_timed_out",
1979
+ "review_preempted_by_user",
1980
+ "parent_run_not_completed",
1981
+ "daemon_restarted",
1982
+ "concurrent_run_overlap",
1983
+ "execution_environment_unavailable",
1984
+ "observation_budget_exceeded",
1985
+ "observation_cancelled"
1986
+ ];
1987
+ var AUTO_REVIEW_MODE_SET = new Set(AUTO_REVIEW_MODES);
1988
+ var AUTO_REVIEW_RISK_LEVEL_SET = new Set(AUTO_REVIEW_RISK_LEVELS);
1989
+ var AUTO_REVIEW_STATUS_SET = new Set(AUTO_REVIEW_STATUSES);
1990
+ var AUTO_REVIEW_VERDICT_SET = new Set(AUTO_REVIEW_VERDICTS);
1991
+ var AUTO_REVIEW_SEVERITY_SET = new Set(AUTO_REVIEW_SEVERITIES);
1992
+ var AUTO_REVIEW_REASON_SET = new Set(AUTO_REVIEW_REASONS);
1993
+
1994
+ // ../plugin-contracts/src/manifest/limits.ts
1995
+ var PLUGIN_APP_MANIFEST_LIMITS = Object.freeze({
1996
+ manifestCount: 8,
1997
+ manifestBytes: 256 * 1024,
1998
+ backendCount: 32,
1999
+ surfaceCount: 32
2000
+ });
2001
+ var PLUGIN_APP_RESOURCE_LIMITS = Object.freeze({ htmlBytes: 16 * 1024 * 1024, resourceBytes: 8 * 1024 * 1024 });
2002
+ var PLUGIN_APP_DATA_LIMITS = Object.freeze({ maxArgsBytes: 64 * 1024 * 1024, jsonDepth: 32 });
2003
+
2004
+ // ../domain-contracts/src/plugin-apps/limits.ts
2005
+ var PLUGIN_APP_INPUT_LIMITS = Object.freeze({ handoffBytes: 32 * 1024, messageCharacters: 4096, maxComposerContexts: 8 });
2006
+
2007
+ // ../domain-contracts/src/plugin-apps/history.ts
2008
+ var PLUGIN_UI_LIMITS = { dataBytes: 256 * 1024, actionArgsBytes: 64 * 1024 };
2009
+
2010
+ // ../protocol/src/serialization/json.ts
2011
+ function isUuid(value) {
2012
+ return typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
2013
+ value
2014
+ );
2015
+ }
2016
+ function isNonnegativeInteger(value) {
2017
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
2018
+ }
2019
+
2020
+ // ../protocol/src/requests/requests.ts
2021
+ function parseCancelResponseMode(value) {
2022
+ if (value === void 0 || value === "snapshot") return "snapshot";
2023
+ if (value === "receipt") return "receipt";
2024
+ throw new ProtocolValidationError("Unsupported cancellation response mode", "responseMode");
2025
+ }
2026
+ var ProtocolValidationError = class extends Error {
2027
+ code = "invalid_request";
2028
+ details;
2029
+ constructor(message, field, reason) {
2030
+ super(message);
2031
+ this.name = "ProtocolValidationError";
2032
+ this.details = field || reason !== void 0 ? {
2033
+ ...field ? { field } : {},
2034
+ ...reason !== void 0 ? { reason } : {}
2035
+ } : void 0;
2036
+ }
2037
+ toProtocolError() {
2038
+ return {
2039
+ code: this.code,
2040
+ message: this.message,
2041
+ ...this.details ? { details: this.details } : {}
2042
+ };
2043
+ }
2044
+ };
2045
+ function assertPromptMetadataAllowed2(input) {
2046
+ adaptDomainInput(() => assertPromptMetadataAllowed(input));
2047
+ }
2048
+ function record3(value) {
2049
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2050
+ throw new ProtocolValidationError("Request body must be a JSON object");
2051
+ }
2052
+ return value;
2053
+ }
2054
+ function requiredString2(body, field) {
2055
+ const value = body[field];
2056
+ if (typeof value !== "string") {
2057
+ throw new ProtocolValidationError(`${field} is required`, field);
2058
+ }
2059
+ return value;
2060
+ }
2061
+ function optionalString2(body, field) {
2062
+ const value = body[field];
2063
+ if (value === void 0) return void 0;
2064
+ if (typeof value !== "string") {
2065
+ throw new ProtocolValidationError(`${field} must be a string`, field);
2066
+ }
2067
+ return value;
2068
+ }
2069
+ function optionalBoolean2(body, field) {
2070
+ const value = body[field];
2071
+ if (value === void 0) return void 0;
2072
+ if (typeof value !== "boolean") {
2073
+ throw new ProtocolValidationError(`${field} must be a boolean`, field);
2074
+ }
2075
+ return value;
2076
+ }
2077
+ function optionalRecord(body, field) {
2078
+ const value = body[field];
2079
+ if (value === void 0) return void 0;
2080
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2081
+ throw new ProtocolValidationError(`${field} must be an object`, field);
2082
+ }
2083
+ return value;
2084
+ }
2085
+ function optionalEnum2(body, field, values) {
2086
+ const value = body[field];
2087
+ if (value === void 0) return void 0;
2088
+ if (typeof value !== "string" || !values.includes(value)) {
2089
+ throw new ProtocolValidationError(
2090
+ `${field} must be one of: ${values.join(", ")}`,
2091
+ field
2092
+ );
2093
+ }
2094
+ return value;
2095
+ }
2096
+ function fields2(body, allowed) {
2097
+ for (const key of Object.keys(body)) if (!allowed.includes(key)) throw new ProtocolValidationError(`Unknown field ${key}`, key);
2098
+ }
2099
+ function parseSessionConfiguration2(value) {
2100
+ return adaptDomainInput(() => parseSessionConfiguration(value));
2101
+ }
2102
+ function parseConfigureSessionRequest(value) {
2103
+ const body = record3(value);
2104
+ fields2(body, ["requestId", "expectedRevision", "configuration", "optionsRevision"]);
2105
+ const { requestId, expectedRevision } = body;
2106
+ if (!isUuid(requestId)) throw new ProtocolValidationError("requestId must be a UUID", "requestId");
2107
+ if (!isNonnegativeInteger(expectedRevision)) throw new ProtocolValidationError("expectedRevision must be a nonnegative integer", "expectedRevision");
2108
+ const optionsRevision = optionalString2(body, "optionsRevision");
2109
+ return { requestId, expectedRevision, configuration: parseSessionConfiguration2(body.configuration), ...optionsRevision === void 0 ? {} : { optionsRevision } };
2110
+ }
2111
+ function parseConfigurationResultRequest(value) {
2112
+ const body = record3(value);
2113
+ fields2(body, ["requestId", "original"]);
2114
+ const original = parseConfigureSessionRequest(body.original);
2115
+ if (body.requestId !== original.requestId) throw new ProtocolValidationError("requestId must match original.requestId", "requestId");
2116
+ return { requestId: original.requestId, original };
2117
+ }
2118
+ function appMetadata(value) {
2119
+ const metadata = record3(value);
2120
+ fields2(metadata, ["app"]);
2121
+ optionalRecord(metadata, "app");
2122
+ return metadata;
2123
+ }
2124
+ function parseCreateSessionRequest(value) {
2125
+ const body = record3(value);
2126
+ fields2(body, ["id", "requestId", "cwd", "projectId", "title", "storage", "configuration", "optionsRevision", "metadata"]);
2127
+ const cwd = requiredString2(body, "cwd");
2128
+ const id2 = requiredString2(body, "id");
2129
+ const requestId = requiredString2(body, "requestId");
2130
+ if (!cwd.trim() || !id2.trim() || !requestId.trim()) throw new ProtocolValidationError("cwd, id and requestId cannot be empty");
2131
+ const result = { id: id2, requestId, cwd };
2132
+ for (const key of ["projectId", "title", "optionsRevision"]) if (body[key] !== void 0) result[key] = optionalString2(body, key);
2133
+ if (body.storage !== void 0) result.storage = optionalEnum2(body, "storage", ["sqlite", "memory"]);
2134
+ if (body.configuration !== void 0) result.configuration = parseSessionConfiguration2(body.configuration);
2135
+ if (body.metadata !== void 0) result.metadata = appMetadata(optionalRecord(body, "metadata"));
2136
+ return result;
2137
+ }
2138
+ function parseForkSessionRequest(value) {
2139
+ const body = record3(value);
2140
+ const beforeMessageId = optionalString2(body, "beforeMessageId");
2141
+ const afterMessageId = optionalString2(body, "afterMessageId");
2142
+ const storage = optionalEnum2(body, "storage", ["sqlite", "memory"]);
2143
+ const copyHistory = optionalBoolean2(body, "copyHistory");
2144
+ if (copyHistory === false && (beforeMessageId !== void 0 || afterMessageId !== void 0)) {
2145
+ throw new ProtocolValidationError(
2146
+ "copyHistory=false cannot select a fork point",
2147
+ "copyHistory"
2148
+ );
2149
+ }
2150
+ return {
2151
+ ...body.id !== void 0 ? { id: optionalString2(body, "id") } : {},
2152
+ ...body.requestId !== void 0 ? { requestId: optionalString2(body, "requestId") } : {},
2153
+ ...copyHistory !== void 0 ? { copyHistory } : {},
2154
+ ...beforeMessageId !== void 0 ? { beforeMessageId } : {},
2155
+ ...afterMessageId !== void 0 ? { afterMessageId } : {},
2156
+ ...storage !== void 0 ? { storage } : {}
2157
+ };
2158
+ }
2159
+ function parseUpdateSessionRequest(value) {
2160
+ const body = record3(value);
2161
+ fields2(body, ["title", "metadata"]);
2162
+ const title = optionalString2(body, "title");
2163
+ const metadata = body.metadata === void 0 ? void 0 : appMetadata(optionalRecord(body, "metadata"));
2164
+ return { ...title === void 0 ? {} : { title }, ...metadata === void 0 ? {} : { metadata } };
2165
+ }
2166
+ function adaptDomainInput(read) {
2167
+ try {
2168
+ return read();
2169
+ } catch (error) {
2170
+ if (error instanceof DomainValidationError) throw new ProtocolValidationError(error.message, error.field, error.reason);
2171
+ throw error;
2172
+ }
2173
+ }
2174
+
2175
+ // ../protocol/src/requests/domain-validation.ts
2176
+ function adaptDomainValidation(work) {
2177
+ try {
2178
+ return work();
2179
+ } catch (error) {
2180
+ if (error instanceof DomainValidationError) throw new ProtocolValidationError(error.message, error.field, error.reason);
2181
+ throw error;
2182
+ }
2183
+ }
2184
+
2185
+ // ../protocol/src/session/session-resource-actions.ts
2186
+ var parseSessionManagementAction2 = (...args) => adaptDomainValidation(() => parseSessionManagementAction(...args));
2187
+ var parseSessionResourceMutation2 = (...args) => adaptDomainValidation(() => parseSessionResourceMutation(...args));
2188
+ var decodeSessionResourceRevision2 = (...args) => adaptDomainValidation(() => decodeSessionResourceRevision(...args));
2189
+ var decodeSessionMutationReceipt2 = (...args) => adaptDomainValidation(() => decodeSessionMutationReceipt(...args));
2190
+
2191
+ // ../protocol/src/serialization/serialization.ts
2192
+ function decodeSessionConfigurationSnapshot(value) {
2193
+ const snapshot = object(value, "configurationSnapshot"), root = object(snapshot.configurationRoot, "configurationSnapshot.configurationRoot");
2194
+ if (Object.keys(snapshot).some((key) => !["revision", "configuration", "configurationRoot"].includes(key)) || !isNonnegativeInteger(snapshot.revision) || Object.keys(root).some((key) => !["cwd", "settingsRoot"].includes(key))) throw new ProtocolDataError("Invalid configuration snapshot");
2195
+ const cwd = stringField(root, "cwd", "configurationRoot"), settingsRoot = stringField(root, "settingsRoot", "configurationRoot");
2196
+ if (!cwd.trim() || !settingsRoot.trim()) throw new ProtocolDataError("Configuration roots are required");
2197
+ let configuration;
2198
+ try {
2199
+ configuration = parseSessionConfiguration2(snapshot.configuration);
2200
+ } catch {
2201
+ throw new ProtocolDataError("Invalid resolved configuration");
2202
+ }
2203
+ const required = ["model", "roleId", "systemPrompt", "executionInstructions", "effort", "workMode", "maxTurns", "sessionMode", "replyStyle", "approvalMode", "tools", "pluginsEnabled", "pluginAutoSelectionEnabled", "activePluginId", "pluginIds", "serviceBindings", "memory"];
2204
+ if (required.some((key) => !Object.hasOwn(configuration, key)) || !configuration.tools?.allowed || !configuration.tools.denied) throw new ProtocolDataError("Resolved configuration is incomplete");
2205
+ return { revision: snapshot.revision, configuration, configurationRoot: { cwd, settingsRoot } };
2206
+ }
2207
+ var ProtocolDataError = class extends Error {
2208
+ code = "invalid_protocol_data";
2209
+ details;
2210
+ constructor(message, path2) {
2211
+ super(message);
2212
+ this.name = "ProtocolDataError";
2213
+ this.details = path2 ? { path: path2 } : void 0;
2214
+ }
2215
+ toProtocolError() {
2216
+ return {
2217
+ code: this.code,
2218
+ message: this.message,
2219
+ ...this.details ? { details: this.details } : {}
2220
+ };
2221
+ }
2222
+ };
2223
+ function object(value, path2) {
2224
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2225
+ throw new ProtocolDataError(`${path2} must be an object`, path2);
2226
+ }
2227
+ return value;
2228
+ }
2229
+ function stringField(value, field, path2) {
2230
+ const fieldPath = `${path2}.${field}`;
2231
+ if (typeof value[field] !== "string") {
2232
+ throw new ProtocolDataError(`${fieldPath} must be a string`, fieldPath);
2233
+ }
2234
+ return value[field];
2235
+ }
2236
+ function optionalString3(value, field, path2) {
2237
+ const fieldValue = value[field];
2238
+ if (fieldValue !== void 0 && typeof fieldValue !== "string") {
2239
+ const fieldPath = `${path2}.${field}`;
2240
+ throw new ProtocolDataError(`${fieldPath} must be a string`, fieldPath);
2241
+ }
2242
+ }
2243
+ function numberField(value, field, path2) {
2244
+ const fieldPath = `${path2}.${field}`;
2245
+ const fieldValue = value[field];
2246
+ if (typeof fieldValue !== "number" || !Number.isFinite(fieldValue)) {
2247
+ throw new ProtocolDataError(`${fieldPath} must be a finite number`, fieldPath);
2248
+ }
2249
+ return fieldValue;
2250
+ }
2251
+ function optionalNumber2(value, field, path2, nullable2 = false) {
2252
+ const fieldValue = value[field];
2253
+ if (fieldValue === void 0 || nullable2 && fieldValue === null) return;
2254
+ if (typeof fieldValue !== "number" || !Number.isFinite(fieldValue)) {
2255
+ const fieldPath = `${path2}.${field}`;
2256
+ throw new ProtocolDataError(`${fieldPath} must be a finite number`, fieldPath);
2257
+ }
2258
+ }
2259
+ function booleanField(value, field, path2) {
2260
+ const fieldPath = `${path2}.${field}`;
2261
+ if (typeof value[field] !== "boolean") {
2262
+ throw new ProtocolDataError(`${fieldPath} must be a boolean`, fieldPath);
2263
+ }
2264
+ return value[field];
2265
+ }
2266
+ function recordField(value, field, path2) {
2267
+ return object(value[field], `${path2}.${field}`);
2268
+ }
2269
+ function optionalRecord2(value, field, path2) {
2270
+ if (value[field] !== void 0) object(value[field], `${path2}.${field}`);
2271
+ }
2272
+ function enumField(value, field, path2, allowed) {
2273
+ const fieldPath = `${path2}.${field}`;
2274
+ const fieldValue = value[field];
2275
+ if (typeof fieldValue !== "string" || !allowed.includes(fieldValue)) {
2276
+ throw new ProtocolDataError(
2277
+ `${fieldPath} must be one of: ${allowed.join(", ")}`,
2278
+ fieldPath
2279
+ );
2280
+ }
2281
+ return fieldValue;
2282
+ }
2283
+ function arrayField(value, field, path2, validate) {
2284
+ const fieldPath = `${path2}.${field}`;
2285
+ const items = value[field];
2286
+ if (!Array.isArray(items)) {
2287
+ throw new ProtocolDataError(`${fieldPath} must be an array`, fieldPath);
2288
+ }
2289
+ return items.map((item, index) => validate(item, `${fieldPath}[${index}]`));
2290
+ }
2291
+ function validateSession(value, path2) {
2292
+ const item = object(value, path2);
2293
+ stringField(item, "id", path2);
2294
+ stringField(item, "cwd", path2);
2295
+ stringField(item, "title", path2);
2296
+ stringField(item, "model", path2);
2297
+ enumField(item, "status", path2, ["idle", "running", "closing", "archived", "error"]);
2298
+ if (item.storage !== void 0) enumField(item, "storage", path2, ["sqlite", "memory"]);
2299
+ recordField(item, "metadata", path2);
2300
+ numberField(item, "createdAt", path2);
2301
+ numberField(item, "updatedAt", path2);
2302
+ for (const field of ["parentId", "projectId", "cwdRelative", "agent"]) {
2303
+ optionalString3(item, field, path2);
2304
+ }
2305
+ optionalNumber2(item, "archivedAt", path2);
2306
+ return item;
2307
+ }
2308
+ function validateInput(value, path2) {
2309
+ const item = object(value, path2);
2310
+ stringField(item, "id", path2);
2311
+ stringField(item, "sessionId", path2);
2312
+ numberField(item, "seq", path2);
2313
+ enumField(item, "delivery", path2, ["queue", "steer"]);
2314
+ stringField(item, "content", path2);
2315
+ const attachments = arrayField(item, "attachments", path2, validateInputAttachment);
2316
+ const assetIds = /* @__PURE__ */ new Set();
2317
+ for (const [index, attachment] of attachments.entries()) {
2318
+ const attachmentPath = `${path2}.attachments[${index}]`;
2319
+ if (attachment.sessionId !== item.sessionId) {
2320
+ throw new ProtocolDataError(
2321
+ `${attachmentPath}.sessionId must match ${path2}.sessionId`,
2322
+ `${attachmentPath}.sessionId`
2323
+ );
2324
+ }
2325
+ if (attachment.inputId !== item.id) {
2326
+ throw new ProtocolDataError(
2327
+ `${attachmentPath}.inputId must match ${path2}.id`,
2328
+ `${attachmentPath}.inputId`
2329
+ );
2330
+ }
2331
+ if (attachment.seq !== index) {
2332
+ throw new ProtocolDataError(
2333
+ `${attachmentPath}.seq must equal its array index`,
2334
+ `${attachmentPath}.seq`
2335
+ );
2336
+ }
2337
+ if (assetIds.has(attachment.assetId)) {
2338
+ throw new ProtocolDataError(
2339
+ `${attachmentPath}.assetId must be unique within the input`,
2340
+ `${attachmentPath}.assetId`
2341
+ );
2342
+ }
2343
+ assetIds.add(attachment.assetId);
2344
+ }
2345
+ optionalString3(item, "promotedMessageId", path2);
2346
+ recordField(item, "metadata", path2);
2347
+ numberField(item, "createdAt", path2);
2348
+ return item;
2349
+ }
2350
+ function validateInputAttachment(value, path2) {
2351
+ const item = object(value, path2);
2352
+ for (const field of ["id", "sessionId", "inputId", "assetId", "displayName", "mediaType"]) {
2353
+ stringField(item, field, path2);
2354
+ }
2355
+ optionalString3(item, "draftId", path2);
2356
+ numberField(item, "seq", path2);
2357
+ enumField(item, "intent", path2, [
2358
+ "auto",
2359
+ "vision",
2360
+ "ocr",
2361
+ "document",
2362
+ "tool_resource",
2363
+ "workspace_reference"
2364
+ ]);
2365
+ numberField(item, "sizeBytes", path2);
2366
+ recordField(item, "metadata", path2);
2367
+ numberField(item, "createdAt", path2);
2368
+ return item;
2369
+ }
2370
+ function validateMessage(value, path2) {
2371
+ const item = object(value, path2);
2372
+ stringField(item, "id", path2);
2373
+ stringField(item, "sessionId", path2);
2374
+ numberField(item, "seq", path2);
2375
+ enumField(item, "role", path2, ["system", "user", "assistant"]);
2376
+ optionalString3(item, "runId", path2);
2377
+ optionalString3(item, "inputId", path2);
2378
+ recordField(item, "metadata", path2);
2379
+ numberField(item, "createdAt", path2);
2380
+ numberField(item, "updatedAt", path2);
2381
+ return item;
2382
+ }
2383
+ function validatePart(value, path2) {
2384
+ const item = object(value, path2);
2385
+ stringField(item, "id", path2);
2386
+ stringField(item, "sessionId", path2);
2387
+ stringField(item, "messageId", path2);
2388
+ numberField(item, "seq", path2);
2389
+ const type = enumField(item, "type", path2, [
2390
+ "text",
2391
+ "attachment",
2392
+ "transformation",
2393
+ "reasoning",
2394
+ "tool",
2395
+ "tool_result",
2396
+ "error",
2397
+ "log"
2398
+ ]);
2399
+ enumField(item, "status", path2, ["pending", "running", "completed", "failed", "interrupted"]);
2400
+ for (const field of ["text", "toolUseId", "toolName"]) optionalString3(item, field, path2);
2401
+ optionalRecord2(item, "input", path2);
2402
+ if (item.bodyView !== void 0) {
2403
+ const view = object(item.bodyView, `${path2}.bodyView`);
2404
+ for (const field of ["input", "output"]) enumField(view, field, `${path2}.bodyView`, ["full", "preview", "unavailable"]);
2405
+ if (view.outputReferences !== void 0 && (!Array.isArray(view.outputReferences) || !view.outputReferences.every((ref) => typeof ref === "string")))
2406
+ throw new ProtocolDataError(`${path2}.bodyView.outputReferences must be strings`, `${path2}.bodyView.outputReferences`);
2407
+ }
2408
+ if (item.isError !== void 0 && typeof item.isError !== "boolean") {
2409
+ throw new ProtocolDataError(`${path2}.isError must be a boolean`, `${path2}.isError`);
2410
+ }
2411
+ if (type === "attachment") {
2412
+ for (const field of ["assetId", "displayName", "mediaType"]) {
2413
+ stringField(item, field, path2);
2414
+ }
2415
+ enumField(item, "intent", path2, [
2416
+ "auto",
2417
+ "vision",
2418
+ "ocr",
2419
+ "document",
2420
+ "tool_resource",
2421
+ "workspace_reference"
2422
+ ]);
2423
+ numberField(item, "sizeBytes", path2);
2424
+ }
2425
+ if (type === "transformation") {
2426
+ stringField(item, "assetId", path2);
2427
+ enumField(item, "kind", path2, ["direct", "document_extract", "tool_mount"]);
2428
+ for (const field of ["representationId", "processor", "transformationError"]) {
2429
+ optionalString3(item, field, path2);
2430
+ }
2431
+ }
2432
+ recordField(item, "metadata", path2);
2433
+ numberField(item, "createdAt", path2);
2434
+ numberField(item, "updatedAt", path2);
2435
+ return item;
2436
+ }
2437
+ function validateRun(value, path2) {
2438
+ const item = object(value, path2);
2439
+ stringField(item, "id", path2);
2440
+ stringField(item, "sessionId", path2);
2441
+ optionalString3(item, "inputId", path2);
2442
+ enumField(item, "status", path2, ["pending", "running", "completed", "failed", "interrupted"]);
2443
+ optionalNumber2(item, "startedAt", path2);
2444
+ optionalNumber2(item, "finishedAt", path2);
2445
+ optionalString3(item, "error", path2);
2446
+ recordField(item, "metadata", path2);
2447
+ numberField(item, "createdAt", path2);
2448
+ numberField(item, "updatedAt", path2);
2449
+ return item;
2450
+ }
2451
+ function validateAttempt(value, path2) {
2452
+ const item = object(value, path2);
2453
+ stringField(item, "id", path2);
2454
+ stringField(item, "runId", path2);
2455
+ numberField(item, "sequence", path2);
2456
+ enumField(item, "status", path2, ["pending", "running", "completed", "failed", "cancelled"]);
2457
+ for (const field of ["provider", "model", "retryReason", "errorKind", "error"]) {
2458
+ optionalString3(item, field, path2);
2459
+ }
2460
+ for (const field of ["inputTokens", "outputTokens", "startedAt", "finishedAt"]) {
2461
+ optionalNumber2(item, field, path2);
2462
+ }
2463
+ numberField(item, "createdAt", path2);
2464
+ numberField(item, "updatedAt", path2);
2465
+ return item;
2466
+ }
2467
+ function validateTask(value, path2) {
2468
+ const item = object(value, path2);
2469
+ for (const field of ["id", "sessionId", "type", "description", "cwd"]) {
2470
+ stringField(item, field, path2);
2471
+ }
2472
+ for (const field of ["childSessionId", "runId", "requestNamespace", "requestId", "output", "error"]) {
2473
+ optionalString3(item, field, path2);
2474
+ }
2475
+ enumField(item, "status", path2, ["pending", "running", "completed", "failed", "stopped", "interrupted"]);
2476
+ recordField(item, "metadata", path2);
2477
+ numberField(item, "createdAt", path2);
2478
+ optionalNumber2(item, "startedAt", path2);
2479
+ optionalNumber2(item, "finishedAt", path2);
2480
+ numberField(item, "updatedAt", path2);
2481
+ return item;
2482
+ }
2483
+ function validatePermission(value, path2) {
2484
+ const item = object(value, path2);
2485
+ for (const field of ["id", "sessionId", "toolName"]) stringField(item, field, path2);
2486
+ optionalString3(item, "runId", path2);
2487
+ recordField(item, "payload", path2);
2488
+ enumField(item, "status", path2, ["pending", "approved", "denied", "expired"]);
2489
+ optionalString3(item, "decision", path2);
2490
+ optionalString3(item, "decidedByClientId", path2);
2491
+ numberField(item, "createdAt", path2);
2492
+ numberField(item, "updatedAt", path2);
2493
+ return item;
2494
+ }
2495
+ function decodeSessionEventRecord(value) {
2496
+ const event = object(value, "event");
2497
+ stringField(event, "id", "event");
2498
+ numberField(event, "seq", "event");
2499
+ stringField(event, "type", "event");
2500
+ numberField(event, "schemaVersion", "event");
2501
+ optionalString3(event, "sessionId", "event");
2502
+ recordField(event, "payload", "event");
2503
+ numberField(event, "createdAt", "event");
2504
+ return event;
2505
+ }
2506
+ function validateSessionStateSnapshot(value) {
2507
+ const snapshot = object(value, "snapshot");
2508
+ numberField(snapshot, "cursor", "snapshot");
2509
+ validateSession(snapshot.session, "snapshot.session");
2510
+ arrayField(snapshot, "inputs", "snapshot", validateInput);
2511
+ arrayField(snapshot, "messages", "snapshot", validateMessage);
2512
+ arrayField(snapshot, "parts", "snapshot", validatePart);
2513
+ arrayField(snapshot, "runs", "snapshot", validateRun);
2514
+ arrayField(snapshot, "attempts", "snapshot", validateAttempt);
2515
+ if (snapshot.tasks !== void 0) arrayField(snapshot, "tasks", "snapshot", validateTask);
2516
+ arrayField(snapshot, "permissions", "snapshot", validatePermission);
2517
+ return snapshot;
2518
+ }
2519
+ function decodeAgentSessionStateSnapshot(value) {
2520
+ const snapshot = validateSessionStateSnapshot(value);
2521
+ const { cursor, session, inputs, messages, parts, runs, attempts, tasks, permissions, goal } = snapshot;
2522
+ return { cursor, session, inputs, messages, parts, runs, attempts, ...tasks !== void 0 ? { tasks } : {}, permissions, ...goal !== void 0 ? { goal } : {} };
2523
+ }
2524
+ function decodeSessionConfigurationReceipt(value, expected) {
2525
+ const path2 = "configurationReceipt";
2526
+ const receipt2 = object(value, path2);
2527
+ if (Object.keys(receipt2).some((key) => !["dataScopeId", "sessionId", "requestId", "action", "state", "revision"].includes(key))) throw new ProtocolDataError("Unexpected configuration receipt field", path2);
2528
+ const dataScopeId = stringField(receipt2, "dataScopeId", path2);
2529
+ const state = enumField(receipt2, "state", path2, ["prepared", "completed", "unknown"]);
2530
+ if (!dataScopeId.trim() || receipt2.sessionId !== expected.sessionId || receipt2.requestId !== expected.requestId || receipt2.action !== "configure") throw new ProtocolDataError("Configuration receipt does not match the original request", path2);
2531
+ const { revision: revision2 } = receipt2;
2532
+ if ((revision2 !== void 0 || state === "completed") && !isNonnegativeInteger(revision2)) throw new ProtocolDataError("Configuration receipt revision is invalid", `${path2}.revision`);
2533
+ return { dataScopeId, ...expected, action: "configure", state, ...typeof revision2 === "number" ? { revision: revision2 } : {} };
2534
+ }
2535
+ function decodeJobTarget(value) {
2536
+ const target = object(value, "jobTarget");
2537
+ const kind = enumField(target, "kind", "jobTarget", ["terminal", "shell", "agent", "dream", "workflow"]);
2538
+ if (!stringField(target, "jobId", "jobTarget").trim()) throw new ProtocolDataError("jobTarget.jobId is required", "jobTarget.jobId");
2539
+ if (kind === "agent" && !stringField(target, "runId", "jobTarget").trim()) throw new ProtocolDataError("jobTarget.runId is required", "jobTarget.runId");
2540
+ return target;
2541
+ }
2542
+ function decodeJobInputReceipt(value) {
2543
+ const receipt2 = object(value, "jobInputReceipt");
2544
+ for (const field of ["sessionId", "inputId", "runId"]) {
2545
+ if (!stringField(receipt2, field, "jobInputReceipt").trim()) throw new ProtocolDataError(`jobInputReceipt.${field} is required`, `jobInputReceipt.${field}`);
2546
+ }
2547
+ return receipt2;
2548
+ }
2549
+ function decodeJobListResult(value) {
2550
+ const result = object(value, "jobListResult");
2551
+ if (!Array.isArray(result.jobs) || !Array.isArray(result.errors)) throw new ProtocolDataError("Jobs list requires jobs and errors arrays", "jobListResult");
2552
+ result.jobs.forEach(decodeJobSnapshot);
2553
+ for (const error of result.errors) {
2554
+ const item = object(error, "jobListResult.errors");
2555
+ enumField(item, "kind", "jobListResult.errors", ["terminal", "shell", "agent", "dream", "workflow"]);
2556
+ stringField(item, "message", "jobListResult.errors");
2557
+ }
2558
+ return result;
2559
+ }
2560
+ function cancellationReceipt(value, fields3) {
2561
+ const envelope = object(value, "cancelResponse"), receipt2 = object(envelope.receipt, "cancelResponse.receipt");
2562
+ if (Object.keys(envelope).some((key) => key !== "receipt") || Object.keys(receipt2).some((key) => !fields3.includes(key))) throw new ProtocolDataError("Unexpected cancellation receipt field");
2563
+ for (const field of fields3.filter((field2) => field2 !== "status")) if (!stringField(receipt2, field, "cancelResponse.receipt").trim()) throw new ProtocolDataError("Cancellation receipt ID must not be empty");
2564
+ return receipt2;
2565
+ }
2566
+ function decodeJobCancelReceipt(value) {
2567
+ const receipt2 = cancellationReceipt(value, ["id", "status"]);
2568
+ enumField(receipt2, "status", "cancelResponse.receipt", ["running", "stopping", "completed", "killed", "failed"]);
2569
+ return receipt2;
2570
+ }
2571
+ function decodeQueuedPromptCancelReceipt(value) {
2572
+ const receipt2 = cancellationReceipt(value, ["inputId", "queuedRunId", "status"]);
2573
+ enumField(receipt2, "status", "cancelResponse.receipt", ["interrupted"]);
2574
+ return receipt2;
2575
+ }
2576
+ function decodeJobSnapshot(value) {
2577
+ const job = object(value, "job");
2578
+ for (const field of ["id", "label", "ownerSession", "cwd"]) stringField(job, field, "job");
2579
+ enumField(job, "kind", "job", ["terminal", "shell", "agent", "dream", "workflow"]);
2580
+ const target = decodeJobTarget(job.target);
2581
+ if (target.kind !== job.kind || target.jobId !== job.id) throw new ProtocolDataError("job target does not match snapshot", "job.target");
2582
+ enumField(job, "status", "job", ["running", "stopping", "completed", "killed", "failed"]);
2583
+ const capabilities = recordField(job, "capabilities", "job");
2584
+ for (const field of ["read", "wait", "send", "cancel"]) {
2585
+ booleanField(capabilities, field, "job.capabilities");
2586
+ }
2587
+ numberField(job, "startedAt", "job");
2588
+ numberField(job, "updatedAt", "job");
2589
+ optionalNumber2(job, "finishedAt", "job");
2590
+ const exitCode = job.exitCode;
2591
+ if (exitCode !== void 0 && exitCode !== null && (typeof exitCode !== "number" || !Number.isInteger(exitCode))) {
2592
+ throw new ProtocolDataError("job.exitCode must be an integer or null", "job.exitCode");
2593
+ }
2594
+ optionalString3(job, "detail", "job");
2595
+ optionalRecord2(job, "metadata", "job");
2596
+ return job;
2597
+ }
2598
+ function decodeJobReadResult(value) {
2599
+ const result = object(value, "jobReadResult");
2600
+ stringField(result, "text", "jobReadResult");
2601
+ numberField(result, "cursor", "jobReadResult");
2602
+ booleanField(result, "truncated", "jobReadResult");
2603
+ decodeJobSnapshot(result.snapshot);
2604
+ optionalRecord2(result, "details", "jobReadResult");
2605
+ return result;
2606
+ }
2607
+ function decodeJobWaitResult(value) {
2608
+ const result = object(value, "jobWaitResult");
2609
+ decodeJobReadResult(result);
2610
+ booleanField(result, "timedOut", "jobWaitResult");
2611
+ return result;
2612
+ }
2613
+ function decodeTerminalSessionInfo(value) {
2614
+ const terminal = object(value, "terminal");
2615
+ for (const field of ["id", "name", "cwd", "shell", "createdAt"]) {
2616
+ stringField(terminal, field, "terminal");
2617
+ }
2618
+ const scope = recordField(terminal, "scope", "terminal");
2619
+ const scopeKind = enumField(scope, "kind", "terminal.scope", ["project", "session"]);
2620
+ if (scopeKind === "project") {
2621
+ const projectId = stringField(scope, "projectId", "terminal.scope");
2622
+ optionalString3(terminal, "projectId", "terminal");
2623
+ if (terminal.projectId !== void 0 && terminal.projectId !== projectId) {
2624
+ throw new ProtocolDataError(
2625
+ "terminal.projectId must match terminal.scope.projectId",
2626
+ "terminal.projectId"
2627
+ );
2628
+ }
2629
+ } else {
2630
+ const sessionId = stringField(scope, "sessionId", "terminal.scope");
2631
+ optionalString3(terminal, "sessionId", "terminal");
2632
+ if (terminal.sessionId !== void 0 && terminal.sessionId !== sessionId) {
2633
+ throw new ProtocolDataError(
2634
+ "terminal.sessionId must match terminal.scope.sessionId",
2635
+ "terminal.sessionId"
2636
+ );
2637
+ }
2638
+ }
2639
+ optionalString3(terminal, "projectId", "terminal");
2640
+ optionalString3(terminal, "sessionId", "terminal");
2641
+ enumField(terminal, "runtime", "terminal", ["local", "environment"]);
2642
+ enumField(terminal, "source", "terminal", ["user", "agent"]);
2643
+ enumField(terminal, "status", "terminal", ["running", "stopping", "completed", "killed", "failed"]);
2644
+ numberField(terminal, "cols", "terminal");
2645
+ numberField(terminal, "rows", "terminal");
2646
+ optionalString3(terminal, "exitedAt", "terminal");
2647
+ optionalNumber2(terminal, "exitCode", "terminal", true);
2648
+ return terminal;
2649
+ }
2650
+ function decodeTerminalEvent(value) {
2651
+ const event = object(value, "terminalEvent");
2652
+ const type = enumField(event, "type", "terminalEvent", ["data", "status", "exit", "title", "error"]);
2653
+ stringField(event, "terminalId", "terminalEvent");
2654
+ if (type === "data") {
2655
+ stringField(event, "data", "terminalEvent");
2656
+ numberField(event, "sequence", "terminalEvent");
2657
+ } else if (type === "status") {
2658
+ enumField(event, "status", "terminalEvent", ["stopping", "killed"]);
2659
+ } else if (type === "exit") {
2660
+ optionalNumber2(event, "exitCode", "terminalEvent", true);
2661
+ if (!("exitCode" in event)) {
2662
+ throw new ProtocolDataError("terminalEvent.exitCode is required", "terminalEvent.exitCode");
2663
+ }
2664
+ } else if (type === "title") {
2665
+ stringField(event, "title", "terminalEvent");
2666
+ } else {
2667
+ stringField(event, "message", "terminalEvent");
2668
+ }
2669
+ return event;
2670
+ }
2671
+ function decodeTerminalReadResult(value) {
2672
+ const result = object(value, "terminalReadResult");
2673
+ stringField(result, "terminalId", "terminalReadResult");
2674
+ stringField(result, "data", "terminalReadResult");
2675
+ numberField(result, "sequence", "terminalReadResult");
2676
+ booleanField(result, "truncated", "terminalReadResult");
2677
+ return result;
2678
+ }
2679
+
2680
+ // ../domain-contracts/src/attachments/validation.ts
2681
+ function parseAttachmentLimits(value) {
2682
+ const record4 = recordValue(value, "attachment limits");
2683
+ const limits2 = {
2684
+ maxFilesPerPrompt: positiveInteger(
2685
+ record4.maxFilesPerPrompt,
2686
+ "maxFilesPerPrompt"
2687
+ ),
2688
+ maxBytesPerFile: positiveInteger(record4.maxBytesPerFile, "maxBytesPerFile"),
2689
+ maxBytesPerPrompt: positiveInteger(
2690
+ record4.maxBytesPerPrompt,
2691
+ "maxBytesPerPrompt"
2692
+ ),
2693
+ maxSessionReferencedBytes: positiveInteger(
2694
+ record4.maxSessionReferencedBytes,
2695
+ "maxSessionReferencedBytes"
2696
+ ),
2697
+ resumableThresholdBytes: positiveInteger(
2698
+ record4.resumableThresholdBytes,
2699
+ "resumableThresholdBytes"
2700
+ ),
2701
+ uploadSessionTtlMs: positiveInteger(
2702
+ record4.uploadSessionTtlMs,
2703
+ "uploadSessionTtlMs"
2704
+ ),
2705
+ stagingTtlMs: positiveInteger(record4.stagingTtlMs, "stagingTtlMs")
2706
+ };
2707
+ if (limits2.resumableThresholdBytes > limits2.maxBytesPerFile) {
2708
+ throw new Error("resumableThresholdBytes must not exceed maxBytesPerFile");
2709
+ }
2710
+ if (limits2.maxBytesPerFile > limits2.maxBytesPerPrompt) {
2711
+ throw new Error("maxBytesPerFile must not exceed maxBytesPerPrompt");
2712
+ }
2713
+ if (limits2.maxBytesPerPrompt > limits2.maxSessionReferencedBytes) {
2714
+ throw new Error(
2715
+ "maxBytesPerPrompt must not exceed maxSessionReferencedBytes"
2716
+ );
2717
+ }
2718
+ return limits2;
2719
+ }
2720
+ function parseAttachmentAssetRecord(value) {
2721
+ const record4 = recordValue(value, "attachment asset");
2722
+ const status = enumValue(
2723
+ record4.status,
2724
+ ["importing", "ready", "failed", "deleted"],
2725
+ "status"
2726
+ );
2727
+ const asset = {
2728
+ id: nonEmptyString(record4.id, "id"),
2729
+ displayName: nonEmptyString(record4.displayName, "displayName"),
2730
+ status,
2731
+ createdAt: nonNegativeInteger(record4.createdAt, "createdAt"),
2732
+ updatedAt: nonNegativeInteger(record4.updatedAt, "updatedAt")
2733
+ };
2734
+ const declaredMediaType = optionalNonEmptyString(
2735
+ record4.declaredMediaType,
2736
+ "declaredMediaType"
2737
+ );
2738
+ const mediaType = optionalNonEmptyString(record4.mediaType, "mediaType");
2739
+ const sizeBytes = optionalNonNegativeInteger(record4.sizeBytes, "sizeBytes");
2740
+ const sha256 = optionalSha256(record4.sha256);
2741
+ const failureCode = optionalNonEmptyString(record4.failureCode, "failureCode");
2742
+ const deletedAt = optionalNonNegativeInteger(record4.deletedAt, "deletedAt");
2743
+ if (declaredMediaType !== void 0) asset.declaredMediaType = declaredMediaType;
2744
+ if (mediaType !== void 0) asset.mediaType = mediaType;
2745
+ if (sizeBytes !== void 0) asset.sizeBytes = sizeBytes;
2746
+ if (sha256 !== void 0) asset.sha256 = sha256;
2747
+ if (failureCode !== void 0) asset.failureCode = failureCode;
2748
+ if (deletedAt !== void 0) asset.deletedAt = deletedAt;
2749
+ if (record4.chatSources !== void 0) {
2750
+ if (!Array.isArray(record4.chatSources)) throw new Error("chatSources must be an array");
2751
+ asset.chatSources = record4.chatSources.map(parseChatResourceSource);
2752
+ }
2753
+ if (status === "ready" || status === "deleted") {
2754
+ if (asset.mediaType === void 0) throw new Error("mediaType is required");
2755
+ if (asset.sizeBytes === void 0) throw new Error("sizeBytes is required");
2756
+ if (asset.sha256 === void 0) throw new Error("sha256 is required");
2757
+ }
2758
+ if (status === "failed" && asset.failureCode === void 0) {
2759
+ throw new Error("failureCode is required");
2760
+ }
2761
+ if (status === "deleted" && asset.deletedAt === void 0) {
2762
+ throw new Error("deletedAt is required");
2763
+ }
2764
+ return asset;
2765
+ }
2766
+ function parseChatResourceSource(value) {
2767
+ const record4 = recordValue(value, "chat resource source");
2768
+ const source = {
2769
+ storage: enumValue(record4.storage, ["memory", "sqlite"], "storage"),
2770
+ sessionId: nonEmptyString(record4.sessionId, "sessionId")
2771
+ };
2772
+ for (const field of ["sourceSessionId", "inputId", "runId"]) {
2773
+ const id2 = optionalNonEmptyString(record4[field], field);
2774
+ if (id2 !== void 0) source[field] = id2;
2775
+ }
2776
+ return source;
2777
+ }
2778
+ function recordValue(value, field) {
2779
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
2780
+ throw new Error(`${field} must be an object`);
2781
+ }
2782
+ return value;
2783
+ }
2784
+ function positiveInteger(value, field) {
2785
+ if (!Number.isSafeInteger(value) || Number(value) < 1) {
2786
+ throw new Error(`${field} must be a positive safe integer`);
2787
+ }
2788
+ return Number(value);
2789
+ }
2790
+ function nonNegativeInteger(value, field) {
2791
+ if (!Number.isSafeInteger(value) || Number(value) < 0) {
2792
+ throw new Error(`${field} must be a non-negative safe integer`);
2793
+ }
2794
+ return Number(value);
2795
+ }
2796
+ function optionalNonNegativeInteger(value, field) {
2797
+ return value === void 0 ? void 0 : nonNegativeInteger(value, field);
2798
+ }
2799
+ function nonEmptyString(value, field) {
2800
+ if (typeof value !== "string" || value.length === 0) {
2801
+ throw new Error(`${field} must be a non-empty string`);
2802
+ }
2803
+ return value;
2804
+ }
2805
+ function optionalNonEmptyString(value, field) {
2806
+ return value === void 0 ? void 0 : nonEmptyString(value, field);
2807
+ }
2808
+ function optionalSha256(value) {
2809
+ if (value === void 0) return void 0;
2810
+ if (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) {
2811
+ throw new Error("sha256 must be 64 lowercase hexadecimal characters");
2812
+ }
2813
+ return value;
2814
+ }
2815
+ function enumValue(value, allowed, field) {
2816
+ if (typeof value !== "string" || !allowed.includes(value)) {
2817
+ throw new Error(`${field} must be one of: ${allowed.join(", ")}`);
2818
+ }
2819
+ return value;
2820
+ }
2821
+ function parseAttachmentUploadRequest(value) {
2822
+ const record4 = recordValue(value, "attachment upload");
2823
+ const result = { requestId: nonEmptyString(record4.requestId, "requestId"), draftId: nonEmptyString(record4.draftId, "draftId"), displayName: nonEmptyString(record4.displayName, "displayName"), expectedSha256: optionalSha256(record4.expectedSha256), byteLength: nonNegativeInteger(record4.byteLength, "byteLength") };
2824
+ if (!result.expectedSha256) throw new Error("expectedSha256 is required");
2825
+ const declaredMediaType = optionalNonEmptyString(record4.declaredMediaType, "declaredMediaType");
2826
+ return { ...result, expectedSha256: result.expectedSha256, ...declaredMediaType ? { declaredMediaType } : {} };
2827
+ }
2828
+
2829
+ // ../protocol/src/runtime/capabilities.ts
2830
+ var CURRENT_PROTOCOL_VERSION = 7;
2831
+ var PROTOCOL_VERSION_HEADER = "x-bobannomi-protocol-version";
2832
+ function parseServerCapabilities(value) {
2833
+ if (!isRecord(value))
2834
+ throw new Error("Capabilities response must be an object");
2835
+ if (typeof value.serverVersion !== "string")
2836
+ throw new Error("serverVersion must be a string");
2837
+ if (!isRecord(value.protocol)) throw new Error("protocol must be an object");
2838
+ const version = positiveInteger2(value.protocol.version, "protocol.version");
2839
+ if (!isRecord(value.features)) throw new Error("features must be an object");
2840
+ const features = {};
2841
+ for (const [name, version2] of Object.entries(value.features)) {
2842
+ features[name] = positiveInteger2(version2, `features.${name}`);
2843
+ }
2844
+ const attachments = parseAttachmentTransferCapabilities(value.attachments);
2845
+ const agentEnvironments = parseAgentEnvironmentCapabilities(
2846
+ value.agentEnvironments
2847
+ );
2848
+ const mcpOAuth = parseMcpOAuthCapabilities(value.mcpOAuth);
2849
+ if (value.dataScopeId !== void 0 && (typeof value.dataScopeId !== "string" || !value.dataScopeId || value.dataScopeId.length > 256)) throw new Error("dataScopeId must be a bounded non-empty string");
2850
+ const storage = value.daemonStorage;
2851
+ if (storage !== void 0 && (!isRecord(storage) || !Number.isInteger(storage.pid) || Number(storage.pid) <= 0 || ["instanceId", "configDir", "dataDir", "storePath"].some((key) => typeof storage[key] !== "string" || !storage[key].length))) throw new Error("daemonStorage is invalid");
2852
+ return {
2853
+ ...storage ? { daemonStorage: storage } : {},
2854
+ ...value.dataScopeId === void 0 ? {} : { dataScopeId: value.dataScopeId },
2855
+ serverVersion: value.serverVersion,
2856
+ protocol: { version },
2857
+ features,
2858
+ ...attachments ? { attachments } : {},
2859
+ ...agentEnvironments ? { agentEnvironments } : {},
2860
+ ...mcpOAuth ? { mcpOAuth } : {}
2861
+ };
2862
+ }
2863
+ function parseMcpOAuthCapabilities(value) {
2864
+ if (value === void 0) return void 0;
2865
+ if (!isRecord(value) || typeof value.instanceId !== "string" || value.instanceId.length === 0 || value.instanceId.length > 200) {
2866
+ throw new Error("mcpOAuth.instanceId must be a bounded non-empty string");
2867
+ }
2868
+ return { instanceId: value.instanceId };
2869
+ }
2870
+ function parseAgentEnvironmentCapabilities(value) {
2871
+ if (value === void 0) return void 0;
2872
+ if (!isRecord(value) || value.native !== true || typeof value.wsl !== "boolean") {
2873
+ throw new Error(
2874
+ "agentEnvironments must contain native=true and a boolean wsl value"
2875
+ );
2876
+ }
2877
+ const active = value.activeDefault;
2878
+ if (active !== void 0 && (!isRecord(active) || active.kind !== "native" && active.kind !== "wsl" || typeof active.fingerprint !== "string" || active.distribution !== void 0 && typeof active.distribution !== "string")) throw new Error("agentEnvironments.activeDefault is invalid");
2879
+ return { native: true, wsl: value.wsl, ...active ? { activeDefault: active } : {} };
2880
+ }
2881
+ function checkProtocolCompatibility(server, client) {
2882
+ if (client.version !== server.protocol.version) {
2883
+ return {
2884
+ compatible: false,
2885
+ reason: `Client protocol ${client.version} does not match server protocol ${server.protocol.version}`
2886
+ };
2887
+ }
2888
+ return { compatible: true };
2889
+ }
2890
+ function positiveInteger2(value, field) {
2891
+ if (!Number.isInteger(value) || Number(value) < 1)
2892
+ throw new Error(`${field} must be a positive integer`);
2893
+ return Number(value);
2894
+ }
2895
+ function isRecord(value) {
2896
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2897
+ }
2898
+ function parseAttachmentTransferCapabilities(value) {
2899
+ if (value === void 0) return void 0;
2900
+ if (!isRecord(value)) throw new Error("attachments must be an object");
2901
+ if (!Array.isArray(value.uploadModes) || value.uploadModes.length === 0) {
2902
+ throw new Error("attachments.uploadModes must be a non-empty array");
2903
+ }
2904
+ if (value.uploadModes[0] !== "single" || value.uploadModes.length > 2 || value.uploadModes.length === 2 && value.uploadModes[1] !== "resumable") {
2905
+ throw new Error(
2906
+ 'attachments.uploadModes must be ["single"] or ["single", "resumable"]'
2907
+ );
2908
+ }
2909
+ const uploadModes = value.uploadModes;
2910
+ return {
2911
+ limits: parseAttachmentLimits(value.limits),
2912
+ uploadModes
2913
+ };
2914
+ }
2915
+
2916
+ // ../protocol/src/session/session-goals.ts
2917
+ function decodeSessionGoalRequestReceipt(value) {
2918
+ const fail = () => {
2919
+ throw new ProtocolDataError("Invalid Goal request receipt");
2920
+ };
2921
+ const object3 = (item, allowed) => {
2922
+ if (!item || typeof item !== "object" || Array.isArray(item) || Object.keys(item).some((key) => !allowed.includes(key))) return fail();
2923
+ return item;
2924
+ };
2925
+ const strings = (item, required, optional = []) => {
2926
+ for (const key of required) if (typeof item[key] !== "string" || !item[key]) fail();
2927
+ for (const key of optional) if (item[key] !== void 0 && typeof item[key] !== "string") fail();
2928
+ };
2929
+ const numbers = (item, required, optional = []) => {
2930
+ for (const key of required) if (!Number.isSafeInteger(item[key]) || item[key] < 0) fail();
2931
+ for (const key of optional) if (item[key] !== void 0 && (!Number.isSafeInteger(item[key]) || item[key] < 0)) fail();
2932
+ };
2933
+ const envelope = object3(value, ["request"]), receipt2 = object3(envelope.request, ["requestId", "sessionId", "fingerprint", "status", "goalId", "result", "error", "createdAt", "updatedAt"]);
2934
+ strings(receipt2, ["requestId", "sessionId", "fingerprint"], ["goalId", "error"]);
2935
+ numbers(receipt2, ["createdAt", "updatedAt"]);
2936
+ if (!["pending", "completed", "failed"].includes(String(receipt2.status))) fail();
2937
+ if (receipt2.result !== void 0) {
2938
+ const result = object3(receipt2.result, ["goal", "runId", "inputId", "phase"]);
2939
+ strings(result, [], ["runId", "inputId", "phase"]);
2940
+ if (result.goal !== void 0) {
2941
+ const goal = object3(result.goal, ["id", "sessionId", "objective", "objectiveVersion", "pluginId", "revision", "status", "maxAutoTurns", "tokenBudget", "usage", "autoTurnsUsed", "currentRunId", "queuedResume", "reason", "stopReason", "wait", "createdAt", "updatedAt"]);
2942
+ strings(goal, ["id", "sessionId", "objective"], ["pluginId", "currentRunId", "reason"]);
2943
+ numbers(goal, ["objectiveVersion", "revision", "maxAutoTurns", "autoTurnsUsed", "createdAt", "updatedAt"], ["tokenBudget"]);
2944
+ if (goal.sessionId !== receipt2.sessionId || receipt2.goalId !== void 0 && goal.id !== receipt2.goalId || !["active", "waiting_user", "blocked", "paused", "completed", "cancelled"].includes(String(goal.status))) fail();
2945
+ const usage = object3(goal.usage, ["knownTokens", "incomplete", "unknownAttempts", "partialAttempts", "inFlightAttempts", "runTimeMs", "seq", "updatedAt"]);
2946
+ numbers(usage, ["knownTokens", "unknownAttempts", "partialAttempts", "inFlightAttempts", "runTimeMs", "seq", "updatedAt"]);
2947
+ if (typeof usage.incomplete !== "boolean") fail();
2948
+ if (goal.queuedResume !== void 0) strings(object3(goal.queuedResume, ["requestId"]), ["requestId"]);
2949
+ if (goal.stopReason !== void 0) {
2950
+ const stop2 = object3(goal.stopReason, ["code", "at", "runId", "detail"]);
2951
+ strings(stop2, ["code"], ["runId", "detail"]);
2952
+ numbers(stop2, ["at"]);
2953
+ }
2954
+ if (goal.wait !== void 0) {
2955
+ const wait = goal.wait;
2956
+ if (wait?.kind === "user") {
2957
+ const item = object3(wait, ["kind", "questionId", "question", "objectiveVersion", "replyInputId", "response"]);
2958
+ strings(item, ["questionId", "question"], ["replyInputId", "response"]);
2959
+ numbers(item, ["objectiveVersion"]);
2960
+ } else if (wait?.kind === "approval") strings(object3(wait, ["kind", "permissionRequestId"]), ["permissionRequestId"]);
2961
+ else if (wait?.kind === "external") {
2962
+ const item = object3(wait, ["kind", "targetRunId", "ownerRunId", "goalId", "objectiveVersion", "deadlineAt", "observedStatus"]);
2963
+ strings(item, ["targetRunId", "ownerRunId", "goalId"], ["observedStatus"]);
2964
+ numbers(item, ["objectiveVersion", "deadlineAt"]);
2965
+ } else fail();
2966
+ }
2967
+ }
2968
+ }
2969
+ return receipt2;
2970
+ }
2971
+
2972
+ // ../protocol/src/runtime/execution-observability.ts
2973
+ var EXECUTION_KINDS = [
2974
+ "root_agent_run",
2975
+ "child_agent_run",
2976
+ "workflow_run",
2977
+ "workflow_task"
2978
+ ];
2979
+ var EXECUTION_OUTCOMES = [
2980
+ "completed",
2981
+ "failed",
2982
+ "timed_out",
2983
+ "cancelled",
2984
+ "blocked",
2985
+ "skipped",
2986
+ "running",
2987
+ "pending",
2988
+ "unknown"
2989
+ ];
2990
+ var EXECUTION_FAILURE_KINDS = [
2991
+ "model_error",
2992
+ "tool_error",
2993
+ "timeout",
2994
+ "permission_denied",
2995
+ "budget_exceeded",
2996
+ "dependency_failed",
2997
+ "cancelled_by_user",
2998
+ "cancelled_by_parent",
2999
+ "recovery_failed",
3000
+ "conflict",
3001
+ "unknown"
3002
+ ];
3003
+ var EXECUTION_KIND_SET = new Set(EXECUTION_KINDS);
3004
+ var EXECUTION_OUTCOME_SET = new Set(EXECUTION_OUTCOMES);
3005
+ var EXECUTION_FAILURE_KIND_SET = new Set(EXECUTION_FAILURE_KINDS);
3006
+ var AUTO_REVIEW_STATUS_SET2 = new Set(AUTO_REVIEW_STATUSES);
3007
+ var AUTO_REVIEW_RISK_LEVEL_SET2 = new Set(AUTO_REVIEW_RISK_LEVELS);
3008
+
3009
+ // ../domain-contracts/src/files/validation.ts
3010
+ function isSessionFileDataObject(value) {
3011
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
3012
+ const prototype = Object.getPrototypeOf(value);
3013
+ return prototype === Object.prototype || prototype === null;
3014
+ }
3015
+ function isSessionFileRelativePath(value) {
3016
+ return value.length > 0 && value.length <= 4096 && !value.startsWith("/") && !/^[a-zA-Z]:\//.test(value) && !value.includes("\\") && !value.includes("\0") && !value.split("/").includes("..");
3017
+ }
3018
+
3019
+ // ../protocol/src/files/session-files.ts
3020
+ function responseObject(value) {
3021
+ if (!isSessionFileDataObject(value)) throw new ProtocolDataError("File response must be an object");
3022
+ return value;
3023
+ }
3024
+ function responseString(value, field) {
3025
+ if (typeof value !== "string") throw new ProtocolDataError(`File response ${field} must be a string`, field);
3026
+ return value;
3027
+ }
3028
+ function responsePath(value) {
3029
+ const path2 = responseString(value, "path");
3030
+ if (!isSessionFileRelativePath(path2)) throw new ProtocolDataError("File response path must be relative to the workspace", "path");
3031
+ return path2;
3032
+ }
3033
+ function responseTruncated(value) {
3034
+ if (typeof value !== "boolean") throw new ProtocolDataError("File response truncated must be a boolean", "truncated");
3035
+ return value;
3036
+ }
3037
+ function responseArray(value, field, decode) {
3038
+ if (!Array.isArray(value)) throw new ProtocolDataError(`File response ${field} must be an array`, field);
3039
+ return value.map(decode);
3040
+ }
3041
+ function decodeSessionFileInfo(value) {
3042
+ const data = responseObject(value);
3043
+ const path2 = responsePath(data.path);
3044
+ const name = responseString(data.name, "name");
3045
+ if (!name || /[/\\\0]/.test(name)) throw new ProtocolDataError("File response name must be a filename", "name");
3046
+ const kind = data.kind;
3047
+ if (kind !== "file" && kind !== "directory" && kind !== "symlink" && kind !== "other") {
3048
+ throw new ProtocolDataError("File response kind is invalid", "kind");
3049
+ }
3050
+ const sizeBytes = data.sizeBytes;
3051
+ if (sizeBytes !== void 0 && (typeof sizeBytes !== "number" || !Number.isSafeInteger(sizeBytes) || sizeBytes < 0)) {
3052
+ throw new ProtocolDataError("File response sizeBytes must be a nonnegative integer", "sizeBytes");
3053
+ }
3054
+ const modifiedAt = data.modifiedAt;
3055
+ if (modifiedAt !== void 0 && (typeof modifiedAt !== "number" || !Number.isFinite(modifiedAt) || modifiedAt < 0)) {
3056
+ throw new ProtocolDataError("File response modifiedAt must be a nonnegative timestamp", "modifiedAt");
3057
+ }
3058
+ return { path: path2, name, kind, ...sizeBytes === void 0 ? {} : { sizeBytes }, ...modifiedAt === void 0 ? {} : { modifiedAt } };
3059
+ }
3060
+ function decodeSessionDirectoryResult(value) {
3061
+ const data = responseObject(value);
3062
+ return { path: responsePath(data.path), entries: responseArray(data.entries, "entries", decodeSessionFileInfo), truncated: responseTruncated(data.truncated) };
3063
+ }
3064
+ function decodeSessionTextFileResult(value) {
3065
+ const data = responseObject(value);
3066
+ if (data.encoding !== "utf-8") throw new ProtocolDataError("File response encoding must be utf-8", "encoding");
3067
+ return { path: responsePath(data.path), content: responseString(data.content, "content"), encoding: "utf-8", truncated: responseTruncated(data.truncated) };
3068
+ }
3069
+ function decodeSessionFindFilesResult(value) {
3070
+ const data = responseObject(value);
3071
+ return { path: responsePath(data.path), files: responseArray(data.files, "files", responsePath), truncated: responseTruncated(data.truncated) };
3072
+ }
3073
+ function decodeSearchMatch(value) {
3074
+ const data = responseObject(value);
3075
+ const line = data.line;
3076
+ if (typeof line !== "number" || !Number.isSafeInteger(line) || line < 1) throw new ProtocolDataError("File match line must be a positive integer", "line");
3077
+ return { path: responsePath(data.path), line, text: responseString(data.text, "text") };
3078
+ }
3079
+ function decodeSessionSearchFilesResult(value) {
3080
+ const data = responseObject(value);
3081
+ return { path: responsePath(data.path), matches: responseArray(data.matches, "matches", decodeSearchMatch), truncated: responseTruncated(data.truncated) };
3082
+ }
3083
+
3084
+ // ../agent-contracts/src/tools/tool-data.ts
3085
+ var MCP_CALL_RESULT_MAX_BYTES = 1024 * 1024;
3086
+
3087
+ // ../domain-contracts/src/app-host/app-types.ts
3088
+ var HOST_REQUEST_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
3089
+
3090
+ // ../domain-contracts/src/app-host/wire-validation.ts
3091
+ var text2 = (max = 1024, empty = false) => (v) => typeof v === "string" && (empty || v.length > 0) && new TextEncoder().encode(v).byteLength <= max;
3092
+ var id = (v) => typeof v === "string" && HOST_REQUEST_ID.test(v);
3093
+ var count2 = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
3094
+ var bool = (v) => typeof v === "boolean";
3095
+ var enumeration = (...values) => (v) => values.includes(v);
3096
+ var nullable = (check) => (v) => v === null || check(v);
3097
+ function object2(required, optional = {}) {
3098
+ return (v) => {
3099
+ if (!v || typeof v !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(v))) return false;
3100
+ if (Object.keys(required).some((k) => !Object.hasOwn(v, k))) return false;
3101
+ return Reflect.ownKeys(v).every((k) => {
3102
+ const d = Object.getOwnPropertyDescriptor(v, k);
3103
+ return typeof k === "string" && d.enumerable && Object.hasOwn(d, "value") && (required[k] ?? optional[k])?.(d.value) === true;
3104
+ });
3105
+ };
3106
+ }
3107
+ function array(check, max = 1024) {
3108
+ return (v) => {
3109
+ if (!Array.isArray(v) || Object.getPrototypeOf(v) !== Array.prototype || v.length > max || Reflect.ownKeys(v).length !== v.length + 1) return false;
3110
+ for (let i = 0; i < v.length; i++) {
3111
+ const d = Object.getOwnPropertyDescriptor(v, String(i));
3112
+ if (!d?.enumerable || !Object.hasOwn(d, "value") || !check(d.value)) return false;
3113
+ }
3114
+ return true;
3115
+ };
3116
+ }
3117
+ var json = (value) => {
3118
+ let size = 0;
3119
+ const seen = /* @__PURE__ */ new Set();
3120
+ const visit = (v, depth) => {
3121
+ if (depth > 64 || size > 12 * 1024 * 1024) return false;
3122
+ if (v === null || typeof v === "boolean") {
3123
+ size += 5;
3124
+ return true;
3125
+ }
3126
+ if (typeof v === "string") {
3127
+ size += new TextEncoder().encode(v).byteLength + 2;
3128
+ return size <= 12 * 1024 * 1024;
3129
+ }
3130
+ if (typeof v === "number") {
3131
+ size += 32;
3132
+ return Number.isFinite(v);
3133
+ }
3134
+ if (!v || typeof v !== "object" || seen.has(v)) return false;
3135
+ const list = Array.isArray(v);
3136
+ if (list ? Object.getPrototypeOf(v) !== Array.prototype : ![Object.prototype, null].includes(Object.getPrototypeOf(v))) return false;
3137
+ seen.add(v);
3138
+ try {
3139
+ const keys = Reflect.ownKeys(v);
3140
+ if (list && keys.length !== v.length + 1) return false;
3141
+ return keys.every((k) => {
3142
+ if (list && k === "length") return true;
3143
+ const d = Object.getOwnPropertyDescriptor(v, k);
3144
+ size += typeof k === "string" ? k.length + 3 : 0;
3145
+ return typeof k === "string" && d.enumerable && Object.hasOwn(d, "value") && (!list || /^(0|[1-9][0-9]*)$/.test(k) && Number(k) < v.length) && visit(d.value, depth + 1);
3146
+ });
3147
+ } finally {
3148
+ seen.delete(v);
3149
+ }
3150
+ };
3151
+ return visit(value, 0) && size <= 12 * 1024 * 1024;
3152
+ };
3153
+ var jsonObject = (v) => !!v && typeof v === "object" && !Array.isArray(v) && json(v);
3154
+ var wireConnection = object2({ connectionId: text2(256), baseUrl: text2(2048) });
3155
+
3156
+ // ../domain-contracts/src/app-host/workspace-conversations.ts
3157
+ var validWorkspaceConversation = (value) => {
3158
+ if (!object2(
3159
+ { dataScopeId: text2(), requestId: id, sessionId: id, taskLocation: enumeration("current", "worktree"), configuration: json },
3160
+ { workspaceId: id, outsideProject: (v) => v === true, preparationRevision: text2() }
3161
+ )(value)) return false;
3162
+ const input = value;
3163
+ return input.workspaceId !== void 0 ? input.outsideProject !== true : input.outsideProject === true && input.taskLocation === "current";
3164
+ };
3165
+ var sessionText = (value) => typeof value === "string";
3166
+ var sessionRecord = object2({
3167
+ id,
3168
+ cwd: sessionText,
3169
+ title: sessionText,
3170
+ model: sessionText,
3171
+ status: enumeration("idle", "running", "closing", "archived", "error"),
3172
+ metadata: jsonObject,
3173
+ createdAt: count2,
3174
+ updatedAt: count2
3175
+ }, {
3176
+ storage: enumeration("sqlite", "memory"),
3177
+ parentId: sessionText,
3178
+ projectId: sessionText,
3179
+ cwdRelative: sessionText,
3180
+ agent: sessionText,
3181
+ archivedAt: count2
3182
+ });
3183
+ var workspaceConversationResult = object2({
3184
+ dataScopeId: text2(),
3185
+ sessionId: id,
3186
+ requestId: id,
3187
+ action: (v) => v === "create-session",
3188
+ state: enumeration("prepared", "completed", "unknown")
3189
+ }, {
3190
+ configuration: json,
3191
+ revision: count2,
3192
+ session: sessionRecord,
3193
+ operationState: enumeration("prepared", "running", "completed", "failed", "unknown"),
3194
+ indexBindingPending: (v) => v === true,
3195
+ workspaceId: id,
3196
+ executionRoot: id,
3197
+ privateSessionId: id,
3198
+ worktree: json
3199
+ });
3200
+ var validWorkspaceConversationResult = (value) => {
3201
+ if (!workspaceConversationResult(value)) return false;
3202
+ const result = value;
3203
+ return !result.session || result.state === "completed" && result.session.id === result.sessionId;
3204
+ };
3205
+
3206
+ // ../domain-contracts/src/app-host/session-controls.ts
3207
+ var option = object2({ id: text2(), name: text2() });
3208
+ var choices = array(option);
3209
+ var effortChoices = array(object2({ id: text2(1024, true), name: text2() }));
3210
+ var receiptShape = object2({ dataScopeId: text2(), sessionId: text2(), requestId: id, action: enumeration("fork", "configure", "compact"), state: enumeration("prepared", "created", "completed", "unknown") }, { revision: count2, targetSessionId: text2() });
3211
+ var receipt = receiptShape;
3212
+ function validSessionControlOriginal(value) {
3213
+ if (!object2({ action: text2(), body: json })(value)) return false;
3214
+ const v = value;
3215
+ if (v.action === "compact") return object2({ requestId: id, expectedRevision: count2 })(v.body);
3216
+ return v.action === "fork" && object2({ requestId: id, id: text2() }, { copyHistory: bool, beforeMessageId: text2(), afterMessageId: text2(), storage: enumeration("sqlite") })(v.body);
3217
+ }
3218
+ function validSessionControlInput(method, value) {
3219
+ if (!json(value)) return false;
3220
+ if (method === "sessions.getDraftComposerOptions") {
3221
+ if (!object2({ source: enumeration("instance") }, { workspaceId: id, outsideProject: bool, roleId: (v2) => v2 === null || text2(256)(v2) })(value)) return false;
3222
+ const target = value;
3223
+ return target.workspaceId !== void 0 ? target.outsideProject !== true : target.outsideProject === true;
3224
+ }
3225
+ if (method === "sessions.bindConversationIndex") return object2({ original: validWorkspaceConversation, dataScopeId: text2() })(value);
3226
+ if (method === "sessions.createConversation" || method === "sessions.getConversationCreationResult") return validWorkspaceConversation(value);
3227
+ if (method === "sessions.getControls") return object2({ connectionId: text2(), sessionId: text2() })(value);
3228
+ if (!object2({ requestId: id, sessionId: text2(), original: validSessionControlOriginal }, { connectionId: text2() })(value)) return false;
3229
+ const v = value;
3230
+ return v.original.body.requestId === v.requestId && !!v.connectionId;
3231
+ }
3232
+ function validSessionControlResult(method, value) {
3233
+ if (!json(value)) return false;
3234
+ if (method === "sessions.getDraftComposerOptions") return object2({ source: enumeration("instance"), optionsRevision: text2(), skills: array(object2({ id: text2(), name: text2(), path: text2(4096, true) }, { source: enumeration("bundled", "user", "project", "plugin") }), 128), plugins: array(object2({ id: text2(), name: text2(), agents: array(option, 128) }), 128) })(value);
3235
+ if (method === "sessions.bindConversationIndex") return validWorkspaceConversationResult(value);
3236
+ if (method === "sessions.createConversation" || method === "sessions.getConversationCreationResult")
3237
+ return method === "sessions.getConversationCreationResult" && value === null || validWorkspaceConversationResult(value);
3238
+ if (method === "sessions.getControls") return object2({ dataScopeId: text2(), sessionId: text2(), source: enumeration("instance", "auxiliary", "im"), revision: count2, optionsRevision: text2(), actions: object2(Object.fromEntries(["readContext", "configure", "compact", "edit", "fork", "resume", "goalRead", "goalWrite", "goalStop"].map((k) => [k, bool]))), models: choices, roles: choices, efforts: effortChoices, workModes: choices, skills: array(object2({ id: text2(), name: text2(), path: text2(4096, true) }, { source: enumeration("bundled", "user", "project", "plugin") })), commands: choices, contexts: choices }, { permissionModes: array(option, 128), appServiceBindings: array(option, 128), plugins: array(object2({ id: text2(), name: text2(), agents: choices })) })(value);
3239
+ if (method === "sessions.getControlResult") return value === null || receipt(value);
3240
+ if (!receipt(value)) return false;
3241
+ return false;
3242
+ }
3243
+
3244
+ // ../domain-contracts/src/app-host/fetch.ts
3245
+ var FETCH_CHUNK_BYTES = 64 * 1024;
3246
+ var FETCH_INLINE_BODY_BYTES = 8 * 1024;
3247
+ var FETCH_METADATA_BYTES = 64 * 1024;
3248
+
3249
+ // ../domain-contracts/src/app-host/service-host-protocol.ts
3250
+ var SERVICE_HOST_MAX_FRAME_BYTES = 512 * 1024;
3251
+ var worktreeBody = { workspaceId: id, expectedHead: text2(256), branch: text2(1024) };
3252
+ var worktreeReceipt = object2({ requestId: id, state: enumeration("accepted", "completed", "failed", "unknown") }, { result: object2({ executionRoot: id, workspaceId: id, branch: text2(1024), sourceHead: text2(256) }) });
3253
+
3254
+ // ../domain-contracts/src/app-host/model-providers.ts
3255
+ var provider = text2(256);
3256
+ var imageInputSupport = enumeration("native", "unsupported", "unknown");
3257
+ var limits = { contextWindow: count2, maxOutputTokens: count2 };
3258
+ function headerValues(check) {
3259
+ return (value) => {
3260
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
3261
+ const keys = Object.keys(value);
3262
+ return keys.length <= 128 && keys.every((key) => /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,256}$/.test(key)) && object2(Object.fromEntries(keys.map((key) => [key, check])))(value);
3263
+ };
3264
+ }
3265
+ var headers = headerValues(text2(8192, true));
3266
+ var secretHeaders = headerValues(nullable(text2(8192)));
3267
+ var customProvider = object2({
3268
+ id: provider,
3269
+ displayName: text2(1024),
3270
+ baseUrl: text2(4096),
3271
+ apiFormat: enumeration("openai"),
3272
+ models: array(object2({ id: text2(1024), displayName: text2(1024) }, { imageInputSupport, ...limits }), 16384)
3273
+ }, { apiKey: text2(8192), headers, secretHeaders });
3274
+ var validModel = object2({ id: text2(1024), label: text2(1024) }, { imageInputSupport, declaredLimits: object2({}, limits) });
3275
+ var validConnection = object2({
3276
+ name: provider,
3277
+ displayName: text2(1024),
3278
+ connected: bool,
3279
+ active: bool,
3280
+ credentialSource: enumeration("credentials", "environment", "subscription", "local", "configured", "none"),
3281
+ models: array(validModel, 16384)
3282
+ }, { source: enumeration("builtin", "catalog", "custom", "subscription"), custom: bool, credentialLabel: text2(1024), baseUrl: text2(4096), headers, secretHeaderNames: array(text2(256), 128) });
3283
+ function validModelProviderConnections(value) {
3284
+ return array(validConnection, 4096)(value);
3285
+ }
3286
+ var modelId = text2(1024);
3287
+ var effort = nullable(text2(256));
3288
+ var revision = text2(8192);
3289
+ var verifiedProvider = object2({ model: modelId, checkedAt: count2 });
3290
+ var verified = (value) => {
3291
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
3292
+ const keys = Object.keys(value);
3293
+ return keys.length <= 4096 && keys.every(provider) && object2(Object.fromEntries(keys.map((key) => [key, verifiedProvider])))(value);
3294
+ };
3295
+ var defaultsModel = object2({ id: modelId, label: text2(1024), provider: text2(1024), providerName: provider }, {
3296
+ reasoningEfforts: array(text2(256, true)),
3297
+ contextWindow: count2,
3298
+ inputModalities: array(text2(256)),
3299
+ inputCapabilities: object2({ image: imageInputSupport })
3300
+ });
3301
+ var validProviderDefaultsSnapshot = object2({
3302
+ models: array(defaultsModel, 16384),
3303
+ provider: nullable(provider),
3304
+ model: nullable(modelId),
3305
+ effort,
3306
+ disabled: bool,
3307
+ revision,
3308
+ verified,
3309
+ fastModeAvailable: enumeration(false),
3310
+ fastModeReason: text2(1024)
3311
+ });
3312
+ var validProviderConnectionTestResult = object2({
3313
+ status: enumeration("verified", "failed"),
3314
+ detail: text2(8192),
3315
+ checkedAt: count2
3316
+ }, { category: enumeration("authentication", "address", "network", "model", "unsupported", "service") });
3317
+
3318
+ // src/protocol/protocol-client.ts
3319
+ var IncompatibleProtocolError = class extends Error {
3320
+ constructor(capabilities, message) {
3321
+ super(message);
3322
+ this.capabilities = capabilities;
3323
+ this.name = "IncompatibleProtocolError";
3324
+ }
3325
+ capabilities;
3326
+ };
3327
+ var ProtocolClient = class {
3328
+ constructor(transport) {
3329
+ this.transport = transport;
3330
+ }
3331
+ transport;
3332
+ /** `GET /health` */
3333
+ async health(options = {}) {
3334
+ return this.transport.request("/health", {
3335
+ auth: false,
3336
+ signal: options.signal
3337
+ });
3338
+ }
3339
+ /**
3340
+ * `GET /capabilities`
3341
+ * 连接产品应先调用它,再根据 features 决定显示哪些功能。
3342
+ */
3343
+ async capabilities(options = {}) {
3344
+ const value = await this.transport.request("/capabilities", {
3345
+ auth: options.authenticated === true,
3346
+ ...options.scope === "protocol" ? { headers: { "x-bobannomi-capability-scope": "protocol" } } : {},
3347
+ signal: options.signal
3348
+ });
3349
+ const capabilities = parseServerCapabilities(value);
3350
+ const compatibility = checkProtocolCompatibility(
3351
+ capabilities,
3352
+ options.support ?? { version: CURRENT_PROTOCOL_VERSION }
3353
+ );
3354
+ if (!compatibility.compatible) {
3355
+ throw new IncompatibleProtocolError(
3356
+ capabilities,
3357
+ compatibility.reason ?? "Client and server protocol versions are incompatible"
3358
+ );
3359
+ }
3360
+ if (options.authenticated === true && options.support === void 0) {
3361
+ this.transport.rememberProtocol(capabilities);
3362
+ }
3363
+ return capabilities;
3364
+ }
3365
+ };
3366
+
3367
+ // src/transport/http-transport.ts
3368
+ var BobanNomiApiError = class extends Error {
3369
+ constructor(message, status, body) {
3370
+ super(message);
3371
+ this.status = status;
3372
+ this.body = body;
3373
+ this.name = "BobanNomiApiError";
3374
+ }
3375
+ status;
3376
+ body;
3377
+ };
3378
+ function responseField(value, field) {
3379
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
3380
+ throw new ProtocolDataError("Response body must be an object");
3381
+ }
3382
+ if (!(field in value)) {
3383
+ throw new ProtocolDataError(`Response body is missing ${field}`, field);
3384
+ }
3385
+ return value[field];
3386
+ }
3387
+ function responseArray2(value, field, decode) {
3388
+ const items = responseField(value, field);
3389
+ if (!Array.isArray(items)) {
3390
+ throw new ProtocolDataError(`Response ${field} must be an array`, field);
3391
+ }
3392
+ return items.map(decode);
3393
+ }
3394
+ function normalizeDaemonBaseUrl(value) {
3395
+ const raw = value.trim();
3396
+ if (!raw) throw new Error("Daemon URL is required");
3397
+ let url;
3398
+ try {
3399
+ url = new URL(raw);
3400
+ } catch {
3401
+ throw new Error("Daemon URL must be an absolute http or https URL");
3402
+ }
3403
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
3404
+ throw new Error("Daemon URL must use http or https");
3405
+ }
3406
+ if (url.username || url.password) {
3407
+ throw new Error(
3408
+ "Daemon URL must not contain credentials; use a bearer token instead"
3409
+ );
3410
+ }
3411
+ if (url.search || url.hash) {
3412
+ throw new Error(
3413
+ "Daemon URL must not contain query parameters or a fragment"
3414
+ );
3415
+ }
3416
+ const pathname = url.pathname.replace(/\/+$/, "");
3417
+ return `${url.origin}${pathname === "/" ? "" : pathname}`;
3418
+ }
3419
+ function isReadableStream(value) {
3420
+ return typeof ReadableStream !== "undefined" && value instanceof ReadableStream;
3421
+ }
3422
+ function attachmentRangeHeader(range) {
3423
+ if (!range) return void 0;
3424
+ const { start, end, suffixBytes } = range;
3425
+ if (suffixBytes !== void 0) {
3426
+ if (start !== void 0 || end !== void 0) {
3427
+ throw new Error("suffixBytes cannot be combined with start or end");
3428
+ }
3429
+ assertPositiveSafeInteger(suffixBytes, "suffixBytes");
3430
+ return `bytes=-${suffixBytes}`;
3431
+ }
3432
+ if (start === void 0 && end === void 0) return void 0;
3433
+ if (start === void 0) {
3434
+ throw new Error("range start is required when end is provided");
3435
+ }
3436
+ assertNonNegativeSafeInteger(start, "start");
3437
+ if (end === void 0) return `bytes=${start}-`;
3438
+ assertNonNegativeSafeInteger(end, "end");
3439
+ if (end < start) throw new Error("range end must not be less than start");
3440
+ return `bytes=${start}-${end}`;
3441
+ }
3442
+ function assertNonNegativeSafeInteger(value, field) {
3443
+ if (!Number.isSafeInteger(value) || value < 0) {
3444
+ throw new Error(`${field} must be a non-negative safe integer`);
3445
+ }
3446
+ }
3447
+ function assertPositiveSafeInteger(value, field) {
3448
+ if (!Number.isSafeInteger(value) || value < 1) {
3449
+ throw new Error(`${field} must be a positive safe integer`);
3450
+ }
3451
+ }
3452
+ async function throwResponseError(response) {
3453
+ let body;
3454
+ try {
3455
+ body = await response.json();
3456
+ } catch {
3457
+ body = await response.text().catch(() => "");
3458
+ }
3459
+ const message = body && typeof body === "object" && "error" in body && typeof body.error === "string" ? body.error : body && typeof body === "object" && "message" in body && typeof body.message === "string" ? body.message : `BobanNomi API request failed with ${response.status}`;
3460
+ throw new BobanNomiApiError(message, response.status, body);
3461
+ }
3462
+ var HttpTransport = class {
3463
+ protocolHandshake;
3464
+ protocolVerified = false;
3465
+ baseUrl;
3466
+ token;
3467
+ fetchImpl;
3468
+ constructor(options) {
3469
+ this.baseUrl = normalizeDaemonBaseUrl(options.baseUrl);
3470
+ this.token = options.token;
3471
+ this.fetchImpl = options.fetch ?? fetch;
3472
+ }
3473
+ isHandshakeExempt(pathname) {
3474
+ const path2 = pathname.split("?")[0];
3475
+ return path2 === "/health" || path2 === "/capabilities";
3476
+ }
3477
+ rememberProtocol(capabilities) {
3478
+ if (this.protocolHandshake) return;
3479
+ this.protocolHandshake = Promise.resolve(structuredClone(capabilities));
3480
+ this.protocolVerified = true;
3481
+ }
3482
+ ensureProtocol(signal) {
3483
+ signal?.throwIfAborted();
3484
+ this.protocolHandshake ??= this.requestUnknown("/capabilities", {
3485
+ auth: false,
3486
+ headers: { "x-bobannomi-capability-scope": "protocol" }
3487
+ }).then((value) => {
3488
+ const capabilities = parseServerCapabilities(value);
3489
+ const result = checkProtocolCompatibility(capabilities, { version: CURRENT_PROTOCOL_VERSION });
3490
+ if (!result.compatible) {
3491
+ throw new IncompatibleProtocolError(capabilities, result.reason);
3492
+ }
3493
+ this.protocolVerified = true;
3494
+ return capabilities;
3495
+ }).catch((error) => {
3496
+ this.protocolHandshake = void 0;
3497
+ throw error;
3498
+ });
3499
+ if (!signal) return this.protocolHandshake;
3500
+ return new Promise((resolve5, reject) => {
3501
+ const onAbort = () => reject(signal.reason);
3502
+ signal.addEventListener("abort", onAbort, { once: true });
3503
+ this.protocolHandshake.then(resolve5, reject).finally(() => {
3504
+ signal.removeEventListener("abort", onAbort);
3505
+ });
3506
+ });
3507
+ }
3508
+ headers(jsonOrOptions = false, auth = true) {
3509
+ let json2 = false;
3510
+ let authHeader = auth;
3511
+ let extra;
3512
+ if (typeof jsonOrOptions === "object" && jsonOrOptions !== null) {
3513
+ json2 = jsonOrOptions.json ?? false;
3514
+ authHeader = jsonOrOptions.auth ?? true;
3515
+ extra = jsonOrOptions.extra;
3516
+ } else {
3517
+ json2 = Boolean(jsonOrOptions);
3518
+ authHeader = auth;
3519
+ }
3520
+ return {
3521
+ ...authHeader && this.token ? { authorization: `Bearer ${this.token}` } : {},
3522
+ ...json2 ? { "content-type": "application/json" } : {},
3523
+ ...extra ?? {}
3524
+ };
3525
+ }
3526
+ path(pathname, query = {}) {
3527
+ const params = new URLSearchParams();
3528
+ for (const [key, value] of Object.entries(query)) {
3529
+ if (value === void 0 || value === null || value === false) continue;
3530
+ params.set(key, String(value));
3531
+ }
3532
+ const qs = params.toString();
3533
+ return qs ? `${pathname}?${qs}` : pathname;
3534
+ }
3535
+ resolveUrl(pathname, query) {
3536
+ const resolvedPath = query ? this.path(pathname, query) : pathname;
3537
+ return `${this.baseUrl}${resolvedPath}`;
3538
+ }
3539
+ async request(path2, options = {}) {
3540
+ const business = !this.isHandshakeExempt(path2);
3541
+ if (business && !this.protocolVerified) await this.ensureProtocol(options.signal);
3542
+ options.signal?.throwIfAborted();
3543
+ const url = this.resolveUrl(path2, options.query);
3544
+ const hasJsonBody = options.body !== void 0;
3545
+ const headers2 = mergeHeaders(
3546
+ this.headers(hasJsonBody, options.auth ?? true),
3547
+ options.headers
3548
+ );
3549
+ if (business) headers2[PROTOCOL_VERSION_HEADER] = String(CURRENT_PROTOCOL_VERSION);
3550
+ const response = await this.fetchImpl(url, {
3551
+ method: options.method ?? "GET",
3552
+ headers: headers2,
3553
+ body: hasJsonBody ? JSON.stringify(options.body) : void 0,
3554
+ signal: options.signal
3555
+ });
3556
+ if (!response.ok) {
3557
+ await throwResponseError(response);
3558
+ }
3559
+ return await response.json();
3560
+ }
3561
+ async requestUnknown(path2, options = {}) {
3562
+ return this.request(path2, options);
3563
+ }
3564
+ async requestResponse(path2, options = {}) {
3565
+ const business = !this.isHandshakeExempt(path2);
3566
+ if (business) await this.ensureProtocol(options.signal ?? void 0);
3567
+ options.signal?.throwIfAborted();
3568
+ const url = this.resolveUrl(path2, options.query);
3569
+ const auth = options.auth ?? true;
3570
+ const headers2 = mergeHeaders(this.headers(false, auth), options.headers);
3571
+ if (business) headers2[PROTOCOL_VERSION_HEADER] = String(CURRENT_PROTOCOL_VERSION);
3572
+ const init = {
3573
+ ...options,
3574
+ headers: headers2
3575
+ };
3576
+ if (isReadableStream(init.body) && !init.duplex) {
3577
+ init.duplex = "half";
3578
+ }
3579
+ const response = await this.fetchImpl(url, init);
3580
+ if (!response.ok) {
3581
+ await throwResponseError(response);
3582
+ }
3583
+ return response;
3584
+ }
3585
+ async throwResponseError(response) {
3586
+ return throwResponseError(response);
3587
+ }
3588
+ };
3589
+ function mergeHeaders(defaults, overrides) {
3590
+ const headers2 = new Headers(defaults);
3591
+ if (overrides) {
3592
+ new Headers(overrides).forEach((value, key) => headers2.set(key, value));
3593
+ }
3594
+ return Object.fromEntries(headers2.entries());
3595
+ }
3596
+
3597
+ // src/transport/sse-transport.ts
3598
+ function parseRawSseFrame(frame) {
3599
+ let id2;
3600
+ let event;
3601
+ let retry;
3602
+ const dataLines = [];
3603
+ for (const line of frame.split(/\r?\n/)) {
3604
+ if (!line || line.startsWith(":")) continue;
3605
+ if (line.startsWith("data:")) {
3606
+ dataLines.push(line.startsWith("data: ") ? line.slice(6) : line.slice(5));
3607
+ } else if (line.startsWith("event:")) {
3608
+ event = (line.startsWith("event: ") ? line.slice(7) : line.slice(6)).trim();
3609
+ } else if (line.startsWith("id:")) {
3610
+ id2 = (line.startsWith("id: ") ? line.slice(4) : line.slice(3)).trim();
3611
+ } else if (line.startsWith("retry:")) {
3612
+ const value = (line.startsWith("retry: ") ? line.slice(7) : line.slice(6)).trim();
3613
+ const parsed = parseInt(value, 10);
3614
+ if (!Number.isNaN(parsed)) {
3615
+ retry = parsed;
3616
+ }
3617
+ }
3618
+ }
3619
+ if (dataLines.length === 0 && !id2 && !event && retry === void 0) {
3620
+ return void 0;
3621
+ }
3622
+ return {
3623
+ id: id2,
3624
+ event,
3625
+ retry,
3626
+ data: dataLines.length > 0 ? dataLines.join("\n") : void 0
3627
+ };
3628
+ }
3629
+ function parseSseFrame(frame) {
3630
+ let data = "";
3631
+ for (const line of frame.split(/\r?\n/)) {
3632
+ if (!line || line.startsWith(":")) continue;
3633
+ if (line.startsWith("data:")) {
3634
+ const slice = line.slice(5).trimStart();
3635
+ data = data ? `${data}
3636
+ ${slice}` : slice;
3637
+ }
3638
+ }
3639
+ if (!data) return void 0;
3640
+ return JSON.parse(data);
3641
+ }
3642
+ async function* streamServerSentEvents(open, decode = (value) => value) {
3643
+ const reader = (await open()).getReader();
3644
+ const decoder = new TextDecoder();
3645
+ let buffer = "";
3646
+ try {
3647
+ while (true) {
3648
+ const chunk = await reader.read();
3649
+ if (chunk.done) break;
3650
+ buffer += decoder.decode(chunk.value, { stream: true });
3651
+ const frames = buffer.split(/\r?\n\r?\n/);
3652
+ buffer = frames.pop() ?? "";
3653
+ for (const frame of frames) {
3654
+ const event = parseSseFrame(frame);
3655
+ if (event !== void 0) yield decode(event);
3656
+ }
3657
+ }
3658
+ } finally {
3659
+ try {
3660
+ await reader.cancel();
3661
+ } catch {
3662
+ } finally {
3663
+ reader.releaseLock();
3664
+ }
3665
+ }
3666
+ }
3667
+ var SseTransport = class {
3668
+ constructor(transport) {
3669
+ this.transport = transport;
3670
+ }
3671
+ transport;
3672
+ streamFromReader(open, decode = (val) => val) {
3673
+ return streamServerSentEvents(open, decode);
3674
+ }
3675
+ async *stream(url, options = {}) {
3676
+ let lastEventId = options.lastEventId;
3677
+ let reconnectDelayMs = options.reconnectDelayMs ?? 250;
3678
+ let connected = false;
3679
+ while (!options.signal?.aborted) {
3680
+ const connection = new AbortController();
3681
+ const onOuterAbort = () => connection.abort(options.signal?.reason);
3682
+ options.signal?.addEventListener("abort", onOuterAbort, { once: true });
3683
+ let idleTimer;
3684
+ let idleExpired = false;
3685
+ const resetIdleTimer = () => {
3686
+ if (!options.idleTimeoutMs || options.idleTimeoutMs <= 0) return;
3687
+ if (idleTimer) clearTimeout(idleTimer);
3688
+ idleTimer = setTimeout(() => {
3689
+ idleExpired = true;
3690
+ connection.abort("sse_idle_timeout");
3691
+ }, options.idleTimeoutMs);
3692
+ };
3693
+ try {
3694
+ const headers2 = new Headers(options.headers);
3695
+ if (lastEventId) headers2.set("Last-Event-ID", lastEventId);
3696
+ const requestUrl = connected && lastEventId ? withoutCursor(url) : url;
3697
+ const response = await this.transport.requestResponse(
3698
+ requestUrl.slice(this.transport.baseUrl.length),
3699
+ { headers: headers2, signal: connection.signal }
3700
+ );
3701
+ connected = true;
3702
+ if (!response.body) {
3703
+ throw new Error(
3704
+ options.noBodyMessage ?? "Event stream response has no body"
3705
+ );
3706
+ }
3707
+ options.onOpen?.();
3708
+ resetIdleTimer();
3709
+ try {
3710
+ for await (const frame of readRawSseFrames(
3711
+ response.body,
3712
+ resetIdleTimer
3713
+ )) {
3714
+ if (frame.retry !== void 0) reconnectDelayMs = frame.retry;
3715
+ if (frame.data !== void 0) {
3716
+ const value = (options.decode ?? ((value2) => value2))(
3717
+ JSON.parse(frame.data)
3718
+ );
3719
+ if (frame.id !== void 0) lastEventId = frame.id;
3720
+ yield value;
3721
+ }
3722
+ }
3723
+ } catch (error) {
3724
+ if (!idleExpired) throw error;
3725
+ }
3726
+ } finally {
3727
+ connection.abort();
3728
+ if (idleTimer) clearTimeout(idleTimer);
3729
+ options.signal?.removeEventListener("abort", onOuterAbort);
3730
+ }
3731
+ if (!options.reconnect || options.signal?.aborted) return;
3732
+ await waitForReconnect(reconnectDelayMs, options.signal);
3733
+ }
3734
+ }
3735
+ };
3736
+ async function* readRawSseFrames(stream, onFrame) {
3737
+ const reader = stream.getReader();
3738
+ const decoder = new TextDecoder();
3739
+ let buffer = "";
3740
+ try {
3741
+ while (true) {
3742
+ const chunk = await reader.read();
3743
+ if (chunk.done) break;
3744
+ buffer += decoder.decode(chunk.value, { stream: true });
3745
+ const frames = buffer.split(/\r?\n\r?\n/);
3746
+ buffer = frames.pop() ?? "";
3747
+ for (const value of frames) {
3748
+ onFrame?.();
3749
+ const frame = parseRawSseFrame(value);
3750
+ if (frame) yield frame;
3751
+ }
3752
+ }
3753
+ } finally {
3754
+ try {
3755
+ await reader.cancel();
3756
+ } catch {
3757
+ } finally {
3758
+ reader.releaseLock();
3759
+ }
3760
+ }
3761
+ }
3762
+ function waitForReconnect(ms, signal) {
3763
+ if (signal?.aborted) return Promise.reject(abortError(signal));
3764
+ return new Promise((resolve5, reject) => {
3765
+ const timer = setTimeout(
3766
+ () => {
3767
+ signal?.removeEventListener("abort", onAbort);
3768
+ resolve5();
3769
+ },
3770
+ Math.max(0, ms)
3771
+ );
3772
+ const onAbort = () => {
3773
+ clearTimeout(timer);
3774
+ reject(abortError(signal));
3775
+ };
3776
+ signal?.addEventListener("abort", onAbort, { once: true });
3777
+ });
3778
+ }
3779
+ function abortError(signal) {
3780
+ if (signal.reason instanceof Error) return signal.reason;
3781
+ return new DOMException("Aborted", "AbortError");
3782
+ }
3783
+ function withoutCursor(url) {
3784
+ const parsed = new URL(url);
3785
+ parsed.searchParams.delete("cursor");
3786
+ return parsed.toString();
3787
+ }
3788
+
3789
+ // src/resources/runtime/runtime-resource.ts
3790
+ var RuntimeResource = class {
3791
+ constructor(transport) {
3792
+ this.transport = transport;
3793
+ }
3794
+ transport;
3795
+ async listModels(options = {}) {
3796
+ const response = await this.transport.request("/models", options);
3797
+ return response.providers;
3798
+ }
3799
+ async modelProviders(input = { action: "list" }, options = {}) {
3800
+ const response = await this.transport.request("/providers/manage", { ...options, method: "POST", body: input });
3801
+ if (!validModelProviderConnections(response?.providers)) throw new Error("Invalid model provider response");
3802
+ return response.providers;
3803
+ }
3804
+ async providerDefaults(input = { action: "snapshot" }, options = {}) {
3805
+ const result = await this.transport.request("/providers/defaults", { ...options, method: "POST", body: input });
3806
+ const valid = input.action === "test" ? validProviderConnectionTestResult(result) : validProviderDefaultsSnapshot(result);
3807
+ if (!valid) throw new Error("Invalid provider defaults response");
3808
+ return result;
3809
+ }
3810
+ async listAgentPersonas(options = {}) {
3811
+ const response = await this.transport.request("/agent-personas", options);
3812
+ return response.agents;
3813
+ }
3814
+ listSkills(options = {}) {
3815
+ return this.transport.request("/skills", options);
3816
+ }
3817
+ async getSessionMcp(sessionId, options = {}) {
3818
+ const response = await this.transport.request(`/sessions/${encodeURIComponent(sessionId)}/mcp`, options);
3819
+ return response.servers;
3820
+ }
3821
+ };
3822
+
3823
+ // src/resources/session/session-terminal-resource.ts
3824
+ var SessionTerminalResource = class {
3825
+ constructor(transport) {
3826
+ this.transport = transport;
3827
+ }
3828
+ transport;
3829
+ async list(sessionId, options = {}) {
3830
+ const response = await this.transport.requestUnknown(path(sessionId), options);
3831
+ return responseArray2(response, "terminals", decodeTerminalSessionInfo);
3832
+ }
3833
+ async read(sessionId, terminalId, options = {}) {
3834
+ const { signal, ...query } = options;
3835
+ const response = await this.transport.requestUnknown(path(sessionId, terminalId) + "/output", { signal, query });
3836
+ return decodeTerminalReadResult(responseField(response, "snapshot"));
3837
+ }
3838
+ async stream(sessionId, terminalId, options = {}) {
3839
+ const response = await this.transport.requestResponse(path(sessionId, terminalId) + "/stream", options);
3840
+ const body = response.body;
3841
+ if (!body) throw new Error("Terminal event stream did not return a body");
3842
+ return streamServerSentEvents(async () => body, decodeTerminalEvent);
3843
+ }
3844
+ };
3845
+ function path(sessionId, terminalId) {
3846
+ return `/sessions/${encodeURIComponent(sessionId)}/terminals${terminalId === void 0 ? "" : `/${encodeURIComponent(terminalId)}`}`;
3847
+ }
3848
+
3849
+ // src/resources/session/session-management-resource.ts
3850
+ var SessionManagementResource = class {
3851
+ constructor(transport) {
3852
+ this.transport = transport;
3853
+ }
3854
+ transport;
3855
+ authenticatedCapabilities;
3856
+ async ready(signal) {
3857
+ let capabilities = await this.transport.ensureProtocol(signal);
3858
+ if ((capabilities.features.sessionResources ?? 0) < 1) throw new Error("Server does not support session resources");
3859
+ if (!capabilities.dataScopeId) {
3860
+ capabilities = this.authenticatedCapabilities ?? await new ProtocolClient(this.transport).capabilities({ authenticated: true, signal });
3861
+ if (!capabilities.dataScopeId || (capabilities.features.sessionResources ?? 0) < 1) throw new Error("Server does not support session resources");
3862
+ this.authenticatedCapabilities = capabilities;
3863
+ }
3864
+ return capabilities;
3865
+ }
3866
+ async getRevision(sessionId, input, options = {}) {
3867
+ await this.ready(options.signal);
3868
+ parseSessionManagementAction2(input.action);
3869
+ const response = await this.transport.request(this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/resource-revision`, { action: input.action }), options);
3870
+ return decodeSessionResourceRevision2(response);
3871
+ }
3872
+ async mutate(sessionId, action, input, options) {
3873
+ const body = parseSessionResourceMutation2(action, input), capabilities = await this.ready(options.signal);
3874
+ const response = await this.transport.request(`/sessions/${encodeURIComponent(sessionId)}/resource-actions/${action}`, { method: "POST", body, signal: options.signal });
3875
+ const receipt2 = decodeSessionMutationReceipt2(response.receipt);
3876
+ if (receipt2.dataScopeId !== capabilities.dataScopeId || receipt2.sessionId !== sessionId || receipt2.requestId !== body.requestId || receipt2.result.action !== action) throw new Error("Mutation receipt does not match original request");
3877
+ return receipt2;
3878
+ }
3879
+ rename(id2, input, options = {}) {
3880
+ return this.mutate(id2, "rename", input, options);
3881
+ }
3882
+ setPinned(id2, input, options = {}) {
3883
+ return this.mutate(id2, "pin", input, options);
3884
+ }
3885
+ archive(id2, input, options = {}) {
3886
+ return this.mutate(id2, "archive", input, options);
3887
+ }
3888
+ delete(id2, input, options = {}) {
3889
+ return this.mutate(id2, "delete", input, options);
3890
+ }
3891
+ async getMutation(sessionId, requestId, options = {}) {
3892
+ const capabilities = await this.ready(options.signal);
3893
+ const response = await this.transport.request(`/sessions/${encodeURIComponent(sessionId)}/resource-mutations/${encodeURIComponent(requestId)}`, options);
3894
+ if (response.receipt === null) return null;
3895
+ const receipt2 = decodeSessionMutationReceipt2(response.receipt);
3896
+ if (receipt2.dataScopeId !== capabilities.dataScopeId || receipt2.sessionId !== sessionId || receipt2.requestId !== requestId) throw new Error("Mutation receipt does not match query");
3897
+ return receipt2;
3898
+ }
3899
+ };
3900
+
3901
+ // src/resources/session/session-resource.ts
3902
+ var promptRequestCounter = 0;
3903
+ function createPromptRequestId() {
3904
+ if (typeof globalThis.crypto?.randomUUID === "function") {
3905
+ return globalThis.crypto.randomUUID();
3906
+ }
3907
+ promptRequestCounter += 1;
3908
+ return `prompt-${Date.now().toString(36)}-${promptRequestCounter.toString(36)}`;
3909
+ }
3910
+ var SessionResource = class {
3911
+ constructor(transport) {
3912
+ this.transport = transport;
3913
+ this.resources = new SessionManagementResource(transport);
3914
+ this.terminals = new SessionTerminalResource(transport);
3915
+ }
3916
+ transport;
3917
+ resources;
3918
+ terminals;
3919
+ checkOutputSchema(input, signal) {
3920
+ assertPromptMetadataAllowed2(input);
3921
+ if (input.outputSchema === void 0) return;
3922
+ return this.transport.ensureProtocol(signal).then((capabilities) => {
3923
+ if ((capabilities.features.structuredDelivery ?? 0) < 1) {
3924
+ throw new Error(
3925
+ "Server does not support structured delivery (outputSchema)"
3926
+ );
3927
+ }
3928
+ });
3929
+ }
3930
+ /** `GET /sessions/search` - search saved conversation text without opening it. */
3931
+ async search(options) {
3932
+ const { signal, ...query } = options;
3933
+ const response = await this.transport.request(this.transport.path("/sessions/search", query), { signal });
3934
+ return response.results;
3935
+ }
3936
+ /** `GET /sessions` */
3937
+ async list(options = {}) {
3938
+ const { signal, ...query } = options;
3939
+ const response = await this.transport.request(this.transport.path("/sessions", query), { signal });
3940
+ return response.sessions;
3941
+ }
3942
+ listDirectory(options = {}) {
3943
+ const { signal, ...query } = options;
3944
+ return this.transport.request(
3945
+ this.transport.path("/sessions/directory", query),
3946
+ { signal }
3947
+ );
3948
+ }
3949
+ getActivity(options = {}) {
3950
+ return this.transport.request("/sessions/activity", {
3951
+ signal: options.signal
3952
+ });
3953
+ }
3954
+ async getDraftComposerOptions(input, options = {}) {
3955
+ if (!validSessionControlInput("sessions.getDraftComposerOptions", input))
3956
+ throw new ProtocolDataError("Invalid draft composer target");
3957
+ const { workspaceId, outsideProject, roleId } = input;
3958
+ const path2 = this.transport.path("/sessions/configuration-options", {
3959
+ kind: "draft",
3960
+ workspaceId,
3961
+ outsideProject,
3962
+ roleId: roleId ?? void 0
3963
+ });
3964
+ const result = await this.transport.request(path2, {
3965
+ signal: options.signal
3966
+ });
3967
+ if (!validSessionControlResult("sessions.getDraftComposerOptions", result) || result.source !== input.source) {
3968
+ throw new ProtocolDataError("Draft composer options do not match target");
3969
+ }
3970
+ return result;
3971
+ }
3972
+ async getControls(sessionId, options = {}) {
3973
+ const result = await this.transport.request(
3974
+ `/sessions/${encodeURIComponent(sessionId)}/controls`,
3975
+ { signal: options.signal }
3976
+ );
3977
+ if (!validSessionControlResult("sessions.getControls", result) || result.sessionId !== sessionId) {
3978
+ throw new ProtocolDataError("Session controls do not match target");
3979
+ }
3980
+ return result;
3981
+ }
3982
+ async getControlResult(sessionId, input, options = {}) {
3983
+ const { requestId, original } = input;
3984
+ if (!validSessionControlOriginal(original) || original.body.requestId !== requestId) throw new ProtocolDataError("Invalid original control request");
3985
+ const result = await this.transport.request(
3986
+ `/sessions/${encodeURIComponent(sessionId)}/control-result`,
3987
+ {
3988
+ method: "POST",
3989
+ body: { requestId, original },
3990
+ signal: options.signal
3991
+ }
3992
+ );
3993
+ if (!validSessionControlResult("sessions.getControlResult", result) || result && (result.sessionId !== sessionId || result.requestId !== requestId || result.action !== original.action || original.action === "fork" && result.targetSessionId !== original.body.id))
3994
+ throw new ProtocolDataError(
3995
+ "Control receipt does not match original request"
3996
+ );
3997
+ return result;
3998
+ }
3999
+ /** Current context assembly requires execution authority; /usage is historical billing. */
4000
+ async getContextUsage(sessionId, options = {}) {
4001
+ return this.transport.request(
4002
+ `/sessions/${encodeURIComponent(sessionId)}/context-usage`,
4003
+ { signal: options.signal }
4004
+ );
4005
+ }
4006
+ /** `GET /sessions/:id` */
4007
+ async get(sessionId, options = {}) {
4008
+ const response = await this.transport.request(
4009
+ `/sessions/${encodeURIComponent(sessionId)}`,
4010
+ {
4011
+ signal: options.signal
4012
+ }
4013
+ );
4014
+ return response.session;
4015
+ }
4016
+ /** `POST /sessions` */
4017
+ async create(input, options = {}) {
4018
+ const response = await this.transport.request(
4019
+ "/sessions",
4020
+ {
4021
+ method: "POST",
4022
+ body: parseCreateSessionRequest({
4023
+ ...input,
4024
+ id: input.id ?? createPromptRequestId(),
4025
+ requestId: input.requestId ?? createPromptRequestId()
4026
+ }),
4027
+ signal: options.signal
4028
+ }
4029
+ );
4030
+ return response.session;
4031
+ }
4032
+ async getConfigurationOptions(input, options = {}) {
4033
+ return this.transport.request(
4034
+ this.transport.path("/sessions/configuration-options", input),
4035
+ { signal: options.signal }
4036
+ );
4037
+ }
4038
+ async getCreationResult(input, options = {}) {
4039
+ return this.transport.request("/sessions/creation-result", {
4040
+ method: "POST",
4041
+ body: input,
4042
+ signal: options.signal
4043
+ });
4044
+ }
4045
+ async getConfiguration(sessionId, options = {}) {
4046
+ const value = await this.transport.requestUnknown(
4047
+ `/sessions/${encodeURIComponent(sessionId)}/configuration`,
4048
+ { signal: options.signal }
4049
+ );
4050
+ return decodeSessionConfigurationSnapshot(value);
4051
+ }
4052
+ async configure(sessionId, input, options = {}) {
4053
+ const body = parseConfigureSessionRequest(input);
4054
+ const response = await this.transport.requestUnknown(
4055
+ `/sessions/${encodeURIComponent(sessionId)}/configure`,
4056
+ { method: "POST", body, signal: options.signal }
4057
+ );
4058
+ return decodeSessionConfigurationReceipt(response, {
4059
+ sessionId,
4060
+ requestId: body.requestId
4061
+ });
4062
+ }
4063
+ async getConfigurationResult(sessionId, input, options = {}) {
4064
+ const body = parseConfigurationResultRequest(input);
4065
+ const response = await this.transport.requestUnknown(
4066
+ `/sessions/${encodeURIComponent(sessionId)}/configuration-result`,
4067
+ { method: "POST", body, signal: options.signal }
4068
+ );
4069
+ return response === null ? null : decodeSessionConfigurationReceipt(response, {
4070
+ sessionId,
4071
+ requestId: body.requestId
4072
+ });
4073
+ }
4074
+ /** `PATCH /sessions/:id` - update title or application metadata. */
4075
+ async update(sessionId, input, options = {}) {
4076
+ const response = await this.transport.request(
4077
+ `/sessions/${encodeURIComponent(sessionId)}`,
4078
+ {
4079
+ method: "PATCH",
4080
+ body: parseUpdateSessionRequest(input),
4081
+ signal: options.signal
4082
+ }
4083
+ );
4084
+ return response.session;
4085
+ }
4086
+ /** `POST /sessions/:id/fork` */
4087
+ async fork(sessionId, input = {}, options = {}) {
4088
+ const response = await this.transport.request(
4089
+ `/sessions/${encodeURIComponent(sessionId)}/fork`,
4090
+ {
4091
+ method: "POST",
4092
+ body: parseForkSessionRequest({
4093
+ ...input,
4094
+ id: input.id ?? createPromptRequestId(),
4095
+ requestId: input.requestId ?? createPromptRequestId()
4096
+ }),
4097
+ signal: options.signal
4098
+ }
4099
+ );
4100
+ return response.session;
4101
+ }
4102
+ /** `DELETE /sessions/:id` */
4103
+ async archive(sessionId, options = {}) {
4104
+ const response = await this.transport.request(
4105
+ `/sessions/${encodeURIComponent(sessionId)}`,
4106
+ {
4107
+ method: "DELETE",
4108
+ signal: options.signal
4109
+ }
4110
+ );
4111
+ return response.session;
4112
+ }
4113
+ /** `DELETE /sessions/:id/hard` */
4114
+ async delete(sessionId, options = {}) {
4115
+ const response = await this.transport.request(`/sessions/${encodeURIComponent(sessionId)}/hard`, {
4116
+ method: "DELETE",
4117
+ signal: options.signal
4118
+ });
4119
+ return response.deletedSessionIds;
4120
+ }
4121
+ /** `GET /sessions/:id/state` - atomic attach snapshot plus SSE cursor. */
4122
+ async getState(sessionId, options = {}) {
4123
+ const response = await this.transport.request(
4124
+ this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/state`, {
4125
+ partView: options.partView
4126
+ }),
4127
+ {
4128
+ signal: options.signal
4129
+ }
4130
+ );
4131
+ return decodeAgentSessionStateSnapshot(response);
4132
+ }
4133
+ /** `GET /sessions/:id/messages` */
4134
+ async listMessages(sessionId, options = {}) {
4135
+ const { signal, ...query } = options;
4136
+ const response = await this.transport.request(
4137
+ this.transport.path(
4138
+ `/sessions/${encodeURIComponent(sessionId)}/messages`,
4139
+ query
4140
+ ),
4141
+ { signal }
4142
+ );
4143
+ return response.messages;
4144
+ }
4145
+ /** `GET /sessions/:id/parts` */
4146
+ async listMessageParts(sessionId, options = {}) {
4147
+ const { signal, ...query } = options;
4148
+ const response = await this.transport.request(
4149
+ this.transport.path(
4150
+ `/sessions/${encodeURIComponent(sessionId)}/parts`,
4151
+ query
4152
+ ),
4153
+ { signal }
4154
+ );
4155
+ return response.parts;
4156
+ }
4157
+ /** Read full canonical content for one part in its session/message scope. */
4158
+ async getMessagePart(sessionId, messageId, partId, options = {}) {
4159
+ const response = await this.transport.request(
4160
+ `/sessions/${encodeURIComponent(sessionId)}/messages/${encodeURIComponent(messageId)}/parts/${encodeURIComponent(partId)}`,
4161
+ options
4162
+ );
4163
+ return response.part;
4164
+ }
4165
+ /** `POST /sessions/:id/prompts` — 提交用户输入并触发/排队一次 run。 */
4166
+ async admitPrompt(sessionId, input, options = {}) {
4167
+ const schemaCheck = this.checkOutputSchema(input, options.signal);
4168
+ if (schemaCheck) await schemaCheck;
4169
+ return await this.transport.request(
4170
+ `/sessions/${encodeURIComponent(sessionId)}/prompts`,
4171
+ {
4172
+ method: "POST",
4173
+ body: { ...input, id: input.id ?? createPromptRequestId() },
4174
+ signal: options.signal
4175
+ }
4176
+ );
4177
+ }
4178
+ /** `POST /sessions/:id/prompts/latest/edit` */
4179
+ async editLatestPrompt(sessionId, input, options = {}) {
4180
+ await this.checkOutputSchema(input, options.signal);
4181
+ return await this.transport.request(
4182
+ `/sessions/${encodeURIComponent(sessionId)}/prompts/latest/edit`,
4183
+ {
4184
+ method: "POST",
4185
+ body: input,
4186
+ signal: options.signal
4187
+ }
4188
+ );
4189
+ }
4190
+ /** Promote one durable queued prompt into the exact active run. */
4191
+ async promoteQueuedPrompt(sessionId, inputId, input, options = {}) {
4192
+ return await this.transport.request(
4193
+ `/sessions/${encodeURIComponent(sessionId)}/prompts/${encodeURIComponent(inputId)}/promote`,
4194
+ { method: "POST", body: input, signal: options.signal }
4195
+ );
4196
+ }
4197
+ async cancelQueuedPrompt(sessionId, inputId, input, options = {}) {
4198
+ const mode = parseCancelResponseMode(options.responseMode);
4199
+ const response = await this.transport.request(
4200
+ `/sessions/${encodeURIComponent(sessionId)}/prompts/${encodeURIComponent(inputId)}/cancel`,
4201
+ {
4202
+ method: "POST",
4203
+ body: {
4204
+ ...input,
4205
+ ...options.responseMode ? { responseMode: mode } : {}
4206
+ },
4207
+ signal: options.signal
4208
+ }
4209
+ );
4210
+ if (mode === "receipt") {
4211
+ const receipt2 = decodeQueuedPromptCancelReceipt(response);
4212
+ if (receipt2.inputId !== inputId || receipt2.queuedRunId !== input.queuedRunId)
4213
+ throw new ProtocolDataError(
4214
+ "Cancellation receipt does not match target"
4215
+ );
4216
+ return receipt2;
4217
+ }
4218
+ return response;
4219
+ }
4220
+ /**
4221
+ * `POST /sessions/:id/runs/:runId/resume` — 显式重放一次中断 run 的原始 prompt。
4222
+ * 不会继续旧 provider stream;服务端会创建一个带恢复溯源的新 input/run。
4223
+ */
4224
+ async resumeInterruptedRun(sessionId, runId, input = {}, options = {}) {
4225
+ await this.checkOutputSchema(input, options.signal);
4226
+ return await this.transport.request(
4227
+ `/sessions/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(runId)}/resume`,
4228
+ {
4229
+ method: "POST",
4230
+ body: { ...input, id: input.id ?? createPromptRequestId() },
4231
+ signal: options.signal
4232
+ }
4233
+ );
4234
+ }
4235
+ /** `POST /sessions/:id/interrupt` — 中断当前/排队中的 run。 */
4236
+ async interrupt(sessionId, options = {}) {
4237
+ return await this.transport.request(
4238
+ `/sessions/${encodeURIComponent(sessionId)}/interrupt`,
4239
+ {
4240
+ method: "POST",
4241
+ body: options.expectedRunId || options.source ? {
4242
+ ...options.expectedRunId ? { expectedRunId: options.expectedRunId } : {},
4243
+ ...options.source ? { source: options.source } : {}
4244
+ } : void 0,
4245
+ signal: options.signal
4246
+ }
4247
+ );
4248
+ }
4249
+ /** `POST /sessions/:id/compact` */
4250
+ async compact(sessionId, options = {}) {
4251
+ return await this.transport.request(
4252
+ `/sessions/${encodeURIComponent(sessionId)}/compact`,
4253
+ {
4254
+ method: "POST",
4255
+ signal: options.signal,
4256
+ ...options.requestId ? {
4257
+ body: {
4258
+ requestId: options.requestId,
4259
+ expectedRevision: options.expectedRevision
4260
+ }
4261
+ } : {}
4262
+ }
4263
+ );
4264
+ }
4265
+ /** `POST /sessions/:id/rewind` */
4266
+ async rewind(sessionId, input = {}, options = {}) {
4267
+ return await this.transport.request(
4268
+ `/sessions/${encodeURIComponent(sessionId)}/rewind`,
4269
+ { method: "POST", body: input, signal: options.signal }
4270
+ );
4271
+ }
4272
+ /** `POST /sessions/:id/remember` */
4273
+ async remember(sessionId, options = {}) {
4274
+ return await this.transport.request(
4275
+ `/sessions/${encodeURIComponent(sessionId)}/remember`,
4276
+ { method: "POST", signal: options.signal }
4277
+ );
4278
+ }
4279
+ /** `POST /sessions/:id/export` */
4280
+ async export(sessionId, input = {}, options = {}) {
4281
+ return await this.transport.request(
4282
+ `/sessions/${encodeURIComponent(sessionId)}/export`,
4283
+ { method: "POST", body: input, signal: options.signal }
4284
+ );
4285
+ }
4286
+ /** `GET /sessions/:id/usage` */
4287
+ async getUsage(sessionId, options = {}) {
4288
+ return await this.transport.request(
4289
+ `/sessions/${encodeURIComponent(sessionId)}/usage`,
4290
+ { signal: options.signal }
4291
+ );
4292
+ }
4293
+ /** `GET /sessions/:id/goal` */
4294
+ async getGoal(sessionId) {
4295
+ const response = await this.transport.request(
4296
+ `/sessions/${encodeURIComponent(sessionId)}/goal`
4297
+ );
4298
+ return response.goal;
4299
+ }
4300
+ /** Reads the original durable action receipt after a response was lost. */
4301
+ async getGoalRequest(sessionId, requestId) {
4302
+ const receipt2 = decodeSessionGoalRequestReceipt(
4303
+ await this.transport.request(
4304
+ `/sessions/${encodeURIComponent(sessionId)}/goal/requests/${encodeURIComponent(requestId)}`
4305
+ )
4306
+ );
4307
+ if (receipt2.sessionId !== sessionId || receipt2.requestId !== requestId)
4308
+ throw new ProtocolDataError(
4309
+ "Goal request receipt does not match request"
4310
+ );
4311
+ return receipt2;
4312
+ }
4313
+ /** `POST /sessions/:id/goals` */
4314
+ async createGoal(sessionId, input) {
4315
+ const response = await this.transport.request(
4316
+ `/sessions/${encodeURIComponent(sessionId)}/goals`,
4317
+ { method: "POST", body: input }
4318
+ );
4319
+ return response.goal;
4320
+ }
4321
+ /** `PATCH /sessions/:id/goals/:goalId` */
4322
+ async updateGoal(sessionId, goalId, input) {
4323
+ const response = await this.transport.request(
4324
+ `/sessions/${encodeURIComponent(sessionId)}/goals/${encodeURIComponent(goalId)}`,
4325
+ { method: "PATCH", body: input }
4326
+ );
4327
+ return response.goal;
4328
+ }
4329
+ /** `POST /sessions/:id/goals/:goalId/actions` */
4330
+ async applyGoalAction(sessionId, goalId, input) {
4331
+ const response = await this.transport.request(
4332
+ `/sessions/${encodeURIComponent(sessionId)}/goals/${encodeURIComponent(goalId)}/actions`,
4333
+ { method: "POST", body: input }
4334
+ );
4335
+ return response.goal;
4336
+ }
4337
+ };
4338
+
4339
+ // src/resources/session/attachment-resource.ts
4340
+ var AttachmentResource = class {
4341
+ constructor(transport) {
4342
+ this.transport = transport;
4343
+ }
4344
+ transport;
4345
+ /** `POST /attachments` — upload bytes without JSON or multipart buffering. */
4346
+ async upload(input) {
4347
+ const headers2 = uploadIdentityHeaders(input);
4348
+ headers2["x-bobannomi-filename"] = encodeURIComponent(input.displayName);
4349
+ if (input.mediaType) headers2["content-type"] = input.mediaType;
4350
+ const response = await this.transport.requestResponse("/attachments", {
4351
+ method: "POST",
4352
+ headers: headers2,
4353
+ body: input.body,
4354
+ signal: input.signal
4355
+ });
4356
+ return parseAttachmentAssetRecord(await response.json());
4357
+ }
4358
+ async getUpload(input) {
4359
+ const response = await this.transport.requestResponse("/attachments/uploads", { headers: uploadIdentityHeaders(input), signal: input.signal });
4360
+ const value = await response.json();
4361
+ return value === null ? null : parseAttachmentAssetRecord(value);
4362
+ }
4363
+ async get(id2, options = {}) {
4364
+ const value = await this.transport.request(
4365
+ `/attachments/${encodeURIComponent(id2)}`,
4366
+ { signal: options.signal }
4367
+ );
4368
+ return parseAttachmentAssetRecord(value);
4369
+ }
4370
+ /** Returns the raw response so callers can consume the body as a stream. */
4371
+ async download(id2, options = {}) {
4372
+ const range = attachmentRangeHeader(options.range);
4373
+ const headers2 = {};
4374
+ if (range) headers2.range = range;
4375
+ return await this.transport.requestResponse(
4376
+ `/attachments/${encodeURIComponent(id2)}/content`,
4377
+ { method: "GET", headers: headers2, signal: options.signal }
4378
+ );
4379
+ }
4380
+ async delete(id2, options = {}) {
4381
+ const value = await this.transport.request(
4382
+ `/attachments/${encodeURIComponent(id2)}`,
4383
+ { method: "DELETE", signal: options.signal }
4384
+ );
4385
+ return parseAttachmentAssetRecord(value);
4386
+ }
4387
+ };
4388
+ function uploadIdentityHeaders(input) {
4389
+ parseAttachmentUploadRequest({ ...input, declaredMediaType: input.mediaType });
4390
+ return { "x-bobannomi-request-id": input.requestId, "x-bobannomi-draft-id": input.draftId, "x-bobannomi-sha256": input.expectedSha256, "x-bobannomi-byte-length": String(input.byteLength), "x-bobannomi-filename": encodeURIComponent(input.displayName), ...input.mediaType ? { "content-type": input.mediaType } : {} };
4391
+ }
4392
+
4393
+ // src/resources/configuration/permission-resource.ts
4394
+ var PermissionResource = class {
4395
+ constructor(transport) {
4396
+ this.transport = transport;
4397
+ }
4398
+ transport;
4399
+ /** Answer an actual AskUser question; this cannot approve tools. */
4400
+ async answerQuestion(requestId, input, options = {}) {
4401
+ const capabilities = await this.transport.ensureProtocol(options.signal);
4402
+ if ((capabilities.features.questions ?? 0) < 1) throw new Error("Server does not support questions");
4403
+ const response = await this.transport.request(
4404
+ `/permissions/${encodeURIComponent(requestId)}/answer`,
4405
+ { method: "POST", body: input, signal: options.signal }
4406
+ );
4407
+ return response.request;
4408
+ }
4409
+ async listApprovals() {
4410
+ const response = await this.transport.request("/permissions/approvals");
4411
+ return response.requests;
4412
+ }
4413
+ async revokeApproval(requestId) {
4414
+ const response = await this.transport.request(
4415
+ `/permissions/${encodeURIComponent(requestId)}/revoke`,
4416
+ { method: "POST" }
4417
+ );
4418
+ return response.request;
4419
+ }
4420
+ /** `GET /permissions` */
4421
+ async list(options = {}) {
4422
+ const { signal, ...query } = options;
4423
+ const response = await this.transport.request(this.transport.path("/permissions", query), { signal });
4424
+ return response.requests;
4425
+ }
4426
+ /** `POST /permissions/:id/reply` — 批准/拒绝工具权限请求。 */
4427
+ async reply(requestId, input, options = {}) {
4428
+ const response = await this.transport.request(
4429
+ `/permissions/${encodeURIComponent(requestId)}/reply`,
4430
+ {
4431
+ method: "POST",
4432
+ body: input,
4433
+ signal: options.signal
4434
+ }
4435
+ );
4436
+ return response.request;
4437
+ }
4438
+ };
4439
+
4440
+ // src/resources/runtime/job-resource.ts
4441
+ var JobResource = class {
4442
+ constructor(transport) {
4443
+ this.transport = transport;
4444
+ }
4445
+ transport;
4446
+ async list(options) {
4447
+ const { signal, kinds, statuses, includeFinished, ...query } = options;
4448
+ const response = await this.transport.request(
4449
+ this.transport.path("/jobs", {
4450
+ ...query,
4451
+ ...kinds ? { kinds: kinds.join(",") } : {},
4452
+ ...statuses ? { statuses: statuses.join(",") } : {},
4453
+ ...includeFinished !== void 0 ? { includeFinished: String(includeFinished) } : {}
4454
+ }),
4455
+ { signal }
4456
+ );
4457
+ return decodeJobListResult(response);
4458
+ }
4459
+ async createBackgroundShell(input, options = {}) {
4460
+ return await this.transport.request(
4461
+ "/background-shells",
4462
+ {
4463
+ method: "POST",
4464
+ body: input,
4465
+ signal: options.signal
4466
+ }
4467
+ );
4468
+ }
4469
+ async read(target, options) {
4470
+ const { signal, ...query } = options;
4471
+ const response = await this.transport.request(
4472
+ this.transport.path(`/jobs/${encodeURIComponent(target.jobId)}`, { ...query, kind: target.kind, ...target.kind === "agent" ? { runId: target.runId } : {} }),
4473
+ { signal }
4474
+ );
4475
+ return decodeJobReadResult(response);
4476
+ }
4477
+ async wait(target, input, options = {}) {
4478
+ const response = await this.transport.request(
4479
+ `/jobs/${encodeURIComponent(target.jobId)}/wait`,
4480
+ {
4481
+ method: "POST",
4482
+ body: { ...input, target },
4483
+ signal: options.signal
4484
+ }
4485
+ );
4486
+ return decodeJobWaitResult(response);
4487
+ }
4488
+ async send(target, input, options = {}) {
4489
+ const response = await this.transport.request(`/jobs/${encodeURIComponent(target.jobId)}/input`, {
4490
+ method: "POST",
4491
+ body: { ...input, target },
4492
+ signal: options.signal
4493
+ });
4494
+ if (responseField(response, "sent") !== true) throw new ProtocolDataError("Job input was not accepted", "sent");
4495
+ const receipt2 = response.receipt;
4496
+ return receipt2 === void 0 ? void 0 : decodeJobInputReceipt(receipt2);
4497
+ }
4498
+ async cancel(target, input, options = {}) {
4499
+ const mode = parseCancelResponseMode(options.responseMode);
4500
+ const response = await this.transport.request(
4501
+ `/jobs/${encodeURIComponent(target.jobId)}/cancel`,
4502
+ { method: "POST", body: { ...input, target, ...options.responseMode ? { responseMode: mode } : {} }, signal: options.signal }
4503
+ );
4504
+ if (mode === "receipt") {
4505
+ const receipt2 = decodeJobCancelReceipt(response);
4506
+ if (receipt2.id !== target.jobId) throw new ProtocolDataError("Cancellation receipt does not match target");
4507
+ return receipt2;
4508
+ }
4509
+ return decodeJobSnapshot(responseField(response, "snapshot"));
4510
+ }
4511
+ };
4512
+
4513
+ // src/resources/session/event-resource.ts
4514
+ var EventResource = class {
4515
+ constructor(transport, sse) {
4516
+ this.transport = transport;
4517
+ this.sse = sse;
4518
+ }
4519
+ transport;
4520
+ sse;
4521
+ /** `GET /events` — 用于 attach 时的历史 replay。 */
4522
+ async list(options = {}) {
4523
+ const { signal, ...query } = options;
4524
+ const response = await this.transport.request(
4525
+ this.transport.path("/events", query),
4526
+ { signal }
4527
+ );
4528
+ return responseArray2(response, "events", decodeSessionEventRecord);
4529
+ }
4530
+ stream(options = {}) {
4531
+ const query = {
4532
+ partView: options.partView,
4533
+ cursor: options.cursor,
4534
+ sessionId: options.sessionId
4535
+ };
4536
+ return this.sse.stream(this.transport.resolveUrl("/events/stream", query), {
4537
+ headers: this.transport.headers(),
4538
+ signal: options.signal,
4539
+ decode: decodeSessionEventRecord,
4540
+ reconnect: options.transportReconnect ?? false,
4541
+ onOpen: options.onOpen,
4542
+ idleTimeoutMs: options.idleTimeoutMs
4543
+ });
4544
+ }
4545
+ };
4546
+
4547
+ // src/resources/files/files-resource.ts
4548
+ var FilesResource = class {
4549
+ constructor(transport) {
4550
+ this.transport = transport;
4551
+ }
4552
+ transport;
4553
+ async list(sessionId, options = {}) {
4554
+ const { signal, ...query } = options;
4555
+ const response = await this.transport.request(
4556
+ this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/files`, query),
4557
+ { signal }
4558
+ );
4559
+ return decodeSessionDirectoryResult(response);
4560
+ }
4561
+ async stat(sessionId, path2, options = {}) {
4562
+ const response = await this.transport.request(
4563
+ this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/files/stat`, { path: path2 }),
4564
+ { signal: options.signal }
4565
+ );
4566
+ return decodeSessionFileInfo(response);
4567
+ }
4568
+ async readText(sessionId, path2, options = {}) {
4569
+ const { signal, ...query } = options;
4570
+ const response = await this.transport.request(
4571
+ this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/files/text`, { path: path2, ...query }),
4572
+ { signal }
4573
+ );
4574
+ return decodeSessionTextFileResult(response);
4575
+ }
4576
+ async find(sessionId, options) {
4577
+ const { signal, ...query } = options;
4578
+ const response = await this.transport.request(
4579
+ this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/files/find`, query),
4580
+ { signal }
4581
+ );
4582
+ return decodeSessionFindFilesResult(response);
4583
+ }
4584
+ async search(sessionId, options) {
4585
+ const { signal, caseSensitive, ...query } = options;
4586
+ const response = await this.transport.request(
4587
+ this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/files/search`, {
4588
+ ...query,
4589
+ ...caseSensitive === void 0 ? {} : { caseSensitive: String(caseSensitive) }
4590
+ }),
4591
+ { signal }
4592
+ );
4593
+ return decodeSessionSearchFilesResult(response);
4594
+ }
4595
+ };
4596
+
4597
+ // src/transport/http-client.ts
4598
+ var BobanNomiClient = class {
4599
+ protocol;
4600
+ runtime;
4601
+ schedules;
4602
+ sessions;
4603
+ attachments;
4604
+ permissions;
4605
+ jobs;
4606
+ events;
4607
+ files;
4608
+ constructor(options) {
4609
+ const transport = new HttpTransport(options);
4610
+ const sse = new SseTransport(transport);
4611
+ this.protocol = new ProtocolClient(transport);
4612
+ this.runtime = new RuntimeResource(transport);
4613
+ this.schedules = new ScheduleResource(transport);
4614
+ this.sessions = new SessionResource(transport);
4615
+ this.attachments = new AttachmentResource(transport);
4616
+ this.permissions = new PermissionResource(transport);
4617
+ this.jobs = new JobResource(transport);
4618
+ this.events = new EventResource(transport, sse);
4619
+ this.files = new FilesResource(transport);
4620
+ }
4621
+ };
4622
+
4623
+ // src/service/process.ts
4624
+ import { spawn } from "node:child_process";
4625
+ import { createRequire } from "node:module";
4626
+ import { readFile } from "node:fs/promises";
4627
+ import { dirname, resolve as resolve2 } from "node:path";
4628
+ async function defaultCommand(cwd, dataRoot) {
4629
+ try {
4630
+ const require2 = createRequire(resolve2(cwd, "package.json"));
4631
+ const manifestPath = require2.resolve("@bobannomi/cli/package.json");
4632
+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
4633
+ const bin = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.nomi;
4634
+ if (typeof bin !== "string") throw new Error("CLI bin is missing");
4635
+ return [process.execPath, resolve2(dirname(manifestPath), bin), "--data-root", dataRoot, "serve", "--register", "--host", "127.0.0.1", "--port", "0"];
4636
+ } catch {
4637
+ throw new Error("Cannot locate BobanNomi CLI. Install @bobannomi/cli in your application or pass Service.ensure({ command: [executable, ...args] }).");
4638
+ }
4639
+ }
4640
+ function startProcess(command, cwd, env) {
4641
+ if (!command[0]?.trim()) throw new Error("Service command must include an executable.");
4642
+ const child = spawn(command[0], command.slice(1), {
4643
+ cwd,
4644
+ env,
4645
+ stdio: "ignore",
4646
+ detached: true,
4647
+ windowsHide: true,
4648
+ shell: false
4649
+ });
4650
+ let failure;
4651
+ child.once("error", () => {
4652
+ failure = new Error("Cannot spawn BobanNomi service executable.");
4653
+ });
4654
+ child.once("exit", (code, signal) => {
4655
+ failure ??= new Error(`BobanNomi service exited before registration (${signal ?? code}).`);
4656
+ });
4657
+ child.unref();
4658
+ return { child, failure: () => failure };
4659
+ }
4660
+ async function abandonProcess(child) {
4661
+ if (!child.pid || child.exitCode !== null || child.signalCode !== null) return;
4662
+ await new Promise((resolve5) => {
4663
+ const timer = setTimeout(() => {
4664
+ child.kill("SIGKILL");
4665
+ resolve5();
4666
+ }, 500);
4667
+ child.once("exit", () => {
4668
+ clearTimeout(timer);
4669
+ resolve5();
4670
+ });
4671
+ child.kill("SIGTERM");
4672
+ });
4673
+ }
4674
+
4675
+ // src/service/registry.ts
4676
+ import { readFile as readFile2 } from "node:fs/promises";
4677
+ import { resolve as resolve3 } from "node:path";
4678
+ function pidAlive(pid) {
4679
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
4680
+ try {
4681
+ return process.kill(pid, 0);
4682
+ } catch (error) {
4683
+ return error.code === "EPERM";
4684
+ }
4685
+ }
4686
+ async function readEndpoint(file) {
4687
+ let text3;
4688
+ try {
4689
+ text3 = await readFile2(file, "utf8");
4690
+ } catch (error) {
4691
+ if (error.code === "ENOENT") return void 0;
4692
+ throw error;
4693
+ }
4694
+ try {
4695
+ const value = JSON.parse(text3);
4696
+ if (!value || typeof value !== "object" || !Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.token !== "string" || !value.token.trim() || typeof value.version !== "string" || !value.version.trim() || !Number.isSafeInteger(value.startedAt) || value.startedAt <= 0) return void 0;
4697
+ const url = normalizeDaemonBaseUrl(value.url);
4698
+ const address = new URL(url);
4699
+ if (!["127.0.0.1", "localhost", "[::1]"].includes(address.hostname)) return void 0;
4700
+ return {
4701
+ file: resolve3(file),
4702
+ url,
4703
+ pid: value.pid,
4704
+ token: value.token,
4705
+ version: value.version,
4706
+ startedAt: value.startedAt,
4707
+ ...typeof value.storePath === "string" ? { storePath: value.storePath } : {}
4708
+ };
4709
+ } catch {
4710
+ return void 0;
4711
+ }
4712
+ }
4713
+ function sameInstance(left, right) {
4714
+ return right !== void 0 && left.file === right.file && left.url === right.url && left.pid === right.pid && left.token === right.token && left.startedAt === right.startedAt && left.version === right.version && left.storePath === right.storePath;
4715
+ }
4716
+
4717
+ // src/service/startup-lock.ts
4718
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
4719
+ import { mkdir } from "node:fs/promises";
4720
+ import { dirname as dirname2 } from "node:path";
4721
+ import { setTimeout as sleep } from "node:timers/promises";
4722
+ async function acquireStartupLock(file, end, signal) {
4723
+ await mkdir(dirname2(file), { recursive: true });
4724
+ const compromised = new AbortController();
4725
+ while (Date.now() < end) {
4726
+ signal?.throwIfAborted();
4727
+ try {
4728
+ const release = await (0, import_proper_lockfile.lock)(file, {
4729
+ realpath: false,
4730
+ lockfilePath: `${file}.sdk-start.lock`,
4731
+ stale: 1e4,
4732
+ update: 5e3,
4733
+ retries: 0,
4734
+ onCompromised: (error) => compromised.abort(error)
4735
+ });
4736
+ return {
4737
+ signal: signal ? AbortSignal.any([signal, compromised.signal]) : compromised.signal,
4738
+ release
4739
+ };
4740
+ } catch (error) {
4741
+ if (error.code !== "ELOCKED") throw error;
4742
+ await sleep(Math.max(1, Math.min(50, end - Date.now())), void 0, { signal });
4743
+ }
4744
+ }
4745
+ throw new Error("BobanNomi service startup timed out waiting for the registry lock.");
4746
+ }
4747
+
4748
+ // src/service/service.ts
4749
+ function clientOptions(endpoint) {
4750
+ return { baseUrl: endpoint.url, token: endpoint.token };
4751
+ }
4752
+ function timeout(value, fallback) {
4753
+ const milliseconds = value ?? fallback;
4754
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0 || milliseconds > 2147483647)
4755
+ throw new Error("timeoutMs must be a positive integer no larger than 2147483647.");
4756
+ return milliseconds;
4757
+ }
4758
+ async function probe(endpoint, options, paths) {
4759
+ options.signal?.throwIfAborted();
4760
+ if (!pidAlive(endpoint.pid)) return false;
4761
+ if (typeof options.version === "string" && endpoint.version !== options.version) return false;
4762
+ if (typeof options.version === "function" && !options.version(endpoint.version)) return false;
4763
+ const deadline = AbortSignal.timeout(timeout(options.timeoutMs, 1e3));
4764
+ const signal = options.signal ? AbortSignal.any([options.signal, deadline]) : deadline;
4765
+ try {
4766
+ const client = new BobanNomiClient({
4767
+ ...clientOptions(endpoint),
4768
+ fetch: (input, init) => fetch(input, {
4769
+ ...init,
4770
+ signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal
4771
+ })
4772
+ });
4773
+ const health = await client.protocol.health({ signal });
4774
+ if (!health.ok || health.version !== endpoint.version) return false;
4775
+ if (paths) {
4776
+ const { daemonStorage } = await client.protocol.capabilities({ authenticated: true, scope: "protocol", signal });
4777
+ const key = (value) => process.platform === "win32" ? value.toLowerCase() : value;
4778
+ if (!daemonStorage || daemonStorage.pid !== endpoint.pid || !endpoint.storePath || key(daemonStorage.configDir) !== key(paths.dataRoot) || key(daemonStorage.dataDir) !== key(paths.dataDir) || key(daemonStorage.storePath) !== key(paths.sessionsDatabasePath) || key(endpoint.storePath) !== key(paths.sessionsDatabasePath)) return false;
4779
+ }
4780
+ const sessions = await client.sessions.list({ limit: 1, signal });
4781
+ return Array.isArray(sessions);
4782
+ } catch {
4783
+ options.signal?.throwIfAborted();
4784
+ return false;
4785
+ }
4786
+ }
4787
+ async function discover(options = {}) {
4788
+ options.signal?.throwIfAborted();
4789
+ timeout(options.timeoutMs, 1e3);
4790
+ return discoverAt({ ...options, ...await serviceLocation(options.file, { ...process.env, ...options.env }) });
4791
+ }
4792
+ async function discoverAt(options) {
4793
+ options.signal?.throwIfAborted();
4794
+ const endpoint = await readEndpoint(options.file);
4795
+ if (!endpoint || !await probe(endpoint, options, options.paths)) return void 0;
4796
+ return sameInstance(endpoint, await readEndpoint(endpoint.file)) ? endpoint : void 0;
4797
+ }
4798
+ async function serviceLocation(file, env) {
4799
+ if (file !== void 0) return { file: resolve4(file) };
4800
+ const paths = resolveUserDataPaths(selectDataRoot(void 0, env));
4801
+ assertUnifiedDataRoot(paths, env);
4802
+ const canonical = resolveUserDataPaths(await realpathAllowMissing(paths.dataRoot));
4803
+ return { file: canonical.daemonRegistryPath, paths: canonical };
4804
+ }
4805
+ async function realpathAllowMissing(path2) {
4806
+ try {
4807
+ return await realpath(path2);
4808
+ } catch (error) {
4809
+ const parent = dirname3(path2);
4810
+ if (error.code !== "ENOENT" || parent === path2) throw error;
4811
+ return join2(await realpathAllowMissing(parent), basename2(path2));
4812
+ }
4813
+ }
4814
+ var startups = /* @__PURE__ */ new Map();
4815
+ function waitForStartup(pending, signal) {
4816
+ signal?.throwIfAborted();
4817
+ if (!signal) return pending;
4818
+ return new Promise((resolve5, reject) => {
4819
+ const abort = () => reject(signal.reason);
4820
+ signal.addEventListener("abort", abort, { once: true });
4821
+ pending.then(resolve5, reject).finally(() => signal.removeEventListener("abort", abort));
4822
+ });
4823
+ }
4824
+ async function ensure(options = {}) {
4825
+ options.signal?.throwIfAborted();
4826
+ timeout(options.timeoutMs, 1e4);
4827
+ const env = { ...process.env, ...options.env };
4828
+ const { file, paths } = await serviceLocation(options.file, env);
4829
+ const existing = await discoverAt({ ...options, file, paths });
4830
+ if (existing) return existing;
4831
+ let pending = startups.get(file);
4832
+ const joining = pending !== void 0;
4833
+ if (!pending) {
4834
+ pending = startService({ ...options, file, paths }, env).finally(() => {
4835
+ startups.delete(file);
4836
+ });
4837
+ startups.set(file, pending);
4838
+ }
4839
+ const endpoint = await waitForStartup(pending, options.signal);
4840
+ options.signal?.throwIfAborted();
4841
+ if (typeof options.version === "string" && endpoint.version !== options.version || typeof options.version === "function" && !options.version(endpoint.version))
4842
+ throw new Error("Started service does not satisfy the requested version.");
4843
+ if (joining && paths && !await probe(endpoint, options, paths)) {
4844
+ throw new Error("Registered BobanNomi service does not match the selected dataRoot.");
4845
+ }
4846
+ return endpoint;
4847
+ }
4848
+ async function startService(options, env) {
4849
+ const end = Date.now() + timeout(options.timeoutMs, 1e4);
4850
+ if (!options.command && !options.paths && options.file !== (await serviceLocation(void 0, env)).file) {
4851
+ throw new Error("A custom registry file requires a command that writes it, or a matching BOBANNOMI_CONFIG_DIR.");
4852
+ }
4853
+ if (options.paths) env.BOBANNOMI_CONFIG_DIR = selectDataRoot(void 0, env);
4854
+ options.signal?.throwIfAborted();
4855
+ const lease = await acquireStartupLock(options.file, end, options.signal);
4856
+ try {
4857
+ const locked = { ...options, signal: lease.signal };
4858
+ const existing = await discoverAt({ ...locked, timeoutMs: Math.max(1, Math.min(1e3, end - Date.now())) });
4859
+ if (existing) return existing;
4860
+ return await startRegisteredService(locked, env, end);
4861
+ } finally {
4862
+ await lease.release();
4863
+ }
4864
+ }
4865
+ async function startRegisteredService(options, env, end) {
4866
+ const previous = await readEndpoint(options.file);
4867
+ if (previous && pidAlive(previous.pid))
4868
+ throw new Error("Registered BobanNomi service is incompatible or unhealthy; manage it explicitly before starting another.");
4869
+ if (!previous && await access(options.file).then(() => true, () => false))
4870
+ throw new Error("BobanNomi registry is malformed; inspect it before starting a service.");
4871
+ const cwd = resolve4(options.cwd ?? process.cwd());
4872
+ const command = options.command ?? await defaultCommand(cwd, selectDataRoot(void 0, env));
4873
+ options.signal?.throwIfAborted();
4874
+ if (Date.now() >= end) throw new Error("BobanNomi service startup timed out before process creation.");
4875
+ const started = startProcess(command, cwd, env);
4876
+ try {
4877
+ while (Date.now() < end) {
4878
+ options.signal?.throwIfAborted();
4879
+ const endpoint = await discoverAt({ ...options, timeoutMs: Math.max(1, Math.min(1e3, end - Date.now())) });
4880
+ if (endpoint && !sameInstance(endpoint, previous)) return endpoint;
4881
+ const failure = started.failure();
4882
+ if (failure) throw failure;
4883
+ await sleep2(Math.min(50, Math.max(1, end - Date.now())), void 0, { signal: options.signal });
4884
+ }
4885
+ throw new Error("BobanNomi service startup timed out before compatible registration.");
4886
+ } catch (error) {
4887
+ await abandonProcess(started.child);
4888
+ const current = await readEndpoint(options.file);
4889
+ if (current && current.pid === started.child.pid && !pidAlive(current.pid)) {
4890
+ if (sameInstance(current, await readEndpoint(options.file))) await unlink(options.file).catch(() => {
4891
+ });
4892
+ }
4893
+ throw error;
4894
+ }
4895
+ }
4896
+ async function stop(endpoint, options = {}) {
4897
+ options.signal?.throwIfAborted();
4898
+ const milliseconds = timeout(options.timeoutMs, 5e3);
4899
+ if (endpoint.pid === process.pid) throw new Error("Refusing to stop the calling process.");
4900
+ if (!sameInstance(endpoint, await readEndpoint(endpoint.file))) return false;
4901
+ if (!await probe(endpoint, { ...options, timeoutMs: Math.min(1e3, milliseconds) })) return false;
4902
+ if (!sameInstance(endpoint, await readEndpoint(endpoint.file))) return false;
4903
+ process.kill(endpoint.pid, "SIGTERM");
4904
+ const end = Date.now() + milliseconds;
4905
+ while (pidAlive(endpoint.pid) && Date.now() < end) await sleep2(25, void 0, { signal: options.signal });
4906
+ if (pidAlive(endpoint.pid)) throw new Error("BobanNomi service did not stop before the deadline.");
4907
+ if (sameInstance(endpoint, await readEndpoint(endpoint.file))) await unlink(endpoint.file).catch(() => {
4908
+ });
4909
+ return true;
4910
+ }
4911
+
4912
+ // src/service/index.ts
4913
+ var Service = { discover, ensure, stop, clientOptions };
4914
+ export {
4915
+ Service,
4916
+ clientOptions,
4917
+ discover,
4918
+ ensure,
4919
+ stop
4920
+ };
4921
+ //# sourceMappingURL=service.js.map