@stigmer/cli 0.1.3 → 0.2.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 (230) 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 +155 -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 +5 -0
  52. package/commands/auth/whoami.d.ts.map +1 -1
  53. package/commands/auth/whoami.js +13 -1
  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/embedding.d.ts +28 -0
  62. package/commands/embedding.d.ts.map +1 -0
  63. package/commands/embedding.js +170 -0
  64. package/commands/embedding.js.map +1 -0
  65. package/commands/example.d.ts +13 -0
  66. package/commands/example.d.ts.map +1 -0
  67. package/commands/example.js +126 -0
  68. package/commands/example.js.map +1 -0
  69. package/commands/help.d.ts.map +1 -1
  70. package/commands/help.js +16 -3
  71. package/commands/help.js.map +1 -1
  72. package/commands/load-test/burst.d.ts +64 -0
  73. package/commands/load-test/burst.d.ts.map +1 -0
  74. package/commands/load-test/burst.js +202 -0
  75. package/commands/load-test/burst.js.map +1 -0
  76. package/commands/load-test/index.d.ts +37 -0
  77. package/commands/load-test/index.d.ts.map +1 -0
  78. package/commands/load-test/index.js +154 -0
  79. package/commands/load-test/index.js.map +1 -0
  80. package/commands/load-test/report.d.ts +98 -0
  81. package/commands/load-test/report.d.ts.map +1 -0
  82. package/commands/load-test/report.js +210 -0
  83. package/commands/load-test/report.js.map +1 -0
  84. package/commands/mcp-server.d.ts +3 -3
  85. package/commands/mcp-server.d.ts.map +1 -1
  86. package/commands/mcp-server.js +4 -4
  87. package/commands/mcp-server.js.map +1 -1
  88. package/commands/setup.d.ts +17 -0
  89. package/commands/setup.d.ts.map +1 -1
  90. package/commands/setup.js +71 -1
  91. package/commands/setup.js.map +1 -1
  92. package/commands/up.d.ts.map +1 -1
  93. package/commands/up.js +67 -9
  94. package/commands/up.js.map +1 -1
  95. package/commands/usage.d.ts +15 -0
  96. package/commands/usage.d.ts.map +1 -1
  97. package/commands/usage.js +52 -2
  98. package/commands/usage.js.map +1 -1
  99. package/config/config.d.ts +14 -7
  100. package/config/config.d.ts.map +1 -1
  101. package/config/config.js +5 -1
  102. package/config/config.js.map +1 -1
  103. package/config/index.d.ts +1 -1
  104. package/config/index.d.ts.map +1 -1
  105. package/config/index.js +1 -1
  106. package/config/index.js.map +1 -1
  107. package/config/resolve.d.ts +1 -1
  108. package/config/resolve.d.ts.map +1 -1
  109. package/config/resolve.js +6 -3
  110. package/config/resolve.js.map +1 -1
  111. package/errors/classify.d.ts.map +1 -1
  112. package/errors/classify.js +10 -1
  113. package/errors/classify.js.map +1 -1
  114. package/errors/cli-exit-error.d.ts +3 -1
  115. package/errors/cli-exit-error.d.ts.map +1 -1
  116. package/errors/cli-exit-error.js +6 -2
  117. package/errors/cli-exit-error.js.map +1 -1
  118. package/errors/handle.d.ts +32 -5
  119. package/errors/handle.d.ts.map +1 -1
  120. package/errors/handle.js +67 -8
  121. package/errors/handle.js.map +1 -1
  122. package/local/daemon/components.d.ts +28 -1
  123. package/local/daemon/components.d.ts.map +1 -1
  124. package/local/daemon/components.js +64 -2
  125. package/local/daemon/components.js.map +1 -1
  126. package/local/daemon/host.d.ts.map +1 -1
  127. package/local/daemon/host.js +6 -2
  128. package/local/daemon/host.js.map +1 -1
  129. package/local/daemon/launch.d.ts +12 -4
  130. package/local/daemon/launch.d.ts.map +1 -1
  131. package/local/daemon/launch.js +49 -16
  132. package/local/daemon/launch.js.map +1 -1
  133. package/local/daemon/types.d.ts +9 -1
  134. package/local/daemon/types.d.ts.map +1 -1
  135. package/local/key-check.d.ts +20 -0
  136. package/local/key-check.d.ts.map +1 -0
  137. package/local/key-check.js +45 -0
  138. package/local/key-check.js.map +1 -0
  139. package/local/model-key-step.d.ts +63 -0
  140. package/local/model-key-step.d.ts.map +1 -0
  141. package/local/model-key-step.js +133 -0
  142. package/local/model-key-step.js.map +1 -0
  143. package/local/setup/prompt.d.ts.map +1 -1
  144. package/local/setup/prompt.js +22 -18
  145. package/local/setup/prompt.js.map +1 -1
  146. package/local/setup/wizard.d.ts +10 -0
  147. package/local/setup/wizard.d.ts.map +1 -1
  148. package/local/setup/wizard.js +40 -17
  149. package/local/setup/wizard.js.map +1 -1
  150. package/local/state/lock.d.ts.map +1 -1
  151. package/local/state/lock.js +123 -36
  152. package/local/state/lock.js.map +1 -1
  153. package/local/state/pidfile.d.ts +4 -0
  154. package/local/state/pidfile.d.ts.map +1 -1
  155. package/local/state/pidfile.js +12 -3
  156. package/local/state/pidfile.js.map +1 -1
  157. package/package.json +12 -9
  158. package/program.d.ts.map +1 -1
  159. package/program.js +10 -0
  160. package/program.js.map +1 -1
  161. package/resources/get.js +1 -1
  162. package/resources/get.js.map +1 -1
  163. package/resources/run/stream.d.ts.map +1 -1
  164. package/resources/run/stream.js +2 -1
  165. package/resources/run/stream.js.map +1 -1
  166. package/resources/stream/render-plaintext.d.ts +3 -0
  167. package/resources/stream/render-plaintext.d.ts.map +1 -1
  168. package/resources/stream/render-plaintext.js +20 -2
  169. package/resources/stream/render-plaintext.js.map +1 -1
  170. package/resources/usage.d.ts +8 -0
  171. package/resources/usage.d.ts.map +1 -1
  172. package/resources/usage.js +37 -0
  173. package/resources/usage.js.map +1 -1
  174. package/runtime.d.ts +9 -0
  175. package/runtime.d.ts.map +1 -1
  176. package/runtime.js +12 -1
  177. package/runtime.js.map +1 -1
  178. package/src/auth/browser.ts +57 -0
  179. package/src/auth/callback-server.ts +58 -22
  180. package/src/auth/device.ts +151 -0
  181. package/src/auth/index.ts +4 -3
  182. package/src/auth/login.ts +243 -67
  183. package/src/auth/oidc.ts +270 -0
  184. package/src/auth/token.ts +53 -90
  185. package/src/client/client.ts +4 -1
  186. package/src/client/current-organization.ts +27 -0
  187. package/src/commands/apikey/index.ts +85 -0
  188. package/src/commands/app-handover.ts +188 -0
  189. package/src/commands/auth/index.ts +16 -10
  190. package/src/commands/auth/login.ts +30 -23
  191. package/src/commands/auth/whoami.ts +16 -1
  192. package/src/commands/coding-agent.ts +33 -0
  193. package/src/commands/config/backend.ts +20 -6
  194. package/src/commands/embedding.ts +209 -0
  195. package/src/commands/example.ts +146 -0
  196. package/src/commands/help.ts +16 -3
  197. package/src/commands/load-test/burst.ts +291 -0
  198. package/src/commands/load-test/index.ts +183 -0
  199. package/src/commands/load-test/report.ts +302 -0
  200. package/src/commands/mcp-server.ts +5 -5
  201. package/src/commands/setup.ts +76 -2
  202. package/src/commands/up.ts +76 -10
  203. package/src/commands/usage.ts +55 -2
  204. package/src/config/config.ts +18 -8
  205. package/src/config/index.ts +1 -0
  206. package/src/config/resolve.ts +5 -3
  207. package/src/errors/classify.ts +10 -1
  208. package/src/errors/cli-exit-error.ts +6 -2
  209. package/src/errors/handle.ts +74 -8
  210. package/src/local/daemon/components.ts +66 -2
  211. package/src/local/daemon/host.ts +6 -2
  212. package/src/local/daemon/launch.ts +51 -16
  213. package/src/local/daemon/types.ts +9 -1
  214. package/src/local/key-check.ts +61 -0
  215. package/src/local/model-key-step.ts +164 -0
  216. package/src/local/setup/prompt.ts +22 -18
  217. package/src/local/setup/wizard.ts +45 -18
  218. package/src/local/state/lock.ts +116 -35
  219. package/src/local/state/pidfile.ts +14 -3
  220. package/src/program.ts +10 -0
  221. package/src/resources/get.ts +1 -1
  222. package/src/resources/run/stream.ts +2 -1
  223. package/src/resources/stream/render-plaintext.ts +20 -2
  224. package/src/resources/usage.ts +42 -0
  225. package/src/runtime.ts +17 -1
  226. package/auth/auth0.d.ts +0 -19
  227. package/auth/auth0.d.ts.map +0 -1
  228. package/auth/auth0.js +0 -39
  229. package/auth/auth0.js.map +0 -1
  230. package/src/auth/auth0.ts +0 -43
@@ -0,0 +1,61 @@
1
+ // Whether Anthropic takes a key, asked of Anthropic itself before the CLI
2
+ // calls the key ready: `stigmer up` and `stigmer setup` check the key the
3
+ // local runner will send, so a wrong key is said at the moment it is entered,
4
+ // not inside a first run (stigmer#3036).
5
+ //
6
+ // The rule is Stigmer Cloud's key check, outcome for outcome, so every edition
7
+ // gives a key the same three answers: `GET <base>/v1/models` with the key,
8
+ // 401 or 403 is rejected, a 2xx accepted, and anything else (another status, a
9
+ // timeout, a network fault, a proxy in the way) unchecked, which keeps the key
10
+ // and says so. A listing reads no billing and spends nothing, so a key with no
11
+ // credit passes; the run's own failure names that. The base is the one the
12
+ // runner sends the key to (ANTHROPIC_BASE_URL, else Anthropic's own API, the
13
+ // runner's endpoint rule in backend/services/runner/src/agent-proxy/lanes.ts),
14
+ // so a gateway's key is checked against the gateway. A redirect is never
15
+ // followed (a 3xx is unchecked), so the key reaches only the host the runner
16
+ // was given. The response body is never read and the key is never logged.
17
+
18
+ /** What Anthropic said about a key: took it, refused it, or did not answer. */
19
+ export type KeyCheck = "accepted" | "rejected" | "unchecked";
20
+
21
+ /** Anthropic's own API, where the runner sends a key when no base URL is set. */
22
+ export const ANTHROPIC_API_URL = "https://api.anthropic.com";
23
+
24
+ /** The API version the check asks for; the listing has been stable under it. */
25
+ const ANTHROPIC_VERSION = "2023-06-01";
26
+
27
+ /** How long the check waits before it calls the key unchecked. */
28
+ export const KEY_CHECK_TIMEOUT_MS = 10_000;
29
+
30
+ /** The fetch the check dials with; tests pass their own. */
31
+ export type KeyCheckFetch = (
32
+ url: string,
33
+ init: { headers: Record<string, string>; signal: AbortSignal; redirect: "manual" },
34
+ ) => Promise<{
35
+ readonly status: number;
36
+ }>;
37
+
38
+ /**
39
+ * Ask Anthropic (or the gateway at `baseUrl`) whether it takes `key`. Never
40
+ * throws: a fault of any kind is `unchecked`.
41
+ */
42
+ export async function checkAnthropicKey(
43
+ key: string,
44
+ baseUrl: string = "",
45
+ fetchImpl: KeyCheckFetch = fetch,
46
+ timeoutMs: number = KEY_CHECK_TIMEOUT_MS,
47
+ ): Promise<KeyCheck> {
48
+ const base = (baseUrl.trim() === "" ? ANTHROPIC_API_URL : baseUrl.trim()).replace(/\/+$/, "");
49
+ try {
50
+ const response = await fetchImpl(`${base}/v1/models`, {
51
+ headers: { "x-api-key": key, "anthropic-version": ANTHROPIC_VERSION },
52
+ signal: AbortSignal.timeout(timeoutMs),
53
+ redirect: "manual",
54
+ });
55
+ if (response.status === 401 || response.status === 403) return "rejected";
56
+ if (response.status >= 200 && response.status < 300) return "accepted";
57
+ return "unchecked";
58
+ } catch {
59
+ return "unchecked";
60
+ }
61
+ }
@@ -0,0 +1,164 @@
1
+ // The model key step `stigmer up` and `stigmer setup` share: which key the
2
+ // local runner will send to Anthropic and where, whether Anthropic takes it,
3
+ // and, on a terminal, asking for one when there is none or the saved one is
4
+ // refused. It says why first, the same words the console's key step says
5
+ // (sdk/react's provider-presentation.ts), so a person meets one explanation on
6
+ // every face.
7
+ //
8
+ // Only a key Stigmer can judge is checked: the key the runner sends on the
9
+ // "key" route, or to a gateway that was handed one. A gateway with no key, a
10
+ // cloud backend (Vertex, Bedrock, Foundry) or the proxy authenticates some
11
+ // other way, and stays as before. The key checked is the one the runner gets:
12
+ // an exported ANTHROPIC_API_KEY wins over the saved one (llm-config.ts), so
13
+ // an exported key Anthropic refuses is never prompted over (a pasted key
14
+ // would not reach the runner); one line says what to do instead.
15
+ //
16
+ // Nothing is asked off a terminal or under `--json` and `--quiet` (CLI-05):
17
+ // there the check still runs, and the card says what it found.
18
+
19
+ import type { Config } from "../config/config.js";
20
+ import { resolveApiKey, setLlm } from "./llm-config.js";
21
+ import { type KeyCheck, checkAnthropicKey } from "./key-check.js";
22
+ import { providerReach, type ReachEnv } from "./provider-reach.js";
23
+
24
+ /** Where a person gets an Anthropic key (the console's link says the same). */
25
+ export const ANTHROPIC_KEYS_URL = "https://console.anthropic.com/settings/keys";
26
+
27
+ /** Why Stigmer asks for the key, then where to get one: the prompt's first lines. */
28
+ export const KEY_REASON_LINES = [
29
+ "Your agents think with a model. Stigmer uses your own Anthropic key,",
30
+ `so you pay Anthropic directly. Get one at ${ANTHROPIC_KEYS_URL}`,
31
+ ] as const;
32
+
33
+ /** The prompt's own question. */
34
+ export const KEY_QUESTION = "Anthropic API key (Enter to skip)";
35
+
36
+ /** Cloud's sentence for a refused key, with what to do. */
37
+ export const KEY_REJECTED = "Anthropic rejected this key. Check that it is a valid, active API key";
38
+
39
+ /** Said on a terminal while a key already set is checked, which can take up to the check's timeout. */
40
+ export const KEY_CHECKING_SAVED = "Checking the Anthropic key with Anthropic…\n";
41
+
42
+ /** Said when Anthropic did not answer the check: the key is kept anyway. */
43
+ export const KEY_UNCHECKED = "Anthropic didn't answer, so the key is saved but not checked.";
44
+
45
+ /** Said once for an exported key Anthropic refuses, which no prompt can replace. */
46
+ export const ENV_KEY_REJECTED =
47
+ "Anthropic rejected the key in ANTHROPIC_API_KEY. Export a working key, or unset it and run stigmer setup.";
48
+
49
+ /** Where the runner sends an Anthropic key: the base its check dials, `""` for Anthropic's own API. */
50
+ export interface KeyTarget {
51
+ readonly baseUrl: string;
52
+ }
53
+
54
+ /**
55
+ * Where the runner with environment `env` sends its Anthropic key, or null
56
+ * when it sends none Stigmer can judge (no key, a cloud backend, the proxy,
57
+ * or a gateway with no key).
58
+ */
59
+ export function anthropicKeyTarget(env: ReachEnv): KeyTarget | null {
60
+ const anthropic = providerReach(env).find((entry) => entry.provider === "anthropic");
61
+ if (anthropic === undefined) return null;
62
+ const key = env.ANTHROPIC_API_KEY?.trim() ?? "";
63
+ if (key === "") return null;
64
+ if (anthropic.via === "key") return { baseUrl: "" };
65
+ if (anthropic.via === "gateway") return { baseUrl: env.ANTHROPIC_BASE_URL?.trim() ?? "" };
66
+ return null;
67
+ }
68
+
69
+ /** What the step needs from the outside world; the commands pass the real ones, tests their own. */
70
+ export interface KeyStepDeps {
71
+ /** The environment the runner inherits (the shell's). */
72
+ readonly env: NodeJS.ProcessEnv;
73
+ /** Whether a person is at a terminal to ask (both stdin and stderr a TTY, human output). */
74
+ readonly interactive: boolean;
75
+ readonly loadConfig: () => Config;
76
+ readonly saveConfig: (config: Config) => void;
77
+ readonly promptSecret: (question: string) => Promise<string>;
78
+ /** Where the step speaks: stderr, so stdout stays the card's. */
79
+ readonly write: (text: string) => void;
80
+ readonly check: (key: string, baseUrl: string) => Promise<KeyCheck>;
81
+ }
82
+
83
+ /** What the step found, for the card: the check's answer and whose key it was. */
84
+ export interface KeyStepOutcome {
85
+ readonly check: KeyCheck;
86
+ /** True when the key came from an exported ANTHROPIC_API_KEY, which the card's hint names. */
87
+ readonly fromEnvironment: boolean;
88
+ }
89
+
90
+ /** The environment the runner will get once `key` is the resolved Anthropic key. */
91
+ function withKey(env: NodeJS.ProcessEnv, key: string): ReachEnv {
92
+ return { ...env, ANTHROPIC_API_KEY: key };
93
+ }
94
+
95
+ /**
96
+ * Ask for a key until Anthropic takes it, does not answer, or the person
97
+ * presses Enter. Prints the reason and the link first, then one line per
98
+ * answer. Returns the key and its check, or undefined for a skip.
99
+ */
100
+ export async function askForKey(
101
+ deps: Pick<KeyStepDeps, "env" | "promptSecret" | "write" | "check">,
102
+ ): Promise<{ readonly key: string; readonly check: KeyCheck } | undefined> {
103
+ deps.write(`\n${KEY_REASON_LINES.join("\n")}\n\n`);
104
+ for (;;) {
105
+ const key = (await deps.promptSecret(KEY_QUESTION)).trim();
106
+ if (key === "") return undefined;
107
+ // The base a pasted key goes to is the one the shell already set.
108
+ const target = anthropicKeyTarget(withKey(deps.env, key));
109
+ if (target === null) return { key, check: "unchecked" };
110
+ deps.write("Checking with Anthropic… ");
111
+ const check = await deps.check(key, target.baseUrl);
112
+ if (check === "accepted") {
113
+ deps.write("✓ accepted\n");
114
+ return { key, check };
115
+ }
116
+ if (check === "unchecked") {
117
+ deps.write(`\n${KEY_UNCHECKED}\n`);
118
+ return { key, check };
119
+ }
120
+ deps.write(`\n✗ ${KEY_REJECTED}, then paste it again, or press Enter to skip.\n`);
121
+ }
122
+ }
123
+
124
+ /**
125
+ * `stigmer up`'s step, run before the daemon starts on a terminal (so a key
126
+ * entered here reaches the runner in this start) and beside the start off
127
+ * one. Returns the check's outcome, or undefined when no key Stigmer can
128
+ * judge is set (the card then says what it says today).
129
+ */
130
+ export async function modelKeyStep(deps: KeyStepDeps): Promise<KeyStepOutcome | undefined> {
131
+ const config = deps.loadConfig();
132
+ const key = resolveApiKey(config, deps.env);
133
+ const fromEnvironment = key !== "" && key === deps.env.ANTHROPIC_API_KEY;
134
+ const target = anthropicKeyTarget(withKey(deps.env, key));
135
+
136
+ let saved: KeyStepOutcome | undefined;
137
+ if (target !== null) {
138
+ // The check can take up to its timeout: a terminal says what it waits on.
139
+ if (deps.interactive) deps.write(KEY_CHECKING_SAVED);
140
+ const check = await deps.check(key, target.baseUrl);
141
+ saved = { check, fromEnvironment };
142
+ if (check !== "rejected") return saved;
143
+ if (fromEnvironment) {
144
+ if (deps.interactive) deps.write(`${ENV_KEY_REJECTED}\n`);
145
+ return saved;
146
+ }
147
+ if (!deps.interactive) return saved;
148
+ deps.write("\nAnthropic rejected the saved key.");
149
+ } else {
150
+ // Ask only where a key would make Anthropic reachable and nothing reaches
151
+ // it yet: not over a keyless gateway, a cloud backend or the proxy, not
152
+ // over an exported key, and never off a terminal.
153
+ const reached = providerReach(withKey(deps.env, key)).some((entry) => entry.provider === "anthropic");
154
+ const keyWouldServe = !reached && anthropicKeyTarget(withKey(deps.env, "sk-ant-probe")) !== null;
155
+ if (!deps.interactive || key !== "" || !keyWouldServe) return undefined;
156
+ }
157
+
158
+ const answer = await askForKey(deps);
159
+ if (answer === undefined) return saved;
160
+ // The same section `stigmer setup` writes, read by the launch that follows.
161
+ deps.saveConfig(setLlm(deps.loadConfig(), { provider: "anthropic", api_key: answer.key }));
162
+ deps.write("Saved for this computer's agents.\n\n");
163
+ return { check: answer.check, fromEnvironment: false };
164
+ }
@@ -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
 
package/src/program.ts CHANGED
@@ -30,6 +30,7 @@ import { registerGet } from "./commands/get.js";
30
30
  import { registerInstall } from "./commands/install.js";
31
31
  import { registerInternalDaemon } from "./commands/internal-daemon.js";
32
32
  import { registerList } from "./commands/list.js";
33
+ import { registerLoadTest } from "./commands/load-test/index.js";
33
34
  import { registerLogs } from "./commands/logs.js";
34
35
  import { registerMarketplace } from "./commands/marketplace.js";
35
36
  import { registerMcp } from "./commands/mcp.js";
@@ -52,6 +53,10 @@ import { registerUsage } from "./commands/usage.js";
52
53
  import { registerValidate } from "./commands/validate.js";
53
54
  import { registerVault } from "./commands/vault.js";
54
55
  import { registerVersion } from "./commands/version.js";
56
+ import { registerAppHandover } from "./commands/app-handover.js";
57
+ import { registerCodingAgent } from "./commands/coding-agent.js";
58
+ import { registerEmbedding } from "./commands/embedding.js";
59
+ import { registerExample } from "./commands/example.js";
55
60
  import { applyHelp } from "./commands/help.js";
56
61
  import { setActionCommand, setDebug, setStandalone } from "./runtime.js";
57
62
  import { commandPath } from "./command-tree.js";
@@ -88,6 +93,9 @@ export function buildProgram(): Command {
88
93
  registerRun(program);
89
94
  registerResume(program);
90
95
  registerRuns(program);
96
+ registerAppHandover(program);
97
+ registerCodingAgent(program);
98
+ registerLoadTest(program);
91
99
  // Your library
92
100
  registerGet(program);
93
101
  registerList(program);
@@ -102,6 +110,7 @@ export function buildProgram(): Command {
102
110
  registerVault(program);
103
111
  registerFile(program);
104
112
  registerConnect(program);
113
+ registerExample(program);
105
114
  // Packages
106
115
  registerPush(program);
107
116
  registerInstall(program);
@@ -121,6 +130,7 @@ export function buildProgram(): Command {
121
130
  registerAuth(program);
122
131
  registerApiKey(program);
123
132
  registerServiceAccount(program);
133
+ registerEmbedding(program);
124
134
  registerProviderKey(program);
125
135
  registerAccessHistory(program);
126
136
  registerUsage(program);
@@ -46,6 +46,6 @@ async function fetchOrganization(client: Stigmer, ref: ParsedReference): Promise
46
46
  return { schema: OrganizationSchema, message: await client.organization.get(ref.slug) };
47
47
  } catch (err) {
48
48
  if (!cannotSeeOrganization(err)) throw err;
49
- throw new CliExitError(`organization "${ref.slug}" not found`, ExitCode.NotFound);
49
+ throw new CliExitError(`organization "${ref.slug}" not found`, ExitCode.NotFound, undefined, { cause: err });
50
50
  }
51
51
  }