@cortex-agent/server 2026.9.15 → 2026.9.25

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 (297) hide show
  1. package/README.md +3 -2
  2. package/defaults/config/hooks/08-agents-md-injector-post-tool.json +10 -0
  3. package/defaults/config/hooks/{10-cortex-md-injector-session-start.json → 10-agents-md-injector-session-start.json} +3 -3
  4. package/defaults/config/hooks/{CORTEX.md → AGENTS.md} +2 -2
  5. package/defaults/config/thread-templates/agents/creative.json +17 -0
  6. package/defaults/hooks/{CORTEX.md → AGENTS.md} +1 -1
  7. package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  8. package/defaults/hooks/cortex-hook-api.mjs +2 -2
  9. package/defaults/hooks/new-session-hook.mjs +2 -2
  10. package/defaults/hooks/rules-loader.mjs +2 -2
  11. package/defaults/hooks/status-md-guard.mjs +8 -8
  12. package/defaults/hooks/task-status-check.mjs +18 -76
  13. package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
  14. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
  15. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
  16. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
  17. package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
  18. package/defaults/prompts/systemPrompts/creative.md +13 -0
  19. package/defaults/prompts/systemPrompts/direct.md +1 -1
  20. package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
  21. package/defaults/rules/decision-records.md +1 -1
  22. package/defaults/rules/meta-conventions.md +4 -4
  23. package/defaults/rules/mission-md.md +1 -1
  24. package/dist/agent-adapter/claude/adapter.d.ts +12 -0
  25. package/dist/agent-adapter/claude/adapter.js +19 -1
  26. package/dist/agent-adapter/claude/hooks-builder.js +2 -2
  27. package/dist/agent-adapter/claude/spawn-args.d.ts +7 -0
  28. package/dist/agent-adapter/claude/spawn-args.js +14 -0
  29. package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
  30. package/dist/agent-adapter/claude/turn-machine.js +46 -5
  31. package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
  32. package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
  33. package/dist/agent-adapter/pi/child-runner.d.ts +4 -2
  34. package/dist/agent-adapter/pi/child-runner.js +5 -1
  35. package/dist/agent-adapter/pi/event-parser.d.ts +3 -2
  36. package/dist/agent-adapter/pi/event-parser.js +46 -2
  37. package/dist/agent-adapter/pi/extensions.d.ts +7 -1
  38. package/dist/agent-adapter/pi/extensions.js +10 -3
  39. package/dist/agent-adapter/pi/mcp-bridge.js +8 -8
  40. package/dist/agent-adapter/pi/pi-session.js +5 -0
  41. package/dist/agent-adapter/pi/runtime.js +3 -0
  42. package/dist/agent-adapter/pi/session-options.js +5 -1
  43. package/dist/agent-adapter/pi/subagent.d.ts +15 -3
  44. package/dist/agent-adapter/pi/subagent.js +18 -0
  45. package/dist/agent-adapter/pi/tool-shims.d.ts +6 -1
  46. package/dist/agent-adapter/pi/tool-shims.js +34 -1
  47. package/dist/agent-adapter/types.d.ts +6 -0
  48. package/dist/core/agents/subagent/types.d.ts +3 -0
  49. package/dist/core/config-generator.js +17 -2
  50. package/dist/core/debug-mode.d.ts +11 -10
  51. package/dist/core/debug-mode.js +12 -18
  52. package/dist/core/exec-async.d.ts +26 -0
  53. package/dist/core/exec-async.js +47 -0
  54. package/dist/core/locales/en.d.ts +14 -1
  55. package/dist/core/locales/slices/commands.d.ts +12 -1
  56. package/dist/core/locales/slices/commands.js +24 -2
  57. package/dist/core/locales/slices/startup.d.ts +2 -0
  58. package/dist/core/locales/slices/startup.js +4 -0
  59. package/dist/core/mcp-tool-gate.js +1 -0
  60. package/dist/core/media-types.d.ts +10 -0
  61. package/dist/core/media-types.js +34 -0
  62. package/dist/core/platform-settings-spec.js +1 -1
  63. package/dist/core/rebuild-progress.d.ts +58 -0
  64. package/dist/core/rebuild-progress.js +103 -0
  65. package/dist/core/resilient-watch.js +5 -3
  66. package/dist/core/run-registry.d.ts +7 -0
  67. package/dist/core/run-registry.js +6 -0
  68. package/dist/core/settings-spec.d.ts +21 -0
  69. package/dist/core/settings-spec.js +28 -1
  70. package/dist/core/types/agent-types.d.ts +3 -1
  71. package/dist/core/types/thread-types.d.ts +23 -4
  72. package/dist/core/utils.d.ts +1 -1
  73. package/dist/core/utils.js +1 -1
  74. package/dist/domain/agents/agent-state.d.ts +7 -0
  75. package/dist/domain/agents/agent-state.js +9 -1
  76. package/dist/domain/agents/agent-switch.d.ts +38 -0
  77. package/dist/domain/agents/agent-switch.js +106 -0
  78. package/dist/domain/agents/config.d.ts +20 -2
  79. package/dist/domain/agents/config.js +58 -4
  80. package/dist/domain/agents/index.d.ts +1 -0
  81. package/dist/domain/agents/index.js +1 -0
  82. package/dist/domain/agents/profile-manager.d.ts +6 -0
  83. package/dist/domain/agents/profile-manager.js +14 -1
  84. package/dist/domain/executions/registry.d.ts +3 -2
  85. package/dist/domain/executions/registry.js +84 -10
  86. package/dist/domain/mcp/bundled-server.js +4 -3
  87. package/dist/domain/mcp/feishu/file.js +37 -18
  88. package/dist/domain/mcp/feishu/types.d.ts +3 -0
  89. package/dist/domain/mcp/feishu-server.js +1 -1
  90. package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
  91. package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
  92. package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
  93. package/dist/domain/mcp/tools/remote-file.js +44 -0
  94. package/dist/domain/mcp/tools/slack.d.ts +2 -0
  95. package/dist/domain/mcp/tools/slack.js +22 -7
  96. package/dist/domain/mcp/tools/task-ops.js +5 -13
  97. package/dist/domain/mcp/tools/ui-file.js +23 -10
  98. package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
  99. package/dist/domain/mcp/tools/waitpoint.js +122 -0
  100. package/dist/domain/memory/agents-md-injector.d.ts +24 -0
  101. package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
  102. package/dist/domain/plugins/runtime.js +1 -1
  103. package/dist/domain/plugins/skill-projection.d.ts +8 -2
  104. package/dist/domain/plugins/skill-projection.js +76 -19
  105. package/dist/domain/projects/project-store.d.ts +1 -1
  106. package/dist/domain/projects/project-store.js +3 -3
  107. package/dist/domain/remote/client-bootstrap.js +1 -1
  108. package/dist/domain/remote/client-hot-reload.d.ts +1 -1
  109. package/dist/domain/remote/client-hot-reload.js +30 -24
  110. package/dist/domain/remote/client-manager.js +39 -119
  111. package/dist/domain/remote/cortex-client-config.d.ts +1 -1
  112. package/dist/domain/remote/cortex-client-config.js +1 -1
  113. package/dist/domain/remote/device-file.d.ts +51 -0
  114. package/dist/domain/remote/device-file.js +193 -0
  115. package/dist/domain/remote/device-port.js +3 -0
  116. package/dist/domain/remote/reverse-stream.d.ts +18 -7
  117. package/dist/domain/remote/reverse-stream.js +19 -6
  118. package/dist/domain/runs/engine-spec.js +4 -0
  119. package/dist/domain/runs/request.d.ts +6 -0
  120. package/dist/domain/runs/run.js +1 -0
  121. package/dist/domain/runs/spec-loader.d.ts +4 -3
  122. package/dist/domain/runs/spec-loader.js +4 -3
  123. package/dist/domain/scheduling/jobs/sync-public.js +6 -6
  124. package/dist/domain/scheduling/scheduler.js +14 -12
  125. package/dist/domain/sessions/session-lifecycle.d.ts +5 -0
  126. package/dist/domain/sessions/session-lifecycle.js +13 -1
  127. package/dist/domain/system/rebuild-hold.d.ts +44 -0
  128. package/dist/domain/system/rebuild-hold.js +91 -0
  129. package/dist/domain/system/server-update-check.d.ts +2 -1
  130. package/dist/domain/system/server-update-check.js +15 -13
  131. package/dist/domain/tasks/archiver.js +21 -13
  132. package/dist/domain/tasks/claim-recovery.js +2 -2
  133. package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
  134. package/dist/domain/tasks/dispatch-utils.js +46 -1
  135. package/dist/domain/tasks/dispatcher.js +4 -5
  136. package/dist/domain/tasks/mutator.d.ts +2 -2
  137. package/dist/domain/tasks/mutator.js +62 -61
  138. package/dist/domain/tasks/system/task-cli.js +2 -2
  139. package/dist/domain/tasks/system/task-completion.d.ts +7 -2
  140. package/dist/domain/tasks/system/task-completion.js +69 -6
  141. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -1
  142. package/dist/domain/tasks/system/task-lifecycle-edit.js +21 -2
  143. package/dist/domain/tasks/system/task-lock.d.ts +23 -0
  144. package/dist/domain/tasks/system/task-lock.js +29 -1
  145. package/dist/domain/tasks/system/task-mutations.d.ts +14 -1
  146. package/dist/domain/tasks/system/task-mutations.js +25 -2
  147. package/dist/domain/tasks/system/task-state.d.ts +12 -1
  148. package/dist/domain/tasks/system/task-state.js +20 -3
  149. package/dist/domain/threads/prompt-builder.d.ts +9 -6
  150. package/dist/domain/threads/prompt-builder.js +28 -10
  151. package/dist/domain/threads/runner.js +10 -4
  152. package/dist/domain/threads/state-machine.js +15 -11
  153. package/dist/domain/threads/template-loader.js +6 -4
  154. package/dist/domain/threads/template-validate.d.ts +43 -6
  155. package/dist/domain/threads/template-validate.js +12 -0
  156. package/dist/domain/ui-service/app-router.d.ts +34 -3
  157. package/dist/domain/ui-service/app-router.js +9 -14
  158. package/dist/domain/ui-service/input-schemas.d.ts +28 -5
  159. package/dist/domain/ui-service/input-schemas.js +24 -9
  160. package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
  161. package/dist/domain/ui-service/mutate/sessions.d.ts +6 -1
  162. package/dist/domain/ui-service/mutate/sessions.js +54 -0
  163. package/dist/domain/ui-service/mutate/tasks.js +4 -3
  164. package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
  165. package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
  166. package/dist/domain/ui-service/platform-settings.js +1 -1
  167. package/dist/domain/ui-service/plugins-shared.js +1 -1
  168. package/dist/domain/ui-service/query/config.js +20 -2
  169. package/dist/domain/ui-service/query/executions.js +0 -2
  170. package/dist/domain/ui-service/query/machine-detail.js +3 -8
  171. package/dist/domain/ui-service/query/memory.js +29 -35
  172. package/dist/domain/ui-service/query/sessions.js +96 -12
  173. package/dist/domain/ui-service/query/system.js +19 -0
  174. package/dist/domain/ui-service/query/threads.js +1 -54
  175. package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
  176. package/dist/domain/ui-service/query/waitpoints.js +117 -0
  177. package/dist/domain/ui-service/query-input-schemas.d.ts +4 -0
  178. package/dist/domain/ui-service/query-input-schemas.js +5 -0
  179. package/dist/domain/ui-service/trpc.js +1 -1
  180. package/dist/domain/ui-service/types.d.ts +229 -51
  181. package/dist/domain/ui-service/types.js +1 -1
  182. package/dist/domain/ui-service/ui-service.js +8 -31
  183. package/dist/domain/waitpoints/notices.d.ts +21 -0
  184. package/dist/domain/waitpoints/notices.js +115 -0
  185. package/dist/domain/waitpoints/service.d.ts +91 -0
  186. package/dist/domain/waitpoints/service.js +243 -0
  187. package/dist/entry/app.js +52 -11
  188. package/dist/entry/auth-login-cli.js +1 -1
  189. package/dist/entry/auth-login-terminal.js +1 -1
  190. package/dist/entry/daemon-notice.d.ts +10 -1
  191. package/dist/entry/daemon-notice.js +16 -1
  192. package/dist/entry/daemon.d.ts +43 -2
  193. package/dist/entry/daemon.js +163 -9
  194. package/dist/entry/init-auth.js +1 -1
  195. package/dist/entry/init.js +6 -6
  196. package/dist/entry/signal-cli.d.ts +30 -0
  197. package/dist/entry/signal-cli.js +207 -0
  198. package/dist/entry/start-ui-http.d.ts +1 -1
  199. package/dist/entry/start-ui-http.js +2 -2
  200. package/dist/events/event-types.d.ts +0 -7
  201. package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  202. package/dist/hooks/cortex-hook-api.mjs +2 -2
  203. package/dist/hooks/new-session-hook.mjs +2 -2
  204. package/dist/hooks/rules-loader.mjs +2 -2
  205. package/dist/hooks/status-md-guard.mjs +8 -8
  206. package/dist/hooks/task-status-check.mjs +18 -76
  207. package/dist/hooks/tasks-yaml-guard.mjs +2 -2
  208. package/dist/orchestration/agent-file-send.d.ts +9 -0
  209. package/dist/orchestration/agent-file-send.js +21 -2
  210. package/dist/orchestration/agent-runner.d.ts +3 -2
  211. package/dist/orchestration/agent-runner.js +33 -12
  212. package/dist/orchestration/attachments-store.d.ts +31 -0
  213. package/dist/orchestration/attachments-store.js +184 -0
  214. package/dist/orchestration/conversation-request.d.ts +37 -0
  215. package/dist/orchestration/conversation-request.js +91 -22
  216. package/dist/orchestration/interactions/plan-approvals.js +1 -1
  217. package/dist/orchestration/mid-turn-inject.d.ts +3 -0
  218. package/dist/orchestration/mid-turn-inject.js +9 -4
  219. package/dist/orchestration/outputs-store.d.ts +11 -0
  220. package/dist/orchestration/outputs-store.js +32 -6
  221. package/dist/orchestration/resume-dispatcher.js +4 -2
  222. package/dist/orchestration/routing/commands/mode.js +114 -63
  223. package/dist/orchestration/routing/file-handler.d.ts +23 -2
  224. package/dist/orchestration/routing/file-handler.js +22 -5
  225. package/dist/orchestration/routing/webhook.js +193 -39
  226. package/dist/orchestration/session-gateway.d.ts +1 -1
  227. package/dist/orchestration/session-gateway.js +1 -0
  228. package/dist/orchestration/thread-executor.d.ts +2 -0
  229. package/dist/orchestration/thread-executor.js +24 -1
  230. package/dist/orchestration/thread-input.d.ts +3 -2
  231. package/dist/orchestration/thread-input.js +8 -9
  232. package/dist/orchestration/turn/turn-prep.d.ts +15 -1
  233. package/dist/orchestration/turn/turn-prep.js +19 -8
  234. package/dist/orchestration/turn/turn.js +1 -0
  235. package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
  236. package/dist/orchestration/waitpoint-ingress.js +172 -0
  237. package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
  238. package/dist/orchestration/waitpoint-notifier.js +119 -0
  239. package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
  240. package/dist/orchestration/waitpoint-remote-drain.js +147 -0
  241. package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
  242. package/dist/orchestration/waitpoint-sweep.js +87 -0
  243. package/dist/platform/adapters/feishu-image.d.ts +19 -0
  244. package/dist/platform/adapters/feishu-image.js +71 -0
  245. package/dist/platform/adapters/feishu.d.ts +2 -0
  246. package/dist/platform/adapters/feishu.js +26 -16
  247. package/dist/platform/ui-http/listening-ports.d.ts +1 -1
  248. package/dist/platform/ui-http/listening-ports.js +1 -1
  249. package/dist/platform/ui-http/ui-session.js +1 -1
  250. package/dist/store/conversation-display-projection.d.ts +9 -1
  251. package/dist/store/conversation-display-projection.js +13 -6
  252. package/dist/store/conversation-history-reader.d.ts +19 -0
  253. package/dist/store/conversation-history-reader.js +163 -44
  254. package/dist/store/conversation-history-repo.d.ts +37 -10
  255. package/dist/store/conversation-history-repo.js +161 -139
  256. package/dist/store/conversation-ledger-repo.js +1 -1
  257. package/dist/store/execution-repo.d.ts +1 -19
  258. package/dist/store/execution-repo.js +1 -18
  259. package/dist/store/project-notes-repo.js +11 -2
  260. package/dist/store/prompt-migration-replacements.js +1 -1
  261. package/dist/store/session-registry-import.js +1 -1
  262. package/dist/store/session-registry-journal.d.ts +4 -0
  263. package/dist/store/session-registry-journal.js +5 -1
  264. package/dist/store/session-registry-repo.d.ts +2 -1
  265. package/dist/store/session-registry-repo.js +3 -1
  266. package/dist/store/task-repo.d.ts +6 -3
  267. package/dist/store/task-repo.js +26 -10
  268. package/dist/store/version-migrations.d.ts +13 -3
  269. package/dist/store/version-migrations.js +254 -24
  270. package/dist/store/waitpoint-repo.d.ts +108 -0
  271. package/dist/store/waitpoint-repo.js +94 -0
  272. package/package.json +3 -2
  273. package/web/dist/AGENTS.md +10 -0
  274. package/web/dist/assets/index-B1dBi8Za.css +1 -0
  275. package/web/dist/assets/{index-CEZ0DSei.js → index-BAeLybF0.js} +1 -1
  276. package/web/dist/assets/index-BcQI8Fh5.js +445 -0
  277. package/web/dist/index.html +12 -4
  278. package/web/dist/theme.css +211 -40
  279. package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
  280. package/dist/domain/executions/log-tailer.d.ts +0 -71
  281. package/dist/domain/executions/log-tailer.js +0 -194
  282. package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
  283. package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
  284. package/dist/domain/memory/cortex-md-scanner.js +0 -66
  285. package/dist/domain/remote/cortex-client.d.ts +0 -1
  286. package/dist/domain/remote/cortex-client.js +0 -662
  287. package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
  288. package/dist/domain/tasks/system/cortex-run.js +0 -360
  289. package/web/dist/assets/index-CRDJo39X.css +0 -1
  290. package/web/dist/assets/index-DjuPJVZE.js +0 -444
  291. /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
  292. /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
  293. /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
  294. /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
  295. /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
  296. /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
  297. /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
@@ -1,662 +0,0 @@
1
- import WebSocket from 'ws';
2
- import * as fs from 'fs';
3
- import * as path from 'path';
4
- import * as os from 'os';
5
- import { execFileSync, spawn } from 'child_process';
6
- import { scanCortexMDChain } from '../memory/cortex-md-scanner.js';
7
- import { resolveServerUrl, buildAuthHeaders } from './cortex-client-config.js';
8
- import { createLogger } from '../../core/log.js';
9
- const log = createLogger('cortex-client');
10
- // --- Config ---
11
- const SERVER_HOST = process.env.CORTEX_SERVER_HOST;
12
- const DEVICE_NAME = process.env.CORTEX_DEVICE_NAME || os.hostname();
13
- const PLATFORM = process.platform;
14
- const HEARTBEAT_INTERVAL_MS = 5000;
15
- const GIT_BASH_PATHS = [
16
- 'C:\\Program Files\\Git\\bin\\bash.exe',
17
- 'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
18
- ];
19
- if (!SERVER_HOST && !process.env.CORTEX_SERVER_URL) {
20
- log.error('Either CORTEX_SERVER_URL (full ws/wss URL) or CORTEX_SERVER_HOST is required');
21
- process.exit(1);
22
- }
23
- // --- Output accumulator (prevents WS message size explosion) ---
24
- class OutputAccumulator {
25
- head = '';
26
- headFull = false;
27
- tail = '';
28
- totalChars = 0;
29
- headSize;
30
- tailSize;
31
- constructor(maxBytes) {
32
- this.headSize = Math.floor(maxBytes * 0.6);
33
- this.tailSize = Math.floor(maxBytes * 0.4);
34
- }
35
- append(data) {
36
- this.totalChars += data.length;
37
- if (!this.headFull) {
38
- this.head += data;
39
- if (this.head.length > this.headSize) {
40
- const overflow = this.head.slice(this.headSize);
41
- this.head = this.head.slice(0, this.headSize);
42
- this.headFull = true;
43
- this.tail = overflow;
44
- }
45
- }
46
- else {
47
- this.tail += data;
48
- if (this.tail.length > this.tailSize * 2) {
49
- this.tail = this.tail.slice(-this.tailSize);
50
- }
51
- }
52
- }
53
- toString() {
54
- if (!this.headFull)
55
- return this.head;
56
- const finalTail = this.tail.slice(-this.tailSize);
57
- const omitted = this.totalChars - this.head.length - finalTail.length;
58
- return `${this.head}\n\n[... ${omitted} chars truncated ...]\n\n${finalTail}`;
59
- }
60
- }
61
- // --- Utility functions ---
62
- function detectEncoding(buffer) {
63
- if (buffer.length >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE)
64
- return 'utf16le';
65
- return 'utf8';
66
- }
67
- function detectLineEnding(content) {
68
- const crlfCount = (content.match(/\r\n/g) || []).length;
69
- const lfOnly = content.replace(/\r\n/g, '').match(/\n/g);
70
- const lfCount = lfOnly ? lfOnly.length : 0;
71
- return crlfCount > lfCount ? '\r\n' : '\n';
72
- }
73
- function countWords(text) {
74
- let count = 0;
75
- const english = text.match(/[a-zA-Z]+/g);
76
- if (english)
77
- count += english.length;
78
- const cjk = text.match(/[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/g);
79
- if (cjk)
80
- count += cjk.length;
81
- return count;
82
- }
83
- // --- Image detection ---
84
- const IMAGE_SIGNATURES = [
85
- { bytes: [0xFF, 0xD8, 0xFF], mimeType: 'image/jpeg' },
86
- { bytes: [0x89, 0x50, 0x4E, 0x47], mimeType: 'image/png' },
87
- { bytes: [0x47, 0x49, 0x46, 0x38], mimeType: 'image/gif' },
88
- { bytes: [0x52, 0x49, 0x46, 0x46], mimeType: 'image/webp' },
89
- { bytes: [0x42, 0x4D], mimeType: 'image/bmp' },
90
- ];
91
- function detectImageType(buffer) {
92
- for (const sig of IMAGE_SIGNATURES) {
93
- if (buffer.length < sig.bytes.length)
94
- continue;
95
- if (!sig.bytes.every((b, i) => buffer[i] === b))
96
- continue;
97
- // WebP: RIFF header needs additional check at offset 8-11
98
- if (sig.mimeType === 'image/webp') {
99
- if (buffer.length >= 12 && buffer.slice(8, 12).toString('ascii') === 'WEBP') {
100
- return 'image/webp';
101
- }
102
- continue;
103
- }
104
- return sig.mimeType;
105
- }
106
- return null;
107
- }
108
- function extractImageDimensions(buf, mime) {
109
- try {
110
- if (mime === 'image/png' && buf.length >= 24) {
111
- return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
112
- }
113
- if (mime === 'image/gif' && buf.length >= 10) {
114
- return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
115
- }
116
- if (mime === 'image/bmp' && buf.length >= 26) {
117
- return { width: buf.readInt32LE(18), height: Math.abs(buf.readInt32LE(22)) };
118
- }
119
- if (mime === 'image/webp' && buf.length >= 30) {
120
- if (buf.slice(12, 16).toString('ascii') === 'VP8 ' && buf.length >= 30) {
121
- return { width: buf.readUInt16LE(26) & 0x3FFF, height: buf.readUInt16LE(28) & 0x3FFF };
122
- }
123
- if (buf.slice(12, 17).toString('ascii') === 'VP8L' && buf.length >= 25) {
124
- const bits = buf.readUInt32LE(21);
125
- return { width: (bits & 0x3FFF) + 1, height: ((bits >> 14) & 0x3FFF) + 1 };
126
- }
127
- }
128
- if (mime === 'image/jpeg') {
129
- let offset = 2;
130
- while (offset < buf.length - 9) {
131
- if (buf[offset] !== 0xFF)
132
- break;
133
- const marker = buf[offset + 1];
134
- if (marker === 0xC0 || marker === 0xC2) {
135
- return { width: buf.readUInt16BE(offset + 7), height: buf.readUInt16BE(offset + 5) };
136
- }
137
- const segLen = buf.readUInt16BE(offset + 2);
138
- offset += 2 + segLen;
139
- }
140
- }
141
- }
142
- catch { }
143
- return null;
144
- }
145
- // --- Capabilities detection ---
146
- function detectCapabilities() {
147
- const caps = [];
148
- try {
149
- execFileSync('rg', ['--version'], { timeout: 5000, stdio: 'pipe' });
150
- caps.push('rg');
151
- }
152
- catch { }
153
- return caps;
154
- }
155
- // --- Shell execution ---
156
- function findGitBash() {
157
- for (const p of GIT_BASH_PATHS) {
158
- if (fs.existsSync(p))
159
- return p;
160
- }
161
- return null;
162
- }
163
- function spawnCommand(cmd, args, timeout, maxOutputBytes = 500_000) {
164
- return new Promise((resolve) => {
165
- const proc = spawn(cmd, args, {
166
- stdio: ['pipe', 'pipe', 'pipe'],
167
- env: { ...process.env },
168
- });
169
- const stdoutAcc = new OutputAccumulator(maxOutputBytes);
170
- const stderrAcc = new OutputAccumulator(50_000);
171
- proc.stdout.on('data', (d) => stdoutAcc.append(d.toString()));
172
- proc.stderr.on('data', (d) => stderrAcc.append(d.toString()));
173
- // SIGKILL fallback — ensures process is killed even if it ignores SIGTERM
174
- const timer = setTimeout(() => {
175
- try {
176
- proc.kill('SIGKILL');
177
- }
178
- catch { }
179
- }, timeout);
180
- proc.on('close', (code) => {
181
- clearTimeout(timer);
182
- resolve({ stdout: stdoutAcc.toString(), stderr: stderrAcc.toString(), exitCode: code ?? 1 });
183
- });
184
- proc.on('error', (err) => {
185
- clearTimeout(timer);
186
- resolve({ stdout: stdoutAcc.toString(), stderr: stderrAcc.toString() + '\n' + err.message, exitCode: 127 });
187
- });
188
- });
189
- }
190
- function execBash(command, timeout) {
191
- const shell = PLATFORM === 'win32' ? findGitBash() : '/bin/bash';
192
- if (!shell) {
193
- return Promise.resolve({ stdout: '', stderr: 'bash not found (git-bash not installed on Windows?)', exitCode: 127 });
194
- }
195
- return spawnCommand(shell, ['-l', '-c', command], timeout, 200_000);
196
- }
197
- function execBashBackground(command) {
198
- const shell = PLATFORM === 'win32' ? findGitBash() : '/bin/bash';
199
- if (!shell)
200
- return { pid: undefined };
201
- const proc = spawn(shell, ['-l', '-c', command], {
202
- stdio: 'ignore',
203
- detached: true,
204
- env: { ...process.env },
205
- });
206
- proc.unref();
207
- return { pid: proc.pid };
208
- }
209
- // --- Tool: Read ---
210
- const MAX_READ_WORDS = 25_000;
211
- const DEFAULT_READ_LINES = 2000;
212
- const MAX_READ_FILE_SIZE = 10 * 1024 * 1024; // 10MB
213
- /** Normalize file path for the current platform.
214
- * On Windows, converts git-bash paths (/c/Users/...) to native (C:\Users\...). */
215
- function normalizePath(p) {
216
- if (PLATFORM !== 'win32')
217
- return p;
218
- const m = p.match(/^\/([A-Za-z])\/(.*)/);
219
- if (m)
220
- return `${m[1].toUpperCase()}:\\${m[2].replace(/\//g, '\\')}`;
221
- return p;
222
- }
223
- function safeScanCortexMDs(filePath) {
224
- try {
225
- return scanCortexMDChain(filePath);
226
- }
227
- catch {
228
- return [];
229
- }
230
- }
231
- function handleRead(params) {
232
- try {
233
- const filePath = normalizePath(params.file_path);
234
- if (!path.isAbsolute(filePath)) {
235
- return { error: 'file_path must be absolute' };
236
- }
237
- if (!fs.existsSync(filePath)) {
238
- return { error: `File not found: ${filePath}` };
239
- }
240
- const stat = fs.statSync(filePath);
241
- if (!stat.isFile()) {
242
- return { error: `Not a file: ${filePath}` };
243
- }
244
- if (stat.size > MAX_READ_FILE_SIZE) {
245
- return { error: `File too large (${(stat.size / 1024 / 1024).toFixed(1)}MB, max 10MB). Use offset and limit for range reading.` };
246
- }
247
- const rawBuf = fs.readFileSync(filePath);
248
- const cortexMDs = safeScanCortexMDs(filePath);
249
- // Image detection — before text decode
250
- const imageType = detectImageType(rawBuf);
251
- if (imageType) {
252
- const dims = extractImageDimensions(rawBuf, imageType);
253
- return {
254
- image: {
255
- data: rawBuf.toString('base64'),
256
- mimeType: imageType,
257
- ...(dims ? { width: dims.width, height: dims.height } : {}),
258
- originalSize: rawBuf.length,
259
- },
260
- cortexMDs,
261
- };
262
- }
263
- // PDF detection — return as blob resource
264
- if (rawBuf.length >= 4 && rawBuf[0] === 0x25 && rawBuf[1] === 0x50 && rawBuf[2] === 0x44 && rawBuf[3] === 0x46) {
265
- return { pdf: { data: rawBuf.toString('base64'), originalSize: rawBuf.length }, cortexMDs };
266
- }
267
- // Text path (unchanged)
268
- const encoding = detectEncoding(rawBuf);
269
- const content = rawBuf.toString(encoding);
270
- const lines = content.split('\n');
271
- const offset = params.offset || 0;
272
- const limit = params.limit || DEFAULT_READ_LINES;
273
- const sliced = lines.slice(offset, offset + limit);
274
- const numbered = sliced.map((line, i) => `${offset + i + 1}\t${line}`).join('\n');
275
- // Word-count self-bounds — read never persists to file, returns error instead
276
- const wordCount = countWords(numbered);
277
- if (wordCount > MAX_READ_WORDS) {
278
- const suggestedLimit = Math.max(1, Math.floor(limit * (MAX_READ_WORDS / wordCount) * 0.9));
279
- return {
280
- error: `File content too large (~${wordCount} words, limit is ${MAX_READ_WORDS}). ` +
281
- `Use offset and limit for range reading. Total lines: ${lines.length}. ` +
282
- `Suggested: limit=${suggestedLimit} to stay within bounds.`,
283
- };
284
- }
285
- return { content: numbered, cortexMDs };
286
- }
287
- catch (err) {
288
- return { error: err.message };
289
- }
290
- }
291
- function handleWrite(params) {
292
- try {
293
- const filePath = normalizePath(params.file_path);
294
- if (!path.isAbsolute(filePath)) {
295
- return { error: 'file_path must be absolute' };
296
- }
297
- const dir = path.dirname(filePath);
298
- fs.mkdirSync(dir, { recursive: true });
299
- let content = params.content;
300
- // Preserve existing file's line ending style
301
- if (fs.existsSync(filePath)) {
302
- try {
303
- const existing = fs.readFileSync(filePath, 'utf8');
304
- const lineEnding = detectLineEnding(existing);
305
- if (lineEnding === '\r\n') {
306
- content = content.replace(/\r\n/g, '\n').replace(/\n/g, '\r\n');
307
- }
308
- }
309
- catch { }
310
- }
311
- fs.writeFileSync(filePath, content, 'utf8');
312
- return {
313
- success: true,
314
- cortexMDs: safeScanCortexMDs(filePath),
315
- };
316
- }
317
- catch (err) {
318
- return { error: err.message };
319
- }
320
- }
321
- // --- Tool: Edit ---
322
- function handleEdit(params) {
323
- try {
324
- const filePath = normalizePath(params.file_path);
325
- if (!path.isAbsolute(filePath)) {
326
- return { error: 'file_path must be absolute' };
327
- }
328
- const rawBuf = fs.readFileSync(filePath);
329
- const encoding = detectEncoding(rawBuf);
330
- const rawContent = rawBuf.toString(encoding);
331
- const originalLineEnding = detectLineEnding(rawContent);
332
- // Normalize to \n for matching
333
- const content = rawContent.replace(/\r\n/g, '\n');
334
- const oldStr = (params.old_string || '').replace(/\r\n/g, '\n');
335
- const newStr = (params.new_string || '').replace(/\r\n/g, '\n');
336
- if (!oldStr) {
337
- return { error: 'old_string is required' };
338
- }
339
- const buildResult = () => ({
340
- success: true,
341
- cortexMDs: safeScanCortexMDs(filePath),
342
- });
343
- if (params.replace_all) {
344
- if (!content.includes(oldStr)) {
345
- return { error: 'old_string not found in file' };
346
- }
347
- const result = content.split(oldStr).join(newStr);
348
- const final = originalLineEnding === '\r\n' ? result.replace(/\n/g, '\r\n') : result;
349
- fs.writeFileSync(filePath, final, encoding);
350
- return buildResult();
351
- }
352
- // Uniqueness check
353
- const firstIdx = content.indexOf(oldStr);
354
- if (firstIdx === -1) {
355
- return { error: 'old_string not found in file' };
356
- }
357
- const secondIdx = content.indexOf(oldStr, firstIdx + 1);
358
- if (secondIdx !== -1) {
359
- return { error: 'old_string is not unique in file (found at least 2 occurrences). Provide more context to make it unique, or use replace_all.' };
360
- }
361
- // Functional replace avoids $& / $' / $` interpretation
362
- const result = content.replace(oldStr, () => newStr);
363
- const final = originalLineEnding === '\r\n' ? result.replace(/\n/g, '\r\n') : result;
364
- fs.writeFileSync(filePath, final, encoding);
365
- return buildResult();
366
- }
367
- catch (err) {
368
- return { error: err.message };
369
- }
370
- }
371
- // --- Tool: Glob ---
372
- const GLOB_MAX_RESULTS = 500;
373
- const VCS_DIRS = new Set(['.git', '.svn', '.hg', 'node_modules', '__pycache__', '.tox', '.mypy_cache']);
374
- async function handleGlob(params) {
375
- try {
376
- const pattern = params.pattern;
377
- const cwd = normalizePath(params.path || (PLATFORM === 'win32' ? 'C:\\' : process.cwd()));
378
- if (!fs.existsSync(cwd)) {
379
- return { error: `Directory not found: ${cwd}` };
380
- }
381
- // Safe glob via bash positional args — no shell injection.
382
- // $2 undergoes: parameter expansion -> word splitting -> pathname expansion.
383
- // Command substitution does NOT happen on expanded parameter values.
384
- const limit = GLOB_MAX_RESULTS + 1;
385
- const result = await spawnCommand('bash', [
386
- '-c',
387
- `shopt -s globstar nullglob 2>/dev/null; cd -- "$1" 2>/dev/null || exit 1; i=0; for f in $2; do echo "$f"; i=$((i+1)); [ $i -ge ${limit} ] && break; done`,
388
- '--',
389
- cwd,
390
- pattern,
391
- ], 30000);
392
- if (result.exitCode !== 0 && !result.stdout.trim()) {
393
- return { files: [], truncated: false };
394
- }
395
- let files = result.stdout.trim().split('\n').filter(Boolean);
396
- const truncated = files.length > GLOB_MAX_RESULTS;
397
- if (truncated)
398
- files = files.slice(0, GLOB_MAX_RESULTS);
399
- // Convert to absolute paths
400
- files = files.map(f => path.isAbsolute(f) ? f : path.resolve(cwd, f));
401
- // Filter out VCS/noise directories
402
- files = files.filter(f => {
403
- const parts = path.relative(cwd, f).split(path.sep);
404
- return !parts.some(p => VCS_DIRS.has(p));
405
- });
406
- return { files, truncated };
407
- }
408
- catch (err) {
409
- return { error: err.message };
410
- }
411
- }
412
- // --- Tool: Grep ---
413
- const GREP_VCS_EXCLUDES = ['.git', '.svn', '.hg', 'node_modules', '__pycache__'];
414
- function buildRgArgs(params) {
415
- const args = [];
416
- const mode = params.output_mode || 'files_with_matches';
417
- if (mode === 'files_with_matches') {
418
- args.push('-l');
419
- }
420
- else if (mode === 'count') {
421
- args.push('-c');
422
- }
423
- else {
424
- // content mode
425
- if (params['-n'] !== false)
426
- args.push('-n');
427
- if (params['-A'] != null)
428
- args.push('-A', String(params['-A']));
429
- if (params['-B'] != null)
430
- args.push('-B', String(params['-B']));
431
- const ctx = params['-C'] ?? params.context;
432
- if (ctx != null)
433
- args.push('-C', String(ctx));
434
- }
435
- if (params['-i'])
436
- args.push('-i');
437
- if (params.multiline)
438
- args.push('-U', '--multiline-dotall');
439
- if (params.glob)
440
- args.push('--glob', params.glob);
441
- if (params.type)
442
- args.push('--type', params.type);
443
- // VCS directory exclusion
444
- for (const dir of GREP_VCS_EXCLUDES) {
445
- args.push('--glob', `!${dir}`);
446
- }
447
- // Protect against minified/base64 long lines
448
- args.push('--max-columns', '500');
449
- // -- prevents pattern from being interpreted as an rg flag
450
- args.push('--', params.pattern);
451
- if (params.path)
452
- args.push(normalizePath(params.path));
453
- return args;
454
- }
455
- async function handleGrepFallback(params) {
456
- const args = ['-rn'];
457
- const mode = params.output_mode || 'files_with_matches';
458
- if (mode === 'files_with_matches')
459
- args.push('-l');
460
- else if (mode === 'count')
461
- args.push('-c');
462
- if (params['-i'])
463
- args.push('-i');
464
- args.push('--', params.pattern);
465
- args.push(normalizePath(params.path || '.'));
466
- const result = await spawnCommand('grep', args, 30000);
467
- return { output: result.stdout };
468
- }
469
- async function handleGrep(params) {
470
- try {
471
- const rgArgs = buildRgArgs(params);
472
- const result = await spawnCommand('rg', rgArgs, 30000);
473
- // rg exit codes: 0=matches, 1=no matches, 2=error
474
- // exitCode 127 = rg binary not found (from our error handler)
475
- if (result.exitCode === 127 || result.stderr.includes('not found')) {
476
- return handleGrepFallback(params);
477
- }
478
- if (result.exitCode === 2) {
479
- return { error: result.stderr.trim() || 'grep search error' };
480
- }
481
- let output = result.stdout;
482
- // Apply offset and head_limit pagination
483
- const headLimit = params.head_limit === 0 ? Infinity : (params.head_limit ?? 250);
484
- const offset = params.offset ?? 0;
485
- if (output && (offset > 0 || headLimit < Infinity)) {
486
- const lines = output.split('\n');
487
- const sliced = lines.slice(offset, offset + headLimit);
488
- const remaining = lines.length - offset - sliced.length;
489
- output = sliced.join('\n');
490
- if (remaining > 0) {
491
- output += `\n[... ${remaining} more entries, use offset to paginate]`;
492
- }
493
- }
494
- return { output: output || '' };
495
- }
496
- catch (err) {
497
- return { error: err.message };
498
- }
499
- }
500
- // --- Command dispatcher ---
501
- async function handleCommand(action, params) {
502
- switch (action) {
503
- case 'bash': {
504
- const timeout = Math.min(params.timeout || 120000, 600000);
505
- if (params.run_in_background) {
506
- const { pid } = execBashBackground(params.command);
507
- return {
508
- success: true,
509
- data: { stdout: `Background process started with PID ${pid}`, stderr: '', exitCode: 0 },
510
- };
511
- }
512
- const result = await execBash(params.command, timeout);
513
- return { success: true, data: result };
514
- }
515
- case 'read': {
516
- const result = handleRead(params);
517
- if (result.error)
518
- return { success: false, error: result.error };
519
- return { success: true, data: result };
520
- }
521
- case 'write': {
522
- const result = handleWrite(params);
523
- if (result.error)
524
- return { success: false, error: result.error };
525
- return { success: true, data: result };
526
- }
527
- case 'edit': {
528
- const result = handleEdit(params);
529
- if (result.error)
530
- return { success: false, error: result.error };
531
- return { success: true, data: result };
532
- }
533
- case 'glob': {
534
- const result = await handleGlob(params);
535
- if (result.error)
536
- return { success: false, error: result.error };
537
- return { success: true, data: result };
538
- }
539
- case 'grep': {
540
- const result = await handleGrep(params);
541
- if (result.error)
542
- return { success: false, error: result.error };
543
- return { success: true, data: result };
544
- }
545
- default:
546
- return { success: false, error: `Unknown action: ${action}` };
547
- }
548
- }
549
- // --- WebSocket connection ---
550
- let ws = null;
551
- let heartbeatTimer = null;
552
- let reconnectDelay = 1000;
553
- const MAX_RECONNECT_DELAY = 30000;
554
- function connect() {
555
- const url = resolveServerUrl(process.env);
556
- const headers = buildAuthHeaders(process.env);
557
- const hasToken = !!process.env.CORTEX_CLIENT_TOKEN?.trim();
558
- const hasCf = !!(process.env.CF_ACCESS_CLIENT_ID && process.env.CF_ACCESS_CLIENT_SECRET);
559
- const authTag = hasCf ? (hasToken ? ' [token+CF]' : ' [CF Access]') : (hasToken ? ' [token]' : '');
560
- log.info(`Connecting to ${url} as "${DEVICE_NAME}" (${PLATFORM})${authTag}...`);
561
- ws = headers ? new WebSocket(url, { headers }) : new WebSocket(url);
562
- ws.on('open', () => {
563
- log.info(`Connected to server`);
564
- reconnectDelay = 1000;
565
- const capabilities = detectCapabilities();
566
- ws.send(JSON.stringify({
567
- type: 'hello',
568
- device: DEVICE_NAME,
569
- platform: PLATFORM,
570
- capabilities,
571
- }));
572
- if (heartbeatTimer)
573
- clearInterval(heartbeatTimer);
574
- heartbeatTimer = setInterval(() => {
575
- if (ws && ws.readyState === WebSocket.OPEN) {
576
- ws.send(JSON.stringify({
577
- type: 'heartbeat',
578
- device: DEVICE_NAME,
579
- timestamp: Date.now(),
580
- }));
581
- }
582
- }, HEARTBEAT_INTERVAL_MS);
583
- });
584
- ws.on('message', async (raw) => {
585
- let msg;
586
- try {
587
- msg = JSON.parse(raw.toString());
588
- }
589
- catch {
590
- return;
591
- }
592
- if (msg.type === 'command' && msg.commandId) {
593
- // Capture ws reference before async gap to prevent null dereference
594
- const currentWs = ws;
595
- log.info(`Executing ${msg.action}: ${JSON.stringify(msg.params).substring(0, 100)}`);
596
- try {
597
- const result = await handleCommand(msg.action, msg.params || {});
598
- if (currentWs && currentWs.readyState === WebSocket.OPEN) {
599
- currentWs.send(JSON.stringify({
600
- type: 'result',
601
- commandId: msg.commandId,
602
- ...result,
603
- }));
604
- }
605
- }
606
- catch (err) {
607
- if (currentWs && currentWs.readyState === WebSocket.OPEN) {
608
- currentWs.send(JSON.stringify({
609
- type: 'result',
610
- commandId: msg.commandId,
611
- success: false,
612
- error: err.message,
613
- }));
614
- }
615
- }
616
- }
617
- });
618
- ws.on('close', (code, reason) => {
619
- log.info(`Disconnected (code=${code}, reason=${reason?.toString() || 'none'})`);
620
- cleanup();
621
- if (code === 4002) {
622
- log.info('Server rejected connection (device already connected). Exiting.');
623
- process.exit(1);
624
- }
625
- scheduleReconnect();
626
- });
627
- ws.on('error', (err) => {
628
- log.error(`WebSocket error: ${err.message}`);
629
- });
630
- }
631
- function cleanup() {
632
- if (heartbeatTimer) {
633
- clearInterval(heartbeatTimer);
634
- heartbeatTimer = null;
635
- }
636
- ws = null;
637
- }
638
- function scheduleReconnect() {
639
- log.info(`Reconnecting in ${reconnectDelay / 1000}s...`);
640
- setTimeout(() => {
641
- reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY);
642
- connect();
643
- }, reconnectDelay);
644
- }
645
- // --- Graceful shutdown ---
646
- function shutdown() {
647
- log.info('Shutting down...');
648
- if (heartbeatTimer)
649
- clearInterval(heartbeatTimer);
650
- if (ws) {
651
- try {
652
- ws.close(1000, 'Client shutting down');
653
- }
654
- catch { }
655
- }
656
- process.exit(0);
657
- }
658
- process.on('SIGINT', shutdown);
659
- process.on('SIGTERM', shutdown);
660
- // --- Start ---
661
- log.info(`Starting: device="${DEVICE_NAME}", platform="${PLATFORM}", server=${resolveServerUrl(process.env)}`);
662
- connect();
@@ -1,25 +0,0 @@
1
- #!/usr/bin/env node
2
- declare function resolveTaskGeneration(project: string | null, taskId: string | null, env?: NodeJS.ProcessEnv): string | null;
3
- interface CortexRunArgs {
4
- name?: string;
5
- device: string;
6
- command?: string[];
7
- project: string | null;
8
- taskId: string | null;
9
- envPassthrough: string[];
10
- logTailBytes: number;
11
- cancel: string | null;
12
- signal: string;
13
- stall: string;
14
- gpu: string;
15
- force: boolean;
16
- }
17
- declare function getCortexRunHelp(): string;
18
- /**
19
- * Returns true if the user is asking for help at the top level.
20
- * `--help` / `-h` that appear AFTER the `--` separator belong to the user
21
- * command and must not be treated as cortex-run help requests.
22
- */
23
- declare function isHelpRequest(rawArgs: string[]): boolean;
24
- declare function parseCliArgs(): CortexRunArgs;
25
- export { parseCliArgs, getCortexRunHelp, isHelpRequest, resolveTaskGeneration };