@khanglvm/outline-cli 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,11 @@
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";
8
+ import { collectionsOpenBatchTool, collectionsOpenTool, documentsOpenBatchTool, memoryResolveTool } from "./memory-store.js";
6
9
 
7
10
  const CONTROL_ARG_KEYS = new Set([
8
11
  "performAction",
@@ -14,6 +17,116 @@ const CONTROL_ARG_KEYS = new Set([
14
17
  "compact",
15
18
  ]);
16
19
 
20
+ const ACCESS_RESOLVE_ARG_KEYS = [
21
+ "documentId",
22
+ "collectionId",
23
+ "documentRef",
24
+ "documentRefs",
25
+ "documentQuery",
26
+ "documentQueries",
27
+ "refs",
28
+ "query",
29
+ "queries",
30
+ "shareId",
31
+ "shareIds",
32
+ "urlId",
33
+ "urlIds",
34
+ "url",
35
+ "urls",
36
+ "profile",
37
+ "resolveLimit",
38
+ "minScore",
39
+ "maxAgeHours",
40
+ "refresh",
41
+ "strict",
42
+ "strictThreshold",
43
+ "fallbackSearch",
44
+ "fallbackMinScore",
45
+ "fallbackLimit",
46
+ "fallbackMode",
47
+ "resolveCollectionId",
48
+ "resolveConcurrency",
49
+ "resolveHydrateConcurrency",
50
+ "hydrateConcurrency",
51
+ "snippetMinWords",
52
+ "snippetMaxWords",
53
+ ];
54
+
55
+ const ENTITY_RESOLVE_ARG_KEYS = [
56
+ "ref",
57
+ "refs",
58
+ "query",
59
+ "queries",
60
+ "userRef",
61
+ "userRefs",
62
+ "userQuery",
63
+ "userQueries",
64
+ "groupRef",
65
+ "groupRefs",
66
+ "groupQuery",
67
+ "groupQueries",
68
+ "templateRef",
69
+ "templateRefs",
70
+ "templateQuery",
71
+ "templateQueries",
72
+ "profile",
73
+ "resolveLimit",
74
+ "minScore",
75
+ "maxAgeHours",
76
+ "refresh",
77
+ "strict",
78
+ "strictThreshold",
79
+ "fallbackSearch",
80
+ "fallbackMinScore",
81
+ "fallbackLimit",
82
+ "fallbackMode",
83
+ "resolveConcurrency",
84
+ "resolveHydrateConcurrency",
85
+ "hydrateConcurrency",
86
+ ];
87
+
88
+ const ANSWER_RESOLVE_ARG_KEYS = [
89
+ "id",
90
+ "documentQuery",
91
+ "documentQueries",
92
+ "documentRef",
93
+ "documentRefs",
94
+ "refs",
95
+ "shareId",
96
+ "shareIds",
97
+ "urlId",
98
+ "urlIds",
99
+ "url",
100
+ "urls",
101
+ "collectionQuery",
102
+ "collectionRef",
103
+ "collectionQueries",
104
+ "collectionRefs",
105
+ "userQuery",
106
+ "userRef",
107
+ "userQueries",
108
+ "userRefs",
109
+ "profile",
110
+ "resolveLimit",
111
+ "minScore",
112
+ "maxAgeHours",
113
+ "refresh",
114
+ "strict",
115
+ "strictThreshold",
116
+ "fallbackSearch",
117
+ "fallbackMinScore",
118
+ "fallbackLimit",
119
+ "fallbackMode",
120
+ "resolveCollectionId",
121
+ "resolveConcurrency",
122
+ "resolveHydrateConcurrency",
123
+ "hydrateConcurrency",
124
+ "contextChars",
125
+ "excerptChars",
126
+ "snippetMinWords",
127
+ "snippetMaxWords",
128
+ ];
129
+
17
130
  function maybeDropPolicies(payload, includePolicies) {
18
131
  if (includePolicies) {
19
132
  return payload;
@@ -53,7 +166,334 @@ function appendMultipartValue(form, key, value) {
53
166
  form.append(key, String(value));
54
167
  }
55
168
 
169
+ const ATTACHMENT_REDIRECT_PATTERN =
170
+ /((?:https?:\/\/[^\s)"']+)?\/api\/attachments\.redirect\?[^)\s"']*?\bid=([0-9a-fA-F-]{36})[^)\s"']*)/g;
171
+
172
+ const EXT_BY_CONTENT_TYPE = new Map([
173
+ ["image/png", ".png"],
174
+ ["image/jpeg", ".jpg"],
175
+ ["image/gif", ".gif"],
176
+ ["image/webp", ".webp"],
177
+ ["image/svg+xml", ".svg"],
178
+ ["application/pdf", ".pdf"],
179
+ ["text/plain", ".txt"],
180
+ ["text/markdown", ".md"],
181
+ ["application/json", ".json"],
182
+ ["application/zip", ".zip"],
183
+ ]);
184
+
185
+ function getHeader(headers = {}, name) {
186
+ const target = String(name || "").toLowerCase();
187
+ for (const [key, value] of Object.entries(headers || {})) {
188
+ if (String(key).toLowerCase() === target) {
189
+ return value;
190
+ }
191
+ }
192
+ return undefined;
193
+ }
194
+
195
+ function contentTypeToExtension(contentType) {
196
+ const normalized = String(contentType || "").split(";")[0].trim().toLowerCase();
197
+ return EXT_BY_CONTENT_TYPE.get(normalized) || ".bin";
198
+ }
199
+
200
+ function parseContentDispositionFilename(value) {
201
+ const raw = String(value || "");
202
+ const encoded = raw.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
203
+ if (encoded) {
204
+ try {
205
+ return decodeURIComponent(encoded);
206
+ } catch {
207
+ return encoded;
208
+ }
209
+ }
210
+ return raw.match(/filename="?([^";]+)"?/i)?.[1] || "";
211
+ }
212
+
213
+ function extractAttachmentId(value) {
214
+ const raw = String(value || "").trim();
215
+ if (!raw) {
216
+ return "";
217
+ }
218
+ if (/^[0-9a-fA-F-]{36}$/.test(raw)) {
219
+ return raw.toLowerCase();
220
+ }
221
+
222
+ try {
223
+ const parsed = new URL(raw, "https://outline.local");
224
+ const id = parsed.searchParams.get("id");
225
+ return id && /^[0-9a-fA-F-]{36}$/.test(id) ? id.toLowerCase() : "";
226
+ } catch {
227
+ const match = raw.match(/\bid=([0-9a-fA-F-]{36})\b/);
228
+ return match ? match[1].toLowerCase() : "";
229
+ }
230
+ }
231
+
232
+ function extractDocumentUrlId(value) {
233
+ const raw = String(value || "").trim();
234
+ if (!raw) {
235
+ return "";
236
+ }
237
+
238
+ try {
239
+ const parsed = new URL(raw);
240
+ const last = parsed.pathname.split("/").filter(Boolean).pop() || "";
241
+ return last.match(/-([A-Za-z0-9]{8,})$/)?.[1] || "";
242
+ } catch {
243
+ return raw.match(/-([A-Za-z0-9]{8,})$/)?.[1] || "";
244
+ }
245
+ }
246
+
247
+ function extractAttachmentRefsFromText(text, baseUrl = "") {
248
+ const refs = [];
249
+ const seen = new Set();
250
+ const source = String(text || "");
251
+ const base = String(baseUrl || "").replace(/\/+$/, "");
252
+ const pattern = new RegExp(ATTACHMENT_REDIRECT_PATTERN.source, "g");
253
+ let match;
254
+
255
+ while ((match = pattern.exec(source)) !== null) {
256
+ const id = extractAttachmentId(match[1]);
257
+ if (!id || seen.has(id)) {
258
+ continue;
259
+ }
260
+ seen.add(id);
261
+ const url = match[1];
262
+ refs.push({
263
+ id,
264
+ index: refs.length,
265
+ source: "markdown",
266
+ url,
267
+ absoluteUrl: url.startsWith("http") || !base ? url : `${base}${url}`,
268
+ position: match.index,
269
+ });
270
+ }
271
+
272
+ return refs;
273
+ }
274
+
275
+ async function readDocumentForAttachments(ctx, args = {}) {
276
+ const urlId = args.urlId || extractDocumentUrlId(args.url);
277
+ const id = args.id || args.documentId || urlId;
278
+ const shareId = args.shareId;
279
+ const refArgs = compactValue({
280
+ refs: args.refs,
281
+ queries: args.queries || (args.query ? [args.query] : undefined),
282
+ shareIds: shareId ? [shareId] : undefined,
283
+ urlIds: args.urlId ? [args.urlId] : undefined,
284
+ urls: args.url && !urlId ? [args.url] : undefined,
285
+ profile: args.profile,
286
+ limit: args.resolveLimit,
287
+ minScore: args.minScore,
288
+ maxAgeHours: args.maxAgeHours,
289
+ refresh: args.refresh,
290
+ strict: args.strict,
291
+ strictThreshold: args.strictThreshold,
292
+ fallbackSearch: args.fallbackSearch,
293
+ fallbackMinScore: args.fallbackMinScore,
294
+ fallbackLimit: args.fallbackLimit,
295
+ fallbackMode: args.fallbackMode,
296
+ collectionId: args.resolveCollectionId,
297
+ view: "full",
298
+ concurrency: args.resolveConcurrency,
299
+ hydrateConcurrency: args.resolveHydrateConcurrency,
300
+ maxAttempts: args.maxAttempts,
301
+ }) || {};
302
+
303
+ if (!id && !shareId && (refArgs.refs || refArgs.queries || refArgs.urlIds || refArgs.urls)) {
304
+ const opened = await documentsOpenBatchTool(ctx, refArgs);
305
+ const item = (opened.result?.items || []).find((row) => row?.ok && row.document?.id)
306
+ || (opened.result?.items || [])[0]
307
+ || null;
308
+ if (item?.ok && item.document) {
309
+ return {
310
+ document: item.document,
311
+ resolution: {
312
+ mode: item.mode,
313
+ index: item.index,
314
+ kind: item.kind,
315
+ value: item.value,
316
+ id: item.document.id,
317
+ title: item.document.title,
318
+ candidate: item.candidate,
319
+ memory: item.memory || opened.result?.memory || null,
320
+ },
321
+ };
322
+ }
323
+ return {
324
+ document: null,
325
+ resolution: {
326
+ failed: item
327
+ ? {
328
+ index: item.index,
329
+ kind: item.kind,
330
+ value: item.value,
331
+ status: item.status || "not_found",
332
+ candidate: item.candidate,
333
+ candidates: item.candidates,
334
+ error: item.error,
335
+ }
336
+ : { status: "not_found" },
337
+ memory: item?.memory || opened.result?.memory || null,
338
+ },
339
+ };
340
+ }
341
+
342
+ if (!id && !shareId) {
343
+ throw new CliError("document attachment tools require args.id, args.documentId, args.url, args.shareId, or document refs");
344
+ }
345
+
346
+ const body = compactValue({ id, shareId }) || {};
347
+ const res = await ctx.client.call("documents.info", body, {
348
+ maxAttempts: toInteger(args.maxAttempts, 2),
349
+ });
350
+ const doc = res.body?.data || null;
351
+ if (!doc) {
352
+ throw new CliError("documents.info response did not include document data");
353
+ }
354
+ return {
355
+ document: doc,
356
+ resolution: {
357
+ mode: "direct",
358
+ id: doc?.id || id || "",
359
+ shareId: shareId || "",
360
+ urlId: urlId || "",
361
+ memory: null,
362
+ },
363
+ };
364
+ }
365
+
366
+ function summarizeAttachmentDocument(doc) {
367
+ return {
368
+ id: doc?.id,
369
+ title: doc?.title,
370
+ url: doc?.url,
371
+ urlId: doc?.urlId,
372
+ collectionId: doc?.collectionId,
373
+ parentDocumentId: doc?.parentDocumentId,
374
+ revision: doc?.revision,
375
+ updatedAt: doc?.updatedAt,
376
+ };
377
+ }
378
+
379
+ function resolveAttachmentOutputPath(args, id, headers, index = null) {
380
+ if (args.filePath) {
381
+ return path.resolve(String(args.filePath));
382
+ }
383
+
384
+ const contentType = getHeader(headers, "content-type");
385
+ const dispositionName = parseContentDispositionFilename(getHeader(headers, "content-disposition"));
386
+ const requestedName = typeof args.fileName === "string" ? args.fileName.trim() : "";
387
+ const baseName = requestedName || dispositionName;
388
+ const ext = path.extname(baseName) || contentTypeToExtension(contentType);
389
+ const prefix = index === null ? "" : `${String(index + 1).padStart(2, "0")}-`;
390
+ const fallbackName = `${prefix}${id}${ext}`;
391
+ const safeName = sanitizeFileToken(baseName ? `${prefix}${baseName}` : fallbackName);
392
+ const outputDir = path.resolve(String(args.outputDir || path.join(defaultTmpDir(), "attachments")));
393
+
394
+ return path.join(outputDir, safeName);
395
+ }
396
+
397
+ async function writeAttachmentFile(filePath, buffer, overwrite) {
398
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
399
+ try {
400
+ await fs.writeFile(filePath, buffer, { flag: overwrite ? "w" : "wx" });
401
+ } catch (err) {
402
+ if (err?.code === "EEXIST") {
403
+ throw new CliError(`Attachment file already exists: ${filePath}`, {
404
+ code: "ATTACHMENT_FILE_EXISTS",
405
+ filePath,
406
+ });
407
+ }
408
+ throw err;
409
+ }
410
+ }
411
+
412
+ async function downloadAttachmentToFile(ctx, args = {}, id, index = null) {
413
+ if (!ctx.client || typeof ctx.client.download !== "function") {
414
+ throw new CliError("Current Outline client does not support binary downloads");
415
+ }
416
+
417
+ const res = await ctx.client.download("attachments.redirect", { id }, {
418
+ maxAttempts: toInteger(args.maxAttempts, 2),
419
+ });
420
+ const buffer = res.body;
421
+ const filePath = resolveAttachmentOutputPath(args, id, res.headers, index);
422
+ await writeAttachmentFile(filePath, buffer, args.overwrite === true);
423
+
424
+ const contentType = getHeader(res.headers, "content-type") || "application/octet-stream";
425
+ return {
426
+ id,
427
+ ok: true,
428
+ filePath,
429
+ bytes: buffer.length,
430
+ sha256: createHash("sha256").update(buffer).digest("hex"),
431
+ contentType,
432
+ status: res.status,
433
+ sourceUrl: res.url,
434
+ };
435
+ }
436
+
56
437
  function defaultUsageArgs(def) {
438
+ const resolveConfig = normalizeResolveAccessConfig(def.resolveAccess);
439
+ const entityConfig = normalizeResolveEntityConfig(def.resolveEntity);
440
+ const principalConfig = normalizeResolveEntityConfig(def.resolvePrincipal);
441
+ if (principalConfig) {
442
+ const principalKey = principalConfig.queryKeys?.[0] || `${principalConfig.type}Query`;
443
+ const principalValue = principalConfig.type === "group" ? "Engineering" : "Alice Example";
444
+ if (resolveConfig?.kind === "document") {
445
+ return {
446
+ [resolveConfig.queryKeys?.includes("query") ? "query" : "documentQuery"]: "incident runbook",
447
+ [principalKey]: principalValue,
448
+ ...(def.mutating ? { performAction: true } : {}),
449
+ };
450
+ }
451
+ if (resolveConfig?.kind === "collection") {
452
+ const collectionQueryKey = resolveConfig.queryKeys?.includes("query") ? "query" : "collectionQuery";
453
+ return {
454
+ [collectionQueryKey]: "engineering",
455
+ [principalKey]: principalValue,
456
+ ...(def.mutating ? { performAction: true } : {}),
457
+ };
458
+ }
459
+ if (entityConfig?.type === "group") {
460
+ return {
461
+ [entityConfig.queryKeys?.[0] || "groupQuery"]: "Engineering",
462
+ [principalKey]: principalValue,
463
+ ...(def.mutating ? { performAction: true } : {}),
464
+ };
465
+ }
466
+ }
467
+ if (entityConfig?.type === "user") {
468
+ return {
469
+ query: "Alice Example",
470
+ };
471
+ }
472
+ if (entityConfig?.type === "group") {
473
+ return {
474
+ query: "Engineering",
475
+ limit: 20,
476
+ };
477
+ }
478
+ if (entityConfig?.type === "template") {
479
+ return {
480
+ [entityConfig.queryKeys?.[0] || "templateQuery"]: "incident postmortem",
481
+ limit: 20,
482
+ };
483
+ }
484
+ if (resolveConfig?.kind === "document") {
485
+ return {
486
+ [resolveConfig.queryKeys?.includes("query") ? "query" : "documentQuery"]: "incident runbook",
487
+ limit: 20,
488
+ };
489
+ }
490
+ if (resolveConfig?.kind === "collection") {
491
+ const collectionQueryKey = resolveConfig.queryKeys?.includes("query") ? "query" : "collectionQuery";
492
+ return {
493
+ [collectionQueryKey]: "engineering",
494
+ limit: 20,
495
+ };
496
+ }
57
497
  if (def.tool === "documents.empty_trash") {
58
498
  return def.mutating ? { performAction: true } : {};
59
499
  }
@@ -73,7 +513,7 @@ function defaultUsageArgs(def) {
73
513
  }
74
514
  if (def.tool === "shares.create") {
75
515
  return {
76
- documentId: "document-id",
516
+ documentQuery: "incident runbook",
77
517
  performAction: true,
78
518
  };
79
519
  }
@@ -159,6 +599,410 @@ function defaultUsageArgs(def) {
159
599
  };
160
600
  }
161
601
 
602
+ function nonEmptyString(value) {
603
+ const text = String(value || "").trim();
604
+ return text || "";
605
+ }
606
+
607
+ function hasAccessRefInput(args = {}, kind) {
608
+ if (nonEmptyString(args.query) || nonEmptyString(args.documentQuery) || nonEmptyString(args.urlId) || nonEmptyString(args.url)) {
609
+ return true;
610
+ }
611
+ if (kind === "document" && nonEmptyString(args.shareId)) {
612
+ return true;
613
+ }
614
+ return ["refs", "queries", "documentQueries", "urlIds", "urls", ...(kind === "document" ? ["shareIds"] : [])]
615
+ .some((key) => Array.isArray(args[key]) && args[key].some((item) => nonEmptyString(item)));
616
+ }
617
+
618
+ function normalizeResolveAccessConfig(input) {
619
+ if (!input) {
620
+ return null;
621
+ }
622
+ if (typeof input === "string") {
623
+ const aliasKey = input === "collection" ? "collectionId" : "documentId";
624
+ const queryKeys = input === "document" ? ["query", "documentQuery"] : ["query"];
625
+ const arrayQueryKeys = input === "document" ? ["queries", "documentQueries"] : ["queries"];
626
+ return {
627
+ kind: input,
628
+ outputField: "id",
629
+ resultField: aliasKey,
630
+ exactKeys: ["id", aliasKey],
631
+ required: true,
632
+ queryKeys,
633
+ arrayQueryKeys,
634
+ omitKeys: ACCESS_RESOLVE_ARG_KEYS,
635
+ };
636
+ }
637
+ const kind = input.kind || "document";
638
+ const aliasKey = kind === "collection" ? "collectionId" : "documentId";
639
+ const queryKeys = input.queryKeys || ["query"];
640
+ const arrayQueryKeys = input.arrayQueryKeys || ["queries"];
641
+ const outputField = input.outputField || "id";
642
+ const resultField = input.resultField || aliasKey;
643
+ const omitKeys = new Set([
644
+ ...ACCESS_RESOLVE_ARG_KEYS,
645
+ ...queryKeys,
646
+ ...arrayQueryKeys,
647
+ ...(input.omitKeys || []),
648
+ ]);
649
+ if (input.preserveQuery === true) {
650
+ omitKeys.delete("query");
651
+ omitKeys.delete("queries");
652
+ }
653
+ omitKeys.delete(outputField);
654
+ return {
655
+ kind,
656
+ outputField,
657
+ resultField,
658
+ exactKeys: input.exactKeys || ["id", aliasKey],
659
+ required: input.required !== false,
660
+ queryKeys,
661
+ arrayQueryKeys,
662
+ omitKeys: [...omitKeys],
663
+ };
664
+ }
665
+
666
+ function collectResolveQueries(args, config) {
667
+ const queries = [];
668
+ for (const key of config.queryKeys || []) {
669
+ const value = nonEmptyString(args[key]);
670
+ if (value) {
671
+ queries.push(value);
672
+ }
673
+ }
674
+ for (const key of config.arrayQueryKeys || []) {
675
+ if (!Array.isArray(args[key])) {
676
+ continue;
677
+ }
678
+ for (const value of args[key]) {
679
+ const text = nonEmptyString(value);
680
+ if (text) {
681
+ queries.push(text);
682
+ }
683
+ }
684
+ }
685
+ return queries;
686
+ }
687
+
688
+ function firstEntityReference(args = {}, config = {}) {
689
+ for (const key of config.queryKeys || ["query", "ref"]) {
690
+ const value = nonEmptyString(args[key]);
691
+ if (value) {
692
+ return {
693
+ key,
694
+ value,
695
+ };
696
+ }
697
+ }
698
+ for (const key of config.arrayQueryKeys || ["refs", "queries"]) {
699
+ if (!Array.isArray(args[key])) {
700
+ continue;
701
+ }
702
+ for (const item of args[key]) {
703
+ const value = nonEmptyString(item);
704
+ if (value) {
705
+ return {
706
+ key,
707
+ value,
708
+ };
709
+ }
710
+ }
711
+ }
712
+ return null;
713
+ }
714
+
715
+ function normalizeResolveEntityConfig(input) {
716
+ if (!input) {
717
+ return null;
718
+ }
719
+ const type = typeof input === "string" ? input : input.type;
720
+ if (!type) {
721
+ return null;
722
+ }
723
+ const queryKeys = input.queryKeys || ["query", "ref"];
724
+ const arrayQueryKeys = input.arrayQueryKeys || ["refs", "queries"];
725
+ const outputField = input.outputField || "id";
726
+ const resultField = input.resultField || `${type}Id`;
727
+ return {
728
+ type,
729
+ outputField,
730
+ resultField,
731
+ exactKeys: input.exactKeys || ["id"],
732
+ passthroughKeys: input.passthroughKeys || [],
733
+ queryKeys,
734
+ arrayQueryKeys,
735
+ omitKeys: [...new Set([...ENTITY_RESOLVE_ARG_KEYS, ...queryKeys, ...arrayQueryKeys, ...(input.omitKeys || [])])],
736
+ strictThreshold: input.strictThreshold,
737
+ };
738
+ }
739
+
740
+ function resolutionFromEntityCandidate(resolved, ref, config) {
741
+ const candidates = resolved.result?.candidates || [];
742
+ const topCandidate = candidates[0] || null;
743
+ const strict = ref.strict !== false;
744
+ const strictThreshold = Math.max(0, toInteger(ref.strictThreshold ?? config.strictThreshold, 85));
745
+ const topScore = Number(topCandidate?.score || 0);
746
+
747
+ if (!topCandidate) {
748
+ return {
749
+ error: {
750
+ failed: {
751
+ kind: ref.key,
752
+ value: ref.value,
753
+ status: "not_found",
754
+ },
755
+ memory: resolved.result?.memory || null,
756
+ },
757
+ };
758
+ }
759
+ if (strict && topScore < strictThreshold) {
760
+ return {
761
+ error: {
762
+ failed: {
763
+ kind: ref.key,
764
+ value: ref.value,
765
+ status: "low_confidence",
766
+ strictThreshold,
767
+ },
768
+ candidate: topCandidate,
769
+ candidates,
770
+ memory: resolved.result?.memory || null,
771
+ },
772
+ };
773
+ }
774
+
775
+ const live = (resolved.result?.live || []).find((item) => item?.ok && item.candidate?.id === topCandidate.id)
776
+ || (resolved.result?.live || [])[0]
777
+ || null;
778
+ if (live && !live.ok) {
779
+ return {
780
+ error: {
781
+ failed: {
782
+ kind: ref.key,
783
+ value: ref.value,
784
+ status: "hydrate_failed",
785
+ error: live.error,
786
+ statusCode: live.status,
787
+ },
788
+ candidate: topCandidate,
789
+ memory: resolved.result?.memory || live.memory || null,
790
+ },
791
+ };
792
+ }
793
+
794
+ return {
795
+ id: topCandidate.id,
796
+ resolution: compactValue({
797
+ mode: "memory",
798
+ kind: ref.key,
799
+ value: ref.value,
800
+ id: topCandidate.id,
801
+ name: topCandidate.name,
802
+ email: topCandidate.email,
803
+ candidate: topCandidate,
804
+ live,
805
+ memory: resolved.result?.memory || null,
806
+ }) || { id: topCandidate.id },
807
+ };
808
+ }
809
+
810
+ async function resolveEntityId(ctx, args = {}, input) {
811
+ const config = normalizeResolveEntityConfig(input);
812
+ if (!config) {
813
+ return null;
814
+ }
815
+ const exact = (config.exactKeys || [])
816
+ .map((key) => ({ key, value: nonEmptyString(args[key]) }))
817
+ .find((item) => item.value);
818
+ if (exact?.value) {
819
+ if (exact.key !== config.outputField) {
820
+ return {
821
+ id: exact.value,
822
+ resolution: null,
823
+ outputField: config.outputField,
824
+ resultField: config.resultField,
825
+ omitKeys: config.omitKeys,
826
+ };
827
+ }
828
+ return null;
829
+ }
830
+ if ((config.passthroughKeys || []).some((key) => nonEmptyString(args[key]) || (Array.isArray(args[key]) && args[key].length > 0))) {
831
+ return null;
832
+ }
833
+
834
+ const ref = firstEntityReference(args, config);
835
+ if (!ref) {
836
+ return null;
837
+ }
838
+
839
+ const resolved = await memoryResolveTool(ctx, {
840
+ query: ref.value,
841
+ type: config.type,
842
+ profile: args.profile,
843
+ limit: Math.max(1, toInteger(args.resolveLimit, 5)),
844
+ hydrateLimit: 1,
845
+ maxAgeHours: args.maxAgeHours,
846
+ minScore: args.minScore === undefined && args.strict !== false
847
+ ? Math.max(0, toInteger(args.strictThreshold ?? config.strictThreshold, 85))
848
+ : args.minScore,
849
+ strict: args.strict,
850
+ strictThreshold: args.strictThreshold,
851
+ fallbackSearch: args.fallbackSearch,
852
+ fallbackMinScore: args.fallbackMinScore === undefined && args.strict !== false
853
+ ? Math.max(0, toInteger(args.strictThreshold ?? config.strictThreshold, 85))
854
+ : args.fallbackMinScore,
855
+ fallbackLimit: args.fallbackLimit,
856
+ refresh: args.refresh !== false,
857
+ });
858
+ return {
859
+ ...resolutionFromEntityCandidate(resolved, { ...ref, strict: args.strict, strictThreshold: args.strictThreshold }, config),
860
+ outputField: config.outputField,
861
+ resultField: config.resultField,
862
+ omitKeys: config.omitKeys,
863
+ };
864
+ }
865
+
866
+ function successfulResolutions(resolutions) {
867
+ return resolutions.filter((item) => item?.id);
868
+ }
869
+
870
+ function combinedResolutionPayload(resolutions) {
871
+ const resolved = successfulResolutions(resolutions).filter((item) => item.resolution);
872
+ if (resolved.length === 0) {
873
+ return null;
874
+ }
875
+ if (resolved.length === 1) {
876
+ return resolved[0].resolution;
877
+ }
878
+ const byField = {};
879
+ for (const item of resolved) {
880
+ byField[item.resultField || item.outputField || "id"] = item.resolution;
881
+ }
882
+ return compactValue(byField);
883
+ }
884
+
885
+ function hasConfiguredAccessRefInput(args = {}, config) {
886
+ if (collectResolveQueries(args, config).length > 0) {
887
+ return true;
888
+ }
889
+ if (nonEmptyString(args.urlId) || nonEmptyString(args.url)) {
890
+ return true;
891
+ }
892
+ if (config.kind === "document" && nonEmptyString(args.shareId)) {
893
+ return true;
894
+ }
895
+ return ["refs", "urlIds", "urls", ...(config.kind === "document" ? ["shareIds"] : [])]
896
+ .some((key) => Array.isArray(args[key]) && args[key].some((item) => nonEmptyString(item)));
897
+ }
898
+
899
+ function resolutionFromAccessOpenItem(item, opened, kind) {
900
+ const entity = kind === "collection" ? item?.collection : item?.document;
901
+ if (!item?.ok || !entity?.id) {
902
+ return {
903
+ error: {
904
+ failed: item
905
+ ? {
906
+ index: item.index,
907
+ kind: item.kind,
908
+ value: item.value,
909
+ status: item.status || "not_found",
910
+ error: item.error,
911
+ }
912
+ : {
913
+ status: "not_found",
914
+ },
915
+ memory: opened.result?.memory || item?.memory || null,
916
+ },
917
+ };
918
+ }
919
+
920
+ return {
921
+ id: entity.id,
922
+ resolution: compactValue({
923
+ mode: item.mode,
924
+ index: item.index,
925
+ kind: item.kind,
926
+ value: item.value,
927
+ id: entity.id,
928
+ title: entity.title,
929
+ name: entity.name,
930
+ candidate: item.candidate,
931
+ memory: item.memory || opened.result?.memory || null,
932
+ }) || { id: entity.id },
933
+ };
934
+ }
935
+
936
+ async function resolveAccessId(ctx, args = {}, input) {
937
+ const config = normalizeResolveAccessConfig(input);
938
+ const aliasKey = config.kind === "collection" ? "collectionId" : "documentId";
939
+ const exactId = (config.exactKeys || []).map((key) => nonEmptyString(args[key])).find(Boolean) || "";
940
+ if (exactId) {
941
+ return {
942
+ id: exactId,
943
+ resolution: null,
944
+ outputField: config.outputField,
945
+ resultField: config.resultField,
946
+ omitKeys: config.omitKeys,
947
+ };
948
+ }
949
+ if (!hasConfiguredAccessRefInput(args, config)) {
950
+ return config.required ? {
951
+ error: {
952
+ failed: {
953
+ status: "missing_selector",
954
+ message: `requires ${config.exactKeys.map((key) => `args.${key}`).join(", ")} or a resolvable reference`,
955
+ },
956
+ },
957
+ outputField: config.outputField,
958
+ resultField: config.resultField,
959
+ omitKeys: config.omitKeys,
960
+ } : null;
961
+ }
962
+
963
+ const queries = collectResolveQueries(args, config);
964
+ const openArgs = compactValue({
965
+ refs: args.refs,
966
+ queries: queries.length > 0 ? queries : undefined,
967
+ shareIds: config.kind === "document"
968
+ ? (args.shareIds || (args.shareId ? [args.shareId] : undefined))
969
+ : undefined,
970
+ urlIds: args.urlIds || (args.urlId ? [args.urlId] : undefined),
971
+ urls: args.urls || (args.url ? [args.url] : undefined),
972
+ profile: args.profile,
973
+ limit: args.resolveLimit,
974
+ minScore: args.minScore,
975
+ maxAgeHours: args.maxAgeHours,
976
+ refresh: args.refresh,
977
+ strict: args.strict,
978
+ strictThreshold: args.strictThreshold,
979
+ fallbackSearch: args.fallbackSearch,
980
+ fallbackMinScore: args.fallbackMinScore,
981
+ fallbackLimit: args.fallbackLimit,
982
+ fallbackMode: args.fallbackMode,
983
+ collectionId: config.kind === "document" ? args.resolveCollectionId : undefined,
984
+ snippetMinWords: args.snippetMinWords,
985
+ snippetMaxWords: args.snippetMaxWords,
986
+ view: "summary",
987
+ concurrency: args.resolveConcurrency,
988
+ hydrateConcurrency: args.resolveHydrateConcurrency,
989
+ maxAttempts: args.maxAttempts,
990
+ }) || {};
991
+
992
+ const opened = config.kind === "collection"
993
+ ? await collectionsOpenBatchTool(ctx, openArgs)
994
+ : await documentsOpenBatchTool(ctx, openArgs);
995
+ const item = (opened.result?.items || []).find((row) => row?.ok)
996
+ || (opened.result?.items || [])[0]
997
+ || null;
998
+ return {
999
+ ...resolutionFromAccessOpenItem(item, opened, config.kind),
1000
+ outputField: config.outputField,
1001
+ resultField: config.resultField,
1002
+ omitKeys: config.omitKeys,
1003
+ };
1004
+ }
1005
+
162
1006
  function makeRpcHandler(def) {
163
1007
  return async function rpcHandler(ctx, args = {}) {
164
1008
  if (def.mutating) {
@@ -169,7 +1013,50 @@ function makeRpcHandler(def) {
169
1013
  }
170
1014
 
171
1015
  const maxAttempts = toInteger(args.maxAttempts, def.mutating ? 1 : 2);
172
- const body = buildBody(args);
1016
+ const resolutions = [];
1017
+ if (def.resolveAccess) {
1018
+ resolutions.push(await resolveAccessId(ctx, args, def.resolveAccess));
1019
+ }
1020
+ if (def.resolveEntity) {
1021
+ resolutions.push(await resolveEntityId(ctx, args, def.resolveEntity));
1022
+ }
1023
+ if (def.resolvePrincipal) {
1024
+ resolutions.push(await resolveEntityId(ctx, args, def.resolvePrincipal));
1025
+ }
1026
+ const failedResolution = resolutions.find((item) => item?.error);
1027
+ if (failedResolution?.error) {
1028
+ const resultField = failedResolution.resultField || failedResolution.outputField || (def.resolveAccess === "collection" ? "collectionId" : "documentId");
1029
+ return {
1030
+ tool: def.tool,
1031
+ profile: ctx.profile.id,
1032
+ result: compactValue({
1033
+ ok: false,
1034
+ status: failedResolution.error.status || "not_found",
1035
+ [resultField]: "",
1036
+ resolution: failedResolution.error,
1037
+ data: [],
1038
+ }) || {},
1039
+ };
1040
+ }
1041
+
1042
+ const bodyArgs = { ...args };
1043
+ const omitKeys = [];
1044
+ const resolvedOutputFields = new Set();
1045
+ for (const item of successfulResolutions(resolutions)) {
1046
+ const outputField = item.outputField || "id";
1047
+ bodyArgs[outputField] = item.id;
1048
+ resolvedOutputFields.add(outputField);
1049
+ omitKeys.push(...(item.omitKeys || []));
1050
+ }
1051
+ const effectiveOmitKeys = omitKeys.filter((key) => !resolvedOutputFields.has(key));
1052
+ const body = buildBody(
1053
+ bodyArgs,
1054
+ effectiveOmitKeys.length > 0
1055
+ ? effectiveOmitKeys
1056
+ : def.resolveAccess
1057
+ ? normalizeResolveAccessConfig(def.resolveAccess).omitKeys
1058
+ : []
1059
+ );
173
1060
  let res;
174
1061
  try {
175
1062
  res = await ctx.client.call(def.method, body, { maxAttempts });
@@ -195,55 +1082,312 @@ function makeRpcHandler(def) {
195
1082
  }
196
1083
  }
197
1084
 
1085
+ const resolutionPayload = combinedResolutionPayload(resolutions);
1086
+ const resolvedIds = {};
1087
+ for (const item of successfulResolutions(resolutions)) {
1088
+ resolvedIds[item.resultField || item.outputField || "id"] = item.id;
1089
+ }
1090
+
198
1091
  return {
199
1092
  tool: def.tool,
200
1093
  profile: ctx.profile.id,
201
- result: maybeDropPolicies(res.body, !!args.includePolicies),
1094
+ result: resolutionPayload
1095
+ ? compactValue({
1096
+ ...maybeDropPolicies(res.body, !!args.includePolicies),
1097
+ ...resolvedIds,
1098
+ resolution: resolutionPayload,
1099
+ }) || {}
1100
+ : maybeDropPolicies(res.body, !!args.includePolicies),
202
1101
  };
203
1102
  };
204
1103
  }
205
1104
 
206
1105
  function makeRpcContract(def) {
1106
+ const resolveConfig = normalizeResolveAccessConfig(def.resolveAccess);
1107
+ const entityConfig = normalizeResolveEntityConfig(def.resolveEntity);
1108
+ const principalConfig = normalizeResolveEntityConfig(def.resolvePrincipal);
1109
+ const isAccessResolver = !!resolveConfig;
1110
+ const isEntityResolver = !!entityConfig;
1111
+ const hasPrincipalResolver = !!principalConfig;
1112
+ const targetIdArg = resolveConfig?.kind === "collection" ? "collectionId" : "documentId";
1113
+ const exactIdArg = resolveConfig?.exactKeys?.includes("id") ? "id?: string; " : "";
1114
+ const exactTargetText = resolveConfig?.exactKeys?.includes("id") ? `${targetIdArg}/id` : targetIdArg;
1115
+ const resolverQueryArg = resolveConfig?.queryKeys?.includes("query")
1116
+ ? "query"
1117
+ : resolveConfig?.kind === "collection"
1118
+ ? "collectionQuery"
1119
+ : "documentQuery";
1120
+ const entityQueryArg = entityConfig?.queryKeys?.[0] || "query";
1121
+ const entityExactArg = entityConfig?.exactKeys?.includes("id") ? "id?: string; " : "";
1122
+ const signature = def.signature || (hasPrincipalResolver
1123
+ ? `${def.tool}(args: { ${exactIdArg}${targetIdArg}?: string; ${resolverQueryArg}?: string; userId?: string; groupId?: string; userQuery?: string; groupQuery?: string; userRefs?: string[]; groupRefs?: string[]; includePolicies?: boolean; maxAttempts?: number${def.mutating ? "; performAction?: boolean" : ""} })`
1124
+ : isAccessResolver
1125
+ ? `${def.tool}(args: { ${exactIdArg}${targetIdArg}?: string; ${resolverQueryArg}?: string; refs?: string[]; urlId?: string; url?: string; limit?: number; offset?: number; includePolicies?: boolean; maxAttempts?: number })`
1126
+ : isEntityResolver
1127
+ ? `${def.tool}(args: { ${entityExactArg}${entityQueryArg}?: string; refs?: string[]; limit?: number; offset?: number; includePolicies?: boolean; maxAttempts?: number${def.mutating ? "; performAction?: boolean" : ""} })`
1128
+ : `${def.tool}(args?: { ...endpointArgs; includePolicies?: boolean; maxAttempts?: number${
1129
+ def.mutating ? "; performAction?: boolean" : ""
1130
+ } })`);
1131
+ const bestPractices = def.bestPractices || [
1132
+ hasPrincipalResolver
1133
+ ? `Pass exact IDs when known, or combine target refs with ${principalConfig.type}Query/${principalConfig.type}Refs to resolve remembered ${principalConfig.type}s first.`
1134
+ : isAccessResolver
1135
+ ? `Pass ${exactTargetText} for exact calls, or ${resolverQueryArg}/refs/url/urlId to resolve remembered targets first.`
1136
+ : isEntityResolver
1137
+ ? `Pass ${entityConfig.exactKeys?.includes("id") ? "id" : "exact IDs"} for exact calls, or ${entityQueryArg}/refs to resolve remembered ${entityConfig.type}s first.`
1138
+ : "Prefer minimal payloads to keep responses deterministic and token-efficient.",
1139
+ ...(def.mutating
1140
+ ? ["This tool is action-gated; set performAction=true only for explicitly confirmed mutations."]
1141
+ : ["Use includePolicies=true only when policy details are required."]),
1142
+ ];
207
1143
  return {
208
- signature: `${def.tool}(args?: { ...endpointArgs; includePolicies?: boolean; maxAttempts?: number${
209
- def.mutating ? "; performAction?: boolean" : ""
210
- } })`,
1144
+ signature,
211
1145
  description: def.description,
212
- usageExample: {
1146
+ usageExample: def.usageExample || {
213
1147
  tool: def.tool,
214
1148
  args: defaultUsageArgs(def),
215
1149
  },
216
- bestPractices: [
217
- "Prefer minimal payloads to keep responses deterministic and token-efficient.",
218
- ...(def.mutating
219
- ? ["This tool is action-gated; set performAction=true only for explicitly confirmed mutations."]
220
- : ["Use includePolicies=true only when policy details are required."]),
221
- ],
1150
+ bestPractices,
222
1151
  handler: makeRpcHandler(def),
223
1152
  };
224
1153
  }
225
1154
 
226
1155
  const RPC_WRAPPER_DEFS = [
227
- { tool: "shares.list", method: "shares.list", description: "List shares." },
228
- { tool: "shares.info", method: "shares.info", description: "Get share details." },
229
- { tool: "shares.create", method: "shares.create", description: "Create a share.", mutating: true },
1156
+ {
1157
+ tool: "shares.list",
1158
+ method: "shares.list",
1159
+ description: "List shares, optionally resolving a remembered document first.",
1160
+ resolveAccess: {
1161
+ kind: "document",
1162
+ outputField: "documentId",
1163
+ exactKeys: ["documentId"],
1164
+ required: false,
1165
+ queryKeys: ["documentQuery"],
1166
+ arrayQueryKeys: ["documentQueries"],
1167
+ preserveQuery: true,
1168
+ },
1169
+ },
1170
+ {
1171
+ tool: "shares.info",
1172
+ method: "shares.info",
1173
+ description: "Get share details by share ID, document ID, or remembered document reference.",
1174
+ resolveAccess: {
1175
+ kind: "document",
1176
+ outputField: "documentId",
1177
+ exactKeys: ["documentId"],
1178
+ required: false,
1179
+ queryKeys: ["query", "documentQuery"],
1180
+ arrayQueryKeys: ["queries", "documentQueries"],
1181
+ },
1182
+ },
1183
+ {
1184
+ tool: "shares.create",
1185
+ method: "shares.create",
1186
+ description: "Create a share for a document ID or remembered document reference.",
1187
+ signature:
1188
+ "shares.create(args: { documentId?: string; query?: string; documentQuery?: string; refs?: string[]; shareId?: string; urlId?: string; url?: string; includeChildDocuments?: boolean; published?: boolean; includePolicies?: boolean; view?: 'summary'|'full'; maxAttempts?: number; performAction?: boolean })",
1189
+ usageExample: {
1190
+ tool: "shares.create",
1191
+ args: {
1192
+ documentQuery: "public handbook",
1193
+ published: true,
1194
+ performAction: true,
1195
+ },
1196
+ },
1197
+ bestPractices: [
1198
+ "Pass documentQuery/refs/url/urlId when the user names a document but the exact ID is unknown.",
1199
+ "Use documentId for deterministic automation when already known.",
1200
+ "Confirm the target document before creating public share links in high-risk workspaces.",
1201
+ "This tool is action-gated; set performAction=true only for explicitly confirmed mutations.",
1202
+ ],
1203
+ mutating: true,
1204
+ resolveAccess: {
1205
+ kind: "document",
1206
+ outputField: "documentId",
1207
+ exactKeys: ["documentId"],
1208
+ required: true,
1209
+ queryKeys: ["query", "documentQuery", "documentRef", "shareId", "urlId", "url"],
1210
+ arrayQueryKeys: ["queries", "documentQueries", "documentRefs", "refs", "shareIds", "urlIds", "urls"],
1211
+ },
1212
+ },
230
1213
  { tool: "shares.update", method: "shares.update", description: "Update a share.", mutating: true },
231
1214
  { tool: "shares.revoke", method: "shares.revoke", description: "Revoke a share.", mutating: true },
232
- { tool: "templates.list", method: "templates.list", description: "List templates." },
233
- { tool: "templates.info", method: "templates.info", description: "Get template details." },
1215
+ {
1216
+ tool: "templates.list",
1217
+ method: "templates.list",
1218
+ description: "List templates, optionally resolving a remembered collection filter first.",
1219
+ resolveAccess: {
1220
+ kind: "collection",
1221
+ outputField: "collectionId",
1222
+ exactKeys: ["collectionId"],
1223
+ required: false,
1224
+ queryKeys: ["collectionQuery", "collectionRef"],
1225
+ arrayQueryKeys: ["collectionQueries", "collectionRefs"],
1226
+ },
1227
+ },
1228
+ {
1229
+ tool: "templates.info",
1230
+ method: "templates.info",
1231
+ description: "Get template details by ID or remembered template name.",
1232
+ resolveEntity: {
1233
+ type: "template",
1234
+ outputField: "id",
1235
+ resultField: "templateId",
1236
+ exactKeys: ["id"],
1237
+ queryKeys: ["templateQuery", "templateRef", "query"],
1238
+ arrayQueryKeys: ["templateQueries", "templateRefs", "refs", "queries"],
1239
+ },
1240
+ },
234
1241
  { tool: "templates.create", method: "templates.create", description: "Create a template.", mutating: true },
235
- { tool: "templates.update", method: "templates.update", description: "Update a template.", mutating: true },
236
- { tool: "templates.delete", method: "templates.delete", description: "Delete a template.", mutating: true },
237
- { tool: "templates.restore", method: "templates.restore", description: "Restore a template.", mutating: true },
238
- { tool: "templates.duplicate", method: "templates.duplicate", description: "Duplicate a template.", mutating: true },
1242
+ {
1243
+ tool: "templates.update",
1244
+ method: "templates.update",
1245
+ description: "Update a template by ID or remembered template name.",
1246
+ mutating: true,
1247
+ resolveEntity: {
1248
+ type: "template",
1249
+ outputField: "id",
1250
+ resultField: "templateId",
1251
+ exactKeys: ["id"],
1252
+ queryKeys: ["templateQuery", "templateRef"],
1253
+ arrayQueryKeys: ["templateQueries", "templateRefs", "refs"],
1254
+ },
1255
+ },
1256
+ {
1257
+ tool: "templates.delete",
1258
+ method: "templates.delete",
1259
+ description: "Delete a template by ID or remembered template name.",
1260
+ mutating: true,
1261
+ resolveEntity: {
1262
+ type: "template",
1263
+ outputField: "id",
1264
+ resultField: "templateId",
1265
+ exactKeys: ["id"],
1266
+ queryKeys: ["templateQuery", "templateRef"],
1267
+ arrayQueryKeys: ["templateQueries", "templateRefs", "refs"],
1268
+ },
1269
+ },
1270
+ {
1271
+ tool: "templates.restore",
1272
+ method: "templates.restore",
1273
+ description: "Restore a template by ID or remembered template name.",
1274
+ mutating: true,
1275
+ resolveEntity: {
1276
+ type: "template",
1277
+ outputField: "id",
1278
+ resultField: "templateId",
1279
+ exactKeys: ["id"],
1280
+ queryKeys: ["templateQuery", "templateRef"],
1281
+ arrayQueryKeys: ["templateQueries", "templateRefs", "refs"],
1282
+ },
1283
+ },
1284
+ {
1285
+ tool: "templates.duplicate",
1286
+ method: "templates.duplicate",
1287
+ description: "Duplicate a template by ID or remembered template name.",
1288
+ mutating: true,
1289
+ resolveEntity: {
1290
+ type: "template",
1291
+ outputField: "id",
1292
+ resultField: "templateId",
1293
+ exactKeys: ["id"],
1294
+ queryKeys: ["templateQuery", "templateRef"],
1295
+ arrayQueryKeys: ["templateQueries", "templateRefs", "refs"],
1296
+ },
1297
+ },
239
1298
  { tool: "documents.templatize", method: "documents.templatize", description: "Convert a document into a template.", mutating: true },
240
1299
  { tool: "documents.import", method: "documents.import", description: "Import a document from JSON payload.", mutating: true },
241
- { tool: "comments.list", method: "comments.list", description: "List comments." },
1300
+ {
1301
+ tool: "comments.list",
1302
+ method: "comments.list",
1303
+ description: "List comments, optionally resolving a remembered document first.",
1304
+ resolveAccess: {
1305
+ kind: "document",
1306
+ outputField: "documentId",
1307
+ exactKeys: ["documentId"],
1308
+ required: false,
1309
+ queryKeys: ["query", "documentQuery"],
1310
+ arrayQueryKeys: ["queries", "documentQueries"],
1311
+ },
1312
+ },
242
1313
  { tool: "comments.info", method: "comments.info", description: "Get comment details." },
243
- { tool: "comments.create", method: "comments.create", description: "Create a comment.", mutating: true },
1314
+ {
1315
+ tool: "comments.create",
1316
+ method: "comments.create",
1317
+ description: "Create a comment on a document ID or remembered document reference.",
1318
+ signature:
1319
+ "comments.create(args: { documentId?: string; query?: string; documentQuery?: string; refs?: string[]; shareId?: string; urlId?: string; url?: string; text?: string; data?: object; parentCommentId?: string; includePolicies?: boolean; view?: 'summary'|'full'; maxAttempts?: number; performAction?: boolean })",
1320
+ usageExample: {
1321
+ tool: "comments.create",
1322
+ args: {
1323
+ query: "incident runbook",
1324
+ text: "Looks good.",
1325
+ performAction: true,
1326
+ },
1327
+ },
1328
+ bestPractices: [
1329
+ "Pass query/refs/url/urlId when adding a comment to a remembered document without a separate lookup.",
1330
+ "Use parentCommentId for replies and text for simple comments.",
1331
+ "Inspect the returned documentId and resolution fields when the target was resolved from memory.",
1332
+ "This tool is action-gated; set performAction=true only for explicitly confirmed mutations.",
1333
+ ],
1334
+ mutating: true,
1335
+ resolveAccess: {
1336
+ kind: "document",
1337
+ outputField: "documentId",
1338
+ exactKeys: ["documentId"],
1339
+ required: true,
1340
+ queryKeys: ["query", "documentQuery", "documentRef", "shareId", "urlId", "url"],
1341
+ arrayQueryKeys: ["queries", "documentQueries", "documentRefs", "refs", "shareIds", "urlIds", "urls"],
1342
+ },
1343
+ },
244
1344
  { tool: "comments.update", method: "comments.update", description: "Update a comment.", mutating: true },
245
1345
  { tool: "comments.delete", method: "comments.delete", description: "Delete a comment.", mutating: true },
246
- { tool: "events.list", method: "events.list", description: "List workspace events." },
1346
+ {
1347
+ tool: "events.list",
1348
+ method: "events.list",
1349
+ description: "List workspace events, optionally resolving remembered document, collection, and actor filters first.",
1350
+ signature:
1351
+ "events.list(args?: { documentId?: string; documentQuery?: string; refs?: string[]; collectionId?: string; collectionQuery?: string; actorId?: string; userQuery?: string; name?: string; auditLog?: boolean; limit?: number; offset?: number; includePolicies?: boolean; maxAttempts?: number })",
1352
+ usageExample: {
1353
+ tool: "events.list",
1354
+ args: {
1355
+ documentQuery: "incident runbook",
1356
+ userQuery: "Alice Example",
1357
+ auditLog: true,
1358
+ limit: 20,
1359
+ },
1360
+ },
1361
+ bestPractices: [
1362
+ "Pass exact IDs when known, or use documentQuery/refs/url/urlId, collectionQuery/collectionRefs, and userQuery/userRefs to resolve remembered audit filters first.",
1363
+ "Use auditLog=true when you need audit-grade event context for a scoped document or actor.",
1364
+ "Keep limit small and paginate with offset for low-token history review.",
1365
+ ],
1366
+ resolveAccess: {
1367
+ kind: "document",
1368
+ outputField: "documentId",
1369
+ exactKeys: ["documentId"],
1370
+ required: false,
1371
+ queryKeys: ["documentQuery", "documentRef"],
1372
+ arrayQueryKeys: ["documentQueries", "documentRefs", "refs"],
1373
+ },
1374
+ resolveEntity: {
1375
+ type: "collection",
1376
+ outputField: "collectionId",
1377
+ resultField: "collectionId",
1378
+ exactKeys: ["collectionId"],
1379
+ queryKeys: ["collectionQuery", "collectionRef"],
1380
+ arrayQueryKeys: ["collectionQueries", "collectionRefs"],
1381
+ },
1382
+ resolvePrincipal: {
1383
+ type: "user",
1384
+ outputField: "actorId",
1385
+ resultField: "actorId",
1386
+ exactKeys: ["actorId"],
1387
+ queryKeys: ["userQuery", "userRef"],
1388
+ arrayQueryKeys: ["userQueries", "userRefs"],
1389
+ },
1390
+ },
247
1391
  { tool: "oauth_clients.list", method: "oauthClients.list", description: "List OAuth clients." },
248
1392
  { tool: "oauth_clients.info", method: "oauthClients.info", description: "Get OAuth client details." },
249
1393
  { tool: "oauth_clients.create", method: "oauthClients.create", description: "Create an OAuth client.", mutating: true },
@@ -284,8 +1428,32 @@ const RPC_WRAPPER_DEFS = [
284
1428
  { tool: "data_attributes.update", method: "dataAttributes.update", description: "Update a data attribute.", mutating: true },
285
1429
  { tool: "data_attributes.delete", method: "dataAttributes.delete", description: "Delete a data attribute.", mutating: true },
286
1430
  { tool: "revisions.info", method: "revisions.info", description: "Get revision details." },
287
- { tool: "documents.archived", method: "documents.archived", description: "List archived documents." },
288
- { tool: "documents.deleted", method: "documents.deleted", description: "List deleted documents." },
1431
+ {
1432
+ tool: "documents.archived",
1433
+ method: "documents.archived",
1434
+ description: "List archived documents, optionally resolving a remembered collection filter first.",
1435
+ resolveAccess: {
1436
+ kind: "collection",
1437
+ outputField: "collectionId",
1438
+ exactKeys: ["collectionId"],
1439
+ required: false,
1440
+ queryKeys: ["collectionQuery", "collectionRef"],
1441
+ arrayQueryKeys: ["collectionQueries", "collectionRefs"],
1442
+ },
1443
+ },
1444
+ {
1445
+ tool: "documents.deleted",
1446
+ method: "documents.deleted",
1447
+ description: "List deleted documents, optionally resolving a remembered collection filter first.",
1448
+ resolveAccess: {
1449
+ kind: "collection",
1450
+ outputField: "collectionId",
1451
+ exactKeys: ["collectionId"],
1452
+ required: false,
1453
+ queryKeys: ["collectionQuery", "collectionRef"],
1454
+ arrayQueryKeys: ["collectionQueries", "collectionRefs"],
1455
+ },
1456
+ },
289
1457
  { tool: "documents.archive", method: "documents.archive", description: "Archive a document.", mutating: true },
290
1458
  { tool: "documents.restore", method: "documents.restore", description: "Restore a document.", mutating: true },
291
1459
  {
@@ -301,7 +1469,16 @@ const RPC_WRAPPER_DEFS = [
301
1469
  { tool: "webhooks.update", method: "webhooks.update", description: "Update a webhook.", mutating: true },
302
1470
  { tool: "webhooks.delete", method: "webhooks.delete", description: "Delete a webhook.", mutating: true },
303
1471
  { tool: "users.list", method: "users.list", description: "List users." },
304
- { tool: "users.info", method: "users.info", description: "Get user details." },
1472
+ {
1473
+ tool: "users.info",
1474
+ method: "users.info",
1475
+ description: "Get user details by ID/email or remembered user reference.",
1476
+ resolveEntity: {
1477
+ type: "user",
1478
+ resultField: "userId",
1479
+ passthroughKeys: ["ids", "email"],
1480
+ },
1481
+ },
305
1482
  { tool: "users.invite", method: "users.invite", description: "Invite a user.", mutating: true },
306
1483
  {
307
1484
  tool: "users.update_role",
@@ -312,26 +1489,222 @@ const RPC_WRAPPER_DEFS = [
312
1489
  { tool: "users.activate", method: "users.activate", description: "Activate a user.", mutating: true },
313
1490
  { tool: "users.suspend", method: "users.suspend", description: "Suspend a user.", mutating: true },
314
1491
  { tool: "groups.list", method: "groups.list", description: "List groups." },
315
- { tool: "groups.info", method: "groups.info", description: "Get group details." },
316
- { tool: "groups.memberships", method: "groups.memberships", description: "List group user memberships." },
1492
+ {
1493
+ tool: "groups.info",
1494
+ method: "groups.info",
1495
+ description: "Get group details by ID or remembered group reference.",
1496
+ resolveEntity: {
1497
+ type: "group",
1498
+ resultField: "groupId",
1499
+ passthroughKeys: ["ids"],
1500
+ },
1501
+ },
1502
+ {
1503
+ tool: "groups.memberships",
1504
+ method: "groups.memberships",
1505
+ description: "Resolve a group and list group user memberships.",
1506
+ resolveEntity: {
1507
+ type: "group",
1508
+ resultField: "groupId",
1509
+ },
1510
+ },
317
1511
  { tool: "groups.create", method: "groups.create", description: "Create a group.", mutating: true },
318
1512
  { tool: "groups.update", method: "groups.update", description: "Update a group.", mutating: true },
319
1513
  { tool: "groups.delete", method: "groups.delete", description: "Delete a group.", mutating: true },
320
- { tool: "groups.add_user", method: "groups.add_user", description: "Add a user to a group.", mutating: true },
321
- { tool: "groups.remove_user", method: "groups.remove_user", description: "Remove a user from a group.", mutating: true },
322
- { tool: "collections.memberships", method: "collections.memberships", description: "List collection user memberships." },
323
- { tool: "collections.group_memberships", method: "collections.group_memberships", description: "List collection group memberships." },
324
- { tool: "collections.add_user", method: "collections.add_user", description: "Add a user to a collection.", mutating: true },
325
- { tool: "collections.remove_user", method: "collections.remove_user", description: "Remove a user from a collection.", mutating: true },
326
- { tool: "collections.add_group", method: "collections.add_group", description: "Add a group to a collection.", mutating: true },
327
- { tool: "collections.remove_group", method: "collections.remove_group", description: "Remove a group from a collection.", mutating: true },
328
- { tool: "documents.users", method: "documents.users", description: "List users with access to a document." },
329
- { tool: "documents.memberships", method: "documents.memberships", description: "List document user memberships." },
330
- { tool: "documents.group_memberships", method: "documents.group_memberships", description: "List document group memberships." },
331
- { tool: "documents.add_user", method: "documents.add_user", description: "Add a user to a document.", mutating: true },
332
- { tool: "documents.remove_user", method: "documents.remove_user", description: "Remove a user from a document.", mutating: true },
333
- { tool: "documents.add_group", method: "documents.add_group", description: "Add a group to a document.", mutating: true },
334
- { tool: "documents.remove_group", method: "documents.remove_group", description: "Remove a group from a document.", mutating: true },
1514
+ {
1515
+ tool: "groups.add_user",
1516
+ method: "groups.add_user",
1517
+ description: "Resolve a group and user before adding the user to the group.",
1518
+ mutating: true,
1519
+ resolveEntity: {
1520
+ type: "group",
1521
+ outputField: "id",
1522
+ resultField: "groupId",
1523
+ exactKeys: ["id", "groupId"],
1524
+ queryKeys: ["groupQuery", "groupRef"],
1525
+ arrayQueryKeys: ["groupQueries", "groupRefs"],
1526
+ },
1527
+ resolvePrincipal: {
1528
+ type: "user",
1529
+ outputField: "userId",
1530
+ resultField: "userId",
1531
+ exactKeys: ["userId"],
1532
+ queryKeys: ["userQuery", "userRef"],
1533
+ arrayQueryKeys: ["userQueries", "userRefs"],
1534
+ },
1535
+ },
1536
+ {
1537
+ tool: "groups.remove_user",
1538
+ method: "groups.remove_user",
1539
+ description: "Resolve a group and user before removing the user from the group.",
1540
+ mutating: true,
1541
+ resolveEntity: {
1542
+ type: "group",
1543
+ outputField: "id",
1544
+ resultField: "groupId",
1545
+ exactKeys: ["id", "groupId"],
1546
+ queryKeys: ["groupQuery", "groupRef"],
1547
+ arrayQueryKeys: ["groupQueries", "groupRefs"],
1548
+ },
1549
+ resolvePrincipal: {
1550
+ type: "user",
1551
+ outputField: "userId",
1552
+ resultField: "userId",
1553
+ exactKeys: ["userId"],
1554
+ queryKeys: ["userQuery", "userRef"],
1555
+ arrayQueryKeys: ["userQueries", "userRefs"],
1556
+ },
1557
+ },
1558
+ {
1559
+ tool: "collections.memberships",
1560
+ method: "collections.memberships",
1561
+ description: "Resolve a collection and list collection user memberships.",
1562
+ resolveAccess: "collection",
1563
+ },
1564
+ {
1565
+ tool: "collections.group_memberships",
1566
+ method: "collections.group_memberships",
1567
+ description: "Resolve a collection and list collection group memberships.",
1568
+ resolveAccess: "collection",
1569
+ },
1570
+ {
1571
+ tool: "collections.add_user",
1572
+ method: "collections.add_user",
1573
+ description: "Resolve a collection and user before adding collection access.",
1574
+ mutating: true,
1575
+ resolveAccess: "collection",
1576
+ resolvePrincipal: {
1577
+ type: "user",
1578
+ outputField: "userId",
1579
+ resultField: "userId",
1580
+ exactKeys: ["userId"],
1581
+ queryKeys: ["userQuery", "userRef"],
1582
+ arrayQueryKeys: ["userQueries", "userRefs"],
1583
+ },
1584
+ },
1585
+ {
1586
+ tool: "collections.remove_user",
1587
+ method: "collections.remove_user",
1588
+ description: "Resolve a collection and user before removing collection access.",
1589
+ mutating: true,
1590
+ resolveAccess: "collection",
1591
+ resolvePrincipal: {
1592
+ type: "user",
1593
+ outputField: "userId",
1594
+ resultField: "userId",
1595
+ exactKeys: ["userId"],
1596
+ queryKeys: ["userQuery", "userRef"],
1597
+ arrayQueryKeys: ["userQueries", "userRefs"],
1598
+ },
1599
+ },
1600
+ {
1601
+ tool: "collections.add_group",
1602
+ method: "collections.add_group",
1603
+ description: "Resolve a collection and group before adding group collection access.",
1604
+ mutating: true,
1605
+ resolveAccess: "collection",
1606
+ resolvePrincipal: {
1607
+ type: "group",
1608
+ outputField: "groupId",
1609
+ resultField: "groupId",
1610
+ exactKeys: ["groupId"],
1611
+ queryKeys: ["groupQuery", "groupRef"],
1612
+ arrayQueryKeys: ["groupQueries", "groupRefs"],
1613
+ },
1614
+ },
1615
+ {
1616
+ tool: "collections.remove_group",
1617
+ method: "collections.remove_group",
1618
+ description: "Resolve a collection and group before removing group collection access.",
1619
+ mutating: true,
1620
+ resolveAccess: "collection",
1621
+ resolvePrincipal: {
1622
+ type: "group",
1623
+ outputField: "groupId",
1624
+ resultField: "groupId",
1625
+ exactKeys: ["groupId"],
1626
+ queryKeys: ["groupQuery", "groupRef"],
1627
+ arrayQueryKeys: ["groupQueries", "groupRefs"],
1628
+ },
1629
+ },
1630
+ {
1631
+ tool: "documents.users",
1632
+ method: "documents.users",
1633
+ description: "Resolve a document and list users with access to it.",
1634
+ resolveAccess: "document",
1635
+ },
1636
+ {
1637
+ tool: "documents.memberships",
1638
+ method: "documents.memberships",
1639
+ description: "Resolve a document and list document user memberships.",
1640
+ resolveAccess: "document",
1641
+ },
1642
+ {
1643
+ tool: "documents.group_memberships",
1644
+ method: "documents.group_memberships",
1645
+ description: "Resolve a document and list document group memberships.",
1646
+ resolveAccess: "document",
1647
+ },
1648
+ {
1649
+ tool: "documents.add_user",
1650
+ method: "documents.add_user",
1651
+ description: "Resolve a document and user before adding document access.",
1652
+ mutating: true,
1653
+ resolveAccess: "document",
1654
+ resolvePrincipal: {
1655
+ type: "user",
1656
+ outputField: "userId",
1657
+ resultField: "userId",
1658
+ exactKeys: ["userId"],
1659
+ queryKeys: ["userQuery", "userRef"],
1660
+ arrayQueryKeys: ["userQueries", "userRefs"],
1661
+ },
1662
+ },
1663
+ {
1664
+ tool: "documents.remove_user",
1665
+ method: "documents.remove_user",
1666
+ description: "Resolve a document and user before removing document access.",
1667
+ mutating: true,
1668
+ resolveAccess: "document",
1669
+ resolvePrincipal: {
1670
+ type: "user",
1671
+ outputField: "userId",
1672
+ resultField: "userId",
1673
+ exactKeys: ["userId"],
1674
+ queryKeys: ["userQuery", "userRef"],
1675
+ arrayQueryKeys: ["userQueries", "userRefs"],
1676
+ },
1677
+ },
1678
+ {
1679
+ tool: "documents.add_group",
1680
+ method: "documents.add_group",
1681
+ description: "Resolve a document and group before adding group document access.",
1682
+ mutating: true,
1683
+ resolveAccess: "document",
1684
+ resolvePrincipal: {
1685
+ type: "group",
1686
+ outputField: "groupId",
1687
+ resultField: "groupId",
1688
+ exactKeys: ["groupId"],
1689
+ queryKeys: ["groupQuery", "groupRef"],
1690
+ arrayQueryKeys: ["groupQueries", "groupRefs"],
1691
+ },
1692
+ },
1693
+ {
1694
+ tool: "documents.remove_group",
1695
+ method: "documents.remove_group",
1696
+ description: "Resolve a document and group before removing group document access.",
1697
+ mutating: true,
1698
+ resolveAccess: "document",
1699
+ resolvePrincipal: {
1700
+ type: "group",
1701
+ outputField: "groupId",
1702
+ resultField: "groupId",
1703
+ exactKeys: ["groupId"],
1704
+ queryKeys: ["groupQuery", "groupRef"],
1705
+ arrayQueryKeys: ["groupQueries", "groupRefs"],
1706
+ },
1707
+ },
335
1708
  { tool: "file_operations.list", method: "fileOperations.list", description: "List file operations." },
336
1709
  { tool: "file_operations.info", method: "fileOperations.info", description: "Get file operation details." },
337
1710
  { tool: "file_operations.delete", method: "fileOperations.delete", description: "Delete a file operation.", mutating: true },
@@ -404,14 +1777,383 @@ function normalizeFallbackAnswerHit(row, contextChars = 220) {
404
1777
  });
405
1778
  }
406
1779
 
407
- async function buildAnswerFallbackResult(ctx, question, args = {}) {
1780
+ function firstAnswerReference(args = {}, keys = [], arrayKeys = []) {
1781
+ for (const key of keys) {
1782
+ const value = String(args[key] || "").trim();
1783
+ if (value) {
1784
+ return { key, value };
1785
+ }
1786
+ }
1787
+ for (const key of arrayKeys) {
1788
+ if (!Array.isArray(args[key])) {
1789
+ continue;
1790
+ }
1791
+ for (const item of args[key]) {
1792
+ const value = String(item || "").trim();
1793
+ if (value) {
1794
+ return { key, value };
1795
+ }
1796
+ }
1797
+ }
1798
+ return null;
1799
+ }
1800
+
1801
+ function answerResolutionFromMemoryCandidate(resolved, ref, config, args = {}) {
1802
+ const candidates = resolved.result?.candidates || [];
1803
+ const topCandidate = candidates[0] || null;
1804
+ const strict = args.strict !== false;
1805
+ const strictThreshold = Math.max(0, toInteger(args.strictThreshold, 85));
1806
+ const topScore = Number(topCandidate?.score || 0);
1807
+
1808
+ if (!topCandidate) {
1809
+ return {
1810
+ error: {
1811
+ failed: {
1812
+ kind: ref.key,
1813
+ value: ref.value,
1814
+ status: "not_found",
1815
+ },
1816
+ memory: resolved.result?.memory || null,
1817
+ },
1818
+ };
1819
+ }
1820
+ if (strict && topScore < strictThreshold) {
1821
+ return {
1822
+ error: {
1823
+ failed: {
1824
+ kind: ref.key,
1825
+ value: ref.value,
1826
+ status: "low_confidence",
1827
+ strictThreshold,
1828
+ },
1829
+ candidate: topCandidate,
1830
+ candidates,
1831
+ memory: resolved.result?.memory || null,
1832
+ },
1833
+ };
1834
+ }
1835
+
1836
+ const live = (resolved.result?.live || []).find((item) => item?.ok && item.candidate?.id === topCandidate.id)
1837
+ || (resolved.result?.live || [])[0]
1838
+ || null;
1839
+ if (live && !live.ok) {
1840
+ return {
1841
+ error: {
1842
+ failed: {
1843
+ kind: ref.key,
1844
+ value: ref.value,
1845
+ status: "hydrate_failed",
1846
+ error: live.error,
1847
+ statusCode: live.status,
1848
+ },
1849
+ candidate: topCandidate,
1850
+ memory: resolved.result?.memory || live.memory || null,
1851
+ },
1852
+ };
1853
+ }
1854
+
1855
+ return {
1856
+ id: topCandidate.id,
1857
+ resultField: config.resultField,
1858
+ resolution: compactValue({
1859
+ mode: "memory",
1860
+ kind: ref.key,
1861
+ value: ref.value,
1862
+ id: topCandidate.id,
1863
+ name: topCandidate.name,
1864
+ email: topCandidate.email,
1865
+ candidate: topCandidate,
1866
+ live,
1867
+ memory: resolved.result?.memory || null,
1868
+ }) || { id: topCandidate.id },
1869
+ };
1870
+ }
1871
+
1872
+ async function resolveAnswerEntityFilter(ctx, args = {}, config) {
1873
+ const exact = String(args[config.idKey] || "").trim();
1874
+ if (exact) {
1875
+ return { id: exact, resultField: config.resultField };
1876
+ }
1877
+ const ref = firstAnswerReference(args, config.queryKeys, config.arrayQueryKeys);
1878
+ if (!ref) {
1879
+ return null;
1880
+ }
1881
+
1882
+ const threshold = Math.max(0, toInteger(args.strictThreshold, 85));
1883
+ const resolved = await memoryResolveTool(ctx, {
1884
+ query: ref.value,
1885
+ type: config.type,
1886
+ profile: args.profile,
1887
+ limit: Math.max(1, toInteger(args.resolveLimit, 5)),
1888
+ hydrateLimit: 1,
1889
+ maxAgeHours: args.maxAgeHours,
1890
+ minScore: args.minScore === undefined && args.strict !== false ? threshold : args.minScore,
1891
+ strict: args.strict,
1892
+ strictThreshold: args.strictThreshold,
1893
+ fallbackSearch: args.fallbackSearch,
1894
+ fallbackMinScore: args.fallbackMinScore === undefined && args.strict !== false ? threshold : args.fallbackMinScore,
1895
+ fallbackLimit: args.fallbackLimit,
1896
+ refresh: args.refresh !== false,
1897
+ maxAttempts: args.maxAttempts,
1898
+ });
1899
+
1900
+ return {
1901
+ ...answerResolutionFromMemoryCandidate(resolved, ref, config, args),
1902
+ resultField: config.resultField,
1903
+ };
1904
+ }
1905
+
1906
+ async function resolveAnswerDocumentTarget(ctx, args = {}) {
1907
+ const exact = String(args.documentId || args.id || "").trim();
1908
+ if (exact) {
1909
+ return { id: exact, resultField: "documentId" };
1910
+ }
1911
+
1912
+ const ref = firstAnswerReference(
1913
+ args,
1914
+ ["documentQuery", "documentRef", "shareId", "urlId", "url"],
1915
+ ["documentQueries", "documentRefs", "refs", "shareIds", "urlIds", "urls"]
1916
+ );
1917
+ if (!ref) {
1918
+ return null;
1919
+ }
1920
+
1921
+ const opened = await documentsOpenBatchTool(ctx, compactValue({
1922
+ queries: ["documentQuery", "documentQueries"].includes(ref.key) ? [ref.value] : undefined,
1923
+ refs: ["documentRef", "documentRefs", "refs"].includes(ref.key) ? [ref.value] : undefined,
1924
+ shareIds: ["shareId", "shareIds"].includes(ref.key) ? [ref.value] : undefined,
1925
+ urlIds: ["urlId", "urlIds"].includes(ref.key) ? [ref.value] : undefined,
1926
+ urls: ["url", "urls"].includes(ref.key) ? [ref.value] : undefined,
1927
+ profile: args.profile,
1928
+ limit: args.resolveLimit,
1929
+ minScore: args.minScore,
1930
+ maxAgeHours: args.maxAgeHours,
1931
+ refresh: args.refresh,
1932
+ strict: args.strict,
1933
+ strictThreshold: args.strictThreshold,
1934
+ fallbackSearch: args.fallbackSearch,
1935
+ fallbackMinScore: args.fallbackMinScore,
1936
+ fallbackLimit: args.fallbackLimit,
1937
+ fallbackMode: args.fallbackMode,
1938
+ collectionId: args.resolveCollectionId || args.collectionId,
1939
+ view: "summary",
1940
+ concurrency: args.resolveConcurrency,
1941
+ hydrateConcurrency: args.resolveHydrateConcurrency,
1942
+ maxAttempts: args.maxAttempts,
1943
+ }) || {});
1944
+
1945
+ const item = opened.result?.items?.[0] || null;
1946
+ if (item?.ok && item.document?.id) {
1947
+ return {
1948
+ id: item.document.id,
1949
+ resultField: "documentId",
1950
+ document: item.document,
1951
+ resolution: compactValue({
1952
+ mode: item.mode || "memory",
1953
+ kind: ref.key,
1954
+ value: ref.value,
1955
+ id: item.document.id,
1956
+ title: item.document.title,
1957
+ candidate: item.candidate,
1958
+ memory: opened.result?.memory || null,
1959
+ }) || { id: item.document.id },
1960
+ };
1961
+ }
1962
+
1963
+ return {
1964
+ resultField: "documentId",
1965
+ error: compactValue({
1966
+ failed: {
1967
+ kind: ref.key,
1968
+ value: ref.value,
1969
+ status: item?.status || "not_found",
1970
+ error: item?.error,
1971
+ },
1972
+ candidate: item?.candidate,
1973
+ candidates: item?.candidates,
1974
+ memory: opened.result?.memory || null,
1975
+ }) || {
1976
+ failed: {
1977
+ kind: ref.key,
1978
+ value: ref.value,
1979
+ status: "not_found",
1980
+ },
1981
+ },
1982
+ };
1983
+ }
1984
+
1985
+ function hasAnswerScopeSelectors(args = {}) {
1986
+ return !!firstAnswerReference(
1987
+ args,
1988
+ [
1989
+ "id",
1990
+ "documentId",
1991
+ "documentQuery",
1992
+ "documentRef",
1993
+ "shareId",
1994
+ "urlId",
1995
+ "url",
1996
+ "collectionId",
1997
+ "collectionQuery",
1998
+ "collectionRef",
1999
+ "userId",
2000
+ "userQuery",
2001
+ "userRef",
2002
+ ],
2003
+ [
2004
+ "documentQueries",
2005
+ "documentRefs",
2006
+ "refs",
2007
+ "shareIds",
2008
+ "urlIds",
2009
+ "urls",
2010
+ "collectionQueries",
2011
+ "collectionRefs",
2012
+ "userQueries",
2013
+ "userRefs",
2014
+ ]
2015
+ );
2016
+ }
2017
+
2018
+ async function resolveAnswerScope(ctx, args = {}) {
2019
+ const collection = await resolveAnswerEntityFilter(ctx, args, {
2020
+ type: "collection",
2021
+ idKey: "collectionId",
2022
+ resultField: "collectionId",
2023
+ queryKeys: ["collectionQuery", "collectionRef"],
2024
+ arrayQueryKeys: ["collectionQueries", "collectionRefs"],
2025
+ });
2026
+ const user = await resolveAnswerEntityFilter(ctx, args, {
2027
+ type: "user",
2028
+ idKey: "userId",
2029
+ resultField: "userId",
2030
+ queryKeys: ["userQuery", "userRef"],
2031
+ arrayQueryKeys: ["userQueries", "userRefs"],
2032
+ });
2033
+ const preDocumentFilters = [collection, user].filter(Boolean);
2034
+ const failedFilter = preDocumentFilters.find((filter) => filter?.error);
2035
+ if (failedFilter) {
2036
+ return { error: failedFilter.error, resultField: failedFilter.resultField };
2037
+ }
2038
+
2039
+ const document = await resolveAnswerDocumentTarget(ctx, {
2040
+ ...args,
2041
+ collectionId: collection?.id || args.collectionId,
2042
+ });
2043
+
2044
+ const filters = [document, collection, user].filter(Boolean);
2045
+ const failed = filters.find((filter) => filter?.error);
2046
+ if (failed) {
2047
+ return { error: failed.error, resultField: failed.resultField };
2048
+ }
2049
+
2050
+ const resolution = {};
2051
+ for (const filter of filters) {
2052
+ if (filter.resolution) {
2053
+ resolution[filter.resultField] = filter.resolution;
2054
+ }
2055
+ }
2056
+
2057
+ return {
2058
+ args: compactValue({
2059
+ ...args,
2060
+ documentId: document?.id || args.documentId || args.id,
2061
+ collectionId: collection?.id || args.collectionId,
2062
+ userId: user?.id || args.userId,
2063
+ }) || {},
2064
+ document: document?.document || null,
2065
+ resolution: Object.keys(resolution).length > 0 ? resolution : null,
2066
+ };
2067
+ }
2068
+
2069
+ function buildAnswerEndpointBody(args = {}, question) {
2070
+ return {
2071
+ ...buildBody(args, ["question", "query", "limit", ...ANSWER_RESOLVE_ARG_KEYS]),
2072
+ query: question,
2073
+ };
2074
+ }
2075
+
2076
+ function buildAnswerResolutionMiss(tool, ctx, question, prepared) {
2077
+ return {
2078
+ tool,
2079
+ profile: ctx.profile.id,
2080
+ result: compactValue({
2081
+ ok: false,
2082
+ status: prepared.error?.failed?.status || "not_found",
2083
+ [prepared.resultField || "filterId"]: "",
2084
+ question,
2085
+ resolution: prepared.error,
2086
+ documents: [],
2087
+ }) || {},
2088
+ };
2089
+ }
2090
+
2091
+ async function buildAnswerFallbackResult(ctx, question, args = {}, prepared = {}) {
408
2092
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 2));
409
2093
  const contextChars = Math.max(80, toInteger(args.contextChars, 220));
410
2094
  const limit = Math.max(1, Math.min(8, toInteger(args.limit, 5)));
2095
+ const scopedDocumentId = args.documentId || args.id;
2096
+
2097
+ if (scopedDocumentId) {
2098
+ if (prepared.document?.id === scopedDocumentId) {
2099
+ const document = normalizeFallbackAnswerHit(prepared.document, contextChars);
2100
+ return {
2101
+ question,
2102
+ answer: "",
2103
+ noAnswerReason: "documents.answerQuestion is unsupported by this Outline deployment; returning the scoped document as retrieval evidence instead.",
2104
+ unsupported: true,
2105
+ fallbackUsed: true,
2106
+ fallbackTool: "documents.info",
2107
+ fallbackSuggestion: {
2108
+ tool: "documents.info",
2109
+ args: compactValue({
2110
+ id: scopedDocumentId,
2111
+ view: "summary",
2112
+ }),
2113
+ },
2114
+ resolution: prepared.resolution,
2115
+ documents: document ? [document] : [],
2116
+ retrieval: {
2117
+ query: question,
2118
+ result: {
2119
+ ok: true,
2120
+ data: document,
2121
+ },
2122
+ },
2123
+ };
2124
+ }
2125
+
2126
+ const res = await ctx.client.call("documents.info", { id: scopedDocumentId }, { maxAttempts });
2127
+ const document = normalizeFallbackAnswerHit(res.body?.data, contextChars);
2128
+ return {
2129
+ question,
2130
+ answer: "",
2131
+ noAnswerReason: "documents.answerQuestion is unsupported by this Outline deployment; returning the scoped document as retrieval evidence instead.",
2132
+ unsupported: true,
2133
+ fallbackUsed: true,
2134
+ fallbackTool: "documents.info",
2135
+ fallbackSuggestion: {
2136
+ tool: "documents.info",
2137
+ args: compactValue({
2138
+ id: scopedDocumentId,
2139
+ view: "summary",
2140
+ }),
2141
+ },
2142
+ documents: document ? [document] : [],
2143
+ resolution: prepared.resolution,
2144
+ retrieval: {
2145
+ query: question,
2146
+ result: compactValue({
2147
+ ...maybeDropPolicies(res.body, !!args.includePolicies),
2148
+ data: document,
2149
+ }),
2150
+ },
2151
+ };
2152
+ }
2153
+
411
2154
  const body = compactValue({
412
2155
  query: question,
413
2156
  collectionId: args.collectionId,
414
- documentId: args.documentId || args.id,
415
2157
  userId: args.userId,
416
2158
  shareId: args.shareId,
417
2159
  statusFilter: args.statusFilter,
@@ -447,6 +2189,7 @@ async function buildAnswerFallbackResult(ctx, question, args = {}) {
447
2189
  }),
448
2190
  },
449
2191
  documents,
2192
+ resolution: prepared.resolution,
450
2193
  retrieval: {
451
2194
  query: question,
452
2195
  result: compactValue({
@@ -463,10 +2206,12 @@ async function documentsAnswerTool(ctx, args = {}) {
463
2206
  throw new CliError("documents.answer requires args.question or args.query");
464
2207
  }
465
2208
 
466
- const body = {
467
- ...buildBody(args, ["question", "query", "limit"]),
468
- query: question,
469
- };
2209
+ const prepared = await resolveAnswerScope(ctx, args);
2210
+ if (prepared.error) {
2211
+ return buildAnswerResolutionMiss("documents.answer", ctx, question, prepared);
2212
+ }
2213
+
2214
+ const body = buildAnswerEndpointBody(prepared.args, question);
470
2215
 
471
2216
  try {
472
2217
  const res = await ctx.client.call("documents.answerQuestion", body, {
@@ -479,8 +2224,8 @@ async function documentsAnswerTool(ctx, args = {}) {
479
2224
  profile: ctx.profile.id,
480
2225
  result:
481
2226
  payload && typeof payload === "object"
482
- ? { question, ...payload }
483
- : { question, data: payload },
2227
+ ? compactValue({ question, resolution: prepared.resolution, ...payload }) || { question, ...payload }
2228
+ : { question, resolution: prepared.resolution, data: payload },
484
2229
  };
485
2230
  } catch (err) {
486
2231
  if (!isAnswerEndpointUnsupported(err)) {
@@ -490,7 +2235,7 @@ async function documentsAnswerTool(ctx, args = {}) {
490
2235
  return {
491
2236
  tool: "documents.answer",
492
2237
  profile: ctx.profile.id,
493
- result: await buildAnswerFallbackResult(ctx, question, args),
2238
+ result: await buildAnswerFallbackResult(ctx, question, prepared.args, prepared),
494
2239
  };
495
2240
  }
496
2241
  }
@@ -508,20 +2253,34 @@ async function documentsAnswerBatchTool(ctx, args = {}) {
508
2253
  throw new CliError("documents.answer_batch requires args.question or args.questions[]");
509
2254
  }
510
2255
 
511
- const baseBody = buildBody(args, ["question", "questions", "query", "concurrency", "limit"]);
2256
+ const basePrepared = await resolveAnswerScope(ctx, args);
512
2257
  const includePolicies = !!args.includePolicies;
513
2258
  const maxAttempts = toInteger(args.maxAttempts, 2);
514
2259
  const concurrency = Math.max(1, Math.min(10, toInteger(args.concurrency, 3)));
515
2260
 
516
2261
  const items = await mapLimit(rawItems, concurrency, async (raw, index) => {
517
2262
  let parsed;
2263
+ let prepared;
518
2264
  try {
519
2265
  parsed = parseQuestionItem(raw, index);
520
- const body = {
521
- ...baseBody,
522
- ...parsed.body,
523
- query: parsed.question,
524
- };
2266
+ prepared = hasAnswerScopeSelectors(parsed.body)
2267
+ ? await resolveAnswerScope(ctx, { ...args, ...parsed.body })
2268
+ : basePrepared;
2269
+ if (prepared.error) {
2270
+ return {
2271
+ index,
2272
+ ok: false,
2273
+ question: parsed.question,
2274
+ documentId: parsed.documentId || null,
2275
+ error: "Unable to resolve answer scope",
2276
+ status: prepared.error?.failed?.status || "not_found",
2277
+ resolution: prepared.error,
2278
+ };
2279
+ }
2280
+ const answerArgs = hasAnswerScopeSelectors(parsed.body)
2281
+ ? prepared.args
2282
+ : compactValue({ ...prepared.args, ...parsed.body }) || prepared.args;
2283
+ const body = buildAnswerEndpointBody(answerArgs, parsed.question);
525
2284
  const res = await ctx.client.call("documents.answerQuestion", body, {
526
2285
  maxAttempts,
527
2286
  });
@@ -530,21 +2289,46 @@ async function documentsAnswerBatchTool(ctx, args = {}) {
530
2289
  index,
531
2290
  ok: true,
532
2291
  question: parsed.question,
533
- documentId: parsed.documentId,
534
- result: payload,
2292
+ documentId: body.documentId || parsed.documentId,
2293
+ result: compactValue({ resolution: prepared.resolution, ...payload }) || payload,
535
2294
  };
536
2295
  } catch (err) {
537
2296
  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
- };
2297
+ try {
2298
+ if (prepared.error) {
2299
+ return {
2300
+ index,
2301
+ ok: false,
2302
+ question: parsed.question,
2303
+ documentId: parsed.documentId || null,
2304
+ error: "Unable to resolve answer scope",
2305
+ status: prepared.error?.failed?.status || "not_found",
2306
+ resolution: prepared.error,
2307
+ };
2308
+ }
2309
+ const fallbackArgs = hasAnswerScopeSelectors(parsed.body)
2310
+ ? prepared.args
2311
+ : compactValue({ ...prepared.args, ...parsed.body }) || prepared.args;
2312
+ return {
2313
+ index,
2314
+ ok: true,
2315
+ question: parsed.question,
2316
+ documentId: fallbackArgs.documentId || parsed.documentId,
2317
+ result: await buildAnswerFallbackResult(ctx, parsed.question, fallbackArgs, prepared),
2318
+ };
2319
+ } catch (fallbackErr) {
2320
+ if (fallbackErr instanceof ApiError || fallbackErr instanceof CliError) {
2321
+ return {
2322
+ index,
2323
+ ok: false,
2324
+ question: parsed.question,
2325
+ documentId: parsed.documentId,
2326
+ error: fallbackErr.message,
2327
+ status: fallbackErr instanceof ApiError ? fallbackErr.details.status : undefined,
2328
+ };
2329
+ }
2330
+ throw fallbackErr;
2331
+ }
548
2332
  }
549
2333
  if (err instanceof ApiError || err instanceof CliError) {
550
2334
  return {
@@ -574,6 +2358,110 @@ async function documentsAnswerBatchTool(ctx, args = {}) {
574
2358
  };
575
2359
  }
576
2360
 
2361
+ async function documentsAttachmentsTool(ctx, args = {}) {
2362
+ const read = await readDocumentForAttachments(ctx, args);
2363
+ const doc = read.document;
2364
+ if (!doc) {
2365
+ return {
2366
+ tool: "documents.attachments",
2367
+ profile: ctx.profile.id,
2368
+ result: {
2369
+ ok: false,
2370
+ status: "not_found",
2371
+ document: null,
2372
+ resolution: read.resolution,
2373
+ total: 0,
2374
+ attachments: [],
2375
+ },
2376
+ };
2377
+ }
2378
+ const attachments = extractAttachmentRefsFromText(doc.text || "", ctx.profile?.baseUrl);
2379
+
2380
+ return {
2381
+ tool: "documents.attachments",
2382
+ profile: ctx.profile.id,
2383
+ result: {
2384
+ ok: true,
2385
+ document: summarizeAttachmentDocument(doc),
2386
+ resolution: read.resolution,
2387
+ total: attachments.length,
2388
+ attachments,
2389
+ },
2390
+ };
2391
+ }
2392
+
2393
+ async function attachmentsDownloadTool(ctx, args = {}) {
2394
+ const id = extractAttachmentId(args.id || args.attachmentId || args.url || args.path);
2395
+ if (!id) {
2396
+ throw new CliError("attachments.download requires args.id or an attachment redirect args.url/path");
2397
+ }
2398
+
2399
+ return {
2400
+ tool: "attachments.download",
2401
+ profile: ctx.profile.id,
2402
+ result: await downloadAttachmentToFile(ctx, args, id),
2403
+ };
2404
+ }
2405
+
2406
+ async function documentsDownloadAttachmentsTool(ctx, args = {}) {
2407
+ const read = await readDocumentForAttachments(ctx, args);
2408
+ const doc = read.document;
2409
+ if (!doc) {
2410
+ return {
2411
+ tool: "documents.download_attachments",
2412
+ profile: ctx.profile.id,
2413
+ result: {
2414
+ ok: false,
2415
+ status: "not_found",
2416
+ document: null,
2417
+ resolution: read.resolution,
2418
+ total: 0,
2419
+ succeeded: 0,
2420
+ failed: 0,
2421
+ outputDir: path.resolve(String(args.outputDir || path.join(defaultTmpDir(), "attachments"))),
2422
+ items: [],
2423
+ },
2424
+ };
2425
+ }
2426
+ const attachments = extractAttachmentRefsFromText(doc.text || "", ctx.profile?.baseUrl);
2427
+ const concurrency = Math.max(1, Math.min(8, toInteger(args.concurrency, 3)));
2428
+ const items = await mapLimit(attachments, concurrency, async (attachment, index) => {
2429
+ try {
2430
+ const saved = await downloadAttachmentToFile(ctx, args, attachment.id, index);
2431
+ return {
2432
+ ...attachment,
2433
+ ...saved,
2434
+ };
2435
+ } catch (err) {
2436
+ if (err instanceof ApiError || err instanceof CliError) {
2437
+ return {
2438
+ ...attachment,
2439
+ ok: false,
2440
+ error: err.message,
2441
+ status: err instanceof ApiError ? err.details.status : undefined,
2442
+ };
2443
+ }
2444
+ throw err;
2445
+ }
2446
+ });
2447
+ const failed = items.filter((item) => !item.ok).length;
2448
+
2449
+ return {
2450
+ tool: "documents.download_attachments",
2451
+ profile: ctx.profile.id,
2452
+ result: {
2453
+ ok: failed === 0,
2454
+ document: summarizeAttachmentDocument(doc),
2455
+ resolution: read.resolution,
2456
+ total: attachments.length,
2457
+ succeeded: items.length - failed,
2458
+ failed,
2459
+ outputDir: path.resolve(String(args.outputDir || path.join(defaultTmpDir(), "attachments"))),
2460
+ items,
2461
+ },
2462
+ };
2463
+ }
2464
+
577
2465
  async function documentsImportFileTool(ctx, args = {}) {
578
2466
  assertPerformAction(args, {
579
2467
  tool: "documents.import_file",
@@ -982,12 +2870,239 @@ function normalizeGraphSourceIds(args = {}) {
982
2870
  if (args.id !== undefined && args.id !== null) {
983
2871
  values.push(args.id);
984
2872
  }
2873
+ if (args.documentId !== undefined && args.documentId !== null) {
2874
+ values.push(args.documentId);
2875
+ }
2876
+ if (args.seedId !== undefined && args.seedId !== null) {
2877
+ values.push(args.seedId);
2878
+ }
985
2879
  for (const id of ensureStringArray(args.ids, "ids") || []) {
986
2880
  values.push(id);
987
2881
  }
2882
+ for (const id of ensureStringArray(args.documentIds, "documentIds") || []) {
2883
+ values.push(id);
2884
+ }
2885
+ for (const id of ensureStringArray(args.seedIds, "seedIds") || []) {
2886
+ values.push(id);
2887
+ }
988
2888
  return uniqueStrings(values).sort(compareIdAsc);
989
2889
  }
990
2890
 
2891
+ function normalizeDocumentRefValues(args = {}) {
2892
+ const queries = [];
2893
+ if (args.query !== undefined && args.query !== null) {
2894
+ queries.push(args.query);
2895
+ }
2896
+ if (args.seedQuery !== undefined && args.seedQuery !== null) {
2897
+ queries.push(args.seedQuery);
2898
+ }
2899
+ queries.push(...(ensureStringArray(args.queries, "queries") || []));
2900
+ queries.push(...(ensureStringArray(args.seedQueries, "seedQueries") || []));
2901
+
2902
+ const shareIds = [];
2903
+ if (args.shareId !== undefined && args.shareId !== null) {
2904
+ shareIds.push(args.shareId);
2905
+ }
2906
+ if (args.seedShareId !== undefined && args.seedShareId !== null) {
2907
+ shareIds.push(args.seedShareId);
2908
+ }
2909
+ shareIds.push(...(ensureStringArray(args.shareIds, "shareIds") || []));
2910
+ shareIds.push(...(ensureStringArray(args.seedShareIds, "seedShareIds") || []));
2911
+
2912
+ const urlIds = [];
2913
+ if (args.urlId !== undefined && args.urlId !== null) {
2914
+ urlIds.push(args.urlId);
2915
+ }
2916
+ if (args.seedUrlId !== undefined && args.seedUrlId !== null) {
2917
+ urlIds.push(args.seedUrlId);
2918
+ }
2919
+ urlIds.push(...(ensureStringArray(args.urlIds, "urlIds") || []));
2920
+ urlIds.push(...(ensureStringArray(args.seedUrlIds, "seedUrlIds") || []));
2921
+
2922
+ const urls = [];
2923
+ if (args.url !== undefined && args.url !== null) {
2924
+ urls.push(args.url);
2925
+ }
2926
+ if (args.seedUrl !== undefined && args.seedUrl !== null) {
2927
+ urls.push(args.seedUrl);
2928
+ }
2929
+ urls.push(...(ensureStringArray(args.urls, "urls") || []));
2930
+ urls.push(...(ensureStringArray(args.seedUrls, "seedUrls") || []));
2931
+
2932
+ return {
2933
+ refs: [
2934
+ ...(ensureStringArray(args.refs, "refs") || []),
2935
+ ...(ensureStringArray(args.seedRefs, "seedRefs") || []),
2936
+ ],
2937
+ queries,
2938
+ shareIds,
2939
+ urlIds,
2940
+ urls,
2941
+ };
2942
+ }
2943
+
2944
+ function hasDocumentRefValues(refs) {
2945
+ return Object.values(refs).some((items) =>
2946
+ Array.isArray(items) && items.some((item) => String(item || "").trim())
2947
+ );
2948
+ }
2949
+
2950
+ async function resolveDocumentIdsForRead(ctx, args = {}) {
2951
+ const exactIds = normalizeGraphSourceIds(args);
2952
+ const refs = normalizeDocumentRefValues(args);
2953
+ const resolution = {
2954
+ exactIds,
2955
+ requested: {
2956
+ refs: refs.refs.filter((item) => String(item || "").trim()),
2957
+ queries: refs.queries.filter((item) => String(item || "").trim()),
2958
+ shareIds: refs.shareIds.filter((item) => String(item || "").trim()),
2959
+ urlIds: refs.urlIds.filter((item) => String(item || "").trim()),
2960
+ urls: refs.urls.filter((item) => String(item || "").trim()),
2961
+ },
2962
+ resolved: [],
2963
+ failed: [],
2964
+ memory: null,
2965
+ };
2966
+
2967
+ if (hasDocumentRefValues(refs)) {
2968
+ const opened = await documentsOpenBatchTool(ctx, compactValue({
2969
+ refs: refs.refs,
2970
+ queries: refs.queries,
2971
+ shareIds: refs.shareIds,
2972
+ urlIds: refs.urlIds,
2973
+ urls: refs.urls,
2974
+ profile: args.profile,
2975
+ limit: args.resolveLimit,
2976
+ minScore: args.minScore,
2977
+ maxAgeHours: args.maxAgeHours,
2978
+ refresh: args.refresh,
2979
+ strict: args.strict,
2980
+ strictThreshold: args.strictThreshold,
2981
+ fallbackSearch: args.fallbackSearch,
2982
+ fallbackMinScore: args.fallbackMinScore,
2983
+ fallbackLimit: args.fallbackLimit,
2984
+ fallbackMode: args.fallbackMode,
2985
+ collectionId: args.resolveCollectionId,
2986
+ view: "summary",
2987
+ concurrency: args.resolveConcurrency,
2988
+ hydrateConcurrency: args.resolveHydrateConcurrency,
2989
+ maxAttempts: args.maxAttempts,
2990
+ }) || {});
2991
+ resolution.memory = opened.result?.memory || null;
2992
+ for (const item of opened.result?.items || []) {
2993
+ if (item?.ok && item.document?.id) {
2994
+ resolution.resolved.push({
2995
+ index: item.index,
2996
+ kind: item.kind,
2997
+ value: item.value,
2998
+ id: item.document.id,
2999
+ title: item.document.title,
3000
+ mode: item.mode,
3001
+ candidate: item.candidate,
3002
+ });
3003
+ continue;
3004
+ }
3005
+ resolution.failed.push({
3006
+ index: item?.index,
3007
+ kind: item?.kind,
3008
+ value: item?.value,
3009
+ status: item?.status || "not_found",
3010
+ candidate: item?.candidate,
3011
+ candidates: item?.candidates,
3012
+ error: item?.error,
3013
+ });
3014
+ }
3015
+ }
3016
+
3017
+ const ids = uniqueStrings([
3018
+ ...exactIds,
3019
+ ...resolution.resolved.map((item) => item.id),
3020
+ ]).sort(compareIdAsc);
3021
+
3022
+ return {
3023
+ ids,
3024
+ resolution,
3025
+ };
3026
+ }
3027
+
3028
+ async function resolveCollectionIdForRead(ctx, args = {}) {
3029
+ const exactId = args.collectionId ? String(args.collectionId).trim() : "";
3030
+ if (exactId) {
3031
+ return {
3032
+ id: exactId,
3033
+ resolution: {
3034
+ exactId,
3035
+ resolved: null,
3036
+ failed: null,
3037
+ memory: null,
3038
+ },
3039
+ };
3040
+ }
3041
+
3042
+ const refArgs = compactValue({
3043
+ query: args.collectionQuery,
3044
+ id: args.collectionRefId,
3045
+ urlId: args.collectionUrlId,
3046
+ url: args.collectionUrl,
3047
+ profile: args.profile,
3048
+ limit: args.collectionResolveLimit || args.resolveLimit,
3049
+ minScore: args.collectionMinScore ?? args.minScore,
3050
+ maxAgeHours: args.collectionMaxAgeHours ?? args.maxAgeHours,
3051
+ refresh: args.refresh,
3052
+ strict: args.strict,
3053
+ strictThreshold: args.collectionStrictThreshold ?? args.strictThreshold,
3054
+ fallbackSearch: args.fallbackSearch,
3055
+ fallbackMinScore: args.collectionFallbackMinScore ?? args.fallbackMinScore,
3056
+ fallbackLimit: args.collectionFallbackLimit ?? args.fallbackLimit,
3057
+ view: "summary",
3058
+ maxAttempts: args.maxAttempts,
3059
+ }) || {};
3060
+
3061
+ if (!refArgs.query && !refArgs.id && !refArgs.urlId && !refArgs.url) {
3062
+ return {
3063
+ id: "",
3064
+ resolution: {
3065
+ exactId: "",
3066
+ resolved: null,
3067
+ failed: null,
3068
+ memory: null,
3069
+ },
3070
+ };
3071
+ }
3072
+
3073
+ const opened = await collectionsOpenTool(ctx, refArgs);
3074
+ if (opened.result?.ok && opened.result?.collection?.id) {
3075
+ return {
3076
+ id: opened.result.collection.id,
3077
+ resolution: {
3078
+ exactId: "",
3079
+ resolved: {
3080
+ id: opened.result.collection.id,
3081
+ name: opened.result.collection.name,
3082
+ mode: opened.result.mode,
3083
+ candidate: opened.result.candidate,
3084
+ },
3085
+ failed: null,
3086
+ memory: opened.result.memory || null,
3087
+ },
3088
+ };
3089
+ }
3090
+
3091
+ return {
3092
+ id: "",
3093
+ resolution: {
3094
+ exactId: "",
3095
+ resolved: null,
3096
+ failed: {
3097
+ status: opened.result?.status || "not_found",
3098
+ candidate: opened.result?.candidate,
3099
+ candidates: opened.result?.candidates,
3100
+ },
3101
+ memory: opened.result?.memory || null,
3102
+ },
3103
+ };
3104
+ }
3105
+
991
3106
  function normalizeGraphSearchQueries(value) {
992
3107
  return uniqueStrings(ensureStringArray(value, "searchQueries") || []);
993
3108
  }
@@ -1830,9 +3945,19 @@ async function collectGraphNeighbors(ctx, sourceIds, options = {}) {
1830
3945
  }
1831
3946
 
1832
3947
  async function documentsBacklinksTool(ctx, args = {}) {
1833
- const id = String(args.id || "").trim();
3948
+ const resolved = await resolveDocumentIdsForRead(ctx, args);
3949
+ const id = resolved.ids[0] || "";
1834
3950
  if (!id) {
1835
- throw new CliError("documents.backlinks requires args.id");
3951
+ return {
3952
+ tool: "documents.backlinks",
3953
+ profile: ctx.profile.id,
3954
+ result: {
3955
+ ok: false,
3956
+ status: "not_found",
3957
+ data: [],
3958
+ resolution: resolved.resolution,
3959
+ },
3960
+ };
1836
3961
  }
1837
3962
 
1838
3963
  const view = normalizeGraphView(args.view);
@@ -1858,6 +3983,13 @@ async function documentsBacklinksTool(ctx, args = {}) {
1858
3983
  };
1859
3984
  }
1860
3985
  payload = maybeDropPolicies(payload, !!args.includePolicies);
3986
+ payload = compactValue({
3987
+ ...payload,
3988
+ ok: payload?.ok,
3989
+ resolution: (resolved.resolution.resolved.length > 0 || resolved.resolution.failed.length > 0)
3990
+ ? resolved.resolution
3991
+ : undefined,
3992
+ }) || {};
1861
3993
 
1862
3994
  return {
1863
3995
  tool: "documents.backlinks",
@@ -1867,9 +3999,24 @@ async function documentsBacklinksTool(ctx, args = {}) {
1867
3999
  }
1868
4000
 
1869
4001
  async function documentsGraphNeighborsTool(ctx, args = {}) {
1870
- const sourceIds = normalizeGraphSourceIds(args);
4002
+ const resolved = await resolveDocumentIdsForRead(ctx, args);
4003
+ const sourceIds = resolved.ids;
1871
4004
  if (sourceIds.length === 0) {
1872
- throw new CliError("documents.graph_neighbors requires args.id or args.ids[]");
4005
+ return {
4006
+ tool: "documents.graph_neighbors",
4007
+ profile: ctx.profile.id,
4008
+ result: {
4009
+ ok: false,
4010
+ status: "not_found",
4011
+ sourceIds: [],
4012
+ resolution: resolved.resolution,
4013
+ nodeCount: 0,
4014
+ edgeCount: 0,
4015
+ nodes: [],
4016
+ edges: [],
4017
+ errors: [],
4018
+ },
4019
+ };
1873
4020
  }
1874
4021
 
1875
4022
  const includeBacklinks = args.includeBacklinks !== false;
@@ -1895,12 +4042,16 @@ async function documentsGraphNeighborsTool(ctx, args = {}) {
1895
4042
 
1896
4043
  const nodes = buildGraphNodeList(collected.nodesById, view);
1897
4044
  const edges = sortGraphEdges(collected.edges);
4045
+ const resolution = resolved.resolution.resolved.length > 0 || resolved.resolution.failed.length > 0
4046
+ ? resolved.resolution
4047
+ : undefined;
1898
4048
 
1899
4049
  return {
1900
4050
  tool: "documents.graph_neighbors",
1901
4051
  profile: ctx.profile.id,
1902
4052
  result: {
1903
4053
  sourceIds,
4054
+ ...(resolution ? { resolution } : {}),
1904
4055
  includeBacklinks,
1905
4056
  includeSearchNeighbors,
1906
4057
  searchQueries,
@@ -1915,9 +4066,32 @@ async function documentsGraphNeighborsTool(ctx, args = {}) {
1915
4066
  }
1916
4067
 
1917
4068
  async function documentsGraphReportTool(ctx, args = {}) {
1918
- const requestedSeedIds = uniqueStrings(ensureStringArray(args.seedIds, "seedIds") || []).sort(compareIdAsc);
4069
+ const resolved = await resolveDocumentIdsForRead(ctx, args);
4070
+ const requestedSeedIds = resolved.ids;
1919
4071
  if (requestedSeedIds.length === 0) {
1920
- throw new CliError("documents.graph_report requires args.seedIds[]");
4072
+ return {
4073
+ tool: "documents.graph_report",
4074
+ profile: ctx.profile.id,
4075
+ result: {
4076
+ ok: false,
4077
+ status: "not_found",
4078
+ seedIds: [],
4079
+ requestedSeedCount: 0,
4080
+ resolution: resolved.resolution,
4081
+ depth: Math.max(0, Math.min(6, toInteger(args.depth, 2))),
4082
+ exploredDepth: 0,
4083
+ maxNodes: Math.max(1, Math.min(500, toInteger(args.maxNodes, 120))),
4084
+ includeBacklinks: args.includeBacklinks !== false,
4085
+ includeSearchNeighbors: args.includeSearchNeighbors === true,
4086
+ limitPerSource: Math.max(1, Math.min(100, toInteger(args.limitPerSource, 10))),
4087
+ truncated: false,
4088
+ nodeCount: 0,
4089
+ edgeCount: 0,
4090
+ nodes: [],
4091
+ edges: [],
4092
+ errors: [],
4093
+ },
4094
+ };
1921
4095
  }
1922
4096
 
1923
4097
  const includeBacklinks = args.includeBacklinks !== false;
@@ -2016,6 +4190,9 @@ async function documentsGraphReportTool(ctx, args = {}) {
2016
4190
  (edge) => allowedIds.has(edge.sourceId) && allowedIds.has(edge.targetId)
2017
4191
  )
2018
4192
  );
4193
+ const resolution = resolved.resolution.resolved.length > 0 || resolved.resolution.failed.length > 0
4194
+ ? resolved.resolution
4195
+ : undefined;
2019
4196
 
2020
4197
  return {
2021
4198
  tool: "documents.graph_report",
@@ -2023,6 +4200,7 @@ async function documentsGraphReportTool(ctx, args = {}) {
2023
4200
  result: {
2024
4201
  seedIds,
2025
4202
  requestedSeedCount: requestedSeedIds.length,
4203
+ ...(resolution ? { resolution } : {}),
2026
4204
  depth,
2027
4205
  exploredDepth,
2028
4206
  maxNodes,
@@ -2040,9 +4218,27 @@ async function documentsGraphReportTool(ctx, args = {}) {
2040
4218
  }
2041
4219
 
2042
4220
  async function documentsIssueRefsTool(ctx, args = {}) {
2043
- const ids = normalizeIssueRefIds(args);
4221
+ const resolved = await resolveDocumentIdsForRead(ctx, args);
4222
+ const ids = resolved.ids;
2044
4223
  if (ids.length === 0) {
2045
- throw new CliError("documents.issue_refs requires args.id or args.ids[]");
4224
+ return {
4225
+ tool: "documents.issue_refs",
4226
+ profile: ctx.profile.id,
4227
+ result: {
4228
+ ok: false,
4229
+ status: "not_found",
4230
+ requestedIds: [],
4231
+ resolution: resolved.resolution,
4232
+ documentCount: 0,
4233
+ documentsWithRefs: 0,
4234
+ refCount: 0,
4235
+ keyCount: 0,
4236
+ mentionCount: 0,
4237
+ keys: [],
4238
+ documents: [],
4239
+ errors: [],
4240
+ },
4241
+ };
2046
4242
  }
2047
4243
 
2048
4244
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 2));
@@ -2054,12 +4250,16 @@ async function documentsIssueRefsTool(ctx, args = {}) {
2054
4250
  maxAttempts,
2055
4251
  view,
2056
4252
  });
4253
+ const resolution = resolved.resolution.resolved.length > 0 || resolved.resolution.failed.length > 0
4254
+ ? resolved.resolution
4255
+ : undefined;
2057
4256
 
2058
4257
  return {
2059
4258
  tool: "documents.issue_refs",
2060
4259
  profile: ctx.profile.id,
2061
4260
  result: {
2062
4261
  requestedIds: extracted.requestedIds,
4262
+ ...(resolution ? { resolution } : {}),
2063
4263
  issueDomains: extracted.issueDomains,
2064
4264
  keyPattern: extracted.keyPattern,
2065
4265
  ...extracted.summary,
@@ -2101,10 +4301,40 @@ async function documentsIssueRefReportTool(ctx, args = {}) {
2101
4301
  };
2102
4302
  }
2103
4303
 
4304
+ async function resolveTemplateSelector(ctx, args = {}, options = {}) {
4305
+ const resolved = await resolveEntityId(ctx, args, {
4306
+ type: "template",
4307
+ outputField: options.outputField || "id",
4308
+ resultField: "templateId",
4309
+ exactKeys: options.exactKeys || [options.outputField || "id"],
4310
+ queryKeys: ["templateQuery", "templateRef", "query"],
4311
+ arrayQueryKeys: ["templateQueries", "templateRefs", "refs", "queries"],
4312
+ });
4313
+ if (resolved?.error) {
4314
+ return resolved;
4315
+ }
4316
+ if (resolved?.id) {
4317
+ return resolved;
4318
+ }
4319
+ const exact = (options.exactKeys || [options.outputField || "id"])
4320
+ .map((key) => String(args[key] || "").trim())
4321
+ .find(Boolean);
4322
+ return exact ? { id: exact, resolution: null } : { id: "" };
4323
+ }
4324
+
2104
4325
  async function templatesExtractPlaceholdersTool(ctx, args = {}) {
2105
- const id = String(args.id || "").trim();
4326
+ const resolvedTemplate = await resolveTemplateSelector(ctx, args, {
4327
+ outputField: "id",
4328
+ exactKeys: ["id"],
4329
+ });
4330
+ if (resolvedTemplate.error) {
4331
+ throw new CliError("templates.extract_placeholders could not resolve template", {
4332
+ resolution: resolvedTemplate.error,
4333
+ });
4334
+ }
4335
+ const id = String(resolvedTemplate.id || "").trim();
2106
4336
  if (!id) {
2107
- throw new CliError("templates.extract_placeholders requires args.id");
4337
+ throw new CliError("templates.extract_placeholders requires args.id or args.templateQuery");
2108
4338
  }
2109
4339
 
2110
4340
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 2));
@@ -2118,7 +4348,9 @@ async function templatesExtractPlaceholdersTool(ctx, args = {}) {
2118
4348
  profile: ctx.profile.id,
2119
4349
  result: {
2120
4350
  id: template?.id ? String(template.id) : id,
4351
+ templateId: id,
2121
4352
  title: template?.title ? String(template.title) : "",
4353
+ resolution: resolvedTemplate.resolution,
2122
4354
  placeholders: stats.placeholders,
2123
4355
  counts: stats.countsByPlaceholder,
2124
4356
  meta: {
@@ -2132,16 +4364,25 @@ async function templatesExtractPlaceholdersTool(ctx, args = {}) {
2132
4364
  }
2133
4365
 
2134
4366
  async function documentsCreateFromTemplateTool(ctx, args = {}) {
2135
- const templateId = String(args.templateId || "").trim();
2136
- if (!templateId) {
2137
- throw new CliError("documents.create_from_template requires args.templateId");
2138
- }
2139
-
2140
4367
  assertPerformAction(args, {
2141
4368
  tool: "documents.create_from_template",
2142
4369
  action: "create and optionally update a document from template",
2143
4370
  });
2144
4371
 
4372
+ const resolvedTemplate = await resolveTemplateSelector(ctx, args, {
4373
+ outputField: "templateId",
4374
+ exactKeys: ["templateId"],
4375
+ });
4376
+ if (resolvedTemplate.error) {
4377
+ throw new CliError("documents.create_from_template could not resolve template", {
4378
+ resolution: resolvedTemplate.error,
4379
+ });
4380
+ }
4381
+ const templateId = String(resolvedTemplate.id || "").trim();
4382
+ if (!templateId) {
4383
+ throw new CliError("documents.create_from_template requires args.templateId or args.templateQuery");
4384
+ }
4385
+
2145
4386
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 1));
2146
4387
  const view = normalizeTemplatePipelineView(args.view);
2147
4388
  const strictPlaceholders = args.strictPlaceholders === true;
@@ -2175,6 +4416,8 @@ async function documentsCreateFromTemplateTool(ctx, args = {}) {
2175
4416
  strictPlaceholders,
2176
4417
  publishRequested,
2177
4418
  published: publishRequested,
4419
+ templateId,
4420
+ resolution: resolvedTemplate.resolution,
2178
4421
  document: normalizeTemplatePipelineDocument(finalPayload?.data || createdDoc, view),
2179
4422
  placeholders: {
2180
4423
  providedKeys: [],
@@ -2235,6 +4478,8 @@ async function documentsCreateFromTemplateTool(ctx, args = {}) {
2235
4478
  publishRequested,
2236
4479
  published: false,
2237
4480
  safeBehavior: "left_unpublished_draft",
4481
+ templateId,
4482
+ resolution: resolvedTemplate.resolution,
2238
4483
  document: normalizeTemplatePipelineDocument(updatedDoc, view),
2239
4484
  placeholders: {
2240
4485
  providedKeys: providedPlaceholderKeys,
@@ -2280,6 +4525,8 @@ async function documentsCreateFromTemplateTool(ctx, args = {}) {
2280
4525
  strictPlaceholders,
2281
4526
  publishRequested,
2282
4527
  published,
4528
+ templateId,
4529
+ resolution: resolvedTemplate.resolution,
2283
4530
  document: normalizeTemplatePipelineDocument(finalPayload?.data || updatedDoc, view),
2284
4531
  placeholders: {
2285
4532
  providedKeys: providedPlaceholderKeys,
@@ -2542,25 +4789,60 @@ async function listCollectionDocumentIds(ctx, collectionId, maxAttempts) {
2542
4789
  }
2543
4790
 
2544
4791
  async function commentsReviewQueueTool(ctx, args = {}) {
2545
- const explicitIds = uniqueStrings(ensureStringArray(args.documentIds, "documentIds") || []);
2546
- const collectionId = args.collectionId ? String(args.collectionId) : "";
4792
+ const resolvedDocuments = await resolveDocumentIdsForRead(ctx, args);
4793
+ const documentResolution = resolvedDocuments.resolution.resolved.length > 0 || resolvedDocuments.resolution.failed.length > 0
4794
+ ? resolvedDocuments.resolution
4795
+ : undefined;
4796
+ const resolvedCollection = await resolveCollectionIdForRead(ctx, args);
4797
+ const collectionResolution = resolvedCollection.resolution.resolved || resolvedCollection.resolution.failed
4798
+ ? resolvedCollection.resolution
4799
+ : undefined;
4800
+ const collectionId = resolvedCollection.id;
2547
4801
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 2));
2548
4802
  const includeReplies = args.includeReplies !== false;
2549
4803
  const includeAnchorText = !!args.includeAnchorText;
2550
4804
  const limitPerDocument = Math.max(1, Math.min(200, toInteger(args.limitPerDocument, 30)));
2551
4805
  const view = args.view === "full" ? "full" : "summary";
2552
4806
 
2553
- if (explicitIds.length === 0 && !collectionId) {
2554
- throw new CliError("comments.review_queue requires args.documentIds[] or args.collectionId");
4807
+ const requestedDocumentRefs = documentResolution || resolvedDocuments.resolution.exactIds.length > 0;
4808
+ const requestedCollectionRef = !!args.collectionId || !!args.collectionQuery || !!args.collectionRefId
4809
+ || !!args.collectionUrlId || !!args.collectionUrl;
4810
+ if (!requestedDocumentRefs && !requestedCollectionRef) {
4811
+ throw new CliError("comments.review_queue requires args.documentIds[], document refs, args.collectionId, or collection refs");
2555
4812
  }
2556
4813
 
2557
- let documentIds = explicitIds;
4814
+ let documentIds = resolvedDocuments.ids;
2558
4815
  let collectionScopeTruncated = false;
2559
4816
  if (documentIds.length === 0 && collectionId) {
2560
4817
  const resolved = await listCollectionDocumentIds(ctx, collectionId, maxAttempts);
2561
4818
  documentIds = resolved.ids;
2562
4819
  collectionScopeTruncated = resolved.truncated;
2563
4820
  }
4821
+ if (documentIds.length === 0) {
4822
+ return {
4823
+ tool: "comments.review_queue",
4824
+ profile: ctx.profile.id,
4825
+ result: {
4826
+ ok: false,
4827
+ status: "not_found",
4828
+ scope: {
4829
+ documentIds: [],
4830
+ collectionId,
4831
+ ...(documentResolution ? { documentResolution } : {}),
4832
+ ...(collectionResolution ? { collectionResolution } : {}),
4833
+ },
4834
+ includeReplies,
4835
+ includeAnchorText,
4836
+ limitPerDocument,
4837
+ documentCount: 0,
4838
+ rowCount: 0,
4839
+ failedDocumentCount: 0,
4840
+ truncated: false,
4841
+ rows: [],
4842
+ failures: [],
4843
+ },
4844
+ };
4845
+ }
2564
4846
 
2565
4847
  const perDocument = await mapLimit(documentIds, Math.min(6, Math.max(1, documentIds.length || 1)), async (documentId) => {
2566
4848
  try {
@@ -2633,6 +4915,8 @@ async function commentsReviewQueueTool(ctx, args = {}) {
2633
4915
  scope: {
2634
4916
  documentIds,
2635
4917
  collectionId,
4918
+ ...(documentResolution ? { documentResolution } : {}),
4919
+ ...(collectionResolution ? { collectionResolution } : {}),
2636
4920
  },
2637
4921
  includeReplies,
2638
4922
  includeAnchorText,
@@ -3077,25 +5361,26 @@ export const EXTENDED_TOOLS = {
3077
5361
  ...RPC_TOOLS,
3078
5362
  "documents.answer": {
3079
5363
  signature:
3080
- "documents.answer(args: { question?: string; query?: string; limit?: number; ...endpointArgs; includePolicies?: boolean; maxAttempts?: number })",
5364
+ "documents.answer(args: { question?: string; query?: string; documentId?: string; documentQuery?: string; refs?: string[]; collectionId?: string; collectionQuery?: string; userId?: string; userQuery?: string; limit?: number; ...endpointArgs; includePolicies?: boolean; maxAttempts?: number })",
3081
5365
  description: "Answer a question using Outline AI over the selected document scope.",
3082
5366
  usageExample: {
3083
5367
  tool: "documents.answer",
3084
5368
  args: {
3085
5369
  question: "What changed in our onboarding checklist?",
3086
- collectionId: "collection-id",
5370
+ collectionQuery: "engineering",
3087
5371
  },
3088
5372
  },
3089
5373
  bestPractices: [
3090
5374
  "Use question text that is specific enough to resolve citations quickly.",
3091
- "Scope by collectionId or documentId to reduce latency and hallucination risk.",
5375
+ "Scope by documentQuery, refs, collectionQuery, or userQuery when callers have remembered titles, URLs, collection names, or emails instead of exact IDs.",
5376
+ "Use exact collectionId, documentId, or userId when already known to avoid a memory resolution step.",
3092
5377
  "If the deployment lacks documents.answerQuestion, this wrapper returns fallback retrieval evidence and a concrete search suggestion instead of a raw 404.",
3093
5378
  ],
3094
5379
  handler: documentsAnswerTool,
3095
5380
  },
3096
5381
  "documents.answer_batch": {
3097
5382
  signature:
3098
- "documents.answer_batch(args: { question?: string; questions?: Array<string | { question?: string; query?: string; ...endpointArgs }>; limit?: number; ...endpointArgs; concurrency?: number; includePolicies?: boolean; maxAttempts?: number })",
5383
+ "documents.answer_batch(args: { question?: string; questions?: Array<string | { question?: string; query?: string; documentQuery?: string; collectionQuery?: string; userQuery?: string; ...endpointArgs }>; limit?: number; ...endpointArgs; concurrency?: number; includePolicies?: boolean; maxAttempts?: number })",
3099
5384
  description: "Run multiple documents.answerQuestion calls with per-item isolation.",
3100
5385
  usageExample: {
3101
5386
  tool: "documents.answer_batch",
@@ -3104,12 +5389,13 @@ export const EXTENDED_TOOLS = {
3104
5389
  "Where is the release checklist?",
3105
5390
  "Who owns incident postmortems?",
3106
5391
  ],
3107
- collectionId: "collection-id",
5392
+ collectionQuery: "engineering",
3108
5393
  concurrency: 2,
3109
5394
  },
3110
5395
  },
3111
5396
  bestPractices: [
3112
5397
  "Prefer small batches and low concurrency for predictable token and latency budgets.",
5398
+ "Use top-level collectionQuery/userQuery to resolve shared scope once, or per-item documentQuery when each question targets a different remembered document.",
3113
5399
  "Use per-item statuses to retry only failures.",
3114
5400
  "Unsupported answer endpoints degrade to per-item retrieval evidence rather than failing the whole batch.",
3115
5401
  ],
@@ -3117,8 +5403,8 @@ export const EXTENDED_TOOLS = {
3117
5403
  },
3118
5404
  "documents.backlinks": {
3119
5405
  signature:
3120
- "documents.backlinks(args: { id: string; limit?: number; offset?: number; sort?: string; direction?: 'ASC'|'DESC'; view?: 'ids'|'summary'|'full'; includePolicies?: boolean; maxAttempts?: number })",
3121
- description: "List backlinks for a document via documents.list(backlinkDocumentId=id).",
5406
+ "documents.backlinks(args: { id?: string; query?: string; shareId?: string; urlId?: string; url?: string; limit?: number; offset?: number; sort?: string; direction?: 'ASC'|'DESC'; view?: 'ids'|'summary'|'full'; includePolicies?: boolean; maxAttempts?: number })",
5407
+ description: "List backlinks for a document by exact ID or by resolving a remembered title, share ID, URL id, or URL first.",
3122
5408
  usageExample: {
3123
5409
  tool: "documents.backlinks",
3124
5410
  args: {
@@ -3128,6 +5414,7 @@ export const EXTENDED_TOOLS = {
3128
5414
  },
3129
5415
  },
3130
5416
  bestPractices: [
5417
+ "Pass query/url/urlId directly when you know the document reference but not its exact ID.",
3131
5418
  "Use view=ids for low-token planning loops, then hydrate specific documents separately.",
3132
5419
  "Use limit/offset pagination for deterministic traversal over large backlink sets.",
3133
5420
  ],
@@ -3135,8 +5422,8 @@ export const EXTENDED_TOOLS = {
3135
5422
  },
3136
5423
  "documents.graph_neighbors": {
3137
5424
  signature:
3138
- "documents.graph_neighbors(args: { id?: string; ids?: string[]; includeBacklinks?: boolean; includeSearchNeighbors?: boolean; searchQueries?: string[]; limitPerSource?: number; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
3139
- description: "Collect one-hop graph neighbors and deterministic edge rows for source document IDs.",
5425
+ "documents.graph_neighbors(args: { id?: string; ids?: string[]; refs?: string[]; query?: string; queries?: string[]; shareId?: string; shareIds?: string[]; urlId?: string; urlIds?: string[]; url?: string; urls?: string[]; includeBacklinks?: boolean; includeSearchNeighbors?: boolean; searchQueries?: string[]; limitPerSource?: number; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
5426
+ description: "Collect one-hop graph neighbors and deterministic edge rows for source documents, resolving titles or URLs when needed.",
3140
5427
  usageExample: {
3141
5428
  tool: "documents.graph_neighbors",
3142
5429
  args: {
@@ -3148,6 +5435,7 @@ export const EXTENDED_TOOLS = {
3148
5435
  },
3149
5436
  },
3150
5437
  bestPractices: [
5438
+ "Use refs[] for mixed document titles and URLs; use ids[] when exact document IDs are already known.",
3151
5439
  "Start with a single source id and small limitPerSource, then expand incrementally.",
3152
5440
  "Enable includeSearchNeighbors only when additional semantic neighborhood expansion is needed.",
3153
5441
  ],
@@ -3155,8 +5443,8 @@ export const EXTENDED_TOOLS = {
3155
5443
  },
3156
5444
  "documents.graph_report": {
3157
5445
  signature:
3158
- "documents.graph_report(args: { seedIds: string[]; depth?: number; maxNodes?: number; includeBacklinks?: boolean; includeSearchNeighbors?: boolean; limitPerSource?: number; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
3159
- description: "Build a bounded BFS graph report with stable nodes[] and edges[] output.",
5446
+ "documents.graph_report(args: { seedIds?: string[]; seedRefs?: string[]; seedQuery?: string; seedQueries?: string[]; seedUrl?: string; seedUrls?: string[]; depth?: number; maxNodes?: number; includeBacklinks?: boolean; includeSearchNeighbors?: boolean; limitPerSource?: number; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
5447
+ description: "Build a bounded BFS graph report with stable nodes[] and edges[] output, resolving seed titles or URLs when needed.",
3160
5448
  usageExample: {
3161
5449
  tool: "documents.graph_report",
3162
5450
  args: {
@@ -3169,6 +5457,7 @@ export const EXTENDED_TOOLS = {
3169
5457
  },
3170
5458
  },
3171
5459
  bestPractices: [
5460
+ "Use seedRefs[] for mixed seed titles and URLs; use seedIds[] when exact document IDs are already known.",
3172
5461
  "Cap maxNodes and depth to keep traversal deterministic and cost-bounded.",
3173
5462
  "Prefer view=ids for graph planning and fetch full nodes only for selected IDs.",
3174
5463
  ],
@@ -3176,9 +5465,9 @@ export const EXTENDED_TOOLS = {
3176
5465
  },
3177
5466
  "documents.issue_refs": {
3178
5467
  signature:
3179
- "documents.issue_refs(args: { id?: string; ids?: string[]; issueDomains?: string[]; keyPattern?: string; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
5468
+ "documents.issue_refs(args: { id?: string; ids?: string[]; refs?: string[]; query?: string; queries?: string[]; shareId?: string; shareIds?: string[]; urlId?: string; urlIds?: string[]; url?: string; urls?: string[]; issueDomains?: string[]; keyPattern?: string; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
3180
5469
  description:
3181
- "Extract deterministic issue references (URL links and key-pattern matches) from one or more documents.",
5470
+ "Extract deterministic issue references (URL links and key-pattern matches) from one or more documents, resolving titles or URLs when needed.",
3182
5471
  usageExample: {
3183
5472
  tool: "documents.issue_refs",
3184
5473
  args: {
@@ -3189,6 +5478,7 @@ export const EXTENDED_TOOLS = {
3189
5478
  },
3190
5479
  },
3191
5480
  bestPractices: [
5481
+ "Use refs[] for mixed document titles and URLs; exact IDs can still go through ids[].",
3192
5482
  "Start with view=ids for low-token audits, then re-run selected docs with summary/full views.",
3193
5483
  "Provide issueDomains to reduce non-issue URL noise and keep outputs focused.",
3194
5484
  "Tune keyPattern when your tracker uses custom issue key formats.",
@@ -3217,6 +5507,65 @@ export const EXTENDED_TOOLS = {
3217
5507
  ],
3218
5508
  handler: documentsIssueRefReportTool,
3219
5509
  },
5510
+ "documents.attachments": {
5511
+ signature:
5512
+ "documents.attachments(args: { id?: string; documentId?: string; refs?: string[]; query?: string; queries?: string[]; url?: string; urlId?: string; urlIds?: string[]; urls?: string[]; shareId?: string; shareIds?: string[]; maxAttempts?: number })",
5513
+ description:
5514
+ "Extract embedded Outline attachment references from a document body, including images rendered through /api/attachments.redirect, resolving remembered document refs when needed.",
5515
+ usageExample: {
5516
+ tool: "documents.attachments",
5517
+ args: {
5518
+ query: "example title",
5519
+ },
5520
+ },
5521
+ bestPractices: [
5522
+ "Pass query, refs, url, urlId, or shareId directly when you need to enumerate embedded images or file links without a separate document open step.",
5523
+ "Use strict=true defaults for remembered titles so weak fuzzy matches return a structured miss instead of guessing.",
5524
+ "Follow with attachments.download or documents.download_attachments to save files locally.",
5525
+ ],
5526
+ handler: documentsAttachmentsTool,
5527
+ },
5528
+ "attachments.download": {
5529
+ signature:
5530
+ "attachments.download(args: { id?: string; attachmentId?: string; url?: string; path?: string; outputDir?: string; filePath?: string; fileName?: string; overwrite?: boolean; maxAttempts?: number })",
5531
+ description:
5532
+ "Download one Outline attachment or embedded image through the authenticated attachments.redirect endpoint and save it locally.",
5533
+ usageExample: {
5534
+ tool: "attachments.download",
5535
+ args: {
5536
+ id: "15831936-7fef-4a58-b17b-121a65c3d787",
5537
+ outputDir: "./outline-attachments",
5538
+ overwrite: true,
5539
+ },
5540
+ },
5541
+ bestPractices: [
5542
+ "Prefer id for deterministic downloads; url/path may be an /api/attachments.redirect?id=... value copied from document markdown.",
5543
+ "Use outputDir for generated names or filePath when the caller needs an exact path.",
5544
+ "Inspect returned sha256, bytes, and contentType before handing the file to downstream tools.",
5545
+ ],
5546
+ handler: attachmentsDownloadTool,
5547
+ },
5548
+ "documents.download_attachments": {
5549
+ signature:
5550
+ "documents.download_attachments(args: { id?: string; documentId?: string; refs?: string[]; query?: string; queries?: string[]; url?: string; urlId?: string; urlIds?: string[]; urls?: string[]; shareId?: string; shareIds?: string[]; outputDir?: string; overwrite?: boolean; concurrency?: number; maxAttempts?: number })",
5551
+ description:
5552
+ "Resolve a document, extract all embedded Outline attachment references, and save each referenced file locally.",
5553
+ usageExample: {
5554
+ tool: "documents.download_attachments",
5555
+ args: {
5556
+ query: "example title",
5557
+ outputDir: "./outline-attachments",
5558
+ overwrite: true,
5559
+ },
5560
+ },
5561
+ bestPractices: [
5562
+ "Run documents.attachments first when you only need metadata or want to choose a subset.",
5563
+ "Pass query, refs, url, urlId, or shareId directly when the agent has a remembered document title or pasted URL.",
5564
+ "Keep concurrency modest for large image-heavy documents to avoid rate limits.",
5565
+ "Use overwrite=true for repeatable automation into a scratch directory.",
5566
+ ],
5567
+ handler: documentsDownloadAttachmentsTool,
5568
+ },
3220
5569
  "documents.import_file": {
3221
5570
  signature:
3222
5571
  "documents.import_file(args: { filePath: string; collectionId?: string; parentDocumentId?: string; publish?: boolean; contentType?: string; includePolicies?: boolean; maxAttempts?: number; performAction?: boolean; ...endpointArgs })",
@@ -3239,15 +5588,16 @@ export const EXTENDED_TOOLS = {
3239
5588
  handler: documentsImportFileTool,
3240
5589
  },
3241
5590
  "templates.extract_placeholders": {
3242
- signature: "templates.extract_placeholders(args: { id: string; maxAttempts?: number })",
3243
- description: "Extract sorted unique placeholder keys ({{key}}) from template text nodes.",
5591
+ signature: "templates.extract_placeholders(args: { id?: string; templateQuery?: string; refs?: string[]; refresh?: boolean; maxAttempts?: number })",
5592
+ description: "Resolve a template by ID or remembered name and extract sorted unique placeholder keys ({{key}}) from template text nodes.",
3244
5593
  usageExample: {
3245
5594
  tool: "templates.extract_placeholders",
3246
5595
  args: {
3247
- id: "template-id",
5596
+ templateQuery: "incident postmortem",
3248
5597
  },
3249
5598
  },
3250
5599
  bestPractices: [
5600
+ "Pass templateQuery/templateRef/refs when the user names a template but exact ID is unknown.",
3251
5601
  "Run this before document creation to validate required placeholder keys.",
3252
5602
  "Use counts to catch repeated placeholders for deterministic pipeline checks.",
3253
5603
  ],
@@ -3255,13 +5605,13 @@ export const EXTENDED_TOOLS = {
3255
5605
  },
3256
5606
  "documents.create_from_template": {
3257
5607
  signature:
3258
- "documents.create_from_template(args: { templateId: string; title?: string; collectionId?: string; parentDocumentId?: string; publish?: boolean; placeholderValues?: Record<string,string>; strictPlaceholders?: boolean; view?: 'summary'|'full'; includePolicies?: boolean; maxAttempts?: number; performAction?: boolean })",
5608
+ "documents.create_from_template(args: { templateId?: string; templateQuery?: string; refs?: string[]; title?: string; collectionId?: string; parentDocumentId?: string; publish?: boolean; placeholderValues?: Record<string,string>; strictPlaceholders?: boolean; view?: 'summary'|'full'; includePolicies?: boolean; maxAttempts?: number; performAction?: boolean })",
3259
5609
  description:
3260
5610
  "Create from template, optionally inject placeholder values, and enforce strict unresolved-placeholder safety.",
3261
5611
  usageExample: {
3262
5612
  tool: "documents.create_from_template",
3263
5613
  args: {
3264
- templateId: "template-id",
5614
+ templateQuery: "incident postmortem",
3265
5615
  title: "Service A - Incident Postmortem",
3266
5616
  placeholderValues: {
3267
5617
  service_name: "Service A",
@@ -3273,6 +5623,7 @@ export const EXTENDED_TOOLS = {
3273
5623
  },
3274
5624
  },
3275
5625
  bestPractices: [
5626
+ "Pass templateQuery/templateRef/refs when only the template name is known; local memory can resolve and refresh the template in the same call.",
3276
5627
  "Keep strictPlaceholders=true in automation to prevent publishing unresolved template tokens.",
3277
5628
  "Provide placeholderValues as exact key-value strings and inspect unresolvedCount on every run.",
3278
5629
  "This tool is action-gated; set performAction=true only for explicitly confirmed mutations.",
@@ -3281,18 +5632,19 @@ export const EXTENDED_TOOLS = {
3281
5632
  },
3282
5633
  "comments.review_queue": {
3283
5634
  signature:
3284
- "comments.review_queue(args: { documentIds?: string[]; collectionId?: string; includeAnchorText?: boolean; includeReplies?: boolean; limitPerDocument?: number; view?: 'summary'|'full'; maxAttempts?: number })",
3285
- description: "Build a deterministic comment review queue from comments.list responses.",
5635
+ "comments.review_queue(args: { documentIds?: string[]; documentId?: string; refs?: string[]; query?: string; queries?: string[]; shareId?: string; shareIds?: string[]; urlId?: string; urlIds?: string[]; url?: string; urls?: string[]; collectionId?: string; collectionQuery?: string; collectionRefId?: string; collectionUrlId?: string; collectionUrl?: string; includeAnchorText?: boolean; includeReplies?: boolean; limitPerDocument?: number; view?: 'summary'|'full'; maxAttempts?: number })",
5636
+ description: "Build a deterministic comment review queue from comments.list responses, resolving remembered document or collection references when needed.",
3286
5637
  usageExample: {
3287
5638
  tool: "comments.review_queue",
3288
5639
  args: {
3289
- documentIds: ["doc-1", "doc-2"],
5640
+ refs: ["incident runbook", "https://handbook.example.com/doc/oncall-escalation-AbCdEf12"],
3290
5641
  includeReplies: true,
3291
5642
  limitPerDocument: 20,
3292
5643
  },
3293
5644
  },
3294
5645
  bestPractices: [
3295
- "Scope to explicit documentIds whenever possible for predictable queue size.",
5646
+ "Use explicit documentIds for maximum predictability, or pass refs/query/url when the agent only has a remembered title or pasted Outline URL.",
5647
+ "Use collectionQuery, collectionRefId, collectionUrlId, or collectionUrl when the review queue should cover a remembered collection without a separate collections.open turn.",
3296
5648
  "Use includeReplies=true to capture full threaded review context.",
3297
5649
  "Treat truncated=true as a signal to re-run with a higher limitPerDocument.",
3298
5650
  ],