@cavelon/cli 0.0.0 → 0.1.2
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/README.md +713 -3
- package/dist/LICENSE +201 -0
- package/dist/agents.js +107 -0
- package/dist/branches.js +61 -0
- package/dist/capacity.js +162 -0
- package/dist/cli.js +4 -0
- package/dist/command.js +62 -0
- package/dist/commands/api.js +313 -0
- package/dist/commands/async.js +207 -0
- package/dist/commands/docs.js +158 -0
- package/dist/commands/index.js +112 -0
- package/dist/commands/init.js +481 -0
- package/dist/commands/inventory.js +56 -0
- package/dist/commands/limits-set.js +633 -0
- package/dist/commands/limits.js +156 -0
- package/dist/commands/loops.js +798 -0
- package/dist/commands/models.js +197 -0
- package/dist/commands/sandboxes.js +674 -0
- package/dist/commands/session.js +480 -0
- package/dist/commands/solution.js +830 -0
- package/dist/commands/tenants.js +266 -0
- package/dist/commands/values.js +386 -0
- package/dist/commands/work.js +761 -0
- package/dist/context.js +60 -0
- package/dist/contracts.js +234 -0
- package/dist/credentials.js +134 -0
- package/dist/errors.js +64 -0
- package/dist/features.js +52 -0
- package/dist/format.js +36 -0
- package/dist/fsutil.js +43 -0
- package/dist/git.js +41 -0
- package/dist/http.js +304 -0
- package/dist/invoke.js +165 -0
- package/dist/io.js +49 -0
- package/dist/limits.js +307 -0
- package/dist/local-state.js +78 -0
- package/dist/main.js +227 -0
- package/dist/markers.js +113 -0
- package/dist/mcp.js +137 -0
- package/dist/openapi.js +233 -0
- package/dist/operations.js +107 -0
- package/dist/package-check.js +342 -0
- package/dist/package-files.js +394 -0
- package/dist/pair-order.js +39 -0
- package/dist/paths.js +77 -0
- package/dist/principal.js +33 -0
- package/dist/project.js +157 -0
- package/dist/prompt.js +34 -0
- package/dist/results.js +104 -0
- package/dist/session.js +190 -0
- package/dist/shell.js +41 -0
- package/dist/skills/cavelon-authoring/SKILL.md +224 -0
- package/dist/skills/cavelon-long-running/SKILL.md +185 -0
- package/dist/skills/cavelon-loop/SKILL.md +159 -0
- package/dist/skills/cavelon-testing/SKILL.md +97 -0
- package/dist/sse.js +44 -0
- package/dist/tar.js +172 -0
- package/dist/user-config.js +36 -0
- package/dist/version.js +17 -0
- package/dist/zip.js +132 -0
- package/package.json +40 -4
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
import { capacityLimits, capacityNotes } from "../capacity.js";
|
|
2
|
+
import { boolOption, positional } from "../command.js";
|
|
3
|
+
import { compareContracts, Contracts } from "../contracts.js";
|
|
4
|
+
import { deleteToken, saveToken } from "../credentials.js";
|
|
5
|
+
import { CavelonError, ExitCode, usageError } from "../errors.js";
|
|
6
|
+
import { keyValues } from "../format.js";
|
|
7
|
+
import { formatQuota, formatValue, limitRef, readLimits, readQuotas } from "../limits.js";
|
|
8
|
+
import { ApiClient, tokensDisabledError } from "../http.js";
|
|
9
|
+
import { readAll } from "../io.js";
|
|
10
|
+
import { listPreviews, readPull } from "../local-state.js";
|
|
11
|
+
import { expiryOf, readPrincipal } from "../principal.js";
|
|
12
|
+
import { readHidden } from "../prompt.js";
|
|
13
|
+
import { lookupTenantId, requireInstance, requireToken, TENANT_REF_HINT } from "../session.js";
|
|
14
|
+
import { loadUserConfig, saveUserConfig, tokenKind, updateInstance } from "../user-config.js";
|
|
15
|
+
async function readCapabilities(contracts, refresh) {
|
|
16
|
+
const caps = await contracts.capabilities({ refresh });
|
|
17
|
+
return { caps, needsTenant: contracts.needsTenant };
|
|
18
|
+
}
|
|
19
|
+
async function readMe(client) {
|
|
20
|
+
if (!client.target.token?.startsWith("cvpat_"))
|
|
21
|
+
return undefined;
|
|
22
|
+
const response = await client.get("/api/v1/auth/me", { allow: [401, 403, 404] });
|
|
23
|
+
if (response.status === 401) {
|
|
24
|
+
if (await client.personalAccessTokensOff())
|
|
25
|
+
throw tokensDisabledError(client.url);
|
|
26
|
+
throw new CavelonError(ExitCode.unauthorized, {
|
|
27
|
+
code: "unauthorized",
|
|
28
|
+
status: 401,
|
|
29
|
+
message: `${client.url} refused the token.`,
|
|
30
|
+
hint: "It may be expired or revoked; a person creates a new one on /account/access-tokens and runs `cavelon login`.",
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
return response.status === 200 ? response.data : undefined;
|
|
34
|
+
}
|
|
35
|
+
async function readToken(ctx, fromStdin) {
|
|
36
|
+
let token;
|
|
37
|
+
if (fromStdin) {
|
|
38
|
+
token = (await readAll(ctx.io.stdin)).trim();
|
|
39
|
+
if (!token)
|
|
40
|
+
throw usageError("--token-stdin read nothing from standard input.");
|
|
41
|
+
}
|
|
42
|
+
else if (ctx.io.stdin.isTTY && ctx.io.stderr.isTTY && !ctx.json) {
|
|
43
|
+
token = (await readHidden(ctx.io, "Token (input hidden): ")).trim();
|
|
44
|
+
if (!token)
|
|
45
|
+
throw usageError("No token entered.");
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
throw usageError("No terminal to ask for the token.", "Pipe it in: `cavelon login --token-stdin < file`, or set CAVELON_TOKEN for CI. A person does this, not the agent.");
|
|
49
|
+
}
|
|
50
|
+
if (/\s/.test(token))
|
|
51
|
+
throw usageError("The token contains whitespace; paste exactly the value the Admin showed.");
|
|
52
|
+
return token;
|
|
53
|
+
}
|
|
54
|
+
export const login = {
|
|
55
|
+
name: "login",
|
|
56
|
+
summary: "Store a token for an instance (a person runs this, never the agent).",
|
|
57
|
+
description: "Asks for the token without echoing it, or reads it from standard input with --token-stdin. It is never an argument.\n" +
|
|
58
|
+
"Create a personal access token (cvpat_…) on /account/access-tokens; a tenant API key (cbp_…) also works.\n" +
|
|
59
|
+
"The token is kept in the operating system's credential store, or in a file only you can read.",
|
|
60
|
+
readOnly: false,
|
|
61
|
+
mcpTool: false,
|
|
62
|
+
options: {
|
|
63
|
+
"token-stdin": { type: "boolean", description: "Read the token from standard input." },
|
|
64
|
+
},
|
|
65
|
+
examples: ["cavelon login --instance https://cavelon.example.com", "op read op://dev/cavelon/token | cavelon login --token-stdin"],
|
|
66
|
+
async run(ctx, input) {
|
|
67
|
+
const session = await ctx.session();
|
|
68
|
+
const url = session.url;
|
|
69
|
+
if (!url)
|
|
70
|
+
throw usageError("Which instance?", "Pass --instance <url> (or set CAVELON_URL).");
|
|
71
|
+
const token = await readToken(ctx, boolOption(input, "token-stdin"));
|
|
72
|
+
const kind = tokenKind(token);
|
|
73
|
+
if (kind === "unknown")
|
|
74
|
+
ctx.warn("The token starts with neither cvpat_ nor cbp_; the instance may refuse it.");
|
|
75
|
+
const client = new ApiClient({ url, token }, ctx.io.env);
|
|
76
|
+
const contracts = new Contracts(client, ctx.io.env, ctx.io.now);
|
|
77
|
+
let tenant;
|
|
78
|
+
if (session.tenant && kind !== "api_key") {
|
|
79
|
+
const found = await lookupTenantId(client, session.tenant);
|
|
80
|
+
if (!found) {
|
|
81
|
+
throw new CavelonError(ExitCode.failure, { code: "tenant_not_found", message: `No tenant "${session.tenant}" for this token.`, hint: TENANT_REF_HINT });
|
|
82
|
+
}
|
|
83
|
+
tenant = { ref: session.tenant, ...found };
|
|
84
|
+
client.target.tenantId = found.id;
|
|
85
|
+
}
|
|
86
|
+
const { caps, needsTenant } = await readCapabilities(contracts, true);
|
|
87
|
+
const me = await readMe(client);
|
|
88
|
+
if (!caps && !needsTenant && !me) {
|
|
89
|
+
await client.get("/api/v1/knowledge-bases", { query: { page_size: 1 }, allow: [400, 403, 404, 422] });
|
|
90
|
+
}
|
|
91
|
+
if (needsTenant && !me) {
|
|
92
|
+
throw new CavelonError(ExitCode.validation, {
|
|
93
|
+
code: "tenant_required",
|
|
94
|
+
message: "The instance needs a tenant for this token.",
|
|
95
|
+
hint: "Pass --tenant <slug-or-id>.",
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
const store = await saveToken(ctx.io.env, url, token);
|
|
99
|
+
await updateInstance(ctx.io.env, url, (current) => ({
|
|
100
|
+
...current,
|
|
101
|
+
credential_store: store.kind,
|
|
102
|
+
token_kind: kind,
|
|
103
|
+
logged_in_at: ctx.io.now().toISOString(),
|
|
104
|
+
...(tenant && session.tenantSource === "option" ? { tenant: tenant.ref, tenant_id: tenant.id, tenant_name: tenant.name } : {}),
|
|
105
|
+
}), { makeCurrent: true });
|
|
106
|
+
if (needsTenant) {
|
|
107
|
+
ctx.warn("This token works in Platform mode; choose a tenant with `cavelon use <tenant>` before tenant commands.");
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
for (const warning of compareContracts(caps))
|
|
111
|
+
ctx.warn(warning);
|
|
112
|
+
try {
|
|
113
|
+
await contracts.openapi();
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
ctx.warn(`Could not cache the OpenAPI: ${error instanceof Error ? error.message : String(error)}`);
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
await contracts.errorCatalog();
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
ctx.warn(`Could not cache the error catalog: ${error instanceof Error ? error.message : String(error)}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (!needsTenant) {
|
|
126
|
+
const expiry = expiryOf(await readPrincipal(client), ctx.io.now());
|
|
127
|
+
if (expiry.warning)
|
|
128
|
+
ctx.warn(expiry.warning);
|
|
129
|
+
}
|
|
130
|
+
if (ctx.io.env.CAVELON_TOKEN)
|
|
131
|
+
ctx.warn("CAVELON_TOKEN is set and takes precedence over this login.");
|
|
132
|
+
if (store.kind === "file")
|
|
133
|
+
ctx.warn("No operating-system credential store; the token is in a file only you can read (0600).");
|
|
134
|
+
const data = {
|
|
135
|
+
instance: url,
|
|
136
|
+
credential: { kind, store: store.kind },
|
|
137
|
+
owner: me ? { email: me.email, name: me.display_name ?? null } : null,
|
|
138
|
+
tenant: tenant ? { ref: tenant.ref, id: tenant.id, name: tenant.name ?? null } : null,
|
|
139
|
+
instance_version: caps?.instance.version ?? null,
|
|
140
|
+
contracts: caps?.contracts ?? null,
|
|
141
|
+
};
|
|
142
|
+
const who = me?.email ? ` as ${me.email}` : kind === "api_key" ? " with a tenant API key" : "";
|
|
143
|
+
return {
|
|
144
|
+
data,
|
|
145
|
+
text: `Logged in to ${url}${who}. Token stored in the ${store.kind === "keyring" ? "credential store" : "user-only file"}.`,
|
|
146
|
+
};
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
export const logout = {
|
|
150
|
+
name: "logout",
|
|
151
|
+
summary: "Delete the stored token for an instance.",
|
|
152
|
+
readOnly: false,
|
|
153
|
+
destructive: true,
|
|
154
|
+
idempotent: true,
|
|
155
|
+
mcpTool: false,
|
|
156
|
+
options: { all: { type: "boolean", description: "Log out of every instance." } },
|
|
157
|
+
async run(ctx, input) {
|
|
158
|
+
const env = ctx.io.env;
|
|
159
|
+
const config = await loadUserConfig(env);
|
|
160
|
+
let urls;
|
|
161
|
+
if (boolOption(input, "all"))
|
|
162
|
+
urls = Object.keys(config.instances);
|
|
163
|
+
else
|
|
164
|
+
urls = [requireInstance(await ctx.session())];
|
|
165
|
+
const results = [];
|
|
166
|
+
for (const url of urls) {
|
|
167
|
+
const deleted = await deleteToken(env, url);
|
|
168
|
+
delete config.instances[url];
|
|
169
|
+
if (config.current_instance === url)
|
|
170
|
+
config.current_instance = undefined;
|
|
171
|
+
results.push({ instance: url, deleted });
|
|
172
|
+
}
|
|
173
|
+
await saveUserConfig(env, config);
|
|
174
|
+
if (env.CAVELON_TOKEN)
|
|
175
|
+
ctx.warn("CAVELON_TOKEN is still set in the environment.");
|
|
176
|
+
const text = results.map((r) => (r.deleted ? `Logged out of ${r.instance}.` : `No stored token for ${r.instance}.`)).join("\n");
|
|
177
|
+
return { data: { logged_out: results }, text: text || "No stored logins." };
|
|
178
|
+
},
|
|
179
|
+
};
|
|
180
|
+
function credentialSource(session) {
|
|
181
|
+
if (session.tokenSource === "CAVELON_TOKEN")
|
|
182
|
+
return "CAVELON_TOKEN";
|
|
183
|
+
return session.tokenStore === "file" ? "login (user-only file)" : "login (credential store)";
|
|
184
|
+
}
|
|
185
|
+
export const whoami = {
|
|
186
|
+
name: "whoami",
|
|
187
|
+
summary: "Show who the token acts as, in which tenant, and where the token came from.",
|
|
188
|
+
readOnly: true,
|
|
189
|
+
idempotent: true,
|
|
190
|
+
mcpTool: "whoami",
|
|
191
|
+
async run(ctx) {
|
|
192
|
+
const session = await ctx.session();
|
|
193
|
+
requireToken(session);
|
|
194
|
+
const client = await ctx.client();
|
|
195
|
+
const { caps, needsTenant } = await readCapabilities(await ctx.contracts(), false);
|
|
196
|
+
const me = await readMe(client);
|
|
197
|
+
const principal = needsTenant ? undefined : await readPrincipal(client);
|
|
198
|
+
const contextTenant = me?.context?.tenant_id ?? principal?.tenant_id ?? client.target.tenantId ?? null;
|
|
199
|
+
const tenants = [...(me?.memberships ?? []), ...(me?.accessible_tenants ?? [])];
|
|
200
|
+
const tenantName = tenants.find((t) => t.tenant_id === contextTenant)?.tenant_name ?? session.settings.tenant_name ?? null;
|
|
201
|
+
const expiry = expiryOf(principal, ctx.io.now());
|
|
202
|
+
if (expiry.warning)
|
|
203
|
+
ctx.warn(expiry.warning);
|
|
204
|
+
const data = {
|
|
205
|
+
instance: { url: session.url, source: session.urlSource, version: caps?.instance.version ?? null },
|
|
206
|
+
credential: {
|
|
207
|
+
kind: principal?.kind ?? session.tokenKind,
|
|
208
|
+
source: session.tokenSource,
|
|
209
|
+
store: session.tokenSource === "login" ? session.tokenStore : null,
|
|
210
|
+
name: principal?.token?.name ?? principal?.api_key?.name ?? null,
|
|
211
|
+
prefix: principal?.token?.prefix ?? principal?.api_key?.prefix ?? null,
|
|
212
|
+
expires_at: expiry.expires_at,
|
|
213
|
+
expires_in_days: expiry.days_left,
|
|
214
|
+
may_activate: principal?.token ? principal.token.may_activate : null,
|
|
215
|
+
ceiling_role: principal?.token?.ceiling_role ?? null,
|
|
216
|
+
scopes: principal?.api_key?.scopes ?? null,
|
|
217
|
+
published: Boolean(principal),
|
|
218
|
+
},
|
|
219
|
+
owner: me
|
|
220
|
+
? { id: me.id ?? null, email: me.email ?? null, name: me.display_name ?? null }
|
|
221
|
+
: principal?.user
|
|
222
|
+
? { id: principal.user.id, email: principal.user.email, name: null }
|
|
223
|
+
: null,
|
|
224
|
+
tenant: {
|
|
225
|
+
id: contextTenant,
|
|
226
|
+
name: tenantName,
|
|
227
|
+
ref: session.tenant ?? null,
|
|
228
|
+
source: session.tenant ? session.tenantSource : null,
|
|
229
|
+
mode: me?.context?.mode ?? principal?.mode ?? (session.tokenKind === "api_key" ? "tenant" : null),
|
|
230
|
+
},
|
|
231
|
+
role: me?.context?.effective_role ?? me?.role ?? null,
|
|
232
|
+
};
|
|
233
|
+
if (needsTenant)
|
|
234
|
+
ctx.warn("No tenant selected; this token is in Platform mode. Choose one with `cavelon use <tenant>`.");
|
|
235
|
+
const owner = session.tokenKind === "api_key"
|
|
236
|
+
? principal?.api_key
|
|
237
|
+
? `the tenant API key "${principal.api_key.name}"`
|
|
238
|
+
: "a tenant API key (the instance does not tell a key its name)"
|
|
239
|
+
: me?.email
|
|
240
|
+
? `${me.display_name ? `${me.display_name} <${me.email}>` : me.email}`
|
|
241
|
+
: (principal?.user?.email ?? "unknown");
|
|
242
|
+
const tokenName = data.credential.name ? ` "${data.credential.name}"` : "";
|
|
243
|
+
const expires = !principal
|
|
244
|
+
? "not published by this instance"
|
|
245
|
+
: expiry.expires_at
|
|
246
|
+
? `${expiry.expires_at} (${expiry.days_left < 0 ? "expired" : `in ${expiry.days_left} day${expiry.days_left === 1 ? "" : "s"}`})`
|
|
247
|
+
: "never";
|
|
248
|
+
return {
|
|
249
|
+
data,
|
|
250
|
+
text: keyValues([
|
|
251
|
+
["instance", `${session.url} (${session.urlSource})`],
|
|
252
|
+
["acting as", owner],
|
|
253
|
+
["tenant", contextTenant ? `${tenantName ?? contextTenant}${tenantName ? ` (${contextTenant})` : ""}` : "none (Platform mode)"],
|
|
254
|
+
["tenant from", session.tenant ? session.tenantSource : "the token's default"],
|
|
255
|
+
["role", data.role ?? undefined],
|
|
256
|
+
["credential", `${session.tokenKind === "api_key" ? "tenant API key" : session.tokenKind === "personal_access_token" ? "personal access token" : "token"}${tokenName} from ${credentialSource(session)}`],
|
|
257
|
+
["expires", expires],
|
|
258
|
+
["may activate", principal?.token ? (principal.token.may_activate ? "yes" : "no (a person activates in the Admin)") : undefined],
|
|
259
|
+
["version", data.instance.version ?? undefined],
|
|
260
|
+
]),
|
|
261
|
+
};
|
|
262
|
+
},
|
|
263
|
+
};
|
|
264
|
+
export const use = {
|
|
265
|
+
name: "use",
|
|
266
|
+
summary: "Choose the tenant this instance's commands act in.",
|
|
267
|
+
description: "Stored per instance for your user. CAVELON_TENANT, --tenant and a cavelon.yaml tenant take precedence over it.",
|
|
268
|
+
readOnly: false,
|
|
269
|
+
idempotent: true,
|
|
270
|
+
mcpTool: "use_tenant",
|
|
271
|
+
positionals: [{ name: "tenant", description: "Tenant slug, name or id.", required: false }],
|
|
272
|
+
options: { clear: { type: "boolean", description: "Forget the chosen tenant." } },
|
|
273
|
+
async run(ctx, input) {
|
|
274
|
+
const session = await ctx.session();
|
|
275
|
+
const url = requireInstance(session);
|
|
276
|
+
requireToken(session);
|
|
277
|
+
if (boolOption(input, "clear")) {
|
|
278
|
+
await updateInstance(ctx.io.env, url, (c) => ({ ...c, tenant: undefined, tenant_id: undefined, tenant_name: undefined }));
|
|
279
|
+
return { data: { instance: url, tenant: null }, text: `No tenant chosen for ${url}.` };
|
|
280
|
+
}
|
|
281
|
+
const ref = positional(input, "tenant");
|
|
282
|
+
if (!ref)
|
|
283
|
+
throw usageError("Missing <tenant>.", "Usage: cavelon use <tenant> (or --clear)");
|
|
284
|
+
if (session.tokenKind === "api_key") {
|
|
285
|
+
throw usageError("A tenant API key is bound to its own tenant; `use` applies to personal access tokens.");
|
|
286
|
+
}
|
|
287
|
+
const client = await ctx.client({ tenant: false });
|
|
288
|
+
const found = await lookupTenantId(client, ref);
|
|
289
|
+
if (!found) {
|
|
290
|
+
throw new CavelonError(ExitCode.failure, {
|
|
291
|
+
code: "tenant_not_found",
|
|
292
|
+
message: `No tenant "${ref}" that this token can see.`,
|
|
293
|
+
hint: TENANT_REF_HINT,
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
const probe = new ApiClient({ ...client.target, tenantId: found.id }, ctx.io.env);
|
|
297
|
+
await probe.get("/api/v1/meta/capabilities", { allow: [404] });
|
|
298
|
+
await updateInstance(ctx.io.env, url, (c) => ({
|
|
299
|
+
...c,
|
|
300
|
+
tenant: ref,
|
|
301
|
+
tenant_id: found.id,
|
|
302
|
+
tenant_name: found.name ?? c.tenant_name,
|
|
303
|
+
tenant_ids: { ...c.tenant_ids, [ref]: found.id },
|
|
304
|
+
}));
|
|
305
|
+
if (session.tenantSource && session.tenantSource !== "use") {
|
|
306
|
+
ctx.warn(`${session.tenantSource} names tenant "${session.tenant}" and takes precedence over \`use\` here.`);
|
|
307
|
+
}
|
|
308
|
+
return {
|
|
309
|
+
data: { instance: url, tenant: { ref, id: found.id, name: found.name ?? null } },
|
|
310
|
+
text: `Using tenant ${found.name ?? ref} (${found.id}) on ${url}.`,
|
|
311
|
+
};
|
|
312
|
+
},
|
|
313
|
+
};
|
|
314
|
+
async function nearQuotas(ctx) {
|
|
315
|
+
try {
|
|
316
|
+
const published = await readLimits(ctx);
|
|
317
|
+
if (!published.published)
|
|
318
|
+
return { near: [], capacity: [], data: { published: false } };
|
|
319
|
+
const quotas = await readQuotas(ctx, published);
|
|
320
|
+
const near = quotas?.items.filter((q) => q.near) ?? [];
|
|
321
|
+
const capacity = capacityLimits(published);
|
|
322
|
+
return {
|
|
323
|
+
near,
|
|
324
|
+
capacity,
|
|
325
|
+
published,
|
|
326
|
+
data: {
|
|
327
|
+
published: true,
|
|
328
|
+
near: near.map((q) => ({ key: q.key, current: q.current, limit: q.limit, ratio: q.ratio })),
|
|
329
|
+
capacity: capacity.map(limitRef),
|
|
330
|
+
...(quotas?.unavailable ? { quotas_unavailable: quotas.unavailable } : {}),
|
|
331
|
+
},
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
catch (error) {
|
|
335
|
+
return { near: [], capacity: [], data: { published: null, unavailable: error instanceof Error ? error.message : String(error) } };
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
function capacityLine(capacity) {
|
|
339
|
+
return capacity
|
|
340
|
+
.map((l) => `${l.key} ${formatValue(l)} (${[l.source, l.origin?.replace(/_/g, " ")].filter(Boolean).join(", ")})`)
|
|
341
|
+
.join("; ");
|
|
342
|
+
}
|
|
343
|
+
function limitsLine(state, near) {
|
|
344
|
+
if (state.published === null)
|
|
345
|
+
return `not readable: ${state.unavailable}`;
|
|
346
|
+
if (!state.published)
|
|
347
|
+
return "not published by this instance";
|
|
348
|
+
if (!near.length)
|
|
349
|
+
return "none close to a quota (`cavelon limits` lists them)";
|
|
350
|
+
return `close to a quota: ${near.map((q) => `${q.key} ${formatQuota(q)}`).join("; ")}`;
|
|
351
|
+
}
|
|
352
|
+
export const status = {
|
|
353
|
+
name: "status",
|
|
354
|
+
summary: "Show the instance, tenant, solution, running operations and quotas close to full for this directory.",
|
|
355
|
+
readOnly: true,
|
|
356
|
+
idempotent: true,
|
|
357
|
+
mcpTool: "status",
|
|
358
|
+
options: { offline: { type: "boolean", description: "Do not contact the instance." } },
|
|
359
|
+
async run(ctx, input) {
|
|
360
|
+
const session = await ctx.session();
|
|
361
|
+
const offline = boolOption(input, "offline");
|
|
362
|
+
const data = {
|
|
363
|
+
instance: session.url ? { url: session.url, source: session.urlSource } : null,
|
|
364
|
+
credential: session.token
|
|
365
|
+
? { kind: session.tokenKind, source: session.tokenSource, store: session.tokenStore ?? null }
|
|
366
|
+
: null,
|
|
367
|
+
tenant: session.tenant ? { ref: session.tenant, source: session.tenantSource } : null,
|
|
368
|
+
solution: session.project
|
|
369
|
+
? {
|
|
370
|
+
file: session.project.file,
|
|
371
|
+
root: session.project.root,
|
|
372
|
+
harness: session.project.harness ?? null,
|
|
373
|
+
last_pull: (await readPull(session.project.root)) ?? null,
|
|
374
|
+
open_previews: await listPreviews(session.project.root),
|
|
375
|
+
}
|
|
376
|
+
: null,
|
|
377
|
+
logged_in_at: session.settings.logged_in_at ?? null,
|
|
378
|
+
};
|
|
379
|
+
let operations;
|
|
380
|
+
let near;
|
|
381
|
+
let capacity = [];
|
|
382
|
+
let published;
|
|
383
|
+
let reachError;
|
|
384
|
+
let client;
|
|
385
|
+
if (!offline && session.url && session.token) {
|
|
386
|
+
try {
|
|
387
|
+
client = await ctx.client();
|
|
388
|
+
if (client.target.tenantId)
|
|
389
|
+
data.tenant.id = client.target.tenantId;
|
|
390
|
+
const contracts = await ctx.contracts();
|
|
391
|
+
const caps = await contracts.capabilities();
|
|
392
|
+
data.instance_version = caps?.instance.version ?? null;
|
|
393
|
+
if (contracts.needsTenant) {
|
|
394
|
+
data.operations = { unavailable: "No tenant chosen; operations belong to a tenant." };
|
|
395
|
+
}
|
|
396
|
+
else if (caps?.features?.operations_api_enabled !== false) {
|
|
397
|
+
const page = await client.get("/api/v1/operations", {
|
|
398
|
+
query: { status: ["queued", "running", "needs_action"], limit: 10 },
|
|
399
|
+
allow: [404],
|
|
400
|
+
});
|
|
401
|
+
operations = page.status === 200 ? page.data.items : undefined;
|
|
402
|
+
data.operations = operations
|
|
403
|
+
? { items: operations, more: Boolean(page.data.next_cursor) }
|
|
404
|
+
: { unavailable: "This instance does not offer /api/v1/operations." };
|
|
405
|
+
}
|
|
406
|
+
else {
|
|
407
|
+
data.operations = { unavailable: "The operations API is turned off on this instance." };
|
|
408
|
+
}
|
|
409
|
+
if (!contracts.needsTenant) {
|
|
410
|
+
const limits = await nearQuotas(ctx);
|
|
411
|
+
near = limits.near;
|
|
412
|
+
capacity = limits.capacity;
|
|
413
|
+
published = limits.published;
|
|
414
|
+
data.limits = limits.data;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
catch (error) {
|
|
418
|
+
reachError = error instanceof Error ? error.message : String(error);
|
|
419
|
+
data.error = error instanceof CavelonError ? error.toJSON() : { message: reachError };
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
const tenantText = session.tenant
|
|
423
|
+
? `${session.tenant} (${session.tenantSource})`
|
|
424
|
+
: session.tokenKind === "api_key"
|
|
425
|
+
? "the API key's tenant"
|
|
426
|
+
: "not chosen (`cavelon use <tenant>`)";
|
|
427
|
+
const lines = [
|
|
428
|
+
["instance", session.url ? `${session.url} (${session.urlSource})` : "none (`cavelon login --instance <url>`)"],
|
|
429
|
+
["credential", session.token ? `${session.tokenKind} from ${credentialSource(session)}` : "none"],
|
|
430
|
+
["tenant", tenantText],
|
|
431
|
+
["solution", session.project ? session.project.file : "none (no cavelon.yaml here or above)"],
|
|
432
|
+
];
|
|
433
|
+
if (session.project) {
|
|
434
|
+
const solution = data.solution;
|
|
435
|
+
if (session.project.harness)
|
|
436
|
+
lines.push(["harness", session.project.harness]);
|
|
437
|
+
lines.push(["last pull", solution.last_pull ? `${solution.last_pull.at}${solution.last_pull.harness ? ` (${solution.last_pull.harness.slug})` : ""}` : "never"]);
|
|
438
|
+
lines.push([
|
|
439
|
+
"open previews",
|
|
440
|
+
solution.open_previews.length
|
|
441
|
+
? solution.open_previews.map((p) => `\n ${p.preview_id}${p.env ? ` env ${p.env}` : ""} ${p.created_at}`).join("")
|
|
442
|
+
: "none",
|
|
443
|
+
]);
|
|
444
|
+
}
|
|
445
|
+
if (data.instance_version)
|
|
446
|
+
lines.push(["version", data.instance_version]);
|
|
447
|
+
if (data.limits)
|
|
448
|
+
lines.push(["limits", limitsLine(data.limits, near ?? [])]);
|
|
449
|
+
if (capacity.length)
|
|
450
|
+
lines.push(["run capacity", capacityLine(capacity)]);
|
|
451
|
+
if (reachError)
|
|
452
|
+
lines.push(["instance error", reachError]);
|
|
453
|
+
let text = keyValues(lines);
|
|
454
|
+
if (operations && client) {
|
|
455
|
+
const note = capacityNotes(ctx, client, published);
|
|
456
|
+
const waits = await Promise.all(operations.map(async (o) => (await note(o))?.capacity_wait));
|
|
457
|
+
const waiting = waits.flatMap((wait, i) => (wait ? [{ operation_id: operations[i].id, ...wait }] : []));
|
|
458
|
+
if (waiting.length)
|
|
459
|
+
data.capacity_waits = waiting;
|
|
460
|
+
text += operations.length
|
|
461
|
+
? `\n\nRunning operations:\n${operations
|
|
462
|
+
.map((o, i) => {
|
|
463
|
+
const wait = waits[i];
|
|
464
|
+
return ` ${o.id} ${o.kind} ${o.status}${o.progress?.phase ? ` (${o.progress.phase})` : ""}${wait ? ` ${wait.note}` : ""}`;
|
|
465
|
+
})
|
|
466
|
+
.join("\n")}`
|
|
467
|
+
: "\n\nNo running operations.";
|
|
468
|
+
}
|
|
469
|
+
return { data, text };
|
|
470
|
+
},
|
|
471
|
+
};
|
|
472
|
+
export async function rememberTenant(ctx, url, tenant) {
|
|
473
|
+
await updateInstance(ctx.io.env, url, (c) => ({
|
|
474
|
+
...c,
|
|
475
|
+
tenant: tenant.ref,
|
|
476
|
+
tenant_id: tenant.id,
|
|
477
|
+
tenant_name: tenant.name,
|
|
478
|
+
tenant_ids: { ...c.tenant_ids, [tenant.ref]: tenant.id },
|
|
479
|
+
}));
|
|
480
|
+
}
|