@crewhaus/tool-task 0.7.0 → 0.8.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ CrewHaus Factory
2
+ Copyright 2026 Max Meier
3
+
4
+ This product includes software developed by Max Meier
5
+ (operating as StudioMax — https://studiomax.io) and contributors.
6
+
7
+ The CrewHaus name and logo are trademarks of Max Meier. See
8
+ https://github.com/crewhaus/factory/blob/main/TRADEMARK.md for the
9
+ use-of-marks policy.
package/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # @crewhaus/tool-task
2
+
3
+ Task(description, prompt, subagent_type?) tool — spawns a sub-agent and returns its final message (Section 13)
4
+
5
+ Part of [CrewHaus](https://github.com/crewhaus/factory). Most people install the CLI (`npm install -g crewhaus`) rather than this package.
6
+
7
+ Which tools a spec can turn on, and how: [tools reference](https://github.com/crewhaus/docs/blob/main/TOOLS-REFERENCE.md).
8
+
9
+ Requires [Bun](https://bun.sh) `>=1.3.14`; plain Node is not supported.
10
+
11
+ [Source](https://github.com/crewhaus/factory/tree/main/packages/tool-task)
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type SubAgentDefinition, type SubAgentFailure } from "@crewhaus/agent-context-isolation";
2
2
  import { CrewhausError } from "@crewhaus/errors";
3
- import type { RegisteredTool } from "@crewhaus/tool-catalog";
3
+ import { type RegisteredTool } from "@crewhaus/tool-catalog";
4
4
  import { z } from "zod";
5
5
  export declare class SubAgentResolutionError extends CrewhausError {
6
6
  readonly name = "SubAgentResolutionError";
package/dist/index.js CHANGED
@@ -14,7 +14,12 @@
14
14
  * 1. `opts.subAgents.get(name)` — inline spec map (codegen-supplied).
15
15
  * 2. `<opts.subAgentDir or cwd/.crewhaus/sub-agents>/<name>.md` — frontmatter
16
16
  * file on disk. Format mirrors SKILL.md: leading `---` YAML block, body
17
- * becomes `instructions`.
17
+ * becomes `instructions`. Any agent with a write tool can put a file
18
+ * there, so a definition from disk can only NARROW: its permissions
19
+ * meet the parent's, its pool candidates carry no tool_config, it runs
20
+ * only on models the spec already names (a model id can carry an
21
+ * endpoint), and the file is read without following a link or opening
22
+ * a FIFO planted in its place.
18
23
  * 3. Built-in `general-purpose` fallback.
19
24
  *
20
25
  * Concurrency: a Task dispatch runs in parallel with its siblings ONLY
@@ -38,12 +43,14 @@
38
43
  * occurs when callers wire `Task` into a `runChatLoop` invocation that
39
44
  * doesn't pass `spawnSubAgent`.
40
45
  */
41
- import { existsSync, readFileSync } from "node:fs";
42
46
  import { join } from "node:path";
43
47
  import { projectParentHandle, subAgentProfileAllowlist, } from "@crewhaus/agent-context-isolation";
44
48
  import { CrewhausError } from "@crewhaus/errors";
45
- import { resolveChildPermissions } from "@crewhaus/sub-agent-permission-inheritance";
49
+ import { resolveChildPermissions, resolveChildPermissionsNarrowOnly, } from "@crewhaus/sub-agent-permission-inheritance";
46
50
  import { buildTool } from "@crewhaus/tool-builder";
51
+ import { toolListEntryNames } from "@crewhaus/tool-catalog";
52
+ import { builtinKeyForName, expandToolSelectors, registeredToolName, } from "@crewhaus/tool-categories";
53
+ import { openForReadSync } from "@crewhaus/tool-safety/fs";
47
54
  import { parse as parseYaml } from "yaml";
48
55
  import { z } from "zod";
49
56
  export class SubAgentResolutionError extends CrewhausError {
@@ -128,7 +135,9 @@ const FRONTMATTER_TIER_ROUTING = z
128
135
  * circuit_breaker? }` — the already-resolved shape the compiler produces for a
129
136
  * spec-declared sub-agent. `model_pool` is validated for its routing identity
130
137
  * (`candidates[].{model, tags}`, `policy`) and otherwise passed through: the
131
- * runtime owns the per-candidate settings grammar.
138
+ * runtime owns the per-candidate settings grammar. The Task tool then keeps
139
+ * only the candidate keys {@link DISK_CANDIDATE_KEYS} allows, because a file
140
+ * read from the sub-agents directory may have been written by the model.
132
141
  */
133
142
  const FRONTMATTER_SCHEMA = z.object({
134
143
  name: z.string().min(1),
@@ -275,12 +284,29 @@ export function parseSubAgentFile(content, fallbackName) {
275
284
  };
276
285
  return def;
277
286
  }
287
+ /** A definition is a page of prose; anything past this is not one. */
288
+ const SUB_AGENT_FILE_MAX_BYTES = 256 * 1024;
289
+ /**
290
+ * The file is read contained to the directory, never through a symlink at
291
+ * the leaf, with a FIFO refused before it is opened and the size capped.
292
+ * The directory is one any agent with a write tool can populate: `<name>.md`
293
+ * linked to a file outside it used to be read and handed to a child as its
294
+ * instructions, and a FIFO there blocked the event loop for every session.
295
+ */
278
296
  function loadSubAgentFromDisk(name, dir) {
279
- const filePath = join(dir, `${name}.md`);
280
- if (!existsSync(filePath))
281
- return null;
282
- const content = readFileSync(filePath, "utf-8");
283
- return parseSubAgentFile(content, name);
297
+ const read = openForReadSync(dir, `${name}.md`, {
298
+ maxBytes: SUB_AGENT_FILE_MAX_BYTES,
299
+ followLeafSymlink: false,
300
+ });
301
+ if (!read.ok) {
302
+ if (read.code === "not-found")
303
+ return null;
304
+ throw new SubAgentResolutionError(`sub-agent "${name}" in ${dir} was not read: ${read.reason}`);
305
+ }
306
+ if (read.truncated) {
307
+ throw new SubAgentResolutionError(`sub-agent "${name}" in ${dir} is larger than ${SUB_AGENT_FILE_MAX_BYTES} bytes, so it was not read`);
308
+ }
309
+ return parseSubAgentFile(read.text, name);
284
310
  }
285
311
  /**
286
312
  * `subagent_type` is a model-filled tool argument and model output is
@@ -302,11 +328,20 @@ function isUnsafeSubAgentName(name) {
302
328
  }
303
329
  /** Resolve a sub-agent name to a definition using the documented order. */
304
330
  export function resolveSubAgentDefinition(name, opts) {
331
+ return resolveSubAgent(name, opts).def;
332
+ }
333
+ /**
334
+ * The definition AND where it came from. A definition read from the
335
+ * sub-agents directory is untrusted: any agent that can write a file can
336
+ * put one there mid-run, so its permissions may only narrow the parent's
337
+ * (security-1#1). The inline spec map and the built-in are operator-written.
338
+ */
339
+ function resolveSubAgent(name, opts) {
305
340
  const resolveName = name ?? "general-purpose";
306
341
  if (opts.subAgents !== undefined) {
307
342
  const inline = opts.subAgents.get(resolveName);
308
343
  if (inline !== undefined)
309
- return inline;
344
+ return { def: inline, fromDisk: false };
310
345
  }
311
346
  // Guard the disk lookup against path traversal (the inline map above is an
312
347
  // exact-key lookup and is intentionally not gated).
@@ -316,9 +351,9 @@ export function resolveSubAgentDefinition(name, opts) {
316
351
  const dir = opts.subAgentDir ?? join(process.cwd(), ".crewhaus", "sub-agents");
317
352
  const onDisk = loadSubAgentFromDisk(resolveName, dir);
318
353
  if (onDisk !== null)
319
- return onDisk;
354
+ return { def: onDisk, fromDisk: true };
320
355
  if (resolveName === "general-purpose")
321
- return BUILTIN_GENERAL_PURPOSE;
356
+ return { def: BUILTIN_GENERAL_PURPOSE, fromDisk: false };
322
357
  throw new SubAgentResolutionError(`unknown subagent_type "${resolveName}" — not in spec sub_agents map, not on disk at ${dir}, and no built-in by that name`);
323
358
  }
324
359
  /**
@@ -326,15 +361,296 @@ export function resolveSubAgentDefinition(name, opts) {
326
361
  * tool-name allowlist on the definition. Undefined `def.tools` (with
327
362
  * `permissions: "inherit"`) → the child inherits the parent's full
328
363
  * catalog. Undefined `def.tools` with any other permission mode → empty
329
- * child catalog (the user has implicitly opted out).
364
+ * child catalog (the user has implicitly opted out). An MCP tool may be
365
+ * listed by its pre-0.7.1 spelling (`<server>__<tool>`).
330
366
  */
331
367
  function buildChildCatalog(parentTools, def) {
332
368
  const allowed = def.tools;
333
369
  if (allowed === undefined) {
334
370
  return def.permissions === undefined || def.permissions === "inherit" ? parentTools : [];
335
371
  }
336
- const allowlist = new Set(allowed);
337
- return parentTools.filter((t) => allowlist.has(t.name));
372
+ // A spec key (`read`) names the same tool as its registered name (`Read`);
373
+ // the parent catalog carries registered names, so map keys first. Before
374
+ // this, a definition written with spec keys — the documented spelling for
375
+ // every other tools: list — gave the child no tools at all. An MCP entry may
376
+ // still use the pre-0.7.1 `<server>__<tool>` spelling (toolListEntryNames).
377
+ return parentTools.filter((t) => allowed.some((entry) => toolListEntryNames(registeredToolName(entry) ?? entry, t.name)));
378
+ }
379
+ /**
380
+ * The definition with its `tools` mapped to registered names (`read` → `Read`).
381
+ *
382
+ * A definition from disk never passed through the compiler, so its list is
383
+ * also expanded here the way the compiler expands a spec's: a category
384
+ * (`all-git`) or an exclusion (`-gitPush`) becomes the tool keys it names,
385
+ * and a builtin key is matched without regard to case (`gitstatus`), as
386
+ * `builtinKeyForName` does. Before this, either spelling gave the child no
387
+ * tools at all, silently. A bad category throws the compiler's own
388
+ * `ToolCategoryError`, which the Task call reports.
389
+ */
390
+ function withRegisteredToolNames(def, fromDisk) {
391
+ if (def.tools === undefined)
392
+ return def;
393
+ const listed = fromDisk ? expandToolSelectors(def.tools).tools : def.tools;
394
+ const tools = listed.map((n) => registeredToolName(n) ??
395
+ (fromDisk ? registeredToolName(builtinKeyForName(n) ?? n) : undefined) ??
396
+ n);
397
+ if (tools.length !== def.tools.length)
398
+ return { ...def, tools };
399
+ // Already canonical (every spec-declared definition is, since lowering maps
400
+ // it): hand back the same object.
401
+ return tools.every((n, i) => n === def.tools?.[i]) ? def : { ...def, tools };
402
+ }
403
+ /** Definitions whose ignored allow list has already been reported. */
404
+ const reportedIgnoredAllows = new Set();
405
+ /**
406
+ * The `model_pool` candidate keys a definition read from `.crewhaus/sub-agents`
407
+ * keeps. Every key of the candidate type is decided here — this mapped type
408
+ * stops compiling when the IR gains one — and any other key in the file is
409
+ * dropped. `toolConfigs` is not kept: a candidate's block REPLACES the
410
+ * operator's `tool_config` for every call that candidate serves (an http
411
+ * allow-list, a webhook target) and reads `$VAR`s from the operator's
412
+ * environment, so a file the model could have written must not set it. The
413
+ * rest can only narrow (`tools`, `permissions`, `rateLimits`, `costCapUsdMicros`)
414
+ * or pick what the file could pick anyway with `model:`.
415
+ */
416
+ const DISK_CANDIDATE_KEYS = {
417
+ profile: true,
418
+ model: true,
419
+ tags: true,
420
+ enabled: true,
421
+ thinking: true,
422
+ maxTokens: true,
423
+ temperature: true,
424
+ modelCallTimeoutMs: true,
425
+ overlay: true,
426
+ tools: true,
427
+ toolConfigs: false,
428
+ permissions: true,
429
+ rateLimits: true,
430
+ caching: true,
431
+ costCapUsdMicros: true,
432
+ requires: true,
433
+ capabilities: true,
434
+ fallbacks: true,
435
+ circuitBreaker: true,
436
+ };
437
+ /**
438
+ * security — a definition on disk keeps only {@link DISK_CANDIDATE_KEYS} on
439
+ * each pool candidate. Returns the refused keys it found, to report.
440
+ */
441
+ function narrowDiskModelPool(def) {
442
+ const pool = def.modelPool;
443
+ if (pool === undefined)
444
+ return { def, refused: [] };
445
+ const refused = new Set();
446
+ let changed = false;
447
+ const candidates = pool.candidates.map((candidate) => {
448
+ const kept = {};
449
+ for (const [key, value] of Object.entries(candidate)) {
450
+ const decided = Object.hasOwn(DISK_CANDIDATE_KEYS, key)
451
+ ? DISK_CANDIDATE_KEYS[key]
452
+ : undefined;
453
+ if (decided === true) {
454
+ kept[key] = value;
455
+ continue;
456
+ }
457
+ changed = true;
458
+ if (decided === false)
459
+ refused.add(key);
460
+ }
461
+ return kept;
462
+ });
463
+ if (!changed)
464
+ return { def, refused: [] };
465
+ return { def: { ...def, modelPool: { ...pool, candidates } }, refused: [...refused] };
466
+ }
467
+ /** Definitions whose refused model_pool keys have already been reported. */
468
+ const reportedRefusedPoolKeys = new Set();
469
+ /**
470
+ * The model strings a pool's `strategy` block names (`guide.model`,
471
+ * `shadow.candidate`, `shadow.gradeWith`, `committee.judge`). A pool from
472
+ * disk is passed through unvalidated below `candidates`, so a slot may hold
473
+ * anything: it is returned as found, and the caller refuses a non-string.
474
+ */
475
+ function strategyModelSlots(strategy) {
476
+ if (typeof strategy !== "object" || strategy === null)
477
+ return [strategy];
478
+ const s = strategy;
479
+ const field = (block, key) => typeof block === "object" && block !== null
480
+ ? block[key]
481
+ : undefined;
482
+ return [
483
+ field(s["guide"], "model"),
484
+ field(s["shadow"], "candidate"),
485
+ field(s["shadow"], "gradeWith"),
486
+ field(s["committee"], "judge"),
487
+ ].filter((v) => v !== undefined);
488
+ }
489
+ /**
490
+ * security — a disk definition's pool keeps only models the spec names, in
491
+ * every slot the runtime can call: each candidate's `model` (a candidate on
492
+ * another model is removed) and its `fallbacks` (the runtime builds a
493
+ * failover chain from them, and a file-chosen breaker threshold of 1 turns
494
+ * one transient error into every call going to the fallback), and the
495
+ * pool-level `classifier` and `strategy` blocks, which name models of their
496
+ * own. Returns the same object when nothing was narrowed, and undefined when
497
+ * no candidate is left.
498
+ */
499
+ function narrowPoolModels(pool, ok) {
500
+ let changed = false;
501
+ const candidates = [];
502
+ for (const candidate of pool.candidates) {
503
+ if (!ok(candidate.model)) {
504
+ changed = true;
505
+ continue;
506
+ }
507
+ const fallbacks = candidate.fallbacks;
508
+ if (fallbacks === undefined) {
509
+ candidates.push(candidate);
510
+ continue;
511
+ }
512
+ const kept = Array.isArray(fallbacks)
513
+ ? fallbacks.filter((m) => typeof m === "string" && ok(m))
514
+ : [];
515
+ if (Array.isArray(fallbacks) && kept.length === fallbacks.length) {
516
+ candidates.push(candidate);
517
+ continue;
518
+ }
519
+ changed = true;
520
+ const { fallbacks: _dropped, ...rest } = candidate;
521
+ candidates.push(kept.length > 0 ? { ...rest, fallbacks: kept } : rest);
522
+ }
523
+ if (candidates.length === 0)
524
+ return undefined;
525
+ const { classifier, strategy, ...base } = pool;
526
+ const classifierModel = classifier?.model;
527
+ const keepClassifier = classifier === undefined || (typeof classifierModel === "string" && ok(classifierModel));
528
+ const keepStrategy = strategy === undefined ||
529
+ strategyModelSlots(strategy).every((m) => typeof m === "string" && ok(m));
530
+ if (!changed && keepClassifier && keepStrategy)
531
+ return pool;
532
+ return {
533
+ ...base,
534
+ candidates,
535
+ ...(keepClassifier && classifier !== undefined ? { classifier } : {}),
536
+ ...(keepStrategy && strategy !== undefined ? { strategy } : {}),
537
+ };
538
+ }
539
+ /**
540
+ * Every model the operator's spec names for this Task tool: every model the
541
+ * parent run was configured with (its primary, fallbacks, tiers, pool
542
+ * candidates and their fallbacks, compaction and budget-degrade models — the
543
+ * runtime puts them on the bridge as `specModels`), the arm serving the
544
+ * parent right now, and every model an inline (spec) definition can run on.
545
+ * Exact strings: `vertex/claude-x` and `claude-x` reach different endpoints,
546
+ * and so do two `local/…@url` strings.
547
+ */
548
+ function declaredModels(bridge, subAgents) {
549
+ const out = new Set([bridge.model, ...(bridge.specModels ?? [])]);
550
+ if (bridge.routing?.served.model !== undefined)
551
+ out.add(bridge.routing.served.model);
552
+ for (const def of subAgents?.values() ?? []) {
553
+ if (def.model !== undefined)
554
+ out.add(def.model);
555
+ for (const m of def.modelFallbacks ?? [])
556
+ out.add(m);
557
+ if (def.modelTiers !== undefined) {
558
+ out.add(def.modelTiers.fast);
559
+ out.add(def.modelTiers.default);
560
+ }
561
+ for (const c of def.modelPool?.candidates ?? []) {
562
+ out.add(c.model);
563
+ for (const m of c.fallbacks ?? [])
564
+ out.add(m);
565
+ }
566
+ for (const o of def.allowedProfiles ?? []) {
567
+ out.add(o.model);
568
+ for (const m of o.modelFallbacks ?? [])
569
+ out.add(m);
570
+ }
571
+ }
572
+ return out;
573
+ }
574
+ /**
575
+ * security — a definition on disk may run only on models the spec already
576
+ * names ({@link declaredModels}). A model id can carry an endpoint
577
+ * (`local/<model>@<url>`), so a file the agent wrote could otherwise send the
578
+ * child's whole conversation — its prompt and every tool result it reads —
579
+ * to a host of its choosing, or pick a model the operator never agreed to pay
580
+ * for; 0.6.0 §7.7 already refuses the second for the Task `profile` argument.
581
+ * Anything else is dropped, and the child runs on the parent's model.
582
+ * Returns the fields it dropped, to report — never the model strings, which
583
+ * can carry a URL.
584
+ */
585
+ function narrowDiskModels(def, declared) {
586
+ const refused = [];
587
+ const ok = (model) => declared.has(model);
588
+ let next = def;
589
+ const drop = (field, label) => {
590
+ const { [field]: _dropped, ...rest } = next;
591
+ next = rest;
592
+ refused.push(label);
593
+ };
594
+ if (def.model !== undefined && !ok(def.model)) {
595
+ drop("model", "model");
596
+ if (next.modelProfile !== undefined) {
597
+ const { modelProfile: _p, ...rest } = next;
598
+ next = rest;
599
+ }
600
+ }
601
+ if (def.modelFallbacks !== undefined && !def.modelFallbacks.every(ok)) {
602
+ const kept = def.modelFallbacks.filter(ok);
603
+ if (kept.length > 0) {
604
+ next = { ...next, modelFallbacks: kept };
605
+ refused.push("model_fallbacks");
606
+ }
607
+ else
608
+ drop("modelFallbacks", "model_fallbacks");
609
+ }
610
+ if (def.modelTiers !== undefined && !(ok(def.modelTiers.fast) && ok(def.modelTiers.default))) {
611
+ drop("modelTiers", "model_tiers");
612
+ }
613
+ if (def.modelPool !== undefined) {
614
+ const narrowed = narrowPoolModels(def.modelPool, ok);
615
+ if (narrowed === undefined)
616
+ drop("modelPool", "model_pool");
617
+ else if (narrowed !== def.modelPool) {
618
+ next = { ...next, modelPool: narrowed };
619
+ refused.push("model_pool");
620
+ }
621
+ }
622
+ if (def.allowedProfiles !== undefined &&
623
+ !def.allowedProfiles.every((o) => ok(o.model) && (o.modelFallbacks ?? []).every(ok))) {
624
+ const options = def.allowedProfiles
625
+ .filter((o) => ok(o.model))
626
+ .map((o) => o.modelFallbacks === undefined || o.modelFallbacks.every(ok)
627
+ ? o
628
+ : { ...o, modelFallbacks: o.modelFallbacks.filter(ok) });
629
+ if (options.length > 0) {
630
+ next = { ...next, allowedProfiles: options };
631
+ refused.push("allowed_profiles");
632
+ }
633
+ else
634
+ drop("allowedProfiles", "allowed_profiles");
635
+ }
636
+ return { def: next, refused };
637
+ }
638
+ /** Definitions whose refused models have already been reported. */
639
+ const reportedRefusedModels = new Set();
640
+ /** Definitions from disk whose tool list matched nothing, already reported. */
641
+ const reportedToolless = new Set();
642
+ /**
643
+ * A file's tool entries for a notice: each quoted with its control
644
+ * characters escaped (the file is the agent's to write, and the notice goes
645
+ * to the operator's terminal), shortened, and at most a handful of them.
646
+ */
647
+ function describeEntries(entries) {
648
+ const shown = entries
649
+ .slice(0, 8)
650
+ .map((e) => JSON.stringify(e.length > 64 ? `${e.slice(0, 64)}…` : e));
651
+ return entries.length > shown.length
652
+ ? `${shown.join(", ")} and ${entries.length - shown.length} more`
653
+ : shown.join(", ");
338
654
  }
339
655
  export function createTaskTool(opts = {}) {
340
656
  const knownNames = opts.subAgents !== undefined ? [...opts.subAgents.keys()] : [];
@@ -381,7 +697,8 @@ export function createTaskTool(opts = {}) {
381
697
  return false;
382
698
  let def;
383
699
  try {
384
- def = resolveSubAgentDefinition(parsed.data.subagent_type, opts);
700
+ const resolved = resolveSubAgent(parsed.data.subagent_type, opts);
701
+ def = withRegisteredToolNames(resolved.def, resolved.fromDisk);
385
702
  }
386
703
  catch {
387
704
  return false;
@@ -401,12 +718,32 @@ export function createTaskTool(opts = {}) {
401
718
  }
402
719
  const spawnSubAgent = bridge.spawnSubAgent;
403
720
  let def;
721
+ let fromDisk;
722
+ // The tool list as the definition wrote it, for a notice.
723
+ let listedTools;
404
724
  try {
405
- def = resolveSubAgentDefinition(input.subagent_type, opts);
725
+ ({ def, fromDisk } = resolveSubAgent(input.subagent_type, opts));
726
+ listedTools = def.tools ?? [];
727
+ // One spelling for everything below: the child catalog AND a
728
+ // `scoped` rule filter both match registered names (`Bash`), and a
729
+ // permission glob is case-sensitive. A spec key left raw here would
730
+ // give the child the tool while scoping away the parent's rules for
731
+ // it — so map before either reads the list.
732
+ def = withRegisteredToolNames(def, fromDisk);
406
733
  }
407
734
  catch (err) {
408
735
  return `[Task error] ${err.message}`;
409
736
  }
737
+ // A definition from disk runs only on models the spec names — before
738
+ // the `profile` check below reads its allowed_profiles.
739
+ if (fromDisk) {
740
+ const narrowedModels = narrowDiskModels(def, declaredModels(bridge, opts.subAgents));
741
+ def = narrowedModels.def;
742
+ if (narrowedModels.refused.length > 0 && !reportedRefusedModels.has(def.name)) {
743
+ reportedRefusedModels.add(def.name);
744
+ process.stderr.write(`[task] sub-agent "${def.name}" comes from .crewhaus/sub-agents, so it may run only on models the spec names — its ${narrowedModels.refused.join(", ")} named others, which were dropped; where none was left, it runs on the parent's model. To run it on another model, declare the sub-agent under sub_agents in crewhaus.yaml.\n`);
745
+ }
746
+ }
410
747
  // 0.6.0 §7.7 / §10.1 — the model-filled `profile` argument is checked
411
748
  // against the definition's allowlist BEFORE anything is spawned. Thrown
412
749
  // (not returned) so tool-executor renders it `is_error: true`: the
@@ -418,7 +755,32 @@ export function createTaskTool(opts = {}) {
418
755
  }
419
756
  }
420
757
  const childTools = buildChildCatalog(bridge.tools, def);
421
- const childPerms = resolveChildPermissions({ mode: bridge.permissionMode, rules: bridge.permissionRules }, def);
758
+ if (fromDisk &&
759
+ childTools.length === 0 &&
760
+ listedTools.length > 0 &&
761
+ !reportedToolless.has(def.name)) {
762
+ reportedToolless.add(def.name);
763
+ process.stderr.write(`[task] sub-agent "${def.name}" comes from .crewhaus/sub-agents, and none of its tools (${describeEntries(listedTools)}) is a tool the parent has, so it runs with no tools. List registered names (Read) or spec keys (read); a category (all-git) gives the child only the tools of it the parent has.\n`);
764
+ }
765
+ const parentPerms = { mode: bridge.permissionMode, rules: bridge.permissionRules };
766
+ let childPerms;
767
+ if (fromDisk) {
768
+ const narrowedPool = narrowDiskModelPool(def);
769
+ def = narrowedPool.def;
770
+ if (narrowedPool.refused.length > 0 && !reportedRefusedPoolKeys.has(def.name)) {
771
+ reportedRefusedPoolKeys.add(def.name);
772
+ process.stderr.write(`[task] sub-agent "${def.name}" comes from .crewhaus/sub-agents, so its model_pool candidates cannot set ${narrowedPool.refused.join(", ")} — ignored, so its tools run under the parent's tool_config. To give a candidate its own tool_config, declare the sub-agent under sub_agents in crewhaus.yaml.\n`);
773
+ }
774
+ const narrowed = resolveChildPermissionsNarrowOnly(parentPerms, def);
775
+ if (narrowed.ungrantedAllows.length > 0 && !reportedIgnoredAllows.has(def.name)) {
776
+ reportedIgnoredAllows.add(def.name);
777
+ process.stderr.write(`[task] sub-agent "${def.name}" comes from .crewhaus/sub-agents, so its permissions can only narrow the parent's — the parent does not allow ${narrowed.ungrantedAllows.join(", ")}, so its allow list does not grant them. To grant them, declare the sub-agent under sub_agents in crewhaus.yaml.\n`);
778
+ }
779
+ childPerms = narrowed;
780
+ }
781
+ else {
782
+ childPerms = resolveChildPermissions(parentPerms, def);
783
+ }
422
784
  // 0.6.0 §10.2 — ONE shared projection replaces the field-by-field hand
423
785
  // copy this tool carried (and whose optional-seam omissions were the
424
786
  // mechanism of the G11 approval bug): `projectParentHandle` lives beside
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewhaus/tool-task",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "description": "Task(description, prompt, subagent_type?) tool — spawns a sub-agent and returns its final message (Section 13)",
6
6
  "main": "dist/index.js",
@@ -8,18 +8,21 @@
8
8
  "exports": {
9
9
  ".": {
10
10
  "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js"
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
12
13
  }
13
14
  },
14
15
  "scripts": {
15
16
  "test": "bun test src"
16
17
  },
17
18
  "dependencies": {
18
- "@crewhaus/agent-context-isolation": "0.7.0",
19
- "@crewhaus/errors": "0.7.0",
20
- "@crewhaus/sub-agent-permission-inheritance": "0.7.0",
21
- "@crewhaus/tool-builder": "0.7.0",
22
- "@crewhaus/tool-catalog": "0.7.0",
19
+ "@crewhaus/agent-context-isolation": "0.8.0",
20
+ "@crewhaus/errors": "0.8.0",
21
+ "@crewhaus/sub-agent-permission-inheritance": "0.8.0",
22
+ "@crewhaus/tool-builder": "0.8.0",
23
+ "@crewhaus/tool-catalog": "0.8.0",
24
+ "@crewhaus/tool-categories": "0.8.0",
25
+ "@crewhaus/tool-safety": "0.8.0",
23
26
  "yaml": "^2.6.0",
24
27
  "zod": "^3.23.8"
25
28
  },
@@ -46,5 +49,8 @@
46
49
  "publishConfig": {
47
50
  "access": "public"
48
51
  },
49
- "files": ["dist", "README.md", "LICENSE", "NOTICE"]
52
+ "files": ["dist", "README.md", "LICENSE", "NOTICE"],
53
+ "engines": {
54
+ "bun": ">=1.3.14"
55
+ }
50
56
  }