@apralabs/apra-fleet 0.4.4 → 0.4.5

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 (268) hide show
  1. package/README.md +49 -4
  2. package/dist/agents/backlog-groomer.md +5 -0
  3. package/dist/agents/ci-watcher.md +5 -0
  4. package/dist/agents/deployer.md +20 -2
  5. package/dist/agents/doer.md +38 -2
  6. package/dist/agents/harvester.md +12 -9
  7. package/dist/agents/integ-test-runner.md +5 -0
  8. package/dist/agents/kb-reconciler.md +6 -0
  9. package/dist/agents/plan-reviewer.md +5 -0
  10. package/dist/agents/planner.md +5 -0
  11. package/dist/agents/regression-test-runner.md +5 -0
  12. package/dist/agents/reviewer.md +67 -15
  13. package/dist/agents/schemas/deployer-output.json +5 -0
  14. package/dist/agents/schemas/doer-output.json +78 -2
  15. package/dist/agents/schemas/reviewer-output.json +104 -2
  16. package/dist/cli/auth.js +5 -1
  17. package/dist/cli/beads-pin.js +6 -7
  18. package/dist/cli/claude-mod.d.ts +75 -0
  19. package/dist/cli/claude-mod.js +288 -0
  20. package/dist/cli/dolt-install.d.ts +1 -1
  21. package/dist/cli/dolt-install.js +5 -1
  22. package/dist/cli/fleet-se-guard.d.ts +8 -0
  23. package/dist/cli/fleet-se-guard.js +19 -3
  24. package/dist/cli/install-guard.d.ts +9 -0
  25. package/dist/cli/install-guard.js +24 -0
  26. package/dist/cli/install.d.ts +12 -0
  27. package/dist/cli/install.js +180 -20
  28. package/dist/cli/kb-profile.d.ts +16 -0
  29. package/dist/cli/kb-profile.js +81 -0
  30. package/dist/cli/start.js +3 -0
  31. package/dist/cli/uninstall.js +13 -3
  32. package/dist/cli/update.d.ts +4 -0
  33. package/dist/cli/update.js +19 -3
  34. package/dist/commands/kb-server.d.ts +10 -1
  35. package/dist/commands/kb-server.js +285 -11
  36. package/dist/index.js +22 -1
  37. package/dist/os/git-executable.d.ts +57 -0
  38. package/dist/os/git-executable.js +85 -0
  39. package/dist/os/go-concurrency.d.ts +44 -0
  40. package/dist/os/go-concurrency.js +53 -0
  41. package/dist/os/index.d.ts +1 -0
  42. package/dist/os/index.js +1 -0
  43. package/dist/os/linux.d.ts +2 -0
  44. package/dist/os/linux.js +10 -1
  45. package/dist/os/os-commands.d.ts +25 -0
  46. package/dist/os/os-commands.js +2 -0
  47. package/dist/os/windows-executable.d.ts +53 -0
  48. package/dist/os/windows-executable.js +185 -0
  49. package/dist/os/windows-gitbash.d.ts +23 -14
  50. package/dist/os/windows-gitbash.js +40 -16
  51. package/dist/os/windows.d.ts +2 -0
  52. package/dist/os/windows.js +37 -6
  53. package/dist/paths.d.ts +10 -1
  54. package/dist/paths.js +19 -2
  55. package/dist/services/agy-project.d.ts +7 -1
  56. package/dist/services/agy-project.js +7 -2
  57. package/dist/services/auth-socket.d.ts +18 -0
  58. package/dist/services/auth-socket.js +30 -4
  59. package/dist/services/credential-store.d.ts +33 -0
  60. package/dist/services/credential-store.js +79 -2
  61. package/dist/services/http-transport.d.ts +29 -0
  62. package/dist/services/http-transport.js +166 -37
  63. package/dist/services/kb-tool-profile.d.ts +36 -0
  64. package/dist/services/kb-tool-profile.js +88 -0
  65. package/dist/services/knowledge/bible-blob-id.js +10 -1
  66. package/dist/services/knowledge/bible-import.d.ts +108 -0
  67. package/dist/services/knowledge/bible-import.js +137 -4
  68. package/dist/services/knowledge/file-hash.js +6 -5
  69. package/dist/services/knowledge/http-provider.d.ts +303 -20
  70. package/dist/services/knowledge/http-provider.js +795 -125
  71. package/dist/services/knowledge/kb-config.d.ts +65 -1
  72. package/dist/services/knowledge/kb-config.js +143 -3
  73. package/dist/services/knowledge/kb-http-auth-state.d.ts +26 -0
  74. package/dist/services/knowledge/kb-http-auth-state.js +40 -0
  75. package/dist/services/knowledge/kb-providers.d.ts +9 -2
  76. package/dist/services/knowledge/kb-providers.js +67 -37
  77. package/dist/services/knowledge/kb-removed-scope-keys.js +1 -1
  78. package/dist/services/knowledge/kb-self.d.ts +122 -9
  79. package/dist/services/knowledge/kb-self.js +196 -36
  80. package/dist/services/knowledge/member-bible-view.js +16 -3
  81. package/dist/services/knowledge/path-validation.d.ts +7 -0
  82. package/dist/services/knowledge/path-validation.js +11 -0
  83. package/dist/services/knowledge/project-slug.js +3 -2
  84. package/dist/services/knowledge/repository-header.d.ts +77 -0
  85. package/dist/services/knowledge/repository-header.js +233 -0
  86. package/dist/services/knowledge/require-sqlite-project.d.ts +1 -1
  87. package/dist/services/knowledge/require-sqlite-project.js +1 -1
  88. package/dist/services/knowledge/sqlite-provider.d.ts +169 -0
  89. package/dist/services/knowledge/sqlite-provider.js +416 -4
  90. package/dist/services/knowledge/types.d.ts +15 -2
  91. package/dist/services/member-busy.d.ts +12 -0
  92. package/dist/services/member-busy.js +20 -0
  93. package/dist/services/member-config-io.d.ts +3 -2
  94. package/dist/services/member-config-io.js +7 -4
  95. package/dist/services/member-fleet-install.js +1 -0
  96. package/dist/services/member-tool-allowlist.d.ts +1 -1
  97. package/dist/services/member-tool-allowlist.js +8 -4
  98. package/dist/services/port-holder.js +2 -1
  99. package/dist/services/service-manager/types.d.ts +17 -1
  100. package/dist/services/service-manager/windows.d.ts +7 -2
  101. package/dist/services/service-manager/windows.js +28 -11
  102. package/dist/services/service-notice.d.ts +7 -0
  103. package/dist/services/service-notice.js +19 -0
  104. package/dist/services/session-registry.d.ts +13 -0
  105. package/dist/services/session-registry.js +13 -0
  106. package/dist/services/session-roots.d.ts +67 -0
  107. package/dist/services/session-roots.js +126 -0
  108. package/dist/services/statusline.d.ts +21 -0
  109. package/dist/services/statusline.js +97 -1
  110. package/dist/services/supervisor-service-cleanup.js +2 -1
  111. package/dist/services/tool-registry.js +108 -20
  112. package/dist/services/tool-scope.d.ts +34 -1
  113. package/dist/services/tool-scope.js +27 -2
  114. package/dist/services/vcs/azure-devops.js +10 -0
  115. package/dist/services/vcs/bitbucket.d.ts +22 -1
  116. package/dist/services/vcs/bitbucket.js +163 -17
  117. package/dist/services/vcs/types.d.ts +25 -2
  118. package/dist/services/watch/project-resolver.js +2 -1
  119. package/dist/skills/pm/cost.md +5 -1
  120. package/dist/skills/pm/index.md +9 -9
  121. package/dist/skills/pm/sprint.md +2 -1
  122. package/dist/tools/check-status.d.ts +51 -0
  123. package/dist/tools/check-status.js +124 -12
  124. package/dist/tools/code-intelligence-freshness.js +1 -1
  125. package/dist/tools/code-intelligence-gitnexus.d.ts +19 -0
  126. package/dist/tools/code-intelligence-gitnexus.js +166 -9
  127. package/dist/tools/code-intelligence-readiness.d.ts +58 -1
  128. package/dist/tools/code-intelligence-readiness.js +93 -8
  129. package/dist/tools/code-intelligence-reindex.d.ts +25 -1
  130. package/dist/tools/code-intelligence-reindex.js +76 -4
  131. package/dist/tools/code-intelligence.d.ts +1 -1
  132. package/dist/tools/code-intelligence.js +1 -1
  133. package/dist/tools/execute-command.js +14 -8
  134. package/dist/tools/execute-prompt.js +6 -2
  135. package/dist/tools/fleet-snapshot.d.ts +21 -0
  136. package/dist/tools/fleet-snapshot.js +78 -0
  137. package/dist/tools/kb-bible-commit.d.ts +25 -11
  138. package/dist/tools/kb-bible-commit.js +142 -33
  139. package/dist/tools/kb-capture.d.ts +2 -2
  140. package/dist/tools/kb-context.js +47 -27
  141. package/dist/tools/kb-demote.d.ts +27 -0
  142. package/dist/tools/kb-demote.js +37 -0
  143. package/dist/tools/kb-export.d.ts +35 -3
  144. package/dist/tools/kb-export.js +56 -13
  145. package/dist/tools/kb-feedback.d.ts +2 -0
  146. package/dist/tools/kb-feedback.js +17 -7
  147. package/dist/tools/kb-harvest.js +28 -9
  148. package/dist/tools/kb-import.d.ts +18 -2
  149. package/dist/tools/kb-import.js +24 -9
  150. package/dist/tools/kb-invalidate.d.ts +11 -3
  151. package/dist/tools/kb-invalidate.js +80 -7
  152. package/dist/tools/kb-list.js +38 -10
  153. package/dist/tools/kb-promote.js +6 -4
  154. package/dist/tools/kb-query.d.ts +3 -0
  155. package/dist/tools/kb-query.js +181 -37
  156. package/dist/tools/kb-session-prime.d.ts +4 -4
  157. package/dist/tools/kb-session-prime.js +89 -9
  158. package/dist/tools/kb-setup.d.ts +20 -0
  159. package/dist/tools/kb-setup.js +149 -11
  160. package/dist/tools/list-members.js +1 -1
  161. package/dist/tools/member-detail.js +7 -3
  162. package/dist/tools/provision-vcs-auth.d.ts +28 -3
  163. package/dist/tools/provision-vcs-auth.js +53 -7
  164. package/dist/tools/receive-files.js +7 -4
  165. package/dist/tools/send-files.js +5 -4
  166. package/dist/tools/send-message.d.ts +3 -0
  167. package/dist/tools/send-message.js +15 -2
  168. package/dist/tools/stop-prompt.js +3 -1
  169. package/dist/tools/vcs-credential-exec.d.ts +45 -3
  170. package/dist/tools/vcs-credential-exec.js +90 -11
  171. package/dist/utils/process-utils.js +5 -1
  172. package/dist/utils/redact-known-secrets.d.ts +17 -0
  173. package/dist/utils/redact-known-secrets.js +70 -0
  174. package/dist/utils/skill-matrix.js +1 -1
  175. package/dist/utils/vcs-provider-detect.js +2 -2
  176. package/dist/workflows/auto-sprint.js +245 -9
  177. package/package.json +10 -7
  178. package/packages/apra-fleet-client/package.json +1 -1
  179. package/packages/apra-fleet-client/src/client/api.mjs +172 -19
  180. package/packages/apra-fleet-client/src/client/reconnecting-transport.mjs +35 -2
  181. package/packages/apra-fleet-client/src/client/transport.mjs +6 -0
  182. package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +5 -0
  183. package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +5 -0
  184. package/packages/apra-fleet-se/apra-pm/agents/deployer.md +20 -2
  185. package/packages/apra-fleet-se/apra-pm/agents/doer.md +38 -2
  186. package/packages/apra-fleet-se/apra-pm/agents/harvester.md +12 -9
  187. package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +5 -0
  188. package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +6 -0
  189. package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +5 -0
  190. package/packages/apra-fleet-se/apra-pm/agents/planner.md +5 -0
  191. package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +5 -0
  192. package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +67 -15
  193. package/packages/apra-fleet-se/apra-pm/agents/schemas/deployer-output.json +5 -0
  194. package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-output.json +78 -2
  195. package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-output.json +104 -2
  196. package/packages/apra-fleet-se/apra-pm/skills/pm/cost.md +5 -1
  197. package/packages/apra-fleet-se/apra-pm/skills/pm/index.md +9 -9
  198. package/packages/apra-fleet-se/apra-pm/skills/pm/sprint.md +2 -1
  199. package/packages/apra-fleet-se/bin/cli.mjs +104 -31
  200. package/packages/apra-fleet-se/bin/serve.mjs +46 -8
  201. package/packages/apra-fleet-se/fleet-sprint/abort.mjs +184 -32
  202. package/packages/apra-fleet-se/fleet-sprint/bd-sync-command.mjs +69 -0
  203. package/packages/apra-fleet-se/fleet-sprint/beads-children.mjs +21 -0
  204. package/packages/apra-fleet-se/fleet-sprint/beads-lock-probe.mjs +176 -0
  205. package/packages/apra-fleet-se/fleet-sprint/beads-reachability.mjs +126 -0
  206. package/packages/apra-fleet-se/fleet-sprint/beads-scope.mjs +158 -1
  207. package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +82 -2
  208. package/packages/apra-fleet-se/fleet-sprint/coordination.mjs +23 -6
  209. package/packages/apra-fleet-se/fleet-sprint/decision-notify.mjs +338 -0
  210. package/packages/apra-fleet-se/fleet-sprint/decision-wait.mjs +731 -0
  211. package/packages/apra-fleet-se/fleet-sprint/decisions.mjs +372 -0
  212. package/packages/apra-fleet-se/fleet-sprint/dispatch-role.mjs +44 -11
  213. package/packages/apra-fleet-se/fleet-sprint/docs/README.md +4 -1
  214. package/packages/apra-fleet-se/fleet-sprint/dolt-settle.mjs +9 -3
  215. package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +314 -19
  216. package/packages/apra-fleet-se/fleet-sprint/errors.mjs +72 -4
  217. package/packages/apra-fleet-se/fleet-sprint/git-sync.mjs +7 -1
  218. package/packages/apra-fleet-se/fleet-sprint/git-topology.mjs +112 -1
  219. package/packages/apra-fleet-se/fleet-sprint/guarded-modules.mjs +36 -2
  220. package/packages/apra-fleet-se/fleet-sprint/kb.mjs +736 -101
  221. package/packages/apra-fleet-se/fleet-sprint/member-init-probe.mjs +1 -1
  222. package/packages/apra-fleet-se/fleet-sprint/member-provisioning.mjs +7 -1
  223. package/packages/apra-fleet-se/fleet-sprint/phases/deploy.mjs +49 -2
  224. package/packages/apra-fleet-se/fleet-sprint/phases/develop.mjs +206 -3
  225. package/packages/apra-fleet-se/fleet-sprint/phases/final-review.mjs +61 -3
  226. package/packages/apra-fleet-se/fleet-sprint/phases/harvest.mjs +81 -31
  227. package/packages/apra-fleet-se/fleet-sprint/phases/plan.mjs +7 -3
  228. package/packages/apra-fleet-se/fleet-sprint/phases/publish-pr.mjs +39 -14
  229. package/packages/apra-fleet-se/fleet-sprint/phases/re-review.mjs +17 -1
  230. package/packages/apra-fleet-se/fleet-sprint/phases/review.mjs +18 -3
  231. package/packages/apra-fleet-se/fleet-sprint/pr-body.mjs +14 -1
  232. package/packages/apra-fleet-se/fleet-sprint/prompts.mjs +32 -5
  233. package/packages/apra-fleet-se/fleet-sprint/runner.js +824 -98
  234. package/packages/apra-fleet-se/fleet-sprint/se-os-commands.mjs +4 -2
  235. package/packages/apra-fleet-se/fleet-sprint/se-posix.mjs +54 -1
  236. package/packages/apra-fleet-se/fleet-sprint/se-windows.mjs +29 -2
  237. package/packages/apra-fleet-se/fleet-sprint/set-aside.mjs +288 -0
  238. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +3 -2
  239. package/packages/apra-fleet-se/fleet-sprint/sprint-args.mjs +20 -0
  240. package/packages/apra-fleet-se/fleet-sprint/sprint-report.mjs +21 -0
  241. package/packages/apra-fleet-se/fleet-sprint/sprint-state.mjs +9 -0
  242. package/packages/apra-fleet-se/fleet-sprint/vcs-auth.mjs +605 -32
  243. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/bitbucket.mjs +811 -17
  244. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +89 -1
  245. package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +225 -2
  246. package/packages/apra-fleet-se/fleet-sprint/worklists.mjs +59 -3
  247. package/packages/apra-fleet-se/src/supervisor/api.mjs +148 -8
  248. package/packages/apra-fleet-se/src/supervisor/dashboard.mjs +6 -3
  249. package/packages/apra-fleet-se/src/supervisor/dolt-mutex.mjs +30 -10
  250. package/packages/apra-fleet-se/src/supervisor/fleet-members.mjs +17 -4
  251. package/packages/apra-fleet-se/src/supervisor/history.mjs +8 -1
  252. package/packages/apra-fleet-se/src/supervisor/id-allocator.mjs +92 -2
  253. package/packages/apra-fleet-se/src/supervisor/proxy.mjs +26 -1
  254. package/packages/apra-fleet-se/src/supervisor/server.mjs +151 -8
  255. package/packages/apra-fleet-se/src/supervisor/spawner.mjs +11 -9
  256. package/packages/apra-fleet-se/src/supervisor/watchdog.mjs +7 -1
  257. package/packages/apra-fleet-workflow/package.json +2 -1
  258. package/packages/apra-fleet-workflow/src/viewer/index.mjs +86 -5
  259. package/packages/apra-fleet-workflow/src/viewer/request-guard.mjs +222 -0
  260. package/packages/apra-fleet-workflow/src/workflow/index.mjs +34 -2
  261. package/plugins/claude-code/fleet-status/.claude-plugin/plugin.json +7 -0
  262. package/plugins/claude-code/fleet-status/hooks/hooks.json +1 -0
  263. package/plugins/claude-code/fleet-status/hooks/register.tsx +906 -0
  264. package/plugins/claude-code/fleet-status/types/index.d.ts +88 -0
  265. package/skills/fleet/auth-bitbucket.md +47 -20
  266. package/skills/fleet/onboarding.md +1 -1
  267. package/skills/fleet/skill-matrix.md +3 -3
  268. package/version.json +1 -1
@@ -6,10 +6,12 @@ import { escapeDoubleQuoted, escapeShellArg, escapeBatchMetachars, escapePowerSh
6
6
  import { isWindowsPosixUname } from '../utils/platform.js';
7
7
  import { gitBashCandidates } from './git-bash-candidates.js';
8
8
  import { boundChildEnv, describeBoundedEnv } from './child-env-bound.js';
9
+ import { defaultIsFile, envValue, searchWindowsPath } from './windows-executable.js';
9
10
  import { logWarn } from '../utils/log-helpers.js';
10
- function defaultProbeUname() {
11
+ import { withGoMaxProcsDefault, GO_MAXPROCS_DEFAULT_GITBASH } from './go-concurrency.js';
12
+ function defaultProbeUname(bashPath) {
11
13
  try {
12
- return execFileSync('bash.exe', ['-lc', 'uname -s'], { encoding: 'utf-8', timeout: 5000, windowsHide: true }).toString();
14
+ return execFileSync(bashPath, ['-lc', 'uname -s'], { encoding: 'utf-8', timeout: 5000, windowsHide: true }).toString();
13
15
  }
14
16
  catch {
15
17
  return undefined;
@@ -23,13 +25,15 @@ function defaultProbeUname() {
23
25
  * install location, so the two can never drift apart.
24
26
  *
25
27
  * If none of the known-location candidates exist on disk, this does NOT
26
- * silently trust a bare `bash.exe` resolved off PATH -- Windows also ships
27
- * the WSL launcher under System32/Sysnative/WindowsApps with the identical
28
- * binary name (the same ambiguity isWslLauncherPath/isWindowsPosixUname
29
- * exist to eliminate for the registration probe). Instead it runs `uname -s`
30
- * through whatever bash.exe PATH resolves and only trusts it if that output
31
- * proves a real MSYS/MinGW/Cygwin bash; otherwise it throws, naming every
32
- * candidate path it tried.
28
+ * silently trust a bash.exe found on PATH -- Windows also ships the WSL
29
+ * launcher under System32/Sysnative/WindowsApps with the identical binary
30
+ * name (the same ambiguity isWslLauncherPath/isWindowsPosixUname exist to
31
+ * eliminate for the registration probe). It searches ONLY absolute PATH
32
+ * entries (src/os/windows-executable.ts -- never the cwd, which for
33
+ * LocalStrategy is the member work folder), runs `uname -s` through that
34
+ * absolute path, and returns the absolute path only if the output proves a
35
+ * real MSYS/MinGW/Cygwin bash; otherwise it throws, naming every candidate
36
+ * path it tried. It never returns a bare program name.
33
37
  */
34
38
  export function resolveGitBashPath(deps = {}) {
35
39
  const env = deps.env ?? process.env;
@@ -39,14 +43,21 @@ export function resolveGitBashPath(deps = {}) {
39
43
  if (exists(candidate))
40
44
  return candidate;
41
45
  }
46
+ const { found: pathBash } = searchWindowsPath('bash.exe', {
47
+ pathValue: envValue(env, 'PATH'),
48
+ pathext: envValue(env, 'PATHEXT'),
49
+ isFile: deps.isFile ?? defaultIsFile,
50
+ });
42
51
  const probeUname = deps.probeUname ?? defaultProbeUname;
43
- const unameOutput = probeUname();
44
- if (unameOutput !== undefined && isWindowsPosixUname(unameOutput))
45
- return 'bash.exe';
52
+ const unameOutput = pathBash === undefined ? undefined : probeUname(pathBash);
53
+ if (pathBash !== undefined && unameOutput !== undefined && isWindowsPosixUname(unameOutput))
54
+ return pathBash;
46
55
  throw new Error(`No Git-for-Windows bash.exe found. Tried: ${candidates.join(', ')}` +
47
- (unameOutput === undefined
48
- ? ', and no bash.exe on PATH could be run.'
49
- : `, and the PATH-resolved bash.exe reported "${unameOutput.trim()}" for uname -s (not MSYS/MinGW/Cygwin).`));
56
+ (pathBash === undefined
57
+ ? ', and no bash.exe was found in any absolute PATH entry.'
58
+ : unameOutput === undefined
59
+ ? `, and the PATH bash.exe at ${pathBash} could not be run.`
60
+ : `, and the PATH bash.exe at ${pathBash} reported "${unameOutput.trim()}" for uname -s (not MSYS/MinGW/Cygwin).`));
50
61
  }
51
62
  /**
52
63
  * OS commands for a Windows member whose registered shell is Git-for-Windows
@@ -245,7 +256,20 @@ export class WindowsGitBashCommands extends LinuxCommands {
245
256
  const bounded = boundChildEnv(env, { sep: process.platform === 'win32' ? ';' : ':' });
246
257
  if (bounded.report.dropped.length || bounded.report.overCap)
247
258
  logWarn('clean_env', describeBoundedEnv(bounded.report));
248
- return { command, env: bounded.env, shell: resolveGitBashPath() };
259
+ // GOMAXPROCS default for bd/dolt on Windows (only when unset) -- see go-concurrency.ts.
260
+ return { command, env: withGoMaxProcsDefault(bounded.env), shell: resolveGitBashPath() };
261
+ }
262
+ // --- Remote agent launch / execute_command (GOMAXPROCS default) ---
263
+ //
264
+ // A remote Git Bash member's env is only known to its own shell, so the
265
+ // GOMAXPROCS default (only when the member has none) is a Git Bash statement
266
+ // prefixed to the launch and execute_command wrappers -- see
267
+ // go-concurrency.ts. LinuxCommands (linux/macOS) is unchanged.
268
+ buildAgentPromptCommand(provider, opts) {
269
+ return `${GO_MAXPROCS_DEFAULT_GITBASH}${super.buildAgentPromptCommand(provider, opts)}`;
270
+ }
271
+ wrapInWorkFolder(folder, command) {
272
+ return `${GO_MAXPROCS_DEFAULT_GITBASH}${super.wrapInWorkFolder(folder, command)}`;
249
273
  }
250
274
  // --- Process management ---
251
275
  killPid(pid) {
@@ -80,6 +80,8 @@ export declare class WindowsCommands implements OsCommands {
80
80
  wrapPidCapture(command: string): string;
81
81
  gitCurrentBranch(folder: string): string;
82
82
  gitRemoteOrigin(folder: string): string;
83
+ gitLsRemoteNonInteractive(url: string): string;
84
+ httpGetStatusWithBearer(url: string, token: string): string;
83
85
  killPid(pid: number): string;
84
86
  gpuProcessCheck(): string;
85
87
  gpuUtilization(): string;
@@ -1,10 +1,12 @@
1
1
  import { defaultWindowsPidWrapper } from './windows-wrapper.js';
2
2
  export { defaultWindowsPidWrapper as pidWrapWindows };
3
3
  import { execFileSync } from 'node:child_process';
4
- import { escapeWindowsArg, sanitizeSessionId } from './os-commands.js';
4
+ import { escapeWindowsArg, sanitizeSessionId, GIT_LS_REMOTE_OK_MARKER } from './os-commands.js';
5
5
  import { escapeBatchMetachars, escapePowerShellArgInner } from '../utils/shell-escape.js';
6
6
  import { boundChildEnv, describeBoundedEnv } from './child-env-bound.js';
7
7
  import { logWarn } from '../utils/log-helpers.js';
8
+ import { withGoMaxProcsDefault, GO_MAXPROCS_DEFAULT_PWSH } from './go-concurrency.js';
9
+ import { windowsExecutable } from './windows-executable.js';
8
10
  /**
9
11
  * Wrap a PowerShell script as a base64 `-EncodedCommand` invocation.
10
12
  * Use this for ANY Windows member-bound command instead of sending a raw
@@ -90,9 +92,12 @@ export class WindowsCommands {
90
92
  // script is ~2300. A blocking execSync with no timeout then freezes the
91
93
  // whole fleet server. -NoProfile keeps profile output out of the JSON.
92
94
  const encoded = Buffer.from(script, 'utf16le').toString('base64');
95
+ // Absolute path, resolved outside the try so a missing PowerShell surfaces
96
+ // its own E-WINDOWS-EXECUTABLE-NOT-FOUND error (see windows-executable.ts).
97
+ const powershell = windowsExecutable('powershell.exe');
93
98
  let result;
94
99
  try {
95
- result = execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], { encoding: 'utf-8', windowsHide: true, timeout: CLEAN_ENV_TIMEOUT_MS, stdio: ['ignore', 'pipe', 'pipe'] });
100
+ result = execFileSync(powershell, ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], { encoding: 'utf-8', windowsHide: true, timeout: CLEAN_ENV_TIMEOUT_MS, stdio: ['ignore', 'pipe', 'pipe'] });
96
101
  }
97
102
  catch (err) {
98
103
  const e = err;
@@ -106,7 +111,8 @@ export class WindowsCommands {
106
111
  const { env, report } = boundChildEnv(JSON.parse(result.trim()));
107
112
  if (report.dropped.length || report.overCap)
108
113
  logWarn('clean_env', describeBoundedEnv(report));
109
- this.cachedEnv = env;
114
+ // GOMAXPROCS default for bd/dolt on Windows (only when unset) -- see go-concurrency.ts.
115
+ this.cachedEnv = withGoMaxProcsDefault(env);
110
116
  return this.cachedEnv;
111
117
  }
112
118
  // --- Resources ---
@@ -162,7 +168,9 @@ export class WindowsCommands {
162
168
  instruction = `${nameFlag}${instruction}`;
163
169
  }
164
170
  // Setup: working directory + PATH so the CLI executable is resolvable
165
- const setupCmd = `Set-Location "${escapedFolder}"; ${CLI_PATH}`;
171
+ // GOMAXPROCS default (only when the member has none) for bd/dolt the agent
172
+ // runs -- see go-concurrency.ts.
173
+ const setupCmd = `Set-Location "${escapedFolder}"; ${GO_MAXPROCS_DEFAULT_PWSH}${CLI_PATH}`;
166
174
  // Executable extracted from provider (e.g. "claude" from "claude <args>")
167
175
  const filePath = provider.cliCommand('').trim();
168
176
  // Build argument list (everything that follows the executable)
@@ -385,11 +393,13 @@ $merged | ConvertTo-Json -Depth 99 | Set-Content -Path $p -NoNewline;
385
393
  }
386
394
  // --- Local exec ---
387
395
  cleanExec(command) {
388
- return { command, env: this.getCleanEnv(), shell: 'powershell.exe' };
396
+ // An ABSOLUTE shell path: LocalStrategy spawns this with cwd = the member
397
+ // work folder, where a bare 'powershell.exe' would be searched first.
398
+ return { command, env: this.getCleanEnv(), shell: windowsExecutable('powershell.exe') };
389
399
  }
390
400
  // --- Shell ---
391
401
  wrapInWorkFolder(folder, command) {
392
- return `Set-Location "${escapeWindowsArg(folder)}"; $env:Path = "$env:Path;${FLEET_BIN_PATH_WINDOWS}"; ${command}`;
402
+ return `Set-Location "${escapeWindowsArg(folder)}"; ${GO_MAXPROCS_DEFAULT_PWSH}$env:Path = "$env:Path;${FLEET_BIN_PATH_WINDOWS}"; ${command}`;
393
403
  }
394
404
  wrapPidCapture(command) {
395
405
  return `Write-Output "FLEET_PID:$pid"; ${command}`;
@@ -402,6 +412,27 @@ $merged | ConvertTo-Json -Depth 99 | Set-Content -Path $p -NoNewline;
402
412
  const f = escapeWindowsArg(folder);
403
413
  return `try { $u = git -C "${f}" remote get-url origin 2>$null; if (-not $u) { $u = git -C "${f}" config --get remote.origin.url 2>$null }; if ($u) { Write-Output $u } } catch {}`;
404
414
  }
415
+ gitLsRemoteNonInteractive(url) {
416
+ const u = escapePowerShellArgInner(url);
417
+ return [
418
+ `$env:GIT_TERMINAL_PROMPT = '0'`,
419
+ `$env:GCM_INTERACTIVE = 'never'`,
420
+ `git ls-remote '${u}' HEAD`,
421
+ `if ($LASTEXITCODE -eq 0) { Write-Output '${GIT_LS_REMOTE_OK_MARKER}' } else { exit $LASTEXITCODE }`,
422
+ ].join('; ');
423
+ }
424
+ httpGetStatusWithBearer(url, token) {
425
+ const u = escapePowerShellArgInner(url);
426
+ const t = escapePowerShellArgInner(token);
427
+ // Invoke-WebRequest runs in-process, so the token is on no child process
428
+ // argv (it is still on the powershell.exe command line that runs this
429
+ // script, see os-commands.ts). A non-2xx answer throws; its status is read off the
430
+ // exception's response. No response at all prints a non-numeric marker.
431
+ return [
432
+ `$ProgressPreference = 'SilentlyContinue'`,
433
+ `try { $r = Invoke-WebRequest -UseBasicParsing -Method Get -Uri '${u}' -Headers @{ Authorization = 'Bearer ${t}' }; Write-Output ([int]$r.StatusCode) } catch { $resp = $_.Exception.Response; if ($resp) { Write-Output ([int]$resp.StatusCode) } else { Write-Output 'FLEET_HTTP_NO_RESPONSE' } }`,
434
+ ].join('; ');
435
+ }
405
436
  // --- Process management ---
406
437
  killPid(pid) {
407
438
  return `taskkill /F /T /PID ${pid}`;
package/dist/paths.d.ts CHANGED
@@ -6,6 +6,10 @@ export declare const DEFAULT_PORT: number;
6
6
  /** Name of the member-install marker file inside an install's data dir
7
7
  * (written by `install --member`, see src/cli/install-guard.ts). */
8
8
  export declare const MEMBER_INSTALL_MARKER_FILE = "member-install.json";
9
+ /** Name of the full-install port record inside an install's data dir
10
+ * (written by a non-member `install`, see src/cli/install-guard.ts). Kept
11
+ * apart from the member marker, whose presence means member mode elsewhere. */
12
+ export declare const FULL_INSTALL_PORT_FILE = "full-install.json";
9
13
  /** A usable TCP port number, or undefined. */
10
14
  export declare function validPort(v: unknown): number | undefined;
11
15
  /**
@@ -14,10 +18,15 @@ export declare function validPort(v: unknown): number | undefined;
14
18
  * at call time (never cached): install writes the marker partway through a run.
15
19
  */
16
20
  export declare function recordedMemberInstallPort(dataDir?: string): number | undefined;
21
+ /**
22
+ * The port the last full install in `dataDir` recorded (APRA_FLEET_PORT at
23
+ * install time), or undefined when none/unreadable. Call-time read.
24
+ */
25
+ export declare function recordedFullInstallPort(dataDir?: string): number | undefined;
17
26
  /**
18
27
  * The port THIS process's server binds (and start/install check): an explicit
19
28
  * APRA_FLEET_PORT, else the port this data dir's member install recorded,
20
- * else the built-in default. Resolved at call time, so a service launch with
29
+ * else the port its last full install recorded, else the built-in default. Resolved at call time, so a service launch with
21
30
  * no environment of its own still listens on the member install's port.
22
31
  */
23
32
  export declare function resolveServerPort(): number;
package/dist/paths.js CHANGED
@@ -10,6 +10,10 @@ export const DEFAULT_PORT = parseInt(process.env.APRA_FLEET_PORT ?? '', 10) || R
10
10
  /** Name of the member-install marker file inside an install's data dir
11
11
  * (written by `install --member`, see src/cli/install-guard.ts). */
12
12
  export const MEMBER_INSTALL_MARKER_FILE = 'member-install.json';
13
+ /** Name of the full-install port record inside an install's data dir
14
+ * (written by a non-member `install`, see src/cli/install-guard.ts). Kept
15
+ * apart from the member marker, whose presence means member mode elsewhere. */
16
+ export const FULL_INSTALL_PORT_FILE = 'full-install.json';
13
17
  /** A usable TCP port number, or undefined. */
14
18
  export function validPort(v) {
15
19
  const n = typeof v === 'string' && /^\d+$/.test(v.trim()) ? Number(v.trim()) : v;
@@ -29,14 +33,27 @@ export function recordedMemberInstallPort(dataDir = process.env.APRA_FLEET_DATA_
29
33
  return undefined;
30
34
  }
31
35
  }
36
+ /**
37
+ * The port the last full install in `dataDir` recorded (APRA_FLEET_PORT at
38
+ * install time), or undefined when none/unreadable. Call-time read.
39
+ */
40
+ export function recordedFullInstallPort(dataDir = process.env.APRA_FLEET_DATA_DIR ?? path.join(os.homedir(), '.apra-fleet', 'data')) {
41
+ try {
42
+ const raw = fs.readFileSync(path.join(dataDir, FULL_INSTALL_PORT_FILE), 'utf8');
43
+ return validPort(JSON.parse(raw).port);
44
+ }
45
+ catch {
46
+ return undefined;
47
+ }
48
+ }
32
49
  /**
33
50
  * The port THIS process's server binds (and start/install check): an explicit
34
51
  * APRA_FLEET_PORT, else the port this data dir's member install recorded,
35
- * else the built-in default. Resolved at call time, so a service launch with
52
+ * else the port its last full install recorded, else the built-in default. Resolved at call time, so a service launch with
36
53
  * no environment of its own still listens on the member install's port.
37
54
  */
38
55
  export function resolveServerPort() {
39
- return validPort(process.env.APRA_FLEET_PORT ?? '') ?? recordedMemberInstallPort() ?? RAW_DEFAULT_PORT;
56
+ return validPort(process.env.APRA_FLEET_PORT ?? '') ?? recordedMemberInstallPort() ?? recordedFullInstallPort() ?? RAW_DEFAULT_PORT;
40
57
  }
41
58
  /**
42
59
  * True when this process invocation targets a non-default fleet instance --
@@ -17,12 +17,18 @@ export interface NewProjectScriptOptions {
17
17
  /** Extra NON-SECRET environment for the agy process. The script text is part of
18
18
  * the member command line -- credentials go through stageAuthEnv instead. */
19
19
  env?: Record<string, string>;
20
- /** Test seam: run this executable (plus leading args) instead of `agy`. */
20
+ /** Test seam: run this executable (plus leading args) instead of `agy`.
21
+ * AGY_NODE_SELF means the node binary running the member-side script. */
21
22
  agyCommand?: {
22
23
  file: string;
23
24
  args: string[];
24
25
  };
25
26
  }
27
+ /** agyCommand.file sentinel: spawn the member-side node itself
28
+ * (process.execPath evaluated ON THE MEMBER). Keeps host paths out of the
29
+ * member command line -- a host absolute path is meaningless on a remote
30
+ * member and is environment-derived text in a shell command. */
31
+ export declare const AGY_NODE_SELF = "<node-self>";
26
32
  /**
27
33
  * Member-side node script: list ~/.gemini/config/projects, run
28
34
  * `agy --new-project` (spawned directly, no shell) in the work folder with a
@@ -72,6 +72,11 @@ if (!fs.existsSync(f)) {
72
72
  }
73
73
  console.log(${JSON.stringify(PROBE_MARKER)} + JSON.stringify({ state }));`;
74
74
  }
75
+ /** agyCommand.file sentinel: spawn the member-side node itself
76
+ * (process.execPath evaluated ON THE MEMBER). Keeps host paths out of the
77
+ * member command line -- a host absolute path is meaningless on a remote
78
+ * member and is environment-derived text in a shell command. */
79
+ export const AGY_NODE_SELF = '<node-self>';
75
80
  /**
76
81
  * Member-side node script: list ~/.gemini/config/projects, run
77
82
  * `agy --new-project` (spawned directly, no shell) in the work folder with a
@@ -109,7 +114,7 @@ const extra = [path.join(home, '.local', 'bin')];
109
114
  if (process.platform === 'win32' && env.LOCALAPPDATA) extra.push(path.join(env.LOCALAPPDATA, 'agy', 'bin'));
110
115
  env[pathKey] = extra.join(path.delimiter) + path.delimiter + (env[pathKey] || '');
111
116
  const args = ${JSON.stringify(args)}.map(function (a) { return a === '__LOG_FILE__' ? logFile : a; });
112
- const r = cp.spawnSync(${JSON.stringify(file)}, args, { cwd: ${JSON.stringify(opts.workFolder)}, env: env, encoding: 'utf8', timeout: ${NEW_PROJECT_SPAWN_TIMEOUT_MS}, windowsHide: true });
117
+ const r = cp.spawnSync(${file === AGY_NODE_SELF ? 'process.execPath' : JSON.stringify(file)}, args, { cwd: ${JSON.stringify(opts.workFolder)}, env: env, encoding: 'utf8', timeout: ${NEW_PROJECT_SPAWN_TIMEOUT_MS}, windowsHide: true });
113
118
  const created = list().filter(function (f) { return !before.has(f); }).map(function (f) { return f.slice(0, -5); });
114
119
  const logIds = [];
115
120
  try {
@@ -287,7 +292,7 @@ export async function provisionAgyProject(agent, exec = defaultExec(agent), agyC
287
292
  // ~/.gemini and run a model turn. Without a test override the stand-in
288
293
  // exits 97 and provisioning fails ("agy exited 97").
289
294
  if (!agyCommand && process.env.NODE_ENV === 'test') {
290
- agyCommand = { file: process.execPath, args: ['-e', 'process.exit(97)', '--'] };
295
+ agyCommand = { file: AGY_NODE_SELF, args: ['-e', 'process.exit(97)', '--'] };
291
296
  }
292
297
  const model = getModelOverride('agy', 'cheap') ?? AGY_MODEL_FOR_TIER.cheap;
293
298
  // Stored auth env vars reach agy through the staged env file the command
@@ -61,6 +61,24 @@ export declare function collectOobConfirm(credentialName: string, _opts?: {
61
61
  confirmed: boolean;
62
62
  terminalUnavailable: boolean;
63
63
  }>;
64
+ /**
65
+ * The manual-entry instruction shown when no terminal (and no browser UI) can
66
+ * collect a credential. ASCII only.
67
+ *
68
+ * Credential-collection modes name the credential by the caller's prompt
69
+ * label (the `--prompt` value in `extraArgs`, e.g. a provider's
70
+ * missingCredential.promptFor text) and tell the operator to store it under
71
+ * a secret NAME of their choosing, then pass {{secret.NAME}}. The member name
72
+ * is never offered as a secret name: `secret --set <member>` stored the value
73
+ * under the member's name, which no credential field references.
74
+ *
75
+ * Confirm mode keeps `secret --confirm <name>`: there `memberName` IS the
76
+ * credential name being confirmed (see collectOobConfirm).
77
+ */
78
+ export declare function buildHeadlessFallback(memberName: string, reason: string, context?: {
79
+ command?: string;
80
+ onMember?: string;
81
+ }, extraArgs?: string[]): string;
64
82
  /**
65
83
  * Returns true when a graphical display is available on Linux/BSD.
66
84
  * Checks $DISPLAY (X11) and $WAYLAND_DISPLAY (Wayland).
@@ -7,6 +7,7 @@ import { spawn, execSync } from 'node:child_process';
7
7
  import { FLEET_DIR } from '../paths.js';
8
8
  import { encryptPassword } from '../utils/crypto.js';
9
9
  import { logError } from '../utils/log-helpers.js';
10
+ import { windowsExecutable } from '../os/windows-executable.js';
10
11
  import { escapeShellArg, escapeAppleScriptString, quoteWindowsArgv } from '../utils/shell-escape.js';
11
12
  import { OOB_TIMEOUT_MS } from '../utils/oob-timeout.js';
12
13
  import { launchAuthWeb } from './auth-web.js';
@@ -342,7 +343,11 @@ async function collectOobInput(mode, memberName, toolName, _opts) {
342
343
  }
343
344
  }
344
345
  const manualMsg = result.slice('fallback:'.length);
345
- resolve({ fallback: `🔐 ${manualMsg}\n\nOnce the user has entered the ${inputType}, call ${toolName} again with the same parameters.` });
346
+ resolve({
347
+ fallback: mode === 'confirm'
348
+ ? `${manualMsg}\n\nOnce the user has entered the ${inputType}, call ${toolName} again with the same parameters.`
349
+ : `${manualMsg}\n\nThen call ${toolName} again with {{secret.NAME}} in place of the missing ${inputType}.`,
350
+ });
346
351
  }
347
352
  });
348
353
  const raceResult = await Promise.race([passwordPromise, cancellationPromise]);
@@ -477,7 +482,21 @@ function getAuthCommand(memberName, extraArgs) {
477
482
  const indexJs = path.resolve(path.dirname(new URL(import.meta.url).pathname), '..', 'index.js');
478
483
  return { cmd: process.argv[0], args: [indexJs, ...cmdArgs] };
479
484
  }
480
- function buildHeadlessFallback(memberName, reason, context, extraArgs) {
485
+ /**
486
+ * The manual-entry instruction shown when no terminal (and no browser UI) can
487
+ * collect a credential. ASCII only.
488
+ *
489
+ * Credential-collection modes name the credential by the caller's prompt
490
+ * label (the `--prompt` value in `extraArgs`, e.g. a provider's
491
+ * missingCredential.promptFor text) and tell the operator to store it under
492
+ * a secret NAME of their choosing, then pass {{secret.NAME}}. The member name
493
+ * is never offered as a secret name: `secret --set <member>` stored the value
494
+ * under the member's name, which no credential field references.
495
+ *
496
+ * Confirm mode keeps `secret --confirm <name>`: there `memberName` IS the
497
+ * credential name being confirmed (see collectOobConfirm).
498
+ */
499
+ export function buildHeadlessFallback(memberName, reason, context, extraArgs) {
481
500
  const isConfirm = extraArgs?.includes('--confirm') ?? false;
482
501
  let contextLines = '';
483
502
  if (context?.onMember && context?.command) {
@@ -489,7 +508,14 @@ function buildHeadlessFallback(memberName, reason, context, extraArgs) {
489
508
  if (isConfirm) {
490
509
  return `fallback:${reason}${contextLines}\n\nRun this in a separate terminal to confirm:\n ! apra-fleet secret --confirm ${memberName}\n\nAlternatively, pre-store the value with credential_store_set and reference it as {{secret.NAME}} in the credential field.`;
491
510
  }
492
- return `fallback:${reason}${contextLines}\n\nRun this in a separate terminal to provide the credential:\n ! apra-fleet secret --set ${memberName}\n\nAlternatively, pre-store the value with credential_store_set and reference it as {{secret.NAME}} in the credential field.`;
511
+ const promptIdx = extraArgs?.indexOf('--prompt') ?? -1;
512
+ const promptLabel = extraArgs && promptIdx !== -1 && promptIdx + 1 < extraArgs.length
513
+ ? extraArgs[promptIdx + 1]
514
+ : (extraArgs?.includes('--api-key') ? `Enter API key for ${memberName}` : `Enter password for ${memberName}`);
515
+ return `fallback:${reason}${contextLines}\n\nNo terminal is available to ask for this credential: "${promptLabel}".`
516
+ + `\nStore it as a named fleet secret (choose any NAME, e.g. one per credential) in a separate terminal:`
517
+ + `\n ! apra-fleet secret --set NAME --persist`
518
+ + `\n(or use credential_store_set), then pass {{secret.NAME}} in the credential field when calling the tool again.`;
493
519
  }
494
520
  /**
495
521
  * Returns true when a graphical display is available on Linux/BSD.
@@ -611,7 +637,7 @@ const WINDOWS_AUTH_LAUNCHER_PS = [
611
637
  export function buildWindowsAuthLaunch(fullArgs) {
612
638
  const [exe, ...rest] = fullArgs;
613
639
  return {
614
- file: 'powershell',
640
+ file: windowsExecutable('powershell.exe'),
615
641
  args: ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(WINDOWS_AUTH_LAUNCHER_PS, 'utf16le').toString('base64')],
616
642
  env: {
617
643
  APRA_FLEET_OOB_EXE: exe,
@@ -36,6 +36,39 @@ export declare function credentialResolve(name: string, callingMember?: string):
36
36
  } | {
37
37
  expired: string;
38
38
  } | null;
39
+ export type ServerSecretMeta = Pick<CredentialMeta, 'name' | 'scope' | 'created_at' | 'expiresAt'>;
40
+ export type ServerSecretLookup = {
41
+ status: 'ok';
42
+ value: string;
43
+ meta: ServerSecretMeta;
44
+ } | {
45
+ status: 'missing';
46
+ } | {
47
+ status: 'expired';
48
+ expiresAt: string;
49
+ meta: ServerSecretMeta;
50
+ };
51
+ export type ServerSecretStatus = {
52
+ status: 'ok';
53
+ meta: ServerSecretMeta;
54
+ } | {
55
+ status: 'missing';
56
+ } | {
57
+ status: 'expired';
58
+ expiresAt: string;
59
+ meta: ServerSecretMeta;
60
+ };
61
+ /**
62
+ * Metadata-only server-side lookup (no decryption), for status reporting.
63
+ * Persistent wins over session. allowedMembers is not checked and nothing is
64
+ * deleted, so an expired record stays visible as expired.
65
+ */
66
+ export declare function lookupServerSecretMeta(name: string): ServerSecretStatus;
67
+ /**
68
+ * Server-side named-secret lookup for fleet-server callers (not a member
69
+ * command): ignores allowedMembers, never deletes a record, never logs the value.
70
+ */
71
+ export declare function lookupServerSecret(name: string): ServerSecretLookup;
39
72
  export interface CredentialUpdatePatch {
40
73
  members?: string;
41
74
  expiresAt?: number | null;
@@ -56,8 +56,41 @@ function saveCredentialFile(file) {
56
56
  if (!fs.existsSync(dataDir)) {
57
57
  fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
58
58
  }
59
- fs.writeFileSync(credentialsPath, JSON.stringify(file, null, 2), { mode: 0o600 });
60
- enforceOwnerOnly(credentialsPath);
59
+ // Write a temp file next to credentials.json, then rename it over: a
60
+ // concurrent reader in another process sees either the old or the new
61
+ // file, never a truncated one.
62
+ const tmpPath = `${credentialsPath}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`;
63
+ try {
64
+ fs.writeFileSync(tmpPath, JSON.stringify(file, null, 2), { mode: 0o600 });
65
+ enforceOwnerOnly(tmpPath);
66
+ renameWithRetry(tmpPath, credentialsPath);
67
+ }
68
+ catch (err) {
69
+ try {
70
+ fs.unlinkSync(tmpPath);
71
+ }
72
+ catch { /* temp may not exist */ }
73
+ throw err;
74
+ }
75
+ }
76
+ const RENAME_RETRIES = 10;
77
+ const RENAME_RETRY_DELAY_MS = 20;
78
+ // On Windows, renaming over a file another process has open can fail
79
+ // transiently (EPERM / EACCES / EBUSY).
80
+ function renameWithRetry(from, to) {
81
+ for (let attempt = 0;; attempt++) {
82
+ try {
83
+ fs.renameSync(from, to);
84
+ return;
85
+ }
86
+ catch (err) {
87
+ const code = err.code;
88
+ const transient = code === 'EPERM' || code === 'EACCES' || code === 'EBUSY';
89
+ if (!transient || attempt >= RENAME_RETRIES)
90
+ throw err;
91
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, RENAME_RETRY_DELAY_MS);
92
+ }
93
+ }
61
94
  }
62
95
  // ---------------------------------------------------------------------------
63
96
  // Public API
@@ -200,6 +233,50 @@ export function credentialResolve(name, callingMember) {
200
233
  }
201
234
  return null;
202
235
  }
236
+ function isExpired(expiresAt) {
237
+ return !!expiresAt && Date.now() > new Date(expiresAt).getTime();
238
+ }
239
+ /**
240
+ * Metadata-only server-side lookup (no decryption), for status reporting.
241
+ * Persistent wins over session. allowedMembers is not checked and nothing is
242
+ * deleted, so an expired record stays visible as expired.
243
+ */
244
+ export function lookupServerSecretMeta(name) {
245
+ const persistent = loadCredentialFile().credentials[name];
246
+ const rec = persistent ?? sessionStore.get(name);
247
+ if (!rec)
248
+ return { status: 'missing' };
249
+ const meta = {
250
+ name: rec.name,
251
+ scope: persistent ? 'persistent' : 'session',
252
+ created_at: rec.created_at,
253
+ expiresAt: rec.expiresAt,
254
+ };
255
+ if (isExpired(rec.expiresAt))
256
+ return { status: 'expired', expiresAt: rec.expiresAt, meta };
257
+ return { status: 'ok', meta };
258
+ }
259
+ /**
260
+ * Server-side named-secret lookup for fleet-server callers (not a member
261
+ * command): ignores allowedMembers, never deletes a record, never logs the value.
262
+ */
263
+ export function lookupServerSecret(name) {
264
+ const found = lookupServerSecretMeta(name);
265
+ if (found.status !== 'ok')
266
+ return found;
267
+ const persistent = loadCredentialFile().credentials[name];
268
+ let value;
269
+ if (persistent) {
270
+ value = decryptPassword(persistent.encryptedValue);
271
+ }
272
+ else {
273
+ const session = sessionStore.get(name);
274
+ if (!session)
275
+ return { status: 'missing' };
276
+ value = sessionDecrypt(session.encryptedValue);
277
+ }
278
+ return { status: 'ok', value, meta: found.meta };
279
+ }
203
280
  function membersToAllowed(members) {
204
281
  return members === '*' ? '*' : members.split(',').map(m => m.trim()).filter(Boolean);
205
282
  }
@@ -12,7 +12,22 @@ interface Session {
12
12
  /** Identity that opened this session (see SessionOwner). Every later
13
13
  * GET/DELETE/POST on the session id must come from the same identity. */
14
14
  owner: SessionOwner;
15
+ /** Client name from initialize, for log lines. */
16
+ client: string;
17
+ /** Last time a request on this session started or ended (ms, `now()`). */
18
+ lastActivity: number;
19
+ /** Requests on this session whose response is still open: an SSE GET
20
+ * stream, or a POST whose response streams a long tool call. A session
21
+ * with any open request is never idle-evicted. */
22
+ openRequests: number;
23
+ /** Releases everything the session holds (map entry, McpServer, session
24
+ * registry entry). Idempotent; shared by DELETE and idle eviction. */
25
+ release: (reason: 'closed' | 'idle') => void;
15
26
  }
27
+ /** Idle bound after which a session with no open request is evicted. */
28
+ export declare const DEFAULT_SESSION_IDLE_MS: number;
29
+ /** Open-session count that triggers a one-time WARNING log line. */
30
+ export declare const DEFAULT_SESSION_COUNT_WARN = 500;
16
31
  /**
17
32
  * The identity a /mcp request carries, derived the same way at initialize and
18
33
  * on every later request on that session:
@@ -53,6 +68,18 @@ export interface HttpTransportOptions {
53
68
  /** The member access secret file a `?member=` request is checked against
54
69
  * (default: <data dir>/member-access.key; created when missing). */
55
70
  memberSecretPath?: string;
71
+ /** A session with no open request and no request for this long is evicted
72
+ * (default APRA_FLEET_SESSION_IDLE_MS, else 30 min). A client that drops
73
+ * its session without an HTTP DELETE would otherwise hold its McpServer
74
+ * forever. */
75
+ sessionIdleMs?: number;
76
+ /** How often the idle sweep runs (default 60 s). */
77
+ idleSweepIntervalMs?: number;
78
+ /** Open-session count that logs a WARNING (default
79
+ * APRA_FLEET_SESSION_COUNT_WARN, else 500). */
80
+ sessionCountWarn?: number;
81
+ /** Clock, injectable for tests (default Date.now). */
82
+ now?: () => number;
56
83
  }
57
84
  /** Thrown by createHttpTransport when the configured (non-zero) port is already bound. */
58
85
  export declare class PortInUseError extends Error {
@@ -66,6 +93,8 @@ export interface HttpTransportHandle {
66
93
  port: number;
67
94
  url: string;
68
95
  sessions: Map<string, Session>;
96
+ /** Runs one idle-eviction pass now; returns how many sessions it evicted. */
97
+ sweepIdleSessions(): number;
69
98
  close(): Promise<void>;
70
99
  }
71
100
  export declare function isFetchBlockedPort(port: number): boolean;