@cavelon/cli 0.2.1 → 0.2.3

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 CHANGED
@@ -21,6 +21,16 @@ in Windows PowerShell. With Python, `uvx cavelon` runs the same executable from
21
21
  PyPI, and `uv tool install cavelon` or `pipx install cavelon` installs it. Then
22
22
  `cavelon setup` sets up your coding agents and logs you in.
23
23
 
24
+ Running the one-line installer again updates the CLI, then asks separately
25
+ whether to refresh Cavelon plugins/skills and enable YOLO for new MCP sessions.
26
+ Enter at the YOLO question keeps your choice. Restart your agent afterwards;
27
+ it launches the tools with that personal mode automatically. Critical changes
28
+ still require approval. Other package managers: update the CLI, then run
29
+ `cavelon setup --update`. Change just the mode with
30
+ `cavelon setup --mcp-mode yolo --yes` or `--mcp-mode standard --yes`.
31
+ Interactive `setup` and `setup --update` offer the same YOLO choice, so
32
+ Homebrew, npm, uv and pipx users do not need to run the installer script.
33
+
24
34
  Version 0.1.17 adds Cline, Kilo, Goose and OMP to the OpenCode, Pi and Qwen
25
35
  Code integrations. Each has native settings and four skills; guarded changes
26
36
  use the qualified client dialog or the person’s own terminal:
@@ -0,0 +1,43 @@
1
+ function object(value) {
2
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3
+ }
4
+ function fields(body, allowed) {
5
+ return object(body) && Object.keys(body).every(key => allowed.includes(key));
6
+ }
7
+ function optionalText(body, keys) {
8
+ return keys.every(key => body[key] === undefined || body[key] === null || typeof body[key] === "string");
9
+ }
10
+ export function apiApproval(op, args) {
11
+ if (op.confirmation || op.personOnly?.marked)
12
+ return "person";
13
+ if (op.readOnly)
14
+ return "read";
15
+ if (op.method !== "POST" || args.files?.length || args.bytes || Object.keys(args.headers ?? {}).length)
16
+ return "person";
17
+ const params = Object.keys(args.params ?? {});
18
+ const onlyParams = (...names) => params.every(key => names.includes(key));
19
+ const uuidParam = (name) => {
20
+ const values = args.params?.[name];
21
+ return values?.length === 1 && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(values[0]);
22
+ };
23
+ const body = args.body;
24
+ if (op.path === "/api/v1/harnesses" && onlyParams("Idempotency-Key") &&
25
+ fields(body, ["slug", "name", "description"]) && typeof body.slug === "string" && typeof body.name === "string" &&
26
+ optionalText(body, ["description"]))
27
+ return "routine";
28
+ if (op.path === "/api/v1/harnesses/{harness_id}/clone" && onlyParams("harness_id", "Idempotency-Key") && uuidParam("harness_id") &&
29
+ fields(body, ["slug", "name", "description", "element_slug_suffix", "include_tests", "include_triggers"]) &&
30
+ optionalText(body, ["slug", "name", "description", "element_slug_suffix"]) &&
31
+ ["include_tests", "include_triggers"].every(key => body[key] === undefined || typeof body[key] === "boolean"))
32
+ return "routine";
33
+ if (op.path === "/api/v1/agent-graph/import/preview" && onlyParams() &&
34
+ fields(body, ["package", "mode", "harness_id", "runtime_bindings", "include_tenant_wide"]) && object(body.package) &&
35
+ (body.mode === undefined || body.mode === "overwrite" || body.mode === "replace") && optionalText(body, ["harness_id"]) &&
36
+ (body.runtime_bindings === undefined || object(body.runtime_bindings) && Object.values(body.runtime_bindings).every(value => typeof value === "string")) &&
37
+ (body.include_tenant_wide === undefined || typeof body.include_tenant_wide === "boolean"))
38
+ return "read";
39
+ if (op.path === "/api/v1/database-connectors/connections/{connection_id}/schema" && onlyParams("connection_id") && uuidParam("connection_id") &&
40
+ (body === undefined || body === null || fields(body, ["schema"]) && optionalText(body, ["schema"])))
41
+ return "read";
42
+ return "person";
43
+ }
@@ -0,0 +1,45 @@
1
+ import { createHash } from "node:crypto";
2
+ import { realpath } from "node:fs/promises";
3
+ import { actingTarget } from "./acting.js";
4
+ import { canonical } from "./package-files.js";
5
+ import { lookupHarness } from "./harness-ref.js";
6
+ export async function yoloScope(ctx) {
7
+ const session = await ctx.session();
8
+ const target = await actingTarget(ctx);
9
+ if (!session.token || target.mode !== "tenant" || !target.tenant?.id)
10
+ return undefined;
11
+ const selected = session.envFile?.harness ?? session.project?.harness;
12
+ const harness = selected ? (await lookupHarness(ctx, selected)).harness : undefined;
13
+ if (selected && !harness)
14
+ return undefined;
15
+ return canonical({
16
+ instance: target.instance,
17
+ tenant: target.tenant.id,
18
+ credential: createHash("sha256").update(session.token).digest("hex"),
19
+ root: await realpath(session.project?.root ?? ctx.io.cwd),
20
+ harness: selected ?? null,
21
+ harness_id: harness?.id ?? null,
22
+ environment: ctx.globals.solutionEnv ?? null,
23
+ bindings: session.envFile?.runtimeBindings ?? {},
24
+ mode: session.envFile?.mode ?? null,
25
+ });
26
+ }
27
+ export async function yoloAllows(ctx, harness) {
28
+ if (!ctx.globals.yolo)
29
+ return false;
30
+ const original = await ctx.globals.yoloScope;
31
+ const current = await yoloScope(ctx);
32
+ if (!original || current !== original) {
33
+ ctx.warn("YOLO does not cover this target, credential or solution folder; using the standard confirmation policy. Restart with the intended target to enable it there.");
34
+ return false;
35
+ }
36
+ if (harness) {
37
+ const session = await ctx.session();
38
+ const selected = session.envFile?.harness ?? session.project?.harness;
39
+ if (!selected || (await lookupHarness(ctx, selected)).harness?.id !== harness.id) {
40
+ ctx.warn("YOLO covers only the solution selected at startup; using the standard confirmation policy for this solution.");
41
+ return false;
42
+ }
43
+ }
44
+ return true;
45
+ }
@@ -0,0 +1,35 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import { CavelonError, ExitCode } from "./errors.js";
4
+ import { withoutBom, writePrivateFile } from "./fsutil.js";
5
+ import { configDir } from "./paths.js";
6
+ export async function readMcpMode(env) {
7
+ const file = path.join(configDir(env), "automation.json");
8
+ try {
9
+ const stat = await fs.lstat(file);
10
+ if (!stat.isFile() || stat.isSymbolicLink())
11
+ throw new Error("expected a regular file");
12
+ const value = JSON.parse(withoutBom(await fs.readFile(file, "utf8")));
13
+ if (!value || typeof value !== "object" || Array.isArray(value))
14
+ throw new Error("expected an object");
15
+ const settings = value;
16
+ if (settings.format !== 1 || !["standard", "yolo"].includes(String(settings.mcp_mode)))
17
+ throw new Error("unrecognized settings format or mode");
18
+ return settings.mcp_mode;
19
+ }
20
+ catch (error) {
21
+ if (error.code === "ENOENT")
22
+ return "standard";
23
+ throw new CavelonError(ExitCode.failure, {
24
+ code: "automation_settings_invalid",
25
+ message: `Cannot read the personal MCP mode in ${file}; leaving this file unchanged.`,
26
+ hint: "Restore a regular JSON file with format: 1 and mcp_mode: standard or yolo, or move it aside and run cavelon setup again.",
27
+ });
28
+ }
29
+ }
30
+ export async function saveMcpMode(env, mode) {
31
+ if (await readMcpMode(env) === mode)
32
+ return false;
33
+ await writePrivateFile(configDir(env), path.join(configDir(env), "automation.json"), JSON.stringify({ format: 1, mcp_mode: mode }, null, 2) + "\n");
34
+ return true;
35
+ }
package/dist/command.js CHANGED
@@ -37,6 +37,8 @@ export function ownsTenant(spec) {
37
37
  }
38
38
  export const GLOBAL_OPTIONS = {
39
39
  json: { type: "boolean", description: "Print one JSON document instead of text." },
40
+ yolo: { type: "boolean", cliOnly: true, description: "Automatically apply eligible routine changes in this process's selected target; critical changes still need a person." },
41
+ "no-yolo": { type: "boolean", cliOnly: true, description: "Use standard mode for this process, overriding the personal MCP startup mode." },
40
42
  instance: { type: "string", value: "<url>", description: "The instance URL (overrides CAVELON_URL and cavelon.yaml)." },
41
43
  tenant: { type: "string", value: "<tenant>", description: "Tenant slug, name or id (overrides CAVELON_TENANT and cavelon.yaml)." },
42
44
  help: { type: "boolean", short: "h", description: "Show help for the command." },
@@ -13,6 +13,8 @@ import { CONFIRM_TOKEN, confirmInTerminal, confirmThroughClient, confirmToken, c
13
13
  import { actingTarget, targetLine } from "../acting.js";
14
14
  import { accessFor, operationAccess } from "../access.js";
15
15
  import { cavelonCommand, fill, personCommand } from "../printed.js";
16
+ import { apiApproval } from "../api-approval-policy.js";
17
+ import { yoloAllows } from "../automation-policy.js";
16
18
  export const JSON_BODY_DEPRECATED = "`--json <body>` as the request body is deprecated and will be removed in a later release; pass the body with --body. " +
17
19
  "--json alone prints JSON, as on every command.";
18
20
  export function splitJsonBody(args, warn) {
@@ -202,9 +204,10 @@ export const api = {
202
204
  "As an MCP tool, or run by a coding agent (" +
203
205
  AGENT_VARIABLES.filter((v) => v.variable !== "CAVELON_AGENT").map((v) => (v.value ? `${v.variable}=${v.value}` : v.variable)).join(", ") +
204
206
  "\nor CAVELON_AGENT=1 is set), an operation that changes something returns what it would send and a confirm token,\n" +
205
- "and sends it only with that token and the person's yes: as an MCP tool, confirm: \"<token>\", after which the client\n" +
206
- "asks the person; from an agent's shell, the person sends it from their own terminal. A changed request needs a new\n" +
207
- "preview; confirm: true is refused.\n" +
207
+ "and sends it with that token. Known draft creation and cloning need no personal approval; explicit --yolo also\n" +
208
+ "skips their token round trip within its bound scope. Known import previews and database catalog reads send at once.\n" +
209
+ "Other changes still need the person's yes: the MCP client asks them, or they send it from their own terminal.\n" +
210
+ "A changed request needs a new preview; confirm: true is refused. Instance confirmation requirements always win.\n" +
208
211
  "Run by an agent, one the instance marks for a person only (x-cavelon-person-only) is refused, as is a body that\n" +
209
212
  "sets a field the instance marks as a secret value (x-cavelon-secret) and a file outside the solution folder. On an\n" +
210
213
  "instance that marks no operation, one that changes a secret, creates or revokes a credential or decides an\n" +
@@ -227,8 +230,8 @@ export const api = {
227
230
  type: "string",
228
231
  value: "<token>",
229
232
  mcpToken: true,
230
- description: "Send an operation that changes something: run by a coding agent or as an MCP tool, the token its preview returned. " +
231
- "Without it, nothing is sent. A person's terminal sends at once.",
233
+ description: "Send a previewed operation: run by a coding agent or as an MCP tool, the token its preview returned. " +
234
+ "Known routine changes need no person; other changes require personal approval. A person's terminal sends at once.",
232
235
  },
233
236
  limit: { type: "string", value: "<n>", description: "Show at most n items of a list response (default 50, 0 for all)." },
234
237
  },
@@ -283,7 +286,7 @@ export const api = {
283
286
  ...(rawBody !== undefined ? ["--body", rawBody] : []),
284
287
  ...listOption(input, "file").flatMap((f) => ["--file", f]),
285
288
  ];
286
- const preview = await previewUnlessConfirmed(ctx, input, doc, op, args, driven, personCommand(...words));
289
+ const preview = await previewUnlessConfirmed(ctx, input, doc, op, args, driven, words);
287
290
  if (preview)
288
291
  return preview;
289
292
  }
@@ -308,29 +311,40 @@ export const api = {
308
311
  return { data, text };
309
312
  },
310
313
  };
311
- async function previewUnlessConfirmed(ctx, input, doc, op, args, driven, command) {
314
+ async function previewUnlessConfirmed(ctx, input, doc, op, args, driven, words) {
312
315
  const given = input.options.confirm;
313
316
  if (given === true)
314
317
  throw confirmTokenRequired("api");
315
318
  const request = previewRequest(doc, op, args);
319
+ const policy = apiApproval(op, args);
320
+ const needsPerson = policy === "person";
321
+ const harness = op.path === "/api/v1/harnesses/{harness_id}/clone" ? { id: args.params?.harness_id?.at(-1) ?? "" } : undefined;
322
+ if ((given === undefined || given === false) &&
323
+ (policy === "read" || policy === "routine" && await yoloAllows(ctx, harness)))
324
+ return undefined;
316
325
  const files = (args.files ?? []).map((f) => ({ field: f.field, file: path.relative(ctx.io.cwd, f.path) || f.path }));
317
326
  const session = await ctx.session();
318
327
  const token = confirmToken({ url: session.url, tenant: session.tenant }, "api", { request, files });
319
328
  const route = personRoute(ctx, driven);
329
+ const command = personCommand(...words);
320
330
  if (typeof given === "string" && given === token) {
321
- await personApproves(ctx, driven, { tool: "api", what: `Send ${request.method} ${request.path} (${op.alias}).`, command });
331
+ if (needsPerson)
332
+ await personApproves(ctx, driven, { tool: "api", what: `Send ${request.method} ${request.path} (${op.alias}).`, command });
322
333
  return undefined;
323
334
  }
324
335
  const stale = typeof given === "string" && given !== "";
325
336
  const bare = given === "" && driven.by === "agent";
326
- const confirm = route === "client" ? confirmThroughClient("api", token) : confirmInTerminal(command);
337
+ const confirm = needsPerson
338
+ ? route === "client" ? confirmThroughClient("api", token) : confirmInTerminal(command)
339
+ : driven.by === "mcp" ? `Call api again with the same arguments and confirm: "${token}". No personal approval is needed for this routine operation.`
340
+ : personCommand(...words, "--confirm", token);
327
341
  const target = await actingTarget(ctx);
328
342
  const shown = { operation: op.alias, ...request, ...(files.length ? { files } : {}), target, sent: false };
329
343
  const lines = [`Would send ${request.method} ${request.path}. Nothing was sent.`, targetLine(target)];
330
344
  if (stale)
331
345
  lines.push("The confirm token is not this request's: the request changed since its preview, or the token is another one's.");
332
- if (bare && driven.by === "agent")
333
- lines.push("A coding agent cannot send it: the person sends it from their own terminal.");
346
+ if (bare)
347
+ lines.push(needsPerson ? "A coding agent cannot send it: the person sends it from their own terminal." : "Pass this request's confirm token; a bare --confirm sends nothing.");
334
348
  if (op.confirmation) {
335
349
  lines.push(`The instance requires a confirmation bound to this request (x-cavelon-confirmation)${op.confirmationWhen ? `: ${op.confirmationWhen}` : ""}`, "cavelon asks the person; the instance does not verify their answer.");
336
350
  }
@@ -346,9 +360,9 @@ async function previewUnlessConfirmed(ctx, input, doc, op, args, driven, command
346
360
  return {
347
361
  data: {
348
362
  ...shown,
349
- ...(route === "client" ? { confirm_token: token } : {}),
363
+ ...(!needsPerson || route === "client" ? { confirm_token: token } : {}),
350
364
  confirm,
351
- needs_person: route,
365
+ ...(needsPerson ? { needs_person: route } : {}),
352
366
  ...(op.confirmation ? { instance_confirmation: op.confirmationWhen ?? true } : {}),
353
367
  ...(stale ? { token_mismatch: true } : {}),
354
368
  ...(bare ? { token_required: true } : {}),
@@ -44,10 +44,13 @@ const mcp = {
44
44
  description: "Started by the agent's plugin (`cavelon mcp`); it does not return until the agent disconnects.",
45
45
  readOnly: false,
46
46
  mcpTool: false,
47
+ options: { env: { type: "string", value: "<name>", description: "Start with env/<name>.yaml's tenant, solution and runtime bindings; --yolo stays bound to this environment." } },
47
48
  async run(ctx) {
49
+ if (ctx.globals.solutionEnv)
50
+ await ctx.session();
48
51
  const { createMcpServer } = await import("../mcp.js");
49
52
  const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
50
- const server = createMcpServer(ctx.io, COMMANDS);
53
+ const server = createMcpServer(ctx.io, COMMANDS, {}, ctx.globals);
51
54
  const transport = new StdioServerTransport();
52
55
  const closed = new Promise((resolve) => {
53
56
  server.onclose = () => resolve();
@@ -1,4 +1,5 @@
1
1
  import { noteLines, runCapacityNote } from "../capacity.js";
2
+ import { yoloAllows } from "../automation-policy.js";
2
3
  import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, positional, stringOption, } from "../command.js";
3
4
  import { CavelonError, ExitCode, usageError } from "../errors.js";
4
5
  import { confirmation, confirmTokenRequired, PERSON_CONFIRMS_HELP } from "../confirm-token.js";
@@ -180,8 +181,8 @@ export const loopStart = {
180
181
  name: "loop start",
181
182
  summary: "Start a loop through its trigger, as you; previews first, --confirm starts it and returns the run and operation ids.",
182
183
  description: "Calls the trigger's run-now route. The run (and its loop) acts as the caller: with a personal access token, the person.\n" +
183
- "It runs on its own and spends the tenant's model budget, so without --confirm nothing starts: the preview names the\n" +
184
- "trigger, its solution and the payload. Show it to a person and confirm only with their yes. For a trigger of a draft\n" +
184
+ "It runs on its own and spends the tenant's model budget. The preview names the trigger, its solution and the payload.\n" +
185
+ "--yolo starts a draft's run at once only for the solution selected at startup; existing budget limits still apply. For a trigger of a draft\n" +
185
186
  "solution an agent confirms with the preview's token (--confirm <token>, or confirm over MCP); for any other,\n" +
186
187
  "a coding agent cannot confirm it: over MCP the client asks the person, and from an agent's shell the person runs the\n" +
187
188
  "confirm in their own terminal. Follow the run with `loop watch <run>`, or `wait <operation>`; `loop cancel <run>` stops it.",
@@ -194,7 +195,7 @@ export const loopStart = {
194
195
  wait: WAIT_OPTION,
195
196
  timeout: TIMEOUT_OPTION,
196
197
  "idempotency-key": UUID_KEY_OPTION,
197
- confirm: { type: "boolean", mcpToken: true, description: "Start the run (after a person saw the preview)." },
198
+ confirm: { type: "boolean", mcpToken: true, description: "Start the previewed run; a non-draft run also needs the person's approval." },
198
199
  },
199
200
  examples: [
200
201
  "cavelon loop start counter",
@@ -214,9 +215,10 @@ export const loopStart = {
214
215
  const solution = await triggerSolution(ctx, trigger);
215
216
  const given = stringOption(input, "idempotency-key");
216
217
  const words = ["loop", "start", trigger.slug, ...(raw !== undefined ? ["--input", raw] : []), ...(given ? ["--idempotency-key", given] : [])];
218
+ const automatic = input.options.confirm === undefined && solution?.status === "draft" && await yoloAllows(ctx, solution);
217
219
  const gate = await confirmation(ctx, input, "loop_start", { trigger: trigger.id, payload }, {
218
220
  ...(solution?.status === "draft"
219
- ? {}
221
+ ? { automatic }
220
222
  : { person: { what: `Start a run of the trigger ${trigger.slug}, which acts as the person and spends the tenant's model budget.`, words: [...words, "--confirm"] } }),
221
223
  });
222
224
  if (!gate.confirmed) {
@@ -241,7 +243,7 @@ export const loopStart = {
241
243
  : `Solution: ${solution.id} (not readable).`,
242
244
  `Payload: ${payloadText}`,
243
245
  gate.where, ...(gate.mismatch ? [gate.mismatch] : []),
244
- `Nothing was started. Show this to a person; with their yes: ${confirm}`,
246
+ solution?.status === "draft" ? `Nothing was started. Confirm the requested draft run with: ${confirm}` : `Nothing was started. The person approves this run with: ${confirm}`,
245
247
  ].join("\n"),
246
248
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
247
249
  };
@@ -256,7 +258,8 @@ export const loopStart = {
256
258
  });
257
259
  if (!trigger.is_active)
258
260
  ctx.warn(`Trigger "${trigger.slug}" is not active: its schedule and webhook start no runs, though this manual start did.`);
259
- const started = { trigger: { id: trigger.id, slug: trigger.slug }, ...runSummary(run), idempotency_key: key };
261
+ const started = { trigger: { id: trigger.id, slug: trigger.slug }, ...runSummary(run), idempotency_key: key,
262
+ ...(automatic ? { approval: { source: "yolo", reason: "selected draft run" } } : {}) };
260
263
  if (boolOption(input, "wait") && ctx.mode === "cli" && run.operation_id) {
261
264
  const waited = await waitAndReport(ctx, [run.operation_id], timeoutMs(ctx, stringOption(input, "timeout")));
262
265
  const text = `Started run ${run.id} of ${trigger.slug}.\n${waited.text}`;
@@ -1,6 +1,10 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
- import { boolOption, listOption } from "../command.js";
3
+ import { boolOption, listOption, stringOption } from "../command.js";
4
+ import { agentVariable } from "../agent-env.js";
5
+ import { readMcpMode, saveMcpMode } from "../automation-settings.js";
6
+ import { findProject } from "../project.js";
7
+ import { init } from "./init.js";
4
8
  import { createContext } from "../context.js";
5
9
  import { asCavelonError, CavelonError, ExitCode, usageError } from "../errors.js";
6
10
  import { readJsonFile, writeFileAtomic } from "../fsutil.js";
@@ -123,11 +127,11 @@ function normalizeAddress(raw) {
123
127
  return undefined;
124
128
  }
125
129
  }
126
- async function loginStep(ctx) {
130
+ async function loginStep(ctx, nonInteractive = false) {
127
131
  const session = await ctx.session();
128
132
  if (session.url && session.token)
129
133
  return { status: "already", instance: session.url, text: `Already logged in to ${session.url}.` };
130
- if (!canAsk(ctx)) {
134
+ if (!canAsk(ctx) || nonInteractive) {
131
135
  return {
132
136
  status: "not_logged_in",
133
137
  instance: session.url ?? null,
@@ -189,13 +193,13 @@ async function runSetup(ctx, input) {
189
193
  const state = await loadState(env);
190
194
  const plans = [];
191
195
  for (const { agent, found: where } of chosen)
192
- plans.push(await planAgent(agent, where, env, command, skills, process.platform, state.agents[agent.name]));
196
+ plans.push(await planAgent(agent, where, env, command, skills, process.platform, state.agents[agent.name], boolOption(input, "update")));
193
197
  const pending = plans.some((p) => p.changes.some((c) => c.outcome === "planned"));
194
198
  let results = plans.map((plan) => ({ plan, changes: plan.changes }));
195
199
  let declined = false;
196
200
  if (pending) {
197
201
  if (!boolOption(input, "yes")) {
198
- if (!canAsk(ctx)) {
202
+ if (!canAsk(ctx) || boolOption(input, "non-interactive")) {
199
203
  if (!ctx.json)
200
204
  ctx.io.stderr.write(`cavelon setup would change this:\n${planText(plans, notFound)}\n`);
201
205
  throw confirmationRequired("setup changes your coding agents' settings only when you agree", { agents: plans.map((p) => planJson(p)), server: command });
@@ -222,7 +226,7 @@ async function runSetup(ctx, input) {
222
226
  }
223
227
  if (recovered)
224
228
  await saveState(env, state);
225
- const loginReport = declined ? undefined : await loginStep(ctx);
229
+ const loginReport = declined || boolOption(input, "update") ? undefined : await loginStep(ctx, boolOption(input, "non-interactive"));
226
230
  const failed = results.some((r) => r.changes.some((c) => c.outcome === "failed"));
227
231
  const ready = results.filter((r) => r.changes.length && r.changes.every((c) => c.outcome === "done" || c.outcome === "unchanged"));
228
232
  const changed = results.filter((r) => r.changes.some((c) => c.outcome === "done"));
@@ -269,6 +273,85 @@ async function runSetup(ctx, input) {
269
273
  exitCode,
270
274
  };
271
275
  }
276
+ async function runUpdate(ctx, input) {
277
+ const project = await findProject(ctx.io.cwd);
278
+ if (project && !boolOption(input, "yes")) {
279
+ if (!canAsk(ctx) || boolOption(input, "non-interactive"))
280
+ throw confirmationRequired("updating also refreshes the current solution's generated setup", { solution: project.root });
281
+ if (!(await confirm(ctx, `Update Cavelon plugins, owned skills and generated setup in ${project.root}?`, true))) {
282
+ return { data: { agents: [], not_found: [], server: await serverCommand(ctx.io.env), declined: true, login: null, next: [] }, text: "Nothing was changed.", exitCode: ExitCode.ok };
283
+ }
284
+ input = { ...input, options: { ...input.options, yes: true } };
285
+ }
286
+ const result = await runSetup(ctx, input);
287
+ if (result.data.declined || !project)
288
+ return result;
289
+ try {
290
+ const project = await init.run(ctx, { positionals: {}, options: { update: true } });
291
+ return { ...result, data: { ...result.data, project: project.data }, text: `${result.text}\n\nCurrent solution:\n${project.text}` };
292
+ }
293
+ catch (error) {
294
+ const err = asCavelonError(error);
295
+ return { ...result, data: { ...result.data, project_error: err.toJSON() }, text: `${result.text}\n\nCurrent solution update failed: ${err.message}`, exitCode: err.exitCode };
296
+ }
297
+ }
298
+ function interactiveSetup(ctx, input) {
299
+ return canAsk(ctx) && !boolOption(input, "non-interactive") && !agentVariable(ctx.io.env) && !/^(1|true|yes)$/i.test(ctx.io.env.CI ?? "");
300
+ }
301
+ async function chooseMcpMode(ctx, current) {
302
+ ctx.io.stderr.write(`\nMCP YOLO is currently ${current === "yolo" ? "enabled" : "disabled"}. It combines preview and execution for eligible routine changes in the session's selected target. Critical changes still ask for approval.\n`);
303
+ for (;;) {
304
+ const answer = (await readLine(ctx.io, "YOLO for new agent sessions: [y] enable, [n] disable, [Enter] keep current: ")).toLowerCase();
305
+ if (!answer)
306
+ return undefined;
307
+ if (["y", "yes", "j", "ja"].includes(answer))
308
+ return "yolo";
309
+ if (["n", "no", "nein"].includes(answer))
310
+ return "standard";
311
+ ctx.io.stderr.write("Please choose y, n, or Enter.\n");
312
+ }
313
+ }
314
+ async function offerMcpMode(ctx, input, result) {
315
+ if (!interactiveSetup(ctx, input) || boolOption(input, "yes") || result.data.declined)
316
+ return result;
317
+ try {
318
+ const current = await readMcpMode(ctx.io.env);
319
+ const mode = await chooseMcpMode(ctx, current);
320
+ const changed = mode ? await saveMcpMode(ctx.io.env, mode) : false;
321
+ return { ...result, data: { ...result.data, mcp_mode: mode ?? current, mode_changed: changed }, text: `${result.text}\n\nMCP startup mode: ${mode ?? current}. Restart your coding agent to apply the installed CLI, skills and startup mode.` };
322
+ }
323
+ catch (error) {
324
+ const err = asCavelonError(error);
325
+ return { ...result, data: { ...result.data, mode_error: err.toJSON() }, text: `${result.text}\n\nMCP mode selection incomplete: ${err.message}`, exitCode: err.exitCode };
326
+ }
327
+ }
328
+ async function runFollowUp(ctx, input) {
329
+ const installer = boolOption(input, "installer");
330
+ let update = boolOption(input, "update");
331
+ let mode = stringOption(input, "mcp-mode");
332
+ const current = await readMcpMode(ctx.io.env);
333
+ const interactive = interactiveSetup(ctx, input);
334
+ if (installer && interactive) {
335
+ if (!update && !boolOption(input, "skip-update"))
336
+ update = await confirm(ctx, "Set up or update Cavelon plugins and skills in your coding agents (and this solution, if present)?", true);
337
+ if (!mode)
338
+ mode = await chooseMcpMode(ctx, current);
339
+ }
340
+ if (!installer && mode && mode !== current && !boolOption(input, "yes")) {
341
+ if (!interactive)
342
+ throw confirmationRequired("the personal MCP startup mode changes only when you agree", { mcp_mode: mode });
343
+ if (!(await confirm(ctx, `Set the MCP startup mode to ${mode}? Critical changes still ask for approval.`, false)))
344
+ mode = undefined;
345
+ }
346
+ const changed = mode ? await saveMcpMode(ctx.io.env, mode) : false;
347
+ const selected = mode ?? current;
348
+ const report = update ? await runUpdate(ctx, { ...input, options: { ...input.options, update: true, ...(installer ? { yes: true } : {}) } }) : undefined;
349
+ return {
350
+ data: { updated_agents: Boolean(report && !report.data.declined && report.exitCode === ExitCode.ok), mcp_mode: selected, mode_changed: changed, ...(report ? { update: report.data } : {}) },
351
+ text: [report?.text, `MCP startup mode: ${selected}.`, "Next: restart your coding agent or reconnect its Cavelon tools to use the installed CLI, skills and startup mode.", ...(!update ? ["Run cavelon setup --update to refresh plugins and skills later; cavelon setup also guides first-time login."] : [])].filter(Boolean).join("\n\n"),
352
+ exitCode: report?.exitCode ?? ExitCode.ok,
353
+ };
354
+ }
272
355
  function joinLabels(labels, word = "and") {
273
356
  if (labels.length <= 1)
274
357
  return labels.join("");
@@ -421,12 +504,20 @@ export const setup = {
421
504
  "The server starts as `cavelon mcp` when cavelon is installed, otherwise through npx. --check reports what is set up and\n" +
422
505
  "working: each agent's entry, the MCP server starting, and the login. An agent found but never set up for Cavelon is\n" +
423
506
  "reported and skipped (exit 0 when the rest works); --strict, or naming it with --agents, counts it.\n" +
424
- "Without a terminal it changes nothing unless --yes.",
507
+ "--update refreshes plugins and owned skills, including the current solution's generated setup, and keeps your login.\n" +
508
+ "--mcp-mode saves a personal startup choice; restart your coding agent to apply it. Critical changes still need approval.\n" +
509
+ "Interactive setup and --update also offer the YOLO choice; Enter preserves it. --yes keeps it unless --mcp-mode is given.\n" +
510
+ "Without a terminal it changes nothing unless --yes, or explicit --installer update/mode choices are given.",
425
511
  readOnly: false,
426
512
  destructive: true,
427
513
  idempotent: true,
428
514
  mcpTool: false,
429
515
  options: {
516
+ update: { type: "boolean", description: "Refresh agent plugins, owned skills and the current solution's generated setup; keep your login." },
517
+ "mcp-mode": { type: "string", value: "<standard|yolo>", description: "Save the personal mode for new MCP sessions, without editing agent launch commands. Critical changes still need approval." },
518
+ installer: { type: "boolean", description: "Installer follow-up: ask separately about agent updates and YOLO. Without a terminal, keep both unless explicitly selected." },
519
+ "skip-update": { type: "boolean", description: "With --installer: skip the agent update question and leave plugins and skills unchanged." },
520
+ "non-interactive": { type: "boolean", description: "Never ask questions. Installer choices must be passed explicitly; other changes still require --yes." },
430
521
  agents: {
431
522
  type: "string",
432
523
  value: "<list>",
@@ -442,6 +533,8 @@ export const setup = {
442
533
  "cavelon setup",
443
534
  "cavelon setup --agents claude,codex --instance https://cavelon.example.com --yes",
444
535
  "cavelon setup --check",
536
+ "cavelon setup --update",
537
+ "cavelon setup --mcp-mode yolo --yes",
445
538
  "cavelon setup --remove",
446
539
  ],
447
540
  async run(ctx, input) {
@@ -449,10 +542,21 @@ export const setup = {
449
542
  throw usageError("--check and --remove do not go together.");
450
543
  if (boolOption(input, "strict") && !boolOption(input, "check"))
451
544
  throw usageError("--strict goes with --check.");
545
+ const followUp = boolOption(input, "installer") || stringOption(input, "mcp-mode") !== undefined;
546
+ if ((followUp || boolOption(input, "update")) && (boolOption(input, "check") || boolOption(input, "remove")))
547
+ throw usageError("Update and MCP mode options do not go with --check or --remove.");
548
+ if (boolOption(input, "skip-update") && (!boolOption(input, "installer") || boolOption(input, "update")))
549
+ throw usageError("--skip-update requires --installer and cannot be combined with --update.");
550
+ if (stringOption(input, "mcp-mode") !== undefined && !["standard", "yolo"].includes(stringOption(input, "mcp-mode")))
551
+ throw usageError("--mcp-mode must be standard or yolo.");
452
552
  if (boolOption(input, "check"))
453
553
  return runCheck(ctx, input);
454
554
  if (boolOption(input, "remove"))
455
555
  return runRemove(ctx, input);
456
- return runSetup(ctx, input);
556
+ if (followUp)
557
+ return runFollowUp(ctx, input);
558
+ if (boolOption(input, "update"))
559
+ return offerMcpMode(ctx, input, await runUpdate(ctx, input));
560
+ return offerMcpMode(ctx, input, await runSetup(ctx, input));
457
561
  },
458
562
  };
@@ -18,6 +18,7 @@ import { ceilingHint, LIMIT_ABOVE_CEILING, parseLimits, readLimits } from "../li
18
18
  import { digest, fileDigest, fileDigests, listPreviews, loadPreview, previewExpiry, readItemFiles, readPulledFiles, rememberAppliedFiles, retiredPreview, retirePreviews, savePreview, writePulledFiles, writeState, } from "../local-state.js";
19
19
  import { catalogEntry, checkPackage, KIT_CODES, packageVersionOf } from "../package-check.js";
20
20
  import { applyQueryNotes, connectorOffer, importWritesQueries, NEEDS_SUPERADMIN_CODE, queryBlockedHint, queryChanges, queryTools, readQueryBaseline, rememberQueries, schemaKnowsWrites } from "../database-queries.js";
21
+ import { yoloAllows } from "../automation-policy.js";
21
22
  import { cliFix, similarCodes } from "../code-hints.js";
22
23
  import { KIT_ERROR_CODES } from "../kit-codes.js";
23
24
  import { confirmationPointer } from "../change-confirmation.js";
@@ -726,7 +727,7 @@ function importNeedsAPerson(access) {
726
727
  details: { credential: access?.kind ?? null, needs_a_person: true, reason: person },
727
728
  });
728
729
  }
729
- async function confirmPreview(ctx, project, previewId, allowStale) {
730
+ async function confirmPreview(ctx, project, previewId, allowStale, automatic = false) {
730
731
  const stored = await loadPreview(project.root, previewId);
731
732
  const session = await ctx.session();
732
733
  if (!stored) {
@@ -770,13 +771,6 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
770
771
  const driven = drivenByAgent(ctx);
771
772
  const queries = importWritesQueries(stored.preview);
772
773
  const guarded = queries || stored.request[INCLUDE_TENANT_WIDE] === true || stored.request.package.manifest?.scope === "full_config";
773
- if (driven && (queries || stored.person_reason !== null)) {
774
- const into = stored.harness ? `solution ${stored.harness.slug}` : "the tenant";
775
- const reason = stored.person_reason ?? (queries ? QUERY_IMPORT_REASON : "was stored by an older cavelon, which did not record whether it needs a person");
776
- await personApproves(ctx, driven, { tool: "apply", what: `Import preview ${stored.preview_id} into ${into}: it ${reason}.`, command: personApplyCommand(stored), guarded });
777
- }
778
- else if (!driven)
779
- ctx.approved = { guarded };
780
774
  const acting = await actingTarget(ctx);
781
775
  const disk = await readPackage(project.root, project.layout);
782
776
  const changed = await filesChangedSince(project, stored, disk);
@@ -793,6 +787,13 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
793
787
  ctx.warn(`The package files changed since this preview${changed.length ? ` (${list(changed, 5)})` : ""}; importing what the preview showed (--allow-stale). ` +
794
788
  `The files keep their changes, which the instance does not hold; run \`${cavelonCommand("apply")}\` to preview them.`);
795
789
  }
790
+ if (driven && (queries || stored.person_reason !== null)) {
791
+ const into = stored.harness ? `solution ${stored.harness.slug}` : "the tenant";
792
+ const reason = stored.person_reason ?? (queries ? QUERY_IMPORT_REASON : "was stored by an older cavelon, which did not record whether it needs a person");
793
+ await personApproves(ctx, driven, { tool: "apply", what: `Import preview ${stored.preview_id} into ${into}: it ${reason}.`, command: personApplyCommand(stored), guarded });
794
+ }
795
+ else if (!driven && !automatic)
796
+ ctx.approved = { guarded };
796
797
  try {
797
798
  const result = await callStable(ctx, "POST", "/api/v1/agent-graph/import", "importing packages", {
798
799
  body: { ...stored.request, preview_id: stored.preview_id },
@@ -951,7 +952,8 @@ function personReason(preview, harness, mode, env, shared = [], sharedReaches =
951
952
  export const apply = {
952
953
  name: "apply",
953
954
  summary: "Preview the package files against the instance and print a preview id; --confirm <id> imports exactly that preview.",
954
- description: "Without --confirm nothing is imported: the preview shows what changes, which active solutions it reaches, what the target\n" +
955
+ description: "Without --confirm, shows a preview. With --yolo, an eligible routine draft is previewed and imported in one call.\n" +
956
+ "The preview shows what changes, which active solutions it reaches, what the target\n" +
955
957
  "still needs (secrets and variables with the command that sets each, grants, runtime bindings, trigger identities), loop\n" +
956
958
  "budgets and ignored sections, and is stored in .cavelon/. A preview never creates the solution: one the env file names\n" +
957
959
  "that is not on the instance yet gets the `cavelon harness new` command that creates it as a draft. A person sets the\n" +
@@ -1179,6 +1181,18 @@ export const apply = {
1179
1181
  const expired = (await listPreviews(project.root, ctx.io.now())).filter((old) => old.expired);
1180
1182
  await retirePreviews(project.root, expired.map((old) => ({ preview_id: old.preview_id, reason: "expired", at })));
1181
1183
  }
1184
+ const queryEffectsKnown = !queryTools(disk.package).length ||
1185
+ Array.isArray(preview.database_queries?.would_write);
1186
+ if (preview.preview_id && !reason && !refusal && harness?.status === "draft" &&
1187
+ scope === "agent_graph" && queryEffectsKnown && preview.summary && Array.isArray(preview.impact?.active_harnesses) &&
1188
+ await yoloAllows(ctx, harness)) {
1189
+ const applied = await confirmPreview(ctx, project, preview.preview_id, false, true);
1190
+ return {
1191
+ ...applied,
1192
+ data: { ...applied.data, approval: { source: "yolo", reason: "routine draft import" } },
1193
+ text: `YOLO: validated and previewed the routine draft change.\n${applied.text}`,
1194
+ };
1195
+ }
1182
1196
  data.show_to_person = Boolean(reason || refusal);
1183
1197
  const driven = drivenByAgent(ctx);
1184
1198
  const route = !refusal && driven && reason && preview.preview_id ? personRoute(ctx, driven) : undefined;