@wirecat/drive-cli 0.55.0 → 0.57.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 (132) hide show
  1. package/dist/bin/drive.js +2 -2
  2. package/dist/bundle/{all-profiles-I5KJKZPF.js → all-profiles-7LSZ3CC3.js} +9 -9
  3. package/dist/bundle/{anthropic-DPM7BRKX.js → anthropic-3QRM4QXB.js} +5 -5
  4. package/dist/bundle/{app-server-FTGLOZ2K.js → app-server-WWNMUHID.js} +48 -48
  5. package/dist/bundle/{bun-XRO6XJHQ.js → bun-NIIYUR5F.js} +2 -2
  6. package/dist/bundle/{bun-sqlite-7JJX6OUT.js → bun-sqlite-GSLSN3OT.js} +4 -4
  7. package/dist/bundle/{chunk-NPMVPKBD.js → chunk-2QLLKDE5.js} +48 -47
  8. package/dist/bundle/{chunk-P4ABC6C4.js → chunk-2ULJW5BA.js} +2 -2
  9. package/dist/bundle/{chunk-AR2HRFQO.js → chunk-373WJIHE.js} +2 -2
  10. package/dist/bundle/{chunk-K2DMCTTF.js → chunk-3BXSLNWW.js} +129 -97
  11. package/dist/bundle/{chunk-BO7ZKZCH.js → chunk-4F2VRJZE.js} +121 -46
  12. package/dist/bundle/{chunk-NDUYK676.js → chunk-4UQLL6RJ.js} +10 -9
  13. package/dist/bundle/{chunk-NFOUG7ES.js → chunk-566W4Q6L.js} +2 -2
  14. package/dist/bundle/{chunk-E7RDXCV2.js → chunk-5KNIVHP6.js} +5 -5
  15. package/dist/bundle/{chunk-VXZULAWV.js → chunk-64E6QXXQ.js} +14 -13
  16. package/dist/bundle/{chunk-FNDQFFLP.js → chunk-6CFSDU56.js} +11 -11
  17. package/dist/bundle/{chunk-ORRQDSDH.js → chunk-6ZA4NR5H.js} +3 -3
  18. package/dist/bundle/{chunk-PFTIYWOK.js → chunk-7SNS443B.js} +4 -4
  19. package/dist/bundle/{chunk-JPFF6MNK.js → chunk-AHBUTDS7.js} +8 -8
  20. package/dist/bundle/{chunk-TIEEVT2Z.js → chunk-AKPFH3KC.js} +1 -1
  21. package/dist/bundle/{chunk-FDCGTODC.js → chunk-AL7MY7MW.js} +1 -1
  22. package/dist/bundle/{chunk-RMQGFLT2.js → chunk-B3TPS7BW.js} +6 -6
  23. package/dist/bundle/{chunk-2DZMGPUC.js → chunk-B64EY2SC.js} +123 -34
  24. package/dist/bundle/{chunk-2OGANEKA.js → chunk-CD736BG3.js} +2 -2
  25. package/dist/bundle/{chunk-C4QKY33N.js → chunk-CGCQNYB3.js} +2 -2
  26. package/dist/bundle/{chunk-2KARCTUU.js → chunk-EE7R457T.js} +949 -581
  27. package/dist/bundle/{chunk-TQFCPUIM.js → chunk-EFEI724Z.js} +1 -1
  28. package/dist/bundle/{chunk-JBBZCTTF.js → chunk-EFX6FIDM.js} +1 -1
  29. package/dist/bundle/{chunk-DNJ43DT5.js → chunk-ELIYJXIY.js} +2 -2
  30. package/dist/bundle/{chunk-NPKFXGYG.js → chunk-EN7OZ5JH.js} +41 -23
  31. package/dist/bundle/{chunk-IXXVCKWL.js → chunk-G34Y5RAC.js} +26 -26
  32. package/dist/bundle/{chunk-TBD362SJ.js → chunk-GIQFBXQN.js} +11 -7
  33. package/dist/bundle/{chunk-KWKRTYRL.js → chunk-GKHUHRSL.js} +4 -4
  34. package/dist/bundle/{chunk-VGTDXEYD.js → chunk-HNUSPNUQ.js} +26 -13
  35. package/dist/bundle/{chunk-XTNEYXAQ.js → chunk-IJ2S53WJ.js} +5 -5
  36. package/dist/bundle/{chunk-FUKJQZED.js → chunk-ISK4K7UE.js} +1 -1
  37. package/dist/bundle/{chunk-YP5FDMTG.js → chunk-J2HGHSLX.js} +2 -2
  38. package/dist/bundle/{chunk-ULPS2OAL.js → chunk-JIGMCW4C.js} +4 -4
  39. package/dist/bundle/{chunk-ALMQEGYO.js → chunk-JLKNUFL2.js} +2 -2
  40. package/dist/bundle/{chunk-UDWMRZL6.js → chunk-JUKVJ7M2.js} +21 -21
  41. package/dist/bundle/{chunk-LAVWTS4P.js → chunk-KHNDZNQA.js} +5333 -5108
  42. package/dist/bundle/{chunk-GB5YM5HK.js → chunk-KM4Y55ZE.js} +5 -5
  43. package/dist/bundle/{chunk-CP6M5P4X.js → chunk-KYNTSA6K.js} +3 -3
  44. package/dist/bundle/{chunk-4XRLPQ3N.js → chunk-L4BBK7UX.js} +2 -2
  45. package/dist/bundle/chunk-LBFFI6FE.js +247 -0
  46. package/dist/bundle/{chunk-EOEDICIE.js → chunk-LSSIVBQI.js} +1 -1
  47. package/dist/bundle/{chunk-D6SRTPCV.js → chunk-NLLWLCUZ.js} +2 -2
  48. package/dist/bundle/{chunk-6OJMA4ZT.js → chunk-O5KDIVGE.js} +389 -255
  49. package/dist/bundle/{chunk-2LLNPNMB.js → chunk-OOR6PEHV.js} +1 -1
  50. package/dist/bundle/{chunk-UIPT6IAU.js → chunk-OYNSFQ7K.js} +1 -1
  51. package/dist/bundle/{chunk-67A2YFAT.js → chunk-OZJMZSFB.js} +4 -4
  52. package/dist/bundle/{chunk-GC4JNVYF.js → chunk-Q3TMNETS.js} +98 -37
  53. package/dist/bundle/{chunk-5DEEBWDI.js → chunk-QAT6UXZZ.js} +38 -37
  54. package/dist/bundle/{chunk-VY3TYRCK.js → chunk-R5GJZPRF.js} +114 -59
  55. package/dist/bundle/{chunk-4I7EBJJV.js → chunk-RAEKC6TV.js} +6 -6
  56. package/dist/bundle/{chunk-HNR2BJJU.js → chunk-RB674T6L.js} +75 -17
  57. package/dist/bundle/{chunk-NCCL4QWR.js → chunk-SRNXTXJN.js} +3 -3
  58. package/dist/bundle/{chunk-TD4RAOMZ.js → chunk-TKVSJV5P.js} +3 -3
  59. package/dist/bundle/{chunk-W6DMCGMK.js → chunk-TR5656OS.js} +47 -22
  60. package/dist/bundle/{chunk-VY2AUZMJ.js → chunk-TZHCS5MG.js} +2 -2
  61. package/dist/bundle/{chunk-KM7Q67Z3.js → chunk-U2RSVKR5.js} +1 -1
  62. package/dist/bundle/{chunk-IDK5QUBJ.js → chunk-UKMFPBAO.js} +4 -4
  63. package/dist/bundle/{chunk-GIRVMZD3.js → chunk-VTJF2L5E.js} +16 -16
  64. package/dist/bundle/{chunk-AQNY57J2.js → chunk-W5FOPSJZ.js} +7 -7
  65. package/dist/bundle/{chunk-FKHWVVMV.js → chunk-W6FYYQ2J.js} +3 -3
  66. package/dist/bundle/{chunk-VVMCGF5X.js → chunk-WAVJWGUC.js} +1811 -883
  67. package/dist/bundle/{chunk-FDM3JMQZ.js → chunk-WBYCUBYM.js} +89 -36
  68. package/dist/bundle/{chunk-TIVC4DB5.js → chunk-WJOKTIOJ.js} +2 -2
  69. package/dist/bundle/{chunk-7MVKSPEG.js → chunk-WJPVGXKA.js} +6 -6
  70. package/dist/bundle/{chunk-N4VNUOOD.js → chunk-XGNADVIA.js} +18 -18
  71. package/dist/bundle/{chunk-J6XLM4QW.js → chunk-XJVK7ETL.js} +28 -10
  72. package/dist/bundle/{chunk-3K4H2DTA.js → chunk-YZ6SYLDC.js} +12 -3
  73. package/dist/bundle/command-contract-XIACCAZL.js +35 -0
  74. package/dist/bundle/{decode-3LX3BLZM.js → decode-5MHMPYKE.js} +4 -4
  75. package/dist/bundle/drive.js +6 -6
  76. package/dist/bundle/{echarts-YNGCOYHW.js → echarts-CLB22SZS.js} +2 -2
  77. package/dist/bundle/{embed-FICTRZJL.js → embed-TF66ODAR.js} +5 -5
  78. package/dist/bundle/{embedder-DSMRCRSH.js → embedder-EDWOIAC2.js} +8 -8
  79. package/dist/bundle/{entry-4ZX3BNXK.js → entry-CWYCQ53A.js} +8 -6
  80. package/dist/bundle/{first-run-GRBQ3SQ5.js → first-run-YIH7EHJI.js} +9 -9
  81. package/dist/bundle/first-screen-THH3XD5Y.js +33 -0
  82. package/dist/bundle/{google-QV2B2KZA.js → google-A4F2WFO4.js} +9 -9
  83. package/dist/bundle/{google-api-EVO7F3WB.js → google-api-ZXGQOJUI.js} +51 -51
  84. package/dist/bundle/grants-3Z7DG3W3.js +98 -0
  85. package/dist/bundle/{identity-TKAX75OT.js → identity-4IO7WGG4.js} +4 -4
  86. package/dist/bundle/{instructions-GJHHFV64.js → instructions-BXZZNAMS.js} +1 -1
  87. package/dist/bundle/{login-R2YEAKEM.js → login-A4QHJ5DA.js} +57 -57
  88. package/dist/bundle/{mcp-EMNFFY4N.js → mcp-VVMPUDSL.js} +2 -2
  89. package/dist/bundle/{node-GFOH6FKP.js → node-R6ZNQ3NT.js} +2 -2
  90. package/dist/bundle/{node-sqlite-NZIBED3C.js → node-sqlite-AFQTE4XZ.js} +4 -4
  91. package/dist/bundle/{oauth-WUHT2JII.js → oauth-46XBJBML.js} +6 -6
  92. package/dist/bundle/{open-INBNHORD.js → open-WJCRBIP7.js} +3 -3
  93. package/dist/bundle/{openai-BMREUGJP.js → openai-3TIBDWZA.js} +13 -13
  94. package/dist/bundle/{process-XVDX4SPD.js → process-P36JP33R.js} +1 -1
  95. package/dist/bundle/{program-DUWFQOSL.js → program-AHZH65IT.js} +85 -77
  96. package/dist/bundle/{prompt-S7GHCPGR.js → prompt-FFGBIT4A.js} +4 -4
  97. package/dist/bundle/{reasons-T24V3AYS.js → reasons-VHCVYH54.js} +3 -3
  98. package/dist/bundle/{recognize-T3DABMW5.js → recognize-4EAKIMON.js} +3 -3
  99. package/dist/bundle/{remote-ASYGFT6E.js → remote-HX3JP4EH.js} +6 -6
  100. package/dist/bundle/{rerank-BQ5U252K.js → rerank-BW3A4PUU.js} +6 -6
  101. package/dist/bundle/{serve-JMLNKCUZ.js → serve-YYOOLIBS.js} +8 -8
  102. package/dist/bundle/{server-5E6RC7GZ.js → server-G6XTEEFI.js} +38 -38
  103. package/dist/bundle/server-YKYEUIJT.js +63 -0
  104. package/dist/bundle/{services-NFB3XSON.js → services-OAPILZOW.js} +45 -25
  105. package/dist/bundle/{sqlite-runtime-TAMYMQFR.js → sqlite-runtime-GTXDK4PE.js} +4 -4
  106. package/dist/bundle/{state-DS4G3ZXV.js → state-XG335LGZ.js} +5 -5
  107. package/dist/bundle/{store-MLMKYJLC.js → store-7KOXJNQP.js} +14 -12
  108. package/dist/bundle/{store-HAS2LRFE.js → store-N53SJOPS.js} +33 -15
  109. package/dist/bundle/store-maintenance-command-W3TI52X2.js +52 -0
  110. package/dist/bundle/tokens-P7TEHKDD.js +96 -0
  111. package/dist/commands/knowledge.d.ts.map +1 -1
  112. package/dist/commands/knowledge.js +10 -2
  113. package/dist/commands/knowledge.js.map +1 -1
  114. package/dist/config.d.ts +6 -0
  115. package/dist/config.d.ts.map +1 -1
  116. package/dist/config.js +4 -12
  117. package/dist/config.js.map +1 -1
  118. package/dist/profile-lock.js +2 -2
  119. package/dist/profile-lock.js.map +1 -1
  120. package/dist/reasons.js +1 -1
  121. package/dist/reasons.js.map +1 -1
  122. package/dist/version.d.ts +1 -1
  123. package/dist/version.js +1 -1
  124. package/package.json +3 -3
  125. package/dist/bundle/chunk-3NAVOBGH.js +0 -331
  126. package/dist/bundle/command-contract-VXLGE6NV.js +0 -35
  127. package/dist/bundle/first-screen-JK3MZVCU.js +0 -33
  128. package/dist/bundle/grants-B642KK5M.js +0 -98
  129. package/dist/bundle/server-QI4C3CQT.js +0 -63
  130. package/dist/bundle/store-maintenance-command-LI3JR22B.js +0 -52
  131. package/dist/bundle/tokens-UMSAYGOH.js +0 -96
  132. /package/dist/bundle/{chunk-NPGVOZVK.js → chunk-HPXYN7F3.js} +0 -0
@@ -1,43 +1,71 @@
1
1
  import { createRequire as __bundleRequire } from "node:module";
2
2
  const require = __bundleRequire(import.meta.url);
3
3
  import {
4
- activeProfile,
5
- paths
6
- } from "./chunk-3NAVOBGH.js";
4
+ operations,
5
+ privateFiles
6
+ } from "./chunk-EE7R457T.js";
7
7
  import {
8
- READ_SCOPE,
9
- WRITE_SCOPE,
10
- providerRequest
11
- } from "./chunk-2KARCTUU.js";
8
+ DRIVE_APP
9
+ } from "./chunk-NLLWLCUZ.js";
12
10
  import {
13
- googleError
14
- } from "./chunk-TIEEVT2Z.js";
11
+ commandPathKey,
12
+ commandPermissions
13
+ } from "./chunk-B64EY2SC.js";
15
14
  import {
16
15
  acquireLock
17
- } from "./chunk-VGTDXEYD.js";
16
+ } from "./chunk-HNUSPNUQ.js";
17
+ import {
18
+ AI_ENTRIES,
19
+ checkConfigText,
20
+ issueMessage,
21
+ settingsFor,
22
+ usableProfileName
23
+ } from "./chunk-4F2VRJZE.js";
24
+ import {
25
+ LEVELS
26
+ } from "./chunk-TR5656OS.js";
27
+ import {
28
+ MAX_TEXT_CHARS
29
+ } from "./chunk-373WJIHE.js";
18
30
  import {
19
31
  Credentials,
20
32
  isMovedRun,
21
33
  keyringService,
34
+ resolvePaths,
35
+ saveConfigFile,
22
36
  systemKeyring
23
- } from "./chunk-N4VNUOOD.js";
37
+ } from "./chunk-XGNADVIA.js";
24
38
  import {
25
39
  CliError,
40
+ array,
41
+ boolean,
42
+ integer,
26
43
  isCliError,
44
+ literal,
45
+ maxValue,
27
46
  minLength,
28
- nullable,
47
+ minValue,
29
48
  number,
30
- object,
31
49
  optional,
50
+ parse,
51
+ picklist,
32
52
  pipe,
33
- safeParse,
34
- string
35
- } from "./chunk-TBD362SJ.js";
53
+ record,
54
+ regex,
55
+ strictObject,
56
+ string,
57
+ union
58
+ } from "./chunk-GIQFBXQN.js";
36
59
  import {
37
60
  __name
38
61
  } from "./chunk-ZVVMGPBJ.js";
39
62
 
40
- // node_modules/.pnpm/@wirecat+cli-core@0.507.0_@wirecat+cli-base@0.68.1_commander@15.0.0_esbuild@0.28.2_type_d5beb0101c7a90701cc33879a5be8d28/node_modules/@wirecat/cli-core/dist/oauth/authorize.js
63
+ // node_modules/.pnpm/@wirecat+cli-core@0.546.0_@wirecat+cli-base@0.73.0_commander@15.0.0_esbuild@0.28.2_type_6245070bff0a7c29971e74a96fde145c/node_modules/@wirecat/cli-core/dist/oauth/keeper.js
64
+ import { createHash as createHash2 } from "node:crypto";
65
+ import { join } from "node:path";
66
+ import { setTimeout as delay } from "node:timers/promises";
67
+
68
+ // node_modules/.pnpm/@wirecat+cli-core@0.546.0_@wirecat+cli-base@0.73.0_commander@15.0.0_esbuild@0.28.2_type_6245070bff0a7c29971e74a96fde145c/node_modules/@wirecat/cli-core/dist/oauth/authorize.js
41
69
  import { createHash, randomBytes } from "node:crypto";
42
70
  import { createServer } from "node:http";
43
71
  var DEFAULT_TIMEOUT_MS = 3e5;
@@ -82,7 +110,7 @@ var authorize = /* @__PURE__ */ __name(async (options) => {
82
110
  else
83
111
  fail(new CliError("authentication_error", `${provider.name} sign-in was declined`, { reason: "oauth.declined" }));
84
112
  }, "settle");
85
- const server = createServer((request, response) => {
113
+ const handler = /* @__PURE__ */ __name((request, response) => {
86
114
  let url;
87
115
  try {
88
116
  url = new URL(request.url ?? "/", "http://127.0.0.1");
@@ -104,7 +132,10 @@ var authorize = /* @__PURE__ */ __name(async (options) => {
104
132
  }
105
133
  response.end("Sign-in received; you can close this tab");
106
134
  settle(url.searchParams);
107
- });
135
+ }, "handler");
136
+ const server = createServer(handler);
137
+ const localhost = provider.redirect.kind === "loopback" && provider.redirect.host === "localhost";
138
+ const server6 = localhost ? createServer(handler) : void 0;
108
139
  const onAbort = /* @__PURE__ */ __name(() => fail(cancelled()), "onAbort");
109
140
  options.signal?.addEventListener("abort", onAbort, { once: true });
110
141
  const timer = setTimeout(() => fail(new CliError("timeout", `${provider.name} sign-in timed out`, { reason: "oauth.timeout" })), options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
@@ -116,10 +147,18 @@ var authorize = /* @__PURE__ */ __name(async (options) => {
116
147
  const address = server.address();
117
148
  if (!address || typeof address === "string")
118
149
  throw new CliError("configuration_error", "could not start the local sign-in listener");
150
+ if (server6) {
151
+ server6.on("error", () => {
152
+ });
153
+ await new Promise((resolve) => {
154
+ server6.once("error", () => resolve());
155
+ server6.listen(address.port, "::1", () => resolve());
156
+ });
157
+ }
119
158
  const random = randomBytes(32).toString("base64url");
120
159
  const relay = provider.redirect.kind === "relay";
121
160
  state = relay ? `${address.port}.${random}` : random;
122
- const redirectUri = provider.redirect.kind === "relay" ? provider.redirect.url : `http://127.0.0.1:${address.port}/callback`;
161
+ const redirectUri = provider.redirect.kind === "relay" ? provider.redirect.url : `http://${localhost ? "localhost" : "127.0.0.1"}:${address.port}/callback`;
123
162
  const url = new URL(provider.authorizeUrl);
124
163
  for (const [key, value] of Object.entries({
125
164
  ...provider.authorizeParams,
@@ -154,20 +193,18 @@ var authorize = /* @__PURE__ */ __name(async (options) => {
154
193
  clearTimeout(timer);
155
194
  options.signal?.removeEventListener("abort", onAbort);
156
195
  paste.abort();
157
- server.closeAllConnections();
158
- await new Promise((resolve) => server.close(() => resolve()));
196
+ for (const each of server6 ? [server, server6] : [server]) {
197
+ each.closeAllConnections();
198
+ if (each.listening)
199
+ await new Promise((resolve) => each.close(() => resolve()));
200
+ }
159
201
  }
160
202
  }, "authorize");
161
203
 
162
- // node_modules/.pnpm/@wirecat+cli-core@0.507.0_@wirecat+cli-base@0.68.1_commander@15.0.0_esbuild@0.28.2_type_d5beb0101c7a90701cc33879a5be8d28/node_modules/@wirecat/cli-core/dist/oauth/keeper.js
163
- import { createHash as createHash2 } from "node:crypto";
164
- import { join } from "node:path";
165
- import { setTimeout as delay } from "node:timers/promises";
166
-
167
- // node_modules/.pnpm/@wirecat+cli-core@0.507.0_@wirecat+cli-base@0.68.1_commander@15.0.0_esbuild@0.28.2_type_d5beb0101c7a90701cc33879a5be8d28/node_modules/@wirecat/cli-core/dist/oauth/requests.js
204
+ // node_modules/.pnpm/@wirecat+cli-core@0.546.0_@wirecat+cli-base@0.73.0_commander@15.0.0_esbuild@0.28.2_type_6245070bff0a7c29971e74a96fde145c/node_modules/@wirecat/cli-core/dist/oauth/requests.js
168
205
  var REQUEST_LIMIT_MS = 3e4;
169
206
  var TOKEN_LOG_EVENT = "oauth.token";
170
- var object2 = /* @__PURE__ */ __name((value) => {
207
+ var object = /* @__PURE__ */ __name((value) => {
171
208
  if (typeof value !== "object" || value === null || Array.isArray(value))
172
209
  throw new Error("not an object");
173
210
  return value;
@@ -199,17 +236,17 @@ var clientFields = /* @__PURE__ */ __name(({ client }) => ({
199
236
  }), "clientFields");
200
237
  var requestTokens = /* @__PURE__ */ __name(async (provider, params, context) => {
201
238
  const operation = params.grant_type ?? "unknown";
202
- const record = /* @__PURE__ */ __name((level, fields) => context.log?.[level]({ event: TOKEN_LOG_EVENT, provider: provider.id, operation, pid: process.pid, ...fields }), "record");
239
+ const record2 = /* @__PURE__ */ __name((level, fields) => context.log?.[level]({ event: TOKEN_LOG_EVENT, provider: provider.id, operation, pid: process.pid, ...fields }), "record");
203
240
  const again = `run ${context.signInCommand} again`;
204
241
  const response = await post(provider.tokenUrl, new URLSearchParams({ ...params, ...clientFields(context) }), context);
205
242
  if (!response) {
206
- record("warn", { outcome: "no_response" });
243
+ record2("warn", { outcome: "no_response" });
207
244
  throw new CliError("outcome_unknown", `${provider.name} token request did not finish; ${again} if it keeps failing`, {
208
245
  reason: "oauth.no-response"
209
246
  });
210
247
  }
211
248
  if (!response.ok) {
212
- record("warn", { outcome: "rejected", status: response.status });
249
+ record2("warn", { outcome: "rejected", status: response.status });
213
250
  if (response.status === 429 || response.status >= 500)
214
251
  throw new CliError("provider_unavailable", `${provider.name} token request failed (HTTP ${response.status})`, {
215
252
  status: response.status,
@@ -223,9 +260,9 @@ var requestTokens = /* @__PURE__ */ __name(async (provider, params, context) =>
223
260
  }
224
261
  let body;
225
262
  try {
226
- body = object2(await response.json());
263
+ body = object(await response.json());
227
264
  } catch {
228
- record("error", { outcome: "unreadable_response", status: response.status });
265
+ record2("error", { outcome: "unreadable_response", status: response.status });
229
266
  throw new CliError("invalid_response", `${provider.name} returned an unreadable token response; ${again}`, {
230
267
  reason: "oauth.invalid-response"
231
268
  });
@@ -234,20 +271,20 @@ var requestTokens = /* @__PURE__ */ __name(async (provider, params, context) =>
234
271
  const refreshToken = typeof body.refresh_token === "string" && body.refresh_token ? body.refresh_token : previous?.refreshToken;
235
272
  const expiresIn = body.expires_in;
236
273
  if (typeof body.access_token !== "string" || !body.access_token || expiresIn !== void 0 && (typeof expiresIn !== "number" || !Number.isFinite(expiresIn) || expiresIn <= 0) || body.scope !== void 0 && typeof body.scope !== "string" || body.token_type !== void 0 && typeof body.token_type !== "string") {
237
- record("error", { outcome: "invalid_response", status: response.status });
274
+ record2("error", { outcome: "invalid_response", status: response.status });
238
275
  throw new CliError("invalid_response", `${provider.name} returned an invalid token response; ${again}`, {
239
276
  reason: "oauth.invalid-response"
240
277
  });
241
278
  }
242
279
  if (!refreshToken) {
243
- record("error", { outcome: "no_refresh_token", status: response.status });
280
+ record2("error", { outcome: "no_refresh_token", status: response.status });
244
281
  throw new CliError("authentication_error", `${provider.name} returned no offline refresh token; ${again}`, {
245
282
  reason: "oauth.failed"
246
283
  });
247
284
  }
248
285
  const scopes = typeof body.scope === "string" ? body.scope.split(/\s+/).filter(Boolean) : previous?.scopes ?? [];
249
286
  const tokenType = typeof body.token_type === "string" ? body.token_type : previous?.tokenType;
250
- record("info", {
287
+ record2("info", {
251
288
  outcome: "received",
252
289
  status: response.status,
253
290
  ...previous ? { rotated: refreshToken !== previous.refreshToken } : {}
@@ -281,7 +318,7 @@ var revokeToken = /* @__PURE__ */ __name(async (provider, tokens, context) => {
281
318
  });
282
319
  }, "revokeToken");
283
320
 
284
- // node_modules/.pnpm/@wirecat+cli-core@0.507.0_@wirecat+cli-base@0.68.1_commander@15.0.0_esbuild@0.28.2_type_d5beb0101c7a90701cc33879a5be8d28/node_modules/@wirecat/cli-core/dist/oauth/keeper.js
321
+ // node_modules/.pnpm/@wirecat+cli-core@0.546.0_@wirecat+cli-base@0.73.0_commander@15.0.0_esbuild@0.28.2_type_6245070bff0a7c29971e74a96fde145c/node_modules/@wirecat/cli-core/dist/oauth/keeper.js
285
322
  var inFlight = /* @__PURE__ */ new Map();
286
323
  var refreshedInMemory = /* @__PURE__ */ new Map();
287
324
  var tokenKeeper = /* @__PURE__ */ __name((options) => {
@@ -361,24 +398,37 @@ var tokenKeeper = /* @__PURE__ */ __name((options) => {
361
398
  return kept && fresh(kept) && kept.refreshToken === saved.refreshToken ? kept : void 0;
362
399
  }, "remembered");
363
400
  const forget = /* @__PURE__ */ __name(() => refreshedInMemory.delete(lockPath), "forget");
364
- const tokens = /* @__PURE__ */ __name(async () => {
401
+ let answered;
402
+ const answer = /* @__PURE__ */ __name((given) => {
403
+ answered = given;
404
+ return given;
405
+ }, "answer");
406
+ const tokens = /* @__PURE__ */ __name(async ({ refresh = false } = {}) => {
365
407
  const seen = storage.read();
366
408
  if (!seen)
367
409
  throw notSignedIn();
368
- if (fresh(seen.tokens))
369
- return seen.tokens;
370
- const kept = remembered(seen.tokens);
371
- if (kept)
372
- return kept;
373
- return shared(async () => {
410
+ if (!refresh) {
411
+ const kept = remembered(seen.tokens);
412
+ if (kept)
413
+ return answer(kept);
414
+ if (fresh(seen.tokens))
415
+ return answer(seen.tokens);
416
+ }
417
+ const refused = answered ?? remembered(seen.tokens) ?? seen.tokens;
418
+ return answer(await shared(async () => {
374
419
  const current = storage.read();
375
420
  if (!current)
376
421
  throw notSignedIn();
377
- if (fresh(current.tokens) || current.tokens.refreshToken !== seen.tokens.refreshToken)
378
- return current.tokens;
379
- const keptMeanwhile = remembered(current.tokens);
380
- if (keptMeanwhile)
381
- return keptMeanwhile;
422
+ const latest = remembered(current.tokens) ?? current.tokens;
423
+ if (refresh) {
424
+ if (latest.accessToken !== refused.accessToken && fresh(latest))
425
+ return latest;
426
+ } else {
427
+ if (latest !== current.tokens)
428
+ return latest;
429
+ if (fresh(current.tokens) || current.tokens.refreshToken !== seen.tokens.refreshToken)
430
+ return current.tokens;
431
+ }
382
432
  const client = clientOf(current);
383
433
  const refreshed = await exchange({ grant_type: "refresh_token", refresh_token: current.tokens.refreshToken }, context(client, current.tokens));
384
434
  if (storage.moved && refreshed.refreshToken === current.tokens.refreshToken)
@@ -386,12 +436,12 @@ var tokenKeeper = /* @__PURE__ */ __name((options) => {
386
436
  else
387
437
  storage.write({ tokens: refreshed, client });
388
438
  return refreshed;
389
- });
439
+ }));
390
440
  }, "tokens");
391
441
  return {
392
442
  tokens,
393
- accessToken: /* @__PURE__ */ __name(async () => {
394
- const current = await tokens();
443
+ accessToken: /* @__PURE__ */ __name(async (tokensOptions) => {
444
+ const current = await tokens(tokensOptions);
395
445
  if (!current.accessToken)
396
446
  throw notSignedIn();
397
447
  return current.accessToken;
@@ -430,9 +480,9 @@ var tokenKeeper = /* @__PURE__ */ __name((options) => {
430
480
  };
431
481
  }, "tokenKeeper");
432
482
 
433
- // node_modules/.pnpm/@wirecat+cli-core@0.507.0_@wirecat+cli-base@0.68.1_commander@15.0.0_esbuild@0.28.2_type_d5beb0101c7a90701cc33879a5be8d28/node_modules/@wirecat/cli-core/dist/oauth/storage.js
483
+ // node_modules/.pnpm/@wirecat+cli-core@0.546.0_@wirecat+cli-base@0.73.0_commander@15.0.0_esbuild@0.28.2_type_6245070bff0a7c29971e74a96fde145c/node_modules/@wirecat/cli-core/dist/oauth/storage.js
434
484
  var invalid = /* @__PURE__ */ __name(() => new CliError("authentication_error", "the saved sign-in cannot be read; sign in again", { reason: "oauth.invalid" }), "invalid");
435
- var parse = /* @__PURE__ */ __name((raw) => {
485
+ var parse2 = /* @__PURE__ */ __name((raw) => {
436
486
  let value;
437
487
  try {
438
488
  value = JSON.parse(raw);
@@ -449,7 +499,7 @@ var previousOf = /* @__PURE__ */ __name((raw) => {
449
499
  if (raw === void 0)
450
500
  return {};
451
501
  try {
452
- return parse(raw);
502
+ return parse2(raw);
453
503
  } catch {
454
504
  return {};
455
505
  }
@@ -457,7 +507,7 @@ var previousOf = /* @__PURE__ */ __name((raw) => {
457
507
  var defined = /* @__PURE__ */ __name((value) => Object.fromEntries(Object.entries(value).filter(([, field]) => field !== void 0)), "defined");
458
508
  var driveSessionCodec = {
459
509
  decode: /* @__PURE__ */ __name((raw) => {
460
- const value = parse(raw);
510
+ const value = parse2(raw);
461
511
  const tokens = value.tokens;
462
512
  if (typeof tokens !== "object" || tokens === null || Array.isArray(tokens))
463
513
  throw invalid();
@@ -508,20 +558,20 @@ var keyringFailure = /* @__PURE__ */ __name((thrown, secret) => {
508
558
  var credentialStorage = /* @__PURE__ */ __name((options) => {
509
559
  if (!options.credentials.keyring)
510
560
  throw new CliError("configuration_error", "a sign-in store needs its keyring passed in, never a default");
511
- const credentials2 = new Credentials(options.credentials);
561
+ const credentials = new Credentials(options.credentials);
512
562
  const { account, codec } = options;
513
563
  const moved = options.credentials.isolated === true || options.credentials.keyring === systemKeyring && isMovedRun({ appName: options.credentials.service, env: options.credentials.env ?? process.env });
514
564
  const service = keyringService(options.credentials.service, options.credentials.configDir, options.credentials.isolated);
515
565
  const raw = /* @__PURE__ */ __name((name) => {
516
566
  try {
517
- return credentials2.read(name)?.secret;
567
+ return credentials.read(name)?.secret;
518
568
  } catch (error) {
519
569
  throw keyringFailure(error);
520
570
  }
521
571
  }, "raw");
522
572
  const save = /* @__PURE__ */ __name((value, writeOptions) => {
523
573
  try {
524
- credentials2.write(account, value, writeOptions);
574
+ credentials.write(account, value, writeOptions);
525
575
  } catch (error) {
526
576
  throw keyringFailure(error, value);
527
577
  }
@@ -554,7 +604,7 @@ var credentialStorage = /* @__PURE__ */ __name((options) => {
554
604
  write: /* @__PURE__ */ __name((input, writeOptions) => save(codec.encode({ ...input, previous: raw(account) }), writeOptions), "write"),
555
605
  remove: /* @__PURE__ */ __name(() => {
556
606
  try {
557
- return credentials2.remove(account);
607
+ return credentials.remove(account);
558
608
  } catch (error) {
559
609
  throw keyringFailure(error);
560
610
  }
@@ -562,212 +612,296 @@ var credentialStorage = /* @__PURE__ */ __name((options) => {
562
612
  };
563
613
  }, "credentialStorage");
564
614
 
565
- // dist/tokens.js
566
- import { OAuth2Client } from "google-auth-library";
567
- var Session = object({
568
- principal: string(),
569
- clientId: string(),
570
- clientSecret: optional(string()),
571
- tokens: object({
572
- access_token: optional(nullable(string())),
573
- refresh_token: pipe(string(), minLength(1)),
574
- expiry_date: optional(nullable(number())),
575
- scope: optional(string()),
576
- token_type: optional(nullable(string()))
577
- })
578
- });
579
- var credentialOptions = /* @__PURE__ */ __name((env, storage, keyring) => ({
580
- configDir: paths(env).config,
581
- service: "drive-cli",
582
- // The keyring falls back to the private file by itself (WC-SECR-4); `file` skips the keyring.
583
- storage: storage === "keyring" ? "auto" : storage,
584
- env,
585
- isolated: isMovedRun({ appName: "drive-cli", prefix: "DRIVE", env }),
586
- ...keyring ? { keyring } : {}
587
- }), "credentialOptions");
588
- var credentials = /* @__PURE__ */ __name((env, storage, keyring) => new Credentials(credentialOptions(env, storage, keyring)), "credentials");
589
- var notSaved = /* @__PURE__ */ __name(() => new CliError("configuration_error", "could not save Google sign-in: the private credentials file cannot be read; move it aside and sign in again", { reason: "sign-in.not-saved" }), "notSaved");
590
- var saveSession = /* @__PURE__ */ __name((env, name, session, storage, keyring) => {
591
- try {
592
- credentials(env, storage, keyring).write(name, JSON.stringify(session));
593
- } catch {
594
- throw notSaved();
615
+ // node_modules/.pnpm/@wirecat+cli-core@0.546.0_@wirecat+cli-base@0.73.0_commander@15.0.0_esbuild@0.28.2_type_6245070bff0a7c29971e74a96fde145c/node_modules/@wirecat/cli-core/dist/oauth/client-file.js
616
+ import { readFileSync } from "node:fs";
617
+ var readClientFile = /* @__PURE__ */ __name((location, options = {}) => {
618
+ if (!options.shipped && typeof location === "string") {
619
+ const mode = privateFiles({ files: [location], dirs: [] }, options.platform);
620
+ if (mode.checked && !mode.ok)
621
+ throw new CliError("configuration_error", `the client file can be read by other users of this computer; run chmod 600 ${location} and try again`, { reason: "sign-in.client-file-open" });
595
622
  }
596
- }, "saveSession");
597
- var googleProvider = /* @__PURE__ */ __name((client) => ({
598
- id: "google",
599
- name: "Google",
600
- authorizeUrl: "https://accounts.google.com/o/oauth2/v2/auth",
601
- tokenUrl: "https://oauth2.googleapis.com/token",
602
- revokeUrl: "https://oauth2.googleapis.com/revoke",
603
- client,
604
- redirect: { kind: "loopback" },
605
- // Without offline access Google returns no refresh token; without consent it does not return one again.
606
- authorizeParams: { access_type: "offline", prompt: "select_account consent" }
607
- }), "googleProvider");
608
- var sessionKeeper = /* @__PURE__ */ __name((options) => tokenKeeper({
609
- provider: googleProvider(options.client),
610
- storage: credentialStorage({
611
- credentials: { ...credentialOptions(options.env, options.storage), keyring: options.keyring ?? systemKeyring },
612
- account: options.name,
613
- codec: driveSessionCodec
614
- }),
615
- lockDir: paths(options.env).config,
616
- fetch: options.fetch ?? globalThis.fetch,
617
- signInCommand: `drive ${options.name} session start`,
618
- // Above the client's own 5-minute early refresh, so a token it asks to replace is replaced.
619
- freshForMs: 6 * 6e4,
620
- ...options.signal ? { signal: options.signal } : {}
621
- }), "sessionKeeper");
622
- var authorizedClient = /* @__PURE__ */ __name((env, name, keyring, signal) => {
623
- const profile = activeProfile(env, name);
624
- let parsed;
625
623
  try {
626
- const secret = credentials(env, profile.storage, keyring).read(name)?.secret;
627
- if (!secret)
628
- throw new Error("missing login");
629
- parsed = safeParse(Session, JSON.parse(secret));
624
+ const { installed } = JSON.parse(readFileSync(location, "utf8"));
625
+ const { client_id: clientId, client_secret: clientSecret } = installed;
626
+ if (typeof clientId !== "string" || !clientId)
627
+ throw new TypeError("client_id");
628
+ if (clientSecret !== void 0 && typeof clientSecret !== "string")
629
+ throw new TypeError("client_secret");
630
+ return { clientId, ...clientSecret ? { clientSecret } : {} };
630
631
  } catch {
631
- throw new CliError("authentication_error", `could not load Google sign-in \u2014 run drive ${name} session start again`, {
632
- reason: "sign-in.expired"
633
- });
632
+ throw options.invalid ?? new CliError("configuration_error", "could not read a Desktop app OAuth client JSON from the client file; its contents were not logged", { reason: "sign-in.client-file-invalid" });
634
633
  }
635
- if (!parsed.success || parsed.output.principal !== profile.principal)
636
- throw new CliError("authentication_error", "saved sign-in is invalid or belongs to another account", {
637
- reason: "sign-in.expired"
638
- });
639
- const session = parsed.output;
640
- const keeper = sessionKeeper({
641
- env,
642
- name,
643
- storage: profile.storage,
644
- client: { clientId: session.clientId, ...session.clientSecret ? { clientSecret: session.clientSecret } : {} },
645
- ...keyring ? { keyring } : {},
646
- ...signal ? { signal } : {}
647
- });
648
- const client = new OAuth2Client({
649
- clientId: session.clientId,
650
- clientSecret: session.clientSecret,
651
- transporterOptions: { timeout: 3e4, ...signal ? { signal } : {} }
652
- });
653
- client.refreshHandler = async () => {
654
- try {
655
- const tokens = await keeper.tokens();
656
- if (!tokens.accessToken || tokens.expiresAt === void 0)
657
- throw new Error("no access token");
658
- return { access_token: tokens.accessToken, expiry_date: tokens.expiresAt };
659
- } catch (error) {
660
- if (isCliError(error) && error.code !== "authentication_error")
661
- throw error;
662
- throw new CliError("authentication_error", `Google sign-in expired \u2014 run drive ${name} session start again`, {
663
- reason: "sign-in.expired"
664
- });
634
+ }, "readClientFile");
635
+
636
+ // dist/policy-keys.js
637
+ var permissionKeys = /* @__PURE__ */ __name((paths2) => {
638
+ const keys = /* @__PURE__ */ new Set([
639
+ "mcp.authority",
640
+ "mcp",
641
+ "sheets.create",
642
+ "sheets.rename",
643
+ "sheets.insert",
644
+ "sheets.format",
645
+ "sheets.update"
646
+ ]);
647
+ for (const path of paths2)
648
+ keys.add(path.join("."));
649
+ for (const operation of operations)
650
+ for (const key of methodPolicyKeys(operation.id))
651
+ keys.add(key);
652
+ return keys;
653
+ }, "permissionKeys");
654
+ var permissionNames = /* @__PURE__ */ __name((keys) => {
655
+ const names = /* @__PURE__ */ new Set();
656
+ for (const key of keys) {
657
+ const parts = key.split(".");
658
+ for (let end = 1; end <= parts.length; end++)
659
+ names.add(parts.slice(0, end).join("."));
660
+ }
661
+ return names;
662
+ }, "permissionNames");
663
+ var DEFAULT_LEVELS = {
664
+ "mcp.authority": "deny",
665
+ ...Object.fromEntries(operations.filter((op) => op.effect === "destructive").map((op) => [`api.${op.id}`, "ask"]))
666
+ };
667
+ var methodPolicyKeys = /* @__PURE__ */ __name((method, body) => {
668
+ const parts = method.split(".");
669
+ const verb = parts.at(-1);
670
+ const alias = method.startsWith("drive.files.") ? `files.${verb}` : method.startsWith("docs.documents.") ? `documents.${verb === "batchUpdate" ? "update" : verb}` : method.startsWith("sheets.spreadsheets.") ? `sheets.${method === "sheets.spreadsheets.get" ? "info" : method === "sheets.spreadsheets.values.get" ? "show" : verb === "append" ? "add" : verb}` : method === "driveactivity.activity.query" ? "documents.history" : method.startsWith("drive.") ? `${parts[1]}.${verb}` : void 0;
671
+ const keys = [`api.${method}`, ...alias ? [alias] : []];
672
+ if (method === "drive.replies.create" && body)
673
+ keys.push(body.action === "resolve" ? "comments.resolve" : body.action === "reopen" ? "comments.reopen" : "comments.reply");
674
+ if (method === "drive.replies.create" && body?.content !== void 0)
675
+ keys.push("comments.reply");
676
+ if (method === "sheets.spreadsheets.batchUpdate" && Array.isArray(body?.requests)) {
677
+ const object2 = /* @__PURE__ */ __name((value) => !!value && typeof value === "object" && !Array.isArray(value), "object");
678
+ for (const request of body.requests) {
679
+ if (!object2(request))
680
+ continue;
681
+ if (request.addSheet || request.duplicateSheet)
682
+ keys.push("sheets.create");
683
+ if (object2(request.updateSheetProperties)) {
684
+ const update = request.updateSheetProperties;
685
+ if (object2(update.properties) && update.properties.title !== void 0 || String(update.fields).split(",").some((field) => field.trim() === "title" || field.trim() === "*"))
686
+ keys.push("sheets.rename");
687
+ if (object2(update.properties) && update.properties.gridProperties)
688
+ keys.push("sheets.insert");
689
+ }
690
+ if (request.insertDimension || request.appendDimension || request.insertRange)
691
+ keys.push("sheets.insert");
692
+ if (request.repeatCell || request.updateCells || request.appendCells || request.updateBorders || request.addConditionalFormatRule || request.updateConditionalFormatRule || request.deleteConditionalFormatRule || request.addBanding || request.updateBanding || request.deleteBanding)
693
+ keys.push("sheets.format");
694
+ if (request.updateCells || request.appendCells || request.findReplace || request.pasteData || request.copyPaste || request.cutPaste || request.autoFill)
695
+ keys.push("sheets.update");
696
+ if (request.pasteData || request.copyPaste || request.cutPaste || request.autoFill)
697
+ keys.push("sheets.format");
698
+ if (object2(request.repeatCell) && (String(request.repeatCell.fields).split(",").some((field) => field.trim() === "*" || field.includes("userEnteredValue")) || object2(request.repeatCell.cell) && request.repeatCell.cell.userEnteredValue !== void 0))
699
+ keys.push("sheets.update");
665
700
  }
701
+ }
702
+ return [...new Set(keys)];
703
+ }, "methodPolicyKeys");
704
+
705
+ // dist/config.js
706
+ import { readFileSync as readFileSync2 } from "node:fs";
707
+ import { join as join2 } from "node:path";
708
+
709
+ // dist/oauth-application.js
710
+ var WIRECAT_APPLICATION = Object.freeze({
711
+ clientId: "240274586781-vssrlm9c0l3n1ti12ce7tg95ro4bghal.apps.googleusercontent.com",
712
+ // biome-ignore lint/security/noSecrets: public installed-app OAuth identity, non-confidential per Google native-app guidance
713
+ clientSecret: "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"
714
+ // gitleaks:allow -- public installed-app identity
715
+ });
716
+
717
+ // dist/config.js
718
+ var Common = {
719
+ ...AI_ENTRIES,
720
+ permissions: optional(record(string(), picklist(LEVELS))),
721
+ max_text_chars: optional(pipe(number(), integer(), minValue(1), maxValue(MAX_TEXT_CHARS)))
722
+ };
723
+ var RunSettings = {
724
+ record: optional(boolean()),
725
+ keep_runs_for_days: optional(pipe(number(), integer(), minValue(1))),
726
+ keep_successful_runs_for_days: optional(pipe(number(), integer(), minValue(1))),
727
+ runs_size_limit_mb: optional(pipe(number(), integer(), minValue(1))),
728
+ record_input: optional(union([boolean(), literal("failed")]))
729
+ };
730
+ var SharedDefaults = {
731
+ limit: optional(pipe(number(), integer(), minValue(1))),
732
+ sends_per_hour: optional(pipe(number(), integer(), minValue(0))),
733
+ update_check: optional(boolean()),
734
+ skill_hint: optional(boolean())
735
+ };
736
+ var DEFAULTS_ONLY = /* @__PURE__ */ new Set([...Object.keys(RunSettings), "update_check", "skill_hint"]);
737
+ var SETTING_NAMES = /* @__PURE__ */ new Set([...Object.keys(Common), "picture_search", ...DEFAULTS_ONLY]);
738
+ var Mirror = strictObject({
739
+ id: pipe(string(), regex(/^[a-z0-9-]{1,40}$/)),
740
+ path: pipe(string(), minLength(1)),
741
+ folder: pipe(string(), regex(/^[A-Za-z0-9_-]{1,200}$/))
742
+ });
743
+ var Profile = strictObject({
744
+ principal: string(),
745
+ roots: optional(array(pipe(string(), regex(/^[A-Za-z0-9_-]{1,200}$/))), []),
746
+ mirrors: optional(array(Mirror)),
747
+ storage: picklist(["keyring", "file"]),
748
+ picture_search: optional(boolean()),
749
+ ...Common
750
+ });
751
+ var ConfigSchema = strictObject({
752
+ profiles: optional(record(string(), Profile), {}),
753
+ defaults: optional(strictObject({ ...Common, ...RunSettings, ...SharedDefaults }))
754
+ });
755
+ var keyOf = /* @__PURE__ */ __name((path) => {
756
+ if (path[0] !== "api" || path[1] === void 0)
757
+ return commandPathKey(path);
758
+ if (["call", "list", "show"].includes(path[1]))
759
+ return null;
760
+ const operation = operations.find((one) => one.command === path[1]);
761
+ return operation ? `api.${operation.id}` : commandPathKey(path);
762
+ }, "keyOf");
763
+ var configuration = settingsFor(DRIVE_APP, {
764
+ // drive's own schema decides what the file may hold, so `doctor` names a profile that lacks its principal.
765
+ schema: ConfigSchema,
766
+ profile: {
767
+ principal: optional(string()),
768
+ roots: optional(array(pipe(string(), regex(/^[A-Za-z0-9_-]{1,200}$/)))),
769
+ mirrors: optional(array(Mirror)),
770
+ storage: optional(picklist(["keyring", "file"])),
771
+ max_text_chars: Common.max_text_chars
772
+ },
773
+ permissions: commandPermissions({ keyOf, extra: [...permissionKeys([])], defaults: DEFAULT_LEVELS })
774
+ });
775
+ var paths = /* @__PURE__ */ __name((env) => resolvePaths({ appName: "drive-cli", prefix: "DRIVE", env }), "paths");
776
+ var configPath = /* @__PURE__ */ __name((env) => join2(paths(env).config, "config.json"), "configPath");
777
+ var TOOL = "drive";
778
+ var isNode = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isNode");
779
+ var withoutIncomplete = /* @__PURE__ */ __name((raw, issues) => {
780
+ const incomplete = new Set(issues.flatMap((issue) => issue.kind === "missing_setting" && issue.profile ? [issue.profile] : []));
781
+ if (!incomplete.size || !isNode(raw) || !isNode(raw.profiles))
782
+ return void 0;
783
+ return {
784
+ ...raw,
785
+ profiles: Object.fromEntries(Object.entries(raw.profiles).filter(([name]) => !incomplete.has(name)))
786
+ };
787
+ }, "withoutIncomplete");
788
+ var examine = /* @__PURE__ */ __name((text2, file, knownPermissions) => {
789
+ const check = /* @__PURE__ */ __name((body) => checkConfigText(body, { file, tool: TOOL, schema: ConfigSchema, ...knownPermissions ? { knownPermissions } : {} }), "check");
790
+ const first = check(text2);
791
+ if (first.issues.some((issue) => issue.kind === "invalid_json"))
792
+ return { raw: {}, config: { profiles: {} }, issues: first.issues };
793
+ const raw = JSON.parse(text2);
794
+ if (first.config)
795
+ return { raw, config: first.config, issues: first.issues };
796
+ const rest = withoutIncomplete(raw, first.issues);
797
+ const second = rest && check(JSON.stringify(rest));
798
+ return {
799
+ raw,
800
+ config: second?.config ?? { profiles: {} },
801
+ // Saved permissions are checked only in what loads, and the first pass loaded nothing.
802
+ issues: [...first.issues, ...(second?.issues ?? []).filter((issue) => issue.kind === "unknown_permission")]
666
803
  };
667
- const { refresh_token: _refresh, ...current } = session.tokens;
668
- client.setCredentials(current);
669
- return observeRequests(client);
670
- }, "authorizedClient");
671
- var covers = /* @__PURE__ */ __name((granted, required) => granted.includes(required) || required === READ_SCOPE && granted.includes(WRITE_SCOPE), "covers");
672
- var grantedScopes = /* @__PURE__ */ __name((env, name, keyring) => {
804
+ }, "examine");
805
+ var inspectConfig = /* @__PURE__ */ __name((env, knownPermissions) => {
806
+ const path = configPath(env);
807
+ let text2;
673
808
  try {
674
- const secret = credentials(env, activeProfile(env, name).storage, keyring).read(name)?.secret;
675
- const parsed = secret ? safeParse(Session, JSON.parse(secret)) : void 0;
676
- if (!parsed?.success)
677
- return [];
678
- return parsed.output.tokens.scope?.split(/\s+/).filter(Boolean);
809
+ text2 = readFileSync2(path, "utf8");
679
810
  } catch {
680
- return [];
681
- }
682
- }, "grantedScopes");
683
- var checkAuthorization = /* @__PURE__ */ __name(async (client, required = READ_SCOPE) => {
684
- try {
685
- const { token } = await client.getAccessToken();
686
- if (!token)
687
- throw new CliError("authentication_error", "Google returned no access token");
688
- const info = await client.getTokenInfo(token);
689
- if (!covers(info.scopes, required))
690
- throw new CliError("permission_error", "sign-in lacks the required permission; run drive <profile> session start --grant write, activity or apps when needed", { reason: "sign-in.scope-missing" });
691
- } catch (error) {
692
- throw googleError(error);
811
+ return { path, found: false, raw: {}, config: { profiles: {} }, issues: [] };
693
812
  }
694
- }, "checkAuthorization");
695
- var WORD = /^[a-z][a-z_]{0,23}$/;
696
- var VERB = /^[a-z][A-Za-z]{0,31}$/;
697
- var segment = /* @__PURE__ */ __name((part) => {
698
- if (/^v\d+$/.test(part) || WORD.test(part))
699
- return part;
700
- const verb = part.split(":")[1];
701
- return verb !== void 0 && VERB.test(verb) ? `:id:${verb}` : ":id";
702
- }, "segment");
703
- var operationOf = /* @__PURE__ */ __name((method, url) => {
704
- let path = "";
705
- try {
706
- path = new URL(String(url ?? "")).pathname;
707
- } catch {
813
+ return { path, found: true, ...examine(text2, path, knownPermissions) };
814
+ }, "inspectConfig");
815
+ var configIssues = /* @__PURE__ */ __name((raw, file, knownPermissions) => examine(JSON.stringify(raw), file, knownPermissions).issues, "configIssues");
816
+ var refusal = /* @__PURE__ */ __name((issues) => new CliError("configuration_error", issueMessage(issues)), "refusal");
817
+ var readConfig = /* @__PURE__ */ __name((env, knownPermissions) => {
818
+ const { config, issues } = inspectConfig(env, knownPermissions);
819
+ if (issues.length)
820
+ throw refusal(issues);
821
+ return config;
822
+ }, "readConfig");
823
+ var writeConfig = /* @__PURE__ */ __name((env, config) => {
824
+ const [issue] = configIssues(config, "drive settings");
825
+ if (issue)
826
+ throw new CliError("configuration_error", `drive settings: ${issue.profile === void 0 ? "" : `profile ${issue.profile}: `}${issue.what}`);
827
+ saveConfigFile(configPath(env), parse(ConfigSchema, config));
828
+ }, "writeConfig");
829
+ var profileName = usableProfileName;
830
+ var fileId = /* @__PURE__ */ __name((input) => {
831
+ let id = input;
832
+ if (input.startsWith("https://")) {
833
+ const url = new URL(input);
834
+ if (url.hostname !== "drive.google.com" && url.hostname !== "docs.google.com")
835
+ throw new CliError("validation_error", "use a Google Drive/Docs URL or file ID");
836
+ id = url.pathname.match(/\/(?:folders|d)\/([^/]+)/)?.[1] ?? "";
708
837
  }
709
- const template = path.split("/").filter(Boolean).map((part) => segment(decodeURIComponent(part))).join("/");
710
- return `${(method ?? "GET").toUpperCase()} /${template}`;
711
- }, "operationOf");
712
- var reasonOf = /* @__PURE__ */ __name((data) => {
713
- const error = data?.error;
714
- const reason = error?.errors?.[0]?.reason ?? error?.status;
715
- return typeof reason === "string" ? reason : void 0;
716
- }, "reasonOf");
717
- var observeRequests = /* @__PURE__ */ __name((client) => {
718
- const transporter = client.transporter;
719
- const request = transporter.request.bind(transporter);
720
- transporter.request = (async (options) => {
721
- const method = (options.method ?? "GET").toUpperCase();
722
- const operation = operationOf(method, options.url);
723
- const call = { method, endpointTemplate: operation.slice(method.length + 1), transport: "http" };
724
- let ended;
725
- const adapter = /* @__PURE__ */ __name(async (prepared, next) => {
726
- const attempt = (prepared.retryConfig?.currentRetryAttempt ?? 0) + 1;
727
- const waitMs = ended === void 0 ? void 0 : Math.round(performance.now() - ended);
728
- const answered = providerRequest(operation, void 0, {
729
- ...call,
730
- attempt,
731
- ...waitMs === void 0 ? {} : { waitMs }
732
- });
733
- try {
734
- const response = await (options.adapter ? options.adapter(prepared, next) : next(prepared));
735
- const failed = !(prepared.validateStatus?.(response.status) ?? response.status < 400);
736
- const providerError = failed ? reasonOf(response.data) : void 0;
737
- answered({
738
- status: response.status,
739
- ...failed ? { errorCode: "provider_error" } : {},
740
- ...providerError ? { providerError } : {}
741
- });
742
- return response;
743
- } catch (error) {
744
- answered({ error, errorCode: googleError(error).code });
745
- throw error;
746
- } finally {
747
- ended = performance.now();
748
- }
749
- }, "adapter");
750
- try {
751
- return await request({ ...options, adapter });
752
- } catch (error) {
753
- if (ended === void 0)
754
- providerRequest(operation, void 0, { ...call, attempt: 1 })({ error, errorCode: googleError(error).code });
755
- throw error;
838
+ if (!/^[A-Za-z0-9_-]{1,200}$/.test(id))
839
+ throw new CliError("validation_error", "invalid Google file ID");
840
+ return id;
841
+ }, "fileId");
842
+ var unknownProfile = /* @__PURE__ */ __name((name, profiles) => new CliError("validation_error", profiles.length ? `no profile ${name} here \u2014 profiles here: ${profiles.join(", ")}; a new one signs in with drive ${name} session start` : `no profiles here yet; create one with drive ${name} session start`, { reason: "profile.unknown", profiles }), "unknownProfile");
843
+ var activeProfile = /* @__PURE__ */ __name((env, name) => {
844
+ const config = readConfig(env);
845
+ const profile = config.profiles[profileName(name)];
846
+ if (!profile)
847
+ throw unknownProfile(name, Object.keys(config.profiles).sort());
848
+ return profile;
849
+ }, "activeProfile");
850
+ var checkTextLimit = /* @__PURE__ */ __name((value) => {
851
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1)
852
+ throw new CliError("validation_error", "max_text_chars must be a positive whole number of characters");
853
+ if (value > MAX_TEXT_CHARS)
854
+ throw new CliError("validation_error", `max_text_chars can be at most ${MAX_TEXT_CHARS}: the document readers return at most that many characters`);
855
+ return value;
856
+ }, "checkTextLimit");
857
+ var textLimit = /* @__PURE__ */ __name((env, name) => activeProfile(env, name).max_text_chars ?? readConfig(env).defaults?.max_text_chars ?? MAX_TEXT_CHARS, "textLimit");
858
+ var pictureSearch = /* @__PURE__ */ __name((env, name) => activeProfile(env, name).picture_search ?? false, "pictureSearch");
859
+ var application = /* @__PURE__ */ __name((env, file) => {
860
+ if (!file) {
861
+ if (!env.DRIVE_GOOGLE_CLIENT_ID) {
862
+ if (env.DRIVE_GOOGLE_CLIENT_SECRET)
863
+ throw new CliError("configuration_error", "DRIVE_GOOGLE_CLIENT_SECRET requires DRIVE_GOOGLE_CLIENT_ID");
864
+ return { ...WIRECAT_APPLICATION };
756
865
  }
866
+ return {
867
+ clientId: env.DRIVE_GOOGLE_CLIENT_ID,
868
+ ...env.DRIVE_GOOGLE_CLIENT_SECRET ? { clientSecret: env.DRIVE_GOOGLE_CLIENT_SECRET } : {}
869
+ };
870
+ }
871
+ return readClientFile(file, {
872
+ invalid: new CliError("configuration_error", "could not read a valid Desktop OAuth client JSON; file contents were not logged", { reason: "sign-in.client-file-invalid" })
757
873
  });
758
- return client;
759
- }, "observeRequests");
874
+ }, "application");
875
+ var selectedFolders = /* @__PURE__ */ __name((env, profile, filter = {}) => activeProfile(env, profile).roots.flatMap((id) => filter.id === void 0 || id === filter.id ? [{ id }] : []), "selectedFolders");
876
+ var configuredMirrors = /* @__PURE__ */ __name((env, profile, filter = {}) => (activeProfile(env, profile).mirrors ?? []).filter((row) => Object.entries(filter).every(([key, value]) => row[key] === value)), "configuredMirrors");
877
+ var configuredSessions = /* @__PURE__ */ __name((env, filter, knownPermissions) => Object.entries(readConfig(env, knownPermissions).profiles).flatMap(([name, row]) => (filter.profile === void 0 || filter.profile === name) && (filter.storage === void 0 || filter.storage === row.storage) ? [{ profile: name, selected_folders: row.roots.length, storage: row.storage }] : []), "configuredSessions");
760
878
 
761
879
  export {
762
- credentials,
763
- notSaved,
764
- saveSession,
765
- googleProvider,
766
- sessionKeeper,
767
- authorizedClient,
768
- covers,
769
- grantedScopes,
770
- checkAuthorization,
771
- operationOf,
772
- observeRequests
880
+ tokenKeeper,
881
+ driveSessionCodec,
882
+ credentialStorage,
883
+ permissionKeys,
884
+ permissionNames,
885
+ DEFAULT_LEVELS,
886
+ methodPolicyKeys,
887
+ DEFAULTS_ONLY,
888
+ SETTING_NAMES,
889
+ configuration,
890
+ paths,
891
+ inspectConfig,
892
+ configIssues,
893
+ refusal,
894
+ readConfig,
895
+ writeConfig,
896
+ profileName,
897
+ fileId,
898
+ unknownProfile,
899
+ activeProfile,
900
+ checkTextLimit,
901
+ textLimit,
902
+ pictureSearch,
903
+ application,
904
+ selectedFolders,
905
+ configuredMirrors,
906
+ configuredSessions
773
907
  };