@hmharness/environments 0.23.6 → 0.23.10

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/dist/bridges.js CHANGED
@@ -19,6 +19,7 @@ export function browserActBridge(execute, opts) {
19
19
  // visible-browser workflow: coordinate click through the desktop trio
20
20
  return done(await execute('desktop_click', { x: Number(action.args.x ?? 0), y: Number(action.args.y ?? 0) }));
21
21
  case 'type':
22
+ case 'type-text':
22
23
  return done(await execute('desktop_type', { text: String(action.args.text ?? '') }));
23
24
  default:
24
25
  return { outcome: 'failure', error: { code: 'E_UNKNOWN_ACTION', message: `unknown browser action ${action.type}` } };
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @hmharness/environments - CDP act bridge (headless browser exploration)
3
+ *
4
+ * Executes BrowserEnvironment actions natively over the Chrome DevTools
5
+ * Protocol: one WebSocket per action (Node >= 22 ships a built-in client,
6
+ * so zero dependencies), Runtime.evaluate with a small per-action
7
+ * expression. Meant for OWNED browser instances — e.g. a headless Chrome
8
+ * launched with --remote-debugging-port=9222 and a throwaway profile; it
9
+ * never touches the user's default browser.
10
+ */
11
+ import type { Action } from '@hmharness/cognitive';
12
+ export interface CdpActBridgeOptions {
13
+ /** CDP debugging base (default http://127.0.0.1:9222) */
14
+ cdpBase?: string;
15
+ /** per-action timeout (default 10s) */
16
+ timeoutMs?: number;
17
+ }
18
+ /** Pure mapping action → JS expression ('ok' on success). Exported for
19
+ * tests; null = the action's args are missing or unsafe. */
20
+ export declare function cdpExpression(action: Action): string | null;
21
+ export declare class CdpActBridge {
22
+ private opts;
23
+ /** the driven page target, pinned on first use: CDP /json ordering is not
24
+ * stable across calls, so re-picking per action would silently hop between
25
+ * tabs (about:blank vs the explored page) and fail on elements that exist
26
+ * on the OTHER tab. One bridge drives ONE page, like a user on one tab. */
27
+ private pinned;
28
+ constructor(opts?: CdpActBridgeOptions);
29
+ private get base();
30
+ /** is a debugging browser reachable at base? */
31
+ up(): Promise<boolean>;
32
+ /** resolve (and pin) the page target this bridge drives */
33
+ private target;
34
+ act(action: Action, tabId?: string): Promise<{
35
+ outcome: 'success' | 'failure' | 'unknown';
36
+ output?: unknown;
37
+ error?: {
38
+ code: string;
39
+ message: string;
40
+ };
41
+ }>;
42
+ /** one-shot WebSocket Runtime.evaluate against one debug target */
43
+ private evaluate;
44
+ /** best-effort: wait for the navigated page to finish loading so a later
45
+ * action measures the PAGE, not network timing. Never fails the act. */
46
+ private waitLoad;
47
+ }
@@ -0,0 +1,172 @@
1
+ /** Pure mapping action → JS expression ('ok' on success). Exported for
2
+ * tests; null = the action's args are missing or unsafe. */
3
+ export function cdpExpression(action) {
4
+ switch (action.type) {
5
+ case 'navigate': {
6
+ const url = String(action.args.url ?? '');
7
+ if (!/^https?:\/\//i.test(url))
8
+ return null;
9
+ return `(document.location.href=${JSON.stringify(url)}, 'ok')`;
10
+ }
11
+ case 'click': {
12
+ const sel = String(action.args.selector ?? '');
13
+ if (!sel)
14
+ return null;
15
+ return `(()=>{const el=document.querySelector(${JSON.stringify(sel)}); if(!el) return 'E_NO_MATCH'; el.click(); return 'ok';})()`;
16
+ }
17
+ case 'type-text':
18
+ case 'type': {
19
+ const sel = String(action.args.selector ?? '');
20
+ if (!sel)
21
+ return null;
22
+ const text = String(action.args.text ?? '');
23
+ return `(()=>{const el=document.querySelector(${JSON.stringify(sel)}); if(!el) return 'E_NO_MATCH'; el.value=${JSON.stringify(text)}; el.dispatchEvent(new Event('input',{bubbles:true})); return 'ok';})()`;
24
+ }
25
+ default:
26
+ return null;
27
+ }
28
+ }
29
+ export class CdpActBridge {
30
+ opts;
31
+ /** the driven page target, pinned on first use: CDP /json ordering is not
32
+ * stable across calls, so re-picking per action would silently hop between
33
+ * tabs (about:blank vs the explored page) and fail on elements that exist
34
+ * on the OTHER tab. One bridge drives ONE page, like a user on one tab. */
35
+ pinned = null;
36
+ constructor(opts = {}) {
37
+ this.opts = opts;
38
+ }
39
+ get base() {
40
+ return this.opts.cdpBase ?? 'http://127.0.0.1:9222';
41
+ }
42
+ /** is a debugging browser reachable at base? */
43
+ async up() {
44
+ try {
45
+ await fetch(this.base + '/json/version', { signal: AbortSignal.timeout(1_500) });
46
+ return true;
47
+ }
48
+ catch {
49
+ return false;
50
+ }
51
+ }
52
+ /** resolve (and pin) the page target this bridge drives */
53
+ async target(preferredTabId) {
54
+ if (this.pinned)
55
+ return this.pinned;
56
+ let pages = [];
57
+ try {
58
+ const res = await fetch(this.base + '/json', { signal: AbortSignal.timeout(2_000) });
59
+ pages = (await res.json()).filter((t) => t.type === 'page' && t.webSocketDebuggerUrl);
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
64
+ // explicit tab id wins; otherwise prefer a page that is not about:blank
65
+ const tab = (preferredTabId ? pages.find((t) => t.id === preferredTabId) : undefined) ?? pages.find((t) => !t.url.startsWith('about:')) ?? pages[0];
66
+ if (!tab?.webSocketDebuggerUrl)
67
+ return undefined;
68
+ this.pinned = { id: tab.id, wsUrl: tab.webSocketDebuggerUrl };
69
+ return this.pinned;
70
+ }
71
+ async act(action, tabId) {
72
+ const expr = cdpExpression(action);
73
+ if (expr === null) {
74
+ return { outcome: 'failure', error: { code: 'E_BAD_ACTION', message: `action ${action.type} missing or invalid args` } };
75
+ }
76
+ const started = Date.now();
77
+ const target = await this.target(tabId);
78
+ if (!target) {
79
+ return { outcome: 'failure', error: { code: 'E_NO_TABS', message: `no debuggable page at ${this.base}` } };
80
+ }
81
+ try {
82
+ const value = await this.evaluate(target.wsUrl, expr, this.opts.timeoutMs ?? 10_000);
83
+ if (value === 'E_NO_MATCH') {
84
+ return { outcome: 'failure', error: { code: 'E_NO_MATCH', message: 'selector matched no element' } };
85
+ }
86
+ // let the navigation finish loading before the next action lands
87
+ if (action.type === 'navigate')
88
+ await this.waitLoad(target.wsUrl, this.opts.timeoutMs ?? 10_000);
89
+ return { outcome: 'success', output: { value, ms: Date.now() - started } };
90
+ }
91
+ catch (err) {
92
+ // the pinned tab may be gone (crashed/closed): re-resolve once, then fail honestly
93
+ this.pinned = null;
94
+ const retry = await this.target(tabId);
95
+ if (!retry) {
96
+ return { outcome: 'failure', error: { code: 'E_CDP', message: String(err).slice(0, 200) } };
97
+ }
98
+ try {
99
+ const value = await this.evaluate(retry.wsUrl, expr, this.opts.timeoutMs ?? 10_000);
100
+ if (value === 'E_NO_MATCH') {
101
+ return { outcome: 'failure', error: { code: 'E_NO_MATCH', message: 'selector matched no element' } };
102
+ }
103
+ if (action.type === 'navigate')
104
+ await this.waitLoad(retry.wsUrl, this.opts.timeoutMs ?? 10_000);
105
+ return { outcome: 'success', output: { value, ms: Date.now() - started } };
106
+ }
107
+ catch (err2) {
108
+ return { outcome: 'failure', error: { code: 'E_CDP', message: String(err2).slice(0, 200) } };
109
+ }
110
+ }
111
+ }
112
+ /** one-shot WebSocket Runtime.evaluate against one debug target */
113
+ evaluate(wsUrl, expression, timeoutMs, awaitPromise = false) {
114
+ return new Promise((resolve, reject) => {
115
+ let settled = false;
116
+ const ws = new WebSocket(wsUrl);
117
+ const id = 1;
118
+ const timer = setTimeout(() => {
119
+ if (settled)
120
+ return;
121
+ settled = true;
122
+ try {
123
+ ws.close();
124
+ }
125
+ catch { /* already gone */ }
126
+ reject(new Error('CDP evaluate timeout'));
127
+ }, timeoutMs);
128
+ ws.addEventListener('open', () => {
129
+ ws.send(JSON.stringify({ id, method: 'Runtime.evaluate', params: { expression, returnByValue: true, awaitPromise } }));
130
+ });
131
+ ws.addEventListener('message', (ev) => {
132
+ if (settled)
133
+ return;
134
+ const raw = typeof ev.data === 'string' ? ev.data : Buffer.from(ev.data).toString('utf8');
135
+ let msg;
136
+ try {
137
+ msg = JSON.parse(raw);
138
+ }
139
+ catch {
140
+ return;
141
+ }
142
+ if (msg.id !== id)
143
+ return;
144
+ settled = true;
145
+ clearTimeout(timer);
146
+ try {
147
+ ws.close();
148
+ }
149
+ catch { /* already gone */ }
150
+ if (msg.result?.exceptionDetails) {
151
+ reject(new Error('page exception: ' + JSON.stringify(msg.result.exceptionDetails).slice(0, 160)));
152
+ }
153
+ else {
154
+ resolve(String(msg.result?.result?.value ?? ''));
155
+ }
156
+ });
157
+ ws.addEventListener('error', () => {
158
+ if (settled)
159
+ return;
160
+ settled = true;
161
+ clearTimeout(timer);
162
+ reject(new Error('CDP WebSocket error'));
163
+ });
164
+ });
165
+ }
166
+ /** best-effort: wait for the navigated page to finish loading so a later
167
+ * action measures the PAGE, not network timing. Never fails the act. */
168
+ async waitLoad(wsUrl, timeoutMs) {
169
+ const expr = "new Promise(r => document.readyState === 'complete' ? r('ok') : addEventListener('load', () => r('ok')))";
170
+ await this.evaluate(wsUrl, expr, Math.min(timeoutMs, 8_000), true).catch(() => undefined);
171
+ }
172
+ }
package/dist/index.d.ts CHANGED
@@ -17,3 +17,5 @@ export type { Arc3Frame, Arc3Game } from './arc3-rest.js';
17
17
  export { renderFramePng, gridSummary, ARC3_PALETTE } from './arc3-render.js';
18
18
  export { browserActBridge, desktopActBridge } from './bridges.js';
19
19
  export type { ToolExecute } from './bridges.js';
20
+ export { CdpActBridge, cdpExpression } from './cdp-act.js';
21
+ export type { CdpActBridgeOptions } from './cdp-act.js';
package/dist/index.js CHANGED
@@ -12,3 +12,4 @@ export { BrowserEnvironment, DesktopEnvironment, Arc3Environment } from "./adapt
12
12
  export { Arc3RestBridge, ARC3_BASE } from "./arc3-rest.js";
13
13
  export { renderFramePng, gridSummary, ARC3_PALETTE } from "./arc3-render.js";
14
14
  export { browserActBridge, desktopActBridge } from "./bridges.js";
15
+ export { CdpActBridge, cdpExpression } from "./cdp-act.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/environments",
3
- "version": "0.23.6",
3
+ "version": "0.23.10",
4
4
  "description": "HMH Cognitive OS environment adapters: Terminal (native), HarmonyOS (via domain-harmony), Browser/Desktop (via host automation bridge), ARC3 (external adapter). Every adapter implements the @hmharness/cognitive Environment protocol and must pass the shared conformance test.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -26,7 +26,7 @@
26
26
  "node": ">=22"
27
27
  },
28
28
  "dependencies": {
29
- "@hmharness/kernel": "0.23.6",
30
- "@hmharness/cognitive": "0.23.6"
29
+ "@hmharness/kernel": "0.23.10",
30
+ "@hmharness/cognitive": "0.23.10"
31
31
  }
32
32
  }