@crewhaus/target-crew 0.1.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/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@crewhaus/target-crew",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Codegen for the CRW target — emits a daemon + per-role agent files driven by crew-orchestrator (Section 22)",
6
+ "main": "src/index.ts",
7
+ "types": "src/index.ts",
8
+ "exports": {
9
+ ".": "./src/index.ts"
10
+ },
11
+ "scripts": {
12
+ "test": "bun test src"
13
+ },
14
+ "dependencies": {
15
+ "@crewhaus/errors": "0.0.0",
16
+ "@crewhaus/infra-utils": "0.0.0",
17
+ "@crewhaus/ir": "0.0.0"
18
+ },
19
+ "license": "Apache-2.0",
20
+ "author": {
21
+ "name": "Max Meier",
22
+ "email": "max@studiomax.io",
23
+ "url": "https://studiomax.io"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/crewhaus/factory.git",
28
+ "directory": "packages/target-crew"
29
+ },
30
+ "homepage": "https://github.com/crewhaus/factory/tree/main/packages/target-crew#readme",
31
+ "bugs": {
32
+ "url": "https://github.com/crewhaus/factory/issues"
33
+ },
34
+ "publishConfig": {
35
+ "access": "restricted"
36
+ },
37
+ "files": [
38
+ "src",
39
+ "README.md",
40
+ "LICENSE",
41
+ "NOTICE"
42
+ ]
43
+ }
@@ -0,0 +1,158 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { IrCrewV0 } from "@crewhaus/ir";
3
+ import { TargetEmitError, emitCrew } from "./index.js";
4
+
5
+ const baseRole = {
6
+ tools: [],
7
+ toolConfigs: Object.freeze({}),
8
+ subAgents: [],
9
+ };
10
+
11
+ const minimalIr: IrCrewV0 = {
12
+ version: 0,
13
+ name: "hello-crew",
14
+ target: "crew",
15
+ entry: "researcher",
16
+ roles: [
17
+ {
18
+ name: "researcher",
19
+ model: "claude-sonnet-4-6",
20
+ instructions: "You are the researcher.",
21
+ ...baseRole,
22
+ },
23
+ {
24
+ name: "writer",
25
+ model: "claude-sonnet-4-6",
26
+ instructions: "You are the writer.",
27
+ ...baseRole,
28
+ },
29
+ {
30
+ name: "critic",
31
+ model: "claude-sonnet-4-6",
32
+ instructions: "You are the critic.",
33
+ ...baseRole,
34
+ },
35
+ ],
36
+ mcp_servers: Object.freeze({}),
37
+ permissions: { rules: [] },
38
+ compaction: {},
39
+ };
40
+
41
+ describe("emitCrew", () => {
42
+ test("emits orchestrator + daemon + per-role agent files (T1 bundle structure)", () => {
43
+ const bundle = emitCrew(minimalIr);
44
+ const paths = bundle.files.map((f) => f.path).sort();
45
+ expect(paths).toEqual([
46
+ "agent_critic.ts",
47
+ "agent_researcher.ts",
48
+ "agent_writer.ts",
49
+ "daemon.ts",
50
+ "orchestrator.ts",
51
+ ]);
52
+ });
53
+
54
+ test("orchestrator wires every role + sets entry", () => {
55
+ const bundle = emitCrew(minimalIr);
56
+ const orchestrator = bundle.files.find((f) => f.path === "orchestrator.ts");
57
+ expect(orchestrator).toBeDefined();
58
+ const code = orchestrator?.content;
59
+ expect(code).toContain("import { Crew");
60
+ expect(code).toContain('from "./agent_researcher.js"');
61
+ expect(code).toContain('from "./agent_writer.js"');
62
+ expect(code).toContain('from "./agent_critic.js"');
63
+ expect(code).toContain('.setEntry("researcher")');
64
+ });
65
+
66
+ test("daemon emits JSON events to stdout in a streaming loop", () => {
67
+ const bundle = emitCrew(minimalIr);
68
+ const daemon = bundle.files.find((f) => f.path === "daemon.ts");
69
+ expect(daemon).toBeDefined();
70
+ const code = daemon?.content;
71
+ expect(code).toContain("for await (const ev of crew.run");
72
+ expect(code).toContain("JSON.stringify(ev)");
73
+ expect(code).toContain("readAllStdin");
74
+ });
75
+
76
+ test("per-role agent file exports a RoleDefinition wrapper with model + instructions", () => {
77
+ const bundle = emitCrew(minimalIr);
78
+ const writer = bundle.files.find((f) => f.path === "agent_writer.ts");
79
+ expect(writer).toBeDefined();
80
+ const code = writer?.content;
81
+ expect(code).toContain("export const role:");
82
+ expect(code).toContain('"writer"');
83
+ expect(code).toContain("You are the writer.");
84
+ expect(code).toContain('"claude-sonnet-4-6"');
85
+ });
86
+
87
+ test("rejects empty crew", () => {
88
+ const ir: IrCrewV0 = {
89
+ ...minimalIr,
90
+ roles: [],
91
+ entry: "x",
92
+ };
93
+ expect(() => emitCrew(ir)).toThrow(TargetEmitError);
94
+ });
95
+
96
+ test("rejects entry that doesn't match any role", () => {
97
+ const ir: IrCrewV0 = {
98
+ ...minimalIr,
99
+ entry: "nope",
100
+ };
101
+ expect(() => emitCrew(ir)).toThrow(/entry "nope"/);
102
+ });
103
+
104
+ test("rejects unknown tool names", () => {
105
+ const ir: IrCrewV0 = {
106
+ ...minimalIr,
107
+ roles: [
108
+ {
109
+ name: "r1",
110
+ model: "m",
111
+ instructions: "i",
112
+ tools: ["nonexistent-tool"],
113
+ toolConfigs: Object.freeze({}),
114
+ subAgents: [],
115
+ },
116
+ ],
117
+ entry: "r1",
118
+ };
119
+ expect(() => emitCrew(ir)).toThrow(/unknown tool "nonexistent-tool"/);
120
+ });
121
+
122
+ test('emits routing match table when routing.kind === "match"', () => {
123
+ const ir: IrCrewV0 = {
124
+ ...minimalIr,
125
+ routing: {
126
+ kind: "match",
127
+ match: {
128
+ researcher: [{ contains: "DONE", to: "writer" }],
129
+ writer: [{ contains: "REVIEW", to: "critic" }],
130
+ },
131
+ },
132
+ };
133
+ const bundle = emitCrew(ir);
134
+ const orch = bundle.files.find((f) => f.path === "orchestrator.ts");
135
+ expect(orch).toBeDefined();
136
+ expect(orch?.content).toContain("__routingTable");
137
+ expect(orch?.content).toContain("setRouting");
138
+ expect(orch?.content).toContain("DONE");
139
+ });
140
+
141
+ test("permissions block lands on the daemon's runOptions", () => {
142
+ const ir: IrCrewV0 = {
143
+ ...minimalIr,
144
+ permissions: {
145
+ mode: "default",
146
+ rules: [
147
+ { type: "alwaysAllow", pattern: "Handoff" },
148
+ { type: "alwaysAllow", pattern: "SendMessage" },
149
+ ],
150
+ },
151
+ };
152
+ const bundle = emitCrew(ir);
153
+ const daemon = bundle.files.find((f) => f.path === "daemon.ts");
154
+ expect(daemon?.content).toContain("BUILTIN_DEFAULT_RULES");
155
+ expect(daemon?.content).toContain("permissionMode");
156
+ expect(daemon?.content).toContain("Handoff");
157
+ });
158
+ });
package/src/index.ts ADDED
@@ -0,0 +1,314 @@
1
+ /**
2
+ * Catalog F2 `target-crew` — Section 22.
3
+ *
4
+ * Codegen for the CRW target shape. Mirrors the multi-file pattern from
5
+ * `target-channel-bot`:
6
+ * - `daemon.ts` — entrypoint that loads hooks/skills/commands,
7
+ * constructs the runnable crew, and serves stdin or
8
+ * a webhook.
9
+ * - `orchestrator.ts` — wires the `Crew` builder to the spec roles +
10
+ * entry + routing.
11
+ * - `agent_<role>.ts` — per-role config wrapper exporting a
12
+ * `RoleDefinition` instance for the orchestrator
13
+ * to register.
14
+ *
15
+ * The emitted daemon reads input from stdin (one prompt per line) and
16
+ * pipes events to stdout as JSON-per-line so the smoke harness (and any
17
+ * future shell pipeline consumer) can parse them deterministically.
18
+ */
19
+ import { CrewhausError } from "@crewhaus/errors";
20
+ import { escapeJsonString } from "@crewhaus/infra-utils";
21
+ import type { Bundle, IrCrewRole, IrCrewV0 } from "@crewhaus/ir";
22
+
23
+ export class TargetEmitError extends CrewhausError {
24
+ override readonly name = "TargetEmitError";
25
+ constructor(message: string, cause?: unknown) {
26
+ super("compiler", message, cause);
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Built-in tool name → package + export. Mirrors target-channel-bot's
32
+ * map but excluded `sendMessage` (the channel-bot variant) since CRW
33
+ * roles use `a2a-protocol`'s `SendMessage` automatically wired by the
34
+ * orchestrator.
35
+ */
36
+ type BuiltinToolEntry = {
37
+ readonly package: string;
38
+ readonly export: string;
39
+ readonly initSymbol?: string;
40
+ };
41
+
42
+ const BUILTIN_TOOL_MAP: Record<string, BuiltinToolEntry> = {
43
+ read: { package: "@crewhaus/tool-fs", export: "read" },
44
+ write: { package: "@crewhaus/tool-fs", export: "write" },
45
+ edit: { package: "@crewhaus/tool-fs", export: "edit" },
46
+ glob: { package: "@crewhaus/tool-fs", export: "glob" },
47
+ grep: { package: "@crewhaus/tool-fs", export: "grep" },
48
+ bash: { package: "@crewhaus/tool-bash", export: "bash" },
49
+ todoWrite: { package: "@crewhaus/tool-todo", export: "todoWrite" },
50
+ webFetch: {
51
+ package: "@crewhaus/tool-web",
52
+ export: "webFetch",
53
+ initSymbol: "registerWebFetchConfig",
54
+ },
55
+ webSearch: { package: "@crewhaus/tool-web", export: "webSearch" },
56
+ readImage: { package: "@crewhaus/tool-image", export: "readImage" },
57
+ fetch: {
58
+ package: "@crewhaus/tool-fetch",
59
+ export: "fetch",
60
+ initSymbol: "registerFetchConfig",
61
+ },
62
+ // §47 read-only EVM tools (slice 0).
63
+ evmCall: { package: "@crewhaus/tool-evm", export: "evmCall" },
64
+ evmGetLogs: { package: "@crewhaus/tool-evm", export: "evmGetLogs" },
65
+ evmGetTransaction: { package: "@crewhaus/tool-evm", export: "evmGetTransaction" },
66
+ evmGetTransactionReceipt: {
67
+ package: "@crewhaus/tool-evm",
68
+ export: "evmGetTransactionReceipt",
69
+ },
70
+ evmGetBalance: { package: "@crewhaus/tool-evm", export: "evmGetBalance" },
71
+ evmBlockNumber: { package: "@crewhaus/tool-evm", export: "evmBlockNumber" },
72
+ // §47 destructive EVM tools (slice 1) — gated by permission-engine
73
+ // (destructive: true) and wallet-engine (two-gate model).
74
+ evmSendTransaction: { package: "@crewhaus/tool-evm-tx", export: "evmSendTransaction" },
75
+ evmSimulate: { package: "@crewhaus/tool-evm-tx", export: "evmSimulate" },
76
+ // Pillar 2 — AST-aware code intelligence (recipe 54).
77
+ codegraphSearch: { package: "@crewhaus/tool-codegraph", export: "codegraphSearch" },
78
+ codegraphCallers: { package: "@crewhaus/tool-codegraph", export: "codegraphCallers" },
79
+ codegraphCallees: { package: "@crewhaus/tool-codegraph", export: "codegraphCallees" },
80
+ codegraphImpact: { package: "@crewhaus/tool-codegraph", export: "codegraphImpact" },
81
+ };
82
+
83
+ export function emitCrew(ir: IrCrewV0): Bundle {
84
+ if (ir.roles.length === 0) {
85
+ throw new TargetEmitError("crew target requires at least one role");
86
+ }
87
+ const entryRole = ir.roles.find((r) => r.name === ir.entry);
88
+ if (entryRole === undefined) {
89
+ throw new TargetEmitError(
90
+ `crew entry "${ir.entry}" does not match any defined role (got: ${ir.roles
91
+ .map((r) => r.name)
92
+ .join(", ")})`,
93
+ );
94
+ }
95
+
96
+ const files = [
97
+ { path: "orchestrator.ts", content: renderOrchestrator(ir) },
98
+ { path: "daemon.ts", content: renderDaemon(ir) },
99
+ ];
100
+ for (const role of ir.roles) {
101
+ files.push({ path: `agent_${safeFileName(role.name)}.ts`, content: renderRoleAgent(ir, role) });
102
+ }
103
+ return { files };
104
+ }
105
+
106
+ function safeFileName(role: string): string {
107
+ // Conservative: keep alnum + underscore so generated paths are clean.
108
+ return role.replace(/[^a-zA-Z0-9_]/g, "_");
109
+ }
110
+
111
+ function resolveTools(
112
+ toolNames: readonly string[],
113
+ toolConfigs: Readonly<Record<string, unknown>>,
114
+ ): {
115
+ imports: string[];
116
+ inits: string[];
117
+ registrations: string[];
118
+ } {
119
+ if (toolNames.length === 0) return { imports: [], inits: [], registrations: [] };
120
+ const byPackage = new Map<string, Set<string>>();
121
+ const registrations: string[] = [];
122
+ const inits: string[] = [];
123
+ for (const name of toolNames) {
124
+ const entry = BUILTIN_TOOL_MAP[name];
125
+ if (!entry) {
126
+ const known = Object.keys(BUILTIN_TOOL_MAP).sort().join(", ");
127
+ throw new TargetEmitError(`unknown tool "${name}" — known tools: ${known}`);
128
+ }
129
+ const set = byPackage.get(entry.package) ?? new Set<string>();
130
+ set.add(entry.export);
131
+ byPackage.set(entry.package, set);
132
+ if (entry.initSymbol !== undefined) {
133
+ const cfg = toolConfigs[name];
134
+ if (cfg !== undefined) {
135
+ set.add(entry.initSymbol);
136
+ inits.push(`${entry.initSymbol}(${JSON.stringify(cfg)});`);
137
+ }
138
+ }
139
+ registrations.push(entry.export);
140
+ }
141
+ const imports: string[] = [];
142
+ for (const pkg of [...byPackage.keys()].sort()) {
143
+ const symbols = [...(byPackage.get(pkg) ?? new Set<string>())].sort();
144
+ imports.push(`import { ${symbols.join(", ")} } from "${pkg}";`);
145
+ }
146
+ return { imports, inits, registrations };
147
+ }
148
+
149
+ function renderPermissionsField(ir: IrCrewV0): string {
150
+ const { mode, rules } = ir.permissions;
151
+ if (mode === undefined && rules.length === 0) return "";
152
+ const lines: string[] = [];
153
+ if (mode !== undefined) {
154
+ lines.push(` permissionMode: ${escapeJsonString(mode)},`);
155
+ }
156
+ if (rules.length > 0) {
157
+ const ruleLits = rules
158
+ .map(
159
+ (r) =>
160
+ ` { type: ${escapeJsonString(r.type)}, pattern: ${escapeJsonString(r.pattern)}, source: "yaml" },`,
161
+ )
162
+ .join("\n");
163
+ lines.push(
164
+ [
165
+ " permissionRules: {",
166
+ " flag: [],",
167
+ " settings: [],",
168
+ " yaml: [",
169
+ ruleLits,
170
+ " ],",
171
+ " hooks: [],",
172
+ " builtin: BUILTIN_DEFAULT_RULES,",
173
+ " },",
174
+ ].join("\n"),
175
+ );
176
+ }
177
+ return `\n${lines.join("\n")}`;
178
+ }
179
+
180
+ // ---------------------------------------------------------------------------
181
+ // File: agent_<role>.ts — exports the role's RoleDefinition.
182
+ // ---------------------------------------------------------------------------
183
+
184
+ function renderRoleAgent(ir: IrCrewV0, role: IrCrewRole): string {
185
+ const { imports, inits, registrations } = resolveTools(role.tools, role.toolConfigs);
186
+ const importBlock = imports.length > 0 ? `${imports.join("\n")}\n` : "";
187
+ const initLines = inits.length > 0 ? `${inits.join("\n")}\n` : "";
188
+ const toolsArrayLiteral = registrations.length > 0 ? `[${registrations.join(", ")}]` : "[]";
189
+ return `// Generated by crewhaus. DO NOT EDIT.
190
+ // Source spec: ${ir.name} (target: crew, ir version: ${ir.version}, role: ${role.name})
191
+ ${importBlock}import type { RoleDefinition } from "@crewhaus/crew-orchestrator";
192
+
193
+ ${initLines}
194
+ export const role: { name: string; def: RoleDefinition } = {
195
+ name: ${escapeJsonString(role.name)},
196
+ def: {
197
+ model: ${escapeJsonString(role.model)},
198
+ instructions: ${escapeJsonString(role.instructions)},
199
+ tools: ${toolsArrayLiteral},
200
+ },
201
+ };
202
+ `;
203
+ }
204
+
205
+ // ---------------------------------------------------------------------------
206
+ // File: orchestrator.ts — composes Crew() from roles + entry + routing.
207
+ // ---------------------------------------------------------------------------
208
+
209
+ function renderOrchestrator(ir: IrCrewV0): string {
210
+ const roleImports = ir.roles
211
+ .map((r) => `import { role as ${roleVar(r.name)} } from "./agent_${safeFileName(r.name)}.js";`)
212
+ .join("\n");
213
+ const adds = ir.roles
214
+ .map((r) => ` .addRole(${roleVar(r.name)}.name, ${roleVar(r.name)}.def)`)
215
+ .join("\n");
216
+
217
+ let routerBlock = "";
218
+ if (ir.routing && ir.routing.kind === "match" && ir.routing.match !== undefined) {
219
+ const tableLit = JSON.stringify(ir.routing.match, null, 2)
220
+ .split("\n")
221
+ .map((l) => ` ${l}`)
222
+ .join("\n");
223
+ routerBlock = `
224
+ const __routingTable: Record<string, ReadonlyArray<{ contains: string; to: string }>> =
225
+ ${tableLit};
226
+ builder.setRouting(({ input, lastRole }) => {
227
+ if (lastRole === undefined) return ${escapeJsonString(ir.entry)};
228
+ const rules = __routingTable[lastRole] ?? [];
229
+ for (const r of rules) {
230
+ if (input.includes(r.contains)) return r.to;
231
+ }
232
+ return lastRole;
233
+ });`;
234
+ }
235
+
236
+ return `// Generated by crewhaus. DO NOT EDIT.
237
+ // Source spec: ${ir.name} (target: crew, ir version: ${ir.version}, file: orchestrator.ts)
238
+ import { Crew, type RunnableCrew } from "@crewhaus/crew-orchestrator";
239
+ ${roleImports}
240
+
241
+ export function buildCrew(): RunnableCrew {
242
+ const builder = Crew()
243
+ .setName(${escapeJsonString(ir.name)})
244
+ ${adds}
245
+ .setEntry(${escapeJsonString(ir.entry)});${routerBlock}
246
+ return builder.compile();
247
+ }
248
+ `;
249
+ }
250
+
251
+ function roleVar(name: string): string {
252
+ return `__role_${safeFileName(name)}`;
253
+ }
254
+
255
+ // ---------------------------------------------------------------------------
256
+ // File: daemon.ts — entrypoint. Reads stdin, drives the crew, prints events.
257
+ // ---------------------------------------------------------------------------
258
+
259
+ function renderDaemon(ir: IrCrewV0): string {
260
+ const hasRules = ir.permissions.rules.length > 0;
261
+ const permImport = hasRules
262
+ ? `import { BUILTIN_DEFAULT_RULES } from "@crewhaus/permission-engine";\n`
263
+ : "";
264
+ const permField = renderPermissionsField(ir);
265
+ return `#!/usr/bin/env bun
266
+ // Generated by crewhaus. DO NOT EDIT.
267
+ // Source spec: ${ir.name} (target: crew, ir version: ${ir.version}, file: daemon.ts)
268
+ ${permImport}import { buildCrew } from "./orchestrator.js";
269
+
270
+ async function main(): Promise<void> {
271
+ const crew = buildCrew();
272
+ const input = await readAllStdin();
273
+ const trimmed = input.trim();
274
+ if (trimmed.length === 0) {
275
+ process.stderr.write("[crew] no input on stdin\\n");
276
+ process.exit(2);
277
+ }
278
+ const opts: Parameters<typeof crew.run>[1] = {${permField}
279
+ };
280
+ let lastFinalOutput = "";
281
+ try {
282
+ for await (const ev of crew.run(trimmed, opts)) {
283
+ process.stdout.write(\`\${JSON.stringify(ev)}\\n\`);
284
+ if (ev.kind === "crew_done") lastFinalOutput = ev.finalOutput;
285
+ }
286
+ } catch (err) {
287
+ process.stderr.write(\`[crew] error: \${(err as Error).message}\\n\`);
288
+ process.exit(1);
289
+ }
290
+ if (lastFinalOutput.length > 0) {
291
+ const PREVIEW_LIMIT = 200;
292
+ const preview =
293
+ lastFinalOutput.length > PREVIEW_LIMIT
294
+ ? \`\${lastFinalOutput.slice(0, PREVIEW_LIMIT)}… [preview truncated; full output (\${lastFinalOutput.length} chars) is on stdout in the crew_done event]\`
295
+ : lastFinalOutput;
296
+ process.stderr.write(\`[crew] final: \${preview}\\n\`);
297
+ }
298
+ }
299
+
300
+ async function readAllStdin(): Promise<string> {
301
+ if (process.stdin.isTTY) return "";
302
+ const chunks: Buffer[] = [];
303
+ for await (const chunk of process.stdin) {
304
+ chunks.push(chunk as Buffer);
305
+ }
306
+ return Buffer.concat(chunks).toString("utf-8");
307
+ }
308
+
309
+ main().catch((err) => {
310
+ process.stderr.write(\`[crew] fatal: \${(err as Error).message}\\n\`);
311
+ process.exit(1);
312
+ });
313
+ `;
314
+ }