@crewhaus/target-crew 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.
Files changed (2) hide show
  1. package/dist/index.js +374 -16
  2. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -77,7 +77,7 @@ export function emitCrew(ir, opts = {}) {
77
77
  .join(", ")})`);
78
78
  }
79
79
  const files = [
80
- { path: "orchestrator.ts", content: renderOrchestrator(ir) },
80
+ { path: "orchestrator.ts", content: renderOrchestrator(ir, entryRole) },
81
81
  { path: "daemon.ts", content: renderDaemon(ir) },
82
82
  ];
83
83
  for (const role of ir.roles) {
@@ -163,25 +163,248 @@ function renderFailureTaxonomyField(ir) {
163
163
  return "";
164
164
  return `\n failureTaxonomy: ${JSON.stringify(taxonomy)},`;
165
165
  }
166
+ /**
167
+ * Loop contract 0.4 (Batch A) — the crew-only orchestration ceilings
168
+ * (`limits.crew`) map onto crew-orchestrator's EXISTING RunOptions caps:
169
+ * `max_activations` → `maxActivations`, `refusal_depth` → `refusalDepth`,
170
+ * `max_a2a_depth` → `maxA2ADepth`. Each cap is emitted only when the spec
171
+ * declared it — the orchestrator owns the defaults (16 / 2 / 3) — so
172
+ * existing bundles stay byte-identical.
173
+ */
174
+ function renderCrewCapsFields(ir) {
175
+ const crew = ir.limits?.crew;
176
+ if (crew === undefined)
177
+ return "";
178
+ const pieces = [];
179
+ if (crew.maxActivations !== undefined) {
180
+ pieces.push(`\n maxActivations: ${crew.maxActivations},`);
181
+ }
182
+ if (crew.refusalDepth !== undefined) {
183
+ pieces.push(`\n refusalDepth: ${crew.refusalDepth},`);
184
+ }
185
+ if (crew.maxA2aDepth !== undefined) {
186
+ pieces.push(`\n maxA2ADepth: ${crew.maxA2aDepth},`);
187
+ }
188
+ return pieces.join("");
189
+ }
190
+ /**
191
+ * Loop contract 0.4 (Batch A) — the per-turn loop ceilings (top-level
192
+ * `limits:` minus the crew-only block above) ride `RunOptions.limits`; the
193
+ * orchestrator forwards them to EVERY role's runChatLoop — primary
194
+ * activations and inline A2A peer turns alike (`composeLoopTuning`). Only
195
+ * declared knobs are present — the runtime owns every default. Mirror:
196
+ * target-cli + target-channel-bot + target-managed render the same knobs
197
+ * (as direct runChatLoop fields — crew is the one shape that routes them
198
+ * through an orchestrator).
199
+ */
200
+ function renderLoopLimitsField(ir) {
201
+ const limits = ir.limits;
202
+ if (limits === undefined)
203
+ return "";
204
+ const loop = {
205
+ ...(limits.maxToolIterations !== undefined
206
+ ? { maxToolIterations: limits.maxToolIterations }
207
+ : {}),
208
+ ...(limits.maxConcurrentTools !== undefined
209
+ ? { maxConcurrentTools: limits.maxConcurrentTools }
210
+ : {}),
211
+ ...(limits.contextLimit !== undefined ? { contextLimit: limits.contextLimit } : {}),
212
+ ...(limits.deadlineMs !== undefined ? { deadlineMs: limits.deadlineMs } : {}),
213
+ ...(limits.turnTimeoutMs !== undefined ? { turnTimeoutMs: limits.turnTimeoutMs } : {}),
214
+ ...(limits.modelCallTimeoutMs !== undefined
215
+ ? { modelCallTimeoutMs: limits.modelCallTimeoutMs }
216
+ : {}),
217
+ ...(limits.loopDetection !== undefined ? { loopDetection: limits.loopDetection } : {}),
218
+ };
219
+ if (Object.keys(loop).length === 0)
220
+ return "";
221
+ return `\n limits: ${JSON.stringify(loop)},`;
222
+ }
223
+ /** Item 27 (Batch A extends it to crew) — run-level spend cap + degradation
224
+ * ladder. The orchestrator forwards it to every role's runChatLoop, so the
225
+ * always-on cost meter accrues the WHOLE crew run against one cap. Mirror:
226
+ * target-cli + target-channel-bot render the same field. */
227
+ function renderBudgetField(ir) {
228
+ if (ir.budget === undefined)
229
+ return "";
230
+ return `\n budget: ${JSON.stringify(ir.budget)},`;
231
+ }
232
+ /**
233
+ * Loop contract 0.4 (Batch A) — spec-declared lifecycle hooks (`hooks:`).
234
+ * IrHook is HookDef-shaped by contract (the spec ↔ hooks-engine cross-check
235
+ * test pins the event list), so codegen embeds the array as a literal on
236
+ * `RunOptions.hooks` and the orchestrator forwards it to every role's
237
+ * runChatLoop. The crew daemon discovers no settings.json hooks (unlike
238
+ * cli), so the spec list is the whole array; declaration order is preserved
239
+ * (hooks run in registration order). Absent/empty leaves bundles
240
+ * byte-identical.
241
+ */
242
+ function renderHooksField(ir) {
243
+ if (ir.hooks === undefined || ir.hooks.length === 0)
244
+ return "";
245
+ return `\n hooks: ${JSON.stringify(ir.hooks)},`;
246
+ }
247
+ /**
248
+ * Loop contract 0.4 (Batch A, G05) — spec-declared MCP servers, wired ONCE
249
+ * at daemon boot (the wire-once pattern: one shared McpHost, one
250
+ * registration pass) into a dedicated catalog whose tools every role
251
+ * receives through the orchestrator's crew-wide `extraTools`. The
252
+ * UNRESOLVED IrSecretRef-valued config is embedded and resolved at boot
253
+ * (mirror of target-cli + target-channel-bot's renderMcpServers; keep in
254
+ * sync). One deliberate divergence: `onRegister` logs to STDERR — the crew
255
+ * daemon's stdout is the JSON-per-line event stream and must stay
256
+ * machine-parseable.
257
+ */
258
+ function renderMcpServers(ir) {
259
+ const entries = Object.entries(ir.mcp_servers);
260
+ if (entries.length === 0) {
261
+ return { imports: [], bootBlock: "", hasAny: false };
262
+ }
263
+ const imports = [
264
+ `import { McpHost, resolveMcpServerConfig } from "@crewhaus/mcp-host";`,
265
+ `import { registerMcpServer } from "@crewhaus/tool-mcp";`,
266
+ ];
267
+ const addLines = entries
268
+ .map(([name, cfg]) => ` mcpHost.addServer(${escapeJsonString(name)}, resolveMcpServerConfig(${JSON.stringify(cfg)}, { name: ${escapeJsonString(name)} }));`)
269
+ .join("\n");
270
+ const registerLines = entries
271
+ .map(([name]) => ` registerMcpServer(mcpHost, ${escapeJsonString(name)}, __mcpCatalog, { onRegister: ({ fullName }) => process.stderr.write(\`[mcp] registered \${fullName}\\n\`) }),`)
272
+ .join("\n");
273
+ const bootBlock = `
274
+ // Loop contract 0.4 (Batch A, G05) — MCP servers, wired ONCE: every
275
+ // role's turns see the remote tools through the orchestrator's crew-wide
276
+ // extraTools; the daemon disconnects the shared host on shutdown.
277
+ const mcpHost = new McpHost();
278
+ ${addLines}
279
+ const __mcpCatalog = new ToolCatalog();
280
+ await Promise.all([
281
+ ${registerLines}
282
+ ]);
283
+ const __mcpTools = __mcpCatalog.list();`;
284
+ return { imports, bootBlock, hasAny: true };
285
+ }
166
286
  // ---------------------------------------------------------------------------
167
287
  // File: agent_<role>.ts — exports the role's RoleDefinition.
168
288
  // ---------------------------------------------------------------------------
289
+ /** Render one IrSubAgentDefinition as a TS object literal — mirrors
290
+ * target-cli + target-channel-bot; keep the three in sync. */
291
+ function renderSubAgentDef(d) {
292
+ const lines = [];
293
+ lines.push(`name: ${escapeJsonString(d.name)}`);
294
+ lines.push(`description: ${escapeJsonString(d.description)}`);
295
+ lines.push(`instructions: ${escapeJsonString(d.instructions)}`);
296
+ lines.push(`tools: ${JSON.stringify(d.tools)}`);
297
+ if (d.model !== undefined)
298
+ lines.push(`model: ${escapeJsonString(d.model)}`);
299
+ if (typeof d.permissions === "string") {
300
+ lines.push(`permissions: ${escapeJsonString(d.permissions)}`);
301
+ }
302
+ else {
303
+ lines.push(`permissions: { allow: ${JSON.stringify(d.permissions.allow)}, deny: ${JSON.stringify(d.permissions.deny)} }`);
304
+ }
305
+ lines.push(`inherit_bypass: ${d.inheritBypass}`);
306
+ return `{ ${lines.join(", ")} }`;
307
+ }
308
+ /**
309
+ * Loop contract 0.4 (Batch A) — render the per-role tuning fields onto the
310
+ * RoleDefinition literal, camelCase-mirroring the IR 1:1: `max_tokens` →
311
+ * `maxTokens` (model max OUTPUT tokens per activation) and `thinking` →
312
+ * `thinking` (extended-thinking selector; exactly one of `{ budgetTokens }`
313
+ * / `{ effort }` by spec construction — the orchestrator forwards it to the
314
+ * role's runChatLoop turns). Each field is emitted only when the spec
315
+ * declared it — the runtime owns every default — so existing bundles stay
316
+ * byte-identical. Mirror: target-cli + target-channel-bot render the same
317
+ * knobs on their agent blocks.
318
+ */
319
+ function renderRoleTuningFields(role) {
320
+ const pieces = [];
321
+ if (role.maxTokens !== undefined) {
322
+ pieces.push(`\n maxTokens: ${role.maxTokens},`);
323
+ }
324
+ if (role.thinking !== undefined) {
325
+ pieces.push(`\n thinking: ${JSON.stringify(role.thinking)},`);
326
+ }
327
+ return pieces.join("");
328
+ }
329
+ /**
330
+ * Loop contract 0.4 (Batch G, item 9 / G37) — render the per-role model-
331
+ * routing fields onto the role's `RoleDefinition` literal. The pooled
332
+ * pattern is adopted verbatim from the cli agent block
333
+ * (`@crewhaus/target-cli`'s `renderModelFailoverFields`), so a PolicyRouter
334
+ * decision per role shares the same `@crewhaus/routing-store` scoreboard the
335
+ * cli/pipeline shapes use — runtime-core owns the router; the orchestrator
336
+ * forwards the RoleDefinition's config into this role's `runChatLoop` turns
337
+ * (primary activations AND inline A2A peer turns) exactly as it already
338
+ * forwards `maxTokens`/`thinking`. The four fields are mutually exclusive in
339
+ * the spec (`model_pool` ⊥ `model_tiers` ⊥ `model_fallbacks`, with
340
+ * `circuit_breaker` riding `model_fallbacks`), so at most one clause fires
341
+ * per role. Model strings pass through `escapeJsonString` (user-controlled
342
+ * spec values in generated source); the breaker/tiers/pool blocks are
343
+ * validated numbers/strings/closed-literal unions safe to `JSON.stringify`.
344
+ * Empty when the role declares none, keeping pre-existing bundles
345
+ * byte-identical. Mirror: target-cli + target-channel-bot + target-managed
346
+ * render the same fields on their agent blocks — keep the four in sync.
347
+ */
348
+ function renderRoleModelFailoverFields(role) {
349
+ const pieces = [];
350
+ const fallbacks = role.modelFallbacks;
351
+ if (fallbacks !== undefined && fallbacks.length > 0) {
352
+ pieces.push(`\n modelFallbacks: [${fallbacks.map((m) => escapeJsonString(m)).join(", ")}],`);
353
+ }
354
+ if (role.circuitBreaker !== undefined) {
355
+ pieces.push(`\n circuitBreaker: ${JSON.stringify(role.circuitBreaker)},`);
356
+ }
357
+ if (role.modelTiers !== undefined) {
358
+ pieces.push(`\n modelTiers: ${JSON.stringify(role.modelTiers)},`);
359
+ }
360
+ if (role.modelPool !== undefined) {
361
+ pieces.push(`\n modelPool: ${JSON.stringify(role.modelPool)},`);
362
+ }
363
+ return pieces.join("");
364
+ }
169
365
  function renderRoleAgent(ir, role) {
170
366
  const { imports, inits, registrations } = resolveTools(role.tools, role.toolConfigs);
171
- const importBlock = imports.length > 0 ? `${imports.join("\n")}\n` : "";
367
+ const hasSubAgents = role.subAgents.length > 0;
368
+ // Section 13 (Batch A, G34) — the role's inline sub-agent definitions:
369
+ // rendered as a Map for the Task tool (createTaskTool resolves
370
+ // subagent_type against it) AND threaded onto the RoleDefinition so the
371
+ // orchestrator forwards them to this role's runChatLoop bridge alongside
372
+ // the daemon-injected spawnSubAgent.
373
+ const subAgentImports = hasSubAgents
374
+ ? [
375
+ `import type { SubAgentDefinition } from "@crewhaus/agent-context-isolation";`,
376
+ `import { createTaskTool } from "@crewhaus/tool-task";`,
377
+ ]
378
+ : [];
379
+ const importBlock = imports.length > 0 || subAgentImports.length > 0
380
+ ? `${[...subAgentImports, ...imports].join("\n")}\n`
381
+ : "";
172
382
  const initLines = inits.length > 0 ? `${inits.join("\n")}\n` : "";
173
- const toolsArrayLiteral = registrations.length > 0 ? `[${registrations.join(", ")}]` : "[]";
383
+ const subAgentEntries = role.subAgents
384
+ .map((d) => ` [${escapeJsonString(d.name)}, ${renderSubAgentDef(d)}],`)
385
+ .join("\n");
386
+ const subAgentBlock = hasSubAgents
387
+ ? `const __subAgents: ReadonlyMap<string, SubAgentDefinition> = new Map<string, SubAgentDefinition>([
388
+ ${subAgentEntries}
389
+ ]);
390
+ `
391
+ : "";
392
+ const toolRegistrations = hasSubAgents
393
+ ? [...registrations, "createTaskTool({ subAgents: __subAgents })"]
394
+ : registrations;
395
+ const toolsArrayLiteral = toolRegistrations.length > 0 ? `[${toolRegistrations.join(", ")}]` : "[]";
396
+ const subAgentsField = hasSubAgents ? "\n subAgents: __subAgents," : "";
174
397
  return `// Generated by crewhaus. DO NOT EDIT.
175
398
  // Source spec: ${escapeJsonString(ir.name)} (target: crew, ir version: ${ir.version}, role: ${escapeJsonString(role.name)})
176
399
  ${importBlock}import type { RoleDefinition } from "@crewhaus/crew-orchestrator";
177
400
 
178
- ${initLines}
401
+ ${initLines}${subAgentBlock}
179
402
  export const role: { name: string; def: RoleDefinition } = {
180
403
  name: ${escapeJsonString(role.name)},
181
404
  def: {
182
405
  model: ${escapeJsonString(role.model)},
183
- instructions: ${escapeJsonString(role.instructions)},
184
- tools: ${toolsArrayLiteral},
406
+ instructions: ${escapeJsonString(role.instructions)},${renderRoleTuningFields(role)}${renderRoleModelFailoverFields(role)}
407
+ tools: ${toolsArrayLiteral},${subAgentsField}
185
408
  },
186
409
  };
187
410
  `;
@@ -189,14 +412,110 @@ export const role: { name: string; def: RoleDefinition } = {
189
412
  // ---------------------------------------------------------------------------
190
413
  // File: orchestrator.ts — composes Crew() from roles + entry + routing.
191
414
  // ---------------------------------------------------------------------------
192
- function renderOrchestrator(ir) {
415
+ /** Emit-time cap on the roster excerpt of each role's instructions inside
416
+ * the llm-router classify prompt — the classify turn must stay small. */
417
+ const LLM_ROUTER_DESCRIPTION_MAX_CHARS = 240;
418
+ /** Runtime cap (rendered into the bundle) on the finishing role's output
419
+ * fed to the classify turn. The TAIL is kept: routing signals ("DONE",
420
+ * "needs review", verdicts) conventionally close an output. */
421
+ const LLM_ROUTER_INPUT_MAX_CHARS = 2000;
422
+ function llmRouterDescription(instructions) {
423
+ return instructions.length > LLM_ROUTER_DESCRIPTION_MAX_CHARS
424
+ ? `${instructions.slice(0, LLM_ROUTER_DESCRIPTION_MAX_CHARS)}…`
425
+ : instructions;
426
+ }
427
+ /**
428
+ * Loop contract 0.4 (Batch A, G08) — `routing.kind: "llm"`: render a
429
+ * model-backed router into the generated orchestrator. One small
430
+ * `runChatLoop` classify turn runs after every role_end: it sees the role
431
+ * roster (names + emit-time-truncated instruction excerpts) plus the tail
432
+ * of the finishing role's output and must answer with EXACTLY one role
433
+ * name or DONE — the exact-token output contract is what keeps the
434
+ * decision stable at any sampling temperature. DONE (or re-picking the
435
+ * finishing role) terminates the crew; an unparseable reply falls back to
436
+ * the entry role. The turn runs on the entry role's model in its own
437
+ * session (`<name> (llm-router)`) so the crew transcript stays clean, and
438
+ * it rides the run's session root + `_adapter` test seam via the
439
+ * orchestrator's RouterArgs passthroughs.
440
+ */
441
+ function renderLlmRouter(ir, entryRole) {
442
+ const rosterEntries = ir.roles
443
+ .map((r) => ` { name: ${escapeJsonString(r.name)}, description: ${escapeJsonString(llmRouterDescription(r.instructions))} },`)
444
+ .join("\n");
445
+ const classifierInstructions = "You are the routing classifier for a multi-role agent crew. After a role finishes its turn you decide who acts next. Respond with EXACTLY one word: the name of the next role, or DONE when the crew's work is complete. No punctuation, no explanation — the exact-match contract keeps routing deterministic at any sampling temperature.";
446
+ const prelude = `
447
+ // Loop contract 0.4 (Batch A, G08) — routing.kind "llm": the roster the
448
+ // classify turn picks from (name + an instructions excerpt truncated at
449
+ // compile time to keep the classify prompt small).
450
+ const __roleRoster: ReadonlyArray<{ name: string; description: string }> = [
451
+ ${rosterEntries}
452
+ ];
453
+ const __roleNames: ReadonlyArray<string> = __roleRoster.map((r) => r.name);
454
+
455
+ /**
456
+ * Parse the classifier's reply into the next role. Priority ladder: exact
457
+ * role-name match (quotes/punctuation stripped) → that role; exact DONE →
458
+ * the finishing role (re-picking it terminates the crew); exactly one
459
+ * roster name mentioned → that role; DONE mentioned → the finishing role;
460
+ * anything else is unparseable and falls back to the entry role.
461
+ */
462
+ function __pickNextRole(reply: string, lastRole: string): string {
463
+ const text = reply.trim().toLowerCase();
464
+ const exact = text.replace(/^["'\`\\s]+|["'\`.!\\s]+$/g, "");
465
+ for (const name of __roleNames) {
466
+ if (name.toLowerCase() === exact) return name;
467
+ }
468
+ if (exact === "done") return lastRole;
469
+ const mentioned = __roleNames.filter((name) => text.includes(name.toLowerCase()));
470
+ const only = mentioned[0];
471
+ if (mentioned.length === 1 && only !== undefined) return only;
472
+ if (/\\bdone\\b/.test(text)) return lastRole;
473
+ return ${escapeJsonString(ir.entry)};
474
+ }
475
+ `;
476
+ const routerBlock = `
477
+ // Loop contract 0.4 (Batch A, G08) — model-backed routing: one small
478
+ // classify turn per role_end picks the next role (see __pickNextRole for
479
+ // the parse ladder). Temperature-stable by construction: exact-token
480
+ // output contract + tail-anchored output excerpt.
481
+ builder.setRouting(async ({ input, lastRole, sessionRootDir, _adapter }) => {
482
+ if (lastRole === undefined) return ${escapeJsonString(ir.entry)};
483
+ const roster = __roleRoster.map((r) => \`- \${r.name}: \${r.description}\`).join("\\n");
484
+ const excerpt =
485
+ input.length > ${LLM_ROUTER_INPUT_MAX_CHARS}
486
+ ? \`…\${input.slice(-${LLM_ROUTER_INPUT_MAX_CHARS})}\`
487
+ : input;
488
+ const reply = await runChatLoop({
489
+ model: ${escapeJsonString(entryRole.model)},
490
+ instructions: ${escapeJsonString(classifierInstructions)},
491
+ sessionName: ${escapeJsonString(`${ir.name} (llm-router)`)},
492
+ sessionTarget: "crew",
493
+ ...(sessionRootDir !== undefined ? { sessionRootDir } : {}),
494
+ singleTurn: true,
495
+ installSigintHandler: false,
496
+ maxTokens: 128,
497
+ seedMessages: [
498
+ {
499
+ role: "user",
500
+ content: \`Roles:\\n\${roster}\\n\\nRole that just finished: \${lastRole}\\n\\nIts output:\\n\${excerpt}\\n\\nWhich role acts next? Answer with exactly one of: \${__roleNames.join(", ")}, or DONE.\`,
501
+ },
502
+ ],
503
+ ...(_adapter !== undefined ? { _adapter } : {}),
504
+ });
505
+ return __pickNextRole(reply, lastRole);
506
+ });`;
507
+ return { prelude, routerBlock };
508
+ }
509
+ function renderOrchestrator(ir, entryRole) {
193
510
  const roleImports = ir.roles
194
511
  .map((r) => `import { role as ${roleVar(r.name)} } from "./agent_${safeFileName(r.name)}.js";`)
195
512
  .join("\n");
196
513
  const adds = ir.roles
197
514
  .map((r) => ` .addRole(${roleVar(r.name)}.name, ${roleVar(r.name)}.def)`)
198
515
  .join("\n");
516
+ let prelude = "";
199
517
  let routerBlock = "";
518
+ let runtimeImport = "";
200
519
  if (ir.routing && ir.routing.kind === "match" && ir.routing.match !== undefined) {
201
520
  const tableLit = JSON.stringify(ir.routing.match, null, 2)
202
521
  .split("\n")
@@ -214,11 +533,17 @@ ${tableLit};
214
533
  return lastRole;
215
534
  });`;
216
535
  }
536
+ else if (ir.routing && ir.routing.kind === "llm") {
537
+ const llm = renderLlmRouter(ir, entryRole);
538
+ prelude = llm.prelude;
539
+ routerBlock = llm.routerBlock;
540
+ runtimeImport = `import { runChatLoop } from "@crewhaus/runtime-core";\n`;
541
+ }
217
542
  return `// Generated by crewhaus. DO NOT EDIT.
218
543
  // Source spec: ${escapeJsonString(ir.name)} (target: crew, ir version: ${ir.version}, file: orchestrator.ts)
219
544
  import { Crew, type RunnableCrew } from "@crewhaus/crew-orchestrator";
220
- ${roleImports}
221
-
545
+ ${runtimeImport}${roleImports}
546
+ ${prelude}
222
547
  export function buildCrew(): RunnableCrew {
223
548
  const builder = Crew()
224
549
  .setName(${escapeJsonString(ir.name)})
@@ -265,11 +590,34 @@ function renderDaemon(ir) {
265
590
  : "";
266
591
  const permField = renderPermissionsField(ir);
267
592
  const taxonomyField = renderFailureTaxonomyField(ir);
593
+ // Loop contract 0.4 (Batch A) — the new crew.run knobs.
594
+ const crewCapsFields = renderCrewCapsFields(ir);
595
+ const loopLimitsField = renderLoopLimitsField(ir);
596
+ const budgetField = renderBudgetField(ir);
597
+ const hooksField = renderHooksField(ir);
268
598
  const fabric = memoryFabric(ir);
599
+ const mcp = renderMcpServers(ir);
600
+ // Section 13 (Batch A, G34) — when any role declares sub-agents, inject
601
+ // the spawner once at the run level; the orchestrator stamps it (plus the
602
+ // per-role subAgents map) onto each role's runChatLoop bridge.
603
+ const anySubAgents = ir.roles.some((r) => r.subAgents.length > 0);
604
+ const spawnImport = anySubAgents
605
+ ? `import { spawnSubAgent } from "@crewhaus/sub-agent-spawner";\n`
606
+ : "";
607
+ const spawnField = anySubAgents ? "\n spawnSubAgent," : "";
608
+ // One tool-catalog import line serves both consumers: the MCP wire-once
609
+ // catalog (value) and the memory fabric's collector typing (type).
610
+ const toolCatalogImport = mcp.hasAny && fabric.wired
611
+ ? `import { ToolCatalog, type RegisteredTool } from "@crewhaus/tool-catalog";\n`
612
+ : mcp.hasAny
613
+ ? `import { ToolCatalog } from "@crewhaus/tool-catalog";\n`
614
+ : fabric.wired
615
+ ? `import type { RegisteredTool } from "@crewhaus/tool-catalog";\n`
616
+ : "";
617
+ const mcpImport = mcp.hasAny ? `${mcp.imports.join("\n")}\n` : "";
269
618
  const memImport = fabric.wired
270
619
  ? `import { wireMemory } from "@crewhaus/memory-service";
271
620
  import { createSkillTool } from "@crewhaus/skills-registry";
272
- import type { RegisteredTool } from "@crewhaus/tool-catalog";
273
621
  `
274
622
  : "";
275
623
  const memBoot = fabric.wired
@@ -285,13 +633,23 @@ import type { RegisteredTool } from "@crewhaus/tool-catalog";
285
633
  const __skills = __memWired.options.skills ?? [];
286
634
  if (__skills.length > 0) __memTools.push(createSkillTool(__skills));`
287
635
  : "";
636
+ // Crew-wide extra tools: user-declared MCP tools first (explicit choices
637
+ // win), then the memory fabric's.
638
+ const extraToolsField = mcp.hasAny && fabric.wired
639
+ ? "\n extraTools: [...__mcpTools, ...__memTools],"
640
+ : mcp.hasAny
641
+ ? "\n extraTools: __mcpTools,"
642
+ : fabric.wired
643
+ ? "\n extraTools: __memTools,"
644
+ : "";
288
645
  const memOptsFields = fabric.wired
289
646
  ? `
290
- extraTools: __memTools,
291
647
  ...(__memWired.options.memory !== undefined ? { memory: __memWired.options.memory } : {}),
292
648
  ...(__memWired.options.continuity !== undefined ? { continuity: __memWired.options.continuity } : {}),
293
649
  ...(__skills.length > 0 ? { skills: __skills } : {}),`
294
650
  : "";
651
+ const mcpShutdownOk = mcp.hasAny ? "\n await mcpHost.disconnectAll();" : "";
652
+ const mcpShutdownErr = mcp.hasAny ? "\n await mcpHost.disconnectAll().catch(() => {});" : "";
295
653
  // v0.3.0 Goal 3 — thredz is spec-carried on this shape but not emit-wired
296
654
  // in this release (the one-knob backend flip ships on cli). Surface it,
297
655
  // 0.2.3-style, so nobody wonders why their wiki stayed local.
@@ -302,7 +660,7 @@ import type { RegisteredTool } from "@crewhaus/tool-catalog";
302
660
  // Generated by crewhaus. DO NOT EDIT.
303
661
  // Source spec: ${escapeJsonString(ir.name)} (target: crew, ir version: ${ir.version}, file: daemon.ts)
304
662
  ${thredzWarning}import { formatRunFailure, toFailureReport } from "@crewhaus/errors";
305
- ${permImport}${memImport}import { buildCrew } from "./orchestrator.js";
663
+ ${permImport}${memImport}${mcpImport}${spawnImport}${toolCatalogImport}import { buildCrew } from "./orchestrator.js";
306
664
 
307
665
  async function main(): Promise<void> {
308
666
  const crew = buildCrew();
@@ -311,8 +669,8 @@ async function main(): Promise<void> {
311
669
  if (trimmed.length === 0) {
312
670
  process.stderr.write("[crew] no input on stdin\\n");
313
671
  process.exit(2);
314
- }${memBoot}
315
- const opts: Parameters<typeof crew.run>[1] = {${permField}${taxonomyField}${memOptsFields}
672
+ }${mcp.bootBlock}${memBoot}
673
+ const opts: Parameters<typeof crew.run>[1] = {${permField}${taxonomyField}${crewCapsFields}${loopLimitsField}${budgetField}${hooksField}${spawnField}${extraToolsField}${memOptsFields}
316
674
  };
317
675
  let lastFinalOutput = "";
318
676
  try {
@@ -325,9 +683,9 @@ async function main(): Promise<void> {
325
683
  // for a RunFailedError, generic otherwise) and exit with its coded
326
684
  // status instead of the bare "[crew] error:" line + exit 1.
327
685
  const __report = toFailureReport(err);
328
- process.stderr.write(\`\${formatRunFailure(__report, { prefix: "[crew]" })}\\n\`);
686
+ process.stderr.write(\`\${formatRunFailure(__report, { prefix: "[crew]" })}\\n\`);${mcpShutdownErr}
329
687
  process.exit(__report.exitCode);
330
- }
688
+ }${mcpShutdownOk}
331
689
  if (lastFinalOutput.length > 0) {
332
690
  const PREVIEW_LIMIT = 200;
333
691
  const preview =
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewhaus/target-crew",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "Codegen for the CRW target — emits a daemon + per-role agent files driven by crew-orchestrator (Section 22)",
6
6
  "main": "dist/index.js",
@@ -15,10 +15,10 @@
15
15
  "test": "bun test src"
16
16
  },
17
17
  "dependencies": {
18
- "@crewhaus/errors": "0.3.1",
19
- "@crewhaus/infra-utils": "0.3.1",
20
- "@crewhaus/ir": "0.3.1",
21
- "@crewhaus/memory-service": "0.3.1"
18
+ "@crewhaus/errors": "0.4.0",
19
+ "@crewhaus/infra-utils": "0.4.0",
20
+ "@crewhaus/ir": "0.4.0",
21
+ "@crewhaus/memory-service": "0.4.0"
22
22
  },
23
23
  "license": "Apache-2.0",
24
24
  "author": {