unrestricted 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4221 @@
1
+ #!/usr/bin/env node
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ try {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ } catch (e2) {
12
+ throw mod = 0, e2;
13
+ }
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+
32
+ // node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
33
+ var require_src = __commonJS({
34
+ "node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports, module) {
35
+ "use strict";
36
+ var ESC = "\x1B";
37
+ var CSI = `${ESC}[`;
38
+ var beep = "\x07";
39
+ var cursor = {
40
+ to(x2, y3) {
41
+ if (!y3) return `${CSI}${x2 + 1}G`;
42
+ return `${CSI}${y3 + 1};${x2 + 1}H`;
43
+ },
44
+ move(x2, y3) {
45
+ let ret = "";
46
+ if (x2 < 0) ret += `${CSI}${-x2}D`;
47
+ else if (x2 > 0) ret += `${CSI}${x2}C`;
48
+ if (y3 < 0) ret += `${CSI}${-y3}A`;
49
+ else if (y3 > 0) ret += `${CSI}${y3}B`;
50
+ return ret;
51
+ },
52
+ up: (count = 1) => `${CSI}${count}A`,
53
+ down: (count = 1) => `${CSI}${count}B`,
54
+ forward: (count = 1) => `${CSI}${count}C`,
55
+ backward: (count = 1) => `${CSI}${count}D`,
56
+ nextLine: (count = 1) => `${CSI}E`.repeat(count),
57
+ prevLine: (count = 1) => `${CSI}F`.repeat(count),
58
+ left: `${CSI}G`,
59
+ hide: `${CSI}?25l`,
60
+ show: `${CSI}?25h`,
61
+ save: `${ESC}7`,
62
+ restore: `${ESC}8`
63
+ };
64
+ var scroll = {
65
+ up: (count = 1) => `${CSI}S`.repeat(count),
66
+ down: (count = 1) => `${CSI}T`.repeat(count)
67
+ };
68
+ var erase = {
69
+ screen: `${CSI}2J`,
70
+ up: (count = 1) => `${CSI}1J`.repeat(count),
71
+ down: (count = 1) => `${CSI}J`.repeat(count),
72
+ line: `${CSI}2K`,
73
+ lineEnd: `${CSI}K`,
74
+ lineStart: `${CSI}1K`,
75
+ lines(count) {
76
+ let clear = "";
77
+ for (let i = 0; i < count; i++)
78
+ clear += this.line + (i < count - 1 ? cursor.up() : "");
79
+ if (count)
80
+ clear += cursor.left;
81
+ return clear;
82
+ }
83
+ };
84
+ module.exports = { cursor, scroll, erase, beep };
85
+ }
86
+ });
87
+
88
+ // node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
89
+ var require_picocolors = __commonJS({
90
+ "node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports, module) {
91
+ var p2 = process || {};
92
+ var argv = p2.argv || [];
93
+ var env = p2.env || {};
94
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p2.platform === "win32" || (p2.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
95
+ var formatter = (open, close, replace = open) => (input) => {
96
+ let string = "" + input, index = string.indexOf(close, open.length);
97
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
98
+ };
99
+ var replaceClose = (string, close, replace, index) => {
100
+ let result = "", cursor = 0;
101
+ do {
102
+ result += string.substring(cursor, index) + replace;
103
+ cursor = index + close.length;
104
+ index = string.indexOf(close, cursor);
105
+ } while (~index);
106
+ return result + string.substring(cursor);
107
+ };
108
+ var createColors = (enabled = isColorSupported) => {
109
+ let f = enabled ? formatter : () => String;
110
+ return {
111
+ isColorSupported: enabled,
112
+ reset: f("\x1B[0m", "\x1B[0m"),
113
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
114
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
115
+ italic: f("\x1B[3m", "\x1B[23m"),
116
+ underline: f("\x1B[4m", "\x1B[24m"),
117
+ inverse: f("\x1B[7m", "\x1B[27m"),
118
+ hidden: f("\x1B[8m", "\x1B[28m"),
119
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
120
+ black: f("\x1B[30m", "\x1B[39m"),
121
+ red: f("\x1B[31m", "\x1B[39m"),
122
+ green: f("\x1B[32m", "\x1B[39m"),
123
+ yellow: f("\x1B[33m", "\x1B[39m"),
124
+ blue: f("\x1B[34m", "\x1B[39m"),
125
+ magenta: f("\x1B[35m", "\x1B[39m"),
126
+ cyan: f("\x1B[36m", "\x1B[39m"),
127
+ white: f("\x1B[37m", "\x1B[39m"),
128
+ gray: f("\x1B[90m", "\x1B[39m"),
129
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
130
+ bgRed: f("\x1B[41m", "\x1B[49m"),
131
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
132
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
133
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
134
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
135
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
136
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
137
+ blackBright: f("\x1B[90m", "\x1B[39m"),
138
+ redBright: f("\x1B[91m", "\x1B[39m"),
139
+ greenBright: f("\x1B[92m", "\x1B[39m"),
140
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
141
+ blueBright: f("\x1B[94m", "\x1B[39m"),
142
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
143
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
144
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
145
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
146
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
147
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
148
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
149
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
150
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
151
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
152
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
153
+ };
154
+ };
155
+ module.exports = createColors();
156
+ module.exports.createColors = createColors;
157
+ }
158
+ });
159
+
160
+ // node_modules/.pnpm/@clack+prompts@0.11.0/node_modules/@clack/prompts/dist/index.mjs
161
+ import { stripVTControlCharacters as S2 } from "node:util";
162
+
163
+ // node_modules/.pnpm/@clack+core@0.5.0/node_modules/@clack/core/dist/index.mjs
164
+ var import_sisteransi = __toESM(require_src(), 1);
165
+ import { stdin as j, stdout as M } from "node:process";
166
+ import * as g from "node:readline";
167
+ import O from "node:readline";
168
+ import { Writable as X } from "node:stream";
169
+ function DD({ onlyFirst: e2 = false } = {}) {
170
+ const t = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");
171
+ return new RegExp(t, e2 ? void 0 : "g");
172
+ }
173
+ var uD = DD();
174
+ function P(e2) {
175
+ if (typeof e2 != "string") throw new TypeError(`Expected a \`string\`, got \`${typeof e2}\``);
176
+ return e2.replace(uD, "");
177
+ }
178
+ function L(e2) {
179
+ return e2 && e2.__esModule && Object.prototype.hasOwnProperty.call(e2, "default") ? e2.default : e2;
180
+ }
181
+ var W = { exports: {} };
182
+ (function(e2) {
183
+ var u2 = {};
184
+ e2.exports = u2, u2.eastAsianWidth = function(F2) {
185
+ var s = F2.charCodeAt(0), i = F2.length == 2 ? F2.charCodeAt(1) : 0, D2 = s;
186
+ return 55296 <= s && s <= 56319 && 56320 <= i && i <= 57343 && (s &= 1023, i &= 1023, D2 = s << 10 | i, D2 += 65536), D2 == 12288 || 65281 <= D2 && D2 <= 65376 || 65504 <= D2 && D2 <= 65510 ? "F" : D2 == 8361 || 65377 <= D2 && D2 <= 65470 || 65474 <= D2 && D2 <= 65479 || 65482 <= D2 && D2 <= 65487 || 65490 <= D2 && D2 <= 65495 || 65498 <= D2 && D2 <= 65500 || 65512 <= D2 && D2 <= 65518 ? "H" : 4352 <= D2 && D2 <= 4447 || 4515 <= D2 && D2 <= 4519 || 4602 <= D2 && D2 <= 4607 || 9001 <= D2 && D2 <= 9002 || 11904 <= D2 && D2 <= 11929 || 11931 <= D2 && D2 <= 12019 || 12032 <= D2 && D2 <= 12245 || 12272 <= D2 && D2 <= 12283 || 12289 <= D2 && D2 <= 12350 || 12353 <= D2 && D2 <= 12438 || 12441 <= D2 && D2 <= 12543 || 12549 <= D2 && D2 <= 12589 || 12593 <= D2 && D2 <= 12686 || 12688 <= D2 && D2 <= 12730 || 12736 <= D2 && D2 <= 12771 || 12784 <= D2 && D2 <= 12830 || 12832 <= D2 && D2 <= 12871 || 12880 <= D2 && D2 <= 13054 || 13056 <= D2 && D2 <= 19903 || 19968 <= D2 && D2 <= 42124 || 42128 <= D2 && D2 <= 42182 || 43360 <= D2 && D2 <= 43388 || 44032 <= D2 && D2 <= 55203 || 55216 <= D2 && D2 <= 55238 || 55243 <= D2 && D2 <= 55291 || 63744 <= D2 && D2 <= 64255 || 65040 <= D2 && D2 <= 65049 || 65072 <= D2 && D2 <= 65106 || 65108 <= D2 && D2 <= 65126 || 65128 <= D2 && D2 <= 65131 || 110592 <= D2 && D2 <= 110593 || 127488 <= D2 && D2 <= 127490 || 127504 <= D2 && D2 <= 127546 || 127552 <= D2 && D2 <= 127560 || 127568 <= D2 && D2 <= 127569 || 131072 <= D2 && D2 <= 194367 || 177984 <= D2 && D2 <= 196605 || 196608 <= D2 && D2 <= 262141 ? "W" : 32 <= D2 && D2 <= 126 || 162 <= D2 && D2 <= 163 || 165 <= D2 && D2 <= 166 || D2 == 172 || D2 == 175 || 10214 <= D2 && D2 <= 10221 || 10629 <= D2 && D2 <= 10630 ? "Na" : D2 == 161 || D2 == 164 || 167 <= D2 && D2 <= 168 || D2 == 170 || 173 <= D2 && D2 <= 174 || 176 <= D2 && D2 <= 180 || 182 <= D2 && D2 <= 186 || 188 <= D2 && D2 <= 191 || D2 == 198 || D2 == 208 || 215 <= D2 && D2 <= 216 || 222 <= D2 && D2 <= 225 || D2 == 230 || 232 <= D2 && D2 <= 234 || 236 <= D2 && D2 <= 237 || D2 == 240 || 242 <= D2 && D2 <= 243 || 247 <= D2 && D2 <= 250 || D2 == 252 || D2 == 254 || D2 == 257 || D2 == 273 || D2 == 275 || D2 == 283 || 294 <= D2 && D2 <= 295 || D2 == 299 || 305 <= D2 && D2 <= 307 || D2 == 312 || 319 <= D2 && D2 <= 322 || D2 == 324 || 328 <= D2 && D2 <= 331 || D2 == 333 || 338 <= D2 && D2 <= 339 || 358 <= D2 && D2 <= 359 || D2 == 363 || D2 == 462 || D2 == 464 || D2 == 466 || D2 == 468 || D2 == 470 || D2 == 472 || D2 == 474 || D2 == 476 || D2 == 593 || D2 == 609 || D2 == 708 || D2 == 711 || 713 <= D2 && D2 <= 715 || D2 == 717 || D2 == 720 || 728 <= D2 && D2 <= 731 || D2 == 733 || D2 == 735 || 768 <= D2 && D2 <= 879 || 913 <= D2 && D2 <= 929 || 931 <= D2 && D2 <= 937 || 945 <= D2 && D2 <= 961 || 963 <= D2 && D2 <= 969 || D2 == 1025 || 1040 <= D2 && D2 <= 1103 || D2 == 1105 || D2 == 8208 || 8211 <= D2 && D2 <= 8214 || 8216 <= D2 && D2 <= 8217 || 8220 <= D2 && D2 <= 8221 || 8224 <= D2 && D2 <= 8226 || 8228 <= D2 && D2 <= 8231 || D2 == 8240 || 8242 <= D2 && D2 <= 8243 || D2 == 8245 || D2 == 8251 || D2 == 8254 || D2 == 8308 || D2 == 8319 || 8321 <= D2 && D2 <= 8324 || D2 == 8364 || D2 == 8451 || D2 == 8453 || D2 == 8457 || D2 == 8467 || D2 == 8470 || 8481 <= D2 && D2 <= 8482 || D2 == 8486 || D2 == 8491 || 8531 <= D2 && D2 <= 8532 || 8539 <= D2 && D2 <= 8542 || 8544 <= D2 && D2 <= 8555 || 8560 <= D2 && D2 <= 8569 || D2 == 8585 || 8592 <= D2 && D2 <= 8601 || 8632 <= D2 && D2 <= 8633 || D2 == 8658 || D2 == 8660 || D2 == 8679 || D2 == 8704 || 8706 <= D2 && D2 <= 8707 || 8711 <= D2 && D2 <= 8712 || D2 == 8715 || D2 == 8719 || D2 == 8721 || D2 == 8725 || D2 == 8730 || 8733 <= D2 && D2 <= 8736 || D2 == 8739 || D2 == 8741 || 8743 <= D2 && D2 <= 8748 || D2 == 8750 || 8756 <= D2 && D2 <= 8759 || 8764 <= D2 && D2 <= 8765 || D2 == 8776 || D2 == 8780 || D2 == 8786 || 8800 <= D2 && D2 <= 8801 || 8804 <= D2 && D2 <= 8807 || 8810 <= D2 && D2 <= 8811 || 8814 <= D2 && D2 <= 8815 || 8834 <= D2 && D2 <= 8835 || 8838 <= D2 && D2 <= 8839 || D2 == 8853 || D2 == 8857 || D2 == 8869 || D2 == 8895 || D2 == 8978 || 9312 <= D2 && D2 <= 9449 || 9451 <= D2 && D2 <= 9547 || 9552 <= D2 && D2 <= 9587 || 9600 <= D2 && D2 <= 9615 || 9618 <= D2 && D2 <= 9621 || 9632 <= D2 && D2 <= 9633 || 9635 <= D2 && D2 <= 9641 || 9650 <= D2 && D2 <= 9651 || 9654 <= D2 && D2 <= 9655 || 9660 <= D2 && D2 <= 9661 || 9664 <= D2 && D2 <= 9665 || 9670 <= D2 && D2 <= 9672 || D2 == 9675 || 9678 <= D2 && D2 <= 9681 || 9698 <= D2 && D2 <= 9701 || D2 == 9711 || 9733 <= D2 && D2 <= 9734 || D2 == 9737 || 9742 <= D2 && D2 <= 9743 || 9748 <= D2 && D2 <= 9749 || D2 == 9756 || D2 == 9758 || D2 == 9792 || D2 == 9794 || 9824 <= D2 && D2 <= 9825 || 9827 <= D2 && D2 <= 9829 || 9831 <= D2 && D2 <= 9834 || 9836 <= D2 && D2 <= 9837 || D2 == 9839 || 9886 <= D2 && D2 <= 9887 || 9918 <= D2 && D2 <= 9919 || 9924 <= D2 && D2 <= 9933 || 9935 <= D2 && D2 <= 9953 || D2 == 9955 || 9960 <= D2 && D2 <= 9983 || D2 == 10045 || D2 == 10071 || 10102 <= D2 && D2 <= 10111 || 11093 <= D2 && D2 <= 11097 || 12872 <= D2 && D2 <= 12879 || 57344 <= D2 && D2 <= 63743 || 65024 <= D2 && D2 <= 65039 || D2 == 65533 || 127232 <= D2 && D2 <= 127242 || 127248 <= D2 && D2 <= 127277 || 127280 <= D2 && D2 <= 127337 || 127344 <= D2 && D2 <= 127386 || 917760 <= D2 && D2 <= 917999 || 983040 <= D2 && D2 <= 1048573 || 1048576 <= D2 && D2 <= 1114109 ? "A" : "N";
187
+ }, u2.characterLength = function(F2) {
188
+ var s = this.eastAsianWidth(F2);
189
+ return s == "F" || s == "W" || s == "A" ? 2 : 1;
190
+ };
191
+ function t(F2) {
192
+ return F2.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || [];
193
+ }
194
+ u2.length = function(F2) {
195
+ for (var s = t(F2), i = 0, D2 = 0; D2 < s.length; D2++) i = i + this.characterLength(s[D2]);
196
+ return i;
197
+ }, u2.slice = function(F2, s, i) {
198
+ textLen = u2.length(F2), s = s || 0, i = i || 1, s < 0 && (s = textLen + s), i < 0 && (i = textLen + i);
199
+ for (var D2 = "", C2 = 0, n = t(F2), E = 0; E < n.length; E++) {
200
+ var a = n[E], o2 = u2.length(a);
201
+ if (C2 >= s - (o2 == 2 ? 1 : 0)) if (C2 + o2 <= i) D2 += a;
202
+ else break;
203
+ C2 += o2;
204
+ }
205
+ return D2;
206
+ };
207
+ })(W);
208
+ var tD = W.exports;
209
+ var eD = L(tD);
210
+ var FD = function() {
211
+ return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
212
+ };
213
+ var sD = L(FD);
214
+ function p(e2, u2 = {}) {
215
+ if (typeof e2 != "string" || e2.length === 0 || (u2 = { ambiguousIsNarrow: true, ...u2 }, e2 = P(e2), e2.length === 0)) return 0;
216
+ e2 = e2.replace(sD(), " ");
217
+ const t = u2.ambiguousIsNarrow ? 1 : 2;
218
+ let F2 = 0;
219
+ for (const s of e2) {
220
+ const i = s.codePointAt(0);
221
+ if (i <= 31 || i >= 127 && i <= 159 || i >= 768 && i <= 879) continue;
222
+ switch (eD.eastAsianWidth(s)) {
223
+ case "F":
224
+ case "W":
225
+ F2 += 2;
226
+ break;
227
+ case "A":
228
+ F2 += t;
229
+ break;
230
+ default:
231
+ F2 += 1;
232
+ }
233
+ }
234
+ return F2;
235
+ }
236
+ var w = 10;
237
+ var N = (e2 = 0) => (u2) => `\x1B[${u2 + e2}m`;
238
+ var I = (e2 = 0) => (u2) => `\x1B[${38 + e2};5;${u2}m`;
239
+ var R = (e2 = 0) => (u2, t, F2) => `\x1B[${38 + e2};2;${u2};${t};${F2}m`;
240
+ var r = { modifier: { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], blackBright: [90, 39], gray: [90, 39], grey: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgGray: [100, 49], bgGrey: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } };
241
+ Object.keys(r.modifier);
242
+ var iD = Object.keys(r.color);
243
+ var CD = Object.keys(r.bgColor);
244
+ [...iD, ...CD];
245
+ function rD() {
246
+ const e2 = /* @__PURE__ */ new Map();
247
+ for (const [u2, t] of Object.entries(r)) {
248
+ for (const [F2, s] of Object.entries(t)) r[F2] = { open: `\x1B[${s[0]}m`, close: `\x1B[${s[1]}m` }, t[F2] = r[F2], e2.set(s[0], s[1]);
249
+ Object.defineProperty(r, u2, { value: t, enumerable: false });
250
+ }
251
+ return Object.defineProperty(r, "codes", { value: e2, enumerable: false }), r.color.close = "\x1B[39m", r.bgColor.close = "\x1B[49m", r.color.ansi = N(), r.color.ansi256 = I(), r.color.ansi16m = R(), r.bgColor.ansi = N(w), r.bgColor.ansi256 = I(w), r.bgColor.ansi16m = R(w), Object.defineProperties(r, { rgbToAnsi256: { value: (u2, t, F2) => u2 === t && t === F2 ? u2 < 8 ? 16 : u2 > 248 ? 231 : Math.round((u2 - 8) / 247 * 24) + 232 : 16 + 36 * Math.round(u2 / 255 * 5) + 6 * Math.round(t / 255 * 5) + Math.round(F2 / 255 * 5), enumerable: false }, hexToRgb: { value: (u2) => {
252
+ const t = /[a-f\d]{6}|[a-f\d]{3}/i.exec(u2.toString(16));
253
+ if (!t) return [0, 0, 0];
254
+ let [F2] = t;
255
+ F2.length === 3 && (F2 = [...F2].map((i) => i + i).join(""));
256
+ const s = Number.parseInt(F2, 16);
257
+ return [s >> 16 & 255, s >> 8 & 255, s & 255];
258
+ }, enumerable: false }, hexToAnsi256: { value: (u2) => r.rgbToAnsi256(...r.hexToRgb(u2)), enumerable: false }, ansi256ToAnsi: { value: (u2) => {
259
+ if (u2 < 8) return 30 + u2;
260
+ if (u2 < 16) return 90 + (u2 - 8);
261
+ let t, F2, s;
262
+ if (u2 >= 232) t = ((u2 - 232) * 10 + 8) / 255, F2 = t, s = t;
263
+ else {
264
+ u2 -= 16;
265
+ const C2 = u2 % 36;
266
+ t = Math.floor(u2 / 36) / 5, F2 = Math.floor(C2 / 6) / 5, s = C2 % 6 / 5;
267
+ }
268
+ const i = Math.max(t, F2, s) * 2;
269
+ if (i === 0) return 30;
270
+ let D2 = 30 + (Math.round(s) << 2 | Math.round(F2) << 1 | Math.round(t));
271
+ return i === 2 && (D2 += 60), D2;
272
+ }, enumerable: false }, rgbToAnsi: { value: (u2, t, F2) => r.ansi256ToAnsi(r.rgbToAnsi256(u2, t, F2)), enumerable: false }, hexToAnsi: { value: (u2) => r.ansi256ToAnsi(r.hexToAnsi256(u2)), enumerable: false } }), r;
273
+ }
274
+ var ED = rD();
275
+ var d = /* @__PURE__ */ new Set(["\x1B", "\x9B"]);
276
+ var oD = 39;
277
+ var y = "\x07";
278
+ var V = "[";
279
+ var nD = "]";
280
+ var G = "m";
281
+ var _ = `${nD}8;;`;
282
+ var z = (e2) => `${d.values().next().value}${V}${e2}${G}`;
283
+ var K = (e2) => `${d.values().next().value}${_}${e2}${y}`;
284
+ var aD = (e2) => e2.split(" ").map((u2) => p(u2));
285
+ var k = (e2, u2, t) => {
286
+ const F2 = [...u2];
287
+ let s = false, i = false, D2 = p(P(e2[e2.length - 1]));
288
+ for (const [C2, n] of F2.entries()) {
289
+ const E = p(n);
290
+ if (D2 + E <= t ? e2[e2.length - 1] += n : (e2.push(n), D2 = 0), d.has(n) && (s = true, i = F2.slice(C2 + 1).join("").startsWith(_)), s) {
291
+ i ? n === y && (s = false, i = false) : n === G && (s = false);
292
+ continue;
293
+ }
294
+ D2 += E, D2 === t && C2 < F2.length - 1 && (e2.push(""), D2 = 0);
295
+ }
296
+ !D2 && e2[e2.length - 1].length > 0 && e2.length > 1 && (e2[e2.length - 2] += e2.pop());
297
+ };
298
+ var hD = (e2) => {
299
+ const u2 = e2.split(" ");
300
+ let t = u2.length;
301
+ for (; t > 0 && !(p(u2[t - 1]) > 0); ) t--;
302
+ return t === u2.length ? e2 : u2.slice(0, t).join(" ") + u2.slice(t).join("");
303
+ };
304
+ var lD = (e2, u2, t = {}) => {
305
+ if (t.trim !== false && e2.trim() === "") return "";
306
+ let F2 = "", s, i;
307
+ const D2 = aD(e2);
308
+ let C2 = [""];
309
+ for (const [E, a] of e2.split(" ").entries()) {
310
+ t.trim !== false && (C2[C2.length - 1] = C2[C2.length - 1].trimStart());
311
+ let o2 = p(C2[C2.length - 1]);
312
+ if (E !== 0 && (o2 >= u2 && (t.wordWrap === false || t.trim === false) && (C2.push(""), o2 = 0), (o2 > 0 || t.trim === false) && (C2[C2.length - 1] += " ", o2++)), t.hard && D2[E] > u2) {
313
+ const c = u2 - o2, f = 1 + Math.floor((D2[E] - c - 1) / u2);
314
+ Math.floor((D2[E] - 1) / u2) < f && C2.push(""), k(C2, a, u2);
315
+ continue;
316
+ }
317
+ if (o2 + D2[E] > u2 && o2 > 0 && D2[E] > 0) {
318
+ if (t.wordWrap === false && o2 < u2) {
319
+ k(C2, a, u2);
320
+ continue;
321
+ }
322
+ C2.push("");
323
+ }
324
+ if (o2 + D2[E] > u2 && t.wordWrap === false) {
325
+ k(C2, a, u2);
326
+ continue;
327
+ }
328
+ C2[C2.length - 1] += a;
329
+ }
330
+ t.trim !== false && (C2 = C2.map((E) => hD(E)));
331
+ const n = [...C2.join(`
332
+ `)];
333
+ for (const [E, a] of n.entries()) {
334
+ if (F2 += a, d.has(a)) {
335
+ const { groups: c } = new RegExp(`(?:\\${V}(?<code>\\d+)m|\\${_}(?<uri>.*)${y})`).exec(n.slice(E).join("")) || { groups: {} };
336
+ if (c.code !== void 0) {
337
+ const f = Number.parseFloat(c.code);
338
+ s = f === oD ? void 0 : f;
339
+ } else c.uri !== void 0 && (i = c.uri.length === 0 ? void 0 : c.uri);
340
+ }
341
+ const o2 = ED.codes.get(Number(s));
342
+ n[E + 1] === `
343
+ ` ? (i && (F2 += K("")), s && o2 && (F2 += z(o2))) : a === `
344
+ ` && (s && o2 && (F2 += z(s)), i && (F2 += K(i)));
345
+ }
346
+ return F2;
347
+ };
348
+ function Y(e2, u2, t) {
349
+ return String(e2).normalize().replace(/\r\n/g, `
350
+ `).split(`
351
+ `).map((F2) => lD(F2, u2, t)).join(`
352
+ `);
353
+ }
354
+ var xD = ["up", "down", "left", "right", "space", "enter", "cancel"];
355
+ var B = { actions: new Set(xD), aliases: /* @__PURE__ */ new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"], ["", "cancel"], ["escape", "cancel"]]) };
356
+ function $(e2, u2) {
357
+ if (typeof e2 == "string") return B.aliases.get(e2) === u2;
358
+ for (const t of e2) if (t !== void 0 && $(t, u2)) return true;
359
+ return false;
360
+ }
361
+ function BD(e2, u2) {
362
+ if (e2 === u2) return;
363
+ const t = e2.split(`
364
+ `), F2 = u2.split(`
365
+ `), s = [];
366
+ for (let i = 0; i < Math.max(t.length, F2.length); i++) t[i] !== F2[i] && s.push(i);
367
+ return s;
368
+ }
369
+ var AD = globalThis.process.platform.startsWith("win");
370
+ var S = /* @__PURE__ */ Symbol("clack:cancel");
371
+ function pD(e2) {
372
+ return e2 === S;
373
+ }
374
+ function m(e2, u2) {
375
+ const t = e2;
376
+ t.isTTY && t.setRawMode(u2);
377
+ }
378
+ function fD({ input: e2 = j, output: u2 = M, overwrite: t = true, hideCursor: F2 = true } = {}) {
379
+ const s = g.createInterface({ input: e2, output: u2, prompt: "", tabSize: 1 });
380
+ g.emitKeypressEvents(e2, s), e2.isTTY && e2.setRawMode(true);
381
+ const i = (D2, { name: C2, sequence: n }) => {
382
+ const E = String(D2);
383
+ if ($([E, C2, n], "cancel")) {
384
+ F2 && u2.write(import_sisteransi.cursor.show), process.exit(0);
385
+ return;
386
+ }
387
+ if (!t) return;
388
+ const a = C2 === "return" ? 0 : -1, o2 = C2 === "return" ? -1 : 0;
389
+ g.moveCursor(u2, a, o2, () => {
390
+ g.clearLine(u2, 1, () => {
391
+ e2.once("keypress", i);
392
+ });
393
+ });
394
+ };
395
+ return F2 && u2.write(import_sisteransi.cursor.hide), e2.once("keypress", i), () => {
396
+ e2.off("keypress", i), F2 && u2.write(import_sisteransi.cursor.show), e2.isTTY && !AD && e2.setRawMode(false), s.terminal = false, s.close();
397
+ };
398
+ }
399
+ var gD = Object.defineProperty;
400
+ var vD = (e2, u2, t) => u2 in e2 ? gD(e2, u2, { enumerable: true, configurable: true, writable: true, value: t }) : e2[u2] = t;
401
+ var h = (e2, u2, t) => (vD(e2, typeof u2 != "symbol" ? u2 + "" : u2, t), t);
402
+ var x = class {
403
+ constructor(u2, t = true) {
404
+ h(this, "input"), h(this, "output"), h(this, "_abortSignal"), h(this, "rl"), h(this, "opts"), h(this, "_render"), h(this, "_track", false), h(this, "_prevFrame", ""), h(this, "_subscribers", /* @__PURE__ */ new Map()), h(this, "_cursor", 0), h(this, "state", "initial"), h(this, "error", ""), h(this, "value");
405
+ const { input: F2 = j, output: s = M, render: i, signal: D2, ...C2 } = u2;
406
+ this.opts = C2, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = i.bind(this), this._track = t, this._abortSignal = D2, this.input = F2, this.output = s;
407
+ }
408
+ unsubscribe() {
409
+ this._subscribers.clear();
410
+ }
411
+ setSubscriber(u2, t) {
412
+ const F2 = this._subscribers.get(u2) ?? [];
413
+ F2.push(t), this._subscribers.set(u2, F2);
414
+ }
415
+ on(u2, t) {
416
+ this.setSubscriber(u2, { cb: t });
417
+ }
418
+ once(u2, t) {
419
+ this.setSubscriber(u2, { cb: t, once: true });
420
+ }
421
+ emit(u2, ...t) {
422
+ const F2 = this._subscribers.get(u2) ?? [], s = [];
423
+ for (const i of F2) i.cb(...t), i.once && s.push(() => F2.splice(F2.indexOf(i), 1));
424
+ for (const i of s) i();
425
+ }
426
+ prompt() {
427
+ return new Promise((u2, t) => {
428
+ if (this._abortSignal) {
429
+ if (this._abortSignal.aborted) return this.state = "cancel", this.close(), u2(S);
430
+ this._abortSignal.addEventListener("abort", () => {
431
+ this.state = "cancel", this.close();
432
+ }, { once: true });
433
+ }
434
+ const F2 = new X();
435
+ F2._write = (s, i, D2) => {
436
+ this._track && (this.value = this.rl?.line.replace(/\t/g, ""), this._cursor = this.rl?.cursor ?? 0, this.emit("value", this.value)), D2();
437
+ }, this.input.pipe(F2), this.rl = O.createInterface({ input: this.input, output: F2, tabSize: 2, prompt: "", escapeCodeTimeout: 50, terminal: true }), O.emitKeypressEvents(this.input, this.rl), this.rl.prompt(), this.opts.initialValue !== void 0 && this._track && this.rl.write(this.opts.initialValue), this.input.on("keypress", this.onKeypress), m(this.input, true), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
438
+ this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), m(this.input, false), u2(this.value);
439
+ }), this.once("cancel", () => {
440
+ this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), m(this.input, false), u2(S);
441
+ });
442
+ });
443
+ }
444
+ onKeypress(u2, t) {
445
+ if (this.state === "error" && (this.state = "active"), t?.name && (!this._track && B.aliases.has(t.name) && this.emit("cursor", B.aliases.get(t.name)), B.actions.has(t.name) && this.emit("cursor", t.name)), u2 && (u2.toLowerCase() === "y" || u2.toLowerCase() === "n") && this.emit("confirm", u2.toLowerCase() === "y"), u2 === " " && this.opts.placeholder && (this.value || (this.rl?.write(this.opts.placeholder), this.emit("value", this.opts.placeholder))), u2 && this.emit("key", u2.toLowerCase()), t?.name === "return") {
446
+ if (this.opts.validate) {
447
+ const F2 = this.opts.validate(this.value);
448
+ F2 && (this.error = F2 instanceof Error ? F2.message : F2, this.state = "error", this.rl?.write(this.value));
449
+ }
450
+ this.state !== "error" && (this.state = "submit");
451
+ }
452
+ $([u2, t?.name, t?.sequence], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
453
+ }
454
+ close() {
455
+ this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
456
+ `), m(this.input, false), this.rl?.close(), this.rl = void 0, this.emit(`${this.state}`, this.value), this.unsubscribe();
457
+ }
458
+ restoreCursor() {
459
+ const u2 = Y(this._prevFrame, process.stdout.columns, { hard: true }).split(`
460
+ `).length - 1;
461
+ this.output.write(import_sisteransi.cursor.move(-999, u2 * -1));
462
+ }
463
+ render() {
464
+ const u2 = Y(this._render(this) ?? "", process.stdout.columns, { hard: true });
465
+ if (u2 !== this._prevFrame) {
466
+ if (this.state === "initial") this.output.write(import_sisteransi.cursor.hide);
467
+ else {
468
+ const t = BD(this._prevFrame, u2);
469
+ if (this.restoreCursor(), t && t?.length === 1) {
470
+ const F2 = t[0];
471
+ this.output.write(import_sisteransi.cursor.move(0, F2)), this.output.write(import_sisteransi.erase.lines(1));
472
+ const s = u2.split(`
473
+ `);
474
+ this.output.write(s[F2]), this._prevFrame = u2, this.output.write(import_sisteransi.cursor.move(0, s.length - F2 - 1));
475
+ return;
476
+ }
477
+ if (t && t?.length > 1) {
478
+ const F2 = t[0];
479
+ this.output.write(import_sisteransi.cursor.move(0, F2)), this.output.write(import_sisteransi.erase.down());
480
+ const s = u2.split(`
481
+ `).slice(F2);
482
+ this.output.write(s.join(`
483
+ `)), this._prevFrame = u2;
484
+ return;
485
+ }
486
+ this.output.write(import_sisteransi.erase.down());
487
+ }
488
+ this.output.write(u2), this.state === "initial" && (this.state = "active"), this._prevFrame = u2;
489
+ }
490
+ }
491
+ };
492
+ var A;
493
+ A = /* @__PURE__ */ new WeakMap();
494
+ var kD = Object.defineProperty;
495
+ var $D = (e2, u2, t) => u2 in e2 ? kD(e2, u2, { enumerable: true, configurable: true, writable: true, value: t }) : e2[u2] = t;
496
+ var H = (e2, u2, t) => ($D(e2, typeof u2 != "symbol" ? u2 + "" : u2, t), t);
497
+ var SD = class extends x {
498
+ constructor(u2) {
499
+ super(u2, false), H(this, "options"), H(this, "cursor", 0), this.options = u2.options, this.value = [...u2.initialValues ?? []], this.cursor = Math.max(this.options.findIndex(({ value: t }) => t === u2.cursorAt), 0), this.on("key", (t) => {
500
+ t === "a" && this.toggleAll();
501
+ }), this.on("cursor", (t) => {
502
+ switch (t) {
503
+ case "left":
504
+ case "up":
505
+ this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
506
+ break;
507
+ case "down":
508
+ case "right":
509
+ this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
510
+ break;
511
+ case "space":
512
+ this.toggleValue();
513
+ break;
514
+ }
515
+ });
516
+ }
517
+ get _value() {
518
+ return this.options[this.cursor].value;
519
+ }
520
+ toggleAll() {
521
+ const u2 = this.value.length === this.options.length;
522
+ this.value = u2 ? [] : this.options.map((t) => t.value);
523
+ }
524
+ toggleValue() {
525
+ const u2 = this.value.includes(this._value);
526
+ this.value = u2 ? this.value.filter((t) => t !== this._value) : [...this.value, this._value];
527
+ }
528
+ };
529
+
530
+ // node_modules/.pnpm/@clack+prompts@0.11.0/node_modules/@clack/prompts/dist/index.mjs
531
+ var import_picocolors = __toESM(require_picocolors(), 1);
532
+ var import_sisteransi2 = __toESM(require_src(), 1);
533
+ import y2 from "node:process";
534
+ function ce() {
535
+ return y2.platform !== "win32" ? y2.env.TERM !== "linux" : !!y2.env.CI || !!y2.env.WT_SESSION || !!y2.env.TERMINUS_SUBLIME || y2.env.ConEmuTask === "{cmd::Cmder}" || y2.env.TERM_PROGRAM === "Terminus-Sublime" || y2.env.TERM_PROGRAM === "vscode" || y2.env.TERM === "xterm-256color" || y2.env.TERM === "alacritty" || y2.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
536
+ }
537
+ var V2 = ce();
538
+ var u = (t, n) => V2 ? t : n;
539
+ var le = u("\u25C6", "*");
540
+ var L2 = u("\u25A0", "x");
541
+ var W2 = u("\u25B2", "x");
542
+ var C = u("\u25C7", "o");
543
+ var ue = u("\u250C", "T");
544
+ var o = u("\u2502", "|");
545
+ var d2 = u("\u2514", "\u2014");
546
+ var k2 = u("\u25CF", ">");
547
+ var P2 = u("\u25CB", " ");
548
+ var A2 = u("\u25FB", "[\u2022]");
549
+ var T = u("\u25FC", "[+]");
550
+ var F = u("\u25FB", "[ ]");
551
+ var $e = u("\u25AA", "\u2022");
552
+ var _2 = u("\u2500", "-");
553
+ var me = u("\u256E", "+");
554
+ var de = u("\u251C", "+");
555
+ var pe = u("\u256F", "+");
556
+ var q = u("\u25CF", "\u2022");
557
+ var D = u("\u25C6", "*");
558
+ var U = u("\u25B2", "!");
559
+ var K2 = u("\u25A0", "x");
560
+ var b2 = (t) => {
561
+ switch (t) {
562
+ case "initial":
563
+ case "active":
564
+ return import_picocolors.default.cyan(le);
565
+ case "cancel":
566
+ return import_picocolors.default.red(L2);
567
+ case "error":
568
+ return import_picocolors.default.yellow(W2);
569
+ case "submit":
570
+ return import_picocolors.default.green(C);
571
+ }
572
+ };
573
+ var G2 = (t) => {
574
+ const { cursor: n, options: r2, style: i } = t, s = t.maxItems ?? Number.POSITIVE_INFINITY, c = Math.max(process.stdout.rows - 4, 0), a = Math.min(c, Math.max(s, 5));
575
+ let l2 = 0;
576
+ n >= l2 + a - 3 ? l2 = Math.max(Math.min(n - a + 3, r2.length - a), 0) : n < l2 + 2 && (l2 = Math.max(n - 2, 0));
577
+ const $2 = a < r2.length && l2 > 0, g2 = a < r2.length && l2 + a < r2.length;
578
+ return r2.slice(l2, l2 + a).map((p2, v, f) => {
579
+ const j2 = v === 0 && $2, E = v === f.length - 1 && g2;
580
+ return j2 || E ? import_picocolors.default.dim("...") : i(p2, v + l2 === n);
581
+ });
582
+ };
583
+ var fe = (t) => {
584
+ const n = (r2, i) => {
585
+ const s = r2.label ?? String(r2.value);
586
+ return i === "active" ? `${import_picocolors.default.cyan(A2)} ${s} ${r2.hint ? import_picocolors.default.dim(`(${r2.hint})`) : ""}` : i === "selected" ? `${import_picocolors.default.green(T)} ${import_picocolors.default.dim(s)} ${r2.hint ? import_picocolors.default.dim(`(${r2.hint})`) : ""}` : i === "cancelled" ? `${import_picocolors.default.strikethrough(import_picocolors.default.dim(s))}` : i === "active-selected" ? `${import_picocolors.default.green(T)} ${s} ${r2.hint ? import_picocolors.default.dim(`(${r2.hint})`) : ""}` : i === "submitted" ? `${import_picocolors.default.dim(s)}` : `${import_picocolors.default.dim(F)} ${import_picocolors.default.dim(s)}`;
587
+ };
588
+ return new SD({ options: t.options, initialValues: t.initialValues, required: t.required ?? true, cursorAt: t.cursorAt, validate(r2) {
589
+ if (this.required && r2.length === 0) return `Please select at least one option.
590
+ ${import_picocolors.default.reset(import_picocolors.default.dim(`Press ${import_picocolors.default.gray(import_picocolors.default.bgWhite(import_picocolors.default.inverse(" space ")))} to select, ${import_picocolors.default.gray(import_picocolors.default.bgWhite(import_picocolors.default.inverse(" enter ")))} to submit`))}`;
591
+ }, render() {
592
+ const r2 = `${import_picocolors.default.gray(o)}
593
+ ${b2(this.state)} ${t.message}
594
+ `, i = (s, c) => {
595
+ const a = this.value.includes(s.value);
596
+ return c && a ? n(s, "active-selected") : a ? n(s, "selected") : n(s, c ? "active" : "inactive");
597
+ };
598
+ switch (this.state) {
599
+ case "submit":
600
+ return `${r2}${import_picocolors.default.gray(o)} ${this.options.filter(({ value: s }) => this.value.includes(s)).map((s) => n(s, "submitted")).join(import_picocolors.default.dim(", ")) || import_picocolors.default.dim("none")}`;
601
+ case "cancel": {
602
+ const s = this.options.filter(({ value: c }) => this.value.includes(c)).map((c) => n(c, "cancelled")).join(import_picocolors.default.dim(", "));
603
+ return `${r2}${import_picocolors.default.gray(o)} ${s.trim() ? `${s}
604
+ ${import_picocolors.default.gray(o)}` : ""}`;
605
+ }
606
+ case "error": {
607
+ const s = this.error.split(`
608
+ `).map((c, a) => a === 0 ? `${import_picocolors.default.yellow(d2)} ${import_picocolors.default.yellow(c)}` : ` ${c}`).join(`
609
+ `);
610
+ return `${r2 + import_picocolors.default.yellow(o)} ${G2({ options: this.options, cursor: this.cursor, maxItems: t.maxItems, style: i }).join(`
611
+ ${import_picocolors.default.yellow(o)} `)}
612
+ ${s}
613
+ `;
614
+ }
615
+ default:
616
+ return `${r2}${import_picocolors.default.cyan(o)} ${G2({ options: this.options, cursor: this.cursor, maxItems: t.maxItems, style: i }).join(`
617
+ ${import_picocolors.default.cyan(o)} `)}
618
+ ${import_picocolors.default.cyan(d2)}
619
+ `;
620
+ }
621
+ } }).prompt();
622
+ };
623
+ var Me = (t = "", n = "") => {
624
+ const r2 = `
625
+ ${t}
626
+ `.split(`
627
+ `), i = S2(n).length, s = Math.max(r2.reduce((a, l2) => {
628
+ const $2 = S2(l2);
629
+ return $2.length > a ? $2.length : a;
630
+ }, 0), i) + 2, c = r2.map((a) => `${import_picocolors.default.gray(o)} ${import_picocolors.default.dim(a)}${" ".repeat(s - S2(a).length)}${import_picocolors.default.gray(o)}`).join(`
631
+ `);
632
+ process.stdout.write(`${import_picocolors.default.gray(o)}
633
+ ${import_picocolors.default.green(C)} ${import_picocolors.default.reset(n)} ${import_picocolors.default.gray(_2.repeat(Math.max(s - i - 1, 1)) + me)}
634
+ ${c}
635
+ ${import_picocolors.default.gray(de + _2.repeat(s + 2) + pe)}
636
+ `);
637
+ };
638
+ var xe = (t = "") => {
639
+ process.stdout.write(`${import_picocolors.default.gray(d2)} ${import_picocolors.default.red(t)}
640
+
641
+ `);
642
+ };
643
+ var Ie = (t = "") => {
644
+ process.stdout.write(`${import_picocolors.default.gray(ue)} ${t}
645
+ `);
646
+ };
647
+ var Se = (t = "") => {
648
+ process.stdout.write(`${import_picocolors.default.gray(o)}
649
+ ${import_picocolors.default.gray(d2)} ${t}
650
+
651
+ `);
652
+ };
653
+ var M2 = { message: (t = "", { symbol: n = import_picocolors.default.gray(o) } = {}) => {
654
+ const r2 = [`${import_picocolors.default.gray(o)}`];
655
+ if (t) {
656
+ const [i, ...s] = t.split(`
657
+ `);
658
+ r2.push(`${n} ${i}`, ...s.map((c) => `${import_picocolors.default.gray(o)} ${c}`));
659
+ }
660
+ process.stdout.write(`${r2.join(`
661
+ `)}
662
+ `);
663
+ }, info: (t) => {
664
+ M2.message(t, { symbol: import_picocolors.default.blue(q) });
665
+ }, success: (t) => {
666
+ M2.message(t, { symbol: import_picocolors.default.green(D) });
667
+ }, step: (t) => {
668
+ M2.message(t, { symbol: import_picocolors.default.green(C) });
669
+ }, warn: (t) => {
670
+ M2.message(t, { symbol: import_picocolors.default.yellow(U) });
671
+ }, warning: (t) => {
672
+ M2.warn(t);
673
+ }, error: (t) => {
674
+ M2.message(t, { symbol: import_picocolors.default.red(K2) });
675
+ } };
676
+ var J = `${import_picocolors.default.gray(o)} `;
677
+ var Y2 = ({ indicator: t = "dots" } = {}) => {
678
+ const n = V2 ? ["\u25D2", "\u25D0", "\u25D3", "\u25D1"] : ["\u2022", "o", "O", "0"], r2 = V2 ? 80 : 120, i = process.env.CI === "true";
679
+ let s, c, a = false, l2 = "", $2, g2 = performance.now();
680
+ const p2 = (m2) => {
681
+ const h2 = m2 > 1 ? "Something went wrong" : "Canceled";
682
+ a && N2(h2, m2);
683
+ }, v = () => p2(2), f = () => p2(1), j2 = () => {
684
+ process.on("uncaughtExceptionMonitor", v), process.on("unhandledRejection", v), process.on("SIGINT", f), process.on("SIGTERM", f), process.on("exit", p2);
685
+ }, E = () => {
686
+ process.removeListener("uncaughtExceptionMonitor", v), process.removeListener("unhandledRejection", v), process.removeListener("SIGINT", f), process.removeListener("SIGTERM", f), process.removeListener("exit", p2);
687
+ }, B2 = () => {
688
+ if ($2 === void 0) return;
689
+ i && process.stdout.write(`
690
+ `);
691
+ const m2 = $2.split(`
692
+ `);
693
+ process.stdout.write(import_sisteransi2.cursor.move(-999, m2.length - 1)), process.stdout.write(import_sisteransi2.erase.down(m2.length));
694
+ }, R2 = (m2) => m2.replace(/\.+$/, ""), O2 = (m2) => {
695
+ const h2 = (performance.now() - m2) / 1e3, w2 = Math.floor(h2 / 60), I2 = Math.floor(h2 % 60);
696
+ return w2 > 0 ? `[${w2}m ${I2}s]` : `[${I2}s]`;
697
+ }, H2 = (m2 = "") => {
698
+ a = true, s = fD(), l2 = R2(m2), g2 = performance.now(), process.stdout.write(`${import_picocolors.default.gray(o)}
699
+ `);
700
+ let h2 = 0, w2 = 0;
701
+ j2(), c = setInterval(() => {
702
+ if (i && l2 === $2) return;
703
+ B2(), $2 = l2;
704
+ const I2 = import_picocolors.default.magenta(n[h2]);
705
+ if (i) process.stdout.write(`${I2} ${l2}...`);
706
+ else if (t === "timer") process.stdout.write(`${I2} ${l2} ${O2(g2)}`);
707
+ else {
708
+ const z2 = ".".repeat(Math.floor(w2)).slice(0, 3);
709
+ process.stdout.write(`${I2} ${l2}${z2}`);
710
+ }
711
+ h2 = h2 + 1 < n.length ? h2 + 1 : 0, w2 = w2 < n.length ? w2 + 0.125 : 0;
712
+ }, r2);
713
+ }, N2 = (m2 = "", h2 = 0) => {
714
+ a = false, clearInterval(c), B2();
715
+ const w2 = h2 === 0 ? import_picocolors.default.green(C) : h2 === 1 ? import_picocolors.default.red(L2) : import_picocolors.default.red(W2);
716
+ l2 = R2(m2 ?? l2), t === "timer" ? process.stdout.write(`${w2} ${l2} ${O2(g2)}
717
+ `) : process.stdout.write(`${w2} ${l2}
718
+ `), E(), s();
719
+ };
720
+ return { start: H2, stop: N2, message: (m2 = "") => {
721
+ l2 = R2(m2 ?? l2);
722
+ } };
723
+ };
724
+
725
+ // cli/src/command.ts
726
+ var FAILED = { code: 1 };
727
+ function reason(error) {
728
+ return error instanceof Error ? error.message : String(error);
729
+ }
730
+
731
+ // cli/src/writers/json-file.ts
732
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
733
+
734
+ // cli/src/text-file.ts
735
+ var BOM = "\uFEFF";
736
+ var NEW_FILE = { eol: "\n", bom: false };
737
+ function layoutOf(raw) {
738
+ const firstBreak = raw.indexOf("\n");
739
+ const eol = firstBreak > 0 && raw[firstBreak - 1] === "\r" ? "\r\n" : "\n";
740
+ return { eol, bom: raw.startsWith(BOM) };
741
+ }
742
+ function withoutBom(raw) {
743
+ return raw.startsWith(BOM) ? raw.slice(BOM.length) : raw;
744
+ }
745
+ function withBom(text, layout) {
746
+ return layout.bom ? `${BOM}${text}` : text;
747
+ }
748
+ function toLf(raw) {
749
+ return withoutBom(raw).replace(/\r\n/g, "\n");
750
+ }
751
+ function fromLf(text, layout) {
752
+ return withBom(layout.eol === "\n" ? text : text.replace(/\r?\n/g, "\r\n"), layout);
753
+ }
754
+
755
+ // cli/src/writers/json-file.ts
756
+ function asObject(value) {
757
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
758
+ }
759
+ function readJsonDocument(file) {
760
+ if (!existsSync(file)) writeFileSync(file, "{}\n");
761
+ const raw = readFileSync(file, "utf8");
762
+ const text = toLf(raw).trim();
763
+ return { value: text ? asObject(JSON.parse(text)) : {}, layout: layoutOf(raw) };
764
+ }
765
+ function writeJsonDocument(file, value, layout = NEW_FILE) {
766
+ writeFileSync(file, fromLf(`${JSON.stringify(value, null, 2)}
767
+ `, layout));
768
+ }
769
+
770
+ // cli/src/models.ts
771
+ var MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
772
+ var MODEL_NAME = /^[\p{L}\p{N}._+()/-]+(?: [\p{L}\p{N}._+()/-]+)*$/u;
773
+ function isWritable(value, pattern) {
774
+ return typeof value === "string" && pattern.test(value);
775
+ }
776
+ function isModelId(value) {
777
+ return isWritable(value, MODEL_ID);
778
+ }
779
+ function isLimit(value) {
780
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
781
+ }
782
+ function isPrice(value) {
783
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
784
+ }
785
+ function readPricing(value) {
786
+ const { input, cached_input: cachedInput, output } = asObject(value);
787
+ if (!isPrice(input) || !isPrice(cachedInput) || !isPrice(output)) return null;
788
+ return { input, cachedInput, output };
789
+ }
790
+ function readModel(value) {
791
+ const entry = asObject(value);
792
+ const { id, name, context_length: context, max_output_tokens: maxOutput } = entry;
793
+ if (!isModelId(id) || !isWritable(name, MODEL_NAME) || !isLimit(context) || !isLimit(maxOutput)) return null;
794
+ return { id, name, context, maxOutput, pricing: readPricing(entry.pricing) };
795
+ }
796
+ function parseModelCatalog(body) {
797
+ const data = asObject(body).data;
798
+ if (!Array.isArray(data)) return [];
799
+ const models2 = [];
800
+ for (const value of data) {
801
+ const model = readModel(value);
802
+ if (model && !models2.some((known) => known.id === model.id)) models2.push(model);
803
+ }
804
+ return models2;
805
+ }
806
+ function parseModelList(body) {
807
+ return parseModelCatalog(body).map(({ id, name, context, maxOutput }) => ({ id, name, context, maxOutput }));
808
+ }
809
+ function withListedModels(config, listed) {
810
+ if (listed.length === 0) return config;
811
+ const selected = listed.find((model) => model.id === config.model);
812
+ if (!selected) {
813
+ const own = { id: config.model, name: config.modelName, context: config.context, maxOutput: config.maxOutput };
814
+ return { ...config, models: [own, ...listed] };
815
+ }
816
+ return { ...config, modelName: selected.name, context: selected.context, maxOutput: selected.maxOutput, models: listed };
817
+ }
818
+
819
+ // cli/src/api.ts
820
+ var TIMEOUT_MS = 2e4;
821
+ var TEXT_MAX_LENGTH = 200;
822
+ var PLAN_NAME_MAX_LENGTH = 64;
823
+ var CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/g;
824
+ async function readJson(response) {
825
+ try {
826
+ return await response.json();
827
+ } catch {
828
+ return null;
829
+ }
830
+ }
831
+ async function getJson(url, headers, timeoutMs) {
832
+ const controller = new AbortController();
833
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
834
+ try {
835
+ let response;
836
+ try {
837
+ response = await fetch(url, { headers, signal: controller.signal });
838
+ } catch {
839
+ throw new Error(`Could not reach ${url}.`);
840
+ }
841
+ return { status: response.status, ok: response.ok, body: await readJson(response) };
842
+ } finally {
843
+ clearTimeout(timer);
844
+ }
845
+ }
846
+ function printable(value, maxLength) {
847
+ if (typeof value !== "string") return null;
848
+ const cleaned = value.replace(CONTROL_CHARACTERS, "").trim().slice(0, maxLength);
849
+ return cleaned === "" ? null : cleaned;
850
+ }
851
+ function isAmount(value) {
852
+ return typeof value === "number" && Number.isFinite(value);
853
+ }
854
+ function errorMessage(body) {
855
+ return printable(asObject(asObject(body).error).message, TEXT_MAX_LENGTH);
856
+ }
857
+ async function verifyKey(base, key) {
858
+ const url = `${base}/models`;
859
+ const controller = new AbortController();
860
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
861
+ try {
862
+ let response;
863
+ try {
864
+ response = await fetch(url, { headers: { Authorization: `Bearer ${key}` }, signal: controller.signal });
865
+ } catch {
866
+ throw new Error(`could not reach ${url}`);
867
+ }
868
+ if (!response.ok) throw new Error(`the key was rejected by ${url}`);
869
+ return parseModelList(await readJson(response));
870
+ } finally {
871
+ clearTimeout(timer);
872
+ }
873
+ }
874
+ async function fetchModelCatalog(base, timeoutMs = TIMEOUT_MS) {
875
+ const url = `${base}/models`;
876
+ const answer = await getJson(url, { accept: "application/json" }, timeoutMs);
877
+ if (!answer.ok) throw new Error(`${url} answered ${answer.status}.`);
878
+ return parseModelCatalog(answer.body);
879
+ }
880
+ function parsePlan(value) {
881
+ if (value === null) return null;
882
+ if (typeof value !== "object" || Array.isArray(value)) return void 0;
883
+ const { name, allowance_usd: allowanceUsd, used_usd: usedUsd, renews_at: renews } = asObject(value);
884
+ const planName = printable(name, PLAN_NAME_MAX_LENGTH);
885
+ const renewsAt = typeof renews === "string" ? new Date(renews) : null;
886
+ if (planName === null || !isAmount(allowanceUsd) || !isAmount(usedUsd) || renewsAt === null || Number.isNaN(renewsAt.getTime())) {
887
+ return void 0;
888
+ }
889
+ return { name: planName, allowanceUsd, usedUsd, renewsAt };
890
+ }
891
+ function parseAccount(body) {
892
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return null;
893
+ const { balance_usd: balanceUsd, plan, month_spend_usd: monthSpendUsd, api_locked: apiLocked } = asObject(body);
894
+ const parsedPlan = parsePlan(plan);
895
+ if (!isAmount(balanceUsd) || !isAmount(monthSpendUsd) || typeof apiLocked !== "boolean" || parsedPlan === void 0) return null;
896
+ return { balanceUsd, plan: parsedPlan, monthSpendUsd, apiLocked };
897
+ }
898
+ async function fetchAccount(base, key) {
899
+ const url = `${base}/account`;
900
+ const answer = await getJson(url, { Authorization: `Bearer ${key}`, accept: "application/json" }, TIMEOUT_MS);
901
+ if (answer.status === 401) throw new Error('The key was rejected. Run "unrestricted login" to sign in again.');
902
+ if (answer.status === 403) throw new Error(errorMessage(answer.body) ?? `${url} refused the key.`);
903
+ if (!answer.ok) throw new Error(`${url} answered ${answer.status}.`);
904
+ const account = parseAccount(answer.body);
905
+ if (account === null) throw new Error(`Unexpected answer from ${url}.`);
906
+ return account;
907
+ }
908
+
909
+ // cli/src/config.ts
910
+ import { homedir } from "node:os";
911
+ import { posix, win32 } from "node:path";
912
+ var THIS_MACHINE = { platform: process.platform, homedir };
913
+ var AUTO_UPDATE_TOOLS = ["opencode", "pi"];
914
+ var ALL_TOOLS = ["opencode", "codex", "aider", "continue", "crush", "pi", "claude"];
915
+ var DISABLED_TOOLS = /* @__PURE__ */ new Set(["codex", "claude"]);
916
+ var OFFERED_TOOLS = ALL_TOOLS.filter((tool) => !DISABLED_TOOLS.has(tool));
917
+ var TOOL_LABELS = {
918
+ opencode: "OpenCode",
919
+ codex: "Codex CLI",
920
+ aider: "Aider",
921
+ continue: "Continue",
922
+ crush: "Crush",
923
+ pi: "Pi",
924
+ claude: "Claude Code"
925
+ };
926
+ var SETUP_INTRO = "unrestricted.sh setup";
927
+ var SETUP_OUTRO = "Done.";
928
+ var WINDOWS_PLATFORM = "win32";
929
+ var CONFIG_HOME_DIR = ".config";
930
+ var OPENCODE_CONFIG_DIR = "opencode";
931
+ var OPENCODE_CONFIG_FILE = "opencode.json";
932
+ var OPENCODE_JSONC_FILE = "opencode.jsonc";
933
+ var AIDER_CONFIG_FILE = ".aider.conf.yml";
934
+ var CONTINUE_CONFIG_DIR = ".continue";
935
+ var CONTINUE_CONFIG_FILE = "config.yaml";
936
+ var CRUSH_CONFIG_DIR = "crush";
937
+ var CRUSH_CONFIG_FILE = "crushrc";
938
+ var PI_AGENT_DIR = ".pi/agent";
939
+ var PI_AGENT_DIR_ENV = "PI_CODING_AGENT_DIR";
940
+ var PI_MODELS_FILE = "models.json";
941
+ var PI_SETTINGS_FILE = "settings.json";
942
+ var PI_API = "openai-completions";
943
+ var PI_THINKING_LEVEL_MAP = { off: "none", minimal: null, low: "low", medium: "medium", high: "xhigh" };
944
+ var DEFAULT_BASE_URL = "https://api.unrestricted.sh/v1";
945
+ var DEFAULT_ORIGIN = "https://unrestricted.sh";
946
+ var DEFAULT_MODEL = "qwen3.8-27b-uncensored";
947
+ var DEFAULT_MODEL_NAME = "Qwen3.8 27B Uncensored";
948
+ var PREVIOUS_DEFAULT_MODELS = ["abliterated-model"];
949
+ var CONTEXT = 262144;
950
+ var MAX_OUTPUT = 32768;
951
+ var PROVIDER = "unrestricted";
952
+ var KEY_PREFIX = "unr_sk_";
953
+ var KEY_LENGTH = 39;
954
+ var KEY_ERROR = `UNRESTRICTED_API_KEY is not an ${KEY_PREFIX} key. Leave it unset to approve the connection in the browser instead.`;
955
+ function keyAcceptedMessage(base) {
956
+ return `Key accepted by ${base}`;
957
+ }
958
+ function piModel(id, name, context, maxOutput) {
959
+ return {
960
+ id,
961
+ name,
962
+ reasoning: true,
963
+ thinkingLevelMap: PI_THINKING_LEVEL_MAP,
964
+ input: ["text"],
965
+ contextWindow: context,
966
+ maxTokens: maxOutput
967
+ };
968
+ }
969
+ function isOwnModel(model, config) {
970
+ return model === config.model || model === DEFAULT_MODEL || PREVIOUS_DEFAULT_MODELS.includes(model) || config.models.some((listed) => listed.id === model);
971
+ }
972
+ function isToolId(value) {
973
+ return ALL_TOOLS.includes(value);
974
+ }
975
+ function isAutoUpdateTool(tool) {
976
+ return AUTO_UPDATE_TOOLS.includes(tool);
977
+ }
978
+ function parseTools(value) {
979
+ const tools = [];
980
+ const unknown = [];
981
+ const disabled = [];
982
+ for (const entry of value.split(",")) {
983
+ const name = entry.trim();
984
+ if (!name) continue;
985
+ if (!isToolId(name)) unknown.push(name);
986
+ else if (DISABLED_TOOLS.has(name)) disabled.push(name);
987
+ else tools.push(name);
988
+ }
989
+ return { tools, unknown, disabled };
990
+ }
991
+ function stripTrailingSlashes(value) {
992
+ return value.replace(/\/+$/, "");
993
+ }
994
+ function pathsFor(platform) {
995
+ return platform === WINDOWS_PLATFORM ? win32 : posix;
996
+ }
997
+ function windowsShellPath(dir) {
998
+ if (!dir.startsWith("/") || dir.startsWith("//") || dir.includes("\\")) return dir;
999
+ const drive = /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i.exec(dir);
1000
+ if (drive === null) return dir;
1001
+ return `${drive[1].toUpperCase()}:\\${(drive[2] ?? "").replaceAll("/", "\\")}`;
1002
+ }
1003
+ function resolvePiAgentDir(env, home, platform) {
1004
+ const { join: join4 } = pathsFor(platform);
1005
+ const set = env[PI_AGENT_DIR_ENV];
1006
+ if (!set) return join4(home, ...PI_AGENT_DIR.split("/"));
1007
+ const windows = platform === WINDOWS_PLATFORM;
1008
+ const dir = windows ? windowsShellPath(set) : set;
1009
+ if (dir === "~") return home;
1010
+ if (dir.startsWith("~/") || windows && dir.startsWith("~\\")) return join4(home, dir.slice(2));
1011
+ return dir;
1012
+ }
1013
+ function homeOf(env, machine) {
1014
+ if (env.HOME) return env.HOME;
1015
+ try {
1016
+ return machine.homedir();
1017
+ } catch {
1018
+ return "";
1019
+ }
1020
+ }
1021
+ function readConfig(env, machine = THIS_MACHINE) {
1022
+ const key = env.UNRESTRICTED_API_KEY ?? "";
1023
+ if (key && !key.startsWith(KEY_PREFIX)) throw new Error(KEY_ERROR);
1024
+ if (key && key.length !== KEY_LENGTH) throw new Error("UNRESTRICTED_API_KEY has the wrong length");
1025
+ const home = homeOf(env, machine);
1026
+ if (!home) throw new Error("HOME is not set and the home directory could not be found");
1027
+ const { join: join4 } = pathsFor(machine.platform);
1028
+ const model = env.UNRESTRICTED_MODEL || DEFAULT_MODEL;
1029
+ const modelName = env.UNRESTRICTED_MODEL_NAME || DEFAULT_MODEL_NAME;
1030
+ return {
1031
+ key: key || null,
1032
+ base: env.UNRESTRICTED_BASE_URL || DEFAULT_BASE_URL,
1033
+ origin: stripTrailingSlashes(env.UNRESTRICTED_ORIGIN || env.UNRESTRICTED_SETUP_ORIGIN || DEFAULT_ORIGIN),
1034
+ model,
1035
+ modelName,
1036
+ context: CONTEXT,
1037
+ maxOutput: MAX_OUTPUT,
1038
+ models: [{ id: model, name: modelName, context: CONTEXT, maxOutput: MAX_OUTPUT }],
1039
+ provider: PROVIDER,
1040
+ platform: machine.platform,
1041
+ home,
1042
+ configHome: env.XDG_CONFIG_HOME || join4(home, CONFIG_HOME_DIR),
1043
+ piAgentDir: resolvePiAgentDir(env, home, machine.platform)
1044
+ };
1045
+ }
1046
+
1047
+ // cli/src/format.ts
1048
+ var TOKENS_PER_THOUSAND = 1e3;
1049
+ var TOKENS_PER_MILLION = 1e6;
1050
+ var PRICE_DIGITS = 6;
1051
+ var COLUMN_GAP = " ";
1052
+ var dollars = new Intl.NumberFormat("en-US", {
1053
+ style: "currency",
1054
+ currency: "USD",
1055
+ minimumFractionDigits: 2,
1056
+ maximumFractionDigits: 2
1057
+ });
1058
+ var day = new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" });
1059
+ function contextLabel(tokens) {
1060
+ if (tokens >= TOKENS_PER_MILLION) return `${Math.floor(tokens / TOKENS_PER_MILLION)}M`;
1061
+ return `${Math.round(tokens / TOKENS_PER_THOUSAND)}K`;
1062
+ }
1063
+ function priceLabel(usd) {
1064
+ const [whole, fraction = ""] = usd.toFixed(PRICE_DIGITS).replace(/0+$/, "").split(".");
1065
+ return `$${whole}.${fraction.padEnd(2, "0")}`;
1066
+ }
1067
+ function usdLabel(usd) {
1068
+ return dollars.format(usd);
1069
+ }
1070
+ function dateLabel(date) {
1071
+ return day.format(date);
1072
+ }
1073
+ function table(rows, rightAligned = /* @__PURE__ */ new Set()) {
1074
+ const widths = (rows[0] ?? []).map((_3, column) => Math.max(...rows.map((row) => (row[column] ?? "").length)));
1075
+ return rows.map(
1076
+ (row) => widths.map((width, column) => {
1077
+ const cell = row[column] ?? "";
1078
+ return rightAligned.has(column) ? cell.padStart(width) : cell.padEnd(width);
1079
+ }).join(COLUMN_GAP).trimEnd()
1080
+ ).join("\n");
1081
+ }
1082
+
1083
+ // cli/src/store.ts
1084
+ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, renameSync, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
1085
+ import { join } from "node:path";
1086
+
1087
+ // cli/src/file-mode.ts
1088
+ import { chmodSync } from "node:fs";
1089
+ var WINDOWS = "win32";
1090
+ function setMode(path, mode, platform = process.platform) {
1091
+ if (platform === WINDOWS) return;
1092
+ chmodSync(path, mode);
1093
+ }
1094
+
1095
+ // cli/src/paths.ts
1096
+ var CODEX_CONFIG_DIR = ".codex";
1097
+ var CODEX_CONFIG_FILE = "config.toml";
1098
+ var CLAUDE_CONFIG_DIR = ".claude";
1099
+ var CLAUDE_SETTINGS_FILE = "settings.json";
1100
+ var CLAUDE_SESSION_FILE = "claude-settings.json";
1101
+ var CLAUDE_LAUNCHER = "claude-unrestricted";
1102
+ var STORE_DIR_NAME = "unrestricted";
1103
+ var OPENCODE_PLUGINS_DIR = "plugins";
1104
+ var PI_EXTENSIONS_DIR = "extensions";
1105
+ var AUTO_UPDATE_FILE = "unrestricted.ts";
1106
+ function toolPaths(locations) {
1107
+ const { join: join4 } = pathsFor(locations.platform);
1108
+ const { home, configHome, piAgentDir } = locations;
1109
+ const opencodeDir = join4(configHome, OPENCODE_CONFIG_DIR);
1110
+ const crushDir = join4(configHome, CRUSH_CONFIG_DIR);
1111
+ const continueDir = join4(home, CONTINUE_CONFIG_DIR);
1112
+ const codexDir = join4(home, CODEX_CONFIG_DIR);
1113
+ const claudeDir = join4(home, CLAUDE_CONFIG_DIR);
1114
+ const claudeLauncherDir = join4(home, ".local", "bin");
1115
+ return {
1116
+ opencodeDir,
1117
+ opencodeJson: join4(opencodeDir, OPENCODE_CONFIG_FILE),
1118
+ opencodeJsonc: join4(opencodeDir, OPENCODE_JSONC_FILE),
1119
+ opencodePlugin: join4(opencodeDir, OPENCODE_PLUGINS_DIR, AUTO_UPDATE_FILE),
1120
+ crushDir,
1121
+ crushrc: join4(crushDir, CRUSH_CONFIG_FILE),
1122
+ piAgentDir,
1123
+ piModels: join4(piAgentDir, PI_MODELS_FILE),
1124
+ piSettings: join4(piAgentDir, PI_SETTINGS_FILE),
1125
+ piExtension: join4(piAgentDir, PI_EXTENSIONS_DIR, AUTO_UPDATE_FILE),
1126
+ continueDir,
1127
+ continueConfig: join4(continueDir, CONTINUE_CONFIG_FILE),
1128
+ aiderConfig: join4(home, AIDER_CONFIG_FILE),
1129
+ codexDir,
1130
+ codexConfig: join4(codexDir, CODEX_CONFIG_FILE),
1131
+ claudeDir,
1132
+ claudeGlobalSettings: join4(claudeDir, CLAUDE_SETTINGS_FILE),
1133
+ claudeSessionSettings: join4(configHome, STORE_DIR_NAME, CLAUDE_SESSION_FILE),
1134
+ claudeLauncherDir,
1135
+ claudeLauncher: join4(claudeLauncherDir, CLAUDE_LAUNCHER)
1136
+ };
1137
+ }
1138
+
1139
+ // cli/src/store.ts
1140
+ var CREDENTIALS_FILE = "credentials.json";
1141
+ var STATE_FILE = "state.json";
1142
+ var DIR_MODE = 448;
1143
+ var FILE_MODE = 384;
1144
+ var WEB_ORIGIN = /^https?:\/\/\S+$/;
1145
+ var SHA256 = /^[0-9a-f]{64}$/;
1146
+ function storeDir(configHome) {
1147
+ return join(configHome, STORE_DIR_NAME);
1148
+ }
1149
+ function credentialsPath(configHome) {
1150
+ return join(storeDir(configHome), CREDENTIALS_FILE);
1151
+ }
1152
+ function statePath(configHome) {
1153
+ return join(storeDir(configHome), STATE_FILE);
1154
+ }
1155
+ function isKey(value) {
1156
+ return typeof value === "string" && value.startsWith(KEY_PREFIX) && value.length === KEY_LENGTH;
1157
+ }
1158
+ function readStoreFile(file) {
1159
+ let parsed;
1160
+ try {
1161
+ parsed = JSON.parse(readFileSync2(file, "utf8"));
1162
+ } catch {
1163
+ return null;
1164
+ }
1165
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? asObject(parsed) : null;
1166
+ }
1167
+ function writeStoreFile(configHome, file, value) {
1168
+ const dir = storeDir(configHome);
1169
+ mkdirSync(dir, { recursive: true, mode: DIR_MODE });
1170
+ setMode(dir, DIR_MODE);
1171
+ const pending = `${file}.${process.pid}.tmp`;
1172
+ writeFileSync2(pending, `${JSON.stringify(value, null, 2)}
1173
+ `, { mode: FILE_MODE });
1174
+ setMode(pending, FILE_MODE);
1175
+ renameSync(pending, file);
1176
+ return file;
1177
+ }
1178
+ function unique(values) {
1179
+ return values.filter((value, index) => values.indexOf(value) === index);
1180
+ }
1181
+ function readCredentials(configHome) {
1182
+ const stored = readStoreFile(credentialsPath(configHome));
1183
+ if (stored === null) return null;
1184
+ const { key, origin } = stored;
1185
+ if (!isKey(key) || typeof origin !== "string" || !WEB_ORIGIN.test(origin)) return null;
1186
+ return { key, origin };
1187
+ }
1188
+ function saveCredentials(configHome, credentials) {
1189
+ return writeStoreFile(configHome, credentialsPath(configHome), { key: credentials.key, origin: credentials.origin });
1190
+ }
1191
+ function deleteCredentials(configHome) {
1192
+ const file = credentialsPath(configHome);
1193
+ if (!existsSync2(file)) return false;
1194
+ rmSync(file, { force: true });
1195
+ return true;
1196
+ }
1197
+ function readAutoUpdate(value) {
1198
+ const stored = asObject(value);
1199
+ const records = {};
1200
+ for (const tool of AUTO_UPDATE_TOOLS) {
1201
+ const { path, sha256: sha2562 } = asObject(stored[tool]);
1202
+ if (typeof path === "string" && path !== "" && typeof sha2562 === "string" && SHA256.test(sha2562)) records[tool] = { path, sha256: sha2562 };
1203
+ }
1204
+ return records;
1205
+ }
1206
+ function withAutoUpdate(value, records) {
1207
+ return records === void 0 || Object.keys(records).length === 0 ? value : { ...value, autoUpdate: records };
1208
+ }
1209
+ function readState(configHome) {
1210
+ const stored = readStoreFile(statePath(configHome));
1211
+ if (stored === null || !Array.isArray(stored.tools)) return null;
1212
+ const tools = unique(stored.tools.filter((tool) => typeof tool === "string" && isToolId(tool)));
1213
+ const models2 = Array.isArray(stored.models) ? unique(stored.models.filter(isModelId)) : [];
1214
+ return withAutoUpdate({ tools, models: models2, model: isModelId(stored.model) ? stored.model : null }, readAutoUpdate(stored.autoUpdate));
1215
+ }
1216
+ function saveState(configHome, state) {
1217
+ const { tools, models: models2, model } = state;
1218
+ return writeStoreFile(configHome, statePath(configHome), withAutoUpdate({ tools, models: models2, model }, state.autoUpdate));
1219
+ }
1220
+ function mergeTools(previous, configured) {
1221
+ return unique([...previous, ...configured]);
1222
+ }
1223
+ function mergeAutoUpdate(previous, changes) {
1224
+ const records = { ...previous };
1225
+ for (const tool of AUTO_UPDATE_TOOLS) {
1226
+ const change = changes[tool];
1227
+ if (change === null) delete records[tool];
1228
+ else if (change !== void 0) records[tool] = change;
1229
+ }
1230
+ return records;
1231
+ }
1232
+ function keyFor(pending) {
1233
+ if (pending.key) return pending.key;
1234
+ const stored = readCredentials(pending.configHome);
1235
+ return stored !== null && stored.origin === pending.origin ? stored.key : null;
1236
+ }
1237
+
1238
+ // cli/src/commands/balance.ts
1239
+ var NO_KEY_MESSAGE = 'No key is stored. Run "unrestricted login" to sign in.';
1240
+ function planLine(plan) {
1241
+ if (plan === null) return "none";
1242
+ return `${plan.name}, ${usdLabel(plan.usedUsd)} of ${usdLabel(plan.allowanceUsd)} used, renews ${dateLabel(plan.renewsAt)}`;
1243
+ }
1244
+ function lockedLine(origin) {
1245
+ return `API keys are locked: add funds at ${origin}/billing to unlock them.`;
1246
+ }
1247
+ function balanceLines(account, origin) {
1248
+ const rows = table([
1249
+ ["Balance", usdLabel(account.balanceUsd)],
1250
+ ["Plan", planLine(account.plan)],
1251
+ ["This month", `${usdLabel(account.monthSpendUsd)} spent`]
1252
+ ]);
1253
+ return account.apiLocked ? [rows, "", lockedLine(origin)] : [rows];
1254
+ }
1255
+ async function balance(context) {
1256
+ let pending;
1257
+ try {
1258
+ pending = readConfig(context.env, context.machine);
1259
+ } catch (error) {
1260
+ context.warn(`${reason(error)}
1261
+ `);
1262
+ return FAILED;
1263
+ }
1264
+ const key = keyFor(pending);
1265
+ if (key === null) {
1266
+ context.warn(`${NO_KEY_MESSAGE}
1267
+ `);
1268
+ return FAILED;
1269
+ }
1270
+ let account;
1271
+ try {
1272
+ account = await fetchAccount(pending.base, key);
1273
+ } catch (error) {
1274
+ context.warn(`${reason(error)}
1275
+ `);
1276
+ return FAILED;
1277
+ }
1278
+ context.write(`${balanceLines(account, pending.origin).join("\n")}
1279
+ `);
1280
+ return { code: 0 };
1281
+ }
1282
+
1283
+ // cli/src/device-login.ts
1284
+ var CLIENT_ID = "unrestricted-cli";
1285
+ var GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
1286
+ var DEVICE_CODE_PATH = "/api/auth/device/code";
1287
+ var DEVICE_TOKEN_PATH = "/api/auth/device/token";
1288
+ var CLI_KEY_PATH = "/api/cli/key";
1289
+ var VERIFICATION_PATH = "/device";
1290
+ var BILLING_PATH = "/billing";
1291
+ var DEFAULT_INTERVAL_SECONDS = 5;
1292
+ var DEFAULT_EXPIRES_IN_SECONDS = 600;
1293
+ var SLOW_DOWN_STEP_SECONDS = 5;
1294
+ var NETWORK_RETRIES = 3;
1295
+ var KEY_NAME_MAX_LENGTH = 64;
1296
+ var ERROR_MESSAGE_MAX_LENGTH = 200;
1297
+ var BALANCE_NOTE_MAX_LENGTH = 200;
1298
+ var REQUEST_TIMEOUT_MS = 2e4;
1299
+ var SIGN_IN_TITLE = "Sign in";
1300
+ var WAITING_MESSAGE = "Waiting for you to approve in the browser";
1301
+ var APPROVED_MESSAGE = "Approved";
1302
+ var NOT_APPROVED_MESSAGE = "Not approved";
1303
+ function sleep(ms) {
1304
+ return new Promise((resolve2) => {
1305
+ setTimeout(resolve2, ms);
1306
+ });
1307
+ }
1308
+ function keyName(host) {
1309
+ const machine = host.trim();
1310
+ return (machine ? `cli \xB7 ${machine}` : "cli").slice(0, KEY_NAME_MAX_LENGTH);
1311
+ }
1312
+ var SETUP_RUN = "the setup";
1313
+ function failureMessage(reason2, origin, message, run = SETUP_RUN) {
1314
+ switch (reason2) {
1315
+ case "network":
1316
+ return `Could not reach ${origin}. Check your connection and run ${run} again.`;
1317
+ case "expired":
1318
+ return `The code expired before it was approved. Run ${run} again.`;
1319
+ case "denied":
1320
+ return "The connection was denied in the browser.";
1321
+ case "rejected":
1322
+ return message ?? `${origin} refused the connection request. Run ${run} again.`;
1323
+ }
1324
+ }
1325
+ function readString(value) {
1326
+ return typeof value === "string" ? value : "";
1327
+ }
1328
+ function readPositive(value) {
1329
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
1330
+ }
1331
+ var CONTROL_CHARACTERS2 = /[\u0000-\u001f\u007f]/g;
1332
+ function readable(text, maxLength) {
1333
+ const cleaned = text.replace(CONTROL_CHARACTERS2, "");
1334
+ return cleaned.trim() ? cleaned.slice(0, maxLength) : void 0;
1335
+ }
1336
+ function readErrorMessage(data) {
1337
+ const error = data.error;
1338
+ if (typeof error !== "object" || error === null) return void 0;
1339
+ const message = error.message;
1340
+ if (typeof message !== "string") return void 0;
1341
+ return readable(message, ERROR_MESSAGE_MAX_LENGTH);
1342
+ }
1343
+ function readBalanceNote(data, origin) {
1344
+ const note = typeof data.balanceNote === "string" ? readable(data.balanceNote, BALANCE_NOTE_MAX_LENGTH) : void 0;
1345
+ return note === void 0 ? void 0 : `${note} Add credit: ${origin}${BILLING_PATH}`;
1346
+ }
1347
+ function parseJsonBody(text) {
1348
+ if (!text) return {};
1349
+ try {
1350
+ const value = JSON.parse(text);
1351
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
1352
+ } catch {
1353
+ return {};
1354
+ }
1355
+ }
1356
+ async function postJson(fetchImpl, url, body, accessToken) {
1357
+ const controller = new AbortController();
1358
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
1359
+ const headers = { "content-type": "application/json", accept: "application/json" };
1360
+ if (accessToken) headers.authorization = `Bearer ${accessToken}`;
1361
+ try {
1362
+ const response = await fetchImpl(url, {
1363
+ method: "POST",
1364
+ headers,
1365
+ body: JSON.stringify(body),
1366
+ signal: controller.signal
1367
+ });
1368
+ return { status: response.status, data: parseJsonBody(await response.text()) };
1369
+ } finally {
1370
+ clearTimeout(timer);
1371
+ }
1372
+ }
1373
+ function absoluteUrl(value, origin) {
1374
+ if (!value) return null;
1375
+ try {
1376
+ return new URL(value, `${origin}/`).toString();
1377
+ } catch {
1378
+ return null;
1379
+ }
1380
+ }
1381
+ function withUserCode(uri, userCode) {
1382
+ try {
1383
+ const url = new URL(uri);
1384
+ url.searchParams.set("user_code", userCode);
1385
+ return url.toString();
1386
+ } catch {
1387
+ return uri;
1388
+ }
1389
+ }
1390
+ async function requestDeviceCode(origin, fetchImpl) {
1391
+ let result;
1392
+ try {
1393
+ result = await postJson(fetchImpl, `${origin}${DEVICE_CODE_PATH}`, { client_id: CLIENT_ID });
1394
+ } catch {
1395
+ return { ok: false, reason: "network" };
1396
+ }
1397
+ if (result.status !== 200) return { ok: false, reason: "rejected" };
1398
+ const deviceCode = readString(result.data.device_code);
1399
+ const userCode = readString(result.data.user_code);
1400
+ if (!deviceCode || !userCode) return { ok: false, reason: "rejected" };
1401
+ const verificationUri = absoluteUrl(readString(result.data.verification_uri), origin) ?? `${origin}${VERIFICATION_PATH}`;
1402
+ const verificationUriComplete = absoluteUrl(readString(result.data.verification_uri_complete), origin) ?? withUserCode(verificationUri, userCode);
1403
+ return {
1404
+ ok: true,
1405
+ code: {
1406
+ deviceCode,
1407
+ userCode,
1408
+ verificationUri,
1409
+ verificationUriComplete,
1410
+ expiresIn: readPositive(result.data.expires_in) ?? DEFAULT_EXPIRES_IN_SECONDS,
1411
+ interval: readPositive(result.data.interval) ?? DEFAULT_INTERVAL_SECONDS
1412
+ }
1413
+ };
1414
+ }
1415
+ function classifyToken(result) {
1416
+ if (result.status === 200) {
1417
+ const accessToken = readString(result.data.access_token);
1418
+ return accessToken ? { kind: "token", accessToken } : { kind: "transient" };
1419
+ }
1420
+ if (result.status !== 400) return { kind: "transient" };
1421
+ switch (readString(result.data.error)) {
1422
+ case "authorization_pending":
1423
+ return { kind: "pending" };
1424
+ case "slow_down":
1425
+ return { kind: "slow_down" };
1426
+ case "expired_token":
1427
+ return { kind: "failed", reason: "expired" };
1428
+ case "access_denied":
1429
+ return { kind: "failed", reason: "denied" };
1430
+ case "":
1431
+ return { kind: "transient" };
1432
+ default:
1433
+ return { kind: "failed", reason: "rejected" };
1434
+ }
1435
+ }
1436
+ async function pollForToken(origin, deviceCode, intervalSeconds, expiresInSeconds, deps) {
1437
+ const url = `${origin}${DEVICE_TOKEN_PATH}`;
1438
+ const body = { grant_type: GRANT_TYPE, device_code: deviceCode, client_id: CLIENT_ID };
1439
+ const deadline = deps.now() + Math.max(expiresInSeconds, 0) * 1e3;
1440
+ let waitMs = Math.max(intervalSeconds, 0) * 1e3;
1441
+ let failures = 0;
1442
+ while (deps.now() < deadline) {
1443
+ await deps.sleep(waitMs);
1444
+ if (deps.now() >= deadline) break;
1445
+ let outcome;
1446
+ try {
1447
+ outcome = classifyToken(await postJson(deps.fetch, url, body));
1448
+ } catch {
1449
+ outcome = { kind: "transient" };
1450
+ }
1451
+ if (outcome.kind === "token") return { ok: true, accessToken: outcome.accessToken };
1452
+ if (outcome.kind === "failed") return { ok: false, reason: outcome.reason };
1453
+ if (outcome.kind === "transient") {
1454
+ failures += 1;
1455
+ if (failures > NETWORK_RETRIES) return { ok: false, reason: "network" };
1456
+ continue;
1457
+ }
1458
+ failures = 0;
1459
+ if (outcome.kind === "slow_down") waitMs += SLOW_DOWN_STEP_SECONDS * 1e3;
1460
+ }
1461
+ return { ok: false, reason: "expired" };
1462
+ }
1463
+ async function mintKey(origin, accessToken, name, fetchImpl) {
1464
+ let result;
1465
+ try {
1466
+ result = await postJson(fetchImpl, `${origin}${CLI_KEY_PATH}`, { name }, accessToken);
1467
+ } catch {
1468
+ return { ok: false, reason: "network" };
1469
+ }
1470
+ if (result.status !== 200) return { ok: false, reason: "rejected", message: readErrorMessage(result.data) };
1471
+ const key = readString(result.data.secret);
1472
+ if (!key) return { ok: false, reason: "rejected" };
1473
+ const balanceNote = readBalanceNote(result.data, origin);
1474
+ return balanceNote === void 0 ? { ok: true, key } : { ok: true, key, balanceNote };
1475
+ }
1476
+ async function deviceLogin(deps) {
1477
+ const requested = await requestDeviceCode(deps.origin, deps.fetch);
1478
+ if (!requested.ok) return requested;
1479
+ const { code } = requested;
1480
+ deps.log.note(`Open ${code.verificationUriComplete}
1481
+ Code: ${code.userCode}`, SIGN_IN_TITLE);
1482
+ deps.open(code.verificationUriComplete);
1483
+ deps.log.start(WAITING_MESSAGE);
1484
+ let token;
1485
+ try {
1486
+ token = await pollForToken(deps.origin, code.deviceCode, code.interval, code.expiresIn, {
1487
+ fetch: deps.fetch,
1488
+ sleep: deps.sleep,
1489
+ now: deps.now ?? Date.now
1490
+ });
1491
+ } catch {
1492
+ token = { ok: false, reason: "network" };
1493
+ }
1494
+ deps.log.stop(token.ok ? APPROVED_MESSAGE : NOT_APPROVED_MESSAGE);
1495
+ if (!token.ok) return token;
1496
+ return mintKey(deps.origin, token.accessToken, keyName(deps.hostname()), deps.fetch);
1497
+ }
1498
+
1499
+ // cli/src/sign-in.ts
1500
+ import { hostname } from "node:os";
1501
+
1502
+ // cli/src/open-browser.ts
1503
+ import { spawn } from "node:child_process";
1504
+ function browserCommand(platform, url) {
1505
+ if (platform === "darwin") return { command: "open", args: [url] };
1506
+ if (platform === "win32") return { command: "cmd", args: ["/c", "start", "", url] };
1507
+ return { command: "xdg-open", args: [url] };
1508
+ }
1509
+ function openBrowser(url, platform = process.platform, spawnImpl = spawn) {
1510
+ const { command, args } = browserCommand(platform, url);
1511
+ try {
1512
+ const child = spawnImpl(command, args, { detached: true, stdio: "ignore" });
1513
+ child.on("error", () => void 0);
1514
+ child.unref();
1515
+ } catch {
1516
+ return;
1517
+ }
1518
+ }
1519
+
1520
+ // cli/src/sign-in.ts
1521
+ function signIn(origin) {
1522
+ const waiting = Y2();
1523
+ return deviceLogin({
1524
+ origin,
1525
+ fetch: (url, init) => fetch(url, init),
1526
+ sleep,
1527
+ open: openBrowser,
1528
+ hostname,
1529
+ log: {
1530
+ note: Me,
1531
+ start: (message) => waiting.start(message),
1532
+ stop: (message) => waiting.stop(message)
1533
+ }
1534
+ });
1535
+ }
1536
+
1537
+ // cli/src/commands/login.ts
1538
+ var LOGIN_INTRO = "unrestricted.sh login";
1539
+ var LOGIN_RUN = "unrestricted login";
1540
+ function loginOutro(path) {
1541
+ return `Signed in. The key is saved in ${path}`;
1542
+ }
1543
+ async function login(context) {
1544
+ let pending;
1545
+ try {
1546
+ pending = readConfig(context.env, context.machine);
1547
+ } catch (error) {
1548
+ xe(reason(error));
1549
+ return FAILED;
1550
+ }
1551
+ Ie(LOGIN_INTRO);
1552
+ const signedIn = await signIn(pending.origin);
1553
+ if (!signedIn.ok) {
1554
+ xe(failureMessage(signedIn.reason, pending.origin, signedIn.message, LOGIN_RUN));
1555
+ return FAILED;
1556
+ }
1557
+ let path;
1558
+ try {
1559
+ path = saveCredentials(pending.configHome, { key: signedIn.key, origin: pending.origin });
1560
+ } catch (error) {
1561
+ xe(`could not save the key: ${reason(error)}`);
1562
+ return FAILED;
1563
+ }
1564
+ if (signedIn.balanceNote) M2.info(signedIn.balanceNote);
1565
+ Se(loginOutro(path));
1566
+ return { code: 0 };
1567
+ }
1568
+
1569
+ // cli/src/commands/logout.ts
1570
+ function logoutLines(removed, path, origin) {
1571
+ const revoke = `${origin}/keys`;
1572
+ if (!removed) return ["No key is stored on this machine.", `Keys are revoked at ${revoke}`];
1573
+ return [`Removed the stored key from ${path}.`, `The key keeps working until you revoke it at ${revoke}`];
1574
+ }
1575
+ async function logout(context) {
1576
+ let pending;
1577
+ try {
1578
+ pending = readConfig(context.env, context.machine);
1579
+ } catch (error) {
1580
+ context.warn(`${reason(error)}
1581
+ `);
1582
+ return FAILED;
1583
+ }
1584
+ const removed = deleteCredentials(pending.configHome);
1585
+ context.write(`${logoutLines(removed, credentialsPath(pending.configHome), pending.origin).join("\n")}
1586
+ `);
1587
+ return { code: 0 };
1588
+ }
1589
+
1590
+ // cli/src/commands/models.ts
1591
+ var HEADER = ["ID", "NAME", "CONTEXT", "INPUT/1M", "CACHED/1M", "OUTPUT/1M"];
1592
+ var NUMBER_COLUMNS = /* @__PURE__ */ new Set([2, 3, 4, 5]);
1593
+ var NO_PRICE = "-";
1594
+ function price(usd) {
1595
+ return usd === void 0 ? NO_PRICE : priceLabel(usd);
1596
+ }
1597
+ function modelTable(catalog) {
1598
+ const rows = catalog.map((model) => [
1599
+ model.id,
1600
+ model.name,
1601
+ contextLabel(model.context),
1602
+ price(model.pricing?.input),
1603
+ price(model.pricing?.cachedInput),
1604
+ price(model.pricing?.output)
1605
+ ]);
1606
+ return table([HEADER, ...rows], NUMBER_COLUMNS);
1607
+ }
1608
+ async function models(context) {
1609
+ let pending;
1610
+ try {
1611
+ pending = readConfig(context.env, context.machine);
1612
+ } catch (error) {
1613
+ context.warn(`${reason(error)}
1614
+ `);
1615
+ return FAILED;
1616
+ }
1617
+ let catalog;
1618
+ try {
1619
+ catalog = await fetchModelCatalog(pending.base);
1620
+ } catch (error) {
1621
+ context.warn(`${reason(error)}
1622
+ `);
1623
+ return FAILED;
1624
+ }
1625
+ if (catalog.length === 0) {
1626
+ context.warn(`${pending.base}/models listed no models.
1627
+ `);
1628
+ return FAILED;
1629
+ }
1630
+ context.write(`${modelTable(catalog)}
1631
+ `);
1632
+ return { code: 0, listed: catalog.map((model) => model.id) };
1633
+ }
1634
+
1635
+ // cli/src/auto-update.ts
1636
+ import { createHash } from "node:crypto";
1637
+ import { lstatSync, mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
1638
+ import { dirname } from "node:path";
1639
+
1640
+ // cli/src/templates/opencode-plugin.ts?raw
1641
+ var opencode_plugin_default = 'type ListedModel = {\n id: string;\n name: string;\n context_length: number;\n max_output_tokens: number;\n};\n\ntype ModelDraft = {\n name: string;\n limit: { context: number; output: number };\n capabilities: { input: string[]; output: string[] };\n};\n\ntype ModelEditor = {\n update: (providerID: string, modelID: string, update: (model: ModelDraft) => void) => void;\n};\n\ntype PluginContext = {\n model: {\n transform: (callback: (editor: ModelEditor) => void) => Promise<unknown>;\n reload: () => Promise<unknown>;\n };\n storage: {\n get: (key: string) => Promise<unknown>;\n set: (key: string, value: ListedModel[]) => Promise<unknown>;\n };\n};\n\ntype Catalog = { models: ListedModel[] };\n\nconst ORIGIN = "https://api.unrestricted.sh";\nconst MODELS_URL = `${ORIGIN}/v1/models`;\nconst PROVIDER_ID = "unrestricted";\nconst STORAGE_KEY = "models";\nconst TIMEOUT_MS = 5000;\nconst MAX_MODELS = 50;\nconst MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\nconst MODEL_NAME = /^[\\p{L}\\p{N}._+()/-]+(?: [\\p{L}\\p{N}._+()/-]+)*$/u;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\n\nfunction isLimit(value: unknown): value is number {\n return typeof value === "number" && Number.isSafeInteger(value) && value > 0;\n}\n\nfunction readModel(value: unknown): ListedModel | null {\n if (!isRecord(value)) return null;\n const { id, name, context_length: context, max_output_tokens: output } = value;\n if (typeof id !== "string" || !MODEL_ID.test(id)) return null;\n if (typeof name !== "string" || !MODEL_NAME.test(name)) return null;\n if (!isLimit(context) || !isLimit(output)) return null;\n return { id, name, context_length: context, max_output_tokens: output };\n}\n\nfunction readModels(entries: unknown): ListedModel[] {\n const models: ListedModel[] = [];\n if (!Array.isArray(entries)) return models;\n for (const entry of entries) {\n if (models.length === MAX_MODELS) break;\n const model = readModel(entry);\n if (model !== null && !models.some((known) => known.id === model.id)) models.push(model);\n }\n return models;\n}\n\nfunction sameModels(left: readonly ListedModel[], right: readonly ListedModel[]): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nasync function fetchModels(signal: AbortSignal): Promise<ListedModel[]> {\n const controller = new AbortController();\n const abort = () => controller.abort();\n const timer = setTimeout(abort, TIMEOUT_MS);\n signal.addEventListener("abort", abort);\n try {\n const response = await fetch(MODELS_URL, {\n headers: { accept: "application/json" },\n redirect: "error",\n signal: controller.signal,\n });\n if (!response.ok) return [];\n const body: unknown = await response.json();\n return readModels(isRecord(body) ? body.data : undefined);\n } catch {\n return [];\n } finally {\n clearTimeout(timer);\n signal.removeEventListener("abort", abort);\n }\n}\n\nasync function cachedModels(context: PluginContext): Promise<ListedModel[]> {\n try {\n return readModels(await context.storage.get(STORAGE_KEY));\n } catch {\n return [];\n }\n}\n\nfunction addModels(editor: ModelEditor, models: readonly ListedModel[]): void {\n try {\n for (const listed of models) {\n editor.update(PROVIDER_ID, listed.id, (model) => {\n model.name = listed.name;\n model.limit = { ...model.limit, context: listed.context_length, output: listed.max_output_tokens };\n model.capabilities = { ...model.capabilities, input: ["text"], output: ["text"] };\n });\n }\n } catch {\n return;\n }\n}\n\nasync function save(context: PluginContext, models: ListedModel[]): Promise<void> {\n try {\n await context.storage.set(STORAGE_KEY, models);\n } catch {\n return;\n }\n}\n\nasync function reload(context: PluginContext): Promise<void> {\n try {\n await context.model.reload();\n } catch {\n return;\n }\n}\n\nasync function refresh(context: PluginContext, catalog: Catalog, signal: AbortSignal): Promise<void> {\n const models = await fetchModels(signal);\n if (signal.aborted || models.length === 0 || sameModels(models, catalog.models)) return;\n catalog.models = models;\n await save(context, models);\n if (!signal.aborted) await reload(context);\n}\n\nasync function setup(context: PluginContext): Promise<() => void> {\n const controller = new AbortController();\n const stop = () => controller.abort();\n const catalog: Catalog = { models: await cachedModels(context) };\n try {\n await context.model.transform((editor) => addModels(editor, catalog.models));\n } catch {\n return stop;\n }\n refresh(context, catalog, controller.signal).catch(stop);\n return stop;\n}\n\nconst plugin = { id: "unrestricted", setup };\n\nexport default plugin;\n';
1642
+
1643
+ // cli/src/templates/pi-extension.ts?raw
1644
+ var pi_extension_default = 'type ListedModel = {\n id: string;\n name: string;\n context_length: number;\n max_output_tokens: number;\n};\n\ntype ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high";\n\ntype PiModel = {\n id: string;\n name: string;\n baseUrl: string;\n reasoning: boolean;\n thinkingLevelMap: Record<ThinkingLevel, string | null>;\n input: string[];\n cost: { input: number; output: number; cacheRead: number; cacheWrite: number };\n contextWindow: number;\n maxTokens: number;\n};\n\ntype RefreshContext = {\n allowNetwork?: boolean;\n baseUrl?: unknown;\n signal?: AbortSignal;\n stored?: unknown;\n publish?: (publication: { persist: { models: ListedModel[]; checkedAt: number } }) => Promise<unknown>;\n};\n\ntype ProviderConfig = {\n name: string;\n api: string;\n refreshModels: (context: RefreshContext) => Promise<PiModel[] | undefined>;\n};\n\ntype ExtensionApi = {\n registerProvider: (name: string, config: ProviderConfig) => void;\n};\n\nconst ORIGIN = "https://api.unrestricted.sh";\nconst MODELS_URL = `${ORIGIN}/v1/models`;\nconst PROVIDER_NAME = "unrestricted.sh";\nconst API = "openai-completions";\nconst TIMEOUT_MS = 5000;\nconst MAX_MODELS = 50;\nconst MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\nconst MODEL_NAME = /^[\\p{L}\\p{N}._+()/-]+(?: [\\p{L}\\p{N}._+()/-]+)*$/u;\nconst THINKING_LEVEL_MAP: Record<ThinkingLevel, string | null> = {\n off: "none",\n minimal: null,\n low: "low",\n medium: "medium",\n high: "xhigh",\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\n\nfunction isLimit(value: unknown): value is number {\n return typeof value === "number" && Number.isSafeInteger(value) && value > 0;\n}\n\nfunction readModel(value: unknown): ListedModel | null {\n if (!isRecord(value)) return null;\n const { id, name, context_length: context, max_output_tokens: output } = value;\n if (typeof id !== "string" || !MODEL_ID.test(id)) return null;\n if (typeof name !== "string" || !MODEL_NAME.test(name)) return null;\n if (!isLimit(context) || !isLimit(output)) return null;\n return { id, name, context_length: context, max_output_tokens: output };\n}\n\nfunction readModels(entries: unknown): ListedModel[] {\n const models: ListedModel[] = [];\n if (!Array.isArray(entries)) return models;\n for (const entry of entries) {\n if (models.length === MAX_MODELS) break;\n const model = readModel(entry);\n if (model !== null && !models.some((known) => known.id === model.id)) models.push(model);\n }\n return models;\n}\n\nfunction sameModels(left: readonly ListedModel[], right: readonly ListedModel[]): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nasync function fetchModels(signal: AbortSignal | undefined): Promise<ListedModel[]> {\n if (signal?.aborted) return [];\n const controller = new AbortController();\n const abort = () => controller.abort();\n const timer = setTimeout(abort, TIMEOUT_MS);\n signal?.addEventListener("abort", abort);\n try {\n const response = await fetch(MODELS_URL, {\n headers: { accept: "application/json" },\n redirect: "error",\n signal: controller.signal,\n });\n if (!response.ok) return [];\n const body: unknown = await response.json();\n return readModels(isRecord(body) ? body.data : undefined);\n } catch {\n return [];\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener("abort", abort);\n }\n}\n\nfunction piModel(model: ListedModel, baseUrl: string): PiModel {\n return {\n id: model.id,\n name: model.name,\n baseUrl,\n reasoning: true,\n thinkingLevelMap: { ...THINKING_LEVEL_MAP },\n input: ["text"],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: model.context_length,\n maxTokens: model.max_output_tokens,\n };\n}\n\nasync function persist(context: RefreshContext, models: ListedModel[]): Promise<void> {\n try {\n await context.publish?.({ persist: { models, checkedAt: Date.now() } });\n } catch {\n return;\n }\n}\n\nasync function refreshModels(context: RefreshContext): Promise<PiModel[] | undefined> {\n try {\n const { baseUrl } = context;\n if (typeof baseUrl !== "string" || baseUrl === "") return undefined;\n const stored = readModels(isRecord(context.stored) ? context.stored.models : undefined);\n const fetched = context.allowNetwork === true ? await fetchModels(context.signal) : [];\n if (fetched.length > 0 && !sameModels(fetched, stored)) await persist(context, fetched);\n const models = fetched.length > 0 ? fetched : stored;\n return models.length > 0 ? models.map((model) => piModel(model, baseUrl)) : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport default function unrestricted(pi: ExtensionApi): void {\n try {\n pi.registerProvider("unrestricted", { name: PROVIDER_NAME, api: API, refreshModels });\n } catch {\n return;\n }\n}\n';
1645
+
1646
+ // cli/src/tool-version.ts
1647
+ import { spawnSync } from "node:child_process";
1648
+
1649
+ // cli/src/detect.ts
1650
+ import { accessSync, constants, readdirSync, statSync } from "node:fs";
1651
+ import { join as join2 } from "node:path";
1652
+ var DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD";
1653
+ function isFile(path) {
1654
+ try {
1655
+ return statSync(path).isFile();
1656
+ } catch {
1657
+ return false;
1658
+ }
1659
+ }
1660
+ function isDirectory(path) {
1661
+ try {
1662
+ return statSync(path).isDirectory();
1663
+ } catch {
1664
+ return false;
1665
+ }
1666
+ }
1667
+ function windowsVariable(env, name) {
1668
+ const key = Object.keys(env).find((candidate) => candidate.toUpperCase() === name);
1669
+ return key === void 0 ? void 0 : env[key];
1670
+ }
1671
+ function isExecutable(path) {
1672
+ if (!isFile(path)) return false;
1673
+ try {
1674
+ accessSync(path, constants.X_OK);
1675
+ return true;
1676
+ } catch {
1677
+ return false;
1678
+ }
1679
+ }
1680
+ function hasWindowsCommand(dir, names) {
1681
+ let entries;
1682
+ try {
1683
+ entries = readdirSync(dir);
1684
+ } catch {
1685
+ return false;
1686
+ }
1687
+ return entries.some((entry) => names.has(entry.toLowerCase()) && isFile(join2(dir, entry)));
1688
+ }
1689
+ function searchPath(value, platform) {
1690
+ const { delimiter } = pathsFor(platform);
1691
+ return (value ?? "").split(delimiter).map((part) => platform === WINDOWS_PLATFORM ? part.trim().replace(/^"(.*)"$/, "$1") : part).filter(Boolean);
1692
+ }
1693
+ function windowsExtensions(env) {
1694
+ return (windowsVariable(env, "PATHEXT") || DEFAULT_PATHEXT).split(";").map((extension) => extension.trim()).filter((extension) => extension.startsWith("."));
1695
+ }
1696
+ function onPath(name, env = process.env, platform = process.platform) {
1697
+ if (platform !== WINDOWS_PLATFORM) return searchPath(env.PATH, platform).some((dir) => isExecutable(join2(dir, name)));
1698
+ const extensions = windowsExtensions(env);
1699
+ const commands = new Set([name, ...extensions.map((extension) => `${name}${extension}`)].map((command) => command.toLowerCase()));
1700
+ return searchPath(windowsVariable(env, "PATH"), platform).some((dir) => hasWindowsCommand(dir, commands));
1701
+ }
1702
+ function windowsCommandIn(dir, name, extensions) {
1703
+ let entries;
1704
+ try {
1705
+ entries = readdirSync(dir);
1706
+ } catch {
1707
+ return null;
1708
+ }
1709
+ for (const extension of extensions) {
1710
+ const wanted = `${name}${extension}`.toLowerCase();
1711
+ const entry = entries.find((candidate) => candidate.toLowerCase() === wanted);
1712
+ if (entry !== void 0 && isFile(join2(dir, entry))) return join2(dir, entry);
1713
+ }
1714
+ return null;
1715
+ }
1716
+ function findCommand(name, env = process.env, platform = process.platform) {
1717
+ if (platform !== WINDOWS_PLATFORM) {
1718
+ const dir = searchPath(env.PATH, platform).find((candidate) => isExecutable(join2(candidate, name)));
1719
+ return dir === void 0 ? null : join2(dir, name);
1720
+ }
1721
+ const extensions = windowsExtensions(env);
1722
+ for (const dir of searchPath(windowsVariable(env, "PATH"), platform)) {
1723
+ const command = windowsCommandIn(dir, name, extensions);
1724
+ if (command !== null) return command;
1725
+ }
1726
+ return null;
1727
+ }
1728
+ function detect(tool, config, env = process.env) {
1729
+ const paths = toolPaths(config);
1730
+ const found = (name) => onPath(name, env, config.platform);
1731
+ switch (tool) {
1732
+ case "opencode":
1733
+ return found("opencode") || isDirectory(paths.opencodeDir);
1734
+ case "codex":
1735
+ return found("codex") || isDirectory(paths.codexDir);
1736
+ case "aider":
1737
+ return found("aider") || isFile(paths.aiderConfig);
1738
+ case "continue":
1739
+ return isDirectory(paths.continueDir);
1740
+ case "crush":
1741
+ return found("crush") || isDirectory(paths.crushDir);
1742
+ case "pi":
1743
+ return found("pi") || isDirectory(paths.piAgentDir);
1744
+ case "claude":
1745
+ return found("claude") || isDirectory(paths.claudeDir);
1746
+ }
1747
+ }
1748
+ function detectTools(config, env = process.env) {
1749
+ return OFFERED_TOOLS.filter((tool) => detect(tool, config, env));
1750
+ }
1751
+
1752
+ // cli/src/tool-version.ts
1753
+ var VERSION_TIMEOUT_MS = 1e4;
1754
+ var VERSION_FLAG = "--version";
1755
+ var VERSION_NUMBER = /(\d+)\.(\d+)\.(\d+)/;
1756
+ var WINDOWS_PROGRAMS = /* @__PURE__ */ new Set([".exe", ".com"]);
1757
+ var WINDOWS_SCRIPTS = /* @__PURE__ */ new Set([".cmd", ".bat"]);
1758
+ var WINDOWS_SHELL = "cmd.exe";
1759
+ function parseVersion(output) {
1760
+ const [firstLine = ""] = output.trim().split(/\r?\n/);
1761
+ const match = VERSION_NUMBER.exec(firstLine);
1762
+ if (match === null) return null;
1763
+ const [major, minor, patch] = [match[1], match[2], match[3]].map(Number);
1764
+ return [major, minor, patch].every(Number.isSafeInteger) ? { major, minor, patch } : null;
1765
+ }
1766
+ function isAtLeast(version2, minimum) {
1767
+ if (version2.major !== minimum.major) return version2.major > minimum.major;
1768
+ if (version2.minor !== minimum.minor) return version2.minor > minimum.minor;
1769
+ return version2.patch >= minimum.patch;
1770
+ }
1771
+ function versionLabel(version2) {
1772
+ return `${version2.major}.${version2.minor}.${version2.patch}`;
1773
+ }
1774
+ function versionCommand(file, env, platform) {
1775
+ if (platform !== WINDOWS_PLATFORM) return { file, args: [VERSION_FLAG], verbatim: false };
1776
+ const extension = pathsFor(platform).extname(file).toLowerCase();
1777
+ if (WINDOWS_PROGRAMS.has(extension)) return { file, args: [VERSION_FLAG], verbatim: false };
1778
+ if (!WINDOWS_SCRIPTS.has(extension)) return null;
1779
+ const shell = windowsVariable(env, "COMSPEC") || WINDOWS_SHELL;
1780
+ return { file: shell, args: ["/d", "/s", "/c", `""${file}" ${VERSION_FLAG}"`], verbatim: true };
1781
+ }
1782
+ function readVersion(command, env, platform) {
1783
+ const file = findCommand(command, env, platform);
1784
+ if (file === null) return null;
1785
+ const run = versionCommand(file, env, platform);
1786
+ if (run === null) return null;
1787
+ const result = spawnSync(run.file, run.args, {
1788
+ env,
1789
+ encoding: "utf8",
1790
+ timeout: VERSION_TIMEOUT_MS,
1791
+ stdio: ["ignore", "pipe", "ignore"],
1792
+ windowsHide: true,
1793
+ windowsVerbatimArguments: run.verbatim
1794
+ });
1795
+ if (result.error !== void 0 || result.status !== 0 || typeof result.stdout !== "string") return null;
1796
+ return parseVersion(result.stdout);
1797
+ }
1798
+ function versionReader(env, platform) {
1799
+ return (command) => readVersion(command, env, platform);
1800
+ }
1801
+
1802
+ // cli/src/auto-update.ts
1803
+ var OPENCODE_PLUGIN_MARKER = 'const plugin = { id: "unrestricted", setup };';
1804
+ var PI_EXTENSION_MARKER = 'pi.registerProvider("unrestricted", { name: PROVIDER_NAME, api: API, refreshModels });';
1805
+ var AUTO_UPDATE_FILES = {
1806
+ opencode: {
1807
+ label: "OpenCode plugin",
1808
+ command: "opencode",
1809
+ minimum: { major: 2, minor: 0, patch: 0 },
1810
+ marker: OPENCODE_PLUGIN_MARKER,
1811
+ source: opencode_plugin_default,
1812
+ path: (paths) => paths.opencodePlugin
1813
+ },
1814
+ pi: {
1815
+ label: "Pi extension",
1816
+ command: "pi",
1817
+ minimum: { major: 1, minor: 4, patch: 0 },
1818
+ marker: PI_EXTENSION_MARKER,
1819
+ source: pi_extension_default,
1820
+ path: (paths) => paths.piExtension
1821
+ }
1822
+ };
1823
+ function sha256(text) {
1824
+ return createHash("sha256").update(text).digest("hex");
1825
+ }
1826
+ function isOwnFile(text, marker) {
1827
+ return text.split(/\r?\n/).some((line) => line.trim() === marker);
1828
+ }
1829
+ function isMissing(error) {
1830
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
1831
+ }
1832
+ function readExisting(path, marker) {
1833
+ let stats;
1834
+ try {
1835
+ stats = lstatSync(path);
1836
+ } catch (error) {
1837
+ if (isMissing(error)) return { kind: "missing" };
1838
+ throw error;
1839
+ }
1840
+ if (!stats.isFile()) return { kind: "foreign" };
1841
+ const text = readFileSync3(path, "utf8");
1842
+ return isOwnFile(text, marker) ? { kind: "ours", text } : { kind: "foreign" };
1843
+ }
1844
+ function writeAtomically(path, text) {
1845
+ mkdirSync2(dirname(path), { recursive: true });
1846
+ const pending = `${path}.${process.pid}.tmp`;
1847
+ try {
1848
+ writeFileSync3(pending, text);
1849
+ renameSync2(pending, path);
1850
+ } finally {
1851
+ rmSync2(pending, { force: true });
1852
+ }
1853
+ }
1854
+ function writeAutoUpdateFile(tool, config, version2) {
1855
+ if (version2 === null) return { status: "unknown" };
1856
+ const file = AUTO_UPDATE_FILES[tool];
1857
+ const path = file.path(toolPaths(config));
1858
+ const existing = readExisting(path, file.marker);
1859
+ if (!isAtLeast(version2, file.minimum)) {
1860
+ if (existing.kind !== "ours") return { status: "unsupported" };
1861
+ rmSync2(path, { force: true });
1862
+ return { status: "removed", path };
1863
+ }
1864
+ if (existing.kind === "foreign") return { status: "foreign", path };
1865
+ const hash = sha256(file.source);
1866
+ if (existing.kind === "ours" && sha256(existing.text) === hash) return { status: "current", path, sha256: hash };
1867
+ writeAtomically(path, file.source);
1868
+ return { status: "written", path, sha256: hash };
1869
+ }
1870
+ function installAutoUpdate(tool, config, versionOf) {
1871
+ const file = AUTO_UPDATE_FILES[tool];
1872
+ try {
1873
+ return writeAutoUpdateFile(tool, config, versionOf(file.command));
1874
+ } catch (error) {
1875
+ return { status: "failed", path: file.path(toolPaths(config)), message: error instanceof Error ? error.message : String(error) };
1876
+ }
1877
+ }
1878
+ function autoUpdateMessage(tool, result) {
1879
+ const file = AUTO_UPDATE_FILES[tool];
1880
+ switch (result.status) {
1881
+ case "written":
1882
+ case "current":
1883
+ return { level: "success", text: `${file.label} \xB7 ${result.path}` };
1884
+ case "foreign":
1885
+ return {
1886
+ level: "warn",
1887
+ text: `${result.path} is not from unrestricted.sh, so it was left as it is; new models reach ${TOOL_LABELS[tool]} with "unrestricted update"`
1888
+ };
1889
+ case "removed":
1890
+ return {
1891
+ level: "info",
1892
+ text: `Removed ${result.path}: the ${file.label} needs ${TOOL_LABELS[tool]} ${versionLabel(file.minimum)} or later`
1893
+ };
1894
+ case "failed":
1895
+ return { level: "warn", text: `could not write ${result.path}: ${result.message}` };
1896
+ case "unsupported":
1897
+ case "unknown":
1898
+ return null;
1899
+ }
1900
+ }
1901
+
1902
+ // cli/src/writers/aider.ts
1903
+ import { existsSync as existsSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "node:fs";
1904
+ function write(config) {
1905
+ const file = toolPaths(config).aiderConfig;
1906
+ if (!existsSync3(file)) writeFileSync4(file, "");
1907
+ const raw = readFileSync4(file, "utf8");
1908
+ const content = toLf(raw);
1909
+ const existing = content === "" ? [] : (content.endsWith("\n") ? content.slice(0, -1) : content).split("\n");
1910
+ const kept = existing.filter((line) => !/^(openai-api-base|openai-api-key|model):/.test(line));
1911
+ kept.push(`openai-api-base: ${config.base}`, `openai-api-key: ${config.key}`, `model: openai/${config.model}`);
1912
+ writeFileSync4(file, fromLf(`${kept.join("\n")}
1913
+ `, layoutOf(raw)));
1914
+ setMode(file, 384, config.platform);
1915
+ return { path: file, next: "aider" };
1916
+ }
1917
+
1918
+ // cli/src/writers/claude.ts
1919
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, writeFileSync as writeFileSync5 } from "node:fs";
1920
+ import { dirname as dirname2, resolve } from "node:path";
1921
+ function apiOrigin(base) {
1922
+ return base.replace(/\/v1$/, "");
1923
+ }
1924
+ function underHome(path, home) {
1925
+ return path.startsWith(`${home}/`) ? path.slice(home.length + 1) : "";
1926
+ }
1927
+ function displayPath(path, home) {
1928
+ const rest = underHome(path, home);
1929
+ return rest ? `~/${rest}` : path;
1930
+ }
1931
+ function shellPath(path, home) {
1932
+ const rest = underHome(path, home);
1933
+ return rest ? `"$HOME/${rest}"` : `"${path}"`;
1934
+ }
1935
+ function pathContains(dir, env, platform) {
1936
+ return (env.PATH ?? "").split(pathsFor(platform).delimiter).filter(Boolean).some((entry) => resolve(entry) === resolve(dir));
1937
+ }
1938
+ function isOurs(name, value, config) {
1939
+ if (typeof value !== "string") return false;
1940
+ switch (name) {
1941
+ case "ANTHROPIC_BASE_URL":
1942
+ return value === apiOrigin(config.base);
1943
+ case "ANTHROPIC_AUTH_TOKEN":
1944
+ return value.startsWith(KEY_PREFIX);
1945
+ case "ANTHROPIC_MODEL":
1946
+ case "ANTHROPIC_SMALL_FAST_MODEL":
1947
+ return isOwnModel(value, config);
1948
+ default:
1949
+ return false;
1950
+ }
1951
+ }
1952
+ function removeGlobalEnv(config) {
1953
+ const file = toolPaths(config).claudeGlobalSettings;
1954
+ if (!existsSync4(file)) return void 0;
1955
+ let document;
1956
+ try {
1957
+ document = readJsonDocument(file);
1958
+ } catch {
1959
+ return void 0;
1960
+ }
1961
+ const settings = document.value;
1962
+ const env = asObject(settings.env);
1963
+ const kept = {};
1964
+ let removed = 0;
1965
+ for (const [name, value] of Object.entries(env)) {
1966
+ if (isOurs(name, value, config)) removed += 1;
1967
+ else kept[name] = value;
1968
+ }
1969
+ if (removed === 0) return void 0;
1970
+ if (Object.keys(kept).length > 0) settings.env = kept;
1971
+ else delete settings.env;
1972
+ writeJsonDocument(file, settings, document.layout);
1973
+ return `Removed the old global unrestricted.sh env from ${displayPath(file, config.home)}`;
1974
+ }
1975
+ function write2(config, env = process.env) {
1976
+ const paths = toolPaths(config);
1977
+ const file = paths.claudeSessionSettings;
1978
+ mkdirSync3(dirname2(file), { recursive: true });
1979
+ const document = readJsonDocument(file);
1980
+ const settings = document.value;
1981
+ settings.env = {
1982
+ ...asObject(settings.env),
1983
+ ANTHROPIC_BASE_URL: apiOrigin(config.base),
1984
+ ANTHROPIC_AUTH_TOKEN: config.key,
1985
+ ANTHROPIC_MODEL: config.model,
1986
+ ANTHROPIC_SMALL_FAST_MODEL: config.model,
1987
+ CLAUDE_CODE_MAX_CONTEXT_TOKENS: String(config.context),
1988
+ CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT: "1"
1989
+ };
1990
+ settings.modelPicker = {
1991
+ options: [{ model: config.model, label: config.modelName, description: "unrestricted.sh" }],
1992
+ replaceBuiltInOptions: true
1993
+ };
1994
+ writeJsonDocument(file, settings, document.layout);
1995
+ setMode(file, 384, config.platform);
1996
+ const launcher = paths.claudeLauncher;
1997
+ const bin = paths.claudeLauncherDir;
1998
+ mkdirSync3(bin, { recursive: true });
1999
+ writeFileSync5(launcher, `#!/bin/sh
2000
+ exec claude --settings ${shellPath(file, config.home)} "$@"
2001
+ `);
2002
+ setMode(launcher, 493, config.platform);
2003
+ const hint = removeGlobalEnv(config);
2004
+ const next = pathContains(bin, env, config.platform) ? CLAUDE_LAUNCHER : `claude --settings ${displayPath(file, config.home)} (or add ~/.local/bin to PATH for ${CLAUDE_LAUNCHER})`;
2005
+ return hint ? { path: file, next, hint } : { path: file, next };
2006
+ }
2007
+
2008
+ // cli/src/writers/codex.ts
2009
+ import { existsSync as existsSync5, mkdirSync as mkdirSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync7 } from "node:fs";
2010
+
2011
+ // cli/src/env-file.ts
2012
+ import { appendFileSync, mkdirSync as mkdirSync4, readFileSync as readFileSync5, statSync as statSync2, writeFileSync as writeFileSync6 } from "node:fs";
2013
+ import { join as join3 } from "node:path";
2014
+ function isFile2(path) {
2015
+ try {
2016
+ return statSync2(path).isFile();
2017
+ } catch {
2018
+ return false;
2019
+ }
2020
+ }
2021
+ function writeEnvFile(config) {
2022
+ const dir = join3(config.configHome, "unrestricted");
2023
+ const file = join3(dir, "env");
2024
+ mkdirSync4(dir, { recursive: true });
2025
+ writeFileSync6(file, `export UNRESTRICTED_API_KEY=${config.key}
2026
+ `);
2027
+ setMode(file, 384, config.platform);
2028
+ for (const rc of [join3(config.home, ".zshrc"), join3(config.home, ".bashrc")]) {
2029
+ if (!isFile2(rc)) continue;
2030
+ const content = readFileSync5(rc, "utf8");
2031
+ if (content.includes(file)) continue;
2032
+ appendFileSync(rc, fromLf(`
2033
+ . "${file}"
2034
+ `, { eol: layoutOf(content).eol, bom: false }));
2035
+ }
2036
+ return file;
2037
+ }
2038
+
2039
+ // cli/src/writers/codex.ts
2040
+ function splitLines(content) {
2041
+ if (content === "") return [];
2042
+ return (content.endsWith("\n") ? content.slice(0, -1) : content).split("\n");
2043
+ }
2044
+ function applyTopLevelKeys(content, provider, model) {
2045
+ const providerLine = `model_provider = "${provider}"`;
2046
+ const modelLine2 = `model = "${model}"`;
2047
+ const lines = [];
2048
+ let inTable = false;
2049
+ let seenProvider = false;
2050
+ let seenModel = false;
2051
+ for (const line of splitLines(content)) {
2052
+ if (line.startsWith("[")) {
2053
+ if (!inTable) {
2054
+ if (!seenProvider) lines.push(providerLine);
2055
+ if (!seenModel) lines.push(modelLine2);
2056
+ seenProvider = true;
2057
+ seenModel = true;
2058
+ }
2059
+ inTable = true;
2060
+ lines.push(line);
2061
+ continue;
2062
+ }
2063
+ if (!inTable && /^model_provider[ \t]*=/.test(line)) {
2064
+ lines.push(providerLine);
2065
+ seenProvider = true;
2066
+ continue;
2067
+ }
2068
+ if (!inTable && /^model[ \t]*=/.test(line)) {
2069
+ lines.push(modelLine2);
2070
+ seenModel = true;
2071
+ continue;
2072
+ }
2073
+ lines.push(line);
2074
+ }
2075
+ if (!seenProvider) lines.push(providerLine);
2076
+ if (!seenModel) lines.push(modelLine2);
2077
+ return `${lines.join("\n")}
2078
+ `;
2079
+ }
2080
+ function write3(config) {
2081
+ const { codexDir: dir, codexConfig: file } = toolPaths(config);
2082
+ mkdirSync5(dir, { recursive: true });
2083
+ if (!existsSync5(file)) writeFileSync7(file, "");
2084
+ const raw = readFileSync6(file, "utf8");
2085
+ let content = toLf(raw);
2086
+ const header = new RegExp(`^\\[model_providers\\.${config.provider}\\]`, "m");
2087
+ if (!header.test(content)) {
2088
+ content += `
2089
+ [model_providers.${config.provider}]
2090
+ name = "unrestricted.sh"
2091
+ base_url = "${config.base}"
2092
+ env_key = "UNRESTRICTED_API_KEY"
2093
+ wire_api = "responses"
2094
+ `;
2095
+ }
2096
+ writeFileSync7(file, fromLf(applyTopLevelKeys(content, config.provider, config.model), layoutOf(raw)));
2097
+ setMode(file, 384, config.platform);
2098
+ const envFile = writeEnvFile(config);
2099
+ return { path: file, next: `open a new shell (or: . ${envFile}) then codex` };
2100
+ }
2101
+
2102
+ // cli/src/writers/continue.ts
2103
+ import { existsSync as existsSync6, mkdirSync as mkdirSync6, readFileSync as readFileSync7, writeFileSync as writeFileSync8 } from "node:fs";
2104
+ var ITEM_START = " - ";
2105
+ var ITEM_FIELD = /^ {4}([A-Za-z]+):\s*(.*?)\s*$/;
2106
+ function modelEntry(config, model) {
2107
+ return [
2108
+ ` - name: unrestricted.sh ${model.name}`,
2109
+ " provider: openai",
2110
+ ` apiBase: ${config.base}`,
2111
+ ` apiKey: ${config.key}`,
2112
+ ` model: ${model.id}`,
2113
+ " roles:",
2114
+ " - chat",
2115
+ " - edit",
2116
+ " - agent"
2117
+ ].join("\n");
2118
+ }
2119
+ function modelEntries(config) {
2120
+ return config.models.map((model) => modelEntry(config, model)).join("\n");
2121
+ }
2122
+ function lastTopLevelLine(content) {
2123
+ const lines = content.split("\n").filter((line) => /^[A-Za-z]/.test(line));
2124
+ return lines.length ? lines[lines.length - 1] : "";
2125
+ }
2126
+ function splitLines2(content) {
2127
+ if (content === "") return [];
2128
+ return (content.endsWith("\n") ? content.slice(0, -1) : content).split("\n");
2129
+ }
2130
+ function modelItems(lines) {
2131
+ const header = lines.findIndex((line) => /^models:\s*$/.test(line));
2132
+ if (header === -1) return [];
2133
+ const items = [];
2134
+ for (let index = header + 1; index < lines.length; index += 1) {
2135
+ const line = lines[index];
2136
+ if (/^[^\s#]/.test(line)) break;
2137
+ if (line.startsWith(ITEM_START)) items.push({ start: index, end: index + 1 });
2138
+ else if (/^ {3,}\S/.test(line) && items.length > 0) items[items.length - 1].end = index + 1;
2139
+ }
2140
+ return items;
2141
+ }
2142
+ function itemField(lines, item, field) {
2143
+ for (let index = item.start; index < item.end; index += 1) {
2144
+ const line = index === item.start ? ` ${lines[index].slice(ITEM_START.length)}` : lines[index];
2145
+ const match = ITEM_FIELD.exec(line);
2146
+ if (match?.[1] === field) return match[2];
2147
+ }
2148
+ return void 0;
2149
+ }
2150
+ function isOwnItem(lines, item, config) {
2151
+ const model = itemField(lines, item, "model");
2152
+ return model !== void 0 && isOwnModel(model, config) && itemField(lines, item, "apiBase") === config.base;
2153
+ }
2154
+ function replaceOwnItems(content, entries, config) {
2155
+ const lines = splitLines2(content);
2156
+ const own = modelItems(lines).filter((item) => isOwnItem(lines, item, config));
2157
+ if (own.length === 0) return null;
2158
+ const updated = [];
2159
+ let cursor = 0;
2160
+ for (const item of own) {
2161
+ updated.push(...lines.slice(cursor, item.start));
2162
+ if (item === own[0]) updated.push(entries);
2163
+ cursor = item.end;
2164
+ }
2165
+ updated.push(...lines.slice(cursor));
2166
+ return `${updated.join("\n")}
2167
+ `;
2168
+ }
2169
+ function write4(config) {
2170
+ const { continueDir: dir, continueConfig: file } = toolPaths(config);
2171
+ mkdirSync6(dir, { recursive: true });
2172
+ const entries = modelEntries(config);
2173
+ const next = `reload Continue and pick "unrestricted.sh ${config.modelName}"`;
2174
+ if (!existsSync6(file)) {
2175
+ writeFileSync8(file, `name: unrestricted.sh
2176
+ version: 0.0.1
2177
+ schema: v1
2178
+ models:
2179
+ ${entries}
2180
+ `);
2181
+ setMode(file, 384, config.platform);
2182
+ return { path: file, next };
2183
+ }
2184
+ const raw = readFileSync7(file, "utf8");
2185
+ const layout = layoutOf(raw);
2186
+ const content = toLf(raw);
2187
+ const replaced = replaceOwnItems(content, entries, config);
2188
+ if (replaced !== null) {
2189
+ if (replaced !== content) writeFileSync8(file, fromLf(replaced, layout));
2190
+ return { path: file, next };
2191
+ }
2192
+ if (content.includes(`apiBase: ${config.base}`)) return { path: file, next };
2193
+ if (lastTopLevelLine(content) === "models:") {
2194
+ writeFileSync8(file, fromLf(`${content}${entries}
2195
+ `, layout));
2196
+ return { path: file, next };
2197
+ }
2198
+ return { path: file, next, hint: `could not merge into ${file} automatically; add this under models:
2199
+ ${entries}` };
2200
+ }
2201
+
2202
+ // cli/src/writers/crush.ts
2203
+ import { existsSync as existsSync7, mkdirSync as mkdirSync7, readFileSync as readFileSync8, writeFileSync as writeFileSync9 } from "node:fs";
2204
+ function splitLines3(content) {
2205
+ if (content === "") return [];
2206
+ return (content.endsWith("\n") ? content.slice(0, -1) : content).split("\n");
2207
+ }
2208
+ function isOwnLine(line, config) {
2209
+ const [command, action, target = ""] = line.trim().split(/\s+/);
2210
+ if (command === "provider" && action === "add") return target === config.provider;
2211
+ if (command !== "model" || action !== "add" && action !== "use") return false;
2212
+ const prefix = `${config.provider}/`;
2213
+ return target.startsWith(prefix) && isOwnModel(target.slice(prefix.length), config);
2214
+ }
2215
+ function modelLine(config, model) {
2216
+ return `model add ${config.provider}/${model.id} --name "${model.name}" --context-window ${model.context} --default-max-tokens ${model.maxOutput} --can-reason true`;
2217
+ }
2218
+ function ownLines(config) {
2219
+ return [
2220
+ `provider add ${config.provider} --type openai-compat --base-url "${config.base}" --api-key "${config.key}"`,
2221
+ ...config.models.map((model) => modelLine(config, model)),
2222
+ `model use ${config.provider}/${config.model}`
2223
+ ];
2224
+ }
2225
+ function write5(config) {
2226
+ const { crushDir: dir, crushrc: file } = toolPaths(config);
2227
+ mkdirSync7(dir, { recursive: true });
2228
+ const raw = existsSync7(file) ? readFileSync8(file, "utf8") : "";
2229
+ const lines = splitLines3(toLf(raw));
2230
+ const firstOwn = lines.findIndex((line) => isOwnLine(line, config));
2231
+ const kept = lines.filter((line) => !isOwnLine(line, config));
2232
+ kept.splice(firstOwn === -1 ? kept.length : firstOwn, 0, ...ownLines(config));
2233
+ const updated = fromLf(`${kept.join("\n")}
2234
+ `, layoutOf(raw));
2235
+ if (updated !== raw) {
2236
+ writeFileSync9(file, updated);
2237
+ setMode(file, 384, config.platform);
2238
+ }
2239
+ return { path: file, next: "crush" };
2240
+ }
2241
+
2242
+ // cli/src/writers/opencode.ts
2243
+ import { mkdirSync as mkdirSync8, readFileSync as readFileSync9, statSync as statSync3, writeFileSync as writeFileSync10 } from "node:fs";
2244
+
2245
+ // node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js
2246
+ function createScanner(text, ignoreTrivia = false) {
2247
+ const len = text.length;
2248
+ let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
2249
+ function scanHexDigits(count, exact) {
2250
+ let digits = 0;
2251
+ let value2 = 0;
2252
+ while (digits < count || !exact) {
2253
+ let ch = text.charCodeAt(pos);
2254
+ if (ch >= 48 && ch <= 57) {
2255
+ value2 = value2 * 16 + ch - 48;
2256
+ } else if (ch >= 65 && ch <= 70) {
2257
+ value2 = value2 * 16 + ch - 65 + 10;
2258
+ } else if (ch >= 97 && ch <= 102) {
2259
+ value2 = value2 * 16 + ch - 97 + 10;
2260
+ } else {
2261
+ break;
2262
+ }
2263
+ pos++;
2264
+ digits++;
2265
+ }
2266
+ if (digits < count) {
2267
+ value2 = -1;
2268
+ }
2269
+ return value2;
2270
+ }
2271
+ function setPosition(newPosition) {
2272
+ pos = newPosition;
2273
+ value = "";
2274
+ tokenOffset = 0;
2275
+ token = 16;
2276
+ scanError = 0;
2277
+ }
2278
+ function scanNumber() {
2279
+ let start2 = pos;
2280
+ if (text.charCodeAt(pos) === 48) {
2281
+ pos++;
2282
+ } else {
2283
+ pos++;
2284
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
2285
+ pos++;
2286
+ }
2287
+ }
2288
+ if (pos < text.length && text.charCodeAt(pos) === 46) {
2289
+ pos++;
2290
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
2291
+ pos++;
2292
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
2293
+ pos++;
2294
+ }
2295
+ } else {
2296
+ scanError = 3;
2297
+ return text.substring(start2, pos);
2298
+ }
2299
+ }
2300
+ let end = pos;
2301
+ if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
2302
+ pos++;
2303
+ if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) {
2304
+ pos++;
2305
+ }
2306
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
2307
+ pos++;
2308
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
2309
+ pos++;
2310
+ }
2311
+ end = pos;
2312
+ } else {
2313
+ scanError = 3;
2314
+ }
2315
+ }
2316
+ return text.substring(start2, end);
2317
+ }
2318
+ function scanString() {
2319
+ let result = "", start2 = pos;
2320
+ while (true) {
2321
+ if (pos >= len) {
2322
+ result += text.substring(start2, pos);
2323
+ scanError = 2;
2324
+ break;
2325
+ }
2326
+ const ch = text.charCodeAt(pos);
2327
+ if (ch === 34) {
2328
+ result += text.substring(start2, pos);
2329
+ pos++;
2330
+ break;
2331
+ }
2332
+ if (ch === 92) {
2333
+ result += text.substring(start2, pos);
2334
+ pos++;
2335
+ if (pos >= len) {
2336
+ scanError = 2;
2337
+ break;
2338
+ }
2339
+ const ch2 = text.charCodeAt(pos++);
2340
+ switch (ch2) {
2341
+ case 34:
2342
+ result += '"';
2343
+ break;
2344
+ case 92:
2345
+ result += "\\";
2346
+ break;
2347
+ case 47:
2348
+ result += "/";
2349
+ break;
2350
+ case 98:
2351
+ result += "\b";
2352
+ break;
2353
+ case 102:
2354
+ result += "\f";
2355
+ break;
2356
+ case 110:
2357
+ result += "\n";
2358
+ break;
2359
+ case 114:
2360
+ result += "\r";
2361
+ break;
2362
+ case 116:
2363
+ result += " ";
2364
+ break;
2365
+ case 117:
2366
+ const ch3 = scanHexDigits(4, true);
2367
+ if (ch3 >= 0) {
2368
+ result += String.fromCharCode(ch3);
2369
+ } else {
2370
+ scanError = 4;
2371
+ }
2372
+ break;
2373
+ default:
2374
+ scanError = 5;
2375
+ }
2376
+ start2 = pos;
2377
+ continue;
2378
+ }
2379
+ if (ch >= 0 && ch <= 31) {
2380
+ if (isLineBreak(ch)) {
2381
+ result += text.substring(start2, pos);
2382
+ scanError = 2;
2383
+ break;
2384
+ } else {
2385
+ scanError = 6;
2386
+ }
2387
+ }
2388
+ pos++;
2389
+ }
2390
+ return result;
2391
+ }
2392
+ function scanNext() {
2393
+ value = "";
2394
+ scanError = 0;
2395
+ tokenOffset = pos;
2396
+ lineStartOffset = lineNumber;
2397
+ prevTokenLineStartOffset = tokenLineStartOffset;
2398
+ if (pos >= len) {
2399
+ tokenOffset = len;
2400
+ return token = 17;
2401
+ }
2402
+ let code = text.charCodeAt(pos);
2403
+ if (isWhiteSpace(code)) {
2404
+ do {
2405
+ pos++;
2406
+ value += String.fromCharCode(code);
2407
+ code = text.charCodeAt(pos);
2408
+ } while (isWhiteSpace(code));
2409
+ return token = 15;
2410
+ }
2411
+ if (isLineBreak(code)) {
2412
+ pos++;
2413
+ value += String.fromCharCode(code);
2414
+ if (code === 13 && text.charCodeAt(pos) === 10) {
2415
+ pos++;
2416
+ value += "\n";
2417
+ }
2418
+ lineNumber++;
2419
+ tokenLineStartOffset = pos;
2420
+ return token = 14;
2421
+ }
2422
+ switch (code) {
2423
+ // tokens: []{}:,
2424
+ case 123:
2425
+ pos++;
2426
+ return token = 1;
2427
+ case 125:
2428
+ pos++;
2429
+ return token = 2;
2430
+ case 91:
2431
+ pos++;
2432
+ return token = 3;
2433
+ case 93:
2434
+ pos++;
2435
+ return token = 4;
2436
+ case 58:
2437
+ pos++;
2438
+ return token = 6;
2439
+ case 44:
2440
+ pos++;
2441
+ return token = 5;
2442
+ // strings
2443
+ case 34:
2444
+ pos++;
2445
+ value = scanString();
2446
+ return token = 10;
2447
+ // comments
2448
+ case 47:
2449
+ const start2 = pos - 1;
2450
+ if (text.charCodeAt(pos + 1) === 47) {
2451
+ pos += 2;
2452
+ while (pos < len) {
2453
+ if (isLineBreak(text.charCodeAt(pos))) {
2454
+ break;
2455
+ }
2456
+ pos++;
2457
+ }
2458
+ value = text.substring(start2, pos);
2459
+ return token = 12;
2460
+ }
2461
+ if (text.charCodeAt(pos + 1) === 42) {
2462
+ pos += 2;
2463
+ const safeLength = len - 1;
2464
+ let commentClosed = false;
2465
+ while (pos < safeLength) {
2466
+ const ch = text.charCodeAt(pos);
2467
+ if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
2468
+ pos += 2;
2469
+ commentClosed = true;
2470
+ break;
2471
+ }
2472
+ pos++;
2473
+ if (isLineBreak(ch)) {
2474
+ if (ch === 13 && text.charCodeAt(pos) === 10) {
2475
+ pos++;
2476
+ }
2477
+ lineNumber++;
2478
+ tokenLineStartOffset = pos;
2479
+ }
2480
+ }
2481
+ if (!commentClosed) {
2482
+ pos++;
2483
+ scanError = 1;
2484
+ }
2485
+ value = text.substring(start2, pos);
2486
+ return token = 13;
2487
+ }
2488
+ value += String.fromCharCode(code);
2489
+ pos++;
2490
+ return token = 16;
2491
+ // numbers
2492
+ case 45:
2493
+ value += String.fromCharCode(code);
2494
+ pos++;
2495
+ if (pos === len || !isDigit(text.charCodeAt(pos))) {
2496
+ return token = 16;
2497
+ }
2498
+ // found a minus, followed by a number so
2499
+ // we fall through to proceed with scanning
2500
+ // numbers
2501
+ case 48:
2502
+ case 49:
2503
+ case 50:
2504
+ case 51:
2505
+ case 52:
2506
+ case 53:
2507
+ case 54:
2508
+ case 55:
2509
+ case 56:
2510
+ case 57:
2511
+ value += scanNumber();
2512
+ return token = 11;
2513
+ // literals and unknown symbols
2514
+ default:
2515
+ while (pos < len && isUnknownContentCharacter(code)) {
2516
+ pos++;
2517
+ code = text.charCodeAt(pos);
2518
+ }
2519
+ if (tokenOffset !== pos) {
2520
+ value = text.substring(tokenOffset, pos);
2521
+ switch (value) {
2522
+ case "true":
2523
+ return token = 8;
2524
+ case "false":
2525
+ return token = 9;
2526
+ case "null":
2527
+ return token = 7;
2528
+ }
2529
+ return token = 16;
2530
+ }
2531
+ value += String.fromCharCode(code);
2532
+ pos++;
2533
+ return token = 16;
2534
+ }
2535
+ }
2536
+ function isUnknownContentCharacter(code) {
2537
+ if (isWhiteSpace(code) || isLineBreak(code)) {
2538
+ return false;
2539
+ }
2540
+ switch (code) {
2541
+ case 125:
2542
+ case 93:
2543
+ case 123:
2544
+ case 91:
2545
+ case 34:
2546
+ case 58:
2547
+ case 44:
2548
+ case 47:
2549
+ return false;
2550
+ }
2551
+ return true;
2552
+ }
2553
+ function scanNextNonTrivia() {
2554
+ let result;
2555
+ do {
2556
+ result = scanNext();
2557
+ } while (result >= 12 && result <= 15);
2558
+ return result;
2559
+ }
2560
+ return {
2561
+ setPosition,
2562
+ getPosition: () => pos,
2563
+ scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
2564
+ getToken: () => token,
2565
+ getTokenValue: () => value,
2566
+ getTokenOffset: () => tokenOffset,
2567
+ getTokenLength: () => pos - tokenOffset,
2568
+ getTokenStartLine: () => lineStartOffset,
2569
+ getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,
2570
+ getTokenError: () => scanError
2571
+ };
2572
+ }
2573
+ function isWhiteSpace(ch) {
2574
+ return ch === 32 || ch === 9;
2575
+ }
2576
+ function isLineBreak(ch) {
2577
+ return ch === 10 || ch === 13;
2578
+ }
2579
+ function isDigit(ch) {
2580
+ return ch >= 48 && ch <= 57;
2581
+ }
2582
+ var CharacterCodes;
2583
+ (function(CharacterCodes2) {
2584
+ CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
2585
+ CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
2586
+ CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
2587
+ CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
2588
+ CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
2589
+ CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
2590
+ CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
2591
+ CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
2592
+ CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
2593
+ CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
2594
+ CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
2595
+ CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
2596
+ CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
2597
+ CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
2598
+ CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
2599
+ CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
2600
+ CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
2601
+ CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
2602
+ CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
2603
+ CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
2604
+ CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
2605
+ CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
2606
+ CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
2607
+ CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
2608
+ CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
2609
+ CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
2610
+ CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
2611
+ CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
2612
+ CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
2613
+ CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
2614
+ CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
2615
+ CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
2616
+ CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
2617
+ CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
2618
+ CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
2619
+ CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
2620
+ CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
2621
+ CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
2622
+ CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
2623
+ CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
2624
+ CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
2625
+ CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
2626
+ CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
2627
+ CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
2628
+ CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
2629
+ CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
2630
+ CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
2631
+ CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
2632
+ CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
2633
+ CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
2634
+ CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
2635
+ CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
2636
+ CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
2637
+ CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
2638
+ CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
2639
+ CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
2640
+ CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
2641
+ CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
2642
+ CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
2643
+ CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
2644
+ CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
2645
+ CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
2646
+ CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
2647
+ CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
2648
+ CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
2649
+ CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
2650
+ CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
2651
+ CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
2652
+ CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
2653
+ CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
2654
+ CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
2655
+ CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
2656
+ CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
2657
+ CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
2658
+ CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
2659
+ CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
2660
+ CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
2661
+ CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
2662
+ CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
2663
+ CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
2664
+ })(CharacterCodes || (CharacterCodes = {}));
2665
+
2666
+ // node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js
2667
+ var cachedSpaces = new Array(20).fill(0).map((_3, index) => {
2668
+ return " ".repeat(index);
2669
+ });
2670
+ var maxCachedValues = 200;
2671
+ var cachedBreakLinesWithSpaces = {
2672
+ " ": {
2673
+ "\n": new Array(maxCachedValues).fill(0).map((_3, index) => {
2674
+ return "\n" + " ".repeat(index);
2675
+ }),
2676
+ "\r": new Array(maxCachedValues).fill(0).map((_3, index) => {
2677
+ return "\r" + " ".repeat(index);
2678
+ }),
2679
+ "\r\n": new Array(maxCachedValues).fill(0).map((_3, index) => {
2680
+ return "\r\n" + " ".repeat(index);
2681
+ })
2682
+ },
2683
+ " ": {
2684
+ "\n": new Array(maxCachedValues).fill(0).map((_3, index) => {
2685
+ return "\n" + " ".repeat(index);
2686
+ }),
2687
+ "\r": new Array(maxCachedValues).fill(0).map((_3, index) => {
2688
+ return "\r" + " ".repeat(index);
2689
+ }),
2690
+ "\r\n": new Array(maxCachedValues).fill(0).map((_3, index) => {
2691
+ return "\r\n" + " ".repeat(index);
2692
+ })
2693
+ }
2694
+ };
2695
+ var supportedEols = ["\n", "\r", "\r\n"];
2696
+
2697
+ // node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/format.js
2698
+ function format(documentText, range, options) {
2699
+ let initialIndentLevel;
2700
+ let formatText;
2701
+ let formatTextStart;
2702
+ let rangeStart;
2703
+ let rangeEnd;
2704
+ if (range) {
2705
+ rangeStart = range.offset;
2706
+ rangeEnd = rangeStart + range.length;
2707
+ formatTextStart = rangeStart;
2708
+ while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
2709
+ formatTextStart--;
2710
+ }
2711
+ let endOffset = rangeEnd;
2712
+ while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
2713
+ endOffset++;
2714
+ }
2715
+ formatText = documentText.substring(formatTextStart, endOffset);
2716
+ initialIndentLevel = computeIndentLevel(formatText, options);
2717
+ } else {
2718
+ formatText = documentText;
2719
+ initialIndentLevel = 0;
2720
+ formatTextStart = 0;
2721
+ rangeStart = 0;
2722
+ rangeEnd = documentText.length;
2723
+ }
2724
+ const eol = getEOL(options, documentText);
2725
+ const eolFastPathSupported = supportedEols.includes(eol);
2726
+ let numberLineBreaks = 0;
2727
+ let indentLevel = 0;
2728
+ let indentValue;
2729
+ if (options.insertSpaces) {
2730
+ indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4);
2731
+ } else {
2732
+ indentValue = " ";
2733
+ }
2734
+ const indentType = indentValue === " " ? " " : " ";
2735
+ let scanner = createScanner(formatText, false);
2736
+ let hasError = false;
2737
+ function newLinesAndIndent() {
2738
+ if (numberLineBreaks > 1) {
2739
+ return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);
2740
+ }
2741
+ const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);
2742
+ if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) {
2743
+ return eol + repeat(indentValue, initialIndentLevel + indentLevel);
2744
+ }
2745
+ if (amountOfSpaces <= 0) {
2746
+ return eol;
2747
+ }
2748
+ return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];
2749
+ }
2750
+ function scanNext() {
2751
+ let token = scanner.scan();
2752
+ numberLineBreaks = 0;
2753
+ while (token === 15 || token === 14) {
2754
+ if (token === 14 && options.keepLines) {
2755
+ numberLineBreaks += 1;
2756
+ } else if (token === 14) {
2757
+ numberLineBreaks = 1;
2758
+ }
2759
+ token = scanner.scan();
2760
+ }
2761
+ hasError = token === 16 || scanner.getTokenError() !== 0;
2762
+ return token;
2763
+ }
2764
+ const editOperations = [];
2765
+ function addEdit(text, startOffset, endOffset) {
2766
+ if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) {
2767
+ editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
2768
+ }
2769
+ }
2770
+ let firstToken = scanNext();
2771
+ if (options.keepLines && numberLineBreaks > 0) {
2772
+ addEdit(repeat(eol, numberLineBreaks), 0, 0);
2773
+ }
2774
+ if (firstToken !== 17) {
2775
+ let firstTokenStart = scanner.getTokenOffset() + formatTextStart;
2776
+ let initialIndent = indentValue.length * initialIndentLevel < 20 && options.insertSpaces ? cachedSpaces[indentValue.length * initialIndentLevel] : repeat(indentValue, initialIndentLevel);
2777
+ addEdit(initialIndent, formatTextStart, firstTokenStart);
2778
+ }
2779
+ while (firstToken !== 17) {
2780
+ let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
2781
+ let secondToken = scanNext();
2782
+ let replaceContent = "";
2783
+ let needsLineBreak = false;
2784
+ while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) {
2785
+ let commentTokenStart = scanner.getTokenOffset() + formatTextStart;
2786
+ addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart);
2787
+ firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
2788
+ needsLineBreak = secondToken === 12;
2789
+ replaceContent = needsLineBreak ? newLinesAndIndent() : "";
2790
+ secondToken = scanNext();
2791
+ }
2792
+ if (secondToken === 2) {
2793
+ if (firstToken !== 1) {
2794
+ indentLevel--;
2795
+ }
2796
+ ;
2797
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) {
2798
+ replaceContent = newLinesAndIndent();
2799
+ } else if (options.keepLines) {
2800
+ replaceContent = cachedSpaces[1];
2801
+ }
2802
+ } else if (secondToken === 4) {
2803
+ if (firstToken !== 3) {
2804
+ indentLevel--;
2805
+ }
2806
+ ;
2807
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) {
2808
+ replaceContent = newLinesAndIndent();
2809
+ } else if (options.keepLines) {
2810
+ replaceContent = cachedSpaces[1];
2811
+ }
2812
+ } else {
2813
+ switch (firstToken) {
2814
+ case 3:
2815
+ case 1:
2816
+ indentLevel++;
2817
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
2818
+ replaceContent = newLinesAndIndent();
2819
+ } else {
2820
+ replaceContent = cachedSpaces[1];
2821
+ }
2822
+ break;
2823
+ case 5:
2824
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
2825
+ replaceContent = newLinesAndIndent();
2826
+ } else {
2827
+ replaceContent = cachedSpaces[1];
2828
+ }
2829
+ break;
2830
+ case 12:
2831
+ replaceContent = newLinesAndIndent();
2832
+ break;
2833
+ case 13:
2834
+ if (numberLineBreaks > 0) {
2835
+ replaceContent = newLinesAndIndent();
2836
+ } else if (!needsLineBreak) {
2837
+ replaceContent = cachedSpaces[1];
2838
+ }
2839
+ break;
2840
+ case 6:
2841
+ if (options.keepLines && numberLineBreaks > 0) {
2842
+ replaceContent = newLinesAndIndent();
2843
+ } else if (!needsLineBreak) {
2844
+ replaceContent = cachedSpaces[1];
2845
+ }
2846
+ break;
2847
+ case 10:
2848
+ if (options.keepLines && numberLineBreaks > 0) {
2849
+ replaceContent = newLinesAndIndent();
2850
+ } else if (secondToken === 6 && !needsLineBreak) {
2851
+ replaceContent = "";
2852
+ }
2853
+ break;
2854
+ case 7:
2855
+ case 8:
2856
+ case 9:
2857
+ case 11:
2858
+ case 2:
2859
+ case 4:
2860
+ if (options.keepLines && numberLineBreaks > 0) {
2861
+ replaceContent = newLinesAndIndent();
2862
+ } else {
2863
+ if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) {
2864
+ replaceContent = cachedSpaces[1];
2865
+ } else if (secondToken !== 5 && secondToken !== 17) {
2866
+ hasError = true;
2867
+ }
2868
+ }
2869
+ break;
2870
+ case 16:
2871
+ hasError = true;
2872
+ break;
2873
+ }
2874
+ if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) {
2875
+ replaceContent = newLinesAndIndent();
2876
+ }
2877
+ }
2878
+ if (secondToken === 17) {
2879
+ if (options.keepLines && numberLineBreaks > 0) {
2880
+ replaceContent = newLinesAndIndent();
2881
+ } else {
2882
+ replaceContent = options.insertFinalNewline ? eol : "";
2883
+ }
2884
+ }
2885
+ const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
2886
+ addEdit(replaceContent, firstTokenEnd, secondTokenStart);
2887
+ firstToken = secondToken;
2888
+ }
2889
+ return editOperations;
2890
+ }
2891
+ function repeat(s, count) {
2892
+ let result = "";
2893
+ for (let i = 0; i < count; i++) {
2894
+ result += s;
2895
+ }
2896
+ return result;
2897
+ }
2898
+ function computeIndentLevel(content, options) {
2899
+ let i = 0;
2900
+ let nChars = 0;
2901
+ const tabSize = options.tabSize || 4;
2902
+ while (i < content.length) {
2903
+ let ch = content.charAt(i);
2904
+ if (ch === cachedSpaces[1]) {
2905
+ nChars++;
2906
+ } else if (ch === " ") {
2907
+ nChars += tabSize;
2908
+ } else {
2909
+ break;
2910
+ }
2911
+ i++;
2912
+ }
2913
+ return Math.floor(nChars / tabSize);
2914
+ }
2915
+ function getEOL(options, text) {
2916
+ for (let i = 0; i < text.length; i++) {
2917
+ const ch = text.charAt(i);
2918
+ if (ch === "\r") {
2919
+ if (i + 1 < text.length && text.charAt(i + 1) === "\n") {
2920
+ return "\r\n";
2921
+ }
2922
+ return "\r";
2923
+ } else if (ch === "\n") {
2924
+ return "\n";
2925
+ }
2926
+ }
2927
+ return options && options.eol || "\n";
2928
+ }
2929
+ function isEOL(text, offset) {
2930
+ return "\r\n".indexOf(text.charAt(offset)) !== -1;
2931
+ }
2932
+
2933
+ // node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js
2934
+ var ParseOptions;
2935
+ (function(ParseOptions2) {
2936
+ ParseOptions2.DEFAULT = {
2937
+ allowTrailingComma: false
2938
+ };
2939
+ })(ParseOptions || (ParseOptions = {}));
2940
+ function parse(text, errors = [], options = ParseOptions.DEFAULT) {
2941
+ let currentProperty = null;
2942
+ let currentParent = [];
2943
+ const previousParents = [];
2944
+ function onValue(value) {
2945
+ if (Array.isArray(currentParent)) {
2946
+ currentParent.push(value);
2947
+ } else if (currentProperty !== null) {
2948
+ currentParent[currentProperty] = value;
2949
+ }
2950
+ }
2951
+ const visitor = {
2952
+ onObjectBegin: () => {
2953
+ const object = {};
2954
+ onValue(object);
2955
+ previousParents.push(currentParent);
2956
+ currentParent = object;
2957
+ currentProperty = null;
2958
+ },
2959
+ onObjectProperty: (name) => {
2960
+ currentProperty = name;
2961
+ },
2962
+ onObjectEnd: () => {
2963
+ currentParent = previousParents.pop();
2964
+ },
2965
+ onArrayBegin: () => {
2966
+ const array = [];
2967
+ onValue(array);
2968
+ previousParents.push(currentParent);
2969
+ currentParent = array;
2970
+ currentProperty = null;
2971
+ },
2972
+ onArrayEnd: () => {
2973
+ currentParent = previousParents.pop();
2974
+ },
2975
+ onLiteralValue: onValue,
2976
+ onError: (error, offset, length) => {
2977
+ errors.push({ error, offset, length });
2978
+ }
2979
+ };
2980
+ visit(text, visitor, options);
2981
+ return currentParent[0];
2982
+ }
2983
+ function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {
2984
+ let currentParent = { type: "array", offset: -1, length: -1, children: [], parent: void 0 };
2985
+ function ensurePropertyComplete(endOffset) {
2986
+ if (currentParent.type === "property") {
2987
+ currentParent.length = endOffset - currentParent.offset;
2988
+ currentParent = currentParent.parent;
2989
+ }
2990
+ }
2991
+ function onValue(valueNode) {
2992
+ currentParent.children.push(valueNode);
2993
+ return valueNode;
2994
+ }
2995
+ const visitor = {
2996
+ onObjectBegin: (offset) => {
2997
+ currentParent = onValue({ type: "object", offset, length: -1, parent: currentParent, children: [] });
2998
+ },
2999
+ onObjectProperty: (name, offset, length) => {
3000
+ currentParent = onValue({ type: "property", offset, length: -1, parent: currentParent, children: [] });
3001
+ currentParent.children.push({ type: "string", value: name, offset, length, parent: currentParent });
3002
+ },
3003
+ onObjectEnd: (offset, length) => {
3004
+ ensurePropertyComplete(offset + length);
3005
+ currentParent.length = offset + length - currentParent.offset;
3006
+ currentParent = currentParent.parent;
3007
+ ensurePropertyComplete(offset + length);
3008
+ },
3009
+ onArrayBegin: (offset, length) => {
3010
+ currentParent = onValue({ type: "array", offset, length: -1, parent: currentParent, children: [] });
3011
+ },
3012
+ onArrayEnd: (offset, length) => {
3013
+ currentParent.length = offset + length - currentParent.offset;
3014
+ currentParent = currentParent.parent;
3015
+ ensurePropertyComplete(offset + length);
3016
+ },
3017
+ onLiteralValue: (value, offset, length) => {
3018
+ onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });
3019
+ ensurePropertyComplete(offset + length);
3020
+ },
3021
+ onSeparator: (sep, offset, length) => {
3022
+ if (currentParent.type === "property") {
3023
+ if (sep === ":") {
3024
+ currentParent.colonOffset = offset;
3025
+ } else if (sep === ",") {
3026
+ ensurePropertyComplete(offset);
3027
+ }
3028
+ }
3029
+ },
3030
+ onError: (error, offset, length) => {
3031
+ errors.push({ error, offset, length });
3032
+ }
3033
+ };
3034
+ visit(text, visitor, options);
3035
+ const result = currentParent.children[0];
3036
+ if (result) {
3037
+ delete result.parent;
3038
+ }
3039
+ return result;
3040
+ }
3041
+ function findNodeAtLocation(root, path) {
3042
+ if (!root) {
3043
+ return void 0;
3044
+ }
3045
+ let node = root;
3046
+ for (let segment of path) {
3047
+ if (typeof segment === "string") {
3048
+ if (node.type !== "object" || !Array.isArray(node.children)) {
3049
+ return void 0;
3050
+ }
3051
+ let found = false;
3052
+ for (const propertyNode of node.children) {
3053
+ if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
3054
+ node = propertyNode.children[1];
3055
+ found = true;
3056
+ break;
3057
+ }
3058
+ }
3059
+ if (!found) {
3060
+ return void 0;
3061
+ }
3062
+ } else {
3063
+ const index = segment;
3064
+ if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
3065
+ return void 0;
3066
+ }
3067
+ node = node.children[index];
3068
+ }
3069
+ }
3070
+ return node;
3071
+ }
3072
+ function visit(text, visitor, options = ParseOptions.DEFAULT) {
3073
+ const _scanner = createScanner(text, false);
3074
+ const _jsonPath = [];
3075
+ let suppressedCallbacks = 0;
3076
+ function toNoArgVisit(visitFunction) {
3077
+ return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
3078
+ }
3079
+ function toOneArgVisit(visitFunction) {
3080
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
3081
+ }
3082
+ function toOneArgVisitWithPath(visitFunction) {
3083
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
3084
+ }
3085
+ function toBeginVisit(visitFunction) {
3086
+ return visitFunction ? () => {
3087
+ if (suppressedCallbacks > 0) {
3088
+ suppressedCallbacks++;
3089
+ } else {
3090
+ let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());
3091
+ if (cbReturn === false) {
3092
+ suppressedCallbacks = 1;
3093
+ }
3094
+ }
3095
+ } : () => true;
3096
+ }
3097
+ function toEndVisit(visitFunction) {
3098
+ return visitFunction ? () => {
3099
+ if (suppressedCallbacks > 0) {
3100
+ suppressedCallbacks--;
3101
+ }
3102
+ if (suppressedCallbacks === 0) {
3103
+ visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());
3104
+ }
3105
+ } : () => true;
3106
+ }
3107
+ const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
3108
+ const disallowComments = options && options.disallowComments;
3109
+ const allowTrailingComma = options && options.allowTrailingComma;
3110
+ function scanNext() {
3111
+ while (true) {
3112
+ const token = _scanner.scan();
3113
+ switch (_scanner.getTokenError()) {
3114
+ case 4:
3115
+ handleError(
3116
+ 14
3117
+ /* ParseErrorCode.InvalidUnicode */
3118
+ );
3119
+ break;
3120
+ case 5:
3121
+ handleError(
3122
+ 15
3123
+ /* ParseErrorCode.InvalidEscapeCharacter */
3124
+ );
3125
+ break;
3126
+ case 3:
3127
+ handleError(
3128
+ 13
3129
+ /* ParseErrorCode.UnexpectedEndOfNumber */
3130
+ );
3131
+ break;
3132
+ case 1:
3133
+ if (!disallowComments) {
3134
+ handleError(
3135
+ 11
3136
+ /* ParseErrorCode.UnexpectedEndOfComment */
3137
+ );
3138
+ }
3139
+ break;
3140
+ case 2:
3141
+ handleError(
3142
+ 12
3143
+ /* ParseErrorCode.UnexpectedEndOfString */
3144
+ );
3145
+ break;
3146
+ case 6:
3147
+ handleError(
3148
+ 16
3149
+ /* ParseErrorCode.InvalidCharacter */
3150
+ );
3151
+ break;
3152
+ }
3153
+ switch (token) {
3154
+ case 12:
3155
+ case 13:
3156
+ if (disallowComments) {
3157
+ handleError(
3158
+ 10
3159
+ /* ParseErrorCode.InvalidCommentToken */
3160
+ );
3161
+ } else {
3162
+ onComment();
3163
+ }
3164
+ break;
3165
+ case 16:
3166
+ handleError(
3167
+ 1
3168
+ /* ParseErrorCode.InvalidSymbol */
3169
+ );
3170
+ break;
3171
+ case 15:
3172
+ case 14:
3173
+ break;
3174
+ default:
3175
+ return token;
3176
+ }
3177
+ }
3178
+ }
3179
+ function handleError(error, skipUntilAfter = [], skipUntil = []) {
3180
+ onError(error);
3181
+ if (skipUntilAfter.length + skipUntil.length > 0) {
3182
+ let token = _scanner.getToken();
3183
+ while (token !== 17) {
3184
+ if (skipUntilAfter.indexOf(token) !== -1) {
3185
+ scanNext();
3186
+ break;
3187
+ } else if (skipUntil.indexOf(token) !== -1) {
3188
+ break;
3189
+ }
3190
+ token = scanNext();
3191
+ }
3192
+ }
3193
+ }
3194
+ function parseString(isValue) {
3195
+ const value = _scanner.getTokenValue();
3196
+ if (isValue) {
3197
+ onLiteralValue(value);
3198
+ } else {
3199
+ onObjectProperty(value);
3200
+ _jsonPath.push(value);
3201
+ }
3202
+ scanNext();
3203
+ return true;
3204
+ }
3205
+ function parseLiteral() {
3206
+ switch (_scanner.getToken()) {
3207
+ case 11:
3208
+ const tokenValue = _scanner.getTokenValue();
3209
+ let value = Number(tokenValue);
3210
+ if (isNaN(value)) {
3211
+ handleError(
3212
+ 2
3213
+ /* ParseErrorCode.InvalidNumberFormat */
3214
+ );
3215
+ value = 0;
3216
+ }
3217
+ onLiteralValue(value);
3218
+ break;
3219
+ case 7:
3220
+ onLiteralValue(null);
3221
+ break;
3222
+ case 8:
3223
+ onLiteralValue(true);
3224
+ break;
3225
+ case 9:
3226
+ onLiteralValue(false);
3227
+ break;
3228
+ default:
3229
+ return false;
3230
+ }
3231
+ scanNext();
3232
+ return true;
3233
+ }
3234
+ function parseProperty() {
3235
+ if (_scanner.getToken() !== 10) {
3236
+ handleError(3, [], [
3237
+ 2,
3238
+ 5
3239
+ /* SyntaxKind.CommaToken */
3240
+ ]);
3241
+ return false;
3242
+ }
3243
+ parseString(false);
3244
+ if (_scanner.getToken() === 6) {
3245
+ onSeparator(":");
3246
+ scanNext();
3247
+ if (!parseValue()) {
3248
+ handleError(4, [], [
3249
+ 2,
3250
+ 5
3251
+ /* SyntaxKind.CommaToken */
3252
+ ]);
3253
+ }
3254
+ } else {
3255
+ handleError(5, [], [
3256
+ 2,
3257
+ 5
3258
+ /* SyntaxKind.CommaToken */
3259
+ ]);
3260
+ }
3261
+ _jsonPath.pop();
3262
+ return true;
3263
+ }
3264
+ function parseObject() {
3265
+ onObjectBegin();
3266
+ scanNext();
3267
+ let needsComma = false;
3268
+ while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
3269
+ if (_scanner.getToken() === 5) {
3270
+ if (!needsComma) {
3271
+ handleError(4, [], []);
3272
+ }
3273
+ onSeparator(",");
3274
+ scanNext();
3275
+ if (_scanner.getToken() === 2 && allowTrailingComma) {
3276
+ break;
3277
+ }
3278
+ } else if (needsComma) {
3279
+ handleError(6, [], []);
3280
+ }
3281
+ if (!parseProperty()) {
3282
+ handleError(4, [], [
3283
+ 2,
3284
+ 5
3285
+ /* SyntaxKind.CommaToken */
3286
+ ]);
3287
+ }
3288
+ needsComma = true;
3289
+ }
3290
+ onObjectEnd();
3291
+ if (_scanner.getToken() !== 2) {
3292
+ handleError(7, [
3293
+ 2
3294
+ /* SyntaxKind.CloseBraceToken */
3295
+ ], []);
3296
+ } else {
3297
+ scanNext();
3298
+ }
3299
+ return true;
3300
+ }
3301
+ function parseArray() {
3302
+ onArrayBegin();
3303
+ scanNext();
3304
+ let isFirstElement = true;
3305
+ let needsComma = false;
3306
+ while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
3307
+ if (_scanner.getToken() === 5) {
3308
+ if (!needsComma) {
3309
+ handleError(4, [], []);
3310
+ }
3311
+ onSeparator(",");
3312
+ scanNext();
3313
+ if (_scanner.getToken() === 4 && allowTrailingComma) {
3314
+ break;
3315
+ }
3316
+ } else if (needsComma) {
3317
+ handleError(6, [], []);
3318
+ }
3319
+ if (isFirstElement) {
3320
+ _jsonPath.push(0);
3321
+ isFirstElement = false;
3322
+ } else {
3323
+ _jsonPath[_jsonPath.length - 1]++;
3324
+ }
3325
+ if (!parseValue()) {
3326
+ handleError(4, [], [
3327
+ 4,
3328
+ 5
3329
+ /* SyntaxKind.CommaToken */
3330
+ ]);
3331
+ }
3332
+ needsComma = true;
3333
+ }
3334
+ onArrayEnd();
3335
+ if (!isFirstElement) {
3336
+ _jsonPath.pop();
3337
+ }
3338
+ if (_scanner.getToken() !== 4) {
3339
+ handleError(8, [
3340
+ 4
3341
+ /* SyntaxKind.CloseBracketToken */
3342
+ ], []);
3343
+ } else {
3344
+ scanNext();
3345
+ }
3346
+ return true;
3347
+ }
3348
+ function parseValue() {
3349
+ switch (_scanner.getToken()) {
3350
+ case 3:
3351
+ return parseArray();
3352
+ case 1:
3353
+ return parseObject();
3354
+ case 10:
3355
+ return parseString(true);
3356
+ default:
3357
+ return parseLiteral();
3358
+ }
3359
+ }
3360
+ scanNext();
3361
+ if (_scanner.getToken() === 17) {
3362
+ if (options.allowEmptyContent) {
3363
+ return true;
3364
+ }
3365
+ handleError(4, [], []);
3366
+ return false;
3367
+ }
3368
+ if (!parseValue()) {
3369
+ handleError(4, [], []);
3370
+ return false;
3371
+ }
3372
+ if (_scanner.getToken() !== 17) {
3373
+ handleError(9, [], []);
3374
+ }
3375
+ return true;
3376
+ }
3377
+ function getNodeType(value) {
3378
+ switch (typeof value) {
3379
+ case "boolean":
3380
+ return "boolean";
3381
+ case "number":
3382
+ return "number";
3383
+ case "string":
3384
+ return "string";
3385
+ case "object": {
3386
+ if (!value) {
3387
+ return "null";
3388
+ } else if (Array.isArray(value)) {
3389
+ return "array";
3390
+ }
3391
+ return "object";
3392
+ }
3393
+ default:
3394
+ return "null";
3395
+ }
3396
+ }
3397
+
3398
+ // node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/edit.js
3399
+ function setProperty(text, originalPath, value, options) {
3400
+ const path = originalPath.slice();
3401
+ const errors = [];
3402
+ const root = parseTree(text, errors);
3403
+ let parent = void 0;
3404
+ let lastSegment = void 0;
3405
+ while (path.length > 0) {
3406
+ lastSegment = path.pop();
3407
+ parent = findNodeAtLocation(root, path);
3408
+ if (parent === void 0 && value !== void 0) {
3409
+ if (typeof lastSegment === "string") {
3410
+ value = { [lastSegment]: value };
3411
+ } else {
3412
+ value = [value];
3413
+ }
3414
+ } else {
3415
+ break;
3416
+ }
3417
+ }
3418
+ if (!parent) {
3419
+ if (value === void 0) {
3420
+ throw new Error("Can not delete in empty document");
3421
+ }
3422
+ return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);
3423
+ } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
3424
+ const existing = findNodeAtLocation(parent, [lastSegment]);
3425
+ if (existing !== void 0) {
3426
+ if (value === void 0) {
3427
+ if (!existing.parent) {
3428
+ throw new Error("Malformed AST");
3429
+ }
3430
+ const propertyIndex = parent.children.indexOf(existing.parent);
3431
+ let removeBegin;
3432
+ let removeEnd = existing.parent.offset + existing.parent.length;
3433
+ if (propertyIndex > 0) {
3434
+ let previous = parent.children[propertyIndex - 1];
3435
+ removeBegin = previous.offset + previous.length;
3436
+ } else {
3437
+ removeBegin = parent.offset + 1;
3438
+ if (parent.children.length > 1) {
3439
+ let next = parent.children[1];
3440
+ removeEnd = next.offset;
3441
+ }
3442
+ }
3443
+ return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: "" }, options);
3444
+ } else {
3445
+ return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);
3446
+ }
3447
+ } else {
3448
+ if (value === void 0) {
3449
+ return [];
3450
+ }
3451
+ const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
3452
+ const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map((p2) => p2.children[0].value)) : parent.children.length;
3453
+ let edit;
3454
+ if (index > 0) {
3455
+ let previous = parent.children[index - 1];
3456
+ edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
3457
+ } else if (parent.children.length === 0) {
3458
+ edit = { offset: parent.offset + 1, length: 0, content: newProperty };
3459
+ } else {
3460
+ edit = { offset: parent.offset + 1, length: 0, content: newProperty + "," };
3461
+ }
3462
+ return withFormatting(text, edit, options);
3463
+ }
3464
+ } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
3465
+ const insertIndex = lastSegment;
3466
+ if (insertIndex === -1) {
3467
+ const newProperty = `${JSON.stringify(value)}`;
3468
+ let edit;
3469
+ if (parent.children.length === 0) {
3470
+ edit = { offset: parent.offset + 1, length: 0, content: newProperty };
3471
+ } else {
3472
+ const previous = parent.children[parent.children.length - 1];
3473
+ edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
3474
+ }
3475
+ return withFormatting(text, edit, options);
3476
+ } else if (value === void 0 && parent.children.length >= 0) {
3477
+ const removalIndex = lastSegment;
3478
+ const toRemove = parent.children[removalIndex];
3479
+ let edit;
3480
+ if (parent.children.length === 1) {
3481
+ edit = { offset: parent.offset + 1, length: parent.length - 2, content: "" };
3482
+ } else if (parent.children.length - 1 === removalIndex) {
3483
+ let previous = parent.children[removalIndex - 1];
3484
+ let offset = previous.offset + previous.length;
3485
+ let parentEndOffset = parent.offset + parent.length;
3486
+ edit = { offset, length: parentEndOffset - 2 - offset, content: "" };
3487
+ } else {
3488
+ edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: "" };
3489
+ }
3490
+ return withFormatting(text, edit, options);
3491
+ } else if (value !== void 0) {
3492
+ let edit;
3493
+ const newProperty = `${JSON.stringify(value)}`;
3494
+ if (!options.isArrayInsertion && parent.children.length > lastSegment) {
3495
+ const toModify = parent.children[lastSegment];
3496
+ edit = { offset: toModify.offset, length: toModify.length, content: newProperty };
3497
+ } else if (parent.children.length === 0 || lastSegment === 0) {
3498
+ edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + "," };
3499
+ } else {
3500
+ const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
3501
+ const previous = parent.children[index - 1];
3502
+ edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
3503
+ }
3504
+ return withFormatting(text, edit, options);
3505
+ } else {
3506
+ throw new Error(`Can not ${value === void 0 ? "remove" : options.isArrayInsertion ? "insert" : "modify"} Array index ${insertIndex} as length is not sufficient`);
3507
+ }
3508
+ } else {
3509
+ throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
3510
+ }
3511
+ }
3512
+ function withFormatting(text, edit, options) {
3513
+ if (!options.formattingOptions) {
3514
+ return [edit];
3515
+ }
3516
+ let newText = applyEdit(text, edit);
3517
+ let begin = edit.offset;
3518
+ let end = edit.offset + edit.content.length;
3519
+ if (edit.length === 0 || edit.content.length === 0) {
3520
+ while (begin > 0 && !isEOL(newText, begin - 1)) {
3521
+ begin--;
3522
+ }
3523
+ while (end < newText.length && !isEOL(newText, end)) {
3524
+ end++;
3525
+ }
3526
+ }
3527
+ const edits = format(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false });
3528
+ for (let i = edits.length - 1; i >= 0; i--) {
3529
+ const edit2 = edits[i];
3530
+ newText = applyEdit(newText, edit2);
3531
+ begin = Math.min(begin, edit2.offset);
3532
+ end = Math.max(end, edit2.offset + edit2.length);
3533
+ end += edit2.content.length - edit2.length;
3534
+ }
3535
+ const editLength = text.length - (newText.length - end) - begin;
3536
+ return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
3537
+ }
3538
+ function applyEdit(text, edit) {
3539
+ return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
3540
+ }
3541
+
3542
+ // node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js
3543
+ var createScanner2 = createScanner;
3544
+ var ScanError;
3545
+ (function(ScanError2) {
3546
+ ScanError2[ScanError2["None"] = 0] = "None";
3547
+ ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
3548
+ ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
3549
+ ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
3550
+ ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
3551
+ ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
3552
+ ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
3553
+ })(ScanError || (ScanError = {}));
3554
+ var SyntaxKind;
3555
+ (function(SyntaxKind2) {
3556
+ SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
3557
+ SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
3558
+ SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
3559
+ SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
3560
+ SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
3561
+ SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
3562
+ SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
3563
+ SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
3564
+ SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
3565
+ SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
3566
+ SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
3567
+ SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
3568
+ SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
3569
+ SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
3570
+ SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
3571
+ SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
3572
+ SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
3573
+ })(SyntaxKind || (SyntaxKind = {}));
3574
+ var parse2 = parse;
3575
+ var parseTree2 = parseTree;
3576
+ var findNodeAtLocation2 = findNodeAtLocation;
3577
+ var ParseErrorCode;
3578
+ (function(ParseErrorCode2) {
3579
+ ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
3580
+ ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
3581
+ ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
3582
+ ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
3583
+ ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
3584
+ ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
3585
+ ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
3586
+ ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
3587
+ ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
3588
+ ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
3589
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
3590
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
3591
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
3592
+ ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
3593
+ ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
3594
+ ParseErrorCode2[ParseErrorCode2["InvalidCharacter"] = 16] = "InvalidCharacter";
3595
+ })(ParseErrorCode || (ParseErrorCode = {}));
3596
+ function modify(text, path, value, options) {
3597
+ return setProperty(text, path, value, options);
3598
+ }
3599
+ function applyEdits(text, edits) {
3600
+ let sortedEdits = edits.slice(0).sort((a, b3) => {
3601
+ const diff = a.offset - b3.offset;
3602
+ if (diff === 0) {
3603
+ return a.length - b3.length;
3604
+ }
3605
+ return diff;
3606
+ });
3607
+ let lastModifiedOffset = text.length;
3608
+ for (let i = sortedEdits.length - 1; i >= 0; i--) {
3609
+ let e2 = sortedEdits[i];
3610
+ if (e2.offset + e2.length <= lastModifiedOffset) {
3611
+ text = applyEdit(text, e2);
3612
+ } else {
3613
+ throw new Error("Overlapping edit");
3614
+ }
3615
+ lastModifiedOffset = e2.offset;
3616
+ }
3617
+ return text;
3618
+ }
3619
+
3620
+ // cli/src/writers/jsonc-edit.ts
3621
+ var PARSE_OPTIONS = { allowTrailingComma: true };
3622
+ var FORMATTING = { tabSize: 2, insertSpaces: true, eol: "\n" };
3623
+ function parseJsoncObject(text) {
3624
+ const errors = [];
3625
+ const value = parse2(text, errors, PARSE_OPTIONS);
3626
+ if (errors.length > 0 || typeof value !== "object" || value === null || Array.isArray(value)) return null;
3627
+ return value;
3628
+ }
3629
+ function isJsonObject(value) {
3630
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3631
+ }
3632
+ function valueAt(document, path) {
3633
+ let current = document;
3634
+ for (const segment of path) {
3635
+ if (!isJsonObject(current)) return void 0;
3636
+ current = current[segment];
3637
+ }
3638
+ return current;
3639
+ }
3640
+ function sameJson(left, right) {
3641
+ return JSON.stringify(left) === JSON.stringify(right);
3642
+ }
3643
+ function setJsonc(text, path, value, insertAt) {
3644
+ const current = valueAt(parse2(text, [], PARSE_OPTIONS), path);
3645
+ if (current !== void 0 && sameJson(current, value)) return text;
3646
+ return applyEdits(text, modify(text, path, value, { formattingOptions: FORMATTING, getInsertionIndex: insertAt }));
3647
+ }
3648
+ function nextToken(text, offset) {
3649
+ const scanner = createScanner2(text, true);
3650
+ scanner.setPosition(offset);
3651
+ scanner.scan();
3652
+ const start2 = scanner.getTokenOffset();
3653
+ return { offset: start2, end: start2 + scanner.getTokenLength() };
3654
+ }
3655
+ function isBlank(character) {
3656
+ return character === " " || character === " ";
3657
+ }
3658
+ function lineBreakAt(text, offset) {
3659
+ if (text.startsWith("\r\n", offset)) return 2;
3660
+ return text[offset] === "\n" ? 1 : 0;
3661
+ }
3662
+ function removal(text, start2, end) {
3663
+ let from = start2;
3664
+ while (isBlank(text[from - 1])) from -= 1;
3665
+ let to = end;
3666
+ while (isBlank(text[to])) to += 1;
3667
+ const startsLine = from === 0 || text[from - 1] === "\n";
3668
+ const endsLine = to === text.length || lineBreakAt(text, to) > 0;
3669
+ if (startsLine && endsLine) return { offset: from, length: to + lineBreakAt(text, to) - from, content: "" };
3670
+ if (endsLine) return { offset: from, length: to - from, content: "" };
3671
+ return { offset: start2, length: to - start2, content: "" };
3672
+ }
3673
+ function removeJsonc(text, path) {
3674
+ const root = parseTree2(text, [], PARSE_OPTIONS);
3675
+ const property = root === void 0 ? void 0 : findNodeAtLocation2(root, path)?.parent;
3676
+ const siblings = property?.parent?.children;
3677
+ if (property === void 0 || property.type !== "property" || siblings === void 0) return text;
3678
+ const end = property.offset + property.length;
3679
+ const following = nextToken(text, end);
3680
+ if (text[following.offset] === ",") return applyEdits(text, [removal(text, property.offset, following.end)]);
3681
+ const index = siblings.indexOf(property);
3682
+ if (index <= 0) return applyEdits(text, [removal(text, property.offset, end)]);
3683
+ const previous = siblings[index - 1];
3684
+ const comma = nextToken(text, previous.offset + previous.length);
3685
+ return applyEdits(text, [{ offset: comma.offset, length: comma.end - comma.offset, content: "" }, removal(text, property.offset, end)]);
3686
+ }
3687
+
3688
+ // cli/src/writers/opencode.ts
3689
+ var SCHEMA = "https://opencode.ai/config.json";
3690
+ var PROVIDER_PACKAGE = "@ai-sdk/openai-compatible";
3691
+ var PROVIDER_NAME = "unrestricted.sh";
3692
+ var OWN_PROVIDER_KEYS = ["npm", "name"];
3693
+ var OWN_OPTION_KEYS = ["baseURL", "apiKey"];
3694
+ var FIRST = () => 0;
3695
+ var AFTER_SCHEMA = (keys) => keys.indexOf("$schema") + 1;
3696
+ function withoutOwnModels(models2, config) {
3697
+ return Object.fromEntries(Object.entries(models2).filter(([model]) => !isOwnModel(model, config)));
3698
+ }
3699
+ function ownModel(config, id) {
3700
+ const model = config.models.find((listed) => listed.id === id);
3701
+ return model === void 0 ? {} : { name: model.name, limit: { context: model.context, output: model.maxOutput } };
3702
+ }
3703
+ function ownModels(config) {
3704
+ return Object.fromEntries(config.models.map((model) => [model.id, ownModel(config, model.id)]));
3705
+ }
3706
+ function ownProvider(config) {
3707
+ return {
3708
+ npm: PROVIDER_PACKAGE,
3709
+ name: PROVIDER_NAME,
3710
+ options: { baseURL: config.base, apiKey: config.key },
3711
+ models: ownModels(config)
3712
+ };
3713
+ }
3714
+ function isFile3(path) {
3715
+ try {
3716
+ return statSync3(path).isFile();
3717
+ } catch {
3718
+ return false;
3719
+ }
3720
+ }
3721
+ function writeJson(config, file) {
3722
+ const { value: settings, layout } = readJsonDocument(file);
3723
+ const schema = settings.$schema;
3724
+ settings.$schema = typeof schema === "string" && schema ? schema : SCHEMA;
3725
+ const providers = asObject(settings.provider);
3726
+ settings.provider = providers;
3727
+ const existing = asObject(providers[config.provider]);
3728
+ providers[config.provider] = {
3729
+ ...existing,
3730
+ npm: PROVIDER_PACKAGE,
3731
+ name: PROVIDER_NAME,
3732
+ options: { ...asObject(existing.options), baseURL: config.base, apiKey: config.key },
3733
+ models: { ...withoutOwnModels(asObject(existing.models), config), ...ownModels(config) }
3734
+ };
3735
+ settings.model = `${config.provider}/${config.model}`;
3736
+ writeJsonDocument(file, settings, layout);
3737
+ setMode(file, 384, config.platform);
3738
+ return { path: file, next: "opencode" };
3739
+ }
3740
+ function withOwnModels(text, config, models2) {
3741
+ const path = ["provider", config.provider, "models"];
3742
+ let updated = text;
3743
+ for (const id of Object.keys(models2)) {
3744
+ const listed = config.models.some((model) => model.id === id);
3745
+ if (isOwnModel(id, config) && !listed) updated = removeJsonc(updated, [...path, id]);
3746
+ }
3747
+ let previous;
3748
+ for (const model of config.models) {
3749
+ const after = previous;
3750
+ const insertAt = (keys) => after === void 0 ? 0 : keys.indexOf(after) + 1;
3751
+ updated = setJsonc(updated, [...path, model.id], ownModel(config, model.id), insertAt);
3752
+ previous = model.id;
3753
+ }
3754
+ return updated;
3755
+ }
3756
+ function withOwnProvider(text, config, settings) {
3757
+ const providers = settings.provider;
3758
+ const path = ["provider", config.provider];
3759
+ if (!isJsonObject(providers)) return setJsonc(text, ["provider"], { [config.provider]: ownProvider(config) }, AFTER_SCHEMA);
3760
+ const existing = providers[config.provider];
3761
+ if (!isJsonObject(existing)) return setJsonc(text, path, ownProvider(config), FIRST);
3762
+ let updated = setJsonc(text, [...path, "npm"], PROVIDER_PACKAGE, FIRST);
3763
+ updated = setJsonc(updated, [...path, "name"], PROVIDER_NAME, (keys) => keys.indexOf("npm") + 1);
3764
+ if (isJsonObject(existing.options)) {
3765
+ updated = setJsonc(updated, [...path, "options", "baseURL"], config.base, FIRST);
3766
+ updated = setJsonc(updated, [...path, "options", "apiKey"], config.key, (keys) => keys.indexOf("baseURL") + 1);
3767
+ } else {
3768
+ updated = setJsonc(updated, [...path, "options"], { baseURL: config.base, apiKey: config.key }, FIRST);
3769
+ }
3770
+ if (isJsonObject(existing.models)) return withOwnModels(updated, config, existing.models);
3771
+ return setJsonc(updated, [...path, "models"], ownModels(config), FIRST);
3772
+ }
3773
+ function ownJsonPaths(settings, config) {
3774
+ const paths = [];
3775
+ const model = settings.model;
3776
+ const prefix = `${config.provider}/`;
3777
+ if (typeof model === "string" && model.startsWith(prefix) && isOwnModel(model.slice(prefix.length), config)) paths.push(["model"]);
3778
+ const providers = asObject(settings.provider);
3779
+ const entry = providers[config.provider];
3780
+ if (!isJsonObject(entry)) return paths;
3781
+ const path = ["provider", config.provider];
3782
+ const options = entry.options;
3783
+ const models2 = entry.models;
3784
+ const keptOptions = isJsonObject(options) ? Object.keys(options).filter((key) => !OWN_OPTION_KEYS.includes(key)) : [];
3785
+ const keptModels = isJsonObject(models2) ? Object.keys(models2).filter((id) => !isOwnModel(id, config)) : [];
3786
+ const keptKeys = Object.keys(entry).filter((key) => {
3787
+ if (OWN_PROVIDER_KEYS.includes(key)) return false;
3788
+ if (key === "options" && isJsonObject(options)) return keptOptions.length > 0;
3789
+ if (key === "models" && isJsonObject(models2)) return keptModels.length > 0;
3790
+ return true;
3791
+ });
3792
+ if (keptKeys.length === 0) {
3793
+ paths.push(Object.keys(providers).length === 1 ? ["provider"] : path);
3794
+ return paths;
3795
+ }
3796
+ for (const key of OWN_PROVIDER_KEYS) if (key in entry) paths.push([...path, key]);
3797
+ if (isJsonObject(options)) {
3798
+ if (keptOptions.length === 0) paths.push([...path, "options"]);
3799
+ else for (const key of OWN_OPTION_KEYS) if (key in options) paths.push([...path, "options", key]);
3800
+ }
3801
+ if (isJsonObject(models2)) {
3802
+ if (keptModels.length === 0) paths.push([...path, "models"]);
3803
+ else for (const id of Object.keys(models2)) if (isOwnModel(id, config)) paths.push([...path, "models", id]);
3804
+ }
3805
+ return paths;
3806
+ }
3807
+ function withoutOwnJsonEntries(file, config) {
3808
+ if (!isFile3(file)) return void 0;
3809
+ const raw = readFileSync9(file, "utf8");
3810
+ const original = withoutBom(raw);
3811
+ const settings = original.trim() === "" ? {} : parseJsoncObject(original);
3812
+ if (settings === null) return `${file} could not be read, so the setup left it as it is; OpenCode reads ${OPENCODE_JSONC_FILE} after it`;
3813
+ let updated = original;
3814
+ for (const path of ownJsonPaths(settings, config)) updated = removeJsonc(updated, path);
3815
+ if (updated !== original) writeFileSync10(file, withBom(updated, layoutOf(raw)));
3816
+ return void 0;
3817
+ }
3818
+ function writeJsonc(config, file, jsonFile) {
3819
+ const raw = readFileSync9(file, "utf8");
3820
+ const layout = layoutOf(raw);
3821
+ const original = withoutBom(raw);
3822
+ const text = original.trim() === "" ? `{}${layout.eol}` : original;
3823
+ const settings = parseJsoncObject(text);
3824
+ if (settings === null) throw new Error(`${file} is not a JSON object OpenCode can read; fix it, then run the setup again`);
3825
+ const schema = settings.$schema;
3826
+ let updated = typeof schema === "string" && schema ? text : setJsonc(text, ["$schema"], SCHEMA, FIRST);
3827
+ updated = withOwnProvider(updated, config, settings);
3828
+ updated = setJsonc(updated, ["model"], `${config.provider}/${config.model}`, AFTER_SCHEMA);
3829
+ const output = withBom(updated, layout);
3830
+ if (output !== raw) writeFileSync10(file, output);
3831
+ setMode(file, 384, config.platform);
3832
+ const hint = withoutOwnJsonEntries(jsonFile, config);
3833
+ return hint === void 0 ? { path: file, next: "opencode" } : { path: file, next: "opencode", hint };
3834
+ }
3835
+ function write6(config) {
3836
+ const paths = toolPaths(config);
3837
+ mkdirSync8(paths.opencodeDir, { recursive: true });
3838
+ if (isFile3(paths.opencodeJsonc)) return writeJsonc(config, paths.opencodeJsonc, paths.opencodeJson);
3839
+ return writeJson(config, paths.opencodeJson);
3840
+ }
3841
+
3842
+ // cli/src/writers/pi.ts
3843
+ import { mkdirSync as mkdirSync9 } from "node:fs";
3844
+ var PROVIDER_NAME2 = "unrestricted.sh";
3845
+ function isOwnEntry(entry, config) {
3846
+ const id = asObject(entry).id;
3847
+ return typeof id === "string" && isOwnModel(id, config);
3848
+ }
3849
+ function withOwnModels2(existing, config) {
3850
+ const models2 = Array.isArray(existing) ? existing : [];
3851
+ const firstOwn = models2.findIndex((entry) => isOwnEntry(entry, config));
3852
+ const kept = models2.filter((entry) => !isOwnEntry(entry, config));
3853
+ const own = config.models.map((model) => piModel(model.id, model.name, model.context, model.maxOutput));
3854
+ kept.splice(firstOwn === -1 ? kept.length : firstOwn, 0, ...own);
3855
+ return kept;
3856
+ }
3857
+ function withOwnProvider2(document, config) {
3858
+ const providers = asObject(document.providers);
3859
+ const existing = asObject(providers[config.provider]);
3860
+ const provider = {
3861
+ ...existing,
3862
+ name: PROVIDER_NAME2,
3863
+ baseUrl: config.base,
3864
+ api: PI_API,
3865
+ apiKey: config.key,
3866
+ models: withOwnModels2(existing.models, config)
3867
+ };
3868
+ return { ...document, providers: { ...providers, [config.provider]: provider } };
3869
+ }
3870
+ function write7(config) {
3871
+ const paths = toolPaths(config);
3872
+ mkdirSync9(paths.piAgentDir, { recursive: true });
3873
+ const models2 = readJsonDocument(paths.piModels);
3874
+ const settings = readJsonDocument(paths.piSettings);
3875
+ setMode(paths.piModels, 384, config.platform);
3876
+ writeJsonDocument(paths.piModels, withOwnProvider2(models2.value, config), models2.layout);
3877
+ writeJsonDocument(
3878
+ paths.piSettings,
3879
+ { ...settings.value, defaultProvider: config.provider, defaultModel: config.model },
3880
+ settings.layout
3881
+ );
3882
+ return { path: paths.piModels, next: "pi" };
3883
+ }
3884
+
3885
+ // cli/src/writers/index.ts
3886
+ var writers = {
3887
+ opencode: write6,
3888
+ codex: write3,
3889
+ aider: write,
3890
+ continue: write4,
3891
+ crush: write5,
3892
+ pi: write7,
3893
+ claude: write2
3894
+ };
3895
+
3896
+ // cli/src/configure.ts
3897
+ function recordOf(result) {
3898
+ switch (result.status) {
3899
+ case "written":
3900
+ case "current":
3901
+ return { path: result.path, sha256: result.sha256 };
3902
+ case "foreign":
3903
+ case "removed":
3904
+ case "unsupported":
3905
+ return null;
3906
+ case "failed":
3907
+ case "unknown":
3908
+ return void 0;
3909
+ }
3910
+ }
3911
+ function reportAutoUpdate(tool, result) {
3912
+ const message = autoUpdateMessage(tool, result);
3913
+ if (message !== null) M2[message.level](message.text);
3914
+ }
3915
+ function configureTools(config, tools, versionOf) {
3916
+ const steps = [];
3917
+ const autoUpdate = {};
3918
+ for (const tool of tools) {
3919
+ const label = TOOL_LABELS[tool];
3920
+ const step = Y2();
3921
+ step.start(`Configuring ${label}`);
3922
+ try {
3923
+ const result = writers[tool](config);
3924
+ const live = isAutoUpdateTool(tool) ? { tool, result: installAutoUpdate(tool, config, versionOf) } : null;
3925
+ step.stop(`Configuring ${label}`);
3926
+ M2.success(`${label} \xB7 ${result.path}`);
3927
+ if (result.hint) M2.warn(result.hint);
3928
+ if (live !== null) {
3929
+ reportAutoUpdate(live.tool, live.result);
3930
+ const record = recordOf(live.result);
3931
+ if (record !== void 0) autoUpdate[live.tool] = record;
3932
+ }
3933
+ steps.push(result.next);
3934
+ } catch (error) {
3935
+ step.stop(`${label} failed`);
3936
+ xe(reason(error));
3937
+ return null;
3938
+ }
3939
+ }
3940
+ return { steps, autoUpdate };
3941
+ }
3942
+ function rememberSetup(config, tools, autoUpdate) {
3943
+ try {
3944
+ const previous = readState(config.configHome);
3945
+ saveCredentials(config.configHome, { key: config.key, origin: config.origin });
3946
+ saveState(config.configHome, {
3947
+ tools: mergeTools(previous?.tools ?? [], tools),
3948
+ models: config.models.map((model) => model.id),
3949
+ model: config.model,
3950
+ autoUpdate: mergeAutoUpdate(previous?.autoUpdate ?? {}, autoUpdate)
3951
+ });
3952
+ } catch (error) {
3953
+ M2.warn(`could not save the setup in ${storeDir(config.configHome)}: ${reason(error)}`);
3954
+ }
3955
+ }
3956
+
3957
+ // cli/src/commands/setup.ts
3958
+ var SETUP_TIP = 'Tip: install the CLI with "npm i -g unrestricted", then run "unrestricted update" when new models come out.';
3959
+ async function chooseTools(context, detected) {
3960
+ const requested = context.env.UNRESTRICTED_TOOLS ?? "";
3961
+ if (requested.trim()) {
3962
+ const { tools, unknown, disabled } = parseTools(requested);
3963
+ for (const name of unknown) M2.warn(`unknown tool: ${name} (skipped)`);
3964
+ for (const tool of disabled) M2.warn(`${TOOL_LABELS[tool]} is not available yet`);
3965
+ return tools;
3966
+ }
3967
+ if (context.env.UNRESTRICTED_YES || !process.stdin.isTTY) return detected;
3968
+ const answer = await fe({
3969
+ message: "Which tools should use unrestricted.sh?",
3970
+ options: OFFERED_TOOLS.map((tool) => ({
3971
+ value: tool,
3972
+ label: TOOL_LABELS[tool],
3973
+ hint: detected.includes(tool) ? "detected" : "not found"
3974
+ })),
3975
+ initialValues: detected,
3976
+ required: false
3977
+ });
3978
+ return pD(answer) ? null : answer;
3979
+ }
3980
+ async function setup(context) {
3981
+ let pending;
3982
+ try {
3983
+ pending = readConfig(context.env, context.machine);
3984
+ } catch (error) {
3985
+ xe(reason(error));
3986
+ return FAILED;
3987
+ }
3988
+ Ie(SETUP_INTRO);
3989
+ let key = pending.key;
3990
+ let balanceNote;
3991
+ if (!key) {
3992
+ const signedIn = await signIn(pending.origin);
3993
+ if (!signedIn.ok) {
3994
+ xe(failureMessage(signedIn.reason, pending.origin, signedIn.message));
3995
+ return FAILED;
3996
+ }
3997
+ key = signedIn.key;
3998
+ balanceNote = signedIn.balanceNote;
3999
+ }
4000
+ const check = Y2();
4001
+ check.start("Checking your key");
4002
+ let listed;
4003
+ try {
4004
+ listed = await verifyKey(pending.base, key);
4005
+ } catch (error) {
4006
+ check.stop("Key check failed");
4007
+ xe(reason(error));
4008
+ return FAILED;
4009
+ }
4010
+ check.stop(keyAcceptedMessage(pending.base));
4011
+ const config = withListedModels({ ...pending, key }, listed);
4012
+ const listedIds = config.models.map((model) => model.id);
4013
+ const selected = await chooseTools(context, detectTools(config, context.env));
4014
+ if (selected === null) {
4015
+ xe("Nothing changed.");
4016
+ return { code: 0, listed: listedIds };
4017
+ }
4018
+ if (selected.length === 0) {
4019
+ Se("Nothing to configure.");
4020
+ return { code: 0, listed: listedIds };
4021
+ }
4022
+ const configured = configureTools(config, selected, versionReader(context.env, context.machine.platform));
4023
+ if (configured === null) return FAILED;
4024
+ rememberSetup(config, selected, configured.autoUpdate);
4025
+ if (balanceNote) M2.info(balanceNote);
4026
+ Me(configured.steps.join("\n"), "Next");
4027
+ if (!context.installed) M2.info(SETUP_TIP);
4028
+ Se(SETUP_OUTRO);
4029
+ return { code: 0, listed: listedIds };
4030
+ }
4031
+
4032
+ // cli/src/commands/update.ts
4033
+ var UPDATE_INTRO = "unrestricted.sh update";
4034
+ var NO_TOOLS_MESSAGE = 'No tools are set up yet. Run "unrestricted setup" to configure them.';
4035
+ var NO_KEY_MESSAGE2 = 'No key is stored. Run "unrestricted setup" to sign in and configure your tools.';
4036
+ function selectedModel(env, pending, state, listed) {
4037
+ if (env.UNRESTRICTED_MODEL || state.model === null) return pending.model;
4038
+ return listed.some((model) => model.id === state.model) ? state.model : pending.model;
4039
+ }
4040
+ async function update(context) {
4041
+ let pending;
4042
+ try {
4043
+ pending = readConfig(context.env, context.machine);
4044
+ } catch (error) {
4045
+ xe(reason(error));
4046
+ return FAILED;
4047
+ }
4048
+ const state = readState(pending.configHome);
4049
+ if (state === null || state.tools.length === 0) {
4050
+ xe(NO_TOOLS_MESSAGE);
4051
+ return FAILED;
4052
+ }
4053
+ const key = keyFor(pending);
4054
+ if (key === null) {
4055
+ xe(NO_KEY_MESSAGE2);
4056
+ return FAILED;
4057
+ }
4058
+ Ie(UPDATE_INTRO);
4059
+ const check = Y2();
4060
+ check.start("Checking your key");
4061
+ let listed;
4062
+ try {
4063
+ listed = await verifyKey(pending.base, key);
4064
+ } catch (error) {
4065
+ check.stop("Key check failed");
4066
+ xe(reason(error));
4067
+ return FAILED;
4068
+ }
4069
+ check.stop(keyAcceptedMessage(pending.base));
4070
+ const config = withListedModels({ ...pending, key, model: selectedModel(context.env, pending, state, listed) }, listed);
4071
+ for (const tool of state.tools.filter((tool2) => DISABLED_TOOLS.has(tool2))) M2.warn(`${TOOL_LABELS[tool]} is not available yet`);
4072
+ const tools = state.tools.filter((tool) => !DISABLED_TOOLS.has(tool));
4073
+ const configured = configureTools(config, tools, versionReader(context.env, context.machine.platform));
4074
+ if (configured === null) return FAILED;
4075
+ rememberSetup(config, tools, configured.autoUpdate);
4076
+ const added = config.models.filter((model) => !state.models.includes(model.id));
4077
+ if (added.length > 0) M2.info(`New: ${added.map((model) => model.name).join(", ")}`);
4078
+ Se(SETUP_OUTRO);
4079
+ return { code: 0, listed: config.models.map((model) => model.id) };
4080
+ }
4081
+
4082
+ // cli/src/notice.ts
4083
+ var NOTICE_TIMEOUT_MS = 5e3;
4084
+ function newModelCount(state, listed) {
4085
+ return listed.filter((id) => !state.models.includes(id)).length;
4086
+ }
4087
+ function newModelsNotice(count) {
4088
+ return `${count} new model(s) available: run unrestricted update`;
4089
+ }
4090
+ async function publicModelIds(base) {
4091
+ try {
4092
+ return (await fetchModelCatalog(base, NOTICE_TIMEOUT_MS)).map((model) => model.id);
4093
+ } catch {
4094
+ return null;
4095
+ }
4096
+ }
4097
+ async function announceNewModels(context, listed) {
4098
+ let pending;
4099
+ try {
4100
+ pending = readConfig(context.env, context.machine);
4101
+ } catch {
4102
+ return;
4103
+ }
4104
+ const state = readState(pending.configHome);
4105
+ if (state === null) return;
4106
+ const ids = listed ?? await publicModelIds(pending.base);
4107
+ if (ids === null) return;
4108
+ const count = newModelCount(state, ids);
4109
+ if (count > 0) context.warn(`${newModelsNotice(count)}
4110
+ `);
4111
+ }
4112
+
4113
+ // cli/package.json
4114
+ var version = "1.0.0";
4115
+
4116
+ // cli/src/version.ts
4117
+ var VERSION = version;
4118
+
4119
+ // cli/src/cli.ts
4120
+ var COMMAND_NAMES = ["setup", "update", "models", "balance", "login", "logout"];
4121
+ var COMMANDS = { setup, update, models, balance, login, logout };
4122
+ var HELP_FLAGS = ["-h", "--help"];
4123
+ var VERSION_FLAGS = ["-v", "--version"];
4124
+ var HELP_HINT = 'Run "unrestricted --help" for the commands.';
4125
+ function isCommandName(value) {
4126
+ return COMMAND_NAMES.includes(value);
4127
+ }
4128
+ function helpText() {
4129
+ return [
4130
+ `unrestricted ${VERSION}`,
4131
+ "",
4132
+ "Sets up your coding tools for unrestricted.sh, keeps their model lists current, and shows your credit.",
4133
+ "",
4134
+ "Usage: unrestricted [command]",
4135
+ "",
4136
+ "Commands:",
4137
+ " setup Configure your coding tools (the default)",
4138
+ " update Rewrite the tools you set up with the current models and your stored key",
4139
+ " models List the models with their context and prices per million tokens",
4140
+ " balance Show your credit, your plan's usage and this month's spend",
4141
+ " login Approve this machine in the browser and store its key",
4142
+ " logout Delete the stored key",
4143
+ "",
4144
+ "Options:",
4145
+ " -h, --help Show this help",
4146
+ " -v, --version Print the version",
4147
+ "",
4148
+ "Files:",
4149
+ " ~/.config/unrestricted/credentials.json the stored key",
4150
+ " ~/.config/unrestricted/state.json the tools and models you set up",
4151
+ " (in $XDG_CONFIG_HOME/unrestricted when it is set; ~ is %USERPROFILE% on Windows)",
4152
+ "",
4153
+ "Environment:",
4154
+ " UNRESTRICTED_API_KEY an unr_sk_ key to use instead of the stored key or the browser approval",
4155
+ " UNRESTRICTED_ORIGIN app used for the approval, default https://unrestricted.sh",
4156
+ " UNRESTRICTED_BASE_URL api base url, default https://api.unrestricted.sh/v1",
4157
+ " UNRESTRICTED_MODEL model id the tools start on",
4158
+ " UNRESTRICTED_MODEL_NAME its display name, if the API does not list it",
4159
+ " UNRESTRICTED_TOOLS comma separated tools for setup, skips the prompt",
4160
+ " UNRESTRICTED_YES set up every detected tool without prompting",
4161
+ "",
4162
+ "Without installing:",
4163
+ ' sh -c "$(curl -fsSL https://unrestricted.sh/setup.sh)" macOS and Linux',
4164
+ " irm https://unrestricted.sh/setup.ps1 | iex Windows PowerShell",
4165
+ "",
4166
+ `Tools: ${OFFERED_TOOLS.join(", ")}`,
4167
+ ""
4168
+ ].join("\n");
4169
+ }
4170
+ function parseArguments(argv) {
4171
+ if (argv.some((argument) => HELP_FLAGS.includes(argument))) return { kind: "help" };
4172
+ if (argv.some((argument) => VERSION_FLAGS.includes(argument))) return { kind: "version" };
4173
+ const option = argv.find((argument) => argument.startsWith("-"));
4174
+ if (option !== void 0) return { kind: "error", message: `unknown option: ${option}. ${HELP_HINT}` };
4175
+ const [name = "setup", extra] = argv;
4176
+ if (!isCommandName(name)) return { kind: "error", message: `unknown command: ${name}. ${HELP_HINT}` };
4177
+ if (extra !== void 0) return { kind: "error", message: `unexpected argument: ${extra}. ${HELP_HINT}` };
4178
+ return { kind: "command", name };
4179
+ }
4180
+ async function runCli(argv, context) {
4181
+ const parsed = parseArguments(argv);
4182
+ if (parsed.kind === "help") {
4183
+ context.write(helpText());
4184
+ return 0;
4185
+ }
4186
+ if (parsed.kind === "version") {
4187
+ context.write(`${VERSION}
4188
+ `);
4189
+ return 0;
4190
+ }
4191
+ if (parsed.kind === "error") {
4192
+ context.warn(`${parsed.message}
4193
+ `);
4194
+ return 1;
4195
+ }
4196
+ const result = await COMMANDS[parsed.name](context);
4197
+ if (result.code === 0 && parsed.name !== "logout") await announceNewModels(context, result.listed);
4198
+ return result.code;
4199
+ }
4200
+ function start(installed) {
4201
+ const context = {
4202
+ env: process.env,
4203
+ machine: THIS_MACHINE,
4204
+ installed,
4205
+ write: (text) => {
4206
+ process.stdout.write(text);
4207
+ },
4208
+ warn: (text) => {
4209
+ process.stderr.write(text);
4210
+ }
4211
+ };
4212
+ runCli(process.argv.slice(2), context).then((code) => {
4213
+ process.exitCode = code;
4214
+ }).catch((error) => {
4215
+ xe(reason(error));
4216
+ process.exitCode = 1;
4217
+ });
4218
+ }
4219
+
4220
+ // cli/src/bin.ts
4221
+ start(true);