chainlesschain 0.37.8 → 0.37.10

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 (59) hide show
  1. package/README.md +403 -8
  2. package/bin/chainlesschain.js +4 -0
  3. package/package.json +7 -2
  4. package/src/commands/agent.js +30 -0
  5. package/src/commands/ask.js +114 -0
  6. package/src/commands/audit.js +286 -0
  7. package/src/commands/auth.js +387 -0
  8. package/src/commands/browse.js +184 -0
  9. package/src/commands/chat.js +35 -0
  10. package/src/commands/db.js +152 -0
  11. package/src/commands/did.js +376 -0
  12. package/src/commands/encrypt.js +233 -0
  13. package/src/commands/export.js +125 -0
  14. package/src/commands/git.js +215 -0
  15. package/src/commands/import.js +259 -0
  16. package/src/commands/instinct.js +202 -0
  17. package/src/commands/llm.js +288 -0
  18. package/src/commands/mcp.js +302 -0
  19. package/src/commands/memory.js +282 -0
  20. package/src/commands/note.js +489 -0
  21. package/src/commands/org.js +505 -0
  22. package/src/commands/p2p.js +274 -0
  23. package/src/commands/plugin.js +398 -0
  24. package/src/commands/search.js +237 -0
  25. package/src/commands/session.js +238 -0
  26. package/src/commands/skill.js +479 -0
  27. package/src/commands/sync.js +249 -0
  28. package/src/commands/tokens.js +214 -0
  29. package/src/commands/wallet.js +416 -0
  30. package/src/index.js +65 -0
  31. package/src/lib/audit-logger.js +364 -0
  32. package/src/lib/bm25-search.js +322 -0
  33. package/src/lib/browser-automation.js +216 -0
  34. package/src/lib/crypto-manager.js +246 -0
  35. package/src/lib/did-manager.js +270 -0
  36. package/src/lib/ensure-utf8.js +59 -0
  37. package/src/lib/git-integration.js +220 -0
  38. package/src/lib/instinct-manager.js +190 -0
  39. package/src/lib/knowledge-exporter.js +302 -0
  40. package/src/lib/knowledge-importer.js +293 -0
  41. package/src/lib/llm-providers.js +325 -0
  42. package/src/lib/mcp-client.js +413 -0
  43. package/src/lib/memory-manager.js +211 -0
  44. package/src/lib/note-versioning.js +244 -0
  45. package/src/lib/org-manager.js +424 -0
  46. package/src/lib/p2p-manager.js +317 -0
  47. package/src/lib/pdf-parser.js +96 -0
  48. package/src/lib/permission-engine.js +374 -0
  49. package/src/lib/plan-mode.js +333 -0
  50. package/src/lib/platform.js +15 -0
  51. package/src/lib/plugin-manager.js +312 -0
  52. package/src/lib/response-cache.js +156 -0
  53. package/src/lib/session-manager.js +189 -0
  54. package/src/lib/sync-manager.js +347 -0
  55. package/src/lib/token-tracker.js +200 -0
  56. package/src/lib/wallet-manager.js +348 -0
  57. package/src/repl/agent-repl.js +912 -0
  58. package/src/repl/chat-repl.js +262 -0
  59. package/src/runtime/bootstrap.js +159 -0
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Instinct learning commands
3
+ * chainlesschain instinct show|reset|categories
4
+ */
5
+
6
+ import chalk from "chalk";
7
+ import { logger } from "../lib/logger.js";
8
+ import { bootstrap, shutdown } from "../runtime/bootstrap.js";
9
+ import {
10
+ getInstincts,
11
+ getStrongInstincts,
12
+ resetInstincts,
13
+ deleteInstinct,
14
+ decayInstincts,
15
+ generateInstinctPrompt,
16
+ INSTINCT_CATEGORIES,
17
+ } from "../lib/instinct-manager.js";
18
+
19
+ export function registerInstinctCommand(program) {
20
+ const instinct = program
21
+ .command("instinct")
22
+ .description("Instinct learning — learned user preferences");
23
+
24
+ // instinct show
25
+ instinct
26
+ .command("show", { isDefault: true })
27
+ .description("Show learned instincts")
28
+ .option("--category <cat>", "Filter by category")
29
+ .option("-n, --limit <n>", "Max entries", "30")
30
+ .option("--strong", "Show only high-confidence instincts (>= 70%)")
31
+ .option("--json", "Output as JSON")
32
+ .action(async (options) => {
33
+ try {
34
+ const ctx = await bootstrap({ verbose: program.opts().verbose });
35
+ if (!ctx.db) {
36
+ logger.error("Database not available");
37
+ process.exit(1);
38
+ }
39
+ const db = ctx.db.getDatabase();
40
+
41
+ const instincts = options.strong
42
+ ? getStrongInstincts(db)
43
+ : getInstincts(db, {
44
+ category: options.category,
45
+ limit: parseInt(options.limit) || 30,
46
+ });
47
+
48
+ if (options.json) {
49
+ console.log(JSON.stringify(instincts, null, 2));
50
+ } else if (instincts.length === 0) {
51
+ logger.info(
52
+ "No instincts learned yet. Use the agent to build up preferences.",
53
+ );
54
+ } else {
55
+ logger.log(chalk.bold(`Learned Instincts (${instincts.length}):\n`));
56
+ for (const inst of instincts) {
57
+ const pct = (inst.confidence * 100).toFixed(0);
58
+ const bar =
59
+ "█".repeat(Math.round(inst.confidence * 10)) +
60
+ "░".repeat(10 - Math.round(inst.confidence * 10));
61
+ logger.log(
62
+ ` ${chalk.gray(inst.id.slice(0, 8))} ${chalk.cyan(inst.category.padEnd(18))} ${bar} ${pct}%`,
63
+ );
64
+ logger.log(` ${chalk.white(inst.pattern)}`);
65
+ logger.log(
66
+ ` ${chalk.gray(`seen ${inst.occurrences}x | last: ${inst.last_seen || "unknown"}`)}`,
67
+ );
68
+ }
69
+ }
70
+
71
+ await shutdown();
72
+ } catch (err) {
73
+ logger.error(`Failed: ${err.message}`);
74
+ process.exit(1);
75
+ }
76
+ });
77
+
78
+ // instinct categories
79
+ instinct
80
+ .command("categories")
81
+ .description("List instinct categories")
82
+ .action(async () => {
83
+ logger.log(chalk.bold("Instinct Categories:\n"));
84
+ for (const [key, value] of Object.entries(INSTINCT_CATEGORIES)) {
85
+ logger.log(` ${chalk.cyan(value.padEnd(20))} ${chalk.gray(key)}`);
86
+ }
87
+ });
88
+
89
+ // instinct prompt
90
+ instinct
91
+ .command("prompt")
92
+ .description("Generate a system prompt from learned instincts")
93
+ .option("--json", "Output as JSON")
94
+ .action(async (options) => {
95
+ try {
96
+ const ctx = await bootstrap({ verbose: program.opts().verbose });
97
+ if (!ctx.db) {
98
+ logger.error("Database not available");
99
+ process.exit(1);
100
+ }
101
+ const db = ctx.db.getDatabase();
102
+ const prompt = generateInstinctPrompt(db);
103
+
104
+ if (options.json) {
105
+ console.log(JSON.stringify({ prompt }, null, 2));
106
+ } else if (!prompt) {
107
+ logger.info("No strong instincts yet. Keep using the agent!");
108
+ } else {
109
+ logger.log(prompt);
110
+ }
111
+
112
+ await shutdown();
113
+ } catch (err) {
114
+ logger.error(`Failed: ${err.message}`);
115
+ process.exit(1);
116
+ }
117
+ });
118
+
119
+ // instinct delete
120
+ instinct
121
+ .command("delete")
122
+ .description("Delete an instinct by ID")
123
+ .argument("<id>", "Instinct ID (or prefix)")
124
+ .action(async (id) => {
125
+ try {
126
+ const ctx = await bootstrap({ verbose: program.opts().verbose });
127
+ if (!ctx.db) {
128
+ logger.error("Database not available");
129
+ process.exit(1);
130
+ }
131
+ const db = ctx.db.getDatabase();
132
+ const ok = deleteInstinct(db, id);
133
+ if (ok) {
134
+ logger.success("Instinct deleted");
135
+ } else {
136
+ logger.error(`Instinct not found: ${id}`);
137
+ }
138
+
139
+ await shutdown();
140
+ } catch (err) {
141
+ logger.error(`Failed: ${err.message}`);
142
+ process.exit(1);
143
+ }
144
+ });
145
+
146
+ // instinct reset
147
+ instinct
148
+ .command("reset")
149
+ .description("Reset all learned instincts")
150
+ .option("--force", "Skip confirmation")
151
+ .action(async (options) => {
152
+ try {
153
+ if (!options.force) {
154
+ const { confirm } = await import("@inquirer/prompts");
155
+ const ok = await confirm({
156
+ message: "Reset all learned instincts? This cannot be undone.",
157
+ });
158
+ if (!ok) {
159
+ logger.info("Cancelled");
160
+ return;
161
+ }
162
+ }
163
+
164
+ const ctx = await bootstrap({ verbose: program.opts().verbose });
165
+ if (!ctx.db) {
166
+ logger.error("Database not available");
167
+ process.exit(1);
168
+ }
169
+ const db = ctx.db.getDatabase();
170
+ const count = resetInstincts(db);
171
+ logger.success(`Reset ${count} instincts`);
172
+
173
+ await shutdown();
174
+ } catch (err) {
175
+ logger.error(`Failed: ${err.message}`);
176
+ process.exit(1);
177
+ }
178
+ });
179
+
180
+ // instinct decay
181
+ instinct
182
+ .command("decay")
183
+ .description("Decay old instincts (reduce confidence of unused patterns)")
184
+ .option("--days <n>", "Days threshold", "30")
185
+ .action(async (options) => {
186
+ try {
187
+ const ctx = await bootstrap({ verbose: program.opts().verbose });
188
+ if (!ctx.db) {
189
+ logger.error("Database not available");
190
+ process.exit(1);
191
+ }
192
+ const db = ctx.db.getDatabase();
193
+ const decayed = decayInstincts(db, parseInt(options.days) || 30);
194
+ logger.success(`Decayed ${decayed} old instincts`);
195
+
196
+ await shutdown();
197
+ } catch (err) {
198
+ logger.error(`Failed: ${err.message}`);
199
+ process.exit(1);
200
+ }
201
+ });
202
+ }
@@ -0,0 +1,288 @@
1
+ /**
2
+ * LLM management commands
3
+ * chainlesschain llm models|test|providers|add-provider|switch
4
+ */
5
+
6
+ import ora from "ora";
7
+ import chalk from "chalk";
8
+ import { logger } from "../lib/logger.js";
9
+ import { bootstrap, shutdown } from "../runtime/bootstrap.js";
10
+ import {
11
+ BUILT_IN_PROVIDERS,
12
+ LLMProviderRegistry,
13
+ } from "../lib/llm-providers.js";
14
+
15
+ export function registerLlmCommand(program) {
16
+ const llm = program.command("llm").description("LLM provider management");
17
+
18
+ // llm models - list available models
19
+ llm
20
+ .command("models")
21
+ .description("List available models from the current provider")
22
+ .option("--provider <provider>", "LLM provider", "ollama")
23
+ .option("--base-url <url>", "API base URL", "http://localhost:11434")
24
+ .option("--json", "Output as JSON")
25
+ .action(async (options) => {
26
+ const spinner = ora("Fetching models...").start();
27
+ try {
28
+ if (options.provider === "ollama") {
29
+ const response = await fetch(`${options.baseUrl}/api/tags`);
30
+ if (!response.ok) {
31
+ throw new Error(`Ollama not reachable: ${response.status}`);
32
+ }
33
+ const data = await response.json();
34
+ spinner.stop();
35
+
36
+ if (options.json) {
37
+ console.log(JSON.stringify(data.models, null, 2));
38
+ } else {
39
+ if (!data.models || data.models.length === 0) {
40
+ logger.info("No models installed. Run: ollama pull qwen2:7b");
41
+ } else {
42
+ logger.log(chalk.bold(`Models (${data.models.length}):\n`));
43
+ for (const m of data.models) {
44
+ const size = m.size
45
+ ? chalk.gray(`(${(m.size / 1e9).toFixed(1)}GB)`)
46
+ : "";
47
+ logger.log(` ${chalk.cyan(m.name.padEnd(30))} ${size}`);
48
+ }
49
+ }
50
+ }
51
+ } else {
52
+ // Show known models for non-Ollama providers
53
+ spinner.stop();
54
+ const provider = BUILT_IN_PROVIDERS[options.provider];
55
+ if (provider) {
56
+ if (options.json) {
57
+ console.log(JSON.stringify(provider.models, null, 2));
58
+ } else {
59
+ logger.log(chalk.bold(`${provider.displayName} Models:\n`));
60
+ for (const m of provider.models) {
61
+ logger.log(` ${chalk.cyan(m)}`);
62
+ }
63
+ }
64
+ } else {
65
+ logger.error(`Unknown provider: ${options.provider}`);
66
+ }
67
+ }
68
+ } catch (err) {
69
+ spinner.fail(`Failed to list models: ${err.message}`);
70
+ process.exit(1);
71
+ }
72
+ });
73
+
74
+ // llm test - test connectivity
75
+ llm
76
+ .command("test")
77
+ .description("Test LLM provider connectivity")
78
+ .option("--provider <provider>", "LLM provider", "ollama")
79
+ .option("--model <model>", "Model to test", "qwen2:7b")
80
+ .option("--base-url <url>", "API base URL", "http://localhost:11434")
81
+ .option("--api-key <key>", "API key")
82
+ .action(async (options) => {
83
+ const spinner = ora(`Testing ${options.provider}...`).start();
84
+ try {
85
+ const start = Date.now();
86
+
87
+ if (options.provider === "ollama") {
88
+ const response = await fetch(`${options.baseUrl}/api/generate`, {
89
+ method: "POST",
90
+ headers: { "Content-Type": "application/json" },
91
+ body: JSON.stringify({
92
+ model: options.model,
93
+ prompt: "Say hi in one word.",
94
+ stream: false,
95
+ }),
96
+ });
97
+
98
+ if (!response.ok) {
99
+ throw new Error(`HTTP ${response.status}`);
100
+ }
101
+
102
+ const data = await response.json();
103
+ const elapsed = Date.now() - start;
104
+
105
+ spinner.succeed(
106
+ `${chalk.green("Connected")} to Ollama (${options.model}) in ${elapsed}ms`,
107
+ );
108
+ logger.log(
109
+ ` Response: ${chalk.gray(data.response.trim().substring(0, 100))}`,
110
+ );
111
+ } else if (options.provider === "openai") {
112
+ const apiKey = options.apiKey || process.env.OPENAI_API_KEY;
113
+ if (!apiKey) throw new Error("API key required");
114
+
115
+ const url =
116
+ options.baseUrl !== "http://localhost:11434"
117
+ ? options.baseUrl
118
+ : "https://api.openai.com/v1";
119
+
120
+ const response = await fetch(`${url}/chat/completions`, {
121
+ method: "POST",
122
+ headers: {
123
+ "Content-Type": "application/json",
124
+ Authorization: `Bearer ${apiKey}`,
125
+ },
126
+ body: JSON.stringify({
127
+ model: options.model || "gpt-4o-mini",
128
+ messages: [{ role: "user", content: "Say hi in one word." }],
129
+ max_tokens: 10,
130
+ }),
131
+ });
132
+
133
+ if (!response.ok) {
134
+ throw new Error(`HTTP ${response.status}`);
135
+ }
136
+
137
+ const data = await response.json();
138
+ const elapsed = Date.now() - start;
139
+
140
+ spinner.succeed(
141
+ `${chalk.green("Connected")} to OpenAI (${options.model || "gpt-4o-mini"}) in ${elapsed}ms`,
142
+ );
143
+ logger.log(
144
+ ` Response: ${chalk.gray(data.choices[0].message.content.trim())}`,
145
+ );
146
+ } else {
147
+ spinner.fail(`Unknown provider: ${options.provider}`);
148
+ }
149
+ } catch (err) {
150
+ spinner.fail(`Test failed: ${err.message}`);
151
+ process.exit(1);
152
+ }
153
+ });
154
+
155
+ // llm providers - list all available providers
156
+ llm
157
+ .command("providers")
158
+ .description("List all available LLM providers")
159
+ .option("--json", "Output as JSON")
160
+ .action(async (options) => {
161
+ try {
162
+ const ctx = await bootstrap({ verbose: program.opts().verbose });
163
+ if (!ctx.db) {
164
+ // Fall back to built-in list without DB
165
+ const providers = Object.values(BUILT_IN_PROVIDERS);
166
+ if (options.json) {
167
+ console.log(JSON.stringify(providers, null, 2));
168
+ } else {
169
+ logger.log(chalk.bold(`LLM Providers (${providers.length}):\n`));
170
+ for (const p of providers) {
171
+ const hasKey = p.apiKeyEnv
172
+ ? process.env[p.apiKeyEnv]
173
+ ? chalk.green("✓")
174
+ : chalk.red("✗")
175
+ : chalk.green("✓");
176
+ logger.log(
177
+ ` ${hasKey} ${chalk.cyan(p.name.padEnd(15))} ${p.displayName}`,
178
+ );
179
+ logger.log(` ${chalk.gray("Models:")} ${p.models.join(", ")}`);
180
+ }
181
+ }
182
+ await shutdown();
183
+ return;
184
+ }
185
+
186
+ const db = ctx.db.getDatabase();
187
+ const registry = new LLMProviderRegistry(db);
188
+ const providers = registry.list();
189
+ const active = registry.getActive();
190
+
191
+ if (options.json) {
192
+ console.log(JSON.stringify({ active, providers }, null, 2));
193
+ } else {
194
+ logger.log(chalk.bold(`LLM Providers (${providers.length}):\n`));
195
+ for (const p of providers) {
196
+ const isActive = p.name === active ? chalk.green(" [active]") : "";
197
+ const keyStatus = p.hasApiKey
198
+ ? chalk.green("✓")
199
+ : chalk.red("✗ key missing");
200
+ const custom = p.custom ? chalk.yellow(" [custom]") : "";
201
+ logger.log(
202
+ ` ${keyStatus} ${chalk.cyan(p.name.padEnd(15))} ${p.displayName}${isActive}${custom}`,
203
+ );
204
+ logger.log(` ${chalk.gray("Models:")} ${p.models.join(", ")}`);
205
+ }
206
+ }
207
+
208
+ await shutdown();
209
+ } catch (err) {
210
+ logger.error(`Failed: ${err.message}`);
211
+ process.exit(1);
212
+ }
213
+ });
214
+
215
+ // llm add-provider - add a custom provider
216
+ llm
217
+ .command("add-provider")
218
+ .description("Add a custom LLM provider")
219
+ .argument("<name>", "Provider name")
220
+ .requiredOption("-u, --base-url <url>", "API base URL")
221
+ .option("-d, --display-name <name>", "Display name")
222
+ .option("-k, --api-key-env <var>", "Environment variable for API key")
223
+ .option("-m, --models <models>", "Comma-separated model names")
224
+ .option("--json", "Output as JSON")
225
+ .action(async (name, options) => {
226
+ try {
227
+ const ctx = await bootstrap({ verbose: program.opts().verbose });
228
+ if (!ctx.db) {
229
+ logger.error("Database not available");
230
+ process.exit(1);
231
+ }
232
+
233
+ const db = ctx.db.getDatabase();
234
+ const registry = new LLMProviderRegistry(db);
235
+ const provider = registry.addProvider(name, {
236
+ displayName: options.displayName || name,
237
+ baseUrl: options.baseUrl,
238
+ apiKeyEnv: options.apiKeyEnv,
239
+ models: options.models
240
+ ? options.models.split(",").map((m) => m.trim())
241
+ : [],
242
+ });
243
+
244
+ if (options.json) {
245
+ console.log(JSON.stringify(provider, null, 2));
246
+ } else {
247
+ logger.success(`Added provider ${chalk.cyan(name)}`);
248
+ logger.log(` ${chalk.gray("URL:")} ${provider.baseUrl}`);
249
+ }
250
+
251
+ await shutdown();
252
+ } catch (err) {
253
+ logger.error(`Failed: ${err.message}`);
254
+ process.exit(1);
255
+ }
256
+ });
257
+
258
+ // llm switch - switch active provider
259
+ llm
260
+ .command("switch")
261
+ .description("Switch the active LLM provider")
262
+ .argument("<name>", "Provider name")
263
+ .option("--json", "Output as JSON")
264
+ .action(async (name, options) => {
265
+ try {
266
+ const ctx = await bootstrap({ verbose: program.opts().verbose });
267
+ if (!ctx.db) {
268
+ logger.error("Database not available");
269
+ process.exit(1);
270
+ }
271
+
272
+ const db = ctx.db.getDatabase();
273
+ const registry = new LLMProviderRegistry(db);
274
+ const provider = registry.setActive(name);
275
+
276
+ if (options.json) {
277
+ console.log(JSON.stringify({ active: name, provider }, null, 2));
278
+ } else {
279
+ logger.success(`Switched to ${chalk.cyan(provider.displayName)}`);
280
+ }
281
+
282
+ await shutdown();
283
+ } catch (err) {
284
+ logger.error(`Failed: ${err.message}`);
285
+ process.exit(1);
286
+ }
287
+ });
288
+ }