@dyyz1993/create-agent 2.0.0 → 2.1.0

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 (165) hide show
  1. package/package.json +1 -1
  2. package/src/commands/create.ts +31 -31
  3. package/src/commands/workspace.ts +112 -105
  4. package/src/lib/copy.ts +24 -1
  5. package/templates/agent/electron/main.js +46 -0
  6. package/templates/agent/electron/preload.js +5 -0
  7. package/templates/agent/electron-builder.json +40 -0
  8. package/templates/agent/eslint.config.mjs +17 -2
  9. package/templates/agent/package.json +69 -3
  10. package/templates/agent/src/__tests__/hybrid-mode.test.ts +126 -0
  11. package/templates/agent/src/__tests__/server-config-security.test.ts +55 -0
  12. package/templates/agent/src/bun/index.ts +96 -41
  13. package/templates/agent/src/bun/three.d.ts +1 -0
  14. package/templates/agent/src/gateway/__tests__/ws-handler-token.test.ts +118 -0
  15. package/templates/agent/src/gateway/http-routes.ts +1 -1
  16. package/templates/agent/src/gateway/ws-handler.ts +84 -56
  17. package/templates/agent/src/mainview/App.tsx +29 -26
  18. package/templates/agent/src/mainview/__tests__/i18n/i18n.test.ts +1 -0
  19. package/templates/agent/src/mainview/__tests__/setup.ts +32 -29
  20. package/templates/agent/src/mainview/__tests__/theme-variables.test.ts +36 -0
  21. package/templates/agent/src/mainview/components/chat/ChatPanel.tsx +88 -88
  22. package/templates/agent/src/mainview/components/common/ErrorBoundary.tsx +1 -58
  23. package/templates/agent/src/mainview/components/common/LanguageSwitcher.tsx +1 -0
  24. package/templates/agent/src/mainview/components/common/ThemeToggle.tsx +1 -0
  25. package/templates/agent/src/mainview/components/feed/FeedPanel.tsx +232 -210
  26. package/templates/agent/src/mainview/components/file-preview/VirtualizedCodeView.tsx +105 -81
  27. package/templates/agent/src/mainview/components/search/SearchPanel.tsx +427 -378
  28. package/templates/agent/src/mainview/components/todo/TodoPanel.tsx +149 -122
  29. package/templates/agent/src/mainview/hooks/use-input-history.ts +70 -61
  30. package/templates/agent/src/mainview/lib/api-client.ts +179 -172
  31. package/templates/agent/src/mainview/main.tsx +4 -10
  32. package/templates/agent/src/mainview/stores/use-feed-store.ts +107 -107
  33. package/templates/agent/src/mainview/utils/drop-handler.ts +114 -115
  34. package/templates/agent/src/server-config.ts +34 -32
  35. package/templates/agent/src/server.ts +42 -54
  36. package/templates/agent/src/shared/handlers/__tests__/chat-concurrency.test.ts +127 -0
  37. package/templates/agent/src/shared/handlers/__tests__/handler-isolation.test.ts +244 -0
  38. package/templates/agent/src/shared/handlers/bash.ts +65 -65
  39. package/templates/agent/src/shared/handlers/chat.ts +189 -155
  40. package/templates/agent/src/shared/handlers/debug.ts +12 -0
  41. package/templates/agent/src/shared/handlers/feed.ts +31 -32
  42. package/templates/agent/src/shared/handlers/git.ts +286 -243
  43. package/templates/agent/src/shared/handlers/index.ts +1 -0
  44. package/templates/agent/src/shared/handlers/rules.ts +31 -31
  45. package/templates/agent/src/shared/handlers/todo.ts +31 -31
  46. package/templates/agent/src/shared/http-routes.ts +250 -0
  47. package/templates/agent/src/shared/lib/__tests__/web-server.test.ts +190 -0
  48. package/templates/agent/src/shared/lib/bash-security.ts +43 -43
  49. package/templates/agent/src/shared/lib/logger.ts +117 -95
  50. package/templates/agent/src/shared/lib/web-server.ts +128 -0
  51. package/templates/agent/src/shared/modules/debug.ts +8 -0
  52. package/templates/agent/src/shared/rpc-schema.ts +16 -3
  53. package/templates/agent/test-upload.txt +0 -0
  54. package/templates/agent/tsconfig.ipc.json +14 -0
  55. package/templates/agent/tsconfig.json +13 -3
  56. package/templates/chat/eslint.config.mjs +15 -2
  57. package/templates/chat/package.json +13 -2
  58. package/templates/chat/src/__tests__/hybrid-mode.test.ts +125 -0
  59. package/templates/chat/src/__tests__/server-config-security.test.ts +55 -0
  60. package/templates/chat/src/__tests__/server-config.test.ts +46 -44
  61. package/templates/chat/src/bun/index.ts +94 -44
  62. package/templates/chat/src/bun/three.d.ts +1 -0
  63. package/templates/chat/src/gateway/http-routes.ts +1 -1
  64. package/templates/chat/src/gateway/ws-handler.ts +84 -56
  65. package/templates/chat/src/mainview/App.tsx +6 -0
  66. package/templates/chat/src/mainview/__tests__/i18n/i18n.test.ts +1 -0
  67. package/templates/chat/src/mainview/__tests__/theme-variables.test.ts +36 -0
  68. package/templates/chat/src/mainview/components/common/LanguageSwitcher.tsx +1 -0
  69. package/templates/chat/src/mainview/components/common/ThemeToggle.tsx +1 -0
  70. package/templates/chat/src/mainview/hooks/use-input-history.ts +70 -61
  71. package/templates/chat/src/mainview/lib/api-client.ts +180 -156
  72. package/templates/chat/src/mainview/lib/rpc-cache.ts +84 -0
  73. package/templates/chat/src/mainview/main.tsx +10 -6
  74. package/templates/chat/src/server-config.ts +33 -31
  75. package/templates/chat/src/server.ts +42 -60
  76. package/templates/chat/src/shared/handlers/chat.ts +196 -162
  77. package/templates/chat/src/shared/handlers/debug.ts +12 -0
  78. package/templates/chat/src/shared/handlers/index.ts +1 -0
  79. package/templates/chat/src/shared/http-routes.ts +250 -0
  80. package/templates/chat/src/shared/lib/__tests__/logger.test.ts +92 -0
  81. package/templates/chat/src/shared/lib/logger.ts +108 -95
  82. package/templates/chat/src/shared/lib/web-server.ts +128 -0
  83. package/templates/chat/src/shared/modules/debug.ts +8 -0
  84. package/templates/chat/src/shared/rpc-schema.ts +3 -2
  85. package/templates/chat/test-upload.txt +0 -0
  86. package/templates/chat/tsconfig.ipc.json +14 -0
  87. package/templates/chat/tsconfig.json +12 -2
  88. package/templates/general/eslint.config.mjs +15 -2
  89. package/templates/general/package.json +13 -2
  90. package/templates/general/src/__tests__/hybrid-mode.test.ts +125 -0
  91. package/templates/general/src/__tests__/server-config-security.test.ts +55 -0
  92. package/templates/general/src/__tests__/server-config.test.ts +46 -44
  93. package/templates/general/src/bun/index.ts +94 -44
  94. package/templates/general/src/bun/three.d.ts +1 -0
  95. package/templates/general/src/gateway/http-routes.ts +1 -1
  96. package/templates/general/src/gateway/ws-handler.ts +84 -56
  97. package/templates/general/src/mainview/__tests__/i18n/i18n.test.ts +1 -0
  98. package/templates/general/src/mainview/__tests__/theme-variables.test.ts +36 -0
  99. package/templates/general/src/mainview/components/common/LanguageSwitcher.tsx +1 -0
  100. package/templates/general/src/mainview/components/common/ThemeToggle.tsx +1 -0
  101. package/templates/general/src/mainview/components/feed/FeedPanel.tsx +241 -219
  102. package/templates/general/src/mainview/components/file-preview/VirtualizedCodeView.tsx +101 -81
  103. package/templates/general/src/mainview/components/layout/AppLayout.tsx +6 -0
  104. package/templates/general/src/mainview/components/search/SearchPanel.tsx +429 -378
  105. package/templates/general/src/mainview/hooks/use-input-history.ts +70 -61
  106. package/templates/general/src/mainview/lib/api-client.ts +180 -156
  107. package/templates/general/src/mainview/lib/rpc-cache.ts +84 -0
  108. package/templates/general/src/mainview/main.tsx +10 -6
  109. package/templates/general/src/mainview/stores/use-feed-store.ts +107 -107
  110. package/templates/general/src/mainview/utils/drop-handler.ts +114 -115
  111. package/templates/general/src/server-config.ts +33 -31
  112. package/templates/general/src/server.ts +42 -60
  113. package/templates/general/src/shared/handlers/__tests__/chat.test.ts +165 -160
  114. package/templates/general/src/shared/handlers/chat.ts +189 -155
  115. package/templates/general/src/shared/handlers/debug.ts +12 -0
  116. package/templates/general/src/shared/handlers/feed.ts +38 -40
  117. package/templates/general/src/shared/handlers/git.ts +286 -243
  118. package/templates/general/src/shared/handlers/index.ts +1 -0
  119. package/templates/general/src/shared/http-routes.ts +250 -0
  120. package/templates/general/src/shared/lib/__tests__/logger.test.ts +92 -0
  121. package/templates/general/src/shared/lib/logger.ts +117 -95
  122. package/templates/general/src/shared/lib/web-server.ts +128 -0
  123. package/templates/general/src/shared/modules/debug.ts +8 -0
  124. package/templates/general/src/shared/rpc-schema.ts +12 -2
  125. package/templates/general/test-upload.txt +0 -0
  126. package/templates/general/tsconfig.ipc.json +14 -0
  127. package/templates/general/tsconfig.json +12 -2
  128. package/templates/shared/__tests__/cors-security.test.ts +165 -0
  129. package/templates/shared/__tests__/file-path-security.test.ts +260 -0
  130. package/templates/shared/__tests__/http-routes.test.ts +174 -0
  131. package/templates/shared/__tests__/logger.test.ts +186 -0
  132. package/templates/shared/components/ErrorBoundary.tsx +59 -0
  133. package/templates/shared/env.d.ts +11 -0
  134. package/templates/shared/http-routes.ts +250 -0
  135. package/templates/shared/logger.ts +129 -0
  136. package/templates/shared/test-upload.txt +0 -0
  137. package/templates/shared/vite-base.config.ts +92 -0
  138. package/templates/shared/vitest-base.config.ts +42 -0
  139. package/templates/agent/eslint-plugin-rpc/index.js +0 -50
  140. package/templates/agent/eslint-plugin-rpc/package.json +0 -6
  141. package/templates/agent/eslint-plugin-rpc/rules/module-file-naming.js +0 -99
  142. package/templates/agent/eslint-plugin-rpc/rules/no-bare-method.js +0 -78
  143. package/templates/agent/eslint-plugin-rpc/rules/no-direct-register.js +0 -65
  144. package/templates/agent/eslint-plugin-rpc/rules/no-hardcoded-strings.js +0 -69
  145. package/templates/agent/eslint-plugin-rpc/rules/require-api-client.js +0 -58
  146. package/templates/agent/eslint-plugin-rpc/rules/require-typed-register.js +0 -78
  147. package/templates/agent/eslint-plugin-rpc/rules/schema-merge-only.js +0 -55
  148. package/templates/chat/eslint-plugin-rpc/index.js +0 -50
  149. package/templates/chat/eslint-plugin-rpc/package.json +0 -6
  150. package/templates/chat/eslint-plugin-rpc/rules/module-file-naming.js +0 -99
  151. package/templates/chat/eslint-plugin-rpc/rules/no-bare-method.js +0 -78
  152. package/templates/chat/eslint-plugin-rpc/rules/no-direct-register.js +0 -65
  153. package/templates/chat/eslint-plugin-rpc/rules/no-hardcoded-strings.js +0 -69
  154. package/templates/chat/eslint-plugin-rpc/rules/require-api-client.js +0 -58
  155. package/templates/chat/eslint-plugin-rpc/rules/require-typed-register.js +0 -78
  156. package/templates/chat/eslint-plugin-rpc/rules/schema-merge-only.js +0 -55
  157. package/templates/general/eslint-plugin-rpc/index.js +0 -50
  158. package/templates/general/eslint-plugin-rpc/package.json +0 -6
  159. package/templates/general/eslint-plugin-rpc/rules/module-file-naming.js +0 -99
  160. package/templates/general/eslint-plugin-rpc/rules/no-bare-method.js +0 -78
  161. package/templates/general/eslint-plugin-rpc/rules/no-direct-register.js +0 -65
  162. package/templates/general/eslint-plugin-rpc/rules/no-hardcoded-strings.js +0 -69
  163. package/templates/general/eslint-plugin-rpc/rules/require-api-client.js +0 -58
  164. package/templates/general/eslint-plugin-rpc/rules/require-typed-register.js +0 -78
  165. package/templates/general/eslint-plugin-rpc/rules/schema-merge-only.js +0 -55
@@ -3,40 +3,42 @@
3
3
  * Values are read from environment variables with sensible defaults.
4
4
  */
5
5
 
6
+ import { randomUUID } from "crypto";
7
+
8
+ if (process.env.NODE_ENV === "production" && !process.env.AUTH_TOKEN) {
9
+ throw new Error(
10
+ "[FATAL] AUTH_TOKEN environment variable must be set in production mode. " +
11
+ "Example: AUTH_TOKEN=$(openssl rand -hex 32) bun src/server.ts"
12
+ );
13
+ }
14
+
6
15
  export function parseEnvInt(
7
- key: string,
8
- value: string | undefined,
9
- defaultValue: number,
10
- min: number,
11
- max: number,
16
+ key: string,
17
+ value: string | undefined,
18
+ defaultValue: number,
19
+ min: number,
20
+ max: number
12
21
  ): number {
13
- if (value === undefined || value === "") return defaultValue;
14
- const parsed = parseInt(value, 10);
15
- if (isNaN(parsed) || parsed < min || parsed > max) {
16
- console.warn(
17
- `[config] Invalid ${key}: "${value}", using default: ${defaultValue}`,
18
- );
19
- return defaultValue;
20
- }
21
- return parsed;
22
+ if (value === undefined || value === "") return defaultValue;
23
+ const parsed = parseInt(value, 10);
24
+ if (isNaN(parsed) || parsed < min || parsed > max) {
25
+ process.stderr.write(`[config] Invalid ${key}: "${value}", using default: ${defaultValue}\n`);
26
+ return defaultValue;
27
+ }
28
+ return parsed;
22
29
  }
23
30
 
24
31
  export const config = {
25
- port: parseEnvInt("PORT", process.env.PORT, 3100, 1024, 65535),
26
- authToken: process.env.AUTH_TOKEN || "pi-agent-template-token",
27
- maxUploadSize: parseEnvInt(
28
- "MAX_UPLOAD_SIZE",
29
- process.env.MAX_UPLOAD_SIZE,
30
- 50 * 1024 * 1024,
31
- 0,
32
- 1024 * 1024 * 1024,
33
- ),
34
- logDir: process.env.LOG_DIR || "logs",
35
- corsOrigin: process.env.CORS_ORIGIN || "http://localhost:5173",
32
+ port: parseEnvInt("PORT", process.env.PORT, 3100, 1024, 65535),
33
+ authToken: process.env.AUTH_TOKEN || `dev-${randomUUID()}`,
34
+ maxUploadSize: parseEnvInt(
35
+ "MAX_UPLOAD_SIZE",
36
+ process.env.MAX_UPLOAD_SIZE,
37
+ 50 * 1024 * 1024,
38
+ 0,
39
+ 1024 * 1024 * 1024
40
+ ),
41
+ logDir: process.env.LOG_DIR || "logs",
42
+ enableWebService: process.env.ENABLE_WEB_SERVICE === "true",
43
+ corsOrigin: process.env.CORS_ORIGIN || "http://localhost:5173",
36
44
  } as const;
37
-
38
- if (process.env.NODE_ENV === "production" && !process.env.AUTH_TOKEN) {
39
- console.warn(
40
- "[security] WARNING: Using default AUTH_TOKEN in production. Set AUTH_TOKEN environment variable.",
41
- );
42
- }
@@ -1,15 +1,7 @@
1
- /**
2
- * Web server entry point — HTTP file endpoints + WebSocket RPC gateway.
3
- * Port auto-negotiation: tries config.port first, increments on EADDRINUSE.
4
- * Writes actual port to .server-port for dev orchestration.
5
- */
6
-
7
- import { createServer } from "http";
8
1
  import { writeFileSync, unlinkSync, existsSync } from "fs";
9
2
  import { join, resolve, basename } from "path";
10
3
  import { config } from "./server-config";
11
- import { createHttpHandler } from "./gateway/http-routes";
12
- import { createWsHandler } from "./gateway/ws-handler";
4
+ import { createWebServer, getLocalIP } from "./shared/lib/web-server";
13
5
  import { createLogger, configureLogDir } from "./shared/lib/logger";
14
6
  import { registerPort, unregisterPort, formatRegistryForOutput } from "./shared/lib/port-registry";
15
7
  import { discoverMethodNames } from "./shared/register-all-handlers";
@@ -22,68 +14,58 @@ const PROJECT_ROOT = resolve(import.meta.dir, "..");
22
14
  const PROJECT_NAME = basename(PROJECT_ROOT);
23
15
 
24
16
  function cleanupPortFile() {
25
- try { if (existsSync(PORT_FILE)) unlinkSync(PORT_FILE); } catch {}
26
- unregisterPort(PROJECT_ROOT);
17
+ try {
18
+ if (existsSync(PORT_FILE)) unlinkSync(PORT_FILE);
19
+ } catch {}
20
+ unregisterPort(PROJECT_ROOT);
27
21
  }
28
22
 
29
23
  function writePortFile(port: number) {
30
- writeFileSync(PORT_FILE, String(port), "utf-8");
24
+ writeFileSync(PORT_FILE, String(port), "utf-8");
31
25
  }
32
26
 
33
27
  process.on("exit", cleanupPortFile);
34
- process.on("SIGINT", () => { cleanupPortFile(); process.exit(0); });
35
- process.on("SIGTERM", () => { cleanupPortFile(); process.exit(0); });
36
-
37
- const httpServer = createServer();
38
- const wss = createWsHandler(httpServer, { config });
28
+ process.on("SIGINT", () => {
29
+ cleanupPortFile();
30
+ process.exit(0);
31
+ });
32
+ process.on("SIGTERM", () => {
33
+ cleanupPortFile();
34
+ process.exit(0);
35
+ });
39
36
 
40
- httpServer.on("request", createHttpHandler({
41
- config,
42
- getWebSocketClientCount: () => wss.clients.size,
43
- }));
37
+ async function start() {
38
+ const { port, close } = await createWebServer({
39
+ port: config.port,
40
+ authToken: config.authToken,
41
+ maxUploadSize: config.maxUploadSize,
42
+ corsOrigin: config.corsOrigin,
43
+ });
44
44
 
45
- function checkPort(port: number): Promise<number> {
46
- return new Promise((resolve, reject) => {
47
- const testServer = createServer();
48
- testServer.once("error", (err: NodeJS.ErrnoException) => {
49
- testServer.close();
50
- reject(err);
51
- });
52
- testServer.once("listening", () => {
53
- testServer.close();
54
- resolve(port);
55
- });
56
- testServer.listen(port);
57
- });
58
- }
45
+ process.on("SIGINT", () => {
46
+ close();
47
+ cleanupPortFile();
48
+ process.exit(0);
49
+ });
50
+ process.on("SIGTERM", () => {
51
+ close();
52
+ cleanupPortFile();
53
+ process.exit(0);
54
+ });
59
55
 
60
- async function findAvailablePort(startPort: number, maxRetries: number = 10): Promise<number> {
61
- for (let port = startPort; port < startPort + maxRetries; port++) {
62
- try {
63
- await checkPort(port);
64
- return port;
65
- } catch {
66
- log.info(`Port ${port} in use, trying ${port + 1}...`);
67
- }
68
- }
69
- throw new Error(`No available port found after ${maxRetries} retries`);
70
- }
56
+ writePortFile(port);
57
+ registerPort(PROJECT_ROOT, port, PROJECT_NAME);
71
58
 
72
- async function start() {
73
- const port = await findAvailablePort(config.port);
74
- httpServer.listen(port, () => {
75
- writePortFile(port);
76
- registerPort(PROJECT_ROOT, port, PROJECT_NAME);
77
- log.info(`HTTP + WebSocket server running on http://localhost:${port}`);
78
- log.info(`WebSocket: ws://localhost:${port}/ws (auth required)`);
79
- log.info(`Available RPC methods: ${discoverMethodNames().join(", ")}`);
80
- log.info("File endpoints: GET /file/{path}, GET /info/{path}");
81
- // eslint-disable-next-line no-console
82
- console.log("\n" + formatRegistryForOutput() + "\n");
83
- });
59
+ const localIp = getLocalIP();
60
+ log.info(`HTTP + WebSocket server running on http://localhost:${port}`);
61
+ log.info(`Local network access: http://${localIp}:${port}`);
62
+ log.info(`WebSocket: ws://localhost:${port}/ws (auth required)`);
63
+ log.info(`Available RPC methods: ${discoverMethodNames().join(", ")}`);
64
+ log.info("File endpoints: GET /file/{path}, GET /info/{path}");
65
+ log.info(formatRegistryForOutput());
84
66
  }
85
67
 
86
68
  start().catch((err) => {
87
- log.error("Server failed to start", { error: err.message });
88
- process.exit(1);
69
+ log.error("Server failed to start", { error: err.message });
70
+ process.exit(1);
89
71
  });
@@ -9,178 +9,212 @@ import { createLogger } from "../lib/logger";
9
9
 
10
10
  const log = createLogger("chat");
11
11
 
12
- function getStoragePath(): string {
13
- const dir = join(homedir(), ".pi-agent");
14
- return join(dir, "chat-history.json");
12
+ type Platform = "desktop" | "web";
13
+
14
+ export function getStoragePathFor(platform: Platform): string {
15
+ const dir = join(homedir(), ".pi-agent");
16
+ if (platform === "desktop") {
17
+ return join(dir, "chat-history-desktop.json");
18
+ }
19
+ const sessionId = Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 8);
20
+ return join(dir, `chat-history-web-${sessionId}.json`);
15
21
  }
16
22
 
17
23
  type ChatMessage = { id: string; role: "user" | "assistant"; content: string; timestamp: number };
18
24
 
19
- async function loadMessages(): Promise<ChatMessage[]> {
20
- const filePath = getStoragePath();
21
- try {
22
- if (!existsSync(filePath)) {
23
- log.info(`No history file at ${filePath}`);
24
- return [];
25
- }
26
- const raw = await readFile(filePath, "utf-8");
27
- const msgs = JSON.parse(raw) as ChatMessage[];
28
- log.info(`Loaded ${msgs.length} messages from ${filePath}`);
29
- return msgs;
30
- } catch (err) {
31
- log.error("Failed to load history", { error: err });
32
- return [];
33
- }
34
- }
35
-
36
- async function saveMessages(messages: ChatMessage[]): Promise<void> {
37
- const filePath = getStoragePath();
38
- const dir = dirname(filePath);
39
- try {
40
- if (!existsSync(dir)) {
41
- await mkdir(dir, { recursive: true });
42
- }
43
- await writeFile(filePath, JSON.stringify(messages, null, 2), "utf-8");
44
- log.info(`Saved ${messages.length} messages to ${filePath}`);
45
- } catch (err) {
46
- log.error("Failed to save history", { error: err });
47
- }
25
+ function createMessageStore(filePath: string) {
26
+ async function load(): Promise<ChatMessage[]> {
27
+ try {
28
+ if (!existsSync(filePath)) {
29
+ log.info(`No history file at ${filePath}`);
30
+ return [];
31
+ }
32
+ const raw = await readFile(filePath, "utf-8");
33
+ const msgs = JSON.parse(raw) as ChatMessage[];
34
+ log.info(`Loaded ${msgs.length} messages from ${filePath}`);
35
+ return msgs;
36
+ } catch (err) {
37
+ log.error("Failed to load history", { error: err });
38
+ return [];
39
+ }
40
+ }
41
+
42
+ async function save(messages: ChatMessage[]): Promise<void> {
43
+ const dir = dirname(filePath);
44
+ try {
45
+ if (!existsSync(dir)) {
46
+ await mkdir(dir, { recursive: true });
47
+ }
48
+ await writeFile(filePath, JSON.stringify(messages, null, 2), "utf-8");
49
+ log.info(`Saved ${messages.length} messages to ${filePath}`);
50
+ } catch (err) {
51
+ log.error("Failed to save history", { error: err });
52
+ }
53
+ }
54
+
55
+ return { load, save };
48
56
  }
49
57
 
50
58
  type RegisterFn = <K extends keyof RPCMethods & string>(
51
- method: K,
52
- handler: (params: MethodParams<RPCMethods, K>) => Promise<MethodResult<RPCMethods, K>>,
59
+ method: K,
60
+ handler: (params: MethodParams<RPCMethods, K>) => Promise<MethodResult<RPCMethods, K>>
53
61
  ) => void;
54
62
 
55
63
  export function generateReply(input: string): string {
56
- const lower = input.toLowerCase().trim();
57
-
58
- if (/^(hi|hello|hey|howdy|hola|yo|sup)\b/i.test(lower)) {
59
- const greetings = [
60
- "Hey there! How can I help you today?",
61
- "Hello! Great to see you. What would you like to know?",
62
- "Hi! I'm your desktop assistant. Ask me anything!",
63
- ];
64
- return greetings[Math.floor(Math.random() * greetings.length)];
65
- }
66
-
67
- if (/what('?s| is) the (time|date|day)|current (time|date)|what time|today'?s date/i.test(lower)) {
68
- const now = new Date();
69
- const date = now.toLocaleDateString("en-US", { weekday: "long", year: "numeric", month: "long", day: "numeric" });
70
- const time = now.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" });
71
- return `It's currently **${time}** on **${date}**.`;
72
- }
73
-
74
- const mathMatch = lower.match(
75
- /(?:what(?:'s| is)\s+)?(\d+(?:\.\d+)?)\s*([+\-*/x×÷^])\s*(\d+(?:\.\d+)?)/,
76
- );
77
- if (mathMatch) {
78
- const a = parseFloat(mathMatch[1]);
79
- const op = mathMatch[2];
80
- const b = parseFloat(mathMatch[3]);
81
- let result: number;
82
- switch (op) {
83
- case "+": result = a + b; break;
84
- case "-": result = a - b; break;
85
- case "*": case "x": case "×": result = a * b; break;
86
- case "/": case "÷": result = b !== 0 ? a / b : NaN; break;
87
- case "^": result = Math.pow(a, b); break;
88
- default: result = NaN;
89
- }
90
- if (isNaN(result)) {
91
- return "Hmm, I couldn't calculate that. Did you try dividing by zero?";
92
- }
93
- const niceResult = Number.isInteger(result) ? result.toString() : result.toFixed(4).replace(/0+$/, "").replace(/\.$/, "");
94
- return `That would be **${niceResult}**! Need help with anything else?`;
95
- }
96
-
97
- if (/file|files|browse|explorer|directory|folder|open file/i.test(lower)) {
98
- return (
99
- "I can help you explore files! While I can't directly browse files in this demo, " +
100
- "here's what you can do:\n\n" +
101
- "- Use the **Explorer** panel to browse your project files\n" +
102
- "- Click any file to preview its contents\n" +
103
- "- Use the search feature to find specific files\n\n" +
104
- "Try asking about **time** or **math** for a live demo!"
105
- );
106
- }
107
-
108
- if (/git|commit|branch|status|diff|push|pull/i.test(lower)) {
109
- return (
110
- "Git is a powerful version control system! Here's what I know:\n\n" +
111
- "- **git status** - Check your current changes\n" +
112
- "- **git branch** - See or switch branches\n" +
113
- "- **git log** - View commit history\n" +
114
- "- **git diff** - See what changed\n\n" +
115
- "Check out the **Source Control** panel for a visual Git interface! " +
116
- "Or try asking me about **time** or **math**."
117
- );
118
- }
119
-
120
- if (/^(help|commands|what can you|what do you|capabilities|features)/i.test(lower)) {
121
- return (
122
- "Here's what I can help with:\n\n" +
123
- "- **Greetings** - Say hi and I'll say hi back!\n" +
124
- "- **Time & Date** - Ask \"what time is it?\" or \"what's today's date?\"\n" +
125
- "- **Math** - Give me an expression like \"12 * 8\" or \"what is 100 / 4\"\n" +
126
- "- **Files** - Ask about file browsing and the explorer\n" +
127
- "- **Git** - Ask about version control commands\n" +
128
- "- **Help** - Show this message anytime!\n\n" +
129
- "This is a demo assistant - try different things to see what sticks!"
130
- );
131
- }
132
-
133
- const defaults = [
134
- "That's an interesting question! I'm a demo assistant, so my knowledge is limited - but try asking about **time**, **math**, **files**, or **git**.",
135
- "I wish I could help with that! For now I can answer questions about time, math, files, and git. Type **help** to see what I can do.",
136
- "Hmm, I'm not sure about that one. But I *can* do math, tell you the time, and talk about files and git. Give it a shot!",
137
- ];
138
- return defaults[Math.floor(Math.random() * defaults.length)];
64
+ const lower = input.toLowerCase().trim();
65
+
66
+ if (/^(hi|hello|hey|howdy|hola|yo|sup)\b/i.test(lower)) {
67
+ const greetings = [
68
+ "Hey there! How can I help you today?",
69
+ "Hello! Great to see you. What would you like to know?",
70
+ "Hi! I'm your desktop assistant. Ask me anything!",
71
+ ];
72
+ return greetings[Math.floor(Math.random() * greetings.length)]!;
73
+ }
74
+
75
+ if (
76
+ /what('?s| is) the (time|date|day)|current (time|date)|what time|today'?s date/i.test(lower)
77
+ ) {
78
+ const now = new Date();
79
+ const date = now.toLocaleDateString("en-US", {
80
+ weekday: "long",
81
+ year: "numeric",
82
+ month: "long",
83
+ day: "numeric",
84
+ });
85
+ const time = now.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" });
86
+ return `It's currently **${time}** on **${date}**.`;
87
+ }
88
+
89
+ const mathMatch = lower.match(
90
+ /(?:what(?:'s| is)\s+)?(\d+(?:\.\d+)?)\s*([+\-*/x×÷^])\s*(\d+(?:\.\d+)?)/
91
+ );
92
+ if (mathMatch) {
93
+ const a = parseFloat(mathMatch[1]!);
94
+ const op = mathMatch[2]!;
95
+ const b = parseFloat(mathMatch[3]!);
96
+ let result: number;
97
+ switch (op) {
98
+ case "+":
99
+ result = a + b;
100
+ break;
101
+ case "-":
102
+ result = a - b;
103
+ break;
104
+ case "*":
105
+ case "x":
106
+ case "×":
107
+ result = a * b;
108
+ break;
109
+ case "/":
110
+ case "÷":
111
+ result = b !== 0 ? a / b : NaN;
112
+ break;
113
+ case "^":
114
+ result = Math.pow(a, b);
115
+ break;
116
+ default:
117
+ result = NaN;
118
+ }
119
+ if (isNaN(result)) {
120
+ return "Hmm, I couldn't calculate that. Did you try dividing by zero?";
121
+ }
122
+ const niceResult = Number.isInteger(result)
123
+ ? result.toString()
124
+ : result.toFixed(4).replace(/0+$/, "").replace(/\.$/, "");
125
+ return `That would be **${niceResult}**! Need help with anything else?`;
126
+ }
127
+
128
+ if (/file|files|browse|explorer|directory|folder|open file/i.test(lower)) {
129
+ return (
130
+ "I can help you explore files! While I can't directly browse files in this demo, " +
131
+ "here's what you can do:\n\n" +
132
+ "- Use the **Explorer** panel to browse your project files\n" +
133
+ "- Click any file to preview its contents\n" +
134
+ "- Use the search feature to find specific files\n\n" +
135
+ "Try asking about **time** or **math** for a live demo!"
136
+ );
137
+ }
138
+
139
+ if (/git|commit|branch|status|diff|push|pull/i.test(lower)) {
140
+ return (
141
+ "Git is a powerful version control system! Here's what I know:\n\n" +
142
+ "- **git status** - Check your current changes\n" +
143
+ "- **git branch** - See or switch branches\n" +
144
+ "- **git log** - View commit history\n" +
145
+ "- **git diff** - See what changed\n\n" +
146
+ "Check out the **Source Control** panel for a visual Git interface! " +
147
+ "Or try asking me about **time** or **math**."
148
+ );
149
+ }
150
+
151
+ if (/^(help|commands|what can you|what do you|capabilities|features)/i.test(lower)) {
152
+ return (
153
+ "Here's what I can help with:\n\n" +
154
+ "- **Greetings** - Say hi and I'll say hi back!\n" +
155
+ '- **Time & Date** - Ask "what time is it?" or "what\'s today\'s date?"\n' +
156
+ '- **Math** - Give me an expression like "12 * 8" or "what is 100 / 4"\n' +
157
+ "- **Files** - Ask about file browsing and the explorer\n" +
158
+ "- **Git** - Ask about version control commands\n" +
159
+ "- **Help** - Show this message anytime!\n\n" +
160
+ "This is a demo assistant - try different things to see what sticks!"
161
+ );
162
+ }
163
+
164
+ const defaults = [
165
+ "That's an interesting question! I'm a demo assistant, so my knowledge is limited - but try asking about **time**, **math**, **files**, or **git**.",
166
+ "I wish I could help with that! For now I can answer questions about time, math, files, and git. Type **help** to see what I can do.",
167
+ "Hmm, I'm not sure about that one. But I *can* do math, tell you the time, and talk about files and git. Give it a shot!",
168
+ ];
169
+ return defaults[Math.floor(Math.random() * defaults.length)]!;
139
170
  }
140
171
 
141
- export function register(server: RPCServer, _options: HandlerOptions): void {
142
- const r: RegisterFn = (method, handler) => {
143
- server.register(method, handler as (params: unknown) => Promise<unknown>);
144
- };
145
-
146
- r("chat.list", async (params) => {
147
- const all = await loadMessages();
148
- const limit = params.limit ?? 50;
149
- const messages = all.slice(-limit);
150
- return {
151
- messages,
152
- hasMore: all.length > limit,
153
- };
154
- });
155
-
156
- r("chat.send", async (params) => {
157
- const all = await loadMessages();
158
-
159
- const userMsg: ChatMessage = {
160
- id: `msg-${Date.now()}-user`,
161
- role: "user",
162
- content: params.content,
163
- timestamp: Date.now(),
164
- };
165
- all.push(userMsg);
166
-
167
- server.emitEvent("chat.message", userMsg, { role: userMsg.role });
168
-
169
- const thinkDelay = 200 + Math.floor(Math.random() * 300);
170
- await new Promise((r) => setTimeout(r, thinkDelay));
171
-
172
- const reply: ChatMessage = {
173
- id: `msg-${Date.now()}-assistant`,
174
- role: "assistant",
175
- content: generateReply(params.content),
176
- timestamp: Date.now(),
177
- };
178
- all.push(reply);
179
-
180
- server.emitEvent("chat.message", reply, { role: reply.role });
181
-
182
- await saveMessages(all);
183
-
184
- return { ok: true };
185
- });
172
+ export function register(server: RPCServer, options: HandlerOptions): void {
173
+ const storagePath = getStoragePathFor(options.platform);
174
+ const store = createMessageStore(storagePath);
175
+
176
+ const r: RegisterFn = (method, handler) => {
177
+ server.register(method, handler as (params: unknown) => Promise<unknown>);
178
+ };
179
+
180
+ r("chat.list", async (params) => {
181
+ const all = await store.load();
182
+ const limit = params.limit ?? 50;
183
+ const messages = all.slice(-limit);
184
+ return {
185
+ messages,
186
+ hasMore: all.length > limit,
187
+ };
188
+ });
189
+
190
+ r("chat.send", async (params) => {
191
+ const all = await store.load();
192
+
193
+ const userMsg: ChatMessage = {
194
+ id: `msg-${Date.now()}-user`,
195
+ role: "user",
196
+ content: params.content,
197
+ timestamp: Date.now(),
198
+ };
199
+ all.push(userMsg);
200
+
201
+ server.emitEvent("chat.message", userMsg, { role: userMsg.role });
202
+
203
+ const thinkDelay = 200 + Math.floor(Math.random() * 300);
204
+ await new Promise((r) => setTimeout(r, thinkDelay));
205
+
206
+ const reply: ChatMessage = {
207
+ id: `msg-${Date.now()}-assistant`,
208
+ role: "assistant",
209
+ content: generateReply(params.content),
210
+ timestamp: Date.now(),
211
+ };
212
+ all.push(reply);
213
+
214
+ server.emitEvent("chat.message", reply, { role: reply.role });
215
+
216
+ await store.save(all);
217
+
218
+ return { ok: true };
219
+ });
186
220
  }
@@ -0,0 +1,12 @@
1
+ import type { RPCServer } from "@dyyz1993/rpc-core";
2
+ import type { HandlerOptions } from "../rpc-schema";
3
+
4
+ export function register(server: RPCServer, _options: HandlerOptions): void {
5
+ server.register("debug.subscriptions", async () => {
6
+ return {
7
+ subscriptions: (
8
+ server as unknown as { getActiveSubscriptions(): unknown }
9
+ ).getActiveSubscriptions(),
10
+ };
11
+ });
12
+ }
@@ -1,2 +1,3 @@
1
1
  export { register as system } from "./system";
2
2
  export { register as chat } from "./chat";
3
+ export { register as debug } from "./debug";