@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.
- package/{agent-HUDTEGLK.js → agent-4F3XAJWN.js} +12 -6
- package/agent-4F3XAJWN.js.map +1 -0
- package/{banking-BMZONEXP.js → banking-CWQFQKZB.js} +61 -7
- package/banking-CWQFQKZB.js.map +1 -0
- package/{browser-LQP445CU.js → browser-BI6UFWPH.js} +4 -5
- package/browser-BI6UFWPH.js.map +1 -0
- package/{chat-UF7QAWUT.js → chat-MKIW4FPP.js} +24 -16
- package/chat-MKIW4FPP.js.map +1 -0
- package/chunk-2SJTFDC2.js +189 -0
- package/chunk-2SJTFDC2.js.map +1 -0
- package/chunk-4FTIKZKP.js +64 -0
- package/chunk-4FTIKZKP.js.map +1 -0
- package/chunk-7UZXNER2.js +568 -0
- package/chunk-7UZXNER2.js.map +1 -0
- package/chunk-A6ZRMNM3.js +102 -0
- package/chunk-A6ZRMNM3.js.map +1 -0
- package/{chunk-QC63TUJC.js → chunk-C62A6LD6.js} +2 -2
- package/chunk-CCTF3YVW.js +52 -0
- package/chunk-CCTF3YVW.js.map +1 -0
- package/chunk-CD2BLKGC.js +188 -0
- package/chunk-CD2BLKGC.js.map +1 -0
- package/chunk-CEJGHPF3.js +55 -0
- package/chunk-CEJGHPF3.js.map +1 -0
- package/chunk-DUA6CF7E.js +2053 -0
- package/chunk-DUA6CF7E.js.map +1 -0
- package/chunk-E2TQAKNL.js +1300 -0
- package/chunk-E2TQAKNL.js.map +1 -0
- package/{chunk-5ZZI2LSO.js → chunk-GHKWW4NC.js} +5 -5
- package/chunk-GV3PG6CZ.js +114 -0
- package/chunk-GV3PG6CZ.js.map +1 -0
- package/chunk-GY7D76EZ.js +81 -0
- package/chunk-GY7D76EZ.js.map +1 -0
- package/chunk-HHHHZMTA.js +434 -0
- package/chunk-HHHHZMTA.js.map +1 -0
- package/chunk-HZYOJTEE.js +1275 -0
- package/chunk-HZYOJTEE.js.map +1 -0
- package/chunk-J3ZRXVI6.js +740 -0
- package/chunk-J3ZRXVI6.js.map +1 -0
- package/chunk-JJWFO27K.js +31 -0
- package/chunk-JJWFO27K.js.map +1 -0
- package/chunk-JV6LM2YC.js +39 -0
- package/chunk-JV6LM2YC.js.map +1 -0
- package/chunk-KER77KJB.js +105 -0
- package/chunk-KER77KJB.js.map +1 -0
- package/{chunk-V5ZVB7RJ.js → chunk-KKO2XGLQ.js} +1 -6
- package/chunk-KKO2XGLQ.js.map +1 -0
- package/chunk-LIYPTQAO.js +198 -0
- package/chunk-LIYPTQAO.js.map +1 -0
- package/chunk-LYLDVUHT.js +131 -0
- package/chunk-LYLDVUHT.js.map +1 -0
- package/chunk-PFWBO2VK.js +801 -0
- package/chunk-PFWBO2VK.js.map +1 -0
- package/chunk-RTCRU35A.js +194 -0
- package/chunk-RTCRU35A.js.map +1 -0
- package/{chunk-F2AM4RWA.js → chunk-RTEEWZUT.js} +2 -2
- package/{chunk-F2AM4RWA.js.map → chunk-RTEEWZUT.js.map} +1 -1
- package/{chunk-BRV4D3P2.js → chunk-RUKMHBNQ.js} +2 -2
- package/chunk-SA4DYSBR.js +31 -0
- package/chunk-SA4DYSBR.js.map +1 -0
- package/chunk-SJPOFQJU.js +792 -0
- package/chunk-SJPOFQJU.js.map +1 -0
- package/{chunk-V7A6ZFHR.js → chunk-SMPSKBAP.js} +25 -774
- package/chunk-SMPSKBAP.js.map +1 -0
- package/{chunk-E53W6UVQ.js → chunk-T2X2EGV2.js} +4 -4
- package/chunk-T2X2EGV2.js.map +1 -0
- package/chunk-U2GQH6AD.js +309 -0
- package/chunk-U2GQH6AD.js.map +1 -0
- package/chunk-U6A2RPHO.js +66 -0
- package/chunk-U6A2RPHO.js.map +1 -0
- package/chunk-UIXUGVZB.js +362 -0
- package/chunk-UIXUGVZB.js.map +1 -0
- package/chunk-XRZKJACM.js +49 -0
- package/chunk-XRZKJACM.js.map +1 -0
- package/chunk-YDS3X7KB.js +202 -0
- package/chunk-YDS3X7KB.js.map +1 -0
- package/{chunk-A6TMOGPR.js → chunk-ZKNJW4K6.js} +1412 -334
- package/chunk-ZKNJW4K6.js.map +1 -0
- package/chunk-ZXSCBS77.js +90 -0
- package/chunk-ZXSCBS77.js.map +1 -0
- package/{computer-use-RRD7BCCK.js → computer-use-6AEVW47F.js} +9 -7
- package/computer-use-6AEVW47F.js.map +1 -0
- package/{connector-XX7UU6XE.js → connector-XDQ6JEBU.js} +25 -13
- package/connector-XDQ6JEBU.js.map +1 -0
- package/{credit-GDNNAQRO.js → credit-JPQA5XPA.js} +8 -10
- package/credit-JPQA5XPA.js.map +1 -0
- package/{developer-support-IISP5UBI.js → developer-support-V7NZOU2P.js} +27 -7
- package/developer-support-V7NZOU2P.js.map +1 -0
- package/{doctor-IZM2TJOH.js → doctor-FJO24TG3.js} +13 -11
- package/doctor-FJO24TG3.js.map +1 -0
- package/{feishu-XB7SQBSI.js → feishu-PNOAM33Q.js} +99 -9
- package/feishu-PNOAM33Q.js.map +1 -0
- package/{finance-OGWHKQLU.js → finance-55OJ6GYP.js} +49 -9
- package/finance-55OJ6GYP.js.map +1 -0
- package/{generate-AA2PVOYQ.js → generate-XUKBK523.js} +26 -21
- package/generate-XUKBK523.js.map +1 -0
- package/{github-VJVIBTVF.js → github-V4MD2PMM.js} +83 -8
- package/github-V4MD2PMM.js.map +1 -0
- package/{goal-7SYVHDTK.js → goal-FS5FJKVU.js} +69 -13
- package/goal-FS5FJKVU.js.map +1 -0
- package/{host-UVQMIOBA.js → host-GITTJ6PR.js} +124 -10
- package/host-GITTJ6PR.js.map +1 -0
- package/{logs-PIS4X24E.js → logs-EEUIGYUD.js} +51 -11
- package/logs-EEUIGYUD.js.map +1 -0
- package/{mail-L33OSQ2R.js → mail-G4SAJSBD.js} +39 -8
- package/mail-G4SAJSBD.js.map +1 -0
- package/{maps-D5XTXU5U.js → maps-7ANNU3BX.js} +65 -11
- package/maps-7ANNU3BX.js.map +1 -0
- package/{model-ZFMRECDM.js → model-DSPDCJLB.js} +6 -6
- package/model-DSPDCJLB.js.map +1 -0
- package/{model-provider-EZZ2DRYZ.js → model-provider-RZQ45PNG.js} +6 -6
- package/model-provider-RZQ45PNG.js.map +1 -0
- package/package.json +1 -1
- package/{people-search-PFTIO2QS.js → people-search-I7PUMF5M.js} +22 -6
- package/people-search-I7PUMF5M.js.map +1 -0
- package/{phone-6SG5ZUNL.js → phone-SSAPGMTW.js} +90 -9
- package/phone-SSAPGMTW.js.map +1 -0
- package/{recognize-LLU6J3SW.js → recognize-D7VORZBN.js} +27 -9
- package/recognize-D7VORZBN.js.map +1 -0
- package/{resource-FGUSXS4G.js → resource-76IV3TMW.js} +21 -7
- package/resource-76IV3TMW.js.map +1 -0
- package/{scrape-BAUZ2YFD.js → scrape-JBDLNTLB.js} +22 -6
- package/scrape-JBDLNTLB.js.map +1 -0
- package/{search-DLO5RXRM.js → search-UNZNUTZX.js} +29 -9
- package/search-UNZNUTZX.js.map +1 -0
- package/{slack-CVATPKP3.js → slack-AAH6GG2W.js} +103 -11
- package/slack-AAH6GG2W.js.map +1 -0
- package/{teams-ZZYO6YIK.js → teams-6OPXE4TX.js} +90 -9
- package/teams-6OPXE4TX.js.map +1 -0
- package/{telegram-VY7T4YAR.js → telegram-RRZG73RT.js} +101 -10
- package/telegram-RRZG73RT.js.map +1 -0
- package/{upgrade-GFA4ZUU4.js → upgrade-I5IL4UQL.js} +3 -4
- package/upgrade-I5IL4UQL.js.map +1 -0
- package/{video-STFG7BET.js → video-HV44W4X7.js} +5 -4
- package/video-HV44W4X7.js.map +1 -0
- package/{weather-ISJEHJWR.js → weather-EQ7CSADB.js} +70 -16
- package/weather-EQ7CSADB.js.map +1 -0
- package/{web-YN4CVHK7.js → web-6LIMWEOZ.js} +5 -5
- package/web-6LIMWEOZ.js.map +1 -0
- package/{web-search-PC7IECND.js → web-search-AT7WONZN.js} +22 -6
- package/web-search-AT7WONZN.js.map +1 -0
- package/{whoami-KXFXZGM6.js → whoami-RKTLLSI4.js} +16 -7
- package/whoami-RKTLLSI4.js.map +1 -0
- package/{workflow-O7YZHB7A.js → workflow-ZH32P622.js} +135 -39
- package/workflow-ZH32P622.js.map +1 -0
- package/zero.js +40 -40
- package/agent-HUDTEGLK.js.map +0 -1
- package/banking-BMZONEXP.js.map +0 -1
- package/browser-LQP445CU.js.map +0 -1
- package/chat-UF7QAWUT.js.map +0 -1
- package/chunk-2W73DZDW.js +0 -32
- package/chunk-2W73DZDW.js.map +0 -1
- package/chunk-6PN6QGIM.js +0 -11405
- package/chunk-6PN6QGIM.js.map +0 -1
- package/chunk-A6TMOGPR.js.map +0 -1
- package/chunk-ANOLYIPL.js +0 -10
- package/chunk-ANOLYIPL.js.map +0 -1
- package/chunk-E53W6UVQ.js.map +0 -1
- package/chunk-V5ZVB7RJ.js.map +0 -1
- package/chunk-V7A6ZFHR.js.map +0 -1
- package/computer-use-RRD7BCCK.js.map +0 -1
- package/connector-XX7UU6XE.js.map +0 -1
- package/credit-GDNNAQRO.js.map +0 -1
- package/developer-support-IISP5UBI.js.map +0 -1
- package/doctor-IZM2TJOH.js.map +0 -1
- package/feishu-XB7SQBSI.js.map +0 -1
- package/finance-OGWHKQLU.js.map +0 -1
- package/generate-AA2PVOYQ.js.map +0 -1
- package/github-VJVIBTVF.js.map +0 -1
- package/goal-7SYVHDTK.js.map +0 -1
- package/host-UVQMIOBA.js.map +0 -1
- package/logs-PIS4X24E.js.map +0 -1
- package/mail-L33OSQ2R.js.map +0 -1
- package/maps-D5XTXU5U.js.map +0 -1
- package/model-ZFMRECDM.js.map +0 -1
- package/model-provider-EZZ2DRYZ.js.map +0 -1
- package/people-search-PFTIO2QS.js.map +0 -1
- package/phone-6SG5ZUNL.js.map +0 -1
- package/recognize-LLU6J3SW.js.map +0 -1
- package/resource-FGUSXS4G.js.map +0 -1
- package/scrape-BAUZ2YFD.js.map +0 -1
- package/search-DLO5RXRM.js.map +0 -1
- package/slack-CVATPKP3.js.map +0 -1
- package/teams-ZZYO6YIK.js.map +0 -1
- package/telegram-VY7T4YAR.js.map +0 -1
- package/upgrade-GFA4ZUU4.js.map +0 -1
- package/video-STFG7BET.js.map +0 -1
- package/weather-ISJEHJWR.js.map +0 -1
- package/web-YN4CVHK7.js.map +0 -1
- package/web-search-PC7IECND.js.map +0 -1
- package/whoami-KXFXZGM6.js.map +0 -1
- package/workflow-O7YZHB7A.js.map +0 -1
- /package/{chunk-QC63TUJC.js.map → chunk-C62A6LD6.js.map} +0 -0
- /package/{chunk-5ZZI2LSO.js.map → chunk-GHKWW4NC.js.map} +0 -0
- /package/{chunk-BRV4D3P2.js.map → chunk-RUKMHBNQ.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
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/with-error-handler\";\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/domains/zero-connectors\";\nimport { withErrorHandler } from \"../../../lib/command/with-error-handler\";\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/domains/zero-connectors\";\nimport { withErrorHandler } from \"../../../lib/command/with-error-handler\";\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/domains/zero-connectors\";\nimport { withErrorHandler } from \"../../../lib/command/with-error-handler\";\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/domains/zero-connectors\";\nimport { withErrorHandler } from \"../../../lib/command/with-error-handler\";\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} from \"../../../../lib/api/domains/zero-agents\";\nimport {\n getZeroCustomConnector,\n listZeroCustomConnectors,\n} from \"../../../../lib/api/domains/zero-connectors\";\nimport { withErrorHandler } from \"../../../../lib/command/with-error-handler\";\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 getZeroAgent,\n} from \"../../../../lib/api/domains/zero-agents\";\nimport {\n createZeroCustomConnector,\n setZeroCustomConnectorValues,\n startZeroCustomConnectorOAuth2,\n} from \"../../../../lib/api/domains/zero-connectors\";\nimport { decodeZeroTokenPayload } from \"../../../../lib/api/zero-token\";\nimport { withErrorHandler } from \"../../../../lib/command/with-error-handler\";\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/with-error-handler\";\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 { ApiRequestError } from \"../../../lib/api/core/client-factory\";\nimport { createBrowserAuthorizationRequest } from \"../../../lib/api/domains/zero-browser\";\nimport { createComputerUseAuthorizationRequest } from \"../../../lib/api/domains/zero-computer-use\";\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;AACpC,IAAM,0BAA0B;AAChC,IAAM,2BAA2B;AACjC,IAAM,sCAAsC,GAAG,wBAAwB;AAQhE,SAAS,8BACd,QACS;AACT,SACE,OAAO,kBAAkB,+BACzB,OAAO,eAAe,2BACtB,OAAO,SAAS,4BAChB,OAAO,MAAM,WAAW,mCAAmC,MAAM;AAErE;AAEO,SAAS,qCAA2C;AACzD,UAAQ,IAAI,+DAA+D;AAC3E,UAAQ;AAAA,IACN;AAAA,EACF;AACA,UAAQ;AAAA,IACN;AAAA,EACF;AACA,UAAQ;AAAA,IACN;AAAA,EACF;AACF;;;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,QACA,YAAY,KAAK;AAAA,MACnB,CAAC,GACD;AACA,YAAI,KAAK,mBAAmB,QAAW;AACrC,gBAAM,IAAI;AAAA,YACR;AAAA,UACF;AAAA,QACF;AACA,cAAM,yCAAyC;AAC/C;AAAA,MACF;AAEA,YAAM,UAAU,KAAK,SAAS,QAAQ,IAAI;AAC1C,UAAI,KAAK,QAAQ,QAAW;AAC1B,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAEA,YAAM,oBAAoB,mCAAmC;AAAA,QAC3D,KAAK,KAAK;AAAA,QACV,QAAQ,KAAK;AAAA,QACb;AAAA,MACF,CAAC;AACD,YAAM,aAAa,MAAM,2BAA2B,iBAAiB;AACrE,YAAM,SAAS;AAAA,QACb;AAAA,QACA;AAAA,MACF;AACA,YAAM,SAAS,8BAA8B;AAAA,QAC3C;AAAA,QACA,YAAY,KAAK;AAAA,QACjB,QAAQ,kBAAkB;AAAA,QAC1B,KAAK,kBAAkB;AAAA,MACzB,CAAC;AACD,8BAAwB;AAAA,QACtB;AAAA,QACA,YAAY,KAAK;AAAA,QACjB,QAAQ,kBAAkB;AAAA,QAC1B,KAAK,kBAAkB;AAAA,MACzB,CAAC;AAED,YAAM;AAAA,QACJ,OAAO,UAAU;AAAA,QACjB,OAAO,UAAU;AAAA,QACjB,KAAK;AAAA,QACL;AAAA,QACA,KAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACF;;;AX9ZK,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"]}
|
|
@@ -2,26 +2,24 @@
|
|
|
2
2
|
import { createRequire as __createRequire } from "node:module";
|
|
3
3
|
const require = __createRequire(import.meta.url);
|
|
4
4
|
import {
|
|
5
|
+
createZeroCreditCheckout,
|
|
5
6
|
currentPlanAllowsVideo,
|
|
6
7
|
currentPlanCanBuyCredits,
|
|
7
|
-
currentTokenCanReadBilling
|
|
8
|
-
} from "./chunk-2W73DZDW.js";
|
|
9
|
-
import {
|
|
10
|
-
createZeroCreditCheckout,
|
|
8
|
+
currentTokenCanReadBilling,
|
|
11
9
|
getZeroBillingStatus
|
|
12
|
-
} from "./chunk-
|
|
13
|
-
import "./chunk-
|
|
10
|
+
} from "./chunk-4FTIKZKP.js";
|
|
11
|
+
import "./chunk-7UZXNER2.js";
|
|
12
|
+
import "./chunk-JV6LM2YC.js";
|
|
14
13
|
import {
|
|
15
14
|
planUpgradeUrl
|
|
16
15
|
} from "./chunk-J45P5ALH.js";
|
|
17
16
|
import {
|
|
18
17
|
getPlatformOrigin
|
|
19
|
-
} from "./chunk-
|
|
20
|
-
import "./chunk-ANOLYIPL.js";
|
|
18
|
+
} from "./chunk-RUKMHBNQ.js";
|
|
21
19
|
import {
|
|
22
20
|
source_default,
|
|
23
21
|
withErrorHandler
|
|
24
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-GHKWW4NC.js";
|
|
25
23
|
import {
|
|
26
24
|
decodeZeroTokenPayload
|
|
27
25
|
} from "./chunk-32FE3MDA.js";
|
|
@@ -153,4 +151,4 @@ var zeroCreditCommand = new Command().name("credit").description("View credit ba
|
|
|
153
151
|
export {
|
|
154
152
|
zeroCreditCommand
|
|
155
153
|
};
|
|
156
|
-
//# sourceMappingURL=credit-
|
|
154
|
+
//# sourceMappingURL=credit-JPQA5XPA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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 {\n createZeroCreditCheckout,\n getZeroBillingStatus,\n} from \"../../lib/api/domains/zero-billing\";\nimport { withErrorHandler } from \"../../lib/command/with-error-handler\";\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;AAmBA,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,UAAU,GAAG;AACzD,UAAM,IAAI,MAAM,OAAO;AAAA,EACzB;AACF;AAQA,SAAS,0BAA0B,SAMrB;AACZ,MACE,QAAQ,iBAAiB,SACxB,QAAQ,0BAA0B,UACjC,QAAQ,uBAAuB,SACjC;AACA,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,MAAI,QAAQ,iBAAiB,MAAM;AACjC,WAAO;AAAA,EACT;AACA,MACE,QAAQ,0BAA0B,UAClC,QAAQ,uBAAuB,QAC/B;AACA,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AAAA,IACL,SAAS;AAAA,IACT,WAAW,QAAQ;AAAA,IACnB,QAAQ,QAAQ;AAAA,EAClB;AACF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,QACJ;AAAA,MACF;AAAA,IACF;AACA,YAAQ,IAAI,eAAM,KAAK,oBAAoB,CAAC;AAC5C,YAAQ,IAAI,eAAe,MAAM,CAAC;AAClC;AAAA,EACF;AAEA,QAAM,SAAS,MAAM,yBAAyB;AAAA,IAC5C;AAAA,IACA,YAAY,GAAG,MAAM;AAAA,IACrB,WAAW,GAAG,MAAM;AAAA,IACpB,GAAI,eAAe,EAAE,aAAa,IAAI,CAAC;AAAA,EACzC,CAAC;AACD,UAAQ,IAAI,eAAM,KAAK,uBAAuB,CAAC;AAC/C,UAAQ,IAAI,OAAO,GAAG;AACxB;AAEO,IAAM,oBAAoB,IAAI,QAAQ,EAC1C,KAAK,QAAQ,EACb,YAAY,8DAA8D,EAC1E,SAAS,aAAa,4BAA4B,YAAY,EAC9D;AAAA,EACC,IAAI,OAAO,mBAAmB,qCAAqC;AACrE,EACC;AAAA,EACC;AAAA,EACA;AAAA,EACA;AACF,EACC;AAAA,EACC;AAAA,EACA;AAAA,EACA;AACF,EACC;AAAA,EACC;AAAA,IACE,OAAO,SAA6B,YAA2B;AAC7D,UAAI,YAAY,QAAW;AACzB,cAAM,iBAAiB,OAAO;AAC9B;AAAA,MACF;AACA,YAAM,WAAW,SAAS,OAAO;AAAA,IACnC;AAAA,EACF;AACF;","names":[]}
|
|
@@ -2,14 +2,15 @@
|
|
|
2
2
|
import { createRequire as __createRequire } from "node:module";
|
|
3
3
|
const require = __createRequire(import.meta.url);
|
|
4
4
|
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
import "./chunk-V7A6ZFHR.js";
|
|
9
|
-
import "./chunk-ANOLYIPL.js";
|
|
5
|
+
zeroDeveloperSupportContract
|
|
6
|
+
} from "./chunk-XRZKJACM.js";
|
|
7
|
+
import "./chunk-JV6LM2YC.js";
|
|
10
8
|
import {
|
|
9
|
+
getClientConfig,
|
|
10
|
+
handleError,
|
|
11
|
+
initClient,
|
|
11
12
|
withErrorHandler
|
|
12
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-GHKWW4NC.js";
|
|
13
14
|
import "./chunk-32FE3MDA.js";
|
|
14
15
|
import {
|
|
15
16
|
Command
|
|
@@ -20,6 +21,25 @@ import {
|
|
|
20
21
|
|
|
21
22
|
// src/commands/zero/developer-support.ts
|
|
22
23
|
init_esm_shims();
|
|
24
|
+
|
|
25
|
+
// src/lib/api/domains/zero-developer-support.ts
|
|
26
|
+
init_esm_shims();
|
|
27
|
+
async function requestDeveloperSupportConsent(body) {
|
|
28
|
+
const config = await getClientConfig();
|
|
29
|
+
const client = initClient(zeroDeveloperSupportContract, config);
|
|
30
|
+
const result = await client.submit({ body, headers: {} });
|
|
31
|
+
if (result.status === 200) return result.body;
|
|
32
|
+
handleError(result, "Failed to request developer support consent");
|
|
33
|
+
}
|
|
34
|
+
async function submitDeveloperSupport(body) {
|
|
35
|
+
const config = await getClientConfig();
|
|
36
|
+
const client = initClient(zeroDeveloperSupportContract, config);
|
|
37
|
+
const result = await client.submit({ body, headers: {} });
|
|
38
|
+
if (result.status === 200) return result.body;
|
|
39
|
+
handleError(result, "Failed to submit developer support request");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/commands/zero/developer-support.ts
|
|
23
43
|
var zeroDeveloperSupportCommand = new Command().name("developer-support").description("Submit a diagnostic report to the dev team").requiredOption("--title <text>", "Issue title").requiredOption("--description <text>", "Diagnostic description").option("--consent-code <code>", "User-provided verification code").addHelpText(
|
|
24
44
|
"after",
|
|
25
45
|
`
|
|
@@ -61,4 +81,4 @@ Notes:
|
|
|
61
81
|
export {
|
|
62
82
|
zeroDeveloperSupportCommand
|
|
63
83
|
};
|
|
64
|
-
//# sourceMappingURL=developer-support-
|
|
84
|
+
//# sourceMappingURL=developer-support-V7NZOU2P.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/zero/developer-support.ts","../src/lib/api/domains/zero-developer-support.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { withErrorHandler } from \"../../lib/command/with-error-handler\";\nimport {\n requestDeveloperSupportConsent,\n submitDeveloperSupport,\n} from \"../../lib/api/domains/zero-developer-support\";\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","import { initClient } from \"@vm0/api-contracts/contracts/trpc-contract\";\nimport { zeroDeveloperSupportContract } from \"@vm0/api-contracts/contracts/zero-developer-support\";\nimport { getClientConfig, handleError } from \"../core/client-factory\";\n\nexport async function requestDeveloperSupportConsent(body: {\n title: string;\n description: string;\n}): Promise<{ consentCode: string }> {\n const config = await getClientConfig();\n const client = initClient(zeroDeveloperSupportContract, config);\n const result = await client.submit({ body, headers: {} });\n if (result.status === 200) return result.body as { consentCode: string };\n handleError(result, \"Failed to request developer support consent\");\n}\n\nexport async function submitDeveloperSupport(body: {\n title: string;\n description: string;\n consentCode: string;\n}): Promise<{ reference: string }> {\n const config = await getClientConfig();\n const client = initClient(zeroDeveloperSupportContract, config);\n const result = await client.submit({ body, headers: {} });\n if (result.status === 200) return result.body as { reference: string };\n handleError(result, \"Failed to submit developer support request\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;;;ACAA;AAIA,eAAsB,+BAA+B,MAGhB;AACnC,QAAM,SAAS,MAAM,gBAAgB;AACrC,QAAM,SAAS,WAAW,8BAA8B,MAAM;AAC9D,QAAM,SAAS,MAAM,OAAO,OAAO,EAAE,MAAM,SAAS,CAAC,EAAE,CAAC;AACxD,MAAI,OAAO,WAAW,IAAK,QAAO,OAAO;AACzC,cAAY,QAAQ,6CAA6C;AACnE;AAEA,eAAsB,uBAAuB,MAIV;AACjC,QAAM,SAAS,MAAM,gBAAgB;AACrC,QAAM,SAAS,WAAW,8BAA8B,MAAM;AAC9D,QAAM,SAAS,MAAM,OAAO,OAAO,EAAE,MAAM,SAAS,CAAC,EAAE,CAAC;AACxD,MAAI,OAAO,WAAW,IAAK,QAAO,OAAO;AACzC,cAAY,QAAQ,4CAA4C;AAClE;;;ADlBO,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":[]}
|
|
@@ -2,25 +2,27 @@
|
|
|
2
2
|
import { createRequire as __createRequire } from "node:module";
|
|
3
3
|
const require = __createRequire(import.meta.url);
|
|
4
4
|
import {
|
|
5
|
-
currentPlanAllowsVideo,
|
|
6
|
-
currentPlanCanBuyCredits
|
|
7
|
-
} from "./chunk-2W73DZDW.js";
|
|
8
|
-
import {
|
|
9
|
-
getZeroBillingStatus,
|
|
10
5
|
getZeroOrg
|
|
11
|
-
} from "./chunk-
|
|
12
|
-
import "./chunk-
|
|
6
|
+
} from "./chunk-JJWFO27K.js";
|
|
7
|
+
import "./chunk-ZXSCBS77.js";
|
|
8
|
+
import "./chunk-A6ZRMNM3.js";
|
|
9
|
+
import {
|
|
10
|
+
currentPlanAllowsVideo,
|
|
11
|
+
currentPlanCanBuyCredits,
|
|
12
|
+
getZeroBillingStatus
|
|
13
|
+
} from "./chunk-4FTIKZKP.js";
|
|
14
|
+
import "./chunk-7UZXNER2.js";
|
|
15
|
+
import "./chunk-JV6LM2YC.js";
|
|
13
16
|
import {
|
|
14
17
|
planUpgradeUrl
|
|
15
18
|
} from "./chunk-J45P5ALH.js";
|
|
16
19
|
import {
|
|
17
20
|
getPlatformOrigin
|
|
18
|
-
} from "./chunk-
|
|
19
|
-
import "./chunk-ANOLYIPL.js";
|
|
21
|
+
} from "./chunk-RUKMHBNQ.js";
|
|
20
22
|
import {
|
|
21
23
|
source_default,
|
|
22
24
|
withErrorHandler
|
|
23
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-GHKWW4NC.js";
|
|
24
26
|
import "./chunk-32FE3MDA.js";
|
|
25
27
|
import {
|
|
26
28
|
Command
|
|
@@ -99,4 +101,4 @@ Notes:
|
|
|
99
101
|
export {
|
|
100
102
|
zeroDoctorCommand
|
|
101
103
|
};
|
|
102
|
-
//# sourceMappingURL=doctor-
|
|
104
|
+
//# sourceMappingURL=doctor-FJO24TG3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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 } from \"../../../lib/api/domains/zero-billing\";\nimport { getZeroOrg } from \"../../../lib/api/domains/zero-orgs\";\nimport { withErrorHandler } from \"../../../lib/command/with-error-handler\";\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;AAaO,IAAM,gBAAgB,IAAI,QAAQ,EACtC,KAAK,QAAQ,EACb,YAAY,0DAA0D,EACtE;AAAA,EACC,iBAAiB,YAAY;AAC3B,UAAM,CAAC,KAAK,SAAS,cAAc,IAAI,MAAM,QAAQ,IAAI;AAAA,MACvD,WAAW;AAAA,MACX,qBAAqB;AAAA,MACrB,kBAAkB;AAAA,IACpB,CAAC;AACD,UAAM,oBAAoB,yBAAyB,OAAO;AAE1D,YAAQ,IAAI,eAAM,KAAK,qBAAqB,CAAC;AAC7C,YAAQ,IAAI,gBAAgB,eAAM,MAAM,IAAI,IAAI,CAAC,EAAE;AACnD,YAAQ,IAAI,WAAW,eAAM,KAAK,QAAQ,IAAI,CAAC,EAAE;AACjD,YAAQ;AAAA,MACN,wBAAwB,eAAM,KAAK,QAAQ,QAAQ,eAAe,CAAC,CAAC;AAAA,IACtE;AACA,YAAQ;AAAA,MACN,gCACE,oBAAoB,eAAM,MAAM,KAAK,IAAI,eAAM,OAAO,IAAI,CAC5D;AAAA,IACF;AACA,YAAQ;AAAA,MACN,gCACE,uBAAuB,OAAO,IAC1B,eAAM,MAAM,WAAW,IACvB,eAAM,OAAO,aAAa,CAChC;AAAA,IACF;AACA,YAAQ;AAAA,MACN,oBACE,QAAQ,aAAa,UAAU,eAAM,MAAM,SAAS,IAAI,UAC1D;AAAA,IACF;AACA,QAAI,QAAQ,aAAa,SAAS;AAChC,cAAQ;AAAA,QACN,kBAAkB,QAAQ,aAAa,WAAW,eAAe,KAAK,SAAS;AAAA,MACjF;AACA,cAAQ;AAAA,QACN,eAAe,QAAQ,aAAa,QAAQ,eAAe,KAAK,SAAS;AAAA,MAC3E;AAAA,IACF;AAEA,QAAI,CAAC,mBAAmB;AACtB,cAAQ;AAAA,QACN;AAAA,MACF;AACA,cAAQ,IAAI,eAAe,cAAc,CAAC;AAC1C;AAAA,IACF;AAEA,QAAI,QAAQ,SAAS,QAAQ;AAC3B,cAAQ;AAAA,QACN;AAAA,MACF;AAAA,IACF,OAAO;AACL,cAAQ;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACH;;;ADxEK,IAAM,oBAAoB,IAAI,QAAQ,EAC1C,KAAK,QAAQ,EACb,YAAY,qCAAqC,EACjD,WAAW,aAAa,EACxB;AAAA,EACC;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQF;","names":[]}
|
|
@@ -3,17 +3,22 @@ import { createRequire as __createRequire } from "node:module";
|
|
|
3
3
|
const require = __createRequire(import.meta.url);
|
|
4
4
|
import {
|
|
5
5
|
FEISHU_FILE_UPLOAD_MAX_BYTES,
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
import "./chunk-V7A6ZFHR.js";
|
|
12
|
-
import "./chunk-ANOLYIPL.js";
|
|
6
|
+
integrationsFeishuMessageContract,
|
|
7
|
+
integrationsFeishuUploadCompleteContract,
|
|
8
|
+
integrationsFeishuUploadInitContract
|
|
9
|
+
} from "./chunk-PFWBO2VK.js";
|
|
10
|
+
import "./chunk-JV6LM2YC.js";
|
|
13
11
|
import {
|
|
12
|
+
ApiRequestError,
|
|
13
|
+
getActiveToken,
|
|
14
|
+
getBaseUrl,
|
|
15
|
+
getClientConfig,
|
|
16
|
+
handleError,
|
|
17
|
+
headersWithCliClientHeaders,
|
|
18
|
+
initClient,
|
|
14
19
|
source_default,
|
|
15
20
|
withErrorHandler
|
|
16
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-GHKWW4NC.js";
|
|
17
22
|
import "./chunk-32FE3MDA.js";
|
|
18
23
|
import {
|
|
19
24
|
Command
|
|
@@ -29,6 +34,91 @@ init_esm_shims();
|
|
|
29
34
|
init_esm_shims();
|
|
30
35
|
import { tmpdir } from "os";
|
|
31
36
|
import { basename, join } from "path";
|
|
37
|
+
|
|
38
|
+
// src/lib/api/domains/integrations-feishu.ts
|
|
39
|
+
init_esm_shims();
|
|
40
|
+
import { createWriteStream } from "fs";
|
|
41
|
+
import { Readable } from "stream";
|
|
42
|
+
import { pipeline } from "stream/promises";
|
|
43
|
+
async function sendFeishuMessage(body) {
|
|
44
|
+
const config = await getClientConfig();
|
|
45
|
+
const client = initClient(integrationsFeishuMessageContract, config);
|
|
46
|
+
const result = await client.sendMessage({ body, headers: {} });
|
|
47
|
+
if (result.status === 200) {
|
|
48
|
+
return result.body;
|
|
49
|
+
}
|
|
50
|
+
handleError(result, "Failed to send Feishu message");
|
|
51
|
+
}
|
|
52
|
+
async function initFeishuFileUpload(body) {
|
|
53
|
+
const config = await getClientConfig();
|
|
54
|
+
const client = initClient(integrationsFeishuUploadInitContract, config);
|
|
55
|
+
const result = await client.init({ body, headers: {} });
|
|
56
|
+
if (result.status === 200) {
|
|
57
|
+
return result.body;
|
|
58
|
+
}
|
|
59
|
+
handleError(result, "Failed to initialize Feishu file upload");
|
|
60
|
+
}
|
|
61
|
+
async function completeFeishuFileUpload(body) {
|
|
62
|
+
const config = await getClientConfig();
|
|
63
|
+
const client = initClient(integrationsFeishuUploadCompleteContract, config);
|
|
64
|
+
const result = await client.complete({ body, headers: {} });
|
|
65
|
+
if (result.status === 200) {
|
|
66
|
+
return result.body;
|
|
67
|
+
}
|
|
68
|
+
handleError(result, "Failed to complete Feishu file upload");
|
|
69
|
+
}
|
|
70
|
+
async function downloadFeishuFile(messageId, fileKey, resourceType, installationId, outPath) {
|
|
71
|
+
const baseUrl = await getBaseUrl();
|
|
72
|
+
const token = await getActiveToken();
|
|
73
|
+
if (!token) {
|
|
74
|
+
throw new ApiRequestError("Not authenticated", "UNAUTHORIZED", 401);
|
|
75
|
+
}
|
|
76
|
+
const url = new URL("/api/zero/integrations/feishu/download-file", baseUrl);
|
|
77
|
+
url.searchParams.set("message_id", messageId);
|
|
78
|
+
url.searchParams.set("file_key", fileKey);
|
|
79
|
+
url.searchParams.set("type", resourceType);
|
|
80
|
+
if (installationId) {
|
|
81
|
+
url.searchParams.set("installation_id", installationId);
|
|
82
|
+
}
|
|
83
|
+
const headers = {
|
|
84
|
+
Authorization: `Bearer ${token}`
|
|
85
|
+
};
|
|
86
|
+
const response = await fetch(url, {
|
|
87
|
+
headers: headersWithCliClientHeaders(headers)
|
|
88
|
+
});
|
|
89
|
+
if (!response.ok) {
|
|
90
|
+
let message = `Failed to download Feishu file (HTTP ${response.status})`;
|
|
91
|
+
let code = "UNKNOWN";
|
|
92
|
+
try {
|
|
93
|
+
const body = await response.json();
|
|
94
|
+
if (body.error?.message) {
|
|
95
|
+
message = body.error.message;
|
|
96
|
+
}
|
|
97
|
+
if (body.error?.code) {
|
|
98
|
+
code = body.error.code;
|
|
99
|
+
}
|
|
100
|
+
} catch {
|
|
101
|
+
}
|
|
102
|
+
throw new ApiRequestError(message, code, response.status);
|
|
103
|
+
}
|
|
104
|
+
if (!response.body) {
|
|
105
|
+
throw new ApiRequestError(
|
|
106
|
+
"Feishu download response has no body",
|
|
107
|
+
"EMPTY_BODY",
|
|
108
|
+
502
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
const mimetype = response.headers.get("x-file-mimetype") ?? response.headers.get("content-type") ?? "application/octet-stream";
|
|
112
|
+
await pipeline(
|
|
113
|
+
Readable.fromWeb(response.body),
|
|
114
|
+
createWriteStream(outPath)
|
|
115
|
+
);
|
|
116
|
+
const contentLength = response.headers.get("content-length");
|
|
117
|
+
const size = contentLength ? Number(contentLength) : 0;
|
|
118
|
+
return { path: outPath, mimetype, size };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// src/commands/zero/feishu/download-file.ts
|
|
32
122
|
function defaultOutPath(fileKey) {
|
|
33
123
|
return join(tmpdir(), `feishu-${basename(fileKey).slice(0, 80)}`);
|
|
34
124
|
}
|
|
@@ -278,4 +368,4 @@ Examples:
|
|
|
278
368
|
export {
|
|
279
369
|
zeroFeishuCommand
|
|
280
370
|
};
|
|
281
|
-
//# sourceMappingURL=feishu-
|
|
371
|
+
//# sourceMappingURL=feishu-PNOAM33Q.js.map
|