@aident-ai/cli 0.3.0 → 0.3.1-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.mjs +314 -82
  2. package/dist/dsh.mjs +2970 -47
  3. package/package.json +2 -2
package/dist/dsh.mjs CHANGED
@@ -1,3 +1,2452 @@
1
+ import { createRequire } from "node:module";
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
12
+ var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
20
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
21
+ const to = isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ if (mod && typeof mod === "object" || typeof mod === "function") {
23
+ for (let key of __getOwnPropNames(mod))
24
+ if (!__hasOwnProp.call(to, key))
25
+ __defProp(to, key, {
26
+ get: __accessProp.bind(mod, key),
27
+ enumerable: true
28
+ });
29
+ }
30
+ if (canCache)
31
+ cache.set(mod, to);
32
+ return to;
33
+ };
34
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
35
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
36
+
37
+ // ../../node_modules/queue-tick/queue-microtask.js
38
+ var require_queue_microtask = __commonJS(function(exports, module) {
39
+ module.exports = typeof queueMicrotask === "function" ? queueMicrotask : (fn) => Promise.resolve().then(fn);
40
+ });
41
+
42
+ // ../../node_modules/queue-tick/process-next-tick.js
43
+ var require_process_next_tick = __commonJS(function(exports, module) {
44
+ module.exports = typeof process !== "undefined" && typeof process.nextTick === "function" ? process.nextTick.bind(process) : require_queue_microtask();
45
+ });
46
+
47
+ // ../../node_modules/fast-fifo/fixed-size.js
48
+ var require_fixed_size = __commonJS(function(exports, module) {
49
+ module.exports = class FixedFIFO {
50
+ constructor(hwm) {
51
+ if (!(hwm > 0) || (hwm - 1 & hwm) !== 0)
52
+ throw new Error("Max size for a FixedFIFO should be a power of two");
53
+ this.buffer = new Array(hwm);
54
+ this.mask = hwm - 1;
55
+ this.top = 0;
56
+ this.btm = 0;
57
+ this.next = null;
58
+ }
59
+ clear() {
60
+ this.top = this.btm = 0;
61
+ this.next = null;
62
+ this.buffer.fill(undefined);
63
+ }
64
+ push(data) {
65
+ if (this.buffer[this.top] !== undefined)
66
+ return false;
67
+ this.buffer[this.top] = data;
68
+ this.top = this.top + 1 & this.mask;
69
+ return true;
70
+ }
71
+ shift() {
72
+ const last = this.buffer[this.btm];
73
+ if (last === undefined)
74
+ return;
75
+ this.buffer[this.btm] = undefined;
76
+ this.btm = this.btm + 1 & this.mask;
77
+ return last;
78
+ }
79
+ peek() {
80
+ return this.buffer[this.btm];
81
+ }
82
+ isEmpty() {
83
+ return this.buffer[this.btm] === undefined;
84
+ }
85
+ };
86
+ });
87
+
88
+ // ../../node_modules/fast-fifo/index.js
89
+ var require_fast_fifo = __commonJS(function(exports, module) {
90
+ var FixedFIFO = require_fixed_size();
91
+ module.exports = class FastFIFO {
92
+ constructor(hwm) {
93
+ this.hwm = hwm || 16;
94
+ this.head = new FixedFIFO(this.hwm);
95
+ this.tail = this.head;
96
+ this.length = 0;
97
+ }
98
+ clear() {
99
+ this.head = this.tail;
100
+ this.head.clear();
101
+ this.length = 0;
102
+ }
103
+ push(val) {
104
+ this.length++;
105
+ if (!this.head.push(val)) {
106
+ const prev = this.head;
107
+ this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);
108
+ this.head.push(val);
109
+ }
110
+ }
111
+ shift() {
112
+ if (this.length !== 0)
113
+ this.length--;
114
+ const val = this.tail.shift();
115
+ if (val === undefined && this.tail.next) {
116
+ const next = this.tail.next;
117
+ this.tail.next = null;
118
+ this.tail = next;
119
+ return this.tail.shift();
120
+ }
121
+ return val;
122
+ }
123
+ peek() {
124
+ const val = this.tail.peek();
125
+ if (val === undefined && this.tail.next)
126
+ return this.tail.next.peek();
127
+ return val;
128
+ }
129
+ isEmpty() {
130
+ return this.length === 0;
131
+ }
132
+ };
133
+ });
134
+
135
+ // ../../node_modules/b4a/index.js
136
+ var require_b4a = __commonJS(function(exports, module) {
137
+ function isBuffer(value) {
138
+ return Buffer.isBuffer(value) || value instanceof Uint8Array;
139
+ }
140
+ function isEncoding(encoding) {
141
+ return Buffer.isEncoding(encoding);
142
+ }
143
+ function alloc(size, fill, encoding) {
144
+ return Buffer.alloc(size, fill, encoding);
145
+ }
146
+ function allocUnsafe(size) {
147
+ return Buffer.allocUnsafe(size);
148
+ }
149
+ function allocUnsafeSlow(size) {
150
+ return Buffer.allocUnsafeSlow(size);
151
+ }
152
+ function byteLength(string, encoding) {
153
+ return Buffer.byteLength(string, encoding);
154
+ }
155
+ function compare(a, b) {
156
+ return Buffer.compare(a, b);
157
+ }
158
+ function concat(buffers, totalLength) {
159
+ return Buffer.concat(buffers, totalLength);
160
+ }
161
+ function copy(source, target, targetStart, start, end) {
162
+ return toBuffer(source).copy(target, targetStart, start, end);
163
+ }
164
+ function equals(a, b) {
165
+ return toBuffer(a).equals(b);
166
+ }
167
+ function fill(buffer, value, offset, end, encoding) {
168
+ return toBuffer(buffer).fill(value, offset, end, encoding);
169
+ }
170
+ function from(value, encodingOrOffset, length) {
171
+ return Buffer.from(value, encodingOrOffset, length);
172
+ }
173
+ function includes(buffer, value, byteOffset, encoding) {
174
+ return toBuffer(buffer).includes(value, byteOffset, encoding);
175
+ }
176
+ function indexOf(buffer, value, byfeOffset, encoding) {
177
+ return toBuffer(buffer).indexOf(value, byfeOffset, encoding);
178
+ }
179
+ function lastIndexOf(buffer, value, byteOffset, encoding) {
180
+ return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding);
181
+ }
182
+ function swap16(buffer) {
183
+ return toBuffer(buffer).swap16();
184
+ }
185
+ function swap32(buffer) {
186
+ return toBuffer(buffer).swap32();
187
+ }
188
+ function swap64(buffer) {
189
+ return toBuffer(buffer).swap64();
190
+ }
191
+ function toBuffer(buffer) {
192
+ if (Buffer.isBuffer(buffer))
193
+ return buffer;
194
+ return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
195
+ }
196
+ function toString(buffer, encoding, start, end) {
197
+ return toBuffer(buffer).toString(encoding, start, end);
198
+ }
199
+ function write(buffer, string, offset, length, encoding) {
200
+ return toBuffer(buffer).write(string, offset, length, encoding);
201
+ }
202
+ function writeDoubleLE(buffer, value, offset) {
203
+ return toBuffer(buffer).writeDoubleLE(value, offset);
204
+ }
205
+ function writeFloatLE(buffer, value, offset) {
206
+ return toBuffer(buffer).writeFloatLE(value, offset);
207
+ }
208
+ function writeUInt32LE(buffer, value, offset) {
209
+ return toBuffer(buffer).writeUInt32LE(value, offset);
210
+ }
211
+ function writeInt32LE(buffer, value, offset) {
212
+ return toBuffer(buffer).writeInt32LE(value, offset);
213
+ }
214
+ function readDoubleLE(buffer, offset) {
215
+ return toBuffer(buffer).readDoubleLE(offset);
216
+ }
217
+ function readFloatLE(buffer, offset) {
218
+ return toBuffer(buffer).readFloatLE(offset);
219
+ }
220
+ function readUInt32LE(buffer, offset) {
221
+ return toBuffer(buffer).readUInt32LE(offset);
222
+ }
223
+ function readInt32LE(buffer, offset) {
224
+ return toBuffer(buffer).readInt32LE(offset);
225
+ }
226
+ function writeDoubleBE(buffer, value, offset) {
227
+ return toBuffer(buffer).writeDoubleBE(value, offset);
228
+ }
229
+ function writeFloatBE(buffer, value, offset) {
230
+ return toBuffer(buffer).writeFloatBE(value, offset);
231
+ }
232
+ function writeUInt32BE(buffer, value, offset) {
233
+ return toBuffer(buffer).writeUInt32BE(value, offset);
234
+ }
235
+ function writeInt32BE(buffer, value, offset) {
236
+ return toBuffer(buffer).writeInt32BE(value, offset);
237
+ }
238
+ function readDoubleBE(buffer, offset) {
239
+ return toBuffer(buffer).readDoubleBE(offset);
240
+ }
241
+ function readFloatBE(buffer, offset) {
242
+ return toBuffer(buffer).readFloatBE(offset);
243
+ }
244
+ function readUInt32BE(buffer, offset) {
245
+ return toBuffer(buffer).readUInt32BE(offset);
246
+ }
247
+ function readInt32BE(buffer, offset) {
248
+ return toBuffer(buffer).readInt32BE(offset);
249
+ }
250
+ module.exports = {
251
+ isBuffer,
252
+ isEncoding,
253
+ alloc,
254
+ allocUnsafe,
255
+ allocUnsafeSlow,
256
+ byteLength,
257
+ compare,
258
+ concat,
259
+ copy,
260
+ equals,
261
+ fill,
262
+ from,
263
+ includes,
264
+ indexOf,
265
+ lastIndexOf,
266
+ swap16,
267
+ swap32,
268
+ swap64,
269
+ toBuffer,
270
+ toString,
271
+ write,
272
+ writeDoubleLE,
273
+ writeFloatLE,
274
+ writeUInt32LE,
275
+ writeInt32LE,
276
+ readDoubleLE,
277
+ readFloatLE,
278
+ readUInt32LE,
279
+ readInt32LE,
280
+ writeDoubleBE,
281
+ writeFloatBE,
282
+ writeUInt32BE,
283
+ writeInt32BE,
284
+ readDoubleBE,
285
+ readFloatBE,
286
+ readUInt32BE,
287
+ readInt32BE
288
+ };
289
+ });
290
+
291
+ // ../../node_modules/text-decoder/lib/pass-through-decoder.js
292
+ var require_pass_through_decoder = __commonJS(function(exports, module) {
293
+ var b4a = require_b4a();
294
+ module.exports = class PassThroughDecoder {
295
+ constructor(encoding) {
296
+ this.encoding = encoding;
297
+ }
298
+ get remaining() {
299
+ return 0;
300
+ }
301
+ decode(tail) {
302
+ return b4a.toString(tail, this.encoding);
303
+ }
304
+ flush() {
305
+ return "";
306
+ }
307
+ };
308
+ });
309
+
310
+ // ../../node_modules/text-decoder/lib/utf8-decoder.js
311
+ var require_utf8_decoder = __commonJS(function(exports, module) {
312
+ var b4a = require_b4a();
313
+ module.exports = class UTF8Decoder {
314
+ constructor() {
315
+ this.codePoint = 0;
316
+ this.bytesSeen = 0;
317
+ this.bytesNeeded = 0;
318
+ this.lowerBoundary = 128;
319
+ this.upperBoundary = 191;
320
+ }
321
+ get remaining() {
322
+ return this.bytesSeen;
323
+ }
324
+ decode(data) {
325
+ if (this.bytesNeeded === 0) {
326
+ let isBoundary = true;
327
+ for (let i = Math.max(0, data.byteLength - 4), n = data.byteLength;i < n && isBoundary; i++) {
328
+ isBoundary = data[i] <= 127;
329
+ }
330
+ if (isBoundary)
331
+ return b4a.toString(data, "utf8");
332
+ }
333
+ let result = "";
334
+ for (let i = 0, n = data.byteLength;i < n; i++) {
335
+ const byte = data[i];
336
+ if (this.bytesNeeded === 0) {
337
+ if (byte <= 127) {
338
+ result += String.fromCharCode(byte);
339
+ } else {
340
+ this.bytesSeen = 1;
341
+ if (byte >= 194 && byte <= 223) {
342
+ this.bytesNeeded = 2;
343
+ this.codePoint = byte & 31;
344
+ } else if (byte >= 224 && byte <= 239) {
345
+ if (byte === 224)
346
+ this.lowerBoundary = 160;
347
+ else if (byte === 237)
348
+ this.upperBoundary = 159;
349
+ this.bytesNeeded = 3;
350
+ this.codePoint = byte & 15;
351
+ } else if (byte >= 240 && byte <= 244) {
352
+ if (byte === 240)
353
+ this.lowerBoundary = 144;
354
+ if (byte === 244)
355
+ this.upperBoundary = 143;
356
+ this.bytesNeeded = 4;
357
+ this.codePoint = byte & 7;
358
+ } else {
359
+ result += "�";
360
+ }
361
+ }
362
+ continue;
363
+ }
364
+ if (byte < this.lowerBoundary || byte > this.upperBoundary) {
365
+ this.codePoint = 0;
366
+ this.bytesNeeded = 0;
367
+ this.bytesSeen = 0;
368
+ this.lowerBoundary = 128;
369
+ this.upperBoundary = 191;
370
+ result += "�";
371
+ continue;
372
+ }
373
+ this.lowerBoundary = 128;
374
+ this.upperBoundary = 191;
375
+ this.codePoint = this.codePoint << 6 | byte & 63;
376
+ this.bytesSeen++;
377
+ if (this.bytesSeen !== this.bytesNeeded)
378
+ continue;
379
+ result += String.fromCodePoint(this.codePoint);
380
+ this.codePoint = 0;
381
+ this.bytesNeeded = 0;
382
+ this.bytesSeen = 0;
383
+ }
384
+ return result;
385
+ }
386
+ flush() {
387
+ const result = this.bytesNeeded > 0 ? "�" : "";
388
+ this.codePoint = 0;
389
+ this.bytesNeeded = 0;
390
+ this.bytesSeen = 0;
391
+ this.lowerBoundary = 128;
392
+ this.upperBoundary = 191;
393
+ return result;
394
+ }
395
+ };
396
+ });
397
+
398
+ // ../../node_modules/text-decoder/index.js
399
+ var require_text_decoder = __commonJS(function(exports, module) {
400
+ var PassThroughDecoder = require_pass_through_decoder();
401
+ var UTF8Decoder = require_utf8_decoder();
402
+ module.exports = class TextDecoder {
403
+ constructor(encoding = "utf8") {
404
+ this.encoding = normalizeEncoding(encoding);
405
+ switch (this.encoding) {
406
+ case "utf8":
407
+ this.decoder = new UTF8Decoder;
408
+ break;
409
+ case "utf16le":
410
+ case "base64":
411
+ throw new Error("Unsupported encoding: " + this.encoding);
412
+ default:
413
+ this.decoder = new PassThroughDecoder(this.encoding);
414
+ }
415
+ }
416
+ get remaining() {
417
+ return this.decoder.remaining;
418
+ }
419
+ push(data) {
420
+ if (typeof data === "string")
421
+ return data;
422
+ return this.decoder.decode(data);
423
+ }
424
+ write(data) {
425
+ return this.push(data);
426
+ }
427
+ end(data) {
428
+ let result = "";
429
+ if (data)
430
+ result = this.push(data);
431
+ result += this.decoder.flush();
432
+ return result;
433
+ }
434
+ };
435
+ function normalizeEncoding(encoding) {
436
+ encoding = encoding.toLowerCase();
437
+ switch (encoding) {
438
+ case "utf8":
439
+ case "utf-8":
440
+ return "utf8";
441
+ case "ucs2":
442
+ case "ucs-2":
443
+ case "utf16le":
444
+ case "utf-16le":
445
+ return "utf16le";
446
+ case "latin1":
447
+ case "binary":
448
+ return "latin1";
449
+ case "base64":
450
+ case "ascii":
451
+ case "hex":
452
+ return encoding;
453
+ default:
454
+ throw new Error("Unknown encoding: " + encoding);
455
+ }
456
+ }
457
+ });
458
+
459
+ // ../../node_modules/streamx/index.js
460
+ var require_streamx = __commonJS(function(exports, module) {
461
+ var { EventEmitter } = __require("events");
462
+ var STREAM_DESTROYED = new Error("Stream was destroyed");
463
+ var PREMATURE_CLOSE = new Error("Premature close");
464
+ var queueTick = require_process_next_tick();
465
+ var FIFO = require_fast_fifo();
466
+ var TextDecoder = require_text_decoder();
467
+ var MAX = (1 << 29) - 1;
468
+ var OPENING = 1;
469
+ var PREDESTROYING = 2;
470
+ var DESTROYING = 4;
471
+ var DESTROYED = 8;
472
+ var NOT_OPENING = MAX ^ OPENING;
473
+ var NOT_PREDESTROYING = MAX ^ PREDESTROYING;
474
+ var READ_ACTIVE = 1 << 4;
475
+ var READ_UPDATING = 2 << 4;
476
+ var READ_PRIMARY = 4 << 4;
477
+ var READ_QUEUED = 8 << 4;
478
+ var READ_RESUMED = 16 << 4;
479
+ var READ_PIPE_DRAINED = 32 << 4;
480
+ var READ_ENDING = 64 << 4;
481
+ var READ_EMIT_DATA = 128 << 4;
482
+ var READ_EMIT_READABLE = 256 << 4;
483
+ var READ_EMITTED_READABLE = 512 << 4;
484
+ var READ_DONE = 1024 << 4;
485
+ var READ_NEXT_TICK = 2048 << 4;
486
+ var READ_NEEDS_PUSH = 4096 << 4;
487
+ var READ_READ_AHEAD = 8192 << 4;
488
+ var READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED;
489
+ var READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH;
490
+ var READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE;
491
+ var READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED;
492
+ var READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD;
493
+ var READ_NOT_ACTIVE = MAX ^ READ_ACTIVE;
494
+ var READ_NON_PRIMARY = MAX ^ READ_PRIMARY;
495
+ var READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH);
496
+ var READ_PUSHED = MAX ^ READ_NEEDS_PUSH;
497
+ var READ_PAUSED = MAX ^ READ_RESUMED;
498
+ var READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE);
499
+ var READ_NOT_ENDING = MAX ^ READ_ENDING;
500
+ var READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING;
501
+ var READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK;
502
+ var READ_NOT_UPDATING = MAX ^ READ_UPDATING;
503
+ var READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD;
504
+ var READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD;
505
+ var WRITE_ACTIVE = 1 << 18;
506
+ var WRITE_UPDATING = 2 << 18;
507
+ var WRITE_PRIMARY = 4 << 18;
508
+ var WRITE_QUEUED = 8 << 18;
509
+ var WRITE_UNDRAINED = 16 << 18;
510
+ var WRITE_DONE = 32 << 18;
511
+ var WRITE_EMIT_DRAIN = 64 << 18;
512
+ var WRITE_NEXT_TICK = 128 << 18;
513
+ var WRITE_WRITING = 256 << 18;
514
+ var WRITE_FINISHING = 512 << 18;
515
+ var WRITE_CORKED = 1024 << 18;
516
+ var WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING);
517
+ var WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY;
518
+ var WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING);
519
+ var WRITE_DRAINED = MAX ^ WRITE_UNDRAINED;
520
+ var WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED;
521
+ var WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK;
522
+ var WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING;
523
+ var WRITE_NOT_CORKED = MAX ^ WRITE_CORKED;
524
+ var ACTIVE = READ_ACTIVE | WRITE_ACTIVE;
525
+ var NOT_ACTIVE = MAX ^ ACTIVE;
526
+ var DONE = READ_DONE | WRITE_DONE;
527
+ var DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING;
528
+ var OPEN_STATUS = DESTROY_STATUS | OPENING;
529
+ var AUTO_DESTROY = DESTROY_STATUS | DONE;
530
+ var NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY;
531
+ var ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK;
532
+ var TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE;
533
+ var IS_OPENING = OPEN_STATUS | TICKING;
534
+ var READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE;
535
+ var READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED;
536
+ var READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED;
537
+ var READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE;
538
+ var SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD;
539
+ var READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE;
540
+ var READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY;
541
+ var READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING;
542
+ var WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE;
543
+ var WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED;
544
+ var WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE;
545
+ var WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE;
546
+ var WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED;
547
+ var WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE;
548
+ var WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING;
549
+ var WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE;
550
+ var WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE;
551
+ var WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY;
552
+ var WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS;
553
+ var asyncIterator = Symbol.asyncIterator || Symbol("asyncIterator");
554
+
555
+ class WritableState {
556
+ constructor(stream, { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}) {
557
+ this.stream = stream;
558
+ this.queue = new FIFO;
559
+ this.highWaterMark = highWaterMark;
560
+ this.buffered = 0;
561
+ this.error = null;
562
+ this.pipeline = null;
563
+ this.drains = null;
564
+ this.byteLength = byteLengthWritable || byteLength || defaultByteLength;
565
+ this.map = mapWritable || map;
566
+ this.afterWrite = afterWrite.bind(this);
567
+ this.afterUpdateNextTick = updateWriteNT.bind(this);
568
+ }
569
+ get ended() {
570
+ return (this.stream._duplexState & WRITE_DONE) !== 0;
571
+ }
572
+ push(data) {
573
+ if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0)
574
+ return false;
575
+ if (this.map !== null)
576
+ data = this.map(data);
577
+ this.buffered += this.byteLength(data);
578
+ this.queue.push(data);
579
+ if (this.buffered < this.highWaterMark) {
580
+ this.stream._duplexState |= WRITE_QUEUED;
581
+ return true;
582
+ }
583
+ this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED;
584
+ return false;
585
+ }
586
+ shift() {
587
+ const data = this.queue.shift();
588
+ this.buffered -= this.byteLength(data);
589
+ if (this.buffered === 0)
590
+ this.stream._duplexState &= WRITE_NOT_QUEUED;
591
+ return data;
592
+ }
593
+ end(data) {
594
+ if (typeof data === "function")
595
+ this.stream.once("finish", data);
596
+ else if (data !== undefined && data !== null)
597
+ this.push(data);
598
+ this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY;
599
+ }
600
+ autoBatch(data, cb) {
601
+ const buffer = [];
602
+ const stream = this.stream;
603
+ buffer.push(data);
604
+ while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
605
+ buffer.push(stream._writableState.shift());
606
+ }
607
+ if ((stream._duplexState & OPEN_STATUS) !== 0)
608
+ return cb(null);
609
+ stream._writev(buffer, cb);
610
+ }
611
+ update() {
612
+ const stream = this.stream;
613
+ stream._duplexState |= WRITE_UPDATING;
614
+ do {
615
+ while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
616
+ const data = this.shift();
617
+ stream._duplexState |= WRITE_ACTIVE_AND_WRITING;
618
+ stream._write(data, this.afterWrite);
619
+ }
620
+ if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0)
621
+ this.updateNonPrimary();
622
+ } while (this.continueUpdate() === true);
623
+ stream._duplexState &= WRITE_NOT_UPDATING;
624
+ }
625
+ updateNonPrimary() {
626
+ const stream = this.stream;
627
+ if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
628
+ stream._duplexState = stream._duplexState | WRITE_ACTIVE;
629
+ stream._final(afterFinal.bind(this));
630
+ return;
631
+ }
632
+ if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
633
+ if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
634
+ stream._duplexState |= ACTIVE;
635
+ stream._destroy(afterDestroy.bind(this));
636
+ }
637
+ return;
638
+ }
639
+ if ((stream._duplexState & IS_OPENING) === OPENING) {
640
+ stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
641
+ stream._open(afterOpen.bind(this));
642
+ }
643
+ }
644
+ continueUpdate() {
645
+ if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0)
646
+ return false;
647
+ this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
648
+ return true;
649
+ }
650
+ updateCallback() {
651
+ if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY)
652
+ this.update();
653
+ else
654
+ this.updateNextTick();
655
+ }
656
+ updateNextTick() {
657
+ if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0)
658
+ return;
659
+ this.stream._duplexState |= WRITE_NEXT_TICK;
660
+ if ((this.stream._duplexState & WRITE_UPDATING) === 0)
661
+ queueTick(this.afterUpdateNextTick);
662
+ }
663
+ }
664
+
665
+ class ReadableState {
666
+ constructor(stream, { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}) {
667
+ this.stream = stream;
668
+ this.queue = new FIFO;
669
+ this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark;
670
+ this.buffered = 0;
671
+ this.readAhead = highWaterMark > 0;
672
+ this.error = null;
673
+ this.pipeline = null;
674
+ this.byteLength = byteLengthReadable || byteLength || defaultByteLength;
675
+ this.map = mapReadable || map;
676
+ this.pipeTo = null;
677
+ this.afterRead = afterRead.bind(this);
678
+ this.afterUpdateNextTick = updateReadNT.bind(this);
679
+ }
680
+ get ended() {
681
+ return (this.stream._duplexState & READ_DONE) !== 0;
682
+ }
683
+ pipe(pipeTo, cb) {
684
+ if (this.pipeTo !== null)
685
+ throw new Error("Can only pipe to one destination");
686
+ if (typeof cb !== "function")
687
+ cb = null;
688
+ this.stream._duplexState |= READ_PIPE_DRAINED;
689
+ this.pipeTo = pipeTo;
690
+ this.pipeline = new Pipeline(this.stream, pipeTo, cb);
691
+ if (cb)
692
+ this.stream.on("error", noop);
693
+ if (isStreamx(pipeTo)) {
694
+ pipeTo._writableState.pipeline = this.pipeline;
695
+ if (cb)
696
+ pipeTo.on("error", noop);
697
+ pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
698
+ } else {
699
+ const onerror = this.pipeline.done.bind(this.pipeline, pipeTo);
700
+ const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null);
701
+ pipeTo.on("error", onerror);
702
+ pipeTo.on("close", onclose);
703
+ pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
704
+ }
705
+ pipeTo.on("drain", afterDrain.bind(this));
706
+ this.stream.emit("piping", pipeTo);
707
+ pipeTo.emit("pipe", this.stream);
708
+ }
709
+ push(data) {
710
+ const stream = this.stream;
711
+ if (data === null) {
712
+ this.highWaterMark = 0;
713
+ stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED;
714
+ return false;
715
+ }
716
+ if (this.map !== null) {
717
+ data = this.map(data);
718
+ if (data === null) {
719
+ stream._duplexState &= READ_PUSHED;
720
+ return this.buffered < this.highWaterMark;
721
+ }
722
+ }
723
+ this.buffered += this.byteLength(data);
724
+ this.queue.push(data);
725
+ stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED;
726
+ return this.buffered < this.highWaterMark;
727
+ }
728
+ shift() {
729
+ const data = this.queue.shift();
730
+ this.buffered -= this.byteLength(data);
731
+ if (this.buffered === 0)
732
+ this.stream._duplexState &= READ_NOT_QUEUED;
733
+ return data;
734
+ }
735
+ unshift(data) {
736
+ const pending = [this.map !== null ? this.map(data) : data];
737
+ while (this.buffered > 0)
738
+ pending.push(this.shift());
739
+ for (let i = 0;i < pending.length - 1; i++) {
740
+ const data = pending[i];
741
+ this.buffered += this.byteLength(data);
742
+ this.queue.push(data);
743
+ }
744
+ this.push(pending[pending.length - 1]);
745
+ }
746
+ read() {
747
+ const stream = this.stream;
748
+ if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
749
+ const data = this.shift();
750
+ if (this.pipeTo !== null && this.pipeTo.write(data) === false)
751
+ stream._duplexState &= READ_PIPE_NOT_DRAINED;
752
+ if ((stream._duplexState & READ_EMIT_DATA) !== 0)
753
+ stream.emit("data", data);
754
+ return data;
755
+ }
756
+ if (this.readAhead === false) {
757
+ stream._duplexState |= READ_READ_AHEAD;
758
+ this.updateNextTick();
759
+ }
760
+ return null;
761
+ }
762
+ drain() {
763
+ const stream = this.stream;
764
+ while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) {
765
+ const data = this.shift();
766
+ if (this.pipeTo !== null && this.pipeTo.write(data) === false)
767
+ stream._duplexState &= READ_PIPE_NOT_DRAINED;
768
+ if ((stream._duplexState & READ_EMIT_DATA) !== 0)
769
+ stream.emit("data", data);
770
+ }
771
+ }
772
+ update() {
773
+ const stream = this.stream;
774
+ stream._duplexState |= READ_UPDATING;
775
+ do {
776
+ this.drain();
777
+ while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) {
778
+ stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH;
779
+ stream._read(this.afterRead);
780
+ this.drain();
781
+ }
782
+ if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
783
+ stream._duplexState |= READ_EMITTED_READABLE;
784
+ stream.emit("readable");
785
+ }
786
+ if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0)
787
+ this.updateNonPrimary();
788
+ } while (this.continueUpdate() === true);
789
+ stream._duplexState &= READ_NOT_UPDATING;
790
+ }
791
+ updateNonPrimary() {
792
+ const stream = this.stream;
793
+ if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
794
+ stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING;
795
+ stream.emit("end");
796
+ if ((stream._duplexState & AUTO_DESTROY) === DONE)
797
+ stream._duplexState |= DESTROYING;
798
+ if (this.pipeTo !== null)
799
+ this.pipeTo.end();
800
+ }
801
+ if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
802
+ if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
803
+ stream._duplexState |= ACTIVE;
804
+ stream._destroy(afterDestroy.bind(this));
805
+ }
806
+ return;
807
+ }
808
+ if ((stream._duplexState & IS_OPENING) === OPENING) {
809
+ stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
810
+ stream._open(afterOpen.bind(this));
811
+ }
812
+ }
813
+ continueUpdate() {
814
+ if ((this.stream._duplexState & READ_NEXT_TICK) === 0)
815
+ return false;
816
+ this.stream._duplexState &= READ_NOT_NEXT_TICK;
817
+ return true;
818
+ }
819
+ updateCallback() {
820
+ if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY)
821
+ this.update();
822
+ else
823
+ this.updateNextTick();
824
+ }
825
+ updateNextTickIfOpen() {
826
+ if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0)
827
+ return;
828
+ this.stream._duplexState |= READ_NEXT_TICK;
829
+ if ((this.stream._duplexState & READ_UPDATING) === 0)
830
+ queueTick(this.afterUpdateNextTick);
831
+ }
832
+ updateNextTick() {
833
+ if ((this.stream._duplexState & READ_NEXT_TICK) !== 0)
834
+ return;
835
+ this.stream._duplexState |= READ_NEXT_TICK;
836
+ if ((this.stream._duplexState & READ_UPDATING) === 0)
837
+ queueTick(this.afterUpdateNextTick);
838
+ }
839
+ }
840
+
841
+ class TransformState {
842
+ constructor(stream) {
843
+ this.data = null;
844
+ this.afterTransform = afterTransform.bind(stream);
845
+ this.afterFinal = null;
846
+ }
847
+ }
848
+
849
+ class Pipeline {
850
+ constructor(src, dst, cb) {
851
+ this.from = src;
852
+ this.to = dst;
853
+ this.afterPipe = cb;
854
+ this.error = null;
855
+ this.pipeToFinished = false;
856
+ }
857
+ finished() {
858
+ this.pipeToFinished = true;
859
+ }
860
+ done(stream, err) {
861
+ if (err)
862
+ this.error = err;
863
+ if (stream === this.to) {
864
+ this.to = null;
865
+ if (this.from !== null) {
866
+ if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
867
+ this.from.destroy(this.error || new Error("Writable stream closed prematurely"));
868
+ }
869
+ return;
870
+ }
871
+ }
872
+ if (stream === this.from) {
873
+ this.from = null;
874
+ if (this.to !== null) {
875
+ if ((stream._duplexState & READ_DONE) === 0) {
876
+ this.to.destroy(this.error || new Error("Readable stream closed before ending"));
877
+ }
878
+ return;
879
+ }
880
+ }
881
+ if (this.afterPipe !== null)
882
+ this.afterPipe(this.error);
883
+ this.to = this.from = this.afterPipe = null;
884
+ }
885
+ }
886
+ function afterDrain() {
887
+ this.stream._duplexState |= READ_PIPE_DRAINED;
888
+ this.updateCallback();
889
+ }
890
+ function afterFinal(err) {
891
+ const stream = this.stream;
892
+ if (err)
893
+ stream.destroy(err);
894
+ if ((stream._duplexState & DESTROY_STATUS) === 0) {
895
+ stream._duplexState |= WRITE_DONE;
896
+ stream.emit("finish");
897
+ }
898
+ if ((stream._duplexState & AUTO_DESTROY) === DONE) {
899
+ stream._duplexState |= DESTROYING;
900
+ }
901
+ stream._duplexState &= WRITE_NOT_FINISHING;
902
+ if ((stream._duplexState & WRITE_UPDATING) === 0)
903
+ this.update();
904
+ else
905
+ this.updateNextTick();
906
+ }
907
+ function afterDestroy(err) {
908
+ const stream = this.stream;
909
+ if (!err && this.error !== STREAM_DESTROYED)
910
+ err = this.error;
911
+ if (err)
912
+ stream.emit("error", err);
913
+ stream._duplexState |= DESTROYED;
914
+ stream.emit("close");
915
+ const rs = stream._readableState;
916
+ const ws = stream._writableState;
917
+ if (rs !== null && rs.pipeline !== null)
918
+ rs.pipeline.done(stream, err);
919
+ if (ws !== null) {
920
+ while (ws.drains !== null && ws.drains.length > 0)
921
+ ws.drains.shift().resolve(false);
922
+ if (ws.pipeline !== null)
923
+ ws.pipeline.done(stream, err);
924
+ }
925
+ }
926
+ function afterWrite(err) {
927
+ const stream = this.stream;
928
+ if (err)
929
+ stream.destroy(err);
930
+ stream._duplexState &= WRITE_NOT_ACTIVE;
931
+ if (this.drains !== null)
932
+ tickDrains(this.drains);
933
+ if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
934
+ stream._duplexState &= WRITE_DRAINED;
935
+ if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
936
+ stream.emit("drain");
937
+ }
938
+ }
939
+ this.updateCallback();
940
+ }
941
+ function afterRead(err) {
942
+ if (err)
943
+ this.stream.destroy(err);
944
+ this.stream._duplexState &= READ_NOT_ACTIVE;
945
+ if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0)
946
+ this.stream._duplexState &= READ_NO_READ_AHEAD;
947
+ this.updateCallback();
948
+ }
949
+ function updateReadNT() {
950
+ if ((this.stream._duplexState & READ_UPDATING) === 0) {
951
+ this.stream._duplexState &= READ_NOT_NEXT_TICK;
952
+ this.update();
953
+ }
954
+ }
955
+ function updateWriteNT() {
956
+ if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
957
+ this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
958
+ this.update();
959
+ }
960
+ }
961
+ function tickDrains(drains) {
962
+ for (let i = 0;i < drains.length; i++) {
963
+ if (--drains[i].writes === 0) {
964
+ drains.shift().resolve(true);
965
+ i--;
966
+ }
967
+ }
968
+ }
969
+ function afterOpen(err) {
970
+ const stream = this.stream;
971
+ if (err)
972
+ stream.destroy(err);
973
+ if ((stream._duplexState & DESTROYING) === 0) {
974
+ if ((stream._duplexState & READ_PRIMARY_STATUS) === 0)
975
+ stream._duplexState |= READ_PRIMARY;
976
+ if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0)
977
+ stream._duplexState |= WRITE_PRIMARY;
978
+ stream.emit("open");
979
+ }
980
+ stream._duplexState &= NOT_ACTIVE;
981
+ if (stream._writableState !== null) {
982
+ stream._writableState.updateCallback();
983
+ }
984
+ if (stream._readableState !== null) {
985
+ stream._readableState.updateCallback();
986
+ }
987
+ }
988
+ function afterTransform(err, data) {
989
+ if (data !== undefined && data !== null)
990
+ this.push(data);
991
+ this._writableState.afterWrite(err);
992
+ }
993
+ function newListener(name) {
994
+ if (this._readableState !== null) {
995
+ if (name === "data") {
996
+ this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD;
997
+ this._readableState.updateNextTick();
998
+ }
999
+ if (name === "readable") {
1000
+ this._duplexState |= READ_EMIT_READABLE;
1001
+ this._readableState.updateNextTick();
1002
+ }
1003
+ }
1004
+ if (this._writableState !== null) {
1005
+ if (name === "drain") {
1006
+ this._duplexState |= WRITE_EMIT_DRAIN;
1007
+ this._writableState.updateNextTick();
1008
+ }
1009
+ }
1010
+ }
1011
+
1012
+ class Stream extends EventEmitter {
1013
+ constructor(opts) {
1014
+ super();
1015
+ this._duplexState = 0;
1016
+ this._readableState = null;
1017
+ this._writableState = null;
1018
+ if (opts) {
1019
+ if (opts.open)
1020
+ this._open = opts.open;
1021
+ if (opts.destroy)
1022
+ this._destroy = opts.destroy;
1023
+ if (opts.predestroy)
1024
+ this._predestroy = opts.predestroy;
1025
+ if (opts.signal) {
1026
+ opts.signal.addEventListener("abort", abort.bind(this));
1027
+ }
1028
+ }
1029
+ this.on("newListener", newListener);
1030
+ }
1031
+ _open(cb) {
1032
+ cb(null);
1033
+ }
1034
+ _destroy(cb) {
1035
+ cb(null);
1036
+ }
1037
+ _predestroy() {}
1038
+ get readable() {
1039
+ return this._readableState !== null ? true : undefined;
1040
+ }
1041
+ get writable() {
1042
+ return this._writableState !== null ? true : undefined;
1043
+ }
1044
+ get destroyed() {
1045
+ return (this._duplexState & DESTROYED) !== 0;
1046
+ }
1047
+ get destroying() {
1048
+ return (this._duplexState & DESTROY_STATUS) !== 0;
1049
+ }
1050
+ destroy(err) {
1051
+ if ((this._duplexState & DESTROY_STATUS) === 0) {
1052
+ if (!err)
1053
+ err = STREAM_DESTROYED;
1054
+ this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY;
1055
+ if (this._readableState !== null) {
1056
+ this._readableState.highWaterMark = 0;
1057
+ this._readableState.error = err;
1058
+ }
1059
+ if (this._writableState !== null) {
1060
+ this._writableState.highWaterMark = 0;
1061
+ this._writableState.error = err;
1062
+ }
1063
+ this._duplexState |= PREDESTROYING;
1064
+ this._predestroy();
1065
+ this._duplexState &= NOT_PREDESTROYING;
1066
+ if (this._readableState !== null)
1067
+ this._readableState.updateNextTick();
1068
+ if (this._writableState !== null)
1069
+ this._writableState.updateNextTick();
1070
+ }
1071
+ }
1072
+ }
1073
+
1074
+ class Readable extends Stream {
1075
+ constructor(opts) {
1076
+ super(opts);
1077
+ this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD;
1078
+ this._readableState = new ReadableState(this, opts);
1079
+ if (opts) {
1080
+ if (this._readableState.readAhead === false)
1081
+ this._duplexState &= READ_NO_READ_AHEAD;
1082
+ if (opts.read)
1083
+ this._read = opts.read;
1084
+ if (opts.eagerOpen)
1085
+ this._readableState.updateNextTick();
1086
+ if (opts.encoding)
1087
+ this.setEncoding(opts.encoding);
1088
+ }
1089
+ }
1090
+ setEncoding(encoding) {
1091
+ const dec = new TextDecoder(encoding);
1092
+ const map = this._readableState.map || echo;
1093
+ this._readableState.map = mapOrSkip;
1094
+ return this;
1095
+ function mapOrSkip(data) {
1096
+ const next = dec.push(data);
1097
+ return next === "" && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next);
1098
+ }
1099
+ }
1100
+ _read(cb) {
1101
+ cb(null);
1102
+ }
1103
+ pipe(dest, cb) {
1104
+ this._readableState.updateNextTick();
1105
+ this._readableState.pipe(dest, cb);
1106
+ return dest;
1107
+ }
1108
+ read() {
1109
+ this._readableState.updateNextTick();
1110
+ return this._readableState.read();
1111
+ }
1112
+ push(data) {
1113
+ this._readableState.updateNextTickIfOpen();
1114
+ return this._readableState.push(data);
1115
+ }
1116
+ unshift(data) {
1117
+ this._readableState.updateNextTickIfOpen();
1118
+ return this._readableState.unshift(data);
1119
+ }
1120
+ resume() {
1121
+ this._duplexState |= READ_RESUMED_READ_AHEAD;
1122
+ this._readableState.updateNextTick();
1123
+ return this;
1124
+ }
1125
+ pause() {
1126
+ this._duplexState &= this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED;
1127
+ return this;
1128
+ }
1129
+ static _fromAsyncIterator(ite, opts) {
1130
+ let destroy;
1131
+ const rs = new Readable({
1132
+ ...opts,
1133
+ read(cb) {
1134
+ ite.next().then(push).then(cb.bind(null, null)).catch(cb);
1135
+ },
1136
+ predestroy() {
1137
+ destroy = ite.return();
1138
+ },
1139
+ destroy(cb) {
1140
+ if (!destroy)
1141
+ return cb(null);
1142
+ destroy.then(cb.bind(null, null)).catch(cb);
1143
+ }
1144
+ });
1145
+ return rs;
1146
+ function push(data) {
1147
+ if (data.done)
1148
+ rs.push(null);
1149
+ else
1150
+ rs.push(data.value);
1151
+ }
1152
+ }
1153
+ static from(data, opts) {
1154
+ if (isReadStreamx(data))
1155
+ return data;
1156
+ if (data[asyncIterator])
1157
+ return this._fromAsyncIterator(data[asyncIterator](), opts);
1158
+ if (!Array.isArray(data))
1159
+ data = data === undefined ? [] : [data];
1160
+ let i = 0;
1161
+ return new Readable({
1162
+ ...opts,
1163
+ read(cb) {
1164
+ this.push(i === data.length ? null : data[i++]);
1165
+ cb(null);
1166
+ }
1167
+ });
1168
+ }
1169
+ static isBackpressured(rs) {
1170
+ return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark;
1171
+ }
1172
+ static isPaused(rs) {
1173
+ return (rs._duplexState & READ_RESUMED) === 0;
1174
+ }
1175
+ [asyncIterator]() {
1176
+ const stream = this;
1177
+ let error = null;
1178
+ let promiseResolve = null;
1179
+ let promiseReject = null;
1180
+ this.on("error", (err) => {
1181
+ error = err;
1182
+ });
1183
+ this.on("readable", onreadable);
1184
+ this.on("close", onclose);
1185
+ return {
1186
+ [asyncIterator]() {
1187
+ return this;
1188
+ },
1189
+ next() {
1190
+ return new Promise(function(resolve, reject) {
1191
+ promiseResolve = resolve;
1192
+ promiseReject = reject;
1193
+ const data = stream.read();
1194
+ if (data !== null)
1195
+ ondata(data);
1196
+ else if ((stream._duplexState & DESTROYED) !== 0)
1197
+ ondata(null);
1198
+ });
1199
+ },
1200
+ return() {
1201
+ return destroy(null);
1202
+ },
1203
+ throw(err) {
1204
+ return destroy(err);
1205
+ }
1206
+ };
1207
+ function onreadable() {
1208
+ if (promiseResolve !== null)
1209
+ ondata(stream.read());
1210
+ }
1211
+ function onclose() {
1212
+ if (promiseResolve !== null)
1213
+ ondata(null);
1214
+ }
1215
+ function ondata(data) {
1216
+ if (promiseReject === null)
1217
+ return;
1218
+ if (error)
1219
+ promiseReject(error);
1220
+ else if (data === null && (stream._duplexState & READ_DONE) === 0)
1221
+ promiseReject(STREAM_DESTROYED);
1222
+ else
1223
+ promiseResolve({ value: data, done: data === null });
1224
+ promiseReject = promiseResolve = null;
1225
+ }
1226
+ function destroy(err) {
1227
+ stream.destroy(err);
1228
+ return new Promise((resolve, reject) => {
1229
+ if (stream._duplexState & DESTROYED)
1230
+ return resolve({ value: undefined, done: true });
1231
+ stream.once("close", function() {
1232
+ if (err)
1233
+ reject(err);
1234
+ else
1235
+ resolve({ value: undefined, done: true });
1236
+ });
1237
+ });
1238
+ }
1239
+ }
1240
+ }
1241
+
1242
+ class Writable extends Stream {
1243
+ constructor(opts) {
1244
+ super(opts);
1245
+ this._duplexState |= OPENING | READ_DONE;
1246
+ this._writableState = new WritableState(this, opts);
1247
+ if (opts) {
1248
+ if (opts.writev)
1249
+ this._writev = opts.writev;
1250
+ if (opts.write)
1251
+ this._write = opts.write;
1252
+ if (opts.final)
1253
+ this._final = opts.final;
1254
+ if (opts.eagerOpen)
1255
+ this._writableState.updateNextTick();
1256
+ }
1257
+ }
1258
+ cork() {
1259
+ this._duplexState |= WRITE_CORKED;
1260
+ }
1261
+ uncork() {
1262
+ this._duplexState &= WRITE_NOT_CORKED;
1263
+ this._writableState.updateNextTick();
1264
+ }
1265
+ _writev(batch, cb) {
1266
+ cb(null);
1267
+ }
1268
+ _write(data, cb) {
1269
+ this._writableState.autoBatch(data, cb);
1270
+ }
1271
+ _final(cb) {
1272
+ cb(null);
1273
+ }
1274
+ static isBackpressured(ws) {
1275
+ return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0;
1276
+ }
1277
+ static drained(ws) {
1278
+ if (ws.destroyed)
1279
+ return Promise.resolve(false);
1280
+ const state = ws._writableState;
1281
+ const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length;
1282
+ const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0);
1283
+ if (writes === 0)
1284
+ return Promise.resolve(true);
1285
+ if (state.drains === null)
1286
+ state.drains = [];
1287
+ return new Promise((resolve) => {
1288
+ state.drains.push({ writes, resolve });
1289
+ });
1290
+ }
1291
+ write(data) {
1292
+ this._writableState.updateNextTick();
1293
+ return this._writableState.push(data);
1294
+ }
1295
+ end(data) {
1296
+ this._writableState.updateNextTick();
1297
+ this._writableState.end(data);
1298
+ return this;
1299
+ }
1300
+ }
1301
+
1302
+ class Duplex extends Readable {
1303
+ constructor(opts) {
1304
+ super(opts);
1305
+ this._duplexState = OPENING | this._duplexState & READ_READ_AHEAD;
1306
+ this._writableState = new WritableState(this, opts);
1307
+ if (opts) {
1308
+ if (opts.writev)
1309
+ this._writev = opts.writev;
1310
+ if (opts.write)
1311
+ this._write = opts.write;
1312
+ if (opts.final)
1313
+ this._final = opts.final;
1314
+ }
1315
+ }
1316
+ cork() {
1317
+ this._duplexState |= WRITE_CORKED;
1318
+ }
1319
+ uncork() {
1320
+ this._duplexState &= WRITE_NOT_CORKED;
1321
+ this._writableState.updateNextTick();
1322
+ }
1323
+ _writev(batch, cb) {
1324
+ cb(null);
1325
+ }
1326
+ _write(data, cb) {
1327
+ this._writableState.autoBatch(data, cb);
1328
+ }
1329
+ _final(cb) {
1330
+ cb(null);
1331
+ }
1332
+ write(data) {
1333
+ this._writableState.updateNextTick();
1334
+ return this._writableState.push(data);
1335
+ }
1336
+ end(data) {
1337
+ this._writableState.updateNextTick();
1338
+ this._writableState.end(data);
1339
+ return this;
1340
+ }
1341
+ }
1342
+
1343
+ class Transform extends Duplex {
1344
+ constructor(opts) {
1345
+ super(opts);
1346
+ this._transformState = new TransformState(this);
1347
+ if (opts) {
1348
+ if (opts.transform)
1349
+ this._transform = opts.transform;
1350
+ if (opts.flush)
1351
+ this._flush = opts.flush;
1352
+ }
1353
+ }
1354
+ _write(data, cb) {
1355
+ if (this._readableState.buffered >= this._readableState.highWaterMark) {
1356
+ this._transformState.data = data;
1357
+ } else {
1358
+ this._transform(data, this._transformState.afterTransform);
1359
+ }
1360
+ }
1361
+ _read(cb) {
1362
+ if (this._transformState.data !== null) {
1363
+ const data = this._transformState.data;
1364
+ this._transformState.data = null;
1365
+ cb(null);
1366
+ this._transform(data, this._transformState.afterTransform);
1367
+ } else {
1368
+ cb(null);
1369
+ }
1370
+ }
1371
+ destroy(err) {
1372
+ super.destroy(err);
1373
+ if (this._transformState.data !== null) {
1374
+ this._transformState.data = null;
1375
+ this._transformState.afterTransform();
1376
+ }
1377
+ }
1378
+ _transform(data, cb) {
1379
+ cb(null, data);
1380
+ }
1381
+ _flush(cb) {
1382
+ cb(null);
1383
+ }
1384
+ _final(cb) {
1385
+ this._transformState.afterFinal = cb;
1386
+ this._flush(transformAfterFlush.bind(this));
1387
+ }
1388
+ }
1389
+
1390
+ class PassThrough extends Transform {
1391
+ }
1392
+ function transformAfterFlush(err, data) {
1393
+ const cb = this._transformState.afterFinal;
1394
+ if (err)
1395
+ return cb(err);
1396
+ if (data !== null && data !== undefined)
1397
+ this.push(data);
1398
+ this.push(null);
1399
+ cb(null);
1400
+ }
1401
+ function pipelinePromise(...streams) {
1402
+ return new Promise((resolve, reject) => {
1403
+ return pipeline(...streams, (err) => {
1404
+ if (err)
1405
+ return reject(err);
1406
+ resolve();
1407
+ });
1408
+ });
1409
+ }
1410
+ function pipeline(stream, ...streams) {
1411
+ const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams];
1412
+ const done = all.length && typeof all[all.length - 1] === "function" ? all.pop() : null;
1413
+ if (all.length < 2)
1414
+ throw new Error("Pipeline requires at least 2 streams");
1415
+ let src = all[0];
1416
+ let dest = null;
1417
+ let error = null;
1418
+ for (let i = 1;i < all.length; i++) {
1419
+ dest = all[i];
1420
+ if (isStreamx(src)) {
1421
+ src.pipe(dest, onerror);
1422
+ } else {
1423
+ errorHandle(src, true, i > 1, onerror);
1424
+ src.pipe(dest);
1425
+ }
1426
+ src = dest;
1427
+ }
1428
+ if (done) {
1429
+ let fin = false;
1430
+ const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy);
1431
+ dest.on("error", (err) => {
1432
+ if (error === null)
1433
+ error = err;
1434
+ });
1435
+ dest.on("finish", () => {
1436
+ fin = true;
1437
+ if (!autoDestroy)
1438
+ done(error);
1439
+ });
1440
+ if (autoDestroy) {
1441
+ dest.on("close", () => done(error || (fin ? null : PREMATURE_CLOSE)));
1442
+ }
1443
+ }
1444
+ return dest;
1445
+ function errorHandle(s, rd, wr, onerror) {
1446
+ s.on("error", onerror);
1447
+ s.on("close", onclose);
1448
+ function onclose() {
1449
+ if (rd && s._readableState && !s._readableState.ended)
1450
+ return onerror(PREMATURE_CLOSE);
1451
+ if (wr && s._writableState && !s._writableState.ended)
1452
+ return onerror(PREMATURE_CLOSE);
1453
+ }
1454
+ }
1455
+ function onerror(err) {
1456
+ if (!err || error)
1457
+ return;
1458
+ error = err;
1459
+ for (const s of all) {
1460
+ s.destroy(err);
1461
+ }
1462
+ }
1463
+ }
1464
+ function echo(s) {
1465
+ return s;
1466
+ }
1467
+ function isStream(stream) {
1468
+ return !!stream._readableState || !!stream._writableState;
1469
+ }
1470
+ function isStreamx(stream) {
1471
+ return typeof stream._duplexState === "number" && isStream(stream);
1472
+ }
1473
+ function isEnded(stream) {
1474
+ return !!stream._readableState && stream._readableState.ended;
1475
+ }
1476
+ function isFinished(stream) {
1477
+ return !!stream._writableState && stream._writableState.ended;
1478
+ }
1479
+ function getStreamError(stream, opts = {}) {
1480
+ const err = stream._readableState && stream._readableState.error || stream._writableState && stream._writableState.error;
1481
+ return !opts.all && err === STREAM_DESTROYED ? null : err;
1482
+ }
1483
+ function isReadStreamx(stream) {
1484
+ return isStreamx(stream) && stream.readable;
1485
+ }
1486
+ function isDisturbed(stream) {
1487
+ return (stream._duplexState & OPENING) !== OPENING || (stream._duplexState & ACTIVE_OR_TICKING) !== 0;
1488
+ }
1489
+ function isTypedArray(data) {
1490
+ return typeof data === "object" && data !== null && typeof data.byteLength === "number";
1491
+ }
1492
+ function defaultByteLength(data) {
1493
+ return isTypedArray(data) ? data.byteLength : 1024;
1494
+ }
1495
+ function noop() {}
1496
+ function abort() {
1497
+ this.destroy(new Error("Stream aborted."));
1498
+ }
1499
+ function isWritev(s) {
1500
+ return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev;
1501
+ }
1502
+ module.exports = {
1503
+ pipeline,
1504
+ pipelinePromise,
1505
+ isStream,
1506
+ isStreamx,
1507
+ isEnded,
1508
+ isFinished,
1509
+ isDisturbed,
1510
+ getStreamError,
1511
+ Stream,
1512
+ Writable,
1513
+ Readable,
1514
+ Duplex,
1515
+ Transform,
1516
+ PassThrough
1517
+ };
1518
+ });
1519
+
1520
+ // ../../node_modules/tar-stream/headers.js
1521
+ var require_headers = __commonJS(function(exports) {
1522
+ var b4a = require_b4a();
1523
+ var ZEROS = "0000000000000000000";
1524
+ var SEVENS = "7777777777777777777";
1525
+ var ZERO_OFFSET = 48;
1526
+ var USTAR_MAGIC = b4a.from([117, 115, 116, 97, 114, 0]);
1527
+ var USTAR_VER = b4a.from([ZERO_OFFSET, ZERO_OFFSET]);
1528
+ var GNU_MAGIC = b4a.from([117, 115, 116, 97, 114, 32]);
1529
+ var GNU_VER = b4a.from([32, 0]);
1530
+ var MASK = 4095;
1531
+ var MAGIC_OFFSET = 257;
1532
+ var VERSION_OFFSET = 263;
1533
+ exports.decodeLongPath = function decodeLongPath(buf, encoding) {
1534
+ return decodeStr(buf, 0, buf.length, encoding);
1535
+ };
1536
+ exports.encodePax = function encodePax(opts) {
1537
+ let result = "";
1538
+ if (opts.name)
1539
+ result += addLength(" path=" + opts.name + `
1540
+ `);
1541
+ if (opts.linkname)
1542
+ result += addLength(" linkpath=" + opts.linkname + `
1543
+ `);
1544
+ const pax = opts.pax;
1545
+ if (pax) {
1546
+ for (const key in pax) {
1547
+ result += addLength(" " + key + "=" + pax[key] + `
1548
+ `);
1549
+ }
1550
+ }
1551
+ return b4a.from(result);
1552
+ };
1553
+ exports.decodePax = function decodePax(buf) {
1554
+ const result = {};
1555
+ while (buf.length) {
1556
+ let i = 0;
1557
+ while (i < buf.length && buf[i] !== 32)
1558
+ i++;
1559
+ const len = parseInt(b4a.toString(buf.subarray(0, i)), 10);
1560
+ if (!len)
1561
+ return result;
1562
+ const b = b4a.toString(buf.subarray(i + 1, len - 1));
1563
+ const keyIndex = b.indexOf("=");
1564
+ if (keyIndex === -1)
1565
+ return result;
1566
+ result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1);
1567
+ buf = buf.subarray(len);
1568
+ }
1569
+ return result;
1570
+ };
1571
+ exports.encode = function encode(opts) {
1572
+ const buf = b4a.alloc(512);
1573
+ let name = opts.name;
1574
+ let prefix = "";
1575
+ if (opts.typeflag === 5 && name[name.length - 1] !== "/")
1576
+ name += "/";
1577
+ if (b4a.byteLength(name) !== name.length)
1578
+ return null;
1579
+ while (b4a.byteLength(name) > 100) {
1580
+ const i = name.indexOf("/");
1581
+ if (i === -1)
1582
+ return null;
1583
+ prefix += prefix ? "/" + name.slice(0, i) : name.slice(0, i);
1584
+ name = name.slice(i + 1);
1585
+ }
1586
+ if (b4a.byteLength(name) > 100 || b4a.byteLength(prefix) > 155)
1587
+ return null;
1588
+ if (opts.linkname && b4a.byteLength(opts.linkname) > 100)
1589
+ return null;
1590
+ b4a.write(buf, name);
1591
+ b4a.write(buf, encodeOct(opts.mode & MASK, 6), 100);
1592
+ b4a.write(buf, encodeOct(opts.uid, 6), 108);
1593
+ b4a.write(buf, encodeOct(opts.gid, 6), 116);
1594
+ encodeSize(opts.size, buf, 124);
1595
+ b4a.write(buf, encodeOct(opts.mtime.getTime() / 1000 | 0, 11), 136);
1596
+ buf[156] = ZERO_OFFSET + toTypeflag(opts.type);
1597
+ if (opts.linkname)
1598
+ b4a.write(buf, opts.linkname, 157);
1599
+ b4a.copy(USTAR_MAGIC, buf, MAGIC_OFFSET);
1600
+ b4a.copy(USTAR_VER, buf, VERSION_OFFSET);
1601
+ if (opts.uname)
1602
+ b4a.write(buf, opts.uname, 265);
1603
+ if (opts.gname)
1604
+ b4a.write(buf, opts.gname, 297);
1605
+ b4a.write(buf, encodeOct(opts.devmajor || 0, 6), 329);
1606
+ b4a.write(buf, encodeOct(opts.devminor || 0, 6), 337);
1607
+ if (prefix)
1608
+ b4a.write(buf, prefix, 345);
1609
+ b4a.write(buf, encodeOct(cksum(buf), 6), 148);
1610
+ return buf;
1611
+ };
1612
+ exports.decode = function decode(buf, filenameEncoding, allowUnknownFormat) {
1613
+ let typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET;
1614
+ let name = decodeStr(buf, 0, 100, filenameEncoding);
1615
+ const mode = decodeOct(buf, 100, 8);
1616
+ const uid = decodeOct(buf, 108, 8);
1617
+ const gid = decodeOct(buf, 116, 8);
1618
+ const size = decodeOct(buf, 124, 12);
1619
+ const mtime = decodeOct(buf, 136, 12);
1620
+ const type = toType(typeflag);
1621
+ const linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding);
1622
+ const uname = decodeStr(buf, 265, 32);
1623
+ const gname = decodeStr(buf, 297, 32);
1624
+ const devmajor = decodeOct(buf, 329, 8);
1625
+ const devminor = decodeOct(buf, 337, 8);
1626
+ const c = cksum(buf);
1627
+ if (c === 8 * 32)
1628
+ return null;
1629
+ if (c !== decodeOct(buf, 148, 8))
1630
+ throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");
1631
+ if (isUSTAR(buf)) {
1632
+ if (buf[345])
1633
+ name = decodeStr(buf, 345, 155, filenameEncoding) + "/" + name;
1634
+ } else if (isGNU(buf)) {} else {
1635
+ if (!allowUnknownFormat) {
1636
+ throw new Error("Invalid tar header: unknown format.");
1637
+ }
1638
+ }
1639
+ if (typeflag === 0 && name && name[name.length - 1] === "/")
1640
+ typeflag = 5;
1641
+ return {
1642
+ name,
1643
+ mode,
1644
+ uid,
1645
+ gid,
1646
+ size,
1647
+ mtime: new Date(1000 * mtime),
1648
+ type,
1649
+ linkname,
1650
+ uname,
1651
+ gname,
1652
+ devmajor,
1653
+ devminor,
1654
+ pax: null
1655
+ };
1656
+ };
1657
+ function isUSTAR(buf) {
1658
+ return b4a.equals(USTAR_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6));
1659
+ }
1660
+ function isGNU(buf) {
1661
+ return b4a.equals(GNU_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) && b4a.equals(GNU_VER, buf.subarray(VERSION_OFFSET, VERSION_OFFSET + 2));
1662
+ }
1663
+ function clamp(index, len, defaultValue) {
1664
+ if (typeof index !== "number")
1665
+ return defaultValue;
1666
+ index = ~~index;
1667
+ if (index >= len)
1668
+ return len;
1669
+ if (index >= 0)
1670
+ return index;
1671
+ index += len;
1672
+ if (index >= 0)
1673
+ return index;
1674
+ return 0;
1675
+ }
1676
+ function toType(flag) {
1677
+ switch (flag) {
1678
+ case 0:
1679
+ return "file";
1680
+ case 1:
1681
+ return "link";
1682
+ case 2:
1683
+ return "symlink";
1684
+ case 3:
1685
+ return "character-device";
1686
+ case 4:
1687
+ return "block-device";
1688
+ case 5:
1689
+ return "directory";
1690
+ case 6:
1691
+ return "fifo";
1692
+ case 7:
1693
+ return "contiguous-file";
1694
+ case 72:
1695
+ return "pax-header";
1696
+ case 55:
1697
+ return "pax-global-header";
1698
+ case 27:
1699
+ return "gnu-long-link-path";
1700
+ case 28:
1701
+ case 30:
1702
+ return "gnu-long-path";
1703
+ }
1704
+ return null;
1705
+ }
1706
+ function toTypeflag(flag) {
1707
+ switch (flag) {
1708
+ case "file":
1709
+ return 0;
1710
+ case "link":
1711
+ return 1;
1712
+ case "symlink":
1713
+ return 2;
1714
+ case "character-device":
1715
+ return 3;
1716
+ case "block-device":
1717
+ return 4;
1718
+ case "directory":
1719
+ return 5;
1720
+ case "fifo":
1721
+ return 6;
1722
+ case "contiguous-file":
1723
+ return 7;
1724
+ case "pax-header":
1725
+ return 72;
1726
+ }
1727
+ return 0;
1728
+ }
1729
+ function indexOf(block, num, offset, end) {
1730
+ for (;offset < end; offset++) {
1731
+ if (block[offset] === num)
1732
+ return offset;
1733
+ }
1734
+ return end;
1735
+ }
1736
+ function cksum(block) {
1737
+ let sum = 8 * 32;
1738
+ for (let i = 0;i < 148; i++)
1739
+ sum += block[i];
1740
+ for (let j = 156;j < 512; j++)
1741
+ sum += block[j];
1742
+ return sum;
1743
+ }
1744
+ function encodeOct(val, n) {
1745
+ val = val.toString(8);
1746
+ if (val.length > n)
1747
+ return SEVENS.slice(0, n) + " ";
1748
+ return ZEROS.slice(0, n - val.length) + val + " ";
1749
+ }
1750
+ function encodeSizeBin(num, buf, off) {
1751
+ buf[off] = 128;
1752
+ for (let i = 11;i > 0; i--) {
1753
+ buf[off + i] = num & 255;
1754
+ num = Math.floor(num / 256);
1755
+ }
1756
+ }
1757
+ function encodeSize(num, buf, off) {
1758
+ if (num.toString(8).length > 11) {
1759
+ encodeSizeBin(num, buf, off);
1760
+ } else {
1761
+ b4a.write(buf, encodeOct(num, 11), off);
1762
+ }
1763
+ }
1764
+ function parse256(buf) {
1765
+ let positive;
1766
+ if (buf[0] === 128)
1767
+ positive = true;
1768
+ else if (buf[0] === 255)
1769
+ positive = false;
1770
+ else
1771
+ return null;
1772
+ const tuple = [];
1773
+ let i;
1774
+ for (i = buf.length - 1;i > 0; i--) {
1775
+ const byte = buf[i];
1776
+ if (positive)
1777
+ tuple.push(byte);
1778
+ else
1779
+ tuple.push(255 - byte);
1780
+ }
1781
+ let sum = 0;
1782
+ const l = tuple.length;
1783
+ for (i = 0;i < l; i++) {
1784
+ sum += tuple[i] * Math.pow(256, i);
1785
+ }
1786
+ return positive ? sum : -1 * sum;
1787
+ }
1788
+ function decodeOct(val, offset, length) {
1789
+ val = val.subarray(offset, offset + length);
1790
+ offset = 0;
1791
+ if (val[offset] & 128) {
1792
+ return parse256(val);
1793
+ } else {
1794
+ while (offset < val.length && val[offset] === 32)
1795
+ offset++;
1796
+ const end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length);
1797
+ while (offset < end && val[offset] === 0)
1798
+ offset++;
1799
+ if (end === offset)
1800
+ return 0;
1801
+ return parseInt(b4a.toString(val.subarray(offset, end)), 8);
1802
+ }
1803
+ }
1804
+ function decodeStr(val, offset, length, encoding) {
1805
+ return b4a.toString(val.subarray(offset, indexOf(val, 0, offset, offset + length)), encoding);
1806
+ }
1807
+ function addLength(str) {
1808
+ const len = b4a.byteLength(str);
1809
+ let digits = Math.floor(Math.log(len) / Math.log(10)) + 1;
1810
+ if (len + digits >= Math.pow(10, digits))
1811
+ digits++;
1812
+ return len + digits + str;
1813
+ }
1814
+ });
1815
+
1816
+ // ../../node_modules/tar-stream/extract.js
1817
+ var require_extract = __commonJS(function(exports, module) {
1818
+ var { Writable, Readable, getStreamError } = require_streamx();
1819
+ var FIFO = require_fast_fifo();
1820
+ var b4a = require_b4a();
1821
+ var headers = require_headers();
1822
+ var EMPTY = b4a.alloc(0);
1823
+
1824
+ class BufferList {
1825
+ constructor() {
1826
+ this.buffered = 0;
1827
+ this.shifted = 0;
1828
+ this.queue = new FIFO;
1829
+ this._offset = 0;
1830
+ }
1831
+ push(buffer) {
1832
+ this.buffered += buffer.byteLength;
1833
+ this.queue.push(buffer);
1834
+ }
1835
+ shiftFirst(size) {
1836
+ return this._buffered === 0 ? null : this._next(size);
1837
+ }
1838
+ shift(size) {
1839
+ if (size > this.buffered)
1840
+ return null;
1841
+ if (size === 0)
1842
+ return EMPTY;
1843
+ let chunk = this._next(size);
1844
+ if (size === chunk.byteLength)
1845
+ return chunk;
1846
+ const chunks = [chunk];
1847
+ while ((size -= chunk.byteLength) > 0) {
1848
+ chunk = this._next(size);
1849
+ chunks.push(chunk);
1850
+ }
1851
+ return b4a.concat(chunks);
1852
+ }
1853
+ _next(size) {
1854
+ const buf = this.queue.peek();
1855
+ const rem = buf.byteLength - this._offset;
1856
+ if (size >= rem) {
1857
+ const sub = this._offset ? buf.subarray(this._offset, buf.byteLength) : buf;
1858
+ this.queue.shift();
1859
+ this._offset = 0;
1860
+ this.buffered -= rem;
1861
+ this.shifted += rem;
1862
+ return sub;
1863
+ }
1864
+ this.buffered -= size;
1865
+ this.shifted += size;
1866
+ return buf.subarray(this._offset, this._offset += size);
1867
+ }
1868
+ }
1869
+
1870
+ class Source extends Readable {
1871
+ constructor(self, header, offset) {
1872
+ super();
1873
+ this.header = header;
1874
+ this.offset = offset;
1875
+ this._parent = self;
1876
+ }
1877
+ _read(cb) {
1878
+ if (this.header.size === 0) {
1879
+ this.push(null);
1880
+ }
1881
+ if (this._parent._stream === this) {
1882
+ this._parent._update();
1883
+ }
1884
+ cb(null);
1885
+ }
1886
+ _predestroy() {
1887
+ this._parent.destroy(getStreamError(this));
1888
+ }
1889
+ _detach() {
1890
+ if (this._parent._stream === this) {
1891
+ this._parent._stream = null;
1892
+ this._parent._missing = overflow(this.header.size);
1893
+ this._parent._update();
1894
+ }
1895
+ }
1896
+ _destroy(cb) {
1897
+ this._detach();
1898
+ cb(null);
1899
+ }
1900
+ }
1901
+
1902
+ class Extract extends Writable {
1903
+ constructor(opts) {
1904
+ super(opts);
1905
+ if (!opts)
1906
+ opts = {};
1907
+ this._buffer = new BufferList;
1908
+ this._offset = 0;
1909
+ this._header = null;
1910
+ this._stream = null;
1911
+ this._missing = 0;
1912
+ this._longHeader = false;
1913
+ this._callback = noop;
1914
+ this._locked = false;
1915
+ this._finished = false;
1916
+ this._pax = null;
1917
+ this._paxGlobal = null;
1918
+ this._gnuLongPath = null;
1919
+ this._gnuLongLinkPath = null;
1920
+ this._filenameEncoding = opts.filenameEncoding || "utf-8";
1921
+ this._allowUnknownFormat = !!opts.allowUnknownFormat;
1922
+ this._unlockBound = this._unlock.bind(this);
1923
+ }
1924
+ _unlock(err) {
1925
+ this._locked = false;
1926
+ if (err) {
1927
+ this.destroy(err);
1928
+ this._continueWrite(err);
1929
+ return;
1930
+ }
1931
+ this._update();
1932
+ }
1933
+ _consumeHeader() {
1934
+ if (this._locked)
1935
+ return false;
1936
+ this._offset = this._buffer.shifted;
1937
+ try {
1938
+ this._header = headers.decode(this._buffer.shift(512), this._filenameEncoding, this._allowUnknownFormat);
1939
+ } catch (err) {
1940
+ this._continueWrite(err);
1941
+ return false;
1942
+ }
1943
+ if (!this._header)
1944
+ return true;
1945
+ switch (this._header.type) {
1946
+ case "gnu-long-path":
1947
+ case "gnu-long-link-path":
1948
+ case "pax-global-header":
1949
+ case "pax-header":
1950
+ this._longHeader = true;
1951
+ this._missing = this._header.size;
1952
+ return true;
1953
+ }
1954
+ this._locked = true;
1955
+ this._applyLongHeaders();
1956
+ if (this._header.size === 0 || this._header.type === "directory") {
1957
+ this.emit("entry", this._header, this._createStream(), this._unlockBound);
1958
+ return true;
1959
+ }
1960
+ this._stream = this._createStream();
1961
+ this._missing = this._header.size;
1962
+ this.emit("entry", this._header, this._stream, this._unlockBound);
1963
+ return true;
1964
+ }
1965
+ _applyLongHeaders() {
1966
+ if (this._gnuLongPath) {
1967
+ this._header.name = this._gnuLongPath;
1968
+ this._gnuLongPath = null;
1969
+ }
1970
+ if (this._gnuLongLinkPath) {
1971
+ this._header.linkname = this._gnuLongLinkPath;
1972
+ this._gnuLongLinkPath = null;
1973
+ }
1974
+ if (this._pax) {
1975
+ if (this._pax.path)
1976
+ this._header.name = this._pax.path;
1977
+ if (this._pax.linkpath)
1978
+ this._header.linkname = this._pax.linkpath;
1979
+ if (this._pax.size)
1980
+ this._header.size = parseInt(this._pax.size, 10);
1981
+ this._header.pax = this._pax;
1982
+ this._pax = null;
1983
+ }
1984
+ }
1985
+ _decodeLongHeader(buf) {
1986
+ switch (this._header.type) {
1987
+ case "gnu-long-path":
1988
+ this._gnuLongPath = headers.decodeLongPath(buf, this._filenameEncoding);
1989
+ break;
1990
+ case "gnu-long-link-path":
1991
+ this._gnuLongLinkPath = headers.decodeLongPath(buf, this._filenameEncoding);
1992
+ break;
1993
+ case "pax-global-header":
1994
+ this._paxGlobal = headers.decodePax(buf);
1995
+ break;
1996
+ case "pax-header":
1997
+ this._pax = this._paxGlobal === null ? headers.decodePax(buf) : Object.assign({}, this._paxGlobal, headers.decodePax(buf));
1998
+ break;
1999
+ }
2000
+ }
2001
+ _consumeLongHeader() {
2002
+ this._longHeader = false;
2003
+ this._missing = overflow(this._header.size);
2004
+ const buf = this._buffer.shift(this._header.size);
2005
+ try {
2006
+ this._decodeLongHeader(buf);
2007
+ } catch (err) {
2008
+ this._continueWrite(err);
2009
+ return false;
2010
+ }
2011
+ return true;
2012
+ }
2013
+ _consumeStream() {
2014
+ const buf = this._buffer.shiftFirst(this._missing);
2015
+ if (buf === null)
2016
+ return false;
2017
+ this._missing -= buf.byteLength;
2018
+ const drained = this._stream.push(buf);
2019
+ if (this._missing === 0) {
2020
+ this._stream.push(null);
2021
+ if (drained)
2022
+ this._stream._detach();
2023
+ return drained && this._locked === false;
2024
+ }
2025
+ return drained;
2026
+ }
2027
+ _createStream() {
2028
+ return new Source(this, this._header, this._offset);
2029
+ }
2030
+ _update() {
2031
+ while (this._buffer.buffered > 0 && !this.destroying) {
2032
+ if (this._missing > 0) {
2033
+ if (this._stream !== null) {
2034
+ if (this._consumeStream() === false)
2035
+ return;
2036
+ continue;
2037
+ }
2038
+ if (this._longHeader === true) {
2039
+ if (this._missing > this._buffer.buffered)
2040
+ break;
2041
+ if (this._consumeLongHeader() === false)
2042
+ return false;
2043
+ continue;
2044
+ }
2045
+ const ignore = this._buffer.shiftFirst(this._missing);
2046
+ if (ignore !== null)
2047
+ this._missing -= ignore.byteLength;
2048
+ continue;
2049
+ }
2050
+ if (this._buffer.buffered < 512)
2051
+ break;
2052
+ if (this._stream !== null || this._consumeHeader() === false)
2053
+ return;
2054
+ }
2055
+ this._continueWrite(null);
2056
+ }
2057
+ _continueWrite(err) {
2058
+ const cb = this._callback;
2059
+ this._callback = noop;
2060
+ cb(err);
2061
+ }
2062
+ _write(data, cb) {
2063
+ this._callback = cb;
2064
+ this._buffer.push(data);
2065
+ this._update();
2066
+ }
2067
+ _final(cb) {
2068
+ this._finished = this._missing === 0 && this._buffer.buffered === 0;
2069
+ cb(this._finished ? null : new Error("Unexpected end of data"));
2070
+ }
2071
+ _predestroy() {
2072
+ this._continueWrite(null);
2073
+ }
2074
+ _destroy(cb) {
2075
+ if (this._stream)
2076
+ this._stream.destroy(getStreamError(this));
2077
+ cb(null);
2078
+ }
2079
+ [Symbol.asyncIterator]() {
2080
+ let error = null;
2081
+ let promiseResolve = null;
2082
+ let promiseReject = null;
2083
+ let entryStream = null;
2084
+ let entryCallback = null;
2085
+ const extract = this;
2086
+ this.on("entry", onentry);
2087
+ this.on("error", (err) => {
2088
+ error = err;
2089
+ });
2090
+ this.on("close", onclose);
2091
+ return {
2092
+ [Symbol.asyncIterator]() {
2093
+ return this;
2094
+ },
2095
+ next() {
2096
+ return new Promise(onnext);
2097
+ },
2098
+ return() {
2099
+ return destroy(null);
2100
+ },
2101
+ throw(err) {
2102
+ return destroy(err);
2103
+ }
2104
+ };
2105
+ function consumeCallback(err) {
2106
+ if (!entryCallback)
2107
+ return;
2108
+ const cb = entryCallback;
2109
+ entryCallback = null;
2110
+ cb(err);
2111
+ }
2112
+ function onnext(resolve, reject) {
2113
+ if (error) {
2114
+ return reject(error);
2115
+ }
2116
+ if (entryStream) {
2117
+ resolve({ value: entryStream, done: false });
2118
+ entryStream = null;
2119
+ return;
2120
+ }
2121
+ promiseResolve = resolve;
2122
+ promiseReject = reject;
2123
+ consumeCallback(null);
2124
+ if (extract._finished && promiseResolve) {
2125
+ promiseResolve({ value: undefined, done: true });
2126
+ promiseResolve = promiseReject = null;
2127
+ }
2128
+ }
2129
+ function onentry(header, stream, callback) {
2130
+ entryCallback = callback;
2131
+ stream.on("error", noop);
2132
+ if (promiseResolve) {
2133
+ promiseResolve({ value: stream, done: false });
2134
+ promiseResolve = promiseReject = null;
2135
+ } else {
2136
+ entryStream = stream;
2137
+ }
2138
+ }
2139
+ function onclose() {
2140
+ consumeCallback(error);
2141
+ if (!promiseResolve)
2142
+ return;
2143
+ if (error)
2144
+ promiseReject(error);
2145
+ else
2146
+ promiseResolve({ value: undefined, done: true });
2147
+ promiseResolve = promiseReject = null;
2148
+ }
2149
+ function destroy(err) {
2150
+ extract.destroy(err);
2151
+ consumeCallback(err);
2152
+ return new Promise((resolve, reject) => {
2153
+ if (extract.destroyed)
2154
+ return resolve({ value: undefined, done: true });
2155
+ extract.once("close", function() {
2156
+ if (err)
2157
+ reject(err);
2158
+ else
2159
+ resolve({ value: undefined, done: true });
2160
+ });
2161
+ });
2162
+ }
2163
+ }
2164
+ }
2165
+ module.exports = function extract(opts) {
2166
+ return new Extract(opts);
2167
+ };
2168
+ function noop() {}
2169
+ function overflow(size) {
2170
+ size &= 511;
2171
+ return size && 512 - size;
2172
+ }
2173
+ });
2174
+
2175
+ // ../../node_modules/tar-stream/constants.js
2176
+ var require_constants = __commonJS(function(exports, module) {
2177
+ var constants = {
2178
+ S_IFMT: 61440,
2179
+ S_IFDIR: 16384,
2180
+ S_IFCHR: 8192,
2181
+ S_IFBLK: 24576,
2182
+ S_IFIFO: 4096,
2183
+ S_IFLNK: 40960
2184
+ };
2185
+ try {
2186
+ module.exports = __require("fs").constants || constants;
2187
+ } catch {
2188
+ module.exports = constants;
2189
+ }
2190
+ });
2191
+
2192
+ // ../../node_modules/tar-stream/pack.js
2193
+ var require_pack = __commonJS(function(exports, module) {
2194
+ var { Readable, Writable, getStreamError } = require_streamx();
2195
+ var b4a = require_b4a();
2196
+ var constants = require_constants();
2197
+ var headers = require_headers();
2198
+ var DMODE = 493;
2199
+ var FMODE = 420;
2200
+ var END_OF_TAR = b4a.alloc(1024);
2201
+
2202
+ class Sink extends Writable {
2203
+ constructor(pack, header, callback) {
2204
+ super({ mapWritable, eagerOpen: true });
2205
+ this.written = 0;
2206
+ this.header = header;
2207
+ this._callback = callback;
2208
+ this._linkname = null;
2209
+ this._isLinkname = header.type === "symlink" && !header.linkname;
2210
+ this._isVoid = header.type !== "file" && header.type !== "contiguous-file";
2211
+ this._finished = false;
2212
+ this._pack = pack;
2213
+ this._openCallback = null;
2214
+ if (this._pack._stream === null)
2215
+ this._pack._stream = this;
2216
+ else
2217
+ this._pack._pending.push(this);
2218
+ }
2219
+ _open(cb) {
2220
+ this._openCallback = cb;
2221
+ if (this._pack._stream === this)
2222
+ this._continueOpen();
2223
+ }
2224
+ _continuePack(err) {
2225
+ if (this._callback === null)
2226
+ return;
2227
+ const callback = this._callback;
2228
+ this._callback = null;
2229
+ callback(err);
2230
+ }
2231
+ _continueOpen() {
2232
+ if (this._pack._stream === null)
2233
+ this._pack._stream = this;
2234
+ const cb = this._openCallback;
2235
+ this._openCallback = null;
2236
+ if (cb === null)
2237
+ return;
2238
+ if (this._pack.destroying)
2239
+ return cb(new Error("pack stream destroyed"));
2240
+ if (this._pack._finalized)
2241
+ return cb(new Error("pack stream is already finalized"));
2242
+ this._pack._stream = this;
2243
+ if (!this._isLinkname) {
2244
+ this._pack._encode(this.header);
2245
+ }
2246
+ if (this._isVoid) {
2247
+ this._finish();
2248
+ this._continuePack(null);
2249
+ }
2250
+ cb(null);
2251
+ }
2252
+ _write(data, cb) {
2253
+ if (this._isLinkname) {
2254
+ this._linkname = this._linkname ? b4a.concat([this._linkname, data]) : data;
2255
+ return cb(null);
2256
+ }
2257
+ if (this._isVoid) {
2258
+ if (data.byteLength > 0) {
2259
+ return cb(new Error("No body allowed for this entry"));
2260
+ }
2261
+ return cb();
2262
+ }
2263
+ this.written += data.byteLength;
2264
+ if (this._pack.push(data))
2265
+ return cb();
2266
+ this._pack._drain = cb;
2267
+ }
2268
+ _finish() {
2269
+ if (this._finished)
2270
+ return;
2271
+ this._finished = true;
2272
+ if (this._isLinkname) {
2273
+ this.header.linkname = this._linkname ? b4a.toString(this._linkname, "utf-8") : "";
2274
+ this._pack._encode(this.header);
2275
+ }
2276
+ overflow(this._pack, this.header.size);
2277
+ this._pack._done(this);
2278
+ }
2279
+ _final(cb) {
2280
+ if (this.written !== this.header.size) {
2281
+ return cb(new Error("Size mismatch"));
2282
+ }
2283
+ this._finish();
2284
+ cb(null);
2285
+ }
2286
+ _getError() {
2287
+ return getStreamError(this) || new Error("tar entry destroyed");
2288
+ }
2289
+ _predestroy() {
2290
+ this._pack.destroy(this._getError());
2291
+ }
2292
+ _destroy(cb) {
2293
+ this._pack._done(this);
2294
+ this._continuePack(this._finished ? null : this._getError());
2295
+ cb();
2296
+ }
2297
+ }
2298
+
2299
+ class Pack extends Readable {
2300
+ constructor(opts) {
2301
+ super(opts);
2302
+ this._drain = noop;
2303
+ this._finalized = false;
2304
+ this._finalizing = false;
2305
+ this._pending = [];
2306
+ this._stream = null;
2307
+ }
2308
+ entry(header, buffer, callback) {
2309
+ if (this._finalized || this.destroying)
2310
+ throw new Error("already finalized or destroyed");
2311
+ if (typeof buffer === "function") {
2312
+ callback = buffer;
2313
+ buffer = null;
2314
+ }
2315
+ if (!callback)
2316
+ callback = noop;
2317
+ if (!header.size || header.type === "symlink")
2318
+ header.size = 0;
2319
+ if (!header.type)
2320
+ header.type = modeToType(header.mode);
2321
+ if (!header.mode)
2322
+ header.mode = header.type === "directory" ? DMODE : FMODE;
2323
+ if (!header.uid)
2324
+ header.uid = 0;
2325
+ if (!header.gid)
2326
+ header.gid = 0;
2327
+ if (!header.mtime)
2328
+ header.mtime = new Date;
2329
+ if (typeof buffer === "string")
2330
+ buffer = b4a.from(buffer);
2331
+ const sink = new Sink(this, header, callback);
2332
+ if (b4a.isBuffer(buffer)) {
2333
+ header.size = buffer.byteLength;
2334
+ sink.write(buffer);
2335
+ sink.end();
2336
+ return sink;
2337
+ }
2338
+ if (sink._isVoid) {
2339
+ return sink;
2340
+ }
2341
+ return sink;
2342
+ }
2343
+ finalize() {
2344
+ if (this._stream || this._pending.length > 0) {
2345
+ this._finalizing = true;
2346
+ return;
2347
+ }
2348
+ if (this._finalized)
2349
+ return;
2350
+ this._finalized = true;
2351
+ this.push(END_OF_TAR);
2352
+ this.push(null);
2353
+ }
2354
+ _done(stream) {
2355
+ if (stream !== this._stream)
2356
+ return;
2357
+ this._stream = null;
2358
+ if (this._finalizing)
2359
+ this.finalize();
2360
+ if (this._pending.length)
2361
+ this._pending.shift()._continueOpen();
2362
+ }
2363
+ _encode(header) {
2364
+ if (!header.pax) {
2365
+ const buf = headers.encode(header);
2366
+ if (buf) {
2367
+ this.push(buf);
2368
+ return;
2369
+ }
2370
+ }
2371
+ this._encodePax(header);
2372
+ }
2373
+ _encodePax(header) {
2374
+ const paxHeader = headers.encodePax({
2375
+ name: header.name,
2376
+ linkname: header.linkname,
2377
+ pax: header.pax
2378
+ });
2379
+ const newHeader = {
2380
+ name: "PaxHeader",
2381
+ mode: header.mode,
2382
+ uid: header.uid,
2383
+ gid: header.gid,
2384
+ size: paxHeader.byteLength,
2385
+ mtime: header.mtime,
2386
+ type: "pax-header",
2387
+ linkname: header.linkname && "PaxHeader",
2388
+ uname: header.uname,
2389
+ gname: header.gname,
2390
+ devmajor: header.devmajor,
2391
+ devminor: header.devminor
2392
+ };
2393
+ this.push(headers.encode(newHeader));
2394
+ this.push(paxHeader);
2395
+ overflow(this, paxHeader.byteLength);
2396
+ newHeader.size = header.size;
2397
+ newHeader.type = header.type;
2398
+ this.push(headers.encode(newHeader));
2399
+ }
2400
+ _doDrain() {
2401
+ const drain = this._drain;
2402
+ this._drain = noop;
2403
+ drain();
2404
+ }
2405
+ _predestroy() {
2406
+ const err = getStreamError(this);
2407
+ if (this._stream)
2408
+ this._stream.destroy(err);
2409
+ while (this._pending.length) {
2410
+ const stream = this._pending.shift();
2411
+ stream.destroy(err);
2412
+ stream._continueOpen();
2413
+ }
2414
+ this._doDrain();
2415
+ }
2416
+ _read(cb) {
2417
+ this._doDrain();
2418
+ cb();
2419
+ }
2420
+ }
2421
+ module.exports = function pack(opts) {
2422
+ return new Pack(opts);
2423
+ };
2424
+ function modeToType(mode) {
2425
+ switch (mode & constants.S_IFMT) {
2426
+ case constants.S_IFBLK:
2427
+ return "block-device";
2428
+ case constants.S_IFCHR:
2429
+ return "character-device";
2430
+ case constants.S_IFDIR:
2431
+ return "directory";
2432
+ case constants.S_IFIFO:
2433
+ return "fifo";
2434
+ case constants.S_IFLNK:
2435
+ return "symlink";
2436
+ }
2437
+ return "file";
2438
+ }
2439
+ function noop() {}
2440
+ function overflow(self, size) {
2441
+ size &= 511;
2442
+ if (size)
2443
+ self.push(END_OF_TAR.subarray(0, 512 - size));
2444
+ }
2445
+ function mapWritable(buf) {
2446
+ return b4a.isBuffer(buf) ? buf : b4a.from(buf);
2447
+ }
2448
+ });
2449
+
1
2450
  // src/auth.ts
2
2451
  import { createHash, randomBytes } from "node:crypto";
3
2452
  import { createServer } from "node:http";
@@ -97,7 +2546,7 @@ function readLine(prompt, options = {}) {
97
2546
  var CLIENT_NAME = "aident-cli";
98
2547
  var LOOPBACK_HOST = "127.0.0.1";
99
2548
  var LOGIN_OPEN_TIMEOUT_MS = 90 * 1000;
100
- var LOGIN_COMPLETE_TIMEOUT_AFTER_OPENED_MS = 5 * 60 * 1000;
2549
+ var LOGIN_COMPLETE_TIMEOUT_AFTER_OPENED_MS = 30 * 60 * 1000;
101
2550
  var LOGIN_OPENED_MESSAGE = `User opened the Aident login window. They have ${LOGIN_COMPLETE_TIMEOUT_AFTER_OPENED_MS / 60000} minutes to finish; if it fails, run \`aident login --oob\`, share the URL, and ask for the verification code.`;
102
2551
  async function login(options) {
103
2552
  const baseUrl = options.baseUrl.replace(/\/+$/, "");
@@ -575,7 +3024,7 @@ function getConfigFile() {
575
3024
  function getConfigFileForHome(home) {
576
3025
  return join(getAidentDir(home), "config.json");
577
3026
  }
578
- var DEFAULT_BASE_URL = "https://loadout.aident.ai"?.trim() || "https://loadout.aident.ai";
3027
+ var DEFAULT_BASE_URL = "https://rc.loadout.aident.ai"?.trim() || "https://loadout.aident.ai";
579
3028
  var CONFIG_KEYS = ["baseUrl", "packages"];
580
3029
  async function readConfig(configFile = getConfigFile()) {
581
3030
  try {
@@ -4679,7 +7128,7 @@ function serializeLoadoutSkillPackage(skillPackage) {
4679
7128
  }
4680
7129
 
4681
7130
  // src/version.ts
4682
- var VERSION = "0.3.0";
7131
+ var VERSION = "0.3.1-rc.0";
4683
7132
  var DESKTOP_VERSION = process.env.AIDENT_DESKTOP_VERSION?.trim() || undefined;
4684
7133
  var DESKTOP_CHANNEL = parseDesktopChannel(process.env.AIDENT_DESKTOP_CHANNEL);
4685
7134
  function parseDesktopChannel(value) {
@@ -5883,7 +8332,7 @@ var LoadoutFavoriteSkillsUpdateSchema = objectType({
5883
8332
  syncRequired: booleanType()
5884
8333
  }).strict();
5885
8334
  function getLoadoutFavoriteSkillsStateToken(skills) {
5886
- const state = skills.map(({ name, artifactVersionId }) => ({ name, artifactVersionId })).sort((left, right) => left.name.localeCompare(right.name));
8335
+ const state = skills.map(({ name, artifactVersionId, deliveryRevision }) => ({ name, artifactVersionId, deliveryRevision })).sort((left, right) => left.name.localeCompare(right.name));
5887
8336
  return createHash2("sha256").update(JSON.stringify(state)).digest("hex");
5888
8337
  }
5889
8338
 
@@ -6047,10 +8496,11 @@ var KNOWN_CLEAN_LOADOUT_SKILL_REQUIRED_FILE_GIT_BLOB_SHA1 = {
6047
8496
  }
6048
8497
  ]
6049
8498
  };
6050
- async function fetchLoadoutSkillMetadata(baseUrl) {
8499
+ async function fetchLoadoutSkillMetadata(baseUrl, signal) {
6051
8500
  const metadataUrl = `${baseUrl.replace(/\/+$/, "")}/.well-known/loadout-skill.json`;
6052
8501
  const res = await fetch(metadataUrl, {
6053
8502
  method: "GET",
8503
+ signal,
6054
8504
  headers: {
6055
8505
  "User-Agent": `@aident-ai/cli/${VERSION}`,
6056
8506
  [AIDENT_UPDATE_PROTOCOL_HEADER]: AIDENT_UPDATE_PROTOCOL_VERSION
@@ -6619,11 +9069,466 @@ function isExpired(creds) {
6619
9069
  }
6620
9070
 
6621
9071
  // src/loadoutFavoriteSkills.ts
6622
- import { createHash as createHash4 } from "node:crypto";
6623
- import { lstat as lstat4, mkdir as mkdir6, readFile as readFile7, readlink, rename as rename3, rm as rm2, symlink as symlink2, writeFile as writeFile6 } from "node:fs/promises";
6624
- import { homedir as homedir4 } from "node:os";
9072
+ import { createHash as createHash5 } from "node:crypto";
9073
+ import { cp, lstat as lstat5, mkdir as mkdir8, readFile as readFile8, readlink, rename as rename4, rm as rm3, symlink as symlink3, writeFile as writeFile6 } from "node:fs/promises";
9074
+ import { homedir as homedir5 } from "node:os";
6625
9075
  import path from "node:path";
6626
9076
 
9077
+ // src/agentSkillBundles.ts
9078
+ import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";
9079
+ import { existsSync as existsSync2 } from "node:fs";
9080
+ import { lstat as lstat4, mkdir as mkdir7, mkdtemp, readFile as readFile7, realpath as realpath3, rename as rename3, rm as rm2, symlink as symlink2 } from "node:fs/promises";
9081
+ import { homedir as homedir4 } from "node:os";
9082
+ import { dirname as dirname6, join as join8, resolve as resolve3, sep as sep2 } from "node:path";
9083
+
9084
+ // ../web/shared/agentSkills/AgentSkillBundleArchive.ts
9085
+ import { createWriteStream } from "node:fs";
9086
+ import { mkdir as mkdir6 } from "node:fs/promises";
9087
+ import { dirname as dirname5, posix as posix2, resolve as resolve2, sep } from "node:path";
9088
+ import { Readable, Transform } from "node:stream";
9089
+ import { pipeline } from "node:stream/promises";
9090
+ import { createGunzip, gzipSync } from "node:zlib";
9091
+
9092
+ // ../../node_modules/tar-stream/index.js
9093
+ var $extract = require_extract();
9094
+ var $pack = require_pack();
9095
+
9096
+ // ../web/shared/agentSkills/AgentSkillBundleSchemas.ts
9097
+ var AGENT_SKILL_BUNDLE_BUCKET = "agent-skill-bundles";
9098
+ var AGENT_SKILL_BUNDLE_MAX_ARCHIVE_BYTES = 128 * 1024 * 1024;
9099
+ var AGENT_SKILL_BUNDLE_MAX_UNPACKED_BYTES = 256 * 1024 * 1024;
9100
+ var AGENT_SKILL_BUNDLE_MAX_FILES = 5000;
9101
+ var AgentSkillBundleReleaseStatus;
9102
+ ((AgentSkillBundleReleaseStatus) => {
9103
+ AgentSkillBundleReleaseStatus["Active"] = "active";
9104
+ AgentSkillBundleReleaseStatus["Retired"] = "retired";
9105
+ })(AgentSkillBundleReleaseStatus ||= {});
9106
+ var AgentSkillBundleRightsBasis;
9107
+ ((AgentSkillBundleRightsBasis) => {
9108
+ AgentSkillBundleRightsBasis["AidentOwned"] = "aident-owned";
9109
+ AgentSkillBundleRightsBasis["AuthorizedInternalUse"] = "authorized-internal-use";
9110
+ })(AgentSkillBundleRightsBasis ||= {});
9111
+ var AgentSkillBundleNameSchema = stringType().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).max(80);
9112
+ var AgentSkillBundleVersionSchema = stringType().regex(/^[0-9]+\.[0-9]+\.[0-9]+(?:[+-][0-9A-Za-z.-]+)?$/).max(80);
9113
+ var AgentSkillBundleSha256Schema = stringType().regex(/^[a-f0-9]{64}$/);
9114
+ var AgentSkillBundleGitShaSchema = stringType().regex(/^[a-f0-9]{40}$/);
9115
+ var AgentSkillBundleRightsBasisSchema = nativeEnumType(AgentSkillBundleRightsBasis);
9116
+ var AgentSkillBundleSourcePathSchema = stringType().min(1).max(300).regex(/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/).refine((value) => value.split("/").every((segment) => segment !== "." && segment !== ".."));
9117
+ var AgentSkillBundlePublishManifestSchema = objectType({
9118
+ name: AgentSkillBundleNameSchema,
9119
+ version: AgentSkillBundleVersionSchema,
9120
+ sourceOwner: stringType().regex(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/).max(39).refine((value) => !value.includes("--")),
9121
+ sourceRepository: stringType().regex(/^[A-Za-z0-9_.][A-Za-z0-9_.-]{0,99}$/).refine((value) => value !== "." && value !== ".."),
9122
+ sourcePath: AgentSkillBundleSourcePathSchema.optional(),
9123
+ sourceCommit: AgentSkillBundleGitShaSchema,
9124
+ sourceTree: AgentSkillBundleGitShaSchema,
9125
+ expectedSha256: AgentSkillBundleSha256Schema,
9126
+ expectedBytes: numberType().int().positive().max(AGENT_SKILL_BUNDLE_MAX_ARCHIVE_BYTES),
9127
+ rightsBasis: AgentSkillBundleRightsBasisSchema,
9128
+ rightsNotice: stringType().min(1).max(2000)
9129
+ });
9130
+ var AgentSkillBundlePublishInputSchema = objectType({
9131
+ manifest: AgentSkillBundlePublishManifestSchema
9132
+ });
9133
+ var AgentSkillBundleInstallInputSchema = objectType({
9134
+ name: AgentSkillBundleNameSchema,
9135
+ version: AgentSkillBundleVersionSchema.optional()
9136
+ });
9137
+ var AgentSkillBundleListInputSchema = objectType({
9138
+ name: AgentSkillBundleNameSchema.optional(),
9139
+ status: nativeEnumType(AgentSkillBundleReleaseStatus).default("active" /* Active */)
9140
+ });
9141
+ var AgentSkillBundleReleaseSchema = objectType({
9142
+ id: stringType().uuid(),
9143
+ name: AgentSkillBundleNameSchema,
9144
+ version: AgentSkillBundleVersionSchema,
9145
+ status: nativeEnumType(AgentSkillBundleReleaseStatus),
9146
+ artifactSha256: AgentSkillBundleSha256Schema,
9147
+ artifactBytes: numberType().int().positive(),
9148
+ storageBucket: literalType(AGENT_SKILL_BUNDLE_BUCKET),
9149
+ storageObjectPath: stringType().min(1),
9150
+ sourceOwner: stringType(),
9151
+ sourceRepository: stringType(),
9152
+ sourceCommit: AgentSkillBundleGitShaSchema,
9153
+ sourceTree: AgentSkillBundleGitShaSchema,
9154
+ rightsBasis: AgentSkillBundleRightsBasisSchema,
9155
+ rightsNotice: stringType(),
9156
+ publishedAt: stringType().datetime()
9157
+ });
9158
+ var AgentSkillBundleInstallDescriptorSchema = AgentSkillBundleReleaseSchema.omit({
9159
+ id: true,
9160
+ status: true,
9161
+ storageBucket: true,
9162
+ storageObjectPath: true,
9163
+ rightsNotice: true
9164
+ }).extend({
9165
+ artifactUrl: stringType().url(),
9166
+ expiresAt: stringType().datetime()
9167
+ });
9168
+
9169
+ // ../web/shared/agentSkills/AgentSkillBundleArchive.ts
9170
+ var MAX_SKILL_ENTRYPOINT_BYTES = 64 * 1024;
9171
+ async function extractAgentSkillBundleArchive(archive, expectedSkillName, destination) {
9172
+ await mkdir6(destination, { recursive: true, mode: 448 });
9173
+ return processArchive(archive, expectedSkillName, destination);
9174
+ }
9175
+ async function processArchive(archive, expectedSkillName, destination) {
9176
+ AgentSkillBundleNameSchema.parse(expectedSkillName);
9177
+ const seenPaths = new Set;
9178
+ const rootNames = new Set;
9179
+ let fileCount = 0;
9180
+ let unpackedBytes = 0;
9181
+ let rootSkillContent = null;
9182
+ let extractionError = null;
9183
+ const tarExtractor = $extract();
9184
+ tarExtractor.on("error", (error) => {
9185
+ extractionError = error instanceof Error ? error : new Error(String(error));
9186
+ });
9187
+ tarExtractor.on("entry", (header, stream, next) => {
9188
+ stream.on("error", (error) => {
9189
+ extractionError = error instanceof Error ? error : new Error(String(error));
9190
+ });
9191
+ (async () => {
9192
+ try {
9193
+ const relativePath = normalizeArchivePath(header.name);
9194
+ if (!relativePath) {
9195
+ stream.resume();
9196
+ await onceEnded(stream);
9197
+ next();
9198
+ return;
9199
+ }
9200
+ if (seenPaths.has(relativePath))
9201
+ throw new Error(`Duplicate agent Skill archive entry: ${relativePath}`);
9202
+ seenPaths.add(relativePath);
9203
+ rootNames.add(relativePath.split("/")[0]);
9204
+ if (rootNames.size > 1)
9205
+ throw new Error("Agent Skill archive must contain exactly one root directory");
9206
+ if (header.type !== "file" && header.type !== "directory") {
9207
+ throw new Error(`Unsupported agent Skill archive entry type: ${header.type ?? "unknown"}`);
9208
+ }
9209
+ if (header.type === "directory") {
9210
+ if (destination)
9211
+ await mkdir6(resolveDestination(destination, relativePath), { recursive: true, mode: 448 });
9212
+ stream.resume();
9213
+ await onceEnded(stream);
9214
+ next();
9215
+ return;
9216
+ }
9217
+ fileCount++;
9218
+ if (fileCount > AGENT_SKILL_BUNDLE_MAX_FILES)
9219
+ throw new Error("Agent Skill archive contains too many files");
9220
+ const entrySize = header.size ?? 0;
9221
+ unpackedBytes += entrySize;
9222
+ if (unpackedBytes > AGENT_SKILL_BUNDLE_MAX_UNPACKED_BYTES) {
9223
+ throw new Error("Agent Skill archive exceeds the unpacked size limit");
9224
+ }
9225
+ const rootName = relativePath.split("/")[0];
9226
+ const isRootSkillEntrypoint = relativePath === `${rootName}/SKILL.md`;
9227
+ if (isRootSkillEntrypoint && entrySize > MAX_SKILL_ENTRYPOINT_BYTES) {
9228
+ throw new Error("Agent Skill entrypoint exceeds the size limit");
9229
+ }
9230
+ const chunks = [];
9231
+ const capture = new Transform({
9232
+ transform(chunk, _encoding, callback) {
9233
+ if (isRootSkillEntrypoint)
9234
+ chunks.push(Buffer.from(chunk));
9235
+ callback(null, chunk);
9236
+ }
9237
+ });
9238
+ if (destination) {
9239
+ const outputPath = resolveDestination(destination, relativePath);
9240
+ await mkdir6(dirname5(outputPath), { recursive: true, mode: 448 });
9241
+ await pipeline(stream, capture, createWriteStream(outputPath, { flags: "wx", mode: safeFileMode(header) }));
9242
+ } else {
9243
+ await pipeline(stream, capture, new Transform({
9244
+ transform(_chunk, _encoding, callback) {
9245
+ callback();
9246
+ }
9247
+ }));
9248
+ }
9249
+ if (isRootSkillEntrypoint)
9250
+ rootSkillContent = Buffer.concat(chunks).toString("utf8");
9251
+ next();
9252
+ } catch (error) {
9253
+ stream.resume();
9254
+ next(error);
9255
+ }
9256
+ })();
9257
+ });
9258
+ try {
9259
+ await pipeline(Readable.from(archive), createGunzip(), tarExtractor);
9260
+ } catch (error) {
9261
+ throw extractionError ?? error;
9262
+ }
9263
+ const rootDirectory = Array.from(rootNames)[0];
9264
+ if (!rootDirectory)
9265
+ throw new Error("Agent Skill archive is empty");
9266
+ if (!rootSkillContent)
9267
+ throw new Error("Agent Skill archive is missing its root SKILL.md");
9268
+ const skillName = readSkillName(rootSkillContent);
9269
+ if (skillName !== expectedSkillName) {
9270
+ throw new Error(`Agent Skill archive identity mismatch: expected ${expectedSkillName}, received ${skillName}`);
9271
+ }
9272
+ return { fileCount, rootDirectory, skillName, unpackedBytes };
9273
+ }
9274
+ function normalizeArchivePath(value) {
9275
+ const withoutPrefix = value.replace(/^\.\//, "").replace(/\/$/, "");
9276
+ const normalized = posix2.normalize(withoutPrefix);
9277
+ if (!withoutPrefix)
9278
+ return "";
9279
+ if (withoutPrefix.includes("\\") || withoutPrefix.includes("\x00") || posix2.isAbsolute(withoutPrefix) || normalized === ".." || normalized.startsWith("../") || normalized !== withoutPrefix || withoutPrefix.length > 500) {
9280
+ throw new Error(`Unsafe agent Skill archive path: ${value}`);
9281
+ }
9282
+ return normalized;
9283
+ }
9284
+ function resolveDestination(destination, relativePath) {
9285
+ const root = resolve2(destination);
9286
+ const output = resolve2(root, ...relativePath.split("/"));
9287
+ if (output !== root && !output.startsWith(`${root}${sep}`)) {
9288
+ throw new Error(`Agent Skill archive path escapes its destination: ${relativePath}`);
9289
+ }
9290
+ return output;
9291
+ }
9292
+ function safeFileMode(header) {
9293
+ return (header.mode ?? 420) & 493;
9294
+ }
9295
+ function readSkillName(content) {
9296
+ const frontmatter = content.match(/^---\n([\s\S]*?)\n---(?:\n|$)/)?.[1];
9297
+ const name = frontmatter?.match(/^name:\s*["']?([^\s"']+)["']?\s*$/m)?.[1];
9298
+ if (!name)
9299
+ throw new Error("Agent Skill SKILL.md is missing a frontmatter name");
9300
+ return AgentSkillBundleNameSchema.parse(name);
9301
+ }
9302
+ function onceEnded(stream) {
9303
+ return new Promise((resolvePromise, reject) => {
9304
+ stream.once("end", resolvePromise);
9305
+ stream.once("error", reject);
9306
+ });
9307
+ }
9308
+
9309
+ // src/agentSkillBundles.ts
9310
+ async function installAgentSkillBundle(descriptorValue, options = {}, injected = {}) {
9311
+ const descriptor = AgentSkillBundleInstallDescriptorSchema.parse(descriptorValue);
9312
+ const home = options.home ?? homedir4();
9313
+ const env = options.env ?? process.env;
9314
+ return withInstallLock(descriptor.name, home, async () => {
9315
+ const { releaseDirectory } = await prepareRelease(descriptor, home, injected.fetch ?? fetch);
9316
+ const targets = await reconcileTargets(descriptor.name, releaseDirectory, dirname6(releaseDirectory), home, env);
9317
+ return {
9318
+ name: descriptor.name,
9319
+ version: descriptor.version,
9320
+ artifactSha256: descriptor.artifactSha256,
9321
+ releaseDirectory,
9322
+ success: targets.every((target) => target.status !== "conflict" /* Conflict */ && target.status !== "failed" /* Failed */),
9323
+ targets
9324
+ };
9325
+ });
9326
+ }
9327
+ async function prepareAgentSkillBundleRelease(descriptorValue, options = {}, injected = {}) {
9328
+ const descriptor = AgentSkillBundleInstallDescriptorSchema.parse(descriptorValue);
9329
+ const home = options.home ?? homedir4();
9330
+ return withInstallLock(descriptor.name, home, () => prepareRelease(descriptor, home, injected.fetch ?? fetch));
9331
+ }
9332
+ async function prepareRelease(descriptor, home, fetchImpl) {
9333
+ const stateRoot = join8(home, ".aident", "skills", "internal", descriptor.name);
9334
+ const releasesRoot = join8(stateRoot, "releases");
9335
+ const releaseDirectory = join8(releasesRoot, descriptor.artifactSha256);
9336
+ if (!await pathExists2(releaseDirectory)) {
9337
+ const archive = await downloadArchive(descriptor, fetchImpl);
9338
+ await materializeRelease(archive, descriptor, releasesRoot, releaseDirectory);
9339
+ } else {
9340
+ const existingRelease = await lstat4(releaseDirectory);
9341
+ if (!existingRelease.isDirectory()) {
9342
+ throw new Error(`Existing agent Skill release is not a directory: ${releaseDirectory}`);
9343
+ }
9344
+ await assertInstalledSkillIdentity(releaseDirectory, descriptor.name);
9345
+ }
9346
+ return { descriptor, releaseDirectory };
9347
+ }
9348
+ async function withInstallLock(name, home, run) {
9349
+ const stateRoot = join8(home, ".aident", "skills", "internal", name);
9350
+ await mkdir7(stateRoot, { recursive: true, mode: 448 });
9351
+ const lock = await tryAcquireDirectoryLock(join8(stateRoot, "install.lock"));
9352
+ if (!lock)
9353
+ throw new Error(`Another ${name} installation is already running`);
9354
+ try {
9355
+ return await run();
9356
+ } finally {
9357
+ await lock.release();
9358
+ }
9359
+ }
9360
+ async function genInstallAgentSkillBundleCommandResult(resolved, result, install = installAgentSkillBundle) {
9361
+ if (resolved.domain !== "admin:agent-skills" || resolved.command !== "install" || !result.body.success)
9362
+ return result;
9363
+ try {
9364
+ const installed = await install(result.body.data);
9365
+ return {
9366
+ ...result,
9367
+ body: installed.success ? { success: true, data: installed } : {
9368
+ success: false,
9369
+ data: installed,
9370
+ error: {
9371
+ code: "agent-skill-install-incomplete",
9372
+ message: "Some local Skill targets were preserved or failed"
9373
+ }
9374
+ }
9375
+ };
9376
+ } catch (error) {
9377
+ return {
9378
+ ...result,
9379
+ body: {
9380
+ success: false,
9381
+ error: {
9382
+ code: "agent-skill-install-failed",
9383
+ message: error instanceof Error ? error.message : String(error)
9384
+ }
9385
+ }
9386
+ };
9387
+ }
9388
+ }
9389
+ async function downloadArchive(descriptor, fetchImpl) {
9390
+ const response = await fetchImpl(descriptor.artifactUrl, { signal: AbortSignal.timeout(5 * 60 * 1000) });
9391
+ if (!response.ok)
9392
+ throw new Error(`Failed to download ${descriptor.name}: HTTP ${response.status}`);
9393
+ const contentLength = response.headers.get("content-length");
9394
+ if (contentLength && Number(contentLength) !== descriptor.artifactBytes) {
9395
+ throw new Error(`Agent Skill archive size mismatch: expected ${descriptor.artifactBytes}, received ${contentLength}`);
9396
+ }
9397
+ if (descriptor.artifactBytes > AGENT_SKILL_BUNDLE_MAX_ARCHIVE_BYTES) {
9398
+ throw new Error("Agent Skill archive exceeds the compressed size limit");
9399
+ }
9400
+ const archive = Buffer.from(await response.arrayBuffer());
9401
+ if (archive.length !== descriptor.artifactBytes) {
9402
+ throw new Error(`Agent Skill archive size mismatch: expected ${descriptor.artifactBytes}, received ${archive.length}`);
9403
+ }
9404
+ const digest = createHash4("sha256").update(archive).digest("hex");
9405
+ if (digest !== descriptor.artifactSha256) {
9406
+ throw new Error(`Agent Skill archive digest mismatch: expected ${descriptor.artifactSha256}, received ${digest}`);
9407
+ }
9408
+ return archive;
9409
+ }
9410
+ async function materializeRelease(archive, descriptor, releasesRoot, releaseDirectory) {
9411
+ await mkdir7(releasesRoot, { recursive: true, mode: 448 });
9412
+ const transactionRoot = await mkdtemp(join8(stateParent(releasesRoot), ".install-"));
9413
+ const extractRoot = join8(transactionRoot, "extract");
9414
+ try {
9415
+ const inspection = await extractAgentSkillBundleArchive(archive, descriptor.name, extractRoot);
9416
+ const sourceDirectory = join8(extractRoot, inspection.rootDirectory);
9417
+ await assertInstalledSkillIdentity(sourceDirectory, descriptor.name);
9418
+ await rename3(sourceDirectory, releaseDirectory);
9419
+ } finally {
9420
+ await rm2(transactionRoot, { recursive: true, force: true });
9421
+ }
9422
+ }
9423
+ async function reconcileTargets(name, releaseDirectory, releasesRoot, home, env) {
9424
+ const roots = getGlobalLoadoutSkillHostRoots(home, env);
9425
+ const canonical = roots.find((root) => root.canonical);
9426
+ if (!canonical)
9427
+ throw new Error("Canonical Aident Skill host is unavailable");
9428
+ const detectedWorkBuddyRoots = new Set(getDetectedWorkBuddySkillHostRoots(home, env).map((root) => resolve3(root)));
9429
+ const selected = roots.filter((root) => root.canonical || existsSync2(root.root) || root.agent === "workbuddy" /* WorkBuddy */ && detectedWorkBuddyRoots.has(resolve3(root.root)));
9430
+ const results = [];
9431
+ const canonicalPath = join8(canonical.root, "skills", name);
9432
+ results.push(await reconcileTarget(canonical.agent, canonicalPath, releaseDirectory, releasesRoot));
9433
+ if (results[0]?.status !== "current" /* Current */ && results[0]?.status !== "installed" /* Installed */ && results[0]?.status !== "updated" /* Updated */) {
9434
+ return results;
9435
+ }
9436
+ for (const root of selected) {
9437
+ if (root.canonical)
9438
+ continue;
9439
+ results.push(await reconcileTarget(root.agent, join8(root.root, "skills", name), canonicalPath, releasesRoot));
9440
+ }
9441
+ return results;
9442
+ }
9443
+ async function reconcileTarget(agent, target, desired, releasesRoot) {
9444
+ const desiredRealPath = await realpath3(desired);
9445
+ const currentRealPath = await realpath3(target).catch(() => null);
9446
+ if (currentRealPath === desiredRealPath) {
9447
+ return { agent, path: target, status: "current" /* Current */ };
9448
+ }
9449
+ const existing = await lstat4(target).catch((error) => {
9450
+ if (error.code === "ENOENT")
9451
+ return null;
9452
+ throw error;
9453
+ });
9454
+ if (existing) {
9455
+ const managedRoot = await realpath3(releasesRoot);
9456
+ if (!existing.isSymbolicLink() || !currentRealPath || !isInside(managedRoot, currentRealPath)) {
9457
+ return {
9458
+ agent,
9459
+ path: target,
9460
+ status: "conflict" /* Conflict */,
9461
+ detail: "Existing target is not an Aident-managed internal Skill release"
9462
+ };
9463
+ }
9464
+ }
9465
+ try {
9466
+ await switchManagedLink(target, desired, !!existing);
9467
+ return {
9468
+ agent,
9469
+ path: target,
9470
+ status: existing ? "updated" /* Updated */ : "installed" /* Installed */
9471
+ };
9472
+ } catch (error) {
9473
+ return {
9474
+ agent,
9475
+ path: target,
9476
+ status: "failed" /* Failed */,
9477
+ detail: error instanceof Error ? error.message : String(error)
9478
+ };
9479
+ }
9480
+ }
9481
+ async function switchManagedLink(target, desired, exists) {
9482
+ await mkdir7(dirname6(target), { recursive: true, mode: 448 });
9483
+ const token = randomUUID3();
9484
+ const temporary = `${target}.${token}.tmp`;
9485
+ const backup = `${target}.${token}.backup`;
9486
+ await symlink2(desired, temporary, process.platform === "win32" ? "junction" : "dir");
9487
+ if (!exists) {
9488
+ try {
9489
+ await rename3(temporary, target);
9490
+ } catch (error) {
9491
+ await rm2(temporary, { force: true });
9492
+ throw error;
9493
+ }
9494
+ return;
9495
+ }
9496
+ await rename3(target, backup);
9497
+ try {
9498
+ await rename3(temporary, target);
9499
+ await rm2(backup, { force: true });
9500
+ } catch (error) {
9501
+ await rm2(temporary, { force: true });
9502
+ await rename3(backup, target);
9503
+ throw error;
9504
+ }
9505
+ }
9506
+ async function assertInstalledSkillIdentity(directory, expectedName) {
9507
+ const content = await readFile7(join8(directory, "SKILL.md"), "utf8");
9508
+ const frontmatter = content.match(/^---\n([\s\S]*?)\n---(?:\n|$)/)?.[1];
9509
+ const name = frontmatter?.match(/^name:\s*["']?([^\s"']+)["']?\s*$/m)?.[1];
9510
+ if (name !== expectedName)
9511
+ throw new Error(`Installed agent Skill identity mismatch: expected ${expectedName}`);
9512
+ }
9513
+ async function pathExists2(path) {
9514
+ try {
9515
+ await lstat4(path);
9516
+ return true;
9517
+ } catch (error) {
9518
+ if (error.code === "ENOENT")
9519
+ return false;
9520
+ throw error;
9521
+ }
9522
+ }
9523
+ function stateParent(releasesRoot) {
9524
+ return dirname6(releasesRoot);
9525
+ }
9526
+ function isInside(root, value) {
9527
+ const resolvedRoot = resolve3(root);
9528
+ const resolvedValue = resolve3(value);
9529
+ return resolvedValue === resolvedRoot || resolvedValue.startsWith(`${resolvedRoot}${sep2}`);
9530
+ }
9531
+
6627
9532
  // ../web/shared/integrations/LoadoutSkillConstants.ts
6628
9533
  var LOADOUT_SKILL_ENTRYPOINT = "SKILL.md";
6629
9534
  var LOADOUT_SKILL_PLATFORM_SECTION_HEADING = "Aident Loadout Platform";
@@ -6650,7 +9555,7 @@ function isCanonicalUuid(value) {
6650
9555
  return value === value.toLowerCase() && extractUUID(value) === value;
6651
9556
  }
6652
9557
  function getHome() {
6653
- return process.env.HOME || process.env.USERPROFILE || homedir4();
9558
+ return process.env.HOME || process.env.USERPROFILE || homedir5();
6654
9559
  }
6655
9560
  function getCanonicalRoot(home, env) {
6656
9561
  return path.join(getGlobalLoadoutSkillHostRoots(home, env).find(({ canonical }) => canonical).root, "skills");
@@ -6693,12 +9598,14 @@ function assertPackage(pkg) {
6693
9598
  packageBytes += bytes;
6694
9599
  if (bytes !== file.sizeBytes)
6695
9600
  throw new Error(`Size mismatch: ${pkg.name}/${file.path}`);
6696
- if (createHash4("sha256").update(file.content).digest("hex") !== file.contentDigest) {
9601
+ if (createHash5("sha256").update(file.content).digest("hex") !== file.contentDigest) {
6697
9602
  throw new Error(`Digest mismatch: ${pkg.name}/${file.path}`);
6698
9603
  }
6699
9604
  }
6700
9605
  if (packageBytes > LOADOUT_SKILL_MAX_PACKAGE_BYTES)
6701
9606
  throw new Error(`Package is too large: ${pkg.name}`);
9607
+ if (pkg.bundle)
9608
+ AgentSkillBundleInstallDescriptorSchema.parse(pkg.bundle);
6702
9609
  }
6703
9610
  function quoteYaml(value) {
6704
9611
  return JSON.stringify(value);
@@ -6724,9 +9631,9 @@ function entrypointContent(pkg, content) {
6724
9631
  ].join(`
6725
9632
  `);
6726
9633
  }
6727
- async function pathExists2(target) {
9634
+ async function pathExists3(target) {
6728
9635
  try {
6729
- await lstat4(target);
9636
+ await lstat5(target);
6730
9637
  return true;
6731
9638
  } catch (error) {
6732
9639
  if (error.code === "ENOENT")
@@ -6736,12 +9643,12 @@ async function pathExists2(target) {
6736
9643
  }
6737
9644
  async function readManifest(home, env) {
6738
9645
  try {
6739
- const value = JSON.parse(await readFile7(getManifestPath(home), "utf8"));
9646
+ const value = JSON.parse(await readFile8(getManifestPath(home), "utf8"));
6740
9647
  if (value.version !== MANIFEST_VERSION || !Array.isArray(value.skills))
6741
9648
  throw new Error("Unsupported manifest");
6742
9649
  const harnessRoots = new Set(getHarnessHosts(home, env).map(({ root }) => path.join(root, "skills")));
6743
9650
  for (const skill of value.skills) {
6744
- if (!LOADOUT_SKILL_NAME_PATTERN.test(skill.name) || !isCanonicalUuid(skill.artifactVersionId) || skill.displayName !== undefined && typeof skill.displayName !== "string" || skill.summary !== undefined && typeof skill.summary !== "string" || !/^loadout-[a-z0-9-]+-[0-9a-f]{8}$/.test(skill.commandName) || skill.installPath !== path.join(getCanonicalRoot(home, env), skill.commandName) || skill.linkPaths.some((linkPath) => !harnessRoots.has(path.dirname(linkPath)) || path.basename(linkPath) !== skill.commandName)) {
9651
+ if (!LOADOUT_SKILL_NAME_PATTERN.test(skill.name) || !isCanonicalUuid(skill.artifactVersionId) || skill.displayName !== undefined && typeof skill.displayName !== "string" || skill.summary !== undefined && typeof skill.summary !== "string" || skill.deliveryRevision !== undefined && !/^[a-f0-9]{64}$/.test(skill.deliveryRevision) || !/^loadout-[a-z0-9-]+-[0-9a-f]{8}$/.test(skill.commandName) || skill.installPath !== path.join(getCanonicalRoot(home, env), skill.commandName) || skill.linkPaths.some((linkPath) => !harnessRoots.has(path.dirname(linkPath)) || path.basename(linkPath) !== skill.commandName)) {
6745
9652
  throw new Error("Invalid favorite Skills ownership manifest");
6746
9653
  }
6747
9654
  }
@@ -6759,23 +9666,27 @@ async function getInstalledLoadoutFavoriteSkillsStateToken(home = getHome(), env
6759
9666
  async function writeManifest(home, manifest) {
6760
9667
  const manifestPath = getManifestPath(home);
6761
9668
  const temporaryPath = `${manifestPath}.${process.pid}.tmp`;
6762
- await mkdir6(path.dirname(manifestPath), { recursive: true, mode: 448 });
9669
+ await mkdir8(path.dirname(manifestPath), { recursive: true, mode: 448 });
6763
9670
  await writeFile6(temporaryPath, `${JSON.stringify(manifest, null, 2)}
6764
9671
  `, { mode: 384 });
6765
- await rename3(temporaryPath, manifestPath);
9672
+ await rename4(temporaryPath, manifestPath);
6766
9673
  }
6767
9674
  async function removeOwnedSkill(skill) {
6768
9675
  for (const linkPath of skill.linkPaths) {
6769
- if (!await pathExists2(linkPath))
9676
+ if (!await pathExists3(linkPath))
6770
9677
  continue;
6771
- const stat = await lstat4(linkPath);
9678
+ const stat = await lstat5(linkPath);
6772
9679
  if (stat.isSymbolicLink())
6773
- await rm2(linkPath);
9680
+ await rm3(linkPath);
6774
9681
  }
6775
- if (await pathExists2(skill.installPath))
6776
- await rm2(skill.installPath, { recursive: true });
9682
+ if (await pathExists3(skill.installPath))
9683
+ await rm3(skill.installPath, { recursive: true });
6777
9684
  }
6778
- async function reconcileLoadoutFavoriteSkills(payload, home = getHome(), env = process.env) {
9685
+ async function writeBundlePackage(directory, pkg, releaseDirectory) {
9686
+ await cp(releaseDirectory, directory, { recursive: true });
9687
+ await writeFile6(path.join(directory, LOADOUT_SKILL_ENTRYPOINT), entrypointContent(pkg, await readFile8(path.join(releaseDirectory, LOADOUT_SKILL_ENTRYPOINT), "utf8")));
9688
+ }
9689
+ async function reconcileLoadoutFavoriteSkills(payload, home = getHome(), env = process.env, injected = {}) {
6779
9690
  const manifest = await readManifest(home, env);
6780
9691
  const previousByName = new Map(manifest.skills.map((skill) => [skill.name, skill]));
6781
9692
  const desiredNames = new Set(payload.packages.map((pkg) => pkg.name));
@@ -6790,6 +9701,12 @@ async function reconcileLoadoutFavoriteSkills(payload, home = getHome(), env = p
6790
9701
  if (payload.unavailable.some((name) => desiredNames.has(name))) {
6791
9702
  throw new Error("A favorite Skill cannot be both available and unavailable");
6792
9703
  }
9704
+ const preparedBundles = new Map;
9705
+ for (const pkg of payload.packages) {
9706
+ if (!pkg.bundle)
9707
+ continue;
9708
+ preparedBundles.set(pkg.name, await (injected.prepareBundleRelease ?? prepareAgentSkillBundleRelease)(pkg.bundle, { home, env }));
9709
+ }
6793
9710
  const nextSkills = [];
6794
9711
  const result = {
6795
9712
  installed: [],
@@ -6811,13 +9728,13 @@ async function reconcileLoadoutFavoriteSkills(payload, home = getHome(), env = p
6811
9728
  const installPath = path.join(getCanonicalRoot(home, env), nextCommandName);
6812
9729
  const linkPaths = getHarnessRoots(home, env).map((root) => path.join(root, nextCommandName));
6813
9730
  const conflictingPath = (await Promise.all([installPath, ...linkPaths].map(async (candidate) => {
6814
- if (!await pathExists2(candidate))
9731
+ if (!await pathExists3(candidate))
6815
9732
  return null;
6816
9733
  if (previous && candidate === previous.installPath) {
6817
- return (await lstat4(candidate)).isDirectory() ? null : candidate;
9734
+ return (await lstat5(candidate)).isDirectory() ? null : candidate;
6818
9735
  }
6819
9736
  if (previous && previous.linkPaths.includes(candidate)) {
6820
- const stat = await lstat4(candidate);
9737
+ const stat = await lstat5(candidate);
6821
9738
  if (!stat.isSymbolicLink())
6822
9739
  return candidate;
6823
9740
  return path.resolve(path.dirname(candidate), await readlink(candidate)) === previous.installPath ? null : candidate;
@@ -6830,45 +9747,50 @@ async function reconcileLoadoutFavoriteSkills(payload, home = getHome(), env = p
6830
9747
  nextSkills.push(previous);
6831
9748
  continue;
6832
9749
  }
6833
- const allLinksExist = (await Promise.all(linkPaths.map(pathExists2))).every(Boolean);
6834
- if (previous?.artifactVersionId === pkg.artifactVersionId && previous.displayName === pkg.displayName && previous.summary === pkg.summary && previous.installPath === installPath && previous.linkPaths.length === linkPaths.length && previous.linkPaths.every((linkPath) => linkPaths.includes(linkPath)) && await pathExists2(installPath) && allLinksExist) {
9750
+ const allLinksExist = (await Promise.all(linkPaths.map(pathExists3))).every(Boolean);
9751
+ if (previous?.artifactVersionId === pkg.artifactVersionId && previous.displayName === pkg.displayName && previous.summary === pkg.summary && previous.deliveryRevision === pkg.bundle?.artifactSha256 && previous.installPath === installPath && previous.linkPaths.length === linkPaths.length && previous.linkPaths.every((linkPath) => linkPaths.includes(linkPath)) && await pathExists3(installPath) && allLinksExist) {
6835
9752
  result.unchanged.push(pkg.name);
6836
9753
  nextSkills.push(previous);
6837
9754
  continue;
6838
9755
  }
9756
+ const preparedBundle = preparedBundles.get(pkg.name);
6839
9757
  const temporaryPath = `${installPath}.${process.pid}.tmp`;
6840
9758
  const backupPath = `${installPath}.${process.pid}.backup`;
6841
- await mkdir6(getCanonicalRoot(home, env), { recursive: true });
6842
- await rm2(temporaryPath, { recursive: true, force: true });
6843
- await rm2(backupPath, { recursive: true, force: true });
6844
- await mkdir6(temporaryPath, { recursive: true });
6845
- for (const file of pkg.files) {
6846
- const destination = path.join(temporaryPath, ...file.path.split("/"));
6847
- await mkdir6(path.dirname(destination), { recursive: true });
6848
- await writeFile6(destination, file.path === LOADOUT_SKILL_ENTRYPOINT ? entrypointContent(pkg, file.content) : file.content);
9759
+ await mkdir8(getCanonicalRoot(home, env), { recursive: true });
9760
+ await rm3(temporaryPath, { recursive: true, force: true });
9761
+ await rm3(backupPath, { recursive: true, force: true });
9762
+ if (preparedBundle) {
9763
+ await writeBundlePackage(temporaryPath, pkg, preparedBundle.releaseDirectory);
9764
+ } else {
9765
+ await mkdir8(temporaryPath, { recursive: true });
9766
+ for (const file of pkg.files) {
9767
+ const destination = path.join(temporaryPath, ...file.path.split("/"));
9768
+ await mkdir8(path.dirname(destination), { recursive: true });
9769
+ await writeFile6(destination, file.path === LOADOUT_SKILL_ENTRYPOINT ? entrypointContent(pkg, file.content) : file.content);
9770
+ }
6849
9771
  }
6850
9772
  const createdLinkPaths = [];
6851
9773
  let backedUp = false;
6852
9774
  try {
6853
- if (await pathExists2(installPath)) {
6854
- await rename3(installPath, backupPath);
9775
+ if (await pathExists3(installPath)) {
9776
+ await rename4(installPath, backupPath);
6855
9777
  backedUp = true;
6856
9778
  }
6857
- await rename3(temporaryPath, installPath);
9779
+ await rename4(temporaryPath, installPath);
6858
9780
  for (const linkPath of linkPaths) {
6859
- await mkdir6(path.dirname(linkPath), { recursive: true });
6860
- if (!await pathExists2(linkPath)) {
6861
- await symlink2(installPath, linkPath, "dir");
9781
+ await mkdir8(path.dirname(linkPath), { recursive: true });
9782
+ if (!await pathExists3(linkPath)) {
9783
+ await symlink3(installPath, linkPath, "dir");
6862
9784
  createdLinkPaths.push(linkPath);
6863
9785
  }
6864
9786
  }
6865
- await rm2(backupPath, { recursive: true, force: true });
9787
+ await rm3(backupPath, { recursive: true, force: true });
6866
9788
  } catch (error) {
6867
- await Promise.all(createdLinkPaths.map((linkPath) => rm2(linkPath, { force: true })));
6868
- await rm2(installPath, { recursive: true, force: true });
9789
+ await Promise.all(createdLinkPaths.map((linkPath) => rm3(linkPath, { force: true })));
9790
+ await rm3(installPath, { recursive: true, force: true });
6869
9791
  if (backedUp)
6870
- await rename3(backupPath, installPath);
6871
- await rm2(temporaryPath, { recursive: true, force: true });
9792
+ await rename4(backupPath, installPath);
9793
+ await rm3(temporaryPath, { recursive: true, force: true });
6872
9794
  throw error;
6873
9795
  }
6874
9796
  if (previous && previous.installPath !== installPath)
@@ -6880,7 +9802,8 @@ async function reconcileLoadoutFavoriteSkills(payload, home = getHome(), env = p
6880
9802
  summary: pkg.summary,
6881
9803
  commandName: nextCommandName,
6882
9804
  installPath,
6883
- linkPaths
9805
+ linkPaths,
9806
+ ...pkg.bundle ? { deliveryRevision: pkg.bundle.artifactSha256 } : {}
6884
9807
  });
6885
9808
  (previous ? result.updated : result.installed).push(pkg.name);
6886
9809
  }