@khanglvm/outline-cli 0.1.6 → 0.1.7

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/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.7 - 2026-06-10
4
+
5
+ - Changes since `v0.1.6`.
6
+ - feat: add Outline attachment downloads (e7d3ec0)
7
+
3
8
  ## 0.1.6 - 2026-03-08
4
9
 
5
10
  - Changes since `v0.1.5`.
package/README.md CHANGED
@@ -42,6 +42,19 @@ outline-cli invoke documents.info \
42
42
  --args '{"id":"<document-id>","view":"summary"}'
43
43
  ```
44
44
 
45
+ List and save embedded document images/files:
46
+
47
+ ```bash
48
+ outline-cli invoke documents.attachments \
49
+ --args '{"url":"https://handbook.example.com/doc/example-title-AbCdEf1234"}'
50
+
51
+ outline-cli invoke documents.download_attachments \
52
+ --args '{"url":"https://handbook.example.com/doc/example-title-AbCdEf1234","outputDir":"./outline-attachments","overwrite":true}'
53
+
54
+ outline-cli invoke attachments.download \
55
+ --args '{"id":"<attachment-id>","outputDir":"./outline-attachments","overwrite":true}'
56
+ ```
57
+
45
58
  List only collection root pages:
46
59
 
47
60
  ```bash
@@ -163,6 +176,7 @@ Use this short operating pattern when an AI agent drives the CLI:
163
176
  9. List existing profiles before creating one with `outline-cli profile list`.
164
177
  10. For new profiles, prefer API key mode and guide users through base URL + API key generation (`<base-url>/settings/api-and-apps`) before `profile add`.
165
178
  11. If output is file-offloaded, read only the required fields via `tmp cat` + `jq`.
179
+ 12. For embedded images/files in document markdown, use `documents.attachments`, `attachments.download`, or `documents.download_attachments`; do not force `attachments.redirect` through `api.call` because it returns binary data.
166
180
 
167
181
  For structured AI playbooks and scenario guides:
168
182
 
@@ -222,6 +236,14 @@ Release prerequisites:
222
236
  - `OUTLINE_ENTRY_BUILD_KEY` available in environment or `.env.local`
223
237
  - npm auth ready (`npm login`)
224
238
 
239
+ Optional GitHub automation:
240
+
241
+ - `.github/workflows/npm-auto-publish.yml` auto-publishes on pushes to `main` when `README.md` or `package.json` changes.
242
+ - If `package.json` version changes, the workflow publishes that exact version.
243
+ - If only docs metadata changes (for example `README.md`), the workflow cuts and publishes a patch release automatically.
244
+ - Required repository secrets: `NPM_TOKEN` and `OUTLINE_ENTRY_BUILD_KEY`.
245
+ - Ensure GitHub Actions can push to `main` and create tags in this repository.
246
+
225
247
  ## Security Notes
226
248
 
227
249
  - Never commit real API keys.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@khanglvm/outline-cli",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "Agent-optimized CLI for Outline API",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,9 +1,9 @@
1
1
  import { CliError } from "./errors.js";
2
2
 
3
- const AI_SKILL_DATA_VERSION = "2026-03-07.1";
3
+ const AI_SKILL_DATA_VERSION = "2026-06-10.1";
4
4
  const AI_HELP_SECTION_ID = "ai-skills";
5
5
  const QUICK_START_HELP_SECTION_ID = "quick-start-agent";
6
- const QUICK_START_HELP_VERSION = "2026-03-07.1";
6
+ const QUICK_START_HELP_VERSION = "2026-06-10.1";
7
7
 
8
8
  const QUICK_START_AGENT_PLAYBOOK = {
9
9
  title: "outline-cli onboarding for non-expert users",
@@ -137,6 +137,7 @@ const QUICK_START_AGENT_PLAYBOOK = {
137
137
  "Create a draft release notes document with today's date.",
138
138
  "Append a short status update to document <document-id>.",
139
139
  "Find documents mentioning incident response in the last month.",
140
+ "Download the embedded images from document <document-url> into ./outline-attachments.",
140
141
  "Show who can access document <document-id>.",
141
142
  "Compare two documents and list key differences.",
142
143
  "Generate a TODO list from document <document-id>.",
@@ -172,6 +173,7 @@ const AI_GLOBAL_GUIDANCE = {
172
173
  "Prefer batch operations (queries, ids, or batch command) before multi-call loops.",
173
174
  "For heavy retrieval, use search.research with precisionMode + perQueryView/perQueryHitLimit to control token cost.",
174
175
  "When outputs offload to tmp files, read the new preview first, then inspect file content only when needed.",
176
+ "For embedded images/files, use documents.attachments or documents.download_attachments; attachments.redirect returns binary bytes and should not go through api.call.",
175
177
  "Keep mutating calls action-gated and explicit with performAction=true only at execute time.",
176
178
  "Capture audit evidence (events/revisions/policies) immediately after high-impact changes.",
177
179
  ],
@@ -360,6 +362,47 @@ const AI_SKILLS = [
360
362
  "Never apply mutation from synthetic issue refs without doc hydration.",
361
363
  ],
362
364
  },
365
+ {
366
+ id: "embedded_attachment_access",
367
+ title: "Embedded attachment and image access",
368
+ scenarios: ["UC-08", "UC-12"],
369
+ objective: "Extract, download, and hand off files embedded in Outline documents, including markdown images.",
370
+ featureUpdates: [
371
+ "documents.attachments extracts /api/attachments.redirect references from document markdown.",
372
+ "attachments.download and documents.download_attachments save authenticated binary attachment bytes locally with contentType, byte count, and sha256 metadata.",
373
+ ],
374
+ sequence: [
375
+ {
376
+ step: 1,
377
+ tool: "documents.attachments",
378
+ purpose: "List embedded attachment IDs and source URLs without downloading bytes.",
379
+ },
380
+ {
381
+ step: 2,
382
+ tool: "attachments.download",
383
+ purpose: "Save one selected attachment/image to a local file.",
384
+ },
385
+ {
386
+ step: 3,
387
+ tool: "documents.download_attachments",
388
+ purpose: "Save every embedded file from a document into an output directory.",
389
+ },
390
+ {
391
+ step: 4,
392
+ tool: "documents.info",
393
+ purpose: "Re-read the document only when you need surrounding text context for downloaded files.",
394
+ },
395
+ ],
396
+ efficiencyTips: [
397
+ "Run documents.attachments first when you only need IDs or want to choose a subset.",
398
+ "Use a scratch outputDir plus overwrite=true for repeatable automation.",
399
+ "Keep download concurrency modest for image-heavy documents.",
400
+ ],
401
+ safetyChecks: [
402
+ "Do not use api.call for attachments.redirect; it is a binary endpoint.",
403
+ "Verify returned bytes, contentType, sha256, and filePath before downstream processing.",
404
+ ],
405
+ },
363
406
  {
364
407
  id: "rollback_safe_editing",
365
408
  title: "Rollback-safe postmortem editing",
@@ -3,8 +3,8 @@ export const ENTRY_INTEGRITY_MANIFEST = Object.freeze({
3
3
  version: 1,
4
4
  algorithm: "sha256",
5
5
  signatureAlgorithm: "sha256-salted-manifest-v1",
6
- signature: "c69d41948b78c8ae35c0223377149ece8df5588863a010adf92a0b6ad11876d3",
7
- generatedAt: "2026-03-08T04:29:38.219Z",
6
+ signature: "e811622c1740da1e9a0833e3a00451bbbbe14ad30b29400fd341484db589a301",
7
+ generatedAt: "2026-06-10T08:57:44.270Z",
8
8
  files: [
9
9
  {
10
10
  "path": "src/action-gate.js",
@@ -12,7 +12,7 @@ export const ENTRY_INTEGRITY_MANIFEST = Object.freeze({
12
12
  },
13
13
  {
14
14
  "path": "src/agent-skills.js",
15
- "sha256": "d40e94a4b61922d3ee8a43ed89d5e9ce1562a2cdffd37e2f396c2a18b9a481fc"
15
+ "sha256": "6a23db3378050f5a2e46564bca921985708fddbc144316efd39654d0f2860693"
16
16
  },
17
17
  {
18
18
  "path": "src/cli.js",
@@ -32,7 +32,7 @@ export const ENTRY_INTEGRITY_MANIFEST = Object.freeze({
32
32
  },
33
33
  {
34
34
  "path": "src/outline-client.js",
35
- "sha256": "2fe343f3cb1773c53fd14fad784d3ef1f5ff0e2c4c43b4a752ca9b7d5421677c"
35
+ "sha256": "457900dfee7c521f0683a0344009621df720e72d8cdcb3b32b4efed1c3fdf9be"
36
36
  },
37
37
  {
38
38
  "path": "src/result-store.js",
@@ -48,11 +48,11 @@ export const ENTRY_INTEGRITY_MANIFEST = Object.freeze({
48
48
  },
49
49
  {
50
50
  "path": "src/tool-arg-schemas.js",
51
- "sha256": "51f8727255e5b2b0a4cce78495cfaed9bb1869a7ef104b22dbc170604f878feb"
51
+ "sha256": "e1256642373a8b619b9b690be422e8d7d660e1f67bac10ff9ca237950df0b73d"
52
52
  },
53
53
  {
54
54
  "path": "src/tools.extended.js",
55
- "sha256": "0c5317ca0b28a0b7110d9e6c81d8ca6ccd705e9b303de2f29e03f847b31df310"
55
+ "sha256": "2861108ad0f2d42ad807f222f367557be3b2c6414a58006c89f9afe4bab85e22"
56
56
  },
57
57
  {
58
58
  "path": "src/tools.js",
@@ -39,6 +39,35 @@ export class OutlineClient {
39
39
  throw lastErr;
40
40
  }
41
41
 
42
+ async download(method, body = {}, options = {}) {
43
+ const apiMethod = method.startsWith("/") ? method.slice(1) : method;
44
+ const url = `${this.baseApiUrl}/${apiMethod}`;
45
+ const maxAttempts = Math.max(1, options.maxAttempts || 1);
46
+
47
+ let lastErr;
48
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
49
+ try {
50
+ return await this.#downloadOnce(url, body, options);
51
+ } catch (err) {
52
+ lastErr = err;
53
+ const shouldRetry =
54
+ err instanceof ApiError &&
55
+ (err.details.status === 429 || err.details.status >= 500) &&
56
+ attempt < maxAttempts;
57
+
58
+ if (!shouldRetry) {
59
+ throw err;
60
+ }
61
+
62
+ const retryAfter = Number(err.details.retryAfter || 0);
63
+ const waitMs = retryAfter > 0 ? retryAfter * 1000 : attempt * 400;
64
+ await sleep(waitMs);
65
+ }
66
+ }
67
+
68
+ throw lastErr;
69
+ }
70
+
42
71
  async #callOnce(url, body, options) {
43
72
  const bodyType = options.bodyType === "multipart" ? "multipart" : "json";
44
73
  const requestBody = this.#buildRequestBody(bodyType, body);
@@ -96,6 +125,70 @@ export class OutlineClient {
96
125
  };
97
126
  }
98
127
 
128
+ async #downloadOnce(url, body, options) {
129
+ const requestBody = this.#buildRequestBody(options.bodyType === "multipart" ? "multipart" : "json", body);
130
+ const headers = await this.#buildHeaders(
131
+ {
132
+ Accept: "*/*",
133
+ ...(options.headers || {}),
134
+ },
135
+ { bodyType: options.bodyType === "multipart" ? "multipart" : "json" }
136
+ );
137
+ const controller = new AbortController();
138
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
139
+
140
+ let res;
141
+ try {
142
+ res = await fetch(url, {
143
+ method: "POST",
144
+ headers,
145
+ body: requestBody,
146
+ signal: controller.signal,
147
+ });
148
+ } catch (err) {
149
+ if (err.name === "AbortError") {
150
+ throw new ApiError(`Request timeout after ${this.timeoutMs}ms`, {
151
+ status: 408,
152
+ url,
153
+ });
154
+ }
155
+ throw new ApiError(`Network error: ${err.message}`, {
156
+ status: 503,
157
+ url,
158
+ });
159
+ } finally {
160
+ clearTimeout(timeout);
161
+ }
162
+
163
+ if (!res.ok) {
164
+ const text = await res.text().catch(() => "");
165
+ let parsed;
166
+ try {
167
+ parsed = text ? JSON.parse(text) : {};
168
+ } catch {
169
+ parsed = { ok: false, message: text || res.statusText };
170
+ }
171
+
172
+ const status = parsed?.status || res.status;
173
+ const retryAfter = res.headers.get("retry-after");
174
+ throw new ApiError(parsed?.message || parsed?.error || res.statusText, {
175
+ status,
176
+ retryAfter,
177
+ body: parsed,
178
+ url,
179
+ });
180
+ }
181
+
182
+ const buffer = Buffer.from(await res.arrayBuffer());
183
+ return {
184
+ ok: true,
185
+ status: res.status,
186
+ headers: Object.fromEntries(res.headers.entries()),
187
+ body: buffer,
188
+ url: res.url,
189
+ };
190
+ }
191
+
99
192
  #buildRequestBody(bodyType, body) {
100
193
  if (bodyType === "multipart") {
101
194
  if (body instanceof FormData) {
@@ -640,6 +640,61 @@ export const TOOL_ARG_SCHEMAS = {
640
640
  }
641
641
  },
642
642
  },
643
+ "documents.attachments": {
644
+ properties: {
645
+ id: { type: "string" },
646
+ documentId: { type: "string" },
647
+ url: { type: "string" },
648
+ shareId: { type: "string" },
649
+ maxAttempts: { type: "number", min: 1 },
650
+ },
651
+ custom(args, issues) {
652
+ if (!args.id && !args.documentId && !args.url && !args.shareId) {
653
+ issues.push({ path: "args.id", message: "or args.documentId, args.url, or args.shareId is required" });
654
+ }
655
+ },
656
+ },
657
+ "attachments.download": {
658
+ properties: {
659
+ id: { type: "string" },
660
+ attachmentId: { type: "string" },
661
+ url: { type: "string" },
662
+ path: { type: "string" },
663
+ outputDir: { type: "string" },
664
+ filePath: { type: "string" },
665
+ fileName: { type: "string" },
666
+ overwrite: { type: "boolean" },
667
+ maxAttempts: { type: "number", min: 1 },
668
+ },
669
+ custom(args, issues) {
670
+ if (!args.id && !args.attachmentId && !args.url && !args.path) {
671
+ issues.push({ path: "args.id", message: "or args.attachmentId, args.url, or args.path is required" });
672
+ }
673
+ if (args.filePath && (args.outputDir || args.fileName)) {
674
+ issues.push({ path: "args.filePath", message: "cannot be combined with args.outputDir or args.fileName" });
675
+ }
676
+ },
677
+ },
678
+ "documents.download_attachments": {
679
+ properties: {
680
+ id: { type: "string" },
681
+ documentId: { type: "string" },
682
+ url: { type: "string" },
683
+ shareId: { type: "string" },
684
+ outputDir: { type: "string" },
685
+ overwrite: { type: "boolean" },
686
+ concurrency: { type: "number", min: 1 },
687
+ maxAttempts: { type: "number", min: 1 },
688
+ },
689
+ custom(args, issues) {
690
+ if (!args.id && !args.documentId && !args.url && !args.shareId) {
691
+ issues.push({ path: "args.id", message: "or args.documentId, args.url, or args.shareId is required" });
692
+ }
693
+ if (typeof args.concurrency === "number" && args.concurrency > 8) {
694
+ issues.push({ path: "args.concurrency", message: "must be <= 8" });
695
+ }
696
+ },
697
+ },
643
698
  "documents.info": {
644
699
  properties: {
645
700
  id: { type: "string" },
@@ -1,8 +1,10 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
+ import { createHash } from "node:crypto";
3
4
  import { ApiError, CliError } from "./errors.js";
4
5
  import { assertPerformAction } from "./action-gate.js";
5
- import { compactValue, ensureStringArray, mapLimit, toInteger } from "./utils.js";
6
+ import { defaultTmpDir } from "./config-store.js";
7
+ import { compactValue, ensureStringArray, mapLimit, sanitizeFileToken, toInteger } from "./utils.js";
6
8
 
7
9
  const CONTROL_ARG_KEYS = new Set([
8
10
  "performAction",
@@ -53,6 +55,201 @@ function appendMultipartValue(form, key, value) {
53
55
  form.append(key, String(value));
54
56
  }
55
57
 
58
+ const ATTACHMENT_REDIRECT_PATTERN =
59
+ /((?:https?:\/\/[^\s)"']+)?\/api\/attachments\.redirect\?[^)\s"']*?\bid=([0-9a-fA-F-]{36})[^)\s"']*)/g;
60
+
61
+ const EXT_BY_CONTENT_TYPE = new Map([
62
+ ["image/png", ".png"],
63
+ ["image/jpeg", ".jpg"],
64
+ ["image/gif", ".gif"],
65
+ ["image/webp", ".webp"],
66
+ ["image/svg+xml", ".svg"],
67
+ ["application/pdf", ".pdf"],
68
+ ["text/plain", ".txt"],
69
+ ["text/markdown", ".md"],
70
+ ["application/json", ".json"],
71
+ ["application/zip", ".zip"],
72
+ ]);
73
+
74
+ function getHeader(headers = {}, name) {
75
+ const target = String(name || "").toLowerCase();
76
+ for (const [key, value] of Object.entries(headers || {})) {
77
+ if (String(key).toLowerCase() === target) {
78
+ return value;
79
+ }
80
+ }
81
+ return undefined;
82
+ }
83
+
84
+ function contentTypeToExtension(contentType) {
85
+ const normalized = String(contentType || "").split(";")[0].trim().toLowerCase();
86
+ return EXT_BY_CONTENT_TYPE.get(normalized) || ".bin";
87
+ }
88
+
89
+ function parseContentDispositionFilename(value) {
90
+ const raw = String(value || "");
91
+ const encoded = raw.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
92
+ if (encoded) {
93
+ try {
94
+ return decodeURIComponent(encoded);
95
+ } catch {
96
+ return encoded;
97
+ }
98
+ }
99
+ return raw.match(/filename="?([^";]+)"?/i)?.[1] || "";
100
+ }
101
+
102
+ function extractAttachmentId(value) {
103
+ const raw = String(value || "").trim();
104
+ if (!raw) {
105
+ return "";
106
+ }
107
+ if (/^[0-9a-fA-F-]{36}$/.test(raw)) {
108
+ return raw.toLowerCase();
109
+ }
110
+
111
+ try {
112
+ const parsed = new URL(raw, "https://outline.local");
113
+ const id = parsed.searchParams.get("id");
114
+ return id && /^[0-9a-fA-F-]{36}$/.test(id) ? id.toLowerCase() : "";
115
+ } catch {
116
+ const match = raw.match(/\bid=([0-9a-fA-F-]{36})\b/);
117
+ return match ? match[1].toLowerCase() : "";
118
+ }
119
+ }
120
+
121
+ function extractDocumentUrlId(value) {
122
+ const raw = String(value || "").trim();
123
+ if (!raw) {
124
+ return "";
125
+ }
126
+
127
+ try {
128
+ const parsed = new URL(raw);
129
+ const last = parsed.pathname.split("/").filter(Boolean).pop() || "";
130
+ return last.match(/-([A-Za-z0-9]{8,})$/)?.[1] || "";
131
+ } catch {
132
+ return raw.match(/-([A-Za-z0-9]{8,})$/)?.[1] || "";
133
+ }
134
+ }
135
+
136
+ function extractAttachmentRefsFromText(text, baseUrl = "") {
137
+ const refs = [];
138
+ const seen = new Set();
139
+ const source = String(text || "");
140
+ const base = String(baseUrl || "").replace(/\/+$/, "");
141
+ const pattern = new RegExp(ATTACHMENT_REDIRECT_PATTERN.source, "g");
142
+ let match;
143
+
144
+ while ((match = pattern.exec(source)) !== null) {
145
+ const id = extractAttachmentId(match[1]);
146
+ if (!id || seen.has(id)) {
147
+ continue;
148
+ }
149
+ seen.add(id);
150
+ const url = match[1];
151
+ refs.push({
152
+ id,
153
+ index: refs.length,
154
+ source: "markdown",
155
+ url,
156
+ absoluteUrl: url.startsWith("http") || !base ? url : `${base}${url}`,
157
+ position: match.index,
158
+ });
159
+ }
160
+
161
+ return refs;
162
+ }
163
+
164
+ async function readDocumentForAttachments(ctx, args = {}) {
165
+ const id = args.id || args.documentId || extractDocumentUrlId(args.url);
166
+ const shareId = args.shareId;
167
+ if (!id && !shareId) {
168
+ throw new CliError("document attachment tools require args.id, args.documentId, args.url, or args.shareId");
169
+ }
170
+
171
+ const body = compactValue({ id, shareId }) || {};
172
+ const res = await ctx.client.call("documents.info", body, {
173
+ maxAttempts: toInteger(args.maxAttempts, 2),
174
+ });
175
+ const doc = res.body?.data || null;
176
+ if (!doc) {
177
+ throw new CliError("documents.info response did not include document data");
178
+ }
179
+ return doc;
180
+ }
181
+
182
+ function summarizeAttachmentDocument(doc) {
183
+ return {
184
+ id: doc?.id,
185
+ title: doc?.title,
186
+ url: doc?.url,
187
+ urlId: doc?.urlId,
188
+ collectionId: doc?.collectionId,
189
+ parentDocumentId: doc?.parentDocumentId,
190
+ revision: doc?.revision,
191
+ updatedAt: doc?.updatedAt,
192
+ };
193
+ }
194
+
195
+ function resolveAttachmentOutputPath(args, id, headers, index = null) {
196
+ if (args.filePath) {
197
+ return path.resolve(String(args.filePath));
198
+ }
199
+
200
+ const contentType = getHeader(headers, "content-type");
201
+ const dispositionName = parseContentDispositionFilename(getHeader(headers, "content-disposition"));
202
+ const requestedName = typeof args.fileName === "string" ? args.fileName.trim() : "";
203
+ const baseName = requestedName || dispositionName;
204
+ const ext = path.extname(baseName) || contentTypeToExtension(contentType);
205
+ const prefix = index === null ? "" : `${String(index + 1).padStart(2, "0")}-`;
206
+ const fallbackName = `${prefix}${id}${ext}`;
207
+ const safeName = sanitizeFileToken(baseName ? `${prefix}${baseName}` : fallbackName);
208
+ const outputDir = path.resolve(String(args.outputDir || path.join(defaultTmpDir(), "attachments")));
209
+
210
+ return path.join(outputDir, safeName);
211
+ }
212
+
213
+ async function writeAttachmentFile(filePath, buffer, overwrite) {
214
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
215
+ try {
216
+ await fs.writeFile(filePath, buffer, { flag: overwrite ? "w" : "wx" });
217
+ } catch (err) {
218
+ if (err?.code === "EEXIST") {
219
+ throw new CliError(`Attachment file already exists: ${filePath}`, {
220
+ code: "ATTACHMENT_FILE_EXISTS",
221
+ filePath,
222
+ });
223
+ }
224
+ throw err;
225
+ }
226
+ }
227
+
228
+ async function downloadAttachmentToFile(ctx, args = {}, id, index = null) {
229
+ if (!ctx.client || typeof ctx.client.download !== "function") {
230
+ throw new CliError("Current Outline client does not support binary downloads");
231
+ }
232
+
233
+ const res = await ctx.client.download("attachments.redirect", { id }, {
234
+ maxAttempts: toInteger(args.maxAttempts, 2),
235
+ });
236
+ const buffer = res.body;
237
+ const filePath = resolveAttachmentOutputPath(args, id, res.headers, index);
238
+ await writeAttachmentFile(filePath, buffer, args.overwrite === true);
239
+
240
+ const contentType = getHeader(res.headers, "content-type") || "application/octet-stream";
241
+ return {
242
+ id,
243
+ ok: true,
244
+ filePath,
245
+ bytes: buffer.length,
246
+ sha256: createHash("sha256").update(buffer).digest("hex"),
247
+ contentType,
248
+ status: res.status,
249
+ sourceUrl: res.url,
250
+ };
251
+ }
252
+
56
253
  function defaultUsageArgs(def) {
57
254
  if (def.tool === "documents.empty_trash") {
58
255
  return def.mutating ? { performAction: true } : {};
@@ -408,10 +605,39 @@ async function buildAnswerFallbackResult(ctx, question, args = {}) {
408
605
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 2));
409
606
  const contextChars = Math.max(80, toInteger(args.contextChars, 220));
410
607
  const limit = Math.max(1, Math.min(8, toInteger(args.limit, 5)));
608
+ const scopedDocumentId = args.documentId || args.id;
609
+
610
+ if (scopedDocumentId) {
611
+ const res = await ctx.client.call("documents.info", { id: scopedDocumentId }, { maxAttempts });
612
+ const document = normalizeFallbackAnswerHit(res.body?.data, contextChars);
613
+ return {
614
+ question,
615
+ answer: "",
616
+ noAnswerReason: "documents.answerQuestion is unsupported by this Outline deployment; returning the scoped document as retrieval evidence instead.",
617
+ unsupported: true,
618
+ fallbackUsed: true,
619
+ fallbackTool: "documents.info",
620
+ fallbackSuggestion: {
621
+ tool: "documents.info",
622
+ args: compactValue({
623
+ id: scopedDocumentId,
624
+ view: "summary",
625
+ }),
626
+ },
627
+ documents: document ? [document] : [],
628
+ retrieval: {
629
+ query: question,
630
+ result: compactValue({
631
+ ...maybeDropPolicies(res.body, !!args.includePolicies),
632
+ data: document,
633
+ }),
634
+ },
635
+ };
636
+ }
637
+
411
638
  const body = compactValue({
412
639
  query: question,
413
640
  collectionId: args.collectionId,
414
- documentId: args.documentId || args.id,
415
641
  userId: args.userId,
416
642
  shareId: args.shareId,
417
643
  statusFilter: args.statusFilter,
@@ -535,16 +761,30 @@ async function documentsAnswerBatchTool(ctx, args = {}) {
535
761
  };
536
762
  } catch (err) {
537
763
  if (parsed && isAnswerEndpointUnsupported(err)) {
538
- return {
539
- index,
540
- ok: true,
541
- question: parsed.question,
542
- documentId: parsed.documentId,
543
- result: await buildAnswerFallbackResult(ctx, parsed.question, {
544
- ...args,
545
- ...parsed.body,
546
- }),
547
- };
764
+ try {
765
+ return {
766
+ index,
767
+ ok: true,
768
+ question: parsed.question,
769
+ documentId: parsed.documentId,
770
+ result: await buildAnswerFallbackResult(ctx, parsed.question, {
771
+ ...args,
772
+ ...parsed.body,
773
+ }),
774
+ };
775
+ } catch (fallbackErr) {
776
+ if (fallbackErr instanceof ApiError || fallbackErr instanceof CliError) {
777
+ return {
778
+ index,
779
+ ok: false,
780
+ question: parsed.question,
781
+ documentId: parsed.documentId,
782
+ error: fallbackErr.message,
783
+ status: fallbackErr instanceof ApiError ? fallbackErr.details.status : undefined,
784
+ };
785
+ }
786
+ throw fallbackErr;
787
+ }
548
788
  }
549
789
  if (err instanceof ApiError || err instanceof CliError) {
550
790
  return {
@@ -574,6 +814,73 @@ async function documentsAnswerBatchTool(ctx, args = {}) {
574
814
  };
575
815
  }
576
816
 
817
+ async function documentsAttachmentsTool(ctx, args = {}) {
818
+ const doc = await readDocumentForAttachments(ctx, args);
819
+ const attachments = extractAttachmentRefsFromText(doc.text || "", ctx.profile?.baseUrl);
820
+
821
+ return {
822
+ tool: "documents.attachments",
823
+ profile: ctx.profile.id,
824
+ result: {
825
+ document: summarizeAttachmentDocument(doc),
826
+ total: attachments.length,
827
+ attachments,
828
+ },
829
+ };
830
+ }
831
+
832
+ async function attachmentsDownloadTool(ctx, args = {}) {
833
+ const id = extractAttachmentId(args.id || args.attachmentId || args.url || args.path);
834
+ if (!id) {
835
+ throw new CliError("attachments.download requires args.id or an attachment redirect args.url/path");
836
+ }
837
+
838
+ return {
839
+ tool: "attachments.download",
840
+ profile: ctx.profile.id,
841
+ result: await downloadAttachmentToFile(ctx, args, id),
842
+ };
843
+ }
844
+
845
+ async function documentsDownloadAttachmentsTool(ctx, args = {}) {
846
+ const doc = await readDocumentForAttachments(ctx, args);
847
+ const attachments = extractAttachmentRefsFromText(doc.text || "", ctx.profile?.baseUrl);
848
+ const concurrency = Math.max(1, Math.min(8, toInteger(args.concurrency, 3)));
849
+ const items = await mapLimit(attachments, concurrency, async (attachment, index) => {
850
+ try {
851
+ const saved = await downloadAttachmentToFile(ctx, args, attachment.id, index);
852
+ return {
853
+ ...attachment,
854
+ ...saved,
855
+ };
856
+ } catch (err) {
857
+ if (err instanceof ApiError || err instanceof CliError) {
858
+ return {
859
+ ...attachment,
860
+ ok: false,
861
+ error: err.message,
862
+ status: err instanceof ApiError ? err.details.status : undefined,
863
+ };
864
+ }
865
+ throw err;
866
+ }
867
+ });
868
+ const failed = items.filter((item) => !item.ok).length;
869
+
870
+ return {
871
+ tool: "documents.download_attachments",
872
+ profile: ctx.profile.id,
873
+ result: {
874
+ document: summarizeAttachmentDocument(doc),
875
+ total: attachments.length,
876
+ succeeded: items.length - failed,
877
+ failed,
878
+ outputDir: path.resolve(String(args.outputDir || path.join(defaultTmpDir(), "attachments"))),
879
+ items,
880
+ },
881
+ };
882
+ }
883
+
577
884
  async function documentsImportFileTool(ctx, args = {}) {
578
885
  assertPerformAction(args, {
579
886
  tool: "documents.import_file",
@@ -3217,6 +3524,64 @@ export const EXTENDED_TOOLS = {
3217
3524
  ],
3218
3525
  handler: documentsIssueRefReportTool,
3219
3526
  },
3527
+ "documents.attachments": {
3528
+ signature:
3529
+ "documents.attachments(args: { id?: string; documentId?: string; url?: string; shareId?: string; maxAttempts?: number })",
3530
+ description:
3531
+ "Extract embedded Outline attachment references from a document body, including images rendered through /api/attachments.redirect.",
3532
+ usageExample: {
3533
+ tool: "documents.attachments",
3534
+ args: {
3535
+ url: "https://handbook.example.com/doc/example-title-AbCdEf1234",
3536
+ },
3537
+ },
3538
+ bestPractices: [
3539
+ "Use this after documents.info when you need to enumerate embedded images or file links without downloading bytes.",
3540
+ "Pass a document URL directly; the tool resolves the Outline URL id suffix through documents.info.",
3541
+ "Follow with attachments.download or documents.download_attachments to save files locally.",
3542
+ ],
3543
+ handler: documentsAttachmentsTool,
3544
+ },
3545
+ "attachments.download": {
3546
+ signature:
3547
+ "attachments.download(args: { id?: string; attachmentId?: string; url?: string; path?: string; outputDir?: string; filePath?: string; fileName?: string; overwrite?: boolean; maxAttempts?: number })",
3548
+ description:
3549
+ "Download one Outline attachment or embedded image through the authenticated attachments.redirect endpoint and save it locally.",
3550
+ usageExample: {
3551
+ tool: "attachments.download",
3552
+ args: {
3553
+ id: "15831936-7fef-4a58-b17b-121a65c3d787",
3554
+ outputDir: "./outline-attachments",
3555
+ overwrite: true,
3556
+ },
3557
+ },
3558
+ bestPractices: [
3559
+ "Prefer id for deterministic downloads; url/path may be an /api/attachments.redirect?id=... value copied from document markdown.",
3560
+ "Use outputDir for generated names or filePath when the caller needs an exact path.",
3561
+ "Inspect returned sha256, bytes, and contentType before handing the file to downstream tools.",
3562
+ ],
3563
+ handler: attachmentsDownloadTool,
3564
+ },
3565
+ "documents.download_attachments": {
3566
+ signature:
3567
+ "documents.download_attachments(args: { id?: string; documentId?: string; url?: string; shareId?: string; outputDir?: string; overwrite?: boolean; concurrency?: number; maxAttempts?: number })",
3568
+ description:
3569
+ "Extract all embedded Outline attachment references from a document and save each referenced file locally.",
3570
+ usageExample: {
3571
+ tool: "documents.download_attachments",
3572
+ args: {
3573
+ url: "https://handbook.example.com/doc/example-title-AbCdEf1234",
3574
+ outputDir: "./outline-attachments",
3575
+ overwrite: true,
3576
+ },
3577
+ },
3578
+ bestPractices: [
3579
+ "Run documents.attachments first when you only need metadata or want to choose a subset.",
3580
+ "Keep concurrency modest for large image-heavy documents to avoid rate limits.",
3581
+ "Use overwrite=true for repeatable automation into a scratch directory.",
3582
+ ],
3583
+ handler: documentsDownloadAttachmentsTool,
3584
+ },
3220
3585
  "documents.import_file": {
3221
3586
  signature:
3222
3587
  "documents.import_file(args: { filePath: string; collectionId?: string; parentDocumentId?: string; publish?: boolean; contentType?: string; includePolicies?: boolean; maxAttempts?: number; performAction?: boolean; ...endpointArgs })",