@tyvm/knowhow 0.0.108 → 0.0.109-dev.38b1faa

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 +4 -2
  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 +2 -1
  149. package/ts_build/src/services/MediaProcessorService.js +3 -1
  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
@@ -4,12 +4,18 @@ import { KnowhowSimpleClient, KNOWHOW_API_URL } from "./services/KnowhowClient";
4
4
  import { loadJwt } from "./login";
5
5
  import { getConfig, updateConfig, getLanguageConfig } from "./config";
6
6
  import { services } from "./services";
7
- import { Language, Config } from "./types";
8
- import { S3Service } from "./services/S3";
7
+ import { Language, Config, McpConfig } from "./types";
8
+ import { uploadFile, uploadDirectory } from "./fileSync";
9
+
10
+ export interface CloudWorkerPullOptions {
11
+ id: string;
12
+ apiUrl?: string;
13
+ }
9
14
 
10
15
  export interface CloudWorkerOptions {
11
16
  create?: boolean;
12
17
  push?: string; // uid of existing cloud worker
18
+ init?: boolean; // initialize config.files entries (mutates config)
13
19
  name?: string; // optional name for create
14
20
  apiUrl?: string;
15
21
  dryRun?: boolean;
@@ -25,25 +31,6 @@ interface FileToSync {
25
31
  isDirectory?: boolean; // true if this represents a whole directory
26
32
  }
27
33
 
28
- /**
29
- * Recursively list all files in a local directory, returning relative paths
30
- */
31
- function listFilesRecursively(dir: string): string[] {
32
- const results: string[] = [];
33
- if (!fs.existsSync(dir)) return results;
34
- const entries = fs.readdirSync(dir, { withFileTypes: true });
35
- for (const entry of entries) {
36
- if (entry.isDirectory()) {
37
- listFilesRecursively(path.join(dir, entry.name)).forEach((f) =>
38
- results.push(entry.name + "/" + f)
39
- );
40
- } else {
41
- results.push(entry.name);
42
- }
43
- }
44
- return results;
45
- }
46
-
47
34
  /**
48
35
  * Build the worker config JSON from the local knowhow config
49
36
  */
@@ -66,21 +53,19 @@ function buildWorkerConfigJson(config: Config, files: { remotePath: string; loca
66
53
  }
67
54
 
68
55
  /**
69
- * Collect all files from the .knowhow directory that should be synced
70
- * Uses directory-level entries where possible so the worker config stays compact
71
- * and the folder upload/download feature handles individual files automatically.
56
+ * Collect all files from the .knowhow directory that should be synced.
57
+ * Only includes files/directories that currently exist locally.
58
+ * Used by --init to populate config.files.
72
59
  */
73
60
  async function collectFilesToSync(projectName: string): Promise<FileToSync[]> {
74
61
  const filesToSync: FileToSync[] = [];
75
62
 
76
- // Helper to add file if it exists
77
63
  const addIfExists = (localPath: string, remotePath: string) => {
78
64
  if (fs.existsSync(localPath)) {
79
65
  filesToSync.push({ localPath, remotePath });
80
66
  }
81
67
  };
82
68
 
83
- // Helper to add a directory entry if it exists (trailing slash = directory mode)
84
69
  const addDirIfExists = (localPath: string, remotePath: string) => {
85
70
  if (fs.existsSync(localPath)) {
86
71
  filesToSync.push({ localPath: localPath + "/", remotePath: remotePath + "/", isDirectory: true });
@@ -103,7 +88,9 @@ async function collectFilesToSync(projectName: string): Promise<FileToSync[]> {
103
88
  }
104
89
 
105
90
  /**
106
- * Collect files referenced in language.json sources
91
+ * Collect files referenced in language.json sources.
92
+ * These are always re-collected on both --init and --push so that new
93
+ * language term sources are picked up automatically.
107
94
  */
108
95
  async function collectLanguageReferencedFiles(
109
96
  language: Language,
@@ -119,17 +106,14 @@ async function collectLanguageReferencedFiles(
119
106
  if (source.kind !== "file" || !source.data) continue;
120
107
 
121
108
  for (const filePath of source.data) {
122
- // Normalize the path (strip leading ./)
123
109
  const normalizedPath = filePath.replace(/^\.\//, "");
124
110
 
125
111
  // Skip the main knowhow config — it should not be synced to the language folder
126
- // as it would overwrite the worker's own config
127
112
  if (normalizedPath === ".knowhow/knowhow.json") continue;
128
113
 
129
114
  if (fs.existsSync(normalizedPath)) {
130
115
  const basename = path.basename(normalizedPath);
131
116
  const remotePath = `${projectName}/.knowhow/language/${basename}`;
132
- // localPath is the original path so the worker downloads it to the right place
133
117
  filesToSync.push({ localPath: normalizedPath, remotePath, downloadLocalPath: normalizedPath });
134
118
  }
135
119
  }
@@ -140,37 +124,83 @@ async function collectLanguageReferencedFiles(
140
124
  }
141
125
 
142
126
  /**
143
- * Upload a single file to the cloud worker's file storage
127
+ * Collect language-referenced files if language.json is present in the
128
+ * given config.files entries. Returns empty array if language.json is not
129
+ * configured for sync.
130
+ */
131
+ async function collectLanguageFilesIfConfigured(
132
+ configFiles: { remotePath: string; localPath: string }[],
133
+ projectName: string
134
+ ): Promise<FileToSync[]> {
135
+ const syncingLanguage = configFiles.some(
136
+ (f) => !f.remotePath.endsWith("/") && f.remotePath.endsWith("language.json")
137
+ );
138
+ if (!syncingLanguage) return [];
139
+
140
+ const language = await getLanguageConfig();
141
+ return collectLanguageReferencedFiles(language, projectName);
142
+ }
143
+
144
+ /**
145
+ * Initialize the local config.files entries based on what exists in .knowhow/.
146
+ * This is the --init step — mutates config. Run once to set up sync entries.
147
+ * language-referenced files are also collected if language.json is present.
144
148
  */
145
- async function uploadSingleFile(
146
- client: KnowhowSimpleClient,
147
- s3Service: S3Service,
148
- localPath: string,
149
- remotePath: string,
150
- dryRun: boolean
151
- ): Promise<void> {
152
- console.log(` ⬆️ Uploading ${localPath} → ${remotePath}`);
153
-
154
- if (dryRun) {
155
- console.log(` [DRY RUN] Would upload from ${localPath}`);
156
- return;
149
+ export async function initCloudWorker(options: { apiUrl?: string; dryRun?: boolean } = {}) {
150
+ const { dryRun = false } = options;
151
+
152
+ const config = await getConfig();
153
+ if (!config || Object.keys(config).length === 0) {
154
+ console.error("❌ No knowhow config found. Please run 'knowhow init' first.");
155
+ process.exit(1);
157
156
  }
158
157
 
159
- if (!fs.existsSync(localPath)) {
160
- console.warn(` ⚠️ Local file not found, skipping: ${localPath}`);
161
- return;
158
+ const projectName = path.basename(process.cwd());
159
+ console.log(`📁 Project name: ${projectName}`);
160
+
161
+ console.log("\n📂 Collecting files to sync...");
162
+ const mainFiles = await collectFilesToSync(projectName);
163
+ const languageFiles = await collectLanguageFilesIfConfigured(mainFiles, projectName);
164
+
165
+ if (languageFiles.length === 0 && !mainFiles.some((f) => f.remotePath.endsWith("language.json"))) {
166
+ console.log(" ℹ️ Skipping language-referenced files (language.json not found locally)");
162
167
  }
163
168
 
164
- const presignedUrl = await client.getOrgFilePresignedUploadUrl(remotePath);
165
- await s3Service.uploadToPresignedUrl(presignedUrl, localPath);
166
- await client.markOrgFileUploadComplete(remotePath);
169
+ // Deduplicate by remotePath
170
+ const allFilesMap = new Map<string, FileToSync>();
171
+ for (const f of [...mainFiles, ...languageFiles]) {
172
+ allFilesMap.set(f.remotePath, f);
173
+ }
174
+ const allFiles = Array.from(allFilesMap.values());
175
+
176
+ console.log(` Found ${allFiles.length} files to register`);
167
177
 
168
- const stats = fs.statSync(localPath);
169
- console.log(` ✓ Uploaded ${stats.size} bytes`);
178
+ const configFilesEntries = allFiles.map((f) => ({
179
+ remotePath: f.remotePath,
180
+ localPath: f.downloadLocalPath ?? f.localPath,
181
+ direction: "download" as const,
182
+ }));
183
+
184
+ console.log("\n💾 Updating config.files with sync entries...");
185
+ if (!dryRun) {
186
+ const existingFiles = config.files || [];
187
+ const newRemotePaths = new Set(configFilesEntries.map((e) => e.remotePath));
188
+ const preserved = existingFiles.filter((e) => !newRemotePaths.has(e.remotePath));
189
+ config.files = [...preserved, ...configFilesEntries];
190
+ await updateConfig(config);
191
+ console.log(` ✓ Updated config with ${config.files.length} file entries`);
192
+ } else {
193
+ console.log(` [DRY RUN] Would update config with ${configFilesEntries.length} file entries`);
194
+ for (const f of allFiles) {
195
+ console.log(` ${f.localPath} → ${f.remotePath}`);
196
+ }
197
+ }
170
198
  }
171
199
 
172
200
  /**
173
- * Main cloudWorker command handler
201
+ * Main cloudWorker command handler — push/create only.
202
+ * Reads config.files (set up by --init) and also re-collects any language-referenced
203
+ * files so new language term sources are always included without requiring --init again.
174
204
  */
175
205
  export async function cloudWorker(options: CloudWorkerOptions) {
176
206
  const {
@@ -200,10 +230,6 @@ export async function cloudWorker(options: CloudWorkerOptions) {
200
230
  process.exit(1);
201
231
  }
202
232
 
203
- // Load language config
204
- const language = await getLanguageConfig();
205
-
206
- // Get project name from current directory
207
233
  const projectName = path.basename(process.cwd());
208
234
  console.log(`📁 Project name: ${projectName}`);
209
235
 
@@ -213,86 +239,63 @@ export async function cloudWorker(options: CloudWorkerOptions) {
213
239
  // Get S3 service
214
240
  const { AwsS3 } = services();
215
241
 
216
- // Step 1: Collect all files to sync
217
- console.log("\n📂 Collecting files to sync...");
218
- const mainFiles = await collectFilesToSync(projectName);
219
- const languageFiles = await collectLanguageReferencedFiles(language, projectName);
220
-
221
- // Deduplicate by remotePath
222
- const allFilesMap = new Map<string, FileToSync>();
223
- for (const f of [...mainFiles, ...languageFiles]) {
224
- allFilesMap.set(f.remotePath, f);
242
+ // Start with config.files (set up via --init)
243
+ const configFiles = config.files || [];
244
+ if (configFiles.length === 0) {
245
+ console.warn("⚠️ No files configured. Run 'knowhow cloudworker --init' first to set up file sync entries.");
225
246
  }
226
- const allFiles = Array.from(allFilesMap.values());
227
247
 
228
- console.log(` Found ${allFiles.length} files to sync`);
229
-
230
- if (dryRun) {
231
- console.log("\n📋 Files that would be synced:");
232
- for (const f of allFiles) {
233
- console.log(` ${f.localPath} → ${f.remotePath}`);
234
- }
248
+ // Re-collect language-referenced files on every push (if language.json is in config.files)
249
+ // so that new language term sources are picked up without needing --init again.
250
+ const languageFiles = await collectLanguageFilesIfConfigured(configFiles, projectName);
251
+ if (languageFiles.length > 0) {
252
+ console.log(` + ${languageFiles.length} language-referenced file(s) to sync`);
235
253
  }
236
254
 
237
- // Step 2: Build the config.files array for all synced files
238
- const configFilesEntries = allFiles.map((f) => ({
239
- remotePath: f.remotePath,
240
- localPath: f.downloadLocalPath ?? f.localPath,
241
- direction: "download" as const,
242
- }));
243
-
244
- // Step 3: Update config.files and save
245
- console.log("\n💾 Updating config.files with sync entries...");
246
- if (!dryRun) {
247
- // Preserve any existing files entries not in our set
248
- const existingFiles = config.files || [];
249
- const newRemotePaths = new Set(configFilesEntries.map((e) => e.remotePath));
250
-
251
- // Keep entries that don't overlap with new ones
252
- const preserved = existingFiles.filter(
253
- (e) => !newRemotePaths.has(e.remotePath)
254
- );
255
+ // Merge language files into the upload list (deduplicate by remotePath)
256
+ const allFilesMap = new Map<string, { remotePath: string; localPath: string }>();
257
+ for (const f of configFiles) {
258
+ allFilesMap.set(f.remotePath, f);
259
+ }
260
+ for (const f of languageFiles) {
261
+ const entry = { remotePath: f.remotePath, localPath: f.downloadLocalPath ?? f.localPath };
262
+ allFilesMap.set(f.remotePath, entry);
263
+ }
264
+ const allFiles = Array.from(allFilesMap.values());
255
265
 
256
- config.files = [...preserved, ...configFilesEntries];
266
+ // If new language files were found, update config.files so they persist
267
+ if (languageFiles.length > 0 && !dryRun) {
268
+ config.files = allFiles.map((f) => ({ ...f, direction: "download" as const }));
257
269
  await updateConfig(config);
258
- console.log(` ✓ Updated config with ${config.files.length} file entries`);
259
- } else {
260
- console.log(` [DRY RUN] Would update config with ${configFilesEntries.length} file entries`);
261
270
  }
262
271
 
263
- // Step 4: Build workerConfigJson
264
- const workerConfigJson = buildWorkerConfigJson(config, configFilesEntries);
272
+ // Build the workerConfigJson using the full file list
273
+ const workerConfigJson = buildWorkerConfigJson(config, allFiles.map((f) => ({ ...f, direction: "download" })));
265
274
 
266
- // Step 5: Upload all files
267
- console.log(`\n🚀 Uploading ${allFiles.length} files...`);
275
+ // Upload all files
276
+ console.log(`\n🚀 Uploading ${allFiles.length} configured files...`);
268
277
  let successCount = 0;
269
278
  let failCount = 0;
270
279
 
271
- for (const file of allFiles) {
280
+ for (const mount of allFiles) {
281
+ const { remotePath, localPath } = mount;
272
282
  try {
273
- if (file.isDirectory) {
274
- // Upload all files recursively in the local directory
275
- const localDir = file.localPath.endsWith("/") ? file.localPath : file.localPath + "/";
276
- const remoteDir = file.remotePath.endsWith("/") ? file.remotePath : file.remotePath + "/";
277
- const relFiles = listFilesRecursively(localDir);
278
- console.log(` 📁 Uploading directory ${localDir} → ${remoteDir} (${relFiles.length} files)`);
279
- for (const relFile of relFiles) {
280
- await uploadSingleFile(client, AwsS3, localDir + relFile, remoteDir + relFile, dryRun);
281
- successCount++;
282
- }
283
+ if (remotePath.endsWith("/") || localPath.endsWith("/")) {
284
+ const count = await uploadDirectory(client, AwsS3, remotePath, localPath, dryRun);
285
+ successCount += count;
283
286
  } else {
284
- await uploadSingleFile(client, AwsS3, file.localPath, file.remotePath, dryRun);
287
+ await uploadFile(client, AwsS3, remotePath, localPath, dryRun);
285
288
  successCount++;
286
289
  }
287
290
  } catch (error) {
288
- console.error(` ❌ Failed to upload ${file.localPath}: ${error.message}`);
291
+ console.error(` ❌ Failed to upload ${localPath}: ${error.message}`);
289
292
  failCount++;
290
293
  }
291
294
  }
292
295
 
293
296
  console.log(`\n ✓ Upload complete: ${successCount} succeeded, ${failCount} failed`);
294
297
 
295
- // Step 6: Create or update cloud worker
298
+ // Create or update cloud worker
296
299
  if (create) {
297
300
  const workerName = name || `${projectName}-worker`;
298
301
  console.log(`\n🌩️ Creating cloud worker "${workerName}"...`);
@@ -330,3 +333,62 @@ export async function cloudWorker(options: CloudWorkerOptions) {
330
333
  console.log(`\n✅ Cloud worker sync complete!`);
331
334
  }
332
335
  }
336
+
337
+ /**
338
+ * Pull the latest workerConfigJson from the cloud worker API and update the
339
+ * local knowhow.json config to match.
340
+ */
341
+ export async function pullCloudWorkerConfig(options: CloudWorkerPullOptions) {
342
+ const { id, apiUrl = KNOWHOW_API_URL } = options;
343
+
344
+ // Load JWT
345
+ const jwt = await loadJwt();
346
+ if (!jwt) {
347
+ console.error("❌ No JWT token found. Please run 'knowhow login' first.");
348
+ process.exit(1);
349
+ }
350
+
351
+ const client = new KnowhowSimpleClient(apiUrl, jwt);
352
+
353
+ console.log(`🔄 Pulling config for cloud worker ${id}...`);
354
+
355
+ const resp = await client.getCloudWorker(id);
356
+ const remoteWorker = resp.data;
357
+
358
+ if (!remoteWorker) {
359
+ console.error(`❌ Cloud worker ${id} not found.`);
360
+ process.exit(1);
361
+ }
362
+
363
+ const remoteConfig = (remoteWorker.workerConfigJson ?? {}) as {
364
+ mcps?: McpConfig[];
365
+ modules?: string[];
366
+ plugins?: Config["plugins"];
367
+ agents?: Config["agents"];
368
+ };
369
+
370
+ // Load current local config
371
+ const localConfig = await getConfig();
372
+
373
+ // Merge remote fields into local config
374
+ if (remoteConfig.mcps !== undefined) {
375
+ localConfig.mcps = remoteConfig.mcps;
376
+ }
377
+ if (remoteConfig.modules !== undefined) {
378
+ localConfig.modules = remoteConfig.modules;
379
+ }
380
+ if (remoteConfig.plugins !== undefined) {
381
+ localConfig.plugins = remoteConfig.plugins;
382
+ }
383
+ if (remoteConfig.agents !== undefined) {
384
+ localConfig.agents = remoteConfig.agents;
385
+ }
386
+
387
+ await updateConfig(localConfig);
388
+
389
+ const mcpCount = remoteConfig.mcps?.length ?? 0;
390
+ console.log(`✅ Config pulled! ${mcpCount} MCP(s) now configured locally.`);
391
+ console.log(` Run 'knowhow worker' or trigger reloadConfig to apply changes.`);
392
+
393
+ return { mcps: remoteConfig.mcps, modules: remoteConfig.modules };
394
+ }
@@ -0,0 +1,246 @@
1
+ import { Command } from "commander";
2
+ import { readPromptFile } from "../ai";
3
+ import { AgentModule } from "../chat/modules/AgentModule";
4
+ import { AskModule } from "../chat/modules/AskModule";
5
+ import { SearchModule } from "../chat/modules/SearchModule";
6
+ import { SessionsModule } from "../chat/modules/SessionsModule";
7
+ import { SetupModule } from "../chat/modules/SetupModule";
8
+
9
+ async function readStdin(): Promise<string> {
10
+ return new Promise((resolve) => {
11
+ let data = "";
12
+ process.stdin.setEncoding("utf8");
13
+
14
+ if (process.stdin.isTTY) {
15
+ resolve("");
16
+ return;
17
+ }
18
+
19
+ process.stdin.on("readable", () => {
20
+ const chunk = process.stdin.read();
21
+ if (chunk !== null) data += chunk;
22
+ });
23
+
24
+ process.stdin.on("end", () => resolve(data.trim()));
25
+ });
26
+ }
27
+
28
+ export function addAgentCommand(program: Command, getChatService: () => any): void {
29
+ program
30
+ .command("agent")
31
+ .description("Spin up agents directly from CLI")
32
+ .option(
33
+ "--provider <provider>",
34
+ "AI provider (openai, anthropic, google, xai)"
35
+ )
36
+ .option("--model <model>", "Specific model for the provider")
37
+ .option("--agent-name <name>", "Which agent to use", "Patcher")
38
+ .option(
39
+ "--max-time-limit <minutes>",
40
+ "Time limit for agent execution (minutes)",
41
+ "30"
42
+ )
43
+ .option(
44
+ "--max-spend-limit <dollars>",
45
+ "Cost limit for agent execution (dollars)",
46
+ "10"
47
+ )
48
+ .option("--message-id <messageId>", "Knowhow message ID for task tracking")
49
+ .option("--sync-fs", "Enable filesystem-based synchronization")
50
+ .option(
51
+ "--task-id <taskId>",
52
+ "Pre-generated task ID (used with --sync-fs for predictable agent directory path)"
53
+ )
54
+ .option("--prompt-file <path>", "Custom prompt template file with {text}")
55
+ .option("--input <text>", "Task input (fallback to stdin if not provided)")
56
+ .option(
57
+ "--resume",
58
+ "Resume a previously started task using the --task-id (local FS or remote)"
59
+ )
60
+ .action(async (options) => {
61
+ try {
62
+ const { setupServices } = await import("./services");
63
+ await setupServices();
64
+ const chatService = getChatService();
65
+ const agentModule = new AgentModule();
66
+
67
+ if (options.resume) {
68
+ const threads = await agentModule.loadThreadsForTask(
69
+ options.taskId,
70
+ options.messageId
71
+ );
72
+ const resumeInput =
73
+ options.input || "Please continue from where you left off.";
74
+
75
+ await agentModule.initialize(chatService);
76
+ const { taskCompleted: resumed } =
77
+ await agentModule.resumeFromMessages({
78
+ agentName: options.agentName || "Patcher",
79
+ input: resumeInput,
80
+ threads,
81
+ messageId: options.messageId,
82
+ taskId: options.taskId,
83
+ });
84
+ await resumed;
85
+ return;
86
+ }
87
+
88
+ let input = options.input;
89
+
90
+ if (!input && !options.promptFile) {
91
+ input = await readStdin();
92
+ }
93
+
94
+ input = readPromptFile(options.promptFile, input);
95
+
96
+ if (!input) {
97
+ console.error(
98
+ "Error: No input provided. Use --input flag, pipe input via stdin, or provide --prompt-file."
99
+ );
100
+ process.exit(1);
101
+ }
102
+
103
+ await agentModule.initialize(chatService);
104
+ const { taskCompleted } = await agentModule.setupAgent({
105
+ ...options,
106
+ input,
107
+ maxTimeLimit: parseInt(options.maxTimeLimit, 10),
108
+ maxSpendLimit: parseFloat(options.maxSpendLimit),
109
+ run: true,
110
+ });
111
+ await taskCompleted;
112
+ } catch (error) {
113
+ console.error("Error running agent:", error);
114
+ process.exit(1);
115
+ }
116
+ });
117
+ }
118
+
119
+ export function addAskCommand(program: Command, getChatService: () => any, getConfig: () => any): void {
120
+ program
121
+ .command("ask")
122
+ .description("Direct AI questioning without agent overhead")
123
+ .option("--provider <provider>", "AI provider to use")
124
+ .option("--model <model>", "Specific model")
125
+ .option("--input <text>", "Question (fallback to stdin if not provided)")
126
+ .option("--prompt-file <path>", "Custom prompt template file")
127
+ .action(async (options) => {
128
+ try {
129
+ const { setupServices } = await import("./services");
130
+ await setupServices();
131
+ const chatService = getChatService();
132
+ const config = getConfig();
133
+ let input = options.input;
134
+
135
+ if (!input && !options.promptFile) {
136
+ input = await readStdin();
137
+ }
138
+
139
+ input = readPromptFile(options.promptFile, input);
140
+
141
+ if (!input) {
142
+ console.error(
143
+ "Error: No question provided. Use --input flag, pipe input via stdin, or provide --prompt-file."
144
+ );
145
+ process.exit(1);
146
+ }
147
+
148
+ const askModule = new AskModule();
149
+ await askModule.initialize(chatService);
150
+ await askModule.processAIQuery(input, {
151
+ plugins: config.plugins.enabled,
152
+ currentModel: options.model,
153
+ currentProvider: options.provider,
154
+ chatHistory: [],
155
+ });
156
+ } catch (error) {
157
+ console.error("Error asking AI:", error);
158
+ process.exit(1);
159
+ }
160
+ });
161
+ }
162
+
163
+ export function addSetupCommand(program: Command, getChatService: () => any): void {
164
+ program
165
+ .command("setup")
166
+ .description("Ask the agent to configure knowhow")
167
+ .action(async () => {
168
+ try {
169
+ const { setupServices } = await import("./services");
170
+ await setupServices();
171
+ const chatService = getChatService();
172
+ const agentModule = new AgentModule();
173
+ await agentModule.initialize(chatService);
174
+ const setupModule = new SetupModule(agentModule);
175
+ await setupModule.initialize(chatService);
176
+ await setupModule.handleSetupCommand([]);
177
+ } catch (error) {
178
+ console.error("Error running agent:", error);
179
+ process.exit(1);
180
+ }
181
+ });
182
+ }
183
+
184
+ export function addSearchCommand(program: Command): void {
185
+ program
186
+ .command("search")
187
+ .description("Search embeddings directly from CLI")
188
+ .option(
189
+ "--input <text>",
190
+ "Search query (fallback to stdin if not provided)"
191
+ )
192
+ .option(
193
+ "-e, --embedding <path>",
194
+ "Specific embedding path (default: all)",
195
+ "all"
196
+ )
197
+ .action(async (options) => {
198
+ try {
199
+ const { setupServices } = await import("./services");
200
+ await setupServices();
201
+ let input = options.input;
202
+ if (!input) {
203
+ input = await readStdin();
204
+ if (!input) {
205
+ console.error(
206
+ "Error: No search query provided. Use --input flag or pipe input via stdin."
207
+ );
208
+ process.exit(1);
209
+ }
210
+ }
211
+
212
+ await new SearchModule().searchEmbeddingsCLI(input, options.embedding);
213
+ } catch (error) {
214
+ console.error("Error searching embeddings:", error);
215
+ process.exit(1);
216
+ }
217
+ });
218
+ }
219
+
220
+ export function addSessionsCommand(program: Command, getChatService: () => any): void {
221
+ program
222
+ .command("sessions")
223
+ .description("Manage agent sessions from CLI")
224
+ .option(
225
+ "--all",
226
+ "Show all historical sessions (default: current process only)"
227
+ )
228
+ .option("--csv", "Output sessions as CSV")
229
+ .action(async (options) => {
230
+ try {
231
+ const chatService = getChatService();
232
+ const agentModule = new AgentModule();
233
+ await agentModule.initialize(chatService);
234
+ const sessionsModule = new SessionsModule(agentModule);
235
+ await sessionsModule.initialize(chatService);
236
+ await sessionsModule.logSessionTable(
237
+ options.all || false,
238
+ options.csv || false,
239
+ true
240
+ );
241
+ } catch (error) {
242
+ console.error("Error listing sessions:", error);
243
+ process.exit(1);
244
+ }
245
+ });
246
+ }