deepclause-sdk 0.0.1

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 (111) hide show
  1. package/README.md +446 -0
  2. package/dist/agent.d.ts +44 -0
  3. package/dist/agent.d.ts.map +1 -0
  4. package/dist/agent.js +518 -0
  5. package/dist/agent.js.map +1 -0
  6. package/dist/cli/commands.d.ts +37 -0
  7. package/dist/cli/commands.d.ts.map +1 -0
  8. package/dist/cli/commands.js +105 -0
  9. package/dist/cli/commands.js.map +1 -0
  10. package/dist/cli/compile.d.ts +88 -0
  11. package/dist/cli/compile.d.ts.map +1 -0
  12. package/dist/cli/compile.js +362 -0
  13. package/dist/cli/compile.js.map +1 -0
  14. package/dist/cli/config.d.ts +265 -0
  15. package/dist/cli/config.d.ts.map +1 -0
  16. package/dist/cli/config.js +272 -0
  17. package/dist/cli/config.js.map +1 -0
  18. package/dist/cli/index.d.ts +8 -0
  19. package/dist/cli/index.d.ts.map +1 -0
  20. package/dist/cli/index.js +287 -0
  21. package/dist/cli/index.js.map +1 -0
  22. package/dist/cli/mcp.d.ts +56 -0
  23. package/dist/cli/mcp.d.ts.map +1 -0
  24. package/dist/cli/mcp.js +138 -0
  25. package/dist/cli/mcp.js.map +1 -0
  26. package/dist/cli/prompt.d.ts +20 -0
  27. package/dist/cli/prompt.d.ts.map +1 -0
  28. package/dist/cli/prompt.js +669 -0
  29. package/dist/cli/prompt.js.map +1 -0
  30. package/dist/cli/run.d.ts +33 -0
  31. package/dist/cli/run.d.ts.map +1 -0
  32. package/dist/cli/run.js +429 -0
  33. package/dist/cli/run.js.map +1 -0
  34. package/dist/cli/search.d.ts +25 -0
  35. package/dist/cli/search.d.ts.map +1 -0
  36. package/dist/cli/search.js +125 -0
  37. package/dist/cli/search.js.map +1 -0
  38. package/dist/cli/tools.d.ts +36 -0
  39. package/dist/cli/tools.d.ts.map +1 -0
  40. package/dist/cli/tools.js +204 -0
  41. package/dist/cli/tools.js.map +1 -0
  42. package/dist/cli/tui/index.d.ts +22 -0
  43. package/dist/cli/tui/index.d.ts.map +1 -0
  44. package/dist/cli/tui/index.js +29 -0
  45. package/dist/cli/tui/index.js.map +1 -0
  46. package/dist/index.d.ts +9 -0
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +8 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/prolog/bridge.d.ts +21 -0
  51. package/dist/prolog/bridge.d.ts.map +1 -0
  52. package/dist/prolog/bridge.js +226 -0
  53. package/dist/prolog/bridge.js.map +1 -0
  54. package/dist/prolog/loader.d.ts +40 -0
  55. package/dist/prolog/loader.d.ts.map +1 -0
  56. package/dist/prolog/loader.js +133 -0
  57. package/dist/prolog/loader.js.map +1 -0
  58. package/dist/prolog-src/deepclause_memory.pl +45 -0
  59. package/dist/prolog-src/deepclause_mi.pl +1978 -0
  60. package/dist/prolog-src/deepclause_mi.pl.bak +570 -0
  61. package/dist/prolog-src/deepclause_strings.pl +89 -0
  62. package/dist/runner.d.ts +143 -0
  63. package/dist/runner.d.ts.map +1 -0
  64. package/dist/runner.js +1095 -0
  65. package/dist/runner.js.map +1 -0
  66. package/dist/sdk.d.ts +9 -0
  67. package/dist/sdk.d.ts.map +1 -0
  68. package/dist/sdk.js +131 -0
  69. package/dist/sdk.js.map +1 -0
  70. package/dist/tools.d.ts +22 -0
  71. package/dist/tools.d.ts.map +1 -0
  72. package/dist/tools.js +138 -0
  73. package/dist/tools.js.map +1 -0
  74. package/dist/types.d.ts +186 -0
  75. package/dist/types.d.ts.map +1 -0
  76. package/dist/types.js +5 -0
  77. package/dist/types.js.map +1 -0
  78. package/package.json +79 -0
  79. package/src/prolog-src/deepclause_memory.pl +45 -0
  80. package/src/prolog-src/deepclause_mi.pl +1978 -0
  81. package/src/prolog-src/deepclause_mi.pl.bak +570 -0
  82. package/src/prolog-src/deepclause_strings.pl +89 -0
  83. package/vendor/swipl-wasm/LICENSE.txt +41 -0
  84. package/vendor/swipl-wasm/dist/bin/index.js +25 -0
  85. package/vendor/swipl-wasm/dist/common.d.ts +88 -0
  86. package/vendor/swipl-wasm/dist/generateImage.d.ts +6 -0
  87. package/vendor/swipl-wasm/dist/generateImage.js +76 -0
  88. package/vendor/swipl-wasm/dist/index.d.ts +2 -0
  89. package/vendor/swipl-wasm/dist/index.js +1 -0
  90. package/vendor/swipl-wasm/dist/loadImage.d.ts +2 -0
  91. package/vendor/swipl-wasm/dist/loadImage.js +10 -0
  92. package/vendor/swipl-wasm/dist/loadImageDefault.d.ts +2 -0
  93. package/vendor/swipl-wasm/dist/loadImageDefault.js +11 -0
  94. package/vendor/swipl-wasm/dist/strToBuffer.d.ts +8 -0
  95. package/vendor/swipl-wasm/dist/strToBuffer.js +41 -0
  96. package/vendor/swipl-wasm/dist/swipl/swipl-bundle-no-data.d.ts +2 -0
  97. package/vendor/swipl-wasm/dist/swipl/swipl-bundle-no-data.js +2 -0
  98. package/vendor/swipl-wasm/dist/swipl/swipl-bundle.d.ts +2 -0
  99. package/vendor/swipl-wasm/dist/swipl/swipl-bundle.js +2 -0
  100. package/vendor/swipl-wasm/dist/swipl/swipl-web.d.ts +2 -0
  101. package/vendor/swipl-wasm/dist/swipl/swipl-web.data +0 -0
  102. package/vendor/swipl-wasm/dist/swipl/swipl-web.js +2 -0
  103. package/vendor/swipl-wasm/dist/swipl/swipl-web.wasm +0 -0
  104. package/vendor/swipl-wasm/dist/swipl/swipl-win.js +1 -0
  105. package/vendor/swipl-wasm/dist/swipl/swipl-win.wasm +0 -0
  106. package/vendor/swipl-wasm/dist/swipl/swipl.d.ts +2 -0
  107. package/vendor/swipl-wasm/dist/swipl/swipl.js +1 -0
  108. package/vendor/swipl-wasm/dist/swipl/swipl.wasm +0 -0
  109. package/vendor/swipl-wasm/dist/swipl-node.d.ts +2 -0
  110. package/vendor/swipl-wasm/dist/swipl-node.js +17 -0
  111. package/vendor/swipl-wasm/package.json +129 -0
@@ -0,0 +1,287 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * DeepClause CLI
4
+ *
5
+ * Command-line interface for compiling Markdown to DML and running DML programs.
6
+ */
7
+ import { Command } from 'commander';
8
+ import { initConfig, setModel, showModel, loadConfig } from './config.js';
9
+ import { compile, compileAll } from './compile.js';
10
+ import { run } from './run.js';
11
+ import { listTools } from './tools.js';
12
+ import { listCommands } from './commands.js';
13
+ import { readFileSync } from 'fs';
14
+ import { fileURLToPath } from 'url';
15
+ import { dirname, join } from 'path';
16
+ // Get version from package.json
17
+ const __filename = fileURLToPath(import.meta.url);
18
+ const __dirname = dirname(__filename);
19
+ const packageJsonPath = join(__dirname, '../../package.json');
20
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
21
+ const version = packageJson.version;
22
+ const program = new Command();
23
+ program
24
+ .name('deepclause')
25
+ .description('Compile Markdown to DML and run neurosymbolic AI agents')
26
+ .version(version);
27
+ // =============================================================================
28
+ // Configuration Commands
29
+ // =============================================================================
30
+ program
31
+ .command('init')
32
+ .description('Initialize DeepClause configuration in current directory')
33
+ .option('-f, --force', 'Overwrite existing configuration')
34
+ .option('--model <model>', 'Set initial model (default: gpt-4o)')
35
+ .action(async (options) => {
36
+ try {
37
+ await initConfig(process.cwd(), options);
38
+ console.log('✅ DeepClause initialized successfully');
39
+ console.log(' Configuration: .deepclause/config.json');
40
+ }
41
+ catch (error) {
42
+ console.error('❌ Error:', error.message);
43
+ process.exit(1);
44
+ }
45
+ });
46
+ program
47
+ .command('set-model <model>')
48
+ .description('Set the default LLM model (format: provider/model or just model)')
49
+ .action(async (model) => {
50
+ try {
51
+ const result = await setModel(process.cwd(), model);
52
+ console.log(`✅ Model set to: ${result.provider}/${result.model}`);
53
+ }
54
+ catch (error) {
55
+ console.error('❌ Error:', error.message);
56
+ process.exit(1);
57
+ }
58
+ });
59
+ program
60
+ .command('show-model')
61
+ .description('Show the current LLM model')
62
+ .option('--json', 'Output as JSON')
63
+ .action(async (options) => {
64
+ try {
65
+ const result = await showModel(process.cwd());
66
+ if (options.json) {
67
+ console.log(JSON.stringify({ provider: result.provider, model: result.model }, null, 2));
68
+ }
69
+ else {
70
+ console.log(result.formatted);
71
+ }
72
+ }
73
+ catch (error) {
74
+ console.error('❌ Error:', error.message);
75
+ process.exit(1);
76
+ }
77
+ });
78
+ // =============================================================================
79
+ // Compilation Commands
80
+ // =============================================================================
81
+ program
82
+ .command('compile <source> [output]')
83
+ .description('Compile Markdown task description to DML')
84
+ .option('-f, --force', 'Force recompilation even if source unchanged')
85
+ .option('--validate-only', 'Validate without saving output')
86
+ .option('--model <model>', 'Override model for compilation')
87
+ .option('--temperature <number>', 'Override temperature (0.0-2.0)', parseFloat)
88
+ .action(async (source, output, options) => {
89
+ try {
90
+ const config = await loadConfig(process.cwd());
91
+ const outputDir = output || '.deepclause/tools';
92
+ const result = await compile(source, outputDir, {
93
+ force: options.force,
94
+ validateOnly: options.validateOnly,
95
+ model: options.model || config.model,
96
+ temperature: options.temperature
97
+ });
98
+ if (result.skipped) {
99
+ console.log(`⏭️ Skipped (unchanged): ${source}`);
100
+ }
101
+ else if (options.validateOnly) {
102
+ console.log(`✅ Valid DML generated from: ${source}`);
103
+ }
104
+ else {
105
+ console.log(`✅ Compiled: ${source} → ${result.output}`);
106
+ console.log(` Tools: ${result.tools.join(', ') || 'none'}`);
107
+ }
108
+ }
109
+ catch (error) {
110
+ console.error('❌ Error:', error.message);
111
+ process.exit(1);
112
+ }
113
+ });
114
+ program
115
+ .command('compile-all <sourceDir> [outputDir]')
116
+ .description('Compile all Markdown files in a directory')
117
+ .option('-f, --force', 'Force recompilation of all files')
118
+ .option('--model <model>', 'Override model for compilation')
119
+ .action(async (sourceDir, outputDir, options) => {
120
+ try {
121
+ const config = await loadConfig(process.cwd());
122
+ const out = outputDir || '.deepclause/tools';
123
+ const result = await compileAll(sourceDir, out, {
124
+ force: options.force,
125
+ model: options.model || config.model
126
+ });
127
+ console.log(`\n📊 Compilation Summary:`);
128
+ console.log(` Compiled: ${result.compiled}`);
129
+ console.log(` Skipped: ${result.skipped}`);
130
+ console.log(` Failed: ${result.failed}`);
131
+ }
132
+ catch (error) {
133
+ console.error('❌ Error:', error.message);
134
+ process.exit(1);
135
+ }
136
+ });
137
+ // =============================================================================
138
+ // Execution Commands
139
+ // =============================================================================
140
+ program
141
+ .command('run <file> [args...]')
142
+ .description('Execute a compiled DML program')
143
+ .option('--workspace <path>', 'Working directory for file operations', './')
144
+ .option('--verbose', 'Show debug output including tool calls')
145
+ .option('--stream', 'Stream LLM responses in real-time')
146
+ .option('--headless', 'Plain output only, no TUI formatting')
147
+ .option('--trace <file>', 'Save execution trace to file')
148
+ .option('--dry-run', 'Show what would be executed without running')
149
+ .option('--model <model>', 'Override configured model (can be provider/model format, e.g., google/gemini-2.5-pro)')
150
+ .option('--provider <provider>', 'Override configured provider (openai, anthropic, google, openrouter)')
151
+ .option('--temperature <number>', 'Override temperature (0.0-2.0)', parseFloat)
152
+ .option('-p, --param <key=value>', 'Pass named parameter (can be repeated)', collectParams, {})
153
+ .action(async (file, args, options) => {
154
+ try {
155
+ // Parse provider/model format if provided (e.g., "google/gemini-2.5-pro")
156
+ let model = options.model;
157
+ let provider = options.provider;
158
+ if (model && model.includes('/')) {
159
+ const [parsedProvider, ...modelParts] = model.split('/');
160
+ provider = provider || parsedProvider;
161
+ model = modelParts.join('/'); // Handle models with / in name
162
+ }
163
+ const result = await run(file, args, {
164
+ workspace: options.workspace,
165
+ verbose: options.verbose,
166
+ stream: options.stream,
167
+ headless: options.headless,
168
+ trace: options.trace,
169
+ dryRun: options.dryRun,
170
+ model,
171
+ provider: provider,
172
+ temperature: options.temperature,
173
+ params: options.param
174
+ });
175
+ if (options.dryRun) {
176
+ console.log(result.wouldExecute);
177
+ }
178
+ else {
179
+ // Show outputs only in headless mode (in interactive mode they were already shown)
180
+ if (options.headless && result.output.length > 0) {
181
+ for (const out of result.output) {
182
+ console.log(out);
183
+ }
184
+ }
185
+ // Show answer
186
+ if (result.answer) {
187
+ if (result.output.length > 0) {
188
+ console.log(''); // Blank line before answer
189
+ }
190
+ console.log(result.answer);
191
+ }
192
+ // Show error
193
+ if (result.error) {
194
+ console.error('❌ Error:', result.error);
195
+ process.exit(1);
196
+ }
197
+ // Show trace location if saved
198
+ if (options.trace) {
199
+ console.log(`\n📊 Trace saved to: ${options.trace}`);
200
+ }
201
+ }
202
+ }
203
+ catch (error) {
204
+ console.error('❌ Error:', error.message);
205
+ if (options.verbose) {
206
+ console.error(error.stack);
207
+ }
208
+ process.exit(1);
209
+ }
210
+ });
211
+ // =============================================================================
212
+ // Listing Commands
213
+ // =============================================================================
214
+ program
215
+ .command('list-tools')
216
+ .description('List all available tools from MCP servers and AgentVM')
217
+ .option('--json', 'Output as JSON')
218
+ .action(async (options) => {
219
+ try {
220
+ const tools = await listTools(process.cwd(), { json: options.json });
221
+ if (options.json) {
222
+ console.log(tools);
223
+ }
224
+ else {
225
+ console.log('Available Tools:\n');
226
+ console.log(tools);
227
+ }
228
+ }
229
+ catch (error) {
230
+ console.error('❌ Error:', error.message);
231
+ process.exit(1);
232
+ }
233
+ });
234
+ program
235
+ .command('list-commands')
236
+ .description('List all compiled DML commands')
237
+ .option('--json', 'Output as JSON')
238
+ .option('--detailed', 'Show parameters and tool dependencies')
239
+ .action(async (options) => {
240
+ try {
241
+ const commands = await listCommands(process.cwd(), {
242
+ json: options.json,
243
+ detailed: options.detailed
244
+ });
245
+ if (options.json) {
246
+ console.log(JSON.stringify(commands, null, 2));
247
+ }
248
+ else {
249
+ console.log('Compiled Commands:\n');
250
+ for (const cmd of commands) {
251
+ console.log(`📋 ${cmd.name}`);
252
+ console.log(` ${cmd.description}`);
253
+ if (options.detailed && cmd.parameters) {
254
+ console.log(' Parameters:');
255
+ for (const p of cmd.parameters) {
256
+ const req = p.required ? '(required)' : `(optional, default: ${p.default})`;
257
+ console.log(` • ${p.name} ${req} - ${p.description}`);
258
+ }
259
+ if (cmd.tools?.length) {
260
+ console.log(' Tool Dependencies:');
261
+ for (const t of cmd.tools) {
262
+ console.log(` • ${t}`);
263
+ }
264
+ }
265
+ }
266
+ console.log(` Usage: deepclause run ${cmd.path}\n`);
267
+ }
268
+ }
269
+ }
270
+ catch (error) {
271
+ console.error('❌ Error:', error.message);
272
+ process.exit(1);
273
+ }
274
+ });
275
+ // =============================================================================
276
+ // Helper Functions
277
+ // =============================================================================
278
+ function collectParams(value, previous) {
279
+ const [key, val] = value.split('=');
280
+ if (!key || val === undefined) {
281
+ throw new Error(`Invalid param format: ${value}. Use key=value`);
282
+ }
283
+ return { ...previous, [key]: val };
284
+ }
285
+ // Parse and run
286
+ program.parse();
287
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/cli/index.ts"],"names":[],"mappings":";AACA;;;;GAIG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC1E,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC/B,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAErC,gCAAgC;AAChC,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAClD,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;AACtC,MAAM,eAAe,GAAG,IAAI,CAAC,SAAS,EAAE,oBAAoB,CAAC,CAAC;AAC9D,MAAM,WAAW,GAAG,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;gBACH,CAAC;gBACD,OAAO,CAAC,GAAG,CAAC,4BAA4B,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC;YACxD,CAAC;QACH,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,UAAU,EAAG,KAAe,CAAC,OAAO,CAAC,CAAC;QACpD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC,CAAC,CAAC;AAEL,gFAAgF;AAChF,mBAAmB;AACnB,gFAAgF;AAEhF,SAAS,aAAa,CAAC,KAAa,EAAE,QAAgC;IACpE,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACpC,IAAI,CAAC,GAAG,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,yBAAyB,KAAK,iBAAiB,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,EAAE,GAAG,QAAQ,EAAE,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC;AACrC,CAAC;AAED,gBAAgB;AAChB,OAAO,CAAC,KAAK,EAAE,CAAC"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * DeepClause CLI - MCP (Model Context Protocol) Client Module
3
+ *
4
+ * Handles connections to MCP servers for tool discovery and execution.
5
+ *
6
+ * TODO: Full implementation requires @modelcontextprotocol/sdk package
7
+ * For now, this provides the interface and placeholder implementation.
8
+ */
9
+ import type { MCPServer } from './config.js';
10
+ import type { Tool } from './tools.js';
11
+ import type { ChildProcess } from 'child_process';
12
+ export interface MCPConnection {
13
+ server: MCPServer;
14
+ name: string;
15
+ process?: ChildProcess;
16
+ tools: Tool[];
17
+ connected: boolean;
18
+ error?: string;
19
+ }
20
+ export interface MCPToolCallResult {
21
+ success: boolean;
22
+ result?: unknown;
23
+ error?: string;
24
+ }
25
+ /**
26
+ * Connect to an MCP server and discover its tools
27
+ */
28
+ export declare function connectMCPServer(name: string, config: MCPServer): Promise<MCPConnection>;
29
+ /**
30
+ * Disconnect from an MCP server
31
+ */
32
+ export declare function disconnectMCPServer(name: string): Promise<void>;
33
+ /**
34
+ * Disconnect from all MCP servers
35
+ */
36
+ export declare function disconnectAllMCPServers(): Promise<void>;
37
+ /**
38
+ * Get tools from an MCP server
39
+ */
40
+ export declare function getMCPServerTools(name: string, config: MCPServer): Promise<Tool[]>;
41
+ /**
42
+ * Call a tool on an MCP server
43
+ */
44
+ export declare function callMCPTool(serverName: string, toolName: string, _args: Record<string, unknown>): Promise<MCPToolCallResult>;
45
+ /**
46
+ * Check if an MCP server is connected
47
+ */
48
+ export declare function isMCPServerConnected(name: string): boolean;
49
+ /**
50
+ * Get connection status for all servers
51
+ */
52
+ export declare function getMCPServerStatus(): Map<string, {
53
+ connected: boolean;
54
+ error?: string;
55
+ }>;
56
+ //# sourceMappingURL=mcp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../../src/cli/mcp.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAMlD,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,SAAS,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,YAAY,CAAC;IACvB,KAAK,EAAE,IAAI,EAAE,CAAC;IACd,SAAS,EAAE,OAAO,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAWD;;GAEG;AACH,wBAAsB,gBAAgB,CACpC,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,SAAS,GAChB,OAAO,CAAC,aAAa,CAAC,CA+CxB;AAED;;GAEG;AACH,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAUrE;AAED;;GAEG;AACH,wBAAsB,uBAAuB,IAAI,OAAO,CAAC,IAAI,CAAC,CAI7D;AAED;;GAEG;AACH,wBAAsB,iBAAiB,CACrC,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,SAAS,GAChB,OAAO,CAAC,IAAI,EAAE,CAAC,CAajB;AAED;;GAEG;AACH,wBAAsB,WAAW,CAC/B,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC7B,OAAO,CAAC,iBAAiB,CAAC,CAiB5B;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE1D;AAED;;GAEG;AACH,wBAAgB,kBAAkB,IAAI,GAAG,CAAC,MAAM,EAAE;IAAE,SAAS,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAWxF"}
@@ -0,0 +1,138 @@
1
+ /**
2
+ * DeepClause CLI - MCP (Model Context Protocol) Client Module
3
+ *
4
+ * Handles connections to MCP servers for tool discovery and execution.
5
+ *
6
+ * TODO: Full implementation requires @modelcontextprotocol/sdk package
7
+ * For now, this provides the interface and placeholder implementation.
8
+ */
9
+ // =============================================================================
10
+ // MCP Client (Placeholder Implementation)
11
+ // =============================================================================
12
+ /**
13
+ * Active MCP connections
14
+ */
15
+ const connections = new Map();
16
+ /**
17
+ * Connect to an MCP server and discover its tools
18
+ */
19
+ export async function connectMCPServer(name, config) {
20
+ // Check if already connected
21
+ const existing = connections.get(name);
22
+ if (existing?.connected) {
23
+ return existing;
24
+ }
25
+ const connection = {
26
+ server: config,
27
+ name,
28
+ tools: [],
29
+ connected: false
30
+ };
31
+ try {
32
+ // TODO: Implement actual MCP protocol connection
33
+ // This would involve:
34
+ // 1. Spawn process using config.command and config.args
35
+ // 2. Communicate via stdin/stdout (stdio transport)
36
+ // 3. Send initialize request
37
+ // 4. Query tools/list
38
+ // 5. Parse and store tool schemas
39
+ // Placeholder: Would spawn the process
40
+ console.warn(`[MCP] Server '${name}' connection not yet implemented`);
41
+ console.warn(`[MCP] Would run: ${config.command} ${config.args?.join(' ') || ''}`);
42
+ // In real implementation:
43
+ // const { spawn } = await import('child_process');
44
+ // const proc = spawn(config.command, config.args || [], {
45
+ // env: { ...process.env, ...config.env },
46
+ // stdio: ['pipe', 'pipe', 'pipe']
47
+ // });
48
+ // connection.process = proc;
49
+ // await sendInitialize(proc);
50
+ // connection.tools = await queryTools(proc);
51
+ connection.connected = true;
52
+ connections.set(name, connection);
53
+ return connection;
54
+ }
55
+ catch (error) {
56
+ connection.error = error.message;
57
+ connection.connected = false;
58
+ connections.set(name, connection);
59
+ throw error;
60
+ }
61
+ }
62
+ /**
63
+ * Disconnect from an MCP server
64
+ */
65
+ export async function disconnectMCPServer(name) {
66
+ const connection = connections.get(name);
67
+ if (!connection)
68
+ return;
69
+ if (connection.process) {
70
+ connection.process.kill();
71
+ }
72
+ connection.connected = false;
73
+ connections.delete(name);
74
+ }
75
+ /**
76
+ * Disconnect from all MCP servers
77
+ */
78
+ export async function disconnectAllMCPServers() {
79
+ for (const name of connections.keys()) {
80
+ await disconnectMCPServer(name);
81
+ }
82
+ }
83
+ /**
84
+ * Get tools from an MCP server
85
+ */
86
+ export async function getMCPServerTools(name, config) {
87
+ try {
88
+ const connection = await connectMCPServer(name, config);
89
+ return connection.tools;
90
+ }
91
+ catch (error) {
92
+ // Return empty array with error marker
93
+ return [{
94
+ name: `[${name}]`,
95
+ description: `Connection failed: ${error.message}`,
96
+ provider: name,
97
+ error: error.message
98
+ }];
99
+ }
100
+ }
101
+ /**
102
+ * Call a tool on an MCP server
103
+ */
104
+ export async function callMCPTool(serverName, toolName, _args) {
105
+ const connection = connections.get(serverName);
106
+ if (!connection?.connected) {
107
+ return {
108
+ success: false,
109
+ error: `MCP server '${serverName}' not connected`
110
+ };
111
+ }
112
+ // TODO: Implement actual tool call via MCP protocol
113
+ // This would send a tools/call request and parse the response
114
+ return {
115
+ success: false,
116
+ error: `MCP tool calls not yet implemented (would call ${toolName} on ${serverName})`
117
+ };
118
+ }
119
+ /**
120
+ * Check if an MCP server is connected
121
+ */
122
+ export function isMCPServerConnected(name) {
123
+ return connections.get(name)?.connected ?? false;
124
+ }
125
+ /**
126
+ * Get connection status for all servers
127
+ */
128
+ export function getMCPServerStatus() {
129
+ const status = new Map();
130
+ for (const [name, conn] of connections) {
131
+ status.set(name, {
132
+ connected: conn.connected,
133
+ error: conn.error
134
+ });
135
+ }
136
+ return status;
137
+ }
138
+ //# sourceMappingURL=mcp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.js","sourceRoot":"","sources":["../../src/cli/mcp.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAyBH,gFAAgF;AAChF,0CAA0C;AAC1C,gFAAgF;AAEhF;;GAEG;AACH,MAAM,WAAW,GAAG,IAAI,GAAG,EAAyB,CAAC;AAErD;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,IAAY,EACZ,MAAiB;IAEjB,6BAA6B;IAC7B,MAAM,QAAQ,GAAG,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACvC,IAAI,QAAQ,EAAE,SAAS,EAAE,CAAC;QACxB,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,UAAU,GAAkB;QAChC,MAAM,EAAE,MAAM;QACd,IAAI;QACJ,KAAK,EAAE,EAAE;QACT,SAAS,EAAE,KAAK;KACjB,CAAC;IAEF,IAAI,CAAC;QACH,iDAAiD;QACjD,sBAAsB;QAC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G,IAAI,GAAG,EAAkD,CAAC;IAEzE,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,WAAW,EAAE,CAAC;QACvC,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE;YACf,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC,CAAC;IACL,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * DeepClause CLI - MD to DML Conversion Prompt
3
+ *
4
+ * Contains the base prompt template for converting Markdown task descriptions to DML.
5
+ */
6
+ import { Tool } from './tools.js';
7
+ export declare const DML_CONVERSION_PROMPT = "# Markdown to DML Conversion Prompt\n\nYou are an expert DML (DeepClause Meta Language) programmer. Your task is to convert \nnatural language task descriptions written in Markdown into executable DML programs.\n\n## Tool Types in DML\n\nThere are two kinds of tools in DML:\n\n### 1. DML Tool Wrappers (via `tool/3`)\nThese are predicates you define in DML using the `tool/3` syntax. They are pure DML logic \nand typically wrap one or more external tools for convenience or composition. They are \n**not** registered as external dependencies.\n\n```prolog\ntool(search(Query, Results), \"Search the web for information\") :-\n exec(web_search(query: Query), Results).\n```\n\n### 2. External Tools (MCP/AgentVM)\nThese are provided by the runtime (via MCP servers or built-in AgentVM) and are invoked \ndirectly with `exec/2`. Only these are registered as dependencies in the meta file.\n\n## Available External Tools\n\n{TOOLS_TABLE}\n\n**Note:** Only tools invoked via `exec/2` that correspond to external MCP or AgentVM \ntools are registered as dependencies. DML tool wrappers are not registered unless they \ncall external tools.\n\n## DML Language Overview\n\nDML is a simplified Prolog dialect designed for AI agent programming. It combines \ndeclarative logic programming with LLM-powered task execution.\n\n### Program Structure\n\nEvery DML program must have an `agent_main` entry point that accepts 0+ arguments:\n\n```prolog\n% No arguments\nagent_main :- ...\n\n% One argument\nagent_main(Topic) :- ...\n\n% Two arguments (alphabetical order for dict unpacking)\nagent_main(MaxResults, Topic) :- ...\n```\n\n### Core Predicates\n\n#### Task Execution\n\n| Predicate | Description |\n|-----------|-------------|\n| `task(Description)` | Execute an LLM task with accumulated memory |\n| `task(Description, Var)` | Execute task, bind result to Var |\n| `task(Description, Var1, Var2)` | Execute task, bind two results |\n| `task(Description, Var1, Var2, Var3)` | Execute task, bind three results |\n\n**Important:** Variable names in the description must match the Prolog variables:\n```prolog\ntask(\"Analyze this and store the result in Summary.\", Summary)\n```\n\n#### Fresh LLM Calls (No Memory)\n\n| Predicate | Description |\n|-----------|-------------|\n| `prompt(Description)` | Execute LLM with **empty memory** (fresh context) |\n| `prompt(Description, Var)` | Fresh LLM call, bind result to Var |\n| `prompt(Description, Var1, Var2)` | Fresh LLM call, bind two results |\n| `prompt(Description, Var1, Var2, Var3)` | Fresh LLM call, bind three results |\n\n**When to use `prompt()` vs `task()`:**\n- Use `task()` when you want the LLM to have context from previous `system()`, `user()`, and `task()` calls\n- Use `prompt()` when you want a completely fresh LLM call without any prior conversation context\n\n```prolog\nagent_main :-\n system(\"You are a helpful assistant.\"),\n task(\"What is 2+2?\"), % LLM sees the system message\n prompt(\"What is 3+3?\"). % LLM does NOT see any prior context\n```\n\n#### Direct Tool Execution\n\n| Predicate | Description |\n|-----------|-------------|\n| `exec(Tool, Result)` | Execute external tool directly |\n\n```prolog\nexec(web_search(query: \"AI news\"), Results)\nexec(vm_exec(command: \"echo hello\"), Result)\n```\n\n**Important:** `vm_exec` returns a dict with `stdout`, `stderr`, and `exitCode` fields.\nUse `get_dict/3` to extract values:\n```prolog\nexec(vm_exec(command: \"echo hello\"), Result),\nget_dict(stdout, Result, Output),\noutput(Output).\n```\n\n**VM Working Directory:** The VM starts with the working directory set to `/workspace`, which is \nmounted to your actual workspace. Files are directly accessible:\n```prolog\nexec(vm_exec(command: \"cat README.md\"), Result), % Reads workspace/README.md\nget_dict(stdout, Result, Content).\n```\n\n#### Memory Management\n\n| Predicate | Description |\n|-----------|-------------|\n| `system(Text)` | Add system message (LLM instructions) |\n| `user(Text)` | Add user message to context |\n| `push_context` | Save memory state (for isolation) |\n| `push_context(clear)` | Save and clear memory |\n| `pop_context` | Restore previous memory state |\n| `clear_memory` | Clear all accumulated memory |\n\n**Note:** Memory is automatically restored on backtracking, so `push_context`/`pop_context` \nare primarily useful for manual isolation within a clause.\n\n#### Output\n\n| Predicate | Description |\n|-----------|-------------|\n| `output(Text)` | Emit progress/intermediate output |\n| `yield(Text)` | Alias for output/1 |\n| `log(Text)` | Emit debug/log message |\n| `answer(Text)` | Emit final answer (commits execution) |\n\n#### Tool Definitions\n\nDefine tools that the LLM can call during `task()`:\n\n```prolog\n% Tool wrapper (description is second arg, body calls exec)\ntool(search(Query, Results), \"Search the web for information\") :-\n exec(web_search(query: Query), Results).\n```\n#### Using `task()` and `prompt()` Inside Tools\n\nTools can use `task()` or `prompt()` internally to combine Prolog logic with LLM reasoning:\n\n```prolog\n% A tool that computes then explains\ntool(explain_calculation(A, B, Explanation), \"Calculate and explain the result\") :-\n Sum is A + B, % Prolog computation\n format(string(Desc), \"Explain ~w + ~w = ~w to a child\", [A, B, Sum]),\n task(Desc, Explanation). % LLM explanation\n```\n\n**Memory Isolation:** Nested `task()` calls inside tools run with **fresh memory** - they \ndo NOT have access to the parent's accumulated memory. If you need context, either:\n1. Pass it as a tool argument\n2. Add it explicitly with `system()` inside the tool\n\n```prolog\n% Pass context explicitly as an argument\ntool(analyze_with_context(Context, Data, Result), \"Analyze data with given context\") :-\n system(Context), % Add context to this tool's memory\n format(string(Desc), \"Analyze: ~w\", [Data]),\n task(Desc, Result).\n```\n\n**Automatic Recursion Prevention:** When `task()` runs inside a tool, the nested agent \ncannot call the tool that is currently executing. This prevents infinite recursion.\n\n#### Tool Scoping\n\nControl which tools are available to nested `task()` calls:\n\n| Predicate | Description |\n|-----------|-------------|\n| `with_tools(ToolList, Goal)` | Run Goal with only specified tools available |\n| `without_tools(ToolList, Goal)` | Run Goal excluding specified tools |\n\n```prolog\n% Only allow search tool in nested task\ntool(safe_research(Topic, Result), \"Research with limited tools\") :-\n with_tools([search], (\n format(string(Desc), \"Research ~w using search\", [Topic]),\n task(Desc, Result)\n )).\n\n% Exclude expensive tools from nested task \ntool(cheap_task(Input, Output), \"Process without expensive tools\") :-\n without_tools([expensive_api], (\n task(\"Process {Input} cheaply\", Output)\n )).\n```\n#### Built-in Agent Tools\n\nDuring `task()` execution, the LLM has access to these built-in tools:\n\n| Tool | Description |\n|------|-------------|\n| `store(variable, value)` | Store a result in an output variable |\n| `ask_user(prompt)` | Ask the user for input or clarification |\n| `finish(success)` | Complete the task |\n\n**Important:** If your task might need user input (clarification, choices, confirmation), \nyou should define an `ask_user` tool wrapper so the LLM can request input:\n\n```prolog\n% Define ask_user wrapper so LLM can request user input during task()\ntool(ask_user(Prompt, Response), \"Ask the user a question and get their response\") :-\n exec(ask_user(prompt: Prompt), Result),\n get_dict(user_response, Result, Response).\n```\n\n### String Interpolation\n\nDML supports **automatic string interpolation** using `{Variable}` syntax in task descriptions \nand output predicates. This is the preferred method:\n\n```prolog\nagent_main(Topic) :-\n task(\"Research the topic: {Topic}\"),\n output(\"Finished researching {Topic}\"),\n answer(\"Done\").\n```\n\n**IMPORTANT:** Never mix `{Variable}` interpolation with `format/3`. Choose one approach:\n\n**Option 1: String Interpolation (preferred for simple cases)**\n```prolog\n% Variables are automatically substituted\ntask(\"Analyze {Data} and summarize in Summary.\", Summary),\noutput(\"Analysis complete for {Data}\")\n```\n\n**Option 2: format/3 for complex string building (Prolog-style)**\n```prolog\n% format/3 writes to a string variable - use ~w for terms, ~s for strings\nformat(string(Message), \"Found ~d results for query: ~w\", [Count, Query]),\noutput(Message)\n```\n\n**WRONG - Never do this:**\n```prolog\n% DON'T mix interpolation and format\noutput(format(\"Value: {X}\", [X])) % WRONG! format doesn't return a value\n\n% DON'T use {Var} inside format strings\nformat(string(S), \"Topic: {Topic}\", []) % WRONG! Use ~w instead\n```\n\n### Control Flow\n\n```prolog\n% Conjunction (and)\ngoal1, goal2, goal3\n\n% Disjunction (or)\n(goal1 ; goal2)\n\n% If-then-else\n(Condition -> Then ; Else)\n\n% Negation as failure\n\\+ goal\n\n% Cut (commit to this branch)\n!\n\n% Exception handling\ncatch(Goal, Error, Recovery)\nthrow(some_error)\n```\n\n### Backtracking\n\nDML supports full Prolog backtracking across LLM calls:\n\n```prolog\n% Try multiple approaches\nagent_main :-\n ( try_approach_1\n ; try_approach_2 % Falls back if first fails\n ; fallback_approach\n ),\n answer(\"Done\").\n```\n\n### List Processing\n\n```prolog\n% Recursive list processing\nprocess_items([]).\nprocess_items([H|T]) :-\n process_one(H),\n process_items(T).\n\n% Using findall\nfindall(X, some_condition(X), Results)\n\n% Using maplist\nmaplist(process_one, Items)\n```\n\n---\n\n## Common Patterns\n\n### Pattern 1: Simple Task Agent\n```prolog\nagent_main(Topic) :-\n system(\"You are a helpful research assistant.\"),\n task(\"Research {Topic} and provide a comprehensive summary.\"),\n answer(\"Research complete!\").\n```\n\n### Pattern 2: Multi-Step Workflow\n```prolog\nagent_main(Topic) :-\n system(\"You are a thorough research assistant.\"),\n \n output(\"Step 1: Gathering information...\"),\n task(\"Search for recent information about {Topic}. Store findings in Findings.\", Findings),\n \n output(\"Step 2: Analyzing...\"),\n task(\"Analyze these findings: {Findings}. Store your analysis in Analysis.\", Analysis),\n \n output(\"Step 3: Generating report...\"),\n task(\"Create a comprehensive report based on this analysis: {Analysis}\"),\n \n answer(\"Report generated!\").\n```\n\n### Pattern 3: Tool-Enabled Agent\n```prolog\ntool(search(Query, Results), \"Search the web\") :-\n exec(web_search(query: Query), Results).\n\nagent_main(Topic) :-\n system(\"You are a research assistant with web search. Use the search tool.\"),\n task(\"Research {Topic} using available tools.\"),\n answer(\"Research complete!\").\n```\n\n### Pattern 3b: Tool with Nested LLM Call\n```prolog\n% A tool that uses LLM to analyze search results\ntool(smart_search(Query, Summary), \"Search and summarize results\") :-\n exec(web_search(query: Query), Results),\n format(string(Desc), \"Summarize these search results: ~w\", [Results]),\n task(Desc, Summary). % Nested task CANNOT call smart_search (recursion prevention)\n\nagent_main(Topic) :-\n system(\"Use smart_search to research topics.\"),\n task(\"Research {Topic}.\"),\n answer(\"Done!\").\n```\n\n### Pattern 4: Code Execution (Use Sparingly!)\n```prolog\n% ONLY use exec/Python when you need:\n% - External packages (pandas, numpy, etc.)\n% - Shell commands (find, grep, sed, awk, curl)\n% - Complex imperative logic that's awkward in Prolog\n%\n% NOTE: vm_exec returns a dict with stdout, stderr, exitCode - use get_dict to extract\n% NOTE: The VM starts in /workspace which is your actual workspace directory\n\nagent_main(Task) :-\n system(\"You are a coding assistant.\"),\n \n task(\"Write Python code to solve: {Task}. Store only the code in Code.\", Code),\n \n % Write code to a file in the workspace (VM cwd is /workspace)\n open('script.py', write, S),\n write(S, Code),\n close(S),\n \n output(\"Executing code...\"),\n exec(vm_exec(command: \"python3 script.py\"), Result), % Runs in /workspace\n get_dict(stdout, Result, Output),\n \n task(\"Explain this execution result: {Output}\"),\n \n answer(\"Done!\").\n```\n\n### Pattern 5: Data Analysis with VM\n```prolog\n% Good use of exec: requires pandas package\n% NOTE: vm_exec returns a dict - use get_dict to extract stdout\nagent_main(CsvPath, Question) :-\n system(\"You are a data analyst.\"),\n \n output(\"Setting up environment...\"),\n exec(vm_exec(command: \"pip install pandas\"), _),\n \n output(\"Analyzing data...\"),\n task(\"Write Python code to load {CsvPath} with pandas and answer: {Question}. Store only the code in Code.\", Code),\n \n % Write code to file and execute\n open('analysis.py', write, S),\n write(S, Code),\n close(S),\n exec(vm_exec(command: \"python3 analysis.py\"), Result),\n get_dict(stdout, Result, Output),\n \n task(\"Interpret and explain these analysis results: {Output}\"),\n \n answer(\"Analysis complete!\").\n```\n\n### Pattern 6: File I/O (Use Prolog, NOT Python!)\n```prolog\n% GOOD: Use Prolog's native file I/O\nagent_main(Content) :-\n task(\"Generate a report about {Content}. Store in Report.\", Report),\n \n % Write to file using Prolog (not Python!)\n open('output.md', write, Stream),\n write(Stream, Report),\n close(Stream),\n \n answer(\"Report saved to output.md\").\n\n% Build filename from parts\nagent_main(Name, Content) :-\n task(\"Generate content about {Name}. Store in Text.\", Text),\n \n % Construct filename using atom operations\n atom_string(NameAtom, Name),\n atom_concat(NameAtom, '_report.md', FilenameAtom),\n atom_string(FilenameAtom, Filename),\n \n open(Filename, write, Stream),\n write(Stream, Text),\n close(Stream),\n \n output(\"Saved to {Filename}\"),\n answer(\"Done!\").\n```\n\n### Pattern 7: Using format/3 for Complex Strings\n```prolog\n% When you need to build strings with numbers or complex formatting\nagent_main(Items) :-\n length(Items, Count),\n format(string(StatusMsg), \"Processing ~d items\", [Count]),\n output(StatusMsg),\n \n process_all(Items),\n \n format(string(DoneMsg), \"Completed processing ~d items successfully\", [Count]),\n answer(DoneMsg).\n```\n\n### Pattern 8: Interactive Agent (User Input)\n```prolog\n% When the task may need user clarification or choices\n% Define ask_user wrapper so LLM can interact with user\ntool(ask_user(Prompt, Response), \"Ask the user a question\") :-\n exec(ask_user(prompt: Prompt), Result),\n get_dict(user_response, Result, Response).\n\nagent_main(Task) :-\n system(\"You are a helpful assistant. If you need clarification, use the ask_user tool.\"),\n \n task(\"Help the user with: {Task}. If anything is unclear, ask for clarification.\"),\n \n answer(\"Task completed!\").\n```\n\n### Pattern 9: Error Handling with catch/throw\n```prolog\n% Safe tool call with error recovery\nagent_main(Query) :-\n catch(\n (\n exec(web_search(query: Query), Results),\n task(\"Summarize: {Results}\")\n ),\n Error,\n (\n format(string(ErrMsg), \"Search failed: ~w. Proceeding without search.\", [Error]),\n output(ErrMsg),\n task(\"Answer based on your knowledge: {Query}\")\n )\n ),\n answer(\"Done!\").\n```\n\n### Pattern 10: Fresh Context with prompt()\n```prolog\n% Use prompt() for independent sub-tasks that shouldn't share context\nagent_main(Topic) :-\n system(\"You are a research assistant.\"),\n \n % Main research with accumulated context\n task(\"Research {Topic} deeply.\", MainFindings),\n \n % Independent critique - fresh context, no bias from main research\n prompt(\"As a skeptical reviewer, critique this research: {MainFindings}. Store critique in Critique.\", Critique),\n \n % Back to main context for final synthesis\n task(\"Address this critique: {Critique}\"),\n \n answer(\"Research complete with peer review!\").\n```\n\n---\n\n## When to Use exec() vs Prolog\n\n### Use Prolog Native Functionality For:\n- **File I/O**: `open/3`, `write/2`, `read/2`, `close/1`\n- **String manipulation**: `atom_concat/3`, `atom_string/2`, `split_string/4`\n- **List operations**: `append/3`, `member/2`, `findall/3`, `maplist/2`\n- **Arithmetic**: `is/2`, comparison operators\n- **Logic and control flow**: conjunctions, disjunctions, conditionals\n\n### Use exec() ONLY For:\n- **External packages**: pandas, numpy, requests, matplotlib, etc.\n- **Shell commands**: find, grep, sed, awk, curl, git\n- **System operations**: environment variables, process management\n- **Complex imperative logic**: loops with side effects, mutable state\n\n### BAD Example - Unnecessary Python:\n```prolog\n% DON'T do this - Python for simple file writing\nexec(vm_exec(command: \"python3 -c \"open('out.txt','w').write('hello')\"\"), _)\n```\n\n### GOOD Example - Use Prolog:\n```prolog\n% DO this instead - native Prolog file I/O\nopen('out.txt', write, S),\nwrite(S, Content),\nclose(S)\n```\n\n---\n\n## Conversion Guidelines\n\n1. **Identify the core task** - What is the primary goal?\n2. **Determine parameters** - What inputs does the agent need?\n3. **Map to patterns** - Which DML pattern best fits?\n4. **Prefer Prolog native operations** - Use Prolog for file I/O, strings, lists\n5. **Use exec() sparingly** - Only for packages, shell commands, imperative logic\n6. **Define required tools** - What external capabilities are needed?\n7. **Handle edge cases** - Add fallbacks and error handling\n8. **Add progress output** - Keep users informed with `output/1`\n9. **Add ask_user wrapper** - If the task might need user input, clarification, or choices\n\n## CRITICAL: String Handling Rules\n\n**NEVER do any of these:**\n- `output(format(...))` - format/3 doesn't return a value, it binds to first arg\n- `answer(format(...))` - same issue\n- Mixing `{Var}` and `~w` in the same string\n- Using `{Var}` inside format/3 format strings\n\n**DO this instead:**\n- Use `{Variable}` interpolation directly: `output(\"Processing {Item}\")`\n- Or use format/3 properly: `format(string(Msg), \"Count: ~d\", [N]), output(Msg)`\n\n## CRITICAL: Prolog vs exec() Rules\n\n**Use Prolog for:**\n- File I/O: `open/3`, `write/2`, `close/1`\n- String building: `atom_concat/3`, `atom_string/2`\n- All standard logic and data manipulation\n\n**Use exec() ONLY for:**\n- External packages (pandas, numpy)\n- Shell commands (grep, curl, find)\n- Complex imperative tasks\n\n## Output Requirements\n\nYour DML output must:\n\n1. Start with a comment header describing the program\n2. Define any tool wrappers needed with `tool/3`\n3. **If the task may need user input, define an `ask_user` tool wrapper**\n4. Have a single `agent_main` entry point\n5. Use appropriate system prompts\n6. Include progress outputs for long-running tasks\n7. End with `answer/1` to signal completion\n8. Handle stated edge cases\n9. **Only use tools from the Available External Tools list**\n10. **Use ONLY {Variable} interpolation OR format/3, never mix them**\n11. **NEVER pass format(...) directly to output/1 or answer/1**\n12. **Use Prolog native file I/O, NOT Python exec() for simple file operations**\n\nOutput ONLY the DML code, no explanations or markdown code fences.\n";
8
+ /**
9
+ * Build the tools table for the prompt
10
+ */
11
+ export declare function buildToolsTable(tools: Tool[]): string;
12
+ /**
13
+ * Build the complete compilation prompt with tools injected
14
+ */
15
+ export declare function buildCompilationPrompt(tools: Tool[]): string;
16
+ /**
17
+ * Build the user message containing the markdown to convert
18
+ */
19
+ export declare function buildUserMessage(markdown: string): string;
20
+ //# sourceMappingURL=prompt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../../src/cli/prompt.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAMlC,eAAO,MAAM,qBAAqB,svmBAslBjC,CAAC;AAMF;;GAEG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,IAAI,EAAE,GAAG,MAAM,CAsCrD;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,IAAI,EAAE,GAAG,MAAM,CAG5D;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAUzD"}