@opencode-ai/cli-linux-x64
Advanced tools
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/fromIni.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProfileData.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveAssumeRoleCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveCredentialSource.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveLoginCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProcessCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveSsoCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveStaticCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveWebIdentityCredentials.js"], | ||
| "sourcesContent": [ | ||
| "import { getProfileName, parseKnownFiles } from \"@smithy/core/config\";\nimport { resolveProfileData } from \"./resolveProfileData\";\nexport const fromIni = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-ini - fromIni\");\n const profiles = await parseKnownFiles(init);\n return resolveProfileData(getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n }), profiles, init, callerClientConfig);\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { isAssumeRoleProfile, resolveAssumeRoleCredentials } from \"./resolveAssumeRoleCredentials\";\nimport { isLoginProfile, resolveLoginCredentials } from \"./resolveLoginCredentials\";\nimport { isProcessProfile, resolveProcessCredentials } from \"./resolveProcessCredentials\";\nimport { isSsoProfile, resolveSsoCredentials } from \"./resolveSsoCredentials\";\nimport { isStaticCredsProfile, resolveStaticCredentials } from \"./resolveStaticCredentials\";\nimport { isWebIdentityProfile, resolveWebIdentityCredentials } from \"./resolveWebIdentityCredentials\";\nexport const resolveProfileData = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => {\n const data = profiles[profileName];\n if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) {\n return resolveStaticCredentials(data, options);\n }\n if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) {\n return resolveAssumeRoleCredentials(profileName, profiles, options, callerClientConfig, visitedProfiles, resolveProfileData);\n }\n if (isStaticCredsProfile(data)) {\n return resolveStaticCredentials(data, options);\n }\n if (isWebIdentityProfile(data)) {\n return resolveWebIdentityCredentials(data, options, callerClientConfig);\n }\n if (isProcessProfile(data)) {\n return resolveProcessCredentials(options, profileName);\n }\n if (isSsoProfile(data)) {\n return await resolveSsoCredentials(profileName, data, options, callerClientConfig);\n }\n if (isLoginProfile(data)) {\n return resolveLoginCredentials(profileName, options, callerClientConfig);\n }\n throw new CredentialsProviderError(`Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, { logger: options.logger });\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError, getProfileName } from \"@smithy/core/config\";\nimport { resolveCredentialSource } from \"./resolveCredentialSource\";\nexport const isAssumeRoleProfile = (arg, { profile = \"default\", logger } = {}) => {\n return (Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.role_arn === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.role_session_name) > -1 &&\n [\"undefined\", \"string\"].indexOf(typeof arg.external_id) > -1 &&\n [\"undefined\", \"string\"].indexOf(typeof arg.mfa_serial) > -1 &&\n (isAssumeRoleWithSourceProfile(arg, { profile, logger }) || isCredentialSourceProfile(arg, { profile, logger })));\n};\nconst isAssumeRoleWithSourceProfile = (arg, { profile, logger }) => {\n const withSourceProfile = typeof arg.source_profile === \"string\" && typeof arg.credential_source === \"undefined\";\n if (withSourceProfile) {\n logger?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`);\n }\n return withSourceProfile;\n};\nconst isCredentialSourceProfile = (arg, { profile, logger }) => {\n const withProviderProfile = typeof arg.credential_source === \"string\" && typeof arg.source_profile === \"undefined\";\n if (withProviderProfile) {\n logger?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`);\n }\n return withProviderProfile;\n};\nexport const resolveAssumeRoleCredentials = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, resolveProfileData) => {\n options.logger?.debug(\"@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)\");\n const profileData = profiles[profileName];\n const { source_profile, region } = profileData;\n if (!options.roleAssumer) {\n const { getDefaultRoleAssumer } = await import(\"@aws-sdk/nested-clients/sts\");\n options.roleAssumer = getDefaultRoleAssumer({\n ...options.clientConfig,\n credentialProviderLogger: options.logger,\n parentClientConfig: {\n ...callerClientConfig,\n ...options?.parentClientConfig,\n region: region ?? options?.parentClientConfig?.region ?? callerClientConfig?.region,\n },\n }, options.clientPlugins);\n }\n if (source_profile && source_profile in visitedProfiles) {\n throw new CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile` +\n ` ${getProfileName(options)}. Profiles visited: ` +\n Object.keys(visitedProfiles).join(\", \"), { logger: options.logger });\n }\n options.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`);\n const sourceCredsProvider = source_profile\n ? resolveProfileData(source_profile, profiles, options, callerClientConfig, {\n ...visitedProfiles,\n [source_profile]: true,\n }, isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {}))\n : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))();\n if (isCredentialSourceWithoutRoleArn(profileData)) {\n return sourceCredsProvider.then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SOURCE_PROFILE\", \"o\"));\n }\n else {\n const params = {\n RoleArn: profileData.role_arn,\n RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`,\n ExternalId: profileData.external_id,\n DurationSeconds: parseInt(profileData.duration_seconds || \"3600\", 10),\n };\n const { mfa_serial } = profileData;\n if (mfa_serial) {\n if (!options.mfaCodeProvider) {\n throw new CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, { logger: options.logger, tryNextLink: false });\n }\n params.SerialNumber = mfa_serial;\n params.TokenCode = await options.mfaCodeProvider(mfa_serial);\n }\n const sourceCreds = await sourceCredsProvider;\n return options.roleAssumer(sourceCreds, params).then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SOURCE_PROFILE\", \"o\"));\n }\n};\nconst isCredentialSourceWithoutRoleArn = (section) => {\n return !section.role_arn && !!section.credential_source;\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { chain, CredentialsProviderError } from \"@smithy/core/config\";\nexport const resolveCredentialSource = (credentialSource, profileName, logger) => {\n const sourceProvidersMap = {\n EcsContainer: async (options) => {\n const { fromHttp } = await import(\"@aws-sdk/credential-provider-http\");\n const { fromContainerMetadata } = await import(\"@smithy/credential-provider-imds\");\n logger?.debug(\"@aws-sdk/credential-provider-ini - credential_source is EcsContainer\");\n return async () => chain(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider);\n },\n Ec2InstanceMetadata: async (options) => {\n logger?.debug(\"@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata\");\n const { fromInstanceMetadata } = await import(\"@smithy/credential-provider-imds\");\n return async () => fromInstanceMetadata(options)().then(setNamedProvider);\n },\n Environment: async (options) => {\n logger?.debug(\"@aws-sdk/credential-provider-ini - credential_source is Environment\");\n const { fromEnv } = await import(\"@aws-sdk/credential-provider-env\");\n return async () => fromEnv(options)().then(setNamedProvider);\n },\n };\n if (credentialSource in sourceProvidersMap) {\n return sourceProvidersMap[credentialSource];\n }\n else {\n throw new CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, ` +\n `expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger });\n }\n};\nconst setNamedProvider = (creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_NAMED_PROVIDER\", \"p\");\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isLoginProfile = (data) => {\n return Boolean(data && data.login_session);\n};\nexport const resolveLoginCredentials = async (profileName, options, callerClientConfig) => {\n const { fromLoginCredentials } = await import(\"@aws-sdk/credential-provider-login\");\n const credentials = await fromLoginCredentials({\n ...options,\n profile: profileName,\n })({ callerClientConfig });\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE_LOGIN\", \"AC\");\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isProcessProfile = (arg) => Boolean(arg) && typeof arg === \"object\" && typeof arg.credential_process === \"string\";\nexport const resolveProcessCredentials = async (options, profile) => {\n const { fromProcess } = await import(\"@aws-sdk/credential-provider-process\");\n const credentials = await fromProcess({\n ...options,\n profile,\n })();\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE_PROCESS\", \"v\");\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const resolveSsoCredentials = async (profile, profileData, options = {}, callerClientConfig) => {\n const { fromSSO } = await import(\"@aws-sdk/credential-provider-sso\");\n return fromSSO({\n profile,\n logger: options.logger,\n parentClientConfig: options.parentClientConfig,\n clientConfig: options.clientConfig,\n })({\n callerClientConfig,\n }).then((creds) => {\n if (profileData.sso_session) {\n return setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SSO\", \"r\");\n }\n else {\n return setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SSO_LEGACY\", \"t\");\n }\n });\n};\nexport const isSsoProfile = (arg) => arg &&\n (typeof arg.sso_start_url === \"string\" ||\n typeof arg.sso_account_id === \"string\" ||\n typeof arg.sso_session === \"string\" ||\n typeof arg.sso_region === \"string\" ||\n typeof arg.sso_role_name === \"string\");\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isStaticCredsProfile = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.aws_access_key_id === \"string\" &&\n typeof arg.aws_secret_access_key === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.aws_session_token) > -1 &&\n [\"undefined\", \"string\"].indexOf(typeof arg.aws_account_id) > -1;\nexport const resolveStaticCredentials = async (profile, options) => {\n options?.logger?.debug(\"@aws-sdk/credential-provider-ini - resolveStaticCredentials\");\n const credentials = {\n accessKeyId: profile.aws_access_key_id,\n secretAccessKey: profile.aws_secret_access_key,\n sessionToken: profile.aws_session_token,\n ...(profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }),\n ...(profile.aws_account_id && { accountId: profile.aws_account_id }),\n };\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE\", \"n\");\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isWebIdentityProfile = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.web_identity_token_file === \"string\" &&\n typeof arg.role_arn === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.role_session_name) > -1;\nexport const resolveWebIdentityCredentials = async (profile, options, callerClientConfig) => {\n const { fromTokenFile } = await import(\"@aws-sdk/credential-provider-web-identity\");\n const credentials = await fromTokenFile({\n webIdentityTokenFile: profile.web_identity_token_file,\n roleArn: profile.role_arn,\n roleSessionName: profile.role_session_name,\n roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity,\n logger: options.logger,\n parentClientConfig: options.parentClientConfig,\n })({\n callerClientConfig,\n });\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN\", \"q\");\n};\n" | ||
| ], | ||
| "mappings": ";oKAAA,eCAA,eCAA,eACA,WCDA,eACA,WACa,EAA0B,CAAC,EAAkB,EAAa,IAAW,CAC9E,IAAM,EAAqB,CACvB,aAAc,MAAO,IAAY,CAC7B,IAAQ,YAAa,KAAa,2CAC1B,yBAA0B,KAAa,0CAE/C,OADA,GAAQ,MAAM,sEAAsE,EAC7E,SAAY,QAAM,EAAS,GAAW,CAAC,CAAC,EAAG,EAAsB,CAAO,CAAC,EAAE,EAAE,KAAK,CAAgB,GAE7G,oBAAqB,MAAO,IAAY,CACpC,GAAQ,MAAM,6EAA6E,EAC3F,IAAQ,wBAAyB,KAAa,0CAC9C,MAAO,UAAY,EAAqB,CAAO,EAAE,EAAE,KAAK,CAAgB,GAE5E,YAAa,MAAO,IAAY,CAC5B,GAAQ,MAAM,qEAAqE,EACnF,IAAQ,WAAY,KAAa,0CACjC,MAAO,UAAY,EAAQ,CAAO,EAAE,EAAE,KAAK,CAAgB,EAEnE,EACA,GAAI,KAAoB,EACpB,OAAO,EAAmB,GAG1B,WAAM,IAAI,2BAAyB,4CAA4C,UAAoB,kEAC/B,CAAE,QAAO,CAAC,GAGhF,EAAmB,CAAC,IAAU,uBAAqB,EAAO,qCAAsC,GAAG,ED1BlG,IAAM,EAAsB,CAAC,GAAO,UAAU,UAAW,UAAW,CAAC,IAChE,QAAQ,CAAG,GACf,OAAO,IAAQ,UACf,OAAO,EAAI,WAAa,UACxB,CAAC,YAAa,QAAQ,EAAE,QAAQ,OAAO,EAAI,iBAAiB,EAAI,IAChE,CAAC,YAAa,QAAQ,EAAE,QAAQ,OAAO,EAAI,WAAW,EAAI,IAC1D,CAAC,YAAa,QAAQ,EAAE,QAAQ,OAAO,EAAI,UAAU,EAAI,KACxD,EAA8B,EAAK,CAAE,UAA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} |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/add.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\"\nimport { Effect } from \"effect\"\nimport { applyEdits, modify, parse, type ParseError } from \"jsonc-parser\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Npm } from \"@opencode-ai/util/npm\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { resolveConfigPath } from \"../mcp/add\"\nimport { Config } from \"../../../config\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.add,\n Effect.fn(\"cli.plugin.add\")(function* (input) {\n if (!(yield* Effect.promise(() => Npm.isInstallablePackage(input.package))))\n return yield* Effect.fail(new Error(\"Plugin target must be an npm registry package or Git package specifier\"))\n const npm = yield* Npm.Service\n const installed = yield* npm.add(input.package, { subpaths: [\"server\", \"\"] })\n const tui = yield* npm.resolve(input.package, { subpaths: [\"tui\"] })\n const target = configurationTarget(installed.entrypoint, tui.entrypoint)\n if (!target)\n return yield* Effect.fail(new Error(`Plugin package has no server or TUI entrypoint: ${input.package}`))\n\n if (target === \"server\") {\n const global = yield* Global.Service\n const configPath = yield* Effect.promise(() => resolveConfigPath(global.config))\n const changed = yield* Effect.promise(() => writePluginConfig(configPath, input.package))\n process.stdout.write(\n changed\n ? `Plugin \"${input.package}\" installed and added to ${configPath}${EOL}`\n : `Plugin \"${input.package}\" is already configured in ${configPath}${EOL}`,\n )\n return\n }\n\n const config = yield* Config.Service\n yield* config.update((draft) => {\n if (configured(draft.plugins, input.package)) return\n draft.plugins = [...(draft.plugins ?? []), input.package]\n })\n process.stdout.write(`TUI plugin \"${input.package}\" installed and added to ${config.path}${EOL}`)\n }),\n)\n\nexport function configurationTarget(server?: string, tui?: string) {\n if (server) return \"server\" as const\n if (tui) return \"tui\" as const\n}\n\nexport async function writePluginConfig(configPath: string, spec: string) {\n const text = await readFile(configPath, \"utf8\").catch((error) => {\n if (typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\") return \"{}\"\n throw error\n })\n const errors: ParseError[] = []\n const config: unknown = parse(text, errors, { allowTrailingComma: true })\n if (errors.length || typeof config !== \"object\" || config === null || Array.isArray(config))\n throw new Error(`Invalid global configuration: ${configPath}`)\n const plugins = \"plugins\" in config ? config.plugins : undefined\n if (plugins !== undefined && !Array.isArray(plugins)) throw new Error(`Invalid plugins configuration: ${configPath}`)\n if (configured(plugins, spec)) return false\n\n const updated = applyEdits(\n text,\n modify(text, [\"plugins\"], [...(plugins ?? []), spec], { formattingOptions: { tabSize: 2, insertSpaces: true } }),\n )\n await mkdir(path.dirname(configPath), { recursive: true })\n const temporary = configPath + \".tmp\"\n await writeFile(temporary, updated.endsWith(\"\\n\") ? updated : updated + \"\\n\", { mode: 0o600 })\n await rename(temporary, configPath)\n return true\n}\n\nfunction configured(plugins: readonly unknown[] | undefined, spec: string) {\n return plugins?.some(\n (entry) =>\n entry === spec || (typeof entry === \"object\" && entry !== null && \"package\" in entry && entry.package === spec),\n )\n}\n" | ||
| ], | ||
| "mappings": ";gwBAAA,cAAS,WACT,oBACA,gBAAS,cAAO,YAAU,eAAQ,oBAUlC,IAAe,IAAQ,QACrB,EAAS,SAAS,OAAO,SAAS,IAClC,EAAO,GAAG,gBAAgB,EAAE,SAAU,CAAC,EAAO,CAC5C,GAAI,EAAE,MAAO,EAAO,QAAQ,IAAM,EAAI,qBAAqB,EAAM,OAAO,CAAC,GACvE,OAAO,MAAO,EAAO,KAAS,MAAM,wEAAwE,CAAC,EAC/G,IAAM,EAAM,MAAO,EAAI,QACjB,EAAY,MAAO,EAAI,IAAI,EAAM,QAAS,CAAE,SAAU,CAAC,SAAU,EAAE,CAAE,CAAC,EACtE,EAAM,MAAO,EAAI,QAAQ,EAAM,QAAS,CAAE,SAAU,CAAC,KAAK,CAAE,CAAC,EAC7D,EAAS,EAAoB,EAAU,WAAY,EA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,GAAY,EACpH,GAAI,EAAW,EAAS,CAAI,EAAG,MAAO,GAEtC,IAAM,EAAU,EACd,EACA,EAAO,EAAM,CAAC,SAAS,EAAG,CAAC,GAAI,GAAW,CAAC,EAAI,CAAI,EAAG,CAAE,kBAAmB,CAAE,QAAS,EAAG,aAAc,EAAK,CAAE,CAAC,CACjH,EACA,MAAM,EAAM,EAAK,QAAQ,CAAU,EAAG,CAAE,UAAW,EAAK,CAAC,EACzD,IAAM,EAAY,EAAa,OAG/B,OAFA,MAAM,EAAU,EAAW,EAAQ,SAAS;AAAA,CAAI,EAAI,EAAU,EAAU;AAAA,EAAM,CAAE,KAAM,GAAM,CAAC,EAC7F,MAAM,EAAO,EAAW,CAAU,EAC3B,GAGT,SAAS,CAAU,CAAC,EAAyC,EAAc,CACzE,OAAO,GAAS,KACd,CAAC,IACC,IAAU,GAAS,OAAO,IAAU,UAAY,IAAU,OAAQ,YAAa,IAAS,EAAM,UAAY,CAC9G", | ||
| "debugId": "CC4E4C508ADA208864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "C67631401395EE5664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/stop.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { ServerConnection } from \"../../../services/server-connection\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.stop,\n Effect.fn(\"cli.service.stop\")(function* () {\n const options = yield* ServiceConfig.options()\n yield* ServerConnection.shutdownPersistentPty(options).pipe(Effect.ignore)\n yield* Service.stop(options)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+jCAOA,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,KACnC,EAAO,GAAG,kBAAkB,EAAE,SAAU,EAAG,CACzC,IAAM,EAAU,MAAO,EAAc,QAAQ,EAC7C,MAAO,EAAiB,sBAAsB,CAAO,EAAE,KAAK,EAAO,MAAM,EACzE,MAAO,EAAQ,KAAK,CAAO,EAC5B,CACH", | ||
| "debugId": "ADFAD48B99B7B60764756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/fromContainerMetadata.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/ImdsCredentials.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/RemoteProviderInit.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/httpRequest.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/node-http.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/fromInstanceMetadata.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/error/InstanceMetadataV1FallbackError.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/utils/getInstanceMetadataEndpoint.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/config/Endpoint.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointConfigOptions.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointMode.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointModeConfigOptions.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/utils/getExtendedInstanceMetadataCredentials.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/utils/staticStabilityProvider.js"], | ||
| "sourcesContent": [ | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { fromImdsCredentials, isImdsCredentials } from \"./remoteProvider/ImdsCredentials\";\nimport { providerConfigFromInit } from \"./remoteProvider/RemoteProviderInit\";\nimport { httpRequest } from \"./remoteProvider/httpRequest\";\nimport { retry } from \"./remoteProvider/retry\";\nexport const ENV_CMDS_FULL_URI = \"AWS_CONTAINER_CREDENTIALS_FULL_URI\";\nexport const ENV_CMDS_RELATIVE_URI = \"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\";\nexport const ENV_CMDS_AUTH_TOKEN = \"AWS_CONTAINER_AUTHORIZATION_TOKEN\";\nexport const fromContainerMetadata = (init = {}) => {\n const { timeout, maxRetries } = providerConfigFromInit(init);\n return () => retry(async () => {\n const requestOptions = await getCmdsUri({ logger: init.logger });\n const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions));\n if (!isImdsCredentials(credsResponse)) {\n throw new CredentialsProviderError(\"Invalid response received from instance metadata service.\", {\n logger: init.logger,\n });\n }\n return fromImdsCredentials(credsResponse);\n }, maxRetries);\n};\nconst requestFromEcsImds = async (timeout, options) => {\n if (process.env[ENV_CMDS_AUTH_TOKEN]) {\n options.headers = {\n ...options.headers,\n Authorization: process.env[ENV_CMDS_AUTH_TOKEN],\n };\n }\n const buffer = await httpRequest({\n ...options,\n timeout,\n });\n return buffer.toString();\n};\nconst CMDS_IP = \"169.254.170.2\";\nconst GREENGRASS_HOSTS = new Set([\"localhost\", \"127.0.0.1\"]);\nconst GREENGRASS_PROTOCOLS = new Set([\"http:\", \"https:\"]);\nconst getCmdsUri = async ({ logger }) => {\n if (process.env[ENV_CMDS_RELATIVE_URI]) {\n return {\n hostname: CMDS_IP,\n path: process.env[ENV_CMDS_RELATIVE_URI],\n };\n }\n if (process.env[ENV_CMDS_FULL_URI]) {\n let parsed;\n try {\n parsed = new URL(process.env[ENV_CMDS_FULL_URI]);\n }\n catch {\n throw new CredentialsProviderError(`${process.env[ENV_CMDS_FULL_URI]} is not a valid container metadata service URL`, { tryNextLink: false, logger });\n }\n if (!parsed.hostname || !GREENGRASS_HOSTS.has(parsed.hostname)) {\n throw new CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, {\n tryNextLink: false,\n logger,\n });\n }\n if (!parsed.protocol || !GREENGRASS_PROTOCOLS.has(parsed.protocol)) {\n throw new CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, {\n tryNextLink: false,\n logger,\n });\n }\n return {\n protocol: parsed.protocol,\n hostname: parsed.hostname,\n path: parsed.pathname + parsed.search,\n port: parsed.port ? parseInt(parsed.port, 10) : undefined,\n };\n }\n throw new CredentialsProviderError(\"The container metadata credential provider cannot be used unless\" +\n ` the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment` +\n \" variable is set\", {\n tryNextLink: false,\n logger,\n });\n};\n", | ||
| "export const isImdsCredentials = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.AccessKeyId === \"string\" &&\n typeof arg.SecretAccessKey === \"string\" &&\n typeof arg.Token === \"string\" &&\n typeof arg.Expiration === \"string\";\nexport const fromImdsCredentials = (creds) => ({\n accessKeyId: creds.AccessKeyId,\n secretAccessKey: creds.SecretAccessKey,\n sessionToken: creds.Token,\n expiration: new Date(creds.Expiration),\n ...(creds.AccountId && { accountId: creds.AccountId }),\n});\n", | ||
| "export const DEFAULT_TIMEOUT = 1000;\nexport const DEFAULT_MAX_RETRIES = 0;\nexport const providerConfigFromInit = ({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT, }) => ({ maxRetries, timeout });\n", | ||
| "import { ProviderError } from \"@smithy/core/config\";\nimport { node_http } from \"./node-http\";\nexport function httpRequest(options) {\n return new Promise((resolve, reject) => {\n const req = node_http.request({\n method: \"GET\",\n ...options,\n hostname: options.hostname?.replace(/^\\[(.+)\\]$/, \"$1\"),\n });\n req.on(\"error\", (err) => {\n reject(Object.assign(new ProviderError(\"Unable to connect to instance metadata service\"), err));\n req.destroy();\n });\n req.on(\"timeout\", () => {\n reject(new ProviderError(\"TimeoutError from instance metadata service\"));\n req.destroy();\n });\n req.on(\"response\", (res) => {\n const { statusCode = 400 } = res;\n if (statusCode < 200 || 300 <= statusCode) {\n reject(Object.assign(new ProviderError(\"Error response received from instance metadata service\"), { statusCode }));\n req.destroy();\n }\n const chunks = [];\n res.on(\"data\", (chunk) => {\n chunks.push(chunk);\n });\n res.on(\"end\", () => {\n resolve(Buffer.concat(chunks));\n req.destroy();\n });\n });\n req.end();\n });\n}\n", | ||
| "import node_http from \"node:http\";\nexport { node_http };\n", | ||
| "export const retry = (toRetry, maxRetries) => {\n let promise = toRetry();\n for (let i = 0; i < maxRetries; i++) {\n promise = promise.catch(toRetry);\n }\n return promise;\n};\n", | ||
| "import { CredentialsProviderError, loadConfig } from \"@smithy/core/config\";\nimport { InstanceMetadataV1FallbackError } from \"./error/InstanceMetadataV1FallbackError\";\nimport { fromImdsCredentials, isImdsCredentials } from \"./remoteProvider/ImdsCredentials\";\nimport { providerConfigFromInit } from \"./remoteProvider/RemoteProviderInit\";\nimport { httpRequest } from \"./remoteProvider/httpRequest\";\nimport { retry } from \"./remoteProvider/retry\";\nimport { getInstanceMetadataEndpoint } from \"./utils/getInstanceMetadataEndpoint\";\nimport { staticStabilityProvider } from \"./utils/staticStabilityProvider\";\nconst IMDS_PATH = \"/latest/meta-data/iam/security-credentials/\";\nconst IMDS_TOKEN_PATH = \"/latest/api/token\";\nconst AWS_EC2_METADATA_V1_DISABLED = \"AWS_EC2_METADATA_V1_DISABLED\";\nconst PROFILE_AWS_EC2_METADATA_V1_DISABLED = \"ec2_metadata_v1_disabled\";\nconst X_AWS_EC2_METADATA_TOKEN = \"x-aws-ec2-metadata-token\";\nexport const fromInstanceMetadata = (init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger });\nconst getInstanceMetadataProvider = (init = {}) => {\n let disableFetchToken = false;\n const { logger, profile } = init;\n const { timeout, maxRetries } = providerConfigFromInit(init);\n const getCredentials = async (maxRetries, options) => {\n const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null;\n if (isImdsV1Fallback) {\n let fallbackBlockedFromProfile = false;\n let fallbackBlockedFromProcessEnv = false;\n const configValue = await loadConfig({\n environmentVariableSelector: (env) => {\n const envValue = env[AWS_EC2_METADATA_V1_DISABLED];\n fallbackBlockedFromProcessEnv = !!envValue && envValue !== \"false\";\n if (envValue === undefined) {\n throw new CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init.logger });\n }\n return fallbackBlockedFromProcessEnv;\n },\n configFileSelector: (profile) => {\n const profileValue = profile[PROFILE_AWS_EC2_METADATA_V1_DISABLED];\n fallbackBlockedFromProfile = !!profileValue && profileValue !== \"false\";\n return fallbackBlockedFromProfile;\n },\n default: false,\n }, {\n profile,\n })();\n if (init.ec2MetadataV1Disabled || configValue) {\n const causes = [];\n if (init.ec2MetadataV1Disabled)\n causes.push(\"credential provider initialization (runtime option ec2MetadataV1Disabled)\");\n if (fallbackBlockedFromProfile)\n causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`);\n if (fallbackBlockedFromProcessEnv)\n causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`);\n throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(\", \")}].`);\n }\n }\n const imdsProfile = (await retry(async () => {\n let profile;\n try {\n profile = await getProfile(options);\n }\n catch (err) {\n if (err.statusCode === 401) {\n disableFetchToken = false;\n }\n throw err;\n }\n return profile;\n }, maxRetries)).trim();\n return retry(async () => {\n let creds;\n try {\n creds = await getCredentialsFromProfile(imdsProfile, options, init);\n }\n catch (err) {\n if (err.statusCode === 401) {\n disableFetchToken = false;\n }\n throw err;\n }\n return creds;\n }, maxRetries);\n };\n return async () => {\n const endpoint = await getInstanceMetadataEndpoint();\n if (disableFetchToken) {\n logger?.debug(\"AWS SDK Instance Metadata\", \"using v1 fallback (no token fetch)\");\n return getCredentials(maxRetries, { ...endpoint, timeout });\n }\n else {\n let token;\n try {\n token = (await getMetadataToken({ ...endpoint, timeout })).toString();\n }\n catch (error) {\n if (error?.statusCode === 400) {\n throw Object.assign(error, {\n message: \"EC2 Metadata token request returned error\",\n });\n }\n else if (error.message === \"TimeoutError\" || [403, 404, 405].includes(error.statusCode)) {\n disableFetchToken = true;\n }\n logger?.debug(\"AWS SDK Instance Metadata\", \"using v1 fallback (initial)\");\n return getCredentials(maxRetries, { ...endpoint, timeout });\n }\n return getCredentials(maxRetries, {\n ...endpoint,\n headers: {\n [X_AWS_EC2_METADATA_TOKEN]: token,\n },\n timeout,\n });\n }\n };\n};\nconst getMetadataToken = async (options) => httpRequest({\n ...options,\n path: IMDS_TOKEN_PATH,\n method: \"PUT\",\n headers: {\n \"x-aws-ec2-metadata-token-ttl-seconds\": \"21600\",\n },\n});\nconst getProfile = async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString();\nconst getCredentialsFromProfile = async (profile, options, init) => {\n const credentialsResponse = JSON.parse((await httpRequest({\n ...options,\n path: IMDS_PATH + profile,\n })).toString());\n if (!isImdsCredentials(credentialsResponse)) {\n throw new CredentialsProviderError(\"Invalid response received from instance metadata service.\", {\n logger: init.logger,\n });\n }\n return fromImdsCredentials(credentialsResponse);\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nexport class InstanceMetadataV1FallbackError extends CredentialsProviderError {\n tryNextLink;\n name = \"InstanceMetadataV1FallbackError\";\n constructor(message, tryNextLink = true) {\n super(message, tryNextLink);\n this.tryNextLink = tryNextLink;\n Object.setPrototypeOf(this, InstanceMetadataV1FallbackError.prototype);\n }\n}\n", | ||
| "import { loadConfig } from \"@smithy/core/config\";\nimport { parseUrl } from \"@smithy/core/protocols\";\nimport { Endpoint as InstanceMetadataEndpoint } from \"../config/Endpoint\";\nimport { ENDPOINT_CONFIG_OPTIONS } from \"../config/EndpointConfigOptions\";\nimport { EndpointMode } from \"../config/EndpointMode\";\nimport { ENDPOINT_MODE_CONFIG_OPTIONS, } from \"../config/EndpointModeConfigOptions\";\nexport const getInstanceMetadataEndpoint = async () => parseUrl((await getFromEndpointConfig()) || (await getFromEndpointModeConfig()));\nconst getFromEndpointConfig = async () => loadConfig(ENDPOINT_CONFIG_OPTIONS)();\nconst getFromEndpointModeConfig = async () => {\n const endpointMode = await loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)();\n switch (endpointMode) {\n case EndpointMode.IPv4:\n return InstanceMetadataEndpoint.IPv4;\n case EndpointMode.IPv6:\n return InstanceMetadataEndpoint.IPv6;\n default:\n throw new Error(`Unsupported endpoint mode: ${endpointMode}.` + ` Select from ${Object.values(EndpointMode)}`);\n }\n};\n", | ||
| "export var Endpoint;\n(function (Endpoint) {\n Endpoint[\"IPv4\"] = \"http://169.254.169.254\";\n Endpoint[\"IPv6\"] = \"http://[fd00:ec2::254]\";\n})(Endpoint || (Endpoint = {}));\n", | ||
| "export const ENV_ENDPOINT_NAME = \"AWS_EC2_METADATA_SERVICE_ENDPOINT\";\nexport const CONFIG_ENDPOINT_NAME = \"ec2_metadata_service_endpoint\";\nexport const ENDPOINT_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => env[ENV_ENDPOINT_NAME],\n configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME],\n default: undefined,\n};\n", | ||
| "export var EndpointMode;\n(function (EndpointMode) {\n EndpointMode[\"IPv4\"] = \"IPv4\";\n EndpointMode[\"IPv6\"] = \"IPv6\";\n})(EndpointMode || (EndpointMode = {}));\n", | ||
| "import { EndpointMode } from \"./EndpointMode\";\nexport const ENV_ENDPOINT_MODE_NAME = \"AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE\";\nexport const CONFIG_ENDPOINT_MODE_NAME = \"ec2_metadata_service_endpoint_mode\";\nexport const ENDPOINT_MODE_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => env[ENV_ENDPOINT_MODE_NAME],\n configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME],\n default: EndpointMode.IPv4,\n};\n", | ||
| "const STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60;\nconst STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60;\nconst STATIC_STABILITY_DOC_URL = \"https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html\";\nexport const getExtendedInstanceMetadataCredentials = (credentials, logger) => {\n const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS +\n Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS);\n const newExpiration = new Date(Date.now() + refreshInterval * 1000);\n logger.warn(\"Attempting credential expiration extension due to a credential service availability issue. A refresh of these \" +\n `credentials will be attempted after ${new Date(newExpiration)}.\\nFor more information, please visit: ` +\n STATIC_STABILITY_DOC_URL);\n const originalExpiration = credentials.originalExpiration ?? credentials.expiration;\n return {\n ...credentials,\n ...(originalExpiration ? { originalExpiration } : {}),\n expiration: newExpiration,\n };\n};\n", | ||
| "import { getExtendedInstanceMetadataCredentials } from \"./getExtendedInstanceMetadataCredentials\";\nexport const staticStabilityProvider = (provider, options = {}) => {\n const logger = options?.logger || console;\n let pastCredentials;\n return async () => {\n let credentials;\n try {\n credentials = await provider();\n if (credentials.expiration && credentials.expiration.getTime() < Date.now()) {\n credentials = getExtendedInstanceMetadataCredentials(credentials, logger);\n }\n }\n catch (e) {\n if (pastCredentials) {\n logger.warn(\"Credential renew failed: \", e);\n credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger);\n }\n else {\n throw e;\n }\n }\n pastCredentials = credentials;\n return credentials;\n };\n};\n" | ||
| ], | ||
| "mappings": ";6JAAA,eCAO,IAAM,EAAoB,CAAC,IAAQ,QAAQ,CAAG,GACjD,OAAO,IAAQ,UACf,OAAO,EAAI,cAAgB,UAC3B,OAAO,EAAI,kBAAoB,UAC/B,OAAO,EAAI,QAAU,UACrB,OAAO,EAAI,aAAe,SACjB,EAAsB,CAAC,KAAW,CAC3C,YAAa,EAAM,YACnB,gBAAiB,EAAM,gBACvB,aAAc,EAAM,MACpB,WAAY,IAAI,KAAK,EAAM,UAAU,KACjC,EAAM,WAAa,CAAE,UAAW,EAAM,SAAU,CACxD,GCZO,IAAM,EAAkB,KAClB,EAAsB,EACtB,EAAyB,EAAG,aADN,EACwC,UAF5C,SAE8E,CAAE,aAAY,SAAQ,GCFnI,eCAA,oBDEO,SAAS,CAAW,CAAC,EAAS,CACjC,OAAO,IAAI,QAAQ,CAAC,EAAS,IAAW,CACpC,IAAM,EAAM,EAAU,QAAQ,CAC1B,OAAQ,SACL,EACH,SAAU,EAAQ,UAAU,QAAQ,aAAc,IAAI,CAC1D,CAAC,EACD,EAAI,GAAG,QAAS,CAAC,IAAQ,CACrB,EAAO,OAAO,OAAO,IAAI,gBAAc,gDAAgD,EAAG,CAAG,CAAC,EAC9F,EAAI,QAAQ,EACf,EACD,EAAI,GAAG,UAAW,IAAM,CACpB,EAAO,IAAI,gBAAc,6CAA6C,CAAC,EACvE,EAAI,QAAQ,EACf,EACD,EAAI,GAAG,WAAY,CAAC,IAAQ,CACxB,IAAQ,aAAa,KAAQ,EAC7B,GAAI,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
| "sourcesContent": [ | ||
| "export * as ConfigMCP from \"./mcp.js\"\n\nimport { Schema } from \"effect\"\nimport { Mcp } from \"../mcp.js\"\nimport { optional } from \"../schema.js\"\n\nexport const Timeout = Mcp.TimeoutConfig\nexport type Timeout = Mcp.TimeoutConfig\nexport const Local = Mcp.LocalConfig\nexport type Local = Mcp.LocalConfig\nexport const OAuth = Mcp.OAuthConfig\nexport type OAuth = Mcp.OAuthConfig\nexport const Remote = Mcp.RemoteConfig\nexport type Remote = Mcp.RemoteConfig\nexport const Server = Mcp.ServerConfig\n\nexport class Info extends Schema.Class<Info>(\"Config.MCP\")({\n timeout: Timeout.pipe(optional),\n servers: Schema.Record(Schema.String, Server).pipe(optional),\n}) {}\n" | ||
| ], | ||
| "mappings": ";2TAMO,IAAM,EAAU,EAAI,cAEd,EAAQ,EAAI,YAEZ,EAAQ,EAAI,YAEZ,EAAS,EAAI,aAEb,EAAS,EAAI,aAEnB,MAAM,UAAa,EAAO,MAAY,YAAY,EAAE,CACzD,QAAS,EAAQ,KAAK,CAAQ,EAC9B,QAAS,EAAO,OAAO,EAAO,OAAQ,CAAM,EAAE,KAAK,CAAQ,CAC7D,CAAC,CAAE,CAAC", | ||
| "debugId": "EA8F0C7F88F2232964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "1B42A58514AC274864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/reference.ts", "../schema/src/command.ts", "../schema/src/websearch.ts"], | ||
| "sourcesContent": [ | ||
| "export * as Reference from \"./reference.js\"\n\nimport { Schema } from \"effect\"\nimport { optional } from \"./schema.js\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { AbsolutePath } from \"./schema.js\"\n\nconst Updated = ephemeral({ type: \"reference.updated\", schema: {} })\nexport const Event = { Updated, Definitions: inventory(Updated) }\n\nexport interface LocalSource extends Schema.Schema.Type<typeof LocalSource> {}\nexport const LocalSource = Schema.Struct({\n type: Schema.Literal(\"local\"),\n path: AbsolutePath,\n description: Schema.String.pipe(optional),\n hidden: Schema.Boolean.pipe(optional),\n}).annotate({ identifier: \"Reference.LocalSource\" })\n\nexport interface GitSource extends Schema.Schema.Type<typeof GitSource> {}\nexport const GitSource = Schema.Struct({\n type: Schema.Literal(\"git\"),\n repository: Schema.String,\n branch: Schema.String.pipe(optional),\n description: Schema.String.pipe(optional),\n hidden: Schema.Boolean.pipe(optional),\n}).annotate({ identifier: \"Reference.GitSource\" })\n\nexport const Source = Schema.Union([LocalSource, GitSource])\n .pipe(Schema.toTaggedUnion(\"type\"))\n .annotate({ identifier: \"Reference.Source\" })\nexport type Source = typeof Source.Type\n\nexport const Info = Schema.Struct({\n name: Schema.String,\n path: AbsolutePath,\n description: Schema.String.pipe(optional),\n hidden: Schema.Boolean.pipe(optional),\n source: Source,\n}).annotate({ identifier: \"Reference.Info\" })\nexport interface Info extends Schema.Schema.Type<typeof Info> {}\n", | ||
| "export * as Command from \"./command.js\"\n\nimport { Schema } from \"effect\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { optional } from \"./schema.js\"\n\nconst Updated = ephemeral({ type: \"command.updated\", schema: {} })\n\nexport interface Info extends Schema.Schema.Type<typeof Info> {}\nexport const Info = Schema.Struct({\n name: Schema.String,\n description: Schema.String.pipe(optional),\n}).annotate({ identifier: \"Command.Info\" })\n\nexport const Event = {\n Updated,\n Definitions: inventory(Updated),\n}\n", | ||
| "export * as WebSearch from \"./websearch.js\"\n\nimport { Schema } from \"effect\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { optional } from \"./schema.js\"\n\nexport const ID = Schema.String.pipe(Schema.brand(\"WebSearch.ID\"))\nexport type ID = typeof ID.Type\n\nexport interface Provider extends Schema.Schema.Type<typeof Provider> {}\nexport const Provider = Schema.Struct({\n id: ID,\n name: Schema.String,\n}).annotate({ identifier: \"WebSearch.Provider\" })\n\nexport interface Input extends Schema.Schema.Type<typeof Input> {}\nexport const Input = Schema.Struct({\n query: Schema.String,\n providerID: ID.pipe(optional),\n}).annotate({ identifier: \"WebSearch.Input\" })\nexport type ProviderInput = Pick<Input, \"query\">\n\nexport interface Result extends Schema.Schema.Type<typeof Result> {}\nexport const Result = Schema.Struct({\n url: Schema.String,\n title: Schema.String.pipe(optional),\n content: Schema.String.pipe(optional),\n time: Schema.Struct({\n published: Schema.Finite.pipe(optional),\n }),\n}).annotate({ identifier: \"WebSearch.Result\" })\n\nexport class Response extends Schema.Class<Response>(\"WebSearch.Response\")({\n providerID: ID,\n results: Schema.Array(Result),\n}) {}\n\nconst Updated = ephemeral({\n type: \"websearch.updated\",\n schema: {},\n})\nexport const Event = { Updated, Definitions: inventory(Updated) }\n" | ||
| ], | ||
| "mappings": ";sUAOA,IAAM,EAAU,EAAU,CAAE,KAAM,oBAAqB,OAAQ,CAAC,CAAE,CAAC,EACtD,EAAQ,CAAE,UAAS,YAAa,EAAU,CAAO,CAAE,EAGnD,EAAc,EAAO,OAAO,CACvC,KAAM,EAAO,QAAQ,OAAO,EAC5B,KAAM,EACN,YAAa,EAAO,OAAO,KAAK,CAAQ,EACxC,OAAQ,EAAO,QAAQ,KAAK,CAAQ,CACtC,CAAC,EAAE,SAAS,CAAE,WAAY,uBAAwB,CAAC,EAGtC,EAAY,EAAO,OAAO,CACrC,KAAM,EAAO,QAAQ,KAAK,EAC1B,WAAY,EAAO,OACnB,OAAQ,EAAO,OAAO,KAAK,CAAQ,EACnC,YAAa,EAAO,OAAO,KAAK,CAAQ,EACxC,OAAQ,EAAO,QAAQ,KAAK,CAAQ,CACtC,CAAC,EAAE,SAAS,CAAE,WAAY,qBAAsB,CAAC,EAEpC,EAAS,EAAO,MAAM,CAAC,EAAa,CAAS,CAAC,EACxD,KAAK,EAAO,cAAc,MAAM,CAAC,EACjC,SAAS,CAAE,WAAY,kBAAmB,CAAC,EAGjC,EAAO,EAAO,OAAO,CAChC,K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
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+nested-clients@3.997.43/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsRestJsonProtocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"sso-oauth\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"CreateToken\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"sso-oauth\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.42\";\nvar packageInfo = {\n\tversion: version};\n\nconst k = \"ref\";\nconst a = -1, b = true, c = \"isSet\", d = \"PartitionResult\", e = \"booleanEquals\", f = \"getAttr\", g = { [k]: \"Endpoint\" }, h = { [k]: d }, i = {}, j = [{ [k]: \"Region\" }];\nconst _data = {\n conditions: [\n [c, [g]],\n [c, j],\n [\"aws.partition\", j, d],\n [e, [{ [k]: \"UseFIPS\" }, b]],\n [e, [{ [k]: \"UseDualStack\" }, b]],\n [e, [{ fn: f, argv: [h, \"supportsDualStack\"] }, b]],\n [e, [{ fn: f, argv: [h, \"supportsFIPS\"] }, b]],\n [\"stringEquals\", [{ fn: f, argv: [h, \"name\"] }, \"aws-us-gov\"]]\n ],\n results: [\n [a],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [g, i],\n [\"https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://oidc.{Region}.amazonaws.com\", i],\n [\"https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [\"https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://oidc.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 13, 3,\n 1, 4, r + 12,\n 2, 5, r + 12,\n 3, 8, 6,\n 4, 7, r + 11,\n 5, r + 9, r + 10,\n 4, 11, 9,\n 6, 10, r + 8,\n 7, r + 6, r + 7,\n 5, 12, r + 5,\n 6, r + 4, r + 5,\n 3, r + 1, 14,\n 4, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass SSOOIDCServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, SSOOIDCServiceException.prototype);\n }\n}\n\nclass AccessDeniedException extends SSOOIDCServiceException {\n name = \"AccessDeniedException\";\n $fault = \"client\";\n error;\n reason;\n error_description;\n constructor(opts) {\n super({\n name: \"AccessDeniedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, AccessDeniedException.prototype);\n this.error = opts.error;\n this.reason = opts.reason;\n this.error_description = opts.error_description;\n }\n}\nclass AuthorizationPendingException extends SSOOIDCServiceException {\n name = \"AuthorizationPendingException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"AuthorizationPendingException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, AuthorizationPendingException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass ExpiredTokenException extends SSOOIDCServiceException {\n name = \"ExpiredTokenException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"ExpiredTokenException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ExpiredTokenException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InternalServerException extends SSOOIDCServiceException {\n name = \"InternalServerException\";\n $fault = \"server\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InternalServerException\",\n $fault: \"server\",\n ...opts,\n });\n Object.setPrototypeOf(this, InternalServerException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidClientException extends SSOOIDCServiceException {\n name = \"InvalidClientException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidClientException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidClientException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidGrantException extends SSOOIDCServiceException {\n name = \"InvalidGrantException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidGrantException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidGrantException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidRequestException extends SSOOIDCServiceException {\n name = \"InvalidRequestException\";\n $fault = \"client\";\n error;\n reason;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidRequestException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidRequestException.prototype);\n this.error = opts.error;\n this.reason = opts.reason;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidScopeException extends SSOOIDCServiceException {\n name = \"InvalidScopeException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidScopeException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidScopeException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass SlowDownException extends SSOOIDCServiceException {\n name = \"SlowDownException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"SlowDownException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, SlowDownException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass UnauthorizedClientException extends SSOOIDCServiceException {\n name = \"UnauthorizedClientException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"UnauthorizedClientException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, UnauthorizedClientException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass UnsupportedGrantTypeException extends SSOOIDCServiceException {\n name = \"UnsupportedGrantTypeException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"UnsupportedGrantTypeException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, UnsupportedGrantTypeException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\n\nconst _ADE = \"AccessDeniedException\";\nconst _APE = \"AuthorizationPendingException\";\nconst _AT = \"AccessToken\";\nconst _CS = \"ClientSecret\";\nconst _CT = \"CreateToken\";\nconst _CTR = \"CreateTokenRequest\";\nconst _CTRr = \"CreateTokenResponse\";\nconst _CV = \"CodeVerifier\";\nconst _ETE = \"ExpiredTokenException\";\nconst _ICE = \"InvalidClientException\";\nconst _IGE = \"InvalidGrantException\";\nconst _IRE = \"InvalidRequestException\";\nconst _ISE = \"InternalServerException\";\nconst _ISEn = \"InvalidScopeException\";\nconst _IT = \"IdToken\";\nconst _RT = \"RefreshToken\";\nconst _SDE = \"SlowDownException\";\nconst _UCE = \"UnauthorizedClientException\";\nconst _UGTE = \"UnsupportedGrantTypeException\";\nconst _aT = \"accessToken\";\nconst _c = \"client\";\nconst _cI = \"clientId\";\nconst _cS = \"clientSecret\";\nconst _cV = \"codeVerifier\";\nconst _co = \"code\";\nconst _dC = \"deviceCode\";\nconst _e = \"error\";\nconst _eI = \"expiresIn\";\nconst _ed = \"error_description\";\nconst _gT = \"grantType\";\nconst _h = \"http\";\nconst _hE = \"httpError\";\nconst _iT = \"idToken\";\nconst _r = \"reason\";\nconst _rT = \"refreshToken\";\nconst _rU = \"redirectUri\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.ssooidc\";\nconst _sc = \"scope\";\nconst _se = \"server\";\nconst _tT = \"tokenType\";\nconst n0 = \"com.amazonaws.ssooidc\";\nconst _s_registry = TypeRegistry.for(_s);\nvar SSOOIDCServiceException$ = [-3, _s, \"SSOOIDCServiceException\", 0, [], []];\n_s_registry.registerError(SSOOIDCServiceException$, SSOOIDCServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar AccessDeniedException$ = [-3, n0, _ADE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _r, _ed],\n [0, 0, 0]\n];\nn0_registry.registerError(AccessDeniedException$, AccessDeniedException);\nvar AuthorizationPendingException$ = [-3, n0, _APE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(AuthorizationPendingException$, AuthorizationPendingException);\nvar ExpiredTokenException$ = [-3, n0, _ETE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(ExpiredTokenException$, ExpiredTokenException);\nvar InternalServerException$ = [-3, n0, _ISE,\n { [_e]: _se, [_hE]: 500 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InternalServerException$, InternalServerException);\nvar InvalidClientException$ = [-3, n0, _ICE,\n { [_e]: _c, [_hE]: 401 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InvalidClientException$, InvalidClientException);\nvar InvalidGrantException$ = [-3, n0, _IGE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InvalidGrantException$, InvalidGrantException);\nvar InvalidRequestException$ = [-3, n0, _IRE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _r, _ed],\n [0, 0, 0]\n];\nn0_registry.registerError(InvalidRequestException$, InvalidRequestException);\nvar InvalidScopeException$ = [-3, n0, _ISEn,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InvalidScopeException$, InvalidScopeException);\nvar SlowDownException$ = [-3, n0, _SDE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(SlowDownException$, SlowDownException);\nvar UnauthorizedClientException$ = [-3, n0, _UCE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(UnauthorizedClientException$, UnauthorizedClientException);\nvar UnsupportedGrantTypeException$ = [-3, n0, _UGTE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(UnsupportedGrantTypeException$, UnsupportedGrantTypeException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar AccessToken = [0, n0, _AT, 8, 0];\nvar ClientSecret = [0, n0, _CS, 8, 0];\nvar CodeVerifier = [0, n0, _CV, 8, 0];\nvar IdToken = [0, n0, _IT, 8, 0];\nvar RefreshToken = [0, n0, _RT, 8, 0];\nvar CreateTokenRequest$ = [3, n0, _CTR,\n 0,\n [_cI, _cS, _gT, _dC, _co, _rT, _sc, _rU, _cV],\n [0, [() => ClientSecret, 0], 0, 0, 0, [() => RefreshToken, 0], 64 | 0, 0, [() => CodeVerifier, 0]], 3\n];\nvar CreateTokenResponse$ = [3, n0, _CTRr,\n 0,\n [_aT, _tT, _eI, _rT, _iT],\n [[() => AccessToken, 0], 0, 1, [() => RefreshToken, 0], [() => IdToken, 0]]\n];\nvar CreateToken$ = [9, n0, _CT,\n { [_h]: [\"POST\", \"/token\", 200] }, () => CreateTokenRequest$, () => CreateTokenResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2019-06-10\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOOIDCHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsRestJsonProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.ssooidc\",\n errorTypeRegistries,\n version: \"2019-06-10\",\n serviceTarget: \"AWSSSOOIDCService\",\n },\n serviceId: config?.serviceId ?? \"SSO OIDC\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass SSOOIDCClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"AWSSSOOIDCService\", \"SSOOIDCClient\", getEndpointPlugin);\nconst _ep0 = {};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass CreateTokenCommand extends command(_ep0, _mw0, \"CreateToken\", CreateToken$) {\n}\n\nconst commands = {\n CreateTokenCommand,\n};\nclass SSOOIDC extends SSOOIDCClient {\n}\ncreateAggregatedClient(commands, SSOOIDC);\n\nconst AccessDeniedExceptionReason = {\n KMS_ACCESS_DENIED: \"KMS_AccessDeniedException\",\n};\nconst InvalidRequestExceptionReason = {\n KMS_DISABLED_KEY: \"KMS_DisabledException\",\n KMS_INVALID_KEY_USAGE: \"KMS_InvalidKeyUsageException\",\n KMS_INVALID_STATE: \"KMS_InvalidStateException\",\n KMS_KEY_NOT_FOUND: \"KMS_NotFoundException\",\n};\n\nexports.AccessDeniedException = AccessDeniedException;\nexports.AccessDeniedException$ = AccessDeniedException$;\nexports.AccessDeniedExceptionReason = AccessDeniedExceptionReason;\nexports.AuthorizationPendingException = AuthorizationPendingException;\nexports.AuthorizationPendingException$ = AuthorizationPendingException$;\nexports.CreateToken$ = CreateToken$;\nexports.CreateTokenCommand = CreateTokenCommand;\nexports.CreateTokenRequest$ = CreateTokenRequest$;\nexports.CreateTokenResponse$ = CreateTokenResponse$;\nexports.ExpiredTokenException = ExpiredTokenException;\nexports.ExpiredTokenException$ = ExpiredTokenException$;\nexports.InternalServerException = InternalServerException;\nexports.InternalServerException$ = InternalServerException$;\nexports.InvalidClientException = InvalidClientException;\nexports.InvalidClientException$ = InvalidClientException$;\nexports.InvalidGrantException = InvalidGrantException;\nexports.InvalidGrantException$ = InvalidGrantException$;\nexports.InvalidRequestException = InvalidRequestException;\nexports.InvalidRequestException$ = InvalidRequestException$;\nexports.InvalidRequestExceptionReason = InvalidRequestExceptionReason;\nexports.InvalidScopeException = InvalidScopeException;\nexports.InvalidScopeException$ = InvalidScopeException$;\nexports.SSOOIDC = SSOOIDC;\nexports.SSOOIDCClient = SSOOIDCClient;\nexports.SSOOIDCServiceException = SSOOIDCServiceException;\nexports.SSOOIDCServiceException$ = SSOOIDCServiceException$;\nexports.SlowDownException = SlowDownException;\nexports.SlowDownException$ = SlowDownException$;\nexports.UnauthorizedClientException = UnauthorizedClientException;\nexports.UnauthorizedClientException$ = UnauthorizedClientException$;\nexports.UnsupportedGrantTypeException = UnsupportedGrantTypeException;\nexports.UnsupportedGrantTypeException$ = UnsupportedGrantTypeException$;\nexports.errorTypeRegistries = errorTypeRegistries;\n" | ||
| ], | ||
| "mappings": ";uXAAA,IAAQ,wBAAsB,gCAAiC,GAAmC,kCAAgC,8BAA4B,sCAAoC,0CAAwC,0BAAwB,2BAAyB,sBAAoB,uBAAqB,mBAAiB,sCAC7U,gBAAc,0CAAwC,iCAA+B,+BACrF,oBAAmB,oBAAkB,oBAAkB,cAAY,mCAAiC,6BAA2B,oCAAkC,+BAA6B,SAAQ,eAAa,gCACnN,QAAS,QACjB,IAAQ,GAAW,GACX,GAAW,EACnB,IAAQ,6BAA2B,aAAY,yCAAuC,8CAA4C,8BAA4B,mCAAiC,8BACvL,yBAAuB,iBAAe,kBAAgB,2BAAyB,yBAAuB,4BACtG,YAAU,wCAAsC,mCAAiC,iCACjF,sBAAoB,kCAAgC,mCAAiC,sBAAoB,yBACzG,eAAc,+BACd,4BAA0B,qBAAmB,8CAC7C,UAAQ,YAAU,YAAU,cAAY,8BACxC,mBAAiB,0BACjB,8BACA,gBAEF,GAAiD,MAAO,EAAQ,EAAS,KACpE,CACH,UAAW,GAAiB,CAAO,EAAE,UACrC,OAAQ,MAAM,EAAkB,EAAO,MAAM,EAAE,IAAM,IAAM,CACvD,MAAU,MAAM,yDAAyD,IAC1E,CACP,GAEJ,SAAS,EAAgC,CAAC,EAAgB,CACtD,MAAO,CACH,SAAU,iBACV,kBAAmB,CACf,KAAM,YACN,OAAQ,EAAe,MAC3B,EACA,oBAAqB,CAAC,EAAQ,KAAa,CACvC,kBAAmB,CACf,SACA,SACJ,CACJ,EACJ,EAEJ,SAAS,EAAmC,CA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+BACvB,kBAAmB,4BACnB,kBAAmB,uBACvB,EAEA,IAAQ,GAAwB,EACxB,GAAyB,EACzB,GAA8B,GAC9B,GAAgC,EAChC,GAAiC,EACjC,GAAe,GACf,GAAqB,EACrB,GAAsB,GACtB,GAAuB,GACvB,GAAwB,EACxB,GAAyB,GACzB,GAA0B,EAC1B,GAA2B,GAC3B,GAAyB,EACzB,GAA0B,GAC1B,GAAwB,EACxB,GAAyB,GACzB,GAA0B,EAC1B,GAA2B,GAC3B,GAAgC,GAChC,GAAwB,EACxB,GAAyB,GACzB,GAAU,EACV,GAAgB,EAChB,GAA0B,EAC1B,GAA2B,EAC3B,GAAoB,EACpB,GAAqB,GACrB,GAA8B,EAC9B,GAA+B,GAC/B,GAAgC,EAChC,GAAiC,GACjC,GAAsB", | ||
| "debugId": "DDE4B7F28012DA3364756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../protocol/src/client.ts"], | ||
| "sourcesContent": [ | ||
| "import { InvalidRequestError, SessionNotFoundError } from \"./errors.js\"\nimport { makeDefaultApi } from \"./api.js\"\nimport type { Api } from \"./api.js\"\nimport type { Context } from \"effect\"\nimport { HttpApiMiddleware } from \"effect/unstable/httpapi\"\nimport type { EventGroup } from \"./groups/event.js\"\n\nclass LocationMiddleware extends HttpApiMiddleware.Service<LocationMiddleware>()(\n \"@opencode-ai/client/LocationMiddleware\",\n) {}\n\nclass SessionLocationMiddleware extends HttpApiMiddleware.Service<SessionLocationMiddleware>()(\n \"@opencode-ai/client/SessionLocationMiddleware\",\n { error: [InvalidRequestError, SessionNotFoundError] },\n) {}\n\ntype ClientApiShape = Api<\n Context.Service.Identifier<typeof LocationMiddleware>,\n Context.Service.Shape<typeof LocationMiddleware>,\n Context.Service.Identifier<typeof SessionLocationMiddleware>,\n Context.Service.Shape<typeof SessionLocationMiddleware>,\n Context.Service.Identifier<typeof SessionLocationMiddleware>,\n Context.Service.Shape<typeof SessionLocationMiddleware>,\n typeof EventGroup\n>\n\nexport const ClientApi: ClientApiShape = makeDefaultApi({\n locationMiddleware: LocationMiddleware,\n // The real server uses a form-specific middleware with an undocumented `global` sentinel branch.\n // The generated client only needs a middleware identity for API typing.\n formLocationMiddleware: SessionLocationMiddleware,\n sessionLocationMiddleware: SessionLocationMiddleware,\n})\n\nexport const groupNames = {\n \"server.health\": \"health\",\n \"server.server\": \"server\",\n \"server.debug\": \"debug\",\n \"server.migration\": \"migration\",\n \"server.location\": \"location\",\n \"server.agent\": \"agent\",\n \"server.plugin\": \"plugin\",\n \"server.session\": \"session\",\n \"server.message\": \"message\",\n \"server.model\": \"model\",\n \"server.generate\": \"generate\",\n \"server.provider\": \"provider\",\n \"server.integration\": \"integration\",\n \"server.websearch\": \"websearch\",\n \"server.credential\": \"credential\",\n \"server.form\": \"form\",\n \"server.permission\": \"permission\",\n \"server.fs\": \"file\",\n \"server.command\": \"command\",\n \"server.skill\": \"skill\",\n \"server.rpc\": \"rpc\",\n \"server.event\": \"event\",\n \"server.pty\": \"pty\",\n \"server.experimental\": \"experimental\",\n \"server.shell\": \"shell\",\n \"server.mcp\": \"mcp\",\n \"server.reference\": \"reference\",\n \"server.project\": \"project\",\n \"server.worktree\": \"worktree\",\n \"server.workspace\": \"workspace\",\n \"server.vcs\": \"vcs\",\n \"server.config\": \"config\",\n} as const\n\nexport const promiseOmitEndpoints = new Set([\"pty.connect\", \"persistentPty.connect\"])\nexport const effectOmitEndpoints = new Set([\"fs.read\", \"pty.connect\", \"persistentPty.connect\"])\n" | ||
| ], | ||
| "mappings": ";kuCAOA,MAAM,UAA2B,EAAkB,QAA4B,EAC7E,wCACF,CAAE,CAAC,CAEH,MAAM,UAAkC,EAAkB,QAAmC,EAC3F,gDACA,CAAE,MAAO,CAAC,EAAqB,CAAoB,CAAE,CACvD,CAAE,CAAC,CAYI,IAAM,EAA4B,EAAe,CACtD,mBAAoB,EAGpB,uBAAwB,EACxB,0BAA2B,CAC7B,CAAC,EAEY,EAAa,CACxB,gBAAiB,SACjB,gBAAiB,SACjB,eAAgB,QAChB,mBAAoB,YACpB,kBAAmB,WACnB,eAAgB,QAChB,gBAAiB,SACjB,iBAAkB,UAClB,iBAAkB,UAClB,eAAgB,QAChB,kBAAmB,WACnB,kBAAmB,WACnB,qBAAsB,cACtB,mBAAoB,YACpB,oBAAqB,aACrB,cAAe,OACf,oBAAqB,aACrB,YAAa,OACb,iBAAkB,UAClB,eAAgB,QAChB,aAAc,MACd,eAAgB,QAChB,aAAc,MACd,sBAAuB,eACvB,eAAgB,QAChB,aAAc,MACd,mBAAoB,YACpB,iBAAkB,UAClB,kBAAmB,WACnB,mBAAoB,YACpB,aAAc,MACd,gBAAiB,QACnB,EAEa,EAAuB,IAAI,IAAI,CAAC,cAAe,uBAAuB,CAAC,EACvE,EAAsB,IAAI,IAAI,CAAC,UAAW,cAAe,uBAAuB,CAAC", | ||
| "debugId": "1A223001AAF0ED7B64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+perplexity@3.0.26+d6123d32214422cb/node_modules/@ai-sdk/perplexity/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/perplexity-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n generateId,\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/perplexity-language-model.ts\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonErrorResponseHandler,\n createJsonResponseHandler,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z } from \"zod/v4\";\n\n// src/convert-perplexity-usage.ts\nfunction convertPerplexityUsage(usage) {\n var _a, _b, _c;\n if (usage == null) {\n return {\n inputTokens: {\n total: void 0,\n noCache: void 0,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: void 0,\n text: void 0,\n reasoning: void 0\n },\n raw: void 0\n };\n }\n const promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0;\n const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;\n const reasoningTokens = (_c = usage.reasoning_tokens) != null ? _c : 0;\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: completionTokens,\n text: completionTokens - reasoningTokens,\n reasoning: reasoningTokens\n },\n raw: usage\n };\n}\n\n// src/convert-to-perplexity-messages.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\nimport { convertUint8ArrayToBase64 } from \"@ai-sdk/provider-utils\";\nfunction convertToPerplexityMessages(prompt) {\n const messages = [];\n for (const { role, content } of prompt) {\n switch (role) {\n case \"system\": {\n messages.push({ role: \"system\", content });\n break;\n }\n case \"user\":\n case \"assistant\": {\n const hasMultipartContent = content.some(\n (part) => part.type === \"file\" && part.mediaType.startsWith(\"image/\") || part.type === \"file\" && part.mediaType === \"application/pdf\"\n );\n const messageContent = content.map((part, index) => {\n var _a;\n switch (part.type) {\n case \"text\": {\n return {\n type: \"text\",\n text: part.text\n };\n }\n case \"file\": {\n if (part.mediaType === \"application/pdf\") {\n return part.data instanceof URL ? {\n type: \"file_url\",\n file_url: {\n url: part.data.toString()\n },\n file_name: part.filename\n } : {\n type: \"file_url\",\n file_url: {\n url: typeof part.data === \"string\" ? part.data : convertUint8ArrayToBase64(part.data)\n },\n file_name: part.filename || `document-${index}.pdf`\n };\n } else if (part.mediaType.startsWith(\"image/\")) {\n return part.data instanceof URL ? {\n type: \"image_url\",\n image_url: {\n url: part.data.toString()\n }\n } : {\n type: \"image_url\",\n image_url: {\n url: `data:${(_a = part.mediaType) != null ? _a : \"image/jpeg\"};base64,${typeof part.data === \"string\" ? part.data : convertUint8ArrayToBase64(part.data)}`\n }\n };\n }\n }\n }\n }).filter(Boolean);\n messages.push({\n role,\n content: hasMultipartContent ? messageContent : messageContent.filter((part) => part.type === \"text\").map((part) => part.text).join(\"\")\n });\n break;\n }\n case \"tool\": {\n throw new UnsupportedFunctionalityError({\n functionality: \"Tool messages\"\n });\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return messages;\n}\n\n// src/map-perplexity-finish-reason.ts\nfunction mapPerplexityFinishReason(finishReason) {\n switch (finishReason) {\n case \"stop\":\n case \"length\":\n return finishReason;\n default:\n return \"other\";\n }\n}\n\n// src/perplexity-language-model.ts\nvar PerplexityLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.provider = \"perplexity\";\n this.supportedUrls = {\n // No URLs are supported.\n };\n this.modelId = modelId;\n this.config = config;\n }\n getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n providerOptions\n }) {\n var _a;\n const warnings = [];\n if (topK != null) {\n warnings.push({ type: \"unsupported\", feature: \"topK\" });\n }\n if (stopSequences != null) {\n warnings.push({ type: \"unsupported\", feature: \"stopSequences\" });\n }\n if (seed != null) {\n warnings.push({ type: \"unsupported\", feature: \"seed\" });\n }\n return {\n args: {\n // model id:\n model: this.modelId,\n // standardized settings:\n frequency_penalty: frequencyPenalty,\n max_tokens: maxOutputTokens,\n presence_penalty: presencePenalty,\n temperature,\n top_k: topK,\n top_p: topP,\n // response format:\n response_format: (responseFormat == null ? void 0 : responseFormat.type) === \"json\" ? {\n type: \"json_schema\",\n json_schema: { schema: responseFormat.schema }\n } : void 0,\n // provider extensions\n ...(_a = providerOptions == null ? void 0 : providerOptions.perplexity) != null ? _a : {},\n // messages:\n messages: convertToPerplexityMessages(prompt)\n },\n warnings\n };\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;\n const { args: body, warnings } = this.getArgs(options);\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: perplexityErrorSchema,\n errorToMessage\n }),\n successfulResponseHandler: createJsonResponseHandler(\n perplexityResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const choice = response.choices[0];\n const content = [];\n const text = choice.message.content;\n if (text.length > 0) {\n content.push({ type: \"text\", text });\n }\n if (response.citations != null) {\n for (const url of response.citations) {\n content.push({\n type: \"source\",\n sourceType: \"url\",\n id: this.config.generateId(),\n url\n });\n }\n }\n return {\n content,\n finishReason: {\n unified: mapPerplexityFinishReason(choice.finish_reason),\n raw: (_a = choice.finish_reason) != null ? _a : void 0\n },\n usage: convertPerplexityUsage(response.usage),\n request: { body },\n response: {\n ...getResponseMetadata(response),\n headers: responseHeaders,\n body: rawResponse\n },\n warnings,\n providerMetadata: {\n perplexity: {\n images: (_c = (_b = response.images) == null ? void 0 : _b.map((image) => ({\n imageUrl: image.image_url,\n originUrl: image.origin_url,\n height: image.height,\n width: image.width\n }))) != null ? _c : null,\n usage: {\n citationTokens: (_e = (_d = response.usage) == null ? void 0 : _d.citation_tokens) != null ? _e : null,\n numSearchQueries: (_g = (_f = response.usage) == null ? void 0 : _f.num_search_queries) != null ? _g : null\n },\n cost: ((_h = response.usage) == null ? void 0 : _h.cost) ? {\n inputTokensCost: (_i = response.usage.cost.input_tokens_cost) != null ? _i : null,\n outputTokensCost: (_j = response.usage.cost.output_tokens_cost) != null ? _j : null,\n requestCost: (_k = response.usage.cost.request_cost) != null ? _k : null,\n totalCost: (_l = response.usage.cost.total_cost) != null ? _l : null\n } : null\n }\n }\n };\n }\n async doStream(options) {\n const { args, warnings } = this.getArgs(options);\n const body = { ...args, stream: true };\n const { responseHeaders, value: response } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: perplexityErrorSchema,\n errorToMessage\n }),\n successfulResponseHandler: createEventSourceResponseHandler(\n perplexityChunkSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n let usage = void 0;\n const providerMetadata = {\n perplexity: {\n usage: {\n citationTokens: null,\n numSearchQueries: null\n },\n cost: null,\n images: null\n }\n };\n let isFirstChunk = true;\n let isActive = false;\n const self = this;\n return {\n stream: response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n var _a, _b, _c, _d, _e, _f, _g;\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n if (isFirstChunk) {\n controller.enqueue({\n type: \"response-metadata\",\n ...getResponseMetadata(value)\n });\n (_a = value.citations) == null ? void 0 : _a.forEach((url) => {\n controller.enqueue({\n type: \"source\",\n sourceType: \"url\",\n id: self.config.generateId(),\n url\n });\n });\n isFirstChunk = false;\n }\n if (value.usage != null) {\n usage = value.usage;\n providerMetadata.perplexity.usage = {\n citationTokens: (_b = value.usage.citation_tokens) != null ? _b : null,\n numSearchQueries: (_c = value.usage.num_search_queries) != null ? _c : null\n };\n providerMetadata.perplexity.cost = value.usage.cost ? {\n inputTokensCost: (_d = value.usage.cost.input_tokens_cost) != null ? _d : null,\n outputTokensCost: (_e = value.usage.cost.output_tokens_cost) != null ? _e : null,\n requestCost: (_f = value.usage.cost.request_cost) != null ? _f : null,\n totalCost: (_g = value.usage.cost.total_cost) != null ? _g : null\n } : null;\n }\n if (value.images != null) {\n providerMetadata.perplexity.images = value.images.map((image) => ({\n imageUrl: image.image_url,\n originUrl: image.origin_url,\n height: image.height,\n width: image.width\n }));\n }\n const choice = value.choices[0];\n if ((choice == null ? void 0 : choice.finish_reason) != null) {\n finishReason = {\n unified: mapPerplexityFinishReason(choice.finish_reason),\n raw: choice.finish_reason\n };\n }\n if ((choice == null ? void 0 : choice.delta) == null) {\n return;\n }\n const delta = choice.delta;\n const textContent = delta.content;\n if (textContent != null) {\n if (!isActive) {\n controller.enqueue({ type: \"text-start\", id: \"0\" });\n isActive = true;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: \"0\",\n delta: textContent\n });\n }\n },\n flush(controller) {\n if (isActive) {\n controller.enqueue({ type: \"text-end\", id: \"0\" });\n }\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertPerplexityUsage(usage),\n providerMetadata\n });\n }\n })\n ),\n request: { body },\n response: { headers: responseHeaders }\n };\n }\n};\nfunction getResponseMetadata({\n id,\n model,\n created\n}) {\n return {\n id,\n modelId: model,\n timestamp: new Date(created * 1e3)\n };\n}\nvar perplexityCostSchema = z.object({\n input_tokens_cost: z.number().nullish(),\n output_tokens_cost: z.number().nullish(),\n request_cost: z.number().nullish(),\n total_cost: z.number().nullish()\n});\nvar perplexityUsageSchema = z.object({\n prompt_tokens: z.number(),\n completion_tokens: z.number(),\n total_tokens: z.number().nullish(),\n citation_tokens: z.number().nullish(),\n num_search_queries: z.number().nullish(),\n reasoning_tokens: z.number().nullish(),\n cost: perplexityCostSchema.nullish()\n});\nvar perplexityImageSchema = z.object({\n image_url: z.string(),\n origin_url: z.string(),\n height: z.number(),\n width: z.number()\n});\nvar perplexityResponseSchema = z.object({\n id: z.string(),\n created: z.number(),\n model: z.string(),\n choices: z.array(\n z.object({\n message: z.object({\n role: z.literal(\"assistant\"),\n content: z.string()\n }),\n finish_reason: z.string().nullish()\n })\n ),\n citations: z.array(z.string()).nullish(),\n images: z.array(perplexityImageSchema).nullish(),\n usage: perplexityUsageSchema.nullish()\n});\nvar perplexityChunkSchema = z.object({\n id: z.string(),\n created: z.number(),\n model: z.string(),\n choices: z.array(\n z.object({\n delta: z.object({\n role: z.literal(\"assistant\"),\n content: z.string()\n }),\n finish_reason: z.string().nullish()\n })\n ),\n citations: z.array(z.string()).nullish(),\n images: z.array(perplexityImageSchema).nullish(),\n usage: perplexityUsageSchema.nullish()\n});\nvar perplexityErrorSchema = z.object({\n error: z.object({\n code: z.number(),\n message: z.string().nullish(),\n type: z.string().nullish()\n })\n});\nvar errorToMessage = (data) => {\n var _a, _b;\n return (_b = (_a = data.error.message) != null ? _a : data.error.type) != null ? _b : \"unknown error\";\n};\n\n// src/version.ts\nvar VERSION = true ? \"3.0.26\" : \"0.0.0-test\";\n\n// src/perplexity-provider.ts\nfunction createPerplexity(options = {}) {\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"PERPLEXITY_API_KEY\",\n description: \"Perplexity\"\n })}`,\n ...options.headers\n },\n `ai-sdk/perplexity/${VERSION}`\n );\n const createLanguageModel = (modelId) => {\n var _a;\n return new PerplexityLanguageModel(modelId, {\n baseURL: withoutTrailingSlash(\n (_a = options.baseURL) != null ? _a : \"https://api.perplexity.ai\"\n ),\n headers: getHeaders,\n generateId,\n fetch: options.fetch\n });\n };\n const provider = (modelId) => createLanguageModel(modelId);\n provider.specificationVersion = \"v3\";\n provider.languageModel = createLanguageModel;\n provider.embeddingModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar perplexity = createPerplexity();\nexport {\n VERSION,\n createPerplexity,\n perplexity\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";wYAsBA,SAAS,CAAsB,CAAC,EAAO,CACrC,IAAI,EAAI,EAAI,EACZ,GAAI,GAAS,KACX,MAAO,CACL,YAAa,CACX,MAAY,OACZ,QAAc,OACd,UAAgB,OAChB,WAAiB,MACnB,EACA,aAAc,CACZ,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,OACE,EAAQ,OACb,EACA,qBAAqB,GACvB,EACM,EAAsB,CAAC,IAAY,CACvC,IAAI,EACJ,OAAO,IAAI,EAAwB,EAAS,CAC1C,QAAS,GACN,EAAK,EAAQ,UAAY,KAAO,EAAK,2BACxC,EACA,QAAS,EACT,aACA,MAAO,EAAQ,KACjB,CAAC,GAEG,EAAW,CAAC,IAAY,EAAoB,CAAO,EAUzD,OATA,EAAS,qBAAuB,KAChC,EAAS,cAAgB,EACzB,EAAS,eAAiB,CAAC,IAAY,CACrC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,gBAAiB,CAAC,GAErE,EAAS,mBAAqB,EAAS,eACvC,EAAS,WAAa,CAAC,IAAY,CACjC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,YAAa,CAAC,GAE1D,EAET,IAAI,GAAa,EAAiB", | ||
| "debugId": "4C3939342F8BC2D064756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "399D41173AEABBC064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/ai-gateway-provider@3.1.2+cd874a64d6146f19/node_modules/ai-gateway-provider/dist/providers/unified.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/providers/unified.ts\nimport { createOpenAICompatible } from \"@ai-sdk/openai-compatible\";\nvar createUnified = (arg) => {\n return createOpenAICompatible({\n baseURL: \"https://gateway.ai.cloudflare.com/v1/compat\",\n // intercepted and replaced with actual base URL later\n name: \"Unified\",\n ...arg || {}\n });\n};\nvar unified = createUnified();\nexport {\n createUnified,\n unified\n};\n//# sourceMappingURL=unified.mjs.map" | ||
| ], | ||
| "mappings": ";qUAEA,IAAI,EAAgB,CAAC,IACZ,EAAuB,CAC5B,QAAS,8CAET,KAAM,aACH,GAAO,CAAC,CACb,CAAC,EAEC,EAAU,EAAc", | ||
| "debugId": "27634B47AD0D39F864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/set.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Option } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.set,\n Effect.fn(\"cli.service.set\")(function* (input) {\n yield* ServiceConfig.set(input.key, input.value, Option.getOrUndefined(input.nestedValue))\n }),\n)\n" | ||
| ], | ||
| "mappings": ";i5BAKA,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,IACnC,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAAO,CAC7C,MAAO,EAAc,IAAI,EAAM,IAAK,EAAM,MAAO,EAAO,eAAe,EAAM,WAAW,CAAC,EAC1F,CACH", | ||
| "debugId": "D0C67B3B5E67130964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/auth/list.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { createClient, loadIntegrations } from \"./shared\"\nimport { errorMessage } from \"../../../util/error\"\n\nexport default Runtime.handler(Commands.commands.auth.commands.list, (input) =>\n list(input).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n process.stderr.write(errorMessage(error) + EOL)\n process.exitCode = 1\n }),\n ),\n ),\n)\n\nconst list = Effect.fn(\"cli.auth.list\")(function* (input) {\n const client = yield* createClient({ server: Option.getOrUndefined(input.server), standalone: input.standalone })\n const integrations = (yield* loadIntegrations(client)).filter((integration) => integration.connections.length > 0)\n if (input.format === \"json\") {\n process.stdout.write(\n JSON.stringify(\n integrations.map((integration) => ({\n id: integration.id,\n name: integration.name,\n connections: integration.connections,\n })),\n null,\n 2,\n ) + EOL,\n )\n return\n }\n const rows = integrations.flatMap((integration) =>\n integration.connections.map((connection) => ({\n integration: integration.name,\n source: connection.type === \"credential\" ? connection.label : connection.name,\n type: connection.type === \"credential\" ? \"stored\" : \"environment\",\n })),\n )\n if (rows.length === 0) {\n process.stdout.write(\"No authenticated integrations\" + EOL)\n return\n }\n const width = Math.max(...rows.map((row) => row.integration.length)) + 2\n process.stdout.write(\n rows.map((row) => row.integration.padEnd(width) + row.source.padEnd(28) + row.type).join(EOL) + EOL,\n )\n})\n" | ||
| ], | ||
| "mappings": ";gpCAAA,cAAS,WAOT,IAAe,IAAQ,QAAQ,EAAS,SAAS,KAAK,SAAS,KAAM,CAAC,IACpE,EAAK,CAAK,EAAE,KACV,EAAO,MAAM,CAAC,IACZ,EAAO,KAAK,IAAM,CAChB,QAAQ,OAAO,MAAM,EAAa,CAAK,EAAI,CAAG,EAC9C,QAAQ,SAAW,EACpB,CACH,CACF,CACF,EAEM,EAAO,EAAO,GAAG,eAAe,EAAE,SAAU,CAAC,EAAO,CACxD,IAAM,EAAS,MAAO,EAAa,CAAE,OAAQ,EAAO,eAAe,EAAM,MAAM,EAAG,WAAY,EAAM,UAAW,CAAC,EAC1G,GAAgB,MAAO,EAAiB,CAAM,GAAG,OAAO,CAAC,IAAgB,EAAY,YAAY,OAAS,CAAC,EACjH,GAAI,EAAM,SAAW,OAAQ,CAC3B,QAAQ,OAAO,MACb,KAAK,UACH,EAAa,IAAI,CAAC,KAAiB,CACjC,GAAI,EAAY,GAChB,KAAM,EAAY,KAClB,YAAa,EAAY,WAC3B,EAAE,EACF,KACA,CACF,EAAI,CACN,EACA,OAEF,IAAM,EAAO,EAAa,QAAQ,CAAC,IACjC,EAAY,YAAY,IAAI,CAAC,KAAgB,CAC3C,YAAa,EAAY,KACzB,OAAQ,EAAW,OAAS,aAAe,EAAW,MAAQ,EAAW,KACzE,KAAM,EAAW,OAAS,aAAe,SAAW,aACtD,EAAE,CACJ,EACA,GAAI,EAAK,SAAW,EAAG,CACrB,QAAQ,OAAO,MAAM,gCAAkC,CAAG,EAC1D,OAEF,IAAM,EAAQ,KAAK,IAAI,GAAG,EAAK,IAAI,CAAC,IAAQ,EAAI,YAAY,MAAM,CAAC,EAAI,EACvE,QAAQ,OAAO,MACb,EAAK,IAAI,CAAC,IAAQ,EAAI,YAAY,OAAO,CAAK,EAAI,EAAI,OAAO,OAAO,EAAE,EAAI,EAAI,IAAI,EAAE,KAAK,CAAG,EAAI,CAClG,EACD", | ||
| "debugId": "975346A42302DBE364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "D1050E4F49B3A6BF64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/errors/ai-sdk-error.ts\nvar marker = \"vercel.ai.error\";\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {\n /**\n * Creates an AI SDK Error.\n *\n * @param {Object} params - The parameters for creating the error.\n * @param {string} params.name - The name of the error.\n * @param {string} params.message - The error message.\n * @param {unknown} [params.cause] - The underlying cause of the error.\n */\n constructor({\n name: name14,\n message,\n cause\n }) {\n super(message);\n this[_a] = true;\n this.name = name14;\n this.cause = cause;\n }\n /**\n * Checks if the given error is an AI SDK Error.\n * @param {unknown} error - The error to check.\n * @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n */\n static isInstance(error) {\n return _AISDKError.hasMarker(error, marker);\n }\n static hasMarker(error, marker15) {\n const markerSymbol = Symbol.for(marker15);\n return error != null && typeof error === \"object\" && markerSymbol in error && typeof error[markerSymbol] === \"boolean\" && error[markerSymbol] === true;\n }\n};\n\n// src/errors/api-call-error.ts\nvar name = \"AI_APICallError\";\nvar marker2 = `vercel.ai.error.${name}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2, _b2;\nvar APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {\n constructor({\n message,\n url,\n requestBodyValues,\n statusCode,\n responseHeaders,\n responseBody,\n cause,\n isRetryable = statusCode != null && (statusCode === 408 || // request timeout\n statusCode === 409 || // conflict\n statusCode === 429 || // too many requests\n statusCode >= 500),\n // server error\n data\n }) {\n super({ name, message, cause });\n this[_a2] = true;\n this.url = url;\n this.requestBodyValues = requestBodyValues;\n this.statusCode = statusCode;\n this.responseHeaders = responseHeaders;\n this.responseBody = responseBody;\n this.isRetryable = isRetryable;\n this.data = data;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker2);\n }\n};\n\n// src/errors/empty-response-body-error.ts\nvar name2 = \"AI_EmptyResponseBodyError\";\nvar marker3 = `vercel.ai.error.${name2}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3, _b3;\nvar EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {\n // used in isInstance\n constructor({ message = \"Empty response body\" } = {}) {\n super({ name: name2, message });\n this[_a3] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker3);\n }\n};\n\n// src/errors/get-error-message.ts\nfunction getErrorMessage(error) {\n if (error == null) {\n return \"unknown error\";\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error instanceof Error) {\n return error.message;\n }\n return JSON.stringify(error);\n}\n\n// src/errors/invalid-argument-error.ts\nvar name3 = \"AI_InvalidArgumentError\";\nvar marker4 = `vercel.ai.error.${name3}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4, _b4;\nvar InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {\n constructor({\n message,\n cause,\n argument\n }) {\n super({ name: name3, message, cause });\n this[_a4] = true;\n this.argument = argument;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker4);\n }\n};\n\n// src/errors/invalid-prompt-error.ts\nvar name4 = \"AI_InvalidPromptError\";\nvar marker5 = `vercel.ai.error.${name4}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5, _b5;\nvar InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {\n constructor({\n prompt,\n message,\n cause\n }) {\n super({ name: name4, message: `Invalid prompt: ${message}`, cause });\n this[_a5] = true;\n this.prompt = prompt;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker5);\n }\n};\n\n// src/errors/invalid-response-data-error.ts\nvar name5 = \"AI_InvalidResponseDataError\";\nvar marker6 = `vercel.ai.error.${name5}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6, _b6;\nvar InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {\n constructor({\n data,\n message = `Invalid response data: ${JSON.stringify(data)}.`\n }) {\n super({ name: name5, message });\n this[_a6] = true;\n this.data = data;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker6);\n }\n};\n\n// src/errors/json-parse-error.ts\nvar name6 = \"AI_JSONParseError\";\nvar marker7 = `vercel.ai.error.${name6}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7, _b7;\nvar JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {\n constructor({ text, cause }) {\n super({\n name: name6,\n message: `JSON parsing failed: Text: ${text}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a7] = true;\n this.text = text;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker7);\n }\n};\n\n// src/errors/load-api-key-error.ts\nvar name7 = \"AI_LoadAPIKeyError\";\nvar marker8 = `vercel.ai.error.${name7}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8, _b8;\nvar LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name7, message });\n this[_a8] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker8);\n }\n};\n\n// src/errors/load-setting-error.ts\nvar name8 = \"AI_LoadSettingError\";\nvar marker9 = `vercel.ai.error.${name8}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9, _b9;\nvar LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name8, message });\n this[_a9] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker9);\n }\n};\n\n// src/errors/no-content-generated-error.ts\nvar name9 = \"AI_NoContentGeneratedError\";\nvar marker10 = `vercel.ai.error.${name9}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10, _b10;\nvar NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {\n // used in isInstance\n constructor({\n message = \"No content generated.\"\n } = {}) {\n super({ name: name9, message });\n this[_a10] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker10);\n }\n};\n\n// src/errors/no-such-model-error.ts\nvar name10 = \"AI_NoSuchModelError\";\nvar marker11 = `vercel.ai.error.${name10}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11, _b11;\nvar NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {\n constructor({\n errorName = name10,\n modelId,\n modelType,\n message = `No such ${modelType}: ${modelId}`\n }) {\n super({ name: errorName, message });\n this[_a11] = true;\n this.modelId = modelId;\n this.modelType = modelType;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker11);\n }\n};\n\n// src/errors/too-many-embedding-values-for-call-error.ts\nvar name11 = \"AI_TooManyEmbeddingValuesForCallError\";\nvar marker12 = `vercel.ai.error.${name11}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12, _b12;\nvar TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {\n constructor(options) {\n super({\n name: name11,\n message: `Too many values for a single embedding call. The ${options.provider} model \"${options.modelId}\" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`\n });\n this[_a12] = true;\n this.provider = options.provider;\n this.modelId = options.modelId;\n this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n this.values = options.values;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker12);\n }\n};\n\n// src/errors/type-validation-error.ts\nvar name12 = \"AI_TypeValidationError\";\nvar marker13 = `vercel.ai.error.${name12}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13, _b13;\nvar TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {\n constructor({\n value,\n cause,\n context\n }) {\n let contextPrefix = \"Type validation failed\";\n if (context == null ? void 0 : context.field) {\n contextPrefix += ` for ${context.field}`;\n }\n if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {\n contextPrefix += \" (\";\n const parts = [];\n if (context.entityName) {\n parts.push(context.entityName);\n }\n if (context.entityId) {\n parts.push(`id: \"${context.entityId}\"`);\n }\n contextPrefix += parts.join(\", \");\n contextPrefix += \")\";\n }\n super({\n name: name12,\n message: `${contextPrefix}: Value: ${JSON.stringify(value)}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a13] = true;\n this.value = value;\n this.context = context;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker13);\n }\n /**\n * Wraps an error into a TypeValidationError.\n * If the cause is already a TypeValidationError with the same value and context, it returns the cause.\n * Otherwise, it creates a new TypeValidationError.\n *\n * @param {Object} params - The parameters for wrapping the error.\n * @param {unknown} params.value - The value that failed validation.\n * @param {unknown} params.cause - The original error or cause of the validation failure.\n * @param {TypeValidationContext} params.context - Optional context about what is being validated.\n * @returns {TypeValidationError} A TypeValidationError instance.\n */\n static wrap({\n value,\n cause,\n context\n }) {\n var _a15, _b15, _c;\n if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a15 = cause.context) == null ? void 0 : _a15.field) === (context == null ? void 0 : context.field) && ((_b15 = cause.context) == null ? void 0 : _b15.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) {\n return cause;\n }\n return new _TypeValidationError({ value, cause, context });\n }\n};\n\n// src/errors/unsupported-functionality-error.ts\nvar name13 = \"AI_UnsupportedFunctionalityError\";\nvar marker14 = `vercel.ai.error.${name13}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14, _b14;\nvar UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {\n constructor({\n functionality,\n message = `'${functionality}' functionality not supported.`\n }) {\n super({ name: name13, message });\n this[_a14] = true;\n this.functionality = functionality;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker14);\n }\n};\n\n// src/json-value/is-json.ts\nfunction isJSONValue(value) {\n if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return true;\n }\n if (Array.isArray(value)) {\n return value.every(isJSONValue);\n }\n if (typeof value === \"object\") {\n return Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n }\n return false;\n}\nfunction isJSONArray(value) {\n return Array.isArray(value) && value.every(isJSONValue);\n}\nfunction isJSONObject(value) {\n return value != null && typeof value === \"object\" && Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n}\nexport {\n AISDKError,\n APICallError,\n EmptyResponseBodyError,\n InvalidArgumentError,\n InvalidPromptError,\n InvalidResponseDataError,\n JSONParseError,\n LoadAPIKeyError,\n LoadSettingError,\n NoContentGeneratedError,\n NoSuchModelError,\n TooManyEmbeddingValuesForCallError,\n TypeValidationError,\n UnsupportedFunctionalityError,\n getErrorMessage,\n isJSONArray,\n isJSONObject,\n isJSONValue\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";AACA,IAAI,EAAS,kBACT,GAAS,OAAO,IAAI,CAAM,EAC1B,EAAI,EACJ,EAAa,MAAM,U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AC9C,EAAgB,CAAK,IAChC,OACF,CAAC,EACD,KAAK,GAAQ,GACb,KAAK,MAAQ,EACb,KAAK,QAAU,QAEV,WAAU,CAAC,EAAO,CACvB,OAAO,EAAW,UAAU,EAAO,EAAQ,QAatC,KAAI,EACT,QACA,QACA,WACC,CACD,IAAI,EAAM,EAAM,EAChB,GAAI,EAAqB,WAAW,CAAK,GAAK,EAAM,QAAU,KAAW,EAAO,EAAM,UAAY,KAAY,OAAI,EAAK,UAAY,GAAW,KAAY,OAAI,EAAQ,UAAY,EAAO,EAAM,UAAY,KAAY,OAAI,EAAK,eAAiB,GAAW,KAAY,OAAI,EAAQ,eAAiB,EAAK,EAAM,UAAY,KAAY,OAAI,EAAG,aAAe,GAAW,KAAY,OAAI,EAAQ,UAC/X,OAAO,EAET,OAAO,IAAI,EAAqB,CAAE,QAAO,QAAO,SAAQ,CAAC,EAE7D,EAGI,GAAS,mCACT,GAAW,mBAAmB,KAC9B,GAAW,OAAO,IAAI,EAAQ,EAC9B,EAAM,EACN,GAAgC,cAAe,EAAO,EAAY,EAAO,GAAU,EAAM,CAC3F,WAAW,EACT,gBACA,UAAU,IAAI,mCACb,CACD,MAAM,CAAE,KAAM,GAAQ,SAAQ,CAAC,EAC/B,KAAK,GAAQ,GACb,KAAK,cAAgB,QAEhB,WAAU,CAAC,EAAO,CACvB,OAAO,EAAW,UAAU,EAAO,EAAQ,EAE/C", | ||
| "debugId": "2C4F82FD6B5678EF64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-web-identity@3.972.75/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromTokenFile.js", "../../node_modules/.bun/@aws-sdk+credential-provider-web-identity@3.972.75/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromWebToken.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError, externalDataInterceptor } from \"@smithy/core/config\";\nimport { readFileSync } from \"node:fs\";\nimport { fromWebToken } from \"./fromWebToken\";\nconst ENV_TOKEN_FILE = \"AWS_WEB_IDENTITY_TOKEN_FILE\";\nconst ENV_ROLE_ARN = \"AWS_ROLE_ARN\";\nconst ENV_ROLE_SESSION_NAME = \"AWS_ROLE_SESSION_NAME\";\nexport const fromTokenFile = (init = {}) => async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-web-identity - fromTokenFile\");\n const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE];\n const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN];\n const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME];\n if (!webIdentityTokenFile || !roleArn) {\n throw new CredentialsProviderError(\"Web identity configuration not specified\", {\n logger: init.logger,\n });\n }\n const credentials = await fromWebToken({\n ...init,\n webIdentityToken: externalDataInterceptor?.getTokenRecord?.()[webIdentityTokenFile] ??\n readFileSync(webIdentityTokenFile, { encoding: \"ascii\" }),\n roleArn,\n roleSessionName,\n })(awsIdentityProperties);\n if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) {\n setCredentialFeature(credentials, \"CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN\", \"h\");\n }\n return credentials;\n};\n", | ||
| "export const fromWebToken = (init) => async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-web-identity - fromWebToken\");\n const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init;\n let { roleAssumerWithWebIdentity } = init;\n if (!roleAssumerWithWebIdentity) {\n const { getDefaultRoleAssumerWithWebIdentity } = await import(\"@aws-sdk/nested-clients/sts\");\n roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({\n ...init.clientConfig,\n credentialProviderLogger: init.logger,\n parentClientConfig: {\n ...awsIdentityProperties?.callerClientConfig,\n ...init.parentClientConfig,\n },\n }, init.clientPlugins);\n }\n return roleAssumerWithWebIdentity({\n RoleArn: roleArn,\n RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`,\n WebIdentityToken: webIdentityToken,\n ProviderId: providerId,\n PolicyArns: policyArns,\n Policy: policy,\n DurationSeconds: durationSeconds,\n });\n};\n" | ||
| ], | ||
| "mappings": ";4JAAA,eACA,WACA,uBAAS,WCFF,IAAM,EAAe,CAAC,IAAS,MAAO,IAA0B,CACnE,EAAK,QAAQ,MAAM,0DAA0D,EAC7E,IAAQ,UAAS,kBAAiB,mBAAkB,aAAY,aAAY,SAAQ,mBAAoB,GAClG,8BAA+B,EACrC,GAAI,CAAC,EAA4B,CAC7B,IAAQ,wCAAyC,KAAa,0CAC9D,EAA6B,EAAqC,IAC3D,EAAK,aACR,yBAA0B,EAAK,OAC/B,mBAAoB,IACb,GAAuB,sBACvB,EAAK,kBACZ,CACJ,EAAG,EAAK,aAAa,EAEzB,OAAO,EAA2B,CAC9B,QAAS,EACT,gBAAiB,GAAmB,sBAAsB,KAAK,IAAI,IACnE,iBAAkB,EAClB,WAAY,EACZ,WAAY,EACZ,OAAQ,EACR,gBAAiB,CACrB,CAAC,GDnBL,IAAM,EAAiB,8BACjB,EAAe,eACf,EAAwB,wBACjB,EAAgB,CAAC,EAAO,CAAC,IAAM,MAAO,IAA0B,CACzE,EAAK,QAAQ,MAAM,2DAA2D,EAC9E,IAAM,EAAuB,GAAM,sBAAwB,QAAQ,IAAI,GACjE,EAAU,GAAM,SAAW,QAAQ,IAAI,GACvC,EAAkB,GAAM,iBAAmB,QAAQ,IAAI,GAC7D,GAAI,CAAC,GAAwB,CAAC,EAC1B,MAAM,IAAI,2BAAyB,2CAA4C,CAC3E,OAAQ,EAAK,MACjB,CAAC,EAEL,IAAM,EAAc,MAAM,EAAa,IAChC,EACH,iBAAkB,2BAAyB,iBAAiB,EAAE,IAC1D,EAAa,EAAsB,CAAE,SAAU,OAAQ,CAAC,EAC5D,UACA,iBACJ,CAAC,EAAE,CAAqB,EACxB,GAAI,IAAyB,QAAQ,IAAI,GACrC,uBAAqB,EAAa,wCAAyC,GAAG,EAElF,OAAO", | ||
| "debugId": "9104224CE2D6E35764756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+mistral@3.0.51+d6123d32214422cb/node_modules/@ai-sdk/mistral/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/mistral-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/mistral-chat-language-model.ts\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonResponseHandler,\n generateId,\n injectJsonInstructionIntoMessages,\n parseProviderOptions,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z3 } from \"zod/v4\";\n\n// src/convert-mistral-usage.ts\nfunction convertMistralUsage(usage) {\n var _a, _b, _c, _d, _e;\n if (usage == null) {\n return {\n inputTokens: {\n total: void 0,\n noCache: void 0,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: void 0,\n text: void 0,\n reasoning: void 0\n },\n raw: void 0\n };\n }\n const promptTokens = usage.prompt_tokens;\n const completionTokens = usage.completion_tokens;\n const cacheReadTokens = (_e = (_d = (_b = usage.num_cached_tokens) != null ? _b : (_a = usage.prompt_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _d : (_c = usage.prompt_token_details) == null ? void 0 : _c.cached_tokens) != null ? _e : 0;\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens - cacheReadTokens,\n cacheRead: cacheReadTokens || void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: completionTokens,\n text: completionTokens,\n reasoning: void 0\n },\n raw: usage\n };\n}\n\n// src/convert-to-mistral-chat-messages.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\nimport { convertToBase64 } from \"@ai-sdk/provider-utils\";\nfunction formatFileUrl({\n data,\n mediaType\n}) {\n return data instanceof URL ? data.toString() : `data:${mediaType};base64,${convertToBase64(data)}`;\n}\nfunction convertToMistralChatMessages(prompt) {\n var _a;\n const messages = [];\n for (let i = 0; i < prompt.length; i++) {\n const { role, content } = prompt[i];\n const isLastMessage = i === prompt.length - 1;\n switch (role) {\n case \"system\": {\n messages.push({ role: \"system\", content });\n break;\n }\n case \"user\": {\n messages.push({\n role: \"user\",\n content: content.map((part) => {\n switch (part.type) {\n case \"text\": {\n return { type: \"text\", text: part.text };\n }\n case \"file\": {\n if (part.mediaType.startsWith(\"image/\")) {\n const mediaType = part.mediaType === \"image/*\" ? \"image/jpeg\" : part.mediaType;\n return {\n type: \"image_url\",\n image_url: formatFileUrl({ data: part.data, mediaType })\n };\n } else if (part.mediaType === \"application/pdf\") {\n return {\n type: \"document_url\",\n document_url: formatFileUrl({\n data: part.data,\n mediaType: \"application/pdf\"\n })\n };\n } else {\n throw new UnsupportedFunctionalityError({\n functionality: \"Only images and PDF file parts are supported\"\n });\n }\n }\n }\n })\n });\n break;\n }\n case \"assistant\": {\n let text = \"\";\n const structuredContent = [];\n let hasNativeReasoning = false;\n const toolCalls = [];\n for (const part of content) {\n switch (part.type) {\n case \"text\": {\n text += part.text;\n structuredContent.push({ type: \"text\", text: part.text });\n break;\n }\n case \"tool-call\": {\n toolCalls.push({\n id: part.toolCallId,\n type: \"function\",\n function: {\n name: part.toolName,\n arguments: JSON.stringify(part.input)\n }\n });\n break;\n }\n case \"reasoning\": {\n text += part.text;\n const native = part.providerOptions?.mistral?.thinking;\n if (native?.type === \"thinking\") {\n hasNativeReasoning = true;\n structuredContent.push(native);\n break;\n }\n structuredContent.push({ type: \"text\", text: part.text });\n break;\n }\n default: {\n throw new Error(\n `Unsupported content type in assistant message: ${part.type}`\n );\n }\n }\n }\n messages.push({\n role: \"assistant\",\n content: hasNativeReasoning ? structuredContent : text,\n prefix: isLastMessage ? true : void 0,\n tool_calls: toolCalls.length > 0 ? toolCalls : void 0\n });\n break;\n }\n case \"tool\": {\n for (const toolResponse of content) {\n if (toolResponse.type === \"tool-approval-response\") {\n continue;\n }\n const output = toolResponse.output;\n let contentValue;\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n contentValue = output.value;\n break;\n case \"execution-denied\":\n contentValue = (_a = output.reason) != null ? _a : \"Tool call execution denied.\";\n break;\n case \"content\":\n case \"json\":\n case \"error-json\":\n contentValue = JSON.stringify(output.value);\n break;\n }\n messages.push({\n role: \"tool\",\n name: toolResponse.toolName,\n tool_call_id: toolResponse.toolCallId,\n content: contentValue\n });\n }\n break;\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return messages;\n}\n\n// src/get-response-metadata.ts\nfunction getResponseMetadata({\n id,\n model,\n created\n}) {\n return {\n id: id != null ? id : void 0,\n modelId: model != null ? model : void 0,\n timestamp: created != null ? new Date(created * 1e3) : void 0\n };\n}\n\n// src/map-mistral-finish-reason.ts\nfunction mapMistralFinishReason(finishReason) {\n switch (finishReason) {\n case \"stop\":\n return \"stop\";\n case \"length\":\n case \"model_length\":\n return \"length\";\n case \"tool_calls\":\n return \"tool-calls\";\n default:\n return \"other\";\n }\n}\n\n// src/mistral-chat-options.ts\nimport { z } from \"zod/v4\";\nvar mistralLanguageModelOptions = z.object({\n /**\n * Whether to inject a safety prompt before all conversations.\n *\n * Defaults to `false`.\n */\n safePrompt: z.boolean().optional(),\n documentImageLimit: z.number().optional(),\n documentPageLimit: z.number().optional(),\n /**\n * Whether to use structured outputs.\n *\n * @default true\n */\n structuredOutputs: z.boolean().optional(),\n /**\n * Whether to use strict JSON schema validation.\n *\n * @default false\n */\n strictJsonSchema: z.boolean().optional(),\n /**\n * Whether to enable parallel function calling during tool use.\n * When set to false, the model will use at most one tool per response.\n *\n * @default true\n */\n parallelToolCalls: z.boolean().optional(),\n /**\n * Controls the reasoning effort for models that support adjustable reasoning.\n *\n * - `'high'`: Enable reasoning\n * - `'none'`: Disable reasoning\n */\n reasoningEffort: z.enum([\"high\", \"none\"]).optional(),\n promptCacheKey: z.string().optional()\n});\n\n// src/mistral-error.ts\nimport { createJsonErrorResponseHandler } from \"@ai-sdk/provider-utils\";\nimport { z as z2 } from \"zod/v4\";\nvar mistralErrorDataSchema = z2.object({\n object: z2.literal(\"error\"),\n message: z2.string(),\n type: z2.string(),\n param: z2.string().nullable(),\n code: z2.string().nullable()\n});\nvar mistralFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: mistralErrorDataSchema,\n errorToMessage: (data) => data.message\n});\n\n// src/mistral-prepare-tools.ts\nimport {\n UnsupportedFunctionalityError as UnsupportedFunctionalityError2\n} from \"@ai-sdk/provider\";\nfunction prepareTools({\n tools,\n toolChoice\n}) {\n tools = (tools == null ? void 0 : tools.length) ? tools : void 0;\n const toolWarnings = [];\n if (tools == null) {\n return { tools: void 0, toolChoice: void 0, toolWarnings };\n }\n const mistralTools = [];\n for (const tool of tools) {\n if (tool.type === \"provider\") {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `provider-defined tool ${tool.id}`\n });\n } else {\n mistralTools.push({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n ...tool.strict != null ? { strict: tool.strict } : {}\n }\n });\n }\n }\n if (toolChoice == null) {\n return { tools: mistralTools, toolChoice: void 0, toolWarnings };\n }\n const type = toolChoice.type;\n switch (type) {\n case \"auto\":\n case \"none\":\n return { tools: mistralTools, toolChoice: type, toolWarnings };\n case \"required\":\n return { tools: mistralTools, toolChoice: \"any\", toolWarnings };\n // mistral does not support tool mode directly,\n // so we filter the tools and force the tool choice through 'any'\n case \"tool\":\n return {\n tools: mistralTools.filter(\n (tool) => tool.function.name === toolChoice.toolName\n ),\n toolChoice: \"any\",\n toolWarnings\n };\n default: {\n const _exhaustiveCheck = type;\n throw new UnsupportedFunctionalityError2({\n functionality: `tool choice type: ${_exhaustiveCheck}`\n });\n }\n }\n}\n\n// src/mistral-chat-language-model.ts\nvar MistralChatLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.supportedUrls = {\n \"application/pdf\": [/^https:\\/\\/.*$/]\n };\n var _a;\n this.modelId = modelId;\n this.config = config;\n this.generateId = (_a = config.generateId) != null ? _a : generateId;\n }\n get provider() {\n return this.config.provider;\n }\n async getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n providerOptions,\n tools,\n toolChoice\n }) {\n var _a, _b, _c, _d;\n const warnings = [];\n const options = (_a = await parseProviderOptions({\n provider: \"mistral\",\n providerOptions,\n schema: mistralLanguageModelOptions\n })) != null ? _a : {};\n if (topK != null) {\n warnings.push({ type: \"unsupported\", feature: \"topK\" });\n }\n const structuredOutputs = (_b = options.structuredOutputs) != null ? _b : true;\n const strictJsonSchema = (_c = options.strictJsonSchema) != null ? _c : false;\n if ((responseFormat == null ? void 0 : responseFormat.type) === \"json\" && !(responseFormat == null ? void 0 : responseFormat.schema)) {\n prompt = injectJsonInstructionIntoMessages({\n messages: prompt,\n schema: responseFormat.schema\n });\n }\n const baseArgs = {\n // model id:\n model: this.modelId,\n // model specific settings:\n safe_prompt: options.safePrompt,\n // standardized settings:\n max_tokens: maxOutputTokens,\n temperature,\n top_p: topP,\n ...frequencyPenalty != null ? { frequency_penalty: frequencyPenalty } : {},\n ...presencePenalty != null ? { presence_penalty: presencePenalty } : {},\n stop: stopSequences,\n random_seed: seed,\n reasoning_effort: options.reasoningEffort,\n prompt_cache_key: options.promptCacheKey,\n // response format:\n response_format: (responseFormat == null ? void 0 : responseFormat.type) === \"json\" ? structuredOutputs && (responseFormat == null ? void 0 : responseFormat.schema) != null ? {\n type: \"json_schema\",\n json_schema: {\n schema: responseFormat.schema,\n strict: strictJsonSchema,\n name: (_d = responseFormat.name) != null ? _d : \"response\",\n description: responseFormat.description\n }\n } : { type: \"json_object\" } : void 0,\n // mistral-specific provider options:\n document_image_limit: options.documentImageLimit,\n document_page_limit: options.documentPageLimit,\n // messages:\n messages: convertToMistralChatMessages(prompt)\n };\n const {\n tools: mistralTools,\n toolChoice: mistralToolChoice,\n toolWarnings\n } = prepareTools({\n tools,\n toolChoice\n });\n return {\n args: {\n ...baseArgs,\n tools: mistralTools,\n tool_choice: mistralToolChoice,\n ...mistralTools != null && options.parallelToolCalls !== void 0 ? { parallel_tool_calls: options.parallelToolCalls } : {}\n },\n warnings: [...warnings, ...toolWarnings]\n };\n }\n async doGenerate(options) {\n var _a;\n const { args: body, warnings } = await this.getArgs(options);\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n mistralChatResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const choice = response.choices[0];\n const content = [];\n if (choice.message.content != null && Array.isArray(choice.message.content)) {\n for (const part of choice.message.content) {\n if (part.type === \"thinking\") {\n const reasoningText = extractReasoningContent(part.thinking);\n content.push({\n type: \"reasoning\",\n text: reasoningText,\n providerMetadata: { mistral: { thinking: part } }\n });\n } else if (part.type === \"text\") {\n if (part.text.length > 0) {\n content.push({ type: \"text\", text: part.text });\n }\n }\n }\n } else {\n const text = extractTextContent(choice.message.content);\n if (text != null && text.length > 0) {\n content.push({ type: \"text\", text });\n }\n }\n if (choice.message.tool_calls != null) {\n for (const toolCall of choice.message.tool_calls) {\n content.push({\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: toolCall.function.arguments\n });\n }\n }\n return {\n content,\n finishReason: {\n unified: mapMistralFinishReason(choice.finish_reason),\n raw: (_a = choice.finish_reason) != null ? _a : void 0\n },\n usage: convertMistralUsage(response.usage),\n request: { body },\n response: {\n ...getResponseMetadata(response),\n headers: responseHeaders,\n body: rawResponse\n },\n warnings\n };\n }\n async doStream(options) {\n const { args, warnings } = await this.getArgs(options);\n const body = { ...args, stream: true };\n const { responseHeaders, value: response } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(\n mistralChatChunkSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n let usage = void 0;\n let isFirstChunk = true;\n let activeText = false;\n let activeReasoningId = null;\n let activeThinking = null;\n const generateId2 = this.generateId;\n return {\n stream: response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n if (isFirstChunk) {\n isFirstChunk = false;\n controller.enqueue({\n type: \"response-metadata\",\n ...getResponseMetadata(value)\n });\n }\n if (value.usage != null) {\n usage = value.usage;\n }\n const choice = value.choices[0];\n const delta = choice.delta;\n const textContent = extractTextContent(delta.content);\n if (delta.content != null && Array.isArray(delta.content)) {\n for (const part of delta.content) {\n if (part.type === \"thinking\") {\n const reasoningDelta = extractReasoningContent(part.thinking);\n activeThinking = mergeThinking(activeThinking, part);\n if (activeReasoningId == null) {\n if (activeText) {\n controller.enqueue({ type: \"text-end\", id: \"0\" });\n activeText = false;\n }\n activeReasoningId = generateId2();\n controller.enqueue({\n type: \"reasoning-start\",\n id: activeReasoningId\n });\n }\n if (reasoningDelta.length > 0) {\n controller.enqueue({\n type: \"reasoning-delta\",\n id: activeReasoningId,\n delta: reasoningDelta\n });\n }\n }\n }\n }\n if (textContent != null && textContent.length > 0) {\n if (!activeText) {\n if (activeReasoningId != null) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: activeReasoningId,\n providerMetadata: { mistral: { thinking: activeThinking } }\n });\n activeReasoningId = null;\n activeThinking = null;\n }\n controller.enqueue({ type: \"text-start\", id: \"0\" });\n activeText = true;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: \"0\",\n delta: textContent\n });\n }\n if ((delta == null ? void 0 : delta.tool_calls) != null) {\n for (const toolCall of delta.tool_calls) {\n const toolCallId = toolCall.id;\n const toolName = toolCall.function.name;\n const input = toolCall.function.arguments;\n controller.enqueue({\n type: \"tool-input-start\",\n id: toolCallId,\n toolName\n });\n controller.enqueue({\n type: \"tool-input-delta\",\n id: toolCallId,\n delta: input\n });\n controller.enqueue({\n type: \"tool-input-end\",\n id: toolCallId\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId,\n toolName,\n input\n });\n }\n }\n if (choice.finish_reason != null) {\n finishReason = {\n unified: mapMistralFinishReason(choice.finish_reason),\n raw: choice.finish_reason\n };\n }\n },\n flush(controller) {\n if (activeReasoningId != null) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: activeReasoningId,\n providerMetadata: { mistral: { thinking: activeThinking } }\n });\n }\n if (activeText) {\n controller.enqueue({ type: \"text-end\", id: \"0\" });\n }\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertMistralUsage(usage)\n });\n }\n })\n ),\n request: { body },\n response: { headers: responseHeaders }\n };\n }\n};\nfunction extractReasoningContent(thinking) {\n return thinking.filter((chunk) => chunk.type === \"text\").map((chunk) => chunk.text).join(\"\");\n}\nfunction mergeThinking(current, next) {\n if (current === null) return { ...next, thinking: [...next.thinking] };\n current.thinking.push(...next.thinking);\n if (next.closed !== void 0) current.closed = next.closed;\n if (next.signature !== void 0) current.signature = next.signature;\n return current;\n}\nfunction extractTextContent(content) {\n if (typeof content === \"string\") {\n return content;\n }\n if (content == null) {\n return void 0;\n }\n const textContent = [];\n for (const chunk of content) {\n const { type } = chunk;\n switch (type) {\n case \"text\":\n textContent.push(chunk.text);\n break;\n case \"thinking\":\n case \"image_url\":\n case \"reference\":\n break;\n default: {\n const _exhaustiveCheck = type;\n throw new Error(`Unsupported type: ${_exhaustiveCheck}`);\n }\n }\n }\n return textContent.length ? textContent.join(\"\") : void 0;\n}\nvar mistralThinkingContentSchema = z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"tool_reference\"),\n tool: z3.string(),\n title: z3.string(),\n url: z3.string().nullish(),\n favicon: z3.string().nullish(),\n description: z3.string().nullish()\n }),\n z3.object({\n type: z3.literal(\"reference\"),\n reference_ids: z3.array(z3.union([z3.string(), z3.number().int()]))\n })\n]);\nvar mistralThinkChunkSchema = z3.object({\n type: z3.literal(\"thinking\"),\n thinking: z3.array(mistralThinkingContentSchema),\n closed: z3.boolean().optional(),\n signature: z3.string().nullish()\n});\nvar mistralContentSchema = z3.union([\n z3.string(),\n z3.array(\n z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"image_url\"),\n image_url: z3.union([\n z3.string(),\n z3.object({\n url: z3.string(),\n detail: z3.string().nullable()\n })\n ])\n }),\n z3.object({\n type: z3.literal(\"reference\"),\n reference_ids: z3.array(z3.union([z3.string(), z3.number()]))\n }),\n mistralThinkChunkSchema\n ])\n )\n]).nullish();\nvar mistralUsageSchema = z3.object({\n prompt_tokens: z3.number(),\n completion_tokens: z3.number(),\n total_tokens: z3.number(),\n num_cached_tokens: z3.number().nullish(),\n prompt_tokens_details: z3.object({ cached_tokens: z3.number().nullish() }).nullish(),\n prompt_token_details: z3.object({ cached_tokens: z3.number().nullish() }).nullish()\n});\nvar mistralChatResponseSchema = z3.object({\n id: z3.string().nullish(),\n created: z3.number().nullish(),\n model: z3.string().nullish(),\n choices: z3.array(\n z3.object({\n message: z3.object({\n role: z3.literal(\"assistant\"),\n content: mistralContentSchema,\n tool_calls: z3.array(\n z3.object({\n id: z3.string(),\n function: z3.object({ name: z3.string(), arguments: z3.string() })\n })\n ).nullish()\n }),\n index: z3.number(),\n finish_reason: z3.string().nullish()\n })\n ),\n object: z3.literal(\"chat.completion\"),\n usage: mistralUsageSchema\n});\nvar mistralChatChunkSchema = z3.object({\n id: z3.string().nullish(),\n created: z3.number().nullish(),\n model: z3.string().nullish(),\n choices: z3.array(\n z3.object({\n delta: z3.object({\n role: z3.enum([\"assistant\"]).optional(),\n content: mistralContentSchema,\n tool_calls: z3.array(\n z3.object({\n id: z3.string(),\n function: z3.object({ name: z3.string(), arguments: z3.string() })\n })\n ).nullish()\n }),\n finish_reason: z3.string().nullish(),\n index: z3.number()\n })\n ),\n usage: mistralUsageSchema.nullish()\n});\n\n// src/mistral-embedding-model.ts\nimport {\n TooManyEmbeddingValuesForCallError\n} from \"@ai-sdk/provider\";\nimport {\n combineHeaders as combineHeaders2,\n createJsonResponseHandler as createJsonResponseHandler2,\n postJsonToApi as postJsonToApi2\n} from \"@ai-sdk/provider-utils\";\nimport { z as z4 } from \"zod/v4\";\nvar MistralEmbeddingModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.maxEmbeddingsPerCall = 32;\n this.supportsParallelCalls = false;\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n async doEmbed({\n values,\n abortSignal,\n headers\n }) {\n if (values.length > this.maxEmbeddingsPerCall) {\n throw new TooManyEmbeddingValuesForCallError({\n provider: this.provider,\n modelId: this.modelId,\n maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,\n values\n });\n }\n const {\n responseHeaders,\n value: response,\n rawValue\n } = await postJsonToApi2({\n url: `${this.config.baseURL}/embeddings`,\n headers: combineHeaders2(this.config.headers(), headers),\n body: {\n model: this.modelId,\n input: values,\n encoding_format: \"float\"\n },\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler2(\n MistralTextEmbeddingResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n warnings: [],\n embeddings: response.data.map((item) => item.embedding),\n usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,\n response: { headers: responseHeaders, body: rawValue }\n };\n }\n};\nvar MistralTextEmbeddingResponseSchema = z4.object({\n data: z4.array(z4.object({ embedding: z4.array(z4.number()) })),\n usage: z4.object({ prompt_tokens: z4.number() }).nullish()\n});\n\n// src/mistral-speech-model.ts\nimport {\n combineHeaders as combineHeaders3,\n createJsonResponseHandler as createJsonResponseHandler3,\n parseProviderOptions as parseProviderOptions2,\n postToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z6 } from \"zod/v4\";\n\n// src/mistral-speech-model-options.ts\nimport { z as z5 } from \"zod/v4\";\nvar mistralSpeechModelOptions = z5.object({\n /**\n * Base64-encoded reference audio for one-off voice cloning.\n *\n * When provided, this takes precedence over the standard `voice` option.\n */\n refAudio: z5.string().min(1).optional()\n});\n\n// src/mistral-speech-model.ts\nvar MistralSpeechModel = class {\n constructor(modelId, config) {\n this.modelId = modelId;\n this.config = config;\n this.specificationVersion = \"v3\";\n }\n get provider() {\n return this.config.provider;\n }\n async getArgs({\n text,\n voice,\n outputFormat = \"mp3\",\n instructions,\n speed,\n language,\n providerOptions\n }) {\n const warnings = [];\n const mistralOptions = await parseProviderOptions2({\n provider: \"mistral\",\n providerOptions,\n schema: mistralSpeechModelOptions\n });\n let responseFormat = \"mp3\";\n if ([\"pcm\", \"wav\", \"mp3\", \"flac\", \"opus\"].includes(outputFormat)) {\n responseFormat = outputFormat;\n } else {\n warnings.push({\n type: \"unsupported\",\n feature: \"outputFormat\",\n details: `Unsupported output format: ${outputFormat}. Using mp3 instead.`\n });\n }\n if (instructions != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"instructions\",\n details: \"Mistral speech models do not support the `instructions` option. Use a reference audio clip to guide delivery.\"\n });\n }\n if (speed != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"speed\",\n details: \"Mistral speech models do not support the `speed` option. It was ignored.\"\n });\n }\n if (language != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"language\",\n details: \"Mistral speech models do not support the `language` option. Language is inferred from the input text and voice.\"\n });\n }\n const refAudio = mistralOptions == null ? void 0 : mistralOptions.refAudio;\n const requestBody = {\n model: this.modelId,\n input: text,\n voice_id: refAudio == null ? voice : void 0,\n ref_audio: refAudio,\n response_format: responseFormat,\n stream: false\n };\n const requestBodyValues = {\n ...requestBody,\n ref_audio: refAudio == null ? void 0 : \"[redacted]\"\n };\n return { requestBody, requestBodyValues, warnings };\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e;\n const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();\n const { requestBody, requestBodyValues, warnings } = await this.getArgs(options);\n const {\n value: response,\n responseHeaders,\n rawValue: rawResponse\n } = await postToApi({\n url: `${this.config.baseURL}/audio/speech`,\n headers: combineHeaders3(\n { \"Content-Type\": \"application/json\" },\n (_e = (_d = this.config).headers) == null ? void 0 : _e.call(_d),\n options.headers\n ),\n body: {\n content: JSON.stringify(requestBody),\n values: requestBodyValues\n },\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler3(\n mistralSpeechResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n return {\n audio: response.audio_data,\n warnings,\n request: {\n body: JSON.stringify(requestBodyValues)\n },\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders,\n body: rawResponse\n }\n };\n }\n};\nvar mistralSpeechResponseSchema = z6.object({\n audio_data: z6.string()\n});\n\n// src/version.ts\nvar VERSION = true ? \"3.0.51\" : \"0.0.0-test\";\n\n// src/mistral-provider.ts\nfunction createMistral(options = {}) {\n var _a;\n const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : \"https://api.mistral.ai/v1\";\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"MISTRAL_API_KEY\",\n description: \"Mistral\"\n })}`,\n ...options.headers\n },\n `ai-sdk/mistral/${VERSION}`\n );\n const createChatModel = (modelId) => new MistralChatLanguageModel(modelId, {\n provider: \"mistral.chat\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n generateId: options.generateId\n });\n const createEmbeddingModel = (modelId) => new MistralEmbeddingModel(modelId, {\n provider: \"mistral.embedding\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch\n });\n const createSpeechModel = (modelId) => new MistralSpeechModel(modelId, {\n provider: \"mistral.speech\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch\n });\n const provider = function(modelId) {\n if (new.target) {\n throw new Error(\n \"The Mistral model function cannot be called with the new keyword.\"\n );\n }\n return createChatModel(modelId);\n };\n provider.specificationVersion = \"v3\";\n provider.languageModel = createChatModel;\n provider.chat = createChatModel;\n provider.embedding = createEmbeddingModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbedding = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n provider.speech = createSpeechModel;\n provider.speechModel = createSpeechModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar mistral = createMistral();\nexport {\n VERSION,\n createMistral,\n mistral\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";iZAuBA,SAAS,CAAmB,CAAC,EAAO,CAClC,IAAI,EAAI,EAAI,EAAI,EAAI,EACpB,GAAI,GAAS,KACX,MAAO,CACL,YAAa,CACX,MAAY,OACZ,QAAc,OACd,UAAgB,OAChB,WAAiB,MACnB,EACA,aAAc,CACZ,MAAY,OACZ,KAAW,OACX,UAAgB,MAClB,EACA,IAAU,MACZ,EAEF,IAA2B,cAArB,EACyB,kBAAzB,G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sources": ["src/ui/timeline.tsx", "src/commands/handlers/console/login.ts"], | ||
| "sourcesContent": [ | ||
| "import { createComponent as _$createComponent } from \"@opentui/solid\";\nimport { effect as _$effect } from \"@opentui/solid\";\nimport { createTextNode as _$createTextNode } from \"@opentui/solid\";\nimport { insertNode as _$insertNode } from \"@opentui/solid\";\nimport { insert as _$insert } from \"@opentui/solid\";\nimport { setProp as _$setProp } from \"@opentui/solid\";\nimport { createElement as _$createElement } from \"@opentui/solid\";\n/** @jsxImportSource @opentui/solid */\nimport { createCliRenderer, RGBA } from \"@opentui/core\";\nimport { createScrollbackWriter, render, useKeyboard } from \"@opentui/solid\";\nimport { registerOpencodeSpinner } from \"@opencode-ai/tui/component/register-spinner\";\nimport { Show, createSignal } from \"solid-js\";\nregisterOpencodeSpinner();\nconst SPINNER_FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\nconst IDLE_TIMEOUT = 1_000;\nconst COLORS = {\n accent: RGBA.fromIndex(6),\n error: RGBA.fromIndex(1),\n foreground: RGBA.defaultForeground(),\n muted: RGBA.fromIndex(8),\n success: RGBA.fromIndex(2)\n};\nconst ROWS = {\n intro: {\n marker: \"┌\",\n color: COLORS.muted,\n connector: true\n },\n item: {\n marker: \"●\",\n color: COLORS.accent,\n connector: true\n },\n success: {\n marker: \"◇\",\n color: COLORS.success,\n connector: true\n },\n failure: {\n marker: \"■\",\n color: COLORS.error,\n connector: false\n },\n outro: {\n marker: \"└\",\n color: COLORS.muted,\n connector: false\n }\n};\nfunction row(kind, value) {\n const style = ROWS[kind];\n return createScrollbackWriter(() => (() => {\n var _el$ = _$createElement(\"box\"),\n _el$2 = _$createElement(\"box\"),\n _el$3 = _$createElement(\"text\"),\n _el$4 = _$createElement(\"text\");\n _$insertNode(_el$, _el$2);\n _$setProp(_el$, \"width\", \"100%\");\n _$setProp(_el$, \"minHeight\", 1);\n _$setProp(_el$, \"flexDirection\", \"column\");\n _$insertNode(_el$2, _el$3);\n _$insertNode(_el$2, _el$4);\n _$setProp(_el$2, \"width\", \"100%\");\n _$setProp(_el$2, \"minHeight\", 1);\n _$setProp(_el$2, \"flexDirection\", \"row\");\n _$setProp(_el$2, \"gap\", 1);\n _$setProp(_el$3, \"flexShrink\", 0);\n _$insert(_el$3, () => style.marker);\n _$setProp(_el$4, \"wrapMode\", \"word\");\n _$insert(_el$4, value);\n _$insert(_el$, _$createComponent(Show, {\n get when() {\n return style.connector;\n },\n get children() {\n var _el$5 = _$createElement(\"text\");\n _$insertNode(_el$5, _$createTextNode(`│`));\n _$effect(_$p => _$setProp(_el$5, \"fg\", COLORS.muted, _$p));\n return _el$5;\n }\n }), null);\n _$effect(_p$ => {\n var _v$ = style.color,\n _v$2 = COLORS.foreground;\n _v$ !== _p$.e && (_p$.e = _$setProp(_el$3, \"fg\", _v$, _p$.e));\n _v$2 !== _p$.t && (_p$.t = _$setProp(_el$4, \"fg\", _v$2, _p$.t));\n return _p$;\n }, {\n e: undefined,\n t: undefined\n });\n return _el$;\n })(), {\n startOnNewLine: true,\n trailingNewline: !style.connector\n });\n}\nfunction TimelineFooter(props) {\n useKeyboard(event => {\n if (event.name !== \"escape\" && !(event.ctrl && event.name === \"c\")) return;\n event.preventDefault();\n props.cancel();\n });\n return (() => {\n var _el$7 = _$createElement(\"box\");\n _$setProp(_el$7, \"width\", \"100%\");\n _$setProp(_el$7, \"height\", 1);\n _$setProp(_el$7, \"flexDirection\", \"row\");\n _$setProp(_el$7, \"gap\", 1);\n _$insert(_el$7, _$createComponent(Show, {\n get when() {\n return props.pending();\n },\n children: text => [(() => {\n var _el$8 = _$createElement(\"spinner\");\n _$setProp(_el$8, \"frames\", SPINNER_FRAMES);\n _$setProp(_el$8, \"interval\", 80);\n _$effect(_$p => _$setProp(_el$8, \"color\", COLORS.accent, _$p));\n return _el$8;\n })(), (() => {\n var _el$9 = _$createElement(\"text\");\n _$setProp(_el$9, \"wrapMode\", \"none\");\n _$setProp(_el$9, \"truncate\", true);\n _$insert(_el$9, text);\n _$effect(_$p => _$setProp(_el$9, \"fg\", COLORS.foreground, _$p));\n return _el$9;\n })()]\n }));\n return _el$7;\n })();\n}\nfunction bounded(task) {\n return new Promise(resolve => {\n const timer = setTimeout(resolve, IDLE_TIMEOUT);\n timer.unref();\n const finish = () => {\n clearTimeout(timer);\n resolve();\n };\n void task.then(finish, finish);\n });\n}\nasync function shutdown(renderer) {\n await bounded(renderer.idle());\n try {\n renderer.externalOutputMode = \"passthrough\";\n } finally {\n try {\n renderer.screenMode = \"main-screen\";\n } finally {\n if (!renderer.isDestroyed) renderer.destroy();\n }\n }\n}\nexport async function createTimelineHost() {\n const stdout = process.stdout;\n const controller = new AbortController();\n const signals = [\"SIGINT\", \"SIGHUP\", \"SIGQUIT\"];\n const cancel = () => {\n if (!controller.signal.aborted) controller.abort();\n };\n signals.forEach(signal => process.on(signal, cancel));\n if (!stdout.isTTY || !process.stdin.isTTY) {\n let closed = false;\n let writing = false;\n let active;\n let closeTask;\n const write = async (kind, text) => {\n if (closed) throw new Error(\"timeline closed\");\n if (writing) throw new Error(\"timeline write already in progress\");\n writing = true;\n try {\n const style = kind === \"pending\" ? undefined : ROWS[kind];\n const marker = kind === \"pending\" ? \".\" : ROWS[kind].marker;\n const connector = style?.connector ? \"│\\n\" : \"\";\n active = new Promise((resolve, reject) => {\n stdout.write(`${marker} ${text}\\n${connector}`, error => error ? reject(error) : resolve());\n });\n await active;\n } finally {\n writing = false;\n active = undefined;\n }\n };\n const close = () => {\n if (closeTask) return closeTask;\n closed = true;\n closeTask = (async () => {\n await active?.catch(() => {});\n signals.forEach(signal => process.off(signal, cancel));\n })();\n return closeTask;\n };\n return {\n signal: controller.signal,\n intro: text => write(\"intro\", text),\n item: text => write(\"item\", text),\n pending: text => write(\"pending\", text),\n success: text => write(\"success\", text),\n failure: text => write(\"failure\", text),\n outro: text => write(\"outro\", text),\n close\n };\n }\n let renderer;\n try {\n // Start on a fresh row so delayed SSH cursor reports cannot make\n // split-footer overwrite the shell command.\n process.stdout.write(\"\\n\");\n renderer = await createCliRenderer({\n stdin: process.stdin,\n useMouse: false,\n autoFocus: false,\n openConsoleOnError: false,\n exitOnCtrlC: false,\n exitSignals: [],\n screenMode: \"split-footer\",\n footerHeight: 1,\n externalOutputMode: \"capture-stdout\",\n consoleMode: \"disabled\",\n clearOnShutdown: false\n });\n const activeRenderer = renderer;\n const [pending, setPending] = createSignal();\n const renderTask = render(() => _$createComponent(TimelineFooter, {\n pending: pending,\n cancel: cancel\n }), activeRenderer);\n void renderTask.catch(cancel);\n await bounded(activeRenderer.idle());\n let closed = false;\n let writing = false;\n let active;\n let closeTask;\n const write = (kind, text) => {\n if (closed) return Promise.reject(new Error(\"timeline closed\"));\n if (writing) return Promise.reject(new Error(\"timeline write already in progress\"));\n writing = true;\n active = (async () => {\n if (kind === \"pending\") {\n setPending(text);\n activeRenderer.requestRender();\n } else {\n if (kind === \"success\" || kind === \"failure\" || kind === \"outro\") setPending(undefined);\n activeRenderer.writeToScrollback(row(kind, text));\n activeRenderer.requestRender();\n }\n await bounded(activeRenderer.idle());\n })().finally(() => {\n writing = false;\n active = undefined;\n });\n return active;\n };\n const close = () => {\n if (closeTask) return closeTask;\n closed = true;\n closeTask = (async () => {\n await active?.catch(() => {});\n try {\n await shutdown(activeRenderer);\n await bounded(renderTask);\n } finally {\n signals.forEach(signal => process.off(signal, cancel));\n }\n })();\n return closeTask;\n };\n return {\n signal: controller.signal,\n intro: text => write(\"intro\", text),\n item: text => write(\"item\", text),\n pending: text => write(\"pending\", text),\n success: text => write(\"success\", text),\n failure: text => write(\"failure\", text),\n outro: text => write(\"outro\", text),\n close\n };\n } catch (error) {\n try {\n if (renderer) await shutdown(renderer);\n } finally {\n signals.forEach(signal => process.off(signal, cancel));\n }\n throw error;\n }\n}", | ||
| "import { Cause, Effect, Exit, Option } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode, type OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport { AppProcess } from \"@opencode-ai/util/process\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { createTimelineHost, type TimelineHost } from \"../../../ui/timeline\"\nimport { errorMessage } from \"../../../util/error\"\n\nconst integrationID = \"opencode\"\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.console.commands.login,\n Effect.fn(\"cli.console.login\")(function* (input) {\n const timeline = yield* Effect.acquireRelease(\n Effect.promise(() => createTimelineHost()),\n (value) => request(() => value.close()).pipe(Effect.ignore),\n )\n const exit = yield* login(timeline, Option.getOrUndefined(input.url)).pipe(\n Effect.raceFirst(AppProcess.waitForAbort(timeline.signal)),\n Effect.exit,\n )\n if (Exit.isSuccess(exit)) return\n\n const cancelled = timeline.signal.aborted\n yield* request(() =>\n timeline.failure(cancelled ? \"Authorization cancelled\" : errorMessage(Cause.squash(exit.cause))),\n ).pipe(Effect.ignore)\n process.exitCode = cancelled ? 130 : 1\n }),\n)\n\nconst login = Effect.fn(\"cli.console.login.run\")(function* (timeline: TimelineHost, server?: string) {\n yield* request(() => timeline.intro(\"Log in\"))\n yield* request(() => timeline.pending(\"Connecting to OpenCode...\"))\n\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const found = yield* request((signal) => client.integration.get({ integrationID, location }, { signal }))\n const integration = yield* required(found.data, \"OpenCode Console integration is unavailable\")\n const method = yield* required(\n integration.methods.find((candidate) => candidate.type === \"oauth\"),\n \"OpenCode Console login is unavailable\",\n )\n\n yield* request(() => timeline.pending(\"Starting authorization...\"))\n const started = yield* request((signal) =>\n client.integration.oauth.connect(\n {\n integrationID,\n methodID: method.id,\n ...(server ? { answer: { server } } : {}),\n location,\n },\n { signal },\n ),\n )\n const attempt = started.data\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.oauth.cancel(\n { integrationID, attemptID: attempt.attemptID, location },\n { signal: AbortSignal.timeout(5_000) },\n ),\n ).pipe(Effect.ignore),\n )\n if (attempt.mode !== \"auto\") yield* Effect.fail(new Error(\"OpenCode Console requires a device login\"))\n\n yield* request(() => timeline.item(`Go to: ${attempt.url}`))\n yield* request(() => timeline.item(attempt.instructions))\n yield* request(async () => {\n const { default: open } = await import(\"open\")\n await open(attempt.url)\n }).pipe(Effect.ignore)\n yield* request(() => timeline.pending(\"Waiting for authorization...\"))\n\n const status = yield* waitForConsoleLogin(client, integrationID, attempt.attemptID)\n if (status.status === \"failed\") yield* Effect.fail(new Error(status.message))\n if (status.status === \"expired\") yield* Effect.fail(new Error(\"Device code expired\"))\n\n yield* request(() => timeline.success(\"Connected to OpenCode Console\"))\n yield* request(() => timeline.outro(\"Done\"))\n})\n\nconst waitForConsoleLogin = Effect.fn(\"cli.console.login.wait\")(function* (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n) {\n while (true) {\n const response = yield* request((signal) =>\n client.integration.oauth.status({ integrationID, attemptID, location }, { signal }),\n )\n if (response.data.status !== \"pending\") return response.data\n yield* Effect.sleep(500)\n }\n})\n\nfunction request<A>(task: (signal: AbortSignal) => Promise<A>) {\n return Effect.tryPromise({\n try: task,\n catch: (cause) => cause,\n })\n}\n\nfunction required<A>(value: A | null | undefined, message: string) {\n return value === null || value === undefined ? Effect.fail(new Error(message)) : Effect.succeed(value)\n}\n" | ||
| ], | ||
| "mappings": ";+tCAYA,EAAwB,EACxB,IAAM,GAAiB,CAAC,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,QAAG,EAClE,GAAe,KACf,EAAS,CACb,OAAQ,EAAK,UAAU,CAAC,EACxB,MAAO,EAAK,UAAU,CAAC,EACvB,WAAY,EAAK,kBAAkB,EACnC,MAAO,EAAK,UAAU,CAAC,EACvB,QAAS,EAAK,UAAU,CAAC,CAC3B,EACM,EAAO,CACX,MAAO,C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ACxD,MAAO,EAAQ,SAAY,CACzB,IAAQ,QAAS,GAAS,KAAa,0CACvC,MAAM,EAAK,EAAQ,GAAG,EACvB,EAAE,KAAK,EAAO,MAAM,EACrB,MAAO,EAAQ,IAAM,EAAS,QAAQ,8BAA8B,CAAC,EAErE,IAAM,EAAS,MAAO,GAAoB,EAAQ,EAAe,EAAQ,SAAS,EAClF,GAAI,EAAO,SAAW,SAAU,MAAO,EAAO,KAAS,MAAM,EAAO,OAAO,CAAC,EAC5E,GAAI,EAAO,SAAW,UAAW,MAAO,EAAO,KAAS,MAAM,qBAAqB,CAAC,EAEpF,MAAO,EAAQ,IAAM,EAAS,QAAQ,+BAA+B,CAAC,EACtE,MAAO,EAAQ,IAAM,EAAS,MAAM,MAAM,CAAC,EAC5C,EAEK,GAAsB,EAAO,GAAG,wBAAwB,EAAE,SAAU,CACxE,EACA,EACA,EACA,CACA,MAAO,GAAM,CACX,IAAM,EAAW,MAAO,EAAQ,CAAC,IAC/B,EAAO,YAAY,MAAM,OAAO,CAAE,gBAAe,YAAW,UAAS,EAAG,CAAE,QAAO,CAAC,CACpF,EACA,GAAI,EAAS,KAAK,SAAW,UAAW,OAAO,EAAS,KACxD,MAAO,EAAO,MAAM,GAAG,GAE1B,EAED,SAAS,CAAU,CAAC,EAA2C,CAC7D,OAAO,EAAO,WAAW,CACvB,IAAK,EACL,MAAO,CAAC,IAAU,CACpB,CAAC,EAGH,SAAS,CAAW,CAAC,EAA6B,EAAiB,CACjE,OAAO,IAAU,MAAQ,IAAU,OAAY,EAAO,KAAS,MAAM,CAAO,CAAC,EAAI,EAAO,QAAQ,CAAK", | ||
| "debugId": "AF6660314DD2A85864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/start.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.start,\n Effect.fn(\"cli.service.start\")(function* () {\n const transport = yield* Service.ensure(yield* ServiceConfig.options())\n process.stdout.write(transport.url + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";s5BAAA,cAAS,WAOT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,MACnC,EAAO,GAAG,mBAAmB,EAAE,SAAU,EAAG,CAC1C,IAAM,EAAY,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EACtE,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH", | ||
| "debugId": "6783E696E3B8300164756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/unset.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Option } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.unset,\n Effect.fn(\"cli.service.unset\")(function* (input) {\n yield* ServiceConfig.unset(input.key, Option.getOrUndefined(input.name))\n }),\n)\n" | ||
| ], | ||
| "mappings": ";i5BAKA,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,MACnC,EAAO,GAAG,mBAAmB,EAAE,SAAU,CAAC,EAAO,CAC/C,MAAO,EAAc,MAAM,EAAM,IAAK,EAAO,eAAe,EAAM,IAAI,CAAC,EACxE,CACH", | ||
| "debugId": "B640DA942F7340C464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-process@3.972.69/node_modules/@aws-sdk/credential-provider-process/dist-es/fromProcess.js", "../../node_modules/.bun/@aws-sdk+credential-provider-process@3.972.69/node_modules/@aws-sdk/credential-provider-process/dist-es/resolveProcessCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-process@3.972.69/node_modules/@aws-sdk/credential-provider-process/dist-es/getValidatedProcessCredentials.js"], | ||
| "sourcesContent": [ | ||
| "import { getProfileName, parseKnownFiles } from \"@smithy/core/config\";\nimport { resolveProcessCredentials } from \"./resolveProcessCredentials\";\nexport const fromProcess = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-process - fromProcess\");\n const profiles = await parseKnownFiles(init);\n return resolveProcessCredentials(getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n }), profiles, init.logger);\n};\n", | ||
| "import { CredentialsProviderError, externalDataInterceptor } from \"@smithy/core/config\";\nimport { exec } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { getValidatedProcessCredentials } from \"./getValidatedProcessCredentials\";\nexport const resolveProcessCredentials = async (profileName, profiles, logger) => {\n const profile = profiles[profileName];\n if (profiles[profileName]) {\n const credentialProcess = profile[\"credential_process\"];\n if (credentialProcess !== undefined) {\n const execPromise = promisify(externalDataInterceptor?.getTokenRecord?.().exec ?? exec);\n try {\n const { stdout } = await execPromise(credentialProcess);\n let data;\n try {\n data = JSON.parse(stdout.trim());\n }\n catch {\n throw Error(`Profile ${profileName} credential_process returned invalid JSON.`);\n }\n return getValidatedProcessCredentials(profileName, data, profiles);\n }\n catch (error) {\n throw new CredentialsProviderError(error.message, { logger });\n }\n }\n else {\n throw new CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger });\n }\n }\n else {\n throw new CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, {\n logger,\n });\n }\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const getValidatedProcessCredentials = (profileName, data, profiles) => {\n if (data.Version !== 1) {\n throw Error(`Profile ${profileName} credential_process did not return Version 1.`);\n }\n if (data.AccessKeyId === undefined || data.SecretAccessKey === undefined) {\n throw Error(`Profile ${profileName} credential_process returned invalid credentials.`);\n }\n if (data.Expiration) {\n const currentTime = new Date();\n const expireTime = new Date(data.Expiration);\n if (expireTime < currentTime) {\n throw Error(`Profile ${profileName} credential_process returned expired credentials.`);\n }\n }\n let accountId = data.AccountId;\n if (!accountId && profiles?.[profileName]?.aws_account_id) {\n accountId = profiles[profileName].aws_account_id;\n }\n const credentials = {\n accessKeyId: data.AccessKeyId,\n secretAccessKey: data.SecretAccessKey,\n ...(data.SessionToken && { sessionToken: data.SessionToken }),\n ...(data.Expiration && { expiration: new Date(data.Expiration) }),\n ...(data.CredentialScope && { credentialScope: data.CredentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"CREDENTIALS_PROCESS\", \"w\");\n return credentials;\n};\n" | ||
| ], | ||
| "mappings": ";4JAAA,eCAA,eACA,eAAS,sBACT,oBAAS,aCFT,eACa,EAAiC,CAAC,EAAa,EAAM,IAAa,CAC3E,GAAI,EAAK,UAAY,EACjB,MAAM,MAAM,WAAW,gDAA0D,EAErF,GAAI,EAAK,cAAgB,QAAa,EAAK,kBAAoB,OAC3D,MAAM,MAAM,WAAW,oDAA8D,EAEzF,GAAI,EAAK,WAAY,CACjB,IAAM,EAAc,IAAI,KAExB,GADmB,IAAI,KAAK,EAAK,UAAU,EAC1B,EACb,MAAM,MAAM,WAAW,oDAA8D,EAG7F,IAAI,EAAY,EAAK,UACrB,GAAI,CAAC,GAAa,IAAW,IAAc,eACvC,EAAY,EAAS,GAAa,eAEtC,IAAM,EAAc,CAChB,YAAa,EAAK,YAClB,gBAAiB,EAAK,mBAClB,EAAK,cAAgB,CAAE,aAAc,EAAK,YAAa,KACvD,EAAK,YAAc,CAAE,WAAY,IAAI,KAAK,EAAK,UAAU,CAAE,KAC3D,EAAK,iBAAmB,CAAE,gBAAiB,EAAK,eAAgB,KAChE,GAAa,CAAE,WAAU,CACjC,EAEA,OADA,uBAAqB,EAAa,sBAAuB,GAAG,EACrD,GDxBJ,IAAM,EAA4B,MAAO,EAAa,EAAU,IAAW,CAC9E,IAAM,EAAU,EAAS,GACzB,GAAI,EAAS,GAAc,CACvB,IAAM,EAAoB,EAAQ,mBAClC,GAAI,IAAsB,OAAW,CACjC,IAAM,EAAc,EAAU,2BAAyB,iBAAiB,EAAE,MAAQ,CAAI,EACtF,GAAI,CACA,IAAQ,UAAW,MAAM,EAAY,CAAiB,EAClD,EACJ,GAAI,CACA,EAAO,KAAK,MAAM,EAAO,KAAK,CAAC,EAEnC,KAAM,CACF,MAAM,MAAM,WAAW,6CAAuD,EAElF,OAAO,EAA+B,EAAa,EAAM,CAAQ,EAErE,MAAO,EAAO,CACV,MAAM,IAAI,2BAAyB,EAAM,QAAS,CAAE,QAAO,CAAC,GAIhE,WAAM,IAAI,2BAAyB,WAAW,wCAAmD,CAAE,QAAO,CAAC,EAI/G,WAAM,IAAI,2BAAyB,WAAW,mDAA8D,CACxG,QACJ,CAAC,GD9BF,IAAM,EAAc,CAAC,EAAO,CAAC,IAAM,OAAS,sBAAuB,CAAC,IAAM,CAC7E,EAAK,QAAQ,MAAM,oDAAoD,EACvE,IAAM,EAAW,MAAM,kBAAgB,CAAI,EAC3C,OAAO,EAA0B,iBAAe,CAC5C,QAAS,EAAK,SAAW,GAAoB,OACjD,CAAC,EAAG,EAAU,EAAK,MAAM", | ||
| "debugId": "6627B8D8B3EBE77464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/export.ts"], | ||
| "sourcesContent": [ | ||
| "import { autocomplete, cancel, intro, isCancel, log, outro } from \"@clack/prompts\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, Option } from \"effect\"\nimport { EOL } from \"node:os\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\nimport { errorMessage } from \"../../util/error\"\n\nexport default Runtime.handler(\n Commands.commands.export,\n Effect.fn(\"cli.export\")((input) =>\n Effect.gen(function* () {\n const requested = Option.getOrUndefined(input.session)\n if (!requested && !process.stdin.isTTY) {\n yield* Effect.fail(new Error(\"Pass a session ID when running without an interactive terminal\"))\n }\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({\n baseUrl: server.endpoint.url,\n headers: Service.headers(server.endpoint),\n })\n const sessionID = requested\n ? requested\n : yield* Effect.gen(function* () {\n intro(\"Export session\", { output: process.stderr })\n const location = yield* Effect.tryPromise({\n try: () => client.location.get({ location: { directory: process.cwd() } }),\n catch: (cause) => cause,\n })\n const page = yield* Effect.tryPromise({\n try: () =>\n client.session.list({\n directory: location.directory,\n workspace: location.workspaceID,\n parentID: null,\n order: \"desc\",\n limit: 50,\n }),\n catch: (cause) => cause,\n })\n if (page.data.length === 0) {\n log.error(\"No sessions found\", { output: process.stderr })\n outro(\"Done\", { output: process.stderr })\n return undefined\n }\n const selected = yield* Effect.tryPromise({\n try: () =>\n autocomplete({\n message: \"Select session to export\",\n maxItems: 10,\n options: page.data.map((session) => ({\n label: session.title,\n value: session.id,\n hint: `${new Date(session.time.updated).toLocaleString()} - ${session.id.slice(-8)}`,\n })),\n output: process.stderr,\n }),\n catch: (cause) => cause,\n })\n if (isCancel(selected)) {\n cancel(\"Cancelled\", { output: process.stderr })\n process.exitCode = 130\n return undefined\n }\n outro(\"Exporting session...\", { output: process.stderr })\n return selected\n })\n if (!sessionID) return\n const data = yield* Effect.tryPromise({\n try: () => client.session.export({ sessionID, sanitize: input.sanitize }),\n catch: (cause) => cause,\n })\n process.stdout.write(JSON.stringify(data, null, 2) + EOL)\n }).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n process.stderr.write(errorMessage(error) + EOL)\n process.exitCode = 1\n }),\n ),\n ),\n ),\n)\n" | ||
| ], | ||
| "mappings": ";8vCAIA,cAAS,WAMT,IAAe,IAAQ,QACrB,EAAS,SAAS,OAClB,EAAO,GAAG,YAAY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EAAE,GACnF,EAAE,EACF,OAAQ,QAAQ,MAClB,CAAC,EACH,MAAO,CAAC,IAAU,CACpB,CAAC,EACD,GAAI,EAAS,CAAQ,EAAG,CACtB,EAAO,YAAa,CAAE,OAAQ,QAAQ,MAAO,CAAC,EAC9C,QAAQ,SAAW,IACnB,OAGF,OADA,EAAM,uBAAwB,CAAE,OAAQ,QAAQ,MAAO,CAAC,EACjD,EACR,EACL,GAAI,CAAC,EAAW,OAChB,IAAM,EAAO,MAAO,EAAO,WAAW,CACpC,IAAK,IAAM,EAAO,QAAQ,OAAO,CAAE,YAAW,SAAU,EAAM,QAAS,CAAC,EACxE,MAAO,CAAC,IAAU,CACpB,CAAC,EACD,QAAQ,OAAO,MAAM,KAAK,UAAU,EAAM,KAAM,CAAC,EAAI,CAAG,EACzD,EAAE,KACD,EAAO,MAAM,CAAC,IACZ,EAAO,KAAK,IAAM,CAChB,QAAQ,OAAO,MAAM,EAAa,CAAK,EAAI,CAAG,EAC9C,QAAQ,SAAW,EACpB,CACH,CACF,CACF,CACF", | ||
| "debugId": "60542D29D24FA4DF64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/api.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { Service, type Endpoint } from \"@opencode-ai/client/effect/service\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nconst methods = new Set([\"delete\", \"get\", \"head\", \"options\", \"patch\", \"post\", \"put\"])\n\ntype Operation = {\n operationId?: string\n}\n\ntype OpenApi = {\n paths?: Record<string, Record<string, Operation>>\n}\n\nexport default Runtime.handler(\n Commands.commands.api,\n Effect.fn(\"cli.api\")(function* (input) {\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n mismatch: \"ignore\",\n })\n const endpoint = server.endpoint\n const params = Option.getOrElse(input.param, () => ({}))\n const request = yield* resolveRequest(endpoint, input.request, params)\n const headers = new Headers(Service.headers(endpoint))\n for (const header of input.header) {\n const index = header.indexOf(\":\")\n if (index < 1) return yield* Effect.fail(new Error(`Invalid header, expected name:value: ${header}`))\n headers.set(header.slice(0, index).trim(), header.slice(index + 1).trim())\n }\n const body = Option.getOrUndefined(input.data)\n if (body !== undefined && !headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\")\n\n const response = yield* Effect.tryPromise(() =>\n fetch(new URL(request.path, endpoint.url), {\n method: request.method,\n headers,\n body,\n }),\n )\n const output = yield* Effect.promise(() => response.text())\n if (output) process.stdout.write(output + (output.endsWith(EOL) ? \"\" : EOL))\n }),\n)\n\nexport function resolveOperation(spec: OpenApi, operationID: string, params: Record<string, string>) {\n for (const [path, operations] of Object.entries(spec.paths ?? {})) {\n for (const [method, operation] of Object.entries(operations)) {\n if (!methods.has(method) || operation.operationId !== operationID) continue\n return { method: method.toUpperCase(), path: interpolate(path, params) }\n }\n }\n throw new Error(`Operation not found: ${operationID}`)\n}\n\nexport function rawRequest(input: readonly string[]) {\n if (input.length !== 2 || !methods.has(input[0].toLowerCase()) || !input[1].startsWith(\"/\")) return\n return { method: input[0].toUpperCase(), path: input[1] }\n}\n\nfunction resolveRequest(endpoint: Endpoint, input: readonly string[], params: Record<string, string>) {\n const raw = rawRequest(input)\n if (raw) return Effect.succeed(raw)\n if (input.length !== 1) return Effect.fail(new Error(\"Expected an operation name or an HTTP method and path\"))\n return Effect.tryPromise(async () => {\n const response = await fetch(new URL(\"/openapi.json\", endpoint.url), { headers: Service.headers(endpoint) })\n if (!response.ok) throw new Error(`Failed to load OpenAPI document: HTTP ${response.status}`)\n return resolveOperation((await response.json()) as OpenApi, input[0], params)\n })\n}\n\nfunction interpolate(path: string, params: Record<string, string>) {\n const used = new Set<string>()\n const pathname = path.replaceAll(/\\{([^}]+)\\}/g, (_, name: string) => {\n const value = params[name]\n if (value === undefined) throw new Error(`Missing path parameter: ${name}`)\n used.add(name)\n return encodeURIComponent(value)\n })\n const query = new URLSearchParams(Object.entries(params).filter(([name]) => !used.has(name))).toString()\n return query ? `${pathname}?${query}` : pathname\n}\n" | ||
| ], | ||
| "mappings": ";0jCAAA,cAAS,WAOT,IAAM,EAAU,IAAI,IAAI,CAAC,SAAU,MAAO,OAAQ,UAAW,QAAS,OAAQ,KAAK,CAAC,EAUrE,IAAQ,QACrB,EAAS,SAAS,IAClB,EAAO,GAAG,SAAS,EAAE,SAAU,CAAC,EAAO,CAMrC,IAAM,GALS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,WAClB,SAAU,QACZ,CAAC,GACuB,SAClB,EAAS,EAAO,UAAU,EAAM,MAAO,KAAO,CAAC,EAAE,EACjD,EAAU,MAAO,EAAe,EAAU,EAAM,QAAS,CAAM,EAC/D,EAAU,IAAI,QAAQ,EAAQ,QAAQ,CAAQ,CAAC,EACrD,QAAW,KAAU,EAAM,OAAQ,CACjC,IAAM,EAAQ,EAAO,QAAQ,GAAG,EAChC,GAAI,EAAQ,EAAG,OAAO,MAAO,EAAO,KAAS,MAAM,wCAAwC,GAAQ,CAAC,EACpG,EAAQ,IAAI,EAAO,MAAM,EAAG,CAAK,EAAE,KAAK,EAAG,EAAO,MAAM,EAAQ,CAAC,EAAE,KAAK,CAAC,EAE3E,IAAM,EAAO,EAAO,eAAe,EAAM,IAAI,EAC7C,GAAI,IAAS,QAAa,CAAC,EAAQ,IAAI,cAAc,EAAG,EAAQ,IAAI,eAAgB,kBAAkB,EAEtG,IAAM,EAAW,MAAO,EAAO,WAAW,IACxC,MAAM,IAAI,IAAI,EAAQ,KAAM,EAAS,GAAG,EAAG,CACzC,OAAQ,EAAQ,OAChB,UACA,MACF,CAAC,CACH,EACM,EAAS,MAAO,EAAO,QAAQ,IAAM,EAAS,KAAK,CAAC,EAC1D,GAAI,EAAQ,QAAQ,OAAO,MAAM,GA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U,MAAM,2BAA2B,GAAM,EAE1E,OADA,EAAK,IAAI,CAAI,EACN,mBAAmB,CAAK,EAChC,EACK,EAAQ,IAAI,gBAAgB,OAAO,QAAQ,CAAM,EAAE,OAAO,EAAE,KAAU,CAAC,EAAK,IAAI,CAAI,CAAC,CAAC,EAAE,SAAS,EACvG,OAAO,EAAQ,GAAG,KAAY,IAAU", | ||
| "debugId": "2B41367A6F5476D064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "3ACFFCBCB3348C1364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/check.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { format, inspect } from \"./inventory\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.check,\n Effect.fn(\"cli.plugin.check\")(function* (input) {\n const result = yield* inspect(Option.getOrUndefined(input.target))\n process.stdout.write((format(result.items) || \"No package plugins found\") + EOL)\n if (result.items.some((item) => item.error)) process.exitCode = 1\n }),\n)\n" | ||
| ], | ||
| "mappings": ";u+BAAA,cAAS,WAMT,IAAe,IAAQ,QACrB,EAAS,SAAS,OAAO,SAAS,MAClC,EAAO,GAAG,kBAAkB,EAAE,SAAU,CAAC,EAAO,CAC9C,IAAM,EAAS,MAAO,EAAQ,EAAO,eAAe,EAAM,MAAM,CAAC,EAEjE,GADA,QAAQ,OAAO,OAAO,EAAO,EAAO,KAAK,GAAK,4BAA8B,CAAG,EAC3E,EAAO,MAAM,KAAK,CAAC,IAAS,EAAK,KAAK,EAAG,QAAQ,SAAW,EACjE,CACH", | ||
| "debugId": "84CE05484F5B2A4B64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/workspace-event.ts"], | ||
| "sourcesContent": [ | ||
| "export * as WorkspaceEvent from \"./workspace-event.js\"\n\nimport { Schema } from \"effect\"\nimport { Event } from \"./event.js\"\nimport { WorkspaceID } from \"./workspace-id.js\"\n\nexport const ConnectionStatus = Schema.Struct({\n workspaceID: WorkspaceID,\n status: Schema.Literals([\"connected\", \"connecting\", \"disconnected\", \"error\"]),\n}).annotate({ identifier: \"WorkspaceEvent.ConnectionStatus\" })\nexport interface ConnectionStatus extends Schema.Schema.Type<typeof ConnectionStatus> {}\n\nexport const Ready = Event.ephemeral({\n type: \"workspace.ready\",\n schema: {\n name: Schema.String,\n },\n})\n\nexport const Failed = Event.ephemeral({\n type: \"workspace.failed\",\n schema: {\n message: Schema.String,\n },\n})\n\nexport const Status = Event.ephemeral({\n type: \"workspace.status\",\n schema: ConnectionStatus.fields,\n})\n\nexport const Definitions = Event.inventory(Ready, Failed, Status)\n" | ||
| ], | ||
| "mappings": ";wRAMO,IAAM,EAAmB,EAAO,OAAO,CAC5C,YAAa,EACb,OAAQ,EAAO,SAAS,CAAC,YAAa,aAAc,eAAgB,OAAO,CAAC,CAC9E,CAAC,EAAE,SAAS,CAAE,WAAY,iCAAkC,CAAC,EAGhD,EAAQ,EAAM,UAAU,CACnC,KAAM,kBACN,OAAQ,CACN,KAAM,EAAO,MACf,CACF,CAAC,EAEY,EAAS,EAAM,UAAU,CACpC,KAAM,mBACN,OAAQ,CACN,QAAS,EAAO,MAClB,CACF,CAAC,EAEY,EAAS,EAAM,UAAU,CACpC,KAAM,mBACN,OAAQ,EAAiB,MAC3B,CAAC,EAEY,EAAc,EAAM,UAAU,EAAO,EAAQ,CAAM", | ||
| "debugId": "6EB452221E5384D464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "02DB3858BC91125064756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/stats.ts"], | ||
| "sourcesContent": [ | ||
| "import { ClientError, OpenCode, type SessionStatsInfo } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { TokenUsage } from \"@opencode-ai/schema/token-usage\"\nimport { activityCalendar } from \"@opencode-ai/util/activity-calendar\"\nimport { Effect, Option } from \"effect\"\nimport { EOL } from \"node:os\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\nimport { errorMessage } from \"../../util/error\"\n\nconst handler = Effect.fn(\"cli.stats\")(function* (input: Runtime.Input<typeof Commands.commands.stats>) {\n const days = Option.getOrUndefined(input.days)\n const year = Option.getOrUndefined(input.year)\n const project = Option.getOrUndefined(input.project)\n if ([days !== undefined, year !== undefined, input.all].filter(Boolean).length > 1)\n yield* Effect.fail(new Error(\"--days, --year, and --all cannot be combined\"))\n\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({ baseUrl: server.endpoint.url, headers: Service.headers(server.endpoint) })\n const range = statsRange({ days, year, all: input.all })\n const projectID =\n project === \".\"\n ? yield* request(server.endpoint.url, (signal) =>\n client.location\n .get({ location: { directory: process.cwd() } }, { signal })\n .then((location) => location.project.id),\n )\n : project\n const details = input.models || input.tools || input.cost || input.full\n const stats = yield* request(server.endpoint.url, (signal) =>\n client.session.stats(\n {\n from: range.from,\n to: range.to,\n project: projectID,\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\",\n tools: input.json || input.tools || input.full ? \"detail\" : details ? \"none\" : \"summary\",\n },\n { signal },\n ),\n )\n const output = input.json\n ? JSON.stringify(stats, null, 2)\n : renderStats(stats, {\n label: range.label,\n scope: project === undefined ? \"all projects\" : project === \".\" ? \"current project\" : \"selected project\",\n models: input.models || input.full,\n tools: input.tools || input.full,\n cost: input.cost || input.full,\n limit: input.limit,\n color: process.stdout.isTTY && process.env.NO_COLOR === undefined,\n width: process.stdout.columns ?? 80,\n })\n process.stdout.write(output + EOL)\n})\n\nexport default Runtime.handler(Commands.commands.stats, (input) =>\n handler(input).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n process.stderr.write(errorMessage(error) + EOL)\n process.exitCode = 1\n }),\n ),\n ),\n)\n\nexport function request<A>(url: string, run: (signal: AbortSignal) => Promise<A>) {\n return Effect.tryPromise({\n try: () => run(AbortSignal.timeout(30_000)),\n catch: (cause) =>\n cause instanceof ClientError && cause.reason === \"Transport\"\n ? new Error(`Could not reach server at ${url}`, { cause })\n : cause,\n })\n}\n\ntype RenderOptions = {\n label: string\n scope: string\n models: boolean\n tools: boolean\n cost: boolean\n limit: number\n color: boolean\n width: number\n}\n\nconst colors = terminalPalette()\n\nexport function renderStats(stats: SessionStatsInfo, options: RenderOptions) {\n const totalTokens = TokenUsage.total(stats.tokens)\n const toolTotals = stats.tools.mode === \"none\" ? undefined : stats.tools.totals\n const terminalTools = toolTotals ? toolTotals.succeeded + toolTotals.failed : 0\n const toolRate = !toolTotals || terminalTools === 0 ? undefined : (toolTotals.succeeded / terminalTools) * 100\n const primary = `1;${colors.primary}`\n const sessionLine = [\n metricCount(stats.sessions, \"session\", options.color),\n stats.subagents > 0 ? metricCount(stats.subagents, \"subagent\", options.color) : undefined,\n ]\n .filter((value) => value !== undefined)\n .join(\" · \")\n const toolSummary = !toolTotals\n ? \"tool stats unavailable\"\n : toolRate === undefined\n ? \"no tool calls\"\n : `${style(formatPercent(toolRate), primary, options.color)} tool success`\n const details = options.models || options.tools || options.cost\n const empty = stats.sessions === 0 && stats.prompts === 0 && stats.steps === 0\n const heading = `${style(\"opencode stats\", primary, options.color)} ${style(`· ${options.label} · ${options.scope}`, \"2\", options.color)}`\n const lines = details\n ? [style(`${options.label} · ${options.scope}`, \"2\", options.color)]\n : empty\n ? [\n heading,\n \"\",\n style(\"no activity in this range\", \"2\", options.color),\n \"\",\n style(\"opencode.ai\", \"2\", options.color),\n ]\n : [\n heading,\n \"\",\n ...renderActivity(stats.activity, stats.range.from, stats.range.to, options.color, options.width),\n \"\",\n sessionLine,\n `${metricCount(stats.prompts, \"prompt\", options.color)} · ${metricCount(stats.steps, \"step\", options.color)} · ${metricCount(totalTokens, \"token\", options.color)}`,\n `${toolSummary} · ${metricCount(stats.activeDays, \"active day\", options.color)} · best streak ${style(stats.streak.toString(), primary, options.color)} day${stats.streak === 1 ? \"\" : \"s\"}`,\n \"\",\n style(\"opencode.ai\", \"2\", options.color),\n ]\n\n if (options.cost) lines.push(...(lines.length > 0 ? [\"\"] : []), ...renderCost(stats))\n if (options.models)\n lines.push(...(lines.length > 0 ? [\"\"] : []), ...renderModels(stats, options.limit, options.width))\n if (options.tools) lines.push(...(lines.length > 0 ? [\"\"] : []), ...renderTools(stats, options.limit, options.width))\n return lines.join(EOL)\n}\n\nfunction statsRange(input: { days?: number; year?: number; all: boolean }) {\n const now = new Date()\n const to = now.getTime() + 1\n if (input.all) return { from: undefined, to, label: \"all time\" }\n if (input.days !== undefined) {\n const from = new Date(now.getFullYear(), now.getMonth(), now.getDate())\n from.setDate(from.getDate() - Math.max(0, input.days - 1))\n return {\n from: from.getTime(),\n to,\n label: input.days === 0 || input.days === 1 ? \"today\" : `last ${input.days} days`,\n }\n }\n const year = input.year ?? now.getFullYear()\n return {\n from: new Date(year, 0, 1).getTime(),\n to: year === now.getFullYear() ? to : new Date(year + 1, 0, 1).getTime(),\n label: year === now.getFullYear() ? `${year} so far` : year.toString(),\n }\n}\n\nfunction renderActivity(\n activity: SessionStatsInfo[\"activity\"],\n from: number,\n to: number,\n color: boolean,\n width: number,\n) {\n const calendar = activityCalendar({ activity, from, to, maxWeeks: width - 4 })\n const months = calendar.months\n .map((month, index) =>\n (index === calendar.months.length - 1 || month.label.length <= month.span ? month.label : \"\").padEnd(month.span),\n )\n .join(\"\")\n .trimEnd()\n const weekdays = [\"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\", \"Su\"]\n return [\n style(\n calendar.clipped ? `activity · last ${calendar.weeks.length} weeks` : \"activity\",\n `1;${colors.primary}`,\n color,\n ),\n ` ${style(months, \"2\", color)}`,\n ...weekdays.flatMap((label, day) => [\n `${style(label, \"2\", color)} ${calendar.weeks.map((week) => (week[day].level < 0 ? \" \" : paintActivity(week[day].level, color))).join(\"\")}`,\n ...(day === weekdays.length - 1 ? [] : [\"\"]),\n ]),\n \"\",\n ` ${style(\"less\", \"2\", color)} ${[0, 1, 2, 3, 4].map((level) => paintActivity(level, color)).join(\"\")} ${style(\"more\", \"2\", color)}`,\n ]\n}\n\nfunction renderCost(stats: SessionStatsInfo) {\n const input = stats.tokens.input + stats.tokens.cache.read + stats.tokens.cache.write\n const cached = input === 0 ? 0 : (stats.tokens.cache.read / input) * 100\n return [\n \"COST & TOKENS\",\n row(\"cost\", `$${stats.cost.toFixed(2)}`),\n row(\"input\", formatNumber(stats.tokens.input)),\n row(\"output\", formatNumber(stats.tokens.output)),\n row(\"reasoning\", formatNumber(stats.tokens.reasoning)),\n row(\"cache read\", formatNumber(stats.tokens.cache.read)),\n row(\"cache write\", formatNumber(stats.tokens.cache.write)),\n row(\"cached input\", formatPercent(cached)),\n ]\n}\n\nfunction renderModels(stats: SessionStatsInfo, limit: number, width: number) {\n if (stats.models.length === 0) return [\"MODELS\", \" no model usage\"]\n const models = stats.models.slice(0, limit)\n const more = stats.models.length - models.length\n if (width < 68)\n return [\n \"MODELS\",\n ...models.flatMap((item) => [\n truncate(\n `${item.model.providerID}/${item.model.id}${item.model.variant ? `#${item.model.variant}` : \"\"}`,\n width,\n ),\n ` ${formatNumber(TokenUsage.total(item.tokens))} tokens · ${formatNumber(item.steps)} steps · $${item.cost.toFixed(2)}`,\n ]),\n ...(more > 0 ? [\"\", `+${more.toLocaleString(\"en-US\")} more model${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n return [\n \"MODELS\",\n tableHeader(\"model\", \"tokens\", \"steps\", \"cost\"),\n ...models.map((item) =>\n tableRow(\n `${item.model.providerID}/${item.model.id}${item.model.variant ? `#${item.model.variant}` : \"\"}`,\n formatNumber(TokenUsage.total(item.tokens)),\n formatNumber(item.steps),\n `$${item.cost.toFixed(2)}`,\n ),\n ),\n ...(more > 0 ? [\"\", `+${more.toLocaleString(\"en-US\")} more model${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n}\n\nfunction renderTools(stats: SessionStatsInfo, limit: number, width: number) {\n if (stats.tools.mode !== \"detail\") return [\"TOOL RELIABILITY\", \" tool details unavailable\"]\n if (stats.tools.usage.length === 0) return [\"TOOL RELIABILITY\", \" no tool calls\"]\n const tools = stats.tools.usage.slice(0, limit)\n const more = stats.tools.usage.length - tools.length\n if (width < 68)\n return [\n \"TOOL RELIABILITY\",\n ...tools.flatMap((tool) => {\n const terminal = tool.succeeded + tool.failed\n return [\n truncate(tool.name, width),\n ` ${formatNumber(tool.calls)} calls · ${terminal === 0 ? \"-\" : formatPercent((tool.failed / terminal) * 100)} error · ${tool.durationP50 === undefined ? \"-\" : formatDuration(tool.durationP50)} p50`,\n ]\n }),\n \"\",\n `${formatNumber(stats.tools.totals.succeeded + stats.tools.totals.failed)} finished calls · ${formatNumber(stats.tools.totals.unfinished)} unfinished`,\n ...(more > 0 ? [`+${more.toLocaleString(\"en-US\")} more tool${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n return [\n \"TOOL RELIABILITY\",\n tableHeader(\"tool\", \"calls\", \"error\", \"p50\"),\n ...tools.map((tool) => {\n const terminal = tool.succeeded + tool.failed\n return tableRow(\n tool.name,\n formatNumber(tool.calls),\n terminal === 0 ? \"-\" : formatPercent((tool.failed / terminal) * 100),\n tool.durationP50 === undefined ? \"-\" : formatDuration(tool.durationP50),\n )\n }),\n \"\",\n `${formatNumber(stats.tools.totals.succeeded + stats.tools.totals.failed)} finished calls · ${formatNumber(stats.tools.totals.unfinished)} unfinished`,\n ...(more > 0 ? [`+${more.toLocaleString(\"en-US\")} more tool${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n}\n\nfunction row(label: string, value: string) {\n return ` ${label.padEnd(20)}${value}`\n}\n\nfunction tableHeader(label: string, second: string, third: string, fourth: string) {\n return tableRow(label, second, third, fourth)\n}\n\nfunction tableRow(label: string, second: string, third: string, fourth: string) {\n return `${truncate(label, 34).padEnd(34)}${second.padStart(10)}${third.padStart(12)}${fourth.padStart(12)}`\n}\n\nfunction truncate(value: string, width: number) {\n return value.length <= width ? value : value.slice(0, width - 1) + \"…\"\n}\n\nfunction formatNumber(value: number) {\n if (value >= 1_000_000_000) return `${trimDecimal(value / 1_000_000_000)}b`\n if (value >= 1_000_000) return `${trimDecimal(value / 1_000_000)}m`\n if (value >= 1_000) return `${trimDecimal(value / 1_000)}k`\n return Math.round(value).toLocaleString(\"en-US\")\n}\n\nfunction trimDecimal(value: number) {\n return value.toFixed(1).replace(/\\.0$/, \"\")\n}\n\nfunction formatPercent(value: number) {\n return `${value.toFixed(value >= 10 ? 1 : 2)}%`\n}\n\nfunction formatDuration(value: number) {\n if (value < 1_000) return `${Math.round(value)}ms`\n return `${trimDecimal(value / 1_000)}s`\n}\n\nfunction metricCount(value: number, noun: string, color: boolean) {\n return `${style(formatNumber(value), `1;${colors.primary}`, color)} ${noun}${value === 1 ? \"\" : \"s\"}`\n}\n\nfunction style(value: string, code: string, color: boolean) {\n return color ? `\\x1b[${code}m${value}\\x1b[0m` : value\n}\n\nfunction paintActivity(level: number, color: boolean) {\n const glyph = [\"·\", \"░\", \"▒\", \"▓\", \"█\"][level]\n if (!color) return glyph\n if (level === 0) return `\\x1b[2m${glyph}\\x1b[22m`\n return `\\x1b[${colors.activity[level - 1]}m${glyph}\\x1b[39m`\n}\n\nfunction terminalPalette() {\n const background = Number(process.env.COLORFGBG?.split(\";\").at(-1))\n if (Number.isFinite(background) && background >= 7)\n return {\n primary: \"38;2;59;125;216\",\n activity: [\"38;2;153;169;192\", \"38;2;122;155;200\", \"38;2;90;140;208\", \"38;2;59;125;216\"],\n }\n if (Number.isFinite(background))\n return {\n primary: \"38;2;250;178;131\",\n activity: [\"38;2;117;99;87\", \"38;2;161;125;102\", \"38;2;206;152;116\", \"38;2;250;178;131\"],\n }\n return { primary: \"36\", activity: [\"2;36\", \"36\", \"1;36\", \"1;96\"] }\n}\n" | ||
| ], | ||
| "mappings": ";2uCAKA,cAAS,WAMT,IAAM,EAAU,EAAO,GAAG,WAAW,EAAE,SAAU,CAAC,EAAsD,CACtG,IAAM,EAAO,EAAO,eAAe,EAAM,IAAI,EACvC,EAAO,EAAO,eAAe,EAAM,IAAI,EACvC,EAAU,EAAO,eAAe,EAAM,OAAO,EACnD,GAAI,CAAC,IAAS,OAAW,IAAS,OAAW,EAAM,GAAG,EAAE,OAAO,OAAO,EAAE,OAAS,EAC/E,MAAO,EAAO,KAAS,MAAM,8CAA8C,CAAC,EAE9E,IAAM,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EACK,EAAS,EAAS,KAAK,CAAE,QAAS,EAAO,SAAS,IAAK,QAAS,EAAQ,QAAQ,EAAO,QAAQ,CAAE,CAAC,EAClG,EAAQ,EAAW,CAAE,OAAM,OAAM,IAAK,EAAM,GAAI,CAAC,EACjD,EACJ,IAAY,IACR,MAAO,EAAQ,EAAO,SAAS,IAAK,CAAC,IACnC,EAAO,SACJ,IAAI,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,EAAG,CAAE,QAAO,CAAC,EAC1D,KAAK,CAAC,IAAa,EAAS,QAAQ,EAAE,CAC3C,EACA,EACA,EAAU,EAAM,QAAU,EAAM,OAAS,EAAM,MAAQ,EAAM,KAC7D,EAAQ,MAAO,EAAQ,EAAO,SAAS,IAAK,CAAC,IACjD,EAAO,QAAQ,MACb,CACE,KAAM,EAAM,KACZ,GAA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a,CAAC,EAAe,EAAgB,CACpD,IAAM,EAAQ,CAAC,OAAK,SAAK,SAAK,SAAK,QAAG,EAAE,GACxC,GAAI,CAAC,EAAO,OAAO,EACnB,GAAI,IAAU,EAAG,MAAO,UAAU,YAClC,MAAO,QAAQ,EAAO,SAAS,EAAQ,MAAM,YAG/C,SAAS,CAAe,EAAG,CACzB,IAAM,EAAa,OAAO,QAAQ,IAAI,WAAW,MAAM,GAAG,EAAE,GAAG,EAAE,CAAC,EAClE,GAAI,OAAO,SAAS,CAAU,GAAK,GAAc,EAC/C,MAAO,CACL,QAAS,kBACT,SAAU,CAAC,mBAAoB,mBAAoB,kBAAmB,iBAAiB,CACzF,EACF,GAAI,OAAO,SAAS,CAAU,EAC5B,MAAO,CACL,QAAS,mBACT,SAAU,CAAC,iBAAkB,mBAAoB,mBAAoB,kBAAkB,CACzF,EACF,MAAO,CAAE,QAAS,KAAM,SAAU,CAAC,OAAQ,KAAM,OAAQ,MAAM,CAAE", | ||
| "debugId": "7B11460157B75ABB64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/get.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.get,\n Effect.fn(\"cli.service.get\")(function* (input) {\n process.stdout.write(\n (yield* ServiceConfig.get(Option.getOrUndefined(input.key), Option.getOrUndefined(input.name))) + EOL,\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";i5BAAA,cAAS,WAMT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,IACnC,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAAO,CAC7C,QAAQ,OAAO,OACZ,MAAO,EAAc,IAAI,EAAO,eAAe,EAAM,GAAG,EAAG,EAAO,eAAe,EAAM,IAAI,CAAC,GAAK,CACpG,EACD,CACH", | ||
| "debugId": "7573124546E7E74864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/filesystem.ts"], | ||
| "sourcesContent": [ | ||
| "export * as FileSystem from \"./filesystem.js\"\n\nimport { Schema } from \"effect\"\nimport { optional } from \"./schema.js\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { NonNegativeInt, PositiveInt, RelativePath } from \"./schema.js\"\n\nconst Changed = ephemeral({\n type: \"filesystem.changed\",\n schema: {\n file: Schema.String,\n event: Schema.Literals([\"add\", \"change\", \"unlink\"]),\n },\n})\nexport const Event = { Changed, Definitions: inventory(Changed) }\n\nexport interface Entry extends Schema.Schema.Type<typeof Entry> {}\nexport const Entry = Schema.Struct({\n path: RelativePath,\n type: Schema.Literals([\"file\", \"directory\"]),\n}).annotate({ identifier: \"FileSystem.Entry\" })\n\nexport interface Submatch extends Schema.Schema.Type<typeof Submatch> {}\nexport const Submatch = Schema.Struct({\n text: Schema.String,\n start: NonNegativeInt,\n end: NonNegativeInt,\n}).annotate({ identifier: \"FileSystem.Submatch\" })\n\nexport interface Match extends Schema.Schema.Type<typeof Match> {}\nexport const Match = Schema.Struct({\n entry: Entry,\n line: PositiveInt,\n offset: NonNegativeInt,\n text: Schema.String,\n submatches: Schema.Array(Submatch),\n}).annotate({ identifier: \"FileSystem.Match\" })\n\nexport class FindInput extends Schema.Class<FindInput>(\"FileSystem.FindInput\")({\n query: Schema.String,\n type: Schema.Literals([\"file\", \"directory\"]).pipe(optional),\n limit: PositiveInt.pipe(optional),\n}) {}\n" | ||
| ], | ||
| "mappings": ";oVAOA,IAAM,EAAU,EAAU,CACxB,KAAM,qBACN,OAAQ,CACN,KAAM,EAAO,OACb,MAAO,EAAO,SAAS,CAAC,MAAO,SAAU,QAAQ,CAAC,CACpD,CACF,CAAC,EACY,EAAQ,CAAE,UAAS,YAAa,EAAU,CAAO,CAAE,EAGnD,EAAQ,EAAO,OAAO,CACjC,KAAM,EACN,KAAM,EAAO,SAAS,CAAC,OAAQ,WAAW,CAAC,CAC7C,CAAC,EAAE,SAAS,CAAE,WAAY,kBAAmB,CAAC,EAGjC,EAAW,EAAO,OAAO,CACpC,KAAM,EAAO,OACb,MAAO,EACP,IAAK,CACP,CAAC,EAAE,SAAS,CAAE,WAAY,qBAAsB,CAAC,EAGpC,EAAQ,EAAO,OAAO,CACjC,MAAO,EACP,KAAM,EACN,OAAQ,EACR,KAAM,EAAO,OACb,WAAY,EAAO,MAAM,CAAQ,CACnC,CAAC,EAAE,SAAS,CAAE,WAAY,kBAAmB,CAAC,EAEvC,MAAM,UAAkB,EAAO,MAAiB,sBAAsB,EAAE,CAC7E,MAAO,EAAO,OACd,KAAM,EAAO,SAAS,CAAC,OAAQ,WAAW,CAAC,EAAE,KAAK,CAAQ,EAC1D,MAAO,EAAY,KAAK,CAAQ,CAClC,CAAC,CAAE,CAAC", | ||
| "debugId": "B46A8CBB6C419EB564756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/restart.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { ServerConnection } from \"../../../services/server-connection\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.restart,\n Effect.fn(\"cli.service.restart\")(function* () {\n const options = yield* ServiceConfig.options()\n // Keep this explicit: automatic service replacement must preserve terminals.\n yield* ServerConnection.shutdownPersistentPty(options).pipe(Effect.ignore)\n yield* Service.stop(options)\n const transport = yield* Service.ensure(options)\n process.stdout.write(transport.url + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+jCAAA,cAAS,WAQT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,QACnC,EAAO,GAAG,qBAAqB,EAAE,SAAU,EAAG,CAC5C,IAAM,EAAU,MAAO,EAAc,QAAQ,EAE7C,MAAO,EAAiB,sBAAsB,CAAO,EAAE,KAAK,EAAO,MAAM,EACzE,MAAO,EAAQ,KAAK,CAAO,EAC3B,IAAM,EAAY,MAAO,EAAQ,OAAO,CAAO,EAC/C,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH", | ||
| "debugId": "FE6FFC1F8308B30264756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@smithy+node-http-handler@4.11.2/node_modules/@smithy/node-http-handler/dist-cjs/index.js"], | ||
| "sourcesContent": [ | ||
| "const { buildQueryString, HttpResponse } = require(\"@smithy/core/protocols\");\nconst node_https = require(\"node:https\");\nconst { Readable } = require(\"node:stream\");\nconst http2 = require(\"node:http2\");\nconst { streamCollector } = require(\"@smithy/core/serde\");\nexports.streamCollector = streamCollector;\n\nfunction buildAbortError(abortSignal) {\n const reason = abortSignal && typeof abortSignal === \"object\" && \"reason\" in abortSignal\n ? abortSignal.reason\n : undefined;\n if (reason) {\n if (reason instanceof Error) {\n const abortError = new Error(\"Request aborted\");\n abortError.name = \"AbortError\";\n abortError.cause = reason;\n return abortError;\n }\n const abortError = new Error(String(reason));\n abortError.name = \"AbortError\";\n return abortError;\n }\n const abortError = new Error(\"Request aborted\");\n abortError.name = \"AbortError\";\n return abortError;\n}\n\nconst NODEJS_TIMEOUT_ERROR_CODES = [\"ECONNRESET\", \"EPIPE\", \"ETIMEDOUT\"];\n\nconst getTransformedHeaders = (headers) => {\n const transformedHeaders = {};\n for (const name in headers) {\n const headerValues = headers[name];\n transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(\",\") : headerValues;\n }\n return transformedHeaders;\n};\n\nconst timing = {\n setTimeout: (cb, ms) => setTimeout(cb, ms),\n clearTimeout: (timeoutId) => clearTimeout(timeoutId),\n};\n\nconst DEFER_EVENT_LISTENER_TIME$2 = 1000;\nconst setConnectionTimeout = (request, reject, timeoutInMs = 0) => {\n if (!timeoutInMs) {\n return -1;\n }\n const registerTimeout = (offset) => {\n const timeoutId = timing.setTimeout(() => {\n request.destroy();\n reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${timeoutInMs} ms.`), {\n name: \"TimeoutError\",\n }));\n }, timeoutInMs - offset);\n const doWithSocket = (socket) => {\n if (socket?.connecting) {\n socket.on(\"connect\", () => {\n timing.clearTimeout(timeoutId);\n });\n }\n else {\n timing.clearTimeout(timeoutId);\n }\n };\n if (request.socket) {\n doWithSocket(request.socket);\n }\n else {\n request.on(\"socket\", doWithSocket);\n }\n };\n if (timeoutInMs < 2000) {\n registerTimeout(0);\n return 0;\n }\n return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME$2), DEFER_EVENT_LISTENER_TIME$2);\n};\n\nconst setRequestTimeout = (req, reject, timeoutInMs = 0, throwOnRequestTimeout, logger) => {\n if (timeoutInMs) {\n return timing.setTimeout(() => {\n let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? \"ERROR\" : \"WARN\"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`;\n if (throwOnRequestTimeout) {\n const error = Object.assign(new Error(msg), {\n name: \"TimeoutError\",\n code: \"ETIMEDOUT\",\n });\n req.destroy(error);\n reject(error);\n }\n else {\n msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`;\n logger?.warn?.(msg);\n }\n }, timeoutInMs);\n }\n return -1;\n};\n\nconst DEFER_EVENT_LISTENER_TIME$1 = 3000;\nconst setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME$1) => {\n if (keepAlive !== true) {\n return -1;\n }\n const registerListener = () => {\n if (request.socket) {\n request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);\n }\n else {\n request.on(\"socket\", (socket) => {\n socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);\n });\n }\n };\n if (deferTimeMs === 0) {\n registerListener();\n return 0;\n }\n return timing.setTimeout(registerListener, deferTimeMs);\n};\n\nconst DEFER_EVENT_LISTENER_TIME = 3000;\nconst setSocketTimeout = (request, reject, timeoutInMs = 0) => {\n const registerTimeout = (offset) => {\n const timeout = timeoutInMs - offset;\n const onTimeout = () => {\n request.destroy();\n reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket timed out after ${timeoutInMs} ms of inactivity (configured by client requestHandler).`), { name: \"TimeoutError\" }));\n };\n if (request.socket) {\n request.socket.setTimeout(timeout, onTimeout);\n request.on(\"close\", () => request.socket?.removeListener(\"timeout\", onTimeout));\n }\n else {\n request.setTimeout(timeout, onTimeout);\n }\n };\n if (0 < timeoutInMs && timeoutInMs < 6000) {\n registerTimeout(0);\n return 0;\n }\n return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME);\n};\n\nconst MIN_WAIT_TIME = 6_000;\nasync function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME, externalAgent = false) {\n const headers = request.headers;\n const expect = headers ? headers.Expect || headers.expect : undefined;\n let timeoutId = -1;\n let sendBody = true;\n if (!externalAgent && expect === \"100-continue\") {\n sendBody = await Promise.race([\n new Promise((resolve) => {\n timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)));\n }),\n new Promise((resolve) => {\n httpRequest.on(\"continue\", () => {\n timing.clearTimeout(timeoutId);\n resolve(true);\n });\n httpRequest.on(\"response\", () => {\n timing.clearTimeout(timeoutId);\n resolve(false);\n });\n httpRequest.on(\"error\", () => {\n timing.clearTimeout(timeoutId);\n resolve(false);\n });\n }),\n ]);\n }\n if (sendBody) {\n writeBody(httpRequest, request.body);\n }\n}\nfunction writeBody(httpRequest, body) {\n if (body instanceof Readable) {\n body.pipe(httpRequest);\n return;\n }\n if (body) {\n const isBuffer = Buffer.isBuffer(body);\n const isString = typeof body === \"string\";\n if (isBuffer || isString) {\n if (isBuffer && body.byteLength === 0) {\n httpRequest.end();\n }\n else {\n httpRequest.end(body);\n }\n return;\n }\n const uint8 = body;\n if (typeof uint8 === \"object\" &&\n uint8.buffer &&\n typeof uint8.byteOffset === \"number\" &&\n typeof uint8.byteLength === \"number\") {\n httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));\n return;\n }\n httpRequest.end(Buffer.from(body));\n return;\n }\n httpRequest.end();\n}\n\nconst DEFAULT_REQUEST_TIMEOUT = 0;\nlet hAgent = undefined;\nlet hRequest = undefined;\nclass NodeHttpHandler {\n config;\n configProvider;\n socketWarningTimestamp = 0;\n externalAgent = false;\n metadata = { handlerProtocol: \"http/1.1\" };\n static create(instanceOrOptions) {\n if (typeof instanceOrOptions?.handle === \"function\") {\n return instanceOrOptions;\n }\n return new NodeHttpHandler(instanceOrOptions);\n }\n static checkSocketUsage(agent, socketWarningTimestamp, logger = console) {\n const { sockets, requests, maxSockets } = agent;\n if (typeof maxSockets !== \"number\" || maxSockets === Infinity) {\n return socketWarningTimestamp;\n }\n const interval = 15_000;\n if (Date.now() - interval < socketWarningTimestamp) {\n return socketWarningTimestamp;\n }\n if (sockets && requests) {\n for (const origin in sockets) {\n const socketsInUse = sockets[origin]?.length ?? 0;\n const requestsEnqueued = requests[origin]?.length ?? 0;\n if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) {\n logger?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.\nSee https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html\nor increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`);\n return Date.now();\n }\n }\n }\n return socketWarningTimestamp;\n }\n constructor(options) {\n this.configProvider = new Promise((resolve, reject) => {\n if (typeof options === \"function\") {\n options()\n .then((_options) => {\n resolve(this.resolveDefaultConfig(_options));\n })\n .catch(reject);\n }\n else {\n resolve(this.resolveDefaultConfig(options));\n }\n });\n }\n destroy() {\n this.config?.httpAgent?.destroy();\n this.config?.httpsAgent?.destroy();\n }\n async handle(request, { abortSignal, requestTimeout } = {}) {\n if (!this.config) {\n this.config = await this.configProvider;\n }\n const config = this.config;\n const logger = config.logger;\n const isSSL = request.protocol === \"https:\";\n if (!isSSL && !this.config.httpAgent) {\n this.config.httpAgent = await this.config.httpAgentProvider();\n }\n return new Promise((_resolve, _reject) => {\n let writeRequestBodyPromise = undefined;\n let socketWarningTimeoutId = -1;\n let connectionTimeoutId = -1;\n let requestTimeoutId = -1;\n let socketTimeoutId = -1;\n let keepAliveTimeoutId = -1;\n const clearTimeouts = () => {\n timing.clearTimeout(socketWarningTimeoutId);\n timing.clearTimeout(connectionTimeoutId);\n timing.clearTimeout(requestTimeoutId);\n timing.clearTimeout(socketTimeoutId);\n timing.clearTimeout(keepAliveTimeoutId);\n };\n const resolve = async (arg) => {\n await writeRequestBodyPromise;\n clearTimeouts();\n _resolve(arg);\n };\n const reject = async (arg) => {\n await writeRequestBodyPromise;\n clearTimeouts();\n _reject(arg);\n };\n if (abortSignal?.aborted) {\n const abortError = buildAbortError(abortSignal);\n reject(abortError);\n return;\n }\n const headers = request.headers;\n const expectContinue = headers ? (headers.Expect ?? headers.expect) === \"100-continue\" : false;\n let agent = isSSL ? config.httpsAgent : config.httpAgent;\n if (expectContinue && !this.externalAgent) {\n agent = new (isSSL ? node_https.Agent : hAgent)({\n keepAlive: false,\n maxSockets: Infinity,\n });\n }\n socketWarningTimeoutId = timing.setTimeout(() => {\n this.socketWarningTimestamp = NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, logger);\n }, config.socketAcquisitionWarningTimeout ?? (config.requestTimeout ?? 2000) + (config.connectionTimeout ?? 1000));\n const queryString = request.query ? buildQueryString(request.query) : \"\";\n let auth = undefined;\n if (request.username != null || request.password != null) {\n const username = request.username ?? \"\";\n const password = request.password ?? \"\";\n auth = `${username}:${password}`;\n }\n let path = request.path;\n if (queryString) {\n path += `?${queryString}`;\n }\n if (request.fragment) {\n path += `#${request.fragment}`;\n }\n let hostname = request.hostname ?? \"\";\n if (hostname[0] === \"[\" && hostname.endsWith(\"]\")) {\n hostname = request.hostname.slice(1, -1);\n }\n else {\n hostname = request.hostname;\n }\n const nodeHttpsOptions = {\n headers: request.headers,\n host: hostname,\n method: request.method,\n path,\n port: request.port,\n agent,\n auth,\n };\n const requestFunc = isSSL ? node_https.request : hRequest;\n const req = requestFunc(nodeHttpsOptions, (res) => {\n const httpResponse = new HttpResponse({\n statusCode: res.statusCode || -1,\n reason: res.statusMessage,\n headers: getTransformedHeaders(res.headers),\n body: res,\n });\n resolve({ response: httpResponse });\n });\n req.on(\"error\", (err) => {\n if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) {\n reject(Object.assign(err, { name: \"TimeoutError\" }));\n }\n else {\n reject(err);\n }\n });\n if (abortSignal) {\n const onAbort = () => {\n req.destroy();\n const abortError = buildAbortError(abortSignal);\n reject(abortError);\n };\n if (typeof abortSignal.addEventListener === \"function\") {\n const signal = abortSignal;\n signal.addEventListener(\"abort\", onAbort, { once: true });\n req.once(\"close\", () => signal.removeEventListener(\"abort\", onAbort));\n }\n else {\n abortSignal.onabort = onAbort;\n }\n }\n const effectiveRequestTimeout = requestTimeout ?? config.requestTimeout;\n connectionTimeoutId = setConnectionTimeout(req, reject, config.connectionTimeout);\n requestTimeoutId = setRequestTimeout(req, reject, effectiveRequestTimeout, config.throwOnRequestTimeout, logger ?? console);\n socketTimeoutId = setSocketTimeout(req, reject, config.socketTimeout);\n const httpAgent = nodeHttpsOptions.agent;\n if (typeof httpAgent === \"object\" && \"keepAlive\" in httpAgent) {\n keepAliveTimeoutId = setSocketKeepAlive(req, {\n keepAlive: httpAgent.keepAlive,\n keepAliveMsecs: httpAgent.keepAliveMsecs,\n });\n }\n writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout, this.externalAgent).catch((e) => {\n clearTimeouts();\n return _reject(e);\n });\n });\n }\n updateHttpClientConfig(key, value) {\n this.config = undefined;\n this.configProvider = this.configProvider.then((config) => {\n if (key === Symbol.for(\"logger\")) {\n return {\n ...config,\n logger: config.logger ?? value,\n };\n }\n return {\n ...config,\n [key]: value,\n };\n });\n }\n httpHandlerConfigs() {\n return this.config ?? {};\n }\n resolveDefaultConfig(options) {\n const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, logger, } = options || {};\n const keepAlive = true;\n const maxSockets = 50;\n return {\n connectionTimeout,\n requestTimeout,\n socketTimeout,\n socketAcquisitionWarningTimeout,\n throwOnRequestTimeout,\n httpAgentProvider: async () => {\n const node_http = require('node:http');\n const { Agent, request } = node_http.default ?? node_http;\n hRequest = request;\n hAgent = Agent;\n if (httpAgent instanceof hAgent || typeof httpAgent?.destroy === \"function\") {\n this.externalAgent = true;\n return httpAgent;\n }\n return new hAgent({ keepAlive, maxSockets, ...httpAgent });\n },\n httpsAgent: (() => {\n if (httpsAgent instanceof node_https.Agent || typeof httpsAgent?.destroy === \"function\") {\n this.externalAgent = true;\n return httpsAgent;\n }\n return new node_https.Agent({ keepAlive, maxSockets, ...httpsAgent });\n })(),\n logger,\n };\n }\n}\n\nconst ids = new Uint16Array(1);\nclass ClientHttp2SessionRef {\n id = ids[0]++;\n total = 0;\n max = 0;\n session;\n refs = 0;\n constructor(session) {\n session.unref();\n this.session = session;\n }\n retain() {\n if (this.session.destroyed) {\n throw new Error(\"@smithy/node-http-handler - cannot acquire reference to destroyed session.\");\n }\n this.refs += 1;\n this.total += 1;\n this.max = Math.max(this.refs, this.max);\n this.session.ref();\n }\n free() {\n if (this.session.destroyed) {\n return;\n }\n this.refs -= 1;\n if (this.refs === 0) {\n this.session.unref();\n }\n if (this.refs < 0) {\n throw new Error(\"@smithy/node-http-handler - ClientHttp2Session refcount at zero, cannot decrement.\");\n }\n }\n deref() {\n return this.session;\n }\n close() {\n if (!this.session.closed) {\n this.session.close();\n }\n }\n destroy() {\n this.refs = 0;\n if (!this.session.destroyed) {\n this.session.destroy();\n }\n }\n useCount() {\n return this.refs;\n }\n}\n\nclass NodeHttp2ConnectionPool {\n sessions = [];\n maxConcurrency = 0;\n constructor(sessions) {\n this.sessions = (sessions ?? []).map((session) => new ClientHttp2SessionRef(session));\n }\n poll() {\n let cleanup = false;\n for (const session of this.sessions) {\n if (session.deref().destroyed) {\n cleanup = true;\n continue;\n }\n if (!this.maxConcurrency || session.useCount() < this.maxConcurrency) {\n return session;\n }\n }\n if (cleanup) {\n for (const session of this.sessions) {\n if (session.deref().destroyed) {\n this.remove(session);\n }\n }\n }\n }\n offerLast(ref) {\n this.sessions.push(ref);\n }\n remove(ref) {\n const ix = this.sessions.indexOf(ref);\n if (ix > -1) {\n this.sessions.splice(ix, 1);\n }\n }\n [Symbol.iterator]() {\n return this.sessions[Symbol.iterator]();\n }\n setMaxConcurrency(maxConcurrency) {\n this.maxConcurrency = maxConcurrency;\n }\n destroy(ref) {\n this.remove(ref);\n ref.destroy();\n }\n}\n\nclass NodeHttp2ConnectionManager {\n config;\n connectOptions;\n connectionPools = new Map();\n constructor(config) {\n this.config = config;\n if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) {\n throw new RangeError(\"maxConcurrency must be greater than zero.\");\n }\n }\n lease(requestContext, connectionConfiguration) {\n const url = this.getUrlString(requestContext);\n const pool = this.getPool(url);\n if (!this.config.disableConcurrency && !connectionConfiguration.isEventStream) {\n const available = pool.poll();\n if (available) {\n available.retain();\n return available;\n }\n }\n const ref = new ClientHttp2SessionRef(this.connect(url));\n const session = ref.deref();\n if (this.config.maxConcurrency) {\n session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => {\n if (err) {\n throw new Error(\"Fail to set maxConcurrentStreams to \" +\n this.config.maxConcurrency +\n \"when creating new session for \" +\n requestContext.destination.toString());\n }\n });\n }\n const graceful = () => {\n this.removeFromPoolAndClose(url, ref);\n };\n const ensureDestroyed = () => {\n this.removeFromPoolAndCheckedDestroy(url, ref);\n };\n session.on(\"goaway\", graceful);\n session.on(\"error\", ensureDestroyed);\n session.on(\"frameError\", ensureDestroyed);\n session.on(\"close\", ensureDestroyed);\n if (connectionConfiguration.requestTimeout) {\n session.setTimeout(connectionConfiguration.requestTimeout, ensureDestroyed);\n }\n pool.offerLast(ref);\n ref.retain();\n return ref;\n }\n release(_requestContext, ref) {\n ref.free();\n }\n createIsolatedSession(requestContext, connectionConfiguration) {\n const url = this.getUrlString(requestContext);\n const ref = new ClientHttp2SessionRef(this.connect(url));\n const session = ref.deref();\n session.settings({ maxConcurrentStreams: 1 });\n const ensureDestroyed = () => {\n ref.destroy();\n };\n session.on(\"error\", ensureDestroyed);\n session.on(\"frameError\", ensureDestroyed);\n session.on(\"close\", ensureDestroyed);\n if (connectionConfiguration.requestTimeout) {\n session.setTimeout(connectionConfiguration.requestTimeout, ensureDestroyed);\n }\n ref.retain();\n return ref;\n }\n destroy() {\n for (const [url, connectionPool] of this.connectionPools) {\n for (const session of [...connectionPool]) {\n session.destroy();\n }\n this.connectionPools.delete(url);\n }\n }\n setMaxConcurrentStreams(maxConcurrentStreams) {\n if (maxConcurrentStreams && maxConcurrentStreams <= 0) {\n throw new RangeError(\"maxConcurrentStreams must be greater than zero.\");\n }\n this.config.maxConcurrency = maxConcurrentStreams;\n for (const pool of this.connectionPools.values()) {\n pool.setMaxConcurrency(maxConcurrentStreams);\n }\n }\n setDisableConcurrentStreams(disableConcurrentStreams) {\n this.config.disableConcurrency = disableConcurrentStreams;\n }\n setNodeHttp2ConnectOptions(nodeHttp2ConnectOptions) {\n this.connectOptions = nodeHttp2ConnectOptions;\n }\n debug() {\n const pools = {};\n for (const [url, pool] of this.connectionPools) {\n const sessions = [];\n for (const ref of pool) {\n sessions.push({\n id: ref.id,\n active: ref.useCount(),\n maxConcurrent: ref.max,\n totalRequests: ref.total,\n });\n }\n pools[url] = { sessions };\n }\n return pools;\n }\n removeFromPoolAndClose(authority, ref) {\n this.connectionPools.get(authority)?.remove(ref);\n ref.close();\n }\n removeFromPoolAndCheckedDestroy(authority, ref) {\n this.connectionPools.get(authority)?.remove(ref);\n ref.destroy();\n }\n getPool(url) {\n if (!this.connectionPools.has(url)) {\n const pool = new NodeHttp2ConnectionPool();\n if (this.config.maxConcurrency) {\n pool.setMaxConcurrency(this.config.maxConcurrency);\n }\n this.connectionPools.set(url, pool);\n }\n return this.connectionPools.get(url);\n }\n getUrlString(request) {\n return request.destination.toString();\n }\n connect(url) {\n return this.connectOptions === undefined ? http2.connect(url) : http2.connect(url, this.connectOptions);\n }\n}\n\nconst { constants } = http2;\nclass NodeHttp2Handler {\n config;\n configProvider;\n metadata = { handlerProtocol: \"h2\" };\n connectionManager = new NodeHttp2ConnectionManager({});\n static create(instanceOrOptions) {\n if (typeof instanceOrOptions?.handle === \"function\") {\n return instanceOrOptions;\n }\n return new NodeHttp2Handler(instanceOrOptions);\n }\n constructor(options) {\n this.configProvider = new Promise((resolve, reject) => {\n if (typeof options === \"function\") {\n options()\n .then((opts) => {\n resolve(opts || {});\n })\n .catch(reject);\n }\n else {\n resolve(options || {});\n }\n });\n }\n destroy() {\n this.connectionManager.destroy();\n }\n async handle(request, { abortSignal, requestTimeout, isEventStream } = {}) {\n if (!this.config) {\n this.config = await this.configProvider;\n const { disableConcurrentStreams, maxConcurrentStreams, nodeHttp2ConnectOptions } = this.config;\n this.connectionManager.setDisableConcurrentStreams(disableConcurrentStreams ?? false);\n if (maxConcurrentStreams) {\n this.connectionManager.setMaxConcurrentStreams(maxConcurrentStreams);\n }\n if (nodeHttp2ConnectOptions) {\n this.connectionManager.setNodeHttp2ConnectOptions(nodeHttp2ConnectOptions);\n }\n }\n const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config;\n const useIsolatedSession = disableConcurrentStreams || isEventStream;\n const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout;\n return new Promise((_resolve, _reject) => {\n let fulfilled = false;\n let writeRequestBodyPromise = undefined;\n const resolve = async (arg) => {\n await writeRequestBodyPromise;\n _resolve(arg);\n };\n const reject = async (arg) => {\n await writeRequestBodyPromise;\n _reject(arg);\n };\n if (abortSignal?.aborted) {\n fulfilled = true;\n const abortError = buildAbortError(abortSignal);\n reject(abortError);\n return;\n }\n const { hostname, method, port, protocol, query } = request;\n let auth = \"\";\n if (request.username != null || request.password != null) {\n const username = request.username ?? \"\";\n const password = request.password ?? \"\";\n auth = `${username}:${password}@`;\n }\n const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : \"\"}`;\n const requestContext = { destination: new URL(authority) };\n const connectConfig = {\n requestTimeout: this.config?.sessionTimeout,\n isEventStream,\n };\n const ref = useIsolatedSession\n ? this.connectionManager.createIsolatedSession(requestContext, connectConfig)\n : this.connectionManager.lease(requestContext, connectConfig);\n const session = ref.deref();\n const rejectWithDestroy = (err) => {\n if (useIsolatedSession) {\n ref.destroy();\n }\n fulfilled = true;\n reject(err);\n };\n const queryString = query ? buildQueryString(query) : \"\";\n let path = request.path;\n if (queryString) {\n path += `?${queryString}`;\n }\n if (request.fragment) {\n path += `#${request.fragment}`;\n }\n const clientHttp2Stream = session.request({\n ...request.headers,\n [constants.HTTP2_HEADER_PATH]: path,\n [constants.HTTP2_HEADER_METHOD]: method,\n });\n if (effectiveRequestTimeout) {\n clientHttp2Stream.setTimeout(effectiveRequestTimeout, () => {\n clientHttp2Stream.close();\n const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`);\n timeoutError.name = \"TimeoutError\";\n rejectWithDestroy(timeoutError);\n });\n }\n if (abortSignal) {\n const onAbort = () => {\n clientHttp2Stream.close();\n const abortError = buildAbortError(abortSignal);\n rejectWithDestroy(abortError);\n };\n if (typeof abortSignal.addEventListener === \"function\") {\n const signal = abortSignal;\n signal.addEventListener(\"abort\", onAbort, { once: true });\n clientHttp2Stream.once(\"close\", () => signal.removeEventListener(\"abort\", onAbort));\n }\n else {\n abortSignal.onabort = onAbort;\n }\n }\n clientHttp2Stream.on(\"frameError\", (type, code, id) => {\n rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`));\n });\n clientHttp2Stream.on(\"error\", rejectWithDestroy);\n clientHttp2Stream.on(\"aborted\", () => {\n rejectWithDestroy(new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${clientHttp2Stream.rstCode}.`));\n });\n clientHttp2Stream.on(\"response\", (headers) => {\n const httpResponse = new HttpResponse({\n statusCode: headers[\":status\"] ?? -1,\n headers: getTransformedHeaders(headers),\n body: clientHttp2Stream,\n });\n fulfilled = true;\n resolve({ response: httpResponse });\n if (useIsolatedSession) {\n session.close();\n }\n });\n clientHttp2Stream.on(\"close\", () => {\n if (useIsolatedSession) {\n ref.destroy();\n }\n else {\n this.connectionManager.release(requestContext, ref);\n }\n if (!fulfilled) {\n rejectWithDestroy(new Error(\"Unexpected error: http2 request did not get a response\"));\n }\n });\n writeRequestBodyPromise = writeRequestBody(clientHttp2Stream, request, effectiveRequestTimeout);\n });\n }\n updateHttpClientConfig(key, value) {\n this.config = undefined;\n this.configProvider = this.configProvider.then((config) => {\n return {\n ...config,\n [key]: value,\n };\n });\n }\n httpHandlerConfigs() {\n return this.config ?? {};\n }\n}\n\nexports.DEFAULT_REQUEST_TIMEOUT = DEFAULT_REQUEST_TIMEOUT;\nexports.NodeHttp2Handler = NodeHttp2Handler;\nexports.NodeHttpHandler = NodeHttpHandler;\n" | ||
| ], | ||
| "mappings": ";4LAAA,IAAQ,mBAAkB,qBACpB,cACE,yBACF,cACE,yBACA,mBAAkB,GAE1B,SAAS,CAAe,CAAC,EAAa,CAClC,IAAM,EAAS,GAAe,OAAO,IAAgB,UAAY,WAAY,EACvE,EAAY,OACZ,OACN,GAAI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AAK,QAAU,CAAC,EAE/B,CAEQ,2BAA0B,GAC1B,oBAAmB,EACnB,mBAAkB", | ||
| "debugId": "17FF625C2CCE1E8C64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/debug/paths.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\n\nexport default Runtime.handler(\n Commands.commands.debug.commands.paths,\n Effect.fn(\"cli.debug.paths\")(function* () {\n const global = yield* Global.Service\n process.stdout.write(\n Object.entries(global)\n .map(([key, value]) => `${key.padEnd(10)} ${value}${EOL}`)\n .join(\"\"),\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+pBAAA,cAAS,WAMT,IAAe,IAAQ,QACrB,EAAS,SAAS,MAAM,SAAS,MACjC,EAAO,GAAG,iBAAiB,EAAE,SAAU,EAAG,CACxC,IAAM,EAAS,MAAO,EAAO,QAC7B,QAAQ,OAAO,MACb,OAAO,QAAQ,CAAM,EAClB,IAAI,EAAE,EAAK,KAAW,GAAG,EAAI,OAAO,EAAE,KAAK,IAAQ,GAAK,EACxD,KAAK,EAAE,CACZ,EACD,CACH", | ||
| "debugId": "763929B0CC83937B64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/debug/agents.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.debug.commands.agents,\n Effect.fn(\"cli.debug.agents\")(function* () {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.agent.list({ location: { directory: process.cwd() } }))\n process.stdout.write(\n JSON.stringify(\n response.data.toSorted((a, b) => a.id.localeCompare(b.id)),\n null,\n 2,\n ) + EOL,\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";08BAAA,cAAS,WAQT,IAAe,IAAQ,QACrB,EAAS,SAAS,MAAM,SAAS,OACjC,EAAO,GAAG,kBAAkB,EAAE,SAAU,EAAG,CACzC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAW,MAAO,EAAO,QAAQ,IAAM,EAAO,MAAM,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,EAC1G,QAAQ,OAAO,MACb,KAAK,UACH,EAAS,KAAK,SAAS,CAAC,EAAG,IAAM,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC,EACzD,KACA,CACF,EAAI,CACN,EACD,CACH", | ||
| "debugId": "A77BBA3A903C1F1164756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/remove.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { readFile, rename, writeFile } from \"node:fs/promises\"\nimport { Effect } from \"effect\"\nimport { applyEdits, modify, parse, type ParseError } from \"jsonc-parser\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Config } from \"../../../config\"\nimport { resolveConfigPath } from \"../mcp/add\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.remove,\n Effect.fn(\"cli.plugin.remove\")(function* (input) {\n const global = yield* Global.Service\n const configPath = yield* Effect.promise(() => resolveConfigPath(global.config))\n const server = yield* Effect.promise(() => removePluginConfig(configPath, input.package))\n const config = yield* Config.Service\n const info = yield* config.get()\n const tui = configured(info.plugins, input.package)\n if (tui)\n yield* config.update((draft) => {\n draft.plugins = draft.plugins?.filter((entry) => !matches(entry, input.package))\n })\n\n const removed = [server ? configPath : undefined, tui ? config.path : undefined].filter(\n (file) => file !== undefined,\n )\n process.stdout.write(\n removed.length\n ? `Plugin \"${input.package}\" removed from ${removed.join(\", \")}${EOL}`\n : `Plugin \"${input.package}\" is not configured${EOL}`,\n )\n }),\n)\n\nexport async function removePluginConfig(configPath: string, spec: string) {\n const text = await readFile(configPath, \"utf8\").catch((error) => {\n if (typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\") return undefined\n throw error\n })\n if (text === undefined) return false\n const errors: ParseError[] = []\n const config: unknown = parse(text, errors, { allowTrailingComma: true })\n if (errors.length || typeof config !== \"object\" || config === null || Array.isArray(config))\n throw new Error(`Invalid global configuration: ${configPath}`)\n const plugins = \"plugins\" in config ? config.plugins : undefined\n if (plugins !== undefined && !Array.isArray(plugins)) throw new Error(`Invalid plugins configuration: ${configPath}`)\n if (!configured(plugins, spec)) return false\n\n const updated = applyEdits(\n text,\n modify(\n text,\n [\"plugins\"],\n plugins?.filter((entry) => !matches(entry, spec)),\n {\n formattingOptions: { tabSize: 2, insertSpaces: true },\n },\n ),\n )\n const temporary = configPath + \".tmp\"\n await writeFile(temporary, updated.endsWith(\"\\n\") ? updated : updated + \"\\n\", { mode: 0o600 })\n await rename(temporary, configPath)\n return true\n}\n\nfunction configured(plugins: readonly unknown[] | undefined, spec: string) {\n return plugins?.some((entry) => matches(entry, spec)) ?? false\n}\n\nfunction matches(entry: unknown, spec: string) {\n return entry === spec || (typeof entry === \"object\" && entry !== null && \"package\" in entry && entry.package === spec)\n}\n" | ||
| ], | ||
| "mappings": ";wvBAAA,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AI,IAAY,QAAa,CAAC,MAAM,QAAQ,CAAO,EAAG,MAAU,MAAM,kCAAkC,GAAY,EACpH,GAAI,CAAC,EAAW,EAAS,CAAI,EAAG,MAAO,GAEvC,IAAM,EAAU,EACd,EACA,EACE,EACA,CAAC,SAAS,EACV,GAAS,OAAO,CAAC,IAAU,CAAC,EAAQ,EAAO,CAAI,CAAC,EAChD,CACE,kBAAmB,CAAE,QAAS,EAAG,aAAc,EAAK,CACtD,CACF,CACF,EACM,EAAY,EAAa,OAG/B,OAFA,MAAM,EAAU,EAAW,EAAQ,SAAS;AAAA,CAAI,EAAI,EAAU,EAAU;AAAA,EAAM,CAAE,KAAM,GAAM,CAAC,EAC7F,MAAM,EAAO,EAAW,CAAU,EAC3B,GAGT,SAAS,CAAU,CAAC,EAAyC,EAAc,CACzE,OAAO,GAAS,KAAK,CAAC,IAAU,EAAQ,EAAO,CAAI,CAAC,GAAK,GAG3D,SAAS,CAAO,CAAC,EAAgB,EAAc,CAC7C,OAAO,IAAU,GAAS,OAAO,IAAU,UAAY,IAAU,MAAQ,YAAa,GAAS,EAAM,UAAY", | ||
| "debugId": "2F749EB998F6558164756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/mcp.ts"], | ||
| "sourcesContent": [ | ||
| "export * as Mcp from \"./mcp.js\"\n\nimport { Schema } from \"effect\"\nimport { optional, PositiveInt } from \"./schema.js\"\nimport { IntegrationID } from \"./integration-id.js\"\n\nexport class TimeoutConfig extends Schema.Class<TimeoutConfig>(\"Mcp.TimeoutConfig\")({\n startup: PositiveInt.pipe(optional).annotate({\n description: \"Maximum time in milliseconds to establish and initialize the MCP server.\",\n }),\n catalog: PositiveInt.pipe(optional).annotate({\n description: \"Maximum time in milliseconds to wait for MCP discovery requests such as tools/list and prompts/list.\",\n }),\n execution: PositiveInt.pipe(optional).annotate({\n description: \"Maximum time in milliseconds to wait for MCP tool and prompt execution.\",\n }),\n}) {}\n\nexport class LocalConfig extends Schema.Class<LocalConfig>(\"Mcp.LocalConfig\")({\n type: Schema.Literal(\"local\"),\n command: Schema.String.pipe(Schema.Array),\n cwd: Schema.String.pipe(optional).annotate({\n description: \"Working directory for the MCP server process. Relative paths resolve from the workspace directory.\",\n }),\n environment: Schema.Record(Schema.String, Schema.String).pipe(optional),\n disabled: Schema.Boolean.pipe(optional),\n codemode: Schema.Boolean.pipe(optional).annotate({\n description: \"Expose this server's tools through Code Mode. Defaults to true.\",\n }),\n timeout: TimeoutConfig.pipe(optional),\n}) {}\n\nexport class OAuthConfig extends Schema.Class<OAuthConfig>(\"Mcp.OAuthConfig\")({\n client_id: Schema.String.pipe(optional),\n client_secret: Schema.String.pipe(optional),\n scope: Schema.String.pipe(optional),\n callback_port: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })).pipe(optional),\n redirect_uri: Schema.String.pipe(optional),\n}) {}\n\nexport class RemoteConfig extends Schema.Class<RemoteConfig>(\"Mcp.RemoteConfig\")({\n type: Schema.Literal(\"remote\"),\n url: Schema.String,\n headers: Schema.Record(Schema.String, Schema.String).pipe(optional),\n oauth: Schema.Union([OAuthConfig, Schema.Literal(false)]).pipe(optional),\n disabled: Schema.Boolean.pipe(optional),\n codemode: Schema.Boolean.pipe(optional).annotate({\n description: \"Expose this server's tools through Code Mode. Defaults to true.\",\n }),\n timeout: TimeoutConfig.pipe(optional),\n}) {}\n\nexport const ServerConfig = Schema.Union([LocalConfig, RemoteConfig]).pipe(Schema.toTaggedUnion(\"type\"))\nexport type ServerConfig = typeof ServerConfig.Type\n\nconst Connected = Schema.Struct({ status: Schema.Literal(\"connected\") }).annotate({\n identifier: \"Mcp.Status.Connected\",\n})\nconst Pending = Schema.Struct({ status: Schema.Literal(\"pending\") }).annotate({\n identifier: \"Mcp.Status.Pending\",\n})\nconst Disabled = Schema.Struct({ status: Schema.Literal(\"disabled\") }).annotate({\n identifier: \"Mcp.Status.Disabled\",\n})\nconst Failed = Schema.Struct({ status: Schema.Literal(\"failed\"), error: Schema.String }).annotate({\n identifier: \"Mcp.Status.Failed\",\n})\nconst NeedsAuth = Schema.Struct({ status: Schema.Literal(\"needs_auth\") }).annotate({\n identifier: \"Mcp.Status.NeedsAuth\",\n})\n\nexport type Status = typeof Status.Type\nexport const Status = Schema.Union([Connected, Pending, Disabled, Failed, NeedsAuth]).pipe(\n Schema.toTaggedUnion(\"status\"),\n)\n\nexport interface Server extends Schema.Schema.Type<typeof Server> {}\nexport const Server = Schema.Struct({\n name: Schema.String,\n status: Status,\n // Set for remote servers registered as OAuth integrations; lets clients act on the right integration\n // without matching by name, which could collide with provider or plugin integrations.\n integrationID: optional(IntegrationID),\n}).annotate({ identifier: \"Mcp.Server\" })\n\nexport interface Resource extends Schema.Schema.Type<typeof Resource> {}\nexport const Resource = Schema.Struct({\n server: Schema.String,\n name: Schema.String,\n uri: Schema.String,\n description: optional(Schema.String),\n mimeType: optional(Schema.String),\n}).annotate({ identifier: \"Mcp.Resource\" })\n\nexport interface ResourceTemplate extends Schema.Schema.Type<typeof ResourceTemplate> {}\nexport const ResourceTemplate = Schema.Struct({\n server: Schema.String,\n name: Schema.String,\n uriTemplate: Schema.String,\n description: optional(Schema.String),\n mimeType: optional(Schema.String),\n}).annotate({ identifier: \"Mcp.ResourceTemplate\" })\n\nexport interface ResourceCatalog extends Schema.Schema.Type<typeof ResourceCatalog> {}\nexport const ResourceCatalog = Schema.Struct({\n resources: Schema.Array(Resource),\n templates: Schema.Array(ResourceTemplate),\n}).annotate({ identifier: \"Mcp.ResourceCatalog\" })\n\nexport const ResourceContentPart = Schema.Union([\n Schema.Struct({\n type: Schema.Literal(\"text\"),\n uri: Schema.String,\n text: Schema.String,\n mimeType: optional(Schema.String),\n }),\n Schema.Struct({\n type: Schema.Literal(\"blob\"),\n uri: Schema.String,\n blob: Schema.String,\n mimeType: optional(Schema.String),\n }),\n]).pipe(Schema.toTaggedUnion(\"type\"), Schema.annotate({ identifier: \"Mcp.ResourceContentPart\" }))\nexport type ResourceContentPart = typeof ResourceContentPart.Type\n\nexport interface ResourceContent extends Schema.Schema.Type<typeof ResourceContent> {}\nexport const ResourceContent = Schema.Struct({\n server: Schema.String,\n uri: Schema.String,\n contents: Schema.Array(ResourceContentPart),\n}).annotate({ identifier: \"Mcp.ResourceContent\" })\n" | ||
| ], | ||
| "mappings": ";sdAMO,MAAM,UAAsB,EAAO,MAAqB,mBAAmB,EAAE,CAClF,QAAS,EAAY,KAAK,CAAQ,EAAE,SAAS,CAC3C,YAAa,0EACf,CAAC,EACD,QAAS,EAAY,KAAK,CAAQ,EAAE,SAAS,CAC3C,YAAa,sGACf,CAAC,EACD,UAAW,EAAY,KAAK,CAAQ,EAAE,SAAS,CAC7C,YAAa,yEACf,CAAC,CACH,CAAC,CAAE,CAAC,CAEG,MAAM,UAAoB,EAAO,MAAmB,iBAAiB,EAAE,CAC5E,KAAM,EAAO,QAAQ,OAAO,EAC5B,QAAS,EAAO,OAAO,KAAK,EAAO,KAAK,EACxC,IAAK,EAAO,OAAO,KAAK,CAAQ,EAAE,SAAS,CACzC,YAAa,oGACf,CAAC,EACD,YAAa,EAAO,OAAO,EAAO,OAAQ,EAAO,MAAM,EAAE,KAAK,CAAQ,EACtE,SAAU,EAAO,QAAQ,KAAK,CAAQ,EACtC,SAAU,EAAO,QAAQ,KAAK,CAAQ,EAAE,SAAS,CAC/C,YAAa,iEACf,CAAC,EACD,QAAS,EAAc,KAAK,CAAQ,CACtC,CAAC,CAAE,CAAC,CAEG,MAAM,UAAoB,EAAO,MAAmB,iBAAiB,EAAE,CAC5E,UAAW,EAAO,OAAO,KAAK,CAAQ,EACtC,cAAe,EAAO,OAAO,KAAK,CAAQ,EAC1C,MAAO,EAAO,OAAO,KAAK,CAAQ,EAClC,cAAe,EAAO,IAAI,MAAM,EAAO,UAAU,CAAE,QAAS,EAAG,QAAS,KAAM,CAAC,CAAC,EAAE,KAAK,CAAQ,EAC/F,aAAc,EAAO,OAAO,KAAK,CAAQ,CAC3C,CAAC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R,cAAe,EAAS,CAAa,CACvC,CAAC,EAAE,SAAS,CAAE,WAAY,YAAa,CAAC,EAG3B,EAAW,EAAO,OAAO,CACpC,OAAQ,EAAO,OACf,KAAM,EAAO,OACb,IAAK,EAAO,OACZ,YAAa,EAAS,EAAO,MAAM,EACnC,SAAU,EAAS,EAAO,MAAM,CAClC,CAAC,EAAE,SAAS,CAAE,WAAY,cAAe,CAAC,EAG7B,EAAmB,EAAO,OAAO,CAC5C,OAAQ,EAAO,OACf,KAAM,EAAO,OACb,YAAa,EAAO,OACpB,YAAa,EAAS,EAAO,MAAM,EACnC,SAAU,EAAS,EAAO,MAAM,CAClC,CAAC,EAAE,SAAS,CAAE,WAAY,sBAAuB,CAAC,EAGrC,EAAkB,EAAO,OAAO,CAC3C,UAAW,EAAO,MAAM,CAAQ,EAChC,UAAW,EAAO,MAAM,CAAgB,CAC1C,CAAC,EAAE,SAAS,CAAE,WAAY,qBAAsB,CAAC,EAEpC,EAAsB,EAAO,MAAM,CAC9C,EAAO,OAAO,CACZ,KAAM,EAAO,QAAQ,MAAM,EAC3B,IAAK,EAAO,OACZ,KAAM,EAAO,OACb,SAAU,EAAS,EAAO,MAAM,CAClC,CAAC,EACD,EAAO,OAAO,CACZ,KAAM,EAAO,QAAQ,MAAM,EAC3B,IAAK,EAAO,OACZ,KAAM,EAAO,OACb,SAAU,EAAS,EAAO,MAAM,CAClC,CAAC,CACH,CAAC,EAAE,KAAK,EAAO,cAAc,MAAM,EAAG,EAAO,SAAS,CAAE,WAAY,yBAA0B,CAAC,CAAC,EAInF,EAAkB,EAAO,OAAO,CAC3C,OAAQ,EAAO,OACf,IAAK,EAAO,OACZ,SAAU,EAAO,MAAM,CAAmB,CAC5C,CAAC,EAAE,SAAS,CAAE,WAAY,qBAAsB,CAAC", | ||
| "debugId": "16F20412B976A67964756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/mini.ts", "src/mini-host.ts"], | ||
| "sourcesContent": [ | ||
| "import { Service, type Endpoint } from \"@opencode-ai/client/effect/service\"\nimport { ClientError, OpenCode, type OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport type { MiniFrontendInput } from \"@opencode-ai/tui/mini\"\nimport { setTimeout } from \"node:timers/promises\"\nimport { readStdin } from \"./util/io\"\nimport { createMiniHost, INTERACTIVE_INPUT_ERROR, usingInteractiveStdin } from \"./mini-host\"\nimport { parseSessionTargetModel, resolveSessionTarget, type SessionTargetPreparation } from \"./session-target\"\nimport { Env } from \"./env\"\n\nexport type MiniCommandInput = {\n server: {\n endpoint: Endpoint\n reconnect?: (signal: AbortSignal) => Promise<Endpoint>\n }\n continue?: boolean\n session?: string\n fork?: boolean\n model?: string\n agent?: string\n prompt?: string\n replay?: boolean\n replayLimit?: number\n demo?: boolean\n tuiConfig?: MiniFrontendInput[\"tuiConfig\"]\n config?: MiniFrontendInput[\"config\"]\n paths: { home: string; state: string; log: string }\n}\n\ntype Model = MiniFrontendInput[\"model\"]\n\nclass MiniInputError extends Error {}\n\nexport async function runMini(input: MiniCommandInput) {\n try {\n validate(input)\n const result = await usingInteractiveStdin(async (terminal) => {\n const initialInput = mergeInput(process.stdin.isTTY ? undefined : await readStdin(), input.prompt)\n const frontendTask = import(\"@opencode-ai/tui/mini\")\n const directory = localDirectory()\n const connection = createMiniConnection(input.server)\n const sdk = connection.sdk\n const environment = input.server.reconnect ? Env.session() : undefined\n const requested = parseModel(input.model)\n const model = requested ? { providerID: requested.providerID, modelID: requested.id } : undefined\n const prepare = prepareTarget(input.agent)\n const resolveTarget = async (initial: OpenCodeClient, signal: AbortSignal) => {\n const resolved = await resolveMiniTarget({\n sdk: initial,\n reconnect: connection.reconnect,\n signal,\n resolve: (client) =>\n resolveSessionTarget({\n client,\n location: { directory },\n continue: input.continue,\n session: input.session,\n fork: input.fork,\n model: requested,\n agent: input.agent,\n environment,\n prepare,\n signal,\n }).catch((error) => {\n if (error instanceof Error && error.message === \"Session not found\")\n throw new MiniInputError(error.message)\n throw error\n }),\n })\n const target = resolved.value\n return {\n sdk: resolved.sdk,\n sessionID: target.session.id,\n sessionTitle: target.session.title,\n location: target.location,\n model: target.model ? { providerID: target.model.providerID, modelID: target.model.id } : undefined,\n variant: target.model?.variant,\n agent: target.agent,\n resume: target.resume,\n }\n }\n const create = (\n client: OpenCodeClient,\n next: {\n location: { directory: string; workspaceID?: string }\n agent: string | undefined\n model: Model\n variant: string | undefined\n },\n signal?: AbortSignal,\n ) =>\n resolveSessionTarget({\n client,\n location: { directory: next.location.directory, workspace: next.location.workspaceID },\n agent: next.agent,\n environment,\n model: next.model\n ? { providerID: next.model.providerID, id: next.model.modelID, variant: next.variant }\n : undefined,\n prepare,\n signal,\n }).then((target) => ({\n sessionID: target.session.id,\n sessionTitle: target.session.title,\n location: target.location,\n model: target.model ? { providerID: target.model.providerID, modelID: target.model.id } : undefined,\n variant: target.model?.variant,\n agent: target.agent,\n resume: false,\n }))\n const frontend = await frontendTask\n return frontend.runMiniFrontend({\n host: createMiniHost({ terminal, directory, paths: input.paths }),\n sdk,\n directory,\n target: resolveTarget,\n reconnect: connection.reconnect,\n createSession: create,\n agent: input.agent,\n model,\n variant: requested?.variant,\n files: [],\n initialInput,\n replay: input.replay ?? true,\n replayLimit: input.replayLimit,\n demo: input.demo,\n tuiConfig: input.tuiConfig,\n config: input.config,\n })\n })\n if (result.exitCode !== 0) process.exit(result.exitCode)\n } catch (error) {\n if (error instanceof MiniInputError || (error instanceof Error && error.message === INTERACTIVE_INPUT_ERROR))\n fail(error.message)\n throw error\n }\n}\n\n/** @internal Exported for CLI boundary tests. */\nexport function createMiniConnection(input: MiniCommandInput[\"server\"]) {\n const make = (endpoint: Endpoint) =>\n OpenCode.make({\n baseUrl: endpoint.url,\n headers: Service.headers(endpoint),\n })\n const reconnect = input.reconnect\n return {\n sdk: make(input.endpoint),\n reconnect: reconnect\n ? async (signal: AbortSignal) => {\n const endpoint = await reconnect(signal)\n return make(endpoint)\n }\n : undefined,\n }\n}\n\n/** @internal Exported for reconnect lifecycle tests. */\nexport async function resolveMiniTarget<A>(input: {\n sdk: OpenCodeClient\n reconnect?: (signal: AbortSignal) => Promise<OpenCodeClient>\n signal: AbortSignal\n resolve: (sdk: OpenCodeClient) => Promise<A>\n}) {\n let sdk = input.sdk\n while (true) {\n try {\n return { sdk, value: await input.resolve(sdk) }\n } catch (error) {\n if (!input.reconnect || !(error instanceof ClientError) || error.reason !== \"Transport\") throw error\n while (true) {\n try {\n sdk = await input.reconnect(input.signal)\n break\n } catch (resolveError) {\n if (input.signal.aborted) throw resolveError\n await setTimeout(250, undefined, { signal: input.signal })\n }\n }\n }\n }\n}\n\nexport function validateMiniTerminal() {\n if (!process.stdout.isTTY) fail(\"opencode mini requires a TTY stdout\")\n}\n\n/** @internal Exported for testing. */\nexport function mergeInput(piped: string | undefined, prompt: string | undefined) {\n if (!prompt) return piped || undefined\n if (!piped) return prompt\n return piped + \"\\n\" + prompt\n}\n\nfunction validate(input: MiniCommandInput) {\n validateMiniTerminal()\n if (input.replayLimit !== undefined && (!Number.isInteger(input.replayLimit) || input.replayLimit <= 0)) {\n fail(\"--replay-limit must be a positive integer\")\n }\n if (input.fork && !input.continue && !input.session) fail(\"--fork requires --continue or --session\")\n}\n\nfunction localDirectory(): string {\n const root = process.env.PWD ?? process.cwd()\n try {\n process.chdir(root)\n return process.cwd()\n } catch {\n throw new MiniInputError(`Failed to change directory to ${root}`)\n }\n}\n\nfunction parseModel(value?: string) {\n try {\n return parseSessionTargetModel(value)\n } catch {\n throw new MiniInputError(\"--model must use the format provider/model[#variant]\")\n }\n}\n\nfunction prepareTarget(requestedAgent?: string): SessionTargetPreparation {\n return async (input) => ({ model: input.model, agent: requestedAgent ?? input.agent })\n}\n\nfunction fail(message: string): never {\n process.stderr.write(`\\x1b[91m\\x1b[1mError: \\x1b[0m${message}\\n`)\n process.exit(1)\n}\n", | ||
| "import type { MiniFrontendInput } from \"@opencode-ai/tui/mini\"\nimport { createModelPreferenceRepository } from \"@opencode-ai/tui/model-preference\"\nimport fs from \"node:fs\"\nimport { readFile } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { ReadStream } from \"node:tty\"\nimport { OPENCODE_VERSION } from \"./version\"\n\nexport const INTERACTIVE_INPUT_ERROR = \"opencode mini requires a controlling terminal for input\"\n\nexport type InteractiveStdin = {\n stdin: NodeJS.ReadStream\n cleanup(): void\n}\n\ntype MiniHost = MiniFrontendInput[\"host\"]\n\nfunction preferences(statePath: string): MiniHost[\"preferences\"] {\n const repository = createModelPreferenceRepository(path.join(statePath, \"model.json\"))\n return {\n async resolveVariant(model) {\n if (!model) return\n return repository.resolveVariant(model)\n },\n async saveVariant(model, variant) {\n if (!model) return\n await repository.saveVariant(model, variant).catch(() => undefined)\n },\n }\n}\n\nfunction signal(name: \"SIGINT\" | \"SIGUSR2\"): MiniHost[\"signals\"][\"sigint\"] {\n return {\n subscribe(listener) {\n let subscribed = true\n process.on(name, listener)\n return () => {\n if (!subscribed) return\n subscribed = false\n process.off(name, listener)\n }\n },\n }\n}\n\nfunction createTrace(\n logPath: string,\n diagnostics: { pid: number; cwd: string; argv: string[] },\n): MiniHost[\"diagnostics\"][\"trace\"] {\n if (!process.env.OPENCODE_DIRECT_TRACE) return\n const stamp = new Date()\n .toISOString()\n .replace(/[-:]/g, \"\")\n .replace(/\\.\\d+Z$/, \"Z\")\n const target = path.join(logPath, \"direct\", `${stamp}-${diagnostics.pid}.jsonl`)\n const text = (data: unknown) =>\n JSON.stringify(data, (_key, value) => (typeof value === \"bigint\" ? String(value) : value), 0)\n fs.mkdirSync(path.dirname(target), { recursive: true })\n fs.writeFileSync(\n path.join(logPath, \"direct\", \"latest.json\"),\n text({\n time: new Date().toISOString(),\n ...diagnostics,\n path: target,\n }) + \"\\n\",\n )\n const trace = {\n write(type: string, data?: unknown) {\n fs.appendFileSync(\n target,\n text({\n time: new Date().toISOString(),\n pid: diagnostics.pid,\n type,\n data,\n }) + \"\\n\",\n )\n },\n }\n trace.write(\"trace.start\", {\n argv: diagnostics.argv,\n cwd: diagnostics.cwd,\n path: target,\n })\n return trace\n}\n\nfunction openTerminalStdin(target: string): NodeJS.ReadStream {\n return new ReadStream(fs.openSync(target, \"r\"))\n}\n\nexport function resolveInteractiveStdin(\n stdin: NodeJS.ReadStream = process.stdin,\n open: (target: string) => NodeJS.ReadStream = openTerminalStdin,\n platform: NodeJS.Platform = process.platform,\n): InteractiveStdin {\n if (stdin.isTTY) return { stdin, cleanup() {} }\n const target = platform === \"win32\" ? \"CONIN$\" : \"/dev/tty\"\n try {\n const source = open(target)\n let cleaned = false\n return {\n stdin: source,\n cleanup() {\n if (cleaned) return\n cleaned = true\n source.destroy()\n },\n }\n } catch (error) {\n throw new Error(INTERACTIVE_INPUT_ERROR, { cause: error })\n }\n}\n\n/** @internal Exported for owner-local resource cleanup tests. */\nexport async function usingInteractiveStdin<T>(\n run: (terminal: InteractiveStdin) => Promise<T>,\n resolve: () => InteractiveStdin = resolveInteractiveStdin,\n) {\n const terminal = resolve()\n try {\n return await run(terminal)\n } finally {\n terminal.cleanup()\n }\n}\n\n/** @internal Exported for owner-local host capability tests. */\nexport function createMiniHost(input: {\n terminal: InteractiveStdin\n directory: string\n paths: { home: string; state: string; log: string }\n}): MiniHost {\n const paths = input.paths\n const diagnostics = {\n pid: process.pid,\n cwd: input.directory,\n argv: process.argv.slice(2),\n }\n return {\n version: OPENCODE_VERSION,\n terminal: { stdin: input.terminal.stdin },\n platform: process.platform,\n stdout: {\n write(value) {\n process.stdout.write(value)\n },\n },\n files: {\n readText: (url) => readFile(new URL(url), \"utf8\"),\n },\n editor: {\n async open(options) {\n const { openEditor } = await import(\"@opencode-ai/tui/editor\")\n return openEditor(options)\n },\n },\n paths: { home: paths.home },\n signals: {\n sigint: signal(\"SIGINT\"),\n sigusr2: signal(\"SIGUSR2\"),\n },\n startup: {\n showTiming: [\"1\", \"true\"].includes(process.env.OPENCODE_SHOW_TTFD?.toLowerCase() ?? \"\"),\n now: () => performance.now(),\n },\n diagnostics: {\n trace: createTrace(paths.log, diagnostics),\n },\n preferences: preferences(paths.state),\n }\n}\n" | ||
| ], | ||
| "mappings": ";izBAGA,qBAAS,wBCDT,kBACA,mBAAS,oBACT,oBACA,qBAAS,YAGF,IAAM,EAA0B,0DASvC,SAAS,CAAW,CAAC,EAA4C,CAC/D,IAAM,EAAa,EAAgC,EAAK,KAAK,EAAW,YAAY,CAAC,EACrF,MAAO,MACC,eAAc,CAAC,EAAO,CAC1B,GAAI,CAAC,EAAO,OACZ,OAAO,EAAW,eAAe,CAAK,QAElC,YAAW,CAAC,EAAO,EAAS,CAChC,GAAI,CAAC,EAAO,OACZ,MAAM,EAAW,YAAY,EAAO,CAAO,EAAE,MAAM,IAAG,CAAG,OAAS,EAEtE,EAGF,SAAS,CAAM,CAAC,EAA2D,CACzE,MAAO,CACL,SAAS,CAAC,EAAU,CAClB,IAAI,EAAa,GAEjB,OADA,QAAQ,GAAG,EAAM,CAAQ,EAClB,IAAM,CACX,GAAI,CAAC,EAAY,OACjB,EAAa,GACb,QAAQ,IAAI,EAAM,CAAQ,GAGhC,EAGF,SAAS,CAAW,CAClB,EACA,EACkC,CAClC,GAAI,CAAC,QAAQ,IAAI,sBAAuB,OACxC,IAAM,EAAQ,IAAI,KAAK,EACpB,YAAY,EACZ,QAAQ,QAAS,EAAE,EACnB,QAAQ,UAAW,GAAG,EACnB,EAAS,EAAK,KAAK,EAAS,SAAU,GAAG,KAAS,EAAY,WAAW,EACzE,EAAO,CAAC,IACZ,KAAK,UAAU,EAAM,CAAC,EAAM,IAAW,OAAO,IAAU,SAAW,OAAO,CAAK,EAAI,EAAQ,CAAC,EAC9F,EAAG,UAAU,EAAK,QAAQ,CAAM,EAAG,CAAE,UAAW,EAAK,CAAC,EACtD,EAAG,cACD,EAAK,KAAK,EAAS,SAAU,aAAa,EAC1C,EAAK,CACH,KAAM,IAAI,KAAK,EAAE,YAAY,KAC1B,EAC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AAQ,CAAC,EAAM,UAAY,CAAC,EAAM,QAAS,EAAK,yCAAyC,EAGrG,SAAS,CAAc,EAAW,CAChC,IAAM,EAAO,QAAQ,IAAI,KAAO,QAAQ,IAAI,EAC5C,GAAI,CAEF,OADA,QAAQ,MAAM,CAAI,EACX,QAAQ,IAAI,EACnB,KAAM,CACN,MAAM,IAAI,EAAe,iCAAiC,GAAM,GAIpE,SAAS,CAAU,CAAC,EAAgB,CAClC,GAAI,CACF,OAAO,EAAwB,CAAK,EACpC,KAAM,CACN,MAAM,IAAI,EAAe,sDAAsD,GAInF,SAAS,CAAa,CAAC,EAAmD,CACxE,MAAO,OAAO,KAAW,CAAE,MAAO,EAAM,MAAO,MAAO,GAAkB,EAAM,KAAM,GAGtF,SAAS,CAAI,CAAC,EAAwB,CACpC,QAAQ,OAAO,MAAM,gCAAgC;AAAA,CAAW,EAChE,QAAQ,KAAK,CAAC", | ||
| "debugId": "2F202D7BA0A9B00864756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/auth/logout.ts"], | ||
| "sourcesContent": [ | ||
| "import { autocomplete, intro, outro, spinner } from \"@clack/prompts\"\nimport { Effect, Option } from \"effect\"\nimport type { IntegrationInfo } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { handlePromptErrors, prompt, requireInteractive } from \"../../../ui/prompt\"\nimport { createClient, loadIntegrations, location, request, resolveIntegration } from \"./shared\"\n\nexport default Runtime.handler(\n Commands.commands.auth.commands.logout,\n Effect.fn(\"cli.auth.logout\")((input) =>\n logout({\n target: Option.getOrUndefined(input.target),\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n }).pipe(handlePromptErrors),\n ),\n)\n\nconst logout = Effect.fn(\"cli.auth.logout.run\")(function* (input: {\n target?: string\n server?: string\n standalone: boolean\n}) {\n if (!input.target)\n yield* requireInteractive(\"Pass an integration ID or name when running without an interactive terminal\")\n intro(\"Remove credential\")\n const client = yield* createClient({ server: input.server, standalone: input.standalone })\n const integrations = yield* loadIntegrations(client)\n const integration = yield* chooseIntegration(integrations, input.target)\n const credentials = integration.connections.filter((connection) => connection.type === \"credential\")\n if (credentials.length === 0) {\n const environment = integration.connections\n .filter((connection) => connection.type === \"env\")\n .map((connection) => connection.name)\n if (environment.length) {\n yield* Effect.fail(\n new Error(\n `${integration.name} is authenticated through ${environment.join(\", \")}; unset the environment variable to disconnect`,\n ),\n )\n }\n yield* Effect.fail(new Error(`No stored credentials for ${integration.name}`))\n }\n const progress = spinner()\n progress.start(\"Removing credential...\")\n yield* Effect.forEach(\n credentials,\n (connection) =>\n request((signal) => client.credential.remove({ credentialID: connection.id, location }, { signal })),\n { concurrency: \"unbounded\", discard: true },\n ).pipe(\n Effect.tap(() => Effect.sync(() => progress.stop(`Disconnected from ${integration.name}`))),\n Effect.tapCause(() => Effect.sync(() => progress.stop(\"Failed to remove credential\", 1))),\n )\n outro(\"Done\")\n})\n\nconst chooseIntegration = Effect.fn(\"cli.auth.logout.integration\")(function* (\n integrations: IntegrationInfo[],\n target?: string,\n) {\n if (target) return yield* resolveIntegration(integrations, target)\n const configured = integrations.filter((integration) =>\n integration.connections.some((connection) => connection.type === \"credential\"),\n )\n if (configured.length === 0) return yield* Effect.fail(new Error(\"No stored credentials found\"))\n const id = yield* prompt<string>(() =>\n autocomplete({\n message: \"Select integration\",\n maxItems: 8,\n options: configured.map((integration) => ({\n value: integration.id,\n label: integration.name,\n hint: integration.connections\n .filter((connection) => connection.type === \"credential\")\n .map((connection) => connection.label)\n .join(\", \"),\n })),\n }),\n )\n return yield* resolveIntegration(configured, id)\n})\n" | ||
| ], | ||
| "mappings": ";k1CAQA,IAAe,IAAQ,QACrB,EAAS,SAAS,KAAK,SAAS,OAChC,EAAO,GAAG,iBAAiB,EAAE,CAAC,IAC5B,EAAO,CACL,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,O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EAAQ,OAAO,MAAO,EAAmB,EAAc,CAAM,EACjE,IAAM,EAAa,EAAa,OAAO,CAAC,IACtC,EAAY,YAAY,KAAK,CAAC,IAAe,EAAW,OAAS,YAAY,CAC/E,EACA,GAAI,EAAW,SAAW,EAAG,OAAO,MAAO,EAAO,KAAS,MAAM,6BAA6B,CAAC,EAC/F,IAAM,EAAK,MAAO,EAAe,IAC/B,EAAa,CACX,QAAS,qBACT,SAAU,EACV,QAAS,EAAW,IAAI,CAAC,KAAiB,CACxC,MAAO,EAAY,GACnB,MAAO,EAAY,KACnB,KAAM,EAAY,YACf,OAAO,CAAC,IAAe,EAAW,OAAS,YAAY,EACvD,IAAI,CAAC,IAAe,EAAW,KAAK,EACpC,KAAK,IAAI,CACd,EAAE,CACJ,CAAC,CACH,EACA,OAAO,MAAO,EAAmB,EAAY,CAAE,EAChD", | ||
| "debugId": "E9BB576C32D3674F64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.13/node_modules/@aws-sdk/credential-provider-sso/dist-es/fromSSO.js", "../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.13/node_modules/@aws-sdk/credential-provider-sso/dist-es/isSsoProfile.js", "../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.13/node_modules/@aws-sdk/credential-provider-sso/dist-es/resolveSSOCredentials.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1111.0/node_modules/@aws-sdk/token-providers/dist-es/fromSso.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1111.0/node_modules/@aws-sdk/token-providers/dist-es/constants.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1111.0/node_modules/@aws-sdk/token-providers/dist-es/getSsoOidcClient.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1111.0/node_modules/@aws-sdk/token-providers/dist-es/getNewSsoOidcToken.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1111.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenExpiry.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1111.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenKey.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1111.0/node_modules/@aws-sdk/token-providers/dist-es/writeSSOTokenToFile.js", "../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.13/node_modules/@aws-sdk/credential-provider-sso/dist-es/validateSsoProfile.js"], | ||
| "sourcesContent": [ | ||
| "import { CredentialsProviderError, getProfileName, loadSsoSessionData, parseKnownFiles } from \"@smithy/core/config\";\nimport { isSsoProfile } from \"./isSsoProfile\";\nimport { resolveSSOCredentials } from \"./resolveSSOCredentials\";\nimport { validateSsoProfile } from \"./validateSsoProfile\";\nexport const fromSSO = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-sso - fromSSO\");\n const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init;\n const { ssoClient } = init;\n const profileName = getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n });\n if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {\n const profiles = await parseKnownFiles(init);\n const profile = profiles[profileName];\n if (!profile) {\n throw new CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger });\n }\n if (!isSsoProfile(profile)) {\n throw new CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, {\n logger: init.logger,\n });\n }\n if (profile?.sso_session) {\n const ssoSessions = await loadSsoSessionData(init);\n const session = ssoSessions[profile.sso_session];\n const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`;\n if (ssoRegion && ssoRegion !== session.sso_region) {\n throw new CredentialsProviderError(`Conflicting SSO region` + conflictMsg, {\n tryNextLink: false,\n logger: init.logger,\n });\n }\n if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) {\n throw new CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, {\n tryNextLink: false,\n logger: init.logger,\n });\n }\n profile.sso_region = session.sso_region;\n profile.sso_start_url = session.sso_start_url;\n }\n const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile, init.logger);\n return resolveSSOCredentials({\n ssoStartUrl: sso_start_url,\n ssoSession: sso_session,\n ssoAccountId: sso_account_id,\n ssoRegion: sso_region,\n ssoRoleName: sso_role_name,\n ssoClient: ssoClient,\n clientConfig: init.clientConfig,\n parentClientConfig: init.parentClientConfig,\n callerClientConfig: init.callerClientConfig,\n profile: profileName,\n filepath: init.filepath,\n configFilepath: init.configFilepath,\n ignoreCache: init.ignoreCache,\n logger: init.logger,\n });\n }\n else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) {\n throw new CredentialsProviderError(\"Incomplete configuration. The fromSSO() argument hash must include \" +\n '\"ssoStartUrl\", \"ssoAccountId\", \"ssoRegion\", \"ssoRoleName\"', { tryNextLink: false, logger: init.logger });\n }\n else {\n return resolveSSOCredentials({\n ssoStartUrl,\n ssoSession,\n ssoAccountId,\n ssoRegion,\n ssoRoleName,\n ssoClient,\n clientConfig: init.clientConfig,\n parentClientConfig: init.parentClientConfig,\n callerClientConfig: init.callerClientConfig,\n profile: profileName,\n filepath: init.filepath,\n configFilepath: init.configFilepath,\n ignoreCache: init.ignoreCache,\n logger: init.logger,\n });\n }\n};\n", | ||
| "export const isSsoProfile = (arg) => arg &&\n (typeof arg.sso_start_url === \"string\" ||\n typeof arg.sso_account_id === \"string\" ||\n typeof arg.sso_session === \"string\" ||\n typeof arg.sso_region === \"string\" ||\n typeof arg.sso_role_name === \"string\");\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { fromSso as getSsoTokenProvider } from \"@aws-sdk/token-providers\";\nimport { CredentialsProviderError, getSSOTokenFromFile } from \"@smithy/core/config\";\nconst SHOULD_FAIL_CREDENTIAL_CHAIN = false;\nexport const resolveSSOCredentials = async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, callerClientConfig, profile, filepath, configFilepath, ignoreCache, logger, }) => {\n let token;\n const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`;\n if (ssoSession) {\n try {\n const _token = await getSsoTokenProvider({\n profile,\n filepath,\n configFilepath,\n ignoreCache,\n clientConfig,\n parentClientConfig,\n logger,\n })({ callerClientConfig });\n token = {\n accessToken: _token.token,\n expiresAt: new Date(_token.expiration).toISOString(),\n };\n }\n catch (e) {\n throw new CredentialsProviderError(e.message, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n }\n else {\n try {\n token = await getSSOTokenFromFile(ssoStartUrl);\n }\n catch (e) {\n throw new CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n }\n if (new Date(token.expiresAt).getTime() - Date.now() <= 0) {\n throw new CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n const { accessToken } = token;\n const { SSOClient, GetRoleCredentialsCommand } = await import(\"./loadSso.js\");\n const sso = ssoClient ||\n new SSOClient(Object.assign({}, clientConfig ?? {}, {\n logger: clientConfig?.logger ?? callerClientConfig?.logger ?? parentClientConfig?.logger,\n region: clientConfig?.region ?? ssoRegion,\n userAgentAppId: clientConfig?.userAgentAppId ?? callerClientConfig?.userAgentAppId ?? parentClientConfig?.userAgentAppId,\n }));\n let ssoResp;\n try {\n ssoResp = await sso.send(new GetRoleCredentialsCommand({\n accountId: ssoAccountId,\n roleName: ssoRoleName,\n accessToken,\n }));\n }\n catch (e) {\n throw new CredentialsProviderError(e, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {}, } = ssoResp;\n if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) {\n throw new CredentialsProviderError(\"SSO returns an invalid temporary credential.\", {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n const credentials = {\n accessKeyId,\n secretAccessKey,\n sessionToken,\n expiration: new Date(expiration),\n ...(credentialScope && { credentialScope }),\n ...(accountId && { accountId }),\n };\n if (ssoSession) {\n setCredentialFeature(credentials, \"CREDENTIALS_SSO\", \"s\");\n }\n else {\n setCredentialFeature(credentials, \"CREDENTIALS_SSO_LEGACY\", \"u\");\n }\n return credentials;\n};\n", | ||
| "import { getProfileName, getSSOTokenFromFile, loadSsoSessionData, parseKnownFiles, TokenProviderError, } from \"@smithy/core/config\";\nimport { EXPIRE_WINDOW_MS, REFRESH_MESSAGE } from \"./constants\";\nimport { getNewSsoOidcToken } from \"./getNewSsoOidcToken\";\nimport { validateTokenExpiry } from \"./validateTokenExpiry\";\nimport { validateTokenKey } from \"./validateTokenKey\";\nimport { writeSSOTokenToFile } from \"./writeSSOTokenToFile\";\nconst lastRefreshAttemptTime = new Date(0);\nexport const fromSso = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/token-providers - fromSso\");\n const profiles = await parseKnownFiles(init);\n const profileName = getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n });\n const profile = profiles[profileName];\n if (!profile) {\n throw new TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false);\n }\n else if (!profile[\"sso_session\"]) {\n throw new TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`);\n }\n const ssoSessionName = profile[\"sso_session\"];\n const ssoSessions = await loadSsoSessionData(init);\n const ssoSession = ssoSessions[ssoSessionName];\n if (!ssoSession) {\n throw new TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false);\n }\n for (const ssoSessionRequiredKey of [\"sso_start_url\", \"sso_region\"]) {\n if (!ssoSession[ssoSessionRequiredKey]) {\n throw new TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false);\n }\n }\n const ssoStartUrl = ssoSession[\"sso_start_url\"];\n const ssoRegion = ssoSession[\"sso_region\"];\n let ssoToken;\n try {\n ssoToken = await getSSOTokenFromFile(ssoSessionName);\n }\n catch (e) {\n throw new TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false);\n }\n validateTokenKey(\"accessToken\", ssoToken.accessToken);\n validateTokenKey(\"expiresAt\", ssoToken.expiresAt);\n const { accessToken, expiresAt } = ssoToken;\n const existingToken = { token: accessToken, expiration: new Date(expiresAt) };\n if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) {\n return existingToken;\n }\n if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1000) {\n validateTokenExpiry(existingToken);\n return existingToken;\n }\n validateTokenKey(\"clientId\", ssoToken.clientId, true);\n validateTokenKey(\"clientSecret\", ssoToken.clientSecret, true);\n validateTokenKey(\"refreshToken\", ssoToken.refreshToken, true);\n try {\n lastRefreshAttemptTime.setTime(Date.now());\n const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init, callerClientConfig);\n validateTokenKey(\"accessToken\", newSsoOidcToken.accessToken);\n validateTokenKey(\"expiresIn\", newSsoOidcToken.expiresIn);\n const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1000);\n try {\n await writeSSOTokenToFile(ssoSessionName, {\n ...ssoToken,\n accessToken: newSsoOidcToken.accessToken,\n expiresAt: newTokenExpiration.toISOString(),\n refreshToken: newSsoOidcToken.refreshToken,\n });\n }\n catch (error) {\n }\n return {\n token: newSsoOidcToken.accessToken,\n expiration: newTokenExpiration,\n };\n }\n catch (error) {\n validateTokenExpiry(existingToken);\n return existingToken;\n }\n};\n", | ||
| "export const EXPIRE_WINDOW_MS = 5 * 60 * 1000;\nexport const REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;\n", | ||
| "export const getSsoOidcClient = async (ssoRegion, init = {}, callerClientConfig) => {\n const { SSOOIDCClient } = await import(\"@aws-sdk/nested-clients/sso-oidc\");\n const coalesce = (prop) => init.clientConfig?.[prop] ?? init.parentClientConfig?.[prop] ?? callerClientConfig?.[prop];\n const ssoOidcClient = new SSOOIDCClient(Object.assign({}, init.clientConfig ?? {}, {\n region: ssoRegion ?? init.clientConfig?.region,\n logger: coalesce(\"logger\"),\n userAgentAppId: coalesce(\"userAgentAppId\"),\n }));\n return ssoOidcClient;\n};\n", | ||
| "import { getSsoOidcClient } from \"./getSsoOidcClient\";\nexport const getNewSsoOidcToken = async (ssoToken, ssoRegion, init = {}, callerClientConfig) => {\n const { CreateTokenCommand } = await import(\"@aws-sdk/nested-clients/sso-oidc\");\n const ssoOidcClient = await getSsoOidcClient(ssoRegion, init, callerClientConfig);\n return ssoOidcClient.send(new CreateTokenCommand({\n clientId: ssoToken.clientId,\n clientSecret: ssoToken.clientSecret,\n refreshToken: ssoToken.refreshToken,\n grantType: \"refresh_token\",\n }));\n};\n", | ||
| "import { TokenProviderError } from \"@smithy/core/config\";\nimport { REFRESH_MESSAGE } from \"./constants\";\nexport const validateTokenExpiry = (token) => {\n if (token.expiration && token.expiration.getTime() < Date.now()) {\n throw new TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false);\n }\n};\n", | ||
| "import { TokenProviderError } from \"@smithy/core/config\";\nimport { REFRESH_MESSAGE } from \"./constants\";\nexport const validateTokenKey = (key, value, forRefresh = false) => {\n if (typeof value === \"undefined\") {\n throw new TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? \". Cannot refresh\" : \"\"}. ${REFRESH_MESSAGE}`, false);\n }\n};\n", | ||
| "import { getSSOTokenFilepath } from \"@smithy/core/config\";\nimport { promises as fsPromises } from \"node:fs\";\nconst { writeFile } = fsPromises;\nexport const writeSSOTokenToFile = (id, ssoToken) => {\n const tokenFilepath = getSSOTokenFilepath(id);\n const tokenString = JSON.stringify(ssoToken, null, 2);\n return writeFile(tokenFilepath, tokenString);\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nexport const validateSsoProfile = (profile, logger) => {\n const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile;\n if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) {\n throw new CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters \"sso_account_id\", ` +\n `\"sso_region\", \"sso_role_name\", \"sso_start_url\". Got ${Object.keys(profile).join(\", \")}\\nReference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger });\n }\n return profile;\n};\n" | ||
| ], | ||
| "mappings": ";sKAAA,eCAO,IAAM,EAAe,CAAC,IAAQ,IAChC,OAAO,EAAI,gBAAkB,UAC1B,OAAO,EAAI,iBAAmB,UAC9B,OAAO,EAAI,cAAgB,UAC3B,OAAO,EAAI,aAAe,UAC1B,OAAO,EAAI,gBAAkB,UCLrC,gBCAA,eCAO,IAAM,EAAmB,OACnB,EAAkB,kFCDxB,IAAM,EAAmB,MAAO,EAAW,EAAO,CAAC,EAAG,IAAuB,CAChF,IAAQ,iBAAkB,KAAa,0CACjC,EAAW,CAAC,IAAS,EAAK,eAAe,IAAS,EAAK,qBAAqB,IAAS,IAAqB,GAMhH,OALsB,IAAI,EAAc,OAAO,OAAO,CAAC,EAAG,EAAK,cAAgB,CAAC,EAAG,CAC/E,OAAQ,GAAa,EAAK,cAAc,OACxC,OAAQ,EAAS,QAAQ,EACzB,eAAgB,EAAS,gBAAgB,CAC7C,CAAC,CAAC,GCNC,IAAM,EAAqB,MAAO,EAAU,EAAW,EAAO,CAAC,EAAG,IAAuB,CAC5F,IAAQ,sBAAuB,KAAa,0CAE5C,OADsB,MAAM,EAAiB,EAAW,EAAM,CAAkB,GAC3D,KAAK,IAAI,EAAmB,CAC7C,SAAU,EAAS,SACnB,aAAc,EAAS,aACvB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AAQ,EAAK,MACjB,CAAC,EAEL,EAAQ,WAAa,EAAQ,WAC7B,EAAQ,cAAgB,EAAQ,cAEpC,IAAQ,gBAAe,iBAAgB,aAAY,gBAAe,eAAgB,EAAmB,EAAS,EAAK,MAAM,EACzH,OAAO,EAAsB,CACzB,YAAa,EACb,WAAY,EACZ,aAAc,EACd,UAAW,EACX,YAAa,EACb,UAAW,EACX,aAAc,EAAK,aACnB,mBAAoB,EAAK,mBACzB,mBAAoB,EAAK,mBACzB,QAAS,EACT,SAAU,EAAK,SACf,eAAgB,EAAK,eACrB,YAAa,EAAK,YAClB,OAAQ,EAAK,MACjB,CAAC,EAEA,QAAI,CAAC,GAAe,CAAC,GAAgB,CAAC,GAAa,CAAC,EACrD,MAAM,IAAI,2BAAyB,+HAC8B,CAAE,YAAa,GAAO,OAAQ,EAAK,MAAO,CAAC,EAG5G,YAAO,EAAsB,CACzB,cACA,aACA,eACA,YACA,cACA,YACA,aAAc,EAAK,aACnB,mBAAoB,EAAK,mBACzB,mBAAoB,EAAK,mBACzB,QAAS,EACT,SAAU,EAAK,SACf,eAAgB,EAAK,eACrB,YAAa,EAAK,YAClB,OAAQ,EAAK,MACjB,CAAC", | ||
| "debugId": "879C4286FB0AE24264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mcp/list.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { OpenCode, type McpServer } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.list,\n Effect.fn(\"cli.mcp.list\")(function* () {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.mcp.list({ location: { directory: process.cwd() } }))\n const servers = response.data.toSorted((a, b) => a.name.localeCompare(b.name))\n if (servers.length === 0) {\n process.stdout.write(\"No MCP servers configured\" + EOL)\n return\n }\n const width = Math.max(...servers.map((server) => server.name.length))\n const lines = servers.map(\n (server) => `${icon(server.status)} ${server.name.padEnd(width)} ${describe(server.status)}`,\n )\n process.stdout.write(lines.join(EOL) + EOL)\n }),\n)\n\nfunction icon(status: McpServer[\"status\"]) {\n switch (status.status) {\n case \"connected\":\n return \"✓\"\n case \"needs_auth\":\n return \"⚠\"\n case \"failed\":\n return \"✗\"\n default:\n return \"○\"\n }\n}\n\nfunction describe(status: McpServer[\"status\"]) {\n switch (status.status) {\n case \"needs_auth\":\n return \"needs authentication\"\n case \"failed\":\n return `failed: ${status.error}`\n default:\n return status.status\n }\n}\n" | ||
| ], | ||
| "mappings": ";08BAAA,cAAS,WAQT,IAAe,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,KAC/B,EAAO,GAAG,cAAc,EAAE,SAAU,EAAG,CACrC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,GADW,MAAO,EAAO,QAAQ,IAAM,EAAO,IAAI,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,GAC/E,KAAK,SAAS,CAAC,EAAG,IAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC,EAC7E,GAAI,EAAQ,SAAW,EAAG,CACxB,QAAQ,OAAO,MAAM,4BAA8B,CAAG,EACtD,OAEF,IAAM,EAAQ,KAAK,IAAI,GAAG,EAAQ,IAAI,CAAC,IAAW,EAAO,KAAK,MAAM,CAAC,EAC/D,EAAQ,EAAQ,IACpB,CAAC,IAAW,GAAG,EAAK,EAAO,MAAM,KAAK,EAAO,KAAK,OAAO,CAAK,MAAM,EAAS,EAAO,MAAM,GAC5F,EACA,QAAQ,OAAO,MAAM,EAAM,KAAK,CAAG,EAAI,CAAG,EAC3C,CACH,EAEA,SAAS,CAAI,CAAC,EAA6B,CACzC,OAAQ,EAAO,YACR,YACH,MAAO,aACJ,aACH,MAAO,aACJ,SACH,MAAO,iBAEP,MAAO,UAIb,SAAS,CAAQ,CAAC,EAA6B,CAC7C,OAAQ,EAAO,YACR,aACH,MAAO,2BACJ,SACH,MAAO,WAAW,EAAO,gBAEzB,OAAO,EAAO", | ||
| "debugId": "67553A76926FD57464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mcp/auth.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport {\n OpenCode,\n type IntegrationAttemptStatus,\n type IntegrationOAuthMethod,\n type OpenCodeClient,\n} from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { resolveIntegration } from \"./resolve\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.auth,\n Effect.fn(\"cli.mcp.auth\")(function* (input) {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n\n const integration = yield* resolveIntegration(client, input.name, location)\n if (!integration)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" is not an OAuth-capable remote server`))\n const method = integration.methods.find(\n (candidate): candidate is IntegrationOAuthMethod => candidate.type === \"oauth\",\n )\n if (!method)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" is not an OAuth-capable remote server`))\n\n const started = yield* Effect.promise(() =>\n client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, location }),\n )\n const attempt = started.data\n if (attempt.mode === \"code\")\n return yield* Effect.fail(new Error(\"This server requires manual code entry, which the CLI does not support\"))\n\n process.stdout.write(attempt.instructions + EOL + attempt.url + EOL)\n\n const result = yield* poll(client, integration.id, attempt.attemptID)\n if (result.status === \"complete\") {\n process.stdout.write(`Authenticated with ${input.name}` + EOL)\n return\n }\n const reason = result.status === \"failed\" ? `: ${result.message}` : \"\"\n return yield* Effect.fail(new Error(`Authentication ${result.status}${reason}`))\n }),\n)\n\nconst poll = (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n): Effect.Effect<Exclude<IntegrationAttemptStatus, { status: \"pending\" }>> =>\n Effect.gen(function* () {\n const status = yield* Effect.promise(() =>\n client.integration.oauth.status({ integrationID, attemptID, location }),\n ).pipe(Effect.map((result) => result.data))\n if (status.status === \"pending\") {\n yield* Effect.sleep(\"1 second\")\n return yield* poll(client, integrationID, attemptID)\n }\n return status\n })\n" | ||
| ], | ||
| "mappings": ";8/BAAA,cAAS,WAcT,IAAM,EAAW,CAAE,UAAW,QAAQ,IAAI,CAAE,EAE7B,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,KAC/B,EAAO,GAAG,cAAc,EAAE,SAAU,CAAC,EAAO,CAC1C,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,EAAc,MAAO,EAAmB,EAAQ,EAAM,KAAM,CAAQ,EAC1E,GAAI,CAAC,EACH,OAAO,MAAO,EAAO,KAAS,MAAM,eAAe,EAAM,6CAA6C,CAAC,EACzG,IAAM,EAAS,EAAY,QAAQ,KACjC,CAAC,IAAmD,EAAU,OAAS,OACzE,EACA,GAAI,CAAC,EACH,OAAO,MAAO,EAAO,KAAS,MAAM,eAAe,EAAM,6CAA6C,CAAC,EAKzG,IAAM,GAHU,MAAO,EAAO,QAAQ,IACpC,EAAO,YAAY,MAAM,QAAQ,CAAE,cAAe,EAAY,GAAI,SAAU,EAAO,GAAI,UAAS,CAAC,CACnG,GACwB,KACxB,GAAI,EAAQ,OAAS,OACnB,OAAO,MAAO,EAAO,KAAS,MAAM,wEAAwE,CAAC,EAE/G,QAAQ,OAAO,MAAM,EAAQ,aAAe,EAAM,EAAQ,IAAM,CAAG,EAEnE,IAAM,EAAS,MAAO,EAAK,EAAQ,EAAY,GAAI,EAAQ,SAAS,EACpE,GAAI,EAAO,SAAW,WAAY,CAChC,QAAQ,OAAO,MAAM,sBAAsB,EAAM,OAAS,CAAG,EAC7D,OAEF,IAAM,EAAS,EAAO,SAAW,SAAW,KAAK,EAAO,UAAY,GACpE,OAAO,MAAO,EAAO,KAAS,MAAM,kBAAkB,EAAO,SAAS,GAAQ,CAAC,EAChF,CACH,EAEM,EAAO,CACX,EACA,EACA,IAEA,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAS,MAAO,EAAO,QAAQ,IACnC,EAAO,YAAY,MAAM,OAAO,CAAE,gBAAe,YAAW,UAAS,CAAC,CACxE,EAAE,KAAK,EAAO,IAAI,CAAC,IAAW,EAAO,IAAI,CAAC,EAC1C,GAAI,EAAO,SAAW,UAEpB,OADA,MAAO,EAAO,MAAM,UAAU,EACvB,MAAO,EAAK,EAAQ,EAAe,CAAS,EAErD,OAAO,EACR", | ||
| "debugId": "4170E105BB79477964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/services/service-config.ts"], | ||
| "sourcesContent": [ | ||
| "import { Global } from \"@opencode-ai/util/global\"\nimport { OPENCODE_CHANNEL, OPENCODE_VERSION } from \"../version\"\nimport { Hash } from \"@opencode-ai/util/hash\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, FileSystem, Option, Schema } from \"effect\"\nimport { randomBytes } from \"crypto\"\nimport path from \"path\"\nimport { selfCommand } from \"../util/process\"\n\n// The CLI's service configuration file, plus the Service.EnsureOptions binding that\n// points the client package's service operations at this CLI: which\n// registration file (by channel), which version, and how to spawn opencode.\n\nexport const Info = Schema.Struct({\n hostname: Schema.optional(Schema.String),\n port: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(65_535))),\n password: Schema.optional(Schema.String),\n cors: Schema.optional(Schema.Array(Schema.String)),\n env: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n})\nexport type Info = typeof Info.Type\n\nconst keys = [\"hostname\", \"port\", \"password\", \"cors\", \"env\"] as const\ntype Key = (typeof keys)[number]\n\nconst decodeInfo = Schema.decodeUnknownEffect(Schema.fromJsonString(Info))\nconst decodeRegistration = Schema.decodeUnknownEffect(Schema.fromJsonString(Service.Info))\n\nexport function filename(channel = OPENCODE_CHANNEL) {\n if (channel === \"latest\" || channel === \"dev\" || channel === \"beta\" || channel === \"next\") return \"service.json\"\n return `service-${channel.replace(/[^a-zA-Z0-9._-]/g, \"-\")}.json`\n}\n\nexport function defaultPort(channel = OPENCODE_CHANNEL) {\n if (channel === \"latest\" || channel === \"dev\" || channel === \"beta\" || channel === \"next\") return 0xc0de\n if (channel === \"local\") return 0xc0df\n return 10_000 + (Number.parseInt(Hash.fast(channel).slice(0, 8), 16) % 50_000)\n}\n\nexport function legacyFilename(channel = OPENCODE_CHANNEL) {\n if (channel === \"latest\" || channel === \"local\") return\n return `service-${Hash.fast(channel)}.json`\n}\n\nexport function versionBelongsToChannel(\n version: string | undefined,\n channel = OPENCODE_CHANNEL,\n installedVersion = OPENCODE_VERSION,\n) {\n if (version === undefined) return false\n if (version === installedVersion) return true\n const prefix = `0.0.0-${channel}-`\n if (!version.startsWith(prefix)) return false\n return /^\\d+(?:\\.\\d+)?$/.test(version.slice(prefix.length))\n}\n\nexport const migrateRegistration = Effect.fnUntraced(function* (\n legacy: string,\n file: string,\n channel = OPENCODE_CHANNEL,\n installedVersion = OPENCODE_VERSION,\n) {\n const fs = yield* FileSystem.FileSystem\n const text = yield* fs.readFileString(legacy).pipe(Effect.option)\n if (Option.isNone(text)) return\n const registration = yield* decodeRegistration(text.value).pipe(Effect.option)\n if (Option.isNone(registration)) return\n if (!versionBelongsToChannel(registration.value.version, channel, installedVersion)) return\n yield* fs.writeFileString(file, text.value, { flag: \"wx\", mode: 0o600 }).pipe(Effect.ignore)\n})\n\nexport const migrateConfig = Effect.fnUntraced(function* (legacy: string, file: string) {\n const fs = yield* FileSystem.FileSystem\n const text = yield* fs.readFileString(legacy).pipe(Effect.option)\n if (Option.isNone(text)) return\n if (Option.isNone(yield* decodeInfo(text.value).pipe(Effect.option))) return\n yield* fs.writeFileString(file, text.value, { flag: \"wx\", mode: 0o600 }).pipe(Effect.ignore)\n})\n\nfunction configKey(key: string): Key {\n if (key === \"hostname\" || key === \"port\" || key === \"password\" || key === \"cors\" || key === \"env\") return key\n throw new Error(`Unknown service config key: ${key}`)\n}\n\nconst paths = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem\n const global = yield* Global.Service\n const name = filename()\n const legacy = legacyFilename()\n const file = path.join(global.state, name)\n return {\n fs,\n file,\n legacyConfigFile: legacy ? path.join(global.config, legacy) : undefined,\n legacyRegistrationFiles: [\n ...(legacy ? [path.join(global.state, legacy)] : []),\n ...(name !== \"service.json\" && OPENCODE_CHANNEL !== \"local\" ? [path.join(global.state, \"service.json\")] : []),\n ],\n configFile: path.join(global.config, name),\n }\n})\n\nexport const options = Effect.fnUntraced(function* (input: { readonly checkVersion?: boolean } = {}) {\n const { file, legacyRegistrationFiles } = yield* paths\n yield* Effect.forEach(legacyRegistrationFiles, (legacy) => migrateRegistration(legacy, file))\n return {\n file,\n version: input.checkVersion ? OPENCODE_VERSION : undefined,\n env: (yield* read()).env,\n command: [\n ...selfCommand(),\n \"serve\",\n \"--service\",\n ],\n }\n})\n\nexport const read = Effect.fn(\"cli.service-config.read\")(function* () {\n const { fs, configFile, legacyConfigFile } = yield* paths\n if (legacyConfigFile) yield* migrateConfig(legacyConfigFile, configFile)\n return yield* fs.readFileString(configFile).pipe(\n Effect.flatMap(decodeInfo),\n Effect.orElseSucceed(() => ({}) as Info),\n )\n})\n\nconst write = Effect.fn(\"cli.service-config.write\")(function* (value: Info) {\n const { fs, configFile } = yield* paths\n const temp = configFile + \".tmp\"\n yield* fs.makeDirectory(path.dirname(configFile), { recursive: true })\n yield* fs.writeFileString(temp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n yield* fs.rename(temp, configFile)\n})\n\nexport const password = Effect.fn(\"cli.service-config.password\")(function* (value?: string) {\n const existing = yield* read()\n if (value === undefined && existing.password) return existing.password\n const next = value ?? randomBytes(32).toString(\"base64url\")\n\n // Keep one private credential across server restarts so discovered clients\n // can reconnect without exposing a password flag or environment variable.\n yield* write({ ...existing, password: next })\n return next\n})\n\nexport const get = Effect.fn(\"cli.service-config.get\")(function* (key?: string, name?: string) {\n if (key === undefined) {\n const { password: _password, ...safe } = yield* read()\n return JSON.stringify(safe, null, 2)\n }\n const selected = configKey(key)\n if (selected !== \"env\" && name !== undefined) throw new Error(`Usage: opencode service get ${selected}`)\n switch (selected) {\n case \"hostname\": {\n return (yield* read()).hostname ?? \"\"\n }\n case \"port\": {\n const port = (yield* read()).port\n return port === undefined ? \"\" : String(port)\n }\n case \"password\": {\n return yield* password()\n }\n case \"cors\": {\n return JSON.stringify((yield* read()).cors ?? [], null, 2)\n }\n case \"env\": {\n const env = (yield* read()).env ?? {}\n return name === undefined ? JSON.stringify(env, null, 2) : (env[name] ?? \"\")\n }\n }\n throw new Error(`Unknown service config key: ${key}`)\n})\n\nexport const set = Effect.fn(\"cli.service-config.set\")(function* (key: string, value: string, nestedValue?: string) {\n const selected = configKey(key)\n if (selected !== \"env\" && nestedValue !== undefined)\n throw new Error(`Usage: opencode service set ${selected} <value>`)\n switch (selected) {\n case \"hostname\": {\n yield* Service.stop(yield* options())\n yield* write({ ...(yield* read()), hostname: value })\n return\n }\n case \"port\": {\n const port = Number(value)\n if (!Number.isInteger(port) || port < 1 || port > 65_535) throw new Error(\"Port must be between 1 and 65535\")\n yield* Service.stop(yield* options())\n yield* write({ ...(yield* read()), port })\n return\n }\n case \"password\": {\n yield* Service.stop(yield* options())\n yield* password(value)\n return\n }\n case \"env\": {\n if (nestedValue === undefined) throw new Error(\"Usage: opencode service set env <key> <value>\")\n yield* Service.stop(yield* options())\n const existing = yield* read()\n yield* write({ ...existing, env: { ...existing.env, [value]: nestedValue } })\n return\n }\n case \"cors\": {\n const cors = value.split(\",\").map((origin) => origin.trim())\n if (\n cors.some((origin) => {\n const url = URL.parse(origin)\n return !url || (url.protocol !== \"http:\" && url.protocol !== \"https:\") || url.origin !== origin\n })\n )\n throw new Error(\"CORS must be a comma-separated list of HTTP(S) origins without paths or trailing slashes\")\n yield* Service.stop(yield* options())\n yield* write({ ...(yield* read()), cors })\n return\n }\n }\n})\n\nexport const unset = Effect.fn(\"cli.service-config.unset\")(function* (key: string, name?: string) {\n const selected = configKey(key)\n if (selected !== \"env\" && name !== undefined) throw new Error(`Usage: opencode service unset ${selected}`)\n switch (selected) {\n case \"hostname\": {\n yield* Service.stop(yield* options())\n const { hostname: _hostname, ...next } = yield* read()\n yield* write(next)\n return\n }\n case \"port\": {\n yield* Service.stop(yield* options())\n const { port: _port, ...next } = yield* read()\n yield* write(next)\n return\n }\n case \"password\": {\n yield* Service.stop(yield* options())\n const { password: _password, ...next } = yield* read()\n yield* write(next)\n return\n }\n case \"env\": {\n if (name === undefined) throw new Error(\"Usage: opencode service unset env <key>\")\n yield* Service.stop(yield* options())\n const existing = yield* read()\n const { [name]: _removed, ...env } = existing.env ?? {}\n const { env: _existingEnv, ...rest } = existing\n yield* write(Object.keys(env).length === 0 ? rest : { ...rest, env })\n return\n }\n case \"cors\": {\n yield* Service.stop(yield* options())\n const { cors: _cors, ...next } = yield* read()\n yield* write(next)\n return\n }\n }\n})\n\nexport * as ServiceConfig from \"./service-config\"\n" | ||
| ], | ||
| "mappings": ";ylBAKA,sBAAS,eAC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GAAS,MAAO,EAAK,EAC7C,MAAO,EAAM,CAAI,EACjB,MACF,KACK,WAAY,CACf,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAQ,SAAU,KAAc,GAAS,MAAO,EAAK,EACrD,MAAO,EAAM,CAAI,EACjB,MACF,KACK,MAAO,CACV,GAAI,IAAS,OAAW,MAAU,MAAM,yCAAyC,EACjF,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAM,EAAW,MAAO,EAAK,IACpB,GAAO,KAAa,GAAQ,EAAS,KAAO,CAAC,GAC9C,IAAK,KAAiB,GAAS,EACvC,MAAO,EAAM,OAAO,KAAK,CAAG,EAAE,SAAW,EAAI,EAAO,IAAK,EAAM,KAAI,CAAC,EACpE,MACF,KACK,OAAQ,CACX,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAQ,KAAM,KAAU,GAAS,MAAO,EAAK,EAC7C,MAAO,EAAM,CAAI,EACjB,MACF,GAEH", | ||
| "debugId": "266B0718144AEE3164756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+nested-clients@3.997.43/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/cognito-identity/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsJson1_1Protocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultCognitoIdentityHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"cognito-identity\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultCognitoIdentityHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"GetCredentialsForIdentity\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n case \"GetId\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"cognito-identity\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.42\";\nvar packageInfo = {\n\tversion: version};\n\nconst m = \"ref\";\nconst a = -1, b = true, c = \"isSet\", d = \"PartitionResult\", e = \"booleanEquals\", f = \"getAttr\", g = \"stringEquals\", h = { [m]: \"Endpoint\" }, i = { [m]: d }, j = { [m]: \"Region\" }, k = {}, l = [j];\nconst _data = {\n conditions: [\n [c, [h]],\n [c, l],\n [\"aws.partition\", l, d],\n [e, [{ [m]: \"UseFIPS\" }, b]],\n [e, [{ fn: f, argv: [i, \"supportsFIPS\"] }, b]],\n [e, [{ [m]: \"UseDualStack\" }, b]],\n [e, [{ fn: f, argv: [i, \"supportsDualStack\"] }, b]],\n [g, [{ fn: f, argv: [i, \"name\"] }, \"aws\"]],\n [g, [j, \"us-east-1\"]],\n [g, [j, \"us-east-2\"]],\n [g, [j, \"us-west-1\"]],\n [g, [j, \"us-west-2\"]]\n ],\n results: [\n [a],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [h, k],\n [\"https://cognito-identity-fips.us-east-1.amazonaws.com\", k],\n [\"https://cognito-identity-fips.us-east-2.amazonaws.com\", k],\n [\"https://cognito-identity-fips.us-west-1.amazonaws.com\", k],\n [\"https://cognito-identity-fips.us-west-2.amazonaws.com\", k],\n [\"https://cognito-identity-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", k],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://cognito-identity-fips.{Region}.{PartitionResult#dnsSuffix}\", k],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [\"https://cognito-identity.{Region}.amazonaws.com\", k],\n [\"https://cognito-identity.{Region}.{PartitionResult#dualStackDnsSuffix}\", k],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://cognito-identity.{Region}.{PartitionResult#dnsSuffix}\", k],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 17, 3,\n 1, 4, r + 16,\n 2, 5, r + 16,\n 3, 9, 6,\n 5, 7, r + 15,\n 6, 8, r + 14,\n 7, r + 12, r + 13,\n 4, 11, 10,\n 5, r + 9, r + 11,\n 5, 12, r + 10,\n 6, 13, r + 9,\n 8, r + 4, 14,\n 9, r + 5, 15,\n 10, r + 6, 16,\n 11, r + 7, r + 8,\n 3, r + 1, 18,\n 5, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass CognitoIdentityServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, CognitoIdentityServiceException.prototype);\n }\n}\n\nclass ExternalServiceException extends CognitoIdentityServiceException {\n name = \"ExternalServiceException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ExternalServiceException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ExternalServiceException.prototype);\n }\n}\nclass InternalErrorException extends CognitoIdentityServiceException {\n name = \"InternalErrorException\";\n $fault = \"server\";\n constructor(opts) {\n super({\n name: \"InternalErrorException\",\n $fault: \"server\",\n ...opts,\n });\n Object.setPrototypeOf(this, InternalErrorException.prototype);\n }\n}\nclass InvalidIdentityPoolConfigurationException extends CognitoIdentityServiceException {\n name = \"InvalidIdentityPoolConfigurationException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"InvalidIdentityPoolConfigurationException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidIdentityPoolConfigurationException.prototype);\n }\n}\nclass InvalidParameterException extends CognitoIdentityServiceException {\n name = \"InvalidParameterException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"InvalidParameterException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidParameterException.prototype);\n }\n}\nclass NotAuthorizedException extends CognitoIdentityServiceException {\n name = \"NotAuthorizedException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"NotAuthorizedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, NotAuthorizedException.prototype);\n }\n}\nclass ResourceConflictException extends CognitoIdentityServiceException {\n name = \"ResourceConflictException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ResourceConflictException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ResourceConflictException.prototype);\n }\n}\nclass ResourceNotFoundException extends CognitoIdentityServiceException {\n name = \"ResourceNotFoundException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ResourceNotFoundException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ResourceNotFoundException.prototype);\n }\n}\nclass TooManyRequestsException extends CognitoIdentityServiceException {\n name = \"TooManyRequestsException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"TooManyRequestsException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, TooManyRequestsException.prototype);\n }\n}\nclass LimitExceededException extends CognitoIdentityServiceException {\n name = \"LimitExceededException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"LimitExceededException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, LimitExceededException.prototype);\n }\n}\n\nconst _AI = \"AccountId\";\nconst _AKI = \"AccessKeyId\";\nconst _C = \"Credentials\";\nconst _CRA = \"CustomRoleArn\";\nconst _E = \"Expiration\";\nconst _ESE = \"ExternalServiceException\";\nconst _GCFI = \"GetCredentialsForIdentity\";\nconst _GCFII = \"GetCredentialsForIdentityInput\";\nconst _GCFIR = \"GetCredentialsForIdentityResponse\";\nconst _GI = \"GetId\";\nconst _GII = \"GetIdInput\";\nconst _GIR = \"GetIdResponse\";\nconst _IEE = \"InternalErrorException\";\nconst _II = \"IdentityId\";\nconst _IIPCE = \"InvalidIdentityPoolConfigurationException\";\nconst _IPE = \"InvalidParameterException\";\nconst _IPI = \"IdentityPoolId\";\nconst _IPT = \"IdentityProviderToken\";\nconst _L = \"Logins\";\nconst _LEE = \"LimitExceededException\";\nconst _LM = \"LoginsMap\";\nconst _NAE = \"NotAuthorizedException\";\nconst _RCE = \"ResourceConflictException\";\nconst _RNFE = \"ResourceNotFoundException\";\nconst _SK = \"SecretKey\";\nconst _SKS = \"SecretKeyString\";\nconst _ST = \"SessionToken\";\nconst _TMRE = \"TooManyRequestsException\";\nconst _c = \"client\";\nconst _e = \"error\";\nconst _hE = \"httpError\";\nconst _m = \"message\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.cognitoidentity\";\nconst _se = \"server\";\nconst n0 = \"com.amazonaws.cognitoidentity\";\nconst _s_registry = TypeRegistry.for(_s);\nvar CognitoIdentityServiceException$ = [-3, _s, \"CognitoIdentityServiceException\", 0, [], []];\n_s_registry.registerError(CognitoIdentityServiceException$, CognitoIdentityServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar ExternalServiceException$ = [-3, n0, _ESE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(ExternalServiceException$, ExternalServiceException);\nvar InternalErrorException$ = [-3, n0, _IEE,\n { [_e]: _se },\n [_m],\n [0]\n];\nn0_registry.registerError(InternalErrorException$, InternalErrorException);\nvar InvalidIdentityPoolConfigurationException$ = [-3, n0, _IIPCE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(InvalidIdentityPoolConfigurationException$, InvalidIdentityPoolConfigurationException);\nvar InvalidParameterException$ = [-3, n0, _IPE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(InvalidParameterException$, InvalidParameterException);\nvar LimitExceededException$ = [-3, n0, _LEE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(LimitExceededException$, LimitExceededException);\nvar NotAuthorizedException$ = [-3, n0, _NAE,\n { [_e]: _c, [_hE]: 403 },\n [_m],\n [0]\n];\nn0_registry.registerError(NotAuthorizedException$, NotAuthorizedException);\nvar ResourceConflictException$ = [-3, n0, _RCE,\n { [_e]: _c, [_hE]: 409 },\n [_m],\n [0]\n];\nn0_registry.registerError(ResourceConflictException$, ResourceConflictException);\nvar ResourceNotFoundException$ = [-3, n0, _RNFE,\n { [_e]: _c, [_hE]: 404 },\n [_m],\n [0]\n];\nn0_registry.registerError(ResourceNotFoundException$, ResourceNotFoundException);\nvar TooManyRequestsException$ = [-3, n0, _TMRE,\n { [_e]: _c, [_hE]: 429 },\n [_m],\n [0]\n];\nn0_registry.registerError(TooManyRequestsException$, TooManyRequestsException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar IdentityProviderToken = [0, n0, _IPT, 8, 0];\nvar SecretKeyString = [0, n0, _SKS, 8, 0];\nvar Credentials$ = [3, n0, _C,\n 0,\n [_AKI, _SK, _ST, _E],\n [0, [() => SecretKeyString, 0], 0, 4]\n];\nvar GetCredentialsForIdentityInput$ = [3, n0, _GCFII,\n 0,\n [_II, _L, _CRA],\n [0, [() => LoginsMap, 0], 0], 1\n];\nvar GetCredentialsForIdentityResponse$ = [3, n0, _GCFIR,\n 0,\n [_II, _C],\n [0, [() => Credentials$, 0]]\n];\nvar GetIdInput$ = [3, n0, _GII,\n 0,\n [_IPI, _AI, _L],\n [0, 0, [() => LoginsMap, 0]], 1\n];\nvar GetIdResponse$ = [3, n0, _GIR,\n 0,\n [_II],\n [0]\n];\nvar LoginsMap = [2, n0, _LM,\n 0, [0,\n 0],\n [() => IdentityProviderToken,\n 0]\n];\nvar GetCredentialsForIdentity$ = [9, n0, _GCFI,\n 0, () => GetCredentialsForIdentityInput$, () => GetCredentialsForIdentityResponse$\n];\nvar GetId$ = [9, n0, _GI,\n 0, () => GetIdInput$, () => GetIdResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2014-06-30\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultCognitoIdentityHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsJson1_1Protocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.cognitoidentity\",\n errorTypeRegistries,\n xmlNamespace: \"http://cognito-identity.amazonaws.com/doc/2014-06-30/\",\n version: \"2014-06-30\",\n serviceTarget: \"AWSCognitoIdentityService\",\n },\n serviceId: config?.serviceId ?? \"Cognito Identity\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass CognitoIdentityClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultCognitoIdentityHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"AWSCognitoIdentityService\", \"CognitoIdentityClient\", getEndpointPlugin);\nconst _ep0 = {};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass GetCredentialsForIdentityCommand extends command(_ep0, _mw0, \"GetCredentialsForIdentity\", GetCredentialsForIdentity$) {\n}\n\nclass GetIdCommand extends command(_ep0, _mw0, \"GetId\", GetId$) {\n}\n\nconst commands = {\n GetCredentialsForIdentityCommand,\n GetIdCommand,\n};\nclass CognitoIdentity extends CognitoIdentityClient {\n}\ncreateAggregatedClient(commands, CognitoIdentity);\n\nexports.CognitoIdentity = CognitoIdentity;\nexports.CognitoIdentityClient = CognitoIdentityClient;\nexports.CognitoIdentityServiceException = CognitoIdentityServiceException;\nexports.CognitoIdentityServiceException$ = CognitoIdentityServiceException$;\nexports.Credentials$ = Credentials$;\nexports.ExternalServiceException = ExternalServiceException;\nexports.ExternalServiceException$ = ExternalServiceException$;\nexports.GetCredentialsForIdentity$ = GetCredentialsForIdentity$;\nexports.GetCredentialsForIdentityCommand = GetCredentialsForIdentityCommand;\nexports.GetCredentialsForIdentityInput$ = GetCredentialsForIdentityInput$;\nexports.GetCredentialsForIdentityResponse$ = GetCredentialsForIdentityResponse$;\nexports.GetId$ = GetId$;\nexports.GetIdCommand = GetIdCommand;\nexports.GetIdInput$ = GetIdInput$;\nexports.GetIdResponse$ = GetIdResponse$;\nexports.InternalErrorException = InternalErrorException;\nexports.InternalErrorException$ = InternalErrorException$;\nexports.InvalidIdentityPoolConfigurationException = InvalidIdentityPoolConfigurationException;\nexports.InvalidIdentityPoolConfigurationException$ = InvalidIdentityPoolConfigurationException$;\nexports.InvalidParameterException = InvalidParameterException;\nexports.InvalidParameterException$ = InvalidParameterException$;\nexports.LimitExceededException = LimitExceededException;\nexports.LimitExceededException$ = LimitExceededException$;\nexports.NotAuthorizedException = NotAuthorizedException;\nexports.NotAuthorizedException$ = NotAuthorizedException$;\nexports.ResourceConflictException = ResourceConflictException;\nexports.ResourceConflictException$ = ResourceConflictException$;\nexports.ResourceNotFoundException = ResourceNotFoundException;\nexports.ResourceNotFoundException$ = ResourceNotFoundException$;\nexports.TooManyRequestsException = TooManyRequestsException;\nexports.TooManyRequestsException$ = TooManyRequestsException$;\nexports.errorTypeRegistries = errorTypeRegistries;\n" | ||
| ], | ||
| "mappings": ";uXAAA,IAAQ,wBAAsB,gCAAiC,GAAmC,kCAAgC,8BAA4B,sCAAoC,0CAAwC,0BAAwB,2BAAyB,sBAAoB,uBAAqB,mBAAiB,sCAC7U,gBAAc,0CAAwC,iCAA+B,+BACrF,oBAAmB,oBAAkB,oBAAkB,cAAY,mCAAiC,6BAA2B,oCAAkC,+BAA6B,UAAQ,eAAa,gCACnN,QAAS,QAGjB,IAAQ,6BAA2B,aAAY,yCAAuC,8CAA4C,8BAA4B,mCAAiC,8BACvL,yBAAuB,iBAAe,kBAAgB,2BAAyB,yBAAuB,4BACtG,YAAU,wCAAsC,mCAAiC,iCACjF,sBAAoB,kCAAgC,mCAAiC,sBAAoB,yBACzG,eAAc,+BACd,4BAA0B,qBAAmB,8CAC7C,UAAQ,YAAU,YAAU,cAAY,8BACxC,mBAAiB,0BACjB,6BACA,gBAEF,GAAyD,MAAO,EAAQ,EAAS,KAC5E,CACH,UAAW,GAAiB,CAAO,EAAE,UACrC,OAAQ,MAAM,EAAkB,EAAO,MAAM,EAAE,IAAM,IAAM,CACvD,MAAU,MAAM,yDAAyD,IAC1E,CACP,GAEJ,SAAS,EAAgC,CAAC,EAAgB,CACtD,MAAO,CACH,SAAU,iBACV,kBAAmB,CACf,KAAM,mBACN,OAAQ,EAAe,MAC3B,EACA,oBAAqB,CAAC,EAAQ,KAAa,CACvC,kBAAmB,CACf,SACA,SACJ,CACJ,EACJ,EAEJ,SAAS,CAAmC,CAAC,EAAgB,CACzD,MAAO,CACH,SAAU,mBACd,EAEJ,IAAM,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,EAAM,CAAE,CAChE,CAEA,IAAM,GAAW,CACb,mCACA,cACJ,EACA,MAAM,WAAwB,CAAsB,CACpD,CACA,GAAuB,GAAU,EAAe,EAGhD,IAAQ,GAAwB,EAOhC,IAAQ,GAAmC,EAI3C,IAAQ,GAAe", | ||
| "debugId": "1AC9590980C96BC264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "3632F76A7296448164756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mcp/add.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { readFile, stat, writeFile } from \"node:fs/promises\"\nimport { Effect, Option } from \"effect\"\nimport { applyEdits, modify } from \"jsonc-parser\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.add,\n Effect.fn(\"cli.mcp.add\")(function* (input) {\n const url = Option.getOrUndefined(input.url)\n const headers = Option.getOrUndefined(input.header)\n const environment = Option.getOrUndefined(input.env)\n // The CLI framework strands `--` operands on the root command, so read the local server command\n // straight from argv after `--`. This also lets the command carry its own flags (e.g. `npx -y`).\n const dash = process.argv.indexOf(\"--\")\n const command = dash === -1 ? [...input.command] : process.argv.slice(dash + 1)\n\n const hasCommand = command.length > 0\n if (url && hasCommand)\n return yield* Effect.fail(new Error(\"Provide either --url <url> or a command after --, not both\"))\n if (!url && !hasCommand) return yield* Effect.fail(new Error(\"Provide either --url <url> or a command after --\"))\n if (url && !URL.canParse(url)) return yield* Effect.fail(new Error(`Invalid URL: ${url}`))\n if (url && environment) return yield* Effect.fail(new Error(\"--env is only valid for local MCP servers\"))\n if (hasCommand && headers) return yield* Effect.fail(new Error(\"--header is only valid for remote MCP servers\"))\n\n const server = url\n ? { type: \"remote\" as const, url, ...(headers ? { headers } : {}) }\n : { type: \"local\" as const, command, ...(environment ? { environment } : {}) }\n\n const global = yield* Global.Service\n const configPath = yield* Effect.promise(() => resolveConfigPath(input.global ? global.config : process.cwd()))\n yield* Effect.promise(() => write(configPath, input.name, server))\n process.stdout.write(`MCP server \"${input.name}\" added to ${configPath}` + EOL)\n }),\n)\n\nexport async function resolveConfigPath(directory: string) {\n const candidates = [\n path.join(directory, \"opencode.json\"),\n path.join(directory, \"opencode.jsonc\"),\n path.join(directory, \".opencode\", \"opencode.json\"),\n path.join(directory, \".opencode\", \"opencode.jsonc\"),\n ]\n for (const candidate of candidates) {\n if (\n await stat(candidate).then(\n (info) => info.isFile(),\n () => false,\n )\n )\n return candidate\n }\n return candidates[0]\n}\n\nasync function write(configPath: string, name: string, server: unknown) {\n const text = await readFile(configPath, \"utf8\").catch((error) => {\n if (typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\") return \"{}\"\n throw error\n })\n const edits = modify(text, [\"mcp\", \"servers\", name], server, {\n formattingOptions: { tabSize: 2, insertSpaces: true },\n })\n await writeFile(configPath, applyEdits(text, edits))\n}\n" | ||
| ], | ||
| "mappings": ";wOAAA,cAAS,WACT,oBACA,mBAAS,UAAU,eAAM,oBAOzB,IAAe,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,IAC/B,EAAO,GAAG,aAAa,EAAE,SAAU,CAAC,EAAO,CACzC,IAAM,EAAM,EAAO,eAAe,EAAM,GAAG,EACrC,EAAU,EAAO,eAAe,EAAM,MAAM,EAC5C,EAAc,EAAO,eAAe,EAAM,GAAG,EAG7C,EAAO,QAAQ,KAAK,QAAQ,IAAI,EAChC,EAAU,IAAS,GAAK,CAAC,GAAG,EAAM,OAAO,EAAI,QAAQ,KAAK,MAAM,EAAO,CAAC,EAExE,EAAa,EAAQ,OAAS,EACpC,GAAI,GAAO,EACT,OAAO,MAAO,EAAO,KAAS,MAAM,4DAA4D,CAAC,EAC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AU,MAAO,KACtG,MAAM,EACP,EACK,EAAQ,EAAO,EAAM,CAAC,MAAO,UAAW,CAAI,EAAG,EAAQ,CAC3D,kBAAmB,CAAE,QAAS,EAAG,aAAc,EAAK,CACtD,CAAC,EACD,MAAM,EAAU,EAAY,EAAW,EAAM,CAAK,CAAC", | ||
| "debugId": "B91ACBD0552699CF64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/image/photon-wasm.bun.ts", "../core/src/image/photon.ts"], | ||
| "sourcesContent": [ | ||
| "// @ts-ignore Bun embeds static file imports when compiling the CLI.\nimport photonWasm from \"@silvia-odwyer/photon-node/photon_rs_bg.wasm\" with { type: \"file\" }\n\nexport default photonWasm\n", | ||
| "import photonWasm from \"#photon-wasm\"\nimport { Effect } from \"effect\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport { FileSystem } from \"../filesystem.js\"\nimport { DecodeError, ResizerUnavailableError, SizeError, type Limits } from \"../image.js\"\n\nconst JPEG_QUALITIES = [80, 85, 70, 55, 40]\n\nexport const make = Effect.gen(function* () {\n const loadPhoton = yield* Effect.cached(\n // A runtime without a photon wasm artifact (#photon-wasm resolves to the\n // empty string on workerd) has no resizer, by declaration: fail typed\n // before touching URLs or module loading. The path resolution and import\n // for runtimes that DO have an artifact stay inside the guard too — a\n // throw outside it (workerd's undefined import.meta.url was one) is a\n // defect that escapes the ResizerUnavailableError handling and turns any\n // image-bearing prompt into a 500 instead of degrading to passthrough.\n photonWasm === \"\"\n ? Effect.fail(new ResizerUnavailableError())\n : Effect.tryPromise({\n try: async () => {\n ;(\n globalThis as typeof globalThis & { __OPENCODE_PHOTON_WASM_PATH?: string }\n ).__OPENCODE_PHOTON_WASM_PATH = path.isAbsolute(photonWasm)\n ? photonWasm\n : fileURLToPath(new URL(photonWasm, import.meta.url))\n return await import(\"@silvia-odwyer/photon-node\")\n },\n catch: () => new ResizerUnavailableError(),\n }),\n )\n return Effect.fn(\"Image.Photon.normalize\")(function* (\n resource: string,\n content: FileSystem.Content & { readonly encoding: \"base64\" },\n limits: Readonly<Limits>,\n ) {\n const photon = yield* loadPhoton\n const decoded = yield* Effect.try({\n try: () => photon.PhotonImage.new_from_byteslice(Buffer.from(content.content, \"base64\")),\n catch: () => new DecodeError({ resource }),\n })\n try {\n const width = decoded.get_width()\n const height = decoded.get_height()\n const bytes = Buffer.byteLength(content.content, \"utf-8\")\n if (width <= limits.maxWidth && height <= limits.maxHeight && bytes <= limits.maxBase64Bytes) return content\n if (!limits.autoResize)\n return yield* new SizeError({\n resource,\n width,\n height,\n bytes,\n maxWidth: limits.maxWidth,\n maxHeight: limits.maxHeight,\n maxBytes: limits.maxBase64Bytes,\n })\n const scale = Math.min(1, limits.maxWidth / width, limits.maxHeight / height)\n const sizes = Array.from({ length: 32 }).reduce<Array<{ width: number; height: number }>>((acc) => {\n const previous = acc.at(-1) ?? {\n width: Math.max(1, Math.round(width * scale)),\n height: Math.max(1, Math.round(height * scale)),\n }\n const next =\n acc.length === 0\n ? previous\n : {\n width: previous.width === 1 ? 1 : Math.max(1, Math.floor(previous.width * 0.75)),\n height: previous.height === 1 ? 1 : Math.max(1, Math.floor(previous.height * 0.75)),\n }\n return acc.some((item) => item.width === next.width && item.height === next.height) ? acc : [...acc, next]\n }, [])\n for (const size of sizes) {\n const resized = photon.resize(decoded, size.width, size.height, photon.SamplingFilter.Lanczos3)\n try {\n const encoders: Array<readonly [mime: string, encode: () => Uint8Array]> = [\n [\"image/png\", () => resized.get_bytes()],\n ...JPEG_QUALITIES.map((quality) => [\"image/jpeg\", () => resized.get_bytes_jpeg(quality)] as const),\n ]\n for (const [mime, encode] of encoders) {\n const candidate = encode()\n // Base64 uses four bytes per three input bytes, including padding.\n if (Math.ceil(candidate.length / 3) * 4 <= limits.maxBase64Bytes)\n return {\n ...content,\n content: Buffer.from(candidate).toString(\"base64\"),\n encoding: \"base64\" as const,\n mime,\n }\n }\n } finally {\n resized.free()\n }\n }\n return yield* new SizeError({\n resource,\n width,\n height,\n bytes,\n maxWidth: limits.maxWidth,\n maxHeight: limits.maxHeight,\n maxBytes: limits.maxBase64Bytes,\n })\n } finally {\n decoded.free()\n }\n })\n})\n" | ||
| ], | ||
| "mappings": ";qsCAGA,IAAe,ICDf,oBACA,wBAAS,YAIT,IAAM,EAAiB,CAAC,GAAI,GAAI,GAAI,GAAI,EAAE,EAE7B,EAAO,EAAO,IAAI,SAAU,EAAG,CAC1C,IAAM,EAAa,MAAO,EAAO,OAQ/B,IAAe,GACX,EAAO,KAAK,IAAI,CAAyB,EACzC,EAAO,WAAW,CAChB,IAAK,UAED,WACA,4BAA8B,EAAK,WAAW,CAAU,EACtD,EACA,EAAc,IAAI,IAAI,EAAY,YAAY,GAAG,CAAC,EAC/C,KAAa,2CAEtB,MAAO,IAAM,IAAI,CACnB,CAAC,CACP,EACA,OAAO,EAAO,GAAG,wBAAwB,EAAE,SAAU,CACnD,EACA,EACA,EACA,CACA,IAAM,EAAS,MAAO,EAChB,EAAU,MAAO,EAAO,IAAI,CAChC,IAAK,IAAM,EAAO,YAAY,mBAAmB,OAAO,KAAK,EAAQ,QAAS,QAAQ,CAAC,EACvF,MAAO,IAAM,IAAI,EAAY,CAAE,UAAS,CAAC,CAC3C,CAAC,EACD,GAAI,CACF,IAAM,EAAQ,EAAQ,UAAU,EAC1B,EAAS,EAAQ,WAAW,EAC5B,EAAQ,OAAO,WAAW,EAAQ,QAAS,OAAO,EACxD,GAAI,GAAS,EAAO,UAAY,GAAU,EAAO,WAAa,GAAS,EAAO,eAAgB,OAAO,EACrG,GAAI,CAAC,EAAO,WACV,OAAO,MAAO,IAAI,EAAU,CAC1B,WACA,QACA,SACA,QACA,SAAU,EAAO,SACjB,UAAW,EAAO,UAClB,SAAU,EAAO,cACnB,CAAC,EACH,IAAM,EAAQ,KAAK,IAAI,EAAG,EAAO,SAAW,EAAO,EAAO,UAAY,CAAM,EACtE,EAAQ,MAAM,KAAK,CAAE,OAAQ,EAA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5D283A41052664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/run.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nexport default Runtime.handler(Commands.commands.run, (input) =>\n Effect.gen(function* () {\n const { runNonInteractive } = yield* Effect.promise(() => import(\"../../run/run\"))\n const separator = process.argv.indexOf(\"--\", 2)\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n yield* Effect.promise(() =>\n runNonInteractive({\n server,\n message: [...input.message, ...(separator === -1 ? [] : process.argv.slice(separator + 1))],\n continue: input.continue,\n session: Option.getOrUndefined(input.session),\n fork: input.fork,\n model: Option.getOrUndefined(input.model),\n agent: Option.getOrUndefined(input.agent),\n format: input.format,\n file: [...input.file],\n title: Option.getOrUndefined(input.title),\n thinking: input.thinking,\n auto: input.auto || input.yolo || input.dangerouslySkipPermissions,\n }),\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";0jCAKA,IAAe,IAAQ,QAAQ,EAAS,SAAS,IAAK,CAAC,IACrD,EAAO,IAAI,SAAU,EAAG,CACtB,IAAQ,qBAAsB,MAAO,EAAO,QAAQ,IAAa,wCAAgB,EAC3E,EAAY,QAAQ,KAAK,QAAQ,KAAM,CAAC,EACxC,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EACD,MAAO,EAAO,QAAQ,IACpB,EAAkB,CAChB,SACA,QAAS,CAAC,GAAG,EAAM,QAAS,GAAI,IAAc,GAAK,CAAC,EAAI,QAAQ,KAAK,MAAM,EAAY,CAAC,CAAE,EAC1F,SAAU,EAAM,SAChB,QAAS,EAAO,eAAe,EAAM,OAAO,EAC5C,KAAM,EAAM,KACZ,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,OAAQ,EAAM,OACd,KAAM,CAAC,GAAG,EAAM,IAAI,EACpB,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,SAAU,EAAM,SAChB,KAAM,EAAM,MAAQ,EAAM,MAAQ,EAAM,0BAC1C,CAAC,CACH,EACD,CACH", | ||
| "debugId": "943C1B8F13DE53A164756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/createCredentialChain.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.68/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentity.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.68/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/resolveLogins.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.68/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentityPool.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.68/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/IndexedDbStorage.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.68/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/InMemoryStorage.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.68/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/localStorage.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromCognitoIdentity.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromCognitoIdentityPool.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromContainerMetadata.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromEnv.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromIni.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromInstanceMetadata.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromLoginCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-node@3.972.80/node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js", "../../node_modules/.bun/@aws-sdk+credential-provider-node@3.972.80/node_modules/@aws-sdk/credential-provider-node/dist-es/remoteProvider.js", "../../node_modules/.bun/@aws-sdk+credential-provider-node@3.972.80/node_modules/@aws-sdk/credential-provider-node/dist-es/runtime/memoize-chain.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromNodeProviderChain.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromProcess.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromSSO.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromTemporaryCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromTemporaryCredentials.base.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromTokenFile.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromWebToken.js"], | ||
| "sourcesContent": [ | ||
| "import { ProviderError } from \"@smithy/core/config\";\nexport const createCredentialChain = (...credentialProviders) => {\n let expireAfter = -1;\n const baseFunction = async (awsIdentityProperties) => {\n const credentials = await propertyProviderChain(...credentialProviders)(awsIdentityProperties);\n if (!credentials.expiration && expireAfter !== -1) {\n credentials.expiration = new Date(Date.now() + expireAfter);\n }\n return credentials;\n };\n const withOptions = Object.assign(baseFunction, {\n expireAfter(milliseconds) {\n if (milliseconds < 5 * 60_000) {\n throw new Error(\"@aws-sdk/credential-providers - createCredentialChain(...).expireAfter(ms) may not be called with a duration lower than five minutes.\");\n }\n expireAfter = milliseconds;\n return withOptions;\n },\n });\n return withOptions;\n};\nexport const propertyProviderChain = (...providers) => async (awsIdentityProperties) => {\n if (providers.length === 0) {\n throw new ProviderError(\"No providers in chain\", { tryNextLink: false });\n }\n let lastProviderError;\n for (const provider of providers) {\n try {\n return await provider(awsIdentityProperties);\n }\n catch (err) {\n lastProviderError = err;\n if (err?.tryNextLink) {\n continue;\n }\n throw err;\n }\n }\n throw lastProviderError;\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { resolveLogins } from \"./resolveLogins\";\nexport function fromCognitoIdentity(parameters) {\n return async (awsIdentityProperties) => {\n parameters.logger?.debug(\"@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity\");\n const { GetCredentialsForIdentityCommand, CognitoIdentityClient } = await import(\"./loadCognitoIdentity.js\");\n const fromConfigs = (property) => parameters.clientConfig?.[property] ??\n parameters.parentClientConfig?.[property] ??\n awsIdentityProperties?.callerClientConfig?.[property];\n const { Credentials: { AccessKeyId = throwOnMissingAccessKeyId(parameters.logger), Expiration, SecretKey = throwOnMissingSecretKey(parameters.logger), SessionToken, } = throwOnMissingCredentials(parameters.logger), } = await (parameters.client ??\n new CognitoIdentityClient(Object.assign({}, parameters.clientConfig ?? {}, {\n region: fromConfigs(\"region\"),\n profile: fromConfigs(\"profile\"),\n userAgentAppId: fromConfigs(\"userAgentAppId\"),\n }))).send(new GetCredentialsForIdentityCommand({\n CustomRoleArn: parameters.customRoleArn,\n IdentityId: parameters.identityId,\n Logins: parameters.logins ? await resolveLogins(parameters.logins) : undefined,\n }));\n return {\n identityId: parameters.identityId,\n accessKeyId: AccessKeyId,\n secretAccessKey: SecretKey,\n sessionToken: SessionToken,\n expiration: Expiration,\n };\n };\n}\nfunction throwOnMissingAccessKeyId(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no access key ID\", { logger });\n}\nfunction throwOnMissingCredentials(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no credentials\", { logger });\n}\nfunction throwOnMissingSecretKey(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no secret key\", { logger });\n}\n", | ||
| "export function resolveLogins(logins) {\n return Promise.all(Object.keys(logins).reduce((arr, name) => {\n const tokenOrProvider = logins[name];\n if (typeof tokenOrProvider === \"string\") {\n arr.push([name, tokenOrProvider]);\n }\n else {\n arr.push(tokenOrProvider().then((token) => [name, token]));\n }\n return arr;\n }, [])).then((resolvedPairs) => resolvedPairs.reduce((logins, [key, value]) => {\n logins[key] = value;\n return logins;\n }, {}));\n}\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { fromCognitoIdentity } from \"./fromCognitoIdentity\";\nimport { localStorage } from \"./localStorage\";\nimport { resolveLogins } from \"./resolveLogins\";\nexport function fromCognitoIdentityPool({ accountId, cache = localStorage(), client, clientConfig, customRoleArn, identityPoolId, logins, userIdentifier = !logins || Object.keys(logins).length === 0 ? \"ANONYMOUS\" : undefined, logger, parentClientConfig, }) {\n logger?.debug(\"@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity\");\n const cacheKey = userIdentifier\n ? `aws:cognito-identity-credentials:${identityPoolId}:${userIdentifier}`\n : undefined;\n let provider = async (awsIdentityProperties) => {\n const { GetIdCommand, CognitoIdentityClient } = await import(\"./loadCognitoIdentity.js\");\n const fromConfigs = (property) => clientConfig?.[property] ??\n parentClientConfig?.[property] ??\n awsIdentityProperties?.callerClientConfig?.[property];\n const _client = client ??\n new CognitoIdentityClient(Object.assign({}, clientConfig ?? {}, {\n region: fromConfigs(\"region\"),\n profile: fromConfigs(\"profile\"),\n userAgentAppId: fromConfigs(\"userAgentAppId\"),\n }));\n let identityId = (cacheKey && (await cache.getItem(cacheKey)));\n if (!identityId) {\n const { IdentityId = throwOnMissingId(logger) } = await _client.send(new GetIdCommand({\n AccountId: accountId,\n IdentityPoolId: identityPoolId,\n Logins: logins ? await resolveLogins(logins) : undefined,\n }));\n identityId = IdentityId;\n if (cacheKey) {\n Promise.resolve(cache.setItem(cacheKey, identityId)).catch(() => { });\n }\n }\n provider = fromCognitoIdentity({\n client: _client,\n customRoleArn,\n logins,\n identityId,\n });\n return provider(awsIdentityProperties);\n };\n return (awsIdentityProperties) => provider(awsIdentityProperties).catch(async (err) => {\n if (cacheKey) {\n Promise.resolve(cache.removeItem(cacheKey)).catch(() => { });\n }\n throw err;\n });\n}\nfunction throwOnMissingId(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no identity ID\", { logger });\n}\n", | ||
| "const STORE_NAME = \"IdentityIds\";\nexport class IndexedDbStorage {\n dbName;\n constructor(dbName = \"aws:cognito-identity-ids\") {\n this.dbName = dbName;\n }\n getItem(key) {\n return this.withObjectStore(\"readonly\", (store) => {\n const req = store.get(key);\n return new Promise((resolve) => {\n req.onerror = () => resolve(null);\n req.onsuccess = () => resolve(req.result ? req.result.value : null);\n });\n }).catch(() => null);\n }\n removeItem(key) {\n return this.withObjectStore(\"readwrite\", (store) => {\n const req = store.delete(key);\n return new Promise((resolve, reject) => {\n req.onerror = () => reject(req.error);\n req.onsuccess = () => resolve();\n });\n });\n }\n setItem(id, value) {\n return this.withObjectStore(\"readwrite\", (store) => {\n const req = store.put({ id, value });\n return new Promise((resolve, reject) => {\n req.onerror = () => reject(req.error);\n req.onsuccess = () => resolve();\n });\n });\n }\n getDb() {\n const openDbRequest = self.indexedDB.open(this.dbName, 1);\n return new Promise((resolve, reject) => {\n openDbRequest.onsuccess = () => {\n resolve(openDbRequest.result);\n };\n openDbRequest.onerror = () => {\n reject(openDbRequest.error);\n };\n openDbRequest.onblocked = () => {\n reject(new Error(\"Unable to access DB\"));\n };\n openDbRequest.onupgradeneeded = () => {\n const db = openDbRequest.result;\n db.onerror = () => {\n reject(new Error(\"Failed to create object store\"));\n };\n db.createObjectStore(STORE_NAME, { keyPath: \"id\" });\n };\n });\n }\n withObjectStore(mode, action) {\n return this.getDb().then((db) => {\n const tx = db.transaction(STORE_NAME, mode);\n tx.oncomplete = () => db.close();\n return new Promise((resolve, reject) => {\n tx.onerror = () => reject(tx.error);\n resolve(action(tx.objectStore(STORE_NAME)));\n }).catch((err) => {\n db.close();\n throw err;\n });\n });\n }\n}\n", | ||
| "export class InMemoryStorage {\n store;\n constructor(store = {}) {\n this.store = store;\n }\n getItem(key) {\n if (key in this.store) {\n return this.store[key];\n }\n return null;\n }\n removeItem(key) {\n delete this.store[key];\n }\n setItem(key, value) {\n this.store[key] = value;\n }\n}\n", | ||
| "import { IndexedDbStorage } from \"./IndexedDbStorage\";\nimport { InMemoryStorage } from \"./InMemoryStorage\";\nconst inMemoryStorage = new InMemoryStorage();\nexport function localStorage() {\n if (typeof self === \"object\" && self.indexedDB) {\n return new IndexedDbStorage();\n }\n if (typeof window === \"object\" && window.localStorage) {\n return window.localStorage;\n }\n return inMemoryStorage;\n}\n", | ||
| "import { fromCognitoIdentity as _fromCognitoIdentity } from \"@aws-sdk/credential-provider-cognito-identity\";\nexport const fromCognitoIdentity = (options) => _fromCognitoIdentity({\n ...options,\n});\n", | ||
| "import { fromCognitoIdentityPool as _fromCognitoIdentityPool } from \"@aws-sdk/credential-provider-cognito-identity\";\nexport const fromCognitoIdentityPool = (options) => _fromCognitoIdentityPool({\n ...options,\n});\n", | ||
| "import { fromContainerMetadata as _fromContainerMetadata } from \"@smithy/credential-provider-imds\";\nexport const fromContainerMetadata = (init) => {\n init?.logger?.debug(\"@smithy/credential-provider-imds\", \"fromContainerMetadata\");\n return _fromContainerMetadata(init);\n};\n", | ||
| "import { fromEnv as _fromEnv } from \"@aws-sdk/credential-provider-env\";\nexport const fromEnv = (init) => _fromEnv(init);\n", | ||
| "import { fromIni as _fromIni } from \"@aws-sdk/credential-provider-ini\";\nexport const fromIni = (init = {}) => _fromIni({\n ...init,\n});\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { fromInstanceMetadata as _fromInstanceMetadata } from \"@smithy/credential-provider-imds\";\nexport const fromInstanceMetadata = (init) => {\n init?.logger?.debug(\"@smithy/credential-provider-imds\", \"fromInstanceMetadata\");\n return async () => _fromInstanceMetadata(init)().then((creds) => setCredentialFeature(creds, \"CREDENTIALS_IMDS\", \"0\"));\n};\n", | ||
| "import { fromLoginCredentials as _fromLoginCredentials, } from \"@aws-sdk/credential-provider-login\";\nexport const fromLoginCredentials = (init) => _fromLoginCredentials({\n ...init,\n});\n", | ||
| "import { ENV_KEY, ENV_SECRET, fromEnv } from \"@aws-sdk/credential-provider-env\";\nimport { CredentialsProviderError, ENV_PROFILE } from \"@smithy/core/config\";\nimport { remoteProvider } from \"./remoteProvider\";\nimport { memoizeChain } from \"./runtime/memoize-chain\";\nlet multipleCredentialSourceWarningEmitted = false;\nexport const defaultProvider = (init = {}) => memoizeChain([\n async () => {\n const profile = init.profile ?? process.env[ENV_PROFILE];\n if (profile) {\n const envStaticCredentialsAreSet = process.env[ENV_KEY] && process.env[ENV_SECRET];\n if (envStaticCredentialsAreSet) {\n if (!multipleCredentialSourceWarningEmitted) {\n const warnFn = init.logger?.warn && init.logger?.constructor?.name !== \"NoOpLogger\"\n ? init.logger.warn.bind(init.logger)\n : console.warn;\n warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:\n Multiple credential sources detected: \n Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set.\n This SDK will proceed with the AWS_PROFILE value.\n \n However, a future version may change this behavior to prefer the ENV static credentials.\n Please ensure that your environment only sets either the AWS_PROFILE or the\n AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair.\n`);\n multipleCredentialSourceWarningEmitted = true;\n }\n }\n throw new CredentialsProviderError(\"AWS_PROFILE is set, skipping fromEnv provider.\", {\n logger: init.logger,\n tryNextLink: true,\n });\n }\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromEnv\");\n return fromEnv(init)();\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromSSO\");\n const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init;\n if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {\n throw new CredentialsProviderError(\"Skipping SSO provider in default chain (inputs do not include SSO fields).\", { logger: init.logger });\n }\n const { fromSSO } = await import(\"@aws-sdk/credential-provider-sso\");\n return fromSSO(init)(awsIdentityProperties);\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromIni\");\n const { fromIni } = await import(\"@aws-sdk/credential-provider-ini\");\n return fromIni(init)(awsIdentityProperties);\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromProcess\");\n const { fromProcess } = await import(\"@aws-sdk/credential-provider-process\");\n return fromProcess(init)(awsIdentityProperties);\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile\");\n const { fromTokenFile } = await import(\"@aws-sdk/credential-provider-web-identity\");\n return fromTokenFile(init)(awsIdentityProperties);\n },\n async () => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::remoteProvider\");\n return (await remoteProvider(init))();\n },\n async () => {\n throw new CredentialsProviderError(\"Could not load credentials from any providers\", {\n tryNextLink: false,\n logger: init.logger,\n });\n },\n], credentialsTreatedAsExpired);\nexport const credentialsWillNeedRefresh = (credentials) => credentials?.expiration !== undefined;\nexport const credentialsTreatedAsExpired = (credentials) => credentials?.expiration !== undefined && credentials.expiration.getTime() - Date.now() < 300000;\n", | ||
| "import { chain, CredentialsProviderError } from \"@smithy/core/config\";\nexport const ENV_IMDS_DISABLED = \"AWS_EC2_METADATA_DISABLED\";\nexport const remoteProvider = async (init) => {\n const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await import(\"@smithy/credential-provider-imds\");\n if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata\");\n const { fromHttp } = await import(\"@aws-sdk/credential-provider-http\");\n return chain(fromHttp(init), fromContainerMetadata(init));\n }\n if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== \"false\") {\n return async () => {\n throw new CredentialsProviderError(\"EC2 Instance Metadata Service access disabled\", { logger: init.logger });\n };\n }\n init.logger?.debug(\"@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata\");\n return fromInstanceMetadata(init);\n};\n", | ||
| "export function memoizeChain(providers, treatAsExpired) {\n const chain = internalCreateChain(providers);\n let activeLock;\n let passiveLock;\n let credentials;\n let forceRefreshLock;\n const provider = async (options) => {\n if (options?.forceRefresh) {\n if (!forceRefreshLock) {\n forceRefreshLock = chain(options)\n .then((c) => {\n credentials = c;\n })\n .finally(() => {\n forceRefreshLock = undefined;\n });\n }\n await forceRefreshLock;\n return credentials;\n }\n if (credentials?.expiration) {\n if (credentials?.expiration?.getTime() < Date.now()) {\n credentials = undefined;\n }\n }\n if (activeLock) {\n await activeLock;\n }\n else if (!credentials || treatAsExpired?.(credentials)) {\n if (credentials) {\n if (!passiveLock) {\n passiveLock = chain(options)\n .then((c) => {\n credentials = c;\n })\n .finally(() => {\n passiveLock = undefined;\n });\n }\n }\n else {\n activeLock = chain(options)\n .then((c) => {\n credentials = c;\n })\n .finally(() => {\n activeLock = undefined;\n });\n return provider(options);\n }\n }\n return credentials;\n };\n return provider;\n}\nexport const internalCreateChain = (providers) => async (awsIdentityProperties) => {\n let lastProviderError;\n for (const provider of providers) {\n try {\n return await provider(awsIdentityProperties);\n }\n catch (err) {\n lastProviderError = err;\n if (err?.tryNextLink) {\n continue;\n }\n throw err;\n }\n }\n throw lastProviderError;\n};\n", | ||
| "import { defaultProvider } from \"@aws-sdk/credential-provider-node\";\nexport const fromNodeProviderChain = (init = {}) => defaultProvider({\n ...init,\n});\n", | ||
| "import { fromProcess as _fromProcess } from \"@aws-sdk/credential-provider-process\";\nexport const fromProcess = (init) => _fromProcess(init);\n", | ||
| "import { fromSSO as _fromSSO } from \"@aws-sdk/credential-provider-sso\";\nexport const fromSSO = (init = {}) => {\n return _fromSSO({ ...init });\n};\n", | ||
| "import { loadConfig, NODE_REGION_CONFIG_FILE_OPTIONS } from \"@smithy/core/config\";\nimport { fromNodeProviderChain } from \"./fromNodeProviderChain\";\nimport { fromTemporaryCredentials as fromTemporaryCredentialsBase } from \"./fromTemporaryCredentials.base\";\nexport const fromTemporaryCredentials = (options) => {\n return fromTemporaryCredentialsBase(options, fromNodeProviderChain, async ({ profile = process.env.AWS_PROFILE }) => loadConfig({\n environmentVariableSelector: (env) => env.AWS_REGION,\n configFileSelector: (profileData) => {\n return profileData.region;\n },\n default: () => undefined,\n }, { ...NODE_REGION_CONFIG_FILE_OPTIONS, profile })());\n};\n", | ||
| "import { normalizeProvider } from \"@smithy/core\";\nimport { CredentialsProviderError } from \"@smithy/core/config\";\nconst ASSUME_ROLE_DEFAULT_REGION = \"us-east-1\";\nexport const fromTemporaryCredentials = (options, credentialDefaultProvider, regionProvider) => {\n let stsClient;\n return async (awsIdentityProperties = {}) => {\n const { callerClientConfig } = awsIdentityProperties;\n const profile = options.clientConfig?.profile ?? callerClientConfig?.profile;\n const logger = options.logger ?? callerClientConfig?.logger;\n logger?.debug(\"@aws-sdk/credential-providers - fromTemporaryCredentials (STS)\");\n const params = { ...options.params, RoleSessionName: options.params.RoleSessionName ?? \"aws-sdk-js-\" + Date.now() };\n if (params?.SerialNumber) {\n if (!options.mfaCodeProvider) {\n throw new CredentialsProviderError(`Temporary credential requires multi-factor authentication, but no MFA code callback was provided.`, {\n tryNextLink: false,\n logger,\n });\n }\n params.TokenCode = await options.mfaCodeProvider(params?.SerialNumber);\n }\n const { AssumeRoleCommand, STSClient } = await import(\"./loadSts.js\");\n if (!stsClient) {\n const defaultCredentialsOrError = typeof credentialDefaultProvider === \"function\" ? credentialDefaultProvider() : undefined;\n const credentialSources = [\n options.masterCredentials,\n options.clientConfig?.credentials,\n void callerClientConfig?.credentials,\n callerClientConfig?.credentialDefaultProvider?.(),\n defaultCredentialsOrError,\n ];\n let credentialSource = \"STS client default credentials\";\n if (credentialSources[0]) {\n credentialSource = \"options.masterCredentials\";\n }\n else if (credentialSources[1]) {\n credentialSource = \"options.clientConfig.credentials\";\n }\n else if (credentialSources[2]) {\n credentialSource = \"caller client's credentials\";\n throw new Error(\"fromTemporaryCredentials recursion in callerClientConfig.credentials\");\n }\n else if (credentialSources[3]) {\n credentialSource = \"caller client's credentialDefaultProvider\";\n }\n else if (credentialSources[4]) {\n credentialSource = \"AWS SDK default credentials\";\n }\n const regionSources = [\n options.clientConfig?.region,\n callerClientConfig?.region,\n await regionProvider?.({\n profile,\n }),\n ASSUME_ROLE_DEFAULT_REGION,\n ];\n let regionSource = \"default partition's default region\";\n if (regionSources[0]) {\n regionSource = \"options.clientConfig.region\";\n }\n else if (regionSources[1]) {\n regionSource = \"caller client's region\";\n }\n else if (regionSources[2]) {\n regionSource = \"file or env region\";\n }\n const requestHandlerSources = [\n filterRequestHandler(options.clientConfig?.requestHandler),\n filterRequestHandler(callerClientConfig?.requestHandler),\n ];\n let requestHandlerSource = \"STS default requestHandler\";\n if (requestHandlerSources[0]) {\n requestHandlerSource = \"options.clientConfig.requestHandler\";\n }\n else if (requestHandlerSources[1]) {\n requestHandlerSource = \"caller client's requestHandler\";\n }\n logger?.debug?.(`@aws-sdk/credential-providers - fromTemporaryCredentials STS client init with ` +\n `${regionSource}=${await normalizeProvider(coalesce(regionSources))()}, ${credentialSource}, ${requestHandlerSource}.`);\n stsClient = new STSClient({\n userAgentAppId: callerClientConfig?.userAgentAppId,\n ...options.clientConfig,\n credentials: coalesce(credentialSources),\n logger,\n profile,\n region: coalesce(regionSources),\n requestHandler: coalesce(requestHandlerSources),\n });\n }\n if (options.clientPlugins) {\n for (const plugin of options.clientPlugins) {\n stsClient.middlewareStack.use(plugin);\n }\n }\n const { Credentials } = await stsClient.send(new AssumeRoleCommand(params));\n if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {\n throw new CredentialsProviderError(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`, {\n logger,\n });\n }\n return {\n accessKeyId: Credentials.AccessKeyId,\n secretAccessKey: Credentials.SecretAccessKey,\n sessionToken: Credentials.SessionToken,\n expiration: Credentials.Expiration,\n credentialScope: Credentials.CredentialScope,\n };\n };\n};\nconst filterRequestHandler = (requestHandler) => {\n return requestHandler?.metadata?.handlerProtocol === \"h2\" ? undefined : requestHandler;\n};\nconst coalesce = (args) => {\n for (const item of args) {\n if (item !== undefined) {\n return item;\n }\n }\n};\n", | ||
| "import { fromTokenFile as _fromTokenFile } from \"@aws-sdk/credential-provider-web-identity\";\nexport const fromTokenFile = (init = {}) => _fromTokenFile({\n ...init,\n});\n", | ||
| "import { fromWebToken as _fromWebToken } from \"@aws-sdk/credential-provider-web-identity\";\nexport const fromWebToken = (init) => _fromWebToken({\n ...init,\n});\n" | ||
| ], | ||
| "mappings": ";+rBAAA,eACa,GAAwB,IAAI,IAAwB,CAC7D,IAAI,EAAc,GAQZ,EAAc,OAAO,OAPN,MAAO,IAA0B,CAClD,IAAM,EAAc,MAAM,GAAsB,GAAG,CAAmB,EAAE,CAAqB,EAC7F,GAAI,CAAC,EAAY,YAAc,IAAgB,GAC3C,EAAY,WAAa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AC,IAAS,GAAc,IAC7C,CACP,CAAC", | ||
| "debugId": "350EB8F1C121A5CF64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/oauth/page.ts"], | ||
| "sourcesContent": [ | ||
| "// Branded HTML pages for local OAuth callback servers.\n//\n// These are served by the loopback HTTP servers that finish an OAuth exchange\n// (MCP, Codex/ChatGPT, xAI, Snowflake, DigitalOcean, ...). The functions return\n// a fully self-contained HTML string with no external assets, so they work\n// offline and drop into any transport (`res.end(...)`, Effect `response.end`,\n// etc.).\n//\n// The visual language mirrors the OpenCode app: the design tokens are a curated\n// subset of the OC-2 semantic tokens in `packages/ui/src/styles/theme.css`, and\n// the wordmark is the same geometry as `packages/ui/src/components/logo.tsx`.\n// Keep this file in sync with those sources when the brand changes.\n\nexport interface CallbackPageOptions {\n /** Friendly integration name shown as a subtitle, e.g. \"xAI\", \"Snowflake\", \"MCP\". */\n provider?: string\n /** Attempt to close the window shortly after success. Defaults to true. */\n autoClose?: boolean\n}\n\nexport function success(options?: CallbackPageOptions) {\n const provider = options?.provider\n return renderDocument({\n title: \"Authorization successful\",\n body: renderCard({\n status: \"success\",\n headline: \"Authorization successful\",\n message: provider ? `OpenCode is now connected to ${escapeHtml(provider)}.` : \"OpenCode is now authorized.\",\n footnote: \"You can close this window.\",\n }),\n script: options?.autoClose === false ? undefined : AUTO_CLOSE_SCRIPT,\n })\n}\n\nexport function error(detail: string, options?: CallbackPageOptions) {\n const provider = options?.provider\n return renderDocument({\n title: \"Authorization failed\",\n body: renderCard({\n status: \"error\",\n headline: \"Authorization failed\",\n message: provider\n ? `OpenCode couldn't finish connecting to ${escapeHtml(provider)}.`\n : \"OpenCode couldn't complete authorization.\",\n detail,\n footnote: \"Close this window and try again from OpenCode.\",\n }),\n })\n}\n\nexport interface BootstrapOptions {\n /** Same-origin path the in-browser script POSTs the parsed callback to. */\n tokenPath: string\n provider?: string\n}\n\n// For flows where the credential arrives in the URL fragment (implicit grant),\n// the browser must relay it back to the loopback server. This renders a pending\n// page whose script reads the fragment, POSTs it to `tokenPath`, then resolves\n// to the success or error state in place.\nexport function bootstrap(options: BootstrapOptions) {\n return renderDocument({\n title: \"Finishing sign-in\",\n body: renderCard({\n status: \"pending\",\n headline: \"Finishing sign-in\",\n message: options.provider\n ? `Completing your ${escapeHtml(options.provider)} authorization.`\n : \"Completing authorization.\",\n footnote: \"You can close this window once sign-in finishes.\",\n }),\n script: bootstrapScript(options),\n })\n}\n\nexport * as OauthCallbackPage from \"./page.js\"\n\ntype Status = \"pending\" | \"success\" | \"error\"\n\nfunction renderCard(input: { status: Status; headline: string; message: string; detail?: string; footnote: string }) {\n const detail = input.detail?.trim()\n return `<main class=\"card\" id=\"oc-card\" data-status=\"${input.status}\" role=\"status\" aria-live=\"polite\">\n <div class=\"brand\">${WORDMARK}</div>\n <div class=\"status\" aria-hidden=\"true\">\n <span class=\"icon icon-pending\">${ICON_SPINNER}</span>\n <span class=\"icon icon-success\">${ICON_CHECK}</span>\n <span class=\"icon icon-error\">${ICON_CROSS}</span>\n </div>\n <h1 class=\"headline\" id=\"oc-headline\">${escapeHtml(input.headline)}</h1>\n <p class=\"message\" id=\"oc-message\">${input.message}</p>\n <pre class=\"detail\" id=\"oc-detail\"${detail ? \"\" : \" hidden\"}>${detail ? escapeHtml(detail) : \"\"}</pre>\n <p class=\"footnote\" id=\"oc-footnote\">${escapeHtml(input.footnote)}</p>\n </main>`\n}\n\nfunction renderDocument(input: { title: string; body: string; script?: string }) {\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <meta name=\"robots\" content=\"noindex\" />\n <title>${escapeHtml(input.title)} · OpenCode</title>\n <style>${STYLES}</style>\n </head>\n <body>\n ${input.body}${input.script ? `\\n <script>${input.script}</script>` : \"\"}\n </body>\n</html>`\n}\n\nconst AUTO_CLOSE_SCRIPT = `setTimeout(function(){try{window.close()}catch(e){}},2500)`\n\nfunction bootstrapScript(options: BootstrapOptions) {\n return `var PROVIDER=${scriptString(options.provider ?? \"\")};\nvar TOKEN_URL=new URL(${scriptString(options.tokenPath)},window.location.origin).href;\n(function(){\n var card=document.getElementById(\"oc-card\"),headline=document.getElementById(\"oc-headline\"),message=document.getElementById(\"oc-message\"),detail=document.getElementById(\"oc-detail\"),footnote=document.getElementById(\"oc-footnote\");\n function fail(text){card.dataset.status=\"error\";headline.textContent=\"Authorization failed\";message.textContent=PROVIDER?(\"OpenCode couldn't finish connecting to \"+PROVIDER+\".\"):\"OpenCode couldn't complete authorization.\";if(text){detail.textContent=text;detail.hidden=false}footnote.textContent=\"Close this window and try again from OpenCode.\"}\n function ok(){card.dataset.status=\"success\";headline.textContent=\"Authorization successful\";message.textContent=PROVIDER?(\"OpenCode is now connected to \"+PROVIDER+\".\"):\"OpenCode is now authorized.\";detail.hidden=true;footnote.textContent=\"You can close this window.\";setTimeout(function(){try{window.close()}catch(e){}},2500)}\n try{\n var hash=new URLSearchParams((window.location.hash||\"\").slice(1));\n var search=new URLSearchParams(window.location.search||\"\");\n var err=hash.get(\"error\")||search.get(\"error\");\n var errDescription=hash.get(\"error_description\")||search.get(\"error_description\");\n var body=err?{error:err,error_description:errDescription||\"\"}:{access_token:hash.get(\"access_token\")||\"\",expires_in:hash.get(\"expires_in\")||\"0\",state:hash.get(\"state\")||\"\"};\n fetch(TOKEN_URL,{method:\"POST\",headers:{\"Content-Type\":\"application/json\"},body:JSON.stringify(body)}).then(function(res){\n if(!res.ok)return res.text().catch(function(){return\"\"}).then(function(t){throw new Error(t||(\"callback failed (\"+res.status+\")\"))});\n if(err){fail(errDescription||err);return}\n ok();\n }).catch(function(e){fail(String(e&&e.message?e.message:e))});\n }catch(e){fail(String(e&&e.message?e.message:e))}\n})()`\n}\n\nfunction scriptString(value: string) {\n return JSON.stringify(value).replaceAll(\"<\", \"\\\\u003c\")\n}\n\nfunction escapeHtml(value: string) {\n return value\n .replaceAll(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\")\n .replaceAll('\"', \""\")\n .replaceAll(\"'\", \"'\")\n}\n\n// Curated subset of OC-2 tokens (packages/ui/src/styles/theme.css). Default is\n// light; dark applies via prefers-color-scheme. The [data-theme] selectors let a\n// host force a scheme without changing the default.\nconst LIGHT_VARS = `\n --oc-bg: #f8f8f8;\n --oc-card: #fcfcfc;\n --oc-text-strong: #171717;\n --oc-text-base: #6f6f6f;\n --oc-text-weak: #8f8f8f;\n --oc-border-weak: #e5e5e5;\n --oc-icon-strong: #171717;\n --oc-icon-base: #8f8f8f;\n --oc-icon-weak: #dbdbdb;\n --oc-success: #2dba26;\n --oc-error: #ed4831;\n --oc-detail-bg: #fff8f6;\n --oc-detail-border: #fdc3b7;\n --oc-shadow: 0 16px 48px -6px rgba(0,0,0,.10), 0 6px 12px -2px rgba(0,0,0,.05), 0 1px 2px rgba(0,0,0,.06);`\n\nconst DARK_VARS = `\n --oc-bg: #101010;\n --oc-card: #161616;\n --oc-text-strong: rgba(255,255,255,.936);\n --oc-text-base: rgba(255,255,255,.618);\n --oc-text-weak: rgba(255,255,255,.422);\n --oc-border-weak: #282828;\n --oc-icon-strong: #ededed;\n --oc-icon-base: #7e7e7e;\n --oc-icon-weak: #343434;\n --oc-success: #12c905;\n --oc-error: #fc533a;\n --oc-detail-bg: #28110c;\n --oc-detail-border: #6a1206;\n --oc-shadow: 0 16px 48px -6px rgba(0,0,0,.55), 0 6px 12px -2px rgba(0,0,0,.35), 0 1px 2px rgba(0,0,0,.4);`\n\nconst STYLES = `\n :root { color-scheme: light dark;${LIGHT_VARS}\n --oc-font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n --oc-font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace;\n }\n @media (prefers-color-scheme: dark) { :root:not([data-theme=\"light\"]) {${DARK_VARS} } }\n :root[data-theme=\"dark\"] {${DARK_VARS} }\n :root[data-theme=\"light\"] {${LIGHT_VARS} }\n\n * { box-sizing: border-box; }\n html, body { margin: 0; height: 100%; }\n body {\n min-height: 100vh;\n display: grid;\n place-items: center;\n padding: 24px;\n background: var(--oc-bg);\n color: var(--oc-text-base);\n font-family: var(--oc-font-sans);\n line-height: 1.5;\n -webkit-font-smoothing: antialiased;\n text-rendering: optimizeLegibility;\n }\n .card {\n width: min(100%, 28rem);\n padding: 2.25rem 2rem 1.75rem;\n background: var(--oc-card);\n border: 1px solid var(--oc-border-weak);\n border-radius: 14px;\n box-shadow: var(--oc-shadow);\n text-align: center;\n }\n .brand { display: flex; justify-content: center; margin-bottom: 1.75rem; }\n .brand svg { height: 19px; width: auto; }\n .status { display: flex; justify-content: center; margin-bottom: 1.125rem; }\n .icon { display: none; line-height: 0; }\n .icon svg { display: block; }\n .card[data-status=\"pending\"] .icon-pending,\n .card[data-status=\"success\"] .icon-success,\n .card[data-status=\"error\"] .icon-error { display: block; }\n .icon-success { color: var(--oc-success); }\n .icon-error { color: var(--oc-error); }\n .icon-pending { color: var(--oc-text-weak); }\n .headline { margin: 0; font-size: 1.1875rem; font-weight: 500; line-height: 1.3; letter-spacing: -0.012em; color: var(--oc-text-strong); }\n .message { margin: 0.5rem 0 0; font-size: 0.9375rem; color: var(--oc-text-base); }\n .detail {\n margin: 1.25rem 0 0;\n padding: 0.75rem 0.875rem;\n text-align: left;\n font-family: var(--oc-font-mono);\n font-size: 0.8125rem;\n line-height: 1.55;\n color: var(--oc-text-strong);\n background: var(--oc-detail-bg);\n border: 1px solid var(--oc-detail-border);\n border-radius: 8px;\n white-space: pre-wrap;\n word-break: break-word;\n max-height: 9.5rem;\n overflow: auto;\n }\n .detail[hidden] { display: none; }\n .footnote { margin: 1.5rem 0 0; font-size: 0.8125rem; color: var(--oc-text-weak); }\n .spinner { animation: oc-spin 0.8s linear infinite; transform-origin: center; }\n @keyframes oc-spin { to { transform: rotate(360deg); } }\n @media (prefers-reduced-motion: reduce) { .spinner { animation: none; } }\n`\n\n// OpenCode wordmark — same path geometry as packages/ui/src/components/logo.tsx (Logo).\nconst WORDMARK = `<svg class=\"wordmark\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 234 42\" fill=\"none\" aria-label=\"OpenCode\" role=\"img\">\n <path d=\"M18 30H6V18H18V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M18 12H6V30H18V12ZM24 36H0V6H24V36Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M48 30H36V18H48V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M36 30H48V12H36V30ZM54 36H36V42H30V6H54V36Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M84 24V30H66V24H84Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M84 24H66V30H84V36H60V6H84V24ZM66 18H78V12H66V18Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M108 36H96V18H108V36Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M108 12H96V36H90V6H108V12ZM114 36H108V12H114V36Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M144 30H126V18H144V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M144 12H126V30H144V36H120V6H144V12Z\" fill=\"var(--oc-icon-strong)\" />\n <path d=\"M168 30H156V18H168V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M168 12H156V30H168V12ZM174 36H150V6H174V36Z\" fill=\"var(--oc-icon-strong)\" />\n <path d=\"M198 30H186V18H198V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M198 12H186V30H198V12ZM204 36H180V6H198V0H204V36Z\" fill=\"var(--oc-icon-strong)\" />\n <path d=\"M234 24V30H216V24H234Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M216 12V18H228V12H216ZM234 24H216V30H234V36H210V6H234V24Z\" fill=\"var(--oc-icon-strong)\" />\n </svg>`\n\nconst ICON_CHECK = `<svg viewBox=\"0 0 24 24\" width=\"30\" height=\"30\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"m8.5 12.5 2.4 2.4 4.6-5.4\" /></svg>`\n\nconst ICON_CROSS = `<svg viewBox=\"0 0 24 24\" width=\"30\" height=\"30\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"m9 9 6 6m0-6-6 6\" /></svg>`\n\nconst ICON_SPINNER = `<svg class=\"spinner\" viewBox=\"0 0 24 24\" width=\"30\" height=\"30\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\"><circle cx=\"12\" cy=\"12\" r=\"9\" opacity=\"0.2\" /><path d=\"M21 12a9 9 0 0 0-9-9\" /></svg>`\n" | ||
| ], | ||
| "mappings": ";sIAoBO,SAAS,CAAO,CAAC,EAA+B,CACrD,IAAM,EAAW,GAAS,SAC1B,OAAO,EAAe,CACpB,MAAO,2BACP,KAAM,EAAW,CACf,OAAQ,UACR,SAAU,2BACV,QAAS,EAAW,gCAAgC,EAAW,CAAQ,KAAO,8BAC9E,SAAU,4BACZ,CAAC,EACD,OAAQ,GAAS,YAAc,GAAQ,OAAY,CACrD,CAAC,EAGI,SAAS,CAAK,CAAC,EAAgB,EAA+B,CACnE,IAAM,EAAW,GAAS,SAC1B,OAAO,EAAe,CACpB,MAAO,uBACP,KAAM,EAAW,CACf,OAAQ,QACR,SAAU,uBACV,QAAS,EACL,0CAA0C,EAAW,CAAQ,KAC7D,4CACJ,SACA,SAAU,gDACZ,CAAC,CACH,CAAC,EAaI,SAAS,CAAS,CAAC,EAA2B,CACnD,OAAO,EAAe,CACpB,MAAO,oBACP,KAAM,EAAW,CACf,OAAQ,UACR,SAAU,oBACV,QAAS,EAAQ,SACb,mBAAmB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AA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,+GAgBZ,EAAS;AAAA,qCACsB;AAAA;AAAA;AAAA;AAAA,2EAIsC;AAAA,8BAC7C;AAAA,+BACC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA8DzB,EAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,cAmBX,EAAa,iOAEb,EAAa,wNAEb,EAAe", | ||
| "debugId": "2AD721C63ABD55CB64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/upgrade.ts"], | ||
| "sourcesContent": [ | ||
| "import { intro, log, outro, spinner } from \"@clack/prompts\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { Updater } from \"../../services/updater\"\nimport { handlePromptErrors } from \"../../ui/prompt\"\nimport { OPENCODE_VERSION } from \"../../version\"\n\nexport default Runtime.handler(\n Commands.commands.upgrade,\n Effect.fn(\"cli.upgrade\")(function* (input) {\n intro(\"Upgrade\")\n const updater = yield* Updater.Service\n const method = Option.getOrUndefined(input.method) ?? (yield* updater.method())\n if (!method)\n return yield* Effect.fail(\n new Error(\"Could not detect the installation method. Pass --method to choose how to upgrade OpenCode.\"),\n )\n\n log.info(`Using method: ${method}`)\n const target = Option.getOrUndefined(input.target) ?? (yield* updater.latest())\n const version = target.trim().replace(/^v/, \"\")\n if (version === OPENCODE_VERSION) {\n log.warn(`OpenCode upgrade skipped: ${version} is already installed`)\n outro(\"Done\")\n return\n }\n\n log.info(`From ${OPENCODE_VERSION} → ${version}`)\n const progress = spinner()\n progress.start(\"Upgrading...\")\n yield* updater.upgrade(method, target).pipe(\n Effect.tap(() => Effect.sync(() => progress.stop(\"Upgrade complete\"))),\n Effect.tapCause(() => Effect.sync(() => progress.stop(\"Upgrade failed\", 1))),\n )\n outro(\"Done\")\n }, handlePromptErrors),\n)\n" | ||
| ], | ||
| "mappings": ";63BAQA,IAAe,IAAQ,QACrB,EAAS,SAAS,QAClB,EAAO,GAAG,aAAa,EAAE,SAAU,CAAC,EAAO,CACzC,EAAM,SAAS,EACf,IAAM,EAAU,MAAO,EAAQ,QACzB,EAAS,EAAO,eAAe,EAAM,MAAM,IAAM,MAAO,EAAQ,OAAO,GAC7E,GAAI,CAAC,EACH,OAAO,MAAO,EAAO,KACf,MAAM,4FAA4F,CACxG,EAEF,EAAI,KAAK,iBAAiB,GAAQ,EAClC,IAAM,EAAS,EAAO,eAAe,EAAM,MAAM,IAAM,MAAO,EAAQ,OAAO,GACvE,EAAU,EAAO,KAAK,EAAE,QAAQ,KAAM,EAAE,EAC9C,GAAI,IAAY,EAAkB,CAChC,EAAI,KAAK,6BAA6B,wBAA8B,EACpE,EAAM,MAAM,EACZ,OAGF,EAAI,KAAK,QAAQ,YAAsB,GAAS,EAChD,IAAM,EAAW,EAAQ,EACzB,EAAS,MAAM,cAAc,EAC7B,MAAO,EAAQ,QAAQ,EAAQ,CAAM,EAAE,KACrC,EAAO,IAAI,IAAM,EAAO,KAAK,IAAM,EAAS,KAAK,kBAAkB,CAAC,CAAC,EACrE,EAAO,SAAS,IAAM,EAAO,KAAK,IAAM,EAAS,KAAK,iBAAkB,CAAC,CAAC,CAAC,CAC7E,EACA,EAAM,MAAM,GACX,CAAkB,CACvB", | ||
| "debugId": "4A52518C01AAB59364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "D163C1E25A2FBCCB64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/debug/config.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.debug.commands.config,\n Effect.fn(\"cli.debug.config\")(function* () {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const entries = yield* Effect.promise(() => client.config.get({ location: { directory: process.cwd() } }))\n process.stdout.write(JSON.stringify(entries, null, 2) + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";08BAAA,cAAS,WAQT,IAAe,IAAQ,QACrB,EAAS,SAAS,MAAM,SAAS,OACjC,EAAO,GAAG,kBAAkB,EAAE,SAAU,EAAG,CACzC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAU,MAAO,EAAO,QAAQ,IAAM,EAAO,OAAO,IAAI,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,EACzG,QAAQ,OAAO,MAAM,KAAK,UAAU,EAAS,KAAM,CAAC,EAAI,CAAG,EAC5D,CACH", | ||
| "debugId": "6ADBEDCED046BB0964756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-login@3.972.76/node_modules/@aws-sdk/credential-provider-login/dist-es/fromLoginCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-login@3.972.76/node_modules/@aws-sdk/credential-provider-login/dist-es/LoginCredentialsFetcher.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError, getProfileName, parseKnownFiles } from \"@smithy/core/config\";\nimport { LoginCredentialsFetcher } from \"./LoginCredentialsFetcher\";\nexport const fromLoginCredentials = (init) => async ({ callerClientConfig } = {}) => {\n init?.logger?.debug?.(\"@aws-sdk/credential-providers - fromLoginCredentials\");\n const profiles = await parseKnownFiles(init || {});\n const profileName = getProfileName({\n profile: init?.profile ?? callerClientConfig?.profile,\n });\n const profile = profiles[profileName];\n if (!profile?.login_session) {\n throw new CredentialsProviderError(`Profile ${profileName} does not contain login_session.`, {\n tryNextLink: true,\n logger: init?.logger,\n });\n }\n const fetcher = new LoginCredentialsFetcher(profile, init, callerClientConfig);\n const credentials = await fetcher.loadCredentials();\n return setCredentialFeature(credentials, \"CREDENTIALS_LOGIN\", \"AD\");\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { HttpRequest } from \"@smithy/core/protocols\";\nimport { createHash, createPrivateKey, createPublicKey, sign } from \"node:crypto\";\nimport { promises as fs } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nexport class LoginCredentialsFetcher {\n profileData;\n init;\n callerClientConfig;\n static REFRESH_THRESHOLD = 5 * 60 * 1000;\n constructor(profileData, init, callerClientConfig) {\n this.profileData = profileData;\n this.init = init;\n this.callerClientConfig = callerClientConfig;\n }\n async loadCredentials() {\n const token = await this.loadToken();\n if (!token) {\n throw new CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`, { tryNextLink: false, logger: this.logger });\n }\n const accessToken = token.accessToken;\n const now = Date.now();\n const expiryTime = new Date(accessToken.expiresAt).getTime();\n const timeUntilExpiry = expiryTime - now;\n if (timeUntilExpiry <= LoginCredentialsFetcher.REFRESH_THRESHOLD) {\n return this.refresh(token);\n }\n return this.toCredentials(token.accessToken);\n }\n get logger() {\n return this.init?.logger;\n }\n get loginSession() {\n return this.profileData.login_session;\n }\n toCredentials(token) {\n return {\n accessKeyId: token.accessKeyId,\n secretAccessKey: token.secretAccessKey,\n sessionToken: token.sessionToken,\n accountId: token.accountId,\n expiration: new Date(token.expiresAt),\n };\n }\n async refresh(token) {\n const diskToken = await this.loadToken().catch(() => token);\n const now = Date.now();\n const diskExpiry = new Date(diskToken.accessToken.expiresAt).getTime();\n const tokenExpiry = new Date(token.accessToken.expiresAt).getTime();\n const freshToken = diskExpiry <= now && tokenExpiry > now ? token : diskToken;\n const freshExpiry = new Date(freshToken.accessToken.expiresAt).getTime();\n if (freshExpiry - Date.now() > LoginCredentialsFetcher.REFRESH_THRESHOLD) {\n return this.toCredentials(freshToken.accessToken);\n }\n const { SigninClient, CreateOAuth2TokenCommand } = await import(\"@aws-sdk/nested-clients/signin\");\n const { logger, userAgentAppId } = this.callerClientConfig ?? {};\n const isH2 = (requestHandler) => {\n return requestHandler?.metadata?.handlerProtocol === \"h2\";\n };\n const requestHandler = isH2(this.callerClientConfig?.requestHandler)\n ? undefined\n : this.callerClientConfig?.requestHandler;\n const region = this.profileData.region ?? (await this.callerClientConfig?.region?.()) ?? process.env.AWS_REGION;\n const client = new SigninClient({\n credentials: {\n accessKeyId: \"\",\n secretAccessKey: \"\",\n },\n region,\n requestHandler,\n logger,\n userAgentAppId,\n ...this.init?.clientConfig,\n });\n this.createDPoPInterceptor(client.middlewareStack);\n const commandInput = {\n tokenInput: {\n clientId: freshToken.clientId,\n refreshToken: freshToken.refreshToken,\n grantType: \"refresh_token\",\n },\n };\n try {\n const response = await client.send(new CreateOAuth2TokenCommand(commandInput));\n const { accessKeyId, secretAccessKey, sessionToken } = response.tokenOutput?.accessToken ?? {};\n const { refreshToken, expiresIn } = response.tokenOutput ?? {};\n if (!accessKeyId || !secretAccessKey || !sessionToken || !refreshToken) {\n throw new CredentialsProviderError(\"Token refresh response missing required fields\", {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n const expiresInMs = (expiresIn ?? 900) * 1000;\n const expiration = new Date(Date.now() + expiresInMs);\n const updatedToken = {\n ...freshToken,\n accessToken: {\n ...freshToken.accessToken,\n accessKeyId,\n secretAccessKey,\n sessionToken,\n expiresAt: expiration.toISOString(),\n },\n refreshToken,\n };\n await this.saveToken(updatedToken);\n return this.toCredentials(updatedToken.accessToken);\n }\n catch (error) {\n if (error.name === \"AccessDeniedException\") {\n const errorType = error.error;\n let message;\n switch (errorType) {\n case \"TOKEN_EXPIRED\":\n message = \"Your session has expired. Please reauthenticate.\";\n break;\n case \"USER_CREDENTIALS_CHANGED\":\n message =\n \"Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.\";\n break;\n case \"INSUFFICIENT_PERMISSIONS\":\n message =\n \"Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.\";\n break;\n default:\n message = `Failed to refresh token: ${String(error)}. Please re-authenticate using \\`aws login\\``;\n }\n throw new CredentialsProviderError(message, {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n const tokenExpiry = new Date(freshToken.accessToken.expiresAt).getTime();\n if (tokenExpiry > Date.now()) {\n this.logger?.warn?.(`Failed to refresh token: ${String(error)}. Using existing token until expiry.`);\n return this.toCredentials(freshToken.accessToken);\n }\n throw new CredentialsProviderError(`Failed to refresh token: ${String(error)}. Please re-authenticate using aws login`, { logger: this.logger });\n }\n }\n async loadToken() {\n const tokenFilePath = this.getTokenFilePath();\n try {\n const tokenData = await fs.readFile(tokenFilePath, \"utf8\");\n const token = JSON.parse(tokenData);\n const missingFields = [\"accessToken\", \"clientId\", \"refreshToken\", \"dpopKey\"].filter((k) => !token[k]);\n if (!token.accessToken?.accountId) {\n missingFields.push(\"accountId\");\n }\n if (missingFields.length > 0) {\n throw new CredentialsProviderError(`Token validation failed, missing fields: ${missingFields.join(\", \")}`, {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n return token;\n }\n catch (error) {\n throw new CredentialsProviderError(`Failed to load token from ${tokenFilePath}: ${String(error)}`, {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n }\n async saveToken(token) {\n const tokenFilePath = this.getTokenFilePath();\n const directory = dirname(tokenFilePath);\n try {\n await fs.mkdir(directory, { recursive: true });\n }\n catch (error) {\n }\n await fs.writeFile(tokenFilePath, JSON.stringify(token, null, 2), \"utf8\");\n }\n getTokenFilePath() {\n const directory = process.env.AWS_LOGIN_CACHE_DIRECTORY ?? join(homedir(), \".aws\", \"login\", \"cache\");\n const loginSessionBytes = Buffer.from(this.loginSession, \"utf8\");\n const loginSessionSha256 = createHash(\"sha256\").update(loginSessionBytes).digest(\"hex\");\n return join(directory, `${loginSessionSha256}.json`);\n }\n derToRawSignature(derSignature) {\n let offset = 2;\n if (derSignature[offset] !== 0x02) {\n throw new Error(\"Invalid DER signature\");\n }\n offset++;\n const rLength = derSignature[offset++];\n let r = derSignature.subarray(offset, offset + rLength);\n offset += rLength;\n if (derSignature[offset] !== 0x02) {\n throw new Error(\"Invalid DER signature\");\n }\n offset++;\n const sLength = derSignature[offset++];\n let s = derSignature.subarray(offset, offset + sLength);\n r = r[0] === 0x00 ? r.subarray(1) : r;\n s = s[0] === 0x00 ? s.subarray(1) : s;\n const rPadded = Buffer.concat([Buffer.alloc(32 - r.length), r]);\n const sPadded = Buffer.concat([Buffer.alloc(32 - s.length), s]);\n return Buffer.concat([rPadded, sPadded]);\n }\n createDPoPInterceptor(middlewareStack) {\n middlewareStack.add((next) => async (args) => {\n if (HttpRequest.isInstance(args.request)) {\n const request = args.request;\n const actualEndpoint = `${request.protocol}//${request.hostname}${request.port ? `:${request.port}` : \"\"}${request.path}`;\n const dpop = await this.generateDpop(request.method, actualEndpoint);\n request.headers = {\n ...request.headers,\n DPoP: dpop,\n };\n }\n return next(args);\n }, {\n step: \"finalizeRequest\",\n name: \"dpopInterceptor\",\n override: true,\n });\n }\n async generateDpop(method = \"POST\", endpoint) {\n const token = await this.loadToken();\n try {\n const privateKey = createPrivateKey({\n key: token.dpopKey,\n format: \"pem\",\n type: \"sec1\",\n });\n const publicKey = createPublicKey(privateKey);\n const publicDer = publicKey.export({ format: \"der\", type: \"spki\" });\n let pointStart = -1;\n for (let i = 0; i < publicDer.length; i++) {\n if (publicDer[i] === 0x04) {\n pointStart = i;\n break;\n }\n }\n const x = publicDer.slice(pointStart + 1, pointStart + 33);\n const y = publicDer.slice(pointStart + 33, pointStart + 65);\n const header = {\n alg: \"ES256\",\n typ: \"dpop+jwt\",\n jwk: {\n kty: \"EC\",\n crv: \"P-256\",\n x: x.toString(\"base64url\"),\n y: y.toString(\"base64url\"),\n },\n };\n const payload = {\n jti: crypto.randomUUID(),\n htm: method,\n htu: endpoint,\n iat: Math.floor(Date.now() / 1000),\n };\n const headerB64 = Buffer.from(JSON.stringify(header)).toString(\"base64url\");\n const payloadB64 = Buffer.from(JSON.stringify(payload)).toString(\"base64url\");\n const message = `${headerB64}.${payloadB64}`;\n const asn1Signature = sign(\"sha256\", Buffer.from(message), privateKey);\n const rawSignature = this.derToRawSignature(asn1Signature);\n const signatureB64 = rawSignature.toString(\"base64url\");\n return `${message}.${signatureB64}`;\n }\n catch (error) {\n throw new CredentialsProviderError(`Failed to generate Dpop proof: ${error instanceof Error ? error.message : String(error)}`, { logger: this.logger, tryNextLink: false });\n }\n }\n}\n" | ||
| ], | ||
| "mappings": ";gNAAA,eACA,WCDA,eACA,WACA,qBAAS,sBAAY,qBAAkB,UAAiB,eACxD,mBAAS,WACT,kBAAS,WACT,kBAAS,UAAS,aACX,MAAM,CAAwB,CACjC,YACA,KACA,yBACO,mBAAoB,OAC3B,WAAW,CAAC,EAAa,EAAM,EAAoB,CA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B,EAC3C,gBAAgB,EAClD,OAAO,uBAAqB,EAAa,oBAAqB,IAAI", | ||
| "debugId": "5F78631297DAFBAC64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mini.ts"], | ||
| "sourcesContent": [ | ||
| "import { Context, Effect, FileSystem, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\nimport { Config } from \"../../config\"\nimport { resolve } from \"@opencode-ai/tui/config\"\nimport { Global } from \"@opencode-ai/util/global\"\n\nexport default Runtime.handler(Commands.commands.mini, (input) =>\n Effect.gen(function* () {\n const { runMini, validateMiniTerminal } = yield* Effect.promise(() => import(\"../../mini\"))\n yield* Effect.promise(async () => validateMiniTerminal())\n const serverURL = Option.getOrUndefined(input.server)\n const server = yield* ServerConnection.resolve({\n server: serverURL,\n standalone: input.standalone,\n mismatch: \"replace\",\n })\n const config = yield* Config.Service\n const global = yield* Global.Service\n const resolved = resolve(yield* config.get(), { terminalSuspend: process.platform !== \"win32\" })\n const fileSystem = yield* FileSystem.FileSystem\n const runServicePromise = Effect.runPromiseWith(Context.make(FileSystem.FileSystem, fileSystem))\n const service = server.service\n yield* Effect.promise(() =>\n runMini({\n server: {\n endpoint: server.endpoint,\n reconnect: service ? (signal) => runServicePromise(service.reconnect(), { signal }) : undefined,\n },\n continue: input.continue,\n session: Option.getOrUndefined(input.session),\n fork: input.fork,\n model: Option.getOrUndefined(input.model),\n agent: Option.getOrUndefined(input.agent),\n prompt: Option.getOrUndefined(input.prompt),\n replay: Option.getOrUndefined(input.replay) ?? resolved.mini?.replay ?? true,\n replayLimit: Option.getOrUndefined(input.replayLimit) ?? resolved.mini?.replay_limit,\n demo: input.demo,\n tuiConfig: resolved,\n config: {\n update: (update) => runServicePromise(config.update(update)),\n },\n paths: { home: global.home, state: global.state, log: global.log },\n }),\n )\n }),\n)\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ugId": "74C4780C1AA7216B64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/status.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.status,\n Effect.fn(\"cli.service.status\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover({ ...options, version: undefined })\n process.stdout.write((found?.url ?? \"stopped\") + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";s5BAAA,cAAS,WAOT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,OACnC,EAAO,GAAG,oBAAoB,EAAE,SAAU,EAAG,CAC3C,IAAM,EAAU,MAAO,EAAc,QAAQ,EACvC,EAAQ,MAAO,EAAQ,SAAS,IAAK,EAAS,QAAS,MAAU,CAAC,EACxE,QAAQ,OAAO,OAAO,GAAO,KAAO,WAAa,CAAG,EACrD,CACH", | ||
| "debugId": "77A0BE79465C6EEA64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/auth/form.ts", "src/commands/handlers/auth/login.ts"], | ||
| "sourcesContent": [ | ||
| "import { confirm, log, multiselect, password, select, text, type Option } from \"@clack/prompts\"\nimport { Effect } from \"effect\"\nimport type { FormAnswer, FormField, FormFields } from \"@opencode-ai/client\"\nimport { openUrl, prompt, requireInteractive } from \"../../../ui/prompt\"\n\nconst skip = Symbol(\"skip\")\nconst custom = Symbol(\"custom\")\n\nexport const answerForm = Effect.fn(\"cli.auth.form\")(function* (fields: FormFields | undefined) {\n if (!fields) return undefined\n yield* requireInteractive(\"Authentication form input requires an interactive terminal\")\n const answer: FormAnswer = {}\n for (const field of fields) {\n if (!active(field, answer)) continue\n const value = yield* answerField(field)\n if (value !== undefined) answer[field.key] = value\n }\n return answer\n})\n\nexport const secret = Effect.fn(\"cli.auth.secret\")(function* (message: string) {\n yield* requireInteractive(\"API key input requires an interactive terminal\")\n return yield* prompt<string>(() => password({ message, validate: (value) => (!value ? \"Required\" : undefined) }))\n})\n\nconst answerField = Effect.fn(\"cli.auth.form.field\")(function* (field: FormField) {\n const message = field.title ?? field.key\n if (field.description) log.info(field.description)\n if (field.type === \"external\") {\n log.info(field.url)\n yield* openUrl(field.url)\n const acknowledged = yield* prompt<boolean>(() =>\n confirm({ message: message || \"Continue after completing this step?\", initialValue: true }),\n )\n if (!acknowledged) return yield* Effect.fail(new Error(`${message || \"External step\"} is required`))\n return true\n }\n if (field.type === \"boolean\") {\n if (field.required) return yield* prompt<boolean>(() => confirm({ message, initialValue: field.default ?? true }))\n const options: Array<Option<boolean | typeof skip>> = [\n { value: true, label: \"Yes\" },\n { value: false, label: \"No\" },\n { value: skip, label: \"Skip\" },\n ]\n const value = yield* prompt<boolean | typeof skip>(() =>\n select<boolean | typeof skip>({\n message,\n options,\n initialValue: field.default ?? skip,\n }),\n )\n if (value === skip) return undefined\n return value\n }\n if (field.type === \"multiselect\") {\n const options: Array<Option<string | typeof custom>> = field.options.map((option) => ({\n value: option.value,\n label: option.label,\n hint: option.description,\n }))\n if (field.custom) options.push({ value: custom, label: \"Type another value\" })\n const values = yield* prompt<Array<string | typeof custom>>(() =>\n multiselect<string | typeof custom>({\n message,\n options,\n initialValues: field.default,\n required: field.required || (field.minItems ?? 0) > 0,\n }),\n )\n const selected = values.filter((value): value is string => value !== custom)\n if (values.includes(custom)) {\n selected.push(yield* prompt<string>(() => text({ message: \"Enter value\", validate: required })))\n }\n if (field.minItems !== undefined && selected.length < field.minItems) {\n return yield* Effect.fail(new Error(`Select at least ${field.minItems}`))\n }\n if (field.maxItems !== undefined && selected.length > field.maxItems) {\n return yield* Effect.fail(new Error(`Select at most ${field.maxItems}`))\n }\n return selected\n }\n if (field.type === \"string\" && field.options) {\n const options: Array<Option<string | typeof custom | typeof skip>> = field.options.map((option) => ({\n value: option.value,\n label: option.label,\n hint: option.description,\n }))\n if (field.custom) options.push({ value: custom, label: \"Type your own answer\" })\n if (!field.required) options.push({ value: skip, label: \"Skip\" })\n const value = yield* prompt<string | typeof custom | typeof skip>(() =>\n select<string | typeof custom | typeof skip>({ message, options, initialValue: field.default }),\n )\n if (value === skip) return undefined\n if (value !== custom) return value\n }\n const value = yield* prompt<string>(() =>\n text({\n message,\n placeholder: field.type === \"string\" ? field.placeholder : undefined,\n initialValue: field.default === undefined ? undefined : String(field.default),\n validate: (input) => validateText(field, input),\n }),\n )\n if (!value && !field.required) return undefined\n if (field.type === \"string\") return value\n return Number(value)\n})\n\nfunction active(field: FormField, answer: FormAnswer) {\n if (field.type === \"external\" || !field.when) return true\n return field.when.every((condition) => {\n const value = answer[condition.key]\n if (value === undefined) return false\n const matches = Array.isArray(value) ? value.includes(String(condition.value)) : value === condition.value\n return condition.op === \"eq\" ? matches : !matches\n })\n}\n\nfunction required(value: string | undefined) {\n return value ? undefined : \"Required\"\n}\n\nfunction validateText(field: Exclude<FormField, { type: \"boolean\" | \"external\" | \"multiselect\" }>, value?: string) {\n if (!value) return field.required ? \"Required\" : undefined\n if (field.type === \"number\" || field.type === \"integer\") {\n const number = Number(value)\n if (!Number.isFinite(number)) return \"Expected a number\"\n if (field.type === \"integer\" && !Number.isInteger(number)) return \"Expected an integer\"\n if (typeof field.minimum === \"number\" && number < field.minimum) return `Must be at least ${field.minimum}`\n if (typeof field.maximum === \"number\" && number > field.maximum) return `Must be at most ${field.maximum}`\n return undefined\n }\n if (field.minLength !== undefined && value.length < field.minLength)\n return `Must be at least ${field.minLength} characters`\n if (field.maxLength !== undefined && value.length > field.maxLength)\n return `Must be at most ${field.maxLength} characters`\n if (field.pattern) {\n try {\n if (!new RegExp(field.pattern).test(value)) return \"Invalid format\"\n } catch {\n return \"Invalid format\"\n }\n }\n if (field.format === \"uri\" && !URL.canParse(value)) return \"Expected a URL\"\n if (field.format === \"email\" && !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value)) return \"Expected an email address\"\n if (field.format === \"date\") {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) return \"Expected a date\"\n const date = new Date(`${value}T00:00:00.000Z`)\n if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== value) return \"Expected a date\"\n }\n if (field.format === \"date-time\" && Number.isNaN(Date.parse(value))) return \"Expected a date and time\"\n return undefined\n}\n", | ||
| "import { autocomplete, intro, log, outro, select, spinner, text } from \"@clack/prompts\"\nimport { Effect, Option } from \"effect\"\nimport type { FormAnswer, IntegrationInfo, OpenCodeClient } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { handlePromptErrors, openUrl, prompt, requireInteractive } from \"../../../ui/prompt\"\nimport { answerForm, secret } from \"./form\"\nimport {\n createClient,\n connectMethods,\n loadIntegrations,\n location,\n request,\n resolveIntegration,\n resolveMethod,\n type ConnectMethod,\n} from \"./shared\"\n\nconst integrationPriority = new Map([\n [\"opencode\", 0],\n [\"opencode-go\", 1],\n [\"openai\", 2],\n [\"github-copilot\", 3],\n [\"google\", 4],\n [\"anthropic\", 5],\n [\"openrouter\", 6],\n [\"vercel\", 7],\n])\n\nexport default Runtime.handler(\n Commands.commands.auth.commands.login,\n Effect.fn(\"cli.auth.login\")((input) =>\n login({\n target: Option.getOrUndefined(input.target),\n method: Option.getOrUndefined(input.method),\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n }).pipe(handlePromptErrors),\n ),\n)\n\nconst login = Effect.fn(\"cli.auth.login.run\")(function* (input: {\n target?: string\n method?: string\n server?: string\n standalone: boolean\n}) {\n if (!input.target)\n yield* requireInteractive(\"Pass an integration ID or name when running without an interactive terminal\")\n intro(\"Connect an integration\")\n const client = yield* createClient({ server: input.server, standalone: input.standalone })\n const integration = yield* findIntegration(client, input.target)\n const methods = connectMethods(integration)\n if (methods.length === 0) yield* Effect.fail(new Error(`${integration.name} has no interactive login methods`))\n const method = yield* chooseMethod(methods, input.method)\n const answer = method.type === \"command\" ? undefined : yield* answerForm(method.form)\n yield* authenticate(client, integration, method, answer)\n outro(\"Done\")\n})\n\nconst findIntegration = Effect.fn(\"cli.auth.login.integration\")(function* (client: OpenCodeClient, target?: string) {\n if (target && URL.canParse(target)) {\n const protocol = new URL(target).protocol\n if (protocol === \"http:\" || protocol === \"https:\") {\n const progress = spinner()\n progress.start(\"Discovering authentication provider...\")\n yield* request((signal) => client.integration.wellknown.add({ url: target, location }, { signal })).pipe(\n Effect.tap(() => Effect.sync(() => progress.stop(\"Authentication provider discovered\"))),\n Effect.tapCause(() => Effect.sync(() => progress.stop(\"Discovery failed\", 1))),\n )\n }\n }\n const integrations = yield* loadIntegrations(client)\n if (target) return yield* resolveIntegration(integrations, target)\n const available = integrations\n .filter((integration) => connectMethods(integration).length > 0)\n .toSorted(\n (a, b) =>\n (integrationPriority.get(a.id) ?? integrationPriority.size) -\n (integrationPriority.get(b.id) ?? integrationPriority.size) ||\n a.name.localeCompare(b.name) ||\n a.id.localeCompare(b.id),\n )\n if (available.length === 0) return yield* Effect.fail(new Error(\"No authentication integrations are available\"))\n const id = yield* prompt<string>(() =>\n autocomplete({\n message: \"Select integration\",\n maxItems: 8,\n options: available.map((integration) => {\n const option = { value: integration.id, label: integration.name, hint: integration.id }\n if (integration.connections.length > 0) return { ...option, hint: \"connected\" }\n if (integration.id === \"opencode\") return { ...option, hint: \"recommended\" }\n return option\n }),\n }),\n )\n return yield* resolveIntegration(available, id)\n})\n\nconst chooseMethod = Effect.fn(\"cli.auth.login.method\")(function* (methods: ConnectMethod[], target?: string) {\n if (target) return yield* resolveMethod(methods, target)\n if (methods.length === 1) return methods[0]\n yield* requireInteractive(\"Pass --method when running without an interactive terminal\")\n const id = yield* prompt<string>(() =>\n select({\n message: \"Select login method\",\n options: methods.map((method) => {\n if (method.type === \"key\") return { value: \"key\", label: method.label ?? \"API key\" }\n return { value: method.id, label: method.label }\n }),\n }),\n )\n return yield* resolveMethod(methods, id)\n})\n\nconst authenticate = Effect.fn(\"cli.auth.login.authenticate\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: ConnectMethod,\n answer?: FormAnswer,\n) {\n if (method.type === \"key\") return yield* keyLogin(client, integration, method, answer)\n if (method.type === \"command\") return yield* commandLogin(client, integration, method)\n return yield* oauthLogin(client, integration, method, answer)\n})\n\nconst keyLogin = Effect.fn(\"cli.auth.login.key\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: Extract<ConnectMethod, { type: \"key\" }>,\n answer?: FormAnswer,\n) {\n const key = yield* secret(method.label ?? `Enter your ${integration.name} API key`)\n const progress = spinner()\n progress.start(\"Saving credential...\")\n yield* request((signal) =>\n client.integration.connect.key({ integrationID: integration.id, key, answer, location }, { signal }),\n ).pipe(\n Effect.tap(() => Effect.sync(() => progress.stop(`Connected to ${integration.name}`))),\n Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))),\n )\n})\n\nconst oauthLogin = Effect.fn(\"cli.auth.login.oauth\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: Extract<ConnectMethod, { type: \"oauth\" }>,\n answer?: FormAnswer,\n) {\n const progress = spinner()\n progress.start(\"Starting authorization...\")\n const started = yield* request((signal) =>\n client.integration.oauth.connect(\n { integrationID: integration.id, methodID: method.id, answer, location },\n { signal },\n ),\n ).pipe(Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))))\n const attempt = started.data\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.oauth.cancel(\n { integrationID: integration.id, attemptID: attempt.attemptID, location },\n { signal: AbortSignal.timeout(5_000) },\n ),\n ).pipe(Effect.ignore),\n )\n progress.stop(\"Authorization started\")\n log.info(attempt.instructions)\n log.info(attempt.url)\n if (process.stdin.isTTY && process.stdout.isTTY) yield* openUrl(attempt.url)\n\n if (attempt.mode === \"code\") {\n yield* requireInteractive(\"This login requires an interactive terminal to enter the authorization code\")\n const code = yield* prompt<string>(() =>\n text({ message: \"Paste the authorization code\", validate: (value) => (!value ? \"Required\" : undefined) }),\n )\n const completing = spinner()\n completing.start(\"Completing authorization...\")\n yield* request((signal) =>\n client.integration.oauth.complete(\n { integrationID: integration.id, attemptID: attempt.attemptID, code, location },\n { signal },\n ),\n ).pipe(\n Effect.tap(() => Effect.sync(() => completing.stop(`Connected to ${integration.name}`))),\n Effect.tapCause(() => Effect.sync(() => completing.stop(\"Authentication failed\", 1))),\n )\n return\n }\n\n const waiting = spinner()\n waiting.start(\"Waiting for authorization...\")\n const status = yield* waitForOAuth(client, integration.id, attempt.attemptID).pipe(\n Effect.tapCause(() => Effect.sync(() => waiting.stop(\"Authentication failed\", 1))),\n )\n if (status.status === \"complete\") {\n waiting.stop(`Connected to ${integration.name}`)\n return\n }\n waiting.stop(\"Authentication failed\", 1)\n if (status.status === \"failed\") yield* Effect.fail(new Error(status.message))\n yield* Effect.fail(new Error(\"Authorization expired\"))\n})\n\nconst commandLogin = Effect.fn(\"cli.auth.login.command\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: Extract<ConnectMethod, { type: \"command\" }>,\n) {\n const progress = spinner()\n progress.start(\"Starting authentication command...\")\n const started = yield* request((signal) =>\n client.integration.command.connect({ integrationID: integration.id, methodID: method.id, location }, { signal }),\n ).pipe(Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))))\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.command.cancel(\n {\n integrationID: integration.id,\n attemptID: started.data.attemptID,\n location,\n },\n { signal: AbortSignal.timeout(5_000) },\n ),\n ).pipe(Effect.ignore),\n )\n const status = yield* waitForCommand(client, integration.id, started.data.attemptID, (message) =>\n progress.message(message.trim() || \"Waiting for authentication command...\"),\n ).pipe(Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))))\n if (status.status === \"complete\") {\n progress.stop(`Connected to ${integration.name}`)\n return\n }\n progress.stop(\"Authentication failed\", 1)\n if (status.status === \"failed\") yield* Effect.fail(new Error(status.message))\n yield* Effect.fail(new Error(\"Authentication expired\"))\n})\n\nconst waitForOAuth = Effect.fn(\"cli.auth.login.oauth.wait\")(function* (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n) {\n while (true) {\n const response = yield* request((signal) =>\n client.integration.oauth.status({ integrationID, attemptID, location }, { signal }),\n )\n if (response.data.status !== \"pending\") return response.data\n yield* Effect.sleep(500)\n }\n})\n\nconst waitForCommand = Effect.fn(\"cli.auth.login.command.wait\")(function* (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n update: (message: string) => void,\n) {\n while (true) {\n const response = yield* request((signal) =>\n client.integration.command.status({ integrationID, attemptID, location }, { signal }),\n )\n if (response.data.status !== \"pending\") return response.data\n if (response.data.message) update(response.data.message)\n yield* Effect.sleep(500)\n }\n})\n" | ||
| ], | ||
| "mappings": ";05CAKA,IAAM,EAAO,OAAO,MAAM,EACpB,EAAS,OAAO,QAAQ,EAEjB,EAAa,EAAO,GAAG,eAAe,EAAE,SAAU,CAAC,EAAgC,CAC9F,GAAI,CAAC,EAAQ,OACb,MAAO,EAAmB,4DAA4D,EACtF,IAAM,EAAqB,CAAC,EAC5B,QAAW,KAAS,EAAQ,CAC1B,GAAI,CAAC,EAAO,EAAO,CAAM,EAAG,SAC5B,IAAM,EAAQ,MAAO,EAAY,CAAK,EACtC,GAAI,IAAU,OAAW,EAAO,EAAM,KAAO,EAE/C,OAAO,EACR,EAEY,EAAS,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAAiB,CAE7E,OADA,MAAO,EAAmB,gDAAgD,EACnE,MAAO,EAAe,IAAM,EAAS,CAAE,UAAS,SAAU,CAAC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esContent": [ | ||
| "import { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, Option } from \"effect\"\nimport { EOL } from \"node:os\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nexport default Runtime.handler(\n Commands.commands.models,\n Effect.fn(\"cli.models\")(function* (input) {\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({\n baseUrl: server.endpoint.url,\n headers: Service.headers(server.endpoint),\n })\n const response = yield* Effect.promise(() => client.model.list({ location: { directory: process.cwd() } }))\n const models = response.data\n .map((model) => `${model.providerID}/${model.id}`)\n .toSorted((a, b) => a.localeCompare(b))\n if (models.length > 0) process.stdout.write(models.join(EOL) + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";ukCAGA,cAAS,WAKT,IAAe,IAAQ,QACrB,EAAS,SAAS,OAClB,EAAO,GAAG,YAAY,EAAE,SAAU,CAAC,EAAO,CACxC,IAAM,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EACK,EAAS,EAAS,KAAK,CAC3B,QAAS,EAAO,SAAS,IACzB,QAAS,EAAQ,QAAQ,EAAO,QAAQ,CAC1C,CAAC,EAEK,GADW,MAAO,EAAO,QAAQ,IAAM,EAAO,MAAM,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,GAClF,KACrB,IAAI,CAAC,IAAU,GAAG,EAAM,cAAc,EAAM,IAAI,EAChD,SAAS,CAAC,EAAG,IAAM,EAAE,cAAc,CAAC,CAAC,EACxC,GAAI,EAAO,OAAS,EAAG,QAAQ,OAAO,MAAM,EAAO,KAAK,CAAG,EAAI,CAAG,EACnE,CACH", | ||
| "debugId": "C2498B564CB8B52964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/import.ts"], | ||
| "sourcesContent": [ | ||
| "import { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Session } from \"@opencode-ai/schema/session\"\nimport { SessionTransfer } from \"@opencode-ai/schema/session-transfer\"\nimport { Effect, Option, Schema } from \"effect\"\nimport { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nexport default Runtime.handler(\n Commands.commands.import,\n Effect.fn(\"cli.import\")(function* (input) {\n const text = yield* Effect.tryPromise({\n try: () =>\n input.file.startsWith(\"http://\") || input.file.startsWith(\"https://\")\n ? fetch(input.file).then((response) => {\n if (!response.ok) throw new Error(`Failed to fetch session data: ${response.statusText}`)\n return response.text()\n })\n : Bun.file(input.file).text(),\n catch: (cause) =>\n new Error(`Failed to read session data: ${cause instanceof Error ? cause.message : String(cause)}`),\n })\n const data = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(SessionTransfer.Data))(text)\n const encoded = Schema.encodeSync(SessionTransfer.Data)(data)\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({\n baseUrl: server.endpoint.url,\n headers: Service.headers(server.endpoint),\n })\n const location = yield* Effect.promise(() =>\n client.location.get({\n location: { directory: path.resolve(Option.getOrElse(input.directory, () => process.cwd())) },\n }),\n )\n const response = yield* Effect.promise(() =>\n fetch(new URL(\"/api/session/import\", server.endpoint.url), {\n method: \"POST\",\n headers: { ...Service.headers(server.endpoint), \"content-type\": \"application/json\" },\n body: JSON.stringify({\n ...encoded,\n location: { directory: location.directory, workspaceID: location.workspaceID },\n }),\n }),\n )\n if (response.status === 409) {\n process.stderr.write(`Session already exists${EOL}`)\n return\n }\n if (!response.ok) yield* Effect.fail(new Error(`Failed to import session: ${response.statusText}`))\n const imported = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Struct({ data: Session.Info })))(\n yield* Effect.promise(() => response.text()),\n )\n process.stdout.write(`Imported session: ${imported.data.id}${EOL}`)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";++CAKA,cAAS,WACT,oBAKA,IAAe,IAAQ,QACrB,EAAS,SAAS,OAClB,EAAO,GAAG,YAAY,EAAE,SAAU,CAAC,EAAO,CACxC,IAAM,EAAO,MAAO,EAAO,WAAW,CACpC,IAAK,IACH,EAAM,KAAK,WAAW,SAAS,GAAK,EAAM,KAAK,WAAW,UAAU,EAChE,MAAM,EAAM,IAAI,EAAE,KAAK,CAAC,IAAa,CACnC,GAAI,CAAC,EAAS,GAAI,MAAU,MAAM,iCAAiC,EAAS,YAAY,EACxF,OAAO,EAAS,KAAK,EACtB,EACD,IAAI,KAAK,EAAM,IAAI,EAAE,KAAK,EAChC,MAAO,CAAC,IACF,MAAM,gCAAgC,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,GAAG,CACtG,CAAC,EACK,EAAO,MAAO,EAAO,oBAAoB,EAAO,eAAe,EAAgB,IAAI,CAAC,EAAE,CAAI,EAC1F,EAAU,EAAO,WAAW,EAAgB,IAAI,EAAE,CAAI,EACtD,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EACK,EAAS,EAAS,KAAK,CAC3B,QAAS,EAAO,SAAS,IACzB,QAAS,EAAQ,QAAQ,EAAO,QAAQ,CAC1C,CAAC,EACK,EAAW,MAAO,EAAO,QAAQ,IACrC,EAAO,SAAS,IAAI,CAClB,SAAU,CAAE,UAAW,EAAK,QAAQ,EAAO,UAAU,EAAM,UAAW,IAAM,QAAQ,IAAI,CAAC,CAAC,CAAE,CAC9F,CAAC,CACH,EACM,EAAW,MAAO,EAAO,QAAQ,IACrC,MAAM,IAAI,IAAI,sBAAuB,EAAO,SAAS,GAAG,EAAG,CACzD,OAAQ,OACR,QAAS,IAAK,EAAQ,QAAQ,EAAO,QAAQ,EAAG,eAAgB,kBAAmB,EACnF,KAAM,KAAK,UAAU,IAChB,EACH,SAAU,CAAE,UAAW,EAAS,UAAW,YAAa,EAAS,WAAY,CAC/E,CAAC,CACH,CAAC,CACH,EACA,GAAI,EAAS,SAAW,IAAK,CAC3B,QAAQ,OAAO,MAAM,yBAAyB,GAAK,EACnD,OAEF,GAAI,CAAC,EAAS,GAAI,MAAO,EAAO,KAAS,MAAM,6BAA6B,EAAS,YAAY,CAAC,EAClG,IAAM,EAAW,MAAO,EAAO,oBAAoB,EAAO,eAAe,EAAO,OAAO,CAAE,KAAM,EAAQ,IAAK,CAAC,CAAC,CAAC,EAC7G,MAAO,EAAO,QAAQ,IAAM,EAAS,KAAK,CAAC,CAC7C,EACA,QAAQ,OAAO,MAAM,qBAAqB,EAAS,KAAK,KAAK,GAAK,EACnE,CACH", | ||
| "debugId": "97ED76B38B0D952064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-env@3.972.69/node_modules/@aws-sdk/credential-provider-env/dist-es/fromEnv.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError } from \"@smithy/core/config\";\nexport const ENV_KEY = \"AWS_ACCESS_KEY_ID\";\nexport const ENV_SECRET = \"AWS_SECRET_ACCESS_KEY\";\nexport const ENV_SESSION = \"AWS_SESSION_TOKEN\";\nexport const ENV_EXPIRATION = \"AWS_CREDENTIAL_EXPIRATION\";\nexport const ENV_CREDENTIAL_SCOPE = \"AWS_CREDENTIAL_SCOPE\";\nexport const ENV_ACCOUNT_ID = \"AWS_ACCOUNT_ID\";\nexport const fromEnv = (init) => async () => {\n init?.logger?.debug(\"@aws-sdk/credential-provider-env - fromEnv\");\n const accessKeyId = process.env[ENV_KEY];\n const secretAccessKey = process.env[ENV_SECRET];\n const sessionToken = process.env[ENV_SESSION];\n const expiry = process.env[ENV_EXPIRATION];\n const credentialScope = process.env[ENV_CREDENTIAL_SCOPE];\n const accountId = process.env[ENV_ACCOUNT_ID];\n if (accessKeyId && secretAccessKey) {\n const credentials = {\n accessKeyId,\n secretAccessKey,\n ...(sessionToken && { sessionToken }),\n ...(expiry && { expiration: new Date(expiry) }),\n ...(credentialScope && { credentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"CREDENTIALS_ENV_VARS\", \"g\");\n return credentials;\n }\n throw new CredentialsProviderError(\"Unable to find environment variable credentials.\", { logger: init?.logger });\n};\n" | ||
| ], | ||
| "mappings": ";4JAAA,eACA,WACa,EAAU,oBACV,EAAa,wBACb,EAAc,oBACd,EAAiB,4BACjB,EAAuB,uBACvB,EAAiB,iBACjB,EAAU,CAAC,IAAS,SAAY,CACzC,GAAM,QAAQ,MAAM,4CAA4C,EAChE,IAAM,EAAc,QAAQ,IAAI,GAC1B,EAAkB,QAAQ,IAAI,GAC9B,EAAe,QAAQ,IAAI,GAC3B,EAAS,QAAQ,IAAI,GACrB,EAAkB,QAAQ,IAAI,GAC9B,EAAY,QAAQ,IAAI,GAC9B,GAAI,GAAe,EAAiB,CAChC,IAAM,EAAc,CAChB,cACA,qBACI,GAAgB,CAAE,cAAa,KAC/B,GAAU,CAAE,WAAY,IAAI,KAAK,CAAM,CAAE,KACzC,GAAmB,CAAE,iBAAgB,KACrC,GAAa,CAAE,WAAU,CACjC,EAEA,OADA,uBAAqB,EAAa,uBAAwB,GAAG,EACtD,EAEX,MAAM,IAAI,2BAAyB,mDAAoD,CAAE,OAAQ,GAAM,MAAO,CAAC", | ||
| "debugId": "3E55F59BDA43C0E264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/workspace.ts"], | ||
| "sourcesContent": [ | ||
| "export * as Workspace from \"./workspace.js\"\n\nimport { Schema } from \"effect\"\nimport { WorkspaceEvent } from \"./workspace-event.js\"\nimport { WorkspaceID } from \"./workspace-id.js\"\n\nexport const ID = WorkspaceID\nexport type ID = WorkspaceID\n\nexport const DestroyResult = Schema.Struct({\n destroyed: Schema.Boolean.annotate({\n description: \"True when this request transitioned the workspace from existing to destroyed.\",\n }),\n}).annotate({\n identifier: \"WorkspaceDestroyResult\",\n description: \"Reports whether this request destroyed an existing workspace.\",\n})\nexport interface DestroyResult extends Schema.Schema.Type<typeof DestroyResult> {}\n\nexport const Event = WorkspaceEvent\n" | ||
| ], | ||
| "mappings": ";yRAMO,IAAM,EAAK,EAGL,EAAgB,EAAO,OAAO,CACzC,UAAW,EAAO,QAAQ,SAAS,CACjC,YAAa,+EACf,CAAC,CACH,CAAC,EAAE,SAAS,CACV,WAAY,yBACZ,YAAa,+DACf,CAAC,EAGY,EAAQ", | ||
| "debugId": "18DF56ABBB1DAA7064756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/services/server-connection.ts"], | ||
| "sourcesContent": [ | ||
| "import { Service, type Endpoint, type EnsureOptions } from \"@opencode-ai/client/effect/service\"\nimport { ClientError, isUnauthorizedError, OpenCode } from \"@opencode-ai/client/promise\"\nimport { OPENCODE_VERSION } from \"../version\"\nimport { Effect, Redacted } from \"effect\"\nimport { Env } from \"../env\"\nimport { ServiceConfig } from \"./service-config\"\nimport { Standalone } from \"./standalone\"\n\nexport type Args = {\n readonly server?: string\n readonly standalone?: boolean\n readonly mismatch?: \"replace\" | \"ignore\" | \"error\"\n readonly onStart?: EnsureOptions[\"onStart\"]\n}\n\nexport type Resolved = {\n readonly endpoint: Endpoint\n readonly service?: ReturnType<typeof managedService>\n}\n\nexport const resolve = Effect.fn(\"cli.server-connection.resolve\")(function* (args: Args) {\n if (args.server !== undefined && args.standalone)\n return yield* Effect.fail(new Error(\"--server and --standalone cannot be combined\"))\n if (args.server !== undefined) {\n const password = yield* Env.password\n const endpoint = {\n url: args.server,\n auth: password ? { type: \"basic\" as const, username: \"opencode\", password: Redacted.value(password) } : undefined,\n } satisfies Endpoint\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const health = yield* Effect.tryPromise({\n try: () => client.health.get({ signal: AbortSignal.timeout(5_000) }),\n catch: (cause) => connectError(endpoint, cause),\n })\n if (health.version !== OPENCODE_VERSION)\n process.stderr.write(\n `Warning: Server at ${endpoint.url} has version ${health.version}; this client is ${OPENCODE_VERSION}. Continuing anyway.\\n`,\n )\n return { endpoint } satisfies Resolved\n }\n if (args.standalone) {\n return { endpoint: yield* Standalone.start() } satisfies Resolved\n }\n\n const mismatch = args.mismatch ?? \"ignore\"\n const options = yield* ServiceConfig.options({ checkVersion: mismatch !== \"ignore\" })\n return {\n endpoint: yield* resolveManaged({ ...options, onStart: args.onStart }, mismatch),\n service: managedService(options),\n } satisfies Resolved\n})\n\nfunction managedService(options: EnsureOptions) {\n const reconnectOptions = { ...options, version: undefined }\n return {\n reconnect: () => Service.ensure(reconnectOptions),\n restart: () =>\n Effect.gen(function* () {\n yield* Service.stop(options)\n yield* Service.ensure(reconnectOptions)\n }),\n }\n}\n\nexport const shutdownPersistentPty = Effect.fn(\"cli.server-connection.shutdown-persistent-pty\")(function* (\n options: EnsureOptions,\n) {\n const endpoint = yield* Service.discover({ ...options, version: undefined })\n if (!endpoint) return\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n yield* Effect.tryPromise(() => client.experimental.persistentPty.shutdown())\n})\n\nconst resolveManaged = Effect.fnUntraced(function* (options: EnsureOptions, mismatch: NonNullable<Args[\"mismatch\"]>) {\n if (mismatch === \"replace\") return yield* Service.ensure(options)\n if (mismatch === \"ignore\") return yield* Service.ensure({ ...options, version: undefined })\n\n const compatible = yield* Service.discover(options)\n if (compatible !== undefined) return compatible\n const existing = yield* Service.discover({ ...options, version: undefined })\n if (existing !== undefined)\n return yield* Effect.fail(new Error(\"Background server version does not match this client\"))\n return yield* Service.ensure(options)\n})\n\nfunction connectError(endpoint: Endpoint, cause: unknown) {\n if (isUnauthorizedError(cause)) {\n return new Error(\n endpoint.auth === undefined\n ? `Server at ${endpoint.url} requires a password; set OPENCODE_PASSWORD`\n : `Server at ${endpoint.url} rejected the password`,\n { cause },\n )\n }\n if (cause instanceof ClientError && cause.reason === \"Transport\")\n return new Error(`Could not reach server at ${endpoint.url}`, { cause })\n return new Error(`Server at ${endpoint.url} did not provide a compatible V2 health response`, { cause })\n}\n\nexport * as ServerConnection from \"./server-connection\"\n" | ||
| ], | ||
| "mappings": ";ygBAoBO,IAAM,EAAU,EAAO,GAAG,+BAA+B,EAAE,SAAU,CAAC,EAAY,CACvF,GAAI,EAAK,SAAW,QAAa,EAAK,WACpC,OAAO,MAAO,EAAO,KAAS,MAAM,8CAA8C,CAAC,EACrF,GAAI,EAAK,SAAW,OAAW,CAC7B,IAAM,EAAW,MAAO,EAAI,SACtB,EAAW,CACf,IAAK,EAAK,OACV,KAAM,EAAW,CAAE,KAAM,QAAkB,SAAU,WAAY,SAAU,EAAS,MAAM,CAAQ,CAAE,EAAI,MAC1G,EACM,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAS,MAAO,EAAO,WAAW,CACtC,IAAK,IAAM,EAAO,OAAO,IAAI,CAAE,OAAQ,YAAY,QAAQ,IAAK,CAAE,CAAC,EACnE,MAAO,CAAC,IAAU,EAAa,EAAU,CAAK,CAChD,CAAC,EACD,GAAI,EAAO,UAAY,EACrB,QAAQ,OAAO,MACb,sBAAsB,EAAS,mBAAmB,EAAO,2BAA2B;AAAA,CACtF,EACF,MAAO,CAAE,UAAS,EAEpB,GAAI,EAAK,WACP,MAAO,CAAE,SAAU,MAAO,EAAW,MAAM,CAAE,EAG/C,IAAM,EAAW,EAAK,UAAY,SAC5B,EAAU,MAAO,EAAc,QAAQ,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AS,iDACtB,aAAa,EAAS,4BAC1B,CAAE,OAAM,CACV,EAEF,GAAI,aAAiB,GAAe,EAAM,SAAW,YACnD,OAAW,MAAM,6BAA6B,EAAS,MAAO,CAAE,OAAM,CAAC,EACzE,OAAW,MAAM,aAAa,EAAS,sDAAuD,CAAE,OAAM,CAAC", | ||
| "debugId": "56F871E9CD23F0FF64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+nested-clients@3.997.43/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsRestJsonProtocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"awsssoportal\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultSSOHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"GetRoleCredentials\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"awsssoportal\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.42\";\nvar packageInfo = {\n\tversion: version};\n\nconst k = \"ref\";\nconst a = -1, b = true, c = \"isSet\", d = \"PartitionResult\", e = \"booleanEquals\", f = \"getAttr\", g = { [k]: \"Endpoint\" }, h = { [k]: d }, i = {}, j = [{ [k]: \"Region\" }];\nconst _data = {\n conditions: [\n [c, [g]],\n [c, j],\n [\"aws.partition\", j, d],\n [e, [{ [k]: \"UseFIPS\" }, b]],\n [e, [{ [k]: \"UseDualStack\" }, b]],\n [e, [{ fn: f, argv: [h, \"supportsDualStack\"] }, b]],\n [e, [{ fn: f, argv: [h, \"supportsFIPS\"] }, b]],\n [\"stringEquals\", [{ fn: f, argv: [h, \"name\"] }, \"aws-us-gov\"]]\n ],\n results: [\n [a],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [g, i],\n [\"https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://portal.sso.{Region}.amazonaws.com\", i],\n [\"https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [\"https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://portal.sso.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 13, 3,\n 1, 4, r + 12,\n 2, 5, r + 12,\n 3, 8, 6,\n 4, 7, r + 11,\n 5, r + 9, r + 10,\n 4, 11, 9,\n 6, 10, r + 8,\n 7, r + 6, r + 7,\n 5, 12, r + 5,\n 6, r + 4, r + 5,\n 3, r + 1, 14,\n 4, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass SSOServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, SSOServiceException.prototype);\n }\n}\n\nclass InvalidRequestException extends SSOServiceException {\n name = \"InvalidRequestException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"InvalidRequestException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidRequestException.prototype);\n }\n}\nclass ResourceNotFoundException extends SSOServiceException {\n name = \"ResourceNotFoundException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ResourceNotFoundException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ResourceNotFoundException.prototype);\n }\n}\nclass TooManyRequestsException extends SSOServiceException {\n name = \"TooManyRequestsException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"TooManyRequestsException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, TooManyRequestsException.prototype);\n }\n}\nclass UnauthorizedException extends SSOServiceException {\n name = \"UnauthorizedException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"UnauthorizedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, UnauthorizedException.prototype);\n }\n}\n\nconst _ATT = \"AccessTokenType\";\nconst _GRC = \"GetRoleCredentials\";\nconst _GRCR = \"GetRoleCredentialsRequest\";\nconst _GRCRe = \"GetRoleCredentialsResponse\";\nconst _IRE = \"InvalidRequestException\";\nconst _RC = \"RoleCredentials\";\nconst _RNFE = \"ResourceNotFoundException\";\nconst _SAKT = \"SecretAccessKeyType\";\nconst _STT = \"SessionTokenType\";\nconst _TMRE = \"TooManyRequestsException\";\nconst _UE = \"UnauthorizedException\";\nconst _aI = \"accountId\";\nconst _aKI = \"accessKeyId\";\nconst _aT = \"accessToken\";\nconst _ai = \"account_id\";\nconst _c = \"client\";\nconst _e = \"error\";\nconst _ex = \"expiration\";\nconst _h = \"http\";\nconst _hE = \"httpError\";\nconst _hH = \"httpHeader\";\nconst _hQ = \"httpQuery\";\nconst _m = \"message\";\nconst _rC = \"roleCredentials\";\nconst _rN = \"roleName\";\nconst _rn = \"role_name\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.sso\";\nconst _sAK = \"secretAccessKey\";\nconst _sT = \"sessionToken\";\nconst _xasbt = \"x-amz-sso_bearer_token\";\nconst n0 = \"com.amazonaws.sso\";\nconst _s_registry = TypeRegistry.for(_s);\nvar SSOServiceException$ = [-3, _s, \"SSOServiceException\", 0, [], []];\n_s_registry.registerError(SSOServiceException$, SSOServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar InvalidRequestException$ = [-3, n0, _IRE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(InvalidRequestException$, InvalidRequestException);\nvar ResourceNotFoundException$ = [-3, n0, _RNFE,\n { [_e]: _c, [_hE]: 404 },\n [_m],\n [0]\n];\nn0_registry.registerError(ResourceNotFoundException$, ResourceNotFoundException);\nvar TooManyRequestsException$ = [-3, n0, _TMRE,\n { [_e]: _c, [_hE]: 429 },\n [_m],\n [0]\n];\nn0_registry.registerError(TooManyRequestsException$, TooManyRequestsException);\nvar UnauthorizedException$ = [-3, n0, _UE,\n { [_e]: _c, [_hE]: 401 },\n [_m],\n [0]\n];\nn0_registry.registerError(UnauthorizedException$, UnauthorizedException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar AccessTokenType = [0, n0, _ATT, 8, 0];\nvar SecretAccessKeyType = [0, n0, _SAKT, 8, 0];\nvar SessionTokenType = [0, n0, _STT, 8, 0];\nvar GetRoleCredentialsRequest$ = [3, n0, _GRCR,\n 0,\n [_rN, _aI, _aT],\n [[0, { [_hQ]: _rn }], [0, { [_hQ]: _ai }], [() => AccessTokenType, { [_hH]: _xasbt }]], 3\n];\nvar GetRoleCredentialsResponse$ = [3, n0, _GRCRe,\n 0,\n [_rC],\n [[() => RoleCredentials$, 0]]\n];\nvar RoleCredentials$ = [3, n0, _RC,\n 0,\n [_aKI, _sAK, _sT, _ex],\n [0, [() => SecretAccessKeyType, 0], [() => SessionTokenType, 0], 1]\n];\nvar GetRoleCredentials$ = [9, n0, _GRC,\n { [_h]: [\"GET\", \"/federation/credentials\", 200] }, () => GetRoleCredentialsRequest$, () => GetRoleCredentialsResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2019-06-10\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsRestJsonProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.sso\",\n errorTypeRegistries,\n version: \"2019-06-10\",\n serviceTarget: \"SWBPortalService\",\n },\n serviceId: config?.serviceId ?? \"SSO\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass SSOClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSSOHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"SWBPortalService\", \"SSOClient\", getEndpointPlugin);\nconst _ep0 = {};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass GetRoleCredentialsCommand extends command(_ep0, _mw0, \"GetRoleCredentials\", GetRoleCredentials$) {\n}\n\nconst commands = {\n GetRoleCredentialsCommand,\n};\nclass SSO extends SSOClient {\n}\ncreateAggregatedClient(commands, SSO);\n\nexports.GetRoleCredentials$ = GetRoleCredentials$;\nexports.GetRoleCredentialsCommand = GetRoleCredentialsCommand;\nexports.GetRoleCredentialsRequest$ = GetRoleCredentialsRequest$;\nexports.GetRoleCredentialsResponse$ = GetRoleCredentialsResponse$;\nexports.InvalidRequestException = InvalidRequestException;\nexports.InvalidRequestException$ = InvalidRequestException$;\nexports.ResourceNotFoundException = ResourceNotFoundException;\nexports.ResourceNotFoundException$ = ResourceNotFoundException$;\nexports.RoleCredentials$ = RoleCredentials$;\nexports.SSO = SSO;\nexports.SSOClient = SSOClient;\nexports.SSOServiceException = SSOServiceException;\nexports.SSOServiceException$ = SSOServiceException$;\nexports.TooManyRequestsException = TooManyRequestsException;\nexports.TooManyRequestsException$ = TooManyRequestsException$;\nexports.UnauthorizedException = UnauthorizedException;\nexports.UnauthorizedException$ = UnauthorizedException$;\nexports.errorTypeRegistries = errorTypeRegistries;\n" | ||
| ], | ||
| "mappings": ";iXAAA,IAAQ,wBAAsB,gCAAiC,GAAmC,kCAAgC,8BAA4B,sCAAoC,0CAAwC,0BAAwB,2BAAyB,sBAAoB,uBAAqB,mBAAiB,sCAC7U,gBAAc,0CAAwC,iCAA+B,+BACrF,oBAAmB,oBAAkB,oBAAkB,cAAY,mCAAiC,6BAA2B,oCAAkC,+BAA6B,UAAQ,eAAa,gCACnN,QAAS,QAGjB,IAAQ,6BAA2B,aAAY,yCAAuC,8CAA4C,8BAA4B,mCAAiC,6BACvL,yBAAuB,iBAAe,kBAAgB,2BAAyB,yBAAuB,2BACtG,YAAU,wCAAsC,mCAAiC,gCACjF,sBAAoB,kCAAgC,mCAAiC,sBAAoB,yBACzG,eAAc,8BACd,4BAA0B,qBAAmB,8CAC7C,UAAQ,YAAU,YAAU,cAAY,6BACxC,mBAAiB,0BACjB,8BACA,eAEF,GAA6C,MAAO,EA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AAK,MAAM,CAAC,EAC5D,KAAK,gBAAgB,IAAI,GAAoB,KAAK,MAAM,CAAC,EACzD,KAAK,gBAAgB,IAAI,GAAgB,KAAK,MAAM,CAAC,EACrD,KAAK,gBAAgB,IAAI,GAA4B,KAAK,MAAM,CAAC,EACjE,KAAK,gBAAgB,IAAI,GAAuC,KAAK,OAAQ,CACzE,iCAAkC,GAClC,+BAAgC,MAAO,IAAW,IAAI,GAA8B,CAChF,iBAAkB,EAAO,WAC7B,CAAC,CACL,CAAC,CAAC,EACF,KAAK,gBAAgB,IAAI,GAAqB,KAAK,MAAM,CAAC,EAE9D,OAAO,EAAG,CACN,MAAM,QAAQ,EAEtB,CAEA,IAAM,GAAU,GAAY,GAAc,mBAAoB,YAAa,EAAiB,EACtF,GAAO,CAAC,EACR,GAAO,CAAC,EAAS,EAAI,EAAQ,IAAM,CAAC,EAE1C,MAAM,UAAkC,GAAQ,GAAM,GAAM,qBAAsB,EAAmB,CAAE,CACvG,CAEA,IAAM,GAAW,CACb,2BACJ,EACA,MAAM,UAAY,CAAU,CAC5B,CACA,GAAuB,GAAU,CAAG,EAGpC,IAAQ,EAA4B,EASpC,IAAQ,EAAY", | ||
| "debugId": "DED94A2D1E09C4B264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "F6BEA1CDFF1B9D2A64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/inventory.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Cause, Effect, Exit } from \"effect\"\nimport { OpenCode, type PluginInfo } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Npm } from \"@opencode-ai/util/npm\"\nimport { Config } from \"../../../config\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport interface Item {\n readonly runtime: \"Server\" | \"TUI\"\n readonly target: string\n readonly name: string\n readonly version?: string\n readonly outdated: boolean\n readonly error?: string\n}\n\nexport const inspect = Effect.fn(\"cli.plugin.inspect\")(function* (selected?: string) {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const location = { directory: process.cwd() }\n const listed = yield* Effect.promise(() => client.plugin.list({ location }))\n const serverTargets = new Set(\n listed.data.flatMap((plugin) => (plugin.source.type === \"package\" ? [plugin.source.target] : [])),\n )\n const server =\n selected === undefined || serverTargets.has(selected)\n ? yield* Effect.promise(() => client.plugin.check({ location, ...(selected ? { target: selected } : {}) }))\n : listed\n const serverItems = server.data.flatMap((plugin): Item[] => {\n if (plugin.source.type !== \"package\") return []\n if (selected !== undefined && plugin.source.target !== selected) return []\n return [\n {\n runtime: \"Server\",\n target: plugin.source.target,\n name: plugin.id ?? plugin.source.target,\n ...(plugin.source.version ? { version: displayVersion(plugin.source.version) } : {}),\n outdated: plugin.source.outdated === true,\n ...(plugin.state.status === \"failed\" ? { error: plugin.state.error } : {}),\n },\n ]\n })\n\n const config = yield* Config.Service\n const info = yield* config.get()\n const configured = [\n ...new Set(\n (info.plugins ?? []).flatMap((entry) => {\n const target = typeof entry === \"string\" ? entry : entry.package\n if (target.startsWith(\"-\") || target === \"*\" || target.endsWith(\".*\") || target.startsWith(\"opencode.\")) return []\n return [target]\n }),\n ),\n ]\n const tuiTargets = yield* Effect.promise(async () => {\n const installable = await Promise.all(configured.map((target) => Npm.isInstallablePackage(target)))\n return configured.filter((target, index) => installable[index] && (selected === undefined || target === selected))\n })\n const npm = yield* Npm.Service\n const tuiItems = yield* Effect.forEach(\n tuiTargets,\n (target) =>\n Effect.gen(function* () {\n const installed = yield* npm.resolve(target, { subpaths: [\"tui\"] })\n const outdated = yield* npm.check(target).pipe(Effect.exit)\n return {\n runtime: \"TUI\" as const,\n target,\n name: target,\n ...(installed.version ? { version: displayVersion(installed.version) } : {}),\n outdated: Exit.isSuccess(outdated) && outdated.value,\n ...(Exit.isFailure(outdated) ? { error: Cause.pretty(outdated.cause) } : {}),\n }\n }),\n { concurrency: \"unbounded\" },\n )\n const items = [...serverItems, ...tuiItems]\n if (selected !== undefined && !items.length) return yield* Effect.fail(new Error(`Plugin is not configured: ${selected}`))\n return { client, location, items }\n})\n\nexport function displayVersion(version: string) {\n return /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(version) ? version.slice(0, 7) : version\n}\n\nexport function format(items: readonly Item[]) {\n return [\"Server\", \"TUI\"]\n .flatMap((runtime) => {\n const rows = items.filter((item) => item.runtime === runtime)\n if (!rows.length) return []\n return [\n runtime,\n ...rows.map(\n (item) =>\n ` ${item.name}${item.version ? ` ${item.version}` : \"\"} (${item.error ? \"check failed\" : item.outdated ? \"update available\" : \"current\"})`,\n ),\n ]\n })\n .join(EOL)\n}\n" | ||
| ], | ||
| "mappings": ";wUAAA,cAAS,WAiBF,IAAM,EAAU,EAAO,GAAG,oBAAoB,EAAE,SAAU,CAAC,EAAmB,CACnF,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAW,CAAE,UAAW,QAAQ,IAAI,CAAE,EACtC,EAAS,MAAO,EAAO,QAAQ,IAAM,EAAO,OAAO,KAAK,CAAE,UAAS,CAAC,CAAC,EACrE,EAAgB,IAAI,IACxB,EAAO,KAAK,QAAQ,CAAC,IAAY,EAAO,OAAO,OAAS,UAAY,CAAC,EAAO,OAAO,MAAM,EAAI,CAAC,CAAE,CAClG,EAKM,GAHJ,IAAa,QAAa,EAAc,IAAI,CAAQ,EAChD,MAAO,EAAO,QAAQ,IAAM,EAAO,OAAO,MAAM,CAAE,cAAc,EAAW,CAAE,OAAQ,CAAS,EAAI,CAAC,CAAG,CAAC,CAAC,EACx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KAAM,KACF,EAAU,QAAU,CAAE,QAAS,EAAe,EAAU,OAAO,CAAE,EAAI,CAAC,EAC1E,SAAU,EAAK,UAAU,CAAQ,GAAK,EAAS,SAC3C,EAAK,UAAU,CAAQ,EAAI,CAAE,MAAO,EAAM,OAAO,EAAS,KAAK,CAAE,EAAI,CAAC,CAC5E,EACD,EACH,CAAE,YAAa,WAAY,CAC7B,EACM,EAAQ,CAAC,GAAG,EAAa,GAAG,CAAQ,EAC1C,GAAI,IAAa,QAAa,CAAC,EAAM,OAAQ,OAAO,MAAO,EAAO,KAAS,MAAM,6BAA6B,GAAU,CAAC,EACzH,MAAO,CAAE,SAAQ,WAAU,OAAM,EAClC,EAEM,SAAS,CAAc,CAAC,EAAiB,CAC9C,MAAO,mCAAmC,KAAK,CAAO,EAAI,EAAQ,MAAM,EAAG,CAAC,EAAI,EAG3E,SAAS,CAAM,CAAC,EAAwB,CAC7C,MAAO,CAAC,SAAU,KAAK,EACpB,QAAQ,CAAC,IAAY,CACpB,IAAM,EAAO,EAAM,OAAO,CAAC,IAAS,EAAK,UAAY,CAAO,EAC5D,GAAI,CAAC,EAAK,OAAQ,MAAO,CAAC,EAC1B,MAAO,CACL,EACA,GAAG,EAAK,IACN,CAAC,IACC,KAAK,EAAK,OAAO,EAAK,QAAU,IAAI,EAAK,UAAY,OAAO,EAAK,MAAQ,eAAiB,EAAK,SAAW,mBAAqB,YACnI,CACF,EACD,EACA,KAAK,CAAG", | ||
| "debugId": "C3F6C7A30A8FCB5664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "BADC8F89D837A01264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/mcp/oauth.ts"], | ||
| "sourcesContent": [ | ||
| "export * as McpOAuth from \"./oauth.js\"\n\nimport { auth, type OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\"\nimport type { OAuthClientInformationMixed, OAuthTokens } from \"@modelcontextprotocol/sdk/shared/auth.js\"\nimport { Deferred, Effect } from \"effect\"\nimport { Credential } from \"@opencode-ai/schema/credential\"\nimport { ConfigMCP } from \"@opencode-ai/schema/config/mcp\"\nimport { OauthCallbackPage } from \"../oauth/page.js\"\nimport type { Integration } from \"../integration.js\"\n\n/** Persists the OAuth artifacts for one MCP server session: DCR client info, PKCE verifier, and tokens. */\nexport interface Store {\n readonly tokens: () => Promise<OAuthTokens | undefined>\n readonly saveTokens: (tokens: OAuthTokens) => Promise<void>\n readonly clientInformation: () => Promise<OAuthClientInformationMixed | undefined>\n readonly saveClientInformation: (info: OAuthClientInformationMixed) => Promise<void>\n readonly codeVerifier: () => Promise<string | undefined>\n readonly saveCodeVerifier: (verifier: string) => Promise<void>\n}\n\nexport interface Options {\n /** Loopback URL the authorization server redirects back to after the user approves. */\n readonly redirectUrl: string\n /** Space-delimited OAuth scopes to request when the server requires specific ones. */\n readonly scope?: string\n /** CSRF state embedded in the authorization request; required by the spec and enforced by some servers.\n * The caller is responsible for validating the value echoed back to the redirect. */\n readonly state?: string\n /** Statically pre-registered client credentials from config; when set, the SDK skips dynamic registration. */\n readonly client?: { readonly id: string; readonly secret?: string }\n /** Invoked by the SDK to drop credentials it has determined are invalid (e.g. a rejected refresh token). */\n readonly invalidate?: (scope: \"all\" | \"client\" | \"tokens\" | \"verifier\" | \"discovery\") => void | Promise<void>\n /** Receives the authorization URL so the caller can open a browser and capture the eventual code. */\n readonly onRedirect: (url: URL) => void | Promise<void>\n readonly store: Store\n}\n\n/**\n * Builds the MCP SDK's OAuthClientProvider. The SDK drives dynamic client registration, PKCE, and\n * token refresh through these callbacks; we only persist whatever it hands back via `store`.\n */\nexport const provider = (options: Options): OAuthClientProvider => {\n const state = options.state\n const client = options.client\n return {\n redirectUrl: options.redirectUrl,\n clientMetadata: {\n redirect_uris: [options.redirectUrl],\n client_name: \"opencode\",\n client_uri: \"https://opencode.ai\",\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n token_endpoint_auth_method: client?.secret ? \"client_secret_post\" : \"none\",\n ...(options.scope ? { scope: options.scope } : {}),\n },\n // Only advertise state when the caller supplied one (the interactive flow); the connect-time\n // provider has no redirect to validate, so it omits it.\n ...(state !== undefined ? { state: () => state } : {}),\n // Static client config short-circuits dynamic registration; otherwise the SDK registers and we persist.\n clientInformation: () =>\n client ? { client_id: client.id, client_secret: client.secret } : options.store.clientInformation(),\n saveClientInformation: (info) => options.store.saveClientInformation(info),\n tokens: () => options.store.tokens(),\n saveTokens: (tokens) => options.store.saveTokens(tokens),\n redirectToAuthorization: (url) => options.onRedirect(url),\n ...(options.invalidate ? { invalidateCredentials: options.invalidate } : {}),\n saveCodeVerifier: (verifier) => options.store.saveCodeVerifier(verifier),\n // The SDK only reads the verifier back after saving one earlier in the same flow; a miss means\n // the flow was resumed without its session state, which the SDK surfaces as an auth failure.\n codeVerifier: async () => {\n const verifier = await options.store.codeVerifier()\n if (!verifier) throw new Error(\"Missing PKCE code verifier for MCP OAuth flow\")\n return verifier\n },\n }\n}\n\n/** A Store that keeps OAuth artifacts in memory for the duration of one interactive login attempt. */\nexport const memoryStore = (): Store => {\n let tokens: OAuthTokens | undefined\n let client: OAuthClientInformationMixed | undefined\n let verifier: string | undefined\n return {\n tokens: async () => tokens,\n saveTokens: async (value) => {\n tokens = value\n },\n clientInformation: async () => client,\n saveClientInformation: async (value) => {\n client = value\n },\n codeVerifier: async () => verifier,\n saveCodeVerifier: async (value) => {\n verifier = value\n },\n }\n}\n\n/** Reads the dynamically-registered client info we stash in a credential's metadata, for token refresh. */\nexport const clientFromCredential = (credential: Credential.OAuth) =>\n credential.metadata?.client as OAuthClientInformationMixed | undefined\n\n/** Folds SDK tokens (plus DCR client info and the server URL) into a storable credential. */\nexport const toCredential = (input: {\n readonly methodID: Integration.MethodID\n readonly serverUrl: string\n readonly tokens: OAuthTokens\n readonly client: OAuthClientInformationMixed | undefined\n}) =>\n Credential.OAuth.make({\n type: \"oauth\",\n methodID: input.methodID,\n access: input.tokens.access_token,\n refresh: input.tokens.refresh_token ?? \"\",\n // 0 marks an unknown/non-expiring token; toTokens then omits expires_in so the SDK won't force a refresh.\n expires: input.tokens.expires_in ? Date.now() + input.tokens.expires_in * 1000 : 0,\n metadata: {\n serverUrl: input.serverUrl,\n tokenType: input.tokens.token_type,\n ...(input.tokens.scope ? { scope: input.tokens.scope } : {}),\n ...(input.client ? { client: input.client } : {}),\n },\n })\n\n/** Reconstructs SDK tokens from a stored credential so the connect-time provider can present them. */\nexport const toTokens = (credential: Credential.OAuth): OAuthTokens => {\n const metadata = credential.metadata ?? {}\n return {\n access_token: credential.access,\n token_type: typeof metadata.tokenType === \"string\" ? metadata.tokenType : \"Bearer\",\n ...(credential.refresh ? { refresh_token: credential.refresh } : {}),\n ...(credential.expires ? { expires_in: Math.max(0, Math.floor((credential.expires - Date.now()) / 1000)) } : {}),\n ...(typeof metadata.scope === \"string\" ? { scope: metadata.scope } : {}),\n }\n}\n\n/**\n * Runs the interactive OAuth login for one remote MCP server. Stands up a loopback callback server,\n * lets the SDK drive DCR + PKCE to produce an authorization URL, and returns an attempt whose callback\n * exchanges the redirect code for a storable credential. Scoped: the callback server closes with the scope.\n */\nexport const authorize = (input: {\n readonly name: string\n readonly config: typeof ConfigMCP.Remote.Type\n readonly methodID: Integration.MethodID\n}) =>\n Effect.gen(function* () {\n const oauth = input.config.oauth || undefined\n const store = memoryStore()\n const code = yield* Deferred.make<string, Error>()\n const redirect = oauth?.redirect_uri ? new URL(oauth.redirect_uri) : undefined\n const redirectPath = redirect?.pathname ?? \"/callback\"\n const state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString(\"base64url\")\n\n // Lazy so runtimes without a loopback listener (workerd) never evaluate node:http.\n const { createServer } = yield* Effect.promise(() => import(\"node:http\"))\n const server = createServer((request, response) => {\n const url = new URL(request.url ?? \"/\", \"http://127.0.0.1\")\n if (url.pathname !== redirectPath) {\n response.writeHead(404).end(\"Not found\")\n return\n }\n const fail = (reason: string) => {\n Effect.runFork(Deferred.fail(code, new Error(reason)))\n response\n .writeHead(400, { \"Content-Type\": \"text/html\" })\n .end(OauthCallbackPage.error(reason, { provider: input.name }))\n }\n const error = url.searchParams.get(\"error_description\") ?? url.searchParams.get(\"error\")\n if (error) return fail(error)\n // Reject a redirect whose state does not match what we issued: this is the CSRF defense the\n // state parameter exists for, so an attacker can't inject their own authorization code.\n if (url.searchParams.get(\"state\") !== state) return fail(\"OAuth state mismatch\")\n const value = url.searchParams.get(\"code\")\n if (!value) return fail(\"Missing authorization code\")\n Effect.runFork(Deferred.succeed(code, value))\n response.writeHead(200, { \"Content-Type\": \"text/html\" }).end(OauthCallbackPage.success({ provider: input.name }))\n })\n\n // Bind the port the redirect will actually arrive on: an explicit callback_port wins, else the port\n // pinned by redirect_uri, else an ephemeral port. Binding ephemerally while redirect_uri names a fixed\n // port would send the browser somewhere nothing is listening, hanging the attempt until it expires.\n const redirectPort = Number(redirect?.port) || undefined\n const port = yield* Effect.callback<number, Error>((resume) => {\n server.once(\"error\", (error) => resume(Effect.fail(error)))\n server.listen(oauth?.callback_port ?? redirectPort ?? 0, \"127.0.0.1\", () => {\n const address = server.address()\n resume(\n address && typeof address === \"object\"\n ? Effect.succeed(address.port)\n : Effect.fail(new Error(\"Could not determine MCP OAuth callback port\")),\n )\n })\n })\n yield* Effect.addFinalizer(() => Effect.sync(() => server.close()))\n\n let authorizationUrl: URL | undefined\n const oauthProvider = provider({\n redirectUrl: oauth?.redirect_uri ?? `http://127.0.0.1:${port}${redirectPath}`,\n scope: oauth?.scope,\n state,\n client: oauth?.client_id ? { id: oauth.client_id, secret: oauth.client_secret } : undefined,\n onRedirect: (url) => {\n authorizationUrl = url\n },\n store,\n })\n\n const finalize = Effect.gen(function* () {\n const tokens = yield* Effect.promise(() => store.tokens())\n if (!tokens) return yield* Effect.fail(new Error(`MCP server \"${input.name}\" did not return OAuth tokens`))\n const client = yield* Effect.promise(() => store.clientInformation())\n return toCredential({ methodID: input.methodID, serverUrl: input.config.url, tokens, client })\n })\n\n yield* Effect.tryPromise({\n try: () => auth(oauthProvider, { serverUrl: input.config.url, scope: oauth?.scope }),\n catch: (error) => (error instanceof Error ? error : new Error(String(error))),\n })\n\n if (!authorizationUrl)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" did not provide an authorization URL`))\n\n return {\n url: authorizationUrl.toString(),\n instructions: `Authorize ${input.name} in your browser. This window will close automatically.`,\n mode: \"auto\" as const,\n callback: Deferred.await(code).pipe(\n Effect.flatMap((value) =>\n Effect.tryPromise({\n try: () =>\n auth(oauthProvider, { serverUrl: input.config.url, authorizationCode: value, scope: oauth?.scope }),\n catch: (error) => (error instanceof Error ? error : new Error(String(error))),\n }),\n ),\n Effect.flatMap(() => finalize),\n ),\n }\n })\n" | ||
| ], | ||
| "mappings": ";krBAyCO,IAAM,EAAW,CAAC,IAA0C,CACjE,IAAsB,MAAhB,EACiB,OAAjB,GAAS,EACf,MAAO,CACL,YAAa,EAAQ,YACrB,eAAgB,CACd,cAAe,CAAC,EAAQ,WAAW,EACnC,YAAa,WACb,WAAY,sBACZ,YAAa,CAAC,qBAAsB,eAAe,EACnD,eAAgB,CAAC,MAAM,EACvB,2BAA4B,GAAQ,OAAS,qBAAuB,UAChE,EAAQ,MAAQ,CAAE,MAAO,EAAQ,KAAM,EAAI,CAAC,CAClD,KAGI,IAAU,OAAY,CAAE,MAAO,IAAM,CAAM,EAAI,CAAC,EAEpD,kBAAmB,IACjB,EAAS,CAAE,UAAW,EAAO,GAAI,cAAe,EAAO,MAAO,EAAI,EAAQ,MAAM,kBAAkB,EACpG,sBAAuB,CAAC,IAAS,EAAQ,MAAM,sBAAsB,CAAI,EACzE,OAAQ,IAAM,EAAQ,MAAM,OAAO,EACnC,WAAY,CAAC,IAAW,EAAQ,MAAM,WAAW,CAAM,EACvD,wBAAyB,CAAC,IAAQ,EAAQ,WAAW,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O,KAAS,MAAM,eAAe,EAAM,4CAA4C,CAAC,EAExG,MAAO,CACL,IAAK,EAAiB,SAAS,EAC/B,aAAc,aAAa,EAAM,8DACjC,KAAM,OACN,SAAU,EAAS,MAAM,CAAI,EAAE,KAC7B,EAAO,QAAQ,CAAC,IACd,EAAO,WAAW,CAChB,IAAK,IACH,EAAK,EAAe,CAAE,UAAW,EAAM,OAAO,IAAK,kBAAmB,EAAO,MAAO,GAAO,KAAM,CAAC,EACpG,MAAO,CAAC,IAAW,aAAiB,MAAQ,EAAY,MAAM,OAAO,CAAK,CAAC,CAC7E,CAAC,CACH,EACA,EAAO,QAAQ,IAAM,CAAQ,CAC/B,CACF,EACD", | ||
| "debugId": "D788368E60C6FC9664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/auth/shared.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect } from \"effect\"\nimport { OpenCode, type IntegrationInfo, type IntegrationMethod, type OpenCodeClient } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServerConnection } from \"../../../services/server-connection\"\n\nexport const location = { directory: process.cwd() }\n\nexport const createClient = Effect.fn(\"cli.auth.client\")(function* (input: ServerConnection.Args) {\n const server = yield* ServerConnection.resolve(input)\n return OpenCode.make({ baseUrl: server.endpoint.url, headers: Service.headers(server.endpoint) })\n})\n\nexport function request<A>(run: (signal: AbortSignal) => Promise<A>) {\n return Effect.tryPromise({ try: run, catch: (cause) => cause })\n}\n\nexport const loadIntegrations = Effect.fn(\"cli.auth.integrations\")(function* (client: OpenCodeClient) {\n // The model endpoint is the existing public readiness boundary for the initial plugin generation.\n yield* request((signal) => client.model.default({ location }, { signal }))\n return yield* request((signal) => client.integration.list({ location }, { signal })).pipe(\n Effect.map((response) => response.data),\n )\n})\n\nexport const resolveIntegration = Effect.fn(\"cli.auth.resolve-integration\")(function* (\n integrations: IntegrationInfo[],\n target: string,\n) {\n const normalized = target.replace(/\\/+$/, \"\")\n const byID = integrations.find((integration) => integration.id === normalized)\n if (byID) return byID\n const matches = integrations.filter((integration) => integration.name.toLowerCase() === normalized.toLowerCase())\n if (matches.length === 1) return matches[0]\n if (matches.length > 1) {\n return yield* Effect.fail(\n new Error(\n `Integration name \"${target}\" is ambiguous: ${matches.map((integration) => integration.id).join(\", \")}`,\n ),\n )\n }\n return yield* Effect.fail(new Error(`Integration not found: ${target}`))\n})\n\nexport type ConnectMethod = Exclude<IntegrationMethod, { type: \"env\" }>\n\nexport function connectMethods(integration: IntegrationInfo) {\n return integration.methods\n .filter((method): method is ConnectMethod => method.type !== \"env\")\n .toSorted((a, b) => Number(a.type === \"key\") - Number(b.type === \"key\"))\n}\n\nexport const resolveMethod = Effect.fn(\"cli.auth.resolve-method\")(function* (methods: ConnectMethod[], target: string) {\n const normalized = target.toLowerCase()\n const matches = methods.filter((method) => {\n if (method.type === \"key\") return normalized === \"key\" || method.label?.toLowerCase() === normalized\n return method.id === target || method.label.toLowerCase() === normalized\n })\n if (matches.length === 1) return matches[0]\n if (matches.length > 1) return yield* Effect.fail(new Error(`Authentication method \"${target}\" is ambiguous`))\n const available = methods.map((method) => (method.type === \"key\" ? \"key\" : method.id)).join(\", \")\n return yield* Effect.fail(\n new Error(`Authentication method not found: ${target}${available ? `. Available: ${available}` : \"\"}`),\n )\n})\n" | ||
| ], | ||
| "mappings": ";gNAKO,IAAM,EAAW,CAAE,UAAW,QAAQ,IAAI,CAAE,EAEtC,EAAe,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAA8B,CAChG,IAAM,EAAS,MAAO,EAAiB,QAAQ,CAAK,EACpD,OAAO,EAAS,KAAK,CAAE,QAAS,EAAO,SAAS,IAAK,QAAS,EAAQ,QAAQ,EAAO,QAAQ,CAAE,CAAC,EACjG,EAEM,SAAS,CAAU,CAAC,EAA0C,CACnE,OAAO,EAAO,WAAW,CAAE,IAAK,EAAK,MAAO,CAAC,IAAU,CAAM,CAAC,EAG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AC1F,OAAO,EAAO,KAAO,GAAU,EAAO,MAAM,YAAY,IAAM,EAC/D,EACD,GAAI,EAAQ,SAAW,EAAG,OAAO,EAAQ,GACzC,GAAI,EAAQ,OAAS,EAAG,OAAO,MAAO,EAAO,KAAS,MAAM,0BAA0B,iBAAsB,CAAC,EAC7G,IAAM,EAAY,EAAQ,IAAI,CAAC,IAAY,EAAO,OAAS,MAAQ,MAAQ,EAAO,EAAG,EAAE,KAAK,IAAI,EAChG,OAAO,MAAO,EAAO,KACf,MAAM,oCAAoC,IAAS,EAAY,gBAAgB,IAAc,IAAI,CACvG,EACD", | ||
| "debugId": "481478247A79CA1264756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/list.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { Effect } from \"effect\"\nimport { OpenCode, type PluginInfo } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { Config } from \"../../../config\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Npm } from \"@opencode-ai/util/npm\"\nimport { fileURLToPath } from \"node:url\"\nimport { discoverTuiPlugins, localPluginDirectories, localSource } from \"@opencode-ai/tui/plugin/discovery\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.list,\n Effect.fn(\"cli.plugin.list\")(function* (input) {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.plugin.list({ location: { directory: process.cwd() } }))\n const config = yield* Config.Service\n const global = yield* Global.Service\n const info = yield* config.get()\n const discovered = yield* Effect.promise(() =>\n localPluginDirectories(process.cwd(), global.config).then(discoverTuiPlugins),\n )\n const npm = yield* Npm.Service\n const configured = yield* Effect.forEach(info.plugins ?? [], (entry) =>\n Effect.gen(function* () {\n const target = typeof entry === \"string\" ? entry : entry.package\n if (target.startsWith(\"-\") || target === \"*\" || target.endsWith(\".*\") || target.startsWith(\"opencode.\"))\n return []\n const local = localSource(target, path.dirname(config.path))\n if (local) return [{ target: fileURLToPath(local), version: \"local\" }]\n if (!(yield* Effect.promise(() => Npm.isInstallablePackage(target)))) return []\n const installed = yield* npm.resolve(target, { subpaths: [\"tui\"] })\n if (!installed.entrypoint) return []\n return [{ target, version: installed.version }]\n }),\n )\n const output = format(\n response.data,\n [...configured.flat(), ...discovered.map((target) => ({ target, version: \"local\" }))],\n input.builtin,\n )\n if (!output) {\n process.stdout.write(\"No plugins found\" + EOL)\n return\n }\n process.stdout.write(output + EOL)\n }),\n)\n\nexport function format(\n plugins: readonly PluginInfo[],\n tui: ReadonlyArray<{ readonly target: string; readonly version?: string }>,\n builtin = false,\n) {\n const server = plugins\n .filter((plugin) => builtin || plugin.source.type !== \"builtin\")\n .map((plugin) => ({\n id: plugin.id ?? \"-\",\n version:\n plugin.source.type === \"package\"\n ? (plugin.source.version ?? \"-\")\n : plugin.source.type === \"local\"\n ? \"local\"\n : \"-\",\n target:\n plugin.source.type === \"package\"\n ? plugin.source.target\n : plugin.source.type === \"local\"\n ? plugin.source.path\n : plugin.source.type,\n }))\n const targets = tui\n .filter(\n (item) =>\n !plugins.some((plugin) =>\n plugin.source.type === \"package\"\n ? plugin.source.target === item.target\n : plugin.source.type === \"local\" &&\n (plugin.source.path === item.target ||\n (plugin.features.tui &&\n path.dirname(plugin.source.path) ===\n (item.version === \"local\" && path.extname(item.target) ? path.dirname(item.target) : item.target))),\n ),\n )\n .filter((plugin, index, all) => all.findIndex((candidate) => candidate.target === plugin.target) === index)\n .map((plugin) => ({ id: \"-\", version: plugin.version ?? \"-\", target: plugin.target }))\n const rows = [...server, ...targets]\n .toSorted((a, b) => a.id.localeCompare(b.id) || a.target.localeCompare(b.target))\n .map((item) => [\n item.id,\n /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(item.version) ? item.version.slice(0, 7) : item.version,\n item.target,\n ])\n if (!rows.length) return \"\"\n const table = [[\"ID\", \"VERSION\", \"SOURCE\"], ...rows]\n const widths = [0, 1].map((index) => Math.max(...table.map((row) => row[index].length)))\n return table.map((row) => `${row[0].padEnd(widths[0])} ${row[1].padEnd(widths[1])} ${row[2]}`).join(EOL)\n}\n" | ||
| ], | ||
| "mappings": ";ulCAAA,cAAS,WACT,oBAUA,wBAAS,YAGT,IAAe,IAAQ,QACrB,EAAS,SAAS,OAAO,SAAS,KAClC,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAAO,CAC7C,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAW,MAAO,EAAO,QAAQ,IAAM,EAAO,OAAO,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,EACrG,EAAS,MAAO,EAAO,QACvB,EAAS,MAAO,EAAO,QACvB,EAAO,MAAO,EAAO,IAAI,EACzB,EAAa,MAAO,EAAO,QAAQ,IACvC,EAAuB,QAAQ,IAAI,EAAG,EAAO,MAAM,EAAE,KAAK,CAAkB,CAC9E,EACM,EAAM,MAAO,EAAI,QACjB,EAAa,MAAO,EAAO,QAAQ,EAAK,SAAW,CAAC,EAAG,CAAC,IAC5D,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAS,OAAO,IAAU,SAAW,EAAQ,EAAM,QACzD,GAAI,EAAO,WAAW,GAAG,GAAK,IAAW,KAAO,EAAO,SAAS,IAAI,GAAK,EAAO,WAAW,WAAW,EACpG,MAAO,CAAC,EACV,IAAM,EAAQ,EAAY,EAAQ,EAAK,QAAQ,EAAO,IAAI,CAAC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SAAW,EAAK,QAAQ,EAAK,MAAM,EAAI,EAAK,QAAQ,EAAK,MAAM,EAAI,EAAK,QACtG,CACJ,EACC,OAAO,CAAC,EAAQ,EAAO,IAAQ,EAAI,UAAU,CAAC,IAAc,EAAU,SAAW,EAAO,MAAM,IAAM,CAAK,EACzG,IAAI,CAAC,KAAY,CAAE,GAAI,IAAK,QAAS,EAAO,SAAW,IAAK,OAAQ,EAAO,MAAO,EAAE,EACjF,EAAO,CAAC,GAAG,EAAQ,GAAG,CAAO,EAChC,SAAS,CAAC,EAAG,IAAM,EAAE,GAAG,cAAc,EAAE,EAAE,GAAK,EAAE,OAAO,cAAc,EAAE,MAAM,CAAC,EAC/E,IAAI,CAAC,IAAS,CACb,EAAK,GACL,mCAAmC,KAAK,EAAK,OAAO,EAAI,EAAK,QAAQ,MAAM,EAAG,CAAC,EAAI,EAAK,QACxF,EAAK,MACP,CAAC,EACH,GAAI,CAAC,EAAK,OAAQ,MAAO,GACzB,IAAM,EAAQ,CAAC,CAAC,KAAM,UAAW,QAAQ,EAAG,GAAG,CAAI,EAC7C,EAAS,CAAC,EAAG,CAAC,EAAE,IAAI,CAAC,IAAU,KAAK,IAAI,GAAG,EAAM,IAAI,CAAC,IAAQ,EAAI,GAAO,MAAM,CAAC,CAAC,EACvF,OAAO,EAAM,IAAI,CAAC,IAAQ,GAAG,EAAI,GAAG,OAAO,EAAO,EAAE,MAAM,EAAI,GAAG,OAAO,EAAO,EAAE,MAAM,EAAI,IAAI,EAAE,KAAK,CAAG", | ||
| "debugId": "96228164EDD7085C64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mcp/logout.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { resolveIntegration } from \"./resolve\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.logout,\n Effect.fn(\"cli.mcp.logout\")(function* (input) {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n\n const integration = yield* resolveIntegration(client, input.name, location)\n if (!integration) {\n process.stdout.write(`No stored credentials for ${input.name}` + EOL)\n return\n }\n\n const credentials = integration.connections.filter((connection) => connection.type === \"credential\")\n if (credentials.length === 0) {\n process.stdout.write(`No stored credentials for ${input.name}` + EOL)\n return\n }\n\n yield* Effect.forEach(\n credentials,\n (connection) => Effect.promise(() => client.credential.remove({ credentialID: connection.id, location })),\n { discard: true },\n )\n process.stdout.write(`Removed OAuth credentials for ${input.name}` + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";8/BAAA,cAAS,WAST,IAAM,EAAW,CAAE,UAAW,QAAQ,IAAI,CAAE,EAE7B,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,OAC/B,EAAO,GAAG,gBAAgB,EAAE,SAAU,CAAC,EAAO,CAC5C,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,EAAc,MAAO,EAAmB,EAAQ,EAAM,KAAM,CAAQ,EAC1E,GAAI,CAAC,EAAa,CAChB,QAAQ,OAAO,MAAM,6BAA6B,EAAM,OAAS,CAAG,EACpE,OAGF,IAAM,EAAc,EAAY,YAAY,OAAO,CAAC,IAAe,EAAW,OAAS,YAAY,EACnG,GAAI,EAAY,SAAW,EAAG,CAC5B,QAAQ,OAAO,MAAM,6BAA6B,EAAM,OAAS,CAAG,EACpE,OAGF,MAAO,EAAO,QACZ,EACA,CAAC,IAAe,EAAO,QAAQ,IAAM,EAAO,WAAW,OAAO,CAAE,aAAc,EAAW,GAAI,UAAS,CAAC,CAAC,EACxG,CAAE,QAAS,EAAK,CAClB,EACA,QAAQ,OAAO,MAAM,iCAAiC,EAAM,OAAS,CAAG,EACzE,CACH", | ||
| "debugId": "B069810C87224EF864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/pair.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode } from \"@opencode-ai/client/promise\"\nimport { renderUnicodeCompact } from \"uqr\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServiceConfig } from \"../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.pair,\n Effect.fn(\"cli.pair\")(function* () {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const password = yield* ServiceConfig.password()\n const server = yield* Effect.tryPromise(() =>\n OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }).server.get(),\n )\n const info = { urls: server.urls, username: \"opencode\", password }\n process.stdout.write(\n [\n \"\",\n ` URLs ${info.urls[0] ?? \"(none)\"}`,\n ...info.urls.slice(1).map((url) => ` ${url}`),\n ` Username ${info.username}`,\n ` Password ${info.password}`,\n \"\",\n \" Scan to pair\",\n \"\",\n renderUnicodeCompact(JSON.stringify(info), { border: 2 })\n .split(EOL)\n .map((line) => \" \" + line)\n .join(EOL),\n \"\",\n ].join(EOL) + EOL,\n )\n\n const hostname = new URL(endpoint.url).hostname\n if (![\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(hostname)) return\n process.stderr.write(` Run \\`opencode service set hostname 0.0.0.0\\` to access the service remotely.${EOL}${EOL}`)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";8/BAAA,cAAS,WAST,IAAe,IAAQ,QACrB,EAAS,SAAS,KAClB,EAAO,GAAG,UAAU,EAAE,SAAU,EAAG,CACjC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAW,MAAO,EAAc,SAAS,EAIzC,EAAO,CAAE,MAHA,MAAO,EAAO,WAAW,IACtC,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAAE,OAAO,IAAI,CAC1F,GAC4B,KAAM,SAAU,WAAY,UAAS,EACjE,QAAQ,OAAO,MACb,CACE,GACA,eAAe,EAAK,KAAK,IAAM,WAC/B,GAAG,EAAK,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,IAAQ,eAAe,GAAK,EACvD,eAAe,EAAK,WACpB,eAAe,EAAK,WACpB,GACA,iBACA,GACA,EAAqB,KAAK,UAAU,CAAI,EAAG,CAAE,OAAQ,CAAE,CAAC,EACrD,MAAM,CAAG,EACT,IAAI,CAAC,IAAS,KAAO,CAAI,EACzB,KAAK,CAAG,EACX,EACF,EAAE,KAAK,CAAG,EAAI,CAChB,EAEA,IAAM,EAAW,IAAI,IAAI,EAAS,GAAG,EAAE,SACvC,GAAI,CAAC,CAAC,YAAa,YAAa,OAAO,EAAE,SAAS,CAAQ,EAAG,OAC7D,QAAQ,OAAO,MAAM,kFAAkF,IAAM,GAAK,EACnH,CACH", | ||
| "debugId": "FE920E2121C65FCE64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/update.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Cause, Effect, Exit, Option } from \"effect\"\nimport { Npm } from \"@opencode-ai/util/npm\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { inspect } from \"./inventory\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.update,\n Effect.fn(\"cli.plugin.update\")(function* (input) {\n const result = yield* inspect(Option.getOrUndefined(input.target))\n for (const item of result.items) {\n if (!item.error) continue\n process.stderr.write(`Failed to check ${item.runtime} plugin \"${item.name}\": ${item.error}${EOL}`)\n }\n const selected = result.items.filter((item) => item.outdated)\n if (!selected.length) {\n process.stdout.write(\"No plugin updates available\" + EOL)\n if (result.items.some((item) => item.error)) process.exitCode = 1\n return\n }\n\n const npm = yield* Npm.Service\n const updated = yield* Effect.forEach(\n selected,\n (item) =>\n (item.runtime === \"Server\"\n ? Effect.promise(() => result.client.plugin.update({ location: result.location, target: item.target }))\n : npm.update(item.target, { subpaths: [\"tui\"] }).pipe(Effect.asVoid)\n ).pipe(Effect.exit, Effect.map((result) => ({ item, result }))),\n { concurrency: \"unbounded\" },\n )\n for (const item of updated) {\n if (Exit.isSuccess(item.result)) {\n process.stdout.write(`Updated ${item.item.runtime} plugin \"${item.item.name}\"${EOL}`)\n continue\n }\n process.stderr.write(\n `Failed to update ${item.item.runtime} plugin \"${item.item.name}\": ${Cause.pretty(item.result.cause)}${EOL}`,\n )\n process.exitCode = 1\n }\n }),\n)\n" | ||
| ], | ||
| "mappings": ";4/BAAA,cAAS,WAOT,IAAe,IAAQ,QACrB,EAAS,SAAS,OAAO,SAAS,OAClC,EAAO,GAAG,mBAAmB,EAAE,SAAU,CAAC,EAAO,CAC/C,IAAM,EAAS,MAAO,EAAQ,EAAO,eAAe,EAAM,MAAM,CAAC,EACjE,QAAW,KAAQ,EAAO,MAAO,CAC/B,GAAI,CAAC,EAAK,MAAO,SACjB,QAAQ,OAAO,MAAM,mBAAmB,EAAK,mBAAmB,EAAK,UAAU,EAAK,QAAQ,GAAK,EAEnG,IAAM,EAAW,EAAO,MAAM,OAAO,CAAC,IAAS,EAAK,QAAQ,EAC5D,GAAI,CAAC,EAAS,OAAQ,CAEpB,GADA,QAAQ,OAAO,MAAM,8BAAgC,CAAG,EACpD,EAAO,MAAM,KAAK,CAAC,IAAS,EAAK,KAAK,EAAG,QAAQ,SAAW,EAChE,OAGF,IAAM,EAAM,MAAO,EAAI,QACjB,EAAU,MAAO,EAAO,QAC5B,EACA,CAAC,KACE,EAAK,UAAY,SACd,EAAO,QAAQ,IAAM,EAAO,OAAO,OAAO,OAAO,CAAE,SAAU,EAAO,SAAU,OAAQ,EAAK,MAAO,CAAC,CAAC,EACpG,EAAI,OAAO,EAAK,OAAQ,CAAE,SAAU,CAAC,KAAK,CAAE,CAAC,EAAE,KAAK,EAAO,MAAM,GACnE,KAAK,EAAO,KAAM,EAAO,IAAI,CAAC,KAAY,CAAE,OAAM,QAAO,EAAE,CAAC,EAChE,CAAE,YAAa,WAAY,CAC7B,EACA,QAAW,KAAQ,EAAS,CAC1B,GAAI,EAAK,UAAU,EAAK,MAAM,EAAG,CAC/B,QAAQ,OAAO,MAAM,WAAW,EAAK,KAAK,mBAAmB,EAAK,KAAK,QAAQ,GAAK,EACpF,SAEF,QAAQ,OAAO,MACb,oBAAoB,EAAK,KAAK,mBAAmB,EAAK,KAAK,UAAU,EAAM,OAAO,EAAK,OAAO,KAAK,IAAI,GACzG,EACA,QAAQ,SAAW,GAEtB,CACH", | ||
| "debugId": "C9696350C64B384E64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "F13BC5352D20A0AC64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "0B1EF39BEE6F596A64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+nested-clients@3.997.43/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsRestJsonProtocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultSigninHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"signin\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultSigninHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"CreateOAuth2Token\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"signin\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.42\";\nvar packageInfo = {\n\tversion: version};\n\nconst s = \"ref\";\nconst a = -1, b = false, c = true, d = \"isSet\", e = \"booleanEquals\", f = \"coalesce\", g = \"PartitionResult\", h = \"stringEquals\", i = \"getAttr\", j = \"https://signin.{Region}.{PartitionResult#dualStackDnsSuffix}\", k = { [s]: \"Endpoint\" }, l = { \"fn\": i, \"argv\": [{ [s]: g }, \"name\"] }, m = { [s]: \"Region\" }, n = { [s]: g }, o = { \"authSchemes\": [{ \"name\": \"sigv4\", \"signingName\": \"signin\", \"signingRegion\": \"{Region}\" }] }, p = {}, q = [m];\nconst _data = {\n conditions: [\n [d, q],\n [e, [{ fn: f, argv: [{ [s]: \"IsControlPlane\" }, b] }, c]],\n [d, [k]],\n [\"aws.partition\", q, g],\n [e, [{ [s]: \"UseFIPS\" }, c]],\n [h, [l, \"aws\"]],\n [e, [{ fn: f, argv: [{ [s]: \"IsOAuthEndpoint\" }, b] }, c]],\n [e, [{ [s]: \"UseDualStack\" }, c]],\n [h, [l, \"aws-cn\"]],\n [h, [m, \"us-gov-west-1\"]],\n [h, [l, \"aws-us-gov\"]],\n [e, [{ fn: i, argv: [n, \"supportsFIPS\"] }, c]],\n [h, [l, \"aws-iso\"]],\n [h, [l, \"aws-iso-b\"]],\n [h, [l, \"aws-iso-f\"]],\n [h, [l, \"aws-iso-e\"]],\n [h, [l, \"aws-eusc\"]],\n [e, [{ fn: i, argv: [n, \"supportsDualStack\"] }, c]]\n ],\n results: [\n [a],\n [\"https://signin.{Region}.api.aws\", o],\n [\"https://signin.{Region}.api.amazonwebservices.com.cn\", o],\n [j, o],\n [a, \"FIPS endpoints are not supported for OAuth operations. Disable FIPS or use a non-OAuth operation.\"],\n [\"https://{Region}.oauth.signin.aws\", o],\n [\"https://{Region}.signin.aws.amazon.com\", p],\n [\"https://{Region}.signin.amazonaws.cn\", p],\n [\"https://{Region}.signin.amazonaws-us-gov.com\", p],\n [\"https://{Region}.signin.c2shome.ic.gov\", p],\n [\"https://{Region}.signin.sc2shome.sgov.gov\", p],\n [\"https://{Region}.signin.csphome.hci.ic.gov\", p],\n [\"https://{Region}.signin.csphome.adc-e.uk\", p],\n [\"https://{Region}.signin.amazonaws-eusc.eu\", p],\n [\"https://signin-fips.amazonaws-us-gov.com\", p],\n [\"https://{Region}.signin-fips.amazonaws-us-gov.com\", p],\n [\"https://{Region}.signin.{PartitionResult#dnsSuffix}\", p],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [k, p],\n [\"https://signin-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", p],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://signin-fips.{Region}.{PartitionResult#dnsSuffix}\", p],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [j, p],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://signin.{Region}.{PartitionResult#dnsSuffix}\", p],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 6, 3,\n 2, 36, 4,\n 4, 5, r + 27,\n 6, r + 4, r + 27,\n 1, 29, 7,\n 2, 36, 8,\n 3, 9, 31,\n 4, 22, 10,\n 5, 19, 11,\n 7, 21, 12,\n 8, r + 7, 13,\n 10, r + 8, 14,\n 12, r + 9, 15,\n 13, r + 10, 16,\n 14, r + 11, 17,\n 15, r + 12, 18,\n 16, r + 13, r + 16,\n 6, r + 5, 20,\n 7, 21, r + 6,\n 17, r + 24, r + 25,\n 6, r + 4, 23,\n 7, 27, 24,\n 9, r + 14, 25,\n 10, r + 15, 26,\n 11, r + 22, r + 23,\n 11, 28, r + 21,\n 17, r + 20, r + 21,\n 2, 35, 30,\n 3, 39, 31,\n 4, 32, r + 27,\n 6, r + 4, 33,\n 7, r + 27, 34,\n 9, r + 14, r + 27,\n 3, 39, 36,\n 4, 38, 37,\n 7, r + 18, r + 19,\n 6, r + 4, r + 17,\n 5, r + 1, 40,\n 8, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"IsControlPlane\", \"IsOAuthEndpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass SigninServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, SigninServiceException.prototype);\n }\n}\n\nclass AccessDeniedException extends SigninServiceException {\n name = \"AccessDeniedException\";\n $fault = \"client\";\n error;\n constructor(opts) {\n super({\n name: \"AccessDeniedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, AccessDeniedException.prototype);\n this.error = opts.error;\n }\n}\nclass InternalServerException extends SigninServiceException {\n name = \"InternalServerException\";\n $fault = \"server\";\n error;\n constructor(opts) {\n super({\n name: \"InternalServerException\",\n $fault: \"server\",\n ...opts,\n });\n Object.setPrototypeOf(this, InternalServerException.prototype);\n this.error = opts.error;\n }\n}\nclass TooManyRequestsError extends SigninServiceException {\n name = \"TooManyRequestsError\";\n $fault = \"client\";\n error;\n constructor(opts) {\n super({\n name: \"TooManyRequestsError\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, TooManyRequestsError.prototype);\n this.error = opts.error;\n }\n}\nclass ValidationException extends SigninServiceException {\n name = \"ValidationException\";\n $fault = \"client\";\n error;\n constructor(opts) {\n super({\n name: \"ValidationException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ValidationException.prototype);\n this.error = opts.error;\n }\n}\n\nconst _ADE = \"AccessDeniedException\";\nconst _AT = \"AccessToken\";\nconst _COAT = \"CreateOAuth2Token\";\nconst _COATR = \"CreateOAuth2TokenRequest\";\nconst _COATRB = \"CreateOAuth2TokenRequestBody\";\nconst _COATRBr = \"CreateOAuth2TokenResponseBody\";\nconst _COATRr = \"CreateOAuth2TokenResponse\";\nconst _COATWIAM = \"CreateOAuth2TokenWithIAM\";\nconst _COATWIAMR = \"CreateOAuth2TokenWithIAMRequest\";\nconst _COATWIAMRr = \"CreateOAuth2TokenWithIAMResponse\";\nconst _ISE = \"InternalServerException\";\nconst _OAAT = \"OAuthAccessToken\";\nconst _RT = \"RefreshToken\";\nconst _TMRE = \"TooManyRequestsError\";\nconst _VE = \"ValidationException\";\nconst _aKI = \"accessKeyId\";\nconst _aT = \"accessToken\";\nconst _at = \"access_token\";\nconst _c = \"client\";\nconst _cI = \"clientId\";\nconst _cV = \"codeVerifier\";\nconst _co = \"code\";\nconst _e = \"error\";\nconst _eI = \"expiresIn\";\nconst _ei = \"expires_in\";\nconst _gT = \"grantType\";\nconst _gt = \"grant_type\";\nconst _h = \"http\";\nconst _hE = \"httpError\";\nconst _iT = \"idToken\";\nconst _jN = \"jsonName\";\nconst _m = \"message\";\nconst _r = \"resource\";\nconst _rT = \"refreshToken\";\nconst _rU = \"redirectUri\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.signin\";\nconst _sAK = \"secretAccessKey\";\nconst _sT = \"sessionToken\";\nconst _se = \"server\";\nconst _tI = \"tokenInput\";\nconst _tO = \"tokenOutput\";\nconst _tT = \"tokenType\";\nconst _tt = \"token_type\";\nconst n0 = \"com.amazonaws.signin\";\nconst _s_registry = TypeRegistry.for(_s);\nvar SigninServiceException$ = [-3, _s, \"SigninServiceException\", 0, [], []];\n_s_registry.registerError(SigninServiceException$, SigninServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar AccessDeniedException$ = [-3, n0, _ADE,\n { [_e]: _c },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(AccessDeniedException$, AccessDeniedException);\nvar InternalServerException$ = [-3, n0, _ISE,\n { [_e]: _se, [_hE]: 500 },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(InternalServerException$, InternalServerException);\nvar TooManyRequestsError$ = [-3, n0, _TMRE,\n { [_e]: _c, [_hE]: 429 },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(TooManyRequestsError$, TooManyRequestsError);\nvar ValidationException$ = [-3, n0, _VE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(ValidationException$, ValidationException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar OAuthAccessToken = [0, n0, _OAAT, 8, 0];\nvar RefreshToken = [0, n0, _RT, 8, 0];\nvar AccessToken$ = [3, n0, _AT,\n 8,\n [_aKI, _sAK, _sT],\n [[0, { [_jN]: _aKI }], [0, { [_jN]: _sAK }], [0, { [_jN]: _sT }]], 3\n];\nvar CreateOAuth2TokenRequest$ = [3, n0, _COATR,\n 0,\n [_tI],\n [[() => CreateOAuth2TokenRequestBody$, 16]], 1\n];\nvar CreateOAuth2TokenRequestBody$ = [3, n0, _COATRB,\n 0,\n [_cI, _gT, _co, _rU, _cV, _rT],\n [[0, { [_jN]: _cI }], [0, { [_jN]: _gT }], 0, [0, { [_jN]: _rU }], [0, { [_jN]: _cV }], [() => RefreshToken, { [_jN]: _rT }]], 2\n];\nvar CreateOAuth2TokenResponse$ = [3, n0, _COATRr,\n 0,\n [_tO],\n [[() => CreateOAuth2TokenResponseBody$, 16]], 1\n];\nvar CreateOAuth2TokenResponseBody$ = [3, n0, _COATRBr,\n 0,\n [_aT, _tT, _eI, _rT, _iT],\n [[() => AccessToken$, { [_jN]: _aT }], [0, { [_jN]: _tT }], [1, { [_jN]: _eI }], [() => RefreshToken, { [_jN]: _rT }], [0, { [_jN]: _iT }]], 4\n];\nvar CreateOAuth2TokenWithIAMRequest$ = [3, n0, _COATWIAMR,\n 0,\n [_gT, _r],\n [[0, { [_jN]: _gt }], 0], 2\n];\nvar CreateOAuth2TokenWithIAMResponse$ = [3, n0, _COATWIAMRr,\n 0,\n [_aT, _tT, _eI],\n [[() => OAuthAccessToken, { [_jN]: _at }], [0, { [_jN]: _tt }], [1, { [_jN]: _ei }]], 3\n];\nvar CreateOAuth2Token$ = [9, n0, _COAT,\n { [_h]: [\"POST\", \"/v1/token\", 200] }, () => CreateOAuth2TokenRequest$, () => CreateOAuth2TokenResponse$\n];\nvar CreateOAuth2TokenWithIAM$ = [9, n0, _COATWIAM,\n { [_h]: [\"POST\", \"/v1/token?x-amz-client-auth-method=iam\", 200] }, () => CreateOAuth2TokenWithIAMRequest$, () => CreateOAuth2TokenWithIAMResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2023-01-01\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSigninHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsRestJsonProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.signin\",\n errorTypeRegistries,\n version: \"2023-01-01\",\n serviceTarget: \"Signin\",\n },\n serviceId: config?.serviceId ?? \"Signin\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass SigninClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSigninHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"Signin\", \"SigninClient\", getEndpointPlugin);\nconst _ep0 = {\n IsControlPlane: { type: \"staticContextParams\", value: false },\n};\nconst _ep1 = {\n IsOAuthEndpoint: { type: \"staticContextParams\", value: true },\n};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass CreateOAuth2TokenCommand extends command(_ep0, _mw0, \"CreateOAuth2Token\", CreateOAuth2Token$) {\n}\n\nclass CreateOAuth2TokenWithIAMCommand extends command(_ep1, _mw0, \"CreateOAuth2TokenWithIAM\", CreateOAuth2TokenWithIAM$) {\n}\n\nconst commands = {\n CreateOAuth2TokenCommand,\n CreateOAuth2TokenWithIAMCommand,\n};\nclass Signin extends SigninClient {\n}\ncreateAggregatedClient(commands, Signin);\n\nconst OAuth2ErrorCode = {\n AUTHCODE_EXPIRED: \"AUTHCODE_EXPIRED\",\n CONFLICT: \"CONFLICT\",\n INSUFFICIENT_PERMISSIONS: \"INSUFFICIENT_PERMISSIONS\",\n INVALID_REQUEST: \"INVALID_REQUEST\",\n RESOURCE_NOT_FOUND: \"RESOURCE_NOT_FOUND\",\n SERVER_ERROR: \"server_error\",\n SERVICE_QUOTA_EXCEEDED: \"SERVICE_QUOTA_EXCEEDED\",\n TOKEN_EXPIRED: \"TOKEN_EXPIRED\",\n USER_CREDENTIALS_CHANGED: \"USER_CREDENTIALS_CHANGED\",\n};\n\nexports.AccessDeniedException = AccessDeniedException;\nexports.AccessDeniedException$ = AccessDeniedException$;\nexports.AccessToken$ = AccessToken$;\nexports.CreateOAuth2Token$ = CreateOAuth2Token$;\nexports.CreateOAuth2TokenCommand = CreateOAuth2TokenCommand;\nexports.CreateOAuth2TokenRequest$ = CreateOAuth2TokenRequest$;\nexports.CreateOAuth2TokenRequestBody$ = CreateOAuth2TokenRequestBody$;\nexports.CreateOAuth2TokenResponse$ = CreateOAuth2TokenResponse$;\nexports.CreateOAuth2TokenResponseBody$ = CreateOAuth2TokenResponseBody$;\nexports.CreateOAuth2TokenWithIAM$ = CreateOAuth2TokenWithIAM$;\nexports.CreateOAuth2TokenWithIAMCommand = CreateOAuth2TokenWithIAMCommand;\nexports.CreateOAuth2TokenWithIAMRequest$ = CreateOAuth2TokenWithIAMRequest$;\nexports.CreateOAuth2TokenWithIAMResponse$ = CreateOAuth2TokenWithIAMResponse$;\nexports.InternalServerException = InternalServerException;\nexports.InternalServerException$ = InternalServerException$;\nexports.OAuth2ErrorCode = OAuth2ErrorCode;\nexports.Signin = Signin;\nexports.SigninClient = SigninClient;\nexports.SigninServiceException = SigninServiceException;\nexports.SigninServiceException$ = SigninServiceException$;\nexports.TooManyRequestsError = TooManyRequestsError;\nexports.TooManyRequestsError$ = TooManyRequestsError$;\nexports.ValidationException = ValidationException;\nexports.ValidationException$ = ValidationException$;\nexports.errorTypeRegistries = errorTypeRegistries;\n" | ||
| ], | ||
| "mappings": ";wXAAA,IAAQ,wBAAsB,gCAAiC,GAAmC,kCAAgC,8BAA4B,sCAAoC,0CAAwC,0BAAwB,2BAAyB,sBAAoB,uBAAqB,mBAA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E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.71/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/fromHttp.js", "../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.71/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/checkUrl.js", "../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.71/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/requestHelpers.js", "../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.71/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/retry-wrapper.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError } from \"@smithy/core/config\";\nimport { NodeHttpHandler } from \"@smithy/node-http-handler\";\nimport fs from \"node:fs/promises\";\nimport { checkUrl } from \"./checkUrl\";\nimport { createGetRequest, getCredentials } from \"./requestHelpers\";\nimport { retryWrapper } from \"./retry-wrapper\";\nconst AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = \"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\";\nconst DEFAULT_LINK_LOCAL_HOST = \"http://169.254.170.2\";\nconst AWS_CONTAINER_CREDENTIALS_FULL_URI = \"AWS_CONTAINER_CREDENTIALS_FULL_URI\";\nconst AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = \"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE\";\nconst AWS_CONTAINER_AUTHORIZATION_TOKEN = \"AWS_CONTAINER_AUTHORIZATION_TOKEN\";\nexport const fromHttp = (options = {}) => {\n options.logger?.debug(\"@aws-sdk/credential-provider-http - fromHttp\");\n let host;\n const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI];\n const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI];\n const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN];\n const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE];\n const warn = options.logger?.constructor?.name === \"NoOpLogger\" || !options.logger?.warn\n ? console.warn\n : options.logger.warn.bind(options.logger);\n if (relative && full) {\n warn(\"@aws-sdk/credential-provider-http: \" +\n \"you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri.\");\n warn(\"awsContainerCredentialsRelativeUri will take precedence.\");\n }\n if (token && tokenFile) {\n warn(\"@aws-sdk/credential-provider-http: \" +\n \"you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile.\");\n warn(\"awsContainerAuthorizationTokenFile will take precedence.\");\n }\n if (relative) {\n host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`;\n }\n else if (full) {\n host = full;\n }\n else {\n throw new CredentialsProviderError(`No HTTP credential provider host provided.\nSet AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger });\n }\n const url = new URL(host);\n checkUrl(url, options.logger);\n const requestHandler = NodeHttpHandler.create({ connectionTimeout: options.timeout ?? 1000 });\n const requestTimeout = options.timeout ?? 1000;\n const provider = retryWrapper(async () => {\n const request = createGetRequest(url);\n if (tokenFile) {\n request.headers.Authorization = validateToken((await fs.readFile(tokenFile)).toString());\n }\n else if (token) {\n request.headers.Authorization = validateToken(token);\n }\n try {\n const result = await requestHandler.handle(request, { requestTimeout });\n return getCredentials(result.response).then((creds) => setCredentialFeature(creds, \"CREDENTIALS_HTTP\", \"z\"));\n }\n catch (e) {\n throw new CredentialsProviderError(String(e), { logger: options.logger });\n }\n }, options.maxRetries ?? 3, options.timeout ?? 1000);\n return async () => {\n try {\n return await provider();\n }\n finally {\n requestHandler.destroy?.();\n }\n };\n};\nconst validateToken = (token) => {\n if (token.includes(\"\\r\\n\")) {\n throw new CredentialsProviderError(\"Authorization token contains invalid \\\\r\\\\n sequence.\");\n }\n return token;\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nconst LOOPBACK_CIDR_IPv4 = \"127.0.0.0/8\";\nconst LOOPBACK_CIDR_IPv6 = \"::1/128\";\nconst ECS_CONTAINER_HOST = \"169.254.170.2\";\nconst EKS_CONTAINER_HOST_IPv4 = \"169.254.170.23\";\nconst EKS_CONTAINER_HOST_IPv6 = \"[fd00:ec2::23]\";\nexport const checkUrl = (url, logger) => {\n if (url.protocol === \"https:\") {\n return;\n }\n if (url.hostname === ECS_CONTAINER_HOST ||\n url.hostname === EKS_CONTAINER_HOST_IPv4 ||\n url.hostname === EKS_CONTAINER_HOST_IPv6) {\n return;\n }\n if (url.hostname.includes(\"[\")) {\n if (url.hostname === \"[::1]\" || url.hostname === \"[0000:0000:0000:0000:0000:0000:0000:0001]\") {\n return;\n }\n }\n else {\n if (url.hostname === \"localhost\") {\n return;\n }\n const ipComponents = url.hostname.split(\".\");\n const inRange = (component) => {\n const num = parseInt(component, 10);\n return 0 <= num && num <= 255;\n };\n if (ipComponents[0] === \"127\" &&\n inRange(ipComponents[1]) &&\n inRange(ipComponents[2]) &&\n inRange(ipComponents[3]) &&\n ipComponents.length === 4) {\n return;\n }\n }\n throw new CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following:\n - loopback CIDR 127.0.0.0/8 or [::1/128]\n - ECS container host 169.254.170.2\n - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger });\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { HttpRequest } from \"@smithy/core/protocols\";\nimport { parseRfc3339DateTime } from \"@smithy/core/serde\";\nimport { sdkStreamMixin } from \"@smithy/core/serde\";\nexport function createGetRequest(url) {\n return new HttpRequest({\n protocol: url.protocol,\n hostname: url.hostname,\n port: Number(url.port),\n path: url.pathname,\n query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => {\n acc[k] = v;\n return acc;\n }, {}),\n fragment: url.hash,\n });\n}\nexport async function getCredentials(response, logger) {\n const stream = sdkStreamMixin(response.body);\n const str = await stream.transformToString();\n if (response.statusCode === 200) {\n const parsed = JSON.parse(str);\n if (typeof parsed.AccessKeyId !== \"string\" ||\n typeof parsed.SecretAccessKey !== \"string\" ||\n typeof parsed.Token !== \"string\" ||\n typeof parsed.Expiration !== \"string\") {\n throw new CredentialsProviderError(\"HTTP credential provider response not of the required format, an object matching: \" +\n \"{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }\", { logger });\n }\n return {\n accessKeyId: parsed.AccessKeyId,\n secretAccessKey: parsed.SecretAccessKey,\n sessionToken: parsed.Token,\n expiration: parseRfc3339DateTime(parsed.Expiration),\n };\n }\n if (response.statusCode >= 400 && response.statusCode < 500) {\n let parsedBody = {};\n try {\n parsedBody = JSON.parse(str);\n }\n catch (e) { }\n throw Object.assign(new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }), {\n Code: parsedBody.Code,\n Message: parsedBody.Message,\n });\n }\n throw new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger });\n}\n", | ||
| "export const retryWrapper = (toRetry, maxRetries, delayMs) => {\n return async () => {\n for (let i = 0; i < maxRetries; ++i) {\n try {\n return await toRetry();\n }\n catch (e) {\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n return await toRetry();\n };\n};\n" | ||
| ], | ||
| "mappings": ";4QAAA,eACA,WACA,WACA,2BCHA,eAGA,IAAM,EAAqB,gBACrB,EAA0B,iBAC1B,EAA0B,iBACnB,EAAW,CAAC,EAAK,IAAW,CACrC,GAAI,EAAI,WAAa,SACjB,OAEJ,GAAI,EAAI,WAAa,GACjB,EAAI,WAAa,GACjB,EAAI,WAAa,EACjB,OAEJ,GAAI,EAAI,SAAS,SAAS,GAAG,GACzB,GAAI,EAAI,WAAa,SAAW,EAAI,WAAa,4CAC7C,OAGH,KACD,GAAI,EAAI,WAAa,YACj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AQ,SAAW,IAAK,CAAC,EACtF,EAAiB,EAAQ,SAAW,KACpC,EAAW,EAAa,SAAY,CACtC,IAAM,EAAU,EAAiB,CAAG,EACpC,GAAI,EACA,EAAQ,QAAQ,cAAgB,GAAe,MAAM,EAAG,SAAS,CAAS,GAAG,SAAS,CAAC,EAEtF,QAAI,EACL,EAAQ,QAAQ,cAAgB,EAAc,CAAK,EAEvD,GAAI,CACA,IAAM,EAAS,MAAM,EAAe,OAAO,EAAS,CAAE,gBAAe,CAAC,EACtE,OAAO,EAAe,EAAO,QAAQ,EAAE,KAAK,CAAC,IAAU,uBAAqB,EAAO,mBAAoB,GAAG,CAAC,EAE/G,MAAO,EAAG,CACN,MAAM,IAAI,2BAAyB,OAAO,CAAC,EAAG,CAAE,OAAQ,EAAQ,MAAO,CAAC,IAE7E,EAAQ,YAAc,EAAG,EAAQ,SAAW,IAAI,EACnD,MAAO,UAAY,CACf,GAAI,CACA,OAAO,MAAM,EAAS,SAE1B,CACI,EAAe,UAAU,KAI/B,EAAgB,CAAC,IAAU,CAC7B,GAAI,EAAM,SAAS;AAAA,CAAM,EACrB,MAAM,IAAI,2BAAyB,uDAAuD,EAE9F,OAAO", | ||
| "debugId": "95D27A715D8BB34464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/workspace/driver.ts", "../core/src/workspace/sql.ts", "../core/src/workspace.ts", "../core/src/environment/files.ts", "../core/src/environment/exec-defaults.ts", "../core/src/environment/local.ts", "../core/src/environment/memory.ts", "../core/src/environment/environment.ts", "../core/src/environment/index.ts"], | ||
| "sourcesContent": [ | ||
| "export * as WorkspaceDriver from \"./driver.js\"\n\nimport { Workspace } from \"@opencode-ai/schema/workspace\"\nimport { makeGlobalNode } from \"@opencode-ai/util/effect/app-node\"\nimport { Context, Effect, Layer, Schema } from \"effect\"\nimport type { Scope } from \"effect\"\nimport type { EnvironmentDriver } from \"../environment/driver.js\"\n\n/**\n * Smallest provider-owned JSON value required to reconnect to the same\n * provider resource. Core stores it opaquely and hands it back; only the\n * owning driver reads inside.\n */\nexport const Binding = Schema.Record(Schema.String, Schema.Json)\nexport type Binding = typeof Binding.Type\n\nexport class Error extends Schema.TaggedError<Error>()(\"WorkspaceDriver.Error\", {\n message: Schema.optional(Schema.String),\n cause: Schema.optional(Schema.Defect()),\n}) {}\n\nexport class ProviderNotFound extends Schema.TaggedError<ProviderNotFound>()(\"WorkspaceDriver.ProviderNotFound\", {\n provider: Schema.String,\n}) {}\n\nexport interface Interface {\n /**\n * Get-or-create the provider resource backing this logical workspace.\n *\n * MUST be idempotent per `workspaceID`: core retries the same ID after\n * failures and process crashes, including a crash between a successful\n * create and the binding being persisted, and another process may race the\n * same ID. Key the resource by `workspaceID` (a provider tag or a\n * deterministic name) and adopt an existing match instead of creating a\n * duplicate.\n */\n readonly create: (input: {\n readonly workspaceID: Workspace.ID\n }) => Effect.Effect<{ readonly binding: Binding }, Error>\n readonly connect: (input: {\n readonly workspaceID: Workspace.ID\n readonly binding: Binding\n readonly saveBinding: (binding: Binding) => Effect.Effect<void>\n }) => Effect.Effect<EnvironmentDriver.Driver, Error, Scope.Scope>\n readonly suspendForIdle: (input: {\n readonly workspaceID: Workspace.ID\n readonly binding: Binding\n readonly saveBinding: (binding: Binding) => Effect.Effect<void>\n }) => Effect.Effect<void, Error>\n /**\n * Release the provider resource for this workspace.\n *\n * `binding` is null when none was persisted: the workspace was never\n * provisioned, or provisioning was interrupted mid-create. Look up any\n * resource previously created for `workspaceID` and clean it up, treating\n * absence as success.\n */\n readonly destroy: (input: {\n readonly workspaceID: Workspace.ID\n readonly binding: Binding | null\n }) => Effect.Effect<void, Error>\n}\n\nexport const make = (driver: Interface) => driver\n\nexport interface Registry {\n readonly get: (provider: string) => Effect.Effect<Interface, ProviderNotFound>\n}\n\nexport class RegistryService extends Context.Service<RegistryService, Registry>()(\n \"@opencode/WorkspaceDriverRegistry\",\n) {}\n\nexport const registry = (drivers: Readonly<Record<string, Interface>>): Registry => ({\n get: (provider) => {\n const driver = Object.hasOwn(drivers, provider) ? drivers[provider] : undefined\n return driver ? Effect.succeed(driver) : Effect.fail(new ProviderNotFound({ provider }))\n },\n})\n\nexport const registryNode = (drivers: Readonly<Record<string, Interface>>) =>\n makeGlobalNode({\n service: RegistryService,\n layer: Layer.succeed(RegistryService, RegistryService.of(registry(drivers))),\n deps: [],\n })\n\nexport const node = registryNode({})\n", | ||
| "import { Workspace } from \"@opencode-ai/schema/workspace\"\nimport { integer, sqliteTable, text } from \"drizzle-orm/sqlite-core\"\nimport type { WorkspaceDriver } from \"./driver.js\"\n\nexport const WorkspaceTable = sqliteTable(\"workspace\", {\n id: text().$type<Workspace.ID>().primaryKey(),\n provider: text().notNull(),\n binding: text({ mode: \"json\" }).$type<WorkspaceDriver.Binding>(),\n created_at: integer().notNull(),\n last_used_at: integer().notNull(),\n})\n", | ||
| "export * as Workspace from \"./workspace.js\"\n\nimport { Workspace } from \"@opencode-ai/schema/workspace\"\nimport { makeGlobalNode } from \"@opencode-ai/util/effect/app-node\"\nimport { eq } from \"drizzle-orm\"\nimport { Clock, Context, Deferred, Duration, Effect, Exit, FiberSet, Layer, Ref, Schedule, Schema, Scope } from \"effect\"\nimport { systemError } from \"effect/PlatformError\"\nimport { make } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { EnvironmentDriver } from \"./environment/driver.js\"\nimport { Database } from \"./database/database.js\"\nimport { KeyedMutex } from \"./effect/keyed-mutex.js\"\nimport { WorkspaceDriver } from \"./workspace/driver.js\"\nimport { WorkspaceTable } from \"./workspace/sql.js\"\n\nexport const ID = Workspace.ID\nexport type ID = Workspace.ID\n\nexport class Info extends Schema.Class<Info>(\"Workspace.Info\")({\n id: ID,\n provider: Schema.String,\n binding: WorkspaceDriver.Binding,\n createdAt: Schema.Number,\n lastUsedAt: Schema.Number,\n}) {}\n\nexport class NotFound extends Schema.TaggedError<NotFound>()(\"Workspace.NotFound\", { workspaceID: ID }) {}\n\nexport class CreateConflict extends Schema.TaggedError<CreateConflict>()(\"Workspace.CreateConflict\", {\n workspaceID: ID,\n provider: Schema.String,\n existingProvider: Schema.String,\n}) {}\n\nexport interface Interface {\n /** Instantly commits a logical workspace ID. No provider work happens here. */\n readonly create: (input: {\n readonly id?: ID\n readonly provider: string\n }) => Effect.Effect<ID, CreateConflict | WorkspaceDriver.ProviderNotFound>\n /** Starts or joins the shared attempt that makes the backing resource real, then returns it. */\n readonly provision: (\n workspaceID: ID,\n ) => Effect.Effect<Info, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>\n readonly connect: (\n workspaceID: ID,\n ) => Effect.Effect<EnvironmentDriver.Driver, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>\n /** Makes the workspace absent; reports whether this call destroyed an existing workspace. */\n readonly destroy: (\n workspaceID: ID,\n ) => Effect.Effect<Workspace.DestroyResult, WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>\n}\n\nexport interface Options {\n readonly idleThreshold?: Duration.Input\n readonly pollInterval?: Duration.Input\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@opencode/Workspace\") {}\n\ninterface Connection {\n readonly driver: WorkspaceDriver.Interface\n readonly environment: EnvironmentDriver.Driver\n readonly saveBinding: (binding: WorkspaceDriver.Binding) => Effect.Effect<void>\n readonly lastActivity: Ref.Ref<number>\n readonly active: Ref.Ref<number>\n readonly scope: Scope.Closeable\n}\n\ntype ReadinessError = NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound\n\nexport const configured = (options: Options = {}) =>\n makeGlobalNode({\n service: Service,\n layer: layer(options),\n deps: [Database.node, WorkspaceDriver.node],\n })\n\nconst layer = (options: Options) =>\n Layer.effect(\n Service,\n Effect.gen(function* () {\n const db = (yield* Database.Service).db\n const registry = yield* WorkspaceDriver.RegistryService\n const lifetime = yield* Scope.Scope\n const connections = new Map<ID, Connection>()\n // Destroy cancels the racing provision body by settling the deferred.\n const attempts = new Map<ID, Deferred.Deferred<Info, ReadinessError>>()\n const locks = KeyedMutex.makeUnsafe<ID>()\n const fork = yield* FiberSet.makeRuntime<never, void, never>()\n const idleThreshold = Duration.toMillis(options.idleThreshold ?? Duration.minutes(20))\n\n const find = (workspaceID: ID) =>\n db.select().from(WorkspaceTable).where(eq(WorkspaceTable.id, workspaceID)).get().pipe(Effect.orDie)\n\n const load = Effect.fn(\"Workspace.load\")(function* (workspaceID: ID) {\n const row = yield* find(workspaceID)\n if (!row) return yield* new NotFound({ workspaceID })\n return row\n })\n\n const saveBinding = (workspaceID: ID, binding: WorkspaceDriver.Binding) =>\n db.update(WorkspaceTable).set({ binding }).where(eq(WorkspaceTable.id, workspaceID)).run().pipe(Effect.orDie)\n\n const info = (row: typeof WorkspaceTable.$inferSelect, binding: WorkspaceDriver.Binding) =>\n new Info({\n id: row.id,\n provider: row.provider,\n binding,\n createdAt: row.created_at,\n lastUsedAt: row.last_used_at,\n })\n\n const provision = Effect.fn(\"Workspace.provision\")((workspaceID: ID) =>\n Effect.suspend(() => {\n const existing = attempts.get(workspaceID)\n if (existing) return Deferred.await(existing)\n\n const attempt = Deferred.makeUnsafe<Info, ReadinessError>()\n attempts.set(workspaceID, attempt)\n fork(\n locks\n .withLock(workspaceID)(\n Effect.gen(function* () {\n const row = yield* load(workspaceID)\n if (row.binding) return info(row, row.binding)\n const driver = yield* registry.get(row.provider)\n const result = yield* driver.create({ workspaceID })\n yield* saveBinding(workspaceID, result.binding)\n return info(row, result.binding)\n }),\n )\n .pipe(\n Effect.raceFirst(Deferred.await(attempt)),\n Effect.onExit((exit) =>\n Effect.sync(() => {\n if (attempts.get(workspaceID) === attempt) attempts.delete(workspaceID)\n Deferred.doneUnsafe(attempt, exit)\n }),\n ),\n Effect.exit,\n Effect.asVoid,\n ),\n )\n return Deferred.await(attempt)\n }),\n )\n\n const open = Effect.fn(\"Workspace.open\")(function* (workspaceID: ID) {\n const existing = connections.get(workspaceID)\n if (existing) return existing\n\n const row = yield* load(workspaceID)\n // Bindings are persisted before provision resolves and never nulled; a raced\n // destroy deletes the whole row and surfaces as NotFound from load above.\n if (!row.binding) return yield* Effect.die(`workspace ${workspaceID} has no binding after provision`)\n const driver = yield* registry.get(row.provider)\n const persistBinding = (binding: WorkspaceDriver.Binding) => saveBinding(workspaceID, binding)\n const scope = yield* Scope.fork(lifetime)\n const environment = yield* driver\n .connect({ workspaceID, binding: row.binding, saveBinding: persistBinding })\n .pipe(\n Effect.provideService(Scope.Scope, scope),\n Effect.onError((cause) => Scope.close(scope, Exit.failCause(cause))),\n )\n const now = yield* Clock.currentTimeMillis\n const connection: Connection = {\n driver,\n environment,\n saveBinding: persistBinding,\n lastActivity: yield* Ref.make(now),\n active: yield* Ref.make(0),\n scope,\n }\n connections.set(workspaceID, connection)\n yield* db\n .update(WorkspaceTable)\n .set({ last_used_at: now })\n .where(eq(WorkspaceTable.id, workspaceID))\n .run()\n .pipe(Effect.orDie)\n return connection\n })\n\n yield* Effect.gen(function* () {\n const now = yield* Clock.currentTimeMillis\n yield* Effect.forEach(\n [...connections.entries()],\n ([workspaceID, expected]) =>\n locks.withLock(workspaceID)(\n Effect.gen(function* () {\n const connection = connections.get(workspaceID)\n if (connection !== expected || (yield* Ref.get(connection.active)) > 0) return\n const lastActivity = yield* Ref.get(connection.lastActivity)\n if (now - lastActivity < idleThreshold) return\n const row = yield* load(workspaceID)\n if (!row.binding) return\n // Deliberate: a racing spawn blocks, then wakes cleanly. Unlocking mid-suspend could reattach a sandbox being terminated.\n yield* connection.driver.suspendForIdle({\n workspaceID,\n binding: row.binding,\n saveBinding: connection.saveBinding,\n })\n yield* db\n .update(WorkspaceTable)\n .set({ last_used_at: lastActivity })\n .where(eq(WorkspaceTable.id, workspaceID))\n .run()\n .pipe(Effect.orDie)\n connections.delete(workspaceID)\n yield* Scope.close(connection.scope, Exit.void)\n }).pipe(Effect.catchCause((cause) => Effect.logError(\"workspace idle suspension failed\", cause))),\n ),\n { concurrency: \"unbounded\", discard: true },\n )\n }).pipe(Effect.repeat(Schedule.spaced(options.pollInterval ?? Duration.minutes(1))), Effect.forkScoped)\n\n return Service.of({\n create: Effect.fn(\"Workspace.create\")(function* (input) {\n const workspaceID = input.id ?? ID.create()\n const existing = yield* db\n .select({ provider: WorkspaceTable.provider })\n .from(WorkspaceTable)\n .where(eq(WorkspaceTable.id, workspaceID))\n .get()\n .pipe(Effect.orDie)\n if (existing) {\n if (existing.provider === input.provider) return workspaceID\n return yield* new CreateConflict({\n workspaceID,\n provider: input.provider,\n existingProvider: existing.provider,\n })\n }\n yield* registry.get(input.provider)\n const now = yield* Clock.currentTimeMillis\n const inserted = yield* db\n .insert(WorkspaceTable)\n .values({ id: workspaceID, provider: input.provider, binding: null, created_at: now, last_used_at: now })\n .onConflictDoNothing()\n .returning({ id: WorkspaceTable.id })\n .get()\n .pipe(Effect.orDie)\n if (inserted) return workspaceID\n const row = yield* load(workspaceID).pipe(Effect.orDie)\n if (row.provider !== input.provider)\n return yield* new CreateConflict({\n workspaceID,\n provider: input.provider,\n existingProvider: row.provider,\n })\n return workspaceID\n }),\n provision,\n connect: Effect.fn(\"Workspace.connect\")(function* (workspaceID) {\n const spawner = make((command) =>\n Effect.acquireRelease(\n // A live connection implies the binding is already persisted, so skip the provision hop.\n Effect.suspend(() => (connections.has(workspaceID) ? Effect.void : provision(workspaceID))).pipe(\n Effect.andThen(\n locks.withLock(workspaceID)(\n Effect.gen(function* () {\n const connection = yield* open(workspaceID)\n yield* Ref.set(connection.lastActivity, yield* Clock.currentTimeMillis)\n yield* Ref.update(connection.active, (active) => active + 1)\n return connection\n }),\n ),\n ),\n Effect.mapError((cause) =>\n systemError({\n _tag: \"Unknown\",\n module: \"Workspace\",\n method: \"spawn\",\n description: `Failed to wake workspace ${workspaceID}`,\n cause,\n }),\n ),\n ),\n (connection) =>\n locks.withLock(workspaceID)(\n Effect.gen(function* () {\n yield* Ref.update(connection.active, (active) => active - 1)\n yield* Ref.set(connection.lastActivity, yield* Clock.currentTimeMillis)\n }),\n ),\n ).pipe(Effect.flatMap((connection) => connection.environment.spawner.spawn(command))),\n )\n // Overrides are connection-bound; per-spawn routing is required before any driver ships them, so they are deliberately omitted.\n return { spawner }\n }),\n destroy: Effect.fn(\"Workspace.destroy\")(function* (workspaceID) {\n // Settling the shared attempt cancels its racing provision body and fails\n // waiters with NotFound before teardown commits. Accepted tradeoffs: if the\n // locked teardown below fails, those waiters saw NotFound for a workspace\n // that still exists (the next provision retries it), and a provision racing\n // this window may briefly succeed before teardown destroys its fresh binding.\n const attempt = attempts.get(workspaceID)\n if (attempt) {\n attempts.delete(workspaceID)\n Deferred.doneUnsafe(attempt, Exit.fail(new NotFound({ workspaceID })))\n }\n return yield* locks.withLock(workspaceID)(\n Effect.gen(function* () {\n const row = yield* find(workspaceID)\n if (!row) return { destroyed: false }\n const connection = connections.get(workspaceID)\n connections.delete(workspaceID)\n if (connection) yield* Scope.close(connection.scope, Exit.void)\n // Null binding still reaches the driver: an interrupted or crashed\n // provision may have created a resource that was never persisted. A\n // provider missing from the registry cannot block deleting a\n // never-provisioned row.\n yield* registry.get(row.provider).pipe(\n Effect.flatMap((driver) => driver.destroy({ workspaceID, binding: row.binding })),\n Effect.catchTag(\"WorkspaceDriver.ProviderNotFound\", (error) =>\n row.binding ? Effect.fail(error) : Effect.void,\n ),\n )\n yield* db.delete(WorkspaceTable).where(eq(WorkspaceTable.id, workspaceID)).run().pipe(Effect.orDie)\n return { destroyed: true }\n }),\n )\n }),\n })\n }),\n )\n\nexport const node = configured()\n\n// TODO(workspace-plan): add the boot janitor and ~23h safety snapshot rotation in a later PR.\n// TODO(workspace-plan): make cold wake interruptible with a re-pin loop against janitor races.\n// TODO(workspace-plan): consider extracting a keyed shared-attempt helper (join/cancel, drop-on-settle) beside\n// KeyedMutex at end-of-series consolidation; filesystem/search.ts and session/run-coordinator.ts hand-roll the same\n// shape. Audited stdlib alternatives (rc.111): RcMap fails twice (refcount release cancels in-flight work when the\n// last waiter leaves, and one finalizer path cannot express idle-suspend vs destroy); Cache interrupts the shared\n// lookup when its last awaiter is interrupted and cannot fail waiters with NotFound on invalidation.\n", | ||
| "import { Effect, Schema } from \"effect\"\n\nexport const FileType = Schema.Literals([\"file\", \"directory\", \"symlink\", \"other\"])\nexport type FileType = typeof FileType.Type\n\nexport interface FileInfo {\n readonly type: FileType\n readonly size: number\n readonly mtimeMs: number\n}\n\nexport interface DirEntry {\n readonly name: string\n readonly type: FileType\n}\n\nexport class NotFound extends Schema.TaggedError<NotFound>()(\"Environment.NotFound\", {\n path: Schema.String,\n}) {}\n\nexport class WrongKind extends Schema.TaggedError<WrongKind>()(\"Environment.WrongKind\", {\n path: Schema.String,\n actual: FileType,\n}) {}\n\nexport class Failed extends Schema.TaggedError<Failed>()(\"Environment.Failed\", {\n path: Schema.String,\n cause: Schema.Defect(),\n}) {}\n\nexport interface FilesImpl {\n /**\n * Content operations (`read`, `list`) follow final symlinks; metadata operations (`stat` and entry\n * tags returned by `list`) do not. `info` describes the target file whose bytes are returned.\n * The process-backed default caps collected output at 64 MiB; larger whole-file reads fail with\n * `Failed`, so callers must use ranges for larger files.\n */\n readonly read: (\n path: string,\n range?: { readonly offset: number; readonly length: number },\n ) => Effect.Effect<{ readonly info: FileInfo; readonly bytes: Uint8Array }, NotFound | WrongKind | Failed>\n readonly write: (path: string, bytes: Uint8Array) => Effect.Effect<void, Failed>\n /** Describes the path entry itself, so a final symlink is reported as `symlink` rather than followed. */\n readonly stat: (path: string) => Effect.Effect<FileInfo, NotFound | Failed>\n /** Follows a final symlink to the listed directory while preserving each returned entry's own type. */\n readonly list: (path: string) => Effect.Effect<ReadonlyArray<DirEntry>, NotFound | WrongKind | Failed>\n readonly remove: (path: string) => Effect.Effect<void, Failed>\n readonly move: (from: string, to: string) => Effect.Effect<void, NotFound | Failed>\n readonly mkdir: (path: string) => Effect.Effect<void, Failed>\n}\n\nexport interface Files extends FilesImpl {}\n\n/**\n * Derives a follow-stat kind from the lstat-like Files contract. A dangling\n * symlink fails with `NotFound`.\n */\nexport const typeFollowing = (files: Files, path: string) =>\n files.stat(path).pipe(\n Effect.flatMap((info) =>\n info.type === \"symlink\"\n ? files.read(path, { offset: 0, length: 0 }).pipe(\n Effect.map((result) => result.info.type),\n Effect.catchTag(\"Environment.WrongKind\", (error) => Effect.succeed(error.actual)),\n )\n : Effect.succeed(info.type),\n ),\n )\n\nexport * as EnvironmentFiles from \"./files.js\"\n", | ||
| "import { Effect, Stream } from \"effect\"\nimport { ChildProcess } from \"effect/unstable/process\"\nimport type { ChildProcessSpawner } from \"effect/unstable/process/ChildProcessSpawner\"\nimport { collectStream } from \"@opencode-ai/util/process\"\nimport { Failed, NotFound, WrongKind, type FileInfo, type FileType, type FilesImpl } from \"./files.js\"\n\n/**\n * Files derived from spawning processes: one process per intent, \"$1\" is\n * always the target path. Scripts report classification through an exit-code\n * protocol (44/45/46) so failures never require parsing localized error text;\n * LC_ALL=C pins the one stderr match that remains. Requires GNU coreutils and\n * findutils in the target image — BSD and busybox userlands will not work.\n * Malformed output from these scripts is our own bug and dies as a defect.\n */\n\nconst MAX_DATA_BYTES = 64 * 1024 * 1024\nconst MAX_ERROR_BYTES = 64 * 1024\nconst NOT_FOUND = 44\nconst WRONG_KIND = 45\nconst FAILED = 46\nconst TAB = \"\\t\"\n\nconst loadMetadata = (flags = \"\") => `\nmetadata=$(stat ${flags} -c '%F${TAB}%s${TAB}%Y' -- \"$1\" 2>&1) || {\n case \"$metadata\" in\n *'No such file or directory'*|*'Not a directory'*) exit ${NOT_FOUND} ;;\n *) printf '%s' \"$metadata\" >&2; exit ${FAILED} ;;\n esac\n}\n`\n\nconst statScript = `\n${loadMetadata()}\nprintf '%s\\n' \"$metadata\"\n`\n\nconst readScript = `\n${loadMetadata(\"-L\")}\nkind=\\${metadata%%${TAB}*}\nif [ \"$kind\" != 'regular file' ] && [ \"$kind\" != 'regular empty file' ]; then\n printf '%s' \"$kind\" >&2\n exit ${WRONG_KIND}\nfi\nprintf '%s\\n' \"$metadata\"\nif [ \"$2\" = range ]; then\n dd if=\"$1\" iflag=skip_bytes,count_bytes skip=\"$3\" count=\"$4\" status=none\nelse\n cat -- \"$1\"\nfi\n`\n\nconst listScript = `\n${loadMetadata(\"-L\")}\nkind=\\${metadata%%${TAB}*}\nif [ \"$kind\" != directory ]; then\n printf '%s' \"$kind\" >&2\n exit ${WRONG_KIND}\nfi\nfind -H \"$1\" -mindepth 1 -maxdepth 1 -printf '%y\\\\0%f\\\\0'\n`\n\nconst moveScript = `\n${loadMetadata()}\nmv -- \"$1\" \"$2\"\n`\n\ninterface Result {\n readonly exitCode: number\n readonly stdout: Uint8Array\n readonly stderr: Uint8Array\n}\n\nexport const execDefaults = (spawner: ChildProcessSpawner[\"Service\"]): FilesImpl => {\n const run = (\n path: string,\n script: string,\n args: ReadonlyArray<string> = [],\n stdin?: Uint8Array,\n ): Effect.Effect<Result, Failed> =>\n Effect.scoped(\n Effect.gen(function* () {\n const command = ChildProcess.make(\"sh\", [\"-c\", script, \"sh\", path, ...args], {\n env: { LC_ALL: \"C\" },\n extendEnv: true,\n stdin: stdin === undefined ? undefined : Stream.make(stdin),\n })\n const handle = yield* spawner.spawn(command).pipe(Effect.mapError((cause) => new Failed({ path, cause })))\n const [stdout, stderr, exitCode] = yield* Effect.all(\n [\n collectStream(handle.stdout, MAX_DATA_BYTES),\n collectStream(handle.stderr, MAX_ERROR_BYTES),\n handle.exitCode,\n ],\n { concurrency: \"unbounded\" },\n ).pipe(Effect.mapError((cause) => new Failed({ path, cause })))\n if (stdout.truncated || stderr.truncated) {\n return yield* new Failed({ path, cause: new Error(\"Process output exceeded its collection limit\") })\n }\n return { exitCode, stdout: stdout.buffer, stderr: stderr.buffer }\n }),\n )\n\n const classify = <A>(\n path: string,\n result: Result,\n success: (stdout: Uint8Array) => A,\n ): Effect.Effect<A, NotFound | WrongKind | Failed> => {\n if (result.exitCode === 0) return Effect.sync(() => success(result.stdout))\n if (result.exitCode === NOT_FOUND) return Effect.fail(new NotFound({ path }))\n if (result.exitCode === WRONG_KIND) {\n return Effect.fail(new WrongKind({ path, actual: parseType(new TextDecoder().decode(result.stderr)) }))\n }\n return Effect.fail(processFailure(path, result))\n }\n\n const complete = (path: string, result: Result) =>\n result.exitCode === 0 ? Effect.void : Effect.fail(processFailure(path, result))\n\n return {\n stat: (path) => run(path, statScript).pipe(Effect.flatMap((result) => classifyPlain(path, result, parseInfo))),\n read: (path, range) =>\n run(\n path,\n readScript,\n range === undefined ? [\"whole\"] : [\"range\", String(range.offset), String(range.length)],\n ).pipe(\n Effect.flatMap((result) =>\n classify(path, result, (stdout) => {\n const newline = stdout.indexOf(10)\n if (newline < 0) throw new Error(\"Missing read metadata header\")\n return {\n info: parseInfo(stdout.slice(0, newline)),\n bytes: stdout.slice(newline + 1),\n }\n }),\n ),\n ),\n write: (path, bytes) =>\n run(path, `mkdir -p \"$(dirname \"$1\")\" && cat > \"$1\"`, [], bytes).pipe(\n Effect.flatMap((result) => complete(path, result)),\n ),\n list: (path) => run(path, listScript).pipe(Effect.flatMap((result) => classify(path, result, parseList))),\n remove: (path) => run(path, `rm -rf -- \"$1\"`).pipe(Effect.flatMap((result) => complete(path, result))),\n move: (from, to) =>\n run(from, moveScript, [to]).pipe(Effect.flatMap((result) => classifyPlain(from, result, () => undefined))),\n mkdir: (path) => run(path, `mkdir -p -- \"$1\"`).pipe(Effect.flatMap((result) => complete(path, result))),\n }\n}\n\n/** `classify` for scripts whose protocol never reports WrongKind. */\nconst classifyPlain = <A>(\n path: string,\n result: Result,\n success: (stdout: Uint8Array) => A,\n): Effect.Effect<A, NotFound | Failed> => {\n if (result.exitCode === 0) return Effect.sync(() => success(result.stdout))\n if (result.exitCode === NOT_FOUND) return Effect.fail(new NotFound({ path }))\n return Effect.fail(processFailure(path, result))\n}\n\nconst processFailure = (path: string, result: Result) =>\n new Failed({\n path,\n cause: new Error(new TextDecoder().decode(result.stderr).trim() || `Process exited with code ${result.exitCode}`),\n })\n\nconst parseInfo = (bytes: Uint8Array): FileInfo => {\n const [rawType, rawSize, rawMtime] = new TextDecoder().decode(bytes).trim().split(TAB)\n const size = Number(rawSize)\n const mtimeMs = Number(rawMtime) * 1_000\n if (!rawType || !Number.isFinite(size) || !Number.isFinite(mtimeMs)) throw new Error(\"Invalid stat output\")\n return { type: parseType(rawType), size, mtimeMs }\n}\n\nconst parseType = (value: string): FileType => {\n if (value === \"regular file\" || value === \"regular empty file\" || value === \"f\") return \"file\"\n if (value === \"directory\" || value === \"d\") return \"directory\"\n if (value === \"symbolic link\" || value === \"l\") return \"symlink\"\n return \"other\"\n}\n\nconst parseList = (bytes: Uint8Array) => {\n const fields = new TextDecoder().decode(bytes).split(\"\\0\")\n fields.pop()\n if (fields.length % 2 !== 0) throw new Error(\"Invalid find output\")\n return Array.from({ length: fields.length / 2 }, (_, index) => ({\n name: fields[index * 2 + 1],\n type: parseType(fields[index * 2]),\n }))\n}\n\nexport * as EnvironmentExecDefaults from \"./exec-defaults.js\"\n", | ||
| "import fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { Effect } from \"effect\"\nimport type { ChildProcessSpawner } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { Driver } from \"./driver.js\"\nimport { Failed, NotFound, WrongKind, type FileInfo, type FilesImpl, type FileType } from \"./files.js\"\n\n/**\n * The host filesystem binding. Deliberately raw node:fs rather than effect's\n * FileSystem service or FSUtil: the contract needs lstat semantics (stat\n * reports \"symlink\") and typed directory entries, and effect's node\n * FileSystem provides neither — its stat always follows symlinks and\n * readDirectory returns names only. FSUtil hits the same gap and its\n * readDirectoryEntries already bypasses to raw node readdir internally.\n * Nothing above the environment seam touches node:fs.\n */\nexport const makeLocalDriver = (spawner: ChildProcessSpawner[\"Service\"]): Driver => {\n const overrides: FilesImpl = {\n read: (value, range) =>\n Effect.gen(function* () {\n const info = yield* stat(value, true)\n if (info.type !== \"file\") return yield* new WrongKind({ path: value, actual: info.type })\n if (range === undefined) {\n const bytes = yield* attempt(value, () => fs.readFile(value), true)\n return { info, bytes }\n }\n const bytes = yield* attempt(\n value,\n async () => {\n const handle = await fs.open(value, \"r\")\n try {\n const buffer = new Uint8Array(range.length)\n const result = await handle.read(buffer, 0, range.length, range.offset)\n return buffer.subarray(0, result.bytesRead)\n } finally {\n await handle.close()\n }\n },\n true,\n )\n return { info, bytes }\n }),\n stat: (value) => stat(value, false),\n list: (value) =>\n Effect.gen(function* () {\n const info = yield* stat(value, true)\n if (info.type !== \"directory\") return yield* new WrongKind({ path: value, actual: info.type })\n const entries = yield* attempt(value, () => fs.readdir(value, { withFileTypes: true }), true)\n return entries.map((entry) => ({ name: entry.name, type: fileType(entry) }))\n }),\n write: (value, bytes) =>\n attempt(value, async () => {\n await fs.mkdir(path.dirname(value), { recursive: true })\n await fs.writeFile(value, bytes)\n }),\n remove: (value) => attempt(value, () => fs.rm(value, { recursive: true, force: true })),\n move: (from, to) =>\n Effect.gen(function* () {\n yield* stat(from, false)\n const destination = yield* stat(to, false).pipe(\n Effect.map((info) => (info.type === \"directory\" ? path.join(to, path.basename(from)) : to)),\n Effect.catchIf(\n (error) => error instanceof NotFound,\n () => Effect.succeed(to),\n ),\n )\n yield* attempt(from, () => fs.rename(from, destination))\n }),\n mkdir: (value) => attempt(value, () => fs.mkdir(value, { recursive: true }).then(() => undefined)),\n }\n\n return { spawner, overrides }\n}\n\nconst stat = (value: string, follow: boolean) =>\n attempt(value, () => (follow ? fs.stat(value) : fs.lstat(value)), true).pipe(\n Effect.map((stats): FileInfo => ({ type: fileType(stats), size: stats.size, mtimeMs: stats.mtimeMs })),\n )\n\nconst fileType = (entry: { isFile(): boolean; isDirectory(): boolean; isSymbolicLink(): boolean }): FileType => {\n if (entry.isFile()) return \"file\"\n if (entry.isDirectory()) return \"directory\"\n if (entry.isSymbolicLink()) return \"symlink\"\n return \"other\"\n}\n\nfunction attempt<A>(value: string, run: () => Promise<A>): Effect.Effect<A, Failed>\nfunction attempt<A>(value: string, run: () => Promise<A>, missing: true): Effect.Effect<A, NotFound | Failed>\nfunction attempt<A>(value: string, run: () => Promise<A>, missing = false) {\n return Effect.tryPromise({\n try: run,\n catch: (cause) =>\n missing && isMissing(cause) ? new NotFound({ path: value }) : new Failed({ path: value, cause }),\n })\n}\n\nconst isMissing = (cause: unknown) =>\n cause !== null &&\n typeof cause === \"object\" &&\n \"code\" in cause &&\n (cause.code === \"ENOENT\" || cause.code === \"ENOTDIR\")\n\nexport * as EnvironmentLocal from \"./local.js\"\n", | ||
| "import path from \"node:path\"\nimport { Effect, PlatformError } from \"effect\"\nimport { make } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { Driver } from \"./driver.js\"\nimport { Failed, NotFound, WrongKind, type FileInfo, type FilesImpl, type FileType } from \"./files.js\"\n\ntype Node =\n | { readonly type: \"file\"; readonly bytes: Uint8Array; readonly mtimeMs: number }\n | { readonly type: \"directory\"; readonly mtimeMs: number }\n | { readonly type: \"symlink\"; readonly target: string; readonly mtimeMs: number }\n\nexport interface MemoryDriver extends Driver {\n readonly symlink: (target: string, path: string) => Effect.Effect<void, Failed>\n}\n\nexport const makeMemoryDriver = (): MemoryDriver => {\n const nodes = new Map<string, Node>([[\"/\", { type: \"directory\", mtimeMs: Date.now() }]])\n const key = (value: string) => path.posix.resolve(\"/\", value)\n const info = (node: Node): FileInfo => ({\n type: node.type,\n size:\n node.type === \"file\"\n ? node.bytes.length\n : node.type === \"symlink\"\n ? new TextEncoder().encode(node.target).length\n : 0,\n mtimeMs: node.mtimeMs,\n })\n const resolveKey = (value: string, followFinal: boolean, seen = new Set<string>()): string | undefined => {\n const normalized = key(value)\n const parts = normalized.split(\"/\").filter(Boolean)\n const base = \"/\"\n const walk = (current: string, index: number): string | undefined => {\n if (index === parts.length) return current\n const part = parts[index]\n const candidate = path.posix.join(current, part)\n const node = nodes.get(candidate)\n if (node?.type !== \"symlink\" || (!followFinal && index === parts.length - 1)) return walk(candidate, index + 1)\n if (seen.has(candidate)) return undefined\n seen.add(candidate)\n const target = path.posix.resolve(path.posix.dirname(candidate), node.target)\n return resolveKey(path.posix.join(target, ...parts.slice(index + 1)), followFinal, seen)\n }\n return walk(base, 0)\n }\n const lookup = (value: string) => nodes.get(resolveKey(value, false) ?? key(value))\n const requireParent = (value: string) => {\n const parentPath = path.posix.dirname(key(value))\n const parent = nodes.get(resolveKey(parentPath, true) ?? parentPath)\n if (!parent) throw new Error(`Parent directory does not exist: ${path.posix.dirname(value)}`)\n if (parent.type !== \"directory\") throw new Error(`Parent is not a directory: ${path.posix.dirname(value)}`)\n }\n const mkdirSync = (value: string) => {\n const target = resolveKey(value, false) ?? key(value)\n const existing = nodes.get(target)\n if (existing?.type === \"directory\") return\n if (existing) throw new Error(`Path is not a directory: ${value}`)\n const parent = path.posix.dirname(target)\n if (parent !== target) mkdirSync(parent)\n nodes.set(target, { type: \"directory\", mtimeMs: Date.now() })\n }\n const failed = (value: string, cause: unknown) => new Failed({ path: value, cause })\n const overrides: FilesImpl = {\n stat: (value) =>\n Effect.suspend(() => {\n const node = lookup(value)\n return node ? Effect.succeed(info(node)) : Effect.fail(new NotFound({ path: value }))\n }),\n read: (value, range) =>\n Effect.gen(function* () {\n const original = lookup(value)\n if (!original) return yield* new NotFound({ path: value })\n if (original.type === \"directory\") return yield* new WrongKind({ path: value, actual: \"directory\" })\n const resolved = resolveKey(value, true)\n const node = resolved === undefined ? undefined : nodes.get(resolved)\n if (!node) return yield* new NotFound({ path: value })\n if (node.type !== \"file\") return yield* new WrongKind({ path: value, actual: node.type })\n const bytes = range === undefined ? node.bytes : node.bytes.subarray(range.offset, range.offset + range.length)\n return { info: info(node), bytes: bytes.slice() }\n }),\n write: (value, bytes) =>\n Effect.try({\n try: () => {\n mkdirSync(path.posix.dirname(key(value)))\n const existing = lookup(value)\n if (existing?.type === \"directory\") throw new Error(`Path is a directory: ${value}`)\n const target = existing?.type === \"symlink\" ? resolveKey(value, true) : resolveKey(value, false)\n if (!target) throw new Error(`Cannot resolve symlink: ${value}`)\n requireParent(target)\n nodes.set(target, { type: \"file\", bytes: bytes.slice(), mtimeMs: Date.now() })\n },\n catch: (cause) => failed(value, cause),\n }),\n list: (value) =>\n Effect.gen(function* () {\n const target = resolveKey(value, true) ?? key(value)\n const node = nodes.get(target)\n if (!node) return yield* new NotFound({ path: value })\n if (node.type !== \"directory\") return yield* new WrongKind({ path: value, actual: node.type })\n return [...nodes.entries()]\n .filter(([entry]) => entry !== target && path.posix.dirname(entry) === target)\n .map(([entry, child]) => ({ name: path.posix.basename(entry), type: child.type satisfies FileType }))\n .sort((a, b) => a.name.localeCompare(b.name))\n }),\n remove: (value) =>\n Effect.sync(() => {\n const target = resolveKey(value, false) ?? key(value)\n for (const entry of nodes.keys()) {\n if (entry === target || entry.startsWith(`${target}/`)) nodes.delete(entry)\n }\n }),\n move: (from, to) =>\n Effect.gen(function* () {\n const source = resolveKey(from, false) ?? key(from)\n const node = nodes.get(source)\n if (!node) return yield* new NotFound({ path: from })\n yield* Effect.try({\n try: () => {\n const requested = resolveKey(to, false) ?? key(to)\n const destination =\n nodes.get(requested)?.type === \"directory\"\n ? path.posix.join(requested, path.posix.basename(source))\n : requested\n if (node.type === \"directory\" && destination.startsWith(`${source}/`)) {\n throw new Error(`Cannot move a directory into itself: ${from}`)\n }\n const existing = nodes.get(destination)\n if (node.type === \"directory\" && existing && existing.type !== \"directory\") {\n throw new Error(`Cannot overwrite a non-directory with a directory: ${to}`)\n }\n requireParent(destination)\n const moved = [...nodes.entries()].filter(([entry]) => entry === source || entry.startsWith(`${source}/`))\n for (const [entry] of moved) nodes.delete(entry)\n for (const [entry, child] of moved) nodes.set(`${destination}${entry.slice(source.length)}`, child)\n },\n catch: (cause) => failed(from, cause),\n })\n }),\n mkdir: (value) => Effect.try({ try: () => mkdirSync(value), catch: (cause) => failed(value, cause) }),\n }\n\n const spawner = make((command) =>\n Effect.suspend(() => {\n const description = command._tag === \"StandardCommand\" ? command.command : \"pipeline\"\n return Effect.fail(\n PlatformError.systemError({\n _tag: \"Unknown\",\n module: \"EnvironmentMemory\",\n method: \"spawn\",\n pathOrDescriptor: description,\n cause: failed(description, new Error(\"The memory driver cannot spawn processes\")),\n }),\n )\n }),\n )\n\n return {\n spawner,\n overrides,\n symlink: (target, value) =>\n Effect.try({\n try: () => {\n requireParent(value)\n nodes.set(resolveKey(value, false) ?? key(value), { type: \"symlink\", target, mtimeMs: Date.now() })\n },\n catch: (cause) => failed(value, cause),\n }),\n }\n}\n\nexport * as EnvironmentMemory from \"./memory.js\"\n", | ||
| "import { CrossSpawnSpawner } from \"@opencode-ai/util/cross-spawn-spawner\"\nimport { makeLocationNode } from \"@opencode-ai/util/effect/app-node\"\nimport { Context, Effect, Layer } from \"effect\"\nimport { ChildProcessSpawner } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { Files } from \"./files.js\"\nimport { makeFiles } from \"./index.js\"\nimport { makeLocalDriver } from \"./local.js\"\nimport { Location } from \"../location.js\"\nimport { Workspace } from \"../workspace.js\"\n\nexport interface Interface {\n readonly files: Files\n readonly spawner: ChildProcessSpawner[\"Service\"]\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@opencode/Environment\") {}\n\nconst layer = Layer.effect(\n Service,\n Effect.gen(function* () {\n const spawner = yield* ChildProcessSpawner\n const location = yield* Location.Service\n const workspace = yield* Workspace.Service\n const driver = location.workspaceID\n ? yield* workspace.connect(location.workspaceID).pipe(\n // Environment has no error channel; an unknown or destroyed placement is a configuration defect by design.\n Effect.mapError(\n (cause) => new Error(`Failed to bind Environment to workspace ${location.workspaceID}`, { cause }),\n ),\n Effect.orDie,\n )\n : makeLocalDriver(spawner)\n return Service.of({ files: makeFiles(driver), spawner: driver.spawner })\n }),\n)\n\nexport const node = makeLocationNode({\n service: Service,\n layer,\n deps: [CrossSpawnSpawner.node, Location.node, Workspace.node],\n})\n\nexport * as EnvironmentService from \"./environment.js\"\n", | ||
| "export * as Environment from \"./index.js\"\n\nexport { type Driver } from \"./driver.js\"\nexport {\n type DirEntry,\n Failed,\n type FileInfo,\n type Files,\n type FilesImpl,\n type FileType,\n NotFound,\n typeFollowing,\n WrongKind,\n} from \"./files.js\"\nexport { execDefaults } from \"./exec-defaults.js\"\nexport { makeLocalDriver } from \"./local.js\"\nexport { makeMemoryDriver, type MemoryDriver } from \"./memory.js\"\nexport { type Interface, node, Service } from \"./environment.js\"\n\nimport type { Driver } from \"./driver.js\"\nimport { execDefaults } from \"./exec-defaults.js\"\nimport type { Files } from \"./files.js\"\n\nexport const makeFiles = (driver: Driver): Files => ({\n ...execDefaults(driver.spawner),\n ...driver.overrides,\n})\n" | ||
| ], | ||
| "mappings": ";y8BAaO,IAAM,GAAU,EAAO,OAAO,EAAO,OAAQ,EAAO,IAAI,EAGxD,MAAM,WAAc,EAAO,YAAmB,EAAE,wBAAyB,CAC9E,QAAS,EAAO,SAAS,EAAO,MAAM,EACtC,MAAO,EAAO,SAAS,EAAO,OAAO,CAAC,CACxC,CAAC,CAAE,CAAC,CAEG,MAAM,WAAyB,EAAO,YAA8B,EAAE,mCAAoC,CAC/G,SAAU,EAAO,MACnB,CAAC,CAAE,CAAC,CAwCG,IAAM,GAAO,CAAC,IAAsB,EAMpC,MAAM,UAAwB,EAAQ,QAAmC,EAC9E,mCACF,CAAE,CAAC,CAEI,IAAM,GAAW,CAAC,KAA4D,CACnF,IAAK,CAAC,IAAa,CACjB,IAAM,EAAS,OAAO,OAAO,EAAS,CAAQ,EAAI,EAAQ,GAAY,OACtE,OAAO,EAAS,EAAO,QAAQ,CAAM,EAAI,EAAO,KAAK,IAAI,GAAiB,CAAE,UAAS,CAAC,CAAC,EAE3F,GAEa,GAAe,CAAC,IAC3B,EAAe,CACb,QAAS,EACT,MAAO,EAAM,QAAQ,EAAiB,EAAgB,GAAG,GAAS,CAAO,CAAC,CAAC,EAC3E,KAAM,CAAC,CACT,CAAC,EAEU,GAAO,GAAa,CAAC,CAAC,ECnF5B,IAAM,EAAiB,GAAY,YAAa,CACrD,GAAI,EAAK,EAAE,MAAoB,EAAE,WAAW,EAC5C,SAAU,EAAK,EAA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AO,QAAQ,IAAM,CACnB,IAAM,EAAc,EAAQ,OAAS,kBAAoB,EAAQ,QAAU,WAC3E,OAAO,EAAO,KACZ,GAAc,YAAY,CACxB,KAAM,UACN,OAAQ,oBACR,OAAQ,QACR,iBAAkB,EAClB,MAAO,EAAO,EAAiB,MAAM,0CAA0C,CAAC,CAClF,CAAC,CACH,EACD,CACH,EAIE,YACA,QAAS,CAAC,EAAQ,IAChB,EAAO,IAAI,CACT,IAAK,IAAM,CACT,EAAc,CAAK,EACnB,EAAM,IAAI,EAAW,EAAO,EAAK,GAAK,EAAI,CAAK,EAAG,CAAE,KAAM,UAAW,SAAQ,QAAS,KAAK,IAAI,CAAE,CAAC,GAEpG,MAAO,CAAC,IAAU,EAAO,EAAO,CAAK,CACvC,CAAC,CACL,GCxJK,MAAM,UAAgB,EAAQ,QAA4B,EAAE,uBAAuB,CAAE,CAAC,CAE7F,IAAM,GAAQ,EAAM,OAClB,EACA,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAU,MAAO,GACjB,EAAW,MAAO,GAAS,QAC3B,EAAY,MAAO,EAAU,QAC7B,EAAS,EAAS,YACpB,MAAO,EAAU,QAAQ,EAAS,WAAW,EAAE,KAE7C,EAAO,SACL,CAAC,IAAc,MAAM,2CAA2C,EAAS,cAAe,CAAE,OAAM,CAAC,CACnG,EACA,EAAO,KACT,EACA,GAAgB,CAAO,EAC3B,OAAO,EAAQ,GAAG,CAAE,MAAO,GAAU,CAAM,EAAG,QAAS,EAAO,OAAQ,CAAC,EACxE,CACH,EAEa,GAAO,GAAiB,CACnC,QAAS,EACT,SACA,KAAM,CAAC,GAAkB,KAAM,GAAS,KAAM,EAAU,IAAI,CAC9D,CAAC,ECjBM,IAAM,GAAY,CAAC,KAA2B,IAChD,GAAa,EAAO,OAAO,KAC3B,EAAO,SACZ", | ||
| "debugId": "EAC7C3D331E8B74964756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/server-process.ts", "src/services/service-registration.ts", "src/services/web-ui.ts", "src/app-assets.ts", "src/commands/handlers/serve.ts"], | ||
| "sourcesContent": [ | ||
| "export * as ServerProcess from \"./server-process\"\n\nimport { NodeServices } from \"@effect/platform-node\"\nimport { Service, type DiscoverOptions } from \"@opencode-ai/client/effect/service\"\nimport { LayerNode } from \"@opencode-ai/util/effect/layer-node\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { OPENCODE_CHANNEL, OPENCODE_VERSION } from \"./version\"\nimport { AppProcess } from \"@opencode-ai/util/process\"\nimport { randomBytes, randomUUID } from \"node:crypto\"\nimport { Effect, Option, Redacted, Schedule, Schema } from \"effect\"\nimport { PersistentPty } from \"@opencode-ai/schema/persistent-pty\"\nimport { HttpServer } from \"effect/unstable/http\"\nimport { Env } from \"./env\"\nimport { ServiceConfig } from \"./services/service-config\"\nimport { ServiceRegistration } from \"./services/service-registration\"\nimport { Updater } from \"./services/updater\"\nimport { WebUi } from \"./services/web-ui\"\n\nexport type Mode = \"default\" | \"service\" | \"stdio\"\n\nexport type Options = {\n readonly mode: Mode\n readonly hostname?: string\n readonly port?: number\n readonly cors?: readonly string[]\n}\n\n// The process effect lives until server shutdown; tracing it would parent every request to one process-lifetime trace.\nexport const run = Effect.fnUntraced(function* (options: Options) {\n return yield* processEffect(options).pipe(\n Effect.provide(Updater.layer),\n Effect.provide(\n LayerNode.compile(LayerNode.group([Global.node, AppProcess.node]), {\n replacements: [\n Global.node.replace(\n Global.layerWith(process.env.OPENCODE_CONFIG_DIR ? { config: process.env.OPENCODE_CONFIG_DIR } : {}),\n ),\n ],\n }),\n ),\n Effect.provide(NodeServices.layer),\n )\n})\n\nconst processEffect = Effect.fnUntraced(function* (options: Options) {\n const inherited = process.env.OPENCODE_PTY_HANDOFF\n delete process.env.OPENCODE_PTY_HANDOFF\n const handoff =\n inherited === undefined\n ? undefined\n : yield* Schema.decodeUnknownEffect(Schema.fromJsonString(PersistentPty.Handoff))(inherited).pipe(\n Effect.mapError(() => new Error(\"Invalid PTY restart handoff\")),\n )\n const global = yield* Global.Service\n if (options.mode === \"service\") yield* Effect.sync(() => process.chdir(global.home))\n return yield* Effect.scoped(\n Effect.gen(function* () {\n const foreground = options.mode === \"default\"\n const serviceOptions = options.mode === \"service\" ? yield* ServiceConfig.options() : undefined\n const config = options.mode === \"service\" ? yield* ServiceConfig.read() : {}\n const hostname = options.hostname ?? config.hostname ?? \"127.0.0.1\"\n const port = options.port ?? config.port ?? (options.mode === \"service\" ? ServiceConfig.defaultPort() : undefined)\n const incumbent =\n serviceOptions !== undefined && port !== undefined\n ? yield* Service.incumbent({ ...serviceOptions, url: serviceURL(hostname, port) })\n : undefined\n if (incumbent !== undefined) return\n const { start } = yield* Effect.promise(() => import(\"@opencode-ai/server/process\"))\n const environmentPassword = yield* Env.password\n // Keep the lease credential out of the environment inherited by tools.\n if (options.mode === \"stdio\") {\n delete process.env.OPENCODE_PASSWORD\n delete process.env.OPENCODE_SERVER_PASSWORD\n }\n const password =\n options.mode === \"service\"\n ? config.password || randomBytes(32).toString(\"base64url\")\n : environmentPassword\n ? Redacted.value(environmentPassword)\n : randomBytes(32).toString(\"base64url\")\n if (!password) return yield* Effect.fail(new Error(\"Missing server password\"))\n const instanceID = randomUUID()\n const transform = yield* WebUi.handler()\n const server = yield* start(\n {\n app: {\n name: process.env.OPENCODE_CLIENT ?? \"cli\",\n version: OPENCODE_VERSION,\n channel: OPENCODE_CHANNEL,\n },\n hostname,\n port,\n cors: options.cors ?? config.cors,\n password,\n pty: { handoff },\n simulation: truthy(process.env.OPENCODE_SIMULATE),\n database: {\n path:\n process.env.OPENCODE_DB ??\n ([\"latest\", \"dev\", \"beta\", \"next\", \"prod\"].includes(OPENCODE_CHANNEL) ||\n process.env.OPENCODE_DISABLE_CHANNEL_DB === \"1\" ||\n process.env.OPENCODE_DISABLE_CHANNEL_DB === \"true\"\n ? \"opencode.db\"\n : `opencode-${OPENCODE_CHANNEL.replace(/[^a-zA-Z0-9._-]/g, \"-\")}.db`),\n },\n models: {\n url: process.env.OPENCODE_MODELS_URL,\n file: process.env.OPENCODE_MODELS_PATH,\n fetch: !truthy(process.env.OPENCODE_DISABLE_MODELS_FETCH),\n },\n config: {\n directory: process.env.OPENCODE_CONFIG_DIR,\n project: !truthy(\n process.env.OPENCODE_CONFIG_PROJECT_DISABLE ?? process.env.OPENCODE_DISABLE_PROJECT_CONFIG,\n ),\n file: process.env.OPENCODE_CONFIG,\n content: process.env.OPENCODE_CONFIG_CONTENT,\n },\n windows: {\n gitbash: process.env.OPENCODE_GIT_BASH_PATH,\n },\n fs: {\n filewatcher: !truthy(process.env.OPENCODE_FILEWATCHER_DISABLE ?? process.env.OPENCODE_DISABLE_FILEWATCHER),\n fff:\n process.env.OPENCODE_DISABLE_FFF === undefined\n ? process.platform !== \"win32\"\n : !truthy(process.env.OPENCODE_DISABLE_FFF),\n },\n },\n serviceOptions === undefined\n ? undefined\n : {\n onListen: (address, shutdown) =>\n Effect.gen(function* () {\n if (!config.password) yield* ServiceConfig.password(password)\n return yield* ServiceRegistration.register({\n address,\n password,\n id: instanceID,\n file: serviceOptions.file,\n shutdown,\n })\n }),\n },\n transform,\n ).pipe(\n Effect.catch((error) => {\n if (serviceOptions === undefined || port === undefined || !addressInUse(error)) return Effect.fail(error)\n return recognizeIncumbent(serviceOptions, hostname, port).pipe(\n Effect.flatMap((found) =>\n found\n ? Effect.void\n : Effect.fail(\n new Error(\n `Managed service port ${port} on ${hostname} is already in use by another process. ` +\n \"Configure another port with `opencode service set port <port>` and start the service again.\",\n { cause: error },\n ),\n ),\n ),\n )\n }),\n )\n if (server === undefined) return\n const url = HttpServer.formatAddress(server.address)\n console.log(options.mode === \"stdio\" ? JSON.stringify({ url }) : `server listening on ${url}`)\n if (foreground && !environmentPassword) console.log(`server password ${password}`)\n const updater = yield* Updater.Service\n yield* updater.check().pipe(Effect.schedule(Schedule.spaced(\"10 minutes\")), Effect.forkScoped)\n return yield* options.mode === \"service\"\n ? server.shutdown\n : options.mode === \"stdio\"\n ? waitForStdinClose()\n : Effect.never\n }).pipe(Effect.annotateLogs({ role: \"server\" })),\n )\n})\n\nconst recognizeIncumbent = Effect.fnUntraced(function* (options: DiscoverOptions, hostname: string, port: number) {\n const found = yield* Service.incumbent({ ...options, url: serviceURL(hostname, port) }).pipe(\n Effect.filterOrFail((value) => value !== undefined),\n Effect.retry(Schedule.spaced(\"100 millis\")),\n Effect.timeoutOption(\"15 seconds\"),\n )\n return Option.isSome(found)\n})\n\nfunction serviceURL(hostname: string, port: number) {\n return `http://${hostname.includes(\":\") ? `[${hostname}]` : hostname}:${port}`\n}\n\nfunction truthy(value?: string) {\n return value === \"1\" || value?.toLowerCase() === \"true\"\n}\n\nfunction addressInUse(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false\n if (\"code\" in error && error.code === \"EADDRINUSE\") return true\n return \"cause\" in error && addressInUse(error.cause)\n}\n\nfunction waitForStdinClose() {\n return Effect.callback<void>((resume) => {\n const close = () => resume(Effect.void)\n process.stdin.once(\"end\", close)\n process.stdin.once(\"close\", close)\n process.stdin.resume()\n if (process.stdin.readableEnded || process.stdin.destroyed) close()\n return Effect.sync(() => {\n process.stdin.off(\"end\", close)\n process.stdin.off(\"close\", close)\n process.stdin.pause()\n })\n })\n}\n", | ||
| "export * as ServiceRegistration from \"./service-registration\"\n\nimport { Service, type Info } from \"@opencode-ai/client/effect/service\"\nimport path from \"node:path\"\nimport { Effect, FileSystem, Schedule, Schema } from \"effect\"\nimport { HttpServer } from \"effect/unstable/http\"\nimport { OPENCODE_VERSION } from \"../version\"\n\nconst infoJson = Schema.fromJsonString(Service.Info)\nconst encodeInfo = Schema.encodeEffect(infoJson)\nconst decodeInfo = Schema.decodeUnknownEffect(infoJson)\n\nexport const register = Effect.fnUntraced(function* (options: {\n readonly address: HttpServer.Address\n readonly password: string\n readonly id: string\n readonly file: string\n readonly shutdown: Effect.Effect<void>\n}) {\n const fs = yield* FileSystem.FileSystem\n const temp = options.file + \".\" + options.id + \".tmp\"\n yield* fs.makeDirectory(path.dirname(options.file), { recursive: true })\n const info = {\n id: options.id,\n version: OPENCODE_VERSION,\n url: HttpServer.formatAddress(options.address),\n pid: process.pid,\n password: options.password,\n }\n const encoded = yield* encodeInfo(info)\n const current = fs.readFileString(options.file).pipe(Effect.flatMap(decodeInfo))\n const owns = (found: Info) =>\n found.id === info.id &&\n found.version === info.version &&\n found.url === info.url &&\n found.pid === info.pid &&\n found.password === info.password\n yield* fs.writeFileString(temp, encoded, { mode: 0o600 }).pipe(Effect.andThen(fs.rename(temp, options.file)))\n yield* current.pipe(\n Effect.catchCause((cause) =>\n Effect.logWarning(\"managed service registration check failed; shutting down\", {\n cause,\n serviceID: options.id,\n servicePID: process.pid,\n registration: options.file,\n }).pipe(Effect.andThen(Effect.failCause(cause))),\n ),\n Effect.tap((found) =>\n owns(found)\n ? Effect.void\n : Effect.logWarning(\"managed service registration replaced; shutting down\", {\n serviceID: options.id,\n servicePID: process.pid,\n registration: options.file,\n observedServiceID: found.id,\n observedServicePID: found.pid,\n observedVersion: found.version,\n observedURL: found.url,\n }),\n ),\n Effect.filterOrFail(owns),\n Effect.repeat(Schedule.spaced(\"5 seconds\")),\n Effect.ignore,\n Effect.andThen(options.shutdown),\n Effect.forkScoped,\n )\n return current.pipe(\n Effect.flatMap((found) => (owns(found) ? fs.remove(options.file) : Effect.void)),\n Effect.ignore,\n )\n})\n", | ||
| "import { FSUtil } from \"@opencode-ai/util/fs-util\"\nimport { Effect, FileSystem } from \"effect\"\nimport { HttpServerError, HttpServerRequest, HttpServerResponse } from \"effect/unstable/http\"\nimport { createHash } from \"node:crypto\"\nimport { load, type AssetMap } from \"../app-assets\"\n\nexport const handler = Effect.fn(\"cli.web-ui.handler\")(function* (options?: { readonly assets?: AssetMap }) {\n const fileSystem = yield* FileSystem.FileSystem\n const assets = options?.assets\n ? Effect.succeed(options.assets)\n : yield* Effect.cached(load().pipe(Effect.provideService(FileSystem.FileSystem, fileSystem)))\n return <E, R>(api: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>) =>\n api.pipe(\n Effect.catchIf(isRouteNotFound, () =>\n HttpServerRequest.HttpServerRequest.pipe(\n Effect.flatMap((request) => {\n const url = new URL(request.url, \"http://localhost\")\n if (url.pathname === \"/api\" || url.pathname.startsWith(\"/api/\"))\n return Effect.succeed(HttpServerResponse.empty({ status: 404 }))\n return assets.pipe(Effect.flatMap((files) => serveUI(request, url, files)))\n }),\n ),\n ),\n )\n})\n\nfunction serveUI(request: HttpServerRequest.HttpServerRequest, url: URL, assets: AssetMap) {\n const key = url.pathname.replace(/^\\//, \"\")\n if (key.startsWith(\"_assets/\") && assets[key] === undefined)\n return Effect.succeed(HttpServerResponse.empty({ status: 404, headers: { \"cache-control\": \"no-store\" } }))\n const name = assets[key] !== undefined ? key : \"index.html\"\n const file = assets[name]\n if (!file) return Effect.succeed(HttpServerResponse.empty({ status: 404 }))\n if (request.method !== \"GET\" && request.method !== \"HEAD\")\n return Effect.succeed(HttpServerResponse.empty({ status: 405 }))\n const html = name === \"index.html\"\n const revalidate = html || name === \"sw.js\" || name === \"registerSW.js\"\n const headers = {\n \"content-type\": FSUtil.mimeType(name),\n \"cache-control\": revalidate ? \"no-cache\" : \"public, max-age=31536000, immutable\",\n \"content-security-policy\": html\n ? cspForHtml(typeof file === \"string\" ? file : Buffer.from(file).toString())\n : csp(),\n \"x-content-type-options\": \"nosniff\",\n }\n return Effect.succeed(\n request.method === \"HEAD\"\n ? HttpServerResponse.empty({ headers })\n : HttpServerResponse.raw(file, { headers, contentType: headers[\"content-type\"] }),\n )\n}\n\nfunction isRouteNotFound(error: unknown) {\n return error instanceof HttpServerError.HttpServerError && error.reason._tag === \"RouteNotFound\"\n}\n\nfunction csp(hash = \"\") {\n return `default-src 'self'; script-src 'self' 'wasm-unsafe-eval'${hash ? ` 'sha256-${hash}'` : \"\"}; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: blob:; font-src 'self' data:; media-src 'self' data:; connect-src * data: blob:`\n}\n\nfunction cspForHtml(body: string) {\n const match = body.match(\n /<script\\b(?![^>]*\\bsrc\\s*=)[^>]*\\bid=([\"'])oc-theme-preload-script\\1[^>]*>([\\s\\S]*?)<\\/script>/i,\n )\n return csp(match ? createHash(\"sha256\").update(match[2]).digest(\"base64\") : \"\")\n}\n\nexport * as WebUi from \"./web-ui\"\n", | ||
| "import { Effect, FileSystem, Option } from \"effect\"\nimport path from \"node:path\"\nimport { brotliDecompressSync } from \"node:zlib\"\nimport { OPENCODE_LOCAL } from \"./version\"\n\nexport type AssetMap = Readonly<Record<string, string | Uint8Array>>\ntype EncodedAssetMap = Readonly<Record<string, { readonly content: string; readonly encoding: \"utf8\" | \"base64\" }>>\n\nexport const load = Effect.fn(\"cli.app-assets.load\")(function* () {\n const embedded = yield* Effect.tryPromise(() => import(\"virtual:opencode-app-assets\")).pipe(Effect.option)\n if (Option.isSome(embedded) && embedded.value.default.length > 0) return decodeArchive(embedded.value.default)\n if (!OPENCODE_LOCAL) return yield* Effect.fail(new Error(\"Web UI assets are missing from the CLI build\"))\n return decode(yield* sourceAssets())\n})\n\nfunction decodeArchive(archive: string) {\n const body = brotliDecompressSync(Buffer.from(archive, \"base64\")).toString()\n return decode(JSON.parse(body) as EncodedAssetMap)\n}\n\nconst sourceAssets = Effect.fnUntraced(function* () {\n const fs = yield* FileSystem.FileSystem\n const root = path.resolve(import.meta.dirname, \"../../app/dist\")\n const files = yield* fs.readDirectory(root, { recursive: true })\n return Object.fromEntries(\n (yield* Effect.forEach(\n files.filter((file) => !file.endsWith(\".map\")),\n Effect.fnUntraced(function* (file) {\n const target = path.join(root, file)\n if ((yield* fs.stat(target)).type === \"Directory\") return\n const body = Buffer.from(yield* fs.readFile(target))\n const encoding = isText(file) ? \"utf8\" : \"base64\"\n return [file, { encoding, content: body.toString(encoding) }] as const\n }),\n { concurrency: \"unbounded\" },\n )).filter((asset) => asset !== undefined),\n )\n})\n\nfunction decode(assets: EncodedAssetMap): AssetMap {\n return Object.fromEntries(\n Object.entries(assets).map(([key, asset]) => [\n key,\n asset.encoding === \"utf8\" ? asset.content : Buffer.from(asset.content, \"base64\"),\n ]),\n )\n}\n\nfunction isText(file: string) {\n return file === \"_headers\" || /\\.(?:css|html|js|json|svg|txt|webmanifest|xml)$/.test(file)\n}\n", | ||
| "import { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerProcess } from \"../../server-process\"\n\nexport default Runtime.handler(\n Commands.commands.serve,\n Effect.fnUntraced(function* (input) {\n if (input.service && input.stdio) return yield* Effect.fail(new Error(\"--service and --stdio cannot be combined\"))\n return yield* ServerProcess.run({\n mode: input.service ? \"service\" : input.stdio ? \"stdio\" : \"default\",\n hostname: Option.getOrUndefined(input.hostname),\n port: Option.getOrUndefined(input.port),\n cors: input.cors.length > 0 ? input.cors : undefined,\n })\n }),\n)\n" | ||
| ], | ||
| "mappings": ";unDAQA,sBAAS,gBAAa,0ECLtB,qBAKA,IAAM,EAAW,EAAO,eAAe,EAAQ,IAAI,EAC7C,GAAa,EAAO,aAAa,CAAQ,EACzC,GAAa,EAAO,oBAAoB,CAAQ,EAEzC,GAAW,EAAO,WAAW,SAAU,CAAC,EAMlD,CACD,IAAM,EAAK,MAAO,EAAW,WACvB,EAAO,EAAQ,KAAO,IAAM,EAAQ,GAAK,OAC/C,MAAO,EAAG,cAAc,GAAK,QAAQ,EAAQ,IAAI,EAAG,CAAE,UAAW,EAAK,CAAC,EACvE,IAAM,EAAO,CACX,GAAI,EAAQ,GACZ,QAAS,EACT,IAAK,EAAW,cAAc,EAAQ,OAAO,EAC7C,IAAK,QAAQ,IACb,SAAU,EAAQ,QACpB,EACM,EAAU,MAAO,GAAW,CAAI,EAChC,EAAU,EAAG,eAAe,EAAQ,IAAI,EAAE,KAAK,EAAO,QAAQ,EAAU,CAAC,EACzE,EAAO,CAAC,IACZ,EAAM,KAAO,EAAK,IAClB,EAAM,UAA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,QAAQ,MAAM,OAAO,EACjB,QAAQ,MAAM,eAAiB,QAAQ,MAAM,UAAW,EAAM,EAClE,OAAO,EAAO,KAAK,IAAM,CACvB,QAAQ,MAAM,IAAI,MAAO,CAAK,EAC9B,QAAQ,MAAM,IAAI,QAAS,CAAK,EAChC,QAAQ,MAAM,MAAM,EACrB,EACF,EIhNH,IAAe,MAAQ,QACrB,EAAS,SAAS,MAClB,EAAO,WAAW,SAAU,CAAC,EAAO,CAClC,GAAI,EAAM,SAAW,EAAM,MAAO,OAAO,MAAO,EAAO,KAAS,MAAM,0CAA0C,CAAC,EACjH,OAAO,MAAO,EAAc,IAAI,CAC9B,KAAM,EAAM,QAAU,UAAY,EAAM,MAAQ,QAAU,UAC1D,SAAU,EAAO,eAAe,EAAM,QAAQ,EAC9C,KAAM,EAAO,eAAe,EAAM,IAAI,EACtC,KAAM,EAAM,KAAK,OAAS,EAAI,EAAM,KAAO,MAC7C,CAAC,EACF,CACH", | ||
| "debugId": "0038A8AE4D4636E264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/run/run.ts", "src/run/noninteractive.ts", "src/run/ui.ts"], | ||
| "sourcesContent": [ | ||
| "import { Service, type Endpoint } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode, type OpenCodeClient, type SessionMessageAssistantTool } from \"@opencode-ai/client/promise\"\nimport { FSUtil } from \"@opencode-ai/util/fs-util\"\nimport { open } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { readStdin } from \"../util/io\"\nimport { ServerConnection } from \"../services/server-connection\"\nimport { parseSessionTargetModel, resolveSessionTarget } from \"../session-target\"\nimport { toolInlineInfo } from \"@opencode-ai/tui/mini/tool\"\nimport { runNonInteractivePrompt } from \"./noninteractive\"\nimport { UI } from \"./ui\"\nimport { Env } from \"../env\"\nimport { errorMessage } from \"../util/error\"\n\nexport type RunCommandInput = {\n server: ServerConnection.Resolved\n message: string[]\n continue?: boolean\n session?: string\n fork?: boolean\n model?: string\n agent?: string\n format: \"default\" | \"json\"\n file: string[]\n title?: string\n thinking?: boolean\n auto?: boolean\n}\n\ntype FilePart = {\n url: string\n filename: string\n mime: string\n}\n\ntype Prepared = {\n directory?: string\n message: string\n files: FilePart[]\n}\n\ntype ExecutionOptions = {\n root?: string\n directory?: string\n useServerDirectory?: boolean\n variant?: string\n attached?: boolean\n compatibility?: \"v1\"\n}\n\nclass RunTargetError extends Error {\n constructor(\n message: string,\n readonly sessionID?: string,\n ) {\n super(message)\n }\n}\n\nconst ATTACH_FILE_MAX_BYTES = 10 * 1024 * 1024\n\nexport function runNonInteractive(input: RunCommandInput) {\n return runNonInteractiveWithOptions(input, {})\n}\n\n/** @internal Used only by the V1 command boundary. */\nexport function runNonInteractiveWithOptions(input: RunCommandInput, options: ExecutionOptions) {\n return run(input, options).catch((error) => reportRunError(input, errorMessage(error)))\n}\n\nasync function run(input: RunCommandInput, options: ExecutionOptions) {\n if (input.fork && !input.continue && !input.session) fail(\"--fork requires --continue or --session\")\n const root = options.root ?? process.env.PWD ?? process.cwd()\n const local = localDirectory(root)\n const directory = options.useServerDirectory ? undefined : (options.directory ?? local)\n const message = mergeInput(formatMessage(input.message), process.stdin.isTTY ? undefined : await readStdin())\n if (!message?.trim()) fail(\"You must provide a message\")\n const files = await Promise.all(input.file.map((file) => prepareFile(file, root, options)))\n const prepared = { directory, message, files }\n return execute(input, prepared, input.server.endpoint, options)\n}\n\nasync function execute(input: RunCommandInput, prepared: Prepared, endpoint: Endpoint, options: ExecutionOptions) {\n const client = OpenCode.make({\n baseUrl: endpoint.url,\n headers: Service.headers(endpoint),\n // Bun's default five-minute deadline terminates the event stream used by long-running sessions.\n fetch: ((request: RequestInfo | URL, init?: RequestInit) =>\n fetch(request, { ...init, timeout: false } as BunFetchRequestInit)) as typeof fetch,\n })\n const explicit = parseRunModel(input.model)\n const target = await resolveSessionTarget({\n client,\n location: prepared.directory ? { directory: prepared.directory } : undefined,\n continue: input.continue,\n session: input.session,\n fork: input.fork,\n model: explicit\n ? { providerID: explicit.model.providerID, id: explicit.model.modelID, variant: explicit.variant }\n : undefined,\n agent: input.agent,\n environment: input.server.service ? Env.session() : undefined,\n prepare: async (next) => {\n const selected =\n next.model ??\n (options.variant\n ? await client.model\n .default({ location: { directory: next.location.directory, workspace: next.location.workspaceID } })\n .then((result) => result.data)\n : undefined)\n const model = selected\n ? {\n providerID: selected.providerID,\n id: selected.id,\n variant: options.variant ?? (\"variant\" in selected ? selected.variant : undefined),\n }\n : undefined\n if ((options.variant ?? explicit?.variant) && !model)\n throw new RunTargetError(\"Cannot select a variant before selecting a model\", next.session?.id)\n return { model, agent: next.agent }\n },\n }).catch((error) => {\n if (!(error instanceof RunTargetError)) throw error\n reportRunError(input, error.message, error.sessionID)\n return undefined\n })\n if (!target) return\n const model = target.model ? { providerID: target.model.providerID, modelID: target.model.id } : undefined\n const variant = target.model?.variant\n if (!target.resume && input.title !== undefined) {\n await client.session.rename({\n sessionID: target.session.id,\n title: input.title || prepared.message.slice(0, 50) + (prepared.message.length > 50 ? \"...\" : \"\"),\n })\n }\n\n await runNonInteractivePrompt({\n client,\n sessionID: target.session.id,\n location: target.location,\n message: prepared.message,\n files: prepared.files,\n agent: target.agent,\n model,\n variant,\n thinking: input.thinking ?? false,\n format: input.format,\n auto: input.auto ?? false,\n attached: options.attached ?? true,\n compatibility: options.compatibility,\n renderTool: (part) => renderTool(part, target.location.directory),\n renderToolError: (part) => renderToolError(part, target.location.directory),\n }).catch((error) => reportRunError(input, errorMessage(error), target.session.id))\n}\n\nexport function mergeInput(message: string | undefined, piped: string | undefined) {\n if (!message) return piped || undefined\n if (!piped) return message\n return message + \"\\n\" + piped\n}\n\nfunction formatMessage(message: string[]) {\n const value = message.map((part) => (part.includes(\" \") ? `\"${part.replace(/\"/g, '\\\\\"')}\"` : part)).join(\" \")\n return value || undefined\n}\n\nfunction localDirectory(root: string) {\n try {\n process.chdir(root)\n return process.cwd()\n } catch {\n fail(`Failed to change directory to ${root}`)\n }\n}\n\nexport function parseRunModel(value?: string) {\n const ref = parseSessionTargetModel(value)\n if (!ref) return\n return {\n model: { providerID: ref.providerID, modelID: ref.id },\n variant: ref.variant,\n }\n}\n\nasync function prepareFile(input: string, directory: string, options: ExecutionOptions): Promise<FilePart> {\n const file = path.resolve(directory, input)\n const handle = await open(file, \"r\").catch(() => fail(`File not found: ${input}`))\n try {\n const stat = await handle.stat()\n if (options.compatibility === \"v1\" && options.attached && stat.isDirectory())\n fail(`Cannot attach local directory without a shared filesystem: ${input}`)\n if (!stat.isFile() || stat.size > ATTACH_FILE_MAX_BYTES)\n fail(`Cannot attach a directory, special file, or file larger than 10 MiB: ${input}`)\n const content = Buffer.alloc(Number(stat.size))\n let offset = 0\n while (offset < content.length) {\n const read = await handle.read(content, offset, content.length - offset, offset)\n if (read.bytesRead === 0) break\n offset += read.bytesRead\n }\n const bytes = content.subarray(0, offset)\n const detected = FSUtil.mimeType(file)\n const text = bytes.toString(\"utf8\")\n const mime =\n detected.startsWith(\"image/\") || detected === \"application/pdf\"\n ? detected\n : !isBinaryContent(bytes) && Buffer.from(text, \"utf8\").equals(bytes)\n ? \"text/plain\"\n : detected\n return {\n url: `data:${mime};base64,${bytes.toString(\"base64\")}`,\n filename: path.basename(file),\n mime,\n }\n } finally {\n await handle.close()\n }\n}\n\nfunction isBinaryContent(bytes: Uint8Array) {\n if (bytes.length === 0) return false\n if (bytes.includes(0)) return true\n return bytes.reduce((count, byte) => count + Number(byte < 9 || (byte > 13 && byte < 32)), 0) / bytes.length > 0.3\n}\n\nasync function renderTool(part: SessionMessageAssistantTool, directory: string) {\n const info = toolInlineInfo(part, directory)\n if (info.mode === \"block\") {\n UI.empty()\n UI.println(UI.Style.TEXT_NORMAL + info.icon, UI.Style.TEXT_NORMAL + info.title)\n if (info.body?.trim()) UI.println(info.body)\n UI.empty()\n return\n }\n UI.println(\n UI.Style.TEXT_NORMAL + info.icon,\n UI.Style.TEXT_NORMAL + info.title,\n info.description ? UI.Style.TEXT_DIM + info.description + UI.Style.TEXT_NORMAL : \"\",\n )\n}\n\nasync function renderToolError(part: SessionMessageAssistantTool, directory: string) {\n const info = toolInlineInfo(part, directory)\n UI.println(UI.Style.TEXT_NORMAL + \"✗\", UI.Style.TEXT_NORMAL + `${info.title} failed`)\n}\n\n/** @internal Used by the V1 command boundary before a Session exists. */\nexport function reportRunError(input: Pick<RunCommandInput, \"format\">, message: string, sessionID?: string) {\n process.exitCode = 1\n if (input.format === \"json\") {\n process.stdout.write(\n JSON.stringify({\n type: \"error\",\n timestamp: Date.now(),\n sessionID: sessionID ?? \"\",\n error: { type: \"unknown\", message },\n }) + \"\\n\",\n )\n return\n }\n UI.error(message)\n}\n\nfunction fail(message: string): never {\n throw new Error(message)\n}\n", | ||
| "import type {\n EventSubscribeOutput,\n JsonValue,\n LocationRef,\n OpenCodeClient,\n SessionMessageAssistantTool,\n SessionMessageInfo,\n ToolContent,\n} from \"@opencode-ai/client/promise\"\nimport { SessionMessage } from \"@opencode-ai/schema/session-message\"\nimport { EOL } from \"node:os\"\nimport { readFile } from \"node:fs/promises\"\nimport { nonEmptyToolContent, toolOutputText, type MiniToolPart } from \"@opencode-ai/tui/mini/tool\"\nimport { UI } from \"./ui\"\n\ntype Model = {\n providerID: string\n modelID: string\n}\n\ntype File = {\n url: string\n filename: string\n mime: string\n}\n\ntype Input = {\n client: OpenCodeClient\n sessionID: string\n location: LocationRef\n message: string\n files: File[]\n agent?: string\n model?: Model\n variant?: string\n thinking: boolean\n format: \"default\" | \"json\"\n auto: boolean\n /** True when the client is attached to a shared server rather than an exclusive in-process one. */\n attached: boolean\n compatibility?: \"v1\"\n renderTool: (part: SessionMessageAssistantTool) => Promise<void>\n renderToolError: (part: SessionMessageAssistantTool) => Promise<void>\n}\n\ntype StartedPart = {\n id: string\n timestamp: number\n}\n\ntype ToolState = StartedPart & {\n assistantMessageID: string\n tool: string\n input: Record<string, JsonValue>\n raw?: string\n provider?: unknown\n providerState?: SessionMessageAssistantTool[\"providerState\"]\n metadata: Record<string, JsonValue>\n content: ToolContent[]\n}\n\ntype V2Event = EventSubscribeOutput\ntype FormRequest = Extract<V2Event, { type: \"form.created\" }>[\"data\"][\"form\"]\n\n// MCP elicitations are temporarily owned by the \"global\" sentinel instead of a real\n// session. An exclusive local process may treat them as this run's blockers; an\n// attached client must not cancel input that may belong to another session.\nconst GLOBAL_FORM_SESSION_ID = \"global\"\n\nexport async function runNonInteractivePrompt(input: Input) {\n const controller = new AbortController()\n const stream = input.client.event.subscribe({ signal: controller.signal })[Symbol.asyncIterator]()\n const connected = await stream.next()\n if (connected.done) throw new Error(\"Event stream disconnected before prompt admission\")\n\n const messageID = SessionMessage.ID.create()\n const starts = new Map<string, StartedPart>()\n const tools = new Map<string, ToolState>()\n const renderedText = new Map<string, string>()\n const renderedReasoning = new Map<string, string>()\n const renderedTools = new Set<string>()\n let submitted = false\n let promoted = false\n let emittedError = false\n let permissionRejected = false\n let formCancelled = false\n let interrupted = false\n let v1InvalidOutput = false\n let prePromotionError: { message: string; [key: string]: unknown } | undefined\n let finalizing = false\n let admission: AbortController | undefined\n let pendingStep: { timestamp: number; part: Record<string, unknown>; label: string } | undefined\n\n const emit = (type: string, timestamp: number, data: Record<string, unknown>) => {\n if (input.format !== \"json\") return false\n process.stdout.write(JSON.stringify({ type, timestamp, sessionID: input.sessionID, ...data }) + EOL)\n return true\n }\n\n const writeText = (part: { text: string; [key: string]: unknown }, timestamp: number) => {\n if (emit(\"text\", timestamp, { part })) return\n const text = part.text.trim()\n if (!text) return\n if (!process.stdout.isTTY) {\n process.stdout.write(text + EOL)\n return\n }\n UI.empty()\n UI.println(text)\n UI.empty()\n }\n\n const writeReasoning = (part: { text: string; [key: string]: unknown }, timestamp: number) => {\n if (emit(\"reasoning\", timestamp, { part })) return\n const text = part.text.trim()\n if (!text) return\n const line = `Thinking: ${text}`\n if (!process.stdout.isTTY) return void process.stdout.write(line + EOL)\n UI.empty()\n UI.println(`${UI.Style.TEXT_DIM}\\u001b[3m${line}\\u001b[0m${UI.Style.TEXT_NORMAL}`)\n UI.empty()\n }\n\n const flushStep = () => {\n if (!pendingStep) return\n const value = pendingStep\n pendingStep = undefined\n if (!emit(\"step_start\", value.timestamp, { part: value.part }) && input.format !== \"json\") {\n UI.empty()\n UI.println(value.label)\n UI.empty()\n }\n }\n\n const replyPermission = async (request: { id: string; action: string; resources: ReadonlyArray<string> }) => {\n if (!input.auto) {\n permissionRejected = true\n UI.println(\n UI.Style.TEXT_WARNING_BOLD + \"!\",\n UI.Style.TEXT_NORMAL +\n `permission requested: ${request.action} (${request.resources.join(\", \")}); auto-rejecting`,\n )\n }\n await input.client.permission\n .reply({\n sessionID: input.sessionID,\n requestID: request.id,\n reply: input.auto ? \"once\" : \"reject\",\n })\n .catch(() => {})\n if (!input.auto) {\n await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n }\n }\n\n const cancelForm = async (request: Pick<FormRequest, \"id\" | \"sessionID\">) => {\n try {\n await input.client.form.cancel(\n { sessionID: request.sessionID, formID: request.id },\n ...formRequestOptions(request.sessionID === GLOBAL_FORM_SESSION_ID ? input.location : undefined),\n )\n } catch (error) {\n if (!formAlreadySettled(error)) throw error\n }\n formCancelled = true\n }\n\n const consume = async () => {\n while (!controller.signal.aborted) {\n const next = await stream.next().catch((error) => {\n if (!emittedError) throw error\n return { done: true as const, value: undefined }\n })\n if (next.done) {\n if (emittedError) return\n throw new Error(\"Event stream disconnected during prompt execution\")\n }\n const event = next.value\n\n if (event.type === \"permission.asked\" && submitted && event.data.sessionID === input.sessionID) {\n await replyPermission(event.data)\n continue\n }\n if (\n event.type === \"form.created\" &&\n submitted &&\n (event.data.form.sessionID === input.sessionID ||\n (!input.attached &&\n event.data.form.sessionID === GLOBAL_FORM_SESSION_ID &&\n sameLocation(event.location, input.location)))\n ) {\n await cancelForm(event.data.form)\n continue\n }\n if (!(\"sessionID\" in event.data) || event.data.sessionID !== input.sessionID) continue\n const time = toMillis(\"created\" in event ? event.created : undefined)\n\n if (event.type === \"session.inbox.delivered\") {\n if (event.data.inboxID === messageID) {\n promoted = true\n prePromotionError = undefined\n continue\n }\n }\n if (\n event.type === \"session.execution.interrupted\" &&\n event.data.reason === \"user\" &&\n (interrupted || permissionRejected || formCancelled)\n ) {\n return\n }\n if (!promoted && event.type === \"session.execution.failed\") {\n prePromotionError = event.data.error\n if (finalizing) return\n continue\n }\n if (\n !promoted &&\n finalizing &&\n (event.type === \"session.execution.succeeded\" || event.type === \"session.execution.interrupted\")\n )\n return\n if (!promoted) continue\n if (finalizing && !event.type.startsWith(\"session.execution.\")) continue\n\n if (event.type === \"session.step.started\") {\n const part = {\n id: partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"step-start\",\n snapshot: event.data.snapshot,\n }\n if (input.compatibility === \"v1\") {\n pendingStep = {\n timestamp: time,\n part,\n label: `> ${event.data.agent} · ${event.data.model.id}`,\n }\n continue\n }\n if (!emit(\"step_start\", time, { part }) && input.format !== \"json\") {\n UI.empty()\n UI.println(`> ${event.data.agent} · ${event.data.model.id}`)\n UI.empty()\n }\n continue\n }\n\n if (event.type === \"session.text.started\") {\n flushStep()\n starts.set(`text\\u0000${contentKey(event.data.assistantMessageID, event.data.ordinal)}`, {\n id: partID(event.id),\n timestamp: time,\n })\n continue\n }\n if (event.type === \"session.text.ended\") {\n const key = contentKey(event.data.assistantMessageID, event.data.ordinal)\n const started = starts.get(`text\\u0000${key}`)\n starts.delete(`text\\u0000${key}`)\n const part = {\n id: started?.id ?? partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"text\",\n text: event.data.text,\n time: { start: started?.timestamp ?? time, end: time },\n }\n renderedText.set(key, event.data.text)\n writeText(part, time)\n continue\n }\n\n if (event.type === \"session.reasoning.started\") {\n flushStep()\n starts.set(`reasoning\\u0000${contentKey(event.data.assistantMessageID, event.data.ordinal)}`, {\n id: partID(event.id),\n timestamp: time,\n })\n continue\n }\n if (event.type === \"session.reasoning.ended\" && input.thinking) {\n const key = contentKey(event.data.assistantMessageID, event.data.ordinal)\n const started = starts.get(`reasoning\\u0000${key}`)\n starts.delete(`reasoning\\u0000${key}`)\n const part = {\n id: started?.id ?? partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"reasoning\",\n text: event.data.text,\n metadata: event.data.state,\n time: { start: started?.timestamp ?? time, end: time },\n }\n renderedReasoning.set(key, event.data.text)\n writeReasoning(part, time)\n continue\n }\n\n if (event.type === \"session.tool.input.started\") {\n flushStep()\n tools.set(toolKey(event.data.assistantMessageID, event.data.id), {\n id: partID(event.id),\n timestamp: time,\n assistantMessageID: event.data.assistantMessageID,\n tool: event.data.name,\n input: {},\n metadata: {},\n content: [],\n })\n continue\n }\n if (event.type === \"session.tool.input.ended\") {\n const current = tools.get(toolKey(event.data.assistantMessageID, event.data.id))\n if (current) current.raw = event.data.text\n continue\n }\n if (event.type === \"session.tool.input.delta\") {\n const current = tools.get(toolKey(event.data.assistantMessageID, event.data.id))\n if (current) current.raw = (current.raw ?? \"\") + event.data.delta\n continue\n }\n if (event.type === \"session.tool.called\") {\n flushStep()\n const key = toolKey(event.data.assistantMessageID, event.data.id)\n const current = tools.get(key)\n tools.set(key, {\n id: current?.id ?? partID(event.id),\n timestamp: current?.timestamp ?? time,\n assistantMessageID: event.data.assistantMessageID,\n tool: current?.tool ?? \"tool\",\n input: event.data.input,\n raw: current?.raw,\n provider: { executed: event.data.executed, state: event.data.state },\n providerState: event.data.state,\n metadata: {},\n content: [],\n })\n continue\n }\n if (event.type === \"session.tool.progress\") {\n const current = tools.get(toolKey(event.data.assistantMessageID, event.data.id))\n if (current) {\n current.metadata = event.data.metadata\n }\n continue\n }\n if (event.type === \"session.tool.success\") {\n const key = toolKey(event.data.assistantMessageID, event.data.id)\n const current = tools.get(key) ?? fallbackTool(event)\n const tool: SessionMessageAssistantTool = {\n type: \"tool\",\n id: event.data.id,\n name: current.tool,\n executed: event.data.executed,\n providerState: current.providerState,\n providerResultState: event.data.resultState,\n state: {\n status: \"completed\",\n input: current.input,\n metadata: event.data.metadata,\n content: event.data.content,\n },\n time: { created: current.timestamp, ran: current.timestamp, completed: time },\n }\n const part: MiniToolPart = {\n partID: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n id: event.data.id,\n tool: current.tool,\n state: {\n status: \"completed\",\n input: current.input,\n output: toolOutputText(current.tool, event.data.content),\n title: current.tool,\n metadata: {\n metadata: event.data.metadata,\n content: event.data.content,\n providerCall: current.provider,\n providerResult: { executed: event.data.executed, state: event.data.resultState },\n rawInput: current.raw,\n },\n time: { start: current.timestamp, end: time },\n },\n }\n tools.delete(key)\n renderedTools.add(key)\n if (!emit(\"tool_use\", time, { part })) await input.renderTool(tool)\n continue\n }\n if (event.type === \"session.tool.failed\") {\n const key = toolKey(event.data.assistantMessageID, event.data.id)\n const current = tools.get(key) ?? fallbackTool(event)\n const error = event.data.error.message\n const metadata = event.data.metadata ?? current.metadata\n const content = event.data.content ?? nonEmptyToolContent(current.content)\n const tool: SessionMessageAssistantTool = {\n type: \"tool\",\n id: event.data.id,\n name: current.tool,\n executed: event.data.executed,\n providerState: current.providerState,\n providerResultState: event.data.resultState,\n state: {\n status: \"error\",\n input: current.input,\n metadata,\n content,\n error: event.data.error,\n },\n time: { created: current.timestamp, ran: current.timestamp, completed: time },\n }\n const part: MiniToolPart = {\n partID: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n id: event.data.id,\n tool: current.tool,\n state: {\n status: \"error\",\n input: current.input,\n error,\n metadata: {\n providerCall: current.provider,\n providerResult: { executed: event.data.executed, state: event.data.resultState },\n rawInput: current.raw,\n },\n time: { start: current.timestamp, end: time },\n },\n }\n tools.delete(key)\n renderedTools.add(key)\n if (input.compatibility === \"v1\" && (permissionRejected || formCancelled)) continue\n if (!emit(\"tool_use\", time, { part })) {\n if (content && toolOutputText(current.tool, content).trim())\n await input.renderTool({\n ...tool,\n state: {\n status: \"completed\",\n input: current.input,\n metadata,\n content,\n },\n })\n await input.renderToolError(tool)\n UI.error(error)\n }\n continue\n }\n\n if (event.type === \"session.step.ended\") {\n flushStep()\n const part = {\n id: partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"step-finish\",\n reason: event.data.finish,\n snapshot: event.data.snapshot,\n cost: event.data.cost,\n tokens: event.data.tokens,\n }\n emit(\"step_finish\", time, { part })\n continue\n }\n if (event.type === \"session.step.failed\") {\n if (input.compatibility === \"v1\" && event.data.error.message === \"The provider response ended unexpectedly.\") {\n pendingStep = undefined\n v1InvalidOutput = true\n continue\n }\n if (interrupted || permissionRejected || formCancelled) continue\n flushStep()\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", time, { error: event.data.error })) UI.error(event.data.error.message)\n continue\n }\n if (event.type === \"session.execution.failed\") {\n if (input.compatibility === \"v1\" && (v1InvalidOutput || permissionRejected || formCancelled)) return\n flushStep()\n if (!emittedError && !formCancelled) {\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", time, { error: event.data.error })) UI.error(event.data.error.message)\n }\n return\n }\n if (event.type === \"session.execution.interrupted\") {\n if (input.compatibility === \"v1\" && (permissionRejected || formCancelled)) return\n if (event.data.reason === \"user\" && interrupted) process.exitCode = 130\n if (event.data.reason !== \"user\" && !emittedError) {\n emittedError = true\n process.exitCode = 1\n const error = { type: \"aborted\" as const, message: `Session interrupted: ${event.data.reason}` }\n if (!emit(\"error\", time, { error })) UI.error(error.message)\n }\n return\n }\n if (event.type === \"session.execution.succeeded\") return\n }\n }\n\n const projectedMessages = async () => {\n const messages: SessionMessageInfo[] = []\n let cursor: string | undefined\n while (true) {\n const page = await input.client.message.list(\n cursor\n ? { sessionID: input.sessionID, limit: 200, cursor }\n : { sessionID: input.sessionID, limit: 200, order: \"desc\" },\n )\n for (const message of page.data) {\n if (message.id === messageID) return { found: true, messages: messages.toReversed() }\n messages.push(message)\n }\n cursor = page.cursor.next ?? undefined\n if (!cursor) return { found: false, messages: [] }\n }\n }\n\n const reconcile = async () => {\n const projected = await projectedMessages()\n for (const message of projected.messages) {\n if (message.type !== \"assistant\") continue\n const timestamp = message.time.completed ?? message.time.created\n let textOrdinal = 0\n let reasoningOrdinal = 0\n for (const item of message.content) {\n if (item.type === \"text\") {\n const ordinal = textOrdinal++\n const key = contentKey(message.id, ordinal)\n const rendered = renderedText.get(key) ?? \"\"\n if (rendered === item.text || !item.text.startsWith(rendered)) continue\n const text = item.text.slice(rendered.length)\n writeText(\n {\n id: projectedPartID(message.id, `text-${ordinal}`),\n sessionID: input.sessionID,\n messageID: message.id,\n type: \"text\",\n text,\n time: { start: message.time.created, end: timestamp },\n },\n timestamp,\n )\n renderedText.set(key, item.text)\n continue\n }\n if (item.type === \"reasoning\") {\n const ordinal = reasoningOrdinal++\n if (!input.thinking) continue\n const key = contentKey(message.id, ordinal)\n const rendered = renderedReasoning.get(key) ?? \"\"\n if (rendered === item.text || !item.text.startsWith(rendered)) continue\n const text = item.text.slice(rendered.length)\n const part = {\n id: projectedPartID(message.id, `reasoning-${ordinal}`),\n sessionID: input.sessionID,\n messageID: message.id,\n type: \"reasoning\",\n text,\n metadata: item.state,\n time: { start: message.time.created, end: timestamp },\n }\n renderedReasoning.set(key, item.text)\n writeReasoning(part, timestamp)\n continue\n }\n\n const key = toolKey(message.id, item.id)\n if (renderedTools.has(key) || item.state.status === \"streaming\" || item.state.status === \"running\") continue\n const part: MiniToolPart = {\n partID: projectedPartID(message.id, `tool-${item.id}`),\n sessionID: input.sessionID,\n messageID: message.id,\n type: \"tool\",\n id: item.id,\n tool: item.name,\n state:\n item.state.status === \"completed\"\n ? {\n status: \"completed\",\n input: item.state.input,\n output: toolOutputText(item.name, item.state.content),\n title: item.name,\n metadata: { metadata: item.state.metadata, content: item.state.content },\n time: { start: item.time.ran ?? item.time.created, end: item.time.completed ?? timestamp },\n }\n : {\n status: \"error\",\n input: item.state.input,\n error: item.state.error.message,\n metadata: { metadata: item.state.metadata, content: item.state.content },\n time: { start: item.time.ran ?? item.time.created, end: item.time.completed ?? timestamp },\n },\n }\n renderedTools.add(key)\n if (emit(\"tool_use\", timestamp, { part })) continue\n if (item.state.status === \"completed\") {\n await input.renderTool(item)\n continue\n }\n if (item.state.content && toolOutputText(item.name, item.state.content).trim()) {\n await input.renderTool({\n ...item,\n state: {\n status: \"completed\",\n input: item.state.input,\n metadata: item.state.metadata,\n content: item.state.content,\n },\n })\n }\n await input.renderToolError(item)\n UI.error(item.state.error.message)\n }\n\n if (message.error && !emittedError) {\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", timestamp, { error: message.error })) UI.error(message.error.message)\n }\n }\n return {\n found: projected.found,\n responded: projected.messages.some((message) => message.type === \"assistant\"),\n }\n }\n\n const interrupt = () => {\n if (interrupted) process.exit(130)\n interrupted = true\n process.exitCode = 130\n admission?.abort()\n void input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n }\n process.on(\"SIGINT\", interrupt)\n\n let completed: Promise<void> | undefined\n try {\n if (input.agent) {\n await input.client.session.switchAgent({ sessionID: input.sessionID, agent: input.agent })\n }\n const selected = input.model\n ? { providerID: input.model.providerID, id: input.model.modelID, variant: input.variant }\n : input.variant\n ? await input.client.session\n .get({ sessionID: input.sessionID })\n .then((result) => result.model)\n .then(async (model) => {\n if (model) return { ...model, variant: input.variant }\n const result = await input.client.model.default()\n const fallback = result.data\n return fallback ? { providerID: fallback.providerID, id: fallback.id, variant: input.variant } : undefined\n })\n : undefined\n if (input.variant && !selected) throw new Error(\"Cannot select a variant before selecting a model\")\n if (selected) {\n await input.client.session.switchModel({ sessionID: input.sessionID, model: selected })\n }\n\n const prepared = await Promise.all(input.files.map(prepareFile))\n if (interrupted) return\n submitted = true\n completed = consume()\n admission = new AbortController()\n const response = await input.client.session\n .prompt(\n {\n sessionID: input.sessionID,\n id: messageID,\n text: [input.message, ...prepared.flatMap((file) => (file.text ? [file.text] : []))].join(\"\\n\\n\"),\n files: prepared.flatMap((file) => (file.attachment ? [file.attachment] : [])),\n delivery: \"steer\",\n },\n { signal: admission.signal },\n )\n .catch(async (error) => {\n if (interrupted) {\n await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n }\n controller.abort()\n await completed?.catch(() => {})\n if (interrupted || emittedError) return undefined\n throw error\n })\n admission = undefined\n if (!response) return\n if (interrupted) await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n\n const [permissions, forms, globals] = await Promise.all([\n input.client.permission.list({ sessionID: input.sessionID }).catch(() => undefined),\n input.client.form.list({ sessionID: input.sessionID }).catch(() => undefined),\n input.attached\n ? Promise.resolve(undefined)\n : input.client.form.request\n .list({\n location: { directory: input.location.directory, workspace: input.location.workspaceID },\n })\n .catch(() => undefined),\n ])\n await Promise.all([\n ...(permissions ?? []).map(replyPermission),\n ...(forms ?? []).map(cancelForm),\n ...(globals && sameLocation(globals.location, input.location)\n ? globals.data.filter((form) => form.sessionID === GLOBAL_FORM_SESSION_ID).map(cancelForm)\n : []),\n ])\n if (input.compatibility === \"v1\") {\n await completed\n return\n }\n\n const waiting = input.client.session.wait({ sessionID: input.sessionID })\n await Promise.race([waiting, completed.then(() => waiting)])\n finalizing = true\n const projected = await reconcile()\n if (\n !projected.responded &&\n !interrupted &&\n !permissionRejected &&\n !formCancelled &&\n !emittedError &&\n !prePromotionError\n ) {\n await completed\n }\n if (!projected.found && !interrupted && !permissionRejected && !formCancelled && !emittedError) {\n const error = prePromotionError ?? { type: \"unknown\", message: \"Prompt was not promoted\" }\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", Date.now(), { error })) UI.error(error.message)\n }\n } finally {\n process.off(\"SIGINT\", interrupt)\n controller.abort()\n if (input.compatibility === \"v1\") await stream.return?.(undefined).catch(() => {})\n else void stream.return?.(undefined).catch(() => {})\n }\n}\n\nfunction sameLocation(left: LocationRef | undefined, right: LocationRef) {\n return !!left && left.directory === right.directory && left.workspaceID === right.workspaceID\n}\n\nfunction formRequestOptions(location: LocationRef | undefined): [] | [{ headers: Record<string, string> }] {\n if (!location) return []\n return [\n {\n headers: {\n \"x-opencode-directory\": encodeURIComponent(location.directory),\n ...(location.workspaceID ? { \"x-opencode-workspace\": location.workspaceID } : {}),\n },\n },\n ]\n}\n\nfunction formAlreadySettled(error: unknown) {\n return !!error && typeof error === \"object\" && Reflect.get(error, \"_tag\") === \"FormAlreadySettledError\"\n}\n\nfunction partID(eventID: string) {\n return `prt_${eventID.replace(/^evt_/, \"\")}`\n}\n\nfunction toolKey(messageID: string, id: string) {\n return `${messageID}\\u0000${id}`\n}\n\nfunction contentKey(messageID: string, ordinal: number) {\n return `${messageID}\\u0000${ordinal}`\n}\n\nfunction projectedPartID(messageID: string, part: string) {\n return `prt_${messageID.replace(/^msg_/, \"\")}_${part}`\n}\n\nfunction fallbackTool(event: {\n id: string\n created: number\n data: { assistantMessageID: string; id: string }\n}): ToolState {\n return {\n id: partID(event.id),\n timestamp: toMillis(event.created),\n assistantMessageID: event.data.assistantMessageID,\n tool: \"tool\",\n input: {},\n metadata: {},\n content: [],\n }\n}\n\nfunction toMillis(value: unknown) {\n if (typeof value === \"number\") return value\n if (typeof value === \"string\") return new Date(value).getTime()\n return Date.now()\n}\n\nasync function prepareFile(file: File) {\n if (file.mime !== \"text/plain\") {\n const uri = file.url.startsWith(\"data:\")\n ? file.url\n : `data:${file.mime};base64,${(await readFile(new URL(file.url))).toString(\"base64\")}`\n return { attachment: { uri, name: file.filename } }\n }\n const content = file.url.startsWith(\"data:\")\n ? Buffer.from(file.url.slice(file.url.indexOf(\",\") + 1), \"base64\").toString(\"utf8\")\n : await readFile(new URL(file.url), \"utf8\")\n return { text: `<file name=\"${file.filename}\">\\n${content}\\n</file>` }\n}\n", | ||
| "import { EOL } from \"node:os\"\n\nexport const Style = {\n TEXT_DIM: \"\\x1b[90m\",\n TEXT_NORMAL: \"\\x1b[0m\",\n TEXT_WARNING_BOLD: \"\\x1b[93m\\x1b[1m\",\n TEXT_DANGER_BOLD: \"\\x1b[91m\\x1b[1m\",\n}\n\nexport function println(...message: string[]) {\n process.stderr.write(message.join(\" \") + EOL)\n}\n\nlet blank = false\n\nexport function empty() {\n if (blank) return\n println(Style.TEXT_NORMAL)\n blank = true\n}\n\nexport function error(message: string) {\n if (message.startsWith(\"Error: \")) message = message.slice(\"Error: \".length)\n println(Style.TEXT_DANGER_BOLD + \"Error: \" + Style.TEXT_NORMAL + message)\n}\n\nexport * as UI from \"./ui\"\n" | ||
| ], | ||
| "mappings": ";26CAGA,eAAS,qBACT,qBCMA,cAAS,WACT,mBAAS,mGCXT,cAAS,YAEF,IAAM,EAAQ,CACnB,SAAU,WACV,YAAa,UACb,kBAAmB,kBACnB,iBAAkB,iBACpB,EAEO,SAAS,CAAO,IAAI,EAAmB,CAC5C,QAAQ,OAAO,MAAM,EAAQ,KAAK,GAAG,EAAI,EAAG,EAG9C,IAAI,GAAQ,GAEL,SAAS,EAAK,EAAG,CACtB,GAAI,GAAO,OACX,EAAQ,EAAM,WAAW,EACzB,GAAQ,GAGH,SAAS,EAAK,CAAC,EAAiB,CACrC,GAAI,EAAQ,WAAW,SAAS,EAAG,EAAU,EAAQ,MAAM,CAAgB,EAC3E,EAAQ,EAAM,iBAAmB,UAAY,EAAM,YAAc,CAAO,ED4C1E,IAAM,EAAyB,SAE/B,eAAsB,EAAuB,CAAC,EAAc,CAC1D,IAAM,EAAa,IAAI,gBACjB,EAAS,EAAM,OAAO,MAAM,UAAU,CAAE,OAAQ,EAAW,MAAO,CAAC,EAAE,OAAO,eAAe,EAEjG,IADkB,MAAM,EAAO,KAAK,GACtB,KAAM,MAAU,MAAM,mDAAmD,EAEvF,IAAM,EAAY,GAAe,GAAG,OAAO,EACrC,EAAS,IAAI,IACb,EAAQ,IAAI,IACZ,EAAe,IAAI,IACnB,EAAoB,IAAI,IACxB,EAAgB,IAAI,IACtB,EAAY,GACZ,EAAW,GACX,EAAe,GACf,EAAqB,GACrB,EAAgB,GAChB,EA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AAG,MAAO,GAC9B,OAAO,EAAM,OAAO,CAAC,EAAO,IAAS,EAAQ,OAAO,EAAO,GAAM,EAAO,IAAM,EAAO,EAAG,EAAG,CAAC,EAAI,EAAM,OAAS,IAGjH,eAAe,EAAU,CAAC,EAAmC,EAAmB,CAC9E,IAAM,EAAO,EAAe,EAAM,CAAS,EAC3C,GAAI,EAAK,OAAS,QAAS,CAGzB,GAFA,EAAG,MAAM,EACT,EAAG,QAAQ,EAAG,MAAM,YAAc,EAAK,KAAM,EAAG,MAAM,YAAc,EAAK,KAAK,EAC1E,EAAK,MAAM,KAAK,EAAG,EAAG,QAAQ,EAAK,IAAI,EAC3C,EAAG,MAAM,EACT,OAEF,EAAG,QACD,EAAG,MAAM,YAAc,EAAK,KAC5B,EAAG,MAAM,YAAc,EAAK,MAC5B,EAAK,YAAc,EAAG,MAAM,SAAW,EAAK,YAAc,EAAG,MAAM,YAAc,EACnF,EAGF,eAAe,EAAe,CAAC,EAAmC,EAAmB,CACnF,IAAM,EAAO,EAAe,EAAM,CAAS,EAC3C,EAAG,QAAQ,EAAG,MAAM,YAAc,SAAK,EAAG,MAAM,YAAc,GAAG,EAAK,cAAc,EAI/E,SAAS,CAAc,CAAC,EAAwC,EAAiB,EAAoB,CAE1G,GADA,QAAQ,SAAW,EACf,EAAM,SAAW,OAAQ,CAC3B,QAAQ,OAAO,MACb,KAAK,UAAU,CACb,KAAM,QACN,UAAW,KAAK,IAAI,EACpB,UAAW,GAAa,GACxB,MAAO,CAAE,KAAM,UAAW,SAAQ,CACpC,CAAC,EAAI;AAAA,CACP,EACA,OAEF,EAAG,MAAM,CAAO,EAGlB,SAAS,CAAI,CAAC,EAAwB,CACpC,MAAU,MAAM,CAAO", | ||
| "debugId": "C3B93531FA00D50764756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "466416BA0DD5739664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/version.ts"], | ||
| "sourcesContent": [ | ||
| "declare const OPENCODE_VERSION: string\ndeclare const OPENCODE_CHANNEL: string\n\nconst version = typeof OPENCODE_VERSION === \"string\" ? OPENCODE_VERSION : \"local\"\nconst channel = typeof OPENCODE_CHANNEL === \"string\" ? OPENCODE_CHANNEL : \"local\"\n\nexport { version as OPENCODE_VERSION, channel as OPENCODE_CHANNEL }\nexport const OPENCODE_LOCAL = channel === \"local\"\n" | ||
| ], | ||
| "mappings": ";AAGA,IAAM,EAAiD,kBACjD,EAAiD,MAGhD,IAAM,EAAiB", | ||
| "debugId": "7F267EECA4DE65EA64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+cohere@3.0.27+d6123d32214422cb/node_modules/@ai-sdk/cohere/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/cohere-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n generateId,\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/cohere-chat-language-model.ts\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonResponseHandler,\n parseProviderOptions,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z3 } from \"zod/v4\";\n\n// src/cohere-chat-options.ts\nimport { z } from \"zod/v4\";\nvar cohereLanguageModelOptions = z.object({\n /**\n * Configuration for reasoning features (optional)\n *\n * Can be set to an object with the two properties `type` and `tokenBudget`. `type` can be set to `'enabled'` or `'disabled'` (defaults to `'enabled'`).\n * `tokenBudget` is the maximum number of tokens the model can use for thinking, which must be set to a positive integer. The model will stop thinking if it reaches the thinking token budget and will proceed with the response\n *\n * @see https://docs.cohere.com/reference/chat#request.body.thinking\n */\n thinking: z.object({\n type: z.enum([\"enabled\", \"disabled\"]).optional(),\n tokenBudget: z.number().optional()\n }).optional()\n});\n\n// src/cohere-error.ts\nimport { createJsonErrorResponseHandler } from \"@ai-sdk/provider-utils\";\nimport { z as z2 } from \"zod/v4\";\nvar cohereErrorDataSchema = z2.object({\n message: z2.string()\n});\nvar cohereFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: cohereErrorDataSchema,\n errorToMessage: (data) => data.message\n});\n\n// src/cohere-prepare-tools.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\nfunction prepareTools({\n tools,\n toolChoice\n}) {\n tools = (tools == null ? void 0 : tools.length) ? tools : void 0;\n const toolWarnings = [];\n if (tools == null) {\n return { tools: void 0, toolChoice: void 0, toolWarnings };\n }\n const cohereTools = [];\n for (const tool of tools) {\n if (tool.type === \"provider\") {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `provider-defined tool ${tool.id}`\n });\n } else {\n cohereTools.push({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema\n }\n });\n }\n }\n if (toolChoice == null) {\n return { tools: cohereTools, toolChoice: void 0, toolWarnings };\n }\n const type = toolChoice.type;\n switch (type) {\n case \"auto\":\n return { tools: cohereTools, toolChoice: void 0, toolWarnings };\n case \"none\":\n return { tools: cohereTools, toolChoice: \"NONE\", toolWarnings };\n case \"required\":\n return { tools: cohereTools, toolChoice: \"REQUIRED\", toolWarnings };\n case \"tool\":\n return {\n tools: cohereTools.filter(\n (tool) => tool.function.name === toolChoice.toolName\n ),\n toolChoice: \"REQUIRED\",\n toolWarnings\n };\n default: {\n const _exhaustiveCheck = type;\n throw new UnsupportedFunctionalityError({\n functionality: `tool choice type: ${_exhaustiveCheck}`\n });\n }\n }\n}\n\n// src/convert-cohere-usage.ts\nfunction convertCohereUsage(tokens) {\n if (tokens == null) {\n return {\n inputTokens: {\n total: void 0,\n noCache: void 0,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: void 0,\n text: void 0,\n reasoning: void 0\n },\n raw: void 0\n };\n }\n const inputTokens = tokens.input_tokens;\n const outputTokens = tokens.output_tokens;\n return {\n inputTokens: {\n total: inputTokens,\n noCache: inputTokens,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: outputTokens,\n text: outputTokens,\n reasoning: void 0\n },\n raw: tokens\n };\n}\n\n// src/convert-to-cohere-chat-prompt.ts\nimport {\n UnsupportedFunctionalityError as UnsupportedFunctionalityError2\n} from \"@ai-sdk/provider\";\nfunction convertToCohereChatPrompt(prompt) {\n const messages = [];\n const documents = [];\n const warnings = [];\n for (const { role, content } of prompt) {\n switch (role) {\n case \"system\": {\n messages.push({ role: \"system\", content });\n break;\n }\n case \"user\": {\n messages.push({\n role: \"user\",\n content: content.map((part) => {\n var _a;\n switch (part.type) {\n case \"text\": {\n return part.text;\n }\n case \"file\": {\n let textContent;\n if (typeof part.data === \"string\") {\n textContent = part.data;\n } else if (part.data instanceof Uint8Array) {\n if (!(((_a = part.mediaType) == null ? void 0 : _a.startsWith(\"text/\")) || part.mediaType === \"application/json\")) {\n throw new UnsupportedFunctionalityError2({\n functionality: `document media type: ${part.mediaType}`,\n message: `Media type '${part.mediaType}' is not supported. Supported media types are: text/* and application/json.`\n });\n }\n textContent = new TextDecoder().decode(part.data);\n } else {\n throw new UnsupportedFunctionalityError2({\n functionality: \"File URL data\",\n message: \"URLs should be downloaded by the AI SDK and not reach this point. This indicates a configuration issue.\"\n });\n }\n documents.push({\n data: {\n text: textContent,\n title: part.filename\n }\n });\n return \"\";\n }\n }\n }).join(\"\")\n });\n break;\n }\n case \"assistant\": {\n let text = \"\";\n const toolCalls = [];\n for (const part of content) {\n switch (part.type) {\n case \"text\": {\n text += part.text;\n break;\n }\n case \"tool-call\": {\n toolCalls.push({\n id: part.toolCallId,\n type: \"function\",\n function: {\n name: part.toolName,\n arguments: JSON.stringify(part.input)\n }\n });\n break;\n }\n }\n }\n messages.push({\n role: \"assistant\",\n content: toolCalls.length > 0 ? void 0 : text,\n tool_calls: toolCalls.length > 0 ? toolCalls : void 0,\n tool_plan: void 0\n });\n break;\n }\n case \"tool\": {\n messages.push(\n ...content.filter((toolResult) => toolResult.type !== \"tool-approval-response\").map((toolResult) => {\n var _a;\n const output = toolResult.output;\n let contentValue;\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n contentValue = output.value;\n break;\n case \"execution-denied\":\n contentValue = (_a = output.reason) != null ? _a : \"Tool execution denied.\";\n break;\n case \"content\":\n case \"json\":\n case \"error-json\":\n contentValue = JSON.stringify(output.value);\n break;\n }\n return {\n role: \"tool\",\n content: contentValue,\n tool_call_id: toolResult.toolCallId\n };\n })\n );\n break;\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return { messages, documents, warnings };\n}\n\n// src/map-cohere-finish-reason.ts\nfunction mapCohereFinishReason(finishReason) {\n switch (finishReason) {\n case \"COMPLETE\":\n case \"STOP_SEQUENCE\":\n return \"stop\";\n case \"MAX_TOKENS\":\n return \"length\";\n case \"ERROR\":\n return \"error\";\n case \"TOOL_CALL\":\n return \"tool-calls\";\n default:\n return \"other\";\n }\n}\n\n// src/cohere-chat-language-model.ts\nvar CohereChatLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.supportedUrls = {\n // No URLs are supported.\n };\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n async getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n tools,\n toolChoice,\n providerOptions\n }) {\n var _a, _b;\n const cohereOptions = (_a = await parseProviderOptions({\n provider: \"cohere\",\n providerOptions,\n schema: cohereLanguageModelOptions\n })) != null ? _a : {};\n const {\n messages: chatPrompt,\n documents: cohereDocuments,\n warnings: promptWarnings\n } = convertToCohereChatPrompt(prompt);\n const {\n tools: cohereTools,\n toolChoice: cohereToolChoice,\n toolWarnings\n } = prepareTools({ tools, toolChoice });\n return {\n args: {\n // model id:\n model: this.modelId,\n // standardized settings:\n frequency_penalty: frequencyPenalty,\n presence_penalty: presencePenalty,\n max_tokens: maxOutputTokens,\n temperature,\n p: topP,\n k: topK,\n seed,\n stop_sequences: stopSequences,\n // response format:\n response_format: (responseFormat == null ? void 0 : responseFormat.type) === \"json\" ? { type: \"json_object\", json_schema: responseFormat.schema } : void 0,\n // messages:\n messages: chatPrompt,\n // tools:\n tools: cohereTools,\n tool_choice: cohereToolChoice,\n // documents for RAG:\n ...cohereDocuments.length > 0 && { documents: cohereDocuments },\n // reasoning\n ...cohereOptions.thinking && {\n thinking: {\n type: (_b = cohereOptions.thinking.type) != null ? _b : \"enabled\",\n token_budget: cohereOptions.thinking.tokenBudget\n }\n }\n },\n warnings: [...toolWarnings, ...promptWarnings]\n };\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e, _f, _g;\n const { args, warnings } = await this.getArgs(options);\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: `${this.config.baseURL}/chat`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body: args,\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n cohereChatResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const content = [];\n for (const item of (_a = response.message.content) != null ? _a : []) {\n if (item.type === \"text\" && item.text.length > 0) {\n content.push({ type: \"text\", text: item.text });\n continue;\n }\n if (item.type === \"thinking\" && item.thinking.length > 0) {\n content.push({ type: \"reasoning\", text: item.thinking });\n continue;\n }\n }\n for (const citation of (_b = response.message.citations) != null ? _b : []) {\n content.push({\n type: \"source\",\n sourceType: \"document\",\n id: this.config.generateId(),\n mediaType: \"text/plain\",\n title: ((_d = (_c = citation.sources[0]) == null ? void 0 : _c.document) == null ? void 0 : _d.title) || \"Document\",\n providerMetadata: {\n cohere: {\n start: citation.start,\n end: citation.end,\n text: citation.text,\n sources: citation.sources,\n ...citation.type && { citationType: citation.type }\n }\n }\n });\n }\n for (const toolCall of (_e = response.message.tool_calls) != null ? _e : []) {\n content.push({\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n // Cohere sometimes returns `null` for tool call arguments for tools\n // defined as having no arguments.\n input: toolCall.function.arguments.replace(/^null$/, \"{}\")\n });\n }\n return {\n content,\n finishReason: {\n unified: mapCohereFinishReason(response.finish_reason),\n raw: (_f = response.finish_reason) != null ? _f : void 0\n },\n usage: convertCohereUsage(response.usage.tokens),\n request: { body: args },\n response: {\n // TODO timestamp, model id\n id: (_g = response.generation_id) != null ? _g : void 0,\n headers: responseHeaders,\n body: rawResponse\n },\n warnings\n };\n }\n async doStream(options) {\n const { args, warnings } = await this.getArgs(options);\n const { responseHeaders, value: response } = await postJsonToApi({\n url: `${this.config.baseURL}/chat`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body: { ...args, stream: true },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(\n cohereChatChunkSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n let usage = void 0;\n let pendingToolCall = null;\n let isActiveReasoning = false;\n return {\n stream: response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n var _a, _b;\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n finishReason = { unified: \"error\", raw: void 0 };\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n const type = value.type;\n switch (type) {\n case \"content-start\": {\n if (value.delta.message.content.type === \"thinking\") {\n controller.enqueue({\n type: \"reasoning-start\",\n id: String(value.index)\n });\n isActiveReasoning = true;\n return;\n }\n controller.enqueue({\n type: \"text-start\",\n id: String(value.index)\n });\n return;\n }\n case \"content-delta\": {\n if (\"thinking\" in value.delta.message.content) {\n controller.enqueue({\n type: \"reasoning-delta\",\n id: String(value.index),\n delta: value.delta.message.content.thinking\n });\n return;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: String(value.index),\n delta: value.delta.message.content.text\n });\n return;\n }\n case \"content-end\": {\n if (isActiveReasoning) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: String(value.index)\n });\n isActiveReasoning = false;\n return;\n }\n controller.enqueue({\n type: \"text-end\",\n id: String(value.index)\n });\n return;\n }\n case \"tool-call-start\": {\n const toolId = value.delta.message.tool_calls.id;\n const toolName = value.delta.message.tool_calls.function.name;\n const initialArgs = value.delta.message.tool_calls.function.arguments;\n pendingToolCall = {\n id: toolId,\n name: toolName,\n arguments: initialArgs,\n hasFinished: false\n };\n controller.enqueue({\n type: \"tool-input-start\",\n id: toolId,\n toolName\n });\n if (initialArgs.length > 0) {\n controller.enqueue({\n type: \"tool-input-delta\",\n id: toolId,\n delta: initialArgs\n });\n }\n return;\n }\n case \"tool-call-delta\": {\n if (pendingToolCall && !pendingToolCall.hasFinished) {\n const argsDelta = value.delta.message.tool_calls.function.arguments;\n pendingToolCall.arguments += argsDelta;\n controller.enqueue({\n type: \"tool-input-delta\",\n id: pendingToolCall.id,\n delta: argsDelta\n });\n }\n return;\n }\n case \"tool-call-end\": {\n if (pendingToolCall && !pendingToolCall.hasFinished) {\n controller.enqueue({\n type: \"tool-input-end\",\n id: pendingToolCall.id\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: pendingToolCall.id,\n toolName: pendingToolCall.name,\n input: JSON.stringify(\n JSON.parse(((_a = pendingToolCall.arguments) == null ? void 0 : _a.trim()) || \"{}\")\n )\n });\n pendingToolCall.hasFinished = true;\n pendingToolCall = null;\n }\n return;\n }\n case \"message-start\": {\n controller.enqueue({\n type: \"response-metadata\",\n id: (_b = value.id) != null ? _b : void 0\n });\n return;\n }\n case \"message-end\": {\n finishReason = {\n unified: mapCohereFinishReason(value.delta.finish_reason),\n raw: value.delta.finish_reason\n };\n usage = value.delta.usage.tokens;\n return;\n }\n default: {\n return;\n }\n }\n },\n flush(controller) {\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertCohereUsage(usage)\n });\n }\n })\n ),\n request: { body: { ...args, stream: true } },\n response: { headers: responseHeaders }\n };\n }\n};\nvar cohereChatResponseSchema = z3.object({\n generation_id: z3.string().nullish(),\n message: z3.object({\n role: z3.string(),\n content: z3.array(\n z3.union([\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"thinking\"),\n thinking: z3.string()\n })\n ])\n ).nullish(),\n tool_plan: z3.string().nullish(),\n tool_calls: z3.array(\n z3.object({\n id: z3.string(),\n type: z3.literal(\"function\"),\n function: z3.object({\n name: z3.string(),\n arguments: z3.string()\n })\n })\n ).nullish(),\n citations: z3.array(\n z3.object({\n start: z3.number(),\n end: z3.number(),\n text: z3.string(),\n sources: z3.array(\n z3.object({\n type: z3.string().optional(),\n id: z3.string().optional(),\n document: z3.object({\n id: z3.string().optional(),\n text: z3.string(),\n title: z3.string()\n })\n })\n ),\n type: z3.string().optional()\n })\n ).nullish()\n }),\n finish_reason: z3.string(),\n usage: z3.object({\n billed_units: z3.object({\n input_tokens: z3.number(),\n output_tokens: z3.number()\n }),\n tokens: z3.object({\n input_tokens: z3.number(),\n output_tokens: z3.number()\n })\n })\n});\nvar cohereChatChunkSchema = z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"citation-start\")\n }),\n z3.object({\n type: z3.literal(\"citation-end\")\n }),\n z3.object({\n type: z3.literal(\"content-start\"),\n index: z3.number(),\n delta: z3.object({\n message: z3.object({\n content: z3.union([\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"thinking\"),\n thinking: z3.string()\n })\n ])\n })\n })\n }),\n z3.object({\n type: z3.literal(\"content-delta\"),\n index: z3.number(),\n delta: z3.object({\n message: z3.object({\n content: z3.union([\n z3.object({\n text: z3.string()\n }),\n z3.object({\n thinking: z3.string()\n })\n ])\n })\n })\n }),\n z3.object({\n type: z3.literal(\"content-end\"),\n index: z3.number()\n }),\n z3.object({\n type: z3.literal(\"message-start\"),\n id: z3.string().nullish()\n }),\n z3.object({\n type: z3.literal(\"message-end\"),\n delta: z3.object({\n finish_reason: z3.string(),\n usage: z3.object({\n tokens: z3.object({\n input_tokens: z3.number(),\n output_tokens: z3.number()\n })\n })\n })\n }),\n // https://docs.cohere.com/v2/docs/streaming#tool-use-stream-events-for-tool-calling\n z3.object({\n type: z3.literal(\"tool-plan-delta\"),\n delta: z3.object({\n message: z3.object({\n tool_plan: z3.string()\n })\n })\n }),\n z3.object({\n type: z3.literal(\"tool-call-start\"),\n delta: z3.object({\n message: z3.object({\n tool_calls: z3.object({\n id: z3.string(),\n type: z3.literal(\"function\"),\n function: z3.object({\n name: z3.string(),\n arguments: z3.string()\n })\n })\n })\n })\n }),\n // A single tool call's `arguments` stream in chunks and must be accumulated\n // in a string and so the full tool object info can only be parsed once we see\n // `tool-call-end`.\n z3.object({\n type: z3.literal(\"tool-call-delta\"),\n delta: z3.object({\n message: z3.object({\n tool_calls: z3.object({\n function: z3.object({\n arguments: z3.string()\n })\n })\n })\n })\n }),\n z3.object({\n type: z3.literal(\"tool-call-end\")\n })\n]);\n\n// src/cohere-embedding-model.ts\nimport {\n TooManyEmbeddingValuesForCallError\n} from \"@ai-sdk/provider\";\nimport {\n combineHeaders as combineHeaders2,\n createJsonResponseHandler as createJsonResponseHandler2,\n parseProviderOptions as parseProviderOptions2,\n postJsonToApi as postJsonToApi2\n} from \"@ai-sdk/provider-utils\";\nimport { z as z5 } from \"zod/v4\";\n\n// src/cohere-embedding-options.ts\nimport { z as z4 } from \"zod/v4\";\nvar cohereEmbeddingModelOptions = z4.object({\n /**\n * Specifies the type of input passed to the model. Default is `search_query`.\n *\n * - \"search_document\": Used for embeddings stored in a vector database for search use-cases.\n * - \"search_query\": Used for embeddings of search queries run against a vector DB to find relevant documents.\n * - \"classification\": Used for embeddings passed through a text classifier.\n * - \"clustering\": Used for embeddings run through a clustering algorithm.\n */\n inputType: z4.enum([\"search_document\", \"search_query\", \"classification\", \"clustering\"]).optional(),\n /**\n * Specifies how the API will handle inputs longer than the maximum token length.\n * Default is `END`.\n *\n * - \"NONE\": If selected, when the input exceeds the maximum input token length will return an error.\n * - \"START\": Will discard the start of the input until the remaining input is exactly the maximum input token length for the model.\n * - \"END\": Will discard the end of the input until the remaining input is exactly the maximum input token length for the model.\n */\n truncate: z4.enum([\"NONE\", \"START\", \"END\"]).optional(),\n /**\n * The number of dimensions of the output embedding.\n * Only available for `embed-v4.0` and newer models.\n *\n * Possible values are `256`, `512`, `1024`, and `1536`.\n * The default is `1536`.\n */\n outputDimension: z4.union([z4.literal(256), z4.literal(512), z4.literal(1024), z4.literal(1536)]).optional()\n});\n\n// src/cohere-embedding-model.ts\nvar CohereEmbeddingModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.maxEmbeddingsPerCall = 96;\n this.supportsParallelCalls = true;\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n async doEmbed({\n values,\n headers,\n abortSignal,\n providerOptions\n }) {\n var _a;\n const embeddingOptions = await parseProviderOptions2({\n provider: \"cohere\",\n providerOptions,\n schema: cohereEmbeddingModelOptions\n });\n if (values.length > this.maxEmbeddingsPerCall) {\n throw new TooManyEmbeddingValuesForCallError({\n provider: this.provider,\n modelId: this.modelId,\n maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,\n values\n });\n }\n const {\n responseHeaders,\n value: response,\n rawValue\n } = await postJsonToApi2({\n url: `${this.config.baseURL}/embed`,\n headers: combineHeaders2(this.config.headers(), headers),\n body: {\n model: this.modelId,\n // The AI SDK only supports 'float' embeddings. Note that the Cohere API\n // supports other embedding types, but they are not currently supported by the AI SDK.\n // https://docs.cohere.com/v2/reference/embed#request.body.embedding_types\n embedding_types: [\"float\"],\n texts: values,\n input_type: (_a = embeddingOptions == null ? void 0 : embeddingOptions.inputType) != null ? _a : \"search_query\",\n truncate: embeddingOptions == null ? void 0 : embeddingOptions.truncate,\n output_dimension: embeddingOptions == null ? void 0 : embeddingOptions.outputDimension\n },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler2(\n cohereTextEmbeddingResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n warnings: [],\n embeddings: response.embeddings.float,\n usage: { tokens: response.meta.billed_units.input_tokens },\n response: { headers: responseHeaders, body: rawValue }\n };\n }\n};\nvar cohereTextEmbeddingResponseSchema = z5.object({\n embeddings: z5.object({\n float: z5.array(z5.array(z5.number()))\n }),\n meta: z5.object({\n billed_units: z5.object({\n input_tokens: z5.number()\n })\n })\n});\n\n// src/reranking/cohere-reranking-model.ts\nimport {\n combineHeaders as combineHeaders3,\n createJsonResponseHandler as createJsonResponseHandler3,\n parseProviderOptions as parseProviderOptions3,\n postJsonToApi as postJsonToApi3\n} from \"@ai-sdk/provider-utils\";\n\n// src/reranking/cohere-reranking-api.ts\nimport { lazySchema, zodSchema } from \"@ai-sdk/provider-utils\";\nimport { z as z6 } from \"zod/v4\";\nvar cohereRerankingResponseSchema = lazySchema(\n () => zodSchema(\n z6.object({\n id: z6.string().nullish(),\n results: z6.array(\n z6.object({\n index: z6.number(),\n relevance_score: z6.number()\n })\n ),\n meta: z6.any()\n })\n )\n);\n\n// src/reranking/cohere-reranking-options.ts\nimport { lazySchema as lazySchema2, zodSchema as zodSchema2 } from \"@ai-sdk/provider-utils\";\nimport { z as z7 } from \"zod/v4\";\nvar cohereRerankingModelOptionsSchema = lazySchema2(\n () => zodSchema2(\n z7.object({\n maxTokensPerDoc: z7.number().optional(),\n priority: z7.number().optional()\n })\n )\n);\n\n// src/reranking/cohere-reranking-model.ts\nvar CohereRerankingModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n // current implementation is based on v2 of the API: https://docs.cohere.com/v2/reference/rerank\n async doRerank({\n documents,\n headers,\n query,\n topN,\n abortSignal,\n providerOptions\n }) {\n var _a;\n const rerankingOptions = await parseProviderOptions3({\n provider: \"cohere\",\n providerOptions,\n schema: cohereRerankingModelOptionsSchema\n });\n const warnings = [];\n if (documents.type === \"object\") {\n warnings.push({\n type: \"compatibility\",\n feature: \"object documents\",\n details: \"Object documents are converted to strings.\"\n });\n }\n const {\n responseHeaders,\n value: response,\n rawValue\n } = await postJsonToApi3({\n url: `${this.config.baseURL}/rerank`,\n headers: combineHeaders3(this.config.headers(), headers),\n body: {\n model: this.modelId,\n query,\n documents: documents.type === \"text\" ? documents.values : documents.values.map((value) => JSON.stringify(value)),\n top_n: topN,\n max_tokens_per_doc: rerankingOptions == null ? void 0 : rerankingOptions.maxTokensPerDoc,\n priority: rerankingOptions == null ? void 0 : rerankingOptions.priority\n },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler3(\n cohereRerankingResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n ranking: response.results.map((result) => ({\n index: result.index,\n relevanceScore: result.relevance_score\n })),\n warnings,\n response: {\n id: (_a = response.id) != null ? _a : void 0,\n headers: responseHeaders,\n body: rawValue\n }\n };\n }\n};\n\n// src/version.ts\nvar VERSION = true ? \"3.0.27\" : \"0.0.0-test\";\n\n// src/cohere-provider.ts\nfunction createCohere(options = {}) {\n var _a;\n const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : \"https://api.cohere.com/v2\";\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"COHERE_API_KEY\",\n description: \"Cohere\"\n })}`,\n ...options.headers\n },\n `ai-sdk/cohere/${VERSION}`\n );\n const createChatModel = (modelId) => {\n var _a2;\n return new CohereChatLanguageModel(modelId, {\n provider: \"cohere.chat\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n generateId: (_a2 = options.generateId) != null ? _a2 : generateId\n });\n };\n const createEmbeddingModel = (modelId) => new CohereEmbeddingModel(modelId, {\n provider: \"cohere.textEmbedding\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch\n });\n const createRerankingModel = (modelId) => new CohereRerankingModel(modelId, {\n provider: \"cohere.reranking\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch\n });\n const provider = function(modelId) {\n if (new.target) {\n throw new Error(\n \"The Cohere model function cannot be called with the new keyword.\"\n );\n }\n return createChatModel(modelId);\n };\n provider.specificationVersion = \"v3\";\n provider.languageModel = createChatModel;\n provider.embedding = createEmbeddingModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbedding = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n provider.reranking = createRerankingModel;\n provider.rerankingModel = createRerankingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar cohere = createCohere();\nexport {\n VERSION,\n cohere,\n createCohere\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";gaAuBA,IAAI,EAA6B,EAAE,OAAO,CASxC,SAAU,EAAE,OAAO,CACjB,KAAM,EAAE,KAAK,CAAC,UAAW,UAAU,CAAC,EAAE,SAAS,EAC/C,YAAa,EAAE,OAAO,EAAE,SAAS,CACnC,CAAC,EAAE,SAAS,CACd,CAAC,EAKG,EAAwB,EAAG,OAAO,CACpC,QAAS,EAAG,OAAO,CACrB,CAAC,EACG,EAA8B,EAA+B,CAC/D,YAAa,EACb,eAAgB,CAAC,IAAS,EAAK,OACjC,CAAC,EAMD,SAAS,CAAY,EACnB,QACA,cACC,CACD,GAAS,GAAS,KAAY,OAAI,EAAM,QAAU,EAAa,OAC/D,I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AAM,KAAO,EAAK,4BACtE,EAAa,IAAM,EACvB,CACE,cAAe,UAAU,EAAW,CAClC,OAAQ,EAAQ,OAChB,wBAAyB,iBACzB,YAAa,QACf,CAAC,OACE,EAAQ,OACb,EACA,iBAAiB,IACnB,EACM,EAAkB,CAAC,IAAY,CACnC,IAAI,EACJ,OAAO,IAAI,EAAwB,EAAS,CAC1C,SAAU,cACV,UACA,QAAS,EACT,MAAO,EAAQ,MACf,YAAa,EAAM,EAAQ,aAAe,KAAO,EAAM,CACzD,CAAC,GAEG,EAAuB,CAAC,IAAY,IAAI,EAAqB,EAAS,CAC1E,SAAU,uBACV,UACA,QAAS,EACT,MAAO,EAAQ,KACjB,CAAC,EACK,EAAuB,CAAC,IAAY,IAAI,GAAqB,EAAS,CAC1E,SAAU,mBACV,UACA,QAAS,EACT,MAAO,EAAQ,KACjB,CAAC,EACK,EAAW,QAAQ,CAAC,EAAS,CACjC,GAAI,WACF,MAAU,MACR,kEACF,EAEF,OAAO,EAAgB,CAAO,GAahC,OAXA,EAAS,qBAAuB,KAChC,EAAS,cAAgB,EACzB,EAAS,UAAY,EACrB,EAAS,eAAiB,EAC1B,EAAS,cAAgB,EACzB,EAAS,mBAAqB,EAC9B,EAAS,UAAY,EACrB,EAAS,eAAiB,EAC1B,EAAS,WAAa,CAAC,IAAY,CACjC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,YAAa,CAAC,GAE1D,EAET,IAAI,GAAS,GAAa", | ||
| "debugId": "763517242871D62764756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
+1
-1
| { | ||
| "name": "@opencode-ai/cli-linux-x64", | ||
| "version": "0.0.0-dev-18842", | ||
| "version": "0.0.0-dev-18847", | ||
| "license": "MIT", | ||
@@ -5,0 +5,0 @@ "repository": { |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/ai-gateway-provider@3.1.2+cd874a64d6146f19/node_modules/ai-gateway-provider/dist/providers/unified.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/providers/unified.ts\nimport { createOpenAICompatible } from \"@ai-sdk/openai-compatible\";\nvar createUnified = (arg) => {\n return createOpenAICompatible({\n baseURL: \"https://gateway.ai.cloudflare.com/v1/compat\",\n // intercepted and replaced with actual base URL later\n name: \"Unified\",\n ...arg || {}\n });\n};\nvar unified = createUnified();\nexport {\n createUnified,\n unified\n};\n//# sourceMappingURL=unified.mjs.map" | ||
| ], | ||
| "mappings": ";qUAEA,IAAI,EAAgB,CAAC,IACZ,EAAuB,CAC5B,QAAS,8CAET,KAAM,aACH,GAAO,CAAC,CACb,CAAC,EAEC,EAAU,EAAc", | ||
| "debugId": "27634B47AD0D39F864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/remove.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { readFile, rename, writeFile } from \"node:fs/promises\"\nimport { Effect } from \"effect\"\nimport { applyEdits, modify, parse, type ParseError } from \"jsonc-parser\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Config } from \"../../../config\"\nimport { resolveConfigPath } from \"../mcp/add\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.remove,\n Effect.fn(\"cli.plugin.remove\")(function* (input) {\n const global = yield* Global.Service\n const configPath = yield* Effect.promise(() => resolveConfigPath(global.config))\n const server = yield* Effect.promise(() => removePluginConfig(configPath, input.package))\n const config = yield* Config.Service\n const info = yield* config.get()\n const tui = configured(info.plugins, input.package)\n if (tui)\n yield* config.update((draft) => {\n draft.plugins = draft.plugins?.filter((entry) => !matches(entry, input.package))\n })\n\n const removed = [server ? configPath : undefined, tui ? config.path : undefined].filter(\n (file) => file !== undefined,\n )\n process.stdout.write(\n removed.length\n ? `Plugin \"${input.package}\" removed from ${removed.join(\", \")}${EOL}`\n : `Plugin \"${input.package}\" is not configured${EOL}`,\n )\n }),\n)\n\nexport async function removePluginConfig(configPath: string, spec: string) {\n const text = await readFile(configPath, \"utf8\").catch((error) => {\n if (typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\") return undefined\n throw error\n })\n if (text === undefined) return false\n const errors: ParseError[] = []\n const config: unknown = parse(text, errors, { allowTrailingComma: true })\n if (errors.length || typeof config !== \"object\" || config === null || Array.isArray(config))\n throw new Error(`Invalid global configuration: ${configPath}`)\n const plugins = \"plugins\" in config ? config.plugins : undefined\n if (plugins !== undefined && !Array.isArray(plugins)) throw new Error(`Invalid plugins configuration: ${configPath}`)\n if (!configured(plugins, spec)) return false\n\n const updated = applyEdits(\n text,\n modify(\n text,\n [\"plugins\"],\n plugins?.filter((entry) => !matches(entry, spec)),\n {\n formattingOptions: { tabSize: 2, insertSpaces: true },\n },\n ),\n )\n const temporary = configPath + \".tmp\"\n await writeFile(temporary, updated.endsWith(\"\\n\") ? updated : updated + \"\\n\", { mode: 0o600 })\n await rename(temporary, configPath)\n return true\n}\n\nfunction configured(plugins: readonly unknown[] | undefined, spec: string) {\n return plugins?.some((entry) => matches(entry, spec)) ?? false\n}\n\nfunction matches(entry: unknown, spec: string) {\n return entry === spec || (typeof entry === \"object\" && entry !== null && \"package\" in entry && entry.package === spec)\n}\n" | ||
| ], | ||
| "mappings": ";wvBAAA,cAAS,WAET,mBAAS,YAAU,eAAQ,oBAS3B,IAAe,IAAQ,QACrB,EAAS,SAAS,OAAO,SAAS,OAClC,EAAO,GAAG,mBAAmB,EAAE,SAAU,CAAC,EAAO,CAC/C,IAAM,EAAS,MAAO,EAAO,QACvB,EAAa,MAAO,EAAO,QAAQ,IAAM,EAAkB,EAAO,MAAM,CAAC,EACzE,EAAS,MAAO,EAAO,QAAQ,IAAM,EAAmB,EAAY,EAAM,OAAO,CAAC,EAClF,EAAS,MAAO,EAAO,QACvB,EAAO,MAAO,EAAO,IAAI,EACzB,EAAM,EAAW,EAAK,QAAS,EAAM,O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;AAAA,EAAM,CAAE,KAAM,GAAM,CAAC,EAC7F,MAAM,EAAO,EAAW,CAAU,EAC3B,GAGT,SAAS,CAAU,CAAC,EAAyC,EAAc,CACzE,OAAO,GAAS,KAAK,CAAC,IAAU,EAAQ,EAAO,CAAI,CAAC,GAAK,GAG3D,SAAS,CAAO,CAAC,EAAgB,EAAc,CAC7C,OAAO,IAAU,GAAS,OAAO,IAAU,UAAY,IAAU,MAAQ,YAAa,GAAS,EAAM,UAAY", | ||
| "debugId": "2F749EB998F6558164756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/websearch.ts", "../schema/src/reference.ts", "../schema/src/command.ts"], | ||
| "sourcesContent": [ | ||
| "export * as WebSearch from \"./websearch.js\"\n\nimport { Schema } from \"effect\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { optional } from \"./schema.js\"\n\nexport const ID = Schema.String.pipe(Schema.brand(\"WebSearch.ID\"))\nexport type ID = typeof ID.Type\n\nexport interface Provider extends Schema.Schema.Type<typeof Provider> {}\nexport const Provider = Schema.Struct({\n id: ID,\n name: Schema.String,\n}).annotate({ identifier: \"WebSearch.Provider\" })\n\nexport interface Input extends Schema.Schema.Type<typeof Input> {}\nexport const Input = Schema.Struct({\n query: Schema.String,\n providerID: ID.pipe(optional),\n}).annotate({ identifier: \"WebSearch.Input\" })\nexport type ProviderInput = Pick<Input, \"query\">\n\nexport interface Result extends Schema.Schema.Type<typeof Result> {}\nexport const Result = Schema.Struct({\n url: Schema.String,\n title: Schema.String.pipe(optional),\n content: Schema.String.pipe(optional),\n time: Schema.Struct({\n published: Schema.Finite.pipe(optional),\n }),\n}).annotate({ identifier: \"WebSearch.Result\" })\n\nexport class Response extends Schema.Class<Response>(\"WebSearch.Response\")({\n providerID: ID,\n results: Schema.Array(Result),\n}) {}\n\nconst Updated = ephemeral({\n type: \"websearch.updated\",\n schema: {},\n})\nexport const Event = { Updated, Definitions: inventory(Updated) }\n", | ||
| "export * as Reference from \"./reference.js\"\n\nimport { Schema } from \"effect\"\nimport { optional } from \"./schema.js\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { AbsolutePath } from \"./schema.js\"\n\nconst Updated = ephemeral({ type: \"reference.updated\", schema: {} })\nexport const Event = { Updated, Definitions: inventory(Updated) }\n\nexport interface LocalSource extends Schema.Schema.Type<typeof LocalSource> {}\nexport const LocalSource = Schema.Struct({\n type: Schema.Literal(\"local\"),\n path: AbsolutePath,\n description: Schema.String.pipe(optional),\n hidden: Schema.Boolean.pipe(optional),\n}).annotate({ identifier: \"Reference.LocalSource\" })\n\nexport interface GitSource extends Schema.Schema.Type<typeof GitSource> {}\nexport const GitSource = Schema.Struct({\n type: Schema.Literal(\"git\"),\n repository: Schema.String,\n branch: Schema.String.pipe(optional),\n description: Schema.String.pipe(optional),\n hidden: Schema.Boolean.pipe(optional),\n}).annotate({ identifier: \"Reference.GitSource\" })\n\nexport const Source = Schema.Union([LocalSource, GitSource])\n .pipe(Schema.toTaggedUnion(\"type\"))\n .annotate({ identifier: \"Reference.Source\" })\nexport type Source = typeof Source.Type\n\nexport const Info = Schema.Struct({\n name: Schema.String,\n path: AbsolutePath,\n description: Schema.String.pipe(optional),\n hidden: Schema.Boolean.pipe(optional),\n source: Source,\n}).annotate({ identifier: \"Reference.Info\" })\nexport interface Info extends Schema.Schema.Type<typeof Info> {}\n", | ||
| "export * as Command from \"./command.js\"\n\nimport { Schema } from \"effect\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { optional } from \"./schema.js\"\n\nconst Updated = ephemeral({ type: \"command.updated\", schema: {} })\n\nexport interface Info extends Schema.Schema.Type<typeof Info> {}\nexport const Info = Schema.Struct({\n name: Schema.String,\n description: Schema.String.pipe(optional),\n}).annotate({ identifier: \"Command.Info\" })\n\nexport const Event = {\n Updated,\n Definitions: inventory(Updated),\n}\n" | ||
| ], | ||
| "mappings": ";4UAMO,IAAM,EAAK,EAAO,OAAO,KA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AAQ,CACtC,CAAC,EAAE,SAAS,CAAE,WAAY,qBAAsB,CAAC,EAEpC,EAAS,EAAO,MAAM,CAAC,EAAa,CAAS,CAAC,EACxD,KAAK,EAAO,cAAc,MAAM,CAAC,EACjC,SAAS,CAAE,WAAY,kBAAmB,CAAC,EAGjC,EAAO,EAAO,OAAO,CAChC,KAAM,EAAO,OACb,KAAM,EACN,YAAa,EAAO,OAAO,KAAK,CAAQ,EACxC,OAAQ,EAAO,QAAQ,KAAK,CAAQ,EACpC,OAAQ,CACV,CAAC,EAAE,SAAS,CAAE,WAAY,gBAAiB,CAAC,uDChC5C,IAAM,EAAU,EAAU,CAAE,KAAM,kBAAmB,OAAQ,CAAC,CAAE,CAAC,EAGpD,EAAO,EAAO,OAAO,CAChC,KAAM,EAAO,OACb,YAAa,EAAO,OAAO,KAAK,CAAQ,CAC1C,CAAC,EAAE,SAAS,CAAE,WAAY,cAAe,CAAC,EAE7B,EAAQ,CACnB,UACA,YAAa,EAAU,CAAO,CAChC", | ||
| "debugId": "D980C9385653641A64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-login@3.972.76/node_modules/@aws-sdk/credential-provider-login/dist-es/fromLoginCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-login@3.972.76/node_modules/@aws-sdk/credential-provider-login/dist-es/LoginCredentialsFetcher.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError, getProfileName, parseKnownFiles } from \"@smithy/core/config\";\nimport { LoginCredentialsFetcher } from \"./LoginCredentialsFetcher\";\nexport const fromLoginCredentials = (init) => async ({ callerClientConfig } = {}) => {\n init?.logger?.debug?.(\"@aws-sdk/credential-providers - fromLoginCredentials\");\n const profiles = await parseKnownFiles(init || {});\n const profileName = getProfileName({\n profile: init?.profile ?? callerClientConfig?.profile,\n });\n const profile = profiles[profileName];\n if (!profile?.login_session) {\n throw new CredentialsProviderError(`Profile ${profileName} does not contain login_session.`, {\n tryNextLink: true,\n logger: init?.logger,\n });\n }\n const fetcher = new LoginCredentialsFetcher(profile, init, callerClientConfig);\n const credentials = await fetcher.loadCredentials();\n return setCredentialFeature(credentials, \"CREDENTIALS_LOGIN\", \"AD\");\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { HttpRequest } from \"@smithy/core/protocols\";\nimport { createHash, createPrivateKey, createPublicKey, sign } from \"node:crypto\";\nimport { promises as fs } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nexport class LoginCredentialsFetcher {\n profileData;\n init;\n callerClientConfig;\n static REFRESH_THRESHOLD = 5 * 60 * 1000;\n constructor(profileData, init, callerClientConfig) {\n this.profileData = profileData;\n this.init = init;\n this.callerClientConfig = callerClientConfig;\n }\n async loadCredentials() {\n const token = await this.loadToken();\n if (!token) {\n throw new CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`, { tryNextLink: false, logger: this.logger });\n }\n const accessToken = token.accessToken;\n const now = Date.now();\n const expiryTime = new Date(accessToken.expiresAt).getTime();\n const timeUntilExpiry = expiryTime - now;\n if (timeUntilExpiry <= LoginCredentialsFetcher.REFRESH_THRESHOLD) {\n return this.refresh(token);\n }\n return this.toCredentials(token.accessToken);\n }\n get logger() {\n return this.init?.logger;\n }\n get loginSession() {\n return this.profileData.login_session;\n }\n toCredentials(token) {\n return {\n accessKeyId: token.accessKeyId,\n secretAccessKey: token.secretAccessKey,\n sessionToken: token.sessionToken,\n accountId: token.accountId,\n expiration: new Date(token.expiresAt),\n };\n }\n async refresh(token) {\n const diskToken = await this.loadToken().catch(() => token);\n const now = Date.now();\n const diskExpiry = new Date(diskToken.accessToken.expiresAt).getTime();\n const tokenExpiry = new Date(token.accessToken.expiresAt).getTime();\n const freshToken = diskExpiry <= now && tokenExpiry > now ? token : diskToken;\n const freshExpiry = new Date(freshToken.accessToken.expiresAt).getTime();\n if (freshExpiry - Date.now() > LoginCredentialsFetcher.REFRESH_THRESHOLD) {\n return this.toCredentials(freshToken.accessToken);\n }\n const { SigninClient, CreateOAuth2TokenCommand } = await import(\"@aws-sdk/nested-clients/signin\");\n const { logger, userAgentAppId } = this.callerClientConfig ?? {};\n const isH2 = (requestHandler) => {\n return requestHandler?.metadata?.handlerProtocol === \"h2\";\n };\n const requestHandler = isH2(this.callerClientConfig?.requestHandler)\n ? undefined\n : this.callerClientConfig?.requestHandler;\n const region = this.profileData.region ?? (await this.callerClientConfig?.region?.()) ?? process.env.AWS_REGION;\n const client = new SigninClient({\n credentials: {\n accessKeyId: \"\",\n secretAccessKey: \"\",\n },\n region,\n requestHandler,\n logger,\n userAgentAppId,\n ...this.init?.clientConfig,\n });\n this.createDPoPInterceptor(client.middlewareStack);\n const commandInput = {\n tokenInput: {\n clientId: freshToken.clientId,\n refreshToken: freshToken.refreshToken,\n grantType: \"refresh_token\",\n },\n };\n try {\n const response = await client.send(new CreateOAuth2TokenCommand(commandInput));\n const { accessKeyId, secretAccessKey, sessionToken } = response.tokenOutput?.accessToken ?? {};\n const { refreshToken, expiresIn } = response.tokenOutput ?? {};\n if (!accessKeyId || !secretAccessKey || !sessionToken || !refreshToken) {\n throw new CredentialsProviderError(\"Token refresh response missing required fields\", {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n const expiresInMs = (expiresIn ?? 900) * 1000;\n const expiration = new Date(Date.now() + expiresInMs);\n const updatedToken = {\n ...freshToken,\n accessToken: {\n ...freshToken.accessToken,\n accessKeyId,\n secretAccessKey,\n sessionToken,\n expiresAt: expiration.toISOString(),\n },\n refreshToken,\n };\n await this.saveToken(updatedToken);\n return this.toCredentials(updatedToken.accessToken);\n }\n catch (error) {\n if (error.name === \"AccessDeniedException\") {\n const errorType = error.error;\n let message;\n switch (errorType) {\n case \"TOKEN_EXPIRED\":\n message = \"Your session has expired. Please reauthenticate.\";\n break;\n case \"USER_CREDENTIALS_CHANGED\":\n message =\n \"Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.\";\n break;\n case \"INSUFFICIENT_PERMISSIONS\":\n message =\n \"Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.\";\n break;\n default:\n message = `Failed to refresh token: ${String(error)}. Please re-authenticate using \\`aws login\\``;\n }\n throw new CredentialsProviderError(message, {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n const tokenExpiry = new Date(freshToken.accessToken.expiresAt).getTime();\n if (tokenExpiry > Date.now()) {\n this.logger?.warn?.(`Failed to refresh token: ${String(error)}. Using existing token until expiry.`);\n return this.toCredentials(freshToken.accessToken);\n }\n throw new CredentialsProviderError(`Failed to refresh token: ${String(error)}. Please re-authenticate using aws login`, { logger: this.logger });\n }\n }\n async loadToken() {\n const tokenFilePath = this.getTokenFilePath();\n try {\n const tokenData = await fs.readFile(tokenFilePath, \"utf8\");\n const token = JSON.parse(tokenData);\n const missingFields = [\"accessToken\", \"clientId\", \"refreshToken\", \"dpopKey\"].filter((k) => !token[k]);\n if (!token.accessToken?.accountId) {\n missingFields.push(\"accountId\");\n }\n if (missingFields.length > 0) {\n throw new CredentialsProviderError(`Token validation failed, missing fields: ${missingFields.join(\", \")}`, {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n return token;\n }\n catch (error) {\n throw new CredentialsProviderError(`Failed to load token from ${tokenFilePath}: ${String(error)}`, {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n }\n async saveToken(token) {\n const tokenFilePath = this.getTokenFilePath();\n const directory = dirname(tokenFilePath);\n try {\n await fs.mkdir(directory, { recursive: true });\n }\n catch (error) {\n }\n await fs.writeFile(tokenFilePath, JSON.stringify(token, null, 2), \"utf8\");\n }\n getTokenFilePath() {\n const directory = process.env.AWS_LOGIN_CACHE_DIRECTORY ?? join(homedir(), \".aws\", \"login\", \"cache\");\n const loginSessionBytes = Buffer.from(this.loginSession, \"utf8\");\n const loginSessionSha256 = createHash(\"sha256\").update(loginSessionBytes).digest(\"hex\");\n return join(directory, `${loginSessionSha256}.json`);\n }\n derToRawSignature(derSignature) {\n let offset = 2;\n if (derSignature[offset] !== 0x02) {\n throw new Error(\"Invalid DER signature\");\n }\n offset++;\n const rLength = derSignature[offset++];\n let r = derSignature.subarray(offset, offset + rLength);\n offset += rLength;\n if (derSignature[offset] !== 0x02) {\n throw new Error(\"Invalid DER signature\");\n }\n offset++;\n const sLength = derSignature[offset++];\n let s = derSignature.subarray(offset, offset + sLength);\n r = r[0] === 0x00 ? r.subarray(1) : r;\n s = s[0] === 0x00 ? s.subarray(1) : s;\n const rPadded = Buffer.concat([Buffer.alloc(32 - r.length), r]);\n const sPadded = Buffer.concat([Buffer.alloc(32 - s.length), s]);\n return Buffer.concat([rPadded, sPadded]);\n }\n createDPoPInterceptor(middlewareStack) {\n middlewareStack.add((next) => async (args) => {\n if (HttpRequest.isInstance(args.request)) {\n const request = args.request;\n const actualEndpoint = `${request.protocol}//${request.hostname}${request.port ? `:${request.port}` : \"\"}${request.path}`;\n const dpop = await this.generateDpop(request.method, actualEndpoint);\n request.headers = {\n ...request.headers,\n DPoP: dpop,\n };\n }\n return next(args);\n }, {\n step: \"finalizeRequest\",\n name: \"dpopInterceptor\",\n override: true,\n });\n }\n async generateDpop(method = \"POST\", endpoint) {\n const token = await this.loadToken();\n try {\n const privateKey = createPrivateKey({\n key: token.dpopKey,\n format: \"pem\",\n type: \"sec1\",\n });\n const publicKey = createPublicKey(privateKey);\n const publicDer = publicKey.export({ format: \"der\", type: \"spki\" });\n let pointStart = -1;\n for (let i = 0; i < publicDer.length; i++) {\n if (publicDer[i] === 0x04) {\n pointStart = i;\n break;\n }\n }\n const x = publicDer.slice(pointStart + 1, pointStart + 33);\n const y = publicDer.slice(pointStart + 33, pointStart + 65);\n const header = {\n alg: \"ES256\",\n typ: \"dpop+jwt\",\n jwk: {\n kty: \"EC\",\n crv: \"P-256\",\n x: x.toString(\"base64url\"),\n y: y.toString(\"base64url\"),\n },\n };\n const payload = {\n jti: crypto.randomUUID(),\n htm: method,\n htu: endpoint,\n iat: Math.floor(Date.now() / 1000),\n };\n const headerB64 = Buffer.from(JSON.stringify(header)).toString(\"base64url\");\n const payloadB64 = Buffer.from(JSON.stringify(payload)).toString(\"base64url\");\n const message = `${headerB64}.${payloadB64}`;\n const asn1Signature = sign(\"sha256\", Buffer.from(message), privateKey);\n const rawSignature = this.derToRawSignature(asn1Signature);\n const signatureB64 = rawSignature.toString(\"base64url\");\n return `${message}.${signatureB64}`;\n }\n catch (error) {\n throw new CredentialsProviderError(`Failed to generate Dpop proof: ${error instanceof Error ? error.message : String(error)}`, { logger: this.logger, tryNextLink: false });\n }\n }\n}\n" | ||
| ], | ||
| "mappings": ";gNAAA,eACA,WCDA,eACA,WACA,qBAAS,sBAAY,qBAAkB,UAAiB,eACxD,mBAAS,WACT,kBAAS,WACT,kBAAS,UAAS,aACX,MAAM,CAAwB,CACjC,YACA,KACA,yBACO,mBAAoB,OAC3B,WAAW,CAAC,EAAa,EAAM,EAAoB,CAC/C,KAAK,YAAc,EACnB,KAAK,KAAO,EACZ,KAAK,mBAAqB,OAExB,gBAAe,EAAG,CACpB,IAAM,EAAQ,MAAM,KAAK,UAAU,EACnC,GAAI,CAAC,EACD,MAAM,IAAI,2BAAyB,sCAAsC,KAAK,uDAAwD,CAAE,YAAa,GAAO,OAAQ,KAAK,MAAO,CAAC,EAErL,IAAM,EAAc,EAAM,YACpB,EAAM,KAAK,IAAI,EAGrB,GAFmB,IAAI,KAAK,EAAY,SAAS,EAAE,QAAQ,EACtB,GACd,EAAwB,kBAC3C,OAAO,KAAK,QAAQ,CAAK,EAE7B,OAAO,KAAK,cAAc,EAAM,WAAW,KAE3C,OAAM,EAAG,CACT,OAAO,KAAK,MAAM,UAElB,aAAY,EAAG,CACf,OAAO,KAAK,YAAY,cAE5B,aAAa,CAAC,EAAO,CACjB,MAAO,CACH,YAAa,EAAM,YACnB,gBAAiB,EAAM,gBACvB,aAAc,EAAM,aAC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OAAO,KAAK,CAAO,EAAG,CAAU,EAE/D,EADe,KAAK,kBAAkB,CAAa,EACvB,SAAS,WAAW,EACtD,MAAO,GAAG,KAAW,IAEzB,MAAO,EAAO,CACV,MAAM,IAAI,2BAAyB,kCAAkC,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,IAAK,CAAE,OAAQ,KAAK,OAAQ,YAAa,EAAM,CAAC,GAGtL,CDxQO,IAAM,EAAuB,CAAC,IAAS,OAAS,sBAAuB,CAAC,IAAM,CACjF,GAAM,QAAQ,QAAQ,sDAAsD,EAC5E,IAAM,EAAW,MAAM,kBAAgB,GAAQ,CAAC,CAAC,EAC3C,EAAc,iBAAe,CAC/B,QAAS,GAAM,SAAW,GAAoB,OAClD,CAAC,EACK,EAAU,EAAS,GACzB,GAAI,CAAC,GAAS,cACV,MAAM,IAAI,2BAAyB,WAAW,oCAA+C,CACzF,YAAa,GACb,OAAQ,GAAM,MAClB,CAAC,EAGL,IAAM,EAAc,MADJ,IAAI,EAAwB,EAAS,EAAM,CAAkB,EAC3C,gBAAgB,EAClD,OAAO,uBAAqB,EAAa,oBAAqB,IAAI", | ||
| "debugId": "07BF31DC23331A0264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/run.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nexport default Runtime.handler(Commands.commands.run, (input) =>\n Effect.gen(function* () {\n const { runNonInteractive } = yield* Effect.promise(() => import(\"../../run/run\"))\n const separator = process.argv.indexOf(\"--\", 2)\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n yield* Effect.promise(() =>\n runNonInteractive({\n server,\n message: [...input.message, ...(separator === -1 ? [] : process.argv.slice(separator + 1))],\n continue: input.continue,\n session: Option.getOrUndefined(input.session),\n fork: input.fork,\n model: Option.getOrUndefined(input.model),\n agent: Option.getOrUndefined(input.agent),\n format: input.format,\n file: [...input.file],\n title: Option.getOrUndefined(input.title),\n thinking: input.thinking,\n auto: input.auto || input.yolo || input.dangerouslySkipPermissions,\n }),\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";0jCAKA,IAAe,IAAQ,QAAQ,EAAS,SAAS,IAAK,CAAC,IACrD,EAAO,IAAI,SAAU,EAAG,CACtB,IAAQ,qBAAsB,MAAO,EAAO,QAAQ,IAAa,wCAAgB,EAC3E,EAAY,QAAQ,KAAK,QAAQ,KAAM,CAAC,EACxC,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EACD,MAAO,EAAO,QAAQ,IACpB,EAAkB,CAChB,SACA,QAAS,CAAC,GAAG,EAAM,QAAS,GAAI,IAAc,GAAK,CAAC,EAAI,QAAQ,KAAK,MAAM,EAAY,CAAC,CAAE,EAC1F,SAAU,EAAM,SAChB,QAAS,EAAO,eAAe,EAAM,OAAO,EAC5C,KAAM,EAAM,KACZ,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,OAAQ,EAAM,OACd,KAAM,CAAC,GAAG,EAAM,IAAI,EACpB,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,SAAU,EAAM,SAChB,KAAM,EAAM,MAAQ,EAAM,MAAQ,EAAM,0BAC1C,CAAC,CACH,EACD,CACH", | ||
| "debugId": "943C1B8F13DE53A164756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/export.ts"], | ||
| "sourcesContent": [ | ||
| "import { autocomplete, cancel, intro, isCancel, log, outro } from \"@clack/prompts\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, Option } from \"effect\"\nimport { EOL } from \"node:os\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\nimport { errorMessage } from \"../../util/error\"\n\nexport default Runtime.handler(\n Commands.commands.export,\n Effect.fn(\"cli.export\")((input) =>\n Effect.gen(function* () {\n const requested = Option.getOrUndefined(input.session)\n if (!requested && !process.stdin.isTTY) {\n yield* Effect.fail(new Error(\"Pass a session ID when running without an interactive terminal\"))\n }\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({\n baseUrl: server.endpoint.url,\n headers: Service.headers(server.endpoint),\n })\n const sessionID = requested\n ? requested\n : yield* Effect.gen(function* () {\n intro(\"Export session\", { output: process.stderr })\n const location = yield* Effect.tryPromise({\n try: () => client.location.get({ location: { directory: process.cwd() } }),\n catch: (cause) => cause,\n })\n const page = yield* Effect.tryPromise({\n try: () =>\n client.session.list({\n directory: location.directory,\n workspace: location.workspaceID,\n parentID: null,\n order: \"desc\",\n limit: 50,\n }),\n catch: (cause) => cause,\n })\n if (page.data.length === 0) {\n log.error(\"No sessions found\", { output: process.stderr })\n outro(\"Done\", { output: process.stderr })\n return undefined\n }\n const selected = yield* Effect.tryPromise({\n try: () =>\n autocomplete({\n message: \"Select session to export\",\n maxItems: 10,\n options: page.data.map((session) => ({\n label: session.title,\n value: session.id,\n hint: `${new Date(session.time.updated).toLocaleString()} - ${session.id.slice(-8)}`,\n })),\n output: process.stderr,\n }),\n catch: (cause) => cause,\n })\n if (isCancel(selected)) {\n cancel(\"Cancelled\", { output: process.stderr })\n process.exitCode = 130\n return undefined\n }\n outro(\"Exporting session...\", { output: process.stderr })\n return selected\n })\n if (!sessionID) return\n const data = yield* Effect.tryPromise({\n try: () => client.session.export({ sessionID, sanitize: input.sanitize }),\n catch: (cause) => cause,\n })\n process.stdout.write(JSON.stringify(data, null, 2) + EOL)\n }).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n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ACV,QAAS,EAAK,KAAK,IAAI,CAAC,KAAa,CACnC,MAAO,EAAQ,MACf,MAAO,EAAQ,GACf,KAAM,GAAG,IAAI,KAAK,EAAQ,KAAK,OAAO,EAAE,eAAe,OAAO,EAAQ,GAAG,MAAM,EAAE,GACnF,EAAE,EACF,OAAQ,QAAQ,MAClB,CAAC,EACH,MAAO,CAAC,IAAU,CACpB,CAAC,EACD,GAAI,EAAS,CAAQ,EAAG,CACtB,EAAO,YAAa,CAAE,OAAQ,QAAQ,MAAO,CAAC,EAC9C,QAAQ,SAAW,IACnB,OAGF,OADA,EAAM,uBAAwB,CAAE,OAAQ,QAAQ,MAAO,CAAC,EACjD,EACR,EACL,GAAI,CAAC,EAAW,OAChB,IAAM,EAAO,MAAO,EAAO,WAAW,CACpC,IAAK,IAAM,EAAO,QAAQ,OAAO,CAAE,YAAW,SAAU,EAAM,QAAS,CAAC,EACxE,MAAO,CAAC,IAAU,CACpB,CAAC,EACD,QAAQ,OAAO,MAAM,KAAK,UAAU,EAAM,KAAM,CAAC,EAAI,CAAG,EACzD,EAAE,KACD,EAAO,MAAM,CAAC,IACZ,EAAO,KAAK,IAAM,CAChB,QAAQ,OAAO,MAAM,EAAa,CAAK,EAAI,CAAG,EAC9C,QAAQ,SAAW,EACpB,CACH,CACF,CACF,CACF", | ||
| "debugId": "60542D29D24FA4DF64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mcp/logout.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { resolveIntegration } from \"./resolve\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.logout,\n Effect.fn(\"cli.mcp.logout\")(function* (input) {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n\n const integration = yield* resolveIntegration(client, input.name, location)\n if (!integration) {\n process.stdout.write(`No stored credentials for ${input.name}` + EOL)\n return\n }\n\n const credentials = integration.connections.filter((connection) => connection.type === \"credential\")\n if (credentials.length === 0) {\n process.stdout.write(`No stored credentials for ${input.name}` + EOL)\n return\n }\n\n yield* Effect.forEach(\n credentials,\n (connection) => Effect.promise(() => client.credential.remove({ credentialID: connection.id, location })),\n { discard: true },\n )\n process.stdout.write(`Removed OAuth credentials for ${input.name}` + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";8/BAAA,cAAS,WAST,IAAM,EAAW,CAAE,UAAW,QAAQ,IAAI,CAAE,EAE7B,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,OAC/B,EAAO,GAAG,gBAAgB,EAAE,SAAU,CAAC,EAAO,CAC5C,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,EAAc,MAAO,EAAmB,EAAQ,EAAM,KAAM,CAAQ,EAC1E,GAAI,CAAC,EAAa,CAChB,QAAQ,OAAO,MAAM,6BAA6B,EAAM,OAAS,CAAG,EACpE,OAGF,IAAM,EAAc,EAAY,YAAY,OAAO,CAAC,IAAe,EAAW,OAAS,YAAY,EACnG,GAAI,EAAY,SAAW,EAAG,CAC5B,QAAQ,OAAO,MAAM,6BAA6B,EAAM,OAAS,CAAG,EACpE,OAGF,MAAO,EAAO,QACZ,EACA,CAAC,IAAe,EAAO,QAAQ,IAAM,EAAO,WAAW,OAAO,CAAE,aAAc,EAAW,GAAI,UAAS,CAAC,CAAC,EACxG,CAAE,QAAS,EAAK,CAClB,EACA,QAAQ,OAAO,MAAM,iCAAiC,EAAM,OAAS,CAAG,EACzE,CACH", | ||
| "debugId": "B069810C87224EF864756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/workspace/driver.ts", "../core/src/workspace/sql.ts", "../core/src/workspace.ts", "../core/src/environment/files.ts", "../core/src/environment/exec-defaults.ts", "../core/src/environment/local.ts", "../core/src/environment/memory.ts", "../core/src/environment/environment.ts", "../core/src/environment/index.ts"], | ||
| "sourcesContent": [ | ||
| "export * as WorkspaceDriver from \"./driver.js\"\n\nimport { Workspace } from \"@opencode-ai/schema/workspace\"\nimport { makeGlobalNode } from \"@opencode-ai/util/effect/app-node\"\nimport { Context, Effect, Layer, Schema } from \"effect\"\nimport type { Scope } from \"effect\"\nimport type { EnvironmentDriver } from \"../environment/driver.js\"\n\n/**\n * Smallest provider-owned JSON value required to reconnect to the same\n * provider resource. Core stores it opaquely and hands it back; only the\n * owning driver reads inside.\n */\nexport const Binding = Schema.Record(Schema.String, Schema.Json)\nexport type Binding = typeof Binding.Type\n\nexport class Error extends Schema.TaggedError<Error>()(\"WorkspaceDriver.Error\", {\n message: Schema.optional(Schema.String),\n cause: Schema.optional(Schema.Defect()),\n}) {}\n\nexport class ProviderNotFound extends Schema.TaggedError<ProviderNotFound>()(\"WorkspaceDriver.ProviderNotFound\", {\n provider: Schema.String,\n}) {}\n\nexport interface Interface {\n /**\n * Get-or-create the provider resource backing this logical workspace.\n *\n * MUST be idempotent per `workspaceID`: core retries the same ID after\n * failures and process crashes, including a crash between a successful\n * create and the binding being persisted, and another process may race the\n * same ID. Key the resource by `workspaceID` (a provider tag or a\n * deterministic name) and adopt an existing match instead of creating a\n * duplicate.\n */\n readonly create: (input: {\n readonly workspaceID: Workspace.ID\n }) => Effect.Effect<{ readonly binding: Binding }, Error>\n readonly connect: (input: {\n readonly workspaceID: Workspace.ID\n readonly binding: Binding\n readonly saveBinding: (binding: Binding) => Effect.Effect<void>\n }) => Effect.Effect<EnvironmentDriver.Driver, Error, Scope.Scope>\n readonly suspendForIdle: (input: {\n readonly workspaceID: Workspace.ID\n readonly binding: Binding\n readonly saveBinding: (binding: Binding) => Effect.Effect<void>\n }) => Effect.Effect<void, Error>\n /**\n * Release the provider resource for this workspace.\n *\n * `binding` is null when none was persisted: the workspace was never\n * provisioned, or provisioning was interrupted mid-create. Look up any\n * resource previously created for `workspaceID` and clean it up, treating\n * absence as success.\n */\n readonly destroy: (input: {\n readonly workspaceID: Workspace.ID\n readonly binding: Binding | null\n }) => Effect.Effect<void, Error>\n}\n\nexport const make = (driver: Interface) => driver\n\nexport interface Registry {\n readonly get: (provider: string) => Effect.Effect<Interface, ProviderNotFound>\n}\n\nexport class RegistryService extends Context.Service<RegistryService, Registry>()(\n \"@opencode/WorkspaceDriverRegistry\",\n) {}\n\nexport const registry = (drivers: Readonly<Record<string, Interface>>): Registry => ({\n get: (provider) => {\n const driver = Object.hasOwn(drivers, provider) ? drivers[provider] : undefined\n return driver ? Effect.succeed(driver) : Effect.fail(new ProviderNotFound({ provider }))\n },\n})\n\nexport const registryNode = (drivers: Readonly<Record<string, Interface>>) =>\n makeGlobalNode({\n service: RegistryService,\n layer: Layer.succeed(RegistryService, RegistryService.of(registry(drivers))),\n deps: [],\n })\n\nexport const node = registryNode({})\n", | ||
| "import { Workspace } from \"@opencode-ai/schema/workspace\"\nimport { integer, sqliteTable, text } from \"drizzle-orm/sqlite-core\"\nimport type { WorkspaceDriver } from \"./driver.js\"\n\nexport const WorkspaceTable = sqliteTable(\"workspace\", {\n id: text().$type<Workspace.ID>().primaryKey(),\n provider: text().notNull(),\n binding: text({ mode: \"json\" }).$type<WorkspaceDriver.Binding>(),\n created_at: integer().notNull(),\n last_used_at: integer().notNull(),\n})\n", | ||
| "export * as Workspace from \"./workspace.js\"\n\nimport { Workspace } from \"@opencode-ai/schema/workspace\"\nimport { makeGlobalNode } from \"@opencode-ai/util/effect/app-node\"\nimport { eq } from \"drizzle-orm\"\nimport { Clock, Context, Deferred, Duration, Effect, Exit, FiberSet, Layer, Ref, Schedule, Schema, Scope } from \"effect\"\nimport { systemError } from \"effect/PlatformError\"\nimport { make } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { EnvironmentDriver } from \"./environment/driver.js\"\nimport { Database } from \"./database/database.js\"\nimport { KeyedMutex } from \"./effect/keyed-mutex.js\"\nimport { WorkspaceDriver } from \"./workspace/driver.js\"\nimport { WorkspaceTable } from \"./workspace/sql.js\"\n\nexport const ID = Workspace.ID\nexport type ID = Workspace.ID\n\nexport class Info extends Schema.Class<Info>(\"Workspace.Info\")({\n id: ID,\n provider: Schema.String,\n binding: WorkspaceDriver.Binding,\n createdAt: Schema.Number,\n lastUsedAt: Schema.Number,\n}) {}\n\nexport class NotFound extends Schema.TaggedError<NotFound>()(\"Workspace.NotFound\", { workspaceID: ID }) {}\n\nexport class CreateConflict extends Schema.TaggedError<CreateConflict>()(\"Workspace.CreateConflict\", {\n workspaceID: ID,\n provider: Schema.String,\n existingProvider: Schema.String,\n}) {}\n\nexport interface Interface {\n /** Instantly commits a logical workspace ID. No provider work happens here. */\n readonly create: (input: {\n readonly id?: ID\n readonly provider: string\n }) => Effect.Effect<ID, CreateConflict | WorkspaceDriver.ProviderNotFound>\n /** Starts or joins the shared attempt that makes the backing resource real, then returns it. */\n readonly provision: (\n workspaceID: ID,\n ) => Effect.Effect<Info, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>\n readonly connect: (\n workspaceID: ID,\n ) => Effect.Effect<EnvironmentDriver.Driver, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>\n /** Makes the workspace absent; reports whether this call destroyed an existing workspace. */\n readonly destroy: (\n workspaceID: ID,\n ) => Effect.Effect<Workspace.DestroyResult, WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>\n}\n\nexport interface Options {\n readonly idleThreshold?: Duration.Input\n readonly pollInterval?: Duration.Input\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@opencode/Workspace\") {}\n\ninterface Connection {\n readonly driver: WorkspaceDriver.Interface\n readonly environment: EnvironmentDriver.Driver\n readonly saveBinding: (binding: WorkspaceDriver.Binding) => Effect.Effect<void>\n readonly lastActivity: Ref.Ref<number>\n readonly active: Ref.Ref<number>\n readonly scope: Scope.Closeable\n}\n\ntype ReadinessError = NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound\n\nexport const configured = (options: Options = {}) =>\n makeGlobalNode({\n service: Service,\n layer: layer(options),\n deps: [Database.node, WorkspaceDriver.node],\n })\n\nconst layer = (options: Options) =>\n Layer.effect(\n Service,\n Effect.gen(function* () {\n const db = (yield* Database.Service).db\n const registry = yield* WorkspaceDriver.RegistryService\n const lifetime = yield* Scope.Scope\n const connections = new Map<ID, Connection>()\n // Destroy cancels the racing provision body by settling the deferred.\n const attempts = new Map<ID, Deferred.Deferred<Info, ReadinessError>>()\n const locks = KeyedMutex.makeUnsafe<ID>()\n const fork = yield* FiberSet.makeRuntime<never, void, never>()\n const idleThreshold = Duration.toMillis(options.idleThreshold ?? Duration.minutes(20))\n\n const find = (workspaceID: ID) =>\n db.select().from(WorkspaceTable).where(eq(WorkspaceTable.id, workspaceID)).get().pipe(Effect.orDie)\n\n const load = Effect.fn(\"Workspace.load\")(function* (workspaceID: ID) {\n const row = yield* find(workspaceID)\n if (!row) return yield* new NotFound({ workspaceID })\n return row\n })\n\n const saveBinding = (workspaceID: ID, binding: WorkspaceDriver.Binding) =>\n db.update(WorkspaceTable).set({ binding }).where(eq(WorkspaceTable.id, workspaceID)).run().pipe(Effect.orDie)\n\n const info = (row: typeof WorkspaceTable.$inferSelect, binding: WorkspaceDriver.Binding) =>\n new Info({\n id: row.id,\n provider: row.provider,\n binding,\n createdAt: row.created_at,\n lastUsedAt: row.last_used_at,\n })\n\n const provision = Effect.fn(\"Workspace.provision\")((workspaceID: ID) =>\n Effect.suspend(() => {\n const existing = attempts.get(workspaceID)\n if (existing) return Deferred.await(existing)\n\n const attempt = Deferred.makeUnsafe<Info, ReadinessError>()\n attempts.set(workspaceID, attempt)\n fork(\n locks\n .withLock(workspaceID)(\n Effect.gen(function* () {\n const row = yield* load(workspaceID)\n if (row.binding) return info(row, row.binding)\n const driver = yield* registry.get(row.provider)\n const result = yield* driver.create({ workspaceID })\n yield* saveBinding(workspaceID, result.binding)\n return info(row, result.binding)\n }),\n )\n .pipe(\n Effect.raceFirst(Deferred.await(attempt)),\n Effect.onExit((exit) =>\n Effect.sync(() => {\n if (attempts.get(workspaceID) === attempt) attempts.delete(workspaceID)\n Deferred.doneUnsafe(attempt, exit)\n }),\n ),\n Effect.exit,\n Effect.asVoid,\n ),\n )\n return Deferred.await(attempt)\n }),\n )\n\n const open = Effect.fn(\"Workspace.open\")(function* (workspaceID: ID) {\n const existing = connections.get(workspaceID)\n if (existing) return existing\n\n const row = yield* load(workspaceID)\n // Bindings are persisted before provision resolves and never nulled; a raced\n // destroy deletes the whole row and surfaces as NotFound from load above.\n if (!row.binding) return yield* Effect.die(`workspace ${workspaceID} has no binding after provision`)\n const driver = yield* registry.get(row.provider)\n const persistBinding = (binding: WorkspaceDriver.Binding) => saveBinding(workspaceID, binding)\n const scope = yield* Scope.fork(lifetime)\n const environment = yield* driver\n .connect({ workspaceID, binding: row.binding, saveBinding: persistBinding })\n .pipe(\n Effect.provideService(Scope.Scope, scope),\n Effect.onError((cause) => Scope.close(scope, Exit.failCause(cause))),\n )\n const now = yield* Clock.currentTimeMillis\n const connection: Connection = {\n driver,\n environment,\n saveBinding: persistBinding,\n lastActivity: yield* Ref.make(now),\n active: yield* Ref.make(0),\n scope,\n }\n connections.set(workspaceID, connection)\n yield* db\n .update(WorkspaceTable)\n .set({ last_used_at: now })\n .where(eq(WorkspaceTable.id, workspaceID))\n .run()\n .pipe(Effect.orDie)\n return connection\n })\n\n yield* Effect.gen(function* () {\n const now = yield* Clock.currentTimeMillis\n yield* Effect.forEach(\n [...connections.entries()],\n ([workspaceID, expected]) =>\n locks.withLock(workspaceID)(\n Effect.gen(function* () {\n const connection = connections.get(workspaceID)\n if (connection !== expected || (yield* Ref.get(connection.active)) > 0) return\n const lastActivity = yield* Ref.get(connection.lastActivity)\n if (now - lastActivity < idleThreshold) return\n const row = yield* load(workspaceID)\n if (!row.binding) return\n // Deliberate: a racing spawn blocks, then wakes cleanly. Unlocking mid-suspend could reattach a sandbox being terminated.\n yield* connection.driver.suspendForIdle({\n workspaceID,\n binding: row.binding,\n saveBinding: connection.saveBinding,\n })\n yield* db\n .update(WorkspaceTable)\n .set({ last_used_at: lastActivity })\n .where(eq(WorkspaceTable.id, workspaceID))\n .run()\n .pipe(Effect.orDie)\n connections.delete(workspaceID)\n yield* Scope.close(connection.scope, Exit.void)\n }).pipe(Effect.catchCause((cause) => Effect.logError(\"workspace idle suspension failed\", cause))),\n ),\n { concurrency: \"unbounded\", discard: true },\n )\n }).pipe(Effect.repeat(Schedule.spaced(options.pollInterval ?? Duration.minutes(1))), Effect.forkScoped)\n\n return Service.of({\n create: Effect.fn(\"Workspace.create\")(function* (input) {\n const workspaceID = input.id ?? ID.create()\n const existing = yield* db\n .select({ provider: WorkspaceTable.provider })\n .from(WorkspaceTable)\n .where(eq(WorkspaceTable.id, workspaceID))\n .get()\n .pipe(Effect.orDie)\n if (existing) {\n if (existing.provider === input.provider) return workspaceID\n return yield* new CreateConflict({\n workspaceID,\n provider: input.provider,\n existingProvider: existing.provider,\n })\n }\n yield* registry.get(input.provider)\n const now = yield* Clock.currentTimeMillis\n const inserted = yield* db\n .insert(WorkspaceTable)\n .values({ id: workspaceID, provider: input.provider, binding: null, created_at: now, last_used_at: now })\n .onConflictDoNothing()\n .returning({ id: WorkspaceTable.id })\n .get()\n .pipe(Effect.orDie)\n if (inserted) return workspaceID\n const row = yield* load(workspaceID).pipe(Effect.orDie)\n if (row.provider !== input.provider)\n return yield* new CreateConflict({\n workspaceID,\n provider: input.provider,\n existingProvider: row.provider,\n })\n return workspaceID\n }),\n provision,\n connect: Effect.fn(\"Workspace.connect\")(function* (workspaceID) {\n const spawner = make((command) =>\n Effect.acquireRelease(\n // A live connection implies the binding is already persisted, so skip the provision hop.\n Effect.suspend(() => (connections.has(workspaceID) ? Effect.void : provision(workspaceID))).pipe(\n Effect.andThen(\n locks.withLock(workspaceID)(\n Effect.gen(function* () {\n const connection = yield* open(workspaceID)\n yield* Ref.set(connection.lastActivity, yield* Clock.currentTimeMillis)\n yield* Ref.update(connection.active, (active) => active + 1)\n return connection\n }),\n ),\n ),\n Effect.mapError((cause) =>\n systemError({\n _tag: \"Unknown\",\n module: \"Workspace\",\n method: \"spawn\",\n description: `Failed to wake workspace ${workspaceID}`,\n cause,\n }),\n ),\n ),\n (connection) =>\n locks.withLock(workspaceID)(\n Effect.gen(function* () {\n yield* Ref.update(connection.active, (active) => active - 1)\n yield* Ref.set(connection.lastActivity, yield* Clock.currentTimeMillis)\n }),\n ),\n ).pipe(Effect.flatMap((connection) => connection.environment.spawner.spawn(command))),\n )\n // Overrides are connection-bound; per-spawn routing is required before any driver ships them, so they are deliberately omitted.\n return { spawner }\n }),\n destroy: Effect.fn(\"Workspace.destroy\")(function* (workspaceID) {\n // Settling the shared attempt cancels its racing provision body and fails\n // waiters with NotFound before teardown commits. Accepted tradeoffs: if the\n // locked teardown below fails, those waiters saw NotFound for a workspace\n // that still exists (the next provision retries it), and a provision racing\n // this window may briefly succeed before teardown destroys its fresh binding.\n const attempt = attempts.get(workspaceID)\n if (attempt) {\n attempts.delete(workspaceID)\n Deferred.doneUnsafe(attempt, Exit.fail(new NotFound({ workspaceID })))\n }\n return yield* locks.withLock(workspaceID)(\n Effect.gen(function* () {\n const row = yield* find(workspaceID)\n if (!row) return { destroyed: false }\n const connection = connections.get(workspaceID)\n connections.delete(workspaceID)\n if (connection) yield* Scope.close(connection.scope, Exit.void)\n // Null binding still reaches the driver: an interrupted or crashed\n // provision may have created a resource that was never persisted. A\n // provider missing from the registry cannot block deleting a\n // never-provisioned row.\n yield* registry.get(row.provider).pipe(\n Effect.flatMap((driver) => driver.destroy({ workspaceID, binding: row.binding })),\n Effect.catchTag(\"WorkspaceDriver.ProviderNotFound\", (error) =>\n row.binding ? Effect.fail(error) : Effect.void,\n ),\n )\n yield* db.delete(WorkspaceTable).where(eq(WorkspaceTable.id, workspaceID)).run().pipe(Effect.orDie)\n return { destroyed: true }\n }),\n )\n }),\n })\n }),\n )\n\nexport const node = configured()\n\n// TODO(workspace-plan): add the boot janitor and ~23h safety snapshot rotation in a later PR.\n// TODO(workspace-plan): make cold wake interruptible with a re-pin loop against janitor races.\n// TODO(workspace-plan): consider extracting a keyed shared-attempt helper (join/cancel, drop-on-settle) beside\n// KeyedMutex at end-of-series consolidation; filesystem/search.ts and session/run-coordinator.ts hand-roll the same\n// shape. Audited stdlib alternatives (rc.111): RcMap fails twice (refcount release cancels in-flight work when the\n// last waiter leaves, and one finalizer path cannot express idle-suspend vs destroy); Cache interrupts the shared\n// lookup when its last awaiter is interrupted and cannot fail waiters with NotFound on invalidation.\n", | ||
| "import { Effect, Schema } from \"effect\"\n\nexport const FileType = Schema.Literals([\"file\", \"directory\", \"symlink\", \"other\"])\nexport type FileType = typeof FileType.Type\n\nexport interface FileInfo {\n readonly type: FileType\n readonly size: number\n readonly mtimeMs: number\n}\n\nexport interface DirEntry {\n readonly name: string\n readonly type: FileType\n}\n\nexport class NotFound extends Schema.TaggedError<NotFound>()(\"Environment.NotFound\", {\n path: Schema.String,\n}) {}\n\nexport class WrongKind extends Schema.TaggedError<WrongKind>()(\"Environment.WrongKind\", {\n path: Schema.String,\n actual: FileType,\n}) {}\n\nexport class Failed extends Schema.TaggedError<Failed>()(\"Environment.Failed\", {\n path: Schema.String,\n cause: Schema.Defect(),\n}) {}\n\nexport interface FilesImpl {\n /**\n * Content operations (`read`, `list`) follow final symlinks; metadata operations (`stat` and entry\n * tags returned by `list`) do not. `info` describes the target file whose bytes are returned.\n * The process-backed default caps collected output at 64 MiB; larger whole-file reads fail with\n * `Failed`, so callers must use ranges for larger files.\n */\n readonly read: (\n path: string,\n range?: { readonly offset: number; readonly length: number },\n ) => Effect.Effect<{ readonly info: FileInfo; readonly bytes: Uint8Array }, NotFound | WrongKind | Failed>\n readonly write: (path: string, bytes: Uint8Array) => Effect.Effect<void, Failed>\n /** Describes the path entry itself, so a final symlink is reported as `symlink` rather than followed. */\n readonly stat: (path: string) => Effect.Effect<FileInfo, NotFound | Failed>\n /** Follows a final symlink to the listed directory while preserving each returned entry's own type. */\n readonly list: (path: string) => Effect.Effect<ReadonlyArray<DirEntry>, NotFound | WrongKind | Failed>\n readonly remove: (path: string) => Effect.Effect<void, Failed>\n readonly move: (from: string, to: string) => Effect.Effect<void, NotFound | Failed>\n readonly mkdir: (path: string) => Effect.Effect<void, Failed>\n}\n\nexport interface Files extends FilesImpl {}\n\n/**\n * Derives a follow-stat kind from the lstat-like Files contract. A dangling\n * symlink fails with `NotFound`.\n */\nexport const typeFollowing = (files: Files, path: string) =>\n files.stat(path).pipe(\n Effect.flatMap((info) =>\n info.type === \"symlink\"\n ? files.read(path, { offset: 0, length: 0 }).pipe(\n Effect.map((result) => result.info.type),\n Effect.catchTag(\"Environment.WrongKind\", (error) => Effect.succeed(error.actual)),\n )\n : Effect.succeed(info.type),\n ),\n )\n\nexport * as EnvironmentFiles from \"./files.js\"\n", | ||
| "import { Effect, Stream } from \"effect\"\nimport { ChildProcess } from \"effect/unstable/process\"\nimport type { ChildProcessSpawner } from \"effect/unstable/process/ChildProcessSpawner\"\nimport { collectStream } from \"@opencode-ai/util/process\"\nimport { Failed, NotFound, WrongKind, type FileInfo, type FileType, type FilesImpl } from \"./files.js\"\n\n/**\n * Files derived from spawning processes: one process per intent, \"$1\" is\n * always the target path. Scripts report classification through an exit-code\n * protocol (44/45/46) so failures never require parsing localized error text;\n * LC_ALL=C pins the one stderr match that remains. Requires GNU coreutils and\n * findutils in the target image — BSD and busybox userlands will not work.\n * Malformed output from these scripts is our own bug and dies as a defect.\n */\n\nconst MAX_DATA_BYTES = 64 * 1024 * 1024\nconst MAX_ERROR_BYTES = 64 * 1024\nconst NOT_FOUND = 44\nconst WRONG_KIND = 45\nconst FAILED = 46\nconst TAB = \"\\t\"\n\nconst loadMetadata = (flags = \"\") => `\nmetadata=$(stat ${flags} -c '%F${TAB}%s${TAB}%Y' -- \"$1\" 2>&1) || {\n case \"$metadata\" in\n *'No such file or directory'*|*'Not a directory'*) exit ${NOT_FOUND} ;;\n *) printf '%s' \"$metadata\" >&2; exit ${FAILED} ;;\n esac\n}\n`\n\nconst statScript = `\n${loadMetadata()}\nprintf '%s\\n' \"$metadata\"\n`\n\nconst readScript = `\n${loadMetadata(\"-L\")}\nkind=\\${metadata%%${TAB}*}\nif [ \"$kind\" != 'regular file' ] && [ \"$kind\" != 'regular empty file' ]; then\n printf '%s' \"$kind\" >&2\n exit ${WRONG_KIND}\nfi\nprintf '%s\\n' \"$metadata\"\nif [ \"$2\" = range ]; then\n dd if=\"$1\" iflag=skip_bytes,count_bytes skip=\"$3\" count=\"$4\" status=none\nelse\n cat -- \"$1\"\nfi\n`\n\nconst listScript = `\n${loadMetadata(\"-L\")}\nkind=\\${metadata%%${TAB}*}\nif [ \"$kind\" != directory ]; then\n printf '%s' \"$kind\" >&2\n exit ${WRONG_KIND}\nfi\nfind -H \"$1\" -mindepth 1 -maxdepth 1 -printf '%y\\\\0%f\\\\0'\n`\n\nconst moveScript = `\n${loadMetadata()}\nmv -- \"$1\" \"$2\"\n`\n\ninterface Result {\n readonly exitCode: number\n readonly stdout: Uint8Array\n readonly stderr: Uint8Array\n}\n\nexport const execDefaults = (spawner: ChildProcessSpawner[\"Service\"]): FilesImpl => {\n const run = (\n path: string,\n script: string,\n args: ReadonlyArray<string> = [],\n stdin?: Uint8Array,\n ): Effect.Effect<Result, Failed> =>\n Effect.scoped(\n Effect.gen(function* () {\n const command = ChildProcess.make(\"sh\", [\"-c\", script, \"sh\", path, ...args], {\n env: { LC_ALL: \"C\" },\n extendEnv: true,\n stdin: stdin === undefined ? undefined : Stream.make(stdin),\n })\n const handle = yield* spawner.spawn(command).pipe(Effect.mapError((cause) => new Failed({ path, cause })))\n const [stdout, stderr, exitCode] = yield* Effect.all(\n [\n collectStream(handle.stdout, MAX_DATA_BYTES),\n collectStream(handle.stderr, MAX_ERROR_BYTES),\n handle.exitCode,\n ],\n { concurrency: \"unbounded\" },\n ).pipe(Effect.mapError((cause) => new Failed({ path, cause })))\n if (stdout.truncated || stderr.truncated) {\n return yield* new Failed({ path, cause: new Error(\"Process output exceeded its collection limit\") })\n }\n return { exitCode, stdout: stdout.buffer, stderr: stderr.buffer }\n }),\n )\n\n const classify = <A>(\n path: string,\n result: Result,\n success: (stdout: Uint8Array) => A,\n ): Effect.Effect<A, NotFound | WrongKind | Failed> => {\n if (result.exitCode === 0) return Effect.sync(() => success(result.stdout))\n if (result.exitCode === NOT_FOUND) return Effect.fail(new NotFound({ path }))\n if (result.exitCode === WRONG_KIND) {\n return Effect.fail(new WrongKind({ path, actual: parseType(new TextDecoder().decode(result.stderr)) }))\n }\n return Effect.fail(processFailure(path, result))\n }\n\n const complete = (path: string, result: Result) =>\n result.exitCode === 0 ? Effect.void : Effect.fail(processFailure(path, result))\n\n return {\n stat: (path) => run(path, statScript).pipe(Effect.flatMap((result) => classifyPlain(path, result, parseInfo))),\n read: (path, range) =>\n run(\n path,\n readScript,\n range === undefined ? [\"whole\"] : [\"range\", String(range.offset), String(range.length)],\n ).pipe(\n Effect.flatMap((result) =>\n classify(path, result, (stdout) => {\n const newline = stdout.indexOf(10)\n if (newline < 0) throw new Error(\"Missing read metadata header\")\n return {\n info: parseInfo(stdout.slice(0, newline)),\n bytes: stdout.slice(newline + 1),\n }\n }),\n ),\n ),\n write: (path, bytes) =>\n run(path, `mkdir -p \"$(dirname \"$1\")\" && cat > \"$1\"`, [], bytes).pipe(\n Effect.flatMap((result) => complete(path, result)),\n ),\n list: (path) => run(path, listScript).pipe(Effect.flatMap((result) => classify(path, result, parseList))),\n remove: (path) => run(path, `rm -rf -- \"$1\"`).pipe(Effect.flatMap((result) => complete(path, result))),\n move: (from, to) =>\n run(from, moveScript, [to]).pipe(Effect.flatMap((result) => classifyPlain(from, result, () => undefined))),\n mkdir: (path) => run(path, `mkdir -p -- \"$1\"`).pipe(Effect.flatMap((result) => complete(path, result))),\n }\n}\n\n/** `classify` for scripts whose protocol never reports WrongKind. */\nconst classifyPlain = <A>(\n path: string,\n result: Result,\n success: (stdout: Uint8Array) => A,\n): Effect.Effect<A, NotFound | Failed> => {\n if (result.exitCode === 0) return Effect.sync(() => success(result.stdout))\n if (result.exitCode === NOT_FOUND) return Effect.fail(new NotFound({ path }))\n return Effect.fail(processFailure(path, result))\n}\n\nconst processFailure = (path: string, result: Result) =>\n new Failed({\n path,\n cause: new Error(new TextDecoder().decode(result.stderr).trim() || `Process exited with code ${result.exitCode}`),\n })\n\nconst parseInfo = (bytes: Uint8Array): FileInfo => {\n const [rawType, rawSize, rawMtime] = new TextDecoder().decode(bytes).trim().split(TAB)\n const size = Number(rawSize)\n const mtimeMs = Number(rawMtime) * 1_000\n if (!rawType || !Number.isFinite(size) || !Number.isFinite(mtimeMs)) throw new Error(\"Invalid stat output\")\n return { type: parseType(rawType), size, mtimeMs }\n}\n\nconst parseType = (value: string): FileType => {\n if (value === \"regular file\" || value === \"regular empty file\" || value === \"f\") return \"file\"\n if (value === \"directory\" || value === \"d\") return \"directory\"\n if (value === \"symbolic link\" || value === \"l\") return \"symlink\"\n return \"other\"\n}\n\nconst parseList = (bytes: Uint8Array) => {\n const fields = new TextDecoder().decode(bytes).split(\"\\0\")\n fields.pop()\n if (fields.length % 2 !== 0) throw new Error(\"Invalid find output\")\n return Array.from({ length: fields.length / 2 }, (_, index) => ({\n name: fields[index * 2 + 1],\n type: parseType(fields[index * 2]),\n }))\n}\n\nexport * as EnvironmentExecDefaults from \"./exec-defaults.js\"\n", | ||
| "import fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { Effect } from \"effect\"\nimport type { ChildProcessSpawner } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { Driver } from \"./driver.js\"\nimport { Failed, NotFound, WrongKind, type FileInfo, type FilesImpl, type FileType } from \"./files.js\"\n\n/**\n * The host filesystem binding. Deliberately raw node:fs rather than effect's\n * FileSystem service or FSUtil: the contract needs lstat semantics (stat\n * reports \"symlink\") and typed directory entries, and effect's node\n * FileSystem provides neither — its stat always follows symlinks and\n * readDirectory returns names only. FSUtil hits the same gap and its\n * readDirectoryEntries already bypasses to raw node readdir internally.\n * Nothing above the environment seam touches node:fs.\n */\nexport const makeLocalDriver = (spawner: ChildProcessSpawner[\"Service\"]): Driver => {\n const overrides: FilesImpl = {\n read: (value, range) =>\n Effect.gen(function* () {\n const info = yield* stat(value, true)\n if (info.type !== \"file\") return yield* new WrongKind({ path: value, actual: info.type })\n if (range === undefined) {\n const bytes = yield* attempt(value, () => fs.readFile(value), true)\n return { info, bytes }\n }\n const bytes = yield* attempt(\n value,\n async () => {\n const handle = await fs.open(value, \"r\")\n try {\n const buffer = new Uint8Array(range.length)\n const result = await handle.read(buffer, 0, range.length, range.offset)\n return buffer.subarray(0, result.bytesRead)\n } finally {\n await handle.close()\n }\n },\n true,\n )\n return { info, bytes }\n }),\n stat: (value) => stat(value, false),\n list: (value) =>\n Effect.gen(function* () {\n const info = yield* stat(value, true)\n if (info.type !== \"directory\") return yield* new WrongKind({ path: value, actual: info.type })\n const entries = yield* attempt(value, () => fs.readdir(value, { withFileTypes: true }), true)\n return entries.map((entry) => ({ name: entry.name, type: fileType(entry) }))\n }),\n write: (value, bytes) =>\n attempt(value, async () => {\n await fs.mkdir(path.dirname(value), { recursive: true })\n await fs.writeFile(value, bytes)\n }),\n remove: (value) => attempt(value, () => fs.rm(value, { recursive: true, force: true })),\n move: (from, to) =>\n Effect.gen(function* () {\n yield* stat(from, false)\n const destination = yield* stat(to, false).pipe(\n Effect.map((info) => (info.type === \"directory\" ? path.join(to, path.basename(from)) : to)),\n Effect.catchIf(\n (error) => error instanceof NotFound,\n () => Effect.succeed(to),\n ),\n )\n yield* attempt(from, () => fs.rename(from, destination))\n }),\n mkdir: (value) => attempt(value, () => fs.mkdir(value, { recursive: true }).then(() => undefined)),\n }\n\n return { spawner, overrides }\n}\n\nconst stat = (value: string, follow: boolean) =>\n attempt(value, () => (follow ? fs.stat(value) : fs.lstat(value)), true).pipe(\n Effect.map((stats): FileInfo => ({ type: fileType(stats), size: stats.size, mtimeMs: stats.mtimeMs })),\n )\n\nconst fileType = (entry: { isFile(): boolean; isDirectory(): boolean; isSymbolicLink(): boolean }): FileType => {\n if (entry.isFile()) return \"file\"\n if (entry.isDirectory()) return \"directory\"\n if (entry.isSymbolicLink()) return \"symlink\"\n return \"other\"\n}\n\nfunction attempt<A>(value: string, run: () => Promise<A>): Effect.Effect<A, Failed>\nfunction attempt<A>(value: string, run: () => Promise<A>, missing: true): Effect.Effect<A, NotFound | Failed>\nfunction attempt<A>(value: string, run: () => Promise<A>, missing = false) {\n return Effect.tryPromise({\n try: run,\n catch: (cause) =>\n missing && isMissing(cause) ? new NotFound({ path: value }) : new Failed({ path: value, cause }),\n })\n}\n\nconst isMissing = (cause: unknown) =>\n cause !== null &&\n typeof cause === \"object\" &&\n \"code\" in cause &&\n (cause.code === \"ENOENT\" || cause.code === \"ENOTDIR\")\n\nexport * as EnvironmentLocal from \"./local.js\"\n", | ||
| "import path from \"node:path\"\nimport { Effect, PlatformError } from \"effect\"\nimport { make } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { Driver } from \"./driver.js\"\nimport { Failed, NotFound, WrongKind, type FileInfo, type FilesImpl, type FileType } from \"./files.js\"\n\ntype Node =\n | { readonly type: \"file\"; readonly bytes: Uint8Array; readonly mtimeMs: number }\n | { readonly type: \"directory\"; readonly mtimeMs: number }\n | { readonly type: \"symlink\"; readonly target: string; readonly mtimeMs: number }\n\nexport interface MemoryDriver extends Driver {\n readonly symlink: (target: string, path: string) => Effect.Effect<void, Failed>\n}\n\nexport const makeMemoryDriver = (): MemoryDriver => {\n const nodes = new Map<string, Node>([[\"/\", { type: \"directory\", mtimeMs: Date.now() }]])\n const key = (value: string) => path.posix.resolve(\"/\", value)\n const info = (node: Node): FileInfo => ({\n type: node.type,\n size:\n node.type === \"file\"\n ? node.bytes.length\n : node.type === \"symlink\"\n ? new TextEncoder().encode(node.target).length\n : 0,\n mtimeMs: node.mtimeMs,\n })\n const resolveKey = (value: string, followFinal: boolean, seen = new Set<string>()): string | undefined => {\n const normalized = key(value)\n const parts = normalized.split(\"/\").filter(Boolean)\n const base = \"/\"\n const walk = (current: string, index: number): string | undefined => {\n if (index === parts.length) return current\n const part = parts[index]\n const candidate = path.posix.join(current, part)\n const node = nodes.get(candidate)\n if (node?.type !== \"symlink\" || (!followFinal && index === parts.length - 1)) return walk(candidate, index + 1)\n if (seen.has(candidate)) return undefined\n seen.add(candidate)\n const target = path.posix.resolve(path.posix.dirname(candidate), node.target)\n return resolveKey(path.posix.join(target, ...parts.slice(index + 1)), followFinal, seen)\n }\n return walk(base, 0)\n }\n const lookup = (value: string) => nodes.get(resolveKey(value, false) ?? key(value))\n const requireParent = (value: string) => {\n const parentPath = path.posix.dirname(key(value))\n const parent = nodes.get(resolveKey(parentPath, true) ?? parentPath)\n if (!parent) throw new Error(`Parent directory does not exist: ${path.posix.dirname(value)}`)\n if (parent.type !== \"directory\") throw new Error(`Parent is not a directory: ${path.posix.dirname(value)}`)\n }\n const mkdirSync = (value: string) => {\n const target = resolveKey(value, false) ?? key(value)\n const existing = nodes.get(target)\n if (existing?.type === \"directory\") return\n if (existing) throw new Error(`Path is not a directory: ${value}`)\n const parent = path.posix.dirname(target)\n if (parent !== target) mkdirSync(parent)\n nodes.set(target, { type: \"directory\", mtimeMs: Date.now() })\n }\n const failed = (value: string, cause: unknown) => new Failed({ path: value, cause })\n const overrides: FilesImpl = {\n stat: (value) =>\n Effect.suspend(() => {\n const node = lookup(value)\n return node ? Effect.succeed(info(node)) : Effect.fail(new NotFound({ path: value }))\n }),\n read: (value, range) =>\n Effect.gen(function* () {\n const original = lookup(value)\n if (!original) return yield* new NotFound({ path: value })\n if (original.type === \"directory\") return yield* new WrongKind({ path: value, actual: \"directory\" })\n const resolved = resolveKey(value, true)\n const node = resolved === undefined ? undefined : nodes.get(resolved)\n if (!node) return yield* new NotFound({ path: value })\n if (node.type !== \"file\") return yield* new WrongKind({ path: value, actual: node.type })\n const bytes = range === undefined ? node.bytes : node.bytes.subarray(range.offset, range.offset + range.length)\n return { info: info(node), bytes: bytes.slice() }\n }),\n write: (value, bytes) =>\n Effect.try({\n try: () => {\n mkdirSync(path.posix.dirname(key(value)))\n const existing = lookup(value)\n if (existing?.type === \"directory\") throw new Error(`Path is a directory: ${value}`)\n const target = existing?.type === \"symlink\" ? resolveKey(value, true) : resolveKey(value, false)\n if (!target) throw new Error(`Cannot resolve symlink: ${value}`)\n requireParent(target)\n nodes.set(target, { type: \"file\", bytes: bytes.slice(), mtimeMs: Date.now() })\n },\n catch: (cause) => failed(value, cause),\n }),\n list: (value) =>\n Effect.gen(function* () {\n const target = resolveKey(value, true) ?? key(value)\n const node = nodes.get(target)\n if (!node) return yield* new NotFound({ path: value })\n if (node.type !== \"directory\") return yield* new WrongKind({ path: value, actual: node.type })\n return [...nodes.entries()]\n .filter(([entry]) => entry !== target && path.posix.dirname(entry) === target)\n .map(([entry, child]) => ({ name: path.posix.basename(entry), type: child.type satisfies FileType }))\n .sort((a, b) => a.name.localeCompare(b.name))\n }),\n remove: (value) =>\n Effect.sync(() => {\n const target = resolveKey(value, false) ?? key(value)\n for (const entry of nodes.keys()) {\n if (entry === target || entry.startsWith(`${target}/`)) nodes.delete(entry)\n }\n }),\n move: (from, to) =>\n Effect.gen(function* () {\n const source = resolveKey(from, false) ?? key(from)\n const node = nodes.get(source)\n if (!node) return yield* new NotFound({ path: from })\n yield* Effect.try({\n try: () => {\n const requested = resolveKey(to, false) ?? key(to)\n const destination =\n nodes.get(requested)?.type === \"directory\"\n ? path.posix.join(requested, path.posix.basename(source))\n : requested\n if (node.type === \"directory\" && destination.startsWith(`${source}/`)) {\n throw new Error(`Cannot move a directory into itself: ${from}`)\n }\n const existing = nodes.get(destination)\n if (node.type === \"directory\" && existing && existing.type !== \"directory\") {\n throw new Error(`Cannot overwrite a non-directory with a directory: ${to}`)\n }\n requireParent(destination)\n const moved = [...nodes.entries()].filter(([entry]) => entry === source || entry.startsWith(`${source}/`))\n for (const [entry] of moved) nodes.delete(entry)\n for (const [entry, child] of moved) nodes.set(`${destination}${entry.slice(source.length)}`, child)\n },\n catch: (cause) => failed(from, cause),\n })\n }),\n mkdir: (value) => Effect.try({ try: () => mkdirSync(value), catch: (cause) => failed(value, cause) }),\n }\n\n const spawner = make((command) =>\n Effect.suspend(() => {\n const description = command._tag === \"StandardCommand\" ? command.command : \"pipeline\"\n return Effect.fail(\n PlatformError.systemError({\n _tag: \"Unknown\",\n module: \"EnvironmentMemory\",\n method: \"spawn\",\n pathOrDescriptor: description,\n cause: failed(description, new Error(\"The memory driver cannot spawn processes\")),\n }),\n )\n }),\n )\n\n return {\n spawner,\n overrides,\n symlink: (target, value) =>\n Effect.try({\n try: () => {\n requireParent(value)\n nodes.set(resolveKey(value, false) ?? key(value), { type: \"symlink\", target, mtimeMs: Date.now() })\n },\n catch: (cause) => failed(value, cause),\n }),\n }\n}\n\nexport * as EnvironmentMemory from \"./memory.js\"\n", | ||
| "import { CrossSpawnSpawner } from \"@opencode-ai/util/cross-spawn-spawner\"\nimport { makeLocationNode } from \"@opencode-ai/util/effect/app-node\"\nimport { Context, Effect, Layer } from \"effect\"\nimport { ChildProcessSpawner } from \"effect/unstable/process/ChildProcessSpawner\"\nimport type { Files } from \"./files.js\"\nimport { makeFiles } from \"./index.js\"\nimport { makeLocalDriver } from \"./local.js\"\nimport { Location } from \"../location.js\"\nimport { Workspace } from \"../workspace.js\"\n\nexport interface Interface {\n readonly files: Files\n readonly spawner: ChildProcessSpawner[\"Service\"]\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@opencode/Environment\") {}\n\nconst layer = Layer.effect(\n Service,\n Effect.gen(function* () {\n const spawner = yield* ChildProcessSpawner\n const location = yield* Location.Service\n const workspace = yield* Workspace.Service\n const driver = location.workspaceID\n ? yield* workspace.connect(location.workspaceID).pipe(\n // Environment has no error channel; an unknown or destroyed placement is a configuration defect by design.\n Effect.mapError(\n (cause) => new Error(`Failed to bind Environment to workspace ${location.workspaceID}`, { cause }),\n ),\n Effect.orDie,\n )\n : makeLocalDriver(spawner)\n return Service.of({ files: makeFiles(driver), spawner: driver.spawner })\n }),\n)\n\nexport const node = makeLocationNode({\n service: Service,\n layer,\n deps: [CrossSpawnSpawner.node, Location.node, Workspace.node],\n})\n\nexport * as EnvironmentService from \"./environment.js\"\n", | ||
| "export * as Environment from \"./index.js\"\n\nexport { type Driver } from \"./driver.js\"\nexport {\n type DirEntry,\n Failed,\n type FileInfo,\n type Files,\n type FilesImpl,\n type FileType,\n NotFound,\n typeFollowing,\n WrongKind,\n} from \"./files.js\"\nexport { execDefaults } from \"./exec-defaults.js\"\nexport { makeLocalDriver } from \"./local.js\"\nexport { makeMemoryDriver, type MemoryDriver } from \"./memory.js\"\nexport { type Interface, node, Service } from \"./environment.js\"\n\nimport type { Driver } from \"./driver.js\"\nimport { execDefaults } from \"./exec-defaults.js\"\nimport type { Files } from \"./files.js\"\n\nexport const makeFiles = (driver: Driver): Files => ({\n ...execDefaults(driver.spawner),\n ...driver.overrides,\n})\n" | ||
| ], | ||
| "mappings": ";y8BAaO,IAAM,GAAU,EAAO,OAAO,EAAO,OAAQ,EAAO,IAAI,EAGxD,MAAM,WAAc,EAAO,YAAmB,EAAE,wBAAyB,CAC9E,QAAS,EAAO,SAAS,EAAO,MAAM,EACtC,MAAO,EAAO,SAAS,EAAO,OAAO,CAAC,CACxC,CAAC,CAAE,CAAC,CAEG,MAAM,WAAyB,EAAO,YAA8B,EAAE,mCAAoC,CAC/G,SA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AAM,EAAU,MAAO,GACjB,EAAW,MAAO,GAAS,QAC3B,EAAY,MAAO,EAAU,QAC7B,EAAS,EAAS,YACpB,MAAO,EAAU,QAAQ,EAAS,WAAW,EAAE,KAE7C,EAAO,SACL,CAAC,IAAc,MAAM,2CAA2C,EAAS,cAAe,CAAE,OAAM,CAAC,CACnG,EACA,EAAO,KACT,EACA,GAAgB,CAAO,EAC3B,OAAO,EAAQ,GAAG,CAAE,MAAO,GAAU,CAAM,EAAG,QAAS,EAAO,OAAQ,CAAC,EACxE,CACH,EAEa,GAAO,GAAiB,CACnC,QAAS,EACT,SACA,KAAM,CAAC,GAAkB,KAAM,GAAS,KAAM,EAAU,IAAI,CAC9D,CAAC,ECjBM,IAAM,GAAY,CAAC,KAA2B,IAChD,GAAa,EAAO,OAAO,KAC3B,EAAO,SACZ", | ||
| "debugId": "2D00D0FB05C5CE4A64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mcp/auth.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport {\n OpenCode,\n type IntegrationAttemptStatus,\n type IntegrationOAuthMethod,\n type OpenCodeClient,\n} from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { resolveIntegration } from \"./resolve\"\n\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.auth,\n Effect.fn(\"cli.mcp.auth\")(function* (input) {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n\n const integration = yield* resolveIntegration(client, input.name, location)\n if (!integration)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" is not an OAuth-capable remote server`))\n const method = integration.methods.find(\n (candidate): candidate is IntegrationOAuthMethod => candidate.type === \"oauth\",\n )\n if (!method)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" is not an OAuth-capable remote server`))\n\n const started = yield* Effect.promise(() =>\n client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, location }),\n )\n const attempt = started.data\n if (attempt.mode === \"code\")\n return yield* Effect.fail(new Error(\"This server requires manual code entry, which the CLI does not support\"))\n\n process.stdout.write(attempt.instructions + EOL + attempt.url + EOL)\n\n const result = yield* poll(client, integration.id, attempt.attemptID)\n if (result.status === \"complete\") {\n process.stdout.write(`Authenticated with ${input.name}` + EOL)\n return\n }\n const reason = result.status === \"failed\" ? `: ${result.message}` : \"\"\n return yield* Effect.fail(new Error(`Authentication ${result.status}${reason}`))\n }),\n)\n\nconst poll = (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n): Effect.Effect<Exclude<IntegrationAttemptStatus, { status: \"pending\" }>> =>\n Effect.gen(function* () {\n const status = yield* Effect.promise(() =>\n client.integration.oauth.status({ integrationID, attemptID, location }),\n ).pipe(Effect.map((result) => result.data))\n if (status.status === \"pending\") {\n yield* Effect.sleep(\"1 second\")\n return yield* poll(client, integrationID, attemptID)\n }\n return status\n })\n" | ||
| ], | ||
| "mappings": ";8/BAAA,cAAS,WAcT,IAAM,EAAW,CAAE,UAAW,QAAQ,IAAI,CAAE,EAE7B,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,KAC/B,EAAO,GAAG,cAAc,EAAE,SAAU,CAAC,EAAO,CAC1C,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,EAAc,MAAO,EAAmB,EAAQ,EAAM,KAAM,CAAQ,EAC1E,GAAI,CAAC,EACH,OAAO,MAAO,EAAO,KAAS,MAAM,eAAe,EAAM,6CAA6C,CAAC,EACzG,IAAM,EAAS,EAAY,QAAQ,KACjC,CAAC,IAAmD,EAAU,OAAS,OACzE,EACA,GAAI,CAAC,EACH,OAAO,MAAO,EAAO,KAAS,MAAM,eAAe,EAAM,6CAA6C,CAAC,EAKzG,IAAM,GAHU,MAAO,EAAO,QAAQ,IACpC,EAAO,YAAY,MAAM,QAAQ,CAAE,cAAe,EAAY,GAAI,SAAU,EAAO,GAAI,UAAS,CAAC,CACnG,GACwB,KACxB,GAAI,EAAQ,OAAS,OACnB,OAAO,MAAO,EAAO,KAAS,MAAM,wEAAwE,CAAC,EAE/G,QAAQ,OAAO,MAAM,EAAQ,aAAe,EAAM,EAAQ,IAAM,CAAG,EAEnE,IAAM,EAAS,MAAO,EAAK,EAAQ,EAAY,GAAI,EAAQ,SAAS,EACpE,GAAI,EAAO,SAAW,WAAY,CAChC,QAAQ,OAAO,MAAM,sBAAsB,EAAM,OAAS,CAAG,EAC7D,OAEF,IAAM,EAAS,EAAO,SAAW,SAAW,KAAK,EAAO,UAAY,GACpE,OAAO,MAAO,EAAO,KAAS,MAAM,kBAAkB,EAAO,SAAS,GAAQ,CAAC,EAChF,CACH,EAEM,EAAO,CACX,EACA,EACA,IAEA,EAAO,IAAI,SAAU,EAAG,CACtB,IAAM,EAAS,MAAO,EAAO,QAAQ,IACnC,EAAO,YAAY,MAAM,OAAO,CAAE,gBAAe,YAAW,UAAS,CAAC,CACxE,EAAE,KAAK,EAAO,IAAI,CAAC,IAAW,EAAO,IAAI,CAAC,EAC1C,GAAI,EAAO,SAAW,UAEpB,OADA,MAAO,EAAO,MAAM,UAAU,EACvB,MAAO,EAAK,EAAQ,EAAe,CAAS,EAErD,OAAO,EACR", | ||
| "debugId": "4170E105BB79477964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/auth/shared.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect } from \"effect\"\nimport { OpenCode, type IntegrationInfo, type IntegrationMethod, type OpenCodeClient } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServerConnection } from \"../../../services/server-connection\"\n\nexport const location = { directory: process.cwd() }\n\nexport const createClient = Effect.fn(\"cli.auth.client\")(function* (input: ServerConnection.Args) {\n const server = yield* ServerConnection.resolve(input)\n return OpenCode.make({ baseUrl: server.endpoint.url, headers: Service.headers(server.endpoint) })\n})\n\nexport function request<A>(run: (signal: AbortSignal) => Promise<A>) {\n return Effect.tryPromise({ try: run, catch: (cause) => cause })\n}\n\nexport const loadIntegrations = Effect.fn(\"cli.auth.integrations\")(function* (client: OpenCodeClient) {\n // The model endpoint is the existing public readiness boundary for the initial plugin generation.\n yield* request((signal) => client.model.default({ location }, { signal }))\n return yield* request((signal) => client.integration.list({ location }, { signal })).pipe(\n Effect.map((response) => response.data),\n )\n})\n\nexport const resolveIntegration = Effect.fn(\"cli.auth.resolve-integration\")(function* (\n integrations: IntegrationInfo[],\n target: string,\n) {\n const normalized = target.replace(/\\/+$/, \"\")\n const byID = integrations.find((integration) => integration.id === normalized)\n if (byID) return byID\n const matches = integrations.filter((integration) => integration.name.toLowerCase() === normalized.toLowerCase())\n if (matches.length === 1) return matches[0]\n if (matches.length > 1) {\n return yield* Effect.fail(\n new Error(\n `Integration name \"${target}\" is ambiguous: ${matches.map((integration) => integration.id).join(\", \")}`,\n ),\n )\n }\n return yield* Effect.fail(new Error(`Integration not found: ${target}`))\n})\n\nexport type ConnectMethod = Exclude<IntegrationMethod, { type: \"env\" }>\n\nexport function connectMethods(integration: IntegrationInfo) {\n return integration.methods\n .filter((method): method is ConnectMethod => method.type !== \"env\")\n .toSorted((a, b) => Number(a.type === \"key\") - Number(b.type === \"key\"))\n}\n\nexport const resolveMethod = Effect.fn(\"cli.auth.resolve-method\")(function* (methods: ConnectMethod[], target: string) {\n const normalized = target.toLowerCase()\n const matches = methods.filter((method) => {\n if (method.type === \"key\") return normalized === \"key\" || method.label?.toLowerCase() === normalized\n return method.id === target || method.label.toLowerCase() === normalized\n })\n if (matches.length === 1) return matches[0]\n if (matches.length > 1) return yield* Effect.fail(new Error(`Authentication method \"${target}\" is ambiguous`))\n const available = methods.map((method) => (method.type === \"key\" ? \"key\" : method.id)).join(\", \")\n return yield* Effect.fail(\n new Error(`Authentication method not found: ${target}${available ? `. Available: ${available}` : \"\"}`),\n )\n})\n" | ||
| ], | ||
| "mappings": ";gNAKO,IAAM,EAAW,CAAE,UAAW,QAAQ,IAAI,CAAE,EAEtC,EAAe,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAA8B,CAChG,IAAM,EAAS,MAAO,EAAiB,QAAQ,CAAK,EACpD,OAAO,EAAS,KAAK,CAAE,QAAS,EAAO,SAAS,IAAK,QAAS,EAAQ,QAAQ,EAAO,QAAQ,CAAE,CAAC,EACjG,EAEM,SAAS,CAAU,CAAC,EAA0C,CACnE,OAAO,EAAO,WAAW,CAAE,IAAK,EAAK,MAAO,CAAC,IAAU,CAAM,CAAC,EAGzD,IAAM,EAAmB,EAAO,GAAG,uBAAuB,EAAE,SAAU,CAAC,EAAwB,CAGpG,OADA,MAAO,EAAQ,CAAC,IAAW,EAAO,MAAM,QAAQ,CAAE,UAAS,EAAG,CAAE,QAAO,CAAC,CAAC,EAClE,MAAO,EAAQ,CAAC,IAAW,EAAO,YAAY,KAAK,CAAE,UAAS,EAAG,CAAE,QAAO,CAAC,CAAC,EAAE,KACnF,EAAO,IAAI,CAAC,IAAa,EAAS,IAAI,CACxC,EACD,EAEY,EAAqB,EAAO,GAAG,8BAA8B,EAAE,SAAU,CACpF,EACA,EACA,CACA,IAAM,EAAa,EAAO,QAAQ,OAAQ,EAAE,EACtC,EAAO,EAAa,KAAK,CAAC,IAAgB,EAAY,KAAO,CAAU,EAC7E,GAAI,EAAM,OAAO,EACjB,IAAM,EAAU,EAAa,OAAO,CAAC,IAAgB,EAAY,KAAK,YAAY,IAAM,EAAW,YAAY,CAAC,EAChH,GAAI,EAAQ,SAAW,EAAG,OAAO,EAAQ,GACzC,GAAI,EAAQ,OAAS,EACnB,OAAO,MAAO,EAAO,KACf,MACF,qBAAqB,oBAAyB,EAAQ,IAAI,CAAC,IAAgB,EAAY,EAAE,EAAE,KAAK,IAAI,GACtG,CACF,EAEF,OAAO,MAAO,EAAO,KAAS,MAAM,0BAA0B,GAAQ,CAAC,EACxE,EAIM,SAAS,CAAc,CAAC,EAA8B,CAC3D,OAAO,EAAY,QAChB,OAAO,CAAC,IAAoC,EAAO,OAAS,KAAK,EACjE,SAAS,CAAC,EAAG,IAAM,OAAO,EAAE,OAAS,KAAK,EAAI,OAAO,EAAE,OAAS,KAAK,CAAC,EAGpE,IAAM,EAAgB,EAAO,GAAG,yBAAyB,EAAE,SAAU,CAAC,EAA0B,EAAgB,CACrH,IAAM,EAAa,EAAO,YAAY,EAChC,EAAU,EAAQ,OAAO,CAAC,IAAW,CACzC,GAAI,EAAO,OAAS,MAAO,OAAO,IAAe,OAAS,EAAO,OAAO,YAAY,IAAM,EAC1F,OAAO,EAAO,KAAO,GAAU,EAAO,MAAM,YAAY,IAAM,EAC/D,EACD,GAAI,EAAQ,SAAW,EAAG,OAAO,EAAQ,GACzC,GAAI,EAAQ,OAAS,EAAG,OAAO,MAAO,EAAO,KAAS,MAAM,0BAA0B,iBAAsB,CAAC,EAC7G,IAAM,EAAY,EAAQ,IAAI,CAAC,IAAY,EAAO,OAAS,MAAQ,MAAQ,EAAO,EAAG,EAAE,KAAK,IAAI,EAChG,OAAO,MAAO,EAAO,KACf,MAAM,oCAAoC,IAAS,EAAY,gBAAgB,IAAc,IAAI,CACvG,EACD", | ||
| "debugId": "481478247A79CA1264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/status.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.status,\n Effect.fn(\"cli.service.status\")(function* () {\n const options = yield* ServiceConfig.options()\n const found = yield* Service.discover({ ...options, version: undefined })\n process.stdout.write((found?.url ?? \"stopped\") + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";s5BAAA,cAAS,WAOT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,OACnC,EAAO,GAAG,oBAAoB,EAAE,SAAU,EAAG,CAC3C,IAAM,EAAU,MAAO,EAAc,QAAQ,EACvC,EAAQ,MAAO,EAAQ,SAAS,IAAK,EAAS,QAAS,MAAU,CAAC,EACxE,QAAQ,OAAO,OAAO,GAAO,KAAO,WAAa,CAAG,EACrD,CACH", | ||
| "debugId": "77A0BE79465C6EEA64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/unset.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Option } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.unset,\n Effect.fn(\"cli.service.unset\")(function* (input) {\n yield* ServiceConfig.unset(input.key, Option.getOrUndefined(input.name))\n }),\n)\n" | ||
| ], | ||
| "mappings": ";i5BAKA,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,MACnC,EAAO,GAAG,mBAAmB,EAAE,SAAU,CAAC,EAAO,CAC/C,MAAO,EAAc,MAAM,EAAM,IAAK,EAAO,eAAe,EAAM,IAAI,CAAC,EACxE,CACH", | ||
| "debugId": "B640DA942F7340C464756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/check.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { format, inspect } from \"./inventory\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.check,\n Effect.fn(\"cli.plugin.check\")(function* (input) {\n const result = yield* inspect(Option.getOrUndefined(input.target))\n process.stdout.write((format(result.items) || \"No package plugins found\") + EOL)\n if (result.items.some((item) => item.error)) process.exitCode = 1\n }),\n)\n" | ||
| ], | ||
| "mappings": ";u+BAAA,cAAS,WAMT,IAAe,IAAQ,QACrB,EAAS,SAAS,OAAO,SAAS,MAClC,EAAO,GAAG,kBAAkB,EAAE,SAAU,CAAC,EAAO,CAC9C,IAAM,EAAS,MAAO,EAAQ,EAAO,eAAe,EAAM,MAAM,CAAC,EAEjE,GADA,QAAQ,OAAO,OAAO,EAAO,EAAO,KAAK,GAAK,4BAA8B,CAAG,EAC3E,EAAO,MAAM,KAAK,CAAC,IAAS,EAAK,KAAK,EAAG,QAAQ,SAAW,EACjE,CACH", | ||
| "debugId": "84CE05484F5B2A4B64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/models.ts"], | ||
| "sourcesContent": [ | ||
| "import { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, Option } from \"effect\"\nimport { EOL } from \"node:os\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nexport default Runtime.handler(\n Commands.commands.models,\n Effect.fn(\"cli.models\")(function* (input) {\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({\n baseUrl: server.endpoint.url,\n headers: Service.headers(server.endpoint),\n })\n const response = yield* Effect.promise(() => client.model.list({ location: { directory: process.cwd() } }))\n const models = response.data\n .map((model) => `${model.providerID}/${model.id}`)\n .toSorted((a, b) => a.localeCompare(b))\n if (models.length > 0) process.stdout.write(models.join(EOL) + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";ukCAGA,cAAS,WAKT,IAAe,IAAQ,QACrB,EAAS,SAAS,OAClB,EAAO,GAAG,YAAY,EAAE,SAAU,CAAC,EAAO,CACxC,IAAM,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,UACpB,CAAC,EACK,EAAS,EAAS,KAAK,CAC3B,QAAS,EAAO,SAAS,IACzB,QAAS,EAAQ,QAAQ,EAAO,QAAQ,CAC1C,CAAC,EAEK,GADW,MAAO,EAAO,QAAQ,IAAM,EAAO,MAAM,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,GAClF,KACrB,IAAI,CAAC,IAAU,GAAG,EAAM,cAAc,EAAM,IAAI,EAChD,SAAS,CAAC,EAAG,IAAM,EAAE,cAAc,CAAC,CAAC,EACxC,GAAI,EAAO,OAAS,EAAG,QAAQ,OAAO,MAAM,EAAO,KAAK,CAAG,EAAI,CAAG,EACnE,CACH", | ||
| "debugId": "C2498B564CB8B52964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "0B1EF39BEE6F596A64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "3ACFFCBCB3348C1364756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.13/node_modules/@aws-sdk/credential-provider-sso/dist-es/fromSSO.js", "../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.13/node_modules/@aws-sdk/credential-provider-sso/dist-es/isSsoProfile.js", "../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.13/node_modules/@aws-sdk/credential-provider-sso/dist-es/resolveSSOCredentials.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1111.0/node_modules/@aws-sdk/token-providers/dist-es/fromSso.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1111.0/node_modules/@aws-sdk/token-providers/dist-es/constants.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1111.0/node_modules/@aws-sdk/token-providers/dist-es/getSsoOidcClient.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1111.0/node_modules/@aws-sdk/token-providers/dist-es/getNewSsoOidcToken.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1111.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenExpiry.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1111.0/node_modules/@aws-sdk/token-providers/dist-es/validateTokenKey.js", "../../node_modules/.bun/@aws-sdk+token-providers@3.1111.0/node_modules/@aws-sdk/token-providers/dist-es/writeSSOTokenToFile.js", "../../node_modules/.bun/@aws-sdk+credential-provider-sso@3.973.13/node_modules/@aws-sdk/credential-provider-sso/dist-es/validateSsoProfile.js"], | ||
| "sourcesContent": [ | ||
| "import { CredentialsProviderError, getProfileName, loadSsoSessionData, parseKnownFiles } from \"@smithy/core/config\";\nimport { isSsoProfile } from \"./isSsoProfile\";\nimport { resolveSSOCredentials } from \"./resolveSSOCredentials\";\nimport { validateSsoProfile } from \"./validateSsoProfile\";\nexport const fromSSO = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-sso - fromSSO\");\n const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init;\n const { ssoClient } = init;\n const profileName = getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n });\n if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {\n const profiles = await parseKnownFiles(init);\n const profile = profiles[profileName];\n if (!profile) {\n throw new CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger });\n }\n if (!isSsoProfile(profile)) {\n throw new CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, {\n logger: init.logger,\n });\n }\n if (profile?.sso_session) {\n const ssoSessions = await loadSsoSessionData(init);\n const session = ssoSessions[profile.sso_session];\n const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`;\n if (ssoRegion && ssoRegion !== session.sso_region) {\n throw new CredentialsProviderError(`Conflicting SSO region` + conflictMsg, {\n tryNextLink: false,\n logger: init.logger,\n });\n }\n if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) {\n throw new CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, {\n tryNextLink: false,\n logger: init.logger,\n });\n }\n profile.sso_region = session.sso_region;\n profile.sso_start_url = session.sso_start_url;\n }\n const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile, init.logger);\n return resolveSSOCredentials({\n ssoStartUrl: sso_start_url,\n ssoSession: sso_session,\n ssoAccountId: sso_account_id,\n ssoRegion: sso_region,\n ssoRoleName: sso_role_name,\n ssoClient: ssoClient,\n clientConfig: init.clientConfig,\n parentClientConfig: init.parentClientConfig,\n callerClientConfig: init.callerClientConfig,\n profile: profileName,\n filepath: init.filepath,\n configFilepath: init.configFilepath,\n ignoreCache: init.ignoreCache,\n logger: init.logger,\n });\n }\n else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) {\n throw new CredentialsProviderError(\"Incomplete configuration. The fromSSO() argument hash must include \" +\n '\"ssoStartUrl\", \"ssoAccountId\", \"ssoRegion\", \"ssoRoleName\"', { tryNextLink: false, logger: init.logger });\n }\n else {\n return resolveSSOCredentials({\n ssoStartUrl,\n ssoSession,\n ssoAccountId,\n ssoRegion,\n ssoRoleName,\n ssoClient,\n clientConfig: init.clientConfig,\n parentClientConfig: init.parentClientConfig,\n callerClientConfig: init.callerClientConfig,\n profile: profileName,\n filepath: init.filepath,\n configFilepath: init.configFilepath,\n ignoreCache: init.ignoreCache,\n logger: init.logger,\n });\n }\n};\n", | ||
| "export const isSsoProfile = (arg) => arg &&\n (typeof arg.sso_start_url === \"string\" ||\n typeof arg.sso_account_id === \"string\" ||\n typeof arg.sso_session === \"string\" ||\n typeof arg.sso_region === \"string\" ||\n typeof arg.sso_role_name === \"string\");\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { fromSso as getSsoTokenProvider } from \"@aws-sdk/token-providers\";\nimport { CredentialsProviderError, getSSOTokenFromFile } from \"@smithy/core/config\";\nconst SHOULD_FAIL_CREDENTIAL_CHAIN = false;\nexport const resolveSSOCredentials = async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, callerClientConfig, profile, filepath, configFilepath, ignoreCache, logger, }) => {\n let token;\n const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`;\n if (ssoSession) {\n try {\n const _token = await getSsoTokenProvider({\n profile,\n filepath,\n configFilepath,\n ignoreCache,\n clientConfig,\n parentClientConfig,\n logger,\n })({ callerClientConfig });\n token = {\n accessToken: _token.token,\n expiresAt: new Date(_token.expiration).toISOString(),\n };\n }\n catch (e) {\n throw new CredentialsProviderError(e.message, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n }\n else {\n try {\n token = await getSSOTokenFromFile(ssoStartUrl);\n }\n catch (e) {\n throw new CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n }\n if (new Date(token.expiresAt).getTime() - Date.now() <= 0) {\n throw new CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n const { accessToken } = token;\n const { SSOClient, GetRoleCredentialsCommand } = await import(\"./loadSso.js\");\n const sso = ssoClient ||\n new SSOClient(Object.assign({}, clientConfig ?? {}, {\n logger: clientConfig?.logger ?? callerClientConfig?.logger ?? parentClientConfig?.logger,\n region: clientConfig?.region ?? ssoRegion,\n userAgentAppId: clientConfig?.userAgentAppId ?? callerClientConfig?.userAgentAppId ?? parentClientConfig?.userAgentAppId,\n }));\n let ssoResp;\n try {\n ssoResp = await sso.send(new GetRoleCredentialsCommand({\n accountId: ssoAccountId,\n roleName: ssoRoleName,\n accessToken,\n }));\n }\n catch (e) {\n throw new CredentialsProviderError(e, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {}, } = ssoResp;\n if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) {\n throw new CredentialsProviderError(\"SSO returns an invalid temporary credential.\", {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n const credentials = {\n accessKeyId,\n secretAccessKey,\n sessionToken,\n expiration: new Date(expiration),\n ...(credentialScope && { credentialScope }),\n ...(accountId && { accountId }),\n };\n if (ssoSession) {\n setCredentialFeature(credentials, \"CREDENTIALS_SSO\", \"s\");\n }\n else {\n setCredentialFeature(credentials, \"CREDENTIALS_SSO_LEGACY\", \"u\");\n }\n return credentials;\n};\n", | ||
| "import { getProfileName, getSSOTokenFromFile, loadSsoSessionData, parseKnownFiles, TokenProviderError, } from \"@smithy/core/config\";\nimport { EXPIRE_WINDOW_MS, REFRESH_MESSAGE } from \"./constants\";\nimport { getNewSsoOidcToken } from \"./getNewSsoOidcToken\";\nimport { validateTokenExpiry } from \"./validateTokenExpiry\";\nimport { validateTokenKey } from \"./validateTokenKey\";\nimport { writeSSOTokenToFile } from \"./writeSSOTokenToFile\";\nconst lastRefreshAttemptTime = new Date(0);\nexport const fromSso = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/token-providers - fromSso\");\n const profiles = await parseKnownFiles(init);\n const profileName = getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n });\n const profile = profiles[profileName];\n if (!profile) {\n throw new TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false);\n }\n else if (!profile[\"sso_session\"]) {\n throw new TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`);\n }\n const ssoSessionName = profile[\"sso_session\"];\n const ssoSessions = await loadSsoSessionData(init);\n const ssoSession = ssoSessions[ssoSessionName];\n if (!ssoSession) {\n throw new TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false);\n }\n for (const ssoSessionRequiredKey of [\"sso_start_url\", \"sso_region\"]) {\n if (!ssoSession[ssoSessionRequiredKey]) {\n throw new TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false);\n }\n }\n const ssoStartUrl = ssoSession[\"sso_start_url\"];\n const ssoRegion = ssoSession[\"sso_region\"];\n let ssoToken;\n try {\n ssoToken = await getSSOTokenFromFile(ssoSessionName);\n }\n catch (e) {\n throw new TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false);\n }\n validateTokenKey(\"accessToken\", ssoToken.accessToken);\n validateTokenKey(\"expiresAt\", ssoToken.expiresAt);\n const { accessToken, expiresAt } = ssoToken;\n const existingToken = { token: accessToken, expiration: new Date(expiresAt) };\n if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) {\n return existingToken;\n }\n if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1000) {\n validateTokenExpiry(existingToken);\n return existingToken;\n }\n validateTokenKey(\"clientId\", ssoToken.clientId, true);\n validateTokenKey(\"clientSecret\", ssoToken.clientSecret, true);\n validateTokenKey(\"refreshToken\", ssoToken.refreshToken, true);\n try {\n lastRefreshAttemptTime.setTime(Date.now());\n const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init, callerClientConfig);\n validateTokenKey(\"accessToken\", newSsoOidcToken.accessToken);\n validateTokenKey(\"expiresIn\", newSsoOidcToken.expiresIn);\n const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1000);\n try {\n await writeSSOTokenToFile(ssoSessionName, {\n ...ssoToken,\n accessToken: newSsoOidcToken.accessToken,\n expiresAt: newTokenExpiration.toISOString(),\n refreshToken: newSsoOidcToken.refreshToken,\n });\n }\n catch (error) {\n }\n return {\n token: newSsoOidcToken.accessToken,\n expiration: newTokenExpiration,\n };\n }\n catch (error) {\n validateTokenExpiry(existingToken);\n return existingToken;\n }\n};\n", | ||
| "export const EXPIRE_WINDOW_MS = 5 * 60 * 1000;\nexport const REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;\n", | ||
| "export const getSsoOidcClient = async (ssoRegion, init = {}, callerClientConfig) => {\n const { SSOOIDCClient } = await import(\"@aws-sdk/nested-clients/sso-oidc\");\n const coalesce = (prop) => init.clientConfig?.[prop] ?? init.parentClientConfig?.[prop] ?? callerClientConfig?.[prop];\n const ssoOidcClient = new SSOOIDCClient(Object.assign({}, init.clientConfig ?? {}, {\n region: ssoRegion ?? init.clientConfig?.region,\n logger: coalesce(\"logger\"),\n userAgentAppId: coalesce(\"userAgentAppId\"),\n }));\n return ssoOidcClient;\n};\n", | ||
| "import { getSsoOidcClient } from \"./getSsoOidcClient\";\nexport const getNewSsoOidcToken = async (ssoToken, ssoRegion, init = {}, callerClientConfig) => {\n const { CreateTokenCommand } = await import(\"@aws-sdk/nested-clients/sso-oidc\");\n const ssoOidcClient = await getSsoOidcClient(ssoRegion, init, callerClientConfig);\n return ssoOidcClient.send(new CreateTokenCommand({\n clientId: ssoToken.clientId,\n clientSecret: ssoToken.clientSecret,\n refreshToken: ssoToken.refreshToken,\n grantType: \"refresh_token\",\n }));\n};\n", | ||
| "import { TokenProviderError } from \"@smithy/core/config\";\nimport { REFRESH_MESSAGE } from \"./constants\";\nexport const validateTokenExpiry = (token) => {\n if (token.expiration && token.expiration.getTime() < Date.now()) {\n throw new TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false);\n }\n};\n", | ||
| "import { TokenProviderError } from \"@smithy/core/config\";\nimport { REFRESH_MESSAGE } from \"./constants\";\nexport const validateTokenKey = (key, value, forRefresh = false) => {\n if (typeof value === \"undefined\") {\n throw new TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? \". Cannot refresh\" : \"\"}. ${REFRESH_MESSAGE}`, false);\n }\n};\n", | ||
| "import { getSSOTokenFilepath } from \"@smithy/core/config\";\nimport { promises as fsPromises } from \"node:fs\";\nconst { writeFile } = fsPromises;\nexport const writeSSOTokenToFile = (id, ssoToken) => {\n const tokenFilepath = getSSOTokenFilepath(id);\n const tokenString = JSON.stringify(ssoToken, null, 2);\n return writeFile(tokenFilepath, tokenString);\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nexport const validateSsoProfile = (profile, logger) => {\n const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile;\n if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) {\n throw new CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters \"sso_account_id\", ` +\n `\"sso_region\", \"sso_role_name\", \"sso_start_url\". Got ${Object.keys(profile).join(\", \")}\\nReference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger });\n }\n return profile;\n};\n" | ||
| ], | ||
| "mappings": ";sKAAA,eCAO,IAAM,EAAe,CAAC,IAAQ,IAChC,OAAO,EAAI,gBAAkB,UAC1B,OAAO,EAAI,iBAAmB,UAC9B,OAAO,EAAI,cAAgB,UAC3B,OAAO,EAAI,aAAe,UAC1B,OAAO,EAAI,gBAAkB,UCLrC,gBCAA,eCAO,IAAM,EAAmB,OACnB,EAAkB,kFCDxB,IAAM,EAAmB,MAAO,EAAW,EAAO,CAAC,EAAG,IAAuB,CAChF,IAA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F363BE568B1B64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/image/photon-wasm.bun.ts", "../core/src/image/photon.ts"], | ||
| "sourcesContent": [ | ||
| "// @ts-ignore Bun embeds static file imports when compiling the CLI.\nimport photonWasm from \"@silvia-odwyer/photon-node/photon_rs_bg.wasm\" with { type: \"file\" }\n\nexport default photonWasm\n", | ||
| "import photonWasm from \"#photon-wasm\"\nimport { Effect } from \"effect\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport { FileSystem } from \"../filesystem.js\"\nimport { DecodeError, ResizerUnavailableError, SizeError, type Limits } from \"../image.js\"\n\nconst JPEG_QUALITIES = [80, 85, 70, 55, 40]\n\nexport const make = Effect.gen(function* () {\n const loadPhoton = yield* Effect.cached(\n // A runtime without a photon wasm artifact (#photon-wasm resolves to the\n // empty string on workerd) has no resizer, by declaration: fail typed\n // before touching URLs or module loading. The path resolution and import\n // for runtimes that DO have an artifact stay inside the guard too — a\n // throw outside it (workerd's undefined import.meta.url was one) is a\n // defect that escapes the ResizerUnavailableError handling and turns any\n // image-bearing prompt into a 500 instead of degrading to passthrough.\n photonWasm === \"\"\n ? Effect.fail(new ResizerUnavailableError())\n : Effect.tryPromise({\n try: async () => {\n ;(\n globalThis as typeof globalThis & { __OPENCODE_PHOTON_WASM_PATH?: string }\n ).__OPENCODE_PHOTON_WASM_PATH = path.isAbsolute(photonWasm)\n ? photonWasm\n : fileURLToPath(new URL(photonWasm, import.meta.url))\n return await import(\"@silvia-odwyer/photon-node\")\n },\n catch: () => new ResizerUnavailableError(),\n }),\n )\n return Effect.fn(\"Image.Photon.normalize\")(function* (\n resource: string,\n content: FileSystem.Content & { readonly encoding: \"base64\" },\n limits: Readonly<Limits>,\n ) {\n const photon = yield* loadPhoton\n const decoded = yield* Effect.try({\n try: () => photon.PhotonImage.new_from_byteslice(Buffer.from(content.content, \"base64\")),\n catch: () => new DecodeError({ resource }),\n })\n try {\n const width = decoded.get_width()\n const height = decoded.get_height()\n const bytes = Buffer.byteLength(content.content, \"utf-8\")\n if (width <= limits.maxWidth && height <= limits.maxHeight && bytes <= limits.maxBase64Bytes) return content\n if (!limits.autoResize)\n return yield* new SizeError({\n resource,\n width,\n height,\n bytes,\n maxWidth: limits.maxWidth,\n maxHeight: limits.maxHeight,\n maxBytes: limits.maxBase64Bytes,\n })\n const scale = Math.min(1, limits.maxWidth / width, limits.maxHeight / height)\n const sizes = Array.from({ length: 32 }).reduce<Array<{ width: number; height: number }>>((acc) => {\n const previous = acc.at(-1) ?? {\n width: Math.max(1, Math.round(width * scale)),\n height: Math.max(1, Math.round(height * scale)),\n }\n const next =\n acc.length === 0\n ? previous\n : {\n width: previous.width === 1 ? 1 : Math.max(1, Math.floor(previous.width * 0.75)),\n height: previous.height === 1 ? 1 : Math.max(1, Math.floor(previous.height * 0.75)),\n }\n return acc.some((item) => item.width === next.width && item.height === next.height) ? acc : [...acc, next]\n }, [])\n for (const size of sizes) {\n const resized = photon.resize(decoded, size.width, size.height, photon.SamplingFilter.Lanczos3)\n try {\n const encoders: Array<readonly [mime: string, encode: () => Uint8Array]> = [\n [\"image/png\", () => resized.get_bytes()],\n ...JPEG_QUALITIES.map((quality) => [\"image/jpeg\", () => resized.get_bytes_jpeg(quality)] as const),\n ]\n for (const [mime, encode] of encoders) {\n const candidate = encode()\n // Base64 uses four bytes per three input bytes, including padding.\n if (Math.ceil(candidate.length / 3) * 4 <= limits.maxBase64Bytes)\n return {\n ...content,\n content: Buffer.from(candidate).toString(\"base64\"),\n encoding: \"base64\" as const,\n mime,\n }\n }\n } finally {\n resized.free()\n }\n }\n return yield* new SizeError({\n resource,\n width,\n height,\n bytes,\n maxWidth: limits.maxWidth,\n maxHeight: limits.maxHeight,\n maxBytes: limits.maxBase64Bytes,\n })\n } finally {\n decoded.free()\n }\n })\n})\n" | ||
| ], | ||
| "mappings": ";qsCAGA,IAAe,ICDf,oBACA,wBAA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,CAAK,CAAC,CAChD,EACM,EACJ,EAAI,SAAW,EACX,EACA,CACE,MAAO,EAAS,QAAU,EAAI,EAAI,KAAK,IAAI,EAAG,KAAK,MAAM,EAAS,MAAQ,IAAI,CAAC,EAC/E,OAAQ,EAAS,SAAW,EAAI,EAAI,KAAK,IAAI,EAAG,KAAK,MAAM,EAAS,OAAS,IAAI,CAAC,CACpF,EACN,OAAO,EAAI,KAAK,CAAC,IAAS,EAAK,QAAU,EAAK,OAAS,EAAK,SAAW,EAAK,MAAM,EAAI,EAAM,CAAC,GAAG,EAAK,CAAI,GACxG,CAAC,CAAC,EACL,QAAW,KAAQ,EAAO,CACxB,IAAM,EAAU,EAAO,OAAO,EAAS,EAAK,MAAO,EAAK,OAAQ,EAAO,eAAe,QAAQ,EAC9F,GAAI,CACF,IAAM,EAAqE,CACzE,CAAC,YAAa,IAAM,EAAQ,UAAU,CAAC,EACvC,GAAG,EAAe,IAAI,CAAC,IAAY,CAAC,aAAc,IAAM,EAAQ,eAAe,CAAO,CAAC,CAAU,CACnG,EACA,QAAY,EAAM,KAAW,EAAU,CACrC,IAAM,EAAY,EAAO,EAEzB,GAAI,KAAK,KAAK,EAAU,OAAS,CAAC,EAAI,GAAK,EAAO,eAChD,MAAO,IACF,EACH,QAAS,OAAO,KAAK,CAAS,EAAE,SAAS,QAAQ,EACjD,SAAU,SACV,MACF,UAEJ,CACA,EAAQ,KAAK,GAGjB,OAAO,MAAO,IAAI,EAAU,CAC1B,WACA,QACA,SACA,QACA,SAAU,EAAO,SACjB,UAAW,EAAO,UAClB,SAAU,EAAO,cACnB,CAAC,SACD,CACA,EAAQ,KAAK,GAEhB,EACF", | ||
| "debugId": "A22CD7EBE30D09F864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/config/mcp.ts"], | ||
| "sourcesContent": [ | ||
| "export * as ConfigMCP from \"./mcp.js\"\n\nimport { Schema } from \"effect\"\nimport { Mcp } from \"../mcp.js\"\nimport { optional } from \"../schema.js\"\n\nexport const Timeout = Mcp.TimeoutConfig\nexport type Timeout = Mcp.TimeoutConfig\nexport const Local = Mcp.LocalConfig\nexport type Local = Mcp.LocalConfig\nexport const OAuth = Mcp.OAuthConfig\nexport type OAuth = Mcp.OAuthConfig\nexport const Remote = Mcp.RemoteConfig\nexport type Remote = Mcp.RemoteConfig\nexport const Server = Mcp.ServerConfig\n\nexport class Info extends Schema.Class<Info>(\"Config.MCP\")({\n timeout: Timeout.pipe(optional),\n servers: Schema.Record(Schema.String, Server).pipe(optional),\n}) {}\n" | ||
| ], | ||
| "mappings": ";2TAMO,IAAM,EAAU,EAAI,cAEd,EAAQ,EAAI,YAEZ,EAAQ,EAAI,YAEZ,EAAS,EAAI,aAEb,EAAS,EAAI,aAEnB,MAAM,UAAa,EAAO,MAAY,YAAY,EAAE,CACzD,QAAS,EAAQ,KAAK,CAAQ,EAC9B,QAAS,EAAO,OAAO,EAAO,OAAQ,CAAM,EAAE,KAAK,CAAQ,CAC7D,CAAC,CAAE,CAAC", | ||
| "debugId": "E9F101C25C616A2C64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/auth/logout.ts"], | ||
| "sourcesContent": [ | ||
| "import { autocomplete, intro, outro, spinner } from \"@clack/prompts\"\nimport { Effect, Option } from \"effect\"\nimport type { IntegrationInfo } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { handlePromptErrors, prompt, requireInteractive } from \"../../../ui/prompt\"\nimport { createClient, loadIntegrations, location, request, resolveIntegration } from \"./shared\"\n\nexport default Runtime.handler(\n Commands.commands.auth.commands.logout,\n Effect.fn(\"cli.auth.logout\")((input) =>\n logout({\n target: Option.getOrUndefined(input.target),\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n }).pipe(handlePromptErrors),\n ),\n)\n\nconst logout = Effect.fn(\"cli.auth.logout.run\")(function* (input: {\n target?: string\n server?: string\n standalone: boolean\n}) {\n if (!input.target)\n yield* requireInteractive(\"Pass an integration ID or name when running without an interactive terminal\")\n intro(\"Remove credential\")\n const client = yield* createClient({ server: input.server, standalone: input.standalone })\n const integrations = yield* loadIntegrations(client)\n const integration = yield* chooseIntegration(integrations, input.target)\n const credentials = integration.connections.filter((connection) => connection.type === \"credential\")\n if (credentials.length === 0) {\n const environment = integration.connections\n .filter((connection) => connection.type === \"env\")\n .map((connection) => connection.name)\n if (environment.length) {\n yield* Effect.fail(\n new Error(\n `${integration.name} is authenticated through ${environment.join(\", \")}; unset the environment variable to disconnect`,\n ),\n )\n }\n yield* Effect.fail(new Error(`No stored credentials for ${integration.name}`))\n }\n const progress = spinner()\n progress.start(\"Removing credential...\")\n yield* Effect.forEach(\n credentials,\n (connection) =>\n request((signal) => client.credential.remove({ credentialID: connection.id, location }, { signal })),\n { concurrency: \"unbounded\", discard: true },\n ).pipe(\n Effect.tap(() => Effect.sync(() => progress.stop(`Disconnected from ${integration.name}`))),\n Effect.tapCause(() => Effect.sync(() => progress.stop(\"Failed to remove credential\", 1))),\n )\n outro(\"Done\")\n})\n\nconst chooseIntegration = Effect.fn(\"cli.auth.logout.integration\")(function* (\n integrations: IntegrationInfo[],\n target?: string,\n) {\n if (target) return yield* resolveIntegration(integrations, target)\n const configured = integrations.filter((integration) =>\n integration.connections.some((connection) => connection.type === \"credential\"),\n )\n if (configured.length === 0) return yield* Effect.fail(new Error(\"No stored credentials found\"))\n const id = yield* prompt<string>(() =>\n autocomplete({\n message: \"Select integration\",\n maxItems: 8,\n options: configured.map((integration) => ({\n value: integration.id,\n label: integration.name,\n hint: integration.connections\n .filter((connection) => connection.type === \"credential\")\n .map((connection) => connection.label)\n .join(\", \"),\n })),\n }),\n )\n return yield* resolveIntegration(configured, id)\n})\n" | ||
| ], | ||
| "mappings": ";k1CAQA,IAAe,IAAQ,QACrB,EAAS,SAAS,KAAK,SAAS,OAChC,EAAO,GAAG,iBAAiB,EAAE,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oB,EAAO,GAAG,6BAA6B,EAAE,SAAU,CAC3E,EACA,EACA,CACA,GAAI,EAAQ,OAAO,MAAO,EAAmB,EAAc,CAAM,EACjE,IAAM,EAAa,EAAa,OAAO,CAAC,IACtC,EAAY,YAAY,KAAK,CAAC,IAAe,EAAW,OAAS,YAAY,CAC/E,EACA,GAAI,EAAW,SAAW,EAAG,OAAO,MAAO,EAAO,KAAS,MAAM,6BAA6B,CAAC,EAC/F,IAAM,EAAK,MAAO,EAAe,IAC/B,EAAa,CACX,QAAS,qBACT,SAAU,EACV,QAAS,EAAW,IAAI,CAAC,KAAiB,CACxC,MAAO,EAAY,GACnB,MAAO,EAAY,KACnB,KAAM,EAAY,YACf,OAAO,CAAC,IAAe,EAAW,OAAS,YAAY,EACvD,IAAI,CAAC,IAAe,EAAW,KAAK,EACpC,KAAK,IAAI,CACd,EAAE,CACJ,CAAC,CACH,EACA,OAAO,MAAO,EAAmB,EAAY,CAAE,EAChD", | ||
| "debugId": "E9BB576C32D3674F64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/stats.ts"], | ||
| "sourcesContent": [ | ||
| "import { ClientError, OpenCode, type SessionStatsInfo } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { TokenUsage } from \"@opencode-ai/schema/token-usage\"\nimport { activityCalendar } from \"@opencode-ai/util/activity-calendar\"\nimport { Effect, Option } from \"effect\"\nimport { EOL } from \"node:os\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\nimport { errorMessage } from \"../../util/error\"\n\nconst handler = Effect.fn(\"cli.stats\")(function* (input: Runtime.Input<typeof Commands.commands.stats>) {\n const days = Option.getOrUndefined(input.days)\n const year = Option.getOrUndefined(input.year)\n const project = Option.getOrUndefined(input.project)\n if ([days !== undefined, year !== undefined, input.all].filter(Boolean).length > 1)\n yield* Effect.fail(new Error(\"--days, --year, and --all cannot be combined\"))\n\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({ baseUrl: server.endpoint.url, headers: Service.headers(server.endpoint) })\n const range = statsRange({ days, year, all: input.all })\n const projectID =\n project === \".\"\n ? yield* request(server.endpoint.url, (signal) =>\n client.location\n .get({ location: { directory: process.cwd() } }, { signal })\n .then((location) => location.project.id),\n )\n : project\n const details = input.models || input.tools || input.cost || input.full\n const stats = yield* request(server.endpoint.url, (signal) =>\n client.session.stats(\n {\n from: range.from,\n to: range.to,\n project: projectID,\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\",\n tools: input.json || input.tools || input.full ? \"detail\" : details ? \"none\" : \"summary\",\n },\n { signal },\n ),\n )\n const output = input.json\n ? JSON.stringify(stats, null, 2)\n : renderStats(stats, {\n label: range.label,\n scope: project === undefined ? \"all projects\" : project === \".\" ? \"current project\" : \"selected project\",\n models: input.models || input.full,\n tools: input.tools || input.full,\n cost: input.cost || input.full,\n limit: input.limit,\n color: process.stdout.isTTY && process.env.NO_COLOR === undefined,\n width: process.stdout.columns ?? 80,\n })\n process.stdout.write(output + EOL)\n})\n\nexport default Runtime.handler(Commands.commands.stats, (input) =>\n handler(input).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n process.stderr.write(errorMessage(error) + EOL)\n process.exitCode = 1\n }),\n ),\n ),\n)\n\nexport function request<A>(url: string, run: (signal: AbortSignal) => Promise<A>) {\n return Effect.tryPromise({\n try: () => run(AbortSignal.timeout(30_000)),\n catch: (cause) =>\n cause instanceof ClientError && cause.reason === \"Transport\"\n ? new Error(`Could not reach server at ${url}`, { cause })\n : cause,\n })\n}\n\ntype RenderOptions = {\n label: string\n scope: string\n models: boolean\n tools: boolean\n cost: boolean\n limit: number\n color: boolean\n width: number\n}\n\nconst colors = terminalPalette()\n\nexport function renderStats(stats: SessionStatsInfo, options: RenderOptions) {\n const totalTokens = TokenUsage.total(stats.tokens)\n const toolTotals = stats.tools.mode === \"none\" ? undefined : stats.tools.totals\n const terminalTools = toolTotals ? toolTotals.succeeded + toolTotals.failed : 0\n const toolRate = !toolTotals || terminalTools === 0 ? undefined : (toolTotals.succeeded / terminalTools) * 100\n const primary = `1;${colors.primary}`\n const sessionLine = [\n metricCount(stats.sessions, \"session\", options.color),\n stats.subagents > 0 ? metricCount(stats.subagents, \"subagent\", options.color) : undefined,\n ]\n .filter((value) => value !== undefined)\n .join(\" · \")\n const toolSummary = !toolTotals\n ? \"tool stats unavailable\"\n : toolRate === undefined\n ? \"no tool calls\"\n : `${style(formatPercent(toolRate), primary, options.color)} tool success`\n const details = options.models || options.tools || options.cost\n const empty = stats.sessions === 0 && stats.prompts === 0 && stats.steps === 0\n const heading = `${style(\"opencode stats\", primary, options.color)} ${style(`· ${options.label} · ${options.scope}`, \"2\", options.color)}`\n const lines = details\n ? [style(`${options.label} · ${options.scope}`, \"2\", options.color)]\n : empty\n ? [\n heading,\n \"\",\n style(\"no activity in this range\", \"2\", options.color),\n \"\",\n style(\"opencode.ai\", \"2\", options.color),\n ]\n : [\n heading,\n \"\",\n ...renderActivity(stats.activity, stats.range.from, stats.range.to, options.color, options.width),\n \"\",\n sessionLine,\n `${metricCount(stats.prompts, \"prompt\", options.color)} · ${metricCount(stats.steps, \"step\", options.color)} · ${metricCount(totalTokens, \"token\", options.color)}`,\n `${toolSummary} · ${metricCount(stats.activeDays, \"active day\", options.color)} · best streak ${style(stats.streak.toString(), primary, options.color)} day${stats.streak === 1 ? \"\" : \"s\"}`,\n \"\",\n style(\"opencode.ai\", \"2\", options.color),\n ]\n\n if (options.cost) lines.push(...(lines.length > 0 ? [\"\"] : []), ...renderCost(stats))\n if (options.models)\n lines.push(...(lines.length > 0 ? [\"\"] : []), ...renderModels(stats, options.limit, options.width))\n if (options.tools) lines.push(...(lines.length > 0 ? [\"\"] : []), ...renderTools(stats, options.limit, options.width))\n return lines.join(EOL)\n}\n\nfunction statsRange(input: { days?: number; year?: number; all: boolean }) {\n const now = new Date()\n const to = now.getTime() + 1\n if (input.all) return { from: undefined, to, label: \"all time\" }\n if (input.days !== undefined) {\n const from = new Date(now.getFullYear(), now.getMonth(), now.getDate())\n from.setDate(from.getDate() - Math.max(0, input.days - 1))\n return {\n from: from.getTime(),\n to,\n label: input.days === 0 || input.days === 1 ? \"today\" : `last ${input.days} days`,\n }\n }\n const year = input.year ?? now.getFullYear()\n return {\n from: new Date(year, 0, 1).getTime(),\n to: year === now.getFullYear() ? to : new Date(year + 1, 0, 1).getTime(),\n label: year === now.getFullYear() ? `${year} so far` : year.toString(),\n }\n}\n\nfunction renderActivity(\n activity: SessionStatsInfo[\"activity\"],\n from: number,\n to: number,\n color: boolean,\n width: number,\n) {\n const calendar = activityCalendar({ activity, from, to, maxWeeks: width - 4 })\n const months = calendar.months\n .map((month, index) =>\n (index === calendar.months.length - 1 || month.label.length <= month.span ? month.label : \"\").padEnd(month.span),\n )\n .join(\"\")\n .trimEnd()\n const weekdays = [\"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\", \"Su\"]\n return [\n style(\n calendar.clipped ? `activity · last ${calendar.weeks.length} weeks` : \"activity\",\n `1;${colors.primary}`,\n color,\n ),\n ` ${style(months, \"2\", color)}`,\n ...weekdays.flatMap((label, day) => [\n `${style(label, \"2\", color)} ${calendar.weeks.map((week) => (week[day].level < 0 ? \" \" : paintActivity(week[day].level, color))).join(\"\")}`,\n ...(day === weekdays.length - 1 ? [] : [\"\"]),\n ]),\n \"\",\n ` ${style(\"less\", \"2\", color)} ${[0, 1, 2, 3, 4].map((level) => paintActivity(level, color)).join(\"\")} ${style(\"more\", \"2\", color)}`,\n ]\n}\n\nfunction renderCost(stats: SessionStatsInfo) {\n const input = stats.tokens.input + stats.tokens.cache.read + stats.tokens.cache.write\n const cached = input === 0 ? 0 : (stats.tokens.cache.read / input) * 100\n return [\n \"COST & TOKENS\",\n row(\"cost\", `$${stats.cost.toFixed(2)}`),\n row(\"input\", formatNumber(stats.tokens.input)),\n row(\"output\", formatNumber(stats.tokens.output)),\n row(\"reasoning\", formatNumber(stats.tokens.reasoning)),\n row(\"cache read\", formatNumber(stats.tokens.cache.read)),\n row(\"cache write\", formatNumber(stats.tokens.cache.write)),\n row(\"cached input\", formatPercent(cached)),\n ]\n}\n\nfunction renderModels(stats: SessionStatsInfo, limit: number, width: number) {\n if (stats.models.length === 0) return [\"MODELS\", \" no model usage\"]\n const models = stats.models.slice(0, limit)\n const more = stats.models.length - models.length\n if (width < 68)\n return [\n \"MODELS\",\n ...models.flatMap((item) => [\n truncate(\n `${item.model.providerID}/${item.model.id}${item.model.variant ? `#${item.model.variant}` : \"\"}`,\n width,\n ),\n ` ${formatNumber(TokenUsage.total(item.tokens))} tokens · ${formatNumber(item.steps)} steps · $${item.cost.toFixed(2)}`,\n ]),\n ...(more > 0 ? [\"\", `+${more.toLocaleString(\"en-US\")} more model${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n return [\n \"MODELS\",\n tableHeader(\"model\", \"tokens\", \"steps\", \"cost\"),\n ...models.map((item) =>\n tableRow(\n `${item.model.providerID}/${item.model.id}${item.model.variant ? `#${item.model.variant}` : \"\"}`,\n formatNumber(TokenUsage.total(item.tokens)),\n formatNumber(item.steps),\n `$${item.cost.toFixed(2)}`,\n ),\n ),\n ...(more > 0 ? [\"\", `+${more.toLocaleString(\"en-US\")} more model${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n}\n\nfunction renderTools(stats: SessionStatsInfo, limit: number, width: number) {\n if (stats.tools.mode !== \"detail\") return [\"TOOL RELIABILITY\", \" tool details unavailable\"]\n if (stats.tools.usage.length === 0) return [\"TOOL RELIABILITY\", \" no tool calls\"]\n const tools = stats.tools.usage.slice(0, limit)\n const more = stats.tools.usage.length - tools.length\n if (width < 68)\n return [\n \"TOOL RELIABILITY\",\n ...tools.flatMap((tool) => {\n const terminal = tool.succeeded + tool.failed\n return [\n truncate(tool.name, width),\n ` ${formatNumber(tool.calls)} calls · ${terminal === 0 ? \"-\" : formatPercent((tool.failed / terminal) * 100)} error · ${tool.durationP50 === undefined ? \"-\" : formatDuration(tool.durationP50)} p50`,\n ]\n }),\n \"\",\n `${formatNumber(stats.tools.totals.succeeded + stats.tools.totals.failed)} finished calls · ${formatNumber(stats.tools.totals.unfinished)} unfinished`,\n ...(more > 0 ? [`+${more.toLocaleString(\"en-US\")} more tool${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n return [\n \"TOOL RELIABILITY\",\n tableHeader(\"tool\", \"calls\", \"error\", \"p50\"),\n ...tools.map((tool) => {\n const terminal = tool.succeeded + tool.failed\n return tableRow(\n tool.name,\n formatNumber(tool.calls),\n terminal === 0 ? \"-\" : formatPercent((tool.failed / terminal) * 100),\n tool.durationP50 === undefined ? \"-\" : formatDuration(tool.durationP50),\n )\n }),\n \"\",\n `${formatNumber(stats.tools.totals.succeeded + stats.tools.totals.failed)} finished calls · ${formatNumber(stats.tools.totals.unfinished)} unfinished`,\n ...(more > 0 ? [`+${more.toLocaleString(\"en-US\")} more tool${more === 1 ? \"\" : \"s\"}`] : []),\n ]\n}\n\nfunction row(label: string, value: string) {\n return ` ${label.padEnd(20)}${value}`\n}\n\nfunction tableHeader(label: string, second: string, third: string, fourth: string) {\n return tableRow(label, second, third, fourth)\n}\n\nfunction tableRow(label: string, second: string, third: string, fourth: string) {\n return `${truncate(label, 34).padEnd(34)}${second.padStart(10)}${third.padStart(12)}${fourth.padStart(12)}`\n}\n\nfunction truncate(value: string, width: number) {\n return value.length <= width ? value : value.slice(0, width - 1) + \"…\"\n}\n\nfunction formatNumber(value: number) {\n if (value >= 1_000_000_000) return `${trimDecimal(value / 1_000_000_000)}b`\n if (value >= 1_000_000) return `${trimDecimal(value / 1_000_000)}m`\n if (value >= 1_000) return `${trimDecimal(value / 1_000)}k`\n return Math.round(value).toLocaleString(\"en-US\")\n}\n\nfunction trimDecimal(value: number) {\n return value.toFixed(1).replace(/\\.0$/, \"\")\n}\n\nfunction formatPercent(value: number) {\n return `${value.toFixed(value >= 10 ? 1 : 2)}%`\n}\n\nfunction formatDuration(value: number) {\n if (value < 1_000) return `${Math.round(value)}ms`\n return `${trimDecimal(value / 1_000)}s`\n}\n\nfunction metricCount(value: number, noun: string, color: boolean) {\n return `${style(formatNumber(value), `1;${colors.primary}`, color)} ${noun}${value === 1 ? \"\" : \"s\"}`\n}\n\nfunction style(value: string, code: string, color: boolean) {\n return color ? `\\x1b[${code}m${value}\\x1b[0m` : value\n}\n\nfunction paintActivity(level: number, color: boolean) {\n const glyph = [\"·\", \"░\", \"▒\", \"▓\", \"█\"][level]\n if (!color) return glyph\n if (level === 0) return `\\x1b[2m${glyph}\\x1b[22m`\n return `\\x1b[${colors.activity[level - 1]}m${glyph}\\x1b[39m`\n}\n\nfunction terminalPalette() {\n const background = Number(process.env.COLORFGBG?.split(\";\").at(-1))\n if (Number.isFinite(background) && background >= 7)\n return {\n primary: \"38;2;59;125;216\",\n activity: [\"38;2;153;169;192\", \"38;2;122;155;200\", \"38;2;90;140;208\", \"38;2;59;125;216\"],\n }\n if (Number.isFinite(background))\n return {\n primary: \"38;2;250;178;131\",\n activity: [\"38;2;117;99;87\", \"38;2;161;125;102\", \"38;2;206;152;116\", \"38;2;250;178;131\"],\n }\n return { primary: \"36\", activity: [\"2;36\", \"36\", \"1;36\", \"1;96\"] }\n}\n" | ||
| ], | ||
| "mappings": ";2uCAKA,cAAS,WAMT,IAAM,EAAU,EAAO,GAAG,WAAW,EAAE,SAAU,CAAC,EAAsD,CACtG,IAAM,EAAO,EAAO,eAAe,EAAM,IAAI,EACvC,EAAO,EAAO,eAAe,EAAM,IAAI,EACvC,EAAU,EAAO,eAAe,EAAM,OAAO,EACnD,GAAI,CAAC,IAAS,OAAW,IAAS,OAAW,EAAM,GAAG,EAAE,OAAO,OAAO,EAAE,OAAS,EAC/E,MAAO,EAAO,KAAS,MAAM,8CAA8C,CAAC,EAE9E,IAAM,EAAS,MAAO,EAAiB,QAAQ,CA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E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/oauth/page.ts"], | ||
| "sourcesContent": [ | ||
| "// Branded HTML pages for local OAuth callback servers.\n//\n// These are served by the loopback HTTP servers that finish an OAuth exchange\n// (MCP, Codex/ChatGPT, xAI, Snowflake, DigitalOcean, ...). The functions return\n// a fully self-contained HTML string with no external assets, so they work\n// offline and drop into any transport (`res.end(...)`, Effect `response.end`,\n// etc.).\n//\n// The visual language mirrors the OpenCode app: the design tokens are a curated\n// subset of the OC-2 semantic tokens in `packages/ui/src/styles/theme.css`, and\n// the wordmark is the same geometry as `packages/ui/src/components/logo.tsx`.\n// Keep this file in sync with those sources when the brand changes.\n\nexport interface CallbackPageOptions {\n /** Friendly integration name shown as a subtitle, e.g. \"xAI\", \"Snowflake\", \"MCP\". */\n provider?: string\n /** Attempt to close the window shortly after success. Defaults to true. */\n autoClose?: boolean\n}\n\nexport function success(options?: CallbackPageOptions) {\n const provider = options?.provider\n return renderDocument({\n title: \"Authorization successful\",\n body: renderCard({\n status: \"success\",\n headline: \"Authorization successful\",\n message: provider ? `OpenCode is now connected to ${escapeHtml(provider)}.` : \"OpenCode is now authorized.\",\n footnote: \"You can close this window.\",\n }),\n script: options?.autoClose === false ? undefined : AUTO_CLOSE_SCRIPT,\n })\n}\n\nexport function error(detail: string, options?: CallbackPageOptions) {\n const provider = options?.provider\n return renderDocument({\n title: \"Authorization failed\",\n body: renderCard({\n status: \"error\",\n headline: \"Authorization failed\",\n message: provider\n ? `OpenCode couldn't finish connecting to ${escapeHtml(provider)}.`\n : \"OpenCode couldn't complete authorization.\",\n detail,\n footnote: \"Close this window and try again from OpenCode.\",\n }),\n })\n}\n\nexport interface BootstrapOptions {\n /** Same-origin path the in-browser script POSTs the parsed callback to. */\n tokenPath: string\n provider?: string\n}\n\n// For flows where the credential arrives in the URL fragment (implicit grant),\n// the browser must relay it back to the loopback server. This renders a pending\n// page whose script reads the fragment, POSTs it to `tokenPath`, then resolves\n// to the success or error state in place.\nexport function bootstrap(options: BootstrapOptions) {\n return renderDocument({\n title: \"Finishing sign-in\",\n body: renderCard({\n status: \"pending\",\n headline: \"Finishing sign-in\",\n message: options.provider\n ? `Completing your ${escapeHtml(options.provider)} authorization.`\n : \"Completing authorization.\",\n footnote: \"You can close this window once sign-in finishes.\",\n }),\n script: bootstrapScript(options),\n })\n}\n\nexport * as OauthCallbackPage from \"./page.js\"\n\ntype Status = \"pending\" | \"success\" | \"error\"\n\nfunction renderCard(input: { status: Status; headline: string; message: string; detail?: string; footnote: string }) {\n const detail = input.detail?.trim()\n return `<main class=\"card\" id=\"oc-card\" data-status=\"${input.status}\" role=\"status\" aria-live=\"polite\">\n <div class=\"brand\">${WORDMARK}</div>\n <div class=\"status\" aria-hidden=\"true\">\n <span class=\"icon icon-pending\">${ICON_SPINNER}</span>\n <span class=\"icon icon-success\">${ICON_CHECK}</span>\n <span class=\"icon icon-error\">${ICON_CROSS}</span>\n </div>\n <h1 class=\"headline\" id=\"oc-headline\">${escapeHtml(input.headline)}</h1>\n <p class=\"message\" id=\"oc-message\">${input.message}</p>\n <pre class=\"detail\" id=\"oc-detail\"${detail ? \"\" : \" hidden\"}>${detail ? escapeHtml(detail) : \"\"}</pre>\n <p class=\"footnote\" id=\"oc-footnote\">${escapeHtml(input.footnote)}</p>\n </main>`\n}\n\nfunction renderDocument(input: { title: string; body: string; script?: string }) {\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <meta name=\"robots\" content=\"noindex\" />\n <title>${escapeHtml(input.title)} · OpenCode</title>\n <style>${STYLES}</style>\n </head>\n <body>\n ${input.body}${input.script ? `\\n <script>${input.script}</script>` : \"\"}\n </body>\n</html>`\n}\n\nconst AUTO_CLOSE_SCRIPT = `setTimeout(function(){try{window.close()}catch(e){}},2500)`\n\nfunction bootstrapScript(options: BootstrapOptions) {\n return `var PROVIDER=${scriptString(options.provider ?? \"\")};\nvar TOKEN_URL=new URL(${scriptString(options.tokenPath)},window.location.origin).href;\n(function(){\n var card=document.getElementById(\"oc-card\"),headline=document.getElementById(\"oc-headline\"),message=document.getElementById(\"oc-message\"),detail=document.getElementById(\"oc-detail\"),footnote=document.getElementById(\"oc-footnote\");\n function fail(text){card.dataset.status=\"error\";headline.textContent=\"Authorization failed\";message.textContent=PROVIDER?(\"OpenCode couldn't finish connecting to \"+PROVIDER+\".\"):\"OpenCode couldn't complete authorization.\";if(text){detail.textContent=text;detail.hidden=false}footnote.textContent=\"Close this window and try again from OpenCode.\"}\n function ok(){card.dataset.status=\"success\";headline.textContent=\"Authorization successful\";message.textContent=PROVIDER?(\"OpenCode is now connected to \"+PROVIDER+\".\"):\"OpenCode is now authorized.\";detail.hidden=true;footnote.textContent=\"You can close this window.\";setTimeout(function(){try{window.close()}catch(e){}},2500)}\n try{\n var hash=new URLSearchParams((window.location.hash||\"\").slice(1));\n var search=new URLSearchParams(window.location.search||\"\");\n var err=hash.get(\"error\")||search.get(\"error\");\n var errDescription=hash.get(\"error_description\")||search.get(\"error_description\");\n var body=err?{error:err,error_description:errDescription||\"\"}:{access_token:hash.get(\"access_token\")||\"\",expires_in:hash.get(\"expires_in\")||\"0\",state:hash.get(\"state\")||\"\"};\n fetch(TOKEN_URL,{method:\"POST\",headers:{\"Content-Type\":\"application/json\"},body:JSON.stringify(body)}).then(function(res){\n if(!res.ok)return res.text().catch(function(){return\"\"}).then(function(t){throw new Error(t||(\"callback failed (\"+res.status+\")\"))});\n if(err){fail(errDescription||err);return}\n ok();\n }).catch(function(e){fail(String(e&&e.message?e.message:e))});\n }catch(e){fail(String(e&&e.message?e.message:e))}\n})()`\n}\n\nfunction scriptString(value: string) {\n return JSON.stringify(value).replaceAll(\"<\", \"\\\\u003c\")\n}\n\nfunction escapeHtml(value: string) {\n return value\n .replaceAll(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\")\n .replaceAll('\"', \""\")\n .replaceAll(\"'\", \"'\")\n}\n\n// Curated subset of OC-2 tokens (packages/ui/src/styles/theme.css). Default is\n// light; dark applies via prefers-color-scheme. The [data-theme] selectors let a\n// host force a scheme without changing the default.\nconst LIGHT_VARS = `\n --oc-bg: #f8f8f8;\n --oc-card: #fcfcfc;\n --oc-text-strong: #171717;\n --oc-text-base: #6f6f6f;\n --oc-text-weak: #8f8f8f;\n --oc-border-weak: #e5e5e5;\n --oc-icon-strong: #171717;\n --oc-icon-base: #8f8f8f;\n --oc-icon-weak: #dbdbdb;\n --oc-success: #2dba26;\n --oc-error: #ed4831;\n --oc-detail-bg: #fff8f6;\n --oc-detail-border: #fdc3b7;\n --oc-shadow: 0 16px 48px -6px rgba(0,0,0,.10), 0 6px 12px -2px rgba(0,0,0,.05), 0 1px 2px rgba(0,0,0,.06);`\n\nconst DARK_VARS = `\n --oc-bg: #101010;\n --oc-card: #161616;\n --oc-text-strong: rgba(255,255,255,.936);\n --oc-text-base: rgba(255,255,255,.618);\n --oc-text-weak: rgba(255,255,255,.422);\n --oc-border-weak: #282828;\n --oc-icon-strong: #ededed;\n --oc-icon-base: #7e7e7e;\n --oc-icon-weak: #343434;\n --oc-success: #12c905;\n --oc-error: #fc533a;\n --oc-detail-bg: #28110c;\n --oc-detail-border: #6a1206;\n --oc-shadow: 0 16px 48px -6px rgba(0,0,0,.55), 0 6px 12px -2px rgba(0,0,0,.35), 0 1px 2px rgba(0,0,0,.4);`\n\nconst STYLES = `\n :root { color-scheme: light dark;${LIGHT_VARS}\n --oc-font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n --oc-font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace;\n }\n @media (prefers-color-scheme: dark) { :root:not([data-theme=\"light\"]) {${DARK_VARS} } }\n :root[data-theme=\"dark\"] {${DARK_VARS} }\n :root[data-theme=\"light\"] {${LIGHT_VARS} }\n\n * { box-sizing: border-box; }\n html, body { margin: 0; height: 100%; }\n body {\n min-height: 100vh;\n display: grid;\n place-items: center;\n padding: 24px;\n background: var(--oc-bg);\n color: var(--oc-text-base);\n font-family: var(--oc-font-sans);\n line-height: 1.5;\n -webkit-font-smoothing: antialiased;\n text-rendering: optimizeLegibility;\n }\n .card {\n width: min(100%, 28rem);\n padding: 2.25rem 2rem 1.75rem;\n background: var(--oc-card);\n border: 1px solid var(--oc-border-weak);\n border-radius: 14px;\n box-shadow: var(--oc-shadow);\n text-align: center;\n }\n .brand { display: flex; justify-content: center; margin-bottom: 1.75rem; }\n .brand svg { height: 19px; width: auto; }\n .status { display: flex; justify-content: center; margin-bottom: 1.125rem; }\n .icon { display: none; line-height: 0; }\n .icon svg { display: block; }\n .card[data-status=\"pending\"] .icon-pending,\n .card[data-status=\"success\"] .icon-success,\n .card[data-status=\"error\"] .icon-error { display: block; }\n .icon-success { color: var(--oc-success); }\n .icon-error { color: var(--oc-error); }\n .icon-pending { color: var(--oc-text-weak); }\n .headline { margin: 0; font-size: 1.1875rem; font-weight: 500; line-height: 1.3; letter-spacing: -0.012em; color: var(--oc-text-strong); }\n .message { margin: 0.5rem 0 0; font-size: 0.9375rem; color: var(--oc-text-base); }\n .detail {\n margin: 1.25rem 0 0;\n padding: 0.75rem 0.875rem;\n text-align: left;\n font-family: var(--oc-font-mono);\n font-size: 0.8125rem;\n line-height: 1.55;\n color: var(--oc-text-strong);\n background: var(--oc-detail-bg);\n border: 1px solid var(--oc-detail-border);\n border-radius: 8px;\n white-space: pre-wrap;\n word-break: break-word;\n max-height: 9.5rem;\n overflow: auto;\n }\n .detail[hidden] { display: none; }\n .footnote { margin: 1.5rem 0 0; font-size: 0.8125rem; color: var(--oc-text-weak); }\n .spinner { animation: oc-spin 0.8s linear infinite; transform-origin: center; }\n @keyframes oc-spin { to { transform: rotate(360deg); } }\n @media (prefers-reduced-motion: reduce) { .spinner { animation: none; } }\n`\n\n// OpenCode wordmark — same path geometry as packages/ui/src/components/logo.tsx (Logo).\nconst WORDMARK = `<svg class=\"wordmark\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 234 42\" fill=\"none\" aria-label=\"OpenCode\" role=\"img\">\n <path d=\"M18 30H6V18H18V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M18 12H6V30H18V12ZM24 36H0V6H24V36Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M48 30H36V18H48V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M36 30H48V12H36V30ZM54 36H36V42H30V6H54V36Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M84 24V30H66V24H84Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M84 24H66V30H84V36H60V6H84V24ZM66 18H78V12H66V18Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M108 36H96V18H108V36Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M108 12H96V36H90V6H108V12ZM114 36H108V12H114V36Z\" fill=\"var(--oc-icon-base)\" />\n <path d=\"M144 30H126V18H144V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M144 12H126V30H144V36H120V6H144V12Z\" fill=\"var(--oc-icon-strong)\" />\n <path d=\"M168 30H156V18H168V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M168 12H156V30H168V12ZM174 36H150V6H174V36Z\" fill=\"var(--oc-icon-strong)\" />\n <path d=\"M198 30H186V18H198V30Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M198 12H186V30H198V12ZM204 36H180V6H198V0H204V36Z\" fill=\"var(--oc-icon-strong)\" />\n <path d=\"M234 24V30H216V24H234Z\" fill=\"var(--oc-icon-weak)\" />\n <path d=\"M216 12V18H228V12H216ZM234 24H216V30H234V36H210V6H234V24Z\" fill=\"var(--oc-icon-strong)\" />\n </svg>`\n\nconst ICON_CHECK = `<svg viewBox=\"0 0 24 24\" width=\"30\" height=\"30\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"m8.5 12.5 2.4 2.4 4.6-5.4\" /></svg>`\n\nconst ICON_CROSS = `<svg viewBox=\"0 0 24 24\" width=\"30\" height=\"30\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"m9 9 6 6m0-6-6 6\" /></svg>`\n\nconst ICON_SPINNER = `<svg class=\"spinner\" viewBox=\"0 0 24 24\" width=\"30\" height=\"30\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\"><circle cx=\"12\" cy=\"12\" r=\"9\" opacity=\"0.2\" /><path d=\"M21 12a9 9 0 0 0-9-9\" /></svg>`\n" | ||
| ], | ||
| "mappings": ";sIAoBO,SAAS,CAAO,CAAC,EAA+B,CACrD,IAAM,EAAW,GAAS,SAC1B,OAAO,EAAe,CACpB,MAAO,2BACP,KAAM,EAAW,CACf,OAAQ,UACR,SAAU,2BACV,QAAS,EAAW,gCAAgC,EAAW,CAAQ,KAAO,8BAC9E,SAAU,4BACZ,CAAC,EACD,OAAQ,GAAS,YAAc,GAAQ,OAAY,CACrD,CAAC,EAGI,SAAS,CAAK,CAAC,EAAgB,EAA+B,CACnE,IAAM,EAAW,GAAS,SAC1B,OAAO,EAAe,CACpB,MAAO,uBACP,KAAM,EAAW,CACf,OAAQ,QACR,SAAU,uBACV,QAAS,EACL,0CAA0C,EAAW,CAAQ,KAC7D,4CACJ,SACA,SAAU,gDACZ,CAAC,CACH,CAAC,EAaI,SAAS,CAAS,CAAC,EAA2B,CACnD,OAAO,EAAe,CACpB,MAAO,oBACP,KAAM,EAAW,CACf,OAAQ,UACR,SAAU,oBACV,QAAS,EAAQ,SACb,mBAAmB,EAAW,EAAQ,QAAQ,mBAC9C,4BACJ,SAAU,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A;AAAA;AAAA,+GAgBZ,EAAS;AAAA,qCACsB;AAAA;AAAA;AAAA;AAAA,2EAIsC;AAAA,8BAC7C;AAAA,+BACC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA8DzB,EAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,cAmBX,EAAa,iOAEb,EAAa,wNAEb,EAAe", | ||
| "debugId": "3B12A6660748792364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/ui/timeline.tsx", "src/commands/handlers/console/login.ts"], | ||
| "sourcesContent": [ | ||
| "import { createComponent as _$createComponent } from \"@opentui/solid\";\nimport { effect as _$effect } from \"@opentui/solid\";\nimport { createTextNode as _$createTextNode } from \"@opentui/solid\";\nimport { insertNode as _$insertNode } from \"@opentui/solid\";\nimport { insert as _$insert } from \"@opentui/solid\";\nimport { setProp as _$setProp } from \"@opentui/solid\";\nimport { createElement as _$createElement } from \"@opentui/solid\";\n/** @jsxImportSource @opentui/solid */\nimport { createCliRenderer, RGBA } from \"@opentui/core\";\nimport { createScrollbackWriter, render, useKeyboard } from \"@opentui/solid\";\nimport { registerOpencodeSpinner } from \"@opencode-ai/tui/component/register-spinner\";\nimport { Show, createSignal } from \"solid-js\";\nregisterOpencodeSpinner();\nconst SPINNER_FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\nconst IDLE_TIMEOUT = 1_000;\nconst COLORS = {\n accent: RGBA.fromIndex(6),\n error: RGBA.fromIndex(1),\n foreground: RGBA.defaultForeground(),\n muted: RGBA.fromIndex(8),\n success: RGBA.fromIndex(2)\n};\nconst ROWS = {\n intro: {\n marker: \"┌\",\n color: COLORS.muted,\n connector: true\n },\n item: {\n marker: \"●\",\n color: COLORS.accent,\n connector: true\n },\n success: {\n marker: \"◇\",\n color: COLORS.success,\n connector: true\n },\n failure: {\n marker: \"■\",\n color: COLORS.error,\n connector: false\n },\n outro: {\n marker: \"└\",\n color: COLORS.muted,\n connector: false\n }\n};\nfunction row(kind, value) {\n const style = ROWS[kind];\n return createScrollbackWriter(() => (() => {\n var _el$ = _$createElement(\"box\"),\n _el$2 = _$createElement(\"box\"),\n _el$3 = _$createElement(\"text\"),\n _el$4 = _$createElement(\"text\");\n _$insertNode(_el$, _el$2);\n _$setProp(_el$, \"width\", \"100%\");\n _$setProp(_el$, \"minHeight\", 1);\n _$setProp(_el$, \"flexDirection\", \"column\");\n _$insertNode(_el$2, _el$3);\n _$insertNode(_el$2, _el$4);\n _$setProp(_el$2, \"width\", \"100%\");\n _$setProp(_el$2, \"minHeight\", 1);\n _$setProp(_el$2, \"flexDirection\", \"row\");\n _$setProp(_el$2, \"gap\", 1);\n _$setProp(_el$3, \"flexShrink\", 0);\n _$insert(_el$3, () => style.marker);\n _$setProp(_el$4, \"wrapMode\", \"word\");\n _$insert(_el$4, value);\n _$insert(_el$, _$createComponent(Show, {\n get when() {\n return style.connector;\n },\n get children() {\n var _el$5 = _$createElement(\"text\");\n _$insertNode(_el$5, _$createTextNode(`│`));\n _$effect(_$p => _$setProp(_el$5, \"fg\", COLORS.muted, _$p));\n return _el$5;\n }\n }), null);\n _$effect(_p$ => {\n var _v$ = style.color,\n _v$2 = COLORS.foreground;\n _v$ !== _p$.e && (_p$.e = _$setProp(_el$3, \"fg\", _v$, _p$.e));\n _v$2 !== _p$.t && (_p$.t = _$setProp(_el$4, \"fg\", _v$2, _p$.t));\n return _p$;\n }, {\n e: undefined,\n t: undefined\n });\n return _el$;\n })(), {\n startOnNewLine: true,\n trailingNewline: !style.connector\n });\n}\nfunction TimelineFooter(props) {\n useKeyboard(event => {\n if (event.name !== \"escape\" && !(event.ctrl && event.name === \"c\")) return;\n event.preventDefault();\n props.cancel();\n });\n return (() => {\n var _el$7 = _$createElement(\"box\");\n _$setProp(_el$7, \"width\", \"100%\");\n _$setProp(_el$7, \"height\", 1);\n _$setProp(_el$7, \"flexDirection\", \"row\");\n _$setProp(_el$7, \"gap\", 1);\n _$insert(_el$7, _$createComponent(Show, {\n get when() {\n return props.pending();\n },\n children: text => [(() => {\n var _el$8 = _$createElement(\"spinner\");\n _$setProp(_el$8, \"frames\", SPINNER_FRAMES);\n _$setProp(_el$8, \"interval\", 80);\n _$effect(_$p => _$setProp(_el$8, \"color\", COLORS.accent, _$p));\n return _el$8;\n })(), (() => {\n var _el$9 = _$createElement(\"text\");\n _$setProp(_el$9, \"wrapMode\", \"none\");\n _$setProp(_el$9, \"truncate\", true);\n _$insert(_el$9, text);\n _$effect(_$p => _$setProp(_el$9, \"fg\", COLORS.foreground, _$p));\n return _el$9;\n })()]\n }));\n return _el$7;\n })();\n}\nfunction bounded(task) {\n return new Promise(resolve => {\n const timer = setTimeout(resolve, IDLE_TIMEOUT);\n timer.unref();\n const finish = () => {\n clearTimeout(timer);\n resolve();\n };\n void task.then(finish, finish);\n });\n}\nasync function shutdown(renderer) {\n await bounded(renderer.idle());\n try {\n renderer.externalOutputMode = \"passthrough\";\n } finally {\n try {\n renderer.screenMode = \"main-screen\";\n } finally {\n if (!renderer.isDestroyed) renderer.destroy();\n }\n }\n}\nexport async function createTimelineHost() {\n const stdout = process.stdout;\n const controller = new AbortController();\n const signals = [\"SIGINT\", \"SIGHUP\", \"SIGQUIT\"];\n const cancel = () => {\n if (!controller.signal.aborted) controller.abort();\n };\n signals.forEach(signal => process.on(signal, cancel));\n if (!stdout.isTTY || !process.stdin.isTTY) {\n let closed = false;\n let writing = false;\n let active;\n let closeTask;\n const write = async (kind, text) => {\n if (closed) throw new Error(\"timeline closed\");\n if (writing) throw new Error(\"timeline write already in progress\");\n writing = true;\n try {\n const style = kind === \"pending\" ? undefined : ROWS[kind];\n const marker = kind === \"pending\" ? \".\" : ROWS[kind].marker;\n const connector = style?.connector ? \"│\\n\" : \"\";\n active = new Promise((resolve, reject) => {\n stdout.write(`${marker} ${text}\\n${connector}`, error => error ? reject(error) : resolve());\n });\n await active;\n } finally {\n writing = false;\n active = undefined;\n }\n };\n const close = () => {\n if (closeTask) return closeTask;\n closed = true;\n closeTask = (async () => {\n await active?.catch(() => {});\n signals.forEach(signal => process.off(signal, cancel));\n })();\n return closeTask;\n };\n return {\n signal: controller.signal,\n intro: text => write(\"intro\", text),\n item: text => write(\"item\", text),\n pending: text => write(\"pending\", text),\n success: text => write(\"success\", text),\n failure: text => write(\"failure\", text),\n outro: text => write(\"outro\", text),\n close\n };\n }\n let renderer;\n try {\n // Start on a fresh row so delayed SSH cursor reports cannot make\n // split-footer overwrite the shell command.\n process.stdout.write(\"\\n\");\n renderer = await createCliRenderer({\n stdin: process.stdin,\n useMouse: false,\n autoFocus: false,\n openConsoleOnError: false,\n exitOnCtrlC: false,\n exitSignals: [],\n screenMode: \"split-footer\",\n footerHeight: 1,\n externalOutputMode: \"capture-stdout\",\n consoleMode: \"disabled\",\n clearOnShutdown: false\n });\n const activeRenderer = renderer;\n const [pending, setPending] = createSignal();\n const renderTask = render(() => _$createComponent(TimelineFooter, {\n pending: pending,\n cancel: cancel\n }), activeRenderer);\n void renderTask.catch(cancel);\n await bounded(activeRenderer.idle());\n let closed = false;\n let writing = false;\n let active;\n let closeTask;\n const write = (kind, text) => {\n if (closed) return Promise.reject(new Error(\"timeline closed\"));\n if (writing) return Promise.reject(new Error(\"timeline write already in progress\"));\n writing = true;\n active = (async () => {\n if (kind === \"pending\") {\n setPending(text);\n activeRenderer.requestRender();\n } else {\n if (kind === \"success\" || kind === \"failure\" || kind === \"outro\") setPending(undefined);\n activeRenderer.writeToScrollback(row(kind, text));\n activeRenderer.requestRender();\n }\n await bounded(activeRenderer.idle());\n })().finally(() => {\n writing = false;\n active = undefined;\n });\n return active;\n };\n const close = () => {\n if (closeTask) return closeTask;\n closed = true;\n closeTask = (async () => {\n await active?.catch(() => {});\n try {\n await shutdown(activeRenderer);\n await bounded(renderTask);\n } finally {\n signals.forEach(signal => process.off(signal, cancel));\n }\n })();\n return closeTask;\n };\n return {\n signal: controller.signal,\n intro: text => write(\"intro\", text),\n item: text => write(\"item\", text),\n pending: text => write(\"pending\", text),\n success: text => write(\"success\", text),\n failure: text => write(\"failure\", text),\n outro: text => write(\"outro\", text),\n close\n };\n } catch (error) {\n try {\n if (renderer) await shutdown(renderer);\n } finally {\n signals.forEach(signal => process.off(signal, cancel));\n }\n throw error;\n }\n}", | ||
| "import { Cause, Effect, Exit, Option } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode, type OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport { AppProcess } from \"@opencode-ai/util/process\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { createTimelineHost, type TimelineHost } from \"../../../ui/timeline\"\nimport { errorMessage } from \"../../../util/error\"\n\nconst integrationID = \"opencode\"\nconst location = { directory: process.cwd() }\n\nexport default Runtime.handler(\n Commands.commands.console.commands.login,\n Effect.fn(\"cli.console.login\")(function* (input) {\n const timeline = yield* Effect.acquireRelease(\n Effect.promise(() => createTimelineHost()),\n (value) => request(() => value.close()).pipe(Effect.ignore),\n )\n const exit = yield* login(timeline, Option.getOrUndefined(input.url)).pipe(\n Effect.raceFirst(AppProcess.waitForAbort(timeline.signal)),\n Effect.exit,\n )\n if (Exit.isSuccess(exit)) return\n\n const cancelled = timeline.signal.aborted\n yield* request(() =>\n timeline.failure(cancelled ? \"Authorization cancelled\" : errorMessage(Cause.squash(exit.cause))),\n ).pipe(Effect.ignore)\n process.exitCode = cancelled ? 130 : 1\n }),\n)\n\nconst login = Effect.fn(\"cli.console.login.run\")(function* (timeline: TimelineHost, server?: string) {\n yield* request(() => timeline.intro(\"Log in\"))\n yield* request(() => timeline.pending(\"Connecting to OpenCode...\"))\n\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const found = yield* request((signal) => client.integration.get({ integrationID, location }, { signal }))\n const integration = yield* required(found.data, \"OpenCode Console integration is unavailable\")\n const method = yield* required(\n integration.methods.find((candidate) => candidate.type === \"oauth\"),\n \"OpenCode Console login is unavailable\",\n )\n\n yield* request(() => timeline.pending(\"Starting authorization...\"))\n const started = yield* request((signal) =>\n client.integration.oauth.connect(\n {\n integrationID,\n methodID: method.id,\n ...(server ? { answer: { server } } : {}),\n location,\n },\n { signal },\n ),\n )\n const attempt = started.data\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.oauth.cancel(\n { integrationID, attemptID: attempt.attemptID, location },\n { signal: AbortSignal.timeout(5_000) },\n ),\n ).pipe(Effect.ignore),\n )\n if (attempt.mode !== \"auto\") yield* Effect.fail(new Error(\"OpenCode Console requires a device login\"))\n\n yield* request(() => timeline.item(`Go to: ${attempt.url}`))\n yield* request(() => timeline.item(attempt.instructions))\n yield* request(async () => {\n const { default: open } = await import(\"open\")\n await open(attempt.url)\n }).pipe(Effect.ignore)\n yield* request(() => timeline.pending(\"Waiting for authorization...\"))\n\n const status = yield* waitForConsoleLogin(client, integrationID, attempt.attemptID)\n if (status.status === \"failed\") yield* Effect.fail(new Error(status.message))\n if (status.status === \"expired\") yield* Effect.fail(new Error(\"Device code expired\"))\n\n yield* request(() => timeline.success(\"Connected to OpenCode Console\"))\n yield* request(() => timeline.outro(\"Done\"))\n})\n\nconst waitForConsoleLogin = Effect.fn(\"cli.console.login.wait\")(function* (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n) {\n while (true) {\n const response = yield* request((signal) =>\n client.integration.oauth.status({ integrationID, attemptID, location }, { signal }),\n )\n if (response.data.status !== \"pending\") return response.data\n yield* Effect.sleep(500)\n }\n})\n\nfunction request<A>(task: (signal: AbortSignal) => Promise<A>) {\n return Effect.tryPromise({\n try: task,\n catch: (cause) => cause,\n })\n}\n\nfunction required<A>(value: A | null | undefined, message: string) {\n return value === null || value === undefined ? Effect.fail(new Error(message)) : Effect.succeed(value)\n}\n" | ||
| ], | ||
| "mappings": ";+tCAYA,EAAwB,EACxB,IAAM,GAAiB,CAAC,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,QAAG,EAClE,GAAe,KACf,EAAS,CACb,OAAQ,EAAK,UAAU,CAAC,EACxB,MAAO,EAAK,UAAU,CAAC,EACvB,WAAY,EAAK,kBAAkB,EACnC,MAAO,EAAK,UAAU,CAAC,EACvB,QAAS,EAAK,UAAU,CAAC,CAC3B,EACM,EAAO,CACX,MAAO,CACL,OAAQ,SACR,MAAO,EAAO,MACd,UAAW,EACb,EACA,KAAM,CACJ,OAAQ,SACR,MAAO,EAAO,OACd,UAAW,EACb,EACA,QAAS,CACP,OAAQ,SACR,MAAO,EAAO,QACd,UAAW,EACb,EACA,QAAS,CACP,OAAQ,SACR,MAAO,EAAO,MACd,UAAW,EACb,EACA,MAAO,CACL,OAAQ,SACR,MAAO,EAAO,MACd,UAAW,EACb,CACF,EACA,SAAS,EAAG,CAAC,EAAM,EAAO,CACxB,IAAM,EAAQ,EAAK,GACnB,OAAO,EAAuB,KAAO,IAAM,CACzC,IAAI,EAAO,EAAgB,KAAK,EAC9B,EAAQ,EAAgB,KAAK,EAC7B,EAAQ,EAAgB,MAAM,EAC9B,EAAQ,EAAgB,MAAM,EAoChC,OAnCA,EAAa,EAAM,CAAK,EACxB,EAAU,EAAM,QAAS,MAAM,E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A,EACA,CACA,MAAO,GAAM,CACX,IAAM,EAAW,MAAO,EAAQ,CAAC,IAC/B,EAAO,YAAY,MAAM,OAAO,CAAE,gBAAe,YAAW,UAAS,EAAG,CAAE,QAAO,CAAC,CACpF,EACA,GAAI,EAAS,KAAK,SAAW,UAAW,OAAO,EAAS,KACxD,MAAO,EAAO,MAAM,GAAG,GAE1B,EAED,SAAS,CAAU,CAAC,EAA2C,CAC7D,OAAO,EAAO,WAAW,CACvB,IAAK,EACL,MAAO,CAAC,IAAU,CACpB,CAAC,EAGH,SAAS,CAAW,CAAC,EAA6B,EAAiB,CACjE,OAAO,IAAU,MAAQ,IAAU,OAAY,EAAO,KAAS,MAAM,CAAO,CAAC,EAAI,EAAO,QAAQ,CAAK", | ||
| "debugId": "AF6660314DD2A85864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "C67631401395EE5664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+nested-clients@3.997.43/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsRestJsonProtocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"awsssoportal\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultSSOHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"GetRoleCredentials\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"awsssoportal\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.42\";\nvar packageInfo = {\n\tversion: version};\n\nconst k = \"ref\";\nconst a = -1, b = true, c = \"isSet\", d = \"PartitionResult\", e = \"booleanEquals\", f = \"getAttr\", g = { [k]: \"Endpoint\" }, h = { [k]: d }, i = {}, j = [{ [k]: \"Region\" }];\nconst _data = {\n conditions: [\n [c, [g]],\n [c, j],\n [\"aws.partition\", j, d],\n [e, [{ [k]: \"UseFIPS\" }, b]],\n [e, [{ [k]: \"UseDualStack\" }, b]],\n [e, [{ fn: f, argv: [h, \"supportsDualStack\"] }, b]],\n [e, [{ fn: f, argv: [h, \"supportsFIPS\"] }, b]],\n [\"stringEquals\", [{ fn: f, argv: [h, \"name\"] }, \"aws-us-gov\"]]\n ],\n results: [\n [a],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [g, i],\n [\"https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://portal.sso.{Region}.amazonaws.com\", i],\n [\"https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [\"https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://portal.sso.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 13, 3,\n 1, 4, r + 12,\n 2, 5, r + 12,\n 3, 8, 6,\n 4, 7, r + 11,\n 5, r + 9, r + 10,\n 4, 11, 9,\n 6, 10, r + 8,\n 7, r + 6, r + 7,\n 5, 12, r + 5,\n 6, r + 4, r + 5,\n 3, r + 1, 14,\n 4, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass SSOServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, SSOServiceException.prototype);\n }\n}\n\nclass InvalidRequestException extends SSOServiceException {\n name = \"InvalidRequestException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"InvalidRequestException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidRequestException.prototype);\n }\n}\nclass ResourceNotFoundException extends SSOServiceException {\n name = \"ResourceNotFoundException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ResourceNotFoundException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ResourceNotFoundException.prototype);\n }\n}\nclass TooManyRequestsException extends SSOServiceException {\n name = \"TooManyRequestsException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"TooManyRequestsException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, TooManyRequestsException.prototype);\n }\n}\nclass UnauthorizedException extends SSOServiceException {\n name = \"UnauthorizedException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"UnauthorizedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, UnauthorizedException.prototype);\n }\n}\n\nconst _ATT = \"AccessTokenType\";\nconst _GRC = \"GetRoleCredentials\";\nconst _GRCR = \"GetRoleCredentialsRequest\";\nconst _GRCRe = \"GetRoleCredentialsResponse\";\nconst _IRE = \"InvalidRequestException\";\nconst _RC = \"RoleCredentials\";\nconst _RNFE = \"ResourceNotFoundException\";\nconst _SAKT = \"SecretAccessKeyType\";\nconst _STT = \"SessionTokenType\";\nconst _TMRE = \"TooManyRequestsException\";\nconst _UE = \"UnauthorizedException\";\nconst _aI = \"accountId\";\nconst _aKI = \"accessKeyId\";\nconst _aT = \"accessToken\";\nconst _ai = \"account_id\";\nconst _c = \"client\";\nconst _e = \"error\";\nconst _ex = \"expiration\";\nconst _h = \"http\";\nconst _hE = \"httpError\";\nconst _hH = \"httpHeader\";\nconst _hQ = \"httpQuery\";\nconst _m = \"message\";\nconst _rC = \"roleCredentials\";\nconst _rN = \"roleName\";\nconst _rn = \"role_name\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.sso\";\nconst _sAK = \"secretAccessKey\";\nconst _sT = \"sessionToken\";\nconst _xasbt = \"x-amz-sso_bearer_token\";\nconst n0 = \"com.amazonaws.sso\";\nconst _s_registry = TypeRegistry.for(_s);\nvar SSOServiceException$ = [-3, _s, \"SSOServiceException\", 0, [], []];\n_s_registry.registerError(SSOServiceException$, SSOServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar InvalidRequestException$ = [-3, n0, _IRE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(InvalidRequestException$, InvalidRequestException);\nvar ResourceNotFoundException$ = [-3, n0, _RNFE,\n { [_e]: _c, [_hE]: 404 },\n [_m],\n [0]\n];\nn0_registry.registerError(ResourceNotFoundException$, ResourceNotFoundException);\nvar TooManyRequestsException$ = [-3, n0, _TMRE,\n { [_e]: _c, [_hE]: 429 },\n [_m],\n [0]\n];\nn0_registry.registerError(TooManyRequestsException$, TooManyRequestsException);\nvar UnauthorizedException$ = [-3, n0, _UE,\n { [_e]: _c, [_hE]: 401 },\n [_m],\n [0]\n];\nn0_registry.registerError(UnauthorizedException$, UnauthorizedException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar AccessTokenType = [0, n0, _ATT, 8, 0];\nvar SecretAccessKeyType = [0, n0, _SAKT, 8, 0];\nvar SessionTokenType = [0, n0, _STT, 8, 0];\nvar GetRoleCredentialsRequest$ = [3, n0, _GRCR,\n 0,\n [_rN, _aI, _aT],\n [[0, { [_hQ]: _rn }], [0, { [_hQ]: _ai }], [() => AccessTokenType, { [_hH]: _xasbt }]], 3\n];\nvar GetRoleCredentialsResponse$ = [3, n0, _GRCRe,\n 0,\n [_rC],\n [[() => RoleCredentials$, 0]]\n];\nvar RoleCredentials$ = [3, n0, _RC,\n 0,\n [_aKI, _sAK, _sT, _ex],\n [0, [() => SecretAccessKeyType, 0], [() => SessionTokenType, 0], 1]\n];\nvar GetRoleCredentials$ = [9, n0, _GRC,\n { [_h]: [\"GET\", \"/federation/credentials\", 200] }, () => GetRoleCredentialsRequest$, () => GetRoleCredentialsResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2019-06-10\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsRestJsonProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.sso\",\n errorTypeRegistries,\n version: \"2019-06-10\",\n serviceTarget: \"SWBPortalService\",\n },\n serviceId: config?.serviceId ?? \"SSO\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass SSOClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSSOHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"SWBPortalService\", \"SSOClient\", getEndpointPlugin);\nconst _ep0 = {};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass GetRoleCredentialsCommand extends command(_ep0, _mw0, \"GetRoleCredentials\", GetRoleCredentials$) {\n}\n\nconst commands = {\n GetRoleCredentialsCommand,\n};\nclass SSO extends SSOClient {\n}\ncreateAggregatedClient(commands, SSO);\n\nexports.GetRoleCredentials$ = GetRoleCredentials$;\nexports.GetRoleCredentialsCommand = GetRoleCredentialsCommand;\nexports.GetRoleCredentialsRequest$ = GetRoleCredentialsRequest$;\nexports.GetRoleCredentialsResponse$ = GetRoleCredentialsResponse$;\nexports.InvalidRequestException = InvalidRequestException;\nexports.InvalidRequestException$ = InvalidRequestException$;\nexports.ResourceNotFoundException = ResourceNotFoundException;\nexports.ResourceNotFoundException$ = ResourceNotFoundException$;\nexports.RoleCredentials$ = RoleCredentials$;\nexports.SSO = SSO;\nexports.SSOClient = SSOClient;\nexports.SSOServiceException = SSOServiceException;\nexports.SSOServiceException$ = SSOServiceException$;\nexports.TooManyRequestsException = TooManyRequestsException;\nexports.TooManyRequestsException$ = TooManyRequestsException$;\nexports.UnauthorizedException = UnauthorizedException;\nexports.UnauthorizedException$ = UnauthorizedException$;\nexports.errorTypeRegistries = errorTypeRegistries;\n" | ||
| ], | ||
| "mappings": ";iXAAA,IAAQ,wBAAsB,gCAAiC,GAAmC,kCAAgC,8BAA4B,sCAAoC,0CAAwC,0BAAwB,2BAAyB,sBAAoB,uBAAqB,mBAAiB,sCAC7U,gBAAc,0CAAwC,iCAA+B,+BACrF,oBAA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| ||
| "mappings": "", | ||
| "debugId": "F13BC5352D20A0AC64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/mcp.ts"], | ||
| "sourcesContent": [ | ||
| "export * as Mcp from \"./mcp.js\"\n\nimport { Schema } from \"effect\"\nimport { optional, PositiveInt } from \"./schema.js\"\nimport { IntegrationID } from \"./integration-id.js\"\n\nexport class TimeoutConfig extends Schema.Class<TimeoutConfig>(\"Mcp.TimeoutConfig\")({\n startup: PositiveInt.pipe(optional).annotate({\n description: \"Maximum time in milliseconds to establish and initialize the MCP server.\",\n }),\n catalog: PositiveInt.pipe(optional).annotate({\n description: \"Maximum time in milliseconds to wait for MCP discovery requests such as tools/list and prompts/list.\",\n }),\n execution: PositiveInt.pipe(optional).annotate({\n description: \"Maximum time in milliseconds to wait for MCP tool and prompt execution.\",\n }),\n}) {}\n\nexport class LocalConfig extends Schema.Class<LocalConfig>(\"Mcp.LocalConfig\")({\n type: Schema.Literal(\"local\"),\n command: Schema.String.pipe(Schema.Array),\n cwd: Schema.String.pipe(optional).annotate({\n description: \"Working directory for the MCP server process. Relative paths resolve from the workspace directory.\",\n }),\n environment: Schema.Record(Schema.String, Schema.String).pipe(optional),\n disabled: Schema.Boolean.pipe(optional),\n codemode: Schema.Boolean.pipe(optional).annotate({\n description: \"Expose this server's tools through Code Mode. Defaults to true.\",\n }),\n timeout: TimeoutConfig.pipe(optional),\n}) {}\n\nexport class OAuthConfig extends Schema.Class<OAuthConfig>(\"Mcp.OAuthConfig\")({\n client_id: Schema.String.pipe(optional),\n client_secret: Schema.String.pipe(optional),\n scope: Schema.String.pipe(optional),\n callback_port: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })).pipe(optional),\n redirect_uri: Schema.String.pipe(optional),\n}) {}\n\nexport class RemoteConfig extends Schema.Class<RemoteConfig>(\"Mcp.RemoteConfig\")({\n type: Schema.Literal(\"remote\"),\n url: Schema.String,\n headers: Schema.Record(Schema.String, Schema.String).pipe(optional),\n oauth: Schema.Union([OAuthConfig, Schema.Literal(false)]).pipe(optional),\n disabled: Schema.Boolean.pipe(optional),\n codemode: Schema.Boolean.pipe(optional).annotate({\n description: \"Expose this server's tools through Code Mode. Defaults to true.\",\n }),\n timeout: TimeoutConfig.pipe(optional),\n}) {}\n\nexport const ServerConfig = Schema.Union([LocalConfig, RemoteConfig]).pipe(Schema.toTaggedUnion(\"type\"))\nexport type ServerConfig = typeof ServerConfig.Type\n\nconst Connected = Schema.Struct({ status: Schema.Literal(\"connected\") }).annotate({\n identifier: \"Mcp.Status.Connected\",\n})\nconst Pending = Schema.Struct({ status: Schema.Literal(\"pending\") }).annotate({\n identifier: \"Mcp.Status.Pending\",\n})\nconst Disabled = Schema.Struct({ status: Schema.Literal(\"disabled\") }).annotate({\n identifier: \"Mcp.Status.Disabled\",\n})\nconst Failed = Schema.Struct({ status: Schema.Literal(\"failed\"), error: Schema.String }).annotate({\n identifier: \"Mcp.Status.Failed\",\n})\nconst NeedsAuth = Schema.Struct({ status: Schema.Literal(\"needs_auth\") }).annotate({\n identifier: \"Mcp.Status.NeedsAuth\",\n})\n\nexport type Status = typeof Status.Type\nexport const Status = Schema.Union([Connected, Pending, Disabled, Failed, NeedsAuth]).pipe(\n Schema.toTaggedUnion(\"status\"),\n)\n\nexport interface Server extends Schema.Schema.Type<typeof Server> {}\nexport const Server = Schema.Struct({\n name: Schema.String,\n status: Status,\n // Set for remote servers registered as OAuth integrations; lets clients act on the right integration\n // without matching by name, which could collide with provider or plugin integrations.\n integrationID: optional(IntegrationID),\n}).annotate({ identifier: \"Mcp.Server\" })\n\nexport interface Resource extends Schema.Schema.Type<typeof Resource> {}\nexport const Resource = Schema.Struct({\n server: Schema.String,\n name: Schema.String,\n uri: Schema.String,\n description: optional(Schema.String),\n mimeType: optional(Schema.String),\n}).annotate({ identifier: \"Mcp.Resource\" })\n\nexport interface ResourceTemplate extends Schema.Schema.Type<typeof ResourceTemplate> {}\nexport const ResourceTemplate = Schema.Struct({\n server: Schema.String,\n name: Schema.String,\n uriTemplate: Schema.String,\n description: optional(Schema.String),\n mimeType: optional(Schema.String),\n}).annotate({ identifier: \"Mcp.ResourceTemplate\" })\n\nexport interface ResourceCatalog extends Schema.Schema.Type<typeof ResourceCatalog> {}\nexport const ResourceCatalog = Schema.Struct({\n resources: Schema.Array(Resource),\n templates: Schema.Array(ResourceTemplate),\n}).annotate({ identifier: \"Mcp.ResourceCatalog\" })\n\nexport const ResourceContentPart = Schema.Union([\n Schema.Struct({\n type: Schema.Literal(\"text\"),\n uri: Schema.String,\n text: Schema.String,\n mimeType: optional(Schema.String),\n }),\n Schema.Struct({\n type: Schema.Literal(\"blob\"),\n uri: Schema.String,\n blob: Schema.String,\n mimeType: optional(Schema.String),\n }),\n]).pipe(Schema.toTaggedUnion(\"type\"), Schema.annotate({ identifier: \"Mcp.ResourceContentPart\" }))\nexport type ResourceContentPart = typeof ResourceContentPart.Type\n\nexport interface ResourceContent extends Schema.Schema.Type<typeof ResourceContent> {}\nexport const ResourceContent = Schema.Struct({\n server: Schema.String,\n uri: Schema.String,\n contents: Schema.Array(ResourceContentPart),\n}).annotate({ identifier: \"Mcp.ResourceContent\" })\n" | ||
| ], | ||
| "mappings": ";sdAMO,MAAM,UAAsB,EAAO,MAAqB,mBAAmB,EAAE,CAClF,QAAS,EAAY,KAAK,CAAQ,EAAE,SAAS,CAC3C,YAAa,0EACf,CAAC,EACD,QAAS,EAAY,KAAK,CAAQ,EAAE,SAAS,CAC3C,YAAa,sGACf,CAAC,EACD,UAAW,EAAY,KAAK,CAAQ,EAAE,SAAS,CAC7C,YAAa,yEACf,CAAC,CACH,CAAC,CAAE,CAAC,CAEG,MAAM,UAAoB,EAAO,MAAmB,iBAAiB,EAAE,CAC5E,KAAM,EAAO,QAAQ,OAAO,EAC5B,QAAS,EAAO,OAAO,KAAK,EAAO,KAAK,EACxC,IAAK,EAAO,OAAO,KAAK,CAAQ,EAAE,SAAS,CACzC,YAAa,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3B,IAAK,EAAO,OACZ,KAAM,EAAO,OACb,SAAU,EAAS,EAAO,MAAM,CAClC,CAAC,EACD,EAAO,OAAO,CACZ,KAAM,EAAO,QAAQ,MAAM,EAC3B,IAAK,EAAO,OACZ,KAAM,EAAO,OACb,SAAU,EAAS,EAAO,MAAM,CAClC,CAAC,CACH,CAAC,EAAE,KAAK,EAAO,cAAc,MAAM,EAAG,EAAO,SAAS,CAAE,WAAY,yBAA0B,CAAC,CAAC,EAInF,EAAkB,EAAO,OAAO,CAC3C,OAAQ,EAAO,OACf,IAAK,EAAO,OACZ,SAAU,EAAO,MAAM,CAAmB,CAC5C,CAAC,EAAE,SAAS,CAAE,WAAY,qBAAsB,CAAC", | ||
| "debugId": "08BC1812EBAC719764756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mini.ts"], | ||
| "sourcesContent": [ | ||
| "import { Context, Effect, FileSystem, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\nimport { Config } from \"../../config\"\nimport { resolve } from \"@opencode-ai/tui/config\"\nimport { Global } from \"@opencode-ai/util/global\"\n\nexport default Runtime.handler(Commands.commands.mini, (input) =>\n Effect.gen(function* () {\n const { runMini, validateMiniTerminal } = yield* Effect.promise(() => import(\"../../mini\"))\n yield* Effect.promise(async () => validateMiniTerminal())\n const serverURL = Option.getOrUndefined(input.server)\n const server = yield* ServerConnection.resolve({\n server: serverURL,\n standalone: input.standalone,\n mismatch: \"replace\",\n })\n const config = yield* Config.Service\n const global = yield* Global.Service\n const resolved = resolve(yield* config.get(), { terminalSuspend: process.platform !== \"win32\" })\n const fileSystem = yield* FileSystem.FileSystem\n const runServicePromise = Effect.runPromiseWith(Context.make(FileSystem.FileSystem, fileSystem))\n const service = server.service\n yield* Effect.promise(() =>\n runMini({\n server: {\n endpoint: server.endpoint,\n reconnect: service ? (signal) => runServicePromise(service.reconnect(), { signal }) : undefined,\n },\n continue: input.continue,\n session: Option.getOrUndefined(input.session),\n fork: input.fork,\n model: Option.getOrUndefined(input.model),\n agent: Option.getOrUndefined(input.agent),\n prompt: Option.getOrUndefined(input.prompt),\n replay: Option.getOrUndefined(input.replay) ?? resolved.mini?.replay ?? true,\n replayLimit: Option.getOrUndefined(input.replayLimit) ?? resolved.mini?.replay_limit,\n demo: input.demo,\n tuiConfig: resolved,\n config: {\n update: (update) => runServicePromise(config.update(update)),\n },\n paths: { home: global.home, state: global.state, log: global.log },\n }),\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";4mCAQA,IAAe,IAAQ,QAAQ,EAAS,SAAS,KAAM,CAAC,IACtD,EAAO,IAAI,SAAU,EAAG,CACtB,IAAQ,UAAS,wBAAyB,MAAO,EAAO,QAAQ,IAAa,wCAAa,EAC1F,MAAO,EAAO,QAAQ,SAAY,EAAqB,CAAC,EACxD,IAAM,EAAY,EAAO,eAAe,EAAM,MAAM,EAC9C,EAAS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EACR,WAAY,EAAM,WAClB,SAAU,SACZ,CAAC,EACK,EAAS,MAAO,EAAO,QACvB,EAAS,MAAO,EAAO,QACvB,EAAW,EAAQ,MAAO,EAAO,IAAI,EAAG,CAAE,gBAAiB,EAA6B,CAAC,EACzF,EAAa,MAAO,EAAW,WAC/B,EAAoB,EAAO,eAAe,EAAQ,KAAK,EAAW,WAAY,CAAU,CAAC,EACzF,EAAU,EAAO,QACvB,MAAO,EAAO,QAAQ,IACpB,EAAQ,CACN,OAAQ,CACN,SAAU,EAAO,SACjB,UAAW,EAAU,CAAC,IAAW,EAAkB,EAAQ,UAAU,EAAG,CAAE,QAAO,CAAC,EAAI,MACxF,EACA,SAAU,EAAM,SAChB,QAAS,EAAO,eAAe,EAAM,OAAO,EAC5C,KAAM,EAAM,KACZ,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,MAAO,EAAO,eAAe,EAAM,KAAK,EACxC,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,OAAQ,EAAO,eAAe,EAAM,MAAM,GAAK,EAAS,MAAM,QAAU,GACxE,YAAa,EAAO,eAAe,EAAM,WAAW,GAAK,EAAS,MAAM,aACxE,KAAM,EAAM,KACZ,UAAW,EACX,OAAQ,CACN,OAAQ,CAAC,IAAW,EAAkB,EAAO,OAAO,CAAM,CAAC,CAC7D,EACA,MAAO,CAAE,KAAM,EAAO,KAAM,MAAO,EAAO,MAAO,IAAK,EAAO,GAAI,CACnE,CAAC,CACH,EACD,CACH", | ||
| "debugId": "74C4780C1AA7216B64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/debug/agents.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.debug.commands.agents,\n Effect.fn(\"cli.debug.agents\")(function* () {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.agent.list({ location: { directory: process.cwd() } }))\n process.stdout.write(\n JSON.stringify(\n response.data.toSorted((a, b) => a.id.localeCompare(b.id)),\n null,\n 2,\n ) + EOL,\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";08BAAA,cAAS,WAQT,IAAe,IAAQ,QACrB,EAAS,SAAS,MAAM,SAAS,OACjC,EAAO,GAAG,kBAAkB,EAAE,SAAU,EAAG,CACzC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAW,MAAO,EAAO,QAAQ,IAAM,EAAO,MAAM,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,EAC1G,QAAQ,OAAO,MACb,KAAK,UACH,EAAS,KAAK,SAAS,CAAC,EAAG,IAAM,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC,EACzD,KACA,CACF,EAAI,CACN,EACD,CACH", | ||
| "debugId": "A77BBA3A903C1F1164756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/workspace.ts"], | ||
| "sourcesContent": [ | ||
| "export * as Workspace from \"./workspace.js\"\n\nimport { Schema } from \"effect\"\nimport { WorkspaceEvent } from \"./workspace-event.js\"\nimport { WorkspaceID } from \"./workspace-id.js\"\n\nexport const ID = WorkspaceID\nexport type ID = WorkspaceID\n\nexport const DestroyResult = Schema.Struct({\n destroyed: Schema.Boolean.annotate({\n description: \"True when this request transitioned the workspace from existing to destroyed.\",\n }),\n}).annotate({\n identifier: \"WorkspaceDestroyResult\",\n description: \"Reports whether this request destroyed an existing workspace.\",\n})\nexport interface DestroyResult extends Schema.Schema.Type<typeof DestroyResult> {}\n\nexport const Event = WorkspaceEvent\n" | ||
| ], | ||
| "mappings": ";yRAMO,IAAM,EAAK,EAGL,EAAgB,EAAO,OAAO,CACzC,UAAW,EAAO,QAAQ,SAAS,CACjC,YAAa,+EACf,CAAC,CACH,CAAC,EAAE,SAAS,CACV,WAAY,yBACZ,YAAa,+DACf,CAAC,EAGY,EAAQ", | ||
| "debugId": "0116A91F29B02F2864756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/import.ts"], | ||
| "sourcesContent": [ | ||
| "import { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Session } from \"@opencode-ai/schema/session\"\nimport { SessionTransfer } from \"@opencode-ai/schema/session-transfer\"\nimport { Effect, Option, Schema } from \"effect\"\nimport { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nexport default Runtime.handler(\n Commands.commands.import,\n Effect.fn(\"cli.import\")(function* (input) {\n const text = yield* Effect.tryPromise({\n try: () =>\n input.file.startsWith(\"http://\") || input.file.startsWith(\"https://\")\n ? fetch(input.file).then((response) => {\n if (!response.ok) throw new Error(`Failed to fetch session data: ${response.statusText}`)\n return response.text()\n })\n : Bun.file(input.file).text(),\n catch: (cause) =>\n new Error(`Failed to read session data: ${cause instanceof Error ? cause.message : String(cause)}`),\n })\n const data = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(SessionTransfer.Data))(text)\n const encoded = Schema.encodeSync(SessionTransfer.Data)(data)\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n })\n const client = OpenCode.make({\n baseUrl: server.endpoint.url,\n headers: Service.headers(server.endpoint),\n })\n const location = yield* Effect.promise(() =>\n client.location.get({\n location: { directory: path.resolve(Option.getOrElse(input.directory, () => process.cwd())) },\n }),\n )\n const response = yield* Effect.promise(() =>\n fetch(new URL(\"/api/session/import\", server.endpoint.url), {\n method: \"POST\",\n headers: { ...Service.headers(server.endpoint), \"content-type\": \"application/json\" },\n body: JSON.stringify({\n ...encoded,\n location: { directory: location.directory, workspaceID: location.workspaceID },\n }),\n }),\n )\n if (response.status === 409) {\n process.stderr.write(`Session already exists${EOL}`)\n return\n }\n if (!response.ok) yield* Effect.fail(new Error(`Failed to import session: ${response.statusText}`))\n const imported = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Struct({ data: Session.Info })))(\n yield* Effect.promise(() => response.text()),\n )\n process.stdout.write(`Imported session: ${imported.data.id}${EOL}`)\n }),\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W,EAAS,UAAW,YAAa,EAAS,WAAY,CAC/E,CAAC,CACH,CAAC,CACH,EACA,GAAI,EAAS,SAAW,IAAK,CAC3B,QAAQ,OAAO,MAAM,yBAAyB,GAAK,EACnD,OAEF,GAAI,CAAC,EAAS,GAAI,MAAO,EAAO,KAAS,MAAM,6BAA6B,EAAS,YAAY,CAAC,EAClG,IAAM,EAAW,MAAO,EAAO,oBAAoB,EAAO,eAAe,EAAO,OAAO,CAAE,KAAM,EAAQ,IAAK,CAAC,CAAC,CAAC,EAC7G,MAAO,EAAO,QAAQ,IAAM,EAAS,KAAK,CAAC,CAC7C,EACA,QAAQ,OAAO,MAAM,qBAAqB,EAAS,KAAK,KAAK,GAAK,EACnE,CACH", | ||
| "debugId": "97ED76B38B0D952064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+perplexity@3.0.26+d6123d32214422cb/node_modules/@ai-sdk/perplexity/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/perplexity-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n generateId,\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/perplexity-language-model.ts\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonErrorResponseHandler,\n createJsonResponseHandler,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z } from \"zod/v4\";\n\n// src/convert-perplexity-usage.ts\nfunction convertPerplexityUsage(usage) {\n var _a, _b, _c;\n if (usage == null) {\n return {\n inputTokens: {\n total: void 0,\n noCache: void 0,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: void 0,\n text: void 0,\n reasoning: void 0\n },\n raw: void 0\n };\n }\n const promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0;\n const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;\n const reasoningTokens = (_c = usage.reasoning_tokens) != null ? _c : 0;\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: completionTokens,\n text: completionTokens - reasoningTokens,\n reasoning: reasoningTokens\n },\n raw: usage\n };\n}\n\n// src/convert-to-perplexity-messages.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\nimport { convertUint8ArrayToBase64 } from \"@ai-sdk/provider-utils\";\nfunction convertToPerplexityMessages(prompt) {\n const messages = [];\n for (const { role, content } of prompt) {\n switch (role) {\n case \"system\": {\n messages.push({ role: \"system\", content });\n break;\n }\n case \"user\":\n case \"assistant\": {\n const hasMultipartContent = content.some(\n (part) => part.type === \"file\" && part.mediaType.startsWith(\"image/\") || part.type === \"file\" && part.mediaType === \"application/pdf\"\n );\n const messageContent = content.map((part, index) => {\n var _a;\n switch (part.type) {\n case \"text\": {\n return {\n type: \"text\",\n text: part.text\n };\n }\n case \"file\": {\n if (part.mediaType === \"application/pdf\") {\n return part.data instanceof URL ? {\n type: \"file_url\",\n file_url: {\n url: part.data.toString()\n },\n file_name: part.filename\n } : {\n type: \"file_url\",\n file_url: {\n url: typeof part.data === \"string\" ? part.data : convertUint8ArrayToBase64(part.data)\n },\n file_name: part.filename || `document-${index}.pdf`\n };\n } else if (part.mediaType.startsWith(\"image/\")) {\n return part.data instanceof URL ? {\n type: \"image_url\",\n image_url: {\n url: part.data.toString()\n }\n } : {\n type: \"image_url\",\n image_url: {\n url: `data:${(_a = part.mediaType) != null ? _a : \"image/jpeg\"};base64,${typeof part.data === \"string\" ? part.data : convertUint8ArrayToBase64(part.data)}`\n }\n };\n }\n }\n }\n }).filter(Boolean);\n messages.push({\n role,\n content: hasMultipartContent ? messageContent : messageContent.filter((part) => part.type === \"text\").map((part) => part.text).join(\"\")\n });\n break;\n }\n case \"tool\": {\n throw new UnsupportedFunctionalityError({\n functionality: \"Tool messages\"\n });\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return messages;\n}\n\n// src/map-perplexity-finish-reason.ts\nfunction mapPerplexityFinishReason(finishReason) {\n switch (finishReason) {\n case \"stop\":\n case \"length\":\n return finishReason;\n default:\n return \"other\";\n }\n}\n\n// src/perplexity-language-model.ts\nvar PerplexityLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.provider = \"perplexity\";\n this.supportedUrls = {\n // No URLs are supported.\n };\n this.modelId = modelId;\n this.config = config;\n }\n getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n providerOptions\n }) {\n var _a;\n const warnings = [];\n if (topK != null) {\n warnings.push({ type: \"unsupported\", feature: \"topK\" });\n }\n if (stopSequences != null) {\n warnings.push({ type: \"unsupported\", feature: \"stopSequences\" });\n }\n if (seed != null) {\n warnings.push({ type: \"unsupported\", feature: \"seed\" });\n }\n return {\n args: {\n // model id:\n model: this.modelId,\n // standardized settings:\n frequency_penalty: frequencyPenalty,\n max_tokens: maxOutputTokens,\n presence_penalty: presencePenalty,\n temperature,\n top_k: topK,\n top_p: topP,\n // response format:\n response_format: (responseFormat == null ? void 0 : responseFormat.type) === \"json\" ? {\n type: \"json_schema\",\n json_schema: { schema: responseFormat.schema }\n } : void 0,\n // provider extensions\n ...(_a = providerOptions == null ? void 0 : providerOptions.perplexity) != null ? _a : {},\n // messages:\n messages: convertToPerplexityMessages(prompt)\n },\n warnings\n };\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;\n const { args: body, warnings } = this.getArgs(options);\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: perplexityErrorSchema,\n errorToMessage\n }),\n successfulResponseHandler: createJsonResponseHandler(\n perplexityResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const choice = response.choices[0];\n const content = [];\n const text = choice.message.content;\n if (text.length > 0) {\n content.push({ type: \"text\", text });\n }\n if (response.citations != null) {\n for (const url of response.citations) {\n content.push({\n type: \"source\",\n sourceType: \"url\",\n id: this.config.generateId(),\n url\n });\n }\n }\n return {\n content,\n finishReason: {\n unified: mapPerplexityFinishReason(choice.finish_reason),\n raw: (_a = choice.finish_reason) != null ? _a : void 0\n },\n usage: convertPerplexityUsage(response.usage),\n request: { body },\n response: {\n ...getResponseMetadata(response),\n headers: responseHeaders,\n body: rawResponse\n },\n warnings,\n providerMetadata: {\n perplexity: {\n images: (_c = (_b = response.images) == null ? void 0 : _b.map((image) => ({\n imageUrl: image.image_url,\n originUrl: image.origin_url,\n height: image.height,\n width: image.width\n }))) != null ? _c : null,\n usage: {\n citationTokens: (_e = (_d = response.usage) == null ? void 0 : _d.citation_tokens) != null ? _e : null,\n numSearchQueries: (_g = (_f = response.usage) == null ? void 0 : _f.num_search_queries) != null ? _g : null\n },\n cost: ((_h = response.usage) == null ? void 0 : _h.cost) ? {\n inputTokensCost: (_i = response.usage.cost.input_tokens_cost) != null ? _i : null,\n outputTokensCost: (_j = response.usage.cost.output_tokens_cost) != null ? _j : null,\n requestCost: (_k = response.usage.cost.request_cost) != null ? _k : null,\n totalCost: (_l = response.usage.cost.total_cost) != null ? _l : null\n } : null\n }\n }\n };\n }\n async doStream(options) {\n const { args, warnings } = this.getArgs(options);\n const body = { ...args, stream: true };\n const { responseHeaders, value: response } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: perplexityErrorSchema,\n errorToMessage\n }),\n successfulResponseHandler: createEventSourceResponseHandler(\n perplexityChunkSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n let usage = void 0;\n const providerMetadata = {\n perplexity: {\n usage: {\n citationTokens: null,\n numSearchQueries: null\n },\n cost: null,\n images: null\n }\n };\n let isFirstChunk = true;\n let isActive = false;\n const self = this;\n return {\n stream: response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n var _a, _b, _c, _d, _e, _f, _g;\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n if (isFirstChunk) {\n controller.enqueue({\n type: \"response-metadata\",\n ...getResponseMetadata(value)\n });\n (_a = value.citations) == null ? void 0 : _a.forEach((url) => {\n controller.enqueue({\n type: \"source\",\n sourceType: \"url\",\n id: self.config.generateId(),\n url\n });\n });\n isFirstChunk = false;\n }\n if (value.usage != null) {\n usage = value.usage;\n providerMetadata.perplexity.usage = {\n citationTokens: (_b = value.usage.citation_tokens) != null ? _b : null,\n numSearchQueries: (_c = value.usage.num_search_queries) != null ? _c : null\n };\n providerMetadata.perplexity.cost = value.usage.cost ? {\n inputTokensCost: (_d = value.usage.cost.input_tokens_cost) != null ? _d : null,\n outputTokensCost: (_e = value.usage.cost.output_tokens_cost) != null ? _e : null,\n requestCost: (_f = value.usage.cost.request_cost) != null ? _f : null,\n totalCost: (_g = value.usage.cost.total_cost) != null ? _g : null\n } : null;\n }\n if (value.images != null) {\n providerMetadata.perplexity.images = value.images.map((image) => ({\n imageUrl: image.image_url,\n originUrl: image.origin_url,\n height: image.height,\n width: image.width\n }));\n }\n const choice = value.choices[0];\n if ((choice == null ? void 0 : choice.finish_reason) != null) {\n finishReason = {\n unified: mapPerplexityFinishReason(choice.finish_reason),\n raw: choice.finish_reason\n };\n }\n if ((choice == null ? void 0 : choice.delta) == null) {\n return;\n }\n const delta = choice.delta;\n const textContent = delta.content;\n if (textContent != null) {\n if (!isActive) {\n controller.enqueue({ type: \"text-start\", id: \"0\" });\n isActive = true;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: \"0\",\n delta: textContent\n });\n }\n },\n flush(controller) {\n if (isActive) {\n controller.enqueue({ type: \"text-end\", id: \"0\" });\n }\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertPerplexityUsage(usage),\n providerMetadata\n });\n }\n })\n ),\n request: { body },\n response: { headers: responseHeaders }\n };\n }\n};\nfunction getResponseMetadata({\n id,\n model,\n created\n}) {\n return {\n id,\n modelId: model,\n timestamp: new Date(created * 1e3)\n };\n}\nvar perplexityCostSchema = z.object({\n input_tokens_cost: z.number().nullish(),\n output_tokens_cost: z.number().nullish(),\n request_cost: z.number().nullish(),\n total_cost: z.number().nullish()\n});\nvar perplexityUsageSchema = z.object({\n prompt_tokens: z.number(),\n completion_tokens: z.number(),\n total_tokens: z.number().nullish(),\n citation_tokens: z.number().nullish(),\n num_search_queries: z.number().nullish(),\n reasoning_tokens: z.number().nullish(),\n cost: perplexityCostSchema.nullish()\n});\nvar perplexityImageSchema = z.object({\n image_url: z.string(),\n origin_url: z.string(),\n height: z.number(),\n width: z.number()\n});\nvar perplexityResponseSchema = z.object({\n id: z.string(),\n created: z.number(),\n model: z.string(),\n choices: z.array(\n z.object({\n message: z.object({\n role: z.literal(\"assistant\"),\n content: z.string()\n }),\n finish_reason: z.string().nullish()\n })\n ),\n citations: z.array(z.string()).nullish(),\n images: z.array(perplexityImageSchema).nullish(),\n usage: perplexityUsageSchema.nullish()\n});\nvar perplexityChunkSchema = z.object({\n id: z.string(),\n created: z.number(),\n model: z.string(),\n choices: z.array(\n z.object({\n delta: z.object({\n role: z.literal(\"assistant\"),\n content: z.string()\n }),\n finish_reason: z.string().nullish()\n })\n ),\n citations: z.array(z.string()).nullish(),\n images: z.array(perplexityImageSchema).nullish(),\n usage: perplexityUsageSchema.nullish()\n});\nvar perplexityErrorSchema = z.object({\n error: z.object({\n code: z.number(),\n message: z.string().nullish(),\n type: z.string().nullish()\n })\n});\nvar errorToMessage = (data) => {\n var _a, _b;\n return (_b = (_a = data.error.message) != null ? _a : data.error.type) != null ? _b : \"unknown error\";\n};\n\n// src/version.ts\nvar VERSION = true ? \"3.0.26\" : \"0.0.0-test\";\n\n// src/perplexity-provider.ts\nfunction createPerplexity(options = {}) {\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"PERPLEXITY_API_KEY\",\n description: \"Perplexity\"\n })}`,\n ...options.headers\n },\n `ai-sdk/perplexity/${VERSION}`\n );\n const createLanguageModel = (modelId) => {\n var _a;\n return new PerplexityLanguageModel(modelId, {\n baseURL: withoutTrailingSlash(\n (_a = options.baseURL) != null ? _a : \"https://api.perplexity.ai\"\n ),\n headers: getHeaders,\n generateId,\n fetch: options.fetch\n });\n };\n const provider = (modelId) => createLanguageModel(modelId);\n provider.specificationVersion = \"v3\";\n provider.languageModel = createLanguageModel;\n provider.embeddingModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar perplexity = createPerplexity();\nexport {\n VERSION,\n createPerplexity,\n perplexity\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";wYAsBA,SAAS,CAAsB,CAAC,EAAO,CACrC,IAAI,EAAI,EAAI,EACZ,GAAI,GAAS,KACX,MAAO,CACL,YAAa,CACX,MAAY,OACZ,QAAc,OACd,UAAgB,OAChB,WAAiB,MACnB,EACA,aAAc,CACZ,MAAY,OACZ,KAAW,OACX,UAAgB,MAClB,EACA,IAAU,MACZ,EAEF,IAAM,GAAgB,EAAK,EAAM,gBAAkB,KAAO,EAAK,EACzD,GAAoB,EAAK,EAAM,oBA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,UAAY,KAAO,EAAK,2BACxC,EACA,QAAS,EACT,aACA,MAAO,EAAQ,KACjB,CAAC,GAEG,EAAW,CAAC,IAAY,EAAoB,CAAO,EAUzD,OATA,EAAS,qBAAuB,KAChC,EAAS,cAAgB,EACzB,EAAS,eAAiB,CAAC,IAAY,CACrC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,gBAAiB,CAAC,GAErE,EAAS,mBAAqB,EAAS,eACvC,EAAS,WAAa,CAAC,IAAY,CACjC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,YAAa,CAAC,GAE1D,EAET,IAAI,GAAa,EAAiB", | ||
| "debugId": "9F19EDC821BAAFF264756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/services/service-config.ts"], | ||
| "sourcesContent": [ | ||
| "import { Global } from \"@opencode-ai/util/global\"\nimport { OPENCODE_CHANNEL, OPENCODE_VERSION } from \"../version\"\nimport { Hash } from \"@opencode-ai/util/hash\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Effect, FileSystem, Option, Schema } from \"effect\"\nimport { randomBytes } from \"crypto\"\nimport path from \"path\"\nimport { selfCommand } from \"../util/process\"\n\n// The CLI's service configuration file, plus the Service.EnsureOptions binding that\n// points the client package's service operations at this CLI: which\n// registration file (by channel), which version, and how to spawn opencode.\n\nexport const Info = Schema.Struct({\n hostname: Schema.optional(Schema.String),\n port: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(65_535))),\n password: Schema.optional(Schema.String),\n cors: Schema.optional(Schema.Array(Schema.String)),\n env: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n})\nexport type Info = typeof Info.Type\n\nconst keys = [\"hostname\", \"port\", \"password\", \"cors\", \"env\"] as const\ntype Key = (typeof keys)[number]\n\nconst decodeInfo = Schema.decodeUnknownEffect(Schema.fromJsonString(Info))\nconst decodeRegistration = Schema.decodeUnknownEffect(Schema.fromJsonString(Service.Info))\n\nexport function filename(channel = OPENCODE_CHANNEL) {\n if (channel === \"latest\" || channel === \"dev\" || channel === \"beta\" || channel === \"next\") return \"service.json\"\n return `service-${channel.replace(/[^a-zA-Z0-9._-]/g, \"-\")}.json`\n}\n\nexport function defaultPort(channel = OPENCODE_CHANNEL) {\n if (channel === \"latest\" || channel === \"dev\" || channel === \"beta\" || channel === \"next\") return 0xc0de\n if (channel === \"local\") return 0xc0df\n return 10_000 + (Number.parseInt(Hash.fast(channel).slice(0, 8), 16) % 50_000)\n}\n\nexport function legacyFilename(channel = OPENCODE_CHANNEL) {\n if (channel === \"latest\" || channel === \"local\") return\n return `service-${Hash.fast(channel)}.json`\n}\n\nexport function versionBelongsToChannel(\n version: string | undefined,\n channel = OPENCODE_CHANNEL,\n installedVersion = OPENCODE_VERSION,\n) {\n if (version === undefined) return false\n if (version === installedVersion) return true\n const prefix = `0.0.0-${channel}-`\n if (!version.startsWith(prefix)) return false\n return /^\\d+(?:\\.\\d+)?$/.test(version.slice(prefix.length))\n}\n\nexport const migrateRegistration = Effect.fnUntraced(function* (\n legacy: string,\n file: string,\n channel = OPENCODE_CHANNEL,\n installedVersion = OPENCODE_VERSION,\n) {\n const fs = yield* FileSystem.FileSystem\n const text = yield* fs.readFileString(legacy).pipe(Effect.option)\n if (Option.isNone(text)) return\n const registration = yield* decodeRegistration(text.value).pipe(Effect.option)\n if (Option.isNone(registration)) return\n if (!versionBelongsToChannel(registration.value.version, channel, installedVersion)) return\n yield* fs.writeFileString(file, text.value, { flag: \"wx\", mode: 0o600 }).pipe(Effect.ignore)\n})\n\nexport const migrateConfig = Effect.fnUntraced(function* (legacy: string, file: string) {\n const fs = yield* FileSystem.FileSystem\n const text = yield* fs.readFileString(legacy).pipe(Effect.option)\n if (Option.isNone(text)) return\n if (Option.isNone(yield* decodeInfo(text.value).pipe(Effect.option))) return\n yield* fs.writeFileString(file, text.value, { flag: \"wx\", mode: 0o600 }).pipe(Effect.ignore)\n})\n\nfunction configKey(key: string): Key {\n if (key === \"hostname\" || key === \"port\" || key === \"password\" || key === \"cors\" || key === \"env\") return key\n throw new Error(`Unknown service config key: ${key}`)\n}\n\nconst paths = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem\n const global = yield* Global.Service\n const name = filename()\n const legacy = legacyFilename()\n const file = path.join(global.state, name)\n return {\n fs,\n file,\n legacyConfigFile: legacy ? path.join(global.config, legacy) : undefined,\n legacyRegistrationFiles: [\n ...(legacy ? [path.join(global.state, legacy)] : []),\n ...(name !== \"service.json\" && OPENCODE_CHANNEL !== \"local\" ? [path.join(global.state, \"service.json\")] : []),\n ],\n configFile: path.join(global.config, name),\n }\n})\n\nexport const options = Effect.fnUntraced(function* (input: { readonly checkVersion?: boolean } = {}) {\n const { file, legacyRegistrationFiles } = yield* paths\n yield* Effect.forEach(legacyRegistrationFiles, (legacy) => migrateRegistration(legacy, file))\n return {\n file,\n version: input.checkVersion ? OPENCODE_VERSION : undefined,\n env: (yield* read()).env,\n command: [\n ...selfCommand(),\n \"serve\",\n \"--service\",\n ],\n }\n})\n\nexport const read = Effect.fn(\"cli.service-config.read\")(function* () {\n const { fs, configFile, legacyConfigFile } = yield* paths\n if (legacyConfigFile) yield* migrateConfig(legacyConfigFile, configFile)\n return yield* fs.readFileString(configFile).pipe(\n Effect.flatMap(decodeInfo),\n Effect.orElseSucceed(() => ({}) as Info),\n )\n})\n\nconst write = Effect.fn(\"cli.service-config.write\")(function* (value: Info) {\n const { fs, configFile } = yield* paths\n const temp = configFile + \".tmp\"\n yield* fs.makeDirectory(path.dirname(configFile), { recursive: true })\n yield* fs.writeFileString(temp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n yield* fs.rename(temp, configFile)\n})\n\nexport const password = Effect.fn(\"cli.service-config.password\")(function* (value?: string) {\n const existing = yield* read()\n if (value === undefined && existing.password) return existing.password\n const next = value ?? randomBytes(32).toString(\"base64url\")\n\n // Keep one private credential across server restarts so discovered clients\n // can reconnect without exposing a password flag or environment variable.\n yield* write({ ...existing, password: next })\n return next\n})\n\nexport const get = Effect.fn(\"cli.service-config.get\")(function* (key?: string, name?: string) {\n if (key === undefined) {\n const { password: _password, ...safe } = yield* read()\n return JSON.stringify(safe, null, 2)\n }\n const selected = configKey(key)\n if (selected !== \"env\" && name !== undefined) throw new Error(`Usage: opencode service get ${selected}`)\n switch (selected) {\n case \"hostname\": {\n return (yield* read()).hostname ?? \"\"\n }\n case \"port\": {\n const port = (yield* read()).port\n return port === undefined ? \"\" : String(port)\n }\n case \"password\": {\n return yield* password()\n }\n case \"cors\": {\n return JSON.stringify((yield* read()).cors ?? [], null, 2)\n }\n case \"env\": {\n const env = (yield* read()).env ?? {}\n return name === undefined ? JSON.stringify(env, null, 2) : (env[name] ?? \"\")\n }\n }\n throw new Error(`Unknown service config key: ${key}`)\n})\n\nexport const set = Effect.fn(\"cli.service-config.set\")(function* (key: string, value: string, nestedValue?: string) {\n const selected = configKey(key)\n if (selected !== \"env\" && nestedValue !== undefined)\n throw new Error(`Usage: opencode service set ${selected} <value>`)\n switch (selected) {\n case \"hostname\": {\n yield* Service.stop(yield* options())\n yield* write({ ...(yield* read()), hostname: value })\n return\n }\n case \"port\": {\n const port = Number(value)\n if (!Number.isInteger(port) || port < 1 || port > 65_535) throw new Error(\"Port must be between 1 and 65535\")\n yield* Service.stop(yield* options())\n yield* write({ ...(yield* read()), port })\n return\n }\n case \"password\": {\n yield* Service.stop(yield* options())\n yield* password(value)\n return\n }\n case \"env\": {\n if (nestedValue === undefined) throw new Error(\"Usage: opencode service set env <key> <value>\")\n yield* Service.stop(yield* options())\n const existing = yield* read()\n yield* write({ ...existing, env: { ...existing.env, [value]: nestedValue } })\n return\n }\n case \"cors\": {\n const cors = value.split(\",\").map((origin) => origin.trim())\n if (\n cors.some((origin) => {\n const url = URL.parse(origin)\n return !url || (url.protocol !== \"http:\" && url.protocol !== \"https:\") || url.origin !== origin\n })\n )\n throw new Error(\"CORS must be a comma-separated list of HTTP(S) origins without paths or trailing slashes\")\n yield* Service.stop(yield* options())\n yield* write({ ...(yield* read()), cors })\n return\n }\n }\n})\n\nexport const unset = Effect.fn(\"cli.service-config.unset\")(function* (key: string, name?: string) {\n const selected = configKey(key)\n if (selected !== \"env\" && name !== undefined) throw new Error(`Usage: opencode service unset ${selected}`)\n switch (selected) {\n case \"hostname\": {\n yield* Service.stop(yield* options())\n const { hostname: _hostname, ...next } = yield* read()\n yield* write(next)\n return\n }\n case \"port\": {\n yield* Service.stop(yield* options())\n const { port: _port, ...next } = yield* read()\n yield* write(next)\n return\n }\n case \"password\": {\n yield* Service.stop(yield* options())\n const { password: _password, ...next } = yield* read()\n yield* write(next)\n return\n }\n case \"env\": {\n if (name === undefined) throw new Error(\"Usage: opencode service unset env <key>\")\n yield* Service.stop(yield* options())\n const existing = yield* read()\n const { [name]: _removed, ...env } = existing.env ?? {}\n const { env: _existingEnv, ...rest } = existing\n yield* write(Object.keys(env).length === 0 ? rest : { ...rest, env })\n return\n }\n case \"cors\": {\n yield* Service.stop(yield* options())\n const { cors: _cors, ...next } = yield* read()\n yield* write(next)\n return\n }\n }\n})\n\nexport * as ServiceConfig from \"./service-config\"\n" | ||
| ], | ||
| "mappings": ";ylBAKA,sBAAS,eACT,oBAOO,IAAM,EAAO,EAAO,OAAO,CAChC,SAAU,EAAO,SAAS,EAAO,MAAM,EACvC,KAAM,EAAO,SAAS,EAAO,IAAI,MAAM,EAAO,uBAAuB,CAAC,EAAG,EAAO,oBAAoB,KAAM,CAAC,CAAC,EAC5G,SAAU,EAAO,SAAS,EAAO,MAAM,EACvC,KAAM,EAAO,SAAS,EAAO,MAAM,EAAO,MAAM,CAAC,EACjD,IAAK,EAAO,SAAS,EAAO,OAAO,EAAO,OAAQ,EAAO,MAAM,CAAC,CAClE,CAAC,EAMD,IAAM,EAAa,EAAO,oBAAoB,EAAO,eAAe,CAAI,CAAC,EACnE,EAAqB,EAAO,oBAAoB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E,SAAW,EAAI,EAAO,IAAK,EAAM,KAAI,CAAC,EACpE,MACF,KACK,OAAQ,CACX,MAAO,EAAQ,KAAK,MAAO,EAAQ,CAAC,EACpC,IAAQ,KAAM,KAAU,GAAS,MAAO,EAAK,EAC7C,MAAO,EAAM,CAAI,EACjB,MACF,GAEH", | ||
| "debugId": "266B0718144AEE3164756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/upgrade.ts"], | ||
| "sourcesContent": [ | ||
| "import { intro, log, outro, spinner } from \"@clack/prompts\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { Updater } from \"../../services/updater\"\nimport { handlePromptErrors } from \"../../ui/prompt\"\nimport { OPENCODE_VERSION } from \"../../version\"\n\nexport default Runtime.handler(\n Commands.commands.upgrade,\n Effect.fn(\"cli.upgrade\")(function* (input) {\n intro(\"Upgrade\")\n const updater = yield* Updater.Service\n const method = Option.getOrUndefined(input.method) ?? (yield* updater.method())\n if (!method)\n return yield* Effect.fail(\n new Error(\"Could not detect the installation method. Pass --method to choose how to upgrade OpenCode.\"),\n )\n\n log.info(`Using method: ${method}`)\n const target = Option.getOrUndefined(input.target) ?? (yield* updater.latest())\n const version = target.trim().replace(/^v/, \"\")\n if (version === OPENCODE_VERSION) {\n log.warn(`OpenCode upgrade skipped: ${version} is already installed`)\n outro(\"Done\")\n return\n }\n\n log.info(`From ${OPENCODE_VERSION} → ${version}`)\n const progress = spinner()\n progress.start(\"Upgrading...\")\n yield* updater.upgrade(method, target).pipe(\n Effect.tap(() => Effect.sync(() => progress.stop(\"Upgrade complete\"))),\n Effect.tapCause(() => Effect.sync(() => progress.stop(\"Upgrade failed\", 1))),\n )\n outro(\"Done\")\n }, handlePromptErrors),\n)\n" | ||
| ], | ||
| "mappings": ";63BAQA,IAAe,IAAQ,QACrB,EAAS,SAAS,QAClB,EAAO,GAAG,aAAa,EAAE,SAAU,CAAC,EAAO,CACzC,EAAM,SAAS,EACf,IAAM,EAAU,MAAO,EAAQ,QACzB,EAAS,EAAO,eAAe,EAAM,MAAM,IAAM,MAAO,EAAQ,OAAO,GAC7E,GAAI,CAAC,EACH,OAAO,MAAO,EAAO,KACf,MAAM,4FAA4F,CACxG,EAEF,EAAI,KAAK,iBAAiB,GAAQ,EAClC,IAAM,EAAS,EAAO,eAAe,EAAM,MAAM,IAAM,MAAO,EAAQ,OAAO,GACvE,EAAU,EAAO,KAAK,EAAE,QAAQ,KAAM,EAAE,EAC9C,GAAI,IAAY,EAAkB,CAChC,EAAI,KAAK,6BAA6B,wBAA8B,EACpE,EAAM,MAAM,EACZ,OAGF,EAAI,KAAK,QAAQ,YAAsB,GAAS,EAChD,IAAM,EAAW,EAAQ,EACzB,EAAS,MAAM,cAAc,EAC7B,MAAO,EAAQ,QAAQ,EAAQ,CAAM,EAAE,KACrC,EAAO,IAAI,IAAM,EAAO,KAAK,IAAM,EAAS,KAAK,kBAAkB,CAAC,CAAC,EACrE,EAAO,SAAS,IAAM,EAAO,KAAK,IAAM,EAAS,KAAK,iBAAkB,CAAC,CAAC,CAAC,CAC7E,EACA,EAAM,MAAM,GACX,CAAkB,CACvB", | ||
| "debugId": "4A52518C01AAB59364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+cohere@3.0.27+d6123d32214422cb/node_modules/@ai-sdk/cohere/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/cohere-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n generateId,\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/cohere-chat-language-model.ts\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonResponseHandler,\n parseProviderOptions,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z3 } from \"zod/v4\";\n\n// src/cohere-chat-options.ts\nimport { z } from \"zod/v4\";\nvar cohereLanguageModelOptions = z.object({\n /**\n * Configuration for reasoning features (optional)\n *\n * Can be set to an object with the two properties `type` and `tokenBudget`. `type` can be set to `'enabled'` or `'disabled'` (defaults to `'enabled'`).\n * `tokenBudget` is the maximum number of tokens the model can use for thinking, which must be set to a positive integer. The model will stop thinking if it reaches the thinking token budget and will proceed with the response\n *\n * @see https://docs.cohere.com/reference/chat#request.body.thinking\n */\n thinking: z.object({\n type: z.enum([\"enabled\", \"disabled\"]).optional(),\n tokenBudget: z.number().optional()\n }).optional()\n});\n\n// src/cohere-error.ts\nimport { createJsonErrorResponseHandler } from \"@ai-sdk/provider-utils\";\nimport { z as z2 } from \"zod/v4\";\nvar cohereErrorDataSchema = z2.object({\n message: z2.string()\n});\nvar cohereFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: cohereErrorDataSchema,\n errorToMessage: (data) => data.message\n});\n\n// src/cohere-prepare-tools.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\nfunction prepareTools({\n tools,\n toolChoice\n}) {\n tools = (tools == null ? void 0 : tools.length) ? tools : void 0;\n const toolWarnings = [];\n if (tools == null) {\n return { tools: void 0, toolChoice: void 0, toolWarnings };\n }\n const cohereTools = [];\n for (const tool of tools) {\n if (tool.type === \"provider\") {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `provider-defined tool ${tool.id}`\n });\n } else {\n cohereTools.push({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema\n }\n });\n }\n }\n if (toolChoice == null) {\n return { tools: cohereTools, toolChoice: void 0, toolWarnings };\n }\n const type = toolChoice.type;\n switch (type) {\n case \"auto\":\n return { tools: cohereTools, toolChoice: void 0, toolWarnings };\n case \"none\":\n return { tools: cohereTools, toolChoice: \"NONE\", toolWarnings };\n case \"required\":\n return { tools: cohereTools, toolChoice: \"REQUIRED\", toolWarnings };\n case \"tool\":\n return {\n tools: cohereTools.filter(\n (tool) => tool.function.name === toolChoice.toolName\n ),\n toolChoice: \"REQUIRED\",\n toolWarnings\n };\n default: {\n const _exhaustiveCheck = type;\n throw new UnsupportedFunctionalityError({\n functionality: `tool choice type: ${_exhaustiveCheck}`\n });\n }\n }\n}\n\n// src/convert-cohere-usage.ts\nfunction convertCohereUsage(tokens) {\n if (tokens == null) {\n return {\n inputTokens: {\n total: void 0,\n noCache: void 0,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: void 0,\n text: void 0,\n reasoning: void 0\n },\n raw: void 0\n };\n }\n const inputTokens = tokens.input_tokens;\n const outputTokens = tokens.output_tokens;\n return {\n inputTokens: {\n total: inputTokens,\n noCache: inputTokens,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: outputTokens,\n text: outputTokens,\n reasoning: void 0\n },\n raw: tokens\n };\n}\n\n// src/convert-to-cohere-chat-prompt.ts\nimport {\n UnsupportedFunctionalityError as UnsupportedFunctionalityError2\n} from \"@ai-sdk/provider\";\nfunction convertToCohereChatPrompt(prompt) {\n const messages = [];\n const documents = [];\n const warnings = [];\n for (const { role, content } of prompt) {\n switch (role) {\n case \"system\": {\n messages.push({ role: \"system\", content });\n break;\n }\n case \"user\": {\n messages.push({\n role: \"user\",\n content: content.map((part) => {\n var _a;\n switch (part.type) {\n case \"text\": {\n return part.text;\n }\n case \"file\": {\n let textContent;\n if (typeof part.data === \"string\") {\n textContent = part.data;\n } else if (part.data instanceof Uint8Array) {\n if (!(((_a = part.mediaType) == null ? void 0 : _a.startsWith(\"text/\")) || part.mediaType === \"application/json\")) {\n throw new UnsupportedFunctionalityError2({\n functionality: `document media type: ${part.mediaType}`,\n message: `Media type '${part.mediaType}' is not supported. Supported media types are: text/* and application/json.`\n });\n }\n textContent = new TextDecoder().decode(part.data);\n } else {\n throw new UnsupportedFunctionalityError2({\n functionality: \"File URL data\",\n message: \"URLs should be downloaded by the AI SDK and not reach this point. This indicates a configuration issue.\"\n });\n }\n documents.push({\n data: {\n text: textContent,\n title: part.filename\n }\n });\n return \"\";\n }\n }\n }).join(\"\")\n });\n break;\n }\n case \"assistant\": {\n let text = \"\";\n const toolCalls = [];\n for (const part of content) {\n switch (part.type) {\n case \"text\": {\n text += part.text;\n break;\n }\n case \"tool-call\": {\n toolCalls.push({\n id: part.toolCallId,\n type: \"function\",\n function: {\n name: part.toolName,\n arguments: JSON.stringify(part.input)\n }\n });\n break;\n }\n }\n }\n messages.push({\n role: \"assistant\",\n content: toolCalls.length > 0 ? void 0 : text,\n tool_calls: toolCalls.length > 0 ? toolCalls : void 0,\n tool_plan: void 0\n });\n break;\n }\n case \"tool\": {\n messages.push(\n ...content.filter((toolResult) => toolResult.type !== \"tool-approval-response\").map((toolResult) => {\n var _a;\n const output = toolResult.output;\n let contentValue;\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n contentValue = output.value;\n break;\n case \"execution-denied\":\n contentValue = (_a = output.reason) != null ? _a : \"Tool execution denied.\";\n break;\n case \"content\":\n case \"json\":\n case \"error-json\":\n contentValue = JSON.stringify(output.value);\n break;\n }\n return {\n role: \"tool\",\n content: contentValue,\n tool_call_id: toolResult.toolCallId\n };\n })\n );\n break;\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return { messages, documents, warnings };\n}\n\n// src/map-cohere-finish-reason.ts\nfunction mapCohereFinishReason(finishReason) {\n switch (finishReason) {\n case \"COMPLETE\":\n case \"STOP_SEQUENCE\":\n return \"stop\";\n case \"MAX_TOKENS\":\n return \"length\";\n case \"ERROR\":\n return \"error\";\n case \"TOOL_CALL\":\n return \"tool-calls\";\n default:\n return \"other\";\n }\n}\n\n// src/cohere-chat-language-model.ts\nvar CohereChatLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.supportedUrls = {\n // No URLs are supported.\n };\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n async getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n tools,\n toolChoice,\n providerOptions\n }) {\n var _a, _b;\n const cohereOptions = (_a = await parseProviderOptions({\n provider: \"cohere\",\n providerOptions,\n schema: cohereLanguageModelOptions\n })) != null ? _a : {};\n const {\n messages: chatPrompt,\n documents: cohereDocuments,\n warnings: promptWarnings\n } = convertToCohereChatPrompt(prompt);\n const {\n tools: cohereTools,\n toolChoice: cohereToolChoice,\n toolWarnings\n } = prepareTools({ tools, toolChoice });\n return {\n args: {\n // model id:\n model: this.modelId,\n // standardized settings:\n frequency_penalty: frequencyPenalty,\n presence_penalty: presencePenalty,\n max_tokens: maxOutputTokens,\n temperature,\n p: topP,\n k: topK,\n seed,\n stop_sequences: stopSequences,\n // response format:\n response_format: (responseFormat == null ? void 0 : responseFormat.type) === \"json\" ? { type: \"json_object\", json_schema: responseFormat.schema } : void 0,\n // messages:\n messages: chatPrompt,\n // tools:\n tools: cohereTools,\n tool_choice: cohereToolChoice,\n // documents for RAG:\n ...cohereDocuments.length > 0 && { documents: cohereDocuments },\n // reasoning\n ...cohereOptions.thinking && {\n thinking: {\n type: (_b = cohereOptions.thinking.type) != null ? _b : \"enabled\",\n token_budget: cohereOptions.thinking.tokenBudget\n }\n }\n },\n warnings: [...toolWarnings, ...promptWarnings]\n };\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e, _f, _g;\n const { args, warnings } = await this.getArgs(options);\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: `${this.config.baseURL}/chat`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body: args,\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n cohereChatResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const content = [];\n for (const item of (_a = response.message.content) != null ? _a : []) {\n if (item.type === \"text\" && item.text.length > 0) {\n content.push({ type: \"text\", text: item.text });\n continue;\n }\n if (item.type === \"thinking\" && item.thinking.length > 0) {\n content.push({ type: \"reasoning\", text: item.thinking });\n continue;\n }\n }\n for (const citation of (_b = response.message.citations) != null ? _b : []) {\n content.push({\n type: \"source\",\n sourceType: \"document\",\n id: this.config.generateId(),\n mediaType: \"text/plain\",\n title: ((_d = (_c = citation.sources[0]) == null ? void 0 : _c.document) == null ? void 0 : _d.title) || \"Document\",\n providerMetadata: {\n cohere: {\n start: citation.start,\n end: citation.end,\n text: citation.text,\n sources: citation.sources,\n ...citation.type && { citationType: citation.type }\n }\n }\n });\n }\n for (const toolCall of (_e = response.message.tool_calls) != null ? _e : []) {\n content.push({\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n // Cohere sometimes returns `null` for tool call arguments for tools\n // defined as having no arguments.\n input: toolCall.function.arguments.replace(/^null$/, \"{}\")\n });\n }\n return {\n content,\n finishReason: {\n unified: mapCohereFinishReason(response.finish_reason),\n raw: (_f = response.finish_reason) != null ? _f : void 0\n },\n usage: convertCohereUsage(response.usage.tokens),\n request: { body: args },\n response: {\n // TODO timestamp, model id\n id: (_g = response.generation_id) != null ? _g : void 0,\n headers: responseHeaders,\n body: rawResponse\n },\n warnings\n };\n }\n async doStream(options) {\n const { args, warnings } = await this.getArgs(options);\n const { responseHeaders, value: response } = await postJsonToApi({\n url: `${this.config.baseURL}/chat`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body: { ...args, stream: true },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(\n cohereChatChunkSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n let usage = void 0;\n let pendingToolCall = null;\n let isActiveReasoning = false;\n return {\n stream: response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n var _a, _b;\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n finishReason = { unified: \"error\", raw: void 0 };\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n const type = value.type;\n switch (type) {\n case \"content-start\": {\n if (value.delta.message.content.type === \"thinking\") {\n controller.enqueue({\n type: \"reasoning-start\",\n id: String(value.index)\n });\n isActiveReasoning = true;\n return;\n }\n controller.enqueue({\n type: \"text-start\",\n id: String(value.index)\n });\n return;\n }\n case \"content-delta\": {\n if (\"thinking\" in value.delta.message.content) {\n controller.enqueue({\n type: \"reasoning-delta\",\n id: String(value.index),\n delta: value.delta.message.content.thinking\n });\n return;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: String(value.index),\n delta: value.delta.message.content.text\n });\n return;\n }\n case \"content-end\": {\n if (isActiveReasoning) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: String(value.index)\n });\n isActiveReasoning = false;\n return;\n }\n controller.enqueue({\n type: \"text-end\",\n id: String(value.index)\n });\n return;\n }\n case \"tool-call-start\": {\n const toolId = value.delta.message.tool_calls.id;\n const toolName = value.delta.message.tool_calls.function.name;\n const initialArgs = value.delta.message.tool_calls.function.arguments;\n pendingToolCall = {\n id: toolId,\n name: toolName,\n arguments: initialArgs,\n hasFinished: false\n };\n controller.enqueue({\n type: \"tool-input-start\",\n id: toolId,\n toolName\n });\n if (initialArgs.length > 0) {\n controller.enqueue({\n type: \"tool-input-delta\",\n id: toolId,\n delta: initialArgs\n });\n }\n return;\n }\n case \"tool-call-delta\": {\n if (pendingToolCall && !pendingToolCall.hasFinished) {\n const argsDelta = value.delta.message.tool_calls.function.arguments;\n pendingToolCall.arguments += argsDelta;\n controller.enqueue({\n type: \"tool-input-delta\",\n id: pendingToolCall.id,\n delta: argsDelta\n });\n }\n return;\n }\n case \"tool-call-end\": {\n if (pendingToolCall && !pendingToolCall.hasFinished) {\n controller.enqueue({\n type: \"tool-input-end\",\n id: pendingToolCall.id\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: pendingToolCall.id,\n toolName: pendingToolCall.name,\n input: JSON.stringify(\n JSON.parse(((_a = pendingToolCall.arguments) == null ? void 0 : _a.trim()) || \"{}\")\n )\n });\n pendingToolCall.hasFinished = true;\n pendingToolCall = null;\n }\n return;\n }\n case \"message-start\": {\n controller.enqueue({\n type: \"response-metadata\",\n id: (_b = value.id) != null ? _b : void 0\n });\n return;\n }\n case \"message-end\": {\n finishReason = {\n unified: mapCohereFinishReason(value.delta.finish_reason),\n raw: value.delta.finish_reason\n };\n usage = value.delta.usage.tokens;\n return;\n }\n default: {\n return;\n }\n }\n },\n flush(controller) {\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertCohereUsage(usage)\n });\n }\n })\n ),\n request: { body: { ...args, stream: true } },\n response: { headers: responseHeaders }\n };\n }\n};\nvar cohereChatResponseSchema = z3.object({\n generation_id: z3.string().nullish(),\n message: z3.object({\n role: z3.string(),\n content: z3.array(\n z3.union([\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"thinking\"),\n thinking: z3.string()\n })\n ])\n ).nullish(),\n tool_plan: z3.string().nullish(),\n tool_calls: z3.array(\n z3.object({\n id: z3.string(),\n type: z3.literal(\"function\"),\n function: z3.object({\n name: z3.string(),\n arguments: z3.string()\n })\n })\n ).nullish(),\n citations: z3.array(\n z3.object({\n start: z3.number(),\n end: z3.number(),\n text: z3.string(),\n sources: z3.array(\n z3.object({\n type: z3.string().optional(),\n id: z3.string().optional(),\n document: z3.object({\n id: z3.string().optional(),\n text: z3.string(),\n title: z3.string()\n })\n })\n ),\n type: z3.string().optional()\n })\n ).nullish()\n }),\n finish_reason: z3.string(),\n usage: z3.object({\n billed_units: z3.object({\n input_tokens: z3.number(),\n output_tokens: z3.number()\n }),\n tokens: z3.object({\n input_tokens: z3.number(),\n output_tokens: z3.number()\n })\n })\n});\nvar cohereChatChunkSchema = z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"citation-start\")\n }),\n z3.object({\n type: z3.literal(\"citation-end\")\n }),\n z3.object({\n type: z3.literal(\"content-start\"),\n index: z3.number(),\n delta: z3.object({\n message: z3.object({\n content: z3.union([\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"thinking\"),\n thinking: z3.string()\n })\n ])\n })\n })\n }),\n z3.object({\n type: z3.literal(\"content-delta\"),\n index: z3.number(),\n delta: z3.object({\n message: z3.object({\n content: z3.union([\n z3.object({\n text: z3.string()\n }),\n z3.object({\n thinking: z3.string()\n })\n ])\n })\n })\n }),\n z3.object({\n type: z3.literal(\"content-end\"),\n index: z3.number()\n }),\n z3.object({\n type: z3.literal(\"message-start\"),\n id: z3.string().nullish()\n }),\n z3.object({\n type: z3.literal(\"message-end\"),\n delta: z3.object({\n finish_reason: z3.string(),\n usage: z3.object({\n tokens: z3.object({\n input_tokens: z3.number(),\n output_tokens: z3.number()\n })\n })\n })\n }),\n // https://docs.cohere.com/v2/docs/streaming#tool-use-stream-events-for-tool-calling\n z3.object({\n type: z3.literal(\"tool-plan-delta\"),\n delta: z3.object({\n message: z3.object({\n tool_plan: z3.string()\n })\n })\n }),\n z3.object({\n type: z3.literal(\"tool-call-start\"),\n delta: z3.object({\n message: z3.object({\n tool_calls: z3.object({\n id: z3.string(),\n type: z3.literal(\"function\"),\n function: z3.object({\n name: z3.string(),\n arguments: z3.string()\n })\n })\n })\n })\n }),\n // A single tool call's `arguments` stream in chunks and must be accumulated\n // in a string and so the full tool object info can only be parsed once we see\n // `tool-call-end`.\n z3.object({\n type: z3.literal(\"tool-call-delta\"),\n delta: z3.object({\n message: z3.object({\n tool_calls: z3.object({\n function: z3.object({\n arguments: z3.string()\n })\n })\n })\n })\n }),\n z3.object({\n type: z3.literal(\"tool-call-end\")\n })\n]);\n\n// src/cohere-embedding-model.ts\nimport {\n TooManyEmbeddingValuesForCallError\n} from \"@ai-sdk/provider\";\nimport {\n combineHeaders as combineHeaders2,\n createJsonResponseHandler as createJsonResponseHandler2,\n parseProviderOptions as parseProviderOptions2,\n postJsonToApi as postJsonToApi2\n} from \"@ai-sdk/provider-utils\";\nimport { z as z5 } from \"zod/v4\";\n\n// src/cohere-embedding-options.ts\nimport { z as z4 } from \"zod/v4\";\nvar cohereEmbeddingModelOptions = z4.object({\n /**\n * Specifies the type of input passed to the model. Default is `search_query`.\n *\n * - \"search_document\": Used for embeddings stored in a vector database for search use-cases.\n * - \"search_query\": Used for embeddings of search queries run against a vector DB to find relevant documents.\n * - \"classification\": Used for embeddings passed through a text classifier.\n * - \"clustering\": Used for embeddings run through a clustering algorithm.\n */\n inputType: z4.enum([\"search_document\", \"search_query\", \"classification\", \"clustering\"]).optional(),\n /**\n * Specifies how the API will handle inputs longer than the maximum token length.\n * Default is `END`.\n *\n * - \"NONE\": If selected, when the input exceeds the maximum input token length will return an error.\n * - \"START\": Will discard the start of the input until the remaining input is exactly the maximum input token length for the model.\n * - \"END\": Will discard the end of the input until the remaining input is exactly the maximum input token length for the model.\n */\n truncate: z4.enum([\"NONE\", \"START\", \"END\"]).optional(),\n /**\n * The number of dimensions of the output embedding.\n * Only available for `embed-v4.0` and newer models.\n *\n * Possible values are `256`, `512`, `1024`, and `1536`.\n * The default is `1536`.\n */\n outputDimension: z4.union([z4.literal(256), z4.literal(512), z4.literal(1024), z4.literal(1536)]).optional()\n});\n\n// src/cohere-embedding-model.ts\nvar CohereEmbeddingModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.maxEmbeddingsPerCall = 96;\n this.supportsParallelCalls = true;\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n async doEmbed({\n values,\n headers,\n abortSignal,\n providerOptions\n }) {\n var _a;\n const embeddingOptions = await parseProviderOptions2({\n provider: \"cohere\",\n providerOptions,\n schema: cohereEmbeddingModelOptions\n });\n if (values.length > this.maxEmbeddingsPerCall) {\n throw new TooManyEmbeddingValuesForCallError({\n provider: this.provider,\n modelId: this.modelId,\n maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,\n values\n });\n }\n const {\n responseHeaders,\n value: response,\n rawValue\n } = await postJsonToApi2({\n url: `${this.config.baseURL}/embed`,\n headers: combineHeaders2(this.config.headers(), headers),\n body: {\n model: this.modelId,\n // The AI SDK only supports 'float' embeddings. Note that the Cohere API\n // supports other embedding types, but they are not currently supported by the AI SDK.\n // https://docs.cohere.com/v2/reference/embed#request.body.embedding_types\n embedding_types: [\"float\"],\n texts: values,\n input_type: (_a = embeddingOptions == null ? void 0 : embeddingOptions.inputType) != null ? _a : \"search_query\",\n truncate: embeddingOptions == null ? void 0 : embeddingOptions.truncate,\n output_dimension: embeddingOptions == null ? void 0 : embeddingOptions.outputDimension\n },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler2(\n cohereTextEmbeddingResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n warnings: [],\n embeddings: response.embeddings.float,\n usage: { tokens: response.meta.billed_units.input_tokens },\n response: { headers: responseHeaders, body: rawValue }\n };\n }\n};\nvar cohereTextEmbeddingResponseSchema = z5.object({\n embeddings: z5.object({\n float: z5.array(z5.array(z5.number()))\n }),\n meta: z5.object({\n billed_units: z5.object({\n input_tokens: z5.number()\n })\n })\n});\n\n// src/reranking/cohere-reranking-model.ts\nimport {\n combineHeaders as combineHeaders3,\n createJsonResponseHandler as createJsonResponseHandler3,\n parseProviderOptions as parseProviderOptions3,\n postJsonToApi as postJsonToApi3\n} from \"@ai-sdk/provider-utils\";\n\n// src/reranking/cohere-reranking-api.ts\nimport { lazySchema, zodSchema } from \"@ai-sdk/provider-utils\";\nimport { z as z6 } from \"zod/v4\";\nvar cohereRerankingResponseSchema = lazySchema(\n () => zodSchema(\n z6.object({\n id: z6.string().nullish(),\n results: z6.array(\n z6.object({\n index: z6.number(),\n relevance_score: z6.number()\n })\n ),\n meta: z6.any()\n })\n )\n);\n\n// src/reranking/cohere-reranking-options.ts\nimport { lazySchema as lazySchema2, zodSchema as zodSchema2 } from \"@ai-sdk/provider-utils\";\nimport { z as z7 } from \"zod/v4\";\nvar cohereRerankingModelOptionsSchema = lazySchema2(\n () => zodSchema2(\n z7.object({\n maxTokensPerDoc: z7.number().optional(),\n priority: z7.number().optional()\n })\n )\n);\n\n// src/reranking/cohere-reranking-model.ts\nvar CohereRerankingModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n // current implementation is based on v2 of the API: https://docs.cohere.com/v2/reference/rerank\n async doRerank({\n documents,\n headers,\n query,\n topN,\n abortSignal,\n providerOptions\n }) {\n var _a;\n const rerankingOptions = await parseProviderOptions3({\n provider: \"cohere\",\n providerOptions,\n schema: cohereRerankingModelOptionsSchema\n });\n const warnings = [];\n if (documents.type === \"object\") {\n warnings.push({\n type: \"compatibility\",\n feature: \"object documents\",\n details: \"Object documents are converted to strings.\"\n });\n }\n const {\n responseHeaders,\n value: response,\n rawValue\n } = await postJsonToApi3({\n url: `${this.config.baseURL}/rerank`,\n headers: combineHeaders3(this.config.headers(), headers),\n body: {\n model: this.modelId,\n query,\n documents: documents.type === \"text\" ? documents.values : documents.values.map((value) => JSON.stringify(value)),\n top_n: topN,\n max_tokens_per_doc: rerankingOptions == null ? void 0 : rerankingOptions.maxTokensPerDoc,\n priority: rerankingOptions == null ? void 0 : rerankingOptions.priority\n },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler3(\n cohereRerankingResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n ranking: response.results.map((result) => ({\n index: result.index,\n relevanceScore: result.relevance_score\n })),\n warnings,\n response: {\n id: (_a = response.id) != null ? _a : void 0,\n headers: responseHeaders,\n body: rawValue\n }\n };\n }\n};\n\n// src/version.ts\nvar VERSION = true ? \"3.0.27\" : \"0.0.0-test\";\n\n// src/cohere-provider.ts\nfunction createCohere(options = {}) {\n var _a;\n const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : \"https://api.cohere.com/v2\";\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"COHERE_API_KEY\",\n description: \"Cohere\"\n })}`,\n ...options.headers\n },\n `ai-sdk/cohere/${VERSION}`\n );\n const createChatModel = (modelId) => {\n var _a2;\n return new CohereChatLanguageModel(modelId, {\n provider: \"cohere.chat\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n generateId: (_a2 = options.generateId) != null ? _a2 : generateId\n });\n };\n const createEmbeddingModel = (modelId) => new CohereEmbeddingModel(modelId, {\n provider: \"cohere.textEmbedding\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch\n });\n const createRerankingModel = (modelId) => new CohereRerankingModel(modelId, {\n provider: \"cohere.reranking\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch\n });\n const provider = function(modelId) {\n if (new.target) {\n throw new Error(\n \"The Cohere model function cannot be called with the new keyword.\"\n );\n }\n return createChatModel(modelId);\n };\n provider.specificationVersion = \"v3\";\n provider.languageModel = createChatModel;\n provider.embedding = createEmbeddingModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbedding = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n provider.reranking = createRerankingModel;\n provider.rerankingModel = createRerankingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar cohere = createCohere();\nexport {\n VERSION,\n cohere,\n createCohere\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";gaAuBA,IAAI,EAA6B,EAAE,OAAO,CASxC,SAAU,EAAE,OAAO,CACjB,KAAM,EAAE,KAAK,CAAC,UAAW,UAA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Id": "FAABEE0E7153AE9764756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-web-identity@3.972.75/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromTokenFile.js", "../../node_modules/.bun/@aws-sdk+credential-provider-web-identity@3.972.75/node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromWebToken.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError, externalDataInterceptor } from \"@smithy/core/config\";\nimport { readFileSync } from \"node:fs\";\nimport { fromWebToken } from \"./fromWebToken\";\nconst ENV_TOKEN_FILE = \"AWS_WEB_IDENTITY_TOKEN_FILE\";\nconst ENV_ROLE_ARN = \"AWS_ROLE_ARN\";\nconst ENV_ROLE_SESSION_NAME = \"AWS_ROLE_SESSION_NAME\";\nexport const fromTokenFile = (init = {}) => async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-web-identity - fromTokenFile\");\n const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE];\n const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN];\n const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME];\n if (!webIdentityTokenFile || !roleArn) {\n throw new CredentialsProviderError(\"Web identity configuration not specified\", {\n logger: init.logger,\n });\n }\n const credentials = await fromWebToken({\n ...init,\n webIdentityToken: externalDataInterceptor?.getTokenRecord?.()[webIdentityTokenFile] ??\n readFileSync(webIdentityTokenFile, { encoding: \"ascii\" }),\n roleArn,\n roleSessionName,\n })(awsIdentityProperties);\n if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) {\n setCredentialFeature(credentials, \"CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN\", \"h\");\n }\n return credentials;\n};\n", | ||
| "export const fromWebToken = (init) => async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-web-identity - fromWebToken\");\n const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init;\n let { roleAssumerWithWebIdentity } = init;\n if (!roleAssumerWithWebIdentity) {\n const { getDefaultRoleAssumerWithWebIdentity } = await import(\"@aws-sdk/nested-clients/sts\");\n roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({\n ...init.clientConfig,\n credentialProviderLogger: init.logger,\n parentClientConfig: {\n ...awsIdentityProperties?.callerClientConfig,\n ...init.parentClientConfig,\n },\n }, init.clientPlugins);\n }\n return roleAssumerWithWebIdentity({\n RoleArn: roleArn,\n RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`,\n WebIdentityToken: webIdentityToken,\n ProviderId: providerId,\n PolicyArns: policyArns,\n Policy: policy,\n DurationSeconds: durationSeconds,\n });\n};\n" | ||
| ], | ||
| "mappings": ";4JAAA,eACA,WACA,uBAAS,WCFF,IAAM,EAAe,CAAC,IAAS,MAAO,IAA0B,CACnE,EAAK,QAAQ,MAAM,0DAA0D,EAC7E,IAAQ,UAAS,kBAAiB,mBAAkB,aAAY,aAAY,SAAQ,mBAAoB,GAClG,8BAA+B,EACrC,GAAI,CAAC,EAA4B,CAC7B,IAAQ,wCAAyC,KAAa,0CAC9D,EAA6B,EAAqC,IAC3D,EAAK,aACR,yBAA0B,EAAK,OAC/B,mBAAoB,IACb,GAAuB,sBACvB,EAAK,kBACZ,CACJ,EAAG,EAAK,aAAa,EAEzB,OAAO,EAA2B,CAC9B,QAAS,EACT,gBAAiB,GAAmB,sBAAsB,KAAK,IAAI,IACnE,iBAAkB,EAClB,WAAY,EACZ,WAAY,EACZ,OAAQ,EACR,gBAAiB,CACrB,CAAC,GDnBL,IAAM,EAAiB,8BACjB,EAAe,eACf,EAAwB,wBACjB,EAAgB,CAAC,EAAO,CAAC,IAAM,MAAO,IAA0B,CACzE,EAAK,QAAQ,MAAM,2DAA2D,EAC9E,IAAM,EAAuB,GAAM,sBAAwB,QAAQ,IAAI,GACjE,EAAU,GAAM,SAAW,QAAQ,IAAI,GACvC,EAAkB,GAAM,iBAAmB,QAAQ,IAAI,GAC7D,GAAI,CAAC,GAAwB,CAAC,EAC1B,MAAM,IAAI,2BAAyB,2CAA4C,CAC3E,OAAQ,EAAK,MACjB,CAAC,EAEL,IAAM,EAAc,MAAM,EAAa,IAChC,EACH,iBAAkB,2BAAyB,iBAAiB,EAAE,IAC1D,EAAa,EAAsB,CAAE,SAAU,OAAQ,CAAC,EAC5D,UACA,iBACJ,CAAC,EAAE,CAAqB,EACxB,GAAI,IAAyB,QAAQ,IAAI,GACrC,uBAAqB,EAAa,wCAAyC,GAAG,EAElF,OAAO", | ||
| "debugId": "B065CC46F164B81F64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/workspace-event.ts"], | ||
| "sourcesContent": [ | ||
| "export * as WorkspaceEvent from \"./workspace-event.js\"\n\nimport { Schema } from \"effect\"\nimport { Event } from \"./event.js\"\nimport { WorkspaceID } from \"./workspace-id.js\"\n\nexport const ConnectionStatus = Schema.Struct({\n workspaceID: WorkspaceID,\n status: Schema.Literals([\"connected\", \"connecting\", \"disconnected\", \"error\"]),\n}).annotate({ identifier: \"WorkspaceEvent.ConnectionStatus\" })\nexport interface ConnectionStatus extends Schema.Schema.Type<typeof ConnectionStatus> {}\n\nexport const Ready = Event.ephemeral({\n type: \"workspace.ready\",\n schema: {\n name: Schema.String,\n },\n})\n\nexport const Failed = Event.ephemeral({\n type: \"workspace.failed\",\n schema: {\n message: Schema.String,\n },\n})\n\nexport const Status = Event.ephemeral({\n type: \"workspace.status\",\n schema: ConnectionStatus.fields,\n})\n\nexport const Definitions = Event.inventory(Ready, Failed, Status)\n" | ||
| ], | ||
| "mappings": ";wRAMO,IAAM,EAAmB,EAAO,OAAO,CAC5C,YAAa,EACb,OAAQ,EAAO,SAAS,CAAC,YAAa,aAAc,eAAgB,OAAO,CAAC,CAC9E,CAAC,EAAE,SAAS,CAAE,WAAY,iCAAkC,CAAC,EAGhD,EAAQ,EAAM,UAAU,CACnC,KAAM,kBACN,OAAQ,CACN,KAAM,EAAO,MACf,CACF,CAAC,EAEY,EAAS,EAAM,UAAU,CACpC,KAAM,mBACN,OAAQ,CACN,QAAS,EAAO,MAClB,CACF,CAAC,EAEY,EAAS,EAAM,UAAU,CACpC,KAAM,mBACN,OAAQ,EAAiB,MAC3B,CAAC,EAEY,EAAc,EAAM,UAAU,EAAO,EAAQ,CAAM", | ||
| "debugId": "4BE3D3B155F1CB7064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "1B42A58514AC274864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../protocol/src/client.ts"], | ||
| "sourcesContent": [ | ||
| "import { InvalidRequestError, SessionNotFoundError } from \"./errors.js\"\nimport { makeDefaultApi } from \"./api.js\"\nimport type { Api } from \"./api.js\"\nimport type { Context } from \"effect\"\nimport { HttpApiMiddleware } from \"effect/unstable/httpapi\"\nimport type { EventGroup } from \"./groups/event.js\"\n\nclass LocationMiddleware extends HttpApiMiddleware.Service<LocationMiddleware>()(\n \"@opencode-ai/client/LocationMiddleware\",\n) {}\n\nclass SessionLocationMiddleware extends HttpApiMiddleware.Service<SessionLocationMiddleware>()(\n \"@opencode-ai/client/SessionLocationMiddleware\",\n { error: [InvalidRequestError, SessionNotFoundError] },\n) {}\n\ntype ClientApiShape = Api<\n Context.Service.Identifier<typeof LocationMiddleware>,\n Context.Service.Shape<typeof LocationMiddleware>,\n Context.Service.Identifier<typeof SessionLocationMiddleware>,\n Context.Service.Shape<typeof SessionLocationMiddleware>,\n Context.Service.Identifier<typeof SessionLocationMiddleware>,\n Context.Service.Shape<typeof SessionLocationMiddleware>,\n typeof EventGroup\n>\n\nexport const ClientApi: ClientApiShape = makeDefaultApi({\n locationMiddleware: LocationMiddleware,\n // The real server uses a form-specific middleware with an undocumented `global` sentinel branch.\n // The generated client only needs a middleware identity for API typing.\n formLocationMiddleware: SessionLocationMiddleware,\n sessionLocationMiddleware: SessionLocationMiddleware,\n})\n\nexport const groupNames = {\n \"server.health\": \"health\",\n \"server.server\": \"server\",\n \"server.debug\": \"debug\",\n \"server.migration\": \"migration\",\n \"server.location\": \"location\",\n \"server.agent\": \"agent\",\n \"server.plugin\": \"plugin\",\n \"server.session\": \"session\",\n \"server.message\": \"message\",\n \"server.model\": \"model\",\n \"server.generate\": \"generate\",\n \"server.provider\": \"provider\",\n \"server.integration\": \"integration\",\n \"server.websearch\": \"websearch\",\n \"server.credential\": \"credential\",\n \"server.form\": \"form\",\n \"server.permission\": \"permission\",\n \"server.fs\": \"file\",\n \"server.command\": \"command\",\n \"server.skill\": \"skill\",\n \"server.rpc\": \"rpc\",\n \"server.event\": \"event\",\n \"server.pty\": \"pty\",\n \"server.experimental\": \"experimental\",\n \"server.shell\": \"shell\",\n \"server.mcp\": \"mcp\",\n \"server.reference\": \"reference\",\n \"server.project\": \"project\",\n \"server.worktree\": \"worktree\",\n \"server.workspace\": \"workspace\",\n \"server.vcs\": \"vcs\",\n \"server.config\": \"config\",\n} as const\n\nexport const promiseOmitEndpoints = new Set([\"pty.connect\", \"persistentPty.connect\"])\nexport const effectOmitEndpoints = new Set([\"fs.read\", \"pty.connect\", \"persistentPty.connect\"])\n" | ||
| ], | ||
| "mappings": ";kuCAOA,MAAM,UAA2B,EAAkB,QAA4B,EAC7E,wCACF,CAAE,CAAC,CAEH,MAAM,UAAkC,EAAkB,QAAmC,EAC3F,gDACA,CAAE,MAAO,CAAC,EAAqB,CAAoB,CAAE,CACvD,CAAE,CAAC,CAYI,IAAM,EAA4B,EAAe,CACtD,mBAAoB,EAGpB,uBAAwB,EACxB,0BAA2B,CAC7B,CAAC,EAEY,EAAa,CACxB,gBAAiB,SACjB,gBAAiB,SACjB,eAAgB,QAChB,mBAAoB,YACpB,kBAAmB,WACnB,eAAgB,QAChB,gBAAiB,SACjB,iBAAkB,UAClB,iBAAkB,UAClB,eAAgB,QAChB,kBAAmB,WACnB,kBAAmB,WACnB,qBAAsB,cACtB,mBAAoB,YACpB,oBAAqB,aACrB,cAAe,OACf,oBAAqB,aACrB,YAAa,OACb,iBAAkB,UAClB,eAAgB,QAChB,aAAc,MACd,eAAgB,QAChB,aAAc,MACd,sBAAuB,eACvB,eAAgB,QAChB,aAAc,MACd,mBAAoB,YACpB,iBAAkB,UAClB,kBAAmB,WACnB,mBAAoB,YACpB,aAAc,MACd,gBAAiB,QACnB,EAEa,EAAuB,IAAI,IAAI,CAAC,cAAe,uBAAuB,CAAC,EACvE,EAAsB,IAAI,IAAI,CAAC,UAAW,cAAe,uBAAuB,CAAC", | ||
| "debugId": "1A223001AAF0ED7B64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@smithy+node-http-handler@4.11.2/node_modules/@smithy/node-http-handler/dist-cjs/index.js"], | ||
| "sourcesContent": [ | ||
| "const { buildQueryString, HttpResponse } = require(\"@smithy/core/protocols\");\nconst node_https = require(\"node:https\");\nconst { Readable } = require(\"node:stream\");\nconst http2 = require(\"node:http2\");\nconst { streamCollector } = require(\"@smithy/core/serde\");\nexports.streamCollector = streamCollector;\n\nfunction buildAbortError(abortSignal) {\n const reason = abortSignal && typeof abortSignal === \"object\" && \"reason\" in abortSignal\n ? abortSignal.reason\n : undefined;\n if (reason) {\n if (reason instanceof Error) {\n const abortError = new Error(\"Request aborted\");\n abortError.name = \"AbortError\";\n abortError.cause = reason;\n return abortError;\n }\n const abortError = new Error(String(reason));\n abortError.name = \"AbortError\";\n return abortError;\n }\n const abortError = new Error(\"Request aborted\");\n abortError.name = \"AbortError\";\n return abortError;\n}\n\nconst NODEJS_TIMEOUT_ERROR_CODES = [\"ECONNRESET\", \"EPIPE\", \"ETIMEDOUT\"];\n\nconst getTransformedHeaders = (headers) => {\n const transformedHeaders = {};\n for (const name in headers) {\n const headerValues = headers[name];\n transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(\",\") : headerValues;\n }\n return transformedHeaders;\n};\n\nconst timing = {\n setTimeout: (cb, ms) => setTimeout(cb, ms),\n clearTimeout: (timeoutId) => clearTimeout(timeoutId),\n};\n\nconst DEFER_EVENT_LISTENER_TIME$2 = 1000;\nconst setConnectionTimeout = (request, reject, timeoutInMs = 0) => {\n if (!timeoutInMs) {\n return -1;\n }\n const registerTimeout = (offset) => {\n const timeoutId = timing.setTimeout(() => {\n request.destroy();\n reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${timeoutInMs} ms.`), {\n name: \"TimeoutError\",\n }));\n }, timeoutInMs - offset);\n const doWithSocket = (socket) => {\n if (socket?.connecting) {\n socket.on(\"connect\", () => {\n timing.clearTimeout(timeoutId);\n });\n }\n else {\n timing.clearTimeout(timeoutId);\n }\n };\n if (request.socket) {\n doWithSocket(request.socket);\n }\n else {\n request.on(\"socket\", doWithSocket);\n }\n };\n if (timeoutInMs < 2000) {\n registerTimeout(0);\n return 0;\n }\n return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME$2), DEFER_EVENT_LISTENER_TIME$2);\n};\n\nconst setRequestTimeout = (req, reject, timeoutInMs = 0, throwOnRequestTimeout, logger) => {\n if (timeoutInMs) {\n return timing.setTimeout(() => {\n let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? \"ERROR\" : \"WARN\"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`;\n if (throwOnRequestTimeout) {\n const error = Object.assign(new Error(msg), {\n name: \"TimeoutError\",\n code: \"ETIMEDOUT\",\n });\n req.destroy(error);\n reject(error);\n }\n else {\n msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`;\n logger?.warn?.(msg);\n }\n }, timeoutInMs);\n }\n return -1;\n};\n\nconst DEFER_EVENT_LISTENER_TIME$1 = 3000;\nconst setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME$1) => {\n if (keepAlive !== true) {\n return -1;\n }\n const registerListener = () => {\n if (request.socket) {\n request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);\n }\n else {\n request.on(\"socket\", (socket) => {\n socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);\n });\n }\n };\n if (deferTimeMs === 0) {\n registerListener();\n return 0;\n }\n return timing.setTimeout(registerListener, deferTimeMs);\n};\n\nconst DEFER_EVENT_LISTENER_TIME = 3000;\nconst setSocketTimeout = (request, reject, timeoutInMs = 0) => {\n const registerTimeout = (offset) => {\n const timeout = timeoutInMs - offset;\n const onTimeout = () => {\n request.destroy();\n reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket timed out after ${timeoutInMs} ms of inactivity (configured by client requestHandler).`), { name: \"TimeoutError\" }));\n };\n if (request.socket) {\n request.socket.setTimeout(timeout, onTimeout);\n request.on(\"close\", () => request.socket?.removeListener(\"timeout\", onTimeout));\n }\n else {\n request.setTimeout(timeout, onTimeout);\n }\n };\n if (0 < timeoutInMs && timeoutInMs < 6000) {\n registerTimeout(0);\n return 0;\n }\n return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME);\n};\n\nconst MIN_WAIT_TIME = 6_000;\nasync function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME, externalAgent = false) {\n const headers = request.headers;\n const expect = headers ? headers.Expect || headers.expect : undefined;\n let timeoutId = -1;\n let sendBody = true;\n if (!externalAgent && expect === \"100-continue\") {\n sendBody = await Promise.race([\n new Promise((resolve) => {\n timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)));\n }),\n new Promise((resolve) => {\n httpRequest.on(\"continue\", () => {\n timing.clearTimeout(timeoutId);\n resolve(true);\n });\n httpRequest.on(\"response\", () => {\n timing.clearTimeout(timeoutId);\n resolve(false);\n });\n httpRequest.on(\"error\", () => {\n timing.clearTimeout(timeoutId);\n resolve(false);\n });\n }),\n ]);\n }\n if (sendBody) {\n writeBody(httpRequest, request.body);\n }\n}\nfunction writeBody(httpRequest, body) {\n if (body instanceof Readable) {\n body.pipe(httpRequest);\n return;\n }\n if (body) {\n const isBuffer = Buffer.isBuffer(body);\n const isString = typeof body === \"string\";\n if (isBuffer || isString) {\n if (isBuffer && body.byteLength === 0) {\n httpRequest.end();\n }\n else {\n httpRequest.end(body);\n }\n return;\n }\n const uint8 = body;\n if (typeof uint8 === \"object\" &&\n uint8.buffer &&\n typeof uint8.byteOffset === \"number\" &&\n typeof uint8.byteLength === \"number\") {\n httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));\n return;\n }\n httpRequest.end(Buffer.from(body));\n return;\n }\n httpRequest.end();\n}\n\nconst DEFAULT_REQUEST_TIMEOUT = 0;\nlet hAgent = undefined;\nlet hRequest = undefined;\nclass NodeHttpHandler {\n config;\n configProvider;\n socketWarningTimestamp = 0;\n externalAgent = false;\n metadata = { handlerProtocol: \"http/1.1\" };\n static create(instanceOrOptions) {\n if (typeof instanceOrOptions?.handle === \"function\") {\n return instanceOrOptions;\n }\n return new NodeHttpHandler(instanceOrOptions);\n }\n static checkSocketUsage(agent, socketWarningTimestamp, logger = console) {\n const { sockets, requests, maxSockets } = agent;\n if (typeof maxSockets !== \"number\" || maxSockets === Infinity) {\n return socketWarningTimestamp;\n }\n const interval = 15_000;\n if (Date.now() - interval < socketWarningTimestamp) {\n return socketWarningTimestamp;\n }\n if (sockets && requests) {\n for (const origin in sockets) {\n const socketsInUse = sockets[origin]?.length ?? 0;\n const requestsEnqueued = requests[origin]?.length ?? 0;\n if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) {\n logger?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.\nSee https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html\nor increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`);\n return Date.now();\n }\n }\n }\n return socketWarningTimestamp;\n }\n constructor(options) {\n this.configProvider = new Promise((resolve, reject) => {\n if (typeof options === \"function\") {\n options()\n .then((_options) => {\n resolve(this.resolveDefaultConfig(_options));\n })\n .catch(reject);\n }\n else {\n resolve(this.resolveDefaultConfig(options));\n }\n });\n }\n destroy() {\n this.config?.httpAgent?.destroy();\n this.config?.httpsAgent?.destroy();\n }\n async handle(request, { abortSignal, requestTimeout } = {}) {\n if (!this.config) {\n this.config = await this.configProvider;\n }\n const config = this.config;\n const logger = config.logger;\n const isSSL = request.protocol === \"https:\";\n if (!isSSL && !this.config.httpAgent) {\n this.config.httpAgent = await this.config.httpAgentProvider();\n }\n return new Promise((_resolve, _reject) => {\n let writeRequestBodyPromise = undefined;\n let socketWarningTimeoutId = -1;\n let connectionTimeoutId = -1;\n let requestTimeoutId = -1;\n let socketTimeoutId = -1;\n let keepAliveTimeoutId = -1;\n const clearTimeouts = () => {\n timing.clearTimeout(socketWarningTimeoutId);\n timing.clearTimeout(connectionTimeoutId);\n timing.clearTimeout(requestTimeoutId);\n timing.clearTimeout(socketTimeoutId);\n timing.clearTimeout(keepAliveTimeoutId);\n };\n const resolve = async (arg) => {\n await writeRequestBodyPromise;\n clearTimeouts();\n _resolve(arg);\n };\n const reject = async (arg) => {\n await writeRequestBodyPromise;\n clearTimeouts();\n _reject(arg);\n };\n if (abortSignal?.aborted) {\n const abortError = buildAbortError(abortSignal);\n reject(abortError);\n return;\n }\n const headers = request.headers;\n const expectContinue = headers ? (headers.Expect ?? headers.expect) === \"100-continue\" : false;\n let agent = isSSL ? config.httpsAgent : config.httpAgent;\n if (expectContinue && !this.externalAgent) {\n agent = new (isSSL ? node_https.Agent : hAgent)({\n keepAlive: false,\n maxSockets: Infinity,\n });\n }\n socketWarningTimeoutId = timing.setTimeout(() => {\n this.socketWarningTimestamp = NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, logger);\n }, config.socketAcquisitionWarningTimeout ?? (config.requestTimeout ?? 2000) + (config.connectionTimeout ?? 1000));\n const queryString = request.query ? buildQueryString(request.query) : \"\";\n let auth = undefined;\n if (request.username != null || request.password != null) {\n const username = request.username ?? \"\";\n const password = request.password ?? \"\";\n auth = `${username}:${password}`;\n }\n let path = request.path;\n if (queryString) {\n path += `?${queryString}`;\n }\n if (request.fragment) {\n path += `#${request.fragment}`;\n }\n let hostname = request.hostname ?? \"\";\n if (hostname[0] === \"[\" && hostname.endsWith(\"]\")) {\n hostname = request.hostname.slice(1, -1);\n }\n else {\n hostname = request.hostname;\n }\n const nodeHttpsOptions = {\n headers: request.headers,\n host: hostname,\n method: request.method,\n path,\n port: request.port,\n agent,\n auth,\n };\n const requestFunc = isSSL ? node_https.request : hRequest;\n const req = requestFunc(nodeHttpsOptions, (res) => {\n const httpResponse = new HttpResponse({\n statusCode: res.statusCode || -1,\n reason: res.statusMessage,\n headers: getTransformedHeaders(res.headers),\n body: res,\n });\n resolve({ response: httpResponse });\n });\n req.on(\"error\", (err) => {\n if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) {\n reject(Object.assign(err, { name: \"TimeoutError\" }));\n }\n else {\n reject(err);\n }\n });\n if (abortSignal) {\n const onAbort = () => {\n req.destroy();\n const abortError = buildAbortError(abortSignal);\n reject(abortError);\n };\n if (typeof abortSignal.addEventListener === \"function\") {\n const signal = abortSignal;\n signal.addEventListener(\"abort\", onAbort, { once: true });\n req.once(\"close\", () => signal.removeEventListener(\"abort\", onAbort));\n }\n else {\n abortSignal.onabort = onAbort;\n }\n }\n const effectiveRequestTimeout = requestTimeout ?? config.requestTimeout;\n connectionTimeoutId = setConnectionTimeout(req, reject, config.connectionTimeout);\n requestTimeoutId = setRequestTimeout(req, reject, effectiveRequestTimeout, config.throwOnRequestTimeout, logger ?? console);\n socketTimeoutId = setSocketTimeout(req, reject, config.socketTimeout);\n const httpAgent = nodeHttpsOptions.agent;\n if (typeof httpAgent === \"object\" && \"keepAlive\" in httpAgent) {\n keepAliveTimeoutId = setSocketKeepAlive(req, {\n keepAlive: httpAgent.keepAlive,\n keepAliveMsecs: httpAgent.keepAliveMsecs,\n });\n }\n writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout, this.externalAgent).catch((e) => {\n clearTimeouts();\n return _reject(e);\n });\n });\n }\n updateHttpClientConfig(key, value) {\n this.config = undefined;\n this.configProvider = this.configProvider.then((config) => {\n if (key === Symbol.for(\"logger\")) {\n return {\n ...config,\n logger: config.logger ?? value,\n };\n }\n return {\n ...config,\n [key]: value,\n };\n });\n }\n httpHandlerConfigs() {\n return this.config ?? {};\n }\n resolveDefaultConfig(options) {\n const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, logger, } = options || {};\n const keepAlive = true;\n const maxSockets = 50;\n return {\n connectionTimeout,\n requestTimeout,\n socketTimeout,\n socketAcquisitionWarningTimeout,\n throwOnRequestTimeout,\n httpAgentProvider: async () => {\n const node_http = require('node:http');\n const { Agent, request } = node_http.default ?? node_http;\n hRequest = request;\n hAgent = Agent;\n if (httpAgent instanceof hAgent || typeof httpAgent?.destroy === \"function\") {\n this.externalAgent = true;\n return httpAgent;\n }\n return new hAgent({ keepAlive, maxSockets, ...httpAgent });\n },\n httpsAgent: (() => {\n if (httpsAgent instanceof node_https.Agent || typeof httpsAgent?.destroy === \"function\") {\n this.externalAgent = true;\n return httpsAgent;\n }\n return new node_https.Agent({ keepAlive, maxSockets, ...httpsAgent });\n })(),\n logger,\n };\n }\n}\n\nconst ids = new Uint16Array(1);\nclass ClientHttp2SessionRef {\n id = ids[0]++;\n total = 0;\n max = 0;\n session;\n refs = 0;\n constructor(session) {\n session.unref();\n this.session = session;\n }\n retain() {\n if (this.session.destroyed) {\n throw new Error(\"@smithy/node-http-handler - cannot acquire reference to destroyed session.\");\n }\n this.refs += 1;\n this.total += 1;\n this.max = Math.max(this.refs, this.max);\n this.session.ref();\n }\n free() {\n if (this.session.destroyed) {\n return;\n }\n this.refs -= 1;\n if (this.refs === 0) {\n this.session.unref();\n }\n if (this.refs < 0) {\n throw new Error(\"@smithy/node-http-handler - ClientHttp2Session refcount at zero, cannot decrement.\");\n }\n }\n deref() {\n return this.session;\n }\n close() {\n if (!this.session.closed) {\n this.session.close();\n }\n }\n destroy() {\n this.refs = 0;\n if (!this.session.destroyed) {\n this.session.destroy();\n }\n }\n useCount() {\n return this.refs;\n }\n}\n\nclass NodeHttp2ConnectionPool {\n sessions = [];\n maxConcurrency = 0;\n constructor(sessions) {\n this.sessions = (sessions ?? []).map((session) => new ClientHttp2SessionRef(session));\n }\n poll() {\n let cleanup = false;\n for (const session of this.sessions) {\n if (session.deref().destroyed) {\n cleanup = true;\n continue;\n }\n if (!this.maxConcurrency || session.useCount() < this.maxConcurrency) {\n return session;\n }\n }\n if (cleanup) {\n for (const session of this.sessions) {\n if (session.deref().destroyed) {\n this.remove(session);\n }\n }\n }\n }\n offerLast(ref) {\n this.sessions.push(ref);\n }\n remove(ref) {\n const ix = this.sessions.indexOf(ref);\n if (ix > -1) {\n this.sessions.splice(ix, 1);\n }\n }\n [Symbol.iterator]() {\n return this.sessions[Symbol.iterator]();\n }\n setMaxConcurrency(maxConcurrency) {\n this.maxConcurrency = maxConcurrency;\n }\n destroy(ref) {\n this.remove(ref);\n ref.destroy();\n }\n}\n\nclass NodeHttp2ConnectionManager {\n config;\n connectOptions;\n connectionPools = new Map();\n constructor(config) {\n this.config = config;\n if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) {\n throw new RangeError(\"maxConcurrency must be greater than zero.\");\n }\n }\n lease(requestContext, connectionConfiguration) {\n const url = this.getUrlString(requestContext);\n const pool = this.getPool(url);\n if (!this.config.disableConcurrency && !connectionConfiguration.isEventStream) {\n const available = pool.poll();\n if (available) {\n available.retain();\n return available;\n }\n }\n const ref = new ClientHttp2SessionRef(this.connect(url));\n const session = ref.deref();\n if (this.config.maxConcurrency) {\n session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => {\n if (err) {\n throw new Error(\"Fail to set maxConcurrentStreams to \" +\n this.config.maxConcurrency +\n \"when creating new session for \" +\n requestContext.destination.toString());\n }\n });\n }\n const graceful = () => {\n this.removeFromPoolAndClose(url, ref);\n };\n const ensureDestroyed = () => {\n this.removeFromPoolAndCheckedDestroy(url, ref);\n };\n session.on(\"goaway\", graceful);\n session.on(\"error\", ensureDestroyed);\n session.on(\"frameError\", ensureDestroyed);\n session.on(\"close\", ensureDestroyed);\n if (connectionConfiguration.requestTimeout) {\n session.setTimeout(connectionConfiguration.requestTimeout, ensureDestroyed);\n }\n pool.offerLast(ref);\n ref.retain();\n return ref;\n }\n release(_requestContext, ref) {\n ref.free();\n }\n createIsolatedSession(requestContext, connectionConfiguration) {\n const url = this.getUrlString(requestContext);\n const ref = new ClientHttp2SessionRef(this.connect(url));\n const session = ref.deref();\n session.settings({ maxConcurrentStreams: 1 });\n const ensureDestroyed = () => {\n ref.destroy();\n };\n session.on(\"error\", ensureDestroyed);\n session.on(\"frameError\", ensureDestroyed);\n session.on(\"close\", ensureDestroyed);\n if (connectionConfiguration.requestTimeout) {\n session.setTimeout(connectionConfiguration.requestTimeout, ensureDestroyed);\n }\n ref.retain();\n return ref;\n }\n destroy() {\n for (const [url, connectionPool] of this.connectionPools) {\n for (const session of [...connectionPool]) {\n session.destroy();\n }\n this.connectionPools.delete(url);\n }\n }\n setMaxConcurrentStreams(maxConcurrentStreams) {\n if (maxConcurrentStreams && maxConcurrentStreams <= 0) {\n throw new RangeError(\"maxConcurrentStreams must be greater than zero.\");\n }\n this.config.maxConcurrency = maxConcurrentStreams;\n for (const pool of this.connectionPools.values()) {\n pool.setMaxConcurrency(maxConcurrentStreams);\n }\n }\n setDisableConcurrentStreams(disableConcurrentStreams) {\n this.config.disableConcurrency = disableConcurrentStreams;\n }\n setNodeHttp2ConnectOptions(nodeHttp2ConnectOptions) {\n this.connectOptions = nodeHttp2ConnectOptions;\n }\n debug() {\n const pools = {};\n for (const [url, pool] of this.connectionPools) {\n const sessions = [];\n for (const ref of pool) {\n sessions.push({\n id: ref.id,\n active: ref.useCount(),\n maxConcurrent: ref.max,\n totalRequests: ref.total,\n });\n }\n pools[url] = { sessions };\n }\n return pools;\n }\n removeFromPoolAndClose(authority, ref) {\n this.connectionPools.get(authority)?.remove(ref);\n ref.close();\n }\n removeFromPoolAndCheckedDestroy(authority, ref) {\n this.connectionPools.get(authority)?.remove(ref);\n ref.destroy();\n }\n getPool(url) {\n if (!this.connectionPools.has(url)) {\n const pool = new NodeHttp2ConnectionPool();\n if (this.config.maxConcurrency) {\n pool.setMaxConcurrency(this.config.maxConcurrency);\n }\n this.connectionPools.set(url, pool);\n }\n return this.connectionPools.get(url);\n }\n getUrlString(request) {\n return request.destination.toString();\n }\n connect(url) {\n return this.connectOptions === undefined ? http2.connect(url) : http2.connect(url, this.connectOptions);\n }\n}\n\nconst { constants } = http2;\nclass NodeHttp2Handler {\n config;\n configProvider;\n metadata = { handlerProtocol: \"h2\" };\n connectionManager = new NodeHttp2ConnectionManager({});\n static create(instanceOrOptions) {\n if (typeof instanceOrOptions?.handle === \"function\") {\n return instanceOrOptions;\n }\n return new NodeHttp2Handler(instanceOrOptions);\n }\n constructor(options) {\n this.configProvider = new Promise((resolve, reject) => {\n if (typeof options === \"function\") {\n options()\n .then((opts) => {\n resolve(opts || {});\n })\n .catch(reject);\n }\n else {\n resolve(options || {});\n }\n });\n }\n destroy() {\n this.connectionManager.destroy();\n }\n async handle(request, { abortSignal, requestTimeout, isEventStream } = {}) {\n if (!this.config) {\n this.config = await this.configProvider;\n const { disableConcurrentStreams, maxConcurrentStreams, nodeHttp2ConnectOptions } = this.config;\n this.connectionManager.setDisableConcurrentStreams(disableConcurrentStreams ?? false);\n if (maxConcurrentStreams) {\n this.connectionManager.setMaxConcurrentStreams(maxConcurrentStreams);\n }\n if (nodeHttp2ConnectOptions) {\n this.connectionManager.setNodeHttp2ConnectOptions(nodeHttp2ConnectOptions);\n }\n }\n const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config;\n const useIsolatedSession = disableConcurrentStreams || isEventStream;\n const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout;\n return new Promise((_resolve, _reject) => {\n let fulfilled = false;\n let writeRequestBodyPromise = undefined;\n const resolve = async (arg) => {\n await writeRequestBodyPromise;\n _resolve(arg);\n };\n const reject = async (arg) => {\n await writeRequestBodyPromise;\n _reject(arg);\n };\n if (abortSignal?.aborted) {\n fulfilled = true;\n const abortError = buildAbortError(abortSignal);\n reject(abortError);\n return;\n }\n const { hostname, method, port, protocol, query } = request;\n let auth = \"\";\n if (request.username != null || request.password != null) {\n const username = request.username ?? \"\";\n const password = request.password ?? \"\";\n auth = `${username}:${password}@`;\n }\n const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : \"\"}`;\n const requestContext = { destination: new URL(authority) };\n const connectConfig = {\n requestTimeout: this.config?.sessionTimeout,\n isEventStream,\n };\n const ref = useIsolatedSession\n ? this.connectionManager.createIsolatedSession(requestContext, connectConfig)\n : this.connectionManager.lease(requestContext, connectConfig);\n const session = ref.deref();\n const rejectWithDestroy = (err) => {\n if (useIsolatedSession) {\n ref.destroy();\n }\n fulfilled = true;\n reject(err);\n };\n const queryString = query ? buildQueryString(query) : \"\";\n let path = request.path;\n if (queryString) {\n path += `?${queryString}`;\n }\n if (request.fragment) {\n path += `#${request.fragment}`;\n }\n const clientHttp2Stream = session.request({\n ...request.headers,\n [constants.HTTP2_HEADER_PATH]: path,\n [constants.HTTP2_HEADER_METHOD]: method,\n });\n if (effectiveRequestTimeout) {\n clientHttp2Stream.setTimeout(effectiveRequestTimeout, () => {\n clientHttp2Stream.close();\n const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`);\n timeoutError.name = \"TimeoutError\";\n rejectWithDestroy(timeoutError);\n });\n }\n if (abortSignal) {\n const onAbort = () => {\n clientHttp2Stream.close();\n const abortError = buildAbortError(abortSignal);\n rejectWithDestroy(abortError);\n };\n if (typeof abortSignal.addEventListener === \"function\") {\n const signal = abortSignal;\n signal.addEventListener(\"abort\", onAbort, { once: true });\n clientHttp2Stream.once(\"close\", () => signal.removeEventListener(\"abort\", onAbort));\n }\n else {\n abortSignal.onabort = onAbort;\n }\n }\n clientHttp2Stream.on(\"frameError\", (type, code, id) => {\n rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`));\n });\n clientHttp2Stream.on(\"error\", rejectWithDestroy);\n clientHttp2Stream.on(\"aborted\", () => {\n rejectWithDestroy(new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${clientHttp2Stream.rstCode}.`));\n });\n clientHttp2Stream.on(\"response\", (headers) => {\n const httpResponse = new HttpResponse({\n statusCode: headers[\":status\"] ?? -1,\n headers: getTransformedHeaders(headers),\n body: clientHttp2Stream,\n });\n fulfilled = true;\n resolve({ response: httpResponse });\n if (useIsolatedSession) {\n session.close();\n }\n });\n clientHttp2Stream.on(\"close\", () => {\n if (useIsolatedSession) {\n ref.destroy();\n }\n else {\n this.connectionManager.release(requestContext, ref);\n }\n if (!fulfilled) {\n rejectWithDestroy(new Error(\"Unexpected error: http2 request did not get a response\"));\n }\n });\n writeRequestBodyPromise = writeRequestBody(clientHttp2Stream, request, effectiveRequestTimeout);\n });\n }\n updateHttpClientConfig(key, value) {\n this.config = undefined;\n this.configProvider = this.configProvider.then((config) => {\n return {\n ...config,\n [key]: value,\n };\n });\n }\n httpHandlerConfigs() {\n return this.config ?? {};\n }\n}\n\nexports.DEFAULT_REQUEST_TIMEOUT = DEFAULT_REQUEST_TIMEOUT;\nexports.NodeHttp2Handler = NodeHttp2Handler;\nexports.NodeHttpHandler = NodeHttpHandler;\n" | ||
| ], | ||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,EAAS,CAAuB,EACjG,EAEL,sBAAsB,CAAC,EAAK,EAAO,CAC/B,KAAK,OAAS,OACd,KAAK,eAAiB,KAAK,eAAe,KAAK,CAAC,KACrC,IACA,GACF,GAAM,CACX,EACH,EAEL,kBAAkB,EAAG,CACjB,OAAO,KAAK,QAAU,CAAC,EAE/B,CAEQ,2BAA0B,GAC1B,oBAAmB,EACnB,mBAAkB", | ||
| "debugId": "7FCAF7E38EB6E56964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "466416BA0DD5739664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-env@3.972.69/node_modules/@aws-sdk/credential-provider-env/dist-es/fromEnv.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError } from \"@smithy/core/config\";\nexport const ENV_KEY = \"AWS_ACCESS_KEY_ID\";\nexport const ENV_SECRET = \"AWS_SECRET_ACCESS_KEY\";\nexport const ENV_SESSION = \"AWS_SESSION_TOKEN\";\nexport const ENV_EXPIRATION = \"AWS_CREDENTIAL_EXPIRATION\";\nexport const ENV_CREDENTIAL_SCOPE = \"AWS_CREDENTIAL_SCOPE\";\nexport const ENV_ACCOUNT_ID = \"AWS_ACCOUNT_ID\";\nexport const fromEnv = (init) => async () => {\n init?.logger?.debug(\"@aws-sdk/credential-provider-env - fromEnv\");\n const accessKeyId = process.env[ENV_KEY];\n const secretAccessKey = process.env[ENV_SECRET];\n const sessionToken = process.env[ENV_SESSION];\n const expiry = process.env[ENV_EXPIRATION];\n const credentialScope = process.env[ENV_CREDENTIAL_SCOPE];\n const accountId = process.env[ENV_ACCOUNT_ID];\n if (accessKeyId && secretAccessKey) {\n const credentials = {\n accessKeyId,\n secretAccessKey,\n ...(sessionToken && { sessionToken }),\n ...(expiry && { expiration: new Date(expiry) }),\n ...(credentialScope && { credentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"CREDENTIALS_ENV_VARS\", \"g\");\n return credentials;\n }\n throw new CredentialsProviderError(\"Unable to find environment variable credentials.\", { logger: init?.logger });\n};\n" | ||
| ], | ||
| "mappings": ";4JAAA,eACA,WACa,EAAU,oBACV,EAAa,wBACb,EAAc,oBACd,EAAiB,4BACjB,EAAuB,uBACvB,EAAiB,iBACjB,EAAU,CAAC,IAAS,SAAY,CACzC,GAAM,QAAQ,MAAM,4CAA4C,EAChE,IAAM,EAAc,QAAQ,IAAI,GAC1B,EAAkB,QAAQ,IAAI,GAC9B,EAAe,QAAQ,IAAI,GAC3B,EAAS,QAAQ,IAAI,GACrB,EAAkB,QAAQ,IAAI,GAC9B,EAAY,QAAQ,IAAI,GAC9B,GAAI,GAAe,EAAiB,CAChC,IAAM,EAAc,CAChB,cACA,qBACI,GAAgB,CAAE,cAAa,KAC/B,GAAU,CAAE,WAAY,IAAI,KAAK,CAAM,CAAE,KACzC,GAAmB,CAAE,iBAAgB,KACrC,GAAa,CAAE,WAAU,CACjC,EAEA,OADA,uBAAqB,EAAa,uBAAwB,GAAG,EACtD,EAEX,MAAM,IAAI,2BAAyB,mDAAoD,CAAE,OAAQ,GAAM,MAAO,CAAC", | ||
| "debugId": "E09331F4E9DF42A664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/set.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect, Option } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.set,\n Effect.fn(\"cli.service.set\")(function* (input) {\n yield* ServiceConfig.set(input.key, input.value, Option.getOrUndefined(input.nestedValue))\n }),\n)\n" | ||
| ], | ||
| "mappings": ";i5BAKA,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,IACnC,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAAO,CAC7C,MAAO,EAAc,IAAI,EAAM,IAAK,EAAM,MAAO,EAAO,eAAe,EAAM,WAAW,CAAC,EAC1F,CACH", | ||
| "debugId": "D0C67B3B5E67130964756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/inventory.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Cause, Effect, Exit } from \"effect\"\nimport { OpenCode, type PluginInfo } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Npm } from \"@opencode-ai/util/npm\"\nimport { Config } from \"../../../config\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport interface Item {\n readonly runtime: \"Server\" | \"TUI\"\n readonly target: string\n readonly name: string\n readonly version?: string\n readonly outdated: boolean\n readonly error?: string\n}\n\nexport const inspect = Effect.fn(\"cli.plugin.inspect\")(function* (selected?: string) {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const location = { directory: process.cwd() }\n const listed = yield* Effect.promise(() => client.plugin.list({ location }))\n const serverTargets = new Set(\n listed.data.flatMap((plugin) => (plugin.source.type === \"package\" ? [plugin.source.target] : [])),\n )\n const server =\n selected === undefined || serverTargets.has(selected)\n ? yield* Effect.promise(() => client.plugin.check({ location, ...(selected ? { target: selected } : {}) }))\n : listed\n const serverItems = server.data.flatMap((plugin): Item[] => {\n if (plugin.source.type !== \"package\") return []\n if (selected !== undefined && plugin.source.target !== selected) return []\n return [\n {\n runtime: \"Server\",\n target: plugin.source.target,\n name: plugin.id ?? plugin.source.target,\n ...(plugin.source.version ? { version: displayVersion(plugin.source.version) } : {}),\n outdated: plugin.source.outdated === true,\n ...(plugin.state.status === \"failed\" ? { error: plugin.state.error } : {}),\n },\n ]\n })\n\n const config = yield* Config.Service\n const info = yield* config.get()\n const configured = [\n ...new Set(\n (info.plugins ?? []).flatMap((entry) => {\n const target = typeof entry === \"string\" ? entry : entry.package\n if (target.startsWith(\"-\") || target === \"*\" || target.endsWith(\".*\") || target.startsWith(\"opencode.\")) return []\n return [target]\n }),\n ),\n ]\n const tuiTargets = yield* Effect.promise(async () => {\n const installable = await Promise.all(configured.map((target) => Npm.isInstallablePackage(target)))\n return configured.filter((target, index) => installable[index] && (selected === undefined || target === selected))\n })\n const npm = yield* Npm.Service\n const tuiItems = yield* Effect.forEach(\n tuiTargets,\n (target) =>\n Effect.gen(function* () {\n const installed = yield* npm.resolve(target, { subpaths: [\"tui\"] })\n const outdated = yield* npm.check(target).pipe(Effect.exit)\n return {\n runtime: \"TUI\" as const,\n target,\n name: target,\n ...(installed.version ? { version: displayVersion(installed.version) } : {}),\n outdated: Exit.isSuccess(outdated) && outdated.value,\n ...(Exit.isFailure(outdated) ? { error: Cause.pretty(outdated.cause) } : {}),\n }\n }),\n { concurrency: \"unbounded\" },\n )\n const items = [...serverItems, ...tuiItems]\n if (selected !== undefined && !items.length) return yield* Effect.fail(new Error(`Plugin is not configured: ${selected}`))\n return { client, location, items }\n})\n\nexport function displayVersion(version: string) {\n return /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(version) ? version.slice(0, 7) : version\n}\n\nexport function format(items: readonly Item[]) {\n return [\"Server\", \"TUI\"]\n .flatMap((runtime) => {\n const rows = items.filter((item) => item.runtime === runtime)\n if (!rows.length) return []\n return [\n runtime,\n ...rows.map(\n (item) =>\n ` ${item.name}${item.version ? ` ${item.version}` : \"\"} (${item.error ? \"check failed\" : item.outdated ? \"update available\" : \"current\"})`,\n ),\n ]\n })\n .join(EOL)\n}\n" | ||
| ], | ||
| "mappings": ";wUAAA,cAAS,WAiBF,IAAM,EAAU,EAAO,GAAG,oBAAoB,EAAE,SAAU,CAAC,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S,EAAK,UAAY,CAAO,EAC5D,GAAI,CAAC,EAAK,OAAQ,MAAO,CAAC,EAC1B,MAAO,CACL,EACA,GAAG,EAAK,IACN,CAAC,IACC,KAAK,EAAK,OAAO,EAAK,QAAU,IAAI,EAAK,UAAY,OAAO,EAAK,MAAQ,eAAiB,EAAK,SAAW,mBAAqB,YACnI,CACF,EACD,EACA,KAAK,CAAG", | ||
| "debugId": "C3F6C7A30A8FCB5664756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/fromIni.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProfileData.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveAssumeRoleCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveCredentialSource.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveLoginCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProcessCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveSsoCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveStaticCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-ini@3.973.14/node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveWebIdentityCredentials.js"], | ||
| "sourcesContent": [ | ||
| "import { getProfileName, parseKnownFiles } from \"@smithy/core/config\";\nimport { resolveProfileData } from \"./resolveProfileData\";\nexport const fromIni = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-ini - fromIni\");\n const profiles = await parseKnownFiles(init);\n return resolveProfileData(getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n }), profiles, init, callerClientConfig);\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { isAssumeRoleProfile, resolveAssumeRoleCredentials } from \"./resolveAssumeRoleCredentials\";\nimport { isLoginProfile, resolveLoginCredentials } from \"./resolveLoginCredentials\";\nimport { isProcessProfile, resolveProcessCredentials } from \"./resolveProcessCredentials\";\nimport { isSsoProfile, resolveSsoCredentials } from \"./resolveSsoCredentials\";\nimport { isStaticCredsProfile, resolveStaticCredentials } from \"./resolveStaticCredentials\";\nimport { isWebIdentityProfile, resolveWebIdentityCredentials } from \"./resolveWebIdentityCredentials\";\nexport const resolveProfileData = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => {\n const data = profiles[profileName];\n if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) {\n return resolveStaticCredentials(data, options);\n }\n if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) {\n return resolveAssumeRoleCredentials(profileName, profiles, options, callerClientConfig, visitedProfiles, resolveProfileData);\n }\n if (isStaticCredsProfile(data)) {\n return resolveStaticCredentials(data, options);\n }\n if (isWebIdentityProfile(data)) {\n return resolveWebIdentityCredentials(data, options, callerClientConfig);\n }\n if (isProcessProfile(data)) {\n return resolveProcessCredentials(options, profileName);\n }\n if (isSsoProfile(data)) {\n return await resolveSsoCredentials(profileName, data, options, callerClientConfig);\n }\n if (isLoginProfile(data)) {\n return resolveLoginCredentials(profileName, options, callerClientConfig);\n }\n throw new CredentialsProviderError(`Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, { logger: options.logger });\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError, getProfileName } from \"@smithy/core/config\";\nimport { resolveCredentialSource } from \"./resolveCredentialSource\";\nexport const isAssumeRoleProfile = (arg, { profile = \"default\", logger } = {}) => {\n return (Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.role_arn === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.role_session_name) > -1 &&\n [\"undefined\", \"string\"].indexOf(typeof arg.external_id) > -1 &&\n [\"undefined\", \"string\"].indexOf(typeof arg.mfa_serial) > -1 &&\n (isAssumeRoleWithSourceProfile(arg, { profile, logger }) || isCredentialSourceProfile(arg, { profile, logger })));\n};\nconst isAssumeRoleWithSourceProfile = (arg, { profile, logger }) => {\n const withSourceProfile = typeof arg.source_profile === \"string\" && typeof arg.credential_source === \"undefined\";\n if (withSourceProfile) {\n logger?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`);\n }\n return withSourceProfile;\n};\nconst isCredentialSourceProfile = (arg, { profile, logger }) => {\n const withProviderProfile = typeof arg.credential_source === \"string\" && typeof arg.source_profile === \"undefined\";\n if (withProviderProfile) {\n logger?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`);\n }\n return withProviderProfile;\n};\nexport const resolveAssumeRoleCredentials = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, resolveProfileData) => {\n options.logger?.debug(\"@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)\");\n const profileData = profiles[profileName];\n const { source_profile, region } = profileData;\n if (!options.roleAssumer) {\n const { getDefaultRoleAssumer } = await import(\"@aws-sdk/nested-clients/sts\");\n options.roleAssumer = getDefaultRoleAssumer({\n ...options.clientConfig,\n credentialProviderLogger: options.logger,\n parentClientConfig: {\n ...callerClientConfig,\n ...options?.parentClientConfig,\n region: region ?? options?.parentClientConfig?.region ?? callerClientConfig?.region,\n },\n }, options.clientPlugins);\n }\n if (source_profile && source_profile in visitedProfiles) {\n throw new CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile` +\n ` ${getProfileName(options)}. Profiles visited: ` +\n Object.keys(visitedProfiles).join(\", \"), { logger: options.logger });\n }\n options.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`);\n const sourceCredsProvider = source_profile\n ? resolveProfileData(source_profile, profiles, options, callerClientConfig, {\n ...visitedProfiles,\n [source_profile]: true,\n }, isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {}))\n : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))();\n if (isCredentialSourceWithoutRoleArn(profileData)) {\n return sourceCredsProvider.then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SOURCE_PROFILE\", \"o\"));\n }\n else {\n const params = {\n RoleArn: profileData.role_arn,\n RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`,\n ExternalId: profileData.external_id,\n DurationSeconds: parseInt(profileData.duration_seconds || \"3600\", 10),\n };\n const { mfa_serial } = profileData;\n if (mfa_serial) {\n if (!options.mfaCodeProvider) {\n throw new CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, { logger: options.logger, tryNextLink: false });\n }\n params.SerialNumber = mfa_serial;\n params.TokenCode = await options.mfaCodeProvider(mfa_serial);\n }\n const sourceCreds = await sourceCredsProvider;\n return options.roleAssumer(sourceCreds, params).then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SOURCE_PROFILE\", \"o\"));\n }\n};\nconst isCredentialSourceWithoutRoleArn = (section) => {\n return !section.role_arn && !!section.credential_source;\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { chain, CredentialsProviderError } from \"@smithy/core/config\";\nexport const resolveCredentialSource = (credentialSource, profileName, logger) => {\n const sourceProvidersMap = {\n EcsContainer: async (options) => {\n const { fromHttp } = await import(\"@aws-sdk/credential-provider-http\");\n const { fromContainerMetadata } = await import(\"@smithy/credential-provider-imds\");\n logger?.debug(\"@aws-sdk/credential-provider-ini - credential_source is EcsContainer\");\n return async () => chain(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider);\n },\n Ec2InstanceMetadata: async (options) => {\n logger?.debug(\"@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata\");\n const { fromInstanceMetadata } = await import(\"@smithy/credential-provider-imds\");\n return async () => fromInstanceMetadata(options)().then(setNamedProvider);\n },\n Environment: async (options) => {\n logger?.debug(\"@aws-sdk/credential-provider-ini - credential_source is Environment\");\n const { fromEnv } = await import(\"@aws-sdk/credential-provider-env\");\n return async () => fromEnv(options)().then(setNamedProvider);\n },\n };\n if (credentialSource in sourceProvidersMap) {\n return sourceProvidersMap[credentialSource];\n }\n else {\n throw new CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, ` +\n `expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger });\n }\n};\nconst setNamedProvider = (creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_NAMED_PROVIDER\", \"p\");\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isLoginProfile = (data) => {\n return Boolean(data && data.login_session);\n};\nexport const resolveLoginCredentials = async (profileName, options, callerClientConfig) => {\n const { fromLoginCredentials } = await import(\"@aws-sdk/credential-provider-login\");\n const credentials = await fromLoginCredentials({\n ...options,\n profile: profileName,\n })({ callerClientConfig });\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE_LOGIN\", \"AC\");\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isProcessProfile = (arg) => Boolean(arg) && typeof arg === \"object\" && typeof arg.credential_process === \"string\";\nexport const resolveProcessCredentials = async (options, profile) => {\n const { fromProcess } = await import(\"@aws-sdk/credential-provider-process\");\n const credentials = await fromProcess({\n ...options,\n profile,\n })();\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE_PROCESS\", \"v\");\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const resolveSsoCredentials = async (profile, profileData, options = {}, callerClientConfig) => {\n const { fromSSO } = await import(\"@aws-sdk/credential-provider-sso\");\n return fromSSO({\n profile,\n logger: options.logger,\n parentClientConfig: options.parentClientConfig,\n clientConfig: options.clientConfig,\n })({\n callerClientConfig,\n }).then((creds) => {\n if (profileData.sso_session) {\n return setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SSO\", \"r\");\n }\n else {\n return setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SSO_LEGACY\", \"t\");\n }\n });\n};\nexport const isSsoProfile = (arg) => arg &&\n (typeof arg.sso_start_url === \"string\" ||\n typeof arg.sso_account_id === \"string\" ||\n typeof arg.sso_session === \"string\" ||\n typeof arg.sso_region === \"string\" ||\n typeof arg.sso_role_name === \"string\");\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isStaticCredsProfile = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.aws_access_key_id === \"string\" &&\n typeof arg.aws_secret_access_key === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.aws_session_token) > -1 &&\n [\"undefined\", \"string\"].indexOf(typeof arg.aws_account_id) > -1;\nexport const resolveStaticCredentials = async (profile, options) => {\n options?.logger?.debug(\"@aws-sdk/credential-provider-ini - resolveStaticCredentials\");\n const credentials = {\n accessKeyId: profile.aws_access_key_id,\n secretAccessKey: profile.aws_secret_access_key,\n sessionToken: profile.aws_session_token,\n ...(profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }),\n ...(profile.aws_account_id && { accountId: profile.aws_account_id }),\n };\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE\", \"n\");\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isWebIdentityProfile = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.web_identity_token_file === \"string\" &&\n typeof arg.role_arn === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.role_session_name) > -1;\nexport const resolveWebIdentityCredentials = async (profile, options, callerClientConfig) => {\n const { fromTokenFile } = await import(\"@aws-sdk/credential-provider-web-identity\");\n const credentials = await fromTokenFile({\n webIdentityTokenFile: profile.web_identity_token_file,\n roleArn: profile.role_arn,\n roleSessionName: profile.role_session_name,\n roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity,\n logger: options.logger,\n parentClientConfig: options.parentClientConfig,\n })({\n callerClientConfig,\n });\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN\", \"q\");\n};\n" | ||
| ], | ||
| "mappings": ";oKAAA,eCAA,eCAA,eACA,WCDA,eACA,WACa,EAA0B,CAAC,EAAkB,EAAa,IAAW,CAC9E,IAAM,EAAqB,CACvB,aAAc,MAAO,IAAY,CAC7B,IAAQ,YAAa,KAAa,2CAC1B,yBAA0B,KAAa,0CAE/C,OADA,GAAQ,MAAM,sEAAsE,EAC7E,SAAY,QAAM,EAAS,GAAW,CAAC,CAAC,EAAG,EAAsB,CAAO,CAAC,EAAE,EAAE,KAAK,CAAgB,GAE7G,oBAAqB,MAAO,IAAY,CACpC,GAAQ,MAAM,6EAA6E,EAC3F,IAAQ,wBAAyB,KAAa,0CAC9C,MAAO,UAAY,EAAqB,CAAO,EAAE,EAAE,KAAK,CAAgB,GAE5E,YAAa,MAAO,IAAY,CAC5B,GAAQ,MAAM,qEAAqE,EACnF,IAAQ,WAAY,KAAa,0CACjC,MAAO,UAAY,EAAQ,CAAO,EAAE,EAAE,KAAK,CAAgB,EAEnE,EACA,GAAI,KAAoB,EACpB,OAAO,EAAmB,GAG1B,WAAM,IAAI,2BAAyB,4CAA4C,UAAoB,kEAC/B,CAAE,QAAO,CAAC,GAGhF,EAAmB,CAAC,IAAU,uBAAqB,EAAO,qCAAsC,GAAG,ED1BlG,IAAM,EAAsB,CAAC,GAAO,UAAU,UAAW,UAAW,CAAC,IAChE,QAAQ,CAAG,GACf,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AM,OAAS,sBAAuB,CAAC,IAAM,CACzE,EAAK,QAAQ,MAAM,4CAA4C,EAC/D,IAAM,EAAW,MAAM,kBAAgB,CAAI,EAC3C,OAAO,EAAmB,iBAAe,CACrC,QAAS,EAAK,SAAW,GAAoB,OACjD,CAAC,EAAG,EAAU,EAAM,CAAkB", | ||
| "debugId": "4E0948B97C179D0864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+nested-clients@3.997.43/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsRestJsonProtocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultSigninHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"signin\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultSigninHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"CreateOAuth2Token\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"signin\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.42\";\nvar packageInfo = {\n\tversion: version};\n\nconst s = \"ref\";\nconst a = -1, b = false, c = true, d = \"isSet\", e = \"booleanEquals\", f = \"coalesce\", g = \"PartitionResult\", h = \"stringEquals\", i = \"getAttr\", j = \"https://signin.{Region}.{PartitionResult#dualStackDnsSuffix}\", k = { [s]: \"Endpoint\" }, l = { \"fn\": i, \"argv\": [{ [s]: g }, \"name\"] }, m = { [s]: \"Region\" }, n = { [s]: g }, o = { \"authSchemes\": [{ \"name\": \"sigv4\", \"signingName\": \"signin\", \"signingRegion\": \"{Region}\" }] }, p = {}, q = [m];\nconst _data = {\n conditions: [\n [d, q],\n [e, [{ fn: f, argv: [{ [s]: \"IsControlPlane\" }, b] }, c]],\n [d, [k]],\n [\"aws.partition\", q, g],\n [e, [{ [s]: \"UseFIPS\" }, c]],\n [h, [l, \"aws\"]],\n [e, [{ fn: f, argv: [{ [s]: \"IsOAuthEndpoint\" }, b] }, c]],\n [e, [{ [s]: \"UseDualStack\" }, c]],\n [h, [l, \"aws-cn\"]],\n [h, [m, \"us-gov-west-1\"]],\n [h, [l, \"aws-us-gov\"]],\n [e, [{ fn: i, argv: [n, \"supportsFIPS\"] }, c]],\n [h, [l, \"aws-iso\"]],\n [h, [l, \"aws-iso-b\"]],\n [h, [l, \"aws-iso-f\"]],\n [h, [l, \"aws-iso-e\"]],\n [h, [l, \"aws-eusc\"]],\n [e, [{ fn: i, argv: [n, \"supportsDualStack\"] }, c]]\n ],\n results: [\n [a],\n [\"https://signin.{Region}.api.aws\", o],\n [\"https://signin.{Region}.api.amazonwebservices.com.cn\", o],\n [j, o],\n [a, \"FIPS endpoints are not supported for OAuth operations. Disable FIPS or use a non-OAuth operation.\"],\n [\"https://{Region}.oauth.signin.aws\", o],\n [\"https://{Region}.signin.aws.amazon.com\", p],\n [\"https://{Region}.signin.amazonaws.cn\", p],\n [\"https://{Region}.signin.amazonaws-us-gov.com\", p],\n [\"https://{Region}.signin.c2shome.ic.gov\", p],\n [\"https://{Region}.signin.sc2shome.sgov.gov\", p],\n [\"https://{Region}.signin.csphome.hci.ic.gov\", p],\n [\"https://{Region}.signin.csphome.adc-e.uk\", p],\n [\"https://{Region}.signin.amazonaws-eusc.eu\", p],\n [\"https://signin-fips.amazonaws-us-gov.com\", p],\n [\"https://{Region}.signin-fips.amazonaws-us-gov.com\", p],\n [\"https://{Region}.signin.{PartitionResult#dnsSuffix}\", p],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [k, p],\n [\"https://signin-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", p],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://signin-fips.{Region}.{PartitionResult#dnsSuffix}\", p],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [j, p],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://signin.{Region}.{PartitionResult#dnsSuffix}\", p],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 6, 3,\n 2, 36, 4,\n 4, 5, r + 27,\n 6, r + 4, r + 27,\n 1, 29, 7,\n 2, 36, 8,\n 3, 9, 31,\n 4, 22, 10,\n 5, 19, 11,\n 7, 21, 12,\n 8, r + 7, 13,\n 10, r + 8, 14,\n 12, r + 9, 15,\n 13, r + 10, 16,\n 14, r + 11, 17,\n 15, r + 12, 18,\n 16, r + 13, r + 16,\n 6, r + 5, 20,\n 7, 21, r + 6,\n 17, r + 24, r + 25,\n 6, r + 4, 23,\n 7, 27, 24,\n 9, r + 14, 25,\n 10, r + 15, 26,\n 11, r + 22, r + 23,\n 11, 28, r + 21,\n 17, r + 20, r + 21,\n 2, 35, 30,\n 3, 39, 31,\n 4, 32, r + 27,\n 6, r + 4, 33,\n 7, r + 27, 34,\n 9, r + 14, r + 27,\n 3, 39, 36,\n 4, 38, 37,\n 7, r + 18, r + 19,\n 6, r + 4, r + 17,\n 5, r + 1, 40,\n 8, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"IsControlPlane\", \"IsOAuthEndpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass SigninServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, SigninServiceException.prototype);\n }\n}\n\nclass AccessDeniedException extends SigninServiceException {\n name = \"AccessDeniedException\";\n $fault = \"client\";\n error;\n constructor(opts) {\n super({\n name: \"AccessDeniedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, AccessDeniedException.prototype);\n this.error = opts.error;\n }\n}\nclass InternalServerException extends SigninServiceException {\n name = \"InternalServerException\";\n $fault = \"server\";\n error;\n constructor(opts) {\n super({\n name: \"InternalServerException\",\n $fault: \"server\",\n ...opts,\n });\n Object.setPrototypeOf(this, InternalServerException.prototype);\n this.error = opts.error;\n }\n}\nclass TooManyRequestsError extends SigninServiceException {\n name = \"TooManyRequestsError\";\n $fault = \"client\";\n error;\n constructor(opts) {\n super({\n name: \"TooManyRequestsError\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, TooManyRequestsError.prototype);\n this.error = opts.error;\n }\n}\nclass ValidationException extends SigninServiceException {\n name = \"ValidationException\";\n $fault = \"client\";\n error;\n constructor(opts) {\n super({\n name: \"ValidationException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ValidationException.prototype);\n this.error = opts.error;\n }\n}\n\nconst _ADE = \"AccessDeniedException\";\nconst _AT = \"AccessToken\";\nconst _COAT = \"CreateOAuth2Token\";\nconst _COATR = \"CreateOAuth2TokenRequest\";\nconst _COATRB = \"CreateOAuth2TokenRequestBody\";\nconst _COATRBr = \"CreateOAuth2TokenResponseBody\";\nconst _COATRr = \"CreateOAuth2TokenResponse\";\nconst _COATWIAM = \"CreateOAuth2TokenWithIAM\";\nconst _COATWIAMR = \"CreateOAuth2TokenWithIAMRequest\";\nconst _COATWIAMRr = \"CreateOAuth2TokenWithIAMResponse\";\nconst _ISE = \"InternalServerException\";\nconst _OAAT = \"OAuthAccessToken\";\nconst _RT = \"RefreshToken\";\nconst _TMRE = \"TooManyRequestsError\";\nconst _VE = \"ValidationException\";\nconst _aKI = \"accessKeyId\";\nconst _aT = \"accessToken\";\nconst _at = \"access_token\";\nconst _c = \"client\";\nconst _cI = \"clientId\";\nconst _cV = \"codeVerifier\";\nconst _co = \"code\";\nconst _e = \"error\";\nconst _eI = \"expiresIn\";\nconst _ei = \"expires_in\";\nconst _gT = \"grantType\";\nconst _gt = \"grant_type\";\nconst _h = \"http\";\nconst _hE = \"httpError\";\nconst _iT = \"idToken\";\nconst _jN = \"jsonName\";\nconst _m = \"message\";\nconst _r = \"resource\";\nconst _rT = \"refreshToken\";\nconst _rU = \"redirectUri\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.signin\";\nconst _sAK = \"secretAccessKey\";\nconst _sT = \"sessionToken\";\nconst _se = \"server\";\nconst _tI = \"tokenInput\";\nconst _tO = \"tokenOutput\";\nconst _tT = \"tokenType\";\nconst _tt = \"token_type\";\nconst n0 = \"com.amazonaws.signin\";\nconst _s_registry = TypeRegistry.for(_s);\nvar SigninServiceException$ = [-3, _s, \"SigninServiceException\", 0, [], []];\n_s_registry.registerError(SigninServiceException$, SigninServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar AccessDeniedException$ = [-3, n0, _ADE,\n { [_e]: _c },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(AccessDeniedException$, AccessDeniedException);\nvar InternalServerException$ = [-3, n0, _ISE,\n { [_e]: _se, [_hE]: 500 },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(InternalServerException$, InternalServerException);\nvar TooManyRequestsError$ = [-3, n0, _TMRE,\n { [_e]: _c, [_hE]: 429 },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(TooManyRequestsError$, TooManyRequestsError);\nvar ValidationException$ = [-3, n0, _VE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _m],\n [0, 0], 2\n];\nn0_registry.registerError(ValidationException$, ValidationException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar OAuthAccessToken = [0, n0, _OAAT, 8, 0];\nvar RefreshToken = [0, n0, _RT, 8, 0];\nvar AccessToken$ = [3, n0, _AT,\n 8,\n [_aKI, _sAK, _sT],\n [[0, { [_jN]: _aKI }], [0, { [_jN]: _sAK }], [0, { [_jN]: _sT }]], 3\n];\nvar CreateOAuth2TokenRequest$ = [3, n0, _COATR,\n 0,\n [_tI],\n [[() => CreateOAuth2TokenRequestBody$, 16]], 1\n];\nvar CreateOAuth2TokenRequestBody$ = [3, n0, _COATRB,\n 0,\n [_cI, _gT, _co, _rU, _cV, _rT],\n [[0, { [_jN]: _cI }], [0, { [_jN]: _gT }], 0, [0, { [_jN]: _rU }], [0, { [_jN]: _cV }], [() => RefreshToken, { [_jN]: _rT }]], 2\n];\nvar CreateOAuth2TokenResponse$ = [3, n0, _COATRr,\n 0,\n [_tO],\n [[() => CreateOAuth2TokenResponseBody$, 16]], 1\n];\nvar CreateOAuth2TokenResponseBody$ = [3, n0, _COATRBr,\n 0,\n [_aT, _tT, _eI, _rT, _iT],\n [[() => AccessToken$, { [_jN]: _aT }], [0, { [_jN]: _tT }], [1, { [_jN]: _eI }], [() => RefreshToken, { [_jN]: _rT }], [0, { [_jN]: _iT }]], 4\n];\nvar CreateOAuth2TokenWithIAMRequest$ = [3, n0, _COATWIAMR,\n 0,\n [_gT, _r],\n [[0, { [_jN]: _gt }], 0], 2\n];\nvar CreateOAuth2TokenWithIAMResponse$ = [3, n0, _COATWIAMRr,\n 0,\n [_aT, _tT, _eI],\n [[() => OAuthAccessToken, { [_jN]: _at }], [0, { [_jN]: _tt }], [1, { [_jN]: _ei }]], 3\n];\nvar CreateOAuth2Token$ = [9, n0, _COAT,\n { [_h]: [\"POST\", \"/v1/token\", 200] }, () => CreateOAuth2TokenRequest$, () => CreateOAuth2TokenResponse$\n];\nvar CreateOAuth2TokenWithIAM$ = [9, n0, _COATWIAM,\n { [_h]: [\"POST\", \"/v1/token?x-amz-client-auth-method=iam\", 200] }, () => CreateOAuth2TokenWithIAMRequest$, () => CreateOAuth2TokenWithIAMResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2023-01-01\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSigninHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsRestJsonProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.signin\",\n errorTypeRegistries,\n version: \"2023-01-01\",\n serviceTarget: \"Signin\",\n },\n serviceId: config?.serviceId ?? \"Signin\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass SigninClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSigninHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"Signin\", \"SigninClient\", getEndpointPlugin);\nconst _ep0 = {\n IsControlPlane: { type: \"staticContextParams\", value: false },\n};\nconst _ep1 = {\n IsOAuthEndpoint: { type: \"staticContextParams\", value: true },\n};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass CreateOAuth2TokenCommand extends command(_ep0, _mw0, \"CreateOAuth2Token\", CreateOAuth2Token$) {\n}\n\nclass CreateOAuth2TokenWithIAMCommand extends command(_ep1, _mw0, \"CreateOAuth2TokenWithIAM\", CreateOAuth2TokenWithIAM$) {\n}\n\nconst commands = {\n CreateOAuth2TokenCommand,\n CreateOAuth2TokenWithIAMCommand,\n};\nclass Signin extends SigninClient {\n}\ncreateAggregatedClient(commands, Signin);\n\nconst OAuth2ErrorCode = {\n AUTHCODE_EXPIRED: \"AUTHCODE_EXPIRED\",\n CONFLICT: \"CONFLICT\",\n INSUFFICIENT_PERMISSIONS: \"INSUFFICIENT_PERMISSIONS\",\n INVALID_REQUEST: \"INVALID_REQUEST\",\n RESOURCE_NOT_FOUND: \"RESOURCE_NOT_FOUND\",\n SERVER_ERROR: \"server_error\",\n SERVICE_QUOTA_EXCEEDED: \"SERVICE_QUOTA_EXCEEDED\",\n TOKEN_EXPIRED: \"TOKEN_EXPIRED\",\n USER_CREDENTIALS_CHANGED: \"USER_CREDENTIALS_CHANGED\",\n};\n\nexports.AccessDeniedException = AccessDeniedException;\nexports.AccessDeniedException$ = AccessDeniedException$;\nexports.AccessToken$ = AccessToken$;\nexports.CreateOAuth2Token$ = CreateOAuth2Token$;\nexports.CreateOAuth2TokenCommand = CreateOAuth2TokenCommand;\nexports.CreateOAuth2TokenRequest$ = CreateOAuth2TokenRequest$;\nexports.CreateOAuth2TokenRequestBody$ = CreateOAuth2TokenRequestBody$;\nexports.CreateOAuth2TokenResponse$ = CreateOAuth2TokenResponse$;\nexports.CreateOAuth2TokenResponseBody$ = CreateOAuth2TokenResponseBody$;\nexports.CreateOAuth2TokenWithIAM$ = CreateOAuth2TokenWithIAM$;\nexports.CreateOAuth2TokenWithIAMCommand = CreateOAuth2TokenWithIAMCommand;\nexports.CreateOAuth2TokenWithIAMRequest$ = CreateOAuth2TokenWithIAMRequest$;\nexports.CreateOAuth2TokenWithIAMResponse$ = CreateOAuth2TokenWithIAMResponse$;\nexports.InternalServerException = InternalServerException;\nexports.InternalServerException$ = InternalServerException$;\nexports.OAuth2ErrorCode = OAuth2ErrorCode;\nexports.Signin = Signin;\nexports.SigninClient = SigninClient;\nexports.SigninServiceException = SigninServiceException;\nexports.SigninServiceException$ = SigninServiceException$;\nexports.TooManyRequestsError = TooManyRequestsError;\nexports.TooManyRequestsError$ = TooManyRequestsError$;\nexports.ValidationException = ValidationException;\nexports.ValidationException$ = ValidationException$;\nexports.errorTypeRegistries = errorTypeRegistries;\n" | ||
| ], | ||
| "mappings": ";wXAAA,IAAQ,wBAAsB,gCAAiC,GAAmC,kCAAgC,8BAA4B,sCAAoC,0CAAwC,0BAAwB,2BAAyB,sBAAoB,uBAAqB,mBAAiB,sCAC7U,gBAAc,0CAAwC,iCAA+B,+BACrF,qBAAmB,oBAAkB,oBAAkB,cAAY,mCAAiC,6BAA2B,oCAAkC,+BAA6B,UAAQ,eAAa,iCACnN,QAAS,SACjB,IAAQ,GAAW,GACX,GAAW,GACnB,IAAQ,6BAA2B,aAAY,yCAAuC,8CAA4C,8BAA4B,mCAAiC,8BACvL,yBAAuB,iBAAe,kBAAgB,2BAAyB,yBAAuB,4BACtG,YAAU,wCAAsC,mCAAiC,iCACjF,sBAAoB,kCAAgC,mCAAiC,sBAAoB,yBACzG,gBAAc,+BACd,4BAA0B,qBAAmB,8CAC7C,UAAQ,YAAU,YAAU,cAAY,8BACxC,mBAAiB,0BACjB,8BACA,gBAEF,GAAgD,MAAO,EAAQ,EAAS,KACnE,CACH,UAAW,GAAiB,CAAO,EAAE,UACrC,OAAQ,MAAM,GAAkB,EAAO,MAAM,EAAE,IAAM,IAAM,CACvD,MAAU,MAAM,yDAAyD,IAC1E,CACP,GAEJ,SAAS,EAAgC,CAAC,EAAgB,CACtD,MAAO,CACH,SAAU,iBACV,kBAAmB,CACf,KAAM,SACN,OAAQ,EAAe,MAC3B,EACA,oBAAqB,CAAC,EAAQ,KAAa,CACvC,kBAAmB,CACf,SACA,SAC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,gBAAiB,kBACjB,mBAAoB,qBACpB,aAAc,eACd,uBAAwB,yBACxB,cAAe,gBACf,yBAA0B,0BAC9B,EAEA,IAAQ,GAAwB,EACxB,GAAyB,GACzB,GAAe,GACf,GAAqB,GACrB,GAA2B,EAC3B,GAA4B,GAC5B,GAAgC,GAChC,GAA6B,GAC7B,GAAiC,GACjC,GAA4B,GAC5B,GAAkC,EAClC,GAAmC,GACnC,GAAoC,GACpC,GAA0B,EAC1B,GAA2B,GAC3B,GAAkB,GAClB,GAAS,EACT,GAAe,EACf,GAAyB,EACzB,GAA0B,GAC1B,GAAuB,EACvB,GAAwB,GACxB,GAAsB,EACtB,GAAuB,GACvB,GAAsB", | ||
| "debugId": "0731FF42F65B395F64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/get.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.get,\n Effect.fn(\"cli.service.get\")(function* (input) {\n process.stdout.write(\n (yield* ServiceConfig.get(Option.getOrUndefined(input.key), Option.getOrUndefined(input.name))) + EOL,\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";i5BAAA,cAAS,WAMT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,IACnC,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAAO,CAC7C,QAAQ,OAAO,OACZ,MAAO,EAAc,IAAI,EAAO,eAAe,EAAM,GAAG,EAAG,EAAO,eAAe,EAAM,IAAI,CAAC,GAAK,CACpG,EACD,CACH", | ||
| "debugId": "7573124546E7E74864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/stop.ts"], | ||
| "sourcesContent": [ | ||
| "import { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { ServerConnection } from \"../../../services/server-connection\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.stop,\n Effect.fn(\"cli.service.stop\")(function* () {\n const options = yield* ServiceConfig.options()\n yield* ServerConnection.shutdownPersistentPty(options).pipe(Effect.ignore)\n yield* Service.stop(options)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+jCAOA,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,KACnC,EAAO,GAAG,kBAAkB,EAAE,SAAU,EAAG,CACzC,IAAM,EAAU,MAAO,EAAc,QAAQ,EAC7C,MAAO,EAAiB,sBAAsB,CAAO,EAAE,KAAK,EAAO,MAAM,EACzE,MAAO,EAAQ,KAAK,CAAO,EAC5B,CACH", | ||
| "debugId": "ADFAD48B99B7B60764756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/run/run.ts", "src/run/noninteractive.ts", "src/run/ui.ts"], | ||
| "sourcesContent": [ | ||
| "import { Service, type Endpoint } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode, type OpenCodeClient, type SessionMessageAssistantTool } from \"@opencode-ai/client/promise\"\nimport { FSUtil } from \"@opencode-ai/util/fs-util\"\nimport { open } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { readStdin } from \"../util/io\"\nimport { ServerConnection } from \"../services/server-connection\"\nimport { parseSessionTargetModel, resolveSessionTarget } from \"../session-target\"\nimport { toolInlineInfo } from \"@opencode-ai/tui/mini/tool\"\nimport { runNonInteractivePrompt } from \"./noninteractive\"\nimport { UI } from \"./ui\"\nimport { Env } from \"../env\"\nimport { errorMessage } from \"../util/error\"\n\nexport type RunCommandInput = {\n server: ServerConnection.Resolved\n message: string[]\n continue?: boolean\n session?: string\n fork?: boolean\n model?: string\n agent?: string\n format: \"default\" | \"json\"\n file: string[]\n title?: string\n thinking?: boolean\n auto?: boolean\n}\n\ntype FilePart = {\n url: string\n filename: string\n mime: string\n}\n\ntype Prepared = {\n directory?: string\n message: string\n files: FilePart[]\n}\n\ntype ExecutionOptions = {\n root?: string\n directory?: string\n useServerDirectory?: boolean\n variant?: string\n attached?: boolean\n compatibility?: \"v1\"\n}\n\nclass RunTargetError extends Error {\n constructor(\n message: string,\n readonly sessionID?: string,\n ) {\n super(message)\n }\n}\n\nconst ATTACH_FILE_MAX_BYTES = 10 * 1024 * 1024\n\nexport function runNonInteractive(input: RunCommandInput) {\n return runNonInteractiveWithOptions(input, {})\n}\n\n/** @internal Used only by the V1 command boundary. */\nexport function runNonInteractiveWithOptions(input: RunCommandInput, options: ExecutionOptions) {\n return run(input, options).catch((error) => reportRunError(input, errorMessage(error)))\n}\n\nasync function run(input: RunCommandInput, options: ExecutionOptions) {\n if (input.fork && !input.continue && !input.session) fail(\"--fork requires --continue or --session\")\n const root = options.root ?? process.env.PWD ?? process.cwd()\n const local = localDirectory(root)\n const directory = options.useServerDirectory ? undefined : (options.directory ?? local)\n const message = mergeInput(formatMessage(input.message), process.stdin.isTTY ? undefined : await readStdin())\n if (!message?.trim()) fail(\"You must provide a message\")\n const files = await Promise.all(input.file.map((file) => prepareFile(file, root, options)))\n const prepared = { directory, message, files }\n return execute(input, prepared, input.server.endpoint, options)\n}\n\nasync function execute(input: RunCommandInput, prepared: Prepared, endpoint: Endpoint, options: ExecutionOptions) {\n const client = OpenCode.make({\n baseUrl: endpoint.url,\n headers: Service.headers(endpoint),\n // Bun's default five-minute deadline terminates the event stream used by long-running sessions.\n fetch: ((request: RequestInfo | URL, init?: RequestInit) =>\n fetch(request, { ...init, timeout: false } as BunFetchRequestInit)) as typeof fetch,\n })\n const explicit = parseRunModel(input.model)\n const target = await resolveSessionTarget({\n client,\n location: prepared.directory ? { directory: prepared.directory } : undefined,\n continue: input.continue,\n session: input.session,\n fork: input.fork,\n model: explicit\n ? { providerID: explicit.model.providerID, id: explicit.model.modelID, variant: explicit.variant }\n : undefined,\n agent: input.agent,\n environment: input.server.service ? Env.session() : undefined,\n prepare: async (next) => {\n const selected =\n next.model ??\n (options.variant\n ? await client.model\n .default({ location: { directory: next.location.directory, workspace: next.location.workspaceID } })\n .then((result) => result.data)\n : undefined)\n const model = selected\n ? {\n providerID: selected.providerID,\n id: selected.id,\n variant: options.variant ?? (\"variant\" in selected ? selected.variant : undefined),\n }\n : undefined\n if ((options.variant ?? explicit?.variant) && !model)\n throw new RunTargetError(\"Cannot select a variant before selecting a model\", next.session?.id)\n return { model, agent: next.agent }\n },\n }).catch((error) => {\n if (!(error instanceof RunTargetError)) throw error\n reportRunError(input, error.message, error.sessionID)\n return undefined\n })\n if (!target) return\n const model = target.model ? { providerID: target.model.providerID, modelID: target.model.id } : undefined\n const variant = target.model?.variant\n if (!target.resume && input.title !== undefined) {\n await client.session.rename({\n sessionID: target.session.id,\n title: input.title || prepared.message.slice(0, 50) + (prepared.message.length > 50 ? \"...\" : \"\"),\n })\n }\n\n await runNonInteractivePrompt({\n client,\n sessionID: target.session.id,\n location: target.location,\n message: prepared.message,\n files: prepared.files,\n agent: target.agent,\n model,\n variant,\n thinking: input.thinking ?? false,\n format: input.format,\n auto: input.auto ?? false,\n attached: options.attached ?? true,\n compatibility: options.compatibility,\n renderTool: (part) => renderTool(part, target.location.directory),\n renderToolError: (part) => renderToolError(part, target.location.directory),\n }).catch((error) => reportRunError(input, errorMessage(error), target.session.id))\n}\n\nexport function mergeInput(message: string | undefined, piped: string | undefined) {\n if (!message) return piped || undefined\n if (!piped) return message\n return message + \"\\n\" + piped\n}\n\nfunction formatMessage(message: string[]) {\n const value = message.map((part) => (part.includes(\" \") ? `\"${part.replace(/\"/g, '\\\\\"')}\"` : part)).join(\" \")\n return value || undefined\n}\n\nfunction localDirectory(root: string) {\n try {\n process.chdir(root)\n return process.cwd()\n } catch {\n fail(`Failed to change directory to ${root}`)\n }\n}\n\nexport function parseRunModel(value?: string) {\n const ref = parseSessionTargetModel(value)\n if (!ref) return\n return {\n model: { providerID: ref.providerID, modelID: ref.id },\n variant: ref.variant,\n }\n}\n\nasync function prepareFile(input: string, directory: string, options: ExecutionOptions): Promise<FilePart> {\n const file = path.resolve(directory, input)\n const handle = await open(file, \"r\").catch(() => fail(`File not found: ${input}`))\n try {\n const stat = await handle.stat()\n if (options.compatibility === \"v1\" && options.attached && stat.isDirectory())\n fail(`Cannot attach local directory without a shared filesystem: ${input}`)\n if (!stat.isFile() || stat.size > ATTACH_FILE_MAX_BYTES)\n fail(`Cannot attach a directory, special file, or file larger than 10 MiB: ${input}`)\n const content = Buffer.alloc(Number(stat.size))\n let offset = 0\n while (offset < content.length) {\n const read = await handle.read(content, offset, content.length - offset, offset)\n if (read.bytesRead === 0) break\n offset += read.bytesRead\n }\n const bytes = content.subarray(0, offset)\n const detected = FSUtil.mimeType(file)\n const text = bytes.toString(\"utf8\")\n const mime =\n detected.startsWith(\"image/\") || detected === \"application/pdf\"\n ? detected\n : !isBinaryContent(bytes) && Buffer.from(text, \"utf8\").equals(bytes)\n ? \"text/plain\"\n : detected\n return {\n url: `data:${mime};base64,${bytes.toString(\"base64\")}`,\n filename: path.basename(file),\n mime,\n }\n } finally {\n await handle.close()\n }\n}\n\nfunction isBinaryContent(bytes: Uint8Array) {\n if (bytes.length === 0) return false\n if (bytes.includes(0)) return true\n return bytes.reduce((count, byte) => count + Number(byte < 9 || (byte > 13 && byte < 32)), 0) / bytes.length > 0.3\n}\n\nasync function renderTool(part: SessionMessageAssistantTool, directory: string) {\n const info = toolInlineInfo(part, directory)\n if (info.mode === \"block\") {\n UI.empty()\n UI.println(UI.Style.TEXT_NORMAL + info.icon, UI.Style.TEXT_NORMAL + info.title)\n if (info.body?.trim()) UI.println(info.body)\n UI.empty()\n return\n }\n UI.println(\n UI.Style.TEXT_NORMAL + info.icon,\n UI.Style.TEXT_NORMAL + info.title,\n info.description ? UI.Style.TEXT_DIM + info.description + UI.Style.TEXT_NORMAL : \"\",\n )\n}\n\nasync function renderToolError(part: SessionMessageAssistantTool, directory: string) {\n const info = toolInlineInfo(part, directory)\n UI.println(UI.Style.TEXT_NORMAL + \"✗\", UI.Style.TEXT_NORMAL + `${info.title} failed`)\n}\n\n/** @internal Used by the V1 command boundary before a Session exists. */\nexport function reportRunError(input: Pick<RunCommandInput, \"format\">, message: string, sessionID?: string) {\n process.exitCode = 1\n if (input.format === \"json\") {\n process.stdout.write(\n JSON.stringify({\n type: \"error\",\n timestamp: Date.now(),\n sessionID: sessionID ?? \"\",\n error: { type: \"unknown\", message },\n }) + \"\\n\",\n )\n return\n }\n UI.error(message)\n}\n\nfunction fail(message: string): never {\n throw new Error(message)\n}\n", | ||
| "import type {\n EventSubscribeOutput,\n JsonValue,\n LocationRef,\n OpenCodeClient,\n SessionMessageAssistantTool,\n SessionMessageInfo,\n ToolContent,\n} from \"@opencode-ai/client/promise\"\nimport { SessionMessage } from \"@opencode-ai/schema/session-message\"\nimport { EOL } from \"node:os\"\nimport { readFile } from \"node:fs/promises\"\nimport { nonEmptyToolContent, toolOutputText, type MiniToolPart } from \"@opencode-ai/tui/mini/tool\"\nimport { UI } from \"./ui\"\n\ntype Model = {\n providerID: string\n modelID: string\n}\n\ntype File = {\n url: string\n filename: string\n mime: string\n}\n\ntype Input = {\n client: OpenCodeClient\n sessionID: string\n location: LocationRef\n message: string\n files: File[]\n agent?: string\n model?: Model\n variant?: string\n thinking: boolean\n format: \"default\" | \"json\"\n auto: boolean\n /** True when the client is attached to a shared server rather than an exclusive in-process one. */\n attached: boolean\n compatibility?: \"v1\"\n renderTool: (part: SessionMessageAssistantTool) => Promise<void>\n renderToolError: (part: SessionMessageAssistantTool) => Promise<void>\n}\n\ntype StartedPart = {\n id: string\n timestamp: number\n}\n\ntype ToolState = StartedPart & {\n assistantMessageID: string\n tool: string\n input: Record<string, JsonValue>\n raw?: string\n provider?: unknown\n providerState?: SessionMessageAssistantTool[\"providerState\"]\n metadata: Record<string, JsonValue>\n content: ToolContent[]\n}\n\ntype V2Event = EventSubscribeOutput\ntype FormRequest = Extract<V2Event, { type: \"form.created\" }>[\"data\"][\"form\"]\n\n// MCP elicitations are temporarily owned by the \"global\" sentinel instead of a real\n// session. An exclusive local process may treat them as this run's blockers; an\n// attached client must not cancel input that may belong to another session.\nconst GLOBAL_FORM_SESSION_ID = \"global\"\n\nexport async function runNonInteractivePrompt(input: Input) {\n const controller = new AbortController()\n const stream = input.client.event.subscribe({ signal: controller.signal })[Symbol.asyncIterator]()\n const connected = await stream.next()\n if (connected.done) throw new Error(\"Event stream disconnected before prompt admission\")\n\n const messageID = SessionMessage.ID.create()\n const starts = new Map<string, StartedPart>()\n const tools = new Map<string, ToolState>()\n const renderedText = new Map<string, string>()\n const renderedReasoning = new Map<string, string>()\n const renderedTools = new Set<string>()\n let submitted = false\n let promoted = false\n let emittedError = false\n let permissionRejected = false\n let formCancelled = false\n let interrupted = false\n let v1InvalidOutput = false\n let prePromotionError: { message: string; [key: string]: unknown } | undefined\n let finalizing = false\n let admission: AbortController | undefined\n let pendingStep: { timestamp: number; part: Record<string, unknown>; label: string } | undefined\n\n const emit = (type: string, timestamp: number, data: Record<string, unknown>) => {\n if (input.format !== \"json\") return false\n process.stdout.write(JSON.stringify({ type, timestamp, sessionID: input.sessionID, ...data }) + EOL)\n return true\n }\n\n const writeText = (part: { text: string; [key: string]: unknown }, timestamp: number) => {\n if (emit(\"text\", timestamp, { part })) return\n const text = part.text.trim()\n if (!text) return\n if (!process.stdout.isTTY) {\n process.stdout.write(text + EOL)\n return\n }\n UI.empty()\n UI.println(text)\n UI.empty()\n }\n\n const writeReasoning = (part: { text: string; [key: string]: unknown }, timestamp: number) => {\n if (emit(\"reasoning\", timestamp, { part })) return\n const text = part.text.trim()\n if (!text) return\n const line = `Thinking: ${text}`\n if (!process.stdout.isTTY) return void process.stdout.write(line + EOL)\n UI.empty()\n UI.println(`${UI.Style.TEXT_DIM}\\u001b[3m${line}\\u001b[0m${UI.Style.TEXT_NORMAL}`)\n UI.empty()\n }\n\n const flushStep = () => {\n if (!pendingStep) return\n const value = pendingStep\n pendingStep = undefined\n if (!emit(\"step_start\", value.timestamp, { part: value.part }) && input.format !== \"json\") {\n UI.empty()\n UI.println(value.label)\n UI.empty()\n }\n }\n\n const replyPermission = async (request: { id: string; action: string; resources: ReadonlyArray<string> }) => {\n if (!input.auto) {\n permissionRejected = true\n UI.println(\n UI.Style.TEXT_WARNING_BOLD + \"!\",\n UI.Style.TEXT_NORMAL +\n `permission requested: ${request.action} (${request.resources.join(\", \")}); auto-rejecting`,\n )\n }\n await input.client.permission\n .reply({\n sessionID: input.sessionID,\n requestID: request.id,\n reply: input.auto ? \"once\" : \"reject\",\n })\n .catch(() => {})\n if (!input.auto) {\n await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n }\n }\n\n const cancelForm = async (request: Pick<FormRequest, \"id\" | \"sessionID\">) => {\n try {\n await input.client.form.cancel(\n { sessionID: request.sessionID, formID: request.id },\n ...formRequestOptions(request.sessionID === GLOBAL_FORM_SESSION_ID ? input.location : undefined),\n )\n } catch (error) {\n if (!formAlreadySettled(error)) throw error\n }\n formCancelled = true\n }\n\n const consume = async () => {\n while (!controller.signal.aborted) {\n const next = await stream.next().catch((error) => {\n if (!emittedError) throw error\n return { done: true as const, value: undefined }\n })\n if (next.done) {\n if (emittedError) return\n throw new Error(\"Event stream disconnected during prompt execution\")\n }\n const event = next.value\n\n if (event.type === \"permission.asked\" && submitted && event.data.sessionID === input.sessionID) {\n await replyPermission(event.data)\n continue\n }\n if (\n event.type === \"form.created\" &&\n submitted &&\n (event.data.form.sessionID === input.sessionID ||\n (!input.attached &&\n event.data.form.sessionID === GLOBAL_FORM_SESSION_ID &&\n sameLocation(event.location, input.location)))\n ) {\n await cancelForm(event.data.form)\n continue\n }\n if (!(\"sessionID\" in event.data) || event.data.sessionID !== input.sessionID) continue\n const time = toMillis(\"created\" in event ? event.created : undefined)\n\n if (event.type === \"session.inbox.delivered\") {\n if (event.data.inboxID === messageID) {\n promoted = true\n prePromotionError = undefined\n continue\n }\n }\n if (\n event.type === \"session.execution.interrupted\" &&\n event.data.reason === \"user\" &&\n (interrupted || permissionRejected || formCancelled)\n ) {\n return\n }\n if (!promoted && event.type === \"session.execution.failed\") {\n prePromotionError = event.data.error\n if (finalizing) return\n continue\n }\n if (\n !promoted &&\n finalizing &&\n (event.type === \"session.execution.succeeded\" || event.type === \"session.execution.interrupted\")\n )\n return\n if (!promoted) continue\n if (finalizing && !event.type.startsWith(\"session.execution.\")) continue\n\n if (event.type === \"session.step.started\") {\n const part = {\n id: partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"step-start\",\n snapshot: event.data.snapshot,\n }\n if (input.compatibility === \"v1\") {\n pendingStep = {\n timestamp: time,\n part,\n label: `> ${event.data.agent} · ${event.data.model.id}`,\n }\n continue\n }\n if (!emit(\"step_start\", time, { part }) && input.format !== \"json\") {\n UI.empty()\n UI.println(`> ${event.data.agent} · ${event.data.model.id}`)\n UI.empty()\n }\n continue\n }\n\n if (event.type === \"session.text.started\") {\n flushStep()\n starts.set(`text\\u0000${contentKey(event.data.assistantMessageID, event.data.ordinal)}`, {\n id: partID(event.id),\n timestamp: time,\n })\n continue\n }\n if (event.type === \"session.text.ended\") {\n const key = contentKey(event.data.assistantMessageID, event.data.ordinal)\n const started = starts.get(`text\\u0000${key}`)\n starts.delete(`text\\u0000${key}`)\n const part = {\n id: started?.id ?? partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"text\",\n text: event.data.text,\n time: { start: started?.timestamp ?? time, end: time },\n }\n renderedText.set(key, event.data.text)\n writeText(part, time)\n continue\n }\n\n if (event.type === \"session.reasoning.started\") {\n flushStep()\n starts.set(`reasoning\\u0000${contentKey(event.data.assistantMessageID, event.data.ordinal)}`, {\n id: partID(event.id),\n timestamp: time,\n })\n continue\n }\n if (event.type === \"session.reasoning.ended\" && input.thinking) {\n const key = contentKey(event.data.assistantMessageID, event.data.ordinal)\n const started = starts.get(`reasoning\\u0000${key}`)\n starts.delete(`reasoning\\u0000${key}`)\n const part = {\n id: started?.id ?? partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"reasoning\",\n text: event.data.text,\n metadata: event.data.state,\n time: { start: started?.timestamp ?? time, end: time },\n }\n renderedReasoning.set(key, event.data.text)\n writeReasoning(part, time)\n continue\n }\n\n if (event.type === \"session.tool.input.started\") {\n flushStep()\n tools.set(toolKey(event.data.assistantMessageID, event.data.id), {\n id: partID(event.id),\n timestamp: time,\n assistantMessageID: event.data.assistantMessageID,\n tool: event.data.name,\n input: {},\n metadata: {},\n content: [],\n })\n continue\n }\n if (event.type === \"session.tool.input.ended\") {\n const current = tools.get(toolKey(event.data.assistantMessageID, event.data.id))\n if (current) current.raw = event.data.text\n continue\n }\n if (event.type === \"session.tool.input.delta\") {\n const current = tools.get(toolKey(event.data.assistantMessageID, event.data.id))\n if (current) current.raw = (current.raw ?? \"\") + event.data.delta\n continue\n }\n if (event.type === \"session.tool.called\") {\n flushStep()\n const key = toolKey(event.data.assistantMessageID, event.data.id)\n const current = tools.get(key)\n tools.set(key, {\n id: current?.id ?? partID(event.id),\n timestamp: current?.timestamp ?? time,\n assistantMessageID: event.data.assistantMessageID,\n tool: current?.tool ?? \"tool\",\n input: event.data.input,\n raw: current?.raw,\n provider: { executed: event.data.executed, state: event.data.state },\n providerState: event.data.state,\n metadata: {},\n content: [],\n })\n continue\n }\n if (event.type === \"session.tool.progress\") {\n const current = tools.get(toolKey(event.data.assistantMessageID, event.data.id))\n if (current) {\n current.metadata = event.data.metadata\n }\n continue\n }\n if (event.type === \"session.tool.success\") {\n const key = toolKey(event.data.assistantMessageID, event.data.id)\n const current = tools.get(key) ?? fallbackTool(event)\n const tool: SessionMessageAssistantTool = {\n type: \"tool\",\n id: event.data.id,\n name: current.tool,\n executed: event.data.executed,\n providerState: current.providerState,\n providerResultState: event.data.resultState,\n state: {\n status: \"completed\",\n input: current.input,\n metadata: event.data.metadata,\n content: event.data.content,\n },\n time: { created: current.timestamp, ran: current.timestamp, completed: time },\n }\n const part: MiniToolPart = {\n partID: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n id: event.data.id,\n tool: current.tool,\n state: {\n status: \"completed\",\n input: current.input,\n output: toolOutputText(current.tool, event.data.content),\n title: current.tool,\n metadata: {\n metadata: event.data.metadata,\n content: event.data.content,\n providerCall: current.provider,\n providerResult: { executed: event.data.executed, state: event.data.resultState },\n rawInput: current.raw,\n },\n time: { start: current.timestamp, end: time },\n },\n }\n tools.delete(key)\n renderedTools.add(key)\n if (!emit(\"tool_use\", time, { part })) await input.renderTool(tool)\n continue\n }\n if (event.type === \"session.tool.failed\") {\n const key = toolKey(event.data.assistantMessageID, event.data.id)\n const current = tools.get(key) ?? fallbackTool(event)\n const error = event.data.error.message\n const metadata = event.data.metadata ?? current.metadata\n const content = event.data.content ?? nonEmptyToolContent(current.content)\n const tool: SessionMessageAssistantTool = {\n type: \"tool\",\n id: event.data.id,\n name: current.tool,\n executed: event.data.executed,\n providerState: current.providerState,\n providerResultState: event.data.resultState,\n state: {\n status: \"error\",\n input: current.input,\n metadata,\n content,\n error: event.data.error,\n },\n time: { created: current.timestamp, ran: current.timestamp, completed: time },\n }\n const part: MiniToolPart = {\n partID: current.id,\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"tool\",\n id: event.data.id,\n tool: current.tool,\n state: {\n status: \"error\",\n input: current.input,\n error,\n metadata: {\n providerCall: current.provider,\n providerResult: { executed: event.data.executed, state: event.data.resultState },\n rawInput: current.raw,\n },\n time: { start: current.timestamp, end: time },\n },\n }\n tools.delete(key)\n renderedTools.add(key)\n if (input.compatibility === \"v1\" && (permissionRejected || formCancelled)) continue\n if (!emit(\"tool_use\", time, { part })) {\n if (content && toolOutputText(current.tool, content).trim())\n await input.renderTool({\n ...tool,\n state: {\n status: \"completed\",\n input: current.input,\n metadata,\n content,\n },\n })\n await input.renderToolError(tool)\n UI.error(error)\n }\n continue\n }\n\n if (event.type === \"session.step.ended\") {\n flushStep()\n const part = {\n id: partID(event.id),\n sessionID: input.sessionID,\n messageID: event.data.assistantMessageID,\n type: \"step-finish\",\n reason: event.data.finish,\n snapshot: event.data.snapshot,\n cost: event.data.cost,\n tokens: event.data.tokens,\n }\n emit(\"step_finish\", time, { part })\n continue\n }\n if (event.type === \"session.step.failed\") {\n if (input.compatibility === \"v1\" && event.data.error.message === \"The provider response ended unexpectedly.\") {\n pendingStep = undefined\n v1InvalidOutput = true\n continue\n }\n if (interrupted || permissionRejected || formCancelled) continue\n flushStep()\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", time, { error: event.data.error })) UI.error(event.data.error.message)\n continue\n }\n if (event.type === \"session.execution.failed\") {\n if (input.compatibility === \"v1\" && (v1InvalidOutput || permissionRejected || formCancelled)) return\n flushStep()\n if (!emittedError && !formCancelled) {\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", time, { error: event.data.error })) UI.error(event.data.error.message)\n }\n return\n }\n if (event.type === \"session.execution.interrupted\") {\n if (input.compatibility === \"v1\" && (permissionRejected || formCancelled)) return\n if (event.data.reason === \"user\" && interrupted) process.exitCode = 130\n if (event.data.reason !== \"user\" && !emittedError) {\n emittedError = true\n process.exitCode = 1\n const error = { type: \"aborted\" as const, message: `Session interrupted: ${event.data.reason}` }\n if (!emit(\"error\", time, { error })) UI.error(error.message)\n }\n return\n }\n if (event.type === \"session.execution.succeeded\") return\n }\n }\n\n const projectedMessages = async () => {\n const messages: SessionMessageInfo[] = []\n let cursor: string | undefined\n while (true) {\n const page = await input.client.message.list(\n cursor\n ? { sessionID: input.sessionID, limit: 200, cursor }\n : { sessionID: input.sessionID, limit: 200, order: \"desc\" },\n )\n for (const message of page.data) {\n if (message.id === messageID) return { found: true, messages: messages.toReversed() }\n messages.push(message)\n }\n cursor = page.cursor.next ?? undefined\n if (!cursor) return { found: false, messages: [] }\n }\n }\n\n const reconcile = async () => {\n const projected = await projectedMessages()\n for (const message of projected.messages) {\n if (message.type !== \"assistant\") continue\n const timestamp = message.time.completed ?? message.time.created\n let textOrdinal = 0\n let reasoningOrdinal = 0\n for (const item of message.content) {\n if (item.type === \"text\") {\n const ordinal = textOrdinal++\n const key = contentKey(message.id, ordinal)\n const rendered = renderedText.get(key) ?? \"\"\n if (rendered === item.text || !item.text.startsWith(rendered)) continue\n const text = item.text.slice(rendered.length)\n writeText(\n {\n id: projectedPartID(message.id, `text-${ordinal}`),\n sessionID: input.sessionID,\n messageID: message.id,\n type: \"text\",\n text,\n time: { start: message.time.created, end: timestamp },\n },\n timestamp,\n )\n renderedText.set(key, item.text)\n continue\n }\n if (item.type === \"reasoning\") {\n const ordinal = reasoningOrdinal++\n if (!input.thinking) continue\n const key = contentKey(message.id, ordinal)\n const rendered = renderedReasoning.get(key) ?? \"\"\n if (rendered === item.text || !item.text.startsWith(rendered)) continue\n const text = item.text.slice(rendered.length)\n const part = {\n id: projectedPartID(message.id, `reasoning-${ordinal}`),\n sessionID: input.sessionID,\n messageID: message.id,\n type: \"reasoning\",\n text,\n metadata: item.state,\n time: { start: message.time.created, end: timestamp },\n }\n renderedReasoning.set(key, item.text)\n writeReasoning(part, timestamp)\n continue\n }\n\n const key = toolKey(message.id, item.id)\n if (renderedTools.has(key) || item.state.status === \"streaming\" || item.state.status === \"running\") continue\n const part: MiniToolPart = {\n partID: projectedPartID(message.id, `tool-${item.id}`),\n sessionID: input.sessionID,\n messageID: message.id,\n type: \"tool\",\n id: item.id,\n tool: item.name,\n state:\n item.state.status === \"completed\"\n ? {\n status: \"completed\",\n input: item.state.input,\n output: toolOutputText(item.name, item.state.content),\n title: item.name,\n metadata: { metadata: item.state.metadata, content: item.state.content },\n time: { start: item.time.ran ?? item.time.created, end: item.time.completed ?? timestamp },\n }\n : {\n status: \"error\",\n input: item.state.input,\n error: item.state.error.message,\n metadata: { metadata: item.state.metadata, content: item.state.content },\n time: { start: item.time.ran ?? item.time.created, end: item.time.completed ?? timestamp },\n },\n }\n renderedTools.add(key)\n if (emit(\"tool_use\", timestamp, { part })) continue\n if (item.state.status === \"completed\") {\n await input.renderTool(item)\n continue\n }\n if (item.state.content && toolOutputText(item.name, item.state.content).trim()) {\n await input.renderTool({\n ...item,\n state: {\n status: \"completed\",\n input: item.state.input,\n metadata: item.state.metadata,\n content: item.state.content,\n },\n })\n }\n await input.renderToolError(item)\n UI.error(item.state.error.message)\n }\n\n if (message.error && !emittedError) {\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", timestamp, { error: message.error })) UI.error(message.error.message)\n }\n }\n return {\n found: projected.found,\n responded: projected.messages.some((message) => message.type === \"assistant\"),\n }\n }\n\n const interrupt = () => {\n if (interrupted) process.exit(130)\n interrupted = true\n process.exitCode = 130\n admission?.abort()\n void input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n }\n process.on(\"SIGINT\", interrupt)\n\n let completed: Promise<void> | undefined\n try {\n if (input.agent) {\n await input.client.session.switchAgent({ sessionID: input.sessionID, agent: input.agent })\n }\n const selected = input.model\n ? { providerID: input.model.providerID, id: input.model.modelID, variant: input.variant }\n : input.variant\n ? await input.client.session\n .get({ sessionID: input.sessionID })\n .then((result) => result.model)\n .then(async (model) => {\n if (model) return { ...model, variant: input.variant }\n const result = await input.client.model.default()\n const fallback = result.data\n return fallback ? { providerID: fallback.providerID, id: fallback.id, variant: input.variant } : undefined\n })\n : undefined\n if (input.variant && !selected) throw new Error(\"Cannot select a variant before selecting a model\")\n if (selected) {\n await input.client.session.switchModel({ sessionID: input.sessionID, model: selected })\n }\n\n const prepared = await Promise.all(input.files.map(prepareFile))\n if (interrupted) return\n submitted = true\n completed = consume()\n admission = new AbortController()\n const response = await input.client.session\n .prompt(\n {\n sessionID: input.sessionID,\n id: messageID,\n text: [input.message, ...prepared.flatMap((file) => (file.text ? [file.text] : []))].join(\"\\n\\n\"),\n files: prepared.flatMap((file) => (file.attachment ? [file.attachment] : [])),\n delivery: \"steer\",\n },\n { signal: admission.signal },\n )\n .catch(async (error) => {\n if (interrupted) {\n await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n }\n controller.abort()\n await completed?.catch(() => {})\n if (interrupted || emittedError) return undefined\n throw error\n })\n admission = undefined\n if (!response) return\n if (interrupted) await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})\n\n const [permissions, forms, globals] = await Promise.all([\n input.client.permission.list({ sessionID: input.sessionID }).catch(() => undefined),\n input.client.form.list({ sessionID: input.sessionID }).catch(() => undefined),\n input.attached\n ? Promise.resolve(undefined)\n : input.client.form.request\n .list({\n location: { directory: input.location.directory, workspace: input.location.workspaceID },\n })\n .catch(() => undefined),\n ])\n await Promise.all([\n ...(permissions ?? []).map(replyPermission),\n ...(forms ?? []).map(cancelForm),\n ...(globals && sameLocation(globals.location, input.location)\n ? globals.data.filter((form) => form.sessionID === GLOBAL_FORM_SESSION_ID).map(cancelForm)\n : []),\n ])\n if (input.compatibility === \"v1\") {\n await completed\n return\n }\n\n const waiting = input.client.session.wait({ sessionID: input.sessionID })\n await Promise.race([waiting, completed.then(() => waiting)])\n finalizing = true\n const projected = await reconcile()\n if (\n !projected.responded &&\n !interrupted &&\n !permissionRejected &&\n !formCancelled &&\n !emittedError &&\n !prePromotionError\n ) {\n await completed\n }\n if (!projected.found && !interrupted && !permissionRejected && !formCancelled && !emittedError) {\n const error = prePromotionError ?? { type: \"unknown\", message: \"Prompt was not promoted\" }\n emittedError = true\n process.exitCode = 1\n if (!emit(\"error\", Date.now(), { error })) UI.error(error.message)\n }\n } finally {\n process.off(\"SIGINT\", interrupt)\n controller.abort()\n if (input.compatibility === \"v1\") await stream.return?.(undefined).catch(() => {})\n else void stream.return?.(undefined).catch(() => {})\n }\n}\n\nfunction sameLocation(left: LocationRef | undefined, right: LocationRef) {\n return !!left && left.directory === right.directory && left.workspaceID === right.workspaceID\n}\n\nfunction formRequestOptions(location: LocationRef | undefined): [] | [{ headers: Record<string, string> }] {\n if (!location) return []\n return [\n {\n headers: {\n \"x-opencode-directory\": encodeURIComponent(location.directory),\n ...(location.workspaceID ? { \"x-opencode-workspace\": location.workspaceID } : {}),\n },\n },\n ]\n}\n\nfunction formAlreadySettled(error: unknown) {\n return !!error && typeof error === \"object\" && Reflect.get(error, \"_tag\") === \"FormAlreadySettledError\"\n}\n\nfunction partID(eventID: string) {\n return `prt_${eventID.replace(/^evt_/, \"\")}`\n}\n\nfunction toolKey(messageID: string, id: string) {\n return `${messageID}\\u0000${id}`\n}\n\nfunction contentKey(messageID: string, ordinal: number) {\n return `${messageID}\\u0000${ordinal}`\n}\n\nfunction projectedPartID(messageID: string, part: string) {\n return `prt_${messageID.replace(/^msg_/, \"\")}_${part}`\n}\n\nfunction fallbackTool(event: {\n id: string\n created: number\n data: { assistantMessageID: string; id: string }\n}): ToolState {\n return {\n id: partID(event.id),\n timestamp: toMillis(event.created),\n assistantMessageID: event.data.assistantMessageID,\n tool: \"tool\",\n input: {},\n metadata: {},\n content: [],\n }\n}\n\nfunction toMillis(value: unknown) {\n if (typeof value === \"number\") return value\n if (typeof value === \"string\") return new Date(value).getTime()\n return Date.now()\n}\n\nasync function prepareFile(file: File) {\n if (file.mime !== \"text/plain\") {\n const uri = file.url.startsWith(\"data:\")\n ? file.url\n : `data:${file.mime};base64,${(await readFile(new URL(file.url))).toString(\"base64\")}`\n return { attachment: { uri, name: file.filename } }\n }\n const content = file.url.startsWith(\"data:\")\n ? Buffer.from(file.url.slice(file.url.indexOf(\",\") + 1), \"base64\").toString(\"utf8\")\n : await readFile(new URL(file.url), \"utf8\")\n return { text: `<file name=\"${file.filename}\">\\n${content}\\n</file>` }\n}\n", | ||
| "import { EOL } from \"node:os\"\n\nexport const Style = {\n TEXT_DIM: \"\\x1b[90m\",\n TEXT_NORMAL: \"\\x1b[0m\",\n TEXT_WARNING_BOLD: \"\\x1b[93m\\x1b[1m\",\n TEXT_DANGER_BOLD: \"\\x1b[91m\\x1b[1m\",\n}\n\nexport function println(...message: string[]) {\n process.stderr.write(message.join(\" \") + EOL)\n}\n\nlet blank = false\n\nexport function empty() {\n if (blank) return\n println(Style.TEXT_NORMAL)\n blank = true\n}\n\nexport function error(message: string) {\n if (message.startsWith(\"Error: \")) message = message.slice(\"Error: \".length)\n println(Style.TEXT_DANGER_BOLD + \"Error: \" + Style.TEXT_NORMAL + message)\n}\n\nexport * as UI from \"./ui\"\n" | ||
| ], | ||
| "mappings": ";26CAGA,eAAS,qBACT,qBCMA,cAAS,WACT,mBAAS,mGCXT,cAAS,YAEF,IAAM,EAAQ,CACnB,SAAU,WACV,YAAa,UACb,kBAAmB,kBACnB,iBAAkB,iBACpB,EAEO,SAAS,CAAO,IAAI,EAAmB,CAC5C,QAAQ,OAAO,MAAM,EAAQ,KAAK,GAAG,EAAI,EAAG,EAG9C,IAAI,GAAQ,GAEL,SAAS,EAAK,EAAG,CACtB,GAAI,GAAO,OACX,EAAQ,EAAM,WAAW,EACzB,GAAQ,GAGH,SAAS,EAAK,CAAC,EAAiB,CACrC,GAAI,EAAQ,WAAW,SAAS,EAAG,EAAU,EAAQ,MAAM,CAAgB,EAC3E,EAAQ,EAAM,iBAAmB,UAAY,EAAM,YAAc,CAAO,ED4C1E,IAAM,EAAyB,SAE/B,eAAsB,EAAuB,CAAC,EAAc,CAC1D,IAAM,EAAa,IAAI,gBACjB,EAAS,EAAM,OAAO,MAAM,UAAU,CAAE,OAAQ,EAAW,MAAO,CAAC,EAAE,OAAO,eAAe,EAEjG,IADkB,MAAM,EAAO,KAAK,GACtB,KAAM,MAAU,MAAM,mDAAmD,EAEvF,IAAM,EAAY,GAAe,GAAG,OAAO,EACrC,EAAS,IAAI,IACb,EAAQ,IAAI,IACZ,EAAe,IAAI,IACnB,EAAoB,IAAI,IACxB,EAAgB,IAAI,IACtB,EAAY,GACZ,EAAW,GACX,EAAe,GACf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C/B,GAAI,EAAM,SAAS,CAAC,EAAG,MAAO,GAC9B,OAAO,EAAM,OAAO,CAAC,EAAO,IAAS,EAAQ,OAAO,EAAO,GAAM,EAAO,IAAM,EAAO,EAAG,EAAG,CAAC,EAAI,EAAM,OAAS,IAGjH,eAAe,EAAU,CAAC,EAAmC,EAAmB,CAC9E,IAAM,EAAO,EAAe,EAAM,CAAS,EAC3C,GAAI,EAAK,OAAS,QAAS,CAGzB,GAFA,EAAG,MAAM,EACT,EAAG,QAAQ,EAAG,MAAM,YAAc,EAAK,KAAM,EAAG,MAAM,YAAc,EAAK,KAAK,EAC1E,EAAK,MAAM,KAAK,EAAG,EAAG,QAAQ,EAAK,IAAI,EAC3C,EAAG,MAAM,EACT,OAEF,EAAG,QACD,EAAG,MAAM,YAAc,EAAK,KAC5B,EAAG,MAAM,YAAc,EAAK,MAC5B,EAAK,YAAc,EAAG,MAAM,SAAW,EAAK,YAAc,EAAG,MAAM,YAAc,EACnF,EAGF,eAAe,EAAe,CAAC,EAAmC,EAAmB,CACnF,IAAM,EAAO,EAAe,EAAM,CAAS,EAC3C,EAAG,QAAQ,EAAG,MAAM,YAAc,SAAK,EAAG,MAAM,YAAc,GAAG,EAAK,cAAc,EAI/E,SAAS,CAAc,CAAC,EAAwC,EAAiB,EAAoB,CAE1G,GADA,QAAQ,SAAW,EACf,EAAM,SAAW,OAAQ,CAC3B,QAAQ,OAAO,MACb,KAAK,UAAU,CACb,KAAM,QACN,UAAW,KAAK,IAAI,EACpB,UAAW,GAAa,GACxB,MAAO,CAAE,KAAM,UAAW,SAAQ,CACpC,CAAC,EAAI;AAAA,CACP,EACA,OAEF,EAAG,MAAM,CAAO,EAGlB,SAAS,CAAI,CAAC,EAAwB,CACpC,MAAU,MAAM,CAAO", | ||
| "debugId": "C3B93531FA00D50764756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/list.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { Effect } from \"effect\"\nimport { OpenCode, type PluginInfo } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { Config } from \"../../../config\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Npm } from \"@opencode-ai/util/npm\"\nimport { fileURLToPath } from \"node:url\"\nimport { discoverTuiPlugins, localPluginDirectories, localSource } from \"@opencode-ai/tui/plugin/discovery\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.list,\n Effect.fn(\"cli.plugin.list\")(function* (input) {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.plugin.list({ location: { directory: process.cwd() } }))\n const config = yield* Config.Service\n const global = yield* Global.Service\n const info = yield* config.get()\n const discovered = yield* Effect.promise(() =>\n localPluginDirectories(process.cwd(), global.config).then(discoverTuiPlugins),\n )\n const npm = yield* Npm.Service\n const configured = yield* Effect.forEach(info.plugins ?? [], (entry) =>\n Effect.gen(function* () {\n const target = typeof entry === \"string\" ? entry : entry.package\n if (target.startsWith(\"-\") || target === \"*\" || target.endsWith(\".*\") || target.startsWith(\"opencode.\"))\n return []\n const local = localSource(target, path.dirname(config.path))\n if (local) return [{ target: fileURLToPath(local), version: \"local\" }]\n if (!(yield* Effect.promise(() => Npm.isInstallablePackage(target)))) return []\n const installed = yield* npm.resolve(target, { subpaths: [\"tui\"] })\n if (!installed.entrypoint) return []\n return [{ target, version: installed.version }]\n }),\n )\n const output = format(\n response.data,\n [...configured.flat(), ...discovered.map((target) => ({ target, version: \"local\" }))],\n input.builtin,\n )\n if (!output) {\n process.stdout.write(\"No plugins found\" + EOL)\n return\n }\n process.stdout.write(output + EOL)\n }),\n)\n\nexport function format(\n plugins: readonly PluginInfo[],\n tui: ReadonlyArray<{ readonly target: string; readonly version?: string }>,\n builtin = false,\n) {\n const server = plugins\n .filter((plugin) => builtin || plugin.source.type !== \"builtin\")\n .map((plugin) => ({\n id: plugin.id ?? \"-\",\n version:\n plugin.source.type === \"package\"\n ? (plugin.source.version ?? \"-\")\n : plugin.source.type === \"local\"\n ? \"local\"\n : \"-\",\n target:\n plugin.source.type === \"package\"\n ? plugin.source.target\n : plugin.source.type === \"local\"\n ? plugin.source.path\n : plugin.source.type,\n }))\n const targets = tui\n .filter(\n (item) =>\n !plugins.some((plugin) =>\n plugin.source.type === \"package\"\n ? plugin.source.target === item.target\n : plugin.source.type === \"local\" &&\n (plugin.source.path === item.target ||\n (plugin.features.tui &&\n path.dirname(plugin.source.path) ===\n (item.version === \"local\" && path.extname(item.target) ? path.dirname(item.target) : item.target))),\n ),\n )\n .filter((plugin, index, all) => all.findIndex((candidate) => candidate.target === plugin.target) === index)\n .map((plugin) => ({ id: \"-\", version: plugin.version ?? \"-\", target: plugin.target }))\n const rows = [...server, ...targets]\n .toSorted((a, b) => a.id.localeCompare(b.id) || a.target.localeCompare(b.target))\n .map((item) => [\n item.id,\n /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(item.version) ? item.version.slice(0, 7) : item.version,\n item.target,\n ])\n if (!rows.length) return \"\"\n const table = [[\"ID\", \"VERSION\", \"SOURCE\"], ...rows]\n const widths = [0, 1].map((index) => Math.max(...table.map((row) => row[index].length)))\n return table.map((row) => `${row[0].padEnd(widths[0])} ${row[1].padEnd(widths[1])} ${row[2]}`).join(EOL)\n}\n" | ||
| ], | ||
| "mappings": ";ulCAAA,cAAS,WACT,oBAUA,wBAAS,YAGT,IAAe,IAAQ,QACrB,EAAS,SAAS,OAAO,SAAS,KAClC,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAAO,CAC7C,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,E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,EAAG,CAAC,EAAI,EAAK,QACxF,EAAK,MACP,CAAC,EACH,GAAI,CAAC,EAAK,OAAQ,MAAO,GACzB,IAAM,EAAQ,CAAC,CAAC,KAAM,UAAW,QAAQ,EAAG,GAAG,CAAI,EAC7C,EAAS,CAAC,EAAG,CAAC,EAAE,IAAI,CAAC,IAAU,KAAK,IAAI,GAAG,EAAM,IAAI,CAAC,IAAQ,EAAI,GAAO,MAAM,CAAC,CAAC,EACvF,OAAO,EAAM,IAAI,CAAC,IAAQ,GAAG,EAAI,GAAG,OAAO,EAAO,EAAE,MAAM,EAAI,GAAG,OAAO,EAAO,EAAE,MAAM,EAAI,IAAI,EAAE,KAAK,CAAG", | ||
| "debugId": "96228164EDD7085C64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "F6BEA1CDFF1B9D2A64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/version.ts"], | ||
| "sourcesContent": [ | ||
| "declare const OPENCODE_VERSION: string\ndeclare const OPENCODE_CHANNEL: string\n\nconst version = typeof OPENCODE_VERSION === \"string\" ? OPENCODE_VERSION : \"local\"\nconst channel = typeof OPENCODE_CHANNEL === \"string\" ? OPENCODE_CHANNEL : \"local\"\n\nexport { version as OPENCODE_VERSION, channel as OPENCODE_CHANNEL }\nexport const OPENCODE_LOCAL = channel === \"local\"\n" | ||
| ], | ||
| "mappings": ";AAGA,IAAM,EAAiD,kBACjD,EAAiD,MAGhD,IAAM,EAAiB", | ||
| "debugId": "4DFEF762B026F23864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/server-process.ts", "src/services/service-registration.ts", "src/services/web-ui.ts", "src/app-assets.ts", "src/commands/handlers/serve.ts"], | ||
| "sourcesContent": [ | ||
| "export * as ServerProcess from \"./server-process\"\n\nimport { NodeServices } from \"@effect/platform-node\"\nimport { Service, type DiscoverOptions } from \"@opencode-ai/client/effect/service\"\nimport { LayerNode } from \"@opencode-ai/util/effect/layer-node\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { OPENCODE_CHANNEL, OPENCODE_VERSION } from \"./version\"\nimport { AppProcess } from \"@opencode-ai/util/process\"\nimport { randomBytes, randomUUID } from \"node:crypto\"\nimport { Effect, Option, Redacted, Schedule, Schema } from \"effect\"\nimport { PersistentPty } from \"@opencode-ai/schema/persistent-pty\"\nimport { HttpServer } from \"effect/unstable/http\"\nimport { Env } from \"./env\"\nimport { ServiceConfig } from \"./services/service-config\"\nimport { ServiceRegistration } from \"./services/service-registration\"\nimport { Updater } from \"./services/updater\"\nimport { WebUi } from \"./services/web-ui\"\n\nexport type Mode = \"default\" | \"service\" | \"stdio\"\n\nexport type Options = {\n readonly mode: Mode\n readonly hostname?: string\n readonly port?: number\n readonly cors?: readonly string[]\n}\n\n// The process effect lives until server shutdown; tracing it would parent every request to one process-lifetime trace.\nexport const run = Effect.fnUntraced(function* (options: Options) {\n return yield* processEffect(options).pipe(\n Effect.provide(Updater.layer),\n Effect.provide(\n LayerNode.compile(LayerNode.group([Global.node, AppProcess.node]), {\n replacements: [\n Global.node.replace(\n Global.layerWith(process.env.OPENCODE_CONFIG_DIR ? { config: process.env.OPENCODE_CONFIG_DIR } : {}),\n ),\n ],\n }),\n ),\n Effect.provide(NodeServices.layer),\n )\n})\n\nconst processEffect = Effect.fnUntraced(function* (options: Options) {\n const inherited = process.env.OPENCODE_PTY_HANDOFF\n delete process.env.OPENCODE_PTY_HANDOFF\n const handoff =\n inherited === undefined\n ? undefined\n : yield* Schema.decodeUnknownEffect(Schema.fromJsonString(PersistentPty.Handoff))(inherited).pipe(\n Effect.mapError(() => new Error(\"Invalid PTY restart handoff\")),\n )\n const global = yield* Global.Service\n if (options.mode === \"service\") yield* Effect.sync(() => process.chdir(global.home))\n return yield* Effect.scoped(\n Effect.gen(function* () {\n const foreground = options.mode === \"default\"\n const serviceOptions = options.mode === \"service\" ? yield* ServiceConfig.options() : undefined\n const config = options.mode === \"service\" ? yield* ServiceConfig.read() : {}\n const hostname = options.hostname ?? config.hostname ?? \"127.0.0.1\"\n const port = options.port ?? config.port ?? (options.mode === \"service\" ? ServiceConfig.defaultPort() : undefined)\n const incumbent =\n serviceOptions !== undefined && port !== undefined\n ? yield* Service.incumbent({ ...serviceOptions, url: serviceURL(hostname, port) })\n : undefined\n if (incumbent !== undefined) return\n const { start } = yield* Effect.promise(() => import(\"@opencode-ai/server/process\"))\n const environmentPassword = yield* Env.password\n // Keep the lease credential out of the environment inherited by tools.\n if (options.mode === \"stdio\") {\n delete process.env.OPENCODE_PASSWORD\n delete process.env.OPENCODE_SERVER_PASSWORD\n }\n const password =\n options.mode === \"service\"\n ? config.password || randomBytes(32).toString(\"base64url\")\n : environmentPassword\n ? Redacted.value(environmentPassword)\n : randomBytes(32).toString(\"base64url\")\n if (!password) return yield* Effect.fail(new Error(\"Missing server password\"))\n const instanceID = randomUUID()\n const transform = yield* WebUi.handler()\n const server = yield* start(\n {\n app: {\n name: process.env.OPENCODE_CLIENT ?? \"cli\",\n version: OPENCODE_VERSION,\n channel: OPENCODE_CHANNEL,\n },\n hostname,\n port,\n cors: options.cors ?? config.cors,\n password,\n pty: { handoff },\n simulation: truthy(process.env.OPENCODE_SIMULATE),\n database: {\n path:\n process.env.OPENCODE_DB ??\n ([\"latest\", \"dev\", \"beta\", \"next\", \"prod\"].includes(OPENCODE_CHANNEL) ||\n process.env.OPENCODE_DISABLE_CHANNEL_DB === \"1\" ||\n process.env.OPENCODE_DISABLE_CHANNEL_DB === \"true\"\n ? \"opencode.db\"\n : `opencode-${OPENCODE_CHANNEL.replace(/[^a-zA-Z0-9._-]/g, \"-\")}.db`),\n },\n models: {\n url: process.env.OPENCODE_MODELS_URL,\n file: process.env.OPENCODE_MODELS_PATH,\n fetch: !truthy(process.env.OPENCODE_DISABLE_MODELS_FETCH),\n },\n config: {\n directory: process.env.OPENCODE_CONFIG_DIR,\n project: !truthy(\n process.env.OPENCODE_CONFIG_PROJECT_DISABLE ?? process.env.OPENCODE_DISABLE_PROJECT_CONFIG,\n ),\n file: process.env.OPENCODE_CONFIG,\n content: process.env.OPENCODE_CONFIG_CONTENT,\n },\n windows: {\n gitbash: process.env.OPENCODE_GIT_BASH_PATH,\n },\n fs: {\n filewatcher: !truthy(process.env.OPENCODE_FILEWATCHER_DISABLE ?? process.env.OPENCODE_DISABLE_FILEWATCHER),\n fff:\n process.env.OPENCODE_DISABLE_FFF === undefined\n ? process.platform !== \"win32\"\n : !truthy(process.env.OPENCODE_DISABLE_FFF),\n },\n },\n serviceOptions === undefined\n ? undefined\n : {\n onListen: (address, shutdown) =>\n Effect.gen(function* () {\n if (!config.password) yield* ServiceConfig.password(password)\n return yield* ServiceRegistration.register({\n address,\n password,\n id: instanceID,\n file: serviceOptions.file,\n shutdown,\n })\n }),\n },\n transform,\n ).pipe(\n Effect.catch((error) => {\n if (serviceOptions === undefined || port === undefined || !addressInUse(error)) return Effect.fail(error)\n return recognizeIncumbent(serviceOptions, hostname, port).pipe(\n Effect.flatMap((found) =>\n found\n ? Effect.void\n : Effect.fail(\n new Error(\n `Managed service port ${port} on ${hostname} is already in use by another process. ` +\n \"Configure another port with `opencode service set port <port>` and start the service again.\",\n { cause: error },\n ),\n ),\n ),\n )\n }),\n )\n if (server === undefined) return\n const url = HttpServer.formatAddress(server.address)\n console.log(options.mode === \"stdio\" ? JSON.stringify({ url }) : `server listening on ${url}`)\n if (foreground && !environmentPassword) console.log(`server password ${password}`)\n const updater = yield* Updater.Service\n yield* updater.check().pipe(Effect.schedule(Schedule.spaced(\"10 minutes\")), Effect.forkScoped)\n return yield* options.mode === \"service\"\n ? server.shutdown\n : options.mode === \"stdio\"\n ? waitForStdinClose()\n : Effect.never\n }).pipe(Effect.annotateLogs({ role: \"server\" })),\n )\n})\n\nconst recognizeIncumbent = Effect.fnUntraced(function* (options: DiscoverOptions, hostname: string, port: number) {\n const found = yield* Service.incumbent({ ...options, url: serviceURL(hostname, port) }).pipe(\n Effect.filterOrFail((value) => value !== undefined),\n Effect.retry(Schedule.spaced(\"100 millis\")),\n Effect.timeoutOption(\"15 seconds\"),\n )\n return Option.isSome(found)\n})\n\nfunction serviceURL(hostname: string, port: number) {\n return `http://${hostname.includes(\":\") ? `[${hostname}]` : hostname}:${port}`\n}\n\nfunction truthy(value?: string) {\n return value === \"1\" || value?.toLowerCase() === \"true\"\n}\n\nfunction addressInUse(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false\n if (\"code\" in error && error.code === \"EADDRINUSE\") return true\n return \"cause\" in error && addressInUse(error.cause)\n}\n\nfunction waitForStdinClose() {\n return Effect.callback<void>((resume) => {\n const close = () => resume(Effect.void)\n process.stdin.once(\"end\", close)\n process.stdin.once(\"close\", close)\n process.stdin.resume()\n if (process.stdin.readableEnded || process.stdin.destroyed) close()\n return Effect.sync(() => {\n process.stdin.off(\"end\", close)\n process.stdin.off(\"close\", close)\n process.stdin.pause()\n })\n })\n}\n", | ||
| "export * as ServiceRegistration from \"./service-registration\"\n\nimport { Service, type Info } from \"@opencode-ai/client/effect/service\"\nimport path from \"node:path\"\nimport { Effect, FileSystem, Schedule, Schema } from \"effect\"\nimport { HttpServer } from \"effect/unstable/http\"\nimport { OPENCODE_VERSION } from \"../version\"\n\nconst infoJson = Schema.fromJsonString(Service.Info)\nconst encodeInfo = Schema.encodeEffect(infoJson)\nconst decodeInfo = Schema.decodeUnknownEffect(infoJson)\n\nexport const register = Effect.fnUntraced(function* (options: {\n readonly address: HttpServer.Address\n readonly password: string\n readonly id: string\n readonly file: string\n readonly shutdown: Effect.Effect<void>\n}) {\n const fs = yield* FileSystem.FileSystem\n const temp = options.file + \".\" + options.id + \".tmp\"\n yield* fs.makeDirectory(path.dirname(options.file), { recursive: true })\n const info = {\n id: options.id,\n version: OPENCODE_VERSION,\n url: HttpServer.formatAddress(options.address),\n pid: process.pid,\n password: options.password,\n }\n const encoded = yield* encodeInfo(info)\n const current = fs.readFileString(options.file).pipe(Effect.flatMap(decodeInfo))\n const owns = (found: Info) =>\n found.id === info.id &&\n found.version === info.version &&\n found.url === info.url &&\n found.pid === info.pid &&\n found.password === info.password\n yield* fs.writeFileString(temp, encoded, { mode: 0o600 }).pipe(Effect.andThen(fs.rename(temp, options.file)))\n yield* current.pipe(\n Effect.catchCause((cause) =>\n Effect.logWarning(\"managed service registration check failed; shutting down\", {\n cause,\n serviceID: options.id,\n servicePID: process.pid,\n registration: options.file,\n }).pipe(Effect.andThen(Effect.failCause(cause))),\n ),\n Effect.tap((found) =>\n owns(found)\n ? Effect.void\n : Effect.logWarning(\"managed service registration replaced; shutting down\", {\n serviceID: options.id,\n servicePID: process.pid,\n registration: options.file,\n observedServiceID: found.id,\n observedServicePID: found.pid,\n observedVersion: found.version,\n observedURL: found.url,\n }),\n ),\n Effect.filterOrFail(owns),\n Effect.repeat(Schedule.spaced(\"5 seconds\")),\n Effect.ignore,\n Effect.andThen(options.shutdown),\n Effect.forkScoped,\n )\n return current.pipe(\n Effect.flatMap((found) => (owns(found) ? fs.remove(options.file) : Effect.void)),\n Effect.ignore,\n )\n})\n", | ||
| "import { FSUtil } from \"@opencode-ai/util/fs-util\"\nimport { Effect, FileSystem } from \"effect\"\nimport { HttpServerError, HttpServerRequest, HttpServerResponse } from \"effect/unstable/http\"\nimport { createHash } from \"node:crypto\"\nimport { load, type AssetMap } from \"../app-assets\"\n\nexport const handler = Effect.fn(\"cli.web-ui.handler\")(function* (options?: { readonly assets?: AssetMap }) {\n const fileSystem = yield* FileSystem.FileSystem\n const assets = options?.assets\n ? Effect.succeed(options.assets)\n : yield* Effect.cached(load().pipe(Effect.provideService(FileSystem.FileSystem, fileSystem)))\n return <E, R>(api: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>) =>\n api.pipe(\n Effect.catchIf(isRouteNotFound, () =>\n HttpServerRequest.HttpServerRequest.pipe(\n Effect.flatMap((request) => {\n const url = new URL(request.url, \"http://localhost\")\n if (url.pathname === \"/api\" || url.pathname.startsWith(\"/api/\"))\n return Effect.succeed(HttpServerResponse.empty({ status: 404 }))\n return assets.pipe(Effect.flatMap((files) => serveUI(request, url, files)))\n }),\n ),\n ),\n )\n})\n\nfunction serveUI(request: HttpServerRequest.HttpServerRequest, url: URL, assets: AssetMap) {\n const key = url.pathname.replace(/^\\//, \"\")\n if (key.startsWith(\"_assets/\") && assets[key] === undefined)\n return Effect.succeed(HttpServerResponse.empty({ status: 404, headers: { \"cache-control\": \"no-store\" } }))\n const name = assets[key] !== undefined ? key : \"index.html\"\n const file = assets[name]\n if (!file) return Effect.succeed(HttpServerResponse.empty({ status: 404 }))\n if (request.method !== \"GET\" && request.method !== \"HEAD\")\n return Effect.succeed(HttpServerResponse.empty({ status: 405 }))\n const html = name === \"index.html\"\n const revalidate = html || name === \"sw.js\" || name === \"registerSW.js\"\n const headers = {\n \"content-type\": FSUtil.mimeType(name),\n \"cache-control\": revalidate ? \"no-cache\" : \"public, max-age=31536000, immutable\",\n \"content-security-policy\": html\n ? cspForHtml(typeof file === \"string\" ? file : Buffer.from(file).toString())\n : csp(),\n \"x-content-type-options\": \"nosniff\",\n }\n return Effect.succeed(\n request.method === \"HEAD\"\n ? HttpServerResponse.empty({ headers })\n : HttpServerResponse.raw(file, { headers, contentType: headers[\"content-type\"] }),\n )\n}\n\nfunction isRouteNotFound(error: unknown) {\n return error instanceof HttpServerError.HttpServerError && error.reason._tag === \"RouteNotFound\"\n}\n\nfunction csp(hash = \"\") {\n return `default-src 'self'; script-src 'self' 'wasm-unsafe-eval'${hash ? ` 'sha256-${hash}'` : \"\"}; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: blob:; font-src 'self' data:; media-src 'self' data:; connect-src * data: blob:`\n}\n\nfunction cspForHtml(body: string) {\n const match = body.match(\n /<script\\b(?![^>]*\\bsrc\\s*=)[^>]*\\bid=([\"'])oc-theme-preload-script\\1[^>]*>([\\s\\S]*?)<\\/script>/i,\n )\n return csp(match ? createHash(\"sha256\").update(match[2]).digest(\"base64\") : \"\")\n}\n\nexport * as WebUi from \"./web-ui\"\n", | ||
| "import { Effect, FileSystem, Option } from \"effect\"\nimport path from \"node:path\"\nimport { brotliDecompressSync } from \"node:zlib\"\nimport { OPENCODE_LOCAL } from \"./version\"\n\nexport type AssetMap = Readonly<Record<string, string | Uint8Array>>\ntype EncodedAssetMap = Readonly<Record<string, { readonly content: string; readonly encoding: \"utf8\" | \"base64\" }>>\n\nexport const load = Effect.fn(\"cli.app-assets.load\")(function* () {\n const embedded = yield* Effect.tryPromise(() => import(\"virtual:opencode-app-assets\")).pipe(Effect.option)\n if (Option.isSome(embedded) && embedded.value.default.length > 0) return decodeArchive(embedded.value.default)\n if (!OPENCODE_LOCAL) return yield* Effect.fail(new Error(\"Web UI assets are missing from the CLI build\"))\n return decode(yield* sourceAssets())\n})\n\nfunction decodeArchive(archive: string) {\n const body = brotliDecompressSync(Buffer.from(archive, \"base64\")).toString()\n return decode(JSON.parse(body) as EncodedAssetMap)\n}\n\nconst sourceAssets = Effect.fnUntraced(function* () {\n const fs = yield* FileSystem.FileSystem\n const root = path.resolve(import.meta.dirname, \"../../app/dist\")\n const files = yield* fs.readDirectory(root, { recursive: true })\n return Object.fromEntries(\n (yield* Effect.forEach(\n files.filter((file) => !file.endsWith(\".map\")),\n Effect.fnUntraced(function* (file) {\n const target = path.join(root, file)\n if ((yield* fs.stat(target)).type === \"Directory\") return\n const body = Buffer.from(yield* fs.readFile(target))\n const encoding = isText(file) ? \"utf8\" : \"base64\"\n return [file, { encoding, content: body.toString(encoding) }] as const\n }),\n { concurrency: \"unbounded\" },\n )).filter((asset) => asset !== undefined),\n )\n})\n\nfunction decode(assets: EncodedAssetMap): AssetMap {\n return Object.fromEntries(\n Object.entries(assets).map(([key, asset]) => [\n key,\n asset.encoding === \"utf8\" ? asset.content : Buffer.from(asset.content, \"base64\"),\n ]),\n )\n}\n\nfunction isText(file: string) {\n return file === \"_headers\" || /\\.(?:css|html|js|json|svg|txt|webmanifest|xml)$/.test(file)\n}\n", | ||
| "import { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServerProcess } from \"../../server-process\"\n\nexport default Runtime.handler(\n Commands.commands.serve,\n Effect.fnUntraced(function* (input) {\n if (input.service && input.stdio) return yield* Effect.fail(new Error(\"--service and --stdio cannot be combined\"))\n return yield* ServerProcess.run({\n mode: input.service ? \"service\" : input.stdio ? \"stdio\" : \"default\",\n hostname: Option.getOrUndefined(input.hostname),\n port: Option.getOrUndefined(input.port),\n cors: input.cors.length > 0 ? input.cors : undefined,\n })\n }),\n)\n" | ||
| ], | ||
| "mappings": ";unDAQA,sBAAS,gBAAa,0ECLtB,qBAKA,IAAM,EAAW,EAAO,eAAe,EAAQ,IAAI,EAC7C,GAAa,EAAO,aAAa,CAAQ,EACzC,GAAa,EAAO,oBAAoB,CAAQ,EAEzC,GAAW,EAAO,WAAW,SAAU,CAAC,EAMlD,CACD,IAAM,EAAK,MAAO,EAAW,WACvB,EAAO,EAAQ,KAAO,IAAM,EAAQ,GAAK,OAC/C,MAAO,EAAG,cAAc,GAAK,QAAQ,EAAQ,IAAI,EAAG,CAAE,UAAW,EAAK,CAAC,EACvE,IAAM,EAAO,CACX,GAAI,EAAQ,GACZ,QAAS,EACT,IAAK,EAAW,cAAc,EAAQ,OAAO,EAC7C,IAAK,QAAQ,IACb,SAAU,EAAQ,QACpB,EACM,EAAU,MAAO,GAAW,CAAI,EAChC,EAAU,EAAG,eAAe,EAAQ,IAAI,EAAE,KAAK,EAAO,QAAQ,EAAU,CAAC,EACzE,EAAO,CAAC,IACZ,EAAM,KAAO,EAAK,IAClB,EAAM,UAAY,EAAK,SACvB,EAAM,MAAQ,EAAK,KACnB,EAAM,MAAQ,EAAK,KACnB,EAAM,WAAa,EAAK,SA8B1B,OA7BA,MAAO,EAAG,gBAAgB,EAAM,EAAS,C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,CAAK,EAC9B,QAAQ,MAAM,IAAI,QAAS,CAAK,EAChC,QAAQ,MAAM,MAAM,EACrB,EACF,EIhNH,IAAe,MAAQ,QACrB,EAAS,SAAS,MAClB,EAAO,WAAW,SAAU,CAAC,EAAO,CAClC,GAAI,EAAM,SAAW,EAAM,MAAO,OAAO,MAAO,EAAO,KAAS,MAAM,0CAA0C,CAAC,EACjH,OAAO,MAAO,EAAc,IAAI,CAC9B,KAAM,EAAM,QAAU,UAAY,EAAM,MAAQ,QAAU,UAC1D,SAAU,EAAO,eAAe,EAAM,QAAQ,EAC9C,KAAM,EAAO,eAAe,EAAM,IAAI,EACtC,KAAM,EAAM,KAAK,OAAS,EAAI,EAAM,KAAO,MAC7C,CAAC,EACF,CACH", | ||
| "debugId": "0038A8AE4D4636E264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/services/server-connection.ts"], | ||
| "sourcesContent": [ | ||
| "import { Service, type Endpoint, type EnsureOptions } from \"@opencode-ai/client/effect/service\"\nimport { ClientError, isUnauthorizedError, OpenCode } from \"@opencode-ai/client/promise\"\nimport { OPENCODE_VERSION } from \"../version\"\nimport { Effect, Redacted } from \"effect\"\nimport { Env } from \"../env\"\nimport { ServiceConfig } from \"./service-config\"\nimport { Standalone } from \"./standalone\"\n\nexport type Args = {\n readonly server?: string\n readonly standalone?: boolean\n readonly mismatch?: \"replace\" | \"ignore\" | \"error\"\n readonly onStart?: EnsureOptions[\"onStart\"]\n}\n\nexport type Resolved = {\n readonly endpoint: Endpoint\n readonly service?: ReturnType<typeof managedService>\n}\n\nexport const resolve = Effect.fn(\"cli.server-connection.resolve\")(function* (args: Args) {\n if (args.server !== undefined && args.standalone)\n return yield* Effect.fail(new Error(\"--server and --standalone cannot be combined\"))\n if (args.server !== undefined) {\n const password = yield* Env.password\n const endpoint = {\n url: args.server,\n auth: password ? { type: \"basic\" as const, username: \"opencode\", password: Redacted.value(password) } : undefined,\n } satisfies Endpoint\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const health = yield* Effect.tryPromise({\n try: () => client.health.get({ signal: AbortSignal.timeout(5_000) }),\n catch: (cause) => connectError(endpoint, cause),\n })\n if (health.version !== OPENCODE_VERSION)\n process.stderr.write(\n `Warning: Server at ${endpoint.url} has version ${health.version}; this client is ${OPENCODE_VERSION}. Continuing anyway.\\n`,\n )\n return { endpoint } satisfies Resolved\n }\n if (args.standalone) {\n return { endpoint: yield* Standalone.start() } satisfies Resolved\n }\n\n const mismatch = args.mismatch ?? \"ignore\"\n const options = yield* ServiceConfig.options({ checkVersion: mismatch !== \"ignore\" })\n return {\n endpoint: yield* resolveManaged({ ...options, onStart: args.onStart }, mismatch),\n service: managedService(options),\n } satisfies Resolved\n})\n\nfunction managedService(options: EnsureOptions) {\n const reconnectOptions = { ...options, version: undefined }\n return {\n reconnect: () => Service.ensure(reconnectOptions),\n restart: () =>\n Effect.gen(function* () {\n yield* Service.stop(options)\n yield* Service.ensure(reconnectOptions)\n }),\n }\n}\n\nexport const shutdownPersistentPty = Effect.fn(\"cli.server-connection.shutdown-persistent-pty\")(function* (\n options: EnsureOptions,\n) {\n const endpoint = yield* Service.discover({ ...options, version: undefined })\n if (!endpoint) return\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n yield* Effect.tryPromise(() => client.experimental.persistentPty.shutdown())\n})\n\nconst resolveManaged = Effect.fnUntraced(function* (options: EnsureOptions, mismatch: NonNullable<Args[\"mismatch\"]>) {\n if (mismatch === \"replace\") return yield* Service.ensure(options)\n if (mismatch === \"ignore\") return yield* Service.ensure({ ...options, version: undefined })\n\n const compatible = yield* Service.discover(options)\n if (compatible !== undefined) return compatible\n const existing = yield* Service.discover({ ...options, version: undefined })\n if (existing !== undefined)\n return yield* Effect.fail(new Error(\"Background server version does not match this client\"))\n return yield* Service.ensure(options)\n})\n\nfunction connectError(endpoint: Endpoint, cause: unknown) {\n if (isUnauthorizedError(cause)) {\n return new Error(\n endpoint.auth === undefined\n ? `Server at ${endpoint.url} requires a password; set OPENCODE_PASSWORD`\n : `Server at ${endpoint.url} rejected the password`,\n { cause },\n )\n }\n if (cause instanceof ClientError && cause.reason === \"Transport\")\n return new Error(`Could not reach server at ${endpoint.url}`, { cause })\n return new Error(`Server at ${endpoint.url} did not provide a compatible V2 health response`, { cause })\n}\n\nexport * as ServerConnection from \"./server-connection\"\n" | ||
| ], | ||
| "mappings": ";ygBAoBO,IAAM,EAAU,EAAO,GAAG,+BAA+B,EAAE,SAAU,CAAC,EAAY,CACvF,GAAI,EAAK,SAAW,QAAa,EAAK,WACpC,OAAO,MAAO,EAAO,KAAS,MAAM,8CAA8C,CAAC,EACrF,GAAI,EAAK,SAAW,OAAW,CAC7B,IAAM,EAAW,MAAO,EAAI,SACtB,EAAW,CACf,IAAK,EAAK,OACV,KAAM,EAAW,CAAE,KAAM,QAAkB,SAAU,WAAY,SAAU,EAAS,MAAM,CAAQ,CAAE,EAAI,MAC1G,EACM,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAS,MAAO,EAAO,WAAW,CACtC,IAAK,IAAM,EAAO,OAAO,IAAI,CAAE,OAAQ,YAAY,QAAQ,IAAK,CAAE,CAAC,EACnE,MAAO,CAAC,IAAU,EAAa,EAAU,CAAK,CAChD,CAAC,EACD,GAAI,EAAO,UAAY,EACrB,QAAQ,OAAO,MACb,sBAAsB,EAAS,mBAAmB,EAAO,2BAA2B;AAAA,CACtF,EACF,MAAO,CAAE,UAAS,EAEpB,GAAI,EAAK,WACP,MAAO,CAAE,SAAU,MAAO,EAAW,MAAM,CAAE,EAG/C,IAAM,EAAW,EAAK,UAAY,SAC5B,EAAU,MAAO,EAAc,QAAQ,CAAE,aAAc,IAAa,QAAS,CAAC,EACpF,MAAO,CACL,SAAU,MAAO,EAAe,IAAK,EAAS,QAAS,EAAK,OAAQ,EAAG,CAAQ,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B,EAAS,MAAO,CAAE,OAAM,CAAC,EACzE,OAAW,MAAM,aAAa,EAAS,sDAAuD,CAAE,OAAM,CAAC", | ||
| "debugId": "56F871E9CD23F0FF64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/debug/paths.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\n\nexport default Runtime.handler(\n Commands.commands.debug.commands.paths,\n Effect.fn(\"cli.debug.paths\")(function* () {\n const global = yield* Global.Service\n process.stdout.write(\n Object.entries(global)\n .map(([key, value]) => `${key.padEnd(10)} ${value}${EOL}`)\n .join(\"\"),\n )\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+pBAAA,cAAS,WAMT,IAAe,IAAQ,QACrB,EAAS,SAAS,MAAM,SAAS,MACjC,EAAO,GAAG,iBAAiB,EAAE,SAAU,EAAG,CACxC,IAAM,EAAS,MAAO,EAAO,QAC7B,QAAQ,OAAO,MACb,OAAO,QAAQ,CAAM,EAClB,IAAI,EAAE,EAAK,KAAW,GAAG,EAAI,OAAO,EAAE,KAAK,IAAQ,GAAK,EACxD,KAAK,EAAE,CACZ,EACD,CACH", | ||
| "debugId": "763929B0CC83937B64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "02DB3858BC91125064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+mistral@3.0.51+d6123d32214422cb/node_modules/@ai-sdk/mistral/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/mistral-provider.ts\nimport {\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/mistral-chat-language-model.ts\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonResponseHandler,\n generateId,\n injectJsonInstructionIntoMessages,\n parseProviderOptions,\n postJsonToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z3 } from \"zod/v4\";\n\n// src/convert-mistral-usage.ts\nfunction convertMistralUsage(usage) {\n var _a, _b, _c, _d, _e;\n if (usage == null) {\n return {\n inputTokens: {\n total: void 0,\n noCache: void 0,\n cacheRead: void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: void 0,\n text: void 0,\n reasoning: void 0\n },\n raw: void 0\n };\n }\n const promptTokens = usage.prompt_tokens;\n const completionTokens = usage.completion_tokens;\n const cacheReadTokens = (_e = (_d = (_b = usage.num_cached_tokens) != null ? _b : (_a = usage.prompt_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _d : (_c = usage.prompt_token_details) == null ? void 0 : _c.cached_tokens) != null ? _e : 0;\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens - cacheReadTokens,\n cacheRead: cacheReadTokens || void 0,\n cacheWrite: void 0\n },\n outputTokens: {\n total: completionTokens,\n text: completionTokens,\n reasoning: void 0\n },\n raw: usage\n };\n}\n\n// src/convert-to-mistral-chat-messages.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\nimport { convertToBase64 } from \"@ai-sdk/provider-utils\";\nfunction formatFileUrl({\n data,\n mediaType\n}) {\n return data instanceof URL ? data.toString() : `data:${mediaType};base64,${convertToBase64(data)}`;\n}\nfunction convertToMistralChatMessages(prompt) {\n var _a;\n const messages = [];\n for (let i = 0; i < prompt.length; i++) {\n const { role, content } = prompt[i];\n const isLastMessage = i === prompt.length - 1;\n switch (role) {\n case \"system\": {\n messages.push({ role: \"system\", content });\n break;\n }\n case \"user\": {\n messages.push({\n role: \"user\",\n content: content.map((part) => {\n switch (part.type) {\n case \"text\": {\n return { type: \"text\", text: part.text };\n }\n case \"file\": {\n if (part.mediaType.startsWith(\"image/\")) {\n const mediaType = part.mediaType === \"image/*\" ? \"image/jpeg\" : part.mediaType;\n return {\n type: \"image_url\",\n image_url: formatFileUrl({ data: part.data, mediaType })\n };\n } else if (part.mediaType === \"application/pdf\") {\n return {\n type: \"document_url\",\n document_url: formatFileUrl({\n data: part.data,\n mediaType: \"application/pdf\"\n })\n };\n } else {\n throw new UnsupportedFunctionalityError({\n functionality: \"Only images and PDF file parts are supported\"\n });\n }\n }\n }\n })\n });\n break;\n }\n case \"assistant\": {\n let text = \"\";\n const structuredContent = [];\n let hasNativeReasoning = false;\n const toolCalls = [];\n for (const part of content) {\n switch (part.type) {\n case \"text\": {\n text += part.text;\n structuredContent.push({ type: \"text\", text: part.text });\n break;\n }\n case \"tool-call\": {\n toolCalls.push({\n id: part.toolCallId,\n type: \"function\",\n function: {\n name: part.toolName,\n arguments: JSON.stringify(part.input)\n }\n });\n break;\n }\n case \"reasoning\": {\n text += part.text;\n const native = part.providerOptions?.mistral?.thinking;\n if (native?.type === \"thinking\") {\n hasNativeReasoning = true;\n structuredContent.push(native);\n break;\n }\n structuredContent.push({ type: \"text\", text: part.text });\n break;\n }\n default: {\n throw new Error(\n `Unsupported content type in assistant message: ${part.type}`\n );\n }\n }\n }\n messages.push({\n role: \"assistant\",\n content: hasNativeReasoning ? structuredContent : text,\n prefix: isLastMessage ? true : void 0,\n tool_calls: toolCalls.length > 0 ? toolCalls : void 0\n });\n break;\n }\n case \"tool\": {\n for (const toolResponse of content) {\n if (toolResponse.type === \"tool-approval-response\") {\n continue;\n }\n const output = toolResponse.output;\n let contentValue;\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n contentValue = output.value;\n break;\n case \"execution-denied\":\n contentValue = (_a = output.reason) != null ? _a : \"Tool call execution denied.\";\n break;\n case \"content\":\n case \"json\":\n case \"error-json\":\n contentValue = JSON.stringify(output.value);\n break;\n }\n messages.push({\n role: \"tool\",\n name: toolResponse.toolName,\n tool_call_id: toolResponse.toolCallId,\n content: contentValue\n });\n }\n break;\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return messages;\n}\n\n// src/get-response-metadata.ts\nfunction getResponseMetadata({\n id,\n model,\n created\n}) {\n return {\n id: id != null ? id : void 0,\n modelId: model != null ? model : void 0,\n timestamp: created != null ? new Date(created * 1e3) : void 0\n };\n}\n\n// src/map-mistral-finish-reason.ts\nfunction mapMistralFinishReason(finishReason) {\n switch (finishReason) {\n case \"stop\":\n return \"stop\";\n case \"length\":\n case \"model_length\":\n return \"length\";\n case \"tool_calls\":\n return \"tool-calls\";\n default:\n return \"other\";\n }\n}\n\n// src/mistral-chat-options.ts\nimport { z } from \"zod/v4\";\nvar mistralLanguageModelOptions = z.object({\n /**\n * Whether to inject a safety prompt before all conversations.\n *\n * Defaults to `false`.\n */\n safePrompt: z.boolean().optional(),\n documentImageLimit: z.number().optional(),\n documentPageLimit: z.number().optional(),\n /**\n * Whether to use structured outputs.\n *\n * @default true\n */\n structuredOutputs: z.boolean().optional(),\n /**\n * Whether to use strict JSON schema validation.\n *\n * @default false\n */\n strictJsonSchema: z.boolean().optional(),\n /**\n * Whether to enable parallel function calling during tool use.\n * When set to false, the model will use at most one tool per response.\n *\n * @default true\n */\n parallelToolCalls: z.boolean().optional(),\n /**\n * Controls the reasoning effort for models that support adjustable reasoning.\n *\n * - `'high'`: Enable reasoning\n * - `'none'`: Disable reasoning\n */\n reasoningEffort: z.enum([\"high\", \"none\"]).optional(),\n promptCacheKey: z.string().optional()\n});\n\n// src/mistral-error.ts\nimport { createJsonErrorResponseHandler } from \"@ai-sdk/provider-utils\";\nimport { z as z2 } from \"zod/v4\";\nvar mistralErrorDataSchema = z2.object({\n object: z2.literal(\"error\"),\n message: z2.string(),\n type: z2.string(),\n param: z2.string().nullable(),\n code: z2.string().nullable()\n});\nvar mistralFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: mistralErrorDataSchema,\n errorToMessage: (data) => data.message\n});\n\n// src/mistral-prepare-tools.ts\nimport {\n UnsupportedFunctionalityError as UnsupportedFunctionalityError2\n} from \"@ai-sdk/provider\";\nfunction prepareTools({\n tools,\n toolChoice\n}) {\n tools = (tools == null ? void 0 : tools.length) ? tools : void 0;\n const toolWarnings = [];\n if (tools == null) {\n return { tools: void 0, toolChoice: void 0, toolWarnings };\n }\n const mistralTools = [];\n for (const tool of tools) {\n if (tool.type === \"provider\") {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `provider-defined tool ${tool.id}`\n });\n } else {\n mistralTools.push({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n ...tool.strict != null ? { strict: tool.strict } : {}\n }\n });\n }\n }\n if (toolChoice == null) {\n return { tools: mistralTools, toolChoice: void 0, toolWarnings };\n }\n const type = toolChoice.type;\n switch (type) {\n case \"auto\":\n case \"none\":\n return { tools: mistralTools, toolChoice: type, toolWarnings };\n case \"required\":\n return { tools: mistralTools, toolChoice: \"any\", toolWarnings };\n // mistral does not support tool mode directly,\n // so we filter the tools and force the tool choice through 'any'\n case \"tool\":\n return {\n tools: mistralTools.filter(\n (tool) => tool.function.name === toolChoice.toolName\n ),\n toolChoice: \"any\",\n toolWarnings\n };\n default: {\n const _exhaustiveCheck = type;\n throw new UnsupportedFunctionalityError2({\n functionality: `tool choice type: ${_exhaustiveCheck}`\n });\n }\n }\n}\n\n// src/mistral-chat-language-model.ts\nvar MistralChatLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.supportedUrls = {\n \"application/pdf\": [/^https:\\/\\/.*$/]\n };\n var _a;\n this.modelId = modelId;\n this.config = config;\n this.generateId = (_a = config.generateId) != null ? _a : generateId;\n }\n get provider() {\n return this.config.provider;\n }\n async getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n providerOptions,\n tools,\n toolChoice\n }) {\n var _a, _b, _c, _d;\n const warnings = [];\n const options = (_a = await parseProviderOptions({\n provider: \"mistral\",\n providerOptions,\n schema: mistralLanguageModelOptions\n })) != null ? _a : {};\n if (topK != null) {\n warnings.push({ type: \"unsupported\", feature: \"topK\" });\n }\n const structuredOutputs = (_b = options.structuredOutputs) != null ? _b : true;\n const strictJsonSchema = (_c = options.strictJsonSchema) != null ? _c : false;\n if ((responseFormat == null ? void 0 : responseFormat.type) === \"json\" && !(responseFormat == null ? void 0 : responseFormat.schema)) {\n prompt = injectJsonInstructionIntoMessages({\n messages: prompt,\n schema: responseFormat.schema\n });\n }\n const baseArgs = {\n // model id:\n model: this.modelId,\n // model specific settings:\n safe_prompt: options.safePrompt,\n // standardized settings:\n max_tokens: maxOutputTokens,\n temperature,\n top_p: topP,\n ...frequencyPenalty != null ? { frequency_penalty: frequencyPenalty } : {},\n ...presencePenalty != null ? { presence_penalty: presencePenalty } : {},\n stop: stopSequences,\n random_seed: seed,\n reasoning_effort: options.reasoningEffort,\n prompt_cache_key: options.promptCacheKey,\n // response format:\n response_format: (responseFormat == null ? void 0 : responseFormat.type) === \"json\" ? structuredOutputs && (responseFormat == null ? void 0 : responseFormat.schema) != null ? {\n type: \"json_schema\",\n json_schema: {\n schema: responseFormat.schema,\n strict: strictJsonSchema,\n name: (_d = responseFormat.name) != null ? _d : \"response\",\n description: responseFormat.description\n }\n } : { type: \"json_object\" } : void 0,\n // mistral-specific provider options:\n document_image_limit: options.documentImageLimit,\n document_page_limit: options.documentPageLimit,\n // messages:\n messages: convertToMistralChatMessages(prompt)\n };\n const {\n tools: mistralTools,\n toolChoice: mistralToolChoice,\n toolWarnings\n } = prepareTools({\n tools,\n toolChoice\n });\n return {\n args: {\n ...baseArgs,\n tools: mistralTools,\n tool_choice: mistralToolChoice,\n ...mistralTools != null && options.parallelToolCalls !== void 0 ? { parallel_tool_calls: options.parallelToolCalls } : {}\n },\n warnings: [...warnings, ...toolWarnings]\n };\n }\n async doGenerate(options) {\n var _a;\n const { args: body, warnings } = await this.getArgs(options);\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n mistralChatResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const choice = response.choices[0];\n const content = [];\n if (choice.message.content != null && Array.isArray(choice.message.content)) {\n for (const part of choice.message.content) {\n if (part.type === \"thinking\") {\n const reasoningText = extractReasoningContent(part.thinking);\n content.push({\n type: \"reasoning\",\n text: reasoningText,\n providerMetadata: { mistral: { thinking: part } }\n });\n } else if (part.type === \"text\") {\n if (part.text.length > 0) {\n content.push({ type: \"text\", text: part.text });\n }\n }\n }\n } else {\n const text = extractTextContent(choice.message.content);\n if (text != null && text.length > 0) {\n content.push({ type: \"text\", text });\n }\n }\n if (choice.message.tool_calls != null) {\n for (const toolCall of choice.message.tool_calls) {\n content.push({\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: toolCall.function.arguments\n });\n }\n }\n return {\n content,\n finishReason: {\n unified: mapMistralFinishReason(choice.finish_reason),\n raw: (_a = choice.finish_reason) != null ? _a : void 0\n },\n usage: convertMistralUsage(response.usage),\n request: { body },\n response: {\n ...getResponseMetadata(response),\n headers: responseHeaders,\n body: rawResponse\n },\n warnings\n };\n }\n async doStream(options) {\n const { args, warnings } = await this.getArgs(options);\n const body = { ...args, stream: true };\n const { responseHeaders, value: response } = await postJsonToApi({\n url: `${this.config.baseURL}/chat/completions`,\n headers: combineHeaders(this.config.headers(), options.headers),\n body,\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(\n mistralChatChunkSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n let usage = void 0;\n let isFirstChunk = true;\n let activeText = false;\n let activeReasoningId = null;\n let activeThinking = null;\n const generateId2 = this.generateId;\n return {\n stream: response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n if (isFirstChunk) {\n isFirstChunk = false;\n controller.enqueue({\n type: \"response-metadata\",\n ...getResponseMetadata(value)\n });\n }\n if (value.usage != null) {\n usage = value.usage;\n }\n const choice = value.choices[0];\n const delta = choice.delta;\n const textContent = extractTextContent(delta.content);\n if (delta.content != null && Array.isArray(delta.content)) {\n for (const part of delta.content) {\n if (part.type === \"thinking\") {\n const reasoningDelta = extractReasoningContent(part.thinking);\n activeThinking = mergeThinking(activeThinking, part);\n if (activeReasoningId == null) {\n if (activeText) {\n controller.enqueue({ type: \"text-end\", id: \"0\" });\n activeText = false;\n }\n activeReasoningId = generateId2();\n controller.enqueue({\n type: \"reasoning-start\",\n id: activeReasoningId\n });\n }\n if (reasoningDelta.length > 0) {\n controller.enqueue({\n type: \"reasoning-delta\",\n id: activeReasoningId,\n delta: reasoningDelta\n });\n }\n }\n }\n }\n if (textContent != null && textContent.length > 0) {\n if (!activeText) {\n if (activeReasoningId != null) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: activeReasoningId,\n providerMetadata: { mistral: { thinking: activeThinking } }\n });\n activeReasoningId = null;\n activeThinking = null;\n }\n controller.enqueue({ type: \"text-start\", id: \"0\" });\n activeText = true;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: \"0\",\n delta: textContent\n });\n }\n if ((delta == null ? void 0 : delta.tool_calls) != null) {\n for (const toolCall of delta.tool_calls) {\n const toolCallId = toolCall.id;\n const toolName = toolCall.function.name;\n const input = toolCall.function.arguments;\n controller.enqueue({\n type: \"tool-input-start\",\n id: toolCallId,\n toolName\n });\n controller.enqueue({\n type: \"tool-input-delta\",\n id: toolCallId,\n delta: input\n });\n controller.enqueue({\n type: \"tool-input-end\",\n id: toolCallId\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId,\n toolName,\n input\n });\n }\n }\n if (choice.finish_reason != null) {\n finishReason = {\n unified: mapMistralFinishReason(choice.finish_reason),\n raw: choice.finish_reason\n };\n }\n },\n flush(controller) {\n if (activeReasoningId != null) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: activeReasoningId,\n providerMetadata: { mistral: { thinking: activeThinking } }\n });\n }\n if (activeText) {\n controller.enqueue({ type: \"text-end\", id: \"0\" });\n }\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertMistralUsage(usage)\n });\n }\n })\n ),\n request: { body },\n response: { headers: responseHeaders }\n };\n }\n};\nfunction extractReasoningContent(thinking) {\n return thinking.filter((chunk) => chunk.type === \"text\").map((chunk) => chunk.text).join(\"\");\n}\nfunction mergeThinking(current, next) {\n if (current === null) return { ...next, thinking: [...next.thinking] };\n current.thinking.push(...next.thinking);\n if (next.closed !== void 0) current.closed = next.closed;\n if (next.signature !== void 0) current.signature = next.signature;\n return current;\n}\nfunction extractTextContent(content) {\n if (typeof content === \"string\") {\n return content;\n }\n if (content == null) {\n return void 0;\n }\n const textContent = [];\n for (const chunk of content) {\n const { type } = chunk;\n switch (type) {\n case \"text\":\n textContent.push(chunk.text);\n break;\n case \"thinking\":\n case \"image_url\":\n case \"reference\":\n break;\n default: {\n const _exhaustiveCheck = type;\n throw new Error(`Unsupported type: ${_exhaustiveCheck}`);\n }\n }\n }\n return textContent.length ? textContent.join(\"\") : void 0;\n}\nvar mistralThinkingContentSchema = z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"tool_reference\"),\n tool: z3.string(),\n title: z3.string(),\n url: z3.string().nullish(),\n favicon: z3.string().nullish(),\n description: z3.string().nullish()\n }),\n z3.object({\n type: z3.literal(\"reference\"),\n reference_ids: z3.array(z3.union([z3.string(), z3.number().int()]))\n })\n]);\nvar mistralThinkChunkSchema = z3.object({\n type: z3.literal(\"thinking\"),\n thinking: z3.array(mistralThinkingContentSchema),\n closed: z3.boolean().optional(),\n signature: z3.string().nullish()\n});\nvar mistralContentSchema = z3.union([\n z3.string(),\n z3.array(\n z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"text\"),\n text: z3.string()\n }),\n z3.object({\n type: z3.literal(\"image_url\"),\n image_url: z3.union([\n z3.string(),\n z3.object({\n url: z3.string(),\n detail: z3.string().nullable()\n })\n ])\n }),\n z3.object({\n type: z3.literal(\"reference\"),\n reference_ids: z3.array(z3.union([z3.string(), z3.number()]))\n }),\n mistralThinkChunkSchema\n ])\n )\n]).nullish();\nvar mistralUsageSchema = z3.object({\n prompt_tokens: z3.number(),\n completion_tokens: z3.number(),\n total_tokens: z3.number(),\n num_cached_tokens: z3.number().nullish(),\n prompt_tokens_details: z3.object({ cached_tokens: z3.number().nullish() }).nullish(),\n prompt_token_details: z3.object({ cached_tokens: z3.number().nullish() }).nullish()\n});\nvar mistralChatResponseSchema = z3.object({\n id: z3.string().nullish(),\n created: z3.number().nullish(),\n model: z3.string().nullish(),\n choices: z3.array(\n z3.object({\n message: z3.object({\n role: z3.literal(\"assistant\"),\n content: mistralContentSchema,\n tool_calls: z3.array(\n z3.object({\n id: z3.string(),\n function: z3.object({ name: z3.string(), arguments: z3.string() })\n })\n ).nullish()\n }),\n index: z3.number(),\n finish_reason: z3.string().nullish()\n })\n ),\n object: z3.literal(\"chat.completion\"),\n usage: mistralUsageSchema\n});\nvar mistralChatChunkSchema = z3.object({\n id: z3.string().nullish(),\n created: z3.number().nullish(),\n model: z3.string().nullish(),\n choices: z3.array(\n z3.object({\n delta: z3.object({\n role: z3.enum([\"assistant\"]).optional(),\n content: mistralContentSchema,\n tool_calls: z3.array(\n z3.object({\n id: z3.string(),\n function: z3.object({ name: z3.string(), arguments: z3.string() })\n })\n ).nullish()\n }),\n finish_reason: z3.string().nullish(),\n index: z3.number()\n })\n ),\n usage: mistralUsageSchema.nullish()\n});\n\n// src/mistral-embedding-model.ts\nimport {\n TooManyEmbeddingValuesForCallError\n} from \"@ai-sdk/provider\";\nimport {\n combineHeaders as combineHeaders2,\n createJsonResponseHandler as createJsonResponseHandler2,\n postJsonToApi as postJsonToApi2\n} from \"@ai-sdk/provider-utils\";\nimport { z as z4 } from \"zod/v4\";\nvar MistralEmbeddingModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n this.maxEmbeddingsPerCall = 32;\n this.supportsParallelCalls = false;\n this.modelId = modelId;\n this.config = config;\n }\n get provider() {\n return this.config.provider;\n }\n async doEmbed({\n values,\n abortSignal,\n headers\n }) {\n if (values.length > this.maxEmbeddingsPerCall) {\n throw new TooManyEmbeddingValuesForCallError({\n provider: this.provider,\n modelId: this.modelId,\n maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,\n values\n });\n }\n const {\n responseHeaders,\n value: response,\n rawValue\n } = await postJsonToApi2({\n url: `${this.config.baseURL}/embeddings`,\n headers: combineHeaders2(this.config.headers(), headers),\n body: {\n model: this.modelId,\n input: values,\n encoding_format: \"float\"\n },\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler2(\n MistralTextEmbeddingResponseSchema\n ),\n abortSignal,\n fetch: this.config.fetch\n });\n return {\n warnings: [],\n embeddings: response.data.map((item) => item.embedding),\n usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,\n response: { headers: responseHeaders, body: rawValue }\n };\n }\n};\nvar MistralTextEmbeddingResponseSchema = z4.object({\n data: z4.array(z4.object({ embedding: z4.array(z4.number()) })),\n usage: z4.object({ prompt_tokens: z4.number() }).nullish()\n});\n\n// src/mistral-speech-model.ts\nimport {\n combineHeaders as combineHeaders3,\n createJsonResponseHandler as createJsonResponseHandler3,\n parseProviderOptions as parseProviderOptions2,\n postToApi\n} from \"@ai-sdk/provider-utils\";\nimport { z as z6 } from \"zod/v4\";\n\n// src/mistral-speech-model-options.ts\nimport { z as z5 } from \"zod/v4\";\nvar mistralSpeechModelOptions = z5.object({\n /**\n * Base64-encoded reference audio for one-off voice cloning.\n *\n * When provided, this takes precedence over the standard `voice` option.\n */\n refAudio: z5.string().min(1).optional()\n});\n\n// src/mistral-speech-model.ts\nvar MistralSpeechModel = class {\n constructor(modelId, config) {\n this.modelId = modelId;\n this.config = config;\n this.specificationVersion = \"v3\";\n }\n get provider() {\n return this.config.provider;\n }\n async getArgs({\n text,\n voice,\n outputFormat = \"mp3\",\n instructions,\n speed,\n language,\n providerOptions\n }) {\n const warnings = [];\n const mistralOptions = await parseProviderOptions2({\n provider: \"mistral\",\n providerOptions,\n schema: mistralSpeechModelOptions\n });\n let responseFormat = \"mp3\";\n if ([\"pcm\", \"wav\", \"mp3\", \"flac\", \"opus\"].includes(outputFormat)) {\n responseFormat = outputFormat;\n } else {\n warnings.push({\n type: \"unsupported\",\n feature: \"outputFormat\",\n details: `Unsupported output format: ${outputFormat}. Using mp3 instead.`\n });\n }\n if (instructions != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"instructions\",\n details: \"Mistral speech models do not support the `instructions` option. Use a reference audio clip to guide delivery.\"\n });\n }\n if (speed != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"speed\",\n details: \"Mistral speech models do not support the `speed` option. It was ignored.\"\n });\n }\n if (language != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"language\",\n details: \"Mistral speech models do not support the `language` option. Language is inferred from the input text and voice.\"\n });\n }\n const refAudio = mistralOptions == null ? void 0 : mistralOptions.refAudio;\n const requestBody = {\n model: this.modelId,\n input: text,\n voice_id: refAudio == null ? voice : void 0,\n ref_audio: refAudio,\n response_format: responseFormat,\n stream: false\n };\n const requestBodyValues = {\n ...requestBody,\n ref_audio: refAudio == null ? void 0 : \"[redacted]\"\n };\n return { requestBody, requestBodyValues, warnings };\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e;\n const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();\n const { requestBody, requestBodyValues, warnings } = await this.getArgs(options);\n const {\n value: response,\n responseHeaders,\n rawValue: rawResponse\n } = await postToApi({\n url: `${this.config.baseURL}/audio/speech`,\n headers: combineHeaders3(\n { \"Content-Type\": \"application/json\" },\n (_e = (_d = this.config).headers) == null ? void 0 : _e.call(_d),\n options.headers\n ),\n body: {\n content: JSON.stringify(requestBody),\n values: requestBodyValues\n },\n failedResponseHandler: mistralFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler3(\n mistralSpeechResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n return {\n audio: response.audio_data,\n warnings,\n request: {\n body: JSON.stringify(requestBodyValues)\n },\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders,\n body: rawResponse\n }\n };\n }\n};\nvar mistralSpeechResponseSchema = z6.object({\n audio_data: z6.string()\n});\n\n// src/version.ts\nvar VERSION = true ? \"3.0.51\" : \"0.0.0-test\";\n\n// src/mistral-provider.ts\nfunction createMistral(options = {}) {\n var _a;\n const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : \"https://api.mistral.ai/v1\";\n const getHeaders = () => withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"MISTRAL_API_KEY\",\n description: \"Mistral\"\n })}`,\n ...options.headers\n },\n `ai-sdk/mistral/${VERSION}`\n );\n const createChatModel = (modelId) => new MistralChatLanguageModel(modelId, {\n provider: \"mistral.chat\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n generateId: options.generateId\n });\n const createEmbeddingModel = (modelId) => new MistralEmbeddingModel(modelId, {\n provider: \"mistral.embedding\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch\n });\n const createSpeechModel = (modelId) => new MistralSpeechModel(modelId, {\n provider: \"mistral.speech\",\n baseURL,\n headers: getHeaders,\n fetch: options.fetch\n });\n const provider = function(modelId) {\n if (new.target) {\n throw new Error(\n \"The Mistral model function cannot be called with the new keyword.\"\n );\n }\n return createChatModel(modelId);\n };\n provider.specificationVersion = \"v3\";\n provider.languageModel = createChatModel;\n provider.chat = createChatModel;\n provider.embedding = createEmbeddingModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbedding = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n provider.speech = createSpeechModel;\n provider.speechModel = createSpeechModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n return provider;\n}\nvar mistral = createMistral();\nexport {\n VERSION,\n createMistral,\n mistral\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";iZAuBA,SAAS,CAAmB,CAAC,EAAO,CAClC,IAAI,EAAI,EAAI,EAAI,EAAI,EACpB,GAAI,GAAS,KACX,MAAO,CACL,YAAa,CACX,MAAY,OACZ,QAAc,OACd,UAAgB,OAChB,WAAiB,MACnB,EACA,aAAc,CACZ,MAAY,OACZ,KAAW,OACX,UAAgB,MAClB,EACA,IAAU,MACZ,EAEF,IAA2B,cAArB,EACyB,kBAAzB,GAAmB,EACnB,GAAmB,GAAM,GAAM,EAAK,EAAM,oBAAsB,KAAO,GAAM,EAAK,EAAM,wBAA0B,KAAY,OAAI,EAAG,gBAAkB,KAAO,GAAM,EAAK,EAAM,uBAAyB,KAAY,OAAI,EAAG,gBAAkB,KAAO,EAAK,EAC/P,MAAO,CACL,YAAa,CACX,MAAO,EACP,QAAS,EAAe,EACxB,UAAW,GAAwB,OACnC,WAAiB,MACnB,EACA,aAAc,CACZ,MAAO,EACP,KAAM,EACN,UAAgB,MAClB,EACA,IAAK,CACP,EAQF,SAAS,CAAa,EACpB,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AQ,OAChB,wBAAyB,kBACzB,YAAa,SACf,CAAC,OACE,EAAQ,OACb,EACA,kBAAkB,IACpB,EACM,EAAkB,CAAC,IAAY,IAAI,GAAyB,EAAS,CACzE,SAAU,eACV,UACA,QAAS,EACT,MAAO,EAAQ,MACf,WAAY,EAAQ,UACtB,CAAC,EACK,EAAuB,CAAC,IAAY,IAAI,GAAsB,EAAS,CAC3E,SAAU,oBACV,UACA,QAAS,EACT,MAAO,EAAQ,KACjB,CAAC,EACK,EAAoB,CAAC,IAAY,IAAI,GAAmB,EAAS,CACrE,SAAU,iBACV,UACA,QAAS,EACT,MAAO,EAAQ,KACjB,CAAC,EACK,EAAW,QAAQ,CAAC,EAAS,CACjC,GAAI,WACF,MAAU,MACR,mEACF,EAEF,OAAO,EAAgB,CAAO,GAchC,OAZA,EAAS,qBAAuB,KAChC,EAAS,cAAgB,EACzB,EAAS,KAAO,EAChB,EAAS,UAAY,EACrB,EAAS,eAAiB,EAC1B,EAAS,cAAgB,EACzB,EAAS,mBAAqB,EAC9B,EAAS,OAAS,EAClB,EAAS,YAAc,EACvB,EAAS,WAAa,CAAC,IAAY,CACjC,MAAM,IAAI,EAAiB,CAAE,UAAS,UAAW,YAAa,CAAC,GAE1D,EAET,IAAI,GAAU,GAAc", | ||
| "debugId": "B6E23835B5DD1DDC64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/add.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\"\nimport { Effect } from \"effect\"\nimport { applyEdits, modify, parse, type ParseError } from \"jsonc-parser\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Npm } from \"@opencode-ai/util/npm\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { resolveConfigPath } from \"../mcp/add\"\nimport { Config } from \"../../../config\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.add,\n Effect.fn(\"cli.plugin.add\")(function* (input) {\n if (!(yield* Effect.promise(() => Npm.isInstallablePackage(input.package))))\n return yield* Effect.fail(new Error(\"Plugin target must be an npm registry package or Git package specifier\"))\n const npm = yield* Npm.Service\n const installed = yield* npm.add(input.package, { subpaths: [\"server\", \"\"] })\n const tui = yield* npm.resolve(input.package, { subpaths: [\"tui\"] })\n const target = configurationTarget(installed.entrypoint, tui.entrypoint)\n if (!target)\n return yield* Effect.fail(new Error(`Plugin package has no server or TUI entrypoint: ${input.package}`))\n\n if (target === \"server\") {\n const global = yield* Global.Service\n const configPath = yield* Effect.promise(() => resolveConfigPath(global.config))\n const changed = yield* Effect.promise(() => writePluginConfig(configPath, input.package))\n process.stdout.write(\n changed\n ? `Plugin \"${input.package}\" installed and added to ${configPath}${EOL}`\n : `Plugin \"${input.package}\" is already configured in ${configPath}${EOL}`,\n )\n return\n }\n\n const config = yield* Config.Service\n yield* config.update((draft) => {\n if (configured(draft.plugins, input.package)) return\n draft.plugins = [...(draft.plugins ?? []), input.package]\n })\n process.stdout.write(`TUI plugin \"${input.package}\" installed and added to ${config.path}${EOL}`)\n }),\n)\n\nexport function configurationTarget(server?: string, tui?: string) {\n if (server) return \"server\" as const\n if (tui) return \"tui\" as const\n}\n\nexport async function writePluginConfig(configPath: string, spec: string) {\n const text = await readFile(configPath, \"utf8\").catch((error) => {\n if (typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\") return \"{}\"\n throw error\n })\n const errors: ParseError[] = []\n const config: unknown = parse(text, errors, { allowTrailingComma: true })\n if (errors.length || typeof config !== \"object\" || config === null || Array.isArray(config))\n throw new Error(`Invalid global configuration: ${configPath}`)\n const plugins = \"plugins\" in config ? config.plugins : undefined\n if (plugins !== undefined && !Array.isArray(plugins)) throw new Error(`Invalid plugins configuration: ${configPath}`)\n if (configured(plugins, spec)) return false\n\n const updated = applyEdits(\n text,\n modify(text, [\"plugins\"], [...(plugins ?? []), spec], { formattingOptions: { tabSize: 2, insertSpaces: true } }),\n )\n await mkdir(path.dirname(configPath), { recursive: true })\n const temporary = configPath + \".tmp\"\n await writeFile(temporary, updated.endsWith(\"\\n\") ? updated : updated + \"\\n\", { mode: 0o600 })\n await rename(temporary, configPath)\n return true\n}\n\nfunction configured(plugins: readonly unknown[] | undefined, spec: string) {\n return plugins?.some(\n (entry) =>\n entry === spec || (typeof entry === \"object\" && entry !== null && \"package\" in entry && entry.package === spec),\n )\n}\n" | ||
| ], | ||
| "mappings": ";gwBAAA,cAAS,WACT,oBACA,gBAAS,cAAO,YAAU,eAAQ,oBAUlC,IAAe,IAAQ,QACrB,EAAS,SAAS,OAAO,SAAS,IAClC,EAAO,GAAG,gBAAgB,EAAE,SAAU,CAAC,EAAO,CAC5C,GAAI,EAAE,MAAO,EAAO,QAAQ,IAAM,EAAI,qBAAqB,EAAM,OAAO,CAAC,GACvE,OAAO,MAAO,EAAO,KAAS,MAAM,wEAAwE,CAAC,EAC/G,IAAM,EAAM,MAAO,EAAI,QACjB,EAAY,MAAO,EAAI,IAAI,EAAM,QAAS,CAAE,SAAU,CAAC,SAAU,EAAE,CAAE,CAAC,EACtE,EAAM,MAAO,EAAI,QAAQ,EAAM,QAAS,CAAE,SAAU,CAAC,KAAK,CAAE,CAAC,EAC7D,EAAS,EAAoB,EAAU,WAAY,EAAI,UAAU,EACvE,GAAI,CAAC,EACH,OAAO,MAAO,EAAO,KAAS,MAAM,mDAAmD,EAAM,SAAS,CAAC,EAEzG,GAAI,IAAW,SAAU,CACvB,IAAM,EAAS,MAAO,EAAO,QACvB,EAAa,MAAO,EAAO,QAAQ,IAAM,EAAkB,EAAO,MAAM,CAAC,EACzE,EAAU,MAAO,EAAO,QAAQ,IAAM,EAAkB,EAAY,EAAM,OAAO,CAAC,EACxF,QAAQ,OAAO,MACb,EACI,WAAW,EAAM,mCAAmC,IAAa,IACjE,WAAW,EAAM,qCAAqC,IAAa,GACzE,EACA,OAGF,IAAM,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AM,CAAE,KAAM,GAAM,CAAC,EAC7F,MAAM,EAAO,EAAW,CAAU,EAC3B,GAGT,SAAS,CAAU,CAAC,EAAyC,EAAc,CACzE,OAAO,GAAS,KACd,CAAC,IACC,IAAU,GAAS,OAAO,IAAU,UAAY,IAAU,OAAQ,YAAa,IAAS,EAAM,UAAY,CAC9G", | ||
| "debugId": "CC4E4C508ADA208864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "100B780FA641FD7064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mcp/list.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect } from \"effect\"\nimport { OpenCode, type McpServer } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.list,\n Effect.fn(\"cli.mcp.list\")(function* () {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const response = yield* Effect.promise(() => client.mcp.list({ location: { directory: process.cwd() } }))\n const servers = response.data.toSorted((a, b) => a.name.localeCompare(b.name))\n if (servers.length === 0) {\n process.stdout.write(\"No MCP servers configured\" + EOL)\n return\n }\n const width = Math.max(...servers.map((server) => server.name.length))\n const lines = servers.map(\n (server) => `${icon(server.status)} ${server.name.padEnd(width)} ${describe(server.status)}`,\n )\n process.stdout.write(lines.join(EOL) + EOL)\n }),\n)\n\nfunction icon(status: McpServer[\"status\"]) {\n switch (status.status) {\n case \"connected\":\n return \"✓\"\n case \"needs_auth\":\n return \"⚠\"\n case \"failed\":\n return \"✗\"\n default:\n return \"○\"\n }\n}\n\nfunction describe(status: McpServer[\"status\"]) {\n switch (status.status) {\n case \"needs_auth\":\n return \"needs authentication\"\n case \"failed\":\n return `failed: ${status.error}`\n default:\n return status.status\n }\n}\n" | ||
| ], | ||
| "mappings": ";08BAAA,cAAS,WAQT,IAAe,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,KAC/B,EAAO,GAAG,cAAc,EAAE,SAAU,EAAG,CACrC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAEpF,GADW,MAAO,EAAO,QAAQ,IAAM,EAAO,IAAI,KAAK,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,GAC/E,KAAK,SAAS,CAAC,EAAG,IAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC,EAC7E,GAAI,EAAQ,SAAW,EAAG,CACxB,QAAQ,OAAO,MAAM,4BAA8B,CAAG,EACtD,OAEF,IAAM,EAAQ,KAAK,IAAI,GAAG,EAAQ,IAAI,CAAC,IAAW,EAAO,KAAK,MAAM,CAAC,EAC/D,EAAQ,EAAQ,IACpB,CAAC,IAAW,GAAG,EAAK,EAAO,MAAM,KAAK,EAAO,KAAK,OAAO,CAAK,MAAM,EAAS,EAAO,MAAM,GAC5F,EACA,QAAQ,OAAO,MAAM,EAAM,KAAK,CAAG,EAAI,CAAG,EAC3C,CACH,EAEA,SAAS,CAAI,CAAC,EAA6B,CACzC,OAAQ,EAAO,YACR,YACH,MAAO,aACJ,aACH,MAAO,aACJ,SACH,MAAO,iBAEP,MAAO,UAIb,SAAS,CAAQ,CAAC,EAA6B,CAC7C,OAAQ,EAAO,YACR,aACH,MAAO,2BACJ,SACH,MAAO,WAAW,EAAO,gBAEzB,OAAO,EAAO", | ||
| "debugId": "67553A76926FD57464756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "BADC8F89D837A01264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "D1050E4F49B3A6BF64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../schema/src/filesystem.ts"], | ||
| "sourcesContent": [ | ||
| "export * as FileSystem from \"./filesystem.js\"\n\nimport { Schema } from \"effect\"\nimport { optional } from \"./schema.js\"\nimport { ephemeral, inventory } from \"./event.js\"\nimport { NonNegativeInt, PositiveInt, RelativePath } from \"./schema.js\"\n\nconst Changed = ephemeral({\n type: \"filesystem.changed\",\n schema: {\n file: Schema.String,\n event: Schema.Literals([\"add\", \"change\", \"unlink\"]),\n },\n})\nexport const Event = { Changed, Definitions: inventory(Changed) }\n\nexport interface Entry extends Schema.Schema.Type<typeof Entry> {}\nexport const Entry = Schema.Struct({\n path: RelativePath,\n type: Schema.Literals([\"file\", \"directory\"]),\n}).annotate({ identifier: \"FileSystem.Entry\" })\n\nexport interface Submatch extends Schema.Schema.Type<typeof Submatch> {}\nexport const Submatch = Schema.Struct({\n text: Schema.String,\n start: NonNegativeInt,\n end: NonNegativeInt,\n}).annotate({ identifier: \"FileSystem.Submatch\" })\n\nexport interface Match extends Schema.Schema.Type<typeof Match> {}\nexport const Match = Schema.Struct({\n entry: Entry,\n line: PositiveInt,\n offset: NonNegativeInt,\n text: Schema.String,\n submatches: Schema.Array(Submatch),\n}).annotate({ identifier: \"FileSystem.Match\" })\n\nexport class FindInput extends Schema.Class<FindInput>(\"FileSystem.FindInput\")({\n query: Schema.String,\n type: Schema.Literals([\"file\", \"directory\"]).pipe(optional),\n limit: PositiveInt.pipe(optional),\n}) {}\n" | ||
| ], | ||
| "mappings": ";oVAOA,IAAM,EAAU,EAAU,CACxB,KAAM,qBACN,OAAQ,CACN,KAAM,EAAO,OACb,MAAO,EAAO,SAAS,CAAC,MAAO,SAAU,QAAQ,CAAC,CACpD,CACF,CAAC,EACY,EAAQ,CAAE,UAAS,YAAa,EAAU,CAAO,CAAE,EAGnD,EAAQ,EAAO,OAAO,CACjC,KAAM,EACN,KAAM,EAAO,SAAS,CAAC,OAAQ,WAAW,CAAC,CAC7C,CAAC,EAAE,SAAS,CAAE,WAAY,kBAAmB,CAAC,EAGjC,EAAW,EAAO,OAAO,CACpC,KAAM,EAAO,OACb,MAAO,EACP,IAAK,CACP,CAAC,EAAE,SAAS,CAAE,WAAY,qBAAsB,CAAC,EAGpC,EAAQ,EAAO,OAAO,CACjC,MAAO,EACP,KAAM,EACN,OAAQ,EACR,KAAM,EAAO,OACb,WAAY,EAAO,MAAM,CAAQ,CACnC,CAAC,EAAE,SAAS,CAAE,WAAY,kBAAmB,CAAC,EAEvC,MAAM,UAAkB,EAAO,MAAiB,sBAAsB,EAAE,CAC7E,MAAO,EAAO,OACd,KAAM,EAAO,SAAS,CAAC,OAAQ,WAAW,CAAC,EAAE,KAAK,CAAQ,EAC1D,MAAO,EAAY,KAAK,CAAQ,CAClC,CAAC,CAAE,CAAC", | ||
| "debugId": "73E29114B122BCD364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/auth/form.ts", "src/commands/handlers/auth/login.ts"], | ||
| "sourcesContent": [ | ||
| "import { confirm, log, multiselect, password, select, text, type Option } from \"@clack/prompts\"\nimport { Effect } from \"effect\"\nimport type { FormAnswer, FormField, FormFields } from \"@opencode-ai/client\"\nimport { openUrl, prompt, requireInteractive } from \"../../../ui/prompt\"\n\nconst skip = Symbol(\"skip\")\nconst custom = Symbol(\"custom\")\n\nexport const answerForm = Effect.fn(\"cli.auth.form\")(function* (fields: FormFields | undefined) {\n if (!fields) return undefined\n yield* requireInteractive(\"Authentication form input requires an interactive terminal\")\n const answer: FormAnswer = {}\n for (const field of fields) {\n if (!active(field, answer)) continue\n const value = yield* answerField(field)\n if (value !== undefined) answer[field.key] = value\n }\n return answer\n})\n\nexport const secret = Effect.fn(\"cli.auth.secret\")(function* (message: string) {\n yield* requireInteractive(\"API key input requires an interactive terminal\")\n return yield* prompt<string>(() => password({ message, validate: (value) => (!value ? \"Required\" : undefined) }))\n})\n\nconst answerField = Effect.fn(\"cli.auth.form.field\")(function* (field: FormField) {\n const message = field.title ?? field.key\n if (field.description) log.info(field.description)\n if (field.type === \"external\") {\n log.info(field.url)\n yield* openUrl(field.url)\n const acknowledged = yield* prompt<boolean>(() =>\n confirm({ message: message || \"Continue after completing this step?\", initialValue: true }),\n )\n if (!acknowledged) return yield* Effect.fail(new Error(`${message || \"External step\"} is required`))\n return true\n }\n if (field.type === \"boolean\") {\n if (field.required) return yield* prompt<boolean>(() => confirm({ message, initialValue: field.default ?? true }))\n const options: Array<Option<boolean | typeof skip>> = [\n { value: true, label: \"Yes\" },\n { value: false, label: \"No\" },\n { value: skip, label: \"Skip\" },\n ]\n const value = yield* prompt<boolean | typeof skip>(() =>\n select<boolean | typeof skip>({\n message,\n options,\n initialValue: field.default ?? skip,\n }),\n )\n if (value === skip) return undefined\n return value\n }\n if (field.type === \"multiselect\") {\n const options: Array<Option<string | typeof custom>> = field.options.map((option) => ({\n value: option.value,\n label: option.label,\n hint: option.description,\n }))\n if (field.custom) options.push({ value: custom, label: \"Type another value\" })\n const values = yield* prompt<Array<string | typeof custom>>(() =>\n multiselect<string | typeof custom>({\n message,\n options,\n initialValues: field.default,\n required: field.required || (field.minItems ?? 0) > 0,\n }),\n )\n const selected = values.filter((value): value is string => value !== custom)\n if (values.includes(custom)) {\n selected.push(yield* prompt<string>(() => text({ message: \"Enter value\", validate: required })))\n }\n if (field.minItems !== undefined && selected.length < field.minItems) {\n return yield* Effect.fail(new Error(`Select at least ${field.minItems}`))\n }\n if (field.maxItems !== undefined && selected.length > field.maxItems) {\n return yield* Effect.fail(new Error(`Select at most ${field.maxItems}`))\n }\n return selected\n }\n if (field.type === \"string\" && field.options) {\n const options: Array<Option<string | typeof custom | typeof skip>> = field.options.map((option) => ({\n value: option.value,\n label: option.label,\n hint: option.description,\n }))\n if (field.custom) options.push({ value: custom, label: \"Type your own answer\" })\n if (!field.required) options.push({ value: skip, label: \"Skip\" })\n const value = yield* prompt<string | typeof custom | typeof skip>(() =>\n select<string | typeof custom | typeof skip>({ message, options, initialValue: field.default }),\n )\n if (value === skip) return undefined\n if (value !== custom) return value\n }\n const value = yield* prompt<string>(() =>\n text({\n message,\n placeholder: field.type === \"string\" ? field.placeholder : undefined,\n initialValue: field.default === undefined ? undefined : String(field.default),\n validate: (input) => validateText(field, input),\n }),\n )\n if (!value && !field.required) return undefined\n if (field.type === \"string\") return value\n return Number(value)\n})\n\nfunction active(field: FormField, answer: FormAnswer) {\n if (field.type === \"external\" || !field.when) return true\n return field.when.every((condition) => {\n const value = answer[condition.key]\n if (value === undefined) return false\n const matches = Array.isArray(value) ? value.includes(String(condition.value)) : value === condition.value\n return condition.op === \"eq\" ? matches : !matches\n })\n}\n\nfunction required(value: string | undefined) {\n return value ? undefined : \"Required\"\n}\n\nfunction validateText(field: Exclude<FormField, { type: \"boolean\" | \"external\" | \"multiselect\" }>, value?: string) {\n if (!value) return field.required ? \"Required\" : undefined\n if (field.type === \"number\" || field.type === \"integer\") {\n const number = Number(value)\n if (!Number.isFinite(number)) return \"Expected a number\"\n if (field.type === \"integer\" && !Number.isInteger(number)) return \"Expected an integer\"\n if (typeof field.minimum === \"number\" && number < field.minimum) return `Must be at least ${field.minimum}`\n if (typeof field.maximum === \"number\" && number > field.maximum) return `Must be at most ${field.maximum}`\n return undefined\n }\n if (field.minLength !== undefined && value.length < field.minLength)\n return `Must be at least ${field.minLength} characters`\n if (field.maxLength !== undefined && value.length > field.maxLength)\n return `Must be at most ${field.maxLength} characters`\n if (field.pattern) {\n try {\n if (!new RegExp(field.pattern).test(value)) return \"Invalid format\"\n } catch {\n return \"Invalid format\"\n }\n }\n if (field.format === \"uri\" && !URL.canParse(value)) return \"Expected a URL\"\n if (field.format === \"email\" && !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value)) return \"Expected an email address\"\n if (field.format === \"date\") {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) return \"Expected a date\"\n const date = new Date(`${value}T00:00:00.000Z`)\n if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== value) return \"Expected a date\"\n }\n if (field.format === \"date-time\" && Number.isNaN(Date.parse(value))) return \"Expected a date and time\"\n return undefined\n}\n", | ||
| "import { autocomplete, intro, log, outro, select, spinner, text } from \"@clack/prompts\"\nimport { Effect, Option } from \"effect\"\nimport type { FormAnswer, IntegrationInfo, OpenCodeClient } from \"@opencode-ai/client\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { handlePromptErrors, openUrl, prompt, requireInteractive } from \"../../../ui/prompt\"\nimport { answerForm, secret } from \"./form\"\nimport {\n createClient,\n connectMethods,\n loadIntegrations,\n location,\n request,\n resolveIntegration,\n resolveMethod,\n type ConnectMethod,\n} from \"./shared\"\n\nconst integrationPriority = new Map([\n [\"opencode\", 0],\n [\"opencode-go\", 1],\n [\"openai\", 2],\n [\"github-copilot\", 3],\n [\"google\", 4],\n [\"anthropic\", 5],\n [\"openrouter\", 6],\n [\"vercel\", 7],\n])\n\nexport default Runtime.handler(\n Commands.commands.auth.commands.login,\n Effect.fn(\"cli.auth.login\")((input) =>\n login({\n target: Option.getOrUndefined(input.target),\n method: Option.getOrUndefined(input.method),\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n }).pipe(handlePromptErrors),\n ),\n)\n\nconst login = Effect.fn(\"cli.auth.login.run\")(function* (input: {\n target?: string\n method?: string\n server?: string\n standalone: boolean\n}) {\n if (!input.target)\n yield* requireInteractive(\"Pass an integration ID or name when running without an interactive terminal\")\n intro(\"Connect an integration\")\n const client = yield* createClient({ server: input.server, standalone: input.standalone })\n const integration = yield* findIntegration(client, input.target)\n const methods = connectMethods(integration)\n if (methods.length === 0) yield* Effect.fail(new Error(`${integration.name} has no interactive login methods`))\n const method = yield* chooseMethod(methods, input.method)\n const answer = method.type === \"command\" ? undefined : yield* answerForm(method.form)\n yield* authenticate(client, integration, method, answer)\n outro(\"Done\")\n})\n\nconst findIntegration = Effect.fn(\"cli.auth.login.integration\")(function* (client: OpenCodeClient, target?: string) {\n if (target && URL.canParse(target)) {\n const protocol = new URL(target).protocol\n if (protocol === \"http:\" || protocol === \"https:\") {\n const progress = spinner()\n progress.start(\"Discovering authentication provider...\")\n yield* request((signal) => client.integration.wellknown.add({ url: target, location }, { signal })).pipe(\n Effect.tap(() => Effect.sync(() => progress.stop(\"Authentication provider discovered\"))),\n Effect.tapCause(() => Effect.sync(() => progress.stop(\"Discovery failed\", 1))),\n )\n }\n }\n const integrations = yield* loadIntegrations(client)\n if (target) return yield* resolveIntegration(integrations, target)\n const available = integrations\n .filter((integration) => connectMethods(integration).length > 0)\n .toSorted(\n (a, b) =>\n (integrationPriority.get(a.id) ?? integrationPriority.size) -\n (integrationPriority.get(b.id) ?? integrationPriority.size) ||\n a.name.localeCompare(b.name) ||\n a.id.localeCompare(b.id),\n )\n if (available.length === 0) return yield* Effect.fail(new Error(\"No authentication integrations are available\"))\n const id = yield* prompt<string>(() =>\n autocomplete({\n message: \"Select integration\",\n maxItems: 8,\n options: available.map((integration) => {\n const option = { value: integration.id, label: integration.name, hint: integration.id }\n if (integration.connections.length > 0) return { ...option, hint: \"connected\" }\n if (integration.id === \"opencode\") return { ...option, hint: \"recommended\" }\n return option\n }),\n }),\n )\n return yield* resolveIntegration(available, id)\n})\n\nconst chooseMethod = Effect.fn(\"cli.auth.login.method\")(function* (methods: ConnectMethod[], target?: string) {\n if (target) return yield* resolveMethod(methods, target)\n if (methods.length === 1) return methods[0]\n yield* requireInteractive(\"Pass --method when running without an interactive terminal\")\n const id = yield* prompt<string>(() =>\n select({\n message: \"Select login method\",\n options: methods.map((method) => {\n if (method.type === \"key\") return { value: \"key\", label: method.label ?? \"API key\" }\n return { value: method.id, label: method.label }\n }),\n }),\n )\n return yield* resolveMethod(methods, id)\n})\n\nconst authenticate = Effect.fn(\"cli.auth.login.authenticate\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: ConnectMethod,\n answer?: FormAnswer,\n) {\n if (method.type === \"key\") return yield* keyLogin(client, integration, method, answer)\n if (method.type === \"command\") return yield* commandLogin(client, integration, method)\n return yield* oauthLogin(client, integration, method, answer)\n})\n\nconst keyLogin = Effect.fn(\"cli.auth.login.key\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: Extract<ConnectMethod, { type: \"key\" }>,\n answer?: FormAnswer,\n) {\n const key = yield* secret(method.label ?? `Enter your ${integration.name} API key`)\n const progress = spinner()\n progress.start(\"Saving credential...\")\n yield* request((signal) =>\n client.integration.connect.key({ integrationID: integration.id, key, answer, location }, { signal }),\n ).pipe(\n Effect.tap(() => Effect.sync(() => progress.stop(`Connected to ${integration.name}`))),\n Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))),\n )\n})\n\nconst oauthLogin = Effect.fn(\"cli.auth.login.oauth\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: Extract<ConnectMethod, { type: \"oauth\" }>,\n answer?: FormAnswer,\n) {\n const progress = spinner()\n progress.start(\"Starting authorization...\")\n const started = yield* request((signal) =>\n client.integration.oauth.connect(\n { integrationID: integration.id, methodID: method.id, answer, location },\n { signal },\n ),\n ).pipe(Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))))\n const attempt = started.data\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.oauth.cancel(\n { integrationID: integration.id, attemptID: attempt.attemptID, location },\n { signal: AbortSignal.timeout(5_000) },\n ),\n ).pipe(Effect.ignore),\n )\n progress.stop(\"Authorization started\")\n log.info(attempt.instructions)\n log.info(attempt.url)\n if (process.stdin.isTTY && process.stdout.isTTY) yield* openUrl(attempt.url)\n\n if (attempt.mode === \"code\") {\n yield* requireInteractive(\"This login requires an interactive terminal to enter the authorization code\")\n const code = yield* prompt<string>(() =>\n text({ message: \"Paste the authorization code\", validate: (value) => (!value ? \"Required\" : undefined) }),\n )\n const completing = spinner()\n completing.start(\"Completing authorization...\")\n yield* request((signal) =>\n client.integration.oauth.complete(\n { integrationID: integration.id, attemptID: attempt.attemptID, code, location },\n { signal },\n ),\n ).pipe(\n Effect.tap(() => Effect.sync(() => completing.stop(`Connected to ${integration.name}`))),\n Effect.tapCause(() => Effect.sync(() => completing.stop(\"Authentication failed\", 1))),\n )\n return\n }\n\n const waiting = spinner()\n waiting.start(\"Waiting for authorization...\")\n const status = yield* waitForOAuth(client, integration.id, attempt.attemptID).pipe(\n Effect.tapCause(() => Effect.sync(() => waiting.stop(\"Authentication failed\", 1))),\n )\n if (status.status === \"complete\") {\n waiting.stop(`Connected to ${integration.name}`)\n return\n }\n waiting.stop(\"Authentication failed\", 1)\n if (status.status === \"failed\") yield* Effect.fail(new Error(status.message))\n yield* Effect.fail(new Error(\"Authorization expired\"))\n})\n\nconst commandLogin = Effect.fn(\"cli.auth.login.command\")(function* (\n client: OpenCodeClient,\n integration: IntegrationInfo,\n method: Extract<ConnectMethod, { type: \"command\" }>,\n) {\n const progress = spinner()\n progress.start(\"Starting authentication command...\")\n const started = yield* request((signal) =>\n client.integration.command.connect({ integrationID: integration.id, methodID: method.id, location }, { signal }),\n ).pipe(Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))))\n yield* Effect.addFinalizer(() =>\n request(() =>\n client.integration.command.cancel(\n {\n integrationID: integration.id,\n attemptID: started.data.attemptID,\n location,\n },\n { signal: AbortSignal.timeout(5_000) },\n ),\n ).pipe(Effect.ignore),\n )\n const status = yield* waitForCommand(client, integration.id, started.data.attemptID, (message) =>\n progress.message(message.trim() || \"Waiting for authentication command...\"),\n ).pipe(Effect.tapCause(() => Effect.sync(() => progress.stop(\"Authentication failed\", 1))))\n if (status.status === \"complete\") {\n progress.stop(`Connected to ${integration.name}`)\n return\n }\n progress.stop(\"Authentication failed\", 1)\n if (status.status === \"failed\") yield* Effect.fail(new Error(status.message))\n yield* Effect.fail(new Error(\"Authentication expired\"))\n})\n\nconst waitForOAuth = Effect.fn(\"cli.auth.login.oauth.wait\")(function* (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n) {\n while (true) {\n const response = yield* request((signal) =>\n client.integration.oauth.status({ integrationID, attemptID, location }, { signal }),\n )\n if (response.data.status !== \"pending\") return response.data\n yield* Effect.sleep(500)\n }\n})\n\nconst waitForCommand = Effect.fn(\"cli.auth.login.command.wait\")(function* (\n client: OpenCodeClient,\n integrationID: string,\n attemptID: string,\n update: (message: string) => void,\n) {\n while (true) {\n const response = yield* request((signal) =>\n client.integration.command.status({ integrationID, attemptID, location }, { signal }),\n )\n if (response.data.status !== \"pending\") return response.data\n if (response.data.message) update(response.data.message)\n yield* Effect.sleep(500)\n }\n})\n" | ||
| ], | ||
| "mappings": ";05CAKA,IAAM,EAAO,OAAO,MAAM,EACpB,EAAS,OAAO,QAAQ,EAEjB,EAAa,EAAO,GAAG,eAAe,EAAE,SAAU,CAAC,EAAgC,CAC9F,GAAI,CAAC,EAAQ,OACb,MAAO,EAAmB,4DAA4D,EACtF,IAAM,EAAqB,CAAC,EAC5B,QAAW,KAAS,EAAQ,CAC1B,GAAI,CAAC,EAAO,EAAO,CAAM,EAAG,SAC5B,IAAM,EAAQ,MAAO,EAAY,CAAK,EACtC,GAAI,IAAU,OAAW,EAAO,EAAM,KAAO,EAE/C,OAAO,EACR,EAEY,EAAS,EAAO,GAAG,iBAAiB,EAAE,SAAU,CAAC,EAAiB,CAE7E,OADA,MAAO,EAAmB,gDAAgD,EACnE,MAAO,EAAe,IAAM,EAAS,CAAE,UAAS,SAAU,CAAC,IAAW,CAAC,EAAQ,WAAa,MAAW,C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,EAAS,MAAO,GAAe,EAAQ,EAAY,GAAI,EAAQ,KAAK,UAAW,CAAC,IACpF,EAAS,QAAQ,EAAQ,KAAK,GAAK,uCAAuC,CAC5E,EAAE,KAAK,EAAO,SAAS,IAAM,EAAO,KAAK,IAAM,EAAS,KAAK,wBAAyB,CAAC,CAAC,CAAC,CAAC,EAC1F,GAAI,EAAO,SAAW,WAAY,CAChC,EAAS,KAAK,gBAAgB,EAAY,MAAM,EAChD,OAGF,GADA,EAAS,KAAK,wBAAyB,CAAC,EACpC,EAAO,SAAW,SAAU,MAAO,EAAO,KAAS,MAAM,EAAO,OAAO,CAAC,EAC5E,MAAO,EAAO,KAAS,MAAM,wBAAwB,CAAC,EACvD,EAEK,GAAe,EAAO,GAAG,2BAA2B,EAAE,SAAU,CACpE,EACA,EACA,EACA,CACA,MAAO,GAAM,CACX,IAAM,EAAW,MAAO,EAAQ,CAAC,IAC/B,EAAO,YAAY,MAAM,OAAO,CAAE,gBAAe,YAAW,UAAS,EAAG,CAAE,QAAO,CAAC,CACpF,EACA,GAAI,EAAS,KAAK,SAAW,UAAW,OAAO,EAAS,KACxD,MAAO,EAAO,MAAM,GAAG,GAE1B,EAEK,GAAiB,EAAO,GAAG,6BAA6B,EAAE,SAAU,CACxE,EACA,EACA,EACA,EACA,CACA,MAAO,GAAM,CACX,IAAM,EAAW,MAAO,EAAQ,CAAC,IAC/B,EAAO,YAAY,QAAQ,OAAO,CAAE,gBAAe,YAAW,UAAS,EAAG,CAAE,QAAO,CAAC,CACtF,EACA,GAAI,EAAS,KAAK,SAAW,UAAW,OAAO,EAAS,KACxD,GAAI,EAAS,KAAK,QAAS,EAAO,EAAS,KAAK,OAAO,EACvD,MAAO,EAAO,MAAM,GAAG,GAE1B", | ||
| "debugId": "ED5448A1E938AC5A64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/mcp/add.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport path from \"node:path\"\nimport { readFile, stat, writeFile } from \"node:fs/promises\"\nimport { Effect, Option } from \"effect\"\nimport { applyEdits, modify } from \"jsonc-parser\"\nimport { Global } from \"@opencode-ai/util/global\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\n\nexport default Runtime.handler(\n Commands.commands.mcp.commands.add,\n Effect.fn(\"cli.mcp.add\")(function* (input) {\n const url = Option.getOrUndefined(input.url)\n const headers = Option.getOrUndefined(input.header)\n const environment = Option.getOrUndefined(input.env)\n // The CLI framework strands `--` operands on the root command, so read the local server command\n // straight from argv after `--`. This also lets the command carry its own flags (e.g. `npx -y`).\n const dash = process.argv.indexOf(\"--\")\n const command = dash === -1 ? [...input.command] : process.argv.slice(dash + 1)\n\n const hasCommand = command.length > 0\n if (url && hasCommand)\n return yield* Effect.fail(new Error(\"Provide either --url <url> or a command after --, not both\"))\n if (!url && !hasCommand) return yield* Effect.fail(new Error(\"Provide either --url <url> or a command after --\"))\n if (url && !URL.canParse(url)) return yield* Effect.fail(new Error(`Invalid URL: ${url}`))\n if (url && environment) return yield* Effect.fail(new Error(\"--env is only valid for local MCP servers\"))\n if (hasCommand && headers) return yield* Effect.fail(new Error(\"--header is only valid for remote MCP servers\"))\n\n const server = url\n ? { type: \"remote\" as const, url, ...(headers ? { headers } : {}) }\n : { type: \"local\" as const, command, ...(environment ? { environment } : {}) }\n\n const global = yield* Global.Service\n const configPath = yield* Effect.promise(() => resolveConfigPath(input.global ? global.config : process.cwd()))\n yield* Effect.promise(() => write(configPath, input.name, server))\n process.stdout.write(`MCP server \"${input.name}\" added to ${configPath}` + EOL)\n }),\n)\n\nexport async function resolveConfigPath(directory: string) {\n const candidates = [\n path.join(directory, \"opencode.json\"),\n path.join(directory, \"opencode.jsonc\"),\n path.join(directory, \".opencode\", \"opencode.json\"),\n path.join(directory, \".opencode\", \"opencode.jsonc\"),\n ]\n for (const candidate of candidates) {\n if (\n await stat(candidate).then(\n (info) => info.isFile(),\n () => false,\n )\n )\n return candidate\n }\n return candidates[0]\n}\n\nasync function write(configPath: string, name: string, server: unknown) {\n const text = await readFile(configPath, \"utf8\").catch((error) => {\n if (typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\") return \"{}\"\n throw error\n })\n const edits = modify(text, [\"mcp\", \"servers\", name], server, {\n formattingOptions: { tabSize: 2, insertSpaces: true },\n })\n await writeFile(configPath, applyEdits(text, edits))\n}\n" | ||
| ], | ||
| "mappings": ";wOAAA,cAAS,WACT,oBACA,mBAAS,UAAU,eAAM,oBAOzB,IAAe,IAAQ,QACrB,EAAS,SAAS,IAAI,SAAS,IAC/B,EAAO,GAAG,aAAa,EAAE,SAAU,CAAC,EAAO,CACzC,IAAM,EAAM,EAAO,eAAe,EAAM,GAAG,EACrC,EAAU,EAAO,eAAe,EAAM,MAAM,EAC5C,EAAc,EAAO,eAAe,EAAM,GAAG,EAG7C,EAAO,QAAQ,KAAK,QAAQ,IAAI,EAChC,EAAU,IAAS,GAAK,CAAC,GAAG,EAAM,OAAO,EAAI,QAAQ,KAAK,MAAM,EAAO,CAAC,EAExE,EAAa,EAAQ,OAAS,EACpC,GAAI,GAAO,EACT,OAAO,MAAO,EAAO,KAAS,MAAM,4DAA4D,CAAC,EACnG,GAAI,CAAC,GAAO,CAAC,EAAY,OAAO,MAAO,EAAO,KAAS,MAAM,kDAAkD,CAAC,EAChH,GAAI,GAAO,CAAC,IAAI,SAAS,CAAG,EAAG,OAAO,MAAO,EAAO,KAAS,MAAM,gBAAgB,GAAK,CAAC,EACzF,GAAI,GAAO,EAAa,OAAO,MAAO,EAAO,KAAS,MAAM,2CAA2C,CAAC,EACxG,GAAI,GAAc,EAAS,OAAO,MAAO,EAAO,KAAS,MAAM,+CAA+C,CAAC,EAE/G,IAAM,EAAS,EACX,CAAE,KAAM,SAAmB,SAAS,EAAU,CAAE,SAAQ,EAAI,CAAC,CAAG,EAChE,CAAE,KAAM,QAAkB,aAAa,EAAc,CAAE,aAAY,EAAI,CAAC,CAAG,EAEzE,EAAS,MAAO,EAAO,QACvB,EAAa,MAAO,EAAO,QAAQ,IAAM,EAAkB,EAAM,OAAS,EAAO,OAAS,QAAQ,IAAI,CAAC,CAAC,EAC9G,MAAO,EAAO,QAAQ,IAAM,EAAM,EAAY,EAAM,KAAM,CAAM,CAAC,EACjE,QAAQ,OAAO,MAAM,eAAe,EAAM,kBAAkB,IAAe,CAAG,EAC/E,CACH,EAEA,eAAsB,CAAiB,CAAC,EAAmB,CACzD,IAAM,EAAa,CACjB,EAAK,KAAK,EAAW,eAAe,EACpC,EAAK,KAAK,EAAW,gBAAgB,EACrC,EAAK,KAAK,EAAW,YAAa,eAAe,EACjD,EAAK,KAAK,EAAW,YAAa,gBAAgB,CACpD,EACA,QAAW,KAAa,EACtB,GACE,MAAM,EAAK,CAAS,EAAE,KACpB,CAAC,IAAS,EAAK,OAAO,EACtB,IAAM,EACR,EAEA,OAAO,EAEX,OAAO,EAAW,GAGpB,eAAe,CAAK,CAAC,EAAoB,EAAc,EAAiB,CACtE,IAAM,EAAO,MAAM,EAAS,EAAY,MAAM,EAAE,MAAM,CAAC,IAAU,CAC/D,GAAI,OAAO,IAAU,UAAY,IAAU,MAAQ,SAAU,GAAS,EAAM,OAAS,SAAU,MAAO,KACtG,MAAM,EACP,EACK,EAAQ,EAAO,EAAM,CAAC,MAAO,UAAW,CAAI,EAAG,EAAQ,CAC3D,kBAAmB,CAAE,QAAS,EAAG,aAAc,EAAK,CACtD,CAAC,EACD,MAAM,EAAU,EAAY,EAAW,EAAM,CAAK,CAAC", | ||
| "debugId": "B91ACBD0552699CF64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/restart.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\nimport { ServerConnection } from \"../../../services/server-connection\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.restart,\n Effect.fn(\"cli.service.restart\")(function* () {\n const options = yield* ServiceConfig.options()\n // Keep this explicit: automatic service replacement must preserve terminals.\n yield* ServerConnection.shutdownPersistentPty(options).pipe(Effect.ignore)\n yield* Service.stop(options)\n const transport = yield* Service.ensure(options)\n process.stdout.write(transport.url + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";+jCAAA,cAAS,WAQT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,QACnC,EAAO,GAAG,qBAAqB,EAAE,SAAU,EAAG,CAC5C,IAAM,EAAU,MAAO,EAAc,QAAQ,EAE7C,MAAO,EAAiB,sBAAsB,CAAO,EAAE,KAAK,EAAO,MAAM,EACzE,MAAO,EAAQ,KAAK,CAAO,EAC3B,IAAM,EAAY,MAAO,EAAQ,OAAO,CAAO,EAC/C,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH", | ||
| "debugId": "FE6FFC1F8308B30264756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/mini.ts", "src/mini-host.ts"], | ||
| "sourcesContent": [ | ||
| "import { Service, type Endpoint } from \"@opencode-ai/client/effect/service\"\nimport { ClientError, OpenCode, type OpenCodeClient } from \"@opencode-ai/client/promise\"\nimport type { MiniFrontendInput } from \"@opencode-ai/tui/mini\"\nimport { setTimeout } from \"node:timers/promises\"\nimport { readStdin } from \"./util/io\"\nimport { createMiniHost, INTERACTIVE_INPUT_ERROR, usingInteractiveStdin } from \"./mini-host\"\nimport { parseSessionTargetModel, resolveSessionTarget, type SessionTargetPreparation } from \"./session-target\"\nimport { Env } from \"./env\"\n\nexport type MiniCommandInput = {\n server: {\n endpoint: Endpoint\n reconnect?: (signal: AbortSignal) => Promise<Endpoint>\n }\n continue?: boolean\n session?: string\n fork?: boolean\n model?: string\n agent?: string\n prompt?: string\n replay?: boolean\n replayLimit?: number\n demo?: boolean\n tuiConfig?: MiniFrontendInput[\"tuiConfig\"]\n config?: MiniFrontendInput[\"config\"]\n paths: { home: string; state: string; log: string }\n}\n\ntype Model = MiniFrontendInput[\"model\"]\n\nclass MiniInputError extends Error {}\n\nexport async function runMini(input: MiniCommandInput) {\n try {\n validate(input)\n const result = await usingInteractiveStdin(async (terminal) => {\n const initialInput = mergeInput(process.stdin.isTTY ? undefined : await readStdin(), input.prompt)\n const frontendTask = import(\"@opencode-ai/tui/mini\")\n const directory = localDirectory()\n const connection = createMiniConnection(input.server)\n const sdk = connection.sdk\n const environment = input.server.reconnect ? Env.session() : undefined\n const requested = parseModel(input.model)\n const model = requested ? { providerID: requested.providerID, modelID: requested.id } : undefined\n const prepare = prepareTarget(input.agent)\n const resolveTarget = async (initial: OpenCodeClient, signal: AbortSignal) => {\n const resolved = await resolveMiniTarget({\n sdk: initial,\n reconnect: connection.reconnect,\n signal,\n resolve: (client) =>\n resolveSessionTarget({\n client,\n location: { directory },\n continue: input.continue,\n session: input.session,\n fork: input.fork,\n model: requested,\n agent: input.agent,\n environment,\n prepare,\n signal,\n }).catch((error) => {\n if (error instanceof Error && error.message === \"Session not found\")\n throw new MiniInputError(error.message)\n throw error\n }),\n })\n const target = resolved.value\n return {\n sdk: resolved.sdk,\n sessionID: target.session.id,\n sessionTitle: target.session.title,\n location: target.location,\n model: target.model ? { providerID: target.model.providerID, modelID: target.model.id } : undefined,\n variant: target.model?.variant,\n agent: target.agent,\n resume: target.resume,\n }\n }\n const create = (\n client: OpenCodeClient,\n next: {\n location: { directory: string; workspaceID?: string }\n agent: string | undefined\n model: Model\n variant: string | undefined\n },\n signal?: AbortSignal,\n ) =>\n resolveSessionTarget({\n client,\n location: { directory: next.location.directory, workspace: next.location.workspaceID },\n agent: next.agent,\n environment,\n model: next.model\n ? { providerID: next.model.providerID, id: next.model.modelID, variant: next.variant }\n : undefined,\n prepare,\n signal,\n }).then((target) => ({\n sessionID: target.session.id,\n sessionTitle: target.session.title,\n location: target.location,\n model: target.model ? { providerID: target.model.providerID, modelID: target.model.id } : undefined,\n variant: target.model?.variant,\n agent: target.agent,\n resume: false,\n }))\n const frontend = await frontendTask\n return frontend.runMiniFrontend({\n host: createMiniHost({ terminal, directory, paths: input.paths }),\n sdk,\n directory,\n target: resolveTarget,\n reconnect: connection.reconnect,\n createSession: create,\n agent: input.agent,\n model,\n variant: requested?.variant,\n files: [],\n initialInput,\n replay: input.replay ?? true,\n replayLimit: input.replayLimit,\n demo: input.demo,\n tuiConfig: input.tuiConfig,\n config: input.config,\n })\n })\n if (result.exitCode !== 0) process.exit(result.exitCode)\n } catch (error) {\n if (error instanceof MiniInputError || (error instanceof Error && error.message === INTERACTIVE_INPUT_ERROR))\n fail(error.message)\n throw error\n }\n}\n\n/** @internal Exported for CLI boundary tests. */\nexport function createMiniConnection(input: MiniCommandInput[\"server\"]) {\n const make = (endpoint: Endpoint) =>\n OpenCode.make({\n baseUrl: endpoint.url,\n headers: Service.headers(endpoint),\n })\n const reconnect = input.reconnect\n return {\n sdk: make(input.endpoint),\n reconnect: reconnect\n ? async (signal: AbortSignal) => {\n const endpoint = await reconnect(signal)\n return make(endpoint)\n }\n : undefined,\n }\n}\n\n/** @internal Exported for reconnect lifecycle tests. */\nexport async function resolveMiniTarget<A>(input: {\n sdk: OpenCodeClient\n reconnect?: (signal: AbortSignal) => Promise<OpenCodeClient>\n signal: AbortSignal\n resolve: (sdk: OpenCodeClient) => Promise<A>\n}) {\n let sdk = input.sdk\n while (true) {\n try {\n return { sdk, value: await input.resolve(sdk) }\n } catch (error) {\n if (!input.reconnect || !(error instanceof ClientError) || error.reason !== \"Transport\") throw error\n while (true) {\n try {\n sdk = await input.reconnect(input.signal)\n break\n } catch (resolveError) {\n if (input.signal.aborted) throw resolveError\n await setTimeout(250, undefined, { signal: input.signal })\n }\n }\n }\n }\n}\n\nexport function validateMiniTerminal() {\n if (!process.stdout.isTTY) fail(\"opencode mini requires a TTY stdout\")\n}\n\n/** @internal Exported for testing. */\nexport function mergeInput(piped: string | undefined, prompt: string | undefined) {\n if (!prompt) return piped || undefined\n if (!piped) return prompt\n return piped + \"\\n\" + prompt\n}\n\nfunction validate(input: MiniCommandInput) {\n validateMiniTerminal()\n if (input.replayLimit !== undefined && (!Number.isInteger(input.replayLimit) || input.replayLimit <= 0)) {\n fail(\"--replay-limit must be a positive integer\")\n }\n if (input.fork && !input.continue && !input.session) fail(\"--fork requires --continue or --session\")\n}\n\nfunction localDirectory(): string {\n const root = process.env.PWD ?? process.cwd()\n try {\n process.chdir(root)\n return process.cwd()\n } catch {\n throw new MiniInputError(`Failed to change directory to ${root}`)\n }\n}\n\nfunction parseModel(value?: string) {\n try {\n return parseSessionTargetModel(value)\n } catch {\n throw new MiniInputError(\"--model must use the format provider/model[#variant]\")\n }\n}\n\nfunction prepareTarget(requestedAgent?: string): SessionTargetPreparation {\n return async (input) => ({ model: input.model, agent: requestedAgent ?? input.agent })\n}\n\nfunction fail(message: string): never {\n process.stderr.write(`\\x1b[91m\\x1b[1mError: \\x1b[0m${message}\\n`)\n process.exit(1)\n}\n", | ||
| "import type { MiniFrontendInput } from \"@opencode-ai/tui/mini\"\nimport { createModelPreferenceRepository } from \"@opencode-ai/tui/model-preference\"\nimport fs from \"node:fs\"\nimport { readFile } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { ReadStream } from \"node:tty\"\nimport { OPENCODE_VERSION } from \"./version\"\n\nexport const INTERACTIVE_INPUT_ERROR = \"opencode mini requires a controlling terminal for input\"\n\nexport type InteractiveStdin = {\n stdin: NodeJS.ReadStream\n cleanup(): void\n}\n\ntype MiniHost = MiniFrontendInput[\"host\"]\n\nfunction preferences(statePath: string): MiniHost[\"preferences\"] {\n const repository = createModelPreferenceRepository(path.join(statePath, \"model.json\"))\n return {\n async resolveVariant(model) {\n if (!model) return\n return repository.resolveVariant(model)\n },\n async saveVariant(model, variant) {\n if (!model) return\n await repository.saveVariant(model, variant).catch(() => undefined)\n },\n }\n}\n\nfunction signal(name: \"SIGINT\" | \"SIGUSR2\"): MiniHost[\"signals\"][\"sigint\"] {\n return {\n subscribe(listener) {\n let subscribed = true\n process.on(name, listener)\n return () => {\n if (!subscribed) return\n subscribed = false\n process.off(name, listener)\n }\n },\n }\n}\n\nfunction createTrace(\n logPath: string,\n diagnostics: { pid: number; cwd: string; argv: string[] },\n): MiniHost[\"diagnostics\"][\"trace\"] {\n if (!process.env.OPENCODE_DIRECT_TRACE) return\n const stamp = new Date()\n .toISOString()\n .replace(/[-:]/g, \"\")\n .replace(/\\.\\d+Z$/, \"Z\")\n const target = path.join(logPath, \"direct\", `${stamp}-${diagnostics.pid}.jsonl`)\n const text = (data: unknown) =>\n JSON.stringify(data, (_key, value) => (typeof value === \"bigint\" ? String(value) : value), 0)\n fs.mkdirSync(path.dirname(target), { recursive: true })\n fs.writeFileSync(\n path.join(logPath, \"direct\", \"latest.json\"),\n text({\n time: new Date().toISOString(),\n ...diagnostics,\n path: target,\n }) + \"\\n\",\n )\n const trace = {\n write(type: string, data?: unknown) {\n fs.appendFileSync(\n target,\n text({\n time: new Date().toISOString(),\n pid: diagnostics.pid,\n type,\n data,\n }) + \"\\n\",\n )\n },\n }\n trace.write(\"trace.start\", {\n argv: diagnostics.argv,\n cwd: diagnostics.cwd,\n path: target,\n })\n return trace\n}\n\nfunction openTerminalStdin(target: string): NodeJS.ReadStream {\n return new ReadStream(fs.openSync(target, \"r\"))\n}\n\nexport function resolveInteractiveStdin(\n stdin: NodeJS.ReadStream = process.stdin,\n open: (target: string) => NodeJS.ReadStream = openTerminalStdin,\n platform: NodeJS.Platform = process.platform,\n): InteractiveStdin {\n if (stdin.isTTY) return { stdin, cleanup() {} }\n const target = platform === \"win32\" ? \"CONIN$\" : \"/dev/tty\"\n try {\n const source = open(target)\n let cleaned = false\n return {\n stdin: source,\n cleanup() {\n if (cleaned) return\n cleaned = true\n source.destroy()\n },\n }\n } catch (error) {\n throw new Error(INTERACTIVE_INPUT_ERROR, { cause: error })\n }\n}\n\n/** @internal Exported for owner-local resource cleanup tests. */\nexport async function usingInteractiveStdin<T>(\n run: (terminal: InteractiveStdin) => Promise<T>,\n resolve: () => InteractiveStdin = resolveInteractiveStdin,\n) {\n const terminal = resolve()\n try {\n return await run(terminal)\n } finally {\n terminal.cleanup()\n }\n}\n\n/** @internal Exported for owner-local host capability tests. */\nexport function createMiniHost(input: {\n terminal: InteractiveStdin\n directory: string\n paths: { home: string; state: string; log: string }\n}): MiniHost {\n const paths = input.paths\n const diagnostics = {\n pid: process.pid,\n cwd: input.directory,\n argv: process.argv.slice(2),\n }\n return {\n version: OPENCODE_VERSION,\n terminal: { stdin: input.terminal.stdin },\n platform: process.platform,\n stdout: {\n write(value) {\n process.stdout.write(value)\n },\n },\n files: {\n readText: (url) => readFile(new URL(url), \"utf8\"),\n },\n editor: {\n async open(options) {\n const { openEditor } = await import(\"@opencode-ai/tui/editor\")\n return openEditor(options)\n },\n },\n paths: { home: paths.home },\n signals: {\n sigint: signal(\"SIGINT\"),\n sigusr2: signal(\"SIGUSR2\"),\n },\n startup: {\n showTiming: [\"1\", \"true\"].includes(process.env.OPENCODE_SHOW_TTFD?.toLowerCase() ?? \"\"),\n now: () => performance.now(),\n },\n diagnostics: {\n trace: createTrace(paths.log, diagnostics),\n },\n preferences: preferences(paths.state),\n }\n}\n" | ||
| ], | ||
| "mappings": ";izBAGA,qBAAS,wBCDT,kBACA,mBAAS,oBACT,oBACA,qBAAS,YAGF,IAAM,EAA0B,0DASvC,SAAS,CAAW,CAAC,EAA4C,CAC/D,IAAM,EAAa,EAAgC,EAAK,KAAK,EAAW,YAAY,CAAC,EACrF,MAAO,MACC,eAAc,CAAC,EAAO,CAC1B,GAAI,CAAC,EAAO,OACZ,OAAO,EAAW,eAAe,CAAK,QAElC,YAAW,CAAC,EAAO,EAAS,CAChC,GAAI,CAAC,EAAO,OACZ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kB,EAAM,KAAM,GAGtF,SAAS,CAAI,CAAC,EAAwB,CACpC,QAAQ,OAAO,MAAM,gCAAgC;AAAA,CAAW,EAChE,QAAQ,KAAK,CAAC", | ||
| "debugId": "2F202D7BA0A9B00864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/auth/list.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { createClient, loadIntegrations } from \"./shared\"\nimport { errorMessage } from \"../../../util/error\"\n\nexport default Runtime.handler(Commands.commands.auth.commands.list, (input) =>\n list(input).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n process.stderr.write(errorMessage(error) + EOL)\n process.exitCode = 1\n }),\n ),\n ),\n)\n\nconst list = Effect.fn(\"cli.auth.list\")(function* (input) {\n const client = yield* createClient({ server: Option.getOrUndefined(input.server), standalone: input.standalone })\n const integrations = (yield* loadIntegrations(client)).filter((integration) => integration.connections.length > 0)\n if (input.format === \"json\") {\n process.stdout.write(\n JSON.stringify(\n integrations.map((integration) => ({\n id: integration.id,\n name: integration.name,\n connections: integration.connections,\n })),\n null,\n 2,\n ) + EOL,\n )\n return\n }\n const rows = integrations.flatMap((integration) =>\n integration.connections.map((connection) => ({\n integration: integration.name,\n source: connection.type === \"credential\" ? connection.label : connection.name,\n type: connection.type === \"credential\" ? \"stored\" : \"environment\",\n })),\n )\n if (rows.length === 0) {\n process.stdout.write(\"No authenticated integrations\" + EOL)\n return\n }\n const width = Math.max(...rows.map((row) => row.integration.length)) + 2\n process.stdout.write(\n rows.map((row) => row.integration.padEnd(width) + row.source.padEnd(28) + row.type).join(EOL) + EOL,\n )\n})\n" | ||
| ], | ||
| "mappings": ";gpCAAA,cAAS,WAOT,IAAe,IAAQ,QAAQ,EAAS,SAAS,KAAK,SAAS,KAAM,CAAC,IACpE,EAAK,CAAK,EAAE,KACV,EAAO,MAAM,CAAC,IACZ,EAAO,KAAK,IAAM,CAChB,QAAQ,OAAO,MAAM,EAAa,CAAK,EAAI,CAAG,EAC9C,QAAQ,SAAW,EACpB,CACH,CACF,CACF,EAEM,EAAO,EAAO,GAAG,eAAe,EAAE,SAAU,CAAC,EAAO,CACxD,IAAM,EAAS,MAAO,EAAa,CAAE,OAAQ,EAAO,eAAe,EAAM,MAAM,EAAG,WAAY,EAAM,UAAW,CAAC,EAC1G,GAAgB,MAAO,EAAiB,CAAM,GAAG,OAAO,CAAC,IAAgB,EAAY,YAAY,OAAS,CAAC,EACjH,GAAI,EAAM,SAAW,OAAQ,CAC3B,QAAQ,OAAO,MACb,KAAK,UACH,EAAa,IAAI,CAAC,KAAiB,CACjC,GAAI,EAAY,GAChB,KAAM,EAAY,KAClB,YAAa,EAAY,WAC3B,EAAE,EACF,KACA,CACF,EAAI,CACN,EACA,OAEF,IAAM,EAAO,EAAa,QAAQ,CAAC,IACjC,EAAY,YAAY,IAAI,CAAC,KAAgB,CAC3C,YAAa,EAAY,KACzB,OAAQ,EAAW,OAAS,aAAe,EAAW,MAAQ,EAAW,KACzE,KAAM,EAAW,OAAS,aAAe,SAAW,aACtD,EAAE,CACJ,EACA,GAAI,EAAK,SAAW,EAAG,CACrB,QAAQ,OAAO,MAAM,gCAAkC,CAAG,EAC1D,OAEF,IAAM,EAAQ,KAAK,IAAI,GAAG,EAAK,IAAI,CAAC,IAAQ,EAAI,YAAY,MAAM,CAAC,EAAI,EACvE,QAAQ,OAAO,MACb,EAAK,IAAI,CAAC,IAAQ,EAAI,YAAY,OAAO,CAAK,EAAI,EAAI,OAAO,OAAO,EAAE,EAAI,EAAI,IAAI,EAAE,KAAK,CAAG,EAAI,CAClG,EACD", | ||
| "debugId": "975346A42302DBE364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/debug/config.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { OpenCode } from \"@opencode-ai/client\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.debug.commands.config,\n Effect.fn(\"cli.debug.config\")(function* () {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })\n const entries = yield* Effect.promise(() => client.config.get({ location: { directory: process.cwd() } }))\n process.stdout.write(JSON.stringify(entries, null, 2) + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";08BAAA,cAAS,WAQT,IAAe,IAAQ,QACrB,EAAS,SAAS,MAAM,SAAS,OACjC,EAAO,GAAG,kBAAkB,EAAE,SAAU,EAAG,CACzC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAS,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EACpF,EAAU,MAAO,EAAO,QAAQ,IAAM,EAAO,OAAO,IAAI,CAAE,SAAU,CAAE,UAAW,QAAQ,IAAI,CAAE,CAAE,CAAC,CAAC,EACzG,QAAQ,OAAO,MAAM,KAAK,UAAU,EAAS,KAAM,CAAC,EAAI,CAAG,EAC5D,CACH", | ||
| "debugId": "6ADBEDCED046BB0964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/createCredentialChain.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.68/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentity.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.68/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/resolveLogins.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.68/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentityPool.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.68/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/IndexedDbStorage.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.68/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/InMemoryStorage.js", "../../node_modules/.bun/@aws-sdk+credential-provider-cognito-identity@3.972.68/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/localStorage.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromCognitoIdentity.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromCognitoIdentityPool.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromContainerMetadata.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromEnv.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromIni.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromInstanceMetadata.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromLoginCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-node@3.972.80/node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js", "../../node_modules/.bun/@aws-sdk+credential-provider-node@3.972.80/node_modules/@aws-sdk/credential-provider-node/dist-es/remoteProvider.js", "../../node_modules/.bun/@aws-sdk+credential-provider-node@3.972.80/node_modules/@aws-sdk/credential-provider-node/dist-es/runtime/memoize-chain.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromNodeProviderChain.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromProcess.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromSSO.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromTemporaryCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromTemporaryCredentials.base.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromTokenFile.js", "../../node_modules/.bun/@aws-sdk+credential-providers@3.1057.0/node_modules/@aws-sdk/credential-providers/dist-es/fromWebToken.js"], | ||
| "sourcesContent": [ | ||
| "import { ProviderError } from \"@smithy/core/config\";\nexport const createCredentialChain = (...credentialProviders) => {\n let expireAfter = -1;\n const baseFunction = async (awsIdentityProperties) => {\n const credentials = await propertyProviderChain(...credentialProviders)(awsIdentityProperties);\n if (!credentials.expiration && expireAfter !== -1) {\n credentials.expiration = new Date(Date.now() + expireAfter);\n }\n return credentials;\n };\n const withOptions = Object.assign(baseFunction, {\n expireAfter(milliseconds) {\n if (milliseconds < 5 * 60_000) {\n throw new Error(\"@aws-sdk/credential-providers - createCredentialChain(...).expireAfter(ms) may not be called with a duration lower than five minutes.\");\n }\n expireAfter = milliseconds;\n return withOptions;\n },\n });\n return withOptions;\n};\nexport const propertyProviderChain = (...providers) => async (awsIdentityProperties) => {\n if (providers.length === 0) {\n throw new ProviderError(\"No providers in chain\", { tryNextLink: false });\n }\n let lastProviderError;\n for (const provider of providers) {\n try {\n return await provider(awsIdentityProperties);\n }\n catch (err) {\n lastProviderError = err;\n if (err?.tryNextLink) {\n continue;\n }\n throw err;\n }\n }\n throw lastProviderError;\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { resolveLogins } from \"./resolveLogins\";\nexport function fromCognitoIdentity(parameters) {\n return async (awsIdentityProperties) => {\n parameters.logger?.debug(\"@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity\");\n const { GetCredentialsForIdentityCommand, CognitoIdentityClient } = await import(\"./loadCognitoIdentity.js\");\n const fromConfigs = (property) => parameters.clientConfig?.[property] ??\n parameters.parentClientConfig?.[property] ??\n awsIdentityProperties?.callerClientConfig?.[property];\n const { Credentials: { AccessKeyId = throwOnMissingAccessKeyId(parameters.logger), Expiration, SecretKey = throwOnMissingSecretKey(parameters.logger), SessionToken, } = throwOnMissingCredentials(parameters.logger), } = await (parameters.client ??\n new CognitoIdentityClient(Object.assign({}, parameters.clientConfig ?? {}, {\n region: fromConfigs(\"region\"),\n profile: fromConfigs(\"profile\"),\n userAgentAppId: fromConfigs(\"userAgentAppId\"),\n }))).send(new GetCredentialsForIdentityCommand({\n CustomRoleArn: parameters.customRoleArn,\n IdentityId: parameters.identityId,\n Logins: parameters.logins ? await resolveLogins(parameters.logins) : undefined,\n }));\n return {\n identityId: parameters.identityId,\n accessKeyId: AccessKeyId,\n secretAccessKey: SecretKey,\n sessionToken: SessionToken,\n expiration: Expiration,\n };\n };\n}\nfunction throwOnMissingAccessKeyId(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no access key ID\", { logger });\n}\nfunction throwOnMissingCredentials(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no credentials\", { logger });\n}\nfunction throwOnMissingSecretKey(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no secret key\", { logger });\n}\n", | ||
| "export function resolveLogins(logins) {\n return Promise.all(Object.keys(logins).reduce((arr, name) => {\n const tokenOrProvider = logins[name];\n if (typeof tokenOrProvider === \"string\") {\n arr.push([name, tokenOrProvider]);\n }\n else {\n arr.push(tokenOrProvider().then((token) => [name, token]));\n }\n return arr;\n }, [])).then((resolvedPairs) => resolvedPairs.reduce((logins, [key, value]) => {\n logins[key] = value;\n return logins;\n }, {}));\n}\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { fromCognitoIdentity } from \"./fromCognitoIdentity\";\nimport { localStorage } from \"./localStorage\";\nimport { resolveLogins } from \"./resolveLogins\";\nexport function fromCognitoIdentityPool({ accountId, cache = localStorage(), client, clientConfig, customRoleArn, identityPoolId, logins, userIdentifier = !logins || Object.keys(logins).length === 0 ? \"ANONYMOUS\" : undefined, logger, parentClientConfig, }) {\n logger?.debug(\"@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity\");\n const cacheKey = userIdentifier\n ? `aws:cognito-identity-credentials:${identityPoolId}:${userIdentifier}`\n : undefined;\n let provider = async (awsIdentityProperties) => {\n const { GetIdCommand, CognitoIdentityClient } = await import(\"./loadCognitoIdentity.js\");\n const fromConfigs = (property) => clientConfig?.[property] ??\n parentClientConfig?.[property] ??\n awsIdentityProperties?.callerClientConfig?.[property];\n const _client = client ??\n new CognitoIdentityClient(Object.assign({}, clientConfig ?? {}, {\n region: fromConfigs(\"region\"),\n profile: fromConfigs(\"profile\"),\n userAgentAppId: fromConfigs(\"userAgentAppId\"),\n }));\n let identityId = (cacheKey && (await cache.getItem(cacheKey)));\n if (!identityId) {\n const { IdentityId = throwOnMissingId(logger) } = await _client.send(new GetIdCommand({\n AccountId: accountId,\n IdentityPoolId: identityPoolId,\n Logins: logins ? await resolveLogins(logins) : undefined,\n }));\n identityId = IdentityId;\n if (cacheKey) {\n Promise.resolve(cache.setItem(cacheKey, identityId)).catch(() => { });\n }\n }\n provider = fromCognitoIdentity({\n client: _client,\n customRoleArn,\n logins,\n identityId,\n });\n return provider(awsIdentityProperties);\n };\n return (awsIdentityProperties) => provider(awsIdentityProperties).catch(async (err) => {\n if (cacheKey) {\n Promise.resolve(cache.removeItem(cacheKey)).catch(() => { });\n }\n throw err;\n });\n}\nfunction throwOnMissingId(logger) {\n throw new CredentialsProviderError(\"Response from Amazon Cognito contained no identity ID\", { logger });\n}\n", | ||
| "const STORE_NAME = \"IdentityIds\";\nexport class IndexedDbStorage {\n dbName;\n constructor(dbName = \"aws:cognito-identity-ids\") {\n this.dbName = dbName;\n }\n getItem(key) {\n return this.withObjectStore(\"readonly\", (store) => {\n const req = store.get(key);\n return new Promise((resolve) => {\n req.onerror = () => resolve(null);\n req.onsuccess = () => resolve(req.result ? req.result.value : null);\n });\n }).catch(() => null);\n }\n removeItem(key) {\n return this.withObjectStore(\"readwrite\", (store) => {\n const req = store.delete(key);\n return new Promise((resolve, reject) => {\n req.onerror = () => reject(req.error);\n req.onsuccess = () => resolve();\n });\n });\n }\n setItem(id, value) {\n return this.withObjectStore(\"readwrite\", (store) => {\n const req = store.put({ id, value });\n return new Promise((resolve, reject) => {\n req.onerror = () => reject(req.error);\n req.onsuccess = () => resolve();\n });\n });\n }\n getDb() {\n const openDbRequest = self.indexedDB.open(this.dbName, 1);\n return new Promise((resolve, reject) => {\n openDbRequest.onsuccess = () => {\n resolve(openDbRequest.result);\n };\n openDbRequest.onerror = () => {\n reject(openDbRequest.error);\n };\n openDbRequest.onblocked = () => {\n reject(new Error(\"Unable to access DB\"));\n };\n openDbRequest.onupgradeneeded = () => {\n const db = openDbRequest.result;\n db.onerror = () => {\n reject(new Error(\"Failed to create object store\"));\n };\n db.createObjectStore(STORE_NAME, { keyPath: \"id\" });\n };\n });\n }\n withObjectStore(mode, action) {\n return this.getDb().then((db) => {\n const tx = db.transaction(STORE_NAME, mode);\n tx.oncomplete = () => db.close();\n return new Promise((resolve, reject) => {\n tx.onerror = () => reject(tx.error);\n resolve(action(tx.objectStore(STORE_NAME)));\n }).catch((err) => {\n db.close();\n throw err;\n });\n });\n }\n}\n", | ||
| "export class InMemoryStorage {\n store;\n constructor(store = {}) {\n this.store = store;\n }\n getItem(key) {\n if (key in this.store) {\n return this.store[key];\n }\n return null;\n }\n removeItem(key) {\n delete this.store[key];\n }\n setItem(key, value) {\n this.store[key] = value;\n }\n}\n", | ||
| "import { IndexedDbStorage } from \"./IndexedDbStorage\";\nimport { InMemoryStorage } from \"./InMemoryStorage\";\nconst inMemoryStorage = new InMemoryStorage();\nexport function localStorage() {\n if (typeof self === \"object\" && self.indexedDB) {\n return new IndexedDbStorage();\n }\n if (typeof window === \"object\" && window.localStorage) {\n return window.localStorage;\n }\n return inMemoryStorage;\n}\n", | ||
| "import { fromCognitoIdentity as _fromCognitoIdentity } from \"@aws-sdk/credential-provider-cognito-identity\";\nexport const fromCognitoIdentity = (options) => _fromCognitoIdentity({\n ...options,\n});\n", | ||
| "import { fromCognitoIdentityPool as _fromCognitoIdentityPool } from \"@aws-sdk/credential-provider-cognito-identity\";\nexport const fromCognitoIdentityPool = (options) => _fromCognitoIdentityPool({\n ...options,\n});\n", | ||
| "import { fromContainerMetadata as _fromContainerMetadata } from \"@smithy/credential-provider-imds\";\nexport const fromContainerMetadata = (init) => {\n init?.logger?.debug(\"@smithy/credential-provider-imds\", \"fromContainerMetadata\");\n return _fromContainerMetadata(init);\n};\n", | ||
| "import { fromEnv as _fromEnv } from \"@aws-sdk/credential-provider-env\";\nexport const fromEnv = (init) => _fromEnv(init);\n", | ||
| "import { fromIni as _fromIni } from \"@aws-sdk/credential-provider-ini\";\nexport const fromIni = (init = {}) => _fromIni({\n ...init,\n});\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { fromInstanceMetadata as _fromInstanceMetadata } from \"@smithy/credential-provider-imds\";\nexport const fromInstanceMetadata = (init) => {\n init?.logger?.debug(\"@smithy/credential-provider-imds\", \"fromInstanceMetadata\");\n return async () => _fromInstanceMetadata(init)().then((creds) => setCredentialFeature(creds, \"CREDENTIALS_IMDS\", \"0\"));\n};\n", | ||
| "import { fromLoginCredentials as _fromLoginCredentials, } from \"@aws-sdk/credential-provider-login\";\nexport const fromLoginCredentials = (init) => _fromLoginCredentials({\n ...init,\n});\n", | ||
| "import { ENV_KEY, ENV_SECRET, fromEnv } from \"@aws-sdk/credential-provider-env\";\nimport { CredentialsProviderError, ENV_PROFILE } from \"@smithy/core/config\";\nimport { remoteProvider } from \"./remoteProvider\";\nimport { memoizeChain } from \"./runtime/memoize-chain\";\nlet multipleCredentialSourceWarningEmitted = false;\nexport const defaultProvider = (init = {}) => memoizeChain([\n async () => {\n const profile = init.profile ?? process.env[ENV_PROFILE];\n if (profile) {\n const envStaticCredentialsAreSet = process.env[ENV_KEY] && process.env[ENV_SECRET];\n if (envStaticCredentialsAreSet) {\n if (!multipleCredentialSourceWarningEmitted) {\n const warnFn = init.logger?.warn && init.logger?.constructor?.name !== \"NoOpLogger\"\n ? init.logger.warn.bind(init.logger)\n : console.warn;\n warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:\n Multiple credential sources detected: \n Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set.\n This SDK will proceed with the AWS_PROFILE value.\n \n However, a future version may change this behavior to prefer the ENV static credentials.\n Please ensure that your environment only sets either the AWS_PROFILE or the\n AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair.\n`);\n multipleCredentialSourceWarningEmitted = true;\n }\n }\n throw new CredentialsProviderError(\"AWS_PROFILE is set, skipping fromEnv provider.\", {\n logger: init.logger,\n tryNextLink: true,\n });\n }\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromEnv\");\n return fromEnv(init)();\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromSSO\");\n const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init;\n if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {\n throw new CredentialsProviderError(\"Skipping SSO provider in default chain (inputs do not include SSO fields).\", { logger: init.logger });\n }\n const { fromSSO } = await import(\"@aws-sdk/credential-provider-sso\");\n return fromSSO(init)(awsIdentityProperties);\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromIni\");\n const { fromIni } = await import(\"@aws-sdk/credential-provider-ini\");\n return fromIni(init)(awsIdentityProperties);\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromProcess\");\n const { fromProcess } = await import(\"@aws-sdk/credential-provider-process\");\n return fromProcess(init)(awsIdentityProperties);\n },\n async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile\");\n const { fromTokenFile } = await import(\"@aws-sdk/credential-provider-web-identity\");\n return fromTokenFile(init)(awsIdentityProperties);\n },\n async () => {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - defaultProvider::remoteProvider\");\n return (await remoteProvider(init))();\n },\n async () => {\n throw new CredentialsProviderError(\"Could not load credentials from any providers\", {\n tryNextLink: false,\n logger: init.logger,\n });\n },\n], credentialsTreatedAsExpired);\nexport const credentialsWillNeedRefresh = (credentials) => credentials?.expiration !== undefined;\nexport const credentialsTreatedAsExpired = (credentials) => credentials?.expiration !== undefined && credentials.expiration.getTime() - Date.now() < 300000;\n", | ||
| "import { chain, CredentialsProviderError } from \"@smithy/core/config\";\nexport const ENV_IMDS_DISABLED = \"AWS_EC2_METADATA_DISABLED\";\nexport const remoteProvider = async (init) => {\n const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await import(\"@smithy/credential-provider-imds\");\n if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) {\n init.logger?.debug(\"@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata\");\n const { fromHttp } = await import(\"@aws-sdk/credential-provider-http\");\n return chain(fromHttp(init), fromContainerMetadata(init));\n }\n if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== \"false\") {\n return async () => {\n throw new CredentialsProviderError(\"EC2 Instance Metadata Service access disabled\", { logger: init.logger });\n };\n }\n init.logger?.debug(\"@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata\");\n return fromInstanceMetadata(init);\n};\n", | ||
| "export function memoizeChain(providers, treatAsExpired) {\n const chain = internalCreateChain(providers);\n let activeLock;\n let passiveLock;\n let credentials;\n let forceRefreshLock;\n const provider = async (options) => {\n if (options?.forceRefresh) {\n if (!forceRefreshLock) {\n forceRefreshLock = chain(options)\n .then((c) => {\n credentials = c;\n })\n .finally(() => {\n forceRefreshLock = undefined;\n });\n }\n await forceRefreshLock;\n return credentials;\n }\n if (credentials?.expiration) {\n if (credentials?.expiration?.getTime() < Date.now()) {\n credentials = undefined;\n }\n }\n if (activeLock) {\n await activeLock;\n }\n else if (!credentials || treatAsExpired?.(credentials)) {\n if (credentials) {\n if (!passiveLock) {\n passiveLock = chain(options)\n .then((c) => {\n credentials = c;\n })\n .finally(() => {\n passiveLock = undefined;\n });\n }\n }\n else {\n activeLock = chain(options)\n .then((c) => {\n credentials = c;\n })\n .finally(() => {\n activeLock = undefined;\n });\n return provider(options);\n }\n }\n return credentials;\n };\n return provider;\n}\nexport const internalCreateChain = (providers) => async (awsIdentityProperties) => {\n let lastProviderError;\n for (const provider of providers) {\n try {\n return await provider(awsIdentityProperties);\n }\n catch (err) {\n lastProviderError = err;\n if (err?.tryNextLink) {\n continue;\n }\n throw err;\n }\n }\n throw lastProviderError;\n};\n", | ||
| "import { defaultProvider } from \"@aws-sdk/credential-provider-node\";\nexport const fromNodeProviderChain = (init = {}) => defaultProvider({\n ...init,\n});\n", | ||
| "import { fromProcess as _fromProcess } from \"@aws-sdk/credential-provider-process\";\nexport const fromProcess = (init) => _fromProcess(init);\n", | ||
| "import { fromSSO as _fromSSO } from \"@aws-sdk/credential-provider-sso\";\nexport const fromSSO = (init = {}) => {\n return _fromSSO({ ...init });\n};\n", | ||
| "import { loadConfig, NODE_REGION_CONFIG_FILE_OPTIONS } from \"@smithy/core/config\";\nimport { fromNodeProviderChain } from \"./fromNodeProviderChain\";\nimport { fromTemporaryCredentials as fromTemporaryCredentialsBase } from \"./fromTemporaryCredentials.base\";\nexport const fromTemporaryCredentials = (options) => {\n return fromTemporaryCredentialsBase(options, fromNodeProviderChain, async ({ profile = process.env.AWS_PROFILE }) => loadConfig({\n environmentVariableSelector: (env) => env.AWS_REGION,\n configFileSelector: (profileData) => {\n return profileData.region;\n },\n default: () => undefined,\n }, { ...NODE_REGION_CONFIG_FILE_OPTIONS, profile })());\n};\n", | ||
| "import { normalizeProvider } from \"@smithy/core\";\nimport { CredentialsProviderError } from \"@smithy/core/config\";\nconst ASSUME_ROLE_DEFAULT_REGION = \"us-east-1\";\nexport const fromTemporaryCredentials = (options, credentialDefaultProvider, regionProvider) => {\n let stsClient;\n return async (awsIdentityProperties = {}) => {\n const { callerClientConfig } = awsIdentityProperties;\n const profile = options.clientConfig?.profile ?? callerClientConfig?.profile;\n const logger = options.logger ?? callerClientConfig?.logger;\n logger?.debug(\"@aws-sdk/credential-providers - fromTemporaryCredentials (STS)\");\n const params = { ...options.params, RoleSessionName: options.params.RoleSessionName ?? \"aws-sdk-js-\" + Date.now() };\n if (params?.SerialNumber) {\n if (!options.mfaCodeProvider) {\n throw new CredentialsProviderError(`Temporary credential requires multi-factor authentication, but no MFA code callback was provided.`, {\n tryNextLink: false,\n logger,\n });\n }\n params.TokenCode = await options.mfaCodeProvider(params?.SerialNumber);\n }\n const { AssumeRoleCommand, STSClient } = await import(\"./loadSts.js\");\n if (!stsClient) {\n const defaultCredentialsOrError = typeof credentialDefaultProvider === \"function\" ? credentialDefaultProvider() : undefined;\n const credentialSources = [\n options.masterCredentials,\n options.clientConfig?.credentials,\n void callerClientConfig?.credentials,\n callerClientConfig?.credentialDefaultProvider?.(),\n defaultCredentialsOrError,\n ];\n let credentialSource = \"STS client default credentials\";\n if (credentialSources[0]) {\n credentialSource = \"options.masterCredentials\";\n }\n else if (credentialSources[1]) {\n credentialSource = \"options.clientConfig.credentials\";\n }\n else if (credentialSources[2]) {\n credentialSource = \"caller client's credentials\";\n throw new Error(\"fromTemporaryCredentials recursion in callerClientConfig.credentials\");\n }\n else if (credentialSources[3]) {\n credentialSource = \"caller client's credentialDefaultProvider\";\n }\n else if (credentialSources[4]) {\n credentialSource = \"AWS SDK default credentials\";\n }\n const regionSources = [\n options.clientConfig?.region,\n callerClientConfig?.region,\n await regionProvider?.({\n profile,\n }),\n ASSUME_ROLE_DEFAULT_REGION,\n ];\n let regionSource = \"default partition's default region\";\n if (regionSources[0]) {\n regionSource = \"options.clientConfig.region\";\n }\n else if (regionSources[1]) {\n regionSource = \"caller client's region\";\n }\n else if (regionSources[2]) {\n regionSource = \"file or env region\";\n }\n const requestHandlerSources = [\n filterRequestHandler(options.clientConfig?.requestHandler),\n filterRequestHandler(callerClientConfig?.requestHandler),\n ];\n let requestHandlerSource = \"STS default requestHandler\";\n if (requestHandlerSources[0]) {\n requestHandlerSource = \"options.clientConfig.requestHandler\";\n }\n else if (requestHandlerSources[1]) {\n requestHandlerSource = \"caller client's requestHandler\";\n }\n logger?.debug?.(`@aws-sdk/credential-providers - fromTemporaryCredentials STS client init with ` +\n `${regionSource}=${await normalizeProvider(coalesce(regionSources))()}, ${credentialSource}, ${requestHandlerSource}.`);\n stsClient = new STSClient({\n userAgentAppId: callerClientConfig?.userAgentAppId,\n ...options.clientConfig,\n credentials: coalesce(credentialSources),\n logger,\n profile,\n region: coalesce(regionSources),\n requestHandler: coalesce(requestHandlerSources),\n });\n }\n if (options.clientPlugins) {\n for (const plugin of options.clientPlugins) {\n stsClient.middlewareStack.use(plugin);\n }\n }\n const { Credentials } = await stsClient.send(new AssumeRoleCommand(params));\n if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {\n throw new CredentialsProviderError(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`, {\n logger,\n });\n }\n return {\n accessKeyId: Credentials.AccessKeyId,\n secretAccessKey: Credentials.SecretAccessKey,\n sessionToken: Credentials.SessionToken,\n expiration: Credentials.Expiration,\n credentialScope: Credentials.CredentialScope,\n };\n };\n};\nconst filterRequestHandler = (requestHandler) => {\n return requestHandler?.metadata?.handlerProtocol === \"h2\" ? undefined : requestHandler;\n};\nconst coalesce = (args) => {\n for (const item of args) {\n if (item !== undefined) {\n return item;\n }\n }\n};\n", | ||
| "import { fromTokenFile as _fromTokenFile } from \"@aws-sdk/credential-provider-web-identity\";\nexport const fromTokenFile = (init = {}) => _fromTokenFile({\n ...init,\n});\n", | ||
| "import { fromWebToken as _fromWebToken } from \"@aws-sdk/credential-provider-web-identity\";\nexport const fromWebToken = (init) => _fromWebToken({\n ...init,\n});\n" | ||
| ], | ||
| "mappings": ";+rBAAA,eACa,GAAwB,IAAI,IAAwB,CAC7D,IAAI,EAAc,GAQZ,EAAc,OAAO,OAPN,MAAO,IAA0B,CAClD,IAAM,EAAc,MAAM,GAAsB,GAAG,CAAmB,EAAE,CAAqB,EAC7F,GAAI,CAAC,EAAY,YAAc,IAAgB,GAC3C,EAAY,WAAa,IAAI,KAAK,KAAK,IAAI,EAAI,CAAW,EAE9D,OAAO,GAEqC,CAC5C,WAAW,CAAC,EAAc,CACtB,GAAI,EAAe,OACf,MAAU,MAAM,uIAAuI,EAG3J,OADA,EAAc,EACP,EAEf,CAAC,EACD,OAAO,GAEE,GAAwB,IAAI,IAAc,MAAO,IAA0B,CACpF,GAAI,EAAU,SAAW,EACrB,MAAM,IAAI,gBAAc,wBAAyB,CAAE,YAAa,EAAM,CAAC,EAE3E,IAAI,EACJ,QAAW,KAAY,EACnB,GAAI,CACA,OAAO,MAAM,EAAS,CAAqB,EAE/C,MAAO,EAAK,CAER,GADA,EAAoB,EAChB,GAAK,YACL,SAEJ,MAAM,EAGd,MAAM,GCtCV,eCAO,SAAS,CAAa,CAAC,EAAQ,CAClC,OAAO,QAAQ,IAAI,OAAO,KAAK,CAAM,EAAE,OAAO,CAAC,EAAK,IAAS,CACzD,IAAM,E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,EAAY,aAAe,CAAC,EAAY,gBACzD,MAAM,IAAI,2BAAyB,uDAAuD,EAAO,UAAW,CACxG,QACJ,CAAC,EAEL,MAAO,CACH,YAAa,EAAY,YACzB,gBAAiB,EAAY,gBAC7B,aAAc,EAAY,aAC1B,WAAY,EAAY,WACxB,gBAAiB,EAAY,eACjC,IAGF,GAAuB,CAAC,IACnB,GAAgB,UAAU,kBAAoB,KAAO,OAAY,EAEtE,EAAW,CAAC,IAAS,CACvB,QAAW,KAAQ,EACf,GAAI,IAAS,OACT,OAAO,GD/GZ,IAAM,GAA2B,CAAC,IAC9B,GAA6B,EAAS,EAAuB,OAAS,UAAU,QAAQ,IAAI,eAAkB,aAAW,CAC5H,4BAA6B,CAAC,IAAQ,EAAI,WAC1C,mBAAoB,CAAC,IACV,EAAY,OAEvB,QAAS,IAAG,CAAG,OACnB,EAAG,IAAK,kCAAiC,SAAQ,CAAC,EAAE,CAAC,EETlD,IAAM,GAAgB,CAAC,EAAO,CAAC,IAAM,GAAe,IACpD,CACP,CAAC,ECFM,IAAM,GAAe,CAAC,IAAS,GAAc,IAC7C,CACP,CAAC", | ||
| "debugId": "7C8F8412D27B636364756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/plugin/update.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Cause, Effect, Exit, Option } from \"effect\"\nimport { Npm } from \"@opencode-ai/util/npm\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { inspect } from \"./inventory\"\n\nexport default Runtime.handler(\n Commands.commands.plugin.commands.update,\n Effect.fn(\"cli.plugin.update\")(function* (input) {\n const result = yield* inspect(Option.getOrUndefined(input.target))\n for (const item of result.items) {\n if (!item.error) continue\n process.stderr.write(`Failed to check ${item.runtime} plugin \"${item.name}\": ${item.error}${EOL}`)\n }\n const selected = result.items.filter((item) => item.outdated)\n if (!selected.length) {\n process.stdout.write(\"No plugin updates available\" + EOL)\n if (result.items.some((item) => item.error)) process.exitCode = 1\n return\n }\n\n const npm = yield* Npm.Service\n const updated = yield* Effect.forEach(\n selected,\n (item) =>\n (item.runtime === \"Server\"\n ? Effect.promise(() => result.client.plugin.update({ location: result.location, target: item.target }))\n : npm.update(item.target, { subpaths: [\"tui\"] }).pipe(Effect.asVoid)\n ).pipe(Effect.exit, Effect.map((result) => ({ item, result }))),\n { concurrency: \"unbounded\" },\n )\n for (const item of updated) {\n if (Exit.isSuccess(item.result)) {\n process.stdout.write(`Updated ${item.item.runtime} plugin \"${item.item.name}\"${EOL}`)\n continue\n }\n process.stderr.write(\n `Failed to update ${item.item.runtime} plugin \"${item.item.name}\": ${Cause.pretty(item.result.cause)}${EOL}`,\n )\n process.exitCode = 1\n }\n }),\n)\n" | ||
| ], | ||
| "mappings": ";4/BAAA,cAAS,WAOT,IAAe,IAAQ,QACrB,EAAS,SAAS,OAAO,SAAS,OAClC,EAAO,GAAG,mBAAmB,EAAE,SAAU,CAAC,EAAO,CAC/C,IAAM,EAAS,MAAO,EAAQ,EAAO,eAAe,EAAM,MAAM,CAAC,EACjE,QAAW,KAAQ,EAAO,MAAO,CAC/B,GAAI,CAAC,EAAK,MAAO,SACjB,QAAQ,OAAO,MAAM,mBAAmB,EAAK,mBAAmB,EAAK,UAAU,EAAK,QAAQ,GAAK,EAEnG,IAAM,EAAW,EAAO,MAAM,OAAO,CAAC,IAAS,EAAK,QAAQ,EAC5D,GAAI,CAAC,EAAS,OAAQ,CAEpB,GADA,QAAQ,OAAO,MAAM,8BAAgC,CAAG,EACpD,EAAO,MAAM,KAAK,CAAC,IAAS,EAAK,KAAK,EAAG,QAAQ,SAAW,EAChE,OAGF,IAAM,EAAM,MAAO,EAAI,QACjB,EAAU,MAAO,EAAO,QAC5B,EACA,CAAC,KACE,EAAK,UAAY,SACd,EAAO,QAAQ,IAAM,EAAO,OAAO,OAAO,OAAO,CAAE,SAAU,EAAO,SAAU,OAAQ,EAAK,MAAO,CAAC,CAAC,EACpG,EAAI,OAAO,EAAK,OAAQ,CAAE,SAAU,CAAC,KAAK,CAAE,CAAC,EAAE,KAAK,EAAO,MAAM,GACnE,KAAK,EAAO,KAAM,EAAO,IAAI,CAAC,KAAY,CAAE,OAAM,QAAO,EAAE,CAAC,EAChE,CAAE,YAAa,WAAY,CAC7B,EACA,QAAW,KAAQ,EAAS,CAC1B,GAAI,EAAK,UAAU,EAAK,MAAM,EAAG,CAC/B,QAAQ,OAAO,MAAM,WAAW,EAAK,KAAK,mBAAmB,EAAK,KAAK,QAAQ,GAAK,EACpF,SAEF,QAAQ,OAAO,MACb,oBAAoB,EAAK,KAAK,mBAAmB,EAAK,KAAK,UAAU,EAAM,OAAO,EAAK,OAAO,KAAK,IAAI,GACzG,EACA,QAAQ,SAAW,GAEtB,CACH", | ||
| "debugId": "C9696350C64B384E64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-process@3.972.69/node_modules/@aws-sdk/credential-provider-process/dist-es/fromProcess.js", "../../node_modules/.bun/@aws-sdk+credential-provider-process@3.972.69/node_modules/@aws-sdk/credential-provider-process/dist-es/resolveProcessCredentials.js", "../../node_modules/.bun/@aws-sdk+credential-provider-process@3.972.69/node_modules/@aws-sdk/credential-provider-process/dist-es/getValidatedProcessCredentials.js"], | ||
| "sourcesContent": [ | ||
| "import { getProfileName, parseKnownFiles } from \"@smithy/core/config\";\nimport { resolveProcessCredentials } from \"./resolveProcessCredentials\";\nexport const fromProcess = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-process - fromProcess\");\n const profiles = await parseKnownFiles(init);\n return resolveProcessCredentials(getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n }), profiles, init.logger);\n};\n", | ||
| "import { CredentialsProviderError, externalDataInterceptor } from \"@smithy/core/config\";\nimport { exec } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { getValidatedProcessCredentials } from \"./getValidatedProcessCredentials\";\nexport const resolveProcessCredentials = async (profileName, profiles, logger) => {\n const profile = profiles[profileName];\n if (profiles[profileName]) {\n const credentialProcess = profile[\"credential_process\"];\n if (credentialProcess !== undefined) {\n const execPromise = promisify(externalDataInterceptor?.getTokenRecord?.().exec ?? exec);\n try {\n const { stdout } = await execPromise(credentialProcess);\n let data;\n try {\n data = JSON.parse(stdout.trim());\n }\n catch {\n throw Error(`Profile ${profileName} credential_process returned invalid JSON.`);\n }\n return getValidatedProcessCredentials(profileName, data, profiles);\n }\n catch (error) {\n throw new CredentialsProviderError(error.message, { logger });\n }\n }\n else {\n throw new CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger });\n }\n }\n else {\n throw new CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, {\n logger,\n });\n }\n};\n", | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const getValidatedProcessCredentials = (profileName, data, profiles) => {\n if (data.Version !== 1) {\n throw Error(`Profile ${profileName} credential_process did not return Version 1.`);\n }\n if (data.AccessKeyId === undefined || data.SecretAccessKey === undefined) {\n throw Error(`Profile ${profileName} credential_process returned invalid credentials.`);\n }\n if (data.Expiration) {\n const currentTime = new Date();\n const expireTime = new Date(data.Expiration);\n if (expireTime < currentTime) {\n throw Error(`Profile ${profileName} credential_process returned expired credentials.`);\n }\n }\n let accountId = data.AccountId;\n if (!accountId && profiles?.[profileName]?.aws_account_id) {\n accountId = profiles[profileName].aws_account_id;\n }\n const credentials = {\n accessKeyId: data.AccessKeyId,\n secretAccessKey: data.SecretAccessKey,\n ...(data.SessionToken && { sessionToken: data.SessionToken }),\n ...(data.Expiration && { expiration: new Date(data.Expiration) }),\n ...(data.CredentialScope && { credentialScope: data.CredentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"CREDENTIALS_PROCESS\", \"w\");\n return credentials;\n};\n" | ||
| ], | ||
| "mappings": ";4JA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AAO,CAAC,EAI/G,WAAM,IAAI,2BAAyB,WAAW,mDAA8D,CACxG,QACJ,CAAC,GD9BF,IAAM,EAAc,CAAC,EAAO,CAAC,IAAM,OAAS,sBAAuB,CAAC,IAAM,CAC7E,EAAK,QAAQ,MAAM,oDAAoD,EACvE,IAAM,EAAW,MAAM,kBAAgB,CAAI,EAC3C,OAAO,EAA0B,iBAAe,CAC5C,QAAS,EAAK,SAAW,GAAoB,OACjD,CAAC,EAAG,EAAU,EAAK,MAAM", | ||
| "debugId": "CC915F4350D9611964756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+nested-clients@3.997.43/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsRestJsonProtocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"sso-oauth\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"CreateToken\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"sso-oauth\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.42\";\nvar packageInfo = {\n\tversion: version};\n\nconst k = \"ref\";\nconst a = -1, b = true, c = \"isSet\", d = \"PartitionResult\", e = \"booleanEquals\", f = \"getAttr\", g = { [k]: \"Endpoint\" }, h = { [k]: d }, i = {}, j = [{ [k]: \"Region\" }];\nconst _data = {\n conditions: [\n [c, [g]],\n [c, j],\n [\"aws.partition\", j, d],\n [e, [{ [k]: \"UseFIPS\" }, b]],\n [e, [{ [k]: \"UseDualStack\" }, b]],\n [e, [{ fn: f, argv: [h, \"supportsDualStack\"] }, b]],\n [e, [{ fn: f, argv: [h, \"supportsFIPS\"] }, b]],\n [\"stringEquals\", [{ fn: f, argv: [h, \"name\"] }, \"aws-us-gov\"]]\n ],\n results: [\n [a],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [g, i],\n [\"https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://oidc.{Region}.amazonaws.com\", i],\n [\"https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [\"https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}\", i],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://oidc.{Region}.{PartitionResult#dnsSuffix}\", i],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 13, 3,\n 1, 4, r + 12,\n 2, 5, r + 12,\n 3, 8, 6,\n 4, 7, r + 11,\n 5, r + 9, r + 10,\n 4, 11, 9,\n 6, 10, r + 8,\n 7, r + 6, r + 7,\n 5, 12, r + 5,\n 6, r + 4, r + 5,\n 3, r + 1, 14,\n 4, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass SSOOIDCServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, SSOOIDCServiceException.prototype);\n }\n}\n\nclass AccessDeniedException extends SSOOIDCServiceException {\n name = \"AccessDeniedException\";\n $fault = \"client\";\n error;\n reason;\n error_description;\n constructor(opts) {\n super({\n name: \"AccessDeniedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, AccessDeniedException.prototype);\n this.error = opts.error;\n this.reason = opts.reason;\n this.error_description = opts.error_description;\n }\n}\nclass AuthorizationPendingException extends SSOOIDCServiceException {\n name = \"AuthorizationPendingException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"AuthorizationPendingException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, AuthorizationPendingException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass ExpiredTokenException extends SSOOIDCServiceException {\n name = \"ExpiredTokenException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"ExpiredTokenException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ExpiredTokenException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InternalServerException extends SSOOIDCServiceException {\n name = \"InternalServerException\";\n $fault = \"server\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InternalServerException\",\n $fault: \"server\",\n ...opts,\n });\n Object.setPrototypeOf(this, InternalServerException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidClientException extends SSOOIDCServiceException {\n name = \"InvalidClientException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidClientException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidClientException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidGrantException extends SSOOIDCServiceException {\n name = \"InvalidGrantException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidGrantException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidGrantException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidRequestException extends SSOOIDCServiceException {\n name = \"InvalidRequestException\";\n $fault = \"client\";\n error;\n reason;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidRequestException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidRequestException.prototype);\n this.error = opts.error;\n this.reason = opts.reason;\n this.error_description = opts.error_description;\n }\n}\nclass InvalidScopeException extends SSOOIDCServiceException {\n name = \"InvalidScopeException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidScopeException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidScopeException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass SlowDownException extends SSOOIDCServiceException {\n name = \"SlowDownException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"SlowDownException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, SlowDownException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass UnauthorizedClientException extends SSOOIDCServiceException {\n name = \"UnauthorizedClientException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"UnauthorizedClientException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, UnauthorizedClientException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nclass UnsupportedGrantTypeException extends SSOOIDCServiceException {\n name = \"UnsupportedGrantTypeException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"UnsupportedGrantTypeException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, UnsupportedGrantTypeException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\n\nconst _ADE = \"AccessDeniedException\";\nconst _APE = \"AuthorizationPendingException\";\nconst _AT = \"AccessToken\";\nconst _CS = \"ClientSecret\";\nconst _CT = \"CreateToken\";\nconst _CTR = \"CreateTokenRequest\";\nconst _CTRr = \"CreateTokenResponse\";\nconst _CV = \"CodeVerifier\";\nconst _ETE = \"ExpiredTokenException\";\nconst _ICE = \"InvalidClientException\";\nconst _IGE = \"InvalidGrantException\";\nconst _IRE = \"InvalidRequestException\";\nconst _ISE = \"InternalServerException\";\nconst _ISEn = \"InvalidScopeException\";\nconst _IT = \"IdToken\";\nconst _RT = \"RefreshToken\";\nconst _SDE = \"SlowDownException\";\nconst _UCE = \"UnauthorizedClientException\";\nconst _UGTE = \"UnsupportedGrantTypeException\";\nconst _aT = \"accessToken\";\nconst _c = \"client\";\nconst _cI = \"clientId\";\nconst _cS = \"clientSecret\";\nconst _cV = \"codeVerifier\";\nconst _co = \"code\";\nconst _dC = \"deviceCode\";\nconst _e = \"error\";\nconst _eI = \"expiresIn\";\nconst _ed = \"error_description\";\nconst _gT = \"grantType\";\nconst _h = \"http\";\nconst _hE = \"httpError\";\nconst _iT = \"idToken\";\nconst _r = \"reason\";\nconst _rT = \"refreshToken\";\nconst _rU = \"redirectUri\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.ssooidc\";\nconst _sc = \"scope\";\nconst _se = \"server\";\nconst _tT = \"tokenType\";\nconst n0 = \"com.amazonaws.ssooidc\";\nconst _s_registry = TypeRegistry.for(_s);\nvar SSOOIDCServiceException$ = [-3, _s, \"SSOOIDCServiceException\", 0, [], []];\n_s_registry.registerError(SSOOIDCServiceException$, SSOOIDCServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar AccessDeniedException$ = [-3, n0, _ADE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _r, _ed],\n [0, 0, 0]\n];\nn0_registry.registerError(AccessDeniedException$, AccessDeniedException);\nvar AuthorizationPendingException$ = [-3, n0, _APE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(AuthorizationPendingException$, AuthorizationPendingException);\nvar ExpiredTokenException$ = [-3, n0, _ETE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(ExpiredTokenException$, ExpiredTokenException);\nvar InternalServerException$ = [-3, n0, _ISE,\n { [_e]: _se, [_hE]: 500 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InternalServerException$, InternalServerException);\nvar InvalidClientException$ = [-3, n0, _ICE,\n { [_e]: _c, [_hE]: 401 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InvalidClientException$, InvalidClientException);\nvar InvalidGrantException$ = [-3, n0, _IGE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InvalidGrantException$, InvalidGrantException);\nvar InvalidRequestException$ = [-3, n0, _IRE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _r, _ed],\n [0, 0, 0]\n];\nn0_registry.registerError(InvalidRequestException$, InvalidRequestException);\nvar InvalidScopeException$ = [-3, n0, _ISEn,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(InvalidScopeException$, InvalidScopeException);\nvar SlowDownException$ = [-3, n0, _SDE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(SlowDownException$, SlowDownException);\nvar UnauthorizedClientException$ = [-3, n0, _UCE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(UnauthorizedClientException$, UnauthorizedClientException);\nvar UnsupportedGrantTypeException$ = [-3, n0, _UGTE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0]\n];\nn0_registry.registerError(UnsupportedGrantTypeException$, UnsupportedGrantTypeException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar AccessToken = [0, n0, _AT, 8, 0];\nvar ClientSecret = [0, n0, _CS, 8, 0];\nvar CodeVerifier = [0, n0, _CV, 8, 0];\nvar IdToken = [0, n0, _IT, 8, 0];\nvar RefreshToken = [0, n0, _RT, 8, 0];\nvar CreateTokenRequest$ = [3, n0, _CTR,\n 0,\n [_cI, _cS, _gT, _dC, _co, _rT, _sc, _rU, _cV],\n [0, [() => ClientSecret, 0], 0, 0, 0, [() => RefreshToken, 0], 64 | 0, 0, [() => CodeVerifier, 0]], 3\n];\nvar CreateTokenResponse$ = [3, n0, _CTRr,\n 0,\n [_aT, _tT, _eI, _rT, _iT],\n [[() => AccessToken, 0], 0, 1, [() => RefreshToken, 0], [() => IdToken, 0]]\n];\nvar CreateToken$ = [9, n0, _CT,\n { [_h]: [\"POST\", \"/token\", 200] }, () => CreateTokenRequest$, () => CreateTokenResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2019-06-10\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOOIDCHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsRestJsonProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.ssooidc\",\n errorTypeRegistries,\n version: \"2019-06-10\",\n serviceTarget: \"AWSSSOOIDCService\",\n },\n serviceId: config?.serviceId ?? \"SSO OIDC\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass SSOOIDCClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"AWSSSOOIDCService\", \"SSOOIDCClient\", getEndpointPlugin);\nconst _ep0 = {};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass CreateTokenCommand extends command(_ep0, _mw0, \"CreateToken\", CreateToken$) {\n}\n\nconst commands = {\n CreateTokenCommand,\n};\nclass SSOOIDC extends SSOOIDCClient {\n}\ncreateAggregatedClient(commands, SSOOIDC);\n\nconst AccessDeniedExceptionReason = {\n KMS_ACCESS_DENIED: \"KMS_AccessDeniedException\",\n};\nconst InvalidRequestExceptionReason = {\n KMS_DISABLED_KEY: \"KMS_DisabledException\",\n KMS_INVALID_KEY_USAGE: \"KMS_InvalidKeyUsageException\",\n KMS_INVALID_STATE: \"KMS_InvalidStateException\",\n KMS_KEY_NOT_FOUND: \"KMS_NotFoundException\",\n};\n\nexports.AccessDeniedException = AccessDeniedException;\nexports.AccessDeniedException$ = AccessDeniedException$;\nexports.AccessDeniedExceptionReason = AccessDeniedExceptionReason;\nexports.AuthorizationPendingException = AuthorizationPendingException;\nexports.AuthorizationPendingException$ = AuthorizationPendingException$;\nexports.CreateToken$ = CreateToken$;\nexports.CreateTokenCommand = CreateTokenCommand;\nexports.CreateTokenRequest$ = CreateTokenRequest$;\nexports.CreateTokenResponse$ = CreateTokenResponse$;\nexports.ExpiredTokenException = ExpiredTokenException;\nexports.ExpiredTokenException$ = ExpiredTokenException$;\nexports.InternalServerException = InternalServerException;\nexports.InternalServerException$ = InternalServerException$;\nexports.InvalidClientException = InvalidClientException;\nexports.InvalidClientException$ = InvalidClientException$;\nexports.InvalidGrantException = InvalidGrantException;\nexports.InvalidGrantException$ = InvalidGrantException$;\nexports.InvalidRequestException = InvalidRequestException;\nexports.InvalidRequestException$ = InvalidRequestException$;\nexports.InvalidRequestExceptionReason = InvalidRequestExceptionReason;\nexports.InvalidScopeException = InvalidScopeException;\nexports.InvalidScopeException$ = InvalidScopeException$;\nexports.SSOOIDC = SSOOIDC;\nexports.SSOOIDCClient = SSOOIDCClient;\nexports.SSOOIDCServiceException = SSOOIDCServiceException;\nexports.SSOOIDCServiceException$ = SSOOIDCServiceException$;\nexports.SlowDownException = SlowDownException;\nexports.SlowDownException$ = SlowDownException$;\nexports.UnauthorizedClientException = UnauthorizedClientException;\nexports.UnauthorizedClientException$ = UnauthorizedClientException$;\nexports.UnsupportedGrantTypeException = UnsupportedGrantTypeException;\nexports.UnsupportedGrantTypeException$ = UnsupportedGrantTypeException$;\nexports.errorTypeRegistries = errorTypeRegistries;\n" | ||
| ], | ||
| "mappings": ";uXAAA,IAAQ,wBAAsB,gCAAiC,GAAmC,kCAAgC,8BAA4B,sCAAoC,0CAAwC,0BAAwB,2BAAyB,sBAAoB,uBAAqB,mBAAiB,sCAC7U,gBAAc,0CAAwC,iCAA+B,+BACrF,oBAAmB,oBAAkB,oBAAkB,cAAY,mCAAiC,6BAA2B,oCAAkC,+BAA6B,SAAQ,eAAa,gCACnN,QAAS,QACjB,IAAQ,GAAW,GACX,GAAW,EACnB,IAAQ,6BAA2B,aAAY,yCAAuC,8CAA4C,8BAA4B,mCAAiC,8BACvL,yBAAuB,iBAAe,kBAAgB,2BAAyB,yBAAuB,4BACtG,YAAU,wCAAsC,mCAAiC,iCACjF,sBAAoB,kCAAgC,mCAAiC,sBAAoB,yBACzG,eAAc,+BACd,4BAA0B,qBAAmB,8CAC7C,UAAQ,YAAU,YAAU,cAAY,8BACxC,mBAAiB,0BACjB,8BACA,gBA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AAQ,EAEtB,CAEA,IAAM,GAAU,GAAY,GAAc,oBAAqB,gBAAiB,EAAiB,EAC3F,GAAO,CAAC,EACR,GAAO,CAAC,EAAS,EAAI,EAAQ,IAAM,CAAC,EAE1C,MAAM,UAA2B,GAAQ,GAAM,GAAM,cAAe,EAAY,CAAE,CAClF,CAEA,IAAM,GAAW,CACb,oBACJ,EACA,MAAM,UAAgB,CAAc,CACpC,CACA,GAAuB,GAAU,CAAO,EAExC,IAAM,GAA8B,CAChC,kBAAmB,2BACvB,EACM,GAAgC,CAClC,iBAAkB,wBAClB,sBAAuB,+BACvB,kBAAmB,4BACnB,kBAAmB,uBACvB,EAEA,IAAQ,GAAwB,EACxB,GAAyB,EACzB,GAA8B,GAC9B,GAAgC,EAChC,GAAiC,EACjC,GAAe,GACf,GAAqB,EACrB,GAAsB,GACtB,GAAuB,GACvB,GAAwB,EACxB,GAAyB,GACzB,GAA0B,EAC1B,GAA2B,GAC3B,GAAyB,EACzB,GAA0B,GAC1B,GAAwB,EACxB,GAAyB,GACzB,GAA0B,EAC1B,GAA2B,GAC3B,GAAgC,GAChC,GAAwB,EACxB,GAAyB,GACzB,GAAU,EACV,GAAgB,EAChB,GAA0B,EAC1B,GAA2B,EAC3B,GAAoB,EACpB,GAAqB,GACrB,GAA8B,EAC9B,GAA+B,GAC/B,GAAgC,EAChC,GAAiC,GACjC,GAAsB", | ||
| "debugId": "BA1EBBEA5CEC036264756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.71/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/fromHttp.js", "../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.71/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/checkUrl.js", "../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.71/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/requestHelpers.js", "../../node_modules/.bun/@aws-sdk+credential-provider-http@3.972.71/node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/retry-wrapper.js"], | ||
| "sourcesContent": [ | ||
| "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError } from \"@smithy/core/config\";\nimport { NodeHttpHandler } from \"@smithy/node-http-handler\";\nimport fs from \"node:fs/promises\";\nimport { checkUrl } from \"./checkUrl\";\nimport { createGetRequest, getCredentials } from \"./requestHelpers\";\nimport { retryWrapper } from \"./retry-wrapper\";\nconst AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = \"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\";\nconst DEFAULT_LINK_LOCAL_HOST = \"http://169.254.170.2\";\nconst AWS_CONTAINER_CREDENTIALS_FULL_URI = \"AWS_CONTAINER_CREDENTIALS_FULL_URI\";\nconst AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = \"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE\";\nconst AWS_CONTAINER_AUTHORIZATION_TOKEN = \"AWS_CONTAINER_AUTHORIZATION_TOKEN\";\nexport const fromHttp = (options = {}) => {\n options.logger?.debug(\"@aws-sdk/credential-provider-http - fromHttp\");\n let host;\n const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI];\n const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI];\n const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN];\n const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE];\n const warn = options.logger?.constructor?.name === \"NoOpLogger\" || !options.logger?.warn\n ? console.warn\n : options.logger.warn.bind(options.logger);\n if (relative && full) {\n warn(\"@aws-sdk/credential-provider-http: \" +\n \"you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri.\");\n warn(\"awsContainerCredentialsRelativeUri will take precedence.\");\n }\n if (token && tokenFile) {\n warn(\"@aws-sdk/credential-provider-http: \" +\n \"you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile.\");\n warn(\"awsContainerAuthorizationTokenFile will take precedence.\");\n }\n if (relative) {\n host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`;\n }\n else if (full) {\n host = full;\n }\n else {\n throw new CredentialsProviderError(`No HTTP credential provider host provided.\nSet AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger });\n }\n const url = new URL(host);\n checkUrl(url, options.logger);\n const requestHandler = NodeHttpHandler.create({ connectionTimeout: options.timeout ?? 1000 });\n const requestTimeout = options.timeout ?? 1000;\n const provider = retryWrapper(async () => {\n const request = createGetRequest(url);\n if (tokenFile) {\n request.headers.Authorization = validateToken((await fs.readFile(tokenFile)).toString());\n }\n else if (token) {\n request.headers.Authorization = validateToken(token);\n }\n try {\n const result = await requestHandler.handle(request, { requestTimeout });\n return getCredentials(result.response).then((creds) => setCredentialFeature(creds, \"CREDENTIALS_HTTP\", \"z\"));\n }\n catch (e) {\n throw new CredentialsProviderError(String(e), { logger: options.logger });\n }\n }, options.maxRetries ?? 3, options.timeout ?? 1000);\n return async () => {\n try {\n return await provider();\n }\n finally {\n requestHandler.destroy?.();\n }\n };\n};\nconst validateToken = (token) => {\n if (token.includes(\"\\r\\n\")) {\n throw new CredentialsProviderError(\"Authorization token contains invalid \\\\r\\\\n sequence.\");\n }\n return token;\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nconst LOOPBACK_CIDR_IPv4 = \"127.0.0.0/8\";\nconst LOOPBACK_CIDR_IPv6 = \"::1/128\";\nconst ECS_CONTAINER_HOST = \"169.254.170.2\";\nconst EKS_CONTAINER_HOST_IPv4 = \"169.254.170.23\";\nconst EKS_CONTAINER_HOST_IPv6 = \"[fd00:ec2::23]\";\nexport const checkUrl = (url, logger) => {\n if (url.protocol === \"https:\") {\n return;\n }\n if (url.hostname === ECS_CONTAINER_HOST ||\n url.hostname === EKS_CONTAINER_HOST_IPv4 ||\n url.hostname === EKS_CONTAINER_HOST_IPv6) {\n return;\n }\n if (url.hostname.includes(\"[\")) {\n if (url.hostname === \"[::1]\" || url.hostname === \"[0000:0000:0000:0000:0000:0000:0000:0001]\") {\n return;\n }\n }\n else {\n if (url.hostname === \"localhost\") {\n return;\n }\n const ipComponents = url.hostname.split(\".\");\n const inRange = (component) => {\n const num = parseInt(component, 10);\n return 0 <= num && num <= 255;\n };\n if (ipComponents[0] === \"127\" &&\n inRange(ipComponents[1]) &&\n inRange(ipComponents[2]) &&\n inRange(ipComponents[3]) &&\n ipComponents.length === 4) {\n return;\n }\n }\n throw new CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following:\n - loopback CIDR 127.0.0.0/8 or [::1/128]\n - ECS container host 169.254.170.2\n - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger });\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { HttpRequest } from \"@smithy/core/protocols\";\nimport { parseRfc3339DateTime } from \"@smithy/core/serde\";\nimport { sdkStreamMixin } from \"@smithy/core/serde\";\nexport function createGetRequest(url) {\n return new HttpRequest({\n protocol: url.protocol,\n hostname: url.hostname,\n port: Number(url.port),\n path: url.pathname,\n query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => {\n acc[k] = v;\n return acc;\n }, {}),\n fragment: url.hash,\n });\n}\nexport async function getCredentials(response, logger) {\n const stream = sdkStreamMixin(response.body);\n const str = await stream.transformToString();\n if (response.statusCode === 200) {\n const parsed = JSON.parse(str);\n if (typeof parsed.AccessKeyId !== \"string\" ||\n typeof parsed.SecretAccessKey !== \"string\" ||\n typeof parsed.Token !== \"string\" ||\n typeof parsed.Expiration !== \"string\") {\n throw new CredentialsProviderError(\"HTTP credential provider response not of the required format, an object matching: \" +\n \"{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }\", { logger });\n }\n return {\n accessKeyId: parsed.AccessKeyId,\n secretAccessKey: parsed.SecretAccessKey,\n sessionToken: parsed.Token,\n expiration: parseRfc3339DateTime(parsed.Expiration),\n };\n }\n if (response.statusCode >= 400 && response.statusCode < 500) {\n let parsedBody = {};\n try {\n parsedBody = JSON.parse(str);\n }\n catch (e) { }\n throw Object.assign(new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }), {\n Code: parsedBody.Code,\n Message: parsedBody.Message,\n });\n }\n throw new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger });\n}\n", | ||
| "export const retryWrapper = (toRetry, maxRetries, delayMs) => {\n return async () => {\n for (let i = 0; i < maxRetries; ++i) {\n try {\n return await toRetry();\n }\n catch (e) {\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n return await toRetry();\n };\n};\n" | ||
| ], | ||
| "mappings": ";4QAAA,eACA,WACA,WACA,2BCHA,eAGA,IAAM,EAAqB,gBACrB,EAA0B,iBAC1B,EAA0B,iBACnB,EAAW,CAAC,EAAK,IAAW,CACrC,GAAI,EAAI,WAAa,SACjB,OAEJ,GAAI,EAAI,WAAa,GACjB,EAAI,WAAa,GACjB,EAAI,WAAa,EACjB,OAEJ,GAAI,EAAI,SAAS,SAAS,GAAG,GACzB,GAAI,EAAI,WAAa,SAAW,EAAI,WAAa,4CAC7C,OAGH,KACD,GAAI,EAAI,WAAa,YACjB,OAEJ,IAAM,EAAe,EAAI,SAAS,MAAM,GAAG,EACrC,EAAU,CAAC,IAAc,CAC3B,IAAM,EAAM,SAAS,EAAW,EAAE,EAClC,MAAO,IAAK,GAAO,GAAO,KAE9B,GAAI,EAAa,KAAO,OACpB,EAAQ,EAAa,EAAE,GACvB,EAAQ,EAAa,EAAE,GACvB,EAAQ,EAAa,EAAE,GACvB,EAAa,SAAW,EACxB,OAGR,MAAM,IAAI,2BAAyB;AAAA;AAAA;AAAA,yDAGmB,CAAE,QAAO,CAAC,GCxCpE,eACA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,EAAE,KAAK,CAAC,IAAU,uBAAqB,EAAO,mBAAoB,GAAG,CAAC,EAE/G,MAAO,EAAG,CACN,MAAM,IAAI,2BAAyB,OAAO,CAAC,EAAG,CAAE,OAAQ,EAAQ,MAAO,CAAC,IAE7E,EAAQ,YAAc,EAAG,EAAQ,SAAW,IAAI,EACnD,MAAO,UAAY,CACf,GAAI,CACA,OAAO,MAAM,EAAS,SAE1B,CACI,EAAe,UAAU,KAI/B,EAAgB,CAAC,IAAU,CAC7B,GAAI,EAAM,SAAS;AAAA,CAAM,EACrB,MAAM,IAAI,2BAAyB,uDAAuD,EAE9F,OAAO", | ||
| "debugId": "4ADBB1E2454BB41D64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/dist/index.mjs"], | ||
| "sourcesContent": [ | ||
| "// src/errors/ai-sdk-error.ts\nvar marker = \"vercel.ai.error\";\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {\n /**\n * Creates an AI SDK Error.\n *\n * @param {Object} params - The parameters for creating the error.\n * @param {string} params.name - The name of the error.\n * @param {string} params.message - The error message.\n * @param {unknown} [params.cause] - The underlying cause of the error.\n */\n constructor({\n name: name14,\n message,\n cause\n }) {\n super(message);\n this[_a] = true;\n this.name = name14;\n this.cause = cause;\n }\n /**\n * Checks if the given error is an AI SDK Error.\n * @param {unknown} error - The error to check.\n * @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n */\n static isInstance(error) {\n return _AISDKError.hasMarker(error, marker);\n }\n static hasMarker(error, marker15) {\n const markerSymbol = Symbol.for(marker15);\n return error != null && typeof error === \"object\" && markerSymbol in error && typeof error[markerSymbol] === \"boolean\" && error[markerSymbol] === true;\n }\n};\n\n// src/errors/api-call-error.ts\nvar name = \"AI_APICallError\";\nvar marker2 = `vercel.ai.error.${name}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2, _b2;\nvar APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {\n constructor({\n message,\n url,\n requestBodyValues,\n statusCode,\n responseHeaders,\n responseBody,\n cause,\n isRetryable = statusCode != null && (statusCode === 408 || // request timeout\n statusCode === 409 || // conflict\n statusCode === 429 || // too many requests\n statusCode >= 500),\n // server error\n data\n }) {\n super({ name, message, cause });\n this[_a2] = true;\n this.url = url;\n this.requestBodyValues = requestBodyValues;\n this.statusCode = statusCode;\n this.responseHeaders = responseHeaders;\n this.responseBody = responseBody;\n this.isRetryable = isRetryable;\n this.data = data;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker2);\n }\n};\n\n// src/errors/empty-response-body-error.ts\nvar name2 = \"AI_EmptyResponseBodyError\";\nvar marker3 = `vercel.ai.error.${name2}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3, _b3;\nvar EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {\n // used in isInstance\n constructor({ message = \"Empty response body\" } = {}) {\n super({ name: name2, message });\n this[_a3] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker3);\n }\n};\n\n// src/errors/get-error-message.ts\nfunction getErrorMessage(error) {\n if (error == null) {\n return \"unknown error\";\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error instanceof Error) {\n return error.message;\n }\n return JSON.stringify(error);\n}\n\n// src/errors/invalid-argument-error.ts\nvar name3 = \"AI_InvalidArgumentError\";\nvar marker4 = `vercel.ai.error.${name3}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4, _b4;\nvar InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {\n constructor({\n message,\n cause,\n argument\n }) {\n super({ name: name3, message, cause });\n this[_a4] = true;\n this.argument = argument;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker4);\n }\n};\n\n// src/errors/invalid-prompt-error.ts\nvar name4 = \"AI_InvalidPromptError\";\nvar marker5 = `vercel.ai.error.${name4}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5, _b5;\nvar InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {\n constructor({\n prompt,\n message,\n cause\n }) {\n super({ name: name4, message: `Invalid prompt: ${message}`, cause });\n this[_a5] = true;\n this.prompt = prompt;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker5);\n }\n};\n\n// src/errors/invalid-response-data-error.ts\nvar name5 = \"AI_InvalidResponseDataError\";\nvar marker6 = `vercel.ai.error.${name5}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6, _b6;\nvar InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {\n constructor({\n data,\n message = `Invalid response data: ${JSON.stringify(data)}.`\n }) {\n super({ name: name5, message });\n this[_a6] = true;\n this.data = data;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker6);\n }\n};\n\n// src/errors/json-parse-error.ts\nvar name6 = \"AI_JSONParseError\";\nvar marker7 = `vercel.ai.error.${name6}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7, _b7;\nvar JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {\n constructor({ text, cause }) {\n super({\n name: name6,\n message: `JSON parsing failed: Text: ${text}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a7] = true;\n this.text = text;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker7);\n }\n};\n\n// src/errors/load-api-key-error.ts\nvar name7 = \"AI_LoadAPIKeyError\";\nvar marker8 = `vercel.ai.error.${name7}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8, _b8;\nvar LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name7, message });\n this[_a8] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker8);\n }\n};\n\n// src/errors/load-setting-error.ts\nvar name8 = \"AI_LoadSettingError\";\nvar marker9 = `vercel.ai.error.${name8}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9, _b9;\nvar LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name8, message });\n this[_a9] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker9);\n }\n};\n\n// src/errors/no-content-generated-error.ts\nvar name9 = \"AI_NoContentGeneratedError\";\nvar marker10 = `vercel.ai.error.${name9}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10, _b10;\nvar NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {\n // used in isInstance\n constructor({\n message = \"No content generated.\"\n } = {}) {\n super({ name: name9, message });\n this[_a10] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker10);\n }\n};\n\n// src/errors/no-such-model-error.ts\nvar name10 = \"AI_NoSuchModelError\";\nvar marker11 = `vercel.ai.error.${name10}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11, _b11;\nvar NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {\n constructor({\n errorName = name10,\n modelId,\n modelType,\n message = `No such ${modelType}: ${modelId}`\n }) {\n super({ name: errorName, message });\n this[_a11] = true;\n this.modelId = modelId;\n this.modelType = modelType;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker11);\n }\n};\n\n// src/errors/too-many-embedding-values-for-call-error.ts\nvar name11 = \"AI_TooManyEmbeddingValuesForCallError\";\nvar marker12 = `vercel.ai.error.${name11}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12, _b12;\nvar TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {\n constructor(options) {\n super({\n name: name11,\n message: `Too many values for a single embedding call. The ${options.provider} model \"${options.modelId}\" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`\n });\n this[_a12] = true;\n this.provider = options.provider;\n this.modelId = options.modelId;\n this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n this.values = options.values;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker12);\n }\n};\n\n// src/errors/type-validation-error.ts\nvar name12 = \"AI_TypeValidationError\";\nvar marker13 = `vercel.ai.error.${name12}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13, _b13;\nvar TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {\n constructor({\n value,\n cause,\n context\n }) {\n let contextPrefix = \"Type validation failed\";\n if (context == null ? void 0 : context.field) {\n contextPrefix += ` for ${context.field}`;\n }\n if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {\n contextPrefix += \" (\";\n const parts = [];\n if (context.entityName) {\n parts.push(context.entityName);\n }\n if (context.entityId) {\n parts.push(`id: \"${context.entityId}\"`);\n }\n contextPrefix += parts.join(\", \");\n contextPrefix += \")\";\n }\n super({\n name: name12,\n message: `${contextPrefix}: Value: ${JSON.stringify(value)}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a13] = true;\n this.value = value;\n this.context = context;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker13);\n }\n /**\n * Wraps an error into a TypeValidationError.\n * If the cause is already a TypeValidationError with the same value and context, it returns the cause.\n * Otherwise, it creates a new TypeValidationError.\n *\n * @param {Object} params - The parameters for wrapping the error.\n * @param {unknown} params.value - The value that failed validation.\n * @param {unknown} params.cause - The original error or cause of the validation failure.\n * @param {TypeValidationContext} params.context - Optional context about what is being validated.\n * @returns {TypeValidationError} A TypeValidationError instance.\n */\n static wrap({\n value,\n cause,\n context\n }) {\n var _a15, _b15, _c;\n if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a15 = cause.context) == null ? void 0 : _a15.field) === (context == null ? void 0 : context.field) && ((_b15 = cause.context) == null ? void 0 : _b15.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) {\n return cause;\n }\n return new _TypeValidationError({ value, cause, context });\n }\n};\n\n// src/errors/unsupported-functionality-error.ts\nvar name13 = \"AI_UnsupportedFunctionalityError\";\nvar marker14 = `vercel.ai.error.${name13}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14, _b14;\nvar UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {\n constructor({\n functionality,\n message = `'${functionality}' functionality not supported.`\n }) {\n super({ name: name13, message });\n this[_a14] = true;\n this.functionality = functionality;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker14);\n }\n};\n\n// src/json-value/is-json.ts\nfunction isJSONValue(value) {\n if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return true;\n }\n if (Array.isArray(value)) {\n return value.every(isJSONValue);\n }\n if (typeof value === \"object\") {\n return Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n }\n return false;\n}\nfunction isJSONArray(value) {\n return Array.isArray(value) && value.every(isJSONValue);\n}\nfunction isJSONObject(value) {\n return value != null && typeof value === \"object\" && Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n}\nexport {\n AISDKError,\n APICallError,\n EmptyResponseBodyError,\n InvalidArgumentError,\n InvalidPromptError,\n InvalidResponseDataError,\n JSONParseError,\n LoadAPIKeyError,\n LoadSettingError,\n NoContentGeneratedError,\n NoSuchModelError,\n TooManyEmbeddingValuesForCallError,\n TypeValidationError,\n UnsupportedFunctionalityError,\n getErrorMessage,\n isJSONArray,\n isJSONObject,\n isJSONValue\n};\n//# sourceMappingURL=index.mjs.map" | ||
| ], | ||
| "mappings": ";AACA,IAAI,EAAS,kBACT,GAAS,OAAO,IAAI,CAAM,EAC1B,EAAI,EACJ,EAAa,MAAM,UAAqB,EAAK,MAAO,EAAK,GAA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F,CAAC,EACD,KAAK,GAAQ,GACb,KAAK,MAAQ,EACb,KAAK,QAAU,QAEV,WAAU,CAAC,EAAO,CACvB,OAAO,EAAW,UAAU,EAAO,EAAQ,QAatC,KAAI,EACT,QACA,QACA,WACC,CACD,IAAI,EAAM,EAAM,EAChB,GAAI,EAAqB,WAAW,CAAK,GAAK,EAAM,QAAU,KAAW,EAAO,EAAM,UAAY,KAAY,OAAI,EAAK,UAAY,GAAW,KAAY,OAAI,EAAQ,UAAY,EAAO,EAAM,UAAY,KAAY,OAAI,EAAK,eAAiB,GAAW,KAAY,OAAI,EAAQ,eAAiB,EAAK,EAAM,UAAY,KAAY,OAAI,EAAG,aAAe,GAAW,KAAY,OAAI,EAAQ,UAC/X,OAAO,EAET,OAAO,IAAI,EAAqB,CAAE,QAAO,QAAO,SAAQ,CAAC,EAE7D,EAGI,GAAS,mCACT,GAAW,mBAAmB,KAC9B,GAAW,OAAO,IAAI,EAAQ,EAC9B,EAAM,EACN,GAAgC,cAAe,EAAO,EAAY,EAAO,GAAU,EAAM,CAC3F,WAAW,EACT,gBACA,UAAU,IAAI,mCACb,CACD,MAAM,CAAE,KAAM,GAAQ,SAAQ,CAAC,EAC/B,KAAK,GAAQ,GACb,KAAK,cAAgB,QAEhB,WAAU,CAAC,EAAO,CACvB,OAAO,EAAW,UAAU,EAAO,EAAQ,EAE/C", | ||
| "debugId": "2E99BB5673AAF69B64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/fromContainerMetadata.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/ImdsCredentials.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/RemoteProviderInit.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/httpRequest.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/node-http.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/fromInstanceMetadata.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/error/InstanceMetadataV1FallbackError.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/utils/getInstanceMetadataEndpoint.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/config/Endpoint.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointConfigOptions.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointMode.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointModeConfigOptions.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/utils/getExtendedInstanceMetadataCredentials.js", "../../node_modules/.bun/@smithy+credential-provider-imds@4.5.2/node_modules/@smithy/credential-provider-imds/dist-es/utils/staticStabilityProvider.js"], | ||
| "sourcesContent": [ | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nimport { fromImdsCredentials, isImdsCredentials } from \"./remoteProvider/ImdsCredentials\";\nimport { providerConfigFromInit } from \"./remoteProvider/RemoteProviderInit\";\nimport { httpRequest } from \"./remoteProvider/httpRequest\";\nimport { retry } from \"./remoteProvider/retry\";\nexport const ENV_CMDS_FULL_URI = \"AWS_CONTAINER_CREDENTIALS_FULL_URI\";\nexport const ENV_CMDS_RELATIVE_URI = \"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\";\nexport const ENV_CMDS_AUTH_TOKEN = \"AWS_CONTAINER_AUTHORIZATION_TOKEN\";\nexport const fromContainerMetadata = (init = {}) => {\n const { timeout, maxRetries } = providerConfigFromInit(init);\n return () => retry(async () => {\n const requestOptions = await getCmdsUri({ logger: init.logger });\n const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions));\n if (!isImdsCredentials(credsResponse)) {\n throw new CredentialsProviderError(\"Invalid response received from instance metadata service.\", {\n logger: init.logger,\n });\n }\n return fromImdsCredentials(credsResponse);\n }, maxRetries);\n};\nconst requestFromEcsImds = async (timeout, options) => {\n if (process.env[ENV_CMDS_AUTH_TOKEN]) {\n options.headers = {\n ...options.headers,\n Authorization: process.env[ENV_CMDS_AUTH_TOKEN],\n };\n }\n const buffer = await httpRequest({\n ...options,\n timeout,\n });\n return buffer.toString();\n};\nconst CMDS_IP = \"169.254.170.2\";\nconst GREENGRASS_HOSTS = new Set([\"localhost\", \"127.0.0.1\"]);\nconst GREENGRASS_PROTOCOLS = new Set([\"http:\", \"https:\"]);\nconst getCmdsUri = async ({ logger }) => {\n if (process.env[ENV_CMDS_RELATIVE_URI]) {\n return {\n hostname: CMDS_IP,\n path: process.env[ENV_CMDS_RELATIVE_URI],\n };\n }\n if (process.env[ENV_CMDS_FULL_URI]) {\n let parsed;\n try {\n parsed = new URL(process.env[ENV_CMDS_FULL_URI]);\n }\n catch {\n throw new CredentialsProviderError(`${process.env[ENV_CMDS_FULL_URI]} is not a valid container metadata service URL`, { tryNextLink: false, logger });\n }\n if (!parsed.hostname || !GREENGRASS_HOSTS.has(parsed.hostname)) {\n throw new CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, {\n tryNextLink: false,\n logger,\n });\n }\n if (!parsed.protocol || !GREENGRASS_PROTOCOLS.has(parsed.protocol)) {\n throw new CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, {\n tryNextLink: false,\n logger,\n });\n }\n return {\n protocol: parsed.protocol,\n hostname: parsed.hostname,\n path: parsed.pathname + parsed.search,\n port: parsed.port ? parseInt(parsed.port, 10) : undefined,\n };\n }\n throw new CredentialsProviderError(\"The container metadata credential provider cannot be used unless\" +\n ` the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment` +\n \" variable is set\", {\n tryNextLink: false,\n logger,\n });\n};\n", | ||
| "export const isImdsCredentials = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.AccessKeyId === \"string\" &&\n typeof arg.SecretAccessKey === \"string\" &&\n typeof arg.Token === \"string\" &&\n typeof arg.Expiration === \"string\";\nexport const fromImdsCredentials = (creds) => ({\n accessKeyId: creds.AccessKeyId,\n secretAccessKey: creds.SecretAccessKey,\n sessionToken: creds.Token,\n expiration: new Date(creds.Expiration),\n ...(creds.AccountId && { accountId: creds.AccountId }),\n});\n", | ||
| "export const DEFAULT_TIMEOUT = 1000;\nexport const DEFAULT_MAX_RETRIES = 0;\nexport const providerConfigFromInit = ({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT, }) => ({ maxRetries, timeout });\n", | ||
| "import { ProviderError } from \"@smithy/core/config\";\nimport { node_http } from \"./node-http\";\nexport function httpRequest(options) {\n return new Promise((resolve, reject) => {\n const req = node_http.request({\n method: \"GET\",\n ...options,\n hostname: options.hostname?.replace(/^\\[(.+)\\]$/, \"$1\"),\n });\n req.on(\"error\", (err) => {\n reject(Object.assign(new ProviderError(\"Unable to connect to instance metadata service\"), err));\n req.destroy();\n });\n req.on(\"timeout\", () => {\n reject(new ProviderError(\"TimeoutError from instance metadata service\"));\n req.destroy();\n });\n req.on(\"response\", (res) => {\n const { statusCode = 400 } = res;\n if (statusCode < 200 || 300 <= statusCode) {\n reject(Object.assign(new ProviderError(\"Error response received from instance metadata service\"), { statusCode }));\n req.destroy();\n }\n const chunks = [];\n res.on(\"data\", (chunk) => {\n chunks.push(chunk);\n });\n res.on(\"end\", () => {\n resolve(Buffer.concat(chunks));\n req.destroy();\n });\n });\n req.end();\n });\n}\n", | ||
| "import node_http from \"node:http\";\nexport { node_http };\n", | ||
| "export const retry = (toRetry, maxRetries) => {\n let promise = toRetry();\n for (let i = 0; i < maxRetries; i++) {\n promise = promise.catch(toRetry);\n }\n return promise;\n};\n", | ||
| "import { CredentialsProviderError, loadConfig } from \"@smithy/core/config\";\nimport { InstanceMetadataV1FallbackError } from \"./error/InstanceMetadataV1FallbackError\";\nimport { fromImdsCredentials, isImdsCredentials } from \"./remoteProvider/ImdsCredentials\";\nimport { providerConfigFromInit } from \"./remoteProvider/RemoteProviderInit\";\nimport { httpRequest } from \"./remoteProvider/httpRequest\";\nimport { retry } from \"./remoteProvider/retry\";\nimport { getInstanceMetadataEndpoint } from \"./utils/getInstanceMetadataEndpoint\";\nimport { staticStabilityProvider } from \"./utils/staticStabilityProvider\";\nconst IMDS_PATH = \"/latest/meta-data/iam/security-credentials/\";\nconst IMDS_TOKEN_PATH = \"/latest/api/token\";\nconst AWS_EC2_METADATA_V1_DISABLED = \"AWS_EC2_METADATA_V1_DISABLED\";\nconst PROFILE_AWS_EC2_METADATA_V1_DISABLED = \"ec2_metadata_v1_disabled\";\nconst X_AWS_EC2_METADATA_TOKEN = \"x-aws-ec2-metadata-token\";\nexport const fromInstanceMetadata = (init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger });\nconst getInstanceMetadataProvider = (init = {}) => {\n let disableFetchToken = false;\n const { logger, profile } = init;\n const { timeout, maxRetries } = providerConfigFromInit(init);\n const getCredentials = async (maxRetries, options) => {\n const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null;\n if (isImdsV1Fallback) {\n let fallbackBlockedFromProfile = false;\n let fallbackBlockedFromProcessEnv = false;\n const configValue = await loadConfig({\n environmentVariableSelector: (env) => {\n const envValue = env[AWS_EC2_METADATA_V1_DISABLED];\n fallbackBlockedFromProcessEnv = !!envValue && envValue !== \"false\";\n if (envValue === undefined) {\n throw new CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init.logger });\n }\n return fallbackBlockedFromProcessEnv;\n },\n configFileSelector: (profile) => {\n const profileValue = profile[PROFILE_AWS_EC2_METADATA_V1_DISABLED];\n fallbackBlockedFromProfile = !!profileValue && profileValue !== \"false\";\n return fallbackBlockedFromProfile;\n },\n default: false,\n }, {\n profile,\n })();\n if (init.ec2MetadataV1Disabled || configValue) {\n const causes = [];\n if (init.ec2MetadataV1Disabled)\n causes.push(\"credential provider initialization (runtime option ec2MetadataV1Disabled)\");\n if (fallbackBlockedFromProfile)\n causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`);\n if (fallbackBlockedFromProcessEnv)\n causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`);\n throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(\", \")}].`);\n }\n }\n const imdsProfile = (await retry(async () => {\n let profile;\n try {\n profile = await getProfile(options);\n }\n catch (err) {\n if (err.statusCode === 401) {\n disableFetchToken = false;\n }\n throw err;\n }\n return profile;\n }, maxRetries)).trim();\n return retry(async () => {\n let creds;\n try {\n creds = await getCredentialsFromProfile(imdsProfile, options, init);\n }\n catch (err) {\n if (err.statusCode === 401) {\n disableFetchToken = false;\n }\n throw err;\n }\n return creds;\n }, maxRetries);\n };\n return async () => {\n const endpoint = await getInstanceMetadataEndpoint();\n if (disableFetchToken) {\n logger?.debug(\"AWS SDK Instance Metadata\", \"using v1 fallback (no token fetch)\");\n return getCredentials(maxRetries, { ...endpoint, timeout });\n }\n else {\n let token;\n try {\n token = (await getMetadataToken({ ...endpoint, timeout })).toString();\n }\n catch (error) {\n if (error?.statusCode === 400) {\n throw Object.assign(error, {\n message: \"EC2 Metadata token request returned error\",\n });\n }\n else if (error.message === \"TimeoutError\" || [403, 404, 405].includes(error.statusCode)) {\n disableFetchToken = true;\n }\n logger?.debug(\"AWS SDK Instance Metadata\", \"using v1 fallback (initial)\");\n return getCredentials(maxRetries, { ...endpoint, timeout });\n }\n return getCredentials(maxRetries, {\n ...endpoint,\n headers: {\n [X_AWS_EC2_METADATA_TOKEN]: token,\n },\n timeout,\n });\n }\n };\n};\nconst getMetadataToken = async (options) => httpRequest({\n ...options,\n path: IMDS_TOKEN_PATH,\n method: \"PUT\",\n headers: {\n \"x-aws-ec2-metadata-token-ttl-seconds\": \"21600\",\n },\n});\nconst getProfile = async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString();\nconst getCredentialsFromProfile = async (profile, options, init) => {\n const credentialsResponse = JSON.parse((await httpRequest({\n ...options,\n path: IMDS_PATH + profile,\n })).toString());\n if (!isImdsCredentials(credentialsResponse)) {\n throw new CredentialsProviderError(\"Invalid response received from instance metadata service.\", {\n logger: init.logger,\n });\n }\n return fromImdsCredentials(credentialsResponse);\n};\n", | ||
| "import { CredentialsProviderError } from \"@smithy/core/config\";\nexport class InstanceMetadataV1FallbackError extends CredentialsProviderError {\n tryNextLink;\n name = \"InstanceMetadataV1FallbackError\";\n constructor(message, tryNextLink = true) {\n super(message, tryNextLink);\n this.tryNextLink = tryNextLink;\n Object.setPrototypeOf(this, InstanceMetadataV1FallbackError.prototype);\n }\n}\n", | ||
| "import { loadConfig } from \"@smithy/core/config\";\nimport { parseUrl } from \"@smithy/core/protocols\";\nimport { Endpoint as InstanceMetadataEndpoint } from \"../config/Endpoint\";\nimport { ENDPOINT_CONFIG_OPTIONS } from \"../config/EndpointConfigOptions\";\nimport { EndpointMode } from \"../config/EndpointMode\";\nimport { ENDPOINT_MODE_CONFIG_OPTIONS, } from \"../config/EndpointModeConfigOptions\";\nexport const getInstanceMetadataEndpoint = async () => parseUrl((await getFromEndpointConfig()) || (await getFromEndpointModeConfig()));\nconst getFromEndpointConfig = async () => loadConfig(ENDPOINT_CONFIG_OPTIONS)();\nconst getFromEndpointModeConfig = async () => {\n const endpointMode = await loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)();\n switch (endpointMode) {\n case EndpointMode.IPv4:\n return InstanceMetadataEndpoint.IPv4;\n case EndpointMode.IPv6:\n return InstanceMetadataEndpoint.IPv6;\n default:\n throw new Error(`Unsupported endpoint mode: ${endpointMode}.` + ` Select from ${Object.values(EndpointMode)}`);\n }\n};\n", | ||
| "export var Endpoint;\n(function (Endpoint) {\n Endpoint[\"IPv4\"] = \"http://169.254.169.254\";\n Endpoint[\"IPv6\"] = \"http://[fd00:ec2::254]\";\n})(Endpoint || (Endpoint = {}));\n", | ||
| "export const ENV_ENDPOINT_NAME = \"AWS_EC2_METADATA_SERVICE_ENDPOINT\";\nexport const CONFIG_ENDPOINT_NAME = \"ec2_metadata_service_endpoint\";\nexport const ENDPOINT_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => env[ENV_ENDPOINT_NAME],\n configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME],\n default: undefined,\n};\n", | ||
| "export var EndpointMode;\n(function (EndpointMode) {\n EndpointMode[\"IPv4\"] = \"IPv4\";\n EndpointMode[\"IPv6\"] = \"IPv6\";\n})(EndpointMode || (EndpointMode = {}));\n", | ||
| "import { EndpointMode } from \"./EndpointMode\";\nexport const ENV_ENDPOINT_MODE_NAME = \"AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE\";\nexport const CONFIG_ENDPOINT_MODE_NAME = \"ec2_metadata_service_endpoint_mode\";\nexport const ENDPOINT_MODE_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => env[ENV_ENDPOINT_MODE_NAME],\n configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME],\n default: EndpointMode.IPv4,\n};\n", | ||
| "const STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60;\nconst STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60;\nconst STATIC_STABILITY_DOC_URL = \"https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html\";\nexport const getExtendedInstanceMetadataCredentials = (credentials, logger) => {\n const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS +\n Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS);\n const newExpiration = new Date(Date.now() + refreshInterval * 1000);\n logger.warn(\"Attempting credential expiration extension due to a credential service availability issue. A refresh of these \" +\n `credentials will be attempted after ${new Date(newExpiration)}.\\nFor more information, please visit: ` +\n STATIC_STABILITY_DOC_URL);\n const originalExpiration = credentials.originalExpiration ?? credentials.expiration;\n return {\n ...credentials,\n ...(originalExpiration ? { originalExpiration } : {}),\n expiration: newExpiration,\n };\n};\n", | ||
| "import { getExtendedInstanceMetadataCredentials } from \"./getExtendedInstanceMetadataCredentials\";\nexport const staticStabilityProvider = (provider, options = {}) => {\n const logger = options?.logger || console;\n let pastCredentials;\n return async () => {\n let credentials;\n try {\n credentials = await provider();\n if (credentials.expiration && credentials.expiration.getTime() < Date.now()) {\n credentials = getExtendedInstanceMetadataCredentials(credentials, logger);\n }\n }\n catch (e) {\n if (pastCredentials) {\n logger.warn(\"Credential renew failed: \", e);\n credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger);\n }\n else {\n throw e;\n }\n }\n pastCredentials = credentials;\n return credentials;\n };\n};\n" | ||
| ], | ||
| "mappings": ";6JAAA,eCAO,IAAM,EAAoB,CAAC,IAAQ,QAAQ,CAAG,GACjD,OAAO,IAAQ,UACf,OAAO,EAAI,cAAgB,UAC3B,OAAO,EAAI,kBAAoB,UAC/B,OAAO,EAAI,QAAU,UACrB,OAAO,EAAI,aAAe,SACjB,EAAsB,CAAC,KAAW,CAC3C,YAAa,EAAM,YACnB,gBAAiB,EAAM,gBACvB,aAAc,EAAM,MACpB,WAAY,IAAI,KAAK,EAAM,UAAU,KACjC,EAAM,WAAa,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AAe,EAAY,IAC3B,EACH,QAAS,EACJ,GAA2B,CAChC,EACA,SACJ,CAAC,KAIP,GAAmB,MAAO,IAAY,EAAY,IACjD,EACH,KAAM,GACN,OAAQ,MACR,QAAS,CACL,uCAAwC,OAC5C,CACJ,CAAC,EACK,GAAa,MAAO,KAAa,MAAM,EAAY,IAAK,EAAS,KAAM,CAAU,CAAC,GAAG,SAAS,EAC9F,GAA4B,MAAO,EAAS,EAAS,IAAS,CAChE,IAAM,EAAsB,KAAK,OAAO,MAAM,EAAY,IACnD,EACH,KAAM,EAAY,CACtB,CAAC,GAAG,SAAS,CAAC,EACd,GAAI,CAAC,EAAkB,CAAmB,EACtC,MAAM,IAAI,2BAAyB,4DAA6D,CAC5F,OAAQ,EAAK,MACjB,CAAC,EAEL,OAAO,EAAoB,CAAmB", | ||
| "debugId": "58F94166237E14D864756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "399D41173AEABBC064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/pair.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { OpenCode } from \"@opencode-ai/client/promise\"\nimport { renderUnicodeCompact } from \"uqr\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { ServiceConfig } from \"../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.pair,\n Effect.fn(\"cli.pair\")(function* () {\n const endpoint = yield* Service.ensure(yield* ServiceConfig.options())\n const password = yield* ServiceConfig.password()\n const server = yield* Effect.tryPromise(() =>\n OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }).server.get(),\n )\n const info = { urls: server.urls, username: \"opencode\", password }\n process.stdout.write(\n [\n \"\",\n ` URLs ${info.urls[0] ?? \"(none)\"}`,\n ...info.urls.slice(1).map((url) => ` ${url}`),\n ` Username ${info.username}`,\n ` Password ${info.password}`,\n \"\",\n \" Scan to pair\",\n \"\",\n renderUnicodeCompact(JSON.stringify(info), { border: 2 })\n .split(EOL)\n .map((line) => \" \" + line)\n .join(EOL),\n \"\",\n ].join(EOL) + EOL,\n )\n\n const hostname = new URL(endpoint.url).hostname\n if (![\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(hostname)) return\n process.stderr.write(` Run \\`opencode service set hostname 0.0.0.0\\` to access the service remotely.${EOL}${EOL}`)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";8/BAAA,cAAS,WAST,IAAe,IAAQ,QACrB,EAAS,SAAS,KAClB,EAAO,GAAG,UAAU,EAAE,SAAU,EAAG,CACjC,IAAM,EAAW,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EAC/D,EAAW,MAAO,EAAc,SAAS,EAIzC,EAAO,CAAE,MAHA,MAAO,EAAO,WAAW,IACtC,EAAS,KAAK,CAAE,QAAS,EAAS,IAAK,QAAS,EAAQ,QAAQ,CAAQ,CAAE,CAAC,EAAE,OAAO,IAAI,CAC1F,GAC4B,KAAM,SAAU,WAAY,UAAS,EACjE,QAAQ,OAAO,MACb,CACE,GACA,eAAe,EAAK,KAAK,IAAM,WAC/B,GAAG,EAAK,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,IAAQ,eAAe,GAAK,EACvD,eAAe,EAAK,WACpB,eAAe,EAAK,WACpB,GACA,iBACA,GACA,EAAqB,KAAK,UAAU,CAAI,EAAG,CAAE,OAAQ,CAAE,CAAC,EACrD,MAAM,CAAG,EACT,IAAI,CAAC,IAAS,KAAO,CAAI,EACzB,KAAK,CAAG,EACX,EACF,EAAE,KAAK,CAAG,EAAI,CAChB,EAEA,IAAM,EAAW,IAAI,IAAI,EAAS,GAAG,EAAE,SACvC,GAAI,CAAC,CAAC,YAAa,YAAa,OAAO,EAAE,SAAS,CAAQ,EAAG,OAC7D,QAAQ,OAAO,MAAM,kFAAkF,IAAM,GAAK,EACnH,CACH", | ||
| "debugId": "FE920E2121C65FCE64756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": ["../../node_modules/.bun/@aws-sdk+nested-clients@3.997.43/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/cognito-identity/index.js"], | ||
| "sourcesContent": [ | ||
| "const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = require(\"@aws-sdk/core/client\");\nconst { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = require(\"@smithy/core\");\nconst { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = require(\"@smithy/core/client\");\nconst { Command: $Command } = require(\"@smithy/core/client\");\nexports.$Command = $Command;\nexports.__Client = Client;\nconst { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = require(\"@smithy/core/config\");\nconst { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = require(\"@smithy/core/endpoints\");\nconst { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = require(\"@smithy/core/protocols\");\nconst { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = require(\"@smithy/core/retry\");\nconst { TypeRegistry, getSchemaSerdePlugin } = require(\"@smithy/core/schema\");\nconst { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = require(\"@aws-sdk/core/httpAuthSchemes\");\nconst { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = require(\"@smithy/core/serde\");\nconst { streamCollector, NodeHttpHandler } = require(\"@smithy/node-http-handler\");\nconst { AwsJson1_1Protocol } = require(\"@aws-sdk/core/protocols\");\nconst { Sha256 } = require(\"@smithy/core/checksum\");\n\nconst defaultCognitoIdentityHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"cognito-identity\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nconst defaultCognitoIdentityHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"GetCredentialsForIdentity\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n case \"GetId\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption());\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nconst resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n\nconst resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"cognito-identity\",\n });\n};\nconst commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n\nvar version = \"3.997.42\";\nvar packageInfo = {\n\tversion: version};\n\nconst m = \"ref\";\nconst a = -1, b = true, c = \"isSet\", d = \"PartitionResult\", e = \"booleanEquals\", f = \"getAttr\", g = \"stringEquals\", h = { [m]: \"Endpoint\" }, i = { [m]: d }, j = { [m]: \"Region\" }, k = {}, l = [j];\nconst _data = {\n conditions: [\n [c, [h]],\n [c, l],\n [\"aws.partition\", l, d],\n [e, [{ [m]: \"UseFIPS\" }, b]],\n [e, [{ fn: f, argv: [i, \"supportsFIPS\"] }, b]],\n [e, [{ [m]: \"UseDualStack\" }, b]],\n [e, [{ fn: f, argv: [i, \"supportsDualStack\"] }, b]],\n [g, [{ fn: f, argv: [i, \"name\"] }, \"aws\"]],\n [g, [j, \"us-east-1\"]],\n [g, [j, \"us-east-2\"]],\n [g, [j, \"us-west-1\"]],\n [g, [j, \"us-west-2\"]]\n ],\n results: [\n [a],\n [a, \"Invalid Configuration: FIPS and custom endpoint are not supported\"],\n [a, \"Invalid Configuration: Dualstack and custom endpoint are not supported\"],\n [h, k],\n [\"https://cognito-identity-fips.us-east-1.amazonaws.com\", k],\n [\"https://cognito-identity-fips.us-east-2.amazonaws.com\", k],\n [\"https://cognito-identity-fips.us-west-1.amazonaws.com\", k],\n [\"https://cognito-identity-fips.us-west-2.amazonaws.com\", k],\n [\"https://cognito-identity-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", k],\n [a, \"FIPS and DualStack are enabled, but this partition does not support one or both\"],\n [\"https://cognito-identity-fips.{Region}.{PartitionResult#dnsSuffix}\", k],\n [a, \"FIPS is enabled but this partition does not support FIPS\"],\n [\"https://cognito-identity.{Region}.amazonaws.com\", k],\n [\"https://cognito-identity.{Region}.{PartitionResult#dualStackDnsSuffix}\", k],\n [a, \"DualStack is enabled but this partition does not support DualStack\"],\n [\"https://cognito-identity.{Region}.{PartitionResult#dnsSuffix}\", k],\n [a, \"Invalid Configuration: Missing Region\"]\n ]\n};\nconst root = 2;\nconst r = 100_000_000;\nconst nodes = new Int32Array([\n -1, 1, -1,\n 0, 17, 3,\n 1, 4, r + 16,\n 2, 5, r + 16,\n 3, 9, 6,\n 5, 7, r + 15,\n 6, 8, r + 14,\n 7, r + 12, r + 13,\n 4, 11, 10,\n 5, r + 9, r + 11,\n 5, 12, r + 10,\n 6, 13, r + 9,\n 8, r + 4, 14,\n 9, r + 5, 15,\n 10, r + 6, 16,\n 11, r + 7, r + 8,\n 3, r + 1, 18,\n 5, r + 2, r + 3,\n]);\nconst bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results);\n\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nconst defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => decideEndpoint(bdd, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n\nclass CognitoIdentityServiceException extends ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, CognitoIdentityServiceException.prototype);\n }\n}\n\nclass ExternalServiceException extends CognitoIdentityServiceException {\n name = \"ExternalServiceException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ExternalServiceException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ExternalServiceException.prototype);\n }\n}\nclass InternalErrorException extends CognitoIdentityServiceException {\n name = \"InternalErrorException\";\n $fault = \"server\";\n constructor(opts) {\n super({\n name: \"InternalErrorException\",\n $fault: \"server\",\n ...opts,\n });\n Object.setPrototypeOf(this, InternalErrorException.prototype);\n }\n}\nclass InvalidIdentityPoolConfigurationException extends CognitoIdentityServiceException {\n name = \"InvalidIdentityPoolConfigurationException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"InvalidIdentityPoolConfigurationException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidIdentityPoolConfigurationException.prototype);\n }\n}\nclass InvalidParameterException extends CognitoIdentityServiceException {\n name = \"InvalidParameterException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"InvalidParameterException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidParameterException.prototype);\n }\n}\nclass NotAuthorizedException extends CognitoIdentityServiceException {\n name = \"NotAuthorizedException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"NotAuthorizedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, NotAuthorizedException.prototype);\n }\n}\nclass ResourceConflictException extends CognitoIdentityServiceException {\n name = \"ResourceConflictException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ResourceConflictException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ResourceConflictException.prototype);\n }\n}\nclass ResourceNotFoundException extends CognitoIdentityServiceException {\n name = \"ResourceNotFoundException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ResourceNotFoundException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ResourceNotFoundException.prototype);\n }\n}\nclass TooManyRequestsException extends CognitoIdentityServiceException {\n name = \"TooManyRequestsException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"TooManyRequestsException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, TooManyRequestsException.prototype);\n }\n}\nclass LimitExceededException extends CognitoIdentityServiceException {\n name = \"LimitExceededException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"LimitExceededException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, LimitExceededException.prototype);\n }\n}\n\nconst _AI = \"AccountId\";\nconst _AKI = \"AccessKeyId\";\nconst _C = \"Credentials\";\nconst _CRA = \"CustomRoleArn\";\nconst _E = \"Expiration\";\nconst _ESE = \"ExternalServiceException\";\nconst _GCFI = \"GetCredentialsForIdentity\";\nconst _GCFII = \"GetCredentialsForIdentityInput\";\nconst _GCFIR = \"GetCredentialsForIdentityResponse\";\nconst _GI = \"GetId\";\nconst _GII = \"GetIdInput\";\nconst _GIR = \"GetIdResponse\";\nconst _IEE = \"InternalErrorException\";\nconst _II = \"IdentityId\";\nconst _IIPCE = \"InvalidIdentityPoolConfigurationException\";\nconst _IPE = \"InvalidParameterException\";\nconst _IPI = \"IdentityPoolId\";\nconst _IPT = \"IdentityProviderToken\";\nconst _L = \"Logins\";\nconst _LEE = \"LimitExceededException\";\nconst _LM = \"LoginsMap\";\nconst _NAE = \"NotAuthorizedException\";\nconst _RCE = \"ResourceConflictException\";\nconst _RNFE = \"ResourceNotFoundException\";\nconst _SK = \"SecretKey\";\nconst _SKS = \"SecretKeyString\";\nconst _ST = \"SessionToken\";\nconst _TMRE = \"TooManyRequestsException\";\nconst _c = \"client\";\nconst _e = \"error\";\nconst _hE = \"httpError\";\nconst _m = \"message\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.cognitoidentity\";\nconst _se = \"server\";\nconst n0 = \"com.amazonaws.cognitoidentity\";\nconst _s_registry = TypeRegistry.for(_s);\nvar CognitoIdentityServiceException$ = [-3, _s, \"CognitoIdentityServiceException\", 0, [], []];\n_s_registry.registerError(CognitoIdentityServiceException$, CognitoIdentityServiceException);\nconst n0_registry = TypeRegistry.for(n0);\nvar ExternalServiceException$ = [-3, n0, _ESE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(ExternalServiceException$, ExternalServiceException);\nvar InternalErrorException$ = [-3, n0, _IEE,\n { [_e]: _se },\n [_m],\n [0]\n];\nn0_registry.registerError(InternalErrorException$, InternalErrorException);\nvar InvalidIdentityPoolConfigurationException$ = [-3, n0, _IIPCE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(InvalidIdentityPoolConfigurationException$, InvalidIdentityPoolConfigurationException);\nvar InvalidParameterException$ = [-3, n0, _IPE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(InvalidParameterException$, InvalidParameterException);\nvar LimitExceededException$ = [-3, n0, _LEE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nn0_registry.registerError(LimitExceededException$, LimitExceededException);\nvar NotAuthorizedException$ = [-3, n0, _NAE,\n { [_e]: _c, [_hE]: 403 },\n [_m],\n [0]\n];\nn0_registry.registerError(NotAuthorizedException$, NotAuthorizedException);\nvar ResourceConflictException$ = [-3, n0, _RCE,\n { [_e]: _c, [_hE]: 409 },\n [_m],\n [0]\n];\nn0_registry.registerError(ResourceConflictException$, ResourceConflictException);\nvar ResourceNotFoundException$ = [-3, n0, _RNFE,\n { [_e]: _c, [_hE]: 404 },\n [_m],\n [0]\n];\nn0_registry.registerError(ResourceNotFoundException$, ResourceNotFoundException);\nvar TooManyRequestsException$ = [-3, n0, _TMRE,\n { [_e]: _c, [_hE]: 429 },\n [_m],\n [0]\n];\nn0_registry.registerError(TooManyRequestsException$, TooManyRequestsException);\nconst errorTypeRegistries = [\n _s_registry,\n n0_registry,\n];\nvar IdentityProviderToken = [0, n0, _IPT, 8, 0];\nvar SecretKeyString = [0, n0, _SKS, 8, 0];\nvar Credentials$ = [3, n0, _C,\n 0,\n [_AKI, _SK, _ST, _E],\n [0, [() => SecretKeyString, 0], 0, 4]\n];\nvar GetCredentialsForIdentityInput$ = [3, n0, _GCFII,\n 0,\n [_II, _L, _CRA],\n [0, [() => LoginsMap, 0], 0], 1\n];\nvar GetCredentialsForIdentityResponse$ = [3, n0, _GCFIR,\n 0,\n [_II, _C],\n [0, [() => Credentials$, 0]]\n];\nvar GetIdInput$ = [3, n0, _GII,\n 0,\n [_IPI, _AI, _L],\n [0, 0, [() => LoginsMap, 0]], 1\n];\nvar GetIdResponse$ = [3, n0, _GIR,\n 0,\n [_II],\n [0]\n];\nvar LoginsMap = [2, n0, _LM,\n 0, [0,\n 0],\n [() => IdentityProviderToken,\n 0]\n];\nvar GetCredentialsForIdentity$ = [9, n0, _GCFI,\n 0, () => GetCredentialsForIdentityInput$, () => GetCredentialsForIdentityResponse$\n];\nvar GetId$ = [9, n0, _GI,\n 0, () => GetIdInput$, () => GetIdResponse$\n];\n\nconst getRuntimeConfig$1 = (config) => {\n return {\n apiVersion: \"2014-06-30\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultCognitoIdentityHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsJson1_1Protocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.cognitoidentity\",\n errorTypeRegistries,\n xmlNamespace: \"http://cognito-identity.amazonaws.com/doc/2014-06-30/\",\n version: \"2014-06-30\",\n serviceTarget: \"AWSCognitoIdentityService\",\n },\n serviceId: config?.serviceId ?? \"Cognito Identity\",\n sha256: config?.sha256 ?? Sha256,\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n\nconst getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getRuntimeConfig$1(config);\n emitWarningIfUnsupportedVersion$1(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n\nconst getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nconst resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n\nconst resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n\nclass CognitoIdentityClient extends Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultCognitoIdentityHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n\nconst command = makeBuilder(commonParams, \"AWSCognitoIdentityService\", \"CognitoIdentityClient\", getEndpointPlugin);\nconst _ep0 = {};\nconst _mw0 = (Command, cs, config, o) => [];\n\nclass GetCredentialsForIdentityCommand extends command(_ep0, _mw0, \"GetCredentialsForIdentity\", GetCredentialsForIdentity$) {\n}\n\nclass GetIdCommand extends command(_ep0, _mw0, \"GetId\", GetId$) {\n}\n\nconst commands = {\n GetCredentialsForIdentityCommand,\n GetIdCommand,\n};\nclass CognitoIdentity extends CognitoIdentityClient {\n}\ncreateAggregatedClient(commands, CognitoIdentity);\n\nexports.CognitoIdentity = CognitoIdentity;\nexports.CognitoIdentityClient = CognitoIdentityClient;\nexports.CognitoIdentityServiceException = CognitoIdentityServiceException;\nexports.CognitoIdentityServiceException$ = CognitoIdentityServiceException$;\nexports.Credentials$ = Credentials$;\nexports.ExternalServiceException = ExternalServiceException;\nexports.ExternalServiceException$ = ExternalServiceException$;\nexports.GetCredentialsForIdentity$ = GetCredentialsForIdentity$;\nexports.GetCredentialsForIdentityCommand = GetCredentialsForIdentityCommand;\nexports.GetCredentialsForIdentityInput$ = GetCredentialsForIdentityInput$;\nexports.GetCredentialsForIdentityResponse$ = GetCredentialsForIdentityResponse$;\nexports.GetId$ = GetId$;\nexports.GetIdCommand = GetIdCommand;\nexports.GetIdInput$ = GetIdInput$;\nexports.GetIdResponse$ = GetIdResponse$;\nexports.InternalErrorException = InternalErrorException;\nexports.InternalErrorException$ = InternalErrorException$;\nexports.InvalidIdentityPoolConfigurationException = InvalidIdentityPoolConfigurationException;\nexports.InvalidIdentityPoolConfigurationException$ = InvalidIdentityPoolConfigurationException$;\nexports.InvalidParameterException = InvalidParameterException;\nexports.InvalidParameterException$ = InvalidParameterException$;\nexports.LimitExceededException = LimitExceededException;\nexports.LimitExceededException$ = LimitExceededException$;\nexports.NotAuthorizedException = NotAuthorizedException;\nexports.NotAuthorizedException$ = NotAuthorizedException$;\nexports.ResourceConflictException = ResourceConflictException;\nexports.ResourceConflictException$ = ResourceConflictException$;\nexports.ResourceNotFoundException = ResourceNotFoundException;\nexports.ResourceNotFoundException$ = ResourceNotFoundException$;\nexports.TooManyRequestsException = TooManyRequestsException;\nexports.TooManyRequestsException$ = TooManyRequestsException$;\nexports.errorTypeRegistries = errorTypeRegistries;\n" | ||
| ], | ||
| "mappings": ";uXAAA,IAAQ,wBAAsB,gCAAiC,GAAmC,kCAAgC,8BAA4B,sCAAoC,0CAAwC,0BAAwB,2BAAyB,sBAAoB,uBAAqB,mBAAiB,sCAC7U,gBAAc,0CAAwC,iCAA+B,+BACrF,oBAAmB,oBAAkB,oBAAkB,cAAY,mCAAiC,6BAA2B,oCAAkC,+BAA6B,UAAQ,eAAa,gCACnN,QAAS,QAGjB,IAAQ,6BAA2B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,KAAK,gBAAgB,IAAI,GAAuB,KAAK,MAAM,CAAC,EAC5D,KAAK,gBAAgB,IAAI,GAAoB,KAAK,MAAM,CAAC,EACzD,KAAK,gBAAgB,IAAI,GAAgB,KAAK,MAAM,CAAC,EACrD,KAAK,gBAAgB,IAAI,GAA4B,KAAK,MAAM,CAAC,EACjE,KAAK,gBAAgB,IAAI,GAAuC,KAAK,OAAQ,CACzE,iCAAkC,GAClC,+BAAgC,MAAO,KAAW,IAAI,GAA8B,CAChF,iBAAkB,GAAO,WAC7B,CAAC,CACL,CAAC,CAAC,EACF,KAAK,gBAAgB,IAAI,GAAqB,KAAK,MAAM,CAAC,EAE9D,OAAO,EAAG,CACN,MAAM,QAAQ,EAEtB,CAEA,IAAM,EAAU,GAAY,GAAc,4BAA6B,wBAAyB,EAAiB,EAC3G,GAAO,CAAC,EACR,GAAO,CAAC,EAAS,EAAI,EAAQ,IAAM,CAAC,EAE1C,MAAM,UAAyC,EAAQ,GAAM,GAAM,4BAA6B,EAA0B,CAAE,CAC5H,CAEA,MAAM,UAAqB,EAAQ,GAAM,GAAM,QAAS,EAAM,CAAE,CAChE,CAEA,IAAM,GAAW,CACb,mCACA,cACJ,EACA,MAAM,WAAwB,CAAsB,CACpD,CACA,GAAuB,GAAU,EAAe,EAGhD,IAAQ,GAAwB,EAOhC,IAAQ,GAAmC,EAI3C,IAAQ,GAAe", | ||
| "debugId": "D796B439FF07B45664756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/api.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"node:os\"\nimport { Effect, Option } from \"effect\"\nimport { Commands } from \"../commands\"\nimport { Runtime } from \"../../framework/runtime\"\nimport { Service, type Endpoint } from \"@opencode-ai/client/effect/service\"\nimport { ServerConnection } from \"../../services/server-connection\"\n\nconst methods = new Set([\"delete\", \"get\", \"head\", \"options\", \"patch\", \"post\", \"put\"])\n\ntype Operation = {\n operationId?: string\n}\n\ntype OpenApi = {\n paths?: Record<string, Record<string, Operation>>\n}\n\nexport default Runtime.handler(\n Commands.commands.api,\n Effect.fn(\"cli.api\")(function* (input) {\n const server = yield* ServerConnection.resolve({\n server: Option.getOrUndefined(input.server),\n standalone: input.standalone,\n mismatch: \"ignore\",\n })\n const endpoint = server.endpoint\n const params = Option.getOrElse(input.param, () => ({}))\n const request = yield* resolveRequest(endpoint, input.request, params)\n const headers = new Headers(Service.headers(endpoint))\n for (const header of input.header) {\n const index = header.indexOf(\":\")\n if (index < 1) return yield* Effect.fail(new Error(`Invalid header, expected name:value: ${header}`))\n headers.set(header.slice(0, index).trim(), header.slice(index + 1).trim())\n }\n const body = Option.getOrUndefined(input.data)\n if (body !== undefined && !headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\")\n\n const response = yield* Effect.tryPromise(() =>\n fetch(new URL(request.path, endpoint.url), {\n method: request.method,\n headers,\n body,\n }),\n )\n const output = yield* Effect.promise(() => response.text())\n if (output) process.stdout.write(output + (output.endsWith(EOL) ? \"\" : EOL))\n }),\n)\n\nexport function resolveOperation(spec: OpenApi, operationID: string, params: Record<string, string>) {\n for (const [path, operations] of Object.entries(spec.paths ?? {})) {\n for (const [method, operation] of Object.entries(operations)) {\n if (!methods.has(method) || operation.operationId !== operationID) continue\n return { method: method.toUpperCase(), path: interpolate(path, params) }\n }\n }\n throw new Error(`Operation not found: ${operationID}`)\n}\n\nexport function rawRequest(input: readonly string[]) {\n if (input.length !== 2 || !methods.has(input[0].toLowerCase()) || !input[1].startsWith(\"/\")) return\n return { method: input[0].toUpperCase(), path: input[1] }\n}\n\nfunction resolveRequest(endpoint: Endpoint, input: readonly string[], params: Record<string, string>) {\n const raw = rawRequest(input)\n if (raw) return Effect.succeed(raw)\n if (input.length !== 1) return Effect.fail(new Error(\"Expected an operation name or an HTTP method and path\"))\n return Effect.tryPromise(async () => {\n const response = await fetch(new URL(\"/openapi.json\", endpoint.url), { headers: Service.headers(endpoint) })\n if (!response.ok) throw new Error(`Failed to load OpenAPI document: HTTP ${response.status}`)\n return resolveOperation((await response.json()) as OpenApi, input[0], params)\n })\n}\n\nfunction interpolate(path: string, params: Record<string, string>) {\n const used = new Set<string>()\n const pathname = path.replaceAll(/\\{([^}]+)\\}/g, (_, name: string) => {\n const value = params[name]\n if (value === undefined) throw new Error(`Missing path parameter: ${name}`)\n used.add(name)\n return encodeURIComponent(value)\n })\n const query = new URLSearchParams(Object.entries(params).filter(([name]) => !used.has(name))).toString()\n return query ? `${pathname}?${query}` : pathname\n}\n" | ||
| ], | ||
| "mappings": ";0jCAAA,cAAS,WAOT,IAAM,EAAU,IAAI,IAAI,CAAC,SAAU,MAAO,OAAQ,UAAW,QAAS,OAAQ,KAAK,CAAC,EAUrE,IAAQ,QACrB,EAAS,SAAS,IAClB,EAAO,GAAG,SAAS,EAAE,SAAU,CAAC,EAAO,CAMrC,IAAM,GALS,MAAO,EAAiB,QAAQ,CAC7C,OAAQ,EAAO,eAAe,EAAM,MAAM,EAC1C,WAAY,EAAM,WAClB,SAAU,QACZ,CAAC,GACuB,SAClB,EAAS,EAAO,UAAU,EAAM,MAAO,KAAO,CAAC,EAAE,EACjD,EAAU,MAAO,EAAe,EAAU,EAAM,QAAS,CAAM,EAC/D,EAAU,IAAI,QAAQ,EAAQ,QAAQ,CAAQ,CAAC,EACrD,QAAW,KAAU,EAAM,OAAQ,CACjC,IAAM,EAAQ,EAAO,QAAQ,GAAG,EAChC,GAAI,EAAQ,EAAG,OAAO,MAAO,EAAO,KAAS,MAAM,wCAAwC,GAAQ,CAAC,EACpG,EAAQ,IAAI,EAAO,MAAM,EAAG,CAAK,EAAE,KAAK,EAAG,EAAO,MAAM,EAAQ,CAAC,EAAE,KAAK,CAAC,EAE3E,IAAM,EAAO,EAAO,eAAe,EAAM,IAAI,EAC7C,GAAI,IAAS,QAAa,CAAC,EAAQ,IAAI,cAAc,EAAG,EAAQ,IAAI,eAAgB,kBAAkB,EAEtG,IA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OAAO,EAAkB,MAAM,EAAS,KAAK,EAAe,EAAM,GAAI,CAAM,EAC7E,EAGH,SAAS,CAAW,CAAC,EAAc,EAAgC,CACjE,IAAM,EAAO,IAAI,IACX,EAAW,EAAK,WAAW,eAAgB,CAAC,EAAG,IAAiB,CACpE,IAAM,EAAQ,EAAO,GACrB,GAAI,IAAU,OAAW,MAAU,MAAM,2BAA2B,GAAM,EAE1E,OADA,EAAK,IAAI,CAAI,EACN,mBAAmB,CAAK,EAChC,EACK,EAAQ,IAAI,gBAAgB,OAAO,QAAQ,CAAM,EAAE,OAAO,EAAE,KAAU,CAAC,EAAK,IAAI,CAAI,CAAC,CAAC,EAAE,SAAS,EACvG,OAAO,EAAQ,GAAG,KAAY,IAAU", | ||
| "debugId": "2B41367A6F5476D064756E2164756E21", | ||
| "names": [] | ||
| } |
| { | ||
| "version": 3, | ||
| "sources": [], | ||
| "sourcesContent": [ | ||
| ], | ||
| "mappings": "", | ||
| "debugId": "81BFC8497E61546164756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["../core/src/mcp/oauth.ts"], | ||
| "sourcesContent": [ | ||
| "export * as McpOAuth from \"./oauth.js\"\n\nimport { auth, type OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\"\nimport type { OAuthClientInformationMixed, OAuthTokens } from \"@modelcontextprotocol/sdk/shared/auth.js\"\nimport { Deferred, Effect } from \"effect\"\nimport { Credential } from \"@opencode-ai/schema/credential\"\nimport { ConfigMCP } from \"@opencode-ai/schema/config/mcp\"\nimport { OauthCallbackPage } from \"../oauth/page.js\"\nimport type { Integration } from \"../integration.js\"\n\n/** Persists the OAuth artifacts for one MCP server session: DCR client info, PKCE verifier, and tokens. */\nexport interface Store {\n readonly tokens: () => Promise<OAuthTokens | undefined>\n readonly saveTokens: (tokens: OAuthTokens) => Promise<void>\n readonly clientInformation: () => Promise<OAuthClientInformationMixed | undefined>\n readonly saveClientInformation: (info: OAuthClientInformationMixed) => Promise<void>\n readonly codeVerifier: () => Promise<string | undefined>\n readonly saveCodeVerifier: (verifier: string) => Promise<void>\n}\n\nexport interface Options {\n /** Loopback URL the authorization server redirects back to after the user approves. */\n readonly redirectUrl: string\n /** Space-delimited OAuth scopes to request when the server requires specific ones. */\n readonly scope?: string\n /** CSRF state embedded in the authorization request; required by the spec and enforced by some servers.\n * The caller is responsible for validating the value echoed back to the redirect. */\n readonly state?: string\n /** Statically pre-registered client credentials from config; when set, the SDK skips dynamic registration. */\n readonly client?: { readonly id: string; readonly secret?: string }\n /** Invoked by the SDK to drop credentials it has determined are invalid (e.g. a rejected refresh token). */\n readonly invalidate?: (scope: \"all\" | \"client\" | \"tokens\" | \"verifier\" | \"discovery\") => void | Promise<void>\n /** Receives the authorization URL so the caller can open a browser and capture the eventual code. */\n readonly onRedirect: (url: URL) => void | Promise<void>\n readonly store: Store\n}\n\n/**\n * Builds the MCP SDK's OAuthClientProvider. The SDK drives dynamic client registration, PKCE, and\n * token refresh through these callbacks; we only persist whatever it hands back via `store`.\n */\nexport const provider = (options: Options): OAuthClientProvider => {\n const state = options.state\n const client = options.client\n return {\n redirectUrl: options.redirectUrl,\n clientMetadata: {\n redirect_uris: [options.redirectUrl],\n client_name: \"opencode\",\n client_uri: \"https://opencode.ai\",\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n token_endpoint_auth_method: client?.secret ? \"client_secret_post\" : \"none\",\n ...(options.scope ? { scope: options.scope } : {}),\n },\n // Only advertise state when the caller supplied one (the interactive flow); the connect-time\n // provider has no redirect to validate, so it omits it.\n ...(state !== undefined ? { state: () => state } : {}),\n // Static client config short-circuits dynamic registration; otherwise the SDK registers and we persist.\n clientInformation: () =>\n client ? { client_id: client.id, client_secret: client.secret } : options.store.clientInformation(),\n saveClientInformation: (info) => options.store.saveClientInformation(info),\n tokens: () => options.store.tokens(),\n saveTokens: (tokens) => options.store.saveTokens(tokens),\n redirectToAuthorization: (url) => options.onRedirect(url),\n ...(options.invalidate ? { invalidateCredentials: options.invalidate } : {}),\n saveCodeVerifier: (verifier) => options.store.saveCodeVerifier(verifier),\n // The SDK only reads the verifier back after saving one earlier in the same flow; a miss means\n // the flow was resumed without its session state, which the SDK surfaces as an auth failure.\n codeVerifier: async () => {\n const verifier = await options.store.codeVerifier()\n if (!verifier) throw new Error(\"Missing PKCE code verifier for MCP OAuth flow\")\n return verifier\n },\n }\n}\n\n/** A Store that keeps OAuth artifacts in memory for the duration of one interactive login attempt. */\nexport const memoryStore = (): Store => {\n let tokens: OAuthTokens | undefined\n let client: OAuthClientInformationMixed | undefined\n let verifier: string | undefined\n return {\n tokens: async () => tokens,\n saveTokens: async (value) => {\n tokens = value\n },\n clientInformation: async () => client,\n saveClientInformation: async (value) => {\n client = value\n },\n codeVerifier: async () => verifier,\n saveCodeVerifier: async (value) => {\n verifier = value\n },\n }\n}\n\n/** Reads the dynamically-registered client info we stash in a credential's metadata, for token refresh. */\nexport const clientFromCredential = (credential: Credential.OAuth) =>\n credential.metadata?.client as OAuthClientInformationMixed | undefined\n\n/** Folds SDK tokens (plus DCR client info and the server URL) into a storable credential. */\nexport const toCredential = (input: {\n readonly methodID: Integration.MethodID\n readonly serverUrl: string\n readonly tokens: OAuthTokens\n readonly client: OAuthClientInformationMixed | undefined\n}) =>\n Credential.OAuth.make({\n type: \"oauth\",\n methodID: input.methodID,\n access: input.tokens.access_token,\n refresh: input.tokens.refresh_token ?? \"\",\n // 0 marks an unknown/non-expiring token; toTokens then omits expires_in so the SDK won't force a refresh.\n expires: input.tokens.expires_in ? Date.now() + input.tokens.expires_in * 1000 : 0,\n metadata: {\n serverUrl: input.serverUrl,\n tokenType: input.tokens.token_type,\n ...(input.tokens.scope ? { scope: input.tokens.scope } : {}),\n ...(input.client ? { client: input.client } : {}),\n },\n })\n\n/** Reconstructs SDK tokens from a stored credential so the connect-time provider can present them. */\nexport const toTokens = (credential: Credential.OAuth): OAuthTokens => {\n const metadata = credential.metadata ?? {}\n return {\n access_token: credential.access,\n token_type: typeof metadata.tokenType === \"string\" ? metadata.tokenType : \"Bearer\",\n ...(credential.refresh ? { refresh_token: credential.refresh } : {}),\n ...(credential.expires ? { expires_in: Math.max(0, Math.floor((credential.expires - Date.now()) / 1000)) } : {}),\n ...(typeof metadata.scope === \"string\" ? { scope: metadata.scope } : {}),\n }\n}\n\n/**\n * Runs the interactive OAuth login for one remote MCP server. Stands up a loopback callback server,\n * lets the SDK drive DCR + PKCE to produce an authorization URL, and returns an attempt whose callback\n * exchanges the redirect code for a storable credential. Scoped: the callback server closes with the scope.\n */\nexport const authorize = (input: {\n readonly name: string\n readonly config: typeof ConfigMCP.Remote.Type\n readonly methodID: Integration.MethodID\n}) =>\n Effect.gen(function* () {\n const oauth = input.config.oauth || undefined\n const store = memoryStore()\n const code = yield* Deferred.make<string, Error>()\n const redirect = oauth?.redirect_uri ? new URL(oauth.redirect_uri) : undefined\n const redirectPath = redirect?.pathname ?? \"/callback\"\n const state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString(\"base64url\")\n\n // Lazy so runtimes without a loopback listener (workerd) never evaluate node:http.\n const { createServer } = yield* Effect.promise(() => import(\"node:http\"))\n const server = createServer((request, response) => {\n const url = new URL(request.url ?? \"/\", \"http://127.0.0.1\")\n if (url.pathname !== redirectPath) {\n response.writeHead(404).end(\"Not found\")\n return\n }\n const fail = (reason: string) => {\n Effect.runFork(Deferred.fail(code, new Error(reason)))\n response\n .writeHead(400, { \"Content-Type\": \"text/html\" })\n .end(OauthCallbackPage.error(reason, { provider: input.name }))\n }\n const error = url.searchParams.get(\"error_description\") ?? url.searchParams.get(\"error\")\n if (error) return fail(error)\n // Reject a redirect whose state does not match what we issued: this is the CSRF defense the\n // state parameter exists for, so an attacker can't inject their own authorization code.\n if (url.searchParams.get(\"state\") !== state) return fail(\"OAuth state mismatch\")\n const value = url.searchParams.get(\"code\")\n if (!value) return fail(\"Missing authorization code\")\n Effect.runFork(Deferred.succeed(code, value))\n response.writeHead(200, { \"Content-Type\": \"text/html\" }).end(OauthCallbackPage.success({ provider: input.name }))\n })\n\n // Bind the port the redirect will actually arrive on: an explicit callback_port wins, else the port\n // pinned by redirect_uri, else an ephemeral port. Binding ephemerally while redirect_uri names a fixed\n // port would send the browser somewhere nothing is listening, hanging the attempt until it expires.\n const redirectPort = Number(redirect?.port) || undefined\n const port = yield* Effect.callback<number, Error>((resume) => {\n server.once(\"error\", (error) => resume(Effect.fail(error)))\n server.listen(oauth?.callback_port ?? redirectPort ?? 0, \"127.0.0.1\", () => {\n const address = server.address()\n resume(\n address && typeof address === \"object\"\n ? Effect.succeed(address.port)\n : Effect.fail(new Error(\"Could not determine MCP OAuth callback port\")),\n )\n })\n })\n yield* Effect.addFinalizer(() => Effect.sync(() => server.close()))\n\n let authorizationUrl: URL | undefined\n const oauthProvider = provider({\n redirectUrl: oauth?.redirect_uri ?? `http://127.0.0.1:${port}${redirectPath}`,\n scope: oauth?.scope,\n state,\n client: oauth?.client_id ? { id: oauth.client_id, secret: oauth.client_secret } : undefined,\n onRedirect: (url) => {\n authorizationUrl = url\n },\n store,\n })\n\n const finalize = Effect.gen(function* () {\n const tokens = yield* Effect.promise(() => store.tokens())\n if (!tokens) return yield* Effect.fail(new Error(`MCP server \"${input.name}\" did not return OAuth tokens`))\n const client = yield* Effect.promise(() => store.clientInformation())\n return toCredential({ methodID: input.methodID, serverUrl: input.config.url, tokens, client })\n })\n\n yield* Effect.tryPromise({\n try: () => auth(oauthProvider, { serverUrl: input.config.url, scope: oauth?.scope }),\n catch: (error) => (error instanceof Error ? error : new Error(String(error))),\n })\n\n if (!authorizationUrl)\n return yield* Effect.fail(new Error(`MCP server \"${input.name}\" did not provide an authorization URL`))\n\n return {\n url: authorizationUrl.toString(),\n instructions: `Authorize ${input.name} in your browser. This window will close automatically.`,\n mode: \"auto\" as const,\n callback: Deferred.await(code).pipe(\n Effect.flatMap((value) =>\n Effect.tryPromise({\n try: () =>\n auth(oauthProvider, { serverUrl: input.config.url, authorizationCode: value, scope: oauth?.scope }),\n catch: (error) => (error instanceof Error ? error : new Error(String(error))),\n }),\n ),\n Effect.flatMap(() => finalize),\n ),\n }\n })\n" | ||
| ], | ||
| "mappings": ";krBAyCO,IAAM,EAAW,CAAC,IAA0C,CACjE,IAAsB,MAAhB,EACiB,OAAjB,GAAS,EACf,MAAO,CACL,YAAa,EAAQ,YACrB,eAAgB,CACd,cAAe,CAAC,EAAQ,WAAW,EACnC,YAAa,WACb,WAAY,sBACZ,YAAa,CAAC,qBAAsB,eAAe,EACnD,eAAgB,CAAC,MAAM,EACvB,2BAA4B,GAAQ,OAAS,qBAAuB,UAChE,EAAQ,MAAQ,CAAE,MAAO,EAAQ,KAAM,EAAI,CAAC,CAClD,KAGI,IAAU,OAAY,CAAE,MAAO,IAAM,CAAM,EAAI,CAAC,EAEpD,kBAAmB,IACjB,EAAS,CAAE,UAAW,EAAO,GAAI,cAAe,EAAO,MAAO,EAAI,EAAQ,MAAM,kBAAkB,EACpG,sBAAuB,CAAC,IAAS,EAAQ,MAAM,sBAAsB,CAAI,EACzE,OAAQ,IAAM,EAAQ,MAAM,OAAO,EACnC,WAAY,CAAC,IAAW,EAAQ,MAAM,WAAW,CAAM,EACvD,wBAAyB,CAAC,IAAQ,EAAQ,WAAW,CAAG,KACpD,EAAQ,WAAa,CAAE,sBAAuB,EAAQ,UAAW,EAAI,CAAC,EAC1E,iBAAkB,CAAC,IAAa,EAAQ,MAAM,iBAAiB,CAAQ,EAGvE,aAAc,SAAY,CACxB,IAAM,EAAW,MAAM,EAAQ,MAAM,aAAa,EAClD,GAAI,CAAC,EAAU,MAAU,MAAM,+CAA+C,EAC9E,OAAO,EAEX,GAIW,EAAc,IAAa,CACtC,IAAI,EACA,EACA,EACJ,MAAO,CACL,OAAQ,SAAY,EACpB,WAAY,MAAO,IAAU,CAC3B,EAAS,GAEX,kBAAmB,SAAY,EAC/B,sB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AO,QAAQ,IAAM,CAAQ,CAC/B,CACF,EACD", | ||
| "debugId": "43D59B6EB6EFF9EC64756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| { | ||
| "version": 3, | ||
| "sources": ["src/commands/handlers/service/start.ts"], | ||
| "sourcesContent": [ | ||
| "import { EOL } from \"os\"\nimport { Effect } from \"effect\"\nimport { Service } from \"@opencode-ai/client/effect/service\"\nimport { Commands } from \"../../commands\"\nimport { Runtime } from \"../../../framework/runtime\"\nimport { ServiceConfig } from \"../../../services/service-config\"\n\nexport default Runtime.handler(\n Commands.commands.service.commands.start,\n Effect.fn(\"cli.service.start\")(function* () {\n const transport = yield* Service.ensure(yield* ServiceConfig.options())\n process.stdout.write(transport.url + EOL)\n }),\n)\n" | ||
| ], | ||
| "mappings": ";s5BAAA,cAAS,WAOT,IAAe,IAAQ,QACrB,EAAS,SAAS,QAAQ,SAAS,MACnC,EAAO,GAAG,mBAAmB,EAAE,SAAU,EAAG,CAC1C,IAAM,EAAY,MAAO,EAAQ,OAAO,MAAO,EAAc,QAAQ,CAAC,EACtE,QAAQ,OAAO,MAAM,EAAU,IAAM,CAAG,EACzC,CACH", | ||
| "debugId": "6783E696E3B8300164756E2164756E21", | ||
| "names": [] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
257381330
-0.01%