@khanglvm/outline-cli 0.1.7 → 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.
@@ -5,6 +5,7 @@ import { ApiError, CliError } from "./errors.js";
5
5
  import { assertPerformAction } from "./action-gate.js";
6
6
  import { defaultTmpDir } from "./config-store.js";
7
7
  import { compactValue, ensureStringArray, mapLimit, sanitizeFileToken, toInteger } from "./utils.js";
8
+ import { collectionsOpenBatchTool, collectionsOpenTool, documentsOpenBatchTool, memoryResolveTool } from "./memory-store.js";
8
9
 
9
10
  const CONTROL_ARG_KEYS = new Set([
10
11
  "performAction",
@@ -16,6 +17,116 @@ const CONTROL_ARG_KEYS = new Set([
16
17
  "compact",
17
18
  ]);
18
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
+
19
130
  function maybeDropPolicies(payload, includePolicies) {
20
131
  if (includePolicies) {
21
132
  return payload;
@@ -162,10 +273,74 @@ function extractAttachmentRefsFromText(text, baseUrl = "") {
162
273
  }
163
274
 
164
275
  async function readDocumentForAttachments(ctx, args = {}) {
165
- const id = args.id || args.documentId || extractDocumentUrlId(args.url);
276
+ const urlId = args.urlId || extractDocumentUrlId(args.url);
277
+ const id = args.id || args.documentId || urlId;
166
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
+
167
342
  if (!id && !shareId) {
168
- throw new CliError("document attachment tools require args.id, args.documentId, args.url, or args.shareId");
343
+ throw new CliError("document attachment tools require args.id, args.documentId, args.url, args.shareId, or document refs");
169
344
  }
170
345
 
171
346
  const body = compactValue({ id, shareId }) || {};
@@ -176,7 +351,16 @@ async function readDocumentForAttachments(ctx, args = {}) {
176
351
  if (!doc) {
177
352
  throw new CliError("documents.info response did not include document data");
178
353
  }
179
- return doc;
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
+ };
180
364
  }
181
365
 
182
366
  function summarizeAttachmentDocument(doc) {
@@ -251,6 +435,65 @@ async function downloadAttachmentToFile(ctx, args = {}, id, index = null) {
251
435
  }
252
436
 
253
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
+ }
254
497
  if (def.tool === "documents.empty_trash") {
255
498
  return def.mutating ? { performAction: true } : {};
256
499
  }
@@ -270,7 +513,7 @@ function defaultUsageArgs(def) {
270
513
  }
271
514
  if (def.tool === "shares.create") {
272
515
  return {
273
- documentId: "document-id",
516
+ documentQuery: "incident runbook",
274
517
  performAction: true,
275
518
  };
276
519
  }
@@ -356,6 +599,410 @@ function defaultUsageArgs(def) {
356
599
  };
357
600
  }
358
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
+
359
1006
  function makeRpcHandler(def) {
360
1007
  return async function rpcHandler(ctx, args = {}) {
361
1008
  if (def.mutating) {
@@ -366,7 +1013,50 @@ function makeRpcHandler(def) {
366
1013
  }
367
1014
 
368
1015
  const maxAttempts = toInteger(args.maxAttempts, def.mutating ? 1 : 2);
369
- 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
+ );
370
1060
  let res;
371
1061
  try {
372
1062
  res = await ctx.client.call(def.method, body, { maxAttempts });
@@ -392,55 +1082,312 @@ function makeRpcHandler(def) {
392
1082
  }
393
1083
  }
394
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
+
395
1091
  return {
396
1092
  tool: def.tool,
397
1093
  profile: ctx.profile.id,
398
- 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),
399
1101
  };
400
1102
  };
401
1103
  }
402
1104
 
403
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
+ ];
404
1143
  return {
405
- signature: `${def.tool}(args?: { ...endpointArgs; includePolicies?: boolean; maxAttempts?: number${
406
- def.mutating ? "; performAction?: boolean" : ""
407
- } })`,
1144
+ signature,
408
1145
  description: def.description,
409
- usageExample: {
1146
+ usageExample: def.usageExample || {
410
1147
  tool: def.tool,
411
1148
  args: defaultUsageArgs(def),
412
1149
  },
413
- bestPractices: [
414
- "Prefer minimal payloads to keep responses deterministic and token-efficient.",
415
- ...(def.mutating
416
- ? ["This tool is action-gated; set performAction=true only for explicitly confirmed mutations."]
417
- : ["Use includePolicies=true only when policy details are required."]),
418
- ],
1150
+ bestPractices,
419
1151
  handler: makeRpcHandler(def),
420
1152
  };
421
1153
  }
422
1154
 
423
1155
  const RPC_WRAPPER_DEFS = [
424
- { tool: "shares.list", method: "shares.list", description: "List shares." },
425
- { tool: "shares.info", method: "shares.info", description: "Get share details." },
426
- { 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
+ },
427
1213
  { tool: "shares.update", method: "shares.update", description: "Update a share.", mutating: true },
428
1214
  { tool: "shares.revoke", method: "shares.revoke", description: "Revoke a share.", mutating: true },
429
- { tool: "templates.list", method: "templates.list", description: "List templates." },
430
- { 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
+ },
431
1241
  { tool: "templates.create", method: "templates.create", description: "Create a template.", mutating: true },
432
- { tool: "templates.update", method: "templates.update", description: "Update a template.", mutating: true },
433
- { tool: "templates.delete", method: "templates.delete", description: "Delete a template.", mutating: true },
434
- { tool: "templates.restore", method: "templates.restore", description: "Restore a template.", mutating: true },
435
- { 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
+ },
436
1298
  { tool: "documents.templatize", method: "documents.templatize", description: "Convert a document into a template.", mutating: true },
437
1299
  { tool: "documents.import", method: "documents.import", description: "Import a document from JSON payload.", mutating: true },
438
- { 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
+ },
439
1313
  { tool: "comments.info", method: "comments.info", description: "Get comment details." },
440
- { 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
+ },
441
1344
  { tool: "comments.update", method: "comments.update", description: "Update a comment.", mutating: true },
442
1345
  { tool: "comments.delete", method: "comments.delete", description: "Delete a comment.", mutating: true },
443
- { 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
+ },
444
1391
  { tool: "oauth_clients.list", method: "oauthClients.list", description: "List OAuth clients." },
445
1392
  { tool: "oauth_clients.info", method: "oauthClients.info", description: "Get OAuth client details." },
446
1393
  { tool: "oauth_clients.create", method: "oauthClients.create", description: "Create an OAuth client.", mutating: true },
@@ -481,8 +1428,32 @@ const RPC_WRAPPER_DEFS = [
481
1428
  { tool: "data_attributes.update", method: "dataAttributes.update", description: "Update a data attribute.", mutating: true },
482
1429
  { tool: "data_attributes.delete", method: "dataAttributes.delete", description: "Delete a data attribute.", mutating: true },
483
1430
  { tool: "revisions.info", method: "revisions.info", description: "Get revision details." },
484
- { tool: "documents.archived", method: "documents.archived", description: "List archived documents." },
485
- { 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
+ },
486
1457
  { tool: "documents.archive", method: "documents.archive", description: "Archive a document.", mutating: true },
487
1458
  { tool: "documents.restore", method: "documents.restore", description: "Restore a document.", mutating: true },
488
1459
  {
@@ -498,7 +1469,16 @@ const RPC_WRAPPER_DEFS = [
498
1469
  { tool: "webhooks.update", method: "webhooks.update", description: "Update a webhook.", mutating: true },
499
1470
  { tool: "webhooks.delete", method: "webhooks.delete", description: "Delete a webhook.", mutating: true },
500
1471
  { tool: "users.list", method: "users.list", description: "List users." },
501
- { 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
+ },
502
1482
  { tool: "users.invite", method: "users.invite", description: "Invite a user.", mutating: true },
503
1483
  {
504
1484
  tool: "users.update_role",
@@ -509,105 +1489,640 @@ const RPC_WRAPPER_DEFS = [
509
1489
  { tool: "users.activate", method: "users.activate", description: "Activate a user.", mutating: true },
510
1490
  { tool: "users.suspend", method: "users.suspend", description: "Suspend a user.", mutating: true },
511
1491
  { tool: "groups.list", method: "groups.list", description: "List groups." },
512
- { tool: "groups.info", method: "groups.info", description: "Get group details." },
513
- { 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
+ },
514
1511
  { tool: "groups.create", method: "groups.create", description: "Create a group.", mutating: true },
515
1512
  { tool: "groups.update", method: "groups.update", description: "Update a group.", mutating: true },
516
1513
  { tool: "groups.delete", method: "groups.delete", description: "Delete a group.", mutating: true },
517
- { tool: "groups.add_user", method: "groups.add_user", description: "Add a user to a group.", mutating: true },
518
- { tool: "groups.remove_user", method: "groups.remove_user", description: "Remove a user from a group.", mutating: true },
519
- { tool: "collections.memberships", method: "collections.memberships", description: "List collection user memberships." },
520
- { tool: "collections.group_memberships", method: "collections.group_memberships", description: "List collection group memberships." },
521
- { tool: "collections.add_user", method: "collections.add_user", description: "Add a user to a collection.", mutating: true },
522
- { tool: "collections.remove_user", method: "collections.remove_user", description: "Remove a user from a collection.", mutating: true },
523
- { tool: "collections.add_group", method: "collections.add_group", description: "Add a group to a collection.", mutating: true },
524
- { tool: "collections.remove_group", method: "collections.remove_group", description: "Remove a group from a collection.", mutating: true },
525
- { tool: "documents.users", method: "documents.users", description: "List users with access to a document." },
526
- { tool: "documents.memberships", method: "documents.memberships", description: "List document user memberships." },
527
- { tool: "documents.group_memberships", method: "documents.group_memberships", description: "List document group memberships." },
528
- { tool: "documents.add_user", method: "documents.add_user", description: "Add a user to a document.", mutating: true },
529
- { tool: "documents.remove_user", method: "documents.remove_user", description: "Remove a user from a document.", mutating: true },
530
- { tool: "documents.add_group", method: "documents.add_group", description: "Add a group to a document.", mutating: true },
531
- { 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
+ },
532
1708
  { tool: "file_operations.list", method: "fileOperations.list", description: "List file operations." },
533
1709
  { tool: "file_operations.info", method: "fileOperations.info", description: "Get file operation details." },
534
1710
  { tool: "file_operations.delete", method: "fileOperations.delete", description: "Delete a file operation.", mutating: true },
535
1711
  ];
536
1712
 
537
- const RPC_TOOLS = Object.fromEntries(
538
- RPC_WRAPPER_DEFS.map((def) => [
539
- def.tool,
540
- makeRpcContract({
541
- ...def,
542
- mutating: !!def.mutating,
543
- }),
544
- ])
545
- );
1713
+ const RPC_TOOLS = Object.fromEntries(
1714
+ RPC_WRAPPER_DEFS.map((def) => [
1715
+ def.tool,
1716
+ makeRpcContract({
1717
+ ...def,
1718
+ mutating: !!def.mutating,
1719
+ }),
1720
+ ])
1721
+ );
1722
+
1723
+ function parseQuestionItem(raw, index) {
1724
+ if (typeof raw === "string") {
1725
+ const question = raw.trim();
1726
+ if (!question) {
1727
+ throw new CliError(`questions[${index}] must not be empty`);
1728
+ }
1729
+ return {
1730
+ question,
1731
+ body: {},
1732
+ documentId: null,
1733
+ };
1734
+ }
1735
+
1736
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
1737
+ const question = String(raw.question ?? raw.query ?? "").trim();
1738
+ if (!question) {
1739
+ throw new CliError(`questions[${index}].question is required`);
1740
+ }
1741
+ const body = buildBody(raw, ["question", "query"]);
1742
+ return {
1743
+ question,
1744
+ body,
1745
+ documentId: body.id || body.documentId || null,
1746
+ };
1747
+ }
1748
+
1749
+ throw new CliError(`questions[${index}] must be string or object`);
1750
+ }
1751
+
1752
+ function isAnswerEndpointUnsupported(err) {
1753
+ if (!(err instanceof ApiError)) {
1754
+ return false;
1755
+ }
1756
+ if (err.details?.status !== 404) {
1757
+ return false;
1758
+ }
1759
+ const url = String(err.details?.url || "").toLowerCase();
1760
+ const message = String(err.message || "").toLowerCase();
1761
+ return url.includes("documents.answerquestion") || message.includes("answerquestion");
1762
+ }
1763
+
1764
+ function normalizeFallbackAnswerHit(row, contextChars = 220) {
1765
+ const doc = row?.document || row || {};
1766
+ const context = typeof row?.context === "string" ? row.context : "";
1767
+ return compactValue({
1768
+ id: doc.id,
1769
+ title: doc.title,
1770
+ collectionId: doc.collectionId,
1771
+ parentDocumentId: doc.parentDocumentId,
1772
+ updatedAt: doc.updatedAt,
1773
+ publishedAt: doc.publishedAt,
1774
+ urlId: doc.urlId,
1775
+ ranking: row?.ranking,
1776
+ context: context.length > contextChars ? `${context.slice(0, contextChars)}...` : context,
1777
+ });
1778
+ }
1779
+
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
+ }
546
1911
 
547
- function parseQuestionItem(raw, index) {
548
- if (typeof raw === "string") {
549
- const question = raw.trim();
550
- if (!question) {
551
- throw new CliError(`questions[${index}] must not be empty`);
552
- }
553
- return {
554
- question,
555
- body: {},
556
- documentId: null,
557
- };
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;
558
1919
  }
559
1920
 
560
- if (raw && typeof raw === "object" && !Array.isArray(raw)) {
561
- const question = String(raw.question ?? raw.query ?? "").trim();
562
- if (!question) {
563
- throw new CliError(`questions[${index}].question is required`);
564
- }
565
- const body = buildBody(raw, ["question", "query"]);
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) {
566
1947
  return {
567
- question,
568
- body,
569
- documentId: body.id || body.documentId || null,
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 },
570
1960
  };
571
1961
  }
572
1962
 
573
- throw new CliError(`questions[${index}] must be string or object`);
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
+ };
574
1983
  }
575
1984
 
576
- function isAnswerEndpointUnsupported(err) {
577
- if (!(err instanceof ApiError)) {
578
- return false;
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 };
579
2037
  }
580
- if (err.details?.status !== 404) {
581
- return false;
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 };
582
2048
  }
583
- const url = String(err.details?.url || "").toLowerCase();
584
- const message = String(err.message || "").toLowerCase();
585
- return url.includes("documents.answerquestion") || message.includes("answerquestion");
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
+ };
586
2067
  }
587
2068
 
588
- function normalizeFallbackAnswerHit(row, contextChars = 220) {
589
- const doc = row?.document || row || {};
590
- const context = typeof row?.context === "string" ? row.context : "";
591
- return compactValue({
592
- id: doc.id,
593
- title: doc.title,
594
- collectionId: doc.collectionId,
595
- parentDocumentId: doc.parentDocumentId,
596
- updatedAt: doc.updatedAt,
597
- publishedAt: doc.publishedAt,
598
- urlId: doc.urlId,
599
- ranking: row?.ranking,
600
- context: context.length > contextChars ? `${context.slice(0, contextChars)}...` : context,
601
- });
2069
+ function buildAnswerEndpointBody(args = {}, question) {
2070
+ return {
2071
+ ...buildBody(args, ["question", "query", "limit", ...ANSWER_RESOLVE_ARG_KEYS]),
2072
+ query: question,
2073
+ };
602
2074
  }
603
2075
 
604
- async function buildAnswerFallbackResult(ctx, question, args = {}) {
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 = {}) {
605
2092
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 2));
606
2093
  const contextChars = Math.max(80, toInteger(args.contextChars, 220));
607
2094
  const limit = Math.max(1, Math.min(8, toInteger(args.limit, 5)));
608
2095
  const scopedDocumentId = args.documentId || args.id;
609
2096
 
610
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
+
611
2126
  const res = await ctx.client.call("documents.info", { id: scopedDocumentId }, { maxAttempts });
612
2127
  const document = normalizeFallbackAnswerHit(res.body?.data, contextChars);
613
2128
  return {
@@ -625,6 +2140,7 @@ async function buildAnswerFallbackResult(ctx, question, args = {}) {
625
2140
  }),
626
2141
  },
627
2142
  documents: document ? [document] : [],
2143
+ resolution: prepared.resolution,
628
2144
  retrieval: {
629
2145
  query: question,
630
2146
  result: compactValue({
@@ -673,6 +2189,7 @@ async function buildAnswerFallbackResult(ctx, question, args = {}) {
673
2189
  }),
674
2190
  },
675
2191
  documents,
2192
+ resolution: prepared.resolution,
676
2193
  retrieval: {
677
2194
  query: question,
678
2195
  result: compactValue({
@@ -689,10 +2206,12 @@ async function documentsAnswerTool(ctx, args = {}) {
689
2206
  throw new CliError("documents.answer requires args.question or args.query");
690
2207
  }
691
2208
 
692
- const body = {
693
- ...buildBody(args, ["question", "query", "limit"]),
694
- query: question,
695
- };
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);
696
2215
 
697
2216
  try {
698
2217
  const res = await ctx.client.call("documents.answerQuestion", body, {
@@ -705,8 +2224,8 @@ async function documentsAnswerTool(ctx, args = {}) {
705
2224
  profile: ctx.profile.id,
706
2225
  result:
707
2226
  payload && typeof payload === "object"
708
- ? { question, ...payload }
709
- : { question, data: payload },
2227
+ ? compactValue({ question, resolution: prepared.resolution, ...payload }) || { question, ...payload }
2228
+ : { question, resolution: prepared.resolution, data: payload },
710
2229
  };
711
2230
  } catch (err) {
712
2231
  if (!isAnswerEndpointUnsupported(err)) {
@@ -716,7 +2235,7 @@ async function documentsAnswerTool(ctx, args = {}) {
716
2235
  return {
717
2236
  tool: "documents.answer",
718
2237
  profile: ctx.profile.id,
719
- result: await buildAnswerFallbackResult(ctx, question, args),
2238
+ result: await buildAnswerFallbackResult(ctx, question, prepared.args, prepared),
720
2239
  };
721
2240
  }
722
2241
  }
@@ -734,20 +2253,34 @@ async function documentsAnswerBatchTool(ctx, args = {}) {
734
2253
  throw new CliError("documents.answer_batch requires args.question or args.questions[]");
735
2254
  }
736
2255
 
737
- const baseBody = buildBody(args, ["question", "questions", "query", "concurrency", "limit"]);
2256
+ const basePrepared = await resolveAnswerScope(ctx, args);
738
2257
  const includePolicies = !!args.includePolicies;
739
2258
  const maxAttempts = toInteger(args.maxAttempts, 2);
740
2259
  const concurrency = Math.max(1, Math.min(10, toInteger(args.concurrency, 3)));
741
2260
 
742
2261
  const items = await mapLimit(rawItems, concurrency, async (raw, index) => {
743
2262
  let parsed;
2263
+ let prepared;
744
2264
  try {
745
2265
  parsed = parseQuestionItem(raw, index);
746
- const body = {
747
- ...baseBody,
748
- ...parsed.body,
749
- query: parsed.question,
750
- };
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);
751
2284
  const res = await ctx.client.call("documents.answerQuestion", body, {
752
2285
  maxAttempts,
753
2286
  });
@@ -756,21 +2289,32 @@ async function documentsAnswerBatchTool(ctx, args = {}) {
756
2289
  index,
757
2290
  ok: true,
758
2291
  question: parsed.question,
759
- documentId: parsed.documentId,
760
- result: payload,
2292
+ documentId: body.documentId || parsed.documentId,
2293
+ result: compactValue({ resolution: prepared.resolution, ...payload }) || payload,
761
2294
  };
762
2295
  } catch (err) {
763
2296
  if (parsed && isAnswerEndpointUnsupported(err)) {
764
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;
765
2312
  return {
766
2313
  index,
767
2314
  ok: true,
768
2315
  question: parsed.question,
769
- documentId: parsed.documentId,
770
- result: await buildAnswerFallbackResult(ctx, parsed.question, {
771
- ...args,
772
- ...parsed.body,
773
- }),
2316
+ documentId: fallbackArgs.documentId || parsed.documentId,
2317
+ result: await buildAnswerFallbackResult(ctx, parsed.question, fallbackArgs, prepared),
774
2318
  };
775
2319
  } catch (fallbackErr) {
776
2320
  if (fallbackErr instanceof ApiError || fallbackErr instanceof CliError) {
@@ -815,14 +2359,31 @@ async function documentsAnswerBatchTool(ctx, args = {}) {
815
2359
  }
816
2360
 
817
2361
  async function documentsAttachmentsTool(ctx, args = {}) {
818
- const doc = await readDocumentForAttachments(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
+ }
819
2378
  const attachments = extractAttachmentRefsFromText(doc.text || "", ctx.profile?.baseUrl);
820
2379
 
821
2380
  return {
822
2381
  tool: "documents.attachments",
823
2382
  profile: ctx.profile.id,
824
2383
  result: {
2384
+ ok: true,
825
2385
  document: summarizeAttachmentDocument(doc),
2386
+ resolution: read.resolution,
826
2387
  total: attachments.length,
827
2388
  attachments,
828
2389
  },
@@ -843,7 +2404,25 @@ async function attachmentsDownloadTool(ctx, args = {}) {
843
2404
  }
844
2405
 
845
2406
  async function documentsDownloadAttachmentsTool(ctx, args = {}) {
846
- const doc = await readDocumentForAttachments(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
+ }
847
2426
  const attachments = extractAttachmentRefsFromText(doc.text || "", ctx.profile?.baseUrl);
848
2427
  const concurrency = Math.max(1, Math.min(8, toInteger(args.concurrency, 3)));
849
2428
  const items = await mapLimit(attachments, concurrency, async (attachment, index) => {
@@ -871,7 +2450,9 @@ async function documentsDownloadAttachmentsTool(ctx, args = {}) {
871
2450
  tool: "documents.download_attachments",
872
2451
  profile: ctx.profile.id,
873
2452
  result: {
2453
+ ok: failed === 0,
874
2454
  document: summarizeAttachmentDocument(doc),
2455
+ resolution: read.resolution,
875
2456
  total: attachments.length,
876
2457
  succeeded: items.length - failed,
877
2458
  failed,
@@ -1289,12 +2870,239 @@ function normalizeGraphSourceIds(args = {}) {
1289
2870
  if (args.id !== undefined && args.id !== null) {
1290
2871
  values.push(args.id);
1291
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
+ }
1292
2879
  for (const id of ensureStringArray(args.ids, "ids") || []) {
1293
2880
  values.push(id);
1294
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
+ }
1295
2888
  return uniqueStrings(values).sort(compareIdAsc);
1296
2889
  }
1297
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
+
1298
3106
  function normalizeGraphSearchQueries(value) {
1299
3107
  return uniqueStrings(ensureStringArray(value, "searchQueries") || []);
1300
3108
  }
@@ -2137,9 +3945,19 @@ async function collectGraphNeighbors(ctx, sourceIds, options = {}) {
2137
3945
  }
2138
3946
 
2139
3947
  async function documentsBacklinksTool(ctx, args = {}) {
2140
- const id = String(args.id || "").trim();
3948
+ const resolved = await resolveDocumentIdsForRead(ctx, args);
3949
+ const id = resolved.ids[0] || "";
2141
3950
  if (!id) {
2142
- 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
+ };
2143
3961
  }
2144
3962
 
2145
3963
  const view = normalizeGraphView(args.view);
@@ -2165,6 +3983,13 @@ async function documentsBacklinksTool(ctx, args = {}) {
2165
3983
  };
2166
3984
  }
2167
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
+ }) || {};
2168
3993
 
2169
3994
  return {
2170
3995
  tool: "documents.backlinks",
@@ -2174,9 +3999,24 @@ async function documentsBacklinksTool(ctx, args = {}) {
2174
3999
  }
2175
4000
 
2176
4001
  async function documentsGraphNeighborsTool(ctx, args = {}) {
2177
- const sourceIds = normalizeGraphSourceIds(args);
4002
+ const resolved = await resolveDocumentIdsForRead(ctx, args);
4003
+ const sourceIds = resolved.ids;
2178
4004
  if (sourceIds.length === 0) {
2179
- 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
+ };
2180
4020
  }
2181
4021
 
2182
4022
  const includeBacklinks = args.includeBacklinks !== false;
@@ -2202,12 +4042,16 @@ async function documentsGraphNeighborsTool(ctx, args = {}) {
2202
4042
 
2203
4043
  const nodes = buildGraphNodeList(collected.nodesById, view);
2204
4044
  const edges = sortGraphEdges(collected.edges);
4045
+ const resolution = resolved.resolution.resolved.length > 0 || resolved.resolution.failed.length > 0
4046
+ ? resolved.resolution
4047
+ : undefined;
2205
4048
 
2206
4049
  return {
2207
4050
  tool: "documents.graph_neighbors",
2208
4051
  profile: ctx.profile.id,
2209
4052
  result: {
2210
4053
  sourceIds,
4054
+ ...(resolution ? { resolution } : {}),
2211
4055
  includeBacklinks,
2212
4056
  includeSearchNeighbors,
2213
4057
  searchQueries,
@@ -2222,9 +4066,32 @@ async function documentsGraphNeighborsTool(ctx, args = {}) {
2222
4066
  }
2223
4067
 
2224
4068
  async function documentsGraphReportTool(ctx, args = {}) {
2225
- const requestedSeedIds = uniqueStrings(ensureStringArray(args.seedIds, "seedIds") || []).sort(compareIdAsc);
4069
+ const resolved = await resolveDocumentIdsForRead(ctx, args);
4070
+ const requestedSeedIds = resolved.ids;
2226
4071
  if (requestedSeedIds.length === 0) {
2227
- 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
+ };
2228
4095
  }
2229
4096
 
2230
4097
  const includeBacklinks = args.includeBacklinks !== false;
@@ -2323,6 +4190,9 @@ async function documentsGraphReportTool(ctx, args = {}) {
2323
4190
  (edge) => allowedIds.has(edge.sourceId) && allowedIds.has(edge.targetId)
2324
4191
  )
2325
4192
  );
4193
+ const resolution = resolved.resolution.resolved.length > 0 || resolved.resolution.failed.length > 0
4194
+ ? resolved.resolution
4195
+ : undefined;
2326
4196
 
2327
4197
  return {
2328
4198
  tool: "documents.graph_report",
@@ -2330,6 +4200,7 @@ async function documentsGraphReportTool(ctx, args = {}) {
2330
4200
  result: {
2331
4201
  seedIds,
2332
4202
  requestedSeedCount: requestedSeedIds.length,
4203
+ ...(resolution ? { resolution } : {}),
2333
4204
  depth,
2334
4205
  exploredDepth,
2335
4206
  maxNodes,
@@ -2347,9 +4218,27 @@ async function documentsGraphReportTool(ctx, args = {}) {
2347
4218
  }
2348
4219
 
2349
4220
  async function documentsIssueRefsTool(ctx, args = {}) {
2350
- const ids = normalizeIssueRefIds(args);
4221
+ const resolved = await resolveDocumentIdsForRead(ctx, args);
4222
+ const ids = resolved.ids;
2351
4223
  if (ids.length === 0) {
2352
- 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
+ };
2353
4242
  }
2354
4243
 
2355
4244
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 2));
@@ -2361,12 +4250,16 @@ async function documentsIssueRefsTool(ctx, args = {}) {
2361
4250
  maxAttempts,
2362
4251
  view,
2363
4252
  });
4253
+ const resolution = resolved.resolution.resolved.length > 0 || resolved.resolution.failed.length > 0
4254
+ ? resolved.resolution
4255
+ : undefined;
2364
4256
 
2365
4257
  return {
2366
4258
  tool: "documents.issue_refs",
2367
4259
  profile: ctx.profile.id,
2368
4260
  result: {
2369
4261
  requestedIds: extracted.requestedIds,
4262
+ ...(resolution ? { resolution } : {}),
2370
4263
  issueDomains: extracted.issueDomains,
2371
4264
  keyPattern: extracted.keyPattern,
2372
4265
  ...extracted.summary,
@@ -2408,10 +4301,40 @@ async function documentsIssueRefReportTool(ctx, args = {}) {
2408
4301
  };
2409
4302
  }
2410
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
+
2411
4325
  async function templatesExtractPlaceholdersTool(ctx, args = {}) {
2412
- 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();
2413
4336
  if (!id) {
2414
- throw new CliError("templates.extract_placeholders requires args.id");
4337
+ throw new CliError("templates.extract_placeholders requires args.id or args.templateQuery");
2415
4338
  }
2416
4339
 
2417
4340
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 2));
@@ -2425,7 +4348,9 @@ async function templatesExtractPlaceholdersTool(ctx, args = {}) {
2425
4348
  profile: ctx.profile.id,
2426
4349
  result: {
2427
4350
  id: template?.id ? String(template.id) : id,
4351
+ templateId: id,
2428
4352
  title: template?.title ? String(template.title) : "",
4353
+ resolution: resolvedTemplate.resolution,
2429
4354
  placeholders: stats.placeholders,
2430
4355
  counts: stats.countsByPlaceholder,
2431
4356
  meta: {
@@ -2439,16 +4364,25 @@ async function templatesExtractPlaceholdersTool(ctx, args = {}) {
2439
4364
  }
2440
4365
 
2441
4366
  async function documentsCreateFromTemplateTool(ctx, args = {}) {
2442
- const templateId = String(args.templateId || "").trim();
2443
- if (!templateId) {
2444
- throw new CliError("documents.create_from_template requires args.templateId");
2445
- }
2446
-
2447
4367
  assertPerformAction(args, {
2448
4368
  tool: "documents.create_from_template",
2449
4369
  action: "create and optionally update a document from template",
2450
4370
  });
2451
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
+
2452
4386
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 1));
2453
4387
  const view = normalizeTemplatePipelineView(args.view);
2454
4388
  const strictPlaceholders = args.strictPlaceholders === true;
@@ -2482,6 +4416,8 @@ async function documentsCreateFromTemplateTool(ctx, args = {}) {
2482
4416
  strictPlaceholders,
2483
4417
  publishRequested,
2484
4418
  published: publishRequested,
4419
+ templateId,
4420
+ resolution: resolvedTemplate.resolution,
2485
4421
  document: normalizeTemplatePipelineDocument(finalPayload?.data || createdDoc, view),
2486
4422
  placeholders: {
2487
4423
  providedKeys: [],
@@ -2542,6 +4478,8 @@ async function documentsCreateFromTemplateTool(ctx, args = {}) {
2542
4478
  publishRequested,
2543
4479
  published: false,
2544
4480
  safeBehavior: "left_unpublished_draft",
4481
+ templateId,
4482
+ resolution: resolvedTemplate.resolution,
2545
4483
  document: normalizeTemplatePipelineDocument(updatedDoc, view),
2546
4484
  placeholders: {
2547
4485
  providedKeys: providedPlaceholderKeys,
@@ -2587,6 +4525,8 @@ async function documentsCreateFromTemplateTool(ctx, args = {}) {
2587
4525
  strictPlaceholders,
2588
4526
  publishRequested,
2589
4527
  published,
4528
+ templateId,
4529
+ resolution: resolvedTemplate.resolution,
2590
4530
  document: normalizeTemplatePipelineDocument(finalPayload?.data || updatedDoc, view),
2591
4531
  placeholders: {
2592
4532
  providedKeys: providedPlaceholderKeys,
@@ -2849,25 +4789,60 @@ async function listCollectionDocumentIds(ctx, collectionId, maxAttempts) {
2849
4789
  }
2850
4790
 
2851
4791
  async function commentsReviewQueueTool(ctx, args = {}) {
2852
- const explicitIds = uniqueStrings(ensureStringArray(args.documentIds, "documentIds") || []);
2853
- 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;
2854
4801
  const maxAttempts = Math.max(1, toInteger(args.maxAttempts, 2));
2855
4802
  const includeReplies = args.includeReplies !== false;
2856
4803
  const includeAnchorText = !!args.includeAnchorText;
2857
4804
  const limitPerDocument = Math.max(1, Math.min(200, toInteger(args.limitPerDocument, 30)));
2858
4805
  const view = args.view === "full" ? "full" : "summary";
2859
4806
 
2860
- if (explicitIds.length === 0 && !collectionId) {
2861
- 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");
2862
4812
  }
2863
4813
 
2864
- let documentIds = explicitIds;
4814
+ let documentIds = resolvedDocuments.ids;
2865
4815
  let collectionScopeTruncated = false;
2866
4816
  if (documentIds.length === 0 && collectionId) {
2867
4817
  const resolved = await listCollectionDocumentIds(ctx, collectionId, maxAttempts);
2868
4818
  documentIds = resolved.ids;
2869
4819
  collectionScopeTruncated = resolved.truncated;
2870
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
+ }
2871
4846
 
2872
4847
  const perDocument = await mapLimit(documentIds, Math.min(6, Math.max(1, documentIds.length || 1)), async (documentId) => {
2873
4848
  try {
@@ -2940,6 +4915,8 @@ async function commentsReviewQueueTool(ctx, args = {}) {
2940
4915
  scope: {
2941
4916
  documentIds,
2942
4917
  collectionId,
4918
+ ...(documentResolution ? { documentResolution } : {}),
4919
+ ...(collectionResolution ? { collectionResolution } : {}),
2943
4920
  },
2944
4921
  includeReplies,
2945
4922
  includeAnchorText,
@@ -3384,25 +5361,26 @@ export const EXTENDED_TOOLS = {
3384
5361
  ...RPC_TOOLS,
3385
5362
  "documents.answer": {
3386
5363
  signature:
3387
- "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 })",
3388
5365
  description: "Answer a question using Outline AI over the selected document scope.",
3389
5366
  usageExample: {
3390
5367
  tool: "documents.answer",
3391
5368
  args: {
3392
5369
  question: "What changed in our onboarding checklist?",
3393
- collectionId: "collection-id",
5370
+ collectionQuery: "engineering",
3394
5371
  },
3395
5372
  },
3396
5373
  bestPractices: [
3397
5374
  "Use question text that is specific enough to resolve citations quickly.",
3398
- "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.",
3399
5377
  "If the deployment lacks documents.answerQuestion, this wrapper returns fallback retrieval evidence and a concrete search suggestion instead of a raw 404.",
3400
5378
  ],
3401
5379
  handler: documentsAnswerTool,
3402
5380
  },
3403
5381
  "documents.answer_batch": {
3404
5382
  signature:
3405
- "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 })",
3406
5384
  description: "Run multiple documents.answerQuestion calls with per-item isolation.",
3407
5385
  usageExample: {
3408
5386
  tool: "documents.answer_batch",
@@ -3411,12 +5389,13 @@ export const EXTENDED_TOOLS = {
3411
5389
  "Where is the release checklist?",
3412
5390
  "Who owns incident postmortems?",
3413
5391
  ],
3414
- collectionId: "collection-id",
5392
+ collectionQuery: "engineering",
3415
5393
  concurrency: 2,
3416
5394
  },
3417
5395
  },
3418
5396
  bestPractices: [
3419
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.",
3420
5399
  "Use per-item statuses to retry only failures.",
3421
5400
  "Unsupported answer endpoints degrade to per-item retrieval evidence rather than failing the whole batch.",
3422
5401
  ],
@@ -3424,8 +5403,8 @@ export const EXTENDED_TOOLS = {
3424
5403
  },
3425
5404
  "documents.backlinks": {
3426
5405
  signature:
3427
- "documents.backlinks(args: { id: string; limit?: number; offset?: number; sort?: string; direction?: 'ASC'|'DESC'; view?: 'ids'|'summary'|'full'; includePolicies?: boolean; maxAttempts?: number })",
3428
- 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.",
3429
5408
  usageExample: {
3430
5409
  tool: "documents.backlinks",
3431
5410
  args: {
@@ -3435,6 +5414,7 @@ export const EXTENDED_TOOLS = {
3435
5414
  },
3436
5415
  },
3437
5416
  bestPractices: [
5417
+ "Pass query/url/urlId directly when you know the document reference but not its exact ID.",
3438
5418
  "Use view=ids for low-token planning loops, then hydrate specific documents separately.",
3439
5419
  "Use limit/offset pagination for deterministic traversal over large backlink sets.",
3440
5420
  ],
@@ -3442,8 +5422,8 @@ export const EXTENDED_TOOLS = {
3442
5422
  },
3443
5423
  "documents.graph_neighbors": {
3444
5424
  signature:
3445
- "documents.graph_neighbors(args: { id?: string; ids?: string[]; includeBacklinks?: boolean; includeSearchNeighbors?: boolean; searchQueries?: string[]; limitPerSource?: number; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
3446
- 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.",
3447
5427
  usageExample: {
3448
5428
  tool: "documents.graph_neighbors",
3449
5429
  args: {
@@ -3455,6 +5435,7 @@ export const EXTENDED_TOOLS = {
3455
5435
  },
3456
5436
  },
3457
5437
  bestPractices: [
5438
+ "Use refs[] for mixed document titles and URLs; use ids[] when exact document IDs are already known.",
3458
5439
  "Start with a single source id and small limitPerSource, then expand incrementally.",
3459
5440
  "Enable includeSearchNeighbors only when additional semantic neighborhood expansion is needed.",
3460
5441
  ],
@@ -3462,8 +5443,8 @@ export const EXTENDED_TOOLS = {
3462
5443
  },
3463
5444
  "documents.graph_report": {
3464
5445
  signature:
3465
- "documents.graph_report(args: { seedIds: string[]; depth?: number; maxNodes?: number; includeBacklinks?: boolean; includeSearchNeighbors?: boolean; limitPerSource?: number; view?: 'ids'|'summary'|'full'; maxAttempts?: number })",
3466
- 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.",
3467
5448
  usageExample: {
3468
5449
  tool: "documents.graph_report",
3469
5450
  args: {
@@ -3476,6 +5457,7 @@ export const EXTENDED_TOOLS = {
3476
5457
  },
3477
5458
  },
3478
5459
  bestPractices: [
5460
+ "Use seedRefs[] for mixed seed titles and URLs; use seedIds[] when exact document IDs are already known.",
3479
5461
  "Cap maxNodes and depth to keep traversal deterministic and cost-bounded.",
3480
5462
  "Prefer view=ids for graph planning and fetch full nodes only for selected IDs.",
3481
5463
  ],
@@ -3483,9 +5465,9 @@ export const EXTENDED_TOOLS = {
3483
5465
  },
3484
5466
  "documents.issue_refs": {
3485
5467
  signature:
3486
- "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 })",
3487
5469
  description:
3488
- "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.",
3489
5471
  usageExample: {
3490
5472
  tool: "documents.issue_refs",
3491
5473
  args: {
@@ -3496,6 +5478,7 @@ export const EXTENDED_TOOLS = {
3496
5478
  },
3497
5479
  },
3498
5480
  bestPractices: [
5481
+ "Use refs[] for mixed document titles and URLs; exact IDs can still go through ids[].",
3499
5482
  "Start with view=ids for low-token audits, then re-run selected docs with summary/full views.",
3500
5483
  "Provide issueDomains to reduce non-issue URL noise and keep outputs focused.",
3501
5484
  "Tune keyPattern when your tracker uses custom issue key formats.",
@@ -3526,18 +5509,18 @@ export const EXTENDED_TOOLS = {
3526
5509
  },
3527
5510
  "documents.attachments": {
3528
5511
  signature:
3529
- "documents.attachments(args: { id?: string; documentId?: string; url?: string; shareId?: string; maxAttempts?: number })",
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 })",
3530
5513
  description:
3531
- "Extract embedded Outline attachment references from a document body, including images rendered through /api/attachments.redirect.",
5514
+ "Extract embedded Outline attachment references from a document body, including images rendered through /api/attachments.redirect, resolving remembered document refs when needed.",
3532
5515
  usageExample: {
3533
5516
  tool: "documents.attachments",
3534
5517
  args: {
3535
- url: "https://handbook.example.com/doc/example-title-AbCdEf1234",
5518
+ query: "example title",
3536
5519
  },
3537
5520
  },
3538
5521
  bestPractices: [
3539
- "Use this after documents.info when you need to enumerate embedded images or file links without downloading bytes.",
3540
- "Pass a document URL directly; the tool resolves the Outline URL id suffix through documents.info.",
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.",
3541
5524
  "Follow with attachments.download or documents.download_attachments to save files locally.",
3542
5525
  ],
3543
5526
  handler: documentsAttachmentsTool,
@@ -3564,19 +5547,20 @@ export const EXTENDED_TOOLS = {
3564
5547
  },
3565
5548
  "documents.download_attachments": {
3566
5549
  signature:
3567
- "documents.download_attachments(args: { id?: string; documentId?: string; url?: string; shareId?: string; outputDir?: string; overwrite?: boolean; concurrency?: number; maxAttempts?: number })",
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 })",
3568
5551
  description:
3569
- "Extract all embedded Outline attachment references from a document and save each referenced file locally.",
5552
+ "Resolve a document, extract all embedded Outline attachment references, and save each referenced file locally.",
3570
5553
  usageExample: {
3571
5554
  tool: "documents.download_attachments",
3572
5555
  args: {
3573
- url: "https://handbook.example.com/doc/example-title-AbCdEf1234",
5556
+ query: "example title",
3574
5557
  outputDir: "./outline-attachments",
3575
5558
  overwrite: true,
3576
5559
  },
3577
5560
  },
3578
5561
  bestPractices: [
3579
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.",
3580
5564
  "Keep concurrency modest for large image-heavy documents to avoid rate limits.",
3581
5565
  "Use overwrite=true for repeatable automation into a scratch directory.",
3582
5566
  ],
@@ -3604,15 +5588,16 @@ export const EXTENDED_TOOLS = {
3604
5588
  handler: documentsImportFileTool,
3605
5589
  },
3606
5590
  "templates.extract_placeholders": {
3607
- signature: "templates.extract_placeholders(args: { id: string; maxAttempts?: number })",
3608
- 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.",
3609
5593
  usageExample: {
3610
5594
  tool: "templates.extract_placeholders",
3611
5595
  args: {
3612
- id: "template-id",
5596
+ templateQuery: "incident postmortem",
3613
5597
  },
3614
5598
  },
3615
5599
  bestPractices: [
5600
+ "Pass templateQuery/templateRef/refs when the user names a template but exact ID is unknown.",
3616
5601
  "Run this before document creation to validate required placeholder keys.",
3617
5602
  "Use counts to catch repeated placeholders for deterministic pipeline checks.",
3618
5603
  ],
@@ -3620,13 +5605,13 @@ export const EXTENDED_TOOLS = {
3620
5605
  },
3621
5606
  "documents.create_from_template": {
3622
5607
  signature:
3623
- "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 })",
3624
5609
  description:
3625
5610
  "Create from template, optionally inject placeholder values, and enforce strict unresolved-placeholder safety.",
3626
5611
  usageExample: {
3627
5612
  tool: "documents.create_from_template",
3628
5613
  args: {
3629
- templateId: "template-id",
5614
+ templateQuery: "incident postmortem",
3630
5615
  title: "Service A - Incident Postmortem",
3631
5616
  placeholderValues: {
3632
5617
  service_name: "Service A",
@@ -3638,6 +5623,7 @@ export const EXTENDED_TOOLS = {
3638
5623
  },
3639
5624
  },
3640
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.",
3641
5627
  "Keep strictPlaceholders=true in automation to prevent publishing unresolved template tokens.",
3642
5628
  "Provide placeholderValues as exact key-value strings and inspect unresolvedCount on every run.",
3643
5629
  "This tool is action-gated; set performAction=true only for explicitly confirmed mutations.",
@@ -3646,18 +5632,19 @@ export const EXTENDED_TOOLS = {
3646
5632
  },
3647
5633
  "comments.review_queue": {
3648
5634
  signature:
3649
- "comments.review_queue(args: { documentIds?: string[]; collectionId?: string; includeAnchorText?: boolean; includeReplies?: boolean; limitPerDocument?: number; view?: 'summary'|'full'; maxAttempts?: number })",
3650
- 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.",
3651
5637
  usageExample: {
3652
5638
  tool: "comments.review_queue",
3653
5639
  args: {
3654
- documentIds: ["doc-1", "doc-2"],
5640
+ refs: ["incident runbook", "https://handbook.example.com/doc/oncall-escalation-AbCdEf12"],
3655
5641
  includeReplies: true,
3656
5642
  limitPerDocument: 20,
3657
5643
  },
3658
5644
  },
3659
5645
  bestPractices: [
3660
- "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.",
3661
5648
  "Use includeReplies=true to capture full threaded review context.",
3662
5649
  "Treat truncated=true as a signal to re-run with a higher limitPerDocument.",
3663
5650
  ],