@vm0/cli 9.278.0 → 9.278.1

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 (194) hide show
  1. package/{agent-HUDTEGLK.js → agent-4F3XAJWN.js} +12 -6
  2. package/agent-4F3XAJWN.js.map +1 -0
  3. package/{banking-BMZONEXP.js → banking-CWQFQKZB.js} +61 -7
  4. package/banking-CWQFQKZB.js.map +1 -0
  5. package/{browser-LQP445CU.js → browser-BI6UFWPH.js} +4 -5
  6. package/browser-BI6UFWPH.js.map +1 -0
  7. package/{chat-UF7QAWUT.js → chat-MKIW4FPP.js} +24 -16
  8. package/chat-MKIW4FPP.js.map +1 -0
  9. package/chunk-2SJTFDC2.js +189 -0
  10. package/chunk-2SJTFDC2.js.map +1 -0
  11. package/chunk-4FTIKZKP.js +64 -0
  12. package/chunk-4FTIKZKP.js.map +1 -0
  13. package/chunk-7UZXNER2.js +568 -0
  14. package/chunk-7UZXNER2.js.map +1 -0
  15. package/chunk-A6ZRMNM3.js +102 -0
  16. package/chunk-A6ZRMNM3.js.map +1 -0
  17. package/{chunk-QC63TUJC.js → chunk-C62A6LD6.js} +2 -2
  18. package/chunk-CCTF3YVW.js +52 -0
  19. package/chunk-CCTF3YVW.js.map +1 -0
  20. package/chunk-CD2BLKGC.js +188 -0
  21. package/chunk-CD2BLKGC.js.map +1 -0
  22. package/chunk-CEJGHPF3.js +55 -0
  23. package/chunk-CEJGHPF3.js.map +1 -0
  24. package/chunk-DUA6CF7E.js +2053 -0
  25. package/chunk-DUA6CF7E.js.map +1 -0
  26. package/chunk-E2TQAKNL.js +1300 -0
  27. package/chunk-E2TQAKNL.js.map +1 -0
  28. package/{chunk-5ZZI2LSO.js → chunk-GHKWW4NC.js} +5 -5
  29. package/chunk-GV3PG6CZ.js +114 -0
  30. package/chunk-GV3PG6CZ.js.map +1 -0
  31. package/chunk-GY7D76EZ.js +81 -0
  32. package/chunk-GY7D76EZ.js.map +1 -0
  33. package/chunk-HHHHZMTA.js +434 -0
  34. package/chunk-HHHHZMTA.js.map +1 -0
  35. package/chunk-HZYOJTEE.js +1275 -0
  36. package/chunk-HZYOJTEE.js.map +1 -0
  37. package/chunk-J3ZRXVI6.js +740 -0
  38. package/chunk-J3ZRXVI6.js.map +1 -0
  39. package/chunk-JJWFO27K.js +31 -0
  40. package/chunk-JJWFO27K.js.map +1 -0
  41. package/chunk-JV6LM2YC.js +39 -0
  42. package/chunk-JV6LM2YC.js.map +1 -0
  43. package/chunk-KER77KJB.js +105 -0
  44. package/chunk-KER77KJB.js.map +1 -0
  45. package/{chunk-V5ZVB7RJ.js → chunk-KKO2XGLQ.js} +1 -6
  46. package/chunk-KKO2XGLQ.js.map +1 -0
  47. package/chunk-LIYPTQAO.js +198 -0
  48. package/chunk-LIYPTQAO.js.map +1 -0
  49. package/chunk-LYLDVUHT.js +131 -0
  50. package/chunk-LYLDVUHT.js.map +1 -0
  51. package/chunk-PFWBO2VK.js +801 -0
  52. package/chunk-PFWBO2VK.js.map +1 -0
  53. package/chunk-RTCRU35A.js +194 -0
  54. package/chunk-RTCRU35A.js.map +1 -0
  55. package/{chunk-F2AM4RWA.js → chunk-RTEEWZUT.js} +2 -2
  56. package/{chunk-F2AM4RWA.js.map → chunk-RTEEWZUT.js.map} +1 -1
  57. package/{chunk-BRV4D3P2.js → chunk-RUKMHBNQ.js} +2 -2
  58. package/chunk-SA4DYSBR.js +31 -0
  59. package/chunk-SA4DYSBR.js.map +1 -0
  60. package/chunk-SJPOFQJU.js +792 -0
  61. package/chunk-SJPOFQJU.js.map +1 -0
  62. package/{chunk-V7A6ZFHR.js → chunk-SMPSKBAP.js} +25 -774
  63. package/chunk-SMPSKBAP.js.map +1 -0
  64. package/{chunk-E53W6UVQ.js → chunk-T2X2EGV2.js} +4 -4
  65. package/chunk-T2X2EGV2.js.map +1 -0
  66. package/chunk-U2GQH6AD.js +309 -0
  67. package/chunk-U2GQH6AD.js.map +1 -0
  68. package/chunk-U6A2RPHO.js +66 -0
  69. package/chunk-U6A2RPHO.js.map +1 -0
  70. package/chunk-UIXUGVZB.js +362 -0
  71. package/chunk-UIXUGVZB.js.map +1 -0
  72. package/chunk-XRZKJACM.js +49 -0
  73. package/chunk-XRZKJACM.js.map +1 -0
  74. package/chunk-YDS3X7KB.js +202 -0
  75. package/chunk-YDS3X7KB.js.map +1 -0
  76. package/{chunk-A6TMOGPR.js → chunk-ZKNJW4K6.js} +1412 -334
  77. package/chunk-ZKNJW4K6.js.map +1 -0
  78. package/chunk-ZXSCBS77.js +90 -0
  79. package/chunk-ZXSCBS77.js.map +1 -0
  80. package/{computer-use-RRD7BCCK.js → computer-use-6AEVW47F.js} +9 -7
  81. package/computer-use-6AEVW47F.js.map +1 -0
  82. package/{connector-XX7UU6XE.js → connector-XDQ6JEBU.js} +25 -13
  83. package/connector-XDQ6JEBU.js.map +1 -0
  84. package/{credit-GDNNAQRO.js → credit-JPQA5XPA.js} +8 -10
  85. package/credit-JPQA5XPA.js.map +1 -0
  86. package/{developer-support-IISP5UBI.js → developer-support-V7NZOU2P.js} +27 -7
  87. package/developer-support-V7NZOU2P.js.map +1 -0
  88. package/{doctor-IZM2TJOH.js → doctor-FJO24TG3.js} +13 -11
  89. package/doctor-FJO24TG3.js.map +1 -0
  90. package/{feishu-XB7SQBSI.js → feishu-PNOAM33Q.js} +99 -9
  91. package/feishu-PNOAM33Q.js.map +1 -0
  92. package/{finance-OGWHKQLU.js → finance-55OJ6GYP.js} +49 -9
  93. package/finance-55OJ6GYP.js.map +1 -0
  94. package/{generate-AA2PVOYQ.js → generate-XUKBK523.js} +26 -21
  95. package/generate-XUKBK523.js.map +1 -0
  96. package/{github-VJVIBTVF.js → github-V4MD2PMM.js} +83 -8
  97. package/github-V4MD2PMM.js.map +1 -0
  98. package/{goal-7SYVHDTK.js → goal-FS5FJKVU.js} +69 -13
  99. package/goal-FS5FJKVU.js.map +1 -0
  100. package/{host-UVQMIOBA.js → host-GITTJ6PR.js} +124 -10
  101. package/host-GITTJ6PR.js.map +1 -0
  102. package/{logs-PIS4X24E.js → logs-EEUIGYUD.js} +51 -11
  103. package/logs-EEUIGYUD.js.map +1 -0
  104. package/{mail-L33OSQ2R.js → mail-G4SAJSBD.js} +39 -8
  105. package/mail-G4SAJSBD.js.map +1 -0
  106. package/{maps-D5XTXU5U.js → maps-7ANNU3BX.js} +65 -11
  107. package/maps-7ANNU3BX.js.map +1 -0
  108. package/{model-ZFMRECDM.js → model-DSPDCJLB.js} +6 -6
  109. package/model-DSPDCJLB.js.map +1 -0
  110. package/{model-provider-EZZ2DRYZ.js → model-provider-RZQ45PNG.js} +6 -6
  111. package/model-provider-RZQ45PNG.js.map +1 -0
  112. package/package.json +1 -1
  113. package/{people-search-PFTIO2QS.js → people-search-I7PUMF5M.js} +22 -6
  114. package/people-search-I7PUMF5M.js.map +1 -0
  115. package/{phone-6SG5ZUNL.js → phone-SSAPGMTW.js} +90 -9
  116. package/phone-SSAPGMTW.js.map +1 -0
  117. package/{recognize-LLU6J3SW.js → recognize-D7VORZBN.js} +27 -9
  118. package/recognize-D7VORZBN.js.map +1 -0
  119. package/{resource-FGUSXS4G.js → resource-76IV3TMW.js} +21 -7
  120. package/resource-76IV3TMW.js.map +1 -0
  121. package/{scrape-BAUZ2YFD.js → scrape-JBDLNTLB.js} +22 -6
  122. package/scrape-JBDLNTLB.js.map +1 -0
  123. package/{search-DLO5RXRM.js → search-UNZNUTZX.js} +29 -9
  124. package/search-UNZNUTZX.js.map +1 -0
  125. package/{slack-CVATPKP3.js → slack-AAH6GG2W.js} +103 -11
  126. package/slack-AAH6GG2W.js.map +1 -0
  127. package/{teams-ZZYO6YIK.js → teams-6OPXE4TX.js} +90 -9
  128. package/teams-6OPXE4TX.js.map +1 -0
  129. package/{telegram-VY7T4YAR.js → telegram-RRZG73RT.js} +101 -10
  130. package/telegram-RRZG73RT.js.map +1 -0
  131. package/{upgrade-GFA4ZUU4.js → upgrade-I5IL4UQL.js} +3 -4
  132. package/upgrade-I5IL4UQL.js.map +1 -0
  133. package/{video-STFG7BET.js → video-HV44W4X7.js} +5 -4
  134. package/video-HV44W4X7.js.map +1 -0
  135. package/{weather-ISJEHJWR.js → weather-EQ7CSADB.js} +70 -16
  136. package/weather-EQ7CSADB.js.map +1 -0
  137. package/{web-YN4CVHK7.js → web-6LIMWEOZ.js} +5 -5
  138. package/web-6LIMWEOZ.js.map +1 -0
  139. package/{web-search-PC7IECND.js → web-search-AT7WONZN.js} +22 -6
  140. package/web-search-AT7WONZN.js.map +1 -0
  141. package/{whoami-KXFXZGM6.js → whoami-RKTLLSI4.js} +16 -7
  142. package/whoami-RKTLLSI4.js.map +1 -0
  143. package/{workflow-O7YZHB7A.js → workflow-ZH32P622.js} +135 -39
  144. package/workflow-ZH32P622.js.map +1 -0
  145. package/zero.js +40 -40
  146. package/agent-HUDTEGLK.js.map +0 -1
  147. package/banking-BMZONEXP.js.map +0 -1
  148. package/browser-LQP445CU.js.map +0 -1
  149. package/chat-UF7QAWUT.js.map +0 -1
  150. package/chunk-2W73DZDW.js +0 -32
  151. package/chunk-2W73DZDW.js.map +0 -1
  152. package/chunk-6PN6QGIM.js +0 -11405
  153. package/chunk-6PN6QGIM.js.map +0 -1
  154. package/chunk-A6TMOGPR.js.map +0 -1
  155. package/chunk-ANOLYIPL.js +0 -10
  156. package/chunk-ANOLYIPL.js.map +0 -1
  157. package/chunk-E53W6UVQ.js.map +0 -1
  158. package/chunk-V5ZVB7RJ.js.map +0 -1
  159. package/chunk-V7A6ZFHR.js.map +0 -1
  160. package/computer-use-RRD7BCCK.js.map +0 -1
  161. package/connector-XX7UU6XE.js.map +0 -1
  162. package/credit-GDNNAQRO.js.map +0 -1
  163. package/developer-support-IISP5UBI.js.map +0 -1
  164. package/doctor-IZM2TJOH.js.map +0 -1
  165. package/feishu-XB7SQBSI.js.map +0 -1
  166. package/finance-OGWHKQLU.js.map +0 -1
  167. package/generate-AA2PVOYQ.js.map +0 -1
  168. package/github-VJVIBTVF.js.map +0 -1
  169. package/goal-7SYVHDTK.js.map +0 -1
  170. package/host-UVQMIOBA.js.map +0 -1
  171. package/logs-PIS4X24E.js.map +0 -1
  172. package/mail-L33OSQ2R.js.map +0 -1
  173. package/maps-D5XTXU5U.js.map +0 -1
  174. package/model-ZFMRECDM.js.map +0 -1
  175. package/model-provider-EZZ2DRYZ.js.map +0 -1
  176. package/people-search-PFTIO2QS.js.map +0 -1
  177. package/phone-6SG5ZUNL.js.map +0 -1
  178. package/recognize-LLU6J3SW.js.map +0 -1
  179. package/resource-FGUSXS4G.js.map +0 -1
  180. package/scrape-BAUZ2YFD.js.map +0 -1
  181. package/search-DLO5RXRM.js.map +0 -1
  182. package/slack-CVATPKP3.js.map +0 -1
  183. package/teams-ZZYO6YIK.js.map +0 -1
  184. package/telegram-VY7T4YAR.js.map +0 -1
  185. package/upgrade-GFA4ZUU4.js.map +0 -1
  186. package/video-STFG7BET.js.map +0 -1
  187. package/weather-ISJEHJWR.js.map +0 -1
  188. package/web-YN4CVHK7.js.map +0 -1
  189. package/web-search-PC7IECND.js.map +0 -1
  190. package/whoami-KXFXZGM6.js.map +0 -1
  191. package/workflow-O7YZHB7A.js.map +0 -1
  192. /package/{chunk-QC63TUJC.js.map → chunk-C62A6LD6.js.map} +0 -0
  193. /package/{chunk-5ZZI2LSO.js.map → chunk-GHKWW4NC.js.map} +0 -0
  194. /package/{chunk-BRV4D3P2.js.map → chunk-RUKMHBNQ.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/zero/computer-use/index.ts","../src/commands/zero/computer-use/output-artifacts.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { Command } from \"commander\";\nimport type {\n ComputerUseCommandResponse,\n ComputerUseReadCommandKind,\n ComputerUseWriteCommandKind,\n} from \"@vm0/api-contracts/contracts/zero-computer-use\";\nimport {\n COMPUTER_USE_FILESYSTEM_PLUGIN,\n COMPUTER_USE_MCP_LIST_TOOLS,\n COMPUTER_USE_MCP_PLUGIN,\n type ComputerUseMcpPluginCallBody,\n type ComputerUseFilesystemTool,\n type ComputerUsePluginCallBody,\n} from \"@vm0/api-contracts/contracts/zero-computer-use-plugins\";\nimport {\n ApiRequestError,\n createComputerUsePluginCommand,\n listComputerUseHosts,\n createComputerUseReadCommand,\n createComputerUseWriteCommand,\n fetchComputerUsePluginContent,\n fetchComputerUseScreenshot,\n getComputerUseCommand,\n} from \"../../../lib/api\";\nimport { withErrorHandler } from \"../../../lib/command/with-error-handler\";\nimport {\n computerUseOutputDir,\n writeComputerUseArtifact,\n} from \"./output-artifacts\";\n\ninterface ComputerUseCommandOptions {\n readonly timeout?: string;\n}\n\ninterface ComputerUseAppOptions extends ComputerUseCommandOptions {\n readonly app: string;\n}\n\ninterface ComputerUseClickOptions extends ComputerUseAppOptions {\n readonly snapshotId?: string;\n readonly element?: string;\n readonly elementIndex?: string;\n readonly x?: string;\n readonly y?: string;\n readonly button?: \"left\" | \"right\" | \"middle\";\n readonly clickCount?: string;\n}\n\ninterface ComputerUseScrollOptions extends ComputerUseAppOptions {\n readonly snapshotId?: string;\n readonly element?: string;\n readonly elementIndex?: string;\n readonly direction: \"up\" | \"down\" | \"left\" | \"right\";\n readonly pages?: string;\n}\n\ninterface ComputerUseSetValueOptions extends ComputerUseAppOptions {\n readonly snapshotId?: string;\n readonly element?: string;\n readonly elementIndex?: string;\n readonly value: string;\n}\n\ninterface ComputerUsePerformActionOptions extends ComputerUseAppOptions {\n readonly snapshotId?: string;\n readonly element?: string;\n readonly elementIndex?: string;\n readonly action: string;\n}\n\ninterface ComputerUseTypeTextOptions extends ComputerUseAppOptions {\n readonly snapshotId?: string;\n readonly text: string;\n}\n\ninterface ComputerUsePressKeyOptions extends ComputerUseAppOptions {\n readonly snapshotId?: string;\n readonly key: string;\n}\n\ninterface ComputerUsePluginOptions extends ComputerUseCommandOptions {\n readonly argumentsJson?: string;\n}\n\ninterface FilesystemPathOptions extends ComputerUsePluginOptions {\n readonly path: string;\n}\n\ninterface FilesystemReadTextOptions extends FilesystemPathOptions {\n readonly head?: string;\n readonly tail?: string;\n}\n\ninterface FilesystemReadMultipleFilesOptions extends ComputerUsePluginOptions {\n readonly path: readonly string[];\n}\n\ninterface FilesystemWriteFileOptions extends FilesystemPathOptions {\n readonly content: string;\n}\n\ninterface FilesystemEditFileOptions extends FilesystemPathOptions {\n readonly oldText?: string;\n readonly newText?: string;\n readonly dryRun?: boolean;\n}\n\ninterface FilesystemListDirectoryWithSizesOptions extends FilesystemPathOptions {\n readonly sortBy?: \"name\" | \"size\";\n}\n\ninterface FilesystemDirectoryTreeOptions extends FilesystemPathOptions {\n readonly excludePattern?: readonly string[];\n}\n\ninterface FilesystemMoveFileOptions extends ComputerUsePluginOptions {\n readonly source: string;\n readonly destination: string;\n}\n\ninterface FilesystemSearchFilesOptions extends FilesystemPathOptions {\n readonly pattern: string;\n readonly excludePattern?: readonly string[];\n}\n\nconst DATA_URL_PATTERN = /^data:([^;,]+);base64,(.*)$/s;\nconst COMPUTER_USE_REQUIRED_CAPABILITY_MESSAGE =\n \"Missing required capability: computer-use:write\";\nconst COMPUTER_USE_AUTHORIZATION_REQUIRED_ERROR =\n \"COMPUTER_USE_AUTHORIZATION_REQUIRED\";\nconst COMPUTER_USE_HELP_TEXT = `\nWorkflow:\n 1. Start the Zero Desktop app and make sure Computer Use is online.\n 2. Run \"zero computer-use list-apps\" to find the target app's bundleId.\n --app accepts a bundle id only (e.g. com.google.Chrome); the name is for\n display. Apps listed without a bundleId cannot be targeted.\n 3. Run \"zero computer-use get-app-state --app <bundleId>\" to get a screenshot,\n snapshotId, visible element indexes, and accessibility state.\n 4. Prefer element actions with --snapshot-id and --element-index. Use --x/--y\n only when the target is visible in the returned screenshot but has no useful\n accessibility element.\n 5. Read the JSON result. Screenshot and App State data are saved under\n /tmp/vm0/computer-use and replaced with local file paths in CLI output.\n Files are named from app and snapshotId; rerunning the same snapshot\n overwrites the same files.\n\nNotes:\n Write commands are sent to the connected Desktop host. Coordinate fallbacks use\n screenshot coordinates from get-app-state; pass the matching --snapshot-id when\n acting on a prior snapshot.\n type-text sends literal keyboard input to the target app's current focus. It\n first verifies the focused element is editable and fails with\n element_not_editable when it is not (for example a focused table or list), so\n click into a text field before typing. Use set-value when you need\n deterministic accessibility value assignment.\n press-key accepts xdotool-style names such as shift+semicolon, Control_L+J,\n ctrl+alt+n, and BackSpace, plus existing macOS-style forms such as Command+L.\n type-text and press-key accept the same --snapshot-id as the element actions:\n pass it to deliver keyboard input to that snapshot's window. Without it, the\n most relevant window for the app is picked, which is ambiguous for multi-window\n apps.\n\nExamples:\n List available apps:\n zero computer-use list-apps\n\n Inspect Safari state:\n zero computer-use get-app-state --app com.apple.Safari\n\n Click element index 7 from snapshot desktop_abc:\n zero computer-use click --app com.apple.Safari --snapshot-id desktop_abc --element-index 7\n\n Click screenshot coordinate (320, 240) from snapshot desktop_abc:\n zero computer-use click --app com.apple.Safari --snapshot-id desktop_abc --x 320 --y 240\n\n Type text into the snapshot desktop_abc window in Safari:\n zero computer-use type-text --app com.apple.Safari --snapshot-id desktop_abc --text \"Hello\"\n\n Press a keyboard shortcut in the snapshot desktop_abc window:\n zero computer-use press-key --app com.apple.Safari --snapshot-id desktop_abc --key shift+semicolon\n\n Open an app without activating the current foreground app:\n zero computer-use open-app --app com.culturedcode.ThingsMac`;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nfunction throwComputerUseAuthorizationGuidanceError(error: unknown): never {\n if (\n error instanceof ApiRequestError &&\n error.status === 403 &&\n error.code === \"FORBIDDEN\" &&\n error.message === COMPUTER_USE_REQUIRED_CAPABILITY_MESSAGE\n ) {\n throw new ApiRequestError(\n \"Computer Use authorization required\",\n COMPUTER_USE_AUTHORIZATION_REQUIRED_ERROR,\n 403,\n );\n }\n\n throw error;\n}\n\nfunction parseTimeoutSeconds(value: string | undefined): number {\n if (!value) return 30;\n const seconds = Number.parseInt(value, 10);\n if (!Number.isFinite(seconds) || seconds <= 0) {\n throw new Error(\"Timeout must be a positive number of seconds\");\n }\n return seconds;\n}\n\nfunction parseOptionalNonNegativeInteger(\n value: string | undefined,\n label: string,\n): number | undefined {\n if (value === undefined) return undefined;\n const parsed = Number.parseInt(value, 10);\n if (!Number.isFinite(parsed) || parsed < 0) {\n throw new Error(`${label} must be a non-negative integer`);\n }\n return parsed;\n}\n\nfunction parsePositiveInteger(\n value: string | undefined,\n label: string,\n): number {\n if (value === undefined) {\n throw new Error(`${label} is required`);\n }\n const parsed = Number.parseInt(value, 10);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(`${label} must be a positive integer`);\n }\n return parsed;\n}\n\nfunction parsePositiveNumber(\n value: string | undefined,\n label: string,\n): number | undefined {\n if (value === undefined) return undefined;\n const parsed = Number.parseFloat(value);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(`${label} must be a positive number`);\n }\n return parsed;\n}\n\nfunction parseMouseButton(\n value: string | undefined,\n): \"left\" | \"right\" | \"middle\" {\n if (value === \"left\" || value === \"right\" || value === \"middle\") {\n return value;\n }\n throw new Error(\"button must be left, right, or middle\");\n}\n\nfunction elementTargetPayload(options: {\n readonly element?: string;\n readonly elementIndex?: string;\n}): { readonly elementId?: string; readonly elementIndex?: number } {\n const elementIndex = parseOptionalNonNegativeInteger(\n options.elementIndex,\n \"element-index\",\n );\n if (!options.element && elementIndex === undefined) {\n throw new Error(\"element or element-index is required\");\n }\n return {\n ...(options.element ? { elementId: options.element } : {}),\n ...(elementIndex !== undefined ? { elementIndex } : {}),\n };\n}\n\nfunction sanitizeFilenamePart(value: unknown, fallback: string): string {\n if (typeof value !== \"string\") {\n return fallback;\n }\n const sanitized = value\n .trim()\n .replace(/[^A-Za-z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 80);\n return sanitized.length > 0 ? sanitized : fallback;\n}\n\nfunction extensionForMimeType(mimeType: string): string {\n if (mimeType === \"image/png\") {\n return \"png\";\n }\n if (mimeType === \"image/jpeg\") {\n return \"jpg\";\n }\n if (mimeType === \"image/webp\") {\n return \"webp\";\n }\n const suffix = mimeType.startsWith(\"image/\") ? mimeType.slice(6) : \"bin\";\n return sanitizeFilenamePart(suffix, \"bin\").toLowerCase();\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(\n value: Record<string, unknown>,\n key: string,\n): string | undefined {\n const field = value[key];\n return typeof field === \"string\" ? field : undefined;\n}\n\nasync function writeScreenshotDataUrl(\n result: Record<string, unknown>,\n dataUrl: string,\n): Promise<string | null> {\n const match = DATA_URL_PATTERN.exec(dataUrl);\n if (!match) {\n return null;\n }\n\n const mimeType = match[1] ?? \"\";\n if (!mimeType.startsWith(\"image/\")) {\n throw new Error(`Unsupported screenshot MIME type: ${mimeType}`);\n }\n\n const base64Data = match[2] ?? \"\";\n const appName = sanitizeFilenamePart(result.app, \"app\");\n const snapshotId = sanitizeFilenamePart(result.snapshotId, \"snapshot\");\n const outputPath = join(\n computerUseOutputDir(),\n `${appName}-${snapshotId}.${extensionForMimeType(mimeType)}`,\n );\n\n await writeComputerUseArtifact(outputPath, Buffer.from(base64Data, \"base64\"));\n return outputPath;\n}\n\nfunction screenshotPointerType(value: unknown): \"s3\" | \"expired\" | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const type = (value as { readonly type?: unknown }).type;\n return type === \"s3\" || type === \"expired\" ? type : null;\n}\n\nasync function writeScreenshotBytes(\n result: Record<string, unknown>,\n buffer: Buffer,\n mimeType: string,\n): Promise<string> {\n const appName = sanitizeFilenamePart(result.app, \"app\");\n const snapshotId = sanitizeFilenamePart(result.snapshotId, \"snapshot\");\n const outputPath = join(\n computerUseOutputDir(),\n `${appName}-${snapshotId}.${extensionForMimeType(mimeType)}`,\n );\n\n await writeComputerUseArtifact(outputPath, buffer);\n return outputPath;\n}\n\nasync function writeAppStateText(\n result: Record<string, unknown>,\n appState: string,\n): Promise<string> {\n const appName = sanitizeFilenamePart(result.app, \"app\");\n const snapshotId = sanitizeFilenamePart(result.snapshotId, \"snapshot\");\n const outputPath = join(\n computerUseOutputDir(),\n `${appName}-${snapshotId}.appState.txt`,\n );\n\n await writeComputerUseArtifact(outputPath, appState);\n return outputPath;\n}\n\nfunction compactActionResult(\n action: Record<string, unknown>,\n): Record<string, unknown> {\n const compact: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(action)) {\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n compact[key] = value;\n }\n }\n return compact;\n}\n\nexport async function formatComputerUseResultForConsole(\n result: Record<string, unknown>,\n commandId: string,\n): Promise<string> {\n const printable: Record<string, unknown> = { status: \"succeeded\" };\n const apps = result.apps;\n if (Array.isArray(apps)) {\n printable.apps = apps;\n }\n const snapshotId = stringField(result, \"snapshotId\");\n if (snapshotId) {\n printable.snapshotId = snapshotId;\n }\n const appState = stringField(result, \"appState\");\n if (appState) {\n printable.appState = await writeAppStateText(result, appState);\n }\n const screenshot = result.screenshot;\n if (typeof screenshot === \"string\") {\n const screenshotPath = await writeScreenshotDataUrl(result, screenshot);\n printable.screenshot = screenshotPath ?? screenshot;\n } else {\n const pointerType = screenshotPointerType(screenshot);\n if (pointerType === \"s3\") {\n const { buffer, mimeType } = await fetchComputerUseScreenshot(commandId);\n printable.screenshot = await writeScreenshotBytes(\n result,\n buffer,\n mimeType,\n );\n } else if (pointerType === \"expired\") {\n printable.screenshot = \"[screenshot expired]\";\n }\n }\n const action = result.action;\n if (isRecord(action)) {\n printable.action = compactActionResult(action);\n }\n return JSON.stringify(printable, null, 2);\n}\n\nasync function commandOutputText(\n command: ComputerUseCommandResponse,\n): Promise<string> {\n if (!command.result) {\n return \"\";\n }\n return await formatComputerUseResultForConsole(command.result, command.id);\n}\n\nfunction pluginContentPointerType(value: unknown): \"s3\" | \"expired\" | null {\n if (!isRecord(value)) {\n return null;\n }\n const type = value.type;\n return type === \"s3\" || type === \"expired\" ? type : null;\n}\n\nfunction pluginContentFileName(value: unknown): string {\n if (!isRecord(value) || typeof value.fileName !== \"string\") {\n return \"plugin-content.bin\";\n }\n return sanitizeFilenamePart(value.fileName, \"plugin-content.bin\");\n}\n\nasync function writePluginContent(\n commandId: string,\n result: Record<string, unknown>,\n): Promise<string> {\n const downloaded = await fetchComputerUsePluginContent(commandId);\n const pointerFileName = pluginContentFileName(result.pluginContent);\n const directoryName = sanitizeFilenamePart(commandId, \"command\");\n const outputPath = join(\n computerUseOutputDir(),\n \"plugins\",\n directoryName,\n sanitizeFilenamePart(\n downloaded.fileName || pointerFileName,\n pointerFileName,\n ),\n );\n await writeComputerUseArtifact(outputPath, downloaded.buffer);\n return outputPath;\n}\n\nfunction formatHumanValue(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (Array.isArray(value)) {\n return value.map(formatHumanValue).join(\"\\n\");\n }\n if (value === null || value === undefined) {\n return \"\";\n }\n return JSON.stringify(value, null, 2);\n}\n\nasync function pluginCommandOutputText(\n command: ComputerUseCommandResponse,\n): Promise<string> {\n const result = command.result;\n if (!result) {\n return \"\";\n }\n const content = stringField(result, \"content\");\n if (content) {\n return content;\n }\n\n const pluginContentType = pluginContentPointerType(result.pluginContent);\n if (pluginContentType === \"s3\") {\n const outputPath = await writePluginContent(command.id, result);\n const sizeBytes =\n typeof result.sizeBytes === \"number\"\n ? ` (${result.sizeBytes} bytes)`\n : \"\";\n return `Saved plugin content${sizeBytes}: ${outputPath}`;\n }\n if (pluginContentType === \"expired\") {\n return \"Plugin content expired.\";\n }\n\n const lines: string[] = [];\n for (const [key, value] of Object.entries(result)) {\n if (key === \"pluginContent\") {\n continue;\n }\n const formatted = formatHumanValue(value);\n if (formatted) {\n lines.push(`${key}: ${formatted}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\nasync function waitForCommand(\n commandId: string,\n timeoutSeconds: number,\n formatter: (\n command: ComputerUseCommandResponse,\n ) => Promise<string> = commandOutputText,\n): Promise<void> {\n const deadline = Date.now() + timeoutSeconds * 1000;\n while (Date.now() <= deadline) {\n const command = await getComputerUseCommand(commandId);\n if (command.status === \"queued\" || command.status === \"running\") {\n if (process.stdout.isTTY) {\n process.stdout.write(\".\");\n }\n await sleep(500);\n continue;\n }\n\n if (process.stdout.isTTY) {\n process.stdout.write(\"\\n\");\n }\n\n if (command.status === \"failed\") {\n throw new Error(\n command.error\n ? `${command.error.code}: ${command.error.message}`\n : \"Computer-use command failed\",\n );\n }\n\n const text = await formatter(command);\n if (text) {\n console.log(text);\n }\n return;\n }\n\n throw new Error(`Computer-use command timed out: ${commandId}`);\n}\n\nasync function runReadCommand(\n kind: ComputerUseReadCommandKind,\n options: ComputerUseCommandOptions,\n payload: { readonly app?: string } = {},\n): Promise<void> {\n const timeoutSeconds = parseTimeoutSeconds(options.timeout);\n try {\n const created = await createComputerUseReadCommand({\n kind,\n timeoutMs: timeoutSeconds * 1000,\n ...payload,\n });\n await waitForCommand(created.commandId, timeoutSeconds);\n } catch (error) {\n throwComputerUseAuthorizationGuidanceError(error);\n }\n}\n\nasync function runWriteCommand(\n kind: ComputerUseWriteCommandKind,\n options: ComputerUseCommandOptions,\n payload: {\n readonly app: string;\n readonly snapshotId?: string;\n readonly elementId?: string;\n readonly elementIndex?: number;\n readonly x?: number;\n readonly y?: number;\n readonly button?: \"left\" | \"right\" | \"middle\";\n readonly clickCount?: number;\n readonly direction?: \"up\" | \"down\" | \"left\" | \"right\";\n readonly pages?: number;\n readonly value?: string;\n readonly text?: string;\n readonly key?: string;\n readonly action?: string;\n },\n): Promise<void> {\n const timeoutSeconds = parseTimeoutSeconds(options.timeout);\n try {\n const created = await createComputerUseWriteCommand({\n kind,\n timeoutMs: timeoutSeconds * 1000,\n ...payload,\n });\n await waitForCommand(created.commandId, timeoutSeconds);\n } catch (error) {\n throwComputerUseAuthorizationGuidanceError(error);\n }\n}\n\nfunction parseArgumentsJson(\n value: string | undefined,\n): Record<string, unknown> {\n if (!value) {\n return {};\n }\n const parsed: unknown = JSON.parse(value);\n if (!isRecord(parsed)) {\n throw new Error(\"arguments-json must be a JSON object\");\n }\n return parsed;\n}\n\nfunction withArgumentsJson(\n options: ComputerUsePluginOptions,\n fallback: Record<string, unknown>,\n): Record<string, unknown> {\n return options.argumentsJson\n ? parseArgumentsJson(options.argumentsJson)\n : fallback;\n}\n\nfunction parseOptionalPositiveInteger(\n value: string | undefined,\n label: string,\n): number | undefined {\n if (value === undefined) {\n return undefined;\n }\n return parsePositiveInteger(value, label);\n}\n\nasync function runFilesystemPluginCommand(\n tool: ComputerUseFilesystemTool,\n options: ComputerUsePluginOptions,\n args: Record<string, unknown>,\n): Promise<void> {\n const timeoutSeconds = parseTimeoutSeconds(options.timeout);\n const body: ComputerUsePluginCallBody = {\n plugin: COMPUTER_USE_FILESYSTEM_PLUGIN,\n tool,\n arguments: args,\n timeoutMs: timeoutSeconds * 1000,\n };\n try {\n const created = await createComputerUsePluginCommand(body);\n await waitForCommand(\n created.commandId,\n timeoutSeconds,\n pluginCommandOutputText,\n );\n } catch (error) {\n throwComputerUseAuthorizationGuidanceError(error);\n }\n}\n\nfunction addTargetOptions(command: Command): Command {\n return command.option(\"--timeout <seconds>\", \"Maximum time to wait\", \"30\");\n}\n\nfunction addPluginOptions(command: Command): Command {\n return addTargetOptions(command).option(\n \"--arguments-json <json>\",\n \"Raw tool arguments object for advanced cases\",\n );\n}\n\nfunction appOption(command: Command): Command {\n return command.requiredOption(\n \"--app <bundleId>\",\n \"Target app bundle id (e.g. com.google.Chrome); run list-apps to find it\",\n );\n}\n\nconst listAppsCommand = addTargetOptions(\n new Command()\n .name(\"list-apps\")\n .description(\"List apps available to the Desktop Computer Use host\")\n .action(\n withErrorHandler(async (options: ComputerUseCommandOptions) => {\n await runReadCommand(\"apps.list\", options);\n }),\n ),\n);\n\nconst getAppStateCommand = appOption(\n addTargetOptions(\n new Command()\n .name(\"get-app-state\")\n .description(\n \"Get screenshot and accessibility state without activating an app\",\n )\n .action(\n withErrorHandler(async (options: ComputerUseAppOptions) => {\n await runReadCommand(\"app.state\", options, { app: options.app });\n }),\n ),\n ),\n);\n\nconst clickCommand = appOption(\n addTargetOptions(\n new Command()\n .name(\"click\")\n .description(\n \"Click an accessibility element or background screenshot coordinate\",\n )\n .option(\"--snapshot-id <id>\", \"Snapshot id returned by get-app-state\")\n .option(\"--element <id>\", \"Element id from get-app-state\")\n .option(\"--element-index <index>\", \"Element index from get-app-state\")\n .option(\"--x <points>\", \"Screenshot x coordinate fallback\")\n .option(\"--y <points>\", \"Screenshot y coordinate fallback\")\n .option(\"--button <button>\", \"Mouse button\", \"left\")\n .option(\"--click-count <count>\", \"Number of clicks\", \"1\")\n .action(\n withErrorHandler(async (options: ComputerUseClickOptions) => {\n const x = parseOptionalNonNegativeInteger(options.x, \"x\");\n const y = parseOptionalNonNegativeInteger(options.y, \"y\");\n const elementIndex = parseOptionalNonNegativeInteger(\n options.elementIndex,\n \"element-index\",\n );\n await runWriteCommand(\"element.click\", options, {\n app: options.app,\n ...(options.snapshotId ? { snapshotId: options.snapshotId } : {}),\n ...(options.element ? { elementId: options.element } : {}),\n ...(elementIndex !== undefined ? { elementIndex } : {}),\n ...(x !== undefined ? { x } : {}),\n ...(y !== undefined ? { y } : {}),\n button: parseMouseButton(options.button),\n clickCount: parsePositiveInteger(options.clickCount, \"click-count\"),\n });\n }),\n ),\n ),\n);\n\nconst scrollCommand = appOption(\n addTargetOptions(\n new Command()\n .name(\"scroll\")\n .description(\"Scroll an accessibility element\")\n .option(\"--snapshot-id <id>\", \"Snapshot id returned by get-app-state\")\n .option(\"--element <id>\", \"Element id from get-app-state\")\n .option(\"--element-index <index>\", \"Element index from get-app-state\")\n .requiredOption(\n \"--direction <direction>\",\n \"Scroll direction: up, down, left, or right\",\n )\n .option(\"--pages <count>\", \"Number of pages to scroll\", \"1\")\n .action(\n withErrorHandler(async (options: ComputerUseScrollOptions) => {\n await runWriteCommand(\"element.scroll\", options, {\n app: options.app,\n ...(options.snapshotId ? { snapshotId: options.snapshotId } : {}),\n ...elementTargetPayload(options),\n direction: options.direction,\n pages: parsePositiveNumber(options.pages, \"pages\"),\n });\n }),\n ),\n ),\n);\n\nconst setValueCommand = appOption(\n addTargetOptions(\n new Command()\n .name(\"set-value\")\n .description(\"Set the value of a settable accessibility element\")\n .option(\"--snapshot-id <id>\", \"Snapshot id returned by get-app-state\")\n .option(\"--element <id>\", \"Element id from get-app-state\")\n .option(\"--element-index <index>\", \"Element index from get-app-state\")\n .requiredOption(\"--value <text>\", \"Value to assign\")\n .action(\n withErrorHandler(async (options: ComputerUseSetValueOptions) => {\n await runWriteCommand(\"element.set_value\", options, {\n app: options.app,\n ...(options.snapshotId ? { snapshotId: options.snapshotId } : {}),\n ...elementTargetPayload(options),\n value: options.value,\n });\n }),\n ),\n ),\n);\n\nconst typeTextCommand = appOption(\n addTargetOptions(\n new Command()\n .name(\"type-text\")\n .description(\"Type literal keyboard input into the target app\")\n .option(\"--snapshot-id <id>\", \"Snapshot id returned by get-app-state\")\n .requiredOption(\"--text <text>\", \"Text to type\")\n .action(\n withErrorHandler(async (options: ComputerUseTypeTextOptions) => {\n await runWriteCommand(\"keyboard.type_text\", options, {\n app: options.app,\n ...(options.snapshotId ? { snapshotId: options.snapshotId } : {}),\n text: options.text,\n });\n }),\n ),\n ),\n);\n\nconst pressKeyCommand = appOption(\n addTargetOptions(\n new Command()\n .name(\"press-key\")\n .description(\"Send a background key or key combination to the target app\")\n .option(\"--snapshot-id <id>\", \"Snapshot id returned by get-app-state\")\n .requiredOption(\n \"--key <key>\",\n \"Key or xdotool-style combination, for example Command+K, shift+semicolon, or Control_L+J\",\n )\n .action(\n withErrorHandler(async (options: ComputerUsePressKeyOptions) => {\n await runWriteCommand(\"keyboard.press_key\", options, {\n app: options.app,\n ...(options.snapshotId ? { snapshotId: options.snapshotId } : {}),\n key: options.key,\n });\n }),\n ),\n ),\n);\n\nconst performActionCommand = appOption(\n addTargetOptions(\n new Command()\n .name(\"perform-action\")\n .description(\"Invoke a secondary accessibility action\")\n .option(\"--snapshot-id <id>\", \"Snapshot id returned by get-app-state\")\n .option(\"--element <id>\", \"Element id from get-app-state\")\n .option(\"--element-index <index>\", \"Element index from get-app-state\")\n .requiredOption(\"--action <name>\", \"Accessibility action name\")\n .action(\n withErrorHandler(async (options: ComputerUsePerformActionOptions) => {\n await runWriteCommand(\"element.perform_action\", options, {\n app: options.app,\n ...(options.snapshotId ? { snapshotId: options.snapshotId } : {}),\n ...elementTargetPayload(options),\n action: options.action,\n });\n }),\n ),\n ),\n);\n\nconst openAppCommand = appOption(\n addTargetOptions(\n new Command()\n .name(\"open-app\")\n .description(\"Open an app on the Desktop host without activating it\")\n .action(\n withErrorHandler(async (options: ComputerUseAppOptions) => {\n await runWriteCommand(\"app.open\", options, { app: options.app });\n }),\n ),\n ),\n);\n\nconst filesystemListAllowedDirectoriesCommand = addPluginOptions(\n new Command()\n .name(\"list_allowed_directories\")\n .description(\"List directories enabled in Zero Desktop\")\n .action(\n withErrorHandler(async (options: ComputerUsePluginOptions) => {\n await runFilesystemPluginCommand(\n \"list_allowed_directories\",\n options,\n withArgumentsJson(options, {}),\n );\n }),\n ),\n);\n\nconst filesystemReadTextFileCommand = addPluginOptions(\n new Command()\n .name(\"read_text_file\")\n .description(\"Read a text file\")\n .requiredOption(\"--path <path>\", \"File path\")\n .option(\"--head <lines>\", \"Read the first N lines\")\n .option(\"--tail <lines>\", \"Read the last N lines\")\n .action(\n withErrorHandler(async (options: FilesystemReadTextOptions) => {\n await runFilesystemPluginCommand(\n \"read_text_file\",\n options,\n withArgumentsJson(options, {\n path: options.path,\n ...(options.head\n ? { head: parseOptionalPositiveInteger(options.head, \"head\") }\n : {}),\n ...(options.tail\n ? { tail: parseOptionalPositiveInteger(options.tail, \"tail\") }\n : {}),\n }),\n );\n }),\n ),\n);\n\nconst filesystemReadMediaFileCommand = addPluginOptions(\n new Command()\n .name(\"read_media_file\")\n .description(\"Read an image or audio file\")\n .requiredOption(\"--path <path>\", \"File path\")\n .action(\n withErrorHandler(async (options: FilesystemPathOptions) => {\n await runFilesystemPluginCommand(\n \"read_media_file\",\n options,\n withArgumentsJson(options, { path: options.path }),\n );\n }),\n ),\n);\n\nconst filesystemReadMultipleFilesCommand = addPluginOptions(\n new Command()\n .name(\"read_multiple_files\")\n .description(\"Read multiple text files\")\n .requiredOption(\"--path <path...>\", \"File paths\")\n .action(\n withErrorHandler(async (options: FilesystemReadMultipleFilesOptions) => {\n await runFilesystemPluginCommand(\n \"read_multiple_files\",\n options,\n withArgumentsJson(options, { paths: options.path }),\n );\n }),\n ),\n);\n\nconst filesystemWriteFileCommand = addPluginOptions(\n new Command()\n .name(\"write_file\")\n .description(\"Write a file\")\n .requiredOption(\"--path <path>\", \"File path\")\n .requiredOption(\"--content <text>\", \"File content\")\n .action(\n withErrorHandler(async (options: FilesystemWriteFileOptions) => {\n await runFilesystemPluginCommand(\n \"write_file\",\n options,\n withArgumentsJson(options, {\n path: options.path,\n content: options.content,\n }),\n );\n }),\n ),\n);\n\nconst filesystemEditFileCommand = addPluginOptions(\n new Command()\n .name(\"edit_file\")\n .description(\"Edit a file\")\n .requiredOption(\"--path <path>\", \"File path\")\n .option(\"--old-text <text>\", \"Text to replace\")\n .option(\"--new-text <text>\", \"Replacement text\")\n .option(\"--dry-run\", \"Preview changes without writing\")\n .action(\n withErrorHandler(async (options: FilesystemEditFileOptions) => {\n if (\n !options.argumentsJson &&\n (!options.oldText || options.newText === undefined)\n ) {\n throw new Error(\n \"edit_file requires --old-text and --new-text, or --arguments-json\",\n );\n }\n await runFilesystemPluginCommand(\n \"edit_file\",\n options,\n withArgumentsJson(options, {\n path: options.path,\n edits: [\n {\n oldText: options.oldText,\n newText: options.newText,\n },\n ],\n dryRun: options.dryRun === true,\n }),\n );\n }),\n ),\n);\n\nconst filesystemCreateDirectoryCommand = addPluginOptions(\n new Command()\n .name(\"create_directory\")\n .description(\"Create a directory\")\n .requiredOption(\"--path <path>\", \"Directory path\")\n .action(\n withErrorHandler(async (options: FilesystemPathOptions) => {\n await runFilesystemPluginCommand(\n \"create_directory\",\n options,\n withArgumentsJson(options, { path: options.path }),\n );\n }),\n ),\n);\n\nconst filesystemListDirectoryCommand = addPluginOptions(\n new Command()\n .name(\"list_directory\")\n .description(\"List directory entries\")\n .requiredOption(\"--path <path>\", \"Directory path\")\n .action(\n withErrorHandler(async (options: FilesystemPathOptions) => {\n await runFilesystemPluginCommand(\n \"list_directory\",\n options,\n withArgumentsJson(options, { path: options.path }),\n );\n }),\n ),\n);\n\nconst filesystemListDirectoryWithSizesCommand = addPluginOptions(\n new Command()\n .name(\"list_directory_with_sizes\")\n .description(\"List directory entries with sizes\")\n .requiredOption(\"--path <path>\", \"Directory path\")\n .option(\"--sort-by <field>\", \"Sort by name or size\", \"name\")\n .action(\n withErrorHandler(\n async (options: FilesystemListDirectoryWithSizesOptions) => {\n await runFilesystemPluginCommand(\n \"list_directory_with_sizes\",\n options,\n withArgumentsJson(options, {\n path: options.path,\n sortBy: options.sortBy ?? \"name\",\n }),\n );\n },\n ),\n ),\n);\n\nconst filesystemDirectoryTreeCommand = addPluginOptions(\n new Command()\n .name(\"directory_tree\")\n .description(\"Return a directory tree\")\n .requiredOption(\"--path <path>\", \"Directory path\")\n .option(\"--exclude-pattern <pattern...>\", \"Patterns to exclude\")\n .action(\n withErrorHandler(async (options: FilesystemDirectoryTreeOptions) => {\n await runFilesystemPluginCommand(\n \"directory_tree\",\n options,\n withArgumentsJson(options, {\n path: options.path,\n ...(options.excludePattern\n ? { excludePatterns: options.excludePattern }\n : {}),\n }),\n );\n }),\n ),\n);\n\nconst filesystemMoveFileCommand = addPluginOptions(\n new Command()\n .name(\"move_file\")\n .description(\"Move or rename a file\")\n .requiredOption(\"--source <path>\", \"Source path\")\n .requiredOption(\"--destination <path>\", \"Destination path\")\n .action(\n withErrorHandler(async (options: FilesystemMoveFileOptions) => {\n await runFilesystemPluginCommand(\n \"move_file\",\n options,\n withArgumentsJson(options, {\n source: options.source,\n destination: options.destination,\n }),\n );\n }),\n ),\n);\n\nconst filesystemSearchFilesCommand = addPluginOptions(\n new Command()\n .name(\"search_files\")\n .description(\"Search files by name\")\n .requiredOption(\"--path <path>\", \"Directory path\")\n .requiredOption(\"--pattern <pattern>\", \"Search pattern\")\n .option(\"--exclude-pattern <pattern...>\", \"Patterns to exclude\")\n .action(\n withErrorHandler(async (options: FilesystemSearchFilesOptions) => {\n await runFilesystemPluginCommand(\n \"search_files\",\n options,\n withArgumentsJson(options, {\n path: options.path,\n pattern: options.pattern,\n ...(options.excludePattern\n ? { excludePatterns: options.excludePattern }\n : {}),\n }),\n );\n }),\n ),\n);\n\nconst filesystemGetFileInfoCommand = addPluginOptions(\n new Command()\n .name(\"get_file_info\")\n .description(\"Get file metadata\")\n .requiredOption(\"--path <path>\", \"File or directory path\")\n .action(\n withErrorHandler(async (options: FilesystemPathOptions) => {\n await runFilesystemPluginCommand(\n \"get_file_info\",\n options,\n withArgumentsJson(options, { path: options.path }),\n );\n }),\n ),\n);\n\nconst filesystemPluginCommand = new Command()\n .name(\"filesystem\")\n .description(\"Use the Zero Desktop filesystem plugin\")\n .addCommand(filesystemListAllowedDirectoriesCommand)\n .addCommand(filesystemReadTextFileCommand)\n .addCommand(filesystemReadMediaFileCommand)\n .addCommand(filesystemReadMultipleFilesCommand)\n .addCommand(filesystemWriteFileCommand)\n .addCommand(filesystemEditFileCommand)\n .addCommand(filesystemCreateDirectoryCommand)\n .addCommand(filesystemListDirectoryCommand)\n .addCommand(filesystemListDirectoryWithSizesCommand)\n .addCommand(filesystemDirectoryTreeCommand)\n .addCommand(filesystemMoveFileCommand)\n .addCommand(filesystemSearchFilesCommand)\n .addCommand(filesystemGetFileInfoCommand);\n\nconst MCP_SERVER_CAPABILITY_PREFIX = `plugin.${COMPUTER_USE_MCP_PLUGIN}.`;\n\ninterface ComputerUseMcpCallOptions extends ComputerUseCommandOptions {\n readonly args?: string;\n readonly argsFile?: string;\n}\n\nfunction parseMcpToolArguments(\n options: ComputerUseMcpCallOptions,\n): Record<string, unknown> {\n if (options.args && options.argsFile) {\n throw new Error(\"Pass either --args or --args-file, not both\");\n }\n if (options.argsFile) {\n return parseArgumentsJson(readFileSync(options.argsFile, \"utf8\"));\n }\n return parseArgumentsJson(options.args);\n}\n\nasync function runMcpPluginCommand(\n server: string,\n tool: string,\n options: ComputerUseCommandOptions,\n args: Record<string, unknown>,\n): Promise<void> {\n const timeoutSeconds = parseTimeoutSeconds(options.timeout);\n const body: ComputerUseMcpPluginCallBody = {\n plugin: COMPUTER_USE_MCP_PLUGIN,\n server,\n tool,\n arguments: args,\n timeoutMs: timeoutSeconds * 1000,\n };\n try {\n const created = await createComputerUsePluginCommand(body);\n await waitForCommand(\n created.commandId,\n timeoutSeconds,\n pluginCommandOutputText,\n );\n } catch (error) {\n throwComputerUseAuthorizationGuidanceError(error);\n }\n}\n\nasync function printMcpServers(): Promise<void> {\n const hosts = await listComputerUseHosts().catch((error: unknown) => {\n throwComputerUseAuthorizationGuidanceError(error);\n });\n const lines: string[] = [];\n for (const host of hosts) {\n const servers = host.supportedCapabilities\n .filter((capability) => {\n return capability.startsWith(MCP_SERVER_CAPABILITY_PREFIX);\n })\n .map((capability) => {\n return capability.slice(MCP_SERVER_CAPABILITY_PREFIX.length);\n });\n if (servers.length === 0) {\n continue;\n }\n lines.push(`${host.displayName} (${host.status}): ${servers.join(\", \")}`);\n }\n if (lines.length === 0) {\n console.log(\n \"No MCP servers are running on any linked host. Configure and enable them in the Zero Desktop app's Developer Tools section.\",\n );\n return;\n }\n console.log(lines.join(\"\\n\"));\n}\n\nconst mcpListCommand = new Command()\n .name(\"list\")\n .description(\n \"List MCP servers on linked hosts, or a server's tools and schemas\",\n )\n .argument(\"[server]\", \"MCP server name; omit to list available servers\")\n .action(\n withErrorHandler(\n async (\n server: string | undefined,\n _options: Record<string, never>,\n command: Command,\n ) => {\n if (!server) {\n await printMcpServers();\n return;\n }\n await runMcpPluginCommand(\n server,\n COMPUTER_USE_MCP_LIST_TOOLS,\n command.optsWithGlobals<ComputerUseCommandOptions>(),\n {},\n );\n },\n ),\n );\n\nconst mcpCallCommand = new Command()\n .name(\"call\")\n .description(\"Call a tool on a configured MCP server\")\n .argument(\"<server>\", \"MCP server name (see: plugin mcp list)\")\n .argument(\"<tool>\", \"Tool name (see: plugin mcp list <server>)\")\n .option(\"--args <json>\", \"Tool arguments as a JSON object\")\n .option(\"--args-file <path>\", \"Read tool arguments JSON from a file\")\n .action(\n withErrorHandler(\n async (\n server: string,\n tool: string,\n options: ComputerUseMcpCallOptions,\n command: Command,\n ) => {\n await runMcpPluginCommand(\n server,\n tool,\n command.optsWithGlobals<ComputerUseCommandOptions>(),\n parseMcpToolArguments(options),\n );\n },\n ),\n );\n\nconst mcpPluginCommand = new Command()\n .name(\"mcp\")\n .description(\"Use custom MCP servers configured in the Zero Desktop app\")\n .addCommand(mcpListCommand)\n .addCommand(mcpCallCommand);\n\nconst pluginCommand = addTargetOptions(\n new Command()\n .name(\"plugin\")\n .description(\"Use Desktop Computer Use plugins\")\n .addCommand(filesystemPluginCommand)\n .addCommand(mcpPluginCommand),\n);\n\nexport const zeroComputerUseCommand = new Command()\n .name(\"computer-use\")\n .description(\"Desktop app computer use through Zero CLI\")\n .addHelpText(\"after\", COMPUTER_USE_HELP_TEXT)\n .addCommand(listAppsCommand)\n .addCommand(getAppStateCommand)\n .addCommand(clickCommand)\n .addCommand(scrollCommand)\n .addCommand(setValueCommand)\n .addCommand(typeTextCommand)\n .addCommand(pressKeyCommand)\n .addCommand(performActionCommand)\n .addCommand(openAppCommand)\n .addCommand(pluginCommand);\n","import { randomUUID } from \"node:crypto\";\nimport type { Dirent } from \"node:fs\";\nimport {\n chmod,\n lstat,\n mkdir,\n readdir,\n rename,\n rm,\n writeFile,\n} from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport path from \"node:path\";\n\nconst COMPUTER_USE_OUTPUT_DIR_MODE = 0o700;\nconst COMPUTER_USE_OUTPUT_FILE_MODE = 0o600;\nconst COMPUTER_USE_OUTPUT_TTL_MS = 24 * 60 * 60 * 1000;\nconst DEFAULT_COMPUTER_USE_OUTPUT_DIR = path.join(\n tmpdir(),\n \"vm0\",\n \"computer-use\",\n);\n\nexport function computerUseOutputDir(): string {\n const configured = process.env.VM0_COMPUTER_OUTPUT_DIR?.trim();\n return configured && configured.length > 0\n ? configured\n : DEFAULT_COMPUTER_USE_OUTPUT_DIR;\n}\n\nasync function ensurePrivateDirectory(directory: string): Promise<void> {\n await mkdir(directory, {\n recursive: true,\n mode: COMPUTER_USE_OUTPUT_DIR_MODE,\n });\n const stats = await lstat(directory);\n if (!stats.isDirectory() || stats.isSymbolicLink()) {\n throw new Error(\n `Computer-use output path is not a directory: ${directory}`,\n );\n }\n await chmod(directory, COMPUTER_USE_OUTPUT_DIR_MODE);\n}\n\nasync function removeStaleEntries(\n directory: string,\n cutoffMs: number,\n): Promise<void> {\n let entries: Dirent[];\n try {\n entries = await readdir(directory, { withFileTypes: true });\n } catch (error) {\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n ) {\n return;\n }\n throw error;\n }\n\n for (const entry of entries) {\n const entryPath = path.join(directory, entry.name);\n const stats = await lstat(entryPath).catch(() => {\n return null;\n });\n if (!stats) {\n continue;\n }\n if (entry.isDirectory() && !stats.isSymbolicLink()) {\n await removeStaleEntries(entryPath, cutoffMs);\n continue;\n }\n if (stats.mtimeMs < cutoffMs) {\n await rm(entryPath, { force: true, recursive: entry.isDirectory() });\n }\n }\n}\n\nasync function prepareComputerUseOutputDir(): Promise<string> {\n const outputDir = computerUseOutputDir();\n await ensurePrivateDirectory(outputDir);\n await removeStaleEntries(outputDir, Date.now() - COMPUTER_USE_OUTPUT_TTL_MS);\n return outputDir;\n}\n\nasync function ensureOutputPathDirectory(outputPath: string): Promise<void> {\n const outputDir = await prepareComputerUseOutputDir();\n const directory = path.dirname(outputPath);\n const relative = path.relative(outputDir, directory);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw new Error(`Computer-use artifact path escapes output directory`);\n }\n\n let current = outputDir;\n for (const part of relative.split(path.sep).filter(Boolean)) {\n current = path.join(current, part);\n await ensurePrivateDirectory(current);\n }\n}\n\nexport async function writeComputerUseArtifact(\n outputPath: string,\n data: string | Buffer,\n): Promise<void> {\n await ensureOutputPathDirectory(outputPath);\n const tempPath = path.join(\n path.dirname(outputPath),\n `.${path.basename(outputPath)}.${process.pid.toString()}.${randomUUID()}.tmp`,\n );\n let moved = false;\n try {\n await writeFile(tempPath, data, {\n flag: \"wx\",\n mode: COMPUTER_USE_OUTPUT_FILE_MODE,\n });\n await chmod(tempPath, COMPUTER_USE_OUTPUT_FILE_MODE);\n await rename(tempPath, outputPath);\n moved = true;\n await chmod(outputPath, COMPUTER_USE_OUTPUT_FILE_MODE);\n } finally {\n if (!moved) {\n await rm(tempPath, { force: true });\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,SAAS,oBAAoB;AAC7B,SAAS,YAAY;;;ACDrB;AAAA,SAAS,kBAAkB;AAE3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AACvB,OAAO,UAAU;AAEjB,IAAM,+BAA+B;AACrC,IAAM,gCAAgC;AACtC,IAAM,6BAA6B,KAAK,KAAK,KAAK;AAClD,IAAM,kCAAkC,KAAK;AAAA,EAC3C,OAAO;AAAA,EACP;AAAA,EACA;AACF;AAEO,SAAS,uBAA+B;AAC7C,QAAM,aAAa,QAAQ,IAAI,yBAAyB,KAAK;AAC7D,SAAO,cAAc,WAAW,SAAS,IACrC,aACA;AACN;AAEA,eAAe,uBAAuB,WAAkC;AACtE,QAAM,MAAM,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ACE,QACA,UACA,YACG;AACH,UAAI,CAAC,QAAQ;AACX,cAAM,gBAAgB;AACtB;AAAA,MACF;AACA,YAAM;AAAA,QACJ;AAAA,QACA;AAAA,QACA,QAAQ,gBAA2C;AAAA,QACnD,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;AAEF,IAAM,iBAAiB,IAAI,QAAQ,EAChC,KAAK,MAAM,EACX,YAAY,wCAAwC,EACpD,SAAS,YAAY,wCAAwC,EAC7D,SAAS,UAAU,2CAA2C,EAC9D,OAAO,iBAAiB,iCAAiC,EACzD,OAAO,sBAAsB,sCAAsC,EACnE;AAAA,EACC;AAAA,IACE,OACE,QACA,MACA,SACA,YACG;AACH,YAAM;AAAA,QACJ;AAAA,QACA;AAAA,QACA,QAAQ,gBAA2C;AAAA,QACnD,sBAAsB,OAAO;AAAA,MAC/B;AAAA,IACF;AAAA,EACF;AACF;AAEF,IAAM,mBAAmB,IAAI,QAAQ,EAClC,KAAK,KAAK,EACV,YAAY,2DAA2D,EACvE,WAAW,cAAc,EACzB,WAAW,cAAc;AAE5B,IAAM,gBAAgB;AAAA,EACpB,IAAI,QAAQ,EACT,KAAK,QAAQ,EACb,YAAY,kCAAkC,EAC9C,WAAW,uBAAuB,EAClC,WAAW,gBAAgB;AAChC;AAEO,IAAM,yBAAyB,IAAI,QAAQ,EAC/C,KAAK,cAAc,EACnB,YAAY,2CAA2C,EACvD,YAAY,SAAS,sBAAsB,EAC3C,WAAW,eAAe,EAC1B,WAAW,kBAAkB,EAC7B,WAAW,YAAY,EACvB,WAAW,aAAa,EACxB,WAAW,eAAe,EAC1B,WAAW,eAAe,EAC1B,WAAW,eAAe,EAC1B,WAAW,oBAAoB,EAC/B,WAAW,cAAc,EACzB,WAAW,aAAa;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/zero/connector/index.ts","../src/commands/zero/connector/check.ts","../src/commands/zero/connector/computer-use-guidance.ts","../src/commands/zero/connector/connect.ts","../src/commands/zero/connector/list.ts","../src/commands/zero/connector/connected-as.ts","../src/commands/zero/connector/discovery.ts","../src/commands/zero/connector/search.ts","../src/commands/zero/connector/status.ts","../src/commands/zero/connector/custom/index.ts","../src/commands/zero/connector/custom/create.ts","../src/commands/zero/connector/permission-request.ts","../src/commands/zero/connector/browser-guidance.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { checkConnectorCommand } from \"./check\";\nimport { connectCommand } from \"./connect\";\nimport { listCommand } from \"./list\";\nimport { searchCommand } from \"./search\";\nimport { statusCommand } from \"./status\";\nimport { customConnectorCommand } from \"./custom\";\nimport { permissionRequestCommand } from \"./permission-request\";\n\nexport const zeroConnectorCommand = new Command()\n .name(\"connector\")\n .description(\"Manage and diagnose third-party service connections\")\n .addCommand(checkConnectorCommand)\n .addCommand(customConnectorCommand)\n .addCommand(connectCommand)\n .addCommand(listCommand)\n .addCommand(searchCommand)\n .addCommand(statusCommand)\n .addCommand(permissionRequestCommand);\n","import { Command, Option } from \"commander\";\nimport type { ConnectorSlug } from \"@vm0/api-contracts/contracts/connector-identity\";\nimport type {\n ConnectorCheckPolicy,\n ConnectorCheckRequest,\n} from \"@vm0/api-contracts/contracts/zero-connector-check\";\n\nimport { getApiUrl } from \"../../../lib/api/config\";\nimport {\n diagnoseZeroConnectorCheck,\n getZeroConnector,\n type ZeroConnectorCheckDiagnosticResult,\n} from \"../../../lib/api/domains/zero-connectors\";\nimport { getZeroAgentUserConnectors } from \"../../../lib/api/domains/zero-agents\";\nimport { withErrorHandler } from \"../../../lib/command\";\nimport { toPlatformUrl } from \"../doctor/platform-url\";\nimport {\n isComputerUsePermissionTarget,\n printComputerUsePermissionGuidance,\n} from \"./computer-use-guidance\";\nimport {\n CALLBACK_PROMPT_PLACEHOLDER,\n connectorActionUrl,\n currentChatSupportsActionCallback,\n printCallbackActionUrlExample,\n} from \"./action-url\";\n\ninterface CheckConnectorOptions {\n readonly connector?: string;\n readonly envName?: string;\n readonly url?: string;\n readonly method: string;\n readonly checkPermission?: string;\n}\n\ntype ValidatedCheckConnectorOptions = CheckConnectorOptions &\n (\n | { readonly url: string }\n | { readonly url?: undefined; readonly envName: string }\n );\n\nexport type ResolvedDiagnostic = Extract<\n ZeroConnectorCheckDiagnosticResult,\n { readonly outcome: \"resolved\" }\n>;\ntype ResolvedUrlDiagnostic = Extract<\n ResolvedDiagnostic,\n { readonly mode: \"url\" }\n>;\ntype ResolvedEnvironmentDiagnostic = Extract<\n ResolvedDiagnostic,\n { readonly mode: \"environment\" }\n>;\ntype UrlDiagnosticRequest = Extract<\n ConnectorCheckRequest,\n { readonly mode: \"url\" }\n>;\n\ninterface DiagContext {\n readonly environmentNames: readonly string[] | null;\n readonly connectorSlug: ConnectorSlug;\n readonly label: string;\n readonly connectorAvailable: boolean;\n readonly credentialResolution: \"network-boundary\" | \"none\";\n readonly run: ResolvedDiagnostic[\"run\"];\n readonly platformOrigin: string;\n readonly agentId: string | undefined;\n}\n\nfunction stripUrlQueryAndFragment(url: string): string {\n const queryIndex = url.indexOf(\"?\");\n const fragmentIndex = url.indexOf(\"#\");\n let end = url.length;\n if (queryIndex !== -1) end = Math.min(end, queryIndex);\n if (fragmentIndex !== -1) end = Math.min(end, fragmentIndex);\n return url.slice(0, end);\n}\n\nfunction rawUrlAuthorityHasUserinfo(url: string): boolean {\n const schemeEnd = url.indexOf(\"://\");\n if (schemeEnd === -1) return false;\n\n const authorityStart = schemeEnd + 3;\n let authorityEnd = url.length;\n for (const delimiter of [\"/\", \"?\", \"#\"]) {\n const delimiterIndex = url.indexOf(delimiter, authorityStart);\n if (delimiterIndex !== -1) {\n authorityEnd = Math.min(authorityEnd, delimiterIndex);\n }\n }\n return url.slice(authorityStart, authorityEnd).includes(\"@\");\n}\n\nfunction shellQuoteArg(value: string): string {\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\nfunction connectorSelectionCommand(\n url: string,\n method: string,\n connectorSlug: string,\n): string {\n const args = [\n `--url ${shellQuoteArg(url)}`,\n `--connector ${shellQuoteArg(connectorSlug)}`,\n ];\n if (method !== \"GET\") {\n args.push(`--method ${shellQuoteArg(method)}`);\n }\n return `zero connector check ${args.join(\" \")}`;\n}\n\nfunction rawPathFromUrl(url: string): string | undefined {\n const sanitizedUrl = stripUrlQueryAndFragment(url);\n const schemeEnd = sanitizedUrl.indexOf(\"://\");\n if (schemeEnd === -1) return undefined;\n\n const pathStart = sanitizedUrl.indexOf(\"/\", schemeEnd + 3);\n return pathStart === -1 ? \"/\" : sanitizedUrl.slice(pathStart);\n}\n\nfunction isComputerUseCheckTarget(opts: CheckConnectorOptions): boolean {\n return isComputerUsePermissionTarget({\n connectorSlug: opts.connector ?? \"\",\n path: opts.url === undefined ? undefined : rawPathFromUrl(opts.url),\n permission: opts.checkPermission,\n });\n}\n\nfunction validateCheckConnectorOptions(\n opts: CheckConnectorOptions,\n command: Command,\n): asserts opts is ValidatedCheckConnectorOptions {\n const hasUrl = opts.url !== undefined;\n // Reject embedded credentials before the diagnostic request leaves the client.\n if (opts.url !== undefined && rawUrlAuthorityHasUserinfo(opts.url)) {\n throw unsafeInputError(\"invalid-url\");\n }\n if (opts.connector !== undefined && !hasUrl) {\n throw new Error(\n \"--connector can only be used with --url. Add --url <URL> or remove --connector.\",\n );\n }\n if (opts.checkPermission !== undefined && hasUrl) {\n throw new Error(\n \"--check-permission cannot be used with --url because the permission is derived from the request. Remove --check-permission.\",\n );\n }\n if (opts.checkPermission?.trim() === \"\") {\n throw new Error(\"--check-permission requires a non-empty permission name.\");\n }\n if (!hasUrl && command.getOptionValueSource(\"method\") === \"cli\") {\n throw new Error(\n \"--method can only be used with --url. Add --url <URL> or remove --method.\",\n );\n }\n if (opts.envName === undefined && !hasUrl) {\n throw new Error(\n \"Either --env-name or --url is required. Use --help for usage.\",\n );\n }\n}\n\nexport function buildConnectorUrlDiagnosticRequest(args: {\n readonly url: string;\n readonly method: string;\n readonly connectorSlug?: string;\n readonly environmentName?: string;\n}): UrlDiagnosticRequest {\n if (rawUrlAuthorityHasUserinfo(args.url)) {\n throw unsafeInputError(\"invalid-url\");\n }\n return {\n mode: \"url\",\n method: args.method.toUpperCase(),\n url: stripUrlQueryAndFragment(args.url),\n ...(args.connectorSlug !== undefined\n ? { connectorSlug: args.connectorSlug }\n : {}),\n ...(args.environmentName !== undefined\n ? { environmentName: args.environmentName }\n : {}),\n };\n}\n\nfunction buildDiagnosticRequest(\n opts: ValidatedCheckConnectorOptions,\n method: string,\n): ConnectorCheckRequest {\n if (opts.url !== undefined) {\n return buildConnectorUrlDiagnosticRequest({\n method,\n url: opts.url,\n connectorSlug: opts.connector,\n environmentName: opts.envName,\n });\n }\n\n return {\n mode: \"environment\",\n environmentName: opts.envName,\n ...(opts.checkPermission !== undefined\n ? { permission: opts.checkPermission }\n : {}),\n };\n}\n\nfunction requireUrlRequest(\n request: ConnectorCheckRequest,\n): UrlDiagnosticRequest {\n if (request.mode !== \"url\") {\n throw new Error(\n \"Connector diagnostic returned a URL-only outcome for an environment request.\",\n );\n }\n return request;\n}\n\nfunction requestedEnvironmentName(request: ConnectorCheckRequest): string {\n if (request.environmentName === undefined) {\n throw new Error(\n \"Connector diagnostic returned an environment outcome without an environment name.\",\n );\n }\n return request.environmentName;\n}\n\nfunction unsafeInputError(\n reason: Extract<\n ZeroConnectorCheckDiagnosticResult,\n { readonly outcome: \"unsafe-input\" }\n >[\"reason\"],\n): Error {\n switch (reason) {\n case \"invalid-method\":\n return new Error(\n \"connector check requires --method to be a supported HTTP method.\",\n );\n case \"invalid-url\":\n return new Error(\n \"connector check requires --url to be a valid absolute http or https URL.\",\n );\n case \"unsafe-path\":\n return new Error(\n \"connector check cannot diagnose unsafe URL paths because they are blocked before permission policy evaluation.\",\n );\n }\n}\n\nfunction ambiguousConnectorError(\n request: UrlDiagnosticRequest,\n result: Extract<\n ZeroConnectorCheckDiagnosticResult,\n { readonly outcome: \"ambiguous\" }\n >,\n): Error {\n const candidates = [...result.candidates].sort((left, right) => {\n return left.connectorSlug.localeCompare(right.connectorSlug);\n });\n const commands = candidates.map((candidate) => {\n return ` ${connectorSelectionCommand(request.url, request.method, candidate.connectorSlug)}`;\n });\n return new Error(\n `Multiple connectors match ${request.method} ${request.url}: ${candidates\n .map((candidate) => {\n return candidate.connectorSlug;\n })\n .join(\", \")}\\nSelect one explicitly:\\n${commands.join(\"\\n\")}`,\n );\n}\n\nfunction unknownConnectorError(request: ConnectorCheckRequest): Error {\n if (request.mode === \"url\" && request.connectorSlug !== undefined) {\n return new Error(\n `Unknown connector slug: ${request.connectorSlug}\\nRun: zero connector search ${shellQuoteArg(request.connectorSlug)}`,\n );\n }\n return new Error(\"The requested connector is unknown.\");\n}\n\nfunction noMatchError(\n result: Extract<\n ZeroConnectorCheckDiagnosticResult,\n { readonly outcome: \"no-match\" }\n >,\n): Error {\n return new Error(\n result.scope === \"run\"\n ? \"No connector found for provided URL — no connector configured for the current run matches this URL\"\n : \"No connector found for provided URL — no registered connector base URL matches this URL\",\n );\n}\n\nfunction connectorMismatchError(\n request: UrlDiagnosticRequest,\n result: Extract<\n ZeroConnectorCheckDiagnosticResult,\n { readonly outcome: \"connector-mismatch\" }\n >,\n): Error {\n const requestedSlug = request.connectorSlug ?? \"the requested connector\";\n return new Error(\n `Connector ${requestedSlug} does not own ${request.method} ${request.url}; the matching connector is ${result.connector.connectorSlug}\\nRun: ${connectorSelectionCommand(request.url, request.method, result.connector.connectorSlug)}`,\n );\n}\n\nfunction environmentNotOwnedError(\n request: ConnectorCheckRequest,\n result: Extract<\n ZeroConnectorCheckDiagnosticResult,\n { readonly outcome: \"environment-not-owned\" }\n >,\n): Error {\n const environmentName = requestedEnvironmentName(request);\n return new Error(\n `${environmentName} is not an environment name for the ${result.connector.label} connector. Remove --env-name to use the matched route metadata.`,\n );\n}\n\nfunction environmentNotUsedError(\n request: ConnectorCheckRequest,\n result: Extract<\n ZeroConnectorCheckDiagnosticResult,\n { readonly outcome: \"environment-not-used\" }\n >,\n): Error {\n const environmentName = requestedEnvironmentName(request);\n return new Error(\n `${environmentName} is not used by the matched API route. Expected one of: ${result.environmentNames.join(\", \") || \"none\"}. Remove --env-name to use the matched route metadata.`,\n );\n}\n\nexport function resolveConnectorCheckDiagnostic(\n request: ConnectorCheckRequest,\n result: ZeroConnectorCheckDiagnosticResult,\n): ResolvedDiagnostic {\n switch (result.outcome) {\n case \"resolved\":\n return result;\n case \"unsafe-input\":\n throw unsafeInputError(result.reason);\n case \"unknown-connector\":\n throw unknownConnectorError(request);\n case \"unknown-environment\":\n throw new Error(\n `Unknown environment name: ${requestedEnvironmentName(request)} — not managed by any connector`,\n );\n case \"no-match\":\n throw noMatchError(result);\n case \"ambiguous\":\n throw ambiguousConnectorError(requireUrlRequest(request), result);\n case \"connector-mismatch\":\n throw connectorMismatchError(requireUrlRequest(request), result);\n case \"environment-not-owned\":\n throw environmentNotOwnedError(request, result);\n case \"environment-not-used\":\n throw environmentNotUsedError(request, result);\n case \"unresolved-dynamic-base\":\n throw new Error(\n `No authoritative ${result.connector.label} base URL is available for this diagnostic. Verify the ${result.connector.connectorSlug} connector configuration for the affected context and retry.`,\n );\n case \"run-context-unavailable\":\n throw new Error(\n \"The current run context is unavailable for connector diagnosis. Retry from an active run or start a new run.\",\n );\n }\n}\n\nfunction printDiagnosticSummary(\n request: ConnectorCheckRequest,\n result: ResolvedDiagnostic,\n): void {\n if (result.mode === \"url\") {\n const urlRequest = requireUrlRequest(request);\n console.log(\n `URL ${urlRequest.url} matches the ${result.connector.label} connector (slug: ${result.connector.connectorSlug}).`,\n );\n console.log(` Matched base URL: ${result.base}`);\n console.log(` Relative path: ${result.relativePath}`);\n if (result.environmentNames === null) {\n console.log(\" Environment names: unavailable\");\n } else {\n console.log(\n ` Environment names: [${result.environmentNames.join(\", \")}]`,\n );\n }\n return;\n }\n\n console.log(\n `${result.environmentName} is managed by the ${result.connector.label} connector (slug: ${result.connector.connectorSlug}).`,\n );\n}\n\nfunction diagnosticEnvironmentNames(\n result: ResolvedDiagnostic,\n): readonly string[] | null {\n return result.mode === \"url\"\n ? result.environmentNames\n : [result.environmentName];\n}\n\nfunction printConnectorConnectionStatus(\n ctx: DiagContext,\n isConnected: boolean,\n isExpired: boolean,\n hasPermission: boolean,\n): void {\n console.log(\n \"### 2a: Connector status (user must configure via OAuth login or API key)\",\n );\n console.log(\"\");\n if (!ctx.connectorAvailable) {\n console.log(\n `The ${ctx.label} connector is not available for this account.`,\n );\n } else if (!isConnected) {\n console.log(`The ${ctx.label} connector is not connected.`);\n if (ctx.agentId && hasPermission) {\n const connectUrl = connectorActionUrl({\n origin: ctx.platformOrigin,\n path: `/connectors/${ctx.connectorSlug}/connect`,\n agentId: ctx.agentId,\n });\n console.log(`Connect it at: [Connect ${ctx.label}](${connectUrl})`);\n printCallbackActionUrlExample(connectUrl, ctx.agentId);\n } else if (!ctx.agentId) {\n const connectUrl = connectorActionUrl({\n origin: ctx.platformOrigin,\n path: `/connectors/${ctx.connectorSlug}/connect`,\n });\n console.log(`Connect it at: [Connect ${ctx.label}](${connectUrl})`);\n }\n } else if (isExpired) {\n const url = connectorActionUrl({\n origin: ctx.platformOrigin,\n path: `/connectors/${ctx.connectorSlug}/connect`,\n agentId: ctx.agentId,\n });\n console.log(\n `The ${ctx.label} connector is connected but has expired and needs to be reconnected.`,\n );\n console.log(`Reconnect it at: [Reconnect ${ctx.label}](${url})`);\n printCallbackActionUrlExample(url, ctx.agentId);\n } else {\n console.log(`The ${ctx.label} connector is connected and active.`);\n }\n console.log(\"\");\n}\n\nfunction printAgentAuthorizationStatus(\n ctx: DiagContext,\n isConnected: boolean,\n isExpired: boolean,\n hasPermission: boolean,\n): void {\n if (!ctx.agentId) {\n console.log(\"ZERO_AGENT_ID is not set — cannot check agent authorization.\");\n } else if (isExpired) {\n console.log(\n `Skipped — agent authorization can only be checked once the ${ctx.label} connector is reconnected (see 2a).`,\n );\n } else if (hasPermission) {\n console.log(\n isConnected\n ? `The ${ctx.label} connector is authorized for this agent.`\n : `The ${ctx.label} connector is authorized for this agent, but it is not connected.`,\n );\n } else {\n const url = connectorActionUrl({\n origin: ctx.platformOrigin,\n path: `/connectors/${ctx.connectorSlug}/authorize`,\n agentId: ctx.agentId,\n });\n console.log(\n isConnected\n ? `The ${ctx.label} connector is not authorized for this agent (${ctx.agentId}).`\n : `The ${ctx.label} connector needs to be connected and authorized for this agent (${ctx.agentId}).`,\n );\n console.log(`Authorize it at: [Authorize ${ctx.label}](${url})`);\n printCallbackActionUrlExample(url, ctx.agentId);\n }\n}\n\nfunction printConnectorAuthorizationStatus(\n ctx: DiagContext,\n isConnected: boolean,\n isExpired: boolean,\n hasPermission: boolean,\n): void {\n console.log(\n \"### 2b: Agent authorization (user must authorize agent to use this connector)\",\n );\n console.log(\"\");\n if (!ctx.connectorAvailable) {\n console.log(\n `Skipped — the ${ctx.label} connector is not available for this account.`,\n );\n } else {\n printAgentAuthorizationStatus(ctx, isConnected, isExpired, hasPermission);\n }\n console.log(\n `This run uses agent-scoped connector authorization for ${ctx.label} access.`,\n );\n console.log(\"\");\n}\n\nfunction checkEnvironmentNames(ctx: DiagContext): void {\n console.log(\"## Step 1: Sandbox environment name\");\n console.log(\"\");\n if (ctx.environmentNames === null) {\n console.log(\n \"Environment metadata is unavailable for this run's sanitized firewall entry, so no environment name was guessed.\",\n );\n console.log(\"\");\n return;\n }\n if (ctx.environmentNames.length === 0) {\n console.log(\n \"The matched API route does not use a sandbox environment name.\",\n );\n console.log(\"\");\n return;\n }\n\n let environmentPresent = false;\n for (const environmentName of ctx.environmentNames) {\n const present = Boolean(process.env[environmentName]);\n environmentPresent ||= present;\n console.log(\n `Checking process.env.${environmentName}: ${present ? \"present\" : \"not present\"}`,\n );\n }\n if (environmentPresent) {\n console.log(\n \"At least one connector value is present in the sandbox environment. These values may be non-secret connector settings or credential placeholders; real credentials are never injected and are resolved at the network boundary for registered base URLs.\",\n );\n } else {\n console.log(\n \"No value found for these environment names. Note: credential replacement at the network boundary is independent of these names — the proxy injects auth headers based on the destination URL.\",\n );\n }\n console.log(\"\");\n}\n\nasync function checkConnectorStatus(ctx: DiagContext): Promise<{\n readonly isConnected: boolean;\n readonly isExpired: boolean;\n readonly hasPermission: boolean;\n}> {\n console.log(\"## Step 2: Connector configuration\");\n console.log(\"\");\n console.log(\n \"A Connector holds the real credentials (OAuth tokens or API keys) for an external service. These credentials are never injected into the sandbox. Instead, when the sandbox sends an HTTP request to a base URL registered by the Connector, the network boundary intercepts the request and replaces the auth headers with real credentials. For this to work, three conditions must be met:\",\n );\n console.log(\"\");\n\n const [connector, enabledConnectorSlugs] = await Promise.all([\n getZeroConnector(ctx.connectorSlug),\n ctx.agentId\n ? getZeroAgentUserConnectors(ctx.agentId)\n : Promise.resolve(null),\n ]);\n\n const isConnected = connector !== null;\n const isExpired = connector?.connectionStatus === \"reconnect-required\";\n const hasPermission =\n enabledConnectorSlugs !== null &&\n enabledConnectorSlugs.includes(ctx.connectorSlug);\n\n printConnectorConnectionStatus(ctx, isConnected, isExpired, hasPermission);\n printConnectorAuthorizationStatus(ctx, isConnected, isExpired, hasPermission);\n\n return { isConnected, isExpired, hasPermission };\n}\n\nfunction checkConnectorDomains(ctx: DiagContext): boolean | null {\n console.log(\n \"### 2c: Registered base URLs (credential replacement only applies to URLs matching these prefixes)\",\n );\n console.log(\"\");\n\n switch (ctx.run.status) {\n case \"not-scoped\":\n console.log(\n \"This diagnostic is not scoped to a run — skipping the run base URL check.\",\n );\n console.log(\"\");\n return null;\n case \"not-configured\":\n console.log(\n `No configuration found for the ${ctx.label} connector in this run.`,\n );\n console.log(\n \"This means no base URLs are registered for credential replacement for this connector.\",\n );\n console.log(\"\");\n return false;\n case \"configured\":\n console.log(\n `The ${ctx.label} connector is configured for this run with the following base URLs:`,\n );\n for (const base of ctx.run.bases) {\n console.log(` - ${base}`);\n }\n console.log(\"\");\n if (ctx.credentialResolution === \"network-boundary\") {\n console.log(\n \"Credentials are resolved at the network boundary for requests matching these registered base URLs.\",\n );\n }\n console.log(\"\");\n return true;\n }\n}\n\nfunction printUnavailablePolicy(\n policy: Extract<\n ConnectorCheckPolicy,\n {\n readonly outcome: \"unavailable\";\n }\n >,\n): void {\n switch (policy.basis) {\n case \"not-run-scoped\":\n console.log(\n \"Result: Permission policy is unavailable because this diagnostic is not scoped to a run.\",\n );\n return;\n case \"policies-unavailable\":\n console.log(\n \"Result: Network policies are unavailable for this run, so the permission status cannot be determined.\",\n );\n return;\n case \"connector-not-configured\":\n console.log(\n \"Result: The connector is not configured for this run, so requests cannot receive credentials.\",\n );\n return;\n }\n}\n\nfunction printNamedPolicyResult(\n connectorSlug: string,\n permission: string,\n policy: ConnectorCheckPolicy,\n agentId: string | undefined,\n request: UrlDiagnosticRequest | undefined,\n): void {\n switch (policy.outcome) {\n case \"allow\": {\n switch (policy.basis) {\n case \"allow-list\":\n console.log(\n `Result: \"${permission}\" is in the allow list — allowed.`,\n );\n return;\n case \"not-blocked\":\n console.log(\n `Result: \"${permission}\" is not blocked by the deny or ask list — allowed.`,\n );\n return;\n case \"no-policy\":\n console.log(\n `Result: No policy entry exists for this connector — \"${permission}\" is allowed.`,\n );\n return;\n case \"unknown-policy\":\n console.log(\n `Result: The server policy allows \"${permission}\" through the unknown-endpoint policy.`,\n );\n return;\n }\n break;\n }\n case \"deny\":\n console.log(\n policy.basis === \"deny-list\"\n ? `Result: \"${permission}\" is in the deny list — denied.`\n : `Result: The unknown-endpoint policy denies \"${permission}\".`,\n );\n printPermissionRequestCommands(\n connectorSlug,\n permission,\n agentId,\n \"To request this permission, run\",\n request,\n );\n return;\n case \"ask\":\n console.log(\n policy.basis === \"ask-list\"\n ? `Result: \"${permission}\" is in the ask list — blocked until approval.`\n : `Result: The unknown-endpoint policy blocks \"${permission}\" until approval.`,\n );\n printPermissionRequestCommands(\n connectorSlug,\n permission,\n agentId,\n \"To request this permission, run\",\n request,\n );\n return;\n case \"unavailable\":\n printUnavailablePolicy(policy);\n return;\n }\n}\n\nfunction permissionRequestCommand(\n connectorSlug: string,\n permission: string,\n request: UrlDiagnosticRequest,\n): string {\n return `zero connector permission-request ${shellQuoteArg(connectorSlug)} --permission ${shellQuoteArg(permission)} --url ${shellQuoteArg(request.url)} --method ${shellQuoteArg(request.method)}`;\n}\n\nfunction printPermissionRequestCommands(\n connectorSlug: string,\n permission: string,\n agentId: string | undefined,\n introduction: string,\n request: UrlDiagnosticRequest | undefined,\n): void {\n if (request === undefined) {\n console.log(\n \"Diagnose the failed request with zero connector check --url <FAILED_URL> --method <METHOD> before requesting this permission.\",\n );\n return;\n }\n const command = permissionRequestCommand(connectorSlug, permission, request);\n console.log(`${introduction}: ${command}`);\n if (!currentChatSupportsActionCallback(agentId)) {\n return;\n }\n\n console.log(\"\");\n console.log(\n \"Or, if this is the only connector or permission action needed, run the callback command below. After the user completes this action, Zero will automatically start the next round with the callback prompt:\",\n );\n console.log(`${command} --callback-prompt \"${CALLBACK_PROMPT_PLACEHOLDER}\"`);\n}\n\nfunction printUnknownEndpointPolicy(\n connectorSlug: string,\n policy: ConnectorCheckPolicy,\n agentId: string | undefined,\n request: UrlDiagnosticRequest,\n): void {\n switch (policy.outcome) {\n case \"allow\":\n console.log(\n policy.basis === \"no-policy\"\n ? \"Result: No policy entry exists for this connector, so the request is allowed.\"\n : \"Result: No permission matched. The unknown endpoint policy allows this request.\",\n );\n return;\n case \"deny\":\n console.log(\n \"Result: No permission matched. The unknown endpoint policy denies this request.\",\n );\n printPermissionRequestCommands(\n connectorSlug,\n \"__unknown__\",\n agentId,\n \"To request access to unknown endpoints, run\",\n request,\n );\n return;\n case \"ask\":\n console.log(\n \"Result: No permission matched. The unknown endpoint policy requires approval.\",\n );\n printPermissionRequestCommands(\n connectorSlug,\n \"__unknown__\",\n agentId,\n \"To request access to unknown endpoints, run\",\n request,\n );\n return;\n case \"unavailable\":\n printUnavailablePolicy(policy);\n return;\n }\n}\n\nfunction printUrlPermissionDiagnostic(\n request: UrlDiagnosticRequest,\n result: ResolvedUrlDiagnostic,\n agentId: string | undefined,\n): void {\n console.log(\"## Step 3: Permission policy check (auto-detected from URL)\");\n console.log(\"\");\n console.log(\n `Matching ${result.method} ${result.relativePath} (relative to base URL ${result.base}) against the ${result.connector.label} connector's permission rules.`,\n );\n console.log(\"\");\n\n if (result.permission.kind === \"matched\") {\n console.log(\n `Matched permissions: [${result.permission.permissions\n .map((permission) => {\n return permission.name;\n })\n .join(\", \")}]`,\n );\n console.log(\"\");\n for (const permission of result.permission.permissions) {\n printNamedPolicyResult(\n result.connector.connectorSlug,\n permission.name,\n permission.policy,\n agentId,\n request,\n );\n }\n } else {\n console.log(\n `No named permission matches ${result.method} ${result.relativePath}. This request falls through to the unknown-endpoint policy.`,\n );\n console.log(\"\");\n printUnknownEndpointPolicy(\n result.connector.connectorSlug,\n result.permission.policy,\n agentId,\n request,\n );\n }\n console.log(\"\");\n}\n\nfunction printEnvironmentPermissionDiagnostic(\n result: ResolvedEnvironmentDiagnostic,\n permissionName: string | undefined,\n agentId: string | undefined,\n): void {\n if (result.permission === null) {\n return;\n }\n if (permissionName === undefined) {\n throw new Error(\n \"Connector diagnostic returned a permission outcome without a requested permission.\",\n );\n }\n console.log(\"## Step 3: Permission policy check\");\n console.log(\"\");\n console.log(\n `Checking permission: \"${permissionName}\" for the ${result.connector.label} connector.`,\n );\n console.log(\"\");\n printNamedPolicyResult(\n result.connector.connectorSlug,\n permissionName,\n result.permission,\n agentId,\n undefined,\n );\n console.log(\"\");\n}\n\nfunction printRediagnoseHint(\n opts: CheckConnectorOptions,\n method: string,\n): void {\n const args: string[] = [];\n if (opts.url !== undefined) {\n args.push(`--url ${shellQuoteArg(stripUrlQueryAndFragment(opts.url))}`);\n if (opts.connector !== undefined) {\n args.push(`--connector ${shellQuoteArg(opts.connector)}`);\n }\n if (opts.envName !== undefined) {\n args.push(`--env-name ${shellQuoteArg(opts.envName)}`);\n }\n if (method !== \"GET\") {\n args.push(`--method ${shellQuoteArg(method)}`);\n }\n } else if (opts.envName !== undefined) {\n args.push(`--env-name ${shellQuoteArg(opts.envName)}`);\n }\n if (opts.checkPermission !== undefined) {\n args.push(`--check-permission ${shellQuoteArg(opts.checkPermission)}`);\n }\n console.log(\n `To re-diagnose after changes, run: zero connector check ${args.join(\" \")}`,\n );\n}\n\nexport const checkConnectorCommand = new Command()\n .name(\"check\")\n .description(\n \"Diagnose connector health: environment names, connector configuration, and permission policies\",\n )\n .addOption(\n new Option(\n \"--env-name <ENV_NAME>\",\n \"The connector environment name to check (e.g. GITHUB_TOKEN)\",\n ),\n )\n .addOption(\n new Option(\n \"--url <URL>\",\n \"A full URL to diagnose — matches connector ownership, route environment names, and permission (e.g. https://api.github.com/repos/owner/repo)\",\n ),\n )\n .addOption(\n new Option(\n \"--connector <slug>\",\n \"Select the connector when multiple connectors own the same URL route\",\n ),\n )\n .addOption(\n new Option(\n \"--method <METHOD>\",\n \"HTTP method to use when matching permissions with --url\",\n ).default(\"GET\"),\n )\n .addOption(\n new Option(\n \"--check-permission <name>\",\n \"Check whether a specific permission is allowed or denied (e.g. contents:read)\",\n ),\n )\n .addHelpText(\n \"after\",\n `\nExamples:\n zero connector check --env-name GITHUB_TOKEN\n zero connector check --url https://api.github.com/repos/owner/repo\n zero connector check --url https://api.accounts.nintendo.com/2.0.0/users/me --connector nintendo-store\n zero connector check --url https://slack.com/api/chat.postMessage --method POST\n zero connector check --env-name SLACK_TOKEN --check-permission chat:write\n\nHow connectors work:\n A Connector holds the real credentials for an external service. These credentials\n are never injected into the sandbox. Instead, when the sandbox sends an HTTP\n request to a base URL registered by the Connector, the network boundary intercepts\n the request and replaces the auth headers with real credentials.\n\n This command checks each part of that pipeline and reports what it finds.`,\n )\n .action(\n withErrorHandler(async (opts: CheckConnectorOptions, command: Command) => {\n validateCheckConnectorOptions(opts, command);\n if (isComputerUseCheckTarget(opts)) {\n printComputerUsePermissionGuidance();\n return;\n }\n const method = opts.method.toUpperCase();\n const request = buildDiagnosticRequest(opts, method);\n const diagnostic = await diagnoseZeroConnectorCheck(request);\n const result = resolveConnectorCheckDiagnostic(request, diagnostic);\n\n printDiagnosticSummary(request, result);\n console.log(\"\");\n\n const platformUrl = toPlatformUrl(await getApiUrl());\n const ctx: DiagContext = {\n environmentNames: diagnosticEnvironmentNames(result),\n connectorSlug: result.connector.connectorSlug,\n label: result.connector.label,\n connectorAvailable: result.connector.visibility === \"available\",\n credentialResolution: result.connector.credentialResolution,\n run: result.run,\n platformOrigin: platformUrl.origin,\n agentId: process.env.ZERO_AGENT_ID || undefined,\n };\n\n checkEnvironmentNames(ctx);\n const { isConnected, isExpired, hasPermission } =\n await checkConnectorStatus(ctx);\n const configuredForRun = checkConnectorDomains(ctx);\n\n if (configuredForRun === false) {\n console.log(\n `Steps 1-2 summary: The ${ctx.label} connector is not configured for this run. Check the agent authorization settings, then start a new run after updating them.`,\n );\n } else if (isConnected && !isExpired && hasPermission) {\n console.log(\n `Steps 1-2 summary: The ${ctx.label} connector is connected, active, and authorized. Outbound requests to the registered base URLs will have credentials injected at the network boundary.`,\n );\n }\n console.log(\"\");\n\n if (result.mode === \"url\") {\n printUrlPermissionDiagnostic(\n requireUrlRequest(request),\n result,\n ctx.agentId,\n );\n } else {\n printEnvironmentPermissionDiagnostic(\n result,\n request.mode === \"environment\" ? request.permission : undefined,\n ctx.agentId,\n );\n }\n\n printRediagnoseHint(opts, method);\n }),\n );\n","const COMPUTER_USE_CONNECTOR_SLUG = \"computer-use\";\nconst COMPUTER_USE_CAPABILITY = \"computer-use:write\";\nconst COMPUTER_USE_PATH_PREFIX = \"/computer-use\";\nconst COMPUTER_USE_PATH_PREFIX_WITH_SLASH = `${COMPUTER_USE_PATH_PREFIX}/`;\n\ninterface ComputerUsePermissionTarget {\n readonly connectorSlug: string;\n readonly path?: string;\n readonly permission?: string;\n}\n\nexport function isComputerUsePermissionTarget(\n target: ComputerUsePermissionTarget,\n): boolean {\n return (\n target.connectorSlug === COMPUTER_USE_CONNECTOR_SLUG ||\n target.permission === COMPUTER_USE_CAPABILITY ||\n target.path === COMPUTER_USE_PATH_PREFIX ||\n target.path?.startsWith(COMPUTER_USE_PATH_PREFIX_WITH_SLASH) === true\n );\n}\n\nexport function printComputerUsePermissionGuidance(): void {\n console.log(\"Computer Use access is not managed as a connector permission.\");\n console.log(\n \"The current run token needs computer-use:write, which is issued only when a Zero Desktop Computer Use host is selected for the chat or thread before the run starts.\",\n );\n console.log(\n \"Open Zero Desktop, make sure Computer Use is online, select the Computer Use host for this chat/thread, then start a new run. Existing run tokens cannot be upgraded in place.\",\n );\n console.log(\n \"Run `zero whoami` to confirm whether the current ZERO_TOKEN includes computer-use:write.\",\n );\n}\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport {\n connectZeroConnectorManualGrant,\n listZeroConnectorCatalogStatus,\n} from \"../../../lib/api\";\nimport { withErrorHandler } from \"../../../lib/command\";\nimport {\n availableConnectorSlugs,\n findConnectorStatusItem,\n resolveManualGrantAuthMethod,\n} from \"./public-catalog\";\n\ninterface ConnectOptions {\n readonly authMethod?: string;\n readonly value?: readonly string[];\n readonly json?: boolean;\n}\n\nfunction collectValue(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nfunction parseConnectorValues(rawValues: readonly string[] | undefined) {\n if (!rawValues || rawValues.length === 0) {\n throw new Error(\"At least one --value NAME=VALUE is required\", {\n cause: new Error(\n \"Example: zero connector connect zendesk --value apiToken=token\",\n ),\n });\n }\n\n const values: Record<string, string> = {};\n for (const rawValue of rawValues) {\n const separatorIndex = rawValue.indexOf(\"=\");\n if (separatorIndex <= 0) {\n throw new Error(\"Invalid --value format\", {\n cause: new Error(\"Use --value NAME=VALUE\"),\n });\n }\n\n const name = rawValue.slice(0, separatorIndex);\n if (!name.trim()) {\n throw new Error(\"Invalid --value format\", {\n cause: new Error(\"Field name cannot be empty\"),\n });\n }\n\n values[name] = rawValue.slice(separatorIndex + 1);\n }\n\n return values;\n}\n\nexport const connectCommand = new Command()\n .name(\"connect\")\n .description(\"Connect a connector with manual grant values\")\n .argument(\"<slug>\", \"Connector slug (e.g., zendesk)\")\n .option(\"--auth-method <method>\", \"Connector auth method to use\")\n .option(\n \"--value <name=value>\",\n \"Connector field value; repeat for multiple fields\",\n collectValue,\n [],\n )\n .option(\"--json\", \"Print the connector response as JSON\")\n .action(\n withErrorHandler(async (connectorSlug: string, options: ConnectOptions) => {\n const values = parseConnectorValues(options.value);\n const catalog = await listZeroConnectorCatalogStatus();\n const connectorMetadata = findConnectorStatusItem(\n catalog.connectors,\n connectorSlug,\n );\n if (!connectorMetadata) {\n throw new Error(`Unknown or unavailable connector: ${connectorSlug}`, {\n cause: new Error(\n `Available connectors: ${availableConnectorSlugs(catalog.connectors)}`,\n ),\n });\n }\n\n const authMethod = resolveManualGrantAuthMethod(\n connectorMetadata,\n options.authMethod,\n );\n const connector = await connectZeroConnectorManualGrant(\n connectorMetadata.slug,\n authMethod.id,\n values,\n );\n\n if (options.json) {\n console.log(JSON.stringify(connector, null, 2));\n return;\n }\n\n console.log(chalk.green(`✓ ${connectorMetadata.label} connected`));\n console.log(chalk.dim(` Slug: ${connector.slug}`));\n console.log(chalk.dim(` Auth Method: ${connector.authMethod}`));\n console.log(chalk.dim(` Run: zero connector status ${connector.slug}`));\n }),\n );\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport {\n listZeroConnectorCatalogStatus,\n listZeroCustomConnectors,\n} from \"../../../lib/api\";\nimport { withErrorHandler } from \"../../../lib/command\";\nimport { resolveConnectorDiscoveryAgentContext } from \"./agent-context\";\nimport { padEndAnsi, stripAnsi } from \"./connected-as\";\nimport {\n connectorDiscoveryItems,\n isConnectorDiscoveryAuthorized,\n renderConnectorDiscoveryConnectedAsCell,\n} from \"./discovery\";\n\nexport const listCommand = new Command()\n .name(\"list\")\n .alias(\"ls\")\n .description(\"List all connectors and their status\")\n .option(\"--agent <id>\", \"Show per-agent authorization column\")\n .action(\n withErrorHandler(async (options: { agent?: string }) => {\n const [{ connectors }, customConnectors, agentCtx] = await Promise.all([\n listZeroConnectorCatalogStatus(),\n listZeroCustomConnectors(),\n resolveConnectorDiscoveryAgentContext(options.agent),\n ]);\n const discoveredConnectors = connectorDiscoveryItems(\n connectors,\n customConnectors,\n );\n\n const connectorSlugs = discoveredConnectors.map((connector) => {\n return connector.slug;\n });\n\n const connectorSlugWidth = Math.max(\n 4,\n ...connectorSlugs.map((connectorSlug) => {\n return connectorSlug.length;\n }),\n );\n\n const connectedAsHeader = \"CONNECTED AS\";\n const connectedCells = discoveredConnectors.map((connector) => {\n return renderConnectorDiscoveryConnectedAsCell(connector);\n });\n const connectedAsWidth = Math.max(\n connectedAsHeader.length,\n ...connectedCells.map((c) => {\n return stripAnsi(c).length;\n }),\n );\n\n const authorizedHeader = agentCtx\n ? `AUTHORIZED FOR ${agentCtx.displayName}`\n : null;\n\n // Print header\n const headerParts = [\n \"SLUG\".padEnd(connectorSlugWidth),\n connectedAsHeader.padEnd(connectedAsWidth),\n ];\n if (authorizedHeader) headerParts.push(authorizedHeader);\n console.log(chalk.dim(headerParts.join(\" \")));\n\n // Print rows\n for (let i = 0; i < connectorSlugs.length; i++) {\n const connector = discoveredConnectors[i]!;\n const connectorSlug = connectorSlugs[i]!;\n const connectedCell = padEndAnsi(connectedCells[i]!, connectedAsWidth);\n const parts = [connectorSlug.padEnd(connectorSlugWidth), connectedCell];\n if (agentCtx) {\n parts.push(\n isConnectorDiscoveryAuthorized(connector, agentCtx)\n ? chalk.green(\"✓\")\n : chalk.dim(\"-\"),\n );\n }\n console.log(parts.join(\" \"));\n }\n }),\n );\n","import chalk from \"chalk\";\nimport type { PublicConnectorStatus } from \"./public-catalog\";\n\nfunction renderIdentity(connector: PublicConnectorStatus): string {\n if (connector.connection?.externalUsername) {\n return `@${connector.connection.externalUsername}`;\n }\n if (connector.connection?.externalEmail)\n return connector.connection.externalEmail;\n return \"-\";\n}\n\nexport function renderConnectedAsCell(\n connector: PublicConnectorStatus | undefined,\n): string {\n if (!connector || connector.connectionStatus === \"not-connected\") {\n return chalk.dim(\"(not connected)\");\n }\n const identity = renderIdentity(connector);\n if (connector.connectionStatus === \"reconnect-required\") {\n return chalk.yellow(`${identity} (reconnect needed)`);\n }\n if (\n connector.scopeMismatch ||\n connector.connectionStatus === \"scope-mismatch\"\n ) {\n return chalk.yellow(`${identity} (permissions update available)`);\n }\n return identity;\n}\n\nconst ESC = \"\\u001b\";\nconst ANSI_PATTERN = new RegExp(`${ESC}\\\\[[0-9;]*m`, \"g\");\n\nexport function stripAnsi(s: string): string {\n return s.replace(ANSI_PATTERN, \"\");\n}\n\nexport function padEndAnsi(s: string, width: number): string {\n const visible = stripAnsi(s).length;\n return s + \" \".repeat(Math.max(0, width - visible));\n}\n","import chalk from \"chalk\";\nimport type { CustomConnectorResponse } from \"@vm0/api-contracts/contracts/zero-custom-connectors\";\nimport type { ZeroConnectorCatalogStatus } from \"../../../lib/api/domains/zero-connectors\";\nimport type { ConnectorDiscoveryAgentContext } from \"./agent-context\";\nimport { renderConnectedAsCell } from \"./connected-as\";\n\ninterface CatalogConnectorDiscoveryItem {\n readonly kind: \"catalog\";\n readonly slug: string;\n readonly label: string;\n readonly description: string;\n readonly category: string;\n readonly tags: readonly string[];\n readonly generation: readonly string[];\n readonly authMethods: ZeroConnectorCatalogStatus[\"authMethods\"];\n readonly catalogConnector: ZeroConnectorCatalogStatus;\n}\n\ninterface CustomConnectorDiscoveryItem {\n readonly kind: \"custom\";\n readonly slug: string;\n readonly label: string;\n readonly description: string;\n readonly category: string;\n readonly tags: readonly string[];\n readonly generation: readonly string[];\n readonly authMethods: readonly [];\n readonly customConnector: CustomConnectorResponse;\n}\n\ntype ConnectorDiscoveryItem =\n | CatalogConnectorDiscoveryItem\n | CustomConnectorDiscoveryItem;\n\nexport function connectorDiscoveryItems(\n catalogConnectors: readonly ZeroConnectorCatalogStatus[],\n customConnectors: readonly CustomConnectorResponse[],\n): readonly ConnectorDiscoveryItem[] {\n return [\n ...catalogConnectors.map((connector): CatalogConnectorDiscoveryItem => {\n return {\n kind: \"catalog\",\n slug: connector.slug,\n label: connector.label,\n description: connector.description,\n category: connector.category,\n tags: connector.tags,\n generation: connector.generation,\n authMethods: connector.authMethods,\n catalogConnector: connector,\n };\n }),\n ...customConnectors.map((connector): CustomConnectorDiscoveryItem => {\n return {\n kind: \"custom\",\n slug: connector.slug,\n label: connector.displayName,\n description: \"\",\n category: \"custom\",\n tags: [],\n generation: [],\n authMethods: [],\n customConnector: connector,\n };\n }),\n ];\n}\n\nexport function renderConnectorDiscoveryConnectedAsCell(\n connector: ConnectorDiscoveryItem,\n): string {\n if (connector.kind === \"catalog\") {\n return renderConnectedAsCell(connector.catalogConnector);\n }\n if (connector.customConnector.connected) {\n return chalk.green(\"connected\");\n }\n if (connector.customConnector.missingRequiredFields.length === 0) {\n return chalk.dim(\"(not connected)\");\n }\n return chalk.yellow(\n `missing ${connector.customConnector.missingRequiredFields.join(\", \")}`,\n );\n}\n\nexport function isConnectorDiscoveryAuthorized(\n connector: ConnectorDiscoveryItem,\n agentContext: ConnectorDiscoveryAgentContext,\n): boolean {\n if (connector.kind === \"catalog\") {\n return agentContext.authorizedConnectorSlugs.has(connector.slug);\n }\n return agentContext.authorizedCustomConnectorIds.has(\n connector.customConnector.id,\n );\n}\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport {\n listZeroConnectorCatalogStatus,\n listZeroCustomConnectors,\n} from \"../../../lib/api\";\nimport { withErrorHandler } from \"../../../lib/command\";\nimport { resolveConnectorDiscoveryAgentContext } from \"./agent-context\";\nimport { padEndAnsi, stripAnsi } from \"./connected-as\";\nimport {\n connectorDiscoveryItems,\n isConnectorDiscoveryAuthorized,\n renderConnectorDiscoveryConnectedAsCell,\n} from \"./discovery\";\nimport { searchConnectorCatalog } from \"./public-catalog\";\n\nconst DEFAULT_LIMIT = 5;\nconst EXACT_MATCH_THRESHOLD = 80;\n\nfunction parseLimit(raw: string): number {\n const trimmed = raw.trim();\n const n = Number(trimmed);\n if (!/^\\d+$/.test(trimmed) || !Number.isSafeInteger(n) || n <= 0) {\n throw new Error(`--limit must be a positive integer, got \"${raw}\".`);\n }\n return n;\n}\n\nexport const searchCommand = new Command()\n .name(\"search\")\n .description(\n \"Search connectors by slug, label, category, generation type, or tag\",\n )\n .argument(\"<keyword>\", \"Search keyword (case-insensitive)\")\n .option(\"--agent <id>\", \"Show per-agent authorization column\")\n .option(\n \"--limit <n>\",\n `Maximum number of results to display (default ${DEFAULT_LIMIT})`,\n parseLimit,\n DEFAULT_LIMIT,\n )\n .action(\n withErrorHandler(\n async (keyword: string, options: { agent?: string; limit: number }) => {\n const trimmed = keyword.trim();\n if (!trimmed) {\n throw new Error(\"Keyword cannot be empty.\");\n }\n\n const [{ connectors }, customConnectors, agentCtx] = await Promise.all([\n listZeroConnectorCatalogStatus(),\n listZeroCustomConnectors(),\n resolveConnectorDiscoveryAgentContext(options.agent),\n ]);\n const { results, total } = searchConnectorCatalog(\n connectorDiscoveryItems(connectors, customConnectors),\n trimmed,\n options.limit,\n );\n\n if (results.length === 0) {\n console.log(\"No matches found.\");\n return;\n }\n\n const topScore = results[0]!.score;\n if (topScore < EXACT_MATCH_THRESHOLD) {\n console.log(\"No exact match. Showing closest:\");\n }\n if (total > options.limit) {\n console.log(`Too many results (top ${options.limit} of ${total}):`);\n }\n\n const connectorSlugHeader = \"SLUG\";\n const connectedAsHeader = \"CONNECTED AS\";\n\n const connectedCells = results.map((r) => {\n return renderConnectorDiscoveryConnectedAsCell(r.connector);\n });\n\n const connectorSlugWidth = Math.max(\n connectorSlugHeader.length,\n ...results.map((r) => {\n return r.connector.slug.length;\n }),\n );\n const connectedAsWidth = Math.max(\n connectedAsHeader.length,\n ...connectedCells.map((c) => {\n return stripAnsi(c).length;\n }),\n );\n\n const headerParts = [\n connectorSlugHeader.padEnd(connectorSlugWidth),\n connectedAsHeader.padEnd(connectedAsWidth),\n ];\n if (agentCtx) {\n headerParts.push(`AUTHORIZED FOR ${agentCtx.displayName}`);\n }\n console.log(chalk.dim(headerParts.join(\" \")));\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i]!;\n const parts = [\n result.connector.slug.padEnd(connectorSlugWidth),\n padEndAnsi(connectedCells[i]!, connectedAsWidth),\n ];\n if (agentCtx) {\n parts.push(\n isConnectorDiscoveryAuthorized(result.connector, agentCtx)\n ? chalk.green(\"✓\")\n : chalk.dim(\"-\"),\n );\n }\n console.log(parts.join(\" \"));\n }\n },\n ),\n );\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { listZeroConnectorCatalogStatus } from \"../../../lib/api\";\nimport { withErrorHandler } from \"../../../lib/command\";\nimport { resolveAgentContext } from \"./agent-context\";\nimport { getPlatformOrigin } from \"../doctor/platform-url\";\nimport {\n availableConnectorSlugs,\n findConnectorStatusItem,\n type PublicConnectorStatus,\n} from \"./public-catalog\";\nimport {\n connectorActionUrl,\n printCallbackActionUrlExample,\n} from \"./action-url\";\n\nconst LABEL_WIDTH = 16;\n\ntype AgentContext = NonNullable<\n Awaited<ReturnType<typeof resolveAgentContext>>\n>;\n\nfunction printConnectorDetails(connector: PublicConnectorStatus): void {\n if (connector.connectionStatus === \"not-connected\") {\n console.log(\n `${\"Status:\".padEnd(LABEL_WIDTH)}${chalk.dim(\"not connected\")}`,\n );\n return;\n }\n\n console.log(\n `${\"Status:\".padEnd(LABEL_WIDTH)}${\n connector.connectionStatus === \"reconnect-required\"\n ? chalk.yellow(\"reconnect needed\")\n : chalk.green(\"connected\")\n }`,\n );\n if (connector.connection?.externalUsername) {\n console.log(\n `${\"Account:\".padEnd(LABEL_WIDTH)}@${connector.connection.externalUsername}`,\n );\n } else if (connector.connection?.externalEmail) {\n console.log(\n `${\"Account:\".padEnd(LABEL_WIDTH)}${connector.connection.externalEmail}`,\n );\n }\n if (connector.connection?.authMethod) {\n console.log(\n `${\"Auth Method:\".padEnd(LABEL_WIDTH)}${connector.connection.authMethod}`,\n );\n }\n if (connector.scopeMismatch) {\n console.log(\n `${\"Permissions:\".padEnd(LABEL_WIDTH)}${chalk.yellow(\"update available\")}`,\n );\n }\n if (connector.tokenExpiresAt) {\n console.log(\n `${\"Token Expires:\".padEnd(LABEL_WIDTH)}${connector.tokenExpiresAt}`,\n );\n }\n}\n\nasync function printAgentAction(\n connector: PublicConnectorStatus,\n agentCtx: AgentContext,\n): Promise<void> {\n const connectorSlug = connector.slug;\n const authorized = agentCtx.authorizedConnectorSlugs.has(connectorSlug);\n const isConnected = connector.connected;\n const needsReconnect = connector.connectionStatus === \"reconnect-required\";\n const agentLabel =\n agentCtx.displayName === agentCtx.agentId\n ? agentCtx.agentId\n : `${agentCtx.displayName} (${agentCtx.agentId})`;\n\n console.log();\n if (needsReconnect) {\n const origin = await getPlatformOrigin();\n const url = connectorActionUrl({\n origin,\n path: `/connectors/${connectorSlug}/connect`,\n agentId: agentCtx.agentId,\n });\n console.log(\n `The ${connectorSlug} connector is connected but needs to be reconnected before agent ${agentLabel} can use it.`,\n );\n console.log(`Reconnect it at: [Reconnect ${connectorSlug}](${url})`);\n printCallbackActionUrlExample(url, agentCtx.agentId);\n } else if (authorized && !isConnected) {\n const origin = await getPlatformOrigin();\n const url = connectorActionUrl({\n origin,\n path: `/connectors/${connectorSlug}/connect`,\n agentId: agentCtx.agentId,\n });\n console.log(\n `The ${connectorSlug} connector is authorized for agent ${agentLabel}, but it is not connected.`,\n );\n console.log(`Connect it at: [Connect ${connectorSlug}](${url})`);\n printCallbackActionUrlExample(url, agentCtx.agentId);\n } else if (authorized) {\n console.log(\n `The ${connectorSlug} connector is authorized for agent ${agentLabel}.`,\n );\n } else if (!isConnected) {\n const origin = await getPlatformOrigin();\n const url = connectorActionUrl({\n origin,\n path: `/connectors/${connectorSlug}/connect`,\n agentId: agentCtx.agentId,\n });\n console.log(\n `The ${connectorSlug} connector is not connected. Once connected, it will be authorized for agent ${agentLabel}.`,\n );\n console.log(\n `Connect and authorize it at: [Connect ${connectorSlug}](${url})`,\n );\n printCallbackActionUrlExample(url, agentCtx.agentId);\n } else {\n const origin = await getPlatformOrigin();\n const url = connectorActionUrl({\n origin,\n path: `/connectors/${connectorSlug}/authorize`,\n agentId: agentCtx.agentId,\n });\n console.log(\n `The ${connectorSlug} connector is not authorized for agent ${agentLabel}.`,\n );\n console.log(`Authorize it at: [Authorize ${connectorSlug}](${url})`);\n printCallbackActionUrlExample(url, agentCtx.agentId);\n }\n}\n\nasync function printStandaloneAction(\n connector: PublicConnectorStatus,\n): Promise<void> {\n const connectorSlug = connector.slug;\n if (\n connector.connectionStatus === \"connected\" ||\n connector.connectionStatus === \"scope-mismatch\"\n ) {\n return;\n }\n\n const origin = await getPlatformOrigin();\n console.log();\n if (connector.connectionStatus === \"reconnect-required\") {\n const url = `${origin}/connectors`;\n console.log(\n `The ${connectorSlug} connector is connected but needs to be reconnected.`,\n );\n console.log(`Reconnect it at: [Reconnect ${connectorSlug}](${url})`);\n } else {\n const url = `${origin}/connectors/${connectorSlug}/connect`;\n console.log(`Connect it at: [Connect ${connectorSlug}](${url})`);\n }\n}\n\nexport const statusCommand = new Command()\n .name(\"status\")\n .description(\"Show detailed status of a connector\")\n .argument(\"<slug>\", \"Connector slug (e.g., github)\")\n .option(\"--agent <id>\", \"Show authorization state for the given agent\")\n .action(\n withErrorHandler(\n async (connectorSlug: string, options: { agent?: string }) => {\n const [catalog, agentCtx] = await Promise.all([\n listZeroConnectorCatalogStatus(),\n resolveAgentContext(options.agent),\n ]);\n const connector = findConnectorStatusItem(\n catalog.connectors,\n connectorSlug,\n );\n if (!connector) {\n throw new Error(\n `Unknown or unavailable connector: ${connectorSlug}`,\n {\n cause: new Error(\n `Available connectors: ${availableConnectorSlugs(catalog.connectors)}`,\n ),\n },\n );\n }\n\n console.log(`Connector: ${chalk.cyan(connector.slug)}`);\n console.log();\n\n printConnectorDetails(connector);\n\n if (agentCtx) {\n await printAgentAction(connector, agentCtx);\n } else {\n await printStandaloneAction(connector);\n }\n },\n ),\n );\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport {\n getZeroAgent,\n getZeroAgentCustomConnectors,\n getZeroCustomConnector,\n listZeroCustomConnectors,\n} from \"../../../../lib/api\";\nimport { withErrorHandler } from \"../../../../lib/command\";\nimport { createCustomConnectorCommand } from \"./create\";\n\nconst LABEL_WIDTH = 18;\n\nfunction renderConnected(connector: {\n readonly connected: boolean;\n readonly missingRequiredFields: readonly string[];\n}): string {\n if (connector.connected) {\n return chalk.green(\"connected\");\n }\n if (connector.missingRequiredFields.length === 0) {\n return chalk.dim(\"not connected\");\n }\n return chalk.yellow(`missing ${connector.missingRequiredFields.join(\", \")}`);\n}\n\nasync function resolveCustomAgentContext(agentId: string | undefined): Promise<{\n readonly agentId: string;\n readonly displayName: string;\n readonly authorizedIds: Set<string>;\n} | null> {\n const resolvedAgentId = agentId ?? process.env.ZERO_AGENT_ID;\n if (!resolvedAgentId) {\n return null;\n }\n const [agent, enabledIds] = await Promise.all([\n getZeroAgent(resolvedAgentId),\n getZeroAgentCustomConnectors(resolvedAgentId),\n ]);\n return {\n agentId: agent.agentId,\n displayName: agent.displayName ?? agent.agentId,\n authorizedIds: new Set(enabledIds),\n };\n}\n\nconst listCommand = new Command()\n .name(\"list\")\n .alias(\"ls\")\n .description(\"List org custom connectors\")\n .option(\"--agent <id>\", \"Show per-agent authorization column\")\n .action(\n withErrorHandler(async (options: { agent?: string }) => {\n const [connectors, agentCtx] = await Promise.all([\n listZeroCustomConnectors(),\n resolveCustomAgentContext(options.agent),\n ]);\n const idWidth = Math.max(\n 2,\n ...connectors.map((connector) => {\n return connector.id.length;\n }),\n );\n const nameWidth = Math.max(\n 4,\n ...connectors.map((connector) => {\n return connector.displayName.length;\n }),\n );\n const header = [\"ID\".padEnd(idWidth), \"NAME\".padEnd(nameWidth), \"STATUS\"];\n if (agentCtx) {\n header.push(`AUTHORIZED FOR ${agentCtx.displayName}`);\n }\n console.log(chalk.dim(header.join(\" \")));\n for (const connector of connectors) {\n const row = [\n connector.id.padEnd(idWidth),\n connector.displayName.padEnd(nameWidth),\n renderConnected(connector),\n ];\n if (agentCtx) {\n row.push(\n agentCtx.authorizedIds.has(connector.id)\n ? chalk.green(\"✓\")\n : chalk.dim(\"-\"),\n );\n }\n console.log(row.join(\" \"));\n }\n }),\n );\n\nconst statusCommand = new Command()\n .name(\"status\")\n .description(\"Show detailed status of a custom connector\")\n .argument(\"<connector-id>\", \"Custom connector id\")\n .option(\"--agent <id>\", \"Show authorization state for the given agent\")\n .action(\n withErrorHandler(\n async (connectorId: string, options: { agent?: string }) => {\n const [connector, agentCtx] = await Promise.all([\n getZeroCustomConnector(connectorId),\n resolveCustomAgentContext(options.agent),\n ]);\n if (!connector) {\n throw new Error(`Custom connector not found: ${connectorId}`);\n }\n console.log(`Custom connector: ${chalk.cyan(connector.displayName)}`);\n console.log();\n console.log(`${\"ID:\".padEnd(LABEL_WIDTH)}${connector.id}`);\n console.log(\n `${\"Status:\".padEnd(LABEL_WIDTH)}${renderConnected(connector)}`,\n );\n console.log(\n `${\"Prefixes:\".padEnd(LABEL_WIDTH)}${connector.prefixTemplates.join(\", \")}`,\n );\n console.log(\n `${\"Fields:\".padEnd(LABEL_WIDTH)}${connector.fields\n .map((field) => {\n return `${field.kind}:${field.key}${field.required ? \"\" : \"?\"}`;\n })\n .join(\", \")}`,\n );\n if (connector.headerInjections.length > 0) {\n console.log(\n `${\"Headers:\".padEnd(LABEL_WIDTH)}${connector.headerInjections\n .map((header) => {\n return header.name;\n })\n .join(\", \")}`,\n );\n }\n if (connector.queryInjections.length > 0) {\n console.log(\n `${\"Query params:\".padEnd(LABEL_WIDTH)}${connector.queryInjections\n .map((query) => {\n return query.name;\n })\n .join(\", \")}`,\n );\n }\n if (agentCtx) {\n console.log(\n `${\"Authorized:\".padEnd(LABEL_WIDTH)}${\n agentCtx.authorizedIds.has(connector.id)\n ? chalk.green(\"yes\")\n : chalk.yellow(\"no\")\n }`,\n );\n }\n },\n ),\n );\n\nexport const customConnectorCommand = new Command()\n .name(\"custom\")\n .description(\"Create and inspect org custom connectors\")\n .addCommand(createCustomConnectorCommand)\n .addCommand(listCommand)\n .addCommand(statusCommand);\n","import { readFile } from \"node:fs/promises\";\n\nimport {\n customConnectorAuthModeSchema,\n customConnectorOAuthConfigInputSchema,\n customConnectorValueInputSchema,\n updateCustomConnectorBodySchema,\n type CustomConnectorResponse,\n} from \"@vm0/api-contracts/contracts/zero-custom-connectors\";\nimport chalk from \"chalk\";\nimport { Command } from \"commander\";\n\nimport {\n addZeroAgentCustomConnector,\n createZeroCustomConnector,\n getZeroAgent,\n setZeroCustomConnectorValues,\n startZeroCustomConnectorOAuth2,\n} from \"../../../../lib/api\";\nimport { decodeZeroTokenPayload } from \"../../../../lib/api/zero-token\";\nimport { withErrorHandler } from \"../../../../lib/command\";\n\nconst customConnectorDefinitionSchema = updateCustomConnectorBodySchema.omit({\n authMode: true,\n oauthConfig: true,\n});\n\nconst manualCustomConnectorCreateSchema = customConnectorDefinitionSchema\n .extend({\n authMode: customConnectorAuthModeSchema.extract([\"manual\"]),\n values: customConnectorValueInputSchema.array(),\n })\n .strict();\n\nconst oauthCreateConfigSchema = customConnectorOAuthConfigInputSchema.required({\n clientSecret: true,\n});\n\nconst oauthCustomConnectorCreateSchema = customConnectorDefinitionSchema\n .extend({\n authMode: customConnectorAuthModeSchema.extract([\"oauth\"]),\n oauthConfig: oauthCreateConfigSchema,\n values: customConnectorValueInputSchema.array(),\n })\n .strict();\n\nconst customConnectorCreateSchema = manualCustomConnectorCreateSchema.or(\n oauthCustomConnectorCreateSchema,\n);\n\ntype CustomConnectorCreateInput = ReturnType<\n typeof customConnectorCreateSchema.parse\n>;\n\ninterface CreateOptions {\n readonly file: string;\n readonly agent?: string;\n readonly json?: boolean;\n}\n\ninterface CreateResult {\n readonly connector: CustomConnectorResponse;\n readonly agentId?: string;\n readonly authorizationUrl?: string;\n}\n\nfunction requireCustomConnectorWriteCapability(): void {\n const payload = decodeZeroTokenPayload();\n if (payload && !payload.capabilities.includes(\"connector:write\")) {\n throw new Error(\n \"Custom connector creation is not enabled for this agent run\",\n );\n }\n}\n\nfunction valueMarker(value: {\n readonly key: string;\n readonly kind: \"secret\" | \"variable\";\n}): string {\n return `${value.kind}:${value.key}`;\n}\n\nfunction validateValues(definition: CustomConnectorCreateInput): void {\n const fields = new Map(\n definition.fields.map((field) => {\n return [valueMarker(field), field] as const;\n }),\n );\n const provided = new Set<string>();\n for (const value of definition.values) {\n const marker = valueMarker(value);\n if (!fields.has(marker)) {\n throw new Error(`Unknown custom connector value: ${marker}`);\n }\n if (provided.has(marker)) {\n throw new Error(`Duplicate custom connector value: ${marker}`);\n }\n provided.add(marker);\n }\n const missing = definition.fields.flatMap((field) => {\n const marker = valueMarker(field);\n return field.required && !provided.has(marker) ? [marker] : [];\n });\n if (missing.length > 0) {\n throw new Error(\n `Missing required custom connector values: ${missing.join(\", \")}`,\n );\n }\n}\n\nfunction printCreateResult(result: CreateResult, json: boolean): void {\n if (json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n console.log(\n chalk.green(`✓ Custom connector \"${result.connector.displayName}\" created`),\n );\n console.log(chalk.dim(` ID: ${result.connector.id}`));\n console.log(chalk.dim(` Slug: ${result.connector.slug}`));\n console.log(\n chalk.dim(` Authentication: ${result.connector.authMode ?? \"manual\"}`),\n );\n console.log(\n chalk.dim(\n ` Status: ${\n result.connector.connected ? \"connected\" : \"awaiting authorization\"\n }`,\n ),\n );\n if (result.agentId && !result.authorizationUrl) {\n console.log(chalk.dim(` Agent: ${result.agentId} (authorized)`));\n }\n if (!result.authorizationUrl) {\n return;\n }\n\n console.log();\n console.log(\"Complete OAuth authorization:\");\n console.log(\n ` [Authorize ${result.connector.displayName}](${result.authorizationUrl})`,\n );\n if (result.agentId) {\n console.log(\n chalk.dim(\n ` Approval will also authorize this connector for agent ${result.agentId}.`,\n ),\n );\n }\n}\n\nasync function createManualCustomConnector(\n definition: Extract<CustomConnectorCreateInput, { authMode: \"manual\" }>,\n agentId: string | undefined,\n): Promise<CreateResult> {\n validateValues(definition);\n const { values, ...body } = definition;\n const created = await createZeroCustomConnector(body);\n const connector = await setZeroCustomConnectorValues(created.id, values);\n if (agentId) {\n await addZeroAgentCustomConnector(agentId, connector.id);\n }\n return {\n connector,\n ...(agentId ? { agentId } : {}),\n };\n}\n\nasync function createOAuthCustomConnector(\n definition: Extract<CustomConnectorCreateInput, { authMode: \"oauth\" }>,\n agentId: string | undefined,\n): Promise<CreateResult> {\n const { values, ...body } = definition;\n if (body.fields.length > 0 || values.length > 0) {\n throw new Error(\n \"OAuth custom connectors require empty fields and values arrays\",\n );\n }\n const created = await createZeroCustomConnector(body);\n const authorizationUrl = await startZeroCustomConnectorOAuth2(\n created.id,\n agentId,\n );\n return {\n connector: created,\n authorizationUrl,\n ...(agentId ? { agentId } : {}),\n };\n}\n\nexport const createCustomConnectorCommand = new Command()\n .name(\"create\")\n .description(\n \"Create and configure a manual or OAuth custom connector from JSON\",\n )\n .requiredOption(\n \"-f, --file <path>\",\n \"JSON file containing the connector definition and credentials\",\n )\n .option(\n \"--agent <id>\",\n \"Authorize this agent (defaults to ZERO_AGENT_ID when available)\",\n )\n .option(\"--json\", \"Print the connector and authorization result as JSON\")\n .addHelpText(\n \"after\",\n `\nFile format:\n The file must contain one complete connector definition. The agent should\n generate this file from the user's requirements and credentials.\n\nAgent workflow:\n 1. Ask the user in chat only for missing API details and credentials.\n 2. Derive the prefixes, fields, injections, and OAuth settings.\n 3. Write a temporary JSON file, run this command, then remove the file.\n The user should not need to write JSON or run this command.\n\n Common fields:\n displayName Human-readable connector name\n prefixTemplates Allowed HTTPS API URL prefixes\n fields Inputs referenced by manual templates\n headerInjections Headers added to matching requests\n queryInjections Query parameters added to matching requests\n authMode \"manual\" or \"oauth\"\n\nManual mode:\n Add a values array with one entry for every required field. References use\n {{secrets.KEY}} or {{variables.KEY}}. The command creates the connector,\n stores the values, and authorizes --agent in one flow.\n\n {\n \"displayName\": \"Acme API\",\n \"prefixTemplates\": [\"https://api.acme.example/v1/\"],\n \"fields\": [\n {\n \"key\": \"api_key\",\n \"label\": \"API key\",\n \"kind\": \"secret\",\n \"required\": true\n }\n ],\n \"headerInjections\": [\n {\n \"name\": \"Authorization\",\n \"valueTemplate\": \"Bearer {{secrets.api_key}}\"\n }\n ],\n \"queryInjections\": [],\n \"authMode\": \"manual\",\n \"values\": [\n { \"key\": \"api_key\", \"kind\": \"secret\", \"value\": \"<user-api-key>\" }\n ]\n }\n\nOAuth mode:\n Use {{oauth.access_token}} in an injection and provide the complete OAuth\n client configuration. OAuth mode requires empty fields and values arrays.\n The command prints an authorization link. If --agent is set, completing\n OAuth also authorizes that agent.\n\n {\n \"displayName\": \"Acme OAuth API\",\n \"prefixTemplates\": [\"https://api.acme.example/v1/\"],\n \"fields\": [],\n \"headerInjections\": [\n {\n \"name\": \"Authorization\",\n \"valueTemplate\": \"Bearer {{oauth.access_token}}\"\n }\n ],\n \"queryInjections\": [],\n \"authMode\": \"oauth\",\n \"values\": [],\n \"oauthConfig\": {\n \"providerAdapter\": \"standard\",\n \"clientId\": \"<oauth-client-id>\",\n \"clientSecret\": \"<oauth-client-secret>\",\n \"authorizationUrl\": \"https://acme.example/oauth/authorize\",\n \"tokenUrl\": \"https://acme.example/oauth/token\",\n \"tokenEndpointAuthMethod\": \"client_secret_post\",\n \"pkceMethod\": \"S256\",\n \"scopes\": [\"read\", \"write\"],\n \"authorizationParams\": {}\n }\n }\n\nExamples:\n zero connector custom create --file ./connector.json\n zero connector custom create --file ./connector.json --agent <agent-id>\n zero connector custom create --file ./connector.json --json\n\nNotes:\n - Requires an organization admin\n - Requires the customConnectorCliCreate feature\n - OAuth custom connectors also require the customConnectorOAuth2 feature\n - --agent defaults to ZERO_AGENT_ID inside an agent run\n - OAuth always requires the user to approve the generated authorization link\n - The file contains plaintext credentials; keep it temporary and never commit it`,\n )\n .action(\n withErrorHandler(async (options: CreateOptions) => {\n requireCustomConnectorWriteCapability();\n const raw = await readFile(options.file, \"utf8\");\n const input: unknown = JSON.parse(raw);\n const definition = customConnectorCreateSchema.parse(input);\n const agentId = options.agent ?? process.env.ZERO_AGENT_ID;\n if (agentId) {\n await getZeroAgent(agentId);\n }\n const result =\n definition.authMode === \"manual\"\n ? await createManualCustomConnector(definition, agentId)\n : await createOAuthCustomConnector(definition, agentId);\n printCreateResult(result, options.json ?? false);\n }),\n );\n","import { Command, Option } from \"commander\";\nimport { UNKNOWN_PERMISSION_GRANT } from \"@vm0/connectors/firewall-types\";\nimport type { ConnectorCheckPolicy } from \"@vm0/api-contracts/contracts/zero-connector-check\";\nimport { withErrorHandler } from \"../../../lib/command\";\nimport { getPlatformOrigin } from \"../doctor/platform-url\";\nimport {\n isComputerUsePermissionTarget,\n printComputerUsePermissionGuidance,\n} from \"./computer-use-guidance\";\nimport {\n isBrowserPermissionTarget,\n printBrowserPermissionGuidance,\n} from \"./browser-guidance\";\nimport {\n ApiRequestError,\n createBrowserAuthorizationRequest,\n createComputerUseAuthorizationRequest,\n} from \"../../../lib/api\";\nimport { diagnoseZeroConnectorCheck } from \"../../../lib/api/domains/zero-connectors\";\nimport {\n addRequestedCallbackSearchParams,\n connectorActionCallbackAvailable,\n printCallbackTurnInstruction,\n} from \"./action-url\";\nimport {\n buildConnectorUrlDiagnosticRequest,\n resolveConnectorCheckDiagnostic,\n type ResolvedDiagnostic,\n} from \"./check\";\n\nfunction permissionDescription(permission: string): string {\n return permission === UNKNOWN_PERMISSION_GRANT\n ? \"unknown endpoints\"\n : `the \"${permission}\" permission`;\n}\n\nfunction permissionPolicyForDiagnostic(args: {\n readonly result: ResolvedDiagnostic;\n readonly permission: string;\n readonly method: string;\n readonly url: string;\n}): ConnectorCheckPolicy {\n if (args.result.mode !== \"url\") {\n throw new Error(\n \"Connector diagnostic returned an environment result for a URL request.\",\n );\n }\n\n if (args.permission === UNKNOWN_PERMISSION_GRANT) {\n if (args.result.permission.kind === \"unknown-endpoint\") {\n return args.result.permission.policy;\n }\n throw permissionMismatchError({\n permission: args.permission,\n method: args.method,\n url: args.url,\n matchedPermissions: args.result.permission.permissions.map(\n (permission) => {\n return permission.name;\n },\n ),\n });\n }\n\n if (args.result.permission.kind === \"unknown-endpoint\") {\n throw permissionMismatchError({\n permission: args.permission,\n method: args.method,\n url: args.url,\n matchedPermissions: [UNKNOWN_PERMISSION_GRANT],\n });\n }\n\n const matchedPermission = args.result.permission.permissions.find(\n (permission) => {\n return permission.name === args.permission;\n },\n );\n if (matchedPermission === undefined) {\n throw permissionMismatchError({\n permission: args.permission,\n method: args.method,\n url: args.url,\n matchedPermissions: args.result.permission.permissions.map(\n (permission) => {\n return permission.name;\n },\n ),\n });\n }\n return matchedPermission.policy;\n}\n\nfunction permissionMismatchError(args: {\n readonly permission: string;\n readonly method: string;\n readonly url: string;\n readonly matchedPermissions: readonly string[];\n}): Error {\n return new Error(\n `Permission \"${args.permission}\" does not match ${args.method} ${args.url}. The request maps to: ${args.matchedPermissions.join(\", \")}. Use the exact permission-request command printed by zero connector check; provider OAuth scopes and missing_scope/needed values cannot be granted here.`,\n );\n}\n\nfunction assertRequestablePolicy(args: {\n readonly policy: ConnectorCheckPolicy;\n readonly permission: string;\n readonly method: string;\n readonly url: string;\n}): void {\n switch (args.policy.outcome) {\n case \"deny\":\n case \"ask\":\n return;\n case \"allow\":\n throw new Error(\n `${permissionDescription(args.permission)} is already allowed by Zero for ${args.method} ${args.url}. Provider authorization failures cannot be fixed with a Zero permission request.`,\n );\n case \"unavailable\":\n throw new Error(\n `Zero permission policy is unavailable for ${args.method} ${args.url}. Retry zero connector check from an active run before requesting access.`,\n );\n }\n}\n\nfunction printSensitivePermissionGuidance(\n connectorSlug: string,\n permission: string,\n): void {\n // Slack chat:write: strongly recommend bot-based messaging over user identity\n if (connectorSlug === \"slack\" && permission === \"chat:write\") {\n console.log(\"\");\n console.log(\n \"IMPORTANT: Granting chat:write allows sending messages AS THE USER's identity, not as a bot.\",\n );\n console.log(\n \"Use `zero slack message send -c <channel> -t <text>` to send messages as the bot instead — this is the recommended approach for most use cases.\",\n );\n console.log(\n \"Only allow this permission below if acting as the user is specifically required.\",\n );\n console.log(\"\");\n }\n\n // Gmail send permissions: strongly recommend draft-based workflow over direct send.\n if (\n connectorSlug === \"gmail\" &&\n (permission === \"messages.send\" || permission === \"drafts.send\")\n ) {\n console.log(\"\");\n console.log(\n \"IMPORTANT: Granting Gmail send permissions allows the agent to send emails directly as the user.\",\n );\n console.log(\n \"Consider keeping messages.send and drafts.send disabled and using drafts.write instead — the agent can create drafts for the user to review and send manually.\",\n );\n console.log(\n \"Only allow this permission below if direct sending is specifically required.\",\n );\n console.log(\"\");\n }\n}\n\nfunction printPermissionRequestMessage(args: {\n readonly permission: string;\n readonly label: string;\n readonly url: string;\n}): void {\n console.log(\n `You can allow ${permissionDescription(args.permission)} for your connector access: [Manage ${args.label} permissions](${args.url})`,\n );\n}\n\nfunction printComputerUseAuthorizationLink(args: {\n readonly authorizationUrl: string;\n readonly expiresAt: string;\n}): void {\n console.log(\n \"Computer Use needs a Zero Desktop host selected before a run starts.\",\n );\n console.log(\n \"Ask the user to authorize a host for future runs in this chat or Slack thread:\",\n );\n console.log(args.authorizationUrl);\n console.log(\n `This link expires at ${args.expiresAt}. Existing run tokens cannot be upgraded in place; start a new run after authorization.`,\n );\n}\n\nasync function printComputerUsePermissionRequestMessage(): Promise<void> {\n if (!process.env.ZERO_TOKEN) {\n printComputerUsePermissionGuidance();\n return;\n }\n\n try {\n const request = await createComputerUseAuthorizationRequest();\n printComputerUseAuthorizationLink({\n authorizationUrl: request.authorizationUrl,\n expiresAt: request.expiresAt,\n });\n } catch (error) {\n if (error instanceof ApiRequestError) {\n console.log(\n `Computer Use authorization link unavailable: ${error.message}`,\n );\n printComputerUsePermissionGuidance();\n return;\n }\n const message = error instanceof Error ? error.message : \"Unknown error\";\n console.log(`Computer Use authorization link unavailable: ${message}`);\n printComputerUsePermissionGuidance();\n }\n}\n\nfunction printBrowserAuthorizationLink(args: {\n readonly authorizationUrl: string;\n readonly expiresAt: string;\n}): void {\n console.log(\n \"Cloud browser needs to be enabled for this chat thread before a run starts.\",\n );\n console.log(\n \"Ask the user to enable the cloud browser for future runs in this thread:\",\n );\n console.log(args.authorizationUrl);\n console.log(\n `This link expires at ${args.expiresAt}. Existing run tokens cannot be upgraded in place; start a new run after authorization.`,\n );\n}\n\nasync function printBrowserPermissionRequestMessage(): Promise<void> {\n if (!process.env.ZERO_TOKEN) {\n printBrowserPermissionGuidance();\n return;\n }\n try {\n const request = await createBrowserAuthorizationRequest();\n printBrowserAuthorizationLink(request);\n } catch (error) {\n if (error instanceof ApiRequestError) {\n console.log(\n `Cloud browser authorization link unavailable: ${error.message}`,\n );\n printBrowserPermissionGuidance();\n return;\n }\n const message = error instanceof Error ? error.message : \"Unknown error\";\n console.log(`Cloud browser authorization link unavailable: ${message}`);\n printBrowserPermissionGuidance();\n }\n}\n\nasync function outputPermissionRequestMessage(\n connectorSlug: string,\n label: string,\n permission: string,\n agentId: string | undefined,\n callbackPrompt: string | undefined,\n): Promise<void> {\n const platformOrigin = await getPlatformOrigin();\n\n const urlParams = new URLSearchParams({\n connectorSlug,\n permission,\n action: \"allow\",\n });\n addRequestedCallbackSearchParams(urlParams, callbackPrompt, agentId);\n\n const pagePath = agentId ? `/agents/${agentId}/permissions` : \"/agents\";\n const url = `${platformOrigin}${pagePath}?${urlParams.toString()}`;\n\n printSensitivePermissionGuidance(connectorSlug, permission);\n printPermissionRequestMessage({\n permission,\n label,\n url,\n });\n if (callbackPrompt !== undefined) {\n printCallbackTurnInstruction();\n }\n}\n\nconst callbackPromptOption = new Option(\n \"--callback-prompt <prompt>\",\n \"Start the next web chat round with this prompt after the permission is granted\",\n);\nconst callbackPromptAvailable = connectorActionCallbackAvailable();\nif (!callbackPromptAvailable) {\n callbackPromptOption.hideHelp();\n}\nconst callbackPromptExample = callbackPromptAvailable\n ? ' zero connector permission-request github --permission contents:write --url https://api.github.com/repos/vm0-ai/vm0 --method POST --callback-prompt \"Re-check the permission, then continue the previous task\"\\n'\n : \"\";\nconst callbackPromptNotes = callbackPromptAvailable\n ? \" - Use --callback-prompt only when this turn needs exactly one connector or permission action\\n - Callback prompts are included in the URL; keep them concise and do not include secrets\\n\"\n : \"\";\n\nexport const permissionRequestCommand = new Command()\n .name(\"permission-request\")\n .description(\"Request permission to use a connector capability\")\n .argument(\"<slug>\", \"The connector slug (e.g. github)\")\n .addOption(\n new Option(\n \"--permission <name>\",\n \"The permission name to request\",\n ).makeOptionMandatory(),\n )\n .addOption(\n new Option(\n \"--agent <id>\",\n \"Agent ID whose permission page should be opened (defaults to ZERO_AGENT_ID)\",\n ),\n )\n .addOption(\n new Option(\n \"--url <URL>\",\n \"The failed request URL reported to zero connector check\",\n ),\n )\n .addOption(\n new Option(\"--method <METHOD>\", \"The failed request HTTP method\").default(\n \"GET\",\n ),\n )\n .addOption(callbackPromptOption)\n .addHelpText(\n \"after\",\n `\nExamples:\n zero connector permission-request github --permission contents:read --url https://api.github.com/repos/vm0-ai/vm0 --method GET\n${callbackPromptExample} zero connector permission-request gmail --permission messages.write --url https://gmail.googleapis.com/gmail/v1/users/me/messages --method POST --agent <agent-id>\n zero connector permission-request cloudflare --permission __unknown__ --url https://api.cloudflare.com/client/v4/example --method POST\n zero connector permission-request computer-use --permission computer-use:write\n zero connector permission-request browser --permission browser:write\n\nNotes:\n - First run zero connector check --url <FAILED_URL> --method <METHOD>\n - Use the exact permission-request command printed by connector check\n - A platform URL is output only when that request maps to a denied or approval-required permission\n - Use --permission __unknown__ to request access to unknown endpoints\n - Use --agent to request a permission for another agent; defaults to ZERO_AGENT_ID\n - The user chooses the permission duration on the confirmation page\n${callbackPromptNotes} - Permission requests update the current user's connector grants after confirmation`,\n )\n .action(\n withErrorHandler(\n async (\n connectorSlug: string,\n opts: {\n permission: string;\n agent?: string;\n url?: string;\n method: string;\n callbackPrompt?: string;\n },\n ) => {\n if (\n isBrowserPermissionTarget({\n connectorSlug,\n permission: opts.permission,\n })\n ) {\n if (opts.callbackPrompt !== undefined) {\n throw new Error(\n \"--callback-prompt is not supported for cloud browser authorization requests\",\n );\n }\n await printBrowserPermissionRequestMessage();\n return;\n }\n if (\n isComputerUsePermissionTarget({\n connectorSlug,\n permission: opts.permission,\n })\n ) {\n if (opts.callbackPrompt !== undefined) {\n throw new Error(\n \"--callback-prompt is not supported for Computer Use authorization requests\",\n );\n }\n await printComputerUsePermissionRequestMessage();\n return;\n }\n\n const agentId = opts.agent ?? process.env.ZERO_AGENT_ID;\n if (opts.url === undefined) {\n throw new Error(\n \"--url is required for connector permission requests. Run zero connector check --url <FAILED_URL> --method <METHOD> and use the permission-request command it prints.\",\n );\n }\n\n const diagnosticRequest = buildConnectorUrlDiagnosticRequest({\n url: opts.url,\n method: opts.method,\n connectorSlug,\n });\n const diagnostic = await diagnoseZeroConnectorCheck(diagnosticRequest);\n const result = resolveConnectorCheckDiagnostic(\n diagnosticRequest,\n diagnostic,\n );\n const policy = permissionPolicyForDiagnostic({\n result,\n permission: opts.permission,\n method: diagnosticRequest.method,\n url: diagnosticRequest.url,\n });\n assertRequestablePolicy({\n policy,\n permission: opts.permission,\n method: diagnosticRequest.method,\n url: diagnosticRequest.url,\n });\n\n await outputPermissionRequestMessage(\n result.connector.connectorSlug,\n result.connector.label,\n opts.permission,\n agentId,\n opts.callbackPrompt,\n );\n },\n ),\n );\n","const BROWSER_CONNECTOR_SLUG = \"browser\";\nconst BROWSER_WRITE_CAPABILITY = \"browser:write\";\n\nexport function isBrowserPermissionTarget(args: {\n readonly connectorSlug: string;\n readonly permission: string;\n}): boolean {\n return (\n args.connectorSlug === BROWSER_CONNECTOR_SLUG ||\n args.permission === BROWSER_WRITE_CAPABILITY\n );\n}\n\nexport function printBrowserPermissionGuidance(): void {\n console.log(\n \"Cloud browser access is controlled by the current chat thread, not a connector grant.\",\n );\n console.log(\n \"Enable Cloud browser under Your computer in the chat composer, then start a new run. Existing run tokens cannot be upgraded in place.\",\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;ACAA;;;ACAA;AAAA,IAAM,8BAA8B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IACF;AAAA,EACF;AACF;;;AXhaK,IAAM,uBAAuB,IAAI,QAAQ,EAC7C,KAAK,WAAW,EAChB,YAAY,qDAAqD,EACjE,WAAW,qBAAqB,EAChC,WAAW,sBAAsB,EACjC,WAAW,cAAc,EACzB,WAAW,WAAW,EACtB,WAAW,aAAa,EACxB,WAAW,aAAa,EACxB,WAAWC,yBAAwB;","names":["LABEL_WIDTH","listCommand","statusCommand","permissionRequestCommand","permissionRequestCommand"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/zero/credit.ts"],"sourcesContent":["import { Command, Option } from \"commander\";\nimport chalk from \"chalk\";\nimport type { ZeroCapability } from \"@vm0/api-contracts/contracts/composes\";\nimport type { BillingStatusResponse } from \"@vm0/api-contracts/contracts/zero-billing\";\n\nimport { createZeroCreditCheckout, getZeroBillingStatus } from \"../../lib/api\";\nimport { withErrorHandler } from \"../../lib/command\";\nimport { decodeZeroTokenPayload } from \"../../lib/api/zero-token\";\nimport { getPlatformOrigin } from \"./doctor/platform-url\";\nimport {\n currentPlanAllowsVideo,\n currentPlanCanBuyCredits,\n currentTokenCanReadBilling,\n} from \"./shared/billing-capabilities\";\nimport { planUpgradeUrl } from \"./shared/billing-links\";\n\nfunction parseCredits(value: string): number {\n const credits = Number(value.replaceAll(\",\", \"\"));\n if (!Number.isInteger(credits) || credits <= 0) {\n throw new Error(\"credits must be a positive integer\");\n }\n return credits;\n}\n\nfunction requireZeroCapabilityForCreditAction(\n capability: ZeroCapability,\n message: string,\n): void {\n const payload = decodeZeroTokenPayload();\n if (payload && !payload.capabilities.includes(capability)) {\n throw new Error(message);\n }\n}\n\ninterface CreditOptions {\n readonly autoRecharge?: boolean;\n readonly autoRechargeThreshold?: number;\n readonly autoRechargeAmount?: number;\n}\n\nfunction autoRechargeConfiguration(options: CreditOptions):\n | {\n readonly enabled: true;\n readonly threshold: number;\n readonly amount: number;\n }\n | undefined {\n if (\n options.autoRecharge !== true &&\n (options.autoRechargeThreshold !== undefined ||\n options.autoRechargeAmount !== undefined)\n ) {\n throw new Error(\n \"--auto-recharge-threshold and --auto-recharge-amount require --auto-recharge\",\n );\n }\n\n if (options.autoRecharge !== true) {\n return undefined;\n }\n if (\n options.autoRechargeThreshold === undefined ||\n options.autoRechargeAmount === undefined\n ) {\n throw new Error(\n \"--auto-recharge requires --auto-recharge-threshold and --auto-recharge-amount\",\n );\n }\n return {\n enabled: true,\n threshold: options.autoRechargeThreshold,\n amount: options.autoRechargeAmount,\n };\n}\n\nfunction printCreditStatus(billing: BillingStatusResponse): void {\n console.log(chalk.bold(\"Credit status:\"));\n console.log(` Tier: ${chalk.cyan(billing.tier)}`);\n console.log(\n ` Available credits: ${chalk.cyan(billing.credits.toLocaleString())}`,\n );\n console.log(\n ` Can purchase credits: ${\n currentPlanCanBuyCredits(billing)\n ? chalk.green(\"yes\")\n : chalk.yellow(\"no\")\n }`,\n );\n console.log(\n ` Built-in video generation: ${\n currentPlanAllowsVideo(billing)\n ? chalk.green(\"available\")\n : chalk.yellow(\"unavailable\")\n }`,\n );\n console.log(\n ` Auto-recharge: ${\n billing.autoRecharge.enabled ? chalk.green(\"enabled\") : \"disabled\"\n }`,\n );\n if (billing.autoRecharge.enabled) {\n console.log(\n ` Threshold: ${billing.autoRecharge.threshold?.toLocaleString() ?? \"not set\"}`,\n );\n console.log(\n ` Amount: ${billing.autoRecharge.amount?.toLocaleString() ?? \"not set\"}`,\n );\n }\n}\n\nasync function showCreditStatus(options: CreditOptions): Promise<void> {\n requireZeroCapabilityForCreditAction(\n \"billing:read\",\n \"checking credit status requires billing:read capability\",\n );\n if (\n options.autoRecharge === true ||\n options.autoRechargeThreshold !== undefined ||\n options.autoRechargeAmount !== undefined\n ) {\n throw new Error(\"auto-recharge options require a credit amount\");\n }\n printCreditStatus(await getZeroBillingStatus());\n}\n\nasync function buyCredits(\n credits: number,\n options: CreditOptions,\n): Promise<void> {\n requireZeroCapabilityForCreditAction(\n \"billing:write\",\n \"buying credits requires billing:write capability\",\n );\n const autoRecharge = autoRechargeConfiguration(options);\n // Only workspace admins can buy credits; the checkout route enforces it.\n const billing = currentTokenCanReadBilling()\n ? await getZeroBillingStatus()\n : null;\n const origin = await getPlatformOrigin();\n if (billing && !currentPlanCanBuyCredits(billing)) {\n console.log(\n chalk.yellow(\n \"Credit purchases are not available for this workspace plan.\",\n ),\n );\n console.log(chalk.bold(\"Plan upgrade link:\"));\n console.log(planUpgradeUrl(origin));\n return;\n }\n\n const result = await createZeroCreditCheckout({\n credits,\n successUrl: `${origin}/?settings=usage&credit=success`,\n cancelUrl: `${origin}/?settings=usage&credit=canceled`,\n ...(autoRecharge ? { autoRecharge } : {}),\n });\n console.log(chalk.bold(\"Credit checkout link:\"));\n console.log(result.url);\n}\n\nexport const zeroCreditCommand = new Command()\n .name(\"credit\")\n .description(\"View credit balance or create a checkout link to buy credits\")\n .argument(\"[credits]\", \"Number of credits to buy\", parseCredits)\n .addOption(\n new Option(\"--auto-recharge\", \"Enable auto-recharge after checkout\"),\n )\n .option(\n \"--auto-recharge-threshold <credits>\",\n \"Recharge when balance is at or below this number of credits\",\n parseCredits,\n )\n .option(\n \"--auto-recharge-amount <credits>\",\n \"Credits to buy for each auto-recharge\",\n parseCredits,\n )\n .action(\n withErrorHandler(\n async (credits: number | undefined, options: CreditOptions) => {\n if (credits === undefined) {\n await showCreditStatus(options);\n return;\n }\n await buyCredits(credits, options);\n },\n ),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAgBA,SAAS,aAAa,OAAuB;AAC3C,QAAM,UAAU,OAAO,MAAM,WAAW,KAAK,EAAE,CAAC;AAChD,MAAI,CAAC,OAAO,UAAU,OAAO,KAAK,WAAW,GAAG;AAC9C,UAAM,IAAI,MAAM,oCAAoC;AAAA,EACtD;AACA,SAAO;AACT;AAEA,SAAS,qCACP,YACA,SACM;AACN,QAAM,UAAU,uBAAuB;AACvC,MAAI,WAAW,CAAC,QAAQ,aAAa,SAAS,UAA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O;AAAA,IACnC;AAAA,EACF;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/zero/developer-support.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { withErrorHandler } from \"../../lib/command\";\nimport {\n requestDeveloperSupportConsent,\n submitDeveloperSupport,\n} from \"../../lib/api\";\n\nexport const zeroDeveloperSupportCommand = new Command()\n .name(\"developer-support\")\n .description(\"Submit a diagnostic report to the dev team\")\n .requiredOption(\"--title <text>\", \"Issue title\")\n .requiredOption(\"--description <text>\", \"Diagnostic description\")\n .option(\"--consent-code <code>\", \"User-provided verification code\")\n .addHelpText(\n \"after\",\n `\nExamples:\n Step 1 — Get consent code:\n zero developer-support --title \"GitHub 403 error\" --description \"Connector connected but API returns 403\"\n\n Step 2 — Submit with code:\n zero developer-support --title \"GitHub 403 error\" --description \"Connector connected but API returns 403\" --consent-code A7X3\n\nNotes:\n - The consent code must be provided by the user to confirm sharing their conversation\n - The dev team will receive a diagnostic bundle with conversation, environment, and connector info`,\n )\n .action(\n withErrorHandler(\n async (options: {\n title: string;\n description: string;\n consentCode?: string;\n }) => {\n if (!options.consentCode) {\n const { consentCode } = await requestDeveloperSupportConsent({\n title: options.title,\n description: options.description,\n });\n console.log(\n \"Consent required to share chat history with developers.\",\n );\n console.log(`Code: ${consentCode}`);\n console.log(\"Ask the user to confirm by providing this code.\");\n } else {\n const { reference } = await submitDeveloperSupport({\n title: options.title,\n description: options.description,\n consentCode: options.consentCode,\n });\n console.log(\"Developer support request submitted successfully.\");\n console.log(`Reference: ${reference}`);\n }\n },\n ),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAOO,IAAM,8BAA8B,IAAI,QAAQ,EACpD,KAAK,mBAAmB,EACxB,YAAY,4CAA4C,EACxD,eAAe,kBAAkB,aAAa,EAC9C,eAAe,wBAAwB,wBAAwB,EAC/D,OAAO,yBAAyB,iCAAiC,EACjE;AAAA,EACC;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWF,EACC;AAAA,EACC;AAAA,IACE,OAAO,YAID;AACJ,UAAI,CAAC,QAAQ,aAAa;AACxB,cAAM,EAAE,YAAY,IAAI,MAAM,+BAA+B;AAAA,UAC3D,OAAO,QAAQ;AAAA,UACf,aAAa,QAAQ;AAAA,QACvB,CAAC;AACD,gBAAQ;AAAA,UACN;AAAA,QACF;AACA,gBAAQ,IAAI,SAAS,WAAW,EAAE;AAClC,gBAAQ,IAAI,iDAAiD;AAAA,MAC/D,OAAO;AACL,cAAM,EAAE,UAAU,IAAI,MAAM,uBAAuB;AAAA,UACjD,OAAO,QAAQ;AAAA,UACf,aAAa,QAAQ;AAAA,UACrB,aAAa,QAAQ;AAAA,QACvB,CAAC;AACD,gBAAQ,IAAI,mDAAmD;AAC/D,gBAAQ,IAAI,cAAc,SAAS,EAAE;AAAA,MACvC;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/zero/doctor/index.ts","../src/commands/zero/doctor/credit.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { creditCommand } from \"./credit\";\n\nexport const zeroDoctorCommand = new Command()\n .name(\"doctor\")\n .description(\"Diagnose account and runtime issues\")\n .addCommand(creditCommand)\n .addHelpText(\n \"after\",\n `\nExamples:\n Check credits? zero doctor credit\n\nNotes:\n - Use zero doctor credit when a run or generation fails because the org has insufficient credits, when a user asks how to recharge, or before trying to buy credits\n - Use zero generate <type> (no --prompt) to see every provider available for a given generation type\n - Use zero connector check for connector and permission diagnostics`,\n );\n","import { Command } from \"commander\";\nimport chalk from \"chalk\";\n\nimport { getZeroBillingStatus, getZeroOrg } from \"../../../lib/api\";\nimport { withErrorHandler } from \"../../../lib/command\";\nimport { getPlatformOrigin } from \"./platform-url\";\nimport {\n currentPlanAllowsVideo,\n currentPlanCanBuyCredits,\n} from \"../shared/billing-capabilities\";\nimport { planUpgradeUrl } from \"../shared/billing-links\";\n\nexport const creditCommand = new Command()\n .name(\"credit\")\n .description(\"Diagnose current organization credit and purchase access\")\n .action(\n withErrorHandler(async () => {\n const [org, billing, platformOrigin] = await Promise.all([\n getZeroOrg(),\n getZeroBillingStatus(),\n getPlatformOrigin(),\n ]);\n const planCanBuyCredits = currentPlanCanBuyCredits(billing);\n\n console.log(chalk.bold(\"Credit diagnostics:\"));\n console.log(` Workspace: ${chalk.green(org.name)}`);\n console.log(` Tier: ${chalk.cyan(billing.tier)}`);\n console.log(\n ` Available credits: ${chalk.cyan(billing.credits.toLocaleString())}`,\n );\n console.log(\n ` Plan can purchase credits: ${\n planCanBuyCredits ? chalk.green(\"yes\") : chalk.yellow(\"no\")\n }`,\n );\n console.log(\n ` Built-in video generation: ${\n currentPlanAllowsVideo(billing)\n ? chalk.green(\"available\")\n : chalk.yellow(\"unavailable\")\n }`,\n );\n console.log(\n ` Auto-recharge: ${\n billing.autoRecharge.enabled ? chalk.green(\"enabled\") : \"disabled\"\n }`,\n );\n if (billing.autoRecharge.enabled) {\n console.log(\n ` Threshold: ${billing.autoRecharge.threshold?.toLocaleString() ?? \"not set\"}`,\n );\n console.log(\n ` Amount: ${billing.autoRecharge.amount?.toLocaleString() ?? \"not set\"}`,\n );\n }\n\n if (!planCanBuyCredits) {\n console.log(\n \"\\nThis workspace plan cannot buy credits. A workspace admin has to upgrade the plan instead:\",\n );\n console.log(planUpgradeUrl(platformOrigin));\n return;\n }\n\n if (billing.tier === \"free\") {\n console.log(\n \"\\nWorkspace admins can upgrade to Pro from billing or buy credits with `zero credit <credits>`.\",\n );\n } else {\n console.log(\n \"\\nWorkspace admins can use `zero credit <credits>` to buy more credits.\",\n );\n }\n }),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;ACAA;AAYO,IAAM,gBAAgB,IAAI,QAAQ,EACtC,KAAK,QAAQ,EACb,YAAY,0DAA0D,EACtE;AAAA,EACC,iBAAiB,YAAY;AAC3B,U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EAC1C,KAAK,QAAQ,EACb,YAAY,qCAAqC,EACjD,WAAW,aAAa,EACxB;AAAA,EACC;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/zero/feishu/index.ts","../src/commands/zero/feishu/download-file.ts","../src/commands/zero/feishu/message/index.ts","../src/commands/zero/feishu/message/send.ts","../src/commands/zero/feishu/upload-file.ts"],"sourcesContent":["import { Command } from \"commander\";\n\nimport { downloadFileCommand } from \"./download-file\";\nimport { zeroFeishuMessageCommand } from \"./message\";\nimport { uploadFileCommand } from \"./upload-file\";\n\nexport const zeroFeishuCommand = new Command()\n .name(\"feishu\")\n .description(\"Send messages and transfer files through Feishu\")\n .addCommand(zeroFeishuMessageCommand)\n .addCommand(downloadFileCommand)\n .addCommand(uploadFileCommand)\n .addHelpText(\n \"after\",\n `\nExamples:\n Send to a chat: zero feishu message send -c <chat-id> -t \"Hello!\"\n Send a DM: zero feishu message send -u <open-id> -t \"Hello!\"\n Reply in a thread: zero feishu message send -r <message-id> --thread -t \"Reply\"\n Upload a file: zero feishu upload-file -f /tmp/report.pdf -c <chat-id>\n Download a file: zero feishu download-file <message-id> <file-key> --type file`,\n );\n","import { tmpdir } from \"node:os\";\nimport { basename, join } from \"node:path\";\n\nimport { Command } from \"commander\";\nimport type { FeishuResourceType } from \"@vm0/api-contracts/contracts/integrations\";\n\nimport { downloadFeishuFile } from \"../../../lib/api\";\nimport { withErrorHandler } from \"../../../lib/command\";\n\nfunction defaultOutPath(fileKey: string): string {\n return join(tmpdir(), `feishu-${basename(fileKey).slice(0, 80)}`);\n}\n\nfunction parseResourceType(value: string): FeishuResourceType {\n if (value !== \"file\" && value !== \"image\") {\n throw new Error(\"--type must be either file or image\");\n }\n return value;\n}\n\nexport const downloadFileCommand = new Command()\n .name(\"download-file\")\n .description(\"Download a file from a Feishu message\")\n .argument(\"<message-id>\", \"Message ID from a [Feishu file] block\")\n .argument(\"<file-key>\", \"File key from a [Feishu file] block\")\n .requiredOption(\n \"--type <type>\",\n \"Resource type from the block: file or image\",\n )\n .option(\"-i, --installation <id>\", \"Feishu installation ID\")\n .option(\"-o, --out <path>\", \"Output path (default: /tmp/feishu-<file-key>)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n Download a file: zero feishu download-file om_xxx file_xxx --type file\n Download an image: zero feishu download-file om_xxx img_xxx --type image -o /tmp/image.png\n Select an app: zero feishu download-file om_xxx file_xxx --type file -i <installation-id>\n\nOutput:\n Prints a JSON object to stdout on success:\n {\"path\":\"/tmp/feishu-file_xxx\",\"mimetype\":\"application/pdf\",\"size\":12345}\n\nNotes:\n - Use the message ID, file key, and type exactly as shown in a [Feishu file] block\n - Specify --installation when the organization has multiple Feishu bots\n - Streams the file bytes directly to disk`,\n )\n .action(\n withErrorHandler(\n async (\n messageId: string,\n fileKey: string,\n options: {\n readonly type: string;\n readonly installation?: string;\n readonly out?: string;\n },\n ) => {\n const outPath = options.out ?? defaultOutPath(fileKey);\n const result = await downloadFeishuFile(\n messageId,\n fileKey,\n parseResourceType(options.type),\n options.installation,\n outPath,\n );\n console.log(JSON.stringify(result));\n },\n ),\n );\n","import { Command } from \"commander\";\n\nimport { sendCommand } from \"./send\";\n\nexport const zeroFeishuMessageCommand = new Command()\n .name(\"message\")\n .description(\"Send Feishu messages\")\n .addCommand(sendCommand);\n","import { readFileSync } from \"node:fs\";\n\nimport chalk from \"chalk\";\nimport { Command } from \"commander\";\n\nimport { sendFeishuMessage } from \"../../../../lib/api\";\nimport { withErrorHandler } from \"../../../../lib/command\";\n\ninterface SendFeishuOptions {\n readonly installation?: string;\n readonly chat?: string;\n readonly user?: string;\n readonly reply?: string;\n readonly thread?: boolean;\n readonly text?: string;\n readonly card?: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction parseCard(\n input: string | undefined,\n): Record<string, unknown> | undefined {\n if (!input) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(input);\n } catch {\n throw new Error(\"Invalid JSON for --card flag\", {\n cause: new Error(\"Provide a valid Feishu card JSON object\"),\n });\n }\n if (!isRecord(parsed)) {\n throw new Error(\"Invalid JSON for --card\", {\n cause: new Error(\"Provide a Feishu card JSON object\"),\n });\n }\n return parsed;\n}\n\nexport const sendCommand = new Command()\n .name(\"send\")\n .description(\"Send a message to a Feishu chat or user\")\n .option(\"-i, --installation <id>\", \"Feishu installation ID\")\n .option(\"-c, --chat <id>\", \"Feishu chat ID\")\n .option(\"-u, --user <open-id>\", 'Feishu user open ID (use \"me\" for yourself)')\n .option(\"-r, --reply <message-id>\", \"Message ID to reply to\")\n .option(\"--thread\", \"Reply in a Feishu thread\")\n .option(\"-t, --text <message>\", \"Message text\")\n .option(\"--card <json>\", \"Feishu interactive card JSON\")\n .addHelpText(\n \"after\",\n `\nExamples:\n Chat message: zero feishu message send -c oc_xxx -t \"Hello!\"\n Direct message: zero feishu message send -u ou_xxx -t \"Hello!\"\n DM yourself: zero feishu message send -u me -t \"Hello!\"\n Thread reply: zero feishu message send -r om_xxx --thread -t \"Reply\"\n Interactive card: zero feishu message send -c oc_xxx --card '{\"schema\":\"2.0\",\"body\":{\"elements\":[]}}'\n Select a custom app: zero feishu message send -i <installation-id> -c oc_xxx -t \"Hello!\"\n\nNotes:\n - Exactly one of --chat, --user, or --reply is required\n - Exactly one of --text or --card is required\n - --installation is required when the organization has multiple Feishu bots`,\n )\n .action(\n withErrorHandler(async (options: SendFeishuOptions) => {\n const targets = [options.chat, options.user, options.reply].filter(\n Boolean,\n );\n if (targets.length !== 1) {\n throw new Error(\n \"Exactly one of --chat, --user, or --reply must be provided\",\n );\n }\n if (options.thread && !options.reply) {\n throw new Error(\"--thread requires --reply\");\n }\n\n let text = options.text;\n if (!text && !options.card && !process.stdin.isTTY) {\n try {\n text = readFileSync(\"/dev/stdin\", \"utf8\").trim();\n } catch {\n // stdin is not readable; fall through to normal input validation.\n }\n }\n const card = parseCard(options.card);\n if (Boolean(text) === Boolean(card)) {\n throw new Error(\"Exactly one of --text or --card must be provided\");\n }\n\n const result = await sendFeishuMessage({\n installationId: options.installation,\n chat: options.chat,\n user: options.user,\n replyToMessageId: options.reply,\n replyInThread: options.thread,\n text,\n card,\n });\n console.log(chalk.green(`✓ Message sent (message: ${result.messageId})`));\n }),\n );\n","import { readFileSync, statSync } from \"node:fs\";\nimport { basename, extname } from \"node:path\";\n\nimport { Command } from \"commander\";\nimport { FEISHU_FILE_UPLOAD_MAX_BYTES } from \"@vm0/api-contracts/contracts/integrations\";\n\nimport {\n completeFeishuFileUpload,\n initFeishuFileUpload,\n} from \"../../../lib/api\";\nimport { withErrorHandler } from \"../../../lib/command\";\n\nconst MIME_BY_EXTENSION: Readonly<Record<string, string>> = {\n \".csv\": \"text/csv\",\n \".gif\": \"image/gif\",\n \".jpeg\": \"image/jpeg\",\n \".jpg\": \"image/jpeg\",\n \".json\": \"application/json\",\n \".md\": \"text/markdown\",\n \".mov\": \"video/quicktime\",\n \".mp4\": \"video/mp4\",\n \".pdf\": \"application/pdf\",\n \".png\": \"image/png\",\n \".svg\": \"image/svg+xml\",\n \".txt\": \"text/plain\",\n \".webm\": \"video/webm\",\n \".webp\": \"image/webp\",\n};\n\ninterface UploadFeishuOptions {\n readonly file: string;\n readonly installation?: string;\n readonly chat?: string;\n readonly user?: string;\n readonly reply?: string;\n readonly thread?: boolean;\n readonly contentType?: string;\n}\n\nfunction inferContentType(localPath: string): string {\n return (\n MIME_BY_EXTENSION[extname(localPath).toLowerCase()] ??\n \"application/octet-stream\"\n );\n}\n\nexport const uploadFileCommand = new Command()\n .name(\"upload-file\")\n .description(\"Upload a local file to Feishu as an organization bot\")\n .requiredOption(\"-f, --file <path>\", \"Local file path to upload\")\n .option(\"-i, --installation <id>\", \"Feishu installation ID\")\n .option(\"-c, --chat <id>\", \"Feishu chat ID\")\n .option(\"-u, --user <open-id>\", 'Feishu user open ID (use \"me\" for yourself)')\n .option(\"-r, --reply <message-id>\", \"Message ID to reply to\")\n .option(\"--thread\", \"Reply in a Feishu thread\")\n .option(\"--content-type <mime>\", \"Override inferred content type\")\n .addHelpText(\n \"after\",\n `\nExamples:\n Upload to a chat: zero feishu upload-file -f /tmp/report.pdf -c oc_xxx\n Send a DM: zero feishu upload-file -f /tmp/report.pdf -u ou_xxx\n Reply with a file: zero feishu upload-file -f /tmp/report.pdf -r om_xxx --thread\n Select a custom app: zero feishu upload-file -f /tmp/report.pdf -i <installation-id> -c oc_xxx\n\nOutput:\n Prints a JSON object to stdout on success:\n {\"messageId\":\"om_xxx\",\"chatId\":\"oc_xxx\",\"fileKey\":\"file_xxx\",\"filename\":\"report.pdf\",\"mimetype\":\"application/pdf\",\"size\":12345,\"url\":\"https://...\"}\n\nNotes:\n - Exactly one of --chat, --user, or --reply is required\n - Feishu accepts non-empty files up to 30 MB\n - Specify --installation when the organization has multiple Feishu bots`,\n )\n .action(\n withErrorHandler(async (options: UploadFeishuOptions) => {\n const targets = [options.chat, options.user, options.reply].filter(\n Boolean,\n );\n if (targets.length !== 1) {\n throw new Error(\n \"Exactly one of --chat, --user, or --reply must be provided\",\n );\n }\n if (options.thread && !options.reply) {\n throw new Error(\"--thread requires --reply\");\n }\n\n let fileSize: number;\n try {\n const stat = statSync(options.file);\n if (!stat.isFile()) {\n throw new Error(`Not a regular file: ${options.file}`);\n }\n fileSize = stat.size;\n } catch (error) {\n if (error instanceof Error && error.message.startsWith(\"Not \")) {\n throw error;\n }\n throw new Error(`File not found: ${options.file}`);\n }\n if (fileSize === 0) {\n throw new Error(\"File is empty\");\n }\n if (fileSize > FEISHU_FILE_UPLOAD_MAX_BYTES) {\n throw new Error(\n `File exceeds Feishu's ${FEISHU_FILE_UPLOAD_MAX_BYTES}-byte limit`,\n );\n }\n\n const filename = basename(options.file);\n const contentType = options.contentType ?? inferContentType(options.file);\n const prepared = await initFeishuFileUpload({\n filename,\n contentType,\n length: fileSize,\n supportsUploadHeaders: true,\n });\n const uploadResponse = await fetch(prepared.uploadUrl, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": prepared.contentType,\n ...prepared.uploadHeaders,\n },\n body: new Uint8Array(readFileSync(options.file)),\n });\n if (!uploadResponse.ok) {\n throw new Error(\n `File upload failed: ${uploadResponse.status} ${uploadResponse.statusText}`,\n );\n }\n\n const result = await completeFeishuFileUpload({\n uploadId: prepared.uploadId,\n installationId: options.installation,\n chat: options.chat,\n user: options.user,\n replyToMessageId: options.reply,\n replyInThread: options.thread,\n contentType: prepared.contentType,\n });\n console.log(JSON.stringify(result));\n }),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;ACAA;AAAA,SAAS,cAAc;AACvB,SAAS,UAAU,YAAY;AAQ/B,SAAS,eAAe,SAAyB;AAC/C,SAAO,KAAK,OAAO,GAAG,UAAU,SAAS,OAAO,EAAE,MAAM,GAAG,EAAE,CAAC,EAAE;AAClE;AAEA,SAAS,kBAAkB,OAAmC;AAC5D,MAAI,UAAU,UAAU,UAAU,SAAS;AACzC,UAAM,IAAI,MAAM,qCAAqC;AAAA,EACvD;AACA,SAAO;AACT;AAEO,IAAM,sBAAsB,IAAI,QAAQ,EAC5C,KAAK,eAAe,EACpB,YAAY,uCAAuC,EACnD,SAAS,gBAAgB,uCAAuC,EAChE,SAAS,cAAc,qCAAqC,EAC5D;AAAA,EACC;AAAA,EACA;AACF,EACC,OAAO,2BAA2B,wBAAwB,EAC1D,OAAO,oBAAoB,+CAA+C,EAC1E;AAAA,EACC;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcF,EACC;AAAA,EACC;AAAA,IACE,OACE,WACA,SACA,YAKG;AACH,YAAM,UAAU,QAAQ,OAAO,eAAe,OAAO;AACrD,YAAM,SAAS,MAAM;AAAA,QACnB;AAAA,QACA;AAAA,QACA,kBAAkB,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