@openape/ape-agent 2.9.2 → 2.11.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,4440 @@
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 __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __commonJS = (cb, mod) => function __require() {
12
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ };
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
+ // If the importer is in node compatibility mode or this is not an ESM
28
+ // file that has been converted to a CommonJS file using a Babel-
29
+ // compatible transform (i.e. "__esModule" has not been set), then set
30
+ // "default" to the CommonJS "module.exports" for node compatibility.
31
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
+ mod
33
+ ));
34
+
35
+ // ../../packages/apes/dist/chunk-OBF7IMQ2.js
36
+ import { homedir as homedir2 } from "os";
37
+ import { join as join2 } from "path";
38
+ var CONFIG_DIR2, AUTH_FILE, CONFIG_FILE;
39
+ var init_chunk_OBF7IMQ2 = __esm({
40
+ "../../packages/apes/dist/chunk-OBF7IMQ2.js"() {
41
+ "use strict";
42
+ CONFIG_DIR2 = join2(homedir2(), ".config", "apes");
43
+ AUTH_FILE = join2(CONFIG_DIR2, "auth.json");
44
+ CONFIG_FILE = join2(CONFIG_DIR2, "config.toml");
45
+ }
46
+ });
47
+
48
+ // ../../node_modules/.pnpm/consola@3.4.2/node_modules/consola/dist/chunks/prompt.mjs
49
+ var prompt_exports = {};
50
+ __export(prompt_exports, {
51
+ kCancel: () => kCancel,
52
+ prompt: () => prompt
53
+ });
54
+ import "util";
55
+ import g, { stdin, stdout } from "process";
56
+ import f from "readline";
57
+ import { WriteStream } from "tty";
58
+ function getDefaultExportFromCjs(x2) {
59
+ return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
60
+ }
61
+ function requireSrc() {
62
+ if (hasRequiredSrc) return src;
63
+ hasRequiredSrc = 1;
64
+ const ESC = "\x1B";
65
+ const CSI = `${ESC}[`;
66
+ const beep = "\x07";
67
+ const cursor = {
68
+ to(x2, y3) {
69
+ if (!y3) return `${CSI}${x2 + 1}G`;
70
+ return `${CSI}${y3 + 1};${x2 + 1}H`;
71
+ },
72
+ move(x2, y3) {
73
+ let ret = "";
74
+ if (x2 < 0) ret += `${CSI}${-x2}D`;
75
+ else if (x2 > 0) ret += `${CSI}${x2}C`;
76
+ if (y3 < 0) ret += `${CSI}${-y3}A`;
77
+ else if (y3 > 0) ret += `${CSI}${y3}B`;
78
+ return ret;
79
+ },
80
+ up: (count = 1) => `${CSI}${count}A`,
81
+ down: (count = 1) => `${CSI}${count}B`,
82
+ forward: (count = 1) => `${CSI}${count}C`,
83
+ backward: (count = 1) => `${CSI}${count}D`,
84
+ nextLine: (count = 1) => `${CSI}E`.repeat(count),
85
+ prevLine: (count = 1) => `${CSI}F`.repeat(count),
86
+ left: `${CSI}G`,
87
+ hide: `${CSI}?25l`,
88
+ show: `${CSI}?25h`,
89
+ save: `${ESC}7`,
90
+ restore: `${ESC}8`
91
+ };
92
+ const scroll = {
93
+ up: (count = 1) => `${CSI}S`.repeat(count),
94
+ down: (count = 1) => `${CSI}T`.repeat(count)
95
+ };
96
+ const erase = {
97
+ screen: `${CSI}2J`,
98
+ up: (count = 1) => `${CSI}1J`.repeat(count),
99
+ down: (count = 1) => `${CSI}J`.repeat(count),
100
+ line: `${CSI}2K`,
101
+ lineEnd: `${CSI}K`,
102
+ lineStart: `${CSI}1K`,
103
+ lines(count) {
104
+ let clear = "";
105
+ for (let i2 = 0; i2 < count; i2++)
106
+ clear += this.line + (i2 < count - 1 ? cursor.up() : "");
107
+ if (count)
108
+ clear += cursor.left;
109
+ return clear;
110
+ }
111
+ };
112
+ src = { cursor, scroll, erase, beep };
113
+ return src;
114
+ }
115
+ function requirePicocolors() {
116
+ if (hasRequiredPicocolors) return picocolors.exports;
117
+ hasRequiredPicocolors = 1;
118
+ let p = process || {}, argv2 = p.argv || [], env2 = p.env || {};
119
+ let isColorSupported2 = !(!!env2.NO_COLOR || argv2.includes("--no-color")) && (!!env2.FORCE_COLOR || argv2.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env2.TERM !== "dumb" || !!env2.CI);
120
+ let formatter = (open, close, replace = open) => (input) => {
121
+ let string = "" + input, index = string.indexOf(close, open.length);
122
+ return ~index ? open + replaceClose2(string, close, replace, index) + close : open + string + close;
123
+ };
124
+ let replaceClose2 = (string, close, replace, index) => {
125
+ let result = "", cursor = 0;
126
+ do {
127
+ result += string.substring(cursor, index) + replace;
128
+ cursor = index + close.length;
129
+ index = string.indexOf(close, cursor);
130
+ } while (~index);
131
+ return result + string.substring(cursor);
132
+ };
133
+ let createColors2 = (enabled = isColorSupported2) => {
134
+ let f3 = enabled ? formatter : () => String;
135
+ return {
136
+ isColorSupported: enabled,
137
+ reset: f3("\x1B[0m", "\x1B[0m"),
138
+ bold: f3("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
139
+ dim: f3("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
140
+ italic: f3("\x1B[3m", "\x1B[23m"),
141
+ underline: f3("\x1B[4m", "\x1B[24m"),
142
+ inverse: f3("\x1B[7m", "\x1B[27m"),
143
+ hidden: f3("\x1B[8m", "\x1B[28m"),
144
+ strikethrough: f3("\x1B[9m", "\x1B[29m"),
145
+ black: f3("\x1B[30m", "\x1B[39m"),
146
+ red: f3("\x1B[31m", "\x1B[39m"),
147
+ green: f3("\x1B[32m", "\x1B[39m"),
148
+ yellow: f3("\x1B[33m", "\x1B[39m"),
149
+ blue: f3("\x1B[34m", "\x1B[39m"),
150
+ magenta: f3("\x1B[35m", "\x1B[39m"),
151
+ cyan: f3("\x1B[36m", "\x1B[39m"),
152
+ white: f3("\x1B[37m", "\x1B[39m"),
153
+ gray: f3("\x1B[90m", "\x1B[39m"),
154
+ bgBlack: f3("\x1B[40m", "\x1B[49m"),
155
+ bgRed: f3("\x1B[41m", "\x1B[49m"),
156
+ bgGreen: f3("\x1B[42m", "\x1B[49m"),
157
+ bgYellow: f3("\x1B[43m", "\x1B[49m"),
158
+ bgBlue: f3("\x1B[44m", "\x1B[49m"),
159
+ bgMagenta: f3("\x1B[45m", "\x1B[49m"),
160
+ bgCyan: f3("\x1B[46m", "\x1B[49m"),
161
+ bgWhite: f3("\x1B[47m", "\x1B[49m"),
162
+ blackBright: f3("\x1B[90m", "\x1B[39m"),
163
+ redBright: f3("\x1B[91m", "\x1B[39m"),
164
+ greenBright: f3("\x1B[92m", "\x1B[39m"),
165
+ yellowBright: f3("\x1B[93m", "\x1B[39m"),
166
+ blueBright: f3("\x1B[94m", "\x1B[39m"),
167
+ magentaBright: f3("\x1B[95m", "\x1B[39m"),
168
+ cyanBright: f3("\x1B[96m", "\x1B[39m"),
169
+ whiteBright: f3("\x1B[97m", "\x1B[39m"),
170
+ bgBlackBright: f3("\x1B[100m", "\x1B[49m"),
171
+ bgRedBright: f3("\x1B[101m", "\x1B[49m"),
172
+ bgGreenBright: f3("\x1B[102m", "\x1B[49m"),
173
+ bgYellowBright: f3("\x1B[103m", "\x1B[49m"),
174
+ bgBlueBright: f3("\x1B[104m", "\x1B[49m"),
175
+ bgMagentaBright: f3("\x1B[105m", "\x1B[49m"),
176
+ bgCyanBright: f3("\x1B[106m", "\x1B[49m"),
177
+ bgWhiteBright: f3("\x1B[107m", "\x1B[49m")
178
+ };
179
+ };
180
+ picocolors.exports = createColors2();
181
+ picocolors.exports.createColors = createColors2;
182
+ return picocolors.exports;
183
+ }
184
+ function J({ onlyFirst: t2 = false } = {}) {
185
+ const F3 = ["[\\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("|");
186
+ return new RegExp(F3, t2 ? void 0 : "g");
187
+ }
188
+ function T$1(t2) {
189
+ if (typeof t2 != "string") throw new TypeError(`Expected a \`string\`, got \`${typeof t2}\``);
190
+ return t2.replace(Q, "");
191
+ }
192
+ function O(t2) {
193
+ return t2 && t2.__esModule && Object.prototype.hasOwnProperty.call(t2, "default") ? t2.default : t2;
194
+ }
195
+ function A$1(t2, u3 = {}) {
196
+ if (typeof t2 != "string" || t2.length === 0 || (u3 = { ambiguousIsNarrow: true, ...u3 }, t2 = T$1(t2), t2.length === 0)) return 0;
197
+ t2 = t2.replace(FD(), " ");
198
+ const F3 = u3.ambiguousIsNarrow ? 1 : 2;
199
+ let e2 = 0;
200
+ for (const s2 of t2) {
201
+ const i2 = s2.codePointAt(0);
202
+ if (i2 <= 31 || i2 >= 127 && i2 <= 159 || i2 >= 768 && i2 <= 879) continue;
203
+ switch (DD.eastAsianWidth(s2)) {
204
+ case "F":
205
+ case "W":
206
+ e2 += 2;
207
+ break;
208
+ case "A":
209
+ e2 += F3;
210
+ break;
211
+ default:
212
+ e2 += 1;
213
+ }
214
+ }
215
+ return e2;
216
+ }
217
+ function sD() {
218
+ const t2 = /* @__PURE__ */ new Map();
219
+ for (const [u3, F3] of Object.entries(r)) {
220
+ for (const [e2, s2] of Object.entries(F3)) r[e2] = { open: `\x1B[${s2[0]}m`, close: `\x1B[${s2[1]}m` }, F3[e2] = r[e2], t2.set(s2[0], s2[1]);
221
+ Object.defineProperty(r, u3, { value: F3, enumerable: false });
222
+ }
223
+ return Object.defineProperty(r, "codes", { value: t2, enumerable: false }), r.color.close = "\x1B[39m", r.bgColor.close = "\x1B[49m", r.color.ansi = L$1(), r.color.ansi256 = N(), r.color.ansi16m = I(), r.bgColor.ansi = L$1(m), r.bgColor.ansi256 = N(m), r.bgColor.ansi16m = I(m), Object.defineProperties(r, { rgbToAnsi256: { value: (u3, F3, e2) => u3 === F3 && F3 === e2 ? u3 < 8 ? 16 : u3 > 248 ? 231 : Math.round((u3 - 8) / 247 * 24) + 232 : 16 + 36 * Math.round(u3 / 255 * 5) + 6 * Math.round(F3 / 255 * 5) + Math.round(e2 / 255 * 5), enumerable: false }, hexToRgb: { value: (u3) => {
224
+ const F3 = /[a-f\d]{6}|[a-f\d]{3}/i.exec(u3.toString(16));
225
+ if (!F3) return [0, 0, 0];
226
+ let [e2] = F3;
227
+ e2.length === 3 && (e2 = [...e2].map((i2) => i2 + i2).join(""));
228
+ const s2 = Number.parseInt(e2, 16);
229
+ return [s2 >> 16 & 255, s2 >> 8 & 255, s2 & 255];
230
+ }, enumerable: false }, hexToAnsi256: { value: (u3) => r.rgbToAnsi256(...r.hexToRgb(u3)), enumerable: false }, ansi256ToAnsi: { value: (u3) => {
231
+ if (u3 < 8) return 30 + u3;
232
+ if (u3 < 16) return 90 + (u3 - 8);
233
+ let F3, e2, s2;
234
+ if (u3 >= 232) F3 = ((u3 - 232) * 10 + 8) / 255, e2 = F3, s2 = F3;
235
+ else {
236
+ u3 -= 16;
237
+ const C3 = u3 % 36;
238
+ F3 = Math.floor(u3 / 36) / 5, e2 = Math.floor(C3 / 6) / 5, s2 = C3 % 6 / 5;
239
+ }
240
+ const i2 = Math.max(F3, e2, s2) * 2;
241
+ if (i2 === 0) return 30;
242
+ let D2 = 30 + (Math.round(s2) << 2 | Math.round(e2) << 1 | Math.round(F3));
243
+ return i2 === 2 && (D2 += 60), D2;
244
+ }, enumerable: false }, rgbToAnsi: { value: (u3, F3, e2) => r.ansi256ToAnsi(r.rgbToAnsi256(u3, F3, e2)), enumerable: false }, hexToAnsi: { value: (u3) => r.ansi256ToAnsi(r.hexToAnsi256(u3)), enumerable: false } }), r;
245
+ }
246
+ function G(t2, u3, F3) {
247
+ return String(t2).normalize().replace(/\r\n/g, `
248
+ `).split(`
249
+ `).map((e2) => oD(e2, u3, F3)).join(`
250
+ `);
251
+ }
252
+ function k$1(t2, u3) {
253
+ if (typeof t2 == "string") return c.aliases.get(t2) === u3;
254
+ for (const F3 of t2) if (F3 !== void 0 && k$1(F3, u3)) return true;
255
+ return false;
256
+ }
257
+ function lD(t2, u3) {
258
+ if (t2 === u3) return;
259
+ const F3 = t2.split(`
260
+ `), e2 = u3.split(`
261
+ `), s2 = [];
262
+ for (let i2 = 0; i2 < Math.max(F3.length, e2.length); i2++) F3[i2] !== e2[i2] && s2.push(i2);
263
+ return s2;
264
+ }
265
+ function d$1(t2, u3) {
266
+ const F3 = t2;
267
+ F3.isTTY && F3.setRawMode(u3);
268
+ }
269
+ function ce() {
270
+ return g.platform !== "win32" ? g.env.TERM !== "linux" : !!g.env.CI || !!g.env.WT_SESSION || !!g.env.TERMINUS_SUBLIME || g.env.ConEmuTask === "{cmd::Cmder}" || g.env.TERM_PROGRAM === "Terminus-Sublime" || g.env.TERM_PROGRAM === "vscode" || g.env.TERM === "xterm-256color" || g.env.TERM === "alacritty" || g.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
271
+ }
272
+ async function prompt(message, opts = {}) {
273
+ const handleCancel = (value) => {
274
+ if (typeof value !== "symbol" || value.toString() !== "Symbol(clack:cancel)") {
275
+ return value;
276
+ }
277
+ switch (opts.cancel) {
278
+ case "reject": {
279
+ const error = new Error("Prompt cancelled.");
280
+ error.name = "ConsolaPromptCancelledError";
281
+ if (Error.captureStackTrace) {
282
+ Error.captureStackTrace(error, prompt);
283
+ }
284
+ throw error;
285
+ }
286
+ case "undefined": {
287
+ return void 0;
288
+ }
289
+ case "null": {
290
+ return null;
291
+ }
292
+ case "symbol": {
293
+ return kCancel;
294
+ }
295
+ default:
296
+ case "default": {
297
+ return opts.default ?? opts.initial;
298
+ }
299
+ }
300
+ };
301
+ if (!opts.type || opts.type === "text") {
302
+ return await he({
303
+ message,
304
+ defaultValue: opts.default,
305
+ placeholder: opts.placeholder,
306
+ initialValue: opts.initial
307
+ }).then(handleCancel);
308
+ }
309
+ if (opts.type === "confirm") {
310
+ return await ye({
311
+ message,
312
+ initialValue: opts.initial
313
+ }).then(handleCancel);
314
+ }
315
+ if (opts.type === "select") {
316
+ return await ve({
317
+ message,
318
+ options: opts.options.map(
319
+ (o3) => typeof o3 === "string" ? { value: o3, label: o3 } : o3
320
+ ),
321
+ initialValue: opts.initial
322
+ }).then(handleCancel);
323
+ }
324
+ if (opts.type === "multiselect") {
325
+ return await fe({
326
+ message,
327
+ options: opts.options.map(
328
+ (o3) => typeof o3 === "string" ? { value: o3, label: o3 } : o3
329
+ ),
330
+ required: opts.required,
331
+ initialValues: opts.initial
332
+ }).then(handleCancel);
333
+ }
334
+ throw new Error(`Unknown prompt type: ${opts.type}`);
335
+ }
336
+ var src, hasRequiredSrc, srcExports, picocolors, hasRequiredPicocolors, picocolorsExports, e, Q, P$1, X, DD, uD, FD, m, L$1, N, I, r, tD, eD, iD, v, CD, w$1, W$1, rD, R, y, V$1, z, ED, _, nD, oD, aD, c, S, AD, pD, h, x, fD, bD, mD, Y, wD, SD, $D, q, jD, PD, V, u, le, L, W, C, o, d, k, P, A, T, F, w, B, he, ye, ve, fe, kCancel;
337
+ var init_prompt = __esm({
338
+ "../../node_modules/.pnpm/consola@3.4.2/node_modules/consola/dist/chunks/prompt.mjs"() {
339
+ "use strict";
340
+ srcExports = requireSrc();
341
+ picocolors = { exports: {} };
342
+ picocolorsExports = /* @__PURE__ */ requirePicocolors();
343
+ e = /* @__PURE__ */ getDefaultExportFromCjs(picocolorsExports);
344
+ Q = J();
345
+ P$1 = { exports: {} };
346
+ (function(t2) {
347
+ var u3 = {};
348
+ t2.exports = u3, u3.eastAsianWidth = function(e2) {
349
+ var s2 = e2.charCodeAt(0), i2 = e2.length == 2 ? e2.charCodeAt(1) : 0, D2 = s2;
350
+ return 55296 <= s2 && s2 <= 56319 && 56320 <= i2 && i2 <= 57343 && (s2 &= 1023, i2 &= 1023, D2 = s2 << 10 | i2, 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";
351
+ }, u3.characterLength = function(e2) {
352
+ var s2 = this.eastAsianWidth(e2);
353
+ return s2 == "F" || s2 == "W" || s2 == "A" ? 2 : 1;
354
+ };
355
+ function F3(e2) {
356
+ return e2.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || [];
357
+ }
358
+ u3.length = function(e2) {
359
+ for (var s2 = F3(e2), i2 = 0, D2 = 0; D2 < s2.length; D2++) i2 = i2 + this.characterLength(s2[D2]);
360
+ return i2;
361
+ }, u3.slice = function(e2, s2, i2) {
362
+ textLen = u3.length(e2), s2 = s2 || 0, i2 = i2 || 1, s2 < 0 && (s2 = textLen + s2), i2 < 0 && (i2 = textLen + i2);
363
+ for (var D2 = "", C3 = 0, o3 = F3(e2), E = 0; E < o3.length; E++) {
364
+ var a2 = o3[E], n2 = u3.length(a2);
365
+ if (C3 >= s2 - (n2 == 2 ? 1 : 0)) if (C3 + n2 <= i2) D2 += a2;
366
+ else break;
367
+ C3 += n2;
368
+ }
369
+ return D2;
370
+ };
371
+ })(P$1);
372
+ X = P$1.exports;
373
+ DD = O(X);
374
+ uD = function() {
375
+ 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;
376
+ };
377
+ FD = O(uD);
378
+ m = 10;
379
+ L$1 = (t2 = 0) => (u3) => `\x1B[${u3 + t2}m`;
380
+ N = (t2 = 0) => (u3) => `\x1B[${38 + t2};5;${u3}m`;
381
+ I = (t2 = 0) => (u3, F3, e2) => `\x1B[${38 + t2};2;${u3};${F3};${e2}m`;
382
+ 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] } };
383
+ Object.keys(r.modifier);
384
+ tD = Object.keys(r.color);
385
+ eD = Object.keys(r.bgColor);
386
+ [...tD, ...eD];
387
+ iD = sD();
388
+ v = /* @__PURE__ */ new Set(["\x1B", "\x9B"]);
389
+ CD = 39;
390
+ w$1 = "\x07";
391
+ W$1 = "[";
392
+ rD = "]";
393
+ R = "m";
394
+ y = `${rD}8;;`;
395
+ V$1 = (t2) => `${v.values().next().value}${W$1}${t2}${R}`;
396
+ z = (t2) => `${v.values().next().value}${y}${t2}${w$1}`;
397
+ ED = (t2) => t2.split(" ").map((u3) => A$1(u3));
398
+ _ = (t2, u3, F3) => {
399
+ const e2 = [...u3];
400
+ let s2 = false, i2 = false, D2 = A$1(T$1(t2[t2.length - 1]));
401
+ for (const [C3, o3] of e2.entries()) {
402
+ const E = A$1(o3);
403
+ if (D2 + E <= F3 ? t2[t2.length - 1] += o3 : (t2.push(o3), D2 = 0), v.has(o3) && (s2 = true, i2 = e2.slice(C3 + 1).join("").startsWith(y)), s2) {
404
+ i2 ? o3 === w$1 && (s2 = false, i2 = false) : o3 === R && (s2 = false);
405
+ continue;
406
+ }
407
+ D2 += E, D2 === F3 && C3 < e2.length - 1 && (t2.push(""), D2 = 0);
408
+ }
409
+ !D2 && t2[t2.length - 1].length > 0 && t2.length > 1 && (t2[t2.length - 2] += t2.pop());
410
+ };
411
+ nD = (t2) => {
412
+ const u3 = t2.split(" ");
413
+ let F3 = u3.length;
414
+ for (; F3 > 0 && !(A$1(u3[F3 - 1]) > 0); ) F3--;
415
+ return F3 === u3.length ? t2 : u3.slice(0, F3).join(" ") + u3.slice(F3).join("");
416
+ };
417
+ oD = (t2, u3, F3 = {}) => {
418
+ if (F3.trim !== false && t2.trim() === "") return "";
419
+ let e2 = "", s2, i2;
420
+ const D2 = ED(t2);
421
+ let C3 = [""];
422
+ for (const [E, a2] of t2.split(" ").entries()) {
423
+ F3.trim !== false && (C3[C3.length - 1] = C3[C3.length - 1].trimStart());
424
+ let n2 = A$1(C3[C3.length - 1]);
425
+ if (E !== 0 && (n2 >= u3 && (F3.wordWrap === false || F3.trim === false) && (C3.push(""), n2 = 0), (n2 > 0 || F3.trim === false) && (C3[C3.length - 1] += " ", n2++)), F3.hard && D2[E] > u3) {
426
+ const B2 = u3 - n2, p = 1 + Math.floor((D2[E] - B2 - 1) / u3);
427
+ Math.floor((D2[E] - 1) / u3) < p && C3.push(""), _(C3, a2, u3);
428
+ continue;
429
+ }
430
+ if (n2 + D2[E] > u3 && n2 > 0 && D2[E] > 0) {
431
+ if (F3.wordWrap === false && n2 < u3) {
432
+ _(C3, a2, u3);
433
+ continue;
434
+ }
435
+ C3.push("");
436
+ }
437
+ if (n2 + D2[E] > u3 && F3.wordWrap === false) {
438
+ _(C3, a2, u3);
439
+ continue;
440
+ }
441
+ C3[C3.length - 1] += a2;
442
+ }
443
+ F3.trim !== false && (C3 = C3.map((E) => nD(E)));
444
+ const o3 = [...C3.join(`
445
+ `)];
446
+ for (const [E, a2] of o3.entries()) {
447
+ if (e2 += a2, v.has(a2)) {
448
+ const { groups: B2 } = new RegExp(`(?:\\${W$1}(?<code>\\d+)m|\\${y}(?<uri>.*)${w$1})`).exec(o3.slice(E).join("")) || { groups: {} };
449
+ if (B2.code !== void 0) {
450
+ const p = Number.parseFloat(B2.code);
451
+ s2 = p === CD ? void 0 : p;
452
+ } else B2.uri !== void 0 && (i2 = B2.uri.length === 0 ? void 0 : B2.uri);
453
+ }
454
+ const n2 = iD.codes.get(Number(s2));
455
+ o3[E + 1] === `
456
+ ` ? (i2 && (e2 += z("")), s2 && n2 && (e2 += V$1(n2))) : a2 === `
457
+ ` && (s2 && n2 && (e2 += V$1(s2)), i2 && (e2 += z(i2)));
458
+ }
459
+ return e2;
460
+ };
461
+ aD = ["up", "down", "left", "right", "space", "enter", "cancel"];
462
+ c = { actions: new Set(aD), aliases: /* @__PURE__ */ new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"], ["", "cancel"], ["escape", "cancel"]]) };
463
+ globalThis.process.platform.startsWith("win");
464
+ S = /* @__PURE__ */ Symbol("clack:cancel");
465
+ AD = Object.defineProperty;
466
+ pD = (t2, u3, F3) => u3 in t2 ? AD(t2, u3, { enumerable: true, configurable: true, writable: true, value: F3 }) : t2[u3] = F3;
467
+ h = (t2, u3, F3) => (pD(t2, typeof u3 != "symbol" ? u3 + "" : u3, F3), F3);
468
+ x = class {
469
+ constructor(u3, F3 = true) {
470
+ 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");
471
+ const { input: e2 = stdin, output: s2 = stdout, render: i2, signal: D2, ...C3 } = u3;
472
+ this.opts = C3, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = i2.bind(this), this._track = F3, this._abortSignal = D2, this.input = e2, this.output = s2;
473
+ }
474
+ unsubscribe() {
475
+ this._subscribers.clear();
476
+ }
477
+ setSubscriber(u3, F3) {
478
+ const e2 = this._subscribers.get(u3) ?? [];
479
+ e2.push(F3), this._subscribers.set(u3, e2);
480
+ }
481
+ on(u3, F3) {
482
+ this.setSubscriber(u3, { cb: F3 });
483
+ }
484
+ once(u3, F3) {
485
+ this.setSubscriber(u3, { cb: F3, once: true });
486
+ }
487
+ emit(u3, ...F3) {
488
+ const e2 = this._subscribers.get(u3) ?? [], s2 = [];
489
+ for (const i2 of e2) i2.cb(...F3), i2.once && s2.push(() => e2.splice(e2.indexOf(i2), 1));
490
+ for (const i2 of s2) i2();
491
+ }
492
+ prompt() {
493
+ return new Promise((u3, F3) => {
494
+ if (this._abortSignal) {
495
+ if (this._abortSignal.aborted) return this.state = "cancel", this.close(), u3(S);
496
+ this._abortSignal.addEventListener("abort", () => {
497
+ this.state = "cancel", this.close();
498
+ }, { once: true });
499
+ }
500
+ const e2 = new WriteStream(0);
501
+ e2._write = (s2, i2, D2) => {
502
+ this._track && (this.value = this.rl?.line.replace(/\t/g, ""), this._cursor = this.rl?.cursor ?? 0, this.emit("value", this.value)), D2();
503
+ }, this.input.pipe(e2), this.rl = f.createInterface({ input: this.input, output: e2, tabSize: 2, prompt: "", escapeCodeTimeout: 50 }), f.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), d$1(this.input, true), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
504
+ this.output.write(srcExports.cursor.show), this.output.off("resize", this.render), d$1(this.input, false), u3(this.value);
505
+ }), this.once("cancel", () => {
506
+ this.output.write(srcExports.cursor.show), this.output.off("resize", this.render), d$1(this.input, false), u3(S);
507
+ });
508
+ });
509
+ }
510
+ onKeypress(u3, F3) {
511
+ if (this.state === "error" && (this.state = "active"), F3?.name && (!this._track && c.aliases.has(F3.name) && this.emit("cursor", c.aliases.get(F3.name)), c.actions.has(F3.name) && this.emit("cursor", F3.name)), u3 && (u3.toLowerCase() === "y" || u3.toLowerCase() === "n") && this.emit("confirm", u3.toLowerCase() === "y"), u3 === " " && this.opts.placeholder && (this.value || (this.rl?.write(this.opts.placeholder), this.emit("value", this.opts.placeholder))), u3 && this.emit("key", u3.toLowerCase()), F3?.name === "return") {
512
+ if (this.opts.validate) {
513
+ const e2 = this.opts.validate(this.value);
514
+ e2 && (this.error = e2 instanceof Error ? e2.message : e2, this.state = "error", this.rl?.write(this.value));
515
+ }
516
+ this.state !== "error" && (this.state = "submit");
517
+ }
518
+ k$1([u3, F3?.name, F3?.sequence], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
519
+ }
520
+ close() {
521
+ this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
522
+ `), d$1(this.input, false), this.rl?.close(), this.rl = void 0, this.emit(`${this.state}`, this.value), this.unsubscribe();
523
+ }
524
+ restoreCursor() {
525
+ const u3 = G(this._prevFrame, process.stdout.columns, { hard: true }).split(`
526
+ `).length - 1;
527
+ this.output.write(srcExports.cursor.move(-999, u3 * -1));
528
+ }
529
+ render() {
530
+ const u3 = G(this._render(this) ?? "", process.stdout.columns, { hard: true });
531
+ if (u3 !== this._prevFrame) {
532
+ if (this.state === "initial") this.output.write(srcExports.cursor.hide);
533
+ else {
534
+ const F3 = lD(this._prevFrame, u3);
535
+ if (this.restoreCursor(), F3 && F3?.length === 1) {
536
+ const e2 = F3[0];
537
+ this.output.write(srcExports.cursor.move(0, e2)), this.output.write(srcExports.erase.lines(1));
538
+ const s2 = u3.split(`
539
+ `);
540
+ this.output.write(s2[e2]), this._prevFrame = u3, this.output.write(srcExports.cursor.move(0, s2.length - e2 - 1));
541
+ return;
542
+ }
543
+ if (F3 && F3?.length > 1) {
544
+ const e2 = F3[0];
545
+ this.output.write(srcExports.cursor.move(0, e2)), this.output.write(srcExports.erase.down());
546
+ const s2 = u3.split(`
547
+ `).slice(e2);
548
+ this.output.write(s2.join(`
549
+ `)), this._prevFrame = u3;
550
+ return;
551
+ }
552
+ this.output.write(srcExports.erase.down());
553
+ }
554
+ this.output.write(u3), this.state === "initial" && (this.state = "active"), this._prevFrame = u3;
555
+ }
556
+ }
557
+ };
558
+ fD = class extends x {
559
+ get cursor() {
560
+ return this.value ? 0 : 1;
561
+ }
562
+ get _value() {
563
+ return this.cursor === 0;
564
+ }
565
+ constructor(u3) {
566
+ super(u3, false), this.value = !!u3.initialValue, this.on("value", () => {
567
+ this.value = this._value;
568
+ }), this.on("confirm", (F3) => {
569
+ this.output.write(srcExports.cursor.move(0, -1)), this.value = F3, this.state = "submit", this.close();
570
+ }), this.on("cursor", () => {
571
+ this.value = !this.value;
572
+ });
573
+ }
574
+ };
575
+ bD = Object.defineProperty;
576
+ mD = (t2, u3, F3) => u3 in t2 ? bD(t2, u3, { enumerable: true, configurable: true, writable: true, value: F3 }) : t2[u3] = F3;
577
+ Y = (t2, u3, F3) => (mD(t2, typeof u3 != "symbol" ? u3 + "" : u3, F3), F3);
578
+ wD = class extends x {
579
+ constructor(u3) {
580
+ super(u3, false), Y(this, "options"), Y(this, "cursor", 0), this.options = u3.options, this.value = [...u3.initialValues ?? []], this.cursor = Math.max(this.options.findIndex(({ value: F3 }) => F3 === u3.cursorAt), 0), this.on("key", (F3) => {
581
+ F3 === "a" && this.toggleAll();
582
+ }), this.on("cursor", (F3) => {
583
+ switch (F3) {
584
+ case "left":
585
+ case "up":
586
+ this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
587
+ break;
588
+ case "down":
589
+ case "right":
590
+ this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
591
+ break;
592
+ case "space":
593
+ this.toggleValue();
594
+ break;
595
+ }
596
+ });
597
+ }
598
+ get _value() {
599
+ return this.options[this.cursor].value;
600
+ }
601
+ toggleAll() {
602
+ const u3 = this.value.length === this.options.length;
603
+ this.value = u3 ? [] : this.options.map((F3) => F3.value);
604
+ }
605
+ toggleValue() {
606
+ const u3 = this.value.includes(this._value);
607
+ this.value = u3 ? this.value.filter((F3) => F3 !== this._value) : [...this.value, this._value];
608
+ }
609
+ };
610
+ SD = Object.defineProperty;
611
+ $D = (t2, u3, F3) => u3 in t2 ? SD(t2, u3, { enumerable: true, configurable: true, writable: true, value: F3 }) : t2[u3] = F3;
612
+ q = (t2, u3, F3) => ($D(t2, typeof u3 != "symbol" ? u3 + "" : u3, F3), F3);
613
+ jD = class extends x {
614
+ constructor(u3) {
615
+ super(u3, false), q(this, "options"), q(this, "cursor", 0), this.options = u3.options, this.cursor = this.options.findIndex(({ value: F3 }) => F3 === u3.initialValue), this.cursor === -1 && (this.cursor = 0), this.changeValue(), this.on("cursor", (F3) => {
616
+ switch (F3) {
617
+ case "left":
618
+ case "up":
619
+ this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
620
+ break;
621
+ case "down":
622
+ case "right":
623
+ this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
624
+ break;
625
+ }
626
+ this.changeValue();
627
+ });
628
+ }
629
+ get _value() {
630
+ return this.options[this.cursor];
631
+ }
632
+ changeValue() {
633
+ this.value = this._value.value;
634
+ }
635
+ };
636
+ PD = class extends x {
637
+ get valueWithCursor() {
638
+ if (this.state === "submit") return this.value;
639
+ if (this.cursor >= this.value.length) return `${this.value}\u2588`;
640
+ const u3 = this.value.slice(0, this.cursor), [F3, ...e$1] = this.value.slice(this.cursor);
641
+ return `${u3}${e.inverse(F3)}${e$1.join("")}`;
642
+ }
643
+ get cursor() {
644
+ return this._cursor;
645
+ }
646
+ constructor(u3) {
647
+ super(u3), this.on("finalize", () => {
648
+ this.value || (this.value = u3.defaultValue);
649
+ });
650
+ }
651
+ };
652
+ V = ce();
653
+ u = (t2, n2) => V ? t2 : n2;
654
+ le = u("\u276F", ">");
655
+ L = u("\u25A0", "x");
656
+ W = u("\u25B2", "x");
657
+ C = u("\u2714", "\u221A");
658
+ o = u("");
659
+ d = u("");
660
+ k = u("\u25CF", ">");
661
+ P = u("\u25CB", " ");
662
+ A = u("\u25FB", "[\u2022]");
663
+ T = u("\u25FC", "[+]");
664
+ F = u("\u25FB", "[ ]");
665
+ w = (t2) => {
666
+ switch (t2) {
667
+ case "initial":
668
+ case "active":
669
+ return e.cyan(le);
670
+ case "cancel":
671
+ return e.red(L);
672
+ case "error":
673
+ return e.yellow(W);
674
+ case "submit":
675
+ return e.green(C);
676
+ }
677
+ };
678
+ B = (t2) => {
679
+ const { cursor: n2, options: s2, style: r3 } = t2, i2 = t2.maxItems ?? Number.POSITIVE_INFINITY, a2 = Math.max(process.stdout.rows - 4, 0), c3 = Math.min(a2, Math.max(i2, 5));
680
+ let l2 = 0;
681
+ n2 >= l2 + c3 - 3 ? l2 = Math.max(Math.min(n2 - c3 + 3, s2.length - c3), 0) : n2 < l2 + 2 && (l2 = Math.max(n2 - 2, 0));
682
+ const $ = c3 < s2.length && l2 > 0, p = c3 < s2.length && l2 + c3 < s2.length;
683
+ return s2.slice(l2, l2 + c3).map((M, v2, x2) => {
684
+ const j = v2 === 0 && $, E = v2 === x2.length - 1 && p;
685
+ return j || E ? e.dim("...") : r3(M, v2 + l2 === n2);
686
+ });
687
+ };
688
+ he = (t2) => new PD({ validate: t2.validate, placeholder: t2.placeholder, defaultValue: t2.defaultValue, initialValue: t2.initialValue, render() {
689
+ const n2 = `${e.gray(o)}
690
+ ${w(this.state)} ${t2.message}
691
+ `, s2 = t2.placeholder ? e.inverse(t2.placeholder[0]) + e.dim(t2.placeholder.slice(1)) : e.inverse(e.hidden("_")), r3 = this.value ? this.valueWithCursor : s2;
692
+ switch (this.state) {
693
+ case "error":
694
+ return `${n2.trim()}
695
+ ${e.yellow(o)} ${r3}
696
+ ${e.yellow(d)} ${e.yellow(this.error)}
697
+ `;
698
+ case "submit":
699
+ return `${n2}${e.gray(o)} ${e.dim(this.value || t2.placeholder)}`;
700
+ case "cancel":
701
+ return `${n2}${e.gray(o)} ${e.strikethrough(e.dim(this.value ?? ""))}${this.value?.trim() ? `
702
+ ${e.gray(o)}` : ""}`;
703
+ default:
704
+ return `${n2}${e.cyan(o)} ${r3}
705
+ ${e.cyan(d)}
706
+ `;
707
+ }
708
+ } }).prompt();
709
+ ye = (t2) => {
710
+ const n2 = t2.active ?? "Yes", s2 = t2.inactive ?? "No";
711
+ return new fD({ active: n2, inactive: s2, initialValue: t2.initialValue ?? true, render() {
712
+ const r3 = `${e.gray(o)}
713
+ ${w(this.state)} ${t2.message}
714
+ `, i2 = this.value ? n2 : s2;
715
+ switch (this.state) {
716
+ case "submit":
717
+ return `${r3}${e.gray(o)} ${e.dim(i2)}`;
718
+ case "cancel":
719
+ return `${r3}${e.gray(o)} ${e.strikethrough(e.dim(i2))}
720
+ ${e.gray(o)}`;
721
+ default:
722
+ return `${r3}${e.cyan(o)} ${this.value ? `${e.green(k)} ${n2}` : `${e.dim(P)} ${e.dim(n2)}`} ${e.dim("/")} ${this.value ? `${e.dim(P)} ${e.dim(s2)}` : `${e.green(k)} ${s2}`}
723
+ ${e.cyan(d)}
724
+ `;
725
+ }
726
+ } }).prompt();
727
+ };
728
+ ve = (t2) => {
729
+ const n2 = (s2, r3) => {
730
+ const i2 = s2.label ?? String(s2.value);
731
+ switch (r3) {
732
+ case "selected":
733
+ return `${e.dim(i2)}`;
734
+ case "active":
735
+ return `${e.green(k)} ${i2} ${s2.hint ? e.dim(`(${s2.hint})`) : ""}`;
736
+ case "cancelled":
737
+ return `${e.strikethrough(e.dim(i2))}`;
738
+ default:
739
+ return `${e.dim(P)} ${e.dim(i2)}`;
740
+ }
741
+ };
742
+ return new jD({ options: t2.options, initialValue: t2.initialValue, render() {
743
+ const s2 = `${e.gray(o)}
744
+ ${w(this.state)} ${t2.message}
745
+ `;
746
+ switch (this.state) {
747
+ case "submit":
748
+ return `${s2}${e.gray(o)} ${n2(this.options[this.cursor], "selected")}`;
749
+ case "cancel":
750
+ return `${s2}${e.gray(o)} ${n2(this.options[this.cursor], "cancelled")}
751
+ ${e.gray(o)}`;
752
+ default:
753
+ return `${s2}${e.cyan(o)} ${B({ cursor: this.cursor, options: this.options, maxItems: t2.maxItems, style: (r3, i2) => n2(r3, i2 ? "active" : "inactive") }).join(`
754
+ ${e.cyan(o)} `)}
755
+ ${e.cyan(d)}
756
+ `;
757
+ }
758
+ } }).prompt();
759
+ };
760
+ fe = (t2) => {
761
+ const n2 = (s2, r3) => {
762
+ const i2 = s2.label ?? String(s2.value);
763
+ return r3 === "active" ? `${e.cyan(A)} ${i2} ${s2.hint ? e.dim(`(${s2.hint})`) : ""}` : r3 === "selected" ? `${e.green(T)} ${e.dim(i2)}` : r3 === "cancelled" ? `${e.strikethrough(e.dim(i2))}` : r3 === "active-selected" ? `${e.green(T)} ${i2} ${s2.hint ? e.dim(`(${s2.hint})`) : ""}` : r3 === "submitted" ? `${e.dim(i2)}` : `${e.dim(F)} ${e.dim(i2)}`;
764
+ };
765
+ return new wD({ options: t2.options, initialValues: t2.initialValues, required: t2.required ?? true, cursorAt: t2.cursorAt, validate(s2) {
766
+ if (this.required && s2.length === 0) return `Please select at least one option.
767
+ ${e.reset(e.dim(`Press ${e.gray(e.bgWhite(e.inverse(" space ")))} to select, ${e.gray(e.bgWhite(e.inverse(" enter ")))} to submit`))}`;
768
+ }, render() {
769
+ const s2 = `${e.gray(o)}
770
+ ${w(this.state)} ${t2.message}
771
+ `, r3 = (i2, a2) => {
772
+ const c3 = this.value.includes(i2.value);
773
+ return a2 && c3 ? n2(i2, "active-selected") : c3 ? n2(i2, "selected") : n2(i2, a2 ? "active" : "inactive");
774
+ };
775
+ switch (this.state) {
776
+ case "submit":
777
+ return `${s2}${e.gray(o)} ${this.options.filter(({ value: i2 }) => this.value.includes(i2)).map((i2) => n2(i2, "submitted")).join(e.dim(", ")) || e.dim("none")}`;
778
+ case "cancel": {
779
+ const i2 = this.options.filter(({ value: a2 }) => this.value.includes(a2)).map((a2) => n2(a2, "cancelled")).join(e.dim(", "));
780
+ return `${s2}${e.gray(o)} ${i2.trim() ? `${i2}
781
+ ${e.gray(o)}` : ""}`;
782
+ }
783
+ case "error": {
784
+ const i2 = this.error.split(`
785
+ `).map((a2, c3) => c3 === 0 ? `${e.yellow(d)} ${e.yellow(a2)}` : ` ${a2}`).join(`
786
+ `);
787
+ return `${s2 + e.yellow(o)} ${B({ options: this.options, cursor: this.cursor, maxItems: t2.maxItems, style: r3 }).join(`
788
+ ${e.yellow(o)} `)}
789
+ ${i2}
790
+ `;
791
+ }
792
+ default:
793
+ return `${s2}${e.cyan(o)} ${B({ options: this.options, cursor: this.cursor, maxItems: t2.maxItems, style: r3 }).join(`
794
+ ${e.cyan(o)} `)}
795
+ ${e.cyan(d)}
796
+ `;
797
+ }
798
+ } }).prompt();
799
+ };
800
+ `${e.gray(o)} `;
801
+ kCancel = /* @__PURE__ */ Symbol.for("cancel");
802
+ }
803
+ });
804
+
805
+ // ../../node_modules/.pnpm/shell-quote@1.8.4/node_modules/shell-quote/quote.js
806
+ var require_quote = __commonJS({
807
+ "../../node_modules/.pnpm/shell-quote@1.8.4/node_modules/shell-quote/quote.js"(exports, module) {
808
+ "use strict";
809
+ var OPS = [
810
+ "||",
811
+ "&&",
812
+ ";;",
813
+ "|&",
814
+ "<(",
815
+ "<<<",
816
+ ">>",
817
+ ">&",
818
+ "<&",
819
+ "&",
820
+ ";",
821
+ "(",
822
+ ")",
823
+ "|",
824
+ "<",
825
+ ">"
826
+ ];
827
+ var LINE_TERMINATORS = /[\n\r\u2028\u2029]/;
828
+ var GLOB_SHELL_SPECIAL = /[\s#!"$&'():;<=>@\\^`|]/g;
829
+ module.exports = function quote(xs) {
830
+ return xs.map(function(s2) {
831
+ if (s2 === "") {
832
+ return "''";
833
+ }
834
+ if (s2 && typeof s2 === "object") {
835
+ if (s2.op === "glob") {
836
+ if (typeof s2.pattern !== "string") {
837
+ throw new TypeError("glob token requires a string `pattern`");
838
+ }
839
+ if (LINE_TERMINATORS.test(s2.pattern)) {
840
+ throw new TypeError("glob `pattern` must not contain line terminators");
841
+ }
842
+ return s2.pattern.replace(GLOB_SHELL_SPECIAL, "\\$&");
843
+ }
844
+ if (typeof s2.op === "string") {
845
+ if (OPS.indexOf(s2.op) < 0) {
846
+ throw new TypeError("invalid `op` value: " + JSON.stringify(s2.op));
847
+ }
848
+ return s2.op.replace(/[\s\S]/g, "\\$&");
849
+ }
850
+ if (typeof s2.comment === "string") {
851
+ if (LINE_TERMINATORS.test(s2.comment)) {
852
+ throw new TypeError("`comment` must not contain line terminators");
853
+ }
854
+ return "#" + s2.comment;
855
+ }
856
+ throw new TypeError("unrecognized object token shape");
857
+ }
858
+ if (/["\s\\]/.test(s2) && !/'/.test(s2)) {
859
+ return "'" + s2.replace(/(['])/g, "\\$1") + "'";
860
+ }
861
+ if (/["'\s]/.test(s2)) {
862
+ return '"' + s2.replace(/(["\\$`!])/g, "\\$1") + '"';
863
+ }
864
+ return String(s2).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g, "$1\\$2");
865
+ }).join(" ");
866
+ };
867
+ }
868
+ });
869
+
870
+ // ../../node_modules/.pnpm/shell-quote@1.8.4/node_modules/shell-quote/parse.js
871
+ var require_parse = __commonJS({
872
+ "../../node_modules/.pnpm/shell-quote@1.8.4/node_modules/shell-quote/parse.js"(exports, module) {
873
+ "use strict";
874
+ var CONTROL = "(?:" + [
875
+ "\\|\\|",
876
+ "\\&\\&",
877
+ ";;",
878
+ "\\|\\&",
879
+ "\\<\\(",
880
+ "\\<\\<\\<",
881
+ ">>",
882
+ ">\\&",
883
+ "<\\&",
884
+ "[&;()|<>]"
885
+ ].join("|") + ")";
886
+ var controlRE = new RegExp("^" + CONTROL + "$");
887
+ var META = "|&;()<> \\t";
888
+ var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
889
+ var DOUBLE_QUOTE = "'((\\\\'|[^'])*?)'";
890
+ var hash = /^#$/;
891
+ var SQ = "'";
892
+ var DQ = '"';
893
+ var DS = "$";
894
+ var TOKEN = "";
895
+ var mult = 4294967296;
896
+ for (i2 = 0; i2 < 4; i2++) {
897
+ TOKEN += (mult * Math.random()).toString(16);
898
+ }
899
+ var i2;
900
+ var startsWithToken = new RegExp("^" + TOKEN);
901
+ function matchAll(s2, r3) {
902
+ var origIndex = r3.lastIndex;
903
+ var matches = [];
904
+ var matchObj;
905
+ while (matchObj = r3.exec(s2)) {
906
+ matches.push(matchObj);
907
+ if (r3.lastIndex === matchObj.index) {
908
+ r3.lastIndex += 1;
909
+ }
910
+ }
911
+ r3.lastIndex = origIndex;
912
+ return matches;
913
+ }
914
+ function getVar(env2, pre, key) {
915
+ var r3 = typeof env2 === "function" ? env2(key) : env2[key];
916
+ if (typeof r3 === "undefined" && key != "") {
917
+ r3 = "";
918
+ } else if (typeof r3 === "undefined") {
919
+ r3 = "$";
920
+ }
921
+ if (typeof r3 === "object") {
922
+ return pre + TOKEN + JSON.stringify(r3) + TOKEN;
923
+ }
924
+ return pre + r3;
925
+ }
926
+ function parseInternal(string, env2, opts) {
927
+ if (!opts) {
928
+ opts = {};
929
+ }
930
+ var BS = opts.escape || "\\";
931
+ var BAREWORD = "(\\" + BS + `['"` + META + `]|[^\\s'"` + META + "])+";
932
+ var chunker = new RegExp([
933
+ "(" + CONTROL + ")",
934
+ // control chars
935
+ "(" + BAREWORD + "|" + SINGLE_QUOTE + "|" + DOUBLE_QUOTE + ")+"
936
+ ].join("|"), "g");
937
+ var matches = matchAll(string, chunker);
938
+ if (matches.length === 0) {
939
+ return [];
940
+ }
941
+ if (!env2) {
942
+ env2 = {};
943
+ }
944
+ var commented = false;
945
+ return matches.map(function(match) {
946
+ var s2 = match[0];
947
+ if (!s2 || commented) {
948
+ return void 0;
949
+ }
950
+ if (controlRE.test(s2)) {
951
+ return { op: s2 };
952
+ }
953
+ var quote = false;
954
+ var esc = false;
955
+ var out = "";
956
+ var isGlob = false;
957
+ var i3;
958
+ function parseEnvVar() {
959
+ i3 += 1;
960
+ var varend;
961
+ var varname;
962
+ var char = s2.charAt(i3);
963
+ if (char === "{") {
964
+ i3 += 1;
965
+ if (s2.charAt(i3) === "}") {
966
+ throw new Error("Bad substitution: " + s2.slice(i3 - 2, i3 + 1));
967
+ }
968
+ varend = s2.indexOf("}", i3);
969
+ if (varend < 0) {
970
+ throw new Error("Bad substitution: " + s2.slice(i3));
971
+ }
972
+ varname = s2.slice(i3, varend);
973
+ i3 = varend;
974
+ } else if (/[*@#?$!_-]/.test(char)) {
975
+ varname = char;
976
+ i3 += 1;
977
+ } else {
978
+ var slicedFromI = s2.slice(i3);
979
+ varend = slicedFromI.match(/[^\w\d_]/);
980
+ if (!varend) {
981
+ varname = slicedFromI;
982
+ i3 = s2.length;
983
+ } else {
984
+ varname = slicedFromI.slice(0, varend.index);
985
+ i3 += varend.index - 1;
986
+ }
987
+ }
988
+ return getVar(env2, "", varname);
989
+ }
990
+ for (i3 = 0; i3 < s2.length; i3++) {
991
+ var c3 = s2.charAt(i3);
992
+ isGlob = isGlob || !quote && (c3 === "*" || c3 === "?");
993
+ if (esc) {
994
+ out += c3;
995
+ esc = false;
996
+ } else if (quote) {
997
+ if (c3 === quote) {
998
+ quote = false;
999
+ } else if (quote == SQ) {
1000
+ out += c3;
1001
+ } else {
1002
+ if (c3 === BS) {
1003
+ i3 += 1;
1004
+ c3 = s2.charAt(i3);
1005
+ if (c3 === DQ || c3 === BS || c3 === DS) {
1006
+ out += c3;
1007
+ } else {
1008
+ out += BS + c3;
1009
+ }
1010
+ } else if (c3 === DS) {
1011
+ out += parseEnvVar();
1012
+ } else {
1013
+ out += c3;
1014
+ }
1015
+ }
1016
+ } else if (c3 === DQ || c3 === SQ) {
1017
+ quote = c3;
1018
+ } else if (controlRE.test(c3)) {
1019
+ return { op: s2 };
1020
+ } else if (hash.test(c3)) {
1021
+ commented = true;
1022
+ var commentObj = { comment: string.slice(match.index + i3 + 1) };
1023
+ if (out.length) {
1024
+ return [out, commentObj];
1025
+ }
1026
+ return [commentObj];
1027
+ } else if (c3 === BS) {
1028
+ esc = true;
1029
+ } else if (c3 === DS) {
1030
+ out += parseEnvVar();
1031
+ } else {
1032
+ out += c3;
1033
+ }
1034
+ }
1035
+ if (isGlob) {
1036
+ return { op: "glob", pattern: out };
1037
+ }
1038
+ return out;
1039
+ }).reduce(function(prev, arg) {
1040
+ return typeof arg === "undefined" ? prev : prev.concat(arg);
1041
+ }, []);
1042
+ }
1043
+ module.exports = function parse(s2, env2, opts) {
1044
+ var mapped = parseInternal(s2, env2, opts);
1045
+ if (typeof env2 !== "function") {
1046
+ return mapped;
1047
+ }
1048
+ return mapped.reduce(function(acc, s3) {
1049
+ if (typeof s3 === "object") {
1050
+ return acc.concat(s3);
1051
+ }
1052
+ var xs = s3.split(RegExp("(" + TOKEN + ".*?" + TOKEN + ")", "g"));
1053
+ if (xs.length === 1) {
1054
+ return acc.concat(xs[0]);
1055
+ }
1056
+ return acc.concat(xs.filter(Boolean).map(function(x2) {
1057
+ if (startsWithToken.test(x2)) {
1058
+ return JSON.parse(x2.split(TOKEN)[1]);
1059
+ }
1060
+ return x2;
1061
+ }));
1062
+ }, []);
1063
+ };
1064
+ }
1065
+ });
1066
+
1067
+ // ../../node_modules/.pnpm/shell-quote@1.8.4/node_modules/shell-quote/index.js
1068
+ var require_shell_quote = __commonJS({
1069
+ "../../node_modules/.pnpm/shell-quote@1.8.4/node_modules/shell-quote/index.js"(exports) {
1070
+ "use strict";
1071
+ exports.quote = require_quote();
1072
+ exports.parse = require_parse();
1073
+ }
1074
+ });
1075
+
1076
+ // src/service-bridge-main.ts
1077
+ import process4 from "process";
1078
+
1079
+ // src/service-bridge.ts
1080
+ import { randomUUID } from "crypto";
1081
+ import process3 from "process";
1082
+
1083
+ // ../../packages/apes/dist/chunk-3LH4FT4R.js
1084
+ import { homedir } from "os";
1085
+ import { dirname, join } from "path";
1086
+
1087
+ // ../../packages/core/dist/index.js
1088
+ import * as jose from "jose";
1089
+ import { lookup } from "dns/promises";
1090
+ import { isIP } from "net";
1091
+ var HKDF_INFO = new TextEncoder().encode("openape-sealed-box-v1");
1092
+ function isBlockedAddress(ip) {
1093
+ const fam = isIP(ip);
1094
+ if (fam === 4) {
1095
+ const o3 = ip.split(".");
1096
+ const a2 = Number(o3[0]);
1097
+ const b2 = Number(o3[1]);
1098
+ if (a2 === 0) return true;
1099
+ if (a2 === 127) return true;
1100
+ if (a2 === 10) return true;
1101
+ if (a2 === 172 && b2 >= 16 && b2 <= 31) return true;
1102
+ if (a2 === 192 && b2 === 168) return true;
1103
+ if (a2 === 169 && b2 === 254) return true;
1104
+ if (a2 === 100 && b2 >= 64 && b2 <= 127) return true;
1105
+ return false;
1106
+ }
1107
+ const low = ip.toLowerCase().replace(/^\[|\]$/g, "");
1108
+ if (low === "::" || low === "::1") return true;
1109
+ if (low.startsWith("fe80")) return true;
1110
+ if (low.startsWith("fc") || low.startsWith("fd")) return true;
1111
+ const mapped = low.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/);
1112
+ if (mapped) return isBlockedAddress(mapped[1]);
1113
+ return false;
1114
+ }
1115
+ async function assertPublicUrl(rawUrl, opts = {}) {
1116
+ let url;
1117
+ try {
1118
+ url = new URL(rawUrl);
1119
+ } catch {
1120
+ throw new Error(`Invalid URL: ${rawUrl}`);
1121
+ }
1122
+ const allowedSchemes = opts.allowHttp === true ? /* @__PURE__ */ new Set(["https:", "http:"]) : /* @__PURE__ */ new Set(["https:"]);
1123
+ if (!allowedSchemes.has(url.protocol)) {
1124
+ const expected = opts.allowHttp === true ? "http(s)" : "https";
1125
+ throw new Error(`URL must use ${expected}:// (got ${url.protocol}//) \u2014 ${rawUrl}`);
1126
+ }
1127
+ const host = url.hostname.replace(/^\[|\]$/g, "");
1128
+ const addresses = [];
1129
+ if (isIP(host)) {
1130
+ addresses.push(host);
1131
+ } else {
1132
+ const results = await lookup(host, { all: true });
1133
+ for (const r3 of results) addresses.push(r3.address);
1134
+ }
1135
+ if (addresses.length === 0) {
1136
+ throw new Error(`Host did not resolve: ${host}`);
1137
+ }
1138
+ for (const addr of addresses) {
1139
+ if (isBlockedAddress(addr)) {
1140
+ throw new Error(`Refusing to fetch a private/loopback address (${addr}) for ${rawUrl}`);
1141
+ }
1142
+ }
1143
+ return url;
1144
+ }
1145
+
1146
+ // ../../packages/apes/dist/chunk-3LH4FT4R.js
1147
+ var CONFIG_DIR = join(homedir(), ".config", "openape");
1148
+ var SECRETS_DIR = join(CONFIG_DIR, "secrets.d");
1149
+ var X25519_KEY_PATH = join(CONFIG_DIR, "agent-x25519.key");
1150
+ var X25519_PUBKEY_PATH = `${X25519_KEY_PATH}.pub`;
1151
+
1152
+ // ../../packages/apes/dist/chunk-BA2V3BBO.js
1153
+ init_chunk_OBF7IMQ2();
1154
+
1155
+ // ../../node_modules/.pnpm/citty@0.2.2/node_modules/citty/dist/index.mjs
1156
+ import { parseArgs as parseArgs$1 } from "util";
1157
+ function defineCommand(def) {
1158
+ return def;
1159
+ }
1160
+
1161
+ // ../../packages/shapes/dist/index.js
1162
+ import { createHash } from "crypto";
1163
+ import { existsSync as existsSync2, readdirSync, readFileSync } from "fs";
1164
+ import { homedir as homedir22 } from "os";
1165
+ import { basename, join as join22 } from "path";
1166
+
1167
+ // ../../packages/grants/dist/index.js
1168
+ function normalizeSelector(selector) {
1169
+ if (!selector)
1170
+ return void 0;
1171
+ const entries = Object.entries(selector).filter(([, value]) => value !== void 0 && value !== "").sort(([a2], [b2]) => a2.localeCompare(b2));
1172
+ if (entries.length === 0)
1173
+ return void 0;
1174
+ return Object.fromEntries(entries);
1175
+ }
1176
+ function selectorString(selector) {
1177
+ const normalized = normalizeSelector(selector);
1178
+ if (!normalized)
1179
+ return "*";
1180
+ return Object.entries(normalized).map(([key, value]) => `${key}=${value}`).join(",");
1181
+ }
1182
+ function canonicalizeCliPermission(detail) {
1183
+ const chain = detail.resource_chain.map((resource) => `${resource.resource}[${selectorString(resource.selector)}]`).join(".");
1184
+ return `${detail.cli_id}.${chain}#${detail.action}`;
1185
+ }
1186
+ async function computeArgvHash(argv2) {
1187
+ const encoder = new TextEncoder();
1188
+ const data = encoder.encode(JSON.stringify(argv2));
1189
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
1190
+ const hashArray = new Uint8Array(hashBuffer);
1191
+ const digest2 = Array.from(hashArray).map((b2) => b2.toString(16).padStart(2, "0")).join("");
1192
+ return `SHA-256:${digest2}`;
1193
+ }
1194
+ function parseOptionArgs(tokens, valueOptions) {
1195
+ const options = {};
1196
+ const positionals = [];
1197
+ const takesValue = new Set(valueOptions ?? []);
1198
+ for (let index = 0; index < tokens.length; index += 1) {
1199
+ const token = tokens[index];
1200
+ if (token.startsWith("--")) {
1201
+ const stripped = token.slice(2);
1202
+ const eqIndex = stripped.indexOf("=");
1203
+ if (eqIndex >= 0) {
1204
+ options[stripped.slice(0, eqIndex)] = stripped.slice(eqIndex + 1);
1205
+ continue;
1206
+ }
1207
+ const next = tokens[index + 1];
1208
+ if (next && !next.startsWith("-")) {
1209
+ options[stripped] = next;
1210
+ index += 1;
1211
+ continue;
1212
+ }
1213
+ options[stripped] = "true";
1214
+ } else if (token.startsWith("-") && token.length > 1 && !/^-\d/.test(token)) {
1215
+ const key = token.slice(1);
1216
+ if (key.length === 1 && !takesValue.has(key)) {
1217
+ options[key] = "true";
1218
+ } else {
1219
+ const next = tokens[index + 1];
1220
+ if (next && !next.startsWith("-")) {
1221
+ options[key] = next;
1222
+ index += 1;
1223
+ } else {
1224
+ options[key] = "true";
1225
+ }
1226
+ }
1227
+ } else {
1228
+ positionals.push(token);
1229
+ }
1230
+ }
1231
+ return { options, positionals };
1232
+ }
1233
+ function resolveBindingToken(binding, bindings) {
1234
+ const match = binding.match(/^\{([^}|]+)(?:\|([^}]+))?\}$/);
1235
+ if (!match) return binding;
1236
+ const [, name, transform] = match;
1237
+ const value = bindings[name];
1238
+ if (!value) throw new Error(`Missing binding: ${name}`);
1239
+ if (!transform) return value;
1240
+ if (transform === "owner" || transform === "name") {
1241
+ const [owner, repo] = value.split("/");
1242
+ if (!owner || !repo) throw new Error(`Binding ${name} must be in owner/name form`);
1243
+ return transform === "owner" ? owner : repo;
1244
+ }
1245
+ throw new Error(`Unsupported binding transform: ${transform}`);
1246
+ }
1247
+ function renderTemplate(template, bindings) {
1248
+ return template.replace(/\{([^}]+)\}/g, (_3, expression) => resolveBindingToken(`{${expression}}`, bindings));
1249
+ }
1250
+ function parseResourceChain(chain, bindings) {
1251
+ return chain.map((entry) => {
1252
+ const [resource, selectorSpec = "*"] = entry.split(":", 2);
1253
+ if (!resource) throw new Error(`Invalid resource chain entry: ${entry}`);
1254
+ if (selectorSpec === "*") return { resource };
1255
+ const selector = Object.fromEntries(
1256
+ selectorSpec.split(",").map((segment) => {
1257
+ const [key, rawValue] = segment.split("=", 2);
1258
+ if (!key || !rawValue) throw new Error(`Invalid selector segment: ${segment}`);
1259
+ return [key, renderTemplate(rawValue, bindings)];
1260
+ })
1261
+ );
1262
+ return { resource, selector };
1263
+ });
1264
+ }
1265
+ function matchOperation(operation, argv2) {
1266
+ if (argv2.length < operation.command.length) return null;
1267
+ const prefix = argv2.slice(0, operation.command.length);
1268
+ if (prefix.join("\0") !== operation.command.join("\0")) return null;
1269
+ const remainder = argv2.slice(operation.command.length);
1270
+ const { options, positionals } = parseOptionArgs(remainder, operation.required_options);
1271
+ const expectedPositionals = operation.positionals ?? [];
1272
+ if (positionals.length !== expectedPositionals.length) return null;
1273
+ for (const option of operation.required_options ?? []) {
1274
+ if (!options[option]) return null;
1275
+ }
1276
+ const bindings = { ...options };
1277
+ for (let index = 0; index < expectedPositionals.length; index += 1) {
1278
+ const name = expectedPositionals[index];
1279
+ const value = positionals[index];
1280
+ if (name.startsWith("=")) {
1281
+ if (value !== name.slice(1)) return null;
1282
+ continue;
1283
+ }
1284
+ bindings[name] = value;
1285
+ }
1286
+ return bindings;
1287
+ }
1288
+ function expandCombinedFlags(argv2) {
1289
+ return argv2.flatMap((token) => {
1290
+ if (token.startsWith("-") && !token.startsWith("--") && token.length > 2 && /^-[a-z]+$/i.test(token)) {
1291
+ return Array.from(token.slice(1), (c3) => `-${c3}`);
1292
+ }
1293
+ return [token];
1294
+ });
1295
+ }
1296
+ function tryMatch(operations, argv2) {
1297
+ return operations.flatMap((operation) => {
1298
+ try {
1299
+ const bindings = matchOperation(operation, argv2);
1300
+ return bindings ? [{ operation, bindings }] : [];
1301
+ } catch {
1302
+ return [];
1303
+ }
1304
+ });
1305
+ }
1306
+ function matchArgvToOperation(operations, commandArgv) {
1307
+ let matches = tryMatch(operations, commandArgv);
1308
+ if (matches.length === 0) {
1309
+ const expanded = expandCombinedFlags(commandArgv);
1310
+ if (expanded.length !== commandArgv.length) {
1311
+ matches = tryMatch(operations, expanded);
1312
+ }
1313
+ }
1314
+ if (matches.length === 0) return null;
1315
+ if (matches.length > 1) {
1316
+ matches.sort((a2, b2) => b2.operation.command.length - a2.operation.command.length);
1317
+ matches = [matches[0]];
1318
+ }
1319
+ return matches[0];
1320
+ }
1321
+ function buildCliAuthDetail(cliId, operation, bindings) {
1322
+ const resource_chain = parseResourceChain(operation.resource_chain, bindings);
1323
+ const detail = {
1324
+ type: "openape_cli",
1325
+ cli_id: cliId,
1326
+ operation_id: operation.id,
1327
+ resource_chain,
1328
+ action: operation.action,
1329
+ permission: "",
1330
+ display: renderTemplate(operation.display, bindings),
1331
+ risk: operation.risk,
1332
+ ...operation.exact_command ? { constraints: { exact_command: true } } : {}
1333
+ };
1334
+ detail.permission = canonicalizeCliPermission(detail);
1335
+ return detail;
1336
+ }
1337
+
1338
+ // ../../node_modules/.pnpm/consola@3.4.2/node_modules/consola/dist/core.mjs
1339
+ var LogLevels = {
1340
+ silent: Number.NEGATIVE_INFINITY,
1341
+ fatal: 0,
1342
+ error: 0,
1343
+ warn: 1,
1344
+ log: 2,
1345
+ info: 3,
1346
+ success: 3,
1347
+ fail: 3,
1348
+ ready: 3,
1349
+ start: 3,
1350
+ box: 3,
1351
+ debug: 4,
1352
+ trace: 5,
1353
+ verbose: Number.POSITIVE_INFINITY
1354
+ };
1355
+ var LogTypes = {
1356
+ // Silent
1357
+ silent: {
1358
+ level: -1
1359
+ },
1360
+ // Level 0
1361
+ fatal: {
1362
+ level: LogLevels.fatal
1363
+ },
1364
+ error: {
1365
+ level: LogLevels.error
1366
+ },
1367
+ // Level 1
1368
+ warn: {
1369
+ level: LogLevels.warn
1370
+ },
1371
+ // Level 2
1372
+ log: {
1373
+ level: LogLevels.log
1374
+ },
1375
+ // Level 3
1376
+ info: {
1377
+ level: LogLevels.info
1378
+ },
1379
+ success: {
1380
+ level: LogLevels.success
1381
+ },
1382
+ fail: {
1383
+ level: LogLevels.fail
1384
+ },
1385
+ ready: {
1386
+ level: LogLevels.info
1387
+ },
1388
+ start: {
1389
+ level: LogLevels.info
1390
+ },
1391
+ box: {
1392
+ level: LogLevels.info
1393
+ },
1394
+ // Level 4
1395
+ debug: {
1396
+ level: LogLevels.debug
1397
+ },
1398
+ // Level 5
1399
+ trace: {
1400
+ level: LogLevels.trace
1401
+ },
1402
+ // Verbose
1403
+ verbose: {
1404
+ level: LogLevels.verbose
1405
+ }
1406
+ };
1407
+ function isPlainObject$1(value) {
1408
+ if (value === null || typeof value !== "object") {
1409
+ return false;
1410
+ }
1411
+ const prototype = Object.getPrototypeOf(value);
1412
+ if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
1413
+ return false;
1414
+ }
1415
+ if (Symbol.iterator in value) {
1416
+ return false;
1417
+ }
1418
+ if (Symbol.toStringTag in value) {
1419
+ return Object.prototype.toString.call(value) === "[object Module]";
1420
+ }
1421
+ return true;
1422
+ }
1423
+ function _defu(baseObject, defaults, namespace = ".", merger) {
1424
+ if (!isPlainObject$1(defaults)) {
1425
+ return _defu(baseObject, {}, namespace, merger);
1426
+ }
1427
+ const object = Object.assign({}, defaults);
1428
+ for (const key in baseObject) {
1429
+ if (key === "__proto__" || key === "constructor") {
1430
+ continue;
1431
+ }
1432
+ const value = baseObject[key];
1433
+ if (value === null || value === void 0) {
1434
+ continue;
1435
+ }
1436
+ if (merger && merger(object, key, value, namespace)) {
1437
+ continue;
1438
+ }
1439
+ if (Array.isArray(value) && Array.isArray(object[key])) {
1440
+ object[key] = [...value, ...object[key]];
1441
+ } else if (isPlainObject$1(value) && isPlainObject$1(object[key])) {
1442
+ object[key] = _defu(
1443
+ value,
1444
+ object[key],
1445
+ (namespace ? `${namespace}.` : "") + key.toString(),
1446
+ merger
1447
+ );
1448
+ } else {
1449
+ object[key] = value;
1450
+ }
1451
+ }
1452
+ return object;
1453
+ }
1454
+ function createDefu(merger) {
1455
+ return (...arguments_) => (
1456
+ // eslint-disable-next-line unicorn/no-array-reduce
1457
+ arguments_.reduce((p, c3) => _defu(p, c3, "", merger), {})
1458
+ );
1459
+ }
1460
+ var defu = createDefu();
1461
+ function isPlainObject(obj) {
1462
+ return Object.prototype.toString.call(obj) === "[object Object]";
1463
+ }
1464
+ function isLogObj(arg) {
1465
+ if (!isPlainObject(arg)) {
1466
+ return false;
1467
+ }
1468
+ if (!arg.message && !arg.args) {
1469
+ return false;
1470
+ }
1471
+ if (arg.stack) {
1472
+ return false;
1473
+ }
1474
+ return true;
1475
+ }
1476
+ var paused = false;
1477
+ var queue = [];
1478
+ var Consola = class _Consola {
1479
+ options;
1480
+ _lastLog;
1481
+ _mockFn;
1482
+ /**
1483
+ * Creates an instance of Consola with specified options or defaults.
1484
+ *
1485
+ * @param {Partial<ConsolaOptions>} [options={}] - Configuration options for the Consola instance.
1486
+ */
1487
+ constructor(options = {}) {
1488
+ const types = options.types || LogTypes;
1489
+ this.options = defu(
1490
+ {
1491
+ ...options,
1492
+ defaults: { ...options.defaults },
1493
+ level: _normalizeLogLevel(options.level, types),
1494
+ reporters: [...options.reporters || []]
1495
+ },
1496
+ {
1497
+ types: LogTypes,
1498
+ throttle: 1e3,
1499
+ throttleMin: 5,
1500
+ formatOptions: {
1501
+ date: true,
1502
+ colors: false,
1503
+ compact: true
1504
+ }
1505
+ }
1506
+ );
1507
+ for (const type in types) {
1508
+ const defaults = {
1509
+ type,
1510
+ ...this.options.defaults,
1511
+ ...types[type]
1512
+ };
1513
+ this[type] = this._wrapLogFn(defaults);
1514
+ this[type].raw = this._wrapLogFn(
1515
+ defaults,
1516
+ true
1517
+ );
1518
+ }
1519
+ if (this.options.mockFn) {
1520
+ this.mockTypes();
1521
+ }
1522
+ this._lastLog = {};
1523
+ }
1524
+ /**
1525
+ * Gets the current log level of the Consola instance.
1526
+ *
1527
+ * @returns {number} The current log level.
1528
+ */
1529
+ get level() {
1530
+ return this.options.level;
1531
+ }
1532
+ /**
1533
+ * Sets the minimum log level that will be output by the instance.
1534
+ *
1535
+ * @param {number} level - The new log level to set.
1536
+ */
1537
+ set level(level) {
1538
+ this.options.level = _normalizeLogLevel(
1539
+ level,
1540
+ this.options.types,
1541
+ this.options.level
1542
+ );
1543
+ }
1544
+ /**
1545
+ * Displays a prompt to the user and returns the response.
1546
+ * Throw an error if `prompt` is not supported by the current configuration.
1547
+ *
1548
+ * @template T
1549
+ * @param {string} message - The message to display in the prompt.
1550
+ * @param {T} [opts] - Optional options for the prompt. See {@link PromptOptions}.
1551
+ * @returns {promise<T>} A promise that infer with the prompt options. See {@link PromptOptions}.
1552
+ */
1553
+ prompt(message, opts) {
1554
+ if (!this.options.prompt) {
1555
+ throw new Error("prompt is not supported!");
1556
+ }
1557
+ return this.options.prompt(message, opts);
1558
+ }
1559
+ /**
1560
+ * Creates a new instance of Consola, inheriting options from the current instance, with possible overrides.
1561
+ *
1562
+ * @param {Partial<ConsolaOptions>} options - Optional overrides for the new instance. See {@link ConsolaOptions}.
1563
+ * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
1564
+ */
1565
+ create(options) {
1566
+ const instance = new _Consola({
1567
+ ...this.options,
1568
+ ...options
1569
+ });
1570
+ if (this._mockFn) {
1571
+ instance.mockTypes(this._mockFn);
1572
+ }
1573
+ return instance;
1574
+ }
1575
+ /**
1576
+ * Creates a new Consola instance with the specified default log object properties.
1577
+ *
1578
+ * @param {InputLogObject} defaults - Default properties to include in any log from the new instance. See {@link InputLogObject}.
1579
+ * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
1580
+ */
1581
+ withDefaults(defaults) {
1582
+ return this.create({
1583
+ ...this.options,
1584
+ defaults: {
1585
+ ...this.options.defaults,
1586
+ ...defaults
1587
+ }
1588
+ });
1589
+ }
1590
+ /**
1591
+ * Creates a new Consola instance with a specified tag, which will be included in every log.
1592
+ *
1593
+ * @param {string} tag - The tag to include in each log of the new instance.
1594
+ * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
1595
+ */
1596
+ withTag(tag) {
1597
+ return this.withDefaults({
1598
+ tag: this.options.defaults.tag ? this.options.defaults.tag + ":" + tag : tag
1599
+ });
1600
+ }
1601
+ /**
1602
+ * Adds a custom reporter to the Consola instance.
1603
+ * Reporters will be called for each log message, depending on their implementation and log level.
1604
+ *
1605
+ * @param {ConsolaReporter} reporter - The reporter to add. See {@link ConsolaReporter}.
1606
+ * @returns {Consola} The current Consola instance.
1607
+ */
1608
+ addReporter(reporter) {
1609
+ this.options.reporters.push(reporter);
1610
+ return this;
1611
+ }
1612
+ /**
1613
+ * Removes a custom reporter from the Consola instance.
1614
+ * If no reporter is specified, all reporters will be removed.
1615
+ *
1616
+ * @param {ConsolaReporter} reporter - The reporter to remove. See {@link ConsolaReporter}.
1617
+ * @returns {Consola} The current Consola instance.
1618
+ */
1619
+ removeReporter(reporter) {
1620
+ if (reporter) {
1621
+ const i2 = this.options.reporters.indexOf(reporter);
1622
+ if (i2 !== -1) {
1623
+ return this.options.reporters.splice(i2, 1);
1624
+ }
1625
+ } else {
1626
+ this.options.reporters.splice(0);
1627
+ }
1628
+ return this;
1629
+ }
1630
+ /**
1631
+ * Replaces all reporters of the Consola instance with the specified array of reporters.
1632
+ *
1633
+ * @param {ConsolaReporter[]} reporters - The new reporters to set. See {@link ConsolaReporter}.
1634
+ * @returns {Consola} The current Consola instance.
1635
+ */
1636
+ setReporters(reporters) {
1637
+ this.options.reporters = Array.isArray(reporters) ? reporters : [reporters];
1638
+ return this;
1639
+ }
1640
+ wrapAll() {
1641
+ this.wrapConsole();
1642
+ this.wrapStd();
1643
+ }
1644
+ restoreAll() {
1645
+ this.restoreConsole();
1646
+ this.restoreStd();
1647
+ }
1648
+ /**
1649
+ * Overrides console methods with Consola logging methods for consistent logging.
1650
+ */
1651
+ wrapConsole() {
1652
+ for (const type in this.options.types) {
1653
+ if (!console["__" + type]) {
1654
+ console["__" + type] = console[type];
1655
+ }
1656
+ console[type] = this[type].raw;
1657
+ }
1658
+ }
1659
+ /**
1660
+ * Restores the original console methods, removing Consola overrides.
1661
+ */
1662
+ restoreConsole() {
1663
+ for (const type in this.options.types) {
1664
+ if (console["__" + type]) {
1665
+ console[type] = console["__" + type];
1666
+ delete console["__" + type];
1667
+ }
1668
+ }
1669
+ }
1670
+ /**
1671
+ * Overrides standard output and error streams to redirect them through Consola.
1672
+ */
1673
+ wrapStd() {
1674
+ this._wrapStream(this.options.stdout, "log");
1675
+ this._wrapStream(this.options.stderr, "log");
1676
+ }
1677
+ _wrapStream(stream, type) {
1678
+ if (!stream) {
1679
+ return;
1680
+ }
1681
+ if (!stream.__write) {
1682
+ stream.__write = stream.write;
1683
+ }
1684
+ stream.write = (data) => {
1685
+ this[type].raw(String(data).trim());
1686
+ };
1687
+ }
1688
+ /**
1689
+ * Restores the original standard output and error streams, removing the Consola redirection.
1690
+ */
1691
+ restoreStd() {
1692
+ this._restoreStream(this.options.stdout);
1693
+ this._restoreStream(this.options.stderr);
1694
+ }
1695
+ _restoreStream(stream) {
1696
+ if (!stream) {
1697
+ return;
1698
+ }
1699
+ if (stream.__write) {
1700
+ stream.write = stream.__write;
1701
+ delete stream.__write;
1702
+ }
1703
+ }
1704
+ /**
1705
+ * Pauses logging, queues incoming logs until resumed.
1706
+ */
1707
+ pauseLogs() {
1708
+ paused = true;
1709
+ }
1710
+ /**
1711
+ * Resumes logging, processing any queued logs.
1712
+ */
1713
+ resumeLogs() {
1714
+ paused = false;
1715
+ const _queue = queue.splice(0);
1716
+ for (const item of _queue) {
1717
+ item[0]._logFn(item[1], item[2]);
1718
+ }
1719
+ }
1720
+ /**
1721
+ * Replaces logging methods with mocks if a mock function is provided.
1722
+ *
1723
+ * @param {ConsolaOptions["mockFn"]} mockFn - The function to use for mocking logging methods. See {@link ConsolaOptions["mockFn"]}.
1724
+ */
1725
+ mockTypes(mockFn) {
1726
+ const _mockFn = mockFn || this.options.mockFn;
1727
+ this._mockFn = _mockFn;
1728
+ if (typeof _mockFn !== "function") {
1729
+ return;
1730
+ }
1731
+ for (const type in this.options.types) {
1732
+ this[type] = _mockFn(type, this.options.types[type]) || this[type];
1733
+ this[type].raw = this[type];
1734
+ }
1735
+ }
1736
+ _wrapLogFn(defaults, isRaw) {
1737
+ return (...args) => {
1738
+ if (paused) {
1739
+ queue.push([this, defaults, args, isRaw]);
1740
+ return;
1741
+ }
1742
+ return this._logFn(defaults, args, isRaw);
1743
+ };
1744
+ }
1745
+ _logFn(defaults, args, isRaw) {
1746
+ if ((defaults.level || 0) > this.level) {
1747
+ return false;
1748
+ }
1749
+ const logObj = {
1750
+ date: /* @__PURE__ */ new Date(),
1751
+ args: [],
1752
+ ...defaults,
1753
+ level: _normalizeLogLevel(defaults.level, this.options.types)
1754
+ };
1755
+ if (!isRaw && args.length === 1 && isLogObj(args[0])) {
1756
+ Object.assign(logObj, args[0]);
1757
+ } else {
1758
+ logObj.args = [...args];
1759
+ }
1760
+ if (logObj.message) {
1761
+ logObj.args.unshift(logObj.message);
1762
+ delete logObj.message;
1763
+ }
1764
+ if (logObj.additional) {
1765
+ if (!Array.isArray(logObj.additional)) {
1766
+ logObj.additional = logObj.additional.split("\n");
1767
+ }
1768
+ logObj.args.push("\n" + logObj.additional.join("\n"));
1769
+ delete logObj.additional;
1770
+ }
1771
+ logObj.type = typeof logObj.type === "string" ? logObj.type.toLowerCase() : "log";
1772
+ logObj.tag = typeof logObj.tag === "string" ? logObj.tag : "";
1773
+ const resolveLog = (newLog = false) => {
1774
+ const repeated = (this._lastLog.count || 0) - this.options.throttleMin;
1775
+ if (this._lastLog.object && repeated > 0) {
1776
+ const args2 = [...this._lastLog.object.args];
1777
+ if (repeated > 1) {
1778
+ args2.push(`(repeated ${repeated} times)`);
1779
+ }
1780
+ this._log({ ...this._lastLog.object, args: args2 });
1781
+ this._lastLog.count = 1;
1782
+ }
1783
+ if (newLog) {
1784
+ this._lastLog.object = logObj;
1785
+ this._log(logObj);
1786
+ }
1787
+ };
1788
+ clearTimeout(this._lastLog.timeout);
1789
+ const diffTime = this._lastLog.time && logObj.date ? logObj.date.getTime() - this._lastLog.time.getTime() : 0;
1790
+ this._lastLog.time = logObj.date;
1791
+ if (diffTime < this.options.throttle) {
1792
+ try {
1793
+ const serializedLog = JSON.stringify([
1794
+ logObj.type,
1795
+ logObj.tag,
1796
+ logObj.args
1797
+ ]);
1798
+ const isSameLog = this._lastLog.serialized === serializedLog;
1799
+ this._lastLog.serialized = serializedLog;
1800
+ if (isSameLog) {
1801
+ this._lastLog.count = (this._lastLog.count || 0) + 1;
1802
+ if (this._lastLog.count > this.options.throttleMin) {
1803
+ this._lastLog.timeout = setTimeout(
1804
+ resolveLog,
1805
+ this.options.throttle
1806
+ );
1807
+ return;
1808
+ }
1809
+ }
1810
+ } catch {
1811
+ }
1812
+ }
1813
+ resolveLog(true);
1814
+ }
1815
+ _log(logObj) {
1816
+ for (const reporter of this.options.reporters) {
1817
+ reporter.log(logObj, {
1818
+ options: this.options
1819
+ });
1820
+ }
1821
+ }
1822
+ };
1823
+ function _normalizeLogLevel(input, types = {}, defaultLevel = 3) {
1824
+ if (input === void 0) {
1825
+ return defaultLevel;
1826
+ }
1827
+ if (typeof input === "number") {
1828
+ return input;
1829
+ }
1830
+ if (types[input] && types[input].level !== void 0) {
1831
+ return types[input].level;
1832
+ }
1833
+ return defaultLevel;
1834
+ }
1835
+ Consola.prototype.add = Consola.prototype.addReporter;
1836
+ Consola.prototype.remove = Consola.prototype.removeReporter;
1837
+ Consola.prototype.clear = Consola.prototype.removeReporter;
1838
+ Consola.prototype.withScope = Consola.prototype.withTag;
1839
+ Consola.prototype.mock = Consola.prototype.mockTypes;
1840
+ Consola.prototype.pause = Consola.prototype.pauseLogs;
1841
+ Consola.prototype.resume = Consola.prototype.resumeLogs;
1842
+ function createConsola(options = {}) {
1843
+ return new Consola(options);
1844
+ }
1845
+
1846
+ // ../../node_modules/.pnpm/consola@3.4.2/node_modules/consola/dist/shared/consola.DRwqZj3T.mjs
1847
+ import { formatWithOptions } from "util";
1848
+ import { sep } from "path";
1849
+ function parseStack(stack, message) {
1850
+ const cwd = process.cwd() + sep;
1851
+ const lines = stack.split("\n").splice(message.split("\n").length).map((l2) => l2.trim().replace("file://", "").replace(cwd, ""));
1852
+ return lines;
1853
+ }
1854
+ function writeStream(data, stream) {
1855
+ const write = stream.__write || stream.write;
1856
+ return write.call(stream, data);
1857
+ }
1858
+ var bracket = (x2) => x2 ? `[${x2}]` : "";
1859
+ var BasicReporter = class {
1860
+ formatStack(stack, message, opts) {
1861
+ const indent = " ".repeat((opts?.errorLevel || 0) + 1);
1862
+ return indent + parseStack(stack, message).join(`
1863
+ ${indent}`);
1864
+ }
1865
+ formatError(err, opts) {
1866
+ const message = err.message ?? formatWithOptions(opts, err);
1867
+ const stack = err.stack ? this.formatStack(err.stack, message, opts) : "";
1868
+ const level = opts?.errorLevel || 0;
1869
+ const causedPrefix = level > 0 ? `${" ".repeat(level)}[cause]: ` : "";
1870
+ const causedError = err.cause ? "\n\n" + this.formatError(err.cause, { ...opts, errorLevel: level + 1 }) : "";
1871
+ return causedPrefix + message + "\n" + stack + causedError;
1872
+ }
1873
+ formatArgs(args, opts) {
1874
+ const _args = args.map((arg) => {
1875
+ if (arg && typeof arg.stack === "string") {
1876
+ return this.formatError(arg, opts);
1877
+ }
1878
+ return arg;
1879
+ });
1880
+ return formatWithOptions(opts, ..._args);
1881
+ }
1882
+ formatDate(date, opts) {
1883
+ return opts.date ? date.toLocaleTimeString() : "";
1884
+ }
1885
+ filterAndJoin(arr) {
1886
+ return arr.filter(Boolean).join(" ");
1887
+ }
1888
+ formatLogObj(logObj, opts) {
1889
+ const message = this.formatArgs(logObj.args, opts);
1890
+ if (logObj.type === "box") {
1891
+ return "\n" + [
1892
+ bracket(logObj.tag),
1893
+ logObj.title && logObj.title,
1894
+ ...message.split("\n")
1895
+ ].filter(Boolean).map((l2) => " > " + l2).join("\n") + "\n";
1896
+ }
1897
+ return this.filterAndJoin([
1898
+ bracket(logObj.type),
1899
+ bracket(logObj.tag),
1900
+ message
1901
+ ]);
1902
+ }
1903
+ log(logObj, ctx) {
1904
+ const line = this.formatLogObj(logObj, {
1905
+ columns: ctx.options.stdout.columns || 0,
1906
+ ...ctx.options.formatOptions
1907
+ });
1908
+ return writeStream(
1909
+ line + "\n",
1910
+ logObj.level < 2 ? ctx.options.stderr || process.stderr : ctx.options.stdout || process.stdout
1911
+ );
1912
+ }
1913
+ };
1914
+
1915
+ // ../../node_modules/.pnpm/consola@3.4.2/node_modules/consola/dist/index.mjs
1916
+ import g$1 from "process";
1917
+
1918
+ // ../../node_modules/.pnpm/consola@3.4.2/node_modules/consola/dist/shared/consola.DXBYu-KD.mjs
1919
+ import * as tty from "tty";
1920
+ var {
1921
+ env = {},
1922
+ argv = [],
1923
+ platform = ""
1924
+ } = typeof process === "undefined" ? {} : process;
1925
+ var isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
1926
+ var isForced = "FORCE_COLOR" in env || argv.includes("--color");
1927
+ var isWindows = platform === "win32";
1928
+ var isDumbTerminal = env.TERM === "dumb";
1929
+ var isCompatibleTerminal = tty && tty.isatty && tty.isatty(1) && env.TERM && !isDumbTerminal;
1930
+ var isCI = "CI" in env && ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
1931
+ var isColorSupported = !isDisabled && (isForced || isWindows && !isDumbTerminal || isCompatibleTerminal || isCI);
1932
+ function replaceClose(index, string, close, replace, head = string.slice(0, Math.max(0, index)) + replace, tail = string.slice(Math.max(0, index + close.length)), next = tail.indexOf(close)) {
1933
+ return head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
1934
+ }
1935
+ function clearBleed(index, string, open, close, replace) {
1936
+ return index < 0 ? open + string + close : open + replaceClose(index, string, close, replace) + close;
1937
+ }
1938
+ function filterEmpty(open, close, replace = open, at = open.length + 1) {
1939
+ return (string) => string || !(string === "" || string === void 0) ? clearBleed(
1940
+ ("" + string).indexOf(close, at),
1941
+ string,
1942
+ open,
1943
+ close,
1944
+ replace
1945
+ ) : "";
1946
+ }
1947
+ function init(open, close, replace) {
1948
+ return filterEmpty(`\x1B[${open}m`, `\x1B[${close}m`, replace);
1949
+ }
1950
+ var colorDefs = {
1951
+ reset: init(0, 0),
1952
+ bold: init(1, 22, "\x1B[22m\x1B[1m"),
1953
+ dim: init(2, 22, "\x1B[22m\x1B[2m"),
1954
+ italic: init(3, 23),
1955
+ underline: init(4, 24),
1956
+ inverse: init(7, 27),
1957
+ hidden: init(8, 28),
1958
+ strikethrough: init(9, 29),
1959
+ black: init(30, 39),
1960
+ red: init(31, 39),
1961
+ green: init(32, 39),
1962
+ yellow: init(33, 39),
1963
+ blue: init(34, 39),
1964
+ magenta: init(35, 39),
1965
+ cyan: init(36, 39),
1966
+ white: init(37, 39),
1967
+ gray: init(90, 39),
1968
+ bgBlack: init(40, 49),
1969
+ bgRed: init(41, 49),
1970
+ bgGreen: init(42, 49),
1971
+ bgYellow: init(43, 49),
1972
+ bgBlue: init(44, 49),
1973
+ bgMagenta: init(45, 49),
1974
+ bgCyan: init(46, 49),
1975
+ bgWhite: init(47, 49),
1976
+ blackBright: init(90, 39),
1977
+ redBright: init(91, 39),
1978
+ greenBright: init(92, 39),
1979
+ yellowBright: init(93, 39),
1980
+ blueBright: init(94, 39),
1981
+ magentaBright: init(95, 39),
1982
+ cyanBright: init(96, 39),
1983
+ whiteBright: init(97, 39),
1984
+ bgBlackBright: init(100, 49),
1985
+ bgRedBright: init(101, 49),
1986
+ bgGreenBright: init(102, 49),
1987
+ bgYellowBright: init(103, 49),
1988
+ bgBlueBright: init(104, 49),
1989
+ bgMagentaBright: init(105, 49),
1990
+ bgCyanBright: init(106, 49),
1991
+ bgWhiteBright: init(107, 49)
1992
+ };
1993
+ function createColors(useColor = isColorSupported) {
1994
+ return useColor ? colorDefs : Object.fromEntries(Object.keys(colorDefs).map((key) => [key, String]));
1995
+ }
1996
+ var colors = createColors();
1997
+ function getColor(color, fallback = "reset") {
1998
+ return colors[color] || colors[fallback];
1999
+ }
2000
+ var ansiRegex = [
2001
+ String.raw`[\u001B\u009B][[\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\d\/#&.:=?%@~_]+)*|[a-zA-Z\d]+(?:;[-a-zA-Z\d\/#&.:=?%@~_]*)*)?\u0007)`,
2002
+ String.raw`(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))`
2003
+ ].join("|");
2004
+ function stripAnsi(text) {
2005
+ return text.replace(new RegExp(ansiRegex, "g"), "");
2006
+ }
2007
+ var boxStylePresets = {
2008
+ solid: {
2009
+ tl: "\u250C",
2010
+ tr: "\u2510",
2011
+ bl: "\u2514",
2012
+ br: "\u2518",
2013
+ h: "\u2500",
2014
+ v: "\u2502"
2015
+ },
2016
+ double: {
2017
+ tl: "\u2554",
2018
+ tr: "\u2557",
2019
+ bl: "\u255A",
2020
+ br: "\u255D",
2021
+ h: "\u2550",
2022
+ v: "\u2551"
2023
+ },
2024
+ doubleSingle: {
2025
+ tl: "\u2553",
2026
+ tr: "\u2556",
2027
+ bl: "\u2559",
2028
+ br: "\u255C",
2029
+ h: "\u2500",
2030
+ v: "\u2551"
2031
+ },
2032
+ doubleSingleRounded: {
2033
+ tl: "\u256D",
2034
+ tr: "\u256E",
2035
+ bl: "\u2570",
2036
+ br: "\u256F",
2037
+ h: "\u2500",
2038
+ v: "\u2551"
2039
+ },
2040
+ singleThick: {
2041
+ tl: "\u250F",
2042
+ tr: "\u2513",
2043
+ bl: "\u2517",
2044
+ br: "\u251B",
2045
+ h: "\u2501",
2046
+ v: "\u2503"
2047
+ },
2048
+ singleDouble: {
2049
+ tl: "\u2552",
2050
+ tr: "\u2555",
2051
+ bl: "\u2558",
2052
+ br: "\u255B",
2053
+ h: "\u2550",
2054
+ v: "\u2502"
2055
+ },
2056
+ singleDoubleRounded: {
2057
+ tl: "\u256D",
2058
+ tr: "\u256E",
2059
+ bl: "\u2570",
2060
+ br: "\u256F",
2061
+ h: "\u2550",
2062
+ v: "\u2502"
2063
+ },
2064
+ rounded: {
2065
+ tl: "\u256D",
2066
+ tr: "\u256E",
2067
+ bl: "\u2570",
2068
+ br: "\u256F",
2069
+ h: "\u2500",
2070
+ v: "\u2502"
2071
+ }
2072
+ };
2073
+ var defaultStyle = {
2074
+ borderColor: "white",
2075
+ borderStyle: "rounded",
2076
+ valign: "center",
2077
+ padding: 2,
2078
+ marginLeft: 1,
2079
+ marginTop: 1,
2080
+ marginBottom: 1
2081
+ };
2082
+ function box(text, _opts = {}) {
2083
+ const opts = {
2084
+ ..._opts,
2085
+ style: {
2086
+ ...defaultStyle,
2087
+ ..._opts.style
2088
+ }
2089
+ };
2090
+ const textLines = text.split("\n");
2091
+ const boxLines = [];
2092
+ const _color = getColor(opts.style.borderColor);
2093
+ const borderStyle = {
2094
+ ...typeof opts.style.borderStyle === "string" ? boxStylePresets[opts.style.borderStyle] || boxStylePresets.solid : opts.style.borderStyle
2095
+ };
2096
+ if (_color) {
2097
+ for (const key in borderStyle) {
2098
+ borderStyle[key] = _color(
2099
+ borderStyle[key]
2100
+ );
2101
+ }
2102
+ }
2103
+ const paddingOffset = opts.style.padding % 2 === 0 ? opts.style.padding : opts.style.padding + 1;
2104
+ const height = textLines.length + paddingOffset;
2105
+ const width = Math.max(
2106
+ ...textLines.map((line) => stripAnsi(line).length),
2107
+ opts.title ? stripAnsi(opts.title).length : 0
2108
+ ) + paddingOffset;
2109
+ const widthOffset = width + paddingOffset;
2110
+ const leftSpace = opts.style.marginLeft > 0 ? " ".repeat(opts.style.marginLeft) : "";
2111
+ if (opts.style.marginTop > 0) {
2112
+ boxLines.push("".repeat(opts.style.marginTop));
2113
+ }
2114
+ if (opts.title) {
2115
+ const title = _color ? _color(opts.title) : opts.title;
2116
+ const left = borderStyle.h.repeat(
2117
+ Math.floor((width - stripAnsi(opts.title).length) / 2)
2118
+ );
2119
+ const right = borderStyle.h.repeat(
2120
+ width - stripAnsi(opts.title).length - stripAnsi(left).length + paddingOffset
2121
+ );
2122
+ boxLines.push(
2123
+ `${leftSpace}${borderStyle.tl}${left}${title}${right}${borderStyle.tr}`
2124
+ );
2125
+ } else {
2126
+ boxLines.push(
2127
+ `${leftSpace}${borderStyle.tl}${borderStyle.h.repeat(widthOffset)}${borderStyle.tr}`
2128
+ );
2129
+ }
2130
+ const valignOffset = opts.style.valign === "center" ? Math.floor((height - textLines.length) / 2) : opts.style.valign === "top" ? height - textLines.length - paddingOffset : height - textLines.length;
2131
+ for (let i2 = 0; i2 < height; i2++) {
2132
+ if (i2 < valignOffset || i2 >= valignOffset + textLines.length) {
2133
+ boxLines.push(
2134
+ `${leftSpace}${borderStyle.v}${" ".repeat(widthOffset)}${borderStyle.v}`
2135
+ );
2136
+ } else {
2137
+ const line = textLines[i2 - valignOffset];
2138
+ const left = " ".repeat(paddingOffset);
2139
+ const right = " ".repeat(width - stripAnsi(line).length);
2140
+ boxLines.push(
2141
+ `${leftSpace}${borderStyle.v}${left}${line}${right}${borderStyle.v}`
2142
+ );
2143
+ }
2144
+ }
2145
+ boxLines.push(
2146
+ `${leftSpace}${borderStyle.bl}${borderStyle.h.repeat(widthOffset)}${borderStyle.br}`
2147
+ );
2148
+ if (opts.style.marginBottom > 0) {
2149
+ boxLines.push("".repeat(opts.style.marginBottom));
2150
+ }
2151
+ return boxLines.join("\n");
2152
+ }
2153
+
2154
+ // ../../node_modules/.pnpm/consola@3.4.2/node_modules/consola/dist/index.mjs
2155
+ import "util";
2156
+ import "path";
2157
+ import "tty";
2158
+ var r2 = /* @__PURE__ */ Object.create(null);
2159
+ var i = (e2) => globalThis.process?.env || import.meta.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (e2 ? r2 : globalThis);
2160
+ var o2 = new Proxy(r2, { get(e2, s2) {
2161
+ return i()[s2] ?? r2[s2];
2162
+ }, has(e2, s2) {
2163
+ const E = i();
2164
+ return s2 in E || s2 in r2;
2165
+ }, set(e2, s2, E) {
2166
+ const B2 = i(true);
2167
+ return B2[s2] = E, true;
2168
+ }, deleteProperty(e2, s2) {
2169
+ if (!s2) return false;
2170
+ const E = i(true);
2171
+ return delete E[s2], true;
2172
+ }, ownKeys() {
2173
+ const e2 = i(true);
2174
+ return Object.keys(e2);
2175
+ } });
2176
+ var t = typeof process < "u" && process.env && process.env.NODE_ENV || "";
2177
+ var f2 = [["APPVEYOR"], ["AWS_AMPLIFY", "AWS_APP_ID", { ci: true }], ["AZURE_PIPELINES", "SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"], ["AZURE_STATIC", "INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN"], ["APPCIRCLE", "AC_APPCIRCLE"], ["BAMBOO", "bamboo_planKey"], ["BITBUCKET", "BITBUCKET_COMMIT"], ["BITRISE", "BITRISE_IO"], ["BUDDY", "BUDDY_WORKSPACE_ID"], ["BUILDKITE"], ["CIRCLE", "CIRCLECI"], ["CIRRUS", "CIRRUS_CI"], ["CLOUDFLARE_PAGES", "CF_PAGES", { ci: true }], ["CODEBUILD", "CODEBUILD_BUILD_ARN"], ["CODEFRESH", "CF_BUILD_ID"], ["DRONE"], ["DRONE", "DRONE_BUILD_EVENT"], ["DSARI"], ["GITHUB_ACTIONS"], ["GITLAB", "GITLAB_CI"], ["GITLAB", "CI_MERGE_REQUEST_ID"], ["GOCD", "GO_PIPELINE_LABEL"], ["LAYERCI"], ["HUDSON", "HUDSON_URL"], ["JENKINS", "JENKINS_URL"], ["MAGNUM"], ["NETLIFY"], ["NETLIFY", "NETLIFY_LOCAL", { ci: false }], ["NEVERCODE"], ["RENDER"], ["SAIL", "SAILCI"], ["SEMAPHORE"], ["SCREWDRIVER"], ["SHIPPABLE"], ["SOLANO", "TDDIUM"], ["STRIDER"], ["TEAMCITY", "TEAMCITY_VERSION"], ["TRAVIS"], ["VERCEL", "NOW_BUILDER"], ["VERCEL", "VERCEL", { ci: false }], ["VERCEL", "VERCEL_ENV", { ci: false }], ["APPCENTER", "APPCENTER_BUILD_ID"], ["CODESANDBOX", "CODESANDBOX_SSE", { ci: false }], ["CODESANDBOX", "CODESANDBOX_HOST", { ci: false }], ["STACKBLITZ"], ["STORMKIT"], ["CLEAVR"], ["ZEABUR"], ["CODESPHERE", "CODESPHERE_APP_ID", { ci: true }], ["RAILWAY", "RAILWAY_PROJECT_ID"], ["RAILWAY", "RAILWAY_SERVICE_ID"], ["DENO-DEPLOY", "DENO_DEPLOYMENT_ID"], ["FIREBASE_APP_HOSTING", "FIREBASE_APP_HOSTING", { ci: true }]];
2178
+ function b() {
2179
+ if (globalThis.process?.env) for (const e2 of f2) {
2180
+ const s2 = e2[1] || e2[0];
2181
+ if (globalThis.process?.env[s2]) return { name: e2[0].toLowerCase(), ...e2[2] };
2182
+ }
2183
+ return globalThis.process?.env?.SHELL === "/bin/jsh" && globalThis.process?.versions?.webcontainer ? { name: "stackblitz", ci: false } : { name: "", ci: false };
2184
+ }
2185
+ var l = b();
2186
+ l.name;
2187
+ function n(e2) {
2188
+ return e2 ? e2 !== "false" : false;
2189
+ }
2190
+ var I2 = globalThis.process?.platform || "";
2191
+ var T2 = n(o2.CI) || l.ci !== false;
2192
+ var a = n(globalThis.process?.stdout && globalThis.process?.stdout.isTTY);
2193
+ var g2 = n(o2.DEBUG);
2194
+ var R2 = t === "test" || n(o2.TEST);
2195
+ n(o2.MINIMAL) || T2 || R2 || !a;
2196
+ var A2 = /^win/i.test(I2);
2197
+ !n(o2.NO_COLOR) && (n(o2.FORCE_COLOR) || (a || A2) && o2.TERM !== "dumb" || T2);
2198
+ var C2 = (globalThis.process?.versions?.node || "").replace(/^v/, "") || null;
2199
+ Number(C2?.split(".")[0]) || null;
2200
+ var y2 = globalThis.process || /* @__PURE__ */ Object.create(null);
2201
+ var _2 = { versions: {} };
2202
+ new Proxy(y2, { get(e2, s2) {
2203
+ if (s2 === "env") return o2;
2204
+ if (s2 in e2) return e2[s2];
2205
+ if (s2 in _2) return _2[s2];
2206
+ } });
2207
+ var c2 = globalThis.process?.release?.name === "node";
2208
+ var O2 = !!globalThis.Bun || !!globalThis.process?.versions?.bun;
2209
+ var D = !!globalThis.Deno;
2210
+ var L2 = !!globalThis.fastly;
2211
+ var S2 = !!globalThis.Netlify;
2212
+ var u2 = !!globalThis.EdgeRuntime;
2213
+ var N2 = globalThis.navigator?.userAgent === "Cloudflare-Workers";
2214
+ var F2 = [[S2, "netlify"], [u2, "edge-light"], [N2, "workerd"], [L2, "fastly"], [D, "deno"], [O2, "bun"], [c2, "node"]];
2215
+ function G2() {
2216
+ const e2 = F2.find((s2) => s2[0]);
2217
+ if (e2) return { name: e2[1] };
2218
+ }
2219
+ var P2 = G2();
2220
+ P2?.name || "";
2221
+ function ansiRegex2({ onlyFirst = false } = {}) {
2222
+ const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
2223
+ const pattern = [
2224
+ `[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?${ST})`,
2225
+ "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"
2226
+ ].join("|");
2227
+ return new RegExp(pattern, onlyFirst ? void 0 : "g");
2228
+ }
2229
+ var regex = ansiRegex2();
2230
+ function stripAnsi2(string) {
2231
+ if (typeof string !== "string") {
2232
+ throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
2233
+ }
2234
+ return string.replace(regex, "");
2235
+ }
2236
+ function isAmbiguous(x2) {
2237
+ return x2 === 161 || x2 === 164 || x2 === 167 || x2 === 168 || x2 === 170 || x2 === 173 || x2 === 174 || x2 >= 176 && x2 <= 180 || x2 >= 182 && x2 <= 186 || x2 >= 188 && x2 <= 191 || x2 === 198 || x2 === 208 || x2 === 215 || x2 === 216 || x2 >= 222 && x2 <= 225 || x2 === 230 || x2 >= 232 && x2 <= 234 || x2 === 236 || x2 === 237 || x2 === 240 || x2 === 242 || x2 === 243 || x2 >= 247 && x2 <= 250 || x2 === 252 || x2 === 254 || x2 === 257 || x2 === 273 || x2 === 275 || x2 === 283 || x2 === 294 || x2 === 295 || x2 === 299 || x2 >= 305 && x2 <= 307 || x2 === 312 || x2 >= 319 && x2 <= 322 || x2 === 324 || x2 >= 328 && x2 <= 331 || x2 === 333 || x2 === 338 || x2 === 339 || x2 === 358 || x2 === 359 || x2 === 363 || x2 === 462 || x2 === 464 || x2 === 466 || x2 === 468 || x2 === 470 || x2 === 472 || x2 === 474 || x2 === 476 || x2 === 593 || x2 === 609 || x2 === 708 || x2 === 711 || x2 >= 713 && x2 <= 715 || x2 === 717 || x2 === 720 || x2 >= 728 && x2 <= 731 || x2 === 733 || x2 === 735 || x2 >= 768 && x2 <= 879 || x2 >= 913 && x2 <= 929 || x2 >= 931 && x2 <= 937 || x2 >= 945 && x2 <= 961 || x2 >= 963 && x2 <= 969 || x2 === 1025 || x2 >= 1040 && x2 <= 1103 || x2 === 1105 || x2 === 8208 || x2 >= 8211 && x2 <= 8214 || x2 === 8216 || x2 === 8217 || x2 === 8220 || x2 === 8221 || x2 >= 8224 && x2 <= 8226 || x2 >= 8228 && x2 <= 8231 || x2 === 8240 || x2 === 8242 || x2 === 8243 || x2 === 8245 || x2 === 8251 || x2 === 8254 || x2 === 8308 || x2 === 8319 || x2 >= 8321 && x2 <= 8324 || x2 === 8364 || x2 === 8451 || x2 === 8453 || x2 === 8457 || x2 === 8467 || x2 === 8470 || x2 === 8481 || x2 === 8482 || x2 === 8486 || x2 === 8491 || x2 === 8531 || x2 === 8532 || x2 >= 8539 && x2 <= 8542 || x2 >= 8544 && x2 <= 8555 || x2 >= 8560 && x2 <= 8569 || x2 === 8585 || x2 >= 8592 && x2 <= 8601 || x2 === 8632 || x2 === 8633 || x2 === 8658 || x2 === 8660 || x2 === 8679 || x2 === 8704 || x2 === 8706 || x2 === 8707 || x2 === 8711 || x2 === 8712 || x2 === 8715 || x2 === 8719 || x2 === 8721 || x2 === 8725 || x2 === 8730 || x2 >= 8733 && x2 <= 8736 || x2 === 8739 || x2 === 8741 || x2 >= 8743 && x2 <= 8748 || x2 === 8750 || x2 >= 8756 && x2 <= 8759 || x2 === 8764 || x2 === 8765 || x2 === 8776 || x2 === 8780 || x2 === 8786 || x2 === 8800 || x2 === 8801 || x2 >= 8804 && x2 <= 8807 || x2 === 8810 || x2 === 8811 || x2 === 8814 || x2 === 8815 || x2 === 8834 || x2 === 8835 || x2 === 8838 || x2 === 8839 || x2 === 8853 || x2 === 8857 || x2 === 8869 || x2 === 8895 || x2 === 8978 || x2 >= 9312 && x2 <= 9449 || x2 >= 9451 && x2 <= 9547 || x2 >= 9552 && x2 <= 9587 || x2 >= 9600 && x2 <= 9615 || x2 >= 9618 && x2 <= 9621 || x2 === 9632 || x2 === 9633 || x2 >= 9635 && x2 <= 9641 || x2 === 9650 || x2 === 9651 || x2 === 9654 || x2 === 9655 || x2 === 9660 || x2 === 9661 || x2 === 9664 || x2 === 9665 || x2 >= 9670 && x2 <= 9672 || x2 === 9675 || x2 >= 9678 && x2 <= 9681 || x2 >= 9698 && x2 <= 9701 || x2 === 9711 || x2 === 9733 || x2 === 9734 || x2 === 9737 || x2 === 9742 || x2 === 9743 || x2 === 9756 || x2 === 9758 || x2 === 9792 || x2 === 9794 || x2 === 9824 || x2 === 9825 || x2 >= 9827 && x2 <= 9829 || x2 >= 9831 && x2 <= 9834 || x2 === 9836 || x2 === 9837 || x2 === 9839 || x2 === 9886 || x2 === 9887 || x2 === 9919 || x2 >= 9926 && x2 <= 9933 || x2 >= 9935 && x2 <= 9939 || x2 >= 9941 && x2 <= 9953 || x2 === 9955 || x2 === 9960 || x2 === 9961 || x2 >= 9963 && x2 <= 9969 || x2 === 9972 || x2 >= 9974 && x2 <= 9977 || x2 === 9979 || x2 === 9980 || x2 === 9982 || x2 === 9983 || x2 === 10045 || x2 >= 10102 && x2 <= 10111 || x2 >= 11094 && x2 <= 11097 || x2 >= 12872 && x2 <= 12879 || x2 >= 57344 && x2 <= 63743 || x2 >= 65024 && x2 <= 65039 || x2 === 65533 || x2 >= 127232 && x2 <= 127242 || x2 >= 127248 && x2 <= 127277 || x2 >= 127280 && x2 <= 127337 || x2 >= 127344 && x2 <= 127373 || x2 === 127375 || x2 === 127376 || x2 >= 127387 && x2 <= 127404 || x2 >= 917760 && x2 <= 917999 || x2 >= 983040 && x2 <= 1048573 || x2 >= 1048576 && x2 <= 1114109;
2238
+ }
2239
+ function isFullWidth(x2) {
2240
+ return x2 === 12288 || x2 >= 65281 && x2 <= 65376 || x2 >= 65504 && x2 <= 65510;
2241
+ }
2242
+ function isWide(x2) {
2243
+ return x2 >= 4352 && x2 <= 4447 || x2 === 8986 || x2 === 8987 || x2 === 9001 || x2 === 9002 || x2 >= 9193 && x2 <= 9196 || x2 === 9200 || x2 === 9203 || x2 === 9725 || x2 === 9726 || x2 === 9748 || x2 === 9749 || x2 >= 9776 && x2 <= 9783 || x2 >= 9800 && x2 <= 9811 || x2 === 9855 || x2 >= 9866 && x2 <= 9871 || x2 === 9875 || x2 === 9889 || x2 === 9898 || x2 === 9899 || x2 === 9917 || x2 === 9918 || x2 === 9924 || x2 === 9925 || x2 === 9934 || x2 === 9940 || x2 === 9962 || x2 === 9970 || x2 === 9971 || x2 === 9973 || x2 === 9978 || x2 === 9981 || x2 === 9989 || x2 === 9994 || x2 === 9995 || x2 === 10024 || x2 === 10060 || x2 === 10062 || x2 >= 10067 && x2 <= 10069 || x2 === 10071 || x2 >= 10133 && x2 <= 10135 || x2 === 10160 || x2 === 10175 || x2 === 11035 || x2 === 11036 || x2 === 11088 || x2 === 11093 || x2 >= 11904 && x2 <= 11929 || x2 >= 11931 && x2 <= 12019 || x2 >= 12032 && x2 <= 12245 || x2 >= 12272 && x2 <= 12287 || x2 >= 12289 && x2 <= 12350 || x2 >= 12353 && x2 <= 12438 || x2 >= 12441 && x2 <= 12543 || x2 >= 12549 && x2 <= 12591 || x2 >= 12593 && x2 <= 12686 || x2 >= 12688 && x2 <= 12773 || x2 >= 12783 && x2 <= 12830 || x2 >= 12832 && x2 <= 12871 || x2 >= 12880 && x2 <= 42124 || x2 >= 42128 && x2 <= 42182 || x2 >= 43360 && x2 <= 43388 || x2 >= 44032 && x2 <= 55203 || x2 >= 63744 && x2 <= 64255 || x2 >= 65040 && x2 <= 65049 || x2 >= 65072 && x2 <= 65106 || x2 >= 65108 && x2 <= 65126 || x2 >= 65128 && x2 <= 65131 || x2 >= 94176 && x2 <= 94180 || x2 === 94192 || x2 === 94193 || x2 >= 94208 && x2 <= 100343 || x2 >= 100352 && x2 <= 101589 || x2 >= 101631 && x2 <= 101640 || x2 >= 110576 && x2 <= 110579 || x2 >= 110581 && x2 <= 110587 || x2 === 110589 || x2 === 110590 || x2 >= 110592 && x2 <= 110882 || x2 === 110898 || x2 >= 110928 && x2 <= 110930 || x2 === 110933 || x2 >= 110948 && x2 <= 110951 || x2 >= 110960 && x2 <= 111355 || x2 >= 119552 && x2 <= 119638 || x2 >= 119648 && x2 <= 119670 || x2 === 126980 || x2 === 127183 || x2 === 127374 || x2 >= 127377 && x2 <= 127386 || x2 >= 127488 && x2 <= 127490 || x2 >= 127504 && x2 <= 127547 || x2 >= 127552 && x2 <= 127560 || x2 === 127568 || x2 === 127569 || x2 >= 127584 && x2 <= 127589 || x2 >= 127744 && x2 <= 127776 || x2 >= 127789 && x2 <= 127797 || x2 >= 127799 && x2 <= 127868 || x2 >= 127870 && x2 <= 127891 || x2 >= 127904 && x2 <= 127946 || x2 >= 127951 && x2 <= 127955 || x2 >= 127968 && x2 <= 127984 || x2 === 127988 || x2 >= 127992 && x2 <= 128062 || x2 === 128064 || x2 >= 128066 && x2 <= 128252 || x2 >= 128255 && x2 <= 128317 || x2 >= 128331 && x2 <= 128334 || x2 >= 128336 && x2 <= 128359 || x2 === 128378 || x2 === 128405 || x2 === 128406 || x2 === 128420 || x2 >= 128507 && x2 <= 128591 || x2 >= 128640 && x2 <= 128709 || x2 === 128716 || x2 >= 128720 && x2 <= 128722 || x2 >= 128725 && x2 <= 128727 || x2 >= 128732 && x2 <= 128735 || x2 === 128747 || x2 === 128748 || x2 >= 128756 && x2 <= 128764 || x2 >= 128992 && x2 <= 129003 || x2 === 129008 || x2 >= 129292 && x2 <= 129338 || x2 >= 129340 && x2 <= 129349 || x2 >= 129351 && x2 <= 129535 || x2 >= 129648 && x2 <= 129660 || x2 >= 129664 && x2 <= 129673 || x2 >= 129679 && x2 <= 129734 || x2 >= 129742 && x2 <= 129756 || x2 >= 129759 && x2 <= 129769 || x2 >= 129776 && x2 <= 129784 || x2 >= 131072 && x2 <= 196605 || x2 >= 196608 && x2 <= 262141;
2244
+ }
2245
+ function validate(codePoint) {
2246
+ if (!Number.isSafeInteger(codePoint)) {
2247
+ throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
2248
+ }
2249
+ }
2250
+ function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) {
2251
+ validate(codePoint);
2252
+ if (isFullWidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) {
2253
+ return 2;
2254
+ }
2255
+ return 1;
2256
+ }
2257
+ var emojiRegex = () => {
2258
+ return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\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?|[\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](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\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-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;
2259
+ };
2260
+ var segmenter = globalThis.Intl?.Segmenter ? new Intl.Segmenter() : { segment: (str) => str.split("") };
2261
+ var defaultIgnorableCodePointRegex = new RegExp("^\\p{Default_Ignorable_Code_Point}$", "u");
2262
+ function stringWidth$1(string, options = {}) {
2263
+ if (typeof string !== "string" || string.length === 0) {
2264
+ return 0;
2265
+ }
2266
+ const {
2267
+ ambiguousIsNarrow = true,
2268
+ countAnsiEscapeCodes = false
2269
+ } = options;
2270
+ if (!countAnsiEscapeCodes) {
2271
+ string = stripAnsi2(string);
2272
+ }
2273
+ if (string.length === 0) {
2274
+ return 0;
2275
+ }
2276
+ let width = 0;
2277
+ const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
2278
+ for (const { segment: character } of segmenter.segment(string)) {
2279
+ const codePoint = character.codePointAt(0);
2280
+ if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) {
2281
+ continue;
2282
+ }
2283
+ if (codePoint >= 8203 && codePoint <= 8207 || codePoint === 65279) {
2284
+ continue;
2285
+ }
2286
+ if (codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071) {
2287
+ continue;
2288
+ }
2289
+ if (codePoint >= 55296 && codePoint <= 57343) {
2290
+ continue;
2291
+ }
2292
+ if (codePoint >= 65024 && codePoint <= 65039) {
2293
+ continue;
2294
+ }
2295
+ if (defaultIgnorableCodePointRegex.test(character)) {
2296
+ continue;
2297
+ }
2298
+ if (emojiRegex().test(character)) {
2299
+ width += 2;
2300
+ continue;
2301
+ }
2302
+ width += eastAsianWidth(codePoint, eastAsianWidthOptions);
2303
+ }
2304
+ return width;
2305
+ }
2306
+ function isUnicodeSupported() {
2307
+ const { env: env2 } = g$1;
2308
+ const { TERM, TERM_PROGRAM } = env2;
2309
+ if (g$1.platform !== "win32") {
2310
+ return TERM !== "linux";
2311
+ }
2312
+ return Boolean(env2.WT_SESSION) || Boolean(env2.TERMINUS_SUBLIME) || env2.ConEmuTask === "{cmd::Cmder}" || TERM_PROGRAM === "Terminus-Sublime" || TERM_PROGRAM === "vscode" || TERM === "xterm-256color" || TERM === "alacritty" || TERM === "rxvt-unicode" || TERM === "rxvt-unicode-256color" || env2.TERMINAL_EMULATOR === "JetBrains-JediTerm";
2313
+ }
2314
+ var TYPE_COLOR_MAP = {
2315
+ info: "cyan",
2316
+ fail: "red",
2317
+ success: "green",
2318
+ ready: "green",
2319
+ start: "magenta"
2320
+ };
2321
+ var LEVEL_COLOR_MAP = {
2322
+ 0: "red",
2323
+ 1: "yellow"
2324
+ };
2325
+ var unicode = isUnicodeSupported();
2326
+ var s = (c3, fallback) => unicode ? c3 : fallback;
2327
+ var TYPE_ICONS = {
2328
+ error: s("\u2716", "\xD7"),
2329
+ fatal: s("\u2716", "\xD7"),
2330
+ ready: s("\u2714", "\u221A"),
2331
+ warn: s("\u26A0", "\u203C"),
2332
+ info: s("\u2139", "i"),
2333
+ success: s("\u2714", "\u221A"),
2334
+ debug: s("\u2699", "D"),
2335
+ trace: s("\u2192", "\u2192"),
2336
+ fail: s("\u2716", "\xD7"),
2337
+ start: s("\u25D0", "o"),
2338
+ log: ""
2339
+ };
2340
+ function stringWidth(str) {
2341
+ const hasICU = typeof Intl === "object";
2342
+ if (!hasICU || !Intl.Segmenter) {
2343
+ return stripAnsi(str).length;
2344
+ }
2345
+ return stringWidth$1(str);
2346
+ }
2347
+ var FancyReporter = class extends BasicReporter {
2348
+ formatStack(stack, message, opts) {
2349
+ const indent = " ".repeat((opts?.errorLevel || 0) + 1);
2350
+ return `
2351
+ ${indent}` + parseStack(stack, message).map(
2352
+ (line) => " " + line.replace(/^at +/, (m2) => colors.gray(m2)).replace(/\((.+)\)/, (_3, m2) => `(${colors.cyan(m2)})`)
2353
+ ).join(`
2354
+ ${indent}`);
2355
+ }
2356
+ formatType(logObj, isBadge, opts) {
2357
+ const typeColor = TYPE_COLOR_MAP[logObj.type] || LEVEL_COLOR_MAP[logObj.level] || "gray";
2358
+ if (isBadge) {
2359
+ return getBgColor(typeColor)(
2360
+ colors.black(` ${logObj.type.toUpperCase()} `)
2361
+ );
2362
+ }
2363
+ const _type = typeof TYPE_ICONS[logObj.type] === "string" ? TYPE_ICONS[logObj.type] : logObj.icon || logObj.type;
2364
+ return _type ? getColor2(typeColor)(_type) : "";
2365
+ }
2366
+ formatLogObj(logObj, opts) {
2367
+ const [message, ...additional] = this.formatArgs(logObj.args, opts).split(
2368
+ "\n"
2369
+ );
2370
+ if (logObj.type === "box") {
2371
+ return box(
2372
+ characterFormat(
2373
+ message + (additional.length > 0 ? "\n" + additional.join("\n") : "")
2374
+ ),
2375
+ {
2376
+ title: logObj.title ? characterFormat(logObj.title) : void 0,
2377
+ style: logObj.style
2378
+ }
2379
+ );
2380
+ }
2381
+ const date = this.formatDate(logObj.date, opts);
2382
+ const coloredDate = date && colors.gray(date);
2383
+ const isBadge = logObj.badge ?? logObj.level < 2;
2384
+ const type = this.formatType(logObj, isBadge, opts);
2385
+ const tag = logObj.tag ? colors.gray(logObj.tag) : "";
2386
+ let line;
2387
+ const left = this.filterAndJoin([type, characterFormat(message)]);
2388
+ const right = this.filterAndJoin(opts.columns ? [tag, coloredDate] : [tag]);
2389
+ const space = (opts.columns || 0) - stringWidth(left) - stringWidth(right) - 2;
2390
+ line = space > 0 && (opts.columns || 0) >= 80 ? left + " ".repeat(space) + right : (right ? `${colors.gray(`[${right}]`)} ` : "") + left;
2391
+ line += characterFormat(
2392
+ additional.length > 0 ? "\n" + additional.join("\n") : ""
2393
+ );
2394
+ if (logObj.type === "trace") {
2395
+ const _err = new Error("Trace: " + logObj.message);
2396
+ line += this.formatStack(_err.stack || "", _err.message);
2397
+ }
2398
+ return isBadge ? "\n" + line + "\n" : line;
2399
+ }
2400
+ };
2401
+ function characterFormat(str) {
2402
+ return str.replace(/`([^`]+)`/gm, (_3, m2) => colors.cyan(m2)).replace(/\s+_([^_]+)_\s+/gm, (_3, m2) => ` ${colors.underline(m2)} `);
2403
+ }
2404
+ function getColor2(color = "white") {
2405
+ return colors[color] || colors.white;
2406
+ }
2407
+ function getBgColor(color = "bgWhite") {
2408
+ return colors[`bg${color[0].toUpperCase()}${color.slice(1)}`] || colors.bgWhite;
2409
+ }
2410
+ function createConsola2(options = {}) {
2411
+ let level = _getDefaultLogLevel();
2412
+ if (process.env.CONSOLA_LEVEL) {
2413
+ level = Number.parseInt(process.env.CONSOLA_LEVEL) ?? level;
2414
+ }
2415
+ const consola2 = createConsola({
2416
+ level,
2417
+ defaults: { level },
2418
+ stdout: process.stdout,
2419
+ stderr: process.stderr,
2420
+ prompt: (...args) => Promise.resolve().then(() => (init_prompt(), prompt_exports)).then((m2) => m2.prompt(...args)),
2421
+ reporters: options.reporters || [
2422
+ options.fancy ?? !(T2 || R2) ? new FancyReporter() : new BasicReporter()
2423
+ ],
2424
+ ...options
2425
+ });
2426
+ return consola2;
2427
+ }
2428
+ function _getDefaultLogLevel() {
2429
+ if (g2) {
2430
+ return LogLevels.debug;
2431
+ }
2432
+ if (R2) {
2433
+ return LogLevels.warn;
2434
+ }
2435
+ return LogLevels.info;
2436
+ }
2437
+ var consola = createConsola2();
2438
+
2439
+ // ../../packages/shapes/dist/index.js
2440
+ var import_shell_quote = __toESM(require_shell_quote(), 1);
2441
+ import { homedir as homedir5 } from "os";
2442
+ import { join as join5 } from "path";
2443
+ function parseKeyValue(line) {
2444
+ const eqIndex = line.indexOf("=");
2445
+ if (eqIndex === -1)
2446
+ return null;
2447
+ const key = line.slice(0, eqIndex).trim();
2448
+ const value = line.slice(eqIndex + 1).trim();
2449
+ if (!key || !value)
2450
+ return null;
2451
+ return { key, value };
2452
+ }
2453
+ function parseTomlValue(raw) {
2454
+ const trimmed = raw.trim();
2455
+ if (trimmed.startsWith('"') && trimmed.endsWith('"'))
2456
+ return trimmed.slice(1, -1);
2457
+ if (trimmed === "true")
2458
+ return true;
2459
+ if (trimmed === "false")
2460
+ return false;
2461
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
2462
+ const inner = trimmed.slice(1, -1).trim();
2463
+ if (!inner)
2464
+ return [];
2465
+ return inner.split(",").map((value) => value.trim().replace(/^"|"$/g, ""));
2466
+ }
2467
+ return trimmed;
2468
+ }
2469
+ function parseAdapterToml(content) {
2470
+ const result = {};
2471
+ const operations = [];
2472
+ let currentSection = "root";
2473
+ let currentEntry = {};
2474
+ const flushOperation = () => {
2475
+ if (currentSection === "operation" && Object.keys(currentEntry).length > 0) {
2476
+ operations.push(currentEntry);
2477
+ currentEntry = {};
2478
+ }
2479
+ };
2480
+ for (const rawLine of content.split("\n")) {
2481
+ const line = rawLine.trim();
2482
+ if (!line || line.startsWith("#"))
2483
+ continue;
2484
+ if (line === "[cli]") {
2485
+ flushOperation();
2486
+ currentSection = "cli";
2487
+ result.cli = {};
2488
+ continue;
2489
+ }
2490
+ if (line === "[[operation]]") {
2491
+ flushOperation();
2492
+ currentSection = "operation";
2493
+ currentEntry = {};
2494
+ continue;
2495
+ }
2496
+ const kv = parseKeyValue(line);
2497
+ if (!kv)
2498
+ continue;
2499
+ const value = parseTomlValue(kv.value);
2500
+ if (currentSection === "root") {
2501
+ ;
2502
+ result[kv.key] = value;
2503
+ } else if (currentSection === "cli") {
2504
+ ;
2505
+ result.cli[kv.key] = value;
2506
+ } else {
2507
+ currentEntry[kv.key] = value;
2508
+ }
2509
+ }
2510
+ flushOperation();
2511
+ result.operation = operations;
2512
+ if (result.schema !== "openape-shapes/v1") {
2513
+ throw new Error(`Unsupported adapter schema: ${result.schema ?? "missing"}`);
2514
+ }
2515
+ if (!result.cli?.id || !result.cli.executable) {
2516
+ throw new Error("Adapter is missing cli.id or cli.executable");
2517
+ }
2518
+ if (!result.operation?.length) {
2519
+ throw new Error("Adapter must define at least one [[operation]] entry");
2520
+ }
2521
+ return {
2522
+ schema: result.schema,
2523
+ cli: {
2524
+ id: String(result.cli.id),
2525
+ executable: String(result.cli.executable),
2526
+ ...result.cli.audience ? { audience: String(result.cli.audience) } : {},
2527
+ ...result.cli.version ? { version: String(result.cli.version) } : {}
2528
+ },
2529
+ operations: result.operation.map((operation) => {
2530
+ if (!Array.isArray(operation.command) || operation.command.some((token) => typeof token !== "string")) {
2531
+ throw new Error(`Operation ${String(operation.id ?? "<unknown>")} is missing command[]`);
2532
+ }
2533
+ if (!Array.isArray(operation.resource_chain) || operation.resource_chain.some((token) => typeof token !== "string")) {
2534
+ throw new Error(`Operation ${String(operation.id ?? "<unknown>")} is missing resource_chain[]`);
2535
+ }
2536
+ if (typeof operation.id !== "string" || typeof operation.display !== "string" || typeof operation.action !== "string") {
2537
+ throw new TypeError("Operation must define id, display, and action");
2538
+ }
2539
+ return {
2540
+ id: operation.id,
2541
+ command: operation.command,
2542
+ ...Array.isArray(operation.positionals) ? { positionals: operation.positionals } : {},
2543
+ ...Array.isArray(operation.required_options) ? { required_options: operation.required_options } : {},
2544
+ display: operation.display,
2545
+ action: operation.action,
2546
+ risk: operation.risk || "low",
2547
+ resource_chain: operation.resource_chain,
2548
+ ...operation.exact_command !== void 0 ? { exact_command: Boolean(operation.exact_command) } : {}
2549
+ };
2550
+ })
2551
+ };
2552
+ }
2553
+ function digest(content) {
2554
+ return `SHA-256:${createHash("sha256").update(content).digest("hex")}`;
2555
+ }
2556
+ function adapterDirs() {
2557
+ return [
2558
+ join22(process.cwd(), ".openape", "shapes", "adapters"),
2559
+ join22(homedir22(), ".openape", "shapes", "adapters"),
2560
+ join22("/etc", "openape", "shapes", "adapters")
2561
+ ];
2562
+ }
2563
+ function findByExecutable(executable) {
2564
+ for (const dir of adapterDirs()) {
2565
+ if (!existsSync2(dir))
2566
+ continue;
2567
+ try {
2568
+ const files = readdirSync(dir).filter((f3) => f3.endsWith(".toml"));
2569
+ for (const file of files) {
2570
+ const path = join22(dir, file);
2571
+ const content = readFileSync(path, "utf-8");
2572
+ const match = content.match(/^\s*executable\s*=\s*"([^"]+)"/m);
2573
+ if (match && match[1] === executable)
2574
+ return path;
2575
+ }
2576
+ } catch {
2577
+ }
2578
+ }
2579
+ return void 0;
2580
+ }
2581
+ function resolveAdapterPath(cliId, explicitPath) {
2582
+ if (explicitPath) {
2583
+ if (existsSync2(explicitPath))
2584
+ return explicitPath;
2585
+ throw new Error(`Adapter file not found: ${explicitPath}`);
2586
+ }
2587
+ const candidates = adapterDirs().map((dir) => join22(dir, `${cliId}.toml`));
2588
+ const match = candidates.find((path) => existsSync2(path));
2589
+ if (match)
2590
+ return match;
2591
+ const byExec = findByExecutable(cliId);
2592
+ if (byExec)
2593
+ return byExec;
2594
+ throw new Error(`No adapter found for ${cliId}`);
2595
+ }
2596
+ function loadAdapter(cliId, explicitPath) {
2597
+ const source = resolveAdapterPath(cliId, explicitPath);
2598
+ const content = readFileSync(source, "utf-8");
2599
+ const adapter = parseAdapterToml(content);
2600
+ const idMatch = adapter.cli.id === cliId;
2601
+ const fileMatch = basename(source) === `${cliId}.toml`;
2602
+ const execMatch = adapter.cli.executable === cliId;
2603
+ if (!idMatch && !fileMatch && !execMatch)
2604
+ throw new Error(`Adapter ${source} does not match requested CLI ${cliId}`);
2605
+ return {
2606
+ adapter,
2607
+ source,
2608
+ digest: digest(content)
2609
+ };
2610
+ }
2611
+ var REGISTRY_URL = process.env.SHAPES_REGISTRY_URL ?? "https://raw.githubusercontent.com/openape-ai/shapes-registry/main/registry.json";
2612
+ var CACHE_TTL_MS = 60 * 60 * 1e3;
2613
+ async function resolveCommand(loaded, fullArgv) {
2614
+ const [executable, ...commandArgv] = fullArgv;
2615
+ if (!executable) {
2616
+ throw new Error("Missing wrapped command");
2617
+ }
2618
+ if (executable !== loaded.adapter.cli.executable) {
2619
+ throw new Error(`Adapter ${loaded.adapter.cli.id} expects executable ${loaded.adapter.cli.executable}, got ${executable}`);
2620
+ }
2621
+ const match = matchArgvToOperation(loaded.adapter.operations, commandArgv);
2622
+ if (!match) {
2623
+ throw new Error(`No adapter operation matched: ${fullArgv.join(" ")}`);
2624
+ }
2625
+ const { operation, bindings } = match;
2626
+ const detail = buildCliAuthDetail(loaded.adapter.cli.id, operation, bindings);
2627
+ return {
2628
+ adapter: loaded.adapter,
2629
+ source: loaded.source,
2630
+ digest: loaded.digest,
2631
+ executable,
2632
+ commandArgv,
2633
+ bindings,
2634
+ detail,
2635
+ executionContext: {
2636
+ argv: fullArgv,
2637
+ argv_hash: await computeArgvHash(fullArgv),
2638
+ adapter_id: loaded.adapter.cli.id,
2639
+ adapter_version: loaded.adapter.cli.version ?? loaded.adapter.schema,
2640
+ adapter_digest: loaded.digest,
2641
+ resolved_executable: executable,
2642
+ context_bindings: bindings
2643
+ },
2644
+ permission: detail.permission
2645
+ };
2646
+ }
2647
+ var AUTH_FILE2 = join5(homedir5(), ".config", "apes", "auth.json");
2648
+
2649
+ // ../../packages/apes/dist/chunk-BA2V3BBO.js
2650
+ var explainCommand = defineCommand({
2651
+ meta: {
2652
+ name: "explain",
2653
+ description: "Show what permission a wrapped command would need"
2654
+ },
2655
+ args: {
2656
+ adapter: {
2657
+ type: "string",
2658
+ description: "Explicit path to adapter TOML file"
2659
+ },
2660
+ _: {
2661
+ type: "positional",
2662
+ description: "Wrapped command (after --)",
2663
+ required: false
2664
+ }
2665
+ },
2666
+ async run({ rawArgs }) {
2667
+ const command = extractWrappedCommand(rawArgs ?? []);
2668
+ if (command.length === 0)
2669
+ throw new Error("Missing wrapped command. Usage: shapes explain [--adapter <file>] -- <cli> ...");
2670
+ const adapterOpt = extractOption(rawArgs ?? [], "adapter");
2671
+ const loaded = loadAdapter(command[0], adapterOpt);
2672
+ const resolved = await resolveCommand(loaded, command);
2673
+ process.stdout.write(`${JSON.stringify({
2674
+ adapter: resolved.adapter.cli.id,
2675
+ source: resolved.source,
2676
+ operation: resolved.detail.operation_id,
2677
+ display: resolved.detail.display,
2678
+ permission: resolved.permission,
2679
+ resource_chain: resolved.detail.resource_chain,
2680
+ exact_command: resolved.detail.constraints?.exact_command ?? false,
2681
+ adapter_digest: resolved.digest
2682
+ }, null, 2)}
2683
+ `);
2684
+ }
2685
+ });
2686
+ function extractWrappedCommand(args) {
2687
+ const delimiter = args.indexOf("--");
2688
+ return delimiter >= 0 ? args.slice(delimiter + 1) : [];
2689
+ }
2690
+ function extractOption(args, name) {
2691
+ const delimiter = args.indexOf("--");
2692
+ const optionArgs = delimiter >= 0 ? args.slice(0, delimiter) : args;
2693
+ const index = optionArgs.indexOf(`--${name}`);
2694
+ if (index >= 0 && index + 1 < optionArgs.length)
2695
+ return optionArgs[index + 1];
2696
+ return void 0;
2697
+ }
2698
+
2699
+ // ../../packages/apes/dist/chunk-MMBFV5WN.js
2700
+ init_chunk_OBF7IMQ2();
2701
+ var debug = process.argv.includes("--debug");
2702
+
2703
+ // ../../packages/apes/dist/index.js
2704
+ init_chunk_OBF7IMQ2();
2705
+
2706
+ // ../../packages/agent-runtime/dist/index.js
2707
+ import { spawn } from "child_process";
2708
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
2709
+ import { homedir as homedir4 } from "os";
2710
+ import { dirname as dirname2, normalize, resolve } from "path";
2711
+ import { homedir as homedir24 } from "os";
2712
+ import { resolve as resolve2 } from "path";
2713
+ import process2 from "process";
2714
+ import { execFileSync } from "child_process";
2715
+ import { readFileSync as readFileSync23 } from "fs";
2716
+ import { homedir as homedir32 } from "os";
2717
+ import { join as join4 } from "path";
2718
+ import { execFileSync as execFileSync2 } from "child_process";
2719
+
2720
+ // ../../packages/cli-auth/dist/index.js
2721
+ import { ofetch } from "ofetch";
2722
+ import { existsSync, mkdirSync, readFileSync as readFileSync2, readdirSync as readdirSync2, unlinkSync, writeFileSync } from "fs";
2723
+ import { homedir as homedir3 } from "os";
2724
+ import { join as join3 } from "path";
2725
+ import { ofetch as ofetch3 } from "ofetch";
2726
+ import { Buffer as Buffer2 } from "buffer";
2727
+ import { sign } from "crypto";
2728
+ import { existsSync as existsSync22, readFileSync as readFileSync22 } from "fs";
2729
+ import { homedir as homedir23 } from "os";
2730
+ import { join as join23 } from "path";
2731
+ import { ofetch as ofetch2 } from "ofetch";
2732
+ import { Buffer as Buffer3 } from "buffer";
2733
+ import { createPrivateKey } from "crypto";
2734
+ import { ofetch as ofetch4 } from "ofetch";
2735
+ import { ofetch as ofetch5 } from "ofetch";
2736
+ function getConfigDir(authHome) {
2737
+ if (authHome) return join3(authHome, ".config", "apes");
2738
+ const override = process.env.OPENAPE_CLI_AUTH_HOME;
2739
+ if (override) return override;
2740
+ return join3(homedir3(), ".config", "apes");
2741
+ }
2742
+ function getAuthFile(authHome) {
2743
+ return join3(getConfigDir(authHome), "auth.json");
2744
+ }
2745
+ function getSpTokensDir() {
2746
+ return join3(getConfigDir(), "sp-tokens");
2747
+ }
2748
+ function ensureConfigDir(authHome) {
2749
+ const dir = getConfigDir(authHome);
2750
+ if (!existsSync(dir)) {
2751
+ mkdirSync(dir, { recursive: true, mode: 448 });
2752
+ }
2753
+ }
2754
+ function ensureSpTokensDir() {
2755
+ ensureConfigDir();
2756
+ const dir = getSpTokensDir();
2757
+ if (!existsSync(dir)) {
2758
+ mkdirSync(dir, { recursive: true, mode: 448 });
2759
+ }
2760
+ }
2761
+ function loadIdpAuth(authHome) {
2762
+ const file = getAuthFile(authHome);
2763
+ if (!existsSync(file)) return null;
2764
+ try {
2765
+ const raw = readFileSync2(file, "utf-8");
2766
+ if (!raw.trim()) return null;
2767
+ return JSON.parse(raw);
2768
+ } catch {
2769
+ return null;
2770
+ }
2771
+ }
2772
+ function saveIdpAuth(auth, authHome) {
2773
+ ensureConfigDir(authHome);
2774
+ const file = getAuthFile(authHome);
2775
+ let extra = {};
2776
+ if (existsSync(file)) {
2777
+ try {
2778
+ const raw = readFileSync2(file, "utf-8");
2779
+ if (raw.trim()) {
2780
+ const prev = JSON.parse(raw);
2781
+ for (const key of Object.keys(prev)) {
2782
+ if (!(key in auth)) {
2783
+ extra[key] = prev[key];
2784
+ }
2785
+ }
2786
+ }
2787
+ } catch {
2788
+ extra = {};
2789
+ }
2790
+ }
2791
+ const merged = { ...extra, ...auth };
2792
+ writeFileSync(file, JSON.stringify(merged, null, 2), { mode: 384 });
2793
+ }
2794
+ function audToFilename(aud) {
2795
+ return aud.replace(/[^\w.-]/g, "_");
2796
+ }
2797
+ function spTokenPath(aud) {
2798
+ return join3(getSpTokensDir(), `${audToFilename(aud)}.json`);
2799
+ }
2800
+ function loadSpToken(aud) {
2801
+ const path = spTokenPath(aud);
2802
+ if (!existsSync(path)) return null;
2803
+ try {
2804
+ const raw = readFileSync2(path, "utf-8");
2805
+ if (!raw.trim()) return null;
2806
+ return JSON.parse(raw);
2807
+ } catch {
2808
+ return null;
2809
+ }
2810
+ }
2811
+ function saveSpToken(token) {
2812
+ ensureSpTokensDir();
2813
+ writeFileSync(spTokenPath(token.aud), JSON.stringify(token, null, 2), { mode: 384 });
2814
+ }
2815
+ var AuthError = class extends Error {
2816
+ status;
2817
+ hint;
2818
+ constructor(status, message, hint) {
2819
+ super(hint ? `${message}
2820
+ ${hint}` : message);
2821
+ this.name = "AuthError";
2822
+ this.status = status;
2823
+ this.hint = hint;
2824
+ }
2825
+ };
2826
+ var NotLoggedInError = class extends AuthError {
2827
+ constructor(hint) {
2828
+ super(
2829
+ 401,
2830
+ "Not logged in",
2831
+ hint ?? "Run `apes login <email>` once on this device to authenticate against the OpenApe IdP."
2832
+ );
2833
+ this.name = "NotLoggedInError";
2834
+ }
2835
+ };
2836
+ async function exchangeForSpToken(idpAuth, request, now = Math.floor(Date.now() / 1e3)) {
2837
+ const url = `${request.endpoint.replace(/\/$/, "")}/api/cli/exchange`;
2838
+ let response;
2839
+ try {
2840
+ response = await ofetch(url, {
2841
+ method: "POST",
2842
+ body: {
2843
+ subject_token: idpAuth.access_token,
2844
+ ...request.scopes ? { scopes: request.scopes } : {}
2845
+ }
2846
+ });
2847
+ } catch (err) {
2848
+ const status = err.status ?? err.statusCode ?? 0;
2849
+ const data = err.data;
2850
+ const title = data?.title ?? `Token exchange failed (HTTP ${status})`;
2851
+ const hint = status === 401 ? `IdP token rejected at ${url}. Try \`apes login\` again \u2014 token may be expired or audience-mismatched.` : data?.detail;
2852
+ throw new AuthError(status, title, hint);
2853
+ }
2854
+ if (!response.access_token) {
2855
+ throw new AuthError(0, `Exchange response from ${url} missing access_token`);
2856
+ }
2857
+ const expiresAt = response.expires_at ?? (response.expires_in ? now + response.expires_in : now + 3600);
2858
+ const token = {
2859
+ endpoint: request.endpoint,
2860
+ aud: response.aud ?? request.aud,
2861
+ access_token: response.access_token,
2862
+ expires_at: expiresAt,
2863
+ ...request.scopes ? { scopes: request.scopes } : {},
2864
+ issued_from_idp_iat: now
2865
+ };
2866
+ saveSpToken(token);
2867
+ return token;
2868
+ }
2869
+ var OPENSSH_MAGIC = "openssh-key-v1\0";
2870
+ function loadEd25519PrivateKey(pem) {
2871
+ if (pem.includes("BEGIN OPENSSH PRIVATE KEY")) {
2872
+ return parseOpenSSHEd25519(pem);
2873
+ }
2874
+ return createPrivateKey(pem);
2875
+ }
2876
+ function parseOpenSSHEd25519(pem) {
2877
+ const b64 = pem.replace(/-----BEGIN OPENSSH PRIVATE KEY-----/, "").replace(/-----END OPENSSH PRIVATE KEY-----/, "").replace(/\s/g, "");
2878
+ const buf = Buffer3.from(b64, "base64");
2879
+ let offset = 0;
2880
+ const magic = buf.subarray(0, OPENSSH_MAGIC.length).toString("ascii");
2881
+ if (magic !== OPENSSH_MAGIC) {
2882
+ throw new Error("Not an OpenSSH private key");
2883
+ }
2884
+ offset += OPENSSH_MAGIC.length;
2885
+ const cipherLen = buf.readUInt32BE(offset);
2886
+ offset += 4;
2887
+ const cipher = buf.subarray(offset, offset + cipherLen).toString();
2888
+ offset += cipherLen;
2889
+ if (cipher !== "none") {
2890
+ throw new Error(`Encrypted keys not supported (cipher: ${cipher}). Decrypt first with: ssh-keygen -p -f <key>`);
2891
+ }
2892
+ const kdfLen = buf.readUInt32BE(offset);
2893
+ offset += 4;
2894
+ offset += kdfLen;
2895
+ const kdfOptsLen = buf.readUInt32BE(offset);
2896
+ offset += 4;
2897
+ offset += kdfOptsLen;
2898
+ const numKeys = buf.readUInt32BE(offset);
2899
+ offset += 4;
2900
+ if (numKeys !== 1) {
2901
+ throw new Error(`Expected 1 key, got ${numKeys}`);
2902
+ }
2903
+ const pubSectionLen = buf.readUInt32BE(offset);
2904
+ offset += 4;
2905
+ offset += pubSectionLen;
2906
+ const privSectionLen = buf.readUInt32BE(offset);
2907
+ offset += 4;
2908
+ const privSection = buf.subarray(offset, offset + privSectionLen);
2909
+ let pOffset = 0;
2910
+ const check1 = privSection.readUInt32BE(pOffset);
2911
+ pOffset += 4;
2912
+ const check2 = privSection.readUInt32BE(pOffset);
2913
+ pOffset += 4;
2914
+ if (check1 !== check2) {
2915
+ throw new Error("Check integers mismatch \u2014 key may be corrupted or encrypted");
2916
+ }
2917
+ const keyTypeLen = privSection.readUInt32BE(pOffset);
2918
+ pOffset += 4;
2919
+ const keyType = privSection.subarray(pOffset, pOffset + keyTypeLen).toString();
2920
+ pOffset += keyTypeLen;
2921
+ if (keyType !== "ssh-ed25519") {
2922
+ throw new Error(`Expected ssh-ed25519, got ${keyType}`);
2923
+ }
2924
+ const pubKeyLen = privSection.readUInt32BE(pOffset);
2925
+ pOffset += 4;
2926
+ const pubKey = privSection.subarray(pOffset, pOffset + pubKeyLen);
2927
+ pOffset += pubKeyLen;
2928
+ const privKeyLen = privSection.readUInt32BE(pOffset);
2929
+ pOffset += 4;
2930
+ const privKeyData = privSection.subarray(pOffset, pOffset + privKeyLen);
2931
+ const seed = privKeyData.subarray(0, 32);
2932
+ return createPrivateKey({
2933
+ key: { kty: "OKP", crv: "Ed25519", d: seed.toString("base64url"), x: pubKey.toString("base64url") },
2934
+ format: "jwk"
2935
+ });
2936
+ }
2937
+ async function getEndpoints(idp) {
2938
+ let disco = {};
2939
+ try {
2940
+ disco = await ofetch2(`${idp}/.well-known/openid-configuration`);
2941
+ } catch {
2942
+ }
2943
+ return {
2944
+ challenge: disco.ddisa_agent_challenge_endpoint ?? `${idp}/api/agent/challenge`,
2945
+ authenticate: disco.ddisa_agent_authenticate_endpoint ?? `${idp}/api/agent/authenticate`
2946
+ };
2947
+ }
2948
+ function resolveKeyPath(p) {
2949
+ if (p.startsWith("~")) return join23(homedir23(), p.slice(1));
2950
+ return p;
2951
+ }
2952
+ function findSigningKey(auth) {
2953
+ const candidates = [];
2954
+ if (auth.key_path) candidates.push(resolveKeyPath(auth.key_path));
2955
+ candidates.push(join23(homedir23(), ".ssh", "id_ed25519"));
2956
+ for (const p of candidates) {
2957
+ if (existsSync22(p)) {
2958
+ try {
2959
+ return { keyPath: p, keyContent: readFileSync22(p, "utf-8") };
2960
+ } catch {
2961
+ }
2962
+ }
2963
+ }
2964
+ return null;
2965
+ }
2966
+ async function refreshAgentToken(auth, now = Math.floor(Date.now() / 1e3)) {
2967
+ const key = findSigningKey(auth);
2968
+ if (!key) return null;
2969
+ let privateKey;
2970
+ try {
2971
+ privateKey = loadEd25519PrivateKey(key.keyContent);
2972
+ } catch {
2973
+ return null;
2974
+ }
2975
+ let endpoints;
2976
+ try {
2977
+ endpoints = await getEndpoints(auth.idp);
2978
+ } catch {
2979
+ return null;
2980
+ }
2981
+ let challenge;
2982
+ try {
2983
+ const resp = await ofetch2(endpoints.challenge, {
2984
+ method: "POST",
2985
+ headers: { "Content-Type": "application/json" },
2986
+ body: { agent_id: auth.email }
2987
+ });
2988
+ challenge = resp.challenge;
2989
+ } catch {
2990
+ return null;
2991
+ }
2992
+ let signature;
2993
+ try {
2994
+ signature = sign(null, Buffer2.from(challenge), privateKey).toString("base64");
2995
+ } catch {
2996
+ return null;
2997
+ }
2998
+ let authResp;
2999
+ try {
3000
+ authResp = await ofetch2(endpoints.authenticate, {
3001
+ method: "POST",
3002
+ headers: { "Content-Type": "application/json" },
3003
+ body: { agent_id: auth.email, challenge, signature }
3004
+ });
3005
+ } catch {
3006
+ return null;
3007
+ }
3008
+ return {
3009
+ ...auth,
3010
+ access_token: authResp.token,
3011
+ expires_at: now + (authResp.expires_in || 3600),
3012
+ key_path: auth.key_path ?? key.keyPath
3013
+ };
3014
+ }
3015
+ var EXPIRY_SKEW_SECONDS = 30;
3016
+ async function getTokenEndpoint(idp) {
3017
+ try {
3018
+ const disco = await ofetch3(`${idp}/.well-known/openid-configuration`);
3019
+ if (disco.token_endpoint) return disco.token_endpoint;
3020
+ } catch {
3021
+ }
3022
+ return `${idp}/token`;
3023
+ }
3024
+ async function ensureFreshIdpAuth(now = Math.floor(Date.now() / 1e3), authHome) {
3025
+ const auth = loadIdpAuth(authHome);
3026
+ if (!auth) {
3027
+ throw new NotLoggedInError();
3028
+ }
3029
+ if (auth.expires_at > now + EXPIRY_SKEW_SECONDS) {
3030
+ return auth;
3031
+ }
3032
+ if (!auth.refresh_token) {
3033
+ const refreshed = await refreshAgentToken(auth, now);
3034
+ if (refreshed) {
3035
+ saveIdpAuth(refreshed, authHome);
3036
+ return refreshed;
3037
+ }
3038
+ throw new NotLoggedInError(
3039
+ `IdP token expired at ${new Date(auth.expires_at * 1e3).toISOString()} and no refresh_token is stored. Run \`apes login\` again.`
3040
+ );
3041
+ }
3042
+ const tokenEndpoint = await getTokenEndpoint(auth.idp);
3043
+ const body = new URLSearchParams({
3044
+ grant_type: "refresh_token",
3045
+ refresh_token: auth.refresh_token
3046
+ });
3047
+ let response;
3048
+ try {
3049
+ response = await ofetch3(tokenEndpoint, {
3050
+ method: "POST",
3051
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
3052
+ body: body.toString()
3053
+ });
3054
+ } catch (err) {
3055
+ const status = err.status ?? err.statusCode ?? 0;
3056
+ if (status === 400 || status === 401) {
3057
+ saveIdpAuth({ ...auth, refresh_token: void 0 }, authHome);
3058
+ throw new NotLoggedInError(
3059
+ `Refresh token rejected by ${auth.idp}. Run \`apes login\` again.`
3060
+ );
3061
+ }
3062
+ throw new AuthError(
3063
+ 0,
3064
+ `Network error refreshing IdP token at ${tokenEndpoint}`,
3065
+ `Underlying: ${err.message ?? err}`
3066
+ );
3067
+ }
3068
+ if (!response.access_token) {
3069
+ throw new AuthError(0, `IdP refresh response missing access_token (endpoint: ${tokenEndpoint})`);
3070
+ }
3071
+ const next = {
3072
+ ...auth,
3073
+ access_token: response.access_token,
3074
+ refresh_token: response.refresh_token ?? auth.refresh_token,
3075
+ expires_at: now + (response.expires_in ?? 3600)
3076
+ };
3077
+ saveIdpAuth(next, authHome);
3078
+ return next;
3079
+ }
3080
+ var SP_TOKEN_SKEW_SECONDS = 60;
3081
+ async function getAuthorizedBearer(opts) {
3082
+ const now = Math.floor(Date.now() / 1e3);
3083
+ if (!opts.forceRefresh) {
3084
+ const cached = loadSpToken(opts.aud);
3085
+ if (cached && cached.expires_at > now + SP_TOKEN_SKEW_SECONDS) {
3086
+ return `Bearer ${cached.access_token}`;
3087
+ }
3088
+ }
3089
+ const idpAuth = await ensureFreshIdpAuth(now);
3090
+ const sp = await exchangeForSpToken(idpAuth, {
3091
+ endpoint: opts.endpoint,
3092
+ aud: opts.aud,
3093
+ ...opts.scopes ? { scopes: opts.scopes } : {}
3094
+ }, now);
3095
+ return `Bearer ${sp.access_token}`;
3096
+ }
3097
+
3098
+ // ../../packages/agent-runtime/dist/index.js
3099
+ var DEFAULT_TIMEOUT_MS = 5 * 60 * 1e3;
3100
+ var MAX_STDIO_BYTES = 64 * 1024;
3101
+ var BIN = "ape-shell";
3102
+ function capStdio(s2) {
3103
+ const buf = Buffer.from(s2, "utf8");
3104
+ if (buf.byteLength <= MAX_STDIO_BYTES) return s2;
3105
+ return `${buf.subarray(0, MAX_STDIO_BYTES).toString("utf8")}
3106
+ [truncated to ${MAX_STDIO_BYTES} bytes]`;
3107
+ }
3108
+ function runApeShell(cmd, timeoutMs = DEFAULT_TIMEOUT_MS, cwd) {
3109
+ const bypass = process.env.OPENAPE_BYPASS_APE_SHELL === "1";
3110
+ const [execBin, execArgs] = bypass ? ["/bin/bash", ["-c", cmd]] : [BIN, ["-c", cmd]];
3111
+ return new Promise((resolveResult) => {
3112
+ const child = spawn(execBin, execArgs, {
3113
+ env: { ...process.env, APE_WAIT: "1" },
3114
+ stdio: ["ignore", "pipe", "pipe"],
3115
+ ...cwd ? { cwd } : {}
3116
+ });
3117
+ let stdout2 = "";
3118
+ let stderr = "";
3119
+ let timedOut = false;
3120
+ let spawnError = null;
3121
+ child.stdout.on("data", (chunk) => {
3122
+ stdout2 += chunk.toString("utf8");
3123
+ });
3124
+ child.stderr.on("data", (chunk) => {
3125
+ stderr += chunk.toString("utf8");
3126
+ });
3127
+ child.on("error", (err) => {
3128
+ spawnError = err;
3129
+ });
3130
+ const timer = setTimeout(() => {
3131
+ timedOut = true;
3132
+ child.kill("SIGTERM");
3133
+ setTimeout(() => {
3134
+ try {
3135
+ child.kill("SIGKILL");
3136
+ } catch {
3137
+ }
3138
+ }, 5e3);
3139
+ }, timeoutMs);
3140
+ child.on("close", (code) => {
3141
+ clearTimeout(timer);
3142
+ if (spawnError) {
3143
+ resolveResult({
3144
+ stdout: "",
3145
+ stderr: "",
3146
+ exit_code: -1,
3147
+ error: spawnError.message,
3148
+ hint: `Could not exec '${execBin}'. The agent host needs @openape/apes installed globally so ape-shell is on PATH (or set OPENAPE_BYPASS_APE_SHELL=1 to skip the gated shell entirely \u2014 meant for the OpenApe pod where the container IS the sandbox).`
3149
+ });
3150
+ return;
3151
+ }
3152
+ resolveResult({
3153
+ stdout: capStdio(stdout2),
3154
+ stderr: capStdio(stderr),
3155
+ exit_code: code ?? -1,
3156
+ ...timedOut ? { timed_out: true } : {}
3157
+ });
3158
+ });
3159
+ });
3160
+ }
3161
+ var DEFAULTS = { DEFAULT_TIMEOUT_MS };
3162
+ var bashTools = [
3163
+ {
3164
+ name: "bash",
3165
+ description: "Run a shell command on the agent host. Every invocation goes through the OpenApe DDISA grant cycle \u2014 auto-approved if the owner has a matching YOLO scope, otherwise the owner gets a push notification to approve. Runs as the agent's macOS user, so file/network access is limited to what that user can see. Returns stdout, stderr, and exit code. For repeated command patterns ask the owner to set up a YOLO scope so approvals don't pile up.",
3166
+ parameters: {
3167
+ type: "object",
3168
+ properties: {
3169
+ cmd: {
3170
+ type: "string",
3171
+ description: "Shell command to run, e.g. `ls -la ~/Documents`, `git status`, `curl -fsSL https://example.com`. The whole string is passed to `bash -c`; quote internally as needed."
3172
+ },
3173
+ timeout_ms: {
3174
+ type: "number",
3175
+ description: "Wall-clock cap for the whole approval-and-run cycle in milliseconds. Default 300000 (5 min). Approval waits count against this budget."
3176
+ }
3177
+ },
3178
+ required: ["cmd"]
3179
+ },
3180
+ execute: async (args) => {
3181
+ const a2 = args;
3182
+ if (typeof a2.cmd !== "string" || a2.cmd.trim() === "") {
3183
+ throw new Error("cmd must be a non-empty string");
3184
+ }
3185
+ const timeout = typeof a2.timeout_ms === "number" && a2.timeout_ms > 0 ? a2.timeout_ms : DEFAULTS.DEFAULT_TIMEOUT_MS;
3186
+ return await runApeShell(a2.cmd, timeout);
3187
+ }
3188
+ }
3189
+ ];
3190
+ var MAX_BYTES = 1024 * 1024;
3191
+ var extraReadRoots = /* @__PURE__ */ new Set();
3192
+ function isUnder(candidate, root) {
3193
+ return candidate === root || candidate.startsWith(`${root}/`);
3194
+ }
3195
+ function jailPath(input, opts = {}) {
3196
+ if (typeof input !== "string" || input === "") {
3197
+ throw new Error("path must be a non-empty string");
3198
+ }
3199
+ const home = homedir4();
3200
+ const candidate = input.startsWith("~/") ? resolve(home, input.slice(2)) : input.startsWith("/") ? normalize(input) : resolve(home, input);
3201
+ if (isUnder(candidate, home)) return candidate;
3202
+ if (opts.allowReadRoots) {
3203
+ for (const root of extraReadRoots) {
3204
+ if (isUnder(candidate, root)) return candidate;
3205
+ }
3206
+ }
3207
+ throw new Error(`path "${input}" resolves outside the agent's home`);
3208
+ }
3209
+ var fileTools = [
3210
+ {
3211
+ name: "file.read",
3212
+ description: "Read a UTF-8 file from the agent's home directory ($HOME) or a bundled skill directory (e.g. a skill's SKILL.md). Capped at 1MB. Path traversal blocked.",
3213
+ parameters: {
3214
+ type: "object",
3215
+ properties: {
3216
+ path: { type: "string", description: "Path relative to $HOME (or absolute under $HOME). `..` segments are rejected." }
3217
+ },
3218
+ required: ["path"]
3219
+ },
3220
+ execute: async (args) => {
3221
+ const a2 = args;
3222
+ const p = jailPath(a2.path, { allowReadRoots: true });
3223
+ const content = readFileSync3(p, "utf8");
3224
+ if (Buffer.byteLength(content, "utf8") > MAX_BYTES) {
3225
+ return { path: p, truncated: true, content: content.slice(0, MAX_BYTES) };
3226
+ }
3227
+ return { path: p, truncated: false, content };
3228
+ }
3229
+ },
3230
+ {
3231
+ name: "file.write",
3232
+ description: "Write a UTF-8 file under the agent's home directory. Creates parent dirs as needed. 1MB max.",
3233
+ parameters: {
3234
+ type: "object",
3235
+ properties: {
3236
+ path: { type: "string", description: "Path relative to $HOME (or absolute under $HOME)." },
3237
+ content: { type: "string", description: "File body. Existing files are overwritten." }
3238
+ },
3239
+ required: ["path", "content"]
3240
+ },
3241
+ execute: async (args) => {
3242
+ const a2 = args;
3243
+ if (typeof a2.content !== "string") throw new Error("content must be a string");
3244
+ if (Buffer.byteLength(a2.content, "utf8") > MAX_BYTES) {
3245
+ throw new Error(`content exceeds ${MAX_BYTES} byte cap`);
3246
+ }
3247
+ const p = jailPath(a2.path);
3248
+ mkdirSync2(dirname2(p), { recursive: true });
3249
+ writeFileSync2(p, a2.content, { encoding: "utf8" });
3250
+ return { path: p, bytes: Buffer.byteLength(a2.content, "utf8") };
3251
+ }
3252
+ },
3253
+ {
3254
+ name: "file.edit",
3255
+ description: "Replace an exact substring in a file under the agent's home directory. Prefer this over file.write for edits \u2014 it touches only the changed region instead of rewriting the whole file. `old_string` must appear exactly once unless `replace_all` is true. Path traversal blocked, 1MB max.",
3256
+ parameters: {
3257
+ type: "object",
3258
+ properties: {
3259
+ path: { type: "string", description: "Path relative to $HOME (or absolute under $HOME)." },
3260
+ old_string: { type: "string", description: "Exact text to replace. Include enough surrounding context to be unique unless replace_all is set." },
3261
+ new_string: { type: "string", description: "Replacement text. Must differ from old_string." },
3262
+ replace_all: { type: "boolean", description: "Replace every occurrence instead of requiring a unique match. Default false." }
3263
+ },
3264
+ required: ["path", "old_string", "new_string"]
3265
+ },
3266
+ execute: async (args) => {
3267
+ const a2 = args;
3268
+ if (typeof a2.old_string !== "string" || a2.old_string === "") {
3269
+ throw new Error("old_string must be a non-empty string");
3270
+ }
3271
+ if (typeof a2.new_string !== "string") {
3272
+ throw new TypeError("new_string must be a string");
3273
+ }
3274
+ if (a2.old_string === a2.new_string) {
3275
+ throw new Error("old_string and new_string are identical \u2014 nothing to change");
3276
+ }
3277
+ const replaceAll = a2.replace_all === true;
3278
+ const p = jailPath(a2.path);
3279
+ const before = readFileSync3(p, "utf8");
3280
+ const occurrences = before.split(a2.old_string).length - 1;
3281
+ if (occurrences === 0) {
3282
+ throw new Error("old_string not found in file");
3283
+ }
3284
+ if (occurrences > 1 && !replaceAll) {
3285
+ throw new Error(`old_string occurs ${occurrences} times \u2014 pass replace_all:true or add surrounding context to make it unique`);
3286
+ }
3287
+ const after = replaceAll ? before.split(a2.old_string).join(a2.new_string) : before.replace(a2.old_string, a2.new_string);
3288
+ if (Buffer.byteLength(after, "utf8") > MAX_BYTES) {
3289
+ throw new Error(`result exceeds ${MAX_BYTES} byte cap`);
3290
+ }
3291
+ writeFileSync2(p, after, { encoding: "utf8" });
3292
+ return { path: p, replacements: replaceAll ? occurrences : 1 };
3293
+ }
3294
+ }
3295
+ ];
3296
+ var BRANCH_RE = /^[\w./-]{1,200}$/;
3297
+ var ID_RE = /^\d{1,12}$/;
3298
+ function shq(s2) {
3299
+ return `'${String(s2).replace(/'/g, "'\\''")}'`;
3300
+ }
3301
+ function assertBranch(v2) {
3302
+ if (typeof v2 !== "string" || !BRANCH_RE.test(v2)) {
3303
+ throw new Error("branch must match ^[A-Za-z0-9._/-]{1,200}$");
3304
+ }
3305
+ return v2;
3306
+ }
3307
+ function assertId(v2) {
3308
+ if (typeof v2 !== "string" && typeof v2 !== "number") throw new Error("id required");
3309
+ const s2 = String(v2);
3310
+ if (!ID_RE.test(s2)) throw new Error("id must be a number");
3311
+ return s2;
3312
+ }
3313
+ var githubAdapter = {
3314
+ id: "github",
3315
+ matchesRemote: (url) => /github\.com/i.test(url),
3316
+ prCreate: (i2) => {
3317
+ const head = assertBranch(i2.head);
3318
+ const parts = ["gh", "pr", "create", "--title", shq(i2.title), "--body", shq(i2.body), "--head", shq(head)];
3319
+ if (i2.base !== void 0) parts.push("--base", shq(assertBranch(i2.base)));
3320
+ return parts.join(" ");
3321
+ },
3322
+ prMerge: (i2) => {
3323
+ const ref = String(i2.ref);
3324
+ const refTok = ID_RE.test(ref) ? ref : assertBranch(ref);
3325
+ const parts = ["gh", "pr", "merge", shq(refTok)];
3326
+ if (i2.squash === true) parts.push("--squash");
3327
+ if (i2.auto) parts.push("--auto");
3328
+ if (i2.deleteBranch) parts.push("--delete-branch");
3329
+ return parts.join(" ");
3330
+ },
3331
+ prStatus: (ref) => {
3332
+ const r3 = String(ref);
3333
+ const refTok = ID_RE.test(r3) ? r3 : assertBranch(r3);
3334
+ return `gh pr view ${shq(refTok)} --json state,mergeStateStatus,statusCheckRollup,reviewDecision`;
3335
+ },
3336
+ issueGet: (ref, repo) => `gh issue view ${assertId(ref)}${repo ? ` --repo ${shq(repo)}` : ""} --json number,title,body,labels`
3337
+ };
3338
+ var azureAdapter = {
3339
+ id: "azure",
3340
+ matchesRemote: (url) => /dev\.azure\.com|visualstudio\.com/i.test(url),
3341
+ prCreate: (i2) => {
3342
+ const head = assertBranch(i2.head);
3343
+ const parts = ["az", "repos", "pr", "create", "--title", shq(i2.title), "--description", shq(i2.body), "--source-branch", shq(head)];
3344
+ if (i2.base !== void 0) parts.push("--target-branch", shq(assertBranch(i2.base)));
3345
+ return parts.join(" ");
3346
+ },
3347
+ prMerge: (i2) => {
3348
+ const id = assertId(i2.ref);
3349
+ const parts = ["az", "repos", "pr", "update", "--id", id];
3350
+ if (i2.auto) parts.push("--auto-complete", "true");
3351
+ else parts.push("--status", "completed");
3352
+ if (i2.squash === true) parts.push("--merge-commit-message-style", "squash");
3353
+ if (i2.deleteBranch) parts.push("--delete-source-branch", "true");
3354
+ return parts.join(" ");
3355
+ },
3356
+ prStatus: (ref) => `az repos pr show --id ${assertId(ref)}`,
3357
+ // Azure work items are org/project-scoped, not repo-scoped, so `repo`
3358
+ // doesn't apply here — the caller's `az` config (defaults.organization/
3359
+ // project) resolves it.
3360
+ issueGet: (ref, _repo) => `az boards work-item show --id ${assertId(ref)}`
3361
+ };
3362
+ var registry = /* @__PURE__ */ new Map([
3363
+ [githubAdapter.id, githubAdapter],
3364
+ [azureAdapter.id, azureAdapter]
3365
+ ]);
3366
+ function listForges() {
3367
+ return [...registry.keys()];
3368
+ }
3369
+ function getForge(id) {
3370
+ const a2 = registry.get(id);
3371
+ if (!a2) {
3372
+ throw new Error(`unknown forge '${id}'. Registered: ${listForges().join(", ")}. Add one with registerForge().`);
3373
+ }
3374
+ return a2;
3375
+ }
3376
+ function detectForge(remoteUrl) {
3377
+ if (typeof remoteUrl !== "string" || remoteUrl === "") {
3378
+ throw new Error("remote URL required to detect forge");
3379
+ }
3380
+ for (const a2 of registry.values()) {
3381
+ if (a2.matchesRemote(remoteUrl)) return a2.id;
3382
+ }
3383
+ throw new Error(`no forge adapter matches remote: ${remoteUrl}. Registered: ${listForges().join(", ")}. Register one with registerForge() (e.g. GitLab/Bitbucket/Gitea).`);
3384
+ }
3385
+ function buildPrCreate(input) {
3386
+ return getForge(input.forge).prCreate(input);
3387
+ }
3388
+ function buildPrMerge(input) {
3389
+ return getForge(input.forge).prMerge(input);
3390
+ }
3391
+ function buildPrStatus(forge, ref) {
3392
+ return getForge(forge).prStatus(ref);
3393
+ }
3394
+ function buildIssueGet(forge, ref, repo) {
3395
+ return getForge(forge).issueGet(ref, repo);
3396
+ }
3397
+ function resolveForge(a2) {
3398
+ if (typeof a2.forge === "string" && a2.forge !== "") return a2.forge;
3399
+ if (typeof a2.remote === "string") return detectForge(a2.remote);
3400
+ throw new Error("provide a forge id (e.g. github, azure, or a registered adapter) or a remote URL to detect it");
3401
+ }
3402
+ var forgeParam = { type: "string", description: "Target forge id (github, azure, or a registered adapter). Omit to auto-detect from `remote`." };
3403
+ var remoteParam = { type: "string", description: "git remote URL \u2014 used to auto-detect the forge when `forge` is omitted." };
3404
+ var forgeTools = [
3405
+ {
3406
+ name: "forge.pr.create",
3407
+ description: "Open a pull request on GitHub (gh) or Azure DevOps (az). Gated via the DDISA grant cycle. Provider chosen by `forge` or auto-detected from `remote`.",
3408
+ parameters: {
3409
+ type: "object",
3410
+ properties: {
3411
+ forge: forgeParam,
3412
+ remote: remoteParam,
3413
+ title: { type: "string", description: "PR title." },
3414
+ body: { type: "string", description: "PR description / body." },
3415
+ head: { type: "string", description: "Source branch." },
3416
+ base: { type: "string", description: "Target branch. Omit for the repo default." }
3417
+ },
3418
+ required: ["title", "body", "head"]
3419
+ },
3420
+ execute: async (args) => {
3421
+ const a2 = args;
3422
+ const cmd = buildPrCreate({ forge: resolveForge(a2), title: a2.title, body: a2.body, head: a2.head, base: a2.base });
3423
+ return await runApeShell(cmd);
3424
+ }
3425
+ },
3426
+ {
3427
+ name: "forge.pr.merge",
3428
+ description: 'Merge a PR \u2014 or with auto=true, arm "merge when checks pass" (gh --auto / az auto-complete) so the platform merges only on green CI. Gated. Never bypasses required checks (branch protection is the server-side gate).',
3429
+ parameters: {
3430
+ type: "object",
3431
+ properties: {
3432
+ forge: forgeParam,
3433
+ remote: remoteParam,
3434
+ ref: { type: "string", description: "GitHub: PR number or branch. Azure: PR id." },
3435
+ auto: { type: "boolean", description: "Arm merge-when-green instead of immediate merge. Recommended." },
3436
+ squash: { type: "boolean", description: "Squash-merge. Default true." },
3437
+ delete_branch: { type: "boolean", description: "Delete the source branch after merge." }
3438
+ },
3439
+ required: ["ref"]
3440
+ },
3441
+ execute: async (args) => {
3442
+ const a2 = args;
3443
+ const cmd = buildPrMerge({ forge: resolveForge(a2), ref: a2.ref, auto: a2.auto, squash: a2.squash, deleteBranch: a2.delete_branch });
3444
+ return await runApeShell(cmd);
3445
+ }
3446
+ },
3447
+ {
3448
+ name: "forge.pr.status",
3449
+ description: "Fetch a PR's state + checks + review decision. Gated (read).",
3450
+ parameters: {
3451
+ type: "object",
3452
+ properties: { forge: forgeParam, remote: remoteParam, ref: { type: "string", description: "PR number/branch (GitHub) or id (Azure)." } },
3453
+ required: ["ref"]
3454
+ },
3455
+ execute: async (args) => {
3456
+ const a2 = args;
3457
+ return await runApeShell(buildPrStatus(resolveForge(a2), a2.ref));
3458
+ }
3459
+ },
3460
+ {
3461
+ name: "forge.issue.get",
3462
+ description: "Fetch an issue (GitHub) or work-item (Azure) \u2014 title, body, labels. Gated (read). Use to turn an assigned task into a coding run.",
3463
+ parameters: {
3464
+ type: "object",
3465
+ properties: { forge: forgeParam, remote: remoteParam, ref: { type: "string", description: "Issue number (GitHub) or work-item id (Azure)." } },
3466
+ required: ["ref"]
3467
+ },
3468
+ execute: async (args) => {
3469
+ const a2 = args;
3470
+ const repo = typeof a2.remote === "string" ? a2.remote : void 0;
3471
+ return await runApeShell(buildIssueGet(resolveForge(a2), a2.ref, repo));
3472
+ }
3473
+ }
3474
+ ];
3475
+ function jailedRoot(envVar, fallbackName) {
3476
+ const home = homedir24();
3477
+ const raw = process2.env[envVar];
3478
+ const dir = raw ? resolve2(raw) : resolve2(home, fallbackName);
3479
+ if (dir !== home && !dir.startsWith(`${home}/`)) {
3480
+ throw new Error(`${envVar} (${dir}) must resolve inside the agent's home`);
3481
+ }
3482
+ return dir;
3483
+ }
3484
+ function workRoot() {
3485
+ return jailedRoot("OPENAPE_CODING_WORK_DIR", "work");
3486
+ }
3487
+ function reposRoot() {
3488
+ return jailedRoot("OPENAPE_CODING_REPOS_DIR", "repos");
3489
+ }
3490
+ var TASK_ID_RE = /^[\w.-]{1,64}$/;
3491
+ var BRANCH_RE2 = /^[\w./-]{1,128}$/;
3492
+ var URL_RE = /^(?:https:\/\/|git@)[\w@:/.-]{3,256}$/;
3493
+ function assertTaskId(v2) {
3494
+ if (typeof v2 !== "string" || !TASK_ID_RE.test(v2)) {
3495
+ throw new Error("task_id must match ^[a-zA-Z0-9._-]{1,64}$");
3496
+ }
3497
+ return v2;
3498
+ }
3499
+ function assertBranch2(v2) {
3500
+ if (typeof v2 !== "string" || !BRANCH_RE2.test(v2)) {
3501
+ throw new Error("branch must match ^[A-Za-z0-9._/-]{1,128}$");
3502
+ }
3503
+ return v2;
3504
+ }
3505
+ function resolveRepo(repo) {
3506
+ if (typeof repo !== "string" || repo === "") {
3507
+ throw new Error("repo must be a non-empty string (URL or path under $HOME)");
3508
+ }
3509
+ const home = homedir24();
3510
+ if (URL_RE.test(repo)) {
3511
+ const tail = repo.replace(/\.git$/, "").replace(/[/:]+$/, "");
3512
+ const parts = tail.split(/[/:]/).filter(Boolean).slice(-2);
3513
+ const base = parts.join("-").replace(/[^\w.-]/g, "");
3514
+ if (!base) throw new Error("could not derive a clone name from repo URL");
3515
+ return { source: repo, baseDir: resolve2(reposRoot(), base), isUrl: true };
3516
+ }
3517
+ const candidate = repo.startsWith("~/") ? resolve2(home, repo.slice(2)) : resolve2(home, repo);
3518
+ if (candidate !== home && !candidate.startsWith(`${home}/`)) {
3519
+ throw new Error(`repo path "${repo}" resolves outside the agent's home`);
3520
+ }
3521
+ return { source: candidate, baseDir: candidate, isUrl: false };
3522
+ }
3523
+ function worktreePathFor(taskId) {
3524
+ return resolve2(workRoot(), assertTaskId(taskId));
3525
+ }
3526
+ var q2 = (s2) => `'${s2}'`;
3527
+ function buildCreateCommand(repo, taskId, branch) {
3528
+ const id = assertTaskId(taskId);
3529
+ const br = assertBranch2(branch);
3530
+ const { source, baseDir, isUrl } = resolveRepo(repo);
3531
+ const wt = worktreePathFor(id);
3532
+ const clone = isUrl ? `if [ ! -d ${q2(baseDir)}/.git ]; then git clone ${q2(source)} ${q2(baseDir)}; fi` : `test -d ${q2(baseDir)}/.git`;
3533
+ const reset = [
3534
+ `git -C ${q2(baseDir)} worktree remove --force ${q2(wt)} 2>/dev/null || true`,
3535
+ `git -C ${q2(baseDir)} worktree prune 2>/dev/null || true`,
3536
+ `rm -rf ${q2(wt)} 2>/dev/null || true`
3537
+ ].join("; ");
3538
+ const ghAuth = /github\.com/i.test(source) ? `git -C ${q2(baseDir)} config credential.helper '' && git -C ${q2(baseDir)} config --add credential.helper '!f() { echo username=x-access-token; echo "password=$GH_TOKEN"; }; f'` : "true";
3539
+ return [
3540
+ `mkdir -p ${q2(reposRoot())} ${q2(workRoot())}`,
3541
+ clone,
3542
+ ghAuth,
3543
+ `git -C ${q2(baseDir)} fetch --quiet || true`,
3544
+ `{ ${reset}; }`,
3545
+ `git -C ${q2(baseDir)} worktree add -B ${q2(br)} ${q2(wt)}`,
3546
+ `echo ${q2(wt)}`
3547
+ ].join(" && ");
3548
+ }
3549
+ function buildRemoveCommand(repo, taskId) {
3550
+ const id = assertTaskId(taskId);
3551
+ const { baseDir } = resolveRepo(repo);
3552
+ const wt = worktreePathFor(id);
3553
+ return `git -C ${q2(baseDir)} worktree remove --force ${q2(wt)} && git -C ${q2(baseDir)} worktree prune`;
3554
+ }
3555
+ function buildListCommand() {
3556
+ return `ls -1 ${q2(workRoot())} 2>/dev/null || true`;
3557
+ }
3558
+ var gitWorktreeTools = [
3559
+ {
3560
+ name: "git.worktree",
3561
+ description: "Manage isolated git worktrees for coding tasks. action=create clones the repo (cached under ~/repos) and adds a fresh worktree under ~/work/<task_id> on a new branch. action=remove tears it down. action=list shows current task worktrees. Git operations go through the DDISA grant cycle (git-shape).",
3562
+ parameters: {
3563
+ type: "object",
3564
+ properties: {
3565
+ action: { type: "string", enum: ["create", "remove", "list"], description: "create | remove | list" },
3566
+ repo: { type: "string", description: "For create/remove: git remote URL (https/git@) or a path under $HOME to an existing clone." },
3567
+ task_id: { type: "string", description: "For create/remove: identifier for the worktree, ^[a-zA-Z0-9._-]{1,64}$. The worktree lands at ~/work/<task_id>." },
3568
+ branch: { type: "string", description: "For create: new branch name, ^[A-Za-z0-9._/-]{1,128}$." }
3569
+ },
3570
+ required: ["action"]
3571
+ },
3572
+ execute: async (args) => {
3573
+ const a2 = args;
3574
+ let cmd;
3575
+ if (a2.action === "create") {
3576
+ if (typeof a2.branch !== "string") throw new Error("branch is required for action=create");
3577
+ cmd = buildCreateCommand(a2.repo, assertTaskId(a2.task_id), a2.branch);
3578
+ } else if (a2.action === "remove") {
3579
+ cmd = buildRemoveCommand(a2.repo, assertTaskId(a2.task_id));
3580
+ } else if (a2.action === "list") {
3581
+ cmd = buildListCommand();
3582
+ } else {
3583
+ throw new Error("action must be one of: create, remove, list");
3584
+ }
3585
+ const res = await runApeShell(cmd);
3586
+ return {
3587
+ action: a2.action,
3588
+ ...a2.action !== "list" ? { worktree: worktreePathFor(assertTaskId(a2.task_id)) } : {},
3589
+ stdout: res.stdout,
3590
+ stderr: res.stderr,
3591
+ exit_code: res.exit_code,
3592
+ ...res.error ? { error: res.error, hint: res.hint } : {}
3593
+ };
3594
+ }
3595
+ }
3596
+ ];
3597
+ async function safeFetch(rawUrl, init2 = {}, maxRedirects = 5) {
3598
+ let current = rawUrl;
3599
+ for (let hop = 0; hop <= maxRedirects; hop += 1) {
3600
+ await assertPublicUrl(current, { allowHttp: true });
3601
+ const res = await fetch(current, { ...init2, redirect: "manual" });
3602
+ if (res.status >= 300 && res.status < 400) {
3603
+ const location = res.headers.get("location");
3604
+ if (!location) return res;
3605
+ current = new URL(location, current).toString();
3606
+ if (init2.body) init2 = { ...init2, body: void 0, method: "GET" };
3607
+ continue;
3608
+ }
3609
+ return res;
3610
+ }
3611
+ throw new Error(`Too many redirects (>${maxRedirects}) for ${rawUrl}`);
3612
+ }
3613
+ var MAX_BYTES2 = 1024 * 1024;
3614
+ var FORBIDDEN_HEADERS = /* @__PURE__ */ new Set([
3615
+ "host",
3616
+ "authorization",
3617
+ "cookie",
3618
+ "connection",
3619
+ "transfer-encoding",
3620
+ "upgrade",
3621
+ "proxy-authorization"
3622
+ ]);
3623
+ function sanitizeHeaders(input) {
3624
+ if (!input || typeof input !== "object") return {};
3625
+ const out = {};
3626
+ for (const [k2, v2] of Object.entries(input)) {
3627
+ if (typeof v2 !== "string") continue;
3628
+ if (FORBIDDEN_HEADERS.has(k2.toLowerCase())) continue;
3629
+ out[k2] = v2;
3630
+ }
3631
+ return out;
3632
+ }
3633
+ async function readCappedBody(res) {
3634
+ const buf = new Uint8Array(MAX_BYTES2 + 1);
3635
+ let written = 0;
3636
+ const reader = res.body?.getReader();
3637
+ if (!reader) return await res.text();
3638
+ while (true) {
3639
+ const { value, done } = await reader.read();
3640
+ if (done) break;
3641
+ if (written + value.byteLength > MAX_BYTES2) {
3642
+ buf.set(value.subarray(0, MAX_BYTES2 - written), written);
3643
+ written = MAX_BYTES2;
3644
+ try {
3645
+ await reader.cancel();
3646
+ } catch {
3647
+ }
3648
+ break;
3649
+ }
3650
+ buf.set(value, written);
3651
+ written += value.byteLength;
3652
+ }
3653
+ return new TextDecoder().decode(buf.subarray(0, written));
3654
+ }
3655
+ var httpTools = [
3656
+ {
3657
+ name: "http.get",
3658
+ description: "GET an HTTPS URL and return the response body (capped at 1MB). Useful for reading public APIs, RSS feeds, web pages.",
3659
+ parameters: {
3660
+ type: "object",
3661
+ properties: {
3662
+ url: { type: "string", description: "Absolute HTTPS URL." },
3663
+ headers: { type: "object", description: "Optional headers (Host, Authorization, Cookie are stripped)." }
3664
+ },
3665
+ required: ["url"]
3666
+ },
3667
+ execute: async (args) => {
3668
+ const a2 = args;
3669
+ if (typeof a2.url !== "string") {
3670
+ throw new TypeError("url must be an http(s) URL");
3671
+ }
3672
+ const res = await safeFetch(a2.url, { method: "GET", headers: sanitizeHeaders(a2.headers) });
3673
+ const body = await readCappedBody(res);
3674
+ return { status: res.status, headers: Object.fromEntries(res.headers), body };
3675
+ }
3676
+ },
3677
+ {
3678
+ name: "http.post",
3679
+ description: "POST JSON to an HTTPS URL and return the response body (capped at 1MB).",
3680
+ parameters: {
3681
+ type: "object",
3682
+ properties: {
3683
+ url: { type: "string", description: "Absolute HTTPS URL." },
3684
+ body: { description: "JSON-serialisable payload." },
3685
+ headers: { type: "object", description: "Optional headers (Host, Authorization, Cookie are stripped)." }
3686
+ },
3687
+ required: ["url", "body"]
3688
+ },
3689
+ execute: async (args) => {
3690
+ const a2 = args;
3691
+ if (typeof a2.url !== "string") {
3692
+ throw new TypeError("url must be an http(s) URL");
3693
+ }
3694
+ const res = await safeFetch(a2.url, {
3695
+ method: "POST",
3696
+ headers: { "content-type": "application/json", ...sanitizeHeaders(a2.headers) },
3697
+ body: JSON.stringify(a2.body)
3698
+ });
3699
+ const body = await readCappedBody(res);
3700
+ return { status: res.status, headers: Object.fromEntries(res.headers), body };
3701
+ }
3702
+ }
3703
+ ];
3704
+ function o365(args) {
3705
+ try {
3706
+ return execFileSync("o365-cli", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
3707
+ } catch (err) {
3708
+ const e2 = err;
3709
+ if (e2.code === "ENOENT") {
3710
+ throw new Error("o365-cli is not installed on this agent host");
3711
+ }
3712
+ const stderr = typeof e2.stderr === "string" ? e2.stderr : e2.stderr?.toString("utf8");
3713
+ throw new Error(`o365-cli failed: ${stderr ?? e2.message ?? err}`);
3714
+ }
3715
+ }
3716
+ var mailTools = [
3717
+ {
3718
+ name: "mail.list",
3719
+ description: "List recent inbox messages via o365-cli. Optional `unread_only` and `limit`.",
3720
+ parameters: {
3721
+ type: "object",
3722
+ properties: {
3723
+ limit: { type: "integer", minimum: 1, maximum: 100, default: 20 },
3724
+ unread_only: { type: "boolean", default: false }
3725
+ },
3726
+ required: []
3727
+ },
3728
+ execute: async (args) => {
3729
+ const a2 = args ?? {};
3730
+ const argv2 = ["mail", "list", "--json", "--limit", String(a2.limit ?? 20)];
3731
+ if (a2.unread_only) argv2.push("--unread");
3732
+ const out = o365(argv2);
3733
+ try {
3734
+ return JSON.parse(out);
3735
+ } catch {
3736
+ return { raw: out };
3737
+ }
3738
+ }
3739
+ },
3740
+ {
3741
+ name: "mail.search",
3742
+ description: "Search the inbox via o365-cli using a free-form query string.",
3743
+ parameters: {
3744
+ type: "object",
3745
+ properties: {
3746
+ q: { type: "string" },
3747
+ limit: { type: "integer", minimum: 1, maximum: 100, default: 20 }
3748
+ },
3749
+ required: ["q"]
3750
+ },
3751
+ execute: async (args) => {
3752
+ const a2 = args;
3753
+ if (typeof a2.q !== "string" || a2.q.length === 0) throw new Error("q is required");
3754
+ const argv2 = ["mail", "search", a2.q, "--json", "--limit", String(a2.limit ?? 20)];
3755
+ const out = o365(argv2);
3756
+ try {
3757
+ return JSON.parse(out);
3758
+ } catch {
3759
+ return { raw: out };
3760
+ }
3761
+ }
3762
+ }
3763
+ ];
3764
+ function troopBase() {
3765
+ return (process.env.OPENAPE_TROOP_URL ?? "https://troop.openape.ai").replace(/\/+$/, "");
3766
+ }
3767
+ function readAgentToken() {
3768
+ const path = process.env.OPENAPE_CLI_AUTH_HOME ? join4(process.env.OPENAPE_CLI_AUTH_HOME, "auth.json") : join4(homedir32(), ".config", "apes", "auth.json");
3769
+ const auth = JSON.parse(readFileSync23(path, "utf8"));
3770
+ if (!auth.access_token) throw new Error(`no access_token in ${path}`);
3771
+ return auth.access_token;
3772
+ }
3773
+ async function exchangeBearer(base, scope) {
3774
+ const res = await fetch(`${base}/api/cli/exchange`, {
3775
+ method: "POST",
3776
+ headers: { "content-type": "application/json" },
3777
+ body: JSON.stringify({ subject_token: readAgentToken(), scopes: [scope] })
3778
+ });
3779
+ if (!res.ok) {
3780
+ throw new Error(`token exchange ${res.status} \u2014 ${(await res.text().catch(() => "")).slice(0, 200)} (does this agent hold the ${scope} scope?)`);
3781
+ }
3782
+ return (await res.json()).access_token;
3783
+ }
3784
+ var spawnTools = [
3785
+ {
3786
+ name: "agent.spawn",
3787
+ description: "Spawn a worker agent on the nest via troop, tiering its compute by task difficulty: pick `model` (gpt-5.4-mini | gpt-5.4 | gpt-5.5) and `reasoning_effort` (minimal | low | medium | high) \u2014 quick-win = cheap+low, research/architecture = gpt-5.5+high. Optionally attach a `recipe_ref` so the worker runs a known persona. Returns the spawn intent id. Use multiple calls to fan out several workers in parallel.",
3788
+ parameters: {
3789
+ type: "object",
3790
+ properties: {
3791
+ name: { type: "string", description: "unique worker name, /^[a-z][a-z0-9-]{0,23}$/" },
3792
+ model: { type: "string", description: "gpt-5.4-mini | gpt-5.4 | gpt-5.5" },
3793
+ reasoning_effort: { type: "string", description: "minimal | low | medium | high" },
3794
+ recipe_ref: { type: "string", description: "optional recipe, e.g. github.com/openape-ai/agent-catalog/backend-engineer@v0.2.0" },
3795
+ system_prompt: { type: "string", description: "optional system prompt / task brief" }
3796
+ },
3797
+ required: ["name"]
3798
+ },
3799
+ execute: async (args) => {
3800
+ const a2 = args;
3801
+ const base = troopBase();
3802
+ let bearer;
3803
+ try {
3804
+ bearer = await exchangeBearer(base, "troop:spawn-agent");
3805
+ } catch (err) {
3806
+ return `spawn failed: ${err instanceof Error ? err.message : String(err)}`;
3807
+ }
3808
+ const body = { name: a2.name };
3809
+ if (a2.model) body.bridge_model = a2.model;
3810
+ if (a2.reasoning_effort) body.bridge_reasoning_effort = a2.reasoning_effort;
3811
+ if (a2.system_prompt) body.system_prompt = a2.system_prompt;
3812
+ if (a2.recipe_ref) body.recipe = { repo_ref: a2.recipe_ref, params: {} };
3813
+ const spRes = await fetch(`${base}/api/agents/spawn-intent`, {
3814
+ method: "POST",
3815
+ headers: { "content-type": "application/json", authorization: `Bearer ${bearer}` },
3816
+ body: JSON.stringify(body)
3817
+ });
3818
+ if (!spRes.ok) {
3819
+ return `spawn failed: spawn-intent ${spRes.status} \u2014 ${(await spRes.text().catch(() => "")).slice(0, 200)}`;
3820
+ }
3821
+ const sp = await spRes.json();
3822
+ return `spawned worker "${a2.name}" (model=${a2.model ?? "default"}, reasoning=${a2.reasoning_effort ?? "default"}); intent=${sp.intent_id ?? "?"}`;
3823
+ }
3824
+ },
3825
+ {
3826
+ name: "agent.destroy",
3827
+ description: "Destroy a worker agent on the nest (full teardown: OS user, IdP, bridge). The PM calls this after collecting an ephemeral worker's result, so workers do not linger idle. Requires the troop:destroy-agent scope.",
3828
+ parameters: {
3829
+ type: "object",
3830
+ properties: {
3831
+ name: { type: "string", description: "the worker agent name to destroy" }
3832
+ },
3833
+ required: ["name"]
3834
+ },
3835
+ execute: async (args) => {
3836
+ const a2 = args;
3837
+ const base = troopBase();
3838
+ let bearer;
3839
+ try {
3840
+ bearer = await exchangeBearer(base, "troop:destroy-agent");
3841
+ } catch (err) {
3842
+ return `destroy failed: ${err instanceof Error ? err.message : String(err)}`;
3843
+ }
3844
+ const res = await fetch(`${base}/api/agents/destroy-intent`, {
3845
+ method: "POST",
3846
+ headers: { "content-type": "application/json", authorization: `Bearer ${bearer}` },
3847
+ body: JSON.stringify({ name: a2.name })
3848
+ });
3849
+ if (!res.ok) {
3850
+ return `destroy failed: destroy-intent ${res.status} \u2014 ${(await res.text().catch(() => "")).slice(0, 200)}`;
3851
+ }
3852
+ const d2 = await res.json();
3853
+ return `destroying worker "${a2.name}"; intent=${d2.intent_id ?? "?"}`;
3854
+ }
3855
+ }
3856
+ ];
3857
+ function ape(args) {
3858
+ try {
3859
+ return execFileSync2("ape-tasks", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
3860
+ } catch (err) {
3861
+ const e2 = err;
3862
+ const stderr = typeof e2.stderr === "string" ? e2.stderr : e2.stderr?.toString("utf8");
3863
+ throw new Error(`ape-tasks failed: ${stderr ?? e2.message ?? err}`);
3864
+ }
3865
+ }
3866
+ var tasksTools = [
3867
+ {
3868
+ name: "tasks.list",
3869
+ description: "List the owner's open ape-tasks (the user's personal task list at tasks.openape.ai).",
3870
+ parameters: {
3871
+ type: "object",
3872
+ properties: {
3873
+ status: { type: "string", enum: ["open", "doing", "done", "archived"] },
3874
+ team_id: { type: "string" }
3875
+ },
3876
+ required: []
3877
+ },
3878
+ execute: async (args) => {
3879
+ const a2 = args ?? {};
3880
+ const argv2 = ["list", "--json"];
3881
+ if (a2.status) argv2.push("--status", a2.status);
3882
+ if (a2.team_id) argv2.push("--team", a2.team_id);
3883
+ const out = ape(argv2);
3884
+ try {
3885
+ return JSON.parse(out);
3886
+ } catch {
3887
+ return { raw: out };
3888
+ }
3889
+ }
3890
+ },
3891
+ {
3892
+ name: "tasks.create",
3893
+ description: "Create a new ape-task at tasks.openape.ai. Pass `team` (the team id) to file it on a shared team board, and `assignee` (an email) to delegate it to a teammate.",
3894
+ parameters: {
3895
+ type: "object",
3896
+ properties: {
3897
+ title: { type: "string" },
3898
+ notes: { type: "string" },
3899
+ priority: { type: "string", enum: ["low", "med", "high"] },
3900
+ due_at: { type: "string", description: "ISO date or +Nh/+Nd shorthand." },
3901
+ team: { type: "string", description: "Team id to file the task on (required when you belong to a team)." },
3902
+ assignee: { type: "string", description: "Email of the teammate to assign the task to." },
3903
+ dedup_key: { type: "string", description: "Stable id for the source (e.g. a mail Message-ID). If an open task with this key already exists, no duplicate is created \u2014 pass it for recurring triage so the same item is not filed twice." }
3904
+ },
3905
+ required: ["title"]
3906
+ },
3907
+ execute: async (args) => {
3908
+ const a2 = args;
3909
+ const argv2 = ["new", "--title", a2.title, "--json"];
3910
+ if (a2.notes) argv2.push("--notes", a2.notes);
3911
+ if (a2.priority) argv2.push("--priority", a2.priority);
3912
+ if (a2.due_at) argv2.push("--due", a2.due_at);
3913
+ if (a2.team) argv2.push("--team", a2.team);
3914
+ if (a2.assignee) argv2.push("--assignee", a2.assignee);
3915
+ if (a2.dedup_key) argv2.push("--dedup-key", a2.dedup_key);
3916
+ const out = ape(argv2);
3917
+ try {
3918
+ return JSON.parse(out);
3919
+ } catch {
3920
+ return { raw: out };
3921
+ }
3922
+ }
3923
+ }
3924
+ ];
3925
+ var timeTools = [
3926
+ {
3927
+ name: "time.now",
3928
+ description: "Returns the current UTC date and time as ISO 8601 plus epoch seconds. No inputs.",
3929
+ parameters: { type: "object", properties: {}, required: [] },
3930
+ execute: async () => {
3931
+ const now = /* @__PURE__ */ new Date();
3932
+ return {
3933
+ iso: now.toISOString(),
3934
+ epoch_seconds: Math.floor(now.getTime() / 1e3),
3935
+ timezone_offset_minutes: -now.getTimezoneOffset()
3936
+ };
3937
+ }
3938
+ }
3939
+ ];
3940
+ var TROOP = "https://troop.openape.ai";
3941
+ var RESOURCES = ["objectives", "reports", "members", "cost-snapshots", "overview"];
3942
+ function pathFor(resource, orgId) {
3943
+ const id = encodeURIComponent(orgId);
3944
+ return resource === "overview" ? `/api/orgs/${id}` : `/api/orgs/${id}/${resource}`;
3945
+ }
3946
+ var OBJECTIVE_STATUS = ["planned", "in_progress", "done", "abandoned"];
3947
+ var troopTools = [
3948
+ {
3949
+ name: "troop.company.read",
3950
+ description: "Read your troop company data on troop.openape.ai. resource: objectives | reports | members | cost-snapshots | overview (vision+budget). Read-only.",
3951
+ parameters: {
3952
+ type: "object",
3953
+ properties: {
3954
+ resource: { type: "string", enum: [...RESOURCES], description: "Which company resource to read." },
3955
+ org_id: { type: "string", description: "Your company (org) id." }
3956
+ },
3957
+ required: ["resource", "org_id"]
3958
+ },
3959
+ execute: async (args) => {
3960
+ const { resource, org_id } = args ?? {};
3961
+ if (!resource || !RESOURCES.includes(resource)) {
3962
+ throw new Error(`troop.company.read: unknown resource '${resource}' (expected ${RESOURCES.join(" | ")})`);
3963
+ }
3964
+ if (!org_id) throw new Error("troop.company.read: org_id is required");
3965
+ const bearer = await getAuthorizedBearer({ endpoint: TROOP, aud: "troop.openape.ai" });
3966
+ const res = await fetch(`${TROOP}${pathFor(resource, org_id)}`, {
3967
+ headers: { authorization: bearer }
3968
+ });
3969
+ if (!res.ok) {
3970
+ throw new Error(`troop.company.read ${resource} \u2192 ${res.status}: ${(await res.text()).slice(0, 200)}`);
3971
+ }
3972
+ return JSON.stringify(await res.json());
3973
+ }
3974
+ },
3975
+ {
3976
+ name: "troop.objective.upsert",
3977
+ description: "Create or update a company objective on troop.openape.ai. Pass objective_id to update an existing one; omit it to create. Authenticated as the agent (acting for the owner).",
3978
+ parameters: {
3979
+ type: "object",
3980
+ properties: {
3981
+ org_id: { type: "string", description: "Your company (org) id." },
3982
+ objective_id: { type: "string", description: "Omit to create; pass to update an existing objective." },
3983
+ title: { type: "string" },
3984
+ description: { type: "string" },
3985
+ status: { type: "string", enum: [...OBJECTIVE_STATUS] },
3986
+ target_date: { type: "number", description: "Unix seconds, or null to clear." }
3987
+ },
3988
+ required: ["org_id"]
3989
+ },
3990
+ execute: async (args) => {
3991
+ const a2 = args ?? {};
3992
+ if (!a2.org_id) throw new Error("troop.objective.upsert: org_id is required");
3993
+ if (a2.status && !OBJECTIVE_STATUS.includes(a2.status)) {
3994
+ throw new Error(`troop.objective.upsert: bad status '${a2.status}'`);
3995
+ }
3996
+ if (!a2.objective_id && !a2.title) throw new Error("troop.objective.upsert: title is required to create an objective");
3997
+ const bearer = await getAuthorizedBearer({ endpoint: TROOP, aud: "troop.openape.ai" });
3998
+ const id = encodeURIComponent(a2.org_id);
3999
+ const body = {};
4000
+ if (a2.title !== void 0) body.title = a2.title;
4001
+ if (a2.description !== void 0) body.description = a2.description;
4002
+ if (a2.status !== void 0) body.status = a2.status;
4003
+ if (a2.target_date !== void 0) body.target_date = a2.target_date;
4004
+ const url = a2.objective_id ? `${TROOP}/api/orgs/${id}/objectives/${encodeURIComponent(a2.objective_id)}` : `${TROOP}/api/orgs/${id}/objectives`;
4005
+ const res = await fetch(url, {
4006
+ method: a2.objective_id ? "PATCH" : "POST",
4007
+ headers: { authorization: bearer, "content-type": "application/json" },
4008
+ body: JSON.stringify(body)
4009
+ });
4010
+ if (!res.ok) {
4011
+ throw new Error(`troop.objective.upsert \u2192 ${res.status}: ${(await res.text()).slice(0, 200)}`);
4012
+ }
4013
+ return JSON.stringify(await res.json());
4014
+ }
4015
+ }
4016
+ ];
4017
+ var CWD_RE = /^[\w./-]{1,256}$/;
4018
+ async function runVerify(cwd, command, timeoutMs) {
4019
+ if (typeof cwd !== "string" || !CWD_RE.test(cwd)) {
4020
+ throw new Error("cwd must match ^[A-Za-z0-9._/-]{1,256}$");
4021
+ }
4022
+ if (typeof command !== "string" || command.trim() === "") {
4023
+ throw new Error("verify command must be a non-empty string");
4024
+ }
4025
+ const res = await runApeShell(`cd '${cwd}' && ${command}`, timeoutMs);
4026
+ return {
4027
+ passed: res.exit_code === 0,
4028
+ exit_code: res.exit_code,
4029
+ stdout: res.stdout,
4030
+ stderr: res.stderr,
4031
+ ...res.timed_out ? { timed_out: true } : {}
4032
+ };
4033
+ }
4034
+ var verifyTools = [
4035
+ {
4036
+ name: "verify",
4037
+ description: "Run the verification command (tests/build/lint) in a worktree and report pass/fail. The coding loop must NOT open or merge a PR when this fails. Runs through the DDISA grant cycle (same as bash). Returns { passed, exit_code, stdout, stderr }.",
4038
+ parameters: {
4039
+ type: "object",
4040
+ properties: {
4041
+ cwd: { type: "string", description: "Worktree path to run in (e.g. ~/work/issue-42)." },
4042
+ command: { type: "string", description: "Verification command, e.g. `pnpm test` or `npm run build && npm test`." },
4043
+ timeout_ms: { type: "number", description: "Wall-clock cap incl. approval wait. Default 300000." }
4044
+ },
4045
+ required: ["cwd", "command"]
4046
+ },
4047
+ execute: async (args) => {
4048
+ const a2 = args;
4049
+ const timeout = typeof a2.timeout_ms === "number" && a2.timeout_ms > 0 ? a2.timeout_ms : void 0;
4050
+ return await runVerify(a2.cwd, a2.command, timeout);
4051
+ }
4052
+ }
4053
+ ];
4054
+ var ALL_TOOLS = [
4055
+ ...timeTools,
4056
+ ...httpTools,
4057
+ ...fileTools,
4058
+ ...tasksTools,
4059
+ ...mailTools,
4060
+ ...bashTools,
4061
+ ...gitWorktreeTools,
4062
+ ...verifyTools,
4063
+ ...forgeTools,
4064
+ ...spawnTools,
4065
+ ...troopTools
4066
+ ];
4067
+ var TOOLS = Object.fromEntries(
4068
+ ALL_TOOLS.map((t2) => [t2.name, t2])
4069
+ );
4070
+ function taskTools(names) {
4071
+ const out = [];
4072
+ const missing = [];
4073
+ for (const name of names) {
4074
+ const tool = TOOLS[name];
4075
+ if (!tool) missing.push(name);
4076
+ else out.push(tool);
4077
+ }
4078
+ if (missing.length > 0) {
4079
+ throw new Error(`unknown tool(s): ${missing.join(", ")}`);
4080
+ }
4081
+ return out;
4082
+ }
4083
+ function asOpenAiTools(tools) {
4084
+ return tools.map((t2) => ({
4085
+ type: "function",
4086
+ function: { name: wireToolName(t2.name), description: t2.description, parameters: t2.parameters }
4087
+ }));
4088
+ }
4089
+ function wireToolName(local) {
4090
+ return local.replace(/\./g, "_");
4091
+ }
4092
+ function localToolName(wire) {
4093
+ for (const t2 of Object.values(TOOLS)) {
4094
+ if (wireToolName(t2.name) === wire) return t2.name;
4095
+ }
4096
+ return wire;
4097
+ }
4098
+ function previewJson(value, max = 500) {
4099
+ let s2;
4100
+ try {
4101
+ s2 = JSON.stringify(value);
4102
+ } catch {
4103
+ s2 = String(value);
4104
+ }
4105
+ return s2.length > max ? `${s2.slice(0, max)}\u2026` : s2;
4106
+ }
4107
+ async function aggregateChatStream(res) {
4108
+ if (!res.body) throw new Error("LiteLLM streaming response had no body");
4109
+ const reader = res.body.getReader();
4110
+ const decoder = new TextDecoder();
4111
+ let buf = "";
4112
+ let content = "";
4113
+ const toolCalls = /* @__PURE__ */ new Map();
4114
+ let finishReason;
4115
+ while (true) {
4116
+ const { value, done } = await reader.read();
4117
+ if (done) break;
4118
+ buf += decoder.decode(value, { stream: true });
4119
+ while (true) {
4120
+ const nl = buf.indexOf("\n");
4121
+ if (nl === -1) break;
4122
+ const line = buf.slice(0, nl).trim();
4123
+ buf = buf.slice(nl + 1);
4124
+ if (!line.startsWith("data:")) continue;
4125
+ const payload = line.slice(5).trim();
4126
+ if (!payload || payload === "[DONE]") continue;
4127
+ let chunk;
4128
+ try {
4129
+ chunk = JSON.parse(payload);
4130
+ } catch {
4131
+ continue;
4132
+ }
4133
+ const ch0 = chunk.choices?.[0];
4134
+ const delta = ch0?.delta;
4135
+ if (delta?.content) content += delta.content;
4136
+ if (delta?.tool_calls) {
4137
+ for (const tc of delta.tool_calls) {
4138
+ const idx = tc.index ?? 0;
4139
+ const existing = toolCalls.get(idx) ?? { id: "", type: "function", function: { name: "", arguments: "" } };
4140
+ if (tc.id) existing.id = tc.id;
4141
+ if (tc.function?.name) existing.function.name = tc.function.name;
4142
+ if (tc.function?.arguments) existing.function.arguments += tc.function.arguments;
4143
+ toolCalls.set(idx, existing);
4144
+ }
4145
+ }
4146
+ if (ch0?.finish_reason) finishReason = ch0.finish_reason;
4147
+ }
4148
+ }
4149
+ const message = { role: "assistant", content: content || null };
4150
+ if (toolCalls.size > 0) message.tool_calls = Array.from(toolCalls.values());
4151
+ return { choices: [{ message, finish_reason: finishReason }] };
4152
+ }
4153
+ async function runLoop(opts) {
4154
+ const fetchFn = opts.fetchImpl ?? fetch;
4155
+ const trace = [];
4156
+ const messages = [
4157
+ { role: "system", content: opts.systemPrompt },
4158
+ ...opts.history ?? [],
4159
+ { role: "user", content: opts.userMessage }
4160
+ ];
4161
+ const tools = asOpenAiTools(opts.tools);
4162
+ for (let step = 1; step <= opts.maxSteps; step++) {
4163
+ const requestBody = {
4164
+ model: opts.config.model,
4165
+ messages,
4166
+ ...opts.config.reasoningEffort ? { reasoning_effort: opts.config.reasoningEffort } : {},
4167
+ ...tools.length > 0 ? { tools, tool_choice: "auto" } : {},
4168
+ ...opts.streamAggregate ? { stream: true } : {}
4169
+ };
4170
+ const res = await fetchFn(`${opts.config.apiBase}/chat/completions`, {
4171
+ method: "POST",
4172
+ headers: {
4173
+ "authorization": `Bearer ${opts.config.apiKey}`,
4174
+ "content-type": "application/json"
4175
+ },
4176
+ body: JSON.stringify(requestBody)
4177
+ });
4178
+ if (!res.ok) {
4179
+ const text = await res.text().catch(() => "");
4180
+ throw new Error(`LiteLLM ${res.status}: ${text.slice(0, 500)}`);
4181
+ }
4182
+ const data = opts.streamAggregate ? await aggregateChatStream(res) : await res.json();
4183
+ const choice = data.choices?.[0];
4184
+ if (!choice) throw new Error("LiteLLM response had no choices");
4185
+ const assistant = choice.message;
4186
+ messages.push(assistant);
4187
+ if (assistant.content) opts.handlers?.onTextDelta?.(assistant.content);
4188
+ trace.push({
4189
+ step,
4190
+ type: "assistant",
4191
+ preview: previewJson({ content: assistant.content, tool_calls: assistant.tool_calls?.length ?? 0 })
4192
+ });
4193
+ if (!assistant.tool_calls || assistant.tool_calls.length === 0) {
4194
+ const result2 = {
4195
+ status: "ok",
4196
+ finalMessage: assistant.content,
4197
+ stepCount: step,
4198
+ trace
4199
+ };
4200
+ opts.handlers?.onDone?.(result2);
4201
+ return result2;
4202
+ }
4203
+ for (const call of assistant.tool_calls) {
4204
+ const wireName = call.function.name;
4205
+ const localName = localToolName(wireName);
4206
+ const tool = opts.tools.find((t2) => t2.name === localName);
4207
+ let parsedArgs;
4208
+ try {
4209
+ parsedArgs = JSON.parse(call.function.arguments);
4210
+ } catch {
4211
+ parsedArgs = {};
4212
+ }
4213
+ opts.handlers?.onToolCall?.({ name: localName, args: parsedArgs });
4214
+ trace.push({ step, type: "tool_call", tool: localName, preview: previewJson(parsedArgs) });
4215
+ let result2;
4216
+ let isError = false;
4217
+ if (!tool) {
4218
+ result2 = `unknown tool: ${localName}`;
4219
+ isError = true;
4220
+ } else {
4221
+ try {
4222
+ result2 = await tool.execute(parsedArgs);
4223
+ } catch (err) {
4224
+ result2 = err?.message ?? String(err);
4225
+ isError = true;
4226
+ }
4227
+ }
4228
+ if (isError) {
4229
+ opts.handlers?.onToolError?.({ name: localName, error: String(result2) });
4230
+ trace.push({ step, type: "tool_error", tool: localName, preview: previewJson(result2) });
4231
+ } else {
4232
+ opts.handlers?.onToolResult?.({ name: localName, result: result2 });
4233
+ trace.push({ step, type: "tool_result", tool: localName, preview: previewJson(result2) });
4234
+ }
4235
+ messages.push({
4236
+ role: "tool",
4237
+ tool_call_id: call.id,
4238
+ name: wireToolName(localName),
4239
+ content: typeof result2 === "string" ? result2 : JSON.stringify(result2)
4240
+ });
4241
+ }
4242
+ }
4243
+ const result = {
4244
+ status: "error",
4245
+ finalMessage: `max_steps (${opts.maxSteps}) reached without completion`,
4246
+ stepCount: opts.maxSteps,
4247
+ trace
4248
+ };
4249
+ opts.handlers?.onDone?.(result);
4250
+ return result;
4251
+ }
4252
+ var RPC_SESSION_TTL_MS = 60 * 60 * 1e3;
4253
+ var DEFAULT_INSTRUCTIONS = [
4254
+ "Work in the provided worktree. When done:",
4255
+ "- ensure the verification command passes (no PR on red)",
4256
+ "- open a PR that references this issue",
4257
+ "- leave risk-path / agent-judged-risky changes for human approval"
4258
+ ].join("\n");
4259
+ var DIFF_CAP = 60 * 1024;
4260
+ var DIFF_CAP2 = 48 * 1024;
4261
+ var RISK_SYSTEM = [
4262
+ "You are a security/risk classifier for an autonomous coding agent.",
4263
+ "Given a diff + changed file paths, decide whether merging it WITHOUT a human is risky.",
4264
+ "Risky = touches authentication, authorization, secrets/credentials, payment, data migrations,",
4265
+ "deploy/release/CI config, cryptography, deletion of data, or anything whose failure is hard to",
4266
+ "reverse in production. Routine code/tests/docs/refactors are NOT risky.",
4267
+ 'Respond ONLY as JSON: {"risky": boolean, "reason": string}.'
4268
+ ].join(" ");
4269
+ var REVIEW_SYSTEM = [
4270
+ "You are a code reviewer for an autonomous coding agent.",
4271
+ "Given a PR diff, decide whether it is correct, safe, and complete enough to auto-merge.",
4272
+ "Approve only if you would be comfortable shipping it without further human review.",
4273
+ "Block if you see bugs, missing tests, security issues, or incomplete work.",
4274
+ 'Respond ONLY as JSON: {"approved": boolean, "reason": string}.'
4275
+ ].join(" ");
4276
+
4277
+ // src/identity.ts
4278
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
4279
+ import { homedir as homedir6 } from "os";
4280
+ import { join as join6 } from "path";
4281
+ function authPath(home) {
4282
+ return join6(home, ".config", "apes", "auth.json");
4283
+ }
4284
+ function readAgentIdentity(home = homedir6()) {
4285
+ const path = authPath(home);
4286
+ if (!existsSync3(path)) {
4287
+ throw new Error(`agent identity not found at ${path}`);
4288
+ }
4289
+ const raw = readFileSync4(path, "utf8");
4290
+ const parsed = JSON.parse(raw);
4291
+ if (!parsed.email) throw new Error(`auth.json at ${path} missing 'email'`);
4292
+ if (!parsed.idp) throw new Error(`auth.json at ${path} missing 'idp'`);
4293
+ const ownerEmail = parsed.owner_email ?? process.env.OPENAPE_OWNER_EMAIL;
4294
+ if (!ownerEmail) {
4295
+ throw new Error(
4296
+ `auth.json at ${path} missing 'owner_email' and no OPENAPE_OWNER_EMAIL env var set \u2014 re-spawn the agent with @openape/apes >= 0.28 or set OPENAPE_OWNER_EMAIL in the container env`
4297
+ );
4298
+ }
4299
+ return { email: parsed.email, ownerEmail, idp: parsed.idp };
4300
+ }
4301
+
4302
+ // src/llm-gateway-key.ts
4303
+ async function resolveLlmGatewayKey(base, fallback, log2, exchange = getAuthorizedBearer) {
4304
+ if (!base.includes("llms.openape.ai"))
4305
+ return fallback;
4306
+ try {
4307
+ const u3 = new URL(base);
4308
+ const bearer = await exchange({ endpoint: u3.origin, aud: u3.host });
4309
+ return bearer.replace(/^Bearer\s+/i, "");
4310
+ } catch (err) {
4311
+ log2(`llm gateway token exchange failed (keeping current key): ${err instanceof Error ? err.message : String(err)}`);
4312
+ return fallback;
4313
+ }
4314
+ }
4315
+
4316
+ // src/service-bridge.ts
4317
+ function textArtifact(text) {
4318
+ return { artifactId: randomUUID(), parts: [{ kind: "text", text }] };
4319
+ }
4320
+ function parseTaskSpec(task) {
4321
+ const dataPart = task.history[0]?.parts.find((p) => p.kind === "data");
4322
+ const data = dataPart?.data;
4323
+ if (!data || typeof data.systemPrompt !== "string" || typeof data.userMessage !== "string")
4324
+ throw new Error("task payload missing systemPrompt/userMessage");
4325
+ return {
4326
+ systemPrompt: data.systemPrompt,
4327
+ userMessage: data.userMessage,
4328
+ tools: Array.isArray(data.tools) ? data.tools.filter((t2) => typeof t2 === "string") : void 0,
4329
+ model: typeof data.model === "string" ? data.model : void 0,
4330
+ maxSteps: typeof data.maxSteps === "number" ? data.maxSteps : void 0
4331
+ };
4332
+ }
4333
+ async function getNextTask(deps) {
4334
+ const res = await deps.fetchImpl(`${deps.spBaseUrl}/api/agent/tasks/next`, {
4335
+ method: "POST",
4336
+ headers: { "authorization": await deps.bearer(), "content-type": "application/json" }
4337
+ });
4338
+ if (!res.ok)
4339
+ throw new Error(`GetNextTask HTTP ${res.status}`);
4340
+ const body = await res.json();
4341
+ return body.task ?? null;
4342
+ }
4343
+ async function resolveTask(deps, id, state, artifact) {
4344
+ const res = await deps.fetchImpl(`${deps.spBaseUrl}/api/agent/tasks/resolve`, {
4345
+ method: "POST",
4346
+ headers: { "authorization": await deps.bearer(), "content-type": "application/json" },
4347
+ body: JSON.stringify({ id, state, artifact })
4348
+ });
4349
+ if (!res.ok)
4350
+ throw new Error(`ResolveTask HTTP ${res.status}`);
4351
+ }
4352
+ async function pollOnce(deps) {
4353
+ const task = await getNextTask(deps);
4354
+ if (!task)
4355
+ return "idle";
4356
+ let state;
4357
+ let artifact;
4358
+ try {
4359
+ const spec = parseTaskSpec(task);
4360
+ const apiKey = deps.refreshApiKey ? await deps.refreshApiKey() : deps.config.apiKey;
4361
+ const config = { ...deps.config, apiKey, ...spec.model ? { model: spec.model } : {} };
4362
+ const result = await deps.runLoopImpl({
4363
+ config,
4364
+ userMessage: spec.userMessage,
4365
+ systemPrompt: spec.systemPrompt,
4366
+ tools: taskTools(spec.tools ?? []),
4367
+ maxSteps: spec.maxSteps ?? deps.maxSteps
4368
+ });
4369
+ if (result.status === "error")
4370
+ throw new Error(result.finalMessage ?? "runLoop returned status error");
4371
+ state = "completed";
4372
+ artifact = textArtifact(result.finalMessage ?? "");
4373
+ } catch (err) {
4374
+ const msg = err instanceof Error ? err.message : String(err);
4375
+ deps.log(`task ${task.id} failed: ${msg}`);
4376
+ state = "failed";
4377
+ artifact = textArtifact(msg);
4378
+ }
4379
+ await resolveTask(deps, task.id, state, artifact);
4380
+ return "task";
4381
+ }
4382
+ function readServiceConfig() {
4383
+ const spBaseUrl = process3.env.OPENAPE_SP_BASE_URL?.replace(/\/$/, "");
4384
+ if (!spBaseUrl)
4385
+ throw new Error("OPENAPE_SP_BASE_URL is not set \u2014 the SP backend this service-agent serves.");
4386
+ const apiKey = process3.env.LITELLM_API_KEY ?? process3.env.LITELLM_MASTER_KEY;
4387
+ if (!apiKey)
4388
+ throw new Error("LITELLM_API_KEY (or LITELLM_MASTER_KEY) must be set.");
4389
+ const model = process3.env.APE_SERVICE_MODEL;
4390
+ if (!model)
4391
+ throw new Error("APE_SERVICE_MODEL is not set (e.g. gpt-5.5).");
4392
+ const poll = process3.env.APE_SERVICE_POLL_MS ? Number.parseInt(process3.env.APE_SERVICE_POLL_MS, 10) : 2e3;
4393
+ const steps = process3.env.APE_SERVICE_MAX_STEPS ? Number.parseInt(process3.env.APE_SERVICE_MAX_STEPS, 10) : 10;
4394
+ return {
4395
+ spBaseUrl,
4396
+ apiBase: (process3.env.LITELLM_BASE_URL ?? "http://127.0.0.1:4001/v1").replace(/\/$/, ""),
4397
+ apiKey,
4398
+ model,
4399
+ pollIntervalMs: Number.isFinite(poll) && poll > 0 ? poll : 2e3,
4400
+ maxSteps: Number.isFinite(steps) && steps > 0 ? steps : 10
4401
+ };
4402
+ }
4403
+ function log(line) {
4404
+ process3.stderr.write(`${(/* @__PURE__ */ new Date()).toISOString()} [service] ${line}
4405
+ `);
4406
+ }
4407
+ function sleep(ms) {
4408
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
4409
+ }
4410
+ async function runService() {
4411
+ const cfg = readServiceConfig();
4412
+ const id = readAgentIdentity();
4413
+ const deps = {
4414
+ spBaseUrl: cfg.spBaseUrl,
4415
+ bearer: async () => `Bearer ${(await ensureFreshIdpAuth()).access_token}`,
4416
+ fetchImpl: fetch,
4417
+ runLoopImpl: runLoop,
4418
+ config: { apiBase: cfg.apiBase, apiKey: cfg.apiKey, model: cfg.model },
4419
+ refreshApiKey: () => resolveLlmGatewayKey(cfg.apiBase, cfg.apiKey, log),
4420
+ maxSteps: cfg.maxSteps,
4421
+ log
4422
+ };
4423
+ log(`service-agent ${id.email} \u2192 SP ${cfg.spBaseUrl}, LLM ${cfg.apiBase}, model ${cfg.model}, poll ${cfg.pollIntervalMs}ms`);
4424
+ for (; ; ) {
4425
+ try {
4426
+ if (await pollOnce(deps) === "idle")
4427
+ await sleep(cfg.pollIntervalMs);
4428
+ } catch (err) {
4429
+ log(`poll error: ${err instanceof Error ? err.message : String(err)}`);
4430
+ await sleep(cfg.pollIntervalMs);
4431
+ }
4432
+ }
4433
+ }
4434
+
4435
+ // src/service-bridge-main.ts
4436
+ runService().catch((err) => {
4437
+ process4.stderr.write(`fatal: ${err instanceof Error ? err.message : String(err)}
4438
+ `);
4439
+ process4.exit(1);
4440
+ });