@hmharness/environments 0.19.8 → 0.20.0

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.
@@ -14,6 +14,7 @@
14
14
  * bundle at runtime; register() refuses to fake runs without it.
15
15
  */
16
16
  import type { Environment, Observation, Action, ActionResult, Snapshot, EnvironmentScore, Capability } from '@hmharness/cognitive';
17
+ import { Arc3RestBridge } from './arc3-rest.js';
17
18
  export interface BrowserEnvOptions {
18
19
  /** CDP debugging address (default Chrome :9222) */
19
20
  cdpBase?: string;
@@ -73,26 +74,25 @@ export declare class DesktopEnvironment implements Environment {
73
74
  close(): Promise<void>;
74
75
  }
75
76
  export interface Arc3EnvOptions {
76
- /** path/endpoint to the ARC-AGI-3 SDK task bundle; REQUIRED for real runs */
77
- taskBundle?: string;
78
- /** host bridge executing ARC interactions (SDK client) */
79
- interact?: (action: Action) => Promise<{
80
- outcome: 'success' | 'failure' | 'unknown';
81
- observation?: unknown;
82
- }>;
77
+ /** live REST bridge (real runs); omit for the honest not-configured state */
78
+ bridge?: Arc3RestBridge;
79
+ /** game to play (game_id from GET /api/games); default: first listed */
80
+ gameId?: string;
83
81
  }
84
82
  export declare class Arc3Environment implements Environment {
85
83
  private opts;
86
84
  id: string;
87
85
  version: string;
86
+ private session;
88
87
  constructor(opts?: Arc3EnvOptions);
89
88
  capabilities(): Promise<Capability[]>;
90
- private refuse;
89
+ private ensureLive;
91
90
  reset(): Promise<Observation>;
92
91
  observe(): Promise<Observation>;
92
+ private actionSpecs;
93
93
  act(action: Action): Promise<ActionResult>;
94
94
  snapshot(): Promise<Snapshot>;
95
- restore(): Promise<void>;
95
+ restore(snapshot: Snapshot): Promise<void>;
96
96
  evaluate(): Promise<EnvironmentScore>;
97
97
  close(): Promise<void>;
98
98
  }
package/dist/adapters.js CHANGED
@@ -160,65 +160,153 @@ export class DesktopEnvironment {
160
160
  export class Arc3Environment {
161
161
  opts;
162
162
  id = 'arc3';
163
- version = '0.1.0';
163
+ version = '1.0.0';
164
+ session = null;
164
165
  constructor(opts = {}) {
165
166
  this.opts = opts;
166
167
  }
167
168
  async capabilities() {
168
- const ready = Boolean(this.opts.taskBundle && this.opts.interact);
169
+ const live = Boolean(this.opts.bridge);
169
170
  return [
170
- { kind: 'observe', detail: 'ARC task grid state via SDK', limitation: ready ? undefined : 'ARC-AGI-3 SDK task bundle + interact bridge required' },
171
- { kind: 'act', detail: 'ARC actions mapped through the SDK', limitation: ready ? undefined : 'not configured — adapter refuses to fake runs' },
172
- { kind: 'evaluate', detail: 'ARC official scoring via SDK replay' },
171
+ { kind: 'observe', detail: 'ARC-AGI-3 game frame via official REST API', limitation: live ? undefined : 'no bridge configured — runArc3() wires the official API (needs X-API-Key)' },
172
+ { kind: 'act', detail: 'ACTION1-7 (ACTION6 = 64×64 coordinate), reasoning rides along', limitation: live ? undefined : 'not configured — refuses to fake runs' },
173
+ { kind: 'evaluate', detail: 'scorecard aggregate via /api/scorecard/{card_id}', limitation: live ? undefined : 'bridge-gated' },
173
174
  ];
174
175
  }
175
- refuse() {
176
- throw new Error('ARC3 adapter is a skeleton: configure Arc3EnvOptions.taskBundle + interact (ARC-001); no fake runs');
176
+ ensureLive() {
177
+ if (!this.opts.bridge)
178
+ throw new Error('ARC3 not wired: construct via runArc3()/Arc3RestBridge (official REST API at three.arcprize.org, X-API-Key required)');
179
+ return this.opts.bridge;
177
180
  }
178
181
  async reset() {
179
- if (!this.opts.interact)
180
- return this.refuse();
181
- const r = await this.opts.interact({ id: 'reset', type: 'reset', args: {} });
182
- return {
183
- environmentId: this.id,
184
- timestamp: new Date().toISOString(),
185
- state: r.observation ?? null,
186
- availableActions: [
187
- { id: 'submit', type: 'submit', description: 'submit an answer grid', argsSchema: { grid: 'unknown' }, cost: 5 },
188
- ],
189
- };
182
+ const bridge = this.ensureLive();
183
+ if (!this.session) {
184
+ const gameId = this.opts.gameId ?? (await bridge.listGames())[0]?.game_id;
185
+ if (!gameId)
186
+ throw new Error('E_ARC3_NO_GAMES: /api/games returned no titles');
187
+ const cardId = await bridge.openScorecard({ tags: ['hmharness'] });
188
+ this.session = { cardId, gameId, steps: 0, totalReward: 0 };
189
+ }
190
+ const frame = await bridge.reset(this.session.gameId, this.session.cardId, this.session.guid);
191
+ this.session.guid = frame.guid;
192
+ this.session.lastFrame = frame;
193
+ this.session.steps = 0;
194
+ return this.observe();
190
195
  }
191
196
  async observe() {
192
- if (!this.opts.interact)
193
- return this.refuse();
194
- const r = await this.opts.interact({ id: 'observe', type: 'observe', args: {} });
197
+ if (!this.session?.lastFrame) {
198
+ // pre-reset: expose the affordance map without touching the API
199
+ return {
200
+ environmentId: this.id,
201
+ timestamp: new Date().toISOString(),
202
+ state: { configured: false, note: 'call reset() first (opens scorecard + starts a game instance)' },
203
+ availableActions: this.actionSpecs(),
204
+ };
205
+ }
206
+ const f = this.session.lastFrame;
195
207
  return {
196
208
  environmentId: this.id,
197
209
  timestamp: new Date().toISOString(),
198
- state: r.observation ?? null,
199
- availableActions: [{ id: 'submit', type: 'submit', description: 'submit an answer grid', argsSchema: { grid: 'unknown' }, cost: 5 }],
210
+ state: {
211
+ gameId: this.session.gameId,
212
+ guid: this.session.guid,
213
+ score: f.score,
214
+ reward: f.reward,
215
+ status: f.status,
216
+ framePreview: Array.isArray(f.frame) ? f.frame.slice(0, 64) : f.frame,
217
+ steps: this.session.steps,
218
+ totalReward: this.session.totalReward,
219
+ },
220
+ availableActions: this.actionSpecs(),
221
+ raw: f,
200
222
  };
201
223
  }
224
+ actionSpecs() {
225
+ return [
226
+ { id: 'a1', type: 'ACTION1', description: 'simple action 1 (game-defined, e.g. move up / option A)', cost: 1 },
227
+ { id: 'a2', type: 'ACTION2', description: 'simple action 2', cost: 1 },
228
+ { id: 'a3', type: 'ACTION3', description: 'simple action 3', cost: 1 },
229
+ { id: 'a4', type: 'ACTION4', description: 'simple action 4', cost: 1 },
230
+ { id: 'a5', type: 'ACTION5', description: 'simple action 5 (e.g. jump / fire / option E)', cost: 1 },
231
+ { id: 'a6', type: 'ACTION6', description: 'coordinate action: click/tap at (x,y) on the 64×64 grid', argsSchema: { x: 'number 0-63', y: 'number 0-63' }, cost: 1 },
232
+ { id: 'a7', type: 'ACTION7', description: 'undo (games that support it)', cost: 1 },
233
+ ];
234
+ }
202
235
  async act(action) {
203
- if (!this.opts.interact)
204
- return this.refuse();
205
- const r = await this.opts.interact(action);
206
- return { actionId: action.id, outcome: r.outcome, output: r.observation };
236
+ const bridge = this.ensureLive();
237
+ const started = Date.now();
238
+ if (!this.session?.guid) {
239
+ return { actionId: action.id, outcome: 'failure', error: { code: 'E_ARC3_NOT_STARTED', message: 'reset() first' }, durationMs: Date.now() - started };
240
+ }
241
+ try {
242
+ let frame;
243
+ const reasoning = action.reason !== undefined ? { reason: action.reason } : undefined;
244
+ if (action.type === 'ACTION6') {
245
+ frame = await bridge.actionXY(this.session.gameId, this.session.guid, Number(action.args.x ?? 32), Number(action.args.y ?? 32), reasoning);
246
+ }
247
+ else if (/^ACTION[1-5]|^ACTION7$/.test(action.type)) {
248
+ frame = await bridge.action(this.session.gameId, this.session.guid, Number(action.type.replace('ACTION', '')), reasoning);
249
+ }
250
+ else {
251
+ return { actionId: action.id, outcome: 'failure', error: { code: 'E_UNKNOWN_ACTION', message: `unknown ARC action ${action.type}` }, durationMs: Date.now() - started };
252
+ }
253
+ this.session.lastFrame = frame;
254
+ this.session.steps += 1;
255
+ this.session.totalReward += frame.reward ?? 0;
256
+ return {
257
+ actionId: action.id,
258
+ outcome: frame.status === 'DEAD' || frame.reward !== undefined && frame.reward < 0 ? 'failure' : 'success',
259
+ output: { score: frame.score, reward: frame.reward, status: frame.status },
260
+ durationMs: Date.now() - started,
261
+ cost: 1,
262
+ };
263
+ }
264
+ catch (err) {
265
+ return { actionId: action.id, outcome: 'failure', error: { code: 'E_ARC3_CALL', message: String(err).slice(0, 250) }, durationMs: Date.now() - started };
266
+ }
207
267
  }
208
268
  async snapshot() {
209
- if (!this.opts.interact)
210
- return this.refuse();
211
- return { environmentId: this.id, version: 1, takenAt: new Date().toISOString(), stateHash: 'arc3-pending', payload: null };
269
+ if (!this.session) {
270
+ return { environmentId: this.id, version: 1, takenAt: new Date().toISOString(), stateHash: 'arc3-not-started', payload: null };
271
+ }
272
+ // ARC sessions are server-side stateful: the snapshot records the handle
273
+ // (guid) so a supervisor can resume, but cannot fork server state
274
+ return {
275
+ environmentId: this.id,
276
+ version: 1,
277
+ takenAt: new Date().toISOString(),
278
+ stateHash: stableHash({ guid: this.session.guid, steps: this.session.steps }),
279
+ payload: { cardId: this.session.cardId, gameId: this.session.gameId, guid: this.session.guid, steps: this.session.steps, totalReward: this.session.totalReward },
280
+ };
212
281
  }
213
- async restore() {
214
- this.refuse();
282
+ async restore(snapshot) {
283
+ const p = snapshot.payload;
284
+ if (p?.guid)
285
+ this.session = { ...p };
215
286
  }
216
287
  async evaluate() {
217
- if (!this.opts.interact)
218
- return this.refuse();
219
- return { environmentId: this.id, metrics: {} };
288
+ const bridge = this.ensureLive();
289
+ if (!this.session)
290
+ return { environmentId: this.id, metrics: {} };
291
+ const summary = await bridge.getScorecard(this.session.cardId).catch(() => ({}));
292
+ const envs = (summary.environments ?? []);
293
+ const mine = envs.find((e) => e.game_id === this.session?.gameId) ?? summary;
294
+ const num = (v) => (typeof v === 'number' ? v : 0);
295
+ return {
296
+ environmentId: this.id,
297
+ metrics: {
298
+ steps: this.session.steps,
299
+ totalReward: this.session.totalReward,
300
+ score: num(mine.score),
301
+ winRate: num(mine.win_rate),
302
+ },
303
+ details: 'ARC-AGI-3 official scorecard',
304
+ };
220
305
  }
221
306
  async close() {
222
- /* nothing held */
307
+ if (this.session) {
308
+ await this.opts.bridge?.closeScorecard(this.session.cardId).catch(() => undefined);
309
+ this.session = null;
310
+ }
223
311
  }
224
312
  }
@@ -0,0 +1,52 @@
1
+ export declare const ARC3_BASE = "https://three.arcprize.org";
2
+ export interface Arc3Frame {
3
+ game_id: string;
4
+ guid: string;
5
+ frame?: number[];
6
+ score?: number;
7
+ reward?: number;
8
+ status?: string;
9
+ [k: string]: unknown;
10
+ }
11
+ export interface Arc3Game {
12
+ game_id: string;
13
+ title?: string | null;
14
+ tags?: string[] | null;
15
+ }
16
+ export declare class Arc3RestBridge {
17
+ private opts;
18
+ private cookies;
19
+ private key;
20
+ private keyChecked;
21
+ constructor(opts?: {
22
+ apiKey?: string;
23
+ baseUrl?: string;
24
+ home?: string;
25
+ });
26
+ private base;
27
+ private apiKey;
28
+ private absorbCookies;
29
+ private cookieHeader;
30
+ private call;
31
+ /** GET /api/healthcheck — plain text when healthy */
32
+ health(): Promise<string>;
33
+ /** GET /api/games */
34
+ listGames(): Promise<Arc3Game[]>;
35
+ /** POST /api/scorecard/open */
36
+ openScorecard(meta?: {
37
+ source_url?: string;
38
+ tags?: string[];
39
+ opaque?: unknown;
40
+ competition_mode?: boolean;
41
+ }): Promise<string>;
42
+ /** POST /api/scorecard/close */
43
+ closeScorecard(cardId: string): Promise<Record<string, unknown>>;
44
+ /** GET /api/scorecard/{card_id} */
45
+ getScorecard(cardId: string): Promise<Record<string, unknown>>;
46
+ /** POST /api/cmd/RESET — no guid: new instance; with guid: level/game reset */
47
+ reset(gameId: string, cardId: string, guid?: string): Promise<Arc3Frame>;
48
+ /** ACTION1..5, ACTION7 (simple) */
49
+ action(gameId: string, guid: string, n: 1 | 2 | 3 | 4 | 5 | 7, reasoning?: unknown): Promise<Arc3Frame>;
50
+ /** ACTION6 (coordinate, 64x64 grid) */
51
+ actionXY(gameId: string, guid: string, x: number, y: number, reasoning?: unknown): Promise<Arc3Frame>;
52
+ }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * @hmharness/environments - ARC-AGI-3 REST bridge (blueprint §14 / ARC-001..003)
3
+ *
4
+ * Implements the OFFICIAL ARC-AGI-3 REST API (spec: docs.arcprize.org/arc3v1.yaml):
5
+ * base https://three.arcprize.org
6
+ * auth X-API-Key header (issued from the ARC-AGI-3 web console)
7
+ * games GET /api/games | GET /api/games/{game_id}
8
+ * cards POST /api/scorecard/open -> {card_id} | /close | GET /api/scorecard/{card_id}
9
+ * play POST /api/cmd/RESET {game_id, card_id, guid?} -> FrameResponse
10
+ * POST /api/cmd/ACTION1..5,7 {game_id, guid, reasoning?}
11
+ * POST /api/cmd/ACTION6 {game_id, guid, x(0..63), y(0..63), reasoning?}
12
+ *
13
+ * Games are stateful behind an AWS load balancer: every response may set
14
+ * AWSALB* cookies that MUST be echoed on subsequent requests (session
15
+ * affinity) — this bridge owns the cookie jar.
16
+ *
17
+ * The API key is read from (in order): explicit option, HMH_HOME config
18
+ * `arc3.apiKey`, env ARC_API_KEY. Without a key every call fails with the
19
+ * structured E_NO_API_KEY pointing at the console — no fake runs.
20
+ */
21
+ import { readFile } from 'node:fs/promises';
22
+ import { join } from 'node:path';
23
+ import { homedir } from 'node:os';
24
+ export const ARC3_BASE = 'https://three.arcprize.org';
25
+ export class Arc3RestBridge {
26
+ opts;
27
+ cookies = new Map();
28
+ key = null;
29
+ keyChecked = false;
30
+ constructor(opts = {}) {
31
+ this.opts = opts;
32
+ }
33
+ base() {
34
+ return this.opts.baseUrl ?? ARC3_BASE;
35
+ }
36
+ async apiKey() {
37
+ if (this.keyChecked)
38
+ return this.key;
39
+ this.keyChecked = true;
40
+ if (this.opts.apiKey) {
41
+ this.key = this.opts.apiKey;
42
+ return this.key;
43
+ }
44
+ const env = process.env.ARC_API_KEY ?? process.env.ARC3_API_KEY;
45
+ if (env) {
46
+ this.key = env;
47
+ return this.key;
48
+ }
49
+ try {
50
+ const home = this.opts.home ?? join(homedir(), '.hmharness');
51
+ const cfg = JSON.parse(await readFile(join(home, 'config.json'), 'utf8'));
52
+ if (cfg.arc3?.apiKey)
53
+ this.key = cfg.arc3.apiKey;
54
+ }
55
+ catch { /* no config: env/console only */ }
56
+ return this.key;
57
+ }
58
+ absorbCookies(res) {
59
+ const raw = res.headers.getSetCookie?.() ?? [];
60
+ for (const line of raw) {
61
+ const [pair] = line.split(';');
62
+ const eq = pair.indexOf('=');
63
+ if (eq > 0)
64
+ this.cookies.set(pair.slice(0, eq).trim(), pair.slice(eq + 1).trim());
65
+ }
66
+ }
67
+ cookieHeader() {
68
+ return [...this.cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; ');
69
+ }
70
+ async call(method, path, body) {
71
+ const key = await this.apiKey();
72
+ if (!key) {
73
+ throw new Error('E_NO_API_KEY: ARC-AGI-3 requires an X-API-Key — create one at the ARC-AGI-3 web console (arcprize.org), then set config {arc3:{apiKey}} or env ARC_API_KEY');
74
+ }
75
+ const headers = { 'X-API-Key': key };
76
+ const cookie = this.cookieHeader();
77
+ if (cookie)
78
+ headers.cookie = cookie;
79
+ if (body !== undefined)
80
+ headers['content-type'] = 'application/json';
81
+ let res;
82
+ try {
83
+ res = await fetch(this.base() + path, {
84
+ method,
85
+ headers,
86
+ body: body === undefined ? undefined : JSON.stringify(body),
87
+ signal: AbortSignal.timeout(30_000),
88
+ });
89
+ }
90
+ catch (err) {
91
+ throw new Error(`E_ARC3_NETWORK: ${err instanceof Error ? err.message : String(err)}`);
92
+ }
93
+ this.absorbCookies(res);
94
+ if (!res.ok) {
95
+ const text = await res.text().catch(() => '');
96
+ throw new Error(`E_ARC3_HTTP_${res.status}: ${text.slice(0, 200)}`);
97
+ }
98
+ const text = await res.text();
99
+ try {
100
+ return JSON.parse(text);
101
+ }
102
+ catch {
103
+ return text;
104
+ }
105
+ }
106
+ /** GET /api/healthcheck — plain text when healthy */
107
+ async health() {
108
+ const key = await this.apiKey();
109
+ const res = await fetch(this.base() + '/api/healthcheck', {
110
+ headers: key ? { 'X-API-Key': key } : {},
111
+ signal: AbortSignal.timeout(10_000),
112
+ }).catch((err) => {
113
+ throw new Error(`E_ARC3_NETWORK: ${err instanceof Error ? err.message : String(err)}`);
114
+ });
115
+ if (!res.ok)
116
+ throw new Error(`E_ARC3_HTTP_${res.status}`);
117
+ return res.text();
118
+ }
119
+ /** GET /api/games */
120
+ async listGames() {
121
+ const r = await this.call('GET', '/api/games');
122
+ return Array.isArray(r) ? r : (r.games ?? []);
123
+ }
124
+ /** POST /api/scorecard/open */
125
+ async openScorecard(meta) {
126
+ const r = await this.call('POST', '/api/scorecard/open', meta ?? {});
127
+ return r.card_id;
128
+ }
129
+ /** POST /api/scorecard/close */
130
+ async closeScorecard(cardId) {
131
+ return this.call('POST', '/api/scorecard/close', { card_id: cardId });
132
+ }
133
+ /** GET /api/scorecard/{card_id} */
134
+ async getScorecard(cardId) {
135
+ return this.call('GET', `/api/scorecard/${encodeURIComponent(cardId)}`);
136
+ }
137
+ /** POST /api/cmd/RESET — no guid: new instance; with guid: level/game reset */
138
+ async reset(gameId, cardId, guid) {
139
+ const body = { game_id: gameId, card_id: cardId };
140
+ if (guid)
141
+ body.guid = guid;
142
+ return this.call('POST', '/api/cmd/RESET', body);
143
+ }
144
+ /** ACTION1..5, ACTION7 (simple) */
145
+ async action(gameId, guid, n, reasoning) {
146
+ const body = { game_id: gameId, guid };
147
+ if (reasoning !== undefined)
148
+ body.reasoning = reasoning;
149
+ return this.call('POST', `/api/cmd/ACTION${n}`, body);
150
+ }
151
+ /** ACTION6 (coordinate, 64x64 grid) */
152
+ async actionXY(gameId, guid, x, y, reasoning) {
153
+ const body = { game_id: gameId, guid, x: Math.max(0, Math.min(63, Math.round(x))), y: Math.max(0, Math.min(63, Math.round(y))) };
154
+ if (reasoning !== undefined)
155
+ body.reasoning = reasoning;
156
+ return this.call('POST', '/api/cmd/ACTION6', body);
157
+ }
158
+ }
package/dist/index.d.ts CHANGED
@@ -12,5 +12,7 @@ export { HarmonyOsEnvironment } from './harmonyos.js';
12
12
  export type { HarmonyOsEnvOptions } from './harmonyos.js';
13
13
  export { BrowserEnvironment, DesktopEnvironment, Arc3Environment } from './adapters.js';
14
14
  export type { BrowserEnvOptions, DesktopEnvOptions, Arc3EnvOptions } from './adapters.js';
15
+ export { Arc3RestBridge, ARC3_BASE } from './arc3-rest.js';
16
+ export type { Arc3Frame, Arc3Game } from './arc3-rest.js';
15
17
  export { browserActBridge, desktopActBridge } from './bridges.js';
16
18
  export type { ToolExecute } from './bridges.js';
package/dist/index.js CHANGED
@@ -9,4 +9,5 @@
9
9
  export { TerminalEnvironment, runShell } from "./terminal.js";
10
10
  export { HarmonyOsEnvironment } from "./harmonyos.js";
11
11
  export { BrowserEnvironment, DesktopEnvironment, Arc3Environment } from "./adapters.js";
12
+ export { Arc3RestBridge, ARC3_BASE } from "./arc3-rest.js";
12
13
  export { browserActBridge, desktopActBridge } from "./bridges.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/environments",
3
- "version": "0.19.8",
3
+ "version": "0.20.0",
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.19.8",
30
- "@hmharness/cognitive": "0.19.8"
29
+ "@hmharness/kernel": "0.20.0",
30
+ "@hmharness/cognitive": "0.20.0"
31
31
  }
32
32
  }