@wirecat/cli-core 0.688.0 → 0.690.0

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.
Files changed (35) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/cli/documents/index.d.ts +1 -0
  3. package/dist/cli/documents/index.js +1 -0
  4. package/dist/cli/documents/library.d.ts +109 -0
  5. package/dist/cli/documents/library.js +523 -0
  6. package/dist/cli/documents/testing/source-contract.d.ts +11 -6
  7. package/dist/cli/documents/testing/source-contract.js +54 -23
  8. package/dist/cli/documents/testing/source.d.ts +11 -3
  9. package/dist/cli/documents/testing/source.js +15 -10
  10. package/dist/documents/index.d.ts +3 -1
  11. package/dist/documents/index.js +2 -0
  12. package/dist/documents/model.d.ts +20 -6
  13. package/dist/documents/model.js +2 -1
  14. package/dist/errors/reasons.d.ts +1 -1
  15. package/dist/errors/reasons.js +11 -0
  16. package/dist/resolve.d.ts +1 -1
  17. package/dist/resolve.js +1 -1
  18. package/dist/search/account-list.d.ts +2 -0
  19. package/dist/search/account-list.js +32 -4
  20. package/dist/services/documents/file-text.d.ts +13 -0
  21. package/dist/services/documents/file-text.js +33 -0
  22. package/dist/services/documents/plan.d.ts +3 -2
  23. package/dist/services/documents/plan.js +50 -16
  24. package/dist/services/documents/ports.d.ts +2 -2
  25. package/dist/services/documents/sync.js +2 -2
  26. package/dist/services/message-resolution.d.ts +1 -1
  27. package/dist/services/message-resolution.js +1 -1
  28. package/dist/store/sqlite/manifest.js +2 -0
  29. package/dist/store/sqlite/migrations.generated.js +20 -0
  30. package/dist/store/sqlite/schema.d.ts +169 -0
  31. package/dist/store/sqlite/schema.js +18 -0
  32. package/dist/store/sqlite/vectors.d.ts +26 -1
  33. package/dist/store/sqlite/vectors.js +72 -15
  34. package/dist/store/vectors.js +6 -2
  35. package/package.json +2 -2
@@ -1,21 +1,23 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { isCliError } from "@wirecat/cli-base";
3
3
  import { ANSWER_RESERVE_MS, runBudget } from "../../../background/budget.js";
4
+ import { feedOf, } from "../../../documents.js";
4
5
  import { DEFAULT_AGENT_COOPERATIVE_MS } from "../../execution.js";
5
6
  const MAX_ENTRIES = 500;
7
+ // Each listing is given the folder as listed, as the sync gives it: a source that addresses by path reads it there.
6
8
  const walk = async ({ source, root, isFolder }) => {
7
9
  const seen = new Map();
8
- const stack = [root];
10
+ const stack = [await source.metadata(root)];
9
11
  while (stack.length) {
10
12
  const parent = stack.pop();
11
- for (const child of await source.children(parent)) {
12
- assert.ok(child.parents.includes(parent), `${child.id} is a child of ${parent} and names it among its parents`);
13
+ for (const child of await source.children(parent.id, parent)) {
14
+ assert.ok(child.parents.includes(parent.id), `${child.id} is a child of ${parent.id} and names it among its parents`);
13
15
  if (seen.has(child.id))
14
16
  continue;
15
17
  seen.set(child.id, child);
16
18
  assert.ok(seen.size <= MAX_ENTRIES, `more than ${MAX_ENTRIES} entries under the fixture's root`);
17
19
  if (isFolder(child))
18
- stack.push(child.id);
20
+ stack.push(child);
19
21
  }
20
22
  }
21
23
  return [...seen.values()];
@@ -98,7 +100,7 @@ export const documentSourceContract = (make) => {
98
100
  assert.equal(typeof entry.url, "string", `${entry.id} has a URL`);
99
101
  assert.equal(typeof entry.canDownload, "boolean", `${entry.id} says whether it can be downloaded`);
100
102
  assert.ok(isTime(entry.modifiedAt) && isTime(entry.createdAt), `${entry.id}'s times parse`);
101
- assert.equal((await fixture.source.metadata(entry.id)).id, entry.id, `metadata(${entry.id}) is the same file`);
103
+ assert.equal((await fixture.source.metadata(entry.id, entry)).id, entry.id, `metadata(${entry.id}) is the same file`);
102
104
  }
103
105
  },
104
106
  },
@@ -109,14 +111,14 @@ export const documentSourceContract = (make) => {
109
111
  const files = (await walk(fixture)).filter((entry) => isImported(fixture, entry) && entry.canDownload);
110
112
  assert.ok(files.length > 0, "the root has a file that can be downloaded");
111
113
  for (const file of files.slice(0, 5)) {
112
- const content = await fixture.source.content(file.id);
114
+ const content = await fixture.source.content(file.id, undefined, file);
113
115
  assert.equal(content.metadata.id, file.id);
114
116
  assert.equal(typeof content.text, "string");
115
117
  assert.equal(typeof content.markdown, "string");
116
118
  assert.ok(Array.isArray(content.tabs), "tabs is a list, empty for a document without tabs");
117
119
  for (const tab of content.tabs)
118
120
  assert.ok(typeof tab.id === "string" && typeof tab.title === "string" && typeof tab.text === "string");
119
- const bytes = await fixture.source.bytes(file.id);
121
+ const bytes = await fixture.source.bytes(file.id, file);
120
122
  assert.ok(bytes instanceof Uint8Array, `bytes(${file.id}) is a Uint8Array`);
121
123
  }
122
124
  },
@@ -126,10 +128,15 @@ export const documentSourceContract = (make) => {
126
128
  async run() {
127
129
  const fixture = await make();
128
130
  const { source } = fixture;
129
- const token = await source.startToken();
131
+ const feed = feedOf(source);
132
+ if (!feed) {
133
+ assert.ok(!("startToken" in source), "a source has both startToken() and changes(), or neither");
134
+ return;
135
+ }
136
+ const token = await feed.startToken();
130
137
  assert.ok(typeof token === "string" && token, "startToken() gives a cursor");
131
138
  await fixture.change?.();
132
- const page = await source.changes(token);
139
+ const page = await feed.changes(token);
133
140
  assert.ok(Array.isArray(page.items), "a change page has items");
134
141
  if (fixture.change)
135
142
  assert.ok(page.items.length > 0, "the change made after startToken() is in the feed");
@@ -146,11 +153,12 @@ export const documentSourceContract = (make) => {
146
153
  name: "changes: a file added deep in the tree is named in the feed, itself or by its own folder",
147
154
  async run() {
148
155
  const { source, addNested } = await make();
149
- if (!addNested)
156
+ const feed = feedOf(source);
157
+ if (!addNested || !feed)
150
158
  return;
151
- const token = await source.startToken();
159
+ const token = await feed.startToken();
152
160
  const { file, folder } = await addNested();
153
- const named = new Set((await source.changes(token)).items.map((item) => item.id));
161
+ const named = new Set((await feed.changes(token)).items.map((item) => item.id));
154
162
  assert.ok(named.has(file) || named.has(folder), `the feed names ${file} or its folder ${folder}`);
155
163
  },
156
164
  });
@@ -161,30 +169,51 @@ export const documentSourceContract = (make) => {
161
169
  const { source } = fixture;
162
170
  if (!source.childrenPage)
163
171
  return;
164
- const stack = [fixture.root];
172
+ const stack = [await source.metadata(fixture.root)];
165
173
  while (stack.length) {
166
174
  const parent = stack.pop();
167
175
  const paged = [];
168
176
  let cursor;
169
177
  for (let pages = 1;; pages++) {
170
- assert.ok(pages <= MAX_ENTRIES, `childrenPage(${parent}) ends`);
171
- const page = await source.childrenPage(parent, cursor);
178
+ assert.ok(pages <= MAX_ENTRIES, `childrenPage(${parent.id}) ends`);
179
+ const page = await source.childrenPage(parent.id, cursor, parent);
172
180
  assert.ok(Array.isArray(page.files), "a page has files");
173
181
  paged.push(...page.files.map((file) => file.id));
174
182
  for (const file of page.files)
175
183
  if (fixture.isFolder(file))
176
- stack.push(file.id);
184
+ stack.push(file);
177
185
  if (page.cursor === undefined)
178
186
  break;
179
187
  assert.ok(typeof page.cursor === "string" && page.cursor !== cursor, "a page gives a new cursor or none");
180
188
  cursor = page.cursor;
181
189
  }
182
- assert.equal(new Set(paged).size, paged.length, `childrenPage(${parent}) lists each entry once`);
183
- const listed = (await source.children(parent)).map((file) => file.id);
184
- assert.deepEqual([...paged].sort(), [...listed].sort(), `childrenPage(${parent}) lists what children() does`);
190
+ assert.equal(new Set(paged).size, paged.length, `childrenPage(${parent.id}) lists each entry once`);
191
+ const listed = (await source.children(parent.id, parent)).map((file) => file.id);
192
+ assert.deepEqual([...paged].sort(), [...listed].sort(), `childrenPage(${parent.id}) lists what children() does`);
185
193
  }
186
194
  },
187
195
  });
196
+ cases.push({
197
+ name: "without a change feed: the next sync finds a new or edited file and drops a removed one",
198
+ async run() {
199
+ const fixture = await make();
200
+ const sync = fixture.faults?.sync;
201
+ if (feedOf(fixture.source) || !sync || (!fixture.change && !fixture.remove))
202
+ return;
203
+ const before = await finish(sync);
204
+ const idle = await finish(sync);
205
+ assert.equal(idle.result.saved, 0, "a sync with nothing changed on the provider saves nothing again");
206
+ const removed = await fixture.remove?.();
207
+ if (removed !== undefined)
208
+ assert.ok(before.saved.includes(removed), `the first sync holds ${removed} before it is removed`);
209
+ await fixture.change?.();
210
+ const after = await finish(sync);
211
+ if (removed !== undefined)
212
+ assert.ok(!after.saved.includes(removed), `the next sync drops the removed ${removed}`);
213
+ if (fixture.change)
214
+ assert.ok(after.result.saved > 0, "the next sync saves the new or edited file, though no feed named it");
215
+ },
216
+ });
188
217
  cases.push({
189
218
  name: "metadata: an id the provider does not know is not_found",
190
219
  async run() {
@@ -204,9 +233,10 @@ const faultCases = (make) => [
204
233
  const deny = fixture.faults?.deny;
205
234
  if (!deny)
206
235
  return;
236
+ const listed = new Map((await walk(fixture)).map((entry) => [entry.id, entry]));
207
237
  const id = await deny(status);
208
238
  const code = status === 403 ? "permission_error" : "not_found";
209
- await assert.rejects(fixture.source.content(id), (error) => isCliError(error) && error.code === code, `content(${id}) after a ${status} is ${code}`);
239
+ await assert.rejects(fixture.source.content(id, undefined, listed.get(id)), (error) => isCliError(error) && error.code === code, `content(${id}) after a ${status} is ${code}`);
210
240
  const sync = fixture.faults?.sync;
211
241
  if (!sync)
212
242
  return;
@@ -227,14 +257,15 @@ const faultCases = (make) => [
227
257
  name: "faults: a clock off by ten minutes either way loses no change",
228
258
  async run() {
229
259
  const first = await make();
230
- if (!first.faults?.skewed || !first.change)
260
+ if (!first.faults?.skewed || !first.change || !feedOf(first.source))
231
261
  return;
232
262
  for (const ms of [SKEW_MS, -SKEW_MS]) {
233
263
  const fixture = ms === SKEW_MS ? first : await make();
234
264
  const source = (await fixture.faults?.skewed?.(ms));
235
- const token = await source.startToken();
265
+ const { startToken, changes } = source;
266
+ const token = await startToken.call(source);
236
267
  await fixture.change?.();
237
- const page = await source.changes(token);
268
+ const page = await changes.call(source, token);
238
269
  assert.ok(page.items.length > 0, `a change is in the feed with this computer's clock ${ms / 60_000} min off`);
239
270
  }
240
271
  },
@@ -1,8 +1,14 @@
1
- import type { DocumentSource, SourceFile } from "../../../documents.js";
1
+ import type { FeedlessDocumentSource, SourceChange, SourceFile } from "../../../documents.js";
2
2
  /** The folder type of the fake source: no provider's own. */
3
3
  export declare const FAKE_FOLDER = "inode/directory";
4
4
  export declare const fakeFile: (id: string, parents?: string[], mime?: string) => SourceFile;
5
- export interface FakeDocumentSource extends DocumentSource {
5
+ export interface FakeDocumentSource extends FeedlessDocumentSource {
6
+ /** Absent with `feed: false`. */
7
+ startToken?(): Promise<string>;
8
+ changes?(token: string): Promise<{
9
+ items: SourceChange[];
10
+ cursor: string;
11
+ }>;
6
12
  files: Map<string, SourceFile>;
7
13
  /** Puts a file or folder in, or changes it, and lists it in the next change feed. */
8
14
  put(file: SourceFile, text?: string): void;
@@ -13,8 +19,10 @@ export interface FakeDocumentSource extends DocumentSource {
13
19
  }
14
20
  /**
15
21
  * A provider in memory: a root folder, a nested folder and two text files, with a change feed and a cursor. With
16
- * `pageSize` it also lists a folder's children a page at a time through `childrenPage`.
22
+ * `pageSize` it also lists a folder's children a page at a time through `childrenPage`; with `feed: false` it has no
23
+ * change feed, as Yandex Disk.
17
24
  */
18
25
  export declare const fakeDocumentSource: (account?: string, options?: {
19
26
  pageSize?: number;
27
+ feed?: boolean;
20
28
  }) => FakeDocumentSource;
@@ -14,7 +14,8 @@ export const fakeFile = (id, parents = ["root"], mime = "text/plain") => ({
14
14
  });
15
15
  /**
16
16
  * A provider in memory: a root folder, a nested folder and two text files, with a change feed and a cursor. With
17
- * `pageSize` it also lists a folder's children a page at a time through `childrenPage`.
17
+ * `pageSize` it also lists a folder's children a page at a time through `childrenPage`; with `feed: false` it has no
18
+ * change feed, as Yandex Disk.
18
19
  */
19
20
  export const fakeDocumentSource = (account = "alpha", options = {}) => {
20
21
  const files = new Map();
@@ -64,15 +65,19 @@ export const fakeDocumentSource = (account = "alpha", options = {}) => {
64
65
  },
65
66
  }
66
67
  : {}),
67
- startToken: async () => `cursor-${cursor}`,
68
- changes: async (token) => {
69
- if (!/^cursor-\d+$/.test(token))
70
- throw new CliError("validation_error", "unknown synthetic cursor");
71
- const items = feed;
72
- feed = [];
73
- cursor += 1;
74
- return { items, cursor: `cursor-${cursor}` };
75
- },
68
+ ...(options.feed === false
69
+ ? {}
70
+ : {
71
+ startToken: async () => `cursor-${cursor}`,
72
+ changes: async (token) => {
73
+ if (!/^cursor-\d+$/.test(token))
74
+ throw new CliError("validation_error", "unknown synthetic cursor");
75
+ const items = feed;
76
+ feed = [];
77
+ cursor += 1;
78
+ return { items, cursor: `cursor-${cursor}` };
79
+ },
80
+ }),
76
81
  content: async (id, maxChars) => {
77
82
  const file = await metadata(id);
78
83
  if (file.mime === FAKE_FOLDER)
@@ -1,5 +1,6 @@
1
1
  export { type BlockConflict, type BlockHunk, diffBlocks, type Merged, mergeBlocks, } from "../services/documents/block-diff.js";
2
2
  export { type Complete, extractMemories } from "../services/documents/extraction.js";
3
+ export { fileText, readableFile } from "../services/documents/file-text.js";
3
4
  export { documentIngestion, type IngestionOptions } from "../services/documents/ingestion.js";
4
5
  export { type DocumentKnowledge, documentKnowledge } from "../services/documents/knowledge.js";
5
6
  export { blocksMarkdown, inlineMarkdown, spliceMarkdown } from "../services/documents/markdown-splice.js";
@@ -12,6 +13,7 @@ export { type SyncResult, syncDocuments } from "../services/documents/sync.js";
12
13
  export { type Block, blockKey, blockShape, type Inline, type ListKind, normalizeInlines } from "./blocks.js";
13
14
  export { catalogFiles } from "./catalog.js";
14
15
  export { markdownBlocks, type PlacedBlock, placedMarkdownBlocks } from "./markdown-blocks.js";
15
- export type { DocumentSource, IndexedSource, PictureWriter, SourceChange, SourceContent, SourceFile, SourceIndex, SourceSkip, SourceState, SourceStatePort, SourceWalk, SourceWork, TabText, } from "./model.js";
16
+ export type { DocumentSource, FeedlessDocumentSource, IndexedSource, PictureWriter, SourceChange, SourceContent, SourceFile, SourceIndex, SourceSkip, SourceState, SourceStatePort, SourceWalk, SourceWork, TabText, } from "./model.js";
17
+ export { feedOf } from "./model.js";
16
18
  export type { ConflictPart, DocumentTarget, Keep, LocalDocument, Prepared, PushEntry, Pushed, PushPlan, PushState, PushStatePort, RemoteChange, } from "./push-model.js";
17
19
  export { inScope, type SourceQuery, within } from "./scope.js";
@@ -1,5 +1,6 @@
1
1
  export { diffBlocks, mergeBlocks, } from "../services/documents/block-diff.js";
2
2
  export { extractMemories } from "../services/documents/extraction.js";
3
+ export { fileText, readableFile } from "../services/documents/file-text.js";
3
4
  export { documentIngestion } from "../services/documents/ingestion.js";
4
5
  export { documentKnowledge } from "../services/documents/knowledge.js";
5
6
  export { blocksMarkdown, inlineMarkdown, spliceMarkdown } from "../services/documents/markdown-splice.js";
@@ -11,4 +12,5 @@ export { syncDocuments } from "../services/documents/sync.js";
11
12
  export { blockKey, blockShape, normalizeInlines } from "./blocks.js";
12
13
  export { catalogFiles } from "./catalog.js";
13
14
  export { markdownBlocks, placedMarkdownBlocks } from "./markdown-blocks.js";
15
+ export { feedOf } from "./model.js";
14
16
  export { inScope, within } from "./scope.js";
@@ -31,28 +31,42 @@ export interface SourceChange<M extends SourceFile = SourceFile> {
31
31
  removed: boolean;
32
32
  file?: M;
33
33
  }
34
- export interface DocumentSource<M extends SourceFile = SourceFile> {
34
+ /**
35
+ * A provider without a change feed (Yandex Disk, WebDAV, S3): every sync walks the selected folders in full, saves only
36
+ * what changed since the last pass, and removes what the finished pass no longer found. A `DocumentSource` is one too.
37
+ */
38
+ export interface FeedlessDocumentSource<M extends SourceFile = SourceFile> {
35
39
  identity(): Promise<string>;
36
- metadata(id: string): Promise<M>;
37
- children(id: string): Promise<M[]>;
40
+ /**
41
+ * The file `known` is the one the sync last listed under this id, when it has one: a provider that addresses files
42
+ * by path, not by id (Yandex Disk, WebDAV), reads its path from there. The same holds for `children`,
43
+ * `childrenPage`, `content` and `bytes`.
44
+ */
45
+ metadata(id: string, known?: M): Promise<M>;
46
+ children(id: string, folder?: M): Promise<M[]>;
38
47
  /**
39
48
  * One page of a folder's children, for a provider whose folder can be too big for one step of a sync (a Notion
40
49
  * database of 12,000 rows). A sync with it lists one page per step and saves the cursor between calls. A cursor
41
50
  * the provider no longer accepts must fail as `not_found` (through `errorOf`): the sync then lists the folder again
42
51
  * from its first page, where any other error fails every later sync on that page until a `--rescan`.
43
52
  */
44
- childrenPage?(id: string, cursor?: string): Promise<{
53
+ childrenPage?(id: string, cursor?: string, folder?: M): Promise<{
45
54
  files: M[];
46
55
  cursor?: string;
47
56
  }>;
57
+ content(id: string, maxChars?: number, file?: M): Promise<SourceContent<M>>;
58
+ bytes(id: string, file?: M): Promise<Uint8Array>;
59
+ }
60
+ /** A provider with a change feed: after the first walk, a sync reads only what the feed names. */
61
+ export interface DocumentSource<M extends SourceFile = SourceFile> extends FeedlessDocumentSource<M> {
48
62
  startToken(): Promise<string>;
49
63
  changes(token: string): Promise<{
50
64
  items: SourceChange<M>[];
51
65
  cursor: string;
52
66
  }>;
53
- content(id: string, maxChars?: number): Promise<SourceContent<M>>;
54
- bytes(id: string): Promise<Uint8Array>;
55
67
  }
68
+ /** The feed of a source that has one. */
69
+ export declare const feedOf: <M extends SourceFile>(source: FeedlessDocumentSource<M>) => DocumentSource<M> | undefined;
56
70
  export interface IndexedSource<M extends SourceFile = SourceFile> {
57
71
  metadata: M;
58
72
  hash: string;
@@ -1 +1,2 @@
1
- export {};
1
+ /** The feed of a source that has one. */
2
+ export const feedOf = (source) => "changes" in source && typeof source.changes === "function" ? source : undefined;
@@ -7,7 +7,7 @@ export declare const REASONS: ErrorReason[];
7
7
  * Detail keys an error from this package may carry, until each is registered on its own reason. Not `cause`:
8
8
  * that can hold a provider's or SQLite's raw text.
9
9
  */
10
- export declare const DETAILS: readonly ["contracts", "calendars", "allowed", "alternative", "arguments", "at", "available", "batch", "budget", "built", "candidates", "chat", "chat_id", "cli", "column", "complete", "emitted_bytes", "exact", "file", "forum", "guide", "hint", "id", "index", "kind", "limit", "limit_source", "line", "max_bytes", "model", "name", "operation_id", "operation_ids", "text_limit", "store_refused_in", "partial_output", "parent", "path", "permission", "person_ids", "previous_chat_id", "profiles", "provider_error", "provider", "recovery", "reference", "remembered", "retry_at", "retry_after_ms", "runtime", "saved", "scheduled_for", "script", "sent", "sent_count", "settlement_failed", "span", "sqlite", "stage", "standing", "state", "stderr", "term", "total", "upgraded", "wanted"];
10
+ export declare const DETAILS: readonly ["holders", "profile", "contracts", "calendars", "allowed", "alternative", "arguments", "at", "available", "batch", "budget", "built", "candidates", "chat", "chat_id", "cli", "column", "complete", "emitted_bytes", "exact", "file", "forum", "guide", "hint", "id", "index", "kind", "limit", "limit_source", "line", "max_bytes", "model", "name", "operation_id", "operation_ids", "text_limit", "store_refused_in", "partial_output", "parent", "path", "permission", "person_ids", "previous_chat_id", "profiles", "provider_error", "provider", "recovery", "reference", "remembered", "retry_at", "retry_after_ms", "runtime", "saved", "scheduled_for", "script", "sent", "sent_count", "settlement_failed", "span", "sqlite", "stage", "standing", "state", "stderr", "term", "total", "upgraded", "wanted"];
11
11
  /** What a CLI adds to the shared registry: its own reasons, and the detail keys its adapters raise. */
12
12
  export interface AppErrors {
13
13
  reasons?: readonly ErrorReason[];
@@ -187,6 +187,15 @@ const OTHERS = [
187
187
  validation("document.changed", "the document changed while it was read; nothing was saved"),
188
188
  ["document.not-imported", "not_found", "the document is not imported in this source account"],
189
189
  ["document.not-found", "not_found", "no listed document has that reference"],
190
+ ["state.unreadable", "configuration_error", "a sync state file cannot be read; move it away and sync again"],
191
+ ["profile.busy", "provider_unavailable", "another sync or write holds this profile's local copy"],
192
+ ["profile.account-taken", "conflict", "another profile here already uses this provider account"],
193
+ ["profile.other-account", "conflict", "this profile's copy was synced from another provider account"],
194
+ ["profile.not-synced", "not_found", "the profile has no local copy yet; sync it first"],
195
+ ["provider.failed", "provider_error", "a read from the provider failed"],
196
+ ["identity.none", "not_found", "the provider shows no accounts on a document"],
197
+ validation("folder.not-a-folder", "what was named is not a folder the account can read"),
198
+ ["folder.not-chosen", "not_found", "the folder is not among the chosen folders"],
190
199
  ["meeting.not-found", "not_found", "no meeting row has that event or meeting reference"],
191
200
  ["listing.too-large", "provider_error", "the listing is over its bound; the checkpoint was kept"],
192
201
  ["listing.source-not-found", "not_found", "a source: term names no account holding what is listed"],
@@ -698,6 +707,8 @@ export const REASONS = defineReasons([
698
707
  * that can hold a provider's or SQLite's raw text.
699
708
  */
700
709
  export const DETAILS = [
710
+ "holders",
711
+ "profile",
701
712
  "contracts",
702
713
  "calendars",
703
714
  "allowed",
package/dist/resolve.d.ts CHANGED
@@ -27,7 +27,7 @@ export declare const pickChat: (reference: string, chats: Chat[]) => Chat;
27
27
  * `lower()` folds ASCII only, and most of these names are Cyrillic.
28
28
  */
29
29
  export declare const pickPerson: (reference: string, people: PeopleLookup) => Contact;
30
- /** Everyone a name pattern such as `Ярослав*` or `*Орлов*` fits by their alias, name or @username. */
30
+ /** Everyone a name pattern such as `Станислав*` or `*Соколов*` fits by their alias, name or @username. */
31
31
  export declare const peopleMatching: (pattern: string, people: Contact[], { byAddress }?: {
32
32
  byAddress?: boolean | undefined;
33
33
  }) => Contact[];
package/dist/resolve.js CHANGED
@@ -70,7 +70,7 @@ const namePattern = (pattern) => {
70
70
  const automaton = compileAutomaton(wildcardPattern(foldName(pattern.trim().replace(/^@/, ""))));
71
71
  return (names) => names.some((one) => automaton.test(one));
72
72
  };
73
- /** Everyone a name pattern such as `Ярослав*` or `*Орлов*` fits by their alias, name or @username. */
73
+ /** Everyone a name pattern such as `Станислав*` or `*Соколов*` fits by their alias, name or @username. */
74
74
  export const peopleMatching = (pattern, people, { byAddress = false } = {}) => {
75
75
  const fits = namePattern(pattern);
76
76
  return people.filter((person) => fits(namesOf(person, byAddress)));
@@ -42,6 +42,8 @@ export declare const listedHolds: (account: Pick<ListedAccount, "kind" | "kinds"
42
42
  export interface ListedEntry {
43
43
  entry: string;
44
44
  accounts: ListedAccount[];
45
+ /** For a bare word that names no account: the words that name something in the store. */
46
+ holds?: string;
45
47
  }
46
48
  export declare const keyOf: ({ provider, account }: AccountKey) => string;
47
49
  export declare const sourceOf: ({ provider, account }: AccountKey) => string;
@@ -135,6 +135,10 @@ const accountsOfWord = (word, held, context) => {
135
135
  return [...held];
136
136
  if (wanted === "personal" || wanted === "bots")
137
137
  return held.filter((one) => listedHolds(one, "messages") && isBotProvider(one.provider) === (wanted === "bots"));
138
+ // Drive and Notion accounts are stored and searched as notes folders, so their kind stays `notes`; the word still
139
+ // names them, beside the imports whose kind is documents.
140
+ if (wanted === "documents")
141
+ return held.filter((one) => listedHolds(one, "documents") || isDocumentAccount(one));
138
142
  if (isKind(wanted))
139
143
  return held.filter((one) => listedHolds(one, wanted));
140
144
  const recorded = context.profiles[wanted];
@@ -146,6 +150,24 @@ const accountsOfWord = (word, held, context) => {
146
150
  return storedAs(held, { provider, account: "" });
147
151
  return held.filter((one) => one.provider === provider);
148
152
  };
153
+ const isDocumentAccount = ({ stored }) => stored !== undefined && isDocumentAccountProvider(stored.provider);
154
+ /** The words that name something the store holds: the groups no one saves, each kind with an account, each provider. */
155
+ const choices = (held) => {
156
+ const kinds = held.flatMap((one) => one.kinds ?? (one.kind ? [one.kind] : []));
157
+ const messengers = held.filter((one) => listedHolds(one, "messages"));
158
+ // `added` names no account by itself: the owner's added sources are found as notes.
159
+ const providers = held.flatMap(({ stored, provider }) => stored?.provider === ADDED_PROVIDER ? [] : [stored?.provider ?? provider]);
160
+ return [
161
+ ...new Set([
162
+ "all",
163
+ ...(messengers.some((one) => !isBotProvider(one.provider)) ? ["personal"] : []),
164
+ ...(messengers.some((one) => isBotProvider(one.provider)) ? ["bots"] : []),
165
+ ...kinds,
166
+ ...(held.some(isDocumentAccount) ? ["documents"] : []),
167
+ ...providers,
168
+ ]),
169
+ ].join(", ");
170
+ };
149
171
  export const keyOf = ({ provider, account }) => `${provider}\u0000${account}`;
150
172
  export const sourceOf = ({ provider, account }) => `${provider}:${account}`;
151
173
  export const sameAs = (key) => (one) => one.provider === key.provider && one.account === key.account;
@@ -161,7 +183,9 @@ export const entriesOfList = (value, context) => {
161
183
  const colon = item.indexOf(":");
162
184
  if (colon === -1) {
163
185
  try {
164
- entries.push({ entry: item, accounts: accountsOfWord(item, held, context) });
186
+ const accounts = accountsOfWord(item, held, context);
187
+ // A search that reads nothing because a word named nothing answers with the words that do name something.
188
+ entries.push({ entry: item, accounts, ...(accounts.length === 0 && !group ? { holds: choices(held) } : {}) });
165
189
  }
166
190
  catch (error) {
167
191
  if (!group || !(error instanceof CliError))
@@ -192,8 +216,9 @@ export const entriesOfList = (value, context) => {
192
216
  for (const item of itemsOf(value))
193
217
  entry(item);
194
218
  const { only } = context;
195
- return entries.map(({ entry, accounts }) => ({
219
+ return entries.map(({ entry, accounts, holds }) => ({
196
220
  entry,
221
+ ...(holds === undefined ? {} : { holds }),
197
222
  accounts: accounts
198
223
  .filter((one) => only === undefined || only.has(keyOf(one)))
199
224
  .map(({ provider, account, kind, kinds }) => ({
@@ -249,7 +274,10 @@ export const fitting = (entries, kinds, what, reasonOf = (kind) => READS[kind],
249
274
  ? { source: entry, code: "not_found", reason: UNKNOWN_PROVIDER }
250
275
  : { source: entry, code: "not_found", reason: "no account in the store" });
251
276
  }
252
- if (chosen.size === 0)
253
- fail(`--source names nothing ${what} reads: ${skipped.map(({ source, reason }) => `${source} (${reason})`).join(", ")}`);
277
+ if (chosen.size === 0) {
278
+ const words = entries.length === 1 ? entries[0]?.holds : undefined;
279
+ fail(`--source names nothing ${what} reads: ${skipped.map(({ source, reason }) => `${source} (${reason})`).join(", ")}` +
280
+ (words === undefined ? "" : ` — the store holds ${words}`));
281
+ }
254
282
  return { accounts: [...chosen.values()], skipped };
255
283
  };
@@ -0,0 +1,13 @@
1
+ /** A file a documents sync reads the text of: PDF, docx, xlsx, CSV, TSV, plain text and Markdown. */
2
+ export declare const readableFile: ({ name, mime }: {
3
+ name: string;
4
+ mime: string;
5
+ }) => boolean;
6
+ /**
7
+ * The text of a downloaded file through cli-core's readers, or a `validation_error` that says why there is none, in
8
+ * words a person acts on. `command` names the CLI in the hint for a missing reader.
9
+ */
10
+ export declare const fileText: (bytes: Uint8Array, file: {
11
+ name: string;
12
+ mime: string;
13
+ }, command: string, env?: NodeJS.ProcessEnv) => Promise<string>;
@@ -0,0 +1,33 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { engineHint, extractText, importEngine, MAX_TEXT_CHARS } from "../../attachments/extract.js";
3
+ import { attachmentMaxBytes } from "../../attachments/limits.js";
4
+ const READABLE = new Set([
5
+ "application/pdf",
6
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
7
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
8
+ "text/csv",
9
+ "text/tab-separated-values",
10
+ "text/plain",
11
+ "text/markdown",
12
+ ]);
13
+ /** A file a documents sync reads the text of: PDF, docx, xlsx, CSV, TSV, plain text and Markdown. */
14
+ export const readableFile = ({ name, mime }) => READABLE.has(mime) || /\.(md|markdown|txt|pdf|docx|xlsx|csv|tsv)$/iu.test(name);
15
+ /**
16
+ * The text of a downloaded file through cli-core's readers, or a `validation_error` that says why there is none, in
17
+ * words a person acts on. `command` names the CLI in the hint for a missing reader.
18
+ */
19
+ export const fileText = async (bytes, file, command, env = process.env) => {
20
+ const read = await extractText(bytes, { kind: "document", name: file.name, mime: file.mime, path: file.name }, importEngine, undefined, env);
21
+ if (read.status === "extracted")
22
+ return read.text;
23
+ const reason = read.status === "needs-agent"
24
+ ? "file has no text layer (a scan or images only); OCR is not supported"
25
+ : read.status === "engine-missing"
26
+ ? engineHint(read.engine, command)
27
+ : read.status === "unreadable"
28
+ ? "file could not be read as text; it may be damaged or protected"
29
+ : read.status === "unsupported"
30
+ ? "file contents do not match its type"
31
+ : `file is too large for the document readers (over ${Math.round(attachmentMaxBytes(env) / 1024 / 1024)} MB, or over ${MAX_TEXT_CHARS} characters of text)`;
32
+ throw new CliError("validation_error", reason);
33
+ };
@@ -1,4 +1,4 @@
1
- import type { DocumentSource, SourceFile, SourceState, SourceWalk } from "../../documents/model.js";
1
+ import { type FeedlessDocumentSource, type SourceFile, type SourceState, type SourceWalk } from "../../documents/model.js";
2
2
  import { type SourceQuery } from "../../documents/scope.js";
3
3
  import type { SyncOptions } from "./ports.js";
4
4
  export declare const scopeHash: (roots: string[], query?: Pick<SourceQuery, "key" | "mode">, pages?: boolean) => string;
@@ -22,5 +22,6 @@ export type Plan<M extends SourceFile> = {
22
22
  } | {
23
23
  walk: WalkProgress;
24
24
  };
25
- export declare const planDocuments: <M extends SourceFile>(options: SyncOptions<M>, source: DocumentSource<M> | undefined, state: SourceState<M>, roots: string[], limit: number, pictures: boolean, walks?: WalkStore<M>) => Promise<Plan<M>>;
25
+ export declare const WALKED = "walked";
26
+ export declare const planDocuments: <M extends SourceFile>(options: SyncOptions<M>, source: FeedlessDocumentSource<M> | undefined, state: SourceState<M>, roots: string[], limit: number, pictures: boolean, walks?: WalkStore<M>) => Promise<Plan<M>>;
26
27
  export {};