@open-qa/qa-stage 0.0.0-stage → 0.1.0-alpha.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 (113) hide show
  1. package/LICENSE +204 -0
  2. package/NOTICE +7 -0
  3. package/THIRD_PARTY.md +13 -0
  4. package/THIRD_PARTY_NOTICES.md +11 -0
  5. package/package.json +68 -4
  6. package/scripts/bundle.d.ts +7 -0
  7. package/scripts/bundle.js +78 -0
  8. package/src/auth.d.ts +10 -0
  9. package/src/auth.js +26 -0
  10. package/src/blackboard-tools.d.ts +2 -0
  11. package/src/blackboard-tools.js +46 -0
  12. package/src/config.d.ts +61 -0
  13. package/src/config.js +64 -0
  14. package/src/discord-api.d.ts +47 -0
  15. package/src/discord-api.js +151 -0
  16. package/src/discord-surface.d.ts +4 -0
  17. package/src/discord-surface.js +218 -0
  18. package/src/drivers.d.ts +21 -0
  19. package/src/drivers.js +12 -0
  20. package/src/email-message.d.ts +22 -0
  21. package/src/email-message.js +114 -0
  22. package/src/email-surface.d.ts +4 -0
  23. package/src/email-surface.js +140 -0
  24. package/src/event-log.d.ts +18 -0
  25. package/src/event-log.js +46 -0
  26. package/src/expect-engine.d.ts +15 -0
  27. package/src/expect-engine.js +114 -0
  28. package/src/expect-evidence.d.ts +7 -0
  29. package/src/expect-evidence.js +68 -0
  30. package/src/flow-tools.d.ts +2 -0
  31. package/src/flow-tools.js +26 -0
  32. package/src/http-expect.d.ts +4 -0
  33. package/src/http-expect.js +68 -0
  34. package/src/index.d.ts +13 -0
  35. package/src/index.js +37 -0
  36. package/src/main.d.ts +1 -0
  37. package/src/main.js +51 -0
  38. package/src/mcp.d.ts +14 -0
  39. package/src/mcp.js +23 -0
  40. package/src/observation-tools.d.ts +3 -0
  41. package/src/observation-tools.js +39 -0
  42. package/src/page-diagnostics.d.ts +19 -0
  43. package/src/page-diagnostics.js +53 -0
  44. package/src/page-pixels.d.ts +35 -0
  45. package/src/page-pixels.js +73 -0
  46. package/src/page-policy.d.ts +48 -0
  47. package/src/page-policy.js +125 -0
  48. package/src/page-recording.d.ts +39 -0
  49. package/src/page-recording.js +532 -0
  50. package/src/page-replay.d.ts +7 -0
  51. package/src/page-replay.js +69 -0
  52. package/src/page-views.d.ts +85 -0
  53. package/src/page-views.js +338 -0
  54. package/src/rendered.d.ts +6 -0
  55. package/src/rendered.js +135 -0
  56. package/src/replay-artifacts.d.ts +2 -0
  57. package/src/replay-artifacts.js +100 -0
  58. package/src/replay-assets.d.ts +21 -0
  59. package/src/replay-assets.js +106 -0
  60. package/src/replay-budget.d.ts +22 -0
  61. package/src/replay-budget.js +47 -0
  62. package/src/replay-files.d.ts +3 -0
  63. package/src/replay-files.js +18 -0
  64. package/src/replay-privacy.d.ts +10 -0
  65. package/src/replay-privacy.js +48 -0
  66. package/src/replay-script.d.ts +2 -0
  67. package/src/replay-script.js +65 -0
  68. package/src/replay-warnings.d.ts +6 -0
  69. package/src/replay-warnings.js +16 -0
  70. package/src/replay-writer.d.ts +24 -0
  71. package/src/replay-writer.js +92 -0
  72. package/src/screen-tools.d.ts +5 -0
  73. package/src/screen-tools.js +168 -0
  74. package/src/server.d.ts +50 -0
  75. package/src/server.js +537 -0
  76. package/src/signed-artifacts.d.ts +21 -0
  77. package/src/signed-artifacts.js +127 -0
  78. package/src/sqlite-parser.d.ts +3 -0
  79. package/src/stage-clock.d.ts +2 -0
  80. package/src/stage-clock.js +7 -0
  81. package/src/surface-adapter.d.ts +65 -0
  82. package/src/surface-adapter.js +0 -0
  83. package/src/system-common.d.ts +34 -0
  84. package/src/system-common.js +123 -0
  85. package/src/system-db.d.ts +9 -0
  86. package/src/system-db.js +143 -0
  87. package/src/system-github.d.ts +6 -0
  88. package/src/system-github.js +73 -0
  89. package/src/system-http.d.ts +4 -0
  90. package/src/system-http.js +86 -0
  91. package/src/system-logs.d.ts +6 -0
  92. package/src/system-logs.js +78 -0
  93. package/src/telegram-api.d.ts +162 -0
  94. package/src/telegram-api.js +170 -0
  95. package/src/telegram-markup.d.ts +4 -0
  96. package/src/telegram-markup.js +129 -0
  97. package/src/telegram-surface.d.ts +39 -0
  98. package/src/telegram-surface.js +448 -0
  99. package/src/tool-gateway.d.ts +41 -0
  100. package/src/tool-gateway.js +696 -0
  101. package/src/tool-limits.d.ts +12 -0
  102. package/src/tool-limits.js +41 -0
  103. package/src/tool-secrets.d.ts +8 -0
  104. package/src/tool-secrets.js +38 -0
  105. package/src/vendor/gmail.d.ts +45 -0
  106. package/src/vendor/gmail.js +193 -0
  107. package/src/watch.d.ts +11 -0
  108. package/src/watch.js +30 -0
  109. package/src/web-expect.d.ts +5 -0
  110. package/src/web-expect.js +130 -0
  111. package/src/web-tools.d.ts +15 -0
  112. package/src/web-tools.js +340 -0
  113. package/README.md +0 -3
@@ -0,0 +1,696 @@
1
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
2
+ import { z } from "zod";
3
+ import sharp from "sharp";
4
+ import { cacheContainsPrivateData } from "@open-qa/qa-engine";
5
+ import {
6
+ actionTargetSchema,
7
+ blackboardToolNames,
8
+ flowToolNames,
9
+ observationToolNames,
10
+ idSchema,
11
+ jsonObjectSchema,
12
+ toolResultSchema,
13
+ replaySecretsAllowed,
14
+ hasReplaySecretReference,
15
+ MAX_ASSESSMENT_IMAGE_BYTES
16
+ } from "@open-qa/qa-engine/protocol";
17
+ import { StageError } from "./drivers.js";
18
+ import { blackboardTools } from "./blackboard-tools.js";
19
+ import { flowTools } from "./flow-tools.js";
20
+ import { observationTools } from "./observation-tools.js";
21
+ import { createToolSecrets } from "./tool-secrets.js";
22
+ import {
23
+ fitsJson,
24
+ MAX_TOOL_NAME_CHARS,
25
+ MAX_TOOL_IMAGE_CHARS,
26
+ MAX_VIEW_QUEUE_DEPTH
27
+ } from "./tool-limits.js";
28
+ const builtinTools = /* @__PURE__ */ new Set([
29
+ ...observationToolNames,
30
+ ...flowToolNames,
31
+ ...blackboardToolNames
32
+ ]);
33
+ const builtinStepTools = /* @__PURE__ */ new Set([...flowToolNames, ...blackboardToolNames]);
34
+ function boundedArgs(raw) {
35
+ if (!fitsJson(raw)) return void 0;
36
+ try {
37
+ const parsed = jsonObjectSchema.safeParse(raw);
38
+ return parsed.success ? parsed.data : void 0;
39
+ } catch {
40
+ return void 0;
41
+ }
42
+ }
43
+ class ToolFailure extends Error {
44
+ constructor(code, message) {
45
+ super(message);
46
+ this.code = code;
47
+ }
48
+ code;
49
+ }
50
+ const imageSchema = z.strictObject({
51
+ data: z.string().max(MAX_TOOL_IMAGE_CHARS),
52
+ mimeType: z.enum(["image/png", "image/jpeg", "image/webp"])
53
+ });
54
+ const outputSchema = z.strictObject({
55
+ data: jsonObjectSchema.refine((value) => fitsJson(value), "Tool data is too large"),
56
+ evidence: jsonObjectSchema.refine((value) => fitsJson(value, 1024 * 1024), "Tool evidence is too large").optional(),
57
+ image: imageSchema.optional(),
58
+ target: actionTargetSchema.optional(),
59
+ error: z.strictObject({ code: idSchema, message: z.string() }).optional()
60
+ });
61
+ const observationSchema = z.object({
62
+ shot: idSchema.max(1024),
63
+ thumbnail: z.instanceof(Uint8Array),
64
+ fingerprint: z.string(),
65
+ pixels: z.instanceof(Uint8Array).optional()
66
+ });
67
+ function boundedEvidenceText(text) {
68
+ if (text.length <= 16e3) return text;
69
+ const marker = "\n[...truncated...]\n";
70
+ const head = Math.floor((16e3 - marker.length) / 2);
71
+ return text.slice(0, head) + marker + text.slice(-(16e3 - marker.length - head));
72
+ }
73
+ class ToolGateway {
74
+ constructor(options) {
75
+ this.options = options;
76
+ this.masking = createToolSecrets(options.secrets ?? {}, options.tokens ?? [], options.redactor);
77
+ this.surfaces = options.surfaces ?? [];
78
+ for (const command of [
79
+ ...observationTools(
80
+ (actor) => this.listViews(actor),
81
+ (view, actor) => this.viewDriver(view, actor)
82
+ ),
83
+ ...flowTools(),
84
+ ...blackboardTools()
85
+ ])
86
+ this.register(command);
87
+ this.register({
88
+ name: "arm",
89
+ description: "Save the final tool call for the current together step without executing it. Stop after arming; the conductor fires every participant together.",
90
+ scope: "actor",
91
+ inputSchema: z.strictObject({
92
+ tool: idSchema.describe(
93
+ "The bare command name, such as web_click, without any mcp__ prefix"
94
+ ),
95
+ args: jsonObjectSchema
96
+ }),
97
+ execute: async (args, context) => {
98
+ const current = this.steps.get(context.actor);
99
+ if (!current?.barrier || !current.step)
100
+ throw new ToolFailure("no_barrier", "No active together step");
101
+ if (this.armed.has(context.actor))
102
+ throw new ToolFailure("already_armed", "Actor has already armed this step");
103
+ const tool = args.tool;
104
+ const bare = /^mcp__qa(?:__|\.)(.+)$/.exec(tool)?.[1];
105
+ if (bare !== void 0 && this.commands.has(bare) && !builtinTools.has(bare) && this.allowed(context.actor, bare))
106
+ throw new ToolFailure(
107
+ "invalid_command",
108
+ `Arm takes the bare command name: use "${bare}"`
109
+ );
110
+ if (builtinTools.has(tool))
111
+ throw new ToolFailure("invalid_command", "Only surface commands may be armed");
112
+ const prepared = this.prepare(
113
+ {
114
+ actor: context.actor,
115
+ emit: context.emit,
116
+ signal: context.signal,
117
+ replay: context.replay
118
+ },
119
+ tool,
120
+ args.args
121
+ );
122
+ const target = await prepared.command.captureTarget?.(
123
+ prepared.parsed.data,
124
+ prepared.context
125
+ );
126
+ this.armed.set(context.actor, {
127
+ barrier: current.barrier,
128
+ step: current.step,
129
+ tool,
130
+ args: structuredClone(args.args),
131
+ replay: context.replay,
132
+ consumed: false
133
+ });
134
+ context.emit({ kind: "armed", barrier: current.barrier, step: current.step, tool });
135
+ return { data: { status: "armed", barrier: current.barrier }, ...target && { target } };
136
+ }
137
+ });
138
+ for (const surface of this.surfaces)
139
+ for (const command of surface.tools) this.register(command);
140
+ }
141
+ options;
142
+ // Conductor-only observations use the same ownership and per-view queue, without
143
+ // actor permissions/level restrictions or actor action accounting.
144
+ async captureEvidence(request, context) {
145
+ if (this.steps.get(request.actor)?.step !== request.step)
146
+ throw new StageError(409, "step_mismatch", "Evidence requires the actor's active step");
147
+ const views = [];
148
+ const screenshots = [];
149
+ for (const entry of this.listViews(request.actor)) {
150
+ const view = String(entry.view);
151
+ if ((this.queues.get(view)?.depth ?? 0) >= MAX_VIEW_QUEUE_DEPTH)
152
+ throw new StageError(429, "queue_full", "Evidence queue is full");
153
+ views.push(
154
+ await this.enqueue([view], async () => {
155
+ context.signal.throwIfAborted();
156
+ if (this.steps.get(request.actor)?.step !== request.step)
157
+ throw new StageError(409, "step_mismatch", "Evidence requires the actor's active step");
158
+ const driver = this.viewDriver(view, request.actor);
159
+ const toolContext = {
160
+ actor: request.actor,
161
+ step: request.step,
162
+ view,
163
+ signal: context.signal
164
+ };
165
+ try {
166
+ const rawText = await driver.text(view, toolContext);
167
+ const rawSnapshot = await driver.snapshot(view, toolContext);
168
+ const observation = observationSchema.parse(await driver.observe(view, toolContext));
169
+ if (request.screenshots) {
170
+ const shot = this.masking.redactText(observation.shot);
171
+ const entry2 = { view, shot, phase: request.phase ?? "after" };
172
+ try {
173
+ if (!observation.pixels) throw new Error("No pixels");
174
+ const { data, info } = await sharp(observation.pixels, {
175
+ limitInputPixels: 4e7
176
+ }).rotate().resize(1280, 1280, { fit: "inside", withoutEnlargement: true }).flatten({ background: "white" }).jpeg({ quality: 70 }).toBuffer({ resolveWithObject: true });
177
+ if (data.length > MAX_ASSESSMENT_IMAGE_BYTES)
178
+ screenshots.push({ ...entry2, omitted: "compressed image exceeds 128 KiB" });
179
+ else
180
+ screenshots.push({
181
+ ...entry2,
182
+ image: {
183
+ data: data.toString("base64"),
184
+ mimeType: "image/jpeg",
185
+ width: info.width,
186
+ height: info.height
187
+ }
188
+ });
189
+ } catch {
190
+ screenshots.push({
191
+ ...entry2,
192
+ omitted: "image unavailable or could not be decoded"
193
+ });
194
+ }
195
+ }
196
+ return {
197
+ view,
198
+ text: boundedEvidenceText(this.masking.redactText(rawText)),
199
+ snapshot: boundedEvidenceText(this.masking.redactText(rawSnapshot)),
200
+ shot: this.masking.redactText(observation.shot),
201
+ truncated: rawText.length > 16e3 || rawSnapshot.length > 16e3,
202
+ unavailable: false
203
+ };
204
+ } catch {
205
+ if (request.screenshots)
206
+ screenshots.push({
207
+ view,
208
+ phase: request.phase ?? "after",
209
+ omitted: "view observation unavailable"
210
+ });
211
+ return { view, truncated: false, unavailable: true };
212
+ }
213
+ })
214
+ );
215
+ }
216
+ return { views, ...request.screenshots && { screenshots } };
217
+ }
218
+ steps = /* @__PURE__ */ new Map();
219
+ setStep(request) {
220
+ const previous = this.steps.get(request.actor);
221
+ if (previous?.step !== request.step || previous?.barrier !== request.barrier)
222
+ this.armed.delete(request.actor);
223
+ this.steps.set(request.actor, { ...request });
224
+ return { ...request };
225
+ }
226
+ armed = /* @__PURE__ */ new Map();
227
+ commands = /* @__PURE__ */ new Map();
228
+ queues = /* @__PURE__ */ new Map();
229
+ masking;
230
+ surfaces;
231
+ register(command) {
232
+ if (command.name.length > MAX_TOOL_NAME_CHARS || command.name !== "arm" && !/^[a-zA-Z0-9-]+_[a-zA-Z0-9_-]+$/.test(command.name) || this.commands.has(command.name))
233
+ throw new Error("Invalid or duplicate tool name");
234
+ this.commands.set(command.name, {
235
+ ...command,
236
+ // Dispatch has already parsed the resolved input, including any transforms.
237
+ execute: (args, context) => command.execute(args, context),
238
+ ...command.captureTarget && {
239
+ captureTarget: (args, context) => command.captureTarget(args, context)
240
+ }
241
+ });
242
+ }
243
+ registerTools = (server, session) => {
244
+ server.server.registerCapabilities({ tools: {} });
245
+ server.server.setRequestHandler(ListToolsRequestSchema, async () => ({
246
+ tools: [...this.commands.values()].filter((command) => this.allowed(session.actor, command.name)).map((command) => ({
247
+ name: command.name,
248
+ description: command.description,
249
+ inputSchema: z.toJSONSchema(command.inputSchema, { target: "draft-7", io: "input" })
250
+ }))
251
+ }));
252
+ server.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
253
+ const result = await this.call(
254
+ { ...session, signal: extra.signal },
255
+ request.params.name,
256
+ request.params.arguments ?? {}
257
+ );
258
+ const { image, ...summary } = result;
259
+ return {
260
+ isError: !result.ok,
261
+ content: [
262
+ { type: "text", text: JSON.stringify(summary) },
263
+ ...image ? [{ type: "image", ...image }] : []
264
+ ]
265
+ };
266
+ });
267
+ };
268
+ async call(session, name, raw) {
269
+ const started = this.options.clock.now();
270
+ const args = boundedArgs(raw);
271
+ const command = this.commands.get(name);
272
+ if (name === "arm" && args && typeof args.tool === "string" && args.args && typeof args.args === "object" && !Array.isArray(args.args)) {
273
+ const view = idSchema.safeParse(args.args.view);
274
+ if (view.success) {
275
+ try {
276
+ this.viewDriver(view.data, session.actor);
277
+ } catch {
278
+ return this.dispatch(session, name, args, started);
279
+ }
280
+ if ((this.queues.get(view.data)?.depth ?? 0) >= MAX_VIEW_QUEUE_DEPTH)
281
+ return this.dispatch(
282
+ session,
283
+ name,
284
+ args,
285
+ started,
286
+ new ToolFailure("queue_full", "View queue is full")
287
+ );
288
+ return this.enqueue([view.data], () => this.dispatch(session, name, args, started));
289
+ }
290
+ }
291
+ if (args && name.length <= MAX_TOOL_NAME_CHARS && command?.scope === "view" && this.allowed(session.actor, name)) {
292
+ const view = idSchema.safeParse(args.view);
293
+ if (view.success) {
294
+ try {
295
+ this.viewDriver(view.data, session.actor);
296
+ for (const key of command.viewArgs ?? [])
297
+ this.viewDriver(idSchema.parse(args[key]), session.actor);
298
+ } catch {
299
+ return this.dispatch(session, name, args, started);
300
+ }
301
+ const views = [
302
+ .../* @__PURE__ */ new Set([
303
+ view.data,
304
+ ...(command.viewArgs ?? []).map((key) => idSchema.parse(args[key]))
305
+ ])
306
+ ];
307
+ if (views.some((id) => (this.queues.get(id)?.depth ?? 0) >= MAX_VIEW_QUEUE_DEPTH))
308
+ return this.dispatch(
309
+ session,
310
+ name,
311
+ args,
312
+ started,
313
+ new ToolFailure("queue_full", "View queue is full")
314
+ );
315
+ return this.enqueue(views, () => this.dispatch(session, name, args, started));
316
+ }
317
+ }
318
+ return this.dispatch(session, name, args, started);
319
+ }
320
+ async dispatch(session, name, args, started, failure, firing) {
321
+ const maskedArgs = args ? this.masking.redact(args) : {};
322
+ const auditArgs = fitsJson(maskedArgs) ? maskedArgs : {};
323
+ let context = {
324
+ actor: session.actor,
325
+ signal: session.signal,
326
+ emit: session.emit,
327
+ replay: session.replay
328
+ };
329
+ let before;
330
+ let after;
331
+ let output;
332
+ let result;
333
+ try {
334
+ if (!args || name.length > MAX_TOOL_NAME_CHARS)
335
+ throw new ToolFailure("invalid_input", "Tool arguments or name exceed the allowed limits");
336
+ if (failure) throw failure;
337
+ session.signal?.throwIfAborted();
338
+ const prepared = this.prepare(session, name, args);
339
+ const { command, parsed, driver } = prepared;
340
+ context = prepared.context;
341
+ if (!firing && !builtinTools.has(name) && this.armed.has(session.actor))
342
+ throw new ToolFailure("already_armed", "The final action is already armed");
343
+ if (driver) before = observationSchema.parse(await driver.observe(context.view, context));
344
+ if (firing) {
345
+ await firing.ready();
346
+ session.signal?.throwIfAborted();
347
+ firing.started();
348
+ }
349
+ try {
350
+ const candidate = outputSchema.parse(await command.execute(parsed.data, context));
351
+ candidate.data = this.masking.redact(candidate.data);
352
+ if (candidate.evidence) {
353
+ candidate.evidence = this.masking.redact(candidate.evidence);
354
+ if (!fitsJson(candidate.evidence, 1024 * 1024))
355
+ throw new Error("Tool evidence is too large");
356
+ }
357
+ if (candidate.target?.layer === "semantic") {
358
+ for (const key of ["ref", "role", "name", "label"]) {
359
+ const value = candidate.target[key];
360
+ if (value !== void 0) candidate.target[key] = this.masking.redactText(value);
361
+ }
362
+ }
363
+ if (!fitsJson({ data: candidate.data, target: candidate.target, error: candidate.error }))
364
+ throw new Error("Tool output is too large");
365
+ output = candidate;
366
+ } finally {
367
+ if (driver) {
368
+ try {
369
+ after = observationSchema.parse(await driver.observe(context.view, context));
370
+ } catch {
371
+ if (output && !output.error)
372
+ output.data = { ...output.data, observationError: "observation_unavailable" };
373
+ }
374
+ }
375
+ }
376
+ if (output?.error) throw new ToolFailure(output.error.code, output.error.message);
377
+ result = {
378
+ ok: true,
379
+ data: output.data,
380
+ ms: this.options.clock.now() - started,
381
+ ...before && after ? { changed: this.changed(before, after) } : {},
382
+ ...after ? { shot: after.shot } : {},
383
+ ...output?.image ? { image: output.image } : {}
384
+ };
385
+ } catch (error) {
386
+ firing?.failed(error);
387
+ result = {
388
+ ...output?.image ? { image: output.image } : {},
389
+ ok: false,
390
+ error: error instanceof ToolFailure ? { code: error.code, message: error.message } : { code: "tool_failed", message: "Tool execution failed" },
391
+ ms: this.options.clock.now() - started,
392
+ ...after ? { shot: after.shot } : {}
393
+ };
394
+ }
395
+ const { image, ...summary } = result;
396
+ const redact = this.masking.redactText;
397
+ const safeResult = toolResultSchema.parse({
398
+ ...summary,
399
+ ...summary.ok ? { data: summary.data } : { error: { code: redact(summary.error.code), message: redact(summary.error.message) } },
400
+ ...summary.shot ? { shot: redact(summary.shot) } : {}
401
+ });
402
+ const target = output?.target;
403
+ const event = {
404
+ kind: "action",
405
+ tool: redact(name || "invalid_tool").slice(0, MAX_TOOL_NAME_CHARS),
406
+ args: auditArgs,
407
+ ok: safeResult.ok,
408
+ ms: safeResult.ms,
409
+ ...context.view ? { view: redact(context.view) } : {},
410
+ ...context.step ? { step: redact(context.step) } : {},
411
+ ...before ? { beforeShot: redact(before.shot) } : {},
412
+ ...safeResult.shot ? { shot: safeResult.shot } : {},
413
+ ...safeResult.ok && safeResult.changed !== void 0 ? { changed: safeResult.changed } : {},
414
+ ...!safeResult.ok ? { error: safeResult.error.message } : {},
415
+ ...target ? { target } : {},
416
+ ...output?.evidence ? { data: output.evidence } : {}
417
+ };
418
+ session.emit(event);
419
+ return { ...safeResult, ...image ? { image } : {} };
420
+ }
421
+ prepare(session, name, args) {
422
+ const command = this.commands.get(name);
423
+ if (!command || !this.allowed(session.actor, name))
424
+ throw new ToolFailure("forbidden", "Tool is not available to this actor");
425
+ let context = {
426
+ actor: session.actor,
427
+ signal: session.signal,
428
+ emit: session.emit,
429
+ replay: session.replay
430
+ };
431
+ let driver;
432
+ if (command.scope === "view") {
433
+ const view = idSchema.safeParse(args.view);
434
+ if (!view.success) throw new ToolFailure("invalid_input", "A view is required");
435
+ context = { ...context, view: view.data };
436
+ driver = this.viewDriver(view.data, session.actor);
437
+ if (driver.list().some((entry) => entry.view === view.data && entry.type === "rendered") && !builtinTools.has(name) && !command.allowRendered)
438
+ throw new ToolFailure("read_only_view", "Rendered views only support observation tools");
439
+ }
440
+ let resolved;
441
+ try {
442
+ resolved = name === "arm" ? args : this.masking.resolve(args);
443
+ } catch {
444
+ throw new ToolFailure("unknown_secret", "Unknown secret reference");
445
+ }
446
+ if (!fitsJson(resolved))
447
+ throw new ToolFailure("invalid_input", "Resolved tool arguments are too large");
448
+ const parsed = command.inputSchema.safeParse(resolved);
449
+ if (!parsed.success || !fitsJson(parsed.data) || context.view && parsed.data.view !== context.view || (command.viewArgs ?? []).some((key) => parsed.data[key] !== args[key]))
450
+ throw new ToolFailure("invalid_input", "Invalid tool arguments");
451
+ for (const key of command.viewArgs ?? []) {
452
+ const related = idSchema.safeParse(parsed.data[key]);
453
+ if (!related.success) throw new ToolFailure("invalid_input", "A related view is required");
454
+ this.viewDriver(related.data, session.actor);
455
+ }
456
+ context = {
457
+ ...context,
458
+ level: this.steps.get(session.actor)?.level,
459
+ step: this.steps.has(session.actor) ? this.steps.get(session.actor).step : this.options.currentStep?.(session.actor)
460
+ };
461
+ if (builtinStepTools.has(name) && !context.step)
462
+ throw new ToolFailure("no_active_step", "No active step for this actor");
463
+ return { command, parsed, driver, context };
464
+ }
465
+ async replay(request, context, expect) {
466
+ const current = this.steps.get(request.actor);
467
+ if (current?.step !== request.step)
468
+ return { ok: false, commandIndex: 0, reason: "Replay step is no longer active" };
469
+ if (cacheContainsPrivateData(request, this.masking.redactor) || hasReplaySecretReference(request.postconditions) || request.commands.some(
470
+ (command, index) => !replaySecretsAllowed(command) || "ref" in command.args || "targetRef" in command.args || Object.keys(command.args).some((key) => /selector|xpath|css/i.test(key)) || command.arm && (!current.barrier || index !== request.commands.length - 1) || ["web_click", "web_fill", "web_press", "web_select"].includes(command.tool) && !command.target || command.tool.startsWith("screen_") && !command.target
471
+ ))
472
+ return { ok: false, commandIndex: 0, reason: "Replay cache failed safety validation" };
473
+ const completed = [];
474
+ for (const [commandIndex, command] of request.commands.entries()) {
475
+ context.signal.throwIfAborted();
476
+ if (this.steps.get(request.actor) !== current)
477
+ return { ok: false, commandIndex, reason: "Replay step is no longer active" };
478
+ const args = { ...command.args };
479
+ if (command.target?.layer === "semantic" && ["web_click", "web_fill", "web_press", "web_select", "web_scroll", "web_wait_for"].includes(
480
+ command.tool
481
+ ) && !(command.tool === "web_wait_for" && args.text))
482
+ args.ref = "e0";
483
+ let captured;
484
+ const result = await this.call(
485
+ {
486
+ actor: request.actor,
487
+ replay: command,
488
+ signal: context.signal,
489
+ emit: (event) => {
490
+ if (event.kind === "action") captured = event.target;
491
+ return context.emit({ ...event, actor: request.actor, by: "replay" });
492
+ }
493
+ },
494
+ command.arm ? "arm" : command.tool,
495
+ command.arm ? { tool: command.tool, args } : args
496
+ );
497
+ context.signal.throwIfAborted();
498
+ if (!result.ok)
499
+ return {
500
+ ok: false,
501
+ commandIndex,
502
+ reason: result.error.message,
503
+ completed,
504
+ retrySafe: ["replay_target_changed", "replay_focus_changed"].includes(result.error.code)
505
+ };
506
+ const { cropImage: _crop, endCropImage: _endCrop, target: _oldTarget, ...saved } = command;
507
+ if (captured?.layer === "semantic") {
508
+ const { ref: _ref, ...target } = captured;
509
+ completed.push({ ...saved, target });
510
+ } else completed.push({ ...saved, ...captured && { target: captured } });
511
+ }
512
+ if (!request.commands.some((command) => command.arm)) {
513
+ for (const condition of request.postconditions) {
514
+ const result = await expect(
515
+ {
516
+ actor: request.actor,
517
+ step: request.step,
518
+ condition,
519
+ ...typeof condition.view === "string" && { view: condition.view }
520
+ },
521
+ context
522
+ );
523
+ if (!result.passed)
524
+ return {
525
+ ok: false,
526
+ commandIndex: request.commands.length,
527
+ reason: "Replay postcondition failed",
528
+ completed,
529
+ retrySafe: true
530
+ };
531
+ }
532
+ }
533
+ return { ok: true };
534
+ }
535
+ async fire(request, context) {
536
+ context.signal.throwIfAborted();
537
+ const pending = request.actors.map((actor) => ({ actor, command: this.armed.get(actor) }));
538
+ const missing = pending.filter(({ command }) => !command || command.barrier !== request.barrier || command.consumed).map(({ actor }) => actor);
539
+ if (missing.length)
540
+ throw new StageError(
541
+ 409,
542
+ "not_armed",
543
+ `Together ${request.barrier} missing armed actors: ${missing.join(", ")}`
544
+ );
545
+ const participants = [...this.steps].filter(([, step]) => step.barrier === request.barrier).map(([actor]) => actor);
546
+ if (participants.length !== request.actors.length || participants.some((actor) => !request.actors.includes(actor)))
547
+ throw new StageError(409, "participants", "Fire must include every together participant");
548
+ const commands = pending.map(({ actor, command }) => {
549
+ const session = {
550
+ actor,
551
+ replay: command.replay,
552
+ signal: context.signal,
553
+ emit: (event) => context.emit({ ...event, actor, by: command.replay ? "replay" : "conductor" })
554
+ };
555
+ const saved = command;
556
+ const current = this.steps.get(actor);
557
+ if (current?.step !== saved.step || current.barrier !== saved.barrier)
558
+ throw new StageError(409, "stale_arm", "Armed step is no longer active");
559
+ try {
560
+ this.prepare(session, saved.tool, saved.args);
561
+ } catch {
562
+ throw new StageError(409, "invalid_arm", "Armed command is no longer available");
563
+ }
564
+ return { actor, saved, session };
565
+ });
566
+ for (const { saved } of commands) saved.consumed = true;
567
+ const views = commands.flatMap(({ saved, session }) => {
568
+ const { command, context: context2 } = this.prepare(session, saved.tool, saved.args);
569
+ return context2.view ? [context2.view, ...(command.viewArgs ?? []).map((key) => saved.args[key])] : [];
570
+ });
571
+ if (views.some((view) => (this.queues.get(view)?.depth ?? 0) >= MAX_VIEW_QUEUE_DEPTH))
572
+ throw new StageError(429, "queue_full", "View queue is full");
573
+ return this.enqueue([...new Set(views)], async () => {
574
+ let release;
575
+ let reject;
576
+ const ready = new Promise((resolve, fail) => {
577
+ release = resolve;
578
+ reject = fail;
579
+ });
580
+ void ready.catch(() => {
581
+ });
582
+ let remaining = commands.length;
583
+ const actions = await Promise.all(
584
+ commands.map(async ({ actor, saved, session }) => {
585
+ let startedAt;
586
+ const result = await this.dispatch(
587
+ session,
588
+ saved.tool,
589
+ saved.args,
590
+ this.options.clock.now(),
591
+ void 0,
592
+ {
593
+ ready: () => {
594
+ if (--remaining === 0) {
595
+ try {
596
+ context.signal.throwIfAborted();
597
+ for (const { actor: actor2, saved: saved2 } of commands) {
598
+ const current = this.steps.get(actor2);
599
+ if (this.armed.get(actor2) !== saved2 || current?.step !== saved2.step || current.barrier !== saved2.barrier)
600
+ throw new ToolFailure("stale_arm", "Armed step is no longer active");
601
+ }
602
+ release();
603
+ } catch (error) {
604
+ reject(error);
605
+ }
606
+ }
607
+ return ready;
608
+ },
609
+ started: () => {
610
+ startedAt = this.options.clock.now();
611
+ },
612
+ failed: reject
613
+ }
614
+ );
615
+ return {
616
+ actor,
617
+ step: saved.step,
618
+ tool: saved.tool,
619
+ ...startedAt !== void 0 && { startedAt },
620
+ ok: result.ok
621
+ };
622
+ })
623
+ );
624
+ const times = actions.flatMap(
625
+ (action) => action.startedAt === void 0 ? [] : [action.startedAt]
626
+ );
627
+ const maxSkewMs = times.length ? Math.max(...times) - Math.min(...times) : 0;
628
+ const response = { barrier: request.barrier, actions, maxSkewMs };
629
+ context.emit({ kind: "together_fired", by: "conductor", ...response });
630
+ if (maxSkewMs > 100)
631
+ context.emit({
632
+ kind: "together_warning",
633
+ by: "conductor",
634
+ barrier: request.barrier,
635
+ maxSkewMs,
636
+ message: "Together release exceeded 100ms"
637
+ });
638
+ return response;
639
+ });
640
+ }
641
+ allowed(actor, name) {
642
+ const level = this.steps.get(actor)?.level;
643
+ if (level === "pixel" && (name.startsWith("web_") || name === "view_snapshot" || name === "view_text"))
644
+ return false;
645
+ if (level === "semantic" && name.startsWith("screen_")) return false;
646
+ return this.options.permissions === void 0 ? builtinTools.has(name) : this.options.permissions[actor]?.includes(name) ?? false;
647
+ }
648
+ listViews(actor) {
649
+ return this.surfaces.flatMap((surface) => surface.views?.list() ?? []).filter((view) => view.actor === actor).map((view) => ({ ...view }));
650
+ }
651
+ viewDriver(view, actor) {
652
+ const matches = this.surfaces.filter(
653
+ (surface) => surface.views?.list().some((candidate) => candidate.view === view && candidate.actor === actor)
654
+ );
655
+ if (matches.length !== 1)
656
+ throw new ToolFailure("forbidden", "View is not available to this actor");
657
+ return matches[0].views;
658
+ }
659
+ changed(before, after) {
660
+ if (before.fingerprint !== after.fingerprint || before.thumbnail.length !== after.thumbnail.length)
661
+ return true;
662
+ let difference = 0;
663
+ for (let i = 0; i < before.thumbnail.length; i++)
664
+ difference += Math.abs(before.thumbnail[i] - after.thumbnail[i]);
665
+ return difference > before.thumbnail.length * 255 * 0.01;
666
+ }
667
+ async enqueue(views, execute) {
668
+ const queues = views.map((view) => ({
669
+ view,
670
+ queue: this.queues.get(view) ?? { tail: Promise.resolve(), depth: 0 }
671
+ }));
672
+ const current = Promise.all(queues.map(({ queue }) => queue.tail)).then(execute);
673
+ const settled = current.then(
674
+ () => {
675
+ },
676
+ () => {
677
+ }
678
+ );
679
+ for (const { view, queue } of queues) {
680
+ queue.tail = settled;
681
+ queue.depth++;
682
+ this.queues.set(view, queue);
683
+ }
684
+ try {
685
+ return await current;
686
+ } finally {
687
+ for (const { view, queue } of queues) {
688
+ queue.depth--;
689
+ if (queue.depth === 0) this.queues.delete(view);
690
+ }
691
+ }
692
+ }
693
+ }
694
+ export {
695
+ ToolGateway
696
+ };