spool-engine 0.0.0-stage → 0.2.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 (166) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +12 -2
  3. package/dist/config.js +130 -0
  4. package/dist/config.js.map +1 -0
  5. package/dist/domain/errors.js +108 -0
  6. package/dist/domain/errors.js.map +1 -0
  7. package/dist/domain/journal.js +21 -0
  8. package/dist/domain/journal.js.map +1 -0
  9. package/dist/domain/json.js +55 -0
  10. package/dist/domain/json.js.map +1 -0
  11. package/dist/domain/llm.js +22 -0
  12. package/dist/domain/llm.js.map +1 -0
  13. package/dist/domain/retry.js +21 -0
  14. package/dist/domain/retry.js.map +1 -0
  15. package/dist/domain/run-status.js +40 -0
  16. package/dist/domain/run-status.js.map +1 -0
  17. package/dist/domain/sleep.js +7 -0
  18. package/dist/domain/sleep.js.map +1 -0
  19. package/dist/engine.js +131 -0
  20. package/dist/engine.js.map +1 -0
  21. package/dist/loops/every.js +32 -0
  22. package/dist/loops/every.js.map +1 -0
  23. package/dist/loops/listener.js +58 -0
  24. package/dist/loops/listener.js.map +1 -0
  25. package/dist/loops/live-runs.js +30 -0
  26. package/dist/loops/live-runs.js.map +1 -0
  27. package/dist/loops/queue-depth.js +28 -0
  28. package/dist/loops/queue-depth.js.map +1 -0
  29. package/dist/loops/reaper.js +71 -0
  30. package/dist/loops/reaper.js.map +1 -0
  31. package/dist/loops/waker.js +42 -0
  32. package/dist/loops/waker.js.map +1 -0
  33. package/dist/main.js +48 -0
  34. package/dist/main.js.map +1 -0
  35. package/dist/observability/logger.js +9 -0
  36. package/dist/observability/logger.js.map +1 -0
  37. package/dist/observability/metrics.js +97 -0
  38. package/dist/observability/metrics.js.map +1 -0
  39. package/dist/observability/tracing.js +146 -0
  40. package/dist/observability/tracing.js.map +1 -0
  41. package/dist/proto/limits_pb.d.ts +212 -0
  42. package/dist/proto/limits_pb.js +76 -0
  43. package/dist/proto/runs_pb.d.ts +740 -0
  44. package/dist/proto/runs_pb.js +147 -0
  45. package/dist/proto/workers_pb.d.ts +900 -0
  46. package/dist/proto/workers_pb.js +168 -0
  47. package/dist/services/admission.js +47 -0
  48. package/dist/services/admission.js.map +1 -0
  49. package/dist/services/cancel-run.js +43 -0
  50. package/dist/services/cancel-run.js.map +1 -0
  51. package/dist/services/claim-tasks.js +59 -0
  52. package/dist/services/claim-tasks.js.map +1 -0
  53. package/dist/services/complete-task.js +45 -0
  54. package/dist/services/complete-task.js.map +1 -0
  55. package/dist/services/fail-step.js +102 -0
  56. package/dist/services/fail-step.js.map +1 -0
  57. package/dist/services/group-commit.js +83 -0
  58. package/dist/services/group-commit.js.map +1 -0
  59. package/dist/services/live-tokens.js +90 -0
  60. package/dist/services/live-tokens.js.map +1 -0
  61. package/dist/services/next-step.js +33 -0
  62. package/dist/services/next-step.js.map +1 -0
  63. package/dist/services/notifier.js +54 -0
  64. package/dist/services/notifier.js.map +1 -0
  65. package/dist/services/query-runs.js +14 -0
  66. package/dist/services/query-runs.js.map +1 -0
  67. package/dist/services/replay-run.js +63 -0
  68. package/dist/services/replay-run.js.map +1 -0
  69. package/dist/services/report-step.js +129 -0
  70. package/dist/services/report-step.js.map +1 -0
  71. package/dist/services/run-watches.js +46 -0
  72. package/dist/services/run-watches.js.map +1 -0
  73. package/dist/services/send-event.js +16 -0
  74. package/dist/services/send-event.js.map +1 -0
  75. package/dist/services/sleep-run.js +47 -0
  76. package/dist/services/sleep-run.js.map +1 -0
  77. package/dist/services/throttle-step.js +76 -0
  78. package/dist/services/throttle-step.js.map +1 -0
  79. package/dist/services/trigger-run.js +38 -0
  80. package/dist/services/trigger-run.js.map +1 -0
  81. package/dist/services/wait-for-event.js +73 -0
  82. package/dist/services/wait-for-event.js.map +1 -0
  83. package/dist/services/wakeups.js +70 -0
  84. package/dist/services/wakeups.js.map +1 -0
  85. package/dist/services/watch-run.js +36 -0
  86. package/dist/services/watch-run.js.map +1 -0
  87. package/dist/services/worker-session.js +198 -0
  88. package/dist/services/worker-session.js.map +1 -0
  89. package/dist/store/errors.js +42 -0
  90. package/dist/store/errors.js.map +1 -0
  91. package/dist/store/events.js +96 -0
  92. package/dist/store/events.js.map +1 -0
  93. package/dist/store/idempotency.js +29 -0
  94. package/dist/store/idempotency.js.map +1 -0
  95. package/dist/store/json.js +9 -0
  96. package/dist/store/json.js.map +1 -0
  97. package/dist/store/limits.js +60 -0
  98. package/dist/store/limits.js.map +1 -0
  99. package/dist/store/migrate.js +20 -0
  100. package/dist/store/migrate.js.map +1 -0
  101. package/dist/store/run-views.js +96 -0
  102. package/dist/store/run-views.js.map +1 -0
  103. package/dist/store/runs.js +104 -0
  104. package/dist/store/runs.js.map +1 -0
  105. package/dist/store/schema.js +191 -0
  106. package/dist/store/schema.js.map +1 -0
  107. package/dist/store/steps.js +114 -0
  108. package/dist/store/steps.js.map +1 -0
  109. package/dist/store/tasks.js +463 -0
  110. package/dist/store/tasks.js.map +1 -0
  111. package/dist/store/transaction.js +23 -0
  112. package/dist/store/transaction.js.map +1 -0
  113. package/dist/store/waits.js +75 -0
  114. package/dist/store/waits.js.map +1 -0
  115. package/dist/store/watches.js +31 -0
  116. package/dist/store/watches.js.map +1 -0
  117. package/dist/transport/auth.js +26 -0
  118. package/dist/transport/auth.js.map +1 -0
  119. package/dist/transport/channel.js +46 -0
  120. package/dist/transport/channel.js.map +1 -0
  121. package/dist/transport/errors.js +74 -0
  122. package/dist/transport/errors.js.map +1 -0
  123. package/dist/transport/limits-service.js +60 -0
  124. package/dist/transport/limits-service.js.map +1 -0
  125. package/dist/transport/protocol.js +14 -0
  126. package/dist/transport/protocol.js.map +1 -0
  127. package/dist/transport/run-events.js +133 -0
  128. package/dist/transport/run-events.js.map +1 -0
  129. package/dist/transport/run-messages.js +78 -0
  130. package/dist/transport/run-messages.js.map +1 -0
  131. package/dist/transport/run-service.js +147 -0
  132. package/dist/transport/run-service.js.map +1 -0
  133. package/dist/transport/server.js +227 -0
  134. package/dist/transport/server.js.map +1 -0
  135. package/dist/transport/validation.js +61 -0
  136. package/dist/transport/validation.js.map +1 -0
  137. package/dist/transport/worker-service.js +396 -0
  138. package/dist/transport/worker-service.js.map +1 -0
  139. package/drizzle/0000_init.sql +95 -0
  140. package/drizzle/0001_tasks_storage.sql +2 -0
  141. package/drizzle/0002_waits_route.sql +3 -0
  142. package/drizzle/0003_event_waits.sql +8 -0
  143. package/drizzle/0004_llm_steps.sql +2 -0
  144. package/drizzle/0005_tasks_notify.sql +19 -0
  145. package/drizzle/0006_drop_tasks_notify.sql +8 -0
  146. package/drizzle/0007_tasks_fair.sql +5 -0
  147. package/drizzle/0008_concurrency_limits.sql +8 -0
  148. package/drizzle/0009_rate_limits.sql +12 -0
  149. package/drizzle/0010_run_listings.sql +2 -0
  150. package/drizzle/0011_run_replays.sql +7 -0
  151. package/drizzle/0012_run_watches.sql +8 -0
  152. package/drizzle/meta/0000_snapshot.json +668 -0
  153. package/drizzle/meta/0001_snapshot.json +668 -0
  154. package/drizzle/meta/0002_snapshot.json +680 -0
  155. package/drizzle/meta/0003_snapshot.json +723 -0
  156. package/drizzle/meta/0004_snapshot.json +733 -0
  157. package/drizzle/meta/0005_snapshot.json +733 -0
  158. package/drizzle/meta/0006_snapshot.json +733 -0
  159. package/drizzle/meta/0007_snapshot.json +739 -0
  160. package/drizzle/meta/0008_snapshot.json +791 -0
  161. package/drizzle/meta/0009_snapshot.json +843 -0
  162. package/drizzle/meta/0010_snapshot.json +881 -0
  163. package/drizzle/meta/0011_snapshot.json +903 -0
  164. package/drizzle/meta/0012_snapshot.json +958 -0
  165. package/drizzle/meta/_journal.json +97 -0
  166. package/package.json +58 -3
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # spool-engine
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The engine of [Spool](https://github.com/ishyverma/spool): durable execution for AI agents on plain Postgres. It is a stateless server. Run one or many against one PostgreSQL database, and workers built with the SDK (`npm install spool-sdk`, `pip install spool-sdk`) connect to it.
4
+
5
+ ```sh
6
+ export DATABASE_URL=postgres://spool:spool@127.0.0.1:5432/spool
7
+ export SPOOL_API_KEY=$(openssl rand -hex 32) # at least 32 characters
8
+ npx spool-engine # http://127.0.0.1:7070
9
+ ```
10
+
11
+ It applies its migrations on start. One port serves HTTP/1.1 JSON, HTTP/2, gRPC and gRPC-Web, Prometheus metrics at `/metrics`, and live run events at `/v1/runs/{id}/events`. It stops gracefully on `SIGTERM`. Node 24 or later.
12
+
13
+ The architecture, the internals, every setting and the API are in the [main README](https://github.com/ishyverma/spool#readme).
package/dist/config.js ADDED
@@ -0,0 +1,130 @@
1
+ import { z } from "zod";
2
+ import { MAX_PRICE_PER_MILLION_USD } from "./domain/llm.js";
3
+ /** A whole number from an environment variable; rejects "", "1.5" and "80abc". */
4
+ const integer = (min, max, fallback) => z
5
+ .string()
6
+ .regex(/^\d+$/, "must be a whole number")
7
+ .transform(Number)
8
+ .pipe(z.number().int().min(min).max(max))
9
+ .prefault(String(fallback));
10
+ const databaseUrl = z.url({
11
+ protocol: /^postgres(ql)?$/,
12
+ error: "must be a postgres:// or postgresql:// URL",
13
+ });
14
+ const price = z.number().min(0).max(MAX_PRICE_PER_MILLION_USD);
15
+ /** `{"model": {"input": 3, "output": 15}}`: USD per million tokens. */
16
+ const llmPrices = z
17
+ .string()
18
+ .transform((text, context) => {
19
+ try {
20
+ return JSON.parse(text);
21
+ }
22
+ catch {
23
+ context.addIssue({ code: "custom", message: "must be a JSON object" });
24
+ return z.NEVER;
25
+ }
26
+ })
27
+ .pipe(z.record(z.string().min(1).max(128), z.strictObject({ input: price, output: price })))
28
+ .prefault("{}");
29
+ const environment = z.object({
30
+ DATABASE_URL: databaseUrl,
31
+ /**
32
+ * A direct connection to Postgres for what needs a session: the migrations' advisory lock
33
+ * and LISTEN. Set it when DATABASE_URL points at a transaction pooler such as PgBouncer;
34
+ * it defaults to DATABASE_URL.
35
+ */
36
+ SPOOL_DIRECT_DATABASE_URL: databaseUrl.optional(),
37
+ SPOOL_API_KEY: z.string().min(32, "must be at least 32 characters"),
38
+ SPOOL_HOST: z.string().min(1).prefault("127.0.0.1"),
39
+ SPOOL_PORT: integer(0, 65_535, 7070),
40
+ /** Triggers are shed with 429 once this many tasks are queued or running. */
41
+ SPOOL_MAX_QUEUE_DEPTH: integer(1, 100_000_000, 100_000),
42
+ SPOOL_RETRY_AFTER_SECONDS: integer(1, 3600, 2),
43
+ /** Postgres connections per engine process; bounded so replicas cannot exhaust Postgres. */
44
+ SPOOL_DB_POOL_SIZE: integer(1, 1000, 10),
45
+ /** How long a worker's claim holds a task before another worker may take it. */
46
+ SPOOL_LEASE_SECONDS: integer(1, 3600, 30),
47
+ /** How often each engine returns expired leases to the queue; recovery takes lease + this. */
48
+ SPOOL_REAPER_INTERVAL_MS: integer(10, 60_000, 500),
49
+ /** How often each engine queues sleeping runs whose time has come; a sleep ends up to this late. */
50
+ SPOOL_WAKER_INTERVAL_MS: integer(10, 60_000, 250),
51
+ /** How often a worker stream with free slots looks for work; the wake-up latency when idle. */
52
+ SPOOL_POLL_INTERVAL_MS: integer(10, 10_000, 250),
53
+ /** The first retry of a failed step waits up to this long; each retry doubles it (PRD §5). */
54
+ SPOOL_RETRY_BASE_MS: integer(1, 3_600_000, 1000),
55
+ /** No retry of a failed step waits longer than this. */
56
+ SPOOL_RETRY_CAP_MS: integer(1, 86_400_000, 600_000),
57
+ /** A run whose lease expires this many times in a row without progress fails. */
58
+ SPOOL_MAX_LEASE_EXPIRIES: integer(1, 100, 5),
59
+ /** TCP connections one engine holds at once; the rest are closed on arrival. */
60
+ SPOOL_MAX_CONNECTIONS: integer(1, 1_000_000, 10_000),
61
+ /** Worker streams one engine serves at once; each may poll the database. */
62
+ SPOOL_MAX_WORKER_STREAMS: integer(1, 100_000, 1000),
63
+ /** How often a run's event stream (SSE) looks for a change; one small query each. */
64
+ SPOOL_EVENT_POLL_INTERVAL_MS: integer(50, 60_000, 500),
65
+ /** Run event streams (SSE) one engine serves at once; the rest are refused with 503. */
66
+ SPOOL_MAX_EVENT_STREAMS: integer(1, 100_000, 1000),
67
+ /** Step reports recorded per transaction at most (group commit). */
68
+ SPOOL_GROUP_COMMIT_MAX_BATCH: integer(1, 1000, 100),
69
+ /** Step-report transactions in progress at once; each holds a pooled connection. */
70
+ SPOOL_GROUP_COMMIT_FLUSHES: integer(1, 1000, 4),
71
+ /** Prices for ctx.llm steps by model; a model without one is recorded with no cost. */
72
+ SPOOL_LLM_PRICES: llmPrices,
73
+ SPOOL_LOG_LEVEL: z.enum(["fatal", "error", "warn", "info", "debug", "trace"]).prefault("info"),
74
+ /**
75
+ * Where to send traces, one per run (OTLP over HTTP, such as Jaeger's or Tempo's
76
+ * http://host:4318/v1/traces). Unset, nothing is traced.
77
+ */
78
+ SPOOL_OTLP_TRACES_URL: z.url({ protocol: /^https?$/ }).optional(),
79
+ });
80
+ export class ConfigError extends Error {
81
+ name = "ConfigError";
82
+ code = "INVALID_CONFIG";
83
+ }
84
+ function parse(schema, env) {
85
+ const parsed = schema.safeParse(env);
86
+ if (!parsed.success) {
87
+ // Only variable names and our own messages: values can contain credentials.
88
+ const problems = parsed.error.issues.map((issue) => `${issue.path.join(".")} ${issue.message}`);
89
+ throw new ConfigError(`invalid environment: ${problems.join("; ")}`);
90
+ }
91
+ return parsed.data;
92
+ }
93
+ /** For tools that only touch the database, such as migrations: needs nothing else. */
94
+ export function loadDatabaseUrl(env) {
95
+ return parse(z.object({ DATABASE_URL: databaseUrl }), env).DATABASE_URL;
96
+ }
97
+ export function loadConfig(env) {
98
+ const values = parse(environment.refine((v) => v.SPOOL_RETRY_BASE_MS <= v.SPOOL_RETRY_CAP_MS, {
99
+ path: ["SPOOL_RETRY_CAP_MS"],
100
+ error: "must be at least SPOOL_RETRY_BASE_MS",
101
+ }), env);
102
+ return {
103
+ databaseUrl: values.DATABASE_URL,
104
+ directDatabaseUrl: values.SPOOL_DIRECT_DATABASE_URL ?? values.DATABASE_URL,
105
+ apiKey: values.SPOOL_API_KEY,
106
+ host: values.SPOOL_HOST,
107
+ port: values.SPOOL_PORT,
108
+ maxQueueDepth: values.SPOOL_MAX_QUEUE_DEPTH,
109
+ retryAfterSeconds: values.SPOOL_RETRY_AFTER_SECONDS,
110
+ dbPoolSize: values.SPOOL_DB_POOL_SIZE,
111
+ leaseMs: values.SPOOL_LEASE_SECONDS * 1000,
112
+ reaperIntervalMs: values.SPOOL_REAPER_INTERVAL_MS,
113
+ wakerIntervalMs: values.SPOOL_WAKER_INTERVAL_MS,
114
+ pollIntervalMs: values.SPOOL_POLL_INTERVAL_MS,
115
+ retry: { baseMs: values.SPOOL_RETRY_BASE_MS, capMs: values.SPOOL_RETRY_CAP_MS },
116
+ maxLeaseExpiries: values.SPOOL_MAX_LEASE_EXPIRIES,
117
+ maxConnections: values.SPOOL_MAX_CONNECTIONS,
118
+ maxWorkerStreams: values.SPOOL_MAX_WORKER_STREAMS,
119
+ eventPollIntervalMs: values.SPOOL_EVENT_POLL_INTERVAL_MS,
120
+ maxEventStreams: values.SPOOL_MAX_EVENT_STREAMS,
121
+ llmPrices: new Map(Object.entries(values.SPOOL_LLM_PRICES)),
122
+ groupCommit: {
123
+ maxBatch: values.SPOOL_GROUP_COMMIT_MAX_BATCH,
124
+ maxFlushes: values.SPOOL_GROUP_COMMIT_FLUSHES,
125
+ },
126
+ logLevel: values.SPOOL_LOG_LEVEL,
127
+ otlpTracesUrl: values.SPOOL_OTLP_TRACES_URL,
128
+ };
129
+ }
130
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,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AC/C,cAAc,EAAE,MAAM,CAAC,sBAAsB;QAC7C,KAAK,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,mBAAmB,EAAE,KAAK,EAAE,MAAM,CAAC,kBAAkB,EAAE;QAC/E,gBAAgB,EAAE,MAAM,CAAC,wBAAwB;QACjD,cAAc,EAAE,MAAM,CAAC,qBAAqB;QAC5C,gBAAgB,EAAE,MAAM,CAAC,wBAAwB;QACjD,mBAAmB,EAAE,MAAM,CAAC,4BAA4B;QACxD,eAAe,EAAE,MAAM,CAAC,uBAAuB;QAC/C,SAAS,EAAE,IAAI,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;QAC3D,WAAW,EAAE;YACX,QAAQ,EAAE,MAAM,CAAC,4BAA4B;YAC7C,UAAU,EAAE,MAAM,CAAC,0BAA0B;SAC9C;QACD,QAAQ,EAAE,MAAM,CAAC,eAAe;QAChC,aAAa,EAAE,MAAM,CAAC,qBAAqB;KAC5C,CAAC;AACJ,CAAC"}
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Errors with a stable code that callers may act on. `retryable` says whether the same
3
+ * request can succeed later; it drives retry behaviour.
4
+ */
5
+ export class SpoolError extends Error {
6
+ }
7
+ export class InvalidArgumentError extends SpoolError {
8
+ name = "InvalidArgumentError";
9
+ code = "INVALID_ARGUMENT";
10
+ retryable = false;
11
+ }
12
+ export class IdempotencyConflictError extends SpoolError {
13
+ name = "IdempotencyConflictError";
14
+ code = "IDEMPOTENCY_CONFLICT";
15
+ retryable = false;
16
+ constructor() {
17
+ super("idempotency key was already used with different input");
18
+ }
19
+ }
20
+ /**
21
+ * A completion whose lease was lost: it expired, another worker claimed the task with a
22
+ * newer attempt, or the task already finished. The result was discarded. Not retryable:
23
+ * the same request can never succeed, and the worker must drop the task.
24
+ */
25
+ export class LeaseLostError extends SpoolError {
26
+ name = "LeaseLostError";
27
+ code = "LEASE_LOST";
28
+ retryable = false;
29
+ constructor() {
30
+ super("the lease for this attempt is no longer held; the result was discarded");
31
+ }
32
+ }
33
+ /**
34
+ * A step report names a different step than the journal holds at that position: the
35
+ * workflow's code changed while the run was in flight, so replaying it would hand stored
36
+ * results to the wrong steps. Not retryable.
37
+ */
38
+ export class StepMismatchError extends SpoolError {
39
+ name = "StepMismatchError";
40
+ code = "STEP_MISMATCH";
41
+ retryable = false;
42
+ constructor(seq) {
43
+ super(`step ${String(seq)} was recorded as a different step; the workflow changed while the run was in flight`);
44
+ }
45
+ }
46
+ /** No run has this id. Not retryable: runs are never deleted, so it will not appear. */
47
+ export class RunNotFoundError extends SpoolError {
48
+ name = "RunNotFoundError";
49
+ code = "RUN_NOT_FOUND";
50
+ retryable = false;
51
+ constructor() {
52
+ super("no run has this id");
53
+ }
54
+ }
55
+ /** A run that is still in progress cannot be replayed; cancel it or let it finish first. */
56
+ export class RunNotFinishedError extends SpoolError {
57
+ name = "RunNotFinishedError";
58
+ code = "RUN_NOT_FINISHED";
59
+ retryable = false;
60
+ constructor() {
61
+ super("only a finished run (succeeded, failed or cancelled) can be replayed");
62
+ }
63
+ }
64
+ /** The engine is at capacity; the same request may succeed after `retryAfterSeconds`. */
65
+ export class OverloadedError extends SpoolError {
66
+ retryAfterSeconds;
67
+ name = "OverloadedError";
68
+ code = "OVERLOADED";
69
+ retryable = true;
70
+ constructor(retryAfterSeconds) {
71
+ super("too much work is queued; retry later");
72
+ this.retryAfterSeconds = retryAfterSeconds;
73
+ }
74
+ }
75
+ /**
76
+ * The engine already serves as many worker streams as it allows; the worker should
77
+ * reconnect after a backoff, here or through another engine.
78
+ */
79
+ export class TooManyStreamsError extends SpoolError {
80
+ name = "TooManyStreamsError";
81
+ code = "TOO_MANY_STREAMS";
82
+ retryable = true;
83
+ constructor(limit) {
84
+ super(`this engine serves at most ${String(limit)} worker streams; reconnect later`);
85
+ }
86
+ }
87
+ /**
88
+ * Postgres aborted the transaction to resolve a conflict with another (a deadlock or a
89
+ * serialization failure). Nothing was applied, and the same request can be sent again.
90
+ */
91
+ export class TransactionConflictError extends SpoolError {
92
+ name = "TransactionConflictError";
93
+ code = "TRANSACTION_CONFLICT";
94
+ retryable = true;
95
+ constructor(options) {
96
+ super("the request conflicted with another and was not applied; send it again", options);
97
+ }
98
+ }
99
+ /** The database could not be reached or dropped the connection; retrying may succeed. */
100
+ export class DatabaseUnavailableError extends SpoolError {
101
+ name = "DatabaseUnavailableError";
102
+ code = "DATABASE_UNAVAILABLE";
103
+ retryable = true;
104
+ constructor(options) {
105
+ super("the database is unavailable; retry later", options);
106
+ }
107
+ }
108
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/domain/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,OAAgB,UAAW,SAAQ,KAAK;CAG7C;AAED,MAAM,OAAO,oBAAqB,SAAQ,UAAU;IAChC,IAAI,GAAG,sBAAsB,CAAC;IAC9B,IAAI,GAAG,kBAAkB,CAAC;IAC1B,SAAS,GAAG,KAAK,CAAC;CACrC;AAED,MAAM,OAAO,wBAAyB,SAAQ,UAAU;IACpC,IAAI,GAAG,0BAA0B,CAAC;IAClC,IAAI,GAAG,sBAAsB,CAAC;IAC9B,SAAS,GAAG,KAAK,CAAC;IAEpC;QACE,KAAK,CAAC,uDAAuD,CAAC,CAAC;IACjE,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,OAAO,cAAe,SAAQ,UAAU;IAC1B,IAAI,GAAG,gBAAgB,CAAC;IACxB,IAAI,GAAG,YAAY,CAAC;IACpB,SAAS,GAAG,KAAK,CAAC;IAEpC;QACE,KAAK,CAAC,wEAAwE,CAAC,CAAC;IAClF,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,OAAO,iBAAkB,SAAQ,UAAU;IAC7B,IAAI,GAAG,mBAAmB,CAAC;IAC3B,IAAI,GAAG,eAAe,CAAC;IACvB,SAAS,GAAG,KAAK,CAAC;IAEpC,YAAY,GAAW;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E,EAAE,OAAO,CAAC,CAAC;IAC3F,CAAC;CACF;AAED,yFAAyF;AACzF,MAAM,OAAO,wBAAyB,SAAQ,UAAU;IACpC,IAAI,GAAG,0BAA0B,CAAC;IAClC,IAAI,GAAG,sBAAsB,CAAC;IAC9B,SAAS,GAAG,IAAI,CAAC;IAEnC,YAAY,OAAoC;QAC9C,KAAK,CAAC,0CAA0C,EAAE,OAAO,CAAC,CAAC;IAC7D,CAAC;CACF"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Bounds one run's journal, and so the journal a claim ships to a worker. Real agent runs
3
+ * have tens of steps; a run past this is almost certainly a loop bug.
4
+ */
5
+ export const MAX_STEPS_PER_RUN = 1000;
6
+ /**
7
+ * Decides what a step report means for the journal. Steps run strictly in sequence,
8
+ * so a report is either the next step, a repeat of a recorded one, or a client error.
9
+ * A recorded step is never overwritten: replay must return exactly what ran.
10
+ */
11
+ export function classifyStepReport(position, report) {
12
+ if (report.seq < position.next) {
13
+ return position.nameAtSeq === report.name ? { kind: "duplicate" } : { kind: "mismatch" };
14
+ }
15
+ if (report.seq > position.next)
16
+ return { kind: "gap", expected: position.next };
17
+ if (report.seq >= MAX_STEPS_PER_RUN)
18
+ return { kind: "too_many_steps" };
19
+ return { kind: "record" };
20
+ }
21
+ //# sourceMappingURL=journal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"journal.js","sourceRoot":"","sources":["../../src/domain/journal.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAmBtC;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAChC,QAAyB,EACzB,MAAuD;IAEvD,IAAI,MAAM,CAAC,GAAG,GAAG,QAAQ,CAAC,IAAI,EAAE,CAAC;QAC/B,OAAO,QAAQ,CAAC,SAAS,KAAK,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC;IAC3F,CAAC;IACD,IAAI,MAAM,CAAC,GAAG,GAAG,QAAQ,CAAC,IAAI;QAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC;IAChF,IAAI,MAAM,CAAC,GAAG,IAAI,iBAAiB;QAAE,OAAO,EAAE,IAAI,EAAE,gBAAgB,EAAE,CAAC;IACvE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;AAC5B,CAAC"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Deep enough for real payloads, and safely below what every client can send: protobuf-es
3
+ * stops decoding binary google.protobuf.Value nesting at 49 levels.
4
+ */
5
+ export const MAX_JSON_DEPTH = 32;
6
+ /** Text Postgres can store: no NUL (text and jsonb reject it) and valid UTF-16 (no lone surrogates). */
7
+ export function isStorableText(text) {
8
+ return !text.includes("\u0000") && text.isWellFormed();
9
+ }
10
+ /**
11
+ * Explains why `value` cannot be stored as a jsonb payload, or returns undefined when it
12
+ * can. Iterative, so hostile nesting cannot overflow the stack. Messages never include
13
+ * the content, which may be sensitive.
14
+ */
15
+ export function jsonProblem(value, maxBytes) {
16
+ if (value === undefined)
17
+ return "is required";
18
+ const pending = [{ value, depth: 0 }];
19
+ for (let item = pending.pop(); item !== undefined; item = pending.pop()) {
20
+ const { value: current, depth } = item;
21
+ if (current === null || typeof current === "boolean")
22
+ continue;
23
+ if (typeof current === "number") {
24
+ if (!Number.isFinite(current))
25
+ return "must not contain NaN or Infinity";
26
+ continue;
27
+ }
28
+ if (typeof current === "string") {
29
+ if (!isStorableText(current))
30
+ return "must not contain NUL or unpaired surrogates";
31
+ continue;
32
+ }
33
+ if (typeof current !== "object")
34
+ return `must not contain a ${typeof current}`;
35
+ if (depth >= MAX_JSON_DEPTH)
36
+ return `must not be nested more than ${String(MAX_JSON_DEPTH)} deep`;
37
+ if (Array.isArray(current)) {
38
+ for (const inner of current)
39
+ pending.push({ value: inner, depth: depth + 1 });
40
+ continue;
41
+ }
42
+ if (Object.getPrototypeOf(current) !== Object.prototype)
43
+ return "must contain only plain objects";
44
+ for (const [key, inner] of Object.entries(current)) {
45
+ if (!isStorableText(key))
46
+ return "must not contain NUL or unpaired surrogates";
47
+ pending.push({ value: inner, depth: depth + 1 });
48
+ }
49
+ }
50
+ if (Buffer.byteLength(JSON.stringify(value)) > maxBytes) {
51
+ return `must be at most ${String(maxBytes)} bytes as JSON`;
52
+ }
53
+ return undefined;
54
+ }
55
+ //# sourceMappingURL=json.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json.js","sourceRoot":"","sources":["../../src/domain/json.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,EAAE,CAAC;AAEjC,wGAAwG;AACxG,MAAM,UAAU,cAAc,CAAC,IAAY;IACzC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;AACzD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,KAAc,EAAE,QAAgB;IAC1D,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,aAAa,CAAC;IAC9C,MAAM,OAAO,GAA0D,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;IAC7F,KAAK,IAAI,IAAI,GAAG,OAAO,CAAC,GAAG,EAAE,EAAE,IAAI,KAAK,SAAS,EAAE,IAAI,GAAG,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC;QACxE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QACvC,IAAI,OAAO,KAAK,IAAI,IAAI,OAAO,OAAO,KAAK,SAAS;YAAE,SAAS;QAC/D,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;YAChC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,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22 @@
1
+ /** Tokens one model call may report in each direction; far above any context window. */
2
+ export const MAX_LLM_TOKENS = 100_000_000;
3
+ /**
4
+ * The highest configurable price, USD per million tokens. With MAX_LLM_TOKENS it keeps one
5
+ * call's cost under what steps.cost_usd (numeric(12,6)) holds: 2 × 10^8 tokens × $1,000/M
6
+ * is $200,000.
7
+ */
8
+ export const MAX_PRICE_PER_MILLION_USD = 1000;
9
+ /**
10
+ * What one model call cost, rounded to the millionth of a dollar the database keeps, or
11
+ * undefined when the model has no configured price. Priced by the engine, not the worker,
12
+ * so one table governs every worker and a price change needs no deploy of agent code.
13
+ */
14
+ export function llmCostUsd(prices, usage) {
15
+ const price = prices.get(usage.model);
16
+ if (price === undefined)
17
+ return undefined;
18
+ const micros = Math.round(usage.inputTokens * price.input + usage.outputTokens * price.output);
19
+ // price is per million tokens, so tokens × price is already in millionths of a dollar.
20
+ return micros / 1_000_000;
21
+ }
22
+ //# sourceMappingURL=llm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"llm.js","sourceRoot":"","sources":["../../src/domain/llm.ts"],"names":[],"mappings":"AAAA,wFAAwF;AACxF,MAAM,CAAC,MAAM,cAAc,GAAG,WAAW,CAAC;AAE1C;;;;GAIG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,IAAI,CAAC;AAiB9C;;;;GAIG;AACH,MAAM,UAAU,UAAU,CAAC,MAAiB,EAAE,KAAe;IAC3D,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACtC,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC1C,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,GAAG,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,YAAY,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC;IAC/F,uFAAuF;IACvF,OAAO,MAAM,GAAG,SAAS,CAAC;AAC5B,CAAC"}
@@ -0,0 +1,21 @@
1
+ /** Bounds a step's maxAttempts: a step that needs more is better served by a longer cap. */
2
+ export const MAX_STEP_ATTEMPTS = 100;
3
+ /**
4
+ * Full jitter (PRD §5): a uniform draw from [0, min(cap, base × 2^(failures - 1))). Steps
5
+ * that failed together, say during a provider outage, come back spread out instead of
6
+ * returning at the same moment and failing again.
7
+ */
8
+ export function retryDelayMs(failures, policy, random = Math.random) {
9
+ // 2^n is Infinity for large n; min() keeps the ceiling finite.
10
+ const ceiling = Math.min(policy.capMs, policy.baseMs * 2 ** (failures - 1));
11
+ return Math.floor(random() * ceiling);
12
+ }
13
+ /** What happens to a run after one of its steps failed. */
14
+ export function decideAfterStepFailure(facts, policy, random = Math.random) {
15
+ if (!facts.retryable)
16
+ return { kind: "fail", reason: "non_retryable" };
17
+ if (facts.failures >= facts.maxAttempts)
18
+ return { kind: "fail", reason: "attempts_exhausted" };
19
+ return { kind: "retry", delayMs: retryDelayMs(facts.failures, policy, random) };
20
+ }
21
+ //# sourceMappingURL=retry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/domain/retry.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,MAAM,CAAC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AASrC;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAC1B,QAAgB,EAChB,MAAmB,EACnB,SAAuB,IAAI,CAAC,MAAM;IAElC,+DAA+D;IAC/D,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC;IAC5E,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC;AACxC,CAAC;AAaD,2DAA2D;AAC3D,MAAM,UAAU,sBAAsB,CACpC,KAAuB,EACvB,MAAmB,EACnB,SAAuB,IAAI,CAAC,MAAM;IAElC,IAAI,CAAC,KAAK,CAAC,SAAS;QAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,eAAe,EAAE,CAAC;IACvE,IAAI,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,WAAW;QAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,oBAAoB,EAAE,CAAC;IAC/F,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,CAAC;AAClF,CAAC"}