@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
@@ -2,44 +2,15 @@ Object.defineProperties(exports, {
2
2
  __esModule: { value: true },
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
- const require_extensionService = require("../extensionService-Bp0q295i.cjs");
5
+ const require_extensionService = require("../extensionService-BB08HbHP.cjs");
6
6
  let node_path = require("node:path");
7
7
  node_path = require_extensionService.__toESM(node_path, 1);
8
- let _agimon_ai_po_core_serverFacet = require("@agimon-ai/po-core/serverFacet");
8
+ let node_crypto = require("node:crypto");
9
+ let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
9
10
  let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
11
+ let _agimon_ai_po_core_codemode = require("@agimon-ai/po-core/codemode");
12
+ let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
10
13
  let _agimon_ai_po_minor_mode = require("@agimon-ai/po-minor-mode");
11
- let node_crypto = require("node:crypto");
12
- let _agimon_ai_po_core_packageApi = require("@agimon-ai/po-core/packageApi");
13
- let _agimon_ai_po_core_web = require("@agimon-ai/po-core/web");
14
- //#region src/types/computerUseApi.ts
15
- const API_BASE_PATH = "computer-use";
16
- const computerUseChannelType = "computer_use_state";
17
- const COMPUTER_USE_MODE_ID = "computer-use";
18
- const COMPUTER_USE_STATUS_KEY = "po-computer-use";
19
- const COMPUTER_USE_CONFIRMATION_WINDOW_MS = 12e4;
20
- /**
21
- * Every path this API answers on, below its mount.
22
- *
23
- * The typed route table in `./apiRoutes` is built from this, the dispatcher
24
- * reads that table, and the hub channel addresses the broker with these same
25
- * strings, so a route cannot move on one side alone.
26
- */
27
- const COMPUTER_USE_ROUTES = {
28
- activate: "/activate",
29
- artifact: "/artifact",
30
- agentState: "/agent/state",
31
- agentObserve: "/agent/observe",
32
- agentAction: "/agent/action",
33
- agentStop: "/agent/stop",
34
- hubState: "/hub/state",
35
- hubActivation: "/hub/activation",
36
- hubAuthorization: "/hub/authorization",
37
- hubNext: "/hub/next",
38
- hubComplete: "/hub/complete",
39
- hubStop: "/hub/stop"
40
- };
41
- const COMPUTER_USE_WAKE_LIMIT = 1e6;
42
- //#endregion
43
14
  //#region src/services/mcpTools/index.ts
44
15
  const COMPUTER_USE_MCP_TOOLS_SERVICE = "po/computer-use-mcp-tools";
45
16
  function mountMcpTools(tools) {
@@ -81,6 +52,176 @@ function modeState(state, enabled = false) {
81
52
  };
82
53
  }
83
54
  //#endregion
55
+ //#region src/services/computerNamespace/index.ts
56
+ const NOT_ACTIVE$1 = "Computer use is not active for this session.";
57
+ const DECLARATIONS = `declare const computer: {
58
+ /**
59
+ * Read-only. Observes the authorized window or whole desktop. A screenshot is shown to the model unless includeScreenshot is false.
60
+ * save: true also keeps the screenshot in session artifacts and returns its path as screenshotArtifact.
61
+ * root narrows to one subtree (an element ref, or on the desktop 'dock', 'menubar' or a window root id).
62
+ * label (substring, any case) and role (exact, e.g. 'AXButton') filter elements.
63
+ * offset/limit page through matches; pass nextOffset back while it is present.
64
+ */
65
+ state(options?: {
66
+ includeScreenshot?: boolean;
67
+ save?: boolean;
68
+ root?: string;
69
+ label?: string;
70
+ role?: string;
71
+ offset?: number;
72
+ limit?: number;
73
+ }): Promise<Record<string, unknown>>;
74
+ /**
75
+ * Changes the application. One semantic action using ids from the latest state().
76
+ * set_value accepts {{ env.NAME }} or {{ secrets.NAME }}. Secrets need an approved single-window app and seal observations.
77
+ * perform runs one of the element's nativeActions, such as 'AXShowMenu'.
78
+ * launch opens an installed app by bundle id or name on a whole-desktop grant; it needs no snapshot.
79
+ */
80
+ act(
81
+ action:
82
+ | {
83
+ kind: 'press' | 'focus' | 'set_value' | 'scroll' | 'perform';
84
+ snapshotId: string;
85
+ elementRef: string;
86
+ value?: string;
87
+ direction?: 'up' | 'down' | 'left' | 'right';
88
+ amount?: 'line' | 'page';
89
+ action?: string;
90
+ }
91
+ | { kind: 'launch'; app: string },
92
+ ): Promise<Record<string, unknown>>;
93
+ /** Changes the application. Runs an allowlisted script with only the authorized program API. No screenshot unless asked. */
94
+ run(options: { scriptPath: string; input: unknown; trusted?: boolean; includeScreenshot?: boolean }): Promise<Record<string, unknown>>;
95
+ /** Ends the current grant. It never activates anything or changes settings. */
96
+ stop(): Promise<{ phase: string }>;
97
+ };`;
98
+ /** Detached JSON: screenshots (base64) never travel through the return value. */
99
+ function detach(value) {
100
+ return JSON.parse(JSON.stringify(value ?? null, (key, entry) => key === "screenshot" ? void 0 : entry) ?? "null");
101
+ }
102
+ function plain(value, member, allowed) {
103
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`computer.${member} expects an object.`);
104
+ const unknown = Object.keys(value).find((key) => !allowed.includes(key));
105
+ if (unknown !== void 0) throw new TypeError(`computer.${member} does not accept "${unknown}".`);
106
+ return value;
107
+ }
108
+ function optionalBoolean(options, member, key) {
109
+ const value = options[key];
110
+ if (value !== void 0 && typeof value !== "boolean") throw new TypeError(`computer.${member} ${key} must be a boolean.`);
111
+ return value;
112
+ }
113
+ function failureMessage(details) {
114
+ if (typeof details === "string") return details;
115
+ const failure = details ?? {};
116
+ const message = typeof failure.error === "string" ? failure.error : "Computer use failed.";
117
+ return failure.completedActions === void 0 ? message : `${message} (completedActions: ${JSON.stringify(failure.completedActions)}, outcomeUncertain: ${String(failure.outcomeUncertain)})`;
118
+ }
119
+ function createComputerNamespace(deps) {
120
+ return {
121
+ name: "computer",
122
+ summary: "Observe and act on the application window, or the whole desktop, the person authorized through Po Desktop: state, act, run an allowlisted script, stop. Exists only while that grant is active.",
123
+ declarations: DECLARATIONS,
124
+ bind(run) {
125
+ const guard = () => {
126
+ if (run.sessionId !== deps.sessionId) throw new Error("Computer use belongs to another session.");
127
+ run.signal.throwIfAborted();
128
+ deps.lifetime.throwIfAborted();
129
+ if (!deps.isActive()) throw new Error(NOT_ACTIVE$1);
130
+ return AbortSignal.any([run.signal, deps.lifetime]);
131
+ };
132
+ const finish = (member, tool, args, started, result) => {
133
+ const details = detach(result.details);
134
+ const ok = result.isError !== true;
135
+ run.record?.({
136
+ name: `computer.${member}`,
137
+ tool,
138
+ args: detach(args),
139
+ ok,
140
+ ms: Date.now() - started,
141
+ ...ok ? {} : { error: failureMessage(details).slice(0, 512) },
142
+ result: {
143
+ content: result.content.filter((block) => block.type === "text"),
144
+ details
145
+ }
146
+ });
147
+ if (!ok) throw new Error(failureMessage(details));
148
+ const warnings = [];
149
+ for (const block of result.content) {
150
+ if (block.type !== "image") continue;
151
+ const shown = run.emitImage?.({
152
+ data: block.data,
153
+ mimeType: block.mimeType
154
+ });
155
+ if (shown?.emitted !== true) warnings.push(shown?.warning ?? "Image not shown to the model: this host cannot show images.");
156
+ }
157
+ return warnings.length > 0 ? {
158
+ ...details,
159
+ warning: warnings.join(" ")
160
+ } : details;
161
+ };
162
+ const call = async (member, tool, args, operation) => {
163
+ const signal = guard();
164
+ return finish(member, tool, args, Date.now(), await operation(signal));
165
+ };
166
+ return Object.assign(Object.create(null), {
167
+ state: async (options) => {
168
+ const parsed = options === void 0 ? {} : plain(options, "state", [
169
+ "includeScreenshot",
170
+ "save",
171
+ "root",
172
+ "label",
173
+ "role",
174
+ "offset",
175
+ "limit"
176
+ ]);
177
+ const includeScreenshot = optionalBoolean(parsed, "state", "includeScreenshot");
178
+ const saveScreenshot = optionalBoolean(parsed, "state", "save");
179
+ const { save: _save, includeScreenshot: _include, ...query } = parsed;
180
+ const args = {
181
+ ...query,
182
+ ...includeScreenshot === void 0 ? {} : { includeScreenshot },
183
+ ...saveScreenshot === void 0 ? {} : { saveScreenshot }
184
+ };
185
+ return call("state", "computer_state", args, (signal) => deps.operations.state(args, signal));
186
+ },
187
+ act: async (action) => {
188
+ const parsed = plain(action, "act", [
189
+ "kind",
190
+ "snapshotId",
191
+ "elementRef",
192
+ "value",
193
+ "direction",
194
+ "amount",
195
+ "action",
196
+ "app"
197
+ ]);
198
+ return call("act", "computer_action", parsed, (signal) => deps.operations.act(parsed, signal));
199
+ },
200
+ run: async (options) => {
201
+ const parsed = plain(options, "run", [
202
+ "scriptPath",
203
+ "input",
204
+ "trusted",
205
+ "includeScreenshot"
206
+ ]);
207
+ if (typeof parsed.scriptPath !== "string" || parsed.scriptPath.length === 0) throw new TypeError("computer.run scriptPath must be a non-empty string.");
208
+ if (!("input" in parsed)) throw new TypeError("computer.run requires input.");
209
+ const trusted = optionalBoolean(parsed, "run", "trusted");
210
+ const includeScreenshot = optionalBoolean(parsed, "run", "includeScreenshot");
211
+ const args = {
212
+ scriptPath: parsed.scriptPath,
213
+ input: parsed.input,
214
+ trusted,
215
+ includeScreenshot
216
+ };
217
+ return call("run", "computer_exec", args, (signal) => deps.operations.run(args, signal));
218
+ },
219
+ stop: async () => detach(await deps.operations.stop(guard()))
220
+ });
221
+ }
222
+ };
223
+ }
224
+ //#endregion
84
225
  //#region src/services/computerToolOutput/index.ts
85
226
  const MAX_TEXT_BYTES = 262144;
86
227
  const MAX_IMAGE_DATA_LENGTH = 8388608;
@@ -142,486 +283,117 @@ function computerScriptFailure(error) {
142
283
  };
143
284
  }
144
285
  //#endregion
145
- //#region src/types/apiRoutes.ts
146
- /**
147
- * This package's routes, as data.
148
- *
149
- * No scope and no base path: the build reads both off
150
- * `src/extensions/workspaces/sessions/(backend)/api/computer-use/`, so the
151
- * mount is stated once, by the folder that creates it.
152
- *
153
- * The paths come from `COMPUTER_USE_ROUTES` rather than being written out
154
- * again. That table already addressed the broker from the hub channel and from
155
- * the broker's own dispatcher, and a second copy here is exactly the
156
- * disagreement this file exists to prevent. The dispatcher now reads this
157
- * table, so the page, the broker and the hub all resolve one set of strings.
158
- *
159
- * Activation, status, cancellation and recording reads are reachable from a browser. The `/agent/` and `/hub/` routes
160
- * each demand a host-issued bearer token and answer 404 without one; they are
161
- * declared here because they are this API's surface, not because a page calls
162
- * them.
163
- */
164
- var apiRoutes_default = (0, _agimon_ai_po_core_web.defineApiRoutes)({
165
- artifact: {
166
- method: "GET",
167
- path: COMPUTER_USE_ROUTES.artifact,
168
- query: ["artifactId", "offset"],
169
- raw: true
170
- },
171
- activationState: {
172
- method: "GET",
173
- path: COMPUTER_USE_ROUTES.activate,
174
- response: (0, _agimon_ai_po_core_web.apiResponse)()
175
- },
176
- cancelActivation: {
177
- method: "DELETE",
178
- path: COMPUTER_USE_ROUTES.activate,
179
- response: (0, _agimon_ai_po_core_web.apiResponse)()
180
- },
181
- activate: {
182
- method: "POST",
183
- path: COMPUTER_USE_ROUTES.activate,
184
- response: (0, _agimon_ai_po_core_web.apiResponse)()
185
- },
186
- agentState: {
187
- method: "GET",
188
- path: COMPUTER_USE_ROUTES.agentState,
189
- response: (0, _agimon_ai_po_core_web.apiResponse)()
190
- },
191
- /** Answers whatever the admitted Desktop provider returned, which is runtime-defined JSON. */
192
- agentObserve: {
193
- method: "POST",
194
- path: COMPUTER_USE_ROUTES.agentObserve,
195
- response: (0, _agimon_ai_po_core_web.apiResponse)()
196
- },
197
- agentAction: {
198
- method: "POST",
199
- path: COMPUTER_USE_ROUTES.agentAction,
200
- response: (0, _agimon_ai_po_core_web.apiResponse)()
201
- },
202
- agentStop: {
203
- method: "POST",
204
- path: COMPUTER_USE_ROUTES.agentStop,
205
- response: (0, _agimon_ai_po_core_web.apiResponse)()
206
- },
207
- hubState: {
208
- method: "GET",
209
- path: COMPUTER_USE_ROUTES.hubState,
210
- response: (0, _agimon_ai_po_core_web.apiResponse)()
211
- },
212
- /** Null until a reader has confirmed one; reading it moves the session to `activating`. */
213
- hubActivation: {
214
- method: "GET",
215
- path: COMPUTER_USE_ROUTES.hubActivation,
216
- response: (0, _agimon_ai_po_core_web.apiResponse)()
217
- },
218
- hubAuthorization: {
219
- method: "GET",
220
- path: COMPUTER_USE_ROUTES.hubAuthorization,
221
- response: (0, _agimon_ai_po_core_web.apiResponse)()
222
- },
223
- hubNext: {
224
- method: "GET",
225
- path: COMPUTER_USE_ROUTES.hubNext,
226
- response: (0, _agimon_ai_po_core_web.apiResponse)()
227
- },
228
- hubComplete: {
229
- method: "POST",
230
- path: COMPUTER_USE_ROUTES.hubComplete,
231
- response: (0, _agimon_ai_po_core_web.apiResponse)()
232
- },
233
- hubStop: {
234
- method: "POST",
235
- path: COMPUTER_USE_ROUTES.hubStop,
236
- response: (0, _agimon_ai_po_core_web.apiResponse)()
237
- }
238
- });
239
- //#endregion
240
- //#region src/services/computerUseApi/index.ts
241
- function jsonError(message, status) {
242
- return Response.json({ error: message }, { status });
243
- }
244
- function record$1(value) {
245
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
246
- }
247
- async function body(request) {
248
- try {
249
- return record$1(await request.json()) ?? {};
250
- } catch {
251
- return {};
252
- }
253
- }
254
- function semanticAction(value) {
255
- if (!(typeof value.snapshotId === "string" && value.snapshotId.length > 0 && typeof value.elementRef === "string" && value.elementRef.length > 0)) return false;
256
- const allowed = (keys) => Object.keys(value).every((key) => keys.includes(key));
257
- if (value.kind === "press" || value.kind === "focus") return allowed([
258
- "kind",
259
- "snapshotId",
260
- "elementRef"
261
- ]);
262
- if (value.kind === "set_value") return typeof value.value === "string" && allowed([
263
- "kind",
264
- "snapshotId",
265
- "elementRef",
266
- "value"
267
- ]);
268
- if (value.kind === "scroll") return [
269
- "up",
270
- "down",
271
- "left",
272
- "right"
273
- ].includes(value.direction) && (value.amount === "line" || value.amount === "page") && allowed([
274
- "kind",
275
- "snapshotId",
276
- "elementRef",
277
- "direction",
278
- "amount"
279
- ]);
280
- return false;
281
- }
282
- function artifactView(value) {
283
- const input = record$1(value);
284
- if (typeof input?.artifactId !== "string" || input.status !== "ready" && input.status !== "failed") return void 0;
285
- const safeUrl = (candidate) => typeof candidate === "string" && candidate.startsWith("/api/") ? candidate : void 0;
286
- const downloadUrl = safeUrl(input.downloadUrl);
287
- const previewUrl = safeUrl(input.previewUrl);
288
- const artifactFailure = record$1(input.failure);
289
- const safeFailure = typeof artifactFailure?.code === "string" && typeof artifactFailure.message === "string" ? {
290
- code: artifactFailure.code.slice(0, 128),
291
- message: artifactFailure.message.slice(0, 512)
292
- } : void 0;
293
- return {
294
- artifactId: input.artifactId,
295
- status: input.status,
296
- ...typeof input.sizeBytes === "number" && Number.isSafeInteger(input.sizeBytes) && input.sizeBytes > 0 ? { sizeBytes: input.sizeBytes } : {},
297
- ...downloadUrl === void 0 ? {} : { downloadUrl },
298
- ...previewUrl === void 0 ? {} : { previewUrl },
299
- ...typeof input.actionCount === "number" ? { actionCount: input.actionCount } : {},
300
- ...typeof input.completedAt === "string" ? { completedAt: input.completedAt } : {},
301
- ...safeFailure === void 0 ? {} : { failure: safeFailure }
302
- };
286
+ //#region src/services/computerUseArtifacts/index.ts
287
+ const PNG_SIGNATURE = Buffer.from([
288
+ 137,
289
+ 80,
290
+ 78,
291
+ 71,
292
+ 13,
293
+ 10,
294
+ 26,
295
+ 10
296
+ ]);
297
+ const MAX_SCREENSHOT_BYTES = 8388608;
298
+ const SAFE_SEGMENT = /^[A-Za-z0-9_-]{1,128}$/u;
299
+ function stamp() {
300
+ return `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/gu, "-")}-${(0, node_crypto.randomUUID)().slice(0, 8)}`;
303
301
  }
304
- var ComputerUseRequestBroker = class ComputerUseRequestBroker {
305
- sessionId;
306
- internalToken;
307
- hubToken;
308
- directEvents;
309
- requestTimeoutMs;
310
- revision = 0;
311
- wake = 0;
312
- phase = "inactive";
313
- activation;
314
- grantId;
315
- expiresAt;
316
- actionSequence = 0;
317
- expiryTimer;
318
- failure;
319
- artifact;
320
- pending;
321
- closed = false;
322
- desktop;
323
- beforeActivate;
324
- listeners = /* @__PURE__ */ new Set();
325
- unsubscribeDesktop;
326
- static DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
327
- constructor(options) {
328
- this.sessionId = options.sessionId ?? "unknown";
329
- this.internalToken = options.internalToken;
330
- this.hubToken = options.hubToken;
331
- this.directEvents = options.directEvents;
332
- this.requestTimeoutMs = options.requestTimeoutMs ?? ComputerUseRequestBroker.DEFAULT_REQUEST_TIMEOUT_MS;
333
- this.desktop = options.desktop;
334
- this.beforeActivate = options.beforeActivate;
335
- this.unsubscribeDesktop = options.desktop?.subscribe(() => {
336
- clearTimeout(this.expiryTimer);
337
- if (!options.desktop?.available) {
338
- this.rejectPending("Desktop disconnected.");
339
- this.phase = "failed";
340
- this.grantId = void 0;
341
- this.failure = {
342
- code: "desktop_unavailable",
343
- message: "Desktop disconnected."
344
- };
345
- } else if (this.phase !== "inactive" && this.phase !== "failed") {
346
- this.phase = "stopping";
347
- this.rejectPending("Control was stopped by Desktop.");
348
- }
349
- this.changed();
350
- });
351
- }
352
- state() {
353
- return Object.freeze({
354
- sessionId: this.sessionId,
355
- revision: this.revision,
356
- wake: this.wake,
357
- phase: this.phase,
358
- ...this.activation === void 0 ? {} : {
359
- requestId: this.activation.requestId,
360
- target: this.activation.target,
361
- durationMs: this.activation.durationSeconds * 1e3
362
- },
363
- ...this.expiresAt === void 0 ? {} : { expiresAt: this.expiresAt },
364
- ...this.failure === void 0 ? {} : { failure: this.failure },
365
- ...this.artifact === void 0 ? {} : { artifact: this.artifact }
366
- });
367
- }
368
- /** Tools and the API share this broker. No socket, credential discovery, or second state store. */
369
- sessionClient() {
370
- const result = async (response) => {
371
- const value = await response.json();
372
- if (!response.ok) throw new Error(value.error ?? `Computer-use request failed (${response.status}).`);
373
- return value;
374
- };
375
- const requireDesktop = () => {
376
- if (this.closed || !this.desktop?.available || this.desktop.enabled === false) throw new Error("Desktop computer use is unavailable.");
377
- };
378
- return {
379
- state: async () => this.state(),
380
- subscribeStatus: (listener) => {
381
- this.listeners.add(listener);
382
- return () => {
383
- this.listeners.delete(listener);
384
- };
385
- },
386
- observe: async (signal, options = {}) => {
387
- requireDesktop();
388
- return result(await this.enqueue("observe", options, signal));
389
- },
390
- act: async (action, signal) => {
391
- requireDesktop();
392
- if (!semanticAction(action)) throw new Error("A valid semantic action is required.");
393
- return result(await this.enqueue("act", action, signal));
394
- },
395
- stop: async (signal) => {
396
- signal?.throwIfAborted();
397
- if (this.phase !== "inactive" && this.phase !== "failed") {
398
- this.phase = "stopping";
399
- this.rejectPending("Computer use was stopped.");
400
- this.changed();
401
- }
402
- return this.state();
302
+ /** One queue per session. Callers pass bytes or a host-bound recording, never a filesystem location. */
303
+ function createComputerUseArtifacts(sessionId, environment, binding, mountSignal) {
304
+ let pending = Promise.resolve();
305
+ const enqueue = (segments, write, requestSignal) => {
306
+ const run = pending.catch(() => void 0).then(async () => {
307
+ const active = binding();
308
+ if (!active) throw new Error("Session artifacts are unavailable.");
309
+ const signal = AbortSignal.any([
310
+ mountSignal,
311
+ active.signal,
312
+ ...requestSignal ? [requestSignal] : []
313
+ ]);
314
+ const context = (0, _agimon_ai_po_core_platform.withAbortSignal)(signal, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT);
315
+ const { fs, storage } = active;
316
+ const check = () => {
317
+ signal.throwIfAborted();
318
+ if (binding() !== active) throw new Error("Session artifact storage changed.");
319
+ };
320
+ const safeDirectory = async (path) => {
321
+ const absolute = (0, node_path.resolve)(path);
322
+ if ((0, _agimon_ai_po_core_platform.getOrThrow)(await fs.fileInfo(absolute, context)).kind !== "directory" || (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.canonicalPath(absolute, context)) !== absolute) throw new Error("Unsafe artifact directory.");
323
+ };
324
+ check();
325
+ const root = await storage.rootForSession(sessionId, environment);
326
+ check();
327
+ if (!root) throw new Error("Session artifacts are unavailable.");
328
+ await safeDirectory(root);
329
+ const folders = [root];
330
+ for (const segment of [require_extensionService.COMPUTER_USE_ARTIFACT_DIRECTORY, ...segments]) {
331
+ const directory = (0, node_path.join)(folders.at(-1), segment);
332
+ const info = await fs.fileInfo(directory, context);
333
+ if (!info.ok && info.error.code === "not_found") (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.createDir(directory, void 0, context));
334
+ else (0, _agimon_ai_po_core_platform.getOrThrow)(info);
335
+ await safeDirectory(directory);
336
+ folders.push(directory);
403
337
  }
404
- };
405
- }
406
- changed() {
407
- this.revision += 1;
408
- this.wake = (this.wake + 1) % COMPUTER_USE_WAKE_LIMIT;
409
- const state = this.state();
410
- for (const listener of this.listeners) listener(state);
411
- this.directEvents.publish(computerUseChannelType, this.sessionId, state);
412
- }
413
- authorized(request, token) {
414
- return token !== void 0 && request.headers.get("authorization") === `Bearer ${token}`;
415
- }
416
- async requestActivation(request) {
417
- if (!this.desktop?.available || !(this.desktop.authorizeActivation?.(request.headers) ?? this.desktop.authorize(request.headers))) return jsonError("Not found.", 404);
418
- if (this.desktop.enabled === false) return jsonError("Enable computer use in global Desktop settings first.", 409);
419
- const stamped = (0, _agimon_ai_po_core_packageApi.poApiCallerFrom)(request.headers);
420
- const caller = stamped?.locality === "remote" ? stamped : {
421
- locality: "local",
422
- stepUp: "not-required"
423
- };
424
- if (this.phase !== "inactive" && this.phase !== "failed") return jsonError("Computer use is already busy.", 409);
425
- const input = await body(request);
426
- const target = record$1(input.target);
427
- const durationMs = input.durationMs;
428
- if (target === void 0 && (input.target !== void 0 || caller.locality !== "remote") || target !== void 0 && (typeof target.windowId !== "string" || typeof target.bundleId !== "string")) return jsonError("A Desktop target is required, or a remote request must leave selection to the Mac.", 400);
429
- if (typeof durationMs !== "number" || !Number.isInteger(durationMs) || durationMs < 1e3 || durationMs > 18e5) return jsonError("The requested duration is invalid.", 400);
430
- try {
431
- this.desktop.claim(request.headers);
432
- await this.beforeActivate?.();
433
- } catch (error) {
434
- return jsonError(error instanceof Error ? error.message : String(error), 409);
435
- }
436
- if (this.closed || !this.desktop.available || this.phase !== "inactive" && this.phase !== "failed") return jsonError("Computer use is unavailable or already busy.", 409);
437
- const createdAt = Date.now();
438
- this.activation = Object.freeze({
439
- requestId: (0, node_crypto.randomUUID)(),
440
- ...target === void 0 ? {} : { target: Object.freeze({ ...target }) },
441
- durationSeconds: durationMs / 1e3,
442
- createdAt,
443
- confirmationExpiresAt: createdAt + COMPUTER_USE_CONFIRMATION_WINDOW_MS,
444
- caller: Object.freeze({ ...caller })
445
- });
446
- this.phase = "awaiting_confirmation";
447
- this.failure = void 0;
448
- this.artifact = void 0;
449
- this.changed();
450
- return Response.json(this.state(), { status: 202 });
451
- }
452
- rejectPending(message) {
453
- const pending = this.pending;
454
- if (pending === void 0) return;
455
- this.pending = void 0;
456
- pending.dispose();
457
- pending.reject(new Error(message));
458
- }
459
- stopAfterUncertainRequest(message) {
460
- if (this.phase === "active") {
461
- this.phase = "stopping";
462
- this.changed();
463
- }
464
- this.rejectPending(message);
465
- }
466
- async enqueue(operation, payload, signal) {
467
- if (this.phase !== "active" || this.grantId === void 0) return jsonError("Computer use is not active.", 409);
468
- if (this.pending !== void 0) return jsonError("Another computer-use request is live.", 409);
469
- if (signal?.aborted === true) return jsonError("The computer-use request was cancelled.", 499);
470
- const sequence = operation === "act" ? ++this.actionSequence : void 0;
471
- const request = {
472
- id: (0, node_crypto.randomUUID)(),
473
- operation,
474
- grantId: this.grantId,
475
- ...sequence === void 0 ? {} : { sequence },
476
- ...payload === void 0 ? {} : { payload }
477
- };
478
- const completion = new Promise((resolve, reject) => {
479
- const onAbort = () => this.stopAfterUncertainRequest("The computer-use request was cancelled.");
480
- const timer = setTimeout(() => this.stopAfterUncertainRequest("The computer-use request timed out."), this.requestTimeoutMs);
481
- timer.unref?.();
482
- signal?.addEventListener("abort", onAbort, { once: true });
483
- this.pending = {
484
- request,
485
- resolve,
486
- reject,
487
- dispose: () => {
488
- clearTimeout(timer);
489
- signal?.removeEventListener("abort", onAbort);
338
+ return write({
339
+ fs,
340
+ context,
341
+ relative: [require_extensionService.COMPUTER_USE_ARTIFACT_DIRECTORY, ...segments].join("/"),
342
+ directory: folders.at(-1),
343
+ check,
344
+ recheck: async () => {
345
+ for (const folder of folders) await safeDirectory(folder);
490
346
  }
491
- };
347
+ });
492
348
  });
493
- this.changed();
349
+ pending = run;
350
+ return run;
351
+ };
352
+ /** Writes `.<name>.tmp`, which the artifact list skips, then renames it into place. */
353
+ const place = async (target, name, fill) => {
354
+ const { fs, context, directory } = target;
355
+ const temporary = (0, node_path.join)(directory, `.${name}.tmp`);
356
+ const destination = (0, node_path.join)(directory, name);
357
+ if ((0, _agimon_ai_po_core_platform.getOrThrow)(await fs.exists(temporary, context)) || (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.exists(destination, context))) throw new Error("Artifact filename is already in use.");
494
358
  try {
495
- return Response.json(await completion);
496
- } catch (error) {
497
- return jsonError(error instanceof Error ? error.message : String(error), 502);
498
- }
499
- }
500
- async fetch(request) {
501
- if (this.closed) return jsonError("Computer-use broker is closed.", 503);
502
- const url = new URL(request.url);
503
- const path = url.pathname;
504
- if (request.method === "GET" && path === apiRoutes_default.artifact.path) {
505
- if (!(this.desktop?.authorizeRecording?.(request.headers) ?? this.desktop?.authorize(request.headers)) || !this.desktop?.fetchRecording) return jsonError("Not found.", 404);
506
- const artifactId = url.searchParams.get("artifactId") ?? "";
507
- const offsetText = url.searchParams.get("offset") ?? "";
508
- const offset = Number(offsetText);
509
- if (!/^[0-9]+$/u.test(offsetText) || !Number.isSafeInteger(offset) || offset < 0 || offset > 134217728) return jsonError("Invalid recording offset.", 400);
510
- return this.desktop.fetchRecording(artifactId, `bytes=${offset}-${offset + 1048576 - 1}`);
359
+ target.check();
360
+ await fill(temporary);
361
+ await target.recheck();
362
+ target.check();
363
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.renameFile(temporary, destination, context));
364
+ return `artifact:${target.relative}/${name}`;
365
+ } finally {
366
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.remove(temporary, { force: true }, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT));
511
367
  }
512
- if (path === apiRoutes_default.activate.path && request.method === "GET") {
513
- if (!this.desktop?.authorizePending?.(request.headers) && !(this.desktop?.authorizeRecording?.(request.headers) ?? this.desktop?.authorize(request.headers))) return jsonError("Not found.", 404);
514
- return Response.json(this.state());
515
- }
516
- if (path === apiRoutes_default.activate.path && request.method === "DELETE") {
517
- if (!this.desktop?.authorizePending?.(request.headers)) return jsonError("Not found.", 404);
518
- if (this.phase !== "awaiting_confirmation" && this.phase !== "activating") return jsonError("No activation is pending.", 409);
519
- this.phase = "stopping";
520
- this.rejectPending("The activation was cancelled.");
521
- this.changed();
522
- return Response.json(this.state(), { status: 202 });
523
- }
524
- if (request.method === "POST" && path === apiRoutes_default.activate.path) return this.requestActivation(request);
525
- const agent = path.startsWith("/agent/");
526
- const hub = path.startsWith("/hub/");
527
- if (agent && !this.authorized(request, this.internalToken) || hub && !this.authorized(request, this.hubToken)) return jsonError("Not found.", 404);
528
- if (request.method === "GET" && (path === apiRoutes_default.agentState.path || path === apiRoutes_default.hubState.path)) return Response.json(this.state());
529
- if (request.method === "POST" && path === apiRoutes_default.agentObserve.path) return this.enqueue("observe", void 0, request.signal);
530
- if (request.method === "POST" && path === apiRoutes_default.agentAction.path) {
531
- const action = await body(request);
532
- if (!semanticAction(action)) return jsonError("A valid semantic action is required.", 400);
533
- return this.enqueue("act", action, request.signal);
534
- }
535
- if (request.method === "POST" && path === apiRoutes_default.agentStop.path) {
536
- if (this.phase !== "active") return jsonError("Computer use is not active.", 409);
537
- this.phase = "stopping";
538
- this.rejectPending("The computer-use request was stopped.");
539
- this.changed();
540
- return Response.json(this.state(), { status: 202 });
541
- }
542
- if (request.method === "GET" && path === apiRoutes_default.hubActivation.path) {
543
- if (this.activation === void 0 || this.phase !== "awaiting_confirmation") return Response.json(null);
544
- this.phase = "activating";
545
- this.changed();
546
- return Response.json(this.activation);
547
- }
548
- if (request.method === "GET" && path === apiRoutes_default.hubAuthorization.path) return Response.json(this.grantId === void 0 ? null : {
549
- grantId: this.grantId,
550
- expiresAt: this.expiresAt
551
- });
552
- if (request.method === "GET" && path === apiRoutes_default.hubNext.path) return Response.json(this.pending?.request ?? null);
553
- if (request.method === "POST" && path === apiRoutes_default.hubComplete.path) {
554
- const input = await body(request);
555
- const id = typeof input.id === "string" ? input.id : void 0;
556
- if (this.pending === void 0 || this.pending.request.id !== id) return jsonError("The request is stale.", 409);
557
- const pending = this.pending;
558
- this.pending = void 0;
559
- pending.dispose();
560
- if (typeof input.error === "string") {
561
- this.phase = "stopping";
562
- pending.reject(new Error(input.error));
563
- } else pending.resolve(input.result);
564
- this.changed();
565
- return Response.json(this.state());
566
- }
567
- if (request.method === "POST" && path === apiRoutes_default.hubStop.path) {
568
- const input = await body(request);
569
- if (this.phase === "activating") {
570
- if (typeof input.error === "string") {
571
- this.phase = "failed";
572
- this.failure = {
573
- code: "desktop_unavailable",
574
- message: input.error.slice(0, 512)
575
- };
576
- this.activation = void 0;
577
- } else {
578
- const host = record$1(input.host);
579
- if (typeof host?.grantId !== "string" || !Number.isFinite(host.expiresAt) || host.expiresAt <= Date.now()) return jsonError("Desktop did not issue a complete grant.", 502);
580
- const selectedTarget = record$1(host.target);
581
- if (this.activation !== void 0 && selectedTarget !== void 0) this.activation = Object.freeze({
582
- ...this.activation,
583
- target: Object.freeze({ ...selectedTarget })
584
- });
585
- this.grantId = host.grantId;
586
- this.expiresAt = host.expiresAt;
587
- this.actionSequence = 0;
588
- this.phase = "active";
589
- clearTimeout(this.expiryTimer);
590
- this.expiryTimer = setTimeout(() => {
591
- if (this.closed || this.phase !== "active") return;
592
- this.phase = "stopping";
593
- this.rejectPending("The computer-use grant expired.");
594
- this.changed();
595
- }, Math.max(0, this.expiresAt - Date.now()));
596
- this.expiryTimer.unref?.();
368
+ };
369
+ return {
370
+ /** Saves one observation screenshot (base64 PNG) under its run folder and returns its `artifact:` path. */
371
+ saveScreenshot(data, runId, signal) {
372
+ if (!SAFE_SEGMENT.test(runId)) return Promise.reject(/* @__PURE__ */ new Error("The computer-use run id is invalid."));
373
+ const bytes = Buffer.from(data, "base64");
374
+ if (bytes.length <= PNG_SIGNATURE.length || bytes.length > MAX_SCREENSHOT_BYTES || !bytes.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) return Promise.reject(/* @__PURE__ */ new Error("The screenshot is not a PNG within the size limit."));
375
+ return enqueue([runId], (target) => place(target, `screenshot-${stamp()}.png`, async (temporary) => {
376
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await target.fs.writeFile(temporary, bytes, target.context));
377
+ }), signal);
378
+ },
379
+ /** Copies a finished recording in the host store's own bounded ranges and returns its `artifact:` path. */
380
+ saveRecording(source, signal) {
381
+ const size = source.sizeBytes;
382
+ if (!Number.isSafeInteger(size) || size < 1 || size > 134217728) return Promise.reject(/* @__PURE__ */ new Error("The recording exceeds the permitted size."));
383
+ return enqueue([], (target) => place(target, `recording-${stamp()}.mp4`, async (temporary) => {
384
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await target.fs.writeFile(temporary, /* @__PURE__ */ new Uint8Array(), target.context));
385
+ for (let offset = 0; offset < size; offset += require_extensionService.COMPUTER_USE_RECORDING_CHUNK_BYTES) {
386
+ target.check();
387
+ const end = Math.min(offset + require_extensionService.COMPUTER_USE_RECORDING_CHUNK_BYTES, size) - 1;
388
+ const response = await source.read(`bytes=${offset}-${end}`);
389
+ if (response.status !== 206 || response.headers.get("content-range") !== `bytes ${offset}-${end}/${size}`) throw new Error("The recording is unavailable or changed.");
390
+ const bytes = new Uint8Array(await response.arrayBuffer());
391
+ if (bytes.byteLength !== end - offset + 1) throw new Error("The recording response is incomplete.");
392
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await target.fs.appendFile(temporary, bytes, target.context));
597
393
  }
598
- } else {
599
- clearTimeout(this.expiryTimer);
600
- this.rejectPending("The computer-use session stopped.");
601
- this.phase = "inactive";
602
- this.grantId = void 0;
603
- this.expiresAt = void 0;
604
- this.activation = void 0;
605
- this.artifact = artifactView(input.artifact) ?? this.artifact;
606
- }
607
- this.changed();
608
- return Response.json(this.state());
394
+ }), signal);
609
395
  }
610
- return jsonError("Not found.", 404);
611
- }
612
- close() {
613
- if (this.closed) return;
614
- this.closed = true;
615
- clearTimeout(this.expiryTimer);
616
- this.unsubscribeDesktop?.();
617
- this.listeners.clear();
618
- this.rejectPending("Computer-use broker closed.");
619
- this.grantId = void 0;
620
- this.expiresAt = void 0;
621
- }
622
- };
623
- function createComputerUseApi(options) {
624
- return new ComputerUseRequestBroker(options);
396
+ };
625
397
  }
626
398
  //#endregion
627
399
  //#region src/services/computerUseServer/index.ts
@@ -629,6 +401,7 @@ function createComputerUseApi(options) {
629
401
  const SOURCE = "@agimon-ai/po-computer-use";
630
402
  const SCRIPT_PATHS_ENV = "PO_COMPUTER_USE_SCRIPT_PATHS";
631
403
  const GUIDANCE = "[COMPUTER USE ACTIVE]\nUse computer_state 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.";
404
+ const NOT_ACTIVE = "Computer use is not active for this session.";
632
405
  function output(value, isError = false) {
633
406
  return {
634
407
  content: [{
@@ -645,12 +418,14 @@ function createComputerUseServer(host, apiContext) {
645
418
  commands: []
646
419
  };
647
420
  const desktop = apiContext.computerUse;
648
- const broker = createComputerUseApi({
421
+ let profileRuntime;
422
+ const broker = require_extensionService.createComputerUseApi({
649
423
  sessionId: host.context.sessionId,
650
424
  internalToken: apiContext.internalToken,
651
425
  hubToken: apiContext.hubToken,
652
426
  directEvents: apiContext.directEvents,
653
427
  desktop,
428
+ profileRuntime: () => profileRuntime,
654
429
  beforeActivate: async () => {
655
430
  if (!modeSelected()) throw new Error("Enable computer use before authorizing an application.");
656
431
  const activity = await host.context.session.activity();
@@ -670,22 +445,48 @@ function createComputerUseServer(host, apiContext) {
670
445
  };
671
446
  let state = broker.state();
672
447
  const restrictionListeners = /* @__PURE__ */ new Set();
448
+ let codemodeLive = false;
673
449
  let stopActivity;
674
450
  let modeOwner;
675
- const modeSelected = () => (host.context.selection.state?.["minor-mode"] ?? []).includes(COMPUTER_USE_MODE_ID);
451
+ const lifetime = new AbortController();
452
+ let artifactBinding;
453
+ const artifacts = createComputerUseArtifacts(host.context.sessionId, host.context.environment ?? {}, () => artifactBinding, lifetime.signal);
454
+ const savedRecordings = /* @__PURE__ */ new Set();
455
+ const saveRecording = (artifact) => {
456
+ const fetchRecording = desktop.fetchRecording?.bind(desktop);
457
+ if (artifact?.status !== "ready" || !artifact.sizeBytes || !fetchRecording || savedRecordings.has(artifact.artifactId)) return;
458
+ savedRecordings.add(artifact.artifactId);
459
+ const { artifactId, sizeBytes } = artifact;
460
+ artifacts.saveRecording({
461
+ artifactId,
462
+ sizeBytes,
463
+ read: (range) => fetchRecording(artifactId, range)
464
+ }).then((saved) => host.context.client.notify({
465
+ body: `Computer-use recording saved to ${saved}.`,
466
+ level: "info"
467
+ }), (error) => {
468
+ if (lifetime.signal.aborted) return;
469
+ return host.context.client.notify({
470
+ body: `The computer-use recording was not saved to artifacts: ${error instanceof Error ? error.message : String(error)}`,
471
+ level: "warning"
472
+ });
473
+ }).catch(() => void 0);
474
+ };
475
+ const modeSelected = () => (host.context.selection.state?.["minor-mode"] ?? []).includes(require_extensionService.COMPUTER_USE_MODE_ID);
676
476
  const publishMode = () => modeOwner?.publish();
677
477
  const applyState = (next) => {
678
478
  state = next;
679
- host.context.client.setStatus(COMPUTER_USE_STATUS_KEY, next === void 0 || next.phase === "inactive" ? void 0 : `computer use: ${next.phase}`);
479
+ saveRecording(next?.artifact);
480
+ host.context.client.setStatus(require_extensionService.COMPUTER_USE_STATUS_KEY, next === void 0 || next.phase === "inactive" && !modeSelected() ? void 0 : `computer use: ${next.phase}`);
680
481
  publishMode();
681
482
  for (const listener of restrictionListeners) listener();
682
483
  };
683
484
  const selectMode = async (enabled) => {
684
- const modes = (host.context.selection.state?.["minor-mode"] ?? []).filter((mode) => mode !== COMPUTER_USE_MODE_ID);
485
+ const modes = (host.context.selection.state?.["minor-mode"] ?? []).filter((mode) => mode !== require_extensionService.COMPUTER_USE_MODE_ID);
685
486
  await host.changeSelection({
686
487
  axis: "state",
687
488
  key: "minor-mode",
688
- values: enabled ? [...modes, COMPUTER_USE_MODE_ID] : modes
489
+ values: enabled ? [...modes, require_extensionService.COMPUTER_USE_MODE_ID] : modes
689
490
  });
690
491
  publishMode();
691
492
  };
@@ -700,14 +501,15 @@ function createComputerUseServer(host, apiContext) {
700
501
  applyState(void 0);
701
502
  }
702
503
  };
504
+ const isActive = () => desktop.available && desktop.enabled !== false && modeSelected() && state?.phase === "active";
703
505
  const requireActive = () => {
704
- if (!desktop.available || desktop.enabled === false || !modeSelected() || state?.phase !== "active") throw new Error("Computer use is not active for this session.");
506
+ if (!isActive()) throw new Error(NOT_ACTIVE);
705
507
  return client;
706
508
  };
707
509
  modeOwner = (0, _agimon_ai_po_minor_mode.defineMinorMode)({
708
510
  descriptor: {
709
511
  source: SOURCE,
710
- id: COMPUTER_USE_MODE_ID,
512
+ id: require_extensionService.COMPUTER_USE_MODE_ID,
711
513
  label: "Computer Use",
712
514
  description: "Session-scoped semantic control through Po Desktop.",
713
515
  order: 450,
@@ -741,11 +543,11 @@ function createComputerUseServer(host, apiContext) {
741
543
  ...mode,
742
544
  condition: "blocked",
743
545
  detail: "Enable computer use in global Desktop settings.",
744
- actions: mode.actions.map((action) => ({
546
+ actions: mode.actions.map((action) => action.id === "deactivate" ? action : {
745
547
  ...action,
746
548
  enabled: false,
747
549
  disabledReason: "Enable computer use in global Desktop settings."
748
- }))
550
+ })
749
551
  } : mode;
750
552
  },
751
553
  async handleAction(_runtime, actionId, _argumentsValue, execution) {
@@ -769,21 +571,132 @@ function createComputerUseServer(host, apiContext) {
769
571
  throw new Error(`Unknown computer-use action: ${actionId}`);
770
572
  }
771
573
  }).createOwner(void 0);
574
+ const handlers = {
575
+ async state(parameters, signal) {
576
+ try {
577
+ const { saveScreenshot, ...query } = parameters;
578
+ const save = saveScreenshot === true;
579
+ const observation = await requireActive().observe(signal, {
580
+ ...query,
581
+ includeScreenshot: save || parameters.includeScreenshot !== false
582
+ });
583
+ if (!save) return computerObservationOutput(observation);
584
+ if (!observation.screenshot) throw new Error("Desktop returned no screenshot to save.");
585
+ const screenshotArtifact = await artifacts.saveScreenshot(observation.screenshot.data, observation.runId, signal);
586
+ return computerObservationOutput({
587
+ ...observation,
588
+ ...parameters.includeScreenshot === false ? { screenshot: void 0 } : {},
589
+ screenshotArtifact
590
+ });
591
+ } catch (error) {
592
+ return output(error instanceof Error ? error.message : String(error), true);
593
+ }
594
+ },
595
+ async act(parameters, signal) {
596
+ try {
597
+ const result = await requireActive().act(parameters, signal);
598
+ await refresh(signal);
599
+ return output(result);
600
+ } catch (error) {
601
+ return output(error instanceof Error ? error.message : String(error), true);
602
+ }
603
+ },
604
+ async run(parameters, signal) {
605
+ try {
606
+ requireActive();
607
+ if (!dependencies.scriptRunner) throw new Error("Computer script execution is unavailable.");
608
+ return computerScriptOutput(await dependencies.scriptRunner.execute(parameters.scriptPath, parameters.input, signal, parameters));
609
+ } catch (error) {
610
+ return computerScriptFailure(error);
611
+ }
612
+ },
613
+ async stop(signal) {
614
+ await requireActive().stop(signal);
615
+ await refresh(signal);
616
+ return { phase: state?.phase ?? "inactive" };
617
+ }
618
+ };
772
619
  const unsubscribeState = client.subscribeStatus?.(applyState);
773
620
  return {
774
621
  api: [{
775
- basePath: API_BASE_PATH,
622
+ basePath: require_extensionService.API_BASE_PATH,
776
623
  start: () => broker
777
624
  }],
778
- services: [(context) => {
779
- const fiber = context.plugin((0, _agimon_ai_po_minor_mode.serverMinorModes)([modeOwner]));
780
- context.effect(() => desktop.subscribe(() => {
781
- if (!desktop.available) fiber.dispose();
782
- }));
783
- }],
625
+ services: [
626
+ (context) => {
627
+ context.inject(["po/profile-runtime"], (child) => {
628
+ const profile = child.get("po/profile-runtime");
629
+ profileRuntime = profile;
630
+ return () => {
631
+ if (profileRuntime === profile) profileRuntime = void 0;
632
+ };
633
+ });
634
+ },
635
+ (context) => {
636
+ context.inject([_agimon_ai_po_core_platform.PO_FS_SERVICE, require_extensionService.COMPUTER_USE_ARTIFACTS_SERVICE], (child) => {
637
+ const controller = new AbortController();
638
+ const binding = {
639
+ fs: (0, _agimon_ai_po_core_platform.requirePoFs)(child),
640
+ storage: child.get(require_extensionService.COMPUTER_USE_ARTIFACTS_SERVICE),
641
+ signal: controller.signal
642
+ };
643
+ artifactBinding = binding;
644
+ return () => {
645
+ controller.abort();
646
+ if (artifactBinding === binding) artifactBinding = void 0;
647
+ };
648
+ });
649
+ },
650
+ (context) => {
651
+ const fiber = context.plugin((0, _agimon_ai_po_minor_mode.serverMinorModes)([modeOwner]));
652
+ context.effect(() => desktop.subscribe(() => {
653
+ if (!desktop.available) fiber.dispose();
654
+ }));
655
+ },
656
+ (context) => {
657
+ context.inject([_agimon_ai_po_core_codemode.PO_CODEMODE_SERVICE], (scoped) => {
658
+ const codemode = (0, _agimon_ai_po_core_codemode.readPoCodemode)(scoped);
659
+ if (!codemode) return void 0;
660
+ const restriction = host.registerToolRestriction({ excludedTools: [...require_extensionService.COMPUTER_USE_TOOL_NAMES] });
661
+ let grant;
662
+ const revoke = () => {
663
+ const current = grant;
664
+ grant = void 0;
665
+ codemodeLive = false;
666
+ current?.lifetime.abort(/* @__PURE__ */ new Error(NOT_ACTIVE));
667
+ current?.registration.dispose();
668
+ };
669
+ const sync = () => {
670
+ if (!isActive()) revoke();
671
+ else if (!grant) {
672
+ const lifetime = new AbortController();
673
+ grant = {
674
+ lifetime,
675
+ registration: codemode.register(SOURCE, createComputerNamespace({
676
+ sessionId: host.context.sessionId,
677
+ operations: handlers,
678
+ isActive,
679
+ lifetime: lifetime.signal
680
+ }))
681
+ };
682
+ codemodeLive = true;
683
+ }
684
+ };
685
+ restrictionListeners.add(sync);
686
+ const unsubscribeDesktop = desktop.subscribe(sync);
687
+ sync();
688
+ return () => {
689
+ unsubscribeDesktop();
690
+ restrictionListeners.delete(sync);
691
+ revoke();
692
+ restriction.dispose();
693
+ };
694
+ });
695
+ }
696
+ ],
784
697
  toolRestrictions: [{
785
698
  source: SOURCE,
786
- restrict: () => ({ excludedTools: desktop.available && desktop.enabled !== false && modeSelected() && state?.phase === "active" ? [] : [
699
+ restrict: () => ({ excludedTools: isActive() ? [] : [
787
700
  "computer_state",
788
701
  "computer_action",
789
702
  "computer_exec"
@@ -797,10 +710,10 @@ function createComputerUseServer(host, apiContext) {
797
710
  }],
798
711
  activities: [{
799
712
  when: {
800
- state: { "minor-mode": COMPUTER_USE_MODE_ID },
713
+ state: { "minor-mode": require_extensionService.COMPUTER_USE_MODE_ID },
801
714
  attribution: {
802
715
  kind: "minor",
803
- mode: COMPUTER_USE_MODE_ID
716
+ mode: require_extensionService.COMPUTER_USE_MODE_ID
804
717
  }
805
718
  },
806
719
  name: SOURCE,
@@ -818,40 +731,62 @@ function createComputerUseServer(host, apiContext) {
818
731
  tools: [
819
732
  {
820
733
  when: {
821
- state: { "minor-mode": COMPUTER_USE_MODE_ID },
734
+ state: { "minor-mode": require_extensionService.COMPUTER_USE_MODE_ID },
822
735
  attribution: {
823
736
  kind: "minor",
824
- mode: COMPUTER_USE_MODE_ID
737
+ mode: require_extensionService.COMPUTER_USE_MODE_ID
825
738
  }
826
739
  },
827
740
  name: "computer_state",
828
741
  label: "Computer State",
829
- description: "Observe the authorized application window and return semantic accessibility state.",
742
+ description: "Observe the authorized application window or whole desktop and return semantic accessibility state. root narrows to one subtree (an element ref, or dock, menubar or a window root on the desktop); label and role filter; offset and limit page through matches (pass nextOffset back). saveScreenshot:true also keeps the screenshot in session artifacts and returns its path.",
830
743
  parameters: {
831
744
  type: "object",
832
- properties: { includeScreenshot: { type: "boolean" } },
745
+ properties: {
746
+ includeScreenshot: { type: "boolean" },
747
+ saveScreenshot: { type: "boolean" },
748
+ root: {
749
+ type: "string",
750
+ minLength: 1,
751
+ maxLength: 256
752
+ },
753
+ label: {
754
+ type: "string",
755
+ minLength: 1,
756
+ maxLength: 256
757
+ },
758
+ role: {
759
+ type: "string",
760
+ minLength: 1,
761
+ maxLength: 256
762
+ },
763
+ offset: {
764
+ type: "integer",
765
+ minimum: 0,
766
+ maximum: 2e3
767
+ },
768
+ limit: {
769
+ type: "integer",
770
+ minimum: 1,
771
+ maximum: 500
772
+ }
773
+ },
833
774
  additionalProperties: false
834
775
  },
835
776
  executionMode: "serial",
836
- async execute(_toolCallId, _parameters, signal) {
837
- try {
838
- return computerObservationOutput(await requireActive().observe(signal, { includeScreenshot: _parameters.includeScreenshot !== false }));
839
- } catch (error) {
840
- return output(error instanceof Error ? error.message : String(error), true);
841
- }
842
- }
777
+ execute: (_toolCallId, parameters, signal) => handlers.state(parameters, signal)
843
778
  },
844
779
  {
845
780
  when: {
846
- state: { "minor-mode": COMPUTER_USE_MODE_ID },
781
+ state: { "minor-mode": require_extensionService.COMPUTER_USE_MODE_ID },
847
782
  attribution: {
848
783
  kind: "minor",
849
- mode: COMPUTER_USE_MODE_ID
784
+ mode: require_extensionService.COMPUTER_USE_MODE_ID
850
785
  }
851
786
  },
852
787
  name: "computer_action",
853
788
  label: "Computer Action",
854
- description: "Perform one constrained semantic action in the authorized application window.",
789
+ description: "Perform one constrained semantic action in the authorized application window or desktop. set_value accepts {{ env.NAME }} and {{ secrets.NAME }} references resolved privately. Secrets require an approved single-window app and seal observations. perform runs one of the element nativeActions. launch opens an installed app by bundle id or name on a whole-desktop grant and needs only app.",
855
790
  parameters: {
856
791
  type: "object",
857
792
  properties: {
@@ -861,7 +796,9 @@ function createComputerUseServer(host, apiContext) {
861
796
  "press",
862
797
  "focus",
863
798
  "set_value",
864
- "scroll"
799
+ "scroll",
800
+ "perform",
801
+ "launch"
865
802
  ]
866
803
  },
867
804
  snapshotId: {
@@ -885,32 +822,29 @@ function createComputerUseServer(host, apiContext) {
885
822
  amount: {
886
823
  type: "string",
887
824
  enum: ["line", "page"]
825
+ },
826
+ action: {
827
+ type: "string",
828
+ pattern: "^AX[A-Za-z]{1,62}$"
829
+ },
830
+ app: {
831
+ type: "string",
832
+ minLength: 1,
833
+ maxLength: 256
888
834
  }
889
835
  },
890
- required: [
891
- "kind",
892
- "snapshotId",
893
- "elementRef"
894
- ],
836
+ required: ["kind"],
895
837
  additionalProperties: false
896
838
  },
897
839
  executionMode: "serial",
898
- async execute(_toolCallId, parameters, signal) {
899
- try {
900
- const result = await requireActive().act(parameters, signal);
901
- await refresh(signal);
902
- return output(result);
903
- } catch (error) {
904
- return output(error instanceof Error ? error.message : String(error), true);
905
- }
906
- }
840
+ execute: (_toolCallId, parameters, signal) => handlers.act(parameters, signal)
907
841
  },
908
842
  {
909
843
  when: {
910
- state: { "minor-mode": COMPUTER_USE_MODE_ID },
844
+ state: { "minor-mode": require_extensionService.COMPUTER_USE_MODE_ID },
911
845
  attribution: {
912
846
  kind: "minor",
913
- mode: COMPUTER_USE_MODE_ID
847
+ mode: require_extensionService.COMPUTER_USE_MODE_ID
914
848
  }
915
849
  },
916
850
  name: "computer_exec",
@@ -931,16 +865,7 @@ function createComputerUseServer(host, apiContext) {
931
865
  additionalProperties: false
932
866
  },
933
867
  executionMode: "serial",
934
- async execute(_toolCallId, parameters, signal) {
935
- try {
936
- requireActive();
937
- if (!dependencies.scriptRunner) throw new Error("Computer script execution is unavailable.");
938
- const input = parameters;
939
- return computerScriptOutput(await dependencies.scriptRunner.execute(input.scriptPath, input.input, signal, input));
940
- } catch (error) {
941
- return computerScriptFailure(error);
942
- }
943
- }
868
+ execute: (_toolCallId, parameters, signal) => handlers.run(parameters, signal)
944
869
  }
945
870
  ],
946
871
  commands: [{
@@ -957,7 +882,7 @@ function createComputerUseServer(host, apiContext) {
957
882
  await host.changeSelection({
958
883
  axis: "state",
959
884
  key: "minor-mode",
960
- values: (execution.selection.state?.["minor-mode"] ?? []).filter((mode) => mode !== COMPUTER_USE_MODE_ID)
885
+ values: (execution.selection.state?.["minor-mode"] ?? []).filter((mode) => mode !== require_extensionService.COMPUTER_USE_MODE_ID)
961
886
  });
962
887
  await refresh();
963
888
  }
@@ -965,23 +890,23 @@ function createComputerUseServer(host, apiContext) {
965
890
  }],
966
891
  hooks: [{
967
892
  when: {
968
- state: { "minor-mode": COMPUTER_USE_MODE_ID },
893
+ state: { "minor-mode": require_extensionService.COMPUTER_USE_MODE_ID },
969
894
  attribution: {
970
895
  kind: "minor",
971
- mode: COMPUTER_USE_MODE_ID
896
+ mode: require_extensionService.COMPUTER_USE_MODE_ID
972
897
  }
973
898
  },
974
899
  event: "before_agent_start",
975
900
  handle(event) {
976
901
  if (state?.phase !== "active") return void 0;
977
- return { systemPrompt: `${typeof event.systemPrompt === "string" ? event.systemPrompt : ""}\n\n${GUIDANCE}`.trim() };
902
+ return { systemPrompt: `${typeof event.systemPrompt === "string" ? event.systemPrompt : ""}\n\n${codemodeLive ? require_extensionService.COMPUTER_USE_CODEMODE_GUIDANCE : GUIDANCE}`.trim() };
978
903
  }
979
904
  }, {
980
905
  when: {
981
- state: { "minor-mode": COMPUTER_USE_MODE_ID },
906
+ state: { "minor-mode": require_extensionService.COMPUTER_USE_MODE_ID },
982
907
  attribution: {
983
908
  kind: "minor",
984
- mode: COMPUTER_USE_MODE_ID
909
+ mode: require_extensionService.COMPUTER_USE_MODE_ID
985
910
  }
986
911
  },
987
912
  event: "session_shutdown",
@@ -990,13 +915,19 @@ function createComputerUseServer(host, apiContext) {
990
915
  if (client && state?.phase !== "inactive" && state?.phase !== "failed") await client.stop();
991
916
  }
992
917
  }],
993
- onDispose() {
994
- stopActivity?.();
995
- stopActivity = void 0;
996
- unsubscribeState?.();
997
- broker.close();
998
- restrictionListeners.clear();
999
- host.context.client.setStatus(COMPUTER_USE_STATUS_KEY, void 0);
918
+ async onDispose() {
919
+ await (0, _agimon_ai_po_core_extensionFile.runCleanups)([
920
+ () => {
921
+ const stop = stopActivity;
922
+ stopActivity = void 0;
923
+ stop?.();
924
+ },
925
+ () => unsubscribeState?.(),
926
+ () => broker.close(),
927
+ () => restrictionListeners.clear(),
928
+ () => host.context.client.setStatus(require_extensionService.COMPUTER_USE_STATUS_KEY, void 0),
929
+ () => lifetime.abort()
930
+ ], "Computer-use cleanup failed.");
1000
931
  }
1001
932
  };
1002
933
  }
@@ -1019,6 +950,43 @@ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)((cont
1019
950
  };
1020
951
  });
1021
952
  //#endregion
953
+ //#region src/services/desktopPermissionsApi/index.ts
954
+ /**
955
+ * Desktop's macOS permissions for the settings page.
956
+ *
957
+ * Hub-scoped because the permissions belong to the Mac, not a session. The server's
958
+ * Desktop link reads and requests them; without Desktop the mount answers 404, so
959
+ * the page can say so instead of guessing.
960
+ */
961
+ async function desktopPermissionsResponse(access, request) {
962
+ const path = new URL(request.url).pathname;
963
+ const change = request.method === require_extensionService.routes.requestDesktopPermission.method;
964
+ if (path !== require_extensionService.routes.desktopPermissions.path || !change && request.method !== require_extensionService.routes.desktopPermissions.method) return Response.json({ error: "Not found." }, { status: 404 });
965
+ if (access === void 0) return Response.json({ error: "Po Desktop is not running this server." }, { status: 404 });
966
+ if (!access.authorize(request.headers, change)) return Response.json({ error: "Open Po Desktop on that Mac, or confirm with your passkey." }, { status: 403 });
967
+ let permission;
968
+ if (change) {
969
+ const body = await request.json().catch(() => void 0);
970
+ if (!require_extensionService.isDesktopPermission(body?.permission)) return Response.json({ error: "Name one permission to ask for." }, { status: 400 });
971
+ permission = body.permission;
972
+ }
973
+ try {
974
+ return Response.json(await access.request(permission));
975
+ } catch (error) {
976
+ return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 502 });
977
+ }
978
+ }
979
+ //#endregion
980
+ //#region src/extensions/(backend)/api/desktop-permissions/route.server.ts
981
+ /** Mounts Desktop's macOS permissions at `desktop-permissions`, which the folder names. */
982
+ var route_server_default$1 = (0, _agimon_ai_po_core_extensionFile.defineRoute)({
983
+ basePath: "desktop-permissions",
984
+ start: (context) => ({
985
+ fetch: (request) => desktopPermissionsResponse(context.desktopPermissions, request),
986
+ close: () => void 0
987
+ })
988
+ });
989
+ //#endregion
1022
990
  //#region src/services/webComputerUseAvailability/index.ts
1023
991
  var MissingComputerUseApiError = class extends Error {};
1024
992
  function computerUseSessionApiError(status, value) {
@@ -1030,6 +998,8 @@ function computerUseSessionApiError(status, value) {
1030
998
  //#region src/services/webComputerUseChannel/index.ts
1031
999
  /** Computer use runs on the Po Desktop host, so every other client declines it. */
1032
1000
  const DESKTOP_UNAVAILABLE = "Po Desktop computer use is unavailable.";
1001
+ const SESSION_READY_ATTEMPTS = 5;
1002
+ const SESSION_READY_RETRY_MS = 200;
1033
1003
  function record(value) {
1034
1004
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1035
1005
  }
@@ -1057,7 +1027,7 @@ function sessionState(value) {
1057
1027
  function createComputerUseChannel() {
1058
1028
  let receiveCommand;
1059
1029
  return {
1060
- frameType: computerUseChannelType,
1030
+ frameType: require_extensionService.computerUseChannelType,
1061
1031
  lifecycle: "hub",
1062
1032
  start(host) {
1063
1033
  const scopes = /* @__PURE__ */ new Map();
@@ -1070,12 +1040,21 @@ function createComputerUseChannel() {
1070
1040
  const requests = /* @__PURE__ */ new Map();
1071
1041
  let activeSessionId;
1072
1042
  let closed = false;
1073
- const sessionRequest = async (scope, path, method = "GET", value) => host.requestSessionApi(scope, {
1074
- basePath: API_BASE_PATH,
1075
- path,
1076
- method,
1077
- ...value === void 0 ? {} : { body: JSON.stringify(value) }
1078
- });
1043
+ const sessionRequest = async (scope, path, method = "GET", value) => {
1044
+ const registeredScope = scopes.get(scope.sessionId);
1045
+ for (let attempt = 1;; attempt++) {
1046
+ if (closed || registeredScope === void 0 || scopes.get(scope.sessionId) !== registeredScope) throw new Error("Computer-use session is closed.");
1047
+ const response = await host.requestSessionApi(scope, {
1048
+ basePath: require_extensionService.API_BASE_PATH,
1049
+ path,
1050
+ method,
1051
+ ...value === void 0 ? {} : { body: JSON.stringify(value) }
1052
+ });
1053
+ if (response.status !== 503 || attempt >= SESSION_READY_ATTEMPTS) return response;
1054
+ if (record(await response.clone().json().catch(() => void 0))?.error !== "Session selection is not ready.") return response;
1055
+ await new Promise((resolve) => setTimeout(resolve, SESSION_READY_RETRY_MS));
1056
+ }
1057
+ };
1079
1058
  const publish = (scope, state) => {
1080
1059
  if (state.phase === "active" || state.phase === "activating" || state.phase === "stopping") activeSessionId = scope.sessionId;
1081
1060
  else if (activeSessionId === scope.sessionId) {
@@ -1091,7 +1070,7 @@ function createComputerUseChannel() {
1091
1070
  host.publish(scope.sessionId, payload);
1092
1071
  };
1093
1072
  const refresh = async (scope) => {
1094
- const state = sessionState(await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubState)));
1073
+ const state = sessionState(await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubState)));
1095
1074
  if (state === void 0) throw new Error("Computer-use API returned an invalid session state.");
1096
1075
  publish(scope, state);
1097
1076
  return state;
@@ -1109,16 +1088,17 @@ function createComputerUseChannel() {
1109
1088
  sequence: pending.sequence,
1110
1089
  action: pending.payload
1111
1090
  } : {
1091
+ ...record(pending.payload),
1112
1092
  grantId: pending.grantId,
1113
1093
  includeScreenshot: record(pending.payload)?.includeScreenshot !== false
1114
1094
  }
1115
1095
  });
1116
- await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubComplete, "POST", {
1096
+ await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubComplete, "POST", {
1117
1097
  id: pending.id,
1118
1098
  result
1119
1099
  }));
1120
1100
  } catch (error) {
1121
- await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubComplete, "POST", {
1101
+ await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubComplete, "POST", {
1122
1102
  id: pending.id,
1123
1103
  error: error instanceof Error ? error.message : String(error)
1124
1104
  }));
@@ -1128,7 +1108,7 @@ function createComputerUseChannel() {
1128
1108
  };
1129
1109
  const stopSession = async (scope) => {
1130
1110
  requests.get(scope.sessionId)?.abort();
1131
- const authorization = await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubAuthorization));
1111
+ const authorization = await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubAuthorization));
1132
1112
  let artifact;
1133
1113
  if (authorization !== null && host.computerUse?.available) try {
1134
1114
  artifact = record(await host.computerUse.request(scope, {
@@ -1147,7 +1127,7 @@ function createComputerUseChannel() {
1147
1127
  };
1148
1128
  host.onNotice(`computer-use Desktop stop was already unavailable (${message})`);
1149
1129
  }
1150
- await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubStop, "POST", { artifact }));
1130
+ await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubStop, "POST", { artifact }));
1151
1131
  grants.delete(scope.sessionId);
1152
1132
  if (activeSessionId === scope.sessionId) activeSessionId = void 0;
1153
1133
  };
@@ -1162,7 +1142,7 @@ function createComputerUseChannel() {
1162
1142
  const state = announced ?? await refresh(scope);
1163
1143
  if (state.phase === "active") {
1164
1144
  if (!grants.has(scope.sessionId)) {
1165
- const authorization = await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubAuthorization));
1145
+ const authorization = await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubAuthorization));
1166
1146
  if (authorization !== null) grants.set(scope.sessionId, authorization.grantId);
1167
1147
  }
1168
1148
  const expired = typeof state.expiresAt === "number" && state.expiresAt <= Date.now();
@@ -1179,9 +1159,9 @@ function createComputerUseChannel() {
1179
1159
  }
1180
1160
  }
1181
1161
  if (state.phase === "awaiting_confirmation" && (activeSessionId === void 0 || activeSessionId === scope.sessionId)) {
1182
- const activation = await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubActivation));
1162
+ const activation = await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubActivation));
1183
1163
  if (activation !== null && !host.computerUse?.available) {
1184
- await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubStop, "POST", { error: DESKTOP_UNAVAILABLE }));
1164
+ await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubStop, "POST", { error: DESKTOP_UNAVAILABLE }));
1185
1165
  await refresh(scope);
1186
1166
  return;
1187
1167
  }
@@ -1195,12 +1175,12 @@ function createComputerUseChannel() {
1195
1175
  payload: activation,
1196
1176
  signal: controller.signal
1197
1177
  });
1198
- await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubStop, "POST", { host: hostResult }));
1178
+ await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubStop, "POST", { host: hostResult }));
1199
1179
  const grantId = record(hostResult)?.grantId;
1200
1180
  if (typeof grantId === "string") grants.set(scope.sessionId, grantId);
1201
1181
  } catch (error) {
1202
1182
  activeSessionId = void 0;
1203
- await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubStop, "POST", { error: error instanceof Error ? error.message : String(error) }));
1183
+ await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubStop, "POST", { error: error instanceof Error ? error.message : String(error) }));
1204
1184
  } finally {
1205
1185
  if (requests.get(scope.sessionId) === controller) requests.delete(scope.sessionId);
1206
1186
  }
@@ -1211,7 +1191,7 @@ function createComputerUseChannel() {
1211
1191
  await stopSession(scope);
1212
1192
  await refresh(scope);
1213
1193
  }
1214
- const pending = await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubNext));
1194
+ const pending = await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubNext));
1215
1195
  if (pending !== null) await completePending(scope, pending);
1216
1196
  } catch (error) {
1217
1197
  if (error instanceof MissingComputerUseApiError) latest.delete(scope.sessionId);
@@ -1255,7 +1235,7 @@ function createComputerUseChannel() {
1255
1235
  payloadFor: (scope) => latest.get(scope.sessionId),
1256
1236
  sessionAdded(scope) {
1257
1237
  scopes.set(scope.sessionId, scope);
1258
- const unsubscribe = host.directEvents.subscribe(computerUseChannelType, scope.sessionId, (payload) => onState(scope, payload), { replayLatest: true });
1238
+ const unsubscribe = host.directEvents.subscribe(require_extensionService.computerUseChannelType, scope.sessionId, (payload) => onState(scope, payload), { replayLatest: true });
1259
1239
  subscriptions.set(scope.sessionId, unsubscribe);
1260
1240
  processScope(scope);
1261
1241
  },
@@ -1290,7 +1270,7 @@ function createComputerUseChannel() {
1290
1270
  if (scope !== void 0) host.computerUse.request(scope, {
1291
1271
  operation: "stop",
1292
1272
  payload: { grantId }
1293
- }).catch(() => void 0);
1273
+ }).catch((error) => host.onNotice(`computer-use Desktop stop failed during shutdown (${String(error)})`));
1294
1274
  }
1295
1275
  scopes.clear();
1296
1276
  latest.clear();
@@ -1321,6 +1301,23 @@ var before_agent_start_server_default = (0, _agimon_ai_po_core_extensionFile.def
1321
1301
  //#region src/extensions/workspaces/sessions/(backend)/hook/session-shutdown.server.ts
1322
1302
  var session_shutdown_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)((context) => context.root.hooks?.find((hook) => hook.event === "session_shutdown"), { cardinality: "optional" });
1323
1303
  //#endregion
1304
+ //#region src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-computer-use.server.ts
1305
+ var codemode_how_to_computer_use_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)({
1306
+ name: "codemode-how-to-computer-use",
1307
+ description: "Observe and act on the application window, or the whole desktop, the person authorized through Po Desktop, using the computer namespace in exec. Use when Computer Use is on and the task needs the screen state, a semantic press, focus, set_value, scroll or native action, or an app launch.",
1308
+ kind: "skill",
1309
+ pinned: true,
1310
+ when: {
1311
+ state: { "minor-mode": require_extensionService.COMPUTER_USE_MODE_ID },
1312
+ attribution: {
1313
+ kind: "minor",
1314
+ mode: require_extensionService.COMPUTER_USE_MODE_ID
1315
+ }
1316
+ },
1317
+ path: (0, _agimon_ai_po_core_serverPlugin.packageResourcePath)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-computer-use/SKILL.md"),
1318
+ read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-computer-use/SKILL.md")
1319
+ });
1320
+ //#endregion
1324
1321
  //#region src/extensions/workspaces/sessions/(backend)/tool-restriction/computer-use.server.ts
1325
1322
  var computer_use_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)((context) => context.root.toolRestrictions?.[0], { cardinality: "optional" });
1326
1323
  //#endregion
@@ -1341,17 +1338,28 @@ const via = (identity, value) => value === void 0 ? void 0 : {
1341
1338
  ...identity,
1342
1339
  ...value
1343
1340
  };
1344
- const facet = (0, _agimon_ai_po_core_serverFacet.defineServerPlugin)({
1341
+ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
1345
1342
  name: "@agimon-ai/po-computer-use",
1346
- providerOverrides: (0, _agimon_ai_po_core_serverFacet.composeServerProviderOverrides)(root_server_default),
1347
- global: () => ({ get channels() {
1348
- return [() => via({ frameType: "computer_use" }, computer_use_server_default$2())];
1349
- } }),
1350
- workspace: () => ({ get channels() {
1351
- return [() => via({ frameType: "computer_use" }, computer_use_server_default$2())];
1352
- } }),
1343
+ providerOverrides: (0, _agimon_ai_po_core_serverPlugin.composeServerProviderOverrides)(root_server_default),
1344
+ injects: (0, _agimon_ai_po_core_extensionFile.composeRootInjects)({ session: [root_server_default] }),
1345
+ global: (context) => ({
1346
+ get api() {
1347
+ return [at(route_server_default$1, context)];
1348
+ },
1349
+ get channels() {
1350
+ return [() => via({ frameType: "computer_use" }, at(computer_use_server_default$2, context))];
1351
+ }
1352
+ }),
1353
+ workspace: (context) => ({
1354
+ get api() {
1355
+ return [at(route_server_default$1, context)];
1356
+ },
1357
+ get channels() {
1358
+ return defined([context.hosted("global") ? void 0 : () => via({ frameType: "computer_use" }, at(computer_use_server_default$2, context))]);
1359
+ }
1360
+ }),
1353
1361
  session: async (context) => {
1354
- const scopeSession = await root_server_default(context);
1362
+ const scopeSession = await context.scopeRoot("session", root_server_default, context);
1355
1363
  const contextSession = {
1356
1364
  ...context,
1357
1365
  root: scopeSession.value
@@ -1359,10 +1367,10 @@ const facet = (0, _agimon_ai_po_core_serverFacet.defineServerPlugin)({
1359
1367
  return {
1360
1368
  ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeSession),
1361
1369
  get api() {
1362
- return defined([at(route_server_default, contextSession)]);
1370
+ return defined([at(route_server_default$1, context), at(route_server_default, contextSession)]);
1363
1371
  },
1364
1372
  get channels() {
1365
- return [() => via({ frameType: "computer_use" }, computer_use_server_default$2())];
1373
+ return defined([context.hosted("global") ? void 0 : () => via({ frameType: "computer_use" }, at(computer_use_server_default$2, context))]);
1366
1374
  },
1367
1375
  get commands() {
1368
1376
  return defined([via({ name: "computer-use" }, at(computer_use_server_default$1, contextSession))]);
@@ -1370,6 +1378,9 @@ const facet = (0, _agimon_ai_po_core_serverFacet.defineServerPlugin)({
1370
1378
  get hooks() {
1371
1379
  return defined([via({ event: "before_agent_start" }, at(before_agent_start_server_default, contextSession)), via({ event: "session_shutdown" }, at(session_shutdown_server_default, contextSession))]);
1372
1380
  },
1381
+ get resources() {
1382
+ return [at(codemode_how_to_computer_use_server_default, contextSession)];
1383
+ },
1373
1384
  get toolRestrictions() {
1374
1385
  return defined([at(computer_use_server_default, contextSession)]);
1375
1386
  },
@@ -1388,7 +1399,7 @@ const facet = (0, _agimon_ai_po_core_serverFacet.defineServerPlugin)({
1388
1399
  }
1389
1400
  });
1390
1401
  //#endregion
1391
- exports.default = facet;
1392
- exports.facet = facet;
1402
+ exports.default = serverPlugin;
1403
+ exports.serverPlugin = serverPlugin;
1393
1404
 
1394
1405
  //# sourceMappingURL=server.cjs.map