@mettlelabs/mettle 0.0.0-beta.2-linux-arm64 → 0.0.0-beta.2

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 (62) hide show
  1. package/bin/mettle.js +53 -0
  2. package/bin/postinstall.js +28 -0
  3. package/package.json +19 -13
  4. package/THIRD_PARTY_NOTICES.md +0 -11974
  5. package/bin/mettle +0 -4
  6. package/harness/audit-investigation.mjs +0 -203
  7. package/harness/chunk-1sygmp11.mjs +0 -18142
  8. package/harness/chunk-1ykxpmaz.mjs +0 -7887
  9. package/harness/chunk-2pm2sayw.mjs +0 -248
  10. package/harness/chunk-3m7jn5ac.mjs +0 -16242
  11. package/harness/chunk-3wt8a8fq.mjs +0 -1716
  12. package/harness/chunk-3wvjs93w.mjs +0 -538
  13. package/harness/chunk-49ytr8d5.mjs +0 -33761
  14. package/harness/chunk-4bepyxmq.mjs +0 -113
  15. package/harness/chunk-4vx34w5h.mjs +0 -2357
  16. package/harness/chunk-50sbrf09.mjs +0 -18972
  17. package/harness/chunk-56csr8sw.mjs +0 -322
  18. package/harness/chunk-5wgmv4np.mjs +0 -585
  19. package/harness/chunk-65eyq32y.mjs +0 -225
  20. package/harness/chunk-6fnh6qhk.mjs +0 -195
  21. package/harness/chunk-6kgqw9ny.mjs +0 -32303
  22. package/harness/chunk-7b242j0n.mjs +0 -14
  23. package/harness/chunk-9dg1btk1.mjs +0 -2818
  24. package/harness/chunk-ageqxj9v.mjs +0 -63008
  25. package/harness/chunk-b0qbt5jd.mjs +0 -14
  26. package/harness/chunk-b5g1r3fz.mjs +0 -4785
  27. package/harness/chunk-b71gpkxg.mjs +0 -1514
  28. package/harness/chunk-bdv1rx4a.mjs +0 -20364
  29. package/harness/chunk-c1631s2x.mjs +0 -12241
  30. package/harness/chunk-c7dx5mdd.mjs +0 -10807
  31. package/harness/chunk-d5xgxsnp.mjs +0 -74
  32. package/harness/chunk-erg1fbh0.mjs +0 -0
  33. package/harness/chunk-fh78v9vn.mjs +0 -19366
  34. package/harness/chunk-fjx29qvp.mjs +0 -50
  35. package/harness/chunk-gryka6kg.mjs +0 -39
  36. package/harness/chunk-h1td5kq9.mjs +0 -422
  37. package/harness/chunk-jb0r19et.mjs +0 -180
  38. package/harness/chunk-jp69h6sj.mjs +0 -95
  39. package/harness/chunk-mfn574ss.mjs +0 -179
  40. package/harness/chunk-nz5sv9as.mjs +0 -1642
  41. package/harness/chunk-p9d3cgvq.mjs +0 -452
  42. package/harness/chunk-pq6wvwxr.mjs +0 -12
  43. package/harness/chunk-qcm9arf8.mjs +0 -7736
  44. package/harness/chunk-qr8zfqjd.mjs +0 -24
  45. package/harness/chunk-rd80vvc5.mjs +0 -22047
  46. package/harness/chunk-rz2tz6jp.mjs +0 -26
  47. package/harness/chunk-sbkgc3kn.mjs +0 -8
  48. package/harness/chunk-v66qvpnb.mjs +0 -169
  49. package/harness/chunk-vjaxzab3.mjs +0 -136
  50. package/harness/chunk-vr1n5nza.mjs +0 -1045
  51. package/harness/chunk-vsf2zajv.mjs +0 -3867
  52. package/harness/chunk-w0qwc5z2.mjs +0 -41
  53. package/harness/chunk-wq253fj4.mjs +0 -19041
  54. package/harness/chunk-wyv7ceq4.mjs +0 -0
  55. package/harness/chunk-xnqknk2r.mjs +0 -198
  56. package/harness/chunk-z6n9thea.mjs +0 -45146
  57. package/harness/chunk-zty0d3bw.mjs +0 -0
  58. package/harness/chunk-zvkxtj82.mjs +0 -42
  59. package/harness/issue-api-token.mjs +0 -35
  60. package/harness/launcher.mjs +0 -459
  61. package/harness/sandbox.mjs +0 -133
  62. package/harness/server.mjs +0 -87314
@@ -1,50 +0,0 @@
1
- import { createRequire } from "node:module";
2
- var __create = Object.create;
3
- var __getProtoOf = Object.getPrototypeOf;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- function __accessProp(key) {
8
- return this[key];
9
- }
10
- var __toESMCache_node;
11
- var __toESMCache_esm;
12
- var __toESM2 = (mod, isNodeMode, target) => {
13
- var canCache = mod != null && typeof mod === "object";
14
- if (canCache) {
15
- var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
- var cached = cache.get(mod);
17
- if (cached)
18
- return cached;
19
- }
20
- target = mod != null ? __create(__getProtoOf(mod)) : {};
21
- const to = isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
- if (mod && typeof mod === "object" || typeof mod === "function") {
23
- for (let key of __getOwnPropNames(mod))
24
- if (!__hasOwnProp.call(to, key))
25
- __defProp(to, key, {
26
- get: __accessProp.bind(mod, key),
27
- enumerable: true
28
- });
29
- }
30
- if (canCache)
31
- cache.set(mod, to);
32
- return to;
33
- };
34
- var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
35
- var __returnValue = (v) => v;
36
- function __exportSetter(name, newValue) {
37
- this[name] = __returnValue.bind(null, newValue);
38
- }
39
- var __export = (target, all) => {
40
- for (var name in all)
41
- __defProp(target, name, {
42
- get: all[name],
43
- enumerable: true,
44
- configurable: true,
45
- set: __exportSetter.bind(all, name)
46
- });
47
- };
48
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
49
-
50
- export { __toESM2, __commonJS, __export, __require };
@@ -1,39 +0,0 @@
1
- import {
2
- MastraError
3
- } from "./chunk-v66qvpnb.mjs";
4
-
5
- // node_modules/.bun/@mastra+core@1.71.0+95d98e20cbc6e6e1/node_modules/@mastra/core/dist/gateway-helpers-Dh-2ojNA.js
6
- function getCapabilityFileName(provider) {
7
- return `${encodeURIComponent(provider)}.json`;
8
- }
9
- function getGatewayId(gateway) {
10
- return gateway.getId?.() ?? gateway.id;
11
- }
12
- function shouldEnableGateway(gateway) {
13
- return gateway.shouldEnable?.() ?? true;
14
- }
15
- function hasAuthCredentials(auth) {
16
- return Boolean(auth?.apiKey || auth?.bearerToken || auth?.headers && Object.keys(auth.headers).length > 0);
17
- }
18
- function findGatewayForModel(gatewayId, gateways) {
19
- const prefixedGateway = gateways.find((g) => {
20
- const id = getGatewayId(g);
21
- return id !== "models.dev" && (id === gatewayId || gatewayId.startsWith(`${id}/`));
22
- });
23
- if (prefixedGateway)
24
- return prefixedGateway;
25
- const claimingGateway = gateways.find((g) => getGatewayId(g) !== "models.dev" && g.handlesModel?.(gatewayId) === true);
26
- if (claimingGateway)
27
- return claimingGateway;
28
- const modelsDevGateway = gateways.find((g) => getGatewayId(g) === "models.dev");
29
- if (modelsDevGateway)
30
- return modelsDevGateway;
31
- throw new MastraError({
32
- id: "MODEL_ROUTER_NO_GATEWAY_FOUND",
33
- category: "USER",
34
- domain: "MODEL_ROUTER",
35
- text: `No Mastra model router gateway found for model id ${gatewayId}`
36
- });
37
- }
38
-
39
- export { getCapabilityFileName, getGatewayId, shouldEnableGateway, hasAuthCredentials, findGatewayForModel };
@@ -1,422 +0,0 @@
1
- import {
2
- MAX_LABEL,
3
- MAX_PREVIEW_LINES,
4
- MAX_PREVIEW_LINE,
5
- HarnessError,
6
- canonicalJson,
7
- digest,
8
- captureEvidence,
9
- RUNTIME_VERSION
10
- } from "./chunk-rd80vvc5.mjs";
11
- import {
12
- PROBE_TOOL,
13
- SANDBOX_TOOLS,
14
- PostgresJournal
15
- } from "./chunk-c7dx5mdd.mjs";
16
- import {
17
- dockerJson,
18
- SandboxWorker
19
- } from "./chunk-9dg1btk1.mjs";
20
-
21
- // apps/harness/src/execution/tool-executor.ts
22
- import { setTimeout as sleep } from "node:timers/promises";
23
- var APPROVAL_TTL_MS = 600000;
24
- var INTERRUPTED = "The operator interrupted this call while it ran; its outcome is unknown.";
25
- var SETTLED_FAILURES = new Set([
26
- "tool_denied",
27
- "work_denied",
28
- "coverage_denied",
29
- "approval_denied",
30
- "approval_expired",
31
- "invalid_artifact",
32
- "sandbox_policy",
33
- "sandbox_identity",
34
- "sandbox_probe_failed",
35
- "sandbox_output",
36
- "sandbox_missing",
37
- "sandbox_timeout",
38
- "sandbox_unavailable",
39
- "sandbox_image",
40
- "candidate_denied",
41
- "candidate_conflict",
42
- "repository_bound",
43
- "source_busy",
44
- "source_unavailable",
45
- "source_encoding",
46
- "scanner_denied",
47
- "web_denied",
48
- "sandbox_task_failed",
49
- "sandbox_output_limit",
50
- "tool_interrupted"
51
- ]);
52
- function settledFailure(error) {
53
- return error instanceof HarnessError && SETTLED_FAILURES.has(error.code);
54
- }
55
-
56
- class ToolExecutor {
57
- journal;
58
- lease;
59
- signal;
60
- registry;
61
- hooks;
62
- constructor(journal, lease, signal, registry, hooks = {}) {
63
- this.journal = journal;
64
- this.lease = lease;
65
- this.signal = signal;
66
- this.registry = registry;
67
- this.hooks = hooks;
68
- }
69
- async execute(callId, name, input, turn) {
70
- if (this.signal.aborted)
71
- throw new HarnessError("stop_requested", "Execution cancelled before admission.");
72
- if (!callId)
73
- throw new HarnessError("tool_denied", "A finalized tool call identity is required.");
74
- let args;
75
- let bytes;
76
- try {
77
- bytes = canonicalJson(input);
78
- if (Buffer.byteLength(bytes, "utf8") > 65536)
79
- throw new Error("Input limit exceeded.");
80
- args = JSON.parse(bytes);
81
- } catch {
82
- throw new HarnessError("tool_denied", "Tool arguments must be bounded JSON.");
83
- }
84
- const tool = this.registry.admit(name, args, bytes);
85
- const summary = tool.summarizeArgs(args).slice(0, 512);
86
- const cachedRef = await this.journal.prepareAction(this.lease, callId, tool.name, args, {
87
- label: tool.label(args).slice(0, MAX_LABEL),
88
- summary,
89
- quiet: tool.quiet?.(args) === true
90
- }, tool.idempotent === true);
91
- if (cachedRef)
92
- return this.cached(cachedRef, tool);
93
- if (tool.unavailableReason) {
94
- await this.journal.failAction(this.lease, callId, tool.unavailableReason, "tool_denied");
95
- throw new HarnessError("tool_denied", tool.unavailableReason);
96
- }
97
- const approval = await this.requested(callId, tool, args, summary);
98
- await this.hooks.at?.("after-intent");
99
- if (this.signal.aborted)
100
- throw new HarnessError("stop_requested", "Execution cancelled before approval.");
101
- if (approval)
102
- await this.decided(callId, approval);
103
- if (this.hooks.delayBeforeDispatchMs) {
104
- try {
105
- await sleep(this.hooks.delayBeforeDispatchMs, undefined, {
106
- signal: this.signal
107
- });
108
- } catch {
109
- throw new HarnessError("stop_requested", "Fixture wait cancelled before dispatch.");
110
- }
111
- }
112
- if (this.signal.aborted)
113
- throw new HarnessError("stop_requested", "Execution cancelled before dispatch.");
114
- try {
115
- await this.journal.dispatchAction(this.lease, callId);
116
- } catch (error) {
117
- if (error instanceof HarnessError && error.code === "tool_denied")
118
- await this.journal.failAction(this.lease, callId, error.message, error.code);
119
- throw error;
120
- }
121
- await this.hooks.at?.("after-dispatch");
122
- let ref;
123
- try {
124
- const output = await tool.execute(args, turn ? AbortSignal.any([this.signal, turn]) : this.signal, callId);
125
- await this.hooks.at?.("after-effect");
126
- const result = tool.outputSchema.safeParse(output);
127
- if (!result.success)
128
- throw new HarnessError("invalid_artifact", "Tool output does not match its registered schema.");
129
- const captured = captureEvidence(result.data);
130
- const admitted = tool.outputSchema.safeParse(captured.value);
131
- if (!admitted.success || canonicalJson(admitted.data) !== captured.bytes)
132
- throw new HarnessError("invalid_artifact", "Redacted output is incompatible with the registered tool schema.");
133
- const told = tool.summarizeResult(captured.value, args);
134
- ref = await this.journal.completeAction(this.lease, callId, {
135
- value: captured.value,
136
- summary: told.summary.slice(0, 512),
137
- ...told.rejected ? { rejected: true } : {},
138
- ...told.preview?.length ? {
139
- preview: told.preview.slice(0, MAX_PREVIEW_LINES).map((line) => line.slice(0, MAX_PREVIEW_LINE))
140
- } : {}
141
- });
142
- } catch (error) {
143
- if (turn?.aborted && !this.signal.aborted && !(error instanceof HarnessError && error.code === "lease_lost")) {
144
- await this.journal.failAction(this.lease, callId, INTERRUPTED, "tool_interrupted", false);
145
- throw new HarnessError("tool_interrupted", INTERRUPTED);
146
- }
147
- await this.settle(callId, error);
148
- throw error;
149
- }
150
- await this.hooks.at?.("after-result");
151
- return (await this.journal.artifact(this.lease.runId, ref)).bytes;
152
- }
153
- async requested(callId, tool, args, summary) {
154
- const permission = tool.permission?.(args) ?? "local";
155
- if (permission === "local")
156
- return;
157
- return this.journal.requestApproval(this.lease, callId, {
158
- permission,
159
- action: (tool.approval?.action ?? `${tool.name} ${summary}`).slice(0, 512),
160
- detail: tool.approval?.detail ?? `${permission} against the live target; the effect may persist and the agent cannot undo it.`,
161
- why: tool.approval?.why ?? `The ${permission} permission reaches outside the agent's sandbox, so an operator must authorize it before the call runs.`,
162
- cleanup: tool.approval?.cleanup ?? "No automated rollback; an operator reverses any persisted effect manually if the call must be undone."
163
- }, this.hooks.approvalTtlMs ?? APPROVAL_TTL_MS);
164
- }
165
- async decided(callId, approval) {
166
- const current = await this.journal.approvalState(this.lease, approval.approvalId);
167
- if (current.decision === null)
168
- throw new HarnessError("approval_pending", "Execution is suspended until the recorded approval is decided or expires.");
169
- if (current.decision === "allow")
170
- return;
171
- const error = current.decision === "deny" ? new HarnessError("approval_denied", `The operator denied ${current.permission} for this action.`) : new HarnessError("approval_expired", `The ${current.permission} approval expired before a decision.`);
172
- await this.journal.failAction(this.lease, callId, error.message, error.code);
173
- throw error;
174
- }
175
- async settle(callId, error) {
176
- if (!(error instanceof HarnessError) || !SETTLED_FAILURES.has(error.code))
177
- return;
178
- await this.journal.failAction(this.lease, callId, error.message, error.code).catch(() => {
179
- return;
180
- });
181
- }
182
- async cached(ref, tool) {
183
- const artifact = await this.journal.artifact(this.lease.runId, ref);
184
- try {
185
- if (!tool.outputSchema.safeParse(JSON.parse(artifact.bytes)).success)
186
- throw new Error("Invalid result.");
187
- } catch {
188
- throw new HarnessError("invalid_artifact", "Stored tool output does not match its registered schema.");
189
- }
190
- return artifact.bytes;
191
- }
192
- }
193
-
194
- // apps/harness/src/storage/sandbox-journal.ts
195
- import { randomUUID } from "node:crypto";
196
- class SandboxProbeJournal extends PostgresJournal {
197
- get runtimeVersion() {
198
- return `${RUNTIME_VERSION}/sandbox-probe-v1`;
199
- }
200
- }
201
-
202
- class SandboxJournal {
203
- journal;
204
- lease;
205
- constructor(journal, lease) {
206
- this.journal = journal;
207
- this.lease = lease;
208
- }
209
- async reserve(callId, workerId, image, policyDigest, binding = { tool: PROBE_TOOL, args: {} }, page) {
210
- if (!SANDBOX_TOOLS.includes(binding.tool) || binding.tool === PROBE_TOOL && digest(binding.args) !== digest({}))
211
- throw new HarnessError("sandbox_denied", "Only an approved isolated observation or fixed probe may reserve a sandbox.");
212
- return this.journal.fenced(this.lease, async ({ client }) => {
213
- const action = await client.query("SELECT 1 FROM harness_mastra.actions WHERE run_id=$1 AND call_id=$2 AND tool=$4 AND args_digest=$3 AND state='dispatched'", [this.lease.runId, callId, digest(binding.args), binding.tool]);
214
- if (!action.rowCount)
215
- throw new HarnessError("sandbox_denied", "A sandbox requires the exact committed observation dispatch.");
216
- if (page) {
217
- const available = await client.query("SELECT count(*)::int AS count,clock_timestamp()<$2::timestamptz AS active FROM harness_mastra.browser_pages WHERE run_id=$1 AND NOT closed", [this.lease.runId, page.expiresAt]);
218
- if (binding.tool !== "web_browse" || page.operation !== "open" || available.rows[0].count >= 4 || !available.rows[0].active)
219
- throw new HarnessError("browser_page_denied", "A live page requires an open operation, active grant and fewer than four retained pages.");
220
- }
221
- const record = {
222
- runId: this.lease.runId,
223
- callId,
224
- epoch: this.lease.epoch,
225
- workerId,
226
- name: `mettle-${binding.tool.replace(/^sandbox_/, "")}-${randomUUID()}`,
227
- image,
228
- policyDigest,
229
- containerId: null,
230
- state: "reserved"
231
- };
232
- const inserted = await client.query("INSERT INTO harness_mastra.sandboxes(run_id,call_id,epoch,worker_id,name,image,policy_digest,state) VALUES ($1,$2,$3,$4,$5,$6,$7,'reserved') ON CONFLICT DO NOTHING", [
233
- record.runId,
234
- callId,
235
- record.epoch,
236
- workerId,
237
- record.name,
238
- image,
239
- policyDigest
240
- ]);
241
- if (!inserted.rowCount)
242
- throw new HarnessError("uncertain_execution", "A prior sandbox reservation cannot be executed again.");
243
- if (page)
244
- await client.query("INSERT INTO harness_mastra.browser_pages(run_id,page_id,sandbox_call,owner_call,child_id,identity_id,binding_digest,epoch,expires_at) VALUES($1,$2,$3,$3,$4,$5,$6,$7,LEAST($8::timestamptz,clock_timestamp()+interval '10 minutes'))", [
245
- record.runId,
246
- page.id,
247
- callId,
248
- this.lease.child?.id ?? null,
249
- page.identity,
250
- page.digest,
251
- this.lease.epoch,
252
- page.expiresAt
253
- ]);
254
- return record;
255
- });
256
- }
257
- async acquirePage(callId, args, page) {
258
- return this.journal.fenced(this.lease, async ({ client }) => {
259
- const result = await client.query(`SELECT s.run_id AS "runId",s.call_id AS "callId",s.epoch,s.worker_id AS "workerId",s.name,s.image,s.policy_digest AS "policyDigest",s.container_id AS "containerId",s.state
260
- FROM harness_mastra.browser_pages p JOIN harness_mastra.sandboxes s ON s.run_id=p.run_id AND s.call_id=p.sandbox_call
261
- JOIN harness_mastra.actions a ON a.run_id=p.run_id AND a.call_id=$3
262
- WHERE p.run_id=$1 AND p.page_id=$2 AND NOT p.closed AND p.owner_call IS NULL AND p.epoch=$4 AND p.child_id IS NOT DISTINCT FROM $5 AND p.identity_id=$6 AND p.binding_digest=$7 AND clock_timestamp()<p.expires_at
263
- AND s.state='running' AND a.tool='web_browse' AND a.state='dispatched' AND a.args_digest=$8 AND a.child_id IS NOT DISTINCT FROM $5 FOR UPDATE OF p`, [
264
- this.lease.runId,
265
- page.id,
266
- callId,
267
- this.lease.epoch,
268
- this.lease.child?.id ?? null,
269
- page.identity,
270
- page.digest,
271
- digest(args)
272
- ]);
273
- if (page.operation === "open" || result.rowCount !== 1)
274
- throw new HarnessError("browser_page_lost", "The page is absent, busy, expired, closed, or belongs to another identity, child, grant or worker epoch. Open a new page; previous actions are never replayed.");
275
- await client.query("UPDATE harness_mastra.browser_pages SET owner_call=$3 WHERE run_id=$1 AND page_id=$2", [this.lease.runId, page.id, callId]);
276
- return result.rows[0];
277
- });
278
- }
279
- async suspendPages() {
280
- await this.journal.fenced(this.lease, async ({ client }) => {
281
- await client.query("UPDATE harness_mastra.browser_pages SET suspended_owner=$3 WHERE run_id=$1 AND epoch=$2 AND NOT closed AND owner_call IS NULL AND EXISTS (SELECT 1 FROM harness_mastra.approvals approval JOIN harness_mastra.actions action ON action.run_id=approval.run_id AND action.call_id=approval.call_id WHERE approval.run_id=$1 AND action.state='prepared')", [this.lease.runId, this.lease.epoch, this.lease.owner]);
282
- }, "settlement");
283
- }
284
- async resumePages(previous) {
285
- if (previous.runId !== this.lease.runId || previous.epoch + 1 !== this.lease.epoch)
286
- throw new HarnessError("browser_page_lost", "Only the next owner can resume an approval suspension.");
287
- await this.journal.fenced(this.lease, async ({ client }) => {
288
- await client.query("UPDATE harness_mastra.browser_pages SET epoch=$4,suspended_owner=NULL WHERE run_id=$1 AND epoch=$2 AND suspended_owner=$3 AND NOT closed AND owner_call IS NULL AND clock_timestamp()<expires_at", [this.lease.runId, previous.epoch, previous.owner, this.lease.epoch]);
289
- }, "settlement");
290
- }
291
- async releasePage(record, callId) {
292
- await this.journal.fenced(this.lease, async ({ client }) => {
293
- await this.assertState(record, "running", client);
294
- const result = await client.query("UPDATE harness_mastra.browser_pages SET owner_call=NULL WHERE run_id=$1 AND sandbox_call=$2 AND owner_call=$3 AND epoch=$4 AND NOT closed", [this.lease.runId, record.callId, callId, this.lease.epoch]);
295
- if (result.rowCount !== 1)
296
- throw new HarnessError("browser_page_lost", "A different action owns this page.");
297
- });
298
- }
299
- async pages() {
300
- const retained = await this.journal.fenced(this.lease, async ({ client }) => {
301
- const result = await client.query("SELECT sandbox_call FROM harness_mastra.browser_pages WHERE run_id=$1 AND NOT closed AND ($2::uuid IS NULL OR child_id=$2)", [this.lease.runId, this.lease.child?.id ?? null]);
302
- return new Set(result.rows.map((row) => row.sandbox_call));
303
- }, "settlement");
304
- return (await this.pending()).filter((record) => retained.has(record.callId));
305
- }
306
- async provision(record, operation) {
307
- await this.journal.fenced(this.lease, async ({ client }) => {
308
- await this.assertState(record, "reserved", client);
309
- const containerId = await operation();
310
- await this.transition(record, "reserved", "created", containerId, client);
311
- });
312
- }
313
- async start(record, operation) {
314
- await this.journal.fenced(this.lease, async ({ client }) => {
315
- await this.assertState(record, "created", client);
316
- await operation();
317
- await this.transition(record, "created", "running", record.containerId, client);
318
- });
319
- }
320
- async transition(record, from, to, containerId, client) {
321
- const result = await client.query("UPDATE harness_mastra.sandboxes SET state=$5,container_id=$6 WHERE run_id=$1 AND call_id=$2 AND epoch=$3 AND name=$4 AND state=$7", [
322
- this.lease.runId,
323
- record.callId,
324
- this.lease.epoch,
325
- record.name,
326
- to,
327
- containerId,
328
- from
329
- ]);
330
- if (result.rowCount !== 1)
331
- throw new HarnessError("sandbox_denied", "Sandbox ownership or lifecycle no longer permits this operation.");
332
- record.containerId = containerId;
333
- record.state = to;
334
- }
335
- async assertTaskRunning(record) {
336
- await this.journal.fenced(this.lease, async ({ client }) => {
337
- await this.assertState(record, "running", client);
338
- });
339
- }
340
- async assertState(record, state, client) {
341
- const result = await client.query("SELECT 1 FROM harness_mastra.sandboxes s WHERE run_id=$1 AND call_id=$2 AND epoch=$3 AND name=$4 AND state=$5 AND (epoch=$6 OR (state='running' AND EXISTS (SELECT 1 FROM harness_mastra.browser_pages p WHERE p.run_id=s.run_id AND p.sandbox_call=s.call_id AND p.epoch=$6 AND NOT p.closed AND p.owner_call IS NOT NULL)))", [
342
- this.lease.runId,
343
- record.callId,
344
- record.epoch,
345
- record.name,
346
- state,
347
- this.lease.epoch
348
- ]);
349
- if (record.runId !== this.lease.runId || result.rowCount !== 1)
350
- throw new HarnessError("sandbox_denied", "Sandbox ownership or lifecycle no longer permits this operation.");
351
- }
352
- async removed(record) {
353
- await this.journal.fenced(this.lease, async ({ client }) => {
354
- const result = await client.query("UPDATE harness_mastra.sandboxes SET state='removed',removed_at=clock_timestamp() WHERE run_id=$1 AND call_id=$2 AND name=$3 AND worker_id=$4", [this.lease.runId, record.callId, record.name, record.workerId]);
355
- if (record.runId !== this.lease.runId || !result.rowCount)
356
- throw new HarnessError("sandbox_denied", "Cleanup receipt does not belong to this run.");
357
- await client.query("UPDATE harness_mastra.browser_pages SET closed=true,owner_call=NULL WHERE run_id=$1 AND sandbox_call=$2", [this.lease.runId, record.callId]);
358
- record.state = "removed";
359
- }, "settlement");
360
- }
361
- async pending() {
362
- return this.journal.fenced(this.lease, async ({ client }) => {
363
- const result = await client.query(`SELECT run_id AS "runId",call_id AS "callId",epoch,worker_id AS "workerId",name,image,policy_digest AS "policyDigest",container_id AS "containerId",state FROM harness_mastra.sandboxes WHERE run_id=$1 AND state!='removed' ORDER BY name`, [this.lease.runId]);
364
- return result.rows;
365
- }, "settlement");
366
- }
367
- async markCleanupAttempt() {
368
- await this.journal.fenced(this.lease, async ({ client }) => {
369
- await client.query("UPDATE harness_mastra.sandboxes SET cleanup_attempted_at=clock_timestamp() WHERE run_id=$1 AND state!='removed'", [this.lease.runId]);
370
- }, "settlement");
371
- }
372
- }
373
-
374
- // apps/harness/src/sandbox/reaper.ts
375
- async function reapSandboxes(config, engine, journal, signal, runId, journalForRun) {
376
- const info = dockerJson(await engine.call("GET", "/info"));
377
- if (typeof info?.ID !== "string" || !info.ID)
378
- throw new HarnessError("sandbox_unavailable", "The original engine identity is required.");
379
- const candidates = runId ? [runId] : await journal.orphanedRuns(info.ID);
380
- const outcomes = [];
381
- for (const runId of candidates) {
382
- if (signal.aborted)
383
- break;
384
- let lease;
385
- let selected = journal;
386
- try {
387
- selected = journalForRun ? await journalForRun(runId) : journal;
388
- lease = await selected.acquire(runId, 30000);
389
- const lifecycle = new SandboxJournal(selected, lease);
390
- await lifecycle.markCleanupAttempt();
391
- const worker = new SandboxWorker(config, engine, lifecycle);
392
- const removed = await worker.reap(info.ID);
393
- outcomes.push({ runId, status: "removed", removed });
394
- } catch (error) {
395
- const code = error instanceof HarnessError ? error.code : "internal_failure";
396
- outcomes.push({
397
- runId,
398
- status: code === "run_busy" ? "busy" : "blocked",
399
- removed: 0,
400
- code
401
- });
402
- } finally {
403
- if (lease)
404
- await selected.release(lease).catch(() => {
405
- return;
406
- });
407
- if (selected !== journal)
408
- await selected.close();
409
- }
410
- }
411
- return {
412
- workerId: info.ID,
413
- scanned: candidates.length,
414
- outcomes,
415
- interrupted: signal.aborted,
416
- actionReplayed: false,
417
- actionReconciled: false,
418
- productionApproved: false
419
- };
420
- }
421
-
422
- export { settledFailure, ToolExecutor, SandboxProbeJournal, SandboxJournal, reapSandboxes };
@@ -1,180 +0,0 @@
1
- import {
2
- string,
3
- number,
4
- boolean,
5
- _null,
6
- unknown,
7
- object,
8
- union,
9
- record,
10
- _enum
11
- } from "./chunk-1sygmp11.mjs";
12
-
13
- // node_modules/.bun/@mastra+core@1.71.0+95d98e20cbc6e6e1/node_modules/@mastra/core/dist/define-vaqWwloq.js
14
- var AGENT_SCHEDULE_PREFIX = "agent_";
15
- var WORKFLOW_SCHEDULE_PREFIX = "schedule_";
16
- var SCHEDULE_SIGNAL_TYPES = [
17
- "user",
18
- "state",
19
- "reactive",
20
- "notification",
21
- "user-message",
22
- "system-reminder"
23
- ];
24
- var ScheduleAttributesSchema = record(string(), union([
25
- string(),
26
- number(),
27
- boolean(),
28
- _null()
29
- ]));
30
- var ScheduleStreamOptionsSchema = object({ requestContext: record(string(), unknown()).optional() });
31
- var ScheduleIfActiveSchema = object({
32
- behavior: _enum([
33
- "deliver",
34
- "persist",
35
- "discard"
36
- ]).optional(),
37
- attributes: ScheduleAttributesSchema.optional()
38
- });
39
- var ScheduleIfIdleSchema = object({
40
- behavior: _enum([
41
- "wake",
42
- "persist",
43
- "discard"
44
- ]).optional(),
45
- attributes: ScheduleAttributesSchema.optional(),
46
- streamOptions: ScheduleStreamOptionsSchema.optional()
47
- });
48
- var ScheduleInputSchema = object({
49
- scheduleId: string(),
50
- agentId: string(),
51
- prompt: string(),
52
- threadId: string().optional(),
53
- resourceId: string().optional(),
54
- signalType: _enum(SCHEDULE_SIGNAL_TYPES).optional(),
55
- tagName: string().optional(),
56
- attributes: ScheduleAttributesSchema.optional(),
57
- providerOptions: record(string(), unknown()).optional(),
58
- ifActive: ScheduleIfActiveSchema.optional(),
59
- ifIdle: ScheduleIfIdleSchema.optional()
60
- });
61
- var ScheduleOutputSchema = object({
62
- status: _enum([
63
- "fired",
64
- "signal-accepted",
65
- "skipped-thread-blocked",
66
- "thread-missing",
67
- "agent-missing",
68
- "invalid-input"
69
- ]),
70
- reason: string().optional()
71
- });
72
- var FS_AGENT_SCHEDULE_PREFIX = "fsa_";
73
- function encodeRowIdPart(value) {
74
- return encodeURIComponent(value).replace(/_/g, "%5F");
75
- }
76
- function fsAgentScheduleRowId(agentId, key) {
77
- return `${FS_AGENT_SCHEDULE_PREFIX}${encodeRowIdPart(agentId)}__${encodeRowIdPart(key)}`;
78
- }
79
- function parseFsAgentScheduleRowId(rowId) {
80
- if (!rowId.startsWith("fsa_"))
81
- return;
82
- const rest = rowId.slice(4);
83
- const separator = rest.indexOf("__");
84
- if (separator <= 0)
85
- return;
86
- try {
87
- return {
88
- agentId: decodeURIComponent(rest.slice(0, separator)),
89
- key: decodeURIComponent(rest.slice(separator + 2))
90
- };
91
- } catch {
92
- return;
93
- }
94
- }
95
-
96
- // node_modules/.bun/@mastra+core@1.71.0+95d98e20cbc6e6e1/node_modules/@mastra/core/dist/pull-transport-D6pSbsAj.js
97
- var MastraWorker = class {
98
- mastra;
99
- deps;
100
- __registerMastra(mastra) {
101
- this.mastra = mastra;
102
- }
103
- async init(deps) {
104
- this.deps = deps;
105
- if (!this.mastra && deps.mastra)
106
- this.mastra = deps.mastra;
107
- }
108
- };
109
- var MAX_DRAIN_TIMEOUT_MS = 2147483647;
110
- function assertDrainTimeout(value, label) {
111
- if (!Number.isFinite(value) || value < 0 || value > 2147483647)
112
- throw new RangeError(`${label} drainTimeout must be a finite number of milliseconds between 0 and ${MAX_DRAIN_TIMEOUT_MS}`);
113
- return value;
114
- }
115
- var TOPIC_WORKFLOWS = "workflows";
116
- var DEFAULT_DRAIN_TIMEOUT_MS = 5000;
117
- var PullTransport = class {
118
- #pubsub;
119
- #group;
120
- #topic;
121
- #logger;
122
- #drainTimeout;
123
- #callbacks = [];
124
- #inFlight = /* @__PURE__ */ new Set;
125
- constructor({ pubsub, group, topic, logger, drainTimeout }) {
126
- this.#pubsub = pubsub;
127
- this.#group = group;
128
- this.#topic = topic ?? TOPIC_WORKFLOWS;
129
- this.#logger = logger;
130
- this.#drainTimeout = assertDrainTimeout(drainTimeout ?? DEFAULT_DRAIN_TIMEOUT_MS, "PullTransport");
131
- }
132
- async start(router) {
133
- if (this.#callbacks.length > 0) {
134
- this.#logger?.debug("[PullTransport] start() called while already subscribed; ignoring duplicate call");
135
- return;
136
- }
137
- const cb = (event, ack, nack) => {
138
- const inFlight = router.route(event, ack, nack).catch((err) => {
139
- try {
140
- if (typeof nack === "function")
141
- nack();
142
- } finally {
143
- this.#logger?.error("[PullTransport] router.route rejected", { err });
144
- }
145
- });
146
- this.#inFlight.add(inFlight);
147
- inFlight.finally(() => this.#inFlight.delete(inFlight));
148
- };
149
- await this.#pubsub.subscribe(this.#topic, cb, { group: this.#group });
150
- this.#callbacks.push({
151
- topic: this.#topic,
152
- cb
153
- });
154
- }
155
- async stop(options) {
156
- const drainTimeout = assertDrainTimeout(options?.drainTimeout ?? this.#drainTimeout, "PullTransport.stop()");
157
- for (const { topic, cb } of this.#callbacks)
158
- await this.#pubsub.unsubscribe(topic, cb);
159
- this.#callbacks = [];
160
- await this.#drainInFlight(drainTimeout);
161
- await this.#pubsub.flush();
162
- }
163
- async#drainInFlight(drainTimeout) {
164
- if (this.#inFlight.size === 0)
165
- return;
166
- const pending = this.#inFlight.size;
167
- let timeoutHandle;
168
- try {
169
- if (await Promise.race([Promise.allSettled([...this.#inFlight]).then(() => false), new Promise((resolve) => {
170
- timeoutHandle = setTimeout(() => resolve(true), drainTimeout);
171
- })]))
172
- this.#logger?.warn(`[PullTransport] stop() timed out after ${drainTimeout}ms waiting for ${pending} in-flight event(s)`);
173
- } finally {
174
- if (timeoutHandle)
175
- clearTimeout(timeoutHandle);
176
- }
177
- }
178
- };
179
-
180
- export { AGENT_SCHEDULE_PREFIX, WORKFLOW_SCHEDULE_PREFIX, fsAgentScheduleRowId, parseFsAgentScheduleRowId, MastraWorker, assertDrainTimeout, PullTransport };