@wirecat/drive-cli 0.52.1 → 0.54.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 (218) hide show
  1. package/dist/bin/drive.js +2 -2
  2. package/dist/bin/drive.js.map +1 -1
  3. package/dist/bundle/{chunk-ZWSG7OCA.js → all-profiles-LFIPUPZI.js} +13 -8
  4. package/dist/bundle/{anthropic-KW6KU36Y.js → anthropic-G5ZRRWG4.js} +5 -5
  5. package/dist/bundle/{app-server-TCJZ333E.js → app-server-UVWATOQC.js} +48 -56
  6. package/dist/bundle/{bun-7SYKSCLA.js → bun-DNEFTPTR.js} +2 -2
  7. package/dist/bundle/{bun-sqlite-RI7DR6RZ.js → bun-sqlite-FWBYHIXB.js} +4 -4
  8. package/dist/bundle/{chunk-CM7GAXGD.js → chunk-2CQT2WWN.js} +5 -5
  9. package/dist/bundle/{chunk-HQVJK5E7.js → chunk-2D6AAGBP.js} +246 -383
  10. package/dist/bundle/{chunk-FG4XXZZE.js → chunk-2FFXRWI2.js} +2 -2
  11. package/dist/bundle/{chunk-2UIMEMWU.js → chunk-2HQPJ366.js} +3 -3
  12. package/dist/bundle/{chunk-CB7SBYLO.js → chunk-2HWOGSTA.js} +57 -37
  13. package/dist/bundle/{chunk-7XKAVMCF.js → chunk-2MSJVFAS.js} +8 -8
  14. package/dist/bundle/{chunk-NSIFQ5OP.js → chunk-2NWFZ43Q.js} +1 -1
  15. package/dist/bundle/{chunk-H47W2J6S.js → chunk-2Q3S47BC.js} +1312 -626
  16. package/dist/bundle/{chunk-O6IOL6RX.js → chunk-47MEPBWG.js} +21 -21
  17. package/dist/bundle/{chunk-725OHXKR.js → chunk-4RDXCE45.js} +2226 -37
  18. package/dist/bundle/{chunk-UR32UWTQ.js → chunk-5BPOAHVD.js} +13 -2
  19. package/dist/bundle/{chunk-5FONRUG6.js → chunk-5D4AEUVA.js} +1 -23
  20. package/dist/bundle/{chunk-VZ2I62HN.js → chunk-5LNOVPOR.js} +2 -2
  21. package/dist/bundle/{chunk-EKFEY3KP.js → chunk-5WQN2TUM.js} +1 -1
  22. package/dist/bundle/{chunk-ALJWBGD5.js → chunk-6MGSFYGL.js} +1 -1
  23. package/dist/bundle/{chunk-WUX7AUOQ.js → chunk-6RAEXK7Y.js} +26 -26
  24. package/dist/bundle/{chunk-BSSCTWWK.js → chunk-6SOQJRGI.js} +4 -4
  25. package/dist/bundle/{chunk-CKBHR7QO.js → chunk-75DSLCPC.js} +1 -1
  26. package/dist/bundle/{chunk-VSOLLTYT.js → chunk-76JIVDKC.js} +7 -2
  27. package/dist/bundle/{chunk-33NVQGUY.js → chunk-7WCZ2OZ5.js} +6 -6
  28. package/dist/bundle/{chunk-IDUNJCFO.js → chunk-7XU3TR7K.js} +2 -2
  29. package/dist/bundle/{chunk-7SH4JHYW.js → chunk-A4FTLORC.js} +12 -12
  30. package/dist/bundle/{chunk-CITFEQ6S.js → chunk-AACQA2CO.js} +1 -1
  31. package/dist/bundle/{chunk-PSNHPFSK.js → chunk-AAHIBA36.js} +1 -1
  32. package/dist/bundle/{chunk-PEOCBV2Z.js → chunk-BWBVBW5T.js} +8 -8
  33. package/dist/bundle/{chunk-A4UNTWAX.js → chunk-CVALO727.js} +99 -30
  34. package/dist/bundle/{chunk-G6QF5KWF.js → chunk-FHW4ENRF.js} +37 -43
  35. package/dist/bundle/{chunk-LONV6HIK.js → chunk-HAHARAJD.js} +455 -40
  36. package/dist/bundle/{chunk-2623YE5I.js → chunk-IBRXVPBI.js} +97 -99
  37. package/dist/bundle/{chunk-IWFBAWZK.js → chunk-IKODUUQG.js} +292 -19
  38. package/dist/bundle/{chunk-PQJYM5ES.js → chunk-IOMSC4ZG.js} +3 -3
  39. package/dist/bundle/{chunk-YKZ4IPLB.js → chunk-JKEAZBEZ.js} +7 -7
  40. package/dist/bundle/{chunk-FCJAHD4R.js → chunk-KIQIF5M7.js} +3 -3
  41. package/dist/bundle/{chunk-KYVXMEBC.js → chunk-KT5G3KVS.js} +3 -3
  42. package/dist/bundle/{chunk-W7IK7E4B.js → chunk-L3RV42O3.js} +20 -22
  43. package/dist/bundle/{chunk-NHBUTCNR.js → chunk-LQXLWHKM.js} +9 -9
  44. package/dist/bundle/{chunk-WBTVGFXI.js → chunk-MATUQFYL.js} +11 -11
  45. package/dist/bundle/{chunk-54O62JWP.js → chunk-MULPNGM2.js} +29 -10
  46. package/dist/bundle/{chunk-FJW3DDCF.js → chunk-N4OO3SPQ.js} +5 -5
  47. package/dist/bundle/{chunk-6DHQTUB2.js → chunk-NDWWGBSM.js} +1 -1
  48. package/dist/bundle/{chunk-DLAFGSTN.js → chunk-NHDSJMAR.js} +1 -1
  49. package/dist/bundle/{chunk-PQYVPCJ2.js → chunk-O6YYFVDD.js} +38 -37
  50. package/dist/bundle/{chunk-I7UH5CTA.js → chunk-OYGEBFFO.js} +12 -14
  51. package/dist/bundle/chunk-P7E7K467.js +110 -0
  52. package/dist/bundle/{chunk-ZNZUZGSV.js → chunk-PKNTBZXN.js} +176 -49
  53. package/dist/bundle/{chunk-YNFELLNQ.js → chunk-PU4GANCD.js} +3 -3
  54. package/dist/bundle/{chunk-5PLJKSG4.js → chunk-Q46JLJ5O.js} +7 -9
  55. package/dist/bundle/{chunk-R276546S.js → chunk-QKHFQHE7.js} +1 -1
  56. package/dist/bundle/{chunk-RNSP57TC.js → chunk-QUJCD5U7.js} +4 -4
  57. package/dist/bundle/{chunk-43QVYW3K.js → chunk-RIYXQFKU.js} +262 -88
  58. package/dist/bundle/{chunk-2AUXBJRX.js → chunk-RWEFKLXJ.js} +104 -29
  59. package/dist/bundle/{chunk-WQJBAWQP.js → chunk-SBOTSSYV.js} +879 -508
  60. package/dist/bundle/{chunk-PAXKALHV.js → chunk-U3BOQ63L.js} +118 -7
  61. package/dist/bundle/{chunk-VJZST5RD.js → chunk-UBJX5D2O.js} +2 -2
  62. package/dist/bundle/{chunk-HX7Y2ASG.js → chunk-VCGQMTHW.js} +26318 -15143
  63. package/dist/bundle/{chunk-7YMDL4JQ.js → chunk-VKYCMXEQ.js} +8 -5
  64. package/dist/bundle/{chunk-ZSXRDF6I.js → chunk-VX4RAT3A.js} +1 -1
  65. package/dist/bundle/{chunk-NYOPEHEU.js → chunk-W5SYBHRX.js} +8 -3
  66. package/dist/bundle/{chunk-XOLQSCMF.js → chunk-WGSTTWM5.js} +6 -6
  67. package/dist/bundle/{chunk-WLFUBNFX.js → chunk-WJRE45Z6.js} +4 -4
  68. package/dist/bundle/{chunk-IEXPOEEO.js → chunk-WQPTZHHR.js} +17 -26
  69. package/dist/bundle/{chunk-JEOYFKUK.js → chunk-WSX5UQNT.js} +2 -2
  70. package/dist/bundle/{chunk-LJAX6YCF.js → chunk-WYDYSQ7T.js} +2 -2
  71. package/dist/bundle/{chunk-C6Z25IBJ.js → chunk-XCUUYQN7.js} +4 -4
  72. package/dist/bundle/{chunk-GVCN3GLZ.js → chunk-YOHOQ6ZR.js} +4 -4
  73. package/dist/bundle/chunk-YZ5VMR2S.js +5305 -0
  74. package/dist/bundle/{chunk-ZDLIO76S.js → chunk-ZMMOVTUB.js} +2 -2
  75. package/dist/bundle/command-contract-VZ3ZJLEF.js +35 -0
  76. package/dist/bundle/{decode-EDN2ARXZ.js → decode-DN2DDFET.js} +4 -4
  77. package/dist/bundle/drive.js +11 -22
  78. package/dist/bundle/{echarts-GXY34GHA.js → echarts-VMHZ2UYP.js} +2 -2
  79. package/dist/bundle/{embed-3GSQIQXE.js → embed-MDN7R7BA.js} +5 -5
  80. package/dist/bundle/{embedder-6ULWRG3R.js → embedder-KEVEDNDJ.js} +8 -8
  81. package/dist/bundle/{entry-IPRJLFHO.js → entry-HTNK5TJQ.js} +6 -6
  82. package/dist/bundle/{first-run-FGHGWHC2.js → first-run-QNMCMP67.js} +9 -9
  83. package/dist/bundle/first-screen-RQBEHUQC.js +33 -0
  84. package/dist/bundle/{google-BD3ZNFVJ.js → google-QAKMV57Q.js} +9 -9
  85. package/dist/bundle/{chunk-GR5GGZKH.js → google-api-UJJS7ECO.js} +62 -6
  86. package/dist/bundle/grants-VMPKFEC2.js +98 -0
  87. package/dist/bundle/{identity-U7IHZEMR.js → identity-UODE3QAL.js} +4 -2
  88. package/dist/bundle/{instructions-K5BEQM4C.js → instructions-IWLHCDC7.js} +1 -1
  89. package/dist/bundle/{login-7HRYPZMM.js → login-GIZXEN7I.js} +60 -68
  90. package/dist/bundle/{mcp-WSGVVZWI.js → mcp-RUYPQVYS.js} +2 -2
  91. package/dist/bundle/{node-ZYWB7IET.js → node-25IJLDBZ.js} +2 -2
  92. package/dist/bundle/{node-sqlite-J3OODPYK.js → node-sqlite-DYR4FEI4.js} +4 -4
  93. package/dist/bundle/{oauth-L4VTCBLF.js → oauth-FLHXEDDY.js} +7 -7
  94. package/dist/bundle/{open-SGUN7ZVF.js → open-FWDZB7KX.js} +3 -3
  95. package/dist/bundle/{openai-RLVISEDH.js → openai-HB7UGKPW.js} +13 -13
  96. package/dist/bundle/{process-ZXO2MWRJ.js → process-P6TW37HQ.js} +1 -1
  97. package/dist/bundle/{program-YVLXSKZV.js → program-DVUNLXXS.js} +730 -919
  98. package/dist/bundle/{prompt-AUWTBLO7.js → prompt-MKWMYO3B.js} +4 -4
  99. package/dist/bundle/{reasons-J57GSRWN.js → reasons-25BEO2NE.js} +3 -3
  100. package/dist/bundle/{recognize-ORX2UBQW.js → recognize-VXGNPROM.js} +3 -3
  101. package/dist/bundle/{remote-AGIJY73X.js → remote-H5ZWLJHR.js} +6 -6
  102. package/dist/bundle/{rerank-R6PE44M5.js → rerank-5A3JDK7O.js} +6 -6
  103. package/dist/bundle/{chunk-G7DCVJ4F.js → serve-QNPNEZVR.js} +10 -7
  104. package/dist/bundle/{chunk-F7UUZATI.js → server-GWBVIRLY.js} +42 -15
  105. package/dist/bundle/server-QJU3HEGM.js +63 -0
  106. package/dist/bundle/{services-HZFTTZSF.js → services-PFXEWHJG.js} +30 -31
  107. package/dist/bundle/{sqlite-runtime-DTGPR2T2.js → sqlite-runtime-RGFISYXM.js} +4 -4
  108. package/dist/bundle/{state-WG3JKJM3.js → state-BUSX5BXF.js} +5 -5
  109. package/dist/bundle/{store-EV72MT5U.js → store-FIEE5HHG.js} +14 -16
  110. package/dist/bundle/{store-33VHIMEO.js → store-HFF5KQ44.js} +12 -14
  111. package/dist/bundle/store-maintenance-command-Z4SPEQUM.js +52 -0
  112. package/dist/bundle/{chunk-GNI7INK6.js → terminal-DHJ4D3BC.js} +2 -3
  113. package/dist/bundle/tokens-B6MUZRFM.js +96 -0
  114. package/dist/commands/context.d.ts +14 -13
  115. package/dist/commands/context.d.ts.map +1 -1
  116. package/dist/commands/context.js.map +1 -1
  117. package/dist/commands/documents.d.ts.map +1 -1
  118. package/dist/commands/documents.js +1 -4
  119. package/dist/commands/documents.js.map +1 -1
  120. package/dist/commands/mirrors.d.ts.map +1 -1
  121. package/dist/commands/mirrors.js +1 -2
  122. package/dist/commands/mirrors.js.map +1 -1
  123. package/dist/commands/upgrade.d.ts +1 -1
  124. package/dist/commands/upgrade.d.ts.map +1 -1
  125. package/dist/commands/upgrade.js +4 -9
  126. package/dist/commands/upgrade.js.map +1 -1
  127. package/dist/config.d.ts +182 -0
  128. package/dist/config.d.ts.map +1 -1
  129. package/dist/config.js +38 -3
  130. package/dist/config.js.map +1 -1
  131. package/dist/contract-overrides.d.ts +0 -3
  132. package/dist/contract-overrides.d.ts.map +1 -1
  133. package/dist/contract-overrides.js +0 -234
  134. package/dist/contract-overrides.js.map +1 -1
  135. package/dist/first-screen.d.ts +3 -2
  136. package/dist/first-screen.d.ts.map +1 -1
  137. package/dist/first-screen.js +17 -22
  138. package/dist/first-screen.js.map +1 -1
  139. package/dist/grants.d.ts +9 -0
  140. package/dist/grants.d.ts.map +1 -0
  141. package/dist/grants.js +30 -0
  142. package/dist/grants.js.map +1 -0
  143. package/dist/identity.d.ts.map +1 -1
  144. package/dist/identity.js +2 -0
  145. package/dist/identity.js.map +1 -1
  146. package/dist/login.d.ts.map +1 -1
  147. package/dist/login.js +2 -4
  148. package/dist/login.js.map +1 -1
  149. package/dist/policy-keys.d.ts +12 -0
  150. package/dist/policy-keys.d.ts.map +1 -0
  151. package/dist/policy-keys.js +107 -0
  152. package/dist/policy-keys.js.map +1 -0
  153. package/dist/policy.d.ts +1 -8
  154. package/dist/policy.d.ts.map +1 -1
  155. package/dist/policy.js +2 -105
  156. package/dist/policy.js.map +1 -1
  157. package/dist/program.d.ts +8 -4
  158. package/dist/program.d.ts.map +1 -1
  159. package/dist/program.js +251 -222
  160. package/dist/program.js.map +1 -1
  161. package/dist/testing/mcp.d.ts +28 -0
  162. package/dist/testing/mcp.d.ts.map +1 -0
  163. package/dist/testing/mcp.js +56 -0
  164. package/dist/testing/mcp.js.map +1 -0
  165. package/dist/tokens.d.ts.map +1 -1
  166. package/dist/tokens.js +0 -9
  167. package/dist/tokens.js.map +1 -1
  168. package/dist/version.d.ts +1 -1
  169. package/dist/version.js +1 -1
  170. package/package.json +6 -5
  171. package/scenarios/agent-access.md +4 -2
  172. package/dist/bundle/all-profiles-CYW6XBBS.js +0 -26
  173. package/dist/bundle/chunk-234MHU76.js +0 -384
  174. package/dist/bundle/chunk-BBYD2FA3.js +0 -9
  175. package/dist/bundle/chunk-DO4PDQY5.js +0 -48
  176. package/dist/bundle/chunk-FDWYPONW.js +0 -1988
  177. package/dist/bundle/chunk-FQRJWVEB.js +0 -2
  178. package/dist/bundle/chunk-GJN5B5JK.js +0 -522
  179. package/dist/bundle/chunk-NPSZPUK6.js +0 -193
  180. package/dist/bundle/chunk-PDGECM5D.js +0 -138
  181. package/dist/bundle/chunk-Q765VPZY.js +0 -421
  182. package/dist/bundle/chunk-QYUHS6DE.js +0 -1714
  183. package/dist/bundle/chunk-WQRGA75U.js +0 -256
  184. package/dist/bundle/chunk-YVPHJHIL.js +0 -15572
  185. package/dist/bundle/chunk-Z47LOJUS.js +0 -484
  186. package/dist/bundle/command-contract-I2YB5IXI.js +0 -38
  187. package/dist/bundle/failure-IXS2ZHA5.js +0 -37
  188. package/dist/bundle/first-screen-M62KTPZG.js +0 -36
  189. package/dist/bundle/google-api-BDUWZMRV.js +0 -83
  190. package/dist/bundle/mcp-F67RATLF.js +0 -502
  191. package/dist/bundle/mcp-JZSYPQA4.js +0 -96
  192. package/dist/bundle/serve-VOBAQHAQ.js +0 -20
  193. package/dist/bundle/server-24PS4M7U.js +0 -70
  194. package/dist/bundle/server-G6HFZ2CK.js +0 -57
  195. package/dist/bundle/store-maintenance-command-ZTUEI4EC.js +0 -58
  196. package/dist/bundle/terminal-TFCTWLOS.js +0 -11
  197. package/dist/bundle/tokens-XMOGQFI6.js +0 -102
  198. package/dist/commands/doctor.d.ts +0 -56
  199. package/dist/commands/doctor.d.ts.map +0 -1
  200. package/dist/commands/doctor.js +0 -75
  201. package/dist/commands/doctor.js.map +0 -1
  202. package/dist/commands/mcp.d.ts +0 -6
  203. package/dist/commands/mcp.d.ts.map +0 -1
  204. package/dist/commands/mcp.js +0 -156
  205. package/dist/commands/mcp.js.map +0 -1
  206. package/dist/commands/skill.d.ts +0 -6
  207. package/dist/commands/skill.d.ts.map +0 -1
  208. package/dist/commands/skill.js +0 -34
  209. package/dist/commands/skill.js.map +0 -1
  210. package/dist/failure.d.ts +0 -88
  211. package/dist/failure.d.ts.map +0 -1
  212. package/dist/failure.js +0 -60
  213. package/dist/failure.js.map +0 -1
  214. package/dist/mcp.d.ts +0 -175
  215. package/dist/mcp.d.ts.map +0 -1
  216. package/dist/mcp.js +0 -412
  217. package/dist/mcp.js.map +0 -1
  218. /package/dist/bundle/{chunk-62EDJKGP.js → chunk-HEA3XVAJ.js} +0 -0
package/dist/program.js CHANGED
@@ -1,95 +1,87 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { readFileSync } from "node:fs";
3
- import { CliError, createDeadline, createOutputBuffer, createRenderer, fieldsOf, isCliError, processStreams, projectFields, } from "@wirecat/cli-base";
2
+ import { mkdirSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { CliError, isCliError, processStreams } from "@wirecat/cli-base";
4
5
  import { annotate, flatten, metaOf } from "@wirecat/cli-base/commands";
5
6
  import { timezoneOf } from "@wirecat/cli-base/query";
6
7
  import { writes } from "@wirecat/cli-base/standards";
7
- import { addContractInfo, assertSharedContracts, changesAuthority, commandWords, environmentOf, hasSharedContract, itemOf, LOCAL_READ, liftJson, liftProfile, overrideSharedContract, parseDuration, provide, recordRuns, refuseCommandName, renderAnswer, runsCommand, takesProfile, } from "@wirecat/cli-core/cli";
8
+ import { addContractInfo, appDoctorCommand, appMcpCommand, changesAuthority, commandRuns, commandWords, createProgram as createSharedProgram, environmentOf, hasSharedContract, inRun, itemOf, LOCAL_READ, outputFor, overrideSharedContract, parseDuration, readOnlyRefusal, refuseCommandName, renderAnswer, rootOf, run as runShared, runsCommand, skillCommand, } from "@wirecat/cli-core/cli";
8
9
  import { levelFor, newOperationId } from "@wirecat/cli-core/sends";
9
- import { Command, Help } from "commander";
10
10
  import { validateRequest } from "./api-contract.js";
11
11
  import { apiMethod } from "./api-methods.js";
12
12
  import { installCatalogCommands } from "./commands/catalog.js";
13
13
  import { installConfigCommands, installModelCommands } from "./commands/config.js";
14
14
  import { offset, positive } from "./commands/context.js";
15
15
  import { installCommandsCommand, installCompleteCommand } from "./commands/discovery.js";
16
- import { installDoctorCommand } from "./commands/doctor.js";
17
16
  import { importedDocument, installDocumentCommands, storedDocument } from "./commands/documents.js";
18
17
  import { installFolderCommands } from "./commands/folders.js";
19
18
  import { installKnowledgeCommands } from "./commands/knowledge.js";
20
- import { installMcpCommand } from "./commands/mcp.js";
21
19
  import { installMirrorCommands } from "./commands/mirrors.js";
22
20
  import { installRemoteCommands } from "./commands/remote.js";
23
21
  import { installSearchCommand } from "./commands/search.js";
24
22
  import { installSessionCommands } from "./commands/session.js";
25
- import { installSkillCommand } from "./commands/skill.js";
26
23
  import { installStoreCommands } from "./commands/store.js";
27
24
  import { installSyncCommands } from "./commands/sync.js";
28
25
  import { installUpgradeCommand } from "./commands/upgrade.js";
29
- import { activeProfile, fileId, profileName, readConfig } from "./config.js";
26
+ import { activeProfile, application, configuration, fileId, paths, profileName, readConfig } from "./config.js";
30
27
  import { googleError } from "./errors.js";
31
28
  import { memoryModel } from "./extraction.js";
32
- import { REASONS as CONTRACT_REASONS } from "./failure.js";
33
- import { guide, installFirstScreen } from "./first-screen.js";
29
+ import { FIRST_SCREEN, guide, placeInSections } from "./first-screen.js";
34
30
  import { snakeKeys } from "./output.js";
35
- import { checkPolicy, DRIVE_APP, discoveryAvailability, guardedGoogleWrite, methodPolicyKeys, permissionKeys, permissionNames, policySettings, refuseUnderReadOnly, } from "./policy.js";
31
+ import { checkPolicy, DRIVE_APP, guardedGoogleWrite, methodPolicyKeys, permissionKeys, permissionNames, policySettings, refuseUnderReadOnly, } from "./policy.js";
36
32
  import { lockProfile } from "./profile-lock.js";
37
33
  import { checkProviderJson, checkResultFields, providerJsonFields } from "./provider-json.js";
34
+ import { REASONS } from "./reasons.js";
38
35
  import { ACCOUNT_FREE_COMMANDS, ANY_PROFILE_COMMANDS, describeDriveProgram, markProfileFree, PROFILE_SET_COMMANDS, } from "./registry.js";
39
36
  import { profileDir } from "./state.js";
40
37
  import { openIndex } from "./store.js";
41
38
  import { localTimes } from "./time.js";
42
39
  import { uploadFile } from "./upload.js";
43
- import { VERSION } from "./version.js";
40
+ const SKILL = new URL("../skills/drive-cli/SKILL.md", import.meta.url);
44
41
  const eachItem = (body, change) => "items" in body ? { ...body, items: body.items.map(change) } : { ...body, item: change(body.item) };
45
- const commandIn = (root, words) => {
46
- let at = root;
47
- for (const word of words) {
48
- if (word.startsWith("-"))
49
- continue;
50
- const child = at?.commands.find((command) => command.name() === word);
51
- if (child)
52
- at = child;
53
- }
54
- return at === root ? undefined : at;
55
- };
56
42
  class Preview extends Error {
57
43
  }
58
- export const createProgram = (options = {}) => {
44
+ // An agent names only a file, which lands in the profile's export folder, never a path of its choosing.
45
+ const EXPORTS = new Set(["documents export", "files download", "files export"]);
46
+ const googleOnly = (effects) => effects?.local === "none" && effects.remote !== "none";
47
+ /**
48
+ * The commands are built inside `createProgram`, before `run` hands the program its environment, so what they read
49
+ * from it is looked up when they run.
50
+ */
51
+ const lateEnv = (environment) => {
52
+ const current = () => environment().env ?? process.env;
53
+ return new Proxy({}, {
54
+ get: (_, key) => Reflect.get(current(), key),
55
+ has: (_, key) => Reflect.has(current(), key),
56
+ ownKeys: () => Reflect.ownKeys(current()),
57
+ getOwnPropertyDescriptor: (_, key) => Reflect.getOwnPropertyDescriptor(current(), key),
58
+ });
59
+ };
60
+ const lateStreams = (environment) => ({
61
+ data: (text) => (environment().streams ?? processStreams).data(text),
62
+ diagnostic: (text) => (environment().streams ?? processStreams).diagnostic(text),
63
+ });
64
+ const runsOf = new WeakMap();
65
+ const installDrive = (program) => {
59
66
  const startedAt = Date.now();
60
- const env = options.env ?? process.env;
61
- const streams = options.streams ?? processStreams;
62
- const program = new Command("drive")
63
- .description("manage Google Drive and Docs, local Markdown, shared knowledge and search")
64
- .version(VERSION)
65
- .usage("<profile> [options] <command>")
66
- .option("--json", "print machine-readable JSON; --json=id,name keeps only those fields")
67
- .option("--jsonl", "print machine-readable JSON lines")
68
- .option("--quiet", "suppress optional diagnostics")
69
- .option("--debug", "on failure, show the full error record: cause and stack")
70
- .option("--timeout <duration>", "whole-command deadline, e.g. 30s", (raw) => parseDuration(raw, "--timeout"))
71
- .option("--max-output-bytes <bytes>", "largest result to print, in bytes; 0 for no limit", offset, 4 * 1024 * 1024)
67
+ const environment = () => environmentOf(program);
68
+ const env = lateEnv(environment);
69
+ const streams = lateStreams(environment);
70
+ program
72
71
  .option("--read-only", "refuse local and remote mutations")
73
- .option("--offline", "answer only operations that use local cached data")
74
- .option("--dry-run", "validate command/policy and preview without acting")
75
- .option("--yes", "answer a policy confirmation; cannot override deny or readonly")
76
72
  .option("--allow-dangerous", "answer a permanent-deletion confirmation")
77
- .option("--permission <key=level>", "temporary policy override; repeat to add keys", (value, previous = []) => [...previous, value]);
78
- program
79
- .configureOutput({
80
- writeOut: (text) => streams.data(text.replace(/\n$/, "")),
81
- writeErr: (text) => streams.diagnostic(text.replace(/\n$/, "")),
82
- outputError: () => undefined,
83
- })
84
- .exitOverride();
85
- let profileWord;
73
+ .option("--permission <key=level>", "make a permission stricter for this run only; repeat to add keys", (value, previous = []) => [...previous, value]);
74
+ const profileWord = () => {
75
+ const word = program.opts().profile;
76
+ return word === undefined ? undefined : profileName(word);
77
+ };
86
78
  /**
87
79
  * The profile is the first word, or DRIVE_PROFILE; nothing picks one. DRIVE_PROFILE_LOCK pins the process: a
88
80
  * word or variable naming another profile is refused, so an agent cannot reach a profile with fewer guards.
89
81
  */
90
82
  const selected = () => {
91
83
  const lock = env.DRIVE_PROFILE_LOCK || undefined;
92
- const named = profileWord ?? (env.DRIVE_PROFILE || undefined);
84
+ const named = profileWord() ?? (env.DRIVE_PROFILE || undefined);
93
85
  if (lock !== undefined) {
94
86
  profileName(lock);
95
87
  if (named !== undefined && profileName(named) !== lock)
@@ -106,15 +98,17 @@ export const createProgram = (options = {}) => {
106
98
  };
107
99
  let currentAction;
108
100
  let checkedMethod;
109
- let fields;
110
- let activeSignal = options.signal;
111
- let deadline;
112
- let stopEnds = false;
101
+ let stopSignal;
102
+ let previewsRequest = false;
103
+ const agent = () => environment().agent !== undefined;
113
104
  const confirmations = new Set();
114
105
  const askOnce = async (key) => {
106
+ // Nobody is at a terminal over MCP, and the profile's levels already allowed `ask` (WC-MCP-7).
107
+ if (agent())
108
+ return true;
115
109
  if (confirmations.has(key))
116
110
  return true;
117
- const answered = (await options.ask?.(key)) ?? false;
111
+ const answered = (await environment().ask?.(key)) ?? false;
118
112
  if (answered)
119
113
  confirmations.add(key);
120
114
  return answered;
@@ -122,23 +116,20 @@ export const createProgram = (options = {}) => {
122
116
  let knownKeys;
123
117
  const policyFlags = () => {
124
118
  knownKeys ??= permissionKeys(flatten(describeDriveProgram(program)).map((info) => info.path));
119
+ const flags = program.opts();
125
120
  return {
126
- ...program.opts(),
127
- allowDangerous: program.opts().allowDangerous || currentAction?.opts().allowDelete,
121
+ ...flags,
122
+ permission: [...(environment().agent?.overrides ?? []), ...(flags.permission ?? [])],
123
+ allowDangerous: flags.allowDangerous || currentAction?.opts().allowDelete,
124
+ dryRun: flags.dryRun || previewsRequest,
128
125
  permissionKeys: knownKeys,
129
126
  };
130
127
  };
131
128
  const runId = randomUUID();
129
+ const shown = () => outputFor(currentAction ?? program);
132
130
  const print = (render) => {
133
- const format = program.opts().jsonl
134
- ? "jsonl"
135
- : program.opts().json || !process.stdout.isTTY
136
- ? "json"
137
- : "pretty";
138
- const buffer = createOutputBuffer({ maxOutputBytes: program.opts().maxOutputBytes });
139
- const buffered = { ...streams, data: (text) => buffer.data(text) };
140
- render(createRenderer({ format, color: false, streams: buffered, quiet: program.opts().quiet === true }), format, buffered);
141
- buffer.flush((text) => streams.data(text));
131
+ const { renderer, format, streams: out } = shown();
132
+ render(renderer, format, out);
142
133
  };
143
134
  const output = (body) => {
144
135
  const snaked = eachItem(body, (item) => snakeKeys(item));
@@ -151,37 +142,37 @@ export const createProgram = (options = {}) => {
151
142
  ...body.meta,
152
143
  },
153
144
  };
145
+ const fields = program.opts().fields;
154
146
  if (fields && currentAction)
155
147
  checkResultFields(currentAction, whole, fields);
156
- const paths = fields ? fieldsOf(fields) : undefined;
157
- const answer = paths ? projectFields(whole, paths) : whole;
158
- print((renderer, format, buffered) => {
159
- const command = currentAction ?? program;
160
- if (format !== "pretty")
161
- return renderAnswer(command, { renderer, format, streams: buffered }, answer);
162
- const zone = timezoneOf();
163
- const shown = localTimes(answer, zone);
164
- renderAnswer(command, { renderer, format, streams: buffered }, shown.value);
165
- if (shown.changed || answer.meta.timezone)
166
- buffered.data(`times in ${answer.meta.timezone ?? zone}`);
167
- });
148
+ const command = currentAction ?? program;
149
+ const out = shown();
150
+ if (out.format !== "pretty")
151
+ return renderAnswer(command, out, whole);
152
+ const zone = timezoneOf();
153
+ const local = localTimes(whole, zone);
154
+ renderAnswer(command, out, local.value);
155
+ if (local.changed || whole.meta.timezone)
156
+ out.streams.data(`times in ${whole.meta.timezone ?? zone}`);
168
157
  };
158
+ const signal = () => environment().signal;
169
159
  // Google's client libraries are about 80 ms of a start; only a command that reaches Google loads them.
170
160
  const signedIn = async (name, scope) => {
171
161
  const { authorizedClient, checkAuthorization } = await import("./tokens.js");
172
- const client = authorizedClient(env, name, options.keyring, activeSignal);
162
+ const client = authorizedClient(env, name, environment().keyring, signal());
173
163
  await checkAuthorization(client, scope);
174
164
  return client;
175
165
  };
176
166
  const source = async () => {
177
167
  const name = selected();
178
- if (options.source)
179
- return options.source(name);
168
+ const fake = environment().source;
169
+ if (fake)
170
+ return fake(name);
180
171
  const [{ googleSource }, client] = await Promise.all([import("./google.js"), signedIn(name)]);
181
172
  return googleSource(client);
182
173
  };
183
174
  const withIndex = async (fn) => {
184
- const index = await (options.index?.() ?? openIndex(env, selected(), currentAction?.opts().rescan === true));
175
+ const index = await (environment().index?.() ?? openIndex(env, selected(), currentAction?.opts().rescan === true));
185
176
  try {
186
177
  return await fn(index);
187
178
  }
@@ -189,22 +180,60 @@ export const createProgram = (options = {}) => {
189
180
  await index.close();
190
181
  }
191
182
  };
183
+ const options = {
184
+ get keyring() {
185
+ return environment().keyring;
186
+ },
187
+ get openBrowser() {
188
+ return environment().openBrowser;
189
+ },
190
+ get update() {
191
+ return environment().update;
192
+ },
193
+ get mcp() {
194
+ return agent();
195
+ },
196
+ };
192
197
  const context = {
193
198
  env,
194
199
  streams,
195
200
  options,
196
201
  selected,
197
- signal: () => activeSignal,
202
+ signal,
198
203
  output,
199
204
  print,
200
205
  source,
201
206
  withIndex,
202
207
  policyFlags,
203
- profileWord: () => profileWord,
208
+ profileWord,
204
209
  endsOnStop: () => {
205
- stopEnds = true;
210
+ // cli-core bounds a persistent command by nothing, so its --timeout is drive's to keep.
211
+ const timeout = program.opts().timeout;
212
+ stopSignal = AbortSignal.any([
213
+ environment().untilStopped?.(),
214
+ signal(),
215
+ timeout === undefined ? undefined : AbortSignal.timeout(parseDuration(timeout, "--timeout")),
216
+ ].filter((one) => one !== undefined));
217
+ return stopSignal;
206
218
  },
207
219
  };
220
+ const runs = commandRuns({
221
+ app: DRIVE_APP,
222
+ profile: () => profileWord() ?? (env.DRIVE_PROFILE_LOCK || env.DRIVE_PROFILE || undefined),
223
+ settings: () => {
224
+ const defaults = readConfig(env).defaults;
225
+ return {
226
+ record: defaults?.record,
227
+ keepRunsForDays: defaults?.keep_runs_for_days,
228
+ keepSuccessfulRunsForDays: defaults?.keep_successful_runs_for_days,
229
+ runsSizeLimitMb: defaults?.runs_size_limit_mb,
230
+ recordInput: defaults?.record_input,
231
+ };
232
+ },
233
+ env,
234
+ streams,
235
+ });
236
+ runsOf.set(program, runs);
208
237
  const imported = importedDocument(context);
209
238
  installSessionCommands(program, context);
210
239
  installFolderCommands(program, context);
@@ -217,7 +246,7 @@ export const createProgram = (options = {}) => {
217
246
  document: imported,
218
247
  output,
219
248
  positive,
220
- complete: () => options.complete ?? memoryModel(env, selected(), activeSignal),
249
+ complete: () => environment().complete ?? memoryModel(env, selected(), signal()),
221
250
  run: async (input, fn) => withIndex(async (index) => {
222
251
  const lock = await lockProfile(env, selected());
223
252
  try {
@@ -237,22 +266,26 @@ export const createProgram = (options = {}) => {
237
266
  }),
238
267
  });
239
268
  const remote = {
240
- mcp: options.mcp,
269
+ get mcp() {
270
+ return agent();
271
+ },
241
272
  stored: storedDocument(context),
242
273
  output,
243
274
  positive,
244
- readBody: options.readBody ??
245
- ((path) => {
246
- try {
247
- return readFileSync(path, "utf8");
248
- }
249
- catch {
250
- throw new CliError("validation_error", "the request body file could not be read", {
251
- reason: "body.unreadable",
252
- param: "--body-file",
253
- });
254
- }
255
- }),
275
+ readBody: (path) => {
276
+ const fake = environment().readBody;
277
+ if (fake)
278
+ return fake(path);
279
+ try {
280
+ return readFileSync(path, "utf8");
281
+ }
282
+ catch {
283
+ throw new CliError("validation_error", "the request body file could not be read", {
284
+ reason: "body.unreadable",
285
+ param: "--body-file",
286
+ });
287
+ }
288
+ },
256
289
  call: async (method, params, body) => {
257
290
  const descriptor = apiMethod(method);
258
291
  validateRequest(method, params, body);
@@ -274,8 +307,9 @@ export const createProgram = (options = {}) => {
274
307
  }
275
308
  const act = async () => {
276
309
  try {
277
- if (options.api)
278
- return await options.api.call(method, params, body);
310
+ const fake = environment().api;
311
+ if (fake)
312
+ return await fake.call(method, params, body);
279
313
  const [{ googleApi }, client] = await Promise.all([
280
314
  import("./google-api.js"),
281
315
  signedIn(selected(), descriptor.scope),
@@ -300,8 +334,9 @@ export const createProgram = (options = {}) => {
300
334
  const flags = policyFlags();
301
335
  for (const key of methodPolicyKeys(method))
302
336
  await checkPolicy(env, selected(), key, false, flags, askOnce);
303
- if (options.download)
304
- return options.download(id, mime);
337
+ const fake = environment().download;
338
+ if (fake)
339
+ return fake(id, mime);
305
340
  const [{ googleDownload }, client] = await Promise.all([
306
341
  import("./google-api.js"),
307
342
  signedIn(selected(), apiMethod(method).scope),
@@ -319,7 +354,7 @@ export const createProgram = (options = {}) => {
319
354
  throw new Preview();
320
355
  }
321
356
  const act = async () => {
322
- let request = options.uploadRequest;
357
+ let request = environment().uploadRequest;
323
358
  if (!request) {
324
359
  const [{ googleUploadRequest }, client] = await Promise.all([
325
360
  import("./google-api.js"),
@@ -342,46 +377,22 @@ export const createProgram = (options = {}) => {
342
377
  installConfigCommands(program, context);
343
378
  installCompleteCommand(program, context);
344
379
  installModelCommands(program, context);
345
- installMcpCommand(program, context, createProgram);
346
380
  installCommandsCommand(program, context);
347
- installSkillCommand(program, context);
348
- installDoctorCommand(program, context);
349
381
  installUpgradeCommand(program, context);
350
382
  program.addCommand(overrideSharedContract(runsCommand(DRIVE_APP), "Every drive command declares its effects, groups included; the shared runs group reads only local files.", (runs) => {
351
383
  annotate(runs, { effects: LOCAL_READ });
352
384
  }));
353
- markProfileFree(program);
354
- provide(program, {
355
- env,
356
- streams,
357
- discoveryAvailability: (info) => {
358
- if (!(profileWord ?? env.DRIVE_PROFILE ?? env.DRIVE_PROFILE_LOCK))
359
- return undefined;
360
- try {
361
- const command = flatten(describeDriveProgram(program)).find((one) => one.path.join(" ") === info.path.join(" "));
362
- return command ? discoveryAvailability(command, policySettings(env, selected(), policyFlags())) : undefined;
363
- }
364
- catch {
365
- return undefined;
366
- }
367
- },
368
- });
369
- for (const info of flatten(describeDriveProgram(program))) {
370
- if (info.commands.length)
371
- continue;
372
- let command = program;
373
- for (const word of info.path)
374
- command = command.commands.find((one) => one.name() === word) ?? command;
375
- command.addHelpText("after", () => {
376
- const availability = environmentOf(program).discoveryAvailability?.(info);
377
- return availability?.available === false ? `\nAvailability: unavailable — ${availability.reason}\n` : "";
378
- });
379
- }
380
385
  program.addCommand(guide());
386
+ markProfileFree(program);
381
387
  for (const info of flatten(describeDriveProgram(program))) {
382
388
  let command = program;
383
389
  for (const part of info.path)
384
390
  command = command.commands.find((child) => child.name() === part) ?? command;
391
+ if (!info.commands.length)
392
+ command.addHelpText("after", () => {
393
+ const availability = environment().discoveryAvailability?.(info);
394
+ return availability?.available === false ? `\nAvailability: unavailable — ${availability.reason}\n` : "";
395
+ });
385
396
  const metadata = { origin: metaOf(command).origin ?? "handwritten", state: "beta" };
386
397
  if (hasSharedContract(command))
387
398
  overrideSharedContract(command, "Drive explicitly labels its public CLI commands beta while its provider integration is reviewed.", (one) => {
@@ -390,6 +401,7 @@ export const createProgram = (options = {}) => {
390
401
  else
391
402
  annotate(command, metadata);
392
403
  }
404
+ placeInSections(program);
393
405
  const pathOf = (command) => {
394
406
  const path = [];
395
407
  for (let at = command; at?.parent; at = at.parent)
@@ -398,17 +410,13 @@ export const createProgram = (options = {}) => {
398
410
  };
399
411
  program.hook("preAction", async (_root, action) => {
400
412
  currentAction = action;
401
- checkProviderJson(action, { json: program.opts().json === true, ...(fields ? { fields } : {}) }, process.stdout.isTTY);
402
- if (program.opts().timeout !== undefined && !deadline) {
403
- deadline = createDeadline({
404
- timeoutMs: program.opts().timeout,
405
- ...(options.signal ? { signal: options.signal } : {}),
406
- });
407
- activeSignal = deadline.signal;
408
- }
413
+ runs.start(action);
414
+ const fields = program.opts().fields;
415
+ checkProviderJson(action, { json: program.opts().json === true, ...(fields ? { fields } : {}) }, environment().tty ?? process.stdout.isTTY);
409
416
  const path = pathOf(action);
410
417
  const words = path.join(" ");
411
418
  const metadata = metaOf(action);
419
+ // cli-core's own preview runs after this hook, for every command this one lets through.
412
420
  const preview = () => {
413
421
  output(itemOf({ dry_run: true, command: words, effects: metadata.effects, action_invoked: false }));
414
422
  throw new Preview();
@@ -419,30 +427,46 @@ export const createProgram = (options = {}) => {
419
427
  preview();
420
428
  };
421
429
  // Discovery is account-independent and must not load config, credentials or the store.
422
- if (ACCOUNT_FREE_COMMANDS.has(words) && !options.mcp)
430
+ if (ACCOUNT_FREE_COMMANDS.has(words) && !agent())
423
431
  return previewWrite();
424
- await options.atStart?.(action);
425
432
  if (ANY_PROFILE_COMMANDS.has(words)) {
426
- if (profileWord ?? env.DRIVE_PROFILE ?? env.DRIVE_PROFILE_LOCK)
433
+ if (profileWord() ?? env.DRIVE_PROFILE ?? env.DRIVE_PROFILE_LOCK)
427
434
  selected();
428
435
  return;
429
436
  }
430
437
  // The action picks the profile, the defaults or the top of the file, so a broken file can still be repaired.
431
- if (words === "config unset" && !options.mcp && !profileWord) {
438
+ if (words === "config unset" && !agent() && !profileWord()) {
432
439
  refuseUnderReadOnly(env, "change a setting");
433
440
  return previewWrite();
434
441
  }
435
- // The action names the profiles or refuses; each profile's own `drive <profile> mcp serve` checks its policy.
436
- if (PROFILE_SET_COMMANDS.has(words) &&
437
- !options.mcp &&
438
- (action.opts().profiles !== undefined || !(profileWord ?? env.DRIVE_PROFILE ?? env.DRIVE_PROFILE_LOCK)))
442
+ if (words === "mcp serve" && program.opts().readOnly) {
443
+ // The server's tools are runs of their own, which read the lock from the environment and not this flag.
444
+ const served = environment().env ?? process.env;
445
+ served.DRIVE_READ_ONLY = "1";
446
+ }
447
+ if (words === "mcp revoke" && program.opts().readOnly)
448
+ throw readOnlyRefusal("--read-only", "forget the browser logins");
449
+ // The shared `mcp` names its profiles or refuses; each tool call runs this hook for its own profile.
450
+ if (PROFILE_SET_COMMANDS.has(words) || path[0] === "mcp") {
451
+ const named = profileWord() ?? env.DRIVE_PROFILE ?? env.DRIVE_PROFILE_LOCK;
452
+ if (words === "mcp serve" && named && action.opts().profiles === undefined)
453
+ await checkPolicy(env, selected(), "mcp", false, policyFlags(), askOnce);
439
454
  return;
455
+ }
440
456
  selected();
441
- if ((words === "config set" || words === "config unset") && !options.mcp) {
457
+ if ((words === "config set" || words === "config unset") && !agent()) {
442
458
  refuseUnderReadOnly(env, "change a setting");
443
459
  return previewWrite();
444
460
  }
445
- if (options.mcp && changesAuthority(action)) {
461
+ if (agent() && EXPORTS.has(words)) {
462
+ const name = action.opts().output;
463
+ if (typeof name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(name))
464
+ throw new CliError("validation_error", "MCP exports take a filename inside the profile export folder");
465
+ const directory = join(paths(env).cache, "exports", selected());
466
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
467
+ action.setOptionValue("output", join(directory, name));
468
+ }
469
+ if (agent() && changesAuthority(action)) {
446
470
  const authority = policySettings(env, selected(), policyFlags());
447
471
  if (!["ask", "allow"].includes(levelFor(authority.levels, "mcp.authority").level))
448
472
  throw new CliError("permission_error", "MCP authority changes require the owner's mcp.authority permission");
@@ -453,9 +477,6 @@ export const createProgram = (options = {}) => {
453
477
  }
454
478
  }
455
479
  const flags = policyFlags();
456
- // The server writes only through its tools, and each tool call runs this same check with these flags.
457
- if (words === "mcp serve")
458
- return checkPolicy(env, selected(), "mcp", false, flags, askOnce);
459
480
  const rawMethod = words === "api call" ? action.args[0] : undefined;
460
481
  const method = metadata.api_operation ?? rawMethod;
461
482
  if (rawMethod) {
@@ -478,86 +499,94 @@ export const createProgram = (options = {}) => {
478
499
  throw new CliError("permission_error", "this command may require network access; --offline was requested", {
479
500
  reason: "offline.refused",
480
501
  });
481
- // A command that only calls Google previews the request itself, once its parameters are known.
482
- const googleOnly = metadata.effects?.local === "none" && metadata.effects.remote !== "none";
483
- if (flags.dryRun && !googleOnly)
502
+ if (flags.dryRun && !googleOnly(metadata.effects))
484
503
  preview();
504
+ // A command that only calls Google previews the request itself, once its parameters are known; cli-core, whose
505
+ // hook runs after this one, would preview the bare command instead.
506
+ if (flags.dryRun) {
507
+ previewsRequest = true;
508
+ program.setOptionValue("dryRun", false);
509
+ }
485
510
  if (words === "session start")
486
511
  refuseCommandName(selected(), commandWords(program), "drive");
487
512
  });
513
+ program.hook("postAction", () => runs.succeed());
488
514
  const parse = program.parseAsync.bind(program);
489
- program.parseAsync = async (argv = process.argv, settings) => {
490
- const prefix = settings?.from === "user" ? [] : argv.slice(0, 2);
491
- const args = settings?.from === "user" ? argv : argv.slice(2);
492
- const valued = new Set(program.options
493
- .filter((option) => option.required)
494
- .flatMap((option) => [option.long, option.short].filter((flag) => flag !== undefined)));
495
- const profiled = liftProfile([...args], commandWords(program), valued);
496
- const requested = liftJson(profiled.rest, (words) => commandIn(program, words), providerJsonFields);
497
- fields = requested.fields;
498
- const lifted = { ...profiled, rest: requested.argv };
499
- const flags = lifted.rest.slice(0, lifted.rest.indexOf("--") < 0 ? lifted.rest.length : lifted.rest.indexOf("--"));
500
- if (flags.some((arg) => arg === "--profile" || arg.startsWith("--profile=")))
501
- throw new CliError("validation_error", "the profile is the first word: drive <profile> <command>; there is no --profile");
502
- profileWord = lifted.profile ? profileName(lifted.profile) : undefined;
503
- // cli-core writes the profile into each next[].line from this root option; drive reads it as a first word.
504
- program.setOptionValue("profile", profileWord);
505
- const rest = lifted.rest;
515
+ // Google's clients report each request with `providerEvent`, which lands in the run this scope names.
516
+ const scope = {
517
+ get runId() {
518
+ return runs.runId() ?? runId;
519
+ },
520
+ command: "",
521
+ startedAt,
522
+ events: ((event) => {
523
+ if (event.event === "request" || event.event === "response")
524
+ runs.events(event);
525
+ }),
526
+ };
527
+ program.parseAsync = async (argv, settings) => {
506
528
  try {
507
- const running = parse([...prefix, ...rest], settings);
508
- return deadline ? await deadline.race(async () => running) : await running;
529
+ return await inRun(scope, () => parse(argv, settings));
509
530
  }
510
531
  catch (error) {
511
- if (error instanceof Preview)
512
- return program;
513
- if (stopEnds && activeSignal?.aborted && (!isCliError(error) || error.code !== "outcome_unknown"))
514
- return program;
515
- throw error;
516
- }
517
- finally {
518
- deadline?.dispose();
532
+ const stopped = stopSignal?.aborted && (!isCliError(error) || error.code !== "outcome_unknown");
533
+ if (!(error instanceof Preview) && !stopped)
534
+ throw error;
535
+ await runs.succeed();
536
+ return program;
519
537
  }
520
538
  };
521
- recordRuns(program, {
522
- app: DRIVE_APP,
523
- agent: options.mcp === true,
524
- profile: selected,
525
- settings: () => {
526
- const defaults = readConfig(env).defaults;
527
- return {
528
- record: defaults?.record,
529
- keepRunsForDays: defaults?.keep_runs_for_days,
530
- keepSuccessfulRunsForDays: defaults?.keep_successful_runs_for_days,
531
- runsSizeLimitMb: defaults?.runs_size_limit_mb,
532
- recordInput: defaults?.record_input,
533
- };
534
- },
535
- env,
536
- streams,
537
- });
538
- // Imported generated children have their own Commander exit/output configuration.
539
- for (const info of flatten(describeDriveProgram(program))) {
540
- let command = program;
541
- for (const part of info.path)
542
- command = command.commands.find((child) => child.name() === part) ?? command;
543
- command.configureHelp({
544
- commandUsage: (target) => {
545
- const usage = new Help().commandUsage(target);
546
- return takesProfile(target) ? usage.replace(/^drive /, "drive <profile> ") : usage;
547
- },
548
- });
549
- command.exitOverride().configureOutput({
550
- writeOut: (text) => streams.data(text.replace(/\n$/, "")),
551
- writeErr: (text) => streams.diagnostic(text.replace(/\n$/, "")),
552
- outputError: () => { },
553
- });
554
- }
555
- installFirstScreen(program);
556
539
  addContractInfo(program, (value) => streams.data(JSON.stringify(value)), {
557
540
  fields: providerJsonFields,
558
- errors: { reasons: CONTRACT_REASONS },
541
+ errors: { reasons: REASONS },
542
+ });
543
+ };
544
+ // cli-core reports a missing OAuth client only by throwing, so a broken one is the owner's own.
545
+ const oauthClient = (env) => {
546
+ application(env);
547
+ return { client: env.DRIVE_GOOGLE_CLIENT_ID ? "own" : "wirecat" };
548
+ };
549
+ const mcpCommand = () => {
550
+ // Read when the server starts: the run's keyring and Google fakes are its, and the availability hook takes no command.
551
+ let availability;
552
+ const mcp = appMcpCommand(DRIVE_APP, configuration, {
553
+ name: "Google Drive",
554
+ untrusted: ["document text", "file names", "comments", "author and editor names", "folder names"],
555
+ permissionExample: "files.trash=deny",
556
+ skill: SKILL,
557
+ availability: (path, profile) => availability?.(path, profile),
558
+ // A profile enters the file only when its sign-in succeeds; the keyring is never opened here.
559
+ signedIn: (profile, env) => {
560
+ try {
561
+ return Object.hasOwn(readConfig(env).profiles, profile);
562
+ }
563
+ catch {
564
+ return false;
565
+ }
566
+ },
567
+ });
568
+ return mcp.hook("preAction", async (root, action) => {
569
+ const environment = environmentOf(action);
570
+ // An injected API never asks Google for a token, so there is no grant to read, as at call time.
571
+ if (environment.api)
572
+ return;
573
+ const { grantAvailability } = await import("./grants.js");
574
+ availability = grantAvailability(rootOf(root), environment.env ?? process.env, environment.keyring);
559
575
  });
560
- assertSharedContracts(program);
561
- return program;
562
576
  };
577
+ export const definition = () => ({
578
+ app: DRIVE_APP,
579
+ configuration,
580
+ firstScreen: FIRST_SCREEN,
581
+ commands: () => [
582
+ appDoctorCommand(DRIVE_APP, configuration, { oauthClient }),
583
+ skillCommand(DRIVE_APP, SKILL),
584
+ mcpCommand(),
585
+ ],
586
+ configure: installDrive,
587
+ onFailure: (error, program) => runsOf.get(program)?.fail(error),
588
+ });
589
+ /** The command tree, for discovery and the contract checks; a command runs through `run`. */
590
+ export const createProgram = () => createSharedProgram(definition());
591
+ export const run = (argv, options = {}) => runShared(argv, definition(), options);
563
592
  //# sourceMappingURL=program.js.map