mdedit-cli 0.1.3 → 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/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import { Command as Command7 } from "commander";
5
- import { readFileSync as readFileSync2 } from "fs";
6
- import { dirname, join as join2 } from "path";
7
- import { fileURLToPath } from "url";
4
+ import { Command as Command8 } from "commander";
5
+ import { readFileSync as readFileSync3 } from "fs";
6
+ import { dirname as dirname2, join as join3 } from "path";
7
+ import { fileURLToPath as fileURLToPath2 } from "url";
8
8
 
9
9
  // ../sdk/dist/index.js
10
10
  var _defaultFetchers = null;
@@ -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;
@@ -404,62 +452,7 @@ var deleteFolder = async (workspaceId, folderId, fetchers) => {
404
452
  }
405
453
  return true;
406
454
  };
407
- var listTemplates = async (workspaceId, fetchers) => {
408
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
409
- const response = await fetchV2(`/workspaces/${workspaceId}/templates`, {
410
- method: "GET"
411
- });
412
- if (!response.ok) {
413
- throw new Error(`Failed to fetch templates: ${response.statusText}`);
414
- }
415
- return response.json();
416
- };
417
- var getTemplateById = async (templateId, fetchers) => {
418
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
419
- const response = await fetchV2(`/templates/${templateId}`, { method: "GET" });
420
- if (!response.ok) {
421
- throw new Error(`Failed to fetch template: ${response.statusText}`);
422
- }
423
- return response.json();
424
- };
425
- var getTemplateBySlug = async (slug, fetchers) => {
426
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
427
- const response = await fetchV2(`/templates/slug/${encodeURIComponent(slug)}`, { method: "GET" });
428
- if (!response.ok) {
429
- throw new Error(`Failed to fetch template by slug: ${response.statusText}`);
430
- }
431
- return response.json();
432
- };
433
- var saveArticleAsTemplate = async (workspaceId, articleId, templateData, fetchers) => {
434
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
435
- const response = await fetchV2(
436
- `/workspaces/${workspaceId}/articles/${articleId}/save-as-template`,
437
- { method: "POST", body: JSON.stringify(templateData) }
438
- );
439
- if (!response.ok) {
440
- throw new Error(`Failed to save template: ${response.statusText}`);
441
- }
442
- return response.json();
443
- };
444
- var updateTemplate = async (templateId, updates, fetchers) => {
445
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
446
- const response = await fetchV2(`/templates/${templateId}`, {
447
- method: "PUT",
448
- body: JSON.stringify(updates)
449
- });
450
- if (!response.ok) {
451
- throw new Error(`Failed to update template: ${response.statusText}`);
452
- }
453
- return response.json();
454
- };
455
- var deleteTemplate = async (templateId, fetchers) => {
456
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
457
- const response = await fetchV2(`/templates/${templateId}`, { method: "DELETE" });
458
- if (!response.ok) {
459
- throw new Error(`Failed to delete template: ${response.statusText}`);
460
- }
461
- };
462
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
455
+ var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
463
456
  var isRetriableStatus = (status) => status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
464
457
  var withRetries = async (fn, maxAttempts = 3) => {
465
458
  let lastError;
@@ -578,25 +571,24 @@ function createSdkClient(config) {
578
571
  delete: async (workspaceId, articleId) => {
579
572
  await withFetchError(() => deleteArticle(workspaceId, articleId, fetchers));
580
573
  },
581
- saveContent: (workspaceId, articleId, content) => withFetchError(() => saveArticleContent(workspaceId, articleId, content, fetchers)),
574
+ saveContent: (workspaceId, articleId, content, options) => withFetchError(() => saveArticleContent(workspaceId, articleId, content, options, fetchers)),
582
575
  exportZip: (workspaceId, articleId) => withFetchError(() => exportArticleZip(workspaceId, articleId, fetchers))
583
- },
584
- template: {
585
- list: (workspaceId) => withFetchError(() => listTemplates(workspaceId, fetchers)),
586
- get: (templateId) => withFetchError(() => getTemplateById(templateId, fetchers)),
587
- getBySlug: (slug) => withFetchError(() => getTemplateBySlug(slug, fetchers)),
588
- createFromArticle: (workspaceId, articleId, req) => withFetchError(() => saveArticleAsTemplate(workspaceId, articleId, req, fetchers)),
589
- update: (templateId, updates) => withFetchError(() => updateTemplate(templateId, updates, fetchers)),
590
- delete: (templateId) => withFetchError(() => deleteTemplate(templateId, fetchers))
591
576
  }
592
577
  };
593
578
  }
594
579
 
580
+ // src/index.ts
581
+ import { AgentClientHttpError } from "@mdedit/agent-client";
582
+
595
583
  // src/commands/article.ts
596
584
  import { Command } from "commander";
597
585
  import inquirer from "inquirer";
598
586
  import { v4 as uuidv4 } from "uuid";
599
587
  import { readFile, writeFile } from "fs/promises";
588
+ import { createHash } from "crypto";
589
+ import {
590
+ openArticleSession
591
+ } from "@mdedit/agent-client";
600
592
 
601
593
  // src/utils/output.ts
602
594
  import chalk from "chalk";
@@ -668,13 +660,30 @@ var ConfigManager = class {
668
660
  var configManager = new ConfigManager();
669
661
 
670
662
  // src/utils/output.ts
663
+ var MAX_TABLE_CELL_WIDTH = 80;
664
+ function normalizeFormat(value) {
665
+ const raw = String(value || "").trim().toLowerCase();
666
+ if (raw === "json" || raw === "table" || raw === "plain") return raw;
667
+ return "table";
668
+ }
669
+ function truncateCell(value, max = MAX_TABLE_CELL_WIDTH) {
670
+ const text = value.replace(/\s+/g, " ").trim();
671
+ if (text.length <= max) return text;
672
+ return text.slice(0, Math.max(0, max - 1)).trimEnd() + "\u2026";
673
+ }
671
674
  var OutputFormatter = class {
672
675
  format;
673
676
  constructor() {
674
- this.format = configManager.get("outputFormat") || "plain";
677
+ this.format = normalizeFormat(configManager.get("outputFormat") || "table");
675
678
  }
676
679
  setFormat(format) {
677
- this.format = format;
680
+ this.format = normalizeFormat(format);
681
+ }
682
+ getFormat() {
683
+ return this.format;
684
+ }
685
+ isJson() {
686
+ return this.format === "json";
678
687
  }
679
688
  log(message) {
680
689
  if (this.format === "json") {
@@ -703,9 +712,15 @@ var OutputFormatter = class {
703
712
  console.log(JSON.stringify(data, null, 2));
704
713
  return;
705
714
  }
706
- if (this.format === "table" && Array.isArray(data)) {
707
- console.table(data);
708
- return;
715
+ if (this.format === "table") {
716
+ if (Array.isArray(data)) {
717
+ this.printTable(data);
718
+ return;
719
+ }
720
+ if (typeof data === "object" && data !== null) {
721
+ this.printObject(data);
722
+ return;
723
+ }
709
724
  }
710
725
  if (this.format === "plain") {
711
726
  if (typeof data === "object" && data !== null) {
@@ -722,6 +737,58 @@ var OutputFormatter = class {
722
737
  ${chalk.bold.underline(text)}
723
738
  `);
724
739
  }
740
+ printTable(rowsRaw) {
741
+ if (rowsRaw.length === 0) {
742
+ console.log("(no results)");
743
+ return;
744
+ }
745
+ const rows = rowsRaw.map((row) => {
746
+ if (row && typeof row === "object" && !Array.isArray(row)) return row;
747
+ return { value: row };
748
+ });
749
+ const columns = [];
750
+ const seen = /* @__PURE__ */ new Set();
751
+ const addColumn = (col) => {
752
+ if (seen.has(col)) return;
753
+ seen.add(col);
754
+ columns.push(col);
755
+ };
756
+ addColumn("(index)");
757
+ for (const key of Object.keys(rows[0] || {})) addColumn(key);
758
+ for (const row of rows) {
759
+ for (const key of Object.keys(row)) addColumn(key);
760
+ }
761
+ const cell = (value) => {
762
+ if (value === null || value === void 0) return "";
763
+ if (typeof value === "string") return truncateCell(value);
764
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
765
+ try {
766
+ return truncateCell(JSON.stringify(value));
767
+ } catch {
768
+ return truncateCell(String(value));
769
+ }
770
+ };
771
+ const grid = rows.map((row, idx) => {
772
+ const record = { ...row };
773
+ return columns.map((col) => {
774
+ if (col === "(index)") return String(idx);
775
+ return cell(record[col]);
776
+ });
777
+ });
778
+ const widths = columns.map((col, i) => {
779
+ const headerWidth = col.length;
780
+ const cellsWidth = Math.max(...grid.map((r) => (r[i] ?? "").length), 0);
781
+ return Math.min(MAX_TABLE_CELL_WIDTH, Math.max(headerWidth, cellsWidth));
782
+ });
783
+ const pad = (text, width) => text.length >= width ? text.slice(0, width) : text + " ".repeat(width - text.length);
784
+ const line = (left, mid, right) => left + widths.map((w) => "\u2500".repeat(w + 2)).join(mid) + right;
785
+ const rowLine = (values) => "\u2502" + values.map((v, i) => ` ${pad(v, widths[i])} `).join("\u2502") + "\u2502";
786
+ console.log(line("\u250C", "\u252C", "\u2510"));
787
+ console.log(rowLine(columns.map((c, i) => pad(c, widths[i]))));
788
+ console.log(line("\u251C", "\u253C", "\u2524"));
789
+ for (const r of grid) console.log(rowLine(r.map((v, i) => pad(v, widths[i]))));
790
+ console.log(line("\u2514", "\u2534", "\u2518"));
791
+ }
725
792
  printObject(obj, indent = 0) {
726
793
  if (Array.isArray(obj)) {
727
794
  obj.forEach((item, index) => {
@@ -818,13 +885,136 @@ function getApiClient() {
818
885
  return client;
819
886
  }
820
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
+
929
+ // src/presenters/common.ts
930
+ function isIsoDateString(value) {
931
+ return /^\d{4}-\d{2}-\d{2}T/.test(value);
932
+ }
933
+ function truncate(value, max = 60) {
934
+ const text = String(value ?? "").trim();
935
+ if (!text) return "";
936
+ if (text.length <= max) return text;
937
+ return text.slice(0, Math.max(0, max - 1)).trimEnd() + "\u2026";
938
+ }
939
+ function formatCount(value) {
940
+ const num = typeof value === "number" ? value : Number(value);
941
+ if (!Number.isFinite(num)) return "";
942
+ return new Intl.NumberFormat(void 0, { maximumFractionDigits: 0 }).format(num);
943
+ }
944
+ function toDate(value) {
945
+ if (value === null || value === void 0) return null;
946
+ if (typeof value === "number" && Number.isFinite(value)) {
947
+ const ms = value > 1e12 ? value : value * 1e3;
948
+ const d = new Date(ms);
949
+ return Number.isNaN(d.getTime()) ? null : d;
950
+ }
951
+ if (typeof value === "string") {
952
+ const trimmed = value.trim();
953
+ if (!trimmed) return null;
954
+ if (/^\d+$/.test(trimmed)) {
955
+ const n = Number(trimmed);
956
+ if (!Number.isFinite(n)) return null;
957
+ const ms = n > 1e12 ? n : n * 1e3;
958
+ const d = new Date(ms);
959
+ return Number.isNaN(d.getTime()) ? null : d;
960
+ }
961
+ if (isIsoDateString(trimmed)) {
962
+ const d = new Date(trimmed);
963
+ return Number.isNaN(d.getTime()) ? null : d;
964
+ }
965
+ }
966
+ return null;
967
+ }
968
+ function formatDateShort(value) {
969
+ const d = toDate(value);
970
+ if (!d) return "";
971
+ return d.toISOString().slice(0, 10);
972
+ }
973
+ function formatDateTime(value) {
974
+ const d = toDate(value);
975
+ if (!d) return "";
976
+ return d.toISOString().replace(".000Z", "Z");
977
+ }
978
+
979
+ // src/presenters/article.ts
980
+ function flagsForArticle(article) {
981
+ const pinned = Boolean(article?.isPinned) ? "P" : "";
982
+ const archived = Boolean(article?.isArchived) ? "A" : "";
983
+ return `${pinned}${archived}`;
984
+ }
985
+ function presentArticleListRow(article) {
986
+ const title = article?.title || article?.preview || "";
987
+ const lastEditedAt = article?.lastEditedAt ?? article?.updatedAt ?? article?.createdAt;
988
+ return {
989
+ articleId: article?.articleId ?? "",
990
+ title: truncate(title, 64),
991
+ wordCount: formatCount(article?.wordCount),
992
+ lastEditedAt: formatDateShort(lastEditedAt),
993
+ flags: flagsForArticle(article)
994
+ };
995
+ }
996
+ function presentArticleDetails(article) {
997
+ const lastEditedAt = article?.lastEditedAt ?? article?.updatedAt ?? article?.createdAt;
998
+ return {
999
+ articleId: article?.articleId ?? "",
1000
+ title: article?.title ?? "",
1001
+ wordCount: formatCount(article?.wordCount) || void 0,
1002
+ folderId: article?.folderId ?? null,
1003
+ isArchived: Boolean(article?.isArchived),
1004
+ isPinned: Boolean(article?.isPinned),
1005
+ lastEditedAt: formatDateTime(lastEditedAt) || void 0,
1006
+ createdAt: formatDateTime(article?.createdAt) || void 0,
1007
+ updatedAt: formatDateTime(article?.updatedAt) || void 0
1008
+ };
1009
+ }
1010
+
821
1011
  // src/commands/article.ts
822
1012
  async function readContentFromFile(filePath) {
823
1013
  if (filePath === "-") {
824
- return new Promise((resolve, reject) => {
1014
+ return new Promise((resolve2, reject) => {
825
1015
  const chunks = [];
826
1016
  process.stdin.on("data", (d) => chunks.push(Buffer.isBuffer(d) ? d : Buffer.from(d)));
827
- process.stdin.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
1017
+ process.stdin.on("end", () => resolve2(Buffer.concat(chunks).toString("utf-8")));
828
1018
  process.stdin.on("error", reject);
829
1019
  });
830
1020
  }
@@ -834,9 +1024,35 @@ async function writeBlobToFile(blob, filePath) {
834
1024
  const buffer = Buffer.from(await blob.arrayBuffer());
835
1025
  await writeFile(filePath, buffer);
836
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
+ }
837
1053
  function createArticleCommands() {
838
1054
  const article = new Command("article").description("Manage articles").action(() => article.help());
839
- 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").action(async (options) => {
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) => {
840
1056
  requireApiKey();
841
1057
  const client = getApiClient();
842
1058
  const workspaceId = requireWorkspaceId(options.workspace);
@@ -844,9 +1060,14 @@ function createArticleCommands() {
844
1060
  output.header("Articles");
845
1061
  const offset = Number(options.offset) || 0;
846
1062
  const limit = Number(options.limit) || articles.length;
847
- output.output(articles.slice(offset, offset + limit));
1063
+ const slice = articles.slice(offset, offset + limit);
1064
+ if (output.isJson() || options.full) {
1065
+ output.output(slice);
1066
+ return;
1067
+ }
1068
+ output.output(slice.map(presentArticleListRow));
848
1069
  });
849
- article.command("get <articleId>").description("Get article details").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-o, --output <file>", "Save article content (markdown) to this file path; use - for stdout").option("--content-only", "Print only the article markdown content to stdout (useful for piping / AI agents)").action(async (articleId, options) => {
1070
+ article.command("get <articleId>").description("Get article details").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-o, --output <file>", "Save article content (markdown) to this file path; use - for stdout").option("--content-only", "Print only the article markdown content to stdout (useful for piping / AI agents)").option("--include-content", "Include the article markdown content in the output object").option("--full", "Show full article object (all fields, including nested metadata)").action(async (articleId, options) => {
850
1071
  requireApiKey();
851
1072
  const client = getApiClient();
852
1073
  const workspaceId = requireWorkspaceId(options.workspace);
@@ -866,7 +1087,13 @@ function createArticleCommands() {
866
1087
  return;
867
1088
  }
868
1089
  output.header(`Article: ${articleId}`);
869
- output.output(result);
1090
+ const wantsFull = Boolean(options.full) || Boolean(options.includeContent);
1091
+ if (output.isJson() || wantsFull) {
1092
+ output.output(result);
1093
+ return;
1094
+ }
1095
+ output.output(presentArticleDetails(result));
1096
+ output.info("Hint: use `mdedit article get <articleId> --content-only` to print markdown, or `--include-content` to include it in the output.");
870
1097
  });
871
1098
  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) => {
872
1099
  requireApiKey();
@@ -900,7 +1127,12 @@ function createArticleCommands() {
900
1127
  if (options.content !== void 0) contentText = options.content;
901
1128
  else if (options.file) contentText = await readContentFromFile(options.file);
902
1129
  if (contentText !== null) {
903
- 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
+ });
904
1136
  output.success("Article content uploaded");
905
1137
  }
906
1138
  });
@@ -915,22 +1147,109 @@ function createArticleCommands() {
915
1147
  if (options.title) body.title = options.title;
916
1148
  if (options.archive) body.isArchived = true;
917
1149
  if (options.pin) body.isPinned = true;
918
- 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) {
919
1154
  const result = await client.article.update(workspaceId, { articleId, ...body });
920
1155
  output.success("Article updated successfully");
921
1156
  output.output(result);
922
1157
  }
923
- let contentText = null;
924
- if (options.content !== void 0) contentText = options.content;
925
- else if (options.file) contentText = await readContentFromFile(options.file);
926
1158
  if (contentText !== null) {
927
- 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
+ });
928
1169
  output.success("Article content updated");
1170
+ output.output(result);
929
1171
  }
930
1172
  if (Object.keys(body).length === 0 && contentText === null) {
931
1173
  output.warning("No changes provided. Use --title, --archive, --pin, --file, or --content.");
932
1174
  }
933
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
+ });
934
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) => {
935
1254
  requireApiKey();
936
1255
  const client = getApiClient();
@@ -967,21 +1286,52 @@ function createArticleCommands() {
967
1286
  // src/commands/workspace.ts
968
1287
  import { Command as Command2 } from "commander";
969
1288
  import inquirer2 from "inquirer";
1289
+
1290
+ // src/presenters/workspace.ts
1291
+ function presentWorkspaceListRow(workspace) {
1292
+ return {
1293
+ workspaceId: workspace?.workspaceId ?? "",
1294
+ name: truncate(workspace?.name ?? "", 48),
1295
+ type: workspace?.type ?? "",
1296
+ ownerUsername: workspace?.ownerUsername ?? "",
1297
+ updatedAt: formatDateShort(workspace?.updatedAt)
1298
+ };
1299
+ }
1300
+ function presentWorkspaceDetails(workspace) {
1301
+ return {
1302
+ workspaceId: workspace?.workspaceId ?? "",
1303
+ name: workspace?.name ?? "",
1304
+ type: workspace?.type ?? "",
1305
+ ownerUsername: workspace?.ownerUsername ?? "",
1306
+ createdAt: formatDateTime(workspace?.createdAt) || void 0,
1307
+ updatedAt: formatDateTime(workspace?.updatedAt) || void 0
1308
+ };
1309
+ }
1310
+
1311
+ // src/commands/workspace.ts
970
1312
  function createWorkspaceCommands() {
971
1313
  const workspace = new Command2("workspace").description("Manage workspaces").action(() => workspace.help());
972
- workspace.command("list").description("List all workspaces").action(async () => {
1314
+ workspace.command("list").description("List all workspaces").option("--full", "Show full workspace objects (all fields)").action(async (options) => {
973
1315
  requireApiKey();
974
1316
  const client = getApiClient();
975
1317
  const workspaces = await client.workspace.list();
976
1318
  output.header("Workspaces");
977
- output.output(workspaces);
1319
+ if (output.isJson() || options.full) {
1320
+ output.output(workspaces);
1321
+ return;
1322
+ }
1323
+ output.output(workspaces.map(presentWorkspaceListRow));
978
1324
  });
979
- workspace.command("get <workspaceId>").description("Get workspace details").action(async (workspaceId) => {
1325
+ workspace.command("get <workspaceId>").description("Get workspace details").option("--full", "Show full workspace object (all fields)").action(async (workspaceId, options) => {
980
1326
  requireApiKey();
981
1327
  const client = getApiClient();
982
1328
  const result = await client.workspace.get(workspaceId);
983
1329
  output.header(`Workspace: ${workspaceId}`);
984
- output.output(result);
1330
+ if (output.isJson() || options.full) {
1331
+ output.output(result);
1332
+ return;
1333
+ }
1334
+ output.output(presentWorkspaceDetails(result));
985
1335
  });
986
1336
  workspace.command("create").description("Create a new workspace").option("-n, --name <name>", "Workspace name").option("-t, --type <type>", "Workspace type: user|team", "user").action(async (options) => {
987
1337
  requireApiKey();
@@ -1044,23 +1394,56 @@ function createWorkspaceCommands() {
1044
1394
  import { Command as Command3 } from "commander";
1045
1395
  import inquirer3 from "inquirer";
1046
1396
  import { v4 as uuidv42 } from "uuid";
1397
+
1398
+ // src/presenters/folder.ts
1399
+ function presentFolderListRow(folder) {
1400
+ return {
1401
+ id: folder?.id ?? "",
1402
+ name: truncate(folder?.name ?? "", 48),
1403
+ parentId: folder?.parentId ?? null,
1404
+ updatedAt: formatDateShort(folder?.updatedAt),
1405
+ deletedAt: formatDateShort(folder?.deletedAt)
1406
+ };
1407
+ }
1408
+ function presentFolderDetails(folder) {
1409
+ return {
1410
+ id: folder?.id ?? "",
1411
+ name: folder?.name ?? "",
1412
+ parentId: folder?.parentId ?? null,
1413
+ workspaceId: folder?.workspaceId ?? "",
1414
+ createdAt: formatDateTime(folder?.createdAt) || void 0,
1415
+ updatedAt: formatDateTime(folder?.updatedAt) || void 0,
1416
+ deletedAt: formatDateTime(folder?.deletedAt) || void 0,
1417
+ deletedBy: folder?.deletedBy
1418
+ };
1419
+ }
1420
+
1421
+ // src/commands/folder.ts
1047
1422
  function createFolderCommands() {
1048
1423
  const folder = new Command3("folder").description("Manage folders").action(() => folder.help());
1049
- folder.command("list").description("List all folders").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("--include-deleted", "Include deleted/tombstoned folders").action(async (options) => {
1424
+ folder.command("list").description("List all folders").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("--include-deleted", "Include deleted/tombstoned folders").option("--full", "Show full folder objects (all fields)").action(async (options) => {
1050
1425
  requireApiKey();
1051
1426
  const client = getApiClient();
1052
1427
  const workspaceId = requireWorkspaceId(options.workspace);
1053
1428
  const folders = await client.folder.list(workspaceId, { includeDeleted: Boolean(options.includeDeleted) });
1054
1429
  output.header("Folders");
1055
- output.output(folders);
1430
+ if (output.isJson() || options.full) {
1431
+ output.output(folders);
1432
+ return;
1433
+ }
1434
+ output.output(folders.map(presentFolderListRow));
1056
1435
  });
1057
- folder.command("get <folderId>").description("Get folder details").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").action(async (folderId, options) => {
1436
+ folder.command("get <folderId>").description("Get folder details").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("--full", "Show full folder object (all fields)").action(async (folderId, options) => {
1058
1437
  requireApiKey();
1059
1438
  const client = getApiClient();
1060
1439
  const workspaceId = requireWorkspaceId(options.workspace);
1061
1440
  const result = await client.folder.get(workspaceId, folderId);
1062
1441
  output.header(`Folder: ${folderId}`);
1063
- output.output(result);
1442
+ if (output.isJson() || options.full) {
1443
+ output.output(result);
1444
+ return;
1445
+ }
1446
+ output.output(presentFolderDetails(result));
1064
1447
  });
1065
1448
  folder.command("create").description("Create a new folder").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-i, --id <folderId>", "Folder ID (optional)").option("-n, --name <name>", "Folder name").option("-p, --parent <parentId>", "Parent folder ID").action(async (options) => {
1066
1449
  requireApiKey();
@@ -1122,110 +1505,9 @@ function createFolderCommands() {
1122
1505
  return folder;
1123
1506
  }
1124
1507
 
1125
- // src/commands/template.ts
1508
+ // src/commands/config.ts
1126
1509
  import { Command as Command4 } from "commander";
1127
1510
  import inquirer4 from "inquirer";
1128
- function slugify(input) {
1129
- return input.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
1130
- }
1131
- function createTemplateCommands() {
1132
- const template = new Command4("template").description("Manage templates").action(() => template.help());
1133
- template.command("list").description("List all templates").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").action(async (options) => {
1134
- requireApiKey();
1135
- const client = getApiClient();
1136
- const workspaceId = requireWorkspaceId(options.workspace);
1137
- const templates = await client.template.list(workspaceId);
1138
- output.header("Templates");
1139
- output.output(templates);
1140
- });
1141
- template.command("get <templateId>").description("Get template details").action(async (templateId) => {
1142
- requireApiKey();
1143
- const client = getApiClient();
1144
- const result = await client.template.get(templateId);
1145
- output.header(`Template: ${templateId}`);
1146
- output.output(result);
1147
- });
1148
- template.command("get-by-slug <slug>").description("Get template details by slug").action(async (slug) => {
1149
- requireApiKey();
1150
- const client = getApiClient();
1151
- const result = await client.template.getBySlug(slug);
1152
- output.header(`Template: ${slug}`);
1153
- output.output(result);
1154
- });
1155
- template.command("create <articleId>").description("Create a template from an article").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-n, --name <name>", "Template name").option("--slug <slug>", "Template slug (defaults to slugified name)").option("-d, --description <desc>", "Template description").option("-c, --category <category>", "Category: writing|documentation|planning|general|custom", "custom").option("-t, --tags <tags>", "Comma-separated tags", "").option("-v, --visibility <visibility>", "Visibility: private|workspace", "workspace").action(async (articleId, options) => {
1156
- requireApiKey();
1157
- const client = getApiClient();
1158
- const workspaceId = requireWorkspaceId(options.workspace);
1159
- let name = options.name;
1160
- if (!name) {
1161
- const answers = await inquirer4.prompt([
1162
- {
1163
- type: "input",
1164
- name: "name",
1165
- message: "Template name:",
1166
- validate: (input) => input.length > 0 || "Name is required"
1167
- }
1168
- ]);
1169
- name = String(answers.name);
1170
- }
1171
- const desc = options.description || "";
1172
- const slug = options.slug || slugify(String(name));
1173
- const tags = String(options.tags || "").split(",").map((t) => t.trim()).filter(Boolean);
1174
- const result = await client.template.createFromArticle(workspaceId, articleId, {
1175
- name: String(name),
1176
- slug,
1177
- category: options.category,
1178
- description: desc,
1179
- tags,
1180
- visibility: options.visibility
1181
- });
1182
- output.success("Template created successfully");
1183
- output.output(result);
1184
- });
1185
- template.command("update <templateId>").description("Update a template").option("-n, --name <name>", "Template name").option("-d, --description <desc>", "Template description").option("-c, --category <category>", "Category: writing|documentation|planning|general|custom").option("-t, --tags <tags>", "Comma-separated tags").action(async (templateId, options) => {
1186
- requireApiKey();
1187
- const client = getApiClient();
1188
- const body = {};
1189
- if (options.name) body.name = options.name;
1190
- if (options.description) body.description = options.description;
1191
- if (options.category) body.category = options.category;
1192
- if (typeof options.tags === "string") {
1193
- body.tags = options.tags.split(",").map((t) => t.trim()).filter(Boolean);
1194
- }
1195
- if (Object.keys(body).length === 0) {
1196
- output.warning("No changes provided. Use --name, --description, --category, or --tags.");
1197
- return;
1198
- }
1199
- const result = await client.template.update(templateId, body);
1200
- output.success("Template updated successfully");
1201
- output.output(result);
1202
- });
1203
- template.command("delete <templateId>").description("Delete a template").option("-y, --yes", "Skip confirmation").action(async (templateId, options) => {
1204
- requireApiKey();
1205
- const client = getApiClient();
1206
- if (!options.yes) {
1207
- const { confirm } = await inquirer4.prompt([
1208
- {
1209
- type: "confirm",
1210
- name: "confirm",
1211
- message: `Are you sure you want to delete template ${templateId}?`,
1212
- default: false
1213
- }
1214
- ]);
1215
- if (!confirm) {
1216
- output.info("Delete cancelled");
1217
- return;
1218
- }
1219
- }
1220
- await client.template.delete(templateId);
1221
- output.success("Template deleted successfully");
1222
- });
1223
- return template;
1224
- }
1225
-
1226
- // src/commands/config.ts
1227
- import { Command as Command5 } from "commander";
1228
- import inquirer5 from "inquirer";
1229
1511
  function redactSecret(value) {
1230
1512
  if (!value) return value;
1231
1513
  if (value.length <= 8) return "********";
@@ -1239,7 +1521,7 @@ var ALLOWED_KEYS = [
1239
1521
  "outputFormat"
1240
1522
  ];
1241
1523
  function createConfigCommands() {
1242
- const config = new Command5("config").description("Manage CLI configuration").action(() => config.help());
1524
+ const config = new Command4("config").description("Manage CLI configuration").action(() => config.help());
1243
1525
  config.command("show").description("Show current configuration (effective values including environment variable overrides)").action(() => {
1244
1526
  const effectiveConfig = {};
1245
1527
  for (const key of ALLOWED_KEYS) {
@@ -1272,7 +1554,7 @@ function createConfigCommands() {
1272
1554
  let apiKey = options.apiKey || process.env.MDEDIT_API_KEY;
1273
1555
  if (!apiKey) {
1274
1556
  output.info("Get an API key: https://docs.mdedit.ai/api-keys");
1275
- const answers = await inquirer5.prompt([
1557
+ const answers = await inquirer4.prompt([
1276
1558
  {
1277
1559
  type: "password",
1278
1560
  name: "apiKey",
@@ -1313,7 +1595,7 @@ function createConfigCommands() {
1313
1595
  });
1314
1596
  config.command("clear").description("Clear all configuration").option("-y, --yes", "Skip confirmation").action(async (options) => {
1315
1597
  if (!options.yes) {
1316
- const { confirm } = await inquirer5.prompt([
1598
+ const { confirm } = await inquirer4.prompt([
1317
1599
  {
1318
1600
  type: "confirm",
1319
1601
  name: "confirm",
@@ -1333,16 +1615,32 @@ function createConfigCommands() {
1333
1615
  }
1334
1616
 
1335
1617
  // src/commands/apikey.ts
1336
- import { Command as Command6 } from "commander";
1337
- import inquirer6 from "inquirer";
1618
+ import { Command as Command5 } from "commander";
1619
+ import inquirer5 from "inquirer";
1620
+
1621
+ // src/presenters/apikey.ts
1622
+ function presentApiKeyListRow(key) {
1623
+ return {
1624
+ keyId: key?.keyId ?? "",
1625
+ name: key?.name ?? "",
1626
+ keyPrefix: key?.keyPrefix ?? "",
1627
+ status: key?.status ?? "",
1628
+ lastUsedAt: formatDateShort(key?.lastUsedAt),
1629
+ expiresAt: formatDateShort(key?.expiresAt),
1630
+ usageCount: formatCount(key?.usageCount)
1631
+ };
1632
+ }
1633
+
1634
+ // src/commands/apikey.ts
1635
+ var DEFAULT_API_KEY_SCOPES = ["articles:read", "articles:write"];
1338
1636
  function createApiKeyCommands() {
1339
- const apiKey = new Command6("api-key").description("Manage API keys for authentication").aliases(["apikey"]).action(() => apiKey.help());
1340
- 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) => {
1637
+ const apiKey = new Command5("api-key").description("Manage API keys for authentication").aliases(["apikey"]).action(() => apiKey.help());
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) => {
1341
1639
  requireApiKey();
1342
1640
  const client = getApiClient();
1343
1641
  let name = options.name;
1344
1642
  if (!name) {
1345
- const answers = await inquirer6.prompt([
1643
+ const answers = await inquirer5.prompt([
1346
1644
  {
1347
1645
  type: "input",
1348
1646
  name: "name",
@@ -1361,41 +1659,53 @@ function createApiKeyCommands() {
1361
1659
  }
1362
1660
  expiresInDays = days;
1363
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
+ }
1364
1667
  output.info("Creating API key...");
1365
1668
  const req = { name };
1366
1669
  if (options.description) req.description = options.description;
1367
1670
  if (expiresInDays !== void 0) req.expiresInDays = expiresInDays;
1671
+ req.scopes = scopes;
1368
1672
  const result = await client.apiKeys.create(req);
1369
1673
  output.success("API key created successfully!");
1370
- output.warning("\n\u26A0\uFE0F IMPORTANT: Save this API key now. It will not be shown again!\n");
1371
- console.log("API Key ID:", result.keyId);
1372
- console.log("API Key: ", result.key);
1373
- console.log("Name: ", result.name);
1374
- console.log("Created: ", result.createdAt);
1375
- if (result.expiresAt) {
1376
- console.log("Expires: ", result.expiresAt);
1377
- }
1674
+ output.warning("IMPORTANT: Save this API key now. It will not be shown again.");
1675
+ output.output({
1676
+ keyId: result.keyId,
1677
+ keyPrefix: result.keyPrefix,
1678
+ name: result.name,
1679
+ createdAt: result.createdAt,
1680
+ expiresAt: result.expiresAt,
1681
+ key: result.key
1682
+ });
1378
1683
  output.info("\nTo use this key with the CLI:");
1379
1684
  output.info(` mdedit config set apiKey ${result.key}`);
1380
1685
  output.info("\nOr set environment variable:");
1381
1686
  output.info(` export MDEDIT_API_KEY="${result.key}"`);
1382
1687
  });
1383
- apiKey.command("list").description("List your API keys").action(async () => {
1688
+ apiKey.command("list").description("List your API keys").option("--full", "Show full API key objects (all fields)").action(async (options) => {
1384
1689
  requireApiKey();
1385
1690
  const client = getApiClient();
1386
1691
  const result = await client.apiKeys.list();
1692
+ output.header("Your API Keys");
1693
+ if (output.isJson() || options.full) {
1694
+ output.output(result.keys);
1695
+ return;
1696
+ }
1387
1697
  if (result.keys.length === 0) {
1698
+ output.output([]);
1388
1699
  output.info("No API keys found. Create one with: mdedit apikey create");
1389
1700
  return;
1390
1701
  }
1391
- output.header("Your API Keys");
1392
- output.output(result.keys);
1702
+ output.output(result.keys.map(presentApiKeyListRow));
1393
1703
  });
1394
1704
  apiKey.command("revoke <keyId>").description("Revoke an API key").option("-y, --yes", "Skip confirmation").action(async (keyId, options) => {
1395
1705
  requireApiKey();
1396
1706
  const client = getApiClient();
1397
1707
  if (!options.yes) {
1398
- const { confirm } = await inquirer6.prompt([
1708
+ const { confirm } = await inquirer5.prompt([
1399
1709
  {
1400
1710
  type: "confirm",
1401
1711
  name: "confirm",
@@ -1415,17 +1725,212 @@ function createApiKeyCommands() {
1415
1725
  return apiKey;
1416
1726
  }
1417
1727
 
1418
- // src/index.ts
1728
+ // src/commands/skill.ts
1729
+ import { Command as Command6 } from "commander";
1730
+ import { readFileSync as readFileSync2, mkdirSync as mkdirSync2, existsSync as existsSync2, appendFileSync, writeFileSync as writeFileSync2 } from "fs";
1731
+ import { dirname, join as join2, resolve } from "path";
1732
+ import { homedir as homedir2 } from "os";
1733
+ import { fileURLToPath } from "url";
1419
1734
  var __filename = fileURLToPath(import.meta.url);
1420
1735
  var __dirname = dirname(__filename);
1736
+ function getSkillContent() {
1737
+ const candidates = [join2(__dirname, "../skill.md"), join2(__dirname, "../../skill.md")];
1738
+ for (const candidate of candidates) {
1739
+ if (existsSync2(candidate)) return readFileSync2(candidate, "utf-8");
1740
+ }
1741
+ throw new Error(`skill.md not found (searched: ${candidates.join(", ")})`);
1742
+ }
1743
+ var NAMED_TARGETS = ["claude", "cursor", "codex"];
1744
+ var TARGETS = {
1745
+ claude: {
1746
+ label: "Claude Code",
1747
+ path: (_cwd, global) => global ? join2(homedir2(), ".claude", "CLAUDE.md") : join2(process.cwd(), "CLAUDE.md"),
1748
+ mode: "append-section",
1749
+ sectionHeading: "## mdedit CLI"
1750
+ },
1751
+ cursor: {
1752
+ label: "Cursor",
1753
+ path: (_cwd, global) => global ? join2(homedir2(), ".cursor", "rules", "mdedit.mdc") : join2(process.cwd(), ".cursor", "rules", "mdedit.mdc"),
1754
+ mode: "write"
1755
+ },
1756
+ codex: {
1757
+ label: "GitHub Copilot / Codex",
1758
+ path: (cwd, _global) => join2(cwd, ".github", "copilot-instructions.md"),
1759
+ mode: "append-section",
1760
+ sectionHeading: "## mdedit CLI"
1761
+ }
1762
+ };
1763
+ function installToTarget(spec, skillContent, global) {
1764
+ const targetPath = spec.path(process.cwd(), global);
1765
+ const dir = dirname(resolve(targetPath));
1766
+ if (!existsSync2(dir)) {
1767
+ mkdirSync2(dir, { recursive: true });
1768
+ }
1769
+ if (spec.mode === "write") {
1770
+ writeFileSync2(targetPath, skillContent, "utf-8");
1771
+ output.success(`${spec.label}: skill written to ${targetPath}`);
1772
+ return;
1773
+ }
1774
+ const heading = spec.sectionHeading ?? "## mdedit CLI";
1775
+ if (existsSync2(targetPath)) {
1776
+ const existing = readFileSync2(targetPath, "utf-8");
1777
+ if (existing.includes(heading)) {
1778
+ output.info(`${spec.label}: skill section already present in ${targetPath} (skipped)`);
1779
+ return;
1780
+ }
1781
+ const trimmed = existing.trimEnd();
1782
+ appendFileSync(targetPath, `${trimmed}
1783
+
1784
+ ${heading}
1785
+
1786
+ ${skillContent}`, "utf-8");
1787
+ } else {
1788
+ writeFileSync2(targetPath, `${heading}
1789
+
1790
+ ${skillContent}`, "utf-8");
1791
+ }
1792
+ output.success(`${spec.label}: skill appended to ${targetPath}`);
1793
+ }
1794
+ function createSkillCommands() {
1795
+ const skill = new Command6("skill").description("Manage and install the mdedit agent skill").action(() => skill.help());
1796
+ skill.command("show").description("Print the mdedit agent skill to stdout").action(() => {
1797
+ process.stdout.write(getSkillContent());
1798
+ });
1799
+ skill.command("install").description(
1800
+ "Install the mdedit skill into AI agent configuration files (Claude Code, Cursor, GitHub Copilot/Codex)"
1801
+ ).option(
1802
+ "-t, --target <target>",
1803
+ "Which agent tool to install for: claude | cursor | codex | all (default: all)",
1804
+ "all"
1805
+ ).option("--global", "Install to home-directory targets instead of current project directory").action((options) => {
1806
+ const target = String(options.target).toLowerCase();
1807
+ const global = Boolean(options.global);
1808
+ const skillContent = getSkillContent();
1809
+ const validTargets = [...NAMED_TARGETS, "all"];
1810
+ if (!validTargets.includes(target)) {
1811
+ throw new Error(`Unknown target "${target}". Valid targets: ${validTargets.join(", ")}`);
1812
+ }
1813
+ const keys = target === "all" ? [...NAMED_TARGETS] : [target];
1814
+ for (const key of keys) {
1815
+ installToTarget(TARGETS[key], skillContent, global);
1816
+ }
1817
+ output.info("");
1818
+ output.info("To view the installed skill at any time: mdedit skill show");
1819
+ });
1820
+ return skill;
1821
+ }
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
+
1923
+ // src/index.ts
1924
+ var __filename2 = fileURLToPath2(import.meta.url);
1925
+ var __dirname2 = dirname2(__filename2);
1421
1926
  var version = "0.0.0";
1422
1927
  try {
1423
- const packageJson = JSON.parse(readFileSync2(join2(__dirname, "../package.json"), "utf-8"));
1928
+ const packageJson = JSON.parse(readFileSync3(join3(__dirname2, "../package.json"), "utf-8"));
1424
1929
  version = packageJson.version || version;
1425
1930
  } catch {
1426
1931
  }
1427
- var program = new Command7();
1428
- 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", "plain").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) => {
1932
+ var program = new Command8();
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) => {
1429
1934
  const opts = typeof thisCommand.optsWithGlobals === "function" ? (
1430
1935
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1431
1936
  thisCommand.optsWithGlobals()
@@ -1440,9 +1945,11 @@ program.name("mdedit").description("MDEdit.ai CLI - Command-line interface for t
1440
1945
  program.addCommand(createArticleCommands());
1441
1946
  program.addCommand(createWorkspaceCommands());
1442
1947
  program.addCommand(createFolderCommands());
1443
- program.addCommand(createTemplateCommands());
1444
1948
  program.addCommand(createConfigCommands());
1445
1949
  program.addCommand(createApiKeyCommands());
1950
+ program.addCommand(createSkillCommands());
1951
+ program.addCommand(createReviewCommands());
1952
+ program.addCommand(createSuggestCommand());
1446
1953
  program.command("health").description("Check API health status").action(async () => {
1447
1954
  const base = getApiBaseUrlRoot();
1448
1955
  const response = await fetch(`${base}/health`, { method: "GET" });
@@ -1451,32 +1958,59 @@ program.command("health").description("Check API health status").action(async ()
1451
1958
  }
1452
1959
  const result = await response.json().catch(() => ({}));
1453
1960
  output.success("API is healthy");
1454
- output.output(result);
1961
+ if (output.isJson()) {
1962
+ output.output(result);
1963
+ return;
1964
+ }
1965
+ if (result && typeof result === "object" && "status" in result) {
1966
+ output.info(`Status: ${result.status}`);
1967
+ }
1455
1968
  });
1456
1969
  program.command("info").description("Display CLI and API information").action(async () => {
1457
- output.header("MDEdit.ai CLI Information");
1458
- output.info(`CLI Version: ${version}`);
1459
1970
  const apiUrl = configManager.get("apiUrl") || process.env.MDEDIT_API_URL || "https://apiv2.mdedit.ai";
1460
- output.info(`API URL: ${apiUrl}`);
1461
1971
  const apiKey = configManager.get("apiKey");
1462
- output.info(`Auth Method: ${apiKey ? "API Key" : "None"}`);
1972
+ const workspaceId = configManager.get("workspaceId") || process.env.MDEDIT_WORKSPACE_ID || null;
1973
+ const authMethod = apiKey ? "apiKey" : "none";
1974
+ let health = void 0;
1975
+ let apiStatus = "unavailable";
1463
1976
  try {
1464
1977
  const base = getApiBaseUrlRoot();
1465
- const health = await fetch(`${base}/health`, { method: "GET" }).then((r) => r.json());
1466
- output.success("API Status: Healthy");
1467
- output.output(health);
1978
+ health = await fetch(`${base}/health`, { method: "GET" }).then((r) => r.json());
1979
+ apiStatus = "healthy";
1468
1980
  } catch {
1469
- output.warning("API Status: Unavailable");
1981
+ apiStatus = "unavailable";
1470
1982
  }
1471
- try {
1472
- if (apiKey) {
1983
+ let authOk = null;
1984
+ if (apiKey) {
1985
+ try {
1473
1986
  const client = getApiClient();
1474
1987
  await client.workspace.list();
1475
- output.success("Auth: OK");
1988
+ authOk = true;
1989
+ } catch {
1990
+ authOk = false;
1476
1991
  }
1477
- } catch {
1478
- output.warning("Auth: Failed");
1479
1992
  }
1993
+ if (output.isJson()) {
1994
+ output.output({
1995
+ cliVersion: version,
1996
+ apiUrl,
1997
+ workspaceId,
1998
+ authMethod,
1999
+ apiStatus,
2000
+ health,
2001
+ authOk
2002
+ });
2003
+ return;
2004
+ }
2005
+ output.header("MDEdit.ai CLI");
2006
+ output.info(`CLI Version: ${version}`);
2007
+ output.info(`API URL: ${apiUrl}`);
2008
+ if (workspaceId) output.info(`Workspace: ${workspaceId}`);
2009
+ output.info(`Auth Method: ${authMethod === "apiKey" ? "API Key" : "None"}`);
2010
+ if (apiStatus === "healthy") output.success("API Status: Healthy");
2011
+ else output.warning("API Status: Unavailable");
2012
+ if (authOk === true) output.success("Auth: OK");
2013
+ if (authOk === false) output.warning("Auth: Failed");
1480
2014
  });
1481
2015
  program.action(() => {
1482
2016
  program.outputHelp();
@@ -1492,7 +2026,37 @@ async function main() {
1492
2026
  await program.parseAsync(process.argv);
1493
2027
  } catch (err) {
1494
2028
  const debug = process.env.MDEDIT_DEBUG === "1";
1495
- 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) {
1496
2060
  output.error(`API request failed (${err.status}): ${err.message}`);
1497
2061
  if (err.status === 401) {
1498
2062
  output.info("Hint: set an API key via `mdedit config set apiKey <key>` or pass `--api-key <key>`.");
@@ -1508,7 +2072,7 @@ async function main() {
1508
2072
  } else {
1509
2073
  output.error(err);
1510
2074
  }
1511
- process.exitCode = 1;
2075
+ process.exitCode = CLI_EXIT_CODES.ERROR;
1512
2076
  }
1513
2077
  }
1514
2078
  await main();