mdedit-cli 0.2.0 → 0.2.1

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
@@ -1,10 +1,10 @@
1
1
  # `mdedit-cli`
2
2
 
3
- Official command-line interface for [MD Editor](https://mdedit.ai).
3
+ Official command-line interface for [mdedit.ai](https://mdedit.ai).
4
4
 
5
5
  Links:
6
6
  - [CLI docs](https://docs.mdedit.ai/cli)
7
- - [MD Editor homepage](https://mdedit.ai)
7
+ - [mdedit.ai homepage](https://mdedit.ai)
8
8
 
9
9
  ## Install
10
10
 
@@ -41,6 +41,51 @@ mdedit info
41
41
  mdedit health
42
42
  ```
43
43
 
44
+ ## One-shot article edits
45
+
46
+ Apply a unique text replacement through the same article session used by live collaborators:
47
+
48
+ ```bash
49
+ mdedit article edit <articleId> --replace "old text" --with "new text"
50
+ mdedit article edit <articleId> --ops-file ops.json --format json
51
+ ```
52
+
53
+ An ops file is a non-empty JSON array of `replace`, `insert`, or `delete` operations with
54
+ quote, heading, section, or range anchors. The command exits `2` when an anchor is missing,
55
+ `3` when an anchor is ambiguous, and `4` when an edit conflict is reported. In JSON mode,
56
+ the result or typed error is the only value written to stdout.
57
+
58
+ ## Review commands
59
+
60
+ Review agents can comment and suggest with `articles:read,reviews:write`; accepting a
61
+ suggestion also requires `articles:write` because it changes article text.
62
+
63
+ ```bash
64
+ mdedit review list <articleId> --status open --format json
65
+ mdedit review add <articleId> --quote "claim" --body "Needs a source."
66
+ mdedit review reply <articleId> --thread <reviewId> --body "Fixed."
67
+ mdedit review resolve <articleId> --thread <reviewId>
68
+ mdedit suggest <articleId> --quote "teh" --replace "the" --note "Typo"
69
+ ```
70
+
71
+ One-shot review commands use the REST review resources directly, so listing or commenting
72
+ does not open a metered collaboration WebSocket. Mutations always use the
73
+ server-authoritative `review-commands` API.
74
+
75
+ ## Watch an article
76
+
77
+ Keep an article session open and stream newline-delimited JSON for agent loops:
78
+
79
+ ```bash
80
+ mdedit article watch <articleId>
81
+ mdedit article watch <articleId> --workspace <workspaceId> --agent claude-code
82
+ mdedit article watch <articleId> --poll-interval 5000
83
+ ```
84
+
85
+ Each stdout line is one complete JSON event. The stream starts with `session.ready`,
86
+ then reports article changes, review history events, and review snapshots. `Ctrl+C`
87
+ closes the live session cleanly. Non-collaborative articles use REST polling.
88
+
44
89
  ## Agent / AI tool integration
45
90
 
46
91
  The CLI is designed to be used by AI agents without modification.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import { Command as Command7 } from "commander";
4
+ import { Command as Command8 } from "commander";
5
5
  import { readFileSync as readFileSync3 } from "fs";
6
6
  import { dirname as dirname2, join as join3 } from "path";
7
7
  import { fileURLToPath as fileURLToPath2 } from "url";
@@ -110,6 +110,9 @@ var updateArticle = async (workspaceId, articleRequest, fetchers) => {
110
110
  if (articleRequest.contentHash !== void 0) {
111
111
  body.contentHash = articleRequest.contentHash;
112
112
  }
113
+ if (articleRequest.baseArticleRevision !== void 0) {
114
+ body.baseArticleRevision = articleRequest.baseArticleRevision;
115
+ }
113
116
  const response = await fetchV2(
114
117
  `/workspaces/${workspaceId}/articles/${articleRequest.articleId}`,
115
118
  {
@@ -133,7 +136,7 @@ var updateArticle = async (workspaceId, articleRequest, fetchers) => {
133
136
  quotaError.error = errorData.error;
134
137
  throw quotaError;
135
138
  }
136
- throw new errors_default(`Error updating article metadata. ${errorText}`, response.status);
139
+ throw new errors_default(`Error updating article metadata. ${errorText}`, response.status, errorData);
137
140
  }
138
141
  return response.json();
139
142
  };
@@ -201,19 +204,38 @@ var exportArticleZip = async (workspaceId, articleId, fetchers) => {
201
204
  }
202
205
  return response.blob();
203
206
  };
204
- var saveArticleContent = async (workspaceId, articleId, content, fetchers) => {
205
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
207
+ async function fetchErrorFromResponse(prefix, response) {
208
+ const text = await response.text();
209
+ let data;
210
+ try {
211
+ data = JSON.parse(text);
212
+ } catch {
213
+ data = void 0;
214
+ }
215
+ return new errors_default(`${prefix}. ${text}`, response.status, data);
216
+ }
217
+ var saveArticleContent = async (workspaceId, articleId, content, optionsOrFetchers, fetchers) => {
218
+ const maybeFetchers = optionsOrFetchers && "customFetchV2" in optionsOrFetchers ? optionsOrFetchers : fetchers;
219
+ const options = optionsOrFetchers && !("customFetchV2" in optionsOrFetchers) ? optionsOrFetchers : void 0;
220
+ const fetchV2 = maybeFetchers?.customFetchV2 ?? customFetchV2;
206
221
  const urlResponse = await fetchV2(
207
222
  `/workspaces/${workspaceId}/articles/${articleId}/content-upload-url`,
208
- { method: "POST" }
223
+ {
224
+ method: "POST",
225
+ ...options ? {
226
+ body: JSON.stringify({
227
+ baseContentRevision: options.baseContentRevision,
228
+ baseContentHash: options.baseContentHash,
229
+ contentHash: options.contentHash,
230
+ contentLength: new TextEncoder().encode(content).byteLength
231
+ })
232
+ } : {}
233
+ }
209
234
  );
210
235
  if (!urlResponse.ok) {
211
- throw new errors_default(
212
- `Error getting upload URL. ${await urlResponse.text()}`,
213
- urlResponse.status
214
- );
236
+ throw await fetchErrorFromResponse("Error getting upload URL", urlResponse);
215
237
  }
216
- const { uploadUrl } = await urlResponse.json();
238
+ const { uploadUrl, uploadId } = await urlResponse.json();
217
239
  if (!uploadUrl) {
218
240
  throw new errors_default("No upload URL returned", 500);
219
241
  }
@@ -223,11 +245,37 @@ var saveArticleContent = async (workspaceId, articleId, content, fetchers) => {
223
245
  body: content
224
246
  });
225
247
  if (!uploadResponse.ok) {
226
- throw new errors_default(
227
- `Error uploading content to S3. ${await uploadResponse.text()}`,
228
- uploadResponse.status
229
- );
248
+ throw await fetchErrorFromResponse("Error uploading content to S3", uploadResponse);
249
+ }
250
+ if (!options) {
251
+ return;
252
+ }
253
+ if (!uploadId) {
254
+ throw new errors_default("No uploadId returned for conditional content upload", 500);
230
255
  }
256
+ const commitResponse = await fetchV2(
257
+ `/workspaces/${workspaceId}/articles/${articleId}/content-commit`,
258
+ {
259
+ method: "POST",
260
+ body: JSON.stringify({
261
+ uploadId,
262
+ baseContentRevision: options.baseContentRevision,
263
+ baseContentHash: options.baseContentHash,
264
+ contentHash: options.contentHash,
265
+ title: options.title,
266
+ preview: options.preview,
267
+ wordCount: options.wordCount,
268
+ folderId: options.folderId,
269
+ isPinned: options.isPinned,
270
+ isArchived: options.isArchived,
271
+ articleSettings: options.articleSettings
272
+ })
273
+ }
274
+ );
275
+ if (!commitResponse.ok) {
276
+ throw await fetchErrorFromResponse("Error committing article content", commitResponse);
277
+ }
278
+ return commitResponse.json();
231
279
  };
232
280
  var getWorkspaces = async (fetchers) => {
233
281
  const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
@@ -523,17 +571,24 @@ function createSdkClient(config) {
523
571
  delete: async (workspaceId, articleId) => {
524
572
  await withFetchError(() => deleteArticle(workspaceId, articleId, fetchers));
525
573
  },
526
- saveContent: (workspaceId, articleId, content) => withFetchError(() => saveArticleContent(workspaceId, articleId, content, fetchers)),
574
+ saveContent: (workspaceId, articleId, content, options) => withFetchError(() => saveArticleContent(workspaceId, articleId, content, options, fetchers)),
527
575
  exportZip: (workspaceId, articleId) => withFetchError(() => exportArticleZip(workspaceId, articleId, fetchers))
528
576
  }
529
577
  };
530
578
  }
531
579
 
580
+ // src/index.ts
581
+ import { AgentClientHttpError } from "@mdedit/agent-client";
582
+
532
583
  // src/commands/article.ts
533
584
  import { Command } from "commander";
534
585
  import inquirer from "inquirer";
535
586
  import { v4 as uuidv4 } from "uuid";
536
587
  import { readFile, writeFile } from "fs/promises";
588
+ import { createHash } from "crypto";
589
+ import {
590
+ openArticleSession
591
+ } from "@mdedit/agent-client";
537
592
 
538
593
  // src/utils/output.ts
539
594
  import chalk from "chalk";
@@ -830,6 +885,47 @@ function getApiClient() {
830
885
  return client;
831
886
  }
832
887
 
888
+ // src/utils/exitCodes.ts
889
+ import {
890
+ AmbiguousAnchorError,
891
+ AnchorNotFoundError,
892
+ RestContentConflictError
893
+ } from "@mdedit/agent-client";
894
+ var CLI_EXIT_CODES = {
895
+ ERROR: 1,
896
+ ANCHOR_NOT_FOUND: 2,
897
+ AMBIGUOUS_ANCHOR: 3,
898
+ EDIT_CONFLICT: 4
899
+ };
900
+ function typedCliError(error) {
901
+ if (error instanceof AnchorNotFoundError) {
902
+ return {
903
+ exitCode: CLI_EXIT_CODES.ANCHOR_NOT_FOUND,
904
+ code: "ANCHOR_NOT_FOUND",
905
+ message: error.message,
906
+ anchor: error.anchor
907
+ };
908
+ }
909
+ if (error instanceof AmbiguousAnchorError) {
910
+ return {
911
+ exitCode: CLI_EXIT_CODES.AMBIGUOUS_ANCHOR,
912
+ code: "AMBIGUOUS_ANCHOR",
913
+ message: error.message,
914
+ anchor: error.anchor,
915
+ candidates: error.candidates
916
+ };
917
+ }
918
+ if (error instanceof RestContentConflictError) {
919
+ return {
920
+ exitCode: CLI_EXIT_CODES.EDIT_CONFLICT,
921
+ code: "EDIT_CONFLICT",
922
+ message: error.message,
923
+ details: error.data
924
+ };
925
+ }
926
+ return void 0;
927
+ }
928
+
833
929
  // src/presenters/common.ts
834
930
  function isIsoDateString(value) {
835
931
  return /^\d{4}-\d{2}-\d{2}T/.test(value);
@@ -928,6 +1024,32 @@ async function writeBlobToFile(blob, filePath) {
928
1024
  const buffer = Buffer.from(await blob.arrayBuffer());
929
1025
  await writeFile(filePath, buffer);
930
1026
  }
1027
+ function sha256Hex(content) {
1028
+ return createHash("sha256").update(content).digest("hex");
1029
+ }
1030
+ async function readEditOperations(filePath) {
1031
+ const raw = await readFile(filePath, "utf-8");
1032
+ const parsed = JSON.parse(raw);
1033
+ if (!Array.isArray(parsed) || parsed.length === 0) {
1034
+ throw new Error("--ops-file must contain a non-empty JSON array of edit operations.");
1035
+ }
1036
+ for (const operation of parsed) {
1037
+ if (!operation || typeof operation !== "object" || Array.isArray(operation)) {
1038
+ throw new Error("Each edit operation must be a JSON object.");
1039
+ }
1040
+ const candidate = operation;
1041
+ if (!["replace", "insert", "delete"].includes(String(candidate.type))) {
1042
+ throw new Error("Each edit operation type must be replace, insert, or delete.");
1043
+ }
1044
+ if (!candidate.anchor || typeof candidate.anchor !== "object" || Array.isArray(candidate.anchor)) {
1045
+ throw new Error("Each edit operation must include an anchor object.");
1046
+ }
1047
+ if (candidate.type !== "delete" && typeof candidate.text !== "string") {
1048
+ throw new Error("Replace and insert operations must include a text string.");
1049
+ }
1050
+ }
1051
+ return parsed;
1052
+ }
931
1053
  function createArticleCommands() {
932
1054
  const article = new Command("article").description("Manage articles").action(() => article.help());
933
1055
  article.command("list").description("List all articles").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-f, --folder <folderId>", "Filter by folder ID").option("-l, --limit <number>", "Limit number of results (client-side)", "50").option("-o, --offset <number>", "Offset for pagination (client-side)", "0").option("--full", "Show full article objects (all fields)").action(async (options) => {
@@ -1005,7 +1127,12 @@ function createArticleCommands() {
1005
1127
  if (options.content !== void 0) contentText = options.content;
1006
1128
  else if (options.file) contentText = await readContentFromFile(options.file);
1007
1129
  if (contentText !== null) {
1008
- await client.article.saveContent(workspaceId, articleId, contentText);
1130
+ await client.article.saveContent(workspaceId, articleId, contentText, {
1131
+ baseContentRevision: 0,
1132
+ contentHash: sha256Hex(contentText),
1133
+ title: String(title),
1134
+ folderId: options.folder ?? null
1135
+ });
1009
1136
  output.success("Article content uploaded");
1010
1137
  }
1011
1138
  });
@@ -1020,22 +1147,109 @@ function createArticleCommands() {
1020
1147
  if (options.title) body.title = options.title;
1021
1148
  if (options.archive) body.isArchived = true;
1022
1149
  if (options.pin) body.isPinned = true;
1023
- if (Object.keys(body).length > 0) {
1150
+ let contentText = null;
1151
+ if (options.content !== void 0) contentText = options.content;
1152
+ else if (options.file) contentText = await readContentFromFile(options.file);
1153
+ if (contentText === null && Object.keys(body).length > 0) {
1024
1154
  const result = await client.article.update(workspaceId, { articleId, ...body });
1025
1155
  output.success("Article updated successfully");
1026
1156
  output.output(result);
1027
1157
  }
1028
- let contentText = null;
1029
- if (options.content !== void 0) contentText = options.content;
1030
- else if (options.file) contentText = await readContentFromFile(options.file);
1031
1158
  if (contentText !== null) {
1032
- await client.article.saveContent(workspaceId, articleId, contentText);
1159
+ const remoteArticle = await client.article.get(workspaceId, articleId);
1160
+ const baseContentHash = remoteArticle?.contentHashAlg === "sha256" && remoteArticle?.contentHash ? remoteArticle.contentHash : sha256Hex(remoteArticle?.content || "");
1161
+ const result = await client.article.saveContent(workspaceId, articleId, contentText, {
1162
+ baseContentRevision: remoteArticle?.contentRevision ?? 0,
1163
+ baseContentHash,
1164
+ contentHash: sha256Hex(contentText),
1165
+ title: body.title,
1166
+ isArchived: body.isArchived,
1167
+ isPinned: body.isPinned
1168
+ });
1033
1169
  output.success("Article content updated");
1170
+ output.output(result);
1034
1171
  }
1035
1172
  if (Object.keys(body).length === 0 && contentText === null) {
1036
1173
  output.warning("No changes provided. Use --title, --archive, --pin, --file, or --content.");
1037
1174
  }
1038
1175
  });
1176
+ article.command("watch <articleId>").description("Stream article and review changes as newline-delimited JSON").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("--agent <name>", "Agent presence name", "mdedit-cli").option("--poll-interval <milliseconds>", "REST fallback polling interval", "2000").action(async (articleId, options) => {
1177
+ const apiKey = requireApiKey();
1178
+ const workspaceId = requireWorkspaceId(options.workspace);
1179
+ const pollIntervalMs = Number(options.pollInterval);
1180
+ if (!Number.isFinite(pollIntervalMs) || pollIntervalMs < 100) {
1181
+ throw new Error("--poll-interval must be at least 100 milliseconds.");
1182
+ }
1183
+ const abort = new AbortController();
1184
+ const stop = () => abort.abort();
1185
+ process.once("SIGINT", stop);
1186
+ process.once("SIGTERM", stop);
1187
+ let session;
1188
+ let eventCount = 0;
1189
+ const testEventLimit = Number(process.env.MDEDIT_WATCH_TEST_EVENTS || 0);
1190
+ try {
1191
+ session = await openArticleSession({
1192
+ apiKey,
1193
+ websocketToken: apiKey,
1194
+ workspaceId,
1195
+ articleId,
1196
+ agent: { name: options.agent },
1197
+ apiUrl: getApiUrlRaw()
1198
+ });
1199
+ for await (const event of session.events({ signal: abort.signal, pollIntervalMs })) {
1200
+ console.log(JSON.stringify({ articleId, ...event }));
1201
+ eventCount += 1;
1202
+ if (testEventLimit > 0 && eventCount >= testEventLimit) abort.abort();
1203
+ }
1204
+ } finally {
1205
+ process.off("SIGINT", stop);
1206
+ process.off("SIGTERM", stop);
1207
+ await session?.close();
1208
+ }
1209
+ });
1210
+ article.command("edit <articleId>").description("Apply an anchored one-shot edit through an agent article session").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("--replace <text>", "Replace the unique matching text").option("--with <text>", "Replacement text (used with --replace)").option("--ops-file <path>", "Read a JSON array of edit operations from a file").action(async (articleId, options) => {
1211
+ const apiKey = requireApiKey();
1212
+ const workspaceId = requireWorkspaceId(options.workspace);
1213
+ const hasInlineOption = options.replace !== void 0 || options.with !== void 0;
1214
+ if (options.opsFile && hasInlineOption) {
1215
+ throw new Error("--ops-file cannot be combined with --replace or --with.");
1216
+ }
1217
+ if (!options.opsFile && (options.replace === void 0 || options.with === void 0)) {
1218
+ throw new Error("Provide both --replace and --with, or provide --ops-file <path>.");
1219
+ }
1220
+ const operations = options.opsFile ? await readEditOperations(options.opsFile) : [{ type: "replace", anchor: { quote: options.replace }, text: options.with }];
1221
+ let session;
1222
+ let editError;
1223
+ let result;
1224
+ try {
1225
+ session = await openArticleSession({
1226
+ apiKey,
1227
+ websocketToken: apiKey,
1228
+ workspaceId,
1229
+ articleId,
1230
+ agent: { name: "mdedit-cli" },
1231
+ apiUrl: getApiUrlRaw()
1232
+ });
1233
+ result = await session.edit(operations);
1234
+ } catch (error) {
1235
+ editError = error;
1236
+ throw error;
1237
+ } finally {
1238
+ if (session) {
1239
+ try {
1240
+ await session.close();
1241
+ } catch (closeError) {
1242
+ if (editError === void 0) throw closeError;
1243
+ }
1244
+ }
1245
+ }
1246
+ if (!session || !result) throw new Error("Article edit did not return a result.");
1247
+ output.output({ articleId, mode: session.mode, ...result });
1248
+ if (result.conflicts.length > 0) {
1249
+ output.warning("The edit was applied with overlapping remote changes; re-read the article before continuing.");
1250
+ process.exitCode = CLI_EXIT_CODES.EDIT_CONFLICT;
1251
+ }
1252
+ });
1039
1253
  article.command("delete <articleId>").description("Delete an article").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-y, --yes", "Skip confirmation").action(async (articleId, options) => {
1040
1254
  requireApiKey();
1041
1255
  const client = getApiClient();
@@ -1418,9 +1632,10 @@ function presentApiKeyListRow(key) {
1418
1632
  }
1419
1633
 
1420
1634
  // src/commands/apikey.ts
1635
+ var DEFAULT_API_KEY_SCOPES = ["articles:read", "articles:write"];
1421
1636
  function createApiKeyCommands() {
1422
1637
  const apiKey = new Command5("api-key").description("Manage API keys for authentication").aliases(["apikey"]).action(() => apiKey.help());
1423
- apiKey.command("create").description("Create a new API key").option("-n, --name <name>", 'Key name (e.g., "Local Dev", "CI/CD")').option("-d, --description <desc>", "Key description").option("--expires <days>", "Expiration in days (optional)").action(async (options) => {
1638
+ apiKey.command("create").description("Create a new API key").option("-n, --name <name>", 'Key name (e.g., "Local Dev", "CI/CD")').option("-d, --description <desc>", "Key description").option("--expires <days>", "Expiration in days (optional)").option("--scopes <scopes>", "Comma-separated least-privilege scopes").action(async (options) => {
1424
1639
  requireApiKey();
1425
1640
  const client = getApiClient();
1426
1641
  let name = options.name;
@@ -1444,10 +1659,16 @@ function createApiKeyCommands() {
1444
1659
  }
1445
1660
  expiresInDays = days;
1446
1661
  }
1662
+ const scopesRaw = options.scopes;
1663
+ const scopes = scopesRaw === void 0 ? DEFAULT_API_KEY_SCOPES : [...new Set(scopesRaw.split(",").map((scope) => scope.trim()).filter(Boolean))];
1664
+ if (scopesRaw !== void 0 && scopes?.length === 0) {
1665
+ throw new Error("--scopes must contain at least one scope.");
1666
+ }
1447
1667
  output.info("Creating API key...");
1448
1668
  const req = { name };
1449
1669
  if (options.description) req.description = options.description;
1450
1670
  if (expiresInDays !== void 0) req.expiresInDays = expiresInDays;
1671
+ req.scopes = scopes;
1451
1672
  const result = await client.apiKeys.create(req);
1452
1673
  output.success("API key created successfully!");
1453
1674
  output.warning("IMPORTANT: Save this API key now. It will not be shown again.");
@@ -1539,7 +1760,7 @@ var TARGETS = {
1539
1760
  sectionHeading: "## mdedit CLI"
1540
1761
  }
1541
1762
  };
1542
- function installToTarget(targetKey, spec, skillContent, global) {
1763
+ function installToTarget(spec, skillContent, global) {
1543
1764
  const targetPath = spec.path(process.cwd(), global);
1544
1765
  const dir = dirname(resolve(targetPath));
1545
1766
  if (!existsSync2(dir)) {
@@ -1591,7 +1812,7 @@ function createSkillCommands() {
1591
1812
  }
1592
1813
  const keys = target === "all" ? [...NAMED_TARGETS] : [target];
1593
1814
  for (const key of keys) {
1594
- installToTarget(key, TARGETS[key], skillContent, global);
1815
+ installToTarget(TARGETS[key], skillContent, global);
1595
1816
  }
1596
1817
  output.info("");
1597
1818
  output.info("To view the installed skill at any time: mdedit skill show");
@@ -1599,6 +1820,106 @@ function createSkillCommands() {
1599
1820
  return skill;
1600
1821
  }
1601
1822
 
1823
+ // src/commands/review.ts
1824
+ import { Command as Command7 } from "commander";
1825
+ import {
1826
+ openArticleReviewSession
1827
+ } from "@mdedit/agent-client";
1828
+ async function withReview(articleId, workspaceId, operation) {
1829
+ const apiKey = requireApiKey();
1830
+ const review = openArticleReviewSession({ apiKey, workspaceId, articleId, apiUrl: getApiUrlRaw() });
1831
+ return { mode: "rest", result: await operation(review) };
1832
+ }
1833
+ function quoteAnchor(options) {
1834
+ const occurrence = options.occurrence === void 0 ? void 0 : Number(options.occurrence);
1835
+ if (occurrence !== void 0 && (!Number.isInteger(occurrence) || occurrence < 1)) {
1836
+ throw new Error("--occurrence must be a one-based positive integer.");
1837
+ }
1838
+ return {
1839
+ quote: options.quote,
1840
+ ...occurrence ? { occurrence } : {},
1841
+ ...options.before || options.after ? { context: { before: options.before, after: options.after } } : {}
1842
+ };
1843
+ }
1844
+ function addCommon(command) {
1845
+ return command.option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-t, --target <targetId>", "Markdown review target", "content.md");
1846
+ }
1847
+ function addQuote(command) {
1848
+ return addCommon(command).requiredOption("-q, --quote <text>", "Unique text to anchor the review item").option("--occurrence <number>", "One-based occurrence when the quote repeats").option("--before <text>", "Required context immediately before the quote").option("--after <text>", "Required context immediately after the quote");
1849
+ }
1850
+ function presentReviewItem(item) {
1851
+ return {
1852
+ id: item.value.id,
1853
+ type: item.itemType,
1854
+ targetId: item.targetId,
1855
+ status: item.value.status,
1856
+ author: item.value.createdBy?.kind === "agent" ? `${item.value.createdBy.agentName || item.value.createdBy.displayName}${item.value.createdBy.onBehalfOf ? ` \xB7 for ${item.value.createdBy.onBehalfOf}` : ""}` : item.value.createdBy?.displayName,
1857
+ body: "body" in item.value ? item.value.body : item.value.note,
1858
+ ...item.itemType === "suggestion" ? { originalText: item.value.originalText, suggestedText: item.value.suggestedText } : {}
1859
+ };
1860
+ }
1861
+ function createReviewCommands() {
1862
+ const review = new Command7("review").description("Review an article through server-authoritative agent commands").action(() => review.help());
1863
+ addCommon(review.command("list <articleId>").description("List article review items").option("-s, --status <status>", "Filter by review status")).action(async (articleId, options) => {
1864
+ const workspaceId = requireWorkspaceId(options.workspace);
1865
+ const { result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession.list({
1866
+ status: options.status,
1867
+ targetId: options.target
1868
+ }));
1869
+ output.output(output.isJson() ? result : result.map(presentReviewItem));
1870
+ });
1871
+ addQuote(review.command("add <articleId>").description("Add a comment anchored to quoted text").requiredOption("-b, --body <text>", "Comment body")).action(async (articleId, options) => {
1872
+ const workspaceId = requireWorkspaceId(options.workspace);
1873
+ const { mode, result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession.addComment({
1874
+ anchor: quoteAnchor(options),
1875
+ body: options.body,
1876
+ targetId: options.target
1877
+ }));
1878
+ output.output({ articleId, mode, ...result });
1879
+ });
1880
+ addCommon(review.command("reply <articleId>").description("Reply to a comment or suggestion thread").requiredOption("--thread <reviewId>", "Review thread ID").requiredOption("-b, --body <text>", "Reply body")).action(async (articleId, options) => {
1881
+ const workspaceId = requireWorkspaceId(options.workspace);
1882
+ const { mode, result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession.reply({
1883
+ threadId: options.thread,
1884
+ body: options.body,
1885
+ targetId: options.target
1886
+ }));
1887
+ output.output({ articleId, mode, ...result });
1888
+ });
1889
+ for (const verb of ["resolve", "reopen", "accept", "reject"]) {
1890
+ addCommon(review.command(`${verb} <articleId>`).description(`${verb[0].toUpperCase()}${verb.slice(1)} a review thread`).requiredOption("--thread <reviewId>", "Review thread ID")).action(async (articleId, options) => {
1891
+ const workspaceId = requireWorkspaceId(options.workspace);
1892
+ const { mode, result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession[verb]({
1893
+ threadId: options.thread,
1894
+ targetId: options.target
1895
+ }));
1896
+ output.output({ articleId, mode, ...result });
1897
+ });
1898
+ }
1899
+ addCommon(review.command("delete <articleId>").description("Delete a review item or one of its replies").requiredOption("--thread <reviewId>", "Review thread ID").option("--reply <replyId>", "Reply ID; omit to delete the whole review item")).action(async (articleId, options) => {
1900
+ const workspaceId = requireWorkspaceId(options.workspace);
1901
+ const { mode, result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession.delete({
1902
+ threadId: options.thread,
1903
+ replyId: options.reply,
1904
+ targetId: options.target
1905
+ }));
1906
+ output.output({ articleId, mode, ...result });
1907
+ });
1908
+ return review;
1909
+ }
1910
+ function createSuggestCommand() {
1911
+ return addQuote(new Command7("suggest").description("Suggest a replacement anchored to quoted text").argument("<articleId>", "Article ID").requiredOption("-r, --replace <text>", "Replacement text").option("-n, --note <text>", "Optional explanation for the suggestion")).action(async (articleId, options) => {
1912
+ const workspaceId = requireWorkspaceId(options.workspace);
1913
+ const { mode, result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession.suggest({
1914
+ anchor: quoteAnchor(options),
1915
+ replace: options.replace,
1916
+ note: options.note,
1917
+ targetId: options.target
1918
+ }));
1919
+ output.output({ articleId, mode, ...result });
1920
+ });
1921
+ }
1922
+
1602
1923
  // src/index.ts
1603
1924
  var __filename2 = fileURLToPath2(import.meta.url);
1604
1925
  var __dirname2 = dirname2(__filename2);
@@ -1608,7 +1929,7 @@ try {
1608
1929
  version = packageJson.version || version;
1609
1930
  } catch {
1610
1931
  }
1611
- var program = new Command7();
1932
+ var program = new Command8();
1612
1933
  program.name("mdedit").description("MDEdit.ai CLI - Command-line interface for the markdown editor platform").version(version).option("-F, --format <format>", "Output format: json, table, or plain (default: table)").option("--local", "Use local API at http://localhost:8080").option("--api-url <url>", "Override API URL for this invocation").option("--api-key <key>", "Override API key for this invocation (use env/config in preference)").option("--workspace <workspaceId>", "Override default workspaceId for this invocation").option("--debug", "Show debug output (stacks, request info)").hook("preAction", (thisCommand) => {
1613
1934
  const opts = typeof thisCommand.optsWithGlobals === "function" ? (
1614
1935
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -1627,6 +1948,8 @@ program.addCommand(createFolderCommands());
1627
1948
  program.addCommand(createConfigCommands());
1628
1949
  program.addCommand(createApiKeyCommands());
1629
1950
  program.addCommand(createSkillCommands());
1951
+ program.addCommand(createReviewCommands());
1952
+ program.addCommand(createSuggestCommand());
1630
1953
  program.command("health").description("Check API health status").action(async () => {
1631
1954
  const base = getApiBaseUrlRoot();
1632
1955
  const response = await fetch(`${base}/health`, { method: "GET" });
@@ -1703,7 +2026,37 @@ async function main() {
1703
2026
  await program.parseAsync(process.argv);
1704
2027
  } catch (err) {
1705
2028
  const debug = process.env.MDEDIT_DEBUG === "1";
1706
- if (err instanceof FetchError2) {
2029
+ const typedError = typedCliError(err);
2030
+ if (typedError) {
2031
+ if (output.isJson()) {
2032
+ const { exitCode: _exitCode, ...error } = typedError;
2033
+ output.output({ error });
2034
+ } else {
2035
+ output.error(typedError.message);
2036
+ if (typedError.code === "AMBIGUOUS_ANCHOR") {
2037
+ output.info("Hint: use an ops file with occurrence or context to select one match.");
2038
+ }
2039
+ }
2040
+ if (debug && err instanceof Error && err.stack) output.warning(err.stack);
2041
+ process.exitCode = typedError.exitCode;
2042
+ return;
2043
+ }
2044
+ if (err instanceof AgentClientHttpError) {
2045
+ const data = err.data;
2046
+ const code = data?.code ?? data?.error?.code;
2047
+ const details = data?.details ?? data?.error?.details;
2048
+ if (output.isJson()) {
2049
+ output.output({ error: { code: code || "API_REQUEST_FAILED", message: err.message, status: err.status, details } });
2050
+ } else {
2051
+ output.error(`API request failed (${err.status}): ${err.message}`);
2052
+ if (details?.requiredScope === "articles:write") {
2053
+ output.info("Hint: accepting a suggestion changes article text and requires an API key with articles:write.");
2054
+ } else if (err.status === 403) {
2055
+ output.info("Hint: review keys need articles:read,reviews:write; accepting suggestions additionally needs articles:write.");
2056
+ }
2057
+ }
2058
+ if (debug && err.stack) output.warning(err.stack);
2059
+ } else if (err instanceof FetchError2) {
1707
2060
  output.error(`API request failed (${err.status}): ${err.message}`);
1708
2061
  if (err.status === 401) {
1709
2062
  output.info("Hint: set an API key via `mdedit config set apiKey <key>` or pass `--api-key <key>`.");
@@ -1719,7 +2072,7 @@ async function main() {
1719
2072
  } else {
1720
2073
  output.error(err);
1721
2074
  }
1722
- process.exitCode = 1;
2075
+ process.exitCode = CLI_EXIT_CODES.ERROR;
1723
2076
  }
1724
2077
  }
1725
2078
  await main();