@agimon-ai/po-computer-use 0.0.0-alpha.21 → 0.0.0-alpha.211

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 (49) hide show
  1. package/LICENSE +110 -149
  2. package/README.md +9 -8
  3. package/dist/apiContracts.cjs +65 -45
  4. package/dist/apiContracts.cjs.map +1 -1
  5. package/dist/apiContracts.d.mts +2 -2
  6. package/dist/apiContracts.d.mts.map +1 -1
  7. package/dist/apiContracts.mjs +65 -45
  8. package/dist/apiContracts.mjs.map +1 -1
  9. package/dist/extensionService-BKBTsnkI.cjs +1243 -0
  10. package/dist/extensionService-BKBTsnkI.cjs.map +1 -0
  11. package/dist/extensionService-DqtoB79s.mjs +1077 -0
  12. package/dist/extensionService-DqtoB79s.mjs.map +1 -0
  13. package/dist/extensions/mcp-ui.mjs +12 -9
  14. package/dist/extensions/mcp-ui.mjs.map +1 -1
  15. package/dist/extensions/mcp.cjs +13 -5
  16. package/dist/extensions/mcp.cjs.map +1 -1
  17. package/dist/extensions/mcp.d.mts.map +1 -1
  18. package/dist/extensions/mcp.mjs +13 -5
  19. package/dist/extensions/mcp.mjs.map +1 -1
  20. package/dist/extensions/native.mjs +1493 -8
  21. package/dist/extensions/native.mjs.map +1 -1
  22. package/dist/extensions/server.cjs +1035 -645
  23. package/dist/extensions/server.cjs.map +1 -1
  24. package/dist/extensions/server.d.mts.map +1 -1
  25. package/dist/extensions/server.mjs +1020 -630
  26. package/dist/extensions/server.mjs.map +1 -1
  27. package/dist/extensions/web.mjs +1004 -480
  28. package/dist/extensions/web.mjs.map +1 -1
  29. package/dist/index.cjs +14 -5
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.mts +67 -10
  32. package/dist/index.d.mts.map +1 -1
  33. package/dist/index.mjs +14 -5
  34. package/dist/index.mjs.map +1 -1
  35. package/dist/po-runtime-identity.json +1 -0
  36. package/docs/computer-scripts.md +1 -1
  37. package/docs/remote-computer-use.md +11 -0
  38. package/llms.txt +1 -1
  39. package/locales/vi.json +153 -0
  40. package/locales/zh-CN.json +153 -0
  41. package/package.json +84 -24
  42. package/src/prompts/codemode-how-to-computer-use/SKILL.md +83 -0
  43. package/src/types/computerUse.ts +72 -7
  44. package/src/types/computerUseApi.ts +24 -5
  45. package/dist/extensionService-Bp0q295i.cjs +0 -504
  46. package/dist/extensionService-Bp0q295i.cjs.map +0 -1
  47. package/dist/extensionService-DXvF7esO.mjs +0 -434
  48. package/dist/extensionService-DXvF7esO.mjs.map +0 -1
  49. package/src/prompts/po-use-computer-use/SKILL.md +0 -34
@@ -2,44 +2,17 @@ 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-BKBTsnkI.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_platform = require("@agimon-ai/po-core/platform");
9
+ let node_crypto = require("node:crypto");
8
10
  let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
9
11
  let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
10
- 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
12
+ let _agimon_ai_po_core_codemode = require("@agimon-ai/po-core/codemode");
13
+ let _agimon_ai_po_core_locale = require("@agimon-ai/po-core/locale");
14
+ let _agimon_ai_po_mode = require("@agimon-ai/po-mode");
15
+ let _agimon_ai_po_core_hubChannel = require("@agimon-ai/po-core/hubChannel");
43
16
  //#region src/services/mcpTools/index.ts
44
17
  const COMPUTER_USE_MCP_TOOLS_SERVICE = "po/computer-use-mcp-tools";
45
18
  function mountMcpTools(tools) {
@@ -59,9 +32,9 @@ function modeState(state, enabled = false) {
59
32
  const modeEnabled = enabled || phase !== "inactive" && phase !== "failed";
60
33
  return {
61
34
  activation: modeEnabled ? phase === "stopping" ? "deactivating" : phase === "awaiting_confirmation" || phase === "activating" ? "activating" : "active" : "inactive",
62
- condition: phase === "awaiting_confirmation" ? "blocked" : phase === "failed" ? "failed" : phase === "activating" || phase === "stopping" ? "queued" : "ready",
63
- ...modeEnabled && phase === "inactive" ? { detail: "configure computer use in Activity" } : {},
64
- ...phase === "awaiting_confirmation" ? { detail: "awaiting confirmation in Activity" } : {},
35
+ condition: phase === "failed" ? "failed" : phase === "awaiting_confirmation" || phase === "activating" || phase === "stopping" ? "queued" : "ready",
36
+ ...modeEnabled && phase === "inactive" ? { detail: "Po asks before it takes control" } : {},
37
+ ...phase === "awaiting_confirmation" || phase === "activating" ? { detail: "starting computer use" } : {},
65
38
  actions: [
66
39
  {
67
40
  id: "activate",
@@ -81,6 +54,207 @@ function modeState(state, enabled = false) {
81
54
  };
82
55
  }
83
56
  //#endregion
57
+ //#region src/services/computerNamespace/index.ts
58
+ const NOT_ACTIVE$1 = "Computer use is not active for this session.";
59
+ const REQUEST_DECLARATIONS = `declare const computer: {
60
+ /** Lists possible control targets, without screen contents. */
61
+ targets(): Promise<ComputerUseTarget[]>;
62
+ /** Requests human approval. Returns a pending approval; the outcome arrives as a new message. */
63
+ request(options: { target: ComputerUseTarget; durationMinutes: 5 | 15 | 30; reason: string; keepTrace?: boolean }): Promise<unknown>;
64
+ };
65
+ type ComputerUseTarget = { scope: 'desktop' } | {
66
+ bundleId: string; applicationName: string; processId: number; windowId: string; windowTitle: string;
67
+ };`;
68
+ const CONTROL_DECLARATIONS = `
69
+ /**
70
+ * Read-only. Observes the authorized window or whole desktop. A screenshot is shown to the model unless includeScreenshot is false.
71
+ * save: true also keeps the screenshot in session artifacts and returns its path as screenshotArtifact.
72
+ * root narrows to one subtree (an element ref, or on the desktop 'dock', 'menubar' or a window root id).
73
+ * label (substring, any case) and role (exact, e.g. 'AXButton') filter elements.
74
+ * skeleton: true returns only the outline (containers and interactive elements); use it first on large windows.
75
+ * offset/limit page through matches; pass nextOffset back while it is present.
76
+ */
77
+ state(options?: {
78
+ includeScreenshot?: boolean;
79
+ skeleton?: boolean;
80
+ save?: boolean;
81
+ root?: string;
82
+ label?: string;
83
+ role?: string;
84
+ offset?: number;
85
+ limit?: number;
86
+ }): Promise<Record<string, unknown>>;
87
+ /**
88
+ * Changes the application. One semantic action using ids from the latest state().
89
+ * set_value accepts {{ env.NAME }} or {{ secrets.NAME }}. Secrets need an approved single-window app and seal observations.
90
+ * expand, collapse, toggle, check, uncheck and scroll_to take only the element; select takes value; type takes text.
91
+ * scroll amount is 'line', 'page' or a whole number from 1 to 100.
92
+ * perform runs one of the element's nativeActions, such as 'AXShowMenu'.
93
+ * launch opens an installed app by bundle id or name on a whole-desktop grant; it needs no snapshot.
94
+ */
95
+ act(
96
+ action:
97
+ | {
98
+ kind:
99
+ | 'press' | 'focus' | 'set_value' | 'scroll' | 'perform'
100
+ | 'expand' | 'collapse' | 'toggle' | 'check' | 'uncheck' | 'select' | 'scroll_to' | 'type';
101
+ snapshotId: string;
102
+ elementRef: string;
103
+ value?: string;
104
+ direction?: 'up' | 'down' | 'left' | 'right';
105
+ amount?: 'line' | 'page' | number;
106
+ text?: string;
107
+ action?: string;
108
+ }
109
+ | { kind: 'launch'; app: string },
110
+ ): Promise<Record<string, unknown>>;
111
+ /** Changes the application. Runs an allowlisted script with only the authorized program API. No screenshot unless asked. */
112
+ run(options: { scriptPath: string; input: unknown; trusted?: boolean; includeScreenshot?: boolean }): Promise<Record<string, unknown>>;
113
+ /** Ends the current grant. It never activates anything or changes settings. */
114
+ stop(): Promise<{ phase: string }>;`;
115
+ /** Detached JSON: screenshots (base64) never travel through the return value. */
116
+ function detach(value) {
117
+ return JSON.parse(JSON.stringify(value ?? null, (key, entry) => key === "screenshot" ? void 0 : entry) ?? "null");
118
+ }
119
+ function plain(value, member, allowed) {
120
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`computer.${member} expects an object.`);
121
+ const unknown = Object.keys(value).find((key) => !allowed.includes(key));
122
+ if (unknown !== void 0) throw new TypeError(`computer.${member} does not accept "${unknown}".`);
123
+ return value;
124
+ }
125
+ function optionalBoolean(options, member, key) {
126
+ const value = options[key];
127
+ if (value !== void 0 && typeof value !== "boolean") throw new TypeError(`computer.${member} ${key} must be a boolean.`);
128
+ return value;
129
+ }
130
+ function failureMessage(details) {
131
+ if (typeof details === "string") return details;
132
+ const failure = details ?? {};
133
+ const message = typeof failure.error === "string" ? failure.error : "Computer use failed.";
134
+ return failure.completedActions === void 0 ? message : `${message} (completedActions: ${JSON.stringify(failure.completedActions)}, outcomeUncertain: ${String(failure.outcomeUncertain)})`;
135
+ }
136
+ function createComputerNamespace(deps) {
137
+ const operations = deps.operations;
138
+ return {
139
+ name: "computer",
140
+ summary: operations ? "Request human approval, observe or act within the authorized target, run an allowlisted script, or stop control." : "List computer-use targets and request a time-limited, recorded grant with human approval.",
141
+ declarations: operations ? REQUEST_DECLARATIONS.replace("};", `${CONTROL_DECLARATIONS}\n};`) : REQUEST_DECLARATIONS,
142
+ approval: { request: deps.request.policy },
143
+ bind(run) {
144
+ const guard = () => {
145
+ if (run.sessionId !== deps.sessionId) throw new Error("Computer use belongs to another session.");
146
+ run.signal.throwIfAborted();
147
+ deps.lifetime.throwIfAborted();
148
+ return AbortSignal.any([run.signal, deps.lifetime]);
149
+ };
150
+ const ready = {
151
+ targets: async () => detach(await deps.request.targets(guard())),
152
+ request: async (input) => {
153
+ guard();
154
+ return detach(await deps.request.activate(input, run.approvedCall?.approvalId, run.signal));
155
+ }
156
+ };
157
+ if (!operations) return Object.assign(Object.create(null), ready);
158
+ const finish = (member, tool, args, started, result) => {
159
+ const details = detach(result.details);
160
+ const ok = result.isError !== true;
161
+ run.record?.({
162
+ name: `computer.${member}`,
163
+ tool,
164
+ args: detach(args),
165
+ ok,
166
+ ms: Date.now() - started,
167
+ ...ok ? {} : { error: failureMessage(details).slice(0, 512) },
168
+ result: {
169
+ content: result.content.filter((block) => block.type === "text"),
170
+ details
171
+ }
172
+ });
173
+ if (!ok) throw new Error(failureMessage(details));
174
+ const warnings = [];
175
+ for (const block of result.content) {
176
+ if (block.type !== "image") continue;
177
+ const shown = run.emitImage?.({
178
+ data: block.data,
179
+ mimeType: block.mimeType
180
+ });
181
+ if (shown?.emitted !== true) warnings.push(shown?.warning ?? "Image not shown to the model: this host cannot show images.");
182
+ }
183
+ return warnings.length > 0 ? {
184
+ ...details,
185
+ warning: warnings.join(" ")
186
+ } : details;
187
+ };
188
+ const call = async (member, tool, args, operation) => {
189
+ const signal = guard();
190
+ if (!deps.isActive()) throw new Error(NOT_ACTIVE$1);
191
+ return finish(member, tool, args, Date.now(), await operation(signal));
192
+ };
193
+ return Object.assign(Object.create(null), {
194
+ ...ready,
195
+ state: async (options) => {
196
+ const parsed = options === void 0 ? {} : plain(options, "state", [
197
+ "includeScreenshot",
198
+ "skeleton",
199
+ "save",
200
+ "root",
201
+ "label",
202
+ "role",
203
+ "offset",
204
+ "limit"
205
+ ]);
206
+ const includeScreenshot = optionalBoolean(parsed, "state", "includeScreenshot");
207
+ const saveScreenshot = optionalBoolean(parsed, "state", "save");
208
+ const { save: _save, includeScreenshot: _include, ...query } = parsed;
209
+ const args = {
210
+ ...query,
211
+ ...includeScreenshot === void 0 ? {} : { includeScreenshot },
212
+ ...saveScreenshot === void 0 ? {} : { saveScreenshot }
213
+ };
214
+ return call("state", "computer_state", args, (signal) => operations.state(args, signal));
215
+ },
216
+ act: async (action) => {
217
+ const parsed = plain(action, "act", [
218
+ "kind",
219
+ "snapshotId",
220
+ "elementRef",
221
+ "value",
222
+ "direction",
223
+ "amount",
224
+ "action",
225
+ "app"
226
+ ]);
227
+ return call("act", "computer_action", parsed, (signal) => operations.act(parsed, signal));
228
+ },
229
+ run: async (options) => {
230
+ const parsed = plain(options, "run", [
231
+ "scriptPath",
232
+ "input",
233
+ "trusted",
234
+ "includeScreenshot"
235
+ ]);
236
+ if (typeof parsed.scriptPath !== "string" || parsed.scriptPath.length === 0) throw new TypeError("computer.run scriptPath must be a non-empty string.");
237
+ if (!("input" in parsed)) throw new TypeError("computer.run requires input.");
238
+ const trusted = optionalBoolean(parsed, "run", "trusted");
239
+ const includeScreenshot = optionalBoolean(parsed, "run", "includeScreenshot");
240
+ const args = {
241
+ scriptPath: parsed.scriptPath,
242
+ input: parsed.input,
243
+ trusted,
244
+ includeScreenshot
245
+ };
246
+ return call("run", "computer_exec", args, (signal) => operations.run(args, signal));
247
+ },
248
+ stop: async () => {
249
+ const signal = guard();
250
+ if (!deps.isActive()) throw new Error(NOT_ACTIVE$1);
251
+ return detach(await operations.stop(signal));
252
+ }
253
+ });
254
+ }
255
+ };
256
+ }
257
+ //#endregion
84
258
  //#region src/services/computerToolOutput/index.ts
85
259
  const MAX_TEXT_BYTES = 262144;
86
260
  const MAX_IMAGE_DATA_LENGTH = 8388608;
@@ -142,486 +316,141 @@ function computerScriptFailure(error) {
142
316
  };
143
317
  }
144
318
  //#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
- };
319
+ //#region src/services/computerUseArtifacts/index.ts
320
+ const PNG_SIGNATURE = Buffer.from([
321
+ 137,
322
+ 80,
323
+ 78,
324
+ 71,
325
+ 13,
326
+ 10,
327
+ 26,
328
+ 10
329
+ ]);
330
+ const MAX_SCREENSHOT_BYTES = 8388608;
331
+ const SAFE_SEGMENT = /^[A-Za-z0-9_-]{1,128}$/u;
332
+ function stamp() {
333
+ return `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/gu, "-")}-${(0, node_crypto.randomUUID)().slice(0, 8)}`;
303
334
  }
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();
335
+ /** One queue per session. Callers pass bytes or a host-bound recording, never a filesystem location. */
336
+ function createComputerUseArtifacts(sessionId, environment, binding, mountSignal) {
337
+ let pending = Promise.resolve();
338
+ const enqueue = (segments, write, requestSignal) => {
339
+ const run = pending.catch(() => void 0).then(async () => {
340
+ const active = binding();
341
+ if (!active) throw new Error("Session artifacts are unavailable.");
342
+ const signal = AbortSignal.any([
343
+ mountSignal,
344
+ active.signal,
345
+ ...requestSignal ? [requestSignal] : []
346
+ ]);
347
+ const context = (0, _agimon_ai_po_core_platform.withAbortSignal)(signal, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT);
348
+ const { fs, storage } = active;
349
+ const check = () => {
350
+ signal.throwIfAborted();
351
+ if (binding() !== active) throw new Error("Session artifact storage changed.");
352
+ };
353
+ const safeDirectory = async (path) => {
354
+ const absolute = (0, node_path.resolve)(path);
355
+ 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.");
356
+ };
357
+ check();
358
+ const root = await storage.rootForSession(sessionId, environment);
359
+ check();
360
+ if (!root) throw new Error("Session artifacts are unavailable.");
361
+ await safeDirectory(root);
362
+ const folders = [root];
363
+ for (const segment of [require_extensionService.COMPUTER_USE_ARTIFACT_DIRECTORY, ...segments]) {
364
+ const directory = (0, node_path.join)(folders.at(-1), segment);
365
+ const info = await fs.fileInfo(directory, context);
366
+ if (!info.ok && info.error.code === "not_found") (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.createDir(directory, void 0, context));
367
+ else (0, _agimon_ai_po_core_platform.getOrThrow)(info);
368
+ await safeDirectory(directory);
369
+ folders.push(directory);
403
370
  }
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);
371
+ return write({
372
+ fs,
373
+ context,
374
+ relative: [require_extensionService.COMPUTER_USE_ARTIFACT_DIRECTORY, ...segments].join("/"),
375
+ directory: folders.at(-1),
376
+ check,
377
+ recheck: async () => {
378
+ for (const folder of folders) await safeDirectory(folder);
490
379
  }
491
- };
380
+ });
492
381
  });
493
- this.changed();
382
+ pending = run;
383
+ return run;
384
+ };
385
+ /** Writes `.<name>.tmp`, which the artifact list skips, then renames it into place. */
386
+ const place = async (target, name, fill) => {
387
+ const { fs, context, directory } = target;
388
+ const temporary = (0, node_path.join)(directory, `.${name}.tmp`);
389
+ const destination = (0, node_path.join)(directory, name);
390
+ 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
391
  try {
495
- return Response.json(await completion);
496
- } catch (error) {
497
- return jsonError(error instanceof Error ? error.message : String(error), 502);
392
+ target.check();
393
+ await fill(temporary);
394
+ await target.recheck();
395
+ target.check();
396
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.renameFile(temporary, destination, context));
397
+ return `artifact:${target.relative}/${name}`;
398
+ } finally {
399
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.remove(temporary, { force: true }, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT));
498
400
  }
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}`);
511
- }
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?.();
401
+ };
402
+ return {
403
+ /** Saves one observation screenshot (base64 PNG) under its run folder and returns its `artifact:` path. */
404
+ saveScreenshot(data, runId, signal) {
405
+ if (!SAFE_SEGMENT.test(runId)) return Promise.reject(/* @__PURE__ */ new Error("The computer-use run id is invalid."));
406
+ const bytes = Buffer.from(data, "base64");
407
+ 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."));
408
+ return enqueue([runId], (target) => place(target, `screenshot-${stamp()}.png`, async (temporary) => {
409
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await target.fs.writeFile(temporary, bytes, target.context));
410
+ }), signal);
411
+ },
412
+ /** Copies a consented trace file (JSONL or window PNG) beside the recording, in the host store's bounded ranges. */
413
+ saveTraceFile(kind, source, recordingStamp, signal) {
414
+ const size = source.sizeBytes;
415
+ const limit = kind === "trace" ? require_extensionService.COMPUTER_USE_TRACE_MAX_BYTES : require_extensionService.COMPUTER_USE_WINDOW_MAX_BYTES;
416
+ if (!SAFE_SEGMENT.test(recordingStamp) || !Number.isSafeInteger(size) || size < 1 || size > limit) return Promise.reject(/* @__PURE__ */ new Error("The trace file exceeds the permitted size."));
417
+ const name = kind === "trace" ? `trace-${recordingStamp}.jsonl` : `window-${recordingStamp}-${source.sequence ?? 0}.png`;
418
+ return enqueue([], (target) => place(target, name, async (temporary) => {
419
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await target.fs.writeFile(temporary, /* @__PURE__ */ new Uint8Array(), target.context));
420
+ const chunks = [];
421
+ for (let offset = 0; offset < size; offset += require_extensionService.COMPUTER_USE_RECORDING_CHUNK_BYTES) {
422
+ target.check();
423
+ const end = Math.min(offset + require_extensionService.COMPUTER_USE_RECORDING_CHUNK_BYTES, size) - 1;
424
+ const response = await source.read(`bytes=${offset}-${end}`);
425
+ if (response.status !== 206 || response.headers.get("content-range") !== `bytes ${offset}-${end}/${size}`) throw new Error("The trace file is unavailable or changed.");
426
+ const bytes = new Uint8Array(await response.arrayBuffer());
427
+ if (bytes.byteLength !== end - offset + 1) throw new Error("The trace file response is incomplete.");
428
+ chunks.push(bytes);
597
429
  }
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());
430
+ const all = Buffer.concat(chunks);
431
+ if (kind === "window" && !all.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) throw new Error("The window image is not a PNG.");
432
+ if (kind === "trace") new TextDecoder("utf-8", { fatal: true }).decode(all);
433
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await target.fs.appendFile(temporary, all, target.context));
434
+ }), signal);
435
+ },
436
+ /** Copies a finished recording in the host store's own bounded ranges and returns its `artifact:` path. */
437
+ saveRecording(source, signal) {
438
+ const size = source.sizeBytes;
439
+ if (!Number.isSafeInteger(size) || size < 1 || size > 134217728) return Promise.reject(/* @__PURE__ */ new Error("The recording exceeds the permitted size."));
440
+ return enqueue([], (target) => place(target, `recording-${stamp()}.mp4`, async (temporary) => {
441
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await target.fs.writeFile(temporary, /* @__PURE__ */ new Uint8Array(), target.context));
442
+ for (let offset = 0; offset < size; offset += require_extensionService.COMPUTER_USE_RECORDING_CHUNK_BYTES) {
443
+ target.check();
444
+ const end = Math.min(offset + require_extensionService.COMPUTER_USE_RECORDING_CHUNK_BYTES, size) - 1;
445
+ const response = await source.read(`bytes=${offset}-${end}`);
446
+ if (response.status !== 206 || response.headers.get("content-range") !== `bytes ${offset}-${end}/${size}`) throw new Error("The recording is unavailable or changed.");
447
+ const bytes = new Uint8Array(await response.arrayBuffer());
448
+ if (bytes.byteLength !== end - offset + 1) throw new Error("The recording response is incomplete.");
449
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await target.fs.appendFile(temporary, bytes, target.context));
450
+ }
451
+ }), signal);
609
452
  }
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);
453
+ };
625
454
  }
626
455
  //#endregion
627
456
  //#region src/services/computerUseServer/index.ts
@@ -629,6 +458,7 @@ function createComputerUseApi(options) {
629
458
  const SOURCE = "@agimon-ai/po-computer-use";
630
459
  const SCRIPT_PATHS_ENV = "PO_COMPUTER_USE_SCRIPT_PATHS";
631
460
  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.";
461
+ const NOT_ACTIVE = "Computer use is not active for this session.";
632
462
  function output(value, isError = false) {
633
463
  return {
634
464
  content: [{
@@ -640,21 +470,29 @@ function output(value, isError = false) {
640
470
  };
641
471
  }
642
472
  function createComputerUseServer(host, apiContext) {
473
+ let localeContext;
474
+ const t = (key, fallback, vars) => (localeContext && (0, _agimon_ai_po_core_locale.readPoLang)(localeContext)?.t((0, _agimon_ai_po_core_locale.readPoPersonLocale)(localeContext)?.read(), key, fallback, vars)) ?? (0, _agimon_ai_po_core_locale.formatMessage)(fallback, vars);
475
+ const bindLocale = (context) => {
476
+ localeContext = context;
477
+ context.effect(() => () => {
478
+ localeContext = void 0;
479
+ });
480
+ };
643
481
  if (!apiContext?.computerUse?.available || !apiContext.directEvents) return {
644
482
  tools: [],
645
483
  commands: []
646
484
  };
647
485
  const desktop = apiContext.computerUse;
648
- const broker = createComputerUseApi({
486
+ let profileRuntime;
487
+ const broker = require_extensionService.createComputerUseApi({
649
488
  sessionId: host.context.sessionId,
650
489
  internalToken: apiContext.internalToken,
651
490
  hubToken: apiContext.hubToken,
652
491
  directEvents: apiContext.directEvents,
653
492
  desktop,
654
- beforeActivate: async () => {
655
- if (!modeSelected()) throw new Error("Enable computer use before authorizing an application.");
656
- const activity = await host.context.session.activity();
657
- if (!activity.isIdle || activity.hasPendingMessages) throw new Error("Wait for the agent and its queued prompts to finish before granting computer use.");
493
+ profileRuntime: () => profileRuntime,
494
+ beforeActivate: () => {
495
+ if (!modeSelected()) throw new Error("Enable computer use mode before requesting control.");
658
496
  }
659
497
  });
660
498
  const client = broker.sessionClient();
@@ -670,22 +508,96 @@ function createComputerUseServer(host, apiContext) {
670
508
  };
671
509
  let state = broker.state();
672
510
  const restrictionListeners = /* @__PURE__ */ new Set();
511
+ let codemodeLive = false;
673
512
  let stopActivity;
674
513
  let modeOwner;
675
- const modeSelected = () => (host.context.selection.state?.["minor-mode"] ?? []).includes(COMPUTER_USE_MODE_ID);
514
+ const lifetime = new AbortController();
515
+ let artifactBinding;
516
+ const artifacts = createComputerUseArtifacts(host.context.sessionId, host.context.environment ?? {}, () => artifactBinding, lifetime.signal);
517
+ const savedRecordings = /* @__PURE__ */ new Set();
518
+ const saveRecording = (artifact) => {
519
+ const fetchRecording = desktop.fetchRecording?.bind(desktop);
520
+ if (artifact?.status === "failed" && !savedRecordings.has(artifact.artifactId)) {
521
+ savedRecordings.add(artifact.artifactId);
522
+ Promise.resolve().then(() => host.context.client.notify({
523
+ body: `The computer-use recording failed: ${artifact.failure?.message ?? "no detail was reported."}`,
524
+ localization: { body: {
525
+ key: "computerUse.notification.recordingFailed",
526
+ fallback: "The computer-use recording failed: {error}",
527
+ vars: { error: artifact.failure?.message ?? t("computerUse.notification.noDetail", "no detail was reported.") }
528
+ } },
529
+ level: "warning"
530
+ })).catch(() => void 0);
531
+ return;
532
+ }
533
+ if (artifact?.status !== "ready" || !artifact.sizeBytes || !fetchRecording || savedRecordings.has(artifact.artifactId)) return;
534
+ savedRecordings.add(artifact.artifactId);
535
+ const { artifactId, sizeBytes } = artifact;
536
+ const extras = [...artifact.trace ? [{
537
+ kind: "trace",
538
+ file: artifact.trace
539
+ }] : [], ...(artifact.windows ?? []).slice(0, 32).map((file) => ({
540
+ kind: "window",
541
+ file
542
+ }))];
543
+ const label = artifactId.replace(/[^A-Za-z0-9_-]/gu, "").slice(0, 16) || "trace";
544
+ for (const { kind, file } of extras) artifacts.saveTraceFile(kind, {
545
+ artifactId: file.artifactId,
546
+ sizeBytes: file.sizeBytes,
547
+ ...file.sequence === void 0 ? {} : { sequence: file.sequence },
548
+ read: (range) => fetchRecording(file.artifactId, range)
549
+ }, label).catch((error) => {
550
+ if (lifetime.signal.aborted) return;
551
+ return host.context.client.notify({
552
+ body: `A computer-use trace file was not saved to artifacts: ${error instanceof Error ? error.message : String(error)}`,
553
+ localization: { body: {
554
+ key: "computerUse.notification.traceNotSaved",
555
+ fallback: "A computer-use trace file was not saved to artifacts: {error}",
556
+ vars: { error: error instanceof Error ? error.message : String(error) }
557
+ } },
558
+ level: "warning"
559
+ });
560
+ }).catch(() => void 0);
561
+ artifacts.saveRecording({
562
+ artifactId,
563
+ sizeBytes,
564
+ read: (range) => fetchRecording(artifactId, range)
565
+ }).then((saved) => host.context.client.notify({
566
+ body: `Computer-use recording saved to ${saved}.`,
567
+ localization: { body: {
568
+ key: "computerUse.notification.recordingSaved",
569
+ fallback: "Computer-use recording saved to {path}.",
570
+ vars: { path: saved }
571
+ } },
572
+ level: "info"
573
+ }), (error) => {
574
+ if (lifetime.signal.aborted) return;
575
+ return host.context.client.notify({
576
+ body: `The computer-use recording was not saved to artifacts: ${error instanceof Error ? error.message : String(error)}`,
577
+ localization: { body: {
578
+ key: "computerUse.notification.recordingNotSaved",
579
+ fallback: "The computer-use recording was not saved to artifacts: {error}",
580
+ vars: { error: error instanceof Error ? error.message : String(error) }
581
+ } },
582
+ level: "warning"
583
+ });
584
+ }).catch(() => void 0);
585
+ };
586
+ const modeSelected = () => (host.context.selection.state?.["mode"] ?? []).includes(require_extensionService.COMPUTER_USE_MODE_ID);
676
587
  const publishMode = () => modeOwner?.publish();
677
588
  const applyState = (next) => {
678
589
  state = next;
679
- host.context.client.setStatus(COMPUTER_USE_STATUS_KEY, next === void 0 || next.phase === "inactive" ? void 0 : `computer use: ${next.phase}`);
590
+ saveRecording(next?.artifact);
591
+ host.context.client.setStatus(require_extensionService.COMPUTER_USE_STATUS_KEY, next === void 0 || next.phase === "inactive" ? void 0 : `computer use: ${next.phase}`);
680
592
  publishMode();
681
593
  for (const listener of restrictionListeners) listener();
682
594
  };
683
595
  const selectMode = async (enabled) => {
684
- const modes = (host.context.selection.state?.["minor-mode"] ?? []).filter((mode) => mode !== COMPUTER_USE_MODE_ID);
596
+ const modes = (host.context.selection.state?.["mode"] ?? []).filter((mode) => mode !== require_extensionService.COMPUTER_USE_MODE_ID);
685
597
  await host.changeSelection({
686
598
  axis: "state",
687
- key: "minor-mode",
688
- values: enabled ? [...modes, COMPUTER_USE_MODE_ID] : modes
599
+ key: "mode",
600
+ values: enabled ? [...modes, require_extensionService.COMPUTER_USE_MODE_ID] : modes
689
601
  });
690
602
  publishMode();
691
603
  };
@@ -700,36 +612,209 @@ function createComputerUseServer(host, apiContext) {
700
612
  applyState(void 0);
701
613
  }
702
614
  };
615
+ const isActive = () => desktop.available && desktop.enabled !== false && modeSelected() && state?.phase === "active";
703
616
  const requireActive = () => {
704
- if (!desktop.available || desktop.enabled === false || !modeSelected() || state?.phase !== "active") throw new Error("Computer use is not active for this session.");
617
+ if (!isActive()) throw new Error(NOT_ACTIVE);
705
618
  return client;
706
619
  };
707
- modeOwner = (0, _agimon_ai_po_minor_mode.defineMinorMode)({
620
+ const canRequest = () => desktop.available && desktop.enabled !== false && desktop.claimApproved !== void 0 && modeSelected();
621
+ const windowFields = {
622
+ bundleId: 512,
623
+ applicationName: 256,
624
+ windowId: 256,
625
+ windowTitle: 1024
626
+ };
627
+ const isWindow = (target) => Object.keys(target).length === 5 && Number.isSafeInteger(target.processId) && target.processId > 0 && Object.entries(windowFields).every(([key, max]) => {
628
+ const value = target[key];
629
+ return typeof value === "string" && value.trim().length > 0 && value.length <= max;
630
+ });
631
+ const isDesktop = (target) => Object.keys(target).length === 1 && target.scope === "desktop";
632
+ const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
633
+ const readRequest = (input) => {
634
+ if (!canRequest()) throw new Error("Enable computer use before requesting control.");
635
+ if (state?.phase !== "inactive" && state?.phase !== "failed") throw new Error("Computer use is already busy.");
636
+ const request = record(input);
637
+ if (!request || Object.keys(request).some((key) => ![
638
+ "target",
639
+ "durationMinutes",
640
+ "reason",
641
+ "keepTrace"
642
+ ].includes(key))) throw new Error("Supply a target, duration and reason for computer use.");
643
+ const target = record(request.target);
644
+ if (!target || !isDesktop(target) && !isWindow(target)) throw new Error("Choose a target from computer.targets().");
645
+ const { durationMinutes, reason, keepTrace } = request;
646
+ if (durationMinutes !== 5 && durationMinutes !== 15 && durationMinutes !== 30) throw new Error("Choose 5, 15 or 30 minutes for computer use.");
647
+ if (typeof reason !== "string" || !reason.trim() || reason.length > 400) throw new Error("Give a reason for requesting computer use, up to 400 characters.");
648
+ if (keepTrace !== void 0 && (typeof keepTrace !== "boolean" || keepTrace && isDesktop(target))) throw new Error("Extra trace capture is only available for one approved window.");
649
+ return {
650
+ target,
651
+ durationMinutes,
652
+ reason,
653
+ keepTrace: keepTrace === true
654
+ };
655
+ };
656
+ const targetInventory = async (signal) => {
657
+ signal.throwIfAborted();
658
+ if (!canRequest()) throw new Error("Enable computer use before listing targets.");
659
+ const windows = await desktop.targets?.(signal);
660
+ signal.throwIfAborted();
661
+ if (!canRequest()) throw new Error("Computer use is no longer enabled.");
662
+ return [{ scope: "desktop" }, ...Array.isArray(windows) ? windows.flatMap((window) => {
663
+ const candidate = record(window);
664
+ return candidate && isWindow(candidate) ? [{ ...candidate }] : [];
665
+ }) : []];
666
+ };
667
+ const requestPolicy = {
668
+ requirement: "human",
669
+ ownerOnly: true,
670
+ resolve: ([input]) => [readRequest(input)],
671
+ describe(input) {
672
+ const { target, durationMinutes, reason, keepTrace } = readRequest(input);
673
+ const labelText = (label) => {
674
+ switch (label) {
675
+ case "Application": return t("computerUse.approval.application", "Application");
676
+ case "Window": return t("computerUse.approval.window", "Window");
677
+ case "Bundle ID": return t("computerUse.approval.bundleId", "Bundle ID");
678
+ case "Process ID": return t("computerUse.approval.processId", "Process ID");
679
+ case "Window ID": return t("computerUse.approval.windowId", "Window ID");
680
+ case "Reason": return t("computerUse.approval.reason", "Reason");
681
+ default: return label;
682
+ }
683
+ };
684
+ const content = [];
685
+ const detail = (label, value) => {
686
+ if (value.length <= 300) return {
687
+ label: labelText(label),
688
+ value
689
+ };
690
+ content.push(`${label}:\n${value}`);
691
+ return {
692
+ label: labelText(label),
693
+ value: t("computerUse.approval.fullValue", "See full {label} below.", { label: labelText(label).toLowerCase() })
694
+ };
695
+ };
696
+ const details = isDesktop(target) ? [{
697
+ label: t("computerUse.approval.target", "Target"),
698
+ value: t("computerUse.approval.wholeDesktop", "Whole desktop")
699
+ }] : [
700
+ detail("Application", String(target.applicationName)),
701
+ detail("Window", String(target.windowTitle)),
702
+ detail("Bundle ID", String(target.bundleId)),
703
+ detail("Process ID", String(target.processId)),
704
+ detail("Window ID", String(target.windowId))
705
+ ];
706
+ const reasonDetail = detail("Reason", reason);
707
+ const fullContent = content.join("\n\n");
708
+ if (fullContent.length > 65536) throw new Error("Computer-use approval content is too long.");
709
+ return {
710
+ source: t("computerUse.approval.source", "Computer use"),
711
+ title: t("computerUse.approval.title", "Let Po control your computer"),
712
+ summary: isDesktop(target) ? t("computerUse.approval.desktopSummary", "Po can see and control your whole desktop for {minutes} minutes.", { minutes: durationMinutes }) : t("computerUse.approval.windowSummary", "Po can see and control the selected window for {minutes} minutes.", { minutes: durationMinutes }),
713
+ details: [
714
+ ...details,
715
+ {
716
+ label: t("computerUse.approval.duration", "Duration"),
717
+ value: t("computerUse.approval.minutes", "{minutes} minutes", { minutes: durationMinutes })
718
+ },
719
+ reasonDetail,
720
+ {
721
+ label: t("computerUse.approval.recording", "Recording"),
722
+ value: keepTrace ? t("computerUse.approval.recordingWithTrace", "Screen and audio recording, action trace and window images") : t("computerUse.approval.recordingOn", "Screen and audio recording on")
723
+ },
724
+ {
725
+ label: t("computerUse.approval.savedTo", "Saved to"),
726
+ value: t("computerUse.approval.location", "This session’s artifacts, in computer-use/.")
727
+ },
728
+ {
729
+ label: t("computerUse.approval.whoCanOpen", "Who can open it"),
730
+ value: t("computerUse.approval.access", "The session’s agent and paired clients can access session artifacts.")
731
+ },
732
+ {
733
+ label: t("computerUse.approval.stop", "Stop"),
734
+ value: t("computerUse.approval.stopHint", "You can stop control at any time in Activity.")
735
+ }
736
+ ],
737
+ ...fullContent ? { content: fullContent } : {}
738
+ };
739
+ }
740
+ };
741
+ const requestOperations = {
742
+ policy: requestPolicy,
743
+ targets: targetInventory,
744
+ async activate(input, approvalId, signal) {
745
+ if (!approvalId) throw new Error("Human approval is required before taking control.");
746
+ signal.throwIfAborted();
747
+ const { target, durationMinutes, keepTrace } = readRequest(input);
748
+ if (!isDesktop(target) && !(await targetInventory(signal)).some((candidate) => Object.entries(target).every(([key, value]) => candidate[key] === value))) throw new Error("The approved window is no longer available. Request approval for a current target.");
749
+ signal.throwIfAborted();
750
+ const { requestId } = broker.activateApproved(approvalId, target, durationMinutes * 6e4, keepTrace);
751
+ const deadline = AbortSignal.any([
752
+ signal,
753
+ AbortSignal.timeout(3e4),
754
+ lifetime.signal
755
+ ]);
756
+ let unsubscribe;
757
+ let abort;
758
+ try {
759
+ return await new Promise((resolve, reject) => {
760
+ const inspect = (next) => {
761
+ if (next.phase === "failed") reject(new Error(next.failure?.message ?? "Computer use could not start."));
762
+ else if (next.requestId !== requestId || next.phase === "stopping") reject(/* @__PURE__ */ new Error("Computer use was cancelled before it started."));
763
+ else if (next.phase === "active") resolve({
764
+ phase: next.phase,
765
+ target: next.target,
766
+ expiresAt: next.expiresAt
767
+ });
768
+ };
769
+ abort = () => reject(/* @__PURE__ */ new Error("Computer use did not start before the approval execution ended."));
770
+ unsubscribe = client.subscribeStatus?.(inspect);
771
+ deadline.addEventListener("abort", abort, { once: true });
772
+ if (deadline.aborted) abort();
773
+ else inspect(broker.state());
774
+ });
775
+ } catch (error) {
776
+ if (deadline.aborted && broker.state().requestId === requestId) await client.stop();
777
+ throw error;
778
+ } finally {
779
+ unsubscribe?.();
780
+ if (abort) deadline.removeEventListener("abort", abort);
781
+ }
782
+ }
783
+ };
784
+ modeOwner = (0, _agimon_ai_po_mode.defineMode)({
708
785
  descriptor: {
709
786
  source: SOURCE,
710
- id: COMPUTER_USE_MODE_ID,
787
+ id: require_extensionService.COMPUTER_USE_MODE_ID,
711
788
  label: "Computer Use",
789
+ labelKey: "mode.computer-use.computerUse",
712
790
  description: "Session-scoped semantic control through Po Desktop.",
791
+ descriptionKey: "mode.computer-use.sessionScopedSemanticControlThroughPoDesktop",
713
792
  order: 450,
714
793
  actions: [
715
794
  {
716
795
  id: "activate",
717
796
  label: "Activate",
797
+ labelKey: "mode.computer-use.activate",
718
798
  description: "Enable computer use for this session.",
799
+ descriptionKey: "mode.computer-use.enableComputerUseForThisSession",
719
800
  contexts: ["headless"],
720
801
  parameters: []
721
802
  },
722
803
  {
723
804
  id: "deactivate",
724
805
  label: "Deactivate",
806
+ labelKey: "mode.computer-use.deactivate",
725
807
  description: "Stop this session computer-use run.",
808
+ descriptionKey: "mode.computer-use.stopThisSessionComputerUseRun",
726
809
  contexts: ["headless"],
727
810
  parameters: []
728
811
  },
729
812
  {
730
813
  id: "doctor",
731
814
  label: "Doctor",
815
+ labelKey: "mode.computer-use.doctor",
732
816
  description: "Report Desktop availability and session state.",
817
+ descriptionKey: "mode.computer-use.reportDesktopAvailabilityAndSessionState",
733
818
  contexts: ["headless"],
734
819
  parameters: []
735
820
  }
@@ -741,11 +826,11 @@ function createComputerUseServer(host, apiContext) {
741
826
  ...mode,
742
827
  condition: "blocked",
743
828
  detail: "Enable computer use in global Desktop settings.",
744
- actions: mode.actions.map((action) => ({
829
+ actions: mode.actions.map((action) => action.id === "deactivate" ? action : {
745
830
  ...action,
746
831
  enabled: false,
747
832
  disabledReason: "Enable computer use in global Desktop settings."
748
- }))
833
+ })
749
834
  } : mode;
750
835
  },
751
836
  async handleAction(_runtime, actionId, _argumentsValue, execution) {
@@ -754,7 +839,7 @@ function createComputerUseServer(host, apiContext) {
754
839
  if (!desktop.available || desktop.enabled === false) throw new Error("Enable computer use in global Desktop settings first.");
755
840
  await selectMode(true);
756
841
  await refresh(execution.signal);
757
- return { message: "Computer use is ready to configure in Activity." };
842
+ return { message: t("computerUse.mode.activated", "Computer use is on. Po asks for approval before it takes control.") };
758
843
  }
759
844
  if (actionId === "doctor") {
760
845
  await refresh(execution.signal);
@@ -764,30 +849,141 @@ function createComputerUseServer(host, apiContext) {
764
849
  if (client && state?.phase !== void 0 && state.phase !== "inactive" && state.phase !== "failed") await client.stop(execution.signal);
765
850
  await selectMode(false);
766
851
  await refresh(execution.signal);
767
- return { message: "Computer use deactivated." };
852
+ return { message: t("computerUse.mode.deactivated", "Computer use deactivated.") };
768
853
  }
769
854
  throw new Error(`Unknown computer-use action: ${actionId}`);
770
855
  }
771
856
  }).createOwner(void 0);
857
+ const handlers = {
858
+ async state(parameters, signal) {
859
+ try {
860
+ const { saveScreenshot, ...query } = parameters;
861
+ const save = saveScreenshot === true;
862
+ const observation = await requireActive().observe(signal, {
863
+ ...query,
864
+ includeScreenshot: save || parameters.includeScreenshot !== false
865
+ });
866
+ if (!save) return computerObservationOutput(observation);
867
+ if (!observation.screenshot) throw new Error("Desktop returned no screenshot to save.");
868
+ const screenshotArtifact = await artifacts.saveScreenshot(observation.screenshot.data, observation.runId, signal);
869
+ return computerObservationOutput({
870
+ ...observation,
871
+ ...parameters.includeScreenshot === false ? { screenshot: void 0 } : {},
872
+ screenshotArtifact
873
+ });
874
+ } catch (error) {
875
+ return output(error instanceof Error ? error.message : String(error), true);
876
+ }
877
+ },
878
+ async act(parameters, signal) {
879
+ try {
880
+ const result = await requireActive().act(parameters, signal);
881
+ await refresh(signal);
882
+ return output(result);
883
+ } catch (error) {
884
+ return output(error instanceof Error ? error.message : String(error), true);
885
+ }
886
+ },
887
+ async run(parameters, signal) {
888
+ try {
889
+ requireActive();
890
+ if (!dependencies.scriptRunner) throw new Error("Computer script execution is unavailable.");
891
+ return computerScriptOutput(await dependencies.scriptRunner.execute(parameters.scriptPath, parameters.input, signal, parameters));
892
+ } catch (error) {
893
+ return computerScriptFailure(error);
894
+ }
895
+ },
896
+ async stop(signal) {
897
+ await requireActive().stop(signal);
898
+ await refresh(signal);
899
+ return { phase: state?.phase ?? "inactive" };
900
+ }
901
+ };
772
902
  const unsubscribeState = client.subscribeStatus?.(applyState);
773
903
  return {
774
904
  api: [{
775
- basePath: API_BASE_PATH,
905
+ basePath: require_extensionService.API_BASE_PATH,
776
906
  start: () => broker
777
907
  }],
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
- }],
908
+ services: [
909
+ bindLocale,
910
+ (context) => {
911
+ context.inject(["po/profile-runtime"], (child) => {
912
+ const profile = child.get("po/profile-runtime");
913
+ profileRuntime = profile;
914
+ return () => {
915
+ if (profileRuntime === profile) profileRuntime = void 0;
916
+ };
917
+ });
918
+ },
919
+ (context) => {
920
+ context.inject([_agimon_ai_po_core_platform.PO_FS_SERVICE, require_extensionService.COMPUTER_USE_ARTIFACTS_SERVICE], (child) => {
921
+ const controller = new AbortController();
922
+ const binding = {
923
+ fs: (0, _agimon_ai_po_core_platform.requirePoFs)(child),
924
+ storage: child.get(require_extensionService.COMPUTER_USE_ARTIFACTS_SERVICE),
925
+ signal: controller.signal
926
+ };
927
+ artifactBinding = binding;
928
+ return () => {
929
+ controller.abort();
930
+ if (artifactBinding === binding) artifactBinding = void 0;
931
+ };
932
+ });
933
+ },
934
+ (context) => {
935
+ const fiber = context.plugin((0, _agimon_ai_po_mode.serverModes)([modeOwner]));
936
+ context.effect(() => desktop.subscribe(() => {
937
+ if (!desktop.available) fiber.dispose();
938
+ }));
939
+ },
940
+ (context) => {
941
+ context.inject([_agimon_ai_po_core_codemode.PO_CODEMODE_SERVICE], (scoped) => {
942
+ const codemode = (0, _agimon_ai_po_core_codemode.readPoCodemode)(scoped);
943
+ if (!codemode) return void 0;
944
+ const restriction = host.registerToolRestriction({ excludedTools: [...require_extensionService.COMPUTER_USE_TOOL_NAMES, ...require_extensionService.COMPUTER_USE_REQUEST_TOOL_NAMES] });
945
+ let registration;
946
+ let namespaceLifetime;
947
+ let activeGrant = false;
948
+ const revoke = () => {
949
+ namespaceLifetime?.abort(/* @__PURE__ */ new Error(NOT_ACTIVE));
950
+ namespaceLifetime = void 0;
951
+ registration?.dispose();
952
+ registration = void 0;
953
+ codemodeLive = false;
954
+ };
955
+ const sync = () => {
956
+ const active = isActive();
957
+ const ready = canRequest();
958
+ if (registration && (!ready || active !== activeGrant)) revoke();
959
+ if (ready && !registration) {
960
+ namespaceLifetime = new AbortController();
961
+ registration = codemode.register(SOURCE, createComputerNamespace({
962
+ sessionId: host.context.sessionId,
963
+ request: requestOperations,
964
+ operations: active ? handlers : void 0,
965
+ isActive,
966
+ lifetime: namespaceLifetime.signal
967
+ }));
968
+ activeGrant = active;
969
+ codemodeLive = true;
970
+ }
971
+ };
972
+ restrictionListeners.add(sync);
973
+ const unsubscribeDesktop = desktop.subscribe(sync);
974
+ sync();
975
+ return () => {
976
+ unsubscribeDesktop();
977
+ restrictionListeners.delete(sync);
978
+ revoke();
979
+ restriction.dispose();
980
+ };
981
+ });
982
+ }
983
+ ],
784
984
  toolRestrictions: [{
785
985
  source: SOURCE,
786
- restrict: () => ({ excludedTools: desktop.available && desktop.enabled !== false && modeSelected() && state?.phase === "active" ? [] : [
787
- "computer_state",
788
- "computer_action",
789
- "computer_exec"
790
- ] }),
986
+ restrict: () => ({ excludedTools: [...isActive() ? [] : require_extensionService.COMPUTER_USE_TOOL_NAMES, ...canRequest() ? [] : require_extensionService.COMPUTER_USE_REQUEST_TOOL_NAMES] }),
791
987
  subscribe: (listener) => {
792
988
  restrictionListeners.add(listener);
793
989
  return () => {
@@ -797,10 +993,10 @@ function createComputerUseServer(host, apiContext) {
797
993
  }],
798
994
  activities: [{
799
995
  when: {
800
- state: { "minor-mode": COMPUTER_USE_MODE_ID },
996
+ state: { mode: require_extensionService.COMPUTER_USE_MODE_ID },
801
997
  attribution: {
802
- kind: "minor",
803
- mode: COMPUTER_USE_MODE_ID
998
+ kind: "mode",
999
+ name: require_extensionService.COMPUTER_USE_MODE_ID
804
1000
  }
805
1001
  },
806
1002
  name: SOURCE,
@@ -816,42 +1012,121 @@ function createComputerUseServer(host, apiContext) {
816
1012
  }
817
1013
  }],
818
1014
  tools: [
1015
+ {
1016
+ when: { state: { mode: require_extensionService.COMPUTER_USE_MODE_ID } },
1017
+ name: "computer_targets",
1018
+ label: "Computer Use Targets",
1019
+ description: "List targets for an approval request, without reading any screen contents.",
1020
+ parameters: {
1021
+ type: "object",
1022
+ properties: {},
1023
+ additionalProperties: false
1024
+ },
1025
+ mainAgentOnly: true,
1026
+ async execute(_id, _parameters, signal) {
1027
+ return output(await targetInventory(signal ?? lifetime.signal));
1028
+ }
1029
+ },
1030
+ {
1031
+ when: { state: { mode: require_extensionService.COMPUTER_USE_MODE_ID } },
1032
+ name: "computer_request",
1033
+ label: "Request Computer Use",
1034
+ description: "Ask for a recorded computer-use grant. Requires human approval before any access.",
1035
+ parameters: {
1036
+ type: "object",
1037
+ properties: {
1038
+ target: {
1039
+ type: "object",
1040
+ description: "The exact target returned by computer_targets."
1041
+ },
1042
+ durationMinutes: {
1043
+ type: "integer",
1044
+ enum: [
1045
+ 5,
1046
+ 15,
1047
+ 30
1048
+ ]
1049
+ },
1050
+ reason: {
1051
+ type: "string",
1052
+ minLength: 1,
1053
+ maxLength: 400
1054
+ },
1055
+ keepTrace: { type: "boolean" }
1056
+ },
1057
+ required: [
1058
+ "target",
1059
+ "durationMinutes",
1060
+ "reason"
1061
+ ],
1062
+ additionalProperties: false
1063
+ },
1064
+ mainAgentOnly: true,
1065
+ approval: requestPolicy,
1066
+ async execute(_id, parameters, signal, _update, execution) {
1067
+ if (execution?.sessionId !== host.context.sessionId) throw new Error("Computer use belongs to another session.");
1068
+ return output(await requestOperations.activate(parameters, execution.approvedCall?.approvalId, signal ?? lifetime.signal));
1069
+ }
1070
+ },
819
1071
  {
820
1072
  when: {
821
- state: { "minor-mode": COMPUTER_USE_MODE_ID },
1073
+ state: { mode: require_extensionService.COMPUTER_USE_MODE_ID },
822
1074
  attribution: {
823
- kind: "minor",
824
- mode: COMPUTER_USE_MODE_ID
1075
+ kind: "mode",
1076
+ name: require_extensionService.COMPUTER_USE_MODE_ID
825
1077
  }
826
1078
  },
827
1079
  name: "computer_state",
828
1080
  label: "Computer State",
829
- description: "Observe the authorized application window and return semantic accessibility state.",
1081
+ 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
1082
  parameters: {
831
1083
  type: "object",
832
- properties: { includeScreenshot: { type: "boolean" } },
1084
+ properties: {
1085
+ includeScreenshot: { type: "boolean" },
1086
+ saveScreenshot: { type: "boolean" },
1087
+ root: {
1088
+ type: "string",
1089
+ minLength: 1,
1090
+ maxLength: 256
1091
+ },
1092
+ label: {
1093
+ type: "string",
1094
+ minLength: 1,
1095
+ maxLength: 256
1096
+ },
1097
+ role: {
1098
+ type: "string",
1099
+ minLength: 1,
1100
+ maxLength: 256
1101
+ },
1102
+ skeleton: { type: "boolean" },
1103
+ offset: {
1104
+ type: "integer",
1105
+ minimum: 0,
1106
+ maximum: 2e3
1107
+ },
1108
+ limit: {
1109
+ type: "integer",
1110
+ minimum: 1,
1111
+ maximum: 500
1112
+ }
1113
+ },
833
1114
  additionalProperties: false
834
1115
  },
835
1116
  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
- }
1117
+ execute: (_toolCallId, parameters, signal) => handlers.state(parameters, signal)
843
1118
  },
844
1119
  {
845
1120
  when: {
846
- state: { "minor-mode": COMPUTER_USE_MODE_ID },
1121
+ state: { mode: require_extensionService.COMPUTER_USE_MODE_ID },
847
1122
  attribution: {
848
- kind: "minor",
849
- mode: COMPUTER_USE_MODE_ID
1123
+ kind: "mode",
1124
+ name: require_extensionService.COMPUTER_USE_MODE_ID
850
1125
  }
851
1126
  },
852
1127
  name: "computer_action",
853
1128
  label: "Computer Action",
854
- description: "Perform one constrained semantic action in the authorized application window.",
1129
+ 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
1130
  parameters: {
856
1131
  type: "object",
857
1132
  properties: {
@@ -861,9 +1136,20 @@ function createComputerUseServer(host, apiContext) {
861
1136
  "press",
862
1137
  "focus",
863
1138
  "set_value",
864
- "scroll"
1139
+ "scroll",
1140
+ "perform",
1141
+ "launch",
1142
+ "expand",
1143
+ "collapse",
1144
+ "toggle",
1145
+ "check",
1146
+ "uncheck",
1147
+ "select",
1148
+ "scroll_to",
1149
+ "type"
865
1150
  ]
866
1151
  },
1152
+ text: { type: "string" },
867
1153
  snapshotId: {
868
1154
  type: "string",
869
1155
  minLength: 1
@@ -882,35 +1168,36 @@ function createComputerUseServer(host, apiContext) {
882
1168
  "right"
883
1169
  ]
884
1170
  },
885
- amount: {
1171
+ amount: { anyOf: [{
886
1172
  type: "string",
887
1173
  enum: ["line", "page"]
1174
+ }, {
1175
+ type: "integer",
1176
+ minimum: 1,
1177
+ maximum: 100
1178
+ }] },
1179
+ action: {
1180
+ type: "string",
1181
+ pattern: "^AX[A-Za-z]{1,62}$"
1182
+ },
1183
+ app: {
1184
+ type: "string",
1185
+ minLength: 1,
1186
+ maxLength: 256
888
1187
  }
889
1188
  },
890
- required: [
891
- "kind",
892
- "snapshotId",
893
- "elementRef"
894
- ],
1189
+ required: ["kind"],
895
1190
  additionalProperties: false
896
1191
  },
897
1192
  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
- }
1193
+ execute: (_toolCallId, parameters, signal) => handlers.act(parameters, signal)
907
1194
  },
908
1195
  {
909
1196
  when: {
910
- state: { "minor-mode": COMPUTER_USE_MODE_ID },
1197
+ state: { mode: require_extensionService.COMPUTER_USE_MODE_ID },
911
1198
  attribution: {
912
- kind: "minor",
913
- mode: COMPUTER_USE_MODE_ID
1199
+ kind: "mode",
1200
+ name: require_extensionService.COMPUTER_USE_MODE_ID
914
1201
  }
915
1202
  },
916
1203
  name: "computer_exec",
@@ -931,16 +1218,7 @@ function createComputerUseServer(host, apiContext) {
931
1218
  additionalProperties: false
932
1219
  },
933
1220
  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
- }
1221
+ execute: (_toolCallId, parameters, signal) => handlers.run(parameters, signal)
944
1222
  }
945
1223
  ],
946
1224
  commands: [{
@@ -956,8 +1234,8 @@ function createComputerUseServer(host, apiContext) {
956
1234
  await client.stop();
957
1235
  await host.changeSelection({
958
1236
  axis: "state",
959
- key: "minor-mode",
960
- values: (execution.selection.state?.["minor-mode"] ?? []).filter((mode) => mode !== COMPUTER_USE_MODE_ID)
1237
+ key: "mode",
1238
+ values: (execution.selection.state?.["mode"] ?? []).filter((mode) => mode !== require_extensionService.COMPUTER_USE_MODE_ID)
961
1239
  });
962
1240
  await refresh();
963
1241
  }
@@ -965,23 +1243,23 @@ function createComputerUseServer(host, apiContext) {
965
1243
  }],
966
1244
  hooks: [{
967
1245
  when: {
968
- state: { "minor-mode": COMPUTER_USE_MODE_ID },
1246
+ state: { mode: require_extensionService.COMPUTER_USE_MODE_ID },
969
1247
  attribution: {
970
- kind: "minor",
971
- mode: COMPUTER_USE_MODE_ID
1248
+ kind: "mode",
1249
+ name: require_extensionService.COMPUTER_USE_MODE_ID
972
1250
  }
973
1251
  },
974
1252
  event: "before_agent_start",
975
1253
  handle(event) {
976
- if (state?.phase !== "active") return void 0;
977
- return { systemPrompt: `${typeof event.systemPrompt === "string" ? event.systemPrompt : ""}\n\n${GUIDANCE}`.trim() };
1254
+ if (!canRequest()) return void 0;
1255
+ return { systemPrompt: `${typeof event.systemPrompt === "string" ? event.systemPrompt : ""}\n\n${isActive() ? codemodeLive ? require_extensionService.COMPUTER_USE_CODEMODE_GUIDANCE : GUIDANCE : `Computer use mode is on. If the task requires it, use ${codemodeLive ? "computer.targets() then computer.request() in exec" : "computer_targets then computer_request"} to ask for the narrowest grant. Wait for the approval outcome before acting.`}`.trim() };
978
1256
  }
979
1257
  }, {
980
1258
  when: {
981
- state: { "minor-mode": COMPUTER_USE_MODE_ID },
1259
+ state: { mode: require_extensionService.COMPUTER_USE_MODE_ID },
982
1260
  attribution: {
983
- kind: "minor",
984
- mode: COMPUTER_USE_MODE_ID
1261
+ kind: "mode",
1262
+ name: require_extensionService.COMPUTER_USE_MODE_ID
985
1263
  }
986
1264
  },
987
1265
  event: "session_shutdown",
@@ -1000,7 +1278,8 @@ function createComputerUseServer(host, apiContext) {
1000
1278
  () => unsubscribeState?.(),
1001
1279
  () => broker.close(),
1002
1280
  () => restrictionListeners.clear(),
1003
- () => host.context.client.setStatus(COMPUTER_USE_STATUS_KEY, void 0)
1281
+ () => host.context.client.setStatus(require_extensionService.COMPUTER_USE_STATUS_KEY, void 0),
1282
+ () => lifetime.abort()
1004
1283
  ], "Computer-use cleanup failed.");
1005
1284
  }
1006
1285
  };
@@ -1024,6 +1303,43 @@ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)((cont
1024
1303
  };
1025
1304
  });
1026
1305
  //#endregion
1306
+ //#region src/services/desktopPermissionsApi/index.ts
1307
+ /**
1308
+ * Desktop's macOS permissions for the settings page.
1309
+ *
1310
+ * Hub-scoped because the permissions belong to the Mac, not a session. The server's
1311
+ * Desktop link reads and requests them; without Desktop the mount answers 404, so
1312
+ * the page can say so instead of guessing.
1313
+ */
1314
+ async function desktopPermissionsResponse(access, request) {
1315
+ const path = new URL(request.url).pathname;
1316
+ const change = request.method === require_extensionService.routes.requestDesktopPermission.method;
1317
+ if (path !== require_extensionService.routes.desktopPermissions.path || !change && request.method !== require_extensionService.routes.desktopPermissions.method) return Response.json({ error: "Not found." }, { status: 404 });
1318
+ if (access === void 0) return Response.json({ error: "Po Desktop is not running this server." }, { status: 404 });
1319
+ if (!access.authorize(request.headers, change)) return Response.json({ error: "Open Po Desktop on that Mac, or confirm with your passkey." }, { status: 403 });
1320
+ let permission;
1321
+ if (change) {
1322
+ const body = await request.json().catch(() => void 0);
1323
+ if (!require_extensionService.isDesktopPermission(body?.permission)) return Response.json({ error: "Name one permission to ask for." }, { status: 400 });
1324
+ permission = body.permission;
1325
+ }
1326
+ try {
1327
+ return Response.json(await access.request(permission));
1328
+ } catch (error) {
1329
+ return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 502 });
1330
+ }
1331
+ }
1332
+ //#endregion
1333
+ //#region src/extensions/(backend)/api/desktop-permissions/route.server.ts
1334
+ /** Mounts Desktop's macOS permissions at `desktop-permissions`, which the folder names. */
1335
+ var route_server_default$1 = (0, _agimon_ai_po_core_extensionFile.defineRoute)({
1336
+ basePath: "desktop-permissions",
1337
+ start: (context) => ({
1338
+ fetch: (request) => desktopPermissionsResponse(context.desktopPermissions, request),
1339
+ close: () => void 0
1340
+ })
1341
+ });
1342
+ //#endregion
1027
1343
  //#region src/services/webComputerUseAvailability/index.ts
1028
1344
  var MissingComputerUseApiError = class extends Error {};
1029
1345
  function computerUseSessionApiError(status, value) {
@@ -1035,12 +1351,14 @@ function computerUseSessionApiError(status, value) {
1035
1351
  //#region src/services/webComputerUseChannel/index.ts
1036
1352
  /** Computer use runs on the Po Desktop host, so every other client declines it. */
1037
1353
  const DESKTOP_UNAVAILABLE = "Po Desktop computer use is unavailable.";
1354
+ const SESSION_READY_ATTEMPTS = 5;
1355
+ const SESSION_READY_RETRY_MS = 200;
1038
1356
  function record(value) {
1039
1357
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1040
1358
  }
1041
1359
  function command(value) {
1042
1360
  const input = record(value);
1043
- return input?.action === "status" || input?.action === "targets" || input?.action === "stop" || input?.action === "artifacts" ? { action: input.action } : void 0;
1361
+ return input?.action === "status" || input?.action === "stop" ? { action: input.action } : void 0;
1044
1362
  }
1045
1363
  async function responseJson(response) {
1046
1364
  const value = await response.json();
@@ -1062,12 +1380,11 @@ function sessionState(value) {
1062
1380
  function createComputerUseChannel() {
1063
1381
  let receiveCommand;
1064
1382
  return {
1065
- frameType: computerUseChannelType,
1383
+ frameType: require_extensionService.computerUseChannelType,
1066
1384
  lifecycle: "hub",
1067
1385
  start(host) {
1068
1386
  const scopes = /* @__PURE__ */ new Map();
1069
1387
  const latest = /* @__PURE__ */ new Map();
1070
- const targets = /* @__PURE__ */ new Map();
1071
1388
  const grants = /* @__PURE__ */ new Map();
1072
1389
  const subscriptions = /* @__PURE__ */ new Map();
1073
1390
  const processing = /* @__PURE__ */ new Set();
@@ -1075,28 +1392,37 @@ function createComputerUseChannel() {
1075
1392
  const requests = /* @__PURE__ */ new Map();
1076
1393
  let activeSessionId;
1077
1394
  let closed = false;
1078
- const sessionRequest = async (scope, path, method = "GET", value) => host.requestSessionApi(scope, {
1079
- basePath: API_BASE_PATH,
1080
- path,
1081
- method,
1082
- ...value === void 0 ? {} : { body: JSON.stringify(value) }
1083
- });
1395
+ const sessionRequest = async (scope, path, method = "GET", value) => {
1396
+ const registeredScope = scopes.get(scope.sessionId);
1397
+ for (let attempt = 1;; attempt++) {
1398
+ if (closed || registeredScope === void 0 || scopes.get(scope.sessionId) !== registeredScope) throw new Error("Computer-use session is closed.");
1399
+ const response = await host.requestSessionApi(scope, {
1400
+ basePath: require_extensionService.API_BASE_PATH,
1401
+ path,
1402
+ method,
1403
+ ...value === void 0 ? {} : { body: JSON.stringify(value) }
1404
+ });
1405
+ if (response.status !== 503 || attempt >= SESSION_READY_ATTEMPTS) return response;
1406
+ if (record(await response.clone().json().catch(() => void 0))?.error !== "Session selection is not ready.") return response;
1407
+ await new Promise((resolve) => setTimeout(resolve, SESSION_READY_RETRY_MS));
1408
+ }
1409
+ };
1084
1410
  const publish = (scope, state) => {
1085
- if (state.phase === "active" || state.phase === "activating" || state.phase === "stopping") activeSessionId = scope.sessionId;
1411
+ if (state.phase === "active" || state.phase === "activating" || state.phase === "stopping") activeSessionId ??= scope.sessionId;
1086
1412
  else if (activeSessionId === scope.sessionId) {
1087
1413
  activeSessionId = void 0;
1088
1414
  grants.delete(scope.sessionId);
1089
1415
  }
1090
1416
  const payload = {
1091
1417
  state,
1092
- targets: targets.get(scope.sessionId) ?? [],
1418
+ targets: [],
1093
1419
  ...activeSessionId !== void 0 && activeSessionId !== scope.sessionId ? { busy: true } : {}
1094
1420
  };
1095
1421
  latest.set(scope.sessionId, payload);
1096
1422
  host.publish(scope.sessionId, payload);
1097
1423
  };
1098
1424
  const refresh = async (scope) => {
1099
- const state = sessionState(await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubState)));
1425
+ const state = sessionState(await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubState)));
1100
1426
  if (state === void 0) throw new Error("Computer-use API returned an invalid session state.");
1101
1427
  publish(scope, state);
1102
1428
  return state;
@@ -1114,18 +1440,20 @@ function createComputerUseChannel() {
1114
1440
  sequence: pending.sequence,
1115
1441
  action: pending.payload
1116
1442
  } : {
1443
+ ...record(pending.payload),
1117
1444
  grantId: pending.grantId,
1118
1445
  includeScreenshot: record(pending.payload)?.includeScreenshot !== false
1119
1446
  }
1120
1447
  });
1121
- await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubComplete, "POST", {
1448
+ await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubComplete, "POST", {
1122
1449
  id: pending.id,
1123
1450
  result
1124
1451
  }));
1125
1452
  } catch (error) {
1126
- await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubComplete, "POST", {
1453
+ await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubComplete, "POST", {
1127
1454
  id: pending.id,
1128
- error: error instanceof Error ? error.message : String(error)
1455
+ error: error instanceof Error ? error.message : String(error),
1456
+ ...error instanceof _agimon_ai_po_core_hubChannel.PoComputerUseHostError ? { code: error.code } : {}
1129
1457
  }));
1130
1458
  } finally {
1131
1459
  if (requests.get(scope.sessionId) === controller) requests.delete(scope.sessionId);
@@ -1133,7 +1461,7 @@ function createComputerUseChannel() {
1133
1461
  };
1134
1462
  const stopSession = async (scope) => {
1135
1463
  requests.get(scope.sessionId)?.abort();
1136
- const authorization = await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubAuthorization));
1464
+ const authorization = await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubAuthorization));
1137
1465
  let artifact;
1138
1466
  if (authorization !== null && host.computerUse?.available) try {
1139
1467
  artifact = record(await host.computerUse.request(scope, {
@@ -1152,7 +1480,7 @@ function createComputerUseChannel() {
1152
1480
  };
1153
1481
  host.onNotice(`computer-use Desktop stop was already unavailable (${message})`);
1154
1482
  }
1155
- await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubStop, "POST", { artifact }));
1483
+ await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubStop, "POST", { artifact }));
1156
1484
  grants.delete(scope.sessionId);
1157
1485
  if (activeSessionId === scope.sessionId) activeSessionId = void 0;
1158
1486
  };
@@ -1167,7 +1495,7 @@ function createComputerUseChannel() {
1167
1495
  const state = announced ?? await refresh(scope);
1168
1496
  if (state.phase === "active") {
1169
1497
  if (!grants.has(scope.sessionId)) {
1170
- const authorization = await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubAuthorization));
1498
+ const authorization = await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubAuthorization));
1171
1499
  if (authorization !== null) grants.set(scope.sessionId, authorization.grantId);
1172
1500
  }
1173
1501
  const expired = typeof state.expiresAt === "number" && state.expiresAt <= Date.now();
@@ -1183,10 +1511,11 @@ function createComputerUseChannel() {
1183
1511
  return;
1184
1512
  }
1185
1513
  }
1186
- if (state.phase === "awaiting_confirmation" && (activeSessionId === void 0 || activeSessionId === scope.sessionId)) {
1187
- const activation = await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubActivation));
1188
- if (activation !== null && !host.computerUse?.available) {
1189
- await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubStop, "POST", { error: DESKTOP_UNAVAILABLE }));
1514
+ if (state.phase === "awaiting_confirmation") {
1515
+ const busy = activeSessionId !== void 0 && activeSessionId !== scope.sessionId;
1516
+ const activation = await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubActivation));
1517
+ if (activation !== null && (busy || !host.computerUse?.available)) {
1518
+ await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubStop, "POST", { error: busy ? "Computer use is active in another session." : DESKTOP_UNAVAILABLE }));
1190
1519
  await refresh(scope);
1191
1520
  return;
1192
1521
  }
@@ -1200,12 +1529,12 @@ function createComputerUseChannel() {
1200
1529
  payload: activation,
1201
1530
  signal: controller.signal
1202
1531
  });
1203
- await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubStop, "POST", { host: hostResult }));
1532
+ await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubStop, "POST", { host: hostResult }));
1204
1533
  const grantId = record(hostResult)?.grantId;
1205
1534
  if (typeof grantId === "string") grants.set(scope.sessionId, grantId);
1206
1535
  } catch (error) {
1207
1536
  activeSessionId = void 0;
1208
- await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubStop, "POST", { error: error instanceof Error ? error.message : String(error) }));
1537
+ await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubStop, "POST", { error: error instanceof Error ? error.message : String(error) }));
1209
1538
  } finally {
1210
1539
  if (requests.get(scope.sessionId) === controller) requests.delete(scope.sessionId);
1211
1540
  }
@@ -1216,7 +1545,7 @@ function createComputerUseChannel() {
1216
1545
  await stopSession(scope);
1217
1546
  await refresh(scope);
1218
1547
  }
1219
- const pending = await responseJson(await sessionRequest(scope, COMPUTER_USE_ROUTES.hubNext));
1548
+ const pending = await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubNext));
1220
1549
  if (pending !== null) await completePending(scope, pending);
1221
1550
  } catch (error) {
1222
1551
  if (error instanceof MissingComputerUseApiError) latest.delete(scope.sessionId);
@@ -1235,7 +1564,7 @@ function createComputerUseChannel() {
1235
1564
  const onState = (scope, payload) => {
1236
1565
  const state = sessionState(payload);
1237
1566
  if (state === void 0 || state.sessionId !== scope.sessionId) return;
1238
- if (state.phase === "stopping" || state.phase === "failed" || state.phase === "inactive") requests.get(scope.sessionId)?.abort();
1567
+ if (state.phase === "stopping" && grants.has(scope.sessionId) || state.phase === "failed" || state.phase === "inactive") requests.get(scope.sessionId)?.abort();
1239
1568
  publish(scope, state);
1240
1569
  processScope(scope, state);
1241
1570
  };
@@ -1244,10 +1573,11 @@ function createComputerUseChannel() {
1244
1573
  if (parsed === void 0) return;
1245
1574
  (async () => {
1246
1575
  try {
1247
- if (parsed.action === "targets") {
1248
- const result = host.computerUse?.available ? await host.computerUse.request(scope, { operation: "targets" }) : [];
1249
- targets.set(scope.sessionId, Array.isArray(result) ? result.filter((item) => record(item) !== void 0) : []);
1250
- } else if (parsed.action === "stop") await stopSession(scope);
1576
+ if (parsed.action === "stop") {
1577
+ const stopped = await responseJson(await sessionRequest(scope, require_extensionService.COMPUTER_USE_ROUTES.hubRequestStop, "POST"));
1578
+ await processScope(scope, stopped);
1579
+ return;
1580
+ }
1251
1581
  await refresh(scope);
1252
1582
  processScope(scope);
1253
1583
  } catch (error) {
@@ -1260,7 +1590,7 @@ function createComputerUseChannel() {
1260
1590
  payloadFor: (scope) => latest.get(scope.sessionId),
1261
1591
  sessionAdded(scope) {
1262
1592
  scopes.set(scope.sessionId, scope);
1263
- const unsubscribe = host.directEvents.subscribe(computerUseChannelType, scope.sessionId, (payload) => onState(scope, payload), { replayLatest: true });
1593
+ const unsubscribe = host.directEvents.subscribe(require_extensionService.computerUseChannelType, scope.sessionId, (payload) => onState(scope, payload), { replayLatest: true });
1264
1594
  subscriptions.set(scope.sessionId, unsubscribe);
1265
1595
  processScope(scope);
1266
1596
  },
@@ -1278,7 +1608,6 @@ function createComputerUseChannel() {
1278
1608
  }).catch((error) => host.onNotice(`computer-use session cleanup failed (${error instanceof Error ? error.message : String(error)})`));
1279
1609
  scopes.delete(sessionId);
1280
1610
  latest.delete(sessionId);
1281
- targets.delete(sessionId);
1282
1611
  grants.delete(sessionId);
1283
1612
  processing.delete(sessionId);
1284
1613
  if (activeSessionId === sessionId) activeSessionId = void 0;
@@ -1295,11 +1624,10 @@ function createComputerUseChannel() {
1295
1624
  if (scope !== void 0) host.computerUse.request(scope, {
1296
1625
  operation: "stop",
1297
1626
  payload: { grantId }
1298
- }).catch(() => void 0);
1627
+ }).catch((error) => host.onNotice(`computer-use Desktop stop failed during shutdown (${String(error)})`));
1299
1628
  }
1300
1629
  scopes.clear();
1301
1630
  latest.clear();
1302
- targets.clear();
1303
1631
  grants.clear();
1304
1632
  }
1305
1633
  };
@@ -1321,10 +1649,43 @@ var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedCont
1321
1649
  var computer_use_server_default$1 = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)((context) => context.root.commands.find((command) => command.name === "computer-use"), { cardinality: "optional" });
1322
1650
  //#endregion
1323
1651
  //#region src/extensions/workspaces/sessions/(backend)/hook/before-agent-start.server.ts
1324
- var before_agent_start_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)((context) => context.root.hooks?.find((hook) => hook.event === "before_agent_start"), { cardinality: "optional" });
1652
+ var before_agent_start_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)((0, _agimon_ai_po_core_extensionFile.defineHook)((context) => {
1653
+ const hook = context.root.hooks?.find((hook) => hook.event === "before_agent_start");
1654
+ if (hook === void 0) return void 0;
1655
+ return {
1656
+ ...hook,
1657
+ name: "inject-computer-use-guidance",
1658
+ description: "In computer-use mode with an available enabled desktop and approval capability, append active-control or narrow-grant request guidance."
1659
+ };
1660
+ }), { cardinality: "optional" });
1325
1661
  //#endregion
1326
1662
  //#region src/extensions/workspaces/sessions/(backend)/hook/session-shutdown.server.ts
1327
- var session_shutdown_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)((context) => context.root.hooks?.find((hook) => hook.event === "session_shutdown"), { cardinality: "optional" });
1663
+ var session_shutdown_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)((0, _agimon_ai_po_core_extensionFile.defineHook)((context) => {
1664
+ const hook = context.root.hooks?.find((hook) => hook.event === "session_shutdown");
1665
+ if (hook === void 0) return void 0;
1666
+ return {
1667
+ ...hook,
1668
+ name: "stop-computer-use-session",
1669
+ description: "In computer-use mode, stop the session activity and stop the desktop client unless it is inactive or failed."
1670
+ };
1671
+ }), { cardinality: "optional" });
1672
+ //#endregion
1673
+ //#region src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-computer-use.server.ts
1674
+ var codemode_how_to_computer_use_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)({
1675
+ name: "codemode-how-to-computer-use",
1676
+ 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.",
1677
+ kind: "skill",
1678
+ pinned: true,
1679
+ when: {
1680
+ state: { mode: require_extensionService.COMPUTER_USE_MODE_ID },
1681
+ attribution: {
1682
+ kind: "mode",
1683
+ name: require_extensionService.COMPUTER_USE_MODE_ID
1684
+ }
1685
+ },
1686
+ path: (0, _agimon_ai_po_core_serverPlugin.packageResourcePath)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-computer-use/SKILL.md"),
1687
+ read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-computer-use/SKILL.md")
1688
+ });
1328
1689
  //#endregion
1329
1690
  //#region src/extensions/workspaces/sessions/(backend)/tool-restriction/computer-use.server.ts
1330
1691
  var computer_use_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)((context) => context.root.toolRestrictions?.[0], { cardinality: "optional" });
@@ -1338,24 +1699,48 @@ var _10_computer_action_server_default = (0, _agimon_ai_po_core_extensionFile.de
1338
1699
  //#region src/extensions/workspaces/sessions/(backend)/tool/20-computer-exec.server.ts
1339
1700
  var _20_computer_exec_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)((context) => context.root.tools.find((tool) => tool.name === "computer_exec"), { cardinality: "optional" });
1340
1701
  //#endregion
1702
+ //#region src/extensions/workspaces/sessions/(backend)/tool/30-computer-targets.server.ts
1703
+ var _30_computer_targets_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)((context) => context.root.tools.find((tool) => tool.name === "computer_targets"), { cardinality: "optional" });
1704
+ //#endregion
1705
+ //#region src/extensions/workspaces/sessions/(backend)/tool/40-computer-request.server.ts
1706
+ var _40_computer_request_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)((context) => context.root.tools.find((tool) => tool.name === "computer_request"), { cardinality: "optional" });
1707
+ //#endregion
1341
1708
  //#region generated/server.ts
1342
1709
  const at = (value, context) => typeof value === "function" ? value(context) : value;
1343
1710
  /* v8 ignore next -- generated normalization branch */
1344
1711
  const defined = (values) => values.filter((value) => value !== void 0);
1345
- const via = (identity, value) => value === void 0 ? void 0 : {
1346
- ...identity,
1347
- ...value
1712
+ const via = (identity, value) => {
1713
+ if (value === void 0) return void 0;
1714
+ const declaration = value;
1715
+ return {
1716
+ ...identity,
1717
+ ...declaration,
1718
+ ...declaration.relations === void 0 ? {} : { relations: declaration.relations.map((relation) => ({
1719
+ evidence: "declared",
1720
+ ...relation
1721
+ })) }
1722
+ };
1348
1723
  };
1349
1724
  const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
1350
1725
  name: "@agimon-ai/po-computer-use",
1351
1726
  providerOverrides: (0, _agimon_ai_po_core_serverPlugin.composeServerProviderOverrides)(root_server_default),
1352
1727
  injects: (0, _agimon_ai_po_core_extensionFile.composeRootInjects)({ session: [root_server_default] }),
1353
- global: () => ({ get channels() {
1354
- return [() => via({ frameType: "computer_use" }, computer_use_server_default$2())];
1355
- } }),
1356
- workspace: (context) => ({ get channels() {
1357
- return defined([context.hosted("global") ? void 0 : () => via({ frameType: "computer_use" }, computer_use_server_default$2())]);
1358
- } }),
1728
+ host: (context) => ({
1729
+ get api() {
1730
+ return [at(route_server_default$1, context)];
1731
+ },
1732
+ get channels() {
1733
+ return [() => via({ frameType: "computer_use" }, at(computer_use_server_default$2, context))];
1734
+ }
1735
+ }),
1736
+ workspace: (context) => ({
1737
+ get api() {
1738
+ return [at(route_server_default$1, context)];
1739
+ },
1740
+ get channels() {
1741
+ return defined([context.hosted("host") ? void 0 : () => via({ frameType: "computer_use" }, at(computer_use_server_default$2, context))]);
1742
+ }
1743
+ }),
1359
1744
  session: async (context) => {
1360
1745
  const scopeSession = await context.scopeRoot("session", root_server_default, context);
1361
1746
  const contextSession = {
@@ -1365,10 +1750,10 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
1365
1750
  return {
1366
1751
  ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeSession),
1367
1752
  get api() {
1368
- return defined([at(route_server_default, contextSession)]);
1753
+ return defined([at(route_server_default$1, context), at(route_server_default, contextSession)]);
1369
1754
  },
1370
1755
  get channels() {
1371
- return defined([context.hosted("global") ? void 0 : () => via({ frameType: "computer_use" }, computer_use_server_default$2())]);
1756
+ return defined([context.hosted("host") ? void 0 : () => via({ frameType: "computer_use" }, at(computer_use_server_default$2, context))]);
1372
1757
  },
1373
1758
  get commands() {
1374
1759
  return defined([via({ name: "computer-use" }, at(computer_use_server_default$1, contextSession))]);
@@ -1376,6 +1761,9 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
1376
1761
  get hooks() {
1377
1762
  return defined([via({ event: "before_agent_start" }, at(before_agent_start_server_default, contextSession)), via({ event: "session_shutdown" }, at(session_shutdown_server_default, contextSession))]);
1378
1763
  },
1764
+ get resources() {
1765
+ return [at(codemode_how_to_computer_use_server_default, contextSession)];
1766
+ },
1379
1767
  get toolRestrictions() {
1380
1768
  return defined([at(computer_use_server_default, contextSession)]);
1381
1769
  },
@@ -1383,7 +1771,9 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
1383
1771
  return defined([
1384
1772
  via({ name: "00_computer_state" }, at(_00_computer_state_server_default, contextSession)),
1385
1773
  via({ name: "10_computer_action" }, at(_10_computer_action_server_default, contextSession)),
1386
- via({ name: "20_computer_exec" }, at(_20_computer_exec_server_default, contextSession))
1774
+ via({ name: "20_computer_exec" }, at(_20_computer_exec_server_default, contextSession)),
1775
+ via({ name: "30_computer_targets" }, at(_30_computer_targets_server_default, contextSession)),
1776
+ via({ name: "40_computer_request" }, at(_40_computer_request_server_default, contextSession))
1387
1777
  ]);
1388
1778
  },
1389
1779
  services: [...scopeSession.services ?? []],