@crewhaus/target-browser-driver 0.3.2 → 0.4.2

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/index.d.ts CHANGED
@@ -20,8 +20,26 @@
20
20
  * `webFetch`). The interpreter path (`crewhaus run` →
21
21
  * `runRunBrowser` in apps/cli) mirrors this same set — keep them
22
22
  * in sync.
23
- * 5. Reads a single user prompt from `--prompt <text>` or stdin and
24
- * runs `runChatLoop` in single-turn mode.
23
+ * 5. Reads user input and runs `runChatLoop`. Two modes (G51):
24
+ * - ONE-SHOT: a `--prompt <text>` value or piped stdin runs a single
25
+ * turn and exits (the pre-0.4 behaviour, for CI/scripting). Nobody
26
+ * is there to answer an `ask` permission, so this branch alone
27
+ * carries the G11 approval seam (`permissions.ask_mode`, default
28
+ * `pause`) and PARKS the turn instead of collapsing it to a deny.
29
+ * - REPL: an interactive TTY with no `--prompt` drops into the
30
+ * persistent driver REPL — the chromium context stays connected for
31
+ * the whole `runChatLoop` call, so the agent observes → acts →
32
+ * re-observes across turns against ONE session (mirror of
33
+ * `runRunCli`'s session mode).
34
+ * `--resume <sess_…>` reseats a specific prior session; `--continue`
35
+ * resolves the most-recently-updated session for this spec's name from
36
+ * the cwd session store. The resumed run is wrapped in `withIdempotency`
37
+ * (ITEM 7) so a duplicate re-invocation of an interrupted resumed run
38
+ * returns the cached reply instead of re-driving the browser. Loop
39
+ * contract 0.4 (Batch A) threads `agent.max_tokens` (spec value, else the
40
+ * pinned 4096), `budget:`, the `limits:` ceilings (`deadlineMs`/
41
+ * `turnTimeoutMs` bound each turn; `modelCallTimeoutMs` is the
42
+ * hung-stream watchdog) and spec `hooks:` into that call.
25
43
  * 6. On exit, calls driver.disconnect() so chromium doesn't leak.
26
44
  *
27
45
  * `ir.mcp_servers` and `ir.compaction` are intentionally not wired here:
package/dist/index.js CHANGED
@@ -20,8 +20,26 @@
20
20
  * `webFetch`). The interpreter path (`crewhaus run` →
21
21
  * `runRunBrowser` in apps/cli) mirrors this same set — keep them
22
22
  * in sync.
23
- * 5. Reads a single user prompt from `--prompt <text>` or stdin and
24
- * runs `runChatLoop` in single-turn mode.
23
+ * 5. Reads user input and runs `runChatLoop`. Two modes (G51):
24
+ * - ONE-SHOT: a `--prompt <text>` value or piped stdin runs a single
25
+ * turn and exits (the pre-0.4 behaviour, for CI/scripting). Nobody
26
+ * is there to answer an `ask` permission, so this branch alone
27
+ * carries the G11 approval seam (`permissions.ask_mode`, default
28
+ * `pause`) and PARKS the turn instead of collapsing it to a deny.
29
+ * - REPL: an interactive TTY with no `--prompt` drops into the
30
+ * persistent driver REPL — the chromium context stays connected for
31
+ * the whole `runChatLoop` call, so the agent observes → acts →
32
+ * re-observes across turns against ONE session (mirror of
33
+ * `runRunCli`'s session mode).
34
+ * `--resume <sess_…>` reseats a specific prior session; `--continue`
35
+ * resolves the most-recently-updated session for this spec's name from
36
+ * the cwd session store. The resumed run is wrapped in `withIdempotency`
37
+ * (ITEM 7) so a duplicate re-invocation of an interrupted resumed run
38
+ * returns the cached reply instead of re-driving the browser. Loop
39
+ * contract 0.4 (Batch A) threads `agent.max_tokens` (spec value, else the
40
+ * pinned 4096), `budget:`, the `limits:` ceilings (`deadlineMs`/
41
+ * `turnTimeoutMs` bound each turn; `modelCallTimeoutMs` is the
42
+ * hung-stream watchdog) and spec `hooks:` into that call.
25
43
  * 6. On exit, calls driver.disconnect() so chromium doesn't leak.
26
44
  *
27
45
  * `ir.mcp_servers` and `ir.compaction` are intentionally not wired here:
@@ -126,6 +144,61 @@ function taxonomyField(ir, indent) {
126
144
  return "";
127
145
  return `\n${indent}failureTaxonomy: ${JSON.stringify(taxonomy)},`;
128
146
  }
147
+ /**
148
+ * Item 27 (Batch A extends it to this shape) — render the `budget`
149
+ * runChatLoop field. The IR carries a numbers-and-literals object
150
+ * (`usdMicros` + `onExceed`); `JSON.stringify` safely quotes the degrade
151
+ * `model` string. Empty when the spec omits it, keeping pre-existing
152
+ * bundles byte-identical. The browser loop is single-turn, so the cap
153
+ * bounds ONE prompt→answer run. Mirror: target-cli + target-channel-bot +
154
+ * target-managed + target-batch-worker render the same field.
155
+ */
156
+ function budgetField(ir, indent) {
157
+ if (ir.budget === undefined)
158
+ return "";
159
+ return `\n${indent}budget: ${JSON.stringify(ir.budget)},`;
160
+ }
161
+ /**
162
+ * Loop contract 0.4 (Batch A) — thread the top-level `limits:` ceilings
163
+ * into the single-turn `runChatLoop` call as the runtime's individual
164
+ * top-level knobs, camelCase-mirroring the IR 1:1. Every knob is emitted
165
+ * only when declared — the runtime owns every default — so existing
166
+ * bundles stay byte-identical. On this shape `deadlineMs` and
167
+ * `turnTimeoutMs` bound the SAME single turn (the run IS one turn); both
168
+ * are still emitted verbatim so whichever is tighter fires first, and
169
+ * `modelCallTimeoutMs` remains the hung-stream watchdog underneath them.
170
+ * `limits.crew` never reaches this shape (crew-only; the spec rejects it
171
+ * everywhere else). Mirror: target-cli + target-channel-bot +
172
+ * target-managed + target-batch-worker render the same fields.
173
+ */
174
+ function limitsFields(ir, indent) {
175
+ const limits = ir.limits;
176
+ if (limits === undefined)
177
+ return "";
178
+ const pieces = [];
179
+ if (limits.maxToolIterations !== undefined) {
180
+ pieces.push(`\n${indent}maxToolIterations: ${limits.maxToolIterations},`);
181
+ }
182
+ if (limits.maxConcurrentTools !== undefined) {
183
+ pieces.push(`\n${indent}maxConcurrentTools: ${limits.maxConcurrentTools},`);
184
+ }
185
+ if (limits.contextLimit !== undefined) {
186
+ pieces.push(`\n${indent}contextLimit: ${limits.contextLimit},`);
187
+ }
188
+ if (limits.deadlineMs !== undefined) {
189
+ pieces.push(`\n${indent}deadlineMs: ${limits.deadlineMs},`);
190
+ }
191
+ if (limits.turnTimeoutMs !== undefined) {
192
+ pieces.push(`\n${indent}turnTimeoutMs: ${limits.turnTimeoutMs},`);
193
+ }
194
+ if (limits.modelCallTimeoutMs !== undefined) {
195
+ pieces.push(`\n${indent}modelCallTimeoutMs: ${limits.modelCallTimeoutMs},`);
196
+ }
197
+ if (limits.loopDetection !== undefined) {
198
+ pieces.push(`\n${indent}loopDetection: ${JSON.stringify(limits.loopDetection)},`);
199
+ }
200
+ return pieces.join("");
201
+ }
129
202
  export function emitBrowserDriver(ir, opts = {}) {
130
203
  const files = [{ path: "agent.ts", content: renderAgent(ir) }];
131
204
  // Item 42 — generated bundle README; default ON (`crewhaus compile
@@ -137,6 +210,16 @@ export function emitBrowserDriver(ir, opts = {}) {
137
210
  }
138
211
  function renderAgent(ir) {
139
212
  const startUrl = ir.driver.startUrl;
213
+ // SECURITY — `driver.allowPrivateTargets` relaxes BOTH SSRF layers together:
214
+ // the chromium backend's DNS-pinning proxy and the Navigate tool's pre-goto
215
+ // guard. Emitted ONLY when the spec opts in, so an ordinary bundle is
216
+ // byte-identical to 0.4.1. Waiving one layer alone would be worse than
217
+ // waiving neither: with only the guard relaxed, the proxy answers loopback
218
+ // with its own 403 body, which RENDERS, so the agent screenshots a block
219
+ // page instead of failing cleanly.
220
+ const allowPrivate = ir.driver.allowPrivateTargets === true;
221
+ const allowPrivateField = allowPrivate ? ", ssrfProxy: false" : "";
222
+ const allowPrivateNavField = allowPrivate ? ", allowPrivateTargets: true" : "";
140
223
  const hasRules = ir.permissions.rules.length > 0;
141
224
  const permImport = hasRules
142
225
  ? `import { BUILTIN_DEFAULT_RULES } from "@crewhaus/permission-engine";\n`
@@ -152,6 +235,19 @@ function renderAgent(ir) {
152
235
  const continuityWarning = ir.continuity !== undefined
153
236
  ? "// note: continuity configured but ignored on browser in 0.3.0\n"
154
237
  : "";
238
+ // Loop contract 0.4 (Batch A) — spec-declared lifecycle hooks (`hooks:`).
239
+ // IrHook is HookDef-shaped by contract (the spec ↔ hooks-engine
240
+ // cross-check test pins the event union), so the JSON literal type-checks
241
+ // against `runChatLoop({ hooks })` and declaration order is preserved
242
+ // (hooks run in registration order). Absent/empty emits nothing so
243
+ // pre-existing bundles stay byte-identical. Mirror: target-batch-worker
244
+ // renders the same pieces.
245
+ const specHooks = ir.hooks !== undefined && ir.hooks.length > 0 ? ir.hooks : undefined;
246
+ const hooksImport = specHooks !== undefined ? `import type { HookDef } from "@crewhaus/hooks-engine";\n` : "";
247
+ const hooksConst = specHooks !== undefined
248
+ ? `\n// Loop contract 0.4 — spec-declared lifecycle hooks (registration order preserved).\nconst SPEC_HOOKS: ReadonlyArray<HookDef> = ${JSON.stringify(specHooks)};`
249
+ : "";
250
+ const hooksField = specHooks !== undefined ? "\n hooks: SPEC_HOOKS," : "";
155
251
  return `#!/usr/bin/env bun
156
252
  // Generated by crewhaus. DO NOT EDIT.
157
253
  // Source spec: ${escapeJsonString(ir.name)} (target: browser, ir version: ${ir.version})
@@ -161,26 +257,42 @@ import { createScreenshotTool } from "@crewhaus/tool-screen-capture";
161
257
  import { createAllMouseKeyboardTools } from "@crewhaus/tool-mouse-keyboard";
162
258
  import { createFindElementTool } from "@crewhaus/tool-vision-grounding";
163
259
  import { runChatLoop } from "@crewhaus/runtime-core";
260
+ import { createPendingApprovalStore, resolveSessionRootDir } from "@crewhaus/runtime-core";
164
261
  import { createRunContext } from "@crewhaus/run-context";
165
262
  import { defaultCatalog } from "@crewhaus/tool-catalog";
166
- ${toolImportBlock}${permImport}${toolBootBlock}
263
+ import { createSessionStore } from "@crewhaus/session-store";
264
+ import { createInMemoryIdempotencyStore, idempotencyKey, withIdempotency } from "@crewhaus/idempotency-keys";
265
+ ${toolImportBlock}${hooksImport}${permImport}${toolBootBlock}
266
+ // Session ids round-trip through @crewhaus/session-store's path-traversal
267
+ // guard, so --resume ids must match its \`sess_<16 hex>\` shape.
268
+ const SESSION_ID_REGEX = /^sess_[0-9a-f]{16}$/;
167
269
  const SPEC_NAME = ${escapeJsonString(ir.name)};
168
270
  const SPEC_MODEL = ${escapeJsonString(ir.agent.model)};
169
271
  const SPEC_INSTRUCTIONS = ${escapeJsonString(ir.agent.instructions)};
170
272
  const SPEC_GROUNDING_MODEL = ${escapeJsonString(ir.groundingModel)};
171
273
  const SPEC_BACKEND: "host" | "chromium" | "remote" = ${escapeJsonString(ir.driver.backend)};
172
274
  const SPEC_VIEWPORT = { width: ${ir.driver.viewport.width}, height: ${ir.driver.viewport.height} };
173
- const SPEC_START_URL = ${startUrl !== undefined ? escapeJsonString(startUrl) : "undefined"};
275
+ const SPEC_START_URL = ${startUrl !== undefined ? escapeJsonString(startUrl) : "undefined"};${hooksConst}
174
276
 
175
277
  function emit(event: Record<string, unknown>): void {
176
278
  process.stdout.write(\`\${JSON.stringify(event)}\\n\`);
177
279
  }
178
280
 
179
- function parseArgs(): { prompt: string | undefined } {
281
+ function parseArgs(): {
282
+ prompt: string | undefined;
283
+ resumeId: string | undefined;
284
+ continueSession: boolean;
285
+ } {
180
286
  const args = process.argv.slice(2);
181
- const i = args.indexOf("--prompt");
182
- if (i !== -1 && i + 1 < args.length) return { prompt: String(args[i + 1]) };
183
- return { prompt: undefined };
287
+ const valueOf = (name: string): string | undefined => {
288
+ const i = args.indexOf(name);
289
+ return i !== -1 && i + 1 < args.length ? String(args[i + 1]) : undefined;
290
+ };
291
+ return {
292
+ prompt: valueOf("--prompt"),
293
+ resumeId: valueOf("--resume"),
294
+ continueSession: args.includes("--continue"),
295
+ };
184
296
  }
185
297
 
186
298
  async function readStdin(): Promise<string> {
@@ -191,42 +303,125 @@ async function readStdin(): Promise<string> {
191
303
  }
192
304
 
193
305
  async function main(): Promise<void> {
194
- const { prompt: argPrompt } = parseArgs();
195
- const stdinPrompt = argPrompt ?? (await readStdin());
196
- if (stdinPrompt.length === 0) {
306
+ const { prompt: argPrompt, resumeId, continueSession } = parseArgs();
307
+ if (resumeId !== undefined && continueSession) {
308
+ process.stderr.write("[browser-driver] --resume and --continue are mutually exclusive\\n");
309
+ process.exit(2);
310
+ }
311
+ if (resumeId !== undefined && !SESSION_ID_REGEX.test(resumeId)) {
312
+ process.stderr.write(
313
+ \`[browser-driver] invalid --resume sessionId "\${resumeId}" — expected sess_<16 hex>\\n\`,
314
+ );
315
+ process.exit(2);
316
+ }
317
+
318
+ // Resolve the session to resume: an explicit --resume id, or --continue → the
319
+ // most-recently-updated session for this spec name in the cwd session store
320
+ // (mirror of runRunCli's --continue). Absent → a fresh session.
321
+ const sessionStore = createSessionStore();
322
+ let resume: { sessionId: string } | undefined;
323
+ if (resumeId !== undefined) {
324
+ resume = { sessionId: resumeId };
325
+ } else if (continueSession) {
326
+ const sessions = await sessionStore.list();
327
+ const match = sessions.find((s) => s.name === SPEC_NAME);
328
+ if (match === undefined) {
329
+ process.stderr.write(
330
+ \`[browser-driver] no prior session for "\${SPEC_NAME}" to --continue in \${process.cwd()}/.crewhaus/sessions/\\n\`,
331
+ );
332
+ process.exit(2);
333
+ }
334
+ resume = { sessionId: match.id };
335
+ process.stdout.write(\`[browser-driver] resuming session \${match.id}\\n\`);
336
+ }
337
+
338
+ // ONE-SHOT when a --prompt is supplied or stdin is piped (CI/scripting); an
339
+ // interactive TTY with no --prompt drops into the persistent driver REPL, so
340
+ // the agent observes → acts → re-observes across turns against one session.
341
+ const repl = argPrompt === undefined && process.stdin.isTTY === true;
342
+ const oneShotPrompt = repl ? "" : (argPrompt ?? (await readStdin()));
343
+ if (!repl && oneShotPrompt.length === 0) {
197
344
  process.stderr.write("[browser-driver] no prompt (pass --prompt <text> or pipe stdin)\\n");
198
345
  process.exit(2);
199
346
  }
200
347
 
201
348
  emit({ kind: "browser_start", backend: SPEC_BACKEND });
202
- const driver = createDriver({ backend: SPEC_BACKEND, viewport: SPEC_VIEWPORT });
349
+ const driver = createDriver({ backend: SPEC_BACKEND, viewport: SPEC_VIEWPORT${allowPrivateField} });
203
350
  await driver.connect();
204
351
  if (SPEC_START_URL !== undefined) {
205
352
  await driver.goto(SPEC_START_URL);
206
353
  emit({ kind: "navigated", url: SPEC_START_URL });
207
354
  }
208
355
 
209
- const navigateTool = createNavigateTool({ driver });
356
+ const navigateTool = createNavigateTool({ driver${allowPrivateNavField} });
210
357
  const screenshotTool = createScreenshotTool({ driver });
211
358
  const mk = createAllMouseKeyboardTools({ driver });
212
359
  const findElement = createFindElementTool({ driver, model: SPEC_GROUNDING_MODEL });
213
360
  const tools = [navigateTool, screenshotTool, mk.click, mk.type, mk.key, mk.scroll, findElement, ...defaultCatalog.list()];
214
361
 
215
- const runContext = createRunContext();
216
- let finalText = "";
217
- try {
218
- finalText = await runChatLoop({
219
- model: SPEC_MODEL,
220
- instructions: SPEC_INSTRUCTIONS,${poolField(ir, " ")}${taxonomyField(ir, " ")}
221
- runContext,
222
- sessionName: SPEC_NAME,
223
- sessionTarget: "browser",
362
+ // On resume the run context must carry the resumed sessionId (runtime-core
363
+ // asserts they match); a fresh run mints its own.
364
+ const runContext =
365
+ resume !== undefined ? createRunContext({ sessionId: resume.sessionId }) : createRunContext();
366
+ // Session-persist driver state across turns: the driver stays connected for
367
+ // the whole runChatLoop call, so every REPL turn shares one live browser
368
+ // context. limits/budget/max_tokens (Batch A) apply to each turn.
369
+ const runOptions = {
370
+ model: SPEC_MODEL,
371
+ instructions: SPEC_INSTRUCTIONS,${poolField(ir, " ")}${taxonomyField(ir, " ")}
372
+ runContext,
373
+ sessionName: SPEC_NAME,
374
+ sessionTarget: "browser" as const,
375
+ tools,
376
+ maxTokens: ${ir.agent.maxTokens ?? 4096},${budgetField(ir, " ")}${limitsFields(ir, " ")}${hooksField}${permField}
377
+ };
378
+
379
+ // G11 — a compiled bundle is NON-INTERACTIVE: a tool that lands on \`ask\`
380
+ // has nobody to prompt, so without this it collapsed to a deny. Rooted
381
+ // where the run's session files land, so parks live beside them (and
382
+ // inside a tenant's rebased root when one is active). No I/O until a park.
383
+ const __approvalRoot = resolveSessionRootDir(undefined);
384
+ const __approvals = createPendingApprovalStore(
385
+ __approvalRoot !== undefined ? { rootDir: __approvalRoot } : {},
386
+ );
387
+
388
+ // The REPL lets runChatLoop drive stdin turn-by-turn (singleTurn omitted);
389
+ // one-shot seeds the single inbound message. \`resume\` + \`seedMessages\` is
390
+ // legal ONLY under singleTurn (the seed is the new inbound, the replayed
391
+ // history is the prefix), so REPL resume passes no seed.
392
+ const drive = async (): Promise<string> => {
393
+ if (repl) {
394
+ return await runChatLoop({
395
+ ...runOptions,
396
+ installSigintHandler: true,
397
+ ...(resume !== undefined ? { resume } : {}),
398
+ });
399
+ }
400
+ return await runChatLoop({
401
+ ...runOptions,
224
402
  singleTurn: true,
225
- seedMessages: [{ role: "user", content: stdinPrompt }],
226
- tools,
227
- installSigintHandler: false,
228
- maxTokens: 4096,${permField}
403
+ installSigintHandler: false,${renderApprovalFields(ir, " ")}
404
+ seedMessages: [{ role: "user", content: oneShotPrompt }],
405
+ ...(resume !== undefined ? { resume } : {}),
229
406
  });
407
+ };
408
+
409
+ let finalText = "";
410
+ try {
411
+ if (resume !== undefined) {
412
+ // ITEM 7 — wrap the resume path in withIdempotency so a duplicate
413
+ // re-invocation of an interrupted resumed run returns the cached reply
414
+ // instead of re-driving the browser (at-least-once safety).
415
+ const idemStore = createInMemoryIdempotencyStore<string>();
416
+ const guarded = withIdempotency<undefined, string>(() => drive(), {
417
+ store: idemStore,
418
+ ttlMs: 3_600_000,
419
+ });
420
+ const key = idempotencyKey(\`\${SPEC_NAME}:\${resume.sessionId}:\${oneShotPrompt}\`, 0);
421
+ finalText = (await guarded(undefined, key)).value;
422
+ } else {
423
+ finalText = await drive();
424
+ }
230
425
  } finally {
231
426
  await driver.disconnect();
232
427
  }
@@ -239,6 +434,26 @@ main().catch((err) => {
239
434
  });
240
435
  `;
241
436
  }
437
+ /**
438
+ * Loop contract 0.4 (G11) — the `askMode` + `approvals` fields. Unlike the
439
+ * CLI's `approvalRunOptions`, a bundle parses no `--ask-mode`, so the spec
440
+ * value is FIXED here at emit time. Deliberately NOT folded into
441
+ * `renderPermissionsField`: that one early-returns "" when the spec declares
442
+ * no `permissions:` block, which is exactly the case where parking matters
443
+ * most — with no block every unmatched tool resolves to `ask`.
444
+ *
445
+ * The store is rendered UNCONDITIONALLY, including under `"deny"` where it
446
+ * never parks, so runtime-core's diagnostic can honestly say `ask_mode:
447
+ * "deny"` instead of blaming absent plumbing (it branches on `approvals ===
448
+ * undefined`).
449
+ *
450
+ * One-shot ONLY. The REPL branch spreads `runOptions`, and a REPL prompts on
451
+ * stdin — parking a turn that has a human sitting at it would be wrong.
452
+ */
453
+ function renderApprovalFields(ir, indent) {
454
+ return (`\n${indent}askMode: ${escapeJsonString(ir.permissions.askMode ?? "pause")},` +
455
+ `\n${indent}approvals: { store: __approvals, surface: "browser" },`);
456
+ }
242
457
  function renderPermissionsField(ir) {
243
458
  const { mode, rules } = ir.permissions;
244
459
  if (mode === undefined && rules.length === 0)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewhaus/target-browser-driver",
3
- "version": "0.3.2",
3
+ "version": "0.4.2",
4
4
  "type": "module",
5
5
  "description": "Codegen for the BROW target — emits a single agent.ts that boots a chromium driver + vision-grounding tools (Section 25 BROW)",
6
6
  "main": "dist/index.js",
@@ -15,9 +15,9 @@
15
15
  "test": "bun test src"
16
16
  },
17
17
  "dependencies": {
18
- "@crewhaus/errors": "0.3.2",
19
- "@crewhaus/infra-utils": "0.3.2",
20
- "@crewhaus/ir": "0.3.2"
18
+ "@crewhaus/errors": "0.4.2",
19
+ "@crewhaus/infra-utils": "0.4.2",
20
+ "@crewhaus/ir": "0.4.2"
21
21
  },
22
22
  "license": "Apache-2.0",
23
23
  "author": {