@wirecat/cli-core 0.717.0 → 0.718.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 (47) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/dist/cli/documents/index.d.ts +2 -0
  3. package/dist/cli/documents/index.js +2 -0
  4. package/dist/cli/documents/manifest/manifest.d.ts +82 -0
  5. package/dist/cli/documents/manifest/manifest.js +97 -0
  6. package/dist/cli/documents/manifest/source.d.ts +35 -0
  7. package/dist/cli/documents/manifest/source.js +257 -0
  8. package/dist/cli/documents/words.d.ts +1 -1
  9. package/dist/cli/messenger/conversation-answers.d.ts +1 -1
  10. package/dist/cli/messenger/conversation-answers.js +4 -2
  11. package/dist/cli/messenger/conversations-command.js +13 -4
  12. package/dist/cli/service-api-manifest.d.ts +2 -0
  13. package/dist/cli/service-api-manifest.js +6 -6
  14. package/dist/content/manifest/writer.js +5 -1
  15. package/dist/documents/model.d.ts +6 -0
  16. package/dist/entities/conversation-results.d.ts +5 -0
  17. package/dist/entities/conversation-results.js +6 -1
  18. package/dist/entities/index.d.ts +3 -0
  19. package/dist/errors/reasons.js +8 -0
  20. package/dist/manifest/index.d.ts +22 -3
  21. package/dist/manifest/index.js +13 -2
  22. package/dist/search/lucene/resolved.d.ts +2 -0
  23. package/dist/services/documents/plan.d.ts +2 -0
  24. package/dist/services/documents/plan.js +12 -0
  25. package/dist/services/embeddings-search.d.ts +9 -0
  26. package/dist/services/embeddings-search.js +189 -69
  27. package/dist/services/embeddings.d.ts +6 -0
  28. package/dist/services/metadata.d.ts +1 -1
  29. package/dist/services/named-chat.d.ts +3 -3
  30. package/dist/services/named-chat.js +12 -3
  31. package/dist/store/conversations.d.ts +21 -0
  32. package/dist/store/conversations.js +13 -0
  33. package/dist/store/slow-queries.d.ts +7 -0
  34. package/dist/store/slow-queries.js +47 -0
  35. package/dist/store/sqlite/conversations.d.ts +21 -0
  36. package/dist/store/sqlite/conversations.js +50 -0
  37. package/dist/store/sqlite/lucene-fields.d.ts +2 -0
  38. package/dist/store/sqlite/lucene-fields.js +22 -0
  39. package/dist/store/sqlite/lucene.js +30 -42
  40. package/dist/store/sqlite/open.js +3 -0
  41. package/dist/store/sqlite/vector-index.d.ts +3 -1
  42. package/dist/store/sqlite/vector-index.js +5 -3
  43. package/dist/store/sqlite/vectors.js +20 -11
  44. package/dist/store/sqlite/word-rarity.d.ts +14 -0
  45. package/dist/store/sqlite/word-rarity.js +22 -0
  46. package/package.json +2 -2
  47. package/parity.json +5 -0
@@ -34,6 +34,8 @@ export declare const signRequest: (manifest: ServiceApiManifest, operation: Mani
34
34
  * must never get its sign-in.
35
35
  */
36
36
  export declare const underBase: (url: URL, baseUrl: string) => boolean;
37
+ /** `""` is the answer itself: WordPress answers the list. */
38
+ export declare const answerAt: (value: unknown, path: string) => unknown;
37
39
  export declare const parameterValue: (input: ApiCommandInput, parameter: {
38
40
  in: "query" | "body";
39
41
  name: string;
@@ -131,7 +131,7 @@ export const underBase = (url, baseUrl) => {
131
131
  return url.origin === base.origin && (url.pathname === base.pathname || url.pathname.startsWith(prefix));
132
132
  };
133
133
  /** `""` is the answer itself: WordPress answers the list. */
134
- const at = (value, path) => path === ""
134
+ export const answerAt = (value, path) => path === ""
135
135
  ? value
136
136
  : path
137
137
  .split(".")
@@ -160,12 +160,12 @@ export const withValue = (input, parameter, value) => {
160
160
  * WordPress refuses a page past the end.
161
161
  */
162
162
  export const nextPage = (pagination, input, answer, headers) => {
163
- const listed = pagination.items === undefined ? [answer] : at(answer, pagination.items);
163
+ const listed = pagination.items === undefined ? [answer] : answerAt(answer, pagination.items);
164
164
  const items = Array.isArray(listed) ? listed : [];
165
165
  switch (pagination.style) {
166
166
  case "cursor": {
167
- const cursor = at(answer, pagination.next);
168
- const more = pagination.hasMore === undefined || at(answer, pagination.hasMore) !== false;
167
+ const cursor = answerAt(answer, pagination.next);
168
+ const more = pagination.hasMore === undefined || answerAt(answer, pagination.hasMore) !== false;
169
169
  return more && typeof cursor === "string" && cursor !== ""
170
170
  ? { items, next: { input: withValue(input, pagination.cursor, cursor) } }
171
171
  : { items };
@@ -173,7 +173,7 @@ export const nextPage = (pagination, input, answer, headers) => {
173
173
  case "offset":
174
174
  case "page": {
175
175
  const parameter = pagination.style === "offset" ? pagination.offset : pagination.page;
176
- const total = pagination.total === undefined ? undefined : numberOf(at(answer, pagination.total));
176
+ const total = pagination.total === undefined ? undefined : numberOf(answerAt(answer, pagination.total));
177
177
  const current = numberOf(parameterValue(input, parameter)) ?? (pagination.style === "offset" ? 0 : (pagination.start ?? 1));
178
178
  const next = pagination.style === "offset" ? current + items.length : current + 1;
179
179
  const pages = pagination.style === "page" && pagination.pagesHeader !== undefined
@@ -187,7 +187,7 @@ export const nextPage = (pagination, input, answer, headers) => {
187
187
  return last ? { items } : { items, next: { input: withValue(input, parameter, next) } };
188
188
  }
189
189
  case "link": {
190
- const url = at(answer, pagination.next);
190
+ const url = answerAt(answer, pagination.next);
191
191
  return typeof url === "string" && url !== "" ? { items, next: { url } } : { items };
192
192
  }
193
193
  }
@@ -13,6 +13,10 @@ const mapType = (entity) => {
13
13
  };
14
14
  /** `posts.delete.force` → `delete.force`: the action, whatever route it is on. */
15
15
  const actionOf = (key) => key.slice(key.indexOf(".") + 1);
16
+ const resourceOf = (key) => key.slice(0, key.indexOf("."));
17
+ /** Publishing and unpublishing go out as an update, so a yes to either is a yes to the same resource's update key. */
18
+ const covers = (yes, key) => actionOf(yes) === actionOf(key) ||
19
+ (key === `${resourceOf(yes)}.update` && ["publish", "unpublish"].includes(actionOf(yes)));
16
20
  const iso = (ms) => `${new Date(ms).toISOString().slice(0, 19)}Z`;
17
21
  /**
18
22
  * A `ContentWriter` from the manifest's `writes`. Each write reads the post first: an old version is a conflict, and a
@@ -110,7 +114,7 @@ export const contentWriterFromManifest = (input, options) => {
110
114
  const operation = options.api.operations.find((one) => one.id === call.operation);
111
115
  const route = (operation?.permissions ?? [])
112
116
  .map((one) => one.key)
113
- .filter((key) => confirmed?.some((yes) => actionOf(yes) === actionOf(key)) && !confirmed.includes(key));
117
+ .filter((key) => confirmed?.some((yes) => covers(yes, key)) && !confirmed.includes(key));
114
118
  const { result } = await options.write(options.command, call.operation, inputOf(call, slots, body === undefined && call.body === undefined ? undefined : { ...base, ...body }), !confirmed?.length
115
119
  ? []
116
120
  : [...confirmed, ...route, ...(operation?.command === undefined ? [] : [`api.${operation.command}`])]);
@@ -56,6 +56,12 @@ export interface FeedlessDocumentSource<M extends SourceFile = SourceFile> {
56
56
  }>;
57
57
  content(id: string, maxChars?: number, file?: M): Promise<SourceContent<M>>;
58
58
  bytes(id: string, file?: M): Promise<Uint8Array>;
59
+ /**
60
+ * Whether a saved document is read again though it did not change: one saved before the source learned to read
61
+ * something (a page's authors). The sync reads at most `REREAD_BATCH` of them a pass, so new edits are not held back;
62
+ * `content()` must give what this asks for, or the document is read again on every pass.
63
+ */
64
+ reread?(saved: IndexedSource<M>): boolean;
59
65
  }
60
66
  /** A provider with a change feed: after the first walk, a sync reads only what the feed names. */
61
67
  export interface DocumentSource<M extends SourceFile = SourceFile> extends FeedlessDocumentSource<M> {
@@ -654,4 +654,9 @@ export declare const conversationHit: v.StrictObjectSchema<{
654
654
  readonly matched_in: v.OptionalSchema<v.LiteralSchema<"context", undefined>, undefined>;
655
655
  readonly by: v.ArraySchema<v.PicklistSchema<["meaning", "words"], undefined>, undefined>;
656
656
  readonly stale: v.BooleanSchema<undefined>;
657
+ /** Up to three of the chunk's messages as "sender: text": what the hit says, without opening it. */
658
+ readonly lines: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
659
+ /** In the block of the owner's own conversations, which the hits before it left out. */
660
+ readonly from_owner: v.OptionalSchema<v.LiteralSchema<true, undefined>, undefined>;
661
+ readonly untrusted: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
657
662
  }, undefined>;
@@ -1,7 +1,7 @@
1
1
  import * as v from "valibot";
2
2
  import { conversation } from "./conversation.js";
3
3
  import { chatEmbedding, conversationBuild, conversationPreparation } from "./conversation-preparation.js";
4
- import { count, id, reference, text, time } from "./fields.js";
4
+ import { count, id, reference, text, time, untrusted } from "./fields.js";
5
5
  import { message } from "./message.js";
6
6
  /** JSON returns the conversation with its messages; JSONL streams the messages themselves. */
7
7
  export const conversationDetails = v.union([
@@ -91,4 +91,9 @@ export const conversationHit = v.strictObject({
91
91
  matched_in: v.optional(v.literal("context")),
92
92
  by: v.array(v.picklist(["meaning", "words"])),
93
93
  stale: v.boolean(),
94
+ /** Up to three of the chunk's messages as "sender: text": what the hit says, without opening it. */
95
+ lines: v.optional(v.array(text)),
96
+ /** In the block of the owner's own conversations, which the hits before it left out. */
97
+ from_owner: v.optional(v.literal(true)),
98
+ untrusted,
94
99
  });
@@ -7806,6 +7806,9 @@ export declare const ENTITIES: {
7806
7806
  readonly matched_in: v.OptionalSchema<v.LiteralSchema<"context", undefined>, undefined>;
7807
7807
  readonly by: v.ArraySchema<v.PicklistSchema<["meaning", "words"], undefined>, undefined>;
7808
7808
  readonly stale: v.BooleanSchema<undefined>;
7809
+ readonly lines: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
7810
+ readonly from_owner: v.OptionalSchema<v.LiteralSchema<true, undefined>, undefined>;
7811
+ readonly untrusted: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
7809
7812
  }, undefined>;
7810
7813
  readonly conversation: v.StrictObjectSchema<{
7811
7814
  readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
@@ -71,6 +71,14 @@ const PROVIDER_API = [
71
71
  validation("api.unknown-method", "the provider has no method by this name"),
72
72
  ["api.disabled", "configuration_error", "the provider's API is turned off for this OAuth project"],
73
73
  ["manifest.invalid", "configuration_error", "the source manifest does not match its shape or the generated API"],
74
+ ["source.no-id", "invalid_response", "a row of the provider's answer has no id where the source manifest says"],
75
+ ["source.no-account", "invalid_response", "the provider's answer does not name the signed-in account"],
76
+ validation("source.token-invalid", "the change token is not one this source gave"),
77
+ [
78
+ "source.changes-too-many",
79
+ "invalid_response",
80
+ "more changed since one sync than a round reads, and the provider does not list changes oldest first",
81
+ ],
74
82
  ["verify.no-id", "provider_error", "the answer to the sign-in check holds no account id where auth.verify says"],
75
83
  ["provider.usage-limit", "rate_limited", "the account's usage limit at the provider is reached; wait, do not retry"],
76
84
  ["access.denied", "permission_error", "the provider refused this account access to the item"],
@@ -1,3 +1,4 @@
1
+ import type { DocumentManifest } from "../cli/documents/manifest/manifest.js";
1
2
  import type { ContentManifest } from "../content/manifest/manifest.js";
2
3
  import type { CrmManifest } from "../crm/manifest/manifest.js";
3
4
  import type { OAuthProvider } from "../oauth/provider.js";
@@ -77,13 +78,31 @@ export interface CliConfig {
77
78
  /** cli-template's `--category`; `other` is any API outside them. */
78
79
  category: CliCategory;
79
80
  /**
80
- * A crm, tracker or content CLI's source; checked against the generated API by `parseCrmManifest`,
81
- * `parseTrackerManifest` or `parseContentManifest` once the api group exists.
81
+ * A crm, tracker, content or files CLI's source; checked against the generated API by `parseCrmManifest`,
82
+ * `parseTrackerManifest`, `parseContentManifest` or `parseDocumentManifest` once the api group exists. A files CLI may
83
+ * have none: its source is then code of its own.
82
84
  */
83
- source?: CrmManifest | TrackerManifest | ContentManifest;
85
+ source?: CrmManifest | TrackerManifest | ContentManifest | (DocumentManifest & {
86
+ readonly kinds?: undefined;
87
+ });
88
+ /** What every request of the `api` group and the source carries, and how fast they go. */
89
+ api?: CliApi;
84
90
  /** The module of named hooks, relative to the config: `./src/hooks.ts`. */
85
91
  hooks?: string;
86
92
  }
93
+ /** One pace: requests a minute, and how many may go at once after a pause. */
94
+ export interface CliPace {
95
+ perMinute: number;
96
+ burst?: number;
97
+ }
98
+ export interface CliApi {
99
+ /** Fixed headers, such as the API's version (`notion-version`); never a credential, which the sign-in sends. */
100
+ headers?: Readonly<Record<string, string>>;
101
+ /** The pace of every request; `operations` gives one operation a slower pace of its own, kept beside it. */
102
+ pace?: CliPace & {
103
+ operations?: Readonly<Record<string, CliPace>>;
104
+ };
105
+ }
87
106
  /** Types the config in the editor; it returns what it is given. */
88
107
  export declare const defineCli: (config: CliConfig) => CliConfig;
89
108
  /**
@@ -56,6 +56,10 @@ const verify = v.optional(v.strictObject({
56
56
  name: v.optional(dotPath),
57
57
  active: v.optional(dotPath),
58
58
  }));
59
+ const pace = {
60
+ perMinute: v.pipe(v.number(), v.minValue(1), v.maxValue(60_000)),
61
+ burst: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))),
62
+ };
59
63
  const schema = v.strictObject({
60
64
  identity: v.strictObject({
61
65
  command: word,
@@ -89,6 +93,13 @@ const schema = v.strictObject({
89
93
  ]),
90
94
  category: v.picklist(CLI_CATEGORIES),
91
95
  source: v.optional(v.looseObject({})),
96
+ api: v.optional(v.strictObject({
97
+ headers: v.optional(v.record(v.pipe(v.string(), v.regex(/^[A-Za-z0-9-]+$/, "a header name: letters, digits and dashes"), v.check((name) => !/^(authorization|cookie|proxy-authorization)$/i.test(name) && !secretName(name), "a header that holds no credential: the sign-in sends that, and the config is committed")), v.pipe(v.string(), v.minLength(1)))),
98
+ pace: v.optional(v.strictObject({
99
+ ...pace,
100
+ operations: v.optional(v.record(v.pipe(v.string(), v.minLength(1)), v.strictObject(pace))),
101
+ })),
102
+ })),
92
103
  hooks: v.optional(v.pipe(v.string(), v.regex(/^\.\/([^\s]*\/)?[^/\s.][^/\s]*\.[cm]?[jt]s$/, "a module in the project, such as ./src/hooks.ts"), v.check((text) => !/\.d\.[cm]?ts$/.test(text), "a module, not a .d.ts declaration file"), v.check((text) => !text.split(/[\\/]/).includes(".."), "a module in the project, without .."))),
93
104
  });
94
105
  /**
@@ -115,8 +126,8 @@ export const parseCliConfig = (input) => {
115
126
  const output = parsed.output;
116
127
  const config = output;
117
128
  const sourced = config.category === "crm" || config.category === "tracker" || config.category === "content";
118
- if (!sourced && config.source)
119
- throw new CliError("configuration_error", "wirecat.config: source: only a crm, tracker or content CLI reads a source yet", {
129
+ if (!sourced && config.category !== "files" && config.source)
130
+ throw new CliError("configuration_error", "wirecat.config: source: only a crm, tracker, content or files CLI reads a source yet", {
120
131
  reason: "manifest.invalid",
121
132
  });
122
133
  if (sourced && !config.source)
@@ -57,6 +57,8 @@ export interface QueryExecution {
57
57
  unstemmed?: boolean;
58
58
  /** `mail` searches the mail tables; the default is messages. */
59
59
  corpus?: "messages" | "mail";
60
+ /** Rank each chat's hits by how rare the query words they hold are (`wordRarity`); today's order picks the chats. */
61
+ rareWordsFirst?: boolean;
60
62
  }
61
63
  /** A leaf that reads the word index: every `text` and `exact` leaf, stemmed or not. */
62
64
  export declare const hasText: (node: QueryNode) => boolean;
@@ -3,6 +3,8 @@ 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;
5
5
  export declare const changedSince: (previous: SourceFile, file: SourceFile) => boolean;
6
+ /** Saved documents a source asks to read again, at most, in one pass. */
7
+ export declare const REREAD_BATCH = 50;
6
8
  interface WalkStore<M extends SourceFile> {
7
9
  read: (scope: string) => SourceWalk<M> | undefined;
8
10
  save: (walk: SourceWalk<M>) => void;
@@ -13,6 +13,8 @@ export const changedSince = (previous, file) => previous.version !== file.versio
13
13
  previous.canDownload !== file.canDownload ||
14
14
  JSON.stringify(previous.parents) !== JSON.stringify(file.parents);
15
15
  const SAVE_EVERY_MS = 2000;
16
+ /** Saved documents a source asks to read again, at most, in one pass. */
17
+ export const REREAD_BATCH = 50;
16
18
  // What a pass of a source without a change feed records as its cursor: the next pass is not a first one, so it saves
17
19
  // only what changed.
18
20
  export const WALKED = "walked";
@@ -344,6 +346,9 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
344
346
  }
345
347
  const jobs = [];
346
348
  const skipped = [];
349
+ const again = [];
350
+ let rereads = 0;
351
+ const reread = (known) => known !== undefined && !known.notRead && rereads < REREAD_BATCH && source.reread?.(known) === true && ++rereads > 0;
347
352
  for (const root of roots)
348
353
  if (folders[root]?.trashed)
349
354
  skipped.push({ id: root, reason: "selected folder is unavailable" });
@@ -372,8 +377,15 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
372
377
  initial ||
373
378
  (!feed && moved(known.metadata, file)))
374
379
  jobs.push({ id, kind: "save", file });
380
+ else if (reread(known))
381
+ again.push({ id, kind: "save", file });
375
382
  }
383
+ else if (reread(known))
384
+ again.push({ id, kind: "save", file });
376
385
  }
386
+ // After every real edit, so a run that stops on its deadline spends it on those first.
387
+ for (const job of again)
388
+ jobs.push(job);
377
389
  for (const id of Object.keys(state.documents)) {
378
390
  const file = files.get(id);
379
391
  if (!file || !inScope(file, roots, folders, matched, scoped))
@@ -1,3 +1,12 @@
1
+ import { type ConversationHit } from "../store/store.js";
1
2
  import type { ServiceDeps } from "./deps.js";
2
3
  import type { EmbeddingsService } from "./embeddings.js";
3
4
  export declare const embeddingsSearch: (deps: ServiceDeps) => Pick<EmbeddingsService, "search" | "related">;
5
+ /**
6
+ * Each chat's best hits, as many as the page holds, with each one's lead over the chat's `PER_CHAT`th best (or its
7
+ * last, in a chat with fewer).
8
+ */
9
+ export declare const shared: (hits: ConversationHit[], limit: number) => {
10
+ hit: ConversationHit;
11
+ lead: number;
12
+ }[];