@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
@@ -0,0 +1,523 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync, rmSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { CliError, isCliError, resolvePaths, writeSecurely } from "@wirecat/cli-base";
5
+ import { annotate, metaOf } from "@wirecat/cli-base/commands";
6
+ import { Command } from "commander";
7
+ import { resolveAISettings } from "../../analysis/settings.js";
8
+ import { progressOf } from "../../background/checkpoints.js";
9
+ import { catalogFiles, documentKnowledge, syncDocuments, } from "../../documents.js";
10
+ import { acquireLock } from "../../files/lock.js";
11
+ import { modelGateway } from "../../models/index.js";
12
+ import { modelTarget } from "../../models/settings.js";
13
+ import { readOnlyLockOf } from "../../ports/app.js";
14
+ import { openAppStore } from "../app-store.js";
15
+ import { actorOf } from "../author.js";
16
+ import { baseContext, environmentOf, outputFor } from "../context.js";
17
+ import { refuseOffline } from "../early-refusal.js";
18
+ import { writesOwnerFiles } from "../effects.js";
19
+ import { renderAnswer } from "../envelope.js";
20
+ import { accountFileFor, profilesHere, rememberAccount } from "../messenger/accounts.js";
21
+ import { ProfileTokenStore } from "../profile-token.js";
22
+ import { addDocumentCatalogCommands } from "./catalog.js";
23
+ import { addLocalDocumentCommands } from "./documents.js";
24
+ import { addDocumentFolderCommands } from "./folders.js";
25
+ import { addDocumentKnowledgeCommands } from "./knowledge.js";
26
+ import { factItem, memoryItem } from "./queries.js";
27
+ import { addDocumentSearchCommand } from "./search.js";
28
+ import { addDocumentSyncCommands } from "./sync.js";
29
+ const readJson = (path) => {
30
+ try {
31
+ return JSON.parse(readFileSync(path, "utf8"));
32
+ }
33
+ catch (error) {
34
+ if (error.code === "ENOENT")
35
+ return undefined;
36
+ throw new CliError("configuration_error", `${path} cannot be read; move it away and sync again`, {
37
+ reason: "state.unreadable",
38
+ });
39
+ }
40
+ };
41
+ const writeJson = (path, value) => writeSecurely(path, JSON.stringify(value), 0o600);
42
+ /** A provider id is a file name as it is; anything else is hashed, so no id reaches outside the folder. */
43
+ const fileName = (id) => /^[0-9a-f-]{1,64}$/u.test(id) ? id : createHash("sha256").update(id).digest("hex").slice(0, 40);
44
+ /**
45
+ * One profile's document files under the CLI's state folder: the chosen folders, the sync's checkpoint, its walk and
46
+ * one snapshot per document, each a private file.
47
+ */
48
+ export const documentProfile = (app, env, profile) => {
49
+ const dir = join(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state, "profiles", profile);
50
+ const sync = join(dir, "sync");
51
+ const snapshot = (id) => join(sync, "snapshots", `${fileName(id)}.json`);
52
+ const folders = () => readJson(join(dir, "folders.json")) ?? { roots: [] };
53
+ const state = (principal) => ({
54
+ read: () => readJson(join(sync, "state.json")) ?? {
55
+ version: 1,
56
+ principal,
57
+ scope: "",
58
+ folders: {},
59
+ documents: {},
60
+ skipped: [],
61
+ },
62
+ save: (next) => writeJson(join(sync, "state.json"), next),
63
+ readWalk: (scope) => {
64
+ const walk = readJson(join(sync, "walk.json"));
65
+ return walk?.scope === scope ? walk : undefined;
66
+ },
67
+ saveWalk: (walk) => writeJson(join(sync, "walk.json"), walk),
68
+ removeWalk: () => rmSync(join(sync, "walk.json"), { force: true }),
69
+ saveSnapshot: (content) => writeJson(snapshot(content.metadata.id), content),
70
+ removeSnapshot: (id) => rmSync(snapshot(id), { force: true }),
71
+ });
72
+ return {
73
+ dir,
74
+ folders,
75
+ saveFolders: (roots, files) => writeJson(join(dir, "folders.json"), {
76
+ roots,
77
+ files: Object.fromEntries(roots.flatMap((id) => (files[id] ? [[id, files[id]]] : []))),
78
+ changed_at: new Date().toISOString(),
79
+ }),
80
+ /** Keeps a chosen folder's newer metadata (a new path) without changing the choice or its date. */
81
+ saveFolderFile: (file) => {
82
+ const chosen = folders();
83
+ writeJson(join(dir, "folders.json"), { ...chosen, files: { ...chosen.files, [file.id]: file } });
84
+ },
85
+ state,
86
+ synced: () => existsSync(join(sync, "state.json")),
87
+ walkUnderWay: () => existsSync(join(sync, "walk.json")),
88
+ snapshot: (id) => readJson(snapshot(id)),
89
+ /**
90
+ * The lock a sync and every write to the local copy take, so a tag added during a sync is not lost. A second
91
+ * holder is refused at once: waiting would hold an agent's tool call for the length of a sync.
92
+ */
93
+ locked: async (fn) => {
94
+ const lock = await acquireLock(join(dir, "sync.lock")).catch((error) => {
95
+ throw new CliError("provider_unavailable", "another sync or write holds this profile's local copy; retry later", {
96
+ reason: "profile.busy",
97
+ ...(error instanceof CliError ? { holders: error.details.holders } : {}),
98
+ });
99
+ });
100
+ let held = true;
101
+ try {
102
+ return await fn(() => {
103
+ if (!held)
104
+ throw new CliError("provider_unavailable", "the profile's lock was released", { reason: "profile.busy" });
105
+ });
106
+ }
107
+ finally {
108
+ held = false;
109
+ await lock.release();
110
+ }
111
+ },
112
+ };
113
+ };
114
+ const recalled = (app, env, profile) => readJson(accountFileFor(app, profile, env))?.account;
115
+ /**
116
+ * Takes a provider account for a profile before its copy is written. One account is one collection in the shared
117
+ * store, so two profiles on it would each remove the other's documents; and a profile's copy stays with the account
118
+ * it was synced from.
119
+ */
120
+ export const claimDocumentAccount = (app, env, profile, account, tokens) => {
121
+ const other = profilesHere(app, [], env).find((name) => name !== profile && recalled(app, env, name) === account && tokens.read(name) !== undefined);
122
+ if (other) {
123
+ const fromVariable = tokens.read(other)?.source === "environment";
124
+ throw new CliError("conflict", `profile ${other} already uses this account; use \`${app.command} ${other} …\`, or ` +
125
+ (fromVariable
126
+ ? `give this profile its own token instead of ${app.envPrefix}_TOKEN`
127
+ : `run \`${app.command} ${other} session end\` first`), { reason: "profile.account-taken", profile: other });
128
+ }
129
+ const synced = documentProfile(app, env, profile).state("").read().principal;
130
+ if (synced && synced !== account)
131
+ throw new CliError("conflict", `profile ${profile} holds a copy synced from another account; sign this one in under a new profile ` +
132
+ `(\`${app.command} <new profile> session start\`)`, { reason: "profile.other-account" });
133
+ if (recalled(app, env, profile) !== account)
134
+ rememberAccount(app, profile, account, env);
135
+ };
136
+ const DOCUMENT_REF = /^document:[1-9]\d*$/u;
137
+ /**
138
+ * cli-core's shared `folders`, `sync`, `status`, `documents`, `search`, `catalog` and knowledge groups over a CLI's
139
+ * document source, its files under the CLI's state folder and the shared store. The CLI gives the source, how it
140
+ * files a document and its words. Returned as commands to add to the program.
141
+ */
142
+ export const documentLibraryCommands = (options) => {
143
+ const { app } = options;
144
+ const holder = new Command(app.command);
145
+ // The shared helpers take no command, so each run's command is caught as it starts; an MCP server builds the tree
146
+ // anew for every call.
147
+ let running;
148
+ let warnings = [];
149
+ const command = () => {
150
+ if (!running)
151
+ throw new CliError("configuration_error", "a shared documents port ran outside a command");
152
+ return running;
153
+ };
154
+ const context = () => baseContext(command(), options.resolveSettings);
155
+ const env = () => context().env;
156
+ const profile = () => {
157
+ const name = context().settings.profile;
158
+ if (!name)
159
+ throw new CliError("validation_error", "a profile is required");
160
+ return name;
161
+ };
162
+ const files = () => documentProfile(app, env(), profile());
163
+ const tokens = () => {
164
+ const { env: variables, keyring } = context();
165
+ return new ProfileTokenStore({ app, env: variables, ...(keyring ? { keyring } : {}) });
166
+ };
167
+ const roots = () => files().folders().roots;
168
+ const principal = () => {
169
+ const account = recalled(app, env(), profile());
170
+ if (typeof account !== "string" || !files().synced())
171
+ throw new CliError("not_found", `profile ${profile()} has no local copy yet — ${app.command} ${profile()} sync`, {
172
+ reason: "profile.not-synced",
173
+ });
174
+ return account;
175
+ };
176
+ const withStore = async (write, fn) => {
177
+ const store = await openAppStore(env(), {
178
+ app,
179
+ provider: options.provider,
180
+ readOnly: !write || readOnlyLockOf(app, env()) !== undefined,
181
+ });
182
+ try {
183
+ return await fn(store);
184
+ }
185
+ finally {
186
+ await store.close();
187
+ }
188
+ };
189
+ const locked = (write, fn) => write ? files().locked(fn) : fn(() => undefined);
190
+ const writes = () => metaOf(command()).effects?.local === "write";
191
+ const output = (body) => {
192
+ const seen = new Set();
193
+ const issues = warnings.flatMap((warning) => {
194
+ const key = `${warning.code}:${warning.reason}`;
195
+ if (seen.has(key))
196
+ return [];
197
+ seen.add(key);
198
+ return [{ code: warning.code, reason: warning.reason, source: options.provider.name }];
199
+ });
200
+ renderAnswer(command(), outputFor(command()), {
201
+ ...body,
202
+ ...(issues.length ? { meta: { ...body.meta, issues: [...(body.meta?.issues ?? []), ...issues] } } : {}),
203
+ });
204
+ };
205
+ // The folder as `folders add` read it stands in for the one the last pass held, before the first sync.
206
+ const known = (source) => {
207
+ const chosen = files().folders().files ?? {};
208
+ // The folder as `folders add` last read it wins over the walk's copy: adding a moved folder again under its new
209
+ // path is how a path-addressed source finds it.
210
+ const metadata = (id, held) => source.metadata(id, chosen[id] ?? held);
211
+ // A proxy, not a spread: a source written as a class keeps its methods and private fields.
212
+ return new Proxy(source, {
213
+ get: (target, name) => {
214
+ if (name === "metadata")
215
+ return metadata;
216
+ const value = Reflect.get(target, name);
217
+ return typeof value === "function" ? value.bind(target) : value;
218
+ },
219
+ });
220
+ };
221
+ const withSource = (body, deadline) => {
222
+ refuseOffline(command(), options.service);
223
+ return context().run((events) => body(known(options.source(command(), events, { warn: (one) => warnings.push(one), ...(deadline ? { deadline } : {}) }))));
224
+ };
225
+ const errorOf = (error) => isCliError(error)
226
+ ? error
227
+ : new CliError("provider_error", `a ${options.service} read failed`, { reason: "provider.failed" });
228
+ const knowledgeOf = (store, account) => {
229
+ const ingestion = options.ingestion(store);
230
+ const shared = documentKnowledge(store, async (one) => one === account ? (await ingestion.collection(one, false))?.id : undefined);
231
+ const people = options.people ?? (async () => ({ items: [] }));
232
+ return {
233
+ ...shared,
234
+ context: async (one, ref) => ({
235
+ document: await shared.document(one, ref),
236
+ tags: await store.notes.noteTags(ref),
237
+ links: await store.notes.links({ from: ref }),
238
+ notes: await store.notes.notes({ source: "internal", about: ref, limit: 100 }),
239
+ memories: (await store.memories.list({ subject: ref, limit: 100 })).items.map(memoryItem),
240
+ facts: (await store.facts.list({ subject: ref, limit: 100 })).items.map(factItem),
241
+ people: await people(one, ref),
242
+ }),
243
+ people,
244
+ linkPerson: async () => {
245
+ throw new CliError("not_found", `${options.service} shows no accounts on a document`, {
246
+ reason: "identity.none",
247
+ });
248
+ },
249
+ };
250
+ };
251
+ const imported = (input) => {
252
+ const held = files().state("").read();
253
+ const id = DOCUMENT_REF.test(input)
254
+ ? Object.entries(held.documents).find(([, doc]) => doc.reference === input)?.[0]
255
+ : options.idOf(input);
256
+ const doc = id ? held.documents[id] : undefined;
257
+ const snapshot = id && doc ? files().snapshot(id) : undefined;
258
+ if (!id || !doc || !snapshot)
259
+ throw new CliError("not_found", "this document is not in the selected profile's local copy", {
260
+ reason: "document.not-imported",
261
+ });
262
+ return { id, ref: doc.reference, hash: doc.hash, snapshot, metadata: options.row(doc.metadata, doc.reference) };
263
+ };
264
+ const refOf = async (store, account, input) => {
265
+ if (DOCUMENT_REF.test(input))
266
+ return input;
267
+ const id = options.idOf(input);
268
+ const held = files().state(account).read().documents[id];
269
+ if (held)
270
+ return held.reference;
271
+ const entry = await options.ingestion(store).catalog.get(account, id);
272
+ if (entry)
273
+ return entry.ref;
274
+ throw new CliError("not_found", "this document or folder is not in the selected profile's local copy", {
275
+ reason: "document.not-imported",
276
+ });
277
+ };
278
+ const decider = () => {
279
+ const actor = actorOf(command());
280
+ return actor === "owner" ? "owner" : { bot: actor, reason: `asked by ${actor} through ${app.command}` };
281
+ };
282
+ const groups = {
283
+ folders: {
284
+ add: async (input) => {
285
+ const file = await withSource((source) => options.folder ? options.folder(source, input) : source.metadata(options.idOf(input)));
286
+ if (file.trashed || !options.isFolder(file))
287
+ throw new CliError("validation_error", `choose a folder the ${options.service} account can read`, {
288
+ reason: "folder.not-a-folder",
289
+ });
290
+ const chosen = files().folders();
291
+ // A folder already chosen keeps its date, so status does not report a new plan for it.
292
+ if (!chosen.roots.includes(file.id))
293
+ files().saveFolders([...chosen.roots, file.id], { ...chosen.files, [file.id]: file });
294
+ else
295
+ files().saveFolderFile(file);
296
+ return { id: file.id, name: file.name };
297
+ },
298
+ list: (filter) => roots()
299
+ .filter((id) => filter.id === undefined || filter.id === id)
300
+ .map((id) => ({ id })),
301
+ remove: (input) => {
302
+ const id = options.idOf(input);
303
+ const chosen = files().folders();
304
+ if (!chosen.roots.includes(id))
305
+ throw new CliError("not_found", `${id} is not a chosen folder; folders list shows them`, {
306
+ reason: "folder.not-chosen",
307
+ });
308
+ files().saveFolders(chosen.roots.filter((root) => root !== id), chosen.files ?? {});
309
+ return id;
310
+ },
311
+ ...(options.browse
312
+ ? {
313
+ browse: (folders) => options.browse?.(folders, { env, profile, output, roots, withSource: (body) => withSource(body) }),
314
+ }
315
+ : {}),
316
+ },
317
+ sync: {
318
+ diagnostic: (text) => outputFor(command()).streams.diagnostic(text),
319
+ profile,
320
+ maxEntries: options.maxEntries,
321
+ sync: async ({ limit, rescan, embed, budget, deadline }) => {
322
+ const name = profile();
323
+ const chosen = roots();
324
+ const synced = await withSource(async (source) => {
325
+ const live = await source.identity();
326
+ claimDocumentAccount(app, env(), name, live, tokens());
327
+ return files().locked((assertHeld) => withStore(true, async (store) => {
328
+ const result = await syncDocuments({
329
+ source,
330
+ index: {
331
+ ...options.ingestion(store),
332
+ openPictures: async () => {
333
+ throw new CliError("not_found", `${options.service} pictures are not searched`);
334
+ },
335
+ },
336
+ state: files().state(live),
337
+ principal: live,
338
+ profile: name,
339
+ roots: chosen,
340
+ textLimit: options.textLimit,
341
+ max: limit,
342
+ maxEntries: options.maxEntries,
343
+ isFolder: options.isFolder,
344
+ ...(options.isDocument ? { isDocument: options.isDocument } : {}),
345
+ skipReason: options.skipReason ?? (() => undefined),
346
+ retryable: () => false,
347
+ errorOf,
348
+ assertHeld,
349
+ storeVersion: app.version,
350
+ ...(environmentOf(command()).signal ? { signal: environmentOf(command()).signal } : {}),
351
+ ...(rescan ? { rescan } : {}),
352
+ ...(budget ? { budget } : {}),
353
+ ...(deadline ? { deadline } : {}),
354
+ });
355
+ if (!embed)
356
+ return result;
357
+ const { embedNotes } = await import("../../services/notes-search.js");
358
+ return {
359
+ ...result,
360
+ embeddings: await embedNotes(store, { maxChunks: 600, env: env(), command: app.command }),
361
+ };
362
+ }));
363
+ }, deadline);
364
+ return {
365
+ ...synced,
366
+ warnings: warnings.map(({ id, code, reason, message }) => ({ id: id ?? null, code, reason, message })),
367
+ };
368
+ },
369
+ status: () => {
370
+ const name = profile();
371
+ const held = files().state("").read();
372
+ const pending = held.pending?.jobs.length ?? 0;
373
+ const queued = new Set(held.pending?.jobs.map((job) => job.id));
374
+ const done = Object.keys(held.documents).filter((id) => !queued.has(id)).length;
375
+ const changed = files().folders().changed_at;
376
+ const unplanned = files().walkUnderWay() ||
377
+ (changed !== undefined && (!held.lastSync || Date.parse(changed) > Date.parse(held.lastSync)));
378
+ return {
379
+ profile: name,
380
+ selected_folders: roots(),
381
+ documents: Object.keys(held.documents).length,
382
+ pending,
383
+ skipped: held.skipped.map(({ id, reason }) => ({ id, reason })),
384
+ last_sync: held.lastSync ?? null,
385
+ progress: progressOf({
386
+ job: "sync",
387
+ profile: name,
388
+ done,
389
+ ...(unplanned || (!held.lastSync && !held.pending) ? {} : { total: done + pending }),
390
+ ...(held.lastSync ? { updatedAt: held.lastSync } : {}),
391
+ complete: Boolean(held.lastSync) && !held.pending && !unplanned,
392
+ }),
393
+ coverage: options.coverage,
394
+ remote_checked: false,
395
+ };
396
+ },
397
+ },
398
+ documents: {
399
+ list: (query, page) => {
400
+ const account = principal();
401
+ return withStore(false, async (store) => {
402
+ const found = await knowledgeOf(store, account).documents(account, query, page);
403
+ const held = files().state(account).read().documents;
404
+ return {
405
+ items: found.items.map((note) => {
406
+ const id = (note.path ?? "").replace(/\.md$/u, "");
407
+ const doc = held[id];
408
+ return doc ? options.row(doc.metadata, doc.reference) : { id, name: note.title, reference: note.ref };
409
+ }),
410
+ hasMore: found.hasMore,
411
+ };
412
+ });
413
+ },
414
+ document: (input) => {
415
+ const { id, metadata, snapshot } = imported(input);
416
+ return { id, metadata, snapshot };
417
+ },
418
+ lastSync: () => files().state("").read().lastSync,
419
+ },
420
+ search: {
421
+ search: (query, searchOptions) => {
422
+ const account = principal();
423
+ return withStore(false, async (store) => {
424
+ const folder = await options.ingestion(store).collection(account, false);
425
+ if (!folder)
426
+ return { query, by: "words", hits: [], has_more: false };
427
+ const { searchNotes } = await import("../../services/notes-search.js");
428
+ const { items, hasMore, nextOffset, ...rest } = await searchNotes(store, query, {
429
+ ...searchOptions,
430
+ folderIds: [folder.id],
431
+ env: env(),
432
+ command: app.command,
433
+ });
434
+ return {
435
+ ...rest,
436
+ hits: items.map((hit) => ({ id: (hit.path ?? "").replace(/\.md$/u, ""), ...hit })),
437
+ has_more: hasMore,
438
+ ...(nextOffset === undefined ? {} : { next_offset: nextOffset }),
439
+ };
440
+ });
441
+ },
442
+ imported: () => ({
443
+ profile: profile(),
444
+ chosen: roots().length > 0,
445
+ documents: Object.keys(files().state("").read().documents).length,
446
+ }),
447
+ },
448
+ catalog: {
449
+ run: (fn, write) => {
450
+ const account = principal();
451
+ return withStore(write, (store) => locked(write, async (assertHeld) => {
452
+ const ingestion = options.ingestion(store);
453
+ assertHeld();
454
+ const value = await fn({
455
+ catalog: {
456
+ import: (one) => ingestion.catalog.import(one, catalogFiles(files().state(one).read(), roots())),
457
+ get: (one, id) => ingestion.catalog.get(one, id),
458
+ list: (one, query) => ingestion.catalog.list(one, query),
459
+ },
460
+ knowledge: knowledgeOf(store, account),
461
+ }, account);
462
+ assertHeld();
463
+ return value;
464
+ }));
465
+ },
466
+ id: (input) => options.idOf(input),
467
+ roots,
468
+ },
469
+ knowledge: {
470
+ run: (input, fn) => {
471
+ const write = writes();
472
+ const account = principal();
473
+ return withStore(write, (store) => locked(write, async (assertHeld) => {
474
+ const ref = await refOf(store, account, input);
475
+ assertHeld();
476
+ const value = await fn(knowledgeOf(store, account), account, ref);
477
+ assertHeld();
478
+ return value;
479
+ }));
480
+ },
481
+ document: (input) => {
482
+ const { id, ref, hash, snapshot } = imported(input);
483
+ return { id, ref, hash, snapshot };
484
+ },
485
+ complete: () => {
486
+ const { values } = resolveAISettings(app.envPrefix, [], env());
487
+ const variables = env();
488
+ return modelGateway({
489
+ resolve: (purpose) => modelTarget(values, purpose),
490
+ // Called only by `memories extract`, which the owner or an agent runs on purpose.
491
+ consent: () => true,
492
+ key: (provider) => variables[`${app.envPrefix}_${provider.toUpperCase()}_API_KEY`] ??
493
+ variables[`${provider.toUpperCase()}_API_KEY`],
494
+ ...(environmentOf(command()).signal ? { signal: environmentOf(command()).signal } : {}),
495
+ }).complete;
496
+ },
497
+ author: () => {
498
+ const actor = actorOf(command());
499
+ return actor === "owner" ? "owner" : { bot: actor, kind: "agent" };
500
+ },
501
+ decider,
502
+ },
503
+ };
504
+ const shared = { words: options.words, output };
505
+ addDocumentFolderCommands(holder, { ...shared, ...groups.folders });
506
+ addDocumentSyncCommands(holder, { ...shared, ...groups.sync });
507
+ addLocalDocumentCommands(holder, { ...shared, ...groups.documents });
508
+ addDocumentSearchCommand(holder, { ...shared, ...groups.search });
509
+ addDocumentCatalogCommands(holder, { ...shared, ...groups.catalog });
510
+ addDocumentKnowledgeCommands(holder, { ...shared, ...groups.knowledge });
511
+ const find = (group, name) => group.commands.find((one) => one.name() === name);
512
+ const folders = find(holder, "folders");
513
+ // Choosing a folder changes what the next sync keeps and removes, so an agent asks for it through the write tool.
514
+ writesOwnerFiles(find(folders, "add"));
515
+ if (options.browse)
516
+ annotate(find(folders, "browse"), { partial: true });
517
+ for (const group of holder.commands)
518
+ group.hook("preAction", (_group, action) => {
519
+ running = action;
520
+ warnings = [];
521
+ });
522
+ return [...holder.commands];
523
+ };
@@ -1,10 +1,10 @@
1
1
  import { type Deadline, type RunBudget } from "../../../background/budget.js";
2
- import type { DocumentSource, SourceFile, SyncResult } from "../../../documents.js";
2
+ import { type FeedlessDocumentSource, type SourceFile, type SyncResult } from "../../../documents.js";
3
3
  import type { ContractCase } from "../../../meetings/index.js";
4
4
  /** What one sync of a fault case may be given: the CLI passes each on to `syncDocuments`. */
5
5
  export interface DocumentFaultRun<M extends SourceFile = SourceFile> {
6
6
  /** Wraps the source the CLI builds for this run: the case counts its calls, slows them or cuts them off. */
7
- wrap(source: DocumentSource<M>): DocumentSource<M>;
7
+ wrap(source: FeedlessDocumentSource<M>): FeedlessDocumentSource<M>;
8
8
  budget?: RunBudget;
9
9
  deadline?: Deadline;
10
10
  signal?: AbortSignal;
@@ -18,9 +18,9 @@ export interface DocumentSourceFaults<M extends SourceFile = SourceFile> {
18
18
  */
19
19
  deny?(status: 403 | 404): string | Promise<string>;
20
20
  /** A source over the same provider whose own clock runs `ms` ahead of the provider's, behind when negative. */
21
- skewed?(ms: number): DocumentSource<M> | Promise<DocumentSource<M>>;
21
+ skewed?(ms: number): FeedlessDocumentSource<M> | Promise<FeedlessDocumentSource<M>>;
22
22
  /** A source for a second profile signed in with the same token. */
23
- sameToken?(): DocumentSource<M> | Promise<DocumentSource<M>>;
23
+ sameToken?(): FeedlessDocumentSource<M> | Promise<FeedlessDocumentSource<M>>;
24
24
  /**
25
25
  * The CLI's own sync of the root over this fixture's provider, its state and index kept between calls, and the ids
26
26
  * it holds after the call, all calls together. Given, the cases also check a sync: a fault skipped, an interrupted run resumed, the
@@ -33,15 +33,20 @@ export interface DocumentSourceFaults<M extends SourceFile = SourceFile> {
33
33
  }
34
34
  /** One adapter over recorded or faked responses, fresh for each case. */
35
35
  export interface DocumentSourceFixture<M extends SourceFile = SourceFile> {
36
- source: DocumentSource<M>;
36
+ source: FeedlessDocumentSource<M>;
37
37
  /** A folder the account can read, with at least one file somewhere below it. */
38
38
  root: string;
39
39
  /** The provider's folder test, as the CLI passes it to `syncDocuments`. */
40
40
  isFolder(file: M): boolean;
41
41
  /** A folder that is also a document (a page with sub-pages), as the CLI passes it to `syncDocuments`. */
42
42
  isDocument?(file: M): boolean;
43
- /** Makes a change on the provider's side (a new or edited file) for the change feed to list; absent skips that check. */
43
+ /**
44
+ * Makes a change on the provider's side (a new or edited file) for the change feed to list, or, for a source without
45
+ * a feed, for the next sync to find; absent skips that check.
46
+ */
44
47
  change?(): Promise<void>;
48
+ /** Takes one document out on the provider's side and names it; a source without a feed must drop it on the next sync. */
49
+ remove?(): Promise<string>;
45
50
  /**
46
51
  * Adds a file inside a folder two levels below the root on the provider's side, and names both. A round of changes
47
52
  * lists only the direct children of a folder the feed names, so the feed must name the new file or its own folder;