@byokkit/cmd-provider-openai 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +94 -0
- package/dist/chunk-34MJFIMS.js +90 -0
- package/dist/chunk-34MJFIMS.js.map +1 -0
- package/dist/chunk-J2XEWLRM.js +127 -0
- package/dist/chunk-J2XEWLRM.js.map +1 -0
- package/dist/chunk-NSTLHK7M.js +34 -0
- package/dist/chunk-NSTLHK7M.js.map +1 -0
- package/dist/codex.d.ts +34 -0
- package/dist/codex.js +21 -0
- package/dist/codex.js.map +1 -0
- package/dist/constants-BPm3xKmw.d.ts +20 -0
- package/dist/index.d.ts +58 -0
- package/dist/index.js +488 -0
- package/dist/index.js.map +1 -0
- package/dist/models.d.ts +114 -0
- package/dist/models.js +13 -0
- package/dist/models.js.map +1 -0
- package/dist/server/index.d.ts +28 -0
- package/dist/server/index.js +25 -0
- package/dist/server/index.js.map +1 -0
- package/package.json +50 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../harness/src/mcp/protocol.ts","../../harness/src/mcp/oauth.ts","../../harness/src/provider/oauth-helpers.ts","../src/oauth.ts","../src/provider.ts","../src/index.ts"],"sourcesContent":["// Shared MCP protocol helpers — the JSON-RPC shapes and the MCP→harness conversions\n// used by BOTH transports (stdio + http). Kept in one place so a tool result is\n// interpreted identically regardless of transport (text/image/audio/resource/\n// resource_link content, structuredContent, the legacy toolResult field, and the\n// tool-level `isError` flag → a failed ToolRunResult).\n\nimport type {\n\tToolResultContent,\n\tToolRunResult,\n\tToolSchema,\n} from '../core/index.js';\n\n// MCP protocol version we negotiate. Bumped from the legacy 2024-11-05 to the\n// current revision so servers gating on the newer protocol initialize cleanly.\nexport const MCP_PROTOCOL_VERSION = '2025-03-26';\n\nexport const MCP_CLIENT_INFO = {name: 'commandcode', version: '0.1.0'} as const;\n\n// A hung server (initialized but never replies) must not block the agent forever.\n// Env-overridable via MCP_TOOL_TIMEOUT (milliseconds) — the same knob Claude Code\n// exposes — so slow-but-legitimate servers (big exports, long queries) can be\n// accommodated without a rebuild.\nexport const DEFAULT_MCP_REQUEST_TIMEOUT_MS = 80_000;\n\n// A server description is prompt real estate: an unbounded one (some servers ship\n// multi-KB walls of docs per tool) can blow the system prompt. Cap mirrors Claude\n// Code's MAX_DESCRIPTION_CHARACTERS.\nexport const MCP_MAX_DESCRIPTION_CHARS = 2_048;\n\n// Resolve the per-request timeout: a positive integer MCP_TOOL_TIMEOUT (ms) wins,\n// anything else (absent, zero, junk) falls back to the default. parseInt +\n// positivity mirrors Claude Code's env handling.\nexport function resolveMcpTimeoutMs(params?: {\n\treadonly envValue?: string;\n}): number {\n\tconst raw =\n\t\tparams?.envValue ??\n\t\t(typeof process !== 'undefined'\n\t\t\t? process.env.MCP_TOOL_TIMEOUT\n\t\t\t: undefined);\n\tconst parsed = Number.parseInt(raw ?? '', 10);\n\tif (Number.isFinite(parsed) && parsed > 0) return parsed;\n\treturn DEFAULT_MCP_REQUEST_TIMEOUT_MS;\n}\n\nexport interface JsonRpcResponse {\n\treadonly id?: number;\n\treadonly result?: unknown;\n\treadonly error?: {readonly message?: string; readonly code?: number};\n\t// Present on notifications (no id) — routed by the transports for\n\t// progress + tools/list_changed handling.\n\treadonly method?: string;\n\treadonly params?: Record<string, unknown>;\n}\n\n// MCP tool annotations (spec 2025-03-26 §Tool.annotations). Hints, not\n// guarantees: readOnlyHint drives our concurrency/read-only classification the\n// way codex + Claude Code use it; destructive/openWorld are surfaced for\n// permission UIs. All default to \"absent\" — an unannotated tool is treated as\n// potentially mutating (fail closed).\nexport interface McpToolAnnotations {\n\treadonly title?: string;\n\treadonly readOnlyHint?: boolean;\n\treadonly destructiveHint?: boolean;\n\treadonly idempotentHint?: boolean;\n\treadonly openWorldHint?: boolean;\n}\n\nexport interface McpToolDef {\n\treadonly name: string;\n\treadonly description?: string;\n\t// Open-ended: a server may declare any JSON Schema keyword here ($defs,\n\t// definitions, additionalProperties, …) and mcpToolDefToSchema forwards the\n\t// ones it doesn't own. Dropping them is what broke strict providers.\n\treadonly inputSchema?: {\n\t\treadonly properties?: Record<string, unknown>;\n\t\treadonly required?: readonly string[];\n\t\treadonly type?: unknown;\n\t\treadonly $schema?: unknown;\n\t\treadonly [keyword: string]: unknown;\n\t};\n\t// Declared result shape (spec §Tool.outputSchema). Carried for future\n\t// structured-output validation; not enforced today.\n\treadonly outputSchema?: Record<string, unknown>;\n\treadonly annotations?: McpToolAnnotations;\n}\n\nexport function mcpToolDefToSchema(def: McpToolDef): ToolSchema {\n\t// Fall back to a synthesized description (never empty) so the model still\n\t// has something to select on and providers that reject empty tool\n\t// descriptions don't error. Uses `||` (not `??`) so an explicit empty\n\t// string also falls back — some servers send `description: ''` rather than\n\t// omitting it. Mirrors command's tool-adapter default.\n\tconst raw = def.description || `MCP tool: ${def.name}`;\n\t// Cap runaway descriptions — they're system-prompt bytes on every request.\n\tconst description =\n\t\traw.length > MCP_MAX_DESCRIPTION_CHARS\n\t\t\t? `${raw.slice(0, MCP_MAX_DESCRIPTION_CHARS)}… [truncated]`\n\t\t\t: raw;\n\t// annotations.title is the human display name (spec: precedence over name\n\t// for UIs). ToolSchema.label is display-only — toWireTools strips it, so\n\t// the model never sees it and the wire name stays the sanitized one.\n\tconst title = def.annotations?.title;\n\t// Forward the server's remaining schema keywords instead of rebuilding the\n\t// wrapper from just properties/required. Cherry-picking those two dropped the\n\t// sibling `$defs` bucket while leaving the `$ref`s that point into it, and a\n\t// dangling ref makes Moonshot (Kimi) reject the whole request as \"not a valid\n\t// moonshot flavored json schema\". `type` is re-asserted below (tools are always\n\t// object-shaped) and `$schema` is dropped — a meta-key providers don't want.\n\tconst {\n\t\t$schema: _metaSchema,\n\t\ttype: _declaredType,\n\t\tproperties: _properties,\n\t\trequired: _required,\n\t\t...extraKeywords\n\t} = def.inputSchema ?? {};\n\treturn {\n\t\tname: def.name,\n\t\t...(title ? {label: title} : {}),\n\t\tdescription,\n\t\tinput_schema: {\n\t\t\t...extraKeywords,\n\t\t\ttype: 'object',\n\t\t\tproperties: def.inputSchema?.properties ?? {},\n\t\t\trequired: [...(def.inputSchema?.required ?? [])],\n\t\t},\n\t};\n}\n\n// ── result content transformation ────────────────────────────────────────────\n\ninterface McpContentBlock {\n\treadonly type?: string;\n\treadonly text?: string;\n\treadonly data?: string;\n\treadonly mimeType?: string;\n\treadonly name?: string;\n\treadonly description?: string;\n\treadonly uri?: string;\n\treadonly resource?: {\n\t\treadonly uri?: string;\n\t\treadonly text?: string;\n\t\treadonly blob?: string;\n\t\treadonly mimeType?: string;\n\t};\n}\n\n// Where a decoded MCP binary payload landed (audio blocks, non-image resource\n// blobs). The persister writes RAW BYTES — never base64 text — so downstream\n// native readers get valid PDFs/archives/media.\nexport interface McpPersistedBinary {\n\treadonly filepath: string;\n\treadonly size: number;\n}\n\nexport type McpBinaryPersistResult =\n\t| McpPersistedBinary\n\t| {readonly error: string};\n\nexport type McpBinaryPersister = (params: {\n\treadonly bytes: Uint8Array;\n\treadonly mimeType?: string;\n}) => McpBinaryPersistResult;\n\nexport interface McpResultOptions {\n\t// Provenance for resource prefixes (\"[Resource from <server> at <uri>]\").\n\treadonly serverName?: string;\n\t// Sink for binary payloads. Absent → binary content becomes a short\n\t// placeholder note instead of flooding the context with base64.\n\treadonly persistBinary?: McpBinaryPersister;\n}\n\n// Image MIME types the model can actually view — everything else persists as a\n// file notice (matches Claude Code's IMAGE_MIME_TYPES allowlist).\nconst VIEWABLE_IMAGE_MIME_TYPES = new Set([\n\t'image/png',\n\t'image/jpeg',\n\t'image/gif',\n\t'image/webp',\n]);\n\nfunction formatByteSize(sizeInBytes: number): string {\n\tconst kilobytes = sizeInBytes / 1_024;\n\tif (kilobytes < 1) return `${sizeInBytes} bytes`;\n\tif (kilobytes < 1_024)\n\t\treturn `${kilobytes.toFixed(1).replace(/\\.0$/, '')}KB`;\n\tconst megabytes = kilobytes / 1_024;\n\treturn `${megabytes.toFixed(1).replace(/\\.0$/, '')}MB`;\n}\n\nfunction decodeBase64(data: string): Uint8Array {\n\treturn new Uint8Array(Buffer.from(data, 'base64'));\n}\n\n// Persist decoded bytes and describe the outcome as one text block. A persist\n// failure (or missing persister) degrades to a placeholder — never base64 into\n// the model context, never a thrown error that loses sibling blocks.\nfunction persistedBinaryText(params: {\n\treadonly data: string;\n\treadonly mimeType?: string;\n\treadonly sourcePrefix: string;\n\treadonly options?: McpResultOptions;\n}): ToolResultContent {\n\tconst bytes = decodeBase64(params.data);\n\tconst mime = params.mimeType ?? 'unknown type';\n\tconst persist = params.options?.persistBinary;\n\tif (!persist) {\n\t\treturn {\n\t\t\ttype: 'text',\n\t\t\ttext: `${params.sourcePrefix}Binary content (${mime}, ${formatByteSize(\n\t\t\t\tbytes.byteLength,\n\t\t\t)}) omitted — no binary store configured.`,\n\t\t};\n\t}\n\tconst persisted = persist({bytes, mimeType: params.mimeType});\n\tif ('error' in persisted) {\n\t\treturn {\n\t\t\ttype: 'text',\n\t\t\ttext: `${params.sourcePrefix}Binary content (${mime}, ${formatByteSize(\n\t\t\t\tbytes.byteLength,\n\t\t\t)}) could not be saved to disk: ${persisted.error}`,\n\t\t};\n\t}\n\treturn {\n\t\ttype: 'text',\n\t\ttext: `${params.sourcePrefix}Binary content (${mime}, ${formatByteSize(\n\t\t\tpersisted.size,\n\t\t)}) saved to ${persisted.filepath}`,\n\t};\n}\n\nfunction resourcePrefix(params: {\n\treadonly uri: string;\n\treadonly options?: McpResultOptions;\n}): string {\n\tconst server = params.options?.serverName;\n\tif (server) return `[Resource from ${server} at ${params.uri}] `;\n\treturn `[Resource: ${params.uri}] `;\n}\n\n// One MCP content block → harness ToolResultContent blocks. Text passes through;\n// images become base64 image blocks (the model can see them); audio + non-image\n// resource blobs persist to disk (a location notice, never inline base64);\n// resource text/links are summarized with provenance. May emit multiple blocks\n// (a resource image = provenance text + image).\nfunction blockToContents(\n\tblock: McpContentBlock,\n\toptions?: McpResultOptions,\n): readonly ToolResultContent[] {\n\tif (block.type === 'text' && typeof block.text === 'string') {\n\t\treturn [{type: 'text', text: block.text}];\n\t}\n\tif (block.type === 'image' && typeof block.data === 'string') {\n\t\treturn [\n\t\t\t{\n\t\t\t\ttype: 'image',\n\t\t\t\tsource: {\n\t\t\t\t\ttype: 'base64',\n\t\t\t\t\tmedia_type: block.mimeType ?? 'image/png',\n\t\t\t\t\tdata: block.data,\n\t\t\t\t},\n\t\t\t},\n\t\t];\n\t}\n\tif (block.type === 'audio' && typeof block.data === 'string') {\n\t\tconst server = options?.serverName;\n\t\treturn [\n\t\t\tpersistedBinaryText({\n\t\t\t\tdata: block.data,\n\t\t\t\tmimeType: block.mimeType,\n\t\t\t\tsourcePrefix: server ? `[Audio from ${server}] ` : '[Audio] ',\n\t\t\t\toptions,\n\t\t\t}),\n\t\t];\n\t}\n\tif (block.type === 'resource') {\n\t\treturn resourceToContents(block, options);\n\t}\n\tif (block.type === 'resource_link' && typeof block.uri === 'string') {\n\t\tconst name = block.name ?? block.uri;\n\t\tconst description = block.description ? ` (${block.description})` : '';\n\t\treturn [\n\t\t\t{\n\t\t\t\ttype: 'text',\n\t\t\t\ttext: `[Resource link: ${name}] ${block.uri}${description}`,\n\t\t\t},\n\t\t];\n\t}\n\t// Unknown block shape — preserve it verbatim so nothing is silently dropped.\n\treturn [{type: 'text', text: JSON.stringify(block)}];\n}\n\nfunction resourceToContents(\n\tblock: McpContentBlock,\n\toptions?: McpResultOptions,\n): readonly ToolResultContent[] {\n\tconst resource = block.resource;\n\tconst uri = resource?.uri ?? 'unknown';\n\tconst prefix = resourcePrefix({uri, options});\n\tif (resource && typeof resource.text === 'string') {\n\t\treturn [{type: 'text', text: `${prefix}${resource.text}`}];\n\t}\n\tif (resource && typeof resource.blob === 'string') {\n\t\t// A viewable image blob stays a real image block (with a provenance text\n\t\t// block ahead of it); everything else persists to disk.\n\t\tconst mime = resource.mimeType ?? '';\n\t\tif (VIEWABLE_IMAGE_MIME_TYPES.has(mime)) {\n\t\t\treturn [\n\t\t\t\t{type: 'text', text: prefix.trimEnd()},\n\t\t\t\t{\n\t\t\t\t\ttype: 'image',\n\t\t\t\t\tsource: {\n\t\t\t\t\t\ttype: 'base64',\n\t\t\t\t\t\tmedia_type: mime,\n\t\t\t\t\t\tdata: resource.blob,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t];\n\t\t}\n\t\treturn [\n\t\t\tpersistedBinaryText({\n\t\t\t\tdata: resource.blob,\n\t\t\t\tmimeType: resource.mimeType,\n\t\t\t\tsourcePrefix: prefix,\n\t\t\t\toptions,\n\t\t\t}),\n\t\t];\n\t}\n\treturn [{type: 'text', text: `[Resource: ${uri}]`}];\n}\n\ninterface McpToolCallResult {\n\treadonly content?: unknown;\n\treadonly structuredContent?: unknown;\n\treadonly toolResult?: unknown;\n\treadonly isError?: boolean;\n}\n\n// Map an MCP `tools/call` result to a ToolRunResult. Shape precedence mirrors\n// Claude Code: the pre-spec `toolResult` field, then `structuredContent`\n// (compact JSON — precise for the model), then the `content` block array, then\n// a JSON dump of the whole result so nothing is silently lost. A tool-level\n// error (`isError: true`) is a FAILED tool run even though the JSON-RPC call\n// itself succeeded — surfacing it as ok:true would hide real failures from the\n// model.\nexport function mcpResultToToolRunResult(\n\tresult: unknown,\n\toptions?: McpResultOptions,\n): ToolRunResult {\n\tconst typed = (result ?? {}) as McpToolCallResult;\n\tconst rawContent = typed.content;\n\tconst contentBlocks: readonly ToolResultContent[] | undefined =\n\t\tArray.isArray(rawContent)\n\t\t\t? rawContent.flatMap(block =>\n\t\t\t\t\tblockToContents(block as McpContentBlock, options),\n\t\t\t\t)\n\t\t\t: undefined;\n\n\tif (typed.isError === true) {\n\t\tconst errorText = (contentBlocks ?? [])\n\t\t\t.map(block => (block.type === 'text' ? block.text : '[non-text]'))\n\t\t\t.join('\\n');\n\t\treturn {ok: false, error: errorText || 'MCP tool reported an error'};\n\t}\n\n\t// Legacy pre-spec servers return a bare `toolResult` value.\n\tif ('toolResult' in typed) {\n\t\tconst value = typed.toolResult;\n\t\tconst text = typeof value === 'string' ? value : JSON.stringify(value);\n\t\treturn {ok: true, content: [{type: 'text', text}]};\n\t}\n\n\t// structuredContent wins over the content array (spec: content SHOULD\n\t// mirror it for backwards compatibility — the structured form is the\n\t// precise one) UNLESS the content array carries non-text blocks the JSON\n\t// form would lose (images).\n\tif (typed.structuredContent !== undefined) {\n\t\tconst hasNonText = (contentBlocks ?? []).some(\n\t\t\tblock => block.type !== 'text',\n\t\t);\n\t\tif (!hasNonText) {\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'text',\n\t\t\t\t\t\ttext: JSON.stringify(typed.structuredContent),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t}\n\n\tif (contentBlocks) {\n\t\treturn {ok: true, content: contentBlocks};\n\t}\n\treturn {ok: true, content: [{type: 'text', text: JSON.stringify(result)}]};\n}\n\n// MCP tool/server names handed to the model must match ^[a-zA-Z0-9_-]+$ (the\n// schema constraint Anthropic enforces). Replace anything else with `_`.\nexport function sanitizeMcpToolName(name: string): string {\n\treturn name.replace(/[^a-zA-Z0-9_-]/g, '_');\n}\n\n// ── tool-name (mcp__<server>__<tool>) parsing ────────────────────────────────\n// The namespaced tool name the model sees (built in mcp.ts). Parsing it back lets\n// the tool catalog, mode gating, and feed rendering tell MCP tools from built-ins\n// and recover the originating server/tool.\nexport interface ParsedMcpToolName {\n\treadonly serverName: string;\n\treadonly toolName: string;\n}\n\n// True when a tool name uses the `mcp__server__tool` prefix convention.\nexport function isMcpTool(toolName: string): boolean {\n\treturn toolName.startsWith('mcp__');\n}\n\n// Split a prefixed MCP tool name into its server + tool parts. Returns null for\n// non-MCP names or malformed prefixes (fewer than 3 `__`-separated segments).\nexport function parseMcpToolName(\n\tprefixedName: string,\n): ParsedMcpToolName | null {\n\tif (!isMcpTool(prefixedName)) return null;\n\tconst parts = prefixedName.split('__');\n\tif (parts.length < 3) return null;\n\tconst serverName = parts[1];\n\tif (!serverName) return null;\n\treturn {\n\t\tserverName,\n\t\t// Tool names may themselves contain `__`, so rejoin everything after the server segment.\n\t\ttoolName: parts.slice(2).join('__'),\n\t};\n}\n","// MCP OAuth (PKCE) — everything needed to authenticate to an OAuth-protected MCP\n// server: metadata discovery (RFC 8414 / RFC 9728 / OIDC), a PKCE challenge, the\n// authorization URL, the code→token exchange + refresh, and the interactive\n// auth-code flow (loopback callback server + browser open + CSRF/state check).\n//\n// Zero-dep: node built-ins only (node:crypto, node:http, node:url, node:child_process).\n// fetch + the browser opener are injectable so every piece stays testable.\n\nimport {spawn} from 'node:child_process';\nimport {createHash, randomBytes} from 'node:crypto';\nimport {createServer, type Server} from 'node:http';\nimport {URL} from 'node:url';\nimport {MCP_CLIENT_INFO, MCP_PROTOCOL_VERSION} from './protocol.js';\n\nexport interface OAuthFetchResponse {\n\treadonly ok?: boolean;\n\treadonly status?: number;\n\treadonly statusText?: string;\n\treadonly headers?: {get(name: string): string | null};\n\tjson(): Promise<unknown>;\n\ttext?(): Promise<string>;\n}\n\nexport type OAuthFetchImpl = (\n\turl: string,\n\tinit?: {\n\t\treadonly method?: string;\n\t\treadonly headers?: Record<string, string>;\n\t\treadonly body?: string;\n\t\treadonly signal?: AbortSignal;\n\t},\n) => Promise<OAuthFetchResponse>;\n\nfunction defaultFetch(): OAuthFetchImpl {\n\treturn globalThis.fetch as unknown as OAuthFetchImpl;\n}\n\n// Token-endpoint + probe calls must not hang the agent forever. The interactive\n// auth path injects its own timed fetch, but the BACKGROUND refresh path (through\n// http-client's getValidAccessToken) hands us the raw, untimed globalThis.fetch —\n// so an unresponsive authorization server would otherwise stall a tool call\n// indefinitely. Mirrors command's oauth-flow.ts 80s FETCH_TIMEOUT_MS.\nconst OAUTH_REQUEST_TIMEOUT_MS = 80_000;\n\nasync function fetchWithTimeout(\n\tfetchImpl: OAuthFetchImpl,\n\turl: string,\n\tinit: {\n\t\treadonly method?: string;\n\t\treadonly headers?: Record<string, string>;\n\t\treadonly body?: string;\n\t},\n\ttimeoutMs = OAUTH_REQUEST_TIMEOUT_MS,\n): Promise<OAuthFetchResponse> {\n\tconst controller = new AbortController();\n\tconst timer = setTimeout(() => controller.abort(), timeoutMs);\n\ttry {\n\t\treturn await fetchImpl(url, {...init, signal: controller.signal});\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n}\n\nfunction queryString(params: Record<string, string>): string {\n\treturn Object.entries(params)\n\t\t.map(\n\t\t\t([key, value]) =>\n\t\t\t\t`${encodeURIComponent(key)}=${encodeURIComponent(value)}`,\n\t\t)\n\t\t.join('&');\n}\n\n// How a token request body is encoded. Most servers (and every MCP caller) want the OAuth2\n// default form-urlencoded; some providers (e.g. Anthropic's token endpoint) require a JSON body.\nexport type TokenRequestEncoding = 'form' | 'json';\n\n// Build the headers + body for a token request in the requested encoding. Keeps form-encoded the\n// default so existing MCP callers are byte-for-byte unchanged.\nfunction encodeTokenRequest(\n\tfields: Record<string, string>,\n\tencoding: TokenRequestEncoding,\n): {readonly headers: Record<string, string>; readonly body: string} {\n\tif (encoding === 'json') {\n\t\treturn {\n\t\t\theaders: {\n\t\t\t\t'content-type': 'application/json',\n\t\t\t\taccept: 'application/json',\n\t\t\t},\n\t\t\tbody: JSON.stringify(fields),\n\t\t};\n\t}\n\treturn {\n\t\theaders: {'content-type': 'application/x-www-form-urlencoded'},\n\t\tbody: queryString(fields),\n\t};\n}\n\n// ── URL safety ───────────────────────────────────────────────────────────────\n// True for https:// URLs and for http:// URLs whose host is a loopback address.\n// RFC 8252 carves out loopback for native-app OAuth, so local-dev MCP servers\n// (http://localhost, http://127.0.0.1, http://[::1]) are allowed even with OAuth.\nexport function isSecureOrLoopback(url: string): boolean {\n\ttry {\n\t\tconst parsed = new URL(url);\n\t\tif (parsed.protocol === 'https:') return true;\n\t\tif (parsed.protocol !== 'http:') return false;\n\t\treturn (\n\t\t\tparsed.hostname === 'localhost' ||\n\t\t\tparsed.hostname === '127.0.0.1' ||\n\t\t\tparsed.hostname === '[::1]' ||\n\t\t\tparsed.hostname === '::1'\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// ── PKCE ─────────────────────────────────────────────────────────────────────\nexport interface Pkce {\n\treadonly verifier: string;\n\treadonly challenge: string; // base64url(sha256(verifier)) — the S256 method\n}\n\nexport function generatePkce(\n\tparams: {readonly randomBytesImpl?: (size: number) => Buffer} = {},\n): Pkce {\n\tconst verifier = (params.randomBytesImpl ?? randomBytes)(32).toString(\n\t\t'base64url',\n\t);\n\tconst challenge = createHash('sha256').update(verifier).digest('base64url');\n\treturn {verifier, challenge};\n}\n\n// ── OAuth config + token shapes ──────────────────────────────────────────────\nexport interface OAuthConfig {\n\treadonly authorizationUrl: string;\n\treadonly tokenUrl: string;\n\treadonly clientId: string;\n\treadonly clientSecret?: string;\n\treadonly scopes?: readonly string[];\n}\n\nexport interface TokenResult {\n\treadonly accessToken: string;\n\treadonly refreshToken?: string;\n\treadonly expiresAt?: number; // epoch ms\n\treadonly tokenType?: string;\n\treadonly scope?: string;\n\t// Origin (scheme://host[:port]) of the MCP server the token was issued for.\n\t// Bearer tokens are only attached to requests whose URL origin matches this.\n\treadonly issuerUrl?: string;\n}\n\ninterface RawTokenResponse {\n\treadonly access_token?: string;\n\treadonly refresh_token?: string;\n\treadonly expires_in?: number;\n\treadonly token_type?: string;\n\treadonly scope?: string;\n}\n\nfunction toTokenResult(\n\traw: RawTokenResponse,\n\tnow: () => number,\n\tfallbackRefreshToken?: string,\n): TokenResult {\n\tif (!raw.access_token) {\n\t\tthrow new Error('OAuth token response had no access_token');\n\t}\n\treturn {\n\t\taccessToken: raw.access_token,\n\t\trefreshToken: raw.refresh_token ?? fallbackRefreshToken,\n\t\texpiresAt:\n\t\t\ttypeof raw.expires_in === 'number'\n\t\t\t\t? now() + raw.expires_in * 1000\n\t\t\t\t: undefined,\n\t\ttokenType: raw.token_type,\n\t\tscope: raw.scope,\n\t};\n}\n\n// ── Authorization-server metadata discovery ──────────────────────────────────\nexport interface AuthServerMetadata {\n\treadonly authorizationEndpoint: string;\n\treadonly tokenEndpoint: string;\n\treadonly registrationEndpoint?: string;\n\treadonly scopes?: readonly string[];\n}\n\n// RFC 8414 §3: the well-known suffix is inserted BETWEEN host and issuer path.\n// https://ex.com -> https://ex.com/.well-known/oauth-authorization-server\n// https://ex.com/v1/oauth -> https://ex.com/.well-known/oauth-authorization-server/v1/oauth\nexport function buildOAuthMetadataUrl(issuerUrl: string): string {\n\tconst parsed = new URL(issuerUrl);\n\tconst issuerPath =\n\t\tparsed.pathname === '/' ? '' : parsed.pathname.replace(/\\/+$/, '');\n\tparsed.pathname = `/.well-known/oauth-authorization-server${issuerPath}`;\n\tparsed.search = '';\n\tparsed.hash = '';\n\treturn parsed.toString();\n}\n\n// OIDC Core 1.0 §4 APPENDS `/.well-known/openid-configuration` to the issuer.\nexport function buildOidcMetadataUrl(issuerUrl: string): string {\n\tconst parsed = new URL(issuerUrl);\n\tconst issuerPath = parsed.pathname.replace(/\\/+$/, '');\n\tparsed.pathname = `${issuerPath}/.well-known/openid-configuration`;\n\tparsed.search = '';\n\tparsed.hash = '';\n\treturn parsed.toString();\n}\n\nasync function tryFetchMetadata(\n\tmetadataUrl: string,\n\tfetchImpl: OAuthFetchImpl,\n): Promise<AuthServerMetadata | null> {\n\ttry {\n\t\tconst response = await fetchImpl(metadataUrl, {\n\t\t\tmethod: 'GET',\n\t\t\theaders: {accept: 'application/json'},\n\t\t});\n\t\tif (response.ok === false) return null;\n\t\tconst meta = (await response.json()) as {\n\t\t\tauthorization_endpoint?: string;\n\t\t\ttoken_endpoint?: string;\n\t\t\tregistration_endpoint?: string;\n\t\t\tscopes_supported?: string[];\n\t\t};\n\t\tif (!meta.authorization_endpoint || !meta.token_endpoint) return null;\n\t\treturn {\n\t\t\tauthorizationEndpoint: meta.authorization_endpoint,\n\t\t\ttokenEndpoint: meta.token_endpoint,\n\t\t\tregistrationEndpoint: meta.registration_endpoint,\n\t\t\tscopes: meta.scopes_supported,\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n// RFC 8414 discovery from an issuer identifier, falling back to OIDC discovery.\nexport async function discoverAuthServer(params: {\n\treadonly issuerUrl: string;\n\treadonly fetchImpl?: OAuthFetchImpl;\n}): Promise<AuthServerMetadata> {\n\tconst meta = await discoverOAuthMetadataFromIssuer({\n\t\tissuerUrl: params.issuerUrl,\n\t\tfetchImpl: params.fetchImpl,\n\t});\n\tif (!meta) {\n\t\tthrow new Error('discoverAuthServer: missing endpoints in metadata');\n\t}\n\treturn meta;\n}\n\nexport async function discoverOAuthMetadataFromIssuer(params: {\n\treadonly issuerUrl: string;\n\treadonly fetchImpl?: OAuthFetchImpl;\n}): Promise<AuthServerMetadata | null> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\tconst oauthMeta = await tryFetchMetadata(\n\t\tbuildOAuthMetadataUrl(params.issuerUrl),\n\t\tfetchImpl,\n\t);\n\tif (oauthMeta) return oauthMeta;\n\treturn tryFetchMetadata(buildOidcMetadataUrl(params.issuerUrl), fetchImpl);\n}\n\n// Probe a server's origin for well-known metadata when the issuer is unknown.\n// Prefer the issuer-aware variant whenever an issuer can be obtained.\nexport async function discoverOAuthMetadata(params: {\n\treadonly serverUrl: string;\n\treadonly fetchImpl?: OAuthFetchImpl;\n}): Promise<AuthServerMetadata | null> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\tconst origin = new URL(params.serverUrl).origin;\n\tconst oauthMeta = await tryFetchMetadata(\n\t\t`${origin}/.well-known/oauth-authorization-server`,\n\t\tfetchImpl,\n\t);\n\tif (oauthMeta) return oauthMeta;\n\treturn tryFetchMetadata(\n\t\t`${origin}/.well-known/openid-configuration`,\n\t\tfetchImpl,\n\t);\n}\n\n// Parse the `resource_metadata` param from a WWW-Authenticate header (RFC 9728 §5.1).\nexport function parseResourceMetadataUrl(\n\twwwAuthenticate: string | null | undefined,\n): string | null {\n\tif (!wwwAuthenticate) return null;\n\tconst match = wwwAuthenticate.match(\n\t\t/resource_metadata\\s*=\\s*\"([^\"]+)\"|resource_metadata\\s*=\\s*([^\\s,]+)/i,\n\t);\n\treturn match ? (match[1] ?? match[2] ?? null) : null;\n}\n\nasync function fetchProtectedResourceMetadata(\n\turl: string,\n\tfetchImpl: OAuthFetchImpl,\n): Promise<{\n\tauthorizationServers?: string[];\n\tscopesSupported?: string[];\n} | null> {\n\ttry {\n\t\tconst response = await fetchImpl(url, {\n\t\t\tmethod: 'GET',\n\t\t\theaders: {accept: 'application/json'},\n\t\t});\n\t\tif (response.ok === false) return null;\n\t\tconst data = (await response.json()) as {\n\t\t\tauthorization_servers?: string[];\n\t\t\tscopes_supported?: string[];\n\t\t};\n\t\treturn {\n\t\t\tauthorizationServers: data.authorization_servers,\n\t\t\tscopesSupported: data.scopes_supported,\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport interface ServerAuthRequirements {\n\treadonly requiresAuth: boolean;\n\treadonly metadata?: AuthServerMetadata;\n\treadonly error?: string;\n}\n\n// Probe an MCP server to learn whether it requires OAuth and, if so, where to\n// authenticate. Honors RFC 9728 (the WWW-Authenticate `resource_metadata`\n// pointer names the real authorization server, which often lives on a different\n// host than the MCP endpoint) before falling back to same-origin probing.\nexport async function checkServerAuthRequirements(params: {\n\treadonly serverUrl: string;\n\treadonly fetchImpl?: OAuthFetchImpl;\n}): Promise<ServerAuthRequirements> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\ttry {\n\t\tconst response = await fetchWithTimeout(fetchImpl, params.serverUrl, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {'content-type': 'application/json'},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tjsonrpc: '2.0',\n\t\t\t\tmethod: 'initialize',\n\t\t\t\tid: 0,\n\t\t\t\t// clientInfo is required by the MCP `initialize` spec; a server that\n\t\t\t\t// validates the body before auth would 400 a probe without it (and we\n\t\t\t\t// would then misread that as \"no auth required\").\n\t\t\t\tparams: {\n\t\t\t\t\tprotocolVersion: MCP_PROTOCOL_VERSION,\n\t\t\t\t\tcapabilities: {},\n\t\t\t\t\tclientInfo: MCP_CLIENT_INFO,\n\t\t\t\t},\n\t\t\t}),\n\t\t});\n\t\tconst status = response.status ?? 200;\n\t\tif (status === 401 || status === 403) {\n\t\t\tconst wwwAuth = response.headers?.get('www-authenticate') ?? null;\n\t\t\tconst resourceMetadataUrl = parseResourceMetadataUrl(wwwAuth);\n\t\t\tif (resourceMetadataUrl) {\n\t\t\t\tconst prm = await fetchProtectedResourceMetadata(\n\t\t\t\t\tresourceMetadataUrl,\n\t\t\t\t\tfetchImpl,\n\t\t\t\t);\n\t\t\t\tconst issuer = prm?.authorizationServers?.[0];\n\t\t\t\tif (issuer) {\n\t\t\t\t\tconst metadata = await discoverOAuthMetadataFromIssuer({\n\t\t\t\t\t\tissuerUrl: issuer,\n\t\t\t\t\t\tfetchImpl,\n\t\t\t\t\t});\n\t\t\t\t\tif (metadata) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\trequiresAuth: true,\n\t\t\t\t\t\t\tmetadata: prm?.scopesSupported\n\t\t\t\t\t\t\t\t? {...metadata, scopes: prm.scopesSupported}\n\t\t\t\t\t\t\t\t: metadata,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst metadata = await discoverOAuthMetadata({\n\t\t\t\tserverUrl: params.serverUrl,\n\t\t\t\tfetchImpl,\n\t\t\t});\n\t\t\treturn {requiresAuth: true, metadata: metadata ?? undefined};\n\t\t}\n\t\treturn {requiresAuth: false};\n\t} catch (error) {\n\t\treturn {\n\t\t\trequiresAuth: false,\n\t\t\terror: `Server unreachable: ${String(error)}`,\n\t\t};\n\t}\n}\n\n// RFC 7591 dynamic client registration — some servers mint a client on demand.\nexport async function registerOAuthClient(params: {\n\treadonly registrationEndpoint: string;\n\treadonly clientName: string;\n\treadonly redirectUris: readonly string[];\n\treadonly fetchImpl?: OAuthFetchImpl;\n}): Promise<{clientId: string; clientSecret?: string} | null> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\ttry {\n\t\tconst response = await fetchImpl(params.registrationEndpoint, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {'content-type': 'application/json'},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tclient_name: params.clientName,\n\t\t\t\tredirect_uris: params.redirectUris,\n\t\t\t\ttoken_endpoint_auth_method: 'none', // public client (PKCE)\n\t\t\t\tgrant_types: ['authorization_code', 'refresh_token'],\n\t\t\t\tresponse_types: ['code'],\n\t\t\t}),\n\t\t});\n\t\tif (response.ok === false) return null;\n\t\tconst data = (await response.json()) as {\n\t\t\tclient_id?: string;\n\t\t\tclient_secret?: string;\n\t\t};\n\t\tif (!data.client_id) return null;\n\t\treturn {clientId: data.client_id, clientSecret: data.client_secret};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n// ── Authorization URL ────────────────────────────────────────────────────────\nexport function buildAuthorizationUrl(params: {\n\treadonly authorizationEndpoint: string;\n\treadonly clientId: string;\n\treadonly redirectUri: string;\n\treadonly challenge: string;\n\treadonly scope?: string;\n\treadonly state?: string;\n}): string {\n\tconst query: Record<string, string> = {\n\t\tresponse_type: 'code',\n\t\tclient_id: params.clientId,\n\t\tredirect_uri: params.redirectUri,\n\t\tcode_challenge: params.challenge,\n\t\tcode_challenge_method: 'S256',\n\t};\n\tif (params.scope) query.scope = params.scope;\n\tif (params.state) query.state = params.state;\n\t// Merge into any existing query on the endpoint via the URL API. Raw\n\t// `?${queryString}` concatenation double-`?`s an authorization_endpoint that\n\t// already carries a query (e.g. multi-tenant `.../authorize?tenant=acme`),\n\t// which the authorization server then can't parse.\n\tconst url = new URL(params.authorizationEndpoint);\n\tfor (const [key, value] of Object.entries(query)) {\n\t\turl.searchParams.set(key, value);\n\t}\n\treturn url.toString();\n}\n\n// ── Token exchange + refresh ─────────────────────────────────────────────────\nexport async function exchangeCodeForToken(params: {\n\treadonly tokenEndpoint: string;\n\treadonly code: string;\n\treadonly verifier: string;\n\treadonly clientId: string;\n\treadonly redirectUri: string;\n\treadonly clientSecret?: string;\n\treadonly fetchImpl?: OAuthFetchImpl;\n\treadonly now?: () => number;\n\t// Request body encoding — default form-urlencoded (OAuth2 / every MCP caller); 'json' for\n\t// providers whose token endpoint requires a JSON body (e.g. Anthropic).\n\treadonly encoding?: TokenRequestEncoding;\n}): Promise<TokenResult> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\tconst form: Record<string, string> = {\n\t\tgrant_type: 'authorization_code',\n\t\tcode: params.code,\n\t\tcode_verifier: params.verifier,\n\t\tclient_id: params.clientId,\n\t\tredirect_uri: params.redirectUri,\n\t};\n\tif (params.clientSecret) form.client_secret = params.clientSecret;\n\tconst {headers, body} = encodeTokenRequest(form, params.encoding ?? 'form');\n\tconst response = await fetchWithTimeout(fetchImpl, params.tokenEndpoint, {\n\t\tmethod: 'POST',\n\t\theaders,\n\t\tbody,\n\t});\n\tif (response.ok === false) {\n\t\tconst body = response.text ? await response.text() : '';\n\t\tthrow new Error(\n\t\t\t`Token exchange failed: ${response.status ?? '?'} ${body}`.trim(),\n\t\t);\n\t}\n\treturn toTokenResult(\n\t\t(await response.json()) as RawTokenResponse,\n\t\tparams.now ?? (() => Date.now()),\n\t);\n}\n\nexport async function refreshAccessToken(params: {\n\treadonly tokenEndpoint: string;\n\treadonly refreshToken: string;\n\treadonly clientId: string;\n\treadonly clientSecret?: string;\n\treadonly fetchImpl?: OAuthFetchImpl;\n\treadonly now?: () => number;\n\t// Request body encoding — default form-urlencoded; 'json' for providers (e.g. Anthropic) whose\n\t// token endpoint requires a JSON body.\n\treadonly encoding?: TokenRequestEncoding;\n}): Promise<TokenResult> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\tconst form: Record<string, string> = {\n\t\tgrant_type: 'refresh_token',\n\t\trefresh_token: params.refreshToken,\n\t\tclient_id: params.clientId,\n\t};\n\tif (params.clientSecret) form.client_secret = params.clientSecret;\n\tconst {headers, body} = encodeTokenRequest(form, params.encoding ?? 'form');\n\tconst response = await fetchWithTimeout(fetchImpl, params.tokenEndpoint, {\n\t\tmethod: 'POST',\n\t\theaders,\n\t\tbody,\n\t});\n\tif (response.ok === false) {\n\t\tconst body = response.text ? await response.text() : '';\n\t\tthrow new Error(\n\t\t\t`Token refresh failed: ${response.status ?? '?'} ${body}`.trim(),\n\t\t);\n\t}\n\t// Keep the old refresh token if the server didn't rotate it.\n\treturn toTokenResult(\n\t\t(await response.json()) as RawTokenResponse,\n\t\tparams.now ?? (() => Date.now()),\n\t\tparams.refreshToken,\n\t);\n}\n\n// ── Interactive auth-code + PKCE flow ────────────────────────────────────────\nconst DEFAULT_CALLBACK_PORT = 8085;\nconst LOOPBACK_HOST = '127.0.0.1';\n\nexport interface OAuthResult {\n\treadonly success: boolean;\n\treadonly token?: TokenResult;\n\treadonly error?: string;\n}\n\n// Escape HTML so an attacker-influenced error_description can't inject script\n// into the page rendered back into the user's browser.\nfunction escapeHtml(value: string): string {\n\treturn value\n\t\t.replace(/&/g, '&')\n\t\t.replace(/</g, '<')\n\t\t.replace(/>/g, '>')\n\t\t.replace(/\"/g, '"')\n\t\t.replace(/'/g, ''');\n}\n\nfunction htmlPage(title: string, body: string): string {\n\treturn `<!DOCTYPE html><html><head><title>${title}</title></head><body style=\"font-family: system-ui; padding: 40px; text-align: center;\"><h1>${title}</h1><p>${body}</p></body></html>`;\n}\n\ninterface CallbackServer {\n\treadonly server: Server;\n\treadonly waitForCode: () => Promise<string>;\n}\n\nfunction startCallbackServer(\n\tport: number,\n\texpectedState: string,\n): Promise<CallbackServer> {\n\treturn new Promise((resolveServer, rejectServer) => {\n\t\tlet resolveCode: ((code: string) => void) | null = null;\n\t\tlet rejectCode: ((error: Error) => void) | null = null;\n\t\tconst codePromise = new Promise<string>((resolve, reject) => {\n\t\t\tresolveCode = resolve;\n\t\t\trejectCode = reject;\n\t\t});\n\t\t// Mark as handled so an early callback (e.g. an injected opener that fires\n\t\t// before the caller attaches its consumer) can't trip an unhandled\n\t\t// rejection; the real consumer still receives the resolution/rejection.\n\t\tcodePromise.catch(() => {});\n\n\t\tconst server = createServer((request, response) => {\n\t\t\tconst requestUrl = new URL(\n\t\t\t\trequest.url ?? '/',\n\t\t\t\t`http://${LOOPBACK_HOST}:${port}`,\n\t\t\t);\n\t\t\tif (requestUrl.pathname !== '/callback') {\n\t\t\t\tresponse.writeHead(404, {Connection: 'close'});\n\t\t\t\tresponse.end('Not Found');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst code = requestUrl.searchParams.get('code');\n\t\t\tconst error = requestUrl.searchParams.get('error');\n\t\t\tconst errorDescription =\n\t\t\t\trequestUrl.searchParams.get('error_description');\n\t\t\tconst state = requestUrl.searchParams.get('state');\n\n\t\t\tconst respond = (statusCode: number, page: string): void => {\n\t\t\t\tresponse.writeHead(statusCode, {\n\t\t\t\t\t'Content-Type': 'text/html',\n\t\t\t\t\tConnection: 'close',\n\t\t\t\t});\n\t\t\t\tresponse.end(page);\n\t\t\t};\n\n\t\t\t// CSRF defense: the state we sent must come back unchanged.\n\t\t\tif (state !== expectedState) {\n\t\t\t\trespond(\n\t\t\t\t\t400,\n\t\t\t\t\thtmlPage(\n\t\t\t\t\t\t'Authentication Failed',\n\t\t\t\t\t\t'Invalid state parameter. Please try again.',\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\trejectCode?.(new Error('OAuth state parameter mismatch'));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (error) {\n\t\t\t\tconst safe = escapeHtml(errorDescription || error);\n\t\t\t\trespond(400, htmlPage('Authentication Failed', safe));\n\t\t\t\trejectCode?.(new Error(errorDescription || error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!code) {\n\t\t\t\trespond(\n\t\t\t\t\t400,\n\t\t\t\t\thtmlPage(\n\t\t\t\t\t\t'Invalid Request',\n\t\t\t\t\t\t'No authorization code received.',\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\trejectCode?.(new Error('No authorization code received'));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\trespond(\n\t\t\t\t200,\n\t\t\t\thtmlPage(\n\t\t\t\t\t'Authentication Successful',\n\t\t\t\t\t'You can close this window and return to Command Code.',\n\t\t\t\t),\n\t\t\t);\n\t\t\tresolveCode?.(code);\n\t\t});\n\n\t\tserver.on('error', rejectServer);\n\t\t// Tight keep-alive so idle browser sockets don't pin the event loop after\n\t\t// close. 1ms (not 0 — Node reads 0 as \"never close\").\n\t\tserver.keepAliveTimeout = 1;\n\t\tserver.headersTimeout = 5000;\n\t\tserver.listen(port, LOOPBACK_HOST, () => {\n\t\t\tresolveServer({server, waitForCode: () => codePromise});\n\t\t});\n\t});\n}\n\nfunction defaultOpenBrowser(url: string): void {\n\ttry {\n\t\tif (process.platform === 'win32') {\n\t\t\t// cmd.exe's `start` treats its first quoted token as the window title,\n\t\t\t// so pass an empty \"\" title then the URL. The URL MUST stay quoted:\n\t\t\t// authorization URLs always carry several `&`-separated query params, and\n\t\t\t// an unquoted `&` is a cmd command separator that would truncate the URL\n\t\t\t// and kill the flow. windowsVerbatimArguments stops Node re-quoting (and\n\t\t\t// doubling) our escaping. (The old build shelled out with the URL\n\t\t\t// unquoted, breaking OAuth on Windows.)\n\t\t\tconst child = spawn('cmd', ['/c', 'start', '\"\"', `\"${url}\"`], {\n\t\t\t\tstdio: 'ignore',\n\t\t\t\tdetached: true,\n\t\t\t\twindowsVerbatimArguments: true,\n\t\t\t});\n\t\t\tchild.on('error', () => {});\n\t\t\tchild.unref();\n\t\t\treturn;\n\t\t}\n\t\tconst command = process.platform === 'darwin' ? 'open' : 'xdg-open';\n\t\tconst child = spawn(command, [url], {\n\t\t\tstdio: 'ignore',\n\t\t\tdetached: true,\n\t\t});\n\t\tchild.on('error', () => {});\n\t\tchild.unref();\n\t} catch {\n\t\t// Best-effort: if no opener exists, the user can paste the URL manually.\n\t}\n}\n\n// Run the OAuth2 authorization-code flow with PKCE: start a loopback callback\n// server, open the browser to the authorization URL, await the redirect (with a\n// CSRF/state check + timeout), exchange the code, and persist the token bound to\n// the server URL. The browser opener + fetch are injectable for tests.\nexport async function performOAuthFlow(params: {\n\treadonly serverUrl: string;\n\treadonly config: OAuthConfig;\n\treadonly vault: {\n\t\tset(input: {\n\t\t\treadonly serverUrl: string;\n\t\t\treadonly token: TokenResult;\n\t\t}): Promise<void>;\n\t};\n\treadonly port?: number;\n\treadonly timeoutMs?: number;\n\treadonly onStatus?: (message: string) => void;\n\treadonly openBrowser?: (url: string) => void | Promise<void>;\n\treadonly fetchImpl?: OAuthFetchImpl;\n\treadonly now?: () => number;\n}): Promise<OAuthResult> {\n\tif (!isSecureOrLoopback(params.serverUrl)) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: `MCP server url must use https:// when OAuth is configured (got \"${params.serverUrl}\"). http:// is only allowed for loopback hosts.`,\n\t\t};\n\t}\n\tconst port = params.port ?? DEFAULT_CALLBACK_PORT;\n\tconst timeoutMs = params.timeoutMs ?? 120_000;\n\tconst onStatus = params.onStatus ?? (() => {});\n\tconst openBrowser = params.openBrowser ?? defaultOpenBrowser;\n\tconst redirectUri = `http://${LOOPBACK_HOST}:${port}/callback`;\n\n\tlet server: Server | null = null;\n\tlet timeoutTimer: ReturnType<typeof setTimeout> | undefined;\n\ttry {\n\t\tconst pkce = generatePkce();\n\t\tconst state = randomBytes(32).toString('base64url');\n\n\t\tonStatus('Starting authentication server...');\n\t\tconst callback = await startCallbackServer(port, state);\n\t\tserver = callback.server;\n\n\t\tconst authUrl = buildAuthorizationUrl({\n\t\t\tauthorizationEndpoint: params.config.authorizationUrl,\n\t\t\tclientId: params.config.clientId,\n\t\t\tredirectUri,\n\t\t\tchallenge: pkce.challenge,\n\t\t\tscope: params.config.scopes?.length\n\t\t\t\t? params.config.scopes.join(' ')\n\t\t\t\t: undefined,\n\t\t\tstate,\n\t\t});\n\n\t\tonStatus('Opening browser for authentication...');\n\t\tawait openBrowser(authUrl);\n\n\t\tonStatus('Waiting for authorization...');\n\t\tconst timeoutPromise = new Promise<never>((_, reject) => {\n\t\t\ttimeoutTimer = setTimeout(\n\t\t\t\t() => reject(new Error('Authentication timed out')),\n\t\t\t\ttimeoutMs,\n\t\t\t);\n\t\t});\n\t\tconst code = await Promise.race([\n\t\t\tcallback.waitForCode(),\n\t\t\ttimeoutPromise,\n\t\t]);\n\n\t\tonStatus('Exchanging authorization code for tokens...');\n\t\tconst token = await exchangeCodeForToken({\n\t\t\ttokenEndpoint: params.config.tokenUrl,\n\t\t\tcode,\n\t\t\tverifier: pkce.verifier,\n\t\t\tclientId: params.config.clientId,\n\t\t\tclientSecret: params.config.clientSecret,\n\t\t\tredirectUri,\n\t\t\tfetchImpl: params.fetchImpl,\n\t\t\tnow: params.now,\n\t\t});\n\n\t\t// Bind the token to the server URL so it can never later be attached to a\n\t\t// request to a different origin (a malicious config swap).\n\t\tawait params.vault.set({\n\t\t\tserverUrl: params.serverUrl,\n\t\t\ttoken: {...token, issuerUrl: params.serverUrl},\n\t\t});\n\t\tonStatus('Authentication successful!');\n\t\treturn {success: true, token};\n\t} catch (error) {\n\t\treturn {success: false, error: String(error)};\n\t} finally {\n\t\tif (timeoutTimer) clearTimeout(timeoutTimer);\n\t\tif (server) {\n\t\t\t// close() alone only stops new connections — force idle/active sockets\n\t\t\t// shut so the CLI's event loop can exit.\n\t\t\tserver.closeIdleConnections?.();\n\t\t\tserver.closeAllConnections?.();\n\t\t\tserver.close();\n\t\t\tserver.unref();\n\t\t}\n\t}\n}\n","// Reusable zero-dep OAuth primitives a provider MODULE (built-in or external plugin) can use to\n// build its login flow without re-rolling the boring parts: PKCE, a loopback callback server, and\n// device-code request/poll. PKCE + the token exchange/refresh live in `../mcp/oauth.js` (the MCP\n// client already needed them) — we REUSE those here rather than duplicate, and add the two pieces\n// MCP didn't need: a general loopback server that returns its own redirect URI, and device-code.\n//\n// Node built-ins only (node:http, node:url) + the injected/global fetch — everything stays testable.\n\nimport {createServer, type Server} from 'node:http';\nimport {URL} from 'node:url';\n\nimport type {OAuthFetchImpl, TokenResult} from '../mcp/oauth.js';\n\n// Re-export the shared PKCE + token primitives so a plugin can pull the whole login toolkit from\n// one place. (Token exchange/refresh — exchangeCodeForToken / refreshAccessToken — are already\n// exported from the package root via mcp/oauth.)\nexport {generatePkce} from '../mcp/oauth.js';\nexport type {OAuthFetchImpl, Pkce, TokenResult} from '../mcp/oauth.js';\n\nconst LOOPBACK_HOST = '127.0.0.1';\n\nfunction defaultFetch(): OAuthFetchImpl {\n\treturn globalThis.fetch as unknown as OAuthFetchImpl;\n}\n\nfunction encodeForm(fields: Record<string, string>): string {\n\treturn Object.entries(fields)\n\t\t.map(\n\t\t\t([key, value]) =>\n\t\t\t\t`${encodeURIComponent(key)}=${encodeURIComponent(value)}`,\n\t\t)\n\t\t.join('&');\n}\n\n// ── Loopback callback server (RFC 8252 native-app redirect) ──────────────────\nexport interface LoopbackCallback {\n\t// The http://127.0.0.1:<port><path> to use as the OAuth redirect_uri.\n\treadonly redirectUri: string;\n\t// Resolves with the authorization code (+ returned state) once the browser redirects back.\n\twaitForCode(): Promise<{\n\t\treadonly code: string;\n\t\treadonly state: string | null;\n\t}>;\n\t// Shut the server down — always call this once the flow settles (success or failure).\n\tclose(): void;\n}\n\n// Start a loopback HTTP server that captures the OAuth redirect. Pass port 0 (default) for an\n// ephemeral port so concurrent logins don't collide; read the real redirectUri off the result.\n// CSRF/state checking is the caller's job (it owns the state it sent) — this just surfaces it.\nexport function createLoopbackCallbackServer(\n\tparams: {\n\t\treadonly port?: number;\n\t\treadonly path?: string;\n\t\treadonly host?: string;\n\t\treadonly successHtml?: string;\n\t} = {},\n): Promise<LoopbackCallback> {\n\tconst host = params.host ?? LOOPBACK_HOST;\n\tconst path = params.path ?? '/callback';\n\tconst successHtml =\n\t\tparams.successHtml ??\n\t\t'<!DOCTYPE html><html><head><title>Authenticated</title></head><body style=\"font-family:system-ui;padding:40px;text-align:center;\"><h1>Authentication complete</h1><p>You can close this window and return to your terminal.</p></body></html>';\n\n\treturn new Promise((resolveServer, rejectServer) => {\n\t\tlet resolveCode:\n\t\t\t| ((value: {\n\t\t\t\t\treadonly code: string;\n\t\t\t\t\treadonly state: string | null;\n\t\t\t }) => void)\n\t\t\t| null = null;\n\t\tlet rejectCode: ((error: Error) => void) | null = null;\n\t\tconst codePromise = new Promise<{\n\t\t\treadonly code: string;\n\t\t\treadonly state: string | null;\n\t\t}>((resolve, reject) => {\n\t\t\tresolveCode = resolve;\n\t\t\trejectCode = reject;\n\t\t});\n\t\t// Swallow an early settle (e.g. a test opener firing before the caller awaits) so it can't\n\t\t// trip an unhandled rejection; the real consumer still receives the value.\n\t\tcodePromise.catch(() => {});\n\n\t\tconst server = createServer((request, response) => {\n\t\t\tconst requestUrl = new URL(request.url ?? '/', `http://${host}`);\n\t\t\tif (requestUrl.pathname !== path) {\n\t\t\t\tresponse.writeHead(404, {Connection: 'close'});\n\t\t\t\tresponse.end('Not Found');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst code = requestUrl.searchParams.get('code');\n\t\t\tconst error = requestUrl.searchParams.get('error');\n\t\t\tconst errorDescription =\n\t\t\t\trequestUrl.searchParams.get('error_description');\n\t\t\tconst state = requestUrl.searchParams.get('state');\n\t\t\tif (error) {\n\t\t\t\tresponse.writeHead(400, {\n\t\t\t\t\t'Content-Type': 'text/html',\n\t\t\t\t\tConnection: 'close',\n\t\t\t\t});\n\t\t\t\tresponse.end(\n\t\t\t\t\t'<!DOCTYPE html><html><body><h1>Authentication failed</h1></body></html>',\n\t\t\t\t);\n\t\t\t\trejectCode?.(new Error(errorDescription || error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!code) {\n\t\t\t\tresponse.writeHead(400, {\n\t\t\t\t\t'Content-Type': 'text/html',\n\t\t\t\t\tConnection: 'close',\n\t\t\t\t});\n\t\t\t\tresponse.end(\n\t\t\t\t\t'<!DOCTYPE html><html><body><h1>Missing authorization code</h1></body></html>',\n\t\t\t\t);\n\t\t\t\trejectCode?.(new Error('No authorization code received'));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresponse.writeHead(200, {\n\t\t\t\t'Content-Type': 'text/html',\n\t\t\t\tConnection: 'close',\n\t\t\t});\n\t\t\tresponse.end(successHtml);\n\t\t\tresolveCode?.({code, state});\n\t\t});\n\n\t\tserver.on('error', rejectServer);\n\t\t// Tight keep-alive so an idle browser socket can't pin the event loop after close\n\t\t// (1ms, not 0 — Node reads 0 as \"never close\").\n\t\tserver.keepAliveTimeout = 1;\n\t\tserver.headersTimeout = 5000;\n\t\tserver.listen(params.port ?? 0, host, () => {\n\t\t\tconst address = server.address();\n\t\t\tconst port =\n\t\t\t\ttypeof address === 'object' && address !== null\n\t\t\t\t\t? address.port\n\t\t\t\t\t: (params.port ?? 0);\n\t\t\tresolveServer({\n\t\t\t\tredirectUri: `http://${host}:${port}${path}`,\n\t\t\t\twaitForCode: () => codePromise,\n\t\t\t\tclose: () => {\n\t\t\t\t\tserver.closeIdleConnections?.();\n\t\t\t\t\tserver.closeAllConnections?.();\n\t\t\t\t\tserver.close();\n\t\t\t\t\tserver.unref();\n\t\t\t\t},\n\t\t\t});\n\t\t});\n\t});\n}\n\n// ── Device-code flow (RFC 8628) ──────────────────────────────────────────────\nexport interface DeviceCodeGrant {\n\treadonly deviceCode: string;\n\treadonly userCode: string;\n\treadonly verificationUri: string;\n\treadonly verificationUriComplete?: string;\n\treadonly expiresIn?: number; // seconds\n\treadonly interval?: number; // seconds between polls\n}\n\n// Step 1: ask the device-authorization endpoint for a device + user code.\nexport async function requestDeviceCode(params: {\n\treadonly deviceAuthorizationEndpoint: string;\n\treadonly clientId: string;\n\treadonly scopes?: readonly string[];\n\treadonly fetchImpl?: OAuthFetchImpl;\n}): Promise<DeviceCodeGrant> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\tconst fields: Record<string, string> = {client_id: params.clientId};\n\tif (params.scopes?.length) fields.scope = params.scopes.join(' ');\n\tconst response = await fetchImpl(params.deviceAuthorizationEndpoint, {\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\t'content-type': 'application/x-www-form-urlencoded',\n\t\t\taccept: 'application/json',\n\t\t},\n\t\tbody: encodeForm(fields),\n\t});\n\tif (response.ok === false) {\n\t\tconst body = response.text ? await response.text() : '';\n\t\tthrow new Error(\n\t\t\t`Device authorization failed: ${response.status ?? '?'} ${body}`.trim(),\n\t\t);\n\t}\n\tconst data = (await response.json()) as {\n\t\tdevice_code?: string;\n\t\tuser_code?: string;\n\t\tverification_uri?: string;\n\t\tverification_uri_complete?: string;\n\t\texpires_in?: number;\n\t\tinterval?: number;\n\t};\n\tif (!data.device_code || !data.user_code || !data.verification_uri) {\n\t\tthrow new Error(\n\t\t\t'Device authorization response missing required fields',\n\t\t);\n\t}\n\treturn {\n\t\tdeviceCode: data.device_code,\n\t\tuserCode: data.user_code,\n\t\tverificationUri: data.verification_uri,\n\t\tverificationUriComplete: data.verification_uri_complete,\n\t\texpiresIn: data.expires_in,\n\t\tinterval: data.interval,\n\t};\n}\n\n// Step 2: poll the token endpoint until the user approves (or it times out / errors). Honors the\n// RFC's `authorization_pending` (keep waiting) and `slow_down` (back off) responses. `sleep`/`now`\n// are injectable so a test can drive the loop without real timers.\nexport async function pollDeviceToken(params: {\n\treadonly tokenEndpoint: string;\n\treadonly clientId: string;\n\treadonly deviceCode: string;\n\treadonly intervalMs?: number;\n\treadonly timeoutMs?: number;\n\treadonly clientSecret?: string;\n\treadonly fetchImpl?: OAuthFetchImpl;\n\treadonly now?: () => number;\n\treadonly sleep?: (ms: number) => Promise<void>;\n}): Promise<TokenResult> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\tconst now = params.now ?? (() => Date.now());\n\tconst sleep =\n\t\tparams.sleep ??\n\t\t((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)));\n\tlet intervalMs = params.intervalMs ?? 5000;\n\tconst deadline = now() + (params.timeoutMs ?? 300_000);\n\n\tfor (;;) {\n\t\tif (now() >= deadline) {\n\t\t\tthrow new Error('Device authorization timed out');\n\t\t}\n\t\tawait sleep(intervalMs);\n\t\tconst fields: Record<string, string> = {\n\t\t\tgrant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n\t\t\tdevice_code: params.deviceCode,\n\t\t\tclient_id: params.clientId,\n\t\t};\n\t\tif (params.clientSecret) fields.client_secret = params.clientSecret;\n\t\tconst response = await fetchImpl(params.tokenEndpoint, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\t'content-type': 'application/x-www-form-urlencoded',\n\t\t\t\taccept: 'application/json',\n\t\t\t},\n\t\t\tbody: encodeForm(fields),\n\t\t});\n\t\tconst data = (await response.json()) as {\n\t\t\taccess_token?: string;\n\t\t\trefresh_token?: string;\n\t\t\texpires_in?: number;\n\t\t\ttoken_type?: string;\n\t\t\tscope?: string;\n\t\t\terror?: string;\n\t\t};\n\t\tif (data.access_token) {\n\t\t\treturn {\n\t\t\t\taccessToken: data.access_token,\n\t\t\t\trefreshToken: data.refresh_token,\n\t\t\t\texpiresAt:\n\t\t\t\t\ttypeof data.expires_in === 'number'\n\t\t\t\t\t\t? now() + data.expires_in * 1000\n\t\t\t\t\t\t: undefined,\n\t\t\t\ttokenType: data.token_type,\n\t\t\t\tscope: data.scope,\n\t\t\t};\n\t\t}\n\t\tif (data.error === 'authorization_pending') continue;\n\t\tif (data.error === 'slow_down') {\n\t\t\tintervalMs += 5000; // RFC 8628 §3.5: bump the interval by 5s and keep polling\n\t\t\tcontinue;\n\t\t}\n\t\tthrow new Error(\n\t\t\t`Device authorization failed: ${data.error ?? 'unknown error'}`,\n\t\t);\n\t}\n}\n","// The OpenAI OAuth flow itself, built on the harness's reusable primitives\n// (createLoopbackCallbackServer / exchangeCodeForToken / refreshAccessToken). This is a port of\n// command's `auth/codex.ts`: PKCE authorize URL with the Codex-specific params, a loopback callback\n// server on the registered port, CSRF/state validation, the form-encoded code→token exchange, and\n// the refresh grant.\n\nimport {randomBytes} from 'node:crypto';\n\nimport {\n\ttype Credential,\n\tcreateLoopbackCallbackServer,\n\texchangeCodeForToken,\n\ttype LoopbackCallback,\n\ttype OAuthFetchImpl,\n\trefreshAccessToken,\n\ttype TokenResult,\n} from '@commandcode/harness/provider-kit';\n\nimport {\n\tAUTHORIZE_ENDPOINT,\n\tBIND_HOST,\n\tCALLBACK_PATH,\n\tCALLBACK_TIMEOUT_MS,\n\tCLIENT_ID,\n\tEXPIRY_SKEW_MS,\n\tOAUTH_PORT,\n\tREDIRECT_URI,\n\tSCOPE,\n\tTOKEN_ENDPOINT,\n} from './constants.js';\n\n// Injected I/O so every step stays testable: a custom fetch (defaults to global fetch inside the\n// harness helpers) and a clock for expiry math + `expires_at` computation.\nexport interface OAuthDeps {\n\treadonly fetchImpl?: OAuthFetchImpl;\n\treadonly now: () => number;\n}\n\nconst SUCCESS_HTML = `<!doctype html>\n<html>\n <head><title>Command Code — OpenAI Authorization Successful</title>\n <style>body{font-family:system-ui;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background:#0f0f0f;color:#eee}h1{color:#7ee787}</style>\n </head>\n <body><div><h1>Authorization successful</h1><p>You can close this window and return to Command Code.</p></div>\n <script>setTimeout(()=>window.close(),2000)</script></body>\n</html>`;\n\n// Generate the CSRF `state` exactly like codex.ts (32 random bytes, base64url).\nexport function generateState(): string {\n\treturn randomBytes(32).toString('base64url');\n}\n\n// Build the OpenAI authorize URL with the Codex-specific query params. The extra params\n// (`id_token_add_organizations` / `codex_cli_simplified_flow` / `originator`) are required by\n// OpenAI's Codex flow and are absent from the harness's generic builder, so we assemble the URL here\n// to stay byte-for-byte with codex.ts' buildAuthorizeUrl.\nexport function buildAuthorizeUrl(params: {\n\treadonly challenge: string;\n\treadonly state: string;\n}): string {\n\tconst query = new URLSearchParams({\n\t\tresponse_type: 'code',\n\t\tclient_id: CLIENT_ID,\n\t\tredirect_uri: REDIRECT_URI,\n\t\tscope: SCOPE,\n\t\tcode_challenge: params.challenge,\n\t\tcode_challenge_method: 'S256',\n\t\tid_token_add_organizations: 'true',\n\t\tcodex_cli_simplified_flow: 'true',\n\t\tstate: params.state,\n\t\toriginator: 'codex_cli_rs',\n\t});\n\treturn `${AUTHORIZE_ENDPOINT}?${query.toString()}`;\n}\n\n// Convert a harness TokenResult into the harness Credential the store persists.\nexport function tokenResultToCredential(token: TokenResult): Credential {\n\treturn {\n\t\tkind: 'oauth',\n\t\ttoken: token.accessToken,\n\t\t...(token.refreshToken ? {refreshToken: token.refreshToken} : {}),\n\t\t...(token.expiresAt !== undefined ? {expiresAt: token.expiresAt} : {}),\n\t};\n}\n\n// True when an oauth credential is within the 5-minute refresh skew of expiry (mirrors codex.ts).\nexport function isExpiring(credential: Credential, now: () => number): boolean {\n\treturn (\n\t\ttypeof credential.expiresAt === 'number' &&\n\t\tcredential.expiresAt - EXPIRY_SKEW_MS <= now()\n\t);\n}\n\n// Refresh the access token via the refresh-token grant. codex's token endpoint is FORM-encoded\n// (application/x-www-form-urlencoded), so we use the harness helper's default 'form' encoding (no\n// `encoding: 'json'`). refreshAccessToken keeps the old refresh token when the server doesn't rotate\n// it — matching codex.ts' `tokens.refresh_token || auth.refresh`.\nexport async function refreshCredential(params: {\n\treadonly refreshToken: string;\n\treadonly deps: OAuthDeps;\n}): Promise<Credential> {\n\tconst token = await refreshAccessToken({\n\t\ttokenEndpoint: TOKEN_ENDPOINT,\n\t\trefreshToken: params.refreshToken,\n\t\tclientId: CLIENT_ID,\n\t\tfetchImpl: params.deps.fetchImpl,\n\t\tnow: params.deps.now,\n\t});\n\treturn tokenResultToCredential(token);\n}\n\n// Start the loopback callback server. Binds 127.0.0.1 on the REGISTERED port (1455) at the\n// registered path — exactly like codex.ts (the advertised redirect_uri host stays `localhost`).\nexport function startLoopback(): Promise<LoopbackCallback> {\n\treturn createLoopbackCallbackServer({\n\t\tport: OAUTH_PORT,\n\t\thost: BIND_HOST,\n\t\tpath: CALLBACK_PATH,\n\t\tsuccessHtml: SUCCESS_HTML,\n\t});\n}\n\n// Await the browser redirect (with a 5-minute timeout mirroring codex.ts), verify the returned\n// state (CSRF defense — the harness loopback leaves this to the caller), then exchange the code for\n// tokens. Always closes the loopback server. The exchange is form-encoded (codex default).\nexport async function awaitCodeAndExchange(params: {\n\treadonly loopback: LoopbackCallback;\n\treadonly verifier: string;\n\treadonly expectedState: string;\n\treadonly deps: OAuthDeps;\n}): Promise<Credential> {\n\tconst {loopback, verifier, expectedState, deps} = params;\n\ttry {\n\t\tconst {code, state} = await withTimeout(\n\t\t\tloopback.waitForCode(),\n\t\t\tCALLBACK_TIMEOUT_MS,\n\t\t);\n\t\tif (state !== expectedState) {\n\t\t\tthrow new Error(\n\t\t\t\t'OpenAI OAuth: state mismatch — possible CSRF attempt',\n\t\t\t);\n\t\t}\n\t\tconst token = await exchangeCodeForToken({\n\t\t\ttokenEndpoint: TOKEN_ENDPOINT,\n\t\t\tcode,\n\t\t\tverifier,\n\t\t\tclientId: CLIENT_ID,\n\t\t\tredirectUri: REDIRECT_URI,\n\t\t\tfetchImpl: deps.fetchImpl,\n\t\t\tnow: deps.now,\n\t\t});\n\t\t// codex.ts requires a refresh token on the initial authorization-code grant.\n\t\tif (!token.refreshToken) {\n\t\t\tthrow new Error(\n\t\t\t\t'OpenAI OAuth: issuer did not return a refresh_token',\n\t\t\t);\n\t\t}\n\t\treturn tokenResultToCredential(token);\n\t} finally {\n\t\tloopback.close();\n\t}\n}\n\n// Reject if `promise` doesn't settle within `ms`. The timer is unref'd so a pending login can never\n// keep the process alive on its own.\nfunction withTimeout<Value>(\n\tpromise: Promise<Value>,\n\tms: number,\n): Promise<Value> {\n\treturn new Promise<Value>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\treject(\n\t\t\t\tnew Error(\n\t\t\t\t\t'OpenAI OAuth timed out waiting for browser callback',\n\t\t\t\t),\n\t\t\t);\n\t\t}, ms);\n\t\tif (typeof timer.unref === 'function') timer.unref();\n\t\tpromise.then(\n\t\t\tvalue => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\terror => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treject(\n\t\t\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t\t\t);\n\t\t\t},\n\t\t);\n\t});\n}\n","// The OpenAI ProviderModule: a single loopback-PKCE oauth method + a credential→headers\n// loader (refresh-on-stale, single-flight). Transport is the server-routed gateway, so the loader's\n// headers are the OAUTH_TOKEN / OAUTH_PROVIDER pair Command Code's `/alpha/generate` backend expects\n// (provider value `'codex'` — see constants.ts). This is command's `auth/codex.ts` flow expressed as\n// an external provider module.\n\nimport {\n\ttype AuthMethod,\n\ttype AuthSpec,\n\ttype Credential,\n\ttype CredentialStore,\n\tgeneratePkce,\n\ttype OAuthFetchImpl,\n\ttype ProviderModule,\n\ttype ProviderOAuthResult,\n\ttype RequestAuth,\n} from '@commandcode/harness/provider-kit';\nimport {\n\tDISPLAY_NAME,\n\tGATEWAY_ROUTE,\n\tHEADER_OAUTH_PROVIDER,\n\tHEADER_OAUTH_TOKEN,\n\tOAUTH_PROVIDER_VALUE,\n\tPROVIDER_ID,\n} from './constants.js';\nimport {\n\tbuildCodexProviderOptions,\n\tCODEX_HEADERS,\n\textractCodexAccountId,\n} from './codex.js';\nimport {OPENAI_MODEL_SPECS} from './models.js';\nimport {getCodexLanguageModel} from './server/index.js';\nimport {\n\tawaitCodeAndExchange,\n\tbuildAuthorizeUrl,\n\tgenerateState,\n\tisExpiring,\n\ttype OAuthDeps,\n\trefreshCredential,\n\tstartLoopback,\n} from './oauth.js';\n\nexport interface CreateOpenAIProviderParams {\n\t// Custom fetch for the token endpoint (defaults to global fetch). Injected in tests.\n\treadonly fetchImpl?: OAuthFetchImpl;\n\t// Clock for expiry math + `expires_at` computation (defaults to Date.now). Injected in tests.\n\treadonly now?: () => number;\n}\n\n// Resolve the credential the loader should attach, refreshing in place when it is within the expiry\n// skew. Single-flight per provider id (a Map, not a class) so concurrent calls share one refresh; a\n// refresh failure keeps the existing token rather than dropping it (matches codex.ts).\nasync function freshCredential(params: {\n\treadonly credential: Credential;\n\treadonly store: CredentialStore;\n\treadonly deps: OAuthDeps;\n\treadonly inFlight: Map<string, Promise<Credential>>;\n}): Promise<Credential> {\n\tconst {credential, store, deps, inFlight} = params;\n\tconst refreshToken = credential.refreshToken;\n\tif (!refreshToken || !isExpiring(credential, deps.now)) {\n\t\treturn credential;\n\t}\n\tconst existing = inFlight.get(PROVIDER_ID);\n\tif (existing) return existing;\n\tconst pending = (async (): Promise<Credential> => {\n\t\ttry {\n\t\t\tconst next = await refreshCredential({refreshToken, deps});\n\t\t\tawait store.set({provider: PROVIDER_ID, credential: next});\n\t\t\treturn next;\n\t\t} catch {\n\t\t\treturn credential; // a refresh failure must not drop the existing token\n\t\t} finally {\n\t\t\tinFlight.delete(PROVIDER_ID);\n\t\t}\n\t})();\n\tinFlight.set(PROVIDER_ID, pending);\n\treturn pending;\n}\n\nexport function createOpenAIProvider(\n\tparams: CreateOpenAIProviderParams = {},\n): ProviderModule {\n\tconst deps: OAuthDeps = {\n\t\tfetchImpl: params.fetchImpl,\n\t\tnow: params.now ?? ((): number => Date.now()),\n\t};\n\tconst inFlight = new Map<string, Promise<Credential>>();\n\t// The bearer token the auth.loader resolved, read back out of the request headers so\n\t// buildModel can hand it to the same @ai-sdk model factory the server half uses.\n\tconst bearerToken = (auth: RequestAuth): string =>\n\t\t(auth.headers?.['Authorization'] ?? '').replace(/^Bearer\\s+/i, '');\n\n\tconst oauthMethod: AuthMethod = {\n\t\tkind: 'oauth',\n\t\tlabel: 'Sign in with OpenAI',\n\t\t// Autonomous loopback flow: start the local callback server, hand back the authorize URL +\n\t\t// instructions, and a callback() that resolves on its own once the browser redirects back —\n\t\t// no user-pasted code (so no `prompt`).\n\t\tauthorize: async (): Promise<ProviderOAuthResult> => {\n\t\t\tconst pkce = generatePkce();\n\t\t\tconst state = generateState();\n\t\t\tconst loopback = await startLoopback();\n\t\t\tconst url = buildAuthorizeUrl({challenge: pkce.challenge, state});\n\t\t\treturn {\n\t\t\t\ttype: 'pending',\n\t\t\t\turl,\n\t\t\t\tinstructions:\n\t\t\t\t\t'Open this URL in your browser and approve access. After you authorize, OpenAI ' +\n\t\t\t\t\t'redirects back to this machine automatically — no copy/paste needed.',\n\t\t\t\tcallback: (): Promise<Credential> =>\n\t\t\t\t\tawaitCodeAndExchange({\n\t\t\t\t\t\tloopback,\n\t\t\t\t\t\tverifier: pkce.verifier,\n\t\t\t\t\t\texpectedState: state,\n\t\t\t\t\t\tdeps,\n\t\t\t\t\t}),\n\t\t\t};\n\t\t},\n\t\trefresh: async ({credential}): Promise<Credential> => {\n\t\t\tif (credential.kind !== 'oauth' || !credential.refreshToken) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'OpenAI refresh requires an oauth credential with a refresh token',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn refreshCredential({\n\t\t\t\trefreshToken: credential.refreshToken,\n\t\t\t\tdeps,\n\t\t\t});\n\t\t},\n\t};\n\n\tconst auth: AuthSpec = {\n\t\tmethods: [oauthMethod],\n\t\t// credential → request auth. Refresh happens here (expiry-skew, single-flight); the resulting\n\t\t// headers are exactly what command's `commandAuthHeaders` emits for codex.\n\t\tloader: async ({credential, store}): Promise<RequestAuth> => {\n\t\t\tif (\n\t\t\t\t!credential ||\n\t\t\t\tcredential.kind !== 'oauth' ||\n\t\t\t\t!credential.token\n\t\t\t) {\n\t\t\t\treturn {};\n\t\t\t}\n\t\t\tconst active = await freshCredential({\n\t\t\t\tcredential,\n\t\t\t\tstore,\n\t\t\t\tdeps,\n\t\t\t\tinFlight,\n\t\t\t});\n\t\t\tconst token = active.token ?? credential.token;\n\t\t\tconst accountId = extractCodexAccountId(token);\n\t\t\treturn {\n\t\t\t\theaders: {\n\t\t\t\t\t...CODEX_HEADERS,\n\t\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t\t...(accountId ? {'ChatGPT-Account-Id': accountId} : {}),\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n\n\treturn {\n\t\tid: PROVIDER_ID,\n\t\tdisplayName: DISPLAY_NAME,\n\t\t// The full OpenAI catalog (windows/efforts/spec kinds) — overlays the harness's fallback\n\t\t// mirror so this package is the runtime source of truth.\n\t\tmodels: OPENAI_MODEL_SPECS,\n\t\t// ChatGPT subscription requests go straight to the Codex Responses API, run locally\n\t\t// through the AI SDK (the same model factory the server half uses). Neither the OAuth\n\t\t// token nor prompts pass through Command Code's API.\n\t\ttransport: {\n\t\t\tkind: 'aisdk',\n\t\t\t// Codex takes the system prompt as `instructions` (providerOptions below) and\n\t\t\t// rejects system input items.\n\t\t\tomitSystem: true,\n\t\t\t// The ChatGPT backend 400s on max_output_tokens (\"Unsupported parameter\") —\n\t\t\t// the real Codex client never sends an output limit.\n\t\t\tomitMaxOutputTokens: true,\n\t\t\tbuildModel: ({model, auth}) =>\n\t\t\t\tgetCodexLanguageModel({\n\t\t\t\t\tmodelId: model,\n\t\t\t\t\toAuthToken: bearerToken(auth),\n\t\t\t\t\t...(params.fetchImpl\n\t\t\t\t\t\t? {fetch: params.fetchImpl as typeof globalThis.fetch}\n\t\t\t\t\t\t: {}),\n\t\t\t\t}),\n\t\t\t// instructions + store:false + encrypted-reasoning include + promptCacheKey — the\n\t\t\t// same wire options the server half sends (buildCodexProviderOptions).\n\t\t\tproviderOptions: ({system, threadId}) =>\n\t\t\t\tbuildCodexProviderOptions({\n\t\t\t\t\tsystem: system ?? '',\n\t\t\t\t\t...(threadId ? {sessionId: threadId} : {}),\n\t\t\t\t}),\n\t\t},\n\t\thooks: {\n\t\t\t// effort knob → Responses reasoning options ({reasoning: {effort, summary: 'auto'}}\n\t\t\t// on the wire, via the SDK).\n\t\t\tthinking: ({effort}) => {\n\t\t\t\tif (!effort || effort === 'off') return undefined;\n\t\t\t\treturn {\n\t\t\t\t\topenai: {\n\t\t\t\t\t\treasoningEffort: effort === 'max' ? 'xhigh' : effort,\n\t\t\t\t\t\treasoningSummary: 'auto',\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t\tauth,\n\t};\n}\n","// @byokkit/cmd-provider-openai — OpenAI (Codex / ChatGPT) loopback OAuth as a Command Code\n// ProviderModule. Default export is a ready-to-register module; the named factory lets callers\n// inject a custom fetch/clock (used in tests). Constants are re-exported for parity assertions and\n// for callers that need the registered values.\n\nimport {createOpenAIProvider} from './provider.js';\n\nexport {\n\tADVERTISED_HOST,\n\tAUTHORIZE_ENDPOINT,\n\tBIND_HOST,\n\tCALLBACK_PATH,\n\tCALLBACK_TIMEOUT_MS,\n\tCLIENT_ID,\n\tDISPLAY_NAME,\n\tEXPIRY_SKEW_MS,\n\tGATEWAY_ROUTE,\n\tHEADER_OAUTH_PROVIDER,\n\tHEADER_OAUTH_TOKEN,\n\tISSUER,\n\tOAUTH_PORT,\n\tOAUTH_PROVIDER_VALUE,\n\tPROVIDER_ID,\n\tREDIRECT_URI,\n\tSCOPE,\n\tTOKEN_ENDPOINT,\n} from './constants.js';\nexport type {CreateOpenAIProviderParams} from './provider.js';\nexport {createOpenAIProvider} from './provider.js';\n\n// A concrete, ready-to-register ProviderModule built with the default (global) fetch + clock.\nconst openaiProvider = createOpenAIProvider();\nexport default openaiProvider;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACSA,SAAQ,YAAY,mBAAkB;ACDtC,SAAQ,gBAAAA,qBAAgC;AACxC,SAAQ,OAAAC,YAAU;ADwBlB,SAAS,eAA+B;AACvC,SAAO,WAAW;AACnB;AAOA,IAAM,2BAA2B;AAEjC,eAAe,iBACd,WACA,KACA,MAKA,YAAY,0BACkB;AAC9B,QAAM,aAAa,IAAI,gBAAgB;AACvC,QAAM,QAAQ,WAAW,MAAM,WAAW,MAAM,GAAG,SAAS;AAC5D,MAAI;AACH,WAAO,MAAM,UAAU,KAAK,EAAC,GAAG,MAAM,QAAQ,WA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AAC;AAAA,MACzC,CAAC;AAAA,IACH;AAAA,IACA,OAAO;AAAA;AAAA;AAAA,MAGN,UAAU,CAAC,EAAC,OAAM,MAAM;AACvB,YAAI,CAAC,UAAU,WAAW,MAAO,QAAO;AACxC,eAAO;AAAA,UACN,QAAQ;AAAA,YACP,iBAAiB,WAAW,QAAQ,UAAU;AAAA,YAC9C,kBAAkB;AAAA,UACnB;AAAA,QACD;AAAA,MACD;AAAA,IACD;AAAA,IACA;AAAA,EACD;AACD;;;ACnLA,IAAM,iBAAiB,qBAAqB;AAC5C,IAAO,gBAAQ;","names":["createServer","URL","body","LOOPBACK_HOST","LOOPBACK_HOST","createServer","URL","randomBytes","randomBytes","auth"]}
|
package/dist/models.d.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
type OpenAIReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
|
|
2
|
+
interface OpenAIModelOption {
|
|
3
|
+
readonly id: string;
|
|
4
|
+
readonly provider: 'openai';
|
|
5
|
+
readonly spec: 'responses' | 'chatComplete';
|
|
6
|
+
readonly label: string;
|
|
7
|
+
readonly name: string;
|
|
8
|
+
readonly description: string;
|
|
9
|
+
readonly reasoning?: boolean;
|
|
10
|
+
readonly reasoningEfforts?: readonly OpenAIReasoningEffort[];
|
|
11
|
+
readonly contextWindow?: number;
|
|
12
|
+
readonly inputModalities?: readonly ('text' | 'image')[];
|
|
13
|
+
}
|
|
14
|
+
declare const OPENAI_MODEL_OPTIONS: {
|
|
15
|
+
readonly GPT_5_6_SOL: {
|
|
16
|
+
readonly id: "gpt-5.6-sol";
|
|
17
|
+
readonly inputModalities: readonly ["text", "image"];
|
|
18
|
+
readonly provider: "openai";
|
|
19
|
+
readonly spec: "responses";
|
|
20
|
+
readonly label: "GPT-5.6 Sol";
|
|
21
|
+
readonly name: "GPT-5.6 Sol";
|
|
22
|
+
readonly description: "frontier model for complex professional work";
|
|
23
|
+
readonly reasoning: true;
|
|
24
|
+
readonly reasoningEfforts: readonly OpenAIReasoningEffort[];
|
|
25
|
+
readonly contextWindow: 1050000;
|
|
26
|
+
};
|
|
27
|
+
readonly GPT_5_6_TERRA: {
|
|
28
|
+
readonly id: "gpt-5.6-terra";
|
|
29
|
+
readonly inputModalities: readonly ["text", "image"];
|
|
30
|
+
readonly provider: "openai";
|
|
31
|
+
readonly spec: "responses";
|
|
32
|
+
readonly label: "GPT-5.6 Terra";
|
|
33
|
+
readonly name: "GPT-5.6 Terra";
|
|
34
|
+
readonly description: "balances intelligence and cost";
|
|
35
|
+
readonly reasoning: true;
|
|
36
|
+
readonly reasoningEfforts: readonly OpenAIReasoningEffort[];
|
|
37
|
+
readonly contextWindow: 1050000;
|
|
38
|
+
};
|
|
39
|
+
readonly GPT_5_6_LUNA: {
|
|
40
|
+
readonly id: "gpt-5.6-luna";
|
|
41
|
+
readonly inputModalities: readonly ["text", "image"];
|
|
42
|
+
readonly provider: "openai";
|
|
43
|
+
readonly spec: "responses";
|
|
44
|
+
readonly label: "GPT-5.6 Luna";
|
|
45
|
+
readonly name: "GPT-5.6 Luna";
|
|
46
|
+
readonly description: "optimized for cost-sensitive workloads";
|
|
47
|
+
readonly reasoning: true;
|
|
48
|
+
readonly reasoningEfforts: readonly OpenAIReasoningEffort[];
|
|
49
|
+
readonly contextWindow: 1050000;
|
|
50
|
+
};
|
|
51
|
+
readonly GPT_5_5: {
|
|
52
|
+
readonly id: "gpt-5.5";
|
|
53
|
+
readonly inputModalities: readonly ["text", "image"];
|
|
54
|
+
readonly provider: "openai";
|
|
55
|
+
readonly spec: "responses";
|
|
56
|
+
readonly label: "GPT-5.5";
|
|
57
|
+
readonly name: "GPT-5.5";
|
|
58
|
+
readonly description: "latest frontier model for general complex work";
|
|
59
|
+
readonly reasoning: true;
|
|
60
|
+
readonly reasoningEfforts: readonly OpenAIReasoningEffort[];
|
|
61
|
+
readonly contextWindow: 400000;
|
|
62
|
+
};
|
|
63
|
+
readonly GPT_5_4: {
|
|
64
|
+
readonly id: "gpt-5.4";
|
|
65
|
+
readonly inputModalities: readonly ["text", "image"];
|
|
66
|
+
readonly provider: "openai";
|
|
67
|
+
readonly spec: "responses";
|
|
68
|
+
readonly label: "GPT-5.4";
|
|
69
|
+
readonly name: "GPT-5.4";
|
|
70
|
+
readonly description: "frontier model for general complex work";
|
|
71
|
+
readonly reasoning: true;
|
|
72
|
+
readonly reasoningEfforts: readonly OpenAIReasoningEffort[];
|
|
73
|
+
readonly contextWindow: 400000;
|
|
74
|
+
};
|
|
75
|
+
readonly GPT_5_3_CODEX: {
|
|
76
|
+
readonly id: "gpt-5.3-codex";
|
|
77
|
+
readonly inputModalities: readonly ["text", "image"];
|
|
78
|
+
readonly provider: "openai";
|
|
79
|
+
readonly spec: "responses";
|
|
80
|
+
readonly label: "GPT-5.3 Codex";
|
|
81
|
+
readonly name: "GPT-5.3 Codex";
|
|
82
|
+
readonly description: "frontier coding model";
|
|
83
|
+
readonly reasoning: true;
|
|
84
|
+
readonly reasoningEfforts: readonly OpenAIReasoningEffort[];
|
|
85
|
+
readonly contextWindow: 400000;
|
|
86
|
+
};
|
|
87
|
+
readonly GPT_5_4_MINI: {
|
|
88
|
+
readonly id: "gpt-5.4-mini";
|
|
89
|
+
readonly inputModalities: readonly ["text", "image"];
|
|
90
|
+
readonly provider: "openai";
|
|
91
|
+
readonly spec: "responses";
|
|
92
|
+
readonly label: "GPT-5.4 Mini";
|
|
93
|
+
readonly name: "GPT-5.4 Mini";
|
|
94
|
+
readonly description: "fast, cost-effective model for everyday tasks";
|
|
95
|
+
readonly reasoning: true;
|
|
96
|
+
readonly reasoningEfforts: readonly OpenAIReasoningEffort[];
|
|
97
|
+
readonly contextWindow: 400000;
|
|
98
|
+
};
|
|
99
|
+
};
|
|
100
|
+
/** Canonical OpenAI model ids, in catalog order. */
|
|
101
|
+
declare const OPENAI_MODEL_IDS: readonly string[];
|
|
102
|
+
declare const OPENAI_SUPPORTED_MODEL_PROVIDERS: readonly string[];
|
|
103
|
+
/**
|
|
104
|
+
* Harness ModelSpec-shaped catalog (structural — validated on registration by the harness).
|
|
105
|
+
*/
|
|
106
|
+
declare const OPENAI_MODEL_SPECS: {
|
|
107
|
+
id: "gpt-5.3-codex" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.6-sol" | "gpt-5.6-terra" | "gpt-5.6-luna" | "gpt-5.5";
|
|
108
|
+
provider: "openai";
|
|
109
|
+
contextWindow: 1050000 | 400000 | undefined;
|
|
110
|
+
reasoningEfforts: readonly OpenAIReasoningEffort[];
|
|
111
|
+
inputModalities: readonly ["text", "image"];
|
|
112
|
+
}[];
|
|
113
|
+
|
|
114
|
+
export { OPENAI_MODEL_IDS, OPENAI_MODEL_OPTIONS, OPENAI_MODEL_SPECS, OPENAI_SUPPORTED_MODEL_PROVIDERS, type OpenAIModelOption, type OpenAIReasoningEffort };
|
package/dist/models.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import {
|
|
2
|
+
OPENAI_MODEL_IDS,
|
|
3
|
+
OPENAI_MODEL_OPTIONS,
|
|
4
|
+
OPENAI_MODEL_SPECS,
|
|
5
|
+
OPENAI_SUPPORTED_MODEL_PROVIDERS
|
|
6
|
+
} from "./chunk-J2XEWLRM.js";
|
|
7
|
+
export {
|
|
8
|
+
OPENAI_MODEL_IDS,
|
|
9
|
+
OPENAI_MODEL_OPTIONS,
|
|
10
|
+
OPENAI_MODEL_SPECS,
|
|
11
|
+
OPENAI_SUPPORTED_MODEL_PROVIDERS
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=models.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export { CODEX_API_ENDPOINT, CODEX_BASE_URL, CODEX_HEADERS, CODEX_UNSUPPORTED_TOOL_TYPES, buildCodexProviderOptions, extractCodexAccountId, stripCodexItemIds } from '../codex.js';
|
|
2
|
+
import '../constants-BPm3xKmw.js';
|
|
3
|
+
|
|
4
|
+
interface CodexLanguageModelParams {
|
|
5
|
+
readonly modelId: string;
|
|
6
|
+
/** The auth.openai.com access token (JWT) from the Codex OAuth flow. */
|
|
7
|
+
readonly oAuthToken: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Build the AI-SDK language model for a Codex (ChatGPT subscription) request. Returned as
|
|
11
|
+
* unknown; the api worker casts to its LanguageModelV3 like it always did.
|
|
12
|
+
*/
|
|
13
|
+
declare function getCodexLanguageModel(params: CodexLanguageModelParams): unknown;
|
|
14
|
+
interface OpenAIApiKeyLanguageModelParams {
|
|
15
|
+
readonly modelId: string;
|
|
16
|
+
readonly apiKey?: string;
|
|
17
|
+
/** 'responses' | 'chatComplete' — the catalog's spec kind for this model. */
|
|
18
|
+
readonly spec: 'responses' | 'chatComplete';
|
|
19
|
+
/**
|
|
20
|
+
* Optional fetch override (the api worker wraps global fetch to capture OpenAI's
|
|
21
|
+
* cache_write_tokens at the wire — @ai-sdk/openai strips the field during zod parsing).
|
|
22
|
+
*/
|
|
23
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
24
|
+
}
|
|
25
|
+
/** Plain OPENAI_API_KEY path (api.openai.com), spec-aware. */
|
|
26
|
+
declare function getOpenAIApiKeyLanguageModel(params: OpenAIApiKeyLanguageModelParams): unknown;
|
|
27
|
+
|
|
28
|
+
export { type CodexLanguageModelParams, type OpenAIApiKeyLanguageModelParams, getCodexLanguageModel, getOpenAIApiKeyLanguageModel };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getCodexLanguageModel,
|
|
3
|
+
getOpenAIApiKeyLanguageModel
|
|
4
|
+
} from "../chunk-NSTLHK7M.js";
|
|
5
|
+
import {
|
|
6
|
+
CODEX_API_ENDPOINT,
|
|
7
|
+
CODEX_BASE_URL,
|
|
8
|
+
CODEX_HEADERS,
|
|
9
|
+
CODEX_UNSUPPORTED_TOOL_TYPES,
|
|
10
|
+
buildCodexProviderOptions,
|
|
11
|
+
extractCodexAccountId,
|
|
12
|
+
stripCodexItemIds
|
|
13
|
+
} from "../chunk-34MJFIMS.js";
|
|
14
|
+
export {
|
|
15
|
+
CODEX_API_ENDPOINT,
|
|
16
|
+
CODEX_BASE_URL,
|
|
17
|
+
CODEX_HEADERS,
|
|
18
|
+
CODEX_UNSUPPORTED_TOOL_TYPES,
|
|
19
|
+
buildCodexProviderOptions,
|
|
20
|
+
extractCodexAccountId,
|
|
21
|
+
getCodexLanguageModel,
|
|
22
|
+
getOpenAIApiKeyLanguageModel,
|
|
23
|
+
stripCodexItemIds
|
|
24
|
+
};
|
|
25
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@byokkit/cmd-provider-openai",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "External provider-auth plugin for Command Code: OpenAI (Codex / ChatGPT) loopback OAuth as a ProviderModule.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"import": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts"
|
|
10
|
+
},
|
|
11
|
+
"./models": {
|
|
12
|
+
"import": "./dist/models.js",
|
|
13
|
+
"types": "./dist/models.d.ts"
|
|
14
|
+
},
|
|
15
|
+
"./server": {
|
|
16
|
+
"import": "./dist/server/index.js",
|
|
17
|
+
"types": "./dist/server/index.d.ts"
|
|
18
|
+
},
|
|
19
|
+
"./codex": {
|
|
20
|
+
"import": "./dist/codex.js",
|
|
21
|
+
"types": "./dist/codex.d.ts"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"main": "./dist/index.js",
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"files": [
|
|
27
|
+
"dist",
|
|
28
|
+
"README.md"
|
|
29
|
+
],
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsup && node ../../scripts/fix-provider-dts.mjs dist",
|
|
35
|
+
"dev": "tsup --watch",
|
|
36
|
+
"prepublishOnly": "pnpm build",
|
|
37
|
+
"typecheck": "tsc --noEmit",
|
|
38
|
+
"test": "vitest run"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@ai-sdk/openai": "^3.0.41"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@commandcode/harness": "workspace:*",
|
|
45
|
+
"@types/node": "^24.2.0",
|
|
46
|
+
"tsup": "^8.5.0",
|
|
47
|
+
"typescript": "^5.9.2",
|
|
48
|
+
"vitest": "^4.1.6"
|
|
49
|
+
}
|
|
50
|
+
}
|