@wirecat/drive-cli 0.15.0 → 0.16.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 (124) hide show
  1. package/dist/api-contract.d.ts +1 -0
  2. package/dist/api-contract.d.ts.map +1 -1
  3. package/dist/api-contract.js +9 -1
  4. package/dist/api-contract.js.map +1 -1
  5. package/dist/{catalog-commands.d.ts → commands/catalog.d.ts} +2 -2
  6. package/dist/commands/catalog.d.ts.map +1 -0
  7. package/dist/{catalog-commands.js → commands/catalog.js} +11 -14
  8. package/dist/commands/catalog.js.map +1 -0
  9. package/dist/commands/config.d.ts +5 -0
  10. package/dist/commands/config.d.ts.map +1 -0
  11. package/dist/commands/config.js +81 -0
  12. package/dist/commands/config.js.map +1 -0
  13. package/dist/commands/context.d.ts +38 -0
  14. package/dist/commands/context.d.ts.map +1 -0
  15. package/dist/commands/context.js +14 -0
  16. package/dist/commands/context.js.map +1 -0
  17. package/dist/commands/discovery.d.ts +5 -0
  18. package/dist/commands/discovery.d.ts.map +1 -0
  19. package/dist/commands/discovery.js +27 -0
  20. package/dist/commands/discovery.js.map +1 -0
  21. package/dist/commands/documents.d.ts +10 -0
  22. package/dist/commands/documents.d.ts.map +1 -0
  23. package/dist/commands/documents.js +89 -0
  24. package/dist/commands/documents.js.map +1 -0
  25. package/dist/commands/folders.d.ts +4 -0
  26. package/dist/commands/folders.d.ts.map +1 -0
  27. package/dist/commands/folders.js +44 -0
  28. package/dist/commands/folders.js.map +1 -0
  29. package/dist/{knowledge-commands.d.ts → commands/knowledge.d.ts} +4 -4
  30. package/dist/commands/knowledge.d.ts.map +1 -0
  31. package/dist/{knowledge-commands.js → commands/knowledge.js} +35 -54
  32. package/dist/commands/knowledge.js.map +1 -0
  33. package/dist/commands/mcp.d.ts +4 -0
  34. package/dist/commands/mcp.d.ts.map +1 -0
  35. package/dist/commands/mcp.js +18 -0
  36. package/dist/commands/mcp.js.map +1 -0
  37. package/dist/{remote-commands.d.ts → commands/remote.d.ts} +2 -2
  38. package/dist/commands/remote.d.ts.map +1 -0
  39. package/dist/{remote-commands.js → commands/remote.js} +46 -69
  40. package/dist/commands/remote.js.map +1 -0
  41. package/dist/commands/search.d.ts +4 -0
  42. package/dist/commands/search.d.ts.map +1 -0
  43. package/dist/commands/search.js +20 -0
  44. package/dist/commands/search.js.map +1 -0
  45. package/dist/commands/session.d.ts +4 -0
  46. package/dist/commands/session.d.ts.map +1 -0
  47. package/dist/commands/session.js +59 -0
  48. package/dist/commands/session.js.map +1 -0
  49. package/dist/commands/sheets-structure.d.ts +4 -0
  50. package/dist/commands/sheets-structure.d.ts.map +1 -0
  51. package/dist/commands/sheets-structure.js +112 -0
  52. package/dist/commands/sheets-structure.js.map +1 -0
  53. package/dist/commands/sheets.d.ts +4 -0
  54. package/dist/commands/sheets.d.ts.map +1 -0
  55. package/dist/commands/sheets.js +102 -0
  56. package/dist/commands/sheets.js.map +1 -0
  57. package/dist/commands/sync.d.ts +4 -0
  58. package/dist/commands/sync.d.ts.map +1 -0
  59. package/dist/commands/sync.js +50 -0
  60. package/dist/commands/sync.js.map +1 -0
  61. package/dist/config-upgrade.d.ts.map +1 -1
  62. package/dist/config-upgrade.js +10 -7
  63. package/dist/config-upgrade.js.map +1 -1
  64. package/dist/config.d.ts.map +1 -1
  65. package/dist/config.js +48 -11
  66. package/dist/config.js.map +1 -1
  67. package/dist/errors.d.ts.map +1 -1
  68. package/dist/errors.js +13 -0
  69. package/dist/errors.js.map +1 -1
  70. package/dist/failure.d.ts.map +1 -1
  71. package/dist/failure.js +5 -0
  72. package/dist/failure.js.map +1 -1
  73. package/dist/generated/definitions.d.ts.map +1 -1
  74. package/dist/generated/definitions.js +7310 -0
  75. package/dist/generated/definitions.js.map +1 -1
  76. package/dist/generated/manifest.d.ts.map +1 -1
  77. package/dist/generated/manifest.js +1923 -0
  78. package/dist/generated/manifest.js.map +1 -1
  79. package/dist/generated/metadata.d.ts +17 -0
  80. package/dist/generated/metadata.d.ts.map +1 -1
  81. package/dist/generated/metadata.js +91 -0
  82. package/dist/generated/metadata.js.map +1 -1
  83. package/dist/generated/schemas.d.ts +546 -0
  84. package/dist/generated/schemas.d.ts.map +1 -1
  85. package/dist/generated/schemas.js +2117 -0
  86. package/dist/generated/schemas.js.map +1 -1
  87. package/dist/generated/types.d.ts +2814 -0
  88. package/dist/generated/types.d.ts.map +1 -1
  89. package/dist/google-api.d.ts.map +1 -1
  90. package/dist/google-api.js +16 -3
  91. package/dist/google-api.js.map +1 -1
  92. package/dist/google.js +4 -3
  93. package/dist/google.js.map +1 -1
  94. package/dist/knowledge.js +6 -6
  95. package/dist/knowledge.js.map +1 -1
  96. package/dist/mcp.d.ts +1 -1
  97. package/dist/mcp.d.ts.map +1 -1
  98. package/dist/mcp.js +6 -3
  99. package/dist/mcp.js.map +1 -1
  100. package/dist/policy.d.ts +1 -1
  101. package/dist/policy.d.ts.map +1 -1
  102. package/dist/policy.js +58 -8
  103. package/dist/policy.js.map +1 -1
  104. package/dist/program.d.ts +2 -19
  105. package/dist/program.d.ts.map +1 -1
  106. package/dist/program.js +58 -427
  107. package/dist/program.js.map +1 -1
  108. package/dist/registry.d.ts +4 -0
  109. package/dist/registry.d.ts.map +1 -1
  110. package/dist/registry.js +3 -0
  111. package/dist/registry.js.map +1 -1
  112. package/dist/sheets-input.d.ts +17 -0
  113. package/dist/sheets-input.d.ts.map +1 -0
  114. package/dist/sheets-input.js +32 -0
  115. package/dist/sheets-input.js.map +1 -0
  116. package/dist/store.js +1 -1
  117. package/dist/store.js.map +1 -1
  118. package/package.json +5 -4
  119. package/dist/catalog-commands.d.ts.map +0 -1
  120. package/dist/catalog-commands.js.map +0 -1
  121. package/dist/knowledge-commands.d.ts.map +0 -1
  122. package/dist/knowledge-commands.js.map +0 -1
  123. package/dist/remote-commands.d.ts.map +0 -1
  124. package/dist/remote-commands.js.map +0 -1
package/dist/program.js CHANGED
@@ -1,48 +1,38 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { readFileSync, writeFileSync } from "node:fs";
2
+ import { readFileSync } from "node:fs";
3
3
  import { CliError, createDeadline, createOutputBuffer, createRenderer, fieldsOf, processStreams, projectFields, } from "@wirecat/cli-base";
4
- import { annotate, describeOptions, flatten, metaOf } from "@wirecat/cli-base/commands";
5
- import { formatSuggestions, suggest } from "@wirecat/cli-base/completion";
4
+ import { annotate, flatten, metaOf } from "@wirecat/cli-base/commands";
6
5
  import { writes } from "@wirecat/cli-base/standards";
7
- import { commandWords, itemOf, liftJson, liftProfile, listOf, listQuery, parseDuration, refuseCommandName, renderAnswer, typedQuery, withQuery, } from "@wirecat/cli-core/cli";
8
- import { IMPORTED_DOCUMENT_QUERY } from "@wirecat/cli-core/store";
9
- import { Command, Help, InvalidArgumentError, Option } from "commander";
6
+ import { commandWords, itemOf, liftJson, liftProfile, parseDuration, refuseCommandName, renderAnswer, } from "@wirecat/cli-core/cli";
7
+ import { Command, Help } from "commander";
10
8
  import { validateRequest } from "./api-contract.js";
11
- import { installCatalogCommands } from "./catalog-commands.js";
12
- import { activeProfile, application, checkTextLimit, configKey, fileId, pictureSearch, profileName, readConfig, SETTING_NAMES, writeConfig, } from "./config.js";
9
+ import { installCatalogCommands } from "./commands/catalog.js";
10
+ import { installConfigCommands, installModelCommands } from "./commands/config.js";
11
+ import { offset, positive } from "./commands/context.js";
12
+ import { installCommandsCommand, installCompleteCommand } from "./commands/discovery.js";
13
+ import { importedDocument, installDocumentCommands } from "./commands/documents.js";
14
+ import { installFolderCommands } from "./commands/folders.js";
15
+ import { installKnowledgeCommands } from "./commands/knowledge.js";
16
+ import { installMcpCommand } from "./commands/mcp.js";
17
+ import { installRemoteCommands } from "./commands/remote.js";
18
+ import { installSearchCommand } from "./commands/search.js";
19
+ import { installSessionCommands } from "./commands/session.js";
20
+ import { installSyncCommands } from "./commands/sync.js";
21
+ import { activeProfile, fileId, profileName, readConfig } from "./config.js";
13
22
  import { googleError } from "./errors.js";
14
23
  import { memoryModel } from "./extraction.js";
15
- import { googleSource, MAX_ENTRIES } from "./google.js";
24
+ import { googleSource } from "./google.js";
16
25
  import { apiMethod, googleApi, googleUploadRequest } from "./google-api.js";
17
- import { installKnowledgeCommands } from "./knowledge-commands.js";
18
- import { login } from "./login.js";
19
- import { FOLDER, metadataJson, skipJson } from "./model.js";
20
- import { allOf, snakeKeys } from "./output.js";
26
+ import { snakeKeys } from "./output.js";
21
27
  import { checkPolicy, guardedGoogleWrite, methodPolicyKeys } from "./policy.js";
22
28
  import { lockProfile } from "./profile-lock.js";
23
29
  import { checkProviderJson, checkResultFields, providerJsonFields } from "./provider-json.js";
24
- import { ACCOUNT_FREE_COMMANDS, commandsDocument, describeDriveProgram, examples } from "./registry.js";
25
- import { installRemoteCommands } from "./remote-commands.js";
26
- import { profileDir, readSnapshot, readState } from "./state.js";
30
+ import { ACCOUNT_FREE_COMMANDS, describeDriveProgram } from "./registry.js";
31
+ import { profileDir } from "./state.js";
27
32
  import { openIndex } from "./store.js";
28
- import { sync } from "./sync.js";
29
- import { authorizedClient, checkAuthorization, credentials } from "./tokens.js";
33
+ import { authorizedClient, checkAuthorization } from "./tokens.js";
30
34
  import { uploadFile } from "./upload.js";
31
35
  import { VERSION } from "./version.js";
32
- const NETWORK_GROUPS = ["files", "comments", "permissions", "revisions", "shared-drives"];
33
- const NETWORK_COMMANDS = ["folders add", "documents get", "documents history", "sync"];
34
- const positive = (input) => {
35
- const n = Number(input);
36
- if (!Number.isSafeInteger(n) || n < 1)
37
- throw new InvalidArgumentError("use a positive integer");
38
- return n;
39
- };
40
- const offset = (input) => {
41
- const n = Number(input);
42
- if (!Number.isSafeInteger(n) || n < 0)
43
- throw new InvalidArgumentError("use a nonnegative integer");
44
- return n;
45
- };
46
36
  const eachItem = (body, change) => "items" in body ? { ...body, items: body.items.map(change) } : { ...body, item: change(body.item) };
47
37
  const commandIn = (root, words) => {
48
38
  let at = root;
@@ -57,14 +47,6 @@ const commandIn = (root, words) => {
57
47
  };
58
48
  class Preview extends Error {
59
49
  }
60
- const GRANTS = ["write", "activity", "apps"];
61
- const grants = (raw) => {
62
- const values = raw.split(",").map((value) => value.trim());
63
- const unknown = values.filter((value) => !GRANTS.includes(value));
64
- if (unknown.length)
65
- throw new CliError("validation_error", `--grant takes ${GRANTS.join(", ")}; got ${unknown.join(", ")}`);
66
- return new Set(values);
67
- };
68
50
  export const createProgram = (options = {}) => {
69
51
  const startedAt = Date.now();
70
52
  const env = options.env ?? process.env;
@@ -105,6 +87,7 @@ export const createProgram = (options = {}) => {
105
87
  return profileName(name);
106
88
  };
107
89
  let currentAction;
90
+ let checkedMethod;
108
91
  let fields;
109
92
  let activeSignal = options.signal;
110
93
  let deadline;
@@ -167,212 +150,24 @@ export const createProgram = (options = {}) => {
167
150
  await index.close();
168
151
  }
169
152
  };
170
- const session = program.command("session").description("sign in to Google and manage local profiles");
171
- examples(session.command("start").description("sign in to Google in the browser; read-only unless you pass --grant write"), ["drive personal session start", "drive work session start --grant write,activity"])
172
- .option("--client-file <file>", "path to your own Desktop OAuth client JSON, used instead of WireCat's")
173
- .option("--credential-storage <storage>", "where the sign-in is kept: keyring, or file for a private file", "keyring")
174
- .option("--no-browser", "print the sign-in URL instead of opening a browser")
175
- .option("--grant <scopes>", "also ask for these permissions, comma-separated: write (change Drive files and Docs), " +
176
- "activity (read Drive Activity history), apps (see installed Drive apps)", grants)
177
- .action(async (args) => {
178
- if (args.credentialStorage !== "keyring" && args.credentialStorage !== "file")
179
- throw new CliError("validation_error", "credential storage is keyring or file");
180
- output(itemOf(await login({
181
- env,
182
- profile: selected(),
183
- application: application(env, args.clientFile),
184
- storage: args.credentialStorage,
185
- ...Object.fromEntries([...(args.grant ?? [])].map((grant) => [grant, true])),
186
- ...(options.keyring ? { keyring: options.keyring } : {}),
187
- ...(activeSignal ? { signal: activeSignal } : {}),
188
- openBrowser: args.browser ? (options.openBrowser ?? (async () => { })) : async () => { },
189
- showUrl: (url) => streams.diagnostic(`Open Google sign-in: ${url}\n`),
190
- })));
191
- });
192
- examples(session.command("list").description("list the configured profiles; credentials are never printed"), [
193
- "drive personal session list",
194
- ]).action(() => output(itemOf({
195
- scope: "all-configured-profiles",
196
- items: Object.entries(readConfig(env).profiles).map(([name, p]) => ({
197
- profile: name,
198
- selected_folders: p.roots.length,
199
- storage: p.storage,
200
- })),
201
- })));
202
- examples(session.command("end").description("sign this profile out; imported documents stay"), [
203
- "drive personal session end",
204
- ]).action(() => {
205
- const name = selected();
206
- const config = readConfig(env);
207
- const profile = activeProfile(env, name);
208
- credentials(env, profile.storage, options.keyring).remove(name);
209
- // Preserve the principal and roots so reauthorization resumes the same source identities.
210
- writeConfig(env, config);
211
- output(itemOf({ profile: name, signed_out: true, cached_data: "retained" }));
212
- });
213
- const folders = program.command("folders").description("choose the Google Drive folders that sync imports");
214
- const folderArgument = "folder id or Google Drive URL";
215
- examples(folders
216
- .command("add")
217
- .argument("<folder>", folderArgument)
218
- .description("import a folder and everything under it on the next sync"), ["drive personal folders add FOLDER_ID"]).action(async (input) => {
219
- const id = fileId(input);
220
- const config = readConfig(env);
221
- const name = selected();
222
- const profile = activeProfile(env, name);
223
- const metadata = await (await source()).metadata(id);
224
- if (metadata.mime !== FOLDER || metadata.trashed)
225
- throw new CliError("validation_error", "source is not an accessible Google folder");
226
- if (!profile.roots.includes(metadata.id))
227
- profile.roots.push(metadata.id);
228
- config.profiles[name] = profile;
229
- writeConfig(env, config);
230
- output(itemOf({ id: metadata.id, name: metadata.name, added: true }));
231
- });
232
- examples(folders.command("list").description("list the folder ids sync imports"), [
233
- "drive personal folders list",
234
- ]).action(() => output(allOf(activeProfile(env, selected()).roots.map((id) => ({ id })))));
235
- examples(folders
236
- .command("remove")
237
- .argument("<folder>", folderArgument)
238
- .description("stop importing a folder; the next sync drops its documents"), ["drive personal folders remove FOLDER_ID"]).action((input) => {
239
- const id = fileId(input);
240
- const config = readConfig(env);
241
- const name = selected();
242
- const profile = activeProfile(env, name);
243
- profile.roots = profile.roots.filter((root) => root !== id);
244
- config.profiles[name] = profile;
245
- writeConfig(env, config);
246
- output(itemOf({ id, removed: true }));
247
- });
248
- examples(program
249
- .command("sync")
250
- .summary("import what changed in the chosen folders, and finish an unfinished sync")
251
- .description("import what changed in the chosen folders, and finish an unfinished sync; " +
252
- `one sync reads at most ${MAX_ENTRIES} entries under the chosen folders, and as many changes`), ["drive personal sync", "drive personal sync --rescan --limit 500"])
253
- .option("--limit <n>", "how many documents to read from Google in this run", positive, 200)
254
- .option("--rescan", "read every chosen folder again instead of only what changed")
255
- .option("--embed", "also index pending text for meaning search, with a model already downloaded")
256
- .action(async (args) => {
257
- const remote = activeProfile(env, selected()).roots.length ? await source() : undefined;
258
- const result = await withIndex(async (index) => ({
259
- ...(await sync(remote, index, env, selected(), args.limit, activeSignal, args.rescan)),
260
- ...(args.embed ? { embeddings: await index.embed(600) } : {}),
261
- }));
262
- output(itemOf(result));
263
- if (result.errors.length || result.pending)
264
- streams.diagnostic(`${result.pending} source operations remain; run drive ${selected()} sync again\n`);
265
- if (result.errors.length)
266
- throw new CliError("provider_error", "sync completed partially; failed operations remain pending", {
267
- reason: "sync.partial",
268
- });
269
- });
270
- examples(program.command("status").description("show the last sync, imported documents and pending work"), [
271
- "drive personal status",
272
- ]).action(() => {
273
- const name = selected();
274
- const profile = activeProfile(env, name);
275
- const state = readState(env, name, profile.principal);
276
- output(itemOf({
277
- profile: name,
278
- selected_folders: profile.roots,
279
- documents: Object.keys(state.documents).length,
280
- pending: state.pending?.jobs.length ?? 0,
281
- skipped: state.skipped.map(skipJson),
282
- last_sync: state.lastSync ?? null,
283
- coverage: "Google Docs/Sheets, PDF/DOCX/XLSX and Markdown/TXT/CSV/TSV; native export layout, tab fidelity and assets are not verified",
284
- remote_checked: false,
285
- }));
286
- });
287
- const documents = program.command("documents").description("read imported documents and Google Docs");
288
- const documentArgument = "document id or Google Docs URL";
289
- annotate(withQuery(examples(documents.command("list").description("list imported documents with their Google URLs"), [
290
- "drive personal documents list",
291
- "drive personal documents list tag:budget",
292
- "drive personal documents list person:PERSON_UID --limit 10",
293
- ]), IMPORTED_DOCUMENT_QUERY), { output: { entity: "drive_document" } })
294
- .option("--limit <n>", "how many documents to return", positive, 50)
295
- .option("--page <n>", "which page to return", positive, 1)
296
- .action(async (words, { limit, page }) => {
297
- const profile = activeProfile(env, selected());
298
- const query = typedQuery(words);
299
- const ast = listQuery(query, IMPORTED_DOCUMENT_QUERY, "documents list");
300
- const found = await withIndex(async (index) => {
301
- if (!index.knowledge)
302
- throw new CliError("configuration_error", "index has no shared knowledge adapter");
303
- return index.knowledge.documents(profile.principal, ast, { limit, offset: (page - 1) * limit });
304
- });
305
- const state = readState(env, selected(), profile.principal);
306
- output(listOf("documents list", {
307
- items: found.items.map((note) => {
308
- const id = (note.path ?? "").replace(/\.md$/, "");
309
- const doc = state.documents[id];
310
- return doc
311
- ? { ...metadataJson(doc.metadata), reference: doc.reference, tabs: doc.tabs }
312
- : { id, name: note.title, reference: note.ref, tabs: 0 };
313
- }),
314
- limit,
315
- has_more: found.hasMore,
316
- page,
317
- args: { query: query || undefined },
318
- }));
319
- });
320
- const imported = (input) => {
321
- const id = fileId(input);
322
- const profile = activeProfile(env, selected());
323
- const state = readState(env, selected(), profile.principal);
324
- if (!state.documents[id])
325
- throw new CliError("not_found", "this source is not imported in the selected profile", {
326
- reason: "document.not-imported",
327
- });
328
- const doc = state.documents[id];
329
- return { id, ref: doc.reference, hash: doc.hash, snapshot: readSnapshot(env, selected(), id) };
153
+ const context = {
154
+ env,
155
+ streams,
156
+ options,
157
+ selected,
158
+ signal: () => activeSignal,
159
+ output,
160
+ print,
161
+ source,
162
+ withIndex,
163
+ policyFlags,
330
164
  };
331
- examples(documents
332
- .command("show")
333
- .argument("<document>", documentArgument)
334
- .description("show an imported document's text, tabs and metadata"), ["drive personal documents show DOC_ID"]).action((input) => {
335
- const { snapshot } = imported(input);
336
- output(itemOf({
337
- metadata: metadataJson(snapshot.metadata),
338
- text: snapshot.text,
339
- tabs: snapshot.tabs,
340
- ...(snapshot.notRead ? { not_read: snapshot.notRead } : {}),
341
- }));
342
- });
343
- examples(documents
344
- .command("export")
345
- .argument("<document>", documentArgument)
346
- .description("write an imported document to a new Markdown file"), ["drive personal documents export DOC_ID --output notes.md"])
347
- .requiredOption("--output <file>", "path of the Markdown file to write; an existing file is refused")
348
- .action((input, args) => {
349
- const { id, snapshot } = imported(input);
350
- try {
351
- writeFileSync(args.output, snapshot.markdown, { flag: "wx", mode: 0o600 });
352
- }
353
- catch (error) {
354
- if (error.code === "EEXIST")
355
- throw new CliError("validation_error", "the output file already exists; choose another --output", {
356
- reason: "export.exists",
357
- param: "--output",
358
- });
359
- throw error;
360
- }
361
- output(itemOf({ id, path: args.output, format: "markdown" }));
362
- });
363
- examples(program
364
- .command("search")
365
- .argument("<query>", "words to look for")
366
- .description("search imported documents by words, and by meaning when indexed"), ["drive personal search budget", `drive personal search "quarterly plan" --exact --limit 5`])
367
- .option("--limit <n>", "how many results to return", positive, 20)
368
- .option("--page <n>", "which page to return", positive, 1)
369
- .option("--exact", "match the words exactly: no word forms, no meaning")
370
- .action(async (query, { page, ...args }) => output(itemOf(await withIndex((index) => index.search(activeProfile(env, selected()).principal, query, {
371
- ...args,
372
- offset: (page - 1) * args.limit,
373
- exact: args.exact ?? false,
374
- ...(pictureSearch(env, selected()) ? { pictures: true } : {}),
375
- })))));
165
+ const imported = importedDocument(context);
166
+ installSessionCommands(program, context);
167
+ installFolderCommands(program, context);
168
+ installSyncCommands(program, context);
169
+ installDocumentCommands(program, context);
170
+ installSearchCommand(program, context);
376
171
  installCatalogCommands(program, { env, selected, output, positive, offset, withIndex });
377
172
  installKnowledgeCommands(program, {
378
173
  document: imported,
@@ -416,12 +211,10 @@ export const createProgram = (options = {}) => {
416
211
  const descriptor = apiMethod(method);
417
212
  validateRequest(method, params, body);
418
213
  const flags = policyFlags();
419
- for (const key of methodPolicyKeys(method))
420
- await checkPolicy(env, selected(), key, descriptor.mutates, flags, askOnce);
421
- if (flags.offline)
422
- throw new CliError("permission_error", "this operation needs Google; --offline was requested", {
423
- reason: "offline.refused",
424
- });
214
+ const alreadyChecked = new Set(method === checkedMethod ? methodPolicyKeys(method) : []);
215
+ for (const key of methodPolicyKeys(method, body))
216
+ if (!alreadyChecked.has(key))
217
+ await checkPolicy(env, selected(), key, descriptor.mutates, flags, askOnce);
425
218
  if (flags.dryRun) {
426
219
  output(itemOf({
427
220
  dry_run: true,
@@ -449,12 +242,9 @@ export const createProgram = (options = {}) => {
449
242
  upload: async (path, args) => {
450
243
  const method = "drive.files.create";
451
244
  const flags = policyFlags();
245
+ // The hook checked the command's own key (files.upload); creating a file has its own keys.
452
246
  for (const key of methodPolicyKeys(method))
453
247
  await checkPolicy(env, selected(), key, true, flags, askOnce);
454
- if (flags.offline)
455
- throw new CliError("permission_error", "this operation needs Google; --offline was requested", {
456
- reason: "offline.refused",
457
- });
458
248
  if (flags.dryRun) {
459
249
  output(itemOf({ dry_run: true, method, mutates: true, path, ...args }));
460
250
  throw new Preview();
@@ -471,178 +261,16 @@ export const createProgram = (options = {}) => {
471
261
  return guardedGoogleWrite(env, selected(), `api.${method}`, act, flags, askOnce);
472
262
  },
473
263
  });
474
- const config = program.command("config").description("read and change settings; credentials are kept apart");
475
- examples(config.command("show").description("show the defaults and every profile's settings"), [
476
- "drive personal config show",
477
- ]).action(() => output(itemOf(readConfig(env))));
478
- examples(config.command("set").description("set one setting of this profile, or of the defaults"), [
479
- "drive personal config set read_only true",
480
- `drive personal config set permissions.files '"readonly"' --defaults`,
481
- ])
482
- .argument("<key>", "read_only, max_text_chars, picture_search, shared AI settings, permissions.<key> or models.<purpose>.<field>")
483
- .argument("<json-value>", "the new value, as JSON")
484
- .option("--defaults", "change the defaults instead of this profile")
485
- .action((rawKey, raw, args) => {
486
- const key = configKey(rawKey);
487
- const value = readConfig(env);
488
- if (args.defaults)
489
- value.defaults ??= {};
490
- const target = args.defaults
491
- ? value.defaults
492
- : activeProfile(env, selected());
493
- if (!args.defaults)
494
- value.profiles[selected()] = target;
495
- const [head, ...parts] = key.split(".");
496
- if (!SETTING_NAMES.has(head ?? "") ||
497
- parts.some((part) => ["__proto__", "prototype", "constructor"].includes(part)))
498
- throw new CliError("validation_error", "config set accepts profile settings and shared AI settings");
499
- let parsed;
500
- try {
501
- parsed = JSON.parse(raw);
502
- }
503
- catch {
504
- throw new CliError("validation_error", "setting value must be JSON");
505
- }
506
- if (head === "picture_search") {
507
- if (args.defaults || parts.length || typeof parsed !== "boolean")
508
- throw new CliError("validation_error", "picture_search is true or false, set per profile");
509
- target.picture_search = parsed;
510
- }
511
- else if (head === "max_text_chars" && !parts.length)
512
- target.max_text_chars = checkTextLimit(parsed);
513
- else if (!parts.length)
514
- Object.assign(target, { [key]: parsed });
515
- else if (head === "permissions") {
516
- target.permissions ??= {};
517
- Object.assign(target.permissions, { [parts.join(".")]: parsed });
518
- }
519
- else if (head === "models" && parts.length === 2 && parts[0] && parts[1]) {
520
- target.models ??= {};
521
- target.models[parts[0]] ??= {};
522
- Object.assign(target.models[parts[0]], { [parts[1]]: parsed });
523
- }
524
- else
525
- throw new CliError("validation_error", "unknown setting path");
526
- writeConfig(env, value);
527
- output(itemOf({ key, updated: true, scope: args.defaults ? "defaults" : selected() }));
528
- });
529
- examples(program.command("complete").description("print a shell completion script, or complete words"), [
530
- "drive complete zsh",
531
- ])
532
- .argument("[words...]", "a shell name, or after -- the words typed so far")
533
- .allowUnknownOption()
534
- .helpOption(false)
535
- .action(async (words) => {
536
- if (!program.rawArgs.includes("--")) {
537
- if (!["bash", "zsh", "fish", "powershell"].includes(words[0] ?? ""))
538
- throw new CliError("validation_error", "choose a supported shell");
539
- const { script } = await import("@bomb.sh/tab");
540
- script(words[0], "drive", "drive");
541
- }
542
- else
543
- streams.data(formatSuggestions(suggest({ commands: describeDriveProgram(program), globalOptions: describeOptions(program), words })));
544
- });
545
- examples(program
546
- .command("models")
547
- .description("choose the model that proposes memories; keys stay out of config")
548
- .command("set")
549
- .description("set the provider and model for one use"), ["drive personal models set --provider openai --model MODEL_ID", "drive personal models set --provider off"])
550
- .option("--purpose <purpose>", "what the model is used for", "memories")
551
- .addOption(new Option("--provider <provider>", "who runs the model, or off to use none")
552
- .choices(["openai", "anthropic", "off"])
553
- .makeOptionMandatory())
554
- .option("--model <model>", "model id at the provider")
555
- .option("--base-url <url>", "HTTP or HTTPS address of the model API, without credentials in it")
556
- .action((args) => {
557
- const config = readConfig(env);
558
- config.defaults ??= {};
559
- config.defaults.models ??= {};
560
- config.defaults.models[args.purpose] = {
561
- provider: args.provider,
562
- ...(args.model ? { model: args.model } : {}),
563
- ...(args.baseUrl ? { base_url: args.baseUrl } : {}),
564
- };
565
- writeConfig(env, config);
566
- output(itemOf({ purpose: args.purpose, configured: true }));
567
- });
568
- const mcp = examples(program.command("mcp").description("serve drive's commands to an agent over MCP on stdio"), [
569
- "drive personal mcp",
570
- "drive personal mcp --tools",
571
- ]);
572
- mcp
573
- .option("--tools", "list the tools offered instead of starting the server")
574
- .action(async (args) => {
575
- const { mcpTools, serveMcp } = await import("./mcp.js");
576
- if (args.tools)
577
- output(allOf(mcpTools(createProgram, { ...options, env }, selected(), policyFlags()).map(({ name, schema, command }) => ({ name, input_schema: schema, effects: command.effects }))));
578
- else
579
- await serveMcp(createProgram, { ...options, env, ...(activeSignal ? { signal: activeSignal } : {}) }, selected(), policyFlags());
580
- });
581
- examples(program.command("commands").description("print the command tree and its options as data"), [
582
- "drive commands --json",
583
- "drive commands files copy --json",
584
- ])
585
- .argument("[path...]", "only this command or group, as words")
586
- .action((path) => print((renderer) => renderer.result(commandsDocument(program, path))));
264
+ installConfigCommands(program, context);
265
+ installCompleteCommand(program, context);
266
+ installModelCommands(program, context);
267
+ installMcpCommand(program, context, createProgram);
268
+ installCommandsCommand(program, context);
587
269
  for (const info of flatten(describeDriveProgram(program))) {
588
270
  let command = program;
589
271
  for (const part of info.path)
590
272
  command = command.commands.find((child) => child.name() === part) ?? command;
591
- const localWrites = [
592
- "session start",
593
- "session end",
594
- "folders add",
595
- "folders remove",
596
- "sync",
597
- "documents export",
598
- "tags add",
599
- "tags remove",
600
- "relationships add",
601
- "relationships remove",
602
- "notes add",
603
- "notes edit",
604
- "notes remove",
605
- "memories add",
606
- "memories confirm",
607
- "memories stale",
608
- "memories extract",
609
- "facts add",
610
- "facts confirm",
611
- "facts reverse",
612
- "identities link",
613
- "models set",
614
- "config set",
615
- ];
616
- const remoteWrites = [
617
- "api call",
618
- "files copy",
619
- "files move",
620
- "files update",
621
- "files trash",
622
- "files restore",
623
- "files mkdir",
624
- "files upload",
625
- "documents create",
626
- "documents update",
627
- ];
628
- const name = info.path.join(" ");
629
- const remote = remoteWrites.includes(name) || name === "session start" || name === "memories extract"
630
- ? "write"
631
- : NETWORK_GROUPS.includes(info.path[0] ?? "") || NETWORK_COMMANDS.includes(name)
632
- ? "read"
633
- : "none";
634
- annotate(command, {
635
- origin: metaOf(command).origin ?? "handwritten",
636
- effects: metaOf(command).effects ?? {
637
- remote,
638
- local: localWrites.includes(name)
639
- ? "write"
640
- : remote !== "none" || ACCOUNT_FREE_COMMANDS.has(name)
641
- ? "none"
642
- : "read",
643
- },
644
- state: "beta",
645
- });
273
+ annotate(command, { origin: metaOf(command).origin ?? "handwritten", state: "beta" });
646
274
  }
647
275
  const pathOf = (command) => {
648
276
  const path = [];
@@ -669,6 +297,9 @@ export const createProgram = (options = {}) => {
669
297
  if (["commands", "complete", "config show", "config set", "session list"].includes(words))
670
298
  return;
671
299
  const flags = policyFlags();
300
+ // The server writes only through its tools, and each tool call runs this same check with these flags.
301
+ if (words === "mcp")
302
+ return checkPolicy(env, selected(), "mcp", false, flags, askOnce);
672
303
  const metadata = metaOf(action);
673
304
  const rawMethod = words === "api call" ? action.args[0] : undefined;
674
305
  const method = metadata.api_operation ?? rawMethod;
@@ -687,14 +318,14 @@ export const createProgram = (options = {}) => {
687
318
  const key = method ? `api.${method}` : path.join(".");
688
319
  for (const permission of method ? methodPolicyKeys(method) : [key])
689
320
  await checkPolicy(env, selected(), permission, mutates, flags, askOnce);
321
+ checkedMethod = method;
690
322
  if (flags.offline && (method || metadata.effects?.remote !== "none"))
691
323
  throw new CliError("permission_error", "this command may require network access; --offline was requested", {
692
324
  reason: "offline.refused",
693
325
  });
694
- if (flags.dryRun &&
695
- path[0] !== "api" &&
696
- !NETWORK_GROUPS.includes(path[0] ?? "") &&
697
- !["documents get", "documents create", "documents update", "documents history"].includes(words)) {
326
+ // A command that only calls Google previews the request itself, once its parameters are known.
327
+ const googleOnly = metadata.effects?.local === "none" && metadata.effects.remote !== "none";
328
+ if (flags.dryRun && !googleOnly) {
698
329
  output(itemOf({ dry_run: true, command: words, effects: metadata.effects }));
699
330
  throw new Preview();
700
331
  }