@wirecat/amo-cli 0.4.0 → 0.5.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 (159) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/contracts/wirecat.json +2 -1
  3. package/dist/amo/allow-list.d.ts +1 -1
  4. package/dist/amo/allow-list.d.ts.map +1 -1
  5. package/dist/amo/operation.d.ts +1 -1
  6. package/dist/amo/operation.d.ts.map +1 -1
  7. package/dist/bin/amo.js +2 -2
  8. package/dist/bundle/agent-EFMUK732.js +41 -0
  9. package/dist/bundle/{all-profiles-PRNXEZRH.js → all-profiles-PIWUQWBA.js} +11 -11
  10. package/dist/bundle/amo.js +28 -28
  11. package/dist/bundle/{anthropic-FDI24DU2.js → anthropic-47CMXBPQ.js} +5 -5
  12. package/dist/bundle/{app-server-WAKJVDLN.js → app-server-QRBQODF2.js} +70 -69
  13. package/dist/bundle/areas-QVHVU57Z.js +63 -0
  14. package/dist/bundle/{bun-YPXUXMBI.js → bun-OPDGMZZQ.js} +2 -2
  15. package/dist/bundle/{bun-sqlite-UBQ5M47X.js → bun-sqlite-7I4X7CZW.js} +6 -6
  16. package/dist/bundle/{chunk-SFZVMKB6.js → chunk-2JHVQMVC.js} +1 -1
  17. package/dist/bundle/{chunk-SNBYFQHT.js → chunk-2XBDILVW.js} +1 -1
  18. package/dist/bundle/{chunk-BCIZAUDV.js → chunk-3DEQUYEG.js} +9 -9
  19. package/dist/bundle/{chunk-2AIG2SSJ.js → chunk-3GX6KM2E.js} +1661 -164
  20. package/dist/bundle/{chunk-5II6TAJE.js → chunk-3HC5F3P7.js} +1 -1
  21. package/dist/bundle/{chunk-DWD3KDJA.js → chunk-3PYE55JY.js} +1 -1
  22. package/dist/bundle/{chunk-SMM7GS4Q.js → chunk-3YM4B2GT.js} +1 -1
  23. package/dist/bundle/{chunk-XEYT2EQT.js → chunk-43OW5NTG.js} +6 -6
  24. package/dist/bundle/{chunk-HDZNSOV5.js → chunk-43PMSR33.js} +13 -9
  25. package/dist/bundle/{chunk-EBNCUQLV.js → chunk-4N7PP76S.js} +1 -1
  26. package/dist/bundle/{chunk-WAFB3IWJ.js → chunk-4VN7RI4I.js} +5 -5
  27. package/dist/bundle/{chunk-CEBX63XY.js → chunk-57HFPNMF.js} +8 -8
  28. package/dist/bundle/{chunk-Z2B3VNRI.js → chunk-5UTB3ADZ.js} +11 -11
  29. package/dist/bundle/{chunk-PLU2IQXC.js → chunk-633NQY2R.js} +3 -3
  30. package/dist/bundle/{chunk-NKYWQTS2.js → chunk-63N46DJU.js} +216 -233
  31. package/dist/bundle/{chunk-5HZMXHRH.js → chunk-6D4VWSJD.js} +6 -6
  32. package/dist/bundle/{chunk-V2QWX6B3.js → chunk-6JTHXWPE.js} +3 -3
  33. package/dist/bundle/{chunk-YREKMP24.js → chunk-6QGUK3H7.js} +4 -4
  34. package/dist/bundle/{chunk-4PQECIU2.js → chunk-6WS6GJ4V.js} +2 -2
  35. package/dist/bundle/{chunk-23AQD7JU.js → chunk-7IR2G5XY.js} +16 -16
  36. package/dist/bundle/{chunk-OYMHPQF7.js → chunk-7IWIFVXH.js} +4 -4
  37. package/dist/bundle/{chunk-YHVHDRED.js → chunk-ABX7BBS4.js} +6 -6
  38. package/dist/bundle/{chunk-3K6T2G52.js → chunk-ADTI5RUO.js} +6 -6
  39. package/dist/bundle/{chunk-YFRTEJ6V.js → chunk-AKRIUNYP.js} +7 -7
  40. package/dist/bundle/{chunk-KBAOJISR.js → chunk-BIKOE2IW.js} +7 -7
  41. package/dist/bundle/{chunk-TIR3AB35.js → chunk-BVVMIAQ6.js} +759 -694
  42. package/dist/bundle/{chunk-M54YKD3I.js → chunk-CGW5R4UD.js} +7 -7
  43. package/dist/bundle/{chunk-CYHIM5SL.js → chunk-D4NE7EON.js} +3 -3
  44. package/dist/bundle/{chunk-TCSVW7BA.js → chunk-DNCLQPOM.js} +1 -1
  45. package/dist/bundle/{chunk-WASBOYI2.js → chunk-DPV53EZC.js} +4 -4
  46. package/dist/bundle/{chunk-VEFAYLKX.js → chunk-DQ6S5TFZ.js} +185 -114
  47. package/dist/bundle/{chunk-GMHRPX5M.js → chunk-DSJ6EAOA.js} +61 -61
  48. package/dist/bundle/{chunk-GQKEMBM6.js → chunk-DVZ75WZJ.js} +121 -36
  49. package/dist/bundle/{chunk-SHOSFYI7.js → chunk-EHK73OSW.js} +38 -24
  50. package/dist/bundle/{chunk-KQZTX4LM.js → chunk-FNV5HLHX.js} +17 -17
  51. package/dist/bundle/{chunk-RQPB2BSH.js → chunk-FV4GQNIK.js} +2 -2
  52. package/dist/bundle/{chunk-E3EWS6DF.js → chunk-G2TU5RYY.js} +6 -6
  53. package/dist/bundle/{chunk-WEWJA42Q.js → chunk-GDK7ETSB.js} +12 -12
  54. package/dist/bundle/{chunk-KORZEYZN.js → chunk-GGMAIIVE.js} +1 -1
  55. package/dist/bundle/{chunk-U46RNOEQ.js → chunk-GLYWZQY4.js} +3 -3
  56. package/dist/bundle/{chunk-KRD375P7.js → chunk-H4AFNENN.js} +34 -29
  57. package/dist/bundle/{chunk-SZX7EPPY.js → chunk-HOF7GQWW.js} +4 -4
  58. package/dist/bundle/{chunk-DWA5TZMP.js → chunk-HSPEU6S7.js} +8 -8
  59. package/dist/bundle/{chunk-VG2ERHFJ.js → chunk-IA7LLLEI.js} +3 -3
  60. package/dist/bundle/{chunk-O3WE5IGP.js → chunk-IB55P46L.js} +6 -6
  61. package/dist/bundle/{chunk-2UJ7ZZZC.js → chunk-IG2TJQJ7.js} +3 -3
  62. package/dist/bundle/{chunk-ZJC2XJQC.js → chunk-JG6LCSEX.js} +13 -13
  63. package/dist/bundle/{chunk-ELAKOEIO.js → chunk-JLXXUEAM.js} +2 -2
  64. package/dist/bundle/{chunk-UCM7C773.js → chunk-JXT6GY4V.js} +158 -61
  65. package/dist/bundle/{chunk-ABMPZL2P.js → chunk-K7YY6SXR.js} +19 -15
  66. package/dist/bundle/{chunk-TEGQVVCZ.js → chunk-KEKXERBE.js} +14581 -11880
  67. package/dist/bundle/{chunk-GJBOZAUD.js → chunk-KZ2FIDI3.js} +3 -3
  68. package/dist/bundle/{chunk-IBEHYGG6.js → chunk-KZN2BG3P.js} +8 -8
  69. package/dist/bundle/{chunk-VG26HDKH.js → chunk-LKH3UKLO.js} +4 -4
  70. package/dist/bundle/{chunk-PIOR6PIO.js → chunk-LZPKBN3C.js} +2 -2
  71. package/dist/bundle/{chunk-5SJEJYQZ.js → chunk-M6VZXAJC.js} +3 -3
  72. package/dist/bundle/{chunk-NFWD4QX3.js → chunk-MDEPJZYJ.js} +2 -2
  73. package/dist/bundle/{chunk-QGFURWEP.js → chunk-NB7EOAUZ.js} +8 -1
  74. package/dist/bundle/{chunk-GBQ76X6T.js → chunk-NISH4UXM.js} +2 -2
  75. package/dist/bundle/{chunk-MW7HUD6R.js → chunk-NSKMNIY6.js} +9 -9
  76. package/dist/bundle/chunk-PPSAWFJD.js +1293 -0
  77. package/dist/bundle/{chunk-UEN5NWNW.js → chunk-Q7ICVP25.js} +1 -1
  78. package/dist/bundle/{chunk-7OVTUADG.js → chunk-QFOP3KUP.js} +8 -8
  79. package/dist/bundle/{chunk-LAR2DLTI.js → chunk-R53XXHEI.js} +4 -4
  80. package/dist/bundle/{chunk-A4W7J6VN.js → chunk-RIMPFMZE.js} +28 -189
  81. package/dist/bundle/{chunk-G3LAYJJJ.js → chunk-RN6RT5CB.js} +4 -4
  82. package/dist/bundle/{chunk-FQRP6JWX.js → chunk-RRTMPSQR.js} +2 -2
  83. package/dist/bundle/{chunk-AN6IJYH3.js → chunk-S4ZHQMNM.js} +5 -5
  84. package/dist/bundle/{chunk-AP3CWDRK.js → chunk-S6JG4YUH.js} +2 -2
  85. package/dist/bundle/{chunk-PL7TNKAY.js → chunk-TAVI73RW.js} +2 -2
  86. package/dist/bundle/{chunk-ZKRWNL4T.js → chunk-TLG6ECZ2.js} +2 -2
  87. package/dist/bundle/{chunk-745FMNI5.js → chunk-TXDR6YSF.js} +1 -1
  88. package/dist/bundle/{chunk-3WG4MTQI.js → chunk-TY7NDMFY.js} +1 -1
  89. package/dist/bundle/{chunk-WR2FPZTE.js → chunk-U5RJJ2EC.js} +8 -8
  90. package/dist/bundle/{chunk-6QMSKJB4.js → chunk-UDSL3MUU.js} +8 -8
  91. package/dist/bundle/{chunk-FEUNZG7U.js → chunk-V2CNGXWX.js} +37 -37
  92. package/dist/bundle/{chunk-V5SETIQK.js → chunk-VB7FZOYX.js} +1 -1
  93. package/dist/bundle/{chunk-HZZ56JO7.js → chunk-VZ5PPYDG.js} +1 -1
  94. package/dist/bundle/{chunk-LZ4IWN43.js → chunk-W5JRXIG6.js} +822 -1604
  95. package/dist/bundle/{chunk-SCMB4LI6.js → chunk-WIHN3ELW.js} +19 -19
  96. package/dist/bundle/chunk-WOPVBRPV.js +29 -0
  97. package/dist/bundle/{chunk-6PILR4AX.js → chunk-WUFX4TKA.js} +2 -2
  98. package/dist/bundle/{chunk-NXNUCGGO.js → chunk-WXJYMMEL.js} +6 -6
  99. package/dist/bundle/{chunk-IPNIF5JE.js → chunk-XCCU2E3Z.js} +4 -4
  100. package/dist/bundle/{chunk-EAX5RO7S.js → chunk-XEQQJBBO.js} +1 -1
  101. package/dist/bundle/{chunk-3PCVQCCV.js → chunk-XUT7DSM5.js} +2 -2
  102. package/dist/bundle/{chunk-ASU63X5C.js → chunk-YWDFYQOU.js} +2 -2
  103. package/dist/bundle/{chunk-S6DTLAOB.js → chunk-ZLUIRFJX.js} +37 -18
  104. package/dist/bundle/{cli-QDPKC2HJ.js → cli-3NXOSENF.js} +104 -105
  105. package/dist/bundle/command-contract-LNSAV5LA.js +39 -0
  106. package/dist/bundle/{command-server-entry-TX7WNN7G.js → command-server-entry-4ZQPNUL4.js} +28 -28
  107. package/dist/bundle/{decode-BLPC7OYE.js → decode-K7U7X5EL.js} +5 -5
  108. package/dist/bundle/{dispatch-5JUT55CS.js → dispatch-56FECRCU.js} +8 -8
  109. package/dist/bundle/{echarts-54D3FOCL.js → echarts-O3TNDAXJ.js} +2 -2
  110. package/dist/bundle/{embed-O7KMDYM7.js → embed-SWLVG73O.js} +6 -6
  111. package/dist/bundle/{embedder-4PE67CLX.js → embedder-EJN75BPV.js} +9 -9
  112. package/dist/bundle/{failure-NNQYTB3Z.js → failure-WDSX6H3B.js} +2 -2
  113. package/dist/bundle/{first-run-EAU5SHBI.js → first-run-WPGUUC4Z.js} +12 -12
  114. package/dist/bundle/first-screen-JMNEUQ46.js +40 -0
  115. package/dist/bundle/{instructions-ONXP5DZQ.js → instructions-AMH5RWVJ.js} +1 -1
  116. package/dist/bundle/{mcp-ZNULRPZ4.js → mcp-5HFPWC3W.js} +2 -2
  117. package/dist/bundle/meeting-combined-5TKG2RYD.js +24 -0
  118. package/dist/bundle/{meeting-model-FWIZRKVN.js → meeting-model-YXXNETKC.js} +11 -11
  119. package/dist/bundle/{meeting-semantic-M4YVJ57W.js → meeting-semantic-U7EUB3ET.js} +6 -6
  120. package/dist/bundle/{node-UTQCYQF5.js → node-EGMCBAO7.js} +2 -2
  121. package/dist/bundle/{node-sqlite-APJG6MGL.js → node-sqlite-YVOGMDSP.js} +7 -7
  122. package/dist/bundle/{oauth-TY7RMIBL.js → oauth-2SNRBIJM.js} +7 -7
  123. package/dist/bundle/{open-WDVEQL75.js → open-ABCPY5IH.js} +5 -5
  124. package/dist/bundle/{openai-H5UJHSEZ.js → openai-4D6PXJR7.js} +15 -15
  125. package/dist/bundle/{process-MGMXXPMY.js → process-SGHEN6MQ.js} +1 -1
  126. package/dist/bundle/{program-IF36C6VR.js → program-CBDQBZZ3.js} +319 -133
  127. package/dist/bundle/{prompt-4RLIWLMF.js → prompt-2QUK5QST.js} +5 -5
  128. package/dist/bundle/{recognize-UIRTMWM4.js → recognize-QMQSJRIH.js} +4 -4
  129. package/dist/bundle/{remote-L3MNWZQK.js → remote-U7TC2BLZ.js} +9 -9
  130. package/dist/bundle/{rerank-F4KZQTY6.js → rerank-5UPVXGVV.js} +7 -7
  131. package/dist/bundle/{serve-37AUYTWS.js → serve-VX6GUM6J.js} +9 -9
  132. package/dist/bundle/{server-UBG676ZJ.js → server-FOPC6DJ3.js} +62 -61
  133. package/dist/bundle/server-OIVNOMVK.js +87 -0
  134. package/dist/bundle/source-HWS5SJIV.js +46 -0
  135. package/dist/bundle/{sqlite-runtime-CI3RW7VA.js → sqlite-runtime-77NKDEXN.js} +6 -6
  136. package/dist/bundle/{state-JOHLSLUO.js → state-X2HU6GB2.js} +6 -6
  137. package/dist/bundle/{store-2MBG4IUS.js → store-2U4U6KL4.js} +22 -22
  138. package/dist/bundle/{store-OSOUXBYL.js → store-3CHPHFP7.js} +26 -24
  139. package/dist/bundle/store-Z3747L5F.js +34 -0
  140. package/dist/bundle/store-maintenance-command-UOSZJTVP.js +74 -0
  141. package/dist/bundle/surface-MUT72QON.js +73 -0
  142. package/dist/bundle/writer-RBKQ64ZM.js +48 -0
  143. package/dist/commands/crm-shared.js +1 -1
  144. package/dist/commands/crm-shared.js.map +1 -1
  145. package/dist/version.d.ts +1 -1
  146. package/dist/version.js +1 -1
  147. package/package.json +4 -4
  148. package/skills/amo-cli/SKILL.md +6 -0
  149. package/dist/bundle/agent-43BMVBX2.js +0 -40
  150. package/dist/bundle/chunk-M33XHJTM.js +0 -1266
  151. package/dist/bundle/command-contract-KWNCP3MQ.js +0 -39
  152. package/dist/bundle/first-screen-APSNGZYZ.js +0 -39
  153. package/dist/bundle/meeting-combined-W2XIYXFU.js +0 -24
  154. package/dist/bundle/server-CRF4QSZR.js +0 -86
  155. package/dist/bundle/source-Z7GH7T4B.js +0 -44
  156. package/dist/bundle/store-SNW6U32Y.js +0 -34
  157. package/dist/bundle/store-maintenance-command-W7V54SLT.js +0 -73
  158. package/dist/bundle/surface-ESJS2FUI.js +0 -72
  159. package/dist/bundle/writer-BJDQMKUV.js +0 -46
@@ -1,26 +1,66 @@
1
1
  import { createRequire as __bundleRequire } from "node:module";
2
2
  const require = __bundleRequire(import.meta.url);
3
+ import {
4
+ WIRECAT_TOOLS
5
+ } from "./chunk-NB7EOAUZ.js";
3
6
  import {
4
7
  LIST_QUERY_GUIDE,
5
- timeBounds
6
- } from "./chunk-ABMPZL2P.js";
8
+ queryTerms,
9
+ termField,
10
+ timeBounds,
11
+ withQuery
12
+ } from "./chunk-K7YY6SXR.js";
7
13
  import {
14
+ API_UNTRUSTED,
15
+ Command,
8
16
  MESSENGER_CHANGE_REFUSAL,
17
+ NO_EFFECTS,
18
+ Option,
19
+ REMOTE_READ,
20
+ REMOTE_WRITE,
21
+ ancestorValue,
22
+ annotate,
23
+ baseContext,
9
24
  envName,
25
+ environmentOf,
10
26
  guardedWrite,
27
+ issueMessage,
28
+ itemOf,
29
+ listOf,
30
+ marksUntrusted,
31
+ metaOf,
32
+ outputFor,
33
+ permissionIssues,
11
34
  progressLine,
12
35
  progressOf,
36
+ publicIssue,
37
+ readOnlyLockOf,
13
38
  readOnlyRefusal,
14
- runBudget
15
- } from "./chunk-NKYWQTS2.js";
39
+ renderAnswer,
40
+ rootOf,
41
+ runBudget,
42
+ startRecording,
43
+ wasSettled
44
+ } from "./chunk-63N46DJU.js";
45
+ import {
46
+ keepsSuccess,
47
+ providerErrorKey,
48
+ runContextOf,
49
+ secretInput
50
+ } from "./chunk-CGW5R4UD.js";
16
51
  import {
17
52
  crmIdentityId,
18
53
  crmSettingKey,
19
54
  seenBy
20
- } from "./chunk-TEGQVVCZ.js";
55
+ } from "./chunk-KEKXERBE.js";
21
56
  import {
57
+ KEEP_RUNS_FOR_DAYS,
58
+ KEEP_STORE_RUNS_FOR_DAYS,
59
+ KEEP_SUCCESSFUL_RUNS_FOR_DAYS,
22
60
  LOG_ATTRIBUTES,
61
+ RUNS_SIZE_LIMIT_MB,
23
62
  accountsOfList,
63
+ currentAttempt,
24
64
  currentRun,
25
65
  entriesOfList,
26
66
  fitting,
@@ -29,30 +69,42 @@ import {
29
69
  isGroupName,
30
70
  keyOf,
31
71
  logAttributes,
72
+ runEvent,
32
73
  sameAs,
33
74
  sourceOf3 as sourceOf
34
- } from "./chunk-M33XHJTM.js";
75
+ } from "./chunk-PPSAWFJD.js";
35
76
  import {
36
77
  isCliFailure
37
- } from "./chunk-ELAKOEIO.js";
78
+ } from "./chunk-JLXXUEAM.js";
38
79
  import {
80
+ hostFetch,
81
+ providerWaitMs,
82
+ readJsonResponse,
83
+ statusToCode
84
+ } from "./chunk-G2TU5RYY.js";
85
+ import {
86
+ AUTHORITY_KEY,
39
87
  CEILING_KEY,
40
88
  DEFAULT_PERMISSIONS,
89
+ KEYED_UNDER_HOUSEKEEPING,
41
90
  STORE_ONLY_KEYS,
91
+ WRITE_KEYS,
92
+ keyForCommand,
42
93
  keyForWrite,
43
94
  levelFor,
44
95
  skipFlagFor,
45
96
  stops
46
- } from "./chunk-KBAOJISR.js";
97
+ } from "./chunk-BIKOE2IW.js";
47
98
  import {
48
99
  e164Of,
49
100
  foldName
50
- } from "./chunk-SHOSFYI7.js";
101
+ } from "./chunk-EHK73OSW.js";
51
102
  import {
52
103
  CRM_KINDS,
53
104
  DEAL_KINDS,
54
105
  INTERNAL_NOTES,
55
106
  STAGE_OUTCOMES,
107
+ alsoListedByKey,
56
108
  currencyOf,
57
109
  holdsKindOf,
58
110
  isCrmUserId,
@@ -63,18 +115,23 @@ import {
63
115
  minorUnits,
64
116
  normalCrmUserId,
65
117
  providerNamed
66
- } from "./chunk-S6DTLAOB.js";
118
+ } from "./chunk-ZLUIRFJX.js";
67
119
  import {
68
120
  parseLucene,
69
121
  walkQuery
70
- } from "./chunk-GMHRPX5M.js";
122
+ } from "./chunk-DSJ6EAOA.js";
123
+ import {
124
+ storePath,
125
+ wirecatDirectory
126
+ } from "./chunk-TLG6ECZ2.js";
71
127
  import {
72
128
  backoffMs,
73
129
  logRecordOf,
74
130
  realSleep,
75
131
  resolvePaths,
132
+ wallClock,
76
133
  writeSecurely
77
- } from "./chunk-SCMB4LI6.js";
134
+ } from "./chunk-WIHN3ELW.js";
78
135
  import {
79
136
  array,
80
137
  boolean,
@@ -95,17 +152,233 @@ import {
95
152
  string,
96
153
  union,
97
154
  unknown
98
- } from "./chunk-7OVTUADG.js";
155
+ } from "./chunk-QFOP3KUP.js";
99
156
  import {
100
157
  CliError,
101
158
  isCliError
102
- } from "./chunk-AP3CWDRK.js";
159
+ } from "./chunk-S6JG4YUH.js";
103
160
  import {
104
161
  __export,
105
162
  __name
106
163
  } from "./chunk-ZVVMGPBJ.js";
107
164
 
108
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/values.js
165
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/sends/upload.js
166
+ import { openAsBlob, realpathSync } from "node:fs";
167
+ import { open, stat } from "node:fs/promises";
168
+ import { basename, dirname, extname, isAbsolute, relative, resolve, sep } from "node:path";
169
+ var MAX_BUFFERED_UPLOAD_BYTES = 256 * 1024 * 1024;
170
+ var uploadSize = /* @__PURE__ */ __name((source) => source.kind === "file" ? source.size : source.bytes.byteLength, "uploadSize");
171
+ var PHOTO = /* @__PURE__ */ new Set([".jpg", ".jpeg", ".png", ".webp"]);
172
+ var VOICE = /* @__PURE__ */ new Set([".ogg", ".oga", ".opus"]);
173
+ var JPEG = /* @__PURE__ */ __name((head) => head[0] === 255 && head[1] === 216 && head[2] === 255, "JPEG");
174
+ var SIGNATURES = {
175
+ ".jpg": JPEG,
176
+ ".jpeg": JPEG,
177
+ ".png": /* @__PURE__ */ __name((head) => Buffer.from(head.subarray(0, 8)).toString("latin1") === "\x89PNG\r\n\n", ".png"),
178
+ ".webp": /* @__PURE__ */ __name((head) => {
179
+ const text2 = Buffer.from(head).toString("latin1");
180
+ return text2.startsWith("RIFF") && text2.slice(8, 12) === "WEBP";
181
+ }, ".webp")
182
+ };
183
+ var fileHead = /* @__PURE__ */ __name(async (path2) => {
184
+ const file = await open(path2, "r");
185
+ try {
186
+ const head = new Uint8Array(12);
187
+ const { bytesRead } = await file.read(head, 0, head.length, 0);
188
+ return head.subarray(0, bytesRead);
189
+ } finally {
190
+ await file.close();
191
+ }
192
+ }, "fileHead");
193
+ var typesText = /* @__PURE__ */ __name((types) => types.length < 2 ? types[0] ?? "" : `${types.slice(0, -1).join(", ")} or ${types.at(-1)}`, "typesText");
194
+ var CREDENTIAL_PARTS = /* @__PURE__ */ new Set([
195
+ ".ssh",
196
+ ".gnupg",
197
+ ".aws",
198
+ ".azure",
199
+ ".kube",
200
+ ".secrets",
201
+ "secrets",
202
+ ".password-store",
203
+ ".mozilla",
204
+ ".env",
205
+ ".npmrc",
206
+ ".pypirc",
207
+ ".netrc",
208
+ "_netrc",
209
+ ".git-credentials",
210
+ "credentials.yml.enc",
211
+ "master.key"
212
+ ]);
213
+ var CREDENTIAL_RUNS = [
214
+ [".config", "autostart"],
215
+ [".config", "git", "credentials"],
216
+ [".config", "gh"],
217
+ [".config", "gcloud"],
218
+ [".config", "google-chrome"],
219
+ [".config", "chromium"],
220
+ [".config", "microsoft-edge"],
221
+ [".config", "BraveSoftware"],
222
+ [".docker", "config.json"],
223
+ [".claude", ".credentials.json"],
224
+ [".codex", "auth.json"],
225
+ [".local", "share", "keyrings"],
226
+ ["Library", "Keychains"],
227
+ ["Library", "Cookies"],
228
+ ["Library", "Safari"],
229
+ ["Library", "Application Support", "Google", "Chrome"],
230
+ ["Library", "Application Support", "Chromium"],
231
+ ["Library", "Application Support", "Microsoft Edge"],
232
+ ["Library", "Application Support", "BraveSoftware"],
233
+ ["Library", "Application Support", "Firefox"],
234
+ ["AppData", "Local", "Google", "Chrome"],
235
+ ["AppData", "Local", "Chromium"],
236
+ ["AppData", "Local", "Microsoft", "Edge"],
237
+ ["AppData", "Local", "BraveSoftware"],
238
+ ["AppData", "Roaming", "Mozilla", "Firefox"],
239
+ ["AppData", "Local", "Microsoft", "Credentials"],
240
+ ["AppData", "Roaming", "Microsoft", "Credentials"],
241
+ ["AppData", "Roaming", "Microsoft", "Protect"],
242
+ ["AppData", "Roaming", "gcloud"],
243
+ ["AppData", "Roaming", "GitHub CLI"]
244
+ ];
245
+ var WIRECAT_APPS = [
246
+ ...WIRECAT_TOOLS.map(({ appName, envPrefix }) => ({ appName, prefix: envPrefix })),
247
+ { appName: "beeline-cli", prefix: "BEELINE" },
248
+ { appName: "zm", prefix: "ZM" },
249
+ { appName: "cli-messaging", prefix: "MESSAGING" },
250
+ { appName: "cli-common", prefix: "CLI_COMMON" }
251
+ ];
252
+ var SYSTEM_ROOTS = ["/proc", "/sys", "/dev"];
253
+ var systemPlace = /* @__PURE__ */ __name((path2, platform) => platform !== "win32" && SYSTEM_ROOTS.some((root) => inside(path2, root)), "systemPlace");
254
+ var realPathOf = /* @__PURE__ */ __name((path2) => {
255
+ let ancestor = resolve(path2);
256
+ for (; ; ) {
257
+ try {
258
+ return resolve(realpathSync(ancestor), relative(ancestor, resolve(path2)));
259
+ } catch {
260
+ const parent = dirname(ancestor);
261
+ if (parent === ancestor)
262
+ return resolve(path2);
263
+ ancestor = parent;
264
+ }
265
+ }
266
+ }, "realPathOf");
267
+ var refuseLockedOutput = /* @__PURE__ */ __name((path2, app, env, flag) => {
268
+ const lock = readOnlyLockOf(app, env);
269
+ if (lock === void 0)
270
+ return;
271
+ const named2 = ancestorValue(envName(app, "WORK_FOLDER"), env);
272
+ const work = named2 ? realPathOf(named2) : void 0;
273
+ const real = realPathOf(path2);
274
+ if (work !== void 0 && (real === work || real.startsWith(`${work}${sep}`)))
275
+ return;
276
+ throw new CliError("permission_error", work === void 0 ? `this process is read-only (${lock}) \u2014 ${flag} writes a file only inside a scheduled run's work folder` : `this process is read-only (${lock}) \u2014 ${flag} writes only inside its run's work folder, ${work}`, { reason: "read-only.output-outside", param: flag });
277
+ }, "refuseLockedOutput");
278
+ var refusedPlace = /* @__PURE__ */ __name((path2, app, env, platform = process.platform) => {
279
+ const own = [
280
+ ...[{ appName: app.appName, prefix: app.envPrefix }, ...WIRECAT_APPS].flatMap((one) => Object.values(resolvePaths({ ...one, env, platform }))),
281
+ // The shared WireCat folder: the store, its backups beside it, the models.
282
+ wirecatDirectory(env, platform)
283
+ ];
284
+ const store = resolve(storePath(env));
285
+ const real = realPathOf(path2);
286
+ const folded = platform === "darwin" || platform === "win32";
287
+ const fold = /* @__PURE__ */ __name((text2) => folded ? text2.toLowerCase() : text2, "fold");
288
+ const parts = new Set([...CREDENTIAL_PARTS].map(fold));
289
+ const runs = CREDENTIAL_RUNS.map((run) => run.map(fold));
290
+ const named2 = /* @__PURE__ */ __name((candidate) => {
291
+ const names = candidate.split(sep).map(fold);
292
+ return names.some((name, index) => parts.has(name) || /^\.env\./.test(name) || runs.some((run) => run.every((part, offset) => names[index + offset] === part)));
293
+ }, "named");
294
+ const same = /* @__PURE__ */ __name((a, b) => fold(a) === fold(b), "same");
295
+ return [resolve(path2), real].some((candidate) => systemPlace(candidate, platform) || named2(candidate) || own.some((dir) => inside(fold(candidate), fold(dir))) || [store, `${store}-wal`, `${store}-shm`].some((file) => same(candidate, file)));
296
+ }, "refusedPlace");
297
+ var inside = /* @__PURE__ */ __name((path2, dir) => {
298
+ const way = relative(resolve(dir), path2);
299
+ return way === "" || !way.startsWith("..") && !isAbsolute(way);
300
+ }, "inside");
301
+ var readUpload = /* @__PURE__ */ __name(async (kind2, path2, { app, env = process.env, anyFile = false, photoTypes }) => {
302
+ const extension = extname(path2).toLowerCase();
303
+ if (kind2 === "photo" && photoTypes !== void 0 && !photoTypes.includes(extension)) {
304
+ throw new CliError("validation_error", `this photo must be a ${typesText(photoTypes)} file, not ${path2}`);
305
+ }
306
+ if (kind2 === "photo" && photoTypes === void 0 && !PHOTO.has(extension)) {
307
+ throw new CliError("validation_error", `a photo is a .jpg, .png or .webp \u2014 send ${path2} as a file instead`);
308
+ }
309
+ if (kind2 === "voice" && !VOICE.has(extension)) {
310
+ throw new CliError("validation_error", `a voice message is Ogg Opus: .ogg, .oga or .opus \u2014 send ${path2} as a file`);
311
+ }
312
+ if ([resolve(path2), realPathOf(path2)].some((candidate) => systemPlace(candidate, process.platform))) {
313
+ throw new CliError("validation_error", `cannot send ${path2}: a file under /proc, /sys or /dev is never sent`);
314
+ }
315
+ if (!anyFile && refusedPlace(path2, app, env)) {
316
+ throw new CliError("validation_error", `cannot send ${path2}: known credential files, browser profiles, the WireCat apps' folders and the message store are not sent \u2014 the owner adds --allow-any-file to the command if this file is meant to go`);
317
+ }
318
+ let size;
319
+ let head;
320
+ try {
321
+ const info = await stat(path2);
322
+ if (!info.isFile())
323
+ throw Object.assign(new Error("not a file"), { code: "EISDIR" });
324
+ size = info.size;
325
+ if (photoTypes !== void 0 && SIGNATURES[extension] !== void 0)
326
+ head = await fileHead(path2);
327
+ } catch (error) {
328
+ const code = error.code;
329
+ const reason = code === "ENOENT" ? "no such file" : code === "EISDIR" ? "it is a folder" : "it cannot be read";
330
+ throw new CliError("validation_error", `cannot send ${path2}: ${reason}`);
331
+ }
332
+ if (head !== void 0 && SIGNATURES[extension]?.(head) !== true) {
333
+ throw new CliError("validation_error", `${path2} is not a ${typesText(photoTypes ?? [])} image inside`);
334
+ }
335
+ return { kind: kind2, name: basename(path2), source: { kind: "file", path: resolve(path2), size } };
336
+ }, "readUpload");
337
+ var checkFilename = /* @__PURE__ */ __name((filename, files) => {
338
+ if (files.length === 0)
339
+ throw new CliError("validation_error", "--filename names a --file; give one");
340
+ if (files.length > 1)
341
+ throw new CliError("validation_error", "--filename names one --file; an album keeps its names");
342
+ if (filename.trim() === "" || /[/\\\0]/.test(filename) || filename.length > 255)
343
+ throw new CliError("validation_error", "--filename is a name, not a path: no / or \\, at most 255 characters");
344
+ }, "checkFilename");
345
+ var listOf2 = /* @__PURE__ */ __name((value) => value === void 0 ? [] : typeof value === "string" ? [value] : value, "listOf");
346
+ var readAttachments = /* @__PURE__ */ __name(async ({ photo, file, voice, asFile, filename, text: text2 }, read) => {
347
+ const photos = listOf2(photo);
348
+ const files = listOf2(file);
349
+ if (voice !== void 0 && (photos.length > 0 || files.length > 0 || (text2 ?? "").trim() !== "")) {
350
+ throw new CliError("validation_error", "a voice message goes alone \u2014 no text, no file, no photo beside it");
351
+ }
352
+ if (asFile && files.length === 0)
353
+ throw new CliError("validation_error", "--as-file is about a --file; give one");
354
+ if (filename !== void 0)
355
+ checkFilename(filename, files);
356
+ const uploads = [];
357
+ for (const one of photos)
358
+ uploads.push(await readUpload("photo", one, read));
359
+ for (const one of files)
360
+ uploads.push({
361
+ ...await readUpload("file", one, read),
362
+ ...filename === void 0 ? {} : { name: filename },
363
+ ...asFile ? { asFile: true } : {}
364
+ });
365
+ if (voice !== void 0)
366
+ uploads.push(await readUpload("voice", voice, read));
367
+ return uploads;
368
+ }, "readAttachments");
369
+ var readStickerFile = /* @__PURE__ */ __name(async (path2, maxBytes, read) => {
370
+ if (extname(path2).toLowerCase() !== ".webp")
371
+ throw new CliError("validation_error", `a sticker is a .webp \u2014 send ${path2} as a photo or a file instead`);
372
+ const { name, source } = await readUpload("file", path2, read);
373
+ if (SIGNATURES[".webp"]?.(await fileHead(path2)) !== true)
374
+ throw new CliError("validation_error", `${path2} is named .webp but is not a WebP image \u2014 nothing was sent`);
375
+ const size = uploadSize(source);
376
+ if (size > maxBytes)
377
+ throw new CliError("validation_error", `the sticker is ${Math.ceil(size / 1024)} KiB, and this messenger takes at most ${Math.floor(maxBytes / 1024)} KiB \u2014 nothing was sent`);
378
+ return { name, source };
379
+ }, "readStickerFile");
380
+
381
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/values.js
109
382
  var values_exports = {};
110
383
  __export(values_exports, {
111
384
  amountOf: () => amountOf,
@@ -122,10 +395,10 @@ __export(values_exports, {
122
395
  time: () => time
123
396
  });
124
397
 
125
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/source.js
398
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/source.js
126
399
  var CRM_FILE_SOURCES = ["record", "field", "document", "activity", "comment"];
127
400
 
128
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/files.js
401
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/files.js
129
402
  var parseCrmFileId = /* @__PURE__ */ __name((id2) => {
130
403
  const [kind2 = "", owner = "", source = "", ...rest] = id2.trim().split(":");
131
404
  const providerId = rest.join(":");
@@ -158,7 +431,7 @@ var withoutFileLinks = /* @__PURE__ */ __name((body) => {
158
431
  return walk2(body);
159
432
  }, "withoutFileLinks");
160
433
 
161
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/values.js
434
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/values.js
162
435
  var isRaw = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isRaw");
163
436
  var fieldOf = /* @__PURE__ */ __name((value, key) => isRaw(value) ? value[key] : void 0, "fieldOf");
164
437
  var rawsOf = /* @__PURE__ */ __name((value) => Array.isArray(value) ? value.filter(isRaw) : [], "rawsOf");
@@ -217,10 +490,10 @@ var crmValuesOf = /* @__PURE__ */ __name((values, fields2) => {
217
490
  }));
218
491
  }, "crmValuesOf");
219
492
 
220
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/cli/bot/api-input.js
493
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/cli/bot/api-input.js
221
494
  import { readFileSync } from "node:fs";
222
495
 
223
- // node_modules/.pnpm/@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typescript@7.0.2_vitest@5.0.5/node_modules/@wirecat/cli-base/dist/codegen/names.js
496
+ // node_modules/.pnpm/@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescript@7.0.2_vitest@5.0.5/node_modules/@wirecat/cli-base/dist/codegen/names.js
224
497
  var pascal = /* @__PURE__ */ __name((text2) => text2.split(/[^A-Za-z0-9]+/).filter(Boolean).map((word) => word[0]?.toUpperCase() + word.slice(1)).join(""), "pascal");
225
498
  var GLOBALS = /* @__PURE__ */ new Set([
226
499
  "Array",
@@ -256,7 +529,16 @@ var identifier = /* @__PURE__ */ __name((id2) => {
256
529
  return GLOBALS.has(name) ? `Api${name}` : name;
257
530
  }, "identifier");
258
531
 
259
- // node_modules/.pnpm/@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typescript@7.0.2_vitest@5.0.5/node_modules/@wirecat/cli-base/dist/codegen/sign-in.js
532
+ // node_modules/.pnpm/@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescript@7.0.2_vitest@5.0.5/node_modules/@wirecat/cli-base/dist/codegen/selection.js
533
+ var graphqlDocument = /* @__PURE__ */ __name((binding, selection = binding.selection) => {
534
+ const variables = Object.entries(binding.variables);
535
+ const declared = variables.length ? `(${variables.map(([name, type]) => `$${name}: ${type}`).join(", ")})` : "";
536
+ const passed = variables.length ? `(${variables.map(([name]) => `${name}: $${name}`).join(", ")})` : "";
537
+ const inner = selection.trim() ? ` { ${selection.trim()} }` : "";
538
+ return `${binding.operation} ${binding.field[0]?.toUpperCase()}${binding.field.slice(1)}${declared} { ${binding.field}${passed}${inner} }`;
539
+ }, "graphqlDocument");
540
+
541
+ // node_modules/.pnpm/@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescript@7.0.2_vitest@5.0.5/node_modules/@wirecat/cli-base/dist/codegen/sign-in.js
260
542
  var BEARER = { in: "header", name: "authorization", value: /* @__PURE__ */ __name((token) => `Bearer ${token}`, "value") };
261
543
  var signInPlace = /* @__PURE__ */ __name((scheme) => {
262
544
  if (scheme.type === "apiKey") {
@@ -289,63 +571,10 @@ var signInRequirements = /* @__PURE__ */ __name((operation, document) => {
289
571
  return requirements?.some((one) => Object.keys(one).length > 0) ? requirements : void 0;
290
572
  }, "signInRequirements");
291
573
 
292
- // node_modules/.pnpm/@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typescript@7.0.2_vitest@5.0.5/node_modules/@wirecat/cli-base/dist/codegen/graphql.js
293
- var graphqlDocument = /* @__PURE__ */ __name((binding, selection = binding.selection) => {
294
- const variables = Object.entries(binding.variables);
295
- const declared = variables.length ? `(${variables.map(([name, type]) => `$${name}: ${type}`).join(", ")})` : "";
296
- const passed = variables.length ? `(${variables.map(([name]) => `${name}: $${name}`).join(", ")})` : "";
297
- const inner = selection.trim() ? ` { ${selection.trim()} }` : "";
298
- return `${binding.operation} ${binding.field[0]?.toUpperCase()}${binding.field.slice(1)}${declared} { ${binding.field}${passed}${inner} }`;
299
- }, "graphqlDocument");
300
-
301
- // node_modules/.pnpm/@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typescript@7.0.2_vitest@5.0.5/node_modules/@wirecat/cli-base/dist/codegen/runtime.js
574
+ // node_modules/.pnpm/@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescript@7.0.2_vitest@5.0.5/node_modules/@wirecat/cli-base/dist/codegen/runtime.js
302
575
  var INT64_MIN = -(2n ** 63n);
303
576
  var INT64_MAX = 2n ** 63n - 1n;
304
577
 
305
- // node_modules/.pnpm/@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typescript@7.0.2_vitest@5.0.5/node_modules/@wirecat/cli-base/dist/codegen/openapi.js
306
- var IGNORED = /* @__PURE__ */ new Set([
307
- "readOnly",
308
- "example",
309
- "examples",
310
- "externalDocs",
311
- "title",
312
- "xml",
313
- "writeOnly",
314
- "not",
315
- "minProperties",
316
- "maxProperties"
317
- ]);
318
- var KNOWN = /* @__PURE__ */ new Set([
319
- ...IGNORED,
320
- "type",
321
- "format",
322
- "description",
323
- "nullable",
324
- "deprecated",
325
- "default",
326
- "enum",
327
- "const",
328
- "minLength",
329
- "maxLength",
330
- "pattern",
331
- "minimum",
332
- "maximum",
333
- "items",
334
- "prefixItems",
335
- "minItems",
336
- "maxItems",
337
- "uniqueItems",
338
- "properties",
339
- "required",
340
- "additionalProperties",
341
- "allOf",
342
- "oneOf",
343
- "anyOf",
344
- "$ref",
345
- "discriminator"
346
- ]);
347
- var LARGEST_EXAMPLE = 8 * 1024;
348
-
349
578
  // node_modules/.pnpm/lossless-json@4.3.3/node_modules/lossless-json/lib/esm/utils.js
350
579
  function isInteger(value) {
351
580
  return INTEGER_REGEX.test(value);
@@ -869,17 +1098,17 @@ function isDeepEqual(a, b) {
869
1098
  if (Array.isArray(a) && Array.isArray(b)) {
870
1099
  return a.length === b.length && a.every((item, index) => isDeepEqual(item, b[index]));
871
1100
  }
872
- if (isObject2(a) && isObject2(b)) {
1101
+ if (isObject(a) && isObject(b)) {
873
1102
  const keys = [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])];
874
1103
  return keys.every((key) => isDeepEqual(a[key], b[key]));
875
1104
  }
876
1105
  return false;
877
1106
  }
878
1107
  __name(isDeepEqual, "isDeepEqual");
879
- function isObject2(value) {
1108
+ function isObject(value) {
880
1109
  return typeof value === "object" && value !== null;
881
1110
  }
882
- __name(isObject2, "isObject");
1111
+ __name(isObject, "isObject");
883
1112
  var escapeCharacters = {
884
1113
  '"': '"',
885
1114
  "\\": "\\",
@@ -1030,7 +1259,7 @@ function resolveSpace(space) {
1030
1259
  }
1031
1260
  __name(resolveSpace, "resolveSpace");
1032
1261
 
1033
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/cli/bot/api-input.js
1262
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/cli/bot/api-input.js
1034
1263
  var RENAMED = { timeout: "poll-timeout" };
1035
1264
  var apiFlagOf = /* @__PURE__ */ __name((name) => RENAMED[name] ?? name.replace(/_/g, "-").replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase(), "apiFlagOf");
1036
1265
  var apiOptionKey = /* @__PURE__ */ __name((name) => apiFlagOf(name).replace(/-([a-z0-9])/g, (_, letter) => letter.toUpperCase()), "apiOptionKey");
@@ -1122,6 +1351,7 @@ var finite = /* @__PURE__ */ __name((key, value) => {
1122
1351
  }, "finite");
1123
1352
  var apiJson = /* @__PURE__ */ __name((value) => stringify(value, finite) ?? "null", "apiJson");
1124
1353
  var apiPlainJson = /* @__PURE__ */ __name((value) => JSON.parse(stringify(value, (key, inner) => isLosslessNumber(inner) && !isSafeNumber(inner.value) ? inner.toString() : finite(key, inner)) ?? "null"), "apiPlainJson");
1354
+ var isBlank = /* @__PURE__ */ __name((value) => typeof value === "string" && value.trim() === "", "isBlank");
1125
1355
  var isVariables = /* @__PURE__ */ __name((value) => value !== null && typeof value === "object" && !Array.isArray(value) && !isLosslessNumber(value), "isVariables");
1126
1356
  var graphqlVariables = /* @__PURE__ */ __name((operation, body, fields2) => {
1127
1357
  const { binding } = operation;
@@ -1142,7 +1372,7 @@ var graphqlVariables = /* @__PURE__ */ __name((operation, body, fields2) => {
1142
1372
  throw new CliError("validation_error", `${operation.command} has no variable ${unknown2.join(", ")}`, {
1143
1373
  sent: false
1144
1374
  });
1145
- const missing = Object.entries(binding.variables).filter(([name, type]) => type.endsWith("!") && variables[name] == null).map(([name]) => `--${apiFlagOf(name)}`);
1375
+ const missing = Object.entries(binding.variables).filter(([name, type]) => type.endsWith("!") && (variables[name] == null || isBlank(variables[name]))).map(([name]) => `--${apiFlagOf(name)}`);
1146
1376
  if (missing.length > 0)
1147
1377
  throw new CliError("validation_error", `${operation.command} needs ${missing.join(", ")}`, { sent: false });
1148
1378
  return variables;
@@ -1169,7 +1399,7 @@ var flagValue = /* @__PURE__ */ __name((operation, name, raw, type) => {
1169
1399
  return raw;
1170
1400
  }, "flagValue");
1171
1401
 
1172
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/cli/service-api-manifest.js
1402
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/cli/service-api-manifest.js
1173
1403
  var manifestBaseUrl = /* @__PURE__ */ __name((manifest, given, variables = {}) => {
1174
1404
  const server = manifest.servers?.[0];
1175
1405
  if (given === void 0 && !server)
@@ -1297,12 +1527,12 @@ var nextPage = /* @__PURE__ */ __name((pagination, input, answer, headers) => {
1297
1527
  }
1298
1528
  }, "nextPage");
1299
1529
 
1300
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/sends/guard.js
1530
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/sends/guard.js
1301
1531
  import { randomUUID } from "node:crypto";
1302
1532
 
1303
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/sends/flood.js
1533
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/sends/flood.js
1304
1534
  import { mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "node:fs";
1305
- import { dirname, join } from "node:path";
1535
+ import { dirname as dirname2, join } from "node:path";
1306
1536
  var MOST_DEADLINES = 50;
1307
1537
  var LIMITED_HOLD_MS = 60 * 60 * 1e3;
1308
1538
  var FROZEN_HOLD_MS = 24 * 60 * 60 * 1e3;
@@ -1376,7 +1606,7 @@ var FloodMemory = class {
1376
1606
  }
1377
1607
  #write({ sendBlock, ...rest }) {
1378
1608
  const state = sendBlock ? { ...rest, sendBlock: { ...sendBlock, until: sendBlock.until ?? NO_END } } : rest;
1379
- mkdirSync(dirname(this.path), { recursive: true, mode: 448 });
1609
+ mkdirSync(dirname2(this.path), { recursive: true, mode: 448 });
1380
1610
  const temporary = `${this.path}.${process.pid}.tmp`;
1381
1611
  writeFileSync(temporary, `${JSON.stringify(state)}
1382
1612
  `, { mode: 384 });
@@ -1384,39 +1614,39 @@ var FloodMemory = class {
1384
1614
  }
1385
1615
  };
1386
1616
 
1387
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/sends/journal.js
1617
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/sends/journal.js
1388
1618
  import { appendFileSync, mkdirSync as mkdirSync3, readFileSync as readFileSync3 } from "node:fs";
1389
- import { dirname as dirname3, join as join2 } from "node:path";
1619
+ import { dirname as dirname4, join as join2 } from "node:path";
1390
1620
 
1391
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/sends/file-lock.js
1621
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/sends/file-lock.js
1392
1622
  import { closeSync, mkdirSync as mkdirSync2, openSync, statSync, unlinkSync } from "node:fs";
1393
- import { dirname as dirname2 } from "node:path";
1623
+ import { dirname as dirname3 } from "node:path";
1394
1624
  var LOCK_WAIT_MS = 5e3;
1395
1625
  var LOCK_STALE_MS = 3e4;
1396
1626
  var RETRY_MS = 20;
1397
1627
  var pause = new Int32Array(new SharedArrayBuffer(4));
1398
- var withFileLock = /* @__PURE__ */ __name((path2, what, body, waitMs = LOCK_WAIT_MS) => {
1628
+ var withFileLock = /* @__PURE__ */ __name((path2, what2, body, waitMs = LOCK_WAIT_MS) => {
1399
1629
  const lock = lockFor(path2);
1400
1630
  const deadline = Date.now() + waitMs;
1401
1631
  while (!taken(lock)) {
1402
1632
  if (Date.now() >= deadline)
1403
- throw lockTimeout(what, waitMs, lock);
1633
+ throw lockTimeout(what2, waitMs, lock);
1404
1634
  Atomics.wait(pause, 0, 0, RETRY_MS);
1405
1635
  }
1406
1636
  return holding(lock, body);
1407
1637
  }, "withFileLock");
1408
- var withFileLockAsync = /* @__PURE__ */ __name(async (path2, what, body, waitMs = LOCK_WAIT_MS, sleep = realSleep) => {
1638
+ var withFileLockAsync = /* @__PURE__ */ __name(async (path2, what2, body, waitMs = LOCK_WAIT_MS, sleep = realSleep) => {
1409
1639
  const lock = lockFor(path2);
1410
1640
  const deadline = Date.now() + waitMs;
1411
1641
  while (!taken(lock)) {
1412
1642
  if (Date.now() >= deadline)
1413
- throw lockTimeout(what, waitMs, lock);
1643
+ throw lockTimeout(what2, waitMs, lock);
1414
1644
  await sleep(RETRY_MS);
1415
1645
  }
1416
1646
  return holding(lock, body);
1417
1647
  }, "withFileLockAsync");
1418
1648
  var lockFor = /* @__PURE__ */ __name((path2) => {
1419
- mkdirSync2(dirname2(path2), { recursive: true, mode: 448 });
1649
+ mkdirSync2(dirname3(path2), { recursive: true, mode: 448 });
1420
1650
  return `${path2}.lock`;
1421
1651
  }, "lockFor");
1422
1652
  var taken = /* @__PURE__ */ __name((lock) => {
@@ -1446,7 +1676,7 @@ var holding = /* @__PURE__ */ __name((lock, body) => {
1446
1676
  }
1447
1677
  }
1448
1678
  }, "holding");
1449
- var lockTimeout = /* @__PURE__ */ __name((what, waitMs, lock) => new CliError("timeout", `${what} stayed locked for ${waitMs / 1e3}s (${lock})`), "lockTimeout");
1679
+ var lockTimeout = /* @__PURE__ */ __name((what2, waitMs, lock) => new CliError("timeout", `${what2} stayed locked for ${waitMs / 1e3}s (${lock})`), "lockTimeout");
1450
1680
  var lockTime = /* @__PURE__ */ __name((lock) => {
1451
1681
  try {
1452
1682
  return statSync(lock).mtimeMs;
@@ -1455,7 +1685,7 @@ var lockTime = /* @__PURE__ */ __name((lock) => {
1455
1685
  }
1456
1686
  }, "lockTime");
1457
1687
 
1458
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/sends/journal.js
1688
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/sends/journal.js
1459
1689
  var sendsPathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join2(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state, "sends", `${profile}.jsonl`), "sendsPathFor");
1460
1690
  var SendJournal = class {
1461
1691
  static {
@@ -1491,7 +1721,7 @@ var SendJournal = class {
1491
1721
  resource: this.resource,
1492
1722
  allow: LOG_ATTRIBUTES
1493
1723
  });
1494
- mkdirSync3(dirname3(this.path), { recursive: true, mode: 448 });
1724
+ mkdirSync3(dirname4(this.path), { recursive: true, mode: 448 });
1495
1725
  appendFileSync(this.path, `${JSON.stringify(record2)}
1496
1726
  `, { mode: 384 });
1497
1727
  }
@@ -1532,7 +1762,7 @@ var withSendId = /* @__PURE__ */ __name((entry) => {
1532
1762
  return cid === void 0 || rest.sendId !== void 0 ? rest : { ...rest, sendId: String(cid) };
1533
1763
  }, "withSendId");
1534
1764
 
1535
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/sends/recipients.js
1765
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/sends/recipients.js
1536
1766
  import { existsSync, readFileSync as readFileSync4, rmSync } from "node:fs";
1537
1767
  import { join as join3 } from "node:path";
1538
1768
  var recipientsPathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join3(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state, "profiles", `${profile}.recipients.json`), "recipientsPathFor");
@@ -1644,7 +1874,7 @@ var RecipientList = class {
1644
1874
  }
1645
1875
  };
1646
1876
 
1647
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/sends/guard.js
1877
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/sends/guard.js
1648
1878
  var HOUR_MS = 60 * 60 * 1e3;
1649
1879
  var countsTowardLimit = /* @__PURE__ */ __name(({ kind: kind2 = "message", action, notify }) => kind2 === "message" || kind2 === "forward" || kind2 === "edit" || kind2 === "delete" || kind2 === "pin" && notify === true || action === "create" || action === "members.add" || action === "requests.accept" || action === "join" || action === "contact-import", "countsTowardLimit");
1650
1880
  var weightOf = /* @__PURE__ */ __name(({ kind: kind2 = "message", action, count, people }) => kind2 === "delete" || kind2 === "message" && action === void 0 ? Math.max(1, count ?? 1) : action === "create" || action === "members.add" || action === "requests.accept" || action === "contact-import" ? Math.max(1, people ?? count ?? 1) : 1, "weightOf");
@@ -1832,7 +2062,569 @@ var guardFor = /* @__PURE__ */ __name((app, settings, warn, env = process.env, a
1832
2062
  }), "guardFor");
1833
2063
  var journalFailure = /* @__PURE__ */ __name((error) => error?.code ?? (error instanceof Error ? error.name : "error"), "journalFailure");
1834
2064
 
1835
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/sends/keyed-guard.js
2065
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/cli/command-runs.js
2066
+ import { AsyncLocalStorage } from "node:async_hooks";
2067
+ var runSettings = /* @__PURE__ */ __name((flag, saved = {}) => {
2068
+ const record2 = flag ?? saved.record ?? true;
2069
+ return {
2070
+ record: record2,
2071
+ keepFailedRuns: record2 || flag !== false,
2072
+ keepRunsForDays: saved.keepRunsForDays ?? KEEP_RUNS_FOR_DAYS,
2073
+ keepSuccessfulRunsForDays: saved.keepSuccessfulRunsForDays ?? KEEP_SUCCESSFUL_RUNS_FOR_DAYS,
2074
+ keepStoreRunsForDays: saved.keepStoreRunsForDays ?? KEEP_STORE_RUNS_FOR_DAYS,
2075
+ runsSizeLimitMb: saved.runsSizeLimitMb ?? RUNS_SIZE_LIMIT_MB
2076
+ };
2077
+ }, "runSettings");
2078
+ var SKIPPED = /* @__PURE__ */ new Set(["runs", "help"]);
2079
+ var pathOf = /* @__PURE__ */ __name((command) => {
2080
+ const words = [];
2081
+ for (let at2 = command; at2?.parent; at2 = at2.parent)
2082
+ words.unshift(at2.name());
2083
+ return words;
2084
+ }, "pathOf");
2085
+ var tracker = /* @__PURE__ */ __name((options, typed) => {
2086
+ let recording;
2087
+ const open2 = /* @__PURE__ */ __name((program, words, flag, format, lifetime) => {
2088
+ recording = void 0;
2089
+ if (SKIPPED.has(words[0] ?? ""))
2090
+ return;
2091
+ const environment = environmentOf(program);
2092
+ let saved = {};
2093
+ try {
2094
+ saved = options.settings();
2095
+ } catch {
2096
+ saved = { recordInput: false };
2097
+ }
2098
+ let profile;
2099
+ try {
2100
+ profile = options.profile?.() || void 0;
2101
+ } catch {
2102
+ }
2103
+ const settings = runSettings(flag, saved);
2104
+ const agent = options.agent ?? environment.agent !== void 0;
2105
+ const streams = options.streams ?? environment.streams;
2106
+ const env = options.env ?? environment.env;
2107
+ const command = `${agent ? "mcp " : ""}${words.join(" ") || options.app.command}`;
2108
+ const caller = environment.agent?.caller;
2109
+ recording = startRecording({
2110
+ app: options.app,
2111
+ command,
2112
+ ...profile === void 0 ? {} : { profile },
2113
+ record: keepsSuccess({
2114
+ record: settings.record,
2115
+ fromFlag: flag !== void 0,
2116
+ env: env ?? process.env,
2117
+ caller,
2118
+ persistent: lifetime === "persistent"
2119
+ }),
2120
+ keepFailed: settings.keepFailedRuns,
2121
+ keepDays: settings.keepRunsForDays,
2122
+ keepSuccessDays: settings.keepSuccessfulRunsForDays,
2123
+ keepStoreDays: settings.keepStoreRunsForDays,
2124
+ maxBytes: settings.runsSizeLimitMb * 1024 * 1024,
2125
+ trace: false,
2126
+ format,
2127
+ ...streams ? { streams } : {},
2128
+ ...env ? { env } : {},
2129
+ context: runContextOf({
2130
+ bin: options.app.command,
2131
+ command: words.length > 0 ? command : "",
2132
+ program: rootOf(program),
2133
+ ...environment.argv ?? typed ? { argv: environment.argv ?? typed } : {},
2134
+ env: env ?? process.env,
2135
+ recordInput: saved.recordInput ?? true,
2136
+ caller
2137
+ })
2138
+ });
2139
+ }, "open");
2140
+ const finish = /* @__PURE__ */ __name(() => {
2141
+ const done = recording;
2142
+ recording = void 0;
2143
+ return done;
2144
+ }, "finish");
2145
+ return {
2146
+ start(action) {
2147
+ const flags = action.optsWithGlobals();
2148
+ const json = flags.json !== void 0 && flags.json !== false || Boolean(flags.jsonl);
2149
+ open2(action, pathOf(action), flags.record, options.format?.() ?? (json ? "json" : "pretty"), metaOf(action).lifetime);
2150
+ },
2151
+ async succeed() {
2152
+ await finish()?.succeed();
2153
+ },
2154
+ async fail(error) {
2155
+ await finish()?.fail(options.recognise ? options.recognise(error) : error);
2156
+ },
2157
+ runId: /* @__PURE__ */ __name(() => recording?.runId, "runId"),
2158
+ events: /* @__PURE__ */ __name((event) => recording?.events(event), "events"),
2159
+ open: open2
2160
+ };
2161
+ }, "tracker");
2162
+ var commandRuns = /* @__PURE__ */ __name((options) => tracker(options), "commandRuns");
2163
+ var parses = new AsyncLocalStorage();
2164
+ var commandRunId = /* @__PURE__ */ __name(() => parses.getStore()?.runs.runId(), "commandRunId");
2165
+ var providerEvent = /* @__PURE__ */ __name((event) => {
2166
+ const parse2 = parses.getStore();
2167
+ if (parse2)
2168
+ parse2.runs.events(event);
2169
+ else
2170
+ runEvent(event);
2171
+ }, "providerEvent");
2172
+ var providerRequest = /* @__PURE__ */ __name((operation, sink = providerEvent, call2 = {}) => {
2173
+ const { bytes: sent, ...shape } = call2;
2174
+ const wire = { operation, level: "wire", ...call2.attempt === void 0 ? currentAttempt() : {}, ...shape };
2175
+ sink({ event: "request", ...wire, ...sent === void 0 ? {} : { bytes: sent } });
2176
+ const started = performance.now();
2177
+ return ({ status, error, errorCode, providerError, bytes, counts, ids: ids2 } = {}) => {
2178
+ const failed = error !== void 0 || errorCode !== void 0;
2179
+ const key = providerErrorKey(providerError);
2180
+ sink({
2181
+ event: "response",
2182
+ ...wire,
2183
+ ...status === void 0 ? {} : { status },
2184
+ durationMs: Math.round(performance.now() - started),
2185
+ outcome: failed ? "error" : "ok",
2186
+ ...failed ? { errorCode: errorCode ?? (isCliError(error) ? error.code : "provider_error") } : {},
2187
+ ...key ? { providerError: key } : {},
2188
+ ...bytes === void 0 ? {} : { bytes },
2189
+ ...counts ? { counts } : {},
2190
+ ...ids2 ? { ids: ids2 } : {}
2191
+ });
2192
+ };
2193
+ }, "providerRequest");
2194
+ var pathFromArgs = /* @__PURE__ */ __name((program, args, profileWord) => {
2195
+ const words = [];
2196
+ let at2 = program;
2197
+ let skipped = !profileWord;
2198
+ for (const arg of args) {
2199
+ if (arg.startsWith("-"))
2200
+ continue;
2201
+ const next = at2.commands.find((one) => one.name() === arg || one.aliases().includes(arg));
2202
+ if (next) {
2203
+ words.push(arg);
2204
+ at2 = next;
2205
+ } else if (words.length === 0 && !skipped)
2206
+ skipped = true;
2207
+ else
2208
+ break;
2209
+ }
2210
+ return words;
2211
+ }, "pathFromArgs");
2212
+ var isHelpExit = /* @__PURE__ */ __name((error) => {
2213
+ const { code, exitCode } = error ?? {};
2214
+ return typeof code === "string" && code.startsWith("commander.") && (exitCode === 0 || code === "commander.help");
2215
+ }, "isHelpExit");
2216
+ var recordRuns = /* @__PURE__ */ __name((program, options) => {
2217
+ program.option("--record", "keep this run even where the config says record false; record_input false leaves the typed words out").option("--no-record", "do not keep this run, even if it fails");
2218
+ program.hook("preAction", (_root, action) => {
2219
+ const parse2 = parses.getStore();
2220
+ if (!parse2)
2221
+ return;
2222
+ parse2.started = true;
2223
+ parse2.runs.start(action);
2224
+ });
2225
+ const parseAsync = program.parseAsync.bind(program);
2226
+ program.parseAsync = (argv, settings) => {
2227
+ const args = settings?.from === "user" ? argv ?? [] : (argv ?? process.argv).slice(2);
2228
+ const parse2 = { runs: tracker(options, args), started: false };
2229
+ return parses.run(parse2, async () => {
2230
+ try {
2231
+ const parsed = await parseAsync(argv, settings);
2232
+ await parse2.runs.succeed();
2233
+ return parsed;
2234
+ } catch (error) {
2235
+ if (!isHelpExit(error) && !wasSettled(error)) {
2236
+ try {
2237
+ if (!parse2.started) {
2238
+ const flag = args.includes("--no-record") ? false : args.includes("--record") ? true : void 0;
2239
+ const json = args.some((arg) => arg === "--json" || arg.startsWith("--json=") || arg === "--jsonl");
2240
+ const words = pathFromArgs(program, args, options.profile !== void 0);
2241
+ const format = options.format?.() ?? (json ? "json" : "pretty");
2242
+ parse2.runs.open(program, words, flag, format);
2243
+ }
2244
+ await parse2.runs.fail(error);
2245
+ } catch {
2246
+ }
2247
+ }
2248
+ throw error;
2249
+ }
2250
+ });
2251
+ };
2252
+ }, "recordRuns");
2253
+
2254
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/cli/bot/api-http.js
2255
+ var LARGEST_ANSWER = 16 * 1024 * 1024;
2256
+ var segment = /* @__PURE__ */ __name((name, value) => {
2257
+ if (value === void 0 || value === "" || value === "." || value === "..")
2258
+ throw new CliError("validation_error", `${name} must name one item; an empty, "." or ".." id is refused`);
2259
+ return encodeURIComponent(value);
2260
+ }, "segment");
2261
+ var unsendableBody = /* @__PURE__ */ __name((operation) => {
2262
+ const type = operation.request?.contentType;
2263
+ return type === void 0 || sendsBytes(operation) ? void 0 : `it sends ${type}, which the generated command cannot send`;
2264
+ }, "unsendableBody");
2265
+ var httpApiRequest = /* @__PURE__ */ __name((operation, input, baseUrl) => {
2266
+ const { binding } = operation;
2267
+ if (binding.kind !== "http" && binding.kind !== "graphql")
2268
+ throw new CliError("configuration_error", `${operation.command} is not an HTTP operation`);
2269
+ if (unsendableBody(operation))
2270
+ throw new CliError("validation_error", `${operation.command} sends ${operation.request?.contentType}, which the generated command cannot send; nothing was sent`, { sent: false });
2271
+ if (operation.response?.sensitive)
2272
+ throw new CliError("validation_error", `${operation.command} answers with a credential, which the generated command never prints; nothing was sent`, { sent: false });
2273
+ if (binding.kind === "graphql")
2274
+ return graphqlRequest(operation, binding, input, baseUrl);
2275
+ if (Object.keys(input.fields).length > 0)
2276
+ throw new CliError("configuration_error", `${operation.command} has body fields as flags, which HTTP cannot send`);
2277
+ if (!/^\/(?!\/)/.test(binding.path))
2278
+ throw new CliError("configuration_error", `${operation.command} has a path that does not start with one /`);
2279
+ const base = new URL(baseUrl);
2280
+ const path2 = binding.path.replace(/\{([^}]+)\}/g, (_, name) => segment(name, input.path[name]));
2281
+ const url = new URL(`${base.pathname.replace(/\/$/, "")}${path2}`, base.origin);
2282
+ for (const [name, raw] of Object.entries(input.query)) {
2283
+ const parameter = operation.parameters.find((one) => one.in === "query" && one.name === name);
2284
+ if (parameter?.schema.type === "array")
2285
+ for (const item of raw.split(","))
2286
+ url.searchParams.append(name, item.trim());
2287
+ else
2288
+ url.searchParams.set(name, raw);
2289
+ }
2290
+ const headers = new Headers(input.headers);
2291
+ headers.set("accept", "application/json");
2292
+ if (sendsBytes(operation)) {
2293
+ if (input.bytes === void 0)
2294
+ return { method: binding.method, url, headers };
2295
+ headers.set("content-type", operation.request?.contentType);
2296
+ return { method: binding.method, url, headers, body: input.bytes };
2297
+ }
2298
+ const body = input.body?.trim() ? input.body : void 0;
2299
+ if (body !== void 0)
2300
+ parseApiJson(body);
2301
+ if (body !== void 0)
2302
+ headers.set("content-type", "application/json");
2303
+ return { method: binding.method, url, headers, ...body === void 0 ? {} : { body } };
2304
+ }, "httpApiRequest");
2305
+ var graphqlRequest = /* @__PURE__ */ __name((operation, binding, input, baseUrl) => {
2306
+ const variables = graphqlVariables(operation, input.body, input.fields);
2307
+ const headers = new Headers(input.headers);
2308
+ headers.set("accept", "application/json");
2309
+ headers.set("content-type", "application/json");
2310
+ const query = graphqlDocument(binding, input.selection);
2311
+ return { method: "POST", url: new URL(baseUrl), headers, body: apiJson({ query, variables }), redirect: "error" };
2312
+ }, "graphqlRequest");
2313
+ var templateOf = /* @__PURE__ */ __name((path2) => path2.replace(/\{([^}]+)\}/g, ":$1"), "templateOf");
2314
+ var endpointOf = /* @__PURE__ */ __name((operation) => operation.binding.kind === "http" ? templateOf(operation.binding.path) : operation.binding.kind === "graphql" ? `${operation.binding.operation}/${operation.binding.field}` : "", "endpointOf");
2315
+ var GRAPHQL_CODES = {
2316
+ UNAUTHENTICATED: "authentication_error",
2317
+ AUTHENTICATION_ERROR: "authentication_error",
2318
+ FORBIDDEN: "permission_error",
2319
+ RATELIMITED: "rate_limited",
2320
+ BAD_USER_INPUT: "validation_error",
2321
+ GRAPHQL_VALIDATION_FAILED: "validation_error",
2322
+ INVALID_INPUT: "validation_error"
2323
+ };
2324
+ var NOTHING_RAN = /* @__PURE__ */ new Set(["authentication_error", "permission_error", "rate_limited", "validation_error"]);
2325
+ var graphqlAnswer = /* @__PURE__ */ __name((options, operation, answer) => {
2326
+ const { binding } = operation;
2327
+ if (binding.kind !== "graphql")
2328
+ return answer;
2329
+ const { data, errors } = answer ?? {};
2330
+ if (Array.isArray(errors) && errors.length > 0) {
2331
+ const own = options.failure?.(200, answer, operation);
2332
+ if (own)
2333
+ throw own;
2334
+ const raw = errors[0]?.extensions?.code;
2335
+ const code = typeof raw === "string" && /^[A-Z][A-Z0-9_]{0,40}$/.test(raw) ? raw : void 0;
2336
+ const known = code && GRAPHQL_CODES[code] || "provider_error";
2337
+ const writes = operation.effect !== "read";
2338
+ if (writes && (!NOTHING_RAN.has(known) || data?.[binding.field] != null))
2339
+ return outcomeUnknown(options.service);
2340
+ throw new CliError(known, `${options.service} refused ${operation.command}${code ? ` (${code})` : ""}`, {
2341
+ retryable: known === "rate_limited"
2342
+ });
2343
+ }
2344
+ if (!data || !(binding.field in data))
2345
+ throw new CliError("invalid_response", `${options.service} answered ${operation.command} without data.${binding.field}`);
2346
+ return data[binding.field];
2347
+ }, "graphqlAnswer");
2348
+ var outcomeUnknown = /* @__PURE__ */ __name((service) => {
2349
+ throw new CliError("outcome_unknown", `${service} did not confirm a write; check it before repeating the write`, {
2350
+ retryable: false
2351
+ });
2352
+ }, "outcomeUnknown");
2353
+ var answerOf = /* @__PURE__ */ __name(async (response, maxBytes) => {
2354
+ if (response.status === 204 || !response.body || response.headers.get("content-length") === "0")
2355
+ return {};
2356
+ return readJsonResponse(response, { maxBytes });
2357
+ }, "answerOf");
2358
+ var httpApiExchange = /* @__PURE__ */ __name((options) => async (command, operation, request) => {
2359
+ const writes = operation.effect !== "read";
2360
+ const template = endpointOf(operation);
2361
+ const end = providerRequest(`${request.method} ${template}`, void 0, {
2362
+ method: request.method,
2363
+ endpointTemplate: template,
2364
+ transport: "http"
2365
+ });
2366
+ let response;
2367
+ try {
2368
+ response = await options.fetch(command)(request.url, {
2369
+ method: request.method,
2370
+ headers: request.headers,
2371
+ ...request.body === void 0 ? {} : { body: request.body },
2372
+ ...request.redirect === void 0 ? {} : { redirect: request.redirect }
2373
+ });
2374
+ } catch (error) {
2375
+ const failed = unanswered(options.service, writes, error);
2376
+ end({ error: failed });
2377
+ throw failed;
2378
+ }
2379
+ const { status } = response;
2380
+ let answer;
2381
+ try {
2382
+ answer = await answerOf(response, options.maxBytes ?? LARGEST_ANSWER);
2383
+ } catch {
2384
+ if (response.ok) {
2385
+ end({ status });
2386
+ throw unreadable(options.service, writes, status);
2387
+ }
2388
+ }
2389
+ if (!response.ok) {
2390
+ const failed = status >= 500 && writes ? refusal(options.service, operation, response, writes) : options.failure?.(status, answer, operation) ?? refusal(options.service, operation, response, writes, innerStatus(answer));
2391
+ end({ status, error: failed });
2392
+ throw failed;
2393
+ }
2394
+ try {
2395
+ const result = graphqlAnswer(options, operation, answer);
2396
+ const refused = operation.binding.kind === "http" ? options.failedAnswer?.(answer, operation) : void 0;
2397
+ if (refused)
2398
+ throw refused;
2399
+ end({ status });
2400
+ return { answer: result, headers: response.headers };
2401
+ } catch (error) {
2402
+ end({ status, error });
2403
+ throw error;
2404
+ }
2405
+ }, "httpApiExchange");
2406
+ var httpApiSend = /* @__PURE__ */ __name((options) => {
2407
+ const exchange = httpApiExchange(options);
2408
+ return async (command, operation, request) => (await exchange(command, operation, request)).answer;
2409
+ }, "httpApiSend");
2410
+ var httpApiExecutor = /* @__PURE__ */ __name((options) => async (command, operation, input) => {
2411
+ const request = httpApiRequest(operation, input, options.baseUrl);
2412
+ for (const [name, value] of Object.entries(await options.headers(command, operation)))
2413
+ request.headers.set(name, value);
2414
+ const send = /* @__PURE__ */ __name(() => httpApiSend(options)(command, operation, request), "send");
2415
+ const answer = operation.effect !== "read" ? await options.write(command, operation, send) : await (options.read ?? ((_command, _operation, call2) => call2()))(command, operation, send);
2416
+ renderAnswer(command, outputFor(command), itemOf(answer));
2417
+ }, "httpApiExecutor");
2418
+ var unanswered = /* @__PURE__ */ __name((service, writes, error) => {
2419
+ if (error instanceof CliError && (!writes || error.details?.sent === false))
2420
+ return error;
2421
+ if (writes)
2422
+ return new CliError("outcome_unknown", `${service} did not answer a write; check it before repeating the write`, {
2423
+ retryable: false
2424
+ });
2425
+ return error?.name === "TimeoutError" ? new CliError("timeout", `${service} did not answer in time`, { retryable: true }) : new CliError("network_error", `${service} could not be reached`, { retryable: true });
2426
+ }, "unanswered");
2427
+ var unreadable = /* @__PURE__ */ __name((service, writes, status) => writes ? new CliError("outcome_unknown", `${service} took the write but its answer could not be read; check it before repeating the write`, {
2428
+ status,
2429
+ retryable: false
2430
+ }) : new CliError("invalid_response", `${service} sent an answer that could not be read`, { status, retryable: true }), "unreadable");
2431
+ var innerStatus = /* @__PURE__ */ __name((answer) => {
2432
+ const find = /* @__PURE__ */ __name((value, depth, inDetails) => {
2433
+ if (depth > 5 || typeof value !== "object" || value === null || Array.isArray(value))
2434
+ return void 0;
2435
+ for (const [key, one] of Object.entries(value)) {
2436
+ if (inDetails && key === "status" && typeof one === "number" && one >= 400 && one < 600)
2437
+ return one;
2438
+ const found = find(one, depth + 1, inDetails || key === "details");
2439
+ if (found !== void 0)
2440
+ return found;
2441
+ }
2442
+ return void 0;
2443
+ }, "find");
2444
+ return find(answer, 0, false);
2445
+ }, "innerStatus");
2446
+ var refusal = /* @__PURE__ */ __name((service, operation, response, writes, inner) => {
2447
+ const { status } = response;
2448
+ if (status === 429) {
2449
+ const wait = providerWaitMs(response.headers, wallClock);
2450
+ return new CliError("rate_limited", `${service} asked to slow down; retry the command later`, {
2451
+ status,
2452
+ retryable: true,
2453
+ ...wait === void 0 ? {} : { retry_after_ms: wait }
2454
+ });
2455
+ }
2456
+ if (status >= 500 && writes)
2457
+ return new CliError("outcome_unknown", `${service} failed during a write; check it before repeating the write`, {
2458
+ status,
2459
+ retryable: false
2460
+ });
2461
+ if (status === 401)
2462
+ return new CliError("authentication_error", `${service} refused the sign-in; sign in again`, {
2463
+ reason: "auth.failed",
2464
+ status
2465
+ });
2466
+ if (status === 403)
2467
+ return new CliError("permission_error", `${service} denied ${operation.command} to this account`, {
2468
+ reason: "access.denied",
2469
+ status
2470
+ });
2471
+ const location = status >= 300 && status < 400 ? response.headers.get("location") : null;
2472
+ if (location !== null) {
2473
+ const to = URL.canParse(location, response.url || void 0) ? new URL(location, response.url || void 0) : void 0;
2474
+ const where = to ? `${to.origin}${to.pathname}` : "another address";
2475
+ return new CliError(statusToCode(status), `${service} moved ${operation.command} to ${where} (HTTP ${status}); nothing was sent there`, { status, retryable: false });
2476
+ }
2477
+ return new CliError(statusToCode(status), `${service} refused ${operation.command} (HTTP ${status})`, {
2478
+ status,
2479
+ retryable: status >= 500,
2480
+ ...inner === void 0 || inner === status ? {} : { inner_status: inner }
2481
+ });
2482
+ }, "refusal");
2483
+
2484
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/cli/messenger/ask.js
2485
+ import { openSync as openSync2 } from "node:fs";
2486
+ import { createInterface } from "node:readline";
2487
+ import { ReadStream } from "node:tty";
2488
+ var fromTerminal = /* @__PURE__ */ __name(async (question) => {
2489
+ if (!process.stdin.isTTY || !process.stderr.isTTY)
2490
+ return null;
2491
+ let input;
2492
+ try {
2493
+ input = new ReadStream(openSync2("/dev/tty", "r"));
2494
+ } catch {
2495
+ return null;
2496
+ }
2497
+ const reader = createInterface({ input, output: process.stderr, terminal: true });
2498
+ try {
2499
+ return await new Promise((resolve2, reject) => {
2500
+ const cancel = /* @__PURE__ */ __name(() => reject(new CliError("cancelled", "cancelled \u2014 nothing was done")), "cancel");
2501
+ reader.once("SIGINT", cancel);
2502
+ reader.once("close", cancel);
2503
+ reader.question(question, resolve2);
2504
+ });
2505
+ } finally {
2506
+ reader.close();
2507
+ input.destroy();
2508
+ }
2509
+ }, "fromTerminal");
2510
+ var what = /* @__PURE__ */ __name((key, { chatId, count, personIds, forEveryone }) => [
2511
+ key,
2512
+ forEveryone ? "for everyone" : void 0,
2513
+ count !== void 0 ? `${count} ${count === 1 ? "item" : "items"}` : void 0,
2514
+ personIds?.length ? `${personIds.length} ${personIds.length === 1 ? "person" : "people"}` : void 0,
2515
+ chatId !== null ? `in chat ${chatId}` : void 0
2516
+ ].filter(Boolean).join(", "), "what");
2517
+ var answerOf2 = /* @__PURE__ */ __name(async (command, question) => {
2518
+ const given = command.optsWithGlobals();
2519
+ if (given.json === true || given.jsonl === true)
2520
+ return null;
2521
+ return (environmentOf(command).answer ?? fromTerminal)(question);
2522
+ }, "answerOf");
2523
+ var terminalAsker = /* @__PURE__ */ __name((command) => async (key, request) => {
2524
+ if (environmentOf(command).agent)
2525
+ return;
2526
+ const flag = skipFlagFor(key);
2527
+ const given = command.optsWithGlobals();
2528
+ if (flag === "--yes" ? given.yes === true : given.allowDangerous === true)
2529
+ return;
2530
+ const machine = given.json === true || given.jsonl === true;
2531
+ const answer = machine ? null : await (environmentOf(command).answer ?? fromTerminal)(`${what(key, request)} \u2014 go ahead? [y/N] `);
2532
+ if (answer === null) {
2533
+ throw new CliError("confirmation_required", `${key} asks before it acts (its permission level is ask), and nobody is at a terminal to answer \u2014 add ${flag} to go ahead`, { permission: key });
2534
+ }
2535
+ if (!/^\s*y(es)?\s*$/i.test(answer))
2536
+ throw new CliError("cancelled", `${key}: not done \u2014 the answer was no`);
2537
+ }, "terminalAsker");
2538
+
2539
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/cli/permission-keys.js
2540
+ var HOUSEKEEPING = /* @__PURE__ */ new Set([
2541
+ "help",
2542
+ "guide",
2543
+ "config",
2544
+ "session",
2545
+ "doctor",
2546
+ "commands",
2547
+ "complete",
2548
+ "upgrade",
2549
+ "skill",
2550
+ "mcp",
2551
+ "runs"
2552
+ ]);
2553
+ var commandPathKey = /* @__PURE__ */ __name((path2) => path2[0] === void 0 || HOUSEKEEPING.has(path2[0]) && !KEYED_UNDER_HOUSEKEEPING.has(path2.join(".")) ? null : path2.join("."), "commandPathKey");
2554
+ var commandPermissions = /* @__PURE__ */ __name(({ keyOf: keyOf4 = commandPathKey, extra = [], defaults = {}, alsoChecks } = {}) => ({
2555
+ keyOf: keyOf4,
2556
+ extra: [AUTHORITY_KEY, ...extra],
2557
+ defaults: { ...DEFAULT_PERMISSIONS, ...defaults },
2558
+ ...alsoChecks ? { alsoChecks } : {}
2559
+ }), "commandPermissions");
2560
+ var pathOf2 = /* @__PURE__ */ __name((command) => {
2561
+ const words = [];
2562
+ for (let at2 = command; at2?.parent; at2 = at2.parent)
2563
+ words.unshift(at2.name());
2564
+ return words;
2565
+ }, "pathOf");
2566
+ var rootOf2 = /* @__PURE__ */ __name((command) => {
2567
+ let at2 = command;
2568
+ while (at2.parent)
2569
+ at2 = at2.parent;
2570
+ return at2;
2571
+ }, "rootOf");
2572
+ var everyCommand = /* @__PURE__ */ __name((command) => [command, ...command.commands.flatMap(everyCommand)], "everyCommand");
2573
+ var knownPermissionKeys = /* @__PURE__ */ __name((command, keyOf4 = (one) => keyForCommand(pathOf2(one)), extra = []) => {
2574
+ const known = /* @__PURE__ */ new Set();
2575
+ const add = /* @__PURE__ */ __name((key) => {
2576
+ for (let parts = key.split("."); parts.length > 0; parts = parts.slice(0, -1))
2577
+ known.add(parts.join("."));
2578
+ }, "add");
2579
+ if (typeof keyOf4 !== "function") {
2580
+ for (const one of everyCommand(rootOf2(command))) {
2581
+ const key = keyOf4.keyOf(pathOf2(one));
2582
+ if (key)
2583
+ add(key);
2584
+ }
2585
+ for (const key of [...keyOf4.extra, ...extra])
2586
+ add(key);
2587
+ return known;
2588
+ }
2589
+ for (const one of everyCommand(rootOf2(command))) {
2590
+ const own = keyOf4(one);
2591
+ const key = own === void 0 ? keyForCommand(pathOf2(one)) : own;
2592
+ if (key)
2593
+ add(key);
2594
+ }
2595
+ for (const key of [...WRITE_KEYS, ...extra])
2596
+ add(key);
2597
+ return known;
2598
+ }, "knownPermissionKeys");
2599
+ var RENAMED2 = /* @__PURE__ */ new WeakMap();
2600
+ var markRenamedPermissionKeys = /* @__PURE__ */ __name((command, renamed) => {
2601
+ if (renamed.size > 0)
2602
+ RENAMED2.set(command, renamed);
2603
+ }, "markRenamedPermissionKeys");
2604
+ var renamedPermissionKeys = /* @__PURE__ */ __name((command) => new Map(everyCommand(rootOf2(command)).flatMap((one) => [...RENAMED2.get(one) ?? []])), "renamedPermissionKeys");
2605
+ var knownBeside = /* @__PURE__ */ __name((key, known) => {
2606
+ const parent = key.split(".").slice(0, -1).join(".");
2607
+ const depth = parent === "" ? 1 : parent.split(".").length + 1;
2608
+ return [...known].filter((one) => one.split(".").length === depth && (parent === "" || one.startsWith(`${parent}.`))).sort();
2609
+ }, "knownBeside");
2610
+ var unknownPermissionKeys = /* @__PURE__ */ __name((levels, known) => Object.keys(levels).filter((key) => key !== CEILING_KEY && !known.has(key)), "unknownPermissionKeys");
2611
+ var unknownPermissionIssues = /* @__PURE__ */ __name((command, settings, tool, keyOf4) => {
2612
+ const saved = settings.savedPermissions ?? Object.keys(settings.permissions).filter((key) => key !== CEILING_KEY && settings.permissionSources[key] !== "flag").map((key) => ({ key, at: ["profiles", settings.profile, "permissions", key] }));
2613
+ return permissionIssues(saved, knownPermissionKeys(command, keyOf4), { file: settings.configPath, tool }, renamedPermissionKeys(command)).map(publicIssue);
2614
+ }, "unknownPermissionIssues");
2615
+ var refuseUnknownPermissionKeys = /* @__PURE__ */ __name((command, settings, tool, keyOf4) => {
2616
+ const issues = unknownPermissionIssues(command, settings, tool, keyOf4);
2617
+ if (issues.length > 0)
2618
+ throw new CliError("configuration_error", issueMessage(issues), { permission: issues[0]?.key });
2619
+ const flagged = Object.keys(settings.permissions).filter((key2) => settings.permissionSources[key2] === "flag");
2620
+ const [key] = unknownPermissionKeys(Object.fromEntries(flagged.map((one) => [one, true])), knownPermissionKeys(command, keyOf4));
2621
+ if (key === void 0)
2622
+ return;
2623
+ const now = renamedPermissionKeys(command).get(key);
2624
+ throw new CliError("validation_error", `--permission ${key} names no command${now === void 0 ? "" : `: its command moved, so use ${now}`}`, { permission: key });
2625
+ }, "refuseUnknownPermissionKeys");
2626
+
2627
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/sends/keyed-guard.js
1836
2628
  var keyedGuard = /* @__PURE__ */ __name((build, ask, levelOf, extra) => {
1837
2629
  let question;
1838
2630
  let answered = false;
@@ -1875,19 +2667,523 @@ var keyedGuard = /* @__PURE__ */ __name((build, ask, levelOf, extra) => {
1875
2667
  };
1876
2668
  }, "keyedGuard");
1877
2669
 
1878
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/sends/send-id.js
2670
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/sends/send-id.js
1879
2671
  import { randomBytes } from "node:crypto";
1880
2672
  var newSendId = /* @__PURE__ */ __name(() => randomBytes(8).readBigInt64BE().toString(), "newSendId");
1881
2673
  var newOperationId = newSendId;
1882
2674
 
1883
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/foreign-contacts.js
2675
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/cli/bot/api.js
2676
+ var apiPathOf = /* @__PURE__ */ __name((operation) => {
2677
+ const { command, group } = operation;
2678
+ if (!group)
2679
+ return [command];
2680
+ return [group, command.startsWith(`${group}-`) ? command.slice(group.length + 1) : command];
2681
+ }, "apiPathOf");
2682
+ var scalarOf = /* @__PURE__ */ __name((value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value) : void 0, "scalarOf");
2683
+ var generatedApiCommand = /* @__PURE__ */ __name((api) => {
2684
+ const group = new Command("api").description(api.description ?? "every operation of the official Bot API, generated from its schema");
2685
+ group.option("--store-token <profile>", "keep a returned authentication token only in this bot profile's OS keyring; never print it");
2686
+ const subgroups = /* @__PURE__ */ new Set();
2687
+ for (const operation of api.operations) {
2688
+ const binding = operation.binding.kind === "http" ? `${operation.binding.method} ${operation.binding.path}` : operation.binding.kind === "graphql" ? `${operation.binding.operation} ${operation.binding.field}` : operation.binding.name;
2689
+ const path2 = apiPathOf(operation);
2690
+ const command = annotate(new Command(path2.at(-1)), {
2691
+ effects: operation.effect === "read" ? REMOTE_READ : REMOTE_WRITE
2692
+ }).description(`${operation.summary ?? operation.id} \u2014 ${operation.effect} (${binding})`);
2693
+ for (const parameter of operation.parameters) {
2694
+ if (parameter.sensitive)
2695
+ continue;
2696
+ const option = new Option(`--${apiFlagOf(parameter.name)} <value>`, parameter.description?.split("\n")[0] ?? parameter.name);
2697
+ if (operation.binding.kind === "graphql" && parameter.in === "body")
2698
+ secretInput(option);
2699
+ if (parameter.required && parameter.in !== "body") {
2700
+ const fallback = scalarOf(parameter.schema.default);
2701
+ if (fallback === void 0)
2702
+ option.makeOptionMandatory();
2703
+ else
2704
+ option.default(fallback);
2705
+ }
2706
+ command.addOption(option);
2707
+ }
2708
+ if (operation.request && sendsBytes(operation)) {
2709
+ command.option("--body-file <path>", `the file to upload, sent as ${operation.request.contentType}; - is stdin`);
2710
+ } else if (operation.request) {
2711
+ command.addOption(secretInput(new Option("--body <json>", "the request body as JSON; - reads it from stdin")));
2712
+ command.option("--body-file <path>", "the request body from a JSON file; - is stdin");
2713
+ }
2714
+ marksUntrusted(command, API_UNTRUSTED);
2715
+ annotate(command, {
2716
+ origin: "generated",
2717
+ api_operation: operation.id,
2718
+ effects: { remote: operation.effect === "read" ? "read" : "write", local: "none" }
2719
+ });
2720
+ command.action(async function() {
2721
+ await api.before?.(this, operation);
2722
+ const options = this.opts();
2723
+ const input = { path: {}, query: {}, headers: {}, fields: {} };
2724
+ const tokenProfile = group.opts().storeToken;
2725
+ if (operation.response?.sensitive) {
2726
+ if (!tokenProfile?.trim())
2727
+ throw new CliError("validation_error", "--store-token <profile> is required for this credential-returning operation");
2728
+ input.tokenProfile = tokenProfile;
2729
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(tokenProfile))
2730
+ throw new CliError("validation_error", "--store-token needs a bot profile name using letters, digits, underscores or hyphens");
2731
+ } else if (tokenProfile !== void 0) {
2732
+ throw new CliError("validation_error", "--store-token is only supported for credential-returning operations");
2733
+ }
2734
+ for (const parameter of operation.parameters) {
2735
+ const raw = options[apiOptionKey(parameter.name)];
2736
+ if (raw === void 0)
2737
+ continue;
2738
+ if (parameter.required && parameter.in !== "body" && isBlank(raw))
2739
+ throw new CliError("validation_error", `--${apiFlagOf(parameter.name)} of ${operation.command} is empty`, {
2740
+ sent: false
2741
+ });
2742
+ if (parameter.in !== "body") {
2743
+ const problem = api.checkParameter(parameter.name, parameter.schema, raw);
2744
+ if (problem)
2745
+ throw new CliError("validation_error", problem);
2746
+ }
2747
+ const target = parameter.in === "body" ? input.fields : parameter.in === "header" ? input.headers : input[parameter.in];
2748
+ target[parameter.name] = raw;
2749
+ }
2750
+ if (sendsBytes(operation)) {
2751
+ const path3 = options.bodyFile;
2752
+ if (path3 === void 0 && operation.request?.required)
2753
+ throw new CliError("validation_error", `${operation.command} uploads a file: give --body-file <path>, or - for stdin`);
2754
+ if (path3 !== void 0) {
2755
+ input.bytes = (api.readBytes ?? ((_command, from) => readApiBytes(from)))(this, path3);
2756
+ input.bodySource = path3 === "-" ? "stdin" : "file";
2757
+ }
2758
+ await api.execute(this, operation, input);
2759
+ return;
2760
+ }
2761
+ const text2 = (api.readBody ?? ((_command, body2) => readApiBody(body2)))(this, options);
2762
+ if (options.body !== void 0)
2763
+ input.bodySource = options.body === "-" ? "stdin" : "argument";
2764
+ else if (options.bodyFile !== void 0)
2765
+ input.bodySource = options.bodyFile === "-" ? "stdin" : "file";
2766
+ const given = operation.binding.kind === "graphql" ? apiJson(graphqlVariables(operation, text2, input.fields)) : text2;
2767
+ if (operation.binding.kind === "graphql")
2768
+ input.fields = {};
2769
+ const body = operation.binding.kind === "rpc" ? text2 : api.checkBody ? api.checkBody(operation, given) : given;
2770
+ if (body !== void 0)
2771
+ input.body = body;
2772
+ await api.execute(this, operation, input);
2773
+ });
2774
+ api.configure?.(command, operation);
2775
+ const [first] = path2;
2776
+ const taken2 = group.commands.find((one) => one.name() === first);
2777
+ if (taken2 && (path2.length === 1 || !subgroups.has(taken2)))
2778
+ throw new CliError("configuration_error", `api ${first} is both a group and an operation: rename one`);
2779
+ if (path2.length === 1 || first === void 0) {
2780
+ group.addCommand(command);
2781
+ continue;
2782
+ }
2783
+ const subgroup = taken2 ?? annotate(new Command(first), { effects: NO_EFFECTS }).description(`the ${first} operations`);
2784
+ if (!taken2) {
2785
+ subgroups.add(subgroup);
2786
+ group.addCommand(subgroup);
2787
+ }
2788
+ subgroup.addCommand(command);
2789
+ }
2790
+ return group;
2791
+ }, "generatedApiCommand");
2792
+
2793
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/cli/service-api.js
2794
+ var serviceApiOperations = /* @__PURE__ */ __name((manifest) => {
2795
+ const reasonOf = /* @__PURE__ */ __name((operation) => operation.response?.sensitive ? "it returns a credential, which is never printed" : unsendableBody(operation), "reasonOf");
2796
+ return {
2797
+ offered: manifest.operations.filter((operation) => reasonOf(operation) === void 0),
2798
+ left: manifest.operations.flatMap((operation) => {
2799
+ const reason = reasonOf(operation);
2800
+ return reason ? [{ id: operation.id, reason }] : [];
2801
+ })
2802
+ };
2803
+ }, "serviceApiOperations");
2804
+ var MOST_PAGES = 500;
2805
+ var isObject2 = /* @__PURE__ */ __name((value) => !!value && typeof value === "object" && !Array.isArray(value), "isObject");
2806
+ var keyOf2 = /* @__PURE__ */ __name((operation) => ["api", ...apiPathOf(operation)].join("."), "keyOf");
2807
+ var pathOf3 = /* @__PURE__ */ __name((operation) => apiPathOf(operation).join(" "), "pathOf");
2808
+ var formerKeyOf = /* @__PURE__ */ __name((operation) => {
2809
+ const former = `api.${operation.command}`;
2810
+ return former === keyOf2(operation) ? void 0 : former;
2811
+ }, "formerKeyOf");
2812
+ var permissionsOf = /* @__PURE__ */ __name((operation) => operation.permissions ?? [], "permissionsOf");
2813
+ var destructive = /* @__PURE__ */ __name((operation) => operation.effect === "destructive" || operation.binding.kind === "http" && operation.binding.method === "DELETE", "destructive");
2814
+ var flagsOf = /* @__PURE__ */ __name(({ body = [], query = [] }) => [...body, ...query], "flagsOf");
2815
+ var valuesOf = /* @__PURE__ */ __name(({ values = {} }) => Object.entries(values), "valuesOf");
2816
+ var unlessOf = /* @__PURE__ */ __name(({ unless = {} }) => Object.entries(unless), "unlessOf");
2817
+ var whenOf = /* @__PURE__ */ __name((permission) => {
2818
+ const flags = flagsOf(permission);
2819
+ const values = valuesOf(permission).map(([field, listed2]) => `${field} ${listed2.join(" or ")}`);
2820
+ if (flags.length === 0 && values.length === 0)
2821
+ return void 0;
2822
+ const unless = unlessOf(permission).map(([field, listed2]) => `${field} ${listed2.join(" or ")}`);
2823
+ return `with ${[...values, ...flags.length > 0 ? [`${flags.join(" or ")} set`] : []].join(" or ")}${unless.length > 0 && flags.length > 0 ? `, unless ${unless.join(" or ")}` : ""}`;
2824
+ }, "whenOf");
2825
+ var holds = /* @__PURE__ */ __name((value, listed2) => typeof value === "string" && listed2.includes(value), "holds");
2826
+ var set = /* @__PURE__ */ __name((value) => value !== void 0 && value !== null && value !== false && value !== "false", "set");
2827
+ var applies = /* @__PURE__ */ __name((permission, body, input) => {
2828
+ const sends = /* @__PURE__ */ __name(([field, listed2]) => isObject2(body) && holds(body[field], listed2) || holds(input.query[field], listed2), "sends");
2829
+ const sent = permission.values === void 0 ? set : (value) => value !== void 0;
2830
+ const flagged = flagsOf(permission).some((name) => isObject2(body) && sent(body[name]) || sent(input.query[name]));
2831
+ return whenOf(permission) === void 0 || valuesOf(permission).some(sends) || flagged && !unlessOf(permission).some(sends);
2832
+ }, "applies");
2833
+ var serviceApiKeys = /* @__PURE__ */ __name((input, operation, call2) => {
2834
+ const body = call2.body?.trim() ? parseApiJson(call2.body) : void 0;
2835
+ const keys = [
2836
+ ...permissionsOf(operation).filter((permission) => applies(permission, body, call2)).map(({ key }) => key),
2837
+ ...(input.bodyPermissions?.[operation.command] ?? []).filter((one) => one.applies(body)).map(({ key }) => key)
2838
+ ];
2839
+ return [...new Set(keys)];
2840
+ }, "serviceApiKeys");
2841
+ var serviceApiPermissions = /* @__PURE__ */ __name((input) => {
2842
+ const checks = /* @__PURE__ */ new Map();
2843
+ for (const operation of input.manifest.operations) {
2844
+ checks.set(pathOf3(operation), [
2845
+ ...permissionsOf(operation).map((permission) => {
2846
+ const when = whenOf(permission);
2847
+ return when === void 0 ? permission.key : { key: permission.key, when };
2848
+ }),
2849
+ ...(input.bodyPermissions?.[operation.command] ?? []).map(({ key, when }) => ({ key, when }))
2850
+ ]);
2851
+ }
2852
+ const keys = [...new Set([...checks.values()].flat().map((one) => typeof one === "string" ? one : one.key))];
2853
+ return {
2854
+ extra: keys,
2855
+ alsoChecks: /* @__PURE__ */ __name((path2) => path2[0] === "api" ? checks.get(path2.slice(1).join(" ")) ?? [] : [], "alsoChecks"),
2856
+ defaults: {
2857
+ ...Object.fromEntries(keys.map((key) => [key, "ask"])),
2858
+ ...Object.fromEntries(input.manifest.operations.filter(destructive).map((operation) => [keyOf2(operation), "ask"]))
2859
+ }
2860
+ };
2861
+ }, "serviceApiPermissions");
2862
+ var rowOf = /* @__PURE__ */ __name((operation) => ({
2863
+ command: pathOf3(operation),
2864
+ group: apiPathOf(operation).length > 1 ? apiPathOf(operation)[0] : null,
2865
+ method: operation.binding.kind === "http" ? operation.binding.method : operation.binding.kind === "graphql" ? "POST" : "",
2866
+ path: operation.binding.kind === "http" ? operation.binding.path : operation.binding.kind === "graphql" ? `${operation.binding.operation} ${operation.binding.field}` : "",
2867
+ effect: operation.effect,
2868
+ summary: operation.summary ?? ""
2869
+ }), "rowOf");
2870
+ var API_QUERY = {
2871
+ entity: "api_operation",
2872
+ backend: "native",
2873
+ fields: [
2874
+ termField("effect", "enum", "effect:destructive", { values: ["read", "write", "destructive"] }),
2875
+ termField("tag", "kw", "tag:Pages")
2876
+ ]
2877
+ };
2878
+ var serviceApiCore = /* @__PURE__ */ __name((options) => {
2879
+ const { app, configuration, manifest } = options;
2880
+ const { offered: operations, left } = serviceApiOperations(manifest);
2881
+ if (!options.serverVariables)
2882
+ manifestBaseUrl(manifest, options.baseUrl);
2883
+ const baseUrlOf = /* @__PURE__ */ __name((command) => manifestBaseUrl(manifest, options.baseUrl, options.serverVariables?.(command)), "baseUrlOf");
2884
+ const own = serviceApiPermissions(options);
2885
+ const defaults = { ...own.defaults, ...configuration.permissions?.defaults };
2886
+ const unguarded = operations.filter((operation) => destructive(operation) && !permissionsOf(operation).some(({ key }) => key.endsWith(".delete")));
2887
+ if (unguarded.length > 0)
2888
+ throw new CliError("configuration_error", `${unguarded.map(({ command }) => command).join(", ")} can delete, but the manifest gives no delete key: generate with \`permissions\``);
2889
+ const named2 = new Set(manifest.operations.flatMap((operation) => permissionsOf(operation).map(({ key }) => key)));
2890
+ const unnamed = Object.values(options.bodyPermissions ?? {}).flat().filter(({ key }) => !named2.has(key));
2891
+ if (unnamed.length > 0)
2892
+ throw new CliError("configuration_error", `bodyPermissions name ${unnamed.map(({ key }) => key).join(", ")}, which the manifest does not: the keys come from \`permissions\``);
2893
+ const exchange = httpApiExchange({
2894
+ service: options.service,
2895
+ fetch: options.fetch,
2896
+ ...options.failure ? { failure: options.failure } : {},
2897
+ ...options.failedAnswer ? { failedAnswer: options.failedAnswer } : {}
2898
+ });
2899
+ const operationOf2 = /* @__PURE__ */ __name((name) => {
2900
+ const named3 = /* @__PURE__ */ __name((one) => pathOf3(one) === name || one.command === name || one.id === name, "named");
2901
+ const found = operations.find(named3);
2902
+ if (found)
2903
+ return found;
2904
+ const id2 = manifest.operations.find(named3)?.id ?? name;
2905
+ const why = options.excluded?.find((one) => one.id === name) ?? left.find((one) => one.id === id2);
2906
+ throw new CliError("not_found", why ? `${name} is not offered: ${why.reason}` : `no ${options.service} API operation ${name}; see ${app.command} api list`);
2907
+ }, "operationOf");
2908
+ const signed = /* @__PURE__ */ __name(async (command, operation, request) => {
2909
+ const { token } = options;
2910
+ const baseUrl = baseUrlOf(command);
2911
+ if (!underBase(request.url, baseUrl))
2912
+ throw new CliError("validation_error", `${operation.command} would leave ${baseUrl}`, { sent: false });
2913
+ await signRequest(manifest, operation, request, token && (() => token(command)));
2914
+ if (options.serverVariables)
2915
+ request.redirect = "manual";
2916
+ for (const [name, value] of Object.entries(options.headers?.(command, operation) ?? {}))
2917
+ request.headers.set(name, value);
2918
+ return request;
2919
+ }, "signed");
2920
+ const guardOf2 = /* @__PURE__ */ __name((command, extra, confirmed = [], own2) => {
2921
+ const { settings, env, renderer } = baseContext(command, configuration.resolveSettings);
2922
+ const levelOf = /* @__PURE__ */ __name((key) => levelFor(settings.permissions, key, defaults).level, "levelOf");
2923
+ const asker = terminalAsker(command);
2924
+ return keyedGuard((ask) => guardFor(app, { ...settings, sendsPerHour: Number.MAX_SAFE_INTEGER, permissionDefaults: defaults }, renderer.warn, env, ask), confirmed.length === 0 ? asker : async (_key, asked) => {
2925
+ const asking = [...own2 ? [own2] : [], ...extra].filter((key) => levelOf(key) === "ask" && !confirmed.includes(key));
2926
+ if (asking.length > 0)
2927
+ await asker(asking.join(" and "), asked);
2928
+ }, levelOf, extra);
2929
+ }, "guardOf");
2930
+ const readsFreely = /* @__PURE__ */ __name((command, operation, extra) => {
2931
+ if (operation.effect !== "read")
2932
+ return false;
2933
+ if (extra.length === 0)
2934
+ return true;
2935
+ guardOf2(command, extra).refuse({ chatId: null, kind: "edit", key: keyOf2(operation), operationId: newOperationId() });
2936
+ const { settings } = baseContext(command, configuration.resolveSettings);
2937
+ return extra.every((key) => levelFor(settings.permissions, key, defaults).level !== "ask");
2938
+ }, "readsFreely");
2939
+ const write2 = /* @__PURE__ */ __name(async (command, operation, extra, request, confirmed = []) => {
2940
+ const { run } = baseContext(command, configuration.resolveSettings);
2941
+ const operationId = newOperationId();
2942
+ const guard = guardOf2(command, extra, confirmed, keyOf2(operation));
2943
+ const guarded = { chatId: null, kind: "edit", key: keyOf2(operation), operationId };
2944
+ guard.refuse(guarded);
2945
+ try {
2946
+ const result = await guardedWrite(guard, guarded, () => run(async () => (await exchange(command, operation, request)).answer));
2947
+ return { operation_id: operationId, result };
2948
+ } catch (error) {
2949
+ if (isCliError(error) && error.code === "outcome_unknown")
2950
+ throw new CliError("outcome_unknown", error.message, { ...error.details, operation_id: operationId });
2951
+ throw error;
2952
+ }
2953
+ }, "write");
2954
+ const refuseBeforeBody = /* @__PURE__ */ __name((command, operation) => {
2955
+ const extra = permissionsOf(operation).filter((permission) => whenOf(permission) === void 0).map(({ key }) => key);
2956
+ if (operation.effect === "read" && extra.length === 0)
2957
+ return;
2958
+ guardOf2(command, extra).refuse({ chatId: null, kind: "edit", key: keyOf2(operation), operationId: newOperationId() });
2959
+ }, "refuseBeforeBody");
2960
+ return {
2961
+ operations,
2962
+ left,
2963
+ baseUrlOf,
2964
+ defaults,
2965
+ exchange,
2966
+ operationOf: operationOf2,
2967
+ readsFreely,
2968
+ refuseBeforeBody,
2969
+ signed,
2970
+ write: write2
2971
+ };
2972
+ }, "serviceApiCore");
2973
+ var serviceApiCommand = /* @__PURE__ */ __name((options) => {
2974
+ const { app, configuration, manifest } = options;
2975
+ const { operations, baseUrlOf, exchange, operationOf: operationOf2, readsFreely, refuseBeforeBody, signed, write: write2 } = serviceApiCore(options);
2976
+ const send = /* @__PURE__ */ __name(async (command, operation, request) => (await exchange(command, operation, request)).answer, "send");
2977
+ let schemas;
2978
+ const loaded = /* @__PURE__ */ __name(() => {
2979
+ if (!schemas)
2980
+ throw new CliError("configuration_error", "the api schemas were not loaded before the command ran");
2981
+ return schemas;
2982
+ }, "loaded");
2983
+ const load = /* @__PURE__ */ __name(async () => {
2984
+ schemas ??= await options.schemas();
2985
+ }, "load");
2986
+ const allPages = /* @__PURE__ */ __name(async (command, operation, input) => {
2987
+ const pagination = operation.pagination;
2988
+ if (pagination.style === "page" && pagination.start === void 0 && parameterValue(input, pagination.page) === void 0)
2989
+ throw new CliError("validation_error", `--all on ${operation.command} needs the first page: give --${pagination.page.name} 0 or 1, as ${options.service} counts`);
2990
+ const items = [];
2991
+ const asked = /* @__PURE__ */ new Set();
2992
+ const baseUrl = baseUrlOf(command);
2993
+ let call2 = input;
2994
+ let url;
2995
+ await baseContext(command, configuration.resolveSettings).run(async () => {
2996
+ for (let page = 0; ; page++) {
2997
+ if (page >= MOST_PAGES)
2998
+ throw new CliError("validation_error", `${operation.command} has more than ${MOST_PAGES} pages; narrow it with its own flags, or page it yourself`);
2999
+ const unsigned = httpApiRequest(operation, call2, baseUrl);
3000
+ if (url !== void 0)
3001
+ unsigned.url = new URL(url);
3002
+ const request = await signed(command, operation, unsigned);
3003
+ const key = `${request.url.href} ${request.body ?? ""}`;
3004
+ if (asked.has(key))
3005
+ throw new CliError("invalid_response", `${options.service} gave the same next page twice; nothing more read`);
3006
+ asked.add(key);
3007
+ const { answer, headers } = await exchange(command, operation, request);
3008
+ const step = nextPage(pagination, call2, answer, headers);
3009
+ for (const item of step.items)
3010
+ items.push(item);
3011
+ if (!step.next)
3012
+ return;
3013
+ if ("url" in step.next) {
3014
+ url = new URL(step.next.url, request.url);
3015
+ if (!underBase(url, baseUrl))
3016
+ throw new CliError("invalid_response", `${options.service} pointed the next page outside ${baseUrl}`);
3017
+ } else
3018
+ call2 = step.next.input;
3019
+ }
3020
+ });
3021
+ renderAnswer(command, outputFor(command), listOf(`api ${pathOf3(operation)}`, { items, limit: items.length, has_more: false }));
3022
+ }, "allPages");
3023
+ const refuseOwnFiles = /* @__PURE__ */ __name((command, path2) => {
3024
+ if (path2 === "-")
3025
+ return;
3026
+ const { env } = baseContext(command, configuration.resolveSettings);
3027
+ if (refusedPlace(path2, app, env))
3028
+ throw new CliError("validation_error", `--body-file may not read ${path2}: it holds sign-ins or state`);
3029
+ }, "refuseOwnFiles");
3030
+ const generated = generatedApiCommand({
3031
+ operations,
3032
+ checkParameter: /* @__PURE__ */ __name((name, schema2, raw) => checkApiParameter(name, schema2, raw, loaded()), "checkParameter"),
3033
+ before: refuseBeforeBody,
3034
+ checkBody: /* @__PURE__ */ __name((operation, text2) => checkApiBody(operation, text2, loaded()), "checkBody"),
3035
+ readBody: /* @__PURE__ */ __name((command, body) => {
3036
+ if (body.bodyFile !== void 0)
3037
+ refuseOwnFiles(command, body.bodyFile);
3038
+ return readApiBody(body);
3039
+ }, "readBody"),
3040
+ readBytes: /* @__PURE__ */ __name((command, path2) => {
3041
+ refuseOwnFiles(command, path2);
3042
+ return readApiBytes(path2);
3043
+ }, "readBytes"),
3044
+ configure: /* @__PURE__ */ __name((command, operation) => {
3045
+ if (operation.pagination && !operation.parameters.some(({ name }) => name === "all"))
3046
+ command.option("--all", "read every page, as the API pages it");
3047
+ command.hook("preAction", load);
3048
+ }, "configure"),
3049
+ execute: /* @__PURE__ */ __name(async (command, operation, input) => {
3050
+ const extra = serviceApiKeys(options, operation, input);
3051
+ const read = readsFreely(command, operation, extra);
3052
+ if (operation.pagination && command.opts().all === true) {
3053
+ if (!read)
3054
+ throw new CliError("validation_error", `--all reads only; this call of ${operation.command} is guarded by ${extra.join(", ") || "its write"}`);
3055
+ return allPages(command, operation, input);
3056
+ }
3057
+ const request = await signed(command, operation, httpApiRequest(operation, input, baseUrlOf(command)));
3058
+ const answer = read ? await baseContext(command, configuration.resolveSettings).run(() => send(command, operation, request)) : await write2(command, operation, extra, request);
3059
+ renderAnswer(command, outputFor(command), itemOf(answer));
3060
+ }, "execute")
3061
+ });
3062
+ const list = withQuery(annotate(new Command("list"), {
3063
+ effects: NO_EFFECTS,
3064
+ examples: [`${app.command} api list`, `${app.command} api list effect:destructive --json=command,path`]
3065
+ }), API_QUERY).description(`list every ${options.service} API operation this CLI offers, without calling ${options.service}`).action(function(words) {
3066
+ const terms = queryTerms(words, API_QUERY, "api list");
3067
+ const effect = terms.get("effect");
3068
+ const tag = terms.get("tag");
3069
+ const items = operations.filter((one) => (!effect || one.effect === effect) && (!tag || one.tags.includes(tag))).map(rowOf);
3070
+ renderAnswer(this, outputFor(this), listOf("api list", { items, limit: items.length, has_more: false }));
3071
+ });
3072
+ const show = annotate(new Command("show"), {
3073
+ effects: NO_EFFECTS,
3074
+ examples: [
3075
+ `${app.command} api show ${operations[0] ? JSON.stringify(pathOf3(operations[0])) : "<operation>"} --json`
3076
+ ]
3077
+ }).description(`show one operation's parameters and request schema, without calling ${options.service}`).argument("<operation>", "the operation as api list prints it (quoted), its old name, or its operation id").action(async function(name) {
3078
+ const operation = operationOf2(name);
3079
+ const definitions = await options.definitions();
3080
+ const schema2 = operation.request?.schema ? definitions[operation.request.schema] : void 0;
3081
+ renderAnswer(this, outputFor(this), itemOf({ operation, ...options.shown, ...schema2 ? { request_schema: schema2 } : {} }));
3082
+ });
3083
+ const graphql = operations.length > 0 && operations.every((one) => one.binding.kind === "graphql");
3084
+ const described = options.spec ?? (graphql ? "its GraphQL schema" : "its OpenAPI document");
3085
+ const group = annotate(new Command("api"), { effects: NO_EFFECTS }).description(`the raw ${options.service} API, one command per operation of ${described}`);
3086
+ group.addCommand(list).addCommand(show);
3087
+ for (const child of [...generated.commands])
3088
+ group.addCommand(child);
3089
+ markRenamedPermissionKeys(group, new Map(manifest.operations.flatMap((operation) => {
3090
+ const former = formerKeyOf(operation);
3091
+ return former ? [[former, keyOf2(operation)]] : [];
3092
+ })));
3093
+ return group;
3094
+ }, "serviceApiCommand");
3095
+ var flagText = /* @__PURE__ */ __name((raw) => Array.isArray(raw) ? raw.join(",") : String(raw), "flagText");
3096
+ var writerBody = /* @__PURE__ */ __name((operation, input, schemas) => {
3097
+ if (sendsBytes(operation) || operation.binding.kind === "rpc")
3098
+ return input;
3099
+ const graphql = operation.binding.kind === "graphql";
3100
+ const given = graphql ? apiJson(graphqlVariables(operation, input.body, input.fields ?? {})) : input.body;
3101
+ const body = checkApiBody(operation, given, schemas);
3102
+ return { ...input, ...graphql ? { fields: {} } : {}, ...body === void 0 ? {} : { body } };
3103
+ }, "writerBody");
3104
+ var serviceApiWriter = /* @__PURE__ */ __name((options) => {
3105
+ const { baseUrlOf, operationOf: operationOf2, signed, write: write2 } = serviceApiCore(options);
3106
+ return async (command, name, input, { confirmed } = {}) => {
3107
+ const operation = operationOf2(name);
3108
+ const undeclared = Object.keys(input.query).filter((one) => !operation.parameters.some((parameter) => parameter.in === "query" && parameter.name === one));
3109
+ const overriding = Object.keys(input.headers ?? {}).filter((one) => !operation.parameters.some((parameter) => parameter.in === "header" && parameter.name.toLowerCase() === one.toLowerCase()));
3110
+ if (undeclared.length > 0 || overriding.length > 0)
3111
+ throw new CliError("configuration_error", `${operation.command} does not take ${[...undeclared, ...overriding].join(", ")}`, { sent: false });
3112
+ const extra = serviceApiKeys(options, operation, input);
3113
+ if (operation.effect === "read" && extra.length === 0)
3114
+ throw new CliError("configuration_error", `${operation.command} is a read; send it with serviceApiCall`);
3115
+ const schemas = await options.schemas();
3116
+ const headers = Object.entries(input.headers ?? {});
3117
+ for (const parameter of operation.parameters) {
3118
+ const raw = parameter.in === "header" ? headers.find(([one]) => one.toLowerCase() === parameter.name.toLowerCase())?.[1] : parameter.in === "query" || parameter.in === "path" ? input[parameter.in][parameter.name] : void 0;
3119
+ if (parameter.required && raw !== void 0 && isBlank(flagText(raw)))
3120
+ throw new CliError("validation_error", `${parameter.name} of ${operation.command} is empty`, { sent: false });
3121
+ const problem = raw === void 0 ? void 0 : checkApiParameter(parameter.name, parameter.schema, flagText(raw), schemas);
3122
+ if (problem)
3123
+ throw new CliError("validation_error", problem);
3124
+ }
3125
+ const request = await signed(command, operation, httpApiRequest(operation, writerBody(operation, input, schemas), baseUrlOf(command)));
3126
+ return write2(command, operation, extra, request, confirmed);
3127
+ };
3128
+ }, "serviceApiWriter");
3129
+
3130
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/cli/service-api-call.js
3131
+ var hostsFetch = /* @__PURE__ */ __name((hosts, fetch, credentialScope) => hostFetch({ hosts, ...fetch ? { fetch } : {}, ...credentialScope ? { credentialScope } : {} }), "hostsFetch");
3132
+ var NO_COMMAND = new Command("source");
3133
+ var sender = /* @__PURE__ */ __name((options, writes) => {
3134
+ const baseUrl = manifestBaseUrl(options.manifest, options.baseUrl, options.serverVariables);
3135
+ const operations = new Map(options.manifest.operations.map((one) => [one.id, one]));
3136
+ const exchange = httpApiExchange({
3137
+ service: options.service,
3138
+ fetch: /* @__PURE__ */ __name(() => options.fetch, "fetch"),
3139
+ failure: options.failure,
3140
+ failedAnswer: options.failedAnswer
3141
+ });
3142
+ return async (id2, input) => {
3143
+ const operation = operations.get(id2);
3144
+ if (!operation)
3145
+ throw new CliError("configuration_error", `no ${options.service} API operation ${id2}`);
3146
+ if (!writes && operation.effect !== "read")
3147
+ throw new CliError("configuration_error", `${operation.command} is not a read; a source only reads`);
3148
+ const request = httpApiRequest(operation, input, baseUrl);
3149
+ if (!underBase(request.url, baseUrl))
3150
+ throw new CliError("validation_error", `${operation.command} would leave ${baseUrl}`, { sent: false });
3151
+ const extra = Object.entries(options.headers?.(operation) ?? {});
3152
+ for (const [name, value] of extra)
3153
+ request.headers.set(name, value);
3154
+ await signRequest(options.manifest, operation, request, options.token);
3155
+ if (extra.length || options.serverVariables)
3156
+ request.redirect = "manual";
3157
+ const { answer, headers } = await exchange(NO_COMMAND, operation, request);
3158
+ return { body: answer, headers };
3159
+ };
3160
+ }, "sender");
3161
+ var serviceApiCall = /* @__PURE__ */ __name((options) => {
3162
+ const withHeaders = sender(options, false);
3163
+ return Object.assign(async (id2, input) => (await withHeaders(id2, input)).body, {
3164
+ withHeaders
3165
+ });
3166
+ }, "serviceApiCall");
3167
+
3168
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/sends/profile-writes.js
3169
+ var levelsOf = /* @__PURE__ */ __name((writes, defaults) => {
3170
+ const settings = writes.settings();
3171
+ return { settings, defaults: { ...DEFAULT_PERMISSIONS, ...defaults, ...settings.permissionDefaults } };
3172
+ }, "levelsOf");
3173
+ var profileWriteGuard = /* @__PURE__ */ __name((writes, ask, builtIn, extra) => {
3174
+ const { settings, defaults } = levelsOf(writes, builtIn);
3175
+ return keyedGuard((asker) => guardFor(writes.app, { ...settings, sendsPerHour: Number.MAX_SAFE_INTEGER, permissionDefaults: defaults }, writes.warn ?? (() => {
3176
+ }), writes.env, asker), ask, (key) => levelFor(settings.permissions, key, defaults).level, extra);
3177
+ }, "profileWriteGuard");
3178
+
3179
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/foreign-contacts.js
1884
3180
  import { readFileSync as readFileSync5 } from "node:fs";
1885
3181
  import { join as join4 } from "node:path";
1886
3182
 
1887
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/state-folders.js
3183
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/state-folders.js
1888
3184
  var CRM_SHARED_FOLDERS = { files: "files", foreignContacts: "foreign-contacts" };
1889
3185
 
1890
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/foreign-contacts.js
3186
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/foreign-contacts.js
1891
3187
  var DAILY_FOREIGN_CONTACTS = 100;
1892
3188
  var foreignContactsPathFor = /* @__PURE__ */ __name((app, account, env = process.env, user) => join4(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state, "crm", CRM_SHARED_FOLDERS.foreignContacts, `${[account.provider, account.account, ...user ? [user] : []].join("-").replace(/[^\w.-]+/gu, "_")}.json`), "foreignContactsPathFor");
1893
3189
  var shownIn = /* @__PURE__ */ __name((file, day) => {
@@ -1965,7 +3261,7 @@ var refuseForeignClientReads = /* @__PURE__ */ __name(async (source, readsClient
1965
3261
  throw new CliError("permission_error", `${method} reads contacts or companies, which only the CRM's administrator reads through api call: your clients come with sync, and another one with people show or organizations show, ${DAILY_FOREIGN_CONTACTS} a day`, { reason: "crm.client-reads-admin-only", sent: false });
1966
3262
  }, "refuseForeignClientReads");
1967
3263
 
1968
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/writer.js
3264
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/writer.js
1969
3265
  var CRM_ASSIGN_OTHERS_KEY = "crm.assign-others";
1970
3266
  var CRM_WRITE_KEYS = [CRM_ASSIGN_OTHERS_KEY];
1971
3267
  var PLURALS = {
@@ -1981,8 +3277,15 @@ var VERB_OF = {
1981
3277
  close: "close",
1982
3278
  delete: "remove"
1983
3279
  };
1984
- var crmAlsoChecks = /* @__PURE__ */ __name((also) => (path2) => {
3280
+ var crmAlsoChecks = /* @__PURE__ */ __name((also, activities) => (path2) => {
1985
3281
  const [noun, command] = path2;
3282
+ if (noun === "activities" && command === "close" && path2.length === 2)
3283
+ return activities?.("close") ?? [];
3284
+ if (noun === "activities" && command === "create" && path2.length === 2)
3285
+ return [
3286
+ { key: CRM_ASSIGN_OTHERS_KEY, when: "--owner other than the sign-in's user" },
3287
+ ...["comment", "task"].flatMap((write2) => (activities?.(write2) ?? []).map((key) => ({ key, when: `a ${write2}` })))
3288
+ ];
1986
3289
  const kind2 = noun === void 0 ? void 0 : PLURALS[noun];
1987
3290
  const verb = command === void 0 ? void 0 : VERB_OF[command];
1988
3291
  if (path2.length !== 2 || kind2 === void 0 || verb === void 0)
@@ -1998,7 +3301,7 @@ var CRM_WRITE_DEFAULTS = {
1998
3301
  [CRM_ASSIGN_OTHERS_KEY]: "deny"
1999
3302
  };
2000
3303
 
2001
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/writes.js
3304
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/writes.js
2002
3305
  var moneyChecked = /* @__PURE__ */ __name((check, param) => {
2003
3306
  try {
2004
3307
  check();
@@ -2021,7 +3324,7 @@ var COMMAND = {
2021
3324
  close: "close",
2022
3325
  remove: "delete"
2023
3326
  };
2024
- var keyOf2 = /* @__PURE__ */ __name((kind2, verb) => `${PLURAL[kind2]}.${COMMAND[verb]}`, "keyOf");
3327
+ var keyOf3 = /* @__PURE__ */ __name((kind2, verb) => `${PLURAL[kind2]}.${COMMAND[verb]}`, "keyOf");
2025
3328
  var OPERATION_ID = /^[\x21-\x7e]{1,255}$/u;
2026
3329
  var DECIMAL2 = /^\d{1,16}(\.\d{1,6})?$/u;
2027
3330
  var CURRENCY = /^[A-Z]{3}$/u;
@@ -2070,8 +3373,8 @@ var pipelineOf = /* @__PURE__ */ __name(async (context, kind2, reference, param
2070
3373
  const all = await context.store.deals.pipelines(scope);
2071
3374
  if (all.length === 1)
2072
3375
  return context.store.deals.pipeline(all[0].ref, scope);
2073
- const what = kind2 ? `${kind2} pipeline` : "pipeline";
2074
- throw new CliError("validation_error", all.length === 0 ? `no ${what} of this CRM is stored; run sync first` : `this CRM has ${all.length} ${what}s; name one${param.startsWith("--") ? ` with ${param}` : ""}: ` + all.map(({ name, ref }) => `${name} (${ref})`).join(", "), { reason: "crm.pipeline-required", param, allowed: all.map(({ ref }) => ref) });
3376
+ const what2 = kind2 ? `${kind2} pipeline` : "pipeline";
3377
+ throw new CliError("validation_error", all.length === 0 ? `no ${what2} of this CRM is stored; run sync first` : `this CRM has ${all.length} ${what2}s; name one${param.startsWith("--") ? ` with ${param}` : ""}: ` + all.map(({ name, ref }) => `${name} (${ref})`).join(", "), { reason: "crm.pipeline-required", param, allowed: all.map(({ ref }) => ref) });
2075
3378
  }, "pipelineOf");
2076
3379
  var stageOf = /* @__PURE__ */ __name((pipeline, given) => {
2077
3380
  const byId = pipeline.stages.find((stage) => stage.externalId === given);
@@ -2204,22 +3507,18 @@ var crmCustomValues = /* @__PURE__ */ __name((fields2, pairs) => {
2204
3507
  }));
2205
3508
  }, "crmCustomValues");
2206
3509
  var customOf = /* @__PURE__ */ __name(async (context, kind2, pairs) => pairs?.length ? crmCustomValues(await context.store.crm.fields(context.account, kind2), pairs) : void 0, "customOf");
2207
- var keysOf = /* @__PURE__ */ __name((context, kind2, verb, { stage, owner }) => {
3510
+ var selfOf = /* @__PURE__ */ __name(async ({ writes: { self } }) => (typeof self === "function" ? await self() : self) || void 0, "selfOf");
3511
+ var keysOf = /* @__PURE__ */ __name(async (context, kind2, verb, { stage, owner }) => {
2208
3512
  const extra = [];
2209
3513
  if (stage && verb !== "move")
2210
- extra.push(keyOf2(kind2, "move"));
3514
+ extra.push(keyOf3(kind2, "move"));
2211
3515
  if (stage && stage.outcome !== "open")
2212
- extra.push(keyOf2(kind2, "close"));
2213
- if (owner != null && owner !== context.writes.self)
3516
+ extra.push(keyOf3(kind2, "close"));
3517
+ if (owner != null && owner !== await selfOf(context))
2214
3518
  extra.push(CRM_ASSIGN_OTHERS_KEY);
2215
- return { key: keyOf2(kind2, verb), extra: [...extra, ...context.writes.alsoChecks?.(kind2, verb) ?? []] };
3519
+ return { key: keyOf3(kind2, verb), extra: [...extra, ...context.writes.alsoChecks?.(kind2, verb) ?? []] };
2216
3520
  }, "keysOf");
2217
- var guardOf = /* @__PURE__ */ __name((context, extra) => {
2218
- const settings = context.writes.settings();
2219
- const defaults = { ...DEFAULT_PERMISSIONS, ...CRM_WRITE_DEFAULTS, ...settings.permissionDefaults };
2220
- return keyedGuard((ask) => guardFor(context.writes.app, { ...settings, sendsPerHour: Number.MAX_SAFE_INTEGER, permissionDefaults: defaults }, context.writes.warn ?? (() => {
2221
- }), context.writes.env, ask), context.ask, (key) => levelFor(settings.permissions, key, defaults).level, extra);
2222
- }, "guardOf");
3521
+ var guardOf = /* @__PURE__ */ __name((context, extra) => profileWriteGuard(context.writes, context.ask, CRM_WRITE_DEFAULTS, extra), "guardOf");
2223
3522
  var written = /* @__PURE__ */ __name(async (context, { key, extra }, operationId, act) => {
2224
3523
  try {
2225
3524
  const done = await guardedWrite(guardOf(context, extra), { chatId: null, kind: "edit", key, operationId }, async () => {
@@ -2272,8 +3571,14 @@ var createCrmItem = /* @__PURE__ */ __name(async (context, kind2, input, options
2272
3571
  const custom = await customOf(context, kind2, input.custom);
2273
3572
  if (custom)
2274
3573
  fields2.custom = custom;
3574
+ if (fields2.owner === void 0 && context.writes.ownedByDefault?.includes(kind2)) {
3575
+ const self = await selfOf(context);
3576
+ if (self === void 0)
3577
+ throw invalid(`a new ${kind2} needs --owner: the sign-in names no CRM user`, "--owner");
3578
+ fields2.owner = self;
3579
+ }
2275
3580
  const operationId = operationOf(context, options.operationId);
2276
- const item = await written(context, keysOf(context, kind2, "create", { stage, owner: fields2.owner }), operationId, () => writer.create(kind2, fields2, { operationId }));
3581
+ const item = await written(context, await keysOf(context, kind2, "create", { stage, owner: fields2.owner }), operationId, () => writer.create(kind2, fields2, { operationId }));
2277
3582
  return { operationId, item: await kept(context, kind2, item, operationId) };
2278
3583
  }, "createCrmItem");
2279
3584
  var updateCrmItem = /* @__PURE__ */ __name(async (context, kind2, reference, input, options = {}) => {
@@ -2290,7 +3595,7 @@ var updateCrmItem = /* @__PURE__ */ __name(async (context, kind2, reference, inp
2290
3595
  if (Object.keys(fields2).length === 0)
2291
3596
  throw invalid("nothing to change: name a field");
2292
3597
  const operationId = operationOf(context, options.operationId);
2293
- const item = await written(context, keysOf(context, kind2, "update", { stage, owner: fields2.owner }), operationId, () => writer.update(kind2, copy.externalId, fields2, { operationId }));
3598
+ const item = await written(context, await keysOf(context, kind2, "update", { stage, owner: fields2.owner }), operationId, () => writer.update(kind2, copy.externalId, fields2, { operationId }));
2294
3599
  return { operationId, item: await kept(context, kind2, item, operationId) };
2295
3600
  }, "updateCrmItem");
2296
3601
  var moveCrmItem = /* @__PURE__ */ __name(async (context, kind2, reference, stageName, options = {}) => {
@@ -2299,7 +3604,7 @@ var moveCrmItem = /* @__PURE__ */ __name(async (context, kind2, reference, stage
2299
3604
  const copy = await copyOf(context, kind2, reference);
2300
3605
  const stage = stageOf(await pipelineOf(context, kind2, copy.pipeline), stageName);
2301
3606
  const operationId = operationOf(context, options.operationId);
2302
- const item = await written(context, keysOf(context, kind2, "move", { stage }), operationId, () => writer.move(kind2, copy.externalId, stage.externalId, { operationId }));
3607
+ const item = await written(context, await keysOf(context, kind2, "move", { stage }), operationId, () => writer.move(kind2, copy.externalId, stage.externalId, { operationId }));
2303
3608
  return { operationId, item: await kept(context, kind2, item, operationId) };
2304
3609
  }, "moveCrmItem");
2305
3610
  var closeCrmItem = /* @__PURE__ */ __name(async (context, kind2, reference, outcome, options = {}) => {
@@ -2312,7 +3617,7 @@ var closeCrmItem = /* @__PURE__ */ __name(async (context, kind2, reference, outc
2312
3617
  if (reason !== void 0 && (reason === "" || reason.length > 2e3))
2313
3618
  throw invalid("--reason is 1 to 2000 characters", "--reason");
2314
3619
  const operationId = operationOf(context, options.operationId);
2315
- const item = await written(context, keysOf(context, kind2, "close", {}), operationId, () => writer.close(kind2, copy.externalId, outcome, { operationId, ...reason ? { reason } : {} }));
3620
+ const item = await written(context, await keysOf(context, kind2, "close", {}), operationId, () => writer.close(kind2, copy.externalId, outcome, { operationId, ...reason ? { reason } : {} }));
2316
3621
  return { operationId, item: await kept(context, kind2, item, operationId) };
2317
3622
  }, "closeCrmItem");
2318
3623
  var removeCrmItem = /* @__PURE__ */ __name(async (context, kind2, reference, options = {}) => {
@@ -2320,7 +3625,7 @@ var removeCrmItem = /* @__PURE__ */ __name(async (context, kind2, reference, opt
2320
3625
  supported(writer, kind2, "remove");
2321
3626
  const copy = await copyOf(context, kind2, reference);
2322
3627
  const operationId = operationOf(context, options.operationId);
2323
- await written(context, keysOf(context, kind2, "remove", {}), operationId, () => writer.remove(kind2, copy.externalId, { operationId }));
3628
+ await written(context, await keysOf(context, kind2, "remove", {}), operationId, () => writer.remove(kind2, copy.externalId, { operationId }));
2324
3629
  const removed = await context.store.crm.remove(context.account, kind2, [copy.externalId]);
2325
3630
  return { operationId, ref: copy.ref, removed };
2326
3631
  }, "removeCrmItem");
@@ -2393,7 +3698,7 @@ var writeRecord = /* @__PURE__ */ __name(async (context, kind2, verb, fields2, o
2393
3698
  if (!context.source)
2394
3699
  throw new CliError("configuration_error", "a contact or company write needs the CRM source to tell your clients");
2395
3700
  const rule2 = foreignContacts(context.source(), void 0);
2396
- const record2 = await written(context, keysOf(context, kind2, verb, { owner: fields2.owner }), operationId, act);
3701
+ const record2 = await written(context, await keysOf(context, kind2, verb, { owner: fields2.owner }), operationId, act);
2397
3702
  const stored = await rule2.own(kind2, record2);
2398
3703
  let removed;
2399
3704
  try {
@@ -2444,11 +3749,122 @@ var updateCrmRecord = /* @__PURE__ */ __name(async (context, kind2, externalId,
2444
3749
  const operationId = operationOf(context, options.operationId);
2445
3750
  return writeRecord(context, kind2, "update", fields2, operationId, () => writer.update(kind2, externalId, fields2, { operationId }));
2446
3751
  }, "updateCrmRecord");
3752
+ var MOST_SUBJECT = 500;
3753
+ var MOST_BODY = 2e4;
3754
+ var activityInvalid = /* @__PURE__ */ __name((message, param) => new CliError("validation_error", message, { reason: "crm.activity-field", ...param ? { param } : {} }), "activityInvalid");
3755
+ var activityUnsupported = /* @__PURE__ */ __name((what2) => new CliError("validation_error", `this CRM does not take ${what2}`, { reason: "crm.write-unsupported", sent: false }), "activityUnsupported");
3756
+ var activityTargetOf = /* @__PURE__ */ __name(async (context, given) => {
3757
+ const at2 = given.indexOf(":");
3758
+ const kind2 = given.slice(0, at2);
3759
+ const id2 = given.slice(at2 + 1);
3760
+ if (kind2 === "deal" || kind2 === "lead") {
3761
+ const copy = await copyOf(context, kind2, given.trim());
3762
+ return { kind: kind2, externalId: copy.externalId, ref: copy.ref, title: copy.title };
3763
+ }
3764
+ if (kind2 === "person" || kind2 === "organization") {
3765
+ const crmId = id2.startsWith("crm:") ? id2.slice(4) : /^\d+$/.test(id2) ? void 0 : id2;
3766
+ if (crmId !== void 0 && RECORD_ID.test(crmId))
3767
+ return { kind: kind2, externalId: crmId, ref: null, title: null };
3768
+ if (crmId === void 0) {
3769
+ const ids2 = await context.store.crm.externalIdsOf(context.account, given);
3770
+ if (ids2.length > 1)
3771
+ throw new CliError("validation_error", `${given} is ${ids2.length} records of the CRM; name one as ${kind2}:crm:<id>`, {
3772
+ reason: "crm.record-ambiguous",
3773
+ param: "--subject",
3774
+ candidates: ids2.map((one) => ({ id: `${kind2}:crm:${one}` })),
3775
+ sent: false
3776
+ });
3777
+ if (ids2[0])
3778
+ return { kind: kind2, externalId: ids2[0], ref: given, title: null };
3779
+ throw new CliError("not_found", `the copy holds no ${given}; a ${kind2} by the CRM's id, as ${kind2 === "person" ? "people" : "organizations"} list prints it, is ${kind2}:crm:<id>`, { param: "--subject", sent: false });
3780
+ }
3781
+ }
3782
+ throw new CliError("validation_error", `--subject takes deal:<id>, lead:<id>, person:<id> or organization:<id> as the copy's lists and deals show give them, or person:crm:<id> or organization:crm:<id> by the CRM's id; got ${given}`, { reason: "ref.malformed", param: "--subject" });
3783
+ }, "activityTargetOf");
3784
+ var activityKeys = /* @__PURE__ */ __name(async (context, key, owner, write2) => ({
3785
+ key,
3786
+ extra: [
3787
+ ...owner !== void 0 && owner !== await selfOf(context) ? [CRM_ASSIGN_OTHERS_KEY] : [],
3788
+ ...context.writes.activityChecks?.(write2) ?? []
3789
+ ]
3790
+ }), "activityKeys");
3791
+ var keptActivity = /* @__PURE__ */ __name(async (context, activity, operationId) => {
3792
+ try {
3793
+ if (!await context.store.crm.activitiesOn(context.account))
3794
+ return false;
3795
+ return (await context.store.crm.saveActivities(context.account, [activity])).saved === 1;
3796
+ } catch (error) {
3797
+ throw new CliError("invalid_response", `the CRM wrote activity ${activity.externalId}, but the local store did not keep it (${error instanceof Error ? error.message : String(error)}); sync to store it \u2014 do not write it again`, { external_id: activity.externalId, operation_id: operationId, sent: true });
3798
+ }
3799
+ }, "keptActivity");
3800
+ var answeredTargets = /* @__PURE__ */ __name(async (context, activity, known) => Promise.all(activity.on.map(async ({ kind: kind2, externalId }) => known.find((one) => one.kind === kind2 && one.externalId === externalId) ?? {
3801
+ kind: kind2,
3802
+ externalId,
3803
+ ref: isItemKind(kind2) ? await context.store.crm.refOf(context.account, kind2, externalId) : null,
3804
+ title: null
3805
+ })), "answeredTargets");
3806
+ var createCrmActivity = /* @__PURE__ */ __name(async (context, kind2, input, options = {}) => {
3807
+ const { writer } = context.writes;
3808
+ const create = writer.createActivity?.bind(writer);
3809
+ if (!create || !writer.capabilities.activities?.includes(kind2))
3810
+ throw activityUnsupported(`a new ${kind2}`);
3811
+ const subject = input.title?.trim();
3812
+ const body = input.body?.trim();
3813
+ if (subject !== void 0 && (subject === "" || subject.length > MOST_SUBJECT))
3814
+ throw activityInvalid(`--title is 1 to ${MOST_SUBJECT} characters`, "--title");
3815
+ if (body !== void 0 && (body === "" || body.length > MOST_BODY))
3816
+ throw activityInvalid(`--text is 1 to ${MOST_BODY} characters`, "--text");
3817
+ if (kind2 === "task" && subject === void 0)
3818
+ throw activityInvalid("a new task needs --title", "--title");
3819
+ if (kind2 === "comment" && body === void 0)
3820
+ throw activityInvalid("a new comment needs --text", "--text");
3821
+ if (kind2 === "comment" && input.dueAt !== void 0)
3822
+ throw activityInvalid("a comment has no --due", "--due");
3823
+ if (kind2 === "comment" && input.owner !== void 0)
3824
+ throw activityInvalid("a comment has no --owner", "--owner");
3825
+ const owner = input.owner?.trim();
3826
+ if (owner !== void 0 && !owner)
3827
+ throw activityInvalid("--owner is the CRM user's id", "--owner");
3828
+ if (input.on.length === 0)
3829
+ throw activityInvalid("name the record it is on with --subject, such as deal:12", "--subject");
3830
+ const targets = [];
3831
+ for (const given of input.on) {
3832
+ const target = await activityTargetOf(context, given);
3833
+ if (!targets.some((one) => one.kind === target.kind && one.externalId === target.externalId))
3834
+ targets.push(target);
3835
+ }
3836
+ const draft = {
3837
+ kind: kind2,
3838
+ ...subject === void 0 ? {} : { subject },
3839
+ ...body === void 0 ? {} : { body },
3840
+ ...input.dueAt === void 0 ? {} : { dueAt: input.dueAt },
3841
+ ...owner === void 0 ? {} : { assignee: owner },
3842
+ on: targets.map(({ kind: kind3, externalId }) => ({ kind: kind3, externalId }))
3843
+ };
3844
+ const operationId = operationOf(context, options.operationId);
3845
+ const activity = await written(context, await activityKeys(context, "activities.create", owner, kind2), operationId, () => create(draft, { operationId }));
3846
+ const stored = await keptActivity(context, activity, operationId);
3847
+ return { operationId, activity, stored, on: await answeredTargets(context, activity, targets) };
3848
+ }, "createCrmActivity");
3849
+ var completeCrmActivity = /* @__PURE__ */ __name(async (context, externalId, options = {}) => {
3850
+ const { writer } = context.writes;
3851
+ const complete = writer.completeActivity?.bind(writer);
3852
+ if (!complete || !writer.capabilities.activities?.includes("task"))
3853
+ throw activityUnsupported("a task marked done");
3854
+ if (!RECORD_ID.test(externalId))
3855
+ throw new CliError("validation_error", "name the task by the CRM's id, as activities list prints it", {
3856
+ reason: "ref.malformed"
3857
+ });
3858
+ const operationId = operationOf(context, options.operationId);
3859
+ const activity = await written(context, await activityKeys(context, "activities.close", void 0, "close"), operationId, () => complete(externalId, { operationId }));
3860
+ const stored = await keptActivity(context, activity, operationId);
3861
+ return { operationId, activity, stored, on: await answeredTargets(context, activity, []) };
3862
+ }, "completeCrmActivity");
2447
3863
 
2448
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/file-fetch.js
3864
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/file-fetch.js
2449
3865
  var EXCHANGE_MS = 60 * 60 * 1e3;
2450
3866
 
2451
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/manifest/map.js
3867
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/manifest/map.js
2452
3868
  var at = /* @__PURE__ */ __name((value, path2) => path2 === "." ? value : path2.split(".").reduce((inner, key) => inner === null ? null : Array.isArray(inner) && /^\d+$/.test(key) ? inner[Number(key)] ?? null : isRaw(inner) ? inner[key] : void 0, value), "at");
2453
3869
  var TIMES = { createdAt: "epoch", updatedAt: "epoch" };
2454
3870
  var ITEM = {
@@ -2501,7 +3917,7 @@ var FIELDS = {
2501
3917
  lead: ITEM
2502
3918
  };
2503
3919
 
2504
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/manifest/manifest.js
3920
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/manifest/manifest.js
2505
3921
  var path = pipe(string(), regex(/^[^.\s]+(\.[^.\s]+)*$/, "a dotted path such as properties.name"));
2506
3922
  var paths = pipe(array(path), minLength(1));
2507
3923
  var crmRuleSchema = union([
@@ -2575,6 +3991,22 @@ var fields = strictObject({
2575
3991
  keep: optional(union([strictObject({ path, is: unknown() }), function_()]))
2576
3992
  });
2577
3993
  var kind = picklist(CRM_KINDS);
3994
+ var writeShape = {
3995
+ each: optional(unknown()),
3996
+ list: optional(literal(true)),
3997
+ number: optional(literal(true)),
3998
+ decimals: optional(pipe(number(), integer(), minValue(0)))
3999
+ };
4000
+ var writeRule = strictObject({ to: pipe(string(), minLength(1)), ...writeShape });
4001
+ var write = strictObject({
4002
+ create: optional(call),
4003
+ update: optional(call),
4004
+ remove: optional(call),
4005
+ id: optional(path),
4006
+ fields: record(string(), union([writeRule, literal("implied"), strictObject({ fixed: call, at: path })])),
4007
+ custom: optional(strictObject(writeShape)),
4008
+ clear: optional(unknown())
4009
+ });
2578
4010
  var schema = strictObject({
2579
4011
  provider: pipe(string(), regex(/^[a-z][a-z0-9-]*$/, "a registry name such as hubspot")),
2580
4012
  kinds: pipe(array(kind), minLength(1)),
@@ -2591,13 +4023,14 @@ var schema = strictObject({
2591
4023
  position: optional(rule),
2592
4024
  active: optional(rule)
2593
4025
  })
2594
- }))
4026
+ })),
4027
+ writes: optional(record(kind, optional(write)))
2595
4028
  });
2596
4029
 
2597
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/manifest/source.js
4030
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/manifest/source.js
2598
4031
  var OVERLAP_MS = 10 * 6e4;
2599
4032
 
2600
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/sends/pace.js
4033
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/sends/pace.js
2601
4034
  import { readFileSync as readFileSync6, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
2602
4035
  import { join as join5 } from "node:path";
2603
4036
  var DEFAULT_PACE = { perMinute: 60, burst: 20 };
@@ -2689,13 +4122,13 @@ var waitForTurn = /* @__PURE__ */ __name(async (pacer, options) => {
2689
4122
  counts: { seconds }
2690
4123
  });
2691
4124
  }
2692
- await (options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))))(waitMs);
4125
+ await (options.sleep ?? ((ms) => new Promise((resolve2) => setTimeout(resolve2, ms))))(waitMs);
2693
4126
  }, "waitForTurn");
2694
4127
 
2695
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/provider-call.js
4128
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/provider-call.js
2696
4129
  var RETRY = { retries: 3, baseDelayMs: 1e3, maxDelayMs: 1e4, maxRetryAfterMs: 3e4 };
2697
4130
  var UNANSWERED = /* @__PURE__ */ new Set(["timeout", "network_error", "provider_unavailable", "cancelled", "invalid_response"]);
2698
- var unanswered = /* @__PURE__ */ __name((error) => !isCliError(error) || UNANSWERED.has(error.code) && error.details.sent !== false, "unanswered");
4131
+ var unanswered2 = /* @__PURE__ */ __name((error) => !isCliError(error) || UNANSWERED.has(error.code) && error.details.sent !== false, "unanswered");
2699
4132
  var providerCall = /* @__PURE__ */ __name(async (options) => {
2700
4133
  const retries = options.retries ?? RETRY.retries;
2701
4134
  const sleep = options.sleep ?? ((ms) => realSleep(ms));
@@ -2712,7 +4145,7 @@ var providerCall = /* @__PURE__ */ __name(async (options) => {
2712
4145
  continue;
2713
4146
  throw error;
2714
4147
  }
2715
- if (options.write && unanswered(error))
4148
+ if (options.write && unanswered2(error))
2716
4149
  throw new CliError("outcome_unknown", `${error instanceof Error ? error.message : String(error)}; the CRM may or may not have carried it out`, { ...isCliError(error) ? error.details : {}, retryable: false });
2717
4150
  if (!isCliError(error))
2718
4151
  throw error;
@@ -2728,7 +4161,7 @@ var providerCall = /* @__PURE__ */ __name(async (options) => {
2728
4161
  }
2729
4162
  }, "providerCall");
2730
4163
 
2731
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/query.js
4164
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/query.js
2732
4165
  var valueFor = /* @__PURE__ */ __name((kind2, raw, name) => {
2733
4166
  if (kind2 === "id") {
2734
4167
  if (!/^[\w.:-]{1,100}$/u.test(raw))
@@ -2829,7 +4262,7 @@ var selectedCodes = /* @__PURE__ */ __name((fields2, wanted) => {
2829
4262
  });
2830
4263
  }, "selectedCodes");
2831
4264
 
2832
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/search/groups.js
4265
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/search/groups.js
2833
4266
  var ALL = "all";
2834
4267
  var OWNER_NOTES = { provider: "notes", account: INTERNAL_NOTES };
2835
4268
  var NOT_GROUP_NAMES = /* @__PURE__ */ new Set([ALL, "bots"]);
@@ -2901,7 +4334,7 @@ var groupEntries = /* @__PURE__ */ __name((saved) => ({
2901
4334
  [ALL]: [ALL]
2902
4335
  }), "groupEntries");
2903
4336
 
2904
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/services/search-kind.js
4337
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/services/search-kind.js
2905
4338
  var NO_MAIL = "no_mail";
2906
4339
  var MAIL = "email";
2907
4340
  var groupLockOf = /* @__PURE__ */ __name((app, env) => {
@@ -2926,10 +4359,10 @@ var listContextOf = /* @__PURE__ */ __name(async (store, account, app, stored, e
2926
4359
  if (!members)
2927
4360
  throw new CliError("permission_error", `this process is locked to group ${lock} (${envName(app, "GROUP_LOCK")}), which does not exist`);
2928
4361
  const only = new Set([...members, OWNER_NOTES].map(keyOf));
2929
- const listedAs = /* @__PURE__ */ __name((one) => isFolderProvider(one.provider) || isDocumentAccountProvider(one.provider) ? { provider: "notes", account: String(one.id) } : one, "listedAs");
4362
+ const listedAs = /* @__PURE__ */ __name((one) => isFolderProvider(one.provider) || isDocumentAccountProvider(one.provider) ? [{ provider: "notes", account: String(one.id) }, ...alsoListedByKey(one.provider) ? [one] : []] : [one], "listedAs");
2930
4363
  return {
2931
4364
  ...context,
2932
- held: held.filter((one) => only.has(keyOf(listedAs(one)))),
4365
+ held: held.filter((one) => listedAs(one).some((key) => only.has(keyOf(key)))),
2933
4366
  groups: { [lock]: groups[lock] ?? [] },
2934
4367
  membership: {
2935
4368
  groups: { [lock]: members },
@@ -2975,7 +4408,7 @@ var accountsOfKind = /* @__PURE__ */ __name((kind2, chosen, held, explicit, comm
2975
4408
  return chosenMail.map(({ provider, account }) => ({ provider, account }));
2976
4409
  }, "accountsOfKind");
2977
4410
 
2978
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/group-hint.js
4411
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/group-hint.js
2979
4412
  var workGroupHint = /* @__PURE__ */ __name((key) => `add it to a work group: \`memo groups add work ${key.provider}:${key.account}\``, "workGroupHint");
2980
4413
  var ungroupedHint = /* @__PURE__ */ __name(async (store, key) => {
2981
4414
  const { groups } = (await listContextOf(store, key, void 0)).membership;
@@ -2983,7 +4416,7 @@ var ungroupedHint = /* @__PURE__ */ __name(async (store, key) => {
2983
4416
  return grouped ? void 0 : workGroupHint(key);
2984
4417
  }, "ungroupedHint");
2985
4418
 
2986
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/viewer.js
4419
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/viewer.js
2987
4420
  var VIEWERS = "crm:viewers";
2988
4421
  var viewersOf = /* @__PURE__ */ __name(async (store, account) => {
2989
4422
  try {
@@ -3058,7 +4491,7 @@ var ownerOf = /* @__PURE__ */ __name(async (run, owner) => {
3058
4491
  return crmIdentityId(run.account, normalCrmUserId(owner), "user");
3059
4492
  }, "ownerOf");
3060
4493
 
3061
- // node_modules/.pnpm/@wirecat+cli-core@0.722.0_@wirecat+cli-base@0.127.0_commander@15.0.0_esbuild@0.28.2_typ_d2bed0cfbe6b4358c89d465b9e07afcb/node_modules/@wirecat/cli-core/dist/crm/sync.js
4494
+ // node_modules/.pnpm/@wirecat+cli-core@1.0.0_@wirecat+cli-base@1.0.0_commander@15.0.0_esbuild@0.28.2_typescr_dd5172c52281f8f1e2dd1d4e9555d5c3/node_modules/@wirecat/cli-core/dist/crm/sync.js
3062
4495
  var DAY2 = 864e5;
3063
4496
  var CLOCK_MARGIN = 60 * 6e4;
3064
4497
  var MOST_UNLISTED = 0.5;
@@ -3075,7 +4508,7 @@ var parseCrmCursor = /* @__PURE__ */ __name((value) => {
3075
4508
  const pass = cursor.pass;
3076
4509
  if (round != null && (!isToken(round.from) || !isToken(round.page) || typeof round.reset !== "boolean"))
3077
4510
  return null;
3078
- if (pass != null && (!isToken(pass.page) || typeof pass.startedAt !== "number" || !Array.isArray(pass.seen) || pass.seen.some((id2) => typeof id2 !== "string")))
4511
+ if (pass != null && (!isToken(pass.page) || typeof pass.startedAt !== "number" || !Array.isArray(pass.seen) || pass.seen.some((id2) => typeof id2 !== "string") || pass.unread !== void 0 && pass.unread !== true))
3079
4512
  return null;
3080
4513
  return {
3081
4514
  v: 1,
@@ -3110,7 +4543,7 @@ var scopeOf = /* @__PURE__ */ __name((error) => {
3110
4543
  const scope = error instanceof CliError ? error.details?.scope : void 0;
3111
4544
  return typeof scope === "string" && scope ? scope : void 0;
3112
4545
  }, "scopeOf");
3113
- var refusal = /* @__PURE__ */ __name((kind2, consequence, error, provider) => {
4546
+ var refusal2 = /* @__PURE__ */ __name((kind2, consequence, error, provider) => {
3114
4547
  const code = error instanceof CliError ? error.code : "error";
3115
4548
  const scope = scopeOf(error);
3116
4549
  const message = scope ? `${scope} scope missing: ${consequence}` : `${provider} did not list ${kind2} (${code}): ${consequence}`;
@@ -3157,7 +4590,7 @@ var readUsers = /* @__PURE__ */ __name(async (run) => {
3157
4590
  } catch (error) {
3158
4591
  if (run.signal?.aborted || error instanceof BudgetSpent)
3159
4592
  throw error;
3160
- gap(refusal("users", "nothing stored about them changed", error, source.provider));
4593
+ gap(refusal2("users", "nothing stored about them changed", error, source.provider));
3161
4594
  return null;
3162
4595
  }
3163
4596
  let departments;
@@ -3176,7 +4609,7 @@ var readUsers = /* @__PURE__ */ __name(async (run) => {
3176
4609
  } catch (error) {
3177
4610
  if (run.signal?.aborted || error instanceof BudgetSpent)
3178
4611
  throw error;
3179
- gap(refusal("departments", "reporting lines unknown", error, source.provider));
4612
+ gap(refusal2("departments", "reporting lines unknown", error, source.provider));
3180
4613
  }
3181
4614
  }
3182
4615
  noted(run, "user", await run.store.crm.saveUsers(run.account, users, departments));
@@ -3193,14 +4626,33 @@ var activityCursor = /* @__PURE__ */ __name((value) => {
3193
4626
  return void 0;
3194
4627
  }
3195
4628
  }, "activityCursor");
3196
- var readActivities = /* @__PURE__ */ __name(async (run) => {
4629
+ var removeUnlistedActivities = /* @__PURE__ */ __name(async (run, options, seen) => {
4630
+ const { store, account, source } = run;
4631
+ const { stored, unlisted } = await store.crm.removeUnlistedActivities(account, seen, { dryRun: true });
4632
+ if (unlisted === 0)
4633
+ return;
4634
+ if (!options.rescan && (seen.length === 0 || stored >= GUARDED_FROM && unlisted > stored * MOST_UNLISTED)) {
4635
+ run.report.issues.push({
4636
+ kind: "deal",
4637
+ reason: "crm.activities-unlisted-held",
4638
+ message: `${source.provider} listed ${seen.length} activities, so ${unlisted} of the ${stored} stored would be marked deleted; nothing was \u2014 check the sign-in's rights, then run sync --rescan to let it through`
4639
+ });
4640
+ return;
4641
+ }
4642
+ const done = await store.crm.removeUnlistedActivities(account, seen);
4643
+ if (run.report.activities)
4644
+ run.report.activities.removed += done.unlisted;
4645
+ }, "removeUnlistedActivities");
4646
+ var readActivities = /* @__PURE__ */ __name(async (run, options) => {
3197
4647
  const { source, store, account } = run;
3198
4648
  if (!source.activities || !await store.crm.activitiesOn(account))
3199
4649
  return null;
3200
- const read = { saved: 0, outOfScope: 0, state: "partial" };
4650
+ const read = { saved: 0, outOfScope: 0, removed: 0, state: "partial" };
3201
4651
  run.report.activities = read;
3202
4652
  const saved = activityCursor((await store.sync.syncState(account, ACTIVITIES))?.value);
3203
4653
  const cursor = saved ?? { since: run.now - ACTIVITY_DAYS * DAY2, newest: 0 };
4654
+ const seen = cursor.page === void 0 ? /* @__PURE__ */ new Set() : void 0;
4655
+ const gaps = run.gaps.length;
3204
4656
  for (; ; ) {
3205
4657
  const why = run.budget.take();
3206
4658
  if (why)
@@ -3213,12 +4665,16 @@ var readActivities = /* @__PURE__ */ __name(async (run) => {
3213
4665
  throw error;
3214
4666
  if (!scopeOf(error))
3215
4667
  throw error;
3216
- run.gaps.push(refusal("activities", "no activity or task was read", error, source.provider));
4668
+ run.gaps.push(refusal2("activities", "no activity or task was read", error, source.provider));
3217
4669
  return null;
3218
4670
  }
3219
4671
  const done = await store.crm.saveActivities(account, page.items);
3220
4672
  read.saved += done.saved;
3221
4673
  read.outOfScope += done.outOfScope;
4674
+ if (page.removed?.length)
4675
+ read.removed += await store.crm.removeActivities(account, page.removed);
4676
+ for (const one of page.items)
4677
+ seen?.add(one.externalId);
3222
4678
  cursor.newest = Math.max(cursor.newest, ...page.items.map((one) => one.updatedAt));
3223
4679
  run.moved();
3224
4680
  if (page.hasMore && page.nextCursor !== void 0) {
@@ -3228,6 +4684,8 @@ var readActivities = /* @__PURE__ */ __name(async (run) => {
3228
4684
  return "cancelled";
3229
4685
  continue;
3230
4686
  }
4687
+ if (page.listedAll && seen && run.gaps.length === gaps)
4688
+ await removeUnlistedActivities(run, options, [...seen]);
3231
4689
  const next = page.cursor != null ? Number(page.cursor) : cursor.newest || cursor.since;
3232
4690
  await store.sync.setSyncState(account, ACTIVITIES, JSON.stringify({ since: next, newest: 0 }));
3233
4691
  read.state = "complete";
@@ -3442,6 +4900,8 @@ var syncKind = /* @__PURE__ */ __name(async (run, kind2, options, result) => {
3442
4900
  if (page.hasMore && page.nextCursor === void 0)
3443
4901
  throw new CliError("invalid_response", `${source.provider} said there are more ids but gave no cursor`);
3444
4902
  pass = { ...pass, seen: [...pass.seen, ...page.items], page: page.hasMore ? page.nextCursor ?? null : null };
4903
+ if (run.gaps.some((gap) => gap.kind === kind2))
4904
+ pass = { ...pass, unread: true };
3445
4905
  run.moved();
3446
4906
  if (!page.hasMore)
3447
4907
  break;
@@ -3451,12 +4911,14 @@ var syncKind = /* @__PURE__ */ __name(async (run, kind2, options, result) => {
3451
4911
  const stored = await store.crm.count(account, kind2);
3452
4912
  const unlisted = await store.crm.removeUnlisted(account, kind2, pass.seen, before2, { ...listedOf, dryRun: true });
3453
4913
  const emptied = pass.seen.length === 0 && unlisted > 0;
3454
- if (!options.rescan && (emptied || stored >= GUARDED_FROM && unlisted > stored * MOST_UNLISTED)) {
4914
+ const many = emptied || stored >= GUARDED_FROM && unlisted > stored * MOST_UNLISTED;
4915
+ const unread = pass.unread === true || run.gaps.some((gap) => gap.kind === kind2);
4916
+ if (unlisted > 0 && (unread || many && unlisted > (options.allowDeletions ?? 0))) {
3455
4917
  result.pass = "held";
3456
4918
  run.report.issues.push({
3457
4919
  kind: kind2,
3458
4920
  reason: "crm.unlisted-held",
3459
- message: `${source.provider} listed ${pass.seen.length} ${kind2} ids, so ${unlisted} of the ${stored} stored would be marked deleted; nothing was \u2014 check the sign-in's rights, then run sync --rescan to let it through`
4921
+ message: unread ? `${source.provider} could not read all ${kind2}s, so the ${unlisted} it did not list stay; nothing was marked deleted \u2014 check the sign-in's rights, then run sync again` : `${source.provider} listed ${pass.seen.length} ${kind2} ids, so ${unlisted} of the ${stored} stored would be marked deleted; nothing was \u2014 check the sign-in's rights, then run sync --allow-deletions ${unlisted} to let them through`
3460
4922
  });
3461
4923
  } else {
3462
4924
  result.unlisted = await store.crm.removeUnlisted(account, kind2, pass.seen, before2, listedOf);
@@ -3598,7 +5060,7 @@ var syncCrm = /* @__PURE__ */ __name(async (source, store, account, options = {}
3598
5060
  continue;
3599
5061
  }
3600
5062
  if (scopeOf(error))
3601
- run.gaps.push(refusal(kind2, `no ${kind2} was read`, error, source.provider));
5063
+ run.gaps.push(refusal2(kind2, `no ${kind2} was read`, error, source.provider));
3602
5064
  result.error = isCliFailure(error) ? error.message : `the ${kind2} copy could not be synced`;
3603
5065
  }
3604
5066
  }
@@ -3606,7 +5068,7 @@ var syncCrm = /* @__PURE__ */ __name(async (source, store, account, options = {}
3606
5068
  const rowsStopped = stopped;
3607
5069
  if (!stopped && kinds.some(isItemKind)) {
3608
5070
  try {
3609
- stopped = await stopping(() => readActivities(run));
5071
+ stopped = await stopping(() => readActivities(run, options));
3610
5072
  } catch (error) {
3611
5073
  if (options.signal?.aborted)
3612
5074
  stopped = "cancelled";
@@ -3723,6 +5185,15 @@ export {
3723
5185
  listContextOf,
3724
5186
  listedAccounts,
3725
5187
  accountsOfKind,
5188
+ uploadSize,
5189
+ typesText,
5190
+ realPathOf,
5191
+ refuseLockedOutput,
5192
+ refusedPlace,
5193
+ inside,
5194
+ readUpload,
5195
+ readAttachments,
5196
+ readStickerFile,
3726
5197
  parseCrmFileId,
3727
5198
  withoutFileLinks,
3728
5199
  CRM_SHARED_FOLDERS,
@@ -3732,7 +5203,6 @@ export {
3732
5203
  values_exports,
3733
5204
  at,
3734
5205
  identifier,
3735
- graphqlDocument,
3736
5206
  LosslessNumber,
3737
5207
  isLosslessNumber,
3738
5208
  apiFlagOf,
@@ -3745,18 +5215,11 @@ export {
3745
5215
  parseApiJson,
3746
5216
  apiJson,
3747
5217
  apiPlainJson,
3748
- graphqlVariables,
3749
5218
  manifestBaseUrl,
3750
5219
  siteValue,
3751
5220
  signRequest,
3752
5221
  underBase,
3753
- parameterValue,
3754
5222
  nextPage,
3755
- DEFAULT_PACE,
3756
- pacePathFor,
3757
- Pacer,
3758
- waitForTurn,
3759
- providerCall,
3760
5223
  holdEnd,
3761
5224
  floodPathFor,
3762
5225
  FloodMemory,
@@ -3769,6 +5232,33 @@ export {
3769
5232
  sendGuard,
3770
5233
  guardFor,
3771
5234
  keyedGuard,
5235
+ generatedApiCommand,
5236
+ runSettings,
5237
+ commandRuns,
5238
+ commandRunId,
5239
+ providerEvent,
5240
+ providerRequest,
5241
+ recordRuns,
5242
+ unsendableBody,
5243
+ httpApiRequest,
5244
+ httpApiExecutor,
5245
+ answerOf2 as answerOf,
5246
+ terminalAsker,
5247
+ commandPathKey,
5248
+ commandPermissions,
5249
+ knownPermissionKeys,
5250
+ renamedPermissionKeys,
5251
+ knownBeside,
5252
+ unknownPermissionKeys,
5253
+ unknownPermissionIssues,
5254
+ refuseUnknownPermissionKeys,
5255
+ serviceApiOperations,
5256
+ serviceApiKeys,
5257
+ serviceApiPermissions,
5258
+ serviceApiCommand,
5259
+ serviceApiWriter,
5260
+ hostsFetch,
5261
+ serviceApiCall,
3772
5262
  CRM_ASSIGN_OTHERS_KEY,
3773
5263
  CRM_WRITE_KEYS,
3774
5264
  crmAlsoChecks,
@@ -3786,6 +5276,13 @@ export {
3786
5276
  RECORD_ID,
3787
5277
  createCrmRecord,
3788
5278
  updateCrmRecord,
5279
+ createCrmActivity,
5280
+ completeCrmActivity,
5281
+ DEFAULT_PACE,
5282
+ pacePathFor,
5283
+ Pacer,
5284
+ waitForTurn,
5285
+ providerCall,
3789
5286
  conditionsOf,
3790
5287
  customNames,
3791
5288
  filterableFields,