mdedit-cli 0.2.0 → 0.2.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/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;
230
252
  }
253
+ if (!uploadId) {
254
+ throw new errors_default("No uploadId returned for conditional content upload", 500);
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;
@@ -465,6 +513,20 @@ var revokeApiKey = async (keyId, fetchers) => {
465
513
  }
466
514
  return response.json();
467
515
  };
516
+ var checkpointCollaboration = async (workspaceId, articleId, fetchers) => {
517
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
518
+ const response = await fetchV2(
519
+ `/workspaces/${workspaceId}/articles/${articleId}/collaboration/checkpoint`,
520
+ { method: "POST" }
521
+ );
522
+ if (!response.ok) {
523
+ throw new errors_default(
524
+ `Error checkpointing collaboration. ${await response.text()}`,
525
+ response.status
526
+ );
527
+ }
528
+ return response.json();
529
+ };
468
530
  var FetchError2 = class extends Error {
469
531
  status;
470
532
  data;
@@ -523,17 +585,27 @@ function createSdkClient(config) {
523
585
  delete: async (workspaceId, articleId) => {
524
586
  await withFetchError(() => deleteArticle(workspaceId, articleId, fetchers));
525
587
  },
526
- saveContent: (workspaceId, articleId, content) => withFetchError(() => saveArticleContent(workspaceId, articleId, content, fetchers)),
588
+ saveContent: (workspaceId, articleId, content, options) => withFetchError(() => saveArticleContent(workspaceId, articleId, content, options, fetchers)),
527
589
  exportZip: (workspaceId, articleId) => withFetchError(() => exportArticleZip(workspaceId, articleId, fetchers))
590
+ },
591
+ collaboration: {
592
+ checkpoint: (workspaceId, articleId) => withFetchError(() => checkpointCollaboration(workspaceId, articleId, fetchers))
528
593
  }
529
594
  };
530
595
  }
531
596
 
597
+ // src/index.ts
598
+ import { AgentClientHttpError } from "@mdedit/agent-client";
599
+
532
600
  // src/commands/article.ts
533
601
  import { Command } from "commander";
534
602
  import inquirer from "inquirer";
535
603
  import { v4 as uuidv4 } from "uuid";
536
604
  import { readFile, writeFile } from "fs/promises";
605
+ import { createHash } from "crypto";
606
+ import {
607
+ openArticleSession
608
+ } from "@mdedit/agent-client";
537
609
 
538
610
  // src/utils/output.ts
539
611
  import chalk from "chalk";
@@ -830,6 +902,76 @@ function getApiClient() {
830
902
  return client;
831
903
  }
832
904
 
905
+ // src/utils/exitCodes.ts
906
+ import {
907
+ AmbiguousAnchorError,
908
+ AnchorNotFoundError,
909
+ RestContentConflictError
910
+ } from "@mdedit/agent-client";
911
+ var CLI_EXIT_CODES = {
912
+ ERROR: 1,
913
+ ANCHOR_NOT_FOUND: 2,
914
+ AMBIGUOUS_ANCHOR: 3,
915
+ EDIT_CONFLICT: 4
916
+ };
917
+ var ArticleCreateContentError = class extends Error {
918
+ articleId;
919
+ compensated;
920
+ contentError;
921
+ compensationError;
922
+ constructor(args) {
923
+ const contentError = args.contentError instanceof Error ? args.contentError.message : String(args.contentError);
924
+ const compensationError = args.compensationError instanceof Error ? args.compensationError.message : args.compensationError === void 0 ? void 0 : String(args.compensationError);
925
+ super(args.compensated ? `Initial article content could not be saved; the created article ${args.articleId} was rolled back.` : `Initial article content could not be saved and article ${args.articleId} could not be rolled back.`);
926
+ this.name = "ArticleCreateContentError";
927
+ this.articleId = args.articleId;
928
+ this.compensated = args.compensated;
929
+ this.contentError = contentError;
930
+ this.compensationError = compensationError;
931
+ }
932
+ };
933
+ function typedCliError(error) {
934
+ if (error instanceof ArticleCreateContentError) {
935
+ return {
936
+ exitCode: CLI_EXIT_CODES.ERROR,
937
+ code: "ARTICLE_CREATE_CONTENT_FAILED",
938
+ message: error.message,
939
+ details: {
940
+ articleId: error.articleId,
941
+ compensated: error.compensated,
942
+ contentError: error.contentError,
943
+ ...error.compensationError ? { compensationError: error.compensationError } : {}
944
+ }
945
+ };
946
+ }
947
+ if (error instanceof AnchorNotFoundError) {
948
+ return {
949
+ exitCode: CLI_EXIT_CODES.ANCHOR_NOT_FOUND,
950
+ code: "ANCHOR_NOT_FOUND",
951
+ message: error.message,
952
+ anchor: error.anchor
953
+ };
954
+ }
955
+ if (error instanceof AmbiguousAnchorError) {
956
+ return {
957
+ exitCode: CLI_EXIT_CODES.AMBIGUOUS_ANCHOR,
958
+ code: "AMBIGUOUS_ANCHOR",
959
+ message: error.message,
960
+ anchor: error.anchor,
961
+ candidates: error.candidates
962
+ };
963
+ }
964
+ if (error instanceof RestContentConflictError) {
965
+ return {
966
+ exitCode: CLI_EXIT_CODES.EDIT_CONFLICT,
967
+ code: "EDIT_CONFLICT",
968
+ message: error.message,
969
+ details: error.data
970
+ };
971
+ }
972
+ return void 0;
973
+ }
974
+
833
975
  // src/presenters/common.ts
834
976
  function isIsoDateString(value) {
835
977
  return /^\d{4}-\d{2}-\d{2}T/.test(value);
@@ -928,6 +1070,32 @@ async function writeBlobToFile(blob, filePath) {
928
1070
  const buffer = Buffer.from(await blob.arrayBuffer());
929
1071
  await writeFile(filePath, buffer);
930
1072
  }
1073
+ function sha256Hex(content) {
1074
+ return createHash("sha256").update(content).digest("hex");
1075
+ }
1076
+ async function readEditOperations(filePath) {
1077
+ const raw = await readFile(filePath, "utf-8");
1078
+ const parsed = JSON.parse(raw);
1079
+ if (!Array.isArray(parsed) || parsed.length === 0) {
1080
+ throw new Error("--ops-file must contain a non-empty JSON array of edit operations.");
1081
+ }
1082
+ for (const operation of parsed) {
1083
+ if (!operation || typeof operation !== "object" || Array.isArray(operation)) {
1084
+ throw new Error("Each edit operation must be a JSON object.");
1085
+ }
1086
+ const candidate = operation;
1087
+ if (!["replace", "insert", "delete"].includes(String(candidate.type))) {
1088
+ throw new Error("Each edit operation type must be replace, insert, or delete.");
1089
+ }
1090
+ if (!candidate.anchor || typeof candidate.anchor !== "object" || Array.isArray(candidate.anchor)) {
1091
+ throw new Error("Each edit operation must include an anchor object.");
1092
+ }
1093
+ if (candidate.type !== "delete" && typeof candidate.text !== "string") {
1094
+ throw new Error("Replace and insert operations must include a text string.");
1095
+ }
1096
+ }
1097
+ return parsed;
1098
+ }
931
1099
  function createArticleCommands() {
932
1100
  const article = new Command("article").description("Manage articles").action(() => article.help());
933
1101
  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) => {
@@ -974,12 +1142,15 @@ function createArticleCommands() {
974
1142
  output.info("Hint: use `mdedit article get <articleId> --content-only` to print markdown, or `--include-content` to include it in the output.");
975
1143
  });
976
1144
  article.command("create").description("Create a new article").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-i, --id <articleId>", "Article ID (defaults to a UUID)").option("-t, --title <title>", "Article title").option("-f, --folder <folderId>", "Folder ID").option("-c, --collaborative", "Enable collaborative editing").option("--file <path>", "Read initial article content from a file (use - for stdin)").option("--content <text>", "Set initial article content as an inline string").action(async (options) => {
977
- requireApiKey();
1145
+ const apiKey = requireApiKey();
978
1146
  const client = getApiClient();
979
1147
  const workspaceId = requireWorkspaceId(options.workspace);
980
1148
  if (options.content !== void 0 && options.file !== void 0) {
981
1149
  throw new Error("--content and --file are mutually exclusive. Provide only one.");
982
1150
  }
1151
+ let contentText = null;
1152
+ if (options.content !== void 0) contentText = options.content;
1153
+ else if (options.file) contentText = await readContentFromFile(options.file);
983
1154
  let title = options.title;
984
1155
  if (!title) {
985
1156
  const answers = await inquirer.prompt([
@@ -999,15 +1170,72 @@ function createArticleCommands() {
999
1170
  folderId: options.folder ?? null,
1000
1171
  collaborative: Boolean(options.collaborative)
1001
1172
  });
1002
- output.success("Article created successfully");
1003
- output.output(created);
1004
- let contentText = null;
1005
- if (options.content !== void 0) contentText = options.content;
1006
- else if (options.file) contentText = await readContentFromFile(options.file);
1007
1173
  if (contentText !== null) {
1008
- await client.article.saveContent(workspaceId, articleId, contentText);
1009
- output.success("Article content uploaded");
1174
+ try {
1175
+ if (options.collaborative) {
1176
+ const session = await openArticleSession({
1177
+ apiKey,
1178
+ websocketToken: apiKey,
1179
+ workspaceId,
1180
+ articleId,
1181
+ agent: { name: "mdedit-cli" },
1182
+ apiUrl: getApiUrlRaw()
1183
+ });
1184
+ try {
1185
+ const currentContent = session.read();
1186
+ await session.edit([{
1187
+ type: "replace",
1188
+ anchor: { range: { from: 0, to: currentContent.length } },
1189
+ text: contentText
1190
+ }]);
1191
+ } finally {
1192
+ await session.close();
1193
+ }
1194
+ const expectedContentHash = sha256Hex(contentText);
1195
+ let checkpointedContentHash;
1196
+ for (let attempt = 0; attempt < 20; attempt += 1) {
1197
+ try {
1198
+ const checkpoint = await client.collaboration.checkpoint(workspaceId, articleId);
1199
+ checkpointedContentHash = checkpoint.targetHashes["content.md"];
1200
+ if (checkpointedContentHash === expectedContentHash) break;
1201
+ } catch (error) {
1202
+ if (!(error instanceof FetchError2) || error.status !== 409 && error.status !== 503) {
1203
+ throw error;
1204
+ }
1205
+ }
1206
+ await new Promise((resolve2) => setTimeout(resolve2, 500));
1207
+ }
1208
+ if (checkpointedContentHash !== expectedContentHash) {
1209
+ throw new Error("Collaborative content did not reach a durable checkpoint within 10 seconds.");
1210
+ }
1211
+ } else {
1212
+ await client.article.saveContent(workspaceId, articleId, contentText, {
1213
+ baseContentRevision: 0,
1214
+ contentHash: sha256Hex(contentText),
1215
+ title: String(title),
1216
+ folderId: options.folder ?? null
1217
+ });
1218
+ }
1219
+ } catch (contentError) {
1220
+ let compensated = false;
1221
+ let compensationError;
1222
+ try {
1223
+ await client.article.delete(workspaceId, articleId);
1224
+ compensated = true;
1225
+ } catch (error) {
1226
+ compensationError = error;
1227
+ }
1228
+ throw new ArticleCreateContentError({
1229
+ articleId,
1230
+ compensated,
1231
+ contentError,
1232
+ compensationError
1233
+ });
1234
+ }
1010
1235
  }
1236
+ output.success("Article created successfully");
1237
+ if (contentText !== null) output.success("Article content uploaded");
1238
+ output.output(created);
1011
1239
  });
1012
1240
  article.command("update <articleId>").description("Update an article").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-t, --title <title>", "New title").option("--archive", "Archive the article").option("--pin", "Pin the article").option("--file <path>", "Update article content from a file (use - for stdin)").option("--content <text>", "Update article content as an inline string").action(async (articleId, options) => {
1013
1241
  requireApiKey();
@@ -1020,22 +1248,109 @@ function createArticleCommands() {
1020
1248
  if (options.title) body.title = options.title;
1021
1249
  if (options.archive) body.isArchived = true;
1022
1250
  if (options.pin) body.isPinned = true;
1023
- if (Object.keys(body).length > 0) {
1251
+ let contentText = null;
1252
+ if (options.content !== void 0) contentText = options.content;
1253
+ else if (options.file) contentText = await readContentFromFile(options.file);
1254
+ if (contentText === null && Object.keys(body).length > 0) {
1024
1255
  const result = await client.article.update(workspaceId, { articleId, ...body });
1025
1256
  output.success("Article updated successfully");
1026
1257
  output.output(result);
1027
1258
  }
1028
- let contentText = null;
1029
- if (options.content !== void 0) contentText = options.content;
1030
- else if (options.file) contentText = await readContentFromFile(options.file);
1031
1259
  if (contentText !== null) {
1032
- await client.article.saveContent(workspaceId, articleId, contentText);
1260
+ const remoteArticle = await client.article.get(workspaceId, articleId);
1261
+ const baseContentHash = remoteArticle?.contentHashAlg === "sha256" && remoteArticle?.contentHash ? remoteArticle.contentHash : sha256Hex(remoteArticle?.content || "");
1262
+ const result = await client.article.saveContent(workspaceId, articleId, contentText, {
1263
+ baseContentRevision: remoteArticle?.contentRevision ?? 0,
1264
+ baseContentHash,
1265
+ contentHash: sha256Hex(contentText),
1266
+ title: body.title,
1267
+ isArchived: body.isArchived,
1268
+ isPinned: body.isPinned
1269
+ });
1033
1270
  output.success("Article content updated");
1271
+ output.output(result);
1034
1272
  }
1035
1273
  if (Object.keys(body).length === 0 && contentText === null) {
1036
1274
  output.warning("No changes provided. Use --title, --archive, --pin, --file, or --content.");
1037
1275
  }
1038
1276
  });
1277
+ 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) => {
1278
+ const apiKey = requireApiKey();
1279
+ const workspaceId = requireWorkspaceId(options.workspace);
1280
+ const pollIntervalMs = Number(options.pollInterval);
1281
+ if (!Number.isFinite(pollIntervalMs) || pollIntervalMs < 100) {
1282
+ throw new Error("--poll-interval must be at least 100 milliseconds.");
1283
+ }
1284
+ const abort = new AbortController();
1285
+ const stop = () => abort.abort();
1286
+ process.once("SIGINT", stop);
1287
+ process.once("SIGTERM", stop);
1288
+ let session;
1289
+ let eventCount = 0;
1290
+ const testEventLimit = Number(process.env.MDEDIT_WATCH_TEST_EVENTS || 0);
1291
+ try {
1292
+ session = await openArticleSession({
1293
+ apiKey,
1294
+ websocketToken: apiKey,
1295
+ workspaceId,
1296
+ articleId,
1297
+ agent: { name: options.agent },
1298
+ apiUrl: getApiUrlRaw()
1299
+ });
1300
+ for await (const event of session.events({ signal: abort.signal, pollIntervalMs })) {
1301
+ console.log(JSON.stringify({ articleId, ...event }));
1302
+ eventCount += 1;
1303
+ if (testEventLimit > 0 && eventCount >= testEventLimit) abort.abort();
1304
+ }
1305
+ } finally {
1306
+ process.off("SIGINT", stop);
1307
+ process.off("SIGTERM", stop);
1308
+ await session?.close();
1309
+ }
1310
+ });
1311
+ 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) => {
1312
+ const apiKey = requireApiKey();
1313
+ const workspaceId = requireWorkspaceId(options.workspace);
1314
+ const hasInlineOption = options.replace !== void 0 || options.with !== void 0;
1315
+ if (options.opsFile && hasInlineOption) {
1316
+ throw new Error("--ops-file cannot be combined with --replace or --with.");
1317
+ }
1318
+ if (!options.opsFile && (options.replace === void 0 || options.with === void 0)) {
1319
+ throw new Error("Provide both --replace and --with, or provide --ops-file <path>.");
1320
+ }
1321
+ const operations = options.opsFile ? await readEditOperations(options.opsFile) : [{ type: "replace", anchor: { quote: options.replace }, text: options.with }];
1322
+ let session;
1323
+ let editError;
1324
+ let result;
1325
+ try {
1326
+ session = await openArticleSession({
1327
+ apiKey,
1328
+ websocketToken: apiKey,
1329
+ workspaceId,
1330
+ articleId,
1331
+ agent: { name: "mdedit-cli" },
1332
+ apiUrl: getApiUrlRaw()
1333
+ });
1334
+ result = await session.edit(operations);
1335
+ } catch (error) {
1336
+ editError = error;
1337
+ throw error;
1338
+ } finally {
1339
+ if (session) {
1340
+ try {
1341
+ await session.close();
1342
+ } catch (closeError) {
1343
+ if (editError === void 0) throw closeError;
1344
+ }
1345
+ }
1346
+ }
1347
+ if (!session || !result) throw new Error("Article edit did not return a result.");
1348
+ output.output({ articleId, mode: session.mode, ...result });
1349
+ if (result.conflicts.length > 0) {
1350
+ output.warning("The edit was applied with overlapping remote changes; re-read the article before continuing.");
1351
+ process.exitCode = CLI_EXIT_CODES.EDIT_CONFLICT;
1352
+ }
1353
+ });
1039
1354
  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
1355
  requireApiKey();
1041
1356
  const client = getApiClient();
@@ -1418,9 +1733,10 @@ function presentApiKeyListRow(key) {
1418
1733
  }
1419
1734
 
1420
1735
  // src/commands/apikey.ts
1736
+ var DEFAULT_API_KEY_SCOPES = ["articles:read", "articles:write"];
1421
1737
  function createApiKeyCommands() {
1422
1738
  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) => {
1739
+ 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
1740
  requireApiKey();
1425
1741
  const client = getApiClient();
1426
1742
  let name = options.name;
@@ -1444,10 +1760,16 @@ function createApiKeyCommands() {
1444
1760
  }
1445
1761
  expiresInDays = days;
1446
1762
  }
1763
+ const scopesRaw = options.scopes;
1764
+ const scopes = scopesRaw === void 0 ? DEFAULT_API_KEY_SCOPES : [...new Set(scopesRaw.split(",").map((scope) => scope.trim()).filter(Boolean))];
1765
+ if (scopesRaw !== void 0 && scopes?.length === 0) {
1766
+ throw new Error("--scopes must contain at least one scope.");
1767
+ }
1447
1768
  output.info("Creating API key...");
1448
1769
  const req = { name };
1449
1770
  if (options.description) req.description = options.description;
1450
1771
  if (expiresInDays !== void 0) req.expiresInDays = expiresInDays;
1772
+ req.scopes = scopes;
1451
1773
  const result = await client.apiKeys.create(req);
1452
1774
  output.success("API key created successfully!");
1453
1775
  output.warning("IMPORTANT: Save this API key now. It will not be shown again.");
@@ -1539,7 +1861,7 @@ var TARGETS = {
1539
1861
  sectionHeading: "## mdedit CLI"
1540
1862
  }
1541
1863
  };
1542
- function installToTarget(targetKey, spec, skillContent, global) {
1864
+ function installToTarget(spec, skillContent, global) {
1543
1865
  const targetPath = spec.path(process.cwd(), global);
1544
1866
  const dir = dirname(resolve(targetPath));
1545
1867
  if (!existsSync2(dir)) {
@@ -1591,7 +1913,7 @@ function createSkillCommands() {
1591
1913
  }
1592
1914
  const keys = target === "all" ? [...NAMED_TARGETS] : [target];
1593
1915
  for (const key of keys) {
1594
- installToTarget(key, TARGETS[key], skillContent, global);
1916
+ installToTarget(TARGETS[key], skillContent, global);
1595
1917
  }
1596
1918
  output.info("");
1597
1919
  output.info("To view the installed skill at any time: mdedit skill show");
@@ -1599,6 +1921,106 @@ function createSkillCommands() {
1599
1921
  return skill;
1600
1922
  }
1601
1923
 
1924
+ // src/commands/review.ts
1925
+ import { Command as Command7 } from "commander";
1926
+ import {
1927
+ openArticleReviewSession
1928
+ } from "@mdedit/agent-client";
1929
+ async function withReview(articleId, workspaceId, operation) {
1930
+ const apiKey = requireApiKey();
1931
+ const review = openArticleReviewSession({ apiKey, workspaceId, articleId, apiUrl: getApiUrlRaw() });
1932
+ return { mode: "rest", result: await operation(review) };
1933
+ }
1934
+ function quoteAnchor(options) {
1935
+ const occurrence = options.occurrence === void 0 ? void 0 : Number(options.occurrence);
1936
+ if (occurrence !== void 0 && (!Number.isInteger(occurrence) || occurrence < 1)) {
1937
+ throw new Error("--occurrence must be a one-based positive integer.");
1938
+ }
1939
+ return {
1940
+ quote: options.quote,
1941
+ ...occurrence ? { occurrence } : {},
1942
+ ...options.before || options.after ? { context: { before: options.before, after: options.after } } : {}
1943
+ };
1944
+ }
1945
+ function addCommon(command) {
1946
+ return command.option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-t, --target <targetId>", "Markdown review target", "content.md");
1947
+ }
1948
+ function addQuote(command) {
1949
+ 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");
1950
+ }
1951
+ function presentReviewItem(item) {
1952
+ return {
1953
+ id: item.value.id,
1954
+ type: item.itemType,
1955
+ targetId: item.targetId,
1956
+ status: item.value.status,
1957
+ 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,
1958
+ body: "body" in item.value ? item.value.body : item.value.note,
1959
+ ...item.itemType === "suggestion" ? { originalText: item.value.originalText, suggestedText: item.value.suggestedText } : {}
1960
+ };
1961
+ }
1962
+ function createReviewCommands() {
1963
+ const review = new Command7("review").description("Review an article through server-authoritative agent commands").action(() => review.help());
1964
+ addCommon(review.command("list <articleId>").description("List article review items").option("-s, --status <status>", "Filter by review status")).action(async (articleId, options) => {
1965
+ const workspaceId = requireWorkspaceId(options.workspace);
1966
+ const { result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession.list({
1967
+ status: options.status,
1968
+ targetId: options.target
1969
+ }));
1970
+ output.output(output.isJson() ? result : result.map(presentReviewItem));
1971
+ });
1972
+ addQuote(review.command("add <articleId>").description("Add a comment anchored to quoted text").requiredOption("-b, --body <text>", "Comment body")).action(async (articleId, options) => {
1973
+ const workspaceId = requireWorkspaceId(options.workspace);
1974
+ const { mode, result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession.addComment({
1975
+ anchor: quoteAnchor(options),
1976
+ body: options.body,
1977
+ targetId: options.target
1978
+ }));
1979
+ output.output({ articleId, mode, ...result });
1980
+ });
1981
+ 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) => {
1982
+ const workspaceId = requireWorkspaceId(options.workspace);
1983
+ const { mode, result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession.reply({
1984
+ threadId: options.thread,
1985
+ body: options.body,
1986
+ targetId: options.target
1987
+ }));
1988
+ output.output({ articleId, mode, ...result });
1989
+ });
1990
+ for (const verb of ["resolve", "reopen", "accept", "reject"]) {
1991
+ 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) => {
1992
+ const workspaceId = requireWorkspaceId(options.workspace);
1993
+ const { mode, result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession[verb]({
1994
+ threadId: options.thread,
1995
+ targetId: options.target
1996
+ }));
1997
+ output.output({ articleId, mode, ...result });
1998
+ });
1999
+ }
2000
+ 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) => {
2001
+ const workspaceId = requireWorkspaceId(options.workspace);
2002
+ const { mode, result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession.delete({
2003
+ threadId: options.thread,
2004
+ replyId: options.reply,
2005
+ targetId: options.target
2006
+ }));
2007
+ output.output({ articleId, mode, ...result });
2008
+ });
2009
+ return review;
2010
+ }
2011
+ function createSuggestCommand() {
2012
+ 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) => {
2013
+ const workspaceId = requireWorkspaceId(options.workspace);
2014
+ const { mode, result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession.suggest({
2015
+ anchor: quoteAnchor(options),
2016
+ replace: options.replace,
2017
+ note: options.note,
2018
+ targetId: options.target
2019
+ }));
2020
+ output.output({ articleId, mode, ...result });
2021
+ });
2022
+ }
2023
+
1602
2024
  // src/index.ts
1603
2025
  var __filename2 = fileURLToPath2(import.meta.url);
1604
2026
  var __dirname2 = dirname2(__filename2);
@@ -1608,7 +2030,7 @@ try {
1608
2030
  version = packageJson.version || version;
1609
2031
  } catch {
1610
2032
  }
1611
- var program = new Command7();
2033
+ var program = new Command8();
1612
2034
  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
2035
  const opts = typeof thisCommand.optsWithGlobals === "function" ? (
1614
2036
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -1627,6 +2049,8 @@ program.addCommand(createFolderCommands());
1627
2049
  program.addCommand(createConfigCommands());
1628
2050
  program.addCommand(createApiKeyCommands());
1629
2051
  program.addCommand(createSkillCommands());
2052
+ program.addCommand(createReviewCommands());
2053
+ program.addCommand(createSuggestCommand());
1630
2054
  program.command("health").description("Check API health status").action(async () => {
1631
2055
  const base = getApiBaseUrlRoot();
1632
2056
  const response = await fetch(`${base}/health`, { method: "GET" });
@@ -1703,7 +2127,37 @@ async function main() {
1703
2127
  await program.parseAsync(process.argv);
1704
2128
  } catch (err) {
1705
2129
  const debug = process.env.MDEDIT_DEBUG === "1";
1706
- if (err instanceof FetchError2) {
2130
+ const typedError = typedCliError(err);
2131
+ if (typedError) {
2132
+ if (output.isJson()) {
2133
+ const { exitCode: _exitCode, ...error } = typedError;
2134
+ output.output({ error });
2135
+ } else {
2136
+ output.error(typedError.message);
2137
+ if (typedError.code === "AMBIGUOUS_ANCHOR") {
2138
+ output.info("Hint: use an ops file with occurrence or context to select one match.");
2139
+ }
2140
+ }
2141
+ if (debug && err instanceof Error && err.stack) output.warning(err.stack);
2142
+ process.exitCode = typedError.exitCode;
2143
+ return;
2144
+ }
2145
+ if (err instanceof AgentClientHttpError) {
2146
+ const data = err.data;
2147
+ const code = data?.code ?? data?.error?.code;
2148
+ const details = data?.details ?? data?.error?.details;
2149
+ if (output.isJson()) {
2150
+ output.output({ error: { code: code || "API_REQUEST_FAILED", message: err.message, status: err.status, details } });
2151
+ } else {
2152
+ output.error(`API request failed (${err.status}): ${err.message}`);
2153
+ if (details?.requiredScope === "articles:write") {
2154
+ output.info("Hint: accepting a suggestion changes article text and requires an API key with articles:write.");
2155
+ } else if (err.status === 403) {
2156
+ output.info("Hint: review keys need articles:read,reviews:write; accepting suggestions additionally needs articles:write.");
2157
+ }
2158
+ }
2159
+ if (debug && err.stack) output.warning(err.stack);
2160
+ } else if (err instanceof FetchError2) {
1707
2161
  output.error(`API request failed (${err.status}): ${err.message}`);
1708
2162
  if (err.status === 401) {
1709
2163
  output.info("Hint: set an API key via `mdedit config set apiKey <key>` or pass `--api-key <key>`.");
@@ -1719,7 +2173,7 @@ async function main() {
1719
2173
  } else {
1720
2174
  output.error(err);
1721
2175
  }
1722
- process.exitCode = 1;
2176
+ process.exitCode = CLI_EXIT_CODES.ERROR;
1723
2177
  }
1724
2178
  }
1725
2179
  await main();