holyagent 0.0.0-stage → 0.3.3-bootstrap.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 (140) hide show
  1. package/agents/explorer-lookup-headless-screen.md +126 -0
  2. package/agents/explorer-lookup-screen.md +122 -0
  3. package/agents/explorer-lookup.md +122 -0
  4. package/agents/explorer-map-headless-screen.md +125 -0
  5. package/agents/explorer-map-screen.md +121 -0
  6. package/agents/explorer-map.md +121 -0
  7. package/agents/explorer-trace-headless-screen.md +129 -0
  8. package/agents/explorer-trace-screen.md +125 -0
  9. package/agents/explorer-trace.md +125 -0
  10. package/agents/librarian-lookup-headless-screen.md +132 -0
  11. package/agents/librarian-lookup-screen.md +128 -0
  12. package/agents/librarian-lookup.md +128 -0
  13. package/agents/librarian-research-headless-screen.md +132 -0
  14. package/agents/librarian-research-screen.md +128 -0
  15. package/agents/librarian-research.md +128 -0
  16. package/agents/reviewer-artifact-headless-screen.md +158 -0
  17. package/agents/reviewer-artifact-screen.md +154 -0
  18. package/agents/reviewer-artifact.md +154 -0
  19. package/agents/reviewer-audit-headless-screen.md +124 -0
  20. package/agents/reviewer-audit-screen.md +120 -0
  21. package/agents/reviewer-audit.md +120 -0
  22. package/agents/reviewer-code-headless-screen.md +180 -0
  23. package/agents/reviewer-code-screen.md +176 -0
  24. package/agents/reviewer-code.md +176 -0
  25. package/agents/reviewer-security-headless-screen.md +138 -0
  26. package/agents/reviewer-security-screen.md +134 -0
  27. package/agents/reviewer-security.md +134 -0
  28. package/agents/reviewer-testing-headless-screen.md +173 -0
  29. package/agents/reviewer-testing-screen.md +169 -0
  30. package/agents/reviewer-testing.md +169 -0
  31. package/agents/reviewer-visual-headless-screen.md +161 -0
  32. package/agents/reviewer-visual-screen.md +157 -0
  33. package/agents/reviewer-visual.md +157 -0
  34. package/agents/worker-debugging-headless-screen.md +175 -0
  35. package/agents/worker-debugging-screen.md +171 -0
  36. package/agents/worker-debugging.md +171 -0
  37. package/agents/worker-implementation-headless-screen.md +191 -0
  38. package/agents/worker-implementation-screen.md +187 -0
  39. package/agents/worker-implementation.md +187 -0
  40. package/agents/worker-integration-headless-screen.md +172 -0
  41. package/agents/worker-integration-screen.md +168 -0
  42. package/agents/worker-integration.md +168 -0
  43. package/agents/worker-mechanical-headless-screen.md +176 -0
  44. package/agents/worker-mechanical-screen.md +172 -0
  45. package/agents/worker-mechanical.md +172 -0
  46. package/agents/worker-operations-headless-screen.md +130 -0
  47. package/agents/worker-operations-screen.md +126 -0
  48. package/agents/worker-operations.md +126 -0
  49. package/agents/worker-validation-headless-screen.md +128 -0
  50. package/agents/worker-validation-screen.md +124 -0
  51. package/agents/worker-validation.md +124 -0
  52. package/agents/worker-visual-headless-screen.md +211 -0
  53. package/agents/worker-visual-screen.md +207 -0
  54. package/agents/worker-visual.md +207 -0
  55. package/extensions/holyagent.js +20006 -0
  56. package/families/gpt-6/agents/explorer-lookup-headless-screen.md +113 -0
  57. package/families/gpt-6/agents/explorer-lookup-screen.md +109 -0
  58. package/families/gpt-6/agents/explorer-lookup.md +109 -0
  59. package/families/gpt-6/agents/explorer-map-headless-screen.md +113 -0
  60. package/families/gpt-6/agents/explorer-map-screen.md +109 -0
  61. package/families/gpt-6/agents/explorer-map.md +109 -0
  62. package/families/gpt-6/agents/explorer-trace-headless-screen.md +113 -0
  63. package/families/gpt-6/agents/explorer-trace-screen.md +109 -0
  64. package/families/gpt-6/agents/explorer-trace.md +109 -0
  65. package/families/gpt-6/agents/librarian-lookup-headless-screen.md +115 -0
  66. package/families/gpt-6/agents/librarian-lookup-screen.md +111 -0
  67. package/families/gpt-6/agents/librarian-lookup.md +111 -0
  68. package/families/gpt-6/agents/librarian-research-headless-screen.md +115 -0
  69. package/families/gpt-6/agents/librarian-research-screen.md +111 -0
  70. package/families/gpt-6/agents/librarian-research.md +111 -0
  71. package/families/gpt-6/agents/reviewer-artifact-headless-screen.md +148 -0
  72. package/families/gpt-6/agents/reviewer-artifact-screen.md +144 -0
  73. package/families/gpt-6/agents/reviewer-artifact.md +144 -0
  74. package/families/gpt-6/agents/reviewer-audit-headless-screen.md +111 -0
  75. package/families/gpt-6/agents/reviewer-audit-screen.md +107 -0
  76. package/families/gpt-6/agents/reviewer-audit.md +107 -0
  77. package/families/gpt-6/agents/reviewer-code-headless-screen.md +173 -0
  78. package/families/gpt-6/agents/reviewer-code-screen.md +169 -0
  79. package/families/gpt-6/agents/reviewer-code.md +169 -0
  80. package/families/gpt-6/agents/reviewer-security-headless-screen.md +122 -0
  81. package/families/gpt-6/agents/reviewer-security-screen.md +118 -0
  82. package/families/gpt-6/agents/reviewer-security.md +118 -0
  83. package/families/gpt-6/agents/reviewer-testing-headless-screen.md +163 -0
  84. package/families/gpt-6/agents/reviewer-testing-screen.md +159 -0
  85. package/families/gpt-6/agents/reviewer-testing.md +159 -0
  86. package/families/gpt-6/agents/reviewer-visual-headless-screen.md +153 -0
  87. package/families/gpt-6/agents/reviewer-visual-screen.md +149 -0
  88. package/families/gpt-6/agents/reviewer-visual.md +149 -0
  89. package/families/gpt-6/agents/worker-debugging-headless-screen.md +168 -0
  90. package/families/gpt-6/agents/worker-debugging-screen.md +164 -0
  91. package/families/gpt-6/agents/worker-debugging.md +164 -0
  92. package/families/gpt-6/agents/worker-implementation-headless-screen.md +180 -0
  93. package/families/gpt-6/agents/worker-implementation-screen.md +176 -0
  94. package/families/gpt-6/agents/worker-implementation.md +176 -0
  95. package/families/gpt-6/agents/worker-integration-headless-screen.md +161 -0
  96. package/families/gpt-6/agents/worker-integration-screen.md +157 -0
  97. package/families/gpt-6/agents/worker-integration.md +157 -0
  98. package/families/gpt-6/agents/worker-mechanical-headless-screen.md +165 -0
  99. package/families/gpt-6/agents/worker-mechanical-screen.md +161 -0
  100. package/families/gpt-6/agents/worker-mechanical.md +161 -0
  101. package/families/gpt-6/agents/worker-operations-headless-screen.md +122 -0
  102. package/families/gpt-6/agents/worker-operations-screen.md +118 -0
  103. package/families/gpt-6/agents/worker-operations.md +118 -0
  104. package/families/gpt-6/agents/worker-validation-headless-screen.md +115 -0
  105. package/families/gpt-6/agents/worker-validation-screen.md +111 -0
  106. package/families/gpt-6/agents/worker-validation.md +111 -0
  107. package/families/gpt-6/agents/worker-visual-headless-screen.md +201 -0
  108. package/families/gpt-6/agents/worker-visual-screen.md +197 -0
  109. package/families/gpt-6/agents/worker-visual.md +197 -0
  110. package/families/gpt-6/skills/ci-watch/SKILL.md +34 -0
  111. package/families/gpt-6/skills/desktop-design/SKILL.md +144 -0
  112. package/families/gpt-6/skills/dev-server/SKILL.md +51 -0
  113. package/families/gpt-6/skills/evidence-judging/SKILL.md +37 -0
  114. package/families/gpt-6/skills/instruction-writing/SKILL.md +49 -0
  115. package/families/gpt-6/skills/mobile-design/SKILL.md +144 -0
  116. package/families/gpt-6/skills/state-mode/SKILL.md +17 -0
  117. package/families/gpt-6/skills/tui-design/SKILL.md +162 -0
  118. package/families/gpt-6/skills/user-busy/SKILL.md +16 -0
  119. package/families/gpt-6/skills/visual-judging/SKILL.md +47 -0
  120. package/families/gpt-6/skills/web-design/SKILL.md +161 -0
  121. package/package.json +40 -4
  122. package/prompts/code-review.md +35 -0
  123. package/prompts/security-review.md +35 -0
  124. package/scripts/empty-bunfig.toml +4 -0
  125. package/scripts/holyagent +45 -0
  126. package/scripts/holyagent.js +29047 -0
  127. package/scripts/just-bash.js +90614 -0
  128. package/scripts/setup-tui.js +4334 -0
  129. package/skills/ci-watch/SKILL.md +34 -0
  130. package/skills/desktop-design/SKILL.md +132 -0
  131. package/skills/dev-server/SKILL.md +51 -0
  132. package/skills/evidence-judging/SKILL.md +37 -0
  133. package/skills/instruction-writing/SKILL.md +44 -0
  134. package/skills/mobile-design/SKILL.md +132 -0
  135. package/skills/state-mode/SKILL.md +17 -0
  136. package/skills/tui-design/SKILL.md +150 -0
  137. package/skills/user-busy/SKILL.md +16 -0
  138. package/skills/visual-judging/SKILL.md +45 -0
  139. package/skills/web-design/SKILL.md +149 -0
  140. package/README.md +0 -3
@@ -0,0 +1,4334 @@
1
+ // @bun
2
+ // Generated by packages/integrations/pi/build.ts from packages/runtime/src/setup/tui/entry.tsx; edit the source and rebuild.
3
+ // packages/runtime/src/setup/tui/entry.tsx
4
+ import { createComponent as _$createComponent2 } from "@opentui/solid";
5
+ import { createCliRenderer } from "@opentui/core";
6
+ import { render } from "@opentui/solid";
7
+
8
+ var pipeArguments = (self, args) => {
9
+ switch (args.length) {
10
+ case 0:
11
+ return self;
12
+ case 1:
13
+ return args[0](self);
14
+ case 2:
15
+ return args[1](args[0](self));
16
+ case 3:
17
+ return args[2](args[1](args[0](self)));
18
+ case 4:
19
+ return args[3](args[2](args[1](args[0](self))));
20
+ case 5:
21
+ return args[4](args[3](args[2](args[1](args[0](self)))));
22
+ case 6:
23
+ return args[5](args[4](args[3](args[2](args[1](args[0](self))))));
24
+ case 7:
25
+ return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))));
26
+ case 8:
27
+ return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))));
28
+ case 9:
29
+ return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))));
30
+ default: {
31
+ let ret = self;
32
+ for (let i = 0, len = args.length;i < len; i++) {
33
+ ret = args[i](ret);
34
+ }
35
+ return ret;
36
+ }
37
+ }
38
+ };
39
+
40
+ var dual = function(arity, body) {
41
+ if (typeof arity === "function") {
42
+ return function() {
43
+ return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments);
44
+ };
45
+ }
46
+ switch (arity) {
47
+ case 0:
48
+ case 1:
49
+ throw new RangeError(`Invalid arity ${arity}`);
50
+ case 2:
51
+ return function(a, b) {
52
+ if (arguments.length >= 2) {
53
+ return body(a, b);
54
+ }
55
+ return function(self) {
56
+ return body(self, a);
57
+ };
58
+ };
59
+ case 3:
60
+ return function(a, b, c) {
61
+ if (arguments.length >= 3) {
62
+ return body(a, b, c);
63
+ }
64
+ return function(self) {
65
+ return body(self, a, b);
66
+ };
67
+ };
68
+ default:
69
+ return function() {
70
+ if (arguments.length >= arity) {
71
+ return body.apply(this, arguments);
72
+ }
73
+ const args = arguments;
74
+ return function(self) {
75
+ return body(self, ...args);
76
+ };
77
+ };
78
+ }
79
+ };
80
+ var identity = (a) => a;
81
+ var constant = (value) => () => value;
82
+ var constTrue = /* @__PURE__ */ constant(true);
83
+ var constFalse = /* @__PURE__ */ constant(false);
84
+ var constUndefined = /* @__PURE__ */ constant(undefined);
85
+ var constVoid = constUndefined;
86
+
87
+ var errorSiteKeys = ["line", "column", "sourceURL", "originalLine", "originalColumn"];
88
+ var getAllObjectKeys = (obj) => {
89
+ const keys = new Set(Reflect.ownKeys(obj));
90
+ if (obj.constructor === Object)
91
+ return keys;
92
+ if (obj instanceof Error) {
93
+ keys.delete("stack");
94
+ for (const key of errorSiteKeys) {
95
+ if (!Object.prototype.propertyIsEnumerable.call(obj, key))
96
+ keys.delete(key);
97
+ }
98
+ }
99
+ const proto = Object.getPrototypeOf(obj);
100
+ let current = proto;
101
+ while (current !== null && current !== Object.prototype) {
102
+ const ownKeys = Reflect.ownKeys(current);
103
+ for (let i = 0;i < ownKeys.length; i++) {
104
+ keys.add(ownKeys[i]);
105
+ }
106
+ current = Object.getPrototypeOf(current);
107
+ }
108
+ if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) {
109
+ keys.delete("constructor");
110
+ }
111
+ return keys;
112
+ };
113
+ var byReferenceInstances = /* @__PURE__ */ new WeakSet;
114
+ var viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
115
+ var isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer;
116
+ var bufferBytes = (buffer) => {
117
+ try {
118
+ return new Uint8Array(buffer);
119
+ } catch {
120
+ return;
121
+ }
122
+ };
123
+
124
+ var backEdges = 0;
125
+ var addBackEdge = () => {
126
+ backEdges++;
127
+ };
128
+
129
+ function isNumber(input) {
130
+ return typeof input === "number";
131
+ }
132
+ function isFunction(input) {
133
+ return typeof input === "function";
134
+ }
135
+ function isObjectKeyword(input) {
136
+ return typeof input === "object" && input !== null || isFunction(input);
137
+ }
138
+ var hasProperty = /* @__PURE__ */ dual(2, (self, property) => isObjectKeyword(self) && (property in self));
139
+
140
+ var symbol = "~effect/Hash";
141
+ var hash = (self) => {
142
+ switch (typeof self) {
143
+ case "number":
144
+ return number(self);
145
+ case "bigint":
146
+ return string(self.toString(10));
147
+ case "string":
148
+ return string(self);
149
+ case "function":
150
+ case "object": {
151
+ if (self === null) {
152
+ break;
153
+ } else if (self instanceof Date) {
154
+ if (Number.isNaN(self.getTime())) {
155
+ return string("Invalid Date");
156
+ }
157
+ return string(self.toISOString());
158
+ } else if (self instanceof RegExp) {
159
+ return string(self.toString());
160
+ } else {
161
+ if (byReferenceInstances.has(self)) {
162
+ return random(self);
163
+ }
164
+ const cached = hashCache.get(self);
165
+ if (cached !== undefined) {
166
+ return cached;
167
+ }
168
+ if (visitedObjects.has(self)) {
169
+ addBackEdge();
170
+ return string("[Circular]");
171
+ }
172
+ visitedObjects.add(self);
173
+ const seen = backEdges;
174
+ let h;
175
+ try {
176
+ if (isHash(self)) {
177
+ h = self[symbol]();
178
+ } else if (typeof self === "function") {
179
+ h = random(self);
180
+ } else if (isArrayBufferLike(self)) {
181
+ const bytes = bufferBytes(self);
182
+ h = bytes === undefined ? random(self) : array(bytes);
183
+ } else if (self instanceof DataView) {
184
+ h = array(viewBytes(self));
185
+ } else if (Array.isArray(self) || ArrayBuffer.isView(self)) {
186
+ h = array(self);
187
+ } else if (self instanceof Map) {
188
+ h = hashMap(self);
189
+ } else if (self instanceof Set) {
190
+ h = hashSet(self);
191
+ } else {
192
+ h = structure(self);
193
+ }
194
+ } finally {
195
+ visitedObjects.delete(self);
196
+ }
197
+ if (seen === backEdges) {
198
+ hashCache.set(self, h);
199
+ }
200
+ return h;
201
+ }
202
+ }
203
+ }
204
+ return optimize(mix(string(String(self))));
205
+ };
206
+ var random = (self) => {
207
+ if (!randomHashCache.has(self)) {
208
+ randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0));
209
+ }
210
+ return randomHashCache.get(self);
211
+ };
212
+ var mix = (h) => {
213
+ h ^= h >>> 16;
214
+ h = Math.imul(h, 2246822507);
215
+ h ^= h >>> 13;
216
+ h = Math.imul(h, 3266489909);
217
+ return h ^ h >>> 16;
218
+ };
219
+ var combine = /* @__PURE__ */ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507)));
220
+ var optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824;
221
+ var isHash = (u) => hasProperty(u, symbol) && typeof u[symbol] === "function";
222
+ var float64 = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
223
+ var number = (n) => {
224
+ const h = n | 0;
225
+ if (h === n) {
226
+ return optimize(h);
227
+ }
228
+ float64.setFloat64(0, n !== n ? NaN : n);
229
+ return optimize(combine(float64.getInt32(0), float64.getInt32(4)));
230
+ };
231
+ var string = (str) => {
232
+ let h = 5381, i = str.length;
233
+ while (i) {
234
+ h = h * 33 ^ str.charCodeAt(--i);
235
+ }
236
+ return optimize(h);
237
+ };
238
+ var structureKeys = (o, keys) => {
239
+ let h = 12289;
240
+ for (const key of keys) {
241
+ h ^= combine(hash(key), hash(o[key]));
242
+ }
243
+ return optimize(h);
244
+ };
245
+ var structure = (o) => structureKeys(o, getAllObjectKeys(o));
246
+ var unordered = (seed, f) => (iter) => {
247
+ let h = seed;
248
+ for (const element of iter) {
249
+ h ^= f(element);
250
+ }
251
+ return optimize(h);
252
+ };
253
+ var array = (arr) => {
254
+ let h = 6151;
255
+ for (const element of arr) {
256
+ h = combine(h, hash(element));
257
+ }
258
+ return optimize(h);
259
+ };
260
+ var hashMap = /* @__PURE__ */ unordered(/* @__PURE__ */ string("Map"), ([k, v]) => combine(hash(k), hash(v)));
261
+ var setSeed = /* @__PURE__ */ string("Set");
262
+ var hashSet = /* @__PURE__ */ unordered(setSeed, (element) => combine(setSeed, hash(element)));
263
+ var randomHashCache = /* @__PURE__ */ new WeakMap;
264
+ var hashCache = /* @__PURE__ */ new WeakMap;
265
+ var visitedObjects = /* @__PURE__ */ new WeakSet;
266
+
267
+ var symbol2 = "~effect/Equal";
268
+ function equals() {
269
+ if (arguments.length === 1) {
270
+ return (self) => compareBoth(self, arguments[0]);
271
+ }
272
+ return compareBoth(arguments[0], arguments[1]);
273
+ }
274
+ function compareBoth(self, that) {
275
+ if (self === that)
276
+ return true;
277
+ if (self == null || that == null)
278
+ return false;
279
+ const selfType = typeof self;
280
+ if (selfType !== typeof that) {
281
+ return false;
282
+ }
283
+ if (selfType === "number" && self !== self && that !== that) {
284
+ return true;
285
+ }
286
+ if (selfType !== "object" && selfType !== "function") {
287
+ return false;
288
+ }
289
+ if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) {
290
+ return false;
291
+ }
292
+ return compareObjects(self, that);
293
+ }
294
+ function compareObjects(self, that) {
295
+ const depth = pathLeft.length;
296
+ for (let i = depth;i-- > 0; ) {
297
+ if (pathLeft[i] === self && pathRight[i] === that)
298
+ return true;
299
+ }
300
+ if (depth)
301
+ return compareOnPath(self, that);
302
+ let known = results.get(self);
303
+ if (!known)
304
+ results.set(self, known = new WeakMap);
305
+ let result = known.get(that);
306
+ if (result === undefined)
307
+ known.set(that, result = compareOnPath(self, that));
308
+ return result;
309
+ }
310
+ function compareOnPath(self, that) {
311
+ pathLeft.push(self);
312
+ pathRight.push(that);
313
+ try {
314
+ return compareStructure(self, that);
315
+ } finally {
316
+ pathLeft.pop();
317
+ pathRight.pop();
318
+ }
319
+ }
320
+ var pathLeft = [];
321
+ var pathRight = [];
322
+ var results = /* @__PURE__ */ new WeakMap;
323
+ function compareStructure(self, that) {
324
+ if (hash(self) !== hash(that)) {
325
+ return false;
326
+ } else if (self instanceof Date) {
327
+ if (!(that instanceof Date))
328
+ return false;
329
+ const selfTime = self.getTime();
330
+ const thatTime = that.getTime();
331
+ return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime);
332
+ } else if (self instanceof RegExp) {
333
+ return that instanceof RegExp && self.toString() === that.toString();
334
+ }
335
+ const bothEquals = isEqual(self);
336
+ if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) {
337
+ return false;
338
+ } else if (bothEquals) {
339
+ return self[symbol2](that);
340
+ } else if (Array.isArray(self)) {
341
+ if (!Array.isArray(that) || self.length !== that.length) {
342
+ return false;
343
+ }
344
+ return compareArrays(self, that);
345
+ } else if (isArrayBufferLike(self)) {
346
+ if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) {
347
+ return false;
348
+ }
349
+ const selfBytes = bufferBytes(self);
350
+ const thatBytes = bufferBytes(that);
351
+ return selfBytes !== undefined && thatBytes !== undefined && compareTypedArrays(selfBytes, thatBytes);
352
+ } else if (ArrayBuffer.isView(self)) {
353
+ const selfIsDataView = self instanceof DataView;
354
+ if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) {
355
+ return false;
356
+ }
357
+ if (selfIsDataView) {
358
+ return compareTypedArrays(viewBytes(self), viewBytes(that));
359
+ }
360
+ return compareTypedArrays(self, that);
361
+ } else if (self instanceof Map) {
362
+ if (!(that instanceof Map) || self.size !== that.size) {
363
+ return false;
364
+ }
365
+ return compareHashed(self, that, entryHash, equalEntries);
366
+ } else if (self instanceof Set) {
367
+ if (!(that instanceof Set) || self.size !== that.size) {
368
+ return false;
369
+ }
370
+ return compareHashed(self, that, hash, compareBoth);
371
+ }
372
+ return compareRecords(self, that);
373
+ }
374
+ function compareArrays(self, that) {
375
+ for (let i = 0;i < self.length; i++) {
376
+ if (!compareBoth(self[i], that[i])) {
377
+ return false;
378
+ }
379
+ }
380
+ return true;
381
+ }
382
+ function compareTypedArrays(self, that) {
383
+ if (self.length !== that.length) {
384
+ return false;
385
+ }
386
+ for (let i = 0;i < self.length; i++) {
387
+ if (self[i] !== that[i]) {
388
+ return false;
389
+ }
390
+ }
391
+ return true;
392
+ }
393
+ function compareRecords(self, that) {
394
+ const selfKeys = getAllObjectKeys(self);
395
+ const thatKeys = getAllObjectKeys(that);
396
+ if (selfKeys.size !== thatKeys.size) {
397
+ return false;
398
+ }
399
+ for (const key of selfKeys) {
400
+ if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) {
401
+ return false;
402
+ }
403
+ }
404
+ return true;
405
+ }
406
+ function compareHashed(self, that, hashOf, equivalent) {
407
+ const groups = new Map;
408
+ let remaining = 0;
409
+ for (const item of that) {
410
+ const h = hashOf(item);
411
+ const group = groups.get(h);
412
+ if (group)
413
+ group.push(item);
414
+ else
415
+ groups.set(h, [item]);
416
+ remaining++;
417
+ }
418
+ outer:
419
+ for (const item of self) {
420
+ const group = groups.get(hashOf(item));
421
+ if (group) {
422
+ for (let i = 0;i < group.length; i++) {
423
+ if (equivalent(item, group[i])) {
424
+ group[i] = group[group.length - 1];
425
+ group.pop();
426
+ remaining--;
427
+ continue outer;
428
+ }
429
+ }
430
+ }
431
+ return false;
432
+ }
433
+ return remaining === 0;
434
+ }
435
+ var entryHash = (entry) => hash(entry[0]);
436
+ var equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]);
437
+ var isEqual = (u) => hasProperty(u, symbol2) && typeof u[symbol2] === "function";
438
+
439
+ var symbolRedactable = /* @__PURE__ */ Symbol.for("~effect/Redactable");
440
+ var isRedactable = (u) => hasProperty(u, symbolRedactable);
441
+ function redact(u) {
442
+ if (isRedactable(u))
443
+ return getRedacted(u);
444
+ return u;
445
+ }
446
+ function getRedacted(redactable) {
447
+ return redactable[symbolRedactable](globalThis[currentFiberTypeId]?.context ?? emptyContext);
448
+ }
449
+ var currentFiberTypeId = "~effect/Fiber/currentFiber";
450
+ var emptyMap = /* @__PURE__ */ new Map;
451
+ var emptyContext = {
452
+ "~effect/Context": {},
453
+ base: emptyMap,
454
+ depth: 0,
455
+ mapUnsafe: emptyMap,
456
+ pipe() {
457
+ return pipeArguments(this, arguments);
458
+ }
459
+ };
460
+
461
+ function format(input, options) {
462
+ const space = options?.space ?? 0;
463
+ const ancestors = new WeakSet;
464
+ const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space;
465
+ const ind = (d) => gap.repeat(d);
466
+ const wrap = (v, body) => {
467
+ const ctor = v?.constructor;
468
+ return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body;
469
+ };
470
+ const ownKeys = (o) => {
471
+ try {
472
+ return Reflect.ownKeys(o);
473
+ } catch {
474
+ return ["[ownKeys threw]"];
475
+ }
476
+ };
477
+ function recur(v, d = 0) {
478
+ try {
479
+ return recurUnsafe(v, d);
480
+ } catch {
481
+ if (typeof v === "object" && v !== null || typeof v === "function")
482
+ ancestors.delete(v);
483
+ return "[inspection threw]";
484
+ }
485
+ }
486
+ function recurUnsafe(v, d = 0) {
487
+ if (typeof v === "string")
488
+ return JSON.stringify(v);
489
+ if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol")
490
+ return String(v);
491
+ if (typeof v === "bigint")
492
+ return String(v) + "n";
493
+ if (typeof v === "object" || typeof v === "function") {
494
+ if (ancestors.has(v))
495
+ return CIRCULAR;
496
+ ancestors.add(v);
497
+ let output;
498
+ if (symbolRedactable in v) {
499
+ output = recur(getRedacted(v), d);
500
+ } else if (Array.isArray(v)) {
501
+ output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[
502
+ ${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(`,
503
+ ` + ind(d + 1))}
504
+ ${ind(d)}]`;
505
+ } else if (v instanceof Date) {
506
+ output = formatDate(v);
507
+ } else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) {
508
+ const s = safeToString(v);
509
+ output = v instanceof Error && v.cause !== undefined ? `${s} (cause: ${recur(v.cause, d)})` : s;
510
+ } else if (Symbol.iterator in v) {
511
+ output = `${v.constructor.name}(${recur(Array.from(v), d)})`;
512
+ } else {
513
+ const keys = ownKeys(v);
514
+ if (!gap || keys.length <= 1) {
515
+ const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`;
516
+ output = wrap(v, body);
517
+ } else {
518
+ const body = `{
519
+ ${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(`,
520
+ `)}
521
+ ${ind(d)}}`;
522
+ output = wrap(v, body);
523
+ }
524
+ }
525
+ ancestors.delete(v);
526
+ return output;
527
+ }
528
+ return String(v);
529
+ }
530
+ return recur(input, 0);
531
+ }
532
+ var CIRCULAR = "[Circular]";
533
+ function formatPropertyKey(name) {
534
+ return typeof name === "string" ? JSON.stringify(name) : String(name);
535
+ }
536
+ function formatDate(date) {
537
+ try {
538
+ return date.toISOString();
539
+ } catch {
540
+ return "Invalid Date";
541
+ }
542
+ }
543
+ function safeToString(input) {
544
+ try {
545
+ const s = input.toString();
546
+ return typeof s === "string" ? s : String(s);
547
+ } catch {
548
+ return "[toString threw]";
549
+ }
550
+ }
551
+ function safeGet(input, key) {
552
+ try {
553
+ return input[key];
554
+ } catch {
555
+ return "[property access threw]";
556
+ }
557
+ }
558
+ function formatJson(input, options) {
559
+ const ancestors = [];
560
+ const sources = new WeakMap;
561
+ return JSON.stringify(input, function(key, value) {
562
+ const original = Object.getOwnPropertyDescriptor(sources.get(this) ?? this, key)?.value;
563
+ const redacted = hasProperty(original, symbolRedactable) ? redact(original) : redact(value);
564
+ if (typeof redacted === "bigint") {
565
+ return format(redacted);
566
+ }
567
+ if (typeof redacted !== "object" || redacted === null) {
568
+ return redacted;
569
+ }
570
+ const current = redacted instanceof Error && !hasProperty(redacted, "toJSON") ? {
571
+ ...redacted,
572
+ name: redacted.name,
573
+ message: redacted.message
574
+ } : redacted;
575
+ while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) {
576
+ ancestors.pop();
577
+ }
578
+ if (ancestors.includes(redacted)) {
579
+ return;
580
+ }
581
+ ancestors.push(redacted);
582
+ if (current !== redacted) {
583
+ ancestors.push(current);
584
+ }
585
+ if (!hasGetter(current) || isJsonPrimitiveWrapper(current)) {
586
+ return current;
587
+ }
588
+ const view = redactingView(current);
589
+ sources.set(view, current);
590
+ ancestors.push(view);
591
+ return view;
592
+ }, options?.space) ?? "null";
593
+ }
594
+ function hasGetter(object) {
595
+ for (const key of Object.getOwnPropertyNames(object)) {
596
+ if (Object.getOwnPropertyDescriptor(object, key)?.get !== undefined) {
597
+ return true;
598
+ }
599
+ }
600
+ return false;
601
+ }
602
+ function redactingView(object) {
603
+ const view = Array.isArray(object) ? [] : {};
604
+ const keys = Array.isArray(object) ? Array.from({
605
+ length: object.length
606
+ }, (_, i) => String(i)) : Object.keys(object);
607
+ for (const key of keys) {
608
+ Object.defineProperty(view, key, {
609
+ enumerable: true,
610
+ get: () => {
611
+ const value = Reflect.get(object, key);
612
+ return Object.getOwnPropertyDescriptor(object, key)?.get !== undefined ? redact(value) : value;
613
+ }
614
+ });
615
+ }
616
+ return view;
617
+ }
618
+ function isJsonPrimitiveWrapper(object) {
619
+ for (const valueOf of [Number.prototype.valueOf, Boolean.prototype.valueOf, String.prototype.valueOf]) {
620
+ try {
621
+ Reflect.apply(valueOf, object, []);
622
+ return true;
623
+ } catch {}
624
+ }
625
+ return false;
626
+ }
627
+
628
+ var NodeInspectSymbol = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
629
+ var toJson = (input) => {
630
+ try {
631
+ input = redact(input);
632
+ if (hasProperty(input, "toJSON") && isFunction(input["toJSON"]) && input["toJSON"].length === 0) {
633
+ return input.toJSON();
634
+ } else if (Array.isArray(input)) {
635
+ return input.map(toJson);
636
+ }
637
+ return input;
638
+ } catch {
639
+ return "[toJSON threw]";
640
+ }
641
+ };
642
+ var toStringUnknown = (u, whitespace = 2) => {
643
+ if (typeof u === "string") {
644
+ return u;
645
+ }
646
+ try {
647
+ return typeof u === "object" ? formatJson(u, {
648
+ space: whitespace
649
+ }) : format(u, {
650
+ space: whitespace
651
+ });
652
+ } catch {
653
+ return String(u);
654
+ }
655
+ };
656
+ var BaseProto = {
657
+ toJSON() {
658
+ return toJson(this);
659
+ },
660
+ [NodeInspectSymbol]() {
661
+ return this.toJSON();
662
+ },
663
+ toString() {
664
+ return format(this.toJSON());
665
+ }
666
+ };
667
+
668
+ var isStackTraceLimitWritable = () => {
669
+ const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
670
+ if (desc === undefined) {
671
+ return Object.isExtensible(Error);
672
+ }
673
+ return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== undefined;
674
+ };
675
+ var canWriteStackTraceLimit = /* @__PURE__ */ isStackTraceLimitWritable();
676
+ var getStackTraceLimit = () => Error.stackTraceLimit;
677
+ var setStackTraceLimit = (value) => {
678
+ if (canWriteStackTraceLimit) {
679
+ Error.stackTraceLimit = value;
680
+ }
681
+ };
682
+
683
+ class SingleShotGen {
684
+ constructor(self) {
685
+ this.value = self;
686
+ this.done = false;
687
+ }
688
+ next(a) {
689
+ if (this.done) {
690
+ this.value = a;
691
+ return this;
692
+ }
693
+ this.done = true;
694
+ return {
695
+ value: this.value,
696
+ done: false
697
+ };
698
+ }
699
+ }
700
+ var pickInternalCall = () => {
701
+ const InternalTypeId = "~effect/Utils/internal";
702
+ const standard = {
703
+ [InternalTypeId]: (body) => {
704
+ return body();
705
+ }
706
+ };
707
+ const forced = {
708
+ [InternalTypeId]: (body) => {
709
+ try {
710
+ return body();
711
+ } finally {}
712
+ }
713
+ };
714
+ const limit = getStackTraceLimit();
715
+ if (limit === 0)
716
+ return forced[InternalTypeId];
717
+ setStackTraceLimit(2);
718
+ const error = standard[InternalTypeId](() => new Error);
719
+ setStackTraceLimit(limit);
720
+ return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId];
721
+ };
722
+ var internalCall = /* @__PURE__ */ pickInternalCall();
723
+
724
+ function assignProperty(self, key, value) {
725
+ if (key === "__proto__") {
726
+ Object.defineProperty(self, key, {
727
+ value,
728
+ writable: true,
729
+ enumerable: true,
730
+ configurable: true
731
+ });
732
+ } else {
733
+ self[key] = value;
734
+ }
735
+ }
736
+ function assignProperties(self, source) {
737
+ if (!Object.hasOwn(source, "__proto__")) {
738
+ Object.assign(self, source);
739
+ return;
740
+ }
741
+ for (const key of Reflect.ownKeys(source)) {
742
+ if (Object.prototype.propertyIsEnumerable.call(source, key)) {
743
+ assignProperty(self, key, source[key]);
744
+ }
745
+ }
746
+ }
747
+
748
+ var EffectTypeId = `~effect/Effect`;
749
+ var ExitTypeId = `~effect/Exit`;
750
+ var effectVariance = {
751
+ _A: identity,
752
+ _E: identity,
753
+ _R: identity
754
+ };
755
+ var identifier = `${EffectTypeId}/identifier`;
756
+ var args = `${EffectTypeId}/args`;
757
+ var evaluate = `${EffectTypeId}/evaluate`;
758
+ var contA = `${EffectTypeId}/successCont`;
759
+ var contE = `${EffectTypeId}/failureCont`;
760
+ var contAll = `${EffectTypeId}/ensureCont`;
761
+ var Yield = /* @__PURE__ */ Symbol.for("effect/Effect/Yield");
762
+ var PipeInspectableProto = {
763
+ pipe() {
764
+ return pipeArguments(this, arguments);
765
+ },
766
+ toJSON() {
767
+ return {
768
+ ...this
769
+ };
770
+ },
771
+ toString() {
772
+ return format(this.toJSON(), {
773
+ ignoreToString: true,
774
+ space: 2
775
+ });
776
+ },
777
+ [NodeInspectSymbol]() {
778
+ return this.toJSON();
779
+ }
780
+ };
781
+ var StructuralProto = {
782
+ [symbol]() {
783
+ return structureKeys(this, Object.keys(this));
784
+ },
785
+ [symbol2](that) {
786
+ const selfKeys = Object.keys(this);
787
+ if (selfKeys.length !== Object.keys(that).length)
788
+ return false;
789
+ for (const key of selfKeys) {
790
+ if (!Object.prototype.propertyIsEnumerable.call(that, key) || !equals(this[key], that[key])) {
791
+ return false;
792
+ }
793
+ }
794
+ return true;
795
+ }
796
+ };
797
+ var EffectProto = {
798
+ [EffectTypeId]: effectVariance,
799
+ ...PipeInspectableProto,
800
+ [Symbol.iterator]() {
801
+ return new SingleShotGen(this);
802
+ },
803
+ toJSON() {
804
+ return {
805
+ _id: "Effect",
806
+ op: this[identifier],
807
+ ...args in this ? {
808
+ args: this[args]
809
+ } : undefined
810
+ };
811
+ }
812
+ };
813
+ var isEffect = (u) => hasProperty(u, EffectTypeId);
814
+ var isExit = (u) => hasProperty(u, ExitTypeId);
815
+ var CauseTypeId = "~effect/Cause";
816
+ var CauseReasonTypeId = "~effect/Cause/Reason";
817
+ var isCause = (self) => hasProperty(self, CauseTypeId);
818
+ class CauseImpl {
819
+ constructor(failures) {
820
+ this[CauseTypeId] = CauseTypeId;
821
+ this.reasons = failures;
822
+ }
823
+ pipe() {
824
+ return pipeArguments(this, arguments);
825
+ }
826
+ toJSON() {
827
+ return {
828
+ _id: "Cause",
829
+ reasons: this.reasons.map((f) => f.toJSON())
830
+ };
831
+ }
832
+ toString() {
833
+ return `Cause(${format(this.reasons)})`;
834
+ }
835
+ [NodeInspectSymbol]() {
836
+ return this.toJSON();
837
+ }
838
+ [symbol2](that) {
839
+ return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i]));
840
+ }
841
+ [symbol]() {
842
+ return array(this.reasons);
843
+ }
844
+ }
845
+ var annotationsMap = /* @__PURE__ */ new WeakMap;
846
+
847
+ class ReasonBase {
848
+ [CauseReasonTypeId];
849
+ annotations;
850
+ _tag;
851
+ constructor(_tag, annotations, originalError) {
852
+ this[CauseReasonTypeId] = CauseReasonTypeId;
853
+ this._tag = _tag;
854
+ if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) {
855
+ const prevAnnotations = annotationsMap.get(originalError);
856
+ if (prevAnnotations) {
857
+ annotations = new Map([...prevAnnotations, ...annotations]);
858
+ }
859
+ annotationsMap.set(originalError, annotations);
860
+ }
861
+ this.annotations = annotations;
862
+ }
863
+ annotate(annotations, options) {
864
+ if (annotations.mapUnsafe.size === 0)
865
+ return this;
866
+ const newAnnotations = new Map(this.annotations);
867
+ annotations.mapUnsafe.forEach((value, key) => {
868
+ if (options?.overwrite !== true && newAnnotations.has(key))
869
+ return;
870
+ newAnnotations.set(key, value);
871
+ });
872
+ if (options?.overwrite !== true && newAnnotations.size === this.annotations.size)
873
+ return this;
874
+ const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this);
875
+ self.annotations = newAnnotations;
876
+ return self;
877
+ }
878
+ pipe() {
879
+ return pipeArguments(this, arguments);
880
+ }
881
+ toString() {
882
+ return format(this);
883
+ }
884
+ [NodeInspectSymbol]() {
885
+ return this.toString();
886
+ }
887
+ }
888
+ var constEmptyAnnotations = /* @__PURE__ */ new Map;
889
+
890
+ class Fail extends ReasonBase {
891
+ constructor(error, annotations = constEmptyAnnotations) {
892
+ super("Fail", annotations, error);
893
+ this.error = error;
894
+ }
895
+ toString() {
896
+ return `Fail(${format(this.error)})`;
897
+ }
898
+ toJSON() {
899
+ return {
900
+ _tag: "Fail",
901
+ error: this.error
902
+ };
903
+ }
904
+ [symbol2](that) {
905
+ return isFailReason(that) && equals(this.error, that.error) && equals(this.annotations, that.annotations);
906
+ }
907
+ [symbol]() {
908
+ return combine(string(this._tag))(combine(hash(this.error))(hash(this.annotations)));
909
+ }
910
+ }
911
+ var causeFromReasons = (reasons) => new CauseImpl(reasons);
912
+ var dedupeReasons = (self, that) => {
913
+ const buckets = new Map;
914
+ const out = [];
915
+ for (const reason of self.concat(that)) {
916
+ const hash2 = hash(reason);
917
+ const bucket = buckets.get(hash2);
918
+ if (bucket === undefined) {
919
+ buckets.set(hash2, [reason]);
920
+ } else if (bucket.some((previous) => equals(previous, reason))) {
921
+ continue;
922
+ } else {
923
+ bucket.push(reason);
924
+ }
925
+ out.push(reason);
926
+ }
927
+ return out;
928
+ };
929
+ var causeCombine = /* @__PURE__ */ dual(2, (self, that) => {
930
+ if (self.reasons.length === 0) {
931
+ return that;
932
+ } else if (that.reasons.length === 0) {
933
+ return self;
934
+ }
935
+ const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons));
936
+ return equals(self, newCause) ? self : newCause;
937
+ });
938
+ var causeAddInterrupts = (self, interrupts) => {
939
+ const reasons = self.reasons.slice();
940
+ for (const reason of interrupts.reasons) {
941
+ if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) {
942
+ reasons.push(reason);
943
+ }
944
+ }
945
+ return reasons.length === self.reasons.length ? self : new CauseImpl(reasons);
946
+ };
947
+ var causeEmpty = /* @__PURE__ */ new CauseImpl([]);
948
+ var causeFail = (error) => new CauseImpl([new Fail(error)]);
949
+
950
+ class Die extends ReasonBase {
951
+ constructor(defect, annotations = constEmptyAnnotations) {
952
+ super("Die", annotations, defect);
953
+ this.defect = defect;
954
+ }
955
+ toString() {
956
+ return `Die(${format(this.defect)})`;
957
+ }
958
+ toJSON() {
959
+ return {
960
+ _tag: "Die",
961
+ defect: this.defect
962
+ };
963
+ }
964
+ [symbol2](that) {
965
+ return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations);
966
+ }
967
+ [symbol]() {
968
+ return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations)));
969
+ }
970
+ }
971
+ var causeDie = (defect) => new CauseImpl([new Die(defect)]);
972
+ var causeAnnotate = /* @__PURE__ */ dual((args) => isCause(args[0]), (self, annotations, options) => {
973
+ if (annotations.mapUnsafe.size === 0)
974
+ return self;
975
+ return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options)));
976
+ });
977
+ var isFailReason = (self) => self._tag === "Fail";
978
+ var isDieReason = (self) => self._tag === "Die";
979
+ var isInterruptReason = (self) => self._tag === "Interrupt";
980
+ function defaultEvaluate(_fiber) {
981
+ return exitDie(`Effect.evaluate: Not implemented`);
982
+ }
983
+ var makePrimitiveProto = (options) => ({
984
+ ...EffectProto,
985
+ [identifier]: options.op,
986
+ [evaluate]: options[evaluate] ?? defaultEvaluate,
987
+ [contA]: options[contA],
988
+ [contE]: options[contE],
989
+ [contAll]: options[contAll]
990
+ });
991
+ var makePrimitive = (options) => {
992
+ const Proto = makePrimitiveProto(options);
993
+ const PrimitiveImpl = function(value) {
994
+ this[args] = value;
995
+ };
996
+ PrimitiveImpl.prototype = Proto;
997
+ return function(value) {
998
+ return new PrimitiveImpl(value);
999
+ };
1000
+ };
1001
+ var makeExit = (options) => {
1002
+ const Proto = {
1003
+ [ExitTypeId]: ExitTypeId,
1004
+ _tag: options.op,
1005
+ get [options.prop]() {
1006
+ return this[args];
1007
+ },
1008
+ ...makePrimitiveProto(options),
1009
+ toString() {
1010
+ return `${options.op}(${format(this[args])})`;
1011
+ },
1012
+ toJSON() {
1013
+ return {
1014
+ _id: "Exit",
1015
+ _tag: options.op,
1016
+ [options.prop]: this[args]
1017
+ };
1018
+ },
1019
+ [symbol2](that) {
1020
+ return isExit(that) && that._tag === this._tag && equals(this[args], that[args]);
1021
+ },
1022
+ [symbol]() {
1023
+ return combine(string(options.op), hash(this[args]));
1024
+ }
1025
+ };
1026
+ const ExitPrimitive = function(value) {
1027
+ this[args] = value;
1028
+ };
1029
+ ExitPrimitive.prototype = Proto;
1030
+ return function(value) {
1031
+ return new ExitPrimitive(value);
1032
+ };
1033
+ };
1034
+ var exitSucceed = /* @__PURE__ */ makeExit({
1035
+ op: "Success",
1036
+ prop: "value",
1037
+ [evaluate](fiber) {
1038
+ const cont = fiber.getCont(contA);
1039
+ return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this);
1040
+ }
1041
+ });
1042
+ var StackTraceKey = {
1043
+ key: "effect/Cause/StackTrace"
1044
+ };
1045
+ var InterruptorStackTrace = {
1046
+ key: "effect/Cause/InterruptorStackTrace"
1047
+ };
1048
+ var exitFailCause = /* @__PURE__ */ makeExit({
1049
+ op: "Failure",
1050
+ prop: "cause",
1051
+ [evaluate](fiber) {
1052
+ let cause = this[args];
1053
+ let annotated = false;
1054
+ if (fiber.cache.stackFrame) {
1055
+ cause = causeAnnotate(cause, {
1056
+ mapUnsafe: new Map([[StackTraceKey.key, fiber.cache.stackFrame]])
1057
+ });
1058
+ annotated = true;
1059
+ }
1060
+ let cont = fiber.getCont(contE);
1061
+ const interruptedCause = fiber._interruptedCause;
1062
+ if (interruptedCause && fiber.interruptible) {
1063
+ let skippedHandler = false;
1064
+ while (cont && fiber.interruptible) {
1065
+ skippedHandler ||= identifier in cont;
1066
+ cont = fiber.getCont(contE);
1067
+ }
1068
+ if (skippedHandler) {
1069
+ cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail"));
1070
+ }
1071
+ cause = causeAddInterrupts(cause, interruptedCause);
1072
+ annotated = true;
1073
+ }
1074
+ return cont ? cont[contE](cause, fiber, annotated ? undefined : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this);
1075
+ }
1076
+ });
1077
+ var exitFail = (e) => exitFailCause(causeFail(e));
1078
+ var exitDie = (defect) => exitFailCause(causeDie(defect));
1079
+ var withFiber = /* @__PURE__ */ makePrimitive({
1080
+ op: "WithFiber",
1081
+ [evaluate](fiber) {
1082
+ return this[args](fiber);
1083
+ }
1084
+ });
1085
+ var withFiberSucceed = /* @__PURE__ */ makePrimitive({
1086
+ op: "WithFiberSucceed",
1087
+ [evaluate](fiber) {
1088
+ const value = this[args](fiber);
1089
+ const cont = fiber.getCont(contA);
1090
+ return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value));
1091
+ }
1092
+ });
1093
+ var YieldableError = /* @__PURE__ */ function() {
1094
+
1095
+ class YieldableError extends globalThis.Error {
1096
+ }
1097
+ const proto = /* @__PURE__ */ makePrimitiveProto({
1098
+ op: "YieldableError",
1099
+ [evaluate]() {
1100
+ return exitFail(this);
1101
+ }
1102
+ });
1103
+ delete proto.toString;
1104
+ Object.assign(YieldableError.prototype, proto);
1105
+ return YieldableError;
1106
+ }();
1107
+ var Error2 = /* @__PURE__ */ function() {
1108
+ const plainArgsSymbol = /* @__PURE__ */ Symbol.for("effect/Data/Error/plainArgs");
1109
+ return class Base extends YieldableError {
1110
+ constructor(args) {
1111
+ super(args?.message, args?.cause ? {
1112
+ cause: args.cause
1113
+ } : undefined);
1114
+ if (args) {
1115
+ assignProperties(this, args);
1116
+ Object.defineProperty(this, plainArgsSymbol, {
1117
+ value: args,
1118
+ enumerable: false
1119
+ });
1120
+ }
1121
+ }
1122
+ toJSON() {
1123
+ return {
1124
+ ...this[plainArgsSymbol],
1125
+ ...this
1126
+ };
1127
+ }
1128
+ };
1129
+ }();
1130
+ var TaggedError = (tag) => {
1131
+
1132
+ class Base extends Error2 {
1133
+ _tag = tag;
1134
+ }
1135
+ Base.prototype.name = tag;
1136
+ return Base;
1137
+ };
1138
+ var DoneTypeId = "~effect/Cause/Done";
1139
+ var isDone = (u) => hasProperty(u, DoneTypeId);
1140
+ var DoneVoid = {
1141
+ [DoneTypeId]: DoneTypeId,
1142
+ _tag: "Done",
1143
+ value: undefined
1144
+ };
1145
+
1146
+ var Prototype = (options) => makePrimitiveProto({
1147
+ op: options.label,
1148
+ [evaluate]: options.evaluate
1149
+ });
1150
+
1151
+ var TypeId = "~effect/Option";
1152
+ var CommonProto = {
1153
+ [TypeId]: {
1154
+ _A: (_) => _
1155
+ },
1156
+ ...PipeInspectableProto,
1157
+ [Symbol.iterator]() {
1158
+ return new SingleShotGen(this);
1159
+ }
1160
+ };
1161
+ var SomeProto = /* @__PURE__ */ Object.defineProperty(/* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto), {
1162
+ _tag: "Some",
1163
+ _op: "Some",
1164
+ [symbol2](that) {
1165
+ return isOption(that) && isSome(that) && equals(this.value, that.value);
1166
+ },
1167
+ [symbol]() {
1168
+ return combine(hash(this._tag))(hash(this.value));
1169
+ },
1170
+ toString() {
1171
+ return `some(${format(this.value)})`;
1172
+ },
1173
+ toJSON() {
1174
+ return {
1175
+ _id: "Option",
1176
+ _tag: this._tag,
1177
+ value: toJson(this.value)
1178
+ };
1179
+ }
1180
+ }), "valueOrUndefined", {
1181
+ get() {
1182
+ return this.value;
1183
+ }
1184
+ });
1185
+ var NoneHash = /* @__PURE__ */ hash("None");
1186
+ var NoneProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto), {
1187
+ _tag: "None",
1188
+ _op: "None",
1189
+ valueOrUndefined: undefined,
1190
+ [symbol2](that) {
1191
+ return isOption(that) && isNone(that);
1192
+ },
1193
+ [symbol]() {
1194
+ return NoneHash;
1195
+ },
1196
+ toString() {
1197
+ return `none()`;
1198
+ },
1199
+ toJSON() {
1200
+ return {
1201
+ _id: "Option",
1202
+ _tag: this._tag
1203
+ };
1204
+ }
1205
+ });
1206
+ var isOption = (input) => hasProperty(input, TypeId);
1207
+ var isNone = (fa) => fa._tag === "None";
1208
+ var isSome = (fa) => fa._tag === "Some";
1209
+ var none = /* @__PURE__ */ Object.create(NoneProto);
1210
+ var SomeImpl = function(value) {
1211
+ this.value = value;
1212
+ };
1213
+ SomeImpl.prototype = SomeProto;
1214
+ var some = (value) => new SomeImpl(value);
1215
+
1216
+ var TypeId2 = "~effect/Result";
1217
+ var CommonProto2 = {
1218
+ [TypeId2]: {
1219
+ _A: (_) => _,
1220
+ _E: (_) => _
1221
+ },
1222
+ ...PipeInspectableProto,
1223
+ [Symbol.iterator]() {
1224
+ return new SingleShotGen(this);
1225
+ }
1226
+ };
1227
+ var SuccessProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto2), {
1228
+ _tag: "Success",
1229
+ _op: "Success",
1230
+ [symbol2](that) {
1231
+ return isResult(that) && isSuccess(that) && equals(this.success, that.success);
1232
+ },
1233
+ [symbol]() {
1234
+ return combine(hash(this._tag))(hash(this.success));
1235
+ },
1236
+ toString() {
1237
+ return `success(${format(this.success)})`;
1238
+ },
1239
+ toJSON() {
1240
+ return {
1241
+ _id: "Result",
1242
+ _tag: this._tag,
1243
+ value: toJson(this.success)
1244
+ };
1245
+ }
1246
+ });
1247
+ var FailureProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto2), {
1248
+ _tag: "Failure",
1249
+ _op: "Failure",
1250
+ [symbol2](that) {
1251
+ return isResult(that) && isFailure(that) && equals(this.failure, that.failure);
1252
+ },
1253
+ [symbol]() {
1254
+ return combine(hash(this._tag))(hash(this.failure));
1255
+ },
1256
+ toString() {
1257
+ return `failure(${format(this.failure)})`;
1258
+ },
1259
+ toJSON() {
1260
+ return {
1261
+ _id: "Result",
1262
+ _tag: this._tag,
1263
+ failure: toJson(this.failure)
1264
+ };
1265
+ }
1266
+ });
1267
+ var isResult = (input) => hasProperty(input, TypeId2);
1268
+ var isFailure = (result) => result._tag === "Failure";
1269
+ var isSuccess = (result) => result._tag === "Success";
1270
+ var FailureImpl = function(failure) {
1271
+ this.failure = failure;
1272
+ };
1273
+ FailureImpl.prototype = FailureProto;
1274
+ var fail = (failure) => new FailureImpl(failure);
1275
+ var SuccessImpl = function(success) {
1276
+ this.success = success;
1277
+ };
1278
+ SuccessImpl.prototype = SuccessProto;
1279
+ var succeed = (success) => new SuccessImpl(success);
1280
+
1281
+ function make(compare) {
1282
+ return (self, that) => self === that ? 0 : compare(self, that);
1283
+ }
1284
+ var Number2 = /* @__PURE__ */ make((self, that) => {
1285
+ if (globalThis.Number.isNaN(self) && globalThis.Number.isNaN(that))
1286
+ return 0;
1287
+ if (globalThis.Number.isNaN(self))
1288
+ return -1;
1289
+ if (globalThis.Number.isNaN(that))
1290
+ return 1;
1291
+ return self < that ? -1 : 1;
1292
+ });
1293
+ var mapInput = /* @__PURE__ */ dual(2, (self, f) => make((b1, b2) => self(f(b1), f(b2))));
1294
+ var isGreaterThan = (O) => dual(2, (self, that) => O(self, that) === 1);
1295
+
1296
+ var none2 = () => none;
1297
+ var some2 = some;
1298
+ var isNone2 = isNone;
1299
+
1300
+ var ServiceTypeId = "~effect/Context/Service";
1301
+ var Service = function() {
1302
+ function KeyClass() {}
1303
+ const self = KeyClass;
1304
+ Object.setPrototypeOf(self, ServiceProto);
1305
+ const init = (key, options) => {
1306
+ self.key = key;
1307
+ if (options?.defaultValue) {
1308
+ self[ReferenceTypeId] = ReferenceTypeId;
1309
+ self.defaultValue = options.defaultValue;
1310
+ }
1311
+ if (options?.make) {
1312
+ self.make = options.make;
1313
+ }
1314
+ if (options?.fiberCached) {
1315
+ cacheKeys.add(key);
1316
+ }
1317
+ return self;
1318
+ };
1319
+ return arguments.length > 0 ? init(arguments[0], arguments[1]) : init;
1320
+ };
1321
+ var ServiceProto = {
1322
+ [ServiceTypeId]: ServiceTypeId,
1323
+ .../* @__PURE__ */ Prototype({
1324
+ label: "Service",
1325
+ evaluate(fiber) {
1326
+ return exitSucceed(get(fiber.context, this));
1327
+ }
1328
+ }),
1329
+ toJSON() {
1330
+ return {
1331
+ _id: "Service",
1332
+ key: this.key
1333
+ };
1334
+ },
1335
+ of(self) {
1336
+ return self;
1337
+ },
1338
+ context(self) {
1339
+ return make2(this, self);
1340
+ },
1341
+ use(f) {
1342
+ return withFiber((fiber) => f(get(fiber.context, this)));
1343
+ },
1344
+ useSync(f) {
1345
+ return withFiber((fiber) => exitSucceed(f(get(fiber.context, this))));
1346
+ }
1347
+ };
1348
+ var cacheKeys = /* @__PURE__ */ new Set;
1349
+ var ReferenceTypeId = "~effect/Context/Reference";
1350
+ var TypeId3 = "~effect/Context";
1351
+ var FlattenAfterBaseHits = 8;
1352
+ var makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => {
1353
+ const self = Object.create(Proto);
1354
+ self.cacheRoot = cacheRoot ?? self;
1355
+ self.base = base;
1356
+ self.overlay = overlay;
1357
+ self.depth = depth;
1358
+ self._flat = undefined;
1359
+ self.baseHits = 0;
1360
+ self.maxDepth = maxDepth;
1361
+ return self;
1362
+ };
1363
+ var applyOverlays = (map, overlay) => {
1364
+ if (!overlay)
1365
+ return;
1366
+ applyOverlays(map, overlay.parent);
1367
+ map.set(overlay.key, overlay.value);
1368
+ };
1369
+ var flatten = (self) => {
1370
+ if (self._flat)
1371
+ return self._flat;
1372
+ if (!self.overlay)
1373
+ return self._flat = self.base;
1374
+ const map = new Map(self.base);
1375
+ applyOverlays(map, self.overlay);
1376
+ return self._flat = map;
1377
+ };
1378
+ var notFound = /* @__PURE__ */ Symbol();
1379
+ var lookup = (self, key) => {
1380
+ const impl = self;
1381
+ for (let overlay = impl.overlay;overlay; overlay = overlay.parent) {
1382
+ if (overlay.key === key)
1383
+ return overlay.value;
1384
+ }
1385
+ const value = impl.base.get(key);
1386
+ if (value === undefined && !impl.base.has(key))
1387
+ return notFound;
1388
+ if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) {
1389
+ impl.base = flatten(impl);
1390
+ impl.overlay = undefined;
1391
+ impl.depth = 0;
1392
+ }
1393
+ return value;
1394
+ };
1395
+ var makeUnsafe = (mapUnsafe, options) => {
1396
+ const maxDepth = options?.maxDepth;
1397
+ return makeImpl(undefined, mapUnsafe, undefined, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8);
1398
+ };
1399
+ var Proto = {
1400
+ get mapUnsafe() {
1401
+ return flatten(this);
1402
+ },
1403
+ ...PipeInspectableProto,
1404
+ [TypeId3]: {
1405
+ _Services: (_) => _
1406
+ },
1407
+ toJSON() {
1408
+ return {
1409
+ _id: "Context",
1410
+ services: Array.from(this.mapUnsafe).map(([key, value]) => ({
1411
+ key,
1412
+ value
1413
+ }))
1414
+ };
1415
+ },
1416
+ [symbol2](that) {
1417
+ if (!isContext(that))
1418
+ return false;
1419
+ const self = this.mapUnsafe;
1420
+ const other = that.mapUnsafe;
1421
+ if (self.size !== other.size)
1422
+ return false;
1423
+ for (const [key, value] of self) {
1424
+ if (!other.has(key) || !equals(value, other.get(key)))
1425
+ return false;
1426
+ }
1427
+ return true;
1428
+ },
1429
+ [symbol]() {
1430
+ return number(this.mapUnsafe.size);
1431
+ }
1432
+ };
1433
+ var hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot;
1434
+ var isContext = (u) => hasProperty(u, TypeId3);
1435
+ var isReference = (u) => !!u[ReferenceTypeId];
1436
+ var empty = () => emptyContext2;
1437
+ var emptyContext2 = /* @__PURE__ */ makeUnsafe(/* @__PURE__ */ new Map);
1438
+ var make2 = (key, service) => makeUnsafe(new Map([[key.key, service]]));
1439
+ var add = /* @__PURE__ */ dual(3, (self, key, service) => addUnsafe(self, key.key, service));
1440
+ var addUnsafe = (self, key, service) => {
1441
+ const impl = self;
1442
+ const cacheRoot = cacheKeys.has(key) ? undefined : impl.cacheRoot;
1443
+ if (impl.depth >= impl.maxDepth) {
1444
+ const map = new Map(impl._flat ?? impl.base);
1445
+ if (!impl._flat)
1446
+ applyOverlays(map, impl.overlay);
1447
+ map.set(key, service);
1448
+ return makeImpl(cacheRoot, map, undefined, 0, impl.maxDepth);
1449
+ }
1450
+ return makeImpl(cacheRoot, impl.base, {
1451
+ key,
1452
+ value: service,
1453
+ parent: impl.overlay
1454
+ }, impl.depth + 1, impl.maxDepth);
1455
+ };
1456
+ var getOrUndefinedUnsafe = (self, key) => {
1457
+ const value = lookup(self, key);
1458
+ return value === notFound ? undefined : value;
1459
+ };
1460
+ var getUnsafe = /* @__PURE__ */ dual(2, (self, service) => {
1461
+ const value = lookup(self, service.key);
1462
+ if (value === notFound) {
1463
+ if (isReference(service))
1464
+ return getDefaultValue(service);
1465
+ throw serviceNotFoundError(service);
1466
+ }
1467
+ return value;
1468
+ });
1469
+ var get = getUnsafe;
1470
+ var defaultValueCacheKey = "~effect/Context/defaultValue";
1471
+ var getDefaultValue = (ref) => {
1472
+ if (defaultValueCacheKey in ref) {
1473
+ return ref[defaultValueCacheKey];
1474
+ }
1475
+ return ref[defaultValueCacheKey] = ref.defaultValue();
1476
+ };
1477
+ var serviceNotFoundError = (service) => {
1478
+ const error = new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`);
1479
+ if (error.stack) {
1480
+ const lines = error.stack.split(`
1481
+ `);
1482
+ lines.splice(1, 3);
1483
+ error.stack = lines.join(`
1484
+ `);
1485
+ }
1486
+ return error;
1487
+ };
1488
+ var Reference = Service;
1489
+
1490
+ var succeed2 = succeed;
1491
+ var fail2 = fail;
1492
+ var isFailure2 = isFailure;
1493
+
1494
+ var Array2 = globalThis.Array;
1495
+ var isArray = Array2.isArray;
1496
+ var empty2 = () => [];
1497
+
1498
+ var TypeId4 = "~effect/Duration";
1499
+ var bigint0 = /* @__PURE__ */ BigInt(0);
1500
+ var bigint1 = /* @__PURE__ */ BigInt(1);
1501
+ var bigint2 = /* @__PURE__ */ BigInt(2);
1502
+ var bigint10 = /* @__PURE__ */ BigInt(10);
1503
+ var bigint24 = /* @__PURE__ */ BigInt(24);
1504
+ var bigint60 = /* @__PURE__ */ BigInt(60);
1505
+ var bigint1e3 = /* @__PURE__ */ BigInt(1000);
1506
+ var bigint1e6 = /* @__PURE__ */ BigInt(1e6);
1507
+ var bigint1e9 = /* @__PURE__ */ BigInt(1e9);
1508
+ var bigintNanosPerMinute = /* @__PURE__ */ BigInt(60000000000);
1509
+ var bigintNanosPerHour = /* @__PURE__ */ BigInt(3600000000000);
1510
+ var bigintNanosPerDay = /* @__PURE__ */ BigInt(86400000000000);
1511
+ var bigintNanosPerWeek = /* @__PURE__ */ BigInt(604800000000000);
1512
+ var roundTiesAwayFromZero = (input) => BigInt(Math.sign(input) * Math.round(Math.abs(input)));
1513
+ var roundMillisToNanos = (millis) => Number.isInteger(millis) ? BigInt(millis) * bigint1e6 : roundTiesAwayFromZero(millis * 1e6);
1514
+ var fromNanosNumber = (nanos) => make3(Number.isFinite(nanos) ? roundTiesAwayFromZero(nanos) : nanos);
1515
+ var nanosToUnit = (nanos, divisor) => {
1516
+ const value = Number(nanos);
1517
+ if (Number.isFinite(value))
1518
+ return value / divisor;
1519
+ const scale = BigInt(divisor);
1520
+ return Number(nanos / scale) + Number(nanos % scale) / divisor;
1521
+ };
1522
+ var parseNanos = (input, scale) => {
1523
+ const decimalIndex = input.indexOf(".");
1524
+ if (decimalIndex === -1)
1525
+ return BigInt(input) * scale;
1526
+ const isNegative = input[0] === "-";
1527
+ const fractional = input.slice(decimalIndex + 1);
1528
+ const fractionalScale = bigint10 ** BigInt(fractional.length);
1529
+ const scaled = (BigInt(input.slice(isNegative ? 1 : 0, decimalIndex)) * fractionalScale + BigInt(fractional)) * scale;
1530
+ return divideTiesAwayFromZero(isNegative ? -scaled : scaled, fractionalScale);
1531
+ };
1532
+ var divideTiesAwayFromZero = (numerator, denominator) => {
1533
+ const absolute = numerator < bigint0 ? -numerator : numerator;
1534
+ const rounded = absolute / denominator + (absolute % denominator * bigint2 >= denominator ? bigint1 : bigint0);
1535
+ return numerator < bigint0 ? -rounded : rounded;
1536
+ };
1537
+ var fromMillisString = (input, scale) => {
1538
+ const millis = Number(input) * scale;
1539
+ if (!Number.isFinite(millis))
1540
+ return make3(millis);
1541
+ const nanos = parseNanos(input, BigInt(scale) * bigint1e6);
1542
+ return make3(Number.isInteger(millis) && BigInt(millis) * bigint1e6 === nanos ? millis : nanos);
1543
+ };
1544
+ var DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/;
1545
+ var fromInputUnsafe = (input) => {
1546
+ switch (typeof input) {
1547
+ case "number":
1548
+ return millis(input);
1549
+ case "bigint":
1550
+ return nanos(input);
1551
+ case "string": {
1552
+ if (input === "Infinity") {
1553
+ return infinity;
1554
+ }
1555
+ if (input === "-Infinity") {
1556
+ return negativeInfinity;
1557
+ }
1558
+ const match = DURATION_REGEXP.exec(input);
1559
+ if (!match)
1560
+ break;
1561
+ const [_, valueStr, unit] = match;
1562
+ if (unit === "nano" || unit === "nanos") {
1563
+ return nanos(parseNanos(valueStr, bigint1));
1564
+ }
1565
+ if (unit === "micro" || unit === "micros") {
1566
+ return nanos(parseNanos(valueStr, bigint1e3));
1567
+ }
1568
+ switch (unit) {
1569
+ case "milli":
1570
+ case "millis":
1571
+ return fromMillisString(valueStr, 1);
1572
+ case "second":
1573
+ case "seconds":
1574
+ return fromMillisString(valueStr, 1000);
1575
+ case "minute":
1576
+ case "minutes":
1577
+ return fromMillisString(valueStr, 60000);
1578
+ case "hour":
1579
+ case "hours":
1580
+ return fromMillisString(valueStr, 3600000);
1581
+ case "day":
1582
+ case "days":
1583
+ return fromMillisString(valueStr, 86400000);
1584
+ case "week":
1585
+ case "weeks":
1586
+ return fromMillisString(valueStr, 604800000);
1587
+ }
1588
+ break;
1589
+ }
1590
+ case "object": {
1591
+ if (input === null)
1592
+ break;
1593
+ if (TypeId4 in input)
1594
+ return input;
1595
+ if (Array.isArray(input)) {
1596
+ if (input.length !== 2 || !input.every(isNumber)) {
1597
+ return invalid(input);
1598
+ }
1599
+ if (Number.isNaN(input[0]) || Number.isNaN(input[1])) {
1600
+ return zero;
1601
+ }
1602
+ if (input[0] === -Infinity || input[1] === -Infinity) {
1603
+ return negativeInfinity;
1604
+ }
1605
+ if (input[0] === Infinity || input[1] === Infinity) {
1606
+ return infinity;
1607
+ }
1608
+ const nanos = input[0] * 1e9 + input[1];
1609
+ return Number.isFinite(nanos) && Number.isInteger(input[0]) && Number.isInteger(input[1]) ? make3(BigInt(input[0]) * bigint1e9 + BigInt(input[1])) : fromNanosNumber(nanos);
1610
+ }
1611
+ const obj = input;
1612
+ let millis = 0;
1613
+ if (obj.weeks)
1614
+ millis += obj.weeks * 604800000;
1615
+ if (obj.days)
1616
+ millis += obj.days * 86400000;
1617
+ if (obj.hours)
1618
+ millis += obj.hours * 3600000;
1619
+ if (obj.minutes)
1620
+ millis += obj.minutes * 60000;
1621
+ if (obj.seconds)
1622
+ millis += obj.seconds * 1000;
1623
+ if (obj.milliseconds)
1624
+ millis += obj.milliseconds;
1625
+ if (!obj.microseconds && !obj.nanoseconds) {
1626
+ if (!Number.isFinite(millis))
1627
+ return make3(millis);
1628
+ const exact = sumObjectNanos(obj);
1629
+ return exact === undefined || BigInt(millis) * bigint1e6 === exact ? make3(millis) : make3(exact);
1630
+ }
1631
+ const nanos = millis * 1e6 + (obj.microseconds ?? 0) * 1000 + (obj.nanoseconds ?? 0);
1632
+ const exact = Number.isFinite(nanos) ? sumObjectNanos(obj) : undefined;
1633
+ return exact === undefined ? fromNanosNumber(nanos) : make3(exact);
1634
+ }
1635
+ }
1636
+ return invalid(input);
1637
+ };
1638
+ var isIntegerOrUnset = (n) => !n || Number.isInteger(n);
1639
+ var sumObjectNanos = (obj) => {
1640
+ if (!isIntegerOrUnset(obj.weeks) || !isIntegerOrUnset(obj.days) || !isIntegerOrUnset(obj.hours) || !isIntegerOrUnset(obj.minutes) || !isIntegerOrUnset(obj.seconds) || !isIntegerOrUnset(obj.milliseconds) || !isIntegerOrUnset(obj.microseconds) || !isIntegerOrUnset(obj.nanoseconds))
1641
+ return;
1642
+ let nanos = bigint0;
1643
+ if (obj.weeks)
1644
+ nanos += BigInt(obj.weeks) * bigintNanosPerWeek;
1645
+ if (obj.days)
1646
+ nanos += BigInt(obj.days) * bigintNanosPerDay;
1647
+ if (obj.hours)
1648
+ nanos += BigInt(obj.hours) * bigintNanosPerHour;
1649
+ if (obj.minutes)
1650
+ nanos += BigInt(obj.minutes) * bigintNanosPerMinute;
1651
+ if (obj.seconds)
1652
+ nanos += BigInt(obj.seconds) * bigint1e9;
1653
+ if (obj.milliseconds)
1654
+ nanos += BigInt(obj.milliseconds) * bigint1e6;
1655
+ if (obj.microseconds)
1656
+ nanos += BigInt(obj.microseconds) * bigint1e3;
1657
+ if (obj.nanoseconds)
1658
+ nanos += BigInt(obj.nanoseconds);
1659
+ return nanos;
1660
+ };
1661
+ var invalid = (input) => {
1662
+ throw new Error(`Invalid Input: ${input}`);
1663
+ };
1664
+ var zeroDurationValue = {
1665
+ _tag: "Millis",
1666
+ millis: 0
1667
+ };
1668
+ var infinityDurationValue = {
1669
+ _tag: "Infinity"
1670
+ };
1671
+ var negativeInfinityDurationValue = {
1672
+ _tag: "NegativeInfinity"
1673
+ };
1674
+ var DurationProto = {
1675
+ [TypeId4]: TypeId4,
1676
+ [symbol]() {
1677
+ switch (this.value._tag) {
1678
+ case "Millis":
1679
+ return hash(roundMillisToNanos(this.value.millis));
1680
+ case "Nanos":
1681
+ return hash(this.value.nanos);
1682
+ default:
1683
+ return structure(this.value);
1684
+ }
1685
+ },
1686
+ [symbol2](that) {
1687
+ return isDuration(that) && equals2(this, that);
1688
+ },
1689
+ toString() {
1690
+ switch (this.value._tag) {
1691
+ case "Infinity":
1692
+ return "Infinity";
1693
+ case "NegativeInfinity":
1694
+ return "-Infinity";
1695
+ case "Nanos":
1696
+ return `${this.value.nanos} nanos`;
1697
+ case "Millis":
1698
+ return `${this.value.millis} millis`;
1699
+ }
1700
+ },
1701
+ toJSON() {
1702
+ switch (this.value._tag) {
1703
+ case "Millis":
1704
+ return {
1705
+ _id: "Duration",
1706
+ _tag: "Millis",
1707
+ millis: this.value.millis
1708
+ };
1709
+ case "Nanos":
1710
+ return {
1711
+ _id: "Duration",
1712
+ _tag: "Nanos",
1713
+ nanos: String(this.value.nanos)
1714
+ };
1715
+ case "Infinity":
1716
+ return {
1717
+ _id: "Duration",
1718
+ _tag: "Infinity"
1719
+ };
1720
+ case "NegativeInfinity":
1721
+ return {
1722
+ _id: "Duration",
1723
+ _tag: "NegativeInfinity"
1724
+ };
1725
+ }
1726
+ },
1727
+ [NodeInspectSymbol]() {
1728
+ return this.toJSON();
1729
+ },
1730
+ pipe() {
1731
+ return pipeArguments(this, arguments);
1732
+ }
1733
+ };
1734
+ var make3 = (input) => {
1735
+ const duration = Object.create(DurationProto);
1736
+ if (typeof input === "number") {
1737
+ if (isNaN(input) || input === 0 || Object.is(input, -0)) {
1738
+ duration.value = zeroDurationValue;
1739
+ } else if (!Number.isFinite(input)) {
1740
+ duration.value = input > 0 ? infinityDurationValue : negativeInfinityDurationValue;
1741
+ } else if (!Number.isInteger(input)) {
1742
+ duration.value = {
1743
+ _tag: "Nanos",
1744
+ nanos: roundMillisToNanos(input)
1745
+ };
1746
+ } else {
1747
+ duration.value = {
1748
+ _tag: "Millis",
1749
+ millis: input
1750
+ };
1751
+ }
1752
+ } else if (input === bigint0) {
1753
+ duration.value = zeroDurationValue;
1754
+ } else {
1755
+ duration.value = {
1756
+ _tag: "Nanos",
1757
+ nanos: input
1758
+ };
1759
+ }
1760
+ return duration;
1761
+ };
1762
+ var isDuration = (u) => hasProperty(u, TypeId4);
1763
+ var isZero = (self) => {
1764
+ switch (self.value._tag) {
1765
+ case "Millis":
1766
+ return self.value.millis === 0;
1767
+ case "Nanos":
1768
+ return self.value.nanos === bigint0;
1769
+ case "Infinity":
1770
+ case "NegativeInfinity":
1771
+ return false;
1772
+ }
1773
+ };
1774
+ var isNegative = (self) => {
1775
+ switch (self.value._tag) {
1776
+ case "Millis":
1777
+ return self.value.millis < 0;
1778
+ case "Nanos":
1779
+ return self.value.nanos < bigint0;
1780
+ case "NegativeInfinity":
1781
+ return true;
1782
+ case "Infinity":
1783
+ return false;
1784
+ }
1785
+ };
1786
+ var abs = (self) => {
1787
+ switch (self.value._tag) {
1788
+ case "Infinity":
1789
+ case "NegativeInfinity":
1790
+ return infinity;
1791
+ case "Millis":
1792
+ return self.value.millis < 0 ? make3(-self.value.millis) : self;
1793
+ case "Nanos":
1794
+ return self.value.nanos < bigint0 ? make3(-self.value.nanos) : self;
1795
+ }
1796
+ };
1797
+ var zero = /* @__PURE__ */ make3(0);
1798
+ var infinity = /* @__PURE__ */ make3(Infinity);
1799
+ var negativeInfinity = /* @__PURE__ */ make3(-Infinity);
1800
+ var nanos = (nanos) => make3(nanos);
1801
+ var millis = (millis) => make3(millis);
1802
+ var toMillis = (self) => match(fromInputUnsafe(self), {
1803
+ onMillis: identity,
1804
+ onNanos: (nanos) => nanosToUnit(nanos, 1e6),
1805
+ onInfinity: () => Infinity,
1806
+ onNegativeInfinity: () => -Infinity
1807
+ });
1808
+ var toNanosUnsafe = (input) => {
1809
+ const self = fromInputUnsafe(input);
1810
+ switch (self.value._tag) {
1811
+ case "Infinity":
1812
+ case "NegativeInfinity":
1813
+ throw new Error("Cannot convert infinite duration to nanos");
1814
+ case "Nanos":
1815
+ return self.value.nanos;
1816
+ case "Millis":
1817
+ return roundMillisToNanos(self.value.millis);
1818
+ }
1819
+ };
1820
+ var match = /* @__PURE__ */ dual(2, (self, options) => {
1821
+ switch (self.value._tag) {
1822
+ case "Millis":
1823
+ return options.onMillis(self.value.millis);
1824
+ case "Nanos":
1825
+ return options.onNanos(self.value.nanos);
1826
+ case "Infinity":
1827
+ return options.onInfinity();
1828
+ case "NegativeInfinity":
1829
+ return (options.onNegativeInfinity ?? options.onInfinity)();
1830
+ }
1831
+ });
1832
+ var matchPair = /* @__PURE__ */ dual(3, (self, that, options) => {
1833
+ if (self.value._tag === "Infinity" || self.value._tag === "NegativeInfinity" || that.value._tag === "Infinity" || that.value._tag === "NegativeInfinity")
1834
+ return options.onInfinity(self, that);
1835
+ if (self.value._tag === "Millis") {
1836
+ return that.value._tag === "Millis" ? options.onMillis(self.value.millis, that.value.millis) : options.onNanos(toNanosUnsafe(self), that.value.nanos);
1837
+ } else {
1838
+ return options.onNanos(self.value.nanos, toNanosUnsafe(that));
1839
+ }
1840
+ });
1841
+ var Equivalence = (self, that) => matchPair(self, that, {
1842
+ onMillis: (self, that) => self === that,
1843
+ onNanos: (self, that) => self === that,
1844
+ onInfinity: (self, that) => self.value._tag === that.value._tag
1845
+ });
1846
+ var equals2 = /* @__PURE__ */ dual(2, (self, that) => Equivalence(self, that));
1847
+ var parts = (self) => {
1848
+ if (self.value._tag === "Infinity") {
1849
+ return {
1850
+ days: Infinity,
1851
+ hours: Infinity,
1852
+ minutes: Infinity,
1853
+ seconds: Infinity,
1854
+ millis: Infinity,
1855
+ nanos: Infinity
1856
+ };
1857
+ }
1858
+ if (self.value._tag === "NegativeInfinity") {
1859
+ return {
1860
+ days: -Infinity,
1861
+ hours: -Infinity,
1862
+ minutes: -Infinity,
1863
+ seconds: -Infinity,
1864
+ millis: -Infinity,
1865
+ nanos: -Infinity
1866
+ };
1867
+ }
1868
+ const n = toNanosUnsafe(self);
1869
+ const neg = n < bigint0;
1870
+ const a = neg ? -n : n;
1871
+ const ms = a / bigint1e6;
1872
+ const sec = ms / bigint1e3;
1873
+ const min = sec / bigint60;
1874
+ const hr = min / bigint60;
1875
+ const d = hr / bigint24;
1876
+ const sign = neg ? -1 : 1;
1877
+ return {
1878
+ days: sign * Number(d),
1879
+ hours: sign * Number(hr % bigint24),
1880
+ minutes: sign * Number(min % bigint60),
1881
+ seconds: sign * Number(sec % bigint60),
1882
+ millis: sign * Number(ms % bigint1e3),
1883
+ nanos: sign * Number(a % bigint1e6)
1884
+ };
1885
+ };
1886
+ var format2 = (self) => {
1887
+ if (self.value._tag === "Infinity") {
1888
+ return "Infinity";
1889
+ }
1890
+ if (self.value._tag === "NegativeInfinity") {
1891
+ return "-Infinity";
1892
+ }
1893
+ if (isZero(self)) {
1894
+ return "0";
1895
+ }
1896
+ if (isNegative(self)) {
1897
+ return "-" + format2(abs(self));
1898
+ }
1899
+ const fragments = parts(self);
1900
+ const pieces = [];
1901
+ if (fragments.days !== 0) {
1902
+ pieces.push(`${fragments.days}d`);
1903
+ }
1904
+ if (fragments.hours !== 0) {
1905
+ pieces.push(`${fragments.hours}h`);
1906
+ }
1907
+ if (fragments.minutes !== 0) {
1908
+ pieces.push(`${fragments.minutes}m`);
1909
+ }
1910
+ if (fragments.seconds !== 0) {
1911
+ pieces.push(`${fragments.seconds}s`);
1912
+ }
1913
+ if (fragments.millis !== 0) {
1914
+ pieces.push(`${fragments.millis}ms`);
1915
+ }
1916
+ if (fragments.nanos !== 0) {
1917
+ pieces.push(`${fragments.nanos}ns`);
1918
+ }
1919
+ return pieces.join(" ");
1920
+ };
1921
+
1922
+ var Scheduler = /* @__PURE__ */ Reference("effect/Scheduler", {
1923
+ fiberCached: true,
1924
+ defaultValue: () => new MixedScheduler
1925
+ });
1926
+ var setMicrotask = (f) => {
1927
+ let cancelled = false;
1928
+ Promise.resolve().then(() => {
1929
+ if (!cancelled)
1930
+ f();
1931
+ });
1932
+ return () => {
1933
+ cancelled = true;
1934
+ };
1935
+ };
1936
+ var setTimer = "setImmediate" in globalThis ? (f) => {
1937
+ const timer = globalThis.setImmediate(f);
1938
+ return () => globalThis.clearImmediate(timer);
1939
+ } : (f) => {
1940
+ const timer = setTimeout(f, 0);
1941
+ return () => clearTimeout(timer);
1942
+ };
1943
+ var setImmediate = (f) => {
1944
+ try {
1945
+ return setTimer(f);
1946
+ } catch {
1947
+ return setMicrotask(f);
1948
+ }
1949
+ };
1950
+
1951
+ class PriorityBuckets {
1952
+ buckets = [];
1953
+ scheduleTask(task, priority) {
1954
+ const buckets = this.buckets;
1955
+ const len = buckets.length;
1956
+ let bucket;
1957
+ let index = 0;
1958
+ for (;index < len; index++) {
1959
+ if (buckets[index][0] > priority)
1960
+ break;
1961
+ bucket = buckets[index];
1962
+ }
1963
+ if (bucket && bucket[0] === priority) {
1964
+ bucket[1].push(task);
1965
+ } else if (index === len) {
1966
+ buckets.push([priority, [task]]);
1967
+ } else {
1968
+ buckets.splice(index, 0, [priority, [task]]);
1969
+ }
1970
+ }
1971
+ drain() {
1972
+ const buckets = this.buckets;
1973
+ this.buckets = [];
1974
+ return buckets;
1975
+ }
1976
+ }
1977
+
1978
+ class MixedScheduler {
1979
+ executionMode;
1980
+ setImmediate;
1981
+ constructor(executionMode = "async", setImmediateFn) {
1982
+ this.executionMode = executionMode;
1983
+ this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate);
1984
+ }
1985
+ shouldYield(fiber) {
1986
+ return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield;
1987
+ }
1988
+ makeDispatcher() {
1989
+ return new MixedSchedulerDispatcher(this.setImmediate);
1990
+ }
1991
+ }
1992
+
1993
+ class MixedSchedulerDispatcher {
1994
+ tasks = /* @__PURE__ */ new PriorityBuckets;
1995
+ running = undefined;
1996
+ setImmediate;
1997
+ constructor(setImmediateFn = setImmediate) {
1998
+ this.setImmediate = setImmediateFn;
1999
+ }
2000
+ scheduleTask(task, priority) {
2001
+ this.tasks.scheduleTask(task, priority);
2002
+ if (this.running === undefined) {
2003
+ this.running = this.setImmediate(this.afterScheduled);
2004
+ }
2005
+ }
2006
+ afterScheduled = () => {
2007
+ this.running = undefined;
2008
+ this.runTasks();
2009
+ };
2010
+ runTasks() {
2011
+ const buckets = this.tasks.drain();
2012
+ for (let i = 0;i < buckets.length; i++) {
2013
+ const toRun = buckets[i][1];
2014
+ for (let j = 0;j < toRun.length; j++) {
2015
+ toRun[j]();
2016
+ }
2017
+ }
2018
+ }
2019
+ flush() {
2020
+ while (this.tasks.buckets.length > 0) {
2021
+ if (this.running !== undefined) {
2022
+ this.running();
2023
+ this.running = undefined;
2024
+ }
2025
+ this.runTasks();
2026
+ }
2027
+ }
2028
+ }
2029
+ var MaxOpsBeforeYield = /* @__PURE__ */ Reference("effect/Scheduler/MaxOpsBeforeYield", {
2030
+ fiberCached: true,
2031
+ defaultValue: () => 2048
2032
+ });
2033
+ var PreventSchedulerYield = /* @__PURE__ */ Reference("effect/Scheduler/PreventSchedulerYield", {
2034
+ fiberCached: true,
2035
+ defaultValue: () => false
2036
+ });
2037
+
2038
+ var ParentSpanKey = "effect/Tracer/ParentSpan";
2039
+ var TracerKey = "effect/Tracer";
2040
+
2041
+ var FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics";
2042
+
2043
+ var CurrentStackFrame = /* @__PURE__ */ Reference("effect/References/CurrentStackFrame", {
2044
+ fiberCached: true,
2045
+ defaultValue: constUndefined
2046
+ });
2047
+ var TracerEnabled = /* @__PURE__ */ Reference("effect/References/TracerEnabled", {
2048
+ fiberCached: true,
2049
+ defaultValue: constTrue
2050
+ });
2051
+ var CurrentLogAnnotations = /* @__PURE__ */ Reference("effect/References/CurrentLogAnnotations", {
2052
+ defaultValue: () => ({})
2053
+ });
2054
+ var CurrentLogLevel = /* @__PURE__ */ Reference("effect/References/CurrentLogLevel", {
2055
+ fiberCached: true,
2056
+ defaultValue: () => "Info"
2057
+ });
2058
+ var MinimumLogLevel = /* @__PURE__ */ Reference("effect/References/MinimumLogLevel", {
2059
+ fiberCached: true,
2060
+ defaultValue: () => "Info"
2061
+ });
2062
+ var UnhandledLogLevel = /* @__PURE__ */ Reference("effect/References/UnhandledLogLevel", {
2063
+ defaultValue: () => "Error"
2064
+ });
2065
+ var CurrentLogSpans = /* @__PURE__ */ Reference("effect/References/CurrentLogSpans", {
2066
+ defaultValue: () => []
2067
+ });
2068
+
2069
+ class Interrupt extends ReasonBase {
2070
+ constructor(fiberId, annotations = constEmptyAnnotations) {
2071
+ super("Interrupt", annotations, "Interrupted");
2072
+ this.fiberId = fiberId;
2073
+ }
2074
+ toString() {
2075
+ return `Interrupt(${this.fiberId})`;
2076
+ }
2077
+ toJSON() {
2078
+ return {
2079
+ _tag: "Interrupt",
2080
+ fiberId: this.fiberId
2081
+ };
2082
+ }
2083
+ [symbol2](that) {
2084
+ return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations;
2085
+ }
2086
+ [symbol]() {
2087
+ return string(`${this._tag}:${this.fiberId}`);
2088
+ }
2089
+ }
2090
+ var causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]);
2091
+ var hasFails = (self) => self.reasons.some(isFailReason);
2092
+ var findError = (self) => {
2093
+ for (let i = 0;i < self.reasons.length; i++) {
2094
+ const reason = self.reasons[i];
2095
+ if (reason._tag === "Fail") {
2096
+ return succeed2(reason.error);
2097
+ }
2098
+ }
2099
+ return fail2(self);
2100
+ };
2101
+ var hasDies = (self) => self.reasons.some(isDieReason);
2102
+ var causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self;
2103
+ var findRecoverableError = (self) => hasDies(self) ? fail2(causeElectDefects(self)) : findError(self);
2104
+ var hasInterrupts = (self) => self.reasons.some(isInterruptReason);
2105
+ var causeSquash = (self) => {
2106
+ let die;
2107
+ for (const reason of self.reasons) {
2108
+ if (reason._tag === "Fail")
2109
+ return reason.error;
2110
+ if (reason._tag === "Die")
2111
+ die ??= reason;
2112
+ }
2113
+ if (die !== undefined)
2114
+ return die.defect;
2115
+ if (self.reasons.length > 0)
2116
+ return new globalThis.Error("All fibers interrupted without error");
2117
+ return new globalThis.Error("Empty cause");
2118
+ };
2119
+ var causePrettyErrors = (self, options) => {
2120
+ const errors = [];
2121
+ const interrupts = [];
2122
+ if (self.reasons.length === 0)
2123
+ return errors;
2124
+ const prevStackLimit = getStackTraceLimit();
2125
+ if (prevStackLimit !== 0)
2126
+ setStackTraceLimit(1);
2127
+ try {
2128
+ for (const failure of self.reasons) {
2129
+ if (failure._tag === "Interrupt") {
2130
+ interrupts.push(failure);
2131
+ continue;
2132
+ }
2133
+ errors.push(causePrettyError(failure._tag === "Die" ? failure.defect : failure.error, failure.annotations, options));
2134
+ }
2135
+ if (errors.length === 0) {
2136
+ const cause = new Error("The fiber was interrupted by:");
2137
+ cause.name = "InterruptCause";
2138
+ cause.stack = interruptCauseStack(cause, interrupts);
2139
+ const error = new globalThis.Error("All fibers interrupted without error", {
2140
+ cause
2141
+ });
2142
+ error.name = "InterruptError";
2143
+ error.stack = `${error.name}: ${error.message}`;
2144
+ errors.push(causePrettyError(error, interrupts[0].annotations, options));
2145
+ }
2146
+ } finally {
2147
+ if (prevStackLimit !== 0)
2148
+ setStackTraceLimit(prevStackLimit);
2149
+ }
2150
+ return errors;
2151
+ };
2152
+ var causePrettyError = (original, annotations, options, seen = new Set) => {
2153
+ const kind = typeof original;
2154
+ let error;
2155
+ if (original && kind === "object") {
2156
+ seen.add(original);
2157
+ const cause = original.cause;
2158
+ error = new globalThis.Error(causePrettyMessage(original), {
2159
+ cause: cause !== undefined && !seen.has(cause) ? causePrettyError(cause, undefined, undefined, seen) : undefined
2160
+ });
2161
+ if (typeof original.name === "string") {
2162
+ error.name = original.name;
2163
+ }
2164
+ if (typeof original.stack === "string") {
2165
+ error.stack = cleanErrorStack(original.stack, error, annotations);
2166
+ } else {
2167
+ const stack = `${error.name}: ${error.message}`;
2168
+ error.stack = annotations ? addStackAnnotations(stack, annotations) : stack;
2169
+ }
2170
+ if (options?.includeCauseInStack) {
2171
+ error.stack = renderPrettyError(error);
2172
+ }
2173
+ for (const key of Object.keys(original)) {
2174
+ if (!(key in error)) {
2175
+ error[key] = original[key];
2176
+ }
2177
+ }
2178
+ } else {
2179
+ error = new globalThis.Error(!original ? `Unknown error: ${original}` : kind === "string" ? original : formatJson(original));
2180
+ const stack = `${error.name}: ${error.message}`;
2181
+ error.stack = annotations ? addStackAnnotations(stack, annotations) : stack;
2182
+ }
2183
+ return error;
2184
+ };
2185
+ var causePrettyMessage = (u) => {
2186
+ if (typeof u.message === "string") {
2187
+ return u.message;
2188
+ } else if (typeof u.toString === "function" && u.toString !== Object.prototype.toString && u.toString !== Array.prototype.toString) {
2189
+ try {
2190
+ return u.toString();
2191
+ } catch {}
2192
+ }
2193
+ return formatJson(u);
2194
+ };
2195
+ var locationRegExp = /\((.*)\)/g;
2196
+ var cleanErrorStack = (stack, error, annotations) => {
2197
+ const message = `${error.name}: ${error.message}`;
2198
+ const lines = (stack.startsWith(message) ? stack.slice(message.length) : stack).split(`
2199
+ `);
2200
+ const out = [message];
2201
+ for (let i = 1;i < lines.length; i++) {
2202
+ if (/Generator\.next|~effect\/(?:Effect|Utils)/.test(lines[i])) {
2203
+ break;
2204
+ }
2205
+ out.push(lines[i]);
2206
+ }
2207
+ return annotations ? addStackAnnotations(out.join(`
2208
+ `), annotations) : out.join(`
2209
+ `);
2210
+ };
2211
+ var addStackAnnotations = (stack, annotations) => {
2212
+ const frame = annotations?.get(StackTraceKey.key);
2213
+ if (frame) {
2214
+ stack = `${stack}
2215
+ ${currentStackTrace(frame)}`;
2216
+ }
2217
+ return stack;
2218
+ };
2219
+ var interruptCauseStack = (error, interrupts) => {
2220
+ const out = [`${error.name}: ${error.message}`];
2221
+ for (const current of interrupts) {
2222
+ const fiberId = current.fiberId !== undefined ? `#${current.fiberId}` : "unknown";
2223
+ const frame = current.annotations.get(InterruptorStackTrace.key);
2224
+ out.push(` at fiber (${fiberId})`);
2225
+ if (frame)
2226
+ out.push(currentStackTrace(frame));
2227
+ }
2228
+ return out.join(`
2229
+ `);
2230
+ };
2231
+ var currentStackTrace = (frame) => {
2232
+ const out = [];
2233
+ let current = frame;
2234
+ let i = 0;
2235
+ while (current && i < 10) {
2236
+ const stack = current.stack();
2237
+ if (stack) {
2238
+ const locationMatchAll = stack.matchAll(locationRegExp);
2239
+ let match = false;
2240
+ for (const [, location] of locationMatchAll) {
2241
+ match = true;
2242
+ out.push(` at ${current.name} (${location})`);
2243
+ }
2244
+ if (!match) {
2245
+ out.push(` at ${current.name} (${stack.replace(/^at /, "")})`);
2246
+ }
2247
+ } else {
2248
+ out.push(` at ${current.name}`);
2249
+ }
2250
+ current = current.parent;
2251
+ i++;
2252
+ }
2253
+ return out.join(`
2254
+ `);
2255
+ };
2256
+ var causePretty = (cause) => causePrettyErrors(cause).map(renderPrettyError).join(`
2257
+ `);
2258
+ var renderPrettyError = (e) => e.cause ? `${e.stack} {
2259
+ ${renderErrorCause(e.cause, " ")}
2260
+ }` : e.stack;
2261
+ var renderErrorCause = (cause, prefix) => {
2262
+ const lines = cause.stack.split(`
2263
+ `);
2264
+ let stack = `${prefix}[cause]: ${lines[0]}`;
2265
+ for (let i = 1, len = lines.length;i < len; i++) {
2266
+ stack += `
2267
+ ${prefix}${lines[i]}`;
2268
+ }
2269
+ if (cause.cause) {
2270
+ stack += ` {
2271
+ ${renderErrorCause(cause.cause, `${prefix} `)}
2272
+ ${prefix}}`;
2273
+ }
2274
+ return stack;
2275
+ };
2276
+ var FiberTypeId = "~effect/Fiber";
2277
+ var fiberVariance = {
2278
+ _A: identity,
2279
+ _E: identity
2280
+ };
2281
+ var fiberIdStore = {
2282
+ id: 0
2283
+ };
2284
+ var AsyncResource = /* @__PURE__ */ (() => {
2285
+ try {
2286
+ return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource;
2287
+ } catch {
2288
+ return;
2289
+ }
2290
+ })();
2291
+ var captureAsyncContext = () => AsyncResource === undefined ? undefined : new AsyncResource("effect/Fiber");
2292
+ class FiberImpl {
2293
+ constructor(context, interruptible = true) {
2294
+ this.setContext(context);
2295
+ this.id = ++fiberIdStore.id;
2296
+ this.currentOpCount = 0;
2297
+ this.interruptible = interruptible;
2298
+ this._stack = [];
2299
+ this._observers = undefined;
2300
+ this._exit = undefined;
2301
+ this._children = undefined;
2302
+ this._interruptedCause = undefined;
2303
+ this._yielded = undefined;
2304
+ this._autoYielded = false;
2305
+ this._running = false;
2306
+ this._deferredInterrupt = false;
2307
+ this._parent = undefined;
2308
+ this._asyncContext = undefined;
2309
+ this.cache.runtimeMetrics?.recordFiberStart(this.context);
2310
+ }
2311
+ get [FiberTypeId]() {
2312
+ return fiberVariance;
2313
+ }
2314
+ get currentDispatcher() {
2315
+ return this._dispatcher ??= this.cache.scheduler.makeDispatcher();
2316
+ }
2317
+ getRef(ref) {
2318
+ return get(this.context, ref);
2319
+ }
2320
+ addObserver(cb) {
2321
+ if (this._exit) {
2322
+ cb(this._exit);
2323
+ return constVoid;
2324
+ }
2325
+ if (this._observers === undefined) {
2326
+ this._observers = [cb];
2327
+ } else {
2328
+ this._observers.push(cb);
2329
+ }
2330
+ return () => this.removeObserver(cb);
2331
+ }
2332
+ removeObserver(cb) {
2333
+ if (this._exit || this._observers === undefined)
2334
+ return;
2335
+ const index = this._observers.indexOf(cb);
2336
+ if (index >= 0) {
2337
+ this._observers.splice(index, 1);
2338
+ }
2339
+ }
2340
+ interruptUnsafe(fiberId, annotations) {
2341
+ if (this._exit) {
2342
+ return;
2343
+ }
2344
+ let cause = causeInterrupt(fiberId);
2345
+ if (this.cache.stackFrame) {
2346
+ cause = causeAnnotate(cause, make2(StackTraceKey, this.cache.stackFrame));
2347
+ }
2348
+ if (annotations) {
2349
+ cause = causeAnnotate(cause, annotations);
2350
+ }
2351
+ this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause;
2352
+ if (this.interruptible) {
2353
+ if (this._running) {
2354
+ this._deferredInterrupt = true;
2355
+ } else {
2356
+ this.evaluate(failCause(this._interruptedCause));
2357
+ }
2358
+ }
2359
+ }
2360
+ pollUnsafe() {
2361
+ return this._exit;
2362
+ }
2363
+ evaluate(effect) {
2364
+ if (this._exit) {
2365
+ return;
2366
+ } else if (this._asyncContext !== undefined) {
2367
+ const asyncContext = this._asyncContext;
2368
+ this._asyncContext = undefined;
2369
+ try {
2370
+ return asyncContext.runInAsyncScope(this.evaluate, this, effect);
2371
+ } finally {
2372
+ asyncContext.emitDestroy();
2373
+ }
2374
+ } else if (this._yielded !== undefined) {
2375
+ const yielded = this._yielded;
2376
+ this._yielded = undefined;
2377
+ yielded();
2378
+ }
2379
+ const exit = this.runLoop(effect);
2380
+ if (exit === Yield) {
2381
+ this._asyncContext = captureAsyncContext();
2382
+ return;
2383
+ }
2384
+ const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this);
2385
+ if (interruptChildren !== undefined) {
2386
+ return this.evaluate(flatMap(interruptChildren, () => exit));
2387
+ }
2388
+ this._exit = exit;
2389
+ this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit);
2390
+ if (this._parent) {
2391
+ this._parent._children?.delete(this);
2392
+ this._parent = undefined;
2393
+ }
2394
+ if (this._observers !== undefined) {
2395
+ const observers = this._observers;
2396
+ this._observers = undefined;
2397
+ for (let i = 0;i < observers.length; i++) {
2398
+ observers[i](exit);
2399
+ }
2400
+ }
2401
+ this._stack.length = 0;
2402
+ this._children = undefined;
2403
+ this.context = empty();
2404
+ const cache = this.cache;
2405
+ if (cache.span !== undefined || cache.stackFrame !== undefined) {
2406
+ this.cache = {
2407
+ ...cache,
2408
+ span: undefined,
2409
+ stackFrame: undefined
2410
+ };
2411
+ }
2412
+ }
2413
+ runLoop(effect) {
2414
+ const prevFiber = globalThis[currentFiberTypeId];
2415
+ globalThis[currentFiberTypeId] = this;
2416
+ const prevRunning = this._running;
2417
+ this._running = true;
2418
+ let yielding = false;
2419
+ let resuming = this._autoYielded;
2420
+ this._autoYielded = false;
2421
+ let current = effect;
2422
+ this.currentOpCount = resuming ? 1 : 0;
2423
+ try {
2424
+ while (true) {
2425
+ try {
2426
+ if (this._deferredInterrupt) {
2427
+ this._deferredInterrupt = false;
2428
+ current = failCause(this._interruptedCause);
2429
+ }
2430
+ this.currentOpCount++;
2431
+ const cache = this.cache;
2432
+ if (!resuming && !yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) {
2433
+ yielding = true;
2434
+ current = this.yieldNow(current, 0, true);
2435
+ } else {
2436
+ resuming = false;
2437
+ current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this);
2438
+ }
2439
+ if (current === Yield) {
2440
+ const yielded = this._yielded;
2441
+ if (ExitTypeId in yielded) {
2442
+ this._deferredInterrupt = false;
2443
+ this._yielded = undefined;
2444
+ return yielded;
2445
+ } else if (this._deferredInterrupt) {
2446
+ this._yielded = undefined;
2447
+ yielded();
2448
+ continue;
2449
+ }
2450
+ return Yield;
2451
+ }
2452
+ } catch (error) {
2453
+ if (!hasProperty(current, evaluate)) {
2454
+ return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`);
2455
+ }
2456
+ current = exitDie(error);
2457
+ }
2458
+ }
2459
+ } finally {
2460
+ this._running = prevRunning;
2461
+ globalThis[currentFiberTypeId] = prevFiber;
2462
+ }
2463
+ }
2464
+ getCont(symbol) {
2465
+ if (this._deferredInterrupt) {
2466
+ this._deferredInterrupt = false;
2467
+ return deferredInterruptCont;
2468
+ }
2469
+ while (true) {
2470
+ const op = this._stack.pop();
2471
+ if (!op)
2472
+ return;
2473
+ const all = op[contAll];
2474
+ if (all !== undefined) {
2475
+ const cont = all.call(op, this);
2476
+ if (cont) {
2477
+ cont[symbol] = cont;
2478
+ return cont;
2479
+ }
2480
+ }
2481
+ if (op[symbol])
2482
+ return op;
2483
+ }
2484
+ }
2485
+ succeedWith(value) {
2486
+ if ((++this.currentOpCount & maxInlineSteps - 1) === 0) {
2487
+ return exitSucceed(value);
2488
+ }
2489
+ const cont = this.getCont(contA);
2490
+ return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value));
2491
+ }
2492
+ yieldWith(value) {
2493
+ this._yielded = value;
2494
+ return Yield;
2495
+ }
2496
+ yieldNow(effect, priority = 0, automatic = false) {
2497
+ let resumed = false;
2498
+ this.currentDispatcher.scheduleTask(() => {
2499
+ if (resumed)
2500
+ return;
2501
+ this._autoYielded = automatic;
2502
+ this.evaluate(effect);
2503
+ }, priority);
2504
+ return this.yieldWith(() => {
2505
+ resumed = true;
2506
+ });
2507
+ }
2508
+ children() {
2509
+ return this._children ??= new Set;
2510
+ }
2511
+ pipe() {
2512
+ return pipeArguments(this, arguments);
2513
+ }
2514
+ setContext(context) {
2515
+ const previous = this.context;
2516
+ this.context = context;
2517
+ if (previous !== undefined && hasSameCache(previous, context))
2518
+ return;
2519
+ const root = context.cacheRoot;
2520
+ const cache = root._fiberCache ??= makeFiberContextCache(context);
2521
+ if (this.cache?.scheduler !== cache.scheduler) {
2522
+ this._dispatcher = undefined;
2523
+ }
2524
+ this.cache = cache;
2525
+ }
2526
+ get currentSpanLocal() {
2527
+ const span = this.cache.span;
2528
+ return span?._tag === "Span" ? span : undefined;
2529
+ }
2530
+ }
2531
+ var makeFiberContextCache = (context) => {
2532
+ const currentTracer = getOrUndefinedUnsafe(context, TracerKey);
2533
+ return {
2534
+ scheduler: get(context, Scheduler),
2535
+ tracer: currentTracer,
2536
+ tracerContext: currentTracer ? currentTracer["context"] : undefined,
2537
+ tracerEnabled: get(context, TracerEnabled),
2538
+ span: getOrUndefinedUnsafe(context, ParentSpanKey),
2539
+ logLevel: get(context, CurrentLogLevel),
2540
+ minimumLogLevel: get(context, MinimumLogLevel),
2541
+ stackFrame: get(context, CurrentStackFrame),
2542
+ runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey),
2543
+ maxOpsBeforeYield: get(context, MaxOpsBeforeYield),
2544
+ preventYield: get(context, PreventSchedulerYield)
2545
+ };
2546
+ };
2547
+ var deferredInterruptCont = {
2548
+ [contA](_value, fiber) {
2549
+ return failCause(fiber._interruptedCause);
2550
+ },
2551
+ [contE](_cause, fiber) {
2552
+ return failCause(fiber._interruptedCause);
2553
+ }
2554
+ };
2555
+ var maxInlineSteps = 32;
2556
+ var fiberMiddleware = {
2557
+ interruptChildren: undefined
2558
+ };
2559
+ var fiberStackAnnotations = (fiber) => {
2560
+ if (!fiber.cache.stackFrame)
2561
+ return;
2562
+ const annotations = new Map;
2563
+ annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame);
2564
+ return makeUnsafe(annotations);
2565
+ };
2566
+ var fiberAwaitAll = (self) => callback((resume) => {
2567
+ const iter = self[Symbol.iterator]();
2568
+ const exits = [];
2569
+ let cancel = undefined;
2570
+ function loop() {
2571
+ let result = iter.next();
2572
+ while (!result.done) {
2573
+ if (result.value._exit) {
2574
+ exits.push(result.value._exit);
2575
+ result = iter.next();
2576
+ continue;
2577
+ }
2578
+ cancel = result.value.addObserver((exit) => {
2579
+ exits.push(exit);
2580
+ loop();
2581
+ });
2582
+ return;
2583
+ }
2584
+ resume(succeed3(exits));
2585
+ }
2586
+ loop();
2587
+ return sync(() => cancel?.());
2588
+ });
2589
+ var fiberInterruptAll = (fibers) => withFiber((parent) => {
2590
+ const annotations = fiberStackAnnotations(parent);
2591
+ let fiberArr = empty2();
2592
+ for (const fiber of fibers) {
2593
+ fiber.interruptUnsafe(parent.id, annotations);
2594
+ fiberArr.push(fiber);
2595
+ }
2596
+ return asVoid(fiberAwaitAll(fiberArr));
2597
+ });
2598
+ var succeed3 = exitSucceed;
2599
+ var failCause = exitFailCause;
2600
+ var fail3 = exitFail;
2601
+ var sync = /* @__PURE__ */ makePrimitive({
2602
+ op: "Sync",
2603
+ [evaluate](fiber) {
2604
+ const thunk = this[args];
2605
+ const value = thunk();
2606
+ const cont = fiber.getCont(contA);
2607
+ return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value));
2608
+ }
2609
+ });
2610
+ var suspend = /* @__PURE__ */ makePrimitive({
2611
+ op: "Suspend",
2612
+ [evaluate](_fiber) {
2613
+ const thunk = this[args];
2614
+ return thunk();
2615
+ }
2616
+ });
2617
+ var yieldNowWith = /* @__PURE__ */ makePrimitive({
2618
+ op: "Yield",
2619
+ [evaluate](fiber) {
2620
+ return fiber.yieldNow(exitVoid, this[args] ?? 0);
2621
+ }
2622
+ });
2623
+ var yieldNow = /* @__PURE__ */ yieldNowWith(0);
2624
+ var die = (defect) => exitDie(defect);
2625
+ var void_ = /* @__PURE__ */ succeed3(undefined);
2626
+ var tryPromise = (options) => {
2627
+ const f = typeof options === "function" ? options : options.try;
2628
+ const catcher = typeof options === "function" ? (cause) => new UnknownError(cause, "An error occurred in Effect.tryPromise") : options.catch;
2629
+ return callbackOptions(function(resume, signal) {
2630
+ const failWithCatch = (cause) => suspend(() => {
2631
+ try {
2632
+ return fail3(internalCall(() => catcher(cause)));
2633
+ } catch (err) {
2634
+ return die(err);
2635
+ }
2636
+ });
2637
+ try {
2638
+ f(signal).then((a) => resume(succeed3(a)), (e) => resume(failWithCatch(e)));
2639
+ } catch (err) {
2640
+ resume(failWithCatch(err));
2641
+ }
2642
+ }, f.length !== 0);
2643
+ };
2644
+ var callbackOptions = /* @__PURE__ */ function() {
2645
+ const Proto = /* @__PURE__ */ makePrimitiveProto({
2646
+ op: "Async",
2647
+ [evaluate](fiber) {
2648
+ let resumed = false;
2649
+ let yielded = false;
2650
+ const controller = this.withSignal ? new AbortController : undefined;
2651
+ const onCancel = this.register.call(fiber.cache.scheduler, (effect) => {
2652
+ if (resumed)
2653
+ return;
2654
+ resumed = true;
2655
+ if (yielded) {
2656
+ fiber.evaluate(effect);
2657
+ } else {
2658
+ yielded = effect;
2659
+ }
2660
+ }, controller?.signal);
2661
+ if (yielded !== false)
2662
+ return yielded;
2663
+ yielded = true;
2664
+ fiber.yieldWith(() => {
2665
+ resumed = true;
2666
+ });
2667
+ if (controller === undefined && onCancel === undefined) {
2668
+ return Yield;
2669
+ }
2670
+ fiber._stack.push(asyncFinalizer(() => {
2671
+ resumed = true;
2672
+ controller?.abort();
2673
+ return onCancel ?? exitVoid;
2674
+ }));
2675
+ return Yield;
2676
+ }
2677
+ });
2678
+ const AsyncImpl = function(register, withSignal) {
2679
+ this.register = register;
2680
+ this.withSignal = withSignal;
2681
+ };
2682
+ AsyncImpl.prototype = Proto;
2683
+ return function(register, withSignal) {
2684
+ return new AsyncImpl(register, withSignal);
2685
+ };
2686
+ }();
2687
+ var asyncFinalizer = /* @__PURE__ */ makePrimitive({
2688
+ op: "AsyncFinalizer",
2689
+ [contAll](fiber) {
2690
+ if (fiber.interruptible) {
2691
+ fiber.interruptible = false;
2692
+ fiber._stack.push(setInterruptibleTrue);
2693
+ }
2694
+ },
2695
+ [contE](cause, _fiber) {
2696
+ return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause);
2697
+ }
2698
+ });
2699
+ var callback = (register) => callbackOptions(register, register.length >= 2);
2700
+ var never = /* @__PURE__ */ callback(constVoid);
2701
+ var as = /* @__PURE__ */ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed3(value)));
2702
+ var evaluateCont = function(fiber) {
2703
+ fiber._stack.push(this);
2704
+ return this[args];
2705
+ };
2706
+ var OnSuccessProto = /* @__PURE__ */ makePrimitiveProto({
2707
+ op: "OnSuccess",
2708
+ [evaluate]: evaluateCont
2709
+ });
2710
+ var ContImpl = function(self, cont, payload) {
2711
+ this[args] = self;
2712
+ this[contA] = cont;
2713
+ this.payload = payload;
2714
+ };
2715
+ ContImpl.prototype = OnSuccessProto;
2716
+ var returnPayload = function() {
2717
+ return this.payload;
2718
+ };
2719
+ var continuationMarksStack = /* @__PURE__ */ (() => {
2720
+ const limit = /* @__PURE__ */ getStackTraceLimit();
2721
+ if (limit === 0)
2722
+ return false;
2723
+ const marker = "~effect/Effect/stackProbe";
2724
+ const probe = {
2725
+ [marker]: function stackProbe() {
2726
+ return new Error;
2727
+ }
2728
+ };
2729
+ setStackTraceLimit(1);
2730
+ const error = /* @__PURE__ */ probe[marker]();
2731
+ setStackTraceLimit(limit);
2732
+ return error.stack?.includes("[as " + marker + "]") === true;
2733
+ })();
2734
+ var mapCont = function(value, fiber) {
2735
+ const f = this.payload;
2736
+ return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value)));
2737
+ };
2738
+ var andThenCont = function(value) {
2739
+ const f = this.payload;
2740
+ return f(value);
2741
+ };
2742
+ var asSome = (self) => map(self, some2);
2743
+ var andThen = /* @__PURE__ */ dual(2, (self, f) => new ContImpl(self, isEffect(f) ? returnPayload : andThenCont, f));
2744
+ var asVoid = (self) => new ContImpl(self, returnPayload, exitVoid);
2745
+ var raceAllFirst = (all, options) => withFiber((parent) => {
2746
+ const fibers = new Set;
2747
+ onExitUnsafe(parent, () => fibers.size === 0 ? undefined : fiberInterruptAll(fibers));
2748
+ return callback((resume) => {
2749
+ let done = false;
2750
+ let i = 0;
2751
+ for (const effect of all) {
2752
+ if (done)
2753
+ break;
2754
+ const index = i++;
2755
+ const fiber = forkUnsafe(parent, effect, true, true, false);
2756
+ fibers.add(fiber);
2757
+ fiber.addObserver((exit) => {
2758
+ fibers.delete(fiber);
2759
+ const isWinner = !done;
2760
+ done = true;
2761
+ resume(exit);
2762
+ if (isWinner) {
2763
+ interruptRaceLosers(fibers, parent);
2764
+ options?.onWinner?.({
2765
+ fiber,
2766
+ index,
2767
+ parentFiber: parent
2768
+ });
2769
+ }
2770
+ });
2771
+ }
2772
+ });
2773
+ });
2774
+ var interruptRaceLosers = (fibers, parent) => {
2775
+ const annotations = fiberStackAnnotations(parent);
2776
+ for (const fiber of fibers) {
2777
+ fiber.interruptUnsafe(parent.id, annotations);
2778
+ }
2779
+ };
2780
+ var raceFirst = /* @__PURE__ */ dual((args) => isEffect(args[1]), (self, that, options) => raceAllFirst([self, that], options));
2781
+ var flatMap = /* @__PURE__ */ dual(2, (self, f) => new ContImpl(self, andThenCont, f));
2782
+ var map = /* @__PURE__ */ dual(2, (self, f) => new ContImpl(self, mapCont, f));
2783
+ var exitIsSuccess = (self) => self._tag === "Success";
2784
+ var exitVoid = /* @__PURE__ */ exitSucceed(undefined);
2785
+ var catchCause = /* @__PURE__ */ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f));
2786
+ var OnFailureProto = /* @__PURE__ */ makePrimitiveProto({
2787
+ op: "OnFailure",
2788
+ [evaluate]: evaluateCont
2789
+ });
2790
+ var OnFailureImpl = function(self, f) {
2791
+ this[args] = self;
2792
+ this[contE] = f;
2793
+ };
2794
+ OnFailureImpl.prototype = OnFailureProto;
2795
+ var catchCauseFilter = /* @__PURE__ */ dual(3, (self, filter, f) => catchCause(self, (cause) => {
2796
+ const eb = filter(cause);
2797
+ return isFailure2(eb) ? failCause(eb.failure) : f(eb.success, cause);
2798
+ }));
2799
+ var catch_ = /* @__PURE__ */ dual(2, (self, f) => catchCauseFilter(self, findRecoverableError, (e) => f(e)));
2800
+ var ignoreCauseLogger = (log) => log === "Unhandled" ? (...message) => withFiber((fiber) => {
2801
+ const level = fiber.getRef(UnhandledLogLevel);
2802
+ return level === undefined ? void_ : logWithLevel(level)(...message);
2803
+ }) : logWithLevel(log === true ? undefined : log);
2804
+ var ignore = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self, options) => {
2805
+ if (!options?.log) {
2806
+ return matchEffect(self, {
2807
+ onFailure: (_) => void_,
2808
+ onSuccess: (_) => void_
2809
+ });
2810
+ }
2811
+ const logEffect = ignoreCauseLogger(options.log);
2812
+ return matchCauseEffect(self, {
2813
+ onFailure(cause) {
2814
+ const error = findRecoverableError(cause);
2815
+ return isFailure2(error) ? failCause(error.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause);
2816
+ },
2817
+ onSuccess: (_) => void_
2818
+ });
2819
+ });
2820
+ var matchCauseEffect = /* @__PURE__ */ dual(2, (self, options) => new OnSuccessAndFailureImpl(self, options.onSuccess.length !== 1 ? (a) => options.onSuccess(a) : options.onSuccess, options.onFailure.length !== 1 ? (cause) => options.onFailure(cause) : options.onFailure));
2821
+ var OnSuccessAndFailureProto = /* @__PURE__ */ makePrimitiveProto({
2822
+ op: "OnSuccessAndFailure",
2823
+ [evaluate]: evaluateCont
2824
+ });
2825
+ var OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) {
2826
+ this[args] = self;
2827
+ this[contA] = onSuccess;
2828
+ this[contE] = onFailure;
2829
+ };
2830
+ OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto;
2831
+ var matchSuccess = function(value, fiber) {
2832
+ const handlers = this.payload;
2833
+ return fiber.succeedWith(continuationMarksStack ? handlers.onSuccess(value) : internalCall(() => handlers.onSuccess(value)));
2834
+ };
2835
+ var makeMatch = (op, onFailure) => {
2836
+ const Proto = makePrimitiveProto({
2837
+ op,
2838
+ [evaluate]: evaluateCont,
2839
+ [contA]: matchSuccess,
2840
+ [contE]: onFailure
2841
+ });
2842
+ const MatchImpl = function(self, handlers) {
2843
+ this[args] = self;
2844
+ this.payload = handlers;
2845
+ };
2846
+ MatchImpl.prototype = Proto;
2847
+ return MatchImpl;
2848
+ };
2849
+ var MatchImpl = /* @__PURE__ */ makeMatch("Match", function(cause, fiber) {
2850
+ const error = findRecoverableError(cause);
2851
+ if (isFailure2(error))
2852
+ return failCause(error.failure);
2853
+ const handlers = this.payload;
2854
+ return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(error.success) : internalCall(() => handlers.onFailure(error.success)));
2855
+ });
2856
+ var matchEffect = /* @__PURE__ */ dual(2, (self, options) => matchCauseEffect(self, {
2857
+ onFailure: (cause) => {
2858
+ const error = findRecoverableError(cause);
2859
+ return isFailure2(error) ? failCause(error.failure) : options.onFailure(error.success);
2860
+ },
2861
+ onSuccess: options.onSuccess
2862
+ }));
2863
+ var match3 = /* @__PURE__ */ dual(2, (self, options) => new MatchImpl(self, options));
2864
+ var exitPrimitive = /* @__PURE__ */ makePrimitive({
2865
+ op: "Exit",
2866
+ [evaluate](fiber) {
2867
+ fiber._stack.push(this);
2868
+ return this[args];
2869
+ },
2870
+ [contA](value, fiber, exit) {
2871
+ return fiber.succeedWith(exit ?? exitSucceed(value));
2872
+ },
2873
+ [contE](cause, fiber, exit) {
2874
+ return fiber.succeedWith(exit ?? exitFailCause(cause));
2875
+ }
2876
+ });
2877
+ var timeoutOrElse = /* @__PURE__ */ dual(2, (self, options) => flatMap(timeoutOption(self, options.duration), (option) => isNone2(option) ? options.orElse() : succeed3(option.value)));
2878
+ var timeoutErrorFromDuration = (duration) => new TimeoutError(`Operation timed out after '${format2(duration)}'`);
2879
+ var timeout = /* @__PURE__ */ dual(2, (self, duration) => {
2880
+ const decoded = fromInputUnsafe(duration);
2881
+ return timeoutOrElse(self, {
2882
+ duration: decoded,
2883
+ orElse: () => fail3(timeoutErrorFromDuration(decoded))
2884
+ });
2885
+ });
2886
+ var timeoutOption = /* @__PURE__ */ dual(2, (self, duration) => raceFirst(asSome(self), as(sleep(duration), none2())));
2887
+ var combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause))));
2888
+ var OnExitImpl = /* @__PURE__ */ function() {
2889
+ const Proto = /* @__PURE__ */ makePrimitiveProto({
2890
+ op: "OnExit",
2891
+ [evaluate](fiber) {
2892
+ fiber._stack.push(this);
2893
+ return this.effect;
2894
+ },
2895
+ [contAll](fiber) {
2896
+ if (fiber.interruptible && this.interruptible !== true) {
2897
+ fiber._stack.push(setInterruptibleTrue);
2898
+ fiber.interruptible = false;
2899
+ }
2900
+ },
2901
+ [contA](value, _, exit) {
2902
+ exit ??= exitSucceed(value);
2903
+ let eff;
2904
+ try {
2905
+ eff = this.onExit(exit);
2906
+ } catch (defect) {
2907
+ eff = exitDie(defect);
2908
+ }
2909
+ return eff ? flatMap(eff, (_) => exit) : exit;
2910
+ },
2911
+ [contE](cause, _, exit) {
2912
+ exit ??= exitFailCause(cause);
2913
+ let eff;
2914
+ try {
2915
+ eff = this.onExit(exit);
2916
+ } catch (defect) {
2917
+ eff = exitDie(defect);
2918
+ }
2919
+ return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit;
2920
+ }
2921
+ });
2922
+ const OnExitImpl = function(effect, onExit, interruptible) {
2923
+ this.effect = effect;
2924
+ this.onExit = onExit;
2925
+ this.interruptible = interruptible;
2926
+ };
2927
+ OnExitImpl.prototype = Proto;
2928
+ return OnExitImpl;
2929
+ }();
2930
+ var onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible);
2931
+ var onExitUnsafe = (fiber, f) => {
2932
+ fiber._stack.push(new OnExitImpl(undefined, f, undefined));
2933
+ };
2934
+ var acquireUseRelease = (acquire, use, release) => uninterruptibleMask((restore) => flatMap(acquire, (a) => onExitPrimitive(suspend(() => restore(use(a))), (exit) => release(a, exit), true)));
2935
+ var setInterruptible = /* @__PURE__ */ makePrimitive({
2936
+ op: "SetInterruptible",
2937
+ [contAll](fiber) {
2938
+ fiber.interruptible = this[args];
2939
+ if (fiber._interruptedCause && fiber.interruptible) {
2940
+ return () => failCause(fiber._interruptedCause);
2941
+ }
2942
+ }
2943
+ });
2944
+ var setInterruptibleTrue = /* @__PURE__ */ setInterruptible(true);
2945
+ var setInterruptibleFalse = /* @__PURE__ */ setInterruptible(false);
2946
+ var setFiberInterruptible = (fiber) => {
2947
+ fiber.interruptible = true;
2948
+ fiber._stack.push(setInterruptibleFalse);
2949
+ if (fiber._interruptedCause)
2950
+ return failCause(fiber._interruptedCause);
2951
+ };
2952
+ var interruptible = (self) => withFiber((fiber) => {
2953
+ if (fiber.interruptible)
2954
+ return self;
2955
+ return setFiberInterruptible(fiber) ?? self;
2956
+ });
2957
+ var uninterruptibleMask = (f) => withFiber((fiber) => {
2958
+ if (!fiber.interruptible)
2959
+ return f(identity);
2960
+ fiber.interruptible = false;
2961
+ fiber._stack.push(setInterruptibleTrue);
2962
+ return f(interruptible);
2963
+ });
2964
+ var whileLoop = /* @__PURE__ */ makePrimitive({
2965
+ op: "While",
2966
+ [contA](value, fiber) {
2967
+ this[args].step(value);
2968
+ if (this[args].while()) {
2969
+ fiber._stack.push(this);
2970
+ return this[args].body();
2971
+ }
2972
+ return exitVoid;
2973
+ },
2974
+ [evaluate](fiber) {
2975
+ if (this[args].while()) {
2976
+ fiber._stack.push(this);
2977
+ return this[args].body();
2978
+ }
2979
+ return exitVoid;
2980
+ }
2981
+ });
2982
+ var forkUnsafe = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => {
2983
+ const parentRuntime = parent;
2984
+ const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible;
2985
+ const child = new FiberImpl(parentRuntime.context, interruptible);
2986
+ if (!daemon) {
2987
+ parentRuntime.children().add(child);
2988
+ child._parent = parentRuntime;
2989
+ }
2990
+ if (immediate) {
2991
+ child.evaluate(effect);
2992
+ } else {
2993
+ child._asyncContext = captureAsyncContext();
2994
+ parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0);
2995
+ }
2996
+ return child;
2997
+ };
2998
+ var runForkWith = (context) => (effect, options) => {
2999
+ const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true);
3000
+ fiber.evaluate(effect);
3001
+ if (fiber._exit)
3002
+ return fiber;
3003
+ if (options?.signal) {
3004
+ if (options.signal.aborted) {
3005
+ fiber.interruptUnsafe();
3006
+ } else {
3007
+ const abort = () => fiber.interruptUnsafe();
3008
+ options.signal.addEventListener("abort", abort, {
3009
+ once: true
3010
+ });
3011
+ fiber.addObserver(() => options.signal.removeEventListener("abort", abort));
3012
+ }
3013
+ }
3014
+ if (options?.onFiberStart) {
3015
+ options.onFiberStart(fiber);
3016
+ }
3017
+ return fiber;
3018
+ };
3019
+ var runFork = /* @__PURE__ */ runForkWith(/* @__PURE__ */ empty());
3020
+ var runPromiseExitWith = (context) => {
3021
+ const runFork = runForkWith(context);
3022
+ return (effect, options) => {
3023
+ const fiber = runFork(effect, options);
3024
+ return new Promise((resolve) => {
3025
+ fiber.addObserver((exit) => resolve(exit));
3026
+ });
3027
+ };
3028
+ };
3029
+ var runPromiseWith = (context) => {
3030
+ const runPromiseExit = runPromiseExitWith(context);
3031
+ return (effect, options) => runPromiseExit(effect, options).then((exit) => {
3032
+ if (exit._tag === "Failure") {
3033
+ throw causeSquash(exit.cause);
3034
+ }
3035
+ return exit.value;
3036
+ });
3037
+ };
3038
+ var runPromise = /* @__PURE__ */ runPromiseWith(/* @__PURE__ */ empty());
3039
+ var ClockRef = /* @__PURE__ */ Reference("effect/Clock", {
3040
+ defaultValue: () => new ClockImpl
3041
+ });
3042
+ var MAX_TIMER_MILLIS = 2 ** 31 - 1;
3043
+
3044
+ class ClockImpl {
3045
+ currentTimeMillisUnsafe() {
3046
+ return Date.now();
3047
+ }
3048
+ currentTimeMillis = /* @__PURE__ */ sync(() => this.currentTimeMillisUnsafe());
3049
+ currentTimeNanosUnsafe() {
3050
+ return wallTimeNanos();
3051
+ }
3052
+ currentTimeNanos = /* @__PURE__ */ sync(() => this.currentTimeNanosUnsafe());
3053
+ monotonicTimeNanosUnsafe() {
3054
+ return monotonicNowNanos();
3055
+ }
3056
+ monotonicTimeNanos = /* @__PURE__ */ sync(() => this.monotonicTimeNanosUnsafe());
3057
+ sleep(duration) {
3058
+ return this.sleepMillis(toMillis(duration));
3059
+ }
3060
+ sleepMillis(millis) {
3061
+ if (millis <= 0)
3062
+ return yieldNow;
3063
+ else if (!Number.isFinite(millis))
3064
+ return never;
3065
+ return callback((resume) => {
3066
+ const continuation = millis > MAX_TIMER_MILLIS ? this.sleepMillis(millis - MAX_TIMER_MILLIS) : void_;
3067
+ const handle = setTimeout(() => resume(continuation), Math.min(millis, MAX_TIMER_MILLIS));
3068
+ return sync(() => clearTimeout(handle));
3069
+ });
3070
+ }
3071
+ }
3072
+ var nanosPerMilli = /* @__PURE__ */ BigInt(1e6);
3073
+ var monotonicNowNanos = /* @__PURE__ */ function() {
3074
+ const processHrtime = globalThis.process?.hrtime;
3075
+ if (typeof processHrtime?.bigint === "function") {
3076
+ return () => processHrtime.bigint();
3077
+ }
3078
+ if (typeof performance !== "undefined" && typeof performance.now === "function") {
3079
+ return () => BigInt(Math.round(performance.now() * 1e6));
3080
+ }
3081
+ let previous = /* @__PURE__ */ BigInt(0);
3082
+ return () => {
3083
+ const current = BigInt(Date.now()) * nanosPerMilli;
3084
+ if (current > previous) {
3085
+ previous = current;
3086
+ }
3087
+ return previous;
3088
+ };
3089
+ }();
3090
+ var wallTimeNanos = /* @__PURE__ */ function() {
3091
+ const reanchorThresholdNanos = /* @__PURE__ */ BigInt(1e9);
3092
+ let origin;
3093
+ return () => {
3094
+ const monotonic = monotonicNowNanos();
3095
+ const wall = BigInt(Date.now()) * nanosPerMilli;
3096
+ if (origin === undefined) {
3097
+ origin = wall - monotonic;
3098
+ } else {
3099
+ const projected = origin + monotonic;
3100
+ const skew = wall > projected ? wall - projected : projected - wall;
3101
+ if (skew > reanchorThresholdNanos) {
3102
+ origin = wall - monotonic;
3103
+ }
3104
+ }
3105
+ return origin + monotonic;
3106
+ };
3107
+ }();
3108
+ var clockWith = (f) => withFiber((fiber) => f(fiber.getRef(ClockRef)));
3109
+ var sleep = (duration) => clockWith((clock) => clock.sleep(fromInputUnsafe(duration)));
3110
+ var TimeoutErrorTypeId = "~effect/Cause/TimeoutError";
3111
+ class TimeoutError extends (/* @__PURE__ */ TaggedError("TimeoutError")) {
3112
+ [TimeoutErrorTypeId] = TimeoutErrorTypeId;
3113
+ constructor(message) {
3114
+ super({
3115
+ message
3116
+ });
3117
+ }
3118
+ }
3119
+ var UnknownErrorTypeId = "~effect/Cause/UnknownError";
3120
+ class UnknownError extends (/* @__PURE__ */ TaggedError("UnknownError")) {
3121
+ [UnknownErrorTypeId] = UnknownErrorTypeId;
3122
+ constructor(cause, message) {
3123
+ super({
3124
+ message,
3125
+ cause
3126
+ });
3127
+ }
3128
+ }
3129
+ var ConsoleRef = /* @__PURE__ */ Reference("effect/Console", {
3130
+ defaultValue: () => globalThis.console
3131
+ });
3132
+ var logLevelToOrder = (level) => {
3133
+ switch (level) {
3134
+ case "All":
3135
+ return Number.MIN_SAFE_INTEGER;
3136
+ case "Fatal":
3137
+ return 50000;
3138
+ case "Error":
3139
+ return 40000;
3140
+ case "Warn":
3141
+ return 30000;
3142
+ case "Info":
3143
+ return 20000;
3144
+ case "Debug":
3145
+ return 1e4;
3146
+ case "Trace":
3147
+ return 0;
3148
+ case "None":
3149
+ return Number.MAX_SAFE_INTEGER;
3150
+ }
3151
+ };
3152
+ var LogLevelOrder = /* @__PURE__ */ mapInput(Number2, logLevelToOrder);
3153
+ var isLogLevelGreaterThan = /* @__PURE__ */ isGreaterThan(LogLevelOrder);
3154
+ var CurrentLoggers = /* @__PURE__ */ Reference("effect/Logger/CurrentLoggers", {
3155
+ defaultValue: () => new Set([defaultLogger, tracerLogger])
3156
+ });
3157
+ var LogToStderr = /* @__PURE__ */ Reference("effect/Logger/LogToStderr", {
3158
+ defaultValue: constFalse
3159
+ });
3160
+ var LoggerTypeId = "~effect/Logger";
3161
+ var LoggerProto = {
3162
+ [LoggerTypeId]: {
3163
+ _Message: identity,
3164
+ _Output: identity
3165
+ },
3166
+ pipe() {
3167
+ return pipeArguments(this, arguments);
3168
+ }
3169
+ };
3170
+ var loggerMake = (log) => {
3171
+ const self = Object.create(LoggerProto);
3172
+ self.log = log;
3173
+ return self;
3174
+ };
3175
+ var formatLabel = (key) => key.replace(/[\s="]/g, "_");
3176
+ var formatLogSpan = (self, now) => {
3177
+ const label = formatLabel(self[0]);
3178
+ return `${label}=${now - self[1]}ms`;
3179
+ };
3180
+ var logWithLevel = (level) => (...message) => {
3181
+ let cause = undefined;
3182
+ for (let i = 0, len = message.length;i < len; i++) {
3183
+ const msg = message[i];
3184
+ if (isCause(msg)) {
3185
+ if (cause) {
3186
+ message.splice(i, 1);
3187
+ } else {
3188
+ message = message.slice(0, i).concat(message.slice(i + 1));
3189
+ }
3190
+ cause = cause ? causeFromReasons(cause.reasons.concat(msg.reasons)) : msg;
3191
+ i--;
3192
+ }
3193
+ }
3194
+ if (cause === undefined) {
3195
+ cause = causeEmpty;
3196
+ }
3197
+ return withFiber((fiber) => {
3198
+ const logLevel = level ?? fiber.cache.logLevel;
3199
+ if (isLogLevelGreaterThan(fiber.cache.minimumLogLevel, logLevel)) {
3200
+ return void_;
3201
+ }
3202
+ const clock = fiber.getRef(ClockRef);
3203
+ const loggers = fiber.getRef(CurrentLoggers);
3204
+ if (loggers.size > 0) {
3205
+ const date = new Date(clock.currentTimeMillisUnsafe());
3206
+ for (const logger of loggers) {
3207
+ logger.log({
3208
+ cause,
3209
+ fiber,
3210
+ date,
3211
+ logLevel,
3212
+ message
3213
+ });
3214
+ }
3215
+ }
3216
+ return void_;
3217
+ });
3218
+ };
3219
+ var colors = {
3220
+ bold: "1",
3221
+ red: "31",
3222
+ green: "32",
3223
+ yellow: "33",
3224
+ blue: "34",
3225
+ cyan: "36",
3226
+ white: "37",
3227
+ gray: "90",
3228
+ black: "30",
3229
+ bgBrightRed: "101"
3230
+ };
3231
+ var logLevelColors = {
3232
+ None: [],
3233
+ All: [],
3234
+ Trace: [colors.gray],
3235
+ Debug: [colors.blue],
3236
+ Info: [colors.green],
3237
+ Warn: [colors.yellow],
3238
+ Error: [colors.red],
3239
+ Fatal: [colors.bgBrightRed, colors.black]
3240
+ };
3241
+ var defaultDateFormat = (date) => `${date.getHours().toString().padStart(2, "0")}:${date.getMinutes().toString().padStart(2, "0")}:${date.getSeconds().toString().padStart(2, "0")}.${date.getMilliseconds().toString().padStart(3, "0")}`;
3242
+ var defaultLogger = /* @__PURE__ */ loggerMake(({
3243
+ cause,
3244
+ date,
3245
+ fiber,
3246
+ logLevel,
3247
+ message
3248
+ }) => {
3249
+ const message_ = Array.isArray(message) ? message.slice() : [message];
3250
+ if (cause.reasons.length > 0) {
3251
+ message_.push(causePretty(cause));
3252
+ }
3253
+ const now = date.getTime();
3254
+ const spans = fiber.getRef(CurrentLogSpans);
3255
+ let spanString = "";
3256
+ for (const span of spans) {
3257
+ spanString += ` ${formatLogSpan(span, now)}`;
3258
+ }
3259
+ const annotations = fiber.getRef(CurrentLogAnnotations);
3260
+ if (Object.keys(annotations).length > 0) {
3261
+ message_.push(annotations);
3262
+ }
3263
+ const console = fiber.getRef(ConsoleRef);
3264
+ const log = fiber.getRef(LogToStderr) ? console.error : console.log;
3265
+ log(`[${defaultDateFormat(date)}] ${logLevel.toUpperCase()} (#${fiber.id})${spanString}:`, ...message_);
3266
+ });
3267
+ var tracerLogger = /* @__PURE__ */ loggerMake(({
3268
+ cause,
3269
+ fiber,
3270
+ logLevel,
3271
+ message
3272
+ }) => {
3273
+ const clock = fiber.getRef(ClockRef);
3274
+ const annotations = fiber.getRef(CurrentLogAnnotations);
3275
+ const span = fiber.cache.span;
3276
+ if (span === undefined || span._tag === "ExternalSpan" || span.status._tag === "Ended")
3277
+ return;
3278
+ const attributes = {};
3279
+ for (const [key, value] of Object.entries(annotations)) {
3280
+ assignProperty(attributes, key, value);
3281
+ }
3282
+ attributes["effect.fiberId"] = fiber.id;
3283
+ attributes["effect.logLevel"] = logLevel.toUpperCase();
3284
+ if (cause.reasons.length > 0) {
3285
+ attributes["effect.cause"] = causePretty(cause);
3286
+ }
3287
+ span.event(toStringUnknown(Array.isArray(message) && message.length === 1 ? message[0] : message), clock.currentTimeNanosUnsafe(), attributes);
3288
+ });
3289
+
3290
+ var tryPromise2 = tryPromise;
3291
+ var succeed4 = succeed3;
3292
+ var sync2 = sync;
3293
+ var callback2 = callback;
3294
+ var die2 = die;
3295
+ var flatMap2 = flatMap;
3296
+ var andThen2 = andThen;
3297
+ var map2 = map;
3298
+ var catch_2 = catch_;
3299
+ var ignore2 = ignore;
3300
+ var timeout2 = timeout;
3301
+ var match4 = match3;
3302
+ var acquireUseRelease2 = acquireUseRelease;
3303
+ var runFork2 = runFork;
3304
+ var runPromise2 = runPromise;
3305
+ // packages/runtime/src/setup/tui/app.tsx
3306
+ import { effect as _$effect } from "@opentui/solid";
3307
+ import { memo as _$memo } from "@opentui/solid";
3308
+ import { insert as _$insert } from "@opentui/solid";
3309
+ import { createComponent as _$createComponent } from "@opentui/solid";
3310
+ import { setProp as _$setProp } from "@opentui/solid";
3311
+ import { createElement as _$createElement } from "@opentui/solid";
3312
+ import { RGBA } from "@opentui/core";
3313
+ import { useKeyboard, useTerminalDimensions } from "@opentui/solid";
3314
+ import { createMemo, createSignal, For, onCleanup, Show } from "solid-js";
3315
+
3316
+ var segmenter = new Intl.Segmenter;
3317
+ var cells = (text) => Bun.stringWidth(text);
3318
+ var graphemes = (text) => Array.from(segmenter.segment(text), (part) => part.segment);
3319
+ var prefix = (text, width) => {
3320
+ let taken = "";
3321
+ for (const grapheme of graphemes(text)) {
3322
+ if (cells(taken + grapheme) > width)
3323
+ break;
3324
+ taken += grapheme;
3325
+ }
3326
+ return taken;
3327
+ };
3328
+ var clip = (text, width, ellipsis) => {
3329
+ if (width <= 0)
3330
+ return "";
3331
+ if (cells(text) <= width)
3332
+ return text;
3333
+ const room = width - cells(ellipsis);
3334
+ return room <= 0 ? prefix(ellipsis, width) : prefix(text, room) + ellipsis;
3335
+ };
3336
+ var pad = (text, width) => text + " ".repeat(Math.max(0, width - cells(text)));
3337
+ var FOLDERS = new Set(["/", "\\"]);
3338
+ var MARKS = new Set([".", "_", "-"]);
3339
+ var head2 = (word, room) => {
3340
+ const fits = prefix(word, room);
3341
+ let folder = -1;
3342
+ let mark = -1;
3343
+ let size = 0;
3344
+ let before = "/";
3345
+ for (const grapheme of graphemes(fits)) {
3346
+ size += grapheme.length;
3347
+ if (FOLDERS.has(grapheme))
3348
+ folder = size;
3349
+ else if (MARKS.has(grapheme) && !(grapheme === "." && FOLDERS.has(before)))
3350
+ mark = size;
3351
+ before = grapheme;
3352
+ }
3353
+ const usable = (cut) => cut >= 3 || cut > 0 && cut === fits.length;
3354
+ const cut = usable(folder) ? folder : usable(mark) ? mark : -1;
3355
+ return cut > 0 ? fits.slice(0, cut) : fits;
3356
+ };
3357
+ var wrap = (text, width, hang = 0) => {
3358
+ const lines = [];
3359
+ let line = "";
3360
+ const room = () => Math.max(1, width - (lines.length === 0 ? 0 : hang));
3361
+ const flush = () => {
3362
+ lines.push(`${lines.length === 0 ? "" : " ".repeat(hang)}${line}`);
3363
+ line = "";
3364
+ };
3365
+ for (const word of text.split(/\s+/).filter((part) => part !== "")) {
3366
+ let rest = word;
3367
+ while (cells(rest) > room()) {
3368
+ if (line !== "")
3369
+ flush();
3370
+ const piece = head2(rest, room());
3371
+ if (piece === "")
3372
+ break;
3373
+ line = piece;
3374
+ flush();
3375
+ rest = rest.slice(piece.length);
3376
+ }
3377
+ if (line === "")
3378
+ line = rest;
3379
+ else if (cells(`${line} ${rest}`) <= room())
3380
+ line = `${line} ${rest}`;
3381
+ else {
3382
+ flush();
3383
+ line = rest;
3384
+ }
3385
+ }
3386
+ if (line !== "")
3387
+ flush();
3388
+ return lines;
3389
+ };
3390
+ var wrapItems = (items, width, separator) => {
3391
+ const lines = [];
3392
+ let line = "";
3393
+ for (const item of items) {
3394
+ if (line === "")
3395
+ line = item;
3396
+ else if (cells(line + separator + item) <= width)
3397
+ line += separator + item;
3398
+ else {
3399
+ lines.push(line);
3400
+ line = item;
3401
+ }
3402
+ }
3403
+ return line === "" ? lines : [...lines, line];
3404
+ };
3405
+
3406
+ var BILLION_CONTEXT_GUARDRAILS_FILE = {
3407
+ guardrails: { bashTimeout: 0, maxOutputBytes: 0, repetition: false }
3408
+ };
3409
+
3410
+ var FFF_OVERRIDE_SETTINGS = { mode: "override" };
3411
+ var FFF_NATIVE_HOSTS = [
3412
+ "darwin-arm64",
3413
+ "darwin-x64",
3414
+ "linux-arm64",
3415
+ "linux-x64",
3416
+ "win32-arm64",
3417
+ "win32-x64",
3418
+ "android-arm64"
3419
+ ];
3420
+
3421
+ var pi_packages_default = {
3422
+ "pi-provider-kimi-code": "0.6.13",
3423
+ "@tintinweb/pi-subagents": "0.23.2",
3424
+ "billion-context": "0.1.213",
3425
+ "@juicesharp/rpiv-todo": "2.15.0",
3426
+ "@juicesharp/rpiv-ask-user-question": "2.15.0",
3427
+ "@aliou/pi-processes": "0.13.6",
3428
+ "@amaster.ai/pi-computer-use": "0.1.38",
3429
+ "pi-web-kit": "0.5.0",
3430
+ "@ff-labs/pi-fff": "0.11.0",
3431
+ "@opencode/browse": "0.0.16"
3432
+ };
3433
+
3434
+ var PI_PACKAGE_VERSIONS = pi_packages_default;
3435
+
3436
+ var pypi_packages_default = {
3437
+ "browser-use": "1.0.2"
3438
+ };
3439
+
3440
+ var PYPI_PACKAGE_VERSIONS = pypi_packages_default;
3441
+
3442
+ var BILLION_CONTEXT_FILE = "~/.config/billion-context/billion-context.json";
3443
+ var PI_SETTINGS_FILE = "~/.pi/agent/settings.json";
3444
+ var SUBAGENTS_SETTINGS_FILE = "~/.pi/agent/subagents.json";
3445
+ var SUBAGENTS_ONLY_SPECIALISTS = {
3446
+ disableDefaultAgents: true,
3447
+ fallbackSubagent: "none"
3448
+ };
3449
+ var PI_FFF_FILE = "~/.pi/agent/pi-fff.json";
3450
+ var T3_PREFIX = "mcp__t3*code__";
3451
+ var T3_PREVIEW_TOOLS = [
3452
+ `${T3_PREFIX}preview_*`,
3453
+ `${T3_PREFIX}t3_preview_*`,
3454
+ `${T3_PREFIX}html_render`,
3455
+ `${T3_PREFIX}html_preview`
3456
+ ];
3457
+ var T3_VISUAL_TOOLS = [...T3_PREVIEW_TOOLS, `${T3_PREFIX}device_*`];
3458
+ var COMPUTER_USE_TOOLS = ["computer_use_*"];
3459
+ var BROWSE_PACKAGE = "@opencode/browse";
3460
+ var BROWSE_SERVER = "browse";
3461
+ var BROWSE_TOOLS = [`mcp__${BROWSE_SERVER}__*`];
3462
+ var NPM_REGISTRY = "https://registry.npmjs.org/";
3463
+ var npxServerArgs = (name, rest) => [
3464
+ `--registry=${NPM_REGISTRY}`,
3465
+ ...name.startsWith("@") ? [`--${name.slice(0, name.indexOf("/"))}:registry=${NPM_REGISTRY}`] : [],
3466
+ "-y",
3467
+ `${name}@${PI_PACKAGE_VERSIONS[name]}`,
3468
+ ...rest
3469
+ ];
3470
+ var BROWSE_MCP_SERVER = {
3471
+ name: BROWSE_SERVER,
3472
+ command: "npx",
3473
+ args: npxServerArgs(BROWSE_PACKAGE, ["mcp"])
3474
+ };
3475
+ var BROWSER_USE_PACKAGE = "browser-use";
3476
+ var BROWSER_USE_SERVER = "browser_use";
3477
+ var BROWSER_USE_TOOLS = [
3478
+ `mcp__${BROWSER_USE_SERVER}__browser_exec`,
3479
+ `mcp__${BROWSER_USE_SERVER}__browser_screenshot`
3480
+ ];
3481
+ var BROWSER_USE_ALL_TOOLS = [`mcp__${BROWSER_USE_SERVER}__*`];
3482
+ var PYPI_INDEX = "https://pypi.org/simple";
3483
+ var uvxServerArgs = (name, rest) => [
3484
+ "--no-config",
3485
+ "--default-index",
3486
+ PYPI_INDEX,
3487
+ "--from",
3488
+ `${name}==${PYPI_PACKAGE_VERSIONS[name]}`,
3489
+ ...rest
3490
+ ];
3491
+ var BROWSER_USE_MCP_SERVER = {
3492
+ name: BROWSER_USE_SERVER,
3493
+ command: "uvx",
3494
+ args: uvxServerArgs(BROWSER_USE_PACKAGE, ["browser-use", "--cli-mcp"]),
3495
+ launchesChromium: true
3496
+ };
3497
+ var BROWSE_MINIMUM_NODE = [22, 19, 0];
3498
+ var CHROMIUM_FIX = "set HOLYAGENT_CHROMIUM_PATH to a Chromium executable, or put a Playwright Chromium build in the folder PLAYWRIGHT_BROWSERS_PATH names (PLAYWRIGHT_BROWSERS_PATH=<folder> uvx playwright install chromium)";
3499
+ var nodeNeed = (minimum) => ({
3500
+ kind: "node",
3501
+ minimum,
3502
+ fix: `install Node.js ${minimum.join(".")} or newer from https://nodejs.org, which ships npx`
3503
+ });
3504
+ var sameForm = (packages) => ({
3505
+ headless: { packages, mcpServers: [] },
3506
+ normal: { packages, mcpServers: [] }
3507
+ });
3508
+ var CAPABILITIES = [
3509
+ {
3510
+ name: "subagents",
3511
+ feature: "subagents",
3512
+ description: "Runs the 18 specialists as subagents (@tintinweb/pi-subagents)",
3513
+ skills: [],
3514
+ applicability: "root",
3515
+ defaultOn: true,
3516
+ needs: [],
3517
+ forms: sameForm(["@tintinweb/pi-subagents"]),
3518
+ tools: { rootExclude: [], visual: [], screen: [] },
3519
+ settings: [{ file: SUBAGENTS_SETTINGS_FILE, content: SUBAGENTS_ONLY_SPECIALISTS }],
3520
+ health: ["needs", "packages"]
3521
+ },
3522
+ {
3523
+ name: "context-compression",
3524
+ feature: "contextCompression",
3525
+ description: "Compresses the context of long sessions (Billion Context)",
3526
+ skills: [],
3527
+ applicability: "both",
3528
+ defaultOn: true,
3529
+ needs: [],
3530
+ forms: sameForm(["billion-context"]),
3531
+ tools: { rootExclude: [], visual: [], screen: [] },
3532
+ settings: [{ file: BILLION_CONTEXT_FILE, content: { pi: { subagents: false } } }],
3533
+ health: ["needs", "packages"]
3534
+ },
3535
+ {
3536
+ name: "todo",
3537
+ feature: "todo",
3538
+ description: "Gives the root a todo list tool (@juicesharp/rpiv-todo)",
3539
+ skills: [],
3540
+ applicability: "root",
3541
+ defaultOn: true,
3542
+ needs: [],
3543
+ forms: sameForm(["@juicesharp/rpiv-todo"]),
3544
+ tools: { rootExclude: [], visual: [], screen: [] },
3545
+ settings: [],
3546
+ health: ["needs", "packages"]
3547
+ },
3548
+ {
3549
+ name: "ask",
3550
+ feature: "ask",
3551
+ description: "Lets the root ask the user a question mid-run (@juicesharp/rpiv-ask-user-question)",
3552
+ skills: [],
3553
+ applicability: "root",
3554
+ defaultOn: true,
3555
+ needs: [],
3556
+ forms: sameForm(["@juicesharp/rpiv-ask-user-question"]),
3557
+ tools: { rootExclude: [], visual: [], screen: [] },
3558
+ settings: [],
3559
+ health: ["needs", "packages"]
3560
+ },
3561
+ {
3562
+ name: "processes",
3563
+ feature: "processes",
3564
+ supportedPlatforms: ["darwin", "linux"],
3565
+ description: "Gives the root tools for background processes (@aliou/pi-processes)",
3566
+ skills: [],
3567
+ applicability: "root",
3568
+ defaultOn: true,
3569
+ needs: [],
3570
+ forms: sameForm(["@aliou/pi-processes"]),
3571
+ tools: { rootExclude: [], visual: [], screen: [] },
3572
+ settings: [],
3573
+ health: ["needs", "packages"]
3574
+ },
3575
+ {
3576
+ name: "mcp",
3577
+ feature: "mcp",
3578
+ description: "Pi's built-in MCP extension, which brings T3 Code's browser, render and device tools",
3579
+ skills: [],
3580
+ applicability: "both",
3581
+ defaultOn: true,
3582
+ needs: [],
3583
+ forms: sameForm([]),
3584
+ tools: { rootExclude: [], visual: T3_VISUAL_TOOLS, screen: T3_PREVIEW_TOOLS },
3585
+ settings: [],
3586
+ health: ["needs"]
3587
+ },
3588
+ {
3589
+ name: "computer-use",
3590
+ feature: "computerUse",
3591
+ description: "Lets the visual specialists drive the desktop (@amaster.ai/pi-computer-use)",
3592
+ skills: [],
3593
+ applicability: "specialists",
3594
+ defaultOn: true,
3595
+ needs: [{ kind: "display" }],
3596
+ forms: {
3597
+ headless: { unavailable: "it drives a graphical session and this machine has none" },
3598
+ normal: { packages: ["@amaster.ai/pi-computer-use"], mcpServers: [] }
3599
+ },
3600
+ settings: [
3601
+ {
3602
+ file: PI_SETTINGS_FILE,
3603
+ content: { "pi-computer-use": { confirmAppLaunch: false, confirmDangerousActions: false } }
3604
+ }
3605
+ ],
3606
+ tools: {
3607
+ rootExclude: COMPUTER_USE_TOOLS,
3608
+ visual: COMPUTER_USE_TOOLS,
3609
+ screen: COMPUTER_USE_TOOLS
3610
+ },
3611
+ health: ["needs", "packages"]
3612
+ },
3613
+ {
3614
+ name: "browser-use",
3615
+ feature: "browserUse",
3616
+ description: "Lets screen specialists use a browser: the user's real one through opencode browse (@opencode/browse), or a headless Chromium through the browser-use MCP server (browser-use) where there is no desktop",
3617
+ skills: [],
3618
+ applicability: "specialists",
3619
+ defaultOn: true,
3620
+ needs: [],
3621
+ forms: {
3622
+ headless: {
3623
+ packages: [],
3624
+ mcpServers: [BROWSER_USE_MCP_SERVER],
3625
+ needs: [
3626
+ {
3627
+ kind: "command",
3628
+ command: "uvx",
3629
+ fix: "install uv from https://docs.astral.sh/uv/, which ships uvx and provides the Python 3.11 or newer that browser-use needs"
3630
+ },
3631
+ { kind: "chromium", fix: CHROMIUM_FIX }
3632
+ ]
3633
+ },
3634
+ normal: {
3635
+ packages: [],
3636
+ mcpServers: [BROWSE_MCP_SERVER],
3637
+ needs: [
3638
+ {
3639
+ kind: "command",
3640
+ command: "npx",
3641
+ fix: "install Node.js from https://nodejs.org, which ships npx"
3642
+ },
3643
+ { kind: "display" },
3644
+ nodeNeed(BROWSE_MINIMUM_NODE)
3645
+ ],
3646
+ pairing: true
3647
+ }
3648
+ },
3649
+ tools: {
3650
+ rootExclude: [...BROWSE_TOOLS, ...BROWSER_USE_ALL_TOOLS],
3651
+ visual: [],
3652
+ screen: [...BROWSE_TOOLS, ...BROWSER_USE_TOOLS]
3653
+ },
3654
+ settings: [],
3655
+ health: ["needs"]
3656
+ },
3657
+ {
3658
+ name: "luna-reserve",
3659
+ feature: "lunaReserve",
3660
+ description: "Falls back to Codex's Luna Reserve allowance when the usage limit is reached (Codex provider only)",
3661
+ provider: "openai-codex",
3662
+ skills: [],
3663
+ applicability: "both",
3664
+ defaultOn: true,
3665
+ needs: [],
3666
+ forms: sameForm([]),
3667
+ tools: { rootExclude: [], visual: [], screen: [] },
3668
+ settings: [],
3669
+ health: ["needs"]
3670
+ },
3671
+ {
3672
+ name: "context-management",
3673
+ feature: "contextManagement",
3674
+ description: "Lets the server compact the history with context_management while Billion Context is off (Codex provider only)",
3675
+ provider: "openai-codex",
3676
+ skills: [],
3677
+ applicability: "both",
3678
+ defaultOn: true,
3679
+ needs: [],
3680
+ forms: sameForm([]),
3681
+ tools: { rootExclude: [], visual: [], screen: [] },
3682
+ settings: [],
3683
+ health: ["needs"]
3684
+ },
3685
+ {
3686
+ name: "auto-review",
3687
+ feature: "autoReview",
3688
+ description: "Has the codex-auto-review model judge risky tool calls before they run, as Codex's auto-review does (Codex provider only)",
3689
+ provider: "openai-codex",
3690
+ skills: [],
3691
+ applicability: "both",
3692
+ defaultOn: true,
3693
+ needs: [],
3694
+ forms: sameForm([]),
3695
+ tools: { rootExclude: [], visual: [], screen: [] },
3696
+ settings: [],
3697
+ health: ["needs"]
3698
+ },
3699
+ {
3700
+ name: "just-bash",
3701
+ feature: "justBash",
3702
+ description: "Runs the bash tool on just-bash, with the host's programs, TypeScript first and JavaScript as the fallback; turns Billion Context's bash guardrails off",
3703
+ skills: [],
3704
+ applicability: "both",
3705
+ defaultOn: true,
3706
+ needs: [
3707
+ {
3708
+ kind: "command",
3709
+ command: "bun",
3710
+ fix: "install Bun from https://bun.sh, since the shell runs on it"
3711
+ }
3712
+ ],
3713
+ forms: sameForm([]),
3714
+ tools: { rootExclude: [], visual: [], screen: [] },
3715
+ settings: [
3716
+ {
3717
+ file: BILLION_CONTEXT_FILE,
3718
+ content: BILLION_CONTEXT_GUARDRAILS_FILE,
3719
+ whileOn: "contextCompression",
3720
+ revertWhenOff: true
3721
+ }
3722
+ ],
3723
+ health: ["needs"]
3724
+ },
3725
+ {
3726
+ name: "fff",
3727
+ feature: "fff",
3728
+ description: "Replaces Pi's find and grep with fff, a fast indexed file and content search (@ff-labs/pi-fff)",
3729
+ skills: [],
3730
+ applicability: "both",
3731
+ defaultOn: true,
3732
+ needs: [],
3733
+ nativeHosts: FFF_NATIVE_HOSTS,
3734
+ forms: sameForm(["@ff-labs/pi-fff"]),
3735
+ tools: { rootExclude: [], visual: [], screen: [] },
3736
+ settings: [{ file: PI_FFF_FILE, content: FFF_OVERRIDE_SETTINGS, revertWhenOff: true }],
3737
+ health: ["needs", "packages"]
3738
+ }
3739
+ ];
3740
+ var FEATURE_DEFAULTS = Object.fromEntries(CAPABILITIES.map((capability) => [capability.feature, capability.defaultOn]));
3741
+ var formContent = (capability, form) => {
3742
+ const entry = capability.forms[form];
3743
+ return "unavailable" in entry ? undefined : entry;
3744
+ };
3745
+ var FEATURE_PACKAGES = Object.fromEntries(CAPABILITIES.flatMap((capability) => {
3746
+ const [first] = formContent(capability, "normal")?.packages ?? [];
3747
+ return first === undefined ? [] : [[capability.feature, first]];
3748
+ }));
3749
+
3750
+ var inCi = (env) => {
3751
+ const value = env["CI"]?.trim().toLowerCase();
3752
+ return value !== undefined && !["", "0", "false", "no", "off"].includes(value);
3753
+ };
3754
+
3755
+ var TERMINAL_THEME = {
3756
+ heading: "#7aa2f7",
3757
+ option: "#7dcfff",
3758
+ argument: "#a9b1d6",
3759
+ focus: "#7dcfff",
3760
+ enabled: "#9ece6a",
3761
+ disabled: "#a9b1d6",
3762
+ success: "#73daca",
3763
+ warning: "#e0af68",
3764
+ error: "#f7768e",
3765
+ hint: "#7e87b2"
3766
+ };
3767
+ var LIGHT_THEME = {
3768
+ heading: "#2a5bbd",
3769
+ option: "#00647f",
3770
+ argument: "#33478a",
3771
+ focus: "#00647f",
3772
+ enabled: "#3d6228",
3773
+ disabled: "#33478a",
3774
+ success: "#2a6a5f",
3775
+ warning: "#7c5410",
3776
+ error: "#b5223f",
3777
+ hint: "#565f89"
3778
+ };
3779
+ var BOLD_TONES = new Set(["heading", "focus"]);
3780
+ var paletteOf = (look) => look.background === "light" ? LIGHT_THEME : TERMINAL_THEME;
3781
+ var set = (value) => value !== undefined && value !== "";
3782
+ var colorEnabled = (env, tty) => {
3783
+ if (set(env["NO_COLOR"]) || env["TERM"] === "dumb")
3784
+ return false;
3785
+ if (set(env["FORCE_COLOR"]) && env["FORCE_COLOR"] !== "0")
3786
+ return true;
3787
+ if (inCi(env))
3788
+ return false;
3789
+ return tty;
3790
+ };
3791
+ var unicodeEnabled = (env) => {
3792
+ const locale = [env["LC_ALL"], env["LC_CTYPE"], env["LANG"]].find(set);
3793
+ return locale === undefined || /utf-?8/i.test(locale);
3794
+ };
3795
+ var backgroundFromColorfgbg = (env) => {
3796
+ const value = env["COLORFGBG"];
3797
+ if (!set(value))
3798
+ return;
3799
+ const parts = value.split(";");
3800
+ const last = parts.at(-1) ?? "";
3801
+ if (parts.length < 2 || !/^\d{1,3}$/.test(last))
3802
+ return;
3803
+ return last === "7" || last === "15" ? "light" : "dark";
3804
+ };
3805
+ var lookFor = (env, background = "dark") => ({
3806
+ color: colorEnabled(env, true),
3807
+ unicode: unicodeEnabled(env),
3808
+ background
3809
+ });
3810
+ var glyphs = (look) => look.unicode ? { focus: "\u276F", dot: "\xB7", ellipsis: "\u2026", arrows: "\u2191/\u2193" } : { focus: ">", dot: "-", ellipsis: "...", arrows: "up/down" };
3811
+
3812
+ var CAPABILITY_ROW = "capability:";
3813
+ var LABELS = {
3814
+ pi: "Pi provider",
3815
+ deviceAccess: "Agent device access",
3816
+ worktrees: "New threads in worktrees"
3817
+ };
3818
+ var capabilityOf = (row, offer) => row.startsWith(CAPABILITY_ROW) ? offer.capabilities.find((capability) => capability.feature === row.slice(CAPABILITY_ROW.length)) : undefined;
3819
+ var labelOf = (row, offer) => row === "pi" || row === "deviceAccess" || row === "worktrees" ? LABELS[row] : capabilityOf(row, offer)?.name ?? row;
3820
+ var rowsOf = (offer) => [
3821
+ ...offer.t3 ? ["pi"] : [],
3822
+ ...offer.t3 && offer.device !== undefined ? ["deviceAccess"] : [],
3823
+ ...offer.t3 && offer.worktrees ? ["worktrees"] : [],
3824
+ ...offer.capabilities.map((capability) => `${CAPABILITY_ROW}${capability.feature}`)
3825
+ ];
3826
+ var initialState = (choices) => ({
3827
+ screen: "choose",
3828
+ focus: 0,
3829
+ action: 0,
3830
+ scroll: 0,
3831
+ choices,
3832
+ review: undefined,
3833
+ failure: undefined,
3834
+ applied: undefined
3835
+ });
3836
+ var reviewActions = (state) => state.review === undefined ? ["back", "cancel"] : ["apply", "back", "cancel"];
3837
+ var isCancel = (key) => key.name === "escape" || key.ctrl && key.name === "c";
3838
+ var isQuit = (key) => isCancel(key) || !key.ctrl && key.name === "q";
3839
+ var isEnter = (key) => key.name === "return" || key.name === "enter";
3840
+ var stepOf = (key) => key.ctrl ? 0 : key.name === "up" || key.name === "k" ? -1 : key.name === "down" || key.name === "j" ? 1 : 0;
3841
+ var wrapped = (index, step, length) => ((index + step) % length + length) % length;
3842
+ var toggled = (choices, row) => {
3843
+ if (row === "deviceAccess")
3844
+ return { ...choices, deviceAccess: !choices.deviceAccess };
3845
+ if (row === "worktrees")
3846
+ return { ...choices, worktrees: !choices.worktrees };
3847
+ if (!row.startsWith(CAPABILITY_ROW))
3848
+ return choices;
3849
+ const feature = row.slice(CAPABILITY_ROW.length);
3850
+ return {
3851
+ ...choices,
3852
+ capabilities: { ...choices.capabilities, [feature]: choices.capabilities[feature] !== true }
3853
+ };
3854
+ };
3855
+ var pagedBy = (state, key, scroll) => {
3856
+ if (key.ctrl)
3857
+ return;
3858
+ const direction = key.name === "pagedown" ? 1 : key.name === "pageup" ? -1 : 0;
3859
+ if (direction === 0)
3860
+ return;
3861
+ const from = Math.min(state.scroll, scroll.max);
3862
+ return { ...state, scroll: Math.min(scroll.max, Math.max(0, from + direction * scroll.page)) };
3863
+ };
3864
+ var press = (state, rows, key, scroll = { page: 1, max: 0 }) => {
3865
+ if (state.screen === "choose") {
3866
+ if (isQuit(key))
3867
+ return { state, command: "cancel" };
3868
+ const step = stepOf(key);
3869
+ if (step !== 0)
3870
+ return { state: { ...state, focus: wrapped(state.focus, step, rows.length) } };
3871
+ if (!key.ctrl && key.name === "space") {
3872
+ const row = rows[state.focus];
3873
+ return row === undefined ? { state } : { state: { ...state, choices: toggled(state.choices, row) } };
3874
+ }
3875
+ if (isEnter(key))
3876
+ return {
3877
+ state: {
3878
+ ...state,
3879
+ screen: "review",
3880
+ action: 0,
3881
+ scroll: 0,
3882
+ review: undefined,
3883
+ failure: undefined
3884
+ },
3885
+ command: "review"
3886
+ };
3887
+ return { state };
3888
+ }
3889
+ if (state.screen === "review") {
3890
+ if (isQuit(key))
3891
+ return { state, command: "cancel" };
3892
+ const paged = pagedBy(state, key, scroll);
3893
+ if (paged !== undefined)
3894
+ return { state: paged };
3895
+ const actions = reviewActions(state);
3896
+ const step = stepOf(key);
3897
+ if (step !== 0)
3898
+ return { state: { ...state, action: wrapped(state.action, step, actions.length) } };
3899
+ if (isEnter(key)) {
3900
+ const action = actions[state.action];
3901
+ if (action === "apply")
3902
+ return { state: { ...state, screen: "applying" }, command: "apply" };
3903
+ if (action === "back")
3904
+ return {
3905
+ state: { ...state, screen: "choose", scroll: 0, review: undefined, failure: undefined }
3906
+ };
3907
+ return { state, command: "cancel" };
3908
+ }
3909
+ return { state };
3910
+ }
3911
+ if (state.screen === "applying")
3912
+ return key.ctrl && key.name === "c" ? { state, command: "interrupt" } : { state };
3913
+ const paged = pagedBy(state, key, scroll);
3914
+ if (paged !== undefined)
3915
+ return { state: paged };
3916
+ return isQuit(key) || isEnter(key) || key.name === "space" ? { state, command: "close" } : { state };
3917
+ };
3918
+ var reviewed = (state, review) => state.screen === "review" ? { ...state, review, failure: undefined, action: 0, scroll: 0 } : state;
3919
+ var reviewFailed = (state, failure) => state.screen === "review" ? { ...state, review: undefined, failure, action: 0, scroll: 0 } : state;
3920
+ var finished = (state, applied) => ({
3921
+ ...state,
3922
+ screen: "done",
3923
+ scroll: 0,
3924
+ applied
3925
+ });
3926
+ var KEY_GAP = " ";
3927
+ var segment = (text, tone) => tone === undefined ? { text } : { text, tone };
3928
+ var title = (look) => [segment(`HolyAgent ${glyphs(look).dot} setup`, "heading")];
3929
+ var keyLines = (items, width) => wrapItems(items, width, KEY_GAP).map((text) => [segment(text, "option")]);
3930
+ var heading = (text, width) => wrap(text.toUpperCase(), width).map((part) => [segment(part, "heading")]);
3931
+ var blank = [];
3932
+ var hintLines = (text, width) => wrap(text, width).map((part) => [segment(part, "hint")]);
3933
+ var hintOf = (row, offer) => {
3934
+ if (row === "pi")
3935
+ return "Pi runs in T3 Code as its own provider; it stays on while pi.enable is true, so there is nothing to choose.";
3936
+ if (row === "deviceAccess")
3937
+ return `Lets agents use the iOS simulator or an Android emulator. Found: ${offer.device ?? "no device host"}.`;
3938
+ if (row === "worktrees")
3939
+ return "New T3 Code threads start in their own git worktree instead of the local checkout.";
3940
+ const capability = capabilityOf(row, offer);
3941
+ if (capability === undefined)
3942
+ return "";
3943
+ return capability.unavailable === undefined ? `${capability.description}.` : `${capability.description}. Not offered in this form: ${capability.unavailable}; the choice is kept in the config.`;
3944
+ };
3945
+ var isOn = (row, choices) => row === "deviceAccess" ? choices.deviceAccess : row === "worktrees" ? choices.worktrees : row.startsWith(CAPABILITY_ROW) && choices.capabilities[row.slice(CAPABILITY_ROW.length)] === true;
3946
+ var checkbox = (row, choices) => row === "pi" ? { box: "[x]", word: "fixed" } : isOn(row, choices) ? { box: "[x]", word: "enabled" } : { box: "[ ]", word: "disabled" };
3947
+ var FIXED = { page: 1, max: 0 };
3948
+ var chooseLines = (state, context) => {
3949
+ const { rows, offer, width, look } = context;
3950
+ const g = glyphs(look);
3951
+ const values = rows.map((row) => {
3952
+ const { box, word } = checkbox(row, state.choices);
3953
+ return `${box} ${word}`;
3954
+ });
3955
+ const labels = rows.map((row) => labelOf(row, offer));
3956
+ const valueWidth = Math.max(...values.map(cells));
3957
+ const labelWidth = Math.min(Math.max(...labels.map(cells)), Math.max(4, width - 2 - 2 - valueWidth));
3958
+ const rowLine = (row, index) => {
3959
+ const focused = index === state.focus;
3960
+ const label = pad(clip(labels[index] ?? "", labelWidth, g.ellipsis), labelWidth);
3961
+ const value = values[index] ?? "";
3962
+ if (focused)
3963
+ return [segment(`${g.focus} ${label} ${value}`, "focus")];
3964
+ return [
3965
+ segment(` ${label} `, "argument"),
3966
+ segment(value, row === "pi" || !isOn(row, state.choices) ? "disabled" : "enabled")
3967
+ ];
3968
+ };
3969
+ const group = (title, from, to) => to <= from ? [] : [
3970
+ ...heading(title, width),
3971
+ ...rows.slice(from, to).map((row, index) => rowLine(row, from + index)),
3972
+ blank
3973
+ ];
3974
+ const t3Count = rows.filter((row) => !row.startsWith(CAPABILITY_ROW)).length;
3975
+ const focused = rows[state.focus];
3976
+ return [
3977
+ ...keyLines([`${g.arrows} or j/k focus`, "Space toggle", "Enter review", "Esc cancel"], width),
3978
+ blank,
3979
+ ...group("T3 Code", 0, t3Count),
3980
+ ...group(`Capabilities, ${offer.form} form`, t3Count, rows.length),
3981
+ ...focused === undefined ? [] : hintLines(hintOf(focused, offer), width)
3982
+ ];
3983
+ };
3984
+ var MARK_TONES = {
3985
+ "+": "success",
3986
+ "=": "hint",
3987
+ "~": "warning",
3988
+ "-": "hint"
3989
+ };
3990
+ var MIN_DETAIL = 24;
3991
+ var reviewEntry = (line, nameWidth, width) => {
3992
+ const mark = segment(` ${line.mark} `, MARK_TONES[line.mark]);
3993
+ const side = cells(mark.text) + nameWidth + 2;
3994
+ const room = width - side;
3995
+ if (room < MIN_DETAIL)
3996
+ return [
3997
+ [mark, segment(line.name, "argument")],
3998
+ ...wrap(line.detail, width - 4).map((part) => [segment(` ${part}`, "hint")])
3999
+ ];
4000
+ const parts = wrap(line.detail, room);
4001
+ return (parts.length === 0 ? [""] : parts).map((part, index) => index === 0 ? [
4002
+ mark,
4003
+ segment(pad(line.name, nameWidth), "argument"),
4004
+ ...part === "" ? [] : [segment(` ${part}`, "hint")]
4005
+ ] : [segment(`${" ".repeat(side)}${part}`, "hint")]);
4006
+ };
4007
+ var pageOf = (body, room, from) => {
4008
+ if (body.length <= room)
4009
+ return { shown: body, indicator: undefined, scroll: FIXED };
4010
+ const size = Math.max(1, room - 1);
4011
+ const max = body.length - size;
4012
+ const start = Math.min(Math.max(0, from), max);
4013
+ const end = start + size;
4014
+ const more = start === 0 ? "PgDn for more" : end === body.length ? "PgUp for earlier" : "PgUp/PgDn";
4015
+ return {
4016
+ shown: body.slice(start, end),
4017
+ indicator: [segment(`Lines ${start + 1}-${end} of ${body.length}, ${more}`, "hint")],
4018
+ scroll: { page: Math.max(1, size - 1), max }
4019
+ };
4020
+ };
4021
+ var REVIEW_RECOVERY = "Fix the cause, then choose Back and review again, or choose Cancel and run holyagent setup later.";
4022
+ var reviewLayout = (state, context) => {
4023
+ const { width, look } = context;
4024
+ const g = glyphs(look);
4025
+ const heading_ = heading(context.dryRun ? "Review (dry run: would change, nothing is written)" : "Review", width);
4026
+ const actionLines = () => reviewActions(state).map((action, index) => {
4027
+ const text = action === "apply" ? context.dryRun ? "Apply (dry run)" : "Apply" : action === "back" ? "Back" : "Cancel";
4028
+ if (index === state.action)
4029
+ return [segment(`${g.focus} ${text}`, "focus")];
4030
+ const tone = action === "apply" ? "enabled" : action === "cancel" ? "error" : "argument";
4031
+ return [segment(` ${text}`, tone)];
4032
+ });
4033
+ const keys = (scrolling) => keyLines([
4034
+ `${g.arrows} or j/k focus`,
4035
+ ...scrolling ? ["PgUp/PgDn scroll"] : [],
4036
+ "Enter select",
4037
+ "Esc cancel"
4038
+ ], width);
4039
+ if (state.failure !== undefined) {
4040
+ const cause = wrap(state.failure, width - 2).map((part) => [
4041
+ segment(` ${part}`, "error")
4042
+ ]);
4043
+ const recovery = hintLines(REVIEW_RECOVERY, width);
4044
+ const actions = actionLines();
4045
+ const build = (spaced) => {
4046
+ const gap = spaced ? [blank] : [];
4047
+ const layout = (scrolling) => {
4048
+ const top = [...keys(scrolling), ...gap, ...heading_];
4049
+ const bottom = [...gap, ...recovery, ...gap, ...actions];
4050
+ const page = pageOf(cause, context.height - 1 - top.length - bottom.length, state.scroll);
4051
+ return {
4052
+ lines: [
4053
+ ...top,
4054
+ ...page.shown,
4055
+ ...page.indicator === undefined ? [] : [page.indicator],
4056
+ ...bottom
4057
+ ],
4058
+ scroll: page.scroll,
4059
+ fits: page.indicator === undefined,
4060
+ shown: page.shown.length
4061
+ };
4062
+ };
4063
+ const plain = layout(false);
4064
+ return plain.fits ? plain : layout(true);
4065
+ };
4066
+ const spaced = build(true);
4067
+ const chosen = spaced.shown >= Math.min(3, cause.length) ? spaced : build(false);
4068
+ return { lines: chosen.lines, scroll: chosen.scroll };
4069
+ }
4070
+ if (state.review === undefined) {
4071
+ return {
4072
+ lines: [
4073
+ ...keys(false),
4074
+ blank,
4075
+ ...heading_,
4076
+ [segment(" Reading what will change", "hint")],
4077
+ blank,
4078
+ ...actionLines()
4079
+ ],
4080
+ scroll: FIXED
4081
+ };
4082
+ }
4083
+ const { review } = state;
4084
+ const capabilities = review.capabilities ?? [];
4085
+ const nameWidth = Math.max(...[...capabilities, ...review.choices, ...review.always].map((line) => cells(line.name)));
4086
+ const entries = (lines) => lines.flatMap((line) => reviewEntry(line, nameWidth, width));
4087
+ const section = (title, lines) => lines.length === 0 ? [] : [...heading(title, width), ...entries(lines), blank];
4088
+ const t3 = [
4089
+ ...review.file === undefined ? [] : [
4090
+ ...wrap(review.file, width - 2).map((part) => [segment(` ${part}`, "hint")]),
4091
+ blank
4092
+ ],
4093
+ ...section("Your choices", review.choices),
4094
+ ...section("Always applied", review.always)
4095
+ ];
4096
+ const body = [...section("Capabilities", capabilities), ...t3].slice(0, -1);
4097
+ const actions = actionLines();
4098
+ const build = (scrolling) => {
4099
+ const top = [...keys(scrolling), blank, ...heading_];
4100
+ const room = context.height - 1 - top.length - 1 - actions.length;
4101
+ const page = pageOf(body, room, state.scroll);
4102
+ return {
4103
+ lines: [...top, ...page.shown, page.indicator ?? blank, ...actions],
4104
+ scroll: page.scroll,
4105
+ fits: page.indicator === undefined
4106
+ };
4107
+ };
4108
+ const plain = build(false);
4109
+ return plain.fits ? plain : build(true);
4110
+ };
4111
+ var reportTone = (line) => line.startsWith("+ ") ? "success" : line.startsWith("! ") ? "error" : line.startsWith("~ ") ? "warning" : "hint";
4112
+ var doneHeadline = (ok, dryRun) => ok ? dryRun ? "Dry run finished; nothing was written." : "Setup finished." : dryRun ? "Dry run finished with failures; the lines marked ! failed. Fix the cause, then run the dry run again." : "Setup finished with failures; the lines marked ! failed. Fix the cause, then run holyagent setup again.";
4113
+ var doneLayout = (state, context) => {
4114
+ const { width, height } = context;
4115
+ const applied = state.applied;
4116
+ const ok = applied?.ok !== false;
4117
+ const body = (applied?.lines ?? []).flatMap((line) => wrap(line, width, 2).map((part) => [segment(part, reportTone(line))]));
4118
+ const build = (scrolling) => {
4119
+ const top = [
4120
+ ...keyLines(["Enter close", ...scrolling ? ["PgUp/PgDn scroll"] : []], width),
4121
+ blank,
4122
+ ...heading(context.dryRun ? "Result (dry run)" : "Result", width),
4123
+ ...wrap(doneHeadline(ok, context.dryRun), width).map((part) => [
4124
+ segment(part, ok ? "success" : "error")
4125
+ ]),
4126
+ blank
4127
+ ];
4128
+ const page = pageOf(body, height - 1 - top.length, state.scroll);
4129
+ return {
4130
+ lines: [...top, ...page.shown, ...page.indicator === undefined ? [] : [page.indicator]],
4131
+ scroll: page.scroll,
4132
+ fits: page.indicator === undefined
4133
+ };
4134
+ };
4135
+ const plain = build(false);
4136
+ return plain.fits ? plain : build(true);
4137
+ };
4138
+ var fitLine = (line, width, ellipsis) => {
4139
+ const total = line.reduce((sum, { text }) => sum + cells(text), 0);
4140
+ if (total <= width)
4141
+ return line;
4142
+ const kept = [];
4143
+ let used = 0;
4144
+ for (const part of line) {
4145
+ const room = width - used;
4146
+ if (room <= 0)
4147
+ break;
4148
+ const size = cells(part.text);
4149
+ if (size <= room) {
4150
+ kept.push(part);
4151
+ used += size;
4152
+ continue;
4153
+ }
4154
+ kept.push({ ...part, text: clip(part.text, room, ellipsis) });
4155
+ break;
4156
+ }
4157
+ return kept;
4158
+ };
4159
+ var layoutOf = (state, context) => state.screen === "choose" ? { lines: chooseLines(state, context), scroll: FIXED } : state.screen === "review" ? reviewLayout(state, context) : state.screen === "applying" ? {
4160
+ lines: [
4161
+ [segment("Press Ctrl-C to stop", "option")],
4162
+ blank,
4163
+ ...heading("Applying", context.width),
4164
+ [segment("Applying setup; this can take a moment.", "argument")]
4165
+ ],
4166
+ scroll: FIXED
4167
+ } : doneLayout(state, context);
4168
+ var scrollOf = (state, context) => layoutOf(state, context).scroll;
4169
+ var view = (state, context) => [title(context.look), ...layoutOf(state, context).lines].map((line) => fitLine(line, context.width, glyphs(context.look).ellipsis));
4170
+
4171
+ // packages/runtime/src/setup/tui/app.tsx
4172
+ var settle = (run, onResult) => runFork2(tryPromise2({
4173
+ try: run,
4174
+ catch: (cause) => cause instanceof Error ? cause.message : String(cause)
4175
+ }).pipe(match4({
4176
+ onFailure: (message) => onResult({
4177
+ message
4178
+ }),
4179
+ onSuccess: (value) => onResult({
4180
+ value
4181
+ })
4182
+ })));
4183
+ var SetupApp = (props) => {
4184
+ const dimensions = useTerminalDimensions();
4185
+ const look = lookFor(props.input.env, props.background);
4186
+ const palette = paletteOf(look);
4187
+ const rows = rowsOf(props.input.offer);
4188
+ const [state, setState] = createSignal(initialState(props.input.initial));
4189
+ const abort = new AbortController;
4190
+ onCleanup(() => abort.abort());
4191
+ let ticket = 0;
4192
+ const context = () => ({
4193
+ rows,
4194
+ offer: props.input.offer,
4195
+ dryRun: props.input.dryRun,
4196
+ width: dimensions().width,
4197
+ height: dimensions().height,
4198
+ look
4199
+ });
4200
+ const lines = createMemo(() => view(state(), context()));
4201
+ const run = (command) => {
4202
+ const current = state();
4203
+ if (command === "cancel")
4204
+ return props.done({
4205
+ _tag: "Cancelled"
4206
+ });
4207
+ if (command === "close") {
4208
+ const applied = current.applied;
4209
+ return props.done(applied === undefined ? {
4210
+ _tag: "Cancelled"
4211
+ } : {
4212
+ _tag: "Applied",
4213
+ applied
4214
+ });
4215
+ }
4216
+ if (command === "interrupt") {
4217
+ abort.abort();
4218
+ return props.done({
4219
+ _tag: "Interrupted"
4220
+ });
4221
+ }
4222
+ ticket += 1;
4223
+ const mine = ticket;
4224
+ if (command === "review") {
4225
+ settle(() => props.input.review(current.choices), (result) => {
4226
+ if (mine !== ticket)
4227
+ return;
4228
+ setState((now) => ("value" in result) ? reviewed(now, result.value) : reviewFailed(now, result.message));
4229
+ });
4230
+ return;
4231
+ }
4232
+ settle(() => props.input.apply(current.choices, abort.signal), (result) => {
4233
+ if (mine !== ticket)
4234
+ return;
4235
+ setState((now) => finished(now, "value" in result ? result.value : {
4236
+ ok: false,
4237
+ lines: [`! setup: ${result.message}`]
4238
+ }));
4239
+ });
4240
+ };
4241
+ useKeyboard((event) => {
4242
+ const before = state();
4243
+ const next = press(before, rows, {
4244
+ name: event.name,
4245
+ ctrl: event.ctrl
4246
+ }, scrollOf(before, context()));
4247
+ if (next.state.screen !== before.screen && next.state.screen === "choose")
4248
+ ticket += 1;
4249
+ setState(next.state);
4250
+ if (next.command !== undefined)
4251
+ run(next.command);
4252
+ });
4253
+ const colorOf = (tone) => tone !== undefined && look.color ? palette[tone] : RGBA.defaultForeground();
4254
+ return (() => {
4255
+ var _el$ = _$createElement("box");
4256
+ _$setProp(_el$, "flexDirection", "column");
4257
+ _$insert(_el$, _$createComponent(For, {
4258
+ get each() {
4259
+ return lines();
4260
+ },
4261
+ children: (line) => (() => {
4262
+ var _el$2 = _$createElement("text");
4263
+ _$insert(_el$2, (() => {
4264
+ var _c$ = _$memo(() => line.length === 0);
4265
+ return () => _c$() ? " " : _$createComponent(For, {
4266
+ each: line,
4267
+ children: (part) => _$createComponent(Show, {
4268
+ get when() {
4269
+ return _$memo(() => part.tone !== undefined)() && BOLD_TONES.has(part.tone);
4270
+ },
4271
+ get fallback() {
4272
+ return (() => {
4273
+ var _el$4 = _$createElement("span");
4274
+ _$insert(_el$4, () => part.text);
4275
+ _$effect((_$p) => _$setProp(_el$4, "style", {
4276
+ fg: colorOf(part.tone)
4277
+ }, _$p));
4278
+ return _el$4;
4279
+ })();
4280
+ },
4281
+ get children() {
4282
+ var _el$3 = _$createElement("b");
4283
+ _$insert(_el$3, () => part.text);
4284
+ _$effect((_$p) => _$setProp(_el$3, "style", {
4285
+ fg: colorOf(part.tone)
4286
+ }, _$p));
4287
+ return _el$3;
4288
+ }
4289
+ })
4290
+ });
4291
+ })());
4292
+ _$effect((_$p) => _$setProp(_el$2, "fg", RGBA.defaultForeground(), _$p));
4293
+ return _el$2;
4294
+ })()
4295
+ }));
4296
+ return _el$;
4297
+ })();
4298
+ };
4299
+
4300
+ var BACKGROUND_TIMEOUT_MS = 300;
4301
+ var detectBackground = (env, renderer, timeoutMs = BACKGROUND_TIMEOUT_MS) => {
4302
+ if (!colorEnabled(env, true))
4303
+ return succeed4("dark");
4304
+ const named = backgroundFromColorfgbg(env);
4305
+ if (named !== undefined)
4306
+ return succeed4(named);
4307
+ return tryPromise2(() => renderer.waitForThemeMode(timeoutMs)).pipe(timeout2(timeoutMs + 50), map2((mode) => mode === "light" ? "light" : "dark"), catch_2(() => succeed4("dark")));
4308
+ };
4309
+
4310
+ // packages/runtime/src/setup/tui/entry.tsx
4311
+ var showSetup = (acquire, input) => acquireUseRelease2(acquire, (renderer) => detectBackground(input.env, renderer).pipe(flatMap2((background) => callback2((resume) => {
4312
+ const finish = (outcome) => resume(succeed4(outcome));
4313
+ const destroyed = () => finish({
4314
+ _tag: "Interrupted"
4315
+ });
4316
+ if (renderer.isDestroyed)
4317
+ return destroyed();
4318
+ renderer.once("destroy", destroyed);
4319
+ runFork2(tryPromise2(() => render(() => _$createComponent2(SetupApp, {
4320
+ input,
4321
+ background,
4322
+ done: finish
4323
+ }), renderer)).pipe(catch_2((cause) => sync2(() => resume(die2(cause))))));
4324
+ return sync2(() => renderer.off("destroy", destroyed));
4325
+ }))), (renderer) => sync2(() => renderer.destroy()).pipe(andThen2(tryPromise2(() => renderer.closed)), ignore2));
4326
+ var runSetupTui = (input) => runPromise2(showSetup(tryPromise2(() => createCliRenderer({
4327
+ exitOnCtrlC: false,
4328
+ useMouse: false,
4329
+ clearOnShutdown: true
4330
+ })), input));
4331
+ export {
4332
+ runSetupTui,
4333
+ showSetup
4334
+ };