@agimon-ai/po-computer-use 0.0.0-alpha.13 → 0.0.0-alpha.131

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 (38) hide show
  1. package/LICENSE +149 -21
  2. package/README.md +6 -3
  3. package/dist/apiContracts.cjs +49 -3
  4. package/dist/apiContracts.cjs.map +1 -1
  5. package/dist/apiContracts.d.mts.map +1 -1
  6. package/dist/apiContracts.mjs +49 -3
  7. package/dist/apiContracts.mjs.map +1 -1
  8. package/dist/extensionService-BB08HbHP.cjs +1214 -0
  9. package/dist/extensionService-BB08HbHP.cjs.map +1 -0
  10. package/dist/extensionService-D8bAAsIN.mjs +1066 -0
  11. package/dist/extensionService-D8bAAsIN.mjs.map +1 -0
  12. package/dist/extensions/mcp.cjs.map +1 -1
  13. package/dist/extensions/mcp.mjs.map +1 -1
  14. package/dist/extensions/native.mjs +1616 -6
  15. package/dist/extensions/native.mjs.map +1 -1
  16. package/dist/extensions/server.cjs +623 -612
  17. package/dist/extensions/server.cjs.map +1 -1
  18. package/dist/extensions/server.d.mts +2 -2
  19. package/dist/extensions/server.d.mts.map +1 -1
  20. package/dist/extensions/server.mjs +591 -580
  21. package/dist/extensions/server.mjs.map +1 -1
  22. package/dist/extensions/web.mjs +993 -376
  23. package/dist/extensions/web.mjs.map +1 -1
  24. package/dist/index.cjs +1 -1
  25. package/dist/index.d.mts +35 -2
  26. package/dist/index.d.mts.map +1 -1
  27. package/dist/index.mjs +1 -1
  28. package/docs/remote-computer-use.md +29 -0
  29. package/llms.txt +1 -1
  30. package/package.json +66 -21
  31. package/src/prompts/codemode-how-to-computer-use/SKILL.md +73 -0
  32. package/src/types/computerUse.ts +32 -1
  33. package/src/types/computerUseApi.ts +8 -0
  34. package/dist/extensionService-Bp0q295i.cjs +0 -504
  35. package/dist/extensionService-Bp0q295i.cjs.map +0 -1
  36. package/dist/extensionService-DXvF7esO.mjs +0 -434
  37. package/dist/extensionService-DXvF7esO.mjs.map +0 -1
  38. package/src/prompts/po-use-computer-use/SKILL.md +0 -34
@@ -0,0 +1,1066 @@
1
+ import { createRequire } from "node:module";
2
+ import path from "node:path";
3
+ import { spawn } from "node:child_process";
4
+ import { realpath } from "node:fs/promises";
5
+ import { randomUUID } from "node:crypto";
6
+ import { hasInputTemplate, parseInputTemplate, renderInputTemplate } from "@agimon-ai/po-core/inputTemplate";
7
+ import { poApiCallerFrom } from "@agimon-ai/po-core/packageApi";
8
+ //#region src/constants/computerUse.ts
9
+ const COMPUTER_USE_GUIDANCE = `[COMPUTER USE ACTIVE]
10
+ Use computer_state before acting and after any action that may change the interface. Use only element refs and snapshot ids returned by computer_state. Use computer_action for one semantic press, focus, set_value, or scroll at a time. Use computer_exec only for a trusted, explicitly allowed local TypeScript script. Never infer coordinates, inspect another application, bypass secure elements, or retry an uncertain outcome. Stop computer use when the task is complete.`;
11
+ const COMMAND_NAME = "computer-use";
12
+ const COMMAND_DESCRIPTION = "Inspect or manage the session computer use mode";
13
+ const COMPUTER_USE_TOOL_NAMES = [
14
+ "computer_state",
15
+ "computer_action",
16
+ "computer_exec"
17
+ ];
18
+ /** The session artifact storage service and the folder computer-use evidence lands in. */
19
+ const COMPUTER_USE_ARTIFACTS_SERVICE = "po/artifacts";
20
+ const COMPUTER_USE_ARTIFACT_DIRECTORY = "computer-use";
21
+ /** The host recording store's own bounds: its largest recording and its range size. */
22
+ const COMPUTER_USE_RECORDING_MAX_BYTES = 134217728;
23
+ const COMPUTER_USE_RECORDING_CHUNK_BYTES = 1048576;
24
+ const COMPUTER_USE_CODEMODE_GUIDANCE = "[COMPUTER USE ACTIVE]\nUse computer.state() in exec before acting and after any action that may change the interface. Use only element refs and snapshot ids returned by computer.state(). Never infer coordinates or bypass secure elements. Call computer.stop() when the task is complete. Load codemode-how-to-computer-use for details.";
25
+ //#endregion
26
+ //#region src/services/computerScriptWorker/index.ts
27
+ /** Source for an isolated child process. Restricted modules execute in QuickJS, not in Node's realm. */
28
+ const COMPUTER_SCRIPT_WORKER_SOURCE = String.raw`
29
+ import { readFileSync, realpathSync, statSync } from 'node:fs';
30
+ import path from 'node:path';
31
+ import { stripTypeScriptTypes } from 'node:module';
32
+ import { pathToFileURL } from 'node:url';
33
+
34
+ let nextRequestId = 0;
35
+ let started = false;
36
+ const pending = new Map();
37
+ const controller = new AbortController();
38
+ process.once('SIGTERM', () => controller.abort());
39
+ const send = (message) => {
40
+ if (process.connected) process.send(message, () => {});
41
+ };
42
+ const call = (operation, payload) => new Promise((resolve, reject) => {
43
+ if (controller.signal.aborted) return reject(new Error('Computer script was cancelled.'));
44
+ if (pending.size >= 64) return reject(new Error('Too many outstanding program operations.'));
45
+ const id = String(++nextRequestId);
46
+ pending.set(id, { resolve, reject });
47
+ send({ type: 'program', id, operation, payload });
48
+ });
49
+
50
+ async function restricted(message) {
51
+ const { getQuickJS } = await import(pathToFileURL(message.quickjsPath).href);
52
+ const QuickJS = await getQuickJS();
53
+ const runtime = QuickJS.newRuntime();
54
+ runtime.setMemoryLimit(32 * 1024 * 1024);
55
+ runtime.setMaxStackSize(512 * 1024);
56
+ const deadline = Date.now() + message.timeoutMs;
57
+ runtime.setInterruptHandler(() => controller.signal.aborted || Date.now() >= deadline);
58
+ const { realpath } = await import('node:fs/promises');
59
+ const root = await realpath(message.scriptRoot);
60
+ const sources = new Map();
61
+ let sourceBytes = 0;
62
+ let moduleFailure;
63
+ // sync: QuickJS invokes module normalization and loading synchronously and cannot await filesystem reads.
64
+ const modulePath = (candidate) => {
65
+ const filename = realpathSync(candidate);
66
+ const relative = path.relative(root, filename);
67
+ if (relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) {
68
+ throw new Error('Computer helper escapes the admitted script root.');
69
+ }
70
+ if (!/\.(ts|js|mjs)$/.test(filename)) throw new Error('Computer helpers must be JavaScript or erasable TypeScript.');
71
+ return filename;
72
+ };
73
+ const entry = modulePath(message.scriptPath);
74
+ runtime.setModuleLoader((filename) => {
75
+ // Preserve a rejected normalization even if the engine subsequently asks to load an empty name.
76
+ if (moduleFailure) throw moduleFailure;
77
+ if (sources.has(filename)) return sources.get(filename);
78
+ if (sources.size >= 32 || statSync(filename).size > 256 * 1024) throw new Error('Computer script module limit exceeded.');
79
+ const source = readFileSync(filename, 'utf8');
80
+ sourceBytes += Buffer.byteLength(source);
81
+ if (sourceBytes > 512 * 1024) throw new Error('Computer script source limit exceeded.');
82
+ const compiled = filename.endsWith('.ts') ? stripTypeScriptTypes(source, { mode: 'strip' }) : source;
83
+ sources.set(filename, compiled);
84
+ return compiled;
85
+ }, (base, name) => {
86
+ try {
87
+ if (name === '__entry__') return entry;
88
+ if (!name.startsWith('./') && !name.startsWith('../')) {
89
+ throw new Error('Restricted computer functions cannot import host or package modules.');
90
+ }
91
+ return modulePath(path.resolve(path.dirname(base), name));
92
+ } catch (error) {
93
+ moduleFailure = error;
94
+ throw error;
95
+ }
96
+ });
97
+ const vm = runtime.newContext();
98
+ let disposed = false;
99
+ const deferreds = new Set();
100
+ const pump = () => {
101
+ if (disposed) return;
102
+ const jobs = runtime.executePendingJobs();
103
+ if (jobs.error) {
104
+ const detail = vm.dump(jobs.error);
105
+ jobs.error.dispose();
106
+ throw new Error(detail?.message ?? String(detail));
107
+ }
108
+ };
109
+ const set = (name, value) => {
110
+ vm.setProp(vm.global, name, value);
111
+ value.dispose();
112
+ };
113
+ set('__input', vm.newString(JSON.stringify(message.input)));
114
+ set('__aborted', vm.newFunction('__aborted', () => controller.signal.aborted ? vm.true : vm.false));
115
+ set('__log', vm.newFunction('__log', (level, text) => {
116
+ send({ type: 'log', level: vm.getString(level), message: vm.getString(text) });
117
+ }));
118
+ set('__call', vm.newFunction('__call', (operationHandle, payloadHandle) => {
119
+ const operation = vm.getString(operationHandle);
120
+ const serialized = vm.getString(payloadHandle);
121
+ if (serialized.length > message.maxOutputBytes) throw new Error('Computer action exceeds the size limit.');
122
+ if (operation !== 'observe' && operation !== 'act') throw new Error('Unsupported program operation.');
123
+ const deferred = vm.newPromise();
124
+ deferreds.add(deferred);
125
+ call(operation, JSON.parse(serialized)).then((value) => {
126
+ if (disposed) return;
127
+ const handle = vm.newString(JSON.stringify(value));
128
+ deferred.resolve(handle);
129
+ handle.dispose();
130
+ }, (error) => {
131
+ if (disposed) return;
132
+ const handle = vm.newError(error.message);
133
+ deferred.reject(handle);
134
+ handle.dispose();
135
+ }).then(() => {
136
+ if (disposed) return;
137
+ deferred.dispose();
138
+ deferreds.delete(deferred);
139
+ pump();
140
+ }).catch((error) => send({ type: 'failed', error: error.message }));
141
+ return deferred.handle.dup();
142
+ }));
143
+ let evaluation;
144
+ try {
145
+ evaluation = vm.unwrapResult(vm.evalCode(
146
+ 'import { run } from "__entry__";\n' +
147
+ 'const invoke = __call; const log = __log; const isAborted = __aborted;\n' +
148
+ 'const program = Object.freeze({\n' +
149
+ ' observe: async (options = {}) => JSON.parse(await invoke("observe", JSON.stringify(options))),\n' +
150
+ ' act: async (action) => JSON.parse(await invoke("act", JSON.stringify(action)))\n' +
151
+ '});\n' +
152
+ 'const logger = Object.freeze(Object.fromEntries(["debug","info","warn","error"].map(level => [level, value => log(level, String(value))])));\n' +
153
+ 'const signal = Object.freeze({ get aborted() { return isAborted(); }, throwIfAborted() { if (isAborted()) throw new Error("Computer script was cancelled."); } });\n' +
154
+ 'const result = await run({ context: { program }, input: JSON.parse(__input), logger, signal });\n' +
155
+ 'globalThis.__result = result === undefined ? undefined : JSON.stringify(result);',
156
+ path.join(root, '__computer_entry__.mjs'), { type: 'module' },
157
+ ));
158
+ const completion = vm.resolvePromise(evaluation);
159
+ pump();
160
+ const completed = vm.unwrapResult(await completion);
161
+ completed.dispose();
162
+ const result = vm.getProp(vm.global, '__result');
163
+ const resultJson = vm.dump(result);
164
+ result.dispose();
165
+ return resultJson;
166
+ } finally {
167
+ disposed = true;
168
+ for (const deferred of deferreds) deferred.dispose();
169
+ evaluation?.dispose();
170
+ vm.dispose();
171
+ runtime.dispose();
172
+ }
173
+ }
174
+
175
+ process.on('message', async (message) => {
176
+ if (message?.type === 'response') {
177
+ const request = pending.get(message.id);
178
+ if (!request) return;
179
+ pending.delete(message.id);
180
+ if (message.error) request.reject(new Error(message.error));
181
+ else request.resolve(message.value);
182
+ return;
183
+ }
184
+ if (message?.type !== 'start' || started) return;
185
+ started = true;
186
+ try {
187
+ let resultJson;
188
+ if (message.trusted) {
189
+ const loaded = await import(pathToFileURL(message.scriptPath).href);
190
+ if (typeof loaded.run !== 'function') throw new Error('Computer script must export a named run function.');
191
+ const program = {
192
+ observe: (options = {}) => call('observe', options),
193
+ act: (action) => call('act', action),
194
+ };
195
+ const logger = Object.fromEntries(['debug','info','warn','error'].map(level => [level, value => {
196
+ send({ type: 'log', level, message: String(value) });
197
+ }]));
198
+ const result = await loaded.run({ context: { program }, input: message.input, logger, signal: controller.signal });
199
+ resultJson = result === undefined ? undefined : JSON.stringify(result);
200
+ } else {
201
+ resultJson = await restricted(message);
202
+ }
203
+ if (typeof resultJson === 'string' && Buffer.byteLength(resultJson) > message.maxOutputBytes) {
204
+ throw new Error('Computer script result exceeded the size limit.');
205
+ }
206
+ send({ type: 'complete', resultJson });
207
+ } catch (error) {
208
+ send({ type: 'failed', error: String(error?.message ?? error).slice(0, 1024) });
209
+ }
210
+ });
211
+ `;
212
+ //#endregion
213
+ //#region src/types/computerUseApi.ts
214
+ const API_BASE_PATH = "computer-use";
215
+ const computerUseChannelType = "computer_use_state";
216
+ const COMPUTER_USE_MODE_ID = "computer-use";
217
+ const COMPUTER_USE_STATUS_KEY = "po-computer-use";
218
+ const COMPUTER_USE_CONFIRMATION_WINDOW_MS = 12e4;
219
+ /**
220
+ * Every path this API answers on, below its mount.
221
+ *
222
+ * The typed route table in `./apiRoutes` is built from this, the dispatcher
223
+ * reads that table, and the hub channel addresses the broker with these same
224
+ * strings, so a route cannot move on one side alone.
225
+ */
226
+ const COMPUTER_USE_ROUTES = {
227
+ activate: "/activate",
228
+ artifact: "/artifact",
229
+ agentState: "/agent/state",
230
+ agentObserve: "/agent/observe",
231
+ agentAction: "/agent/action",
232
+ agentStop: "/agent/stop",
233
+ hubState: "/hub/state",
234
+ hubActivation: "/hub/activation",
235
+ hubAuthorization: "/hub/authorization",
236
+ hubNext: "/hub/next",
237
+ hubComplete: "/hub/complete",
238
+ hubStop: "/hub/stop"
239
+ };
240
+ const COMPUTER_USE_WAKE_LIMIT = 1e6;
241
+ //#endregion
242
+ //#region src/types/desktopPermissions.ts
243
+ /** The macOS privacy permissions Desktop reports, in the order the settings page shows them. */
244
+ const DESKTOP_PERMISSIONS = [
245
+ "accessibility",
246
+ "screen-recording",
247
+ "microphone",
248
+ "automation",
249
+ "full-disk-access"
250
+ ];
251
+ function isDesktopPermission(value) {
252
+ return typeof value === "string" && DESKTOP_PERMISSIONS.includes(value);
253
+ }
254
+ //#endregion
255
+ //#region src/types/apiRoutes.ts
256
+ /**
257
+ * This package's routes, as data.
258
+ *
259
+ * No scope and no base path: the build reads both off
260
+ * `src/extensions/workspaces/sessions/(backend)/api/computer-use/`, so the
261
+ * mount is stated once, by the folder that creates it.
262
+ *
263
+ * The paths come from `COMPUTER_USE_ROUTES` rather than being written out
264
+ * again. That table already addressed the broker from the hub channel and from
265
+ * the broker's own dispatcher, and a second copy here is exactly the
266
+ * disagreement this file exists to prevent. The dispatcher now reads this
267
+ * table, so the page, the broker and the hub all resolve one set of strings.
268
+ *
269
+ * Activation, status, cancellation and recording reads are reachable from a browser. The `/agent/` and `/hub/` routes
270
+ * each demand a host-issued bearer token and answer 404 without one; they are
271
+ * declared here because they are this API's surface, not because a page calls
272
+ * them.
273
+ */
274
+ const routes = {
275
+ artifact: {
276
+ method: "GET",
277
+ path: COMPUTER_USE_ROUTES.artifact,
278
+ query: ["artifactId", "offset"],
279
+ raw: true
280
+ },
281
+ activationState: {
282
+ method: "GET",
283
+ path: COMPUTER_USE_ROUTES.activate,
284
+ response: void 0
285
+ },
286
+ cancelActivation: {
287
+ method: "DELETE",
288
+ path: COMPUTER_USE_ROUTES.activate,
289
+ response: void 0
290
+ },
291
+ activate: {
292
+ method: "POST",
293
+ path: COMPUTER_USE_ROUTES.activate,
294
+ response: void 0
295
+ },
296
+ agentState: {
297
+ method: "GET",
298
+ path: COMPUTER_USE_ROUTES.agentState,
299
+ response: void 0
300
+ },
301
+ /** Answers whatever the admitted Desktop provider returned, which is runtime-defined JSON. */
302
+ agentObserve: {
303
+ method: "POST",
304
+ path: COMPUTER_USE_ROUTES.agentObserve,
305
+ response: void 0
306
+ },
307
+ agentAction: {
308
+ method: "POST",
309
+ path: COMPUTER_USE_ROUTES.agentAction,
310
+ response: void 0
311
+ },
312
+ agentStop: {
313
+ method: "POST",
314
+ path: COMPUTER_USE_ROUTES.agentStop,
315
+ response: void 0
316
+ },
317
+ hubState: {
318
+ method: "GET",
319
+ path: COMPUTER_USE_ROUTES.hubState,
320
+ response: void 0
321
+ },
322
+ /** Null until a reader has confirmed one; reading it moves the session to `activating`. */
323
+ hubActivation: {
324
+ method: "GET",
325
+ path: COMPUTER_USE_ROUTES.hubActivation,
326
+ response: void 0
327
+ },
328
+ hubAuthorization: {
329
+ method: "GET",
330
+ path: COMPUTER_USE_ROUTES.hubAuthorization,
331
+ response: void 0
332
+ },
333
+ hubNext: {
334
+ method: "GET",
335
+ path: COMPUTER_USE_ROUTES.hubNext,
336
+ response: void 0
337
+ },
338
+ hubComplete: {
339
+ method: "POST",
340
+ path: COMPUTER_USE_ROUTES.hubComplete,
341
+ response: void 0
342
+ },
343
+ hubStop: {
344
+ method: "POST",
345
+ path: COMPUTER_USE_ROUTES.hubStop,
346
+ response: void 0
347
+ },
348
+ /** Desktop's macOS permission states, served by the hub's `desktop-permissions` mount. */
349
+ desktopPermissions: {
350
+ method: "GET",
351
+ path: "/",
352
+ response: void 0
353
+ },
354
+ /** Asks macOS for the body's permission on the Mac running Desktop; answers the states after. */
355
+ requestDesktopPermission: {
356
+ method: "POST",
357
+ path: "/",
358
+ response: void 0
359
+ }
360
+ };
361
+ //#endregion
362
+ //#region src/services/computerUseApi/index.ts
363
+ function jsonError(message, status) {
364
+ return Response.json({ error: message }, { status });
365
+ }
366
+ function record(value) {
367
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
368
+ }
369
+ async function body(request) {
370
+ try {
371
+ return record(await request.json()) ?? {};
372
+ } catch {
373
+ return {};
374
+ }
375
+ }
376
+ function semanticAction(value) {
377
+ const allowed = (keys) => Object.keys(value).every((key) => keys.includes(key));
378
+ if (value.kind === "launch") return typeof value.app === "string" && value.app.length > 0 && allowed(["kind", "app"]);
379
+ if (!(typeof value.snapshotId === "string" && value.snapshotId.length > 0 && typeof value.elementRef === "string" && value.elementRef.length > 0)) return false;
380
+ if (value.kind === "press" || value.kind === "focus") return allowed([
381
+ "kind",
382
+ "snapshotId",
383
+ "elementRef"
384
+ ]);
385
+ if (value.kind === "set_value") return typeof value.value === "string" && allowed([
386
+ "kind",
387
+ "snapshotId",
388
+ "elementRef",
389
+ "value"
390
+ ]);
391
+ if (value.kind === "scroll") return [
392
+ "up",
393
+ "down",
394
+ "left",
395
+ "right"
396
+ ].includes(value.direction) && (value.amount === "line" || value.amount === "page") && allowed([
397
+ "kind",
398
+ "snapshotId",
399
+ "elementRef",
400
+ "direction",
401
+ "amount"
402
+ ]);
403
+ if (value.kind === "perform") return typeof value.action === "string" && /^AX[A-Za-z]{1,62}$/u.test(value.action) && allowed([
404
+ "kind",
405
+ "snapshotId",
406
+ "elementRef",
407
+ "action"
408
+ ]);
409
+ return false;
410
+ }
411
+ /** Throws on anything but the documented observation options, so every caller shares one check. */
412
+ function observationOptions(value) {
413
+ const options = record(value);
414
+ if (options === void 0) throw new TypeError("Observation options must be an object.");
415
+ for (const [key, entry] of Object.entries(options)) if (!(key === "includeScreenshot" ? typeof entry === "boolean" : key === "root" || key === "label" || key === "role" ? typeof entry === "string" && entry.length > 0 && entry.length <= 256 : key === "offset" ? Number.isInteger(entry) && entry >= 0 && entry <= 2e3 : key === "limit" && Number.isInteger(entry) && entry >= 1 && entry <= 500)) throw new TypeError(`Invalid observation option "${key}".`);
416
+ return options;
417
+ }
418
+ function artifactView(value) {
419
+ const input = record(value);
420
+ if (typeof input?.artifactId !== "string" || input.status !== "ready" && input.status !== "failed") return void 0;
421
+ const safeUrl = (candidate) => typeof candidate === "string" && candidate.startsWith("/api/") ? candidate : void 0;
422
+ const downloadUrl = safeUrl(input.downloadUrl);
423
+ const previewUrl = safeUrl(input.previewUrl);
424
+ const artifactFailure = record(input.failure);
425
+ const safeFailure = typeof artifactFailure?.code === "string" && typeof artifactFailure.message === "string" ? {
426
+ code: artifactFailure.code.slice(0, 128),
427
+ message: artifactFailure.message.slice(0, 512)
428
+ } : void 0;
429
+ return {
430
+ artifactId: input.artifactId,
431
+ status: input.status,
432
+ ...typeof input.sizeBytes === "number" && Number.isSafeInteger(input.sizeBytes) && input.sizeBytes > 0 ? { sizeBytes: input.sizeBytes } : {},
433
+ ...downloadUrl === void 0 ? {} : { downloadUrl },
434
+ ...previewUrl === void 0 ? {} : { previewUrl },
435
+ ...typeof input.actionCount === "number" ? { actionCount: input.actionCount } : {},
436
+ ...typeof input.completedAt === "string" ? { completedAt: input.completedAt } : {},
437
+ ...safeFailure === void 0 ? {} : { failure: safeFailure }
438
+ };
439
+ }
440
+ var ComputerUseRequestBroker = class ComputerUseRequestBroker {
441
+ sessionId;
442
+ internalToken;
443
+ hubToken;
444
+ directEvents;
445
+ requestTimeoutMs;
446
+ revision = 0;
447
+ wake = 0;
448
+ phase = "inactive";
449
+ activation;
450
+ grantId;
451
+ expiresAt;
452
+ actionSequence = 0;
453
+ expiryTimer;
454
+ failure;
455
+ artifact;
456
+ pending;
457
+ closed = false;
458
+ desktop;
459
+ beforeActivate;
460
+ profileRuntime;
461
+ nativeTarget;
462
+ resolvingInput = false;
463
+ inputController;
464
+ sensitiveInput = false;
465
+ listeners = /* @__PURE__ */ new Set();
466
+ unsubscribeDesktop;
467
+ static DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
468
+ constructor(options) {
469
+ this.sessionId = options.sessionId ?? "unknown";
470
+ this.internalToken = options.internalToken;
471
+ this.hubToken = options.hubToken;
472
+ this.directEvents = options.directEvents;
473
+ this.requestTimeoutMs = options.requestTimeoutMs ?? ComputerUseRequestBroker.DEFAULT_REQUEST_TIMEOUT_MS;
474
+ this.desktop = options.desktop;
475
+ this.beforeActivate = options.beforeActivate;
476
+ this.profileRuntime = options.profileRuntime;
477
+ this.unsubscribeDesktop = options.desktop?.subscribe(() => {
478
+ this.inputController?.abort();
479
+ clearTimeout(this.expiryTimer);
480
+ if (!options.desktop?.available) {
481
+ this.rejectPending("Desktop disconnected.");
482
+ this.phase = "failed";
483
+ this.grantId = void 0;
484
+ this.failure = {
485
+ code: "desktop_unavailable",
486
+ message: "Desktop disconnected."
487
+ };
488
+ } else if (this.phase !== "inactive" && this.phase !== "failed") {
489
+ this.phase = "stopping";
490
+ this.rejectPending("Control was stopped by Desktop.");
491
+ }
492
+ this.changed();
493
+ });
494
+ }
495
+ state() {
496
+ return Object.freeze({
497
+ sessionId: this.sessionId,
498
+ revision: this.revision,
499
+ wake: this.wake,
500
+ phase: this.phase,
501
+ ...this.activation === void 0 ? {} : {
502
+ requestId: this.activation.requestId,
503
+ target: this.activation.target,
504
+ durationMs: this.activation.durationSeconds * 1e3
505
+ },
506
+ ...this.expiresAt === void 0 ? {} : { expiresAt: this.expiresAt },
507
+ ...this.failure === void 0 ? {} : { failure: this.failure },
508
+ ...this.artifact === void 0 ? {} : { artifact: this.artifact }
509
+ });
510
+ }
511
+ /** Tools and the API share this broker. No socket, credential discovery, or second state store. */
512
+ sessionClient() {
513
+ const result = async (response) => {
514
+ const value = await response.json();
515
+ if (!response.ok) throw new Error(value.error ?? `Computer-use request failed (${response.status}).`);
516
+ return value;
517
+ };
518
+ const requireDesktop = () => {
519
+ if (this.closed || !this.desktop?.available || this.desktop.enabled === false) throw new Error("Desktop computer use is unavailable.");
520
+ };
521
+ return {
522
+ state: async () => this.state(),
523
+ subscribeStatus: (listener) => {
524
+ this.listeners.add(listener);
525
+ return () => {
526
+ this.listeners.delete(listener);
527
+ };
528
+ },
529
+ observe: async (signal, options = {}) => {
530
+ requireDesktop();
531
+ return result(await this.enqueue("observe", observationOptions(options), signal));
532
+ },
533
+ act: async (action, signal) => {
534
+ requireDesktop();
535
+ if (!semanticAction(action)) throw new Error("A valid semantic action is required.");
536
+ return result(await this.performAction(action, signal));
537
+ },
538
+ stop: async (signal) => {
539
+ signal?.throwIfAborted();
540
+ this.inputController?.abort();
541
+ if (this.phase !== "inactive" && this.phase !== "failed") {
542
+ this.phase = "stopping";
543
+ this.rejectPending("Computer use was stopped.");
544
+ this.changed();
545
+ }
546
+ return this.state();
547
+ }
548
+ };
549
+ }
550
+ changed() {
551
+ this.revision += 1;
552
+ this.wake = (this.wake + 1) % COMPUTER_USE_WAKE_LIMIT;
553
+ const state = this.state();
554
+ for (const listener of this.listeners) listener(state);
555
+ this.directEvents.publish(computerUseChannelType, this.sessionId, state);
556
+ }
557
+ authorized(request, token) {
558
+ return token !== void 0 && request.headers.get("authorization") === `Bearer ${token}`;
559
+ }
560
+ async requestActivation(request) {
561
+ if (!this.desktop?.available || !(this.desktop.authorizeActivation?.(request.headers) ?? this.desktop.authorize(request.headers))) return jsonError("Not found.", 404);
562
+ if (this.desktop.enabled === false) return jsonError("Enable computer use in global Desktop settings first.", 409);
563
+ const stamped = poApiCallerFrom(request.headers);
564
+ const caller = stamped?.locality === "remote" ? stamped : {
565
+ locality: "local",
566
+ stepUp: "not-required"
567
+ };
568
+ if (this.phase !== "inactive" && this.phase !== "failed") return jsonError("Computer use is already busy.", 409);
569
+ const input = await body(request);
570
+ if (input.confirmed !== true) return jsonError("Approve computer control in the in-app dialog first.", 400);
571
+ const target = record(input.target);
572
+ const durationMs = input.durationMs;
573
+ const desktopTarget = target?.scope === "desktop" && Object.keys(target).length === 1;
574
+ if (target === void 0 || !desktopTarget && (typeof target.windowId !== "string" || typeof target.bundleId !== "string")) return jsonError("An explicit application window or whole-desktop target is required.", 400);
575
+ if (typeof durationMs !== "number" || !Number.isInteger(durationMs) || durationMs < 1e3 || durationMs > 18e5) return jsonError("The requested duration is invalid.", 400);
576
+ try {
577
+ this.desktop.claim(request.headers);
578
+ await this.beforeActivate?.();
579
+ } catch (error) {
580
+ return jsonError(error instanceof Error ? error.message : String(error), 409);
581
+ }
582
+ if (this.closed || !this.desktop.available || this.phase !== "inactive" && this.phase !== "failed") return jsonError("Computer use is unavailable or already busy.", 409);
583
+ const createdAt = Date.now();
584
+ this.activation = Object.freeze({
585
+ requestId: randomUUID(),
586
+ target: Object.freeze({ ...target }),
587
+ durationSeconds: durationMs / 1e3,
588
+ createdAt,
589
+ confirmationExpiresAt: createdAt + COMPUTER_USE_CONFIRMATION_WINDOW_MS,
590
+ confirmedAt: createdAt,
591
+ caller: Object.freeze({ ...caller })
592
+ });
593
+ this.phase = "awaiting_confirmation";
594
+ this.failure = void 0;
595
+ this.artifact = void 0;
596
+ this.changed();
597
+ return Response.json(this.state(), { status: 202 });
598
+ }
599
+ rejectPending(message) {
600
+ const pending = this.pending;
601
+ if (pending === void 0) return;
602
+ this.pending = void 0;
603
+ pending.dispose();
604
+ pending.reject(new Error(message));
605
+ }
606
+ stopAfterUncertainRequest(message) {
607
+ if (this.phase === "active") {
608
+ this.phase = "stopping";
609
+ this.changed();
610
+ }
611
+ this.rejectPending(message);
612
+ }
613
+ async performAction(action, requestSignal) {
614
+ if (this.resolvingInput) return jsonError("Another computer-use request is live.", 409);
615
+ if (action.kind !== "set_value" || !hasInputTemplate(action.value)) return this.enqueue("act", action, requestSignal);
616
+ this.resolvingInput = true;
617
+ try {
618
+ if (this.phase !== "active" || this.pending || !this.grantId) throw new Error();
619
+ const parts = parseInputTemplate(action.value);
620
+ const profile = this.profileRuntime?.();
621
+ if (!profile) throw new Error();
622
+ const snapshot = profile.readSelection();
623
+ const generation = snapshot.generation;
624
+ const grantId = this.grantId;
625
+ const target = this.nativeTarget;
626
+ const usesSecret = parts.some((part) => part.kind === "secret");
627
+ if (usesSecret && (!target || target.scope === "desktop" || typeof target.bundleId !== "string")) throw new Error();
628
+ const controller = new AbortController();
629
+ this.inputController = controller;
630
+ const signal = AbortSignal.any([
631
+ snapshot.signal,
632
+ controller.signal,
633
+ ...requestSignal ? [requestSignal] : []
634
+ ]);
635
+ const value = await renderInputTemplate(parts, {
636
+ readEnv: (name) => snapshot.env && Object.hasOwn(snapshot.env, name) ? snapshot.env[name] : void 0,
637
+ resolveSecret: (name) => profile.resolveInputSecret(name, {
638
+ surface: "computer",
639
+ target: target.bundleId,
640
+ signal
641
+ }),
642
+ onResolved: () => {
643
+ this.sensitiveInput = true;
644
+ },
645
+ signal
646
+ });
647
+ signal.throwIfAborted();
648
+ if (this.closed || this.phase !== "active" || this.grantId !== grantId || this.nativeTarget !== target || this.profileRuntime?.() !== profile || profile.readSelection().generation !== generation) throw new Error();
649
+ this.resolvingInput = false;
650
+ return await this.enqueue("act", {
651
+ ...action,
652
+ value,
653
+ ...usesSecret ? { sensitiveBundleId: target.bundleId } : {}
654
+ }, signal);
655
+ } catch {
656
+ return jsonError("Computer input template failed.", 400);
657
+ } finally {
658
+ this.inputController = void 0;
659
+ this.resolvingInput = false;
660
+ }
661
+ }
662
+ async enqueue(operation, payload, signal) {
663
+ if (this.resolvingInput) return jsonError("Another computer-use request is live.", 409);
664
+ if (operation === "observe" && this.sensitiveInput) return jsonError("Observations are sealed after sensitive input.", 409);
665
+ if (this.phase !== "active" || this.grantId === void 0) return jsonError("Computer use is not active.", 409);
666
+ if (this.pending !== void 0) return jsonError("Another computer-use request is live.", 409);
667
+ if (signal?.aborted === true) return jsonError("The computer-use request was cancelled.", 499);
668
+ const sequence = operation === "act" ? ++this.actionSequence : void 0;
669
+ const request = {
670
+ id: randomUUID(),
671
+ operation,
672
+ grantId: this.grantId,
673
+ ...sequence === void 0 ? {} : { sequence },
674
+ ...payload === void 0 ? {} : { payload }
675
+ };
676
+ const completion = new Promise((resolve, reject) => {
677
+ const onAbort = () => this.stopAfterUncertainRequest("The computer-use request was cancelled.");
678
+ const timer = setTimeout(() => this.stopAfterUncertainRequest("The computer-use request timed out."), this.requestTimeoutMs);
679
+ timer.unref?.();
680
+ signal?.addEventListener("abort", onAbort, { once: true });
681
+ this.pending = {
682
+ request,
683
+ resolve,
684
+ reject,
685
+ dispose: () => {
686
+ clearTimeout(timer);
687
+ signal?.removeEventListener("abort", onAbort);
688
+ }
689
+ };
690
+ });
691
+ this.changed();
692
+ try {
693
+ const value = await completion;
694
+ return Response.json(this.sensitiveInput ? { applied: true } : value);
695
+ } catch (error) {
696
+ return jsonError(this.sensitiveInput ? "Sensitive computer input failed." : error instanceof Error ? error.message : String(error), 502);
697
+ }
698
+ }
699
+ async fetch(request) {
700
+ if (this.closed) return jsonError("Computer-use broker is closed.", 503);
701
+ const url = new URL(request.url);
702
+ const path = url.pathname;
703
+ if (request.method === "GET" && path === routes.artifact.path) {
704
+ if (!(this.desktop?.authorizeRecording?.(request.headers) ?? this.desktop?.authorize(request.headers)) || !this.desktop?.fetchRecording) return jsonError("Not found.", 404);
705
+ const artifactId = url.searchParams.get("artifactId") ?? "";
706
+ const offsetText = url.searchParams.get("offset") ?? "";
707
+ const offset = Number(offsetText);
708
+ if (!/^[0-9]+$/u.test(offsetText) || !Number.isSafeInteger(offset) || offset < 0 || offset > 134217728) return jsonError("Invalid recording offset.", 400);
709
+ return this.desktop.fetchRecording(artifactId, `bytes=${offset}-${offset + 1048576 - 1}`);
710
+ }
711
+ if (path === routes.activate.path && request.method === "GET") {
712
+ if (!this.desktop?.authorizePending?.(request.headers) && !(this.desktop?.authorizeRecording?.(request.headers) ?? this.desktop?.authorize(request.headers))) return jsonError("Not found.", 404);
713
+ return Response.json(this.state());
714
+ }
715
+ if (path === routes.activate.path && request.method === "DELETE") {
716
+ if (!this.desktop?.authorizePending?.(request.headers)) return jsonError("Not found.", 404);
717
+ if (this.phase !== "awaiting_confirmation" && this.phase !== "activating") return jsonError("No activation is pending.", 409);
718
+ this.phase = "stopping";
719
+ this.rejectPending("The activation was cancelled.");
720
+ this.changed();
721
+ return Response.json(this.state(), { status: 202 });
722
+ }
723
+ if (request.method === "POST" && path === routes.activate.path) return this.requestActivation(request);
724
+ const agent = path.startsWith("/agent/");
725
+ const hub = path.startsWith("/hub/");
726
+ if (agent && !this.authorized(request, this.internalToken) || hub && !this.authorized(request, this.hubToken)) return jsonError("Not found.", 404);
727
+ if (request.method === "GET" && (path === routes.agentState.path || path === routes.hubState.path)) return Response.json(this.state());
728
+ if (request.method === "POST" && path === routes.agentObserve.path) return this.enqueue("observe", void 0, request.signal);
729
+ if (request.method === "POST" && path === routes.agentAction.path) {
730
+ const action = await body(request);
731
+ if (!semanticAction(action)) return jsonError("A valid semantic action is required.", 400);
732
+ return this.performAction(action, request.signal);
733
+ }
734
+ if (request.method === "POST" && path === routes.agentStop.path) {
735
+ this.inputController?.abort();
736
+ if (this.phase !== "active") return jsonError("Computer use is not active.", 409);
737
+ this.phase = "stopping";
738
+ this.rejectPending("The computer-use request was stopped.");
739
+ this.changed();
740
+ return Response.json(this.state(), { status: 202 });
741
+ }
742
+ if (request.method === "GET" && path === routes.hubActivation.path) {
743
+ if (this.activation?.confirmedAt === void 0 || this.phase !== "awaiting_confirmation") return Response.json(null);
744
+ this.phase = "activating";
745
+ this.changed();
746
+ return Response.json(this.activation);
747
+ }
748
+ if (request.method === "GET" && path === routes.hubAuthorization.path) return Response.json(this.grantId === void 0 ? null : {
749
+ grantId: this.grantId,
750
+ expiresAt: this.expiresAt
751
+ });
752
+ if (request.method === "GET" && path === routes.hubNext.path) return Response.json(this.pending?.request ?? null);
753
+ if (request.method === "POST" && path === routes.hubComplete.path) {
754
+ const input = await body(request);
755
+ const id = typeof input.id === "string" ? input.id : void 0;
756
+ if (this.pending === void 0 || this.pending.request.id !== id) return jsonError("The request is stale.", 409);
757
+ const pending = this.pending;
758
+ this.pending = void 0;
759
+ pending.dispose();
760
+ if (typeof input.error === "string") {
761
+ this.phase = "stopping";
762
+ pending.reject(new Error(input.error));
763
+ } else pending.resolve(input.result);
764
+ this.changed();
765
+ return Response.json(this.state());
766
+ }
767
+ if (request.method === "POST" && path === routes.hubStop.path) {
768
+ this.inputController?.abort();
769
+ const input = await body(request);
770
+ if (this.phase === "activating") {
771
+ if (typeof input.error === "string") {
772
+ this.phase = "failed";
773
+ this.failure = {
774
+ code: "desktop_unavailable",
775
+ message: input.error.slice(0, 512)
776
+ };
777
+ this.activation = void 0;
778
+ } else {
779
+ const host = record(input.host);
780
+ if (typeof host?.grantId !== "string" || !Number.isFinite(host.expiresAt) || host.expiresAt <= Date.now()) return jsonError("Desktop did not issue a complete grant.", 502);
781
+ const selectedTarget = record(host.target);
782
+ this.nativeTarget = selectedTarget === void 0 ? void 0 : Object.freeze({ ...selectedTarget });
783
+ if (this.activation !== void 0 && selectedTarget !== void 0) this.activation = Object.freeze({
784
+ ...this.activation,
785
+ target: Object.freeze({ ...selectedTarget })
786
+ });
787
+ this.grantId = host.grantId;
788
+ this.expiresAt = host.expiresAt;
789
+ this.actionSequence = 0;
790
+ this.phase = "active";
791
+ clearTimeout(this.expiryTimer);
792
+ this.expiryTimer = setTimeout(() => {
793
+ if (this.closed || this.phase !== "active") return;
794
+ this.phase = "stopping";
795
+ this.inputController?.abort();
796
+ this.rejectPending("The computer-use grant expired.");
797
+ this.changed();
798
+ }, Math.max(0, this.expiresAt - Date.now()));
799
+ this.expiryTimer.unref?.();
800
+ }
801
+ } else {
802
+ clearTimeout(this.expiryTimer);
803
+ this.rejectPending("The computer-use session stopped.");
804
+ this.phase = "inactive";
805
+ this.grantId = void 0;
806
+ this.expiresAt = void 0;
807
+ this.activation = void 0;
808
+ this.nativeTarget = void 0;
809
+ this.artifact = artifactView(input.artifact) ?? this.artifact;
810
+ }
811
+ this.changed();
812
+ return Response.json(this.state());
813
+ }
814
+ return jsonError("Not found.", 404);
815
+ }
816
+ close() {
817
+ if (this.closed) return;
818
+ this.closed = true;
819
+ this.inputController?.abort();
820
+ clearTimeout(this.expiryTimer);
821
+ this.unsubscribeDesktop?.();
822
+ this.listeners.clear();
823
+ this.rejectPending("Computer-use broker closed.");
824
+ this.grantId = void 0;
825
+ this.expiresAt = void 0;
826
+ }
827
+ };
828
+ function createComputerUseApi(options) {
829
+ return new ComputerUseRequestBroker(options);
830
+ }
831
+ //#endregion
832
+ //#region src/services/computerScriptRunner/index.ts
833
+ const DEFAULT_TIMEOUT_MS = 3e4;
834
+ const DEFAULT_MAX_OUTPUT_BYTES = 262144;
835
+ const MAX_IMAGE_BYTES = 6291456;
836
+ const MAX_PENDING_OPERATIONS = 64;
837
+ var ComputerScriptExecutionError = class extends Error {
838
+ completedActions;
839
+ outcomeUncertain;
840
+ constructor(message, completedActions, outcomeUncertain) {
841
+ super(message);
842
+ this.completedActions = completedActions;
843
+ this.outcomeUncertain = outcomeUncertain;
844
+ this.name = "ComputerScriptExecutionError";
845
+ }
846
+ };
847
+ var ComputerScriptRunner = class {
848
+ client;
849
+ allowedScriptPaths;
850
+ scriptRoot;
851
+ timeoutMs;
852
+ maxOutputBytes;
853
+ constructor(options) {
854
+ this.client = options.client;
855
+ this.allowedScriptPaths = options.allowedScriptPaths;
856
+ this.scriptRoot = options.scriptRoot;
857
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
858
+ this.maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
859
+ }
860
+ async execute(scriptPath, input, signal, options = {}, cwd) {
861
+ signal?.throwIfAborted();
862
+ const resolvedPath = await realpath(path.resolve(this.scriptRoot ?? cwd ?? process.cwd(), scriptPath));
863
+ const allowedPaths = await Promise.all(this.allowedScriptPaths.map(async (candidate) => realpath(candidate).catch(() => "")));
864
+ const trusted = options.trusted === true;
865
+ if ((trusted || this.scriptRoot === void 0) && !allowedPaths.includes(resolvedPath)) throw new Error("Computer script path is not explicitly allowed.");
866
+ if (!/\.(ts|js|mjs)$/u.test(resolvedPath)) throw new Error("Computer scripts must be JavaScript or erasable TypeScript files.");
867
+ const root = await realpath(this.scriptRoot ?? path.dirname(resolvedPath));
868
+ const relative = path.relative(root, resolvedPath);
869
+ if (!trusted && (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))) throw new Error("Computer script escapes the admitted script root.");
870
+ const serializedInput = JSON.stringify(input);
871
+ if (serializedInput === void 0) throw new Error("Computer script input must be JSON serializable.");
872
+ if (Buffer.byteLength(serializedInput) > this.maxOutputBytes) throw new Error("Computer script input exceeds the size limit.");
873
+ const quickjsPath = trusted ? void 0 : createRequire(import.meta.url).resolve("quickjs-emscripten");
874
+ signal?.throwIfAborted();
875
+ const started = performance.now();
876
+ return new Promise((resolve, reject) => {
877
+ const child = spawn(process.execPath, [
878
+ "--input-type=module",
879
+ "--eval",
880
+ COMPUTER_SCRIPT_WORKER_SOURCE
881
+ ], {
882
+ stdio: [
883
+ "ignore",
884
+ "pipe",
885
+ "pipe",
886
+ "ipc"
887
+ ],
888
+ env: trusted ? process.env : { ELECTRON_RUN_AS_NODE: "1" }
889
+ });
890
+ const controller = new AbortController();
891
+ const logs = [];
892
+ let outputBytes = 0;
893
+ let completedActions = 0;
894
+ let observations = 0;
895
+ let actionInFlight = false;
896
+ let settled = false;
897
+ let completing = false;
898
+ let outstanding = 0;
899
+ let operation = Promise.resolve();
900
+ const finish = (error, value) => {
901
+ if (settled) return;
902
+ settled = true;
903
+ clearTimeout(timeout);
904
+ signal?.removeEventListener("abort", onAbort);
905
+ controller.abort();
906
+ child.kill("SIGTERM");
907
+ setTimeout(() => child.kill("SIGKILL"), 250).unref();
908
+ if (error) reject(new ComputerScriptExecutionError(error.message, completedActions, actionInFlight));
909
+ else resolve(value);
910
+ };
911
+ const addOutput = (value) => {
912
+ outputBytes += Buffer.byteLength(value);
913
+ if (outputBytes <= this.maxOutputBytes) return true;
914
+ finish(/* @__PURE__ */ new Error("Computer script output exceeded the size limit."));
915
+ return false;
916
+ };
917
+ const send = (value) => {
918
+ if (settled || !child.connected) return;
919
+ child.send(value, (error) => {
920
+ if (error && !settled) finish(error);
921
+ });
922
+ };
923
+ const onAbort = () => finish(/* @__PURE__ */ new Error("Computer script execution was cancelled."));
924
+ const timeout = setTimeout(() => finish(/* @__PURE__ */ new Error("Computer script execution timed out.")), this.timeoutMs);
925
+ timeout.unref();
926
+ signal?.addEventListener("abort", onAbort, { once: true });
927
+ if (signal?.aborted) return onAbort();
928
+ child.stdout?.on("data", (chunk) => addOutput(chunk.toString("utf8")));
929
+ child.stderr?.on("data", (chunk) => addOutput(chunk.toString("utf8")));
930
+ child.on("error", (error) => finish(error));
931
+ child.on("exit", (code, exitSignal) => {
932
+ if (!settled) finish(/* @__PURE__ */ new Error(`Computer script worker exited before completion (${exitSignal ?? code ?? "unknown"}).`));
933
+ });
934
+ const observe = async (options) => {
935
+ const includeScreenshot = options.includeScreenshot === true;
936
+ const value = await this.client.observe(controller.signal, {
937
+ ...options,
938
+ includeScreenshot
939
+ });
940
+ observations += 1;
941
+ const { screenshot, ...semantic } = value;
942
+ if (Buffer.byteLength(JSON.stringify(semantic)) > this.maxOutputBytes) throw new Error("Computer observation exceeds the size limit.");
943
+ if (includeScreenshot && screenshot) {
944
+ if (screenshot.mimeType !== "image/png" || screenshot.data.length > Math.ceil(MAX_IMAGE_BYTES / 3) * 4) throw new Error("Computer screenshot exceeds the image limit.");
945
+ return {
946
+ ...semantic,
947
+ screenshot
948
+ };
949
+ }
950
+ return semantic;
951
+ };
952
+ child.on("message", (raw) => {
953
+ if (settled) return;
954
+ if (!raw || typeof raw !== "object" || Buffer.byteLength(JSON.stringify(raw)) > this.maxOutputBytes + 4096) {
955
+ finish(/* @__PURE__ */ new Error("Computer worker message exceeds the size limit."));
956
+ return;
957
+ }
958
+ if (raw.type === "log" && typeof raw.message === "string") {
959
+ const line = `[${String(raw.level)}] ${raw.message}`;
960
+ if (addOutput(line)) logs.push(line);
961
+ return;
962
+ }
963
+ if (raw.type === "program") {
964
+ if (completing || typeof raw.id !== "string" || raw.id.length > 128 || raw.operation !== "observe" && raw.operation !== "act" || outstanding >= MAX_PENDING_OPERATIONS) {
965
+ finish(/* @__PURE__ */ new Error("Invalid or excessive computer program operations."));
966
+ return;
967
+ }
968
+ outstanding += 1;
969
+ operation = operation.then(async () => {
970
+ if (settled || controller.signal.aborted) return;
971
+ try {
972
+ let value;
973
+ if (raw.operation === "observe") value = await observe(observationOptions(raw.payload));
974
+ else {
975
+ actionInFlight = true;
976
+ value = await this.client.act(raw.payload, controller.signal);
977
+ completedActions += 1;
978
+ actionInFlight = false;
979
+ }
980
+ send({
981
+ type: "response",
982
+ id: raw.id,
983
+ value
984
+ });
985
+ } catch (error) {
986
+ if (actionInFlight) finish(error instanceof Error ? error : new Error(String(error)));
987
+ else send({
988
+ type: "response",
989
+ id: raw.id,
990
+ error: error instanceof Error ? error.message : String(error)
991
+ });
992
+ } finally {
993
+ outstanding -= 1;
994
+ }
995
+ }).catch((error) => finish(error instanceof Error ? error : new Error(String(error))));
996
+ return;
997
+ }
998
+ if (raw.type === "failed" && typeof raw.error === "string") {
999
+ finish(new Error(raw.error));
1000
+ return;
1001
+ }
1002
+ if (raw.type === "complete") {
1003
+ if (completing) {
1004
+ finish(/* @__PURE__ */ new Error("Computer worker completed twice."));
1005
+ return;
1006
+ }
1007
+ completing = true;
1008
+ operation = operation.then(async () => {
1009
+ if (settled) return;
1010
+ const resultJson = raw.resultJson;
1011
+ if (resultJson !== void 0 && typeof resultJson !== "string") throw new Error("Computer script returned an invalid result.");
1012
+ if (typeof resultJson === "string" && !addOutput(resultJson)) return;
1013
+ const observation = await observe({ includeScreenshot: options.includeScreenshot === true });
1014
+ if (settled || !addOutput(JSON.stringify({
1015
+ ...observation,
1016
+ screenshot: void 0
1017
+ }))) return;
1018
+ finish(void 0, {
1019
+ ...typeof resultJson === "string" ? { result: JSON.parse(resultJson) } : {},
1020
+ observation,
1021
+ logs,
1022
+ metrics: {
1023
+ actions: completedActions,
1024
+ observations,
1025
+ durationMs: Math.round(performance.now() - started),
1026
+ outputBytes
1027
+ }
1028
+ });
1029
+ }).catch((error) => finish(error instanceof Error ? error : new Error(String(error))));
1030
+ }
1031
+ });
1032
+ send({
1033
+ type: "start",
1034
+ scriptPath: resolvedPath,
1035
+ scriptRoot: root,
1036
+ input: JSON.parse(serializedInput),
1037
+ trusted,
1038
+ quickjsPath,
1039
+ timeoutMs: this.timeoutMs,
1040
+ maxOutputBytes: this.maxOutputBytes
1041
+ });
1042
+ });
1043
+ }
1044
+ };
1045
+ //#endregion
1046
+ //#region src/services/extensionService/index.ts
1047
+ var DefaultComputerUseExtensionService = class {
1048
+ client;
1049
+ constructor(client) {
1050
+ this.client = client;
1051
+ }
1052
+ async execute() {
1053
+ if (this.client === void 0) return {
1054
+ message: "Computer use requires a Po Desktop session.",
1055
+ level: "error"
1056
+ };
1057
+ return {
1058
+ message: `Computer use is ${(await this.client.state()).phase.replaceAll("_", " ")}.`,
1059
+ level: "info"
1060
+ };
1061
+ }
1062
+ };
1063
+ //#endregion
1064
+ export { COMPUTER_USE_GUIDANCE as _, routes as a, COMPUTER_USE_TOOL_NAMES as b, COMPUTER_USE_MODE_ID as c, computerUseChannelType as d, COMMAND_DESCRIPTION as f, COMPUTER_USE_CODEMODE_GUIDANCE as g, COMPUTER_USE_ARTIFACT_DIRECTORY as h, createComputerUseApi as i, COMPUTER_USE_ROUTES as l, COMPUTER_USE_ARTIFACTS_SERVICE as m, ComputerScriptExecutionError as n, isDesktopPermission as o, COMMAND_NAME as p, ComputerScriptRunner as r, API_BASE_PATH as s, DefaultComputerUseExtensionService as t, COMPUTER_USE_STATUS_KEY as u, COMPUTER_USE_RECORDING_CHUNK_BYTES as v, COMPUTER_USE_RECORDING_MAX_BYTES as y };
1065
+
1066
+ //# sourceMappingURL=extensionService-D8bAAsIN.mjs.map