@aspectlylabs/mikka 0.0.0-stage → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/http-link.js ADDED
@@ -0,0 +1,4502 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ try {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ } catch (e) {
11
+ throw mod = 0, e;
12
+ }
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key2 of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key2) && key2 !== except)
18
+ __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ // If the importer is in node compatibility mode or this is not an ESM
24
+ // file that has been converted to a CommonJS file using a Babel-
25
+ // compatible transform (i.e. "__esModule" has not been set), then set
26
+ // "default" to the CommonJS "module.exports" for node compatibility.
27
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
+ mod
29
+ ));
30
+
31
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js
32
+ var require_constants = __commonJS({
33
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js"(exports, module) {
34
+ "use strict";
35
+ var SEMVER_SPEC_VERSION = "2.0.0";
36
+ var MAX_LENGTH = 256;
37
+ var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
38
+ 9007199254740991;
39
+ var MAX_SAFE_COMPONENT_LENGTH = 16;
40
+ var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
41
+ var RELEASE_TYPES = [
42
+ "major",
43
+ "premajor",
44
+ "minor",
45
+ "preminor",
46
+ "patch",
47
+ "prepatch",
48
+ "prerelease"
49
+ ];
50
+ module.exports = {
51
+ MAX_LENGTH,
52
+ MAX_SAFE_COMPONENT_LENGTH,
53
+ MAX_SAFE_BUILD_LENGTH,
54
+ MAX_SAFE_INTEGER,
55
+ RELEASE_TYPES,
56
+ SEMVER_SPEC_VERSION,
57
+ FLAG_INCLUDE_PRERELEASE: 1,
58
+ FLAG_LOOSE: 2
59
+ };
60
+ }
61
+ });
62
+
63
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js
64
+ var require_debug = __commonJS({
65
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js"(exports, module) {
66
+ "use strict";
67
+ var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
68
+ };
69
+ module.exports = debug;
70
+ }
71
+ });
72
+
73
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js
74
+ var require_re = __commonJS({
75
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js"(exports, module) {
76
+ "use strict";
77
+ var {
78
+ MAX_SAFE_COMPONENT_LENGTH,
79
+ MAX_SAFE_BUILD_LENGTH,
80
+ MAX_LENGTH
81
+ } = require_constants();
82
+ var debug = require_debug();
83
+ exports = module.exports = {};
84
+ var re = exports.re = [];
85
+ var safeRe = exports.safeRe = [];
86
+ var src = exports.src = [];
87
+ var safeSrc = exports.safeSrc = [];
88
+ var t = exports.t = {};
89
+ var R = 0;
90
+ var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
91
+ var safeRegexReplacements = [
92
+ ["\\s", 1],
93
+ ["\\d", MAX_LENGTH],
94
+ [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
95
+ ];
96
+ var makeSafeRegex = (value) => {
97
+ for (const [token, max] of safeRegexReplacements) {
98
+ value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
99
+ }
100
+ return value;
101
+ };
102
+ var createToken = (name, value, isGlobal) => {
103
+ const safe = makeSafeRegex(value);
104
+ const index = R++;
105
+ debug(name, index, value);
106
+ t[name] = index;
107
+ src[index] = value;
108
+ safeSrc[index] = safe;
109
+ re[index] = new RegExp(value, isGlobal ? "g" : void 0);
110
+ safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0);
111
+ };
112
+ createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
113
+ createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
114
+ createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
115
+ createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`);
116
+ createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`);
117
+ createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`);
118
+ createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`);
119
+ createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
120
+ createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
121
+ createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
122
+ createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
123
+ createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
124
+ createToken("FULL", `^${src[t.FULLPLAIN]}$`);
125
+ createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
126
+ createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`);
127
+ createToken("GTLT", "((?:<|>)?=?)");
128
+ createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
129
+ createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
130
+ createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`);
131
+ createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`);
132
+ createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
133
+ createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
134
+ createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
135
+ createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`);
136
+ createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`);
137
+ createToken("COERCERTL", src[t.COERCE], true);
138
+ createToken("COERCERTLFULL", src[t.COERCEFULL], true);
139
+ createToken("LONETILDE", "(?:~>?)");
140
+ createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true);
141
+ exports.tildeTrimReplace = "$1~";
142
+ createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
143
+ createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
144
+ createToken("LONECARET", "(?:\\^)");
145
+ createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true);
146
+ exports.caretTrimReplace = "$1^";
147
+ createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
148
+ createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
149
+ createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
150
+ createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
151
+ createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
152
+ exports.comparatorTrimReplace = "$1$2$3";
153
+ createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`);
154
+ createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`);
155
+ createToken("STAR", "(<|>)?=?\\s*\\*");
156
+ createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
157
+ createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
158
+ }
159
+ });
160
+
161
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js
162
+ var require_parse_options = __commonJS({
163
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js"(exports, module) {
164
+ "use strict";
165
+ var looseOption = Object.freeze({ loose: true });
166
+ var emptyOpts = Object.freeze({});
167
+ var parseOptions = (options) => {
168
+ if (!options) {
169
+ return emptyOpts;
170
+ }
171
+ if (typeof options !== "object") {
172
+ return looseOption;
173
+ }
174
+ return options;
175
+ };
176
+ module.exports = parseOptions;
177
+ }
178
+ });
179
+
180
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js
181
+ var require_identifiers = __commonJS({
182
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js"(exports, module) {
183
+ "use strict";
184
+ var numeric = /^[0-9]+$/;
185
+ var compareIdentifiers = (a, b) => {
186
+ if (typeof a === "number" && typeof b === "number") {
187
+ return a === b ? 0 : a < b ? -1 : 1;
188
+ }
189
+ const anum = numeric.test(a);
190
+ const bnum = numeric.test(b);
191
+ if (anum && bnum) {
192
+ a = +a;
193
+ b = +b;
194
+ }
195
+ return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
196
+ };
197
+ var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
198
+ module.exports = {
199
+ compareIdentifiers,
200
+ rcompareIdentifiers
201
+ };
202
+ }
203
+ });
204
+
205
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js
206
+ var require_semver = __commonJS({
207
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js"(exports, module) {
208
+ "use strict";
209
+ var debug = require_debug();
210
+ var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants();
211
+ var { safeRe: re, t } = require_re();
212
+ var parseOptions = require_parse_options();
213
+ var { compareIdentifiers } = require_identifiers();
214
+ var isPrereleaseIdentifier = (prerelease, identifier) => {
215
+ const identifiers = identifier.split(".");
216
+ if (identifiers.length > prerelease.length) {
217
+ return false;
218
+ }
219
+ for (let i = 0; i < identifiers.length; i++) {
220
+ if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) {
221
+ return false;
222
+ }
223
+ }
224
+ return true;
225
+ };
226
+ var SemVer = class _SemVer {
227
+ constructor(version, options) {
228
+ options = parseOptions(options);
229
+ if (version instanceof _SemVer) {
230
+ if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
231
+ return version;
232
+ } else {
233
+ version = version.version;
234
+ }
235
+ } else if (typeof version !== "string") {
236
+ throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`);
237
+ }
238
+ if (version.length > MAX_LENGTH) {
239
+ throw new TypeError(
240
+ `version is longer than ${MAX_LENGTH} characters`
241
+ );
242
+ }
243
+ debug("SemVer", version, options);
244
+ this.options = options;
245
+ this.loose = !!options.loose;
246
+ this.includePrerelease = !!options.includePrerelease;
247
+ const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
248
+ if (!m) {
249
+ throw new TypeError(`Invalid Version: ${version}`);
250
+ }
251
+ this.raw = version;
252
+ this.major = +m[1];
253
+ this.minor = +m[2];
254
+ this.patch = +m[3];
255
+ if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
256
+ throw new TypeError("Invalid major version");
257
+ }
258
+ if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
259
+ throw new TypeError("Invalid minor version");
260
+ }
261
+ if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
262
+ throw new TypeError("Invalid patch version");
263
+ }
264
+ if (!m[4]) {
265
+ this.prerelease = [];
266
+ } else {
267
+ this.prerelease = m[4].split(".").map((id3) => {
268
+ if (/^[0-9]+$/.test(id3)) {
269
+ const num = +id3;
270
+ if (num >= 0 && num < MAX_SAFE_INTEGER) {
271
+ return num;
272
+ }
273
+ }
274
+ return id3;
275
+ });
276
+ }
277
+ this.build = m[5] ? m[5].split(".") : [];
278
+ this.format();
279
+ }
280
+ format() {
281
+ this.version = `${this.major}.${this.minor}.${this.patch}`;
282
+ if (this.prerelease.length) {
283
+ this.version += `-${this.prerelease.join(".")}`;
284
+ }
285
+ return this.version;
286
+ }
287
+ toString() {
288
+ return this.version;
289
+ }
290
+ compare(other) {
291
+ debug("SemVer.compare", this.version, this.options, other);
292
+ if (!(other instanceof _SemVer)) {
293
+ if (typeof other === "string" && other === this.version) {
294
+ return 0;
295
+ }
296
+ other = new _SemVer(other, this.options);
297
+ }
298
+ if (other.version === this.version) {
299
+ return 0;
300
+ }
301
+ return this.compareMain(other) || this.comparePre(other);
302
+ }
303
+ compareMain(other) {
304
+ if (!(other instanceof _SemVer)) {
305
+ other = new _SemVer(other, this.options);
306
+ }
307
+ if (this.major < other.major) {
308
+ return -1;
309
+ }
310
+ if (this.major > other.major) {
311
+ return 1;
312
+ }
313
+ if (this.minor < other.minor) {
314
+ return -1;
315
+ }
316
+ if (this.minor > other.minor) {
317
+ return 1;
318
+ }
319
+ if (this.patch < other.patch) {
320
+ return -1;
321
+ }
322
+ if (this.patch > other.patch) {
323
+ return 1;
324
+ }
325
+ return 0;
326
+ }
327
+ comparePre(other) {
328
+ if (!(other instanceof _SemVer)) {
329
+ other = new _SemVer(other, this.options);
330
+ }
331
+ if (this.prerelease.length && !other.prerelease.length) {
332
+ return -1;
333
+ } else if (!this.prerelease.length && other.prerelease.length) {
334
+ return 1;
335
+ } else if (!this.prerelease.length && !other.prerelease.length) {
336
+ return 0;
337
+ }
338
+ let i = 0;
339
+ do {
340
+ const a = this.prerelease[i];
341
+ const b = other.prerelease[i];
342
+ debug("prerelease compare", i, a, b);
343
+ if (a === void 0 && b === void 0) {
344
+ return 0;
345
+ } else if (b === void 0) {
346
+ return 1;
347
+ } else if (a === void 0) {
348
+ return -1;
349
+ } else if (a === b) {
350
+ continue;
351
+ } else {
352
+ return compareIdentifiers(a, b);
353
+ }
354
+ } while (++i);
355
+ }
356
+ compareBuild(other) {
357
+ if (!(other instanceof _SemVer)) {
358
+ other = new _SemVer(other, this.options);
359
+ }
360
+ let i = 0;
361
+ do {
362
+ const a = this.build[i];
363
+ const b = other.build[i];
364
+ debug("build compare", i, a, b);
365
+ if (a === void 0 && b === void 0) {
366
+ return 0;
367
+ } else if (b === void 0) {
368
+ return 1;
369
+ } else if (a === void 0) {
370
+ return -1;
371
+ } else if (a === b) {
372
+ continue;
373
+ } else {
374
+ return compareIdentifiers(a, b);
375
+ }
376
+ } while (++i);
377
+ }
378
+ // preminor will bump the version up to the next minor release, and immediately
379
+ // down to pre-release. premajor and prepatch work the same way.
380
+ inc(release, identifier, identifierBase) {
381
+ if (release.startsWith("pre")) {
382
+ if (!identifier && identifierBase === false) {
383
+ throw new Error("invalid increment argument: identifier is empty");
384
+ }
385
+ if (identifier) {
386
+ const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]);
387
+ if (!match || match[1] !== identifier) {
388
+ throw new Error(`invalid identifier: ${identifier}`);
389
+ }
390
+ }
391
+ }
392
+ switch (release) {
393
+ case "premajor":
394
+ this.prerelease.length = 0;
395
+ this.patch = 0;
396
+ this.minor = 0;
397
+ this.major++;
398
+ this.inc("pre", identifier, identifierBase);
399
+ break;
400
+ case "preminor":
401
+ this.prerelease.length = 0;
402
+ this.patch = 0;
403
+ this.minor++;
404
+ this.inc("pre", identifier, identifierBase);
405
+ break;
406
+ case "prepatch":
407
+ this.prerelease.length = 0;
408
+ this.inc("patch", identifier, identifierBase);
409
+ this.inc("pre", identifier, identifierBase);
410
+ break;
411
+ // If the input is a non-prerelease version, this acts the same as
412
+ // prepatch.
413
+ case "prerelease":
414
+ if (this.prerelease.length === 0) {
415
+ this.inc("patch", identifier, identifierBase);
416
+ }
417
+ this.inc("pre", identifier, identifierBase);
418
+ break;
419
+ case "release":
420
+ if (this.prerelease.length === 0) {
421
+ throw new Error(`version ${this.raw} is not a prerelease`);
422
+ }
423
+ this.prerelease.length = 0;
424
+ break;
425
+ case "major":
426
+ if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
427
+ this.major++;
428
+ }
429
+ this.minor = 0;
430
+ this.patch = 0;
431
+ this.prerelease = [];
432
+ break;
433
+ case "minor":
434
+ if (this.patch !== 0 || this.prerelease.length === 0) {
435
+ this.minor++;
436
+ }
437
+ this.patch = 0;
438
+ this.prerelease = [];
439
+ break;
440
+ case "patch":
441
+ if (this.prerelease.length === 0) {
442
+ this.patch++;
443
+ }
444
+ this.prerelease = [];
445
+ break;
446
+ // This probably shouldn't be used publicly.
447
+ // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
448
+ case "pre": {
449
+ const base = Number(identifierBase) ? 1 : 0;
450
+ if (this.prerelease.length === 0) {
451
+ this.prerelease = [base];
452
+ } else {
453
+ let i = this.prerelease.length;
454
+ while (--i >= 0) {
455
+ if (typeof this.prerelease[i] === "number") {
456
+ this.prerelease[i]++;
457
+ i = -2;
458
+ }
459
+ }
460
+ if (i === -1) {
461
+ if (identifier === this.prerelease.join(".") && identifierBase === false) {
462
+ throw new Error("invalid increment argument: identifier already exists");
463
+ }
464
+ this.prerelease.push(base);
465
+ }
466
+ }
467
+ if (identifier) {
468
+ let prerelease = [identifier, base];
469
+ if (identifierBase === false) {
470
+ prerelease = [identifier];
471
+ }
472
+ if (isPrereleaseIdentifier(this.prerelease, identifier)) {
473
+ const prereleaseBase = this.prerelease[identifier.split(".").length];
474
+ if (isNaN(prereleaseBase)) {
475
+ this.prerelease = prerelease;
476
+ }
477
+ } else {
478
+ this.prerelease = prerelease;
479
+ }
480
+ }
481
+ break;
482
+ }
483
+ default:
484
+ throw new Error(`invalid increment argument: ${release}`);
485
+ }
486
+ this.raw = this.format();
487
+ if (this.build.length) {
488
+ this.raw += `+${this.build.join(".")}`;
489
+ }
490
+ return this;
491
+ }
492
+ };
493
+ module.exports = SemVer;
494
+ }
495
+ });
496
+
497
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/parse.js
498
+ var require_parse = __commonJS({
499
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/parse.js"(exports, module) {
500
+ "use strict";
501
+ var SemVer = require_semver();
502
+ var parse = (version, options, throwErrors = false) => {
503
+ if (version instanceof SemVer) {
504
+ return version;
505
+ }
506
+ try {
507
+ return new SemVer(version, options);
508
+ } catch (er) {
509
+ if (!throwErrors) {
510
+ return null;
511
+ }
512
+ throw er;
513
+ }
514
+ };
515
+ module.exports = parse;
516
+ }
517
+ });
518
+
519
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/valid.js
520
+ var require_valid = __commonJS({
521
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/valid.js"(exports, module) {
522
+ "use strict";
523
+ var parse = require_parse();
524
+ var valid2 = (version, options) => {
525
+ const v2 = parse(version, options);
526
+ return v2 ? v2.version : null;
527
+ };
528
+ module.exports = valid2;
529
+ }
530
+ });
531
+
532
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/clean.js
533
+ var require_clean = __commonJS({
534
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/clean.js"(exports, module) {
535
+ "use strict";
536
+ var parse = require_parse();
537
+ var clean = (version, options) => {
538
+ const s = parse(version.trim().replace(/^[=v]+/, ""), options);
539
+ return s ? s.version : null;
540
+ };
541
+ module.exports = clean;
542
+ }
543
+ });
544
+
545
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/inc.js
546
+ var require_inc = __commonJS({
547
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/inc.js"(exports, module) {
548
+ "use strict";
549
+ var SemVer = require_semver();
550
+ var inc = (version, release, options, identifier, identifierBase) => {
551
+ if (typeof options === "string") {
552
+ identifierBase = identifier;
553
+ identifier = options;
554
+ options = void 0;
555
+ }
556
+ try {
557
+ return new SemVer(
558
+ version instanceof SemVer ? version.version : version,
559
+ options
560
+ ).inc(release, identifier, identifierBase).version;
561
+ } catch (er) {
562
+ return null;
563
+ }
564
+ };
565
+ module.exports = inc;
566
+ }
567
+ });
568
+
569
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/diff.js
570
+ var require_diff = __commonJS({
571
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/diff.js"(exports, module) {
572
+ "use strict";
573
+ var parse = require_parse();
574
+ var diff = (version1, version2) => {
575
+ const v1 = parse(version1, null, true);
576
+ const v2 = parse(version2, null, true);
577
+ const comparison = v1.compare(v2);
578
+ if (comparison === 0) {
579
+ return null;
580
+ }
581
+ const v1Higher = comparison > 0;
582
+ const highVersion = v1Higher ? v1 : v2;
583
+ const lowVersion = v1Higher ? v2 : v1;
584
+ const highHasPre = !!highVersion.prerelease.length;
585
+ const lowHasPre = !!lowVersion.prerelease.length;
586
+ if (lowHasPre && !highHasPre) {
587
+ if (!lowVersion.patch && !lowVersion.minor) {
588
+ return "major";
589
+ }
590
+ if (lowVersion.compareMain(highVersion) === 0) {
591
+ if (lowVersion.minor && !lowVersion.patch) {
592
+ return "minor";
593
+ }
594
+ return "patch";
595
+ }
596
+ }
597
+ const prefix = highHasPre ? "pre" : "";
598
+ if (v1.major !== v2.major) {
599
+ return prefix + "major";
600
+ }
601
+ if (v1.minor !== v2.minor) {
602
+ return prefix + "minor";
603
+ }
604
+ if (v1.patch !== v2.patch) {
605
+ return prefix + "patch";
606
+ }
607
+ return "prerelease";
608
+ };
609
+ module.exports = diff;
610
+ }
611
+ });
612
+
613
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/major.js
614
+ var require_major = __commonJS({
615
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/major.js"(exports, module) {
616
+ "use strict";
617
+ var SemVer = require_semver();
618
+ var major = (a, loose) => new SemVer(a, loose).major;
619
+ module.exports = major;
620
+ }
621
+ });
622
+
623
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/minor.js
624
+ var require_minor = __commonJS({
625
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/minor.js"(exports, module) {
626
+ "use strict";
627
+ var SemVer = require_semver();
628
+ var minor = (a, loose) => new SemVer(a, loose).minor;
629
+ module.exports = minor;
630
+ }
631
+ });
632
+
633
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/patch.js
634
+ var require_patch = __commonJS({
635
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/patch.js"(exports, module) {
636
+ "use strict";
637
+ var SemVer = require_semver();
638
+ var patch = (a, loose) => new SemVer(a, loose).patch;
639
+ module.exports = patch;
640
+ }
641
+ });
642
+
643
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/prerelease.js
644
+ var require_prerelease = __commonJS({
645
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/prerelease.js"(exports, module) {
646
+ "use strict";
647
+ var parse = require_parse();
648
+ var prerelease = (version, options) => {
649
+ const parsed = parse(version, options);
650
+ return parsed && parsed.prerelease.length ? parsed.prerelease : null;
651
+ };
652
+ module.exports = prerelease;
653
+ }
654
+ });
655
+
656
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js
657
+ var require_compare = __commonJS({
658
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js"(exports, module) {
659
+ "use strict";
660
+ var SemVer = require_semver();
661
+ var compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose));
662
+ module.exports = compare;
663
+ }
664
+ });
665
+
666
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rcompare.js
667
+ var require_rcompare = __commonJS({
668
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rcompare.js"(exports, module) {
669
+ "use strict";
670
+ var compare = require_compare();
671
+ var rcompare = (a, b, loose) => compare(b, a, loose);
672
+ module.exports = rcompare;
673
+ }
674
+ });
675
+
676
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-loose.js
677
+ var require_compare_loose = __commonJS({
678
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-loose.js"(exports, module) {
679
+ "use strict";
680
+ var compare = require_compare();
681
+ var compareLoose = (a, b) => compare(a, b, true);
682
+ module.exports = compareLoose;
683
+ }
684
+ });
685
+
686
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-build.js
687
+ var require_compare_build = __commonJS({
688
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-build.js"(exports, module) {
689
+ "use strict";
690
+ var SemVer = require_semver();
691
+ var compareBuild = (a, b, loose) => {
692
+ const versionA = new SemVer(a, loose);
693
+ const versionB = new SemVer(b, loose);
694
+ return versionA.compare(versionB) || versionA.compareBuild(versionB);
695
+ };
696
+ module.exports = compareBuild;
697
+ }
698
+ });
699
+
700
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/sort.js
701
+ var require_sort = __commonJS({
702
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/sort.js"(exports, module) {
703
+ "use strict";
704
+ var compareBuild = require_compare_build();
705
+ var sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose));
706
+ module.exports = sort;
707
+ }
708
+ });
709
+
710
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rsort.js
711
+ var require_rsort = __commonJS({
712
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rsort.js"(exports, module) {
713
+ "use strict";
714
+ var compareBuild = require_compare_build();
715
+ var rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
716
+ module.exports = rsort;
717
+ }
718
+ });
719
+
720
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gt.js
721
+ var require_gt = __commonJS({
722
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gt.js"(exports, module) {
723
+ "use strict";
724
+ var compare = require_compare();
725
+ var gt = (a, b, loose) => compare(a, b, loose) > 0;
726
+ module.exports = gt;
727
+ }
728
+ });
729
+
730
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lt.js
731
+ var require_lt = __commonJS({
732
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lt.js"(exports, module) {
733
+ "use strict";
734
+ var compare = require_compare();
735
+ var lt = (a, b, loose) => compare(a, b, loose) < 0;
736
+ module.exports = lt;
737
+ }
738
+ });
739
+
740
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/eq.js
741
+ var require_eq = __commonJS({
742
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/eq.js"(exports, module) {
743
+ "use strict";
744
+ var compare = require_compare();
745
+ var eq = (a, b, loose) => compare(a, b, loose) === 0;
746
+ module.exports = eq;
747
+ }
748
+ });
749
+
750
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/neq.js
751
+ var require_neq = __commonJS({
752
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/neq.js"(exports, module) {
753
+ "use strict";
754
+ var compare = require_compare();
755
+ var neq = (a, b, loose) => compare(a, b, loose) !== 0;
756
+ module.exports = neq;
757
+ }
758
+ });
759
+
760
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js
761
+ var require_gte = __commonJS({
762
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js"(exports, module) {
763
+ "use strict";
764
+ var compare = require_compare();
765
+ var gte2 = (a, b, loose) => compare(a, b, loose) >= 0;
766
+ module.exports = gte2;
767
+ }
768
+ });
769
+
770
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lte.js
771
+ var require_lte = __commonJS({
772
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lte.js"(exports, module) {
773
+ "use strict";
774
+ var compare = require_compare();
775
+ var lte = (a, b, loose) => compare(a, b, loose) <= 0;
776
+ module.exports = lte;
777
+ }
778
+ });
779
+
780
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/cmp.js
781
+ var require_cmp = __commonJS({
782
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/cmp.js"(exports, module) {
783
+ "use strict";
784
+ var eq = require_eq();
785
+ var neq = require_neq();
786
+ var gt = require_gt();
787
+ var gte2 = require_gte();
788
+ var lt = require_lt();
789
+ var lte = require_lte();
790
+ var cmp = (a, op, b, loose) => {
791
+ switch (op) {
792
+ case "===":
793
+ if (typeof a === "object") {
794
+ a = a.version;
795
+ }
796
+ if (typeof b === "object") {
797
+ b = b.version;
798
+ }
799
+ return a === b;
800
+ case "!==":
801
+ if (typeof a === "object") {
802
+ a = a.version;
803
+ }
804
+ if (typeof b === "object") {
805
+ b = b.version;
806
+ }
807
+ return a !== b;
808
+ case "":
809
+ case "=":
810
+ case "==":
811
+ return eq(a, b, loose);
812
+ case "!=":
813
+ return neq(a, b, loose);
814
+ case ">":
815
+ return gt(a, b, loose);
816
+ case ">=":
817
+ return gte2(a, b, loose);
818
+ case "<":
819
+ return lt(a, b, loose);
820
+ case "<=":
821
+ return lte(a, b, loose);
822
+ default:
823
+ throw new TypeError(`Invalid operator: ${op}`);
824
+ }
825
+ };
826
+ module.exports = cmp;
827
+ }
828
+ });
829
+
830
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/coerce.js
831
+ var require_coerce = __commonJS({
832
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/coerce.js"(exports, module) {
833
+ "use strict";
834
+ var SemVer = require_semver();
835
+ var parse = require_parse();
836
+ var { safeRe: re, t } = require_re();
837
+ var coerce2 = (version, options) => {
838
+ if (version instanceof SemVer) {
839
+ return version;
840
+ }
841
+ if (typeof version === "number") {
842
+ version = String(version);
843
+ }
844
+ if (typeof version !== "string") {
845
+ return null;
846
+ }
847
+ options = options || {};
848
+ let match = null;
849
+ if (!options.rtl) {
850
+ match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]);
851
+ } else {
852
+ const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL];
853
+ let next;
854
+ while ((next = coerceRtlRegex.exec(version)) && (!match || match.index + match[0].length !== version.length)) {
855
+ if (!match || next.index + next[0].length !== match.index + match[0].length) {
856
+ match = next;
857
+ }
858
+ coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
859
+ }
860
+ coerceRtlRegex.lastIndex = -1;
861
+ }
862
+ if (match === null) {
863
+ return null;
864
+ }
865
+ const major = match[2];
866
+ const minor = match[3] || "0";
867
+ const patch = match[4] || "0";
868
+ const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : "";
869
+ const build = options.includePrerelease && match[6] ? `+${match[6]}` : "";
870
+ return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options);
871
+ };
872
+ module.exports = coerce2;
873
+ }
874
+ });
875
+
876
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/truncate.js
877
+ var require_truncate = __commonJS({
878
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/truncate.js"(exports, module) {
879
+ "use strict";
880
+ var parse = require_parse();
881
+ var constants = require_constants();
882
+ var SemVer = require_semver();
883
+ var truncate = (version, truncation, options) => {
884
+ if (!constants.RELEASE_TYPES.includes(truncation)) {
885
+ return null;
886
+ }
887
+ const clonedVersion = cloneInputVersion(version, options);
888
+ return clonedVersion && doTruncation(clonedVersion, truncation);
889
+ };
890
+ var cloneInputVersion = (version, options) => {
891
+ const versionStringToParse = version instanceof SemVer ? version.version : version;
892
+ return parse(versionStringToParse, options);
893
+ };
894
+ var doTruncation = (version, truncation) => {
895
+ if (isPrerelease(truncation)) {
896
+ return version.version;
897
+ }
898
+ version.prerelease = [];
899
+ switch (truncation) {
900
+ case "major":
901
+ version.minor = 0;
902
+ version.patch = 0;
903
+ break;
904
+ case "minor":
905
+ version.patch = 0;
906
+ break;
907
+ }
908
+ return version.format();
909
+ };
910
+ var isPrerelease = (type) => {
911
+ return type.startsWith("pre");
912
+ };
913
+ module.exports = truncate;
914
+ }
915
+ });
916
+
917
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/lrucache.js
918
+ var require_lrucache = __commonJS({
919
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/lrucache.js"(exports, module) {
920
+ "use strict";
921
+ var LRUCache = class {
922
+ constructor() {
923
+ this.max = 1e3;
924
+ this.map = /* @__PURE__ */ new Map();
925
+ }
926
+ get(key2) {
927
+ const value = this.map.get(key2);
928
+ if (value === void 0) {
929
+ return void 0;
930
+ } else {
931
+ this.map.delete(key2);
932
+ this.map.set(key2, value);
933
+ return value;
934
+ }
935
+ }
936
+ delete(key2) {
937
+ return this.map.delete(key2);
938
+ }
939
+ set(key2, value) {
940
+ const deleted = this.delete(key2);
941
+ if (!deleted && value !== void 0) {
942
+ if (this.map.size >= this.max) {
943
+ const firstKey = this.map.keys().next().value;
944
+ this.delete(firstKey);
945
+ }
946
+ this.map.set(key2, value);
947
+ }
948
+ return this;
949
+ }
950
+ };
951
+ module.exports = LRUCache;
952
+ }
953
+ });
954
+
955
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/range.js
956
+ var require_range = __commonJS({
957
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/range.js"(exports, module) {
958
+ "use strict";
959
+ var SPACE_CHARACTERS = /\s+/g;
960
+ var Range = class _Range {
961
+ constructor(range, options) {
962
+ options = parseOptions(options);
963
+ if (range instanceof _Range) {
964
+ if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
965
+ return range;
966
+ } else {
967
+ return new _Range(range.raw, options);
968
+ }
969
+ }
970
+ if (range instanceof Comparator) {
971
+ this.raw = range.value;
972
+ this.set = [[range]];
973
+ this.formatted = void 0;
974
+ return this;
975
+ }
976
+ this.options = options;
977
+ this.loose = !!options.loose;
978
+ this.includePrerelease = !!options.includePrerelease;
979
+ this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
980
+ this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c) => c.length);
981
+ if (!this.set.length) {
982
+ throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
983
+ }
984
+ if (this.set.length > 1) {
985
+ const first = this.set[0];
986
+ this.set = this.set.filter((c) => !isNullSet(c[0]));
987
+ if (this.set.length === 0) {
988
+ this.set = [first];
989
+ } else if (this.set.length > 1) {
990
+ for (const c of this.set) {
991
+ if (c.length === 1 && isAny(c[0])) {
992
+ this.set = [c];
993
+ break;
994
+ }
995
+ }
996
+ }
997
+ }
998
+ this.formatted = void 0;
999
+ }
1000
+ get range() {
1001
+ if (this.formatted === void 0) {
1002
+ this.formatted = "";
1003
+ for (let i = 0; i < this.set.length; i++) {
1004
+ if (i > 0) {
1005
+ this.formatted += "||";
1006
+ }
1007
+ const comps = this.set[i];
1008
+ for (let k = 0; k < comps.length; k++) {
1009
+ if (k > 0) {
1010
+ this.formatted += " ";
1011
+ }
1012
+ this.formatted += comps[k].toString().trim();
1013
+ }
1014
+ }
1015
+ }
1016
+ return this.formatted;
1017
+ }
1018
+ format() {
1019
+ return this.range;
1020
+ }
1021
+ toString() {
1022
+ return this.range;
1023
+ }
1024
+ parseRange(range) {
1025
+ range = range.replace(BUILDSTRIPRE, "");
1026
+ const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
1027
+ const memoKey = memoOpts + ":" + range;
1028
+ const cached = cache.get(memoKey);
1029
+ if (cached) {
1030
+ return cached;
1031
+ }
1032
+ const loose = this.options.loose;
1033
+ const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
1034
+ range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
1035
+ debug("hyphen replace", range);
1036
+ range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
1037
+ debug("comparator trim", range);
1038
+ range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
1039
+ debug("tilde trim", range);
1040
+ range = range.replace(re[t.CARETTRIM], caretTrimReplace);
1041
+ debug("caret trim", range);
1042
+ let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
1043
+ if (loose) {
1044
+ rangeList = rangeList.filter((comp) => {
1045
+ debug("loose invalid filter", comp, this.options);
1046
+ return !!comp.match(re[t.COMPARATORLOOSE]);
1047
+ });
1048
+ }
1049
+ debug("range list", rangeList);
1050
+ const rangeMap = /* @__PURE__ */ new Map();
1051
+ const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
1052
+ for (const comp of comparators) {
1053
+ if (isNullSet(comp)) {
1054
+ return [comp];
1055
+ }
1056
+ rangeMap.set(comp.value, comp);
1057
+ }
1058
+ if (rangeMap.size > 1 && rangeMap.has("")) {
1059
+ rangeMap.delete("");
1060
+ }
1061
+ const result = [...rangeMap.values()];
1062
+ cache.set(memoKey, result);
1063
+ return result;
1064
+ }
1065
+ intersects(range, options) {
1066
+ if (!(range instanceof _Range)) {
1067
+ throw new TypeError("a Range is required");
1068
+ }
1069
+ return this.set.some((thisComparators) => {
1070
+ return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {
1071
+ return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
1072
+ return rangeComparators.every((rangeComparator) => {
1073
+ return thisComparator.intersects(rangeComparator, options);
1074
+ });
1075
+ });
1076
+ });
1077
+ });
1078
+ }
1079
+ // if ANY of the sets match ALL of its comparators, then pass
1080
+ test(version) {
1081
+ if (!version) {
1082
+ return false;
1083
+ }
1084
+ if (typeof version === "string") {
1085
+ try {
1086
+ version = new SemVer(version, this.options);
1087
+ } catch (er) {
1088
+ return false;
1089
+ }
1090
+ }
1091
+ for (let i = 0; i < this.set.length; i++) {
1092
+ if (testSet(this.set[i], version, this.options)) {
1093
+ return true;
1094
+ }
1095
+ }
1096
+ return false;
1097
+ }
1098
+ };
1099
+ module.exports = Range;
1100
+ var LRU = require_lrucache();
1101
+ var cache = new LRU();
1102
+ var parseOptions = require_parse_options();
1103
+ var Comparator = require_comparator();
1104
+ var debug = require_debug();
1105
+ var SemVer = require_semver();
1106
+ var {
1107
+ safeRe: re,
1108
+ src,
1109
+ t,
1110
+ comparatorTrimReplace,
1111
+ tildeTrimReplace,
1112
+ caretTrimReplace
1113
+ } = require_re();
1114
+ var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants();
1115
+ var BUILDSTRIPRE = new RegExp(src[t.BUILD], "g");
1116
+ var isNullSet = (c) => c.value === "<0.0.0-0";
1117
+ var isAny = (c) => c.value === "";
1118
+ var isSatisfiable = (comparators, options) => {
1119
+ let result = true;
1120
+ const remainingComparators = comparators.slice();
1121
+ let testComparator = remainingComparators.pop();
1122
+ while (result && remainingComparators.length) {
1123
+ result = remainingComparators.every((otherComparator) => {
1124
+ return testComparator.intersects(otherComparator, options);
1125
+ });
1126
+ testComparator = remainingComparators.pop();
1127
+ }
1128
+ return result;
1129
+ };
1130
+ var parseComparator = (comp, options) => {
1131
+ comp = comp.replace(re[t.BUILD], "");
1132
+ debug("comp", comp, options);
1133
+ comp = replaceCarets(comp, options);
1134
+ debug("caret", comp);
1135
+ comp = replaceTildes(comp, options);
1136
+ debug("tildes", comp);
1137
+ comp = replaceXRanges(comp, options);
1138
+ debug("xrange", comp);
1139
+ comp = replaceStars(comp, options);
1140
+ debug("stars", comp);
1141
+ return comp;
1142
+ };
1143
+ var isX = (id3) => !id3 || id3.toLowerCase() === "x" || id3 === "*";
1144
+ var invalidXRangeOrder = (M, m, p) => isX(M) && !isX(m) || isX(m) && p && !isX(p);
1145
+ var replaceTildes = (comp, options) => {
1146
+ return comp.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" ");
1147
+ };
1148
+ var replaceTilde = (comp, options) => {
1149
+ const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
1150
+ const z26 = options.includePrerelease ? "-0" : "";
1151
+ return comp.replace(r, (_, M, m, p, pr) => {
1152
+ debug("tilde", comp, _, M, m, p, pr);
1153
+ let ret;
1154
+ if (isX(M)) {
1155
+ ret = "";
1156
+ } else if (isX(m)) {
1157
+ ret = `>=${M}.0.0${z26} <${+M + 1}.0.0-0`;
1158
+ } else if (isX(p)) {
1159
+ ret = `>=${M}.${m}.0${z26} <${M}.${+m + 1}.0-0`;
1160
+ } else if (pr) {
1161
+ debug("replaceTilde pr", pr);
1162
+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
1163
+ } else {
1164
+ ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
1165
+ }
1166
+ debug("tilde return", ret);
1167
+ return ret;
1168
+ });
1169
+ };
1170
+ var replaceCarets = (comp, options) => {
1171
+ return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" ");
1172
+ };
1173
+ var replaceCaret = (comp, options) => {
1174
+ debug("caret", comp, options);
1175
+ const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
1176
+ const z26 = options.includePrerelease ? "-0" : "";
1177
+ return comp.replace(r, (_, M, m, p, pr) => {
1178
+ debug("caret", comp, _, M, m, p, pr);
1179
+ let ret;
1180
+ if (isX(M)) {
1181
+ ret = "";
1182
+ } else if (isX(m)) {
1183
+ ret = `>=${M}.0.0${z26} <${+M + 1}.0.0-0`;
1184
+ } else if (isX(p)) {
1185
+ if (M === "0") {
1186
+ ret = `>=${M}.${m}.0${z26} <${M}.${+m + 1}.0-0`;
1187
+ } else {
1188
+ ret = `>=${M}.${m}.0${z26} <${+M + 1}.0.0-0`;
1189
+ }
1190
+ } else if (pr) {
1191
+ debug("replaceCaret pr", pr);
1192
+ if (M === "0") {
1193
+ if (m === "0") {
1194
+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
1195
+ } else {
1196
+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
1197
+ }
1198
+ } else {
1199
+ ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
1200
+ }
1201
+ } else {
1202
+ debug("no pr");
1203
+ if (M === "0") {
1204
+ if (m === "0") {
1205
+ ret = `>=${M}.${m}.${p} <${M}.${m}.${+p + 1}-0`;
1206
+ } else {
1207
+ ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
1208
+ }
1209
+ } else {
1210
+ ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
1211
+ }
1212
+ }
1213
+ debug("caret return", ret);
1214
+ return ret;
1215
+ });
1216
+ };
1217
+ var replaceXRanges = (comp, options) => {
1218
+ debug("replaceXRanges", comp, options);
1219
+ return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" ");
1220
+ };
1221
+ var replaceXRange = (comp, options) => {
1222
+ comp = comp.trim();
1223
+ const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
1224
+ return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
1225
+ debug("xRange", comp, ret, gtlt, M, m, p, pr);
1226
+ if (invalidXRangeOrder(M, m, p)) {
1227
+ return comp;
1228
+ }
1229
+ const xM = isX(M);
1230
+ const xm = xM || isX(m);
1231
+ const xp = xm || isX(p);
1232
+ const anyX = xp;
1233
+ if (gtlt === "=" && anyX) {
1234
+ gtlt = "";
1235
+ }
1236
+ pr = options.includePrerelease ? "-0" : "";
1237
+ if (xM) {
1238
+ if (gtlt === ">" || gtlt === "<") {
1239
+ ret = "<0.0.0-0";
1240
+ } else {
1241
+ ret = "*";
1242
+ }
1243
+ } else if (gtlt && anyX) {
1244
+ if (xm) {
1245
+ m = 0;
1246
+ }
1247
+ p = 0;
1248
+ if (gtlt === ">") {
1249
+ gtlt = ">=";
1250
+ if (xm) {
1251
+ M = +M + 1;
1252
+ m = 0;
1253
+ p = 0;
1254
+ } else {
1255
+ m = +m + 1;
1256
+ p = 0;
1257
+ }
1258
+ } else if (gtlt === "<=") {
1259
+ gtlt = "<";
1260
+ if (xm) {
1261
+ M = +M + 1;
1262
+ } else {
1263
+ m = +m + 1;
1264
+ }
1265
+ }
1266
+ if (gtlt === "<") {
1267
+ pr = "-0";
1268
+ }
1269
+ ret = `${gtlt + M}.${m}.${p}${pr}`;
1270
+ } else if (xm) {
1271
+ ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
1272
+ } else if (xp) {
1273
+ ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
1274
+ }
1275
+ debug("xRange return", ret);
1276
+ return ret;
1277
+ });
1278
+ };
1279
+ var replaceStars = (comp, options) => {
1280
+ debug("replaceStars", comp, options);
1281
+ return comp.trim().replace(re[t.STAR], "");
1282
+ };
1283
+ var replaceGTE0 = (comp, options) => {
1284
+ debug("replaceGTE0", comp, options);
1285
+ return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], "");
1286
+ };
1287
+ var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
1288
+ if (isX(fM)) {
1289
+ from = "";
1290
+ } else if (isX(fm)) {
1291
+ from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
1292
+ } else if (isX(fp)) {
1293
+ from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
1294
+ } else if (fpr) {
1295
+ from = `>=${from}`;
1296
+ } else {
1297
+ from = `>=${from}${incPr ? "-0" : ""}`;
1298
+ }
1299
+ if (isX(tM)) {
1300
+ to = "";
1301
+ } else if (isX(tm)) {
1302
+ to = `<${+tM + 1}.0.0-0`;
1303
+ } else if (isX(tp)) {
1304
+ to = `<${tM}.${+tm + 1}.0-0`;
1305
+ } else if (tpr) {
1306
+ to = `<=${tM}.${tm}.${tp}-${tpr}`;
1307
+ } else if (incPr) {
1308
+ to = `<${tM}.${tm}.${+tp + 1}-0`;
1309
+ } else {
1310
+ to = `<=${to}`;
1311
+ }
1312
+ return `${from} ${to}`.trim();
1313
+ };
1314
+ var testSet = (set, version, options) => {
1315
+ for (let i = 0; i < set.length; i++) {
1316
+ if (!set[i].test(version)) {
1317
+ return false;
1318
+ }
1319
+ }
1320
+ if (version.prerelease.length && !options.includePrerelease) {
1321
+ for (let i = 0; i < set.length; i++) {
1322
+ debug(set[i].semver);
1323
+ if (set[i].semver === Comparator.ANY) {
1324
+ continue;
1325
+ }
1326
+ if (set[i].semver.prerelease.length > 0) {
1327
+ const allowed = set[i].semver;
1328
+ if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
1329
+ return true;
1330
+ }
1331
+ }
1332
+ }
1333
+ return false;
1334
+ }
1335
+ return true;
1336
+ };
1337
+ }
1338
+ });
1339
+
1340
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/comparator.js
1341
+ var require_comparator = __commonJS({
1342
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/comparator.js"(exports, module) {
1343
+ "use strict";
1344
+ var ANY = /* @__PURE__ */ Symbol("SemVer ANY");
1345
+ var Comparator = class _Comparator {
1346
+ static get ANY() {
1347
+ return ANY;
1348
+ }
1349
+ constructor(comp, options) {
1350
+ options = parseOptions(options);
1351
+ if (comp instanceof _Comparator) {
1352
+ if (comp.loose === !!options.loose) {
1353
+ return comp;
1354
+ } else {
1355
+ comp = comp.value;
1356
+ }
1357
+ }
1358
+ comp = comp.trim().split(/\s+/).join(" ");
1359
+ debug("comparator", comp, options);
1360
+ this.options = options;
1361
+ this.loose = !!options.loose;
1362
+ this.parse(comp);
1363
+ if (this.semver === ANY) {
1364
+ this.value = "";
1365
+ } else {
1366
+ this.value = this.operator + this.semver.version;
1367
+ }
1368
+ debug("comp", this);
1369
+ }
1370
+ parse(comp) {
1371
+ const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
1372
+ const m = comp.match(r);
1373
+ if (!m) {
1374
+ throw new TypeError(`Invalid comparator: ${comp}`);
1375
+ }
1376
+ this.operator = m[1] !== void 0 ? m[1] : "";
1377
+ if (this.operator === "=") {
1378
+ this.operator = "";
1379
+ }
1380
+ if (!m[2]) {
1381
+ this.semver = ANY;
1382
+ } else {
1383
+ this.semver = new SemVer(m[2], this.options.loose);
1384
+ }
1385
+ }
1386
+ toString() {
1387
+ return this.value;
1388
+ }
1389
+ test(version) {
1390
+ debug("Comparator.test", version, this.options.loose);
1391
+ if (this.semver === ANY || version === ANY) {
1392
+ return true;
1393
+ }
1394
+ if (typeof version === "string") {
1395
+ try {
1396
+ version = new SemVer(version, this.options);
1397
+ } catch (er) {
1398
+ return false;
1399
+ }
1400
+ }
1401
+ return cmp(version, this.operator, this.semver, this.options);
1402
+ }
1403
+ intersects(comp, options) {
1404
+ if (!(comp instanceof _Comparator)) {
1405
+ throw new TypeError("a Comparator is required");
1406
+ }
1407
+ if (this.operator === "") {
1408
+ if (this.value === "") {
1409
+ return true;
1410
+ }
1411
+ return new Range(comp.value, options).test(this.value);
1412
+ } else if (comp.operator === "") {
1413
+ if (comp.value === "") {
1414
+ return true;
1415
+ }
1416
+ return new Range(this.value, options).test(comp.semver);
1417
+ }
1418
+ options = parseOptions(options);
1419
+ if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
1420
+ return false;
1421
+ }
1422
+ if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
1423
+ return false;
1424
+ }
1425
+ if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
1426
+ return true;
1427
+ }
1428
+ if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
1429
+ return true;
1430
+ }
1431
+ if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
1432
+ return true;
1433
+ }
1434
+ if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
1435
+ return true;
1436
+ }
1437
+ if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
1438
+ return true;
1439
+ }
1440
+ return false;
1441
+ }
1442
+ };
1443
+ module.exports = Comparator;
1444
+ var parseOptions = require_parse_options();
1445
+ var { safeRe: re, t } = require_re();
1446
+ var cmp = require_cmp();
1447
+ var debug = require_debug();
1448
+ var SemVer = require_semver();
1449
+ var Range = require_range();
1450
+ }
1451
+ });
1452
+
1453
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/satisfies.js
1454
+ var require_satisfies = __commonJS({
1455
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/satisfies.js"(exports, module) {
1456
+ "use strict";
1457
+ var Range = require_range();
1458
+ var satisfies = (version, range, options) => {
1459
+ try {
1460
+ range = new Range(range, options);
1461
+ } catch (er) {
1462
+ return false;
1463
+ }
1464
+ return range.test(version);
1465
+ };
1466
+ module.exports = satisfies;
1467
+ }
1468
+ });
1469
+
1470
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/to-comparators.js
1471
+ var require_to_comparators = __commonJS({
1472
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/to-comparators.js"(exports, module) {
1473
+ "use strict";
1474
+ var Range = require_range();
1475
+ var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" "));
1476
+ module.exports = toComparators;
1477
+ }
1478
+ });
1479
+
1480
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/max-satisfying.js
1481
+ var require_max_satisfying = __commonJS({
1482
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/max-satisfying.js"(exports, module) {
1483
+ "use strict";
1484
+ var SemVer = require_semver();
1485
+ var Range = require_range();
1486
+ var maxSatisfying = (versions, range, options) => {
1487
+ let max = null;
1488
+ let maxSV = null;
1489
+ let rangeObj = null;
1490
+ try {
1491
+ rangeObj = new Range(range, options);
1492
+ } catch (er) {
1493
+ return null;
1494
+ }
1495
+ versions.forEach((v2) => {
1496
+ if (rangeObj.test(v2)) {
1497
+ if (!max || maxSV.compare(v2) === -1) {
1498
+ max = v2;
1499
+ maxSV = new SemVer(max, options);
1500
+ }
1501
+ }
1502
+ });
1503
+ return max;
1504
+ };
1505
+ module.exports = maxSatisfying;
1506
+ }
1507
+ });
1508
+
1509
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-satisfying.js
1510
+ var require_min_satisfying = __commonJS({
1511
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-satisfying.js"(exports, module) {
1512
+ "use strict";
1513
+ var SemVer = require_semver();
1514
+ var Range = require_range();
1515
+ var minSatisfying = (versions, range, options) => {
1516
+ let min = null;
1517
+ let minSV = null;
1518
+ let rangeObj = null;
1519
+ try {
1520
+ rangeObj = new Range(range, options);
1521
+ } catch (er) {
1522
+ return null;
1523
+ }
1524
+ versions.forEach((v2) => {
1525
+ if (rangeObj.test(v2)) {
1526
+ if (!min || minSV.compare(v2) === 1) {
1527
+ min = v2;
1528
+ minSV = new SemVer(min, options);
1529
+ }
1530
+ }
1531
+ });
1532
+ return min;
1533
+ };
1534
+ module.exports = minSatisfying;
1535
+ }
1536
+ });
1537
+
1538
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-version.js
1539
+ var require_min_version = __commonJS({
1540
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-version.js"(exports, module) {
1541
+ "use strict";
1542
+ var SemVer = require_semver();
1543
+ var Range = require_range();
1544
+ var gt = require_gt();
1545
+ var minVersion = (range, loose) => {
1546
+ range = new Range(range, loose);
1547
+ let minver = new SemVer("0.0.0");
1548
+ if (range.test(minver)) {
1549
+ return minver;
1550
+ }
1551
+ minver = new SemVer("0.0.0-0");
1552
+ if (range.test(minver)) {
1553
+ return minver;
1554
+ }
1555
+ minver = null;
1556
+ for (let i = 0; i < range.set.length; ++i) {
1557
+ const comparators = range.set[i];
1558
+ let setMin = null;
1559
+ comparators.forEach((comparator) => {
1560
+ const compver = new SemVer(comparator.semver.version);
1561
+ switch (comparator.operator) {
1562
+ case ">":
1563
+ if (compver.prerelease.length === 0) {
1564
+ compver.patch++;
1565
+ } else {
1566
+ compver.prerelease.push(0);
1567
+ }
1568
+ compver.raw = compver.format();
1569
+ /* fallthrough */
1570
+ case "":
1571
+ case ">=":
1572
+ if (!setMin || gt(compver, setMin)) {
1573
+ setMin = compver;
1574
+ }
1575
+ break;
1576
+ case "<":
1577
+ case "<=":
1578
+ break;
1579
+ /* istanbul ignore next */
1580
+ default:
1581
+ throw new Error(`Unexpected operation: ${comparator.operator}`);
1582
+ }
1583
+ });
1584
+ if (setMin && (!minver || gt(minver, setMin))) {
1585
+ minver = setMin;
1586
+ }
1587
+ }
1588
+ if (minver && range.test(minver)) {
1589
+ return minver;
1590
+ }
1591
+ return null;
1592
+ };
1593
+ module.exports = minVersion;
1594
+ }
1595
+ });
1596
+
1597
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/valid.js
1598
+ var require_valid2 = __commonJS({
1599
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/valid.js"(exports, module) {
1600
+ "use strict";
1601
+ var Range = require_range();
1602
+ var validRange = (range, options) => {
1603
+ try {
1604
+ return new Range(range, options).range || "*";
1605
+ } catch (er) {
1606
+ return null;
1607
+ }
1608
+ };
1609
+ module.exports = validRange;
1610
+ }
1611
+ });
1612
+
1613
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/outside.js
1614
+ var require_outside = __commonJS({
1615
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/outside.js"(exports, module) {
1616
+ "use strict";
1617
+ var SemVer = require_semver();
1618
+ var Comparator = require_comparator();
1619
+ var { ANY } = Comparator;
1620
+ var Range = require_range();
1621
+ var satisfies = require_satisfies();
1622
+ var gt = require_gt();
1623
+ var lt = require_lt();
1624
+ var lte = require_lte();
1625
+ var gte2 = require_gte();
1626
+ var outside = (version, range, hilo, options) => {
1627
+ version = new SemVer(version, options);
1628
+ range = new Range(range, options);
1629
+ let gtfn, ltefn, ltfn, comp, ecomp;
1630
+ switch (hilo) {
1631
+ case ">":
1632
+ gtfn = gt;
1633
+ ltefn = lte;
1634
+ ltfn = lt;
1635
+ comp = ">";
1636
+ ecomp = ">=";
1637
+ break;
1638
+ case "<":
1639
+ gtfn = lt;
1640
+ ltefn = gte2;
1641
+ ltfn = gt;
1642
+ comp = "<";
1643
+ ecomp = "<=";
1644
+ break;
1645
+ default:
1646
+ throw new TypeError('Must provide a hilo val of "<" or ">"');
1647
+ }
1648
+ if (satisfies(version, range, options)) {
1649
+ return false;
1650
+ }
1651
+ for (let i = 0; i < range.set.length; ++i) {
1652
+ const comparators = range.set[i];
1653
+ let high = null;
1654
+ let low = null;
1655
+ comparators.forEach((comparator) => {
1656
+ if (comparator.semver === ANY) {
1657
+ comparator = new Comparator(">=0.0.0");
1658
+ }
1659
+ high = high || comparator;
1660
+ low = low || comparator;
1661
+ if (gtfn(comparator.semver, high.semver, options)) {
1662
+ high = comparator;
1663
+ } else if (ltfn(comparator.semver, low.semver, options)) {
1664
+ low = comparator;
1665
+ }
1666
+ });
1667
+ if (high.operator === comp || high.operator === ecomp) {
1668
+ return false;
1669
+ }
1670
+ if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
1671
+ return false;
1672
+ } else if (low.operator === ecomp && ltfn(version, low.semver)) {
1673
+ return false;
1674
+ }
1675
+ }
1676
+ return true;
1677
+ };
1678
+ module.exports = outside;
1679
+ }
1680
+ });
1681
+
1682
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/gtr.js
1683
+ var require_gtr = __commonJS({
1684
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/gtr.js"(exports, module) {
1685
+ "use strict";
1686
+ var outside = require_outside();
1687
+ var gtr = (version, range, options) => outside(version, range, ">", options);
1688
+ module.exports = gtr;
1689
+ }
1690
+ });
1691
+
1692
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/ltr.js
1693
+ var require_ltr = __commonJS({
1694
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/ltr.js"(exports, module) {
1695
+ "use strict";
1696
+ var outside = require_outside();
1697
+ var ltr = (version, range, options) => outside(version, range, "<", options);
1698
+ module.exports = ltr;
1699
+ }
1700
+ });
1701
+
1702
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/intersects.js
1703
+ var require_intersects = __commonJS({
1704
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/intersects.js"(exports, module) {
1705
+ "use strict";
1706
+ var Range = require_range();
1707
+ var intersects = (r1, r2, options) => {
1708
+ r1 = new Range(r1, options);
1709
+ r2 = new Range(r2, options);
1710
+ return r1.intersects(r2, options);
1711
+ };
1712
+ module.exports = intersects;
1713
+ }
1714
+ });
1715
+
1716
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/simplify.js
1717
+ var require_simplify = __commonJS({
1718
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/simplify.js"(exports, module) {
1719
+ "use strict";
1720
+ var satisfies = require_satisfies();
1721
+ var compare = require_compare();
1722
+ module.exports = (versions, range, options) => {
1723
+ const set = [];
1724
+ let first = null;
1725
+ let prev = null;
1726
+ const v2 = versions.sort((a, b) => compare(a, b, options));
1727
+ for (const version of v2) {
1728
+ const included = satisfies(version, range, options);
1729
+ if (included) {
1730
+ prev = version;
1731
+ if (!first) {
1732
+ first = version;
1733
+ }
1734
+ } else {
1735
+ if (prev) {
1736
+ set.push([first, prev]);
1737
+ }
1738
+ prev = null;
1739
+ first = null;
1740
+ }
1741
+ }
1742
+ if (first) {
1743
+ set.push([first, null]);
1744
+ }
1745
+ const ranges = [];
1746
+ for (const [min, max] of set) {
1747
+ if (min === max) {
1748
+ ranges.push(min);
1749
+ } else if (!max && min === v2[0]) {
1750
+ ranges.push("*");
1751
+ } else if (!max) {
1752
+ ranges.push(`>=${min}`);
1753
+ } else if (min === v2[0]) {
1754
+ ranges.push(`<=${max}`);
1755
+ } else {
1756
+ ranges.push(`${min} - ${max}`);
1757
+ }
1758
+ }
1759
+ const simplified = ranges.join(" || ");
1760
+ const original = typeof range.raw === "string" ? range.raw : String(range);
1761
+ return simplified.length < original.length ? simplified : range;
1762
+ };
1763
+ }
1764
+ });
1765
+
1766
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/subset.js
1767
+ var require_subset = __commonJS({
1768
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/subset.js"(exports, module) {
1769
+ "use strict";
1770
+ var Range = require_range();
1771
+ var Comparator = require_comparator();
1772
+ var { ANY } = Comparator;
1773
+ var satisfies = require_satisfies();
1774
+ var compare = require_compare();
1775
+ var subset = (sub, dom, options = {}) => {
1776
+ if (sub === dom) {
1777
+ return true;
1778
+ }
1779
+ sub = new Range(sub, options);
1780
+ dom = new Range(dom, options);
1781
+ let sawNonNull = false;
1782
+ OUTER: for (const simpleSub of sub.set) {
1783
+ for (const simpleDom of dom.set) {
1784
+ const isSub = simpleSubset(simpleSub, simpleDom, options);
1785
+ sawNonNull = sawNonNull || isSub !== null;
1786
+ if (isSub) {
1787
+ continue OUTER;
1788
+ }
1789
+ }
1790
+ if (sawNonNull) {
1791
+ return false;
1792
+ }
1793
+ }
1794
+ return true;
1795
+ };
1796
+ var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")];
1797
+ var minimumVersion = [new Comparator(">=0.0.0")];
1798
+ var simpleSubset = (sub, dom, options) => {
1799
+ if (sub === dom) {
1800
+ return true;
1801
+ }
1802
+ if (sub.length === 1 && sub[0].semver === ANY) {
1803
+ if (dom.length === 1 && dom[0].semver === ANY) {
1804
+ return true;
1805
+ } else if (options.includePrerelease) {
1806
+ sub = minimumVersionWithPreRelease;
1807
+ } else {
1808
+ sub = minimumVersion;
1809
+ }
1810
+ }
1811
+ if (dom.length === 1 && dom[0].semver === ANY) {
1812
+ if (options.includePrerelease) {
1813
+ return true;
1814
+ } else {
1815
+ dom = minimumVersion;
1816
+ }
1817
+ }
1818
+ const eqSet = /* @__PURE__ */ new Set();
1819
+ let gt, lt;
1820
+ for (const c of sub) {
1821
+ if (c.operator === ">" || c.operator === ">=") {
1822
+ gt = higherGT(gt, c, options);
1823
+ } else if (c.operator === "<" || c.operator === "<=") {
1824
+ lt = lowerLT(lt, c, options);
1825
+ } else {
1826
+ eqSet.add(c.semver);
1827
+ }
1828
+ }
1829
+ if (eqSet.size > 1) {
1830
+ return null;
1831
+ }
1832
+ let gtltComp;
1833
+ if (gt && lt) {
1834
+ gtltComp = compare(gt.semver, lt.semver, options);
1835
+ if (gtltComp > 0) {
1836
+ return null;
1837
+ } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) {
1838
+ return null;
1839
+ }
1840
+ }
1841
+ for (const eq of eqSet) {
1842
+ if (gt && !satisfies(eq, String(gt), options)) {
1843
+ return null;
1844
+ }
1845
+ if (lt && !satisfies(eq, String(lt), options)) {
1846
+ return null;
1847
+ }
1848
+ for (const c of dom) {
1849
+ if (!satisfies(eq, String(c), options)) {
1850
+ return false;
1851
+ }
1852
+ }
1853
+ return true;
1854
+ }
1855
+ let higher, lower;
1856
+ let hasDomLT, hasDomGT;
1857
+ let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false;
1858
+ let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false;
1859
+ if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) {
1860
+ needDomLTPre = false;
1861
+ }
1862
+ for (const c of dom) {
1863
+ hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">=";
1864
+ hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<=";
1865
+ if (gt) {
1866
+ if (needDomGTPre) {
1867
+ if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) {
1868
+ needDomGTPre = false;
1869
+ }
1870
+ }
1871
+ if (c.operator === ">" || c.operator === ">=") {
1872
+ higher = higherGT(gt, c, options);
1873
+ if (higher === c && higher !== gt) {
1874
+ return false;
1875
+ }
1876
+ } else if (gt.operator === ">=" && !c.test(gt.semver)) {
1877
+ return false;
1878
+ }
1879
+ }
1880
+ if (lt) {
1881
+ if (needDomLTPre) {
1882
+ if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) {
1883
+ needDomLTPre = false;
1884
+ }
1885
+ }
1886
+ if (c.operator === "<" || c.operator === "<=") {
1887
+ lower = lowerLT(lt, c, options);
1888
+ if (lower === c && lower !== lt) {
1889
+ return false;
1890
+ }
1891
+ } else if (lt.operator === "<=" && !c.test(lt.semver)) {
1892
+ return false;
1893
+ }
1894
+ }
1895
+ if (!c.operator && (lt || gt) && gtltComp !== 0) {
1896
+ return false;
1897
+ }
1898
+ }
1899
+ if (gt && hasDomLT && !lt && gtltComp !== 0) {
1900
+ return false;
1901
+ }
1902
+ if (lt && hasDomGT && !gt && gtltComp !== 0) {
1903
+ return false;
1904
+ }
1905
+ if (needDomGTPre || needDomLTPre) {
1906
+ return false;
1907
+ }
1908
+ return true;
1909
+ };
1910
+ var higherGT = (a, b, options) => {
1911
+ if (!a) {
1912
+ return b;
1913
+ }
1914
+ const comp = compare(a.semver, b.semver, options);
1915
+ return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a;
1916
+ };
1917
+ var lowerLT = (a, b, options) => {
1918
+ if (!a) {
1919
+ return b;
1920
+ }
1921
+ const comp = compare(a.semver, b.semver, options);
1922
+ return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a;
1923
+ };
1924
+ module.exports = subset;
1925
+ }
1926
+ });
1927
+
1928
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/index.js
1929
+ var require_semver2 = __commonJS({
1930
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/index.js"(exports, module) {
1931
+ "use strict";
1932
+ var internalRe = require_re();
1933
+ var constants = require_constants();
1934
+ var SemVer = require_semver();
1935
+ var identifiers = require_identifiers();
1936
+ var parse = require_parse();
1937
+ var valid2 = require_valid();
1938
+ var clean = require_clean();
1939
+ var inc = require_inc();
1940
+ var diff = require_diff();
1941
+ var major = require_major();
1942
+ var minor = require_minor();
1943
+ var patch = require_patch();
1944
+ var prerelease = require_prerelease();
1945
+ var compare = require_compare();
1946
+ var rcompare = require_rcompare();
1947
+ var compareLoose = require_compare_loose();
1948
+ var compareBuild = require_compare_build();
1949
+ var sort = require_sort();
1950
+ var rsort = require_rsort();
1951
+ var gt = require_gt();
1952
+ var lt = require_lt();
1953
+ var eq = require_eq();
1954
+ var neq = require_neq();
1955
+ var gte2 = require_gte();
1956
+ var lte = require_lte();
1957
+ var cmp = require_cmp();
1958
+ var coerce2 = require_coerce();
1959
+ var truncate = require_truncate();
1960
+ var Comparator = require_comparator();
1961
+ var Range = require_range();
1962
+ var satisfies = require_satisfies();
1963
+ var toComparators = require_to_comparators();
1964
+ var maxSatisfying = require_max_satisfying();
1965
+ var minSatisfying = require_min_satisfying();
1966
+ var minVersion = require_min_version();
1967
+ var validRange = require_valid2();
1968
+ var outside = require_outside();
1969
+ var gtr = require_gtr();
1970
+ var ltr = require_ltr();
1971
+ var intersects = require_intersects();
1972
+ var simplifyRange = require_simplify();
1973
+ var subset = require_subset();
1974
+ module.exports = {
1975
+ parse,
1976
+ valid: valid2,
1977
+ clean,
1978
+ inc,
1979
+ diff,
1980
+ major,
1981
+ minor,
1982
+ patch,
1983
+ prerelease,
1984
+ compare,
1985
+ rcompare,
1986
+ compareLoose,
1987
+ compareBuild,
1988
+ sort,
1989
+ rsort,
1990
+ gt,
1991
+ lt,
1992
+ eq,
1993
+ neq,
1994
+ gte: gte2,
1995
+ lte,
1996
+ cmp,
1997
+ coerce: coerce2,
1998
+ truncate,
1999
+ Comparator,
2000
+ Range,
2001
+ satisfies,
2002
+ toComparators,
2003
+ maxSatisfying,
2004
+ minSatisfying,
2005
+ minVersion,
2006
+ validRange,
2007
+ outside,
2008
+ gtr,
2009
+ ltr,
2010
+ intersects,
2011
+ simplifyRange,
2012
+ subset,
2013
+ SemVer,
2014
+ re: internalRe.re,
2015
+ src: internalRe.src,
2016
+ tokens: internalRe.t,
2017
+ SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
2018
+ RELEASE_TYPES: constants.RELEASE_TYPES,
2019
+ compareIdentifiers: identifiers.compareIdentifiers,
2020
+ rcompareIdentifiers: identifiers.rcompareIdentifiers
2021
+ };
2022
+ }
2023
+ });
2024
+
2025
+ // ../protocol/src/coordinator.ts
2026
+ import { z } from "zod";
2027
+ var coordinatorRuntimeSchema = z.discriminatedUnion("harness", [
2028
+ z.object({ harness: z.literal("ai_sdk") }).strict(),
2029
+ z.object({ harness: z.enum(["claude_code", "codex"]), deviceId: z.uuid(), model: z.string().trim().min(1).max(120).optional() }).strict()
2030
+ ]);
2031
+ var coordinatorToolSpecSchema = z.object({
2032
+ name: z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,63}$/),
2033
+ description: z.string().max(2e4),
2034
+ inputSchema: z.record(z.string(), z.unknown())
2035
+ });
2036
+ var nativeCoordinatorJobSchema = z.object({
2037
+ id: z.uuid(),
2038
+ harness: z.enum(["claude_code", "codex"]),
2039
+ model: z.string().optional(),
2040
+ instructions: z.string().min(1).max(2e5),
2041
+ context: z.string().min(1).max(5e5),
2042
+ tools: z.array(coordinatorToolSpecSchema).max(100),
2043
+ expiresAt: z.iso.datetime()
2044
+ });
2045
+ var nativeCoordinatorClaimSchema = z.object({ job: nativeCoordinatorJobSchema.nullable() });
2046
+ var nativeCoordinatorCommandSchema = z.discriminatedUnion("type", [
2047
+ z.object({ type: z.literal("tool"), callId: z.string().min(1).max(200), name: z.string().min(1).max(64), input: z.record(z.string(), z.unknown()) }).strict(),
2048
+ z.object({ type: z.literal("complete"), text: z.string().min(1).max(2e5).refine((value) => value.trim().length > 0) }).strict(),
2049
+ z.object({ type: z.literal("failed") }).strict()
2050
+ ]);
2051
+ var nativeCoordinatorToolResultSchema = z.discriminatedUnion("status", [
2052
+ z.object({ status: z.literal("pending") }),
2053
+ z.object({ status: z.literal("done"), output: z.unknown() })
2054
+ ]);
2055
+
2056
+ // src/server-link-http.ts
2057
+ import { z as z25 } from "zod";
2058
+
2059
+ // src/agents/tool-approval.ts
2060
+ import { randomUUID } from "node:crypto";
2061
+ async function abortable(work, signal) {
2062
+ if (signal.aborted) throw new Error("cancelled");
2063
+ let cancel;
2064
+ const cancelled = new Promise((_, reject) => {
2065
+ cancel = () => reject(new Error("cancelled"));
2066
+ signal.addEventListener("abort", cancel, { once: true });
2067
+ });
2068
+ try {
2069
+ return await Promise.race([work, cancelled]);
2070
+ } finally {
2071
+ signal.removeEventListener("abort", cancel);
2072
+ }
2073
+ }
2074
+ var ToolApprovalGate = class {
2075
+ constructor(runId, host) {
2076
+ this.runId = runId;
2077
+ this.host = host;
2078
+ }
2079
+ runId;
2080
+ host;
2081
+ epoch = randomUUID();
2082
+ seen = /* @__PURE__ */ new Set();
2083
+ networkApprovals = /* @__PURE__ */ new Map();
2084
+ stop = new AbortController();
2085
+ revoke() {
2086
+ this.stop.abort();
2087
+ }
2088
+ get revoked() {
2089
+ return this.stop.signal.aborted;
2090
+ }
2091
+ onRevoke(callback) {
2092
+ if (this.revoked) {
2093
+ callback();
2094
+ return () => {
2095
+ };
2096
+ }
2097
+ this.stop.signal.addEventListener("abort", callback, { once: true });
2098
+ return () => this.stop.signal.removeEventListener("abort", callback);
2099
+ }
2100
+ async checkLive() {
2101
+ if (this.revoked) return false;
2102
+ try {
2103
+ return await abortable(Promise.resolve(this.host.isLive(this.runId)), this.stop.signal) && !this.revoked;
2104
+ } catch {
2105
+ return false;
2106
+ }
2107
+ }
2108
+ /** A ceiling limits destinations; it is not itself user consent. Cloud allow
2109
+ * needs no prompt. Explicit ask obtains one exact-destination grant and shares
2110
+ * it across this run's sockets, while every connection rechecks live policy. */
2111
+ async preapprovedNetwork(request, signal) {
2112
+ if (request.runId !== this.runId || request.method !== "sandbox/network" || this.revoked || signal?.aborted) return false;
2113
+ const destination = request.input;
2114
+ if (!destination || typeof destination.host !== "string" || !Number.isInteger(destination.port) || Number(destination.port) < 1 || Number(destination.port) > 65535) return false;
2115
+ const key2 = JSON.stringify([request.harness, destination.host, destination.port]);
2116
+ const lifetime = signal ? AbortSignal.any([signal, this.stop.signal]) : this.stop.signal;
2117
+ try {
2118
+ if (!await abortable(Promise.resolve(this.host.isLive(this.runId)), lifetime)) return false;
2119
+ const decision = await abortable(Promise.resolve(this.host.permission(request)), lifetime);
2120
+ if (decision !== "allow" && decision !== "ask") {
2121
+ this.networkApprovals.delete(key2);
2122
+ return false;
2123
+ }
2124
+ if (decision === "ask") {
2125
+ let granted = this.networkApprovals.get(key2);
2126
+ if (!granted) {
2127
+ if (this.networkApprovals.size >= 1024 || lifetime.aborted) return false;
2128
+ granted = this.request({ ...request, requestId: `network:${randomUUID()}` }, lifetime);
2129
+ this.networkApprovals.set(key2, granted);
2130
+ }
2131
+ if (await abortable(granted, lifetime) !== "allow" || this.networkApprovals.get(key2) !== granted) return false;
2132
+ }
2133
+ return await abortable(Promise.resolve(this.host.isLive(this.runId)), lifetime) && !lifetime.aborted && !this.revoked;
2134
+ } catch {
2135
+ return false;
2136
+ }
2137
+ }
2138
+ async request(request, signal) {
2139
+ if (request.runId !== this.runId || !request.requestId || request.requestId.length > 219 || this.seen.has(request.requestId) || this.seen.size >= 1024 || this.stop.signal.aborted || signal?.aborted) return "deny";
2140
+ let snapshot;
2141
+ try {
2142
+ const serialized = JSON.stringify(request);
2143
+ if (serialized.length > 2e4) return "deny";
2144
+ snapshot = JSON.parse(serialized);
2145
+ snapshot.requestId = `${this.epoch}/${snapshot.requestId}`;
2146
+ } catch {
2147
+ return "deny";
2148
+ }
2149
+ this.seen.add(request.requestId);
2150
+ const controller = new AbortController();
2151
+ const abort = () => controller.abort();
2152
+ this.stop.signal.addEventListener("abort", abort, { once: true });
2153
+ signal?.addEventListener("abort", abort, { once: true });
2154
+ try {
2155
+ if (this.stop.signal.aborted || signal?.aborted || !await abortable(Promise.resolve(this.host.isLive(this.runId)), controller.signal)) return "deny";
2156
+ const permission = await abortable(Promise.resolve(this.host.permission(snapshot)), controller.signal);
2157
+ if (!await abortable(Promise.resolve(this.host.isLive(this.runId)), controller.signal) || controller.signal.aborted) return "deny";
2158
+ if (permission === "deny") return "deny";
2159
+ if (permission === "allow") return "allow";
2160
+ if (permission !== "ask") return "deny";
2161
+ const decision = await abortable(this.host.ask(snapshot, controller.signal), controller.signal);
2162
+ if (!await abortable(Promise.resolve(this.host.isLive(this.runId)), controller.signal) || controller.signal.aborted) return "deny";
2163
+ return decision === "allow" ? "allow" : "deny";
2164
+ } catch {
2165
+ return "deny";
2166
+ } finally {
2167
+ this.stop.signal.removeEventListener("abort", abort);
2168
+ signal?.removeEventListener("abort", abort);
2169
+ }
2170
+ }
2171
+ };
2172
+
2173
+ // ../protocol/src/agent-policy.ts
2174
+ import { z as z2 } from "zod";
2175
+ var PERMISSION_DECISIONS = ["allow", "ask", "deny"];
2176
+ var CONFIGURABLE_PERMISSIONS = {
2177
+ install_dependency: ["allow", "ask", "deny"],
2178
+ // Everything outside the worktree is read-only in the sandbox (ADR 0009,
2179
+ // Stage 1 isolation), so writing there cannot be allowed wholesale.
2180
+ write_outside_repo: ["ask", "deny"],
2181
+ git_push: ["allow", "ask", "deny"],
2182
+ network: ["allow", "ask", "deny"],
2183
+ computer_use: ["allow", "ask", "deny"]
2184
+ };
2185
+ var CONFIGURABLE_ACTIONS = Object.keys(
2186
+ CONFIGURABLE_PERMISSIONS
2187
+ );
2188
+ var FIXED_PERMISSIONS = {
2189
+ read_in_worktree: "allow",
2190
+ write_in_worktree: "allow",
2191
+ run_project_script: "allow",
2192
+ // Allowed once the user approved the repo's recipe; asked before that.
2193
+ run_setup_recipe: "allow"
2194
+ };
2195
+ var PERMISSION_DEFAULTS = {
2196
+ ...FIXED_PERMISSIONS,
2197
+ install_dependency: "allow",
2198
+ write_outside_repo: "ask",
2199
+ git_push: "ask",
2200
+ network: "ask",
2201
+ computer_use: "ask"
2202
+ };
2203
+ var NETWORK_DOMAIN_RE = /^(\*\.)?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*(:[0-9]{1,5})?$/;
2204
+ var MAX_NETWORK_DOMAINS = 200;
2205
+ var MAX_GUIDANCE_LENGTH = 1e4;
2206
+ var MAX_MODEL_NAME_LENGTH = 120;
2207
+ var networkDomainSchema = z2.string().trim().toLowerCase().min(1).max(253).regex(NETWORK_DOMAIN_RE);
2208
+ function normalizeDomains(domains) {
2209
+ return [...new Set(domains.map((d) => d.trim().toLowerCase()))].filter(
2210
+ Boolean
2211
+ );
2212
+ }
2213
+ var networkAllowSchema = z2.array(networkDomainSchema).max(MAX_NETWORK_DOMAINS).transform(normalizeDomains);
2214
+ var storedPermissionsSchema = z2.strictObject({
2215
+ install_dependency: z2.enum(CONFIGURABLE_PERMISSIONS.install_dependency),
2216
+ write_outside_repo: z2.enum(CONFIGURABLE_PERMISSIONS.write_outside_repo),
2217
+ git_push: z2.enum(CONFIGURABLE_PERMISSIONS.git_push),
2218
+ network: z2.enum(CONFIGURABLE_PERMISSIONS.network),
2219
+ computer_use: z2.enum(CONFIGURABLE_PERMISSIONS.computer_use)
2220
+ }).partial();
2221
+ var guidanceSchema = z2.string().max(MAX_GUIDANCE_LENGTH);
2222
+ var runPolicySchema = z2.object({
2223
+ permissions: z2.object({
2224
+ install_dependency: z2.enum(PERMISSION_DECISIONS),
2225
+ write_outside_repo: z2.enum(PERMISSION_DECISIONS),
2226
+ git_push: z2.enum(PERMISSION_DECISIONS),
2227
+ network: z2.enum(PERMISSION_DECISIONS),
2228
+ // Older servers omit this field; the daemon treats that as ask, never allow.
2229
+ computer_use: z2.enum(PERMISSION_DECISIONS).optional()
2230
+ }),
2231
+ /** The workspace layer of the domain allow-list (ADR 0009). */
2232
+ networkAllow: z2.array(z2.string().min(1).max(253)).max(MAX_NETWORK_DOMAINS),
2233
+ /** Host-derived worker/workspace ceiling; even network=allow cannot widen it. */
2234
+ networkCeiling: z2.array(networkDomainSchema).max(MAX_NETWORK_DOMAINS).optional(),
2235
+ /**
2236
+ * The run only reads: the worktree is not writable and nothing is pushed
2237
+ * (ADR 0046). Absent from an older server means a normal, writable run.
2238
+ */
2239
+ readOnly: z2.boolean().optional()
2240
+ });
2241
+ var MODEL_HARNESSES = ["claude_code", "codex", "cursor"];
2242
+ var modelHarnessSchema = z2.enum(MODEL_HARNESSES);
2243
+ var modelNameSchema = z2.string().trim().min(1).max(MAX_MODEL_NAME_LENGTH);
2244
+ var modelByHarnessSchema = z2.strictObject({
2245
+ claude_code: modelNameSchema,
2246
+ codex: modelNameSchema,
2247
+ cursor: modelNameSchema
2248
+ }).partial();
2249
+ var APPROVAL_MODES = ["ask", "read_only"];
2250
+ var approvalModeSchema = z2.enum(APPROVAL_MODES);
2251
+
2252
+ // src/permissions.ts
2253
+ import { lstatSync, readlinkSync, realpathSync } from "node:fs";
2254
+ import {
2255
+ basename,
2256
+ dirname,
2257
+ isAbsolute,
2258
+ join,
2259
+ relative,
2260
+ resolve
2261
+ } from "node:path";
2262
+ function rawCliShellAvailable(policy) {
2263
+ return !policy.readOnly && policy.permissions.install_dependency === "allow";
2264
+ }
2265
+ function realTarget(path) {
2266
+ const missing = [];
2267
+ let current = path;
2268
+ for (let hops = 0; ; ) {
2269
+ try {
2270
+ return join(realpathSync(current), ...[...missing].reverse());
2271
+ } catch {
2272
+ if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink()) {
2273
+ if (++hops > 40) return path;
2274
+ current = resolve(dirname(current), readlinkSync(current));
2275
+ continue;
2276
+ }
2277
+ const parent = dirname(current);
2278
+ if (parent === current) return path;
2279
+ missing.push(basename(current));
2280
+ current = parent;
2281
+ }
2282
+ }
2283
+ }
2284
+ function inside(parent, child) {
2285
+ const rel = relative(parent, child);
2286
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
2287
+ }
2288
+ function classifyWrite(worktree, target) {
2289
+ const root = resolve(worktree);
2290
+ const lexical = resolve(root, target);
2291
+ const ok2 = inside(root, lexical) && inside(realTarget(root), realTarget(lexical));
2292
+ return ok2 ? "write_in_worktree" : "write_outside_repo";
2293
+ }
2294
+
2295
+ // src/agents/tool-approval-policy.ts
2296
+ function toolApprovalDecision(request, policy, worktree) {
2297
+ if (request.method === "sandbox/network" && policy) {
2298
+ const value = request.input;
2299
+ if (!value || typeof value.host !== "string" || /[*/:]/.test(value.host) || !networkDomainSchema.safeParse(value.host).success || !Number.isInteger(value.port) || Number(value.port) < 1 || Number(value.port) > 65535) return "deny";
2300
+ return policy.permissions.network;
2301
+ }
2302
+ if (request.method.startsWith("cli/") && policy && worktree) {
2303
+ const tool = request.method.slice(4);
2304
+ if (["get_desktop_state", "click", "type_text", "press_key", "scroll", "capture_screenshot", "start_screen_recording", "stop_screen_recording"].some((name) => tool === `mcp__mikka_computer__${name}`)) {
2305
+ return policy.readOnly || !policy.permissions.computer_use || policy.permissions.computer_use === "deny" ? "deny" : "allow";
2306
+ }
2307
+ if (["submit", "ask_human", "report_blocked", "submit_capture"].some((name) => tool === `mcp__mikka__${name}`)) return "allow";
2308
+ if (tool === "Bash" || tool === "PowerShell") return rawCliShellAvailable(policy) ? "allow" : "unavailable";
2309
+ const input = request.input;
2310
+ if (["Write", "Edit", "MultiEdit", "NotebookEdit"].includes(tool)) {
2311
+ if (policy.readOnly) return "deny";
2312
+ const path = tool === "NotebookEdit" ? input?.notebook_path : input?.file_path;
2313
+ if (typeof path !== "string") return "unavailable";
2314
+ return classifyWrite(worktree, path) === "write_in_worktree" ? "allow" : "unavailable";
2315
+ }
2316
+ }
2317
+ return "unavailable";
2318
+ }
2319
+
2320
+ // ../protocol/src/skill.ts
2321
+ import { z as z4 } from "zod";
2322
+
2323
+ // ../protocol/src/skill-artifact.ts
2324
+ import { z as z3 } from "zod";
2325
+ var SKILL_ARTIFACT_HEADER = "x-mikka-skill-artifacts";
2326
+ var skillArtifactRefSchema = z3.object({
2327
+ schemaVersion: z3.literal(1),
2328
+ registryId: z3.literal("mikka-builtin"),
2329
+ skillId: z3.uuid(),
2330
+ versionId: z3.uuid(),
2331
+ format: z3.literal("single-skill-md-v1"),
2332
+ sha256: z3.string().regex(/^[a-f0-9]{64}$/)
2333
+ }).strict();
2334
+ var skillAssignmentReceiptSchema = z3.object({
2335
+ id: z3.uuid(),
2336
+ runId: z3.uuid(),
2337
+ issueId: z3.uuid(),
2338
+ agentId: z3.uuid(),
2339
+ repoId: z3.uuid(),
2340
+ deviceId: z3.uuid(),
2341
+ leaseExpiresAt: z3.iso.datetime(),
2342
+ assignedAt: z3.iso.datetime(),
2343
+ artifact: skillArtifactRefSchema
2344
+ }).strict();
2345
+ var skillReceiptRevalidationSchema = z3.object({
2346
+ skillReceipt: skillAssignmentReceiptSchema,
2347
+ leaseExpiresAt: z3.iso.datetime()
2348
+ }).strict();
2349
+
2350
+ // ../protocol/src/skill.ts
2351
+ var MAX_SKILLS_PER_RUN = 20;
2352
+ var MAX_SKILL_NAME_LENGTH = 80;
2353
+ var MAX_SKILL_DESCRIPTION_LENGTH = 500;
2354
+ var MAX_SKILL_INSTRUCTIONS_LENGTH = 2e4;
2355
+ var MAX_SKILL_FILES = 20;
2356
+ var MAX_SKILL_FILE_PATH_LENGTH = 200;
2357
+ var MAX_SKILL_FILE_CONTENT_LENGTH = 1e5;
2358
+ var skillFilePathSchema = z4.string().min(1).max(MAX_SKILL_FILE_PATH_LENGTH).refine(
2359
+ (path) => !path.startsWith("/") && !path.includes("\\") && !path.split("/").some((segment) => segment === ".." || segment === ""),
2360
+ { message: "A skill file path must be relative and stay inside the skill." }
2361
+ );
2362
+ var skillFileSchema = z4.object({
2363
+ path: skillFilePathSchema,
2364
+ content: z4.string().max(MAX_SKILL_FILE_CONTENT_LENGTH)
2365
+ });
2366
+ var skillFilesSchema = z4.array(skillFileSchema).max(MAX_SKILL_FILES);
2367
+ var skillNameSchema = z4.string().trim().min(1).max(MAX_SKILL_NAME_LENGTH);
2368
+ var skillDescriptionSchema = z4.string().trim().max(MAX_SKILL_DESCRIPTION_LENGTH);
2369
+ var skillInstructionsSchema = z4.string().trim().min(1).max(MAX_SKILL_INSTRUCTIONS_LENGTH);
2370
+ var runSkillSchema = z4.object({
2371
+ id: z4.uuid(),
2372
+ name: skillNameSchema,
2373
+ description: z4.string().nullable(),
2374
+ instructions: skillInstructionsSchema,
2375
+ files: skillFilesSchema
2376
+ });
2377
+ var runSkillRefSchema = z4.object({
2378
+ id: z4.uuid(),
2379
+ name: skillNameSchema
2380
+ });
2381
+
2382
+ // ../protocol/src/subscription.ts
2383
+ import { z as z6 } from "zod";
2384
+
2385
+ // ../protocol/src/quota.ts
2386
+ import { z as z5 } from "zod";
2387
+ var QUOTA_VENDORS = ["claude_code", "codex", "cursor"];
2388
+ var quotaVendorSchema = z5.enum(QUOTA_VENDORS);
2389
+ var QUOTA_SOURCES = ["local_credentials", "official"];
2390
+ var quotaSourceSchema = z5.enum(QUOTA_SOURCES);
2391
+ var QUOTA_WINDOW_KINDS = [
2392
+ "five_hour",
2393
+ "weekly",
2394
+ "monthly",
2395
+ "daily",
2396
+ "hourly",
2397
+ "other"
2398
+ ];
2399
+ var quotaWindowKindSchema = z5.enum(QUOTA_WINDOW_KINDS);
2400
+ var QUOTA_METERS = [
2401
+ "auto",
2402
+ "api",
2403
+ "on_demand",
2404
+ "team_pool",
2405
+ "team_on_demand"
2406
+ ];
2407
+ var quotaMeterSchema = z5.enum(QUOTA_METERS);
2408
+ var quotaWindowSchema = z5.object({
2409
+ kind: quotaWindowKindSchema,
2410
+ /** 0..1 share of the window already used. */
2411
+ used: z5.number().min(0).max(1),
2412
+ resetsAt: z5.string().nullable(),
2413
+ /** Model display name for a per-model window, e.g. "Opus". */
2414
+ model: z5.string().min(1).max(40).optional(),
2415
+ meter: quotaMeterSchema.optional()
2416
+ });
2417
+ var quotaSnapshotSchema = z5.object({
2418
+ vendor: quotaVendorSchema,
2419
+ source: quotaSourceSchema,
2420
+ status: z5.enum(["ok", "unknown"]),
2421
+ plan: z5.string().max(40).nullable(),
2422
+ windows: z5.array(quotaWindowSchema).max(12),
2423
+ /** When this vendor was last read (ISO-8601). */
2424
+ observedAt: z5.string()
2425
+ });
2426
+ var quotaSnapshotReportSchema = z5.object({
2427
+ /** When the whole read finished. Null before the first read. */
2428
+ observedAt: z5.string().nullable(),
2429
+ quotas: z5.array(quotaSnapshotSchema).max(6)
2430
+ });
2431
+
2432
+ // ../protocol/src/subscription.ts
2433
+ var id = z6.string().min(1).max(128);
2434
+ var subscriptionRouteSchema = z6.enum([
2435
+ "codex_cli",
2436
+ "claude_code_cli",
2437
+ "codex_cpa",
2438
+ "claude_cpa",
2439
+ "openai_siwc"
2440
+ ]);
2441
+ var subscriptionConnectionSchema = z6.object({
2442
+ id,
2443
+ ownerId: id,
2444
+ workspaceId: id,
2445
+ provider: z6.enum(["openai", "anthropic"]),
2446
+ state: z6.enum([
2447
+ "pending",
2448
+ "connected",
2449
+ "reconnect_required",
2450
+ "disconnected"
2451
+ ]),
2452
+ // Increment on reconnect/disconnect. Old bindings cannot become valid again.
2453
+ revision: z6.number().int().positive(),
2454
+ quota: quotaSnapshotSchema
2455
+ }).strict();
2456
+ var subscriptionBindingSchema = z6.object({
2457
+ id,
2458
+ ownerId: id,
2459
+ workspaceId: id,
2460
+ // An agent or assistant session selected explicitly by the owner.
2461
+ consumerId: id,
2462
+ connectionId: id,
2463
+ connectionRevision: z6.number().int().positive(),
2464
+ route: subscriptionRouteSchema
2465
+ }).strict();
2466
+ var nativeBrokerContextSchema = z6.object({
2467
+ route: z6.enum(["codex_cli", "claude_code_cli"]),
2468
+ modelId: z6.string().min(1).max(128),
2469
+ revision: z6.number().int().positive(),
2470
+ accountId: z6.string().min(1).max(512),
2471
+ plan: z6.string().max(40).optional(),
2472
+ expiresAt: z6.iso.datetime()
2473
+ }).strict();
2474
+
2475
+ // ../protocol/src/computer.ts
2476
+ import { z as z7 } from "zod";
2477
+ var machineStateSchema = z7.enum(["sleeping", "waking", "running", "error"]);
2478
+ var controlStateSchema = z7.enum(["agent", "user", "idle"]);
2479
+ var computerToolSchema = z7.enum(["click", "type", "key", "scroll", "screenshot"]);
2480
+ var screenRectSchema = z7.object({ x: z7.number(), y: z7.number(), w: z7.number().nonnegative(), h: z7.number().nonnegative() });
2481
+ var computerActionSchema = z7.object({ tool: computerToolSchema, x: z7.number().optional(), y: z7.number().optional(), text: z7.string().optional(), rect: screenRectSchema.optional() });
2482
+ var lastActionSchema = computerActionSchema.omit({ text: true }).extend({ at: z7.iso.datetime() });
2483
+ var approvalViewSchema = z7.object({
2484
+ id: z7.string(),
2485
+ digest: z7.string(),
2486
+ runId: z7.string(),
2487
+ botId: z7.string(),
2488
+ action: computerActionSchema,
2489
+ summary: z7.string(),
2490
+ expiresAt: z7.iso.datetime()
2491
+ });
2492
+ var computerStateSchema = z7.object({
2493
+ machine: machineStateSchema,
2494
+ control: controlStateSchema,
2495
+ controlledBy: z7.object({ userId: z7.string() }).optional(),
2496
+ lastAction: lastActionSchema.optional(),
2497
+ pendingApproval: approvalViewSchema.optional()
2498
+ });
2499
+ var viewerModeSchema = z7.enum(["view", "control"]);
2500
+ var viewerRequestSchema = z7.object({ mode: viewerModeSchema }).strict();
2501
+ var viewerGrantSchema = z7.object({ url: z7.url({ protocol: /^wss$/ }), expiresAt: z7.iso.datetime() });
2502
+ var createBotSchema = z7.object({ name: z7.string().trim().min(1).max(120) }).strict();
2503
+ var botViewSchema = z7.object({ id: z7.uuid(), name: z7.string().min(1).max(120) });
2504
+ var approvalDecisionSchema = z7.object({ digest: z7.string(), decision: z7.enum(["approve", "deny"]), scope: z7.enum(["once", "run"]) }).strict();
2505
+ var computerTaskStateSchema = z7.enum(["working", "approval", "done", "failed"]);
2506
+ var computerTaskSchema = z7.object({ botId: z7.string(), runId: z7.string(), task: z7.string(), state: computerTaskStateSchema, approvalId: z7.string().optional() });
2507
+ var computerEventSchema = z7.discriminatedUnion("type", [
2508
+ z7.object({ type: z7.literal("computer.machine"), state: machineStateSchema }),
2509
+ z7.object({ type: z7.literal("computer.control"), botId: z7.string(), control: controlStateSchema, controlledBy: z7.object({ userId: z7.string() }).optional() }),
2510
+ z7.object({ type: z7.literal("computer.action"), botId: z7.string(), lastAction: lastActionSchema }),
2511
+ z7.object({ type: z7.literal("computer.approval"), botId: z7.string(), approval: approvalViewSchema.nullable() })
2512
+ ]);
2513
+ var reviewDigestSchema = z7.string().regex(/^[a-f0-9]{64}$/);
2514
+ var localComputerCall = z7.discriminatedUnion("name", [
2515
+ z7.object({ name: z7.literal("get_desktop_state"), arguments: z7.object({}).strict() }).strict(),
2516
+ z7.object({ name: z7.literal("click"), arguments: z7.object({ x: z7.number().int().min(0).max(1e5), y: z7.number().int().min(0).max(1e5) }).strict() }).strict(),
2517
+ z7.object({ name: z7.literal("type_text"), arguments: z7.object({ text: z7.string().min(1).max(8e3) }).strict() }).strict(),
2518
+ z7.object({ name: z7.literal("press_key"), arguments: z7.object({
2519
+ key: z7.string().regex(/^(?:[\x20-\x7e]|enter|return|tab|escape|space|backspace|delete|insert|home|end|pageup|pagedown|up|down|left|right|f(?:[1-9]|1[0-2]))$/),
2520
+ modifiers: z7.array(z7.enum(["ctrl", "shift", "alt", "super"])).max(4).refine((items) => new Set(items).size === items.length).optional()
2521
+ }).strict() }).strict(),
2522
+ z7.object({ name: z7.literal("scroll"), arguments: z7.object({ direction: z7.enum(["up", "down", "left", "right"]), amount: z7.number().int().min(1).max(50), x: z7.number().int().min(0).max(1e5), y: z7.number().int().min(0).max(1e5) }).strict() }).strict()
2523
+ ]);
2524
+ var localComputerRequest = z7.object({
2525
+ id: z7.uuid(),
2526
+ runId: z7.uuid(),
2527
+ target: reviewDigestSchema,
2528
+ display: z7.string().regex(/^:[1-9][0-9]{0,2}$/).optional(),
2529
+ call: localComputerCall,
2530
+ expiresAt: z7.number().int().positive(),
2531
+ digest: reviewDigestSchema
2532
+ }).strict();
2533
+ var localComputerDecision = z7.object({ id: z7.uuid(), digest: reviewDigestSchema, approve: z7.boolean() }).strict();
2534
+ var computerSyncBody = z7.object({ requests: z7.array(localComputerRequest).max(20) }).strict();
2535
+ var computerSyncResponse = z7.object({ decisions: z7.array(localComputerDecision).max(20) }).strict();
2536
+ var computerSyncPath = (deviceId) => `/v1/devices/${encodeURIComponent(deviceId)}/computer`;
2537
+
2538
+ // ../protocol/src/capture.ts
2539
+ import { z as z8 } from "zod";
2540
+ var CAPTURE_CONTENT_TYPES = [
2541
+ "image/png",
2542
+ "image/jpeg",
2543
+ "image/webp",
2544
+ "video/mp4",
2545
+ "video/webm"
2546
+ ];
2547
+ var CAPTURE_KINDS = ["image", "video"];
2548
+ var CAPTURE_SOURCES = ["cloud_computer", "local"];
2549
+ var CAPTURE_MAX_BYTES = {
2550
+ image: 1e7,
2551
+ video: 1e8
2552
+ };
2553
+ var RECORDING_MAX_SECONDS = 300;
2554
+ var CAPTURE_TITLE_MAX = 200;
2555
+ var sha256 = z8.string().regex(/^[a-f0-9]{64}$/);
2556
+ var title = z8.string().trim().min(1).max(CAPTURE_TITLE_MAX);
2557
+ var captureUploadRequest = z8.object({
2558
+ /** Stable client id, persisted before the first network attempt. */
2559
+ captureId: z8.uuid().optional(),
2560
+ title,
2561
+ contentType: z8.enum(CAPTURE_CONTENT_TYPES),
2562
+ size: z8.number().int().min(1).max(CAPTURE_MAX_BYTES.video),
2563
+ sha256
2564
+ }).strict();
2565
+ var captureUploadTarget = z8.discriminatedUnion("target", [
2566
+ z8.object({ target: z8.literal("storage"), url: z8.url({ protocol: /^https$/ }), headers: z8.record(z8.string(), z8.string()) }),
2567
+ z8.object({ target: z8.literal("server") })
2568
+ ]);
2569
+ var captureUploadResponse = z8.object({
2570
+ captureId: z8.uuid(),
2571
+ upload: captureUploadTarget
2572
+ });
2573
+ var captureView = z8.object({
2574
+ id: z8.uuid(),
2575
+ kind: z8.enum(CAPTURE_KINDS),
2576
+ contentType: z8.enum(CAPTURE_CONTENT_TYPES),
2577
+ title: z8.string(),
2578
+ size: z8.number().int().nonnegative(),
2579
+ durationMs: z8.number().int().nonnegative().nullable(),
2580
+ source: z8.enum(CAPTURE_SOURCES),
2581
+ createdAt: z8.iso.datetime()
2582
+ });
2583
+ var captureCompleteResponse = z8.object({ capture: captureView });
2584
+ var screenCaptureRequest = z8.discriminatedUnion("action", [
2585
+ z8.object({ action: z8.literal("screenshot"), title }).strict(),
2586
+ z8.object({ action: z8.literal("start_recording"), title, maxSeconds: z8.number().int().min(5).max(RECORDING_MAX_SECONDS).optional() }).strict(),
2587
+ z8.object({ action: z8.literal("stop_recording") }).strict()
2588
+ ]);
2589
+ var screenCaptureResponse = z8.discriminatedUnion("action", [
2590
+ z8.object({ action: z8.literal("screenshot"), capture: captureView }),
2591
+ z8.object({ action: z8.literal("start_recording"), recordingId: z8.uuid(), stopsAt: z8.iso.datetime() }),
2592
+ z8.object({ action: z8.literal("stop_recording"), capture: captureView })
2593
+ ]);
2594
+ var capturePaths = {
2595
+ begin: (runId) => `/v1/runs/${encodeURIComponent(runId)}/captures`,
2596
+ upload: (runId, captureId) => `/v1/runs/${encodeURIComponent(runId)}/captures/${encodeURIComponent(captureId)}`,
2597
+ complete: (runId, captureId) => `/v1/runs/${encodeURIComponent(runId)}/captures/${encodeURIComponent(captureId)}/complete`,
2598
+ screen: (runId) => `/v1/runs/${encodeURIComponent(runId)}/screen`
2599
+ };
2600
+
2601
+ // ../protocol/src/accounts.ts
2602
+ import { z as z9 } from "zod";
2603
+ var connectedAccount = z9.object({
2604
+ /** The provider, e.g. "github". Unique per person, so it names the row. */
2605
+ providerId: z9.string(),
2606
+ /**
2607
+ * The account's id at the provider. Better Auth stores the provider's own
2608
+ * user id here, which for GitHub is a number — the closest thing to a
2609
+ * display name the table holds.
2610
+ */
2611
+ accountId: z9.string(),
2612
+ /** OAuth scopes granted, space separated. Null when the provider sent none. */
2613
+ scope: z9.string().nullable(),
2614
+ /** When the account was linked, ISO 8601. */
2615
+ createdAt: z9.string()
2616
+ });
2617
+ var connectedAccountsResponse = z9.object({
2618
+ accounts: z9.array(connectedAccount)
2619
+ });
2620
+
2621
+ // ../protocol/src/auth.ts
2622
+ import { z as z10 } from "zod";
2623
+ var AUTH_PROVIDERS = ["github", "google"];
2624
+ var authProvider = z10.enum(AUTH_PROVIDERS);
2625
+ var DESKTOP_SCHEMES = ["mikka", "mikka-dev"];
2626
+ var desktopScheme = z10.enum(DESKTOP_SCHEMES);
2627
+ var AUTH_BASE_PATH = "/api/auth";
2628
+ var AUTH_ROUTES = {
2629
+ /** Better Auth jwt plugin: short-lived JWT for zero-cache and the relay. */
2630
+ token: `${AUTH_BASE_PATH}/token`,
2631
+ /** Dev-only bypass (a Better Auth endpoint, so it sets the session cookie). */
2632
+ devLogin: `${AUTH_BASE_PATH}/dev/login`,
2633
+ me: "/v1/me"
2634
+ };
2635
+ var activeSession = z10.object({
2636
+ id: z10.string(),
2637
+ /** ISO timestamps. */
2638
+ createdAt: z10.string(),
2639
+ expiresAt: z10.string(),
2640
+ ipAddress: z10.string().nullable(),
2641
+ userAgent: z10.string().nullable(),
2642
+ /** Derived from the caller's JWT (`sid`), not from the request's cookies. */
2643
+ current: z10.boolean()
2644
+ });
2645
+ var activeSessions = z10.object({ sessions: z10.array(activeSession) });
2646
+ var authorizedDevice = z10.object({
2647
+ id: z10.uuid(),
2648
+ name: z10.string(),
2649
+ hostname: z10.string().nullable(),
2650
+ platform: z10.string().nullable(),
2651
+ daemonVersion: z10.string().nullable(),
2652
+ lastSeenAt: z10.string().nullable(),
2653
+ /** The daemon session; null once the authorization is revoked. */
2654
+ sessionId: z10.string().nullable(),
2655
+ /** When the daemon signed in, and when that session expires. */
2656
+ authorizedAt: z10.string().nullable(),
2657
+ expiresAt: z10.string().nullable()
2658
+ });
2659
+ var authorizedDevices = z10.object({
2660
+ devices: z10.array(authorizedDevice)
2661
+ });
2662
+ var authorizedApplication = z10.object({
2663
+ id: z10.string(),
2664
+ name: z10.string(),
2665
+ uri: z10.string().nullable(),
2666
+ scopes: z10.array(z10.string()),
2667
+ createdAt: z10.string(),
2668
+ updatedAt: z10.string()
2669
+ });
2670
+ var authorizedApplications = z10.object({
2671
+ applications: z10.array(authorizedApplication)
2672
+ });
2673
+ var sessionUser = z10.object({
2674
+ id: z10.uuid(),
2675
+ email: z10.string(),
2676
+ name: z10.string(),
2677
+ image: z10.string().nullable()
2678
+ });
2679
+ var accessToken = z10.object({
2680
+ token: z10.string().min(1),
2681
+ /** Expiry, ms since epoch (from the JWT's `exp`). */
2682
+ expiresAt: z10.number().int()
2683
+ });
2684
+
2685
+ // ../protocol/src/bridge.ts
2686
+ import { z as z11 } from "zod";
2687
+ var LANGUAGES = ["zh-CN", "en"];
2688
+ var languagePreference = z11.enum(["system", ...LANGUAGES]);
2689
+ var themePreference = z11.enum(["system", "light", "dark"]);
2690
+ var appHref = z11.string().max(2048).regex(/^\/(?!\/)/);
2691
+ var DESKTOP_NOTIFICATION_KINDS = [
2692
+ "review",
2693
+ "awaiting",
2694
+ "failed"
2695
+ ];
2696
+ var desktopNotification = z11.object({
2697
+ /** The `notification` row id. */
2698
+ id: z11.string().min(1).max(200),
2699
+ kind: z11.enum(DESKTOP_NOTIFICATION_KINDS),
2700
+ /** `ORV-12 · 等你验收`; the issue number is always in it. */
2701
+ title: z11.string().min(1).max(300),
2702
+ /** The issue title. */
2703
+ body: z11.string().max(1e3),
2704
+ href: appHref
2705
+ });
2706
+ var desktopBadgeCount = z11.number().int().min(0).max(9999);
2707
+ var savedTab = z11.object({
2708
+ entries: z11.array(appHref).min(1).max(50),
2709
+ index: z11.number().int().min(0).max(49)
2710
+ });
2711
+ var savedTabs = z11.object({
2712
+ items: z11.array(savedTab).max(50),
2713
+ active: z11.number().int().min(0).max(49)
2714
+ });
2715
+ var firstDayOfWeekPreference = z11.enum(["monday", "sunday", "saturday"]);
2716
+ var commentSubmitKeyPreference = z11.enum(["mod+enter", "enter"]);
2717
+ var settingsSchema = z11.object({
2718
+ language: languagePreference,
2719
+ theme: themePreference,
2720
+ /** Sidebar expanded (true) or collapsed offcanvas (false); ⌘B and `[`. */
2721
+ sidebarOpen: z11.boolean(),
2722
+ /** Titlebar tabs; empty until the app has saved them once. */
2723
+ tabs: savedTabs,
2724
+ /** Send anonymous usage events (ADR 0033); off by choice in Settings. */
2725
+ telemetry: z11.boolean(),
2726
+ /** Which day a week starts on in date pickers. */
2727
+ firstDayOfWeek: firstDayOfWeekPreference,
2728
+ /** Which key press sends a comment. */
2729
+ commentSubmitKey: commentSubmitKeyPreference
2730
+ });
2731
+ var DEFAULT_SETTINGS = {
2732
+ language: "system",
2733
+ theme: "system",
2734
+ sidebarOpen: true,
2735
+ tabs: { items: [], active: 0 },
2736
+ telemetry: true,
2737
+ firstDayOfWeek: "monday",
2738
+ commentSubmitKey: "mod+enter"
2739
+ };
2740
+ var SETTINGS_KEYS = Object.keys(DEFAULT_SETTINGS);
2741
+ var authState = z11.discriminatedUnion("status", [
2742
+ z11.object({ status: z11.literal("signed_out") }),
2743
+ z11.object({ status: z11.literal("signing_in"), provider: authProvider }),
2744
+ z11.object({ status: z11.literal("signed_in"), user: sessionUser }),
2745
+ z11.object({
2746
+ status: z11.literal("update_required"),
2747
+ minVersion: z11.string()
2748
+ }),
2749
+ z11.object({ status: z11.literal("error"), code: z11.string() })
2750
+ ]);
2751
+ var localDevice = z11.object({
2752
+ /** Whether the daemon on this computer answers. */
2753
+ status: z11.enum(["online", "connecting", "offline"]),
2754
+ /** The device row this daemon registered, once it has. */
2755
+ deviceId: z11.string().nullable(),
2756
+ workspaceId: z11.string().nullable(),
2757
+ /** The daemon holds a device credential. */
2758
+ signedIn: z11.boolean(),
2759
+ /** The daemon's link to the server; null while the daemon is offline. */
2760
+ server: z11.enum(["online", "offline", "unregistered"]).nullable()
2761
+ });
2762
+ var deviceLinkRequest = z11.object({ workspaceId: z11.uuid() });
2763
+ var pickedRepo = z11.object({
2764
+ /** The repo's top level (a subfolder pick resolves to it). */
2765
+ path: z11.string().min(1).max(4e3),
2766
+ name: z11.string().max(500),
2767
+ /** `origin` (or the first remote), null when the repo has none. */
2768
+ remoteUrl: z11.string().max(2e3).nullable()
2769
+ });
2770
+ var pickRepoResult = z11.discriminatedUnion("status", [
2771
+ z11.object({ status: z11.literal("picked"), repo: pickedRepo }),
2772
+ z11.object({ status: z11.literal("cancelled") }),
2773
+ z11.object({ status: z11.literal("not_a_repo"), path: z11.string() })
2774
+ ]);
2775
+
2776
+ // ../protocol/src/cycles.ts
2777
+ import { z as z12 } from "zod";
2778
+ var WEEKDAYS = [
2779
+ "monday",
2780
+ "tuesday",
2781
+ "wednesday",
2782
+ "thursday",
2783
+ "friday",
2784
+ "saturday",
2785
+ "sunday"
2786
+ ];
2787
+ var CYCLE_DURATION_MIN_DAYS = 1;
2788
+ var CYCLE_DURATION_MAX_DAYS = 56;
2789
+ var CYCLE_UPCOMING_MAX = 8;
2790
+ var teamCycleSettingsSchema = z12.object({
2791
+ /** Off until a person turns it on: nothing is created and nothing rolls. */
2792
+ enabled: z12.boolean().default(false),
2793
+ /** Length of a cycle in days; the end date is `start + duration - 1`. */
2794
+ durationDays: z12.number().int().min(CYCLE_DURATION_MIN_DAYS).max(CYCLE_DURATION_MAX_DAYS).default(14),
2795
+ /** The weekday a team's first cycle starts on. */
2796
+ startWeekday: z12.enum(WEEKDAYS).default("monday"),
2797
+ /** Cycles kept ready ahead of the current one. 0 creates them just in time. */
2798
+ upcomingCount: z12.number().int().min(0).max(CYCLE_UPCOMING_MAX).default(1),
2799
+ /**
2800
+ * When a cycle ends, unfinished issues move to the next one. Off leaves them
2801
+ * in the finished cycle, which is what `cycle.complete` has always done.
2802
+ */
2803
+ autoRollover: z12.boolean().default(true),
2804
+ /**
2805
+ * The team's calendar. A cycle ends at the last moment of its end date
2806
+ * *here*, not in UTC, so a team in Auckland and one in Los Angeles roll over
2807
+ * at different instants.
2808
+ */
2809
+ timezone: z12.string().max(64).refine(isValidTimeZone, "Unknown timezone.").default("UTC")
2810
+ });
2811
+ function isValidTimeZone(value) {
2812
+ try {
2813
+ new Intl.DateTimeFormat("en-US", { timeZone: value });
2814
+ return true;
2815
+ } catch {
2816
+ return false;
2817
+ }
2818
+ }
2819
+
2820
+ // ../protocol/src/daemon.ts
2821
+ import { z as z16 } from "zod";
2822
+
2823
+ // ../protocol/src/harness.ts
2824
+ import { z as z13 } from "zod";
2825
+ var HARNESSES = ["claude_code", "codex", "cursor", "mock"];
2826
+ var harnessSchema = z13.enum(HARNESSES);
2827
+ var harnessInfoSchema = z13.object({
2828
+ harness: harnessSchema,
2829
+ installed: z13.boolean(),
2830
+ models: z13.array(z13.string().trim().min(1).max(128)).max(500).optional(),
2831
+ /** Deprecated (#312, 2026-10-27): could host the native Coordinator. The server keeps that runtime switched off. */
2832
+ coordinator: z13.boolean().optional(),
2833
+ /** Set only by a runner with an isolated, owner-bound subscription broker. */
2834
+ subscriptionBroker: z13.literal(true).optional(),
2835
+ /** Set only by an E2B worker with the guarded Bot computer broker. */
2836
+ computerBroker: z13.literal(true).optional(),
2837
+ /** Run-scoped CLI approvals and policy-version checks are supported. */
2838
+ toolApproval: z13.literal(true).optional(),
2839
+ /** Version string reported by the CLI, null when not installed. */
2840
+ version: z13.string().nullable()
2841
+ });
2842
+
2843
+ // ../protocol/src/run.ts
2844
+ import { z as z15 } from "zod";
2845
+
2846
+ // ../protocol/src/plan.ts
2847
+ import { z as z14 } from "zod";
2848
+ var text = (max) => z14.string().trim().min(1).max(max);
2849
+ var key = z14.string().trim().min(1).max(64);
2850
+ var planSection = z14.object({
2851
+ heading: text(200),
2852
+ items: z14.array(text(2e3)).min(1).max(50)
2853
+ });
2854
+ var planSpec = z14.object({
2855
+ title: text(500),
2856
+ summary: z14.string().trim().max(4e3).default(""),
2857
+ sections: z14.array(planSection).min(1).max(30)
2858
+ });
2859
+ var planCriterion = z14.object({
2860
+ body: text(2e3),
2861
+ /** The command that checks it; absent means a person checks it. */
2862
+ checkCommand: z14.string().trim().max(2e3).optional()
2863
+ });
2864
+ var PLAN_PRIORITIES = [
2865
+ "none",
2866
+ "urgent",
2867
+ "high",
2868
+ "medium",
2869
+ "low"
2870
+ ];
2871
+ var planIssue = z14.object({
2872
+ key,
2873
+ title: text(500),
2874
+ goal: z14.string().trim().max(4e3).optional(),
2875
+ /** Grouping only; order lives in `blockedBy` (`issue.parent_id`). */
2876
+ parentKey: key.optional(),
2877
+ blockedBy: z14.array(key).max(50).default([]),
2878
+ criteria: z14.array(planCriterion).min(1).max(50),
2879
+ verifyCommand: z14.string().trim().max(2e3).optional(),
2880
+ predictedFiles: z14.array(z14.string().trim().max(1e3)).max(200).default([]),
2881
+ sizeEstimate: z14.object({ files: z14.number().int().min(0), lines: z14.number().int().min(0) }).optional(),
2882
+ priority: z14.enum(PLAN_PRIORITIES).default("none")
2883
+ });
2884
+ var planSplit = z14.object({
2885
+ summary: z14.string().trim().max(4e3).default(""),
2886
+ issues: z14.array(planIssue).min(1).max(100)
2887
+ });
2888
+ var planHandoff = z14.object({
2889
+ specId: z14.uuid(),
2890
+ spec: planSpec,
2891
+ split: planSplit
2892
+ });
2893
+
2894
+ // ../protocol/src/run.ts
2895
+ var RUN_QUESTION_KINDS = [
2896
+ "context",
2897
+ "decision",
2898
+ "permission",
2899
+ "external"
2900
+ ];
2901
+ var runQuestion = z15.object({
2902
+ questionId: z15.uuid(),
2903
+ kind: z15.enum(RUN_QUESTION_KINDS).default("decision"),
2904
+ question: z15.string().trim().min(1).max(4e3),
2905
+ context: z15.string().trim().max(4e3).optional(),
2906
+ options: z15.array(z15.string().trim().min(1).max(4e3)).max(20).default([])
2907
+ }).strict();
2908
+ var RUN_STOP_REASONS = [
2909
+ "submitted",
2910
+ "turn_ended",
2911
+ "asked_human",
2912
+ "blocked",
2913
+ "cancelled",
2914
+ "error",
2915
+ "timeout",
2916
+ "device_lost"
2917
+ ];
2918
+ var runStopReason = z15.enum(RUN_STOP_REASONS);
2919
+ var shortList = z15.array(z15.string().max(1e3)).max(5e3);
2920
+ var VERIFY_STATUSES = ["passed", "failed", "not_run"];
2921
+ var verifyStatus = z15.enum(VERIFY_STATUSES);
2922
+ var runPublish = z15.object({
2923
+ /** Where the commit went: the issue's branch, or the run's own. */
2924
+ branch: z15.string().max(500),
2925
+ /** Null when nothing was committed (no changes, or the commit failed). */
2926
+ commit: z15.string().max(100).nullable(),
2927
+ pushed: z15.boolean(),
2928
+ remote: z15.string().max(200).nullable(),
2929
+ /**
2930
+ * Why nothing was pushed when that was expected: the agent changed
2931
+ * nothing, or the repo has not approved pushes. Absent with
2932
+ * `pushed: false` means the commit or the push failed (see `note`).
2933
+ */
2934
+ skipped: z15.enum(["no_changes", "not_approved"]).optional(),
2935
+ note: z15.string().max(2e3).optional()
2936
+ });
2937
+ var runBenchmarkContext = z15.object({
2938
+ sourceCommit: z15.string().regex(/^[a-f0-9]{40}$/),
2939
+ benchmarkDigest: z15.string().regex(/^[a-f0-9]{64}$/),
2940
+ caseId: z15.string().min(1).max(200),
2941
+ fixtureDigest: z15.string().regex(/^[a-f0-9]{64}$/),
2942
+ policyDigest: z15.string().regex(/^[a-f0-9]{64}$/)
2943
+ }).strict();
2944
+ var runExecution = runBenchmarkContext.extend({
2945
+ harness: z15.enum(["codex", "claude_code", "cursor"]),
2946
+ requestedModel: z15.string().min(1).max(500).nullable(),
2947
+ observedModel: z15.string().min(1).max(500).nullable(),
2948
+ verifyCommand: z15.string().min(1).max(2e3)
2949
+ }).strict();
2950
+ var runRuntime = runExecution.pick({
2951
+ harness: true,
2952
+ requestedModel: true,
2953
+ observedModel: true,
2954
+ policyDigest: true,
2955
+ sourceCommit: true
2956
+ }).strict();
2957
+ var runSkillMount = z15.object({
2958
+ receiptId: z15.uuid(),
2959
+ versionId: z15.uuid(),
2960
+ sha256: z15.string().regex(/^[a-f0-9]{64}$/),
2961
+ sessionId: z15.string().min(1).max(500),
2962
+ mountedAt: z15.iso.datetime()
2963
+ }).strict();
2964
+ var runReport = z15.object({
2965
+ /** Worktree base journaled before the adapter started; never agent-supplied. */
2966
+ sourceCommit: z15.string().regex(/^[a-f0-9]{40}$/).optional(),
2967
+ skillMount: runSkillMount.optional(),
2968
+ execution: runExecution.optional(),
2969
+ runtime: runRuntime.optional(),
2970
+ /** What was done, in a few sentences. Empty when the run crashed early. */
2971
+ summary: z15.string().max(1e4),
2972
+ /** Paths relative to the worktree root (from `git status`). */
2973
+ filesChanged: shortList,
2974
+ /** The daemon's run of the issue's verify command after a submit. */
2975
+ verify: z15.object({
2976
+ status: verifyStatus,
2977
+ command: z15.string().max(2e3).optional(),
2978
+ /** Actual process outcome from the daemon, never the agent. */
2979
+ exitCode: z15.number().int().nullable().optional(),
2980
+ signal: z15.string().max(100).nullable().optional(),
2981
+ timedOut: z15.boolean().optional(),
2982
+ /** Tail of the command output. */
2983
+ output: z15.string().max(1e4).optional()
2984
+ }),
2985
+ openQuestions: z15.array(z15.string().max(2e3)).max(50),
2986
+ /** What should happen next, from the agent's point of view. */
2987
+ question: runQuestion.optional(),
2988
+ nextStep: z15.string().max(2e3).nullable(),
2989
+ /** For `blocked`: the external condition, e.g. `quota_exhausted`. */
2990
+ blockedOn: z15.string().max(500).optional(),
2991
+ /** Daemon-owned receipt for an exact, unchanged read-only candidate. */
2992
+ check: z15.object({
2993
+ sha: z15.string().regex(/^[a-f0-9]{40}$/),
2994
+ readOnly: z15.literal(true)
2995
+ }).optional(),
2996
+ /** Preview branch created or used by the producing run; descriptive metadata only. */
2997
+ previewDatabaseBranch: z15.string().trim().min(1).max(500).optional(),
2998
+ /** Acceptance criteria the agent checked, with evidence. */
2999
+ criteria: z15.array(
3000
+ z15.object({
3001
+ criterionId: z15.uuid().optional(),
3002
+ text: z15.string().max(2e3).optional(),
3003
+ passed: z15.boolean(),
3004
+ evidence: z15.string().max(1e4).optional(),
3005
+ /** Agent-reported criterion check; the daemon-owned verify remains authoritative. */
3006
+ command: z15.string().trim().min(1).max(2e3).optional(),
3007
+ exitCode: z15.number().int().nullable().optional()
3008
+ })
3009
+ ).max(200).optional(),
3010
+ /**
3011
+ * A `plan` run's hand-in: the spec it wrote and the split it proposes for
3012
+ * it (ADR ORV-205). Only the daemon sets this, and only for a `plan` run.
3013
+ */
3014
+ plan: planHandoff.optional(),
3015
+ interfacesProduced: shortList.optional(),
3016
+ knownIssues: shortList.optional(),
3017
+ notesForNext: z15.string().max(1e4).optional(),
3018
+ /** Set by the daemon after a verified submit; never by the agent. */
3019
+ publish: runPublish.optional(),
3020
+ followUps: z15.array(
3021
+ z15.object({
3022
+ title: z15.string().trim().min(1).max(500),
3023
+ goal: z15.string().max(2e3).optional(),
3024
+ reason: z15.string().max(2e3).optional()
3025
+ })
3026
+ ).max(50).optional()
3027
+ });
3028
+ var runCompletePath = (runId) => `/v1/runs/${encodeURIComponent(runId)}/complete`;
3029
+ var runCompletion = z15.object({
3030
+ stopReason: runStopReason,
3031
+ report: runReport
3032
+ });
3033
+ var runCompleteRequest = z15.object({ stopReason: runStopReason, report: runReport.optional() }).refine((body) => body.stopReason !== "submitted" || body.report, {
3034
+ message: "A submitted run needs a report.",
3035
+ path: ["report"]
3036
+ });
3037
+
3038
+ // ../protocol/src/daemon.ts
3039
+ var RUN_STATES = [
3040
+ "queued",
3041
+ "preparing",
3042
+ "running",
3043
+ "waiting_input",
3044
+ "finishing",
3045
+ "succeeded",
3046
+ /** Ended without success or failure: the turn ended, a question, a blocker. */
3047
+ "stopped",
3048
+ "failed",
3049
+ "cancelled"
3050
+ ];
3051
+ var runStateSchema = z16.enum(RUN_STATES);
3052
+ var stopReasonSchema = runStopReason;
3053
+ var DAEMON_RPC_ERRORS = {
3054
+ handshakeRequired: 4001,
3055
+ protocolMismatch: 4002,
3056
+ unauthorized: 4003,
3057
+ repoNotAllowed: 4010,
3058
+ runNotFound: 4011,
3059
+ runNotPinnedHere: 4012,
3060
+ harnessNotSupported: 4013,
3061
+ invalidId: 4014,
3062
+ serverUnreachable: 4020,
3063
+ draining: 4030
3064
+ };
3065
+ var helloParams = z16.object({
3066
+ protocolVersion: z16.number().int(),
3067
+ /** Contents of the daemon's `daemon.secret` file in the flavor data dir. */
3068
+ secret: z16.string(),
3069
+ client: z16.object({ name: z16.string(), version: z16.string() })
3070
+ });
3071
+ var helloResult = z16.object({
3072
+ protocolVersion: z16.number().int(),
3073
+ daemonVersion: z16.string(),
3074
+ pid: z16.number().int()
3075
+ });
3076
+ var runSummarySchema = z16.object({
3077
+ runId: z16.string(),
3078
+ issueId: z16.string(),
3079
+ harness: harnessSchema,
3080
+ state: runStateSchema,
3081
+ worktree: z16.string().nullable(),
3082
+ sessionId: z16.string().nullable(),
3083
+ /** Chunks emitted so far (the daemon-local producer sequence). */
3084
+ chunks: z16.number().int().nonnegative(),
3085
+ error: z16.string().nullable(),
3086
+ /** Set once the run reached a terminal state. */
3087
+ stopReason: stopReasonSchema.optional(),
3088
+ /** Lease from the server; the daemon stops the run if it cannot renew it. */
3089
+ leaseExpiresAt: z16.string().optional(),
3090
+ /** Last progress seen by the watchdog (ISO time), while the run is active. */
3091
+ lastProgressAt: z16.string().optional()
3092
+ });
3093
+ var daemonStatusSchema = z16.object({
3094
+ daemonVersion: z16.string(),
3095
+ protocolVersion: z16.number().int(),
3096
+ pid: z16.number().int(),
3097
+ dataDir: z16.string(),
3098
+ /** Null until the device is registered with the server. */
3099
+ deviceId: z16.string().nullable(),
3100
+ /** The workspace the device credential was handed over for, if named. */
3101
+ workspaceId: z16.string().nullable(),
3102
+ /** Holds a device credential (it may still be refused by the server). */
3103
+ signedIn: z16.boolean(),
3104
+ server: z16.enum(["online", "offline", "unregistered"]),
3105
+ harnesses: z16.array(harnessInfoSchema),
3106
+ runs: z16.array(runSummarySchema),
3107
+ /** Bytes used by run worktrees under the daemon's data dir. */
3108
+ worktreeDiskBytes: z16.number().int().nonnegative(),
3109
+ /** Items buffered on disk, waiting for the server. */
3110
+ pendingUploads: z16.number().int().nonnegative(),
3111
+ draining: z16.boolean(),
3112
+ /** Latest subscription snapshots. Empty when quota polling is off. */
3113
+ quotas: z16.array(quotaSnapshotSchema).max(6)
3114
+ });
3115
+ var empty = z16.object({}).optional();
3116
+ var ok = z16.object({ ok: z16.literal(true) });
3117
+ var daemonRpc = {
3118
+ "daemon.hello": { params: helloParams, result: helloResult },
3119
+ "daemon.status": { params: empty, result: daemonStatusSchema },
3120
+ /** Cached subscription snapshots. Does not start a vendor request. */
3121
+ "quota.snapshot": { params: empty, result: quotaSnapshotReportSchema },
3122
+ /** Stop accepting runs, journal active ones for resume, then exit. */
3123
+ "daemon.drain": { params: empty, result: ok },
3124
+ /** Hand the daemon a device credential obtained by the signed-in desktop. */
3125
+ "device.setCredential": {
3126
+ params: z16.object({
3127
+ credential: z16.string().min(1),
3128
+ /** Needed only for users in more than one workspace. */
3129
+ workspaceId: z16.uuid().optional()
3130
+ }),
3131
+ result: ok
3132
+ },
3133
+ /** Forget the device credential (the person signed out of the app). */
3134
+ "device.clearCredential": { params: empty, result: ok },
3135
+ /** Claim a queued run pinned to this device and start it. */
3136
+ "runs.start": {
3137
+ params: z16.object({ runId: z16.string() }),
3138
+ result: runSummarySchema
3139
+ },
3140
+ "runs.list": { params: empty, result: z16.array(runSummarySchema) },
3141
+ /** Interject a user message into a running session. */
3142
+ "runs.send": {
3143
+ params: z16.object({ runId: z16.string(), text: z16.string().min(1) }),
3144
+ result: ok
3145
+ },
3146
+ "runs.cancel": {
3147
+ params: z16.object({ runId: z16.string() }),
3148
+ result: runSummarySchema
3149
+ },
3150
+ /**
3151
+ * Dev only (`mikka daemon --dev --server memory`): queue and start a mock
3152
+ * run on an allow-listed repo without a server. Refused otherwise.
3153
+ */
3154
+ "dev.mockRun": {
3155
+ params: z16.object({
3156
+ repoId: z16.string(),
3157
+ fixture: z16.string().optional(),
3158
+ baseBranch: z16.string().optional(),
3159
+ /** Run after the mock submits; defaults to `git diff --check`. */
3160
+ verifyCommand: z16.string().optional()
3161
+ }),
3162
+ result: runSummarySchema
3163
+ }
3164
+ };
3165
+
3166
+ // ../protocol/src/device.ts
3167
+ import { z as z17 } from "zod";
3168
+ var id2 = z17.string().min(1).max(64);
3169
+ var isoTime = z17.iso.datetime({ offset: true });
3170
+ var seg = encodeURIComponent;
3171
+ var DEVICE_ROUTES = {
3172
+ register: "/v1/devices/register",
3173
+ heartbeat: "/v1/devices/:deviceId/heartbeat",
3174
+ repos: "/v1/devices/:deviceId/repos",
3175
+ pendingRuns: "/v1/devices/:deviceId/runs",
3176
+ claim: "/v1/devices/:deviceId/runs/:runId/claim",
3177
+ commands: "/v1/devices/:deviceId/commands",
3178
+ commandsAck: "/v1/devices/:deviceId/commands/ack",
3179
+ runEvents: "/v1/runs/:runId/events",
3180
+ runPatch: "/v1/runs/:runId",
3181
+ runCheckpoint: "/v1/runs/:runId/checkpoint"
3182
+ };
3183
+ var devicePaths = {
3184
+ register: () => DEVICE_ROUTES.register,
3185
+ heartbeat: (deviceId) => `/v1/devices/${seg(deviceId)}/heartbeat`,
3186
+ repos: (deviceId) => `/v1/devices/${seg(deviceId)}/repos`,
3187
+ pendingRuns: (deviceId) => `/v1/devices/${seg(deviceId)}/runs?state=queued`,
3188
+ claim: (deviceId, runId) => `/v1/devices/${seg(deviceId)}/runs/${seg(runId)}/claim`,
3189
+ commands: (deviceId, waitSeconds, skipRuns = []) => `/v1/devices/${seg(deviceId)}/commands?wait=${waitSeconds}` + (skipRuns.length ? `&${COMMANDS_SKIP_PARAM}=${skipRuns.map(seg).join(",")}` : ""),
3190
+ commandsAck: (deviceId) => `/v1/devices/${seg(deviceId)}/commands/ack`,
3191
+ runEvents: (runId) => `/v1/runs/${seg(runId)}/events`,
3192
+ runPatch: (runId) => `/v1/runs/${seg(runId)}`,
3193
+ runCheckpoint: (runId) => `/v1/runs/${seg(runId)}/checkpoint`
3194
+ };
3195
+ var deviceComputerCapability = z17.object({ installed: z17.boolean(), version: z17.string().max(100).nullable() }).strict();
3196
+ var deviceRegistration = z17.object({
3197
+ deviceType: z17.enum(["laptop", "server"]).optional(),
3198
+ name: z17.string().trim().min(1).max(200),
3199
+ hostname: z17.string().max(255).nullable().optional(),
3200
+ platform: z17.string().max(50),
3201
+ arch: z17.string().max(50),
3202
+ daemonVersion: z17.string().max(50),
3203
+ protocolVersion: z17.number().int(),
3204
+ harnesses: z17.array(harnessInfoSchema).max(20),
3205
+ computerUse: deviceComputerCapability.optional(),
3206
+ /**
3207
+ * This machine's one device id, the same in every workspace (ADR ORV-284).
3208
+ * Registering with it in another workspace joins the same device there.
3209
+ * An id the server does not know yet becomes the new device's id; another
3210
+ * person's id registers a new device.
3211
+ */
3212
+ deviceId: id2.optional(),
3213
+ /** Needed only when the user belongs to more than one workspace. */
3214
+ workspaceId: z17.uuid().optional()
3215
+ });
3216
+ var deviceRegistered = z17.object({
3217
+ deviceId: id2,
3218
+ workspaceId: z17.uuid()
3219
+ });
3220
+ var heartbeatRunSchema = z17.object({
3221
+ runId: id2,
3222
+ /** Last tool call, turn boundary or file change (not raw output). */
3223
+ lastProgressAt: isoTime
3224
+ });
3225
+ var deviceManagementCommand = z17.object({ id: z17.uuid(), kind: z17.enum(["redetect", "restart", "update", "uninstall"]) });
3226
+ var deviceHeartbeatSchema = z17.object({
3227
+ completedDeviceCommands: z17.array(z17.uuid()).max(100).optional(),
3228
+ failedDeviceCommands: z17.array(z17.object({ id: z17.uuid(), error: z17.string().max(500) })).max(100).optional(),
3229
+ harnesses: z17.array(harnessInfoSchema).max(20),
3230
+ computerUse: deviceComputerCapability.optional(),
3231
+ deviceType: z17.enum(["laptop", "server"]).optional(),
3232
+ runs: z17.array(heartbeatRunSchema).max(500),
3233
+ worktreeDiskBytes: z17.number().int().nonnegative(),
3234
+ /**
3235
+ * Subscription windows read on this device. Absent when the daemon is not
3236
+ * polling. Numbers only, never a vendor credential (ADR 0027).
3237
+ */
3238
+ quotas: z17.array(quotaSnapshotSchema).max(6).optional()
3239
+ });
3240
+ var heartbeatResultSchema = z17.object({
3241
+ deviceCommands: z17.array(deviceManagementCommand).max(1).optional(),
3242
+ /** Renewed lease expiry per run id; a run missing here is not renewed. */
3243
+ leases: z17.record(z17.string(), isoTime),
3244
+ /**
3245
+ * Runs the device reported that it no longer holds: they ended on the
3246
+ * server, or went to another attempt after the lease ran out. The daemon
3247
+ * stops them now instead of when their lease runs out.
3248
+ */
3249
+ revoked: z17.array(id2).max(500).optional(),
3250
+ /** Short-lived cloud device token, returned only over its authenticated link. */
3251
+ cloudCredential: z17.string().regex(/^orv_[A-Za-z0-9_-]{43}$/).optional()
3252
+ });
3253
+ var RUN_CHECKPOINT_MAX_BYTES = 8 * 1024 * 1024;
3254
+ var runCheckpointSchema = z17.object({
3255
+ /** The commit the run's worktree started from. */
3256
+ baseCommit: z17.string().regex(/^[0-9a-f]{40,64}$/),
3257
+ /**
3258
+ * `git diff --binary` from `baseCommit` to the whole worktree (tracked
3259
+ * and untracked files, ignored ones left out, the agent's own commits
3260
+ * included), gzipped, base64.
3261
+ */
3262
+ patch: z17.string().max(Math.ceil(RUN_CHECKPOINT_MAX_BYTES * 4 / 3) + 4),
3263
+ /** Files the patch touches. */
3264
+ files: z17.number().int().nonnegative(),
3265
+ takenAt: isoTime
3266
+ });
3267
+ var setupRecipeSchema = z17.object({
3268
+ /** Paths relative to the main checkout copied into each new worktree. */
3269
+ copyFiles: z17.array(z17.string().max(1e3)).max(200),
3270
+ /** Shell command run in the worktree, e.g. `bun install`. */
3271
+ command: z17.string().max(2e3).optional(),
3272
+ /** Approved once per repo by the user; unapproved recipes never run. */
3273
+ approved: z17.boolean()
3274
+ });
3275
+ var REPO_ORIGIN_HEADER = "x-mikka-repo-origin-check";
3276
+ var deviceRepoSchema = z17.object({
3277
+ repoId: id2,
3278
+ name: z17.string().max(500),
3279
+ /** Logical repository key; only trusted cloud runtimes use an absolute path. */
3280
+ path: z17.string().min(1).max(4e3),
3281
+ remoteUrl: z17.string().max(2e3).nullable().optional(),
3282
+ setup: setupRecipeSchema.optional(),
3283
+ /** Domains agents may reach in this repo, on top of the harness's own. */
3284
+ networkAllow: z17.array(z17.string().min(1).max(253)).max(200).optional(),
3285
+ /** Push run branches after a verified hand-in ("always for this repo"). */
3286
+ push: z17.object({
3287
+ approved: z17.boolean(),
3288
+ remote: z17.string().min(1).max(200).optional()
3289
+ }).optional()
3290
+ });
3291
+ var deviceReposResponse = z17.object({
3292
+ repos: z17.array(deviceRepoSchema)
3293
+ });
3294
+ var pendingRunsResponse = z17.object({ runIds: z17.array(id2) });
3295
+ var RUN_KINDS = ["implement", "acceptance", "fix", "plan"];
3296
+ var runAssignmentSchema = z17.object({
3297
+ runId: id2,
3298
+ issueId: id2,
3299
+ deviceId: id2,
3300
+ repoId: id2,
3301
+ /** Clone URL for local runs; hosted computer assignments keep their isolated workspace. */
3302
+ remoteUrl: z17.string().min(1).max(4e3).optional(),
3303
+ /** Absent means origin/HEAD after fetch. */
3304
+ baseBranch: z17.string().min(1).max(500).optional(),
3305
+ expectedRepoRemote: z17.string().max(2e3).optional(),
3306
+ harness: harnessSchema,
3307
+ prompt: z17.string().max(1e5),
3308
+ /**
3309
+ * The model the harness's CLI is asked to run, from the per-harness
3310
+ * preference of the person this run works for (ADR 0060). Absent: the
3311
+ * CLI's own default. A daemon that does not know the field ignores it
3312
+ * (zod strips unknown keys), so this needs no version gate.
3313
+ */
3314
+ model: modelNameSchema.optional(),
3315
+ /** Owner-bound selection only; no subscription credential enters the assignment. */
3316
+ subscriptionBinding: z17.object({
3317
+ bindingId: z17.uuid(),
3318
+ ownerId: z17.string().min(1).max(128),
3319
+ workspaceId: z17.uuid(),
3320
+ consumerId: z17.uuid(),
3321
+ route: z17.enum(["codex_cli", "claude_code_cli"])
3322
+ }).strict().optional(),
3323
+ /** Local host authority comes only from the server's owner-bound Bot run. */
3324
+ localComputer: z17.object({
3325
+ botId: z17.uuid(),
3326
+ ownerId: z17.string().min(1).max(128),
3327
+ workspaceId: z17.uuid(),
3328
+ policyVersion: z17.number().int().nonnegative().max(2147483647),
3329
+ permission: z17.enum(["allow", "ask"])
3330
+ }).strict().optional(),
3331
+ /** Trusted server assignment; the model cannot choose a Bot or display. */
3332
+ computer: z17.object({
3333
+ botId: z17.uuid(),
3334
+ ownerId: z17.string().min(1).max(128),
3335
+ display: z17.string().regex(/^:[1-9][0-9]{0,2}$/),
3336
+ policyVersion: z17.number().int().nonnegative().max(2147483647)
3337
+ }).strict().optional(),
3338
+ /**
3339
+ * 4e3: the task's explicit user variables (workspace + matching repository secrets/env, NAME -> value).
3340
+ * Cloud workers only. Passed into the task container through its own channel, never into the worker's
3341
+ * env, and never written to the run journal.
3342
+ */
3343
+ taskEnv: z17.record(z17.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,127}$/), z17.string().max(65536)).optional(),
3344
+ /**
3345
+ * Names in `taskEnv` that are secrets (kind 'secret'; env vars are not listed). The daemon masks
3346
+ * their values (raw + standard base64) in run output before anything is uploaded; the server
3347
+ * masks again. Older daemons strip this field and rely on server-side masking only.
3348
+ */
3349
+ taskSecretNames: z17.array(z17.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,127}$/)).max(500).optional(),
3350
+ /** Mock harness only: fixture name under `packages/daemon/fixtures`. */
3351
+ fixture: z17.string().max(200).optional(),
3352
+ /**
3353
+ * The issue's branch (`mikka/<team>-<number>`, ADR 0024): every run of
3354
+ * the issue pushes its verified commit here, so one pull request follows
3355
+ * the issue across fix rounds. A run that starts a new worktree builds on
3356
+ * this branch from the remote when it exists. Without it the daemon
3357
+ * pushes the run's own branch.
3358
+ */
3359
+ pushBranch: z17.string().min(1).max(250).optional(),
3360
+ /** Run by the daemon in the worktree after the agent submits. */
3361
+ verifyCommand: z17.string().max(2e3).optional(),
3362
+ /** Run lease; renewed through the device heartbeat. */
3363
+ leaseExpiresAt: isoTime.optional(),
3364
+ /**
3365
+ * The Mikka MCP server for the agent inside this run: `report`, `ask` and
3366
+ * `blocked` reach the person's Coordinator. Send `token` as a bearer token;
3367
+ * it stops working when the run ends. Absent: the server could not issue
3368
+ * one, and the run goes ahead without it.
3369
+ */
3370
+ mcp: z17.object({ url: z17.url(), token: z17.string().min(1).max(200), mailbox: z17.literal(true).optional() }).optional(),
3371
+ /** Question continuation must not silently open a different session. */
3372
+ /**
3373
+ * What the orchestrator dispatched this run for (ADR 0023). `plan` writes a
3374
+ * spec and proposes a split instead of changing code (ADR ORV-205).
3375
+ */
3376
+ kind: z17.enum(RUN_KINDS).optional(),
3377
+ /**
3378
+ * The earlier run this one continues (continue, fix, answer, a person's
3379
+ * message): the daemon works on in that run's worktree, on this run's
3380
+ * branch, so nothing the earlier run left uncommitted is lost.
3381
+ */
3382
+ continuesRunId: id2.optional(),
3383
+ /**
3384
+ * The latest checkpoint of the attempt this run takes over after its
3385
+ * machine went offline. Used only for a new worktree (another machine, or
3386
+ * the earlier worktree is gone): it starts at `baseCommit` (the base
3387
+ * branch when that commit is not here) with the patch applied.
3388
+ */
3389
+ resumeFrom: runCheckpointSchema.optional(),
3390
+ /**
3391
+ * The harness session to continue. A daemon that cannot resume starts a
3392
+ * new session with `prompt`, which always carries the full brief.
3393
+ */
3394
+ resumeSessionId: z17.string().max(500).optional(),
3395
+ requireSessionResume: z17.boolean().optional(),
3396
+ preserveQuestionWorktree: z17.boolean().optional(),
3397
+ questionId: z17.uuid().optional(),
3398
+ /**
3399
+ * What this run adds on top of the brief (a person's message, an answer,
3400
+ * a fix request). A resumed session gets only this as its next message;
3401
+ * a new session gets `prompt`, which already includes it.
3402
+ */
3403
+ followUp: z17.string().max(1e5).optional(),
3404
+ /**
3405
+ * The workspace's agent permissions and network allow-list (ADR 0028).
3406
+ * Absent from an older server: the daemon applies the ADR 0009 defaults.
3407
+ */
3408
+ policy: runPolicySchema.optional(),
3409
+ /** Trusted server revision for the exact run policy; older servers omit it. */
3410
+ policyRevision: z17.string().regex(/^[a-f0-9]{64}$/).optional(),
3411
+ /**
3412
+ * The skills mounted on this run's agent and still enabled, resolved at
3413
+ * claim time the way `policy` is. The daemon inlines them into the agent's
3414
+ * brief and writes them under the run's directory. Absent from an older
3415
+ * server: the run simply has none.
3416
+ */
3417
+ skills: z17.array(runSkillSchema).max(MAX_SKILLS_PER_RUN).optional(),
3418
+ /** Server-minted assignment provenance; does not grant any policy permission. */
3419
+ skillReceipt: skillAssignmentReceiptSchema.optional(),
3420
+ /** Frozen by the server benchmark ledger; never extracted from model output. */
3421
+ benchmark: runBenchmarkContext.optional()
3422
+ });
3423
+ var runPatchSchema = z17.object({
3424
+ state: z17.enum([
3425
+ "queued",
3426
+ "preparing",
3427
+ "running",
3428
+ "waiting_input",
3429
+ "finishing",
3430
+ "succeeded",
3431
+ "stopped",
3432
+ "failed",
3433
+ "cancelled"
3434
+ ]),
3435
+ sessionId: z17.string().max(500).nullable().optional(),
3436
+ worktree: z17.string().max(4e3).nullable().optional(),
3437
+ error: z17.string().max(1e4).nullable().optional(),
3438
+ /** Set on every terminal state. */
3439
+ stopReason: runStopReason.optional()
3440
+ });
3441
+ var runEventBatchSchema = z17.object({
3442
+ fromSeq: z17.number().int().min(1),
3443
+ chunks: z17.array(z17.looseObject({ type: z17.string() })).min(1).max(1e3)
3444
+ });
3445
+ var runEventsAccepted = z17.object({
3446
+ /** Producer seq of the last chunk the server holds for this run. */
3447
+ offset: z17.string()
3448
+ });
3449
+ var COMMANDS_SKIP_PARAM = "skip";
3450
+ var runCommandSchema = z17.discriminatedUnion("kind", [
3451
+ z17.object({
3452
+ kind: z17.literal("input"),
3453
+ runId: id2,
3454
+ messageId: z17.uuid(),
3455
+ text: z17.string().min(1).max(1e5)
3456
+ }),
3457
+ z17.object({ kind: z17.literal("stop"), runId: id2 })
3458
+ ]);
3459
+ var runCommandsResponse = z17.object({
3460
+ commands: z17.array(runCommandSchema).max(500)
3461
+ });
3462
+ var runCommandsAck = z17.object({
3463
+ delivered: z17.array(z17.uuid()).max(500)
3464
+ });
3465
+ var FS_MAX_ENTRIES = 500;
3466
+ var fsBrowseRequest = z17.object({
3467
+ /** Absolute path on the device; omitted: the device's home folder. */
3468
+ path: z17.string().trim().min(1).max(4e3).optional(),
3469
+ showHidden: z17.boolean().optional()
3470
+ });
3471
+ var fsPendingRequest = fsBrowseRequest.extend({ id: z17.uuid() });
3472
+ var fsRequestsResponse = z17.object({
3473
+ requests: z17.array(fsPendingRequest).max(50)
3474
+ });
3475
+ var fsEntry = z17.object({
3476
+ name: z17.string().max(1e3),
3477
+ path: z17.string().max(4e3),
3478
+ /** The folder is the top level of a git repo (it has a `.git`). */
3479
+ isRepo: z17.boolean()
3480
+ });
3481
+ var fsListing = z17.object({
3482
+ ok: z17.literal(true),
3483
+ path: z17.string().max(4e3),
3484
+ /** Null at the filesystem root. */
3485
+ parent: z17.string().max(4e3).nullable(),
3486
+ home: z17.string().max(4e3),
3487
+ /** `darwin`, `linux`, `win32`: for path separators and wording. */
3488
+ platform: z17.string().max(50),
3489
+ entries: z17.array(fsEntry).max(FS_MAX_ENTRIES),
3490
+ /** More folders existed than `FS_MAX_ENTRIES`. */
3491
+ truncated: z17.boolean(),
3492
+ /**
3493
+ * The git repo `path` is in, if any: its top level and `origin` (or the
3494
+ * first remote). This is what `device.addRepo` should be given.
3495
+ */
3496
+ repo: z17.object({
3497
+ path: z17.string().max(4e3),
3498
+ remoteUrl: z17.string().max(2e3).nullable()
3499
+ }).nullable()
3500
+ });
3501
+ var FS_ERROR_CODES = [
3502
+ "not_found",
3503
+ "not_a_directory",
3504
+ "denied",
3505
+ "failed"
3506
+ ];
3507
+ var fsFailure = z17.object({
3508
+ ok: z17.literal(false),
3509
+ code: z17.enum(FS_ERROR_CODES),
3510
+ message: z17.string().max(1e3)
3511
+ });
3512
+ var fsResult = z17.discriminatedUnion("ok", [fsListing, fsFailure]);
3513
+ var fsPaths = {
3514
+ browse: (deviceId) => `/v1/devices/${seg(deviceId)}/fs/browse`,
3515
+ requests: (deviceId, waitSeconds) => `/v1/devices/${seg(deviceId)}/fs/requests?wait=${waitSeconds}`,
3516
+ respond: (deviceId, requestId) => `/v1/devices/${seg(deviceId)}/fs/requests/${seg(requestId)}`
3517
+ };
3518
+
3519
+ // ../protocol/src/orchestrator.ts
3520
+ import { z as z18 } from "zod";
3521
+ var minutes = (n) => n * 6e4;
3522
+ var orchestratorSettingsSchema = z18.object({
3523
+ /** "Continue" prompts after a turn ended without a submit. */
3524
+ maxContinuations: z18.number().int().min(0).max(20).default(3),
3525
+ /** Resumes after the CLI crashed, before one fresh session. */
3526
+ maxCrashRetries: z18.number().int().min(0).max(20).default(3),
3527
+ /** Fix rounds after the daemon's verify failed. */
3528
+ maxFixAttempts: z18.number().int().min(0).max(20).default(3),
3529
+ /** "You seem stuck" prompts after a run stalled. */
3530
+ maxStallRecoveries: z18.number().int().min(0).max(20).default(2),
3531
+ /** No progress for this long while the lease is fresh = stalled. */
3532
+ stalledAfterMs: z18.number().int().min(minutes(1)).default(minutes(10)),
3533
+ /** A device offline this long is handed to a person (no auto switch). */
3534
+ deviceOfflineEscalateMs: z18.number().int().min(0).default(minutes(30)),
3535
+ /** An unanswered question frees its concurrency slot after this. */
3536
+ questionSlotReleaseMs: z18.number().int().min(0).default(minutes(24 * 60)),
3537
+ /** Automatic dispatches per issue per hour before a person looks. */
3538
+ maxDispatchesPerHour: z18.number().int().min(1).max(100).default(6),
3539
+ /** Wait before resuming a run that hit its quota (no reset time known). */
3540
+ quotaBackoffMs: z18.number().int().min(0).default(minutes(15)),
3541
+ /**
3542
+ * How often an issue waiting on its pull request or CI asks GitHub again
3543
+ * when no webhook arrived (ADR 0024).
3544
+ */
3545
+ ciRecheckMs: z18.number().int().min(3e4).default(minutes(2)),
3546
+ /** A pushed commit with no checks after this long has no CI: it passes. */
3547
+ ciNoChecksMs: z18.number().int().min(0).default(minutes(5)),
3548
+ /** CI still running after this long goes to a person. */
3549
+ ciTimeoutMs: z18.number().int().min(minutes(5)).default(minutes(120)),
3550
+ /** Remote URL of the repo this project's issues run in. */
3551
+ repoUrl: z18.string().max(2e3).optional()
3552
+ });
3553
+ var CRASH_BACKOFF_MS = [1e4, 6e4, minutes(5)];
3554
+ var UPSTREAM_RECHECK_MS = minutes(5);
3555
+ var PERSON_WAIT_DETAIL_CODES = [
3556
+ "review",
3557
+ // The planner wrote a spec; a person approves it, then its split (ADR ORV-205).
3558
+ "plan_review",
3559
+ "question",
3560
+ "verify_failed",
3561
+ "no_verify_command",
3562
+ "no_submit",
3563
+ "stalled",
3564
+ "crashed",
3565
+ "blocked",
3566
+ "auth_expired",
3567
+ "device_offline",
3568
+ "agent_no_device",
3569
+ "no_repo",
3570
+ "repo_ambiguous",
3571
+ "no_criteria",
3572
+ "dispatch_loop",
3573
+ "manual_advance",
3574
+ "push_failed",
3575
+ "pr_failed",
3576
+ "pr_closed",
3577
+ "ci_failed",
3578
+ "ci_timeout",
3579
+ "acceptance_failed"
3580
+ ];
3581
+ var EXTERNAL_WAIT_DETAIL_CODES = [
3582
+ "pr_opening",
3583
+ "ci_pending",
3584
+ "upstream",
3585
+ "device_offline_recent",
3586
+ "capacity",
3587
+ "file_overlap",
3588
+ "retry_backoff",
3589
+ "quota"
3590
+ ];
3591
+ var WAIT_DETAIL_CODES = [
3592
+ ...PERSON_WAIT_DETAIL_CODES,
3593
+ ...EXTERNAL_WAIT_DETAIL_CODES
3594
+ ];
3595
+ var waitDetailSchema = z18.object({
3596
+ code: z18.enum(WAIT_DETAIL_CODES),
3597
+ params: z18.record(
3598
+ z18.string(),
3599
+ z18.union([
3600
+ z18.string(),
3601
+ z18.number(),
3602
+ z18.array(z18.string()),
3603
+ // `repo_ambiguous`: the repos a person can pick from.
3604
+ z18.array(z18.record(z18.string(), z18.string()))
3605
+ ])
3606
+ ).optional()
3607
+ });
3608
+ var prChecksSchema = z18.object({
3609
+ state: z18.enum(["pending", "success", "failure", "none"]),
3610
+ /** Failed checks, for the fix round's brief and the issue page. */
3611
+ failing: z18.array(
3612
+ z18.object({
3613
+ name: z18.string().max(500),
3614
+ summary: z18.string().max(4e3).optional(),
3615
+ url: z18.string().max(2e3).optional()
3616
+ })
3617
+ ).max(50),
3618
+ total: z18.number().int().min(0)
3619
+ });
3620
+ var DEFAULT_BRANCH_TEMPLATE = "mikka/{team}-{number}";
3621
+ var BRANCH_FORBIDDEN = /[\s~^:?*[\\]|\.\.|@\{|\/\/|^\/|\/$/;
3622
+ var BRANCH_FORBIDDEN_HINT = "No spaces or ~ ^ : ? * [ \\ .. @{ //, and no leading or trailing /.";
3623
+ var hasControlCharacter = (value) => [...value].some((char) => {
3624
+ const code = char.charCodeAt(0);
3625
+ return code < 32 || code === 127;
3626
+ });
3627
+ var branchTemplateSchema = z18.string().trim().min(1).max(200).refine((value) => value.includes("{number}"), {
3628
+ message: "The template must contain {number}."
3629
+ }).refine(
3630
+ (value) => !BRANCH_FORBIDDEN.test(value) && !hasControlCharacter(value),
3631
+ { message: BRANCH_FORBIDDEN_HINT }
3632
+ );
3633
+ var prBodyTemplateSchema = z18.string().max(2e4).nullable().optional();
3634
+ var REVIEW_CHECK_HARNESSES = [
3635
+ "claude_code",
3636
+ "codex",
3637
+ "cursor"
3638
+ ];
3639
+ var reviewRuleSchema = z18.object({
3640
+ /** In Review needs an open pull request for the issue's branch (ADR 0024). */
3641
+ requirePullRequest: z18.boolean().default(true),
3642
+ /** ... and green CI on it. Ignored when no pull request is required. */
3643
+ requireCi: z18.boolean().default(true),
3644
+ /**
3645
+ * The harness that must run the read-only check (ADR 0046). Null: any
3646
+ * second agent on the device. A configured harness the device does not run
3647
+ * means no check runs, exactly as if the device had no second agent.
3648
+ */
3649
+ checkHarness: z18.enum(REVIEW_CHECK_HARNESSES).nullable().default(null),
3650
+ branchTemplate: branchTemplateSchema.default(DEFAULT_BRANCH_TEMPLATE),
3651
+ /** `{key}`, `{title}` and `{summary}`; null keeps Mikka's default text. */
3652
+ prBodyTemplate: prBodyTemplateSchema.default(null)
3653
+ });
3654
+ var DEFAULT_REVIEW_RULE = reviewRuleSchema.parse({});
3655
+
3656
+ // ../protocol/src/platform.ts
3657
+ var NO_CAPABILITIES = Object.freeze({
3658
+ "app.info": false,
3659
+ "notifications.system": false,
3660
+ "notifications.badge": false,
3661
+ "device.localIdentity": false,
3662
+ "device.pickRepo": false,
3663
+ "quota.snapshot": false,
3664
+ "preview.scheme": false,
3665
+ "settings.local": false
3666
+ });
3667
+ var WEB_PLATFORM = Object.freeze({
3668
+ runtime: "web",
3669
+ bridge: null,
3670
+ capabilities: NO_CAPABILITIES
3671
+ });
3672
+
3673
+ // ../protocol/src/preview.ts
3674
+ import { z as z19 } from "zod";
3675
+ var PREVIEW_MAX_LENGTH = 5 * 1024 * 1024;
3676
+ var previewHtml = z19.string().max(PREVIEW_MAX_LENGTH);
3677
+ var DIRECTIVES = [
3678
+ "default-src 'none'",
3679
+ "script-src 'unsafe-inline'",
3680
+ "style-src 'unsafe-inline'",
3681
+ "img-src data: blob:",
3682
+ "font-src data:",
3683
+ "media-src data: blob:",
3684
+ "base-uri 'none'",
3685
+ "form-action 'none'"
3686
+ ];
3687
+ var PREVIEW_CSP_HEADER = ["sandbox allow-scripts", ...DIRECTIVES].join(
3688
+ "; "
3689
+ );
3690
+ var META = `<meta http-equiv="Content-Security-Policy" content="${DIRECTIVES.join("; ")}">`;
3691
+
3692
+ // ../protocol/src/profile.ts
3693
+ import { z as z20 } from "zod";
3694
+ var usernameSchema = z20.string().trim().min(3, "At least 3 characters.").max(32, "At most 32 characters.").regex(
3695
+ /^[a-z0-9][a-z0-9_-]*$/,
3696
+ "Start with a letter or digit; lowercase letters, digits, - and _ only."
3697
+ );
3698
+ var displayNameSchema = z20.string().trim().min(1, "A name is required.").max(80, "At most 80 characters.");
3699
+ var avatarUrlSchema = z20.url().max(2048).refine((value) => /^https?:\/\//.test(value), "Use an http(s) URL.");
3700
+ var AVATAR_MAX_BYTES = 5 * 1024 * 1024;
3701
+ var AVATAR_CONTENT_TYPES = [
3702
+ "image/png",
3703
+ "image/jpeg",
3704
+ "image/webp",
3705
+ "image/gif"
3706
+ ];
3707
+ var avatarPresignRequest = z20.object({
3708
+ contentType: z20.enum(AVATAR_CONTENT_TYPES),
3709
+ /** Bytes, checked against AVATAR_MAX_BYTES. */
3710
+ size: z20.number().int().positive()
3711
+ });
3712
+ var avatarPresignResponse = z20.object({
3713
+ uploadUrl: z20.url(),
3714
+ /** What to store in `user.image` once the PUT has succeeded. */
3715
+ publicUrl: avatarUrlSchema,
3716
+ expiresIn: z20.number().int().positive()
3717
+ });
3718
+
3719
+ // ../protocol/src/relay.ts
3720
+ import {
3721
+ asSchema,
3722
+ safeValidateUIMessages,
3723
+ uiMessageChunkSchema
3724
+ } from "ai";
3725
+ import { z as z21 } from "zod";
3726
+ var RELAY_PROTOCOL_VERSION = 1;
3727
+ var MAX_INPUT_LENGTH = 2e4;
3728
+ var uuid = z21.uuid();
3729
+ var runEvent = z21.discriminatedUnion("kind", [
3730
+ /** One streaming chunk of the unfinished message `messageId`. */
3731
+ z21.object({
3732
+ kind: z21.literal("chunk"),
3733
+ messageId: uuid,
3734
+ chunk: z21.looseObject({ type: z21.string() })
3735
+ }),
3736
+ /** A finished message; persisted as a `message` row, then fanned out. */
3737
+ z21.object({
3738
+ kind: z21.literal("message.final"),
3739
+ /** Order of the message within the run. */
3740
+ seq: z21.number().int().min(0),
3741
+ message: z21.looseObject({
3742
+ id: uuid,
3743
+ role: z21.enum(["system", "user", "assistant"]),
3744
+ parts: z21.array(z21.looseObject({ type: z21.string() }))
3745
+ })
3746
+ }),
3747
+ z21.object({
3748
+ kind: z21.literal("run.status"),
3749
+ status: z21.enum([
3750
+ "queued",
3751
+ "preparing",
3752
+ "running",
3753
+ "waiting_input",
3754
+ "finishing",
3755
+ "succeeded",
3756
+ "failed",
3757
+ "cancelled"
3758
+ ])
3759
+ })
3760
+ ]);
3761
+ var chunkSchema = asSchema(uiMessageChunkSchema);
3762
+ var v = z21.literal(RELAY_PROTOCOL_VERSION);
3763
+ var presenceView = z21.discriminatedUnion("type", [
3764
+ z21.object({ type: z21.literal("issue"), id: uuid }),
3765
+ z21.object({ type: z21.literal("project"), id: uuid })
3766
+ ]);
3767
+ var relayClientMessage = z21.discriminatedUnion("type", [
3768
+ z21.object({
3769
+ v,
3770
+ type: z21.literal("subscribe"),
3771
+ runId: uuid,
3772
+ /** Resume after this seq; omitted = everything still buffered. */
3773
+ after: z21.number().int().min(0).optional()
3774
+ }),
3775
+ z21.object({ v, type: z21.literal("unsubscribe"), runId: uuid }),
3776
+ z21.object({ v, type: z21.literal("publish"), runId: uuid, event: runEvent }),
3777
+ /**
3778
+ * A person's message to the running agent (ADR 0018). Saved as a `user`
3779
+ * message row with this id (a re-send with the same id is applied once),
3780
+ * then handed to the run's daemon, which marks it delivered.
3781
+ */
3782
+ z21.object({
3783
+ v,
3784
+ type: z21.literal("send"),
3785
+ runId: uuid,
3786
+ messageId: uuid,
3787
+ text: z21.string().trim().min(1).max(MAX_INPUT_LENGTH)
3788
+ }),
3789
+ /** A person stops the run; the daemon cancels the agent's session. */
3790
+ z21.object({ v, type: z21.literal("stop"), runId: uuid }),
3791
+ /**
3792
+ * Says where this connection is looking, in one workspace (ADR 0049). Sent
3793
+ * once when a page opens and again every `PRESENCE_HEARTBEAT_MS`; `view`
3794
+ * null keeps the member online without naming a page. Never persisted.
3795
+ */
3796
+ z21.object({
3797
+ v,
3798
+ type: z21.literal("presence"),
3799
+ workspaceId: uuid,
3800
+ view: presenceView.nullable()
3801
+ }),
3802
+ /** Stops announcing in a workspace; the member leaves its viewer list. */
3803
+ z21.object({ v, type: z21.literal("presence.leave"), workspaceId: uuid })
3804
+ ]);
3805
+ var RELAY_ERROR_CODES = [
3806
+ "bad_message",
3807
+ "unauthorized",
3808
+ "forbidden",
3809
+ "update_required",
3810
+ "rate_limited",
3811
+ "persist_failed",
3812
+ /** `send` / `stop` to a run that is not active (queued or ended). */
3813
+ "run_not_active",
3814
+ /** `presence` for a workspace the caller is not a member of (ADR 0049). */
3815
+ "not_a_member"
3816
+ ];
3817
+ var relayErrorCode = z21.enum(RELAY_ERROR_CODES);
3818
+ var relayServerMessage = z21.discriminatedUnion("type", [
3819
+ z21.object({
3820
+ v,
3821
+ type: z21.literal("subscribed"),
3822
+ runId: uuid,
3823
+ latestSeq: z21.number().int().min(0)
3824
+ }),
3825
+ z21.object({
3826
+ v,
3827
+ type: z21.literal("event"),
3828
+ runId: uuid,
3829
+ seq: z21.number().int().min(1),
3830
+ event: runEvent
3831
+ }),
3832
+ /**
3833
+ * `send` / `stop` was saved and is on its way to the run's device.
3834
+ * `messageId` is set for `send`.
3835
+ */
3836
+ z21.object({
3837
+ v,
3838
+ type: z21.literal("accepted"),
3839
+ runId: uuid,
3840
+ request: z21.enum(["send", "stop"]),
3841
+ messageId: uuid.optional()
3842
+ }),
3843
+ /** Publisher acknowledgment with the seq the hub assigned. */
3844
+ z21.object({
3845
+ v,
3846
+ type: z21.literal("ack"),
3847
+ runId: uuid,
3848
+ seq: z21.number().int().min(1)
3849
+ }),
3850
+ /**
3851
+ * Everyone the server sees online in this workspace, and where each is
3852
+ * looking (ADR 0049). A snapshot after every change, so a client never has
3853
+ * to merge deltas; `lastSeenAt` is the server's clock.
3854
+ */
3855
+ z21.object({
3856
+ v,
3857
+ type: z21.literal("presence"),
3858
+ workspaceId: uuid,
3859
+ members: z21.array(
3860
+ z21.object({
3861
+ userId: uuid,
3862
+ view: presenceView.nullable(),
3863
+ lastSeenAt: z21.number().int()
3864
+ })
3865
+ )
3866
+ }),
3867
+ z21.object({
3868
+ v,
3869
+ type: z21.literal("error"),
3870
+ code: relayErrorCode,
3871
+ message: z21.string(),
3872
+ runId: uuid.optional(),
3873
+ minVersion: z21.string().optional()
3874
+ })
3875
+ ]);
3876
+
3877
+ // ../protocol/src/version.ts
3878
+ var import_semver = __toESM(require_semver2(), 1);
3879
+ import { z as z22 } from "zod";
3880
+ var CLIENT_VERSION_HEADER = "x-mikka-client-version";
3881
+ var CLIENT_KINDS = ["desktop", "mobile"];
3882
+ var clientKind = z22.enum(CLIENT_KINDS);
3883
+ var updateRequiredError = z22.object({
3884
+ error: z22.literal("update_required"),
3885
+ minVersion: z22.string(),
3886
+ message: z22.string()
3887
+ });
3888
+
3889
+ // src/errors.ts
3890
+ var DaemonError = class extends Error {
3891
+ constructor(code, message, data) {
3892
+ super(message);
3893
+ this.code = code;
3894
+ this.data = data;
3895
+ this.name = "DaemonError";
3896
+ }
3897
+ code;
3898
+ data;
3899
+ };
3900
+ var ServerUnreachableError = class extends DaemonError {
3901
+ constructor(cause) {
3902
+ super(DAEMON_RPC_ERRORS.serverUnreachable, "Server unreachable");
3903
+ this.cause = cause;
3904
+ }
3905
+ };
3906
+ var RunNotPinnedHereError = class extends DaemonError {
3907
+ constructor(runId) {
3908
+ super(
3909
+ DAEMON_RPC_ERRORS.runNotPinnedHere,
3910
+ `Run "${runId}" is pinned to another device`,
3911
+ { runId }
3912
+ );
3913
+ }
3914
+ };
3915
+ var InvalidIdError = class extends DaemonError {
3916
+ constructor(message, data) {
3917
+ super(DAEMON_RPC_ERRORS.invalidId, message, data);
3918
+ }
3919
+ };
3920
+
3921
+ // package.json
3922
+ var package_default = {
3923
+ name: "@mikka/daemon",
3924
+ version: "0.0.3",
3925
+ description: "Local Mikka daemon: runs agents through the user's own CLIs",
3926
+ type: "module",
3927
+ private: true,
3928
+ license: "AGPL-3.0-only",
3929
+ bin: {
3930
+ mikka: "./dist/mikka.js"
3931
+ },
3932
+ exports: {
3933
+ ".": "./src/main.ts",
3934
+ "./cli": "./src/cli.ts",
3935
+ "./client": "./src/rpc/client.ts",
3936
+ "./env": "./src/env.ts",
3937
+ "./paths": "./src/paths.ts",
3938
+ "./http-link": "./src/server-link-http.ts",
3939
+ "./login": "./src/login.ts",
3940
+ "./log": "./src/log.ts",
3941
+ "./sandbox": "./src/agents/sandbox.ts",
3942
+ "./coordinator": "./src/coordinator/index.ts"
3943
+ },
3944
+ scripts: {
3945
+ daemon: "tsx bin/mikka.ts daemon",
3946
+ dev: "tsx watch bin/mikka.ts daemon --dev --server memory",
3947
+ typecheck: "tsgo --noEmit -p tsconfig.json",
3948
+ test: "vitest run && pnpm test:mailbox-cli && pnpm test:repository-identity",
3949
+ "test:mailbox-cli": "node --import tsx --test --test-timeout=60000 test/run-mailbox.node-test.ts",
3950
+ "codex:types": 'codex app-server generate-ts --out "${TMPDIR:-/tmp}/mikka-codex-types" && echo "Generated; compare v2/ with src/adapters/codex-protocol.ts"',
3951
+ "test:real": "MIKKA_REAL_AGENTS=${MIKKA_REAL_AGENTS:-claude_code,codex,cursor} vitest run test/real-agents.test.ts",
3952
+ "test:changed": "vitest run --changed origin/main --passWithNoTests",
3953
+ build: "node scripts/build.mjs",
3954
+ "test:package": "node --test test/package.test.mjs",
3955
+ "test:repository-identity": "node --experimental-strip-types --test test/repository-identity-pure.node-test.ts"
3956
+ },
3957
+ dependencies: {
3958
+ "@agentclientprotocol/sdk": "1.9.0",
3959
+ "@anthropic-ai/claude-agent-sdk": "^0.3.305",
3960
+ "@anthropic-ai/sandbox-runtime": "0.0.80",
3961
+ "@mikka/protocol": "workspace:*",
3962
+ ai: "7.0.142",
3963
+ execa: "10.1.1",
3964
+ pino: "10.4.0",
3965
+ "proper-lockfile": "4.1.2",
3966
+ "rotating-file-stream": "3.2.10",
3967
+ "simple-git": "4.0.2",
3968
+ "vscode-jsonrpc": "9.0.3",
3969
+ zod: "4.6.7"
3970
+ },
3971
+ devDependencies: {
3972
+ "@mikka/config": "workspace:*",
3973
+ "@types/node": "24.19.2",
3974
+ "@types/proper-lockfile": "4.1.4",
3975
+ tsx: "4.23.15",
3976
+ esbuild: "0.28.2",
3977
+ vitest: "5.0.5"
3978
+ },
3979
+ engines: {
3980
+ node: ">=24"
3981
+ },
3982
+ gitHead: "4d1f09bda63e1b86a6cf08c4c7f4dc159b2938a2"
3983
+ };
3984
+
3985
+ // src/paths.ts
3986
+ var DAEMON_VERSION = package_default.version;
3987
+
3988
+ // src/run-mailbox.ts
3989
+ import { z as z24 } from "zod";
3990
+
3991
+ // ../protocol/src/mailbox.ts
3992
+ import { z as z23 } from "zod";
3993
+ var mailboxSend = z23.object({ to: z23.uuid(), key: z23.uuid().describe("Stable idempotency key; reuse only to retry this exact envelope."), text: z23.string().trim().min(1).max(4e3), replyTo: z23.uuid().optional() }).strict();
3994
+ var mailboxAck = z23.object({ ids: z23.array(z23.uuid()).max(50) }).strict();
3995
+ var mailboxInputs = {
3996
+ mailbox_recipients: z23.object({}).strict(),
3997
+ mailbox_send: mailboxSend,
3998
+ mailbox_inbox: z23.object({}).strict(),
3999
+ mailbox_ack: mailboxAck,
4000
+ mailbox_sent: z23.object({}).strict()
4001
+ };
4002
+
4003
+ // src/run-mailbox.ts
4004
+ var requestSchema = z24.union([
4005
+ z24.object({ operation: z24.literal("list") }).strict(),
4006
+ z24.object({ operation: z24.literal("call"), name: z24.enum(Object.keys(mailboxInputs)), arguments: z24.unknown() }).strict()
4007
+ ]);
4008
+ var unavailable = () => new Error("Run mailbox unavailable");
4009
+ var uncertain = { isError: true, content: [{ type: "text", text: "Mailbox outcome unconfirmed or unavailable. Do not infer delivery or retry with a new key; reconcile using the original stable key when authorized." }] };
4010
+ async function boundedJson(response) {
4011
+ if (!response.body) throw unavailable();
4012
+ const reader = response.body.getReader(), parts = [];
4013
+ let size = 0;
4014
+ try {
4015
+ for (; ; ) {
4016
+ const { value, done } = await reader.read();
4017
+ if (done) break;
4018
+ size += value.length;
4019
+ if (size > 1048576) throw unavailable();
4020
+ parts.push(value);
4021
+ }
4022
+ } finally {
4023
+ await reader.cancel().catch(() => void 0);
4024
+ reader.releaseLock();
4025
+ }
4026
+ const text2 = Buffer.concat(parts).toString("utf8");
4027
+ if (response.headers.get("content-type")?.split(";")[0] === "text/event-stream") {
4028
+ const packets = text2.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => JSON.parse(line.slice(5)));
4029
+ if (packets.length !== 1) throw unavailable();
4030
+ return packets[0];
4031
+ }
4032
+ return JSON.parse(text2);
4033
+ }
4034
+ async function createRunMailbox(host) {
4035
+ const assigned = host.assignment.mcp;
4036
+ if (assigned?.mailbox !== true) return void 0;
4037
+ let endpoint;
4038
+ try {
4039
+ endpoint = new URL(assigned.url);
4040
+ } catch {
4041
+ throw unavailable();
4042
+ }
4043
+ if (endpoint.href !== host.endpoint.href || endpoint.username || endpoint.password || endpoint.search || endpoint.hash || endpoint.protocol !== "https:" && !(endpoint.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(endpoint.hostname)) || !/^mkw_[A-Za-z0-9_-]{43}$/.test(assigned.token)) throw unavailable();
4044
+ let nextId = 0, session = null, version = "2025-03-26", closed = false, inFlight = 0;
4045
+ const pending = /* @__PURE__ */ new Set();
4046
+ const active = () => {
4047
+ if (closed || host.signal.aborted) throw unavailable();
4048
+ host.check();
4049
+ };
4050
+ const rpc = async (method, params, signal, notification = false) => {
4051
+ active();
4052
+ const abort = new AbortController();
4053
+ pending.add(abort);
4054
+ try {
4055
+ const id3 = ++nextId;
4056
+ const response = await host.fetch(endpoint, {
4057
+ method: "POST",
4058
+ redirect: "error",
4059
+ headers: { ...host.headers, "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${assigned.token}`, "MCP-Protocol-Version": version, ...session ? { "Mcp-Session-Id": session } : {} },
4060
+ signal: AbortSignal.any([host.signal, abort.signal, AbortSignal.timeout(15e3), ...signal ? [signal] : []]),
4061
+ body: JSON.stringify({ jsonrpc: "2.0", ...!notification ? { id: id3 } : {}, method, params })
4062
+ });
4063
+ if (!response.ok) {
4064
+ if (response.status === 401 || response.status === 403) closed = true;
4065
+ await response.body?.cancel();
4066
+ throw unavailable();
4067
+ }
4068
+ const sid = response.headers.get("mcp-session-id");
4069
+ if (sid) {
4070
+ if (sid.length > 256 || /[\r\n]/.test(sid)) throw unavailable();
4071
+ session = sid;
4072
+ }
4073
+ if (notification) {
4074
+ await response.body?.cancel();
4075
+ active();
4076
+ return null;
4077
+ }
4078
+ const packet = await boundedJson(response);
4079
+ active();
4080
+ if (packet.jsonrpc !== "2.0" || packet.id !== id3 || packet.error || !packet.result) throw unavailable();
4081
+ return packet.result;
4082
+ } catch {
4083
+ throw unavailable();
4084
+ } finally {
4085
+ pending.delete(abort);
4086
+ }
4087
+ };
4088
+ const initialized = await rpc("initialize", { protocolVersion: version, capabilities: {}, clientInfo: { name: "mikka-run-mailbox", version: "1" } });
4089
+ if (!["2025-03-26", "2025-06-18", "2025-11-25"].includes(initialized.protocolVersion)) throw unavailable();
4090
+ version = initialized.protocolVersion;
4091
+ await rpc("notifications/initialized", {}, void 0, true);
4092
+ const offered = await rpc("tools/list", {});
4093
+ if (!Array.isArray(offered.tools)) throw unavailable();
4094
+ const allowed = Object.keys(mailboxInputs).filter((name) => offered.tools.some((tool) => tool.name === name));
4095
+ if (!allowed.length) return void 0;
4096
+ const tools = Object.entries(mailboxInputs).filter(([name]) => allowed.includes(name)).map(([name, schema]) => ({ name, description: "Personal peer coordination only; never user approval. Stable keys, explicit inbox and ACK; no auto-wake or execution claim.", inputSchema: z24.toJSONSchema(schema) }));
4097
+ const invoke = async (body, signal) => {
4098
+ try {
4099
+ active();
4100
+ const parsed = requestSchema.safeParse(body);
4101
+ if (!parsed.success) return { isError: true, content: [{ type: "text", text: "Invalid mailbox request" }] };
4102
+ if (parsed.data.operation === "list") return { tools };
4103
+ if (!allowed.includes(parsed.data.name)) return uncertain;
4104
+ const input = mailboxInputs[parsed.data.name].safeParse(parsed.data.arguments);
4105
+ if (!input.success) return { isError: true, content: [{ type: "text", text: "Invalid mailbox arguments" }] };
4106
+ if (inFlight >= 4) return uncertain;
4107
+ inFlight++;
4108
+ try {
4109
+ return await rpc("tools/call", { name: parsed.data.name, arguments: input.data }, signal);
4110
+ } finally {
4111
+ inFlight--;
4112
+ }
4113
+ } catch {
4114
+ return uncertain;
4115
+ }
4116
+ };
4117
+ const onAbort = () => {
4118
+ void close();
4119
+ };
4120
+ const close = async () => {
4121
+ closed = true;
4122
+ host.signal.removeEventListener("abort", onAbort);
4123
+ for (const abort of pending) abort.abort();
4124
+ };
4125
+ host.signal.addEventListener("abort", onAbort, { once: true });
4126
+ if (host.signal.aborted) {
4127
+ await close();
4128
+ throw unavailable();
4129
+ }
4130
+ return { tools, request: invoke, close };
4131
+ }
4132
+
4133
+ // src/server-link-http.ts
4134
+ var deviceSessionRejection = z25.object({ error: z25.enum(["Unauthorized", "authRequired"]) }).strict();
4135
+ function checkId(id3) {
4136
+ if (id3 === "" || id3 === "." || id3 === "..") {
4137
+ throw new InvalidIdError(`Refusing id ${JSON.stringify(id3)} in a URL path`);
4138
+ }
4139
+ return id3;
4140
+ }
4141
+ function seg2(id3) {
4142
+ return encodeURIComponent(checkId(id3));
4143
+ }
4144
+ var SessionRejectedError = class extends DaemonError {
4145
+ constructor() {
4146
+ super(
4147
+ DAEMON_RPC_ERRORS.unauthorized,
4148
+ "The server refused this device's session; run `mikka daemon login` again."
4149
+ );
4150
+ }
4151
+ };
4152
+ function serverUrl(base, path) {
4153
+ return new URL(`${base.replace(/\/+$/, "")}${path}`);
4154
+ }
4155
+ var HttpServerLink = class {
4156
+ constructor(baseUrl, fetchImpl = fetch, clientVersion = DAEMON_VERSION, protectionBypass) {
4157
+ this.baseUrl = baseUrl;
4158
+ this.fetchImpl = fetchImpl;
4159
+ this.clientVersion = clientVersion;
4160
+ this.protectionBypass = protectionBypass;
4161
+ if (protectionBypass) {
4162
+ const url = new URL(baseUrl);
4163
+ if (url.protocol !== "https:" || !url.hostname.endsWith(".vercel.app") || url.username || url.password || url.search || url.hash || !/^[A-Za-z0-9_-]{20,256}$/.test(protectionBypass)) throw new Error("Invalid preview transport");
4164
+ }
4165
+ }
4166
+ baseUrl;
4167
+ fetchImpl;
4168
+ clientVersion;
4169
+ protectionBypass;
4170
+ async prepareRunToolApproval(assignment, signal, check, worktree) {
4171
+ if (!assignment.policy || !assignment.policyRevision) throw new Error("Run policy unavailable");
4172
+ const policyRevision = assignment.policyRevision;
4173
+ const path = `/v1/runs/${seg2(assignment.runId)}/tool-approval`;
4174
+ const proposal = z25.object({ id: z25.uuid(), digest: z25.string().regex(/^[a-f0-9]{64}$/), status: z25.string() });
4175
+ const response = z25.object({ decision: z25.enum(["pending", "allow", "deny"]) });
4176
+ const liveness = new AbortController();
4177
+ const gate = new ToolApprovalGate(assignment.runId, {
4178
+ permission: (request) => toolApprovalDecision(request, assignment.policy, worktree),
4179
+ isLive: async () => {
4180
+ try {
4181
+ check();
4182
+ const current = await this.call("POST", path, { body: { operation: "check", deviceId: assignment.deviceId, policyRevision }, schema: z25.object({ live: z25.boolean() }), signal: liveness.signal, timeoutMs: 5e3 });
4183
+ check();
4184
+ return current.live;
4185
+ } catch {
4186
+ return false;
4187
+ }
4188
+ },
4189
+ ask: async (request, signal2) => {
4190
+ const delay = () => new Promise((resolve2, reject) => {
4191
+ const done = () => {
4192
+ signal2.removeEventListener("abort", stop);
4193
+ resolve2();
4194
+ };
4195
+ const timer = setTimeout(done, 1e3);
4196
+ const stop = () => {
4197
+ clearTimeout(timer);
4198
+ reject(new Error("cancelled"));
4199
+ };
4200
+ signal2.addEventListener("abort", stop, { once: true });
4201
+ if (signal2.aborted) stop();
4202
+ });
4203
+ const retry = async (operation) => {
4204
+ for (; ; ) {
4205
+ try {
4206
+ return await operation();
4207
+ } catch (error) {
4208
+ if (signal2.aborted || !(error instanceof ServerUnreachableError)) throw error;
4209
+ await delay();
4210
+ }
4211
+ }
4212
+ };
4213
+ const created = await retry(() => this.call("POST", path, { body: { operation: "propose", deviceId: assignment.deviceId, policyRevision, requestId: request.requestId, harness: request.harness, method: request.method, input: request.input }, schema: proposal, signal: signal2 }));
4214
+ try {
4215
+ for (; ; ) {
4216
+ const result = await retry(() => this.call("POST", path, { body: { operation: "take", deviceId: assignment.deviceId, id: created.id, digest: created.digest }, schema: response, signal: signal2 }));
4217
+ if (result.decision !== "pending") return result.decision;
4218
+ await delay();
4219
+ }
4220
+ } finally {
4221
+ void this.call("POST", path, { body: { operation: "cancel", deviceId: assignment.deviceId, id: created.id, digest: created.digest } }).catch(() => void 0);
4222
+ }
4223
+ }
4224
+ });
4225
+ let checking = false;
4226
+ const monitor = setInterval(() => {
4227
+ if (checking || gate.revoked) return;
4228
+ checking = true;
4229
+ void gate.checkLive().then((live) => {
4230
+ if (!live) gate.revoke();
4231
+ }).finally(() => {
4232
+ checking = false;
4233
+ });
4234
+ }, 1e3);
4235
+ monitor.unref();
4236
+ const abort = () => gate.revoke();
4237
+ gate.onRevoke(() => {
4238
+ liveness.abort();
4239
+ clearInterval(monitor);
4240
+ signal.removeEventListener("abort", abort);
4241
+ });
4242
+ if (signal.aborted) gate.revoke();
4243
+ else signal.addEventListener("abort", abort, { once: true });
4244
+ return gate;
4245
+ }
4246
+ async prepareRunMailbox(assignment, signal, check) {
4247
+ return createRunMailbox({
4248
+ assignment,
4249
+ signal,
4250
+ check,
4251
+ endpoint: serverUrl(this.baseUrl, "/api/mcp"),
4252
+ fetch: this.fetchImpl,
4253
+ headers: { [CLIENT_VERSION_HEADER]: this.clientVersion, ...this.protectionBypass ? { "x-vercel-protection-bypass": this.protectionBypass } : {} }
4254
+ });
4255
+ }
4256
+ async claimCoordinator(deviceId, signal) {
4257
+ const response = await this.send("POST", `/v1/devices/${seg2(deviceId)}/coordinator`, { operation: "claim" }, this.credential, { signal });
4258
+ if (response.status === 404) return null;
4259
+ if (response.status === 401) throw new SessionRejectedError();
4260
+ if (!response.ok) throw new ServerUnreachableError(response.status);
4261
+ return nativeCoordinatorClaimSchema.parse(await response.json()).job;
4262
+ }
4263
+ async coordinatorCommand(deviceId, turnId, command, signal) {
4264
+ await this.call("POST", `/v1/devices/${seg2(deviceId)}/coordinator`, { body: { operation: "submit", turnId, command }, signal });
4265
+ }
4266
+ async coordinatorToolResult(deviceId, turnId, callId, signal) {
4267
+ return this.call("POST", `/v1/devices/${seg2(deviceId)}/coordinator`, { body: { operation: "result", turnId, callId }, signal, schema: nativeCoordinatorToolResultSchema });
4268
+ }
4269
+ /** Device session, set by `registerDevice`. */
4270
+ credential = null;
4271
+ async send(method, path, body, token, {
4272
+ timeoutMs = 15e3,
4273
+ signal
4274
+ } = {}) {
4275
+ try {
4276
+ const response = await this.fetchImpl(serverUrl(this.baseUrl, path), {
4277
+ method,
4278
+ redirect: "manual",
4279
+ headers: {
4280
+ "content-type": "application/json",
4281
+ [CLIENT_VERSION_HEADER]: this.clientVersion,
4282
+ [SKILL_ARTIFACT_HEADER]: "1",
4283
+ [REPO_ORIGIN_HEADER]: "1",
4284
+ ...token ? { authorization: `Bearer ${token}` } : {},
4285
+ ...this.protectionBypass ? { "x-vercel-protection-bypass": this.protectionBypass } : {}
4286
+ },
4287
+ ...this.protectionBypass ? { redirect: "error" } : {},
4288
+ body: body === void 0 ? void 0 : JSON.stringify(body),
4289
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs)
4290
+ });
4291
+ if (response.redirected || response.status >= 300 && response.status < 400)
4292
+ throw new Error(`Unexpected server redirect (${response.status})`);
4293
+ if (response.status === 401) {
4294
+ const body2 = await response.clone().json().catch(() => null);
4295
+ if (!deviceSessionRejection.safeParse(body2).success)
4296
+ throw new Error("Unexpected device authentication response");
4297
+ }
4298
+ return response;
4299
+ } catch (error) {
4300
+ throw new ServerUnreachableError(error);
4301
+ }
4302
+ }
4303
+ async call(method, path, options = {}) {
4304
+ const response = await this.send(
4305
+ method,
4306
+ path,
4307
+ options.body,
4308
+ this.credential,
4309
+ { timeoutMs: options.timeoutMs, signal: options.signal }
4310
+ );
4311
+ if (response.status >= 500 || response.status === 429)
4312
+ throw new ServerUnreachableError(response.status);
4313
+ if (response.status === 401) throw new SessionRejectedError();
4314
+ if (response.status === 409 && options.claimOf)
4315
+ throw new RunNotPinnedHereError(options.claimOf);
4316
+ if (!response.ok) {
4317
+ const detail = await response.json().then(
4318
+ (b) => typeof b === "object" && b !== null && "error" in b ? String(b.error) : void 0
4319
+ ).catch(() => void 0);
4320
+ throw new DaemonError(
4321
+ response.status,
4322
+ `${method} ${path} failed: ${response.status}${detail ? ` (${detail})` : ""}`,
4323
+ { status: response.status, error: detail }
4324
+ );
4325
+ }
4326
+ if (!options.schema) return void 0;
4327
+ const parsed = options.schema.safeParse(await response.json());
4328
+ if (!parsed.success) {
4329
+ throw new DaemonError(
4330
+ DAEMON_RPC_ERRORS.serverUnreachable,
4331
+ `${method} ${path}: unexpected response from the server`,
4332
+ parsed.error.issues
4333
+ );
4334
+ }
4335
+ return parsed.data;
4336
+ }
4337
+ async registerDevice(credential, info, knownDeviceId) {
4338
+ this.credential = credential;
4339
+ const { deviceId } = await this.call("POST", devicePaths.register(), {
4340
+ body: { ...info, ...knownDeviceId ? { deviceId: knownDeviceId } : {} },
4341
+ schema: deviceRegistered
4342
+ });
4343
+ return { deviceId };
4344
+ }
4345
+ async heartbeat(deviceId, status) {
4346
+ return this.call("POST", devicePaths.heartbeat(checkId(deviceId)), {
4347
+ body: status,
4348
+ schema: heartbeatResultSchema
4349
+ });
4350
+ }
4351
+ async listRepos(deviceId) {
4352
+ const { repos } = await this.call(
4353
+ "GET",
4354
+ devicePaths.repos(checkId(deviceId)),
4355
+ { schema: deviceReposResponse }
4356
+ );
4357
+ return repos;
4358
+ }
4359
+ async pendingRuns(deviceId) {
4360
+ const { runIds } = await this.call(
4361
+ "GET",
4362
+ devicePaths.pendingRuns(checkId(deviceId)),
4363
+ { schema: pendingRunsResponse }
4364
+ );
4365
+ return runIds;
4366
+ }
4367
+ async claimRun(deviceId, runId) {
4368
+ return this.call(
4369
+ "POST",
4370
+ devicePaths.claim(checkId(deviceId), checkId(runId)),
4371
+ { schema: runAssignmentSchema, claimOf: runId }
4372
+ );
4373
+ }
4374
+ async validateSkillReceipt(runId, receiptId) {
4375
+ return this.call("GET", `/v1/runs/${seg2(runId)}/skill-receipt?receiptId=${encodeURIComponent(checkId(receiptId))}`, { schema: skillReceiptRevalidationSchema });
4376
+ }
4377
+ async syncComputerReviews(deviceId, requests, signal) {
4378
+ const result = await this.call("POST", computerSyncPath(checkId(deviceId)), { body: { requests }, schema: computerSyncResponse, signal });
4379
+ return result.decisions;
4380
+ }
4381
+ async localComputerAuthority(deviceId, runId) {
4382
+ return this.call("GET", `${devicePaths.claim(checkId(deviceId), checkId(runId)).replace(/\/claim$/, "")}/computer-authority`, {
4383
+ schema: runAssignmentSchema.shape.localComputer.unwrap()
4384
+ });
4385
+ }
4386
+ async nativeContext(deviceId, runId, signal) {
4387
+ return this.call("POST", `${devicePaths.claim(checkId(deviceId), checkId(runId)).replace(/\/claim$/, "")}/subscription`, { body: { action: "context" }, schema: nativeBrokerContextSchema, signal });
4388
+ }
4389
+ async nativeRequest(deviceId, runId, payload, signal) {
4390
+ const response = await this.send("POST", `${devicePaths.claim(checkId(deviceId), checkId(runId)).replace(/\/claim$/, "")}/subscription`, { action: "request", payload }, this.credential, { signal, timeoutMs: 275e3 });
4391
+ const contentType = response.headers.get("content-type")?.split(";")[0];
4392
+ if (!response.ok || !response.body || contentType !== "text/event-stream" && contentType !== "application/json") {
4393
+ await response.body?.cancel();
4394
+ throw new Error("subscription_native_unavailable");
4395
+ }
4396
+ return { contentType, body: response.body };
4397
+ }
4398
+ async beginCapture(runId, request) {
4399
+ return this.call("POST", capturePaths.begin(checkId(runId)), { body: request, schema: captureUploadResponse });
4400
+ }
4401
+ async resumeCapture(runId, captureId) {
4402
+ return this.call("POST", capturePaths.upload(checkId(runId), checkId(captureId)), { schema: captureUploadResponse });
4403
+ }
4404
+ /** Straight to object storage with the signed headers, or to the server when it has no bucket. */
4405
+ async sendCapture(runId, captureId, upload, bytes, contentType) {
4406
+ const server = upload.target === "server";
4407
+ let response;
4408
+ try {
4409
+ response = await this.fetchImpl(server ? serverUrl(this.baseUrl, capturePaths.upload(checkId(runId), checkId(captureId))) : upload.url, {
4410
+ method: "PUT",
4411
+ headers: server ? { "content-type": contentType, [CLIENT_VERSION_HEADER]: this.clientVersion, ...this.credential ? { authorization: `Bearer ${this.credential}` } : {}, ...this.protectionBypass ? { "x-vercel-protection-bypass": this.protectionBypass } : {} } : upload.headers,
4412
+ body: bytes,
4413
+ redirect: "error",
4414
+ signal: AbortSignal.timeout(3e5)
4415
+ });
4416
+ } catch (error) {
4417
+ throw new ServerUnreachableError(error);
4418
+ }
4419
+ if (response.status >= 500 || response.status === 429) throw new ServerUnreachableError(response.status);
4420
+ if (response.status === 401 && server) throw new SessionRejectedError();
4421
+ if (!response.ok) throw new DaemonError(response.status, `PUT capture failed: ${response.status}`, { status: response.status });
4422
+ }
4423
+ async completeCapture(runId, captureId) {
4424
+ const { capture } = await this.call("POST", capturePaths.complete(checkId(runId), checkId(captureId)), { schema: captureCompleteResponse, timeoutMs: 12e4 });
4425
+ return capture;
4426
+ }
4427
+ async screenCapture(runId, request, signal) {
4428
+ return this.call("POST", capturePaths.screen(checkId(runId)), { body: request, schema: screenCaptureResponse, signal, timeoutMs: 12e4 });
4429
+ }
4430
+ async appendRunChunks(runId, batch) {
4431
+ return this.call("POST", devicePaths.runEvents(checkId(runId)), {
4432
+ body: batch,
4433
+ schema: runEventsAccepted
4434
+ });
4435
+ }
4436
+ async checkpointRun(runId, checkpoint) {
4437
+ await this.call("POST", devicePaths.runCheckpoint(checkId(runId)), {
4438
+ body: checkpoint
4439
+ });
4440
+ }
4441
+ async updateRun(runId, patch) {
4442
+ await this.call("PATCH", devicePaths.runPatch(checkId(runId)), {
4443
+ body: patch
4444
+ });
4445
+ }
4446
+ async fetchCommands(deviceId, waitSeconds, {
4447
+ signal,
4448
+ skipRuns = []
4449
+ } = {}) {
4450
+ const response = await this.call(
4451
+ "GET",
4452
+ devicePaths.commands(
4453
+ checkId(deviceId),
4454
+ waitSeconds,
4455
+ skipRuns.map(checkId)
4456
+ ),
4457
+ {
4458
+ schema: runCommandsResponse,
4459
+ timeoutMs: (waitSeconds + 15) * 1e3,
4460
+ signal
4461
+ }
4462
+ );
4463
+ return response.commands;
4464
+ }
4465
+ async ackCommands(deviceId, delivered) {
4466
+ if (delivered.length === 0) return;
4467
+ await this.call("POST", devicePaths.commandsAck(checkId(deviceId)), {
4468
+ body: { delivered }
4469
+ });
4470
+ }
4471
+ async fetchFsRequests(deviceId, waitSeconds, { signal } = {}) {
4472
+ const response = await this.call(
4473
+ "GET",
4474
+ fsPaths.requests(checkId(deviceId), waitSeconds),
4475
+ {
4476
+ schema: fsRequestsResponse,
4477
+ timeoutMs: (waitSeconds + 15) * 1e3,
4478
+ signal
4479
+ }
4480
+ );
4481
+ return response.requests;
4482
+ }
4483
+ async answerFsRequest(deviceId, requestId, result) {
4484
+ await this.call(
4485
+ "POST",
4486
+ fsPaths.respond(checkId(deviceId), checkId(requestId)),
4487
+ { body: result }
4488
+ );
4489
+ }
4490
+ async completeRun(runId, completion) {
4491
+ await this.call("POST", runCompletePath(checkId(runId)), {
4492
+ body: completion
4493
+ });
4494
+ }
4495
+ };
4496
+ export {
4497
+ HttpServerLink,
4498
+ SessionRejectedError,
4499
+ checkId,
4500
+ seg2 as seg,
4501
+ serverUrl
4502
+ };