@tyvm/knowhow 0.0.106 → 0.0.108-dev.bd8f104-dev.bd8f104-dev.bd8f104

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 (87) hide show
  1. package/README.md +45 -0
  2. package/package.json +8 -2
  3. package/scripts/publish.sh +70 -0
  4. package/src/agents/base/base.ts +44 -4
  5. package/src/agents/tools/execCommand.ts +49 -6
  6. package/src/chat/modules/AgentModule.ts +55 -30
  7. package/src/chat/modules/SessionsModule.ts +7 -2
  8. package/src/cli.ts +7 -2
  9. package/src/clients/anthropic.ts +27 -18
  10. package/src/clients/gemini.ts +14 -2
  11. package/src/clients/http.ts +4 -0
  12. package/src/clients/openai.ts +12 -1
  13. package/src/clients/pricing/openai.ts +1 -0
  14. package/src/clients/types.ts +35 -1
  15. package/src/clients/xai.ts +11 -1
  16. package/src/cloudWorker.ts +75 -1
  17. package/src/index.ts +17 -0
  18. package/src/plugins/embedding.ts +11 -6
  19. package/src/plugins/vim.ts +5 -16
  20. package/src/services/KnowhowClient.ts +22 -2
  21. package/src/services/S3.ts +10 -0
  22. package/src/services/modules/types.ts +2 -0
  23. package/src/worker.ts +65 -1
  24. package/src/workers/tools/index.ts +2 -0
  25. package/src/workers/tools/reloadConfig.ts +84 -0
  26. package/tests/clients/AIClient.test.ts +1 -1
  27. package/tests/clients/anthropic.test.ts +202 -0
  28. package/tests/services/WorkerReloadConfig.test.ts +141 -0
  29. package/ts_build/package.json +8 -2
  30. package/ts_build/src/agents/base/base.d.ts +1 -0
  31. package/ts_build/src/agents/base/base.js +31 -4
  32. package/ts_build/src/agents/base/base.js.map +1 -1
  33. package/ts_build/src/agents/tools/execCommand.d.ts +1 -1
  34. package/ts_build/src/agents/tools/execCommand.js +39 -5
  35. package/ts_build/src/agents/tools/execCommand.js.map +1 -1
  36. package/ts_build/src/chat/modules/AgentModule.d.ts +1 -1
  37. package/ts_build/src/chat/modules/AgentModule.js +39 -19
  38. package/ts_build/src/chat/modules/AgentModule.js.map +1 -1
  39. package/ts_build/src/chat/modules/SessionsModule.js +7 -2
  40. package/ts_build/src/chat/modules/SessionsModule.js.map +1 -1
  41. package/ts_build/src/cli.js +8 -2
  42. package/ts_build/src/cli.js.map +1 -1
  43. package/ts_build/src/clients/anthropic.d.ts +5 -5
  44. package/ts_build/src/clients/anthropic.js +27 -18
  45. package/ts_build/src/clients/anthropic.js.map +1 -1
  46. package/ts_build/src/clients/gemini.js +10 -1
  47. package/ts_build/src/clients/gemini.js.map +1 -1
  48. package/ts_build/src/clients/http.js +3 -0
  49. package/ts_build/src/clients/http.js.map +1 -1
  50. package/ts_build/src/clients/openai.js +11 -1
  51. package/ts_build/src/clients/openai.js.map +1 -1
  52. package/ts_build/src/clients/pricing/openai.js +1 -0
  53. package/ts_build/src/clients/pricing/openai.js.map +1 -1
  54. package/ts_build/src/clients/types.d.ts +14 -1
  55. package/ts_build/src/clients/xai.js +11 -1
  56. package/ts_build/src/clients/xai.js.map +1 -1
  57. package/ts_build/src/cloudWorker.d.ts +9 -0
  58. package/ts_build/src/cloudWorker.js +36 -0
  59. package/ts_build/src/cloudWorker.js.map +1 -1
  60. package/ts_build/src/index.js +14 -0
  61. package/ts_build/src/index.js.map +1 -1
  62. package/ts_build/src/plugins/embedding.js +4 -3
  63. package/ts_build/src/plugins/embedding.js.map +1 -1
  64. package/ts_build/src/plugins/vim.js +3 -9
  65. package/ts_build/src/plugins/vim.js.map +1 -1
  66. package/ts_build/src/services/KnowhowClient.d.ts +12 -0
  67. package/ts_build/src/services/KnowhowClient.js +11 -0
  68. package/ts_build/src/services/KnowhowClient.js.map +1 -1
  69. package/ts_build/src/services/S3.js +7 -0
  70. package/ts_build/src/services/S3.js.map +1 -1
  71. package/ts_build/src/services/modules/types.d.ts +2 -0
  72. package/ts_build/src/worker.js +38 -0
  73. package/ts_build/src/worker.js.map +1 -1
  74. package/ts_build/src/workers/tools/index.d.ts +2 -0
  75. package/ts_build/src/workers/tools/index.js +4 -1
  76. package/ts_build/src/workers/tools/index.js.map +1 -1
  77. package/ts_build/src/workers/tools/reloadConfig.d.ts +14 -0
  78. package/ts_build/src/workers/tools/reloadConfig.js +48 -0
  79. package/ts_build/src/workers/tools/reloadConfig.js.map +1 -0
  80. package/ts_build/tests/clients/AIClient.test.js +1 -1
  81. package/ts_build/tests/clients/AIClient.test.js.map +1 -1
  82. package/ts_build/tests/clients/anthropic.test.d.ts +1 -0
  83. package/ts_build/tests/clients/anthropic.test.js +159 -0
  84. package/ts_build/tests/clients/anthropic.test.js.map +1 -0
  85. package/ts_build/tests/services/WorkerReloadConfig.test.d.ts +1 -0
  86. package/ts_build/tests/services/WorkerReloadConfig.test.js +86 -0
  87. package/ts_build/tests/services/WorkerReloadConfig.test.js.map +1 -0
@@ -26,7 +26,7 @@ import {
26
26
  } from "../types";
27
27
  import { GeminiTextPricing } from "./pricing";
28
28
  import { ContextLimits } from "./contextLimits";
29
- import { ModelModality } from "./types";
29
+ import { ModelModality, TokenUsage } from "./types";
30
30
 
31
31
  import {
32
32
  GenericClient,
@@ -524,10 +524,22 @@ export class GenericGeminiClient implements GenericClient {
524
524
  ? this.calculateCost(options.model, usage)
525
525
  : undefined;
526
526
 
527
+ // Map cachedContentTokenCount → prompt_tokens_details.cached_tokens so that
528
+ // base.ts can read cache hit tokens via usage.prompt_tokens_details?.cached_tokens
529
+ const cachedTokens = (usage as any)?.cachedContentTokenCount ?? 0;
530
+ const usageWithCache: TokenUsage | undefined = usage
531
+ ? ({
532
+ prompt_tokens: (usage as any).promptTokenCount ?? 0,
533
+ completion_tokens: (usage as any).candidatesTokenCount ?? 0,
534
+ total_tokens: (usage as any).totalTokenCount,
535
+ prompt_tokens_details: { cached_tokens: cachedTokens },
536
+ } as TokenUsage)
537
+ : undefined;
538
+
527
539
  return {
528
540
  choices,
529
541
  model: options.model,
530
- usage,
542
+ usage: usageWithCache,
531
543
  usd_cost: usdCost,
532
544
  };
533
545
  } catch (error) {
@@ -264,6 +264,10 @@ export class HttpClient implements GenericClient {
264
264
  prompt_tokens: data.usage.input_tokens,
265
265
  completion_tokens: data.usage.output_tokens,
266
266
  total_tokens: data.usage.input_tokens + data.usage.output_tokens,
267
+ prompt_tokens_details: {
268
+ cached_tokens:
269
+ data.usage.input_tokens_details?.cached_tokens ?? 0,
270
+ },
267
271
  }
268
272
  : undefined;
269
273
 
@@ -176,7 +176,14 @@ export class GenericOpenAiClient implements GenericClient {
176
176
  })),
177
177
 
178
178
  model: options.model,
179
- usage: response.usage,
179
+ usage: response.usage ? {
180
+ prompt_tokens: response.usage.prompt_tokens ?? 0,
181
+ completion_tokens: response.usage.completion_tokens ?? 0,
182
+ total_tokens: response.usage.total_tokens,
183
+ prompt_tokens_details: {
184
+ cached_tokens: response.usage.prompt_tokens_details?.cached_tokens ?? 0,
185
+ },
186
+ } : undefined,
180
187
  usd_cost: usdCost,
181
188
  };
182
189
  }
@@ -300,6 +307,10 @@ export class GenericOpenAiClient implements GenericClient {
300
307
  completion_tokens: response.usage.output_tokens,
301
308
  total_tokens:
302
309
  response.usage.input_tokens + response.usage.output_tokens,
310
+ prompt_tokens_details: {
311
+ cached_tokens:
312
+ response.usage.input_tokens_details?.cached_tokens ?? 0,
313
+ },
303
314
  }
304
315
  : undefined;
305
316
 
@@ -156,6 +156,7 @@ export const OpenAiResponsesOnlyModels: string[] = [
156
156
  OpenAiModels.GPT_54_Nano,
157
157
  OpenAiModels.GPT_54_Pro,
158
158
  OpenAiModels.GPT_55_Pro,
159
+ OpenAiModels.GPT_55,
159
160
  OpenAiModels.GPT_5_Pro,
160
161
  OpenAiModels.o1,
161
162
  OpenAiModels.o1_Pro,
@@ -61,6 +61,40 @@ export interface CompletionOptions {
61
61
  * Maps to: OpenAI reasoning_effort, xAI reasoning.effort, Gemini thinkingLevel/thinkingBudget, Anthropic thinking budget.
62
62
  * "low" = minimal thinking, "medium" = balanced, "high" = maximum reasoning */
63
63
  reasoning_effort?: "low" | "medium" | "high";
64
+ /**
65
+ * When true, hints to the client that this task is long-running and it should
66
+ * use a long-TTL cache where available.
67
+ * - Anthropic: enables the `extended-cache-ttl-2025-02-19` beta and sets
68
+ * `cache_control.ttl` to 3600 (1 hour) instead of the default 5-minute ephemeral cache.
69
+ */
70
+ long_ttl_cache?: boolean;
71
+ }
72
+
73
+ /**
74
+ * Normalised token-usage shape that every client must return.
75
+ * All clients must map their provider-specific field names into this structure
76
+ * so that base.ts can accurately track input/output and cache utilization.
77
+ */
78
+ export interface TokenUsage {
79
+ /** Total input/prompt tokens consumed */
80
+ prompt_tokens: number;
81
+ /** Total output/completion tokens generated */
82
+ completion_tokens: number;
83
+ /** Alternative field name for input tokens (some providers use this) */
84
+ input_tokens?: number;
85
+ /** Alternative field name for output tokens (some providers use this) */
86
+ output_tokens?: number;
87
+ /** Convenience total (prompt + completion) */
88
+ total_tokens?: number;
89
+ /** Cache details */
90
+ prompt_tokens_details?: {
91
+ /** Tokens served from the prompt cache (reduces cost) */
92
+ cached_tokens: number;
93
+ };
94
+ /** Anthropic-style cache write tokens */
95
+ cache_creation_input_tokens?: number;
96
+ /** Anthropic-style cache read tokens (alternative field name) */
97
+ cache_read_input_tokens?: number;
64
98
  }
65
99
 
66
100
  export interface CompletionResponse {
@@ -69,7 +103,7 @@ export interface CompletionResponse {
69
103
  }[];
70
104
 
71
105
  model: string;
72
- usage: any;
106
+ usage: TokenUsage | undefined;
73
107
  usd_cost?: number;
74
108
  }
75
109
 
@@ -99,7 +99,14 @@ export class GenericXAIClient implements GenericClient {
99
99
  })),
100
100
 
101
101
  model: options.model,
102
- usage: response.usage,
102
+ usage: response.usage ? {
103
+ prompt_tokens: response.usage.prompt_tokens ?? 0,
104
+ completion_tokens: response.usage.completion_tokens ?? 0,
105
+ total_tokens: response.usage.total_tokens,
106
+ prompt_tokens_details: {
107
+ cached_tokens: response.usage.prompt_tokens_details?.cached_tokens ?? 0,
108
+ },
109
+ } : undefined,
103
110
  usd_cost: usdCost,
104
111
  };
105
112
  }
@@ -200,6 +207,9 @@ export class GenericXAIClient implements GenericClient {
200
207
  prompt_tokens: data.usage.input_tokens,
201
208
  completion_tokens: data.usage.output_tokens,
202
209
  total_tokens: data.usage.input_tokens + data.usage.output_tokens,
210
+ prompt_tokens_details: {
211
+ cached_tokens: data.usage.input_tokens_details?.cached_tokens ?? 0,
212
+ },
203
213
  }
204
214
  : undefined;
205
215
 
@@ -4,9 +4,14 @@ 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";
7
+ import { Language, Config, McpConfig } from "./types";
8
8
  import { S3Service } from "./services/S3";
9
9
 
10
+ export interface CloudWorkerPullOptions {
11
+ id: string;
12
+ apiUrl?: string;
13
+ }
14
+
10
15
  export interface CloudWorkerOptions {
11
16
  create?: boolean;
12
17
  push?: string; // uid of existing cloud worker
@@ -330,3 +335,72 @@ export async function cloudWorker(options: CloudWorkerOptions) {
330
335
  console.log(`\n✅ Cloud worker sync complete!`);
331
336
  }
332
337
  }
338
+
339
+ /**
340
+ * Pull the latest workerConfigJson from the cloud worker API and update the
341
+ * local knowhow.json config to match.
342
+ *
343
+ * This is the "pull" half of the config sync cycle. After running this,
344
+ * you can reload the worker's MCPs (in-process) via the reloadConfig
345
+ * WebSocket message or by calling `knowhow worker` again.
346
+ *
347
+ * Merged fields from workerConfigJson:
348
+ * - mcps → overwrites config.mcps
349
+ * - modules → overwrites config.modules (optional, only if present)
350
+ * - plugins → overwrites config.plugins (optional, only if present)
351
+ * - agents → overwrites config.agents (optional, only if present)
352
+ */
353
+ export async function pullCloudWorkerConfig(options: CloudWorkerPullOptions) {
354
+ const { id, apiUrl = KNOWHOW_API_URL } = options;
355
+
356
+ // Load JWT
357
+ const jwt = await loadJwt();
358
+ if (!jwt) {
359
+ console.error("❌ No JWT token found. Please run 'knowhow login' first.");
360
+ process.exit(1);
361
+ }
362
+
363
+ const client = new KnowhowSimpleClient(apiUrl, jwt);
364
+
365
+ console.log(`🔄 Pulling config for cloud worker ${id}...`);
366
+
367
+ const resp = await client.getCloudWorker(id);
368
+ const remoteWorker = resp.data;
369
+
370
+ if (!remoteWorker) {
371
+ console.error(`❌ Cloud worker ${id} not found.`);
372
+ process.exit(1);
373
+ }
374
+
375
+ const remoteConfig = (remoteWorker.workerConfigJson ?? {}) as {
376
+ mcps?: McpConfig[];
377
+ modules?: string[];
378
+ plugins?: Config["plugins"];
379
+ agents?: Config["agents"];
380
+ };
381
+
382
+ // Load current local config
383
+ const localConfig = await getConfig();
384
+
385
+ // Merge remote fields into local config
386
+ if (remoteConfig.mcps !== undefined) {
387
+ localConfig.mcps = remoteConfig.mcps;
388
+ }
389
+ if (remoteConfig.modules !== undefined) {
390
+ localConfig.modules = remoteConfig.modules;
391
+ }
392
+ if (remoteConfig.plugins !== undefined) {
393
+ localConfig.plugins = remoteConfig.plugins;
394
+ }
395
+ if (remoteConfig.agents !== undefined) {
396
+ localConfig.agents = remoteConfig.agents;
397
+ }
398
+
399
+ await updateConfig(localConfig);
400
+
401
+ const mcpCount = remoteConfig.mcps?.length ?? 0;
402
+ console.log(`✅ Config pulled! ${mcpCount} MCP(s) now configured locally.`);
403
+ console.log(` Run 'knowhow worker' or trigger reloadConfig to apply changes.`);
404
+
405
+ return { mcps: remoteConfig.mcps, modules: remoteConfig.modules };
406
+ }
package/src/index.ts CHANGED
@@ -138,6 +138,23 @@ export async function upload() {
138
138
  if (!source.remoteId) {
139
139
  throw new Error("remoteId is required for knowhow uploads");
140
140
  }
141
+ // Warn if the local embeddingModel differs from the one stored on the backend
142
+ try {
143
+ const remoteEmbedding = await knowhowApiClient.getOrgEmbedding(source.remoteId);
144
+ const localModel = config.embeddingModel || EmbeddingModels.openai.EmbeddingAda2;
145
+ const remoteModel = remoteEmbedding?.modelName;
146
+ if (remoteModel && remoteModel !== localModel) {
147
+ console.warn(
148
+ `⚠️ WARNING: Embedding model mismatch for "${remoteEmbedding.name}" (remoteId: ${source.remoteId}).\n` +
149
+ ` Local config.embeddingModel: ${localModel}\n` +
150
+ ` Backend embedding modelName: ${remoteModel}\n` +
151
+ ` Vectors generated with different models are not comparable — search results will be incorrect.\n` +
152
+ ` Update your config.embeddingModel to "${remoteModel}" or update the backend embedding to "${localModel}".`
153
+ );
154
+ }
155
+ } catch (e) {
156
+ // Non-fatal — don't block upload if metadata fetch fails
157
+ }
141
158
  const url = await knowhowApiClient.getPresignedUploadUrl(source);
142
159
  console.log("Uploading to", url);
143
160
  await AwsS3.uploadToPresignedUrl(url, source.output);
@@ -20,9 +20,12 @@ export class EmbeddingPlugin extends PluginBase {
20
20
 
21
21
  constructor(context) {
22
22
  super(context);
23
-
23
+
24
24
  // Subscribe to file:post-edit events
25
- this.context.Events.on("file:post-edit", this.handleFilePostEdit.bind(this));
25
+ this.context.Events.on(
26
+ "file:post-edit",
27
+ this.handleFilePostEdit.bind(this)
28
+ );
26
29
  }
27
30
 
28
31
  async embed() {
@@ -68,10 +71,12 @@ export class EmbeddingPlugin extends PluginBase {
68
71
  this.log(`Reading entry ${entry.id}`);
69
72
  }
70
73
 
71
- const contextLength = JSON.stringify(context).split(" ").length;
74
+ const ids = context.map((entry) => entry.id);
75
+
76
+ const contextLength = JSON.stringify(ids).split(" ").length;
72
77
  this.log(`Found ${context.length} entries. Loading ${contextLength} words`);
73
78
 
74
- return `EMBEDDING PLUGIN: Our knowledgebase contains this information which can be used to answer the question:
75
- ${JSON.stringify(context)}`;
79
+ return `EMBEDDING PLUGIN: Our knowledgebase indicates these embedding entries may be related to the question:
80
+ ${JSON.stringify(ids)}`;
76
81
  }
77
- }
82
+ }
@@ -73,22 +73,11 @@ export class VimPlugin extends PluginBase {
73
73
 
74
74
  async call() {
75
75
  const vimFiles = await this.getVimFiles();
76
- const fileContents = await Promise.all(
77
- vimFiles.map(async (f) => {
78
- const loaded = await this.getFileContents(f);
79
-
80
- const preview =
81
- loaded.content.length > 1000
82
- ? loaded.content.slice(0, 1000) +
83
- "... file trimmed, read file for full content"
84
- : loaded.content;
85
-
86
- return {
87
- sourceFile: loaded.filePath,
88
- content: loaded.content.slice(0, 1000),
89
- };
90
- })
91
- );
76
+ const fileContents = vimFiles.map((f) => {
77
+ return {
78
+ sourceFile: f,
79
+ };
80
+ });
92
81
  if (fileContents.length === 0) {
93
82
  return "VIM PLUGIN: No files open in vim";
94
83
  }
@@ -171,11 +171,9 @@ export class KnowhowSimpleClient {
171
171
  try {
172
172
  this.jwtValidated = true;
173
173
  const response = await this.me();
174
-
175
174
  const user = response.data.user;
176
175
  const orgs = user.orgs;
177
176
  const orgId = response.data.orgId;
178
-
179
177
  const currentOrg = orgs.find((org) => {
180
178
  return org.organizationId === orgId;
181
179
  });
@@ -227,6 +225,17 @@ export class KnowhowSimpleClient {
227
225
  return presignedUrl;
228
226
  }
229
227
 
228
+ async getOrgEmbedding(id: string) {
229
+ await this.checkJwt();
230
+ const resp = await http.get(
231
+ `${this.baseUrl}/api/org-embeddings/${id}`,
232
+ {
233
+ headers: this.headers,
234
+ }
235
+ );
236
+ return resp.data as { id: string; modelName: string; name: string; [key: string]: unknown };
237
+ }
238
+
230
239
  async updateEmbeddingMetadata(
231
240
  id: string,
232
241
  data: {
@@ -718,6 +727,17 @@ export class KnowhowSimpleClient {
718
727
  );
719
728
  }
720
729
 
730
+ /**
731
+ * Get a single cloud worker by ID
732
+ */
733
+ async getCloudWorker(id: string) {
734
+ await this.checkJwt();
735
+ return http.get<{ id: string; name: string; status: string; workerConfigJson?: Record<string, unknown> }>(
736
+ `${this.baseUrl}/api/cloud-workers/${id}`,
737
+ { headers: this.headers }
738
+ );
739
+ }
740
+
721
741
  /**
722
742
  * Update an existing cloud worker
723
743
  */
@@ -1,5 +1,6 @@
1
1
  import * as fs from "fs";
2
2
  import { createWriteStream, createReadStream } from "fs";
3
+ import * as crypto from "crypto";
3
4
  import { pipeline, Readable } from "stream";
4
5
  import * as util from "util";
5
6
 
@@ -14,10 +15,19 @@ export class S3Service {
14
15
  const fileContent = fs.readFileSync(filePath);
15
16
  const fileStats = await fs.promises.stat(filePath);
16
17
 
18
+ // Compute SHA-256 checksum (base64) — required when presigned URL was
19
+ // generated with ChecksumAlgorithm: SHA256
20
+ const sha256Base64 = crypto
21
+ .createHash("sha256")
22
+ .update(fileContent)
23
+ .digest("base64");
24
+
17
25
  const response = await fetch(presignedUrl, {
18
26
  method: "PUT",
19
27
  headers: {
20
28
  "Content-Length": String(fileStats.size),
29
+ "x-amz-checksum-sha256": sha256Base64,
30
+ "x-amz-sdk-checksum-algorithm": "SHA256",
21
31
  },
22
32
  body: fileContent,
23
33
  // @ts-ignore
@@ -9,6 +9,7 @@ import { PluginService } from "../../plugins/plugins";
9
9
  import { AIClient } from "../../clients";
10
10
  import { ToolsService } from "../Tools";
11
11
  import { MediaProcessorService } from "../MediaProcessorService";
12
+ import { TunnelHandler } from "@tyvm/knowhow-tunnel";
12
13
 
13
14
  /*
14
15
  *
@@ -53,6 +54,7 @@ export interface ModuleContext {
53
54
  Clients: AIClient;
54
55
  Tools: ToolsService;
55
56
  MediaProcessor?: MediaProcessorService;
57
+ Tunnel?: TunnelHandler;
56
58
  }
57
59
 
58
60
  export interface KnowhowModule {
package/src/worker.ts CHANGED
@@ -6,7 +6,7 @@ import { loadJwt } from "./login";
6
6
  import { services } from "./services";
7
7
  import { PasskeySetupService } from "./workers/auth/PasskeySetup";
8
8
  import { WorkerPasskeyAuthService } from "./workers/auth/WorkerPasskeyAuth";
9
- import { makeUnlockTool, makeLockTool } from "./workers/tools";
9
+ import { makeUnlockTool, makeLockTool, makeReloadConfigTool } from "./workers/tools";
10
10
  import { McpServerService } from "./services/Mcp";
11
11
  import * as allTools from "./agents/tools";
12
12
  import workerTools from "./workers/tools";
@@ -14,6 +14,7 @@ import { wait } from "./utils";
14
14
  import { getConfig, updateConfig } from "./config";
15
15
  import { KNOWHOW_API_URL } from "./services/KnowhowClient";
16
16
  import { registerWorkerPath } from "./workerRegistry";
17
+ import { ModulesService } from "./services/modules";
17
18
 
18
19
  const API_URL = KNOWHOW_API_URL;
19
20
 
@@ -264,6 +265,22 @@ export async function worker(options?: {
264
265
  console.log("🔑 Auth tools registered: unlock, lock");
265
266
  }
266
267
 
268
+ // Register the reloadConfig tool so agents can hot-reload MCPs/config
269
+ // without restarting the worker process.
270
+ // Uses a closure over `toolsToUse` so the tool can update it in-place.
271
+ const { reloadConfig, reloadConfigDefinition } = makeReloadConfigTool(
272
+ Mcp,
273
+ Tools,
274
+ mcpServer,
275
+ (newTools) => {
276
+ toolsToUse = newTools;
277
+ }
278
+ );
279
+ Tools.addFunctions({ reloadConfig });
280
+ toolsToUse = [...toolsToUse, reloadConfigDefinition];
281
+
282
+ console.log("🔄 reloadConfig tool registered");
283
+
267
284
  mcpServer.createServer(clientName, clientVersion).withTools(toolsToUse);
268
285
 
269
286
  let connected = false;
@@ -403,6 +420,33 @@ export async function worker(options?: {
403
420
  console.log(`✅ Worker ID recorded: ${parsed.workerId}`);
404
421
  }
405
422
  }
423
+
424
+ // Hot-reload: re-read config, reconnect MCPs, and rebuild the tool list
425
+ // without restarting the worker process.
426
+ if (parsed?.type === "reloadConfig") {
427
+ console.log("🔄 Received reloadConfig — reloading MCPs, modules and tools...");
428
+ try {
429
+ // Re-read fresh config from disk
430
+ const freshConfig = await getConfig();
431
+
432
+ // Close all existing MCP connections
433
+ await Mcp.closeAll();
434
+
435
+ // Reconnect from fresh config and re-register tools
436
+ await Mcp.connectToConfigured(Tools);
437
+
438
+ // Rebuild the allowed tools list from fresh config
439
+ const allowedToolNames = freshConfig.worker?.allowedTools ?? Tools.getToolNames();
440
+ toolsToUse = Tools.getToolsByNames(allowedToolNames);
441
+
442
+ // Update the MCP server with new tool list
443
+ mcpServer.withTools(toolsToUse);
444
+
445
+ console.log(`✅ Config reloaded: ${toolsToUse.length} tools active`);
446
+ } catch (err) {
447
+ console.error("❌ Failed to reload config:", err);
448
+ }
449
+ }
406
450
  } catch {
407
451
  // Not our message — ignore parse errors
408
452
  }
@@ -462,6 +506,16 @@ export async function worker(options?: {
462
506
  tunnelHandler = createTunnelHandler(tunnelConnection!, tunnelConfig);
463
507
  console.log("🌐 Tunnel handler initialized");
464
508
  console.log(tunnelConfig);
509
+
510
+ // Let modules that need the tunnel handler register their addons now
511
+ const tunnelModulesService = new ModulesService();
512
+ const { Agents, Embeddings, Plugins, Clients, Tools, MediaProcessor } = services();
513
+ tunnelModulesService.loadModulesFromConfig({
514
+ Agents, Embeddings, Plugins, Clients, Tools, MediaProcessor,
515
+ Tunnel: tunnelHandler,
516
+ }).catch((err) => {
517
+ console.error("Failed to load tunnel modules:", err);
518
+ });
465
519
  });
466
520
 
467
521
  tunnelConnection.on("close", (code, reason) => {
@@ -708,6 +762,16 @@ export async function tunnel(options?: {
708
762
  tunnelHandler = createTunnelHandler(tunnelConnection, tunnelConfig);
709
763
  console.log("🌐 Tunnel handler initialized");
710
764
  console.log(tunnelConfig);
765
+
766
+ // Let modules that need the tunnel handler register their addons now
767
+ const tunnelModulesService2 = new ModulesService();
768
+ const { Agents: A2, Embeddings: E2, Plugins: P2, Clients: C2, Tools: T2, MediaProcessor: MP2 } = services();
769
+ tunnelModulesService2.loadModulesFromConfig({
770
+ Agents: A2, Embeddings: E2, Plugins: P2, Clients: C2, Tools: T2, MediaProcessor: MP2,
771
+ Tunnel: tunnelHandler,
772
+ }).catch((err) => {
773
+ console.error("Failed to load tunnel modules:", err);
774
+ });
711
775
  });
712
776
 
713
777
  tunnelConnection.on("close", (code, reason) => {
@@ -2,6 +2,7 @@ export * from "./listAllowedPorts";
2
2
  export * from "./getChallenge";
3
3
  export * from "./unlock";
4
4
  export * from "./lock";
5
+ export * from "./reloadConfig";
5
6
 
6
7
  import {
7
8
  listAllowedPorts,
@@ -11,6 +12,7 @@ import {
11
12
  export { makeGetChallengeTool } from "./getChallenge";
12
13
  export { makeUnlockTool } from "./unlock";
13
14
  export { makeLockTool } from "./lock";
15
+ export { makeReloadConfigTool } from "./reloadConfig";
14
16
 
15
17
  export default {
16
18
  tools: { listAllowedPorts },
@@ -0,0 +1,84 @@
1
+ import { Tool } from "../../clients/types";
2
+ import { getConfig } from "../../config";
3
+ import { McpServerService } from "../../services/McpServer";
4
+ import { McpService } from "../../services/Mcp";
5
+ import { ToolsService } from "../../services/Tools";
6
+
7
+ export interface ReloadConfigResult {
8
+ success: boolean;
9
+ toolCount: number;
10
+ mcpCount: number;
11
+ message: string;
12
+ }
13
+
14
+ /**
15
+ * Factory that creates the reloadConfig tool with access to runtime services.
16
+ * The tool re-reads the config from disk, reconnects all MCPs, and rebuilds
17
+ * the active tool list — the same logic as the WebSocket reloadConfig handler.
18
+ *
19
+ * Typical usage after pulling updated config from the cloud worker API:
20
+ * 1. execCommand("knowhow cloudworker --pull <cloudWorkerId>")
21
+ * 2. reloadConfig()
22
+ */
23
+ export function makeReloadConfigTool(
24
+ Mcp: McpService,
25
+ Tools: ToolsService,
26
+ mcpServer: McpServerService,
27
+ setToolsToUse: (tools: ReturnType<typeof Tools.getToolsByNames>) => void
28
+ ) {
29
+ const reloadConfig = async (): Promise<ReloadConfigResult> => {
30
+ try {
31
+ // Re-read fresh config from disk
32
+ const freshConfig = await getConfig();
33
+
34
+ // Close all existing MCP connections
35
+ await Mcp.closeAll();
36
+
37
+ // Reconnect from fresh config and re-register tools
38
+ await Mcp.connectToConfigured(Tools);
39
+
40
+ // Rebuild the allowed tools list from fresh config
41
+ const allowedToolNames =
42
+ freshConfig.worker?.allowedTools ?? Tools.getToolNames();
43
+ const newToolsToUse = Tools.getToolsByNames(allowedToolNames);
44
+ setToolsToUse(newToolsToUse);
45
+
46
+ // Update the MCP server with the new tool list
47
+ mcpServer.withTools(newToolsToUse);
48
+
49
+ const mcpCount = freshConfig.mcps?.length ?? 0;
50
+
51
+ return {
52
+ success: true,
53
+ toolCount: newToolsToUse.length,
54
+ mcpCount,
55
+ message: `Config reloaded: ${newToolsToUse.length} tools active, ${mcpCount} MCP(s) configured`,
56
+ };
57
+ } catch (err) {
58
+ const message = err instanceof Error ? err.message : String(err);
59
+ return {
60
+ success: false,
61
+ toolCount: 0,
62
+ mcpCount: 0,
63
+ message: `Failed to reload config: ${message}`,
64
+ };
65
+ }
66
+ };
67
+
68
+ const reloadConfigDefinition: Tool = {
69
+ type: "function" as const,
70
+ function: {
71
+ name: "reloadConfig",
72
+ description:
73
+ "Reload the worker config from disk, reconnect all MCPs, and rebuild the active tool list. " +
74
+ "Call this after running `knowhow cloudworker --pull <id>` to apply updated MCPs without restarting the worker.",
75
+ parameters: {
76
+ type: "object",
77
+ properties: {},
78
+ required: [],
79
+ },
80
+ },
81
+ };
82
+
83
+ return { reloadConfig, reloadConfigDefinition };
84
+ }
@@ -42,7 +42,7 @@ class FakeClient implements GenericClient {
42
42
  },
43
43
  ],
44
44
  model: options.model,
45
- usage: { total_tokens: 100 },
45
+ usage: { prompt_tokens: 50, completion_tokens: 50, total_tokens: 100 },
46
46
  };
47
47
  }
48
48