@crewhaus/target-browser-driver 0.1.3 → 0.1.5

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.
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Catalog F2 `target-browser-driver` — Section 25 BROW.
3
+ *
4
+ * Codegen for the computer-use target. Emits a single `agent.ts` that:
5
+ *
6
+ * 1. Constructs the chromium driver (Playwright-backed).
7
+ * 2. Optionally navigates to `driver.startUrl` before agent input.
8
+ * 3. Registers Navigate + Screenshot + Click + Type + Key + Scroll +
9
+ * FindElement as runtime tools. Destructive ones (Click, Type,
10
+ * Key, Scroll) sit at the `flag` rule layer and require explicit
11
+ * `alwaysAllow` rules — the smoke's permission-floor probe relies
12
+ * on this (same spec without `alwaysAllow` rules → denial cites
13
+ * destructive flag). Navigate, Screenshot and FindElement are
14
+ * default-allowed: Navigate is the agent's bootstrap (gating it
15
+ * would silently brick every browser spec without explicit rules);
16
+ * Screenshot and FindElement are read-only by design.
17
+ * 4. Imports + registers every spec-declared built-in tool from
18
+ * `ir.tools` onto `defaultCatalog`, applying `ir.toolConfigs` for
19
+ * tools whose registration takes a config (currently `fetch` and
20
+ * `webFetch`). The interpreter path (`crewhaus run` →
21
+ * `runRunBrowser` in apps/cli) mirrors this same set — keep them
22
+ * in sync.
23
+ * 5. Reads a single user prompt from `--prompt <text>` or stdin and
24
+ * runs `runChatLoop` in single-turn mode.
25
+ * 6. On exit, calls driver.disconnect() so chromium doesn't leak.
26
+ *
27
+ * `ir.mcp_servers` and `ir.compaction` are intentionally not wired here:
28
+ * the browser target is single-turn (`singleTurn: true`), so multi-turn-
29
+ * only features have no surface to attach to. If the run path ever
30
+ * extends these, mirror the change here too.
31
+ */
32
+ import { CrewhausError } from "@crewhaus/errors";
33
+ import type { Bundle, IrBrowserV0 } from "@crewhaus/ir";
34
+ export declare class TargetEmitError extends CrewhausError {
35
+ readonly name = "TargetEmitError";
36
+ constructor(message: string, cause?: unknown);
37
+ }
38
+ export declare function emitBrowserDriver(ir: IrBrowserV0): Bundle;
@@ -31,123 +31,92 @@
31
31
  */
32
32
  import { CrewhausError } from "@crewhaus/errors";
33
33
  import { escapeJsonString } from "@crewhaus/infra-utils";
34
- import type { Bundle, IrBrowserV0 } from "@crewhaus/ir";
35
-
36
34
  export class TargetEmitError extends CrewhausError {
37
- override readonly name = "TargetEmitError";
38
- constructor(message: string, cause?: unknown) {
39
- super("compiler", message, cause);
40
- }
35
+ name = "TargetEmitError";
36
+ constructor(message, cause) {
37
+ super("compiler", message, cause);
38
+ }
41
39
  }
42
-
43
- /**
44
- * Built-in tool name → package + export. Mirror of `loadToolMap()` in
45
- * `apps/cli/src/index.ts` — the `crewhaus run` browser path resolves the
46
- * same names to RegisteredTool instances. `initSymbol` is the optional
47
- * registration function called with the matching `toolConfigs[name]` blob
48
- * before the tool is registered (mirrors `applyToolConfigs()` in the run
49
- * path, which currently handles `fetch` and `webFetch`).
50
- */
51
- type BuiltinToolEntry = {
52
- readonly package: string;
53
- readonly export: string;
54
- readonly initSymbol?: string;
40
+ const BUILTIN_TOOL_MAP = {
41
+ read: { package: "@crewhaus/tool-fs", export: "read" },
42
+ write: { package: "@crewhaus/tool-fs", export: "write" },
43
+ edit: { package: "@crewhaus/tool-fs", export: "edit" },
44
+ glob: { package: "@crewhaus/tool-fs", export: "glob" },
45
+ grep: { package: "@crewhaus/tool-fs", export: "grep" },
46
+ bash: { package: "@crewhaus/tool-bash", export: "bash" },
47
+ todoWrite: { package: "@crewhaus/tool-todo", export: "todoWrite" },
48
+ webFetch: {
49
+ package: "@crewhaus/tool-web",
50
+ export: "webFetch",
51
+ initSymbol: "registerWebFetchConfig",
52
+ },
53
+ webSearch: { package: "@crewhaus/tool-web", export: "webSearch" },
54
+ readImage: { package: "@crewhaus/tool-image", export: "readImage" },
55
+ fetch: {
56
+ package: "@crewhaus/tool-fetch",
57
+ export: "fetch",
58
+ initSymbol: "registerFetchConfig",
59
+ },
60
+ imageGenerate: {
61
+ package: "@crewhaus/tool-image-generation",
62
+ export: "imageGenerate",
63
+ },
64
+ ingestDocument: {
65
+ package: "@crewhaus/tool-document-ingest",
66
+ export: "ingestDocument",
67
+ },
68
+ codegraphSearch: { package: "@crewhaus/tool-codegraph", export: "codegraphSearch" },
69
+ codegraphCallers: { package: "@crewhaus/tool-codegraph", export: "codegraphCallers" },
70
+ codegraphCallees: { package: "@crewhaus/tool-codegraph", export: "codegraphCallees" },
71
+ codegraphImpact: { package: "@crewhaus/tool-codegraph", export: "codegraphImpact" },
55
72
  };
56
-
57
- const BUILTIN_TOOL_MAP: Record<string, BuiltinToolEntry> = {
58
- read: { package: "@crewhaus/tool-fs", export: "read" },
59
- write: { package: "@crewhaus/tool-fs", export: "write" },
60
- edit: { package: "@crewhaus/tool-fs", export: "edit" },
61
- glob: { package: "@crewhaus/tool-fs", export: "glob" },
62
- grep: { package: "@crewhaus/tool-fs", export: "grep" },
63
- bash: { package: "@crewhaus/tool-bash", export: "bash" },
64
- todoWrite: { package: "@crewhaus/tool-todo", export: "todoWrite" },
65
- webFetch: {
66
- package: "@crewhaus/tool-web",
67
- export: "webFetch",
68
- initSymbol: "registerWebFetchConfig",
69
- },
70
- webSearch: { package: "@crewhaus/tool-web", export: "webSearch" },
71
- readImage: { package: "@crewhaus/tool-image", export: "readImage" },
72
- fetch: {
73
- package: "@crewhaus/tool-fetch",
74
- export: "fetch",
75
- initSymbol: "registerFetchConfig",
76
- },
77
- imageGenerate: {
78
- package: "@crewhaus/tool-image-generation",
79
- export: "imageGenerate",
80
- },
81
- ingestDocument: {
82
- package: "@crewhaus/tool-document-ingest",
83
- export: "ingestDocument",
84
- },
85
- codegraphSearch: { package: "@crewhaus/tool-codegraph", export: "codegraphSearch" },
86
- codegraphCallers: { package: "@crewhaus/tool-codegraph", export: "codegraphCallers" },
87
- codegraphCallees: { package: "@crewhaus/tool-codegraph", export: "codegraphCallees" },
88
- codegraphImpact: { package: "@crewhaus/tool-codegraph", export: "codegraphImpact" },
89
- };
90
-
91
- function resolveTools(
92
- toolNames: readonly string[],
93
- toolConfigs: Readonly<Record<string, unknown>>,
94
- ): {
95
- imports: string[];
96
- inits: string[];
97
- registrations: string[];
98
- } {
99
- if (toolNames.length === 0) return { imports: [], inits: [], registrations: [] };
100
-
101
- const byPackage = new Map<string, Set<string>>();
102
- const registrations: string[] = [];
103
- const inits: string[] = [];
104
- for (const name of toolNames) {
105
- const entry = BUILTIN_TOOL_MAP[name];
106
- if (!entry) {
107
- const known = Object.keys(BUILTIN_TOOL_MAP).sort().join(", ");
108
- throw new TargetEmitError(`unknown tool "${name}" — known tools: ${known}`);
73
+ function resolveTools(toolNames, toolConfigs) {
74
+ if (toolNames.length === 0)
75
+ return { imports: [], inits: [], registrations: [] };
76
+ const byPackage = new Map();
77
+ const registrations = [];
78
+ const inits = [];
79
+ for (const name of toolNames) {
80
+ const entry = BUILTIN_TOOL_MAP[name];
81
+ if (!entry) {
82
+ const known = Object.keys(BUILTIN_TOOL_MAP).sort().join(", ");
83
+ throw new TargetEmitError(`unknown tool "${name}" — known tools: ${known}`);
84
+ }
85
+ const set = byPackage.get(entry.package) ?? new Set();
86
+ set.add(entry.export);
87
+ byPackage.set(entry.package, set);
88
+ if (entry.initSymbol !== undefined) {
89
+ const cfg = toolConfigs[name];
90
+ if (cfg !== undefined) {
91
+ set.add(entry.initSymbol);
92
+ inits.push(`${entry.initSymbol}(${JSON.stringify(cfg)});`);
93
+ }
94
+ }
95
+ registrations.push(`defaultCatalog.register(${entry.export});`);
109
96
  }
110
- const set = byPackage.get(entry.package) ?? new Set<string>();
111
- set.add(entry.export);
112
- byPackage.set(entry.package, set);
113
- if (entry.initSymbol !== undefined) {
114
- const cfg = toolConfigs[name];
115
- if (cfg !== undefined) {
116
- set.add(entry.initSymbol);
117
- inits.push(`${entry.initSymbol}(${JSON.stringify(cfg)});`);
118
- }
97
+ const imports = [];
98
+ for (const pkg of [...byPackage.keys()].sort()) {
99
+ const symbols = [...(byPackage.get(pkg) ?? new Set())].sort();
100
+ imports.push(`import { ${symbols.join(", ")} } from "${pkg}";`);
119
101
  }
120
- registrations.push(`defaultCatalog.register(${entry.export});`);
121
- }
122
-
123
- const imports: string[] = [];
124
- for (const pkg of [...byPackage.keys()].sort()) {
125
- const symbols = [...(byPackage.get(pkg) ?? new Set<string>())].sort();
126
- imports.push(`import { ${symbols.join(", ")} } from "${pkg}";`);
127
- }
128
- return { imports, inits, registrations };
102
+ return { imports, inits, registrations };
129
103
  }
130
-
131
- export function emitBrowserDriver(ir: IrBrowserV0): Bundle {
132
- return { files: [{ path: "agent.ts", content: renderAgent(ir) }] };
104
+ export function emitBrowserDriver(ir) {
105
+ return { files: [{ path: "agent.ts", content: renderAgent(ir) }] };
133
106
  }
134
-
135
- function renderAgent(ir: IrBrowserV0): string {
136
- const startUrl = ir.driver.startUrl;
137
- const hasRules = ir.permissions.rules.length > 0;
138
- const permImport = hasRules
139
- ? `import { BUILTIN_DEFAULT_RULES } from "@crewhaus/permission-engine";\n`
140
- : "";
141
- const permField = renderPermissionsField(ir);
142
-
143
- const { imports: toolImports, inits, registrations } = resolveTools(ir.tools, ir.toolConfigs);
144
- const toolImportBlock = toolImports.length > 0 ? `${toolImports.join("\n")}\n` : "";
145
- const toolBootBlock =
146
- registrations.length > 0
147
- ? `\n${inits.length > 0 ? `${inits.join("\n")}\n` : ""}${registrations.join("\n")}\n`
148
- : "";
149
-
150
- return `#!/usr/bin/env bun
107
+ function renderAgent(ir) {
108
+ const startUrl = ir.driver.startUrl;
109
+ const hasRules = ir.permissions.rules.length > 0;
110
+ const permImport = hasRules
111
+ ? `import { BUILTIN_DEFAULT_RULES } from "@crewhaus/permission-engine";\n`
112
+ : "";
113
+ const permField = renderPermissionsField(ir);
114
+ const { imports: toolImports, inits, registrations } = resolveTools(ir.tools, ir.toolConfigs);
115
+ const toolImportBlock = toolImports.length > 0 ? `${toolImports.join("\n")}\n` : "";
116
+ const toolBootBlock = registrations.length > 0
117
+ ? `\n${inits.length > 0 ? `${inits.join("\n")}\n` : ""}${registrations.join("\n")}\n`
118
+ : "";
119
+ return `#!/usr/bin/env bun
151
120
  // Generated by crewhaus. DO NOT EDIT.
152
121
  // Source spec: ${escapeJsonString(ir.name)} (target: browser, ir version: ${ir.version})
153
122
  import { createDriver } from "@crewhaus/computer-use-driver";
@@ -234,34 +203,29 @@ main().catch((err) => {
234
203
  });
235
204
  `;
236
205
  }
237
-
238
- function renderPermissionsField(ir: IrBrowserV0): string {
239
- const { mode, rules } = ir.permissions;
240
- if (mode === undefined && rules.length === 0) return "";
241
- const lines: string[] = [];
242
- if (mode !== undefined) {
243
- lines.push(` permissionMode: ${escapeJsonString(mode)},`);
244
- }
245
- if (rules.length > 0) {
246
- const ruleLits = rules
247
- .map(
248
- (r) =>
249
- ` { type: ${escapeJsonString(r.type)}, pattern: ${escapeJsonString(r.pattern)}, source: "yaml" },`,
250
- )
251
- .join("\n");
252
- lines.push(
253
- [
254
- " permissionRules: {",
255
- " flag: [],",
256
- " settings: [],",
257
- " yaml: [",
258
- ruleLits,
259
- " ],",
260
- " hooks: [],",
261
- " builtin: BUILTIN_DEFAULT_RULES,",
262
- " },",
263
- ].join("\n"),
264
- );
265
- }
266
- return `\n${lines.join("\n")}`;
206
+ function renderPermissionsField(ir) {
207
+ const { mode, rules } = ir.permissions;
208
+ if (mode === undefined && rules.length === 0)
209
+ return "";
210
+ const lines = [];
211
+ if (mode !== undefined) {
212
+ lines.push(` permissionMode: ${escapeJsonString(mode)},`);
213
+ }
214
+ if (rules.length > 0) {
215
+ const ruleLits = rules
216
+ .map((r) => ` { type: ${escapeJsonString(r.type)}, pattern: ${escapeJsonString(r.pattern)}, source: "yaml" },`)
217
+ .join("\n");
218
+ lines.push([
219
+ " permissionRules: {",
220
+ " flag: [],",
221
+ " settings: [],",
222
+ " yaml: [",
223
+ ruleLits,
224
+ " ],",
225
+ " hooks: [],",
226
+ " builtin: BUILTIN_DEFAULT_RULES,",
227
+ " },",
228
+ ].join("\n"));
229
+ }
230
+ return `\n${lines.join("\n")}`;
267
231
  }
package/package.json CHANGED
@@ -1,20 +1,23 @@
1
1
  {
2
2
  "name": "@crewhaus/target-browser-driver",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
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
- "main": "src/index.ts",
7
- "types": "src/index.ts",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
8
  "exports": {
9
- ".": "./src/index.ts"
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
10
13
  },
11
14
  "scripts": {
12
15
  "test": "bun test src"
13
16
  },
14
17
  "dependencies": {
15
- "@crewhaus/errors": "0.1.3",
16
- "@crewhaus/infra-utils": "0.1.3",
17
- "@crewhaus/ir": "0.1.3"
18
+ "@crewhaus/errors": "0.1.5",
19
+ "@crewhaus/infra-utils": "0.1.5",
20
+ "@crewhaus/ir": "0.1.5"
18
21
  },
19
22
  "license": "Apache-2.0",
20
23
  "author": {
@@ -34,5 +37,5 @@
34
37
  "publishConfig": {
35
38
  "access": "public"
36
39
  },
37
- "files": ["src", "README.md", "LICENSE", "NOTICE"]
40
+ "files": ["dist", "README.md", "LICENSE", "NOTICE"]
38
41
  }
package/src/index.test.ts DELETED
@@ -1,297 +0,0 @@
1
- import { describe, expect, test } from "bun:test";
2
- import type { IrBrowserV0 } from "@crewhaus/ir";
3
- import { TargetEmitError, emitBrowserDriver } from "./index.js";
4
-
5
- const baseIr: IrBrowserV0 = {
6
- version: 0,
7
- name: "hello-browser",
8
- target: "browser",
9
- agent: { model: "claude-sonnet-4-6", instructions: "you click things" },
10
- driver: { backend: "chromium", viewport: { width: 1280, height: 720 } },
11
- groundingModel: "claude-sonnet-4-6",
12
- tools: [],
13
- toolConfigs: Object.freeze({}),
14
- mcp_servers: Object.freeze({}),
15
- permissions: { rules: [] },
16
- compaction: {},
17
- };
18
-
19
- describe("emitBrowserDriver", () => {
20
- test("emits a single agent.ts file (T1 bundle structure)", () => {
21
- const bundle = emitBrowserDriver(baseIr);
22
- expect(bundle.files).toHaveLength(1);
23
- expect(bundle.files[0]?.path).toBe("agent.ts");
24
- });
25
-
26
- test("agent.ts wires driver + navigate + screenshot + mouse-keyboard + vision-grounding", () => {
27
- const code = emitBrowserDriver(baseIr).files[0]?.content ?? "";
28
- expect(code).toContain("@crewhaus/computer-use-driver");
29
- expect(code).toContain("@crewhaus/tool-navigate");
30
- expect(code).toContain("@crewhaus/tool-screen-capture");
31
- expect(code).toContain("@crewhaus/tool-mouse-keyboard");
32
- expect(code).toContain("@crewhaus/tool-vision-grounding");
33
- expect(code).toContain("createNavigateTool");
34
- expect(code).toContain("createScreenshotTool");
35
- expect(code).toContain("createAllMouseKeyboardTools");
36
- expect(code).toContain("createFindElementTool");
37
- });
38
-
39
- test("Navigate is listed first in the runtime tools array (bootstrap before others)", () => {
40
- const code = emitBrowserDriver(baseIr).files[0]?.content ?? "";
41
- // The emitted line declares the tools array. Navigate must appear before
42
- // Screenshot / Click / Type / Key / Scroll / FindElement so the agent has
43
- // an obvious entry point when no startUrl is set.
44
- const toolsLine = code.split("\n").find((l) => l.includes("const tools = ["));
45
- expect(toolsLine).toBeDefined();
46
- expect(toolsLine).toContain("navigateTool");
47
- const navIdx = toolsLine?.indexOf("navigateTool") ?? -1;
48
- const screenshotIdx = toolsLine?.indexOf("screenshotTool") ?? -1;
49
- expect(navIdx).toBeGreaterThanOrEqual(0);
50
- expect(screenshotIdx).toBeGreaterThan(navIdx);
51
- });
52
-
53
- test("startUrl, when set, triggers driver.goto() before runChatLoop", () => {
54
- const ir: IrBrowserV0 = {
55
- ...baseIr,
56
- driver: { ...baseIr.driver, startUrl: "http://localhost:3000/" },
57
- };
58
- const code = emitBrowserDriver(ir).files[0]?.content ?? "";
59
- expect(code).toContain('"http://localhost:3000/"');
60
- expect(code).toContain("driver.goto(SPEC_START_URL)");
61
- expect(code).toContain('"navigated"');
62
- });
63
-
64
- test("absent startUrl yields SPEC_START_URL = undefined", () => {
65
- const code = emitBrowserDriver(baseIr).files[0]?.content ?? "";
66
- expect(code).toContain("SPEC_START_URL = undefined");
67
- });
68
-
69
- test("hard-codes backend + viewport from the spec", () => {
70
- const code = emitBrowserDriver(baseIr).files[0]?.content ?? "";
71
- expect(code).toContain('SPEC_BACKEND: "host" | "chromium" | "remote" = "chromium"');
72
- expect(code).toContain("width: 1280, height: 720");
73
- });
74
-
75
- test("permission rules: spec yaml-source rules pass through (T8 floor)", () => {
76
- const ir: IrBrowserV0 = {
77
- ...baseIr,
78
- permissions: {
79
- mode: "default",
80
- rules: [
81
- { type: "alwaysAllow", pattern: "Click" },
82
- { type: "alwaysAllow", pattern: "FindElement" },
83
- ],
84
- },
85
- };
86
- const code = emitBrowserDriver(ir).files[0]?.content ?? "";
87
- expect(code).toContain('permissionMode: "default"');
88
- expect(code).toContain('pattern: "Click"');
89
- expect(code).toContain('pattern: "FindElement"');
90
- expect(code).toContain("BUILTIN_DEFAULT_RULES");
91
- });
92
-
93
- test("permission floor: NO alwaysAllow rules → no permissionRules block emitted (default mode denies destructive)", () => {
94
- const code = emitBrowserDriver(baseIr).files[0]?.content ?? "";
95
- expect(code).not.toContain("permissionMode");
96
- expect(code).not.toContain("permissionRules");
97
- expect(code).not.toContain("BUILTIN_DEFAULT_RULES");
98
- });
99
-
100
- test("daemon parses --prompt arg + falls back to stdin", () => {
101
- const code = emitBrowserDriver(baseIr).files[0]?.content ?? "";
102
- expect(code).toContain('"--prompt"');
103
- expect(code).toContain("readStdin");
104
- });
105
-
106
- test("daemon emits browser_start / navigated / browser_done JSON events", () => {
107
- const ir: IrBrowserV0 = {
108
- ...baseIr,
109
- driver: { ...baseIr.driver, startUrl: "http://localhost:3000/" },
110
- };
111
- const code = emitBrowserDriver(ir).files[0]?.content ?? "";
112
- expect(code).toContain('"browser_start"');
113
- expect(code).toContain('"navigated"');
114
- expect(code).toContain('"browser_done"');
115
- });
116
-
117
- test("TargetEmitError type is exported", () => {
118
- expect(TargetEmitError).toBeDefined();
119
- });
120
- });
121
-
122
- describe("emitBrowserDriver — tool wiring (parity with runRunBrowser)", () => {
123
- test("empty tools list emits no tool imports and no register block", () => {
124
- const code = emitBrowserDriver(baseIr).files[0]?.content ?? "";
125
- // defaultCatalog import is still present — the final tools array spreads
126
- // it, so the bundle still compiles when no spec tools are declared.
127
- expect(code).toContain('from "@crewhaus/tool-catalog"');
128
- // none of the built-in tool packages should appear
129
- expect(code).not.toContain("@crewhaus/tool-fs");
130
- expect(code).not.toContain("@crewhaus/tool-bash");
131
- expect(code).not.toContain("@crewhaus/tool-web");
132
- expect(code).not.toContain("@crewhaus/tool-fetch");
133
- expect(code).not.toContain("defaultCatalog.register(");
134
- // and the final tools array still has the catalog spread (regression
135
- // guard for the existing behavior)
136
- expect(code).toContain("...defaultCatalog.list()");
137
- });
138
-
139
- test("a single spec tool emits one import + one defaultCatalog.register call", () => {
140
- const ir: IrBrowserV0 = { ...baseIr, tools: ["read"] };
141
- const code = emitBrowserDriver(ir).files[0]?.content ?? "";
142
- expect(code).toContain('import { read } from "@crewhaus/tool-fs";');
143
- expect(code).toContain("defaultCatalog.register(read);");
144
- // and the spread is still in place — registrations land in the final
145
- // tools array via defaultCatalog.list()
146
- expect(code).toContain("...defaultCatalog.list()");
147
- });
148
-
149
- test("multiple tools from the same package are grouped into one import", () => {
150
- const ir: IrBrowserV0 = { ...baseIr, tools: ["read", "write", "edit"] };
151
- const code = emitBrowserDriver(ir).files[0]?.content ?? "";
152
- expect(code).toMatch(/import \{ edit, read, write \} from "@crewhaus\/tool-fs";/);
153
- expect(code).toContain("defaultCatalog.register(read);");
154
- expect(code).toContain("defaultCatalog.register(write);");
155
- expect(code).toContain("defaultCatalog.register(edit);");
156
- });
157
-
158
- test("tools across multiple packages each get their own grouped import", () => {
159
- const ir: IrBrowserV0 = { ...baseIr, tools: ["read", "bash", "todoWrite"] };
160
- const code = emitBrowserDriver(ir).files[0]?.content ?? "";
161
- expect(code).toContain('import { bash } from "@crewhaus/tool-bash";');
162
- expect(code).toContain('import { read } from "@crewhaus/tool-fs";');
163
- expect(code).toContain('import { todoWrite } from "@crewhaus/tool-todo";');
164
- });
165
-
166
- test("unknown tool throws TargetEmitError naming the offender + known names", () => {
167
- const ir: IrBrowserV0 = { ...baseIr, tools: ["unknownTool"] };
168
- expect(() => emitBrowserDriver(ir)).toThrow(TargetEmitError);
169
- try {
170
- emitBrowserDriver(ir);
171
- } catch (e) {
172
- expect(e).toBeInstanceOf(TargetEmitError);
173
- expect((e as Error).message).toContain('unknown tool "unknownTool"');
174
- expect((e as Error).message).toContain("known tools:");
175
- expect((e as Error).message).toContain("read");
176
- }
177
- });
178
-
179
- test("fetch with toolConfigs.fetch emits registerFetchConfig before the register call", () => {
180
- const ir: IrBrowserV0 = {
181
- ...baseIr,
182
- tools: ["fetch"],
183
- toolConfigs: { fetch: { allowed_origins: ["https://example.com"] } },
184
- };
185
- const code = emitBrowserDriver(ir).files[0]?.content ?? "";
186
- expect(code).toMatch(/import \{ fetch, registerFetchConfig \} from "@crewhaus\/tool-fetch";/);
187
- expect(code).toContain('registerFetchConfig({"allowed_origins":["https://example.com"]});');
188
- expect(code).toContain("defaultCatalog.register(fetch);");
189
- // init must come before the register call (so the tool sees its config
190
- // on first execute)
191
- const initIdx = code.indexOf("registerFetchConfig(");
192
- const registerIdx = code.indexOf("defaultCatalog.register(fetch);");
193
- expect(initIdx).toBeGreaterThan(-1);
194
- expect(registerIdx).toBeGreaterThan(initIdx);
195
- });
196
-
197
- test("webFetch with toolConfigs.webFetch emits registerWebFetchConfig", () => {
198
- const ir: IrBrowserV0 = {
199
- ...baseIr,
200
- tools: ["webFetch"],
201
- toolConfigs: { webFetch: { timeout_ms: 5000 } },
202
- };
203
- const code = emitBrowserDriver(ir).files[0]?.content ?? "";
204
- expect(code).toMatch(
205
- /import \{ registerWebFetchConfig, webFetch \} from "@crewhaus\/tool-web";/,
206
- );
207
- expect(code).toContain('registerWebFetchConfig({"timeout_ms":5000});');
208
- expect(code).toContain("defaultCatalog.register(webFetch);");
209
- });
210
-
211
- test("a tool with an initSymbol but no config does NOT emit an init call", () => {
212
- // fetch has an initSymbol but toolConfigs is empty — register should
213
- // still happen, but no registerFetchConfig() call.
214
- const ir: IrBrowserV0 = { ...baseIr, tools: ["fetch"] };
215
- const code = emitBrowserDriver(ir).files[0]?.content ?? "";
216
- expect(code).toContain('import { fetch } from "@crewhaus/tool-fetch";');
217
- expect(code).toContain("defaultCatalog.register(fetch);");
218
- expect(code).not.toContain("registerFetchConfig(");
219
- });
220
-
221
- test("tools without an initSymbol emit no init call regardless of toolConfigs", () => {
222
- // webSearch has no initSymbol; a config keyed on it should be ignored.
223
- const ir: IrBrowserV0 = {
224
- ...baseIr,
225
- tools: ["webSearch"],
226
- toolConfigs: { webSearch: { ignored: true } },
227
- };
228
- const code = emitBrowserDriver(ir).files[0]?.content ?? "";
229
- expect(code).toContain('import { webSearch } from "@crewhaus/tool-web";');
230
- expect(code).toContain("defaultCatalog.register(webSearch);");
231
- expect(code).not.toContain("registerWebFetchConfig(");
232
- expect(code).not.toContain("registerFetchConfig(");
233
- });
234
-
235
- test("tool registrations sit between imports and the SPEC_NAME constants", () => {
236
- const ir: IrBrowserV0 = { ...baseIr, tools: ["read"] };
237
- const code = emitBrowserDriver(ir).files[0]?.content ?? "";
238
- const importIdx = code.indexOf('import { read } from "@crewhaus/tool-fs";');
239
- const registerIdx = code.indexOf("defaultCatalog.register(read);");
240
- const specNameIdx = code.indexOf("const SPEC_NAME =");
241
- expect(importIdx).toBeGreaterThanOrEqual(0);
242
- expect(registerIdx).toBeGreaterThan(importIdx);
243
- expect(specNameIdx).toBeGreaterThan(registerIdx);
244
- });
245
-
246
- test("permission rules and spec tools coexist without stepping on each other", () => {
247
- const ir: IrBrowserV0 = {
248
- ...baseIr,
249
- tools: ["read"],
250
- permissions: {
251
- mode: "default",
252
- rules: [{ type: "alwaysAllow", pattern: "Click" }],
253
- },
254
- };
255
- const code = emitBrowserDriver(ir).files[0]?.content ?? "";
256
- expect(code).toContain('import { read } from "@crewhaus/tool-fs";');
257
- expect(code).toContain("defaultCatalog.register(read);");
258
- expect(code).toContain("BUILTIN_DEFAULT_RULES");
259
- expect(code).toContain('permissionMode: "default"');
260
- expect(code).toContain('pattern: "Click"');
261
- });
262
- });
263
-
264
- describe("emitBrowserDriver — single-turn parity (no mcp_servers, no compaction)", () => {
265
- test("mcp_servers in the IR is NOT wired (matches runRunBrowser's single-turn semantics)", () => {
266
- const ir: IrBrowserV0 = {
267
- ...baseIr,
268
- mcp_servers: {
269
- everything: {
270
- transport: "stdio",
271
- command: "npx",
272
- args: ["-y", "@modelcontextprotocol/server-everything"],
273
- },
274
- },
275
- };
276
- const code = emitBrowserDriver(ir).files[0]?.content ?? "";
277
- // No McpHost boot, no registerMcpServer, no disconnectAll cleanup.
278
- // If this ever needs to change, the run path (apps/cli runRunBrowser)
279
- // must change in lockstep.
280
- expect(code).not.toContain("@crewhaus/mcp-host");
281
- expect(code).not.toContain("@crewhaus/tool-mcp");
282
- expect(code).not.toContain("McpHost");
283
- expect(code).not.toContain("registerMcpServer");
284
- expect(code).not.toContain("disconnectAll");
285
- });
286
-
287
- test("compaction in the IR is NOT wired (matches runRunBrowser's single-turn semantics)", () => {
288
- const ir: IrBrowserV0 = {
289
- ...baseIr,
290
- compaction: { curate: true, dedupeThreshold: 0.9 },
291
- };
292
- const code = emitBrowserDriver(ir).files[0]?.content ?? "";
293
- expect(code).not.toContain("compaction");
294
- expect(code).not.toContain("curate");
295
- expect(code).not.toContain("@crewhaus/compaction-");
296
- });
297
- });