brass-runtime 1.15.0 → 1.16.1

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 (209) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +673 -136
  3. package/dist/agent/cli/main.cjs +40 -35
  4. package/dist/agent/cli/main.js +9 -4
  5. package/dist/agent/cli/main.mjs +9 -4
  6. package/dist/agent/index.cjs +8 -4
  7. package/dist/agent/index.d.ts +1 -1
  8. package/dist/agent/index.js +7 -3
  9. package/dist/agent/index.mjs +7 -3
  10. package/dist/chunk-2HQTDLHF.mjs +683 -0
  11. package/dist/chunk-36I3M4UC.mjs +370 -0
  12. package/dist/chunk-3AYM6WPJ.js +1629 -0
  13. package/dist/chunk-3LOYJFRR.cjs +300 -0
  14. package/dist/chunk-3RG5ZIWI.js +10 -0
  15. package/dist/chunk-3Y2RIUMM.js +300 -0
  16. package/dist/{chunk-VEZNF5GZ.cjs → chunk-4ROBZFL6.cjs} +130 -126
  17. package/dist/{chunk-3QMOKAS5.js → chunk-52OB2ROS.js} +9 -5
  18. package/dist/chunk-52PPNNI4.cjs +416 -0
  19. package/dist/chunk-5EC274J5.cjs +2874 -0
  20. package/dist/chunk-5QC7LRZ3.js +229 -0
  21. package/dist/chunk-5VRJNBLZ.mjs +2874 -0
  22. package/dist/chunk-62AZW6UT.cjs +313 -0
  23. package/dist/chunk-6IXXWIUM.js +683 -0
  24. package/dist/chunk-74ZTY6CP.js +2871 -0
  25. package/dist/chunk-76YMRMH2.cjs +777 -0
  26. package/dist/chunk-7CMJS3QE.mjs +2871 -0
  27. package/dist/{chunk-4NHES7VK.mjs → chunk-7JIJOVCT.js} +27 -13
  28. package/dist/chunk-A2OM6NEH.mjs +194 -0
  29. package/dist/chunk-AGR5B2BC.cjs +683 -0
  30. package/dist/chunk-AVNQLJ5V.js +777 -0
  31. package/dist/chunk-B33ICAKP.js +313 -0
  32. package/dist/{chunk-ELOOF35R.mjs → chunk-B5JD23U7.mjs} +1 -1
  33. package/dist/chunk-BABBZK4Y.js +2024 -0
  34. package/dist/chunk-C3MDXTRZ.js +354 -0
  35. package/dist/chunk-CIZFIMK5.js +2193 -0
  36. package/dist/chunk-CZIVE6NT.cjs +354 -0
  37. package/dist/chunk-DNFJLJMW.mjs +354 -0
  38. package/dist/chunk-DNFO2EIZ.mjs +777 -0
  39. package/dist/chunk-EJ6BPYVR.mjs +416 -0
  40. package/dist/chunk-ENKODRU3.cjs +2193 -0
  41. package/dist/chunk-EOC4UHBS.mjs +229 -0
  42. package/dist/{chunk-BMH5AV44.js → chunk-FH2X7BVP.js} +756 -440
  43. package/dist/{chunk-PPUXIH5R.js → chunk-FHQGHPMO.mjs} +27 -13
  44. package/dist/{chunk-TGIFUAK4.cjs → chunk-GLE2WY7Z.cjs} +951 -635
  45. package/dist/{chunk-BDF4AMWX.mjs → chunk-GYM3LLGS.mjs} +756 -440
  46. package/dist/chunk-HLWLMW2F.mjs +2024 -0
  47. package/dist/chunk-JF5WGYJJ.cjs +194 -0
  48. package/dist/chunk-KH4SYAOS.mjs +1629 -0
  49. package/dist/chunk-KN32XNTH.mjs +313 -0
  50. package/dist/chunk-KQLYONSE.cjs +2871 -0
  51. package/dist/{chunk-STVLQ3XD.cjs → chunk-KZJQ723N.cjs} +92 -78
  52. package/dist/chunk-L2SYFEBS.js +194 -0
  53. package/dist/chunk-L6VB5N7Q.cjs +104 -0
  54. package/dist/{chunk-K6M7MDZ4.mjs → chunk-MBEJI5HF.mjs} +9 -5
  55. package/dist/chunk-MIIYDLGM.js +2874 -0
  56. package/dist/chunk-MOO4L7F4.mjs +104 -0
  57. package/dist/chunk-MT3OWDPC.mjs +2193 -0
  58. package/dist/chunk-MVGUEJ5Z.cjs +370 -0
  59. package/dist/chunk-OBGZSXTJ.cjs +10 -0
  60. package/dist/chunk-PD4EJTQC.cjs +229 -0
  61. package/dist/chunk-PWC3RBQE.mjs +300 -0
  62. package/dist/chunk-Q2I37RP3.cjs +1629 -0
  63. package/dist/chunk-RKGKFN2A.js +416 -0
  64. package/dist/{chunk-R3R2FVLG.cjs → chunk-SA6HUJVI.cjs} +5 -5
  65. package/dist/chunk-TRM4JUZQ.js +104 -0
  66. package/dist/chunk-UB4B6OFY.js +370 -0
  67. package/dist/{chunk-TO7IKXYT.js → chunk-UCUBNWM2.js} +1 -1
  68. package/dist/chunk-VN44DYYT.cjs +2024 -0
  69. package/dist/chunk-Y6FXYEAI.mjs +10 -0
  70. package/dist/client-CZHU674n.d.ts +820 -0
  71. package/dist/core/index.cjs +198 -4
  72. package/dist/core/index.d.ts +311 -212
  73. package/dist/core/index.js +237 -43
  74. package/dist/core/index.mjs +237 -43
  75. package/dist/{effect-CMOQKX8y.d.ts → effect-DIUHZ9IN.d.ts} +195 -1
  76. package/dist/effectRunner-CFLC32IK.cjs +8 -0
  77. package/dist/effectRunner-L4S7IPT3.js +8 -0
  78. package/dist/effectRunner-NNGG75QA.mjs +8 -0
  79. package/dist/http/index.cjs +1227 -2971
  80. package/dist/http/index.d.ts +826 -280
  81. package/dist/http/index.js +1089 -2833
  82. package/dist/http/index.mjs +1089 -2833
  83. package/dist/http/testing.cjs +161 -0
  84. package/dist/http/testing.d.ts +43 -0
  85. package/dist/http/testing.js +161 -0
  86. package/dist/http/testing.mjs +161 -0
  87. package/dist/index.cjs +486 -250
  88. package/dist/index.d.ts +87 -95
  89. package/dist/index.js +391 -155
  90. package/dist/index.mjs +391 -155
  91. package/dist/observability/index.cjs +162 -0
  92. package/dist/observability/index.d.ts +152 -0
  93. package/dist/observability/index.js +162 -0
  94. package/dist/observability/index.mjs +162 -0
  95. package/dist/perf/cli.cjs +401 -0
  96. package/dist/perf/cli.d.ts +1 -0
  97. package/dist/perf/cli.js +401 -0
  98. package/dist/perf/cli.mjs +401 -0
  99. package/dist/perf/index.cjs +141 -0
  100. package/dist/perf/index.d.ts +483 -0
  101. package/dist/perf/index.js +141 -0
  102. package/dist/perf/index.mjs +141 -0
  103. package/dist/schedule-CK3Ml_7p.d.ts +259 -0
  104. package/dist/schema/index.cjs +29 -0
  105. package/dist/schema/index.d.ts +179 -0
  106. package/dist/schema/index.js +29 -0
  107. package/dist/schema/index.mjs +29 -0
  108. package/dist/server-GJPg8ZSG.d.ts +675 -0
  109. package/dist/{stream-FQm9h4Mg.d.ts → stream-B4oK9JFP.d.ts} +1 -1
  110. package/dist/tracer-Hwt1cl7h.d.ts +189 -0
  111. package/dist/tracing-DqbTKGcf.d.ts +148 -0
  112. package/docs/ARCHITECTURE.md +292 -0
  113. package/docs/README.md +63 -0
  114. package/docs/adr/0001-ai-context-pack.md +32 -0
  115. package/docs/agent-apply-mode.md +104 -0
  116. package/docs/agent-approvals.md +110 -0
  117. package/docs/agent-batch.md +185 -0
  118. package/docs/agent-boundaries.md +112 -0
  119. package/docs/agent-chat-sessions.md +160 -0
  120. package/docs/agent-ci.md +17 -0
  121. package/docs/agent-cli.md +405 -0
  122. package/docs/agent-config.md +480 -0
  123. package/docs/agent-context-discovery.md +159 -0
  124. package/docs/agent-copilot-like-dx.md +126 -0
  125. package/docs/agent-declarative-optimized-planning.md +138 -0
  126. package/docs/agent-dx.md +224 -0
  127. package/docs/agent-env-files.md +126 -0
  128. package/docs/agent-follow-up-context.md +43 -0
  129. package/docs/agent-global-usage.md +180 -0
  130. package/docs/agent-init.md +109 -0
  131. package/docs/agent-install-and-configure.md +516 -0
  132. package/docs/agent-language-workspace-ux.md +99 -0
  133. package/docs/agent-llm-adapters.md +123 -0
  134. package/docs/agent-local-install.md +190 -0
  135. package/docs/agent-local-tests.md +51 -0
  136. package/docs/agent-observability.md +155 -0
  137. package/docs/agent-patch-quality-loop.md +162 -0
  138. package/docs/agent-presets.md +22 -0
  139. package/docs/agent-project-commands.md +237 -0
  140. package/docs/agent-project-intelligence.md +156 -0
  141. package/docs/agent-redaction.md +18 -0
  142. package/docs/agent-release-readiness.md +76 -0
  143. package/docs/agent-rollback-safety.md +162 -0
  144. package/docs/agent-rollback.md +23 -0
  145. package/docs/agent-run-artifacts.md +16 -0
  146. package/docs/agent-vscode-auto-discovery.md +137 -0
  147. package/docs/agent-vscode-batch-runner.md +100 -0
  148. package/docs/agent-vscode-chat-layout.md +90 -0
  149. package/docs/agent-vscode-clean-install.md +147 -0
  150. package/docs/agent-vscode-code-actions.md +70 -0
  151. package/docs/agent-vscode-diff-preview.md +45 -0
  152. package/docs/agent-vscode-inline-assist.md +56 -0
  153. package/docs/agent-vscode-install.md +186 -0
  154. package/docs/agent-vscode-model-setup.md +97 -0
  155. package/docs/agent-vscode-patch-preview.md +92 -0
  156. package/docs/agent-vscode-problems.md +79 -0
  157. package/docs/agent-vscode-project-dashboard.md +106 -0
  158. package/docs/agent-vscode-run-history.md +92 -0
  159. package/docs/agent-vscode-ux.md +73 -0
  160. package/docs/ai/INVARIANTS.md +84 -0
  161. package/docs/ai/PROJECT_MAP.md +338 -0
  162. package/docs/ai/PUBLIC_API.md +336 -0
  163. package/docs/ai/VALIDATION_MATRIX.md +67 -0
  164. package/docs/api-polish.md +37 -0
  165. package/docs/cancellation.md +162 -0
  166. package/docs/coverage.md +46 -0
  167. package/docs/getting-started.md +159 -0
  168. package/docs/guides/README.md +40 -0
  169. package/docs/guides/circuit-breaker.md +89 -0
  170. package/docs/guides/error-handling.md +91 -0
  171. package/docs/guides/getting-started.md +107 -0
  172. package/docs/guides/layers.md +189 -0
  173. package/docs/guides/metrics.md +101 -0
  174. package/docs/guides/resource-management.md +141 -0
  175. package/docs/guides/retry.md +215 -0
  176. package/docs/guides/semaphore.md +66 -0
  177. package/docs/guides/streams.md +117 -0
  178. package/docs/guides/supervisors.md +98 -0
  179. package/docs/guides/testing.md +162 -0
  180. package/docs/guides/tracing.md +71 -0
  181. package/docs/http-recipes.md +399 -0
  182. package/docs/http.md +749 -0
  183. package/docs/modules.md +285 -0
  184. package/docs/observability-collector-smoke.md +31 -0
  185. package/docs/observability-framework-examples.md +98 -0
  186. package/docs/observability.md +542 -0
  187. package/docs/otel-collector-smoke.yaml +27 -0
  188. package/docs/performance-profiler.md +199 -0
  189. package/docs/production-readiness.md +73 -0
  190. package/docs/recipes/README.md +12 -0
  191. package/docs/recipes/http-server.md +45 -0
  192. package/docs/recipes/layers.md +44 -0
  193. package/docs/recipes/performance.md +47 -0
  194. package/docs/recipes/runtime.md +41 -0
  195. package/docs/recipes/testing.md +41 -0
  196. package/docs/release.md +53 -0
  197. package/docs/wasm-bounded-queues.md +44 -0
  198. package/docs/wasm-engine-observability-benchmarks.md +85 -0
  199. package/docs/wasm-fiber-engine.md +117 -0
  200. package/docs/wasm-scheduler-state-machine.md +122 -0
  201. package/docs/wasm-stream-chunks.md +54 -0
  202. package/package.json +48 -2
  203. package/dist/chunk-AR22SXML.js +0 -1043
  204. package/dist/chunk-BDYEENHT.js +0 -224
  205. package/dist/chunk-JFPU5GQI.mjs +0 -1043
  206. package/dist/chunk-MS34J5LY.cjs +0 -224
  207. package/dist/chunk-UMAZLXAB.mjs +0 -224
  208. package/dist/chunk-XPZNXSVN.cjs +0 -1043
  209. package/dist/tracing-DNT9jEbr.d.ts +0 -106
@@ -0,0 +1,1629 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6;
2
+
3
+ var _chunk62AZW6UTcjs = require('./chunk-62AZW6UT.cjs');
4
+
5
+
6
+ var _chunkAGR5B2BCcjs = require('./chunk-AGR5B2BC.cjs');
7
+
8
+
9
+ var _chunk52PPNNI4cjs = require('./chunk-52PPNNI4.cjs');
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+ var _chunkGLE2WY7Zcjs = require('./chunk-GLE2WY7Z.cjs');
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+ var _chunkMVGUEJ5Zcjs = require('./chunk-MVGUEJ5Z.cjs');
30
+
31
+ // src/core/types/cancel.ts
32
+ function makeCancelToken() {
33
+ let cancelled = false;
34
+ const listeners = /* @__PURE__ */ new Set();
35
+ const cancel = () => {
36
+ if (cancelled) return;
37
+ cancelled = true;
38
+ listeners.forEach((f) => f());
39
+ listeners.clear();
40
+ };
41
+ return {
42
+ isCancelled: () => cancelled,
43
+ onCancel: (f) => {
44
+ if (cancelled) {
45
+ try {
46
+ f();
47
+ } catch (e2) {
48
+ }
49
+ return () => {
50
+ };
51
+ }
52
+ listeners.add(f);
53
+ return () => {
54
+ listeners.delete(f);
55
+ };
56
+ },
57
+ cancel
58
+ };
59
+ }
60
+ function linkAbortController(token, ac) {
61
+ return token.onCancel(() => ac.abort());
62
+ }
63
+
64
+ // src/core/runtime/dx.ts
65
+ function makeRuntime(env = {}, options = {}) {
66
+ return new (0, _chunkGLE2WY7Zcjs.Runtime)({ ...options, env });
67
+ }
68
+ function runPromise(effect, envOrRuntime) {
69
+ if (envOrRuntime instanceof _chunkGLE2WY7Zcjs.Runtime) return envOrRuntime.toPromise(effect);
70
+ return _chunkGLE2WY7Zcjs.toPromise.call(void 0, effect, envOrRuntime);
71
+ }
72
+ function runExit(effect, envOrRuntime) {
73
+ return new Promise((resolve) => {
74
+ if (envOrRuntime instanceof _chunkGLE2WY7Zcjs.Runtime) {
75
+ envOrRuntime.unsafeRunAsync(effect, resolve);
76
+ return;
77
+ }
78
+ _chunkGLE2WY7Zcjs.unsafeRunAsync.call(void 0, effect, envOrRuntime, resolve);
79
+ });
80
+ }
81
+ var runEffect = runPromise;
82
+
83
+ // src/core/runtime/linkedQueue.ts
84
+ var LinkedQueue = (_class = class {constructor() { _class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this); }
85
+ __init() {this.head = null}
86
+ __init2() {this.tail = null}
87
+ __init3() {this.len = 0}
88
+ get length() {
89
+ return this.len;
90
+ }
91
+ isEmpty() {
92
+ return this.len === 0;
93
+ }
94
+ push(value) {
95
+ const node = { value, next: null, prev: this.tail, removed: false };
96
+ if (this.tail) this.tail.next = node;
97
+ else this.head = node;
98
+ this.tail = node;
99
+ this.len++;
100
+ return node;
101
+ }
102
+ shift() {
103
+ const h = this.head;
104
+ if (!h) return void 0;
105
+ this.unlink(h);
106
+ return h.value;
107
+ }
108
+ remove(node) {
109
+ if (node.removed) return;
110
+ this.unlink(node);
111
+ }
112
+ unlink(node) {
113
+ node.removed = true;
114
+ const { prev, next } = node;
115
+ if (prev) prev.next = next;
116
+ else this.head = next;
117
+ if (next) next.prev = prev;
118
+ else this.tail = prev;
119
+ node.next = null;
120
+ node.prev = null;
121
+ this.len--;
122
+ }
123
+ }, _class);
124
+
125
+ // src/core/runtime/semaphore.ts
126
+ function makeSemaphore(n) {
127
+ const capacity = Math.max(1, Math.floor(n));
128
+ let available = capacity;
129
+ let totalAcquired = 0;
130
+ let totalReleased = 0;
131
+ const waiters = new LinkedQueue();
132
+ const acquire = () => {
133
+ return _chunkMVGUEJ5Zcjs.asyncEffect.call(void 0, (_env, cb) => {
134
+ if (available > 0) {
135
+ available--;
136
+ totalAcquired++;
137
+ cb({ _tag: "Success", value: void 0 });
138
+ return;
139
+ }
140
+ const node = waiters.push(cb);
141
+ return () => {
142
+ waiters.remove(node);
143
+ };
144
+ });
145
+ };
146
+ const release = () => {
147
+ totalReleased++;
148
+ if (waiters.length > 0) {
149
+ const waiter = waiters.shift();
150
+ totalAcquired++;
151
+ waiter({ _tag: "Success", value: void 0 });
152
+ return;
153
+ }
154
+ available++;
155
+ };
156
+ const acquirePermit = () => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0,
157
+ acquire(),
158
+ () => _chunkMVGUEJ5Zcjs.asyncEffect.call(void 0, (_env, cb) => {
159
+ let released = false;
160
+ const releaseOnce = () => {
161
+ if (released) return;
162
+ released = true;
163
+ release();
164
+ };
165
+ const fiber = _chunkGLE2WY7Zcjs.getCurrentFiber.call(void 0, );
166
+ _optionalChain([fiber, 'optionalAccess', _2 => _2.addFinalizer, 'call', _3 => _3(() => {
167
+ releaseOnce();
168
+ })]);
169
+ cb({ _tag: "Success", value: releaseOnce });
170
+ })
171
+ );
172
+ const withPermit = (effect) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0,
173
+ acquirePermit(),
174
+ (releaseOnce) => _chunkMVGUEJ5Zcjs.asyncFold.call(void 0,
175
+ effect,
176
+ (error) => {
177
+ releaseOnce();
178
+ return _chunkMVGUEJ5Zcjs.asyncFail.call(void 0, error);
179
+ },
180
+ (value) => {
181
+ releaseOnce();
182
+ return _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, value);
183
+ }
184
+ )
185
+ );
186
+ return {
187
+ capacity,
188
+ available: () => available,
189
+ waiting: () => waiters.length,
190
+ withPermit,
191
+ acquire,
192
+ release
193
+ };
194
+ }
195
+
196
+ // src/core/runtime/ref.ts
197
+ function makeRef(initial) {
198
+ let value = initial;
199
+ return {
200
+ get: () => _chunkMVGUEJ5Zcjs.asyncSync.call(void 0, () => value),
201
+ set: (v) => _chunkMVGUEJ5Zcjs.asyncSync.call(void 0, () => {
202
+ value = v;
203
+ }),
204
+ update: (f) => _chunkMVGUEJ5Zcjs.asyncSync.call(void 0, () => {
205
+ value = f(value);
206
+ return value;
207
+ }),
208
+ modify: (f) => _chunkMVGUEJ5Zcjs.asyncSync.call(void 0, () => {
209
+ const [result, next] = f(value);
210
+ value = next;
211
+ return result;
212
+ }),
213
+ unsafeGet: () => value
214
+ };
215
+ }
216
+ function derivedRef(parent, get, set) {
217
+ return {
218
+ get: () => _chunkMVGUEJ5Zcjs.asyncSync.call(void 0, () => get(parent.unsafeGet())),
219
+ set: (b) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0, parent.get(), (current) => parent.set(set(current, b))),
220
+ update: (f) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0, parent.get(), (parentVal) => {
221
+ const newB = f(get(parentVal));
222
+ return _chunkMVGUEJ5Zcjs.asyncMap.call(void 0, parent.set(set(parentVal, newB)), () => newB);
223
+ }),
224
+ modify: (f) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0, parent.get(), (parentVal) => {
225
+ const [result, newB] = f(get(parentVal));
226
+ return _chunkMVGUEJ5Zcjs.asyncMap.call(void 0, parent.set(set(parentVal, newB)), () => result);
227
+ }),
228
+ unsafeGet: () => get(parent.unsafeGet())
229
+ };
230
+ }
231
+
232
+ // src/core/runtime/shutdown.ts
233
+ async function gracefulShutdown(runtime, config = {}) {
234
+ const timeoutMs = _nullishCoalesce(config.timeoutMs, () => ( 3e4));
235
+ const startedAt = Date.now();
236
+ _optionalChain([config, 'access', _4 => _4.onStart, 'optionalCall', _5 => _5()]);
237
+ let timedOut = false;
238
+ const shutdownPromise = (async () => {
239
+ try {
240
+ await runtime.shutdown();
241
+ } catch (e3) {
242
+ }
243
+ })();
244
+ const timeoutPromise = new Promise((resolve) => {
245
+ setTimeout(() => {
246
+ timedOut = true;
247
+ resolve();
248
+ }, timeoutMs);
249
+ });
250
+ await Promise.race([shutdownPromise, timeoutPromise]);
251
+ const completedAt = Date.now();
252
+ const stats = {
253
+ startedAt,
254
+ completedAt,
255
+ elapsedMs: completedAt - startedAt,
256
+ timedOut
257
+ };
258
+ if (timedOut) {
259
+ _optionalChain([config, 'access', _6 => _6.onTimeout, 'optionalCall', _7 => _7(stats)]);
260
+ } else {
261
+ _optionalChain([config, 'access', _8 => _8.onComplete, 'optionalCall', _9 => _9(stats)]);
262
+ }
263
+ return stats;
264
+ }
265
+ function registerShutdownHooks(runtime, config = {}) {
266
+ let shuttingDown = false;
267
+ const handler = (signal) => {
268
+ if (shuttingDown) {
269
+ process.exit(1);
270
+ }
271
+ shuttingDown = true;
272
+ console.log(`
273
+ [brass-runtime] Received ${signal}, shutting down gracefully...`);
274
+ gracefulShutdown(runtime, {
275
+ ...config,
276
+ onComplete: (stats) => {
277
+ _optionalChain([config, 'access', _10 => _10.onComplete, 'optionalCall', _11 => _11(stats)]);
278
+ if (!config.onComplete) {
279
+ console.log(`[brass-runtime] Shutdown complete (${stats.elapsedMs}ms)`);
280
+ process.exit(0);
281
+ }
282
+ },
283
+ onTimeout: (stats) => {
284
+ _optionalChain([config, 'access', _12 => _12.onTimeout, 'optionalCall', _13 => _13(stats)]);
285
+ if (!config.onTimeout) {
286
+ console.log(`[brass-runtime] Shutdown timed out after ${stats.elapsedMs}ms, forcing exit`);
287
+ process.exit(1);
288
+ }
289
+ }
290
+ });
291
+ };
292
+ process.on("SIGTERM", () => handler("SIGTERM"));
293
+ process.on("SIGINT", () => handler("SIGINT"));
294
+ return () => {
295
+ process.removeAllListeners("SIGTERM");
296
+ process.removeAllListeners("SIGINT");
297
+ };
298
+ }
299
+
300
+ // src/core/runtime/testing.ts
301
+ var TestScheduler = (_class2 = class {
302
+ constructor(options = {}) {;_class2.prototype.__init4.call(this);_class2.prototype.__init5.call(this);_class2.prototype.__init6.call(this);_class2.prototype.__init7.call(this);_class2.prototype.__init8.call(this);_class2.prototype.__init9.call(this);_class2.prototype.__init10.call(this);_class2.prototype.__init11.call(this);
303
+ this.options = options;
304
+ this.maxSteps = _nullishCoalesce(options.maxSteps, () => ( 1e4));
305
+ }
306
+
307
+ __init4() {this.queue = []}
308
+
309
+ __init5() {this.autoFlushScheduled = false}
310
+ __init6() {this.flushing = false}
311
+ __init7() {this.enqueuedTasks = 0}
312
+ __init8() {this.executedTasks = 0}
313
+ __init9() {this.droppedTasks = 0}
314
+ __init10() {this.scheduledFlushes = 0}
315
+ __init11() {this.completedFlushes = 0}
316
+ schedule(task, tag = "anonymous") {
317
+ if (typeof task !== "function") {
318
+ this.droppedTasks += 1;
319
+ return "dropped";
320
+ }
321
+ this.queue.push({ tag, run: task });
322
+ this.enqueuedTasks += 1;
323
+ this.requestAutoFlush();
324
+ return "accepted";
325
+ }
326
+ scheduleBatch(tasks) {
327
+ return tasks.map(({ fn, tag }) => this.schedule(fn, tag));
328
+ }
329
+ stats() {
330
+ return {
331
+ engine: "ts",
332
+ fallbackUsed: false,
333
+ data: {
334
+ len: this.queue.length,
335
+ phase: this.flushing ? "flushing" : this.autoFlushScheduled ? "scheduled" : "idle",
336
+ scheduledFlushes: this.scheduledFlushes,
337
+ completedFlushes: this.completedFlushes,
338
+ enqueuedTasks: this.enqueuedTasks,
339
+ executedTasks: this.executedTasks,
340
+ droppedTasks: this.droppedTasks,
341
+ yieldedByBudget: 0,
342
+ lanes: [{
343
+ key: "test",
344
+ len: this.queue.length,
345
+ capacity: Number.POSITIVE_INFINITY,
346
+ enqueuedTasks: this.enqueuedTasks,
347
+ executedTasks: this.executedTasks,
348
+ droppedTasks: this.droppedTasks
349
+ }]
350
+ }
351
+ };
352
+ }
353
+ pending() {
354
+ return this.queue.slice();
355
+ }
356
+ size() {
357
+ return this.queue.length;
358
+ }
359
+ flush(maxTasks = 1) {
360
+ if (this.flushing) return 0;
361
+ this.flushing = true;
362
+ this.autoFlushScheduled = false;
363
+ let ran = 0;
364
+ try {
365
+ while (ran < maxTasks) {
366
+ const next = this.queue.shift();
367
+ if (!next) break;
368
+ ran += 1;
369
+ this.executedTasks += 1;
370
+ try {
371
+ next.run();
372
+ } catch (error) {
373
+ console.error(`[TestScheduler] task threw (tag=${next.tag})`, error);
374
+ }
375
+ }
376
+ return ran;
377
+ } finally {
378
+ this.flushing = false;
379
+ this.completedFlushes += ran > 0 ? 1 : 0;
380
+ if (this.queue.length > 0) this.requestAutoFlush();
381
+ }
382
+ }
383
+ flushAll(maxSteps = this.maxSteps) {
384
+ let ran = 0;
385
+ while (this.queue.length > 0) {
386
+ if (ran >= maxSteps) {
387
+ throw new Error(`TestScheduler.flushAll exceeded ${maxSteps} steps; possible runaway fiber loop`);
388
+ }
389
+ ran += this.flush(Math.max(1, maxSteps - ran));
390
+ }
391
+ return ran;
392
+ }
393
+ requestAutoFlush() {
394
+ const autoFlush = _nullishCoalesce(_nullishCoalesce(this.options.autoFlush, () => ( this.options.synchronous)), () => ( true));
395
+ if (!autoFlush || this.autoFlushScheduled || this.flushing) return;
396
+ this.autoFlushScheduled = true;
397
+ this.scheduledFlushes += 1;
398
+ queueMicrotask(() => {
399
+ if (!this.autoFlushScheduled) return;
400
+ this.flushAll();
401
+ });
402
+ }
403
+ }, _class2);
404
+ var TestClock = (_class3 = class {
405
+ constructor(initialTimeMs = 0, flushScheduler = () => void 0, maxSteps = 1e4) {;_class3.prototype.__init12.call(this);_class3.prototype.__init13.call(this);_class3.prototype.__init14.call(this);
406
+ this.flushScheduler = flushScheduler;
407
+ this.maxSteps = maxSteps;
408
+ this.nowMs = Math.max(0, Math.floor(initialTimeMs));
409
+ }
410
+
411
+
412
+
413
+ __init12() {this.nextId = 1}
414
+ __init13() {this.nextSeq = 1}
415
+ __init14() {this.timers = /* @__PURE__ */ new Map()}
416
+ now() {
417
+ return this.nowMs;
418
+ }
419
+ setTimeout(task, ms) {
420
+ const id = this.nextId++;
421
+ const delay = Math.max(0, Math.floor(ms));
422
+ this.timers.set(id, {
423
+ id,
424
+ dueAt: this.nowMs + delay,
425
+ seq: this.nextSeq++,
426
+ task
427
+ });
428
+ return id;
429
+ }
430
+ clearTimeout(timer) {
431
+ if (typeof timer === "number") this.timers.delete(timer);
432
+ }
433
+ pendingTimers() {
434
+ return Array.from(this.timers.values()).sort(compareTimers).map((timer) => ({
435
+ id: timer.id,
436
+ dueAt: timer.dueAt,
437
+ delayMs: Math.max(0, timer.dueAt - this.nowMs)
438
+ }));
439
+ }
440
+ adjust(ms) {
441
+ return this.advance(ms);
442
+ }
443
+ advance(ms) {
444
+ return this.advanceTo(this.nowMs + Math.max(0, Math.floor(ms)));
445
+ }
446
+ advanceTo(targetMs) {
447
+ const target = Math.max(this.nowMs, Math.floor(targetMs));
448
+ let ran = 0;
449
+ while (true) {
450
+ if (ran >= this.maxSteps) {
451
+ throw new Error(`TestClock.advanceTo exceeded ${this.maxSteps} timers; possible runaway timer loop`);
452
+ }
453
+ const next = this.nextDueTimer(target);
454
+ if (!next) break;
455
+ this.timers.delete(next.id);
456
+ this.nowMs = next.dueAt;
457
+ ran += 1;
458
+ next.task();
459
+ this.flushScheduler();
460
+ }
461
+ this.nowMs = target;
462
+ this.flushScheduler();
463
+ return ran;
464
+ }
465
+ runDue() {
466
+ return this.advanceTo(this.nowMs);
467
+ }
468
+ runAll(maxSteps = this.maxSteps) {
469
+ let ran = 0;
470
+ while (this.timers.size > 0) {
471
+ if (ran >= maxSteps) {
472
+ throw new Error(`TestClock.runAll exceeded ${maxSteps} timers; possible runaway timer loop`);
473
+ }
474
+ const next = this.nextDueTimer(Number.POSITIVE_INFINITY);
475
+ if (!next) break;
476
+ ran += this.advanceTo(next.dueAt);
477
+ }
478
+ return ran;
479
+ }
480
+ clear() {
481
+ this.timers.clear();
482
+ }
483
+ nextDueTimer(targetMs) {
484
+ let selected;
485
+ for (const timer of this.timers.values()) {
486
+ if (timer.dueAt > targetMs) continue;
487
+ if (!selected || compareTimers(timer, selected) < 0) selected = timer;
488
+ }
489
+ return selected;
490
+ }
491
+ }, _class3);
492
+ function compareTimers(a, b) {
493
+ return a.dueAt === b.dueAt ? a.seq - b.seq : a.dueAt - b.dueAt;
494
+ }
495
+ function makeTestRuntime(env, options = {}) {
496
+ const scheduler = new TestScheduler(options);
497
+ const clock = new TestClock(options.initialTimeMs, () => scheduler.flushAll(options.maxSteps), options.maxSteps);
498
+ const testEnv = withTestClock(_nullishCoalesce(env, () => ( {})), clock);
499
+ const runtime = _chunkGLE2WY7Zcjs.Runtime.makeWithEngine(testEnv, "ts", { scheduler });
500
+ const flush = (maxTasks) => scheduler.flush(maxTasks);
501
+ const flushAll = (maxSteps) => scheduler.flushAll(maxSteps);
502
+ const advance = (ms) => clock.advance(ms);
503
+ const advanceTo = (targetMs) => clock.advanceTo(targetMs);
504
+ const runDueTimers = () => clock.runDue();
505
+ const runAllTimers = (maxSteps) => clock.runAll(maxSteps);
506
+ const runExit2 = (effect) => {
507
+ const promise = new Promise((resolve) => {
508
+ runtime.unsafeRunAsync(effect, resolve);
509
+ });
510
+ flushAll();
511
+ return promise;
512
+ };
513
+ const run = async (effect) => exitToPromise(await runExit2(effect));
514
+ const fork = (effect) => {
515
+ const fiber = runtime.fork(effect);
516
+ flushAll();
517
+ return fiber;
518
+ };
519
+ return {
520
+ env: testEnv,
521
+ runtime,
522
+ scheduler,
523
+ clock,
524
+ run,
525
+ runExit: runExit2,
526
+ fork,
527
+ flush,
528
+ flushAll,
529
+ advance,
530
+ advanceTo,
531
+ runDueTimers,
532
+ runAllTimers
533
+ };
534
+ }
535
+ function withTestClock(env, clock) {
536
+ const current = env;
537
+ return {
538
+ ...env,
539
+ brass: {
540
+ ..._nullishCoalesce(current.brass, () => ( {})),
541
+ clock
542
+ }
543
+ };
544
+ }
545
+ function exitToPromise(exit) {
546
+ if (exit._tag === "Success") return exit.value;
547
+ const failure = _chunkMVGUEJ5Zcjs.Cause.firstFailure(exit.cause);
548
+ if (failure._tag === "Some") throw failure.value;
549
+ const defect = _chunkMVGUEJ5Zcjs.Cause.firstDefect(exit.cause);
550
+ if (defect._tag === "Some") {
551
+ throw defect.value instanceof Error ? defect.value : new Error(String(defect.value));
552
+ }
553
+ if (_chunkMVGUEJ5Zcjs.Cause.containsInterrupt(exit.cause)) throw new Error("Interrupted");
554
+ throw _chunkMVGUEJ5Zcjs.Cause.toError(exit.cause);
555
+ }
556
+ function runExitWithRuntime(runtime, effect) {
557
+ return new Promise((resolve) => {
558
+ runtime.unsafeRunAsync(effect, resolve);
559
+ });
560
+ }
561
+ function stableJson(value) {
562
+ return JSON.stringify(value);
563
+ }
564
+ function firstFailureValue(exit) {
565
+ if (exit._tag !== "Failure") return void 0;
566
+ const failure = _chunkMVGUEJ5Zcjs.Cause.firstFailure(exit.cause);
567
+ return failure._tag === "Some" ? failure.value : void 0;
568
+ }
569
+ function makeAssertionRuntime(runtime) {
570
+ return _nullishCoalesce(runtime, () => ( _chunkGLE2WY7Zcjs.Runtime.make({})));
571
+ }
572
+ async function assertSucceeds(effect, expected, runtime) {
573
+ const rt = makeAssertionRuntime(runtime);
574
+ const exit = await runExitWithRuntime(rt, effect);
575
+ if (exit._tag !== "Success") {
576
+ throw new Error(`Expected success with ${stableJson(expected)}, got failure: ${stableJson(exit.cause)}`);
577
+ }
578
+ if (stableJson(exit.value) !== stableJson(expected)) {
579
+ throw new Error(`Expected ${stableJson(expected)}, got ${stableJson(exit.value)}`);
580
+ }
581
+ }
582
+ async function assertFails(effect, expectedError, runtime) {
583
+ const rt = makeAssertionRuntime(runtime);
584
+ const exit = await runExitWithRuntime(rt, effect);
585
+ if (exit._tag !== "Failure") {
586
+ throw new Error(`Expected failure with ${stableJson(expectedError)}, got success: ${stableJson(exit.value)}`);
587
+ }
588
+ const error = firstFailureValue(exit);
589
+ if (stableJson(error) !== stableJson(expectedError)) {
590
+ throw new Error(`Expected error ${stableJson(expectedError)}, got ${stableJson(error)}`);
591
+ }
592
+ }
593
+ async function assertFailsWith(effect, predicate, runtime) {
594
+ const rt = makeAssertionRuntime(runtime);
595
+ const exit = await runExitWithRuntime(rt, effect);
596
+ if (exit._tag !== "Failure") {
597
+ throw new Error(`Expected failure, got success: ${stableJson(exit.value)}`);
598
+ }
599
+ const error = firstFailureValue(exit);
600
+ if (error === void 0 || !predicate(error)) {
601
+ throw new Error(`Error did not match predicate: ${stableJson(error)}`);
602
+ }
603
+ }
604
+ async function assertCompletesWithin(effect, maxMs, runtime) {
605
+ const rt = makeAssertionRuntime(runtime);
606
+ const start = _chunkGLE2WY7Zcjs.runtimeClockFromEnv.call(void 0, rt.env).now();
607
+ const result = await rt.toPromise(effect);
608
+ const elapsed = _chunkGLE2WY7Zcjs.runtimeClockFromEnv.call(void 0, rt.env).now() - start;
609
+ if (elapsed > maxMs) {
610
+ throw new Error(`Effect took ${elapsed.toFixed(1)}ms, expected < ${maxMs}ms`);
611
+ }
612
+ return result;
613
+ }
614
+ function flakyEffect(failCount, successValue, errorValue) {
615
+ let calls = 0;
616
+ return _chunkMVGUEJ5Zcjs.asyncEffect.call(void 0, (_env, cb) => {
617
+ calls++;
618
+ if (calls <= failCount) {
619
+ cb(_chunkMVGUEJ5Zcjs.Exit.failCause(_chunkMVGUEJ5Zcjs.Cause.fail(errorValue)));
620
+ } else {
621
+ cb(_chunkMVGUEJ5Zcjs.Exit.succeed(successValue));
622
+ }
623
+ });
624
+ }
625
+ function delayedEffect(ms, value) {
626
+ return _chunkMVGUEJ5Zcjs.asyncEffect.call(void 0, (env, cb) => {
627
+ const clock = _chunkGLE2WY7Zcjs.runtimeClockFromEnv.call(void 0, env);
628
+ const id = clock.setTimeout(() => cb(_chunkMVGUEJ5Zcjs.Exit.succeed(value)), ms);
629
+ return () => clock.clearTimeout(id);
630
+ });
631
+ }
632
+ function neverEffect() {
633
+ return _chunkMVGUEJ5Zcjs.asyncEffect.call(void 0, () => {
634
+ return () => {
635
+ };
636
+ });
637
+ }
638
+
639
+ // src/core/runtime/layer.ts
640
+ var MissingLayerServiceError = (_class4 = class extends Error {
641
+ __init15() {this._tag = "MissingLayerService"}
642
+
643
+ constructor(serviceName) {
644
+ super(`Missing layer service '${serviceName}'. Add a layer that provides this ServiceTag or pass a LayerContext containing it.`);_class4.prototype.__init15.call(this);;
645
+ this.name = "MissingLayerServiceError";
646
+ this.serviceName = serviceName;
647
+ }
648
+ }, _class4);
649
+ function formatLayerError(error) {
650
+ if (error instanceof MissingLayerServiceError) return error.message;
651
+ if (isObjectRecord(error) && error._tag === "MissingLayerService" && typeof error.serviceName === "string") {
652
+ return `Missing layer service '${error.serviceName}'. Add the provider layer before using the service.`;
653
+ }
654
+ return error instanceof Error ? error.message : String(error);
655
+ }
656
+ function makeServiceTag(name) {
657
+ return {
658
+ _tag: "ServiceTag",
659
+ key: Symbol(name),
660
+ name
661
+ };
662
+ }
663
+ var serviceTag = makeServiceTag;
664
+ var defineService = makeServiceTag;
665
+ var LayerContext = class _LayerContext {
666
+
667
+ constructor(entries) {
668
+ if (entries instanceof Map) {
669
+ this.services = new Map(entries);
670
+ return;
671
+ }
672
+ this.services = /* @__PURE__ */ new Map();
673
+ if (!entries) return;
674
+ for (const [tag, service] of entries) this.services.set(tag.key, service);
675
+ }
676
+ static empty() {
677
+ return new _LayerContext();
678
+ }
679
+ get(tag) {
680
+ return this.services.get(tag.key);
681
+ }
682
+ unsafeGet(tag) {
683
+ if (!this.services.has(tag.key)) {
684
+ throw new MissingLayerServiceError(tag.name);
685
+ }
686
+ return this.services.get(tag.key);
687
+ }
688
+ has(tag) {
689
+ return this.services.has(tag.key);
690
+ }
691
+ add(tag, service) {
692
+ const next = new Map(this.services);
693
+ next.set(tag.key, service);
694
+ return new _LayerContext(next);
695
+ }
696
+ merge(other) {
697
+ const next = new Map(this.services);
698
+ for (const [key, service] of other.services) next.set(key, service);
699
+ return new _LayerContext(next);
700
+ }
701
+ size() {
702
+ return this.services.size;
703
+ }
704
+ };
705
+ function makeLayerScope() {
706
+ const cache = /* @__PURE__ */ new WeakMap();
707
+ const finalizers = [];
708
+ let closed = false;
709
+ const scope = {
710
+ get: (l, deps) => {
711
+ if (closed) return _chunkMVGUEJ5Zcjs.asyncFail.call(void 0, new Error("LayerScope is closed"));
712
+ if (cache.has(l)) return _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, cache.get(l));
713
+ const built = l.buildScoped ? l.buildScoped(deps, scope) : _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0,
714
+ l.build(deps),
715
+ ({ service, release }) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0, scope.addFinalizer(release), () => _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, service))
716
+ );
717
+ return _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0,
718
+ built,
719
+ (service) => _chunkMVGUEJ5Zcjs.asyncSync.call(void 0, () => {
720
+ cache.set(l, service);
721
+ return service;
722
+ })
723
+ );
724
+ },
725
+ close: () => {
726
+ if (closed) return _chunkMVGUEJ5Zcjs.unit.call(void 0, );
727
+ closed = true;
728
+ return releaseAll(finalizers);
729
+ },
730
+ size: () => finalizers.length,
731
+ addFinalizer: (release) => _chunkMVGUEJ5Zcjs.asyncSync.call(void 0, () => {
732
+ if (!closed) finalizers.push(release);
733
+ })
734
+ };
735
+ return scope;
736
+ }
737
+ function releaseAll(finalizers) {
738
+ const next = finalizers.pop();
739
+ if (!next) return _chunkMVGUEJ5Zcjs.unit.call(void 0, );
740
+ return _chunkMVGUEJ5Zcjs.asyncFold.call(void 0,
741
+ next(),
742
+ () => releaseAll(finalizers),
743
+ () => releaseAll(finalizers)
744
+ );
745
+ }
746
+ function mergeServices(a, b) {
747
+ if (a instanceof LayerContext && b instanceof LayerContext) {
748
+ return a.merge(b);
749
+ }
750
+ if (isObjectRecord(a) && isObjectRecord(b)) {
751
+ return { ...a, ...b };
752
+ }
753
+ return Object.assign({}, a, b);
754
+ }
755
+ function isObjectRecord(value) {
756
+ return typeof value === "object" && value !== null;
757
+ }
758
+ function layer(acquire, release) {
759
+ return {
760
+ _tag: "Layer",
761
+ build: (_deps) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0, acquire(), (service) => _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, {
762
+ service,
763
+ release: release ? () => release(service) : () => _chunkMVGUEJ5Zcjs.unit.call(void 0, )
764
+ }))
765
+ };
766
+ }
767
+ function layerValue(tag, value) {
768
+ return layerEffect(tag, () => _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, value));
769
+ }
770
+ function layerEffect(tag, acquire, release) {
771
+ return {
772
+ _tag: "Layer",
773
+ build: (deps = LayerContext.empty()) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0, acquire(deps), (service) => _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, {
774
+ service: deps.add(tag, service),
775
+ release: release ? () => release(service) : () => _chunkMVGUEJ5Zcjs.unit.call(void 0, )
776
+ }))
777
+ };
778
+ }
779
+ var layerFromContext = layerEffect;
780
+ var defineLayer = layerEffect;
781
+ function getService(tag) {
782
+ return _chunkMVGUEJ5Zcjs.asyncSync.call(void 0, (context) => context.unsafeGet(tag));
783
+ }
784
+ function layerFrom() {
785
+ return (acquire, release) => ({
786
+ _tag: "Layer",
787
+ build: (deps) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0, acquire(deps), (service) => _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, {
788
+ service,
789
+ release: release ? () => release(service) : () => _chunkMVGUEJ5Zcjs.unit.call(void 0, )
790
+ }))
791
+ });
792
+ }
793
+ function layerSucceed(value) {
794
+ return {
795
+ _tag: "Layer",
796
+ build: () => _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, { service: value, release: () => _chunkMVGUEJ5Zcjs.unit.call(void 0, ) })
797
+ };
798
+ }
799
+ function layerFail(error) {
800
+ return {
801
+ _tag: "Layer",
802
+ build: () => _chunkMVGUEJ5Zcjs.asyncFail.call(void 0, error)
803
+ };
804
+ }
805
+ function compose(from, to) {
806
+ return {
807
+ _tag: "Layer",
808
+ buildScoped: (deps, scope) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0,
809
+ scope.get(from, deps),
810
+ (mid) => scope.get(to, mid)
811
+ ),
812
+ build: (deps) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0,
813
+ from.build(deps),
814
+ ({ service: mid, release: releaseMid }) => _chunkMVGUEJ5Zcjs.asyncFold.call(void 0,
815
+ to.build(mid),
816
+ (error) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0, releaseMid(), () => _chunkMVGUEJ5Zcjs.asyncFail.call(void 0, error)),
817
+ ({ service: out, release: releaseOut }) => _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, {
818
+ service: out,
819
+ release: () => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0, releaseOut(), () => releaseMid())
820
+ })
821
+ )
822
+ )
823
+ };
824
+ }
825
+ function merge(left, right) {
826
+ return {
827
+ _tag: "Layer",
828
+ buildScoped: (deps, scope) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0,
829
+ scope.get(left, deps),
830
+ (a) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0,
831
+ scope.get(right, deps),
832
+ (b) => _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, mergeServices(a, b))
833
+ )
834
+ ),
835
+ build: (deps) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0,
836
+ left.build(deps),
837
+ ({ service: a, release: releaseA }) => _chunkMVGUEJ5Zcjs.asyncFold.call(void 0,
838
+ right.build(deps),
839
+ (error) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0, releaseA(), () => _chunkMVGUEJ5Zcjs.asyncFail.call(void 0, error)),
840
+ ({ service: b, release: releaseB }) => _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, {
841
+ service: mergeServices(a, b),
842
+ release: () => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0, releaseB(), () => releaseA())
843
+ })
844
+ )
845
+ )
846
+ };
847
+ }
848
+ function mapLayer(l, f) {
849
+ return {
850
+ _tag: "Layer",
851
+ buildScoped: (deps, scope) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0,
852
+ scope.get(l, deps),
853
+ (service) => _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, f(service))
854
+ ),
855
+ build: (deps) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0,
856
+ l.build(deps),
857
+ ({ service, release }) => _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, { service: f(service), release })
858
+ )
859
+ };
860
+ }
861
+ function buildLayer(l, deps) {
862
+ const scope = makeLayerScope();
863
+ return _chunkMVGUEJ5Zcjs.asyncFold.call(void 0,
864
+ scope.get(l, deps),
865
+ (error) => _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0, scope.close(), () => _chunkMVGUEJ5Zcjs.asyncFail.call(void 0, error)),
866
+ (service) => _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, {
867
+ service,
868
+ scope,
869
+ close: scope.close,
870
+ use: (body) => body(service)
871
+ })
872
+ );
873
+ }
874
+ function provideLayer(l, use, deps) {
875
+ return _chunkMVGUEJ5Zcjs.asyncFlatMap.call(void 0,
876
+ buildLayer(l, _nullishCoalesce(deps, () => ( {}))),
877
+ ({ service, close }) => _chunk62AZW6UTcjs.ensuring.call(void 0,
878
+ use(service),
879
+ () => close()
880
+ )
881
+ );
882
+ }
883
+ function provideLayerContext(l, use, deps = LayerContext.empty()) {
884
+ return provideLayer(l, use, deps);
885
+ }
886
+ var provide = provideLayer;
887
+ var provideContext = provideLayerContext;
888
+ var Layer = Object.freeze({
889
+ make: layer,
890
+ from: layerFrom,
891
+ succeed: layerSucceed,
892
+ fail: layerFail,
893
+ value: layerValue,
894
+ effect: layerEffect,
895
+ define: defineLayer,
896
+ fromContext: layerFromContext,
897
+ compose,
898
+ merge,
899
+ map: mapLayer,
900
+ provide: provideLayer,
901
+ provideContext: provideLayerContext,
902
+ build: buildLayer,
903
+ scope: makeLayerScope,
904
+ context: LayerContext.empty,
905
+ tag: makeServiceTag,
906
+ service: getService
907
+ });
908
+
909
+ // src/core/runtime/workerPool.ts
910
+ function makeWorkerPool(config = {}) {
911
+ const size = _nullishCoalesce(config.size, () => ( 4));
912
+ const maxQueue = _nullishCoalesce(config.maxQueue, () => ( 1e3));
913
+ const taskTimeoutMs = _nullishCoalesce(config.taskTimeoutMs, () => ( 3e4));
914
+ let closed = false;
915
+ let busy = 0;
916
+ let completed = 0;
917
+ let failed = 0;
918
+ let timedOut = 0;
919
+ const queue = [];
920
+ const processNext = () => {
921
+ if (queue.length === 0 || busy >= size) return;
922
+ const task = queue.shift();
923
+ busy++;
924
+ setImmediate(() => {
925
+ if (task.timeoutId) clearTimeout(task.timeoutId);
926
+ try {
927
+ const result = task.fn();
928
+ busy--;
929
+ completed++;
930
+ task.resolve(result);
931
+ processNext();
932
+ } catch (e) {
933
+ busy--;
934
+ failed++;
935
+ task.reject({ _tag: "WorkerTaskError", message: String(e) });
936
+ processNext();
937
+ }
938
+ });
939
+ };
940
+ const execute = (fn) => {
941
+ if (closed) return _chunkMVGUEJ5Zcjs.asyncFail.call(void 0, { _tag: "WorkerPoolClosed" });
942
+ if (queue.length >= maxQueue) {
943
+ return _chunkMVGUEJ5Zcjs.asyncFail.call(void 0, { _tag: "WorkerPoolFull", queued: queue.length });
944
+ }
945
+ return _chunkMVGUEJ5Zcjs.asyncEffect.call(void 0, (_env, cb) => {
946
+ const task = {
947
+ fn,
948
+ resolve: (value) => cb({ _tag: "Success", value }),
949
+ reject: (error) => cb({ _tag: "Failure", cause: { _tag: "Fail", error } })
950
+ };
951
+ task.timeoutId = setTimeout(() => {
952
+ const idx = queue.indexOf(task);
953
+ if (idx >= 0) {
954
+ queue.splice(idx, 1);
955
+ timedOut++;
956
+ task.reject({ _tag: "WorkerTaskTimeout", ms: taskTimeoutMs });
957
+ }
958
+ }, taskTimeoutMs);
959
+ queue.push(task);
960
+ processNext();
961
+ return () => {
962
+ const idx = queue.indexOf(task);
963
+ if (idx >= 0) {
964
+ queue.splice(idx, 1);
965
+ if (task.timeoutId) clearTimeout(task.timeoutId);
966
+ }
967
+ };
968
+ });
969
+ };
970
+ const run = (taskSource, args = []) => {
971
+ return execute(() => {
972
+ const fn = new Function(...args.map((_, i) => `arg${i}`), taskSource);
973
+ return fn(...args);
974
+ });
975
+ };
976
+ return {
977
+ execute,
978
+ run,
979
+ stats: () => ({
980
+ size,
981
+ busy,
982
+ idle: size - busy,
983
+ queued: queue.length,
984
+ completed,
985
+ failed,
986
+ timedOut
987
+ }),
988
+ shutdown: async () => {
989
+ closed = true;
990
+ while (queue.length > 0) {
991
+ const task = queue.shift();
992
+ if (task.timeoutId) clearTimeout(task.timeoutId);
993
+ task.reject({ _tag: "WorkerPoolClosed" });
994
+ }
995
+ }
996
+ };
997
+ }
998
+
999
+ // src/core/runtime/tracing.ts
1000
+ var idCounter = 0;
1001
+ function generateId() {
1002
+ return (++idCounter).toString(16).padStart(16, "0");
1003
+ }
1004
+ function makeTracer(config) {
1005
+ const completedSpans = [];
1006
+ const sampleRate = _nullishCoalesce(config.sampleRate, () => ( 1));
1007
+ const shouldSample = () => {
1008
+ if (sampleRate >= 1) return true;
1009
+ if (sampleRate <= 0) return false;
1010
+ return Math.random() < sampleRate;
1011
+ };
1012
+ const span = (name, effect, attributes) => {
1013
+ if (!shouldSample()) return effect;
1014
+ const spanObj = {
1015
+ name,
1016
+ context: {
1017
+ traceId: generateId(),
1018
+ spanId: generateId()
1019
+ },
1020
+ startTime: performance.now(),
1021
+ status: "unset",
1022
+ attributes: { "service.name": config.serviceName, ...attributes },
1023
+ events: []
1024
+ };
1025
+ return _chunkMVGUEJ5Zcjs.asyncFold.call(void 0,
1026
+ effect,
1027
+ (error) => {
1028
+ spanObj.endTime = performance.now();
1029
+ spanObj.status = "error";
1030
+ spanObj.events.push({
1031
+ name: "error",
1032
+ time: performance.now(),
1033
+ attributes: { "error.message": String(error) }
1034
+ });
1035
+ completedSpans.push(spanObj);
1036
+ _optionalChain([config, 'access', _14 => _14.onSpanEnd, 'optionalCall', _15 => _15(spanObj)]);
1037
+ return _chunkMVGUEJ5Zcjs.asyncFail.call(void 0, error);
1038
+ },
1039
+ (value) => {
1040
+ spanObj.endTime = performance.now();
1041
+ spanObj.status = "ok";
1042
+ completedSpans.push(spanObj);
1043
+ _optionalChain([config, 'access', _16 => _16.onSpanEnd, 'optionalCall', _17 => _17(spanObj)]);
1044
+ return _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, value);
1045
+ }
1046
+ );
1047
+ };
1048
+ return {
1049
+ span,
1050
+ spans: () => completedSpans,
1051
+ clear: () => {
1052
+ completedSpans.length = 0;
1053
+ }
1054
+ };
1055
+ }
1056
+
1057
+ // src/core/runtime/loggerSink.ts
1058
+ function consoleJsonLogger() {
1059
+ return {
1060
+ emit(ev, ctx) {
1061
+ if (ev.type !== "log") return;
1062
+ const wallTs = Date.now();
1063
+ const out = {
1064
+ level: ev.level,
1065
+ msg: ev.message,
1066
+ wallTs,
1067
+ fiberId: ctx.fiberId,
1068
+ scopeId: ctx.scopeId,
1069
+ traceId: ctx.traceId,
1070
+ spanId: ctx.spanId,
1071
+ parentSpanId: ctx.parentSpanId,
1072
+ ..._nullishCoalesce(ev.fields, () => ( {}))
1073
+ };
1074
+ if (ev.level === "error") console.error(JSON.stringify(out));
1075
+ else console.log(JSON.stringify(out));
1076
+ }
1077
+ };
1078
+ }
1079
+
1080
+ // src/core/runtime/registry.ts
1081
+ var RuntimeRegistry = (_class5 = class {constructor() { _class5.prototype.__init16.call(this);_class5.prototype.__init17.call(this);_class5.prototype.__init18.call(this);_class5.prototype.__init19.call(this);_class5.prototype.__init20.call(this); }
1082
+ __init16() {this.fibers = /* @__PURE__ */ new Map()}
1083
+ __init17() {this.scopes = /* @__PURE__ */ new Map()}
1084
+ __init18() {this.seq = 1}
1085
+ __init19() {this.recent = []}
1086
+ __init20() {this.recentCap = 2e3}
1087
+ emit(ev, ctx) {
1088
+ const rec = _chunk52PPNNI4cjs.makeRuntimeEventRecord.call(void 0, ev, ctx, this.seq++);
1089
+ this.recent.push(rec);
1090
+ if (this.recent.length > this.recentCap) this.recent.shift();
1091
+ switch (rec.type) {
1092
+ case "fiber.start": {
1093
+ const id = rec.fiberId;
1094
+ this.fibers.set(id, {
1095
+ fiberId: id,
1096
+ parentFiberId: rec.parentFiberId,
1097
+ name: rec.name,
1098
+ runState: "Running",
1099
+ status: "Running",
1100
+ createdAt: rec.wallTs,
1101
+ lastActiveAt: rec.wallTs,
1102
+ scopeId: rec.scopeId,
1103
+ traceId: rec.traceId,
1104
+ spanId: rec.spanId
1105
+ });
1106
+ break;
1107
+ }
1108
+ case "fiber.suspend": {
1109
+ const f = this.fibers.get(rec.fiberId);
1110
+ if (f) {
1111
+ f.runState = "Suspended";
1112
+ f.lastActiveAt = rec.wallTs;
1113
+ f.awaiting = { reason: _nullishCoalesce(rec.reason, () => ( "unknown")) };
1114
+ }
1115
+ break;
1116
+ }
1117
+ case "fiber.resume": {
1118
+ const f = this.fibers.get(rec.fiberId);
1119
+ if (f) {
1120
+ f.runState = "Running";
1121
+ f.lastActiveAt = rec.wallTs;
1122
+ f.awaiting = void 0;
1123
+ }
1124
+ break;
1125
+ }
1126
+ case "fiber.end": {
1127
+ const f = this.fibers.get(rec.fiberId);
1128
+ if (f) {
1129
+ f.runState = "Done";
1130
+ f.lastActiveAt = rec.wallTs;
1131
+ f.status = rec.status === "interrupted" ? "Interrupted" : "Done";
1132
+ f.lastEnd = { status: rec.status, error: formatRegistryError(rec.error) };
1133
+ }
1134
+ break;
1135
+ }
1136
+ case "scope.open": {
1137
+ const sid = rec.scopeId;
1138
+ this.scopes.set(sid, {
1139
+ scopeId: sid,
1140
+ parentScopeId: rec.parentScopeId,
1141
+ ownerFiberId: rec.fiberId,
1142
+ openAt: rec.wallTs,
1143
+ finalizers: []
1144
+ });
1145
+ break;
1146
+ }
1147
+ case "scope.close": {
1148
+ const s = this.scopes.get(rec.scopeId);
1149
+ if (s) s.closedAt = rec.wallTs;
1150
+ break;
1151
+ }
1152
+ }
1153
+ }
1154
+ getRecentEvents() {
1155
+ return this.recent.slice();
1156
+ }
1157
+ }, _class5);
1158
+ function formatRegistryError(error) {
1159
+ if (error === void 0) return void 0;
1160
+ if (_chunkMVGUEJ5Zcjs.Cause.isCause(error)) return _chunkMVGUEJ5Zcjs.Cause.pretty(error, { singleLine: true });
1161
+ if (error instanceof Error) return error.message;
1162
+ if (typeof error === "string") return error;
1163
+ try {
1164
+ return JSON.stringify(error);
1165
+ } catch (e4) {
1166
+ return String(error);
1167
+ }
1168
+ }
1169
+
1170
+ // src/core/runtime/dump.ts
1171
+ function dumpAllFibers(reg) {
1172
+ const fibers = Array.from(reg.fibers.values());
1173
+ fibers.sort((a, b) => a.runState === b.runState ? b.lastActiveAt - a.lastActiveAt : a.runState.localeCompare(b.runState));
1174
+ const lines = [];
1175
+ lines.push(`=== Fiber Dump (${(/* @__PURE__ */ new Date()).toISOString()}) ===`);
1176
+ for (const f of fibers) {
1177
+ lines.push(
1178
+ `fiber#${f.fiberId} ${_nullishCoalesce(f.name, () => ( ""))} run=${f.runState} status=${f.status} scope=${_nullishCoalesce(f.scopeId, () => ( "-"))} trace=${_nullishCoalesce(f.traceId, () => ( "-"))} span=${_nullishCoalesce(f.spanId, () => ( "-"))} last=${new Date(f.lastActiveAt).toISOString()}`
1179
+ );
1180
+ if (f.awaiting) lines.push(` awaiting: ${f.awaiting.reason}${f.awaiting.detail ? ` (${f.awaiting.detail})` : ""}`);
1181
+ if (_optionalChain([f, 'access', _18 => _18.lastEnd, 'optionalAccess', _19 => _19.error])) lines.push(` end.error: ${f.lastEnd.error}`);
1182
+ }
1183
+ lines.push(`=== Recent Events ===`);
1184
+ for (const ev of reg.getRecentEvents().slice(-80)) {
1185
+ lines.push(
1186
+ `${ev.seq} ${new Date(ev.wallTs).toISOString()} ${ev.type} fiber=${_nullishCoalesce(ev.fiberId, () => ( "-"))} scope=${_nullishCoalesce(ev.scopeId, () => ( "-"))} trace=${_nullishCoalesce(ev.traceId, () => ( "-"))}`
1187
+ );
1188
+ }
1189
+ return lines.join("\n");
1190
+ }
1191
+
1192
+ // src/core/runtime/tracer.ts
1193
+ var defaultTracer = {
1194
+ newTraceId: () => crypto.randomUUID(),
1195
+ newSpanId: () => crypto.randomUUID()
1196
+ };
1197
+
1198
+ // src/core/types/typedError.ts
1199
+ function catchTag(effect, tag, handler) {
1200
+ return _chunkMVGUEJ5Zcjs.asyncFold.call(void 0,
1201
+ effect,
1202
+ (error) => {
1203
+ if (typeof error === "object" && error !== null && "_tag" in error && error._tag === tag) {
1204
+ return handler(error);
1205
+ }
1206
+ return _chunkMVGUEJ5Zcjs.asyncFail.call(void 0, error);
1207
+ },
1208
+ (value) => _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, value)
1209
+ );
1210
+ }
1211
+ function catchTags(effect, handlers) {
1212
+ return _chunkMVGUEJ5Zcjs.asyncFold.call(void 0,
1213
+ effect,
1214
+ (error) => {
1215
+ if (typeof error === "object" && error !== null && "_tag" in error) {
1216
+ const handler = handlers[error._tag];
1217
+ if (handler) return handler(error);
1218
+ }
1219
+ return _chunkMVGUEJ5Zcjs.asyncFail.call(void 0, error);
1220
+ },
1221
+ (value) => _chunkMVGUEJ5Zcjs.asyncSucceed.call(void 0, value)
1222
+ );
1223
+ }
1224
+ function mapError(effect, f) {
1225
+ return _chunkMVGUEJ5Zcjs.asyncFold.call(void 0, effect, (error) => _chunkMVGUEJ5Zcjs.asyncFail.call(void 0, f(error)), _chunkMVGUEJ5Zcjs.asyncSucceed);
1226
+ }
1227
+ function tagError(effect, tag, enrich) {
1228
+ return _chunkMVGUEJ5Zcjs.asyncFold.call(void 0,
1229
+ effect,
1230
+ (error) => {
1231
+ const fields = enrich ? enrich(error) : {};
1232
+ return _chunkMVGUEJ5Zcjs.asyncFail.call(void 0, { _tag: tag, ...fields });
1233
+ },
1234
+ _chunkMVGUEJ5Zcjs.asyncSucceed
1235
+ );
1236
+ }
1237
+ function orElse(effect, fallback) {
1238
+ return _chunkMVGUEJ5Zcjs.asyncFold.call(void 0, effect, fallback, _chunkMVGUEJ5Zcjs.asyncSucceed);
1239
+ }
1240
+
1241
+ // src/core/runtime/supervisor.ts
1242
+ var nextSupervisorId = 1;
1243
+ var nextChildId = 1;
1244
+ var Supervisor = (_class6 = class {
1245
+ constructor(runtime, config = {}) {;_class6.prototype.__init21.call(this);_class6.prototype.__init22.call(this);_class6.prototype.__init23.call(this);
1246
+ this.runtime = runtime;
1247
+ this.strategy = _nullishCoalesce(config.strategy, () => ( "one-for-one"));
1248
+ this.restart = resolveRestartPolicy(_nullishCoalesce(config.restart, () => ( "on-failure")));
1249
+ this.escalation = _nullishCoalesce(config.escalation, () => ( "shutdown"));
1250
+ this.clock = _nullishCoalesce(config.clock, () => ( Date.now));
1251
+ this.onEvent = config.onEvent;
1252
+ }
1253
+
1254
+ __init21() {this.id = nextSupervisorId++}
1255
+ __init22() {this.records = /* @__PURE__ */ new Map()}
1256
+
1257
+
1258
+
1259
+
1260
+
1261
+ __init23() {this.closed = false}
1262
+ start(spec) {
1263
+ if (this.closed) throw new Error("Supervisor is shut down");
1264
+ const record = {
1265
+ id: nextChildId++,
1266
+ name: spec.name,
1267
+ spec,
1268
+ restart: resolveRestartPolicy(_nullishCoalesce(spec.restart, () => ( this.restart))),
1269
+ status: "running",
1270
+ restartCount: 0,
1271
+ restartTimes: [],
1272
+ generation: 0,
1273
+ plannedRestart: false,
1274
+ joiners: []
1275
+ };
1276
+ this.records.set(record.id, record);
1277
+ this.launch(record);
1278
+ return this.handle(record);
1279
+ }
1280
+ startAll(specs) {
1281
+ return specs.map((spec) => this.start(spec));
1282
+ }
1283
+ shutdown() {
1284
+ return _chunkMVGUEJ5Zcjs.asyncEffect.call(void 0, (_env, cb) => {
1285
+ this.closed = true;
1286
+ this.emit({ type: "shutdown", supervisorId: this.id });
1287
+ const records = [...this.records.values()];
1288
+ let remaining = records.filter((record) => record.current !== void 0).length;
1289
+ for (const record of records) {
1290
+ if (record.timer) {
1291
+ clearTimeout(record.timer);
1292
+ record.timer = void 0;
1293
+ }
1294
+ record.plannedRestart = false;
1295
+ if (record.current) {
1296
+ record.status = "interrupted";
1297
+ record.current.interrupt();
1298
+ } else if (!record.terminalExit) {
1299
+ this.finish(record, interruptExit());
1300
+ }
1301
+ }
1302
+ if (remaining === 0) {
1303
+ cb({ _tag: "Success", value: void 0 });
1304
+ return;
1305
+ }
1306
+ for (const record of records) {
1307
+ _optionalChain([record, 'access', _20 => _20.current, 'optionalAccess', _21 => _21.join, 'call', _22 => _22(() => {
1308
+ remaining--;
1309
+ if (remaining === 0) cb({ _tag: "Success", value: void 0 });
1310
+ })]);
1311
+ }
1312
+ });
1313
+ }
1314
+ handle(record) {
1315
+ return {
1316
+ id: record.id,
1317
+ name: record.name,
1318
+ current: () => record.current,
1319
+ status: () => record.status,
1320
+ restartCount: () => record.restartCount,
1321
+ interrupt: () => {
1322
+ record.plannedRestart = false;
1323
+ if (record.timer) {
1324
+ clearTimeout(record.timer);
1325
+ record.timer = void 0;
1326
+ }
1327
+ if (record.current) {
1328
+ record.current.interrupt();
1329
+ } else if (!record.terminalExit) {
1330
+ this.finish(record, interruptExit());
1331
+ }
1332
+ },
1333
+ join: (cb) => {
1334
+ if (record.terminalExit) cb(record.terminalExit);
1335
+ else record.joiners.push(cb);
1336
+ }
1337
+ };
1338
+ }
1339
+ launch(record) {
1340
+ if (this.closed) return;
1341
+ record.generation++;
1342
+ record.status = "running";
1343
+ record.plannedRestart = false;
1344
+ record.terminalExit = void 0;
1345
+ const generation = record.generation;
1346
+ const effect = typeof record.spec.effect === "function" ? record.spec.effect() : record.spec.effect;
1347
+ const fiber = this.runtime.fork(effect);
1348
+ record.current = fiber;
1349
+ this.emit({
1350
+ type: "child-start",
1351
+ supervisorId: this.id,
1352
+ childId: record.id,
1353
+ name: record.name,
1354
+ status: "running",
1355
+ restartCount: record.restartCount
1356
+ });
1357
+ fiber.join((exit) => this.onChildExit(record, generation, exit));
1358
+ }
1359
+ onChildExit(record, generation, exit) {
1360
+ if (generation !== record.generation) return;
1361
+ record.current = void 0;
1362
+ if (this.closed) {
1363
+ this.finish(record, exit);
1364
+ return;
1365
+ }
1366
+ if (record.plannedRestart) {
1367
+ this.scheduleRestart(record, exit, "all-for-one");
1368
+ return;
1369
+ }
1370
+ this.emit({
1371
+ type: "child-end",
1372
+ supervisorId: this.id,
1373
+ childId: record.id,
1374
+ name: record.name,
1375
+ status: statusFromExit(exit),
1376
+ restartCount: record.restartCount,
1377
+ exit
1378
+ });
1379
+ if (!shouldRestart(record.restart.mode, exit)) {
1380
+ this.finish(record, exit);
1381
+ return;
1382
+ }
1383
+ if (this.strategy === "all-for-one") {
1384
+ this.restartAll(record, exit);
1385
+ return;
1386
+ }
1387
+ this.scheduleRestart(record, exit, "one-for-one");
1388
+ }
1389
+ restartAll(failed, exit) {
1390
+ for (const record of this.records.values()) {
1391
+ if (record.id === failed.id) continue;
1392
+ if (!record.current) continue;
1393
+ record.plannedRestart = true;
1394
+ record.status = "restarting";
1395
+ record.current.interrupt();
1396
+ }
1397
+ this.scheduleRestart(failed, exit, "all-for-one");
1398
+ }
1399
+ scheduleRestart(record, exit, reason) {
1400
+ const context = this.restartContext(record, exit);
1401
+ const delay = this.nextDelay(record, context);
1402
+ if (delay === void 0) {
1403
+ this.escalate(record, exit, "restart policy exhausted");
1404
+ return;
1405
+ }
1406
+ record.status = "restarting";
1407
+ record.restartCount++;
1408
+ this.emit({
1409
+ type: "child-restart",
1410
+ supervisorId: this.id,
1411
+ childId: record.id,
1412
+ name: record.name,
1413
+ status: "restarting",
1414
+ restartCount: record.restartCount,
1415
+ delayMs: delay,
1416
+ exit,
1417
+ reason
1418
+ });
1419
+ record.timer = setTimeout(() => {
1420
+ record.timer = void 0;
1421
+ this.launch(record);
1422
+ }, delay);
1423
+ }
1424
+ nextDelay(record, context) {
1425
+ const now = this.clock();
1426
+ const windowStart = record.restart.withinMs === void 0 ? Number.NEGATIVE_INFINITY : now - record.restart.withinMs;
1427
+ record.restartTimes = record.restartTimes.filter((ts) => ts >= windowStart);
1428
+ if (record.restart.maxRestarts !== void 0 && record.restartTimes.length >= record.restart.maxRestarts) {
1429
+ return void 0;
1430
+ }
1431
+ record.restartTimes.push(now);
1432
+ if (record.restart.schedule) {
1433
+ record.scheduleDriver ??= _chunkAGR5B2BCcjs.makeScheduleDriver.call(void 0, record.restart.schedule, {
1434
+ name: _nullishCoalesce(record.restart.schedule.name, () => ( "supervisor.restart")),
1435
+ clock: this.scheduleClock()
1436
+ });
1437
+ const decision = record.scheduleDriver.next(context);
1438
+ return decision.continue ? Math.max(0, Math.floor(decision.delayMs)) : void 0;
1439
+ }
1440
+ const raw = typeof record.restart.delayMs === "function" ? record.restart.delayMs(context) : _nullishCoalesce(record.restart.delayMs, () => ( 0));
1441
+ return Number.isFinite(raw) ? Math.max(0, Math.floor(raw)) : 0;
1442
+ }
1443
+ escalate(record, exit, reason) {
1444
+ this.emit({
1445
+ type: "child-escalate",
1446
+ supervisorId: this.id,
1447
+ childId: record.id,
1448
+ name: record.name,
1449
+ status: statusFromExit(exit),
1450
+ restartCount: record.restartCount,
1451
+ exit,
1452
+ reason
1453
+ });
1454
+ if (this.escalation === "shutdown") {
1455
+ for (const child of this.records.values()) {
1456
+ if (child.id !== record.id) _optionalChain([child, 'access', _23 => _23.current, 'optionalAccess', _24 => _24.interrupt, 'call', _25 => _25()]);
1457
+ }
1458
+ }
1459
+ this.finish(record, exit);
1460
+ }
1461
+ finish(record, exit) {
1462
+ record.status = statusFromExit(exit);
1463
+ record.terminalExit = exit;
1464
+ const joiners = record.joiners.splice(0);
1465
+ for (const joiner of joiners) joiner(exit);
1466
+ }
1467
+ restartContext(record, exit) {
1468
+ return {
1469
+ supervisorId: this.id,
1470
+ childId: record.id,
1471
+ name: record.name,
1472
+ restartCount: record.restartCount,
1473
+ exit
1474
+ };
1475
+ }
1476
+ emit(event) {
1477
+ _optionalChain([this, 'access', _26 => _26.onEvent, 'optionalCall', _27 => _27(event)]);
1478
+ this.runtime.emit(toRuntimeEvent(event));
1479
+ }
1480
+ scheduleClock() {
1481
+ return {
1482
+ now: this.clock,
1483
+ setTimeout: _chunkGLE2WY7Zcjs.liveClock.setTimeout,
1484
+ clearTimeout: _chunkGLE2WY7Zcjs.liveClock.clearTimeout
1485
+ };
1486
+ }
1487
+ }, _class6);
1488
+ function makeSupervisor(runtime, config = {}) {
1489
+ return new Supervisor(runtime, config);
1490
+ }
1491
+ function supervise(runtime, spec, config = {}) {
1492
+ return new Supervisor(runtime, config).start(spec);
1493
+ }
1494
+ function joinSupervised(fiber) {
1495
+ return _chunkMVGUEJ5Zcjs.asyncEffect.call(void 0, (_env, cb) => fiber.join(cb));
1496
+ }
1497
+ function resolveRestartPolicy(policy) {
1498
+ if (typeof policy === "string") return { mode: policy };
1499
+ return {
1500
+ mode: _nullishCoalesce(policy.mode, () => ( "on-failure")),
1501
+ maxRestarts: policy.maxRestarts,
1502
+ withinMs: policy.withinMs,
1503
+ delayMs: policy.delayMs,
1504
+ schedule: policy.schedule
1505
+ };
1506
+ }
1507
+ function shouldRestart(mode, exit) {
1508
+ if (exit._tag === "Failure" && _chunkMVGUEJ5Zcjs.Cause.isInterruptedOnly(exit.cause)) return false;
1509
+ if (mode === "never") return false;
1510
+ if (mode === "always") return true;
1511
+ return exit._tag === "Failure";
1512
+ }
1513
+ function statusFromExit(exit) {
1514
+ if (exit._tag === "Success") return "succeeded";
1515
+ return _chunkMVGUEJ5Zcjs.Cause.isInterruptedOnly(exit.cause) ? "interrupted" : "failed";
1516
+ }
1517
+ function toRuntimeEvent(event) {
1518
+ switch (event.type) {
1519
+ case "child-start":
1520
+ return {
1521
+ type: "supervisor.child.start",
1522
+ supervisorId: event.supervisorId,
1523
+ childId: event.childId,
1524
+ name: event.name,
1525
+ restartCount: _nullishCoalesce(event.restartCount, () => ( 0))
1526
+ };
1527
+ case "child-end":
1528
+ return {
1529
+ type: "supervisor.child.end",
1530
+ supervisorId: event.supervisorId,
1531
+ childId: event.childId,
1532
+ name: event.name,
1533
+ status: event.status === "succeeded" ? "success" : event.status === "interrupted" ? "interrupted" : "failure",
1534
+ error: _optionalChain([event, 'access', _28 => _28.exit, 'optionalAccess', _29 => _29._tag]) === "Failure" ? event.exit.cause : void 0
1535
+ };
1536
+ case "child-restart":
1537
+ return {
1538
+ type: "supervisor.child.restart",
1539
+ supervisorId: event.supervisorId,
1540
+ childId: event.childId,
1541
+ name: event.name,
1542
+ restartCount: _nullishCoalesce(event.restartCount, () => ( 0)),
1543
+ delayMs: _nullishCoalesce(event.delayMs, () => ( 0)),
1544
+ reason: event.reason
1545
+ };
1546
+ case "child-escalate":
1547
+ return {
1548
+ type: "supervisor.child.escalate",
1549
+ supervisorId: event.supervisorId,
1550
+ childId: event.childId,
1551
+ name: event.name,
1552
+ reason: event.reason,
1553
+ error: _optionalChain([event, 'access', _30 => _30.exit, 'optionalAccess', _31 => _31._tag]) === "Failure" ? event.exit.cause : void 0
1554
+ };
1555
+ case "shutdown":
1556
+ return {
1557
+ type: "supervisor.shutdown",
1558
+ supervisorId: event.supervisorId
1559
+ };
1560
+ }
1561
+ }
1562
+ function interruptExit() {
1563
+ return { _tag: "Failure", cause: { _tag: "Interrupt" } };
1564
+ }
1565
+
1566
+
1567
+
1568
+
1569
+
1570
+
1571
+
1572
+
1573
+
1574
+
1575
+
1576
+
1577
+
1578
+
1579
+
1580
+
1581
+
1582
+
1583
+
1584
+
1585
+
1586
+
1587
+
1588
+
1589
+
1590
+
1591
+
1592
+
1593
+
1594
+
1595
+
1596
+
1597
+
1598
+
1599
+
1600
+
1601
+
1602
+
1603
+
1604
+
1605
+
1606
+
1607
+
1608
+
1609
+
1610
+
1611
+
1612
+
1613
+
1614
+
1615
+
1616
+
1617
+
1618
+
1619
+
1620
+
1621
+
1622
+
1623
+
1624
+
1625
+
1626
+
1627
+
1628
+
1629
+ exports.makeCancelToken = makeCancelToken; exports.linkAbortController = linkAbortController; exports.makeRuntime = makeRuntime; exports.runPromise = runPromise; exports.runExit = runExit; exports.runEffect = runEffect; exports.LinkedQueue = LinkedQueue; exports.makeSemaphore = makeSemaphore; exports.makeRef = makeRef; exports.derivedRef = derivedRef; exports.gracefulShutdown = gracefulShutdown; exports.registerShutdownHooks = registerShutdownHooks; exports.TestScheduler = TestScheduler; exports.TestClock = TestClock; exports.makeTestRuntime = makeTestRuntime; exports.assertSucceeds = assertSucceeds; exports.assertFails = assertFails; exports.assertFailsWith = assertFailsWith; exports.assertCompletesWithin = assertCompletesWithin; exports.flakyEffect = flakyEffect; exports.delayedEffect = delayedEffect; exports.neverEffect = neverEffect; exports.MissingLayerServiceError = MissingLayerServiceError; exports.formatLayerError = formatLayerError; exports.makeServiceTag = makeServiceTag; exports.serviceTag = serviceTag; exports.defineService = defineService; exports.LayerContext = LayerContext; exports.makeLayerScope = makeLayerScope; exports.layer = layer; exports.layerValue = layerValue; exports.layerEffect = layerEffect; exports.layerFromContext = layerFromContext; exports.defineLayer = defineLayer; exports.getService = getService; exports.layerFrom = layerFrom; exports.layerSucceed = layerSucceed; exports.layerFail = layerFail; exports.compose = compose; exports.merge = merge; exports.mapLayer = mapLayer; exports.buildLayer = buildLayer; exports.provideLayer = provideLayer; exports.provideLayerContext = provideLayerContext; exports.provide = provide; exports.provideContext = provideContext; exports.Layer = Layer; exports.makeWorkerPool = makeWorkerPool; exports.makeTracer = makeTracer; exports.consoleJsonLogger = consoleJsonLogger; exports.RuntimeRegistry = RuntimeRegistry; exports.dumpAllFibers = dumpAllFibers; exports.defaultTracer = defaultTracer; exports.catchTag = catchTag; exports.catchTags = catchTags; exports.mapError = mapError; exports.tagError = tagError; exports.orElse = orElse; exports.Supervisor = Supervisor; exports.makeSupervisor = makeSupervisor; exports.supervise = supervise; exports.joinSupervised = joinSupervised;