@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
@@ -1,6 +1,8 @@
1
1
  // `stigmer usage {session,agent,org}` — token, model and working-time reports
2
- // at three granularities — and `stigmer usage hours`, the organization's
3
- // agent hours against its plan. Thin handlers: validate flags, fetch the
2
+ // at three granularities — `stigmer usage hours`, the organization's agent
3
+ // hours against its plan, and `stigmer usage onboarding`, a platform
4
+ // operator's count of how far new organizations got on the journey from a
5
+ // first agent to their users. Thin handlers: validate flags, fetch the
4
6
  // report, render. The dates pass through as typed: the server reads a UTC
5
7
  // calendar day (the whole day, both bounds inclusive) or an RFC 3339
6
8
  // instant. Heavy modules are lazy-imported inside actions so `--help` stays
@@ -16,6 +18,7 @@ import { ensureAuthenticated, resolveOrganization } from "../config/index.js";
16
18
  import { UsageError } from "../errors/index.js";
17
19
  import type { OutputFlags } from "../output/index.js";
18
20
  import { globalOrg, readFormat } from "./shared.js";
21
+ import { CliExitError } from "../errors/cli-exit-error.js";
19
22
 
20
23
  interface UsageFlags extends OutputFlags {
21
24
  from?: string;
@@ -29,6 +32,16 @@ const TO_HELP = "end: a UTC day, inclusive (e.g. 2026-03-13), or an RFC 3339 ins
29
32
  export const AGENT_HOURS_NOT_SERVED =
30
33
  "This server does not count agent hours: they are a Stigmer Cloud plan's. `stigmer usage org` shows working time.";
31
34
 
35
+ /** What `usage onboarding` says to a caller who is no platform operator. */
36
+ export const ONBOARDING_NOT_PERMITTED = "Only a platform operator can read onboarding counts.";
37
+
38
+ /** What `usage onboarding` says on a server older than the count. */
39
+ export const ONBOARDING_NOT_SERVED =
40
+ "This server does not count onboarding yet: it is older than this command. Upgrade the server to read where newcomers stop.";
41
+
42
+ /** How many days `usage onboarding` counts when no --from is given: the last week, today included. */
43
+ const ONBOARDING_DEFAULT_DAYS = 7;
44
+
32
45
  export function registerUsage(program: Command): void {
33
46
  const usage = program.command("usage").description("view token and working-time usage reports");
34
47
 
@@ -54,6 +67,14 @@ export function registerUsage(program: Command): void {
54
67
  .option("-o, --output <format>", "output format: table, json, or yaml")
55
68
  .action((options: UsageFlags, command: Command) => runOrgUsage(options, command));
56
69
 
70
+ usage
71
+ .command("onboarding")
72
+ .description("view how far new organizations got, from a first agent to their users (platform operators)")
73
+ .option("--from <date>", `${FROM_HELP}; default: ${ONBOARDING_DEFAULT_DAYS - 1} days before --to`)
74
+ .option("--to <date>", `${TO_HELP}; default: today`)
75
+ .option("-o, --output <format>", "output format: table, json, or yaml")
76
+ .action((options: UsageFlags) => runOnboardingFunnel(options));
77
+
57
78
  usage
58
79
  .command("hours")
59
80
  .description("view the organization's agent hours against its plan (Stigmer Cloud)")
@@ -114,3 +135,35 @@ async function runAgentHours(options: UsageFlags, command: Command): Promise<voi
114
135
  const hours = await usage.getAgentHours(client.stigmer, org);
115
136
  process.stdout.write(usage.renderAgentHours(hours, readFormat(options)));
116
137
  }
138
+
139
+ async function runOnboardingFunnel(options: UsageFlags): Promise<void> {
140
+ const range = onboardingRange(options, new Date());
141
+ const [{ connectBackend }, usage, { isPermissionDenied, isUnimplemented }, { ExitCode }] = await Promise.all([
142
+ import("../backend.js"),
143
+ import("../resources/usage.js"),
144
+ import("@stigmer/client"),
145
+ import("@stigmer/client/exit-codes"),
146
+ ]);
147
+ const client = connectBackend();
148
+ ensureAuthenticated(client.config);
149
+
150
+ let funnel: Awaited<ReturnType<typeof usage.getOnboardingFunnel>>;
151
+ try {
152
+ funnel = await usage.getOnboardingFunnel(client.stigmer, range);
153
+ } catch (err) {
154
+ if (isPermissionDenied(err)) throw new CliExitError(ONBOARDING_NOT_PERMITTED, ExitCode.Auth, undefined, { cause: err });
155
+ if (isUnimplemented(err)) throw new CliExitError(ONBOARDING_NOT_SERVED, ExitCode.Usage, undefined, { cause: err });
156
+ throw err;
157
+ }
158
+ process.stdout.write(usage.renderOnboardingFunnel(funnel, range, readFormat(options)));
159
+ }
160
+
161
+ /** The window `usage onboarding` counts: as typed, else the last week to today (UTC days). */
162
+ export function onboardingRange(options: UsageFlags, now: Date): { readonly from: string; readonly to: string } {
163
+ const to = options.to ?? now.toISOString().slice(0, 10);
164
+ if (options.from !== undefined) return { from: options.from, to };
165
+ const end = /^\d{4}-\d{2}-\d{2}$/.test(to) ? Date.parse(`${to}T00:00:00Z`) : Date.parse(to);
166
+ if (Number.isNaN(end)) throw new UsageError(`--to "${to}" is not a UTC day (2026-11-07) or an RFC 3339 instant`);
167
+ const from = new Date(end - (ONBOARDING_DEFAULT_DAYS - 1) * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
168
+ return { from, to };
169
+ }
@@ -7,7 +7,7 @@
7
7
  // never clobbers either side's login state. Two names are reserved:
8
8
  // "local" (the managed daemon, never stored in the map — its endpoint and
9
9
  // no-auth posture are fixed) and "cloud" (where `stigmer auth login` lands
10
- // by default).
10
+ // when run from the local daemon, which has nothing to sign in to).
11
11
  //
12
12
  // The `backend.local` section (daemon/LLM/Temporal settings owned by the
13
13
  // local-mode modules) is carried through verbatim, so a save never drops a key
@@ -48,13 +48,14 @@ export const CLOUD_BACKEND_NAME = "cloud";
48
48
  * One named backend: endpoint + its own credentials. Property names are
49
49
  * snake_case to keep the YAML in the file's established dialect.
50
50
  *
51
- * Credential lanes by type:
52
- * - cloud: the OAuth token set (token / refresh_token / token_expiry),
53
- * written by `stigmer auth login` and rotated by the token provider.
54
- * - selfhost: `api_key` — a server-minted `stk_` token
55
- * (`stigmer apikey create`). Browser login against self-hosted
56
- * issuers is deliberately not modeled here; the API token is the
57
- * self-host credential story.
51
+ * Credentials, on any backend:
52
+ * - a sign-in: the OAuth token set (token / refresh_token / token_expiry)
53
+ * beside the issuer and the native client it came from (oidc_issuer /
54
+ * oidc_client_id), written by `stigmer auth login` from what the server
55
+ * announces and refreshed at that issuer by the token provider;
56
+ * - `api_key`: a server-minted `stk_` token (`stigmer apikey create`), set
57
+ * with `config backend add --api-key`. On a selfhost entry holding both,
58
+ * the sign-in is sent; a cloud entry sends only its sign-in.
58
59
  */
59
60
  export interface NamedBackendConfig {
60
61
  type: NamedBackendType;
@@ -64,6 +65,10 @@ export interface NamedBackendConfig {
64
65
  env_id?: string;
65
66
  refresh_token?: string;
66
67
  token_expiry?: string;
68
+ /** The issuer the sign-in came from, exactly as the server announced it. */
69
+ oidc_issuer?: string;
70
+ /** The public native client the sign-in used at that issuer. */
71
+ oidc_client_id?: string;
67
72
  api_key?: string;
68
73
  }
69
74
 
@@ -211,6 +216,11 @@ export function activeBackend(config: Config): {
211
216
  return { name, entry };
212
217
  }
213
218
 
219
+ /** Whether an entry holds a sign-in's token set (as opposed to an API key or nothing). */
220
+ export function hasSignIn(entry: NamedBackendConfig): boolean {
221
+ return (entry.token !== undefined && entry.token !== "") || (entry.refresh_token !== undefined && entry.refresh_token !== "");
222
+ }
223
+
214
224
  /** True when the active backend is Stigmer Cloud. */
215
225
  export function isCloudMode(config: Config): boolean {
216
226
  return activeBackend(config).entry?.type === "cloud";
@@ -12,6 +12,7 @@ export {
12
12
  activeBackend,
13
13
  activeBackendName,
14
14
  getDefault,
15
+ hasSignIn,
15
16
  isCloudMode,
16
17
  load,
17
18
  save,
@@ -4,7 +4,8 @@
4
4
  //
5
5
  // All resolvers read the ACTIVE named backend (config.ts): local is the
6
6
  // managed daemon (fixed endpoint, never requires auth), cloud entries carry
7
- // the OAuth token set, selfhost entries carry an endpoint + api_key.
7
+ // a sign-in's token set, selfhost entries an endpoint and a sign-in or an
8
+ // api_key.
8
9
 
9
10
  import { CliExitError, ExitCode } from "../errors/index.js";
10
11
  import { SERVER_PORT } from "../local/constants.js";
@@ -66,7 +67,7 @@ export function resolveServerAddress(config: Config): ServerAddress {
66
67
  /**
67
68
  * Resolve the auth token.
68
69
  * STIGMER_API_KEY (env, also where the --api-key global is bridged)
69
- * > the active entry's credential (cloud: login token; selfhost: api_key)
70
+ * > the active entry's credential (its sign-in's token; else a selfhost api_key)
70
71
  * > "" (unauthenticated)
71
72
  */
72
73
  export function resolveToken(config: Config): string {
@@ -78,7 +79,8 @@ export function resolveToken(config: Config): string {
78
79
  if (entry === undefined) {
79
80
  return "";
80
81
  }
81
- return (entry.type === "cloud" ? entry.token : entry.api_key) ?? "";
82
+ if (entry.token !== undefined && entry.token !== "") return entry.token;
83
+ return (entry.type === "selfhost" ? entry.api_key : undefined) ?? "";
82
84
  }
83
85
 
84
86
  /**
@@ -76,8 +76,17 @@ export function classify(err: unknown): CliError | null {
76
76
 
77
77
  // Local errors that carry their own exit code (UsageError, auth-required,
78
78
  // etc.) are passed through verbatim, including any remediation hints.
79
+ // One that says a server's refusal in the command's own words keeps the
80
+ // refusal's status, so it still reads as the server's answer.
79
81
  if (err instanceof CliExitError) {
80
- return { exitCode: err.exitCode, message: err.message, hints: err.hints, cause: err };
82
+ const answered = err.cause === undefined ? undefined : extractCoded(err.cause);
83
+ return {
84
+ exitCode: err.exitCode,
85
+ message: err.message,
86
+ hints: err.hints,
87
+ cause: err,
88
+ ...(answered === undefined ? {} : { code: answered.code }),
89
+ };
81
90
  }
82
91
 
83
92
  const coded = extractCoded(err);
@@ -2,13 +2,17 @@
2
2
  // classify() passes these through verbatim, so command code can fail fast with
3
3
  // a precise exit code (e.g. "auth required" -> 4) without round-tripping to the
4
4
  // server. UsageError is the common specialization (exit 2).
5
+ //
6
+ // A command that says a server's refusal in its own words passes the refusal
7
+ // as `cause`: classify() then keeps its RPC status, so the failure still
8
+ // reads as the server's answer (its help line, its debug code).
5
9
 
6
10
  export class CliExitError extends Error {
7
11
  readonly exitCode: number;
8
12
  readonly hints?: readonly string[];
9
13
 
10
- constructor(message: string, exitCode: number, hints?: readonly string[]) {
11
- super(message);
14
+ constructor(message: string, exitCode: number, hints?: readonly string[], options?: { readonly cause?: unknown }) {
15
+ super(message, options);
12
16
  this.name = "CliExitError";
13
17
  this.exitCode = exitCode;
14
18
  this.hints = hints;
@@ -1,16 +1,35 @@
1
1
  // The single exit point for command-level errors: classify, print to stderr,
2
2
  // and exit with the mapped code.
3
+ //
4
+ // A failure the server answered (a refusal, a not-found, a denied call) ends
5
+ // with the server's help line when its operator set one: "Stuck? <words>:
6
+ // <address>". It is asked of the server once, bounded, and only then: a
7
+ // server that could not be reached, a request that timed out and a refusal
8
+ // the CLI made itself ask nothing, so a failure never waits on a server
9
+ // that is down.
3
10
 
4
- import { isDebug } from "../runtime.js";
5
- import { type CliError, classify, codeName } from "./classify.js";
11
+ import { Code } from "@connectrpc/connect";
12
+ import { isDebug, serverHelpProbe } from "../runtime.js";
13
+ import { type CliError, classify, codeName, isTransportFailure } from "./classify.js";
6
14
  import { ExitCode } from "@stigmer/client/exit-codes";
15
+ import { printableCell } from "../output/printable.js";
16
+
17
+ /** How long a failure waits for the server's help link before printing without it. */
18
+ export const HELP_PROBE_TIMEOUT_MS = 1_000;
19
+
20
+ /** Where the server says to ask for help, as the failure's last line prints it. */
21
+ export interface ServerHelp {
22
+ readonly url: string;
23
+ readonly label: string;
24
+ }
7
25
 
8
26
  /**
9
- * Render a CliError for stderr. In debug mode it appends the raw error chain
10
- * and numeric gRPC code. Returns "" when there is nothing to print (a clean
11
- * local cancellation), so the caller writes nothing.
27
+ * Render a CliError for stderr. A server's help link, when given, is the
28
+ * last line before the debug block. In debug mode it appends the raw error
29
+ * chain and numeric gRPC code. Returns "" when there is nothing to print (a
30
+ * clean local cancellation), so the caller writes nothing.
12
31
  */
13
- export function formatError(error: CliError, debugMode: boolean): string {
32
+ export function formatError(error: CliError, debugMode: boolean, help?: ServerHelp): string {
14
33
  const lines: string[] = [];
15
34
 
16
35
  if (error.message !== "") {
@@ -22,6 +41,11 @@ export function formatError(error: CliError, debugMode: boolean): string {
22
41
  lines.push(...error.hints);
23
42
  }
24
43
 
44
+ if (help !== undefined && error.message !== "") {
45
+ lines.push("");
46
+ lines.push(helpLine(help));
47
+ }
48
+
25
49
  if (debugMode && error.cause !== undefined) {
26
50
  lines.push("");
27
51
  lines.push("--- debug ---");
@@ -34,18 +58,60 @@ export function formatError(error: CliError, debugMode: boolean): string {
34
58
  return lines.length > 0 ? lines.join("\n") + "\n" : "";
35
59
  }
36
60
 
61
+ /**
62
+ * The help line as a terminal prints it: the server's words and address on
63
+ * one line, with no control or escape sequence (the server's text reaches
64
+ * the terminal only through output/printable.ts).
65
+ */
66
+ export function helpLine(help: ServerHelp): string {
67
+ return `Stuck? ${printableCell(help.label)}: ${printableCell(help.url)}`;
68
+ }
69
+
70
+ /**
71
+ * Whether a classified failure is a server's answer: it carries an RPC
72
+ * status, and it is neither a request that never reached a server nor one
73
+ * that ran out of time (where asking the server again would wait again).
74
+ */
75
+ export function isServerAnswer(error: CliError): boolean {
76
+ if (error.code === undefined || error.code === Code.DeadlineExceeded) return false;
77
+ if (error.code === Code.Unavailable && isTransportFailure(error.cause?.message ?? "", error.cause)) return false;
78
+ return true;
79
+ }
80
+
81
+ /**
82
+ * The dialled server's help link for a failure it answered, or undefined:
83
+ * when the failure is not the server's, when no client was made, when the
84
+ * server set none, when asking fails, and when the answer takes longer
85
+ * than {@link HELP_PROBE_TIMEOUT_MS}.
86
+ */
87
+ export async function serverHelpFor(error: CliError, timeoutMs = HELP_PROBE_TIMEOUT_MS): Promise<ServerHelp | undefined> {
88
+ const probe = serverHelpProbe();
89
+ if (probe === undefined || !isServerAnswer(error)) return undefined;
90
+ let timer: NodeJS.Timeout | undefined;
91
+ const timeout = new Promise<undefined>((resolve) => {
92
+ timer = setTimeout(() => resolve(undefined), timeoutMs);
93
+ timer.unref();
94
+ });
95
+ try {
96
+ return await Promise.race([probe().catch(() => undefined), timeout]);
97
+ } finally {
98
+ clearTimeout(timer);
99
+ }
100
+ }
101
+
37
102
  /**
38
103
  * Classify the error, print a user-facing message to stderr, and exit with the
39
104
  * appropriate code. The debug flag is read from process-global runtime state
40
105
  * (set from `--debug`), so callers never thread it through.
41
106
  */
42
- export function handle(error: unknown): never {
107
+ export async function handle(error: unknown): Promise<never> {
43
108
  const classified = classify(error);
44
109
  if (classified === null) {
45
110
  process.exit(ExitCode.Success);
46
111
  }
47
112
 
48
- const rendered = formatError(classified, isDebug());
113
+ const help = await serverHelpFor(classified);
114
+ const rendered = formatError(classified, isDebug(), help);
49
115
  if (rendered !== "") {
50
116
  process.stderr.write(rendered);
51
117
  }
@@ -6,11 +6,18 @@
6
6
  // load-bearing env explicitly (ports, queues, db/storage paths) rather than
7
7
  // relying on its compiled defaults makes the launch deterministic and the pin
8
8
  // enforceable.
9
+ //
10
+ // Both children gate the start and are critical while it runs: the server on
11
+ // its gRPC port, the runner on its readiness marker. A runner that ends or
12
+ // stays silent before it polls fails the start as a server does, so `stigmer
13
+ // up` never reports a stack that cannot run anything (stigmer#1629). After
14
+ // the start, a runner crash is the supervisor's to restart, as before.
9
15
 
10
16
  import { dirname, join } from "node:path";
17
+ import { setTimeout as delay } from "node:timers/promises";
11
18
  import { RUNNER_TASK_QUEUE, RUNNER_READY_MARKER, SERVER_PID_FILE, RUNNER_PID_FILE, SERVER_PORT, TEMPORAL_NAMESPACE } from "../constants.js";
12
19
  import { ARTIFACTS_SUBDIR } from "../paths.js";
13
- import { waitForTcp } from "../net/tcp.js";
20
+ import { describeExit, waitForTcp } from "../net/tcp.js";
14
21
  import { type ProviderReach, providerReach, runnerProvidersValue } from "../provider-reach.js";
15
22
  import type { DaemonConfig } from "./env.js";
16
23
  import type { ComponentSpec, ReadinessGate } from "./types.js";
@@ -26,9 +33,34 @@ const RUNNER_EXIT_MARGIN_MS = 2_000;
26
33
  /** How long the server has to open its gRPC port before startup aborts. */
27
34
  const SERVER_GATE_TIMEOUT_MS = 30_000;
28
35
 
36
+ /**
37
+ * How long the runner has, once spawned, to announce it is polling before
38
+ * startup aborts. Well above a cold start on a developer laptop, so only a
39
+ * runner that is stuck, not slow, fails the start.
40
+ */
41
+ export const RUNNER_GATE_TIMEOUT_MS = 120_000;
42
+
43
+ /** How often a gate looks at the child it waits on (the server gate's pace). */
44
+ const GATE_POLL_MS = 150;
45
+
29
46
  /** The server's setting naming the providers its runners reach (the server's `boot/config.ts`). */
30
47
  export const RUNNER_PROVIDERS_ENV = "STIGMER_RUNNER_PROVIDERS";
31
48
 
49
+ /** The server's two help settings (the server's `boot/help-link.ts`). */
50
+ export const HELP_URL_ENV = "STIGMER_HELP_URL";
51
+ export const HELP_LABEL_ENV = "STIGMER_HELP_LABEL";
52
+
53
+ /**
54
+ * Where a person running Stigmer on their own laptop asks for help: the
55
+ * project's community chat (the README's Discord). A laptop has no operator
56
+ * to name one, so `stigmer up` names the project's own; a self-hosted server
57
+ * announces only what its operator sets.
58
+ */
59
+ export const COMMUNITY_HELP = {
60
+ url: "https://discord.com/invite/EtANnfsJ8B",
61
+ label: "Ask the Stigmer community",
62
+ } as const;
63
+
32
64
  /**
33
65
  * Environment for the `stigmer-server` child. Pins ports, Temporal coordinates,
34
66
  * the runner task queue, and the db/storage paths to the ~/.stigmer layout.
@@ -71,6 +103,14 @@ export function buildServerEnv(
71
103
  if (reach !== undefined && base[RUNNER_PROVIDERS_ENV] === undefined) {
72
104
  env[RUNNER_PROVIDERS_ENV] = runnerProvidersValue(reach);
73
105
  }
106
+ // Where the person asks for help (the console's sidebar and failures, the
107
+ // CLI's refused commands): the project's community, unless the person
108
+ // exported either setting themselves, an empty one included (it declares
109
+ // "none"), as RUNNER_PROVIDERS_ENV's rule above.
110
+ if (base[HELP_URL_ENV] === undefined && base[HELP_LABEL_ENV] === undefined) {
111
+ env[HELP_URL_ENV] = COMMUNITY_HELP.url;
112
+ env[HELP_LABEL_ENV] = COMMUNITY_HELP.label;
113
+ }
74
114
  return env;
75
115
  }
76
116
 
@@ -170,7 +210,7 @@ export function buildComponents(
170
210
  components.push({
171
211
  name: "runner",
172
212
  pidFile: join(config.dataDir, RUNNER_PID_FILE),
173
- critical: false,
213
+ critical: true,
174
214
  resolve: () => ({
175
215
  name: "runner",
176
216
  command: runner.nodeBin,
@@ -180,10 +220,34 @@ export function buildComponents(
180
220
  logFile: join(config.logDir, "runner.log"),
181
221
  readinessMarker: RUNNER_READY_MARKER,
182
222
  }),
223
+ gate: runnerGate(),
183
224
  });
184
225
  return components;
185
226
  }
186
227
 
228
+ /**
229
+ * The runner is ready once it has written its readiness marker; fail fast,
230
+ * with how it ended, if it exits first, and at `timeoutMs` if it never
231
+ * announces. It reads the handle and registers nothing, as `ReadinessGate`
232
+ * requires, and keeps wall time as the server gate does; a test passes a
233
+ * short deadline.
234
+ */
235
+ export function runnerGate(timeoutMs: number = RUNNER_GATE_TIMEOUT_MS): ReadinessGate {
236
+ return {
237
+ description: "runner polling for tasks",
238
+ wait: async (handle) => {
239
+ const deadline = Date.now() + timeoutMs;
240
+ for (;;) {
241
+ if (handle.isReady()) return;
242
+ const exit = handle.exitInfo();
243
+ if (exit !== null) throw new Error(`the runner ${describeExit(exit)} before it was ready`);
244
+ if (Date.now() >= deadline) throw new Error(`the runner did not report ready within ${timeoutMs / 1000} s`);
245
+ await delay(GATE_POLL_MS);
246
+ }
247
+ },
248
+ };
249
+ }
250
+
187
251
  // The server is ready once its gRPC port accepts a connection; fail fast, with
188
252
  // how it ended, if it exits first. The error is recorded under the component's
189
253
  // name, so it speaks of "the server".
@@ -78,11 +78,14 @@ export class NodeProcessHost implements ProcessHost {
78
78
  out.write(chunk);
79
79
  mirrorStdout(chunk);
80
80
  if (marker !== undefined && !ready) {
81
- tail = (tail + chunk.toString("utf8")).slice(-Math.max(marker.length * 2, 256));
82
- if (tail.includes(marker)) {
81
+ // Search the whole chunk before trimming: the runner writes a long
82
+ // line right after its marker, often in the same chunk (stigmer#1629).
83
+ const window = tail + chunk.toString("utf8");
84
+ if (window.includes(marker)) {
83
85
  ready = true;
84
86
  readyCb?.();
85
87
  }
88
+ tail = window.slice(-marker.length);
86
89
  }
87
90
  });
88
91
  child.stderr?.on("data", (chunk: Buffer) => {
@@ -126,6 +129,7 @@ export class NodeProcessHost implements ProcessHost {
126
129
  pid,
127
130
  hasExited: () => exitInfo !== null,
128
131
  exitInfo: () => exitInfo,
132
+ isReady: () => ready,
129
133
  stderrTail: () => [...stderrTail],
130
134
  onExit: (cb) => {
131
135
  exitCb = cb;
@@ -6,15 +6,17 @@
6
6
  // server launch, runner entry) so failures surface with a clear message before
7
7
  // anything long-lived starts. The detached shape then re-execs this same CLI
8
8
  // as the hidden `internal-daemon` and waits until the server's gRPC port
9
- // answers; the foreground shape calls the same daemon body in-process, which
10
- // is what a container entrypoint, a systemd unit or a tmux pane wants: one
11
- // process to watch, signals delivered to it, the stack's output on its stdio.
9
+ // answers and, when the stack has a runner, until the daemon records the
10
+ // runner ready (stigmer#1629); the foreground shape calls the same daemon
11
+ // body in-process, which is what a container entrypoint, a systemd unit or a
12
+ // tmux pane wants: one process to watch, signals delivered to it, the stack's
13
+ // output on its stdio.
12
14
  //
13
15
  // When the stack does not start, both shapes say why from the daemon's own
14
- // record, the health snapshot `stigmer status` reads: which component failed,
15
- // how, and its last stderr lines (stigmer#1845). The detached shape watches
16
- // the daemon for the whole wait, so a start that has given up is reported at
17
- // once, not when the wait runs out.
16
+ // record, the health snapshot `stigmer status` reads: which component failed
17
+ // (the runner among them), how, and its last stderr lines (stigmer#1845). The
18
+ // detached shape watches the daemon for the whole wait, so a start that has
19
+ // given up is reported at once, not when the wait runs out.
18
20
  //
19
21
  // A running stack is never touched by `up`: it refuses while the daemon on
20
22
  // record lives, and sweeps only a dead daemon's leftovers. `down` reports a
@@ -26,6 +28,7 @@ import { spawn } from "node:child_process";
26
28
  import { mkdirSync, openSync } from "node:fs";
27
29
  import { homedir } from "node:os";
28
30
  import { join } from "node:path";
31
+ import { setTimeout as delay } from "node:timers/promises";
29
32
  import { type Config, load as loadConfig } from "../../config/config.js";
30
33
  import { log } from "../../logger.js";
31
34
  import { CliExitError } from "../../errors/cli-exit-error.js";
@@ -44,7 +47,7 @@ import { ensureRunner } from "../runtime/runner.js";
44
47
  import { ensureServer } from "../runtime/server.js";
45
48
  import { TemporalManager } from "../temporal/manager.js";
46
49
  import type { ProviderReach } from "../provider-reach.js";
47
- import { localRunnerReach } from "./components.js";
50
+ import { localRunnerReach, RUNNER_GATE_TIMEOUT_MS } from "./components.js";
48
51
  import { buildDaemonEnv, type DaemonEnvInputs, readDaemonConfig } from "./env.js";
49
52
  import { NodeProcessHost, type OutputMirror } from "./host.js";
50
53
  import { type InternalDaemonDeps, runInternalDaemon } from "./process.js";
@@ -53,9 +56,18 @@ import { GRACEFUL_STOP_TIMEOUT_MS } from "./supervisor.js";
53
56
 
54
57
  /** How long `up` waits for the server's gRPC port after spawning the daemon. */
55
58
  const READY_TIMEOUT_MS = 60_000;
59
+ /**
60
+ * How long `up` waits, once the server answers, for the daemon to record the
61
+ * runner ready: the daemon's own runner gate, plus room for the teardown that
62
+ * follows a failed gate, so the launcher never gives up while the daemon is
63
+ * still deciding.
64
+ */
65
+ const RUNNER_READY_TIMEOUT_MS = RUNNER_GATE_TIMEOUT_MS + 30_000;
66
+ /** How often `up` reads the daemon's record while it waits for the runner. */
67
+ const RUNNER_READY_POLL_MS = 250;
56
68
  /** The components whose failure stops the stack, in start order: the first
57
69
  * one recorded failed is the one a failed start names. */
58
- const CRITICAL_COMPONENTS = ["temporal", "stigmer-server"] as const;
70
+ const CRITICAL_COMPONENTS = ["temporal", "stigmer-server", "runner"] as const;
59
71
  /** How long `down` waits for graceful daemon exit before force-killing. */
60
72
  const STOP_TIMEOUT_MS = 15_000;
61
73
  const STOP_POLL_MS = 500;
@@ -92,7 +104,7 @@ export async function up(options: UpOptions = {}, home: string = homedir()): Pro
92
104
  log.info("daemon process started", { pid: daemonPid });
93
105
 
94
106
  /* v8 ignore next -- @preserve: up() spawns the real daemon, which no unit test starts; waitForStack has its own tests, and the cli-up lane runs this end to end */
95
- await waitForStack({ data, logs, daemonPid });
107
+ await waitForStack({ data, logs, daemonPid, runner: options.serverOnly !== true });
96
108
 
97
109
  saveStartupConfig(data, buildStartupConfig(data, logs, temporalAddress, daemonPid, options));
98
110
  /* v8 ignore next -- @preserve: up() spawns the real daemon, which no unit test starts; the cli-up lane's smoke-getting-started runs it end to end, and upReport has its own tests */
@@ -104,17 +116,24 @@ export interface StackWait {
104
116
  data: string;
105
117
  logs: string;
106
118
  daemonPid: number;
119
+ /** Whether the stack starts a runner; the wait then lasts until the daemon records it ready. */
120
+ runner: boolean;
107
121
  /** Default SERVER_PORT; injectable for tests. */
108
122
  port?: number;
109
123
  /** Default READY_TIMEOUT_MS; injectable for tests. */
110
124
  timeoutMs?: number;
125
+ /** Default RUNNER_READY_TIMEOUT_MS; injectable for tests. */
126
+ runnerTimeoutMs?: number;
111
127
  }
112
128
 
113
129
  /**
114
- * Wait until the server answers, watching the daemon the whole time: the
115
- * daemon exits as soon as a critical component fails, so its exit ends the
116
- * wait at once, with the reason it recorded. Throws the failure, or, with no
117
- * record, says the daemon died (its log has the rest) or that the wait ran out.
130
+ * Wait until the server answers and, with a runner, until this daemon's record
131
+ * shows the runner ready, watching the daemon the whole time: the daemon exits
132
+ * as soon as a critical component fails, so its exit ends the wait at once,
133
+ * with the reason it recorded. Only that exit ends it: a runner recorded
134
+ * failed while the daemon still stops the stack is not yet a stopped stack.
135
+ * Throws the failure, or, with no record, says the daemon died (its log has
136
+ * the rest) or that the wait ran out.
118
137
  */
119
138
  export async function waitForStack(wait: StackWait): Promise<void> {
120
139
  const { data, logs, daemonPid } = wait;
@@ -125,6 +144,7 @@ export async function waitForStack(wait: StackWait): Promise<void> {
125
144
  label: "stigmer-server",
126
145
  getExit: () => (isProcessAlive(daemonPid) ? null : { code: null, signal: null }),
127
146
  });
147
+ if (wait.runner) await waitForRunnerReady(data, daemonPid, wait.runnerTimeoutMs ?? RUNNER_READY_TIMEOUT_MS);
128
148
  } catch (err) {
129
149
  const failure = startupFailure(data, daemonPid);
130
150
  if (failure !== null) throw failure;
@@ -137,6 +157,20 @@ export async function waitForStack(wait: StackWait): Promise<void> {
137
157
  }
138
158
  }
139
159
 
160
+ // Poll this daemon's record until it shows the runner ready. The daemon writes
161
+ // that once its start is done, right after the runner passes its gate.
162
+ async function waitForRunnerReady(data: string, daemonPid: number, timeoutMs: number): Promise<void> {
163
+ const path = join(data, HEALTH_STATE_FILE);
164
+ const deadline = Date.now() + timeoutMs;
165
+ while (Date.now() < deadline) {
166
+ const snapshot = loadHealthState(path);
167
+ if (snapshot?.daemon_pid === daemonPid && snapshot.components.runner?.ready === true) return;
168
+ if (!isProcessAlive(daemonPid)) throw new Error("the daemon exited before the runner was ready");
169
+ await delay(RUNNER_READY_POLL_MS);
170
+ }
171
+ throw new CliExitError(`runner did not report ready within ${timeoutMs / 1000} s`, ExitCode.General, [componentLogsHint("runner")]);
172
+ }
173
+
140
174
  /**
141
175
  * Why the stack did not start, from the daemon's own record: the first
142
176
  * critical component recorded failed, how it failed, its last stderr lines and
@@ -332,11 +366,12 @@ function stigmerPortHolder(port: number): number | null {
332
366
  }
333
367
 
334
368
  // Refuse to start beside a stack that is running, still starting or still
335
- // stopping: the daemon on record is alive. Nothing is touched; `down` is the
369
+ // stopping: the daemon on record is alive. `stigmer up` also calls it before
370
+ // asking for a model key on a terminal, so it never asks, then refuses. Nothing is touched; `down` is the
336
371
  // one way to stop it. A recorded PID that is dead, our own, or names another
337
372
  // program now is a leftover, never a stack: its record is dropped here, so the
338
373
  // sweep after (cleanupOrphans) neither re-reads nor re-reports it.
339
- function refuseRunningStack(data: string): void {
374
+ export function refuseRunningStack(data: string): void {
340
375
  const pidPath = join(data, DAEMON_PID_FILE);
341
376
  const pid = recordedLiveProcess(pidPath);
342
377
  if (pid === null) {
@@ -32,6 +32,10 @@ export interface ChildHandle {
32
32
  hasExited(): boolean;
33
33
  /** How the child terminated, once observed; null while it runs. */
34
34
  exitInfo(): ExitInfo | null;
35
+ /** True once the child has written its readiness marker; always false
36
+ * without one. A gate reads this rather than registering `onReady`, whose
37
+ * one slot the supervisor holds. */
38
+ isReady(): boolean;
35
39
  /** The child's last few complete stderr lines, oldest first: its last
36
40
  * words, recorded beside a failure. */
37
41
  stderrTail(): readonly string[];
@@ -73,7 +77,11 @@ export interface ComponentSpec {
73
77
  gate?: ReadinessGate;
74
78
  }
75
79
 
76
- /** A post-spawn readiness check with its own deadline. */
80
+ /**
81
+ * A post-spawn readiness check with its own deadline. It watches the handle
82
+ * through its reads (`exitInfo`, `isReady`) and never registers `onExit` or
83
+ * `onReady`: each holds one callback, which the supervisor has taken.
84
+ */
77
85
  export interface ReadinessGate {
78
86
  /** Resolves when ready; rejects if the deadline passes or the child exits. */
79
87
  wait(handle: ChildHandle): Promise<void>;