@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
package/src/auth/token.ts CHANGED
@@ -1,5 +1,13 @@
1
- // Auth0 token operations: exchange an authorization code for tokens, refresh an
2
- // expired access token, and expose token providers that refresh silently.
1
+ // Keeping a sign-in fresh: refresh an expired access token at the provider
2
+ // that issued it, and expose token providers that refresh silently.
3
+ //
4
+ // A signed-in entry (a `cloud` or `selfhost` backend that `stigmer auth login`
5
+ // wrote) keeps its token set beside the issuer and the native client it came
6
+ // from (`oidc_issuer`, `oidc_client_id`); a refresh reads that issuer's token
7
+ // endpoint from its discovery document and sends that client's id, so every
8
+ // server's sign-in refreshes the same way. An entry with no issuer (written by
9
+ // a CLI from before servers announced their sign-in) is not refreshed: the
10
+ // server refuses its stale token and the person is told to sign in again.
3
11
  //
4
12
  // Two providers share one refresh path (freshCloudToken), so they cannot drift:
5
13
  // - createRefreshingTokenProvider serves a short-lived command. It reads the
@@ -20,21 +28,15 @@ import {
20
28
  type Config,
21
29
  type NamedBackendConfig,
22
30
  activeBackend,
31
+ hasSignIn,
23
32
  load,
24
33
  save,
25
34
  } from "../config/index.js";
26
35
  import { DEFAULT_CLOUD_ENDPOINT } from "../config/resolve.js";
27
36
  import { CliExitError, ExitCode } from "../errors/index.js";
28
- import { CLIENT_ID, callbackUrl, TOKEN_URL } from "./auth0.js";
37
+ import { discover, postTokenForm, type TokenSet } from "./oidc.js";
29
38
 
30
- /** Normalized result of an Auth0 token endpoint call. */
31
- export interface TokenSet {
32
- readonly accessToken: string;
33
- /** Present when `offline_access` was granted; may rotate on refresh. */
34
- readonly refreshToken?: string;
35
- /** Absolute expiry as an RFC 3339 string, derived from `expires_in`. */
36
- readonly expiresAt?: string;
37
- }
39
+ export type { TokenSet } from "./oidc.js";
38
40
 
39
41
  // Refresh this many ms before the real expiry so an in-flight request never
40
42
  // races the token going stale.
@@ -46,49 +48,43 @@ const EXPIRY_SKEW_MS = 60_000;
46
48
  // picks up a new sign-in later.
47
49
  const NO_EXPIRY_REREAD_MS = 5 * 60_000;
48
50
 
49
- interface Auth0TokenResponse {
50
- access_token?: string;
51
- refresh_token?: string;
52
- expires_in?: number;
53
- error?: string;
54
- error_description?: string;
55
- }
56
-
57
- /** Exchange a PKCE authorization code for an access (+refresh) token. */
58
- export async function exchangeCode(params: {
59
- code: string;
60
- codeVerifier: string;
61
- }): Promise<TokenSet> {
62
- return postToken({
63
- grant_type: "authorization_code",
64
- client_id: CLIENT_ID,
65
- code: params.code,
66
- redirect_uri: callbackUrl(),
67
- code_verifier: params.codeVerifier,
68
- });
69
- }
70
-
71
- /** Exchange a refresh token for a fresh access token. */
72
- export async function refreshAccessToken(
73
- refreshToken: string,
74
- ): Promise<TokenSet> {
75
- return postToken({
51
+ /**
52
+ * Exchange a refresh token for a fresh access token at the provider the entry
53
+ * signed in with. An entry that names no provider cannot be refreshed.
54
+ */
55
+ export async function refreshAccessToken(entry: NamedBackendConfig, refreshToken: string): Promise<TokenSet> {
56
+ const issuer = entry.oidc_issuer;
57
+ const clientId = entry.oidc_client_id;
58
+ if (issuer === undefined || issuer === "" || clientId === undefined || clientId === "") {
59
+ throw new CliExitError("this sign-in names no provider to refresh it at", ExitCode.Auth, [
60
+ "Sign in again: stigmer auth login",
61
+ ]);
62
+ }
63
+ const { tokenEndpoint } = await discover(issuer);
64
+ return postTokenForm(tokenEndpoint, {
76
65
  grant_type: "refresh_token",
77
- client_id: CLIENT_ID,
66
+ client_id: clientId,
78
67
  refresh_token: refreshToken,
79
68
  });
80
69
  }
81
70
 
71
+ /** Whether a long-running source may serve this entry's sign-in. */
72
+ function servesSignIn(entry: NamedBackendConfig | undefined, endpoint: string): entry is NamedBackendConfig {
73
+ if (entry === undefined || cloudEndpoint(entry) !== endpoint) return false;
74
+ return entry.type === "cloud" || hasSignIn(entry);
75
+ }
76
+
82
77
  /**
83
78
  * A token provider for the backend client that keeps the access token fresh.
84
79
  *
85
80
  * Precedence and behavior, evaluated per request against the ACTIVE named
86
81
  * backend:
87
82
  * 1. STIGMER_API_KEY (env / bridged --api-key) wins and is never refreshed.
88
- * 2. selfhost backends return their stored api_key (no refresh machinery —
89
- * server-minted `stk_` tokens are opaque and live until deleted or
90
- * expired server-side); local returns null (no auth).
91
- * 3. A cloud backend's non-expired access token is returned as-is.
83
+ * 2. A selfhost backend with no sign-in returns its stored api_key (no
84
+ * refresh machinery — server-minted `stk_` tokens are opaque and live
85
+ * until deleted or expired server-side); local returns null (no auth).
86
+ * 3. A signed-in backend's (any cloud backend, or a selfhost one `stigmer
87
+ * auth login` signed in to) non-expired access token is returned as-is.
92
88
  * 4. An expired token with a refresh token is refreshed; the new token,
93
89
  * rotated refresh token, and expiry are set INTO THE ENTRY and patched
94
90
  * into that entry on disk, then returned. Calls made while a refresh is
@@ -109,7 +105,7 @@ export function createRefreshingTokenProvider(config: Config): TokenProvider {
109
105
 
110
106
  const { name, entry } = activeBackend(config);
111
107
  if (entry === undefined) return null;
112
- if (entry.type === "selfhost") return entry.api_key ?? null;
108
+ if (entry.type === "selfhost" && !hasSignIn(entry)) return entry.api_key ?? null;
113
109
 
114
110
  if (inFlight?.entry !== entry) {
115
111
  const endpoint = cloudEndpoint(entry);
@@ -128,14 +124,15 @@ export function createRefreshingTokenProvider(config: Config): TokenProvider {
128
124
 
129
125
  /**
130
126
  * The token source for a long-running process whose server dials one fixed
131
- * address: the cloud backend `backendName` at `endpoint`, as they were when
132
- * it started. Built on the SDK's token cache, so a token is kept until a
127
+ * address: the signed-in backend `backendName` at `endpoint`, as they were
128
+ * when it started. Built on the SDK's token cache, so a token is kept until a
133
129
  * minute before it expires, concurrent calls share one fetch, and a failed
134
130
  * fetch is not kept. Each fetch:
135
131
  * 1. reads the config file as it is now, so it sees a refresh, a rotated
136
132
  * refresh token or a login another command saved;
137
133
  * 2. answers null (no credential, never another backend's) when the entry
138
- * is gone, is no longer a cloud backend, or now points elsewhere;
134
+ * is gone, no longer holds a sign-in (a selfhost entry signed out), or
135
+ * now points elsewhere;
139
136
  * 3. otherwise refreshes the token when it is expired, persisting it as the
140
137
  * short-lived provider does;
141
138
  * 4. keeps a token with no usable expiry for {@link NO_EXPIRY_REREAD_MS}.
@@ -149,9 +146,7 @@ export function createRefreshingTokenProvider(config: Config): TokenProvider {
149
146
  export function createBackendTokenSource(backendName: string, endpoint: string): TokenCache {
150
147
  return createTokenCache(async () => {
151
148
  const entry = load().backends?.[backendName];
152
- if (entry === undefined || entry.type !== "cloud" || cloudEndpoint(entry) !== endpoint) {
153
- return null;
154
- }
149
+ if (!servesSignIn(entry, endpoint)) return null;
155
150
  const fresh = await freshCloudToken(entry, (next) =>
156
151
  persistRefreshedTokens(backendName, endpoint, next),
157
152
  );
@@ -164,21 +159,21 @@ export function createBackendTokenSource(backendName: string, endpoint: string):
164
159
  });
165
160
  }
166
161
 
167
- /** The address a cloud entry is dialed at: its own, else Stigmer Cloud's. */
162
+ /** The address an entry is dialed at: its own, else (a cloud entry) Stigmer Cloud's. */
168
163
  function cloudEndpoint(entry: NamedBackendConfig): string {
169
164
  return entry.endpoint !== undefined && entry.endpoint !== ""
170
165
  ? entry.endpoint
171
166
  : DEFAULT_CLOUD_ENDPOINT;
172
167
  }
173
168
 
174
- /** A cloud entry's access token and its stored expiry, if any. */
169
+ /** A signed-in entry's access token and its stored expiry, if any. */
175
170
  interface CloudToken {
176
171
  readonly accessToken: string;
177
172
  readonly expiresAt: string | undefined;
178
173
  }
179
174
 
180
175
  /**
181
- * The cloud entry's access token, refreshed first when it is missing or
176
+ * The entry's access token, refreshed first when it is missing or
182
177
  * expired and a refresh token is stored. A refresh sets the new token set into
183
178
  * `entry` and hands it to `persist`. A refused refresh (a revoked or expired
184
179
  * sign-in) answers the current token, if any: the server rejects it and the
@@ -197,7 +192,7 @@ async function freshCloudToken(
197
192
 
198
193
  let next: TokenSet;
199
194
  try {
200
- next = await refreshAccessToken(entry.refresh_token);
195
+ next = await refreshAccessToken(entry, entry.refresh_token);
201
196
  } catch {
202
197
  return current;
203
198
  }
@@ -208,14 +203,14 @@ async function freshCloudToken(
208
203
 
209
204
  /**
210
205
  * Write a refreshed token set into the file as it is on disk now, patching
211
- * only the token fields of `backendName`, and only while that entry is still
212
- * the cloud backend at `endpoint`: a backend removed or re-pointed meanwhile
213
- * is left as the person left it.
206
+ * only the token fields of `backendName`, and only while that entry still
207
+ * holds a sign-in for `endpoint`: a backend removed, signed out or re-pointed
208
+ * meanwhile is left as the person left it.
214
209
  */
215
210
  function persistRefreshedTokens(backendName: string, endpoint: string, next: TokenSet): void {
216
211
  const config = load();
217
212
  const entry = config.backends?.[backendName];
218
- if (entry === undefined || entry.type !== "cloud" || cloudEndpoint(entry) !== endpoint) return;
213
+ if (!servesSignIn(entry, endpoint)) return;
219
214
  applyTokenSet(entry, next);
220
215
  save(config);
221
216
  }
@@ -235,35 +230,3 @@ function isExpired(expiresAt: string | undefined): boolean {
235
230
  if (Number.isNaN(expiryMs)) return false;
236
231
  return Date.now() >= expiryMs - EXPIRY_SKEW_MS;
237
232
  }
238
-
239
- async function postToken(form: Record<string, string>): Promise<TokenSet> {
240
- let response: Response;
241
- try {
242
- response = await fetch(TOKEN_URL, {
243
- method: "POST",
244
- headers: { "content-type": "application/x-www-form-urlencoded" },
245
- body: new URLSearchParams(form).toString(),
246
- });
247
- } catch (err) {
248
- throw new CliExitError(
249
- `failed to reach the authentication server: ${(err as Error).message}`,
250
- ExitCode.Connection,
251
- );
252
- }
253
-
254
- const body = (await response.json().catch(() => ({}))) as Auth0TokenResponse;
255
- if (!response.ok || body.access_token === undefined) {
256
- const detail =
257
- body.error_description ?? body.error ?? `HTTP ${response.status}`;
258
- throw new CliExitError(`authentication failed: ${detail}`, ExitCode.Auth);
259
- }
260
-
261
- return {
262
- accessToken: body.access_token,
263
- refreshToken: body.refresh_token,
264
- expiresAt:
265
- body.expires_in !== undefined
266
- ? new Date(Date.now() + body.expires_in * 1000).toISOString()
267
- : undefined,
268
- };
269
- }
@@ -38,7 +38,7 @@ import {
38
38
  resolveToken,
39
39
  } from "../config/index.js";
40
40
  import { cannotConnect, CliExitError, ExitCode } from "../errors/index.js";
41
- import { type ServerAddress, setServerAddress } from "../runtime.js";
41
+ import { type ServerAddress, setServerAddress, setServerHelpProbe } from "../runtime.js";
42
42
 
43
43
  /** The composed backend client returned by {@link createBackendClient}. */
44
44
  export interface BackendClient {
@@ -114,6 +114,9 @@ export function createBackendClient(
114
114
  });
115
115
  return serverInfo;
116
116
  };
117
+ // A failure this server answers ends with its help line (errors/handle.ts),
118
+ // asked through the same probe so a run that already read it asks nothing.
119
+ setServerHelpProbe(() => probeServerInfo().then((info) => info.help));
117
120
 
118
121
  return {
119
122
  stigmer,
@@ -0,0 +1,27 @@
1
+ // The organization a command acts in, read whole: the one `--org`,
2
+ // `STIGMER_ORG` or the context names, or, on a server that holds one
3
+ // organization (the open-source edition), that one, since there nothing names
4
+ // it. The commands that read or change an organization's own settings
5
+ // (`stigmer embedding`, `stigmer app-handover`) need its record, not only a
6
+ // value to send.
7
+ import type { Organization } from "@stigmer/apis/ai/stigmer/tenancy/organization/v1/api_pb";
8
+ import type { Stigmer } from "@stigmer/client";
9
+ import { UsageError } from "../errors/usage-error.js";
10
+ import { myOrganizations } from "./organizations.js";
11
+ import { holdsOneOrganization } from "./single-org.js";
12
+
13
+ /** The organization `org` names, or the server's one when `org` is empty and it holds one. */
14
+ export async function currentOrganization(
15
+ stigmer: Pick<Stigmer, "organization" | "platform">,
16
+ org: string,
17
+ setItWith: readonly string[],
18
+ ): Promise<Organization> {
19
+ if (org !== "") return stigmer.organization.get(org);
20
+ if (await holdsOneOrganization(stigmer as Stigmer)) {
21
+ const [only] = await myOrganizations(stigmer);
22
+ if (only !== undefined) return only;
23
+ }
24
+ throw new UsageError(
25
+ "organization not set\n\nSet it with:\n" + setItWith.map((line) => ` ${line}`).join("\n"),
26
+ );
27
+ }
@@ -10,6 +10,12 @@
10
10
  // holds a role in, unless the CLI's own credential is limited to one, whose
11
11
  // organization it then takes.
12
12
  //
13
+ // `--save-to-env <path>` (not `--env-file`, which Node and tsx claim for
14
+ // themselves on a source run) appends `STIGMER_API_KEY=<key>` to that file instead of
15
+ // printing the key (made 0600 when new; refused before anything is created
16
+ // when the file already sets the variable), and prints only where it went, so
17
+ // a key made by a coding agent never passes through its transcript.
18
+ //
13
19
  // `--service-account <name>` creates the key for one of the organization's
14
20
  // service accounts instead of for the caller: the key speaks for the service
15
21
  // account, keeps working when the caller leaves, and works only in the
@@ -19,6 +25,8 @@
19
25
  // `STIGMER_ORG`, then the context), and the key needs a `--name` of its own.
20
26
 
21
27
  import { createHash } from "node:crypto";
28
+ import { accessSync, appendFileSync, constants, existsSync, readFileSync, writeFileSync } from "node:fs";
29
+ import { dirname, relative, resolve } from "node:path";
22
30
  import { create } from "@bufbuild/protobuf";
23
31
  import { timestampDate, timestampFromDate } from "@bufbuild/protobuf/wkt";
24
32
  import {
@@ -54,8 +62,12 @@ export interface ApiKeyCreateFlags extends OutputFlags {
54
62
  expiresIn?: string;
55
63
  boundOrg?: string;
56
64
  serviceAccount?: string;
65
+ saveToEnv?: string;
57
66
  }
58
67
 
68
+ /** The variable `--save-to-env` sets: the one the token routes `stigmer app-handover` writes read. */
69
+ export const ENV_FILE_VARIABLE = "STIGMER_API_KEY";
70
+
59
71
  export function registerApiKey(program: Command): void {
60
72
  const apikey = program
61
73
  .command("apikey")
@@ -75,6 +87,10 @@ export function registerApiKey(program: Command): void {
75
87
  "--service-account <name>",
76
88
  "create the key for this service account of the organization; it speaks for the service account, not for you",
77
89
  )
90
+ .option(
91
+ "--save-to-env <path>",
92
+ `append ${ENV_FILE_VARIABLE}=<key> to this file instead of printing the key (0600 when new)`,
93
+ )
78
94
  .action(async (options: ApiKeyCreateFlags, command: Command) => {
79
95
  await runCreate(options, command);
80
96
  });
@@ -93,6 +109,8 @@ async function runCreate(options: ApiKeyCreateFlags, command: Command): Promise<
93
109
  const expiresAt = resolveExpiry(options);
94
110
  const serviceAccount = options.serviceAccount?.trim() ?? "";
95
111
  if (serviceAccount !== "") refuseServiceAccountMisuse(options);
112
+ const envFile = options.saveToEnv?.trim() ?? "";
113
+ if (envFile !== "") refuseEnvFileThatSetsTheKey(envFile);
96
114
 
97
115
  const { connectBackend } = await import("../../backend.js");
98
116
  const client = connectBackend();
@@ -115,6 +133,11 @@ async function runCreate(options: ApiKeyCreateFlags, command: Command): Promise<
115
133
  });
116
134
 
117
135
  const format = readFormat(options);
136
+ if (envFile !== "") {
137
+ saveToEnvFile(envFile, created.spec?.keyHash ?? "");
138
+ process.stdout.write(renderSavedKey(created, serviceAccount, envFile, format));
139
+ return;
140
+ }
118
141
  if (format === "json") {
119
142
  process.stdout.write(renderProtoJson(ApiKeySchema, created));
120
143
  return;
@@ -146,6 +169,68 @@ function refuseServiceAccountMisuse(options: ApiKeyCreateFlags): void {
146
169
  }
147
170
  }
148
171
 
172
+ /**
173
+ * Refuse, before a key is made, a file the key could not be saved to (its
174
+ * folder missing or not writable), and one that already sets the variable: a
175
+ * second key would shadow or lose the first. A key made and then not saved
176
+ * would be live and shown to nobody.
177
+ */
178
+ export function refuseEnvFileThatSetsTheKey(path: string): void {
179
+ if (!existsSync(path)) {
180
+ const folder = dirname(resolve(path));
181
+ try {
182
+ accessSync(folder, constants.W_OK);
183
+ } catch {
184
+ throw new UsageError(`${path} cannot be written: ${folder} is missing or not writable\n\nNo key was created.`);
185
+ }
186
+ return;
187
+ }
188
+ try {
189
+ accessSync(path, constants.W_OK);
190
+ } catch {
191
+ throw new UsageError(`${path} is not writable\n\nNo key was created.`);
192
+ }
193
+ const setsIt = readFileSync(path, "utf8")
194
+ .split(/\r?\n/)
195
+ .some((line) => new RegExp(`^\\s*(export\\s+)?${ENV_FILE_VARIABLE}\\s*=`).test(line));
196
+ if (setsIt) {
197
+ throw new UsageError(
198
+ `${path} already sets ${ENV_FILE_VARIABLE}\n\n` +
199
+ "Keep that key, or remove its line and run this again. No key was created.",
200
+ );
201
+ }
202
+ }
203
+
204
+ /** Append the variable to the file, creating it readable by its owner alone. */
205
+ export function saveToEnvFile(path: string, key: string): void {
206
+ const line = `${ENV_FILE_VARIABLE}=${key}\n`;
207
+ if (!existsSync(path)) {
208
+ writeFileSync(path, line, { mode: 0o600 });
209
+ return;
210
+ }
211
+ const text = readFileSync(path, "utf8");
212
+ appendFileSync(path, text === "" || text.endsWith("\n") ? line : `\n${line}`);
213
+ }
214
+
215
+ /** What `--save-to-env` prints: where the key went, never the key. */
216
+ export function renderSavedKey(key: ApiKey, serviceAccount: string, path: string, format: OutputFormat): string {
217
+ const where = relative(process.cwd(), resolve(path)) || path;
218
+ const fields = {
219
+ id: key.metadata?.id ?? "",
220
+ name: key.metadata?.name ?? "",
221
+ ...(serviceAccount === "" ? {} : { serviceAccount }),
222
+ envFile: where,
223
+ variable: ENV_FILE_VARIABLE,
224
+ expires: formatExpiry(key),
225
+ };
226
+ if (format === "json") return `${JSON.stringify(fields, null, 2)}\n`;
227
+ const lines = [`API key created and saved as ${ENV_FILE_VARIABLE} in ${where}`, "", ` ID: ${fields.id}`];
228
+ if (fields.name !== "") lines.push(` Name: ${fields.name}`);
229
+ if (serviceAccount !== "") lines.push(` Speaks for: service account ${serviceAccount}`);
230
+ lines.push(` Expires: ${fields.expires}`, "", `Keep ${where} out of git; the key is shown nowhere else.`);
231
+ return `${lines.join("\n")}\n`;
232
+ }
233
+
149
234
  /** Resolve the service account by name, then create the key that speaks for it. */
150
235
  async function createForServiceAccount(
151
236
  stigmer: Stigmer,
@@ -0,0 +1,202 @@
1
+ // `stigmer app-handover --stack <stack> --agent <slug> [--write <dir>]` — the
2
+ // code that puts an agent's chat in your own app.
3
+ //
4
+ // Exactly what the console's agent page hands over on its In your app tab,
5
+ // from the one writer (`buildAppHandover`, `@stigmer/client`): for a server
6
+ // that signs people in, a token route for your backend (`GET
7
+ // /api/stigmer-token`, minted with an admin service account's key read from
8
+ // `STIGMER_API_KEY`, for the user your own `currentUser` names) and the chat
9
+ // component; for a server that trusts every caller (`stigmer up`), the
10
+ // development chat alone. Which one is the server's answer
11
+ // (`getServerInfo().authenticationRequired`), as the tab decides.
12
+ //
13
+ // The address written into the code is the backend's as a browser reaches
14
+ // it: `https://<host>` for a TLS endpoint (`:443` dropped), `http://<host>:<port>`
15
+ // for a plaintext one, since one port serves the browser's protocol and gRPC.
16
+ // Printed by default; `--write <dir>` writes the two files under dir (the
17
+ // handover's own paths, e.g. `app/api/stigmer-token/route.ts` and
18
+ // `components/StigmerAgentChat.tsx`), refusing to overwrite a file unless
19
+ // `--force`, and prints what to install: once for a Next.js app, which is
20
+ // one app, else for each file. The page the console offers to try the chat
21
+ // is not written: for a React app of its own it is `src/App.tsx`, which the
22
+ // app already has.
23
+
24
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
25
+ import { dirname, join, relative, resolve } from "node:path";
26
+ import type { Command } from "commander";
27
+ import type { AppHandover, AppHandoverFile, AppHandoverMode, AppHandoverStack } from "@stigmer/client";
28
+ import { ensureAuthenticated, resolveOrganization, resolveServerAddress } from "../config/index.js";
29
+ import { CliExitError, ExitCode, UsageError } from "../errors/index.js";
30
+ import { type OutputFlags, CommandResult, renderResult } from "../output/index.js";
31
+ import { VERSION } from "../version.js";
32
+ import { addResultFlags, globalOrg, resultFormat } from "./shared.js";
33
+
34
+ interface HandoverFlags extends OutputFlags {
35
+ stack?: string;
36
+ agent?: string;
37
+ write?: string;
38
+ force?: boolean;
39
+ }
40
+
41
+ const STACKS: readonly AppHandoverStack[] = ["nextjs", "node", "python", "go", "java"];
42
+ const SET_ORG_WITH = ["stigmer app-handover ... --org <org>", "stigmer config context set --org <org>"];
43
+ const RELEASE = /^\d+\.\d+\.\d+$/;
44
+
45
+ export function registerAppHandover(program: Command): void {
46
+ const command = program
47
+ .command("app-handover")
48
+ .description("print or write the token route and chat that put an agent's chat in your own app")
49
+ .requiredOption("--stack <stack>", `your backend: ${STACKS.join(", ")}`)
50
+ .requiredOption("--agent <slug>", "the agent the chat talks to")
51
+ .option("--write <dir>", "write the files under this folder (your app's root) instead of printing them")
52
+ .option("-f, --force", "with --write, overwrite files that are already there")
53
+ .action(async (options: HandoverFlags, cmd: Command) => {
54
+ const format = resultFormat(options);
55
+ const stack = parseStack(options.stack ?? "");
56
+ const [{ connectBackend }, { currentOrganization }, { buildAppHandover }] = await Promise.all([
57
+ import("../backend.js"),
58
+ import("../client/current-organization.js"),
59
+ import("@stigmer/client"),
60
+ ]);
61
+ const client = connectBackend();
62
+ ensureAuthenticated(client.config);
63
+ const organization = await currentOrganization(
64
+ client.stigmer,
65
+ resolveOrganization(client.config, globalOrg(cmd)),
66
+ SET_ORG_WITH,
67
+ );
68
+ const org = organization.metadata?.slug ?? "";
69
+ const agent = (options.agent ?? "").trim();
70
+ await requireAgent(client.stigmer, org, agent);
71
+ const info = await client.serverInfo();
72
+ const mode: AppHandoverMode = info.authenticationRequired === false ? "local" : "sign-in";
73
+ const handover = buildAppHandover({
74
+ mode,
75
+ stack,
76
+ baseUrl: browserBaseUrl(resolveServerAddress(client.config).address),
77
+ org,
78
+ agent,
79
+ sdkVersion: RELEASE.test(info.version) ? info.version : RELEASE.test(VERSION) ? VERSION : undefined,
80
+ });
81
+ if (options.write === undefined) {
82
+ process.stdout.write(printedHandover(handover, mode));
83
+ return;
84
+ }
85
+ renderResult(writeHandover(handover, mode, options.write, options.force === true), format);
86
+ });
87
+ addResultFlags(command);
88
+ }
89
+
90
+ /** The stack `--stack` names. */
91
+ export function parseStack(value: string): AppHandoverStack {
92
+ const stack = value.trim().toLowerCase().replace(/^next(\.js)?$/, "nextjs");
93
+ if ((STACKS as readonly string[]).includes(stack)) return stack as AppHandoverStack;
94
+ throw new UsageError(`unknown stack "${value}"\n\nUse --stack ${STACKS.join(", ")}.`);
95
+ }
96
+
97
+ /**
98
+ * The address a browser reaches a gRPC endpoint at: `https://host` for
99
+ * `:443`, `http://host:port` otherwise, and a loopback or unported host as
100
+ * the client dials it. Pure.
101
+ */
102
+ export function browserBaseUrl(endpoint: string): string {
103
+ const bare = endpoint.trim().replace(/^https?:\/\//i, "").replace(/\/+$/, "");
104
+ const match = /^(.*):(\d+)$/.exec(bare);
105
+ if (match === null) {
106
+ const host = bare.toLowerCase();
107
+ const loopback = host === "localhost" || host.startsWith("127.") || host === "[::1]";
108
+ return `${loopback ? "http" : "https"}://${bare}`;
109
+ }
110
+ const [, host, port] = match;
111
+ return port === "443" ? `https://${host}` : `http://${host}:${port}`;
112
+ }
113
+
114
+ /** The handover as text to read or paste: each file under its path, with what to install. Pure. */
115
+ export function printedHandover(handover: AppHandover, mode: AppHandoverMode): string {
116
+ const parts: string[] = [];
117
+ if (mode === "local") {
118
+ parts.push(
119
+ "This server trusts every caller, so this is the development chat: it sends no token.",
120
+ "To go live, run the agent on a server that signs people in, and run this again there.",
121
+ "",
122
+ );
123
+ }
124
+ filesOf(handover).forEach((file, index) => {
125
+ const install = handover.oneApp ? (index === 0 ? [`# install, once: ${file.install}`] : []) : [`# install: ${file.install.replace(/\n/g, "\n# ")}`];
126
+ parts.push(`# ${file.file}`, ...install, "", file.code.trimEnd(), "");
127
+ });
128
+ return `${parts.join("\n")}\n`;
129
+ }
130
+
131
+ /** Write the handover's files under `root`, refusing to overwrite unless `force`. */
132
+ export function writeHandover(handover: AppHandover, mode: AppHandoverMode, root: string, force: boolean): CommandResult {
133
+ const files = filesOf(handover);
134
+ const target = resolve(root);
135
+ const existing = files.map((f) => join(target, f.file)).filter((path) => existsSync(path));
136
+ if (existing.length > 0 && !force) {
137
+ throw new CliExitError(
138
+ `${existing.map(shown).join(", ")} ${existing.length === 1 ? "is" : "are"} already there`,
139
+ ExitCode.Usage,
140
+ ["Keep yours and print the code instead (drop --write), or overwrite with --force."],
141
+ );
142
+ }
143
+ for (const file of files) {
144
+ const path = join(target, file.file);
145
+ mkdirSync(dirname(path), { recursive: true });
146
+ writeFileSync(path, file.code);
147
+ }
148
+ const written = files.map((f) => shown(join(target, f.file)));
149
+ const result = CommandResult.success(`Wrote ${written.join(" and ")}`).withData({ mode, files: written });
150
+ if (handover.oneApp) {
151
+ result.hint(`Install, once: ${files[0].install}`);
152
+ } else {
153
+ for (const file of files) {
154
+ result.hint(
155
+ file.installLanguage === "xml"
156
+ ? `For ${file.file}: add the Maven dependency the printed handover names (drop --write to see it)`
157
+ : `For ${file.file}: ${file.install.split("\n")[0]}`,
158
+ );
159
+ }
160
+ }
161
+ if (mode === "sign-in") {
162
+ result
163
+ .hint("Replace currentUser in the route with your app's own sign-in.")
164
+ .hint(`Put the admin service account's key in STIGMER_API_KEY in ${handover.settingsFile ?? ".env"}, and keep that file out of git.`);
165
+ if (handover.readsSettingsFile === false) {
166
+ result.hint(
167
+ `Your backend reads these from its environment: load ${handover.settingsFile ?? ".env"} the way your framework does, or export them in the shell you start it from.`,
168
+ );
169
+ }
170
+ } else {
171
+ result.hint("This is the development chat: it sends no token, for a server that trusts every caller.");
172
+ }
173
+ return result;
174
+ }
175
+
176
+ function filesOf(handover: AppHandover): AppHandoverFile[] {
177
+ return handover.backend === undefined ? [handover.chat] : [handover.backend, handover.chat];
178
+ }
179
+
180
+ async function requireAgent(stigmer: import("@stigmer/client").Stigmer, org: string, slug: string): Promise<void> {
181
+ if (slug === "") throw new UsageError("--agent needs the agent's slug");
182
+ try {
183
+ await stigmer.agent.getByReference({ org, slug });
184
+ } catch (err) {
185
+ const { classify } = await import("../errors/index.js");
186
+ const { Code } = await import("@connectrpc/connect");
187
+ if (classify(err)?.code === Code.NotFound) {
188
+ throw new CliExitError(
189
+ `no agent "${slug}" in ${org}`,
190
+ ExitCode.NotFound,
191
+ ["See the organization's agents: stigmer list agents"],
192
+ { cause: err },
193
+ );
194
+ }
195
+ throw err;
196
+ }
197
+ }
198
+
199
+ function shown(path: string): string {
200
+ const rel = relative(process.cwd(), path);
201
+ return rel.startsWith("..") ? path : rel;
202
+ }