@agimon-ai/po-computer-use 0.0.0-alpha.5 → 0.0.0-alpha.50

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.
package/LICENSE CHANGED
@@ -1,21 +1,149 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Vuong Ngo
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ License text copyright © 2017 MariaDB Corporation Ab, All Rights Reserved.
2
+ "Business Source License" is a trademark of MariaDB Corporation Ab.
3
+
4
+ Parameters
5
+
6
+ Licensor: Agimon Pty Ltd
7
+ Licensed Work: Po, the software in the Po source repository and the
8
+ packages released from it, in each version released by
9
+ the Licensor.
10
+ The Licensed Work is (c) 2026 Agimon Pty Ltd.
11
+ Material identified as third-party in the "Third-party
12
+ components" section at the end of this file or in a
13
+ NOTICE file, and any package or directory whose own
14
+ license file grants a different license, is not part of
15
+ the Licensed Work and remains under its own license.
16
+ Additional Use Grant: You may make production use of the Licensed Work if
17
+ your use is Eligible Use. "Eligible Use" is production use that falls
18
+ within at least one of the following:
19
+
20
+ (a) Personal Use. Use by an individual for their own personal purposes,
21
+ and not on behalf of, or for the benefit of, an employer, client, or
22
+ other Organization. Use by an individual in the course of employment
23
+ or engagement by an Organization is use by that Organization.
24
+
25
+ (b) Small Organization Use. Use by or on behalf of an Organization whose
26
+ Annual Revenue is less than USD 1,000,000.
27
+
28
+ (c) Non-profit, Education and Research Use. Use, regardless of Annual
29
+ Revenue, by (i) an Organization registered or recognized as a
30
+ non-profit or charitable organization under the laws of its
31
+ jurisdiction, for its non-profit purposes; (ii) an accredited school,
32
+ college, or university, for teaching, learning, or academic research;
33
+ or (iii) a publicly funded research institution, for its research.
34
+
35
+ (d) Service Provider Use. Use by a consultant, contractor, agency, or other
36
+ service provider, regardless of its own Annual Revenue, solely to
37
+ build, deploy, host, operate, or support the Licensed Work for a client
38
+ whose own use would be Eligible Use under (a), (b), or (c). A service
39
+ provider's use for its own purposes is Eligible Use only if the service
40
+ provider itself qualifies under (b) or (c).
41
+
42
+
43
+ Hosted services. Offering the Licensed Work to third parties as a hosted
44
+ or managed service whose primary value is the Licensed Work is Eligible
45
+ Use only if each such third party's own use would be Eligible Use.
46
+
47
+ Definitions. "Organization" means any company, partnership, sole
48
+ proprietorship, trust, association, government body, or other entity, and
49
+ includes an individual acting in a business or professional capacity.
50
+ "Affiliate" means any entity that directly or indirectly controls, is
51
+ controlled by, or is under common control with an Organization, where
52
+ "control" means ownership of more than 50% of the voting interests of an
53
+ entity or the power to direct its management and policies by contract or
54
+ otherwise. "Annual Revenue" means the total gross revenue of an
55
+ Organization and all of its Affiliates combined, from all sources and
56
+ whether or not related to the Licensed Work, for its most recently
57
+ completed fiscal year, or, if it has not completed a fiscal year, for the
58
+ twelve months before the use (or since its formation, if shorter),
59
+ converted into US dollars at the average exchange rate for that period.
60
+ Proceeds of equity or debt financing are not revenue.
61
+
62
+ Threshold. If an Organization stops qualifying under (b), its existing
63
+ production use remains Eligible Use for 90 days after it stops
64
+ qualifying, after which it must obtain a commercial license or stop
65
+ production use. Use that was Eligible Use when it occurred never requires
66
+ a commercial license after the fact.
67
+ Change Date: Four years from the date a version of the Licensed Work
68
+ is first publicly released by the Licensor.
69
+ Change License: Apache License, Version 2.0
70
+
71
+ For information about alternative licensing arrangements for the Licensed
72
+ Work, please visit: https://agimon.ai/licensing
73
+
74
+ Notice
75
+
76
+ The Business Source License (this document, or the "License") is not an Open
77
+ Source license. However, the Licensed Work will eventually be made available
78
+ under an Open Source License, as stated in this License.
79
+
80
+ -----------------------------------------------------------------------------
81
+
82
+ Business Source License 1.1
83
+
84
+ Terms
85
+
86
+ The Licensor hereby grants you the right to copy, modify, create derivative
87
+ works, redistribute, and make non-production use of the Licensed Work. The
88
+ Licensor may make an Additional Use Grant, above, permitting limited
89
+ production use.
90
+
91
+ Effective on the Change Date, or the fourth anniversary of the first publicly
92
+ available distribution of a specific version of the Licensed Work under this
93
+ License, whichever comes first, the Licensor hereby grants you rights under
94
+ the terms of the Change License, and the rights granted in the paragraph
95
+ above terminate.
96
+
97
+ If your use of the Licensed Work does not comply with the requirements
98
+ currently in effect as described in this License, you must purchase a
99
+ commercial license from the Licensor, its affiliated entities, or authorized
100
+ resellers, or you must refrain from using the Licensed Work.
101
+
102
+ All copies of the original and modified Licensed Work, and derivative works
103
+ of the Licensed Work, are subject to this License. This License applies
104
+ separately for each version of the Licensed Work and the Change Date may vary
105
+ for each version of the Licensed Work released by Licensor.
106
+
107
+ You must conspicuously display this License on each original or modified copy
108
+ of the Licensed Work. If you receive the Licensed Work in original or
109
+ modified form from a third party, the terms and conditions set forth in this
110
+ License apply to your use of that work.
111
+
112
+ Any use of the Licensed Work in violation of this License will automatically
113
+ terminate your rights under this License for the current and all other
114
+ versions of the Licensed Work.
115
+
116
+ This License does not grant you any right in any trademark or logo of
117
+ Licensor or its affiliates (provided that you may use a trademark or logo of
118
+ Licensor as expressly required by this License).
119
+
120
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
121
+ AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
122
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
123
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
124
+ TITLE.
125
+
126
+ MariaDB hereby grants you permission to use this License’s text to license
127
+ your works, and to refer to it using the trademark “Business Source License”,
128
+ as long as you comply with the Covenants of Licensor below.
129
+
130
+ Covenants of Licensor
131
+
132
+ In consideration of the right to use this License’s text and the “Business
133
+ Source License” name and trademark, Licensor covenants to MariaDB, and to all
134
+ other recipients of the licensed work to be provided by Licensor:
135
+
136
+ 1. To specify as the Change License the GPL Version 2.0 or any later version,
137
+ or a license that is compatible with GPL Version 2.0 or a later version,
138
+ where “compatible” means that software provided under the Change License can
139
+ be included in a program with software provided under GPL Version 2.0 or a
140
+ later version. Licensor may specify additional Change Licenses without
141
+ limitation.
142
+
143
+ 2. To either: (a) specify an additional grant of rights to use that does not
144
+ impose any additional restriction on the right granted in this License, as
145
+ the Additional Use Grant; or (b) insert the text “None”.
146
+
147
+ 3. To specify a Change Date.
148
+
149
+ 4. Not to modify this License in any other way.
package/README.md CHANGED
@@ -16,12 +16,15 @@ The `computer-use` minor mode exposes Activate, Deactivate, and Doctor actions.
16
16
 
17
17
  While active, the package exposes three tools:
18
18
 
19
- - `computer_state` observes the authorized window and returns a semantic snapshot.
19
+ - `computer_state` observes the authorized window and returns a semantic snapshot. `saveScreenshot: true` also keeps the screenshot in session artifacts under `computer-use/<run>/` and returns its `artifact:` path.
20
20
  - `computer_action` performs one semantic press, focus change, value change, or scroll against a current snapshot.
21
21
  - `computer_exec` executes a reusable JavaScript or erasable TypeScript function and its relative helpers in a restricted runtime, then returns a fresh semantic observation.
22
22
 
23
+ Every finished recording is copied from the native store into session artifacts under `computer-use/`, in bounded ranges, when artifacts are available. The private player keeps its own copy.
23
24
  Generated functions receive the authorized program API, JSON input, bounded logging, and cancellation. They do not receive Node or filesystem access. Script-internal observations omit screenshots by default, and `includeScreenshot: true` requests an image explicitly. Full Node execution requires both `trusted: true` and an exact host-configured `PO_COMPUTER_USE_SCRIPT_PATHS` allowlist. Trusted scripts remain unsandboxed, including their imported dependencies. See [Author computer functions](./docs/computer-scripts.md) for the contract, limits, trust boundary, and examples.
24
25
 
26
+ With code mode, the same operations are the `computer` namespace in `exec` (`state`, `act`, `run`, `stop`), registered only while the native grant is active, and the three tools are withdrawn from the agent. The `codemode-how-to-computer-use` guide is listed whenever the mode is selected. MCP clients and hosts without code mode keep the tools.
27
+
25
28
  All three tools remain unavailable during setup and are admitted only after the native grant becomes active. Disabling the mode or global opt-in, stopping control, expiry, or Desktop disconnection stops further actions. Once Desktop claims a session, browser and remote MCP clients cannot drive it, including previously attached clients. This ownership stays pinned for the server lifetime and is not restored from saved session data.
26
29
 
27
30
  ## Public API
@@ -31,7 +34,7 @@ import { ComputerScriptRunner, createComputerUseSessionClient } from '@agimon-ai
31
34
  import type { ComputerScriptRun } from '@agimon-ai/po-computer-use';
32
35
  ```
33
36
 
34
- The session-scoped server facet owns the agent and hub routes. Their host-issued context tokens remain opaque and session-bound inside the request broker.
37
+ The session-scoped server plugin owns the agent and hub routes. Their host-issued context tokens remain opaque and session-bound inside the request broker.
35
38
 
36
39
  ## Development
37
40
 
@@ -44,6 +47,6 @@ pnpm build
44
47
 
45
48
  ## License
46
49
 
47
- MIT
50
+ Business Source License 1.1: free for personal use, organisations under USD 1M revenue, non-profits and education. See [LICENSE](LICENSE) and https://agimon.ai/licensing.
48
51
 
49
52
  Direct plugin routes live in `src/extensions`. The session root constructs one broker shared by the typed agent client and activation API. The host owns the Desktop IPC connection, native renderer authentication, session identity, and grant lifetime. The hub channel uses lifecycle events rather than polling to forward operations. Public exports remain under `src/exports`.
@@ -44,6 +44,26 @@ const ComputerStateSchema = typebox.Type.Object({
44
44
  failure: O(Error),
45
45
  artifact: O(Artifact)
46
46
  });
47
+ const Permission = values([
48
+ "accessibility",
49
+ "screen-recording",
50
+ "microphone",
51
+ "automation",
52
+ "full-disk-access"
53
+ ]);
54
+ const PermissionState = values([
55
+ "granted",
56
+ "denied",
57
+ "not-determined",
58
+ "per-app"
59
+ ]);
60
+ const DesktopPermissionStatesSchema = typebox.Type.Object({
61
+ accessibility: PermissionState,
62
+ "screen-recording": PermissionState,
63
+ microphone: PermissionState,
64
+ automation: PermissionState,
65
+ "full-disk-access": PermissionState
66
+ });
47
67
  const Reference = {
48
68
  snapshotId: typebox.Type.String({ minLength: 1 }),
49
69
  elementRef: typebox.Type.String({ minLength: 1 })
@@ -96,6 +116,32 @@ const apiContracts = (0, _agimon_ai_po_core_apiContracts.defineApiContract)({
96
116
  version: 1,
97
117
  dynamic: ["Desktop provider target extensions, observations and operation results are runtime-defined JSON."],
98
118
  http: [
119
+ ...[
120
+ "global",
121
+ "workspace",
122
+ "session"
123
+ ].flatMap((scope) => ["GET", "POST"].map((method) => ({
124
+ id: `computer.permissions.${method === "GET" ? "read" : "request"}`,
125
+ scope,
126
+ basePath: "desktop-permissions",
127
+ path: "/",
128
+ method,
129
+ authentication: "owner",
130
+ description: method === "GET" ? "Read the Mac-owned permission states. Requires an authorized local Desktop caller or trusted remote caller." : "Ask macOS for one named permission. Requires an authorized local Desktop caller or remote passkey step-up.",
131
+ availability: "Requires Po Desktop to be running this server; otherwise returns 404.",
132
+ ...method === "POST" ? { body: {
133
+ required: true,
134
+ contentType: "application/json",
135
+ schema: typebox.Type.Object({ permission: Permission })
136
+ } } : {},
137
+ responses: {
138
+ ...(0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(DesktopPermissionStatesSchema),
139
+ "502": {
140
+ description: "Desktop permission request failed.",
141
+ schema: typebox.Type.Object({ error: S })
142
+ }
143
+ }
144
+ }))),
99
145
  {
100
146
  id: "computer.activation.state",
101
147
  scope: "session",
@@ -1 +1 @@
1
- {"version":3,"file":"apiContracts.cjs","names":["Type","jsonApiResponses","defineApiContract"],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract, jsonApiResponses, type PoHttpContract } from '@agimon-ai/po-core/apiContracts';\nimport { Type } from 'typebox';\n\nconst S = Type.String();\nconst N = Type.Number();\nconst O = Type.Optional;\nconst values = <T extends string>(items: T[]) => Type.Union(items.map((item) => Type.Literal(item)));\nconst Json = Type.Unknown({\n description:\n 'Desktop provider JSON value. Targets, observations and action results are supplied by the admitted Desktop provider.',\n});\nconst Target = Type.Record(S, Json);\nconst Error = Type.Object({ code: S, message: S });\nconst Artifact = Type.Object({\n artifactId: S,\n status: values(['ready', 'failed']),\n sizeBytes: O(N),\n downloadUrl: O(S),\n previewUrl: O(S),\n actionCount: O(N),\n completedAt: O(S),\n failure: O(Error),\n});\nexport const ComputerStateSchema = Type.Object({\n sessionId: S,\n revision: N,\n wake: N,\n phase: values(['inactive', 'awaiting_confirmation', 'activating', 'active', 'stopping', 'failed']),\n requestId: O(S),\n target: O(Target),\n durationMs: O(N),\n expiresAt: O(N),\n failure: O(Error),\n artifact: O(Artifact),\n});\nconst Reference = { snapshotId: Type.String({ minLength: 1 }), elementRef: Type.String({ minLength: 1 }) };\nexport const ComputerActionSchema = Type.Union([\n Type.Object({ kind: values(['press', 'focus']), ...Reference }, { additionalProperties: false }),\n Type.Object({ kind: Type.Literal('set_value'), ...Reference, value: S }, { additionalProperties: false }),\n Type.Object(\n {\n kind: Type.Literal('scroll'),\n ...Reference,\n direction: values(['up', 'down', 'left', 'right']),\n amount: values(['line', 'page']),\n },\n { additionalProperties: false },\n ),\n]);\nconst internal = (\n method: 'GET' | 'POST',\n path: string,\n output: object,\n body?: object,\n status = 200,\n): PoHttpContract => ({\n id: `computer.${path.slice(1).replaceAll('/', '.')}`,\n scope: 'session',\n basePath: 'computer-use',\n path,\n method,\n authentication: 'owner',\n description: `Computer use broker ${path}. Requires the host-issued ${path.startsWith('/agent/') ? 'agent' : 'hub'} bearer token.`,\n availability: 'Internal broker route; ordinary browser credentials are insufficient.',\n parameters: [{ name: 'Authorization', in: 'header', required: true, schema: Type.String({ pattern: '^Bearer .+' }) }],\n ...(body ? { body: { required: true, contentType: 'application/json', schema: body } } : {}),\n responses: jsonApiResponses(output, status),\n});\nexport const apiContracts = defineApiContract({\n version: 1,\n dynamic: ['Desktop provider target extensions, observations and operation results are runtime-defined JSON.'],\n http: [\n {\n id: 'computer.activation.state',\n scope: 'session',\n basePath: 'computer-use',\n path: '/activate',\n method: 'GET',\n authentication: 'owner',\n description: 'Read state as the matching pending requester or approved recording reader.',\n responses: jsonApiResponses(ComputerStateSchema),\n },\n {\n id: 'computer.activation.cancel',\n scope: 'session',\n basePath: 'computer-use',\n path: '/activate',\n method: 'DELETE',\n authentication: 'owner',\n description: 'Cancel only the matching requester pending activation.',\n responses: jsonApiResponses(ComputerStateSchema, 202),\n },\n {\n id: 'computer.activate',\n scope: 'session',\n basePath: 'computer-use',\n path: '/activate',\n method: 'POST',\n authentication: 'owner',\n description:\n 'Request confirmed Desktop access with admitted caller and remote step-up context. A remote caller may omit target so the local Mac selects the window.',\n body: {\n required: true,\n contentType: 'application/json',\n schema: Type.Object({\n target: O(Type.Object({ windowId: S, bundleId: S })),\n durationMs: Type.Integer({ minimum: 1000, maximum: 1800000 }),\n }),\n },\n responses: jsonApiResponses(ComputerStateSchema, 202),\n },\n {\n id: 'computer.artifact',\n scope: 'session',\n basePath: 'computer-use',\n path: '/artifact',\n method: 'GET',\n authentication: 'owner',\n description: 'Read at most 1 MiB of a recording belonging to this session and approved caller.',\n parameters: [\n { name: 'artifactId', in: 'query', required: true, schema: S },\n { name: 'offset', in: 'query', required: true, schema: Type.Integer({ minimum: 0 }) },\n ],\n responses: {\n 206: {\n description: 'Bounded recording bytes.',\n contentType: 'video/mp4',\n schema: Type.String({ format: 'binary' }),\n },\n },\n },\n internal('GET', '/agent/state', ComputerStateSchema),\n internal('GET', '/hub/state', ComputerStateSchema),\n internal('POST', '/agent/observe', Json),\n internal('POST', '/agent/action', Json, ComputerActionSchema),\n internal('POST', '/agent/stop', ComputerStateSchema, undefined, 202),\n internal(\n 'GET',\n '/hub/activation',\n Type.Union([\n Type.Null(),\n Type.Object({\n requestId: S,\n target: Target,\n durationSeconds: N,\n createdAt: N,\n confirmationExpiresAt: N,\n caller: Type.Object({ locality: values(['local', 'remote']), stepUp: S }),\n }),\n ]),\n ),\n internal('GET', '/hub/authorization', Type.Union([Type.Null(), Type.Object({ grantId: S, expiresAt: O(N) })])),\n internal(\n 'GET',\n '/hub/next',\n Type.Union([\n Type.Null(),\n Type.Object({ id: S, operation: values(['observe', 'act']), payload: O(Json), grantId: S, sequence: O(N) }),\n ]),\n ),\n internal('POST', '/hub/complete', ComputerStateSchema, Type.Object({ id: S, error: O(S), result: O(Json) })),\n internal(\n 'POST',\n '/hub/stop',\n ComputerStateSchema,\n Type.Object({ error: O(S), host: O(Type.Object({ grantId: S, expiresAt: N })), artifact: O(Artifact) }),\n ),\n ],\n sockets: (['global', 'workspace'] as const).flatMap((scope) => [\n {\n id: 'computer.state',\n scope,\n service: 'po.hub',\n member: 'computer_use_state',\n kind: 'channel',\n direction: 'server-to-client',\n description: 'Computer use channel payload.',\n input: Type.Object({ state: ComputerStateSchema, targets: Type.Array(Target), busy: O(Type.Literal(true)) }),\n },\n {\n id: 'computer.command',\n scope,\n service: 'po.hub',\n member: 'computer_use_state',\n kind: 'channel',\n direction: 'client-to-server',\n description: 'Computer use browser channel command.',\n input: Type.Object({ action: values(['status', 'targets', 'stop', 'artifacts']) }),\n },\n ]),\n});\nexport default apiContracts;\n"],"mappings":";;;;;;;AAGA,MAAM,IAAIA,QAAAA,KAAK,OAAO;AACtB,MAAM,IAAIA,QAAAA,KAAK,OAAO;AACtB,MAAM,IAAIA,QAAAA,KAAK;AACf,MAAM,UAA4B,UAAeA,QAAAA,KAAK,MAAM,MAAM,KAAK,SAASA,QAAAA,KAAK,QAAQ,IAAI,CAAC,CAAC;AACnG,MAA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CAAC,CAAC;EAC7G,SACE,OACA,aACAA,QAAAA,KAAK,MAAM,CACTA,QAAAA,KAAK,KAAK,GACVA,QAAAA,KAAK,OAAO;GAAE,IAAI;GAAG,WAAW,OAAO,CAAC,WAAW,KAAK,CAAC;GAAG,SAAS,EAAE,IAAI;GAAG,SAAS;GAAG,UAAU,EAAE,CAAC;EAAE,CAAC,CAC5G,CAAC,CACH;EACA,SAAS,QAAQ,iBAAiB,qBAAqBA,QAAAA,KAAK,OAAO;GAAE,IAAI;GAAG,OAAO,EAAE,CAAC;GAAG,QAAQ,EAAE,IAAI;EAAE,CAAC,CAAC;EAC3G,SACE,QACA,aACA,qBACAA,QAAAA,KAAK,OAAO;GAAE,OAAO,EAAE,CAAC;GAAG,MAAM,EAAEA,QAAAA,KAAK,OAAO;IAAE,SAAS;IAAG,WAAW;GAAE,CAAC,CAAC;GAAG,UAAU,EAAE,QAAQ;EAAE,CAAC,CACxG;CACF;CACA,SAAU,CAAC,UAAU,WAAW,CAAC,CAAW,SAAS,UAAU,CAC7D;EACE,IAAI;EACJ;EACA,SAAS;EACT,QAAQ;EACR,MAAM;EACN,WAAW;EACX,aAAa;EACb,OAAOA,QAAAA,KAAK,OAAO;GAAE,OAAO;GAAqB,SAASA,QAAAA,KAAK,MAAM,MAAM;GAAG,MAAM,EAAEA,QAAAA,KAAK,QAAQ,IAAI,CAAC;EAAE,CAAC;CAC7G,GACA;EACE,IAAI;EACJ;EACA,SAAS;EACT,QAAQ;EACR,MAAM;EACN,WAAW;EACX,aAAa;EACb,OAAOA,QAAAA,KAAK,OAAO,EAAE,QAAQ,OAAO;GAAC;GAAU;GAAW;GAAQ;EAAW,CAAC,EAAE,CAAC;CACnF,CACF,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"apiContracts.cjs","names":["Type","jsonApiResponses","defineApiContract"],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract, jsonApiResponses, type PoHttpContract } from '@agimon-ai/po-core/apiContracts';\nimport { Type } from 'typebox';\n\nconst S = Type.String();\nconst N = Type.Number();\nconst O = Type.Optional;\nconst values = <T extends string>(items: T[]) => Type.Union(items.map((item) => Type.Literal(item)));\nconst Json = Type.Unknown({\n description:\n 'Desktop provider JSON value. Targets, observations and action results are supplied by the admitted Desktop provider.',\n});\nconst Target = Type.Record(S, Json);\nconst Error = Type.Object({ code: S, message: S });\nconst Artifact = Type.Object({\n artifactId: S,\n status: values(['ready', 'failed']),\n sizeBytes: O(N),\n downloadUrl: O(S),\n previewUrl: O(S),\n actionCount: O(N),\n completedAt: O(S),\n failure: O(Error),\n});\nexport const ComputerStateSchema = Type.Object({\n sessionId: S,\n revision: N,\n wake: N,\n phase: values(['inactive', 'awaiting_confirmation', 'activating', 'active', 'stopping', 'failed']),\n requestId: O(S),\n target: O(Target),\n durationMs: O(N),\n expiresAt: O(N),\n failure: O(Error),\n artifact: O(Artifact),\n});\nconst Permission = values(['accessibility', 'screen-recording', 'microphone', 'automation', 'full-disk-access']);\nconst PermissionState = values(['granted', 'denied', 'not-determined', 'per-app']);\nexport const DesktopPermissionStatesSchema = Type.Object({\n accessibility: PermissionState,\n 'screen-recording': PermissionState,\n microphone: PermissionState,\n automation: PermissionState,\n 'full-disk-access': PermissionState,\n});\nconst Reference = { snapshotId: Type.String({ minLength: 1 }), elementRef: Type.String({ minLength: 1 }) };\nexport const ComputerActionSchema = Type.Union([\n Type.Object({ kind: values(['press', 'focus']), ...Reference }, { additionalProperties: false }),\n Type.Object({ kind: Type.Literal('set_value'), ...Reference, value: S }, { additionalProperties: false }),\n Type.Object(\n {\n kind: Type.Literal('scroll'),\n ...Reference,\n direction: values(['up', 'down', 'left', 'right']),\n amount: values(['line', 'page']),\n },\n { additionalProperties: false },\n ),\n]);\nconst internal = (\n method: 'GET' | 'POST',\n path: string,\n output: object,\n body?: object,\n status = 200,\n): PoHttpContract => ({\n id: `computer.${path.slice(1).replaceAll('/', '.')}`,\n scope: 'session',\n basePath: 'computer-use',\n path,\n method,\n authentication: 'owner',\n description: `Computer use broker ${path}. Requires the host-issued ${path.startsWith('/agent/') ? 'agent' : 'hub'} bearer token.`,\n availability: 'Internal broker route; ordinary browser credentials are insufficient.',\n parameters: [{ name: 'Authorization', in: 'header', required: true, schema: Type.String({ pattern: '^Bearer .+' }) }],\n ...(body ? { body: { required: true, contentType: 'application/json', schema: body } } : {}),\n responses: jsonApiResponses(output, status),\n});\nexport const apiContracts = defineApiContract({\n version: 1,\n dynamic: ['Desktop provider target extensions, observations and operation results are runtime-defined JSON.'],\n http: [\n ...(['global', 'workspace', 'session'] as const).flatMap((scope) =>\n (['GET', 'POST'] as const).map((method) => ({\n id: `computer.permissions.${method === 'GET' ? 'read' : 'request'}`,\n scope,\n basePath: 'desktop-permissions',\n path: '/',\n method,\n authentication: 'owner' as const,\n description:\n method === 'GET'\n ? 'Read the Mac-owned permission states. Requires an authorized local Desktop caller or trusted remote caller.'\n : 'Ask macOS for one named permission. Requires an authorized local Desktop caller or remote passkey step-up.',\n availability: 'Requires Po Desktop to be running this server; otherwise returns 404.',\n ...(method === 'POST'\n ? {\n body: {\n required: true,\n contentType: 'application/json',\n schema: Type.Object({ permission: Permission }),\n },\n }\n : {}),\n responses: {\n ...jsonApiResponses(DesktopPermissionStatesSchema),\n '502': { description: 'Desktop permission request failed.', schema: Type.Object({ error: S }) },\n },\n })),\n ),\n {\n id: 'computer.activation.state',\n scope: 'session',\n basePath: 'computer-use',\n path: '/activate',\n method: 'GET',\n authentication: 'owner',\n description: 'Read state as the matching pending requester or approved recording reader.',\n responses: jsonApiResponses(ComputerStateSchema),\n },\n {\n id: 'computer.activation.cancel',\n scope: 'session',\n basePath: 'computer-use',\n path: '/activate',\n method: 'DELETE',\n authentication: 'owner',\n description: 'Cancel only the matching requester pending activation.',\n responses: jsonApiResponses(ComputerStateSchema, 202),\n },\n {\n id: 'computer.activate',\n scope: 'session',\n basePath: 'computer-use',\n path: '/activate',\n method: 'POST',\n authentication: 'owner',\n description:\n 'Request confirmed Desktop access with admitted caller and remote step-up context. A remote caller may omit target so the local Mac selects the window.',\n body: {\n required: true,\n contentType: 'application/json',\n schema: Type.Object({\n target: O(Type.Object({ windowId: S, bundleId: S })),\n durationMs: Type.Integer({ minimum: 1000, maximum: 1800000 }),\n }),\n },\n responses: jsonApiResponses(ComputerStateSchema, 202),\n },\n {\n id: 'computer.artifact',\n scope: 'session',\n basePath: 'computer-use',\n path: '/artifact',\n method: 'GET',\n authentication: 'owner',\n description: 'Read at most 1 MiB of a recording belonging to this session and approved caller.',\n parameters: [\n { name: 'artifactId', in: 'query', required: true, schema: S },\n { name: 'offset', in: 'query', required: true, schema: Type.Integer({ minimum: 0 }) },\n ],\n responses: {\n 206: {\n description: 'Bounded recording bytes.',\n contentType: 'video/mp4',\n schema: Type.String({ format: 'binary' }),\n },\n },\n },\n internal('GET', '/agent/state', ComputerStateSchema),\n internal('GET', '/hub/state', ComputerStateSchema),\n internal('POST', '/agent/observe', Json),\n internal('POST', '/agent/action', Json, ComputerActionSchema),\n internal('POST', '/agent/stop', ComputerStateSchema, undefined, 202),\n internal(\n 'GET',\n '/hub/activation',\n Type.Union([\n Type.Null(),\n Type.Object({\n requestId: S,\n target: Target,\n durationSeconds: N,\n createdAt: N,\n confirmationExpiresAt: N,\n caller: Type.Object({ locality: values(['local', 'remote']), stepUp: S }),\n }),\n ]),\n ),\n internal('GET', '/hub/authorization', Type.Union([Type.Null(), Type.Object({ grantId: S, expiresAt: O(N) })])),\n internal(\n 'GET',\n '/hub/next',\n Type.Union([\n Type.Null(),\n Type.Object({ id: S, operation: values(['observe', 'act']), payload: O(Json), grantId: S, sequence: O(N) }),\n ]),\n ),\n internal('POST', '/hub/complete', ComputerStateSchema, Type.Object({ id: S, error: O(S), result: O(Json) })),\n internal(\n 'POST',\n '/hub/stop',\n ComputerStateSchema,\n Type.Object({ error: O(S), host: O(Type.Object({ grantId: S, expiresAt: N })), artifact: O(Artifact) }),\n ),\n ],\n sockets: (['global', 'workspace'] as const).flatMap((scope) => [\n {\n id: 'computer.state',\n scope,\n service: 'po.hub',\n member: 'computer_use_state',\n kind: 'channel',\n direction: 'server-to-client',\n description: 'Computer use channel payload.',\n input: Type.Object({ state: ComputerStateSchema, targets: Type.Array(Target), busy: O(Type.Literal(true)) }),\n },\n {\n id: 'computer.command',\n scope,\n service: 'po.hub',\n member: 'computer_use_state',\n kind: 'channel',\n direction: 'client-to-server',\n description: 'Computer use browser channel command.',\n input: Type.Object({ action: values(['status', 'targets', 'stop', 'artifacts']) }),\n },\n ]),\n});\nexport default apiContracts;\n"],"mappings":";;;;;;;AAGA,MAAM,IAAIA,QAAAA,KAAK,OAAO;AACtB,MAAM,IAAIA,QAAAA,KAAK,OAAO;AACtB,MAAM,IAAIA,QAAAA,KAAK;AACf,MAAM,UAA4B,UAAeA,QAAAA,KAAK,MAAM,MAAM,KAAK,SAASA,QAAAA,KAAK,QAAQ,IAAI,CAAC,CAAC;AACnG,MAAM,OAAOA,QAAAA,KAAK,QAAQ,EACxB,aACE,uHACJ,CAAC;AACD,MAAM,SAASA,QAAAA,KAAK,OAAO,GAAG,IAAI;AAClC,MAAM,QAAQA,QAAAA,KAAK,OAAO;CAAE,MAAM;CAAG,SAAS;AAAE,CAAC;AACjD,MAAM,WAAWA,QAAAA,KAAK,OAAO;CAC3B,YAAY;CACZ,QAAQ,OAAO,CAAC,SAAS,QAAQ,CAAC;CAClC,WAAW,EAAE,CAAC;CACd,aAAa,EAAE,CAAC;CAChB,YAAY,EAAE,CAAC;CACf,aAAa,EAAE,CAAC;CAChB,aAAa,EAAE,CAAC;CAChB,SAAS,EAAE,KAAK;AAClB,CAAC;AACD,MAAa,sBAAsBA,QAAAA,KAAK,OAAO;CAC7C,WAAW;CACX,UAAU;CACV,MAAM;CACN,OAAO,OAAO;EAAC;EAAY;EAAyB;EAAc;EAAU;EAAY;CAAQ,CAAC;CACjG,WAAW,EAAE,CAAC;CACd,QAAQ,EAAE,MAAM;CAChB,YAAY,EAAE,CAAC;CACf,WAAW,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file":"apiContracts.d.mts","names":[],"sources":["../src/schemas/apiContracts.ts"],"mappings":";;qBAoEa"}
1
+ {"version":3,"file":"apiContracts.d.mts","names":[],"sources":["../src/schemas/apiContracts.ts"],"mappings":";;qBA6Ea"}
@@ -40,6 +40,26 @@ const ComputerStateSchema = Type.Object({
40
40
  failure: O(Error),
41
41
  artifact: O(Artifact)
42
42
  });
43
+ const Permission = values([
44
+ "accessibility",
45
+ "screen-recording",
46
+ "microphone",
47
+ "automation",
48
+ "full-disk-access"
49
+ ]);
50
+ const PermissionState = values([
51
+ "granted",
52
+ "denied",
53
+ "not-determined",
54
+ "per-app"
55
+ ]);
56
+ const DesktopPermissionStatesSchema = Type.Object({
57
+ accessibility: PermissionState,
58
+ "screen-recording": PermissionState,
59
+ microphone: PermissionState,
60
+ automation: PermissionState,
61
+ "full-disk-access": PermissionState
62
+ });
43
63
  const Reference = {
44
64
  snapshotId: Type.String({ minLength: 1 }),
45
65
  elementRef: Type.String({ minLength: 1 })
@@ -92,6 +112,32 @@ const apiContracts = defineApiContract({
92
112
  version: 1,
93
113
  dynamic: ["Desktop provider target extensions, observations and operation results are runtime-defined JSON."],
94
114
  http: [
115
+ ...[
116
+ "global",
117
+ "workspace",
118
+ "session"
119
+ ].flatMap((scope) => ["GET", "POST"].map((method) => ({
120
+ id: `computer.permissions.${method === "GET" ? "read" : "request"}`,
121
+ scope,
122
+ basePath: "desktop-permissions",
123
+ path: "/",
124
+ method,
125
+ authentication: "owner",
126
+ description: method === "GET" ? "Read the Mac-owned permission states. Requires an authorized local Desktop caller or trusted remote caller." : "Ask macOS for one named permission. Requires an authorized local Desktop caller or remote passkey step-up.",
127
+ availability: "Requires Po Desktop to be running this server; otherwise returns 404.",
128
+ ...method === "POST" ? { body: {
129
+ required: true,
130
+ contentType: "application/json",
131
+ schema: Type.Object({ permission: Permission })
132
+ } } : {},
133
+ responses: {
134
+ ...jsonApiResponses(DesktopPermissionStatesSchema),
135
+ "502": {
136
+ description: "Desktop permission request failed.",
137
+ schema: Type.Object({ error: S })
138
+ }
139
+ }
140
+ }))),
95
141
  {
96
142
  id: "computer.activation.state",
97
143
  scope: "session",
@@ -1 +1 @@
1
- {"version":3,"file":"apiContracts.mjs","names":[],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract, jsonApiResponses, type PoHttpContract } from '@agimon-ai/po-core/apiContracts';\nimport { Type } from 'typebox';\n\nconst S = Type.String();\nconst N = Type.Number();\nconst O = Type.Optional;\nconst values = <T extends string>(items: T[]) => Type.Union(items.map((item) => Type.Literal(item)));\nconst Json = Type.Unknown({\n description:\n 'Desktop provider JSON value. Targets, observations and action results are supplied by the admitted Desktop provider.',\n});\nconst Target = Type.Record(S, Json);\nconst Error = Type.Object({ code: S, message: S });\nconst Artifact = Type.Object({\n artifactId: S,\n status: values(['ready', 'failed']),\n sizeBytes: O(N),\n downloadUrl: O(S),\n previewUrl: O(S),\n actionCount: O(N),\n completedAt: O(S),\n failure: O(Error),\n});\nexport const ComputerStateSchema = Type.Object({\n sessionId: S,\n revision: N,\n wake: N,\n phase: values(['inactive', 'awaiting_confirmation', 'activating', 'active', 'stopping', 'failed']),\n requestId: O(S),\n target: O(Target),\n durationMs: O(N),\n expiresAt: O(N),\n failure: O(Error),\n artifact: O(Artifact),\n});\nconst Reference = { snapshotId: Type.String({ minLength: 1 }), elementRef: Type.String({ minLength: 1 }) };\nexport const ComputerActionSchema = Type.Union([\n Type.Object({ kind: values(['press', 'focus']), ...Reference }, { additionalProperties: false }),\n Type.Object({ kind: Type.Literal('set_value'), ...Reference, value: S }, { additionalProperties: false }),\n Type.Object(\n {\n kind: Type.Literal('scroll'),\n ...Reference,\n direction: values(['up', 'down', 'left', 'right']),\n amount: values(['line', 'page']),\n },\n { additionalProperties: false },\n ),\n]);\nconst internal = (\n method: 'GET' | 'POST',\n path: string,\n output: object,\n body?: object,\n status = 200,\n): PoHttpContract => ({\n id: `computer.${path.slice(1).replaceAll('/', '.')}`,\n scope: 'session',\n basePath: 'computer-use',\n path,\n method,\n authentication: 'owner',\n description: `Computer use broker ${path}. Requires the host-issued ${path.startsWith('/agent/') ? 'agent' : 'hub'} bearer token.`,\n availability: 'Internal broker route; ordinary browser credentials are insufficient.',\n parameters: [{ name: 'Authorization', in: 'header', required: true, schema: Type.String({ pattern: '^Bearer .+' }) }],\n ...(body ? { body: { required: true, contentType: 'application/json', schema: body } } : {}),\n responses: jsonApiResponses(output, status),\n});\nexport const apiContracts = defineApiContract({\n version: 1,\n dynamic: ['Desktop provider target extensions, observations and operation results are runtime-defined JSON.'],\n http: [\n {\n id: 'computer.activation.state',\n scope: 'session',\n basePath: 'computer-use',\n path: '/activate',\n method: 'GET',\n authentication: 'owner',\n description: 'Read state as the matching pending requester or approved recording reader.',\n responses: jsonApiResponses(ComputerStateSchema),\n },\n {\n id: 'computer.activation.cancel',\n scope: 'session',\n basePath: 'computer-use',\n path: '/activate',\n method: 'DELETE',\n authentication: 'owner',\n description: 'Cancel only the matching requester pending activation.',\n responses: jsonApiResponses(ComputerStateSchema, 202),\n },\n {\n id: 'computer.activate',\n scope: 'session',\n basePath: 'computer-use',\n path: '/activate',\n method: 'POST',\n authentication: 'owner',\n description:\n 'Request confirmed Desktop access with admitted caller and remote step-up context. A remote caller may omit target so the local Mac selects the window.',\n body: {\n required: true,\n contentType: 'application/json',\n schema: Type.Object({\n target: O(Type.Object({ windowId: S, bundleId: S })),\n durationMs: Type.Integer({ minimum: 1000, maximum: 1800000 }),\n }),\n },\n responses: jsonApiResponses(ComputerStateSchema, 202),\n },\n {\n id: 'computer.artifact',\n scope: 'session',\n basePath: 'computer-use',\n path: '/artifact',\n method: 'GET',\n authentication: 'owner',\n description: 'Read at most 1 MiB of a recording belonging to this session and approved caller.',\n parameters: [\n { name: 'artifactId', in: 'query', required: true, schema: S },\n { name: 'offset', in: 'query', required: true, schema: Type.Integer({ minimum: 0 }) },\n ],\n responses: {\n 206: {\n description: 'Bounded recording bytes.',\n contentType: 'video/mp4',\n schema: Type.String({ format: 'binary' }),\n },\n },\n },\n internal('GET', '/agent/state', ComputerStateSchema),\n internal('GET', '/hub/state', ComputerStateSchema),\n internal('POST', '/agent/observe', Json),\n internal('POST', '/agent/action', Json, ComputerActionSchema),\n internal('POST', '/agent/stop', ComputerStateSchema, undefined, 202),\n internal(\n 'GET',\n '/hub/activation',\n Type.Union([\n Type.Null(),\n Type.Object({\n requestId: S,\n target: Target,\n durationSeconds: N,\n createdAt: N,\n confirmationExpiresAt: N,\n caller: Type.Object({ locality: values(['local', 'remote']), stepUp: S }),\n }),\n ]),\n ),\n internal('GET', '/hub/authorization', Type.Union([Type.Null(), Type.Object({ grantId: S, expiresAt: O(N) })])),\n internal(\n 'GET',\n '/hub/next',\n Type.Union([\n Type.Null(),\n Type.Object({ id: S, operation: values(['observe', 'act']), payload: O(Json), grantId: S, sequence: O(N) }),\n ]),\n ),\n internal('POST', '/hub/complete', ComputerStateSchema, Type.Object({ id: S, error: O(S), result: O(Json) })),\n internal(\n 'POST',\n '/hub/stop',\n ComputerStateSchema,\n Type.Object({ error: O(S), host: O(Type.Object({ grantId: S, expiresAt: N })), artifact: O(Artifact) }),\n ),\n ],\n sockets: (['global', 'workspace'] as const).flatMap((scope) => [\n {\n id: 'computer.state',\n scope,\n service: 'po.hub',\n member: 'computer_use_state',\n kind: 'channel',\n direction: 'server-to-client',\n description: 'Computer use channel payload.',\n input: Type.Object({ state: ComputerStateSchema, targets: Type.Array(Target), busy: O(Type.Literal(true)) }),\n },\n {\n id: 'computer.command',\n scope,\n service: 'po.hub',\n member: 'computer_use_state',\n kind: 'channel',\n direction: 'client-to-server',\n description: 'Computer use browser channel command.',\n input: Type.Object({ action: values(['status', 'targets', 'stop', 'artifacts']) }),\n },\n ]),\n});\nexport default apiContracts;\n"],"mappings":";;;AAGA,MAAM,IAAI,KAAK,OAAO;AACtB,MAAM,IAAI,KAAK,OAAO;AACtB,MAAM,IAAI,KAAK;AACf,MAAM,UAA4B,UAAe,KAAK,MAAM,MAA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;GAAE,IAAI;GAAG,OAAO,EAAE,CAAC;GAAG,QAAQ,EAAE,IAAI;EAAE,CAAC,CAAC;EAC3G,SACE,QACA,aACA,qBACA,KAAK,OAAO;GAAE,OAAO,EAAE,CAAC;GAAG,MAAM,EAAE,KAAK,OAAO;IAAE,SAAS;IAAG,WAAW;GAAE,CAAC,CAAC;GAAG,UAAU,EAAE,QAAQ;EAAE,CAAC,CACxG;CACF;CACA,SAAU,CAAC,UAAU,WAAW,CAAC,CAAW,SAAS,UAAU,CAC7D;EACE,IAAI;EACJ;EACA,SAAS;EACT,QAAQ;EACR,MAAM;EACN,WAAW;EACX,aAAa;EACb,OAAO,KAAK,OAAO;GAAE,OAAO;GAAqB,SAAS,KAAK,MAAM,MAAM;GAAG,MAAM,EAAE,KAAK,QAAQ,IAAI,CAAC;EAAE,CAAC;CAC7G,GACA;EACE,IAAI;EACJ;EACA,SAAS;EACT,QAAQ;EACR,MAAM;EACN,WAAW;EACX,aAAa;EACb,OAAO,KAAK,OAAO,EAAE,QAAQ,OAAO;GAAC;GAAU;GAAW;GAAQ;EAAW,CAAC,EAAE,CAAC;CACnF,CACF,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"apiContracts.mjs","names":[],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract, jsonApiResponses, type PoHttpContract } from '@agimon-ai/po-core/apiContracts';\nimport { Type } from 'typebox';\n\nconst S = Type.String();\nconst N = Type.Number();\nconst O = Type.Optional;\nconst values = <T extends string>(items: T[]) => Type.Union(items.map((item) => Type.Literal(item)));\nconst Json = Type.Unknown({\n description:\n 'Desktop provider JSON value. Targets, observations and action results are supplied by the admitted Desktop provider.',\n});\nconst Target = Type.Record(S, Json);\nconst Error = Type.Object({ code: S, message: S });\nconst Artifact = Type.Object({\n artifactId: S,\n status: values(['ready', 'failed']),\n sizeBytes: O(N),\n downloadUrl: O(S),\n previewUrl: O(S),\n actionCount: O(N),\n completedAt: O(S),\n failure: O(Error),\n});\nexport const ComputerStateSchema = Type.Object({\n sessionId: S,\n revision: N,\n wake: N,\n phase: values(['inactive', 'awaiting_confirmation', 'activating', 'active', 'stopping', 'failed']),\n requestId: O(S),\n target: O(Target),\n durationMs: O(N),\n expiresAt: O(N),\n failure: O(Error),\n artifact: O(Artifact),\n});\nconst Permission = values(['accessibility', 'screen-recording', 'microphone', 'automation', 'full-disk-access']);\nconst PermissionState = values(['granted', 'denied', 'not-determined', 'per-app']);\nexport const DesktopPermissionStatesSchema = Type.Object({\n accessibility: PermissionState,\n 'screen-recording': PermissionState,\n microphone: PermissionState,\n automation: PermissionState,\n 'full-disk-access': PermissionState,\n});\nconst Reference = { snapshotId: Type.String({ minLength: 1 }), elementRef: Type.String({ minLength: 1 }) };\nexport const ComputerActionSchema = Type.Union([\n Type.Object({ kind: values(['press', 'focus']), ...Reference }, { additionalProperties: false }),\n Type.Object({ kind: Type.Literal('set_value'), ...Reference, value: S }, { additionalProperties: false }),\n Type.Object(\n {\n kind: Type.Literal('scroll'),\n ...Reference,\n direction: values(['up', 'down', 'left', 'right']),\n amount: values(['line', 'page']),\n },\n { additionalProperties: false },\n ),\n]);\nconst internal = (\n method: 'GET' | 'POST',\n path: string,\n output: object,\n body?: object,\n status = 200,\n): PoHttpContract => ({\n id: `computer.${path.slice(1).replaceAll('/', '.')}`,\n scope: 'session',\n basePath: 'computer-use',\n path,\n method,\n authentication: 'owner',\n description: `Computer use broker ${path}. Requires the host-issued ${path.startsWith('/agent/') ? 'agent' : 'hub'} bearer token.`,\n availability: 'Internal broker route; ordinary browser credentials are insufficient.',\n parameters: [{ name: 'Authorization', in: 'header', required: true, schema: Type.String({ pattern: '^Bearer .+' }) }],\n ...(body ? { body: { required: true, contentType: 'application/json', schema: body } } : {}),\n responses: jsonApiResponses(output, status),\n});\nexport const apiContracts = defineApiContract({\n version: 1,\n dynamic: ['Desktop provider target extensions, observations and operation results are runtime-defined JSON.'],\n http: [\n ...(['global', 'workspace', 'session'] as const).flatMap((scope) =>\n (['GET', 'POST'] as const).map((method) => ({\n id: `computer.permissions.${method === 'GET' ? 'read' : 'request'}`,\n scope,\n basePath: 'desktop-permissions',\n path: '/',\n method,\n authentication: 'owner' as const,\n description:\n method === 'GET'\n ? 'Read the Mac-owned permission states. Requires an authorized local Desktop caller or trusted remote caller.'\n : 'Ask macOS for one named permission. Requires an authorized local Desktop caller or remote passkey step-up.',\n availability: 'Requires Po Desktop to be running this server; otherwise returns 404.',\n ...(method === 'POST'\n ? {\n body: {\n required: true,\n contentType: 'application/json',\n schema: Type.Object({ permission: Permission }),\n },\n }\n : {}),\n responses: {\n ...jsonApiResponses(DesktopPermissionStatesSchema),\n '502': { description: 'Desktop permission request failed.', schema: Type.Object({ error: S }) },\n },\n })),\n ),\n {\n id: 'computer.activation.state',\n scope: 'session',\n basePath: 'computer-use',\n path: '/activate',\n method: 'GET',\n authentication: 'owner',\n description: 'Read state as the matching pending requester or approved recording reader.',\n responses: jsonApiResponses(ComputerStateSchema),\n },\n {\n id: 'computer.activation.cancel',\n scope: 'session',\n basePath: 'computer-use',\n path: '/activate',\n method: 'DELETE',\n authentication: 'owner',\n description: 'Cancel only the matching requester pending activation.',\n responses: jsonApiResponses(ComputerStateSchema, 202),\n },\n {\n id: 'computer.activate',\n scope: 'session',\n basePath: 'computer-use',\n path: '/activate',\n method: 'POST',\n authentication: 'owner',\n description:\n 'Request confirmed Desktop access with admitted caller and remote step-up context. A remote caller may omit target so the local Mac selects the window.',\n body: {\n required: true,\n contentType: 'application/json',\n schema: Type.Object({\n target: O(Type.Object({ windowId: S, bundleId: S })),\n durationMs: Type.Integer({ minimum: 1000, maximum: 1800000 }),\n }),\n },\n responses: jsonApiResponses(ComputerStateSchema, 202),\n },\n {\n id: 'computer.artifact',\n scope: 'session',\n basePath: 'computer-use',\n path: '/artifact',\n method: 'GET',\n authentication: 'owner',\n description: 'Read at most 1 MiB of a recording belonging to this session and approved caller.',\n parameters: [\n { name: 'artifactId', in: 'query', required: true, schema: S },\n { name: 'offset', in: 'query', required: true, schema: Type.Integer({ minimum: 0 }) },\n ],\n responses: {\n 206: {\n description: 'Bounded recording bytes.',\n contentType: 'video/mp4',\n schema: Type.String({ format: 'binary' }),\n },\n },\n },\n internal('GET', '/agent/state', ComputerStateSchema),\n internal('GET', '/hub/state', ComputerStateSchema),\n internal('POST', '/agent/observe', Json),\n internal('POST', '/agent/action', Json, ComputerActionSchema),\n internal('POST', '/agent/stop', ComputerStateSchema, undefined, 202),\n internal(\n 'GET',\n '/hub/activation',\n Type.Union([\n Type.Null(),\n Type.Object({\n requestId: S,\n target: Target,\n durationSeconds: N,\n createdAt: N,\n confirmationExpiresAt: N,\n caller: Type.Object({ locality: values(['local', 'remote']), stepUp: S }),\n }),\n ]),\n ),\n internal('GET', '/hub/authorization', Type.Union([Type.Null(), Type.Object({ grantId: S, expiresAt: O(N) })])),\n internal(\n 'GET',\n '/hub/next',\n Type.Union([\n Type.Null(),\n Type.Object({ id: S, operation: values(['observe', 'act']), payload: O(Json), grantId: S, sequence: O(N) }),\n ]),\n ),\n internal('POST', '/hub/complete', ComputerStateSchema, Type.Object({ id: S, error: O(S), result: O(Json) })),\n internal(\n 'POST',\n '/hub/stop',\n ComputerStateSchema,\n Type.Object({ error: O(S), host: O(Type.Object({ grantId: S, expiresAt: N })), artifact: O(Artifact) }),\n ),\n ],\n sockets: (['global', 'workspace'] as const).flatMap((scope) => [\n {\n id: 'computer.state',\n scope,\n service: 'po.hub',\n member: 'computer_use_state',\n kind: 'channel',\n direction: 'server-to-client',\n description: 'Computer use channel payload.',\n input: Type.Object({ state: ComputerStateSchema, targets: Type.Array(Target), busy: O(Type.Literal(true)) }),\n },\n {\n id: 'computer.command',\n scope,\n service: 'po.hub',\n member: 'computer_use_state',\n kind: 'channel',\n direction: 'client-to-server',\n description: 'Computer use browser channel command.',\n input: Type.Object({ action: values(['status', 'targets', 'stop', 'artifacts']) }),\n },\n ]),\n});\nexport default apiContracts;\n"],"mappings":";;;AAGA,MAAM,IAAI,KA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Aa;EACb,OAAO,KAAK,OAAO;GAAE,OAAO;GAAqB,SAAS,KAAK,MAAM,MAAM;GAAG,MAAM,EAAE,KAAK,QAAQ,IAAI,CAAC;EAAE,CAAC;CAC7G,GACA;EACE,IAAI;EACJ;EACA,SAAS;EACT,QAAQ;EACR,MAAM;EACN,WAAW;EACX,aAAa;EACb,OAAO,KAAK,OAAO,EAAE,QAAQ,OAAO;GAAC;GAAU;GAAW;GAAQ;EAAW,CAAC,EAAE,CAAC;CACnF,CACF,CAAC;AACH,CAAC"}
@@ -35,6 +35,13 @@ const COMPUTER_USE_TOOL_NAMES = [
35
35
  "computer_action",
36
36
  "computer_exec"
37
37
  ];
38
+ /** The session artifact storage service and the folder computer-use evidence lands in. */
39
+ const COMPUTER_USE_ARTIFACTS_SERVICE = "po/artifacts";
40
+ const COMPUTER_USE_ARTIFACT_DIRECTORY = "computer-use";
41
+ /** The host recording store's own bounds: its largest recording and its range size. */
42
+ const COMPUTER_USE_RECORDING_MAX_BYTES = 134217728;
43
+ const COMPUTER_USE_RECORDING_CHUNK_BYTES = 1048576;
44
+ const COMPUTER_USE_CODEMODE_GUIDANCE = "[COMPUTER USE ACTIVE]\nUse computer.state() in exec before acting and after any action that may change the interface. Use only element refs and snapshot ids returned by computer.state(). Never infer coordinates or bypass secure elements. Call computer.stop() when the task is complete. Load codemode-how-to-computer-use for details.";
38
45
  //#endregion
39
46
  //#region src/services/computerScriptWorker/index.ts
40
47
  /** Source for an isolated child process. Restricted modules execute in QuickJS, not in Node's realm. */
@@ -68,10 +75,12 @@ async function restricted(message) {
68
75
  runtime.setMaxStackSize(512 * 1024);
69
76
  const deadline = Date.now() + message.timeoutMs;
70
77
  runtime.setInterruptHandler(() => controller.signal.aborted || Date.now() >= deadline);
71
- const root = realpathSync(message.scriptRoot);
78
+ const { realpath } = await import('node:fs/promises');
79
+ const root = await realpath(message.scriptRoot);
72
80
  const sources = new Map();
73
81
  let sourceBytes = 0;
74
82
  let moduleFailure;
83
+ // sync: QuickJS invokes module normalization and loading synchronously and cannot await filesystem reads.
75
84
  const modulePath = (candidate) => {
76
85
  const filename = realpathSync(candidate);
77
86
  const relative = path.relative(root, filename);
@@ -464,12 +473,42 @@ Object.defineProperty(exports, "COMMAND_NAME", {
464
473
  return COMMAND_NAME;
465
474
  }
466
475
  });
476
+ Object.defineProperty(exports, "COMPUTER_USE_ARTIFACTS_SERVICE", {
477
+ enumerable: true,
478
+ get: function() {
479
+ return COMPUTER_USE_ARTIFACTS_SERVICE;
480
+ }
481
+ });
482
+ Object.defineProperty(exports, "COMPUTER_USE_ARTIFACT_DIRECTORY", {
483
+ enumerable: true,
484
+ get: function() {
485
+ return COMPUTER_USE_ARTIFACT_DIRECTORY;
486
+ }
487
+ });
488
+ Object.defineProperty(exports, "COMPUTER_USE_CODEMODE_GUIDANCE", {
489
+ enumerable: true,
490
+ get: function() {
491
+ return COMPUTER_USE_CODEMODE_GUIDANCE;
492
+ }
493
+ });
467
494
  Object.defineProperty(exports, "COMPUTER_USE_GUIDANCE", {
468
495
  enumerable: true,
469
496
  get: function() {
470
497
  return COMPUTER_USE_GUIDANCE;
471
498
  }
472
499
  });
500
+ Object.defineProperty(exports, "COMPUTER_USE_RECORDING_CHUNK_BYTES", {
501
+ enumerable: true,
502
+ get: function() {
503
+ return COMPUTER_USE_RECORDING_CHUNK_BYTES;
504
+ }
505
+ });
506
+ Object.defineProperty(exports, "COMPUTER_USE_RECORDING_MAX_BYTES", {
507
+ enumerable: true,
508
+ get: function() {
509
+ return COMPUTER_USE_RECORDING_MAX_BYTES;
510
+ }
511
+ });
473
512
  Object.defineProperty(exports, "COMPUTER_USE_TOOL_NAMES", {
474
513
  enumerable: true,
475
514
  get: function() {
@@ -501,4 +540,4 @@ Object.defineProperty(exports, "__toESM", {
501
540
  }
502
541
  });
503
542
 
504
- //# sourceMappingURL=extensionService-Bp0q295i.cjs.map
543
+ //# sourceMappingURL=extensionService-CgmosGkY.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extensionService-CgmosGkY.cjs","names":["realpath","path","createRequire","spawn"],"sources":["../src/constants/computerUse.ts","../src/services/computerScriptWorker/index.ts","../src/services/computerScriptRunner/index.ts","../src/services/extensionService/index.ts"],"sourcesContent":["export const COMPUTER_USE_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. Use computer_action for one semantic press, focus, set_value, or scroll at a time. Use computer_exec only for a trusted, explicitly allowed local TypeScript script. Never infer coordinates, inspect another application, bypass secure elements, or retry an uncertain outcome. Stop computer use when the task is complete.`;\nexport const COMMAND_NAME = 'computer-use';\nexport const COMMAND_DESCRIPTION = 'Inspect or manage the session computer use mode';\n\nexport const COMPUTER_USE_TOOL_NAMES = ['computer_state', 'computer_action', 'computer_exec'] as const;\n/** The session artifact storage service and the folder computer-use evidence lands in. */\nexport const COMPUTER_USE_ARTIFACTS_SERVICE = 'po/artifacts';\nexport const COMPUTER_USE_ARTIFACT_DIRECTORY = 'computer-use';\n/** The host recording store's own bounds: its largest recording and its range size. */\nexport const COMPUTER_USE_RECORDING_MAX_BYTES = 128 * 1024 * 1024;\nexport const COMPUTER_USE_RECORDING_CHUNK_BYTES = 1024 * 1024;\nexport const COMPUTER_USE_CODEMODE_GUIDANCE =\n '[COMPUTER USE ACTIVE]\\nUse computer.state() in exec before acting and after any action that may change the interface. Use only element refs and snapshot ids returned by computer.state(). Never infer coordinates or bypass secure elements. Call computer.stop() when the task is complete. Load codemode-how-to-computer-use for details.';\n","/** Source for an isolated child process. Restricted modules execute in QuickJS, not in Node's realm. */\nexport const COMPUTER_SCRIPT_WORKER_SOURCE = String.raw`\nimport { readFileSync, realpathSync, statSync } from 'node:fs';\nimport path from 'node:path';\nimport { stripTypeScriptTypes } from 'node:module';\nimport { pathToFileURL } from 'node:url';\n\nlet nextRequestId = 0;\nlet started = false;\nconst pending = new Map();\nconst controller = new AbortController();\nprocess.once('SIGTERM', () => controller.abort());\nconst send = (message) => {\n if (process.connected) process.send(message, () => {});\n};\nconst call = (operation, payload) => new Promise((resolve, reject) => {\n if (controller.signal.aborted) return reject(new Error('Computer script was cancelled.'));\n if (pending.size >= 64) return reject(new Error('Too many outstanding program operations.'));\n const id = String(++nextRequestId);\n pending.set(id, { resolve, reject });\n send({ type: 'program', id, operation, payload });\n});\n\nasync function restricted(message) {\n const { getQuickJS } = await import(pathToFileURL(message.quickjsPath).href);\n const QuickJS = await getQuickJS();\n const runtime = QuickJS.newRuntime();\n runtime.setMemoryLimit(32 * 1024 * 1024);\n runtime.setMaxStackSize(512 * 1024);\n const deadline = Date.now() + message.timeoutMs;\n runtime.setInterruptHandler(() => controller.signal.aborted || Date.now() >= deadline);\n const { realpath } = await import('node:fs/promises');\n const root = await realpath(message.scriptRoot);\n const sources = new Map();\n let sourceBytes = 0;\n let moduleFailure;\n // sync: QuickJS invokes module normalization and loading synchronously and cannot await filesystem reads.\n const modulePath = (candidate) => {\n const filename = realpathSync(candidate);\n const relative = path.relative(root, filename);\n if (relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) {\n throw new Error('Computer helper escapes the admitted script root.');\n }\n if (!/\\.(ts|js|mjs)$/.test(filename)) throw new Error('Computer helpers must be JavaScript or erasable TypeScript.');\n return filename;\n };\n const entry = modulePath(message.scriptPath);\n runtime.setModuleLoader((filename) => {\n // Preserve a rejected normalization even if the engine subsequently asks to load an empty name.\n if (moduleFailure) throw moduleFailure;\n if (sources.has(filename)) return sources.get(filename);\n if (sources.size >= 32 || statSync(filename).size > 256 * 1024) throw new Error('Computer script module limit exceeded.');\n const source = readFileSync(filename, 'utf8');\n sourceBytes += Buffer.byteLength(source);\n if (sourceBytes > 512 * 1024) throw new Error('Computer script source limit exceeded.');\n const compiled = filename.endsWith('.ts') ? stripTypeScriptTypes(source, { mode: 'strip' }) : source;\n sources.set(filename, compiled);\n return compiled;\n }, (base, name) => {\n try {\n if (name === '__entry__') return entry;\n if (!name.startsWith('./') && !name.startsWith('../')) {\n throw new Error('Restricted computer functions cannot import host or package modules.');\n }\n return modulePath(path.resolve(path.dirname(base), name));\n } catch (error) {\n moduleFailure = error;\n throw error;\n }\n });\n const vm = runtime.newContext();\n let disposed = false;\n const deferreds = new Set();\n const pump = () => {\n if (disposed) return;\n const jobs = runtime.executePendingJobs();\n if (jobs.error) {\n const detail = vm.dump(jobs.error);\n jobs.error.dispose();\n throw new Error(detail?.message ?? String(detail));\n }\n };\n const set = (name, value) => {\n vm.setProp(vm.global, name, value);\n value.dispose();\n };\n set('__input', vm.newString(JSON.stringify(message.input)));\n set('__aborted', vm.newFunction('__aborted', () => controller.signal.aborted ? vm.true : vm.false));\n set('__log', vm.newFunction('__log', (level, text) => {\n send({ type: 'log', level: vm.getString(level), message: vm.getString(text) });\n }));\n set('__call', vm.newFunction('__call', (operationHandle, payloadHandle) => {\n const operation = vm.getString(operationHandle);\n const serialized = vm.getString(payloadHandle);\n if (serialized.length > message.maxOutputBytes) throw new Error('Computer action exceeds the size limit.');\n if (operation !== 'observe' && operation !== 'act') throw new Error('Unsupported program operation.');\n const deferred = vm.newPromise();\n deferreds.add(deferred);\n call(operation, JSON.parse(serialized)).then((value) => {\n if (disposed) return;\n const handle = vm.newString(JSON.stringify(value));\n deferred.resolve(handle);\n handle.dispose();\n }, (error) => {\n if (disposed) return;\n const handle = vm.newError(error.message);\n deferred.reject(handle);\n handle.dispose();\n }).then(() => {\n if (disposed) return;\n deferred.dispose();\n deferreds.delete(deferred);\n pump();\n }).catch((error) => send({ type: 'failed', error: error.message }));\n return deferred.handle.dup();\n }));\n let evaluation;\n try {\n evaluation = vm.unwrapResult(vm.evalCode(\n 'import { run } from \"__entry__\";\\n' +\n 'const invoke = __call; const log = __log; const isAborted = __aborted;\\n' +\n 'const program = Object.freeze({\\n' +\n ' observe: async (options = {}) => JSON.parse(await invoke(\"observe\", JSON.stringify(options))),\\n' +\n ' act: async (action) => JSON.parse(await invoke(\"act\", JSON.stringify(action)))\\n' +\n '});\\n' +\n 'const logger = Object.freeze(Object.fromEntries([\"debug\",\"info\",\"warn\",\"error\"].map(level => [level, value => log(level, String(value))])));\\n' +\n 'const signal = Object.freeze({ get aborted() { return isAborted(); }, throwIfAborted() { if (isAborted()) throw new Error(\"Computer script was cancelled.\"); } });\\n' +\n 'const result = await run({ context: { program }, input: JSON.parse(__input), logger, signal });\\n' +\n 'globalThis.__result = result === undefined ? undefined : JSON.stringify(result);',\n path.join(root, '__computer_entry__.mjs'), { type: 'module' },\n ));\n const completion = vm.resolvePromise(evaluation);\n pump();\n const completed = vm.unwrapResult(await completion);\n completed.dispose();\n const result = vm.getProp(vm.global, '__result');\n const resultJson = vm.dump(result);\n result.dispose();\n return resultJson;\n } finally {\n disposed = true;\n for (const deferred of deferreds) deferred.dispose();\n evaluation?.dispose();\n vm.dispose();\n runtime.dispose();\n }\n}\n\nprocess.on('message', async (message) => {\n if (message?.type === 'response') {\n const request = pending.get(message.id);\n if (!request) return;\n pending.delete(message.id);\n if (message.error) request.reject(new Error(message.error));\n else request.resolve(message.value);\n return;\n }\n if (message?.type !== 'start' || started) return;\n started = true;\n try {\n let resultJson;\n if (message.trusted) {\n const loaded = await import(pathToFileURL(message.scriptPath).href);\n if (typeof loaded.run !== 'function') throw new Error('Computer script must export a named run function.');\n const program = {\n observe: (options = {}) => call('observe', options),\n act: (action) => call('act', action),\n };\n const logger = Object.fromEntries(['debug','info','warn','error'].map(level => [level, value => {\n send({ type: 'log', level, message: String(value) });\n }]));\n const result = await loaded.run({ context: { program }, input: message.input, logger, signal: controller.signal });\n resultJson = result === undefined ? undefined : JSON.stringify(result);\n } else {\n resultJson = await restricted(message);\n }\n if (typeof resultJson === 'string' && Buffer.byteLength(resultJson) > message.maxOutputBytes) {\n throw new Error('Computer script result exceeded the size limit.');\n }\n send({ type: 'complete', resultJson });\n } catch (error) {\n send({ type: 'failed', error: String(error?.message ?? error).slice(0, 1024) });\n }\n});\n`;\n","import { spawn } from 'node:child_process';\nimport { realpath } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\n\nimport type {\n ComputerScriptExecutionOptions,\n ComputerScriptExecutionResult,\n ComputerScriptRunnerOptions,\n} from '../../types/computerScript';\nimport type { ComputerUseAction, ComputerUseObservation, ComputerUseSessionClient } from '../../types/computerUse';\nimport { COMPUTER_SCRIPT_WORKER_SOURCE } from '../computerScriptWorker';\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_OUTPUT_BYTES = 256 * 1024;\nconst MAX_IMAGE_BYTES = 6 * 1024 * 1024;\nconst MAX_PENDING_OPERATIONS = 64;\n\nexport class ComputerScriptExecutionError extends Error {\n constructor(\n message: string,\n readonly completedActions: number,\n readonly outcomeUncertain: boolean,\n ) {\n super(message);\n this.name = 'ComputerScriptExecutionError';\n }\n}\n\ninterface WorkerMessage {\n readonly type?: unknown;\n readonly id?: unknown;\n readonly operation?: unknown;\n readonly payload?: unknown;\n readonly level?: unknown;\n readonly message?: unknown;\n readonly resultJson?: unknown;\n readonly error?: unknown;\n}\n\nexport class ComputerScriptRunner {\n private readonly client: ComputerUseSessionClient;\n private readonly allowedScriptPaths: readonly string[];\n private readonly scriptRoot?: string;\n private readonly timeoutMs: number;\n private readonly maxOutputBytes: number;\n\n constructor(options: ComputerScriptRunnerOptions) {\n this.client = options.client;\n this.allowedScriptPaths = options.allowedScriptPaths;\n this.scriptRoot = options.scriptRoot;\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n }\n\n async execute(\n scriptPath: string,\n input: unknown,\n signal?: AbortSignal,\n options: ComputerScriptExecutionOptions = {},\n cwd?: string,\n ): Promise<ComputerScriptExecutionResult> {\n signal?.throwIfAborted();\n const resolvedPath = await realpath(path.resolve(this.scriptRoot ?? cwd ?? process.cwd(), scriptPath));\n const allowedPaths = await Promise.all(\n this.allowedScriptPaths.map(async (candidate) => realpath(candidate).catch(() => '')),\n );\n const trusted = options.trusted === true;\n if ((trusted || this.scriptRoot === undefined) && !allowedPaths.includes(resolvedPath)) {\n throw new Error('Computer script path is not explicitly allowed.');\n }\n if (!/\\.(ts|js|mjs)$/u.test(resolvedPath))\n throw new Error('Computer scripts must be JavaScript or erasable TypeScript files.');\n const root = await realpath(this.scriptRoot ?? path.dirname(resolvedPath));\n const relative = path.relative(root, resolvedPath);\n if (!trusted && (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))) {\n throw new Error('Computer script escapes the admitted script root.');\n }\n const serializedInput = JSON.stringify(input);\n if (serializedInput === undefined) throw new Error('Computer script input must be JSON serializable.');\n if (Buffer.byteLength(serializedInput) > this.maxOutputBytes)\n throw new Error('Computer script input exceeds the size limit.');\n const quickjsPath = trusted ? undefined : createRequire(import.meta.url).resolve('quickjs-emscripten');\n signal?.throwIfAborted();\n const started = performance.now();\n\n return new Promise((resolve, reject) => {\n const child = spawn(process.execPath, ['--input-type=module', '--eval', COMPUTER_SCRIPT_WORKER_SOURCE], {\n stdio: ['ignore', 'pipe', 'pipe', 'ipc'],\n // Preserve Electron's Node mode, but no host credentials, for restricted workers.\n env: trusted ? process.env : { ELECTRON_RUN_AS_NODE: '1' },\n });\n const controller = new AbortController();\n const logs: string[] = [];\n let outputBytes = 0;\n let completedActions = 0;\n let observations = 0;\n let actionInFlight = false;\n let settled = false;\n let completing = false;\n let outstanding = 0;\n let operation: Promise<void> = Promise.resolve();\n const finish = (error?: Error, value?: ComputerScriptExecutionResult): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timeout);\n signal?.removeEventListener('abort', onAbort);\n controller.abort();\n child.kill('SIGTERM');\n const killTimer = setTimeout(() => child.kill('SIGKILL'), 250);\n killTimer.unref();\n if (error) reject(new ComputerScriptExecutionError(error.message, completedActions, actionInFlight));\n else resolve(value!);\n };\n const addOutput = (value: string): boolean => {\n outputBytes += Buffer.byteLength(value);\n if (outputBytes <= this.maxOutputBytes) return true;\n finish(new Error('Computer script output exceeded the size limit.'));\n return false;\n };\n const send = (value: object): void => {\n if (settled || !child.connected) return;\n child.send(value, (error) => {\n if (error && !settled) finish(error);\n });\n };\n const onAbort = (): void => finish(new Error('Computer script execution was cancelled.'));\n const timeout = setTimeout(() => finish(new Error('Computer script execution timed out.')), this.timeoutMs);\n timeout.unref();\n signal?.addEventListener('abort', onAbort, { once: true });\n if (signal?.aborted) return onAbort();\n child.stdout?.on('data', (chunk: Buffer) => addOutput(chunk.toString('utf8')));\n child.stderr?.on('data', (chunk: Buffer) => addOutput(chunk.toString('utf8')));\n child.on('error', (error) => finish(error));\n child.on('exit', (code, exitSignal) => {\n if (!settled)\n finish(new Error(`Computer script worker exited before completion (${exitSignal ?? code ?? 'unknown'}).`));\n });\n\n const observe = async (includeScreenshot: boolean): Promise<ComputerUseObservation> => {\n const value = await this.client.observe(controller.signal, { includeScreenshot });\n observations += 1;\n const { screenshot, ...semantic } = value;\n if (Buffer.byteLength(JSON.stringify(semantic)) > this.maxOutputBytes)\n throw new Error('Computer observation exceeds the size limit.');\n if (includeScreenshot && screenshot) {\n if (screenshot.mimeType !== 'image/png' || screenshot.data.length > Math.ceil(MAX_IMAGE_BYTES / 3) * 4) {\n throw new Error('Computer screenshot exceeds the image limit.');\n }\n return { ...semantic, screenshot };\n }\n return semantic;\n };\n\n child.on('message', (raw: WorkerMessage) => {\n if (settled) return;\n if (!raw || typeof raw !== 'object' || Buffer.byteLength(JSON.stringify(raw)) > this.maxOutputBytes + 4096) {\n finish(new Error('Computer worker message exceeds the size limit.'));\n return;\n }\n if (raw.type === 'log' && typeof raw.message === 'string') {\n const line = `[${String(raw.level)}] ${raw.message}`;\n if (addOutput(line)) logs.push(line);\n return;\n }\n if (raw.type === 'program') {\n if (\n completing ||\n typeof raw.id !== 'string' ||\n raw.id.length > 128 ||\n (raw.operation !== 'observe' && raw.operation !== 'act') ||\n outstanding >= MAX_PENDING_OPERATIONS\n ) {\n finish(new Error('Invalid or excessive computer program operations.'));\n return;\n }\n outstanding += 1;\n operation = operation\n .then(async () => {\n if (settled || controller.signal.aborted) return;\n try {\n let value: unknown;\n if (raw.operation === 'observe') {\n const settings = raw.payload;\n if (\n !settings ||\n typeof settings !== 'object' ||\n Array.isArray(settings) ||\n Object.keys(settings).some((key) => key !== 'includeScreenshot') ||\n ('includeScreenshot' in settings && typeof settings.includeScreenshot !== 'boolean')\n ) {\n throw new Error('Invalid observation options.');\n }\n value = await observe('includeScreenshot' in settings && settings.includeScreenshot === true);\n } else {\n actionInFlight = true;\n value = await this.client.act(raw.payload as ComputerUseAction, controller.signal);\n completedActions += 1;\n actionInFlight = false;\n }\n send({ type: 'response', id: raw.id, value });\n } catch (error) {\n // An action can have taken effect before its transport failed. Never run the remaining chain.\n if (actionInFlight) finish(error instanceof Error ? error : new Error(String(error)));\n else\n send({ type: 'response', id: raw.id, error: error instanceof Error ? error.message : String(error) });\n } finally {\n outstanding -= 1;\n }\n })\n .catch((error: unknown) => finish(error instanceof Error ? error : new Error(String(error))));\n return;\n }\n if (raw.type === 'failed' && typeof raw.error === 'string') {\n finish(new Error(raw.error));\n return;\n }\n if (raw.type === 'complete') {\n if (completing) {\n finish(new Error('Computer worker completed twice.'));\n return;\n }\n completing = true;\n operation = operation\n .then(async () => {\n if (settled) return;\n const resultJson = raw.resultJson;\n if (resultJson !== undefined && typeof resultJson !== 'string')\n throw new Error('Computer script returned an invalid result.');\n if (typeof resultJson === 'string' && !addOutput(resultJson)) return;\n const observation = await observe(options.includeScreenshot === true);\n if (settled || !addOutput(JSON.stringify({ ...observation, screenshot: undefined }))) return;\n finish(undefined, {\n ...(typeof resultJson === 'string' ? { result: JSON.parse(resultJson) as unknown } : {}),\n observation,\n logs,\n metrics: {\n actions: completedActions,\n observations,\n durationMs: Math.round(performance.now() - started),\n outputBytes,\n },\n });\n })\n .catch((error: unknown) => finish(error instanceof Error ? error : new Error(String(error))));\n }\n });\n send({\n type: 'start',\n scriptPath: resolvedPath,\n scriptRoot: root,\n input: JSON.parse(serializedInput) as unknown,\n trusted,\n quickjsPath,\n timeoutMs: this.timeoutMs,\n maxOutputBytes: this.maxOutputBytes,\n });\n });\n }\n}\n","import type { ComputerUseExtensionResult, ComputerUseExtensionService } from '../../types/extension';\nimport type { ComputerUseSessionClient } from '../sessionApiClient';\n\nexport class DefaultComputerUseExtensionService implements ComputerUseExtensionService {\n public constructor(private readonly client?: ComputerUseSessionClient) {}\n\n public async execute(): Promise<ComputerUseExtensionResult> {\n if (this.client === undefined) return { message: 'Computer use requires a Po Desktop session.', level: 'error' };\n const state = await this.client.state();\n return { message: `Computer use is ${state.phase.replaceAll('_', ' ')}.`, level: 'info' };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAa,wBAAwB;;AAErC,MAAa,eAAe;AAC5B,MAAa,sBAAsB;AAEnC,MAAa,0BAA0B;CAAC;CAAkB;CAAmB;AAAe;;AAE5F,MAAa,iCAAiC;AAC9C,MAAa,kCAAkC;;AAE/C,MAAa,mCAAmC;AAChD,MAAa,qCAAqC;AAClD,MAAa,iCACX;;;;ACZF,MAAa,gCAAgC,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACYvD,MAAM,qBAAqB;AAC3B,MAAM,2BAA2B;AACjC,MAAM,kBAAkB;AACxB,MAAM,yBAAyB;AAE/B,IAAa,+BAAb,cAAkD,MAAM;CAG3C;CACA;CAHX,YACE,SACA,kBACA,kBACA;EACA,MAAM,OAAO;EAHJ,KAAA,mBAAA;EACA,KAAA,mBAAA;EAGT,KAAK,OAAO;CACd;AACF;AAaA,IAAa,uBAAb,MAAkC;CAChC;CACA;CACA;CACA;CACA;CA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