create-expert 0.0.18 → 0.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/cli.js CHANGED
@@ -1,10 +1,4343 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync } from 'fs';
3
- import { parseWithFriendlyError, perstackConfigSchema } from '@perstack/core';
4
- import { startHandler } from '@perstack/tui';
5
- import { Command } from 'commander';
2
+ import { readFileSync, existsSync, mkdirSync, writeFileSync, readdirSync } from 'fs';
3
+ import { parseWithFriendlyError, perstackConfigSchema, startCommandInputSchema, defaultMaxRetries, defaultTimeout, checkpointSchema, jobSchema, runSettingSchema, BASE_SKILL_PREFIX, createBaseToolActivity, createGeneralToolActivity } from '@perstack/core';
4
+ import { readFile, mkdir, writeFile } from 'fs/promises';
5
+ import path5 from 'path';
6
+ import { findLockfile, loadLockfile, runtimeVersion, run } from '@perstack/runtime';
7
+ import { render, useApp, useInput, Box, Text } from 'ink';
8
+ import { createContext, useMemo, useReducer, useState, useEffect, useCallback, useRef, useInsertionEffect, useContext } from 'react';
9
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
10
+ import dotenv from 'dotenv';
6
11
  import TOML from 'smol-toml';
12
+ import { Command } from 'commander';
13
+
14
+ // ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/_u64.js
15
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
16
+ var _32n = /* @__PURE__ */ BigInt(32);
17
+ function fromBig(n, le = false) {
18
+ if (le)
19
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
20
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
21
+ }
22
+ function split(lst, le = false) {
23
+ const len = lst.length;
24
+ let Ah = new Uint32Array(len);
25
+ let Al = new Uint32Array(len);
26
+ for (let i = 0; i < len; i++) {
27
+ const { h, l } = fromBig(lst[i], le);
28
+ [Ah[i], Al[i]] = [h, l];
29
+ }
30
+ return [Ah, Al];
31
+ }
32
+ var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
33
+ var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
34
+ var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
35
+ var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
36
+
37
+ // ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/utils.js
38
+ function isBytes(a) {
39
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
40
+ }
41
+ function anumber(n, title = "") {
42
+ if (!Number.isSafeInteger(n) || n < 0) {
43
+ const prefix = title && `"${title}" `;
44
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
45
+ }
46
+ }
47
+ function abytes(value, length, title = "") {
48
+ const bytes = isBytes(value);
49
+ const len = value?.length;
50
+ const needsLen = length !== void 0;
51
+ if (!bytes || needsLen) {
52
+ const prefix = title && `"${title}" `;
53
+ const ofLen = "";
54
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
55
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
56
+ }
57
+ return value;
58
+ }
59
+ function aexists(instance, checkFinished = true) {
60
+ if (instance.destroyed)
61
+ throw new Error("Hash instance has been destroyed");
62
+ if (checkFinished && instance.finished)
63
+ throw new Error("Hash#digest() has already been called");
64
+ }
65
+ function aoutput(out, instance) {
66
+ abytes(out, void 0, "digestInto() output");
67
+ const min = instance.outputLen;
68
+ if (out.length < min) {
69
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
70
+ }
71
+ }
72
+ function u32(arr) {
73
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
74
+ }
75
+ function clean(...arrays) {
76
+ for (let i = 0; i < arrays.length; i++) {
77
+ arrays[i].fill(0);
78
+ }
79
+ }
80
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
81
+ function byteSwap(word) {
82
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
83
+ }
84
+ function byteSwap32(arr) {
85
+ for (let i = 0; i < arr.length; i++) {
86
+ arr[i] = byteSwap(arr[i]);
87
+ }
88
+ return arr;
89
+ }
90
+ var swap32IfBE = isLE ? (u) => u : byteSwap32;
91
+ function createHasher(hashCons, info = {}) {
92
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
93
+ const tmp = hashCons(void 0);
94
+ hashC.outputLen = tmp.outputLen;
95
+ hashC.blockLen = tmp.blockLen;
96
+ hashC.create = (opts) => hashCons(opts);
97
+ Object.assign(hashC, info);
98
+ return Object.freeze(hashC);
99
+ }
100
+ var oidNist = (suffix) => ({
101
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
102
+ });
103
+
104
+ // ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/sha3.js
105
+ var _0n = BigInt(0);
106
+ var _1n = BigInt(1);
107
+ var _2n = BigInt(2);
108
+ var _7n = BigInt(7);
109
+ var _256n = BigInt(256);
110
+ var _0x71n = BigInt(113);
111
+ var SHA3_PI = [];
112
+ var SHA3_ROTL = [];
113
+ var _SHA3_IOTA = [];
114
+ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
115
+ [x, y] = [y, (2 * x + 3 * y) % 5];
116
+ SHA3_PI.push(2 * (5 * y + x));
117
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
118
+ let t = _0n;
119
+ for (let j = 0; j < 7; j++) {
120
+ R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
121
+ if (R & _2n)
122
+ t ^= _1n << (_1n << BigInt(j)) - _1n;
123
+ }
124
+ _SHA3_IOTA.push(t);
125
+ }
126
+ var IOTAS = split(_SHA3_IOTA, true);
127
+ var SHA3_IOTA_H = IOTAS[0];
128
+ var SHA3_IOTA_L = IOTAS[1];
129
+ var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
130
+ var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
131
+ function keccakP(s, rounds = 24) {
132
+ const B = new Uint32Array(5 * 2);
133
+ for (let round = 24 - rounds; round < 24; round++) {
134
+ for (let x = 0; x < 10; x++)
135
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
136
+ for (let x = 0; x < 10; x += 2) {
137
+ const idx1 = (x + 8) % 10;
138
+ const idx0 = (x + 2) % 10;
139
+ const B0 = B[idx0];
140
+ const B1 = B[idx0 + 1];
141
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
142
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
143
+ for (let y = 0; y < 50; y += 10) {
144
+ s[x + y] ^= Th;
145
+ s[x + y + 1] ^= Tl;
146
+ }
147
+ }
148
+ let curH = s[2];
149
+ let curL = s[3];
150
+ for (let t = 0; t < 24; t++) {
151
+ const shift = SHA3_ROTL[t];
152
+ const Th = rotlH(curH, curL, shift);
153
+ const Tl = rotlL(curH, curL, shift);
154
+ const PI = SHA3_PI[t];
155
+ curH = s[PI];
156
+ curL = s[PI + 1];
157
+ s[PI] = Th;
158
+ s[PI + 1] = Tl;
159
+ }
160
+ for (let y = 0; y < 50; y += 10) {
161
+ for (let x = 0; x < 10; x++)
162
+ B[x] = s[y + x];
163
+ for (let x = 0; x < 10; x++)
164
+ s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
165
+ }
166
+ s[0] ^= SHA3_IOTA_H[round];
167
+ s[1] ^= SHA3_IOTA_L[round];
168
+ }
169
+ clean(B);
170
+ }
171
+ var Keccak = class _Keccak {
172
+ state;
173
+ pos = 0;
174
+ posOut = 0;
175
+ finished = false;
176
+ state32;
177
+ destroyed = false;
178
+ blockLen;
179
+ suffix;
180
+ outputLen;
181
+ enableXOF = false;
182
+ rounds;
183
+ // NOTE: we accept arguments in bytes instead of bits here.
184
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
185
+ this.blockLen = blockLen;
186
+ this.suffix = suffix;
187
+ this.outputLen = outputLen;
188
+ this.enableXOF = enableXOF;
189
+ this.rounds = rounds;
190
+ anumber(outputLen, "outputLen");
191
+ if (!(0 < blockLen && blockLen < 200))
192
+ throw new Error("only keccak-f1600 function is supported");
193
+ this.state = new Uint8Array(200);
194
+ this.state32 = u32(this.state);
195
+ }
196
+ clone() {
197
+ return this._cloneInto();
198
+ }
199
+ keccak() {
200
+ swap32IfBE(this.state32);
201
+ keccakP(this.state32, this.rounds);
202
+ swap32IfBE(this.state32);
203
+ this.posOut = 0;
204
+ this.pos = 0;
205
+ }
206
+ update(data) {
207
+ aexists(this);
208
+ abytes(data);
209
+ const { blockLen, state } = this;
210
+ const len = data.length;
211
+ for (let pos = 0; pos < len; ) {
212
+ const take = Math.min(blockLen - this.pos, len - pos);
213
+ for (let i = 0; i < take; i++)
214
+ state[this.pos++] ^= data[pos++];
215
+ if (this.pos === blockLen)
216
+ this.keccak();
217
+ }
218
+ return this;
219
+ }
220
+ finish() {
221
+ if (this.finished)
222
+ return;
223
+ this.finished = true;
224
+ const { state, suffix, pos, blockLen } = this;
225
+ state[pos] ^= suffix;
226
+ if ((suffix & 128) !== 0 && pos === blockLen - 1)
227
+ this.keccak();
228
+ state[blockLen - 1] ^= 128;
229
+ this.keccak();
230
+ }
231
+ writeInto(out) {
232
+ aexists(this, false);
233
+ abytes(out);
234
+ this.finish();
235
+ const bufferOut = this.state;
236
+ const { blockLen } = this;
237
+ for (let pos = 0, len = out.length; pos < len; ) {
238
+ if (this.posOut >= blockLen)
239
+ this.keccak();
240
+ const take = Math.min(blockLen - this.posOut, len - pos);
241
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
242
+ this.posOut += take;
243
+ pos += take;
244
+ }
245
+ return out;
246
+ }
247
+ xofInto(out) {
248
+ if (!this.enableXOF)
249
+ throw new Error("XOF is not possible for this instance");
250
+ return this.writeInto(out);
251
+ }
252
+ xof(bytes) {
253
+ anumber(bytes);
254
+ return this.xofInto(new Uint8Array(bytes));
255
+ }
256
+ digestInto(out) {
257
+ aoutput(out, this);
258
+ if (this.finished)
259
+ throw new Error("digest() was already called");
260
+ this.writeInto(out);
261
+ this.destroy();
262
+ return out;
263
+ }
264
+ digest() {
265
+ return this.digestInto(new Uint8Array(this.outputLen));
266
+ }
267
+ destroy() {
268
+ this.destroyed = true;
269
+ clean(this.state);
270
+ }
271
+ _cloneInto(to) {
272
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
273
+ to ||= new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds);
274
+ to.state32.set(this.state32);
275
+ to.pos = this.pos;
276
+ to.posOut = this.posOut;
277
+ to.finished = this.finished;
278
+ to.rounds = rounds;
279
+ to.suffix = suffix;
280
+ to.outputLen = outputLen;
281
+ to.enableXOF = enableXOF;
282
+ to.destroyed = this.destroyed;
283
+ return to;
284
+ }
285
+ };
286
+ var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
287
+ var sha3_512 = /* @__PURE__ */ genKeccak(
288
+ 6,
289
+ 72,
290
+ 64,
291
+ /* @__PURE__ */ oidNist(10)
292
+ );
293
+
294
+ // ../../node_modules/.pnpm/bignumber.js@9.3.1/node_modules/bignumber.js/bignumber.mjs
295
+ var isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
296
+ var mathceil = Math.ceil;
297
+ var mathfloor = Math.floor;
298
+ var bignumberError = "[BigNumber Error] ";
299
+ var tooManyDigits = bignumberError + "Number primitive has more than 15 significant digits: ";
300
+ var BASE = 1e14;
301
+ var LOG_BASE = 14;
302
+ var MAX_SAFE_INTEGER = 9007199254740991;
303
+ var POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13];
304
+ var SQRT_BASE = 1e7;
305
+ var MAX = 1e9;
306
+ function clone(configObject) {
307
+ var div, convertBase, parseNumeric, P = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = {
308
+ prefix: "",
309
+ groupSize: 3,
310
+ secondaryGroupSize: 0,
311
+ groupSeparator: ",",
312
+ decimalSeparator: ".",
313
+ fractionGroupSize: 0,
314
+ fractionGroupSeparator: "\xA0",
315
+ // non-breaking space
316
+ suffix: ""
317
+ }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true;
318
+ function BigNumber2(v, b) {
319
+ var alphabet2, c, caseChanged, e, i, isNum, len, str, x = this;
320
+ if (!(x instanceof BigNumber2)) return new BigNumber2(v, b);
321
+ if (b == null) {
322
+ if (v && v._isBigNumber === true) {
323
+ x.s = v.s;
324
+ if (!v.c || v.e > MAX_EXP) {
325
+ x.c = x.e = null;
326
+ } else if (v.e < MIN_EXP) {
327
+ x.c = [x.e = 0];
328
+ } else {
329
+ x.e = v.e;
330
+ x.c = v.c.slice();
331
+ }
332
+ return;
333
+ }
334
+ if ((isNum = typeof v == "number") && v * 0 == 0) {
335
+ x.s = 1 / v < 0 ? (v = -v, -1) : 1;
336
+ if (v === ~~v) {
337
+ for (e = 0, i = v; i >= 10; i /= 10, e++) ;
338
+ if (e > MAX_EXP) {
339
+ x.c = x.e = null;
340
+ } else {
341
+ x.e = e;
342
+ x.c = [v];
343
+ }
344
+ return;
345
+ }
346
+ str = String(v);
347
+ } else {
348
+ if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);
349
+ x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;
350
+ }
351
+ if ((e = str.indexOf(".")) > -1) str = str.replace(".", "");
352
+ if ((i = str.search(/e/i)) > 0) {
353
+ if (e < 0) e = i;
354
+ e += +str.slice(i + 1);
355
+ str = str.substring(0, i);
356
+ } else if (e < 0) {
357
+ e = str.length;
358
+ }
359
+ } else {
360
+ intCheck(b, 2, ALPHABET.length, "Base");
361
+ if (b == 10 && alphabetHasNormalDecimalDigits) {
362
+ x = new BigNumber2(v);
363
+ return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);
364
+ }
365
+ str = String(v);
366
+ if (isNum = typeof v == "number") {
367
+ if (v * 0 != 0) return parseNumeric(x, str, isNum, b);
368
+ x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;
369
+ if (BigNumber2.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) {
370
+ throw Error(tooManyDigits + v);
371
+ }
372
+ } else {
373
+ x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;
374
+ }
375
+ alphabet2 = ALPHABET.slice(0, b);
376
+ e = i = 0;
377
+ for (len = str.length; i < len; i++) {
378
+ if (alphabet2.indexOf(c = str.charAt(i)) < 0) {
379
+ if (c == ".") {
380
+ if (i > e) {
381
+ e = len;
382
+ continue;
383
+ }
384
+ } else if (!caseChanged) {
385
+ if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) {
386
+ caseChanged = true;
387
+ i = -1;
388
+ e = 0;
389
+ continue;
390
+ }
391
+ }
392
+ return parseNumeric(x, String(v), isNum, b);
393
+ }
394
+ }
395
+ isNum = false;
396
+ str = convertBase(str, b, 10, x.s);
397
+ if ((e = str.indexOf(".")) > -1) str = str.replace(".", "");
398
+ else e = str.length;
399
+ }
400
+ for (i = 0; str.charCodeAt(i) === 48; i++) ;
401
+ for (len = str.length; str.charCodeAt(--len) === 48; ) ;
402
+ if (str = str.slice(i, ++len)) {
403
+ len -= i;
404
+ if (isNum && BigNumber2.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {
405
+ throw Error(tooManyDigits + x.s * v);
406
+ }
407
+ if ((e = e - i - 1) > MAX_EXP) {
408
+ x.c = x.e = null;
409
+ } else if (e < MIN_EXP) {
410
+ x.c = [x.e = 0];
411
+ } else {
412
+ x.e = e;
413
+ x.c = [];
414
+ i = (e + 1) % LOG_BASE;
415
+ if (e < 0) i += LOG_BASE;
416
+ if (i < len) {
417
+ if (i) x.c.push(+str.slice(0, i));
418
+ for (len -= LOG_BASE; i < len; ) {
419
+ x.c.push(+str.slice(i, i += LOG_BASE));
420
+ }
421
+ i = LOG_BASE - (str = str.slice(i)).length;
422
+ } else {
423
+ i -= len;
424
+ }
425
+ for (; i--; str += "0") ;
426
+ x.c.push(+str);
427
+ }
428
+ } else {
429
+ x.c = [x.e = 0];
430
+ }
431
+ }
432
+ BigNumber2.clone = clone;
433
+ BigNumber2.ROUND_UP = 0;
434
+ BigNumber2.ROUND_DOWN = 1;
435
+ BigNumber2.ROUND_CEIL = 2;
436
+ BigNumber2.ROUND_FLOOR = 3;
437
+ BigNumber2.ROUND_HALF_UP = 4;
438
+ BigNumber2.ROUND_HALF_DOWN = 5;
439
+ BigNumber2.ROUND_HALF_EVEN = 6;
440
+ BigNumber2.ROUND_HALF_CEIL = 7;
441
+ BigNumber2.ROUND_HALF_FLOOR = 8;
442
+ BigNumber2.EUCLID = 9;
443
+ BigNumber2.config = BigNumber2.set = function(obj) {
444
+ var p, v;
445
+ if (obj != null) {
446
+ if (typeof obj == "object") {
447
+ if (obj.hasOwnProperty(p = "DECIMAL_PLACES")) {
448
+ v = obj[p];
449
+ intCheck(v, 0, MAX, p);
450
+ DECIMAL_PLACES = v;
451
+ }
452
+ if (obj.hasOwnProperty(p = "ROUNDING_MODE")) {
453
+ v = obj[p];
454
+ intCheck(v, 0, 8, p);
455
+ ROUNDING_MODE = v;
456
+ }
457
+ if (obj.hasOwnProperty(p = "EXPONENTIAL_AT")) {
458
+ v = obj[p];
459
+ if (v && v.pop) {
460
+ intCheck(v[0], -MAX, 0, p);
461
+ intCheck(v[1], 0, MAX, p);
462
+ TO_EXP_NEG = v[0];
463
+ TO_EXP_POS = v[1];
464
+ } else {
465
+ intCheck(v, -MAX, MAX, p);
466
+ TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);
467
+ }
468
+ }
469
+ if (obj.hasOwnProperty(p = "RANGE")) {
470
+ v = obj[p];
471
+ if (v && v.pop) {
472
+ intCheck(v[0], -MAX, -1, p);
473
+ intCheck(v[1], 1, MAX, p);
474
+ MIN_EXP = v[0];
475
+ MAX_EXP = v[1];
476
+ } else {
477
+ intCheck(v, -MAX, MAX, p);
478
+ if (v) {
479
+ MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);
480
+ } else {
481
+ throw Error(bignumberError + p + " cannot be zero: " + v);
482
+ }
483
+ }
484
+ }
485
+ if (obj.hasOwnProperty(p = "CRYPTO")) {
486
+ v = obj[p];
487
+ if (v === !!v) {
488
+ if (v) {
489
+ if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
490
+ CRYPTO = v;
491
+ } else {
492
+ CRYPTO = !v;
493
+ throw Error(bignumberError + "crypto unavailable");
494
+ }
495
+ } else {
496
+ CRYPTO = v;
497
+ }
498
+ } else {
499
+ throw Error(bignumberError + p + " not true or false: " + v);
500
+ }
501
+ }
502
+ if (obj.hasOwnProperty(p = "MODULO_MODE")) {
503
+ v = obj[p];
504
+ intCheck(v, 0, 9, p);
505
+ MODULO_MODE = v;
506
+ }
507
+ if (obj.hasOwnProperty(p = "POW_PRECISION")) {
508
+ v = obj[p];
509
+ intCheck(v, 0, MAX, p);
510
+ POW_PRECISION = v;
511
+ }
512
+ if (obj.hasOwnProperty(p = "FORMAT")) {
513
+ v = obj[p];
514
+ if (typeof v == "object") FORMAT = v;
515
+ else throw Error(bignumberError + p + " not an object: " + v);
516
+ }
517
+ if (obj.hasOwnProperty(p = "ALPHABET")) {
518
+ v = obj[p];
519
+ if (typeof v == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) {
520
+ alphabetHasNormalDecimalDigits = v.slice(0, 10) == "0123456789";
521
+ ALPHABET = v;
522
+ } else {
523
+ throw Error(bignumberError + p + " invalid: " + v);
524
+ }
525
+ }
526
+ } else {
527
+ throw Error(bignumberError + "Object expected: " + obj);
528
+ }
529
+ }
530
+ return {
531
+ DECIMAL_PLACES,
532
+ ROUNDING_MODE,
533
+ EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],
534
+ RANGE: [MIN_EXP, MAX_EXP],
535
+ CRYPTO,
536
+ MODULO_MODE,
537
+ POW_PRECISION,
538
+ FORMAT,
539
+ ALPHABET
540
+ };
541
+ };
542
+ BigNumber2.isBigNumber = function(v) {
543
+ if (!v || v._isBigNumber !== true) return false;
544
+ if (!BigNumber2.DEBUG) return true;
545
+ var i, n, c = v.c, e = v.e, s = v.s;
546
+ out: if ({}.toString.call(c) == "[object Array]") {
547
+ if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {
548
+ if (c[0] === 0) {
549
+ if (e === 0 && c.length === 1) return true;
550
+ break out;
551
+ }
552
+ i = (e + 1) % LOG_BASE;
553
+ if (i < 1) i += LOG_BASE;
554
+ if (String(c[0]).length == i) {
555
+ for (i = 0; i < c.length; i++) {
556
+ n = c[i];
557
+ if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;
558
+ }
559
+ if (n !== 0) return true;
560
+ }
561
+ }
562
+ } else if (c === null && e === null && (s === null || s === 1 || s === -1)) {
563
+ return true;
564
+ }
565
+ throw Error(bignumberError + "Invalid BigNumber: " + v);
566
+ };
567
+ BigNumber2.maximum = BigNumber2.max = function() {
568
+ return maxOrMin(arguments, -1);
569
+ };
570
+ BigNumber2.minimum = BigNumber2.min = function() {
571
+ return maxOrMin(arguments, 1);
572
+ };
573
+ BigNumber2.random = (function() {
574
+ var pow2_53 = 9007199254740992;
575
+ var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() {
576
+ return mathfloor(Math.random() * pow2_53);
577
+ } : function() {
578
+ return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0);
579
+ };
580
+ return function(dp) {
581
+ var a, b, e, k, v, i = 0, c = [], rand = new BigNumber2(ONE);
582
+ if (dp == null) dp = DECIMAL_PLACES;
583
+ else intCheck(dp, 0, MAX);
584
+ k = mathceil(dp / LOG_BASE);
585
+ if (CRYPTO) {
586
+ if (crypto.getRandomValues) {
587
+ a = crypto.getRandomValues(new Uint32Array(k *= 2));
588
+ for (; i < k; ) {
589
+ v = a[i] * 131072 + (a[i + 1] >>> 11);
590
+ if (v >= 9e15) {
591
+ b = crypto.getRandomValues(new Uint32Array(2));
592
+ a[i] = b[0];
593
+ a[i + 1] = b[1];
594
+ } else {
595
+ c.push(v % 1e14);
596
+ i += 2;
597
+ }
598
+ }
599
+ i = k / 2;
600
+ } else if (crypto.randomBytes) {
601
+ a = crypto.randomBytes(k *= 7);
602
+ for (; i < k; ) {
603
+ v = (a[i] & 31) * 281474976710656 + a[i + 1] * 1099511627776 + a[i + 2] * 4294967296 + a[i + 3] * 16777216 + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];
604
+ if (v >= 9e15) {
605
+ crypto.randomBytes(7).copy(a, i);
606
+ } else {
607
+ c.push(v % 1e14);
608
+ i += 7;
609
+ }
610
+ }
611
+ i = k / 7;
612
+ } else {
613
+ CRYPTO = false;
614
+ throw Error(bignumberError + "crypto unavailable");
615
+ }
616
+ }
617
+ if (!CRYPTO) {
618
+ for (; i < k; ) {
619
+ v = random53bitInt();
620
+ if (v < 9e15) c[i++] = v % 1e14;
621
+ }
622
+ }
623
+ k = c[--i];
624
+ dp %= LOG_BASE;
625
+ if (k && dp) {
626
+ v = POWS_TEN[LOG_BASE - dp];
627
+ c[i] = mathfloor(k / v) * v;
628
+ }
629
+ for (; c[i] === 0; c.pop(), i--) ;
630
+ if (i < 0) {
631
+ c = [e = 0];
632
+ } else {
633
+ for (e = -1; c[0] === 0; c.splice(0, 1), e -= LOG_BASE) ;
634
+ for (i = 1, v = c[0]; v >= 10; v /= 10, i++) ;
635
+ if (i < LOG_BASE) e -= LOG_BASE - i;
636
+ }
637
+ rand.e = e;
638
+ rand.c = c;
639
+ return rand;
640
+ };
641
+ })();
642
+ BigNumber2.sum = function() {
643
+ var i = 1, args = arguments, sum = new BigNumber2(args[0]);
644
+ for (; i < args.length; ) sum = sum.plus(args[i++]);
645
+ return sum;
646
+ };
647
+ convertBase = /* @__PURE__ */ (function() {
648
+ var decimal = "0123456789";
649
+ function toBaseOut(str, baseIn, baseOut, alphabet2) {
650
+ var j, arr = [0], arrL, i = 0, len = str.length;
651
+ for (; i < len; ) {
652
+ for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) ;
653
+ arr[0] += alphabet2.indexOf(str.charAt(i++));
654
+ for (j = 0; j < arr.length; j++) {
655
+ if (arr[j] > baseOut - 1) {
656
+ if (arr[j + 1] == null) arr[j + 1] = 0;
657
+ arr[j + 1] += arr[j] / baseOut | 0;
658
+ arr[j] %= baseOut;
659
+ }
660
+ }
661
+ }
662
+ return arr.reverse();
663
+ }
664
+ return function(str, baseIn, baseOut, sign, callerIsToString) {
665
+ var alphabet2, d, e, k, r, x, xc, y, i = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE;
666
+ if (i >= 0) {
667
+ k = POW_PRECISION;
668
+ POW_PRECISION = 0;
669
+ str = str.replace(".", "");
670
+ y = new BigNumber2(baseIn);
671
+ x = y.pow(str.length - i);
672
+ POW_PRECISION = k;
673
+ y.c = toBaseOut(
674
+ toFixedPoint(coeffToString(x.c), x.e, "0"),
675
+ 10,
676
+ baseOut,
677
+ decimal
678
+ );
679
+ y.e = y.c.length;
680
+ }
681
+ xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET));
682
+ e = k = xc.length;
683
+ for (; xc[--k] == 0; xc.pop()) ;
684
+ if (!xc[0]) return alphabet2.charAt(0);
685
+ if (i < 0) {
686
+ --e;
687
+ } else {
688
+ x.c = xc;
689
+ x.e = e;
690
+ x.s = sign;
691
+ x = div(x, y, dp, rm, baseOut);
692
+ xc = x.c;
693
+ r = x.r;
694
+ e = x.e;
695
+ }
696
+ d = e + dp + 1;
697
+ i = xc[d];
698
+ k = baseOut / 2;
699
+ r = r || d < 0 || xc[d + 1] != null;
700
+ r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k && (rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7));
701
+ if (d < 1 || !xc[0]) {
702
+ str = r ? toFixedPoint(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0);
703
+ } else {
704
+ xc.length = d;
705
+ if (r) {
706
+ for (--baseOut; ++xc[--d] > baseOut; ) {
707
+ xc[d] = 0;
708
+ if (!d) {
709
+ ++e;
710
+ xc = [1].concat(xc);
711
+ }
712
+ }
713
+ }
714
+ for (k = xc.length; !xc[--k]; ) ;
715
+ for (i = 0, str = ""; i <= k; str += alphabet2.charAt(xc[i++])) ;
716
+ str = toFixedPoint(str, e, alphabet2.charAt(0));
717
+ }
718
+ return str;
719
+ };
720
+ })();
721
+ div = /* @__PURE__ */ (function() {
722
+ function multiply(x, k, base) {
723
+ var m, temp, xlo, xhi, carry = 0, i = x.length, klo = k % SQRT_BASE, khi = k / SQRT_BASE | 0;
724
+ for (x = x.slice(); i--; ) {
725
+ xlo = x[i] % SQRT_BASE;
726
+ xhi = x[i] / SQRT_BASE | 0;
727
+ m = khi * xlo + xhi * klo;
728
+ temp = klo * xlo + m % SQRT_BASE * SQRT_BASE + carry;
729
+ carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;
730
+ x[i] = temp % base;
731
+ }
732
+ if (carry) x = [carry].concat(x);
733
+ return x;
734
+ }
735
+ function compare2(a, b, aL, bL) {
736
+ var i, cmp;
737
+ if (aL != bL) {
738
+ cmp = aL > bL ? 1 : -1;
739
+ } else {
740
+ for (i = cmp = 0; i < aL; i++) {
741
+ if (a[i] != b[i]) {
742
+ cmp = a[i] > b[i] ? 1 : -1;
743
+ break;
744
+ }
745
+ }
746
+ }
747
+ return cmp;
748
+ }
749
+ function subtract(a, b, aL, base) {
750
+ var i = 0;
751
+ for (; aL--; ) {
752
+ a[aL] -= i;
753
+ i = a[aL] < b[aL] ? 1 : 0;
754
+ a[aL] = i * base + a[aL] - b[aL];
755
+ }
756
+ for (; !a[0] && a.length > 1; a.splice(0, 1)) ;
757
+ }
758
+ return function(x, y, dp, rm, base) {
759
+ var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s = x.s == y.s ? 1 : -1, xc = x.c, yc = y.c;
760
+ if (!xc || !xc[0] || !yc || !yc[0]) {
761
+ return new BigNumber2(
762
+ // Return NaN if either NaN, or both Infinity or 0.
763
+ !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : (
764
+ // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
765
+ xc && xc[0] == 0 || !yc ? s * 0 : s / 0
766
+ )
767
+ );
768
+ }
769
+ q = new BigNumber2(s);
770
+ qc = q.c = [];
771
+ e = x.e - y.e;
772
+ s = dp + e + 1;
773
+ if (!base) {
774
+ base = BASE;
775
+ e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);
776
+ s = s / LOG_BASE | 0;
777
+ }
778
+ for (i = 0; yc[i] == (xc[i] || 0); i++) ;
779
+ if (yc[i] > (xc[i] || 0)) e--;
780
+ if (s < 0) {
781
+ qc.push(1);
782
+ more = true;
783
+ } else {
784
+ xL = xc.length;
785
+ yL = yc.length;
786
+ i = 0;
787
+ s += 2;
788
+ n = mathfloor(base / (yc[0] + 1));
789
+ if (n > 1) {
790
+ yc = multiply(yc, n, base);
791
+ xc = multiply(xc, n, base);
792
+ yL = yc.length;
793
+ xL = xc.length;
794
+ }
795
+ xi = yL;
796
+ rem = xc.slice(0, yL);
797
+ remL = rem.length;
798
+ for (; remL < yL; rem[remL++] = 0) ;
799
+ yz = yc.slice();
800
+ yz = [0].concat(yz);
801
+ yc0 = yc[0];
802
+ if (yc[1] >= base / 2) yc0++;
803
+ do {
804
+ n = 0;
805
+ cmp = compare2(yc, rem, yL, remL);
806
+ if (cmp < 0) {
807
+ rem0 = rem[0];
808
+ if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
809
+ n = mathfloor(rem0 / yc0);
810
+ if (n > 1) {
811
+ if (n >= base) n = base - 1;
812
+ prod = multiply(yc, n, base);
813
+ prodL = prod.length;
814
+ remL = rem.length;
815
+ while (compare2(prod, rem, prodL, remL) == 1) {
816
+ n--;
817
+ subtract(prod, yL < prodL ? yz : yc, prodL, base);
818
+ prodL = prod.length;
819
+ cmp = 1;
820
+ }
821
+ } else {
822
+ if (n == 0) {
823
+ cmp = n = 1;
824
+ }
825
+ prod = yc.slice();
826
+ prodL = prod.length;
827
+ }
828
+ if (prodL < remL) prod = [0].concat(prod);
829
+ subtract(rem, prod, remL, base);
830
+ remL = rem.length;
831
+ if (cmp == -1) {
832
+ while (compare2(yc, rem, yL, remL) < 1) {
833
+ n++;
834
+ subtract(rem, yL < remL ? yz : yc, remL, base);
835
+ remL = rem.length;
836
+ }
837
+ }
838
+ } else if (cmp === 0) {
839
+ n++;
840
+ rem = [0];
841
+ }
842
+ qc[i++] = n;
843
+ if (rem[0]) {
844
+ rem[remL++] = xc[xi] || 0;
845
+ } else {
846
+ rem = [xc[xi]];
847
+ remL = 1;
848
+ }
849
+ } while ((xi++ < xL || rem[0] != null) && s--);
850
+ more = rem[0] != null;
851
+ if (!qc[0]) qc.splice(0, 1);
852
+ }
853
+ if (base == BASE) {
854
+ for (i = 1, s = qc[0]; s >= 10; s /= 10, i++) ;
855
+ round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);
856
+ } else {
857
+ q.e = e;
858
+ q.r = +more;
859
+ }
860
+ return q;
861
+ };
862
+ })();
863
+ function format(n, i, rm, id) {
864
+ var c0, e, ne, len, str;
865
+ if (rm == null) rm = ROUNDING_MODE;
866
+ else intCheck(rm, 0, 8);
867
+ if (!n.c) return n.toString();
868
+ c0 = n.c[0];
869
+ ne = n.e;
870
+ if (i == null) {
871
+ str = coeffToString(n.c);
872
+ str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential(str, ne) : toFixedPoint(str, ne, "0");
873
+ } else {
874
+ n = round(new BigNumber2(n), i, rm);
875
+ e = n.e;
876
+ str = coeffToString(n.c);
877
+ len = str.length;
878
+ if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {
879
+ for (; len < i; str += "0", len++) ;
880
+ str = toExponential(str, e);
881
+ } else {
882
+ i -= ne + (id === 2 && e > ne);
883
+ str = toFixedPoint(str, e, "0");
884
+ if (e + 1 > len) {
885
+ if (--i > 0) for (str += "."; i--; str += "0") ;
886
+ } else {
887
+ i += e - len;
888
+ if (i > 0) {
889
+ if (e + 1 == len) str += ".";
890
+ for (; i--; str += "0") ;
891
+ }
892
+ }
893
+ }
894
+ }
895
+ return n.s < 0 && c0 ? "-" + str : str;
896
+ }
897
+ function maxOrMin(args, n) {
898
+ var k, y, i = 1, x = new BigNumber2(args[0]);
899
+ for (; i < args.length; i++) {
900
+ y = new BigNumber2(args[i]);
901
+ if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) {
902
+ x = y;
903
+ }
904
+ }
905
+ return x;
906
+ }
907
+ function normalise(n, c, e) {
908
+ var i = 1, j = c.length;
909
+ for (; !c[--j]; c.pop()) ;
910
+ for (j = c[0]; j >= 10; j /= 10, i++) ;
911
+ if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {
912
+ n.c = n.e = null;
913
+ } else if (e < MIN_EXP) {
914
+ n.c = [n.e = 0];
915
+ } else {
916
+ n.e = e;
917
+ n.c = c;
918
+ }
919
+ return n;
920
+ }
921
+ parseNumeric = /* @__PURE__ */ (function() {
922
+ var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
923
+ return function(x, str, isNum, b) {
924
+ var base, s = isNum ? str : str.replace(whitespaceOrPlus, "");
925
+ if (isInfinityOrNaN.test(s)) {
926
+ x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
927
+ } else {
928
+ if (!isNum) {
929
+ s = s.replace(basePrefix, function(m, p1, p2) {
930
+ base = (p2 = p2.toLowerCase()) == "x" ? 16 : p2 == "b" ? 2 : 8;
931
+ return !b || b == base ? p1 : m;
932
+ });
933
+ if (b) {
934
+ base = b;
935
+ s = s.replace(dotAfter, "$1").replace(dotBefore, "0.$1");
936
+ }
937
+ if (str != s) return new BigNumber2(s, base);
938
+ }
939
+ if (BigNumber2.DEBUG) {
940
+ throw Error(bignumberError + "Not a" + (b ? " base " + b : "") + " number: " + str);
941
+ }
942
+ x.s = null;
943
+ }
944
+ x.c = x.e = null;
945
+ };
946
+ })();
947
+ function round(x, sd, rm, r) {
948
+ var d, i, j, k, n, ni, rd, xc = x.c, pows10 = POWS_TEN;
949
+ if (xc) {
950
+ out: {
951
+ for (d = 1, k = xc[0]; k >= 10; k /= 10, d++) ;
952
+ i = sd - d;
953
+ if (i < 0) {
954
+ i += LOG_BASE;
955
+ j = sd;
956
+ n = xc[ni = 0];
957
+ rd = mathfloor(n / pows10[d - j - 1] % 10);
958
+ } else {
959
+ ni = mathceil((i + 1) / LOG_BASE);
960
+ if (ni >= xc.length) {
961
+ if (r) {
962
+ for (; xc.length <= ni; xc.push(0)) ;
963
+ n = rd = 0;
964
+ d = 1;
965
+ i %= LOG_BASE;
966
+ j = i - LOG_BASE + 1;
967
+ } else {
968
+ break out;
969
+ }
970
+ } else {
971
+ n = k = xc[ni];
972
+ for (d = 1; k >= 10; k /= 10, d++) ;
973
+ i %= LOG_BASE;
974
+ j = i - LOG_BASE + d;
975
+ rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10);
976
+ }
977
+ }
978
+ r = r || sd < 0 || // Are there any non-zero digits after the rounding digit?
979
+ // The expression n % pows10[d - j - 1] returns all digits of n to the right
980
+ // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
981
+ xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);
982
+ r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd.
983
+ (i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x.s < 0 ? 8 : 7));
984
+ if (sd < 1 || !xc[0]) {
985
+ xc.length = 0;
986
+ if (r) {
987
+ sd -= x.e + 1;
988
+ xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];
989
+ x.e = -sd || 0;
990
+ } else {
991
+ xc[0] = x.e = 0;
992
+ }
993
+ return x;
994
+ }
995
+ if (i == 0) {
996
+ xc.length = ni;
997
+ k = 1;
998
+ ni--;
999
+ } else {
1000
+ xc.length = ni + 1;
1001
+ k = pows10[LOG_BASE - i];
1002
+ xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;
1003
+ }
1004
+ if (r) {
1005
+ for (; ; ) {
1006
+ if (ni == 0) {
1007
+ for (i = 1, j = xc[0]; j >= 10; j /= 10, i++) ;
1008
+ j = xc[0] += k;
1009
+ for (k = 1; j >= 10; j /= 10, k++) ;
1010
+ if (i != k) {
1011
+ x.e++;
1012
+ if (xc[0] == BASE) xc[0] = 1;
1013
+ }
1014
+ break;
1015
+ } else {
1016
+ xc[ni] += k;
1017
+ if (xc[ni] != BASE) break;
1018
+ xc[ni--] = 0;
1019
+ k = 1;
1020
+ }
1021
+ }
1022
+ }
1023
+ for (i = xc.length; xc[--i] === 0; xc.pop()) ;
1024
+ }
1025
+ if (x.e > MAX_EXP) {
1026
+ x.c = x.e = null;
1027
+ } else if (x.e < MIN_EXP) {
1028
+ x.c = [x.e = 0];
1029
+ }
1030
+ }
1031
+ return x;
1032
+ }
1033
+ function valueOf(n) {
1034
+ var str, e = n.e;
1035
+ if (e === null) return n.toString();
1036
+ str = coeffToString(n.c);
1037
+ str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(str, e) : toFixedPoint(str, e, "0");
1038
+ return n.s < 0 ? "-" + str : str;
1039
+ }
1040
+ P.absoluteValue = P.abs = function() {
1041
+ var x = new BigNumber2(this);
1042
+ if (x.s < 0) x.s = 1;
1043
+ return x;
1044
+ };
1045
+ P.comparedTo = function(y, b) {
1046
+ return compare(this, new BigNumber2(y, b));
1047
+ };
1048
+ P.decimalPlaces = P.dp = function(dp, rm) {
1049
+ var c, n, v, x = this;
1050
+ if (dp != null) {
1051
+ intCheck(dp, 0, MAX);
1052
+ if (rm == null) rm = ROUNDING_MODE;
1053
+ else intCheck(rm, 0, 8);
1054
+ return round(new BigNumber2(x), dp + x.e + 1, rm);
1055
+ }
1056
+ if (!(c = x.c)) return null;
1057
+ n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;
1058
+ if (v = c[v]) for (; v % 10 == 0; v /= 10, n--) ;
1059
+ if (n < 0) n = 0;
1060
+ return n;
1061
+ };
1062
+ P.dividedBy = P.div = function(y, b) {
1063
+ return div(this, new BigNumber2(y, b), DECIMAL_PLACES, ROUNDING_MODE);
1064
+ };
1065
+ P.dividedToIntegerBy = P.idiv = function(y, b) {
1066
+ return div(this, new BigNumber2(y, b), 0, 1);
1067
+ };
1068
+ P.exponentiatedBy = P.pow = function(n, m) {
1069
+ var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, x = this;
1070
+ n = new BigNumber2(n);
1071
+ if (n.c && !n.isInteger()) {
1072
+ throw Error(bignumberError + "Exponent not an integer: " + valueOf(n));
1073
+ }
1074
+ if (m != null) m = new BigNumber2(m);
1075
+ nIsBig = n.e > 14;
1076
+ if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {
1077
+ y = new BigNumber2(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n)));
1078
+ return m ? y.mod(m) : y;
1079
+ }
1080
+ nIsNeg = n.s < 0;
1081
+ if (m) {
1082
+ if (m.c ? !m.c[0] : !m.s) return new BigNumber2(NaN);
1083
+ isModExp = !nIsNeg && x.isInteger() && m.isInteger();
1084
+ if (isModExp) x = x.mod(m);
1085
+ } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {
1086
+ k = x.s < 0 && isOdd(n) ? -0 : 0;
1087
+ if (x.e > -1) k = 1 / k;
1088
+ return new BigNumber2(nIsNeg ? 1 / k : k);
1089
+ } else if (POW_PRECISION) {
1090
+ k = mathceil(POW_PRECISION / LOG_BASE + 2);
1091
+ }
1092
+ if (nIsBig) {
1093
+ half = new BigNumber2(0.5);
1094
+ if (nIsNeg) n.s = 1;
1095
+ nIsOdd = isOdd(n);
1096
+ } else {
1097
+ i = Math.abs(+valueOf(n));
1098
+ nIsOdd = i % 2;
1099
+ }
1100
+ y = new BigNumber2(ONE);
1101
+ for (; ; ) {
1102
+ if (nIsOdd) {
1103
+ y = y.times(x);
1104
+ if (!y.c) break;
1105
+ if (k) {
1106
+ if (y.c.length > k) y.c.length = k;
1107
+ } else if (isModExp) {
1108
+ y = y.mod(m);
1109
+ }
1110
+ }
1111
+ if (i) {
1112
+ i = mathfloor(i / 2);
1113
+ if (i === 0) break;
1114
+ nIsOdd = i % 2;
1115
+ } else {
1116
+ n = n.times(half);
1117
+ round(n, n.e + 1, 1);
1118
+ if (n.e > 14) {
1119
+ nIsOdd = isOdd(n);
1120
+ } else {
1121
+ i = +valueOf(n);
1122
+ if (i === 0) break;
1123
+ nIsOdd = i % 2;
1124
+ }
1125
+ }
1126
+ x = x.times(x);
1127
+ if (k) {
1128
+ if (x.c && x.c.length > k) x.c.length = k;
1129
+ } else if (isModExp) {
1130
+ x = x.mod(m);
1131
+ }
1132
+ }
1133
+ if (isModExp) return y;
1134
+ if (nIsNeg) y = ONE.div(y);
1135
+ return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;
1136
+ };
1137
+ P.integerValue = function(rm) {
1138
+ var n = new BigNumber2(this);
1139
+ if (rm == null) rm = ROUNDING_MODE;
1140
+ else intCheck(rm, 0, 8);
1141
+ return round(n, n.e + 1, rm);
1142
+ };
1143
+ P.isEqualTo = P.eq = function(y, b) {
1144
+ return compare(this, new BigNumber2(y, b)) === 0;
1145
+ };
1146
+ P.isFinite = function() {
1147
+ return !!this.c;
1148
+ };
1149
+ P.isGreaterThan = P.gt = function(y, b) {
1150
+ return compare(this, new BigNumber2(y, b)) > 0;
1151
+ };
1152
+ P.isGreaterThanOrEqualTo = P.gte = function(y, b) {
1153
+ return (b = compare(this, new BigNumber2(y, b))) === 1 || b === 0;
1154
+ };
1155
+ P.isInteger = function() {
1156
+ return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;
1157
+ };
1158
+ P.isLessThan = P.lt = function(y, b) {
1159
+ return compare(this, new BigNumber2(y, b)) < 0;
1160
+ };
1161
+ P.isLessThanOrEqualTo = P.lte = function(y, b) {
1162
+ return (b = compare(this, new BigNumber2(y, b))) === -1 || b === 0;
1163
+ };
1164
+ P.isNaN = function() {
1165
+ return !this.s;
1166
+ };
1167
+ P.isNegative = function() {
1168
+ return this.s < 0;
1169
+ };
1170
+ P.isPositive = function() {
1171
+ return this.s > 0;
1172
+ };
1173
+ P.isZero = function() {
1174
+ return !!this.c && this.c[0] == 0;
1175
+ };
1176
+ P.minus = function(y, b) {
1177
+ var i, j, t, xLTy, x = this, a = x.s;
1178
+ y = new BigNumber2(y, b);
1179
+ b = y.s;
1180
+ if (!a || !b) return new BigNumber2(NaN);
1181
+ if (a != b) {
1182
+ y.s = -b;
1183
+ return x.plus(y);
1184
+ }
1185
+ var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c;
1186
+ if (!xe || !ye) {
1187
+ if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber2(yc ? x : NaN);
1188
+ if (!xc[0] || !yc[0]) {
1189
+ return yc[0] ? (y.s = -b, y) : new BigNumber2(xc[0] ? x : (
1190
+ // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
1191
+ ROUNDING_MODE == 3 ? -0 : 0
1192
+ ));
1193
+ }
1194
+ }
1195
+ xe = bitFloor(xe);
1196
+ ye = bitFloor(ye);
1197
+ xc = xc.slice();
1198
+ if (a = xe - ye) {
1199
+ if (xLTy = a < 0) {
1200
+ a = -a;
1201
+ t = xc;
1202
+ } else {
1203
+ ye = xe;
1204
+ t = yc;
1205
+ }
1206
+ t.reverse();
1207
+ for (b = a; b--; t.push(0)) ;
1208
+ t.reverse();
1209
+ } else {
1210
+ j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;
1211
+ for (a = b = 0; b < j; b++) {
1212
+ if (xc[b] != yc[b]) {
1213
+ xLTy = xc[b] < yc[b];
1214
+ break;
1215
+ }
1216
+ }
1217
+ }
1218
+ if (xLTy) {
1219
+ t = xc;
1220
+ xc = yc;
1221
+ yc = t;
1222
+ y.s = -y.s;
1223
+ }
1224
+ b = (j = yc.length) - (i = xc.length);
1225
+ if (b > 0) for (; b--; xc[i++] = 0) ;
1226
+ b = BASE - 1;
1227
+ for (; j > a; ) {
1228
+ if (xc[--j] < yc[j]) {
1229
+ for (i = j; i && !xc[--i]; xc[i] = b) ;
1230
+ --xc[i];
1231
+ xc[j] += BASE;
1232
+ }
1233
+ xc[j] -= yc[j];
1234
+ }
1235
+ for (; xc[0] == 0; xc.splice(0, 1), --ye) ;
1236
+ if (!xc[0]) {
1237
+ y.s = ROUNDING_MODE == 3 ? -1 : 1;
1238
+ y.c = [y.e = 0];
1239
+ return y;
1240
+ }
1241
+ return normalise(y, xc, ye);
1242
+ };
1243
+ P.modulo = P.mod = function(y, b) {
1244
+ var q, s, x = this;
1245
+ y = new BigNumber2(y, b);
1246
+ if (!x.c || !y.s || y.c && !y.c[0]) {
1247
+ return new BigNumber2(NaN);
1248
+ } else if (!y.c || x.c && !x.c[0]) {
1249
+ return new BigNumber2(x);
1250
+ }
1251
+ if (MODULO_MODE == 9) {
1252
+ s = y.s;
1253
+ y.s = 1;
1254
+ q = div(x, y, 0, 3);
1255
+ y.s = s;
1256
+ q.s *= s;
1257
+ } else {
1258
+ q = div(x, y, 0, MODULO_MODE);
1259
+ }
1260
+ y = x.minus(q.times(y));
1261
+ if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;
1262
+ return y;
1263
+ };
1264
+ P.multipliedBy = P.times = function(y, b) {
1265
+ var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = (y = new BigNumber2(y, b)).c;
1266
+ if (!xc || !yc || !xc[0] || !yc[0]) {
1267
+ if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {
1268
+ y.c = y.e = y.s = null;
1269
+ } else {
1270
+ y.s *= x.s;
1271
+ if (!xc || !yc) {
1272
+ y.c = y.e = null;
1273
+ } else {
1274
+ y.c = [0];
1275
+ y.e = 0;
1276
+ }
1277
+ }
1278
+ return y;
1279
+ }
1280
+ e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);
1281
+ y.s *= x.s;
1282
+ xcL = xc.length;
1283
+ ycL = yc.length;
1284
+ if (xcL < ycL) {
1285
+ zc = xc;
1286
+ xc = yc;
1287
+ yc = zc;
1288
+ i = xcL;
1289
+ xcL = ycL;
1290
+ ycL = i;
1291
+ }
1292
+ for (i = xcL + ycL, zc = []; i--; zc.push(0)) ;
1293
+ base = BASE;
1294
+ sqrtBase = SQRT_BASE;
1295
+ for (i = ycL; --i >= 0; ) {
1296
+ c = 0;
1297
+ ylo = yc[i] % sqrtBase;
1298
+ yhi = yc[i] / sqrtBase | 0;
1299
+ for (k = xcL, j = i + k; j > i; ) {
1300
+ xlo = xc[--k] % sqrtBase;
1301
+ xhi = xc[k] / sqrtBase | 0;
1302
+ m = yhi * xlo + xhi * ylo;
1303
+ xlo = ylo * xlo + m % sqrtBase * sqrtBase + zc[j] + c;
1304
+ c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;
1305
+ zc[j--] = xlo % base;
1306
+ }
1307
+ zc[j] = c;
1308
+ }
1309
+ if (c) {
1310
+ ++e;
1311
+ } else {
1312
+ zc.splice(0, 1);
1313
+ }
1314
+ return normalise(y, zc, e);
1315
+ };
1316
+ P.negated = function() {
1317
+ var x = new BigNumber2(this);
1318
+ x.s = -x.s || null;
1319
+ return x;
1320
+ };
1321
+ P.plus = function(y, b) {
1322
+ var t, x = this, a = x.s;
1323
+ y = new BigNumber2(y, b);
1324
+ b = y.s;
1325
+ if (!a || !b) return new BigNumber2(NaN);
1326
+ if (a != b) {
1327
+ y.s = -b;
1328
+ return x.minus(y);
1329
+ }
1330
+ var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c;
1331
+ if (!xe || !ye) {
1332
+ if (!xc || !yc) return new BigNumber2(a / 0);
1333
+ if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber2(xc[0] ? x : a * 0);
1334
+ }
1335
+ xe = bitFloor(xe);
1336
+ ye = bitFloor(ye);
1337
+ xc = xc.slice();
1338
+ if (a = xe - ye) {
1339
+ if (a > 0) {
1340
+ ye = xe;
1341
+ t = yc;
1342
+ } else {
1343
+ a = -a;
1344
+ t = xc;
1345
+ }
1346
+ t.reverse();
1347
+ for (; a--; t.push(0)) ;
1348
+ t.reverse();
1349
+ }
1350
+ a = xc.length;
1351
+ b = yc.length;
1352
+ if (a - b < 0) {
1353
+ t = yc;
1354
+ yc = xc;
1355
+ xc = t;
1356
+ b = a;
1357
+ }
1358
+ for (a = 0; b; ) {
1359
+ a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;
1360
+ xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
1361
+ }
1362
+ if (a) {
1363
+ xc = [a].concat(xc);
1364
+ ++ye;
1365
+ }
1366
+ return normalise(y, xc, ye);
1367
+ };
1368
+ P.precision = P.sd = function(sd, rm) {
1369
+ var c, n, v, x = this;
1370
+ if (sd != null && sd !== !!sd) {
1371
+ intCheck(sd, 1, MAX);
1372
+ if (rm == null) rm = ROUNDING_MODE;
1373
+ else intCheck(rm, 0, 8);
1374
+ return round(new BigNumber2(x), sd, rm);
1375
+ }
1376
+ if (!(c = x.c)) return null;
1377
+ v = c.length - 1;
1378
+ n = v * LOG_BASE + 1;
1379
+ if (v = c[v]) {
1380
+ for (; v % 10 == 0; v /= 10, n--) ;
1381
+ for (v = c[0]; v >= 10; v /= 10, n++) ;
1382
+ }
1383
+ if (sd && x.e + 1 > n) n = x.e + 1;
1384
+ return n;
1385
+ };
1386
+ P.shiftedBy = function(k) {
1387
+ intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);
1388
+ return this.times("1e" + k);
1389
+ };
1390
+ P.squareRoot = P.sqrt = function() {
1391
+ var m, n, r, rep, t, x = this, c = x.c, s = x.s, e = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber2("0.5");
1392
+ if (s !== 1 || !c || !c[0]) {
1393
+ return new BigNumber2(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);
1394
+ }
1395
+ s = Math.sqrt(+valueOf(x));
1396
+ if (s == 0 || s == 1 / 0) {
1397
+ n = coeffToString(c);
1398
+ if ((n.length + e) % 2 == 0) n += "0";
1399
+ s = Math.sqrt(+n);
1400
+ e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);
1401
+ if (s == 1 / 0) {
1402
+ n = "5e" + e;
1403
+ } else {
1404
+ n = s.toExponential();
1405
+ n = n.slice(0, n.indexOf("e") + 1) + e;
1406
+ }
1407
+ r = new BigNumber2(n);
1408
+ } else {
1409
+ r = new BigNumber2(s + "");
1410
+ }
1411
+ if (r.c[0]) {
1412
+ e = r.e;
1413
+ s = e + dp;
1414
+ if (s < 3) s = 0;
1415
+ for (; ; ) {
1416
+ t = r;
1417
+ r = half.times(t.plus(div(x, t, dp, 1)));
1418
+ if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {
1419
+ if (r.e < e) --s;
1420
+ n = n.slice(s - 3, s + 1);
1421
+ if (n == "9999" || !rep && n == "4999") {
1422
+ if (!rep) {
1423
+ round(t, t.e + DECIMAL_PLACES + 2, 0);
1424
+ if (t.times(t).eq(x)) {
1425
+ r = t;
1426
+ break;
1427
+ }
1428
+ }
1429
+ dp += 4;
1430
+ s += 4;
1431
+ rep = 1;
1432
+ } else {
1433
+ if (!+n || !+n.slice(1) && n.charAt(0) == "5") {
1434
+ round(r, r.e + DECIMAL_PLACES + 2, 1);
1435
+ m = !r.times(r).eq(x);
1436
+ }
1437
+ break;
1438
+ }
1439
+ }
1440
+ }
1441
+ }
1442
+ return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);
1443
+ };
1444
+ P.toExponential = function(dp, rm) {
1445
+ if (dp != null) {
1446
+ intCheck(dp, 0, MAX);
1447
+ dp++;
1448
+ }
1449
+ return format(this, dp, rm, 1);
1450
+ };
1451
+ P.toFixed = function(dp, rm) {
1452
+ if (dp != null) {
1453
+ intCheck(dp, 0, MAX);
1454
+ dp = dp + this.e + 1;
1455
+ }
1456
+ return format(this, dp, rm);
1457
+ };
1458
+ P.toFormat = function(dp, rm, format2) {
1459
+ var str, x = this;
1460
+ if (format2 == null) {
1461
+ if (dp != null && rm && typeof rm == "object") {
1462
+ format2 = rm;
1463
+ rm = null;
1464
+ } else if (dp && typeof dp == "object") {
1465
+ format2 = dp;
1466
+ dp = rm = null;
1467
+ } else {
1468
+ format2 = FORMAT;
1469
+ }
1470
+ } else if (typeof format2 != "object") {
1471
+ throw Error(bignumberError + "Argument not an object: " + format2);
1472
+ }
1473
+ str = x.toFixed(dp, rm);
1474
+ if (x.c) {
1475
+ var i, arr = str.split("."), g1 = +format2.groupSize, g2 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length;
1476
+ if (g2) {
1477
+ i = g1;
1478
+ g1 = g2;
1479
+ g2 = i;
1480
+ len -= i;
1481
+ }
1482
+ if (g1 > 0 && len > 0) {
1483
+ i = len % g1 || g1;
1484
+ intPart = intDigits.substr(0, i);
1485
+ for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);
1486
+ if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);
1487
+ if (isNeg) intPart = "-" + intPart;
1488
+ }
1489
+ str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g2 = +format2.fractionGroupSize) ? fractionPart.replace(
1490
+ new RegExp("\\d{" + g2 + "}\\B", "g"),
1491
+ "$&" + (format2.fractionGroupSeparator || "")
1492
+ ) : fractionPart) : intPart;
1493
+ }
1494
+ return (format2.prefix || "") + str + (format2.suffix || "");
1495
+ };
1496
+ P.toFraction = function(md) {
1497
+ var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, x = this, xc = x.c;
1498
+ if (md != null) {
1499
+ n = new BigNumber2(md);
1500
+ if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {
1501
+ throw Error(bignumberError + "Argument " + (n.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n));
1502
+ }
1503
+ }
1504
+ if (!xc) return new BigNumber2(x);
1505
+ d = new BigNumber2(ONE);
1506
+ n1 = d0 = new BigNumber2(ONE);
1507
+ d1 = n0 = new BigNumber2(ONE);
1508
+ s = coeffToString(xc);
1509
+ e = d.e = s.length - x.e - 1;
1510
+ d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];
1511
+ md = !md || n.comparedTo(d) > 0 ? e > 0 ? d : n1 : n;
1512
+ exp = MAX_EXP;
1513
+ MAX_EXP = 1 / 0;
1514
+ n = new BigNumber2(s);
1515
+ n0.c[0] = 0;
1516
+ for (; ; ) {
1517
+ q = div(n, d, 0, 1);
1518
+ d2 = d0.plus(q.times(d1));
1519
+ if (d2.comparedTo(md) == 1) break;
1520
+ d0 = d1;
1521
+ d1 = d2;
1522
+ n1 = n0.plus(q.times(d2 = n1));
1523
+ n0 = d2;
1524
+ d = n.minus(q.times(d2 = d));
1525
+ n = d2;
1526
+ }
1527
+ d2 = div(md.minus(d0), d1, 0, 1);
1528
+ n0 = n0.plus(d2.times(n1));
1529
+ d0 = d0.plus(d2.times(d1));
1530
+ n0.s = n1.s = x.s;
1531
+ e = e * 2;
1532
+ r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(
1533
+ div(n0, d0, e, ROUNDING_MODE).minus(x).abs()
1534
+ ) < 1 ? [n1, d1] : [n0, d0];
1535
+ MAX_EXP = exp;
1536
+ return r;
1537
+ };
1538
+ P.toNumber = function() {
1539
+ return +valueOf(this);
1540
+ };
1541
+ P.toPrecision = function(sd, rm) {
1542
+ if (sd != null) intCheck(sd, 1, MAX);
1543
+ return format(this, sd, rm, 2);
1544
+ };
1545
+ P.toString = function(b) {
1546
+ var str, n = this, s = n.s, e = n.e;
1547
+ if (e === null) {
1548
+ if (s) {
1549
+ str = "Infinity";
1550
+ if (s < 0) str = "-" + str;
1551
+ } else {
1552
+ str = "NaN";
1553
+ }
1554
+ } else {
1555
+ if (b == null) {
1556
+ str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(coeffToString(n.c), e) : toFixedPoint(coeffToString(n.c), e, "0");
1557
+ } else if (b === 10 && alphabetHasNormalDecimalDigits) {
1558
+ n = round(new BigNumber2(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);
1559
+ str = toFixedPoint(coeffToString(n.c), n.e, "0");
1560
+ } else {
1561
+ intCheck(b, 2, ALPHABET.length, "Base");
1562
+ str = convertBase(toFixedPoint(coeffToString(n.c), e, "0"), 10, b, s, true);
1563
+ }
1564
+ if (s < 0 && n.c[0]) str = "-" + str;
1565
+ }
1566
+ return str;
1567
+ };
1568
+ P.valueOf = P.toJSON = function() {
1569
+ return valueOf(this);
1570
+ };
1571
+ P._isBigNumber = true;
1572
+ P[Symbol.toStringTag] = "BigNumber";
1573
+ P[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")] = P.valueOf;
1574
+ if (configObject != null) BigNumber2.set(configObject);
1575
+ return BigNumber2;
1576
+ }
1577
+ function bitFloor(n) {
1578
+ var i = n | 0;
1579
+ return n > 0 || n === i ? i : i - 1;
1580
+ }
1581
+ function coeffToString(a) {
1582
+ var s, z, i = 1, j = a.length, r = a[0] + "";
1583
+ for (; i < j; ) {
1584
+ s = a[i++] + "";
1585
+ z = LOG_BASE - s.length;
1586
+ for (; z--; s = "0" + s) ;
1587
+ r += s;
1588
+ }
1589
+ for (j = r.length; r.charCodeAt(--j) === 48; ) ;
1590
+ return r.slice(0, j + 1 || 1);
1591
+ }
1592
+ function compare(x, y) {
1593
+ var a, b, xc = x.c, yc = y.c, i = x.s, j = y.s, k = x.e, l = y.e;
1594
+ if (!i || !j) return null;
1595
+ a = xc && !xc[0];
1596
+ b = yc && !yc[0];
1597
+ if (a || b) return a ? b ? 0 : -j : i;
1598
+ if (i != j) return i;
1599
+ a = i < 0;
1600
+ b = k == l;
1601
+ if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;
1602
+ if (!b) return k > l ^ a ? 1 : -1;
1603
+ j = (k = xc.length) < (l = yc.length) ? k : l;
1604
+ for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;
1605
+ return k == l ? 0 : k > l ^ a ? 1 : -1;
1606
+ }
1607
+ function intCheck(n, min, max, name) {
1608
+ if (n < min || n > max || n !== mathfloor(n)) {
1609
+ throw Error(bignumberError + (name || "Argument") + (typeof n == "number" ? n < min || n > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n));
1610
+ }
1611
+ }
1612
+ function isOdd(n) {
1613
+ var k = n.c.length - 1;
1614
+ return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;
1615
+ }
1616
+ function toExponential(str, e) {
1617
+ return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e < 0 ? "e" : "e+") + e;
1618
+ }
1619
+ function toFixedPoint(str, e, z) {
1620
+ var len, zs;
1621
+ if (e < 0) {
1622
+ for (zs = z + "."; ++e; zs += z) ;
1623
+ str = zs + str;
1624
+ } else {
1625
+ len = str.length;
1626
+ if (++e > len) {
1627
+ for (zs = z, e -= len; --e; zs += z) ;
1628
+ str += zs;
1629
+ } else if (e < len) {
1630
+ str = str.slice(0, e) + "." + str.slice(e);
1631
+ }
1632
+ }
1633
+ return str;
1634
+ }
1635
+ var BigNumber = clone();
1636
+ var bignumber_default = BigNumber;
1637
+
1638
+ // ../../node_modules/.pnpm/@paralleldrive+cuid2@3.0.6/node_modules/@paralleldrive/cuid2/src/index.js
1639
+ var defaultLength = 24;
1640
+ var bigLength = 32;
1641
+ var createRandom = () => {
1642
+ if (typeof globalThis !== "undefined" && globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {
1643
+ return () => {
1644
+ const buffer = new Uint32Array(1);
1645
+ globalThis.crypto.getRandomValues(buffer);
1646
+ return buffer[0] / 4294967296;
1647
+ };
1648
+ }
1649
+ return Math.random;
1650
+ };
1651
+ var random = createRandom();
1652
+ var createEntropy = (length = 4, rand = random) => {
1653
+ let entropy = "";
1654
+ while (entropy.length < length) {
1655
+ entropy = entropy + Math.floor(rand() * 36).toString(36);
1656
+ }
1657
+ return entropy;
1658
+ };
1659
+ function bufToBigInt(buf) {
1660
+ let value = new bignumber_default(0);
1661
+ for (const i of buf.values()) {
1662
+ value = value.multipliedBy(256).plus(i);
1663
+ }
1664
+ return value;
1665
+ }
1666
+ var hash = (input = "") => {
1667
+ const encoder = new TextEncoder();
1668
+ return bufToBigInt(sha3_512(encoder.encode(input))).toString(36).slice(1);
1669
+ };
1670
+ var alphabet = Array.from(
1671
+ { length: 26 },
1672
+ (x, i) => String.fromCharCode(i + 97)
1673
+ );
1674
+ var randomLetter = (rand) => alphabet[Math.floor(rand() * alphabet.length)];
1675
+ var createFingerprint = ({
1676
+ globalObj = typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : {},
1677
+ random: rand = random
1678
+ } = {}) => {
1679
+ const globals = Object.keys(globalObj).toString();
1680
+ const sourceString = globals.length ? globals + createEntropy(bigLength, rand) : createEntropy(bigLength, rand);
1681
+ return hash(sourceString).substring(0, bigLength);
1682
+ };
1683
+ var createCounter = (count) => () => {
1684
+ return count++;
1685
+ };
1686
+ var initialCountMax = 476782367;
1687
+ var init = ({
1688
+ // Fallback if the user does not pass in a CSPRNG. This should be OK
1689
+ // because we don't rely solely on the random number generator for entropy.
1690
+ // We also use the host fingerprint, current time, and a session counter.
1691
+ random: rand = random,
1692
+ counter = createCounter(Math.floor(rand() * initialCountMax)),
1693
+ length = defaultLength,
1694
+ fingerprint = createFingerprint({ random: rand })
1695
+ } = {}) => {
1696
+ if (length > bigLength) {
1697
+ throw new Error(
1698
+ `Length must be between 2 and ${bigLength}. Received: ${length}`
1699
+ );
1700
+ }
1701
+ return function cuid2() {
1702
+ const firstLetter = randomLetter(rand);
1703
+ const time = Date.now().toString(36);
1704
+ const count = counter().toString(36);
1705
+ const salt = createEntropy(length, rand);
1706
+ const hashInput = `${time + salt + count + fingerprint}`;
1707
+ return `${firstLetter + hash(hashInput).substring(1, length)}`;
1708
+ };
1709
+ };
1710
+ var createId = lazy(init);
1711
+ function lazy(fn) {
1712
+ let initialized;
1713
+ return () => {
1714
+ if (!initialized) {
1715
+ initialized = fn();
1716
+ }
1717
+ return initialized();
1718
+ };
1719
+ }
1720
+ function getJobsDir() {
1721
+ return `${process.cwd()}/perstack/jobs`;
1722
+ }
1723
+ function getJobDir(jobId) {
1724
+ return `${getJobsDir()}/${jobId}`;
1725
+ }
1726
+ function storeJob(job) {
1727
+ const jobDir = getJobDir(job.id);
1728
+ if (!existsSync(jobDir)) {
1729
+ mkdirSync(jobDir, { recursive: true });
1730
+ }
1731
+ const jobPath = path5.resolve(jobDir, "job.json");
1732
+ writeFileSync(jobPath, JSON.stringify(job, null, 2));
1733
+ }
1734
+ function retrieveJob(jobId) {
1735
+ const jobDir = getJobDir(jobId);
1736
+ const jobPath = path5.resolve(jobDir, "job.json");
1737
+ if (!existsSync(jobPath)) {
1738
+ return void 0;
1739
+ }
1740
+ const content = readFileSync(jobPath, "utf-8");
1741
+ return jobSchema.parse(JSON.parse(content));
1742
+ }
1743
+ function getAllJobs() {
1744
+ const jobsDir = getJobsDir();
1745
+ if (!existsSync(jobsDir)) {
1746
+ return [];
1747
+ }
1748
+ const jobDirNames = readdirSync(jobsDir, { withFileTypes: true }).filter((dir) => dir.isDirectory()).map((dir) => dir.name);
1749
+ if (jobDirNames.length === 0) {
1750
+ return [];
1751
+ }
1752
+ const jobs = [];
1753
+ for (const jobDirName of jobDirNames) {
1754
+ const jobPath = path5.resolve(jobsDir, jobDirName, "job.json");
1755
+ if (!existsSync(jobPath)) {
1756
+ continue;
1757
+ }
1758
+ try {
1759
+ const content = readFileSync(jobPath, "utf-8");
1760
+ jobs.push(jobSchema.parse(JSON.parse(content)));
1761
+ } catch {
1762
+ }
1763
+ }
1764
+ return jobs.sort((a, b) => b.startedAt - a.startedAt);
1765
+ }
1766
+ function createInitialJob(jobId, expertKey, maxSteps) {
1767
+ return {
1768
+ id: jobId,
1769
+ status: "running",
1770
+ coordinatorExpertKey: expertKey,
1771
+ runtimeVersion: "v1.0",
1772
+ totalSteps: 0,
1773
+ maxSteps,
1774
+ usage: {
1775
+ inputTokens: 0,
1776
+ outputTokens: 0,
1777
+ reasoningTokens: 0,
1778
+ totalTokens: 0,
1779
+ cachedInputTokens: 0
1780
+ },
1781
+ startedAt: Date.now()
1782
+ };
1783
+ }
1784
+
1785
+ // ../../packages/filesystem/src/checkpoint.ts
1786
+ function getCheckpointDir(jobId) {
1787
+ return `${getJobDir(jobId)}/checkpoints`;
1788
+ }
1789
+ function getCheckpointPath(jobId, checkpointId) {
1790
+ return `${getCheckpointDir(jobId)}/${checkpointId}.json`;
1791
+ }
1792
+ async function defaultRetrieveCheckpoint(jobId, checkpointId) {
1793
+ const checkpointPath = getCheckpointPath(jobId, checkpointId);
1794
+ if (!existsSync(checkpointPath)) {
1795
+ throw new Error(`checkpoint not found: ${checkpointId}`);
1796
+ }
1797
+ const checkpoint = await readFile(checkpointPath, "utf8");
1798
+ return checkpointSchema.parse(JSON.parse(checkpoint));
1799
+ }
1800
+ async function defaultStoreCheckpoint(checkpoint) {
1801
+ const { id, jobId } = checkpoint;
1802
+ const checkpointDir = getCheckpointDir(jobId);
1803
+ await mkdir(checkpointDir, { recursive: true });
1804
+ await writeFile(getCheckpointPath(jobId, id), JSON.stringify(checkpoint));
1805
+ }
1806
+ function getCheckpointsByJobId(jobId) {
1807
+ const checkpointDir = getCheckpointDir(jobId);
1808
+ if (!existsSync(checkpointDir)) {
1809
+ return [];
1810
+ }
1811
+ const files = readdirSync(checkpointDir).filter((file) => file.endsWith(".json"));
1812
+ const checkpoints = [];
1813
+ for (const file of files) {
1814
+ try {
1815
+ const content = readFileSync(path5.resolve(checkpointDir, file), "utf-8");
1816
+ checkpoints.push(checkpointSchema.parse(JSON.parse(content)));
1817
+ } catch {
1818
+ }
1819
+ }
1820
+ return checkpoints.sort((a, b) => a.stepNumber - b.stepNumber);
1821
+ }
1822
+ function defaultGetRunDir(jobId, runId) {
1823
+ return `${process.cwd()}/perstack/jobs/${jobId}/runs/${runId}`;
1824
+ }
1825
+ function getAllRuns() {
1826
+ const jobsDir = getJobsDir();
1827
+ if (!existsSync(jobsDir)) {
1828
+ return [];
1829
+ }
1830
+ const jobDirNames = readdirSync(jobsDir, { withFileTypes: true }).filter((dir) => dir.isDirectory()).map((dir) => dir.name);
1831
+ if (jobDirNames.length === 0) {
1832
+ return [];
1833
+ }
1834
+ const runs = [];
1835
+ for (const jobDirName of jobDirNames) {
1836
+ const runsDir = path5.resolve(jobsDir, jobDirName, "runs");
1837
+ if (!existsSync(runsDir)) {
1838
+ continue;
1839
+ }
1840
+ const runDirNames = readdirSync(runsDir, { withFileTypes: true }).filter((dir) => dir.isDirectory()).map((dir) => dir.name);
1841
+ for (const runDirName of runDirNames) {
1842
+ const runSettingPath = path5.resolve(runsDir, runDirName, "run-setting.json");
1843
+ if (!existsSync(runSettingPath)) {
1844
+ continue;
1845
+ }
1846
+ try {
1847
+ const content = readFileSync(runSettingPath, "utf-8");
1848
+ runs.push(runSettingSchema.parse(JSON.parse(content)));
1849
+ } catch {
1850
+ }
1851
+ }
1852
+ }
1853
+ return runs.sort((a, b) => b.updatedAt - a.updatedAt);
1854
+ }
1855
+
1856
+ // ../../packages/filesystem/src/event.ts
1857
+ async function defaultStoreEvent(event) {
1858
+ const { timestamp, jobId, runId, stepNumber, type } = event;
1859
+ const runDir = defaultGetRunDir(jobId, runId);
1860
+ const eventPath = `${runDir}/event-${timestamp}-${stepNumber}-${type}.json`;
1861
+ await mkdir(runDir, { recursive: true });
1862
+ await writeFile(eventPath, JSON.stringify(event));
1863
+ }
1864
+ function getEventContents(jobId, runId, maxStepNumber) {
1865
+ const runDir = defaultGetRunDir(jobId, runId);
1866
+ if (!existsSync(runDir)) {
1867
+ return [];
1868
+ }
1869
+ const eventFiles = readdirSync(runDir).filter((file) => file.startsWith("event-")).map((file) => {
1870
+ const [_, timestamp, step, type] = file.split(".")[0].split("-");
1871
+ return { file, timestamp: Number(timestamp), stepNumber: Number(step), type };
1872
+ }).filter((e) => maxStepNumber === void 0 || e.stepNumber <= maxStepNumber).sort((a, b) => a.timestamp - b.timestamp);
1873
+ const events = [];
1874
+ for (const { file } of eventFiles) {
1875
+ try {
1876
+ const content = readFileSync(path5.resolve(runDir, file), "utf-8");
1877
+ events.push(JSON.parse(content));
1878
+ } catch {
1879
+ }
1880
+ }
1881
+ return events;
1882
+ }
1883
+ function getRunIdsByJobId(jobId) {
1884
+ const runsDir = path5.resolve(getJobDir(jobId), "runs");
1885
+ if (!existsSync(runsDir)) {
1886
+ return [];
1887
+ }
1888
+ return readdirSync(runsDir, { withFileTypes: true }).filter((dir) => dir.isDirectory()).map((dir) => dir.name);
1889
+ }
1890
+
1891
+ // ../../packages/tui-components/src/utils/event-queue.ts
1892
+ var defaultErrorLogger = (message, error) => {
1893
+ console.error(message, error);
1894
+ };
1895
+ var EventQueue = class _EventQueue {
1896
+ static MAX_PENDING_EVENTS = 1e3;
1897
+ pendingEvents = [];
1898
+ handler = null;
1899
+ onError;
1900
+ errorLogger;
1901
+ constructor(options) {
1902
+ this.onError = options?.onError;
1903
+ this.errorLogger = options?.errorLogger ?? defaultErrorLogger;
1904
+ }
1905
+ setHandler(fn) {
1906
+ this.handler = fn;
1907
+ for (const event of this.pendingEvents) {
1908
+ this.safeHandle(event);
1909
+ }
1910
+ this.pendingEvents.length = 0;
1911
+ }
1912
+ emit(event) {
1913
+ if (this.handler) {
1914
+ this.safeHandle(event);
1915
+ } else {
1916
+ if (this.pendingEvents.length >= _EventQueue.MAX_PENDING_EVENTS) {
1917
+ this.pendingEvents.shift();
1918
+ }
1919
+ this.pendingEvents.push(event);
1920
+ }
1921
+ }
1922
+ safeHandle(event) {
1923
+ try {
1924
+ this.handler?.(event);
1925
+ } catch (error) {
1926
+ if (this.onError) {
1927
+ this.onError(error);
1928
+ } else {
1929
+ this.errorLogger("EventQueue handler error:", error);
1930
+ }
1931
+ }
1932
+ }
1933
+ };
1934
+ var InputAreaContext = createContext(null);
1935
+ var InputAreaProvider = InputAreaContext.Provider;
1936
+ var useInputAreaContext = () => {
1937
+ const context = useContext(InputAreaContext);
1938
+ if (!context) {
1939
+ throw new Error("useInputAreaContext must be used within InputAreaProvider");
1940
+ }
1941
+ return context;
1942
+ };
1943
+
1944
+ // ../../packages/tui-components/src/helpers.ts
1945
+ var truncateText = (text, maxLength) => {
1946
+ if (text.length <= maxLength) return text;
1947
+ return `${text.slice(0, maxLength)}...`;
1948
+ };
1949
+ var assertNever = (x) => {
1950
+ throw new Error(`Unexpected value: ${x}`);
1951
+ };
1952
+ var formatTimestamp = (timestamp) => new Date(timestamp).toLocaleString();
1953
+ var shortenPath = (fullPath, maxLength = 60) => {
1954
+ if (fullPath.length <= maxLength) return fullPath;
1955
+ const parts = fullPath.split("/");
1956
+ if (parts.length <= 2) return fullPath;
1957
+ const filename = parts[parts.length - 1] ?? "";
1958
+ const parentDir = parts[parts.length - 2] ?? "";
1959
+ const shortened = `.../${parentDir}/${filename}`;
1960
+ if (shortened.length <= maxLength) return shortened;
1961
+ return `.../${filename}`;
1962
+ };
1963
+ var summarizeOutput = (lines, maxLines) => {
1964
+ const filtered = lines.filter((l) => l.trim());
1965
+ const visible = filtered.slice(0, maxLines);
1966
+ const remaining = filtered.length - visible.length;
1967
+ return { visible, remaining };
1968
+ };
1969
+
1970
+ // ../../packages/tui-components/src/constants.ts
1971
+ var UI_CONSTANTS = {
1972
+ MAX_VISIBLE_LIST_ITEMS: 25,
1973
+ TRUNCATE_TEXT_MEDIUM: 80,
1974
+ TRUNCATE_TEXT_DEFAULT: 100};
1975
+ var RENDER_CONSTANTS = {
1976
+ EXEC_OUTPUT_MAX_LINES: 4,
1977
+ NEW_TODO_MAX_PREVIEW: 3,
1978
+ LIST_DIR_MAX_ITEMS: 4
1979
+ };
1980
+ var INDICATOR = {
1981
+ BULLET: "\u25CF",
1982
+ TREE: "\u2514",
1983
+ ELLIPSIS: "..."
1984
+ };
1985
+ var STOP_EVENT_TYPES = [
1986
+ "stopRunByInteractiveTool",
1987
+ "stopRunByDelegate",
1988
+ "stopRunByExceededMaxSteps"
1989
+ ];
1990
+ var KEY_BINDINGS = {
1991
+ NAVIGATE_UP: "\u2191",
1992
+ NAVIGATE_DOWN: "\u2193",
1993
+ SELECT: "Enter",
1994
+ BACK: "b",
1995
+ ESCAPE: "Esc",
1996
+ INPUT_MODE: "i",
1997
+ HISTORY: "h",
1998
+ NEW: "n",
1999
+ CHECKPOINTS: "c",
2000
+ EVENTS: "e",
2001
+ RESUME: "Enter"};
2002
+ var KEY_HINTS = {
2003
+ NAVIGATE: `${KEY_BINDINGS.NAVIGATE_UP}${KEY_BINDINGS.NAVIGATE_DOWN}:Navigate`,
2004
+ SELECT: `${KEY_BINDINGS.SELECT}:Select`,
2005
+ RESUME: `${KEY_BINDINGS.RESUME}:Resume`,
2006
+ BACK: `${KEY_BINDINGS.BACK}:Back`,
2007
+ CANCEL: `${KEY_BINDINGS.ESCAPE}:Cancel`,
2008
+ INPUT: `${KEY_BINDINGS.INPUT_MODE}:Input`,
2009
+ HISTORY: `${KEY_BINDINGS.HISTORY}:History`,
2010
+ NEW: `${KEY_BINDINGS.NEW}:New Run`,
2011
+ CHECKPOINTS: `${KEY_BINDINGS.CHECKPOINTS}:Checkpoints`,
2012
+ EVENTS: `${KEY_BINDINGS.EVENTS}:Events`};
2013
+ var useListNavigation = (options) => {
2014
+ const { items, onSelect, onBack } = options;
2015
+ const [selectedIndex, setSelectedIndex] = useState(0);
2016
+ useEffect(() => {
2017
+ if (selectedIndex >= items.length && items.length > 0) {
2018
+ setSelectedIndex(items.length - 1);
2019
+ }
2020
+ }, [items.length, selectedIndex]);
2021
+ const handleNavigation = useCallback(
2022
+ (inputChar, key) => {
2023
+ if (key.upArrow && items.length > 0) {
2024
+ setSelectedIndex((prev) => Math.max(0, prev - 1));
2025
+ return true;
2026
+ }
2027
+ if (key.downArrow && items.length > 0) {
2028
+ setSelectedIndex((prev) => Math.min(items.length - 1, prev + 1));
2029
+ return true;
2030
+ }
2031
+ if (key.return && items[selectedIndex]) {
2032
+ onSelect?.(items[selectedIndex]);
2033
+ return true;
2034
+ }
2035
+ if ((key.escape || inputChar === "b") && onBack) {
2036
+ onBack();
2037
+ return true;
2038
+ }
2039
+ return false;
2040
+ },
2041
+ [items, selectedIndex, onSelect, onBack]
2042
+ );
2043
+ return { selectedIndex, handleNavigation };
2044
+ };
2045
+ var ListBrowser = ({
2046
+ title,
2047
+ items,
2048
+ renderItem,
2049
+ onSelect,
2050
+ emptyMessage = "No items found",
2051
+ extraKeyHandler,
2052
+ onBack,
2053
+ maxItems = UI_CONSTANTS.MAX_VISIBLE_LIST_ITEMS
2054
+ }) => {
2055
+ const { selectedIndex, handleNavigation } = useListNavigation({
2056
+ items,
2057
+ onSelect,
2058
+ onBack
2059
+ });
2060
+ useInput((inputChar, key) => {
2061
+ if (extraKeyHandler?.(inputChar, key, items[selectedIndex])) return;
2062
+ handleNavigation(inputChar, key);
2063
+ });
2064
+ const { scrollOffset, displayItems } = useMemo(() => {
2065
+ const offset = Math.max(0, Math.min(selectedIndex - maxItems + 1, items.length - maxItems));
2066
+ return {
2067
+ scrollOffset: offset,
2068
+ displayItems: items.slice(offset, offset + maxItems)
2069
+ };
2070
+ }, [items, selectedIndex, maxItems]);
2071
+ const hasMoreAbove = scrollOffset > 0;
2072
+ const hasMoreBelow = scrollOffset + maxItems < items.length;
2073
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
2074
+ /* @__PURE__ */ jsxs(Box, { children: [
2075
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: title }),
2076
+ items.length > maxItems && /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
2077
+ " ",
2078
+ "(",
2079
+ selectedIndex + 1,
2080
+ "/",
2081
+ items.length,
2082
+ ")"
2083
+ ] })
2084
+ ] }),
2085
+ hasMoreAbove && /* @__PURE__ */ jsx(Text, { color: "gray", children: INDICATOR.ELLIPSIS }),
2086
+ /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: displayItems.length === 0 ? /* @__PURE__ */ jsx(Text, { color: "gray", children: emptyMessage }) : displayItems.map((item, index) => {
2087
+ const actualIndex = scrollOffset + index;
2088
+ return renderItem(item, actualIndex === selectedIndex, actualIndex);
2089
+ }) }),
2090
+ hasMoreBelow && /* @__PURE__ */ jsx(Text, { color: "gray", children: INDICATOR.ELLIPSIS })
2091
+ ] });
2092
+ };
2093
+ var BrowsingCheckpointsInput = ({
2094
+ job,
2095
+ checkpoints,
2096
+ onCheckpointSelect,
2097
+ onCheckpointResume,
2098
+ onBack,
2099
+ showEventsHint = true
2100
+ }) => /* @__PURE__ */ jsx(
2101
+ ListBrowser,
2102
+ {
2103
+ title: `Checkpoints for ${job.expertKey} ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.RESUME} ${showEventsHint ? KEY_HINTS.EVENTS : ""} ${KEY_HINTS.BACK}`.trim(),
2104
+ items: checkpoints,
2105
+ onSelect: onCheckpointResume,
2106
+ onBack,
2107
+ emptyMessage: "No checkpoints found",
2108
+ extraKeyHandler: (char, _key, selected) => {
2109
+ if (char === "e" && selected) {
2110
+ onCheckpointSelect(selected);
2111
+ return true;
2112
+ }
2113
+ return false;
2114
+ },
2115
+ renderItem: (cp, isSelected) => /* @__PURE__ */ jsxs(Text, { color: isSelected ? "cyan" : "gray", children: [
2116
+ isSelected ? ">" : " ",
2117
+ " Step ",
2118
+ cp.stepNumber,
2119
+ " (",
2120
+ cp.id,
2121
+ ")"
2122
+ ] }, cp.id)
2123
+ }
2124
+ );
2125
+ var BrowsingEventDetailInput = ({ event, onBack }) => {
2126
+ useInput((input, key) => {
2127
+ if (input === "b" || key.escape) {
2128
+ onBack();
2129
+ }
2130
+ });
2131
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, children: [
2132
+ /* @__PURE__ */ jsxs(Box, { marginBottom: 1, children: [
2133
+ /* @__PURE__ */ jsx(Text, { bold: true, children: "Event Detail" }),
2134
+ /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
2135
+ " ",
2136
+ KEY_HINTS.BACK
2137
+ ] })
2138
+ ] }),
2139
+ /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginLeft: 2, children: [
2140
+ /* @__PURE__ */ jsxs(Text, { children: [
2141
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Type: " }),
2142
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: event.type })
2143
+ ] }),
2144
+ /* @__PURE__ */ jsxs(Text, { children: [
2145
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Step: " }),
2146
+ /* @__PURE__ */ jsx(Text, { children: event.stepNumber })
2147
+ ] }),
2148
+ /* @__PURE__ */ jsxs(Text, { children: [
2149
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Timestamp: " }),
2150
+ /* @__PURE__ */ jsx(Text, { children: formatTimestamp(event.timestamp) })
2151
+ ] }),
2152
+ /* @__PURE__ */ jsxs(Text, { children: [
2153
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "ID: " }),
2154
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: event.id })
2155
+ ] }),
2156
+ /* @__PURE__ */ jsxs(Text, { children: [
2157
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Run ID: " }),
2158
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: event.runId })
2159
+ ] })
2160
+ ] })
2161
+ ] });
2162
+ };
2163
+ var BrowsingEventsInput = ({
2164
+ checkpoint,
2165
+ events,
2166
+ onEventSelect,
2167
+ onBack
2168
+ }) => /* @__PURE__ */ jsx(
2169
+ ListBrowser,
2170
+ {
2171
+ title: `Events for Step ${checkpoint.stepNumber} ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.SELECT} ${KEY_HINTS.BACK}`,
2172
+ items: events,
2173
+ onSelect: onEventSelect,
2174
+ onBack,
2175
+ emptyMessage: "No events found",
2176
+ renderItem: (ev, isSelected) => /* @__PURE__ */ jsxs(Text, { color: isSelected ? "cyan" : "gray", children: [
2177
+ isSelected ? ">" : " ",
2178
+ " [",
2179
+ ev.type,
2180
+ "] Step ",
2181
+ ev.stepNumber,
2182
+ " (",
2183
+ formatTimestamp(ev.timestamp),
2184
+ ")"
2185
+ ] }, ev.id)
2186
+ }
2187
+ );
2188
+ var TOOL_RESULT_EVENT_TYPES = /* @__PURE__ */ new Set(["resolveToolResults", "attemptCompletion"]);
2189
+ function toolToActivity(toolCall, toolResult, reasoning, meta) {
2190
+ const { skillName, toolName } = toolCall;
2191
+ const baseActivity = skillName.startsWith(BASE_SKILL_PREFIX) ? createBaseToolActivity(toolName, toolCall, toolResult, reasoning) : createGeneralToolActivity(skillName, toolName, toolCall, toolResult, reasoning);
2192
+ return {
2193
+ ...baseActivity,
2194
+ id: meta.id,
2195
+ expertKey: meta.expertKey,
2196
+ runId: meta.runId,
2197
+ previousActivityId: meta.previousActivityId,
2198
+ delegatedBy: meta.delegatedBy
2199
+ };
2200
+ }
2201
+ function createInitialActivityProcessState() {
2202
+ return {
2203
+ tools: /* @__PURE__ */ new Map(),
2204
+ runStates: /* @__PURE__ */ new Map()
2205
+ };
2206
+ }
2207
+ function getOrCreateRunState(state, runId, expertKey) {
2208
+ let runState = state.runStates.get(runId);
2209
+ if (!runState) {
2210
+ runState = {
2211
+ expertKey,
2212
+ queryLogged: false,
2213
+ completionLogged: false,
2214
+ isComplete: false,
2215
+ pendingDelegateCount: 0
2216
+ };
2217
+ state.runStates.set(runId, runState);
2218
+ }
2219
+ return runState;
2220
+ }
2221
+ var isRunEvent = (event) => "type" in event && "expertKey" in event;
2222
+ var isCompleteStreamingReasoningEvent = (event) => "type" in event && event.type === "completeStreamingReasoning";
2223
+ var isToolCallsEvent = (event) => event.type === "callTools" && "toolCalls" in event;
2224
+ var isStopRunByDelegateEvent = (event) => event.type === "stopRunByDelegate" && "checkpoint" in event;
2225
+ var isStopRunByInteractiveToolEvent = (event) => event.type === "stopRunByInteractiveTool" && "checkpoint" in event;
2226
+ var isToolResultsEvent = (event) => event.type === "resolveToolResults" && "toolResults" in event;
2227
+ var isToolResultEvent = (event) => TOOL_RESULT_EVENT_TYPES.has(event.type) && "toolResult" in event;
2228
+ function wrapInGroupIfParallel(activities, reasoning, meta) {
2229
+ if (activities.length <= 1) {
2230
+ return activities;
2231
+ }
2232
+ const activitiesWithoutReasoning = activities.map((a) => {
2233
+ const { reasoning: _, ...rest } = a;
2234
+ return rest;
2235
+ });
2236
+ const group = {
2237
+ type: "parallelGroup",
2238
+ id: `parallel-${activities[0].id}`,
2239
+ expertKey: meta.expertKey,
2240
+ runId: meta.runId,
2241
+ reasoning,
2242
+ activities: activitiesWithoutReasoning
2243
+ };
2244
+ return [group];
2245
+ }
2246
+ function processRunEventToActivity(state, event, addActivity) {
2247
+ if (isCompleteStreamingReasoningEvent(event)) {
2248
+ const reasoningEvent = event;
2249
+ const { runId, text, expertKey } = reasoningEvent;
2250
+ const runState2 = state.runStates.get(runId);
2251
+ if (runState2) {
2252
+ runState2.completedReasoning = text;
2253
+ } else {
2254
+ state.runStates.set(runId, {
2255
+ expertKey,
2256
+ queryLogged: false,
2257
+ completionLogged: false,
2258
+ isComplete: false,
2259
+ pendingDelegateCount: 0,
2260
+ completedReasoning: text
2261
+ });
2262
+ }
2263
+ return;
2264
+ }
2265
+ if (!isRunEvent(event)) {
2266
+ return;
2267
+ }
2268
+ const runState = getOrCreateRunState(state, event.runId, event.expertKey);
2269
+ if (event.type === "startRun") {
2270
+ const startRunEvent = event;
2271
+ const userMessage = startRunEvent.inputMessages.find((m) => m.type === "userMessage");
2272
+ const queryText = userMessage?.contents?.find((c) => c.type === "textPart")?.text;
2273
+ if (!runState.delegatedBy) {
2274
+ const delegatedByInfo = startRunEvent.initialCheckpoint?.delegatedBy;
2275
+ if (delegatedByInfo) {
2276
+ runState.delegatedBy = {
2277
+ expertKey: delegatedByInfo.expert.key,
2278
+ runId: delegatedByInfo.runId
2279
+ };
2280
+ }
2281
+ }
2282
+ const isDelegationReturn = startRunEvent.initialCheckpoint?.status === "stoppedByDelegate" || startRunEvent.initialCheckpoint?.status === "stoppedByInteractiveTool";
2283
+ if (queryText && !runState.queryLogged && !isDelegationReturn) {
2284
+ const activityId = `query-${event.runId}`;
2285
+ addActivity({
2286
+ type: "query",
2287
+ id: activityId,
2288
+ expertKey: event.expertKey,
2289
+ runId: event.runId,
2290
+ previousActivityId: runState.lastActivityId,
2291
+ delegatedBy: runState.delegatedBy,
2292
+ text: queryText
2293
+ });
2294
+ runState.lastActivityId = activityId;
2295
+ runState.queryLogged = true;
2296
+ }
2297
+ return;
2298
+ }
2299
+ if (event.type === "resumeFromStop") {
2300
+ if (!runState.delegatedBy) {
2301
+ const resumeEvent = event;
2302
+ const delegatedByInfo = resumeEvent.checkpoint?.delegatedBy;
2303
+ if (delegatedByInfo) {
2304
+ runState.delegatedBy = {
2305
+ expertKey: delegatedByInfo.expert.key,
2306
+ runId: delegatedByInfo.runId
2307
+ };
2308
+ }
2309
+ }
2310
+ return;
2311
+ }
2312
+ if (event.type === "retry") {
2313
+ const retryEvent = event;
2314
+ const activityId = `retry-${event.id}`;
2315
+ addActivity({
2316
+ type: "retry",
2317
+ id: activityId,
2318
+ expertKey: event.expertKey,
2319
+ runId: event.runId,
2320
+ previousActivityId: runState.lastActivityId,
2321
+ delegatedBy: runState.delegatedBy,
2322
+ reasoning: runState.completedReasoning,
2323
+ error: retryEvent.reason,
2324
+ message: ""
2325
+ });
2326
+ runState.lastActivityId = activityId;
2327
+ runState.completedReasoning = void 0;
2328
+ return;
2329
+ }
2330
+ if (event.type === "completeRun") {
2331
+ if (!runState.completionLogged) {
2332
+ const text = event.text ?? "";
2333
+ const activityId = `completion-${event.runId}`;
2334
+ addActivity({
2335
+ type: "complete",
2336
+ id: activityId,
2337
+ expertKey: event.expertKey,
2338
+ runId: event.runId,
2339
+ previousActivityId: runState.lastActivityId,
2340
+ delegatedBy: runState.delegatedBy,
2341
+ reasoning: runState.completedReasoning,
2342
+ text
2343
+ });
2344
+ runState.lastActivityId = activityId;
2345
+ runState.completionLogged = true;
2346
+ runState.isComplete = true;
2347
+ runState.completedReasoning = void 0;
2348
+ }
2349
+ return;
2350
+ }
2351
+ if (event.type === "stopRunByError") {
2352
+ const errorEvent = event;
2353
+ const activityId = `error-${event.id}`;
2354
+ addActivity({
2355
+ type: "error",
2356
+ id: activityId,
2357
+ expertKey: event.expertKey,
2358
+ runId: event.runId,
2359
+ previousActivityId: runState.lastActivityId,
2360
+ delegatedBy: runState.delegatedBy,
2361
+ errorName: errorEvent.error.name,
2362
+ error: errorEvent.error.message,
2363
+ isRetryable: errorEvent.error.isRetryable
2364
+ });
2365
+ runState.lastActivityId = activityId;
2366
+ runState.isComplete = true;
2367
+ runState.completedReasoning = void 0;
2368
+ return;
2369
+ }
2370
+ if (isToolCallsEvent(event)) {
2371
+ for (const toolCall of event.toolCalls) {
2372
+ if (!state.tools.has(toolCall.id)) {
2373
+ state.tools.set(toolCall.id, { id: toolCall.id, toolCall, logged: false });
2374
+ }
2375
+ }
2376
+ }
2377
+ if (isStopRunByDelegateEvent(event)) {
2378
+ const reasoning = runState.completedReasoning;
2379
+ const delegations = event.checkpoint.delegateTo ?? [];
2380
+ runState.pendingDelegateCount += delegations.length;
2381
+ const delegateActivities = [];
2382
+ for (const delegation of delegations) {
2383
+ const existingTool = state.tools.get(delegation.toolCallId);
2384
+ if (!existingTool || !existingTool.logged) {
2385
+ if (existingTool) {
2386
+ existingTool.logged = true;
2387
+ }
2388
+ const activityId = `delegate-${delegation.toolCallId}`;
2389
+ delegateActivities.push({
2390
+ type: "delegate",
2391
+ id: activityId,
2392
+ expertKey: event.expertKey,
2393
+ runId: event.runId,
2394
+ previousActivityId: runState.lastActivityId,
2395
+ delegatedBy: runState.delegatedBy,
2396
+ delegateExpertKey: delegation.expert.key,
2397
+ query: delegation.query,
2398
+ reasoning
2399
+ });
2400
+ runState.lastActivityId = activityId;
2401
+ }
2402
+ }
2403
+ const wrapped = wrapInGroupIfParallel(delegateActivities, reasoning, {
2404
+ expertKey: event.expertKey,
2405
+ runId: event.runId,
2406
+ delegatedBy: runState.delegatedBy
2407
+ });
2408
+ for (const item of wrapped) {
2409
+ addActivity(item);
2410
+ }
2411
+ runState.completedReasoning = void 0;
2412
+ return;
2413
+ }
2414
+ if (isStopRunByInteractiveToolEvent(event)) {
2415
+ const reasoning = runState.completedReasoning;
2416
+ const pendingToolCalls = event.checkpoint.pendingToolCalls ?? [];
2417
+ const interactiveActivities = [];
2418
+ for (const toolCall of pendingToolCalls) {
2419
+ const existingTool = state.tools.get(toolCall.id);
2420
+ if (!existingTool || !existingTool.logged) {
2421
+ if (existingTool) {
2422
+ existingTool.logged = true;
2423
+ }
2424
+ const activityId = `interactive-${toolCall.id}`;
2425
+ interactiveActivities.push({
2426
+ type: "interactiveTool",
2427
+ id: activityId,
2428
+ expertKey: event.expertKey,
2429
+ runId: event.runId,
2430
+ previousActivityId: runState.lastActivityId,
2431
+ delegatedBy: runState.delegatedBy,
2432
+ skillName: toolCall.skillName,
2433
+ toolName: toolCall.toolName,
2434
+ args: toolCall.args,
2435
+ reasoning
2436
+ });
2437
+ runState.lastActivityId = activityId;
2438
+ }
2439
+ }
2440
+ const wrapped = wrapInGroupIfParallel(interactiveActivities, reasoning, {
2441
+ expertKey: event.expertKey,
2442
+ runId: event.runId,
2443
+ delegatedBy: runState.delegatedBy
2444
+ });
2445
+ for (const item of wrapped) {
2446
+ addActivity(item);
2447
+ }
2448
+ runState.completedReasoning = void 0;
2449
+ return;
2450
+ }
2451
+ if (isToolResultsEvent(event)) {
2452
+ const reasoning = runState.completedReasoning;
2453
+ const toolActivities = [];
2454
+ for (const toolResult of event.toolResults) {
2455
+ const tool = state.tools.get(toolResult.id);
2456
+ if (tool && !tool.logged) {
2457
+ const activityId = `action-${tool.id}`;
2458
+ const activity = toolToActivity(tool.toolCall, toolResult, reasoning, {
2459
+ id: activityId,
2460
+ expertKey: event.expertKey,
2461
+ runId: event.runId,
2462
+ previousActivityId: runState.lastActivityId,
2463
+ delegatedBy: runState.delegatedBy
2464
+ });
2465
+ toolActivities.push(activity);
2466
+ runState.lastActivityId = activityId;
2467
+ tool.logged = true;
2468
+ }
2469
+ }
2470
+ if (toolActivities.length > 0) {
2471
+ const wrapped = wrapInGroupIfParallel(toolActivities, reasoning, {
2472
+ expertKey: event.expertKey,
2473
+ runId: event.runId,
2474
+ delegatedBy: runState.delegatedBy
2475
+ });
2476
+ for (const item of wrapped) {
2477
+ addActivity(item);
2478
+ }
2479
+ runState.completedReasoning = void 0;
2480
+ }
2481
+ } else if (isToolResultEvent(event)) {
2482
+ const { toolResult } = event;
2483
+ const tool = state.tools.get(toolResult.id);
2484
+ if (tool && !tool.logged) {
2485
+ const activityId = `action-${tool.id}`;
2486
+ const activity = toolToActivity(tool.toolCall, toolResult, runState.completedReasoning, {
2487
+ id: activityId,
2488
+ expertKey: event.expertKey,
2489
+ runId: event.runId,
2490
+ previousActivityId: runState.lastActivityId,
2491
+ delegatedBy: runState.delegatedBy
2492
+ });
2493
+ addActivity(activity);
2494
+ runState.lastActivityId = activityId;
2495
+ tool.logged = true;
2496
+ runState.completedReasoning = void 0;
2497
+ }
2498
+ }
2499
+ }
2500
+
2501
+ // ../../packages/react/src/hooks/use-run.ts
2502
+ var STREAMING_EVENT_TYPES = /* @__PURE__ */ new Set([
2503
+ "startStreamingReasoning",
2504
+ "streamReasoning",
2505
+ "completeStreamingReasoning",
2506
+ "startStreamingRunResult",
2507
+ "streamRunResult",
2508
+ "completeStreamingRunResult"
2509
+ ]);
2510
+ var isStreamingEvent = (event) => "type" in event && "expertKey" in event && STREAMING_EVENT_TYPES.has(event.type);
2511
+ function processStreamingEvent(event, prevState) {
2512
+ const { runId, expertKey } = event;
2513
+ switch (event.type) {
2514
+ case "startStreamingReasoning": {
2515
+ return {
2516
+ newState: {
2517
+ ...prevState,
2518
+ runs: {
2519
+ ...prevState.runs,
2520
+ [runId]: {
2521
+ expertKey,
2522
+ reasoning: "",
2523
+ isReasoningActive: true
2524
+ }
2525
+ }
2526
+ },
2527
+ handled: true
2528
+ };
2529
+ }
2530
+ case "streamReasoning": {
2531
+ return {
2532
+ newState: {
2533
+ ...prevState,
2534
+ runs: {
2535
+ ...prevState.runs,
2536
+ [runId]: {
2537
+ ...prevState.runs[runId],
2538
+ expertKey,
2539
+ reasoning: (prevState.runs[runId]?.reasoning ?? "") + event.delta
2540
+ }
2541
+ }
2542
+ },
2543
+ handled: true
2544
+ };
2545
+ }
2546
+ case "completeStreamingReasoning": {
2547
+ return {
2548
+ newState: {
2549
+ ...prevState,
2550
+ runs: {
2551
+ ...prevState.runs,
2552
+ [runId]: {
2553
+ ...prevState.runs[runId],
2554
+ expertKey,
2555
+ isReasoningActive: false
2556
+ }
2557
+ }
2558
+ },
2559
+ handled: false
2560
+ };
2561
+ }
2562
+ case "startStreamingRunResult": {
2563
+ return {
2564
+ newState: {
2565
+ ...prevState,
2566
+ runs: {
2567
+ ...prevState.runs,
2568
+ [runId]: {
2569
+ expertKey,
2570
+ reasoning: void 0,
2571
+ isReasoningActive: false,
2572
+ runResult: "",
2573
+ isRunResultActive: true
2574
+ }
2575
+ }
2576
+ },
2577
+ handled: true
2578
+ };
2579
+ }
2580
+ case "streamRunResult": {
2581
+ return {
2582
+ newState: {
2583
+ ...prevState,
2584
+ runs: {
2585
+ ...prevState.runs,
2586
+ [runId]: {
2587
+ ...prevState.runs[runId],
2588
+ expertKey,
2589
+ runResult: (prevState.runs[runId]?.runResult ?? "") + event.delta
2590
+ }
2591
+ }
2592
+ },
2593
+ handled: true
2594
+ };
2595
+ }
2596
+ case "completeStreamingRunResult": {
2597
+ return {
2598
+ newState: {
2599
+ ...prevState,
2600
+ runs: {
2601
+ ...prevState.runs,
2602
+ [runId]: {
2603
+ ...prevState.runs[runId],
2604
+ expertKey,
2605
+ isRunResultActive: false
2606
+ }
2607
+ }
2608
+ },
2609
+ handled: true
2610
+ };
2611
+ }
2612
+ default:
2613
+ return { newState: prevState, handled: false };
2614
+ }
2615
+ }
2616
+ function useRun() {
2617
+ const [activities, setActivities] = useState([]);
2618
+ const [streaming, setStreaming] = useState({ runs: {} });
2619
+ const [eventCount, setEventCount] = useState(0);
2620
+ const [isComplete, setIsComplete] = useState(false);
2621
+ const stateRef = useRef(createInitialActivityProcessState());
2622
+ const clearStreaming = useCallback(() => {
2623
+ setStreaming({ runs: {} });
2624
+ }, []);
2625
+ const handleStreamingEvent = useCallback((event) => {
2626
+ let handled = false;
2627
+ setStreaming((prev) => {
2628
+ const result = processStreamingEvent(event, prev);
2629
+ handled = result.handled;
2630
+ return result.newState;
2631
+ });
2632
+ return handled;
2633
+ }, []);
2634
+ const processEvent = useCallback((event) => {
2635
+ const newActivities = [];
2636
+ const addActivity = (activity) => newActivities.push(activity);
2637
+ processRunEventToActivity(stateRef.current, event, addActivity);
2638
+ if (newActivities.length > 0) {
2639
+ setActivities((prev) => [...prev, ...newActivities]);
2640
+ }
2641
+ const rootRunComplete = Array.from(stateRef.current.runStates.values()).some(
2642
+ (rs) => rs.isComplete && !rs.delegatedBy
2643
+ );
2644
+ setIsComplete(rootRunComplete);
2645
+ }, []);
2646
+ const clearRunStreaming = useCallback((runId) => {
2647
+ setStreaming((prev) => {
2648
+ const { [runId]: _, ...rest } = prev.runs;
2649
+ return { runs: rest };
2650
+ });
2651
+ }, []);
2652
+ const addEvent = useCallback(
2653
+ (event) => {
2654
+ if (isStreamingEvent(event)) {
2655
+ const handled = handleStreamingEvent(event);
2656
+ if (handled) {
2657
+ setEventCount((prev) => prev + 1);
2658
+ return;
2659
+ }
2660
+ }
2661
+ if ("type" in event && "runId" in event && (event.type === "completeRun" || event.type === "stopRunByError")) {
2662
+ clearRunStreaming(event.runId);
2663
+ }
2664
+ processEvent(event);
2665
+ setEventCount((prev) => prev + 1);
2666
+ },
2667
+ [handleStreamingEvent, clearRunStreaming, processEvent]
2668
+ );
2669
+ const appendHistoricalEvents = useCallback((historicalEvents) => {
2670
+ const newActivities = [];
2671
+ const addActivity = (activity) => newActivities.push(activity);
2672
+ for (const event of historicalEvents) {
2673
+ processRunEventToActivity(stateRef.current, event, addActivity);
2674
+ }
2675
+ if (newActivities.length > 0) {
2676
+ setActivities((prev) => [...prev, ...newActivities]);
2677
+ }
2678
+ setEventCount((prev) => prev + historicalEvents.length);
2679
+ const rootRunComplete = Array.from(stateRef.current.runStates.values()).some(
2680
+ (rs) => rs.isComplete && !rs.delegatedBy
2681
+ );
2682
+ setIsComplete(rootRunComplete);
2683
+ }, []);
2684
+ return {
2685
+ activities,
2686
+ streaming,
2687
+ isComplete,
2688
+ eventCount,
2689
+ addEvent,
2690
+ appendHistoricalEvents,
2691
+ clearStreaming
2692
+ };
2693
+ }
2694
+ var useRuntimeInfo = (options) => {
2695
+ const [runtimeInfo, setRuntimeInfo] = useState({
2696
+ status: "initializing",
2697
+ runtimeVersion: options.initialConfig.runtimeVersion,
2698
+ expertName: options.initialExpertName,
2699
+ model: options.initialConfig.model,
2700
+ maxSteps: options.initialConfig.maxSteps,
2701
+ maxRetries: options.initialConfig.maxRetries,
2702
+ timeout: options.initialConfig.timeout,
2703
+ activeSkills: [],
2704
+ contextWindowUsage: options.initialConfig.contextWindowUsage
2705
+ });
2706
+ const handleEvent = useCallback((event) => {
2707
+ if (event.type === "initializeRuntime") {
2708
+ setRuntimeInfo((prev) => ({
2709
+ runtimeVersion: event.runtimeVersion,
2710
+ expertName: event.expertName,
2711
+ model: event.model,
2712
+ maxSteps: event.maxSteps,
2713
+ maxRetries: event.maxRetries,
2714
+ timeout: event.timeout,
2715
+ currentStep: 1,
2716
+ status: "running",
2717
+ query: event.query,
2718
+ statusChangedAt: Date.now(),
2719
+ activeSkills: [],
2720
+ contextWindowUsage: prev.contextWindowUsage
2721
+ }));
2722
+ return { initialized: true };
2723
+ }
2724
+ if (event.type === "skillConnected") {
2725
+ setRuntimeInfo((prev) => ({
2726
+ ...prev,
2727
+ activeSkills: [...prev.activeSkills, event.skillName]
2728
+ }));
2729
+ return null;
2730
+ }
2731
+ if (event.type === "skillDisconnected") {
2732
+ setRuntimeInfo((prev) => ({
2733
+ ...prev,
2734
+ activeSkills: prev.activeSkills.filter((s) => s !== event.skillName)
2735
+ }));
2736
+ return null;
2737
+ }
2738
+ if ("stepNumber" in event) {
2739
+ const isComplete = event.type === "completeRun";
2740
+ const isStopped = STOP_EVENT_TYPES.includes(event.type);
2741
+ const checkpoint = "nextCheckpoint" in event ? event.nextCheckpoint : "checkpoint" in event ? event.checkpoint : void 0;
2742
+ setRuntimeInfo((prev) => ({
2743
+ ...prev,
2744
+ currentStep: event.stepNumber,
2745
+ status: isComplete ? "completed" : isStopped ? "stopped" : "running",
2746
+ ...isComplete || isStopped ? { statusChangedAt: Date.now() } : {},
2747
+ ...checkpoint?.contextWindowUsage !== void 0 ? { contextWindowUsage: checkpoint.contextWindowUsage } : {}
2748
+ }));
2749
+ if (isComplete) return { completed: true };
2750
+ if (isStopped) return { stopped: true };
2751
+ }
2752
+ return null;
2753
+ }, []);
2754
+ const setExpertName = useCallback((expertName) => {
2755
+ setRuntimeInfo((prev) => ({ ...prev, expertName }));
2756
+ }, []);
2757
+ const setQuery = useCallback((query) => {
2758
+ setRuntimeInfo((prev) => ({ ...prev, query }));
2759
+ }, []);
2760
+ const setCurrentStep = useCallback((step) => {
2761
+ setRuntimeInfo((prev) => ({ ...prev, currentStep: step }));
2762
+ }, []);
2763
+ const setContextWindowUsage = useCallback((contextWindowUsage) => {
2764
+ setRuntimeInfo((prev) => ({ ...prev, contextWindowUsage }));
2765
+ }, []);
2766
+ return {
2767
+ runtimeInfo,
2768
+ handleEvent,
2769
+ setExpertName,
2770
+ setQuery,
2771
+ setCurrentStep,
2772
+ setContextWindowUsage
2773
+ };
2774
+ };
2775
+ var useLatestRef = (value) => {
2776
+ const ref = useRef(value);
2777
+ useInsertionEffect(() => {
2778
+ ref.current = value;
2779
+ });
2780
+ return ref;
2781
+ };
2782
+
2783
+ // ../../packages/tui-components/src/hooks/use-text-input.ts
2784
+ var useTextInput = (options) => {
2785
+ const [input, setInput] = useState("");
2786
+ const inputRef = useLatestRef(input);
2787
+ const onSubmitRef = useLatestRef(options.onSubmit);
2788
+ const onCancelRef = useLatestRef(options.onCancel);
2789
+ const handleInput = useCallback(
2790
+ (inputChar, key) => {
2791
+ if (key.escape) {
2792
+ setInput("");
2793
+ onCancelRef.current?.();
2794
+ return;
2795
+ }
2796
+ if (key.return && inputRef.current.trim()) {
2797
+ onSubmitRef.current(inputRef.current.trim());
2798
+ setInput("");
2799
+ return;
2800
+ }
2801
+ if (key.backspace || key.delete) {
2802
+ setInput((prev) => prev.slice(0, -1));
2803
+ return;
2804
+ }
2805
+ if (!key.ctrl && !key.meta && inputChar) {
2806
+ setInput((prev) => prev + inputChar);
2807
+ }
2808
+ },
2809
+ [inputRef, onSubmitRef, onCancelRef]
2810
+ );
2811
+ const reset = useCallback(() => {
2812
+ setInput("");
2813
+ }, []);
2814
+ return { input, handleInput, reset };
2815
+ };
7
2816
 
2817
+ // ../../packages/tui-components/src/hooks/ui/use-expert-selector.ts
2818
+ var useExpertSelector = (options) => {
2819
+ const { experts, onExpertSelect, extraKeyHandler } = options;
2820
+ const [inputMode, setInputMode] = useState(false);
2821
+ const { selectedIndex, handleNavigation } = useListNavigation({
2822
+ items: experts,
2823
+ onSelect: (expert) => onExpertSelect(expert.key)
2824
+ });
2825
+ const { input, handleInput, reset } = useTextInput({
2826
+ onSubmit: (value) => {
2827
+ onExpertSelect(value);
2828
+ setInputMode(false);
2829
+ },
2830
+ onCancel: () => setInputMode(false)
2831
+ });
2832
+ const handleKeyInput = useCallback(
2833
+ (inputChar, key) => {
2834
+ if (inputMode) {
2835
+ handleInput(inputChar, key);
2836
+ return;
2837
+ }
2838
+ if (handleNavigation(inputChar, key)) return;
2839
+ if (extraKeyHandler?.(inputChar, key)) return;
2840
+ if (inputChar === "i") {
2841
+ reset();
2842
+ setInputMode(true);
2843
+ }
2844
+ },
2845
+ [inputMode, handleInput, handleNavigation, extraKeyHandler, reset]
2846
+ );
2847
+ return {
2848
+ inputMode,
2849
+ input,
2850
+ selectedIndex,
2851
+ handleKeyInput
2852
+ };
2853
+ };
2854
+ var ExpertList = ({
2855
+ experts,
2856
+ selectedIndex,
2857
+ showSource = false,
2858
+ inline = false,
2859
+ maxItems
2860
+ }) => {
2861
+ const displayExperts = maxItems ? experts.slice(0, maxItems) : experts;
2862
+ if (displayExperts.length === 0) {
2863
+ return /* @__PURE__ */ jsx(Text, { color: "gray", children: "No experts found." });
2864
+ }
2865
+ const items = displayExperts.map((expert, index) => /* @__PURE__ */ jsxs(Text, { color: index === selectedIndex ? "cyan" : "gray", children: [
2866
+ index === selectedIndex ? ">" : " ",
2867
+ " ",
2868
+ showSource ? expert.key : expert.name,
2869
+ showSource && expert.source && /* @__PURE__ */ jsxs(Fragment, { children: [
2870
+ " ",
2871
+ /* @__PURE__ */ jsxs(Text, { color: expert.source === "configured" ? "green" : "yellow", children: [
2872
+ "[",
2873
+ expert.source === "configured" ? "config" : "recent",
2874
+ "]"
2875
+ ] })
2876
+ ] }),
2877
+ inline ? " " : ""
2878
+ ] }, expert.key));
2879
+ return inline ? /* @__PURE__ */ jsx(Box, { children: items }) : /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: items });
2880
+ };
2881
+ var ExpertSelectorBase = ({
2882
+ experts,
2883
+ hint,
2884
+ onExpertSelect,
2885
+ showSource = false,
2886
+ inline = false,
2887
+ maxItems = UI_CONSTANTS.MAX_VISIBLE_LIST_ITEMS,
2888
+ extraKeyHandler
2889
+ }) => {
2890
+ const { inputMode, input, selectedIndex, handleKeyInput } = useExpertSelector({
2891
+ experts,
2892
+ onExpertSelect,
2893
+ extraKeyHandler
2894
+ });
2895
+ useInput(handleKeyInput);
2896
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: inline ? "row" : "column", children: [
2897
+ !inputMode && /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
2898
+ /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { color: "cyan", children: hint }) }),
2899
+ /* @__PURE__ */ jsx(
2900
+ ExpertList,
2901
+ {
2902
+ experts,
2903
+ selectedIndex,
2904
+ showSource,
2905
+ inline,
2906
+ maxItems
2907
+ }
2908
+ )
2909
+ ] }),
2910
+ inputMode && /* @__PURE__ */ jsxs(Box, { children: [
2911
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Expert: " }),
2912
+ /* @__PURE__ */ jsx(Text, { color: "white", children: input }),
2913
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
2914
+ ] })
2915
+ ] });
2916
+ };
2917
+ var BrowsingExpertsInput = ({
2918
+ experts,
2919
+ onExpertSelect,
2920
+ onSwitchToHistory
2921
+ }) => {
2922
+ const extraKeyHandler = useCallback(
2923
+ (inputChar) => {
2924
+ if (inputChar === "h") {
2925
+ onSwitchToHistory();
2926
+ return true;
2927
+ }
2928
+ return false;
2929
+ },
2930
+ [onSwitchToHistory]
2931
+ );
2932
+ const hint = `Experts ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.SELECT} ${KEY_HINTS.INPUT} ${KEY_HINTS.HISTORY} ${KEY_HINTS.CANCEL}`;
2933
+ return /* @__PURE__ */ jsx(
2934
+ ExpertSelectorBase,
2935
+ {
2936
+ experts,
2937
+ hint,
2938
+ onExpertSelect,
2939
+ showSource: true,
2940
+ maxItems: UI_CONSTANTS.MAX_VISIBLE_LIST_ITEMS,
2941
+ extraKeyHandler
2942
+ }
2943
+ );
2944
+ };
2945
+ var BrowsingHistoryInput = ({
2946
+ jobs,
2947
+ onJobSelect,
2948
+ onJobResume,
2949
+ onSwitchToExperts
2950
+ }) => /* @__PURE__ */ jsx(
2951
+ ListBrowser,
2952
+ {
2953
+ title: `Job History ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.RESUME} ${KEY_HINTS.CHECKPOINTS} ${KEY_HINTS.NEW}`,
2954
+ items: jobs,
2955
+ onSelect: onJobResume,
2956
+ emptyMessage: "No jobs found. Press n to start a new job.",
2957
+ extraKeyHandler: (char, _key, selected) => {
2958
+ if (char === "c" && selected) {
2959
+ onJobSelect(selected);
2960
+ return true;
2961
+ }
2962
+ if (char === "n") {
2963
+ onSwitchToExperts();
2964
+ return true;
2965
+ }
2966
+ return false;
2967
+ },
2968
+ renderItem: (job, isSelected) => /* @__PURE__ */ jsxs(Text, { color: isSelected ? "cyan" : "gray", children: [
2969
+ isSelected ? ">" : " ",
2970
+ " ",
2971
+ job.expertKey,
2972
+ " - ",
2973
+ job.totalSteps,
2974
+ " steps (",
2975
+ job.jobId,
2976
+ ") (",
2977
+ formatTimestamp(job.startedAt),
2978
+ ")"
2979
+ ] }, job.jobId)
2980
+ }
2981
+ );
2982
+ var BrowserRouter = ({ inputState, showEventsHint = true }) => {
2983
+ const ctx = useInputAreaContext();
2984
+ const handleEventSelect = useCallback(
2985
+ (event) => {
2986
+ if (inputState.type === "browsingEvents") {
2987
+ ctx.onEventSelect(inputState, event);
2988
+ }
2989
+ },
2990
+ [ctx.onEventSelect, inputState]
2991
+ );
2992
+ switch (inputState.type) {
2993
+ case "browsingHistory":
2994
+ return /* @__PURE__ */ jsx(
2995
+ BrowsingHistoryInput,
2996
+ {
2997
+ jobs: inputState.jobs,
2998
+ onJobSelect: ctx.onJobSelect,
2999
+ onJobResume: ctx.onJobResume,
3000
+ onSwitchToExperts: ctx.onSwitchToExperts
3001
+ }
3002
+ );
3003
+ case "browsingExperts":
3004
+ return /* @__PURE__ */ jsx(
3005
+ BrowsingExpertsInput,
3006
+ {
3007
+ experts: inputState.experts,
3008
+ onExpertSelect: ctx.onExpertSelect,
3009
+ onSwitchToHistory: ctx.onSwitchToHistory
3010
+ }
3011
+ );
3012
+ case "browsingCheckpoints":
3013
+ return /* @__PURE__ */ jsx(
3014
+ BrowsingCheckpointsInput,
3015
+ {
3016
+ job: inputState.job,
3017
+ checkpoints: inputState.checkpoints,
3018
+ onCheckpointSelect: ctx.onCheckpointSelect,
3019
+ onCheckpointResume: ctx.onCheckpointResume,
3020
+ onBack: ctx.onBack,
3021
+ showEventsHint
3022
+ }
3023
+ );
3024
+ case "browsingEvents":
3025
+ return /* @__PURE__ */ jsx(
3026
+ BrowsingEventsInput,
3027
+ {
3028
+ checkpoint: inputState.checkpoint,
3029
+ events: inputState.events,
3030
+ onEventSelect: handleEventSelect,
3031
+ onBack: ctx.onBack
3032
+ }
3033
+ );
3034
+ case "browsingEventDetail":
3035
+ return /* @__PURE__ */ jsx(BrowsingEventDetailInput, { event: inputState.selectedEvent, onBack: ctx.onBack });
3036
+ default:
3037
+ return assertNever(inputState);
3038
+ }
3039
+ };
3040
+ var ActionRowSimple = ({
3041
+ indicatorColor,
3042
+ text,
3043
+ textDimColor = false
3044
+ }) => /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
3045
+ /* @__PURE__ */ jsx(Box, { paddingRight: 1, children: /* @__PURE__ */ jsx(Text, { color: indicatorColor, children: INDICATOR.BULLET }) }),
3046
+ /* @__PURE__ */ jsx(Text, { color: "white", dimColor: textDimColor, children: text })
3047
+ ] }) });
3048
+ var ActionRow = ({ indicatorColor, label, summary, children }) => /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3049
+ /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
3050
+ /* @__PURE__ */ jsx(Text, { color: indicatorColor, children: INDICATOR.BULLET }),
3051
+ /* @__PURE__ */ jsx(Text, { color: "white", children: label }),
3052
+ summary && /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: summary })
3053
+ ] }),
3054
+ /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
3055
+ /* @__PURE__ */ jsx(Box, { paddingRight: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: INDICATOR.TREE }) }),
3056
+ children
3057
+ ] })
3058
+ ] });
3059
+ var CheckpointActionRow = ({ action }) => {
3060
+ if (action.type === "parallelGroup") {
3061
+ return renderParallelGroup(action);
3062
+ }
3063
+ const actionElement = renderAction(action);
3064
+ if (!actionElement) return null;
3065
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3066
+ action.reasoning && renderReasoning(action.reasoning),
3067
+ actionElement
3068
+ ] });
3069
+ };
3070
+ function renderParallelGroup(group) {
3071
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3072
+ group.reasoning && renderReasoning(group.reasoning),
3073
+ group.activities.map((activity, index) => {
3074
+ const actionElement = renderAction(activity);
3075
+ if (!actionElement) return null;
3076
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: actionElement }, activity.id || `${activity.type}-${index}`);
3077
+ })
3078
+ ] });
3079
+ }
3080
+ function renderReasoning(text) {
3081
+ const lines = text.split("\n");
3082
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "white", label: "Reasoning", children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsx(Text, { dimColor: true, wrap: "wrap", children: line }, `reasoning-${idx}`)) }) });
3083
+ }
3084
+ function renderAction(action) {
3085
+ const color = action.type === "error" || "error" in action && action.error ? "red" : "green";
3086
+ switch (action.type) {
3087
+ case "query":
3088
+ return renderQuery(action.text, action.runId);
3089
+ case "retry":
3090
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "yellow", label: "Retry", children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: action.message || action.error }) });
3091
+ case "complete":
3092
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "green", label: "Run Results", children: /* @__PURE__ */ jsx(Text, { children: action.text }) });
3093
+ case "attemptCompletion": {
3094
+ if (action.error) {
3095
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "red", label: "Completion Failed", children: /* @__PURE__ */ jsx(Text, { color: "red", children: action.error }) });
3096
+ }
3097
+ const remaining = action.remainingTodos?.filter((t) => !t.completed) ?? [];
3098
+ if (remaining.length > 0) {
3099
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "yellow", label: "Completion Blocked", children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3100
+ remaining.length,
3101
+ " remaining task",
3102
+ remaining.length > 1 ? "s" : ""
3103
+ ] }) });
3104
+ }
3105
+ return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: "green", text: "Completion Accepted" });
3106
+ }
3107
+ case "todo":
3108
+ return renderTodo(action, color);
3109
+ case "clearTodo":
3110
+ return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: color, text: "Todo Cleared" });
3111
+ case "readTextFile":
3112
+ return renderReadTextFile(action, color);
3113
+ case "writeTextFile":
3114
+ return renderWriteTextFile(action, color);
3115
+ case "editTextFile":
3116
+ return renderEditTextFile(action, color);
3117
+ case "appendTextFile":
3118
+ return renderAppendTextFile(action, color);
3119
+ case "deleteFile":
3120
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Delete", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Removed" }) });
3121
+ case "deleteDirectory":
3122
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Delete Dir", summary: shortenPath(action.path), children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3123
+ "Removed",
3124
+ action.recursive ? " (recursive)" : ""
3125
+ ] }) });
3126
+ case "moveFile":
3127
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Move", summary: shortenPath(action.source), children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3128
+ "\u2192 ",
3129
+ shortenPath(action.destination, 30)
3130
+ ] }) });
3131
+ case "createDirectory":
3132
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Mkdir", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Created" }) });
3133
+ case "listDirectory":
3134
+ return renderListDirectory(action, color);
3135
+ case "getFileInfo":
3136
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Info", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Fetched" }) });
3137
+ case "readPdfFile":
3138
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "PDF", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Read" }) });
3139
+ case "readImageFile":
3140
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Image", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Read" }) });
3141
+ case "exec":
3142
+ return renderExec(action, color);
3143
+ case "delegate":
3144
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "yellow", label: action.delegateExpertKey, children: /* @__PURE__ */ jsx(
3145
+ Text,
3146
+ {
3147
+ dimColor: true,
3148
+ children: `{"query":"${truncateText(action.query, UI_CONSTANTS.TRUNCATE_TEXT_MEDIUM)}"}`
3149
+ }
3150
+ ) });
3151
+ case "delegationComplete":
3152
+ return /* @__PURE__ */ jsx(
3153
+ ActionRowSimple,
3154
+ {
3155
+ indicatorColor: "green",
3156
+ text: `Delegation Complete (${action.count} delegate${action.count > 1 ? "s" : ""} returned)`
3157
+ }
3158
+ );
3159
+ case "interactiveTool":
3160
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "yellow", label: `Interactive: ${action.toolName}`, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: truncateText(JSON.stringify(action.args), UI_CONSTANTS.TRUNCATE_TEXT_MEDIUM) }) });
3161
+ case "generalTool":
3162
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: action.toolName, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: truncateText(JSON.stringify(action.args), UI_CONSTANTS.TRUNCATE_TEXT_MEDIUM) }) });
3163
+ case "error":
3164
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "red", label: action.errorName ?? "Error", children: /* @__PURE__ */ jsx(Text, { color: "red", children: action.error ?? "Unknown error" }) });
3165
+ default: {
3166
+ return null;
3167
+ }
3168
+ }
3169
+ }
3170
+ function renderTodo(action, color) {
3171
+ const { newTodos, completedTodos, todos } = action;
3172
+ const hasNewTodos = newTodos && newTodos.length > 0;
3173
+ const hasCompletedTodos = completedTodos && completedTodos.length > 0;
3174
+ if (!hasNewTodos && !hasCompletedTodos) {
3175
+ return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: color, text: "Todo No changes" });
3176
+ }
3177
+ const labelParts = [];
3178
+ if (hasNewTodos) {
3179
+ labelParts.push(`Added ${newTodos.length} task${newTodos.length > 1 ? "s" : ""}`);
3180
+ }
3181
+ if (hasCompletedTodos) {
3182
+ labelParts.push(
3183
+ `Completed ${completedTodos.length} task${completedTodos.length > 1 ? "s" : ""}`
3184
+ );
3185
+ }
3186
+ const label = `Todo ${labelParts.join(", ")}`;
3187
+ const completedTitles = hasCompletedTodos ? completedTodos.map((id) => todos.find((t) => t.id === id)?.title).filter((t) => t !== void 0) : [];
3188
+ if (!hasNewTodos && completedTitles.length === 0) {
3189
+ return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: color, text: label });
3190
+ }
3191
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label, children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3192
+ hasNewTodos && newTodos.slice(0, RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW).map((todo, idx) => /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3193
+ "\u25CB ",
3194
+ todo
3195
+ ] }, `todo-${idx}`)),
3196
+ hasNewTodos && newTodos.length > RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3197
+ "... +",
3198
+ newTodos.length - RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW,
3199
+ " more"
3200
+ ] }),
3201
+ completedTitles.slice(0, RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW).map((title, idx) => /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3202
+ "\u2713 ",
3203
+ title
3204
+ ] }, `completed-${idx}`)),
3205
+ completedTitles.length > RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3206
+ "... +",
3207
+ completedTitles.length - RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW,
3208
+ " more"
3209
+ ] })
3210
+ ] }) });
3211
+ }
3212
+ function renderReadTextFile(action, color) {
3213
+ const { path: path6, content, from, to } = action;
3214
+ const lineRange = from !== void 0 && to !== void 0 ? `#${from}-${to}` : "";
3215
+ const lines = content?.split("\n") ?? [];
3216
+ return /* @__PURE__ */ jsx(
3217
+ ActionRow,
3218
+ {
3219
+ indicatorColor: color,
3220
+ label: "Read Text File",
3221
+ summary: `${shortenPath(path6)}${lineRange}`,
3222
+ children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsx(Box, { flexDirection: "row", gap: 1, children: /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: line }) }, `read-${idx}`)) })
3223
+ }
3224
+ );
3225
+ }
3226
+ function renderWriteTextFile(action, color) {
3227
+ const { path: path6, text } = action;
3228
+ const lines = text.split("\n");
3229
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Write Text File", summary: shortenPath(path6), children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
3230
+ /* @__PURE__ */ jsx(Text, { color: "green", dimColor: true, children: "+" }),
3231
+ /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: line })
3232
+ ] }, `write-${idx}`)) }) });
3233
+ }
3234
+ function renderEditTextFile(action, color) {
3235
+ const { path: path6, oldText, newText } = action;
3236
+ const oldLines = oldText.split("\n");
3237
+ const newLines = newText.split("\n");
3238
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Edit Text File", summary: shortenPath(path6), children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3239
+ oldLines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
3240
+ /* @__PURE__ */ jsx(Text, { color: "red", dimColor: true, children: "-" }),
3241
+ /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: line })
3242
+ ] }, `old-${idx}`)),
3243
+ newLines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
3244
+ /* @__PURE__ */ jsx(Text, { color: "green", dimColor: true, children: "+" }),
3245
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: line })
3246
+ ] }, `new-${idx}`))
3247
+ ] }) });
3248
+ }
3249
+ function renderAppendTextFile(action, color) {
3250
+ const { path: path6, text } = action;
3251
+ const lines = text.split("\n");
3252
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Append Text File", summary: shortenPath(path6), children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
3253
+ /* @__PURE__ */ jsx(Text, { color: "green", dimColor: true, children: "+" }),
3254
+ /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: line })
3255
+ ] }, `append-${idx}`)) }) });
3256
+ }
3257
+ function renderListDirectory(action, color) {
3258
+ const { path: path6, items } = action;
3259
+ const itemLines = items?.map((item) => `${item.type === "directory" ? "\u{1F4C1}" : "\u{1F4C4}"} ${item.name}`) ?? [];
3260
+ const { visible, remaining } = summarizeOutput(itemLines, RENDER_CONSTANTS.LIST_DIR_MAX_ITEMS);
3261
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "List", summary: shortenPath(path6), children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3262
+ visible.map((line, idx) => /* @__PURE__ */ jsx(Text, { dimColor: true, children: truncateText(line, UI_CONSTANTS.TRUNCATE_TEXT_DEFAULT) }, `dir-${idx}`)),
3263
+ remaining > 0 && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3264
+ "... +",
3265
+ remaining,
3266
+ " more"
3267
+ ] })
3268
+ ] }) });
3269
+ }
3270
+ function renderExec(action, color) {
3271
+ const { command, args, cwd, output } = action;
3272
+ const cwdPart = cwd ? ` ${shortenPath(cwd, 40)}` : "";
3273
+ const cmdLine = truncateText(
3274
+ `${command} ${args.join(" ")}${cwdPart}`,
3275
+ UI_CONSTANTS.TRUNCATE_TEXT_DEFAULT
3276
+ );
3277
+ const outputLines = output?.split("\n") ?? [];
3278
+ const { visible, remaining } = summarizeOutput(
3279
+ outputLines,
3280
+ RENDER_CONSTANTS.EXEC_OUTPUT_MAX_LINES
3281
+ );
3282
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: `Bash ${cmdLine}`, children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3283
+ visible.map((line, idx) => /* @__PURE__ */ jsx(Text, { dimColor: true, children: truncateText(line, UI_CONSTANTS.TRUNCATE_TEXT_DEFAULT) }, `out-${idx}`)),
3284
+ remaining > 0 && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3285
+ "... +",
3286
+ remaining,
3287
+ " more"
3288
+ ] })
3289
+ ] }) });
3290
+ }
3291
+ function renderQuery(text, runId) {
3292
+ const lines = text.split("\n");
3293
+ const shortRunId = runId.slice(0, 8);
3294
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "cyan", label: "Query", summary: `(${shortRunId})`, children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsx(Text, { dimColor: true, wrap: "wrap", children: line }, `query-${idx}`)) }) });
3295
+ }
3296
+ var RunSetting = ({
3297
+ info,
3298
+ eventCount,
3299
+ isEditing,
3300
+ expertName,
3301
+ onQuerySubmit
3302
+ }) => {
3303
+ const { input, handleInput } = useTextInput({
3304
+ onSubmit: onQuerySubmit ?? (() => {
3305
+ })
3306
+ });
3307
+ useInput(handleInput, { isActive: isEditing });
3308
+ const displayExpertName = expertName ?? info.expertName;
3309
+ const skills = info.activeSkills.length > 0 ? info.activeSkills.join(", ") : "";
3310
+ const step = info.currentStep !== void 0 ? String(info.currentStep) : "";
3311
+ const usagePercent = (info.contextWindowUsage * 100).toFixed(1);
3312
+ return /* @__PURE__ */ jsxs(
3313
+ Box,
3314
+ {
3315
+ flexDirection: "column",
3316
+ borderStyle: "single",
3317
+ borderColor: "gray",
3318
+ borderTop: true,
3319
+ borderBottom: false,
3320
+ borderLeft: false,
3321
+ borderRight: false,
3322
+ children: [
3323
+ /* @__PURE__ */ jsxs(Text, { children: [
3324
+ /* @__PURE__ */ jsx(Text, { bold: true, color: "cyan", children: "Perstack" }),
3325
+ info.runtimeVersion && /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
3326
+ " (v",
3327
+ info.runtimeVersion,
3328
+ ")"
3329
+ ] })
3330
+ ] }),
3331
+ /* @__PURE__ */ jsxs(Text, { children: [
3332
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Expert: " }),
3333
+ /* @__PURE__ */ jsx(Text, { color: "white", children: displayExpertName }),
3334
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Skills: " }),
3335
+ /* @__PURE__ */ jsx(Text, { color: "green", children: skills })
3336
+ ] }),
3337
+ /* @__PURE__ */ jsxs(Text, { children: [
3338
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Status: " }),
3339
+ /* @__PURE__ */ jsx(
3340
+ Text,
3341
+ {
3342
+ color: info.status === "running" ? "green" : info.status === "completed" ? "cyan" : "yellow",
3343
+ children: info.status
3344
+ }
3345
+ ),
3346
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Step: " }),
3347
+ /* @__PURE__ */ jsx(Text, { color: "white", children: step }),
3348
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Events: " }),
3349
+ /* @__PURE__ */ jsx(Text, { color: "white", children: eventCount }),
3350
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Usage: " }),
3351
+ /* @__PURE__ */ jsxs(Text, { color: "white", children: [
3352
+ usagePercent,
3353
+ "%"
3354
+ ] })
3355
+ ] }),
3356
+ /* @__PURE__ */ jsxs(Text, { children: [
3357
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Model: " }),
3358
+ /* @__PURE__ */ jsx(Text, { color: "white", children: info.model })
3359
+ ] }),
3360
+ /* @__PURE__ */ jsxs(Box, { children: [
3361
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Query: " }),
3362
+ isEditing ? /* @__PURE__ */ jsxs(Fragment, { children: [
3363
+ /* @__PURE__ */ jsx(Text, { color: "white", children: input }),
3364
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
3365
+ ] }) : /* @__PURE__ */ jsx(Text, { color: "white", children: info.query })
3366
+ ] })
3367
+ ]
3368
+ }
3369
+ );
3370
+ };
3371
+ var StreamingDisplay = ({ streaming }) => {
3372
+ const activeRuns = Object.entries(streaming.runs).filter(
3373
+ ([, run]) => run.isReasoningActive || run.isRunResultActive
3374
+ );
3375
+ if (activeRuns.length === 0) return null;
3376
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginY: 1, children: activeRuns.map(([runId, run]) => /* @__PURE__ */ jsx(StreamingRunSection, { run }, runId)) });
3377
+ };
3378
+ function StreamingRunSection({ run }) {
3379
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3380
+ run.isReasoningActive && run.reasoning !== void 0 && /* @__PURE__ */ jsx(StreamingReasoning, { expertKey: run.expertKey, text: run.reasoning }),
3381
+ run.isRunResultActive && run.runResult !== void 0 && /* @__PURE__ */ jsx(StreamingRunResult, { expertKey: run.expertKey, text: run.runResult })
3382
+ ] });
3383
+ }
3384
+ function StreamingReasoning({
3385
+ expertKey,
3386
+ text
3387
+ }) {
3388
+ const lines = text.split("\n");
3389
+ const label = `[${formatExpertKey(expertKey)}] Reasoning...`;
3390
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "cyan", label, children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsx(Text, { dimColor: true, wrap: "wrap", children: line }, `streaming-reasoning-${idx}`)) }) });
3391
+ }
3392
+ function StreamingRunResult({
3393
+ expertKey,
3394
+ text
3395
+ }) {
3396
+ const lines = text.split("\n");
3397
+ const label = `[${formatExpertKey(expertKey)}] Generating...`;
3398
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "green", label, children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsx(Text, { wrap: "wrap", children: line }, `streaming-run-result-${idx}`)) }) });
3399
+ }
3400
+ function formatExpertKey(expertKey) {
3401
+ const atIndex = expertKey.lastIndexOf("@");
3402
+ if (atIndex > 0) {
3403
+ return expertKey.substring(0, atIndex);
3404
+ }
3405
+ return expertKey;
3406
+ }
3407
+ function getActivityKey(activityOrGroup, index) {
3408
+ return activityOrGroup.id || `activity-${index}`;
3409
+ }
3410
+ var RunBox = ({ node, isRoot }) => {
3411
+ if (isRoot) {
3412
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3413
+ node.activities.map((activity, index) => /* @__PURE__ */ jsx(CheckpointActionRow, { action: activity }, getActivityKey(activity, index))),
3414
+ node.children.map((child) => /* @__PURE__ */ jsx(RunBox, { node: child, isRoot: false }, child.runId))
3415
+ ] });
3416
+ }
3417
+ const shortRunId = node.runId.slice(0, 8);
3418
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "gray", marginLeft: 1, children: [
3419
+ /* @__PURE__ */ jsxs(Text, { dimColor: true, bold: true, children: [
3420
+ "[",
3421
+ node.expertKey,
3422
+ "] ",
3423
+ /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3424
+ "(",
3425
+ shortRunId,
3426
+ ")"
3427
+ ] })
3428
+ ] }),
3429
+ node.activities.map((activity, index) => /* @__PURE__ */ jsx(CheckpointActionRow, { action: activity }, getActivityKey(activity, index))),
3430
+ node.children.map((child) => /* @__PURE__ */ jsx(RunBox, { node: child, isRoot: false }, child.runId))
3431
+ ] });
3432
+ };
3433
+ function getActivityProps(activityOrGroup) {
3434
+ if (activityOrGroup.type === "parallelGroup") {
3435
+ const group = activityOrGroup;
3436
+ const firstActivity = group.activities[0];
3437
+ return {
3438
+ runId: group.runId,
3439
+ expertKey: group.expertKey,
3440
+ delegatedBy: firstActivity?.delegatedBy
3441
+ };
3442
+ }
3443
+ return activityOrGroup;
3444
+ }
3445
+ var ActivityLogPanel = ({ activities }) => {
3446
+ const rootNodes = useMemo(() => {
3447
+ const nodeMap = /* @__PURE__ */ new Map();
3448
+ const roots = [];
3449
+ const orphanChildren = /* @__PURE__ */ new Map();
3450
+ for (const activityOrGroup of activities) {
3451
+ const { runId, expertKey, delegatedBy } = getActivityProps(activityOrGroup);
3452
+ let node = nodeMap.get(runId);
3453
+ if (!node) {
3454
+ node = {
3455
+ runId,
3456
+ expertKey,
3457
+ activities: [],
3458
+ children: []
3459
+ };
3460
+ nodeMap.set(runId, node);
3461
+ const waitingChildren = orphanChildren.get(runId);
3462
+ if (waitingChildren) {
3463
+ for (const child of waitingChildren) {
3464
+ node.children.push(child);
3465
+ const rootIndex = roots.indexOf(child);
3466
+ if (rootIndex !== -1) {
3467
+ roots.splice(rootIndex, 1);
3468
+ }
3469
+ }
3470
+ orphanChildren.delete(runId);
3471
+ }
3472
+ if (delegatedBy) {
3473
+ const parentNode = nodeMap.get(delegatedBy.runId);
3474
+ if (parentNode) {
3475
+ parentNode.children.push(node);
3476
+ } else {
3477
+ const orphans = orphanChildren.get(delegatedBy.runId) ?? [];
3478
+ orphans.push(node);
3479
+ orphanChildren.set(delegatedBy.runId, orphans);
3480
+ roots.push(node);
3481
+ }
3482
+ } else {
3483
+ roots.push(node);
3484
+ }
3485
+ }
3486
+ node.activities.push(activityOrGroup);
3487
+ }
3488
+ return roots;
3489
+ }, [activities]);
3490
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: rootNodes.map((node) => /* @__PURE__ */ jsx(RunBox, { node, isRoot: true }, node.runId)) });
3491
+ };
3492
+ var ContinueInputPanel = ({
3493
+ isActive,
3494
+ runStatus,
3495
+ onSubmit
3496
+ }) => {
3497
+ const { input, handleInput } = useTextInput({
3498
+ onSubmit: (newQuery) => {
3499
+ if (isActive && newQuery.trim()) {
3500
+ onSubmit(newQuery.trim());
3501
+ }
3502
+ }
3503
+ });
3504
+ useInput(handleInput, { isActive });
3505
+ if (runStatus === "running") {
3506
+ return null;
3507
+ }
3508
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", borderStyle: "single", borderColor: "gray", children: [
3509
+ /* @__PURE__ */ jsxs(Text, { children: [
3510
+ /* @__PURE__ */ jsx(Text, { color: runStatus === "completed" ? "green" : "yellow", bold: true, children: runStatus === "completed" ? "Completed" : "Stopped" }),
3511
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: " - Enter a follow-up query or wait to exit" })
3512
+ ] }),
3513
+ /* @__PURE__ */ jsxs(Box, { children: [
3514
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Continue: " }),
3515
+ /* @__PURE__ */ jsx(Text, { children: input }),
3516
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
3517
+ ] })
3518
+ ] });
3519
+ };
3520
+ var StatusPanel = ({
3521
+ runtimeInfo,
3522
+ eventCount,
3523
+ runStatus
3524
+ }) => {
3525
+ if (runStatus !== "running") {
3526
+ return null;
3527
+ }
3528
+ return /* @__PURE__ */ jsx(RunSetting, { info: runtimeInfo, eventCount, isEditing: false });
3529
+ };
3530
+ var useExecutionState = (options) => {
3531
+ const { expertKey, query, config: config2, continueTimeoutMs, historicalEvents, onReady, onComplete } = options;
3532
+ const { exit } = useApp();
3533
+ const runState = useRun();
3534
+ const { runtimeInfo, handleEvent, setQuery } = useRuntimeInfo({
3535
+ initialExpertName: expertKey,
3536
+ initialConfig: config2
3537
+ });
3538
+ const [runStatus, setRunStatus] = useState("running");
3539
+ const [isAcceptingContinue, setIsAcceptingContinue] = useState(false);
3540
+ const timeoutRef = useRef(null);
3541
+ const clearTimeoutIfExists = useCallback(() => {
3542
+ if (timeoutRef.current) {
3543
+ clearTimeout(timeoutRef.current);
3544
+ timeoutRef.current = null;
3545
+ }
3546
+ }, []);
3547
+ const startExitTimeout = useCallback(() => {
3548
+ clearTimeoutIfExists();
3549
+ timeoutRef.current = setTimeout(() => {
3550
+ onComplete({ nextQuery: null });
3551
+ exit();
3552
+ }, continueTimeoutMs);
3553
+ }, [clearTimeoutIfExists, continueTimeoutMs, onComplete, exit]);
3554
+ useEffect(() => {
3555
+ setQuery(query);
3556
+ }, [query, setQuery]);
3557
+ useEffect(() => {
3558
+ if (historicalEvents && historicalEvents.length > 0) {
3559
+ runState.appendHistoricalEvents(historicalEvents);
3560
+ }
3561
+ }, [historicalEvents, runState.appendHistoricalEvents]);
3562
+ useEffect(() => {
3563
+ onReady((event) => {
3564
+ runState.addEvent(event);
3565
+ const result = handleEvent(event);
3566
+ if (result?.completed) {
3567
+ setRunStatus("completed");
3568
+ setIsAcceptingContinue(true);
3569
+ startExitTimeout();
3570
+ } else if (result?.stopped) {
3571
+ setRunStatus("stopped");
3572
+ setIsAcceptingContinue(true);
3573
+ startExitTimeout();
3574
+ }
3575
+ });
3576
+ }, [onReady, runState.addEvent, handleEvent, startExitTimeout]);
3577
+ useEffect(() => {
3578
+ return () => {
3579
+ clearTimeoutIfExists();
3580
+ };
3581
+ }, [clearTimeoutIfExists]);
3582
+ const handleContinueSubmit = useCallback(
3583
+ (newQuery) => {
3584
+ if (isAcceptingContinue && newQuery.trim()) {
3585
+ clearTimeoutIfExists();
3586
+ onComplete({ nextQuery: newQuery.trim() });
3587
+ exit();
3588
+ }
3589
+ },
3590
+ [isAcceptingContinue, clearTimeoutIfExists, onComplete, exit]
3591
+ );
3592
+ return {
3593
+ activities: runState.activities,
3594
+ streaming: runState.streaming,
3595
+ eventCount: runState.eventCount,
3596
+ runtimeInfo,
3597
+ runStatus,
3598
+ isAcceptingContinue,
3599
+ handleContinueSubmit,
3600
+ clearTimeout: clearTimeoutIfExists
3601
+ };
3602
+ };
3603
+ var ExecutionApp = (props) => {
3604
+ const { expertKey, query, config: config2, continueTimeoutMs, historicalEvents, onReady, onComplete } = props;
3605
+ const { exit } = useApp();
3606
+ const state = useExecutionState({
3607
+ expertKey,
3608
+ query,
3609
+ config: config2,
3610
+ continueTimeoutMs,
3611
+ historicalEvents,
3612
+ onReady,
3613
+ onComplete
3614
+ });
3615
+ useInput((input, key) => {
3616
+ if (key.ctrl && input === "c") {
3617
+ state.clearTimeout();
3618
+ exit();
3619
+ }
3620
+ });
3621
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3622
+ /* @__PURE__ */ jsx(ActivityLogPanel, { activities: state.activities }),
3623
+ /* @__PURE__ */ jsx(StreamingDisplay, { streaming: state.streaming }),
3624
+ /* @__PURE__ */ jsx(
3625
+ StatusPanel,
3626
+ {
3627
+ runtimeInfo: state.runtimeInfo,
3628
+ eventCount: state.eventCount,
3629
+ runStatus: state.runStatus
3630
+ }
3631
+ ),
3632
+ /* @__PURE__ */ jsx(
3633
+ ContinueInputPanel,
3634
+ {
3635
+ isActive: state.isAcceptingContinue,
3636
+ runStatus: state.runStatus,
3637
+ onSubmit: state.handleContinueSubmit
3638
+ }
3639
+ )
3640
+ ] });
3641
+ };
3642
+ function renderExecution(params) {
3643
+ const eventQueue = new EventQueue();
3644
+ const result = new Promise((resolve, reject) => {
3645
+ let resolved = false;
3646
+ const { waitUntilExit } = render(
3647
+ /* @__PURE__ */ jsx(
3648
+ ExecutionApp,
3649
+ {
3650
+ ...params,
3651
+ onReady: (handler) => {
3652
+ eventQueue.setHandler(handler);
3653
+ },
3654
+ onComplete: (result2) => {
3655
+ resolved = true;
3656
+ resolve(result2);
3657
+ }
3658
+ }
3659
+ )
3660
+ );
3661
+ waitUntilExit().then(() => {
3662
+ if (!resolved) {
3663
+ reject(new Error("Execution cancelled"));
3664
+ }
3665
+ }).catch(reject);
3666
+ });
3667
+ return {
3668
+ result,
3669
+ eventListener: (event) => {
3670
+ eventQueue.emit(event);
3671
+ }
3672
+ };
3673
+ }
3674
+ var selectionReducer = (_state, action) => {
3675
+ switch (action.type) {
3676
+ case "BROWSE_HISTORY":
3677
+ return { type: "browsingHistory", jobs: action.jobs };
3678
+ case "BROWSE_EXPERTS":
3679
+ return { type: "browsingExperts", experts: action.experts };
3680
+ case "SELECT_EXPERT":
3681
+ return { type: "enteringQuery", expertKey: action.expertKey };
3682
+ case "SELECT_JOB":
3683
+ return { type: "browsingCheckpoints", job: action.job, checkpoints: action.checkpoints };
3684
+ case "GO_BACK_FROM_CHECKPOINTS":
3685
+ return { type: "browsingHistory", jobs: action.jobs };
3686
+ default:
3687
+ return assertNever(action);
3688
+ }
3689
+ };
3690
+ var SelectionApp = (props) => {
3691
+ const {
3692
+ showHistory,
3693
+ initialExpertKey,
3694
+ initialQuery,
3695
+ initialCheckpoint,
3696
+ configuredExperts,
3697
+ recentExperts,
3698
+ historyJobs,
3699
+ onLoadCheckpoints,
3700
+ onComplete
3701
+ } = props;
3702
+ const { exit } = useApp();
3703
+ const allExperts = useMemo(() => {
3704
+ const configured = configuredExperts.map((e) => ({ ...e, source: "configured" }));
3705
+ const recent = recentExperts.filter((e) => !configured.some((c) => c.key === e.key)).map((e) => ({ ...e, source: "recent" }));
3706
+ return [...configured, ...recent];
3707
+ }, [configuredExperts, recentExperts]);
3708
+ const getInitialState = () => {
3709
+ if (initialExpertKey && !initialQuery) {
3710
+ return { type: "enteringQuery", expertKey: initialExpertKey };
3711
+ }
3712
+ if (showHistory && historyJobs.length > 0) {
3713
+ return { type: "browsingHistory", jobs: historyJobs };
3714
+ }
3715
+ return { type: "browsingExperts", experts: allExperts };
3716
+ };
3717
+ const [state, dispatch] = useReducer(selectionReducer, void 0, getInitialState);
3718
+ const [selectedCheckpoint, setSelectedCheckpoint] = useState(
3719
+ initialCheckpoint
3720
+ );
3721
+ useEffect(() => {
3722
+ if (initialExpertKey && initialQuery) {
3723
+ onComplete({
3724
+ expertKey: initialExpertKey,
3725
+ query: initialQuery,
3726
+ checkpoint: initialCheckpoint
3727
+ });
3728
+ exit();
3729
+ }
3730
+ }, [initialExpertKey, initialQuery, initialCheckpoint, onComplete, exit]);
3731
+ const { input: queryInput, handleInput: handleQueryInput } = useTextInput({
3732
+ onSubmit: (query) => {
3733
+ if (state.type === "enteringQuery" && query.trim()) {
3734
+ onComplete({
3735
+ expertKey: state.expertKey,
3736
+ query: query.trim(),
3737
+ checkpoint: selectedCheckpoint
3738
+ });
3739
+ exit();
3740
+ }
3741
+ }
3742
+ });
3743
+ useInput(handleQueryInput, { isActive: state.type === "enteringQuery" });
3744
+ const handleExpertSelect = useCallback((expertKey) => {
3745
+ dispatch({ type: "SELECT_EXPERT", expertKey });
3746
+ }, []);
3747
+ const handleJobSelect = useCallback(
3748
+ async (job) => {
3749
+ try {
3750
+ const checkpoints = await onLoadCheckpoints(job);
3751
+ dispatch({ type: "SELECT_JOB", job, checkpoints });
3752
+ } catch {
3753
+ dispatch({ type: "SELECT_JOB", job, checkpoints: [] });
3754
+ }
3755
+ },
3756
+ [onLoadCheckpoints]
3757
+ );
3758
+ const handleJobResume = useCallback(
3759
+ async (job) => {
3760
+ try {
3761
+ const checkpoints = await onLoadCheckpoints(job);
3762
+ const latestCheckpoint = checkpoints[0];
3763
+ if (latestCheckpoint) {
3764
+ setSelectedCheckpoint(latestCheckpoint);
3765
+ }
3766
+ dispatch({ type: "SELECT_EXPERT", expertKey: job.expertKey });
3767
+ } catch {
3768
+ dispatch({ type: "SELECT_EXPERT", expertKey: job.expertKey });
3769
+ }
3770
+ },
3771
+ [onLoadCheckpoints]
3772
+ );
3773
+ const handleCheckpointResume = useCallback(
3774
+ (checkpoint) => {
3775
+ setSelectedCheckpoint(checkpoint);
3776
+ if (state.type === "browsingCheckpoints") {
3777
+ dispatch({ type: "SELECT_EXPERT", expertKey: state.job.expertKey });
3778
+ }
3779
+ },
3780
+ [state]
3781
+ );
3782
+ const handleBack = useCallback(() => {
3783
+ if (state.type === "browsingCheckpoints") {
3784
+ dispatch({ type: "GO_BACK_FROM_CHECKPOINTS", jobs: historyJobs });
3785
+ }
3786
+ }, [state, historyJobs]);
3787
+ const handleSwitchToExperts = useCallback(() => {
3788
+ dispatch({ type: "BROWSE_EXPERTS", experts: allExperts });
3789
+ }, [allExperts]);
3790
+ const handleSwitchToHistory = useCallback(() => {
3791
+ dispatch({ type: "BROWSE_HISTORY", jobs: historyJobs });
3792
+ }, [historyJobs]);
3793
+ useInput((input, key) => {
3794
+ if (key.ctrl && input === "c") {
3795
+ exit();
3796
+ }
3797
+ });
3798
+ const contextValue = useMemo(
3799
+ () => ({
3800
+ onExpertSelect: handleExpertSelect,
3801
+ onQuerySubmit: () => {
3802
+ },
3803
+ // Not used in browser
3804
+ onJobSelect: handleJobSelect,
3805
+ onJobResume: handleJobResume,
3806
+ onCheckpointSelect: () => {
3807
+ },
3808
+ // Not used in selection (no event browsing)
3809
+ onCheckpointResume: handleCheckpointResume,
3810
+ onEventSelect: () => {
3811
+ },
3812
+ // Not used in selection
3813
+ onBack: handleBack,
3814
+ onSwitchToExperts: handleSwitchToExperts,
3815
+ onSwitchToHistory: handleSwitchToHistory
3816
+ }),
3817
+ [
3818
+ handleExpertSelect,
3819
+ handleJobSelect,
3820
+ handleJobResume,
3821
+ handleCheckpointResume,
3822
+ handleBack,
3823
+ handleSwitchToExperts,
3824
+ handleSwitchToHistory
3825
+ ]
3826
+ );
3827
+ if (initialExpertKey && initialQuery) {
3828
+ return null;
3829
+ }
3830
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3831
+ /* @__PURE__ */ jsx(InputAreaProvider, { value: contextValue, children: (state.type === "browsingHistory" || state.type === "browsingExperts" || state.type === "browsingCheckpoints") && /* @__PURE__ */ jsx(
3832
+ BrowserRouter,
3833
+ {
3834
+ inputState: state,
3835
+ showEventsHint: false
3836
+ }
3837
+ ) }),
3838
+ state.type === "enteringQuery" && /* @__PURE__ */ jsxs(Box, { flexDirection: "column", borderStyle: "single", borderColor: "gray", children: [
3839
+ /* @__PURE__ */ jsxs(Text, { children: [
3840
+ /* @__PURE__ */ jsx(Text, { color: "cyan", bold: true, children: "Expert:" }),
3841
+ " ",
3842
+ /* @__PURE__ */ jsx(Text, { children: state.expertKey }),
3843
+ selectedCheckpoint && /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
3844
+ " (resuming from step ",
3845
+ selectedCheckpoint.stepNumber,
3846
+ ")"
3847
+ ] })
3848
+ ] }),
3849
+ /* @__PURE__ */ jsxs(Box, { children: [
3850
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Query: " }),
3851
+ /* @__PURE__ */ jsx(Text, { children: queryInput }),
3852
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
3853
+ ] }),
3854
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Press Enter to start" })
3855
+ ] })
3856
+ ] });
3857
+ };
3858
+ async function renderSelection(params) {
3859
+ return new Promise((resolve, reject) => {
3860
+ let resolved = false;
3861
+ const { waitUntilExit } = render(
3862
+ /* @__PURE__ */ jsx(
3863
+ SelectionApp,
3864
+ {
3865
+ ...params,
3866
+ onComplete: (result) => {
3867
+ resolved = true;
3868
+ resolve(result);
3869
+ }
3870
+ }
3871
+ )
3872
+ );
3873
+ waitUntilExit().then(() => {
3874
+ if (!resolved) {
3875
+ reject(new Error("Selection cancelled"));
3876
+ }
3877
+ }).catch(reject);
3878
+ });
3879
+ }
3880
+ function getEnv(envPath) {
3881
+ const env = Object.fromEntries(
3882
+ Object.entries(process.env).filter(([_, value]) => !!value).map(([key, value]) => [key, value])
3883
+ );
3884
+ dotenv.config({ path: envPath, processEnv: env, quiet: true });
3885
+ return env;
3886
+ }
3887
+ var ALLOWED_CONFIG_HOSTS = ["raw.githubusercontent.com"];
3888
+ async function getPerstackConfig(configPath) {
3889
+ const configString = await findPerstackConfigString(configPath);
3890
+ if (configString === null) {
3891
+ throw new Error("perstack.toml not found. Create one or specify --config path.");
3892
+ }
3893
+ return await parsePerstackConfig(configString);
3894
+ }
3895
+ function isRemoteUrl(configPath) {
3896
+ const lower = configPath.toLowerCase();
3897
+ return lower.startsWith("https://") || lower.startsWith("http://");
3898
+ }
3899
+ async function fetchRemoteConfig(url) {
3900
+ let parsed;
3901
+ try {
3902
+ parsed = new URL(url);
3903
+ } catch {
3904
+ throw new Error(`Invalid remote config URL: ${url}`);
3905
+ }
3906
+ if (parsed.protocol !== "https:") {
3907
+ throw new Error("Remote config requires HTTPS");
3908
+ }
3909
+ if (!ALLOWED_CONFIG_HOSTS.includes(parsed.hostname)) {
3910
+ throw new Error(`Remote config only allowed from: ${ALLOWED_CONFIG_HOSTS.join(", ")}`);
3911
+ }
3912
+ try {
3913
+ const response = await fetch(url, { redirect: "error" });
3914
+ if (!response.ok) {
3915
+ throw new Error(`${response.status} ${response.statusText}`);
3916
+ }
3917
+ return await response.text();
3918
+ } catch (error) {
3919
+ const message = error instanceof Error ? error.message : String(error);
3920
+ throw new Error(`Failed to fetch remote config: ${message}`);
3921
+ }
3922
+ }
3923
+ async function findPerstackConfigString(configPath) {
3924
+ if (configPath) {
3925
+ if (isRemoteUrl(configPath)) {
3926
+ return await fetchRemoteConfig(configPath);
3927
+ }
3928
+ try {
3929
+ const tomlString = await readFile(path5.resolve(process.cwd(), configPath), "utf-8");
3930
+ return tomlString;
3931
+ } catch {
3932
+ throw new Error(`Given config path "${configPath}" is not found`);
3933
+ }
3934
+ }
3935
+ return await findPerstackConfigStringRecursively(path5.resolve(process.cwd()));
3936
+ }
3937
+ async function findPerstackConfigStringRecursively(cwd) {
3938
+ try {
3939
+ const tomlString = await readFile(path5.resolve(cwd, "perstack.toml"), "utf-8");
3940
+ return tomlString;
3941
+ } catch {
3942
+ if (cwd === path5.parse(cwd).root) {
3943
+ return null;
3944
+ }
3945
+ return await findPerstackConfigStringRecursively(path5.dirname(cwd));
3946
+ }
3947
+ }
3948
+ async function parsePerstackConfig(config2) {
3949
+ const toml = TOML.parse(config2 ?? "");
3950
+ return parseWithFriendlyError(perstackConfigSchema, toml, "perstack.toml");
3951
+ }
3952
+
3953
+ // ../../packages/tui/src/lib/provider-config.ts
3954
+ function getProviderConfig(provider, env, providerTable) {
3955
+ const setting = providerTable?.setting ?? {};
3956
+ switch (provider) {
3957
+ case "anthropic": {
3958
+ const apiKey = env.ANTHROPIC_API_KEY;
3959
+ if (!apiKey) throw new Error("ANTHROPIC_API_KEY is not set");
3960
+ return {
3961
+ providerName: "anthropic",
3962
+ apiKey,
3963
+ baseUrl: setting.baseUrl ?? env.ANTHROPIC_BASE_URL,
3964
+ headers: setting.headers
3965
+ };
3966
+ }
3967
+ case "google": {
3968
+ const apiKey = env.GOOGLE_GENERATIVE_AI_API_KEY;
3969
+ if (!apiKey) throw new Error("GOOGLE_GENERATIVE_AI_API_KEY is not set");
3970
+ return {
3971
+ providerName: "google",
3972
+ apiKey,
3973
+ baseUrl: setting.baseUrl ?? env.GOOGLE_GENERATIVE_AI_BASE_URL,
3974
+ headers: setting.headers
3975
+ };
3976
+ }
3977
+ case "openai": {
3978
+ const apiKey = env.OPENAI_API_KEY;
3979
+ if (!apiKey) throw new Error("OPENAI_API_KEY is not set");
3980
+ return {
3981
+ providerName: "openai",
3982
+ apiKey,
3983
+ baseUrl: setting.baseUrl ?? env.OPENAI_BASE_URL,
3984
+ organization: setting.organization ?? env.OPENAI_ORGANIZATION,
3985
+ project: setting.project ?? env.OPENAI_PROJECT,
3986
+ name: setting.name,
3987
+ headers: setting.headers
3988
+ };
3989
+ }
3990
+ case "ollama": {
3991
+ return {
3992
+ providerName: "ollama",
3993
+ baseUrl: setting.baseUrl ?? env.OLLAMA_BASE_URL,
3994
+ headers: setting.headers
3995
+ };
3996
+ }
3997
+ case "azure-openai": {
3998
+ const apiKey = env.AZURE_API_KEY;
3999
+ if (!apiKey) throw new Error("AZURE_API_KEY is not set");
4000
+ const resourceName = setting.resourceName ?? env.AZURE_RESOURCE_NAME;
4001
+ const baseUrl = setting.baseUrl ?? env.AZURE_BASE_URL;
4002
+ if (!resourceName && !baseUrl) throw new Error("AZURE_RESOURCE_NAME or baseUrl is not set");
4003
+ return {
4004
+ providerName: "azure-openai",
4005
+ apiKey,
4006
+ resourceName,
4007
+ apiVersion: setting.apiVersion ?? env.AZURE_API_VERSION,
4008
+ baseUrl,
4009
+ headers: setting.headers,
4010
+ useDeploymentBasedUrls: setting.useDeploymentBasedUrls
4011
+ };
4012
+ }
4013
+ case "amazon-bedrock": {
4014
+ const accessKeyId = env.AWS_ACCESS_KEY_ID;
4015
+ const secretAccessKey = env.AWS_SECRET_ACCESS_KEY;
4016
+ const sessionToken = env.AWS_SESSION_TOKEN;
4017
+ if (!accessKeyId) throw new Error("AWS_ACCESS_KEY_ID is not set");
4018
+ if (!secretAccessKey) throw new Error("AWS_SECRET_ACCESS_KEY is not set");
4019
+ const region = setting.region ?? env.AWS_REGION;
4020
+ if (!region) throw new Error("AWS_REGION is not set");
4021
+ return {
4022
+ providerName: "amazon-bedrock",
4023
+ accessKeyId,
4024
+ secretAccessKey,
4025
+ region,
4026
+ sessionToken
4027
+ };
4028
+ }
4029
+ case "google-vertex": {
4030
+ return {
4031
+ providerName: "google-vertex",
4032
+ project: setting.project ?? env.GOOGLE_VERTEX_PROJECT,
4033
+ location: setting.location ?? env.GOOGLE_VERTEX_LOCATION,
4034
+ baseUrl: setting.baseUrl ?? env.GOOGLE_VERTEX_BASE_URL,
4035
+ headers: setting.headers
4036
+ };
4037
+ }
4038
+ case "deepseek": {
4039
+ const apiKey = env.DEEPSEEK_API_KEY;
4040
+ if (!apiKey) throw new Error("DEEPSEEK_API_KEY is not set");
4041
+ return {
4042
+ providerName: "deepseek",
4043
+ apiKey,
4044
+ baseUrl: setting.baseUrl ?? env.DEEPSEEK_BASE_URL,
4045
+ headers: setting.headers
4046
+ };
4047
+ }
4048
+ }
4049
+ }
4050
+ function getAllJobs2() {
4051
+ return getAllJobs();
4052
+ }
4053
+ function getAllRuns2() {
4054
+ return getAllRuns();
4055
+ }
4056
+ function getMostRecentRun() {
4057
+ const runs = getAllRuns2();
4058
+ if (runs.length === 0) {
4059
+ throw new Error("No runs found");
4060
+ }
4061
+ return runs[0];
4062
+ }
4063
+ function getCheckpointsByJobId2(jobId) {
4064
+ return getCheckpointsByJobId(jobId);
4065
+ }
4066
+ function getMostRecentCheckpoint(jobId) {
4067
+ const targetJobId = jobId ?? getMostRecentRun().jobId;
4068
+ const checkpoints = getCheckpointsByJobId2(targetJobId);
4069
+ if (checkpoints.length === 0) {
4070
+ throw new Error(`No checkpoints found for job ${targetJobId}`);
4071
+ }
4072
+ return checkpoints[checkpoints.length - 1];
4073
+ }
4074
+ function getRecentExperts(limit) {
4075
+ const runs = getAllRuns2();
4076
+ const expertMap = /* @__PURE__ */ new Map();
4077
+ for (const setting of runs) {
4078
+ const expertKey = setting.expertKey;
4079
+ if (!expertMap.has(expertKey) || expertMap.get(expertKey).lastUsed < setting.updatedAt) {
4080
+ expertMap.set(expertKey, {
4081
+ key: expertKey,
4082
+ name: expertKey,
4083
+ lastUsed: setting.updatedAt
4084
+ });
4085
+ }
4086
+ }
4087
+ return Array.from(expertMap.values()).sort((a, b) => b.lastUsed - a.lastUsed).slice(0, limit);
4088
+ }
4089
+ function getCheckpointById(jobId, checkpointId) {
4090
+ const checkpointPath = getCheckpointPath(jobId, checkpointId);
4091
+ if (!existsSync(checkpointPath)) {
4092
+ throw new Error(`Checkpoint ${checkpointId} not found in job ${jobId}`);
4093
+ }
4094
+ const checkpoint = readFileSync(checkpointPath, "utf-8");
4095
+ return checkpointSchema.parse(JSON.parse(checkpoint));
4096
+ }
4097
+ function getCheckpointsWithDetails(jobId) {
4098
+ return getCheckpointsByJobId2(jobId).map((cp) => ({
4099
+ id: cp.id,
4100
+ runId: cp.runId,
4101
+ stepNumber: cp.stepNumber,
4102
+ contextWindowUsage: cp.contextWindowUsage ?? 0
4103
+ })).sort((a, b) => b.stepNumber - a.stepNumber);
4104
+ }
4105
+ function getAllEventContentsForJob(jobId, maxStepNumber) {
4106
+ const runIds = getRunIdsByJobId(jobId);
4107
+ const allEvents = [];
4108
+ for (const runId of runIds) {
4109
+ const events = getEventContents(jobId, runId, maxStepNumber);
4110
+ allEvents.push(...events);
4111
+ }
4112
+ return allEvents.sort((a, b) => a.timestamp - b.timestamp);
4113
+ }
4114
+
4115
+ // ../../packages/tui/src/lib/context.ts
4116
+ var defaultProvider = "anthropic";
4117
+ var defaultModel = "claude-sonnet-4-5";
4118
+ async function resolveRunContext(input) {
4119
+ const perstackConfig = input.perstackConfig ?? await getPerstackConfig(input.configPath);
4120
+ let checkpoint;
4121
+ if (input.resumeFrom) {
4122
+ if (!input.continueJob) {
4123
+ throw new Error("--resume-from requires --continue-job");
4124
+ }
4125
+ checkpoint = getCheckpointById(input.continueJob, input.resumeFrom);
4126
+ } else if (input.continueJob) {
4127
+ checkpoint = getMostRecentCheckpoint(input.continueJob);
4128
+ } else if (input.continue) {
4129
+ checkpoint = getMostRecentCheckpoint();
4130
+ }
4131
+ if ((input.continue || input.continueJob || input.resumeFrom) && !checkpoint) {
4132
+ throw new Error("No checkpoint found");
4133
+ }
4134
+ if (checkpoint && input.expertKey && checkpoint.expert.key !== input.expertKey) {
4135
+ throw new Error(
4136
+ `Checkpoint expert key ${checkpoint.expert.key} does not match input expert key ${input.expertKey}`
4137
+ );
4138
+ }
4139
+ const envPath = input.envPath && input.envPath.length > 0 ? input.envPath : perstackConfig.envPath ?? [".env", ".env.local"];
4140
+ const env = getEnv(envPath);
4141
+ const provider = input.provider ?? perstackConfig.provider?.providerName ?? defaultProvider;
4142
+ const model = input.model ?? perstackConfig.model ?? defaultModel;
4143
+ const providerConfig = getProviderConfig(provider, env, perstackConfig.provider);
4144
+ const experts = Object.fromEntries(
4145
+ Object.entries(perstackConfig.experts ?? {}).map(([name, expert]) => {
4146
+ return [
4147
+ name,
4148
+ {
4149
+ name,
4150
+ version: expert.version ?? "1.0.0",
4151
+ description: expert.description,
4152
+ instruction: expert.instruction,
4153
+ skills: expert.skills,
4154
+ delegates: expert.delegates,
4155
+ tags: expert.tags
4156
+ }
4157
+ ];
4158
+ })
4159
+ );
4160
+ return {
4161
+ perstackConfig,
4162
+ checkpoint,
4163
+ env,
4164
+ providerConfig,
4165
+ model,
4166
+ experts
4167
+ };
4168
+ }
4169
+
4170
+ // ../../packages/tui/src/lib/interactive.ts
4171
+ function parseInteractiveToolCallResult(query, checkpoint) {
4172
+ const lastMessage = checkpoint.messages[checkpoint.messages.length - 1];
4173
+ if (lastMessage.type !== "expertMessage") {
4174
+ throw new Error("Last message is not a expert message");
4175
+ }
4176
+ const content = lastMessage.contents.find((c) => c.type === "toolCallPart");
4177
+ if (!content || content.type !== "toolCallPart") {
4178
+ throw new Error("Last message content is not a tool call part");
4179
+ }
4180
+ const toolCallId = content.toolCallId;
4181
+ const toolName = content.toolName;
4182
+ const pendingToolCall = checkpoint.pendingToolCalls?.find((tc) => tc.id === toolCallId);
4183
+ const skillName = pendingToolCall?.skillName ?? "";
4184
+ return {
4185
+ interactiveToolCallResult: {
4186
+ toolCallId,
4187
+ toolName,
4188
+ skillName,
4189
+ text: query
4190
+ }
4191
+ };
4192
+ }
4193
+
4194
+ // ../../packages/tui/src/start-handler.ts
4195
+ var CONTINUE_TIMEOUT_MS = 6e4;
4196
+ async function startHandler(expertKey, query, options, handlerOptions) {
4197
+ const input = parseWithFriendlyError(startCommandInputSchema, { expertKey, query, options });
4198
+ try {
4199
+ const { perstackConfig, checkpoint, env, providerConfig, model, experts } = await resolveRunContext({
4200
+ configPath: input.options.config,
4201
+ provider: input.options.provider,
4202
+ model: input.options.model,
4203
+ envPath: input.options.envPath,
4204
+ continue: input.options.continue,
4205
+ continueJob: input.options.continueJob,
4206
+ resumeFrom: input.options.resumeFrom,
4207
+ expertKey: input.expertKey,
4208
+ perstackConfig: handlerOptions?.perstackConfig
4209
+ });
4210
+ if (handlerOptions?.additionalEnv) {
4211
+ Object.assign(env, handlerOptions.additionalEnv(env));
4212
+ }
4213
+ const maxSteps = input.options.maxSteps ?? perstackConfig.maxSteps;
4214
+ const maxRetries = input.options.maxRetries ?? perstackConfig.maxRetries ?? defaultMaxRetries;
4215
+ const timeout = input.options.timeout ?? perstackConfig.timeout ?? defaultTimeout;
4216
+ const configuredExperts = Object.keys(perstackConfig.experts ?? {}).map((key) => ({
4217
+ key,
4218
+ name: key
4219
+ }));
4220
+ const recentExperts = getRecentExperts(10);
4221
+ const showHistory = !input.expertKey && !input.query && !checkpoint;
4222
+ const historyJobs = showHistory ? getAllJobs2().map((j) => ({
4223
+ jobId: j.id,
4224
+ status: j.status,
4225
+ expertKey: j.coordinatorExpertKey,
4226
+ totalSteps: j.totalSteps,
4227
+ startedAt: j.startedAt,
4228
+ finishedAt: j.finishedAt
4229
+ })) : [];
4230
+ const selection = await renderSelection({
4231
+ showHistory,
4232
+ initialExpertKey: input.expertKey,
4233
+ initialQuery: input.query,
4234
+ initialCheckpoint: checkpoint ? {
4235
+ id: checkpoint.id,
4236
+ jobId: checkpoint.jobId,
4237
+ runId: checkpoint.runId,
4238
+ stepNumber: checkpoint.stepNumber,
4239
+ contextWindowUsage: checkpoint.contextWindowUsage ?? 0
4240
+ } : void 0,
4241
+ configuredExperts,
4242
+ recentExperts,
4243
+ historyJobs,
4244
+ onLoadCheckpoints: async (j) => {
4245
+ const checkpoints = getCheckpointsWithDetails(j.jobId);
4246
+ return checkpoints.map((cp) => ({ ...cp, jobId: j.jobId }));
4247
+ }
4248
+ });
4249
+ if (!selection.expertKey) {
4250
+ console.error("Expert key is required");
4251
+ return;
4252
+ }
4253
+ if (!selection.query && !selection.checkpoint) {
4254
+ console.error("Query is required");
4255
+ return;
4256
+ }
4257
+ let currentCheckpoint = selection.checkpoint ? getCheckpointById(selection.checkpoint.jobId, selection.checkpoint.id) : checkpoint;
4258
+ if (currentCheckpoint && currentCheckpoint.expert.key !== selection.expertKey) {
4259
+ console.error(
4260
+ `Checkpoint expert key ${currentCheckpoint.expert.key} does not match input expert key ${selection.expertKey}`
4261
+ );
4262
+ return;
4263
+ }
4264
+ const lockfilePath = findLockfile();
4265
+ const lockfile = lockfilePath ? loadLockfile(lockfilePath) ?? void 0 : void 0;
4266
+ let currentQuery = selection.query;
4267
+ let currentJobId = currentCheckpoint?.jobId ?? input.options.jobId ?? createId();
4268
+ let isNextQueryInteractiveToolResult = input.options.interactiveToolCallResult ?? false;
4269
+ let isFirstIteration = true;
4270
+ const initialHistoricalEvents = currentCheckpoint ? getAllEventContentsForJob(currentCheckpoint.jobId, currentCheckpoint.stepNumber) : void 0;
4271
+ while (currentQuery !== null) {
4272
+ const historicalEvents = isFirstIteration ? initialHistoricalEvents : void 0;
4273
+ const runId = createId();
4274
+ const { result: executionResult, eventListener } = renderExecution({
4275
+ expertKey: selection.expertKey,
4276
+ query: currentQuery,
4277
+ config: {
4278
+ runtimeVersion,
4279
+ model,
4280
+ maxSteps,
4281
+ maxRetries,
4282
+ timeout,
4283
+ contextWindowUsage: currentCheckpoint?.contextWindowUsage ?? 0
4284
+ },
4285
+ continueTimeoutMs: CONTINUE_TIMEOUT_MS,
4286
+ historicalEvents
4287
+ });
4288
+ const runResult = await run(
4289
+ {
4290
+ setting: {
4291
+ jobId: currentJobId,
4292
+ runId,
4293
+ expertKey: selection.expertKey,
4294
+ input: isNextQueryInteractiveToolResult && currentCheckpoint ? parseInteractiveToolCallResult(currentQuery, currentCheckpoint) : { text: currentQuery },
4295
+ experts,
4296
+ model,
4297
+ providerConfig,
4298
+ reasoningBudget: input.options.reasoningBudget ?? perstackConfig.reasoningBudget,
4299
+ maxSteps: input.options.maxSteps ?? perstackConfig.maxSteps,
4300
+ maxRetries: input.options.maxRetries ?? perstackConfig.maxRetries,
4301
+ timeout: input.options.timeout ?? perstackConfig.timeout,
4302
+ perstackApiBaseUrl: perstackConfig.perstackApiBaseUrl,
4303
+ perstackApiKey: env.PERSTACK_API_KEY,
4304
+ perstackBaseSkillCommand: perstackConfig.perstackBaseSkillCommand,
4305
+ env,
4306
+ verbose: input.options.verbose
4307
+ },
4308
+ checkpoint: currentCheckpoint
4309
+ },
4310
+ {
4311
+ eventListener,
4312
+ storeCheckpoint: defaultStoreCheckpoint,
4313
+ storeEvent: defaultStoreEvent,
4314
+ retrieveCheckpoint: defaultRetrieveCheckpoint,
4315
+ storeJob,
4316
+ retrieveJob,
4317
+ createJob: createInitialJob,
4318
+ lockfile
4319
+ }
4320
+ );
4321
+ const result = await executionResult;
4322
+ const canContinue = runResult.status === "completed" || runResult.status === "stoppedByExceededMaxSteps" || runResult.status === "stoppedByError" || runResult.status === "stoppedByInteractiveTool";
4323
+ if (result.nextQuery && canContinue) {
4324
+ currentQuery = result.nextQuery;
4325
+ currentCheckpoint = runResult;
4326
+ currentJobId = runResult.jobId;
4327
+ isNextQueryInteractiveToolResult = runResult.status === "stoppedByInteractiveTool";
4328
+ isFirstIteration = false;
4329
+ } else {
4330
+ currentQuery = null;
4331
+ }
4332
+ }
4333
+ } catch (error) {
4334
+ if (error instanceof Error) {
4335
+ console.error(error.message);
4336
+ } else {
4337
+ console.error(error);
4338
+ }
4339
+ }
4340
+ }
8
4341
  var tomlPath = new URL("../perstack.toml", import.meta.url);
9
4342
  var config = parseWithFriendlyError(
10
4343
  perstackConfigSchema,
@@ -33,5 +4366,10 @@ new Command().name("create-expert").description("Create and modify Perstack expe
33
4366
  }
34
4367
  );
35
4368
  }).parse();
4369
+ /*! Bundled license information:
4370
+
4371
+ @noble/hashes/utils.js:
4372
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4373
+ */
36
4374
  //# sourceMappingURL=cli.js.map
37
4375
  //# sourceMappingURL=cli.js.map