@soleri/forge 0.0.1 → 3.0.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 (143) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/README.md +199 -0
  3. package/dist/facades/forge.facade.d.ts +9 -0
  4. package/dist/facades/forge.facade.js +134 -0
  5. package/dist/facades/forge.facade.js.map +1 -0
  6. package/dist/index.d.ts +2 -0
  7. package/dist/index.js +81 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/knowledge-installer.d.ts +30 -0
  10. package/dist/knowledge-installer.js +437 -0
  11. package/dist/knowledge-installer.js.map +1 -0
  12. package/dist/scaffolder.d.ts +13 -0
  13. package/dist/scaffolder.js +420 -0
  14. package/dist/scaffolder.js.map +1 -0
  15. package/dist/templates/activate.d.ts +9 -0
  16. package/dist/templates/activate.js +140 -0
  17. package/dist/templates/activate.js.map +1 -0
  18. package/dist/templates/brain.d.ts +6 -0
  19. package/dist/templates/brain.js +478 -0
  20. package/dist/templates/brain.js.map +1 -0
  21. package/dist/templates/claude-md-template.d.ts +11 -0
  22. package/dist/templates/claude-md-template.js +73 -0
  23. package/dist/templates/claude-md-template.js.map +1 -0
  24. package/dist/templates/core-facade.d.ts +6 -0
  25. package/dist/templates/core-facade.js +461 -0
  26. package/dist/templates/core-facade.js.map +1 -0
  27. package/dist/templates/domain-facade.d.ts +7 -0
  28. package/dist/templates/domain-facade.js +121 -0
  29. package/dist/templates/domain-facade.js.map +1 -0
  30. package/dist/templates/entry-point.d.ts +5 -0
  31. package/dist/templates/entry-point.js +121 -0
  32. package/dist/templates/entry-point.js.map +1 -0
  33. package/dist/templates/facade-factory.d.ts +1 -0
  34. package/dist/templates/facade-factory.js +63 -0
  35. package/dist/templates/facade-factory.js.map +1 -0
  36. package/dist/templates/facade-types.d.ts +1 -0
  37. package/dist/templates/facade-types.js +46 -0
  38. package/dist/templates/facade-types.js.map +1 -0
  39. package/dist/templates/inject-claude-md.d.ts +11 -0
  40. package/dist/templates/inject-claude-md.js +92 -0
  41. package/dist/templates/inject-claude-md.js.map +1 -0
  42. package/dist/templates/intelligence-loader.d.ts +1 -0
  43. package/dist/templates/intelligence-loader.js +43 -0
  44. package/dist/templates/intelligence-loader.js.map +1 -0
  45. package/dist/templates/intelligence-types.d.ts +1 -0
  46. package/dist/templates/intelligence-types.js +24 -0
  47. package/dist/templates/intelligence-types.js.map +1 -0
  48. package/dist/templates/llm-client.d.ts +7 -0
  49. package/dist/templates/llm-client.js +301 -0
  50. package/dist/templates/llm-client.js.map +1 -0
  51. package/dist/templates/llm-key-pool.d.ts +7 -0
  52. package/dist/templates/llm-key-pool.js +211 -0
  53. package/dist/templates/llm-key-pool.js.map +1 -0
  54. package/dist/templates/llm-types.d.ts +5 -0
  55. package/dist/templates/llm-types.js +161 -0
  56. package/dist/templates/llm-types.js.map +1 -0
  57. package/dist/templates/llm-utils.d.ts +5 -0
  58. package/dist/templates/llm-utils.js +260 -0
  59. package/dist/templates/llm-utils.js.map +1 -0
  60. package/dist/templates/package-json.d.ts +2 -0
  61. package/dist/templates/package-json.js +38 -0
  62. package/dist/templates/package-json.js.map +1 -0
  63. package/dist/templates/persona.d.ts +2 -0
  64. package/dist/templates/persona.js +42 -0
  65. package/dist/templates/persona.js.map +1 -0
  66. package/dist/templates/planner.d.ts +5 -0
  67. package/dist/templates/planner.js +150 -0
  68. package/dist/templates/planner.js.map +1 -0
  69. package/dist/templates/readme.d.ts +5 -0
  70. package/dist/templates/readme.js +316 -0
  71. package/dist/templates/readme.js.map +1 -0
  72. package/dist/templates/setup-script.d.ts +6 -0
  73. package/dist/templates/setup-script.js +112 -0
  74. package/dist/templates/setup-script.js.map +1 -0
  75. package/dist/templates/test-brain.d.ts +6 -0
  76. package/dist/templates/test-brain.js +474 -0
  77. package/dist/templates/test-brain.js.map +1 -0
  78. package/dist/templates/test-facades.d.ts +6 -0
  79. package/dist/templates/test-facades.js +652 -0
  80. package/dist/templates/test-facades.js.map +1 -0
  81. package/dist/templates/test-llm.d.ts +7 -0
  82. package/dist/templates/test-llm.js +574 -0
  83. package/dist/templates/test-llm.js.map +1 -0
  84. package/dist/templates/test-loader.d.ts +5 -0
  85. package/dist/templates/test-loader.js +146 -0
  86. package/dist/templates/test-loader.js.map +1 -0
  87. package/dist/templates/test-planner.d.ts +5 -0
  88. package/dist/templates/test-planner.js +271 -0
  89. package/dist/templates/test-planner.js.map +1 -0
  90. package/dist/templates/test-vault.d.ts +5 -0
  91. package/dist/templates/test-vault.js +380 -0
  92. package/dist/templates/test-vault.js.map +1 -0
  93. package/dist/templates/tsconfig.d.ts +1 -0
  94. package/dist/templates/tsconfig.js +25 -0
  95. package/dist/templates/tsconfig.js.map +1 -0
  96. package/dist/templates/vault.d.ts +5 -0
  97. package/dist/templates/vault.js +263 -0
  98. package/dist/templates/vault.js.map +1 -0
  99. package/dist/templates/vitest-config.d.ts +1 -0
  100. package/dist/templates/vitest-config.js +27 -0
  101. package/dist/templates/vitest-config.js.map +1 -0
  102. package/dist/types.d.ts +89 -0
  103. package/dist/types.js +21 -0
  104. package/dist/types.js.map +1 -0
  105. package/package.json +42 -4
  106. package/src/__tests__/knowledge-installer.test.ts +805 -0
  107. package/src/__tests__/scaffolder.test.ts +335 -0
  108. package/src/facades/forge.facade.ts +150 -0
  109. package/src/index.ts +101 -0
  110. package/src/knowledge-installer.ts +532 -0
  111. package/src/scaffolder.ts +482 -0
  112. package/src/templates/activate.ts +146 -0
  113. package/src/templates/brain.ts +478 -0
  114. package/src/templates/claude-md-template.ts +137 -0
  115. package/src/templates/core-facade.ts +462 -0
  116. package/src/templates/domain-facade.ts +123 -0
  117. package/src/templates/entry-point.ts +125 -0
  118. package/src/templates/facade-factory.ts +62 -0
  119. package/src/templates/facade-types.ts +45 -0
  120. package/src/templates/inject-claude-md.ts +94 -0
  121. package/src/templates/intelligence-loader.ts +42 -0
  122. package/src/templates/intelligence-types.ts +23 -0
  123. package/src/templates/llm-client.ts +302 -0
  124. package/src/templates/llm-key-pool.ts +212 -0
  125. package/src/templates/llm-types.ts +160 -0
  126. package/src/templates/llm-utils.ts +259 -0
  127. package/src/templates/package-json.ts +40 -0
  128. package/src/templates/persona.ts +45 -0
  129. package/src/templates/planner.ts +150 -0
  130. package/src/templates/readme.ts +319 -0
  131. package/src/templates/setup-script.ts +113 -0
  132. package/src/templates/test-brain.ts +474 -0
  133. package/src/templates/test-facades.ts +659 -0
  134. package/src/templates/test-llm.ts +575 -0
  135. package/src/templates/test-loader.ts +146 -0
  136. package/src/templates/test-planner.ts +271 -0
  137. package/src/templates/test-vault.ts +380 -0
  138. package/src/templates/tsconfig.ts +25 -0
  139. package/src/templates/vault.ts +263 -0
  140. package/src/templates/vitest-config.ts +26 -0
  141. package/src/types.ts +68 -0
  142. package/tsconfig.json +21 -0
  143. package/vitest.config.ts +15 -0
@@ -0,0 +1,125 @@
1
+ import type { AgentConfig } from '../types.js';
2
+
3
+ /**
4
+ * Generate the main index.ts entry point for the agent.
5
+ */
6
+ export function generateEntryPoint(config: AgentConfig): string {
7
+ const facadeImports = config.domains
8
+ .map((d) => {
9
+ const fn = `create${pascalCase(d)}Facade`;
10
+ const file = `${d}.facade.js`;
11
+ return `import { ${fn} } from './facades/${file}';`;
12
+ })
13
+ .join('\n');
14
+
15
+ const facadeCreations = config.domains
16
+ .map((d) => ` create${pascalCase(d)}Facade(vault, brain),`)
17
+ .join('\n');
18
+
19
+ return `#!/usr/bin/env node
20
+
21
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
22
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
23
+ import { dirname, join } from 'node:path';
24
+ import { fileURLToPath } from 'node:url';
25
+ import { homedir } from 'node:os';
26
+
27
+ import { registerAllFacades } from './facades/facade-factory.js';
28
+ ${facadeImports}
29
+ import { createCoreFacade } from './facades/core.facade.js';
30
+ import { loadIntelligenceData } from './intelligence/loader.js';
31
+ import { Vault } from './vault/vault.js';
32
+ import { Planner } from './planning/planner.js';
33
+ import { Brain } from './brain/brain.js';
34
+ import { LLMClient } from './llm/llm-client.js';
35
+ import { KeyPool, loadKeyPoolConfig } from './llm/key-pool.js';
36
+ import { PERSONA, getPersonaPrompt } from './identity/persona.js';
37
+
38
+ const __dirname = dirname(fileURLToPath(import.meta.url));
39
+
40
+ async function main(): Promise<void> {
41
+ // Initialize persistent vault at ~/.${config.id}/vault.db
42
+ const vaultPath = join(homedir(), '.${config.id}', 'vault.db');
43
+ const vault = new Vault(vaultPath);
44
+ console.error(\`[\${PERSONA.name.toLowerCase()}] Vault: \${vaultPath}\`);
45
+
46
+ // Load and seed intelligence data
47
+ const dataDir = join(__dirname, 'intelligence', 'data');
48
+ const entries = loadIntelligenceData(dataDir);
49
+ if (entries.length > 0) {
50
+ const seeded = vault.seed(entries);
51
+ console.error(\`[\${PERSONA.name.toLowerCase()}] Seeded vault with \${seeded} intelligence entries\`);
52
+ } else {
53
+ console.error(\`[\${PERSONA.name.toLowerCase()}] Vault is empty — ready for knowledge capture\`);
54
+ }
55
+
56
+ // Initialize planner at ~/.${config.id}/plans.json
57
+ const plansPath = join(homedir(), '.${config.id}', 'plans.json');
58
+ const planner = new Planner(plansPath);
59
+ console.error(\`[\${PERSONA.name.toLowerCase()}] Planner: \${plansPath}\`);
60
+
61
+ // Initialize brain — intelligence layer for ranked search, auto-tagging, dedup
62
+ const brain = new Brain(vault);
63
+ console.error(\`[\${PERSONA.name.toLowerCase()}] Brain: vocabulary \${brain.getVocabularySize()} terms\`);
64
+
65
+ // Initialize LLM client (optional — works without API keys)
66
+ const keyPoolFiles = loadKeyPoolConfig();
67
+ const openaiKeyPool = new KeyPool(keyPoolFiles.openai);
68
+ const anthropicKeyPool = new KeyPool(keyPoolFiles.anthropic);
69
+ const llmClient = new LLMClient(openaiKeyPool, anthropicKeyPool);
70
+ const llmAvail = llmClient.isAvailable();
71
+ console.error(\`[\${PERSONA.name.toLowerCase()}] LLM: OpenAI \${llmAvail.openai ? 'available' : 'not configured'}, Anthropic \${llmAvail.anthropic ? 'available' : 'not configured'}\`);
72
+
73
+ // Create MCP server
74
+ const server = new McpServer({
75
+ name: '${config.id}-mcp',
76
+ version: '1.0.0',
77
+ });
78
+
79
+ // Register persona prompt
80
+ server.prompt('persona', 'Get agent persona and principles', async () => ({
81
+ messages: [{ role: 'assistant' as const, content: { type: 'text' as const, text: getPersonaPrompt() } }],
82
+ }));
83
+
84
+ // Create and register facades
85
+ const facades = [
86
+ ${facadeCreations}
87
+ createCoreFacade(vault, planner, brain, llmClient, openaiKeyPool, anthropicKeyPool),
88
+ ];
89
+
90
+ registerAllFacades(server, facades);
91
+
92
+ const stats = vault.stats();
93
+ console.error(\`[\${PERSONA.name.toLowerCase()}] \${PERSONA.name} — \${PERSONA.role}\`);
94
+ console.error(\`[\${PERSONA.name.toLowerCase()}] Vault: \${stats.totalEntries} entries across \${Object.keys(stats.byDomain).length} domains\`);
95
+ console.error(\`[\${PERSONA.name.toLowerCase()}] Registered \${facades.length} facades with \${facades.reduce((sum, f) => sum + f.ops.length, 0)} operations\`);
96
+
97
+ // Stdio transport
98
+ const transport = new StdioServerTransport();
99
+ await server.connect(transport);
100
+ console.error(\`[\${PERSONA.name.toLowerCase()}] Connected via stdio transport\`);
101
+ console.error(\`[\${PERSONA.name.toLowerCase()}] Say "Hello, \${PERSONA.name}!" to activate\`);
102
+
103
+ // Graceful shutdown
104
+ const shutdown = async (): Promise<void> => {
105
+ console.error(\`[\${PERSONA.name.toLowerCase()}] Shutting down...\`);
106
+ vault.close();
107
+ process.exit(0);
108
+ };
109
+ process.on('SIGTERM', shutdown);
110
+ process.on('SIGINT', shutdown);
111
+ }
112
+
113
+ main().catch((err) => {
114
+ console.error('[${config.id}] Fatal error:', err);
115
+ process.exit(1);
116
+ });
117
+ `;
118
+ }
119
+
120
+ function pascalCase(s: string): string {
121
+ return s
122
+ .split(/[-_\s]+/)
123
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
124
+ .join('');
125
+ }
@@ -0,0 +1,62 @@
1
+ export function generateFacadeFactory(): string {
2
+ return `import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { z } from 'zod';
4
+ import type { FacadeConfig, FacadeResponse } from './types.js';
5
+
6
+ export function registerFacade(server: McpServer, facade: FacadeConfig): void {
7
+ const opNames = facade.ops.map((o) => o.name);
8
+
9
+ server.tool(
10
+ facade.name,
11
+ \`\${facade.description}\\n\\nOperations: \${opNames.join(', ')}\`,
12
+ {
13
+ op: z.string().describe(\`Operation: \${opNames.join(' | ')}\`),
14
+ params: z.record(z.unknown()).optional().default({}).describe('Operation parameters'),
15
+ },
16
+ async ({ op, params }): Promise<{ content: Array<{ type: 'text'; text: string }> }> => {
17
+ const response = await dispatchOp(facade, op, params);
18
+ return { content: [{ type: 'text' as const, text: JSON.stringify(response, null, 2) }] };
19
+ },
20
+ );
21
+ }
22
+
23
+ async function dispatchOp(
24
+ facade: FacadeConfig,
25
+ opName: string,
26
+ params: Record<string, unknown>,
27
+ ): Promise<FacadeResponse> {
28
+ const op = facade.ops.find((o) => o.name === opName);
29
+ if (!op) {
30
+ return {
31
+ success: false,
32
+ error: \`Unknown operation "\${opName}" on \${facade.name}. Available: \${facade.ops.map((o) => o.name).join(', ')}\`,
33
+ op: opName,
34
+ facade: facade.name,
35
+ };
36
+ }
37
+
38
+ try {
39
+ let validatedParams = params;
40
+ if (op.schema) {
41
+ const result = op.schema.safeParse(params);
42
+ if (!result.success) {
43
+ return { success: false, error: \`Invalid params for \${opName}: \${result.error.message}\`, op: opName, facade: facade.name };
44
+ }
45
+ validatedParams = result.data as Record<string, unknown>;
46
+ }
47
+
48
+ const data = await op.handler(validatedParams);
49
+ return { success: true, data, op: opName, facade: facade.name };
50
+ } catch (err) {
51
+ const message = err instanceof Error ? err.message : String(err);
52
+ return { success: false, error: message, op: opName, facade: facade.name };
53
+ }
54
+ }
55
+
56
+ export function registerAllFacades(server: McpServer, facades: FacadeConfig[]): void {
57
+ for (const facade of facades) {
58
+ registerFacade(server, facade);
59
+ }
60
+ }
61
+ `;
62
+ }
@@ -0,0 +1,45 @@
1
+ export function generateFacadeTypes(): string {
2
+ return `import { z } from 'zod';
3
+
4
+ /** Handler function for a single facade operation */
5
+ export type OpHandler = (params: Record<string, unknown>) => Promise<unknown>;
6
+
7
+ /** Auth level required for an operation */
8
+ export type AuthLevel = 'read' | 'write' | 'admin';
9
+
10
+ /** Operation definition within a facade */
11
+ export interface OpDefinition {
12
+ name: string;
13
+ description: string;
14
+ auth: AuthLevel;
15
+ handler: OpHandler;
16
+ schema?: z.ZodType;
17
+ }
18
+
19
+ /** Facade configuration — one MCP tool */
20
+ export interface FacadeConfig {
21
+ /** MCP tool name */
22
+ name: string;
23
+ /** Human-readable description */
24
+ description: string;
25
+ /** Domain operations */
26
+ ops: OpDefinition[];
27
+ }
28
+
29
+ /** Standard facade response envelope */
30
+ export interface FacadeResponse {
31
+ success: boolean;
32
+ data?: unknown;
33
+ error?: string;
34
+ op?: string;
35
+ facade?: string;
36
+ }
37
+
38
+ export const facadeInputSchema = z.object({
39
+ op: z.string().describe('Operation name'),
40
+ params: z.record(z.unknown()).optional().default({}),
41
+ });
42
+
43
+ export type FacadeInput = z.infer<typeof facadeInputSchema>;
44
+ `;
45
+ }
@@ -0,0 +1,94 @@
1
+ import type { AgentConfig } from '../types.js';
2
+
3
+ /**
4
+ * Generates src/activation/inject-claude-md.ts for a new agent.
5
+ * Provides idempotent CLAUDE.md injection — creates, appends, or updates
6
+ * the agent's section between HTML comment markers.
7
+ * Supports both project-level and global (~/.claude/CLAUDE.md) injection.
8
+ *
9
+ * Uses array-joined pattern because the generated code contains
10
+ * template literals (backticks) for path operations and string interpolation.
11
+ */
12
+ export function generateInjectClaudeMd(config: AgentConfig): string {
13
+ const marker = `${config.id}:mode`;
14
+
15
+ return [
16
+ "import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';",
17
+ "import { homedir } from 'node:os';",
18
+ "import { join } from 'node:path';",
19
+ "import { getClaudeMdContent, getClaudeMdMarker } from './claude-md-content.js';",
20
+ '',
21
+ 'export interface InjectResult {',
22
+ ' injected: boolean;',
23
+ ' path: string;',
24
+ " action: 'created' | 'updated' | 'appended';",
25
+ '}',
26
+ '',
27
+ '/**',
28
+ ' * Inject into a specific CLAUDE.md file path.',
29
+ ' * Shared logic for both project-level and global injection.',
30
+ ' */',
31
+ 'function injectIntoFile(filePath: string): InjectResult {',
32
+ ' const content = getClaudeMdContent();',
33
+ ' const marker = getClaudeMdMarker();',
34
+ ` const startMarker = '<!-- ' + marker + ' -->';`,
35
+ ` const endMarker = '<!-- /' + marker + ' -->';`,
36
+ '',
37
+ ' if (!existsSync(filePath)) {',
38
+ " writeFileSync(filePath, content + '\\n', 'utf-8');",
39
+ " return { injected: true, path: filePath, action: 'created' };",
40
+ ' }',
41
+ '',
42
+ " const existing = readFileSync(filePath, 'utf-8');",
43
+ '',
44
+ ' if (existing.includes(startMarker)) {',
45
+ ' const startIdx = existing.indexOf(startMarker);',
46
+ ' const endIdx = existing.indexOf(endMarker);',
47
+ ' if (endIdx === -1) {',
48
+ " const updated = existing.slice(0, startIdx) + content + '\\n' + existing.slice(startIdx + startMarker.length);",
49
+ " writeFileSync(filePath, updated, 'utf-8');",
50
+ " return { injected: true, path: filePath, action: 'updated' };",
51
+ ' }',
52
+ ' const updated = existing.slice(0, startIdx) + content + existing.slice(endIdx + endMarker.length);',
53
+ " writeFileSync(filePath, updated, 'utf-8');",
54
+ " return { injected: true, path: filePath, action: 'updated' };",
55
+ ' }',
56
+ '',
57
+ " const separator = existing.endsWith('\\n') ? '\\n' : '\\n\\n';",
58
+ " writeFileSync(filePath, existing + separator + content + '\\n', 'utf-8');",
59
+ " return { injected: true, path: filePath, action: 'appended' };",
60
+ '}',
61
+ '',
62
+ '/**',
63
+ ' * Inject agent CLAUDE.md section into a project.',
64
+ ' * - If no CLAUDE.md exists: creates one',
65
+ ' * - If markers found: replaces content between them (update)',
66
+ ' * - If no markers: appends section to end',
67
+ ' */',
68
+ 'export function injectClaudeMd(projectPath: string): InjectResult {',
69
+ " return injectIntoFile(join(projectPath, 'CLAUDE.md'));",
70
+ '}',
71
+ '',
72
+ '/**',
73
+ ' * Inject agent CLAUDE.md section into the global ~/.claude/CLAUDE.md.',
74
+ " * Creates ~/.claude/ directory if it doesn't exist.",
75
+ ' * This makes the activation phrase work in any project.',
76
+ ' */',
77
+ 'export function injectClaudeMdGlobal(): InjectResult {',
78
+ " const claudeDir = join(homedir(), '.claude');",
79
+ ' if (!existsSync(claudeDir)) {',
80
+ ' mkdirSync(claudeDir, { recursive: true });',
81
+ ' }',
82
+ " return injectIntoFile(join(claudeDir, 'CLAUDE.md'));",
83
+ '}',
84
+ '',
85
+ '/**',
86
+ ' * Check if the agent marker exists in a CLAUDE.md file.',
87
+ ' */',
88
+ 'export function hasAgentMarker(filePath: string): boolean {',
89
+ ' if (!existsSync(filePath)) return false;',
90
+ " const content = readFileSync(filePath, 'utf-8');",
91
+ ` return content.includes('<!-- ${marker} -->');`,
92
+ '}',
93
+ ].join('\n');
94
+ }
@@ -0,0 +1,42 @@
1
+ export function generateIntelligenceLoader(): string {
2
+ return `import { readFileSync, readdirSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import type { IntelligenceBundle, IntelligenceEntry } from './types.js';
5
+
6
+ export function loadIntelligenceData(dataDir: string): IntelligenceEntry[] {
7
+ const entries: IntelligenceEntry[] = [];
8
+ let files: string[];
9
+ try {
10
+ files = readdirSync(dataDir).filter((f) => f.endsWith('.json'));
11
+ } catch {
12
+ console.warn('Intelligence data directory not found: ' + dataDir);
13
+ return entries;
14
+ }
15
+
16
+ for (const file of files) {
17
+ try {
18
+ const raw = readFileSync(join(dataDir, file), 'utf-8');
19
+ const bundle = JSON.parse(raw) as IntelligenceBundle;
20
+ if (!bundle.entries || !Array.isArray(bundle.entries)) continue;
21
+ for (const entry of bundle.entries) {
22
+ if (validateEntry(entry)) entries.push(entry);
23
+ }
24
+ } catch (err) {
25
+ console.warn('Failed to load ' + file + ': ' + (err instanceof Error ? err.message : err));
26
+ }
27
+ }
28
+ return entries;
29
+ }
30
+
31
+ function validateEntry(entry: IntelligenceEntry): boolean {
32
+ return (
33
+ typeof entry.id === 'string' && entry.id.length > 0 &&
34
+ ['pattern', 'anti-pattern', 'rule'].includes(entry.type) &&
35
+ typeof entry.title === 'string' && entry.title.length > 0 &&
36
+ typeof entry.description === 'string' && entry.description.length > 0 &&
37
+ ['critical', 'warning', 'suggestion'].includes(entry.severity) &&
38
+ Array.isArray(entry.tags)
39
+ );
40
+ }
41
+ `;
42
+ }
@@ -0,0 +1,23 @@
1
+ export function generateIntelligenceTypes(): string {
2
+ return `export interface IntelligenceEntry {
3
+ id: string;
4
+ type: 'pattern' | 'anti-pattern' | 'rule';
5
+ domain: string;
6
+ title: string;
7
+ severity: 'critical' | 'warning' | 'suggestion';
8
+ description: string;
9
+ context?: string;
10
+ example?: string;
11
+ counterExample?: string;
12
+ why?: string;
13
+ tags: string[];
14
+ appliesTo?: string[];
15
+ }
16
+
17
+ export interface IntelligenceBundle {
18
+ domain: string;
19
+ version: string;
20
+ entries: IntelligenceEntry[];
21
+ }
22
+ `;
23
+ }
@@ -0,0 +1,302 @@
1
+ import type { AgentConfig } from '../types.js';
2
+
3
+ /**
4
+ * Generate the LLM client file for a new agent.
5
+ * Contains LLMClient (OpenAI fetch + Anthropic SDK) and ModelRouter (inlined).
6
+ * Uses config.id to resolve ~/.{agentId}/model-routing.json.
7
+ */
8
+ export function generateLLMClient(config: AgentConfig): string {
9
+ return `/**
10
+ * LLM Client — Unified OpenAI/Anthropic caller with key pool rotation
11
+ * Generated by Soleri — do not edit manually.
12
+ */
13
+
14
+ import Anthropic from '@anthropic-ai/sdk';
15
+ import { SecretString, LLMError } from './types.js';
16
+ import type {
17
+ LLMCallOptions,
18
+ LLMCallResult,
19
+ RouteEntry,
20
+ RoutingConfig,
21
+ } from './types.js';
22
+ import { CircuitBreaker, retry, parseRateLimitHeaders } from './utils.js';
23
+ import type { KeyPool } from './key-pool.js';
24
+ import * as fs from 'node:fs';
25
+ import * as path from 'node:path';
26
+ import { homedir } from 'node:os';
27
+
28
+ // =============================================================================
29
+ // CONSTANTS
30
+ // =============================================================================
31
+
32
+ const OPENAI_API_URL = 'https://api.openai.com/v1/chat/completions';
33
+
34
+ // =============================================================================
35
+ // MODEL ROUTER (inlined)
36
+ // =============================================================================
37
+
38
+ function loadRoutingConfig(): RoutingConfig {
39
+ const defaultConfig: RoutingConfig = {
40
+ routes: [],
41
+ defaultOpenAIModel: 'gpt-4o-mini',
42
+ defaultAnthropicModel: 'claude-sonnet-4-20250514',
43
+ };
44
+
45
+ const configPath = path.join(
46
+ homedir(),
47
+ '.${config.id}',
48
+ 'model-routing.json',
49
+ );
50
+
51
+ try {
52
+ if (fs.existsSync(configPath)) {
53
+ const data = JSON.parse(fs.readFileSync(configPath, 'utf-8')) as Partial<RoutingConfig>;
54
+ if (data.routes && Array.isArray(data.routes)) {
55
+ defaultConfig.routes = data.routes;
56
+ }
57
+ if (data.defaultOpenAIModel) {
58
+ defaultConfig.defaultOpenAIModel = data.defaultOpenAIModel;
59
+ }
60
+ if (data.defaultAnthropicModel) {
61
+ defaultConfig.defaultAnthropicModel = data.defaultAnthropicModel;
62
+ }
63
+ }
64
+ } catch {
65
+ // Config not available — use defaults
66
+ }
67
+
68
+ return defaultConfig;
69
+ }
70
+
71
+ function inferProvider(model: string): 'openai' | 'anthropic' {
72
+ if (model.startsWith('claude-') || model.startsWith('anthropic/')) {
73
+ return 'anthropic';
74
+ }
75
+ return 'openai';
76
+ }
77
+
78
+ class ModelRouter {
79
+ private config: RoutingConfig;
80
+
81
+ constructor(config?: RoutingConfig) {
82
+ this.config = config || loadRoutingConfig();
83
+ }
84
+
85
+ resolve(
86
+ caller: string,
87
+ task?: string,
88
+ originalModel?: string,
89
+ ): { model: string; provider: 'openai' | 'anthropic' } {
90
+ if (task) {
91
+ const exactMatch = this.config.routes.find(
92
+ (r) => r.caller === caller && r.task === task,
93
+ );
94
+ if (exactMatch) {
95
+ return { model: exactMatch.model, provider: exactMatch.provider };
96
+ }
97
+ }
98
+
99
+ const callerMatch = this.config.routes.find(
100
+ (r) => r.caller === caller && !r.task,
101
+ );
102
+ if (callerMatch) {
103
+ return { model: callerMatch.model, provider: callerMatch.provider };
104
+ }
105
+
106
+ if (originalModel) {
107
+ const provider = inferProvider(originalModel);
108
+ return { model: originalModel, provider };
109
+ }
110
+
111
+ return { model: this.config.defaultOpenAIModel, provider: 'openai' };
112
+ }
113
+
114
+ getRoutes(): RouteEntry[] {
115
+ return [...this.config.routes];
116
+ }
117
+ }
118
+
119
+ // =============================================================================
120
+ // LLM CLIENT
121
+ // =============================================================================
122
+
123
+ export class LLMClient {
124
+ private openaiKeyPool: KeyPool;
125
+ private anthropicKeyPool: KeyPool;
126
+ private anthropicClient: Anthropic | null = null;
127
+ private anthropicBreaker: CircuitBreaker;
128
+ private anthropicKeyFingerprint: string = '';
129
+ private router: ModelRouter;
130
+
131
+ constructor(openaiKeyPool: KeyPool, anthropicKeyPool: KeyPool) {
132
+ this.openaiKeyPool = openaiKeyPool;
133
+ this.anthropicKeyPool = anthropicKeyPool;
134
+ this.anthropicBreaker = new CircuitBreaker({
135
+ name: 'llm-anthropic',
136
+ failureThreshold: 5,
137
+ resetTimeoutMs: 60_000,
138
+ });
139
+ this.router = new ModelRouter();
140
+ }
141
+
142
+ async complete(options: LLMCallOptions): Promise<LLMCallResult> {
143
+ const routed = this.router.resolve(
144
+ options.caller,
145
+ options.task,
146
+ options.model,
147
+ );
148
+ const resolvedOptions = { ...options, model: routed.model, provider: routed.provider };
149
+
150
+ return resolvedOptions.provider === 'anthropic'
151
+ ? this.callAnthropic(resolvedOptions)
152
+ : this.callOpenAI(resolvedOptions);
153
+ }
154
+
155
+ isAvailable(): { openai: boolean; anthropic: boolean } {
156
+ return {
157
+ openai: this.openaiKeyPool.hasKeys,
158
+ anthropic: this.anthropicKeyPool.hasKeys,
159
+ };
160
+ }
161
+
162
+ getRoutes(): RouteEntry[] {
163
+ return this.router.getRoutes();
164
+ }
165
+
166
+ // ===========================================================================
167
+ // OPENAI
168
+ // ===========================================================================
169
+
170
+ private async callOpenAI(options: LLMCallOptions): Promise<LLMCallResult> {
171
+ const keyPool = this.openaiKeyPool.hasKeys ? this.openaiKeyPool : null;
172
+
173
+ if (!keyPool) {
174
+ throw new LLMError('OpenAI API key not configured', { retryable: false });
175
+ }
176
+
177
+ const start = Date.now();
178
+
179
+ const doRequest = async (): Promise<LLMCallResult> => {
180
+ const apiKey = keyPool.getActiveKey().expose();
181
+ const keyIndex = keyPool.activeKeyIndex;
182
+
183
+ const response = await fetch(OPENAI_API_URL, {
184
+ method: 'POST',
185
+ headers: {
186
+ 'Content-Type': 'application/json',
187
+ Authorization: \`Bearer \${apiKey}\`,
188
+ },
189
+ body: JSON.stringify({
190
+ model: options.model,
191
+ messages: [
192
+ { role: 'system', content: options.systemPrompt },
193
+ { role: 'user', content: options.userPrompt },
194
+ ],
195
+ temperature: options.temperature ?? 0.3,
196
+ max_completion_tokens: options.maxTokens ?? 500,
197
+ }),
198
+ });
199
+
200
+ if (response.headers) {
201
+ const rateLimits = parseRateLimitHeaders(response.headers);
202
+ if (rateLimits.remaining !== null) {
203
+ keyPool.updateQuota(keyIndex, rateLimits.remaining);
204
+ keyPool.rotatePreemptive();
205
+ }
206
+ }
207
+
208
+ if (!response.ok) {
209
+ if (response.status === 429 && keyPool.poolSize > 1) {
210
+ keyPool.rotateOnError();
211
+ }
212
+
213
+ const errorBody = await response.text();
214
+ throw new LLMError(
215
+ \`OpenAI API error: \${response.status} - \${errorBody}\`,
216
+ { retryable: response.status === 429 || response.status >= 500, statusCode: response.status },
217
+ );
218
+ }
219
+
220
+ const data = (await response.json()) as {
221
+ choices: Array<{ message: { content: string } }>;
222
+ usage?: { prompt_tokens?: number; completion_tokens?: number };
223
+ };
224
+
225
+ return {
226
+ text: data.choices[0]?.message?.content || '',
227
+ model: options.model,
228
+ provider: 'openai' as const,
229
+ inputTokens: data.usage?.prompt_tokens,
230
+ outputTokens: data.usage?.completion_tokens,
231
+ durationMs: Date.now() - start,
232
+ };
233
+ };
234
+
235
+ return retry(doRequest, { maxAttempts: 3 });
236
+ }
237
+
238
+ // ===========================================================================
239
+ // ANTHROPIC
240
+ // ===========================================================================
241
+
242
+ private async callAnthropic(options: LLMCallOptions): Promise<LLMCallResult> {
243
+ const client = this.getAnthropicClient();
244
+ if (!client) {
245
+ throw new LLMError('Anthropic API key not configured', { retryable: false });
246
+ }
247
+
248
+ const start = Date.now();
249
+
250
+ return this.anthropicBreaker.call(() =>
251
+ retry(
252
+ async () => {
253
+ const response = await client.messages.create(
254
+ {
255
+ model: options.model,
256
+ max_tokens: options.maxTokens ?? 1024,
257
+ system: options.systemPrompt,
258
+ messages: [{ role: 'user', content: options.userPrompt }],
259
+ },
260
+ { timeout: 60_000 },
261
+ );
262
+
263
+ const text = response.content
264
+ .filter(
265
+ (block): block is Anthropic.TextBlock => block.type === 'text',
266
+ )
267
+ .map((block) => block.text)
268
+ .join('\\n');
269
+
270
+ return {
271
+ text,
272
+ model: options.model,
273
+ provider: 'anthropic' as const,
274
+ inputTokens: response.usage?.input_tokens,
275
+ outputTokens: response.usage?.output_tokens,
276
+ durationMs: Date.now() - start,
277
+ };
278
+ },
279
+ { maxAttempts: 2 },
280
+ ),
281
+ );
282
+ }
283
+
284
+ private getAnthropicClient(): Anthropic | null {
285
+ if (!this.anthropicKeyPool.hasKeys) return null;
286
+
287
+ const currentKey = this.anthropicKeyPool.getActiveKey().expose();
288
+ const currentFingerprint = currentKey.slice(-8);
289
+
290
+ if (currentFingerprint !== this.anthropicKeyFingerprint) {
291
+ this.anthropicClient = null;
292
+ this.anthropicKeyFingerprint = currentFingerprint;
293
+ }
294
+
295
+ if (this.anthropicClient) return this.anthropicClient;
296
+
297
+ this.anthropicClient = new Anthropic({ apiKey: currentKey });
298
+ return this.anthropicClient;
299
+ }
300
+ }
301
+ `;
302
+ }