agentpacks 0.3.0 → 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 (166) hide show
  1. package/README.md +168 -8
  2. package/dist/api.d.ts +2 -0
  3. package/dist/api.js +929 -409
  4. package/dist/cli/export-cmd.js +281 -149
  5. package/dist/cli/generate.js +740 -247
  6. package/dist/cli/import-cmd.js +57 -85
  7. package/dist/cli/info.d.ts +4 -0
  8. package/dist/cli/info.js +232 -0
  9. package/dist/cli/init.js +8 -36
  10. package/dist/cli/install.js +414 -129
  11. package/dist/cli/login.d.ts +9 -0
  12. package/dist/cli/login.js +202 -0
  13. package/dist/cli/models-explain.d.ts +16 -0
  14. package/dist/cli/models-explain.js +1205 -0
  15. package/dist/cli/pack/create.js +4 -32
  16. package/dist/cli/pack/enable.js +1 -29
  17. package/dist/cli/pack/list.js +266 -134
  18. package/dist/cli/pack/validate.js +274 -127
  19. package/dist/cli/publish.d.ts +8 -0
  20. package/dist/cli/publish.js +672 -0
  21. package/dist/cli/search.d.ts +12 -0
  22. package/dist/cli/search.js +210 -0
  23. package/dist/core/config.d.ts +2 -1
  24. package/dist/core/config.js +74 -117
  25. package/dist/core/dependency-resolver.js +4 -28
  26. package/dist/core/feature-merger.d.ts +7 -0
  27. package/dist/core/feature-merger.js +289 -29
  28. package/dist/core/index.js +283 -140
  29. package/dist/core/lockfile.js +0 -28
  30. package/dist/core/metarepo.js +74 -116
  31. package/dist/core/pack-loader.d.ts +2 -0
  32. package/dist/core/pack-loader.js +266 -133
  33. package/dist/core/profile-resolver.d.ts +75 -0
  34. package/dist/core/profile-resolver.js +111 -0
  35. package/dist/exporters/cursor-plugin.js +4 -32
  36. package/dist/exporters/index.js +4 -32
  37. package/dist/features/agents.d.ts +5 -0
  38. package/dist/features/agents.js +2 -30
  39. package/dist/features/commands.js +2 -30
  40. package/dist/features/hooks.js +2 -30
  41. package/dist/features/ignore.js +0 -28
  42. package/dist/features/index.d.ts +1 -0
  43. package/dist/features/index.js +176 -31
  44. package/dist/features/mcp.js +2 -30
  45. package/dist/features/models.d.ts +167 -0
  46. package/dist/features/models.js +293 -0
  47. package/dist/features/plugins.js +2 -30
  48. package/dist/features/rules.js +2 -30
  49. package/dist/features/skills.js +2 -30
  50. package/dist/importers/claude-code.js +10 -38
  51. package/dist/importers/cursor.js +15 -43
  52. package/dist/importers/opencode.js +16 -44
  53. package/dist/importers/rulesync.js +22 -50
  54. package/dist/index.js +1710 -538
  55. package/dist/node/api.js +929 -409
  56. package/dist/node/cli/export-cmd.js +281 -149
  57. package/dist/node/cli/generate.js +740 -247
  58. package/dist/node/cli/import-cmd.js +57 -85
  59. package/dist/node/cli/info.js +232 -0
  60. package/dist/node/cli/init.js +8 -36
  61. package/dist/node/cli/install.js +414 -129
  62. package/dist/node/cli/login.js +202 -0
  63. package/dist/node/cli/models-explain.js +1205 -0
  64. package/dist/node/cli/pack/create.js +4 -32
  65. package/dist/node/cli/pack/enable.js +1 -29
  66. package/dist/node/cli/pack/list.js +266 -134
  67. package/dist/node/cli/pack/validate.js +274 -127
  68. package/dist/node/cli/publish.js +672 -0
  69. package/dist/node/cli/search.js +210 -0
  70. package/dist/node/core/config.js +74 -117
  71. package/dist/node/core/dependency-resolver.js +4 -28
  72. package/dist/node/core/feature-merger.js +289 -29
  73. package/dist/node/core/index.js +283 -140
  74. package/dist/node/core/lockfile.js +0 -28
  75. package/dist/node/core/metarepo.js +74 -116
  76. package/dist/node/core/pack-loader.js +266 -133
  77. package/dist/node/core/profile-resolver.js +111 -0
  78. package/dist/node/exporters/cursor-plugin.js +4 -32
  79. package/dist/node/exporters/index.js +4 -32
  80. package/dist/node/features/agents.js +2 -30
  81. package/dist/node/features/commands.js +2 -30
  82. package/dist/node/features/hooks.js +2 -30
  83. package/dist/node/features/ignore.js +0 -28
  84. package/dist/node/features/index.js +176 -31
  85. package/dist/node/features/mcp.js +2 -30
  86. package/dist/node/features/models.js +293 -0
  87. package/dist/node/features/plugins.js +2 -30
  88. package/dist/node/features/rules.js +2 -30
  89. package/dist/node/features/skills.js +2 -30
  90. package/dist/node/importers/claude-code.js +10 -38
  91. package/dist/node/importers/cursor.js +15 -43
  92. package/dist/node/importers/opencode.js +16 -44
  93. package/dist/node/importers/rulesync.js +22 -50
  94. package/dist/node/index.js +1710 -538
  95. package/dist/node/sources/git-ref.js +7 -30
  96. package/dist/node/sources/git.js +7 -30
  97. package/dist/node/sources/index.js +337 -39
  98. package/dist/node/sources/local.js +0 -28
  99. package/dist/node/sources/npm-ref.js +0 -28
  100. package/dist/node/sources/npm.js +10 -37
  101. package/dist/node/sources/registry-ref.js +37 -0
  102. package/dist/node/sources/registry.js +355 -0
  103. package/dist/node/targets/additional-targets.js +196 -37
  104. package/dist/node/targets/agents-md.js +5 -33
  105. package/dist/node/targets/base-target.js +0 -28
  106. package/dist/node/targets/claude-code.js +211 -41
  107. package/dist/node/targets/codex-cli.js +7 -35
  108. package/dist/node/targets/copilot.js +202 -41
  109. package/dist/node/targets/cursor.js +188 -40
  110. package/dist/node/targets/gemini-cli.js +10 -38
  111. package/dist/node/targets/generic-md-target.js +196 -37
  112. package/dist/node/targets/index.js +414 -106
  113. package/dist/node/targets/opencode.js +171 -51
  114. package/dist/node/targets/registry.js +414 -106
  115. package/dist/node/utils/credentials.js +38 -0
  116. package/dist/node/utils/diff.js +22 -34
  117. package/dist/node/utils/filesystem.js +2 -30
  118. package/dist/node/utils/frontmatter.js +0 -28
  119. package/dist/node/utils/global.js +3 -31
  120. package/dist/node/utils/markdown.js +0 -28
  121. package/dist/node/utils/model-allowlist.js +110 -0
  122. package/dist/node/utils/model-guidance.js +78 -0
  123. package/dist/node/utils/registry-client.js +142 -0
  124. package/dist/node/utils/tarball.js +49 -0
  125. package/dist/sources/git-ref.js +7 -30
  126. package/dist/sources/git.d.ts +2 -2
  127. package/dist/sources/git.js +7 -30
  128. package/dist/sources/index.d.ts +2 -0
  129. package/dist/sources/index.js +337 -39
  130. package/dist/sources/local.js +0 -28
  131. package/dist/sources/npm-ref.js +0 -28
  132. package/dist/sources/npm.js +10 -37
  133. package/dist/sources/registry-ref.d.ts +30 -0
  134. package/dist/sources/registry-ref.js +37 -0
  135. package/dist/sources/registry.d.ts +18 -0
  136. package/dist/sources/registry.js +355 -0
  137. package/dist/targets/additional-targets.js +196 -37
  138. package/dist/targets/agents-md.js +5 -33
  139. package/dist/targets/base-target.d.ts +2 -0
  140. package/dist/targets/base-target.js +0 -28
  141. package/dist/targets/claude-code.js +211 -41
  142. package/dist/targets/codex-cli.js +7 -35
  143. package/dist/targets/copilot.js +202 -41
  144. package/dist/targets/cursor.js +188 -40
  145. package/dist/targets/gemini-cli.js +10 -38
  146. package/dist/targets/generic-md-target.js +196 -37
  147. package/dist/targets/index.js +414 -106
  148. package/dist/targets/opencode.js +171 -51
  149. package/dist/targets/registry.js +414 -106
  150. package/dist/utils/credentials.d.ts +19 -0
  151. package/dist/utils/credentials.js +38 -0
  152. package/dist/utils/diff.js +22 -34
  153. package/dist/utils/filesystem.js +2 -30
  154. package/dist/utils/frontmatter.js +0 -28
  155. package/dist/utils/global.js +3 -31
  156. package/dist/utils/markdown.js +0 -28
  157. package/dist/utils/model-allowlist.d.ts +39 -0
  158. package/dist/utils/model-allowlist.js +110 -0
  159. package/dist/utils/model-guidance.d.ts +6 -0
  160. package/dist/utils/model-guidance.js +78 -0
  161. package/dist/utils/registry-client.d.ts +141 -0
  162. package/dist/utils/registry-client.js +142 -0
  163. package/dist/utils/tarball.d.ts +13 -0
  164. package/dist/utils/tarball.js +49 -0
  165. package/package.json +171 -5
  166. package/templates/pack/models.json +38 -0
@@ -0,0 +1,1205 @@
1
+ // @bun
2
+ var __require = import.meta.require;
3
+
4
+ // src/core/config.ts
5
+ import { z } from "zod";
6
+ import { readFileSync, existsSync } from "fs";
7
+ import { resolve } from "path";
8
+ import { parse as parseJsonc } from "jsonc-parser";
9
+ var TARGET_IDS = [
10
+ "opencode",
11
+ "cursor",
12
+ "claudecode",
13
+ "codexcli",
14
+ "geminicli",
15
+ "copilot",
16
+ "agentsmd",
17
+ "cline",
18
+ "kilo",
19
+ "roo",
20
+ "qwencode",
21
+ "kiro",
22
+ "factorydroid",
23
+ "antigravity",
24
+ "junie",
25
+ "augmentcode",
26
+ "windsurf",
27
+ "warp",
28
+ "replit",
29
+ "zed"
30
+ ];
31
+ var FEATURE_IDS = [
32
+ "rules",
33
+ "commands",
34
+ "agents",
35
+ "skills",
36
+ "hooks",
37
+ "plugins",
38
+ "mcp",
39
+ "ignore",
40
+ "models"
41
+ ];
42
+ var REPO_MODES = ["repo", "monorepo", "metarepo"];
43
+ var PackManifestSchema = z.object({
44
+ name: z.string().min(1),
45
+ version: z.string().default("1.0.0"),
46
+ description: z.string().default(""),
47
+ author: z.union([
48
+ z.string(),
49
+ z.object({ name: z.string(), email: z.string().optional() })
50
+ ]).optional(),
51
+ tags: z.array(z.string()).default([]),
52
+ dependencies: z.array(z.string()).default([]),
53
+ conflicts: z.array(z.string()).default([]),
54
+ targets: z.union([z.literal("*"), z.array(z.string())]).default("*"),
55
+ features: z.union([z.literal("*"), z.array(z.string())]).default("*")
56
+ });
57
+ var FeaturesSchema = z.union([
58
+ z.literal("*"),
59
+ z.array(z.string()),
60
+ z.record(z.string(), z.union([z.literal("*"), z.array(z.string())]))
61
+ ]);
62
+ var WorkspaceConfigSchema = z.object({
63
+ $schema: z.string().optional(),
64
+ packs: z.array(z.string()).default(["./packs/default"]),
65
+ disabled: z.array(z.string()).default([]),
66
+ targets: z.union([z.literal("*"), z.array(z.string())]).default("*"),
67
+ features: FeaturesSchema.default("*"),
68
+ mode: z.enum(REPO_MODES).default("repo"),
69
+ baseDirs: z.array(z.string()).default(["."]),
70
+ global: z.boolean().default(false),
71
+ delete: z.boolean().default(true),
72
+ verbose: z.boolean().default(false),
73
+ silent: z.boolean().default(false),
74
+ overrides: z.record(z.string(), z.record(z.string(), z.string())).default({}),
75
+ sources: z.array(z.object({
76
+ source: z.string(),
77
+ packs: z.array(z.string()).optional(),
78
+ skills: z.array(z.string()).optional()
79
+ })).default([]),
80
+ modelProfile: z.string().optional()
81
+ });
82
+ var CONFIG_FILES = ["agentpacks.local.jsonc", "agentpacks.jsonc"];
83
+ function loadWorkspaceConfig(projectRoot) {
84
+ for (const filename of CONFIG_FILES) {
85
+ const filepath = resolve(projectRoot, filename);
86
+ if (existsSync(filepath)) {
87
+ const raw = readFileSync(filepath, "utf-8");
88
+ const parsed = parseJsonc(raw);
89
+ return WorkspaceConfigSchema.parse(parsed);
90
+ }
91
+ }
92
+ return WorkspaceConfigSchema.parse({});
93
+ }
94
+ function loadPackManifest(packDir) {
95
+ const filepath = resolve(packDir, "pack.json");
96
+ if (!existsSync(filepath)) {
97
+ const dirName = packDir.split("/").pop() ?? "unknown";
98
+ return PackManifestSchema.parse({ name: dirName });
99
+ }
100
+ const raw = readFileSync(filepath, "utf-8");
101
+ const parsed = JSON.parse(raw);
102
+ return PackManifestSchema.parse(parsed);
103
+ }
104
+ function resolveFeatures(config, targetId) {
105
+ const { features } = config;
106
+ if (features === "*") {
107
+ return [...FEATURE_IDS];
108
+ }
109
+ if (Array.isArray(features)) {
110
+ if (features.includes("*"))
111
+ return [...FEATURE_IDS];
112
+ return features.filter((f) => FEATURE_IDS.includes(f));
113
+ }
114
+ const targetFeatures = features[targetId];
115
+ if (!targetFeatures)
116
+ return [];
117
+ if (targetFeatures === "*")
118
+ return [...FEATURE_IDS];
119
+ if (Array.isArray(targetFeatures) && targetFeatures.includes("*"))
120
+ return [...FEATURE_IDS];
121
+ return targetFeatures.filter((f) => FEATURE_IDS.includes(f));
122
+ }
123
+ function resolveTargets(config) {
124
+ if (config.targets === "*")
125
+ return [...TARGET_IDS];
126
+ return config.targets;
127
+ }
128
+
129
+ // src/utils/filesystem.ts
130
+ import {
131
+ existsSync as existsSync2,
132
+ mkdirSync,
133
+ readFileSync as readFileSync2,
134
+ writeFileSync,
135
+ readdirSync,
136
+ rmSync,
137
+ statSync
138
+ } from "fs";
139
+ import { dirname, relative, join } from "path";
140
+ var GENERATED_HEADER_MD = "<!-- Generated by agentpacks. DO NOT EDIT. -->";
141
+ var GENERATED_HEADER_JSON = "// Generated by agentpacks. DO NOT EDIT.";
142
+ var GENERATED_HEADER_JS = "// Generated by agentpacks. DO NOT EDIT.";
143
+ function writeGeneratedFile(filepath, content, options = {}) {
144
+ const { header = true, type } = options;
145
+ const ext = type ?? inferFileType(filepath);
146
+ ensureDir(dirname(filepath));
147
+ let output = content;
148
+ if (header) {
149
+ const headerComment = getHeader(ext);
150
+ if (headerComment) {
151
+ output = `${headerComment}
152
+ ${content}`;
153
+ }
154
+ }
155
+ writeFileSync(filepath, output, "utf-8");
156
+ }
157
+ function writeGeneratedJson(filepath, data, options = {}) {
158
+ const json = JSON.stringify(data, null, 2);
159
+ writeGeneratedFile(filepath, json + `
160
+ `, { ...options, type: "json" });
161
+ }
162
+ function readFileOrNull(filepath) {
163
+ if (!existsSync2(filepath))
164
+ return null;
165
+ return readFileSync2(filepath, "utf-8");
166
+ }
167
+ function readJsonOrNull(filepath) {
168
+ const content = readFileOrNull(filepath);
169
+ if (content === null)
170
+ return null;
171
+ return JSON.parse(content);
172
+ }
173
+ function ensureDir(dirPath) {
174
+ if (!existsSync2(dirPath)) {
175
+ mkdirSync(dirPath, { recursive: true });
176
+ }
177
+ }
178
+ function removeIfExists(targetPath) {
179
+ if (existsSync2(targetPath)) {
180
+ rmSync(targetPath, { recursive: true, force: true });
181
+ }
182
+ }
183
+ function listFiles(dirPath, options = {}) {
184
+ const { extension, recursive = false } = options;
185
+ if (!existsSync2(dirPath))
186
+ return [];
187
+ const results = [];
188
+ const entries = readdirSync(dirPath);
189
+ for (const entry of entries) {
190
+ const fullPath = join(dirPath, entry);
191
+ const stat = statSync(fullPath);
192
+ if (stat.isDirectory() && recursive) {
193
+ results.push(...listFiles(fullPath, options));
194
+ } else if (stat.isFile()) {
195
+ if (!extension || entry.endsWith(extension)) {
196
+ results.push(fullPath);
197
+ }
198
+ }
199
+ }
200
+ return results;
201
+ }
202
+ function listDirs(dirPath) {
203
+ if (!existsSync2(dirPath))
204
+ return [];
205
+ return readdirSync(dirPath).map((entry) => join(dirPath, entry)).filter((fullPath) => statSync(fullPath).isDirectory());
206
+ }
207
+ function relPath(projectRoot, filepath) {
208
+ return relative(projectRoot, filepath);
209
+ }
210
+ function isGeneratedFile(filepath) {
211
+ const content = readFileOrNull(filepath);
212
+ if (!content)
213
+ return false;
214
+ return content.startsWith(GENERATED_HEADER_MD) || content.startsWith(GENERATED_HEADER_JSON) || content.startsWith(GENERATED_HEADER_JS);
215
+ }
216
+ function inferFileType(filepath) {
217
+ if (filepath.endsWith(".json") || filepath.endsWith(".jsonc"))
218
+ return "json";
219
+ if (filepath.endsWith(".ts") || filepath.endsWith(".mts"))
220
+ return "ts";
221
+ if (filepath.endsWith(".js") || filepath.endsWith(".mjs"))
222
+ return "js";
223
+ return "md";
224
+ }
225
+ function getHeader(type) {
226
+ switch (type) {
227
+ case "md":
228
+ return GENERATED_HEADER_MD;
229
+ case "json":
230
+ return GENERATED_HEADER_JSON;
231
+ case "js":
232
+ case "ts":
233
+ return GENERATED_HEADER_JS;
234
+ default:
235
+ return null;
236
+ }
237
+ }
238
+
239
+ // src/utils/frontmatter.ts
240
+ import matter from "gray-matter";
241
+ function parseFrontmatter(source) {
242
+ const { data, content } = matter(source);
243
+ return {
244
+ data,
245
+ content: content.trim(),
246
+ raw: source
247
+ };
248
+ }
249
+ function serializeFrontmatter(data, content) {
250
+ const filtered = Object.fromEntries(Object.entries(data).filter(([, v]) => v !== undefined));
251
+ if (Object.keys(filtered).length === 0) {
252
+ return content;
253
+ }
254
+ return matter.stringify(content, filtered);
255
+ }
256
+
257
+ // src/features/rules.ts
258
+ import { readFileSync as readFileSync3 } from "fs";
259
+ import { basename } from "path";
260
+ function parseRules(rulesDir, packName) {
261
+ const files = listFiles(rulesDir, { extension: ".md" });
262
+ return files.map((filepath) => parseRuleFile(filepath, packName));
263
+ }
264
+ function parseRuleFile(filepath, packName) {
265
+ const raw = readFileSync3(filepath, "utf-8");
266
+ const { data, content } = parseFrontmatter(raw);
267
+ return {
268
+ name: basename(filepath, ".md"),
269
+ sourcePath: filepath,
270
+ packName,
271
+ meta: data,
272
+ content
273
+ };
274
+ }
275
+ function ruleMatchesTarget(rule, targetId) {
276
+ const { targets } = rule.meta;
277
+ if (!targets || targets === "*")
278
+ return true;
279
+ if (Array.isArray(targets) && targets.includes("*"))
280
+ return true;
281
+ return Array.isArray(targets) && targets.includes(targetId);
282
+ }
283
+ function getRootRules(rules) {
284
+ return rules.filter((r) => r.meta.root === true);
285
+ }
286
+ function getDetailRules(rules) {
287
+ return rules.filter((r) => r.meta.root !== true);
288
+ }
289
+
290
+ // src/features/commands.ts
291
+ import { readFileSync as readFileSync4 } from "fs";
292
+ import { basename as basename2 } from "path";
293
+ function parseCommands(commandsDir, packName) {
294
+ const files = listFiles(commandsDir, { extension: ".md" });
295
+ return files.map((filepath) => parseCommandFile(filepath, packName));
296
+ }
297
+ function parseCommandFile(filepath, packName) {
298
+ const raw = readFileSync4(filepath, "utf-8");
299
+ const { data, content } = parseFrontmatter(raw);
300
+ return {
301
+ name: basename2(filepath, ".md"),
302
+ sourcePath: filepath,
303
+ packName,
304
+ meta: data,
305
+ content
306
+ };
307
+ }
308
+ function commandMatchesTarget(cmd, targetId) {
309
+ const { targets } = cmd.meta;
310
+ if (!targets || targets === "*")
311
+ return true;
312
+ if (Array.isArray(targets) && targets.includes("*"))
313
+ return true;
314
+ return Array.isArray(targets) && targets.includes(targetId);
315
+ }
316
+
317
+ // src/features/agents.ts
318
+ import { readFileSync as readFileSync5 } from "fs";
319
+ import { basename as basename3 } from "path";
320
+ function parseAgents(agentsDir, packName) {
321
+ const files = listFiles(agentsDir, { extension: ".md" });
322
+ return files.map((filepath) => parseAgentFile(filepath, packName));
323
+ }
324
+ function parseAgentFile(filepath, packName) {
325
+ const raw = readFileSync5(filepath, "utf-8");
326
+ const { data, content } = parseFrontmatter(raw);
327
+ return {
328
+ name: data.name ?? basename3(filepath, ".md"),
329
+ sourcePath: filepath,
330
+ packName,
331
+ meta: data,
332
+ content
333
+ };
334
+ }
335
+ function agentMatchesTarget(agent, targetId) {
336
+ const { targets } = agent.meta;
337
+ if (!targets || targets === "*")
338
+ return true;
339
+ if (Array.isArray(targets) && targets.includes("*"))
340
+ return true;
341
+ return Array.isArray(targets) && targets.includes(targetId);
342
+ }
343
+
344
+ // src/features/skills.ts
345
+ import { readFileSync as readFileSync6, existsSync as existsSync3 } from "fs";
346
+ import { basename as basename4, join as join2 } from "path";
347
+ function parseSkills(skillsDir, packName) {
348
+ const dirs = listDirs(skillsDir);
349
+ const skills = [];
350
+ for (const dir of dirs) {
351
+ const skillMd = join2(dir, "SKILL.md");
352
+ if (existsSync3(skillMd)) {
353
+ skills.push(parseSkillFile(skillMd, dir, packName));
354
+ }
355
+ }
356
+ return skills;
357
+ }
358
+ function parseSkillFile(filepath, skillDir, packName) {
359
+ const raw = readFileSync6(filepath, "utf-8");
360
+ const { data, content } = parseFrontmatter(raw);
361
+ return {
362
+ name: data.name ?? basename4(skillDir),
363
+ sourcePath: filepath,
364
+ sourceDir: skillDir,
365
+ packName,
366
+ meta: data,
367
+ content
368
+ };
369
+ }
370
+ function skillMatchesTarget(skill, targetId) {
371
+ const { targets } = skill.meta;
372
+ if (!targets || targets === "*")
373
+ return true;
374
+ if (Array.isArray(targets) && targets.includes("*"))
375
+ return true;
376
+ return Array.isArray(targets) && targets.includes(targetId);
377
+ }
378
+
379
+ // src/features/hooks.ts
380
+ import { join as join3 } from "path";
381
+ var TARGET_OVERRIDE_KEYS = ["cursor", "claudecode", "opencode"];
382
+ function parseHooks(packDir, packName) {
383
+ const hooksPath = join3(packDir, "hooks", "hooks.json");
384
+ const raw = readJsonOrNull(hooksPath);
385
+ if (!raw)
386
+ return null;
387
+ const shared = raw.hooks ?? {};
388
+ const targetOverrides = {};
389
+ for (const key of TARGET_OVERRIDE_KEYS) {
390
+ const override = raw[key];
391
+ if (override && typeof override === "object" && "hooks" in override && override.hooks) {
392
+ targetOverrides[key] = override.hooks;
393
+ }
394
+ }
395
+ return {
396
+ packName,
397
+ sourcePath: hooksPath,
398
+ version: raw.version,
399
+ shared,
400
+ targetOverrides
401
+ };
402
+ }
403
+ function resolveHooksForTarget(hooks, targetId) {
404
+ const merged = {};
405
+ for (const [event, entries] of Object.entries(hooks.shared)) {
406
+ merged[event] = [...entries];
407
+ }
408
+ const overrides = hooks.targetOverrides[targetId];
409
+ if (overrides) {
410
+ for (const [event, entries] of Object.entries(overrides)) {
411
+ merged[event] = [...merged[event] ?? [], ...entries];
412
+ }
413
+ }
414
+ return merged;
415
+ }
416
+
417
+ // src/features/plugins.ts
418
+ import { readFileSync as readFileSync7, existsSync as existsSync4 } from "fs";
419
+ import { basename as basename5, join as join4 } from "path";
420
+ function parsePlugins(packDir, packName) {
421
+ const pluginsDir = join4(packDir, "plugins");
422
+ if (!existsSync4(pluginsDir))
423
+ return [];
424
+ const tsFiles = listFiles(pluginsDir, { extension: ".ts" });
425
+ const jsFiles = listFiles(pluginsDir, { extension: ".js" });
426
+ const allFiles = [...tsFiles, ...jsFiles];
427
+ return allFiles.map((filepath) => parsePluginFile(filepath, packName));
428
+ }
429
+ function parsePluginFile(filepath, packName) {
430
+ const content = readFileSync7(filepath, "utf-8");
431
+ const ext = filepath.endsWith(".ts") ? "ts" : "js";
432
+ return {
433
+ name: basename5(filepath, `.${ext}`),
434
+ sourcePath: filepath,
435
+ packName,
436
+ content,
437
+ extension: ext
438
+ };
439
+ }
440
+
441
+ // src/features/mcp.ts
442
+ import { join as join5 } from "path";
443
+ function parseMcp(packDir, packName) {
444
+ const mcpPath = join5(packDir, "mcp.json");
445
+ const raw = readJsonOrNull(mcpPath);
446
+ if (!raw?.mcpServers)
447
+ return null;
448
+ return {
449
+ packName,
450
+ sourcePath: mcpPath,
451
+ servers: raw.mcpServers
452
+ };
453
+ }
454
+ function mergeMcpConfigs(configs) {
455
+ const servers = {};
456
+ const warnings = [];
457
+ for (const config of configs) {
458
+ for (const [name, entry] of Object.entries(config.servers)) {
459
+ if (name in servers) {
460
+ warnings.push(`MCP server "${name}" from pack "${config.packName}" skipped (already defined).`);
461
+ continue;
462
+ }
463
+ servers[name] = entry;
464
+ }
465
+ }
466
+ return { servers, warnings };
467
+ }
468
+
469
+ // src/features/ignore.ts
470
+ import { existsSync as existsSync5, readFileSync as readFileSync8 } from "fs";
471
+ import { join as join6 } from "path";
472
+ var IGNORE_FILES = ["ignore", ".aiignore"];
473
+ function parseIgnore(packDir, packName) {
474
+ for (const filename of IGNORE_FILES) {
475
+ const filepath = join6(packDir, filename);
476
+ if (existsSync5(filepath)) {
477
+ const raw = readFileSync8(filepath, "utf-8");
478
+ const patterns = parseIgnoreContent(raw);
479
+ return {
480
+ packName,
481
+ sourcePath: filepath,
482
+ patterns
483
+ };
484
+ }
485
+ }
486
+ return null;
487
+ }
488
+ function parseIgnoreContent(content) {
489
+ return content.split(`
490
+ `).map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
491
+ }
492
+ function mergeIgnorePatterns(configs) {
493
+ const seen = new Set;
494
+ const result = [];
495
+ for (const config of configs) {
496
+ for (const pattern of config.patterns) {
497
+ if (!seen.has(pattern)) {
498
+ seen.add(pattern);
499
+ result.push(pattern);
500
+ }
501
+ }
502
+ }
503
+ return result;
504
+ }
505
+
506
+ // src/features/models.ts
507
+ import { join as join7 } from "path";
508
+ import { z as z2 } from "zod";
509
+ var SECRET_PATTERNS = [
510
+ /["']api[_-]?key["']\s*:/i,
511
+ /["']apiKey["']\s*:/i,
512
+ /["']secret["']\s*:/i,
513
+ /["']password["']\s*:/i,
514
+ /["'](?:auth_token|access_token|bearer_token)["']\s*:/i,
515
+ /["']private[_-]?key["']\s*:/i,
516
+ /-----BEGIN\s+(RSA|EC|DSA|OPENSSH|PGP)\s+PRIVATE\s+KEY-----/,
517
+ /sk-[a-zA-Z0-9]{20,}/,
518
+ /Bearer\s+[a-zA-Z0-9._-]{20,}/
519
+ ];
520
+ var AgentModelSchema = z2.object({
521
+ model: z2.string(),
522
+ temperature: z2.number().min(0).max(2).optional(),
523
+ top_p: z2.number().min(0).max(1).optional()
524
+ });
525
+ var ModelProfileSchema = z2.object({
526
+ extends: z2.string().optional(),
527
+ description: z2.string().optional(),
528
+ default: z2.string().optional(),
529
+ small: z2.string().optional(),
530
+ agents: z2.record(z2.string(), AgentModelSchema).optional()
531
+ });
532
+ var RoutingConditionSchema = z2.object({
533
+ complexity: z2.enum(["low", "medium", "high", "critical"]).optional().describe("Task complexity level"),
534
+ urgency: z2.enum(["low", "normal", "high"]).optional().describe("Time sensitivity"),
535
+ budget: z2.enum(["minimal", "standard", "premium"]).optional().describe("Cost/token budget tier"),
536
+ contextWindowNeed: z2.enum(["small", "medium", "large", "max"]).optional().describe("Required context window size"),
537
+ toolUseIntensity: z2.enum(["none", "light", "heavy"]).optional().describe("Expected tool/function calling intensity")
538
+ });
539
+ var RoutingRuleSchema = z2.object({
540
+ when: z2.record(z2.string(), z2.string()),
541
+ use: z2.string(),
542
+ description: z2.string().optional(),
543
+ priority: z2.number().optional()
544
+ });
545
+ var ProviderModelSchema = z2.object({
546
+ options: z2.record(z2.string(), z2.unknown()).optional(),
547
+ variants: z2.record(z2.string(), z2.record(z2.string(), z2.unknown())).optional()
548
+ });
549
+ var ProviderConfigSchema = z2.object({
550
+ options: z2.record(z2.string(), z2.unknown()).optional(),
551
+ models: z2.record(z2.string(), ProviderModelSchema).optional()
552
+ });
553
+ var ModelsSchema = z2.object({
554
+ default: z2.string().optional(),
555
+ small: z2.string().optional(),
556
+ agents: z2.record(z2.string(), AgentModelSchema).optional(),
557
+ profiles: z2.record(z2.string(), ModelProfileSchema).optional(),
558
+ providers: z2.record(z2.string(), ProviderConfigSchema).optional(),
559
+ routing: z2.array(RoutingRuleSchema).optional(),
560
+ overrides: z2.record(z2.string(), z2.object({
561
+ default: z2.string().optional(),
562
+ small: z2.string().optional(),
563
+ agents: z2.record(z2.string(), AgentModelSchema).optional()
564
+ })).optional()
565
+ });
566
+ function parseModels(packDir, packName) {
567
+ const modelsPath = join7(packDir, "models.json");
568
+ const raw = readJsonOrNull(modelsPath);
569
+ if (!raw)
570
+ return null;
571
+ const parsed = ModelsSchema.parse(raw);
572
+ return {
573
+ packName,
574
+ sourcePath: modelsPath,
575
+ config: parsed
576
+ };
577
+ }
578
+ function mergeModelsConfigs(configs) {
579
+ const warnings = [];
580
+ const result = {};
581
+ for (const entry of configs) {
582
+ const { config, packName } = entry;
583
+ if (config.default !== undefined && result.default === undefined) {
584
+ result.default = config.default;
585
+ } else if (config.default !== undefined && result.default !== undefined) {
586
+ warnings.push(`Models "default" from pack "${packName}" skipped (already defined).`);
587
+ }
588
+ if (config.small !== undefined && result.small === undefined) {
589
+ result.small = config.small;
590
+ } else if (config.small !== undefined && result.small !== undefined) {
591
+ warnings.push(`Models "small" from pack "${packName}" skipped (already defined).`);
592
+ }
593
+ if (config.agents) {
594
+ if (!result.agents)
595
+ result.agents = {};
596
+ for (const [name, assignment] of Object.entries(config.agents)) {
597
+ if (name in result.agents) {
598
+ warnings.push(`Models agent "${name}" from pack "${packName}" skipped (already defined).`);
599
+ continue;
600
+ }
601
+ result.agents[name] = assignment;
602
+ }
603
+ }
604
+ if (config.profiles) {
605
+ if (!result.profiles)
606
+ result.profiles = {};
607
+ for (const [name, profile] of Object.entries(config.profiles)) {
608
+ if (name in result.profiles) {
609
+ warnings.push(`Models profile "${name}" from pack "${packName}" skipped (already defined).`);
610
+ continue;
611
+ }
612
+ result.profiles[name] = profile;
613
+ }
614
+ }
615
+ if (config.providers) {
616
+ if (!result.providers)
617
+ result.providers = {};
618
+ for (const [providerName, providerConfig] of Object.entries(config.providers)) {
619
+ if (!(providerName in result.providers)) {
620
+ result.providers[providerName] = providerConfig;
621
+ } else {
622
+ const existing = result.providers[providerName];
623
+ if (!existing) {
624
+ result.providers[providerName] = providerConfig;
625
+ continue;
626
+ }
627
+ if (providerConfig.options) {
628
+ existing.options = {
629
+ ...providerConfig.options,
630
+ ...existing.options
631
+ };
632
+ }
633
+ if (providerConfig.models) {
634
+ if (!existing.models)
635
+ existing.models = {};
636
+ for (const [modelName, modelConfig] of Object.entries(providerConfig.models)) {
637
+ if (!(modelName in existing.models)) {
638
+ existing.models[modelName] = modelConfig;
639
+ }
640
+ }
641
+ }
642
+ }
643
+ }
644
+ }
645
+ if (config.routing) {
646
+ if (!result.routing)
647
+ result.routing = [];
648
+ result.routing.push(...config.routing);
649
+ }
650
+ if (config.overrides) {
651
+ if (!result.overrides)
652
+ result.overrides = {};
653
+ for (const [targetId, override] of Object.entries(config.overrides)) {
654
+ if (targetId in result.overrides) {
655
+ warnings.push(`Models override for target "${targetId}" from pack "${packName}" skipped (already defined).`);
656
+ continue;
657
+ }
658
+ result.overrides[targetId] = override;
659
+ }
660
+ }
661
+ }
662
+ return { config: result, warnings };
663
+ }
664
+ function scanModelsForSecrets(config) {
665
+ const warnings = [];
666
+ const json = JSON.stringify(config);
667
+ for (const pattern of SECRET_PATTERNS) {
668
+ if (pattern.test(json)) {
669
+ warnings.push(`Potential secret detected in models.json matching pattern: ${pattern.source}`);
670
+ }
671
+ }
672
+ return warnings;
673
+ }
674
+
675
+ // src/core/pack-loader.ts
676
+ import { existsSync as existsSync6 } from "fs";
677
+ import { resolve as resolve2, isAbsolute } from "path";
678
+ class PackLoader {
679
+ projectRoot;
680
+ config;
681
+ constructor(projectRoot, config) {
682
+ this.projectRoot = projectRoot;
683
+ this.config = config;
684
+ }
685
+ loadAll() {
686
+ const warnings = [];
687
+ const packs = [];
688
+ const disabledSet = new Set(this.config.disabled);
689
+ for (const packRef of this.config.packs) {
690
+ const packDir = this.resolvePackPath(packRef);
691
+ if (!packDir) {
692
+ warnings.push(`Pack "${packRef}" could not be resolved. Skipping.`);
693
+ continue;
694
+ }
695
+ if (!existsSync6(packDir)) {
696
+ warnings.push(`Pack directory "${packDir}" does not exist. Skipping.`);
697
+ continue;
698
+ }
699
+ const manifest = loadPackManifest(packDir);
700
+ if (disabledSet.has(manifest.name) || disabledSet.has(packRef)) {
701
+ continue;
702
+ }
703
+ const loaded = this.loadPack(packDir, manifest);
704
+ packs.push(loaded);
705
+ }
706
+ return { packs, warnings };
707
+ }
708
+ loadPack(packDir, manifest) {
709
+ const name = manifest.name;
710
+ const rulesDir = resolve2(packDir, "rules");
711
+ const commandsDir = resolve2(packDir, "commands");
712
+ const agentsDir = resolve2(packDir, "agents");
713
+ const skillsDir = resolve2(packDir, "skills");
714
+ return {
715
+ manifest,
716
+ directory: packDir,
717
+ rules: existsSync6(rulesDir) ? parseRules(rulesDir, name) : [],
718
+ commands: existsSync6(commandsDir) ? parseCommands(commandsDir, name) : [],
719
+ agents: existsSync6(agentsDir) ? parseAgents(agentsDir, name) : [],
720
+ skills: existsSync6(skillsDir) ? parseSkills(skillsDir, name) : [],
721
+ hooks: parseHooks(packDir, name),
722
+ plugins: parsePlugins(packDir, name),
723
+ mcp: parseMcp(packDir, name),
724
+ ignore: parseIgnore(packDir, name),
725
+ models: parseModels(packDir, name)
726
+ };
727
+ }
728
+ loadForBaseDir(baseDir) {
729
+ const baseDirRoot = resolve2(this.projectRoot, baseDir);
730
+ const localConfigPath = resolve2(baseDirRoot, "agentpacks.jsonc");
731
+ if (!existsSync6(localConfigPath)) {
732
+ return { packs: [], warnings: [] };
733
+ }
734
+ const localConfig = loadWorkspaceConfig(baseDirRoot);
735
+ const loader = new PackLoader(baseDirRoot, localConfig);
736
+ return loader.loadAll();
737
+ }
738
+ resolveCuratedPack(packRef) {
739
+ const curatedDir = resolve2(this.projectRoot, ".agentpacks", ".curated");
740
+ let packName = packRef;
741
+ if (packName.startsWith("registry:"))
742
+ packName = packName.slice(9);
743
+ if (packName.startsWith("npm:"))
744
+ packName = packName.slice(4);
745
+ if (packName.startsWith("github:"))
746
+ packName = packName.slice(7);
747
+ if (packName.startsWith("@"))
748
+ packName = packName.slice(1);
749
+ if (packName.includes("/")) {
750
+ const parts = packName.split("/");
751
+ packName = packName.includes("@") ? parts.join("-") : parts[parts.length - 1] ?? packName;
752
+ }
753
+ const withoutVersion = packName.split("@")[0] ?? packName;
754
+ packName = withoutVersion.split(":")[0] ?? withoutVersion;
755
+ const resolved = resolve2(curatedDir, packName);
756
+ return existsSync6(resolved) ? resolved : null;
757
+ }
758
+ resolvePackPath(packRef) {
759
+ if (packRef.startsWith("./") || packRef.startsWith("../")) {
760
+ return resolve2(this.projectRoot, packRef);
761
+ }
762
+ if (isAbsolute(packRef)) {
763
+ return packRef;
764
+ }
765
+ if (packRef.startsWith("registry:")) {
766
+ return this.resolveCuratedPack(packRef);
767
+ }
768
+ if (packRef.startsWith("@") || packRef.startsWith("npm:") || !packRef.includes("/")) {
769
+ return this.resolveCuratedPack(packRef);
770
+ }
771
+ if (packRef.startsWith("github:") || packRef.includes("/")) {
772
+ return this.resolveCuratedPack(packRef);
773
+ }
774
+ return resolve2(this.projectRoot, packRef);
775
+ }
776
+ }
777
+
778
+ // src/core/feature-merger.ts
779
+ class FeatureMerger {
780
+ packs;
781
+ warnings = [];
782
+ constructor(packs) {
783
+ this.packs = packs;
784
+ }
785
+ merge() {
786
+ this.warnings = [];
787
+ const features = {
788
+ rules: this.mergeRules(),
789
+ commands: this.mergeByName("commands"),
790
+ agents: this.mergeByName("agents"),
791
+ skills: this.mergeByName("skills"),
792
+ hooks: this.mergeHooks(),
793
+ plugins: this.mergePlugins(),
794
+ mcpServers: this.mergeMcp(),
795
+ ignorePatterns: this.mergeIgnore(),
796
+ models: this.mergeModels()
797
+ };
798
+ return { features, warnings: this.warnings };
799
+ }
800
+ mergeRules() {
801
+ const seen = new Map;
802
+ const result = [];
803
+ for (const pack of this.packs) {
804
+ for (const rule of pack.rules) {
805
+ const existing = seen.get(rule.name);
806
+ if (existing) {
807
+ this.warnings.push(`Rule "${rule.name}" from pack "${rule.packName}" skipped (already defined by "${existing}").`);
808
+ continue;
809
+ }
810
+ seen.set(rule.name, rule.packName);
811
+ result.push(rule);
812
+ }
813
+ }
814
+ return result;
815
+ }
816
+ mergeByName(featureKey) {
817
+ const seen = new Map;
818
+ const result = [];
819
+ for (const pack of this.packs) {
820
+ const items = pack[featureKey];
821
+ for (const item of items) {
822
+ const existing = seen.get(item.name);
823
+ if (existing) {
824
+ this.warnings.push(`${featureKey.slice(0, -1)} "${item.name}" from pack "${item.packName}" skipped (already defined by "${existing}").`);
825
+ continue;
826
+ }
827
+ seen.set(item.name, item.packName);
828
+ result.push(item);
829
+ }
830
+ }
831
+ return result;
832
+ }
833
+ mergeHooks() {
834
+ return this.packs.map((p) => p.hooks).filter((h) => h !== null);
835
+ }
836
+ mergePlugins() {
837
+ const seen = new Map;
838
+ const result = [];
839
+ for (const pack of this.packs) {
840
+ for (const plugin of pack.plugins) {
841
+ const key = `${plugin.name}.${plugin.extension}`;
842
+ const existing = seen.get(key);
843
+ if (existing) {
844
+ this.warnings.push(`Plugin "${key}" from pack "${plugin.packName}" skipped (already defined by "${existing}").`);
845
+ continue;
846
+ }
847
+ seen.set(key, plugin.packName);
848
+ result.push(plugin);
849
+ }
850
+ }
851
+ return result;
852
+ }
853
+ mergeMcp() {
854
+ const servers = {};
855
+ for (const pack of this.packs) {
856
+ if (!pack.mcp)
857
+ continue;
858
+ for (const [name, entry] of Object.entries(pack.mcp.servers)) {
859
+ if (name in servers) {
860
+ this.warnings.push(`MCP server "${name}" from pack "${pack.manifest.name}" skipped (already defined).`);
861
+ continue;
862
+ }
863
+ servers[name] = entry;
864
+ }
865
+ }
866
+ return servers;
867
+ }
868
+ mergeIgnore() {
869
+ const seen = new Set;
870
+ const result = [];
871
+ for (const pack of this.packs) {
872
+ if (!pack.ignore)
873
+ continue;
874
+ for (const pattern of pack.ignore.patterns) {
875
+ if (!seen.has(pattern)) {
876
+ seen.add(pattern);
877
+ result.push(pattern);
878
+ }
879
+ }
880
+ }
881
+ return result;
882
+ }
883
+ mergeModels() {
884
+ const configs = this.packs.map((p) => p.models).filter((m) => m != null);
885
+ if (configs.length === 0)
886
+ return null;
887
+ const { config, warnings } = mergeModelsConfigs(configs);
888
+ this.warnings.push(...warnings);
889
+ return config;
890
+ }
891
+ }
892
+
893
+ // src/core/profile-resolver.ts
894
+ function resolveModels(merged, modelProfile, targetId) {
895
+ let defaultModel = merged.default;
896
+ let smallModel = merged.small;
897
+ let agents = { ...merged.agents };
898
+ if (modelProfile && merged.profiles?.[modelProfile]) {
899
+ const resolvedProfile = resolveProfileInheritance(modelProfile, merged.profiles);
900
+ if (resolvedProfile.default)
901
+ defaultModel = resolvedProfile.default;
902
+ if (resolvedProfile.small)
903
+ smallModel = resolvedProfile.small;
904
+ if (resolvedProfile.agents) {
905
+ agents = { ...agents, ...resolvedProfile.agents };
906
+ }
907
+ }
908
+ if (targetId) {
909
+ const targetOverride = merged.overrides?.[targetId];
910
+ if (targetOverride) {
911
+ if (targetOverride.default)
912
+ defaultModel = targetOverride.default;
913
+ if (targetOverride.small)
914
+ smallModel = targetOverride.small;
915
+ if (targetOverride.agents) {
916
+ agents = { ...agents, ...targetOverride.agents };
917
+ }
918
+ }
919
+ }
920
+ const providers = {};
921
+ if (merged.providers) {
922
+ for (const [name, config] of Object.entries(merged.providers)) {
923
+ providers[name] = {
924
+ ...config.options ? { options: config.options } : {},
925
+ ...config.models ? { models: config.models } : {}
926
+ };
927
+ }
928
+ }
929
+ const profileNames = Object.keys(merged.profiles ?? {});
930
+ const profiles = {};
931
+ if (merged.profiles) {
932
+ for (const [name, profile] of Object.entries(merged.profiles)) {
933
+ profiles[name] = {
934
+ description: profile.description,
935
+ default: profile.default,
936
+ small: profile.small
937
+ };
938
+ }
939
+ }
940
+ return {
941
+ default: defaultModel,
942
+ small: smallModel,
943
+ agents,
944
+ providers,
945
+ routing: merged.routing ?? [],
946
+ profileNames,
947
+ activeProfile: modelProfile,
948
+ profiles
949
+ };
950
+ }
951
+ function resolveAgentModel(resolved, agentName, frontmatterModel) {
952
+ const fromModels = resolved.agents[agentName];
953
+ if (fromModels) {
954
+ return {
955
+ model: fromModels.model,
956
+ temperature: fromModels.temperature,
957
+ top_p: fromModels.top_p
958
+ };
959
+ }
960
+ if (frontmatterModel) {
961
+ return { model: frontmatterModel };
962
+ }
963
+ return {};
964
+ }
965
+ function resolveProfileInheritance(profileName, profiles) {
966
+ const visited = new Set;
967
+ return resolveProfileChain(profileName, profiles, visited, 0);
968
+ }
969
+ var MAX_INHERITANCE_DEPTH = 10;
970
+ function resolveProfileChain(name, profiles, visited, depth) {
971
+ if (depth > MAX_INHERITANCE_DEPTH) {
972
+ throw new Error(`Profile inheritance too deep (max ${MAX_INHERITANCE_DEPTH}): ${name}`);
973
+ }
974
+ if (visited.has(name)) {
975
+ throw new Error(`Circular profile inheritance detected: ${[...visited, name].join(" \u2192 ")}`);
976
+ }
977
+ const profile = profiles[name];
978
+ if (!profile) {
979
+ throw new Error(`Profile "${name}" not found`);
980
+ }
981
+ visited.add(name);
982
+ if (!profile.extends) {
983
+ return { ...profile };
984
+ }
985
+ const parent = resolveProfileChain(profile.extends, profiles, visited, depth + 1);
986
+ return {
987
+ description: profile.description ?? parent.description,
988
+ default: profile.default ?? parent.default,
989
+ small: profile.small ?? parent.small,
990
+ agents: {
991
+ ...parent.agents,
992
+ ...profile.agents
993
+ }
994
+ };
995
+ }
996
+
997
+ // src/utils/model-guidance.ts
998
+ function generateModelGuidanceMarkdown(resolved) {
999
+ if (!resolved.default && !resolved.small && Object.keys(resolved.agents).length === 0 && Object.keys(resolved.profiles).length === 0) {
1000
+ return null;
1001
+ }
1002
+ const lines = [];
1003
+ lines.push("# Model Configuration");
1004
+ lines.push("");
1005
+ lines.push("Use the following model preferences when working in this project.");
1006
+ lines.push("");
1007
+ if (resolved.default || resolved.small) {
1008
+ lines.push("## Default Models");
1009
+ lines.push("");
1010
+ if (resolved.default) {
1011
+ lines.push(`- **Primary model**: ${resolved.default}`);
1012
+ }
1013
+ if (resolved.small) {
1014
+ lines.push(`- **Lightweight tasks** (titles, summaries): ${resolved.small}`);
1015
+ }
1016
+ lines.push("");
1017
+ }
1018
+ const agentEntries = Object.entries(resolved.agents);
1019
+ if (agentEntries.length > 0) {
1020
+ lines.push("## Agent Model Assignments");
1021
+ lines.push("");
1022
+ lines.push("| Agent | Model | Temperature |");
1023
+ lines.push("| --- | --- | --- |");
1024
+ for (const [name, assignment] of agentEntries) {
1025
+ const temp = assignment.temperature !== undefined ? String(assignment.temperature) : "\u2014";
1026
+ lines.push(`| ${name} | ${assignment.model} | ${temp} |`);
1027
+ }
1028
+ lines.push("");
1029
+ }
1030
+ if (Object.keys(resolved.profiles).length > 0) {
1031
+ lines.push("## Available Profiles");
1032
+ lines.push("");
1033
+ lines.push("| Profile | Description | Default Model |");
1034
+ lines.push("| --- | --- | --- |");
1035
+ for (const [name, profile] of Object.entries(resolved.profiles)) {
1036
+ lines.push(`| ${name} | ${profile.description ?? "\u2014"} | ${profile.default ?? "\u2014"} |`);
1037
+ }
1038
+ lines.push("");
1039
+ }
1040
+ if (resolved.activeProfile) {
1041
+ lines.push(`**Active profile**: \`${resolved.activeProfile}\``);
1042
+ lines.push("");
1043
+ }
1044
+ if (resolved.routing.length > 0) {
1045
+ lines.push("## Task-Aware Routing");
1046
+ lines.push("");
1047
+ lines.push("Select the appropriate profile based on the task context:");
1048
+ lines.push("");
1049
+ lines.push("| Condition | Profile | Description |");
1050
+ lines.push("| --- | --- | --- |");
1051
+ for (const rule of resolved.routing) {
1052
+ const conditions = Object.entries(rule.when).map(([k, v]) => `${k}=${v}`).join(", ");
1053
+ const desc = rule.description ?? "\u2014";
1054
+ lines.push(`| ${conditions} | ${rule.use} | ${desc} |`);
1055
+ }
1056
+ lines.push("");
1057
+ lines.push("### Condition Reference");
1058
+ lines.push("");
1059
+ lines.push("- **complexity**: low | medium | high | critical");
1060
+ lines.push("- **urgency**: low | normal | high");
1061
+ lines.push("- **budget**: minimal | standard | premium");
1062
+ lines.push("- **contextWindowNeed**: small | medium | large | max");
1063
+ lines.push("- **toolUseIntensity**: none | light | heavy");
1064
+ lines.push("");
1065
+ }
1066
+ return lines.join(`
1067
+ `);
1068
+ }
1069
+
1070
+ // src/cli/models-explain.ts
1071
+ import chalk from "chalk";
1072
+ import { resolve as resolve3 } from "path";
1073
+ function runModelsExplain(options) {
1074
+ const projectRoot = resolve3(options.config ?? ".");
1075
+ const config = loadWorkspaceConfig(projectRoot);
1076
+ const loader = new PackLoader(projectRoot, config);
1077
+ const { packs } = loader.loadAll();
1078
+ if (packs.length === 0) {
1079
+ console.log(chalk.red("No packs loaded. Run `agentpacks init` first."));
1080
+ process.exit(1);
1081
+ }
1082
+ const merger = new FeatureMerger(packs);
1083
+ const { features: merged } = merger.merge();
1084
+ if (!merged.models) {
1085
+ console.log(chalk.dim("No model configuration found in your packs."));
1086
+ return;
1087
+ }
1088
+ const profile = options.profile;
1089
+ const target = options.target;
1090
+ const resolved = resolveModels(merged.models, profile, target);
1091
+ console.log(chalk.bold(`
1092
+ \uD83D\uDCCB Model Configuration Summary
1093
+ `));
1094
+ if (resolved.default) {
1095
+ console.log(` ${chalk.dim("Default model:")} ${chalk.cyan(resolved.default)}`);
1096
+ }
1097
+ if (resolved.small) {
1098
+ console.log(` ${chalk.dim("Small model:")} ${chalk.cyan(resolved.small)}`);
1099
+ }
1100
+ if (resolved.activeProfile) {
1101
+ console.log(` ${chalk.dim("Active profile:")} ${chalk.green(resolved.activeProfile)}`);
1102
+ }
1103
+ if (target) {
1104
+ console.log(` ${chalk.dim("Target:")} ${chalk.yellow(target)}`);
1105
+ }
1106
+ const agentEntries = Object.entries(resolved.agents);
1107
+ if (agentEntries.length > 0) {
1108
+ console.log(chalk.bold(`
1109
+ Agent Assignments:`));
1110
+ for (const [name, config2] of agentEntries) {
1111
+ const temp = config2.temperature !== undefined ? ` (temp: ${config2.temperature})` : "";
1112
+ console.log(` ${chalk.dim("\u2022")} ${name}: ${chalk.cyan(config2.model)}${chalk.dim(temp)}`);
1113
+ }
1114
+ }
1115
+ if (resolved.profileNames.length > 0) {
1116
+ console.log(chalk.bold(`
1117
+ Available Profiles:`));
1118
+ for (const name of resolved.profileNames) {
1119
+ const profileData = resolved.profiles[name];
1120
+ const desc = profileData?.description ?? "";
1121
+ const active = name === resolved.activeProfile ? chalk.green(" \u2190 active") : "";
1122
+ console.log(` ${chalk.dim("\u2022")} ${name}${active}${desc ? chalk.dim(` \u2014 ${desc}`) : ""}`);
1123
+ }
1124
+ }
1125
+ if (resolved.routing.length > 0) {
1126
+ console.log(chalk.bold(`
1127
+ Routing Rules:`));
1128
+ for (const rule of resolved.routing) {
1129
+ const conditions = Object.entries(rule.when).map(([k, v]) => `${chalk.yellow(k)}=${chalk.cyan(v)}`).join(", ");
1130
+ const desc = rule.description;
1131
+ console.log(` ${chalk.dim("\u2022")} When ${conditions} \u2192 use ${chalk.green(rule.use)}${desc ? chalk.dim(` (${desc})`) : ""}`);
1132
+ }
1133
+ if (options.task) {
1134
+ console.log(chalk.bold(`
1135
+ Task Analysis:`));
1136
+ console.log(` ${chalk.dim("Task:")} "${options.task}"`);
1137
+ const matched = matchTaskToRouting(options.task, resolved.routing);
1138
+ if (matched) {
1139
+ console.log(` ${chalk.green("\u2713")} Matched rule: ${chalk.green(matched.use)}`);
1140
+ const conditions = Object.entries(matched.when).map(([k, v]) => `${k}=${v}`).join(", ");
1141
+ console.log(` ${chalk.dim(" Conditions:")} ${conditions}`);
1142
+ } else {
1143
+ console.log(` ${chalk.yellow("\u25CB")} No routing rule matched \u2014 using default profile`);
1144
+ }
1145
+ }
1146
+ }
1147
+ const guidance = generateModelGuidanceMarkdown(resolved);
1148
+ if (guidance) {
1149
+ console.log(chalk.bold(`
1150
+ Generated Guidance Preview:`));
1151
+ console.log(chalk.dim(" " + "\u2500".repeat(50)));
1152
+ for (const line of guidance.split(`
1153
+ `).slice(0, 20)) {
1154
+ console.log(` ${chalk.dim(line)}`);
1155
+ }
1156
+ if (guidance.split(`
1157
+ `).length > 20) {
1158
+ console.log(chalk.dim(` ... (${guidance.split(`
1159
+ `).length - 20} more lines)`));
1160
+ }
1161
+ }
1162
+ console.log("");
1163
+ }
1164
+ function matchTaskToRouting(task, routing) {
1165
+ const lowerTask = task.toLowerCase();
1166
+ const complexityKeywords = {
1167
+ critical: ["critical", "security", "production", "hotfix"],
1168
+ high: ["refactor", "architecture", "complex", "rewrite", "migrate"],
1169
+ medium: ["feature", "implement", "update", "modify"],
1170
+ low: ["fix", "typo", "comment", "rename", "format"]
1171
+ };
1172
+ const urgencyKeywords = {
1173
+ high: ["urgent", "asap", "emergency", "hotfix", "critical"],
1174
+ normal: ["feature", "implement", "add"],
1175
+ low: ["cleanup", "refactor", "docs", "todo"]
1176
+ };
1177
+ const inferred = {};
1178
+ for (const [level, keywords] of Object.entries(complexityKeywords)) {
1179
+ if (keywords.some((kw) => lowerTask.includes(kw))) {
1180
+ inferred["complexity"] = level;
1181
+ break;
1182
+ }
1183
+ }
1184
+ for (const [level, keywords] of Object.entries(urgencyKeywords)) {
1185
+ if (keywords.some((kw) => lowerTask.includes(kw))) {
1186
+ inferred["urgency"] = level;
1187
+ break;
1188
+ }
1189
+ }
1190
+ for (const rule of routing) {
1191
+ const matches = Object.entries(rule.when).every(([key, value]) => {
1192
+ if (inferred[key] === value)
1193
+ return true;
1194
+ if (lowerTask.includes(value.toLowerCase()))
1195
+ return true;
1196
+ return false;
1197
+ });
1198
+ if (matches)
1199
+ return rule;
1200
+ }
1201
+ return null;
1202
+ }
1203
+ export {
1204
+ runModelsExplain
1205
+ };