@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.
- package/CHANGELOG.md +62 -0
- package/dist/cli/documents/index.d.ts +2 -0
- package/dist/cli/documents/index.js +2 -0
- package/dist/cli/documents/manifest/manifest.d.ts +82 -0
- package/dist/cli/documents/manifest/manifest.js +97 -0
- package/dist/cli/documents/manifest/source.d.ts +35 -0
- package/dist/cli/documents/manifest/source.js +257 -0
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/cli/messenger/conversation-answers.d.ts +1 -1
- package/dist/cli/messenger/conversation-answers.js +4 -2
- package/dist/cli/messenger/conversations-command.js +13 -4
- package/dist/cli/service-api-manifest.d.ts +2 -0
- package/dist/cli/service-api-manifest.js +6 -6
- package/dist/content/manifest/writer.js +5 -1
- package/dist/documents/model.d.ts +6 -0
- package/dist/entities/conversation-results.d.ts +5 -0
- package/dist/entities/conversation-results.js +6 -1
- package/dist/entities/index.d.ts +3 -0
- package/dist/errors/reasons.js +8 -0
- package/dist/manifest/index.d.ts +22 -3
- package/dist/manifest/index.js +13 -2
- package/dist/search/lucene/resolved.d.ts +2 -0
- package/dist/services/documents/plan.d.ts +2 -0
- package/dist/services/documents/plan.js +12 -0
- package/dist/services/embeddings-search.d.ts +9 -0
- package/dist/services/embeddings-search.js +189 -69
- package/dist/services/embeddings.d.ts +6 -0
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/named-chat.d.ts +3 -3
- package/dist/services/named-chat.js +12 -3
- package/dist/store/conversations.d.ts +21 -0
- package/dist/store/conversations.js +13 -0
- package/dist/store/slow-queries.d.ts +7 -0
- package/dist/store/slow-queries.js +47 -0
- package/dist/store/sqlite/conversations.d.ts +21 -0
- package/dist/store/sqlite/conversations.js +50 -0
- package/dist/store/sqlite/lucene-fields.d.ts +2 -0
- package/dist/store/sqlite/lucene-fields.js +22 -0
- package/dist/store/sqlite/lucene.js +30 -42
- package/dist/store/sqlite/open.js +3 -0
- package/dist/store/sqlite/vector-index.d.ts +3 -1
- package/dist/store/sqlite/vector-index.js +5 -3
- package/dist/store/sqlite/vectors.js +20 -11
- package/dist/store/sqlite/word-rarity.d.ts +14 -0
- package/dist/store/sqlite/word-rarity.js +22 -0
- package/package.json +2 -2
- package/parity.json +5 -0
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,68 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
|
|
|
5
5
|
minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
|
|
6
6
|
shape of this file.
|
|
7
7
|
|
|
8
|
+
## 0.718.0 — 21.11.2026
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **A `files` CLI's source can come from its config.** `documentSourceFromManifest` (`@wirecat/cli-core/documents/cli`)
|
|
13
|
+
answers a `DocumentSource` from the calls `wirecat.config.ts` names: the account, one file, a folder's children a
|
|
14
|
+
page at a time, the changes since a time and a document's Markdown. Hooks give what the manifest cannot say, through
|
|
15
|
+
the same calls. `parseCliConfig` takes a source for the `files` category, which stays optional there
|
|
16
|
+
([DOCUMENTS.md](docs/dev/DOCUMENTS.md#a-source-from-a-manifest)).
|
|
17
|
+
- **`wirecat.config.ts` says the API's fixed headers and its paces**: `api.headers` (a header that could hold a
|
|
18
|
+
credential is refused) and `api.pace`, with a slower pace for one operation in `api.pace.operations`. cli-core
|
|
19
|
+
checks them; the CLI passes them to its transport.
|
|
20
|
+
- **A documents source can ask for a saved document to be read again** though it did not change: `reread(saved)`,
|
|
21
|
+
at most 50 a pass, for a source that learned to read something later, such as a page's authors.
|
|
22
|
+
- **`search conversations` shows what each hit says.** Every hit carries `lines`: up to three of its chunk's messages,
|
|
23
|
+
the ones sharing most words with the query, as "sender: text" cut to 200 characters; a longer one keeps its first 80
|
|
24
|
+
and the part around the match. An agent sees the answer in the first call instead of opening one hit after another;
|
|
25
|
+
the owner's own messages are marked "(you)", and in the block of the owner's conversations they come first.
|
|
26
|
+
- **`search conversations --like <text>`**: a made-up one-sentence reply that would answer the query, searched by
|
|
27
|
+
meaning beside the query and fused with it. It finds an answer worded unlike the question, in one call.
|
|
28
|
+
- `WIRECAT_SQL_SLOW_MS=<ms>` prints each store statement slower than that to stderr, with its time, rows and shape.
|
|
29
|
+
|
|
30
|
+
### Fixed
|
|
31
|
+
|
|
32
|
+
- **A content `publish` or `unpublish` asks one question, not two.** A CLI that gives its raw update route the
|
|
33
|
+
content command's own key (WC-PERM-22, as wordpress-cli gives `api posts-update` the key `posts.update`) asked
|
|
34
|
+
`posts.publish`, then `posts.update` again when the write went out. Publishing is sent as an update, so a yes to
|
|
35
|
+
`posts.publish` or `posts.unpublish` now counts for `posts.update` on that route, and for no other resource's
|
|
36
|
+
update key. A yes to `update` still does not count for a publish key, so updating a published post asks for it as
|
|
37
|
+
before.
|
|
38
|
+
- **A capitalised word that is not a name no longer sends a search into one dialog.** A place or a brand written a few
|
|
39
|
+
times in one private chat made the search treat it as that person's name, and that chat's hits filled the page. The
|
|
40
|
+
chat must now hold at least 5% of the word's uses across all chats, groups included.
|
|
41
|
+
- **A big group no longer hides its answers behind its own size.** When one group held most of the candidates of a
|
|
42
|
+
search across chats, its 20th best was nearly as close as its best, so nothing in it ranked high. Such a group (100
|
|
43
|
+
or more of the 500 candidates) is now measured against its 100th best, and its entries past the usual 20 come after
|
|
44
|
+
every other chat's, so private dialogs keep their places.
|
|
45
|
+
- **A hit's lines show the message after the one that asks.** An answer rarely repeats the question's words, so the
|
|
46
|
+
line after the best match on them is shown too, and the question's own words count twice against a made-up answer's
|
|
47
|
+
(`--like`) when lines are picked.
|
|
48
|
+
- **A hit's lines show a reply that sits outside its chunk.** A later answer to a message of the chunk is often put in
|
|
49
|
+
another chunk, so the best such reply (by the query's words, else the oldest) is shown after the hit's lines, one per
|
|
50
|
+
hit.
|
|
51
|
+
- **The owner's block keeps a conversation the named-chat step pushed off the page.** Its chunk was left out of the
|
|
52
|
+
block because the list showed that conversation, and then the named chat's hits pushed it out of the list.
|
|
53
|
+
- **A question searched by words is ranked by relevance again when one of its words cannot rank.** A word shorter than
|
|
54
|
+
three letters next to longer ones, or a word start no indexed word has, dropped the relevance score of the whole
|
|
55
|
+
question, and its matches came newest first. The ranking now uses the words it can; which messages match is
|
|
56
|
+
unchanged.
|
|
57
|
+
- **A conversation search by words ranks a chat's messages by how rare the words they hold are.** A common word has
|
|
58
|
+
many forms, and each form was weighed on its own, so short messages holding one rare form of it came before the
|
|
59
|
+
message holding the rarer words of the question. Each chat's matches are now ranked by how few messages hold each
|
|
60
|
+
word they share with the question; which chats fill the list is decided as before, so a small chat's answer is not
|
|
61
|
+
pushed out by large groups.
|
|
62
|
+
- **A meaning search over all chats no longer reads every vector of the store.** The vector index rarely held the
|
|
63
|
+
exact answer among its most candidates across all chats, and the search then fell back to a scan of every vector:
|
|
64
|
+
15 seconds and more when the store was not in memory. Across all chats it now keeps what the index's 4,096 nearest
|
|
65
|
+
chunks hold.
|
|
66
|
+
- **The owner's block finds the owner's chunks through the owner's own messages.** Without planner statistics SQLite
|
|
67
|
+
walked every message of the account to find them: 17 seconds from a cold disk on a store of a million messages,
|
|
68
|
+
0.35 seconds now.
|
|
69
|
+
|
|
8
70
|
## 0.717.0 — 21.11.2026
|
|
9
71
|
|
|
10
72
|
### Changed — may break callers
|
|
@@ -35,3 +35,5 @@ export interface DocumentCommands<S> {
|
|
|
35
35
|
*/
|
|
36
36
|
export declare const addDocumentCommands: <S>(program: Command, options: DocumentCommands<S>) => Command;
|
|
37
37
|
export { claimDocumentAccount, type DocumentLibraryOptions, type DocumentLibraryTools, type DocumentSourceRun, type DocumentWarning, documentLibraryCommands, documentProfile, } from "./library.js";
|
|
38
|
+
export { type DocumentCall, type DocumentFileMap, type DocumentManifest, parseDocumentManifest, } from "./manifest/manifest.js";
|
|
39
|
+
export { type DocumentManifestSourceOptions, type DocumentManifestTools, type DocumentSlots, documentSourceFromManifest, type ManifestDocumentSource, } from "./manifest/source.js";
|
|
@@ -31,3 +31,5 @@ export const addDocumentCommands = (program, options) => {
|
|
|
31
31
|
return documents;
|
|
32
32
|
};
|
|
33
33
|
export { claimDocumentAccount, documentLibraryCommands, documentProfile, } from "./library.js";
|
|
34
|
+
export { parseDocumentManifest, } from "./manifest/manifest.js";
|
|
35
|
+
export { documentSourceFromManifest, } from "./manifest/source.js";
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { ServiceApiManifest } from "../../service-api-manifest.js";
|
|
2
|
+
/**
|
|
3
|
+
* One read the source sends: an operation of the generated API and what to put in it. A value `"{id}"`, `"{since}"`
|
|
4
|
+
* or `"{cursor}"` anywhere in `path`, `query` or `body` is filled in by the source; one left without a value is left
|
|
5
|
+
* out. `items`: where the answer's rows are when the operation has no `pagination`.
|
|
6
|
+
*/
|
|
7
|
+
export interface DocumentCall {
|
|
8
|
+
operation: string;
|
|
9
|
+
path?: Readonly<Record<string, string>>;
|
|
10
|
+
query?: Readonly<Record<string, string | number | boolean>>;
|
|
11
|
+
body?: unknown;
|
|
12
|
+
items?: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Dot paths into one row of the answer. `parent` names one parent, `parents` a list of them; `folder` says which rows
|
|
16
|
+
* are folders (`path` equal to `is`). `mime` is a path, or with `folder` a fixed type for files and for folders.
|
|
17
|
+
*/
|
|
18
|
+
export interface DocumentFileMap {
|
|
19
|
+
id: string;
|
|
20
|
+
name: string;
|
|
21
|
+
parent?: string;
|
|
22
|
+
parents?: string;
|
|
23
|
+
url?: string;
|
|
24
|
+
modifiedAt?: string;
|
|
25
|
+
createdAt?: string;
|
|
26
|
+
version?: string;
|
|
27
|
+
trashed?: string;
|
|
28
|
+
mime?: string;
|
|
29
|
+
folder?: {
|
|
30
|
+
path: string;
|
|
31
|
+
is: string | number | boolean;
|
|
32
|
+
mime?: {
|
|
33
|
+
folder: string;
|
|
34
|
+
file: string;
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* A documents source read from a config (a `files` CLI): the calls it sends and where its answers hold a file. A
|
|
40
|
+
* method the manifest does not describe comes from a hook; `reads` names the calls a hook sends, so every request a
|
|
41
|
+
* sync makes is in the config.
|
|
42
|
+
*/
|
|
43
|
+
export interface DocumentManifest {
|
|
44
|
+
provider: string;
|
|
45
|
+
/** The account: the values at `id` joined by `:` (`workspace:user`). */
|
|
46
|
+
identity: DocumentCall & {
|
|
47
|
+
id: string | readonly string[];
|
|
48
|
+
};
|
|
49
|
+
/** One file by its id: needs `"{id}"`. */
|
|
50
|
+
get?: DocumentCall & {
|
|
51
|
+
map: DocumentFileMap;
|
|
52
|
+
};
|
|
53
|
+
/** A folder's children, by the operation's `pagination`: needs `"{id}"`. Mapped by `get.map` unless it has one. */
|
|
54
|
+
children?: DocumentCall & {
|
|
55
|
+
map?: DocumentFileMap;
|
|
56
|
+
};
|
|
57
|
+
/** What changed since a time, newest first or in any order: needs `"{since}"`. */
|
|
58
|
+
changes?: DocumentCall & {
|
|
59
|
+
since: "iso" | "ms" | "seconds";
|
|
60
|
+
time: string;
|
|
61
|
+
overlapMs?: number;
|
|
62
|
+
map?: DocumentFileMap;
|
|
63
|
+
};
|
|
64
|
+
/** A document's text as Markdown, at `markdown` in the answer: needs `"{id}"`. */
|
|
65
|
+
content?: DocumentCall & {
|
|
66
|
+
markdown: string;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* A saved document read again though it did not change: one whose `providerMetadata` has no value at `missing`
|
|
70
|
+
* (a field the source learned to read later, such as authors).
|
|
71
|
+
*/
|
|
72
|
+
reread?: {
|
|
73
|
+
missing: string;
|
|
74
|
+
};
|
|
75
|
+
/** Calls named for the hooks, sent with `read(name, slots)`. */
|
|
76
|
+
reads?: Readonly<Record<string, DocumentCall>>;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The manifest checked against its shape and the generated API: each operation exists and only reads, and each call
|
|
80
|
+
* places the value it needs. Every error names where it is.
|
|
81
|
+
*/
|
|
82
|
+
export declare const parseDocumentManifest: (input: unknown, api: ServiceApiManifest) => DocumentManifest;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import * as v from "valibot";
|
|
3
|
+
import { editDistance } from "../../../search/correct.js";
|
|
4
|
+
const dotPath = v.pipe(v.string(), v.regex(/^[^.\s]+(\.[^.\s]+)*$/, "a dot path into the answer, such as data.id"));
|
|
5
|
+
const scalar = v.union([v.string(), v.number(), v.boolean()]);
|
|
6
|
+
const callEntries = {
|
|
7
|
+
operation: v.pipe(v.string(), v.minLength(1)),
|
|
8
|
+
path: v.optional(v.record(v.string(), v.string())),
|
|
9
|
+
query: v.optional(v.record(v.string(), scalar)),
|
|
10
|
+
body: v.optional(v.unknown()),
|
|
11
|
+
items: v.optional(dotPath),
|
|
12
|
+
};
|
|
13
|
+
const fileMap = v.strictObject({
|
|
14
|
+
id: dotPath,
|
|
15
|
+
name: dotPath,
|
|
16
|
+
parent: v.optional(dotPath),
|
|
17
|
+
parents: v.optional(dotPath),
|
|
18
|
+
url: v.optional(dotPath),
|
|
19
|
+
modifiedAt: v.optional(dotPath),
|
|
20
|
+
createdAt: v.optional(dotPath),
|
|
21
|
+
version: v.optional(dotPath),
|
|
22
|
+
trashed: v.optional(dotPath),
|
|
23
|
+
mime: v.optional(dotPath),
|
|
24
|
+
folder: v.optional(v.strictObject({
|
|
25
|
+
path: dotPath,
|
|
26
|
+
is: scalar,
|
|
27
|
+
mime: v.optional(v.strictObject({ folder: v.string(), file: v.string() })),
|
|
28
|
+
})),
|
|
29
|
+
});
|
|
30
|
+
const schema = v.strictObject({
|
|
31
|
+
provider: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9-]*$/, "lower-case letters, digits and dashes")),
|
|
32
|
+
identity: v.strictObject({ ...callEntries, id: v.union([dotPath, v.pipe(v.array(dotPath), v.minLength(1))]) }),
|
|
33
|
+
get: v.optional(v.strictObject({ ...callEntries, map: fileMap })),
|
|
34
|
+
children: v.optional(v.strictObject({ ...callEntries, map: v.optional(fileMap) })),
|
|
35
|
+
changes: v.optional(v.strictObject({
|
|
36
|
+
...callEntries,
|
|
37
|
+
since: v.picklist(["iso", "ms", "seconds"]),
|
|
38
|
+
time: dotPath,
|
|
39
|
+
overlapMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))),
|
|
40
|
+
map: v.optional(fileMap),
|
|
41
|
+
})),
|
|
42
|
+
content: v.optional(v.strictObject({ ...callEntries, markdown: dotPath })),
|
|
43
|
+
reread: v.optional(v.strictObject({ missing: dotPath })),
|
|
44
|
+
reads: v.optional(v.record(v.pipe(v.string(), v.regex(/^[a-z][A-Za-z0-9]*$/, "a camelCase name")), v.strictObject(callEntries))),
|
|
45
|
+
});
|
|
46
|
+
const BUILT_IN = ["identity", "get", "children", "changes", "content"];
|
|
47
|
+
const invalid = (where, message) => new CliError("configuration_error", `source manifest: ${where}: ${message}`, { reason: "manifest.invalid" });
|
|
48
|
+
const nearest = (wanted, known) => known
|
|
49
|
+
.map((one) => ({ one, edits: editDistance(wanted, one, 2) }))
|
|
50
|
+
.filter(({ edits }) => edits <= 2)
|
|
51
|
+
.sort((a, b) => a.edits - b.edits)[0]?.one;
|
|
52
|
+
const hasPlaceholder = (value, placeholder) => value === placeholder ||
|
|
53
|
+
(Array.isArray(value) && value.some((one) => hasPlaceholder(one, placeholder))) ||
|
|
54
|
+
(typeof value === "object" && value !== null && Object.values(value).some((one) => hasPlaceholder(one, placeholder)));
|
|
55
|
+
/**
|
|
56
|
+
* The manifest checked against its shape and the generated API: each operation exists and only reads, and each call
|
|
57
|
+
* places the value it needs. Every error names where it is.
|
|
58
|
+
*/
|
|
59
|
+
export const parseDocumentManifest = (input, api) => {
|
|
60
|
+
const parsed = v.safeParse(schema, input);
|
|
61
|
+
if (!parsed.success) {
|
|
62
|
+
const [issue] = parsed.issues;
|
|
63
|
+
throw invalid(v.getDotPath(issue) ?? "(root)", issue.message);
|
|
64
|
+
}
|
|
65
|
+
const manifest = parsed.output;
|
|
66
|
+
const operations = new Map(api.operations.map((one) => [one.id, one]));
|
|
67
|
+
const known = [...operations.keys()];
|
|
68
|
+
const check = (where, call, placeholder) => {
|
|
69
|
+
if (!call)
|
|
70
|
+
return;
|
|
71
|
+
const operation = operations.get(call.operation);
|
|
72
|
+
if (!operation) {
|
|
73
|
+
const near = nearest(call.operation, known);
|
|
74
|
+
throw invalid(`${where}.operation`, `no operation ${call.operation} in the API${near ? `; did you mean ${near}?` : ""}`);
|
|
75
|
+
}
|
|
76
|
+
if (operation.effect !== "read")
|
|
77
|
+
throw invalid(`${where}.operation`, `${call.operation} is a ${operation.effect}, and a source only reads`);
|
|
78
|
+
if (placeholder && !hasPlaceholder([call.path, call.query, call.body], placeholder))
|
|
79
|
+
throw invalid(where, `no "${placeholder}" in its path, query or body`);
|
|
80
|
+
};
|
|
81
|
+
check("identity", manifest.identity);
|
|
82
|
+
check("get", manifest.get, "{id}");
|
|
83
|
+
check("children", manifest.children, "{id}");
|
|
84
|
+
check("changes", manifest.changes, "{since}");
|
|
85
|
+
check("content", manifest.content, "{id}");
|
|
86
|
+
for (const [name, call] of Object.entries(manifest.reads ?? {})) {
|
|
87
|
+
// A hook sends a named call and a manifest call by the same name; one would hide the other.
|
|
88
|
+
if (BUILT_IN.includes(name))
|
|
89
|
+
throw invalid(`reads.${name}`, `${name} is the manifest's own call; name it otherwise`);
|
|
90
|
+
check(`reads.${name}`, call);
|
|
91
|
+
}
|
|
92
|
+
if (manifest.children && !manifest.get?.map && !manifest.children.map)
|
|
93
|
+
throw invalid("children", "no map: give children a map, or get one");
|
|
94
|
+
if (manifest.changes && !manifest.get?.map && !manifest.changes.map)
|
|
95
|
+
throw invalid("changes", "no map: give changes a map, or get one");
|
|
96
|
+
return manifest;
|
|
97
|
+
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { DocumentSource, FeedlessDocumentSource, SourceFile } from "../../../documents.js";
|
|
2
|
+
import type { ServiceApiCall } from "../../service-api-call.js";
|
|
3
|
+
import { type ServiceApiManifest } from "../../service-api-manifest.js";
|
|
4
|
+
import { type DocumentManifest } from "./manifest.js";
|
|
5
|
+
/** What a slot in a call is filled with; one left without a value is left out of the request. */
|
|
6
|
+
export interface DocumentSlots {
|
|
7
|
+
id?: string;
|
|
8
|
+
since?: string;
|
|
9
|
+
cursor?: string;
|
|
10
|
+
}
|
|
11
|
+
/** A source of a `files` CLI: a change feed when the manifest or a hook gives one. */
|
|
12
|
+
export type ManifestDocumentSource<M extends SourceFile = SourceFile> = FeedlessDocumentSource<M> & Partial<Pick<DocumentSource<M>, "startToken" | "changes">>;
|
|
13
|
+
/** What a hook builds on: the manifest's own calls, and the source the manifest alone describes. */
|
|
14
|
+
export interface DocumentManifestTools<M extends SourceFile = SourceFile> {
|
|
15
|
+
manifest: DocumentManifest;
|
|
16
|
+
/** Sends one named call of `reads`, or `identity`, `get`, `children`, `changes`, `content`. */
|
|
17
|
+
read(name: string, slots?: DocumentSlots, body?: unknown): Promise<unknown>;
|
|
18
|
+
/** One row of an answer as a file, by `get.map` (or the named call's own map). */
|
|
19
|
+
file(row: unknown, from?: "get" | "children" | "changes"): M;
|
|
20
|
+
base: Partial<ManifestDocumentSource<M>>;
|
|
21
|
+
}
|
|
22
|
+
export interface DocumentManifestSourceOptions<M extends SourceFile = SourceFile> {
|
|
23
|
+
api: ServiceApiManifest;
|
|
24
|
+
call: ServiceApiCall;
|
|
25
|
+
now?: () => number;
|
|
26
|
+
/** The methods the manifest cannot describe, or that the provider does otherwise; each wins over the manifest's. */
|
|
27
|
+
hooks?: (tools: DocumentManifestTools<M>) => Partial<ManifestDocumentSource<M>>;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* A `DocumentSource` read from a manifest: the account, one file, a folder's children and the changes since a time
|
|
31
|
+
* by the calls it names, each paged by its operation's own `pagination`, each row mapped onto a file; a document's
|
|
32
|
+
* Markdown from one call. What the manifest cannot say comes from `hooks`, which send their requests through the
|
|
33
|
+
* calls the manifest names.
|
|
34
|
+
*/
|
|
35
|
+
export declare const documentSourceFromManifest: <M extends SourceFile = SourceFile>(input: unknown, options: DocumentManifestSourceOptions<M>) => ManifestDocumentSource<M>;
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { answerAt as at, nextPage, parameterValue, withValue, } from "../../service-api-manifest.js";
|
|
3
|
+
import { parseDocumentManifest } from "./manifest.js";
|
|
4
|
+
const OVERLAP_MS = 10 * 60_000;
|
|
5
|
+
/** A change round reads at most this many pages; the next round goes on from the time the first one started. */
|
|
6
|
+
const MOST_PAGES = 100;
|
|
7
|
+
const DROP = Symbol("drop");
|
|
8
|
+
const fill = (value, slots) => {
|
|
9
|
+
if (value === "{id}")
|
|
10
|
+
return slots.id ?? DROP;
|
|
11
|
+
if (value === "{since}")
|
|
12
|
+
return slots.since ?? DROP;
|
|
13
|
+
if (value === "{cursor}")
|
|
14
|
+
return slots.cursor ?? DROP;
|
|
15
|
+
if (Array.isArray(value))
|
|
16
|
+
return value.map((one) => fill(one, slots)).filter((one) => one !== DROP);
|
|
17
|
+
if (typeof value === "object" && value !== null)
|
|
18
|
+
return Object.fromEntries(Object.entries(value).flatMap(([key, one]) => {
|
|
19
|
+
const filled = fill(one, slots);
|
|
20
|
+
return filled === DROP ? [] : [[key, filled]];
|
|
21
|
+
}));
|
|
22
|
+
return value;
|
|
23
|
+
};
|
|
24
|
+
const inputOf = (call, slots, body) => {
|
|
25
|
+
const path = fill(call.path ?? {}, slots);
|
|
26
|
+
const query = fill(call.query ?? {}, slots);
|
|
27
|
+
const sent = body ?? (call.body === undefined ? undefined : fill(call.body, slots));
|
|
28
|
+
return {
|
|
29
|
+
path: Object.fromEntries(Object.entries(path).map(([key, one]) => [key, String(one)])),
|
|
30
|
+
query: Object.fromEntries(Object.entries(query).map(([key, one]) => [key, String(one)])),
|
|
31
|
+
headers: {},
|
|
32
|
+
fields: {},
|
|
33
|
+
...(sent === undefined || sent === DROP ? {} : { body: JSON.stringify(sent) }),
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
const SINCE = {
|
|
37
|
+
iso: (ms) => new Date(ms).toISOString(),
|
|
38
|
+
ms: (ms) => String(ms),
|
|
39
|
+
seconds: (ms) => String(Math.floor(ms / 1000)),
|
|
40
|
+
};
|
|
41
|
+
const pageParameter = (pagination) => pagination.style === "cursor"
|
|
42
|
+
? pagination.cursor
|
|
43
|
+
: pagination.style === "offset"
|
|
44
|
+
? pagination.offset
|
|
45
|
+
: pagination.style === "page"
|
|
46
|
+
? pagination.page
|
|
47
|
+
: undefined;
|
|
48
|
+
const text = (value) => value === null || value === undefined ? undefined : typeof value === "string" ? value : String(value);
|
|
49
|
+
const time = (value) => {
|
|
50
|
+
const ms = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
|
|
51
|
+
return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* A `DocumentSource` read from a manifest: the account, one file, a folder's children and the changes since a time
|
|
55
|
+
* by the calls it names, each paged by its operation's own `pagination`, each row mapped onto a file; a document's
|
|
56
|
+
* Markdown from one call. What the manifest cannot say comes from `hooks`, which send their requests through the
|
|
57
|
+
* calls the manifest names.
|
|
58
|
+
*/
|
|
59
|
+
export const documentSourceFromManifest = (input, options) => {
|
|
60
|
+
const manifest = parseDocumentManifest(input, options.api);
|
|
61
|
+
const now = options.now ?? Date.now;
|
|
62
|
+
const operations = new Map(options.api.operations.map((one) => [one.id, one]));
|
|
63
|
+
const calls = {
|
|
64
|
+
...manifest.reads,
|
|
65
|
+
identity: manifest.identity,
|
|
66
|
+
get: manifest.get,
|
|
67
|
+
children: manifest.children,
|
|
68
|
+
changes: manifest.changes,
|
|
69
|
+
content: manifest.content,
|
|
70
|
+
};
|
|
71
|
+
const callOf = (name) => {
|
|
72
|
+
const call = calls[name];
|
|
73
|
+
if (!call)
|
|
74
|
+
throw new CliError("configuration_error", `source manifest: no call ${name}`, { reason: "manifest.invalid" });
|
|
75
|
+
return call;
|
|
76
|
+
};
|
|
77
|
+
const send = (call, request) => options.call(call.operation, request);
|
|
78
|
+
const read = (name, slots = {}, body) => {
|
|
79
|
+
const call = callOf(name);
|
|
80
|
+
return send(call, inputOf(call, slots, body));
|
|
81
|
+
};
|
|
82
|
+
const rowsOf = (call, answer) => {
|
|
83
|
+
const pagination = operations.get(call.operation)?.pagination;
|
|
84
|
+
const listed = call.items ? at(answer, call.items) : pagination?.items ? at(answer, pagination.items) : answer;
|
|
85
|
+
return Array.isArray(listed) ? listed : [];
|
|
86
|
+
};
|
|
87
|
+
/** One page of a listing call: its rows and the token of the next page, when there is one. */
|
|
88
|
+
const page = async (call, slots, token) => {
|
|
89
|
+
const pagination = operations.get(call.operation)?.pagination;
|
|
90
|
+
const parameter = pagination ? pageParameter(pagination) : undefined;
|
|
91
|
+
// A next-page link names no parameter to carry between rounds; one page of it would pass the rest over.
|
|
92
|
+
if (pagination && !parameter)
|
|
93
|
+
throw new CliError("configuration_error", `source manifest: ${call.operation} pages by a link, which a source cannot`, {
|
|
94
|
+
reason: "manifest.invalid",
|
|
95
|
+
});
|
|
96
|
+
const first = inputOf(call, slots);
|
|
97
|
+
const value = pagination?.style === "cursor" ? token : Number(token);
|
|
98
|
+
const request = token !== undefined && parameter && value !== undefined ? withValue(first, parameter, value) : first;
|
|
99
|
+
const answer = await send(call, request);
|
|
100
|
+
if (!pagination || !parameter)
|
|
101
|
+
return { rows: rowsOf(call, answer) };
|
|
102
|
+
const step = nextPage(pagination, request, answer);
|
|
103
|
+
const next = step.next && "input" in step.next ? parameterValue(step.next.input, parameter) : undefined;
|
|
104
|
+
return { rows: rowsOf(call, answer), ...(next === undefined || next === null ? {} : { next: String(next) }) };
|
|
105
|
+
};
|
|
106
|
+
const mapOf = (from) => {
|
|
107
|
+
const own = from === "get" ? undefined : manifest[from]?.map;
|
|
108
|
+
const map = own ?? manifest.get?.map;
|
|
109
|
+
if (!map)
|
|
110
|
+
throw new CliError("configuration_error", `source manifest: ${from} has no map`, { reason: "manifest.invalid" });
|
|
111
|
+
return map;
|
|
112
|
+
};
|
|
113
|
+
const file = (row, from = "get") => {
|
|
114
|
+
const map = mapOf(from);
|
|
115
|
+
const id = text(at(row, map.id));
|
|
116
|
+
if (!id)
|
|
117
|
+
throw new CliError("invalid_response", `a ${manifest.provider} answer has no id at ${map.id}`, {
|
|
118
|
+
reason: "source.no-id",
|
|
119
|
+
});
|
|
120
|
+
const folder = map.folder ? at(row, map.folder.path) === map.folder.is : false;
|
|
121
|
+
const listed = map.parents ? at(row, map.parents) : undefined;
|
|
122
|
+
const parents = Array.isArray(listed)
|
|
123
|
+
? listed.map(text).filter((one) => Boolean(one))
|
|
124
|
+
: map.parent && text(at(row, map.parent))
|
|
125
|
+
? [text(at(row, map.parent))]
|
|
126
|
+
: [];
|
|
127
|
+
const modifiedAt = map.modifiedAt ? time(at(row, map.modifiedAt)) : undefined;
|
|
128
|
+
const createdAt = map.createdAt ? time(at(row, map.createdAt)) : undefined;
|
|
129
|
+
const version = map.version ? text(at(row, map.version)) : modifiedAt;
|
|
130
|
+
const mime = (map.mime && text(at(row, map.mime))) ||
|
|
131
|
+
(map.folder?.mime ? (folder ? map.folder.mime.folder : map.folder.mime.file) : "application/octet-stream");
|
|
132
|
+
return {
|
|
133
|
+
id,
|
|
134
|
+
name: text(at(row, map.name))?.trim() || id,
|
|
135
|
+
mime,
|
|
136
|
+
parents,
|
|
137
|
+
url: (map.url && text(at(row, map.url))) || "",
|
|
138
|
+
trashed: map.trashed ? at(row, map.trashed) === true : false,
|
|
139
|
+
canDownload: !folder,
|
|
140
|
+
...(version ? { version } : {}),
|
|
141
|
+
...(modifiedAt ? { modifiedAt } : {}),
|
|
142
|
+
...(createdAt ? { createdAt } : {}),
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
const base = {};
|
|
146
|
+
let account;
|
|
147
|
+
base.identity = () => {
|
|
148
|
+
account ??= read("identity").then((answer) => {
|
|
149
|
+
const paths = typeof manifest.identity.id === "string" ? [manifest.identity.id] : manifest.identity.id;
|
|
150
|
+
const parts = paths.map((path) => text(at(answer, path)));
|
|
151
|
+
if (parts.some((part) => !part))
|
|
152
|
+
throw new CliError("invalid_response", `${manifest.provider} did not name the signed-in account`, {
|
|
153
|
+
reason: "source.no-account",
|
|
154
|
+
});
|
|
155
|
+
return parts.join(":");
|
|
156
|
+
});
|
|
157
|
+
// A failed read is not kept: a long-lived server would fail every later call on one network error.
|
|
158
|
+
account.catch(() => {
|
|
159
|
+
account = undefined;
|
|
160
|
+
});
|
|
161
|
+
return account;
|
|
162
|
+
};
|
|
163
|
+
const { get, children, changes, content } = manifest;
|
|
164
|
+
if (get)
|
|
165
|
+
base.metadata = async (id) => {
|
|
166
|
+
const answer = await read("get", { id });
|
|
167
|
+
return file(get.items ? at(answer, get.items) : answer);
|
|
168
|
+
};
|
|
169
|
+
if (children) {
|
|
170
|
+
base.childrenPage = async (id, cursor) => {
|
|
171
|
+
const { rows, next } = await page(children, { id }, cursor);
|
|
172
|
+
return { files: rows.map((row) => file(row, "children")), ...(next ? { cursor: next } : {}) };
|
|
173
|
+
};
|
|
174
|
+
base.children = async (id) => {
|
|
175
|
+
const files = [];
|
|
176
|
+
let cursor;
|
|
177
|
+
do {
|
|
178
|
+
const listed = await base.childrenPage(id, cursor);
|
|
179
|
+
for (const one of listed.files)
|
|
180
|
+
files.push(one);
|
|
181
|
+
cursor = listed.cursor;
|
|
182
|
+
} while (cursor);
|
|
183
|
+
return files;
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
if (changes) {
|
|
187
|
+
base.startToken = async () => String(now());
|
|
188
|
+
base.changes = async (token) => {
|
|
189
|
+
const from = Number(token);
|
|
190
|
+
if (!Number.isSafeInteger(from))
|
|
191
|
+
throw new CliError("validation_error", `not a change token of ${manifest.provider}: ${token}`, {
|
|
192
|
+
reason: "source.token-invalid",
|
|
193
|
+
});
|
|
194
|
+
const started = now();
|
|
195
|
+
const sinceMs = from - (changes.overlapMs ?? OVERLAP_MS);
|
|
196
|
+
const since = SINCE[changes.since](sinceMs);
|
|
197
|
+
const items = [];
|
|
198
|
+
let cursor;
|
|
199
|
+
let last = Number.NEGATIVE_INFINITY;
|
|
200
|
+
let oldestFirst = true;
|
|
201
|
+
for (let pages = 0; pages < MOST_PAGES; pages++) {
|
|
202
|
+
const { rows, next } = await page(changes, { since }, cursor);
|
|
203
|
+
let older = false;
|
|
204
|
+
for (const row of rows) {
|
|
205
|
+
const edited = Date.parse(time(at(row, changes.time)) ?? "");
|
|
206
|
+
if (Number.isFinite(edited)) {
|
|
207
|
+
if (edited < last)
|
|
208
|
+
oldestFirst = false;
|
|
209
|
+
last = Math.max(last, edited);
|
|
210
|
+
// A provider that sorts by time without filtering by it lists older rows too; they are not changes.
|
|
211
|
+
if (edited < sinceMs) {
|
|
212
|
+
older = true;
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
const changed = file(row, "changes");
|
|
217
|
+
items.push({ id: changed.id, removed: changed.trashed, file: changed });
|
|
218
|
+
}
|
|
219
|
+
if (!next || (older && !oldestFirst))
|
|
220
|
+
return { items, cursor: String(started) };
|
|
221
|
+
cursor = next;
|
|
222
|
+
}
|
|
223
|
+
// Past its pages, a round listed oldest first goes on next time from the newest row it read; any other order
|
|
224
|
+
// cannot say where it stopped, and would read the same pages on every round.
|
|
225
|
+
if (oldestFirst && Number.isFinite(last) && last > from)
|
|
226
|
+
return { items, cursor: String(last) };
|
|
227
|
+
throw new CliError("invalid_response", `more than ${MOST_PAGES} pages of ${manifest.provider} changed since one sync; list changes oldest first`, { reason: "source.changes-too-many" });
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
if (content)
|
|
231
|
+
base.content = async (id, maxChars, known) => {
|
|
232
|
+
const metadata = known ?? (await source.metadata(id));
|
|
233
|
+
const answer = await read("content", { id });
|
|
234
|
+
const markdown = text(at(answer, content.markdown)) ?? "";
|
|
235
|
+
const cut = maxChars === undefined ? markdown : markdown.slice(0, maxChars);
|
|
236
|
+
return { metadata, markdown: cut, text: cut, tabs: [] };
|
|
237
|
+
};
|
|
238
|
+
if (manifest.reread) {
|
|
239
|
+
const missing = manifest.reread.missing;
|
|
240
|
+
base.reread = (saved) => at(saved.metadata.providerMetadata, missing) === undefined;
|
|
241
|
+
}
|
|
242
|
+
const source = { ...base, ...options.hooks?.({ manifest, read, file, base }) };
|
|
243
|
+
source.bytes ??= async (id, known) => new TextEncoder().encode((await source.content(id, undefined, known)).markdown);
|
|
244
|
+
for (const method of ["identity", "metadata", "children", "content"])
|
|
245
|
+
if (typeof source[method] !== "function")
|
|
246
|
+
throw new CliError("configuration_error", `source manifest: no ${method}: describe it in the manifest or give it as a hook`, { reason: "manifest.invalid" });
|
|
247
|
+
// The manifest's own content gives back the metadata it was given, so the field `reread` waits for never comes.
|
|
248
|
+
if (manifest.reread && source.content === base.content)
|
|
249
|
+
throw new CliError("configuration_error", "source manifest: reread needs content from a hook, which saves the field", {
|
|
250
|
+
reason: "manifest.invalid",
|
|
251
|
+
});
|
|
252
|
+
if (Boolean(source.startToken) !== Boolean(source.changes))
|
|
253
|
+
throw new CliError("configuration_error", "source manifest: a change feed needs both startToken and changes", {
|
|
254
|
+
reason: "manifest.invalid",
|
|
255
|
+
});
|
|
256
|
+
return source;
|
|
257
|
+
};
|
|
@@ -58,8 +58,8 @@ export interface CopyAge {
|
|
|
58
58
|
}
|
|
59
59
|
export declare const ageOf: (lastSync: string | undefined, now?: number) => CopyAge;
|
|
60
60
|
export declare const staleCopy: (provider: string, lastSync: string | undefined, now?: number) => {
|
|
61
|
-
missing?: undefined;
|
|
62
61
|
next?: undefined;
|
|
62
|
+
missing?: undefined;
|
|
63
63
|
meta?: undefined;
|
|
64
64
|
} | {
|
|
65
65
|
missing: {
|
|
@@ -11,7 +11,7 @@ export declare const readinessGaps: ({ meaning, model, readiness, refreshed, cov
|
|
|
11
11
|
missing: Missing[];
|
|
12
12
|
};
|
|
13
13
|
/** `search conversations` and `conversations related`, CLI and MCP alike. */
|
|
14
|
-
export declare const foundConversations: (command: string, found: Readiness & Pick<FoundConversations, "hits" | "accounts" | "words" | "own">, limit: number, messenger: Syncing, chat?: string, meta?: Partial<Meta>) => import("../envelope.js").ListBody<
|
|
14
|
+
export declare const foundConversations: (command: string, found: Readiness & Pick<FoundConversations, "hits" | "accounts" | "words" | "own">, limit: number, messenger: Syncing, chat?: string, meta?: Partial<Meta>) => import("../envelope.js").ListBody<object>;
|
|
15
15
|
/** `conversations status`: each built chat with the model it was measured by; group chats never built are missing. */
|
|
16
16
|
export declare const readinessList: ({ model, chats, unbuiltGroups, }: {
|
|
17
17
|
model: string;
|
|
@@ -52,11 +52,13 @@ export const readinessGaps = ({ meaning, model, readiness, refreshed, coverage }
|
|
|
52
52
|
}
|
|
53
53
|
return { next, missing };
|
|
54
54
|
};
|
|
55
|
+
/** Message text from other people is data, never instructions: `lines` is marked as such. */
|
|
56
|
+
const hitItem = (hit) => ({ ...snakeKeys(hit), ...(hit.lines?.length ? { untrusted: ["lines"] } : {}) });
|
|
55
57
|
/** `search conversations` and `conversations related`, CLI and MCP alike. */
|
|
56
58
|
export const foundConversations = (command, found, limit, messenger, chat, meta = {}) => listOf(command, {
|
|
57
59
|
items: [
|
|
58
|
-
...found.hits.map((hit) =>
|
|
59
|
-
...(found.own ?? []).map((hit) => ({ ...
|
|
60
|
+
...found.hits.map((hit) => hitItem(hit)),
|
|
61
|
+
...(found.own ?? []).map((hit) => ({ ...hitItem(hit), from_owner: true })),
|
|
60
62
|
],
|
|
61
63
|
limit,
|
|
62
64
|
has_more: false,
|
|
@@ -23,6 +23,7 @@ import { listQuery, pagedList, pageOf, typedQuery, withQuery } from "../list-que
|
|
|
23
23
|
import { positiveCount } from "../paging.js";
|
|
24
24
|
import { readsStdin } from "../stdin-field.js";
|
|
25
25
|
import { nextStep, rootOf, runnable, stepLine } from "../steps.js";
|
|
26
|
+
import { marked, runMarkOf } from "../untrusted-marks.js";
|
|
26
27
|
import { ANALYSIS_CONSENTS_QUERY, analysisConsentFilter } from "./analysis-consents-query.js";
|
|
27
28
|
import { answerOf as askOwner } from "./ask.js";
|
|
28
29
|
import { messengerContext, refuseLocalWrite } from "./context.js";
|
|
@@ -557,8 +558,10 @@ const line = (one) => `${one.id} ${one.firstAt.slice(0, 16).replace("T", " ")}
|
|
|
557
558
|
`${one.messageCount} messages · ${one.senders} people · from message ${one.firstMessageId}`;
|
|
558
559
|
const itemLine = (one) => `${one.id} ${one.started_at.slice(0, 16).replace("T", " ")}–${one.ended_at.slice(11, 16)} ` +
|
|
559
560
|
`${one.messages_count} messages · ${one.senders_count} people · from ${one.first_message}`;
|
|
560
|
-
|
|
561
|
-
|
|
561
|
+
/** In a scheduled agent's run (`mark`), other people's lines go between the run's markers, as JSON marks them. */
|
|
562
|
+
const hitLine = ({ summary, chunk, score, stale, locator, lines }, mark) => `${score === null ? " — " : score.toFixed(3)} ${line(summary)} ` +
|
|
563
|
+
`(messages ${chunk.firstMessageId}–${chunk.lastMessageId})${locator ? ` ${locator}` : ""}${stale ? " stale" : ""}` +
|
|
564
|
+
(lines ?? []).map((one) => `\n ${mark === undefined ? one : marked(one, mark, "lines", locator)}`).join("");
|
|
562
565
|
const readinessLine = ({ chat, state, graph, pending, vectors }, model) => graph === null
|
|
563
566
|
? `${chat} ${state} — \`conversations links rebuild --chat ${chat}\``
|
|
564
567
|
: `${chat} ${state} built ${graph.builtAt.slice(0, 16).replace("T", " ")}, rules v${graph.rulesVersion}` +
|
|
@@ -571,6 +574,8 @@ export const conversationsSearchCommand = (messenger) => syncOptions(boundOption
|
|
|
571
574
|
.description("the conversations nearest to a query in meaning and in words, best first, in one chat or every one — " +
|
|
572
575
|
"meaning after `conversations embed`; runs on this machine")
|
|
573
576
|
.argument("<query>", "what to look for, in your own words, in any language the model reads")
|
|
577
|
+
.option("--like <text>", "a made-up reply that would answer the query, one sentence: searched by meaning too, which finds an answer " +
|
|
578
|
+
"worded unlike the question")
|
|
574
579
|
.option("--chat <chat>", `only this chat: ${messenger.chatArgument}`)
|
|
575
580
|
.option("--since-time <time>", "only those still going at this ISO 8601 time, or 30m / 2h / 1d ago, or later")
|
|
576
581
|
.option("--filter <query>", "strict Lucene filter: any message in a conversation must match; does not change the meaning query")
|
|
@@ -614,6 +619,7 @@ export const conversationsSearchCommand = (messenger) => syncOptions(boundOption
|
|
|
614
619
|
}
|
|
615
620
|
: {}),
|
|
616
621
|
limit,
|
|
622
|
+
...(options.like === undefined ? {} : { like: options.like }),
|
|
617
623
|
...(options.filter === undefined ? {} : { filter: options.filter }),
|
|
618
624
|
...(options.source === undefined ? {} : { source: options.source }),
|
|
619
625
|
...(options.timezone === undefined ? {} : { timezone: options.timezone }),
|
|
@@ -632,8 +638,11 @@ export const conversationsSearchCommand = (messenger) => syncOptions(boundOption
|
|
|
632
638
|
context.renderer.note(`«${found.named.word}» is a name in chat ${found.named.title ?? found.named.chatId} (${found.named.chatId}): its hits come first`);
|
|
633
639
|
if (found.words === "out-of-time")
|
|
634
640
|
context.renderer.note("the word half ran out of time, so these are by meaning alone; --timeout gives it longer");
|
|
635
|
-
|
|
636
|
-
|
|
641
|
+
const mark = runMarkOf(this);
|
|
642
|
+
renderAnswer(this, context, foundConversations("search conversations", found, limit, messenger, chat, window.meta), () => found.hits.map((hit) => `${hitLine(hit, mark)}\n`).join("") +
|
|
643
|
+
(found.own?.length
|
|
644
|
+
? `conversations where you wrote, nearest in meaning:\n${found.own.map((hit) => `${hitLine(hit, mark)}\n`).join("")}`
|
|
645
|
+
: ""));
|
|
637
646
|
if (found.hits.length === 0 && context.format === "pretty")
|
|
638
647
|
context.renderer.note(found.meaning === "unavailable"
|
|
639
648
|
? "nothing matches in words"
|