@open-wa/runtime-core 5.0.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.
- package/LICENSE.md +67 -0
- package/README.md +21 -0
- package/dist/index.cjs +568 -0
- package/dist/index.d.cts +341 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +341 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +530 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +42 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
### Copyright (c) 2020 Mohammed Shah
|
|
2
|
+
|
|
3
|
+
# Hippocratic + Do Not Harm (H-DNH) Version 1.1
|
|
4
|
+
|
|
5
|
+
## Preamble
|
|
6
|
+
|
|
7
|
+
Most software today is developed with little to no thought of how it will be used, or the consequences for our society and planet.
|
|
8
|
+
|
|
9
|
+
As software developers, we engineer the infrastructure of the 21st century. We recognise that our infrastructure has great power to shape the world and the lives of those we share it with, and we choose to consciously take responsibility for the social and environmental impacts of what we build.
|
|
10
|
+
|
|
11
|
+
We envisage a world free from injustice, inequality, and the reckless destruction of lives and our planet. We reject slavery in all its forms, whether by force, indebtedness, or by algorithms that hack human vulnerabilities. We seek a world where humankind is at peace with our neighbours, nature, and ourselves. We want our work to enrich the physical, mental and spiritual wellbeing of all society.
|
|
12
|
+
|
|
13
|
+
We build software to further this vision of a just world, or at the very least, to not put that vision further from reach.
|
|
14
|
+
|
|
15
|
+
## Terms
|
|
16
|
+
|
|
17
|
+
Licensor hereby grants permission by this license ("License"), free of charge, to any person or entity (the "Licensee") obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
18
|
+
|
|
19
|
+
1. All redistribution of source code or binary form, including any modifications must be under these terms. You must inform recipients that the code is governed by these conditions, and how they can obtain a copy of this license. You may not attempt to alter the conditions of who may/may not use this software.
|
|
20
|
+
|
|
21
|
+
2. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
|
22
|
+
|
|
23
|
+
3. This software must not be used by any organisation, website, product or service that:
|
|
24
|
+
|
|
25
|
+
a) lobbies for, promotes, or derives a majority of income from actions that support or contribute to:
|
|
26
|
+
* sex trafficking
|
|
27
|
+
* human trafficking
|
|
28
|
+
* slavery
|
|
29
|
+
* indentured servitude
|
|
30
|
+
* gambling
|
|
31
|
+
* tobacco
|
|
32
|
+
* adversely addictive behaviours
|
|
33
|
+
* nuclear energy
|
|
34
|
+
* warfare
|
|
35
|
+
* weapons manufacturing
|
|
36
|
+
* war crimes
|
|
37
|
+
* settler colonialism
|
|
38
|
+
* apartheid
|
|
39
|
+
* vaccine misinformation
|
|
40
|
+
* climate misinformation
|
|
41
|
+
* child endangerment
|
|
42
|
+
* violence (except when required to protect public safety)
|
|
43
|
+
* burning of forests
|
|
44
|
+
* deforestation
|
|
45
|
+
* hate speech or discrimination based on age, gender, gender identity, race, sexuality, religion, nationality
|
|
46
|
+
|
|
47
|
+
b) lobbies against, or derives a majority of income from actions that discourage or frustrate:
|
|
48
|
+
* peace
|
|
49
|
+
* access to the rights set out in the Universal Declaration of Human Rights and the Convention on the Rights of the Child
|
|
50
|
+
* peaceful assembly and association (including worker associations)
|
|
51
|
+
* a safe environment or action to curtail the use of fossil fuels or prevent climate change
|
|
52
|
+
* democratic processes
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
4. Compliance with Human Rights Laws and Human Rights Principles:
|
|
56
|
+
|
|
57
|
+
a. **Human Rights Laws**. The Software shall not be used by any person or entity for any systems, activities, or other uses that violate any applicable laws, regulations, or rules that protect human, civil, labor, privacy, political, environmental, security, economic, due process, or similar rights (the "Human Rights Laws"). Where the Human Rights Laws of more than one jurisdiction are applicable to the use of the Software, the Human Rights Laws that are most protective of the individuals or groups harmed shall apply.
|
|
58
|
+
|
|
59
|
+
b. **Human Rights Principles**. Licensee is advised to consult the articles of the United Nations Universal Declaration of Human Rights (https://www.un.org/en/universal-declaration-human-rights/) and the United Nations Global Compact (https://www.unglobalcompact.org/ what-is-gc/mission/principles) that define recognized principles of international human rights (the "Human Rights Principles"). It is Licensor's express intent that all use of the Software be consistent with Human Rights Principles. If Licensor receives notification or otherwise learns of an alleged violation of any Human Rights Principles relating to Licensee's use of the Software, Licensor may in its discretion and without obligation (i) (a) notify Licensee of such allegation and (b) allow Licensee 90 days from notification under (i)(a) to investigate and respond to Licensor regarding the allegation and (ii) (a) after the earlier of 90 days from notification under (i)(a), or Licensee's response under (i)(b), notify Licensee of License termination and (b) allow Licensee an additional 90 days from notification under (ii)(a) to cease use of the Software.
|
|
60
|
+
|
|
61
|
+
c. **Indemnity**. Licensee shall hold harmless and indemnify Licensor against all losses, damages, liabilities, deficiencies, claims, actions, judgments, settlements, interest, awards, penalties, fines, costs, or expenses of whatever kind, including Licensor's reasonable attorneys' fees, arising out of or relating to Licensee's non-compliance with this License or use of the Software in violation of Human Rights Laws or Human Rights Principles.
|
|
62
|
+
|
|
63
|
+
5. Enforceability: If any portion or provision of this License is determined to be invalid, illegal, or unenforceable by a court of competent jurisdiction, then such invalidity, illegality, or unenforceability shall not affect any other term or provision of this License or invalidate or render unenforceable such term or provision in any other jurisdiction. Upon a determination that any term or provision is invalid, illegal, or unenforceable, to the extent permitted by applicable law, the court may modify this License to affect the original intent of the parties as closely as possible. The section headings are for convenience only and are not intended to affect the construction or interpretation of this License. Any rule of construction to the effect that ambiguities are to be resolved against the drafting party shall not apply in interpreting this License. The language in this License shall be interpreted as to its fair meaning and not strictly for or against any party.
|
|
64
|
+
|
|
65
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
66
|
+
|
|
67
|
+
This license is an extension of the Hippocratic License - an Ethical Source license (https://ethicalsource.dev) and the Do Not Harm License - (https://github.com/raisely/NoHarm)
|
package/README.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# @open-wa/runtime-core
|
|
2
|
+
|
|
3
|
+
Portable Effect runtime capabilities for open-wa
|
|
4
|
+
|
|
5
|
+
Part of the [@open-wa v5 monorepo](https://github.com/open-wa/wa-automate-nodejs).
|
|
6
|
+
|
|
7
|
+
## Development
|
|
8
|
+
|
|
9
|
+
- `pnpm --filter @open-wa/runtime-core build`
|
|
10
|
+
- `pnpm --filter @open-wa/runtime-core test`
|
|
11
|
+
- `pnpm --filter @open-wa/runtime-core lint`
|
|
12
|
+
- `pnpm --filter @open-wa/runtime-core typecheck`
|
|
13
|
+
- `pnpm --filter @open-wa/runtime-core clean`
|
|
14
|
+
|
|
15
|
+
## Documentation
|
|
16
|
+
|
|
17
|
+
See the [docs site](https://docs.openwa.dev).
|
|
18
|
+
|
|
19
|
+
## License
|
|
20
|
+
|
|
21
|
+
[H-DNH 1.1](https://github.com/open-wa/wa-automate-nodejs/blob/master/LICENSE.md) - Hippocratic + Do Not Harm
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let effect = require("effect");
|
|
3
|
+
let effect_unstable_httpapi = require("effect/unstable/httpapi");
|
|
4
|
+
let effect_unstable_rpc = require("effect/unstable/rpc");
|
|
5
|
+
//#region src/errors.ts
|
|
6
|
+
var RuntimeCapabilityError = class extends effect.Data.TaggedError("RuntimeCapabilityError") {};
|
|
7
|
+
var QueueOverloadedError = class extends effect.Data.TaggedError("QueueOverloadedError") {};
|
|
8
|
+
var QueueClosedError = class extends effect.Data.TaggedError("QueueClosedError") {};
|
|
9
|
+
var TaskTimeoutError = class extends effect.Data.TaggedError("TaskTimeoutError") {};
|
|
10
|
+
var TaskExecutionError = class extends effect.Data.TaggedError("TaskExecutionError") {};
|
|
11
|
+
var StartupGraphError = class extends effect.Data.TaggedError("StartupGraphError") {};
|
|
12
|
+
var SandboxPolicyError = class extends effect.Data.TaggedError("SandboxPolicyError") {};
|
|
13
|
+
var SandboxExecutionError = class extends effect.Data.TaggedError("SandboxExecutionError") {};
|
|
14
|
+
var SessionAdmissionError = class extends effect.Data.TaggedError("SessionAdmissionError") {};
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region src/effect-spikes.ts
|
|
17
|
+
const RuntimeHealthSchema = effect.Schema.Struct({
|
|
18
|
+
sessionId: effect.Schema.String,
|
|
19
|
+
state: effect.Schema.Literals([
|
|
20
|
+
"STARTING",
|
|
21
|
+
"AUTHENTICATING",
|
|
22
|
+
"READY",
|
|
23
|
+
"DISCONNECTED",
|
|
24
|
+
"STOPPED"
|
|
25
|
+
]),
|
|
26
|
+
ready: effect.Schema.Boolean
|
|
27
|
+
});
|
|
28
|
+
const RuntimeEventSchema = effect.Schema.Struct({
|
|
29
|
+
event: effect.Schema.String,
|
|
30
|
+
sessionId: effect.Schema.String,
|
|
31
|
+
timestamp: effect.Schema.Number,
|
|
32
|
+
payload: effect.Schema.Unknown
|
|
33
|
+
});
|
|
34
|
+
const OpenWaHttpApi = effect_unstable_httpapi.HttpApi.make("openwa").add(effect_unstable_httpapi.HttpApiGroup.make("runtime").add(effect_unstable_httpapi.HttpApiEndpoint.get("health", "/health", { success: RuntimeHealthSchema })));
|
|
35
|
+
const OpenWaAskRpc = effect_unstable_rpc.Rpc.make("openwa.ask", {
|
|
36
|
+
payload: {
|
|
37
|
+
method: effect.Schema.String,
|
|
38
|
+
args: effect.Schema.Array(effect.Schema.Unknown)
|
|
39
|
+
},
|
|
40
|
+
success: effect.Schema.Unknown
|
|
41
|
+
});
|
|
42
|
+
const decodeRuntimeEvent = effect.Schema.decodeUnknownEffect(RuntimeEventSchema);
|
|
43
|
+
const makeBoundedEventPipeline = (capacity) => effect.Effect.gen(function* () {
|
|
44
|
+
const pubsub = yield* effect.PubSub.bounded(capacity);
|
|
45
|
+
return {
|
|
46
|
+
publish: (event) => effect.PubSub.publish(pubsub, event),
|
|
47
|
+
events: effect.Stream.fromPubSub(pubsub),
|
|
48
|
+
shutdown: effect.PubSub.shutdown(pubsub)
|
|
49
|
+
};
|
|
50
|
+
});
|
|
51
|
+
//#endregion
|
|
52
|
+
//#region src/services.ts
|
|
53
|
+
const RuntimeCapabilities = effect.Context.Service("@open-wa/RuntimeCapabilities");
|
|
54
|
+
const BrowserDriver = effect.Context.Service("@open-wa/BrowserDriver");
|
|
55
|
+
const BrowserSession = effect.Context.Service("@open-wa/BrowserSession");
|
|
56
|
+
const PatchSource = effect.Context.Service("@open-wa/PatchSource");
|
|
57
|
+
const LicenseService = effect.Context.Service("@open-wa/LicenseService");
|
|
58
|
+
const SessionStore = effect.Context.Service("@open-wa/SessionStore");
|
|
59
|
+
const PluginRegistry = effect.Context.Service("@open-wa/PluginRegistry");
|
|
60
|
+
const ChatExecutor = effect.Context.Service("@open-wa/ChatExecutor");
|
|
61
|
+
const SessionAdmission = effect.Context.Service("@open-wa/SessionAdmission");
|
|
62
|
+
const RuntimeObservability = effect.Context.Service("@open-wa/RuntimeObservability");
|
|
63
|
+
const serviceLayer = (key, service) => effect.Layer.succeed(key, service);
|
|
64
|
+
//#endregion
|
|
65
|
+
//#region src/observability.ts
|
|
66
|
+
const serializeCause = (cause, seen = /* @__PURE__ */ new Set()) => {
|
|
67
|
+
if (!(cause instanceof Error)) return {
|
|
68
|
+
name: typeof cause,
|
|
69
|
+
message: String(cause)
|
|
70
|
+
};
|
|
71
|
+
if (seen.has(cause)) return {
|
|
72
|
+
name: cause.name,
|
|
73
|
+
message: `${cause.message} [circular cause]`
|
|
74
|
+
};
|
|
75
|
+
seen.add(cause);
|
|
76
|
+
const nested = "cause" in cause && cause.cause !== void 0 ? serializeCause(cause.cause, seen) : void 0;
|
|
77
|
+
const errors = cause instanceof AggregateError ? cause.errors.map((error) => serializeCause(error, seen)) : void 0;
|
|
78
|
+
return {
|
|
79
|
+
name: cause.name,
|
|
80
|
+
message: cause.message,
|
|
81
|
+
...cause.stack ? { stack: cause.stack } : {},
|
|
82
|
+
...nested ? { cause: nested } : {},
|
|
83
|
+
...errors ? { errors } : {}
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
const makeInMemoryObservability = () => {
|
|
87
|
+
const values = /* @__PURE__ */ new Map();
|
|
88
|
+
const causes = [];
|
|
89
|
+
const keyFor = (metric, attributes) => {
|
|
90
|
+
if (!attributes || Object.keys(attributes).length === 0) return metric;
|
|
91
|
+
return `${metric}{${Object.entries(attributes).sort(([left], [right]) => left.localeCompare(right)).map(([key, value]) => `${key}=${String(value)}`).join(",")}}`;
|
|
92
|
+
};
|
|
93
|
+
return {
|
|
94
|
+
increment: (metric, value = 1, attributes) => effect.Effect.sync(() => {
|
|
95
|
+
const key = keyFor(metric, attributes);
|
|
96
|
+
values.set(key, (values.get(key) ?? 0) + value);
|
|
97
|
+
}),
|
|
98
|
+
gauge: (metric, value, attributes) => effect.Effect.sync(() => {
|
|
99
|
+
values.set(keyFor(metric, attributes), value);
|
|
100
|
+
}),
|
|
101
|
+
snapshot: effect.Effect.sync(() => Object.fromEntries(values)),
|
|
102
|
+
recordCause: (scope, cause, attributes) => effect.Effect.sync(() => {
|
|
103
|
+
causes.push({
|
|
104
|
+
scope,
|
|
105
|
+
recordedAt: Date.now(),
|
|
106
|
+
...attributes ? { attributes } : {},
|
|
107
|
+
cause: serializeCause(cause)
|
|
108
|
+
});
|
|
109
|
+
const key = keyFor("cause_failures", {
|
|
110
|
+
scope,
|
|
111
|
+
...attributes
|
|
112
|
+
});
|
|
113
|
+
values.set(key, (values.get(key) ?? 0) + 1);
|
|
114
|
+
}),
|
|
115
|
+
causes: effect.Effect.sync(() => causes.map((record) => ({ ...record })))
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
const InMemoryObservabilityLayer = effect.Layer.sync(RuntimeObservability, makeInMemoryObservability);
|
|
119
|
+
const queueMetricsObserver = (observability) => {
|
|
120
|
+
let previousDropped = 0;
|
|
121
|
+
let previousFailed = 0;
|
|
122
|
+
let previousRateLimited = 0;
|
|
123
|
+
return (metrics) => {
|
|
124
|
+
const attributes = { queue: metrics.name };
|
|
125
|
+
effect.Effect.runSync(effect.Effect.all([
|
|
126
|
+
observability.gauge("queue_depth", metrics.depth, attributes),
|
|
127
|
+
observability.gauge("queue_active", metrics.active, attributes),
|
|
128
|
+
observability.gauge("active_fibers", metrics.active, attributes),
|
|
129
|
+
observability.increment("queue_drops", Math.max(0, metrics.dropped - previousDropped), attributes),
|
|
130
|
+
observability.increment("queue_failures", Math.max(0, metrics.failed - previousFailed), attributes),
|
|
131
|
+
observability.increment("rate_decisions", Math.max(0, metrics.rateLimited - previousRateLimited), attributes)
|
|
132
|
+
]));
|
|
133
|
+
previousDropped = metrics.dropped;
|
|
134
|
+
previousFailed = metrics.failed;
|
|
135
|
+
previousRateLimited = metrics.rateLimited;
|
|
136
|
+
};
|
|
137
|
+
};
|
|
138
|
+
//#endregion
|
|
139
|
+
//#region src/runtime-capabilities.ts
|
|
140
|
+
const makeRuntimeCapabilities = (runtime, capabilities) => {
|
|
141
|
+
const supported = new Set(capabilities);
|
|
142
|
+
return {
|
|
143
|
+
runtime,
|
|
144
|
+
supported,
|
|
145
|
+
has: (capability) => supported.has(capability),
|
|
146
|
+
require: (capability) => supported.has(capability) ? effect.Effect.void : effect.Effect.fail(new RuntimeCapabilityError({
|
|
147
|
+
capability,
|
|
148
|
+
runtime,
|
|
149
|
+
detail: `${runtime} does not provide ${capability}`
|
|
150
|
+
}))
|
|
151
|
+
};
|
|
152
|
+
};
|
|
153
|
+
const runtimeCapabilitiesLayer = (runtime, capabilities) => effect.Layer.succeed(RuntimeCapabilities, makeRuntimeCapabilities(runtime, capabilities));
|
|
154
|
+
//#endregion
|
|
155
|
+
//#region src/sandbox.ts
|
|
156
|
+
const defaultChatSandboxPolicy = {
|
|
157
|
+
chats: false,
|
|
158
|
+
isolation: "process",
|
|
159
|
+
timeoutMs: 3e4,
|
|
160
|
+
idleTimeoutMs: 3e5,
|
|
161
|
+
memoryMb: 256,
|
|
162
|
+
concurrency: 1,
|
|
163
|
+
filesystem: "none",
|
|
164
|
+
network: "none",
|
|
165
|
+
networkAllowlist: [],
|
|
166
|
+
env: "none",
|
|
167
|
+
capabilities: ["sendText"]
|
|
168
|
+
};
|
|
169
|
+
const ExecutionSandbox = effect.Context.Service("@open-wa/ExecutionSandbox");
|
|
170
|
+
/** Cause capture only. This function does not provide a security boundary. */
|
|
171
|
+
const captureSandboxCause = (effect$2) => effect.Effect.sandbox(effect$2);
|
|
172
|
+
//#endregion
|
|
173
|
+
//#region src/scoped-task-queue.ts
|
|
174
|
+
var ScopedTaskQueue = class ScopedTaskQueue {
|
|
175
|
+
policy;
|
|
176
|
+
queue;
|
|
177
|
+
scope;
|
|
178
|
+
activeTasks = /* @__PURE__ */ new Set();
|
|
179
|
+
metricsState = {
|
|
180
|
+
depth: 0,
|
|
181
|
+
active: 0,
|
|
182
|
+
completed: 0,
|
|
183
|
+
failed: 0,
|
|
184
|
+
dropped: 0,
|
|
185
|
+
rateLimited: 0,
|
|
186
|
+
closed: false
|
|
187
|
+
};
|
|
188
|
+
rateWindowStartedAt = Date.now();
|
|
189
|
+
rateWindowCount = 0;
|
|
190
|
+
constructor(policy, queue, scope) {
|
|
191
|
+
this.policy = policy;
|
|
192
|
+
this.queue = queue;
|
|
193
|
+
this.scope = scope;
|
|
194
|
+
}
|
|
195
|
+
static async make(policy) {
|
|
196
|
+
if (!Number.isInteger(policy.capacity) || policy.capacity < 1) throw new RangeError("queue capacity must be a positive integer");
|
|
197
|
+
if (!Number.isInteger(policy.concurrency) || policy.concurrency < 1) throw new RangeError("queue concurrency must be a positive integer");
|
|
198
|
+
if (policy.rate && (!Number.isInteger(policy.rate.limit) || policy.rate.limit < 1 || !Number.isFinite(policy.rate.intervalMs) || policy.rate.intervalMs <= 0)) throw new RangeError("queue rate limit and interval must be positive");
|
|
199
|
+
const normalized = {
|
|
200
|
+
...policy,
|
|
201
|
+
ordering: "fifo"
|
|
202
|
+
};
|
|
203
|
+
const scope = await effect.Effect.runPromise(effect.Scope.make());
|
|
204
|
+
const queue = await effect.Effect.runPromise(normalized.overload === "dropping" ? effect.Queue.dropping(normalized.capacity) : effect.Queue.bounded(normalized.capacity));
|
|
205
|
+
const taskQueue = new ScopedTaskQueue(normalized, queue, scope);
|
|
206
|
+
for (let index = 0; index < normalized.concurrency; index += 1) await effect.Effect.runPromise(effect.Effect.forkIn(taskQueue.worker(index), scope));
|
|
207
|
+
return taskQueue;
|
|
208
|
+
}
|
|
209
|
+
submit(operation, label) {
|
|
210
|
+
if (this.metricsState.closed) return Promise.reject(new QueueClosedError({ queue: this.policy.name }));
|
|
211
|
+
return new Promise((resolve, reject) => {
|
|
212
|
+
const task = {
|
|
213
|
+
operation: async () => operation(),
|
|
214
|
+
resolve: (value) => resolve(value),
|
|
215
|
+
reject,
|
|
216
|
+
enqueuedAt: Date.now(),
|
|
217
|
+
label
|
|
218
|
+
};
|
|
219
|
+
this.metricsState.depth += 1;
|
|
220
|
+
this.notifyObserver();
|
|
221
|
+
effect.Effect.runPromise(effect.Queue.offer(this.queue, task)).then((accepted) => {
|
|
222
|
+
if (!accepted) {
|
|
223
|
+
this.metricsState.depth = Math.max(0, this.metricsState.depth - 1);
|
|
224
|
+
this.metricsState.dropped += 1;
|
|
225
|
+
this.notifyObserver();
|
|
226
|
+
reject(new QueueOverloadedError({
|
|
227
|
+
queue: this.policy.name,
|
|
228
|
+
capacity: this.policy.capacity
|
|
229
|
+
}));
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
}).catch((error) => {
|
|
233
|
+
this.metricsState.depth = Math.max(0, this.metricsState.depth - 1);
|
|
234
|
+
this.notifyObserver();
|
|
235
|
+
reject(this.metricsState.closed ? new QueueClosedError({ queue: this.policy.name }) : error);
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
metrics() {
|
|
240
|
+
return {
|
|
241
|
+
name: this.policy.name,
|
|
242
|
+
capacity: this.policy.capacity,
|
|
243
|
+
...this.metricsState
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
async close() {
|
|
247
|
+
if (this.metricsState.closed) return;
|
|
248
|
+
this.metricsState.closed = true;
|
|
249
|
+
this.notifyObserver();
|
|
250
|
+
while (true) {
|
|
251
|
+
const result = effect.Queue.takeUnsafe(this.queue);
|
|
252
|
+
if (result === void 0) break;
|
|
253
|
+
if (effect.Exit.isFailure(result)) continue;
|
|
254
|
+
this.metricsState.depth = Math.max(0, this.metricsState.depth - 1);
|
|
255
|
+
result.value.reject(new QueueClosedError({ queue: this.policy.name }));
|
|
256
|
+
this.notifyObserver();
|
|
257
|
+
}
|
|
258
|
+
for (const task of this.activeTasks) task.reject(new QueueClosedError({ queue: this.policy.name }));
|
|
259
|
+
this.activeTasks.clear();
|
|
260
|
+
this.metricsState.active = 0;
|
|
261
|
+
this.notifyObserver();
|
|
262
|
+
await effect.Effect.runPromise(effect.Queue.shutdown(this.queue));
|
|
263
|
+
await effect.Effect.runPromise(effect.Scope.close(this.scope, effect.Exit.void));
|
|
264
|
+
}
|
|
265
|
+
async waitForIdle() {
|
|
266
|
+
while (this.metricsState.depth > 0 || this.metricsState.active > 0) await effect.Effect.runPromise(effect.Effect.sleep(5));
|
|
267
|
+
}
|
|
268
|
+
worker(index) {
|
|
269
|
+
const self = this;
|
|
270
|
+
return effect.Effect.gen(function* () {
|
|
271
|
+
while (true) {
|
|
272
|
+
const task = yield* effect.Queue.take(self.queue);
|
|
273
|
+
self.metricsState.depth = Math.max(0, self.metricsState.depth - 1);
|
|
274
|
+
yield* self.reserveRatePermit();
|
|
275
|
+
self.activeTasks.add(task);
|
|
276
|
+
self.metricsState.active += 1;
|
|
277
|
+
self.notifyObserver();
|
|
278
|
+
let execution = effect.Effect.tryPromise({
|
|
279
|
+
try: task.operation,
|
|
280
|
+
catch: (cause) => new TaskExecutionError({
|
|
281
|
+
queue: self.policy.name,
|
|
282
|
+
cause
|
|
283
|
+
})
|
|
284
|
+
});
|
|
285
|
+
if (self.policy.timeoutMs !== void 0) execution = execution.pipe(effect.Effect.timeoutOrElse({
|
|
286
|
+
duration: self.policy.timeoutMs,
|
|
287
|
+
orElse: () => effect.Effect.fail(new TaskTimeoutError({
|
|
288
|
+
queue: self.policy.name,
|
|
289
|
+
timeoutMs: self.policy.timeoutMs
|
|
290
|
+
}))
|
|
291
|
+
}));
|
|
292
|
+
const result = yield* effect.Effect.exit(execution.pipe(effect.Effect.withSpan(`openwa.queue.${self.policy.name}`, { attributes: {
|
|
293
|
+
"queue.name": self.policy.name,
|
|
294
|
+
"queue.worker": index,
|
|
295
|
+
"queue.wait_ms": Date.now() - task.enqueuedAt,
|
|
296
|
+
...task.label ? { "task.label": task.label } : {}
|
|
297
|
+
} })));
|
|
298
|
+
self.activeTasks.delete(task);
|
|
299
|
+
self.metricsState.active = Math.max(0, self.metricsState.active - 1);
|
|
300
|
+
if (effect.Exit.isSuccess(result)) {
|
|
301
|
+
self.metricsState.completed += 1;
|
|
302
|
+
task.resolve(result.value);
|
|
303
|
+
} else {
|
|
304
|
+
self.metricsState.failed += 1;
|
|
305
|
+
task.reject(effect.Cause.squash(result.cause));
|
|
306
|
+
}
|
|
307
|
+
self.notifyObserver();
|
|
308
|
+
}
|
|
309
|
+
}).pipe(effect.Effect.withSpan(`openwa.queue.worker.${self.policy.name}`));
|
|
310
|
+
}
|
|
311
|
+
reserveRatePermit() {
|
|
312
|
+
const rate = this.policy.rate;
|
|
313
|
+
if (!rate) return effect.Effect.void;
|
|
314
|
+
const self = this;
|
|
315
|
+
return effect.Effect.suspend(() => {
|
|
316
|
+
const now = Date.now();
|
|
317
|
+
const elapsed = now - self.rateWindowStartedAt;
|
|
318
|
+
if (elapsed >= rate.intervalMs) {
|
|
319
|
+
self.rateWindowStartedAt = now;
|
|
320
|
+
self.rateWindowCount = 0;
|
|
321
|
+
}
|
|
322
|
+
if (self.rateWindowCount < rate.limit) {
|
|
323
|
+
self.rateWindowCount += 1;
|
|
324
|
+
return effect.Effect.void;
|
|
325
|
+
}
|
|
326
|
+
self.metricsState.rateLimited += 1;
|
|
327
|
+
self.notifyObserver();
|
|
328
|
+
return effect.Effect.sleep(Math.max(1, rate.intervalMs - elapsed)).pipe(effect.Effect.andThen(self.reserveRatePermit()));
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
notifyObserver() {
|
|
332
|
+
try {
|
|
333
|
+
this.policy.observe?.(this.metrics());
|
|
334
|
+
} catch {}
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
//#endregion
|
|
338
|
+
//#region src/session-admission.ts
|
|
339
|
+
const makeSessionAdmission = (options) => effect.Effect.gen(function* () {
|
|
340
|
+
const memory = yield* effect.Semaphore.make(options.memoryCapacityMb);
|
|
341
|
+
const launches = yield* effect.Semaphore.make(options.maxConcurrentLaunches);
|
|
342
|
+
let activeSessions = 0;
|
|
343
|
+
let availableMemoryMb = options.memoryCapacityMb;
|
|
344
|
+
return {
|
|
345
|
+
acquire: (memoryMb) => effect.Effect.gen(function* () {
|
|
346
|
+
if (memoryMb > options.memoryCapacityMb) return yield* effect.Effect.fail(new SessionAdmissionError({
|
|
347
|
+
requestedMemoryMb: memoryMb,
|
|
348
|
+
availableMemoryMb
|
|
349
|
+
}));
|
|
350
|
+
yield* effect.Semaphore.take(memory, memoryMb);
|
|
351
|
+
yield* effect.Semaphore.take(launches, 1);
|
|
352
|
+
availableMemoryMb -= memoryMb;
|
|
353
|
+
activeSessions += 1;
|
|
354
|
+
if (options.observability) yield* options.observability.gauge("session_browser_memory_mb", options.memoryCapacityMb - availableMemoryMb);
|
|
355
|
+
let released = false;
|
|
356
|
+
return {
|
|
357
|
+
memoryMb,
|
|
358
|
+
release: effect.Effect.suspend(() => {
|
|
359
|
+
if (released) return effect.Effect.void;
|
|
360
|
+
released = true;
|
|
361
|
+
activeSessions = Math.max(0, activeSessions - 1);
|
|
362
|
+
availableMemoryMb = Math.min(options.memoryCapacityMb, availableMemoryMb + memoryMb);
|
|
363
|
+
return effect.Effect.all([
|
|
364
|
+
effect.Semaphore.release(memory, memoryMb),
|
|
365
|
+
effect.Semaphore.release(launches, 1),
|
|
366
|
+
...options.observability ? [options.observability.gauge("session_browser_memory_mb", options.memoryCapacityMb - availableMemoryMb)] : []
|
|
367
|
+
]).pipe(effect.Effect.asVoid);
|
|
368
|
+
})
|
|
369
|
+
};
|
|
370
|
+
}),
|
|
371
|
+
snapshot: effect.Effect.sync(() => ({
|
|
372
|
+
capacityMemoryMb: options.memoryCapacityMb,
|
|
373
|
+
availableMemoryMb,
|
|
374
|
+
activeSessions
|
|
375
|
+
}))
|
|
376
|
+
};
|
|
377
|
+
});
|
|
378
|
+
const sessionAdmissionLayer = (options) => effect.Layer.effect(SessionAdmission, makeSessionAdmission(options));
|
|
379
|
+
//#endregion
|
|
380
|
+
//#region src/session-scope.ts
|
|
381
|
+
var SessionScope = class SessionScope {
|
|
382
|
+
scope;
|
|
383
|
+
observability;
|
|
384
|
+
metricAttributes;
|
|
385
|
+
finalizerNames = /* @__PURE__ */ new Set();
|
|
386
|
+
closed = false;
|
|
387
|
+
activeFibers = 0;
|
|
388
|
+
constructor(scope, observability, metricAttributes = {}) {
|
|
389
|
+
this.scope = scope;
|
|
390
|
+
this.observability = observability;
|
|
391
|
+
this.metricAttributes = metricAttributes;
|
|
392
|
+
}
|
|
393
|
+
static async make(options = {}) {
|
|
394
|
+
return new SessionScope(await effect.Effect.runPromise(effect.Scope.make()), options.observability, options.metricAttributes);
|
|
395
|
+
}
|
|
396
|
+
async addFinalizer(name, finalizer) {
|
|
397
|
+
if (this.closed) throw new Error("session scope is already closed");
|
|
398
|
+
this.finalizerNames.add(name);
|
|
399
|
+
let active = true;
|
|
400
|
+
await effect.Effect.runPromise(effect.Scope.addFinalizer(this.scope, effect.Effect.promise(async () => {
|
|
401
|
+
if (!active) return;
|
|
402
|
+
active = false;
|
|
403
|
+
this.finalizerNames.delete(name);
|
|
404
|
+
await finalizer();
|
|
405
|
+
})));
|
|
406
|
+
return () => {
|
|
407
|
+
active = false;
|
|
408
|
+
this.finalizerNames.delete(name);
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
snapshot() {
|
|
412
|
+
return {
|
|
413
|
+
closed: this.closed,
|
|
414
|
+
finalizers: [...this.finalizerNames]
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
async fork(effect$1) {
|
|
418
|
+
if (this.closed) throw new Error("session scope is already closed");
|
|
419
|
+
const fiber = await effect.Effect.runPromise(effect.Effect.forkIn(effect$1, this.scope));
|
|
420
|
+
this.activeFibers += 1;
|
|
421
|
+
this.publishActiveFibers();
|
|
422
|
+
effect.Effect.runPromise(effect.Fiber.await(fiber)).finally(() => {
|
|
423
|
+
this.activeFibers = Math.max(0, this.activeFibers - 1);
|
|
424
|
+
this.publishActiveFibers();
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
async close(reason = "normal-stop") {
|
|
428
|
+
if (this.closed) return;
|
|
429
|
+
this.closed = true;
|
|
430
|
+
await effect.Effect.runPromise(effect.Scope.close(this.scope, reason === "normal-stop" ? effect.Exit.void : effect.Exit.fail(/* @__PURE__ */ new Error(`session scope closed: ${reason}`))));
|
|
431
|
+
}
|
|
432
|
+
publishActiveFibers() {
|
|
433
|
+
if (!this.observability) return;
|
|
434
|
+
effect.Effect.runSync(this.observability.gauge("active_fibers", this.activeFibers, {
|
|
435
|
+
owner: "session-scope",
|
|
436
|
+
...this.metricAttributes
|
|
437
|
+
}));
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
//#endregion
|
|
441
|
+
//#region src/startup-graph.ts
|
|
442
|
+
const validateStartupGraph = (nodes) => effect.Effect.try({
|
|
443
|
+
try: () => {
|
|
444
|
+
const ids = new Set(nodes.map((node) => node.id));
|
|
445
|
+
if (ids.size !== nodes.length) throw new StartupGraphError({
|
|
446
|
+
detail: "startup graph contains duplicate node ids",
|
|
447
|
+
nodes: nodes.map((node) => node.id)
|
|
448
|
+
});
|
|
449
|
+
for (const node of nodes) for (const dependency of node.dependsOn ?? []) if (!ids.has(dependency)) throw new StartupGraphError({
|
|
450
|
+
detail: `${node.id} depends on missing node ${dependency}`,
|
|
451
|
+
nodes: [node.id, dependency]
|
|
452
|
+
});
|
|
453
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
454
|
+
const visited = /* @__PURE__ */ new Set();
|
|
455
|
+
const byId = new Map(nodes.map((node) => [node.id, node]));
|
|
456
|
+
const visit = (id) => {
|
|
457
|
+
if (visited.has(id)) return;
|
|
458
|
+
if (visiting.has(id)) throw new StartupGraphError({
|
|
459
|
+
detail: `startup graph contains a cycle at ${id}`,
|
|
460
|
+
nodes: [...visiting, id]
|
|
461
|
+
});
|
|
462
|
+
visiting.add(id);
|
|
463
|
+
for (const dependency of byId.get(id)?.dependsOn ?? []) visit(dependency);
|
|
464
|
+
visiting.delete(id);
|
|
465
|
+
visited.add(id);
|
|
466
|
+
};
|
|
467
|
+
for (const node of nodes) visit(node.id);
|
|
468
|
+
},
|
|
469
|
+
catch: (error) => error instanceof StartupGraphError ? error : new StartupGraphError({
|
|
470
|
+
detail: String(error),
|
|
471
|
+
nodes: nodes.map((node) => node.id)
|
|
472
|
+
})
|
|
473
|
+
});
|
|
474
|
+
const runStartupGraph = (nodes, options = {}) => effect.Effect.gen(function* () {
|
|
475
|
+
yield* validateStartupGraph(nodes);
|
|
476
|
+
const startedAt = Date.now();
|
|
477
|
+
const pending = new Map(nodes.map((node) => [node.id, node]));
|
|
478
|
+
const values = /* @__PURE__ */ new Map();
|
|
479
|
+
const phases = [];
|
|
480
|
+
while (pending.size > 0) {
|
|
481
|
+
const ready = [...pending.values()].filter((node) => (node.dependsOn ?? []).every((dependency) => values.has(dependency)));
|
|
482
|
+
if (ready.length === 0) return yield* effect.Effect.fail(new StartupGraphError({
|
|
483
|
+
detail: "startup graph made no progress",
|
|
484
|
+
nodes: [...pending.keys()]
|
|
485
|
+
}));
|
|
486
|
+
const results = yield* effect.Effect.all(ready.map((node) => effect.Effect.gen(function* () {
|
|
487
|
+
return {
|
|
488
|
+
node,
|
|
489
|
+
nodeStartedAt: Date.now(),
|
|
490
|
+
exit: yield* effect.Effect.exit(node.run(values).pipe(effect.Effect.withSpan(`openwa.startup.${node.id}`, { attributes: {
|
|
491
|
+
"startup.node": node.id,
|
|
492
|
+
"startup.optional": node.optional ?? false
|
|
493
|
+
} })))
|
|
494
|
+
};
|
|
495
|
+
})), { concurrency: options.concurrency ?? 4 });
|
|
496
|
+
for (const { node, nodeStartedAt, exit } of results) {
|
|
497
|
+
pending.delete(node.id);
|
|
498
|
+
if (exit._tag === "Failure") {
|
|
499
|
+
if (!node.optional) return yield* effect.Effect.failCause(exit.cause);
|
|
500
|
+
values.set(node.id, exit);
|
|
501
|
+
phases.push({
|
|
502
|
+
id: node.id,
|
|
503
|
+
durationMs: Date.now() - nodeStartedAt,
|
|
504
|
+
optional: true,
|
|
505
|
+
result: exit
|
|
506
|
+
});
|
|
507
|
+
options.onPhase?.(phases.at(-1));
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
values.set(node.id, exit.value);
|
|
511
|
+
phases.push({
|
|
512
|
+
id: node.id,
|
|
513
|
+
durationMs: Date.now() - nodeStartedAt,
|
|
514
|
+
optional: node.optional ?? false,
|
|
515
|
+
result: exit.value
|
|
516
|
+
});
|
|
517
|
+
options.onPhase?.(phases.at(-1));
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
const result = {
|
|
521
|
+
values,
|
|
522
|
+
phases,
|
|
523
|
+
criticalPathMs: Date.now() - startedAt
|
|
524
|
+
};
|
|
525
|
+
options.onComplete?.(result);
|
|
526
|
+
return result;
|
|
527
|
+
});
|
|
528
|
+
//#endregion
|
|
529
|
+
exports.BrowserDriver = BrowserDriver;
|
|
530
|
+
exports.BrowserSession = BrowserSession;
|
|
531
|
+
exports.ChatExecutor = ChatExecutor;
|
|
532
|
+
exports.ExecutionSandbox = ExecutionSandbox;
|
|
533
|
+
exports.InMemoryObservabilityLayer = InMemoryObservabilityLayer;
|
|
534
|
+
exports.LicenseService = LicenseService;
|
|
535
|
+
exports.OpenWaAskRpc = OpenWaAskRpc;
|
|
536
|
+
exports.OpenWaHttpApi = OpenWaHttpApi;
|
|
537
|
+
exports.PatchSource = PatchSource;
|
|
538
|
+
exports.PluginRegistry = PluginRegistry;
|
|
539
|
+
exports.QueueClosedError = QueueClosedError;
|
|
540
|
+
exports.QueueOverloadedError = QueueOverloadedError;
|
|
541
|
+
exports.RuntimeCapabilities = RuntimeCapabilities;
|
|
542
|
+
exports.RuntimeCapabilityError = RuntimeCapabilityError;
|
|
543
|
+
exports.RuntimeEventSchema = RuntimeEventSchema;
|
|
544
|
+
exports.RuntimeHealthSchema = RuntimeHealthSchema;
|
|
545
|
+
exports.RuntimeObservability = RuntimeObservability;
|
|
546
|
+
exports.SandboxExecutionError = SandboxExecutionError;
|
|
547
|
+
exports.SandboxPolicyError = SandboxPolicyError;
|
|
548
|
+
exports.ScopedTaskQueue = ScopedTaskQueue;
|
|
549
|
+
exports.SessionAdmission = SessionAdmission;
|
|
550
|
+
exports.SessionAdmissionError = SessionAdmissionError;
|
|
551
|
+
exports.SessionScope = SessionScope;
|
|
552
|
+
exports.SessionStore = SessionStore;
|
|
553
|
+
exports.StartupGraphError = StartupGraphError;
|
|
554
|
+
exports.TaskExecutionError = TaskExecutionError;
|
|
555
|
+
exports.TaskTimeoutError = TaskTimeoutError;
|
|
556
|
+
exports.captureSandboxCause = captureSandboxCause;
|
|
557
|
+
exports.decodeRuntimeEvent = decodeRuntimeEvent;
|
|
558
|
+
exports.defaultChatSandboxPolicy = defaultChatSandboxPolicy;
|
|
559
|
+
exports.makeBoundedEventPipeline = makeBoundedEventPipeline;
|
|
560
|
+
exports.makeInMemoryObservability = makeInMemoryObservability;
|
|
561
|
+
exports.makeRuntimeCapabilities = makeRuntimeCapabilities;
|
|
562
|
+
exports.makeSessionAdmission = makeSessionAdmission;
|
|
563
|
+
exports.queueMetricsObserver = queueMetricsObserver;
|
|
564
|
+
exports.runStartupGraph = runStartupGraph;
|
|
565
|
+
exports.runtimeCapabilitiesLayer = runtimeCapabilitiesLayer;
|
|
566
|
+
exports.serviceLayer = serviceLayer;
|
|
567
|
+
exports.sessionAdmissionLayer = sessionAdmissionLayer;
|
|
568
|
+
exports.validateStartupGraph = validateStartupGraph;
|