@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
@@ -2,13 +2,15 @@ import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import * as os from 'os';
4
4
  import * as crypto from 'crypto';
5
- import { execSync } from 'child_process';
5
+ import { runFile, runShell } from '../../core/exec-async.js';
6
6
  import { setClientUpdateHooks, getOnlineDevices, sendControlMessage, } from './client-manager.js';
7
7
  import { STORE_DIR } from '../../core/utils.js';
8
8
  import { createLogger } from '../../core/log.js';
9
9
  import { Icons } from '../../core/icons.js';
10
10
  const log = createLogger('client-hot-reload');
11
- /** The complete update artifact, hashed in this exact order on both ends. */
11
+ /** The complete update artifact, hashed in this exact order on both ends.
12
+ * `cortex-run-watcher.mjs` is a compatibility stub (cortex-run was removed) — see the note on
13
+ * BUNDLE_FILES in client/src/self-update.ts. Both ends drop it in the same release or not at all. */
12
14
  const BUNDLE_FILES = ['client.mjs', 'cortex-run-watcher.mjs'];
13
15
  /** After a failed install, do not re-push the same bundle to that device for this long. */
14
16
  const PUSH_RETRY_COOLDOWN_MS = 10 * 60_000;
@@ -66,22 +68,23 @@ function loadBundleFromDir(dir, version) {
66
68
  }
67
69
  return { version, hash: h.digest('hex'), files };
68
70
  }
69
- /** Dev mode: bundle straight from the client repo (esbuild, sub-second). */
70
- function buildDevBundle() {
71
+ /** Dev mode: bundle straight from the client repo (esbuild, sub-second).
72
+ * Async: the build can take a while and this runs inside the server process. */
73
+ async function buildDevBundle() {
71
74
  const repo = resolveClientRepo();
72
75
  if (!repo) {
73
76
  log.warn('Dev mode: client repo not found — client hot-reload idle');
74
77
  return null;
75
78
  }
76
- try {
79
+ {
77
80
  const start = Date.now();
78
- execSync('npm run bundle', { cwd: repo, encoding: 'utf8', timeout: 120000, stdio: 'pipe' });
81
+ const built = await runShell('npm run bundle', { cwd: repo, timeoutMs: 120000 });
82
+ if (!built.ok) {
83
+ log.error(`Client bundle build failed: ${(built.stderr || built.error || '').trim()}`);
84
+ return null;
85
+ }
79
86
  log.info(`Client bundle built in ${Date.now() - start}ms`);
80
87
  }
81
- catch (err) {
82
- log.error(`Client bundle build failed: ${err.message}`);
83
- return null;
84
- }
85
88
  let version = 'dev';
86
89
  try {
87
90
  version = `${JSON.parse(fs.readFileSync(path.join(repo, 'package.json'), 'utf8')).version}-dev`;
@@ -90,16 +93,15 @@ function buildDevBundle() {
90
93
  return loadBundleFromDir(path.join(repo, 'dist'), version);
91
94
  }
92
95
  /** Release mode: latest published client package, bundle files cached per version. */
93
- function fetchReleaseBundle() {
96
+ async function fetchReleaseBundle() {
94
97
  let version = '';
95
- try {
96
- version = execSync('npm view @cortex-agent/client version', {
97
- encoding: 'utf8', timeout: 30000, stdio: 'pipe',
98
- }).trim();
99
- }
100
- catch (err) {
101
- log.warn(`Release mode: npm registry unreachable — client hot-reload idle (${err.message})`);
102
- return null;
98
+ {
99
+ const probed = await runFile('npm', ['view', '@cortex-agent/client', 'version'], { timeoutMs: 30000 });
100
+ if (!probed.ok) {
101
+ log.warn(`Release mode: npm registry unreachable — client hot-reload idle (${(probed.stderr || probed.error || '').trim()})`);
102
+ return null;
103
+ }
104
+ version = probed.stdout.trim();
103
105
  }
104
106
  if (!version)
105
107
  return null;
@@ -110,11 +112,15 @@ function fetchReleaseBundle() {
110
112
  let tmp = null;
111
113
  try {
112
114
  tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'cortex-client-bundle-'));
113
- execSync(`npm pack @cortex-agent/client@${version}`, { cwd: tmp, encoding: 'utf8', timeout: 60000, stdio: 'pipe' });
115
+ const packed = await runFile('npm', ['pack', `@cortex-agent/client@${version}`], { cwd: tmp, timeoutMs: 60000 });
116
+ if (!packed.ok)
117
+ throw new Error(`npm pack failed: ${(packed.stderr || packed.error || '').trim()}`);
114
118
  const tgz = fs.readdirSync(tmp).find((f) => f.endsWith('.tgz'));
115
119
  if (!tgz)
116
120
  throw new Error('npm pack produced no tgz');
117
- execSync(`tar -xzf ${JSON.stringify(tgz)}`, { cwd: tmp, encoding: 'utf8', timeout: 30000, stdio: 'pipe' });
121
+ const untarred = await runFile('tar', ['-xzf', tgz], { cwd: tmp, timeoutMs: 30000 });
122
+ if (!untarred.ok)
123
+ throw new Error(`tar failed: ${(untarred.stderr || untarred.error || '').trim()}`);
118
124
  fs.mkdirSync(cacheDir, { recursive: true });
119
125
  for (const name of BUNDLE_FILES) {
120
126
  fs.copyFileSync(path.join(tmp, 'package', 'dist', name), path.join(cacheDir, name));
@@ -130,7 +136,7 @@ function fetchReleaseBundle() {
130
136
  }
131
137
  return loadBundleFromDir(cacheDir, version);
132
138
  }
133
- function resolveBundle() {
139
+ async function resolveBundle() {
134
140
  return isDevMode() ? buildDevBundle() : fetchReleaseBundle();
135
141
  }
136
142
  // --- Push decision ---
@@ -210,8 +216,8 @@ function onUpdateResult(device, result) {
210
216
  function initClientHotReload(notify) {
211
217
  _notify = notify;
212
218
  setClientUpdateHooks({ onHello, onUpdateResult });
213
- setImmediate(() => {
214
- const bundle = resolveBundle();
219
+ setImmediate(async () => {
220
+ const bundle = await resolveBundle();
215
221
  if (!bundle)
216
222
  return;
217
223
  _bundle = bundle;
@@ -3,15 +3,12 @@ import * as crypto from 'crypto';
3
3
  import * as fs from 'fs';
4
4
  import * as path from 'path';
5
5
  import { execFile, spawn } from 'child_process';
6
- import { getMachineRegistry } from '../tasks/dispatch-utils.js';
6
+ import { getMachineRegistry, applyReportedGpuCount } from '../tasks/dispatch-utils.js';
7
7
  import { STORE_DIR, DATA_DIR } from '../../core/utils.js';
8
8
  import { AUTH_HEADER, getClientToken, timingSafeEqualStr } from '../../core/auth.js';
9
9
  import { createLogger } from '../../core/log.js';
10
10
  import { claimStream, parseStreamId, cancelStreamsFor } from './reverse-stream.js';
11
11
  import { emitCortexEvent } from '../../core/hook-bus.js';
12
- import { readTasks, findTask } from '../tasks/system/task-lifecycle-edit.js';
13
- import { taskMutator } from '../tasks/mutator.js';
14
- import { setExecutionGpuByTaskId } from '../executions/registry.js';
15
12
  import { SshTunnelSupervisor } from './client-ssh-tunnel.js';
16
13
  const log = createLogger('client-manager');
17
14
  let updateHooks = null;
@@ -31,6 +28,43 @@ function emitDisconnected(device, reason) {
31
28
  const payload = reason ? { device, reason } : { device };
32
29
  void emitCortexEvent('cortex:client.disconnected', payload).catch(() => { });
33
30
  }
31
+ /**
32
+ * Take a device online from its hello frame. Returns the device name, or null when the frame was
33
+ * rejected (no name / a live connection already holds that name) — the socket is closed in that case.
34
+ *
35
+ * The frame also carries the machine's own GPU count, which is reconciled into machines.json here:
36
+ * a client knows its hardware, the registry only holds what someone typed. An absent or
37
+ * unparseable `gpuCount` is "unknown" and leaves the configured value alone.
38
+ */
39
+ function registerHelloDevice(ws, msg) {
40
+ const device = msg.device;
41
+ if (!device) {
42
+ ws.close(4001, 'Missing device name');
43
+ return null;
44
+ }
45
+ const existing = devices.get(device);
46
+ if (existing && existing.ws !== ws) {
47
+ log.info(`Device ${device} already connected, rejecting new connection`);
48
+ ws.close(4002, 'Device already connected');
49
+ return null;
50
+ }
51
+ const bundleHash = typeof msg.bundleHash === 'string' && msg.bundleHash ? msg.bundleHash : null;
52
+ const platform = msg.platform || 'unknown';
53
+ devices.set(device, {
54
+ device, platform, capabilities: msg.capabilities || [],
55
+ connectedAt: new Date(), lastHeartbeat: new Date(), bundleHash, ws,
56
+ });
57
+ log.info(`Device connected: ${device} (${platform})`);
58
+ void emitCortexEvent('cortex:client.connected', { device }).catch(() => { });
59
+ applyReportedGpuCount(device, typeof msg.gpuCount === 'number' ? msg.gpuCount : null);
60
+ try {
61
+ updateHooks?.onHello(device, bundleHash);
62
+ }
63
+ catch (e) {
64
+ log.warn(`onHello hook failed for ${device}: ${e.message}`);
65
+ }
66
+ return device;
67
+ }
34
68
  // --- Server lifecycle ---
35
69
  function startClientManager(port) {
36
70
  if (wss) {
@@ -80,36 +114,7 @@ function startClientManager(port) {
80
114
  return;
81
115
  }
82
116
  if (msg.type === 'hello') {
83
- deviceName = msg.device;
84
- if (!deviceName) {
85
- ws.close(4001, 'Missing device name');
86
- return;
87
- }
88
- // If a device with the same name is already connected, reject the new connection
89
- const existing = devices.get(deviceName);
90
- if (existing && existing.ws !== ws) {
91
- log.info(`Device ${deviceName} already connected, rejecting new connection`);
92
- ws.close(4002, 'Device already connected');
93
- return;
94
- }
95
- const bundleHash = typeof msg.bundleHash === 'string' && msg.bundleHash ? msg.bundleHash : null;
96
- devices.set(deviceName, {
97
- device: deviceName,
98
- platform: msg.platform || 'unknown',
99
- capabilities: msg.capabilities || [],
100
- connectedAt: new Date(),
101
- lastHeartbeat: new Date(),
102
- bundleHash,
103
- ws,
104
- });
105
- log.info(`Device connected: ${deviceName} (${msg.platform || 'unknown'})`);
106
- void emitCortexEvent('cortex:client.connected', { device: deviceName }).catch(() => { });
107
- try {
108
- updateHooks?.onHello(deviceName, bundleHash);
109
- }
110
- catch (e) {
111
- log.warn(`onHello hook failed for ${deviceName}: ${e.message}`);
112
- }
117
+ deviceName = registerHelloDevice(ws, msg);
113
118
  return;
114
119
  }
115
120
  if (msg.type === 'update-result' && deviceName) {
@@ -146,10 +151,6 @@ function startClientManager(port) {
146
151
  }
147
152
  return;
148
153
  }
149
- if (msg.type === 'task-callback') {
150
- void handleTaskCallback(ws, msg).catch((e) => log.error(`task-callback: ${e.message}`));
151
- return;
152
- }
153
154
  });
154
155
  ws.on('close', (_code, reason) => {
155
156
  if (deviceName) {
@@ -676,87 +677,6 @@ function _testReset() {
676
677
  _getRegistryImpl = getMachineRegistry;
677
678
  tunnelSupervisor = new SshTunnelSupervisor();
678
679
  }
679
- // --- Task callback handler (DR-0011 §4.4) ---
680
- function sendAck(ws, callbackId, ok, message) {
681
- if (ws.readyState === WebSocket.OPEN) {
682
- ws.send(JSON.stringify({ type: 'task-callback-ack', callbackId, ok, message }));
683
- }
684
- }
685
- /** Validate an untrusted `gpu` field from a task-callback into a persistable ExecutionGpuInfo,
686
- * or null if absent/malformed. Requires a non-empty numeric `indices` array. */
687
- function normalizeGpuPayload(raw) {
688
- if (!raw || typeof raw !== 'object')
689
- return null;
690
- const obj = raw;
691
- const indices = Array.isArray(obj.indices)
692
- ? obj.indices.filter((n) => typeof n === 'number' && Number.isFinite(n))
693
- : [];
694
- if (indices.length === 0)
695
- return null;
696
- const memoryMb = typeof obj.memoryMb === 'number' && Number.isFinite(obj.memoryMb) ? obj.memoryMb : null;
697
- return { indices, memoryMb };
698
- }
699
- async function handleTaskCallback(ws, msg) {
700
- const { taskProject, taskId, dispatchGeneration, termination, exitCode, durationHuman, remoteResultPath, remoteLogPath, device, callbackId, logTail, gpu } = msg;
701
- // Capture the per-execution GPU onto the dispatch execution record (DR-0018 §6.3 B2-followup).
702
- // Keyed by taskId, independent of task status, and done BEFORE the idempotency short-circuits so
703
- // it lands even on an "already done" callback. No-op when no execution is registered for the task
704
- // (non-webhook-launched run) or the payload is absent/malformed.
705
- if (taskId) {
706
- const normalizedGpu = normalizeGpuPayload(gpu);
707
- if (normalizedGpu) {
708
- try {
709
- setExecutionGpuByTaskId(taskId, normalizedGpu);
710
- }
711
- catch (e) {
712
- log.warn(`task-callback: failed to record GPU for task ${taskId}: ${e.message}`);
713
- }
714
- }
715
- }
716
- // No task linkage: ack-true immediately (client doesn't need to retry)
717
- if (!taskProject || !taskId) {
718
- sendAck(ws, callbackId, true, 'no task linkage');
719
- return;
720
- }
721
- // Read task state from TASKS.yaml for idempotency check
722
- const tasks = readTasks(taskProject);
723
- const found = findTask(tasks, null, taskId);
724
- if ('error' in found) {
725
- log.info(`Ghost callback: task ${taskId} not found in ${taskProject}`);
726
- sendAck(ws, callbackId, true, 'ghost callback');
727
- return;
728
- }
729
- const task = found.task;
730
- if (task.status === 'done') {
731
- sendAck(ws, callbackId, true, 'already done, idempotent');
732
- return;
733
- }
734
- const isSuccess = termination === 'completed' && exitCode === 0;
735
- const remoteRef = remoteResultPath || remoteLogPath || 'unknown';
736
- const note = isSuccess
737
- ? `cortex-run on ${device} completed in ${durationHuman || '?'}, exit 0. Remote: ${remoteRef}`
738
- : `cortex-run on ${device} ${termination || '?'} after ${durationHuman || '?'}, exit ${exitCode ?? '?'}. Remote: ${remoteRef}\n--- log tail ---\n${logTail || '(no log tail)'}`;
739
- // Route through taskMutator (not the bare lifecycle functions) so task.completed /
740
- // task.blocked events fire — a manager thread suspended on this task (DR-0014 §8)
741
- // is woken by exactly these events, possibly days after dispatch.
742
- let result;
743
- if (isSuccess) {
744
- result = await taskMutator.complete(taskId, note, {
745
- skipVerify: true,
746
- skipVerifyReason: 'remote-run',
747
- ownership: { generation: dispatchGeneration ?? null },
748
- });
749
- }
750
- else {
751
- result = await taskMutator.block(taskId, note, {
752
- ownership: { generation: dispatchGeneration ?? null },
753
- });
754
- }
755
- const ackMessage = result.verify_warning
756
- ? `${result.message} (${result.verify_warning})`
757
- : result.message;
758
- sendAck(ws, callbackId, result.stale ? true : result.success, ackMessage);
759
- }
760
680
  export { startClientManager, stopClientManager, getOnlineDevices, isDeviceOnline, sendCommand, sendControlMessage, setClientUpdateHooks, startRemoteClient, launchRemoteClient, startAllRemoteClients, buildRemoteSpawnCommand, localClientEntryPath, clientPids, sshExec,
761
681
  // Test-only hooks (prefixed with _ by convention).
762
682
  _setSshExecForTesting, _setMachineRegistryProviderForTesting, _setTunnelSupervisorForTesting, _getRestartTimerCount, _testReset, };
@@ -10,7 +10,7 @@ export interface ClientConnectEnv {
10
10
  /**
11
11
  * Resolve the WebSocket URL the cortex-client dials.
12
12
  *
13
- * A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.fangxm.me``) takes
13
+ * A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.example.com``) takes
14
14
  * precedence so the client can reach the agent-server through a Cloudflare
15
15
  * Tunnel over 443/TLS. Otherwise it falls back to ``ws://<host>:<port>`` for
16
16
  * direct/LAN reach.
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Resolve the WebSocket URL the cortex-client dials.
3
3
  *
4
- * A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.fangxm.me``) takes
4
+ * A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.example.com``) takes
5
5
  * precedence so the client can reach the agent-server through a Cloudflare
6
6
  * Tunnel over 443/TLS. Otherwise it falls back to ``ws://<host>:<port>`` for
7
7
  * direct/LAN reach.
@@ -0,0 +1,51 @@
1
+ /** `file.stat` is a metadata round trip — the client-manager file-command timeout is plenty. */
2
+ export interface RemoteFileStat {
3
+ size: number;
4
+ name: string;
5
+ mtimeMs?: number;
6
+ }
7
+ /** Metadata probe: existence, regular-file-ness and size, with the device's own error text. */
8
+ export declare function statRemoteFile(device: string, filePath: string): Promise<RemoteFileStat>;
9
+ /**
10
+ * Everything that can be known — and refused — before a single byte moves: that the device is
11
+ * online and new enough, that the path is a readable file, and that it fits under the cap. Callers
12
+ * that need the file's NAME to choose a destination run this first and hand the result back to
13
+ * `fetchRemoteFile`, so the device is stat'ed once rather than twice.
14
+ */
15
+ export declare function prepareRemoteFetch(a: {
16
+ device: string;
17
+ filePath: string;
18
+ maxBytes?: number;
19
+ }): Promise<RemoteFileStat>;
20
+ export interface FetchRemoteFileArgs {
21
+ device: string;
22
+ /** Absolute path ON THE DEVICE. */
23
+ filePath: string;
24
+ /** Local destination; its directory must already exist. */
25
+ destPath: string;
26
+ /** Refuse before transferring anything when the device reports a larger file. */
27
+ maxBytes?: number;
28
+ /** Result of an earlier `prepareRemoteFetch` for this exact file; skips the second stat. */
29
+ stat?: RemoteFileStat;
30
+ }
31
+ /**
32
+ * Copy `filePath` from `device` into `destPath`. Throws — leaving no partial file behind — when the
33
+ * device is offline, too old, the path is not a readable file, it exceeds `maxBytes`, or the
34
+ * transfer ends short.
35
+ */
36
+ export declare function fetchRemoteFile(a: FetchRemoteFileArgs): Promise<RemoteFileStat>;
37
+ export interface StagedRemoteFile {
38
+ /** Server-local path the caller reads, and is expected to delete when done. */
39
+ localPath: string;
40
+ name: string;
41
+ size: number;
42
+ }
43
+ /**
44
+ * Stream a device's file into a server-local staging path. Used by senders that do their own upload
45
+ * from disk (Slack, Feishu); the Web sender writes into the session's outputs directly instead.
46
+ */
47
+ export declare function stageRemoteFile(a: {
48
+ device: string;
49
+ filePath: string;
50
+ maxBytes?: number;
51
+ }): Promise<StagedRemoteFile>;
@@ -0,0 +1,193 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import * as crypto from 'crypto';
4
+ import { WORKSPACE_DIR } from '../../core/paths.js';
5
+ import { createLogger } from '../../core/log.js';
6
+ import { sendCommand, sendControlMessage, getOnlineDevices } from './client-manager.js';
7
+ import { requestFileStream } from './reverse-stream.js';
8
+ const log = createLogger('device-file');
9
+ /**
10
+ * Pull a whole file off a device (`send_file device=…`). Every other remote tool answers on the
11
+ * control socket as one JSON message, which is fine for text but not for bytes: a file would be
12
+ * base64'd whole into memory on both ends and would hold the device's single command channel for
13
+ * the length of the transfer. So this uses the reverse channel instead — the same handshake the
14
+ * port forward already relies on — and streams binary frames straight to disk.
15
+ *
16
+ * The transfer is two steps on purpose. `file.stat` first, over the ordinary command path, so a
17
+ * missing path or an over-cap file fails with a real error message; only then is the stream opened.
18
+ * The stat'd size then doubles as the completeness check: a transfer that ends early is rejected
19
+ * rather than silently delivering a truncated file.
20
+ */
21
+ /** The device must have dialled back AND finished within this; a stalled transfer is not a hang. */
22
+ const IDLE_TIMEOUT_MS = 60_000;
23
+ /** Capability advertised in the device's `hello`. Absent on clients older than this feature. */
24
+ const FILE_STREAM_CAPABILITY = 'file-stream';
25
+ function assertCanStreamFiles(device) {
26
+ const info = getOnlineDevices().find(d => d.device === device);
27
+ if (!info)
28
+ throw new Error(`Device "${device}" is not online`);
29
+ if (!info.capabilities?.includes(FILE_STREAM_CAPABILITY)) {
30
+ throw new Error(`Device "${device}" runs a client too old to stream files. It updates itself on its next `
31
+ + 'reconnect; until then, copy the file to the server yourself.');
32
+ }
33
+ }
34
+ /** Metadata probe: existence, regular-file-ness and size, with the device's own error text. */
35
+ export async function statRemoteFile(device, filePath) {
36
+ const data = await sendCommand(device, { action: 'file.stat', params: { file_path: filePath } });
37
+ if (typeof data?.size !== 'number')
38
+ throw new Error(`Device "${device}" returned no size for ${filePath}`);
39
+ return { size: data.size, name: data.name || filePath.split(/[/\\]/).pop() || 'file', mtimeMs: data.mtimeMs };
40
+ }
41
+ /** Receive the callback socket's frames into `destPath`, resolving with the byte count. */
42
+ function receiveInto(ws, destPath, expected) {
43
+ return new Promise((resolve, reject) => {
44
+ const out = fs.createWriteStream(destPath);
45
+ let received = 0;
46
+ let settled = false;
47
+ let idle;
48
+ const finish = (err) => {
49
+ if (settled)
50
+ return;
51
+ settled = true;
52
+ clearTimeout(idle);
53
+ // End the file either way: the caller deletes a failed destination, and leaving the handle
54
+ // open would keep it undeletable on Windows.
55
+ out.end(() => (err ? reject(err) : resolve(received)));
56
+ if (err) {
57
+ try {
58
+ ws.close();
59
+ }
60
+ catch { /* already closing */ }
61
+ }
62
+ };
63
+ const armIdle = () => {
64
+ clearTimeout(idle);
65
+ idle = setTimeout(() => finish(new Error(`transfer stalled after ${received}/${expected} bytes`)), IDLE_TIMEOUT_MS);
66
+ idle.unref?.();
67
+ };
68
+ armIdle();
69
+ ws.on('message', (data) => {
70
+ const buf = Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
71
+ received += buf.length;
72
+ armIdle();
73
+ if (received > expected) {
74
+ finish(new Error(`device sent more than the ${expected} bytes it declared`));
75
+ return;
76
+ }
77
+ // Pause the socket while the disk catches up, so a slow filesystem costs time, not memory.
78
+ if (!out.write(buf)) {
79
+ ws.pause?.();
80
+ out.once('drain', () => ws.resume?.());
81
+ }
82
+ });
83
+ ws.on('error', (e) => finish(new Error(`stream error: ${e.message}`)));
84
+ out.on('error', (e) => finish(new Error(`write failed: ${e.message}`)));
85
+ ws.on('close', (code, reason) => {
86
+ const why = reason?.toString() || '';
87
+ // The client reports a read-side failure by closing with a reason instead of by sending
88
+ // fewer bytes, so an explicit error is never mistaken for a short file and vice versa.
89
+ if (code !== 1000) {
90
+ finish(new Error(why || `device closed the stream (code ${code})`));
91
+ return;
92
+ }
93
+ if (received !== expected) {
94
+ finish(new Error(`truncated transfer: got ${received} of ${expected} bytes${why ? ` (${why})` : ''}`));
95
+ return;
96
+ }
97
+ finish(null);
98
+ });
99
+ });
100
+ }
101
+ /**
102
+ * Everything that can be known — and refused — before a single byte moves: that the device is
103
+ * online and new enough, that the path is a readable file, and that it fits under the cap. Callers
104
+ * that need the file's NAME to choose a destination run this first and hand the result back to
105
+ * `fetchRemoteFile`, so the device is stat'ed once rather than twice.
106
+ */
107
+ export async function prepareRemoteFetch(a) {
108
+ assertCanStreamFiles(a.device);
109
+ const stat = await statRemoteFile(a.device, a.filePath);
110
+ if (a.maxBytes !== undefined && stat.size > a.maxBytes) {
111
+ throw new Error(`File is ${stat.size} bytes on ${a.device}, over the ${a.maxBytes}-byte limit`);
112
+ }
113
+ return stat;
114
+ }
115
+ /**
116
+ * Copy `filePath` from `device` into `destPath`. Throws — leaving no partial file behind — when the
117
+ * device is offline, too old, the path is not a readable file, it exceeds `maxBytes`, or the
118
+ * transfer ends short.
119
+ */
120
+ export async function fetchRemoteFile(a) {
121
+ const stat = a.stat ?? await prepareRemoteFetch(a);
122
+ const req = requestFileStream(a.device, a.filePath);
123
+ // The claim rejects on its own timer (or when the device disconnects) whether or not anyone is
124
+ // waiting — and if `sendControlMessage` throws we never reach the await. An unobserved rejection
125
+ // would take the daemon down, so mark it handled now; the await below still sees the real error.
126
+ req.socket.catch(() => { });
127
+ let ws;
128
+ try {
129
+ sendControlMessage(a.device, req.message);
130
+ ws = await req.socket;
131
+ }
132
+ catch (e) {
133
+ throw new Error(`Failed to open a file stream from "${a.device}": ${e.message}`);
134
+ }
135
+ try {
136
+ const received = await receiveInto(ws, a.destPath, stat.size);
137
+ log.info(`fetched ${a.filePath} from ${a.device} (${received} bytes)`);
138
+ return stat;
139
+ }
140
+ catch (e) {
141
+ await fs.promises.rm(a.destPath, { force: true }).catch(() => { });
142
+ throw new Error(`Transfer of ${a.filePath} from "${a.device}" failed: ${e.message}`);
143
+ }
144
+ }
145
+ // --- Staging for senders that upload from a local path ---
146
+ /** Transfers in flight for a platform upload live here, one directory per transfer so two files of
147
+ * the same name never collide. */
148
+ const STAGING_DIR = path.join(WORKSPACE_DIR, 'remote-files');
149
+ /** A staged file outlives its upload only if that upload crashed; an hour is far past any transfer
150
+ * still worth waiting for. */
151
+ const STAGING_TTL_MS = 60 * 60_000;
152
+ /** Opportunistic sweep so a crashed uploader leaks at most one TTL window rather than forever. */
153
+ async function sweepStaging() {
154
+ const cutoff = Date.now() - STAGING_TTL_MS;
155
+ let entries;
156
+ try {
157
+ entries = await fs.promises.readdir(STAGING_DIR);
158
+ }
159
+ catch {
160
+ return;
161
+ }
162
+ await Promise.all(entries.map(async (name) => {
163
+ const dir = path.join(STAGING_DIR, name);
164
+ try {
165
+ const st = await fs.promises.stat(dir);
166
+ if (st.mtimeMs < cutoff)
167
+ await fs.promises.rm(dir, { recursive: true, force: true });
168
+ }
169
+ catch { /* raced with another sweep or an active uploader */ }
170
+ }));
171
+ }
172
+ /**
173
+ * Stream a device's file into a server-local staging path. Used by senders that do their own upload
174
+ * from disk (Slack, Feishu); the Web sender writes into the session's outputs directly instead.
175
+ */
176
+ export async function stageRemoteFile(a) {
177
+ const stat = await prepareRemoteFetch(a);
178
+ void sweepStaging();
179
+ const dir = path.join(STAGING_DIR, crypto.randomBytes(8).toString('hex'));
180
+ await fs.promises.mkdir(dir, { recursive: true });
181
+ // The device's own basename, with separators stripped: it is remote input, and it must not be
182
+ // able to steer the write out of the staging directory.
183
+ const safeName = (stat.name.replace(/[/\\]/g, '_') || 'file').slice(0, 200);
184
+ const localPath = path.join(dir, safeName);
185
+ try {
186
+ await fetchRemoteFile({ device: a.device, filePath: a.filePath, destPath: localPath, stat });
187
+ }
188
+ catch (e) {
189
+ await fs.promises.rm(dir, { recursive: true, force: true }).catch(() => { });
190
+ throw e;
191
+ }
192
+ return { localPath, name: safeName, size: stat.size };
193
+ }
@@ -92,6 +92,9 @@ async function serveConnection(entry, tcp) {
92
92
  tcp.destroy();
93
93
  return;
94
94
  }
95
+ // The claim rejects on its own timer even if we bail out below without awaiting it, and an
96
+ // unobserved rejection would take the daemon down. The await further down still sees the error.
97
+ req.socket.catch(() => { });
95
98
  try {
96
99
  sendControl(device, req.message);
97
100
  }
@@ -13,15 +13,15 @@ import type { WebSocket } from 'ws';
13
13
  export declare const REVERSE_PATH_PREFIX = "/reverse";
14
14
  /** `/reverse?stream=<id>` → the id, or null when this is not a callback socket. */
15
15
  export declare function parseStreamId(rawUrl: string | undefined): string | null;
16
- export interface StreamRequest {
16
+ export interface StreamRequest<M = {
17
+ type: 'open-stream';
18
+ streamId: string;
19
+ host: string;
20
+ port: number;
21
+ }> {
17
22
  id: string;
18
23
  /** Message to hand to the device over its control socket. */
19
- message: {
20
- type: 'open-stream';
21
- streamId: string;
22
- host: string;
23
- port: number;
24
- };
24
+ message: M;
25
25
  /** Resolves with the device's callback socket, or rejects on timeout. */
26
26
  socket: Promise<WebSocket>;
27
27
  }
@@ -30,6 +30,17 @@ export interface StreamRequest {
30
30
  * device's control socket and then awaits `socket`.
31
31
  */
32
32
  export declare function requestStream(device: string, host: string, port: number): StreamRequest;
33
+ export type OpenFileStreamMessage = {
34
+ type: 'open-file-stream';
35
+ streamId: string;
36
+ path: string;
37
+ };
38
+ /**
39
+ * Same handshake as `requestStream`, but the device answers with the bytes of a FILE rather than a
40
+ * TCP connection. Both share the claim table, the cap and the callback path, so a file transfer
41
+ * needs no new port, credential or tunnel — only a different message on the control socket.
42
+ */
43
+ export declare function requestFileStream(device: string, filePath: string): StreamRequest<OpenFileStreamMessage>;
33
44
  /**
34
45
  * Pair a callback socket with its request. Returns false when the id is unknown — a stale or forged
35
46
  * callback, which the caller closes rather than trusts.
@@ -29,16 +29,12 @@ export function parseStreamId(rawUrl) {
29
29
  // Ids are minted here and echoed back verbatim; anything else is not ours.
30
30
  return id && /^[0-9a-f]{32}$/.test(id) ? id : null;
31
31
  }
32
- /**
33
- * Mint a stream the device is expected to dial back for. The caller sends `message` over the
34
- * device's control socket and then awaits `socket`.
35
- */
36
- export function requestStream(device, host, port) {
32
+ /** Mint a pending callback slot. `target` is for logging and the timeout message only. */
33
+ function mintStream(device, target) {
37
34
  if (pending.size >= MAX_PENDING) {
38
35
  throw new Error(`too many pending reverse streams (${pending.size})`);
39
36
  }
40
37
  const id = crypto.randomBytes(16).toString('hex');
41
- const target = `${host}:${port}`;
42
38
  let resolve;
43
39
  let reject;
44
40
  const socket = new Promise((res, rej) => { resolve = res; reject = rej; });
@@ -48,8 +44,25 @@ export function requestStream(device, host, port) {
48
44
  }, CLAIM_TIMEOUT_MS);
49
45
  timer.unref?.();
50
46
  pending.set(id, { device, target, resolve, reject, timer });
47
+ return { id, socket };
48
+ }
49
+ /**
50
+ * Mint a stream the device is expected to dial back for. The caller sends `message` over the
51
+ * device's control socket and then awaits `socket`.
52
+ */
53
+ export function requestStream(device, host, port) {
54
+ const { id, socket } = mintStream(device, `${host}:${port}`);
51
55
  return { id, message: { type: 'open-stream', streamId: id, host, port }, socket };
52
56
  }
57
+ /**
58
+ * Same handshake as `requestStream`, but the device answers with the bytes of a FILE rather than a
59
+ * TCP connection. Both share the claim table, the cap and the callback path, so a file transfer
60
+ * needs no new port, credential or tunnel — only a different message on the control socket.
61
+ */
62
+ export function requestFileStream(device, filePath) {
63
+ const { id, socket } = mintStream(device, filePath);
64
+ return { id, message: { type: 'open-file-stream', streamId: id, path: filePath }, socket };
65
+ }
53
66
  /**
54
67
  * Pair a callback socket with its request. Returns false when the id is unknown — a stale or forged
55
68
  * callback, which the caller closes rather than trusts.