@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.
- package/auth/browser.d.ts +7 -0
- package/auth/browser.d.ts.map +1 -0
- package/auth/browser.js +49 -0
- package/auth/browser.js.map +1 -0
- package/auth/callback-server.d.ts +8 -3
- package/auth/callback-server.d.ts.map +1 -1
- package/auth/callback-server.js +53 -19
- package/auth/callback-server.js.map +1 -1
- package/auth/device.d.ts +23 -0
- package/auth/device.d.ts.map +1 -0
- package/auth/device.js +119 -0
- package/auth/device.js.map +1 -0
- package/auth/index.d.ts +4 -3
- package/auth/index.d.ts.map +1 -1
- package/auth/index.js +4 -3
- package/auth/index.js.map +1 -1
- package/auth/login.d.ts +49 -1
- package/auth/login.d.ts.map +1 -1
- package/auth/login.js +161 -51
- package/auth/login.js.map +1 -1
- package/auth/oidc.d.ts +67 -0
- package/auth/oidc.d.ts.map +1 -0
- package/auth/oidc.js +213 -0
- package/auth/oidc.js.map +1 -0
- package/auth/token.d.ts +17 -23
- package/auth/token.d.ts.map +1 -1
- package/auth/token.js +51 -60
- package/auth/token.js.map +1 -1
- package/client/client.d.ts.map +1 -1
- package/client/client.js +4 -1
- package/client/client.js.map +1 -1
- package/client/current-organization.d.ts +5 -0
- package/client/current-organization.d.ts.map +1 -0
- package/client/current-organization.js +15 -0
- package/client/current-organization.js.map +1 -0
- package/commands/apikey/index.d.ts +16 -1
- package/commands/apikey/index.d.ts.map +1 -1
- package/commands/apikey/index.js +81 -0
- package/commands/apikey/index.js.map +1 -1
- package/commands/app-handover.d.ts +17 -0
- package/commands/app-handover.d.ts.map +1 -0
- package/commands/app-handover.js +168 -0
- package/commands/app-handover.js.map +1 -0
- package/commands/auth/index.d.ts.map +1 -1
- package/commands/auth/index.js +15 -9
- package/commands/auth/index.js.map +1 -1
- package/commands/auth/login.d.ts +7 -2
- package/commands/auth/login.d.ts.map +1 -1
- package/commands/auth/login.js +26 -23
- package/commands/auth/login.js.map +1 -1
- package/commands/auth/whoami.d.ts +15 -0
- package/commands/auth/whoami.d.ts.map +1 -1
- package/commands/auth/whoami.js +72 -2
- package/commands/auth/whoami.js.map +1 -1
- package/commands/coding-agent.d.ts +5 -0
- package/commands/coding-agent.d.ts.map +1 -0
- package/commands/coding-agent.js +30 -0
- package/commands/coding-agent.js.map +1 -0
- package/commands/config/backend.js +20 -6
- package/commands/config/backend.js.map +1 -1
- package/commands/docs/index.d.ts +9 -0
- package/commands/docs/index.d.ts.map +1 -0
- package/commands/docs/index.js +64 -0
- package/commands/docs/index.js.map +1 -0
- package/commands/embedding.d.ts +28 -0
- package/commands/embedding.d.ts.map +1 -0
- package/commands/embedding.js +170 -0
- package/commands/embedding.js.map +1 -0
- package/commands/example.d.ts +20 -0
- package/commands/example.d.ts.map +1 -0
- package/commands/example.js +136 -0
- package/commands/example.js.map +1 -0
- package/commands/help.d.ts.map +1 -1
- package/commands/help.js +19 -3
- package/commands/help.js.map +1 -1
- package/commands/list.d.ts.map +1 -1
- package/commands/list.js +13 -1
- package/commands/list.js.map +1 -1
- package/commands/load-test/burst.d.ts +64 -0
- package/commands/load-test/burst.d.ts.map +1 -0
- package/commands/load-test/burst.js +202 -0
- package/commands/load-test/burst.js.map +1 -0
- package/commands/load-test/index.d.ts +37 -0
- package/commands/load-test/index.d.ts.map +1 -0
- package/commands/load-test/index.js +154 -0
- package/commands/load-test/index.js.map +1 -0
- package/commands/load-test/report.d.ts +98 -0
- package/commands/load-test/report.d.ts.map +1 -0
- package/commands/load-test/report.js +210 -0
- package/commands/load-test/report.js.map +1 -0
- package/commands/mcp-server.d.ts +3 -3
- package/commands/mcp-server.d.ts.map +1 -1
- package/commands/mcp-server.js +16 -7
- package/commands/mcp-server.js.map +1 -1
- package/commands/provider-key/index.d.ts.map +1 -1
- package/commands/provider-key/index.js +2 -2
- package/commands/provider-key/index.js.map +1 -1
- package/commands/setup.d.ts +17 -0
- package/commands/setup.d.ts.map +1 -1
- package/commands/setup.js +71 -1
- package/commands/setup.js.map +1 -1
- package/commands/status.d.ts.map +1 -1
- package/commands/status.js +4 -3
- package/commands/status.js.map +1 -1
- package/commands/up.d.ts.map +1 -1
- package/commands/up.js +67 -9
- package/commands/up.js.map +1 -1
- package/commands/usage.d.ts +15 -0
- package/commands/usage.d.ts.map +1 -1
- package/commands/usage.js +52 -2
- package/commands/usage.js.map +1 -1
- package/config/config.d.ts +14 -7
- package/config/config.d.ts.map +1 -1
- package/config/config.js +5 -1
- package/config/config.js.map +1 -1
- package/config/index.d.ts +2 -2
- package/config/index.d.ts.map +1 -1
- package/config/index.js +2 -2
- package/config/index.js.map +1 -1
- package/config/resolve.d.ts +14 -3
- package/config/resolve.d.ts.map +1 -1
- package/config/resolve.js +30 -6
- package/config/resolve.js.map +1 -1
- package/errors/classify.d.ts.map +1 -1
- package/errors/classify.js +10 -1
- package/errors/classify.js.map +1 -1
- package/errors/cli-exit-error.d.ts +3 -1
- package/errors/cli-exit-error.d.ts.map +1 -1
- package/errors/cli-exit-error.js +6 -2
- package/errors/cli-exit-error.js.map +1 -1
- package/errors/handle.d.ts +32 -5
- package/errors/handle.d.ts.map +1 -1
- package/errors/handle.js +67 -8
- package/errors/handle.js.map +1 -1
- package/local/daemon/components.d.ts +28 -1
- package/local/daemon/components.d.ts.map +1 -1
- package/local/daemon/components.js +64 -2
- package/local/daemon/components.js.map +1 -1
- package/local/daemon/host.d.ts.map +1 -1
- package/local/daemon/host.js +6 -2
- package/local/daemon/host.js.map +1 -1
- package/local/daemon/launch.d.ts +12 -4
- package/local/daemon/launch.d.ts.map +1 -1
- package/local/daemon/launch.js +49 -16
- package/local/daemon/launch.js.map +1 -1
- package/local/daemon/types.d.ts +9 -1
- package/local/daemon/types.d.ts.map +1 -1
- package/local/key-check.d.ts +20 -0
- package/local/key-check.d.ts.map +1 -0
- package/local/key-check.js +45 -0
- package/local/key-check.js.map +1 -0
- package/local/model-key-step.d.ts +63 -0
- package/local/model-key-step.d.ts.map +1 -0
- package/local/model-key-step.js +133 -0
- package/local/model-key-step.js.map +1 -0
- package/local/runtime/node.d.ts +12 -4
- package/local/runtime/node.d.ts.map +1 -1
- package/local/runtime/node.js +73 -27
- package/local/runtime/node.js.map +1 -1
- package/local/setup/prompt.d.ts.map +1 -1
- package/local/setup/prompt.js +22 -18
- package/local/setup/prompt.js.map +1 -1
- package/local/setup/wizard.d.ts +10 -0
- package/local/setup/wizard.d.ts.map +1 -1
- package/local/setup/wizard.js +40 -17
- package/local/setup/wizard.js.map +1 -1
- package/local/state/lock.d.ts.map +1 -1
- package/local/state/lock.js +123 -36
- package/local/state/lock.js.map +1 -1
- package/local/state/pidfile.d.ts +4 -0
- package/local/state/pidfile.d.ts.map +1 -1
- package/local/state/pidfile.js +12 -3
- package/local/state/pidfile.js.map +1 -1
- package/local/status.d.ts.map +1 -1
- package/local/status.js +62 -4
- package/local/status.js.map +1 -1
- package/package.json +13 -10
- package/program.d.ts.map +1 -1
- package/program.js +12 -0
- package/program.js.map +1 -1
- package/resources/get.js +1 -1
- package/resources/get.js.map +1 -1
- package/resources/provider-key.d.ts +7 -2
- package/resources/provider-key.d.ts.map +1 -1
- package/resources/provider-key.js +18 -3
- package/resources/provider-key.js.map +1 -1
- package/resources/run/stream.d.ts.map +1 -1
- package/resources/run/stream.js +2 -1
- package/resources/run/stream.js.map +1 -1
- package/resources/runs.d.ts +10 -3
- package/resources/runs.d.ts.map +1 -1
- package/resources/runs.js +22 -4
- package/resources/runs.js.map +1 -1
- package/resources/stream/render-plaintext.d.ts +3 -0
- package/resources/stream/render-plaintext.d.ts.map +1 -1
- package/resources/stream/render-plaintext.js +20 -2
- package/resources/stream/render-plaintext.js.map +1 -1
- package/resources/usage.d.ts +8 -0
- package/resources/usage.d.ts.map +1 -1
- package/resources/usage.js +37 -0
- package/resources/usage.js.map +1 -1
- package/resources/views/agent.d.ts.map +1 -1
- package/resources/views/agent.js +18 -2
- package/resources/views/agent.js.map +1 -1
- package/runtime.d.ts +9 -0
- package/runtime.d.ts.map +1 -1
- package/runtime.js +12 -1
- package/runtime.js.map +1 -1
- package/src/auth/browser.ts +57 -0
- package/src/auth/callback-server.ts +58 -22
- package/src/auth/device.ts +151 -0
- package/src/auth/index.ts +4 -3
- package/src/auth/login.ts +243 -67
- package/src/auth/oidc.ts +270 -0
- package/src/auth/token.ts +53 -90
- package/src/client/client.ts +4 -1
- package/src/client/current-organization.ts +27 -0
- package/src/commands/apikey/index.ts +85 -0
- package/src/commands/app-handover.ts +202 -0
- package/src/commands/auth/index.ts +16 -10
- package/src/commands/auth/login.ts +30 -23
- package/src/commands/auth/whoami.ts +80 -1
- package/src/commands/coding-agent.ts +33 -0
- package/src/commands/config/backend.ts +20 -6
- package/src/commands/docs/index.ts +65 -0
- package/src/commands/embedding.ts +209 -0
- package/src/commands/example.ts +157 -0
- package/src/commands/help.ts +19 -3
- package/src/commands/list.ts +14 -1
- package/src/commands/load-test/burst.ts +291 -0
- package/src/commands/load-test/index.ts +183 -0
- package/src/commands/load-test/report.ts +302 -0
- package/src/commands/mcp-server.ts +16 -8
- package/src/commands/provider-key/index.ts +7 -1
- package/src/commands/setup.ts +76 -2
- package/src/commands/status.ts +4 -3
- package/src/commands/up.ts +76 -10
- package/src/commands/usage.ts +55 -2
- package/src/config/config.ts +18 -8
- package/src/config/index.ts +2 -0
- package/src/config/resolve.ts +31 -6
- package/src/errors/classify.ts +10 -1
- package/src/errors/cli-exit-error.ts +6 -2
- package/src/errors/handle.ts +74 -8
- package/src/local/daemon/components.ts +66 -2
- package/src/local/daemon/host.ts +6 -2
- package/src/local/daemon/launch.ts +51 -16
- package/src/local/daemon/types.ts +9 -1
- package/src/local/key-check.ts +61 -0
- package/src/local/model-key-step.ts +164 -0
- package/src/local/runtime/node.ts +95 -30
- package/src/local/setup/prompt.ts +22 -18
- package/src/local/setup/wizard.ts +45 -18
- package/src/local/state/lock.ts +116 -35
- package/src/local/state/pidfile.ts +14 -3
- package/src/local/status.ts +69 -4
- package/src/program.ts +12 -0
- package/src/resources/get.ts +1 -1
- package/src/resources/provider-key.ts +24 -3
- package/src/resources/run/stream.ts +2 -1
- package/src/resources/runs.ts +36 -4
- package/src/resources/stream/render-plaintext.ts +20 -2
- package/src/resources/usage.ts +42 -0
- package/src/resources/views/agent.ts +19 -2
- package/src/runtime.ts +17 -1
- package/auth/auth0.d.ts +0 -19
- package/auth/auth0.d.ts.map +0 -1
- package/auth/auth0.js +0 -39
- package/auth/auth0.js.map +0 -1
- package/src/auth/auth0.ts +0 -43
package/src/errors/handle.ts
CHANGED
|
@@ -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 {
|
|
5
|
-
import {
|
|
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.
|
|
10
|
-
*
|
|
11
|
-
*
|
|
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
|
|
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:
|
|
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".
|
package/src/local/daemon/host.ts
CHANGED
|
@@ -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
|
-
|
|
82
|
-
|
|
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
|
|
10
|
-
//
|
|
11
|
-
// process
|
|
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
|
|
16
|
-
// the daemon for the whole wait, so a start that has
|
|
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,
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
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.
|
|
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
|
-
/**
|
|
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>;
|
|
@@ -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
|
+
}
|