@creator-notes/cnotes 0.79.0 → 0.80.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "creator-notes-cli",
3
- "version": "0.79.0",
3
+ "version": "0.80.0",
4
4
  "description": "CreatorNotes CLI: create notes, build canvases, search knowledge from the terminal",
5
5
  "author": {
6
6
  "name": "CreatorNotes",
@@ -1 +1 @@
1
- {"version":3,"file":"canvas.d.ts","sourceRoot":"","sources":["../../src/commands/canvas.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAU,MAAM,WAAW,CAAC;AAyL5C,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAu9F7D"}
1
+ {"version":3,"file":"canvas.d.ts","sourceRoot":"","sources":["../../src/commands/canvas.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAU,MAAM,WAAW,CAAC;AA2L5C,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CA2gG7D"}
@@ -2,11 +2,12 @@ import { writeFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { Option } from "commander";
4
4
  import { ApiClient, resolveActiveAgentRun } from "../lib/api-client.js";
5
+ import { resolveActiveSlot, fetchRunStatus, isStillOpen } from "../lib/active-run.js";
5
6
  import { resolveBaseConfig, resolveConfig } from "../lib/config.js";
6
7
  import { ApiError, CliError, EXIT_CODES, handleError, ValidationError } from "../lib/errors.js";
7
8
  import { parseJsonOption, readFileSafe } from "../lib/fs-utils.js";
8
- import { loadConfig, setActiveAgentRunId, clearActiveAgentRunId, getActiveAgentRunId, } from "../lib/auth-store.js";
9
- import { outputJson, outputTable, outputQuiet, truncate, timeAgo, formatAgo } from "../lib/output.js";
9
+ import { loadConfig, setActiveAgentRunId, registerAgentRun, unregisterAgentRun, isOwnedAgentRun, } from "../lib/auth-store.js";
10
+ import { outputJson, outputTable, outputQuiet, truncate, timeAgo } from "../lib/output.js";
10
11
  import { readHeadlineWarnings, reportHeadlineWarnings } from "../lib/headline-warnings.js";
11
12
  import { readCanvasMarkdown, renderCanvasMarkdown, parseSharedCanvasLink, sameServerOrigin, readCanvasSection, renderCanvasSectionMarkdown, } from "../lib/canvas-read.js";
12
13
  import { resolveAgentSession } from "../lib/claude-session.js";
@@ -2258,11 +2259,13 @@ Examples:
2258
2259
  .requiredOption("--prompt <text>", "Run headline. Verb-first, at most 110 characters. The platform may rewrite it. The body is kept.")
2259
2260
  .option("--rationale <text>", "Optional rationale (e.g. agent's plan)")
2260
2261
  .option("--force", "If an active run already exists on this server, end it server-side and start a fresh one")
2262
+ .option("--detached", "Open an independent run that does NOT become the active run on this server. Writes attach to it only through the printed CNOTES_AGENT_RUN_ID / CNOTES_AGENT_BEFORE_SNAPSHOT_ID exports. Use when another agent may hold the active run on this machine.")
2261
2263
  .addHelpText("after", `
2262
2264
  Examples:
2263
2265
  $ cnotes canvas agent-run begin --canvas <id> --prompt "Reorganize into sections"
2264
2266
  $ cnotes canvas place <id> --spec ./layout.json # attaches automatically
2265
2267
  $ cnotes canvas agent-run end --canvas <id>
2268
+ $ eval "$(cnotes canvas agent-run begin --canvas <id> --prompt "..." --detached)" # your own run, env-scoped
2266
2269
 
2267
2270
  After 'begin', every subsequent cnotes write on this server attaches to the
2268
2271
  run automatically — no env var to export, and it survives across separate
@@ -2270,7 +2273,8 @@ shells. End with 'cnotes canvas agent-run end --canvas <id>'.
2270
2273
 
2271
2274
  If a run is already open (from 'agent-run begin' or 'operations begin'),
2272
2275
  begin refuses rather than silently clobbering it. Pass --force to end the
2273
- prior run server-side and start fresh.
2276
+ prior run server-side and start fresh, or --detached to open your own run
2277
+ alongside it (eval the printed exports so your writes carry it).
2274
2278
  `)
2275
2279
  .action(async (opts) => {
2276
2280
  const cfg = resolveConfig(program.opts());
@@ -2286,24 +2290,17 @@ prior run server-side and start fresh.
2286
2290
  // pointer, and a request carries exactly one X-Agent-Run-Id — so a
2287
2291
  // second begin would either clobber the first or silently attach writes
2288
2292
  // to the wrong run. Mirrors `cnotes operations begin`.
2289
- const existing = getActiveAgentRunId(loadConfig(), cfg.serverUrl);
2290
- if (existing) {
2291
- if (opts.force) {
2292
- try {
2293
- await api.post("/api/operations", {
2294
- action: "end",
2295
- agentRunId: existing.agentRunId,
2296
- });
2297
- }
2298
- catch {
2299
- // Best-effort: ending an already-completed/abandoned run is
2300
- // idempotent server-side. Either way clear the local pointer so
2301
- // the caller isn't wedged.
2302
- }
2303
- clearActiveAgentRunId(loadConfig(), cfg.serverUrl);
2304
- }
2305
- else {
2306
- throw new CliError(`An active agent-run already exists on this server (agentRunId ${existing.agentRunId}, started ${formatAgo(existing.startedAt)}).`, EXIT_CODES.CONFLICT, "End it first (`cnotes canvas agent-run end --canvas <id>` or `cnotes operations end`), or pass --force to end it server-side and start fresh.");
2293
+ // A detached run never competes for the pointer, so it needs no
2294
+ // conflict check — and must not --force the active run away either.
2295
+ // Otherwise a stale holder (crashed bot) is forgotten and a running
2296
+ // one needs --force. Mirrors `cnotes operations begin`.
2297
+ if (!opts.detached) {
2298
+ const slot = await resolveActiveSlot(api, cfg.serverUrl, {
2299
+ force: opts.force,
2300
+ endCommand: "cnotes canvas agent-run end --canvas <id>` or `cnotes operations end",
2301
+ });
2302
+ if (slot.forgot) {
2303
+ console.error(`# forgot stale run ${slot.forgot.agentRunId} (${slot.forgot.status} server-side); starting fresh`);
2307
2304
  }
2308
2305
  }
2309
2306
  const body = {
@@ -2328,13 +2325,26 @@ prior run server-side and start fresh.
2328
2325
  // getRevertContext bails — "Revert this run" is dead for the whole
2329
2326
  // batch. Persisting the run id without it produces a run that looks
2330
2327
  // perfectly healthy and cannot be undone.
2331
- const persisted = setActiveAgentRunId(loadConfig(), cfg.serverUrl, data.agentRunId, Date.now(), data.beforeCheckpointId);
2328
+ //
2329
+ // --detached records the run only in the open-run registry (so `end`
2330
+ // knows it is ours) and leaves the active pointer alone: the run is
2331
+ // carried by the printed env exports instead, so another agent's
2332
+ // active run on this machine is neither clobbered nor ended.
2333
+ const tracked = opts.detached
2334
+ ? registerAgentRun(loadConfig(), cfg.serverUrl, data.agentRunId, {
2335
+ startedAt: Date.now(),
2336
+ beforeSnapshotId: data.beforeCheckpointId,
2337
+ canvasId: opts.canvas,
2338
+ detached: true,
2339
+ })
2340
+ : setActiveAgentRunId(loadConfig(), cfg.serverUrl, data.agentRunId, Date.now(), data.beforeCheckpointId);
2341
+ const persisted = tracked && !opts.detached;
2332
2342
  // No stored config entry for this server (token came from --token /
2333
2343
  // CNOTES_TOKEN against a server never logged into), so there is nowhere
2334
2344
  // to record the run. Say so rather than printing "every write now
2335
2345
  // attaches" — silently attaching nothing is the bug this flow exists to
2336
2346
  // kill. stderr, so it can't corrupt --json or the eval form.
2337
- if (!persisted) {
2347
+ if (!tracked && !opts.detached) {
2338
2348
  console.error(`# WARNING: could not persist the active run for ${cfg.serverUrl} — no stored login for that server.`);
2339
2349
  console.error(`# Subsequent cnotes writes will NOT attach to it. Either run \`cnotes auth login\`,`);
2340
2350
  console.error(`# or use the env form: eval "$(cnotes canvas agent-run begin --canvas ${opts.canvas} --prompt "...")"`);
@@ -2345,20 +2355,28 @@ prior run server-side and start fresh.
2345
2355
  return;
2346
2356
  }
2347
2357
  if (wantsJson) {
2348
- outputJson(data);
2358
+ outputJson({
2359
+ ...data,
2360
+ activeRunPersisted: persisted,
2361
+ detached: Boolean(opts.detached),
2362
+ });
2349
2363
  return;
2350
2364
  }
2351
2365
  // Still print the eval-friendly exports so the older
2352
2366
  // eval "$(npx cnotes canvas agent-run begin ...)"
2353
2367
  // form keeps working. The env var takes precedence over the persisted
2354
- // pointer, so both paths agree on the same run.
2368
+ // pointer, so both paths agree on the same run. For a detached run the
2369
+ // exports are the ONLY way writes attach, so they are not optional.
2355
2370
  console.log(`export CNOTES_AGENT_RUN_ID=${data.agentRunId}`);
2356
2371
  console.log(`export CNOTES_AGENT_BEFORE_SNAPSHOT_ID=${data.beforeCheckpointId}`);
2357
2372
  console.error(`# agent run started: v${data.beforeSnapshotNumber} (${data.agentRunId})`);
2358
2373
  if (persisted) {
2359
2374
  console.error(`# every cnotes write on this server now attaches to this run`);
2360
2375
  }
2361
- console.error(`# end with: npx cnotes canvas agent-run end --canvas ${opts.canvas}`);
2376
+ else if (opts.detached) {
2377
+ console.error(`# detached run: writes attach only with the two exports above set (eval this output)`);
2378
+ }
2379
+ console.error(`# end with: npx cnotes canvas agent-run end --canvas ${opts.canvas}${opts.detached ? ` --run-id ${data.agentRunId}` : ""}`);
2362
2380
  }
2363
2381
  catch (error) {
2364
2382
  handleError(error, wantsJson);
@@ -2392,6 +2410,16 @@ Examples:
2392
2410
  });
2393
2411
  console.error(`# agent run started: v${begin.beforeSnapshotNumber} (${begin.agentRunId})`);
2394
2412
  reportHeadlineWarnings(readHeadlineWarnings(begin));
2413
+ // Record the run as one this CLI opened — in the registry only, never as
2414
+ // the active pointer (see below). If the close at the end fails and the
2415
+ // user follows the printed `agent-run end --run-id` advice, `end` then
2416
+ // recognises the run as ours instead of refusing it.
2417
+ registerAgentRun(loadConfig(), cfg.serverUrl, begin.agentRunId, {
2418
+ startedAt: Date.now(),
2419
+ beforeSnapshotId: begin.beforeCheckpointId,
2420
+ canvasId: opts.canvas,
2421
+ detached: true,
2422
+ });
2395
2423
  // Step 2: spawn the wrapped command with the run env var set.
2396
2424
  // stdio is inherited so the subprocess prints to the user's terminal
2397
2425
  // exactly as if they'd run it themselves. Only runId + before-snapshot
@@ -2436,6 +2464,9 @@ Examples:
2436
2464
  action: "agentRunEnd",
2437
2465
  agentRunId: begin.agentRunId,
2438
2466
  });
2467
+ // Closed cleanly: forget it. Only this run — an outer `operations`
2468
+ // run this wrap was nested in stays active and open.
2469
+ unregisterAgentRun(loadConfig(), cfg.serverUrl, begin.agentRunId);
2439
2470
  const status = exitCode === 0 ? "completed" : `exited ${exitCode}`;
2440
2471
  console.error(`# agent run ${status}: v${end.afterSnapshotNumber} (${begin.agentRunId})`);
2441
2472
  if (cfg.json) {
@@ -2459,7 +2490,15 @@ Examples:
2459
2490
  .command("end")
2460
2491
  .description("Close an agent-run session — captures an after-snapshot and clears the active run")
2461
2492
  .requiredOption("--canvas <id>", "Canvas ID to close")
2462
- .option("--run-id <id>", "Agent run ID (defaults to the active run on this server, then CNOTES_AGENT_RUN_ID)")
2493
+ .option("--run-id <id>", "Agent run ID (defaults to CNOTES_AGENT_RUN_ID, then the active run on this server)")
2494
+ .option("--force", "End the run even though this CLI did not open it (another machine or login)")
2495
+ .addHelpText("after", `
2496
+ End only closes runs this CLI opened. Ending one run never touches another:
2497
+ the active pointer is cleared only when it was pointing at the run that
2498
+ ended, so a detached run can end while the active run stays open and vice
2499
+ versa. A run id this CLI has no record of is refused (exit code 5); pass
2500
+ --force to end it anyway.
2501
+ `)
2463
2502
  .action(async (opts) => {
2464
2503
  const cfg = resolveConfig(program.opts());
2465
2504
  const api = new ApiClient(cfg.serverUrl, cfg.token);
@@ -2476,18 +2515,26 @@ Examples:
2476
2515
  if (!runId) {
2477
2516
  throw new ValidationError("No active run on this server, and no --run-id passed", "Open one with `cnotes canvas agent-run begin --canvas <id> --prompt \"...\"`, or pass --run-id <id> to close a specific run.");
2478
2517
  }
2518
+ // Never close a run this CLI did not open (see `operations end`): the
2519
+ // registry holds every run begin/wrap opened here; `null` means there
2520
+ // is no stored login to check against, so let it through.
2521
+ // A run that is already over is harmless to end (idempotent), so
2522
+ // only a live unknown run is refused.
2523
+ const owned = isOwnedAgentRun(loadConfig(), cfg.serverUrl, runId);
2524
+ if (owned === false && !opts.force && isStillOpen(await fetchRunStatus(api, runId))) {
2525
+ throw new CliError(`This CLI has no record of opening run ${runId} on ${cfg.serverUrl}; it was not started here.`, EXIT_CODES.CONFLICT, "Ending it could close another agent's run. If you are sure, pass --force.");
2526
+ }
2479
2527
  const data = await api.post(canvasActionPath(opts.canvas, cfg.workspaceId), {
2480
2528
  action: "agentRunEnd",
2481
2529
  agentRunId: runId,
2530
+ ...(opts.force ? { force: true } : {}),
2482
2531
  });
2483
- // Clear the local pointer so the next write detaches. Only clear when
2484
- // it matches the run we just closed, so a concurrent begin from another
2485
- // shell isn't stomped. Done after a successful response so a transient
2486
- // server error can't desync local state from the server.
2487
- const active = getActiveAgentRunId(loadConfig(), cfg.serverUrl);
2488
- if (active?.agentRunId === data.agentRunId) {
2489
- clearActiveAgentRunId(loadConfig(), cfg.serverUrl);
2490
- }
2532
+ // Forget this run, and only this run: it leaves the open-run registry,
2533
+ // and the active pointer is cleared only when it was pointing at the
2534
+ // run we just closed — a concurrent run from another shell (active or
2535
+ // detached) is left as it was. Done after a successful response so a
2536
+ // transient server error can't desync local state from the server.
2537
+ unregisterAgentRun(loadConfig(), cfg.serverUrl, data.agentRunId);
2491
2538
  if (cfg.quiet) {
2492
2539
  outputQuiet(String(data.afterSnapshotNumber));
2493
2540
  return;