diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 39fff6bb..a5fd6aec 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -707,8 +707,9 @@ zcode ## Official MCP Availability -When the bundled runtime has no official MCP trusted-origin registry, official -HTTP MCP services are reported as disabled with an `official_auth_unavailable` -diagnostic. Other plugin components remain available. This does not disable -certificate, origin, or permission checks, and does not suppress services when -the runtime provides the required registry. No user configuration is rewritten. +Official HTTP MCP services that use ZCode's trusted-origin authentication +require the runtime host to provide its trusted-origin registry and auth-header +port. If those host capabilities are unavailable, the runtime fails that +service connection and reports that the official MCP trusted-origin registry is +unavailable. Other MCP services remain available. No user configuration is +rewritten, and certificate, origin, and permission checks remain enabled. diff --git a/scripts/check-runtime.ts b/scripts/check-runtime.ts index 61829bc9..1c32d7ef 100755 --- a/scripts/check-runtime.ts +++ b/scripts/check-runtime.ts @@ -15,7 +15,6 @@ import { runtimeTestEnv } from "./runtime-test-env.ts"; import { extractRuntimeCapabilities, hasRuntimeAppServerStandaloneAuth, - hasRuntimeBigmodelOAuth, hasRuntimeBrowserUrlOpening, hasRuntimeConfigurationDiagnostics, hasRuntimeCliSettingsFile, @@ -33,12 +32,10 @@ import { hasRuntimeStreamEofFinishGuard, hasRuntimeTrackedDetachedAgentLifecycle, patchRuntimeGoalFailurePause, - patchRuntimeHttpNoContent, patchRuntimeHeadlessLifecycle, patchRuntimeLoginModelDefaults, hasRuntimeNativePollingOAuth, patchRuntimeNetworkRetryClassification, - patchRuntimeOfficialMcpAvailability, patchRuntimeSqliteBusyTimeout, patchRuntimeSqliteWriteRecovery, patchRuntimeStreamEofFinishGuard, @@ -99,9 +96,7 @@ if (!metadataCapabilities throw new Error("The extracted runtime capability manifest is missing or stale; run `bun run sync` again."); } if (patchRuntimeLoginModelDefaults(runtimeSource) !== runtimeSource - || (patchEnabled("official-mcp-availability") && patchRuntimeOfficialMcpAvailability(runtimeSource) !== runtimeSource) || (patchEnabled("goal-failure-pause") && patchRuntimeGoalFailurePause(runtimeSource) !== runtimeSource) - || patchRuntimeHttpNoContent(runtimeSource) !== runtimeSource || !hasRuntimeHttpNoContentGuard(runtimeSource) || patchRuntimeHeadlessLifecycle(runtimeSource) !== runtimeSource || !hasRuntimeHeadlessLifecycle(runtimeSource) @@ -116,7 +111,6 @@ if (patchRuntimeLoginModelDefaults(runtimeSource) !== runtimeSource || !hasRuntimeStreamEofFinishGuard(runtimeSource) || (patchEnabled("cli-help-contract") && !hasRuntimeCliHelpContract(runtimeSource)) || !hasRuntimeAppServerStandaloneAuth(runtimeSource) - || !hasRuntimeBigmodelOAuth(runtimeSource) || !hasRuntimeBrowserUrlOpening(runtimeSource) || !hasRuntimeConfigurationDiagnostics(runtimeSource) || !hasRuntimeRecursiveWorkspacePaths(runtimeSource) @@ -165,8 +159,7 @@ if (patchRuntimeLoginModelDefaults(runtimeSource) !== runtimeSource || (patchEnabled("agent-auto-background") && !runtimeSource.includes("autoBackgroundMs:this.config.subagents?.autoBackgroundMs??1e3,outputRootDir:")) || (patchEnabled("detached-agent-lifecycle") - && !hasRuntimeTrackedDetachedAgentLifecycle(runtimeSource) - && runtimeSource.split("Detached background agent lifecycle failed").length < 3) + && !hasRuntimeTrackedDetachedAgentLifecycle(runtimeSource)) || !runtimeSource.includes('e?.waitForIdle===!0&&t.runtime?.getActiveForegroundExecutionId') || (patchEnabled("terminal-tool-projection") && !runtimeSource.includes('status:"idle",currentTurnId:void 0,activeToolCalls:[],totalTokenCount:')) diff --git a/scripts/runtime-bigmodel-oauth-patches.ts b/scripts/runtime-bigmodel-oauth-patches.ts deleted file mode 100644 index 64625a86..00000000 --- a/scripts/runtime-bigmodel-oauth-patches.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { parseExpressionAt, type FunctionExpression, type Node, type VariableDeclarator } from "acorn"; - -const identifier = "[A-Za-z_$][\\w$]*"; -const helper = 'require(require("node:path").join(__dirname,"cli-config.cjs"))'; - -function incompatible(detail: string): never { - throw new Error(`ZCode runtime is incompatible with BigModel OAuth (${detail}).`); -} - -function unique(values: T[], anchor: string): T { - if (values.length !== 1) incompatible(`${anchor} missing or ambiguous`); - return values[0]!; -} - -function escape(value: string): string { - return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); -} - -function symbol(runtime: string, label: string): string { - return unique([...runtime.matchAll(new RegExp(`${identifier}\\((${identifier}),"${label}"\\)`, "gu"))], label)[1]!; -} - -function namedFunction(runtime: string, label: string): FunctionExpression { - const name = symbol(runtime, label); - const match = unique([...runtime.matchAll(new RegExp(`(?:async )?function ${escape(name)}\\(`, "gu"))], label); - const fn = parseExpressionAt(runtime, match.index!, { ecmaVersion: "latest" }); - if (fn.type !== "FunctionExpression" || fn.id?.name !== name) incompatible(`${label} function changed`); - return fn; -} - -function walk(node: Node, visit: (node: Node) => void): void { - visit(node); - for (const value of Object.values(node)) { - for (const child of Array.isArray(value) ? value : [value]) { - if (child && typeof child === "object" && typeof child.type === "string") walk(child, visit); - } - } -} - -function inspect(runtime: string) { - const login = namedFunction(runtime, "loginBigmodelCodingPlan"); - const param = login.params[0]; - if (param?.type !== "AssignmentPattern" || param.left.type !== "Identifier") incompatible("login options changed"); - const input = param.left.name; - const body = runtime.slice(login.body.start + 1, login.body.end - 1); - const factory = symbol(runtime, "createBigmodelOAuthClient"); - const [, client, http] = unique([...body.matchAll(new RegExp( - `(${identifier})=${escape(factory)}\\(\\{httpClient:(${identifier})\\}\\)`, "gu" - ))], "OAuth client call"); - const [, callback, state] = unique([...body.matchAll(new RegExp( - `${escape(client!)}\\.buildAuthorizeUrl\\(\\{redirectUri:(${identifier})\\.callbackUrl,state:(${identifier})\\}\\)`, "gu" - ))], "authorization callback"); - const persistence = unique([...body.matchAll(new RegExp( - `\\[(${identifier})\\.bigmodelAccessToken\\]:(${identifier})\\.accessToken,`, "gu" - ))], "credential persistence"); - const [, keys, tokens] = persistence; - const bindings: VariableDeclarator[] = []; - walk(login.body, node => { - if (node.type === "VariableDeclarator") { - const binding = node as VariableDeclarator; - if (binding.id.type === "Identifier" && binding.id.name === tokens) bindings.push(binding); - } - }); - const binding = unique(bindings, "token binding"); - if (binding.init?.type !== "AwaitExpression" || binding.init.argument.type !== "CallExpression") incompatible("token exchange changed"); - const call = binding.init.argument; - const args = call.arguments; - if (args.length !== 1 || args[0]?.type !== "ObjectExpression") incompatible("token exchange options changed"); - const code = unique(args[0].properties.filter(node => node.type === "Property" - && node.key.type === "Identifier" && node.key.name === "code"), "authorization code"); - if (code.type !== "Property") incompatible("authorization code changed"); - const codeSource = runtime.slice(code.value.start, code.value.end); - const original = `${client}.exchangeCode({code:${codeSource}})`; - const exchange = `${helper}.exchangeBigmodelOAuthCode({code:${codeSource},redirectUri:${callback}.callbackUrl,state:${state},httpClient:${http},abortSignal:${input}.abortSignal,trace:${input}.trace})`; - const actual = runtime.slice(call.start, call.end); - if (actual !== original && actual !== exchange) incompatible("token exchange call changed"); - const jwt = `[${keys}.zcodeJwtToken]:${tokens}.zcodeJwtToken,`; - const persistenceEnd = login.body.start + 1 + persistence.index! + persistence[0].length; - const stored = runtime.slice(persistenceEnd, persistenceEnd + jwt.length) === jwt; - if ((actual === exchange) !== stored) incompatible("partial OAuth patch"); - return { call, exchange, persistenceEnd, jwt, patched: stored }; -} - -export function hasRuntimeNativePollingOAuth(runtime: string): boolean { - try { - const login = namedFunction(runtime, "loginZCodeCli"); - const wrapper = namedFunction(runtime, "loginBigmodelCodingPlan"); - const polling = symbol(runtime, "pollUntilReady"); - const body = runtime.slice(login.body.start + 1, login.body.end - 1); - const delegation = runtime.slice(wrapper.body.start + 1, wrapper.body.end - 1); - return new RegExp(`${escape(login.id!.name)}\\(\\{\\.\\.\\.${identifier},providerId:"bigmodel"\\}\\)`, "u").test(delegation) - && body.includes(`${polling}({`) - && body.includes('authSource:"oauth"') - && /\[([A-Za-z_$][\w$]*)\.zcodeJwtToken\]:([A-Za-z_$][\w$]*)\.token,\[\1\.bigmodelAccessToken\]:\2\.accessToken,/u.test(body); - } catch { - return false; - } -} - -export function hasRuntimeBigmodelOAuth(runtime: string): boolean { - if (hasRuntimeNativePollingOAuth(runtime)) return true; - try { return inspect(runtime).patched; } catch { return false; } -} - -/** Exchange through the official Desktop broker and persist both provider and ZCode tokens. */ -export function patchRuntimeBigmodelOAuth(runtime: string): string { - if (hasRuntimeNativePollingOAuth(runtime)) return runtime; - const { call, exchange, persistenceEnd, jwt, patched } = inspect(runtime); - if (patched) return runtime; - const edits = [ - { start: call.start, end: call.end, value: exchange }, - { start: persistenceEnd, end: persistenceEnd, value: jwt } - ]; - for (const edit of edits.sort((a, b) => b.start - a.start)) { - runtime = runtime.slice(0, edit.start) + edit.value + runtime.slice(edit.end); - } - return runtime; -} diff --git a/scripts/runtime-oauth-polling.ts b/scripts/runtime-oauth-polling.ts new file mode 100644 index 00000000..7117eeec --- /dev/null +++ b/scripts/runtime-oauth-polling.ts @@ -0,0 +1,49 @@ +import { parseExpressionAt, type FunctionExpression } from "acorn"; + +const identifier = "[A-Za-z_$][\\w$]*"; + +function unique(values: T[], anchor: string): T { + if (values.length !== 1) throw new Error(`ZCode runtime is missing native OAuth polling support (${anchor}).`); + return values[0]!; +} + +function symbol(runtime: string, label: string): string { + return unique( + [...runtime.matchAll(new RegExp(`${identifier}\\((${identifier}),"${label}"\\)`, "gu"))], + label + )[1]!; +} + +function escape(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); +} + +function namedFunction(runtime: string, label: string): FunctionExpression { + const name = symbol(runtime, label); + const match = unique( + [...runtime.matchAll(new RegExp(`(?:async )?function ${name}\\(`, "gu"))], + `${label} function` + ); + const fn = parseExpressionAt(runtime, match.index!, { ecmaVersion: "latest" }); + if (fn.type !== "FunctionExpression" || fn.id?.name !== name) { + throw new Error(`ZCode runtime changed the native ${label} function.`); + } + return fn; +} + +/** Verify the Z.AI and BigModel OAuth polling flow implemented by the pinned runtime. */ +export function hasRuntimeNativePollingOAuth(runtime: string): boolean { + try { + const login = namedFunction(runtime, "loginZCodeCli"); + const wrapper = namedFunction(runtime, "loginBigmodelCodingPlan"); + const polling = symbol(runtime, "pollUntilReady"); + const body = runtime.slice(login.body.start + 1, login.body.end - 1); + const delegation = runtime.slice(wrapper.body.start + 1, wrapper.body.end - 1); + return new RegExp(`${escape(login.id!.name)}\\(\\{\\.\\.\.${identifier},providerId:"bigmodel"\\}\\)`, "u").test(delegation) + && body.includes(`${polling}({`) + && body.includes('authSource:"oauth"') + && /\[([A-Za-z_$][\w$]*)\.zcodeJwtToken\]:([A-Za-z_$][\w$]*)\.token,\[\1\.bigmodelAccessToken\]:\2\.accessToken,/u.test(body); + } catch { + return false; + } +} diff --git a/scripts/sync-runtime.ts b/scripts/sync-runtime.ts index e2443391..10e95555 100755 --- a/scripts/sync-runtime.ts +++ b/scripts/sync-runtime.ts @@ -20,13 +20,12 @@ import { hasRuntimeKeychainRecovery, patchRuntimeKeychainRecovery } from "./runt export { hasRuntimeKeychainRecovery, patchRuntimeKeychainRecovery } from "./runtime-keychain-patches.ts"; import { hasRuntimeSessionLifecycle, patchRuntimeSessionLifecycle } from "./runtime-session-lifecycle-patches.ts"; export { hasRuntimeSessionLifecycle, patchRuntimeSessionLifecycle } from "./runtime-session-lifecycle-patches.ts"; -import { hasRuntimeBigmodelOAuth, hasRuntimeNativePollingOAuth, patchRuntimeBigmodelOAuth } from "./runtime-bigmodel-oauth-patches.ts"; +import { hasRuntimeNativePollingOAuth } from "./runtime-oauth-polling.ts"; import { hasRuntimeSharedOAuth, patchRuntimeSharedOAuth } from "./runtime-shared-oauth-patches.ts"; export { hasRuntimeSharedOAuth, patchRuntimeSharedOAuth } from "./runtime-shared-oauth-patches.ts"; import { hasRuntimeStartPlan, patchRuntimeStartPlan } from "./runtime-start-plan-patches.ts"; export { hasRuntimeStartPlan, patchRuntimeStartPlan } from "./runtime-start-plan-patches.ts"; -export { hasRuntimeBigmodelOAuth, patchRuntimeBigmodelOAuth } from "./runtime-bigmodel-oauth-patches.ts"; -export { hasRuntimeNativePollingOAuth } from "./runtime-bigmodel-oauth-patches.ts"; +export { hasRuntimeNativePollingOAuth } from "./runtime-oauth-polling.ts"; import { hasRuntimeBrowserUrlOpening, patchRuntimeBrowserUrlOpening } from "./runtime-browser-patches.ts"; export { hasRuntimeBrowserUrlOpening, patchRuntimeBrowserUrlOpening } from "./runtime-browser-patches.ts"; import { hasRuntimeAppServerStandaloneAuth, patchRuntimeAppServerStandaloneAuth } from "./runtime-app-server-patches.ts"; @@ -442,26 +441,6 @@ export function patchRuntimeCliHelpContract(runtime: string): string { return patched; } -/** Report missing official authentication support without weakening origin checks. */ -export function patchRuntimeOfficialMcpAvailability(runtime: string): string { - const marker = "zcode_cli_official_mcp_unavailable"; - if (runtime.includes(marker)) return runtime; - const anchor = /await this\.closeRecord\(([A-Za-z_$][\w$]*)\),([A-Za-z_$][\w$]*)\.enabled===!1\)\{let ([A-Za-z_$][\w$]*)=this\.createStatus\(\2,"disabled"\);/gu; - let matches = 0; - const patched = runtime.replace(anchor, (_, name: string, config: string, status: string) => { - matches += 1; - const unavailable = `${config}.type==="http"&&${config}.auth?.type==="zcode_official"` - + `&&${config}.auth.provider==="jwt_token"&&${config}.official!==void 0` - + "&&!this.officialMcpAuth?.trustedOrigins"; - return `await this.closeRecord(${name}),${config}.enabled===!1||(${unavailable})){` - + `let ${status}=this.createStatus(${config},"disabled",${config}.enabled===!1?void 0:` - + `{error:"Official MCP authentication is unavailable in this runtime (${marker}).",` - + 'failureKind:"official_auth_unavailable"});'; - }); - if (matches !== 1) throw new Error("ZCode runtime is incompatible with the official MCP availability patch."); - return patched; -} - /** Keep short Agent calls inline, but detach long-running agents from the foreground turn. */ export function patchRuntimeAgentAutoBackground(runtime: string): string { const marker = "autoBackgroundMs:this.config.subagents?.autoBackgroundMs??1e3,outputRootDir:"; @@ -482,22 +461,6 @@ export function hasRuntimeTrackedDetachedAgentLifecycle(runtime: string): boolea return detached && tracker; } -/** Keep a detached Agent lifecycle failure from terminating the entire CLI process. */ -export function patchRuntimeDetachedAgentLifecycle(runtime: string): string { - const marker = 'Detached background agent lifecycle failed'; - if (hasRuntimeTrackedDetachedAgentLifecycle(runtime)) return runtime; - const detachedRunnerPattern = /(onSessionStartFailed:([A-Za-z_$][\w$]*)\.reject\},[A-Za-z_$][\w$]*\.dispose)\);try\{await \2\.promise\}/gu; - const patched = runtime.replace( - detachedRunnerPattern, - '$1).catch(e=>{console.error("Detached background agent lifecycle failed",e??"unknown rejection")});try{await $2.promise}' - ); - if (patched !== runtime) return patched; - if (!runtime.includes(marker)) { - throw new Error("ZCode runtime is incompatible with the detached Agent lifecycle patch."); - } - return runtime; -} - /** Clear tool projection entries when their owning turn reaches a terminal state. */ export function patchRuntimeTerminalToolProjection(runtime: string): string { const completedMarker = 'status:"idle",currentTurnId:void 0,activeToolCalls:[],totalTokenCount:'; @@ -1222,19 +1185,6 @@ export function hasRuntimeHttpNoContentGuard(runtime: string): boolean { && runtime.includes('"readIncomingResponse"') && runtime.includes('"toWebResponse"'); } -export function patchRuntimeHttpNoContent(runtime: string): string { - const responsePattern = /new Response\(([A-Za-z_$][\w$]*)\.Readable\.toWeb\(([A-Za-z_$][\w$]*)\),\{headers:([A-Za-z_$][\w$]*),status:\2\.statusCode\?\?502,statusText:\2\.statusMessage\}\)/gu; - let changed = false; - const patched = runtime.replace( - responsePattern, - (_match, readableNamespace: string, response: string, headers: string) => { - changed = true; - return `new Response(${response}.statusCode===204||${response}.statusCode===205||${response}.statusCode===304?void 0:${readableNamespace}.Readable.toWeb(${response}),{headers:${headers},status:${response}.statusCode??502,statusText:${response}.statusMessage})`; - } - ); - return changed ? patched : runtime; -} - function escapeRegExpName(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); } @@ -1614,71 +1564,6 @@ export function patchRuntimeCliCredentials(runtime: string): string { return runtime.slice(0, insertion) + override + runtime.slice(insertion); } -export function patchRuntimeZaiDesktopOAuth(runtime: string): string { - if (hasRuntimeNativePollingOAuth(runtime)) return runtime; - if (runtime.includes('ZCODE_CLI_OAUTH_CALLBACK_STDIN==="1"')) return runtime; - - const credentialMarker = ".saveZaiLoginCredentials({accessToken:"; - const markerIndex = runtime.indexOf(credentialMarker); - if (markerIndex < 0) { - throw new Error("ZCode runtime is incompatible with the Desktop OAuth patch (credential anchor missing)."); - } - const functionStart = runtime.lastIndexOf("async function ", markerIndex); - const nextFunction = runtime.indexOf("async function ", markerIndex + credentialMarker.length); - if (functionStart < 0 || nextFunction < 0) { - throw new Error("ZCode runtime is incompatible with the Desktop OAuth patch (function anchor missing)."); - } - const originalFunction = runtime.slice(functionStart, nextFunction); - const nativePolling = /[A-Za-z_$][\w$]*\([A-Za-z_$][\w$]*,"loginZCodeCli"\)/u.test(runtime) - && originalFunction.includes('authSource:"oauth"'); - const nativeSymbol = (label: string) => nativePolling - ? new RegExp(`[A-Za-z_$][\\w$]*\\(([A-Za-z_$][\\w$]*),"${label}"\\)`, "u").exec(runtime)?.[1] - : undefined; - const prefix = /^async function ([A-Za-z_$][\w$]*)\(e=\{\}\)\{/u.exec(originalFunction); - const abortHelper = nativeSymbol("throwIfAborted") ?? /;([A-Za-z_$][\w$]*)\(e\.abortSignal\);let/u.exec(originalFunction)?.[1]; - const credentialStore = /e\.credentialStore\?\?([A-Za-z_$][\w$]*)\(\{env:[A-Za-z_$][\w$]*\}\)/u.exec(originalFunction)?.[1]; - const loginError = /new ([A-Za-z_$][\w$]*)\("credential_write_failed"/u.exec(originalFunction)?.[1]; - const apiKeyResolverMatch = /await ([A-Za-z_$][\w$]*)\(\{accessToken:[^,]+,env:[^,]+,httpClient:e\.httpClient,family:"zai"/u.exec(originalFunction); - const apiKeyResolver = nativeSymbol("resolveCodingPlanMaterial") ?? apiKeyResolverMatch?.[1]; - const configWriter = (nativePolling - ? /await ([A-Za-z_$][\w$]*)\(\{accountIdentity:[^,]+,authSource:"oauth",credentialStore:[^,]+,env:[^,]+,personalProviderConfigPath:e\.personalProviderConfigPath,providerId:[^}]+\}\)/u - : /await ([A-Za-z_$][\w$]*)\(\{accountIdentity:[^,]+\.user\.user_id,apiKey:[^,]+,credentialStore:[^,]+,env:[^,]+,personalProviderConfigPath:e\.personalProviderConfigPath,providerId:"zai"\}\)/u).exec(originalFunction)?.[1]; - const httpClientFactory = nativeSymbol("createDefaultHttpClient") ?? /e\.httpClient\?\?([A-Za-z_$][\w$]*)\([A-Za-z_$][\w$]*\),[A-Za-z_$][\w$]*=e\.state\?\?/u.exec(runtime)?.[1]; - if (!prefix || !abortHelper || !credentialStore || !loginError - || !apiKeyResolver || !configWriter || !httpClientFactory) { - throw new Error("ZCode runtime is incompatible with the Desktop OAuth patch (dependency anchor missing)."); - } - - const branch = [ - `if((e.env??process.env).ZCODE_CLI_OAUTH_CALLBACK_STDIN==="1"${nativePolling ? '&&(e.providerId??"zai")==="zai"' : ""}){`, - "let $zEnv=e.env??process.env;", - `${abortHelper}(e.abortSignal);`, - `let $zStore=e.credentialStore??${credentialStore}({env:$zEnv}),$zHttp=e.httpClient??${httpClientFactory}($zEnv),$zPayload;`, - `try{$zPayload=JSON.parse(require("node:fs").readFileSync(0,"utf8"))}catch($zError){throw new ${loginError}("invalid_callback","Unable to read the Z.AI OAuth callback.",{cause:$zError})}`, - `if(!$zPayload||typeof $zPayload.callbackUrl!=="string"||typeof $zPayload.state!=="string")throw new ${loginError}("invalid_callback","The Z.AI OAuth callback payload is invalid.");`, - "let $zUrl;", - `try{$zUrl=new URL($zPayload.callbackUrl)}catch($zError){throw new ${loginError}("invalid_callback","The Z.AI OAuth callback URL is invalid.",{cause:$zError})}`, - `if($zUrl.protocol!=="zcode:"||$zUrl.hostname!=="zai-auth"||$zUrl.pathname.replace(/\\/+$/u,"")!=="/callback")throw new ${loginError}("invalid_callback","The Z.AI OAuth callback target is invalid.");`, - "let $zCode=$zUrl.searchParams.get(\"code\")??$zUrl.searchParams.get(\"authCode\"),$zState=$zUrl.searchParams.get(\"state\");", - `if(!$zCode||!$zState||$zState!==$zPayload.state)throw new ${loginError}("invalid_callback","The Z.AI OAuth callback state is invalid or expired.");`, - "let $zResponse=await $zHttp.request({maxResponseBytes:65536,body:new TextEncoder().encode(JSON.stringify({provider:\"zai\",code:$zCode,redirect_uri:\"zcode://zai-auth/callback\",state:$zState})),headers:{\"Content-Type\":\"application/json\"},method:\"POST\",trace:e.trace,url:\"https://zcode.z.ai/api/v1/oauth/token\"},e.abortSignal),$zText=new TextDecoder().decode($zResponse.body),$zEnvelope;", - `try{$zEnvelope=JSON.parse($zText)}catch($zError){throw new ${loginError}("token_exchange_failed",$zResponse.status<200||$zResponse.status>=300?"OAuth HTTP error "+$zResponse.status+" (empty or non-JSON response)":"OAuth response is not valid JSON",{cause:$zError})}`, - "let $zMessage=typeof $zEnvelope?.msg===\"string\"&&$zEnvelope.msg.trim()?$zEnvelope.msg.trim():void 0;", - `if($zResponse.status<200||$zResponse.status>=300)throw new ${loginError}("token_exchange_failed",$zMessage??"OAuth HTTP error "+$zResponse.status);`, - `if($zEnvelope?.code!==0)throw new ${loginError}("token_exchange_failed",$zMessage??"Z.AI token exchange failed.");`, - "let $zData=$zEnvelope.data,$zAccessToken=$zData?.zai?.access_token,$zJwtToken=$zData?.token,$zUser=$zData?.user;", - `if(typeof $zAccessToken!=="string"||typeof $zJwtToken!=="string"||!$zUser||typeof $zUser!=="object")throw new ${loginError}("token_exchange_failed","Z.AI token response is missing credentials or user data.");`, - `${abortHelper}(e.abortSignal);`, - `try{await $zStore.saveZaiLoginCredentials({accessToken:$zAccessToken,jwtToken:$zJwtToken,user:$zUser})}catch($zError){throw new ${loginError}("credential_write_failed","Login succeeded but writing credentials failed.",{cause:$zError})}`, - `let $zApiKey=await ${apiKeyResolver}({accessToken:$zAccessToken,env:$zEnv,httpClient:$zHttp,family:"zai",resolver:e.apiKeyResolver${nativePolling ? ",signal:e.abortSignal" : ""}}),$zConfig;`, - `try{$zConfig=await ${configWriter}({accountIdentity:$zUser.user_id,${nativePolling ? 'authSource:"oauth"' : "apiKey:$zApiKey"},credentialStore:$zStore,env:$zEnv,personalProviderConfigPath:e.personalProviderConfigPath,providerId:"zai"})}catch($zError){throw new ${loginError}("config_update_failed","Login succeeded but updating ZCode config failed.",{cause:$zError})}`, - 'return{configPath:$zConfig.path,credentialsPath:$zStore.filePath,model:$zConfig.mainModel,providerId:"zai",user:$zUser}', - "}" - ].join(""); - const insertionPoint = functionStart + prefix[0].length; - return `${runtime.slice(0, insertionPoint)}${branch}${runtime.slice(insertionPoint)}`; -} - const bigmodelSessionReuseMarker = "ZCODE_CLI_BIGMODEL_REUSE_SESSION"; /** @@ -1914,11 +1799,6 @@ export const runtimePatchPlan: readonly RuntimePatchDefinition[] = [ id: "session-lifecycle", requirement: "required", apply: patchRuntimeSessionLifecycle, verify: hasRuntimeSessionLifecycle }, - { - id: "official-mcp-availability", - requirement: "optional", - apply: patchRuntimeOfficialMcpAvailability - }, { id: "resolved-context-window", requirement: "required", @@ -1968,9 +1848,8 @@ export const runtimePatchPlan: readonly RuntimePatchDefinition[] = [ { id: "detached-agent-lifecycle", requirement: "optional", - apply: patchRuntimeDetachedAgentLifecycle, - verify: (runtime) => runtime.includes("Detached background agent lifecycle failed") - || hasRuntimeTrackedDetachedAgentLifecycle(runtime) + apply: (runtime) => runtime, + verify: hasRuntimeTrackedDetachedAgentLifecycle }, { id: "agent-auto-background", @@ -1983,7 +1862,7 @@ export const runtimePatchPlan: readonly RuntimePatchDefinition[] = [ { id: "http-no-content", requirement: "required", - apply: patchRuntimeHttpNoContent, + apply: (runtime) => runtime, verify: hasRuntimeHttpNoContentGuard }, { @@ -2038,10 +1917,10 @@ export const runtimePatchPlan: readonly RuntimePatchDefinition[] = [ && restoredPromptModelSwitch.test(runtime) }, { - id: "bigmodel-oauth", + id: "native-oauth-polling", requirement: "required", - apply: patchRuntimeBigmodelOAuth, - verify: hasRuntimeBigmodelOAuth + apply: (runtime) => runtime, + verify: hasRuntimeNativePollingOAuth }, { id: "browser-url-opening", @@ -2049,13 +1928,6 @@ export const runtimePatchPlan: readonly RuntimePatchDefinition[] = [ apply: patchRuntimeBrowserUrlOpening, verify: hasRuntimeBrowserUrlOpening }, - { - id: "desktop-oauth", - requirement: "required", - apply: patchRuntimeZaiDesktopOAuth, - verify: (runtime) => hasRuntimeNativePollingOAuth(runtime) - || runtime.includes('ZCODE_CLI_OAUTH_CALLBACK_STDIN==="1"') - }, { id: "bigmodel-session-reuse", requirement: "optional", diff --git a/test/runtime/runtime-4.0-compat.test.ts b/test/runtime/runtime-4.0-compat.test.ts index 237cf751..a5ad2102 100644 --- a/test/runtime/runtime-4.0-compat.test.ts +++ b/test/runtime/runtime-4.0-compat.test.ts @@ -1,7 +1,38 @@ import { expect, test } from "bun:test"; import { readFile } from "node:fs/promises"; import { parse } from "acorn"; -import { patchRuntimeBigmodelSessionReuse, patchRuntimePromptModel } from "../../scripts/sync-runtime.ts"; +import { + applyRuntimePatchPlan, + hasRuntimeHttpNoContentGuard, + hasRuntimeNativePollingOAuth, + hasRuntimeTrackedDetachedAgentLifecycle, + patchRuntimeBigmodelSessionReuse, + patchRuntimePromptModel, + runtimePatchPlan +} from "../../scripts/sync-runtime.ts"; + +test("4.0 native runtime features are verified without applying legacy compatibility rewrites", async () => { + const runtime = await readFile(new URL("../../vendor/zcode.cjs", import.meta.url), "utf8"); + const nativePatches = new Map(runtimePatchPlan.map(patch => [patch.id, patch])); + expect(nativePatches.has("official-mcp-availability")).toBe(false); + expect(runtime).toContain("official MCP trusted origin registry is not available in this runtime"); + + for (const [id, check] of [ + ["detached-agent-lifecycle", hasRuntimeTrackedDetachedAgentLifecycle], + ["http-no-content", hasRuntimeHttpNoContentGuard], + ["native-oauth-polling", hasRuntimeNativePollingOAuth] + ] as const) { + const patch = nativePatches.get(id); + expect(patch, `missing native runtime check ${id}`).toBeDefined(); + expect(patch!.apply(runtime)).toBe(runtime); + expect(patch!.verify?.(runtime)).toBe(true); + } + + for (const id of ["http-no-content", "native-oauth-polling"]) { + const patch = nativePatches.get(id)!; + expect(() => applyRuntimePatchPlan("", [patch])).toThrow(`Required runtime patch ${id} failed`); + } +}); test("4.0 TUI prompt overrides apply before the current app wrapper returns", async () => { const runtime = await readFile(new URL("../../vendor/zcode.cjs", import.meta.url), "utf8");