@tyvm/knowhow 0.0.108 → 0.0.109-dev.2b94ba2

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 (236) hide show
  1. package/README.md +45 -0
  2. package/package.json +9 -4
  3. package/scripts/build-for-node.sh +10 -24
  4. package/scripts/publish.sh +86 -0
  5. package/src/agents/base/base.ts +10 -0
  6. package/src/agents/tools/execCommand.ts +49 -6
  7. package/src/agents/tools/index.ts +0 -1
  8. package/src/agents/tools/list.ts +2 -4
  9. package/src/chat/CliChatService.ts +11 -2
  10. package/src/chat/modules/AgentModule.ts +61 -31
  11. package/src/chat/modules/SessionsModule.ts +47 -3
  12. package/src/chat/modules/SystemModule.ts +2 -2
  13. package/src/chat/renderer/CompactRenderer.ts +20 -0
  14. package/src/chat/renderer/ConsoleRenderer.ts +19 -0
  15. package/src/chat/renderer/FancyRenderer.ts +19 -0
  16. package/src/chat/renderer/types.ts +11 -0
  17. package/src/cli.ts +91 -659
  18. package/src/clients/anthropic.ts +18 -17
  19. package/src/clients/index.ts +31 -11
  20. package/src/clients/openai.ts +8 -5
  21. package/src/clients/types.ts +48 -10
  22. package/src/clients/withRetry.ts +89 -0
  23. package/src/cloudWorker.ts +175 -113
  24. package/src/commands/agent.ts +246 -0
  25. package/src/commands/misc.ts +174 -0
  26. package/src/commands/modules.ts +552 -0
  27. package/src/commands/services.ts +77 -0
  28. package/src/commands/workers.ts +168 -0
  29. package/src/config.ts +38 -1
  30. package/src/fileSync.ts +70 -29
  31. package/src/hashes.ts +35 -13
  32. package/src/index.ts +18 -0
  33. package/src/logger.ts +197 -0
  34. package/src/plugins/embedding.ts +11 -6
  35. package/src/plugins/plugins.ts +0 -21
  36. package/src/plugins/vim.ts +5 -16
  37. package/src/processors/JsonCompressor.ts +6 -6
  38. package/src/services/EventService.ts +61 -1
  39. package/src/services/KnowhowClient.ts +34 -4
  40. package/src/services/MediaProcessorService.ts +79 -10
  41. package/src/services/modules/index.ts +102 -53
  42. package/src/services/modules/types.ts +6 -0
  43. package/src/tunnel.ts +216 -0
  44. package/src/types.ts +0 -1
  45. package/src/worker.ts +105 -312
  46. package/src/workers/auth/WsMiddleware.ts +99 -0
  47. package/src/workers/auth/authMiddleware.ts +104 -0
  48. package/src/workers/auth/types.ts +14 -2
  49. package/src/workers/tools/index.ts +2 -0
  50. package/src/workers/tools/reloadConfig.ts +84 -0
  51. package/tests/services/WorkerReloadConfig.test.ts +141 -0
  52. package/tests/unit/clients/AIClient.test.ts +446 -0
  53. package/tests/unit/clients/withRetry.test.ts +319 -0
  54. package/tests/unit/commands/github-credentials.test.ts +210 -0
  55. package/tests/unit/modules/moduleLoading.test.ts +39 -37
  56. package/tests/unit/plugins/pluginLoading.test.ts +0 -85
  57. package/ts_build/package.json +9 -4
  58. package/ts_build/src/agents/base/base.js +11 -0
  59. package/ts_build/src/agents/base/base.js.map +1 -1
  60. package/ts_build/src/agents/tools/execCommand.d.ts +1 -1
  61. package/ts_build/src/agents/tools/execCommand.js +39 -5
  62. package/ts_build/src/agents/tools/execCommand.js.map +1 -1
  63. package/ts_build/src/agents/tools/index.d.ts +0 -1
  64. package/ts_build/src/agents/tools/index.js +0 -1
  65. package/ts_build/src/agents/tools/index.js.map +1 -1
  66. package/ts_build/src/agents/tools/list.js +2 -4
  67. package/ts_build/src/agents/tools/list.js.map +1 -1
  68. package/ts_build/src/chat/CliChatService.js +14 -2
  69. package/ts_build/src/chat/CliChatService.js.map +1 -1
  70. package/ts_build/src/chat/modules/AgentModule.d.ts +1 -1
  71. package/ts_build/src/chat/modules/AgentModule.js +43 -20
  72. package/ts_build/src/chat/modules/AgentModule.js.map +1 -1
  73. package/ts_build/src/chat/modules/SessionsModule.js +37 -3
  74. package/ts_build/src/chat/modules/SessionsModule.js.map +1 -1
  75. package/ts_build/src/chat/modules/SystemModule.js +2 -2
  76. package/ts_build/src/chat/modules/SystemModule.js.map +1 -1
  77. package/ts_build/src/chat/renderer/CompactRenderer.d.ts +4 -0
  78. package/ts_build/src/chat/renderer/CompactRenderer.js +16 -0
  79. package/ts_build/src/chat/renderer/CompactRenderer.js.map +1 -1
  80. package/ts_build/src/chat/renderer/ConsoleRenderer.d.ts +4 -0
  81. package/ts_build/src/chat/renderer/ConsoleRenderer.js +16 -0
  82. package/ts_build/src/chat/renderer/ConsoleRenderer.js.map +1 -1
  83. package/ts_build/src/chat/renderer/FancyRenderer.d.ts +4 -0
  84. package/ts_build/src/chat/renderer/FancyRenderer.js +16 -0
  85. package/ts_build/src/chat/renderer/FancyRenderer.js.map +1 -1
  86. package/ts_build/src/chat/renderer/types.d.ts +2 -0
  87. package/ts_build/src/cli.js +47 -519
  88. package/ts_build/src/cli.js.map +1 -1
  89. package/ts_build/src/clients/anthropic.d.ts +5 -5
  90. package/ts_build/src/clients/anthropic.js +18 -17
  91. package/ts_build/src/clients/anthropic.js.map +1 -1
  92. package/ts_build/src/clients/index.js +9 -10
  93. package/ts_build/src/clients/index.js.map +1 -1
  94. package/ts_build/src/clients/openai.js +4 -4
  95. package/ts_build/src/clients/openai.js.map +1 -1
  96. package/ts_build/src/clients/types.d.ts +15 -8
  97. package/ts_build/src/clients/withRetry.d.ts +2 -0
  98. package/ts_build/src/clients/withRetry.js +60 -0
  99. package/ts_build/src/clients/withRetry.js.map +1 -0
  100. package/ts_build/src/cloudWorker.d.ts +14 -0
  101. package/ts_build/src/cloudWorker.js +105 -66
  102. package/ts_build/src/cloudWorker.js.map +1 -1
  103. package/ts_build/src/commands/agent.d.ts +6 -0
  104. package/ts_build/src/commands/agent.js +229 -0
  105. package/ts_build/src/commands/agent.js.map +1 -0
  106. package/ts_build/src/commands/misc.d.ts +10 -0
  107. package/ts_build/src/commands/misc.js +197 -0
  108. package/ts_build/src/commands/misc.js.map +1 -0
  109. package/ts_build/src/commands/modules.d.ts +3 -0
  110. package/ts_build/src/commands/modules.js +487 -0
  111. package/ts_build/src/commands/modules.js.map +1 -0
  112. package/ts_build/src/commands/services.d.ts +5 -0
  113. package/ts_build/src/commands/services.js +87 -0
  114. package/ts_build/src/commands/services.js.map +1 -0
  115. package/ts_build/src/commands/workers.d.ts +6 -0
  116. package/ts_build/src/commands/workers.js +168 -0
  117. package/ts_build/src/commands/workers.js.map +1 -0
  118. package/ts_build/src/config.d.ts +1 -0
  119. package/ts_build/src/config.js +33 -1
  120. package/ts_build/src/config.js.map +1 -1
  121. package/ts_build/src/fileSync.d.ts +6 -0
  122. package/ts_build/src/fileSync.js +50 -23
  123. package/ts_build/src/fileSync.js.map +1 -1
  124. package/ts_build/src/hashes.d.ts +2 -2
  125. package/ts_build/src/hashes.js +35 -9
  126. package/ts_build/src/hashes.js.map +1 -1
  127. package/ts_build/src/index.d.ts +1 -0
  128. package/ts_build/src/index.js +17 -1
  129. package/ts_build/src/index.js.map +1 -1
  130. package/ts_build/src/logger.d.ts +21 -0
  131. package/ts_build/src/logger.js +106 -0
  132. package/ts_build/src/logger.js.map +1 -0
  133. package/ts_build/src/plugins/embedding.js +4 -3
  134. package/ts_build/src/plugins/embedding.js.map +1 -1
  135. package/ts_build/src/plugins/plugins.d.ts +0 -2
  136. package/ts_build/src/plugins/plugins.js +0 -11
  137. package/ts_build/src/plugins/plugins.js.map +1 -1
  138. package/ts_build/src/plugins/vim.js +3 -9
  139. package/ts_build/src/plugins/vim.js.map +1 -1
  140. package/ts_build/src/processors/JsonCompressor.js +4 -4
  141. package/ts_build/src/processors/JsonCompressor.js.map +1 -1
  142. package/ts_build/src/services/EventService.d.ts +6 -1
  143. package/ts_build/src/services/EventService.js +29 -0
  144. package/ts_build/src/services/EventService.js.map +1 -1
  145. package/ts_build/src/services/KnowhowClient.d.ts +13 -1
  146. package/ts_build/src/services/KnowhowClient.js +19 -2
  147. package/ts_build/src/services/KnowhowClient.js.map +1 -1
  148. package/ts_build/src/services/MediaProcessorService.d.ts +5 -4
  149. package/ts_build/src/services/MediaProcessorService.js +53 -8
  150. package/ts_build/src/services/MediaProcessorService.js.map +1 -1
  151. package/ts_build/src/services/modules/index.d.ts +33 -0
  152. package/ts_build/src/services/modules/index.js +73 -49
  153. package/ts_build/src/services/modules/index.js.map +1 -1
  154. package/ts_build/src/services/modules/types.d.ts +6 -0
  155. package/ts_build/src/tunnel.d.ts +27 -0
  156. package/ts_build/src/tunnel.js +112 -0
  157. package/ts_build/src/tunnel.js.map +1 -0
  158. package/ts_build/src/types.d.ts +0 -1
  159. package/ts_build/src/types.js.map +1 -1
  160. package/ts_build/src/worker.d.ts +1 -4
  161. package/ts_build/src/worker.js +59 -227
  162. package/ts_build/src/worker.js.map +1 -1
  163. package/ts_build/src/workers/auth/WsMiddleware.d.ts +8 -0
  164. package/ts_build/src/workers/auth/WsMiddleware.js +65 -0
  165. package/ts_build/src/workers/auth/WsMiddleware.js.map +1 -0
  166. package/ts_build/src/workers/auth/authMiddleware.d.ts +3 -0
  167. package/ts_build/src/workers/auth/authMiddleware.js +60 -0
  168. package/ts_build/src/workers/auth/authMiddleware.js.map +1 -0
  169. package/ts_build/src/workers/auth/types.d.ts +8 -1
  170. package/ts_build/src/workers/tools/index.d.ts +2 -0
  171. package/ts_build/src/workers/tools/index.js +4 -1
  172. package/ts_build/src/workers/tools/index.js.map +1 -1
  173. package/ts_build/src/workers/tools/reloadConfig.d.ts +14 -0
  174. package/ts_build/src/workers/tools/reloadConfig.js +48 -0
  175. package/ts_build/src/workers/tools/reloadConfig.js.map +1 -0
  176. package/ts_build/tests/services/WorkerReloadConfig.test.d.ts +1 -0
  177. package/ts_build/tests/services/WorkerReloadConfig.test.js +86 -0
  178. package/ts_build/tests/services/WorkerReloadConfig.test.js.map +1 -0
  179. package/ts_build/tests/unit/clients/AIClient.test.d.ts +1 -0
  180. package/ts_build/tests/unit/clients/AIClient.test.js +339 -0
  181. package/ts_build/tests/unit/clients/AIClient.test.js.map +1 -0
  182. package/ts_build/tests/unit/clients/withRetry.test.d.ts +1 -0
  183. package/ts_build/tests/unit/clients/withRetry.test.js +225 -0
  184. package/ts_build/tests/unit/clients/withRetry.test.js.map +1 -0
  185. package/ts_build/tests/unit/commands/github-credentials.test.d.ts +1 -0
  186. package/ts_build/tests/unit/commands/github-credentials.test.js +145 -0
  187. package/ts_build/tests/unit/commands/github-credentials.test.js.map +1 -0
  188. package/ts_build/tests/unit/modules/moduleLoading.test.js +20 -26
  189. package/ts_build/tests/unit/modules/moduleLoading.test.js.map +1 -1
  190. package/ts_build/tests/unit/plugins/pluginLoading.test.js +0 -65
  191. package/ts_build/tests/unit/plugins/pluginLoading.test.js.map +1 -1
  192. package/src/agents/tools/executeScript/README.md +0 -94
  193. package/src/agents/tools/executeScript/definition.ts +0 -79
  194. package/src/agents/tools/executeScript/examples/dependency-injection-validation.ts +0 -272
  195. package/src/agents/tools/executeScript/examples/quick-test.ts +0 -74
  196. package/src/agents/tools/executeScript/examples/serialization-test.ts +0 -321
  197. package/src/agents/tools/executeScript/examples/test-runner.ts +0 -197
  198. package/src/agents/tools/executeScript/index.ts +0 -98
  199. package/src/services/script-execution/SandboxContext.ts +0 -282
  200. package/src/services/script-execution/ScriptExecutor.ts +0 -441
  201. package/src/services/script-execution/ScriptPolicy.ts +0 -194
  202. package/src/services/script-execution/ScriptTracer.ts +0 -249
  203. package/src/services/script-execution/types.ts +0 -134
  204. package/ts_build/src/agents/tools/executeScript/definition.d.ts +0 -2
  205. package/ts_build/src/agents/tools/executeScript/definition.js +0 -76
  206. package/ts_build/src/agents/tools/executeScript/definition.js.map +0 -1
  207. package/ts_build/src/agents/tools/executeScript/examples/dependency-injection-validation.d.ts +0 -18
  208. package/ts_build/src/agents/tools/executeScript/examples/dependency-injection-validation.js +0 -192
  209. package/ts_build/src/agents/tools/executeScript/examples/dependency-injection-validation.js.map +0 -1
  210. package/ts_build/src/agents/tools/executeScript/examples/quick-test.d.ts +0 -3
  211. package/ts_build/src/agents/tools/executeScript/examples/quick-test.js +0 -64
  212. package/ts_build/src/agents/tools/executeScript/examples/quick-test.js.map +0 -1
  213. package/ts_build/src/agents/tools/executeScript/examples/serialization-test.d.ts +0 -15
  214. package/ts_build/src/agents/tools/executeScript/examples/serialization-test.js +0 -266
  215. package/ts_build/src/agents/tools/executeScript/examples/serialization-test.js.map +0 -1
  216. package/ts_build/src/agents/tools/executeScript/examples/test-runner.d.ts +0 -4
  217. package/ts_build/src/agents/tools/executeScript/examples/test-runner.js +0 -208
  218. package/ts_build/src/agents/tools/executeScript/examples/test-runner.js.map +0 -1
  219. package/ts_build/src/agents/tools/executeScript/index.d.ts +0 -28
  220. package/ts_build/src/agents/tools/executeScript/index.js +0 -72
  221. package/ts_build/src/agents/tools/executeScript/index.js.map +0 -1
  222. package/ts_build/src/services/script-execution/SandboxContext.d.ts +0 -34
  223. package/ts_build/src/services/script-execution/SandboxContext.js +0 -189
  224. package/ts_build/src/services/script-execution/SandboxContext.js.map +0 -1
  225. package/ts_build/src/services/script-execution/ScriptExecutor.d.ts +0 -19
  226. package/ts_build/src/services/script-execution/ScriptExecutor.js +0 -269
  227. package/ts_build/src/services/script-execution/ScriptExecutor.js.map +0 -1
  228. package/ts_build/src/services/script-execution/ScriptPolicy.d.ts +0 -28
  229. package/ts_build/src/services/script-execution/ScriptPolicy.js +0 -115
  230. package/ts_build/src/services/script-execution/ScriptPolicy.js.map +0 -1
  231. package/ts_build/src/services/script-execution/ScriptTracer.d.ts +0 -19
  232. package/ts_build/src/services/script-execution/ScriptTracer.js +0 -186
  233. package/ts_build/src/services/script-execution/ScriptTracer.js.map +0 -1
  234. package/ts_build/src/services/script-execution/types.d.ts +0 -108
  235. package/ts_build/src/services/script-execution/types.js +0 -3
  236. package/ts_build/src/services/script-execution/types.js.map +0 -1
@@ -0,0 +1,552 @@
1
+ import { Command } from "commander";
2
+ import { execSync } from "child_process";
3
+ import * as fs from "fs";
4
+ import * as path from "path";
5
+ import * as os from "os";
6
+ import { getConfig, getGlobalConfig, updateConfig, updateGlobalConfig } from "../config";
7
+ import * as readline from "readline";
8
+
9
+ // Default built-in modules that `knowhow modules setup` adds to the config.
10
+ export const BUILTIN_MODULES = [
11
+ "@tyvm/knowhow-module-script",
12
+ "@tyvm/knowhow-module-terminal",
13
+ ];
14
+
15
+ /**
16
+ * Returns the path to the .knowhow directory (used as npm install prefix).
17
+ * For global: ~/.knowhow
18
+ * For local: <cwd>/.knowhow
19
+ */
20
+ function getKnowhowDir(isGlobal: boolean): string {
21
+ if (isGlobal) {
22
+ return path.join(os.homedir(), ".knowhow");
23
+ }
24
+ return path.join(process.cwd(), ".knowhow");
25
+ }
26
+
27
+ /**
28
+ * Ensures the .knowhow directory has a minimal package.json so
29
+ * `npm install --prefix` works cleanly without polluting the project root.
30
+ */
31
+ function ensureKnowhowPackageJson(knowhowDir: string): void {
32
+ const pkgPath = path.join(knowhowDir, "package.json");
33
+ if (!fs.existsSync(pkgPath)) {
34
+ fs.mkdirSync(knowhowDir, { recursive: true });
35
+ fs.writeFileSync(
36
+ pkgPath,
37
+ JSON.stringify({ name: "knowhow-modules", private: true, version: "1.0.0" }, null, 2)
38
+ );
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Run `npm install --prefix <knowhowDir> <mod>` so that modules land in
44
+ * .knowhow/node_modules rather than the project's node_modules.
45
+ */
46
+ function npmInstallToKnowhow(mod: string, knowhowDir: string): void {
47
+ execSync(`npm install --prefix "${knowhowDir}" ${mod}`, {
48
+ stdio: "inherit",
49
+ encoding: "utf-8",
50
+ });
51
+ }
52
+
53
+ /**
54
+ * Returns true if a module package is already installed in the given knowhow dir.
55
+ */
56
+ function isModuleInstalled(mod: string, knowhowDir: string): boolean {
57
+ try {
58
+ require.resolve(mod, {
59
+ paths: [path.join(knowhowDir, "node_modules"), knowhowDir],
60
+ });
61
+ return true;
62
+ } catch {
63
+ return false;
64
+ }
65
+ }
66
+
67
+ interface NpmRegistryInfo {
68
+ latestVersion: string;
69
+ publishedAt: string;
70
+ }
71
+
72
+ /**
73
+ * Fetch the latest version and publish time from the npm registry for a package.
74
+ * Returns null if the package info can't be fetched.
75
+ */
76
+ async function fetchNpmRegistryInfo(mod: string): Promise<NpmRegistryInfo | null> {
77
+ try {
78
+ // npm view <pkg> version time --json returns either a single value or array
79
+ const output = execSync(`npm view ${mod} version time --json`, {
80
+ stdio: ["ignore", "pipe", "pipe"],
81
+ encoding: "utf-8",
82
+ });
83
+ const parsed = JSON.parse(output.trim());
84
+ let latestVersion: string;
85
+ let timestamps: Record<string, string> = {};
86
+ if (Array.isArray(parsed)) {
87
+ latestVersion = parsed[0];
88
+ timestamps = parsed[1] || {};
89
+ } else if (parsed && typeof parsed === "object") {
90
+ latestVersion = parsed["version"] || "";
91
+ timestamps = parsed["time"] || {};
92
+ } else {
93
+ latestVersion = String(parsed);
94
+ }
95
+ const publishedAt = timestamps[latestVersion] || timestamps["modified"] || "";
96
+ return { latestVersion, publishedAt };
97
+ } catch {
98
+ return null;
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Simple engine range checker — handles the common cases:
104
+ * ">=22" ">=22.0.0" "^20" "20.x" "*" ""
105
+ * Returns true if the given nodeVersion satisfies the range.
106
+ * Falls back to true (permissive) for unsupported range syntax.
107
+ */
108
+ function nodeSatisfiesRange(nodeVersion: string, range: string): boolean {
109
+ if (!range || range === "*" || range === "") return true;
110
+
111
+ // Parse "major.minor.patch" from e.g. "v20.17.0"
112
+ const vMatch = nodeVersion.replace(/^v/, "").match(/^(\d+)(?:\.(\d+))?(?:\.(\d+))?/);
113
+ if (!vMatch) return true;
114
+ const vMajor = parseInt(vMatch[1], 10);
115
+ const vMinor = parseInt(vMatch[2] ?? "0", 10);
116
+ const vPatch = parseInt(vMatch[3] ?? "0", 10);
117
+ const vNum = vMajor * 1_000_000 + vMinor * 1_000 + vPatch;
118
+
119
+ function parseVersion(s: string): number {
120
+ const m = s.trim().match(/^(\d+)(?:\.(\d+))?(?:\.(\d+))?/);
121
+ if (!m) return 0;
122
+ return parseInt(m[1], 10) * 1_000_000 + parseInt(m[2] ?? "0", 10) * 1_000 + parseInt(m[3] ?? "0", 10);
123
+ }
124
+
125
+ // Handle " || " — any segment satisfying is fine
126
+ if (range.includes("||")) {
127
+ return range.split("||").some((r) => nodeSatisfiesRange(nodeVersion, r.trim()));
128
+ }
129
+
130
+ // Handle space-separated AND conditions e.g. ">=14 <18"
131
+ const parts = range.trim().split(/\s+/);
132
+ for (const part of parts) {
133
+ const gteMatch = part.match(/^>=(.+)/);
134
+ const gtMatch = part.match(/^>(?!=)(.+)/);
135
+ const lteMatch = part.match(/^<=(.+)/);
136
+ const ltMatch = part.match(/^<(?!=)(.+)/);
137
+ const caretMatch = part.match(/^\^(\d+)/);
138
+ const tildeMatch = part.match(/^~(\d+)(?:\.(\d+))?/);
139
+ const exactMatch = part.match(/^(\d+(?:\.\d+)*)/);
140
+
141
+ if (gteMatch) {
142
+ if (vNum < parseVersion(gteMatch[1])) return false;
143
+ } else if (gtMatch) {
144
+ if (vNum <= parseVersion(gtMatch[1])) return false;
145
+ } else if (lteMatch) {
146
+ if (vNum > parseVersion(lteMatch[1])) return false;
147
+ } else if (ltMatch) {
148
+ if (vNum >= parseVersion(ltMatch[1])) return false;
149
+ } else if (caretMatch) {
150
+ const base = parseVersion(caretMatch[1]);
151
+ const baseMajor = parseInt(caretMatch[1], 10);
152
+ if (vNum < base || vMajor !== baseMajor) return false;
153
+ } else if (tildeMatch) {
154
+ const baseMajor = parseInt(tildeMatch[1], 10);
155
+ const baseMinor = parseInt(tildeMatch[2] ?? "0", 10);
156
+ const base = parseVersion(`${baseMajor}.${baseMinor}`);
157
+ const nextMinor = parseVersion(`${baseMajor}.${baseMinor + 1}`);
158
+ if (vNum < base || vNum >= nextMinor) return false;
159
+ } else if (exactMatch && !part.startsWith("v")) {
160
+ // e.g. "20.x" or "20"
161
+ const xMatch = part.match(/^(\d+)(?:\.x)?$/);
162
+ if (xMatch) {
163
+ if (vMajor !== parseInt(xMatch[1], 10)) return false;
164
+ }
165
+ }
166
+ // Unknown operators — fall through (permissive)
167
+ }
168
+ return true;
169
+ }
170
+
171
+ /**
172
+ * Fetch the latest version of a package that is compatible with the current
173
+ * Node.js engine. Falls back to "@latest" if no engine info is available.
174
+ *
175
+ * Uses the npm registry API to get per-version engine requirements.
176
+ */
177
+ async function fetchLatestCompatibleVersion(mod: string): Promise<string> {
178
+ const currentNode = process.version; // e.g. "v20.17.0"
179
+ try {
180
+ // Encode scoped package names for URL (e.g. @tyvm/pkg -> @tyvm%2Fpkg)
181
+ const encodedMod = mod.replace(/^@/, "").replace("/", "%2F");
182
+ const registryUrl = mod.startsWith("@")
183
+ ? `https://registry.npmjs.org/@${encodedMod}`
184
+ : `https://registry.npmjs.org/${mod}`;
185
+
186
+ const response = await fetch(registryUrl);
187
+ if (!response.ok) throw new Error(`Registry returned ${response.status}`);
188
+ const pkgData = await response.json() as any;
189
+
190
+ // pkgData.versions is a map of version -> package metadata
191
+ const versionsMap: Record<string, any> = pkgData.versions ?? {};
192
+ const allVersions = Object.keys(versionsMap);
193
+
194
+ // Build per-version engine map from actual per-version metadata
195
+ const enginesByVersion: Record<string, string> = {};
196
+ for (const [v, meta] of Object.entries(versionsMap)) {
197
+ enginesByVersion[v] = (meta as any)?.engines?.node ?? "";
198
+ }
199
+
200
+ if (allVersions.length === 0) return `${mod}@latest`;
201
+
202
+ // Sort versions descending (simple semver numeric sort)
203
+ const sorted = [...allVersions].sort((a, b) => {
204
+ const pa = a.split(".").map(Number);
205
+ const pb = b.split(".").map(Number);
206
+ for (let i = 0; i < 3; i++) {
207
+ if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pb[i] ?? 0) - (pa[i] ?? 0);
208
+ }
209
+ return 0;
210
+ });
211
+
212
+ for (const v of sorted) {
213
+ const engineRange = enginesByVersion[v] ?? "";
214
+ if (nodeSatisfiesRange(currentNode, engineRange)) {
215
+ return `${mod}@${v}`;
216
+ }
217
+ }
218
+
219
+ // No compatible version found — warn and fall back to latest
220
+ console.warn(`āš ļø No version of ${mod} found compatible with Node ${currentNode}. Installing latest anyway.`);
221
+ return `${mod}@latest`;
222
+ } catch {
223
+ // Can't fetch registry info — fall back to latest
224
+ return `${mod}@latest`;
225
+ }
226
+ }
227
+
228
+ /**
229
+ * Get the currently installed version of a package in .knowhow/node_modules.
230
+ */
231
+ function getInstalledVersion(mod: string, knowhowDir: string): string | null {
232
+ try {
233
+ const pkgJsonPath = path.join(knowhowDir, "node_modules", mod, "package.json");
234
+ const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
235
+ return pkgJson.version ?? null;
236
+ } catch {
237
+ return null;
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Format a date string as a human-readable relative time (e.g. "2 days ago").
243
+ */
244
+ function formatRelativeTime(isoDate: string): string {
245
+ if (!isoDate) return "unknown";
246
+ const then = new Date(isoDate).getTime();
247
+ if (isNaN(then)) return "unknown";
248
+ const diffMs = Date.now() - then;
249
+ const diffMins = Math.floor(diffMs / 60_000);
250
+ if (diffMins < 2) return "just now";
251
+ if (diffMins < 60) return `${diffMins} minutes ago`;
252
+ const diffHours = Math.floor(diffMins / 60);
253
+ if (diffHours < 24) return `${diffHours} hour${diffHours !== 1 ? "s" : ""} ago`;
254
+ const diffDays = Math.floor(diffHours / 24);
255
+ if (diffDays < 30) return `${diffDays} day${diffDays !== 1 ? "s" : ""} ago`;
256
+ const diffMonths = Math.floor(diffDays / 30);
257
+ if (diffMonths < 12) return `${diffMonths} month${diffMonths !== 1 ? "s" : ""} ago`;
258
+ const diffYears = Math.floor(diffMonths / 12);
259
+ return `${diffYears} year${diffYears !== 1 ? "s" : ""} ago`;
260
+ }
261
+
262
+ /**
263
+ * Prompt the user for a yes/no confirmation.
264
+ */
265
+ function promptConfirm(question: string): Promise<boolean> {
266
+ return new Promise((resolve) => {
267
+ const rl = readline.createInterface({
268
+ input: process.stdin,
269
+ output: process.stdout,
270
+ });
271
+ rl.question(`${question} (y/N) `, (answer) => {
272
+ rl.close();
273
+ resolve(
274
+ answer.trim().toLowerCase() === "y" ||
275
+ answer.trim().toLowerCase() === "yes"
276
+ );
277
+ });
278
+ });
279
+ }
280
+
281
+ export function addModulesCommand(program: Command): void {
282
+ const modulesCmd = program
283
+ .command("modules")
284
+ .description("Manage knowhow modules (install, add to config, list)");
285
+
286
+ modulesCmd
287
+ .command("setup")
288
+ .description(
289
+ "Add default built-in modules to your config and install them into .knowhow/node_modules"
290
+ )
291
+ .option("--global", "Use the global config (~/.knowhow/knowhow.json)")
292
+ .action(async (opts) => {
293
+ try {
294
+ const isGlobal: boolean = opts.global ?? false;
295
+ const cfg = isGlobal ? await getGlobalConfig() : await getConfig();
296
+ const configLabel = isGlobal
297
+ ? "~/.knowhow/knowhow.json"
298
+ : ".knowhow/knowhow.json";
299
+
300
+ if (!cfg.modules) cfg.modules = [];
301
+
302
+ const knowhowDir = getKnowhowDir(isGlobal);
303
+ ensureKnowhowPackageJson(knowhowDir);
304
+
305
+ // Even if modules are already in the config, they may not be installed.
306
+ // Check and install any that are missing from .knowhow/node_modules.
307
+ let anyChanges = false;
308
+ for (const mod of BUILTIN_MODULES) {
309
+ if (!mod.startsWith(".") && !mod.startsWith("/")) {
310
+ if (!isModuleInstalled(mod, knowhowDir)) {
311
+ const installTarget = await fetchLatestCompatibleVersion(mod);
312
+ console.log(`šŸ“¦ Installing ${installTarget}...`);
313
+ npmInstallToKnowhow(installTarget, knowhowDir);
314
+ console.log(`āœ… Installed ${mod}`);
315
+ anyChanges = true;
316
+ }
317
+ }
318
+ if (!cfg.modules.includes(mod)) {
319
+ cfg.modules.push(mod);
320
+ console.log(`āœ… Added ${mod} to ${configLabel}`);
321
+ anyChanges = true;
322
+ }
323
+ }
324
+
325
+ if (!anyChanges) {
326
+ console.log(
327
+ `āœ… All default modules are already in ${configLabel} and installed. Nothing to do.`
328
+ );
329
+ } else {
330
+ await (isGlobal ? updateGlobalConfig(cfg) : updateConfig(cfg));
331
+ console.log(
332
+ `\nšŸŽ‰ Setup complete! Modules ready in ${knowhowDir}/node_modules.`
333
+ );
334
+ }
335
+ } catch (error: any) {
336
+ console.error("Error during modules setup:", error.message ?? error);
337
+ process.exit(1);
338
+ }
339
+ });
340
+
341
+ modulesCmd
342
+ .command("install [module]")
343
+ .description(
344
+ "Install a module into .knowhow/node_modules and add it to your config. " +
345
+ "If no module name is given, installs all modules already in the config."
346
+ )
347
+ .option("--global", "Use the global config (~/.knowhow/knowhow.json)")
348
+ .option("--latest", "Force install the latest version (bypasses package-lock)")
349
+ .action(async (moduleName: string | undefined, opts) => {
350
+ try {
351
+ const isGlobal: boolean = opts.global ?? false;
352
+ const cfg = isGlobal ? await getGlobalConfig() : await getConfig();
353
+ const configLabel = isGlobal
354
+ ? "~/.knowhow/knowhow.json"
355
+ : ".knowhow/knowhow.json";
356
+
357
+ if (!cfg.modules) cfg.modules = [];
358
+
359
+ const knowhowDir = getKnowhowDir(isGlobal);
360
+ ensureKnowhowPackageJson(knowhowDir);
361
+
362
+ if (!moduleName) {
363
+ // No module specified — install everything already in the config
364
+ const installable = cfg.modules.filter(
365
+ (m) => !m.startsWith(".") && !m.startsWith("/")
366
+ );
367
+ if (installable.length === 0) {
368
+ console.log(`ℹ No installable modules found in ${configLabel}.`);
369
+ return;
370
+ }
371
+ console.log(
372
+ `šŸ“¦ Installing ${installable.length} module(s) from ${configLabel} into ${knowhowDir}/node_modules...`
373
+ );
374
+ for (const mod of installable) {
375
+ console.log(` šŸ“¦ Installing ${mod}...`);
376
+ const installTarget = opts.latest ? await fetchLatestCompatibleVersion(mod) : mod;
377
+ npmInstallToKnowhow(installTarget, knowhowDir);
378
+ console.log(` āœ… Installed ${mod}`);
379
+ }
380
+ console.log(`\nšŸŽ‰ All modules installed!`);
381
+ return;
382
+ }
383
+
384
+ // Install the specified module
385
+ const installTarget = opts.latest ? await fetchLatestCompatibleVersion(moduleName) : moduleName;
386
+ console.log(`šŸ“¦ Installing ${installTarget} into ${knowhowDir}/node_modules...`);
387
+ npmInstallToKnowhow(installTarget, knowhowDir);
388
+ console.log(`āœ… Installed ${moduleName}`);
389
+
390
+ // Add to config if not already there
391
+ if (!cfg.modules.includes(moduleName)) {
392
+ cfg.modules.push(moduleName);
393
+ if (isGlobal) {
394
+ await updateGlobalConfig(cfg);
395
+ } else {
396
+ await updateConfig(cfg);
397
+ }
398
+ console.log(`āœ… Added ${moduleName} to ${configLabel}`);
399
+ } else {
400
+ console.log(`ℹ ${moduleName} is already in ${configLabel}`);
401
+ }
402
+ } catch (error: any) {
403
+ console.error("Error during module install:", error.message ?? error);
404
+ process.exit(1);
405
+ }
406
+ });
407
+
408
+ modulesCmd
409
+ .command("list")
410
+ .description("List all modules in your config")
411
+ .option("--global", "Show global config modules only")
412
+ .action(async (opts) => {
413
+ try {
414
+ const isGlobal: boolean = opts.global ?? false;
415
+ const globalCfg = await getGlobalConfig();
416
+ const localCfg = isGlobal ? null : await getConfig();
417
+
418
+ const globalModules = globalCfg.modules || [];
419
+ const localModules = localCfg?.modules || [];
420
+
421
+ if (isGlobal) {
422
+ console.log(`\n🌐 Global modules (~/.knowhow/knowhow.json):`);
423
+ if (globalModules.length === 0) {
424
+ console.log(" (none)");
425
+ } else {
426
+ globalModules.forEach((m, i) => console.log(` ${i + 1}. ${m}`));
427
+ }
428
+ } else {
429
+ console.log(`\n🌐 Global modules (~/.knowhow/knowhow.json):`);
430
+ if (globalModules.length === 0) {
431
+ console.log(" (none)");
432
+ } else {
433
+ globalModules.forEach((m, i) => console.log(` ${i + 1}. ${m}`));
434
+ }
435
+ console.log(`\nšŸ“ Local modules (.knowhow/knowhow.json):`);
436
+ if (localModules.length === 0) {
437
+ console.log(" (none)");
438
+ } else {
439
+ localModules.forEach((m, i) => console.log(` ${i + 1}. ${m}`));
440
+ }
441
+ }
442
+ } catch (error: any) {
443
+ console.error("Error listing modules:", error.message ?? error);
444
+ process.exit(1);
445
+ }
446
+ });
447
+
448
+ modulesCmd
449
+ .command("update")
450
+ .description(
451
+ "Check for updates to all modules in your config and update them. " +
452
+ "Shows installed vs latest version with publish date before updating."
453
+ )
454
+ .option("--global", "Use the global config (~/.knowhow/knowhow.json)")
455
+ .option("-y, --yes", "Skip confirmation prompt and update all outdated modules automatically")
456
+ .action(async (opts) => {
457
+ try {
458
+ const isGlobal: boolean = opts.global ?? false;
459
+ const skipConfirm: boolean = opts.yes ?? false;
460
+ const cfg = isGlobal ? await getGlobalConfig() : await getConfig();
461
+ const configLabel = isGlobal
462
+ ? "~/.knowhow/knowhow.json"
463
+ : ".knowhow/knowhow.json";
464
+
465
+ if (!cfg.modules || cfg.modules.length === 0) {
466
+ console.log(`ℹ No modules found in ${configLabel}.`);
467
+ return;
468
+ }
469
+
470
+ const knowhowDir = getKnowhowDir(isGlobal);
471
+ ensureKnowhowPackageJson(knowhowDir);
472
+
473
+ // Only check npm packages (not local paths)
474
+ const installable = cfg.modules.filter(
475
+ (m) => !m.startsWith(".") && !m.startsWith("/")
476
+ );
477
+
478
+ if (installable.length === 0) {
479
+ console.log(`ℹ No npm modules found in ${configLabel}.`);
480
+ return;
481
+ }
482
+
483
+ console.log(`šŸ” Checking for updates to ${installable.length} module(s)...\n`);
484
+
485
+ interface UpdateInfo {
486
+ mod: string;
487
+ installed: string | null;
488
+ latest: string;
489
+ compatibleVersion: string; // e.g. "@tyvm/knowhow-module-script@0.0.4"
490
+ publishedAt: string;
491
+ needsUpdate: boolean;
492
+ }
493
+
494
+ const updates: UpdateInfo[] = [];
495
+
496
+ for (const mod of installable) {
497
+ const registryInfo = await fetchNpmRegistryInfo(mod);
498
+ if (!registryInfo) {
499
+ console.log(` āš ļø ${mod}: could not fetch registry info (skipping)`);
500
+ continue;
501
+ }
502
+ const installed = getInstalledVersion(mod, knowhowDir);
503
+ const { latestVersion, publishedAt } = registryInfo;
504
+ // Find the latest compatible version for the current Node.js engine
505
+ const compatibleInstallTarget = await fetchLatestCompatibleVersion(mod);
506
+ const compatibleVersion = compatibleInstallTarget.replace(/^[^@]+@/, ""); // strip "pkg@" prefix
507
+ const needsUpdate = installed !== compatibleVersion;
508
+ const timeAgo = formatRelativeTime(publishedAt);
509
+
510
+ if (needsUpdate) {
511
+ const installedStr = installed ?? "(not installed)";
512
+ const versionLabel = compatibleVersion !== latestVersion
513
+ ? `${compatibleVersion} (latest compatible with Node ${process.version}; absolute latest: ${latestVersion})`
514
+ : compatibleVersion;
515
+ console.log(` šŸ“¦ ${mod}`);
516
+ console.log(` installed: ${installedStr} → latest: ${versionLabel} (published ${timeAgo})`);
517
+ } else {
518
+ console.log(` āœ… ${mod} v${compatibleVersion} (up to date, published ${timeAgo})`);
519
+ }
520
+ updates.push({ mod, installed, latest: compatibleVersion, compatibleVersion: compatibleInstallTarget, publishedAt, needsUpdate });
521
+ }
522
+
523
+ const toUpdate = updates.filter((u) => u.needsUpdate);
524
+
525
+ if (toUpdate.length === 0) {
526
+ console.log(`\nāœ… All modules are up to date!`);
527
+ return;
528
+ }
529
+
530
+ console.log(`\n${toUpdate.length} module(s) can be updated.`);
531
+
532
+ if (!skipConfirm) {
533
+ const confirmed = await promptConfirm(`Update ${toUpdate.length} module(s) now?`);
534
+ if (!confirmed) {
535
+ console.log("Cancelled.");
536
+ return;
537
+ }
538
+ }
539
+
540
+ console.log("");
541
+ for (const { mod, compatibleVersion } of toUpdate) {
542
+ console.log(` šŸ“¦ Updating ${compatibleVersion}...`);
543
+ npmInstallToKnowhow(compatibleVersion, knowhowDir);
544
+ console.log(` āœ… Updated ${mod}`);
545
+ }
546
+ console.log(`\nšŸŽ‰ Update complete! ${toUpdate.length} module(s) updated.`);
547
+ } catch (error: any) {
548
+ console.error("Error during modules update:", error.message ?? error);
549
+ process.exit(1);
550
+ }
551
+ });
552
+ }
@@ -0,0 +1,77 @@
1
+ import { includedTools } from "../agents/tools/list";
2
+ import * as allTools from "../agents/tools";
3
+ import { LazyToolsService, services } from "../services";
4
+ import { agents } from "../agents";
5
+ import { ModulesService } from "../services/modules";
6
+
7
+ /**
8
+ * Shared service setup used by commands that need full services (chat, agent, worker, etc.)
9
+ */
10
+ export async function setupServices() {
11
+ const {
12
+ Agents,
13
+ Mcp,
14
+ Clients,
15
+ Tools: AllTools,
16
+ Embeddings,
17
+ Plugins,
18
+ Events,
19
+ MediaProcessor,
20
+ } = services();
21
+
22
+
23
+ // cli uses LazyTools to keep context slim
24
+ const Tools = new LazyToolsService();
25
+
26
+ Tools.setContext({
27
+ ...AllTools.getContext(),
28
+ });
29
+
30
+ const agentContext: import("../agents/base/base").AgentContext = {
31
+ ...services(),
32
+ Tools,
33
+ };
34
+
35
+ const { Researcher, Developer, Patcher, Setup } = agents({
36
+ ...agentContext,
37
+ });
38
+
39
+ Agents.registerAgent(Researcher);
40
+ Agents.registerAgent(Patcher);
41
+ Agents.registerAgent(Developer);
42
+ Agents.registerAgent(Setup);
43
+ Agents.loadAgentsFromConfig(agentContext);
44
+
45
+ Tools.defineTools(includedTools, allTools);
46
+
47
+ Tools.addContext("Mcp", Mcp);
48
+
49
+ Agents.setAgentContext(agentContext);
50
+
51
+ console.log("šŸ”Œ Connecting to MCP...");
52
+ try {
53
+ await Mcp.connectToConfigured(Tools);
54
+ } catch (mcpError) {
55
+ const msg = mcpError instanceof Error ? mcpError.message : String(mcpError);
56
+ console.warn(
57
+ `⚠ Some MCP servers failed to connect (continuing without them): ${msg}`
58
+ );
59
+ }
60
+ console.log("Connecting to clients...");
61
+ await Clients.registerConfiguredModels();
62
+ console.log("āœ“ Services are set up and ready to go!");
63
+
64
+ console.log("šŸ“¦ Loading modules from config...");
65
+ const modulesService = new ModulesService();
66
+ await modulesService.loadModulesFromConfig({
67
+ Agents,
68
+ Embeddings,
69
+ Plugins,
70
+ Clients,
71
+ Tools,
72
+ MediaProcessor,
73
+ Events
74
+ });
75
+
76
+ return { Tools, Clients };
77
+ }