@nestbox-ai/cli 1.0.63 → 1.0.64

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.
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.runReportComposerAgent = runReportComposerAgent;
16
+ const sdk_1 = __importDefault(require("@anthropic-ai/sdk"));
17
+ const fs_1 = __importDefault(require("fs"));
18
+ const path_1 = __importDefault(require("path"));
19
+ const js_yaml_1 = __importDefault(require("js-yaml"));
20
+ const ajv_1 = __importDefault(require("ajv"));
21
+ // ─── Constants ────────────────────────────────────────────────────────────────
22
+ const AGENTS_DIR = __dirname;
23
+ const DEFAULT_MODEL = 'claude-sonnet-4-6';
24
+ const DEFAULT_MAX_ITERATIONS = 5;
25
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
26
+ function readLocalFile(filename) {
27
+ return fs_1.default.readFileSync(path_1.default.join(AGENTS_DIR, filename), 'utf8');
28
+ }
29
+ function validateYaml(content, schemaContent) {
30
+ var _a;
31
+ // Replace ${ENV_VAR} and ${ENV_VAR:-default} references with a plain string
32
+ // so YAML parses cleanly and AJV treats them as valid string values.
33
+ const preprocessed = content.replace(/\$\{[^}]+\}/g, 'env-var-placeholder');
34
+ let data;
35
+ try {
36
+ data = js_yaml_1.default.load(preprocessed);
37
+ }
38
+ catch (e) {
39
+ return { valid: false, errors: [`YAML parse error: ${e.message}`] };
40
+ }
41
+ let schema;
42
+ try {
43
+ schema = js_yaml_1.default.load(schemaContent);
44
+ }
45
+ catch (e) {
46
+ return { valid: false, errors: [`Schema parse error: ${e.message}`] };
47
+ }
48
+ const ajv = new ajv_1.default({ strict: false, allErrors: true });
49
+ // Suppress "unknown format 'uri' ignored" console warnings from AJV
50
+ ajv.addFormat('uri', () => true);
51
+ const validate = ajv.compile(schema);
52
+ const ok = validate(data);
53
+ if (ok)
54
+ return { valid: true, errors: [] };
55
+ const errors = ((_a = validate.errors) !== null && _a !== void 0 ? _a : []).map((err) => {
56
+ const loc = err.instancePath || '(root)';
57
+ return `[${loc}] ${err.message}`;
58
+ });
59
+ return { valid: false, errors };
60
+ }
61
+ // ─── System Prompt ────────────────────────────────────────────────────────────
62
+ function buildSystemPrompt() {
63
+ const systemPrompt = readLocalFile('SYSTEM_PROMPT.md');
64
+ const configGuide = readLocalFile('REPORT_CONFIG_GUIDE.md');
65
+ const example1 = readLocalFile('annual_report_10k.yaml');
66
+ const example2 = readLocalFile('vc_portfolio_monitoring.yaml');
67
+ return [
68
+ systemPrompt,
69
+ '---',
70
+ configGuide,
71
+ '---',
72
+ '# Example 1: Annual Report / 10-K Analysis\n\n```yaml\n' + example1 + '\n```',
73
+ '---',
74
+ '# Example 2: VC Portfolio Monitoring\n\n```yaml\n' + example2 + '\n```',
75
+ ].join('\n\n');
76
+ }
77
+ // ─── Tool Definitions ─────────────────────────────────────────────────────────
78
+ const TOOLS = [
79
+ {
80
+ name: 'write_and_validate_report',
81
+ description: 'Write the report.yaml content and validate it against the schema. Returns "VALID" on success or a list of validation errors to fix.',
82
+ input_schema: {
83
+ type: 'object',
84
+ properties: {
85
+ yaml_content: {
86
+ type: 'string',
87
+ description: 'The complete YAML content for report.yaml',
88
+ },
89
+ },
90
+ required: ['yaml_content'],
91
+ },
92
+ },
93
+ {
94
+ name: 'finish',
95
+ description: 'Signal that the report.yaml is complete and valid. Call this only after write_and_validate_report has returned "VALID".',
96
+ input_schema: {
97
+ type: 'object',
98
+ properties: {
99
+ summary: {
100
+ type: 'string',
101
+ description: 'Brief summary of what was generated and why key choices were made',
102
+ },
103
+ },
104
+ required: ['summary'],
105
+ },
106
+ },
107
+ ];
108
+ // ─── Agent ────────────────────────────────────────────────────────────────────
109
+ function runReportComposerAgent(options) {
110
+ return __awaiter(this, void 0, void 0, function* () {
111
+ const { instructions, anthropicApiKey, model = DEFAULT_MODEL, maxIterations = DEFAULT_MAX_ITERATIONS, onProgress = () => { }, } = options;
112
+ const reportSchema = readLocalFile('report_config.schema.yaml');
113
+ const client = new sdk_1.default({ apiKey: anthropicApiKey });
114
+ // Mutable state updated by tool calls
115
+ let latestReport = '';
116
+ let reportValid = false;
117
+ let finished = false;
118
+ let iteration = 0;
119
+ // Execute a tool call and return the result string
120
+ function executeTool(name, input) {
121
+ var _a;
122
+ if (name === 'write_and_validate_report') {
123
+ const content = (_a = input.yaml_content) !== null && _a !== void 0 ? _a : '';
124
+ latestReport = content;
125
+ const result = validateYaml(content, reportSchema);
126
+ reportValid = result.valid;
127
+ if (result.valid)
128
+ return 'VALID';
129
+ return `VALIDATION ERRORS — fix all of these before calling again:\n${result.errors.map((e) => ` • ${e}`).join('\n')}`;
130
+ }
131
+ if (name === 'finish') {
132
+ if (!reportValid) {
133
+ return 'Cannot finish: the report has not passed schema validation yet. Call write_and_validate_report first and ensure it returns "VALID".';
134
+ }
135
+ finished = true;
136
+ return 'Done.';
137
+ }
138
+ return `Unknown tool: ${name}`;
139
+ }
140
+ // Build the system prompt once and mark it for caching.
141
+ // On iteration 1 the prompt is written to the cache (normal price).
142
+ // On iterations 2+ the large system prompt is read from cache at
143
+ // 10% of the normal input token price.
144
+ const systemPromptText = buildSystemPrompt();
145
+ const systemPrompt = [
146
+ {
147
+ type: 'text',
148
+ text: systemPromptText,
149
+ cache_control: { type: 'ephemeral' },
150
+ },
151
+ ];
152
+ const messages = [
153
+ {
154
+ role: 'user',
155
+ content: `Here are the instructions for the report you need to configure:\n\n${instructions}\n\nGenerate the report.yaml file now. Use the tools to write and validate it.`,
156
+ },
157
+ ];
158
+ onProgress('Starting agent...');
159
+ while (iteration < maxIterations && !finished) {
160
+ iteration++;
161
+ onProgress(`Iteration ${iteration}/${maxIterations} — calling Claude...`);
162
+ const response = yield client.messages.create({
163
+ model,
164
+ max_tokens: 8096,
165
+ system: systemPrompt,
166
+ tools: TOOLS,
167
+ // Force Claude to call a tool every turn — prevents it from
168
+ // replying with plain text and exiting the loop prematurely.
169
+ tool_choice: { type: 'any' },
170
+ messages,
171
+ });
172
+ // Append assistant turn
173
+ messages.push({ role: 'assistant', content: response.content });
174
+ if (response.stop_reason !== 'tool_use') {
175
+ onProgress(`Agent stopped unexpectedly: ${response.stop_reason}`);
176
+ break;
177
+ }
178
+ // Process all tool calls and collect results
179
+ const toolResults = [];
180
+ for (const block of response.content) {
181
+ if (block.type !== 'tool_use')
182
+ continue;
183
+ onProgress(` → tool: ${block.name}`);
184
+ const result = executeTool(block.name, block.input);
185
+ onProgress(` ${result.startsWith('VALID') ? '✓ valid' : result.split('\n')[0]}`);
186
+ toolResults.push({
187
+ type: 'tool_result',
188
+ tool_use_id: block.id,
189
+ content: result,
190
+ });
191
+ if (finished)
192
+ break;
193
+ }
194
+ if (toolResults.length > 0) {
195
+ messages.push({ role: 'user', content: toolResults });
196
+ }
197
+ if (finished)
198
+ break;
199
+ }
200
+ if (iteration >= maxIterations && !finished) {
201
+ onProgress(`Warning: reached max iterations (${maxIterations}) without finishing.`);
202
+ }
203
+ return {
204
+ reportYaml: latestReport,
205
+ iterations: iteration,
206
+ reportValid,
207
+ };
208
+ });
209
+ }
210
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/agents/reportGenerator/index.ts"],"names":[],"mappings":";;;;;;;;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