@crewhaus/target-browser-driver 0.3.1 → 0.4.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.
- package/dist/index.d.ts +17 -2
- package/dist/index.js +195 -23
- package/package.json +4 -4
package/dist/index.d.ts
CHANGED
|
@@ -20,8 +20,23 @@
|
|
|
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
|
|
24
|
-
*
|
|
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).
|
|
26
|
+
* - REPL: an interactive TTY with no `--prompt` drops into the
|
|
27
|
+
* persistent driver REPL — the chromium context stays connected for
|
|
28
|
+
* the whole `runChatLoop` call, so the agent observes → acts →
|
|
29
|
+
* re-observes across turns against ONE session (mirror of
|
|
30
|
+
* `runRunCli`'s session mode).
|
|
31
|
+
* `--resume <sess_…>` reseats a specific prior session; `--continue`
|
|
32
|
+
* resolves the most-recently-updated session for this spec's name from
|
|
33
|
+
* the cwd session store. The resumed run is wrapped in `withIdempotency`
|
|
34
|
+
* (ITEM 7) so a duplicate re-invocation of an interrupted resumed run
|
|
35
|
+
* returns the cached reply instead of re-driving the browser. Loop
|
|
36
|
+
* contract 0.4 (Batch A) threads `agent.max_tokens` (spec value, else the
|
|
37
|
+
* pinned 4096), `budget:`, the `limits:` ceilings (`deadlineMs`/
|
|
38
|
+
* `turnTimeoutMs` bound each turn; `modelCallTimeoutMs` is the
|
|
39
|
+
* hung-stream watchdog) and spec `hooks:` into that call.
|
|
25
40
|
* 6. On exit, calls driver.disconnect() so chromium doesn't leak.
|
|
26
41
|
*
|
|
27
42
|
* `ir.mcp_servers` and `ir.compaction` are intentionally not wired here:
|
package/dist/index.js
CHANGED
|
@@ -20,8 +20,23 @@
|
|
|
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
|
|
24
|
-
*
|
|
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).
|
|
26
|
+
* - REPL: an interactive TTY with no `--prompt` drops into the
|
|
27
|
+
* persistent driver REPL — the chromium context stays connected for
|
|
28
|
+
* the whole `runChatLoop` call, so the agent observes → acts →
|
|
29
|
+
* re-observes across turns against ONE session (mirror of
|
|
30
|
+
* `runRunCli`'s session mode).
|
|
31
|
+
* `--resume <sess_…>` reseats a specific prior session; `--continue`
|
|
32
|
+
* resolves the most-recently-updated session for this spec's name from
|
|
33
|
+
* the cwd session store. The resumed run is wrapped in `withIdempotency`
|
|
34
|
+
* (ITEM 7) so a duplicate re-invocation of an interrupted resumed run
|
|
35
|
+
* returns the cached reply instead of re-driving the browser. Loop
|
|
36
|
+
* contract 0.4 (Batch A) threads `agent.max_tokens` (spec value, else the
|
|
37
|
+
* pinned 4096), `budget:`, the `limits:` ceilings (`deadlineMs`/
|
|
38
|
+
* `turnTimeoutMs` bound each turn; `modelCallTimeoutMs` is the
|
|
39
|
+
* hung-stream watchdog) and spec `hooks:` into that call.
|
|
25
40
|
* 6. On exit, calls driver.disconnect() so chromium doesn't leak.
|
|
26
41
|
*
|
|
27
42
|
* `ir.mcp_servers` and `ir.compaction` are intentionally not wired here:
|
|
@@ -126,6 +141,61 @@ function taxonomyField(ir, indent) {
|
|
|
126
141
|
return "";
|
|
127
142
|
return `\n${indent}failureTaxonomy: ${JSON.stringify(taxonomy)},`;
|
|
128
143
|
}
|
|
144
|
+
/**
|
|
145
|
+
* Item 27 (Batch A extends it to this shape) — render the `budget`
|
|
146
|
+
* runChatLoop field. The IR carries a numbers-and-literals object
|
|
147
|
+
* (`usdMicros` + `onExceed`); `JSON.stringify` safely quotes the degrade
|
|
148
|
+
* `model` string. Empty when the spec omits it, keeping pre-existing
|
|
149
|
+
* bundles byte-identical. The browser loop is single-turn, so the cap
|
|
150
|
+
* bounds ONE prompt→answer run. Mirror: target-cli + target-channel-bot +
|
|
151
|
+
* target-managed + target-batch-worker render the same field.
|
|
152
|
+
*/
|
|
153
|
+
function budgetField(ir, indent) {
|
|
154
|
+
if (ir.budget === undefined)
|
|
155
|
+
return "";
|
|
156
|
+
return `\n${indent}budget: ${JSON.stringify(ir.budget)},`;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Loop contract 0.4 (Batch A) — thread the top-level `limits:` ceilings
|
|
160
|
+
* into the single-turn `runChatLoop` call as the runtime's individual
|
|
161
|
+
* top-level knobs, camelCase-mirroring the IR 1:1. Every knob is emitted
|
|
162
|
+
* only when declared — the runtime owns every default — so existing
|
|
163
|
+
* bundles stay byte-identical. On this shape `deadlineMs` and
|
|
164
|
+
* `turnTimeoutMs` bound the SAME single turn (the run IS one turn); both
|
|
165
|
+
* are still emitted verbatim so whichever is tighter fires first, and
|
|
166
|
+
* `modelCallTimeoutMs` remains the hung-stream watchdog underneath them.
|
|
167
|
+
* `limits.crew` never reaches this shape (crew-only; the spec rejects it
|
|
168
|
+
* everywhere else). Mirror: target-cli + target-channel-bot +
|
|
169
|
+
* target-managed + target-batch-worker render the same fields.
|
|
170
|
+
*/
|
|
171
|
+
function limitsFields(ir, indent) {
|
|
172
|
+
const limits = ir.limits;
|
|
173
|
+
if (limits === undefined)
|
|
174
|
+
return "";
|
|
175
|
+
const pieces = [];
|
|
176
|
+
if (limits.maxToolIterations !== undefined) {
|
|
177
|
+
pieces.push(`\n${indent}maxToolIterations: ${limits.maxToolIterations},`);
|
|
178
|
+
}
|
|
179
|
+
if (limits.maxConcurrentTools !== undefined) {
|
|
180
|
+
pieces.push(`\n${indent}maxConcurrentTools: ${limits.maxConcurrentTools},`);
|
|
181
|
+
}
|
|
182
|
+
if (limits.contextLimit !== undefined) {
|
|
183
|
+
pieces.push(`\n${indent}contextLimit: ${limits.contextLimit},`);
|
|
184
|
+
}
|
|
185
|
+
if (limits.deadlineMs !== undefined) {
|
|
186
|
+
pieces.push(`\n${indent}deadlineMs: ${limits.deadlineMs},`);
|
|
187
|
+
}
|
|
188
|
+
if (limits.turnTimeoutMs !== undefined) {
|
|
189
|
+
pieces.push(`\n${indent}turnTimeoutMs: ${limits.turnTimeoutMs},`);
|
|
190
|
+
}
|
|
191
|
+
if (limits.modelCallTimeoutMs !== undefined) {
|
|
192
|
+
pieces.push(`\n${indent}modelCallTimeoutMs: ${limits.modelCallTimeoutMs},`);
|
|
193
|
+
}
|
|
194
|
+
if (limits.loopDetection !== undefined) {
|
|
195
|
+
pieces.push(`\n${indent}loopDetection: ${JSON.stringify(limits.loopDetection)},`);
|
|
196
|
+
}
|
|
197
|
+
return pieces.join("");
|
|
198
|
+
}
|
|
129
199
|
export function emitBrowserDriver(ir, opts = {}) {
|
|
130
200
|
const files = [{ path: "agent.ts", content: renderAgent(ir) }];
|
|
131
201
|
// Item 42 — generated bundle README; default ON (`crewhaus compile
|
|
@@ -152,6 +222,19 @@ function renderAgent(ir) {
|
|
|
152
222
|
const continuityWarning = ir.continuity !== undefined
|
|
153
223
|
? "// note: continuity configured but ignored on browser in 0.3.0\n"
|
|
154
224
|
: "";
|
|
225
|
+
// Loop contract 0.4 (Batch A) — spec-declared lifecycle hooks (`hooks:`).
|
|
226
|
+
// IrHook is HookDef-shaped by contract (the spec ↔ hooks-engine
|
|
227
|
+
// cross-check test pins the event union), so the JSON literal type-checks
|
|
228
|
+
// against `runChatLoop({ hooks })` and declaration order is preserved
|
|
229
|
+
// (hooks run in registration order). Absent/empty emits nothing so
|
|
230
|
+
// pre-existing bundles stay byte-identical. Mirror: target-batch-worker
|
|
231
|
+
// renders the same pieces.
|
|
232
|
+
const specHooks = ir.hooks !== undefined && ir.hooks.length > 0 ? ir.hooks : undefined;
|
|
233
|
+
const hooksImport = specHooks !== undefined ? `import type { HookDef } from "@crewhaus/hooks-engine";\n` : "";
|
|
234
|
+
const hooksConst = specHooks !== undefined
|
|
235
|
+
? `\n// Loop contract 0.4 — spec-declared lifecycle hooks (registration order preserved).\nconst SPEC_HOOKS: ReadonlyArray<HookDef> = ${JSON.stringify(specHooks)};`
|
|
236
|
+
: "";
|
|
237
|
+
const hooksField = specHooks !== undefined ? "\n hooks: SPEC_HOOKS," : "";
|
|
155
238
|
return `#!/usr/bin/env bun
|
|
156
239
|
// Generated by crewhaus. DO NOT EDIT.
|
|
157
240
|
// Source spec: ${escapeJsonString(ir.name)} (target: browser, ir version: ${ir.version})
|
|
@@ -163,24 +246,39 @@ import { createFindElementTool } from "@crewhaus/tool-vision-grounding";
|
|
|
163
246
|
import { runChatLoop } from "@crewhaus/runtime-core";
|
|
164
247
|
import { createRunContext } from "@crewhaus/run-context";
|
|
165
248
|
import { defaultCatalog } from "@crewhaus/tool-catalog";
|
|
166
|
-
|
|
249
|
+
import { createSessionStore } from "@crewhaus/session-store";
|
|
250
|
+
import { createInMemoryIdempotencyStore, idempotencyKey, withIdempotency } from "@crewhaus/idempotency-keys";
|
|
251
|
+
${toolImportBlock}${hooksImport}${permImport}${toolBootBlock}
|
|
252
|
+
// Session ids round-trip through @crewhaus/session-store's path-traversal
|
|
253
|
+
// guard, so --resume ids must match its \`sess_<16 hex>\` shape.
|
|
254
|
+
const SESSION_ID_REGEX = /^sess_[0-9a-f]{16}$/;
|
|
167
255
|
const SPEC_NAME = ${escapeJsonString(ir.name)};
|
|
168
256
|
const SPEC_MODEL = ${escapeJsonString(ir.agent.model)};
|
|
169
257
|
const SPEC_INSTRUCTIONS = ${escapeJsonString(ir.agent.instructions)};
|
|
170
258
|
const SPEC_GROUNDING_MODEL = ${escapeJsonString(ir.groundingModel)};
|
|
171
259
|
const SPEC_BACKEND: "host" | "chromium" | "remote" = ${escapeJsonString(ir.driver.backend)};
|
|
172
260
|
const SPEC_VIEWPORT = { width: ${ir.driver.viewport.width}, height: ${ir.driver.viewport.height} };
|
|
173
|
-
const SPEC_START_URL = ${startUrl !== undefined ? escapeJsonString(startUrl) : "undefined"}
|
|
261
|
+
const SPEC_START_URL = ${startUrl !== undefined ? escapeJsonString(startUrl) : "undefined"};${hooksConst}
|
|
174
262
|
|
|
175
263
|
function emit(event: Record<string, unknown>): void {
|
|
176
264
|
process.stdout.write(\`\${JSON.stringify(event)}\\n\`);
|
|
177
265
|
}
|
|
178
266
|
|
|
179
|
-
function parseArgs(): {
|
|
267
|
+
function parseArgs(): {
|
|
268
|
+
prompt: string | undefined;
|
|
269
|
+
resumeId: string | undefined;
|
|
270
|
+
continueSession: boolean;
|
|
271
|
+
} {
|
|
180
272
|
const args = process.argv.slice(2);
|
|
181
|
-
const
|
|
182
|
-
|
|
183
|
-
|
|
273
|
+
const valueOf = (name: string): string | undefined => {
|
|
274
|
+
const i = args.indexOf(name);
|
|
275
|
+
return i !== -1 && i + 1 < args.length ? String(args[i + 1]) : undefined;
|
|
276
|
+
};
|
|
277
|
+
return {
|
|
278
|
+
prompt: valueOf("--prompt"),
|
|
279
|
+
resumeId: valueOf("--resume"),
|
|
280
|
+
continueSession: args.includes("--continue"),
|
|
281
|
+
};
|
|
184
282
|
}
|
|
185
283
|
|
|
186
284
|
async function readStdin(): Promise<string> {
|
|
@@ -191,9 +289,44 @@ async function readStdin(): Promise<string> {
|
|
|
191
289
|
}
|
|
192
290
|
|
|
193
291
|
async function main(): Promise<void> {
|
|
194
|
-
const { prompt: argPrompt } = parseArgs();
|
|
195
|
-
|
|
196
|
-
|
|
292
|
+
const { prompt: argPrompt, resumeId, continueSession } = parseArgs();
|
|
293
|
+
if (resumeId !== undefined && continueSession) {
|
|
294
|
+
process.stderr.write("[browser-driver] --resume and --continue are mutually exclusive\\n");
|
|
295
|
+
process.exit(2);
|
|
296
|
+
}
|
|
297
|
+
if (resumeId !== undefined && !SESSION_ID_REGEX.test(resumeId)) {
|
|
298
|
+
process.stderr.write(
|
|
299
|
+
\`[browser-driver] invalid --resume sessionId "\${resumeId}" — expected sess_<16 hex>\\n\`,
|
|
300
|
+
);
|
|
301
|
+
process.exit(2);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Resolve the session to resume: an explicit --resume id, or --continue → the
|
|
305
|
+
// most-recently-updated session for this spec name in the cwd session store
|
|
306
|
+
// (mirror of runRunCli's --continue). Absent → a fresh session.
|
|
307
|
+
const sessionStore = createSessionStore();
|
|
308
|
+
let resume: { sessionId: string } | undefined;
|
|
309
|
+
if (resumeId !== undefined) {
|
|
310
|
+
resume = { sessionId: resumeId };
|
|
311
|
+
} else if (continueSession) {
|
|
312
|
+
const sessions = await sessionStore.list();
|
|
313
|
+
const match = sessions.find((s) => s.name === SPEC_NAME);
|
|
314
|
+
if (match === undefined) {
|
|
315
|
+
process.stderr.write(
|
|
316
|
+
\`[browser-driver] no prior session for "\${SPEC_NAME}" to --continue in \${process.cwd()}/.crewhaus/sessions/\\n\`,
|
|
317
|
+
);
|
|
318
|
+
process.exit(2);
|
|
319
|
+
}
|
|
320
|
+
resume = { sessionId: match.id };
|
|
321
|
+
process.stdout.write(\`[browser-driver] resuming session \${match.id}\\n\`);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// ONE-SHOT when a --prompt is supplied or stdin is piped (CI/scripting); an
|
|
325
|
+
// interactive TTY with no --prompt drops into the persistent driver REPL, so
|
|
326
|
+
// the agent observes → acts → re-observes across turns against one session.
|
|
327
|
+
const repl = argPrompt === undefined && process.stdin.isTTY === true;
|
|
328
|
+
const oneShotPrompt = repl ? "" : (argPrompt ?? (await readStdin()));
|
|
329
|
+
if (!repl && oneShotPrompt.length === 0) {
|
|
197
330
|
process.stderr.write("[browser-driver] no prompt (pass --prompt <text> or pipe stdin)\\n");
|
|
198
331
|
process.exit(2);
|
|
199
332
|
}
|
|
@@ -212,21 +345,60 @@ async function main(): Promise<void> {
|
|
|
212
345
|
const findElement = createFindElementTool({ driver, model: SPEC_GROUNDING_MODEL });
|
|
213
346
|
const tools = [navigateTool, screenshotTool, mk.click, mk.type, mk.key, mk.scroll, findElement, ...defaultCatalog.list()];
|
|
214
347
|
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
348
|
+
// On resume the run context must carry the resumed sessionId (runtime-core
|
|
349
|
+
// asserts they match); a fresh run mints its own.
|
|
350
|
+
const runContext =
|
|
351
|
+
resume !== undefined ? createRunContext({ sessionId: resume.sessionId }) : createRunContext();
|
|
352
|
+
// Session-persist driver state across turns: the driver stays connected for
|
|
353
|
+
// the whole runChatLoop call, so every REPL turn shares one live browser
|
|
354
|
+
// context. limits/budget/max_tokens (Batch A) apply to each turn.
|
|
355
|
+
const runOptions = {
|
|
356
|
+
model: SPEC_MODEL,
|
|
357
|
+
instructions: SPEC_INSTRUCTIONS,${poolField(ir, " ")}${taxonomyField(ir, " ")}
|
|
358
|
+
runContext,
|
|
359
|
+
sessionName: SPEC_NAME,
|
|
360
|
+
sessionTarget: "browser" as const,
|
|
361
|
+
tools,
|
|
362
|
+
maxTokens: ${ir.agent.maxTokens ?? 4096},${budgetField(ir, " ")}${limitsFields(ir, " ")}${hooksField}${permField}
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
// The REPL lets runChatLoop drive stdin turn-by-turn (singleTurn omitted);
|
|
366
|
+
// one-shot seeds the single inbound message. \`resume\` + \`seedMessages\` is
|
|
367
|
+
// legal ONLY under singleTurn (the seed is the new inbound, the replayed
|
|
368
|
+
// history is the prefix), so REPL resume passes no seed.
|
|
369
|
+
const drive = async (): Promise<string> => {
|
|
370
|
+
if (repl) {
|
|
371
|
+
return await runChatLoop({
|
|
372
|
+
...runOptions,
|
|
373
|
+
installSigintHandler: true,
|
|
374
|
+
...(resume !== undefined ? { resume } : {}),
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
return await runChatLoop({
|
|
378
|
+
...runOptions,
|
|
224
379
|
singleTurn: true,
|
|
225
|
-
seedMessages: [{ role: "user", content: stdinPrompt }],
|
|
226
|
-
tools,
|
|
227
380
|
installSigintHandler: false,
|
|
228
|
-
|
|
381
|
+
seedMessages: [{ role: "user", content: oneShotPrompt }],
|
|
382
|
+
...(resume !== undefined ? { resume } : {}),
|
|
229
383
|
});
|
|
384
|
+
};
|
|
385
|
+
|
|
386
|
+
let finalText = "";
|
|
387
|
+
try {
|
|
388
|
+
if (resume !== undefined) {
|
|
389
|
+
// ITEM 7 — wrap the resume path in withIdempotency so a duplicate
|
|
390
|
+
// re-invocation of an interrupted resumed run returns the cached reply
|
|
391
|
+
// instead of re-driving the browser (at-least-once safety).
|
|
392
|
+
const idemStore = createInMemoryIdempotencyStore<string>();
|
|
393
|
+
const guarded = withIdempotency<undefined, string>(() => drive(), {
|
|
394
|
+
store: idemStore,
|
|
395
|
+
ttlMs: 3_600_000,
|
|
396
|
+
});
|
|
397
|
+
const key = idempotencyKey(\`\${SPEC_NAME}:\${resume.sessionId}:\${oneShotPrompt}\`, 0);
|
|
398
|
+
finalText = (await guarded(undefined, key)).value;
|
|
399
|
+
} else {
|
|
400
|
+
finalText = await drive();
|
|
401
|
+
}
|
|
230
402
|
} finally {
|
|
231
403
|
await driver.disconnect();
|
|
232
404
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crewhaus/target-browser-driver",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
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.
|
|
19
|
-
"@crewhaus/infra-utils": "0.
|
|
20
|
-
"@crewhaus/ir": "0.
|
|
18
|
+
"@crewhaus/errors": "0.4.0",
|
|
19
|
+
"@crewhaus/infra-utils": "0.4.0",
|
|
20
|
+
"@crewhaus/ir": "0.4.0"
|
|
21
21
|
},
|
|
22
22
|
"license": "Apache-2.0",
|
|
23
23
|
"author": {
|