@kumion/cli 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.
@@ -0,0 +1,100 @@
1
+ import { NetworkError } from "./client.js";
2
+ import { ReportedFailure } from "./errors.js";
3
+ export const DEVICE_CLIENT_ID = "kumion-cli";
4
+ export const DEFAULT_DEVICE_SCOPES = [
5
+ "agents:read",
6
+ "agents:write",
7
+ "agents:publish",
8
+ "tests:run",
9
+ "calls:create",
10
+ "calls:read",
11
+ ];
12
+ async function post(fetch, url, body) {
13
+ let res;
14
+ try {
15
+ res = await fetch(url, {
16
+ method: "POST",
17
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
18
+ body: JSON.stringify(body),
19
+ });
20
+ }
21
+ catch (err) {
22
+ throw new NetworkError(url, err);
23
+ }
24
+ const text = await res.text();
25
+ let json = {};
26
+ try {
27
+ const parsed = text ? JSON.parse(text) : {};
28
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
29
+ json = parsed;
30
+ }
31
+ catch {
32
+ }
33
+ return { status: res.status, json, retryAfter: res.headers.get("retry-after") };
34
+ }
35
+ export function formatUserCode(code) {
36
+ return code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
37
+ }
38
+ export async function deviceLogin(input) {
39
+ const { baseUrl, fetch, sleep, io } = input;
40
+ const scopes = input.scopes ?? DEFAULT_DEVICE_SCOPES;
41
+ const start = await post(fetch, `${baseUrl}/api/auth/device/code`, {
42
+ client_id: DEVICE_CLIENT_ID,
43
+ scope: scopes.join(" "),
44
+ });
45
+ const deviceCode = start.json.device_code;
46
+ const userCode = start.json.user_code;
47
+ if (start.status !== 200 || typeof deviceCode !== "string" || typeof userCode !== "string") {
48
+ const why = typeof start.json.error_description === "string" ? start.json.error_description : typeof start.json.error === "string" ? start.json.error : `HTTP ${start.status}`;
49
+ throw new ReportedFailure(`The Kumion Portal at ${baseUrl} did not start a device login (${why}).`);
50
+ }
51
+ const verificationUri = typeof start.json.verification_uri === "string" ? start.json.verification_uri : `${baseUrl}/device`;
52
+ const completeUri = typeof start.json.verification_uri_complete === "string" ? start.json.verification_uri_complete : verificationUri;
53
+ let intervalMs = (typeof start.json.interval === "number" ? start.json.interval : 5) * 1000;
54
+ const expiresInMs = (typeof start.json.expires_in === "number" ? start.json.expires_in : 900) * 1000;
55
+ io.out([
56
+ "To log in, open this page in a browser where you are signed in to the Kumion Portal:",
57
+ "",
58
+ ` ${completeUri}`,
59
+ "",
60
+ `and check that it shows this code: ${formatUserCode(userCode)}`,
61
+ "",
62
+ `Waiting for approval (the code expires in ${Math.round(expiresInMs / 60_000)} minutes)…`,
63
+ ].join("\n"));
64
+ let waited = 0;
65
+ while (waited + intervalMs <= expiresInMs) {
66
+ await sleep(intervalMs);
67
+ waited += intervalMs;
68
+ const poll = await post(fetch, `${baseUrl}/api/device/key`, { device_code: deviceCode, client_id: DEVICE_CLIENT_ID });
69
+ if (poll.status === 200 && typeof poll.json.key === "string" && typeof poll.json.tenantId === "string") {
70
+ return {
71
+ key: poll.json.key,
72
+ kind: typeof poll.json.kind === "string" ? poll.json.kind : "personal",
73
+ tenantId: poll.json.tenantId,
74
+ prefix: typeof poll.json.prefix === "string" ? poll.json.prefix : "",
75
+ scopes: Array.isArray(poll.json.scopes) ? poll.json.scopes.map(String) : [],
76
+ expiresAt: typeof poll.json.expiresAt === "string" ? poll.json.expiresAt : "",
77
+ };
78
+ }
79
+ if (poll.status === 429) {
80
+ const retry = Number(poll.retryAfter);
81
+ intervalMs = Math.max(intervalMs, Number.isFinite(retry) && retry > 0 ? retry * 1000 : intervalMs * 2);
82
+ continue;
83
+ }
84
+ const error = poll.json.error;
85
+ if (error === "authorization_pending")
86
+ continue;
87
+ if (error === "slow_down") {
88
+ intervalMs += 5000;
89
+ continue;
90
+ }
91
+ const detail = typeof poll.json.error_description === "string" ? `\nServer said: ${poll.json.error_description}` : "";
92
+ if (error === "access_denied")
93
+ throw new ReportedFailure(`The login was not approved; no key was issued.${detail}`);
94
+ if (error === "expired_token") {
95
+ throw new ReportedFailure(`The code expired before it was approved. Run \`kumion auth login\` again.${detail}`);
96
+ }
97
+ throw new ReportedFailure(`The device login failed (${typeof error === "string" ? error : `HTTP ${poll.status}`}).${detail}`);
98
+ }
99
+ throw new ReportedFailure("The code expired before it was approved. Run `kumion auth login` again.");
100
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,71 @@
1
+ import { ApiError, NetworkError } from "./client.js";
2
+ export class UsageError extends Error {
3
+ }
4
+ export class ReportedFailure extends Error {
5
+ }
6
+ function serverSaid(err) {
7
+ const detail = typeof err.body.error === "string" ? err.body.error : null;
8
+ const requestId = typeof err.body.requestId === "string" ? ` (requestId ${err.body.requestId})` : "";
9
+ return detail ? `\nServer said: ${detail}${requestId}` : requestId ? `\n${requestId.trim()}` : "";
10
+ }
11
+ export function describeApiError(err) {
12
+ switch (err.status) {
13
+ case 401:
14
+ return ("The API key was rejected (401). It may be mistyped, revoked or expired, or issued for a different " +
15
+ "tenant than the one configured. Check with `kumion auth status`, or log in again with `kumion auth login`.");
16
+ case 403: {
17
+ const detail = typeof err.body.error === "string" ? err.body.error : "";
18
+ if (detail.includes(err.scope)) {
19
+ return (`This API key does not have the \`${err.scope}\` scope, which this command needs (403). ` +
20
+ `Issue a key that includes it in the Kumion Portal (設定 → 開発者).` +
21
+ serverSaid(err));
22
+ }
23
+ if (err.code === "plan_publish_required") {
24
+ return `This tenant's plan cannot publish agents (403). Upgrade the plan in the Kumion Portal; no key change helps.${serverSaid(err)}`;
25
+ }
26
+ if (err.scope === "calls:create") {
27
+ return ("The call was refused (403): the tenant has reached its call-minute limit (the 30-minute cap for an " +
28
+ "unsigned tenant, or the monthly cap), or its plan cannot start calls. Check 設定 in the Kumion Portal." +
29
+ serverSaid(err));
30
+ }
31
+ return `Access refused (403).${serverSaid(err)}`;
32
+ }
33
+ case 404:
34
+ return `Not found (404) — check the id, and that it belongs to this tenant.${serverSaid(err)}`;
35
+ case 409:
36
+ if (err.code === "draft_revision_conflict") {
37
+ return ("The agent's draft changed since you read it (409): someone saved it in the Portal or from another " +
38
+ "client. Nothing was written. Run `kumion agents get <agentId>` for the new revision, re-apply your " +
39
+ "change on top of it, and try again." +
40
+ serverSaid(err));
41
+ }
42
+ if (err.code === "test_run_in_progress") {
43
+ return ("This agent already has a test run in progress (409). Wait for it with " +
44
+ "`kumion test-runs list <agentId>` / `kumion test-runs get <agentId> <runId>`, then start another." +
45
+ serverSaid(err));
46
+ }
47
+ if (err.scope === "agents:publish") {
48
+ return ("The publish did not go through (409): another publish is already running for this agent, or the " +
49
+ "draft changed while the check ran. Re-read the agent and try again." +
50
+ serverSaid(err));
51
+ }
52
+ return `Conflict (409).${serverSaid(err)}`;
53
+ case 428:
54
+ return `The API asked for an If-Match revision the CLI did not send (428). This is a CLI bug.${serverSaid(err)}`;
55
+ case 429:
56
+ return `Rate limited (429).${err.retryAfter ? ` Retry in ${err.retryAfter}s.` : ""}${serverSaid(err)}`;
57
+ default:
58
+ if (err.status >= 500)
59
+ return `The Kumion server failed (${err.status}).${serverSaid(err)}`;
60
+ return `Request failed (${err.status}).${serverSaid(err)}`;
61
+ }
62
+ }
63
+ export function describeError(err) {
64
+ if (err instanceof ApiError)
65
+ return describeApiError(err);
66
+ if (err instanceof NetworkError)
67
+ return `${err.message}\nCheck the base URL (\`kumion auth status\`) and your network.`;
68
+ if (err instanceof UsageError || err instanceof ReportedFailure)
69
+ return err.message;
70
+ return `Unexpected error: ${err instanceof Error ? err.message : String(err)}`;
71
+ }