@stigmer/cli 0.1.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (270) hide show
  1. package/auth/browser.d.ts +7 -0
  2. package/auth/browser.d.ts.map +1 -0
  3. package/auth/browser.js +49 -0
  4. package/auth/browser.js.map +1 -0
  5. package/auth/callback-server.d.ts +8 -3
  6. package/auth/callback-server.d.ts.map +1 -1
  7. package/auth/callback-server.js +53 -19
  8. package/auth/callback-server.js.map +1 -1
  9. package/auth/device.d.ts +23 -0
  10. package/auth/device.d.ts.map +1 -0
  11. package/auth/device.js +119 -0
  12. package/auth/device.js.map +1 -0
  13. package/auth/index.d.ts +4 -3
  14. package/auth/index.d.ts.map +1 -1
  15. package/auth/index.js +4 -3
  16. package/auth/index.js.map +1 -1
  17. package/auth/login.d.ts +49 -1
  18. package/auth/login.d.ts.map +1 -1
  19. package/auth/login.js +161 -51
  20. package/auth/login.js.map +1 -1
  21. package/auth/oidc.d.ts +67 -0
  22. package/auth/oidc.d.ts.map +1 -0
  23. package/auth/oidc.js +213 -0
  24. package/auth/oidc.js.map +1 -0
  25. package/auth/token.d.ts +17 -23
  26. package/auth/token.d.ts.map +1 -1
  27. package/auth/token.js +51 -60
  28. package/auth/token.js.map +1 -1
  29. package/client/client.d.ts.map +1 -1
  30. package/client/client.js +4 -1
  31. package/client/client.js.map +1 -1
  32. package/client/current-organization.d.ts +5 -0
  33. package/client/current-organization.d.ts.map +1 -0
  34. package/client/current-organization.js +15 -0
  35. package/client/current-organization.js.map +1 -0
  36. package/commands/apikey/index.d.ts +16 -1
  37. package/commands/apikey/index.d.ts.map +1 -1
  38. package/commands/apikey/index.js +81 -0
  39. package/commands/apikey/index.js.map +1 -1
  40. package/commands/app-handover.d.ts +17 -0
  41. package/commands/app-handover.d.ts.map +1 -0
  42. package/commands/app-handover.js +168 -0
  43. package/commands/app-handover.js.map +1 -0
  44. package/commands/auth/index.d.ts.map +1 -1
  45. package/commands/auth/index.js +15 -9
  46. package/commands/auth/index.js.map +1 -1
  47. package/commands/auth/login.d.ts +7 -2
  48. package/commands/auth/login.d.ts.map +1 -1
  49. package/commands/auth/login.js +26 -23
  50. package/commands/auth/login.js.map +1 -1
  51. package/commands/auth/whoami.d.ts +15 -0
  52. package/commands/auth/whoami.d.ts.map +1 -1
  53. package/commands/auth/whoami.js +72 -2
  54. package/commands/auth/whoami.js.map +1 -1
  55. package/commands/coding-agent.d.ts +5 -0
  56. package/commands/coding-agent.d.ts.map +1 -0
  57. package/commands/coding-agent.js +30 -0
  58. package/commands/coding-agent.js.map +1 -0
  59. package/commands/config/backend.js +20 -6
  60. package/commands/config/backend.js.map +1 -1
  61. package/commands/docs/index.d.ts +9 -0
  62. package/commands/docs/index.d.ts.map +1 -0
  63. package/commands/docs/index.js +64 -0
  64. package/commands/docs/index.js.map +1 -0
  65. package/commands/embedding.d.ts +28 -0
  66. package/commands/embedding.d.ts.map +1 -0
  67. package/commands/embedding.js +170 -0
  68. package/commands/embedding.js.map +1 -0
  69. package/commands/example.d.ts +20 -0
  70. package/commands/example.d.ts.map +1 -0
  71. package/commands/example.js +136 -0
  72. package/commands/example.js.map +1 -0
  73. package/commands/help.d.ts.map +1 -1
  74. package/commands/help.js +19 -3
  75. package/commands/help.js.map +1 -1
  76. package/commands/list.d.ts.map +1 -1
  77. package/commands/list.js +13 -1
  78. package/commands/list.js.map +1 -1
  79. package/commands/load-test/burst.d.ts +64 -0
  80. package/commands/load-test/burst.d.ts.map +1 -0
  81. package/commands/load-test/burst.js +202 -0
  82. package/commands/load-test/burst.js.map +1 -0
  83. package/commands/load-test/index.d.ts +37 -0
  84. package/commands/load-test/index.d.ts.map +1 -0
  85. package/commands/load-test/index.js +154 -0
  86. package/commands/load-test/index.js.map +1 -0
  87. package/commands/load-test/report.d.ts +98 -0
  88. package/commands/load-test/report.d.ts.map +1 -0
  89. package/commands/load-test/report.js +210 -0
  90. package/commands/load-test/report.js.map +1 -0
  91. package/commands/mcp-server.d.ts +3 -3
  92. package/commands/mcp-server.d.ts.map +1 -1
  93. package/commands/mcp-server.js +16 -7
  94. package/commands/mcp-server.js.map +1 -1
  95. package/commands/provider-key/index.d.ts.map +1 -1
  96. package/commands/provider-key/index.js +2 -2
  97. package/commands/provider-key/index.js.map +1 -1
  98. package/commands/setup.d.ts +17 -0
  99. package/commands/setup.d.ts.map +1 -1
  100. package/commands/setup.js +71 -1
  101. package/commands/setup.js.map +1 -1
  102. package/commands/status.d.ts.map +1 -1
  103. package/commands/status.js +4 -3
  104. package/commands/status.js.map +1 -1
  105. package/commands/up.d.ts.map +1 -1
  106. package/commands/up.js +67 -9
  107. package/commands/up.js.map +1 -1
  108. package/commands/usage.d.ts +15 -0
  109. package/commands/usage.d.ts.map +1 -1
  110. package/commands/usage.js +52 -2
  111. package/commands/usage.js.map +1 -1
  112. package/config/config.d.ts +14 -7
  113. package/config/config.d.ts.map +1 -1
  114. package/config/config.js +5 -1
  115. package/config/config.js.map +1 -1
  116. package/config/index.d.ts +2 -2
  117. package/config/index.d.ts.map +1 -1
  118. package/config/index.js +2 -2
  119. package/config/index.js.map +1 -1
  120. package/config/resolve.d.ts +14 -3
  121. package/config/resolve.d.ts.map +1 -1
  122. package/config/resolve.js +30 -6
  123. package/config/resolve.js.map +1 -1
  124. package/errors/classify.d.ts.map +1 -1
  125. package/errors/classify.js +10 -1
  126. package/errors/classify.js.map +1 -1
  127. package/errors/cli-exit-error.d.ts +3 -1
  128. package/errors/cli-exit-error.d.ts.map +1 -1
  129. package/errors/cli-exit-error.js +6 -2
  130. package/errors/cli-exit-error.js.map +1 -1
  131. package/errors/handle.d.ts +32 -5
  132. package/errors/handle.d.ts.map +1 -1
  133. package/errors/handle.js +67 -8
  134. package/errors/handle.js.map +1 -1
  135. package/local/daemon/components.d.ts +28 -1
  136. package/local/daemon/components.d.ts.map +1 -1
  137. package/local/daemon/components.js +64 -2
  138. package/local/daemon/components.js.map +1 -1
  139. package/local/daemon/host.d.ts.map +1 -1
  140. package/local/daemon/host.js +6 -2
  141. package/local/daemon/host.js.map +1 -1
  142. package/local/daemon/launch.d.ts +12 -4
  143. package/local/daemon/launch.d.ts.map +1 -1
  144. package/local/daemon/launch.js +49 -16
  145. package/local/daemon/launch.js.map +1 -1
  146. package/local/daemon/types.d.ts +9 -1
  147. package/local/daemon/types.d.ts.map +1 -1
  148. package/local/key-check.d.ts +20 -0
  149. package/local/key-check.d.ts.map +1 -0
  150. package/local/key-check.js +45 -0
  151. package/local/key-check.js.map +1 -0
  152. package/local/model-key-step.d.ts +63 -0
  153. package/local/model-key-step.d.ts.map +1 -0
  154. package/local/model-key-step.js +133 -0
  155. package/local/model-key-step.js.map +1 -0
  156. package/local/runtime/node.d.ts +12 -4
  157. package/local/runtime/node.d.ts.map +1 -1
  158. package/local/runtime/node.js +73 -27
  159. package/local/runtime/node.js.map +1 -1
  160. package/local/setup/prompt.d.ts.map +1 -1
  161. package/local/setup/prompt.js +22 -18
  162. package/local/setup/prompt.js.map +1 -1
  163. package/local/setup/wizard.d.ts +10 -0
  164. package/local/setup/wizard.d.ts.map +1 -1
  165. package/local/setup/wizard.js +40 -17
  166. package/local/setup/wizard.js.map +1 -1
  167. package/local/state/lock.d.ts.map +1 -1
  168. package/local/state/lock.js +123 -36
  169. package/local/state/lock.js.map +1 -1
  170. package/local/state/pidfile.d.ts +4 -0
  171. package/local/state/pidfile.d.ts.map +1 -1
  172. package/local/state/pidfile.js +12 -3
  173. package/local/state/pidfile.js.map +1 -1
  174. package/local/status.d.ts.map +1 -1
  175. package/local/status.js +62 -4
  176. package/local/status.js.map +1 -1
  177. package/package.json +13 -10
  178. package/program.d.ts.map +1 -1
  179. package/program.js +12 -0
  180. package/program.js.map +1 -1
  181. package/resources/get.js +1 -1
  182. package/resources/get.js.map +1 -1
  183. package/resources/provider-key.d.ts +7 -2
  184. package/resources/provider-key.d.ts.map +1 -1
  185. package/resources/provider-key.js +18 -3
  186. package/resources/provider-key.js.map +1 -1
  187. package/resources/run/stream.d.ts.map +1 -1
  188. package/resources/run/stream.js +2 -1
  189. package/resources/run/stream.js.map +1 -1
  190. package/resources/runs.d.ts +10 -3
  191. package/resources/runs.d.ts.map +1 -1
  192. package/resources/runs.js +22 -4
  193. package/resources/runs.js.map +1 -1
  194. package/resources/stream/render-plaintext.d.ts +3 -0
  195. package/resources/stream/render-plaintext.d.ts.map +1 -1
  196. package/resources/stream/render-plaintext.js +20 -2
  197. package/resources/stream/render-plaintext.js.map +1 -1
  198. package/resources/usage.d.ts +8 -0
  199. package/resources/usage.d.ts.map +1 -1
  200. package/resources/usage.js +37 -0
  201. package/resources/usage.js.map +1 -1
  202. package/resources/views/agent.d.ts.map +1 -1
  203. package/resources/views/agent.js +18 -2
  204. package/resources/views/agent.js.map +1 -1
  205. package/runtime.d.ts +9 -0
  206. package/runtime.d.ts.map +1 -1
  207. package/runtime.js +12 -1
  208. package/runtime.js.map +1 -1
  209. package/src/auth/browser.ts +57 -0
  210. package/src/auth/callback-server.ts +58 -22
  211. package/src/auth/device.ts +151 -0
  212. package/src/auth/index.ts +4 -3
  213. package/src/auth/login.ts +243 -67
  214. package/src/auth/oidc.ts +270 -0
  215. package/src/auth/token.ts +53 -90
  216. package/src/client/client.ts +4 -1
  217. package/src/client/current-organization.ts +27 -0
  218. package/src/commands/apikey/index.ts +85 -0
  219. package/src/commands/app-handover.ts +202 -0
  220. package/src/commands/auth/index.ts +16 -10
  221. package/src/commands/auth/login.ts +30 -23
  222. package/src/commands/auth/whoami.ts +80 -1
  223. package/src/commands/coding-agent.ts +33 -0
  224. package/src/commands/config/backend.ts +20 -6
  225. package/src/commands/docs/index.ts +65 -0
  226. package/src/commands/embedding.ts +209 -0
  227. package/src/commands/example.ts +157 -0
  228. package/src/commands/help.ts +19 -3
  229. package/src/commands/list.ts +14 -1
  230. package/src/commands/load-test/burst.ts +291 -0
  231. package/src/commands/load-test/index.ts +183 -0
  232. package/src/commands/load-test/report.ts +302 -0
  233. package/src/commands/mcp-server.ts +16 -8
  234. package/src/commands/provider-key/index.ts +7 -1
  235. package/src/commands/setup.ts +76 -2
  236. package/src/commands/status.ts +4 -3
  237. package/src/commands/up.ts +76 -10
  238. package/src/commands/usage.ts +55 -2
  239. package/src/config/config.ts +18 -8
  240. package/src/config/index.ts +2 -0
  241. package/src/config/resolve.ts +31 -6
  242. package/src/errors/classify.ts +10 -1
  243. package/src/errors/cli-exit-error.ts +6 -2
  244. package/src/errors/handle.ts +74 -8
  245. package/src/local/daemon/components.ts +66 -2
  246. package/src/local/daemon/host.ts +6 -2
  247. package/src/local/daemon/launch.ts +51 -16
  248. package/src/local/daemon/types.ts +9 -1
  249. package/src/local/key-check.ts +61 -0
  250. package/src/local/model-key-step.ts +164 -0
  251. package/src/local/runtime/node.ts +95 -30
  252. package/src/local/setup/prompt.ts +22 -18
  253. package/src/local/setup/wizard.ts +45 -18
  254. package/src/local/state/lock.ts +116 -35
  255. package/src/local/state/pidfile.ts +14 -3
  256. package/src/local/status.ts +69 -4
  257. package/src/program.ts +12 -0
  258. package/src/resources/get.ts +1 -1
  259. package/src/resources/provider-key.ts +24 -3
  260. package/src/resources/run/stream.ts +2 -1
  261. package/src/resources/runs.ts +36 -4
  262. package/src/resources/stream/render-plaintext.ts +20 -2
  263. package/src/resources/usage.ts +42 -0
  264. package/src/resources/views/agent.ts +19 -2
  265. package/src/runtime.ts +17 -1
  266. package/auth/auth0.d.ts +0 -19
  267. package/auth/auth0.d.ts.map +0 -1
  268. package/auth/auth0.js +0 -39
  269. package/auth/auth0.js.map +0 -1
  270. package/src/auth/auth0.ts +0 -43
@@ -2,32 +2,38 @@
2
2
  // subprocesses.
3
3
  //
4
4
  // We reuse the very Node that is running the CLI (process.execPath). The CLI is
5
- // itself an npm package with `engines: node >= 22.13`, so a suitable Node is
6
- // always present by construction — there is deliberately no hermetic Node
7
- // download (keep the base install lean: nothing to acquire that the host
8
- // already guarantees). This is exactly what the conformance harness does
9
- // (`spawn(process.execPath, ...)`). An explicit STIGMER_NODE_BIN override is
10
- // honored and capability-checked for advanced/multi-runtime setups.
5
+ // itself an npm package whose `engines` is the server's range (Node 22 from
6
+ // 22.19, or 24 and later), so npm warns at install on a Node that cannot run
7
+ // the server — there is deliberately no hermetic Node download (keep the base
8
+ // install lean: nothing to acquire that the host already provides). This is
9
+ // exactly what the conformance harness does (`spawn(process.execPath, ...)`).
10
+ // An explicit STIGMER_NODE_BIN override is honored and checked the same way
11
+ // for advanced/multi-runtime setups.
11
12
  //
12
- // The gates are CAPABILITY probes, not version checks. Two probes, because the
13
- // two children need different sqlite capabilities:
13
+ // The runner's gate is a CAPABILITY probe; the server's is its declared
14
+ // version range, then a capability probe:
14
15
  //
15
16
  // - The RUNNER's durable local checkpointer imports Node's built-in
16
17
  // `node:sqlite`, available unflagged from 22.13 in the 22.x line and only
17
18
  // from 23.4 in the 23.x line — a gap (23.0–23.3) that a previous
18
19
  // version-table gate here missed, letting those Nodes through to crash at
19
- // runner boot with a raw ERR_UNKNOWN_BUILTIN_MODULE.
20
- // - The SERVER additionally needs `node:sqlite` compiled WITH FTS5 (its
21
- // search index; migration v3 creates an fts5 virtual table at boot). Node
22
- // 23.4 PROVIDES node:sqlite but its sqlite build LACKS FTS5 — the reason
23
- // the module-presence probe alone is insufficient
24
- // for the server. Probing "can this binary create an fts5 table?" directly
25
- // cannot drift; the version floors survive only in the error messages,
26
- // where staleness is harmless.
20
+ // runner boot with a raw ERR_UNKNOWN_BUILTIN_MODULE. Probing the module
21
+ // cannot drift; the runner's floors survive only in its error copy.
22
+ // - The SERVER declares the Nodes it runs on in its own `engines`
23
+ // (`backend/services/stigmer-server/package.json`), above the runner's:
24
+ // its outbound dialer loads undici, whose floor is 22.19, and the server
25
+ // supports 22.x and 24+. undici's need has no capability this resolver
26
+ // could probe without loading undici, so here the gate IS a version check,
27
+ // against `SERVER_NODE_LINES`, which a test holds equal to the server's
28
+ // declared range and to this package's own `engines`, so the two cannot
29
+ // drift apart. The server ALSO needs `node:sqlite` compiled WITH FTS5 (its
30
+ // search index; migration v3 creates an fts5 virtual table at boot), and
31
+ // that stays a capability probe: a Node in range whose sqlite build lacks
32
+ // FTS5 is refused by what it cannot do.
27
33
  //
28
34
  // The runner performs the module-presence probe on its own boot (see
29
35
  // backend/services/runner/src/preflight.ts); the server fails at migration
30
- // time. Both probes here exist to fail at resolve time with CLI-appropriate
36
+ // time. These gates exist to fail at resolve time with CLI-appropriate
31
37
  // guidance instead of a subprocess crash.
32
38
 
33
39
  import { execFileSync } from "node:child_process";
@@ -82,24 +88,83 @@ export function resolveNode(): string {
82
88
  return bin;
83
89
  }
84
90
 
91
+ /**
92
+ * The Node lines the server runs on, lowest accepted version first: each
93
+ * entry accepts its major from `minor`, and the last accepts every later
94
+ * major too. The one source for the server's floor in the CLI: the range
95
+ * string, the sentence and the check all derive from it, and a test holds
96
+ * the range equal to the server's `engines.node` and this package's own.
97
+ */
98
+ const SERVER_NODE_LINES = [
99
+ { major: 22, minor: 19 },
100
+ { major: 24, minor: 0 },
101
+ ] as const;
102
+
103
+ /** Whether the line at `index` is the last, which accepts every later major too. */
104
+ const isLastLine = (index: number): boolean => index === SERVER_NODE_LINES.length - 1;
105
+
106
+ /** The server's supported Node range as npm's `engines` writes it: `>=22.19.0 <23 || >=24`. */
107
+ export const SERVER_NODE_RANGE = SERVER_NODE_LINES.map(({ major, minor }, i) =>
108
+ isLastLine(i)
109
+ ? minor === 0
110
+ ? `>=${major}`
111
+ : `>=${major}.${minor}.0`
112
+ : `>=${major}.${minor}.0 <${major + 1}`,
113
+ ).join(" || ");
114
+
115
+ /** The same range in words: "Node.js 22 (22.19 or newer) or Node.js 24 or newer". */
116
+ export const SERVER_NODE_FLOOR = SERVER_NODE_LINES.map(({ major, minor }, i) =>
117
+ isLastLine(i)
118
+ ? minor === 0
119
+ ? `Node.js ${major} or newer`
120
+ : `Node.js ${major}.${minor} or newer`
121
+ : `Node.js ${major} (${major}.${minor} or newer)`,
122
+ ).join(" or ");
123
+
124
+ /** Whether `version` (`v22.19.0` or `22.19.0`) is on a line the server runs on. */
125
+ export function serverRunsOn(version: string): boolean {
126
+ const [major = Number.NaN, minor = Number.NaN] = version.replace(/^v/, "").split(".").map(Number);
127
+ return SERVER_NODE_LINES.some(
128
+ (line, i) => (major === line.major && minor >= line.minor) || (isLastLine(i) && major > line.major),
129
+ );
130
+ }
131
+
85
132
  /**
86
133
  * Resolve the Node binary to launch the TS server with. Same
87
- * STIGMER_NODE_BIN/execPath resolution as {@link resolveNode}, but probes for
88
- * `node:sqlite` WITH FTS5 — the server's search index needs it and some Node
89
- * builds (e.g. 23.4) ship node:sqlite without it. Runs on server-launch paths
90
- * only (ensureServer).
134
+ * STIGMER_NODE_BIN/execPath resolution as {@link resolveNode}, but checks
135
+ * the binary's version against the server's supported lines first (a Node
136
+ * outside them is refused naming the version to install), then probes for
137
+ * `node:sqlite` WITH FTS5 — the server's search index needs it, and a Node
138
+ * build can ship node:sqlite without it. Runs on server-launch paths only
139
+ * (ensureServer).
91
140
  */
92
141
  export function resolveServerNode(): string {
93
142
  const bin = nodeCandidate();
143
+ const version = probeNodeVersion(bin);
144
+ if (version === null) {
145
+ throw new CliExitError(
146
+ `could not run ${bin} to verify the stigmer server's Node requirements`,
147
+ ExitCode.General,
148
+ [`Ensure ${bin} is a working ${SERVER_NODE_FLOOR} runtime.`],
149
+ );
150
+ }
151
+ if (!serverRunsOn(version)) {
152
+ throw new CliExitError(
153
+ `Node at ${bin} (${version}) cannot run the stigmer server: it needs ${SERVER_NODE_FLOOR}`,
154
+ ExitCode.General,
155
+ [
156
+ "These are the Node lines the server is built and tested for; on 22.x its network client needs 22.19 or newer.",
157
+ `Install ${SERVER_NODE_FLOOR}, or point STIGMER_NODE_BIN at one.`,
158
+ ],
159
+ );
160
+ }
94
161
  assertCapability(bin, NODE_SQLITE_FTS5_PROBE, {
95
162
  subject: "the stigmer server",
96
163
  capability: "the built-in node:sqlite module with FTS5",
97
- floor: "Node 22.13+ in the 22.x line (23.x builds lack FTS5)",
164
+ floor: SERVER_NODE_FLOOR,
98
165
  detail: [
99
- "The server's search index requires node:sqlite compiled with FTS5.",
100
- "The 22.x line from 22.13 is known-good; 23.x builds ship node:sqlite",
101
- "WITHOUT FTS5 and cannot run the server. Newer majors work if their",
102
- "sqlite build includes FTS5 — this probe is the authority.",
166
+ "The server's search index requires node:sqlite compiled with FTS5,",
167
+ "and this Node's sqlite build lacks it.",
103
168
  ],
104
169
  });
105
170
  return bin;
@@ -112,7 +177,7 @@ function nodeCandidate(): string {
112
177
  : process.execPath;
113
178
  }
114
179
 
115
- /** Best-effort `--version` for error messages only; null when the spawn fails. */
180
+ /** The binary's `--version` (`v22.19.0`); null when the spawn fails. */
116
181
  function probeNodeVersion(bin: string): string | null {
117
182
  try {
118
183
  const out = execFileSync(bin, ["--version"], {
@@ -130,9 +195,9 @@ interface CapabilityErrorCopy {
130
195
  subject: string;
131
196
  /** The missing capability, in user terms. */
132
197
  capability: string;
133
- /** The known-good version floor, per probe — the two probes differ (the
134
- * runner accepts 23.4+; the server does not). Error copy only; the probe
135
- * is the authority. */
198
+ /** The known-good version floor, per probe — the two differ (the runner
199
+ * accepts 23.4+; the server does not). Error copy only; the probe is the
200
+ * authority for the capability. */
136
201
  floor: string;
137
202
  /** Guidance lines explaining the requirement. */
138
203
  detail: string[];
@@ -43,25 +43,29 @@ export function promptSecret(question: string): Promise<string> {
43
43
  resolve(value);
44
44
  };
45
45
 
46
+ // One chunk can hold many keys: a paste, or a terminal driver typing a
47
+ // whole answer in one write, arrives with its Enter in the same chunk,
48
+ // so each character is read on its own and the first Enter finishes.
46
49
  const onData = (chunk: Buffer): void => {
47
- const char = chunk.toString("utf8");
48
- switch (char) {
49
- case "\n":
50
- case "\r":
51
- case "\u0004": // Ctrl-D
52
- finish();
53
- break;
54
- case "\u0003": // Ctrl-C
55
- stdin.setRawMode(false);
56
- process.stderr.write("\n");
57
- process.exit(130);
58
- break;
59
- case "\u007f": // Backspace
60
- case "\b":
61
- value = value.slice(0, -1);
62
- break;
63
- default:
64
- value += char;
50
+ for (const char of chunk.toString("utf8")) {
51
+ switch (char) {
52
+ case "\n":
53
+ case "\r":
54
+ case "\u0004": // Ctrl-D
55
+ finish();
56
+ return;
57
+ case "\u0003": // Ctrl-C
58
+ stdin.setRawMode(false);
59
+ process.stderr.write("\n");
60
+ process.exit(130);
61
+ return;
62
+ case "\u007f": // Backspace
63
+ case "\b":
64
+ value = value.slice(0, -1);
65
+ break;
66
+ default:
67
+ value += char;
68
+ }
65
69
  }
66
70
  };
67
71
 
@@ -7,7 +7,9 @@
7
7
  // Setup saves the one key the Stigmer and Claude engines run the catalog's
8
8
  // models on, Anthropic's, so the interactive flow is a single API-key prompt
9
9
  // rather than a provider menu, followed by the skippable operator-identity
10
- // prompt (oss#796). The runner reaches the other providers (OpenAI, and
10
+ // prompt (oss#796). The key prompt is `stigmer up`'s (local/model-key-step.ts):
11
+ // it says why, checks the key with Anthropic, and asks again when Anthropic
12
+ // refuses it; an exported key is checked and its answer said. The runner reaches the other providers (OpenAI, and
11
13
  // Anthropic through Vertex, Bedrock, Foundry or a gateway) by settings
12
14
  // exported in the shell; local/provider-reach.ts says which it reaches. There
13
15
  // is no model concept here at all: the platform model registry owns the
@@ -16,6 +18,8 @@
16
18
 
17
19
  import type { Config } from "../../config/config.js";
18
20
  import { type LlmSettings, setLlm } from "../llm-config.js";
21
+ import { type KeyCheck, checkAnthropicKey } from "../key-check.js";
22
+ import { anthropicKeyTarget, askForKey, ENV_KEY_REJECTED, type KeyStepDeps } from "../model-key-step.js";
19
23
  import {
20
24
  type OperatorSettings,
21
25
  setOperator,
@@ -88,26 +92,49 @@ export function applyOperatorIdentity(config: Config, email: string, name: strin
88
92
  * env precedence makes a copy redundant); an empty entry is an explicit skip.
89
93
  */
90
94
  export async function runInteractiveWizard(config: Config, env: NodeJS.ProcessEnv = process.env): Promise<Config> {
91
- process.stderr.write("\nStigmer runs local agents on Anthropic Claude models.\n");
92
- process.stderr.write("The model is chosen automatically from the platform model registry.\n\n");
93
-
94
- let updated: Config;
95
- if (env.ANTHROPIC_API_KEY) {
96
- process.stderr.write("Using ANTHROPIC_API_KEY from environment\n");
97
- updated = applyChoice(config, "anthropic");
98
- } else {
99
- const key = (await promptSecret("Enter your Anthropic API key (press Enter to skip)")).trim();
100
- if (key === "") {
101
- process.stderr.write("Skipped. Agents won't execute until a provider is configured (stigmer setup).\n");
102
- updated = applyChoice(config, "skip");
103
- } else {
104
- updated = applyChoice(config, "anthropic", { apiKey: key });
105
- }
106
- }
107
-
95
+ const updated = await runKeyStep(config, {
96
+ env,
97
+ promptSecret,
98
+ write: (text) => process.stderr.write(text),
99
+ check: (key, baseUrl) => checkAnthropicKey(key, baseUrl),
100
+ });
108
101
  return runOperatorIdentityStep(updated, env);
109
102
  }
110
103
 
104
+ /** What the interactive key step needs: the terminal and the check, which tests replace. */
105
+ export type WizardKeyDeps = Pick<KeyStepDeps, "env" | "promptSecret" | "write" | "check">;
106
+
107
+ /**
108
+ * The interactive key step: an exported key is used without prompting (and
109
+ * never persisted, env precedence makes a copy redundant), checked, and its
110
+ * answer said; otherwise the shared prompt asks until Anthropic takes a key,
111
+ * does not answer, or the person presses Enter, which skips.
112
+ */
113
+ export async function runKeyStep(config: Config, deps: WizardKeyDeps): Promise<Config> {
114
+ deps.write("\nThe model is chosen automatically from the platform model registry.\n");
115
+ const exported = deps.env.ANTHROPIC_API_KEY ?? "";
116
+ if (exported !== "") {
117
+ const target = anthropicKeyTarget(deps.env);
118
+ const check: KeyCheck | undefined = target === null ? undefined : await deps.check(exported, target.baseUrl);
119
+ deps.write(`Using ANTHROPIC_API_KEY from environment${check === undefined ? "" : ENV_CHECK_WORDS[check]}\n`);
120
+ if (check === "rejected") deps.write(`${ENV_KEY_REJECTED}\n`);
121
+ return applyChoice(config, "anthropic");
122
+ }
123
+ const answer = await askForKey(deps);
124
+ if (answer === undefined) {
125
+ deps.write("Skipped. Agents won't execute until a provider is configured (stigmer setup).\n");
126
+ return applyChoice(config, "skip");
127
+ }
128
+ return applyChoice(config, "anthropic", { apiKey: answer.key });
129
+ }
130
+
131
+ /** What an exported key's check adds to its "Using" line. */
132
+ const ENV_CHECK_WORDS: Readonly<Record<KeyCheck, string>> = {
133
+ accepted: " (checked with Anthropic just now)",
134
+ rejected: " (rejected by Anthropic)",
135
+ unchecked: " (not checked: Anthropic didn't answer)",
136
+ };
137
+
111
138
  /**
112
139
  * The operator-identity step (oss#796): opt-in, skippable, and env-aware in
113
140
  * the same way the API-key step is — an env-provided identity is used without
@@ -1,21 +1,43 @@
1
- // A single-instance file lock built on atomic O_EXCL file creation.
1
+ // A single-instance file lock built on atomic file creation.
2
2
  //
3
3
  // Node has no portable `flock`, so the lock is a file whose existence is the
4
4
  // lock and whose contents are the owner's PID record (state/pidfile.ts): its
5
- // PID, and when that process started. Creation uses the "wx" flag
6
- // (O_CREAT | O_EXCL), which is atomic on POSIX and Windows, so two racing
7
- // acquirers cannot both win. If the file already exists the owner is judged as
8
- // every PID reader judges a record, through recordedLiveProcess: a live peer
9
- // that is still the process recorded holds the lock; anything else is stale
10
- // and reclaimed. That covers a dead owner, our own PID from a previous life
11
- // (we hold a lock only if it is tracked in-process), and a number the OS has
12
- // since handed to another program, which would otherwise hold the lock until
13
- // the file was deleted by hand (stigmer#2900). This guards the Temporal dev
14
- // server against double-start without a native dependency.
5
+ // PID, when that process started, and a `lock=` token drawn once per
6
+ // acquisition, so no two lock files are ever byte-identical (a Windows record
7
+ // has no start time, and a reused PID would otherwise read the same). If the
8
+ // file already exists the owner is judged as every PID reader judges a record,
9
+ // through liveRecordedProcess: a live peer that is still the process recorded
10
+ // holds the lock; anything else is stale and reclaimed. That covers a dead
11
+ // owner, our own PID from a previous life (we hold a lock only if it is tracked
12
+ // in-process), and a number the OS has since handed to another program, which
13
+ // would otherwise hold the lock until the file was deleted by hand
14
+ // (stigmer#2900). This guards the Temporal dev server against double-start
15
+ // without a native dependency.
16
+ //
17
+ // Two races once let two acquirers both hold it (stigmer#2993):
18
+ //
19
+ // - Create. Opening with O_EXCL and then writing left the lock's name empty in
20
+ // between, and a racing acquirer reads an empty lock as unowned and reclaims
21
+ // it. The record is now written beside the lock and hard-linked into place;
22
+ // a link fails with EEXIST like O_EXCL, and the name is never seen empty. A
23
+ // filesystem without hard links (EPERM, ENOTSUP, ENOSYS: FAT, some SMB and
24
+ // FUSE mounts) falls back to the open-then-write, and keeps its empty window.
25
+ // - Reclaim. Two acquirers that judged the same stale lock both removed it, and
26
+ // the second removal could take the first's fresh lock. A reclaimer now
27
+ // renames the lock aside, which only one can do to a given file, and keeps it
28
+ // gone only if the moved file holds exactly the bytes it judged; otherwise a
29
+ // peer had already reclaimed it, and the peer's lock is put back.
30
+ //
31
+ // One window remains: a third acquirer that creates the lock between a
32
+ // reclaimer's move-aside and its put-back loses its file to the put-back, and
33
+ // two would hold the lock. It takes three `stigmer up` runs within
34
+ // microseconds over a dead owner's leftover lock; closing it needs a kernel
35
+ // lock, which Node has no portable way to take.
15
36
 
16
- import { closeSync, mkdirSync, openSync, rmSync, writeFileSync } from "node:fs";
17
- import { dirname } from "node:path";
18
- import { pidRecordText, readPidFile, recordedLiveProcess } from "./pidfile.js";
37
+ import { randomBytes } from "node:crypto";
38
+ import { closeSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
39
+ import { basename, dirname } from "node:path";
40
+ import { liveRecordedProcess, parsePidRecord, pidRecordText } from "./pidfile.js";
19
41
 
20
42
  /** A held lock. Call release() exactly once when done. */
21
43
  export interface FileLock {
@@ -23,6 +45,9 @@ export interface FileLock {
23
45
  release(): void;
24
46
  }
25
47
 
48
+ // What a hard link answers on a filesystem that has none.
49
+ const NO_HARD_LINKS = new Set(["EPERM", "ENOTSUP", "ENOSYS"]);
50
+
26
51
  // Lock paths this process currently holds. A lock file naming OUR pid is
27
52
  // genuinely held only if it is in here; otherwise it is a leftover from a
28
53
  // previous life of the pid (a restarted container, a rebooted laptop) and is
@@ -41,31 +66,70 @@ export function acquireLock(path: string): FileLock | null {
41
66
 
42
67
  if (heldInProcess.has(path)) return null; // held right here, by us
43
68
 
44
- if (tryCreate(path)) return makeLock(path);
69
+ // Composed before any create: reading the start time can spawn `ps`.
70
+ const text = `${pidRecordText(process.pid)}lock=${randomBytes(8).toString("hex")}\n`;
71
+ if (tryCreate(path, text)) return makeLock(path, text);
45
72
 
46
- // The lock file exists. It is held only while it names another live
47
- // process that is still the one recorded; recordedLiveProcess answers null
48
- // for our own pid (we just established we are not holding it), a dead
49
- // owner, an unreadable file, and a number now owned by another program.
50
- if (recordedLiveProcess(path) !== null) {
73
+ // The lock file exists. Read it once and judge those bytes: it is held only
74
+ // while it names another live process that is still the one recorded.
75
+ // liveRecordedProcess answers null for our own pid (we just established we
76
+ // are not holding it), a dead owner, an unreadable record, and a number now
77
+ // owned by another program.
78
+ const judged = unlessMissing(() => readFileSync(path, "utf8"));
79
+ if (judged === null) return createOnce(path, text); // its owner released it just now
80
+ if (liveRecordedProcess(parsePidRecord(judged), basename(path)) !== null) {
51
81
  return null; // genuinely held by a live peer
52
82
  }
53
83
 
54
- // Stale (or unreadable) lock: remove and retry exactly once. A failure on the
55
- // retry means another process raced us to it — treat the lock as held.
56
- rmSync(path, { force: true });
57
- return tryCreate(path) ? makeLock(path) : null;
84
+ // Stale: move it aside, which only one reclaimer can do to a given file.
85
+ const aside = `${path}.${process.pid}.stale`;
86
+ const moved = unlessMissing(() => {
87
+ renameSync(path, aside);
88
+ return true;
89
+ });
90
+ if (moved === null) return createOnce(path, text); // a peer moved it first
91
+ if (readFileSync(aside, "utf8") !== judged) {
92
+ // Not the file judged: a peer reclaimed the stale lock and holds it now.
93
+ renameSync(aside, path);
94
+ return null;
95
+ }
96
+ rmSync(aside, { force: true });
97
+ return createOnce(path, text);
98
+ }
99
+
100
+ /** One more create; losing it means a peer took the lock first. */
101
+ function createOnce(path: string, text: string): FileLock | null {
102
+ return tryCreate(path, text) ? makeLock(path, text) : null;
103
+ }
104
+
105
+ /** Create the lock holding `text` in one step; false when it already exists. */
106
+ function tryCreate(path: string, text: string): boolean {
107
+ const temp = `${path}.${process.pid}.tmp`;
108
+ try {
109
+ writeFileSync(temp, text, "utf8");
110
+ try {
111
+ linkSync(temp, path);
112
+ return true;
113
+ } catch (err) {
114
+ const code = (err as NodeJS.ErrnoException).code ?? "";
115
+ if (code === "EEXIST") return false;
116
+ if (!NO_HARD_LINKS.has(code)) throw err;
117
+ }
118
+ } finally {
119
+ rmSync(temp, { force: true });
120
+ }
121
+ return createInPlace(path, text);
58
122
  }
59
123
 
60
- function tryCreate(path: string): boolean {
61
- // Read before the create: the file is empty, and so unowned to a racing
62
- // reader, from the open until the write, and reading the start time can
63
- // spawn `ps`.
64
- const record = pidRecordText(process.pid);
124
+ /** The create without hard links: the name is empty from the open until the write. */
125
+ function createInPlace(path: string, text: string): boolean {
65
126
  try {
66
127
  const fd = openSync(path, "wx");
67
- writeFileSync(fd, record, "utf8");
68
- closeSync(fd);
128
+ try {
129
+ writeFileSync(fd, text, "utf8");
130
+ } finally {
131
+ closeSync(fd);
132
+ }
69
133
  return true;
70
134
  } catch (err) {
71
135
  if ((err as NodeJS.ErrnoException).code === "EEXIST") return false;
@@ -73,7 +137,17 @@ function tryCreate(path: string): boolean {
73
137
  }
74
138
  }
75
139
 
76
- function makeLock(path: string): FileLock {
140
+ /** `act`'s answer, or null when the file it touches is gone (ENOENT). */
141
+ function unlessMissing<T>(act: () => T): T | null {
142
+ try {
143
+ return act();
144
+ } catch (err) {
145
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
146
+ throw err;
147
+ }
148
+ }
149
+
150
+ function makeLock(path: string, text: string): FileLock {
77
151
  heldInProcess.add(path);
78
152
  let released = false;
79
153
  return {
@@ -82,9 +156,16 @@ function makeLock(path: string): FileLock {
82
156
  if (released) return;
83
157
  released = true;
84
158
  heldInProcess.delete(path);
85
- // Only remove the file if we still own it, so we never delete a lock a
86
- // different process acquired after ours was (somehow) gone.
87
- if (readPidFile(path) === process.pid) rmSync(path, { force: true });
159
+ // Only remove the file while it is still the one this lock wrote, token
160
+ // and all, so we never delete a lock another process acquired after ours
161
+ // was (somehow) gone, even one that has our PID.
162
+ let current: string | null = null;
163
+ try {
164
+ current = readFileSync(path, "utf8");
165
+ } catch {
166
+ // gone already, or unreadable: nothing of ours to remove
167
+ }
168
+ if (current === text) rmSync(path, { force: true });
88
169
  },
89
170
  };
90
171
  }
@@ -12,7 +12,9 @@
12
12
  // which answers with the PID only while the live process is still the one
13
13
  // recorded. The Temporal start lock (state/lock.ts) is such a record too, and
14
14
  // judges its owner the same way (stigmer#2900). The first line stays the bare
15
- // PID every reader, an older CLI's included, expects.
15
+ // PID every reader, an older CLI's included, expects. Each reader comes as a
16
+ // parse and a judge over a record already in hand (parsePidRecord,
17
+ // liveRecordedProcess), so the lock can judge exactly the bytes it read.
16
18
 
17
19
  import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
18
20
  import { basename, dirname } from "node:path";
@@ -61,6 +63,11 @@ export function readPidRecord(path: string): PidRecord | null {
61
63
  } catch {
62
64
  return null;
63
65
  }
66
+ return parsePidRecord(raw);
67
+ }
68
+
69
+ /** A PID record's text parsed; null when its first line is not a positive integer. */
70
+ export function parsePidRecord(raw: string): PidRecord | null {
64
71
  const lines = raw.split("\n");
65
72
  const pid = Number.parseInt(lines[0]?.trim() ?? "", 10);
66
73
  if (!Number.isInteger(pid) || pid <= 0) return null;
@@ -78,11 +85,15 @@ export function readPidRecord(path: string): PidRecord | null {
78
85
  * existed, is trusted on liveness alone, as it always was.
79
86
  */
80
87
  export function recordedLiveProcess(path: string): number | null {
81
- const record = readPidRecord(path);
88
+ return liveRecordedProcess(readPidRecord(path), basename(path));
89
+ }
90
+
91
+ /** recordedLiveProcess over a record already read; `name` labels its log line. */
92
+ export function liveRecordedProcess(record: PidRecord | null, name: string): number | null {
82
93
  if (record === null || !isOtherLiveProcess(record.pid)) return null;
83
94
  if (record.started === null) return record.pid;
84
95
  if (processStartTime(record.pid) === record.started) return record.pid;
85
- log.info(`${basename(path)} names another program now; leaving it alone`, { pid: record.pid });
96
+ log.info(`${name} names another program now; leaving it alone`, { pid: record.pid });
86
97
  return null;
87
98
  }
88
99
 
@@ -1,4 +1,16 @@
1
- // `stigmer status` — render the local stack's health as a structured result.
1
+ // `stigmer status` — say which server the CLI uses, then render the local
2
+ // stack's health as a structured result.
3
+ //
4
+ // It names the backend the CLI uses and its address first, read from the
5
+ // same resolver the backend client dials by (config/resolve.ts). When that is
6
+ // not the local stack (a self-hosted server, Stigmer Cloud, or an address in
7
+ // STIGMER_SERVER_ADDRESS), a missing local stack is nothing wrong: it says so
8
+ // and returns success, with no hint to start one, since a person signed in to
9
+ // their own server who follows `stigmer up` starts a second server
10
+ // (stigmer#3369). It never asks the remote server anything; reaching it is
11
+ // `stigmer auth whoami`'s. A backend config that cannot be read is shown on
12
+ // the Backend line with its own error, and the local stack is still reported:
13
+ // a diagnostic command never fails on what it diagnoses.
2
14
  //
3
15
  // Source of truth is `health-state.json`, written by the daemon's health
4
16
  // monitor. If it is missing but the server port answers (the daemon wrote a PID
@@ -10,8 +22,9 @@
10
22
  import { formatElapsed } from "@stigmer/client";
11
23
  import { homedir } from "node:os";
12
24
  import { join } from "node:path";
13
- import { load as loadConfig } from "../config/config.js";
25
+ import { activeBackend, load as loadConfig } from "../config/config.js";
14
26
  import { configPath } from "../config/paths.js";
27
+ import { resolveServerAddress } from "../config/resolve.js";
15
28
  import { CommandResult } from "../output/command-result.js";
16
29
  import { SERVER_PORT, TEMPORAL_UI_PORT } from "./constants.js";
17
30
  import { resolveApiKey } from "./llm-config.js";
@@ -48,14 +61,25 @@ export async function buildStatusResult(
48
61
  const pid = recordedLiveProcess(join(data, DAEMON_PID_FILE));
49
62
  const daemonAlive = pid !== null;
50
63
  const portOpen = await probe(SERVER_PORT);
64
+ const backend = backendInUse(home, env);
65
+ const elsewhere = backend.kind === "remote";
51
66
 
52
67
  if (!daemonAlive && !portOpen) {
53
- return CommandResult.warning("Stigmer server is not running").hint("To start: stigmer up");
68
+ if (elsewhere) {
69
+ const result = CommandResult.success(usesMessage(backend));
70
+ addBackendSection(result, backend);
71
+ result.addSection("Local Stack").field("Status", "Not running ○");
72
+ return result;
73
+ }
74
+ const result = CommandResult.warning("Stigmer server is not running");
75
+ addBackendSection(result, backend);
76
+ return result.hint("To start: stigmer up");
54
77
  }
55
78
 
56
79
  const health = loadHealthState(join(data, "health-state.json")) ?? synthesizeHealth(pid, portOpen);
57
80
 
58
- const result = CommandResult.success("Stigmer server is running");
81
+ const result = CommandResult.success(elsewhere ? usesMessage(backend) : "Stigmer server is running");
82
+ addBackendSection(result, backend);
59
83
 
60
84
  const daemon = result.addSection("Daemon");
61
85
  daemon.field("PID", String(health.daemon_pid));
@@ -80,6 +104,47 @@ export async function buildStatusResult(
80
104
  return result;
81
105
  }
82
106
 
107
+ /** The server the CLI uses: the local stack, another server, or a config that names none it can read. */
108
+ type BackendInUse =
109
+ | { readonly kind: "local"; readonly name: string; readonly address: string }
110
+ | { readonly kind: "remote"; readonly name: string; readonly address: string; readonly fromEnvironment: boolean }
111
+ | { readonly kind: "broken"; readonly error: string };
112
+
113
+ // The local stack's own address, as the resolver names it or as an
114
+ // override may spell it; an override naming it is still the local stack.
115
+ const LOCAL_ADDRESSES = new Set([`localhost:${SERVER_PORT}`, `127.0.0.1:${SERVER_PORT}`]);
116
+
117
+ function backendInUse(home: string, env: NodeJS.ProcessEnv): BackendInUse {
118
+ try {
119
+ const config = loadConfig(configPath(home));
120
+ const { name } = activeBackend(config);
121
+ const { address, source } = resolveServerAddress(config, env);
122
+ if (source === "local" || LOCAL_ADDRESSES.has(address)) return { kind: "local", name, address };
123
+ return { kind: "remote", name, address, fromEnvironment: source === "environment" };
124
+ } catch (err) {
125
+ return { kind: "broken", error: err instanceof Error ? err.message : String(err) };
126
+ }
127
+ }
128
+
129
+ function usesMessage(backend: Extract<BackendInUse, { kind: "remote" }>): string {
130
+ return backend.fromEnvironment
131
+ ? `The CLI uses ${backend.address} (STIGMER_SERVER_ADDRESS), not a local stack`
132
+ : `The CLI uses backend "${backend.name}" at ${backend.address}, not a local stack`;
133
+ }
134
+
135
+ // The same words `stigmer config backend status` uses for the same facts.
136
+ function addBackendSection(result: CommandResult, backend: BackendInUse): void {
137
+ const section = result.addSection("");
138
+ if (backend.kind === "broken") {
139
+ section.field("Backend", `unreadable: ${backend.error}`);
140
+ result.hint("See the configured backends: stigmer config backend list");
141
+ return;
142
+ }
143
+ section.field("Backend", backend.name);
144
+ section.field("Endpoint", backend.address);
145
+ if (backend.kind === "remote" && backend.fromEnvironment) section.field("Set by", "STIGMER_SERVER_ADDRESS");
146
+ }
147
+
83
148
  function synthesizeHealth(pid: number | null, portOpen: boolean): HealthState {
84
149
  // No snapshot on disk: report only what a TCP probe can prove. If the port
85
150
  // answers the server is running; otherwise leave components empty so the