diff --git a/apps/server/src/orchestration-v2/Adapters/ZcodeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ZcodeAdapterV2.test.ts index 26ccb55a805ed..47a0195506d96 100644 --- a/apps/server/src/orchestration-v2/Adapters/ZcodeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ZcodeAdapterV2.test.ts @@ -30,7 +30,6 @@ import { ZCODE_PROVIDER, makeZcodeAdapterV2 } from "@t3tools/provider-zcode/test import { type FakeZcodeScenario, ZcodeAdapterTestLayer, - fakeZcodeRequestAuth, makeFakeZcodeConnection, makeZcodeAdapterOptions, zcodeDriverKind, @@ -303,7 +302,7 @@ describe("ZcodeAdapterV2 (frame-driven)", () => { // thread.runtime-mode.set detaches the session; the next turn reopens and resumes it. const resumedScenario = yield* makeFakeZcodeConnection(); const resumed = yield* openRuntime(resumedScenario, runtimePolicy); - yield* resumed.ensureThread({ + const resumedThread = yield* resumed.ensureThread({ threadId: THREAD_ID, modelSelection: MODEL_SELECTION, runtimePolicy, @@ -315,6 +314,21 @@ describe("ZcodeAdapterV2 (frame-driven)", () => { sessionId: "sess_1", mode: "guarded", }); + + // A resumed session advertises its models only through session/subscribe; the next turn + // still needs the advertised reasoning level. + yield* resumed.startTurn( + yield* makeTurnInput( + resumedThread, + TURN_TEXT, + "account:zai-individual-coding-plan/GLM-5.3-Flash", + ), + ); + assert.deepEqual(requestFor(resumedScenario, "session/send")?.params["modelSelection"], { + providerId: "account:zai-individual-coding-plan", + modelId: "GLM-5.3-Flash", + options: { reasoningLevel: "max" }, + }); assert.deepEqual(resumedScenario.unexpectedMethods(), []); }).pipe(Effect.scoped, Effect.provide(ZcodeAdapterTestLayer)), ); @@ -451,52 +465,29 @@ describe("ZcodeAdapterV2 (frame-driven)", () => { }).pipe(Effect.scoped, Effect.provide(ZcodeAdapterTestLayer)), ); - it.effect( - "sends account-model turns with the advertised reasoning level and serves runtime headers", - () => - Effect.gen(function* () { - const harness = yield* makeHarness({ makeRequestAuth: fakeZcodeRequestAuth() }); - // "default" omits the model entirely; account slugs select per turn. - yield* harness.startTurn(TURN_TEXT, "account:zai-individual-coding-plan/GLM-5.3-Flash"); - const send = requestFor(harness.scenario, "session/send"); - assert.isDefined(send); - assert.deepEqual(send!.params["modelSelection"], { - providerId: "account:zai-individual-coding-plan", - modelId: "GLM-5.3-Flash", - options: { reasoningLevel: "max" }, - }); - - // Before an account-model request the CLI asks the host for project runtime headers; - // the injected request auth's response must reach the wire verbatim. - const broker = zcodeServerRequest("interaction/requestProviderRuntimeHeaders", { - sessionId: harness.scenario.createdSessionId(), - modelSelection: { - providerId: "account:zai-individual-coding-plan", - modelId: "GLM-5.3-Flash", - options: { reasoningLevel: "max" }, - }, - }); - yield* harness.scenario.offerEvent(broker); - // The first two responds are the create-time runtime preferences and MCP auth headers. - yield* harness.scenario.takeRespond; - yield* harness.scenario.takeRespond; - const answered = yield* harness.scenario.takeRespond; - assert.equal(answered.id, broker.id); - assert.deepEqual(answered.result, { - headersApplied: true, - requestAuth: { apiKey: "test", apiKeyId: "k", accountScope: "a" }, - }); + it.effect("sends account-model turns with the advertised reasoning level", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + // "default" omits the model entirely; account slugs select per turn. + yield* harness.startTurn(TURN_TEXT, "account:zai-individual-coding-plan/GLM-5.3-Flash"); + const send = requestFor(harness.scenario, "session/send"); + assert.isDefined(send); + assert.deepEqual(send!.params["modelSelection"], { + providerId: "account:zai-individual-coding-plan", + modelId: "GLM-5.3-Flash", + options: { reasoningLevel: "max" }, + }); - yield* harness.offerTurnEvent("turn.completed", { - response: "pong", - tokenCount: 3, - toolCallCount: 0, - duration: 60, - resultType: "success", - }); - yield* harness.takeEvent("turn.terminal", (event) => event.status === "completed"); - assert.deepEqual(harness.scenario.unexpectedMethods(), []); - }).pipe(Effect.scoped, Effect.provide(ZcodeAdapterTestLayer)), + yield* harness.offerTurnEvent("turn.completed", { + response: "pong", + tokenCount: 3, + toolCallCount: 0, + duration: 60, + resultType: "success", + }); + yield* harness.takeEvent("turn.terminal", (event) => event.status === "completed"); + assert.deepEqual(harness.scenario.unexpectedMethods(), []); + }).pipe(Effect.scoped, Effect.provide(ZcodeAdapterTestLayer)), ); it.effect("maps shell tool lifecycle into command execution items", () => diff --git a/apps/server/src/orchestration-v2/Adapters/ZcodeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ZcodeAdapterV2.testkit.ts index 611850c8f76c6..2f15ec56ac716 100644 --- a/apps/server/src/orchestration-v2/Adapters/ZcodeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/ZcodeAdapterV2.testkit.ts @@ -46,8 +46,6 @@ export interface FakeZcodeScenario { } const KNOWN_METHODS = new Set([ - "provider/updateAccountConfig", - "provider/refreshRegistry", "session/create", "session/read", "session/resume", @@ -119,7 +117,7 @@ function zcodeSessionCreateResult(sessionId: string, params: ZcodeRecord): Zcode }; } -/** Builds the fake `zcode app-server` NDJSON peer the adapter talks to. */ +/** Builds the fake ZCode connection peer the adapter talks to. */ export const makeFakeZcodeConnection = Effect.fnUntraced(function* (): Effect.fn.Return< FakeZcodeScenario, never, @@ -168,7 +166,14 @@ export const makeFakeZcodeConnection = Effect.fnUntraced(function* (): Effect.fn return zcodeSessionCreateResult(createdSessionId, params); } case "session/subscribe": - return { sessionId: createdSessionId, eventSeq: 1, events: [] }; + return { + sessionId: createdSessionId, + eventSeq: 1, + events: [], + snapshot: { + settings: zcodeSessionCreateResult(createdSessionId ?? "sess_1", params).settings, + }, + }; case "session/send": { yield* Queue.offer(events, { method: "state.updated", @@ -182,14 +187,6 @@ export const makeFakeZcodeConnection = Effect.fnUntraced(function* (): Effect.fn }); return { sessionId: createdSessionId, accepted: true, stateRevision: 1 }; } - case "provider/updateAccountConfig": - return { - receivedRevision: String(params["revision"] ?? ""), - providerCount: Object.keys((params["providers"] ?? {}) as ZcodeRecord).length, - status: "received", - }; - case "provider/refreshRegistry": - return { refreshed: true }; case "session/read": return zcodeSessionCreateResult(createdSessionId ?? "sess_unknown", params); case "session/stop": @@ -263,19 +260,6 @@ export const makeZcodeAdapterOptions = (): ZcodeAdapterV2Options => ({ environment: {}, }); -/** - * Request auth the adapter can drive without touching the local credential store or network: - * every runtime-headers request is answered with the fixed successful exchange. - */ -export const fakeZcodeRequestAuth = - (): NonNullable => () => ({ - answerRuntimeHeaders: () => - Effect.succeed({ - headersApplied: true, - requestAuth: { apiKey: "test", apiKeyId: "k", accountScope: "a" }, - }), - }); - /** The driver kind the package driver and the hand-built adapter options must agree on. */ export const zcodeDriverKind: typeof ZCODE_PROVIDER = ZCODE_PROVIDER; diff --git a/docs/user/providers-zcode.md b/docs/user/providers-zcode.md index f24de6f6567df..88472a201b422 100644 --- a/docs/user/providers-zcode.md +++ b/docs/user/providers-zcode.md @@ -1,7 +1,8 @@ # ZCode -T3 Code runs the ZCode CLI as an agent, using your own Z.AI account, skills, plugins, and MCP -configuration. +T3 Code attaches to the ZCode daemon (`zcode serve`) as an agent, using your own Z.AI account, +skills, plugins, and MCP configuration. T3 Code starts the daemon when it is not already running +and leaves it running when the session ends, so other ZCode clients on the machine keep working. ## Set Up ZCode @@ -16,11 +17,10 @@ with T3 Code; the server's own `zcode login` is what counts. ## Credentials -T3 Code never stores your Z.AI sign-in. The ZCode agent asks its host for credentials before every -account-model request, so the server stands in as that host: it reads the sign-in `zcode login` -already wrote on the same machine, exchanges it for a short-lived access token through the same -Z.AI endpoints the ZCode app uses, and holds that token in memory only. The store is never -written, so signing out or signing in again from a terminal applies on the next refresh. +T3 Code never stores or reads your Z.AI sign-in. The ZCode daemon owns the credential exchange: +it reads the sign-in `zcode login` wrote on the same machine and mints the short-lived account +tokens its turns need. T3 Code attaches to that daemon and never handles the tokens. Signing out +or signing in again from a terminal applies to the next turn. ## Models diff --git a/packages/provider-zcode/src/server/adapter.ts b/packages/provider-zcode/src/server/adapter.ts index 6dfb85848796a..45d038c5fb548 100644 --- a/packages/provider-zcode/src/server/adapter.ts +++ b/packages/provider-zcode/src/server/adapter.ts @@ -1,6 +1,4 @@ -import { AgentScope } from "@t3tools/shared/AgentScope"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import { causeErrorTag } from "@t3tools/shared/observability"; import * as Predicate from "effect/Predicate"; import { type OrchestrationV2ConversationMessage, @@ -32,6 +30,7 @@ import * as HttpClient from "effect/http/HttpClient"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; @@ -54,30 +53,21 @@ import { import { isServerRequest, - makeZcodeConnection, zcodeJsonStringify, zcodeRecordArray, zcodeRecordField, zcodeRecordNumber, zcodeRecordString, type ZcodeConnection, + type ZcodeProtocolError, + type ZcodeProtocolTimeoutError, type ZcodeRecord, } from "./zcodeProtocol.ts"; +import { zcodeModelSelectionFromSlug } from "./zcodeRuntime.ts"; import { - readZcodeAppVersion, - resolveZcodeCatalogFiles, - resolveZcodeLaunchCommand, - zcodeDataRoot, - zcodeModelSelectionFromSlug, - zcodeRuntimeEnvironment, - zcodeSpawnArgs, - type ZcodeCatalogFileSet, -} from "./zcodeRuntime.ts"; -import { - makeZcodeRequestAuth, - zcodeAccountConfigPushFromLadder, - zcodeFamilyFromProviderId, -} from "./zcodeRequestAuth.ts"; + makeZcodeServeConnection, + type ZcodeServeConnectionOptions, +} from "./zcodeServeConnection.ts"; export const ZCODE_PROVIDER: ProviderDriverKind = ProviderDriverKind.make("zcode"); const DEFAULT_ZCODE_SETTINGS = Schema.decodeSync(ZcodeSettings)({}); @@ -192,10 +182,14 @@ export interface ZcodeAdapterV2Options { readonly settings: ZcodeSettings; /** Instance environment already merged with the host process environment. */ readonly environment: NodeJS.ProcessEnv; - /** Testkit injection point; production spawns the real `zcode app-server`. */ - readonly makeConnection?: typeof makeZcodeConnection; - /** Testkit injection point; production mints OAuth project tokens from the local store. */ - readonly makeRequestAuth?: typeof makeZcodeRequestAuth; + /** Testkit injection point; production attaches to the local `zcode serve` daemon. */ + readonly makeConnection?: ( + options: ZcodeServeConnectionOptions, + ) => Effect.Effect< + ZcodeConnection, + ZcodeProtocolError | ZcodeProtocolTimeoutError, + ChildProcessSpawner.ChildProcessSpawner | Scope.Scope + >; } function providerRef( @@ -418,7 +412,6 @@ export const makeZcodeAdapterV2 = Effect.fn("makeZcodeAdapterV2")(function* ( options: ZcodeAdapterV2Options, ) { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const agentScope = yield* AgentScope; const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocator.IdAllocatorV2; const host = yield* ProviderHost.ProviderHost; @@ -432,20 +425,6 @@ export const makeZcodeAdapterV2 = Effect.fn("makeZcodeAdapterV2")(function* ( ...(payload === undefined ? {} : { payload }), }); - // The CLI's own host reports the installed version in the token exchange; unknown stays omitted. - const dataRoot = zcodeDataRoot(options.environment); - const clientVersion = - dataRoot === undefined - ? undefined - : yield* readZcodeAppVersion(fileSystem, `${dataRoot}/.zcode/server/current.json`); - - const requestAuth = (options.makeRequestAuth ?? makeZcodeRequestAuth)({ - fileSystem, - httpClient, - environment: options.environment, - clientVersion, - }); - const zcodeMcpServers = ( session: McpProviderSessionConfig | undefined, ): ReadonlyArray | undefined => @@ -474,34 +453,14 @@ export const makeZcodeAdapterV2 = Effect.fn("makeZcodeAdapterV2")(function* ( ) { const scope = yield* Effect.scope; const cwd = input.runtimePolicy.cwd ?? host.paths.cwd; - // Catalog files must exist before spawn: the CLI fails closed on dangling env paths. - const catalogFiles: ZcodeCatalogFileSet = yield* resolveZcodeCatalogFiles( - fileSystem, - options.environment, - ); - const env = zcodeRuntimeEnvironment(options.environment, catalogFiles); - const launchCommand = yield* resolveZcodeLaunchCommand( - options.settings, - options.environment, - fileSystem, - ); - const scopedLaunch = yield* agentScope.wrap({ - command: launchCommand, - args: zcodeSpawnArgs(options.settings.launchArgs), - name: "zcode", - threadId: input.threadId, - env, - }); - // Finalizers run in reverse order: reap detached work after terminating zcode. - const scopeUnit = scopedLaunch.unit; - const stopScope = - scopeUnit === undefined ? Effect.void : yield* Effect.cached(agentScope.stop(scopeUnit)); - yield* Effect.addFinalizer(() => stopScope); - const connection: ZcodeConnection = yield* (options.makeConnection ?? makeZcodeConnection)({ - command: scopedLaunch.command, - args: scopedLaunch.args, + const connection: ZcodeConnection = yield* ( + options.makeConnection ?? makeZcodeServeConnection + )({ + environment: options.environment, + settings: options.settings, cwd, - env, + fileSystem, + httpClient, }).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.mapError( @@ -513,13 +472,8 @@ export const makeZcodeAdapterV2 = Effect.fn("makeZcodeAdapterV2")(function* ( }), ), ); - // Detached children can keep stdout open after zcode exits. - if (scopeUnit !== undefined) { - yield* connection.exited.pipe( - Effect.matchEffect({ onFailure: () => stopScope, onSuccess: () => stopScope }), - Effect.forkIn(scope), - ); - } + // A daemon restart surfaces as a closed channel; the pump below fails with it. + yield* connection.exited.pipe(Effect.ignore, Effect.forkIn(scope)); const now = yield* DateTime.now; let sessionEntity: OrchestrationV2ProviderSession = { @@ -1503,45 +1457,6 @@ export const makeZcodeAdapterV2 = Effect.fn("makeZcodeAdapterV2")(function* ( yield* connection.respond(respondId, {}); return; } - case "interaction/requestProviderRuntimeHeaders": { - const params = zcodeRecordField(record, "params"); - const providerId = - zcodeRecordString(params ?? {}, "providerId") ?? - zcodeRecordString( - zcodeRecordField(params ?? {}, "modelSelection") ?? {}, - "providerId", - ); - const family = zcodeFamilyFromProviderId(providerId); - if (family === undefined) { - yield* connection.respond(respondId, { - headersApplied: false, - errorMessage: "Unsupported ZCode account provider.", - }); - return; - } - const rejectedProjectTokenFingerprint = zcodeRecordString( - params ?? {}, - "rejectedProjectTokenFingerprint", - ); - const answer = requestAuth.answerRuntimeHeaders({ - family, - ...(rejectedProjectTokenFingerprint === undefined - ? {} - : { rejectedProjectTokenFingerprint }), - }); - // Minting can take seconds on a cache miss; the CLI correlates the reply by id, so - // fork it instead of stalling every session event this permit serializes. - yield* answer.pipe( - Effect.flatMap((response) => connection.respond(respondId, response)), - Effect.catchCause((cause) => - Effect.logWarning("ZCode runtime headers answer failed.", { - errorTag: causeErrorTag(cause), - }), - ), - Effect.forkIn(scope), - ); - return; - } case "interaction/requestPermission": { const params = zcodeRecordField(record, "params"); const nativeRequestId = @@ -1656,7 +1571,7 @@ export const makeZcodeAdapterV2 = Effect.fn("makeZcodeAdapterV2")(function* ( ? null : makeProviderFailure({ cause, - message: "zcode app-server exited unexpectedly.", + message: "The ZCode server connection was lost.", class: "transport_error", }); yield* finalizeTurn(state); @@ -1666,8 +1581,8 @@ export const makeZcodeAdapterV2 = Effect.fn("makeZcodeAdapterV2")(function* ( yield* updateProviderSession( interrupted ? "stopped" : "error", interrupted - ? "zcode app-server was stopped." - : "zcode app-server exited unexpectedly.", + ? "The ZCode server connection was closed." + : "The ZCode server connection was lost.", ); yield* Queue.fail( events, @@ -1682,40 +1597,7 @@ export const makeZcodeAdapterV2 = Effect.fn("makeZcodeAdapterV2")(function* ( Effect.forkIn(scope), ); - // Provisioning must precede session/create: the CLI resolves models against the registry - // it builds from this push. Best-effort — a rejected push surfaces honestly as a - // "Select a model" turn failure instead of failing the session open. - const bootstrapProviderRegistry = Effect.fn("ZcodeAdapter.bootstrapProviderRegistry")( - function* () { - if (catalogFiles.builtinCatalog === undefined || catalogFiles.builtinPath === undefined) { - yield* Effect.logWarning( - "ZCode builtin catalog unavailable; account models will report as missing.", - { builtinPath: catalogFiles.builtinPath ?? null }, - ); - return; - } - const push = yield* zcodeAccountConfigPushFromLadder(fileSystem, { - builtinPath: catalogFiles.builtinPath, - builtinCatalog: catalogFiles.builtinCatalog, - environment: options.environment, - }); - if (push === undefined) { - yield* Effect.logWarning( - "ZCode catalog declares no account providers; account models will report as missing.", - ); - return; - } - yield* request("provider/updateAccountConfig", push).pipe( - Effect.tapError((error) => - Effect.logWarning("ZCode account config push failed.", { - operation: error.operation, - }), - ), - Effect.ignore, - ); - }, - ); - yield* bootstrapProviderRegistry(); + // The daemon owns provider/credential provisioning, so no account config is pushed here. const subscribeSession = Effect.fnUntraced(function* (sessionId: string) { const result = yield* request("session/subscribe", { @@ -1728,7 +1610,7 @@ export const makeZcodeAdapterV2 = Effect.fn("makeZcodeAdapterV2")(function* ( const snapshot = zcodeRecordField(Predicate.isObject(result) ? result : {}, "snapshot"); const settings = zcodeRecordField(Predicate.isObject(snapshot) ? snapshot : {}, "settings"); const model = zcodeRecordField(Predicate.isObject(settings) ? settings : {}, "model"); - const models = parseZcodeAvailableModels(model); + const models = parseZcodeAvailableModels(zcodeRecordField(model, "available")); if (models.length > 0) availableModels = models; return result; }); diff --git a/packages/provider-zcode/src/server/status.ts b/packages/provider-zcode/src/server/status.ts index 7955e64ff444d..e1462d3c6ea66 100644 --- a/packages/provider-zcode/src/server/status.ts +++ b/packages/provider-zcode/src/server/status.ts @@ -6,7 +6,7 @@ import { } from "@t3tools/contracts"; import type { ZcodeSettings } from "../settings.ts"; import { resolveZcodeCatalogFiles, resolveZcodeLaunchCommand } from "./zcodeRuntime.ts"; -import { zcodeEntitledModels, zcodeOAuthSelectedFamilies } from "./zcodeRequestAuth.ts"; +import { zcodeEntitledModels, zcodeOAuthSelectedFamilies } from "./zcodeEntitlements.ts"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; import { compareSemverVersions } from "@t3tools/shared/semver"; import { createModelCapabilities } from "@t3tools/shared/model"; @@ -136,8 +136,8 @@ const runZcodeDoctor = Effect.fn("ZcodeProviderStatus.runDoctor")(function* ( /** * Auth is CLI-managed (`zcode login`); the probe derives status from the same credential-store - * keys and setting.json plan selections the provisioning ladder accepts, so an account that can - * make ZCode requests never shows a false `zcode login` warning. + * keys and setting.json plan selections the model picker accepts, so an account that can make + * ZCode requests never shows a false `zcode login` warning. */ export const zcodeAuthFromCredentials = ( data: unknown, @@ -153,7 +153,7 @@ export const zcodeAuthFromCredentials = ( ); return hasActiveProvider ? "authenticated" : "unauthenticated"; } - // Object stores are judged like provisioning, which ignores any oauth:active_provider marker. + // Object stores are judged like the picker, which ignores any oauth:active_provider marker. if (typeof data === "object" && data !== null) { return zcodeOAuthSelectedFamilies(setting, data as Record).size > 0 ? "authenticated" diff --git a/packages/provider-zcode/src/server/zcodeEntitlements.test.ts b/packages/provider-zcode/src/server/zcodeEntitlements.test.ts new file mode 100644 index 0000000000000..3fa0674840e95 --- /dev/null +++ b/packages/provider-zcode/src/server/zcodeEntitlements.test.ts @@ -0,0 +1,191 @@ +// @effect-diagnostics nodeBuiltinImport:off -- tests craft the CLI's own AES-GCM store values with node crypto +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { assert, describe, it } from "@effect/vitest"; +import * as NodeCrypto from "node:crypto"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; + +import { + decryptZcodeCredential, + resolveZcodeCredentialSecret, + zcodeEntitledModels, +} from "./zcodeEntitlements.ts"; + +/** Produces store values the CLI's fallback cipher would hold, keyed the same way. */ +const encryptZcodeCredential = (value: string, secret: string): string => { + const iv = NodeCrypto.randomBytes(12); + const cipher = NodeCrypto.createCipheriv( + "aes-256-gcm", + NodeCrypto.createHash("sha256").update(secret).digest(), + iv, + ); + const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]); + return `enc:v1:${iv.toString("base64url")}.${cipher.getAuthTag().toString("base64url")}.${ciphertext.toString("base64url")}`; +}; + +const catalog = { + config: { + providerConfigRules: { + providerRules: [ + { + providerId: "account:zai-individual-coding-plan", + config: { + access: { type: "zhipu-account", mode: "individual-coding-plan", accountType: "zai" }, + builtinModelIds: ["GLM-5.3", "GLM-5.3-Flash"], + }, + }, + { + providerId: "account:zai-team-coding-plan", + config: { + access: { type: "zhipu-account", mode: "team-coding-plan", accountType: "zai" }, + builtinModelIds: ["GLM-5.3"], + }, + }, + { + providerId: "zai-api", + config: { access: { type: "api-key" }, builtinModelIds: ["GLM-5.3"] }, + }, + ], + }, + modelConfigRules: { + modelRules: [ + { + modelMatch: "^GLM-5\\.3$", + config: { optionSpecs: { reasoningLevel: { values: ["low", "high", "max"] } } }, + }, + { + modelMatch: "^GLM-5\\.3-Flash$", + config: { optionSpecs: { reasoningLevel: { values: ["low", "high"] } } }, + }, + ], + }, + }, +}; + +describe("resolveZcodeCredentialSecret", () => { + it("prefers ZCODE_CREDENTIAL_SECRET and trims it", () => { + assert.equal( + resolveZcodeCredentialSecret({ ZCODE_CREDENTIAL_SECRET: " custom-secret " }, "linux"), + "custom-secret", + ); + const blankOverride = resolveZcodeCredentialSecret( + { ZCODE_CREDENTIAL_SECRET: " ", HOME: "/home/dev" }, + "linux", + ); + assert.match(blankOverride, /^zcode-credential-fallback:linux:\/home\/dev:/); + }); + + it("derives the CLI's machine-bound fallback with the HOME from the environment", () => { + // Username comes from os.userInfo() where resolvable (env names never win); on runtimes + // where it throws, the env fallback speaks. Only the stable parts are asserted here. + const secret = resolveZcodeCredentialSecret( + { USER: "someoneElse", HOME: "/home/dev" }, + "darwin", + ); + assert.match(secret, /^zcode-credential-fallback:darwin:\/home\/dev:/); + assert.match(resolveZcodeCredentialSecret({}, "linux"), /^zcode-credential-fallback:linux:/); + }); +}); + +describe("decryptZcodeCredential", () => { + it("round-trips the CLI's encrypted store values", () => { + const secret = "zcode-credential-fallback:linux:/home/dev:jame"; + for (const plaintext of ["oauth-login-token", "值-with-unicode 🔐", ""]) { + assert.equal( + decryptZcodeCredential(encryptZcodeCredential(plaintext, secret), secret), + plaintext, + ); + } + }); + + it("passes plain store values through and rejects malformed ciphertext", () => { + assert.equal(decryptZcodeCredential("plain-token", "s"), "plain-token"); + assert.throws(() => decryptZcodeCredential("enc:v1:not-a-cipher", "s")); + assert.throws(() => decryptZcodeCredential("enc:v1:only.two", "s")); + }); +}); + +describe("zcodeEntitledModels", () => { + const harness = (input: { + readonly customModels?: unknown; + readonly setting?: unknown; + readonly loginToken?: string; + }) => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "zcode-entitlements-test-" }); + const platform = yield* HostProcess.Platform; + const environment = { ZCODE_DATA_BASE_DIR: root, HOME: "/home/dev", USER: "dev" }; + yield* fs.makeDirectory(`${root}/.zcode/v2`, { recursive: true }); + if (input.setting !== undefined) { + yield* fs.writeFileString( + `${root}/.zcode/v2/setting.json`, + JSON.stringify(input.setting), + ); + } + if (input.loginToken !== undefined) { + yield* fs.writeFileString( + `${root}/.zcode/v2/credentials.json`, + JSON.stringify({ + "oauth:zai:access_token": encryptZcodeCredential( + input.loginToken, + resolveZcodeCredentialSecret(environment, platform), + ), + }), + ); + } + return yield* zcodeEntitledModels(fs, { + builtinPath: `${root}/zcode-builtin.json`, + builtinCatalog: input.customModels ?? catalog, + environment, + }); + }), + ).pipe(Effect.provide(NodeServices.layer)); + + it.effect("enumerates selected individual-coding-plan models with catalog reasoning levels", () => + Effect.gen(function* () { + const models = yield* harness({ + setting: { + providerFamilyConnectionSelections: { zai: { kind: "individual-coding-plan" } }, + }, + loginToken: "zai-login-token", + }); + assert.deepEqual(models, [ + { + providerId: "account:zai-individual-coding-plan", + modelId: "GLM-5.3", + reasoningLevels: ["low", "high", "max"], + }, + { + providerId: "account:zai-individual-coding-plan", + modelId: "GLM-5.3-Flash", + reasoningLevels: ["low", "high"], + }, + ]); + }), + ); + + it.effect("drops a family switched to apiKey mode even with a login token", () => + Effect.gen(function* () { + const models = yield* harness({ + setting: { + providerFamilyConnectionSelections: { zai: { kind: "individual-coding-plan" } }, + modelProviderFamilyModes: { zai: "apiKey" }, + }, + loginToken: "zai-login-token", + }); + assert.deepEqual(models, []); + }), + ); + + it.effect("skips catalogs without zhipu-account rules", () => + Effect.gen(function* () { + const models = yield* harness({ + customModels: { config: { providerConfigRules: { providerRules: [] } } }, + }); + assert.deepEqual(models, []); + }), + ); +}); diff --git a/packages/provider-zcode/src/server/zcodeEntitlements.ts b/packages/provider-zcode/src/server/zcodeEntitlements.ts new file mode 100644 index 0000000000000..b987452d0b901 --- /dev/null +++ b/packages/provider-zcode/src/server/zcodeEntitlements.ts @@ -0,0 +1,229 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the CLI's credential store is AES-256-GCM under a key only node:crypto can derive +// The entitlement ladder shared by the model picker and the auth probe: which individual-coding-plan +// families the user selected in setting.json and holds a decryptable login token for in +// credentials.json, joined against the CLI catalog's zhipu-account rules. +import * as NodeCrypto from "node:crypto"; +import * as NodeOS from "node:os"; + +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Predicate from "effect/Predicate"; +import * as Schema from "effect/Schema"; + +import { + zcodeRecordArray, + zcodeRecordField, + zcodeRecordString, + type ZcodeRecord, +} from "./zcodeProtocol.ts"; +import { zcodeDataRoot } from "./zcodeRuntime.ts"; + +const ENCRYPTED_PREFIX = "enc:v1:"; +const CIPHER_ALGORITHM = "aes-256-gcm"; + +/** + * The CLI's machine-bound fallback cipher secret: sha256 of this string keys the store's + * AES-256-GCM values. ZCODE_CREDENTIAL_SECRET overrides it for custom installs. + */ +export const resolveZcodeCredentialSecret = ( + environment: NodeJS.ProcessEnv, + platform: NodeJS.Platform, +): string => { + const configured = environment.ZCODE_CREDENTIAL_SECRET?.trim(); + if (configured !== undefined && configured.length > 0) return configured; + // The CLI binds the fallback to os.userInfo().username — env USER/USERNAME may be absent in + // server processes and must not silently derive a different key. + let username = "unknown"; + try { + username = NodeOS.userInfo().username; + } catch { + username = environment.USER ?? environment.USERNAME ?? "unknown"; + } + const home = environment.HOME ?? NodeOS.homedir(); + return `zcode-credential-fallback:${platform}:${home}:${username}`; +}; + +export const decryptZcodeCredential = (value: string, secret: string): string => { + if (!value.startsWith(ENCRYPTED_PREFIX)) return value; + const [ivRaw, tagRaw, cipherRaw] = value.slice(ENCRYPTED_PREFIX.length).split("."); + if (ivRaw === undefined || tagRaw === undefined || cipherRaw === undefined) { + throw new Error("Encrypted credential is not ..."); + } + const decipher = NodeCrypto.createDecipheriv( + CIPHER_ALGORITHM, + NodeCrypto.createHash("sha256").update(secret).digest(), + Buffer.from(ivRaw, "base64url"), + ); + decipher.setAuthTag(Buffer.from(tagRaw, "base64url")); + return Buffer.concat([ + decipher.update(Buffer.from(cipherRaw, "base64url")), + decipher.final(), + ]).toString("utf8"); +}; + +const decodeJsonText = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); + +const readDecryptedCredentialStore = Effect.fn("ZcodeEntitlements.readCredentialStore")(function* ( + fileSystem: FileSystem.FileSystem, + credentialsPath: string, + environment: NodeJS.ProcessEnv, + platform: NodeJS.Platform, +): Effect.fn.Return> { + const raw = yield* fileSystem.readFileString(credentialsPath).pipe(Effect.option); + if (Option.isNone(raw)) return {}; + const parsed = Option.getOrUndefined(decodeJsonText(raw.value)); + if (!Predicate.isObject(parsed)) return {}; + const secret = resolveZcodeCredentialSecret(environment, platform); + const entries: Record = {}; + for (const [key, value] of Object.entries(parsed)) { + if (typeof value !== "string") continue; + const decrypted = yield* Effect.try({ + try: () => decryptZcodeCredential(value, secret), + catch: () => undefined, + }).pipe(Effect.option); + if (Option.isSome(decrypted)) entries[key] = decrypted.value; + } + return entries; +}); + +/** + * Families the entitlement ladder treats as signed-in OAuth individual coding plans: setting.json + * selects the plan, no apiKey override, and the credential store holds a login token for the + * family. The provider status probe derives its auth display from this same predicate so the + * probe and the picker cannot drift. + */ +export const zcodeOAuthSelectedFamilies = ( + setting: unknown, + store: Record, +): ReadonlySet => { + if (!Predicate.isObject(setting)) return new Set(); + const selections = setting["providerFamilyConnectionSelections"]; + const modes = setting["modelProviderFamilyModes"]; + const families = new Set(); + if (!Predicate.isObject(selections)) return families; + for (const [family, selection] of Object.entries(selections)) { + const kind = Predicate.isObject(selection) ? selection["kind"] : undefined; + if (kind !== "individual-coding-plan") continue; + if (Predicate.isObject(modes) && modes[family] === "apiKey") continue; + const token = store[`oauth:${family}:access_token`]; + if (typeof token !== "string" || token.length === 0) continue; + families.add(family); + } + return families; +}; + +/** Families whose 3.15+ connection is an active OAuth individual coding plan. */ +const readOAuthSelectedFamilies = Effect.fn("ZcodeEntitlements.readOAuthFamilies")(function* ( + fileSystem: FileSystem.FileSystem, + settingPath: string, + store: Record, +): Effect.fn.Return> { + const raw = yield* fileSystem.readFileString(settingPath).pipe(Effect.option); + const parsed = Option.isNone(raw) ? undefined : Option.getOrUndefined(decodeJsonText(raw.value)); + return zcodeOAuthSelectedFamilies(parsed, store); +}); + +const zcodeRuleAccess = (rule: unknown): ZcodeRecord | undefined => { + const access = zcodeRecordField(zcodeRecordField(rule, "config"), "access"); + return Predicate.isObject(access) ? access : undefined; +}; + +const zcodeBuiltinAccountRules = (builtinCatalog: unknown): ReadonlyArray => { + const providerRules = zcodeRecordArray( + zcodeRecordField(zcodeRecordField(builtinCatalog, "config"), "providerConfigRules"), + "providerRules", + ); + return (providerRules ?? []).filter( + (rule): rule is ZcodeRecord => + Predicate.isObject(rule) && + zcodeRecordString(zcodeRuleAccess(rule), "type") === "zhipu-account", + ); +}; + +const zcodeBuiltinModelIds = (rule: ZcodeRecord): ReadonlyArray => { + const ids = zcodeRecordField(zcodeRecordField(rule, "config"), "builtinModelIds"); + return (Array.isArray(ids) ? ids : []).filter( + (id): id is string => typeof id === "string" && id.length > 0, + ); +}; + +/** + * Entitled individual-coding-plan models for the model picker: enumerated from the injected + * catalog plus the entitlement ladder, so a catalog refresh by the CLI adds models without an + * adapter change. Reasoning levels come from the catalog's modelRules (modelMatch regexes, + * matched case-insensitively against the model id). + */ +export interface ZcodeEntitledModel { + readonly providerId: string; + readonly modelId: string; + readonly reasoningLevels: ReadonlyArray; +} + +export const zcodeEntitledModels = Effect.fn("ZcodeEntitlements.entitledModels")(function* ( + fileSystem: FileSystem.FileSystem, + input: { + readonly builtinPath: string; + readonly builtinCatalog: unknown; + readonly environment: NodeJS.ProcessEnv; + }, +): Effect.fn.Return, never, never> { + const rules = zcodeBuiltinAccountRules(input.builtinCatalog); + const root = zcodeDataRoot(input.environment); + if (rules.length === 0 || root === undefined) return []; + const store = yield* readDecryptedCredentialStore( + fileSystem, + `${root}/.zcode/v2/credentials.json`, + input.environment, + yield* HostProcess.Platform, + ); + const families = yield* readOAuthSelectedFamilies( + fileSystem, + `${root}/.zcode/v2/setting.json`, + store, + ); + const modelRules = zcodeRecordArray( + zcodeRecordField(zcodeRecordField(input.builtinCatalog, "config"), "modelConfigRules"), + "modelRules", + ); + const levelsFor = (modelId: string): ReadonlyArray => { + // Later matching rules compose over earlier ones (the runtime's advertised levels are the + // last match: Flash hits glm-5.* then glm-5\.3, landing on [low, high, max]). + let levels: ReadonlyArray = []; + for (const rule of modelRules ?? []) { + const match = zcodeRecordString(rule, "modelMatch"); + if (match === undefined) continue; + let regex: RegExp; + try { + regex = new RegExp(match, "i"); + } catch { + continue; + } + if (!regex.test(modelId)) continue; + const specs = zcodeRecordField(zcodeRecordField(rule, "config"), "optionSpecs"); + const reasoning = zcodeRecordField(Predicate.isObject(specs) ? specs : {}, "reasoningLevel"); + const values = zcodeRecordArray(reasoning, "values")?.filter( + (value): value is string => typeof value === "string", + ); + if (values !== undefined && values.length > 0) levels = values; + } + return levels; + }; + const out: Array = []; + for (const rule of rules) { + const providerId = zcodeRecordString(rule, "providerId"); + const access = zcodeRuleAccess(rule); + if ( + providerId === undefined || + zcodeRecordString(access, "mode") !== "individual-coding-plan" || + !families.has(zcodeRecordString(access, "accountType") ?? "") + ) { + continue; + } + for (const modelId of zcodeBuiltinModelIds(rule)) { + out.push({ providerId, modelId, reasoningLevels: levelsFor(modelId) }); + } + } + return out; +}); diff --git a/packages/provider-zcode/src/server/zcodeProtocol.test.ts b/packages/provider-zcode/src/server/zcodeProtocol.test.ts deleted file mode 100644 index aa02b7350764e..0000000000000 --- a/packages/provider-zcode/src/server/zcodeProtocol.test.ts +++ /dev/null @@ -1,249 +0,0 @@ -import { assert, describe, it } from "@effect/vitest"; -import { expect, vi } from "vite-plus/test"; -import * as Cause from "effect/Cause"; -import * as Deferred from "effect/Deferred"; -import * as Duration from "effect/Duration"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Fiber from "effect/Fiber"; -import * as Option from "effect/Option"; -import * as Queue from "effect/Queue"; -import * as Sink from "effect/Sink"; -import * as Scope from "effect/Scope"; -import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; -import { ChildProcessSpawner } from "effect/process"; -import * as HostProcess from "@t3tools/shared/HostProcess"; - -import { makeZcodeConnection, ZcodeProtocolError, type ZcodeRecord } from "./zcodeProtocol.ts"; - -// Mirrors the private EXIT_DRAIN_GRACE and TERMINATION_GRACE in zcodeProtocol.ts. -const EXIT_DRAIN_GRACE_MS = 1_000; -const TERMINATION_GRACE_MS = 1_000; - -const processGroupState = vi.hoisted(() => ({ - groupAlive: true, - signals: [] as Array, -})); - -vi.mock("@t3tools/provider-core/server/processGroup", () => ({ - signalProcessGroup: (pid: number, signal: NodeJS.Signals | 0) => { - if (!processGroupState.groupAlive) { - throw Object.assign(new Error(`kill ESRCH: no process group ${pid}`), { code: "ESRCH" }); - } - processGroupState.signals.push(signal); - }, -})); - -const setupProcessGroup = (groupAlive: boolean) => { - processGroupState.groupAlive = groupAlive; - processGroupState.signals = []; -}; - -const makeHeldOpenChild = Effect.fnUntraced(function* (scope?: Scope.Closeable) { - const exitCode = yield* Deferred.make(); - const stdout = yield* Queue.unbounded>(); - const stdinChunks = yield* Queue.unbounded(); - const handle = ChildProcessSpawner.makeHandle({ - pid: ChildProcessSpawner.ProcessId(55_000), - exitCode: Deferred.await(exitCode), - isRunning: Effect.succeed(true), - kill: () => Effect.void, - unref: Effect.succeed(Effect.void), - stdin: Sink.forEach((chunk: Uint8Array) => Queue.offer(stdinChunks, chunk).pipe(Effect.asVoid)), - stdout: Stream.fromQueue(stdout), - stderr: Stream.empty, - all: Stream.empty, - getInputFd: () => Sink.drain, - getOutputFd: () => Stream.empty, - }); - const unscoped = makeZcodeConnection({ - command: "zcode", - args: ["app-server", "--stdio"], - cwd: undefined, - env: {}, - }).pipe( - Effect.provideService( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.succeed(handle)), - ), - Effect.provideService(HostProcess.Platform, "linux"), - ); - const connection = yield* scope === undefined ? unscoped : unscoped.pipe(Scope.provide(scope)); - return { connection, exitCode, stdout, stdinChunks }; -}); - -const takeSentRecord = Effect.fnUntraced(function* (stdinChunks: Queue.Dequeue) { - const line = new TextDecoder().decode(yield* Queue.take(stdinChunks)); - return JSON.parse(line) as ZcodeRecord; -}); - -describe("makeZcodeConnection", () => { - it.effect("fails the transport once the exit grace elapses with stdout still open", () => - Effect.scoped( - Effect.gen(function* () { - // Group modeled empty, so the scope-close termination below is a no-op. - setupProcessGroup(false); - const { connection, exitCode, stdout } = yield* makeHeldOpenChild(); - - yield* Deferred.succeed(exitCode, ChildProcessSpawner.ExitCode(0)); - assert.equal(yield* connection.exited, 0); - - // Records buffered when zcode died still drain while the grace runs. - yield* Queue.offer(stdout, new TextEncoder().encode('{"event":"turn.completed"}\n')); - const drained = yield* Queue.take(connection.events); - assert.equal(drained["event"], "turn.completed"); - - const down = yield* Deferred.make(); - yield* Queue.take(connection.events).pipe( - Effect.catch((error) => Deferred.succeed(down, error)), - Effect.forkScoped, - ); - yield* TestClock.adjust(Duration.millis(EXIT_DRAIN_GRACE_MS - 1)); - assert.isTrue(Option.isNone(yield* Deferred.poll(down))); - yield* TestClock.adjust(Duration.millis(1)); - const error = yield* Deferred.await(down); - assert.instanceOf(error, ZcodeProtocolError); - assert.equal(error.operation, "read"); - assert.equal(error.detail, "zcode app-server exited with code 0, but stdout never closed"); - }), - ), - ); - - it.effect("stdout closing after exit still reports the exit code", () => - Effect.scoped( - Effect.gen(function* () { - // Group modeled empty, so the scope-close termination below is a no-op. - setupProcessGroup(false); - const { connection, exitCode, stdout } = yield* makeHeldOpenChild(); - const down = yield* Deferred.make(); - yield* Queue.take(connection.events).pipe( - Effect.catch((error) => Deferred.succeed(down, error)), - Effect.forkScoped, - ); - - yield* Deferred.succeed(exitCode, ChildProcessSpawner.ExitCode(7)); - assert.equal(yield* connection.exited, 7); - yield* Queue.end(stdout); - - const error = yield* Deferred.await(down); - assert.equal(error.operation, "read"); - assert.equal(error.detail, "zcode app-server exited with code 7"); - }), - ), - ); - - it.effect("escalates to SIGKILL after the leader exits while tools keep the group alive", () => - Effect.scoped( - Effect.gen(function* () { - setupProcessGroup(true); - const scope = yield* Scope.make(); - const { connection, exitCode } = yield* makeHeldOpenChild(scope); - - yield* Deferred.succeed(exitCode, ChildProcessSpawner.ExitCode(0)); - assert.equal(yield* connection.exited, 0); - - // Detached tools keep the pgid alive after the leader is reaped; termination must - // still SIGTERM the group and, after the grace, SIGKILL the survivors. - const closed = yield* Scope.close(scope, Exit.void).pipe(Effect.forkScoped); - yield* TestClock.adjust(Duration.millis(TERMINATION_GRACE_MS)); - yield* Fiber.join(closed); - - // hasExited probes interleave signal 0; assert on the delivered signals only. - const sent = processGroupState.signals.filter((signal) => signal !== 0); - expect(sent).toEqual(["SIGTERM", "SIGKILL"]); - }), - ), - ); - - it.effect("skips group signalling once the leader exited and the group is empty", () => - Effect.scoped( - Effect.gen(function* () { - setupProcessGroup(false); - const scope = yield* Scope.make(); - const { connection, exitCode } = yield* makeHeldOpenChild(scope); - - yield* Deferred.succeed(exitCode, ChildProcessSpawner.ExitCode(0)); - assert.equal(yield* connection.exited, 0); - - // No survivors: termination returns without waiting the grace or signalling. - yield* Scope.close(scope, Exit.void); - - expect(processGroupState.signals).toEqual([]); - }), - ), - ); - - it.effect("a rejected request reports the real method with bounded detail", () => - Effect.scoped( - Effect.gen(function* () { - // Group modeled empty, so the scope-close termination below is a no-op. - setupProcessGroup(false); - const { connection, stdout, stdinChunks } = yield* makeHeldOpenChild(); - - const pending = yield* connection - .request("provider/updateAccountConfig", { accountId: "acct_1" }) - .pipe( - Effect.catch((error) => Effect.succeed(error)), - Effect.forkScoped, - ); - - const sent = yield* takeSentRecord(stdinChunks); - assert.equal(sent["method"], "provider/updateAccountConfig"); - - const payload = "SECRET_ZCODE_SERVER_PAYLOAD"; - const serverError = { code: "accountConfigRejected", message: payload }; - yield* Queue.offer( - stdout, - new TextEncoder().encode(`${JSON.stringify({ id: sent["id"], error: serverError })}\n`), - ); - - const error = yield* Fiber.join(pending); - assert.instanceOf(error, ZcodeProtocolError); - // Raw payload stays in cause only; message and detail carry bounded metadata. - assert.isFalse(`${error.detail}`.includes(payload)); - assert.isFalse(error.message.includes(payload)); - assert.equal( - error.detail, - `code accountConfigRejected, ${JSON.stringify(serverError).length}-char payload`, - ); - assert.include(JSON.stringify(error.cause), payload); - // The failure names the method that failed, not the generic "request". - assert.equal(error.operation, "provider/updateAccountConfig"); - }), - ), - ); - - it.effect("a string error payload also stays confined to cause", () => - Effect.scoped( - Effect.gen(function* () { - // Group modeled empty, so the scope-close termination below is a no-op. - setupProcessGroup(false); - const { connection, stdout, stdinChunks } = yield* makeHeldOpenChild(); - - const pending = yield* connection - .request("session/subscribe", { sessionId: "sess_1" }) - .pipe( - Effect.catch((error) => Effect.succeed(error)), - Effect.forkScoped, - ); - - const sent = yield* takeSentRecord(stdinChunks); - - const payload = "SECRET_BARE_ZCODE_PAYLOAD"; - yield* Queue.offer( - stdout, - new TextEncoder().encode(`${JSON.stringify({ id: sent["id"], error: payload })}\n`), - ); - - const error = yield* Fiber.join(pending); - assert.instanceOf(error, ZcodeProtocolError); - assert.isFalse(`${error.detail}`.includes(payload)); - assert.isFalse(error.message.includes(payload)); - assert.equal(error.detail, `${JSON.stringify(payload).length}-char payload`); - assert.include(JSON.stringify(error.cause), payload); - assert.equal(error.operation, "session/subscribe"); - }), - ), - ); -}); diff --git a/packages/provider-zcode/src/server/zcodeProtocol.ts b/packages/provider-zcode/src/server/zcodeProtocol.ts index 45a67c9a81588..51804049d217e 100644 --- a/packages/provider-zcode/src/server/zcodeProtocol.ts +++ b/packages/provider-zcode/src/server/zcodeProtocol.ts @@ -1,21 +1,10 @@ -// ZCode app-server speaks NDJSON on stdio; responses carry {id, result|error} while server→client -// requests repeat the {id, method, params} shape and must be answered via respond(). -import * as Clock from "effect/Clock"; -import * as Deferred from "effect/Deferred"; -import * as Duration from "effect/Duration"; -import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; +// Shared wire-shape types and errors for the ZCode provider. The transport itself lives in +// `zcodeServeProtocol.ts` (channel frames over the daemon's WebSocket) and +// `zcodeServeConnection.ts` (daemon requests mapped onto this connection surface). import * as Predicate from "effect/Predicate"; -import * as Queue from "effect/Queue"; -import * as Scope from "effect/Scope"; import * as Schema from "effect/Schema"; -import * as Stream from "effect/Stream"; -import * as ChildProcess from "effect/process/ChildProcess"; -import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; -import * as HostProcess from "@t3tools/shared/HostProcess"; -import { resolveSpawnCommand } from "@t3tools/shared/shell"; - -import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; +import type * as Queue from "effect/Queue"; +import type * as Effect from "effect/Effect"; export class ZcodeProtocolError extends Schema.TaggedError()( "ZcodeProtocolError", @@ -66,13 +55,6 @@ export function zcodeRecordArray(input: unknown, key: string): ReadonlyArray record["id"] !== undefined && Predicate.isString(record["method"]); -export interface ZcodeSpawnOptions { - readonly command: string; - readonly args: ReadonlyArray; - readonly cwd: string | undefined; - readonly env: NodeJS.ProcessEnv; -} - export interface ZcodeConnection { readonly request: ( method: string, @@ -85,61 +67,7 @@ export interface ZcodeConnection { readonly terminate: Effect.Effect; } -const DEFAULT_REQUEST_TIMEOUT_MS = 30_000; -const TERMINATION_GRACE = Duration.seconds(1); -const EXIT_DRAIN_GRACE = Duration.seconds(1); - -interface PendingZcodeRequest { - readonly deferred: Deferred.Deferred; - readonly method: string; -} - -const MAX_ZCODE_RECORD_CHARS = 16 * 1024 * 1024; - -function makeJsonlFramer() { - let buffer = ""; - let dropping = false; - return (chunk: string) => { - const lines: string[] = []; - const droppedLengths: number[] = []; - let start = 0; - while (start < chunk.length) { - const newline = chunk.indexOf("\n", start); - const end = newline < 0 ? chunk.length : newline; - if (!dropping) { - if (buffer.length + end - start > MAX_ZCODE_RECORD_CHARS) { - droppedLengths.push(buffer.length + end - start); - buffer = ""; - dropping = true; - } else { - buffer += chunk.slice(start, end); - } - } - if (newline < 0) break; - if (!dropping && buffer.length > 0) { - lines.push(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer); - } - buffer = ""; - dropping = false; - start = newline + 1; - } - return { lines, droppedLengths }; - }; -} - -const logDroppedZcodeRecords = (droppedLengths: ReadonlyArray) => - Effect.forEach( - droppedLengths, - (recordLength) => - Effect.logWarning("Dropping oversized zcode stdout record.", { - recordLength, - maxRecordLength: MAX_ZCODE_RECORD_CHARS, - }), - { discard: true }, - ); - const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown); -const decodeJsonLine = Schema.decodeSync(UnknownFromJsonString); const encodeJsonLine = Schema.encodeSync(UnknownFromJsonString); /** JSON text for wire params/diagnostics; pure, so it may fall back to an empty string. */ @@ -150,331 +78,3 @@ export function zcodeJsonStringify(value: unknown): string { return ""; } } - -const ZCODE_SERVER_ERROR_CODE_MAX_CHARS = 100; - -// Bounded server-error metadata; the raw payload travels only in `cause`. -function describeZcodeServerError(error: unknown): string { - const code = zcodeRecordField(error, "code"); - const codeText = - typeof code === "string" || typeof code === "number" - ? `code ${String(code).slice(0, ZCODE_SERVER_ERROR_CODE_MAX_CHARS)}` - : undefined; - const payloadLength = JSON.stringify(error)?.length ?? 0; - return codeText === undefined - ? `${payloadLength}-char payload` - : `${codeText}, ${payloadLength}-char payload`; -} - -function describeZcodeStdoutClosure(exitCode: number | undefined): string { - if (exitCode === undefined || !Number.isFinite(exitCode)) { - return "zcode app-server closed stdout"; - } - return `zcode app-server exited with code ${exitCode}`; -} - -function parseZcodeRecord(line: string): ZcodeRecord | undefined { - try { - const parsed: unknown = decodeJsonLine(line); - return Predicate.isObject(parsed) ? parsed : undefined; - } catch { - return undefined; - } -} - -const terminateZcodeProcess = Effect.fn("ZcodeProtocol.terminateZcodeProcess")(function* ( - kill: (signal: NodeJS.Signals) => boolean, - hasExited: () => boolean, -) { - if (hasExited()) return; - if (!kill("SIGTERM")) return; - yield* Effect.sleep(TERMINATION_GRACE); - if (hasExited()) return; - kill("SIGKILL"); -}); - -export const makeZcodeConnection = Effect.fnUntraced(function* (options: ZcodeSpawnOptions) { - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const platform = yield* HostProcess.Platform; - const scope = yield* Effect.scope; - - const spawnCommand = yield* resolveSpawnCommand(options.command, [...options.args], { - env: options.env, - }).pipe(Effect.mapError((cause) => new ZcodeProtocolError({ operation: "spawn", cause }))); - const child = yield* spawner - .spawn( - ChildProcess.make(spawnCommand.command, spawnCommand.args, { - ...(options.cwd === undefined ? {} : { cwd: options.cwd }), - env: options.env, - extendEnv: false, - shell: spawnCommand.shell, - detached: platform !== "win32", - stdin: { stream: "pipe", endOnDone: false }, - }), - ) - .pipe(Effect.mapError((cause) => new ZcodeProtocolError({ operation: "spawn", cause }))); - - let childExited = false; - let diagnosingStdoutClose = false; - - const killProcessGroup = (signal: NodeJS.Signals): boolean => { - try { - if (platform === "win32") { - process.kill(Number(child.pid), signal); - } else { - signalProcessGroup(Number(child.pid), signal); - } - return true; - } catch { - return false; - } - }; - - const hasExited = (): boolean => { - // A dead POSIX leader does not empty its group: detached tools keep the pgid alive and - // must stay reachable for the SIGKILL escalation. - if (childExited && platform === "win32") return true; - try { - if (platform === "win32") process.kill(Number(child.pid), 0); - else signalProcessGroup(Number(child.pid), 0); - return false; - } catch { - return true; - } - }; - - const terminateWindowsTree = Effect.gen(function* () { - if (hasExited()) return; - const taskkill = yield* spawner.spawn( - ChildProcess.make("taskkill", ["/PID", String(child.pid), "/T", "/F"]), - ); - yield* taskkill.exitCode; - }).pipe(Effect.scoped, Effect.ignore); - - const terminateProcess = - platform === "win32" - ? terminateWindowsTree - : terminateZcodeProcess(killProcessGroup, hasExited); - - yield* Scope.addFinalizer(scope, terminateProcess.pipe(Effect.ignore, Effect.uninterruptible)); - - const pendingRequests = new Map(); - const events = yield* Queue.unbounded(); - const outgoing = yield* Queue.unbounded(); - const transportDown = yield* Deferred.make(); - const exitDeferred = yield* Deferred.make(); - let nextRequestId = 1; - - const failTransport = Effect.fn("ZcodeProtocol.failTransport")(function* ( - error: ZcodeProtocolError, - ) { - const claimed = yield* Deferred.fail(transportDown, error); - if (!claimed) return; - for (const [key, pending] of pendingRequests) { - pendingRequests.delete(key); - yield* Deferred.fail(pending.deferred, error); - } - yield* Queue.fail(outgoing, error); - yield* Queue.fail(events, error); - }); - - const routeRecord = - /* Streaming deltas ride through here; avoid a span per record. */ - Effect.fnUntraced(function* (record: ZcodeRecord) { - if (isServerRequest(record)) { - // Server→client requests are surfaced as events; the adapter answers via respond(). - yield* Queue.offer(events, record); - return; - } - if (record["id"] !== undefined) { - const key = String(record["id"]); - const pending = pendingRequests.get(key); - if (pending !== undefined) { - pendingRequests.delete(key); - if (record["error"] === undefined) { - yield* Deferred.succeed(pending.deferred, record["result"]); - } else { - yield* Deferred.fail( - pending.deferred, - new ZcodeProtocolError({ - operation: pending.method, - detail: describeZcodeServerError(record["error"]), - ...(record["error"] === undefined ? {} : { cause: record["error"] }), - }), - ); - } - return; - } - } - yield* Queue.offer(events, record); - }); - - yield* child.exitCode.pipe( - Effect.matchEffect({ - onFailure: (cause) => - Deferred.fail(exitDeferred, new ZcodeProtocolError({ operation: "exit", cause })), - onSuccess: (code) => - Effect.suspend(() => { - childExited = true; - return Deferred.succeed(exitDeferred, Number(code)); - }), - }), - Effect.forkIn(scope), - ); - - // A detached tool child can inherit stdout and keep it open after zcode exits, so stdout - // EOF never arrives and stdout closure cannot fail the transport. Give records buffered - // at death the grace window to drain, then fail the transport without EOF; the - // transportDown claim keeps a later stdout close from double-failing. - yield* Deferred.await(exitDeferred).pipe( - Effect.matchEffect({ - onFailure: (cause) => - Effect.sleep(EXIT_DRAIN_GRACE).pipe( - Effect.andThen(failTransport(new ZcodeProtocolError({ operation: "exit", cause }))), - ), - onSuccess: (exitCode) => - Effect.sleep(EXIT_DRAIN_GRACE).pipe( - Effect.andThen( - failTransport( - new ZcodeProtocolError({ - operation: "read", - detail: `zcode app-server exited with code ${exitCode}, but stdout never closed`, - }), - ), - ), - ), - }), - Effect.forkIn(scope), - ); - - yield* Effect.gen(function* () { - const frame = makeJsonlFramer(); - yield* child.stdout.pipe( - Stream.decodeText(), - Stream.runForEach((chunk) => - Effect.gen(function* () { - const { lines, droppedLengths } = frame(chunk); - yield* logDroppedZcodeRecords(droppedLengths); - for (const line of lines) { - const record = parseZcodeRecord(line); - if (record === undefined) { - yield* Effect.logDebug("Dropping non-JSON zcode stdout line.", { - lineLength: line.length, - }); - continue; - } - yield* routeRecord(record); - } - }), - ), - ); - const flushed = frame("\n"); - yield* logDroppedZcodeRecords(flushed.droppedLengths); - for (const line of flushed.lines) { - const trailing = parseZcodeRecord(line); - if (trailing !== undefined) yield* routeRecord(trailing); - } - }).pipe( - Effect.matchCauseEffect({ - onFailure: (cause) => failTransport(new ZcodeProtocolError({ operation: "read", cause })), - onSuccess: Effect.fnUntraced(function* () { - diagnosingStdoutClose = true; - const polled = yield* Deferred.poll(exitDeferred); - const maybeExitCode = Option.isSome(polled) - ? yield* polled.value.pipe( - Effect.asSome, - Effect.orElseSucceed(() => Option.none()), - ) - : yield* Deferred.await(exitDeferred).pipe( - Effect.timeoutOption(Duration.millis(250)), - // Stdout-close waits need wall time; TestClock would strand Stop-with-restart without an exit. - Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()), - Effect.orElseSucceed(() => Option.none()), - ); - return yield* failTransport( - new ZcodeProtocolError({ - operation: "read", - detail: describeZcodeStdoutClosure( - Option.isSome(maybeExitCode) ? maybeExitCode.value : undefined, - ), - }), - ); - }), - }), - Effect.forkIn(scope), - ); - - yield* child.stderr.pipe( - Stream.decodeText(), - Stream.runForEach((chunk) => - chunk.trim().length === 0 - ? Effect.void - : Effect.logDebug("zcode app-server stderr", { stderrLength: chunk.length }), - ), - Effect.ignore, - Effect.forkIn(scope), - ); - - yield* Stream.fromQueue(outgoing).pipe( - Stream.run(child.stdin), - Effect.catchCause((cause) => - diagnosingStdoutClose - ? Effect.void - : failTransport(new ZcodeProtocolError({ operation: "write", cause })), - ), - Effect.forkIn(scope), - ); - - const send = - /* Streaming deltas ride through here; avoid a span per record. */ - Effect.fnUntraced(function* (record: ZcodeRecord): Effect.fn.Return { - const accepted = yield* Queue.offer( - outgoing, - new TextEncoder().encode(`${encodeJsonLine(record)}\n`), - ); - if (!accepted) { - return yield* Deferred.await(transportDown); - } - }); - - const request = Effect.fn("ZcodeProtocol.request")(function* ( - method: string, - params: ZcodeRecord, - timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, - ): Effect.fn.Return { - const id = nextRequestId++; - const deferred = yield* Deferred.make(); - pendingRequests.set(String(id), { deferred, method }); - yield* send({ id, method, params }).pipe( - Effect.tapError(() => Effect.sync(() => pendingRequests.delete(String(id)))), - ); - return yield* Effect.raceFirst(Deferred.await(deferred), Deferred.await(transportDown)).pipe( - Effect.timeoutOrElse({ - duration: Duration.millis(timeoutMs), - orElse: () => Effect.fail(new ZcodeProtocolTimeoutError({ operation: method, timeoutMs })), - }), - Effect.onInterrupt(() => Effect.sync(() => pendingRequests.delete(String(id)))), - Effect.onError(() => Effect.sync(() => pendingRequests.delete(String(id)))), - ); - }); - - const respond = Effect.fnUntraced(function* ( - id: string, - result: unknown, - ): Effect.fn.Return { - yield* send({ id, result }); - }); - - return { - request, - respond, - events, - exited: Deferred.await(exitDeferred), - terminate: failTransport( - new ZcodeProtocolError({ - operation: "terminate", - detail: "zcode app-server was stopped", - }), - ).pipe(Effect.andThen(terminateProcess), Effect.ignore, Effect.uninterruptible), - } satisfies ZcodeConnection; -}); diff --git a/packages/provider-zcode/src/server/zcodeRequestAuth.test.ts b/packages/provider-zcode/src/server/zcodeRequestAuth.test.ts deleted file mode 100644 index b85c402b959a7..0000000000000 --- a/packages/provider-zcode/src/server/zcodeRequestAuth.test.ts +++ /dev/null @@ -1,236 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -- tests craft the CLI's own AES-GCM store values with node crypto -import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as HostProcess from "@t3tools/shared/HostProcess"; -import { assert, describe, it } from "@effect/vitest"; -import * as NodeCrypto from "node:crypto"; -import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as HttpClient from "effect/http/HttpClient"; -import * as HttpClientResponse from "effect/http/HttpClientResponse"; - -import { - decryptZcodeCredential, - makeZcodeRequestAuth, - resolveZcodeCredentialSecret, - zcodeAccountScope, - zcodeFamilyFromProviderId, -} from "./zcodeRequestAuth.ts"; -import { zcodeRecordField, zcodeRecordString } from "./zcodeProtocol.ts"; - -/** Produces store values the CLI's fallback cipher would hold, keyed the same way. */ -const encryptZcodeCredential = (value: string, secret: string): string => { - const iv = NodeCrypto.randomBytes(12); - const cipher = NodeCrypto.createCipheriv( - "aes-256-gcm", - NodeCrypto.createHash("sha256").update(secret).digest(), - iv, - ); - const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]); - return `enc:v1:${iv.toString("base64url")}.${cipher.getAuthTag().toString("base64url")}.${ciphertext.toString("base64url")}`; -}; - -describe("resolveZcodeCredentialSecret", () => { - it("prefers ZCODE_CREDENTIAL_SECRET and trims it", () => { - assert.equal( - resolveZcodeCredentialSecret({ ZCODE_CREDENTIAL_SECRET: " custom-secret " }, "linux"), - "custom-secret", - ); - const blankOverride = resolveZcodeCredentialSecret( - { ZCODE_CREDENTIAL_SECRET: " ", HOME: "/home/dev" }, - "linux", - ); - assert.match(blankOverride, /^zcode-credential-fallback:linux:\/home\/dev:/); - }); - - it("derives the CLI's machine-bound fallback with the HOME from the environment", () => { - // Username comes from os.userInfo() where resolvable (env names never win); on runtimes - // where it throws, the env fallback speaks. Only the stable parts are asserted here. - const secret = resolveZcodeCredentialSecret( - { USER: "someoneElse", HOME: "/home/dev" }, - "darwin", - ); - assert.match(secret, /^zcode-credential-fallback:darwin:\/home\/dev:/); - assert.match(resolveZcodeCredentialSecret({}, "linux"), /^zcode-credential-fallback:linux:/); - }); -}); - -describe("decryptZcodeCredential", () => { - it("round-trips the CLI's encrypted store values", () => { - const secret = "zcode-credential-fallback:linux:/home/dev:jame"; - for (const plaintext of ["oauth-login-token", "值-with-unicode 🔐", ""]) { - assert.equal( - decryptZcodeCredential(encryptZcodeCredential(plaintext, secret), secret), - plaintext, - ); - } - }); - - it("passes plain store values through and rejects malformed ciphertext", () => { - assert.equal(decryptZcodeCredential("plain-token", "s"), "plain-token"); - assert.throws(() => decryptZcodeCredential("enc:v1:not-a-cipher", "s")); - assert.throws(() => decryptZcodeCredential("enc:v1:only.two", "s")); - }); -}); - -describe("zcodeFamilyFromProviderId", () => { - it("maps account plan provider ids to their auth family", () => { - assert.equal(zcodeFamilyFromProviderId("account:zai-individual-coding-plan"), "zai"); - assert.equal(zcodeFamilyFromProviderId("account:bigmodel-individual-coding-plan"), "bigmodel"); - assert.equal(zcodeFamilyFromProviderId("account:zai"), "zai"); - }); - - it("returns undefined for provider ids outside the account namespace", () => { - assert.equal(zcodeFamilyFromProviderId(undefined), undefined); - assert.equal(zcodeFamilyFromProviderId("account:"), undefined); - assert.equal(zcodeFamilyFromProviderId(""), undefined); - }); -}); - -describe("zcodeAccountScope", () => { - it("digests the plan identity, login token, and JWT exactly like the CLI", () => { - assert.equal( - zcodeAccountScope("zai", "login-token", undefined), - NodeCrypto.createHash("sha256") - .update(JSON.stringify(["zai", "individual-coding-plan", null, "login-token", null])) - .digest("hex"), - ); - assert.equal( - zcodeAccountScope("zai", "login-token", "jwt"), - NodeCrypto.createHash("sha256") - .update(JSON.stringify(["zai", "individual-coding-plan", null, "login-token", "jwt"])) - .digest("hex"), - ); - }); - - it("is deterministic and changes with any input", () => { - assert.equal( - zcodeAccountScope("zai", "tok", undefined), - zcodeAccountScope("zai", "tok", undefined), - ); - assert.notEqual( - zcodeAccountScope("zai", "tok", undefined), - zcodeAccountScope("bigmodel", "tok", undefined), - ); - assert.notEqual( - zcodeAccountScope("zai", "tok", undefined), - zcodeAccountScope("zai", "tok2", undefined), - ); - }); -}); - -describe("makeZcodeRequestAuth", () => { - /** A temp data root with the zai login on disk plus an HTTP fake answering the mint chain. */ - const harness = Effect.fnUntraced(function* (clientVersion: string | undefined) { - const fileSystem = yield* FileSystem.FileSystem; - const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "zcode-request-auth-test-" }); - yield* fileSystem.makeDirectory(`${root}/.zcode/v2`, { recursive: true }); - const platform = yield* HostProcess.Platform; - const environment = { ZCODE_DATA_BASE_DIR: root, HOME: "/home/dev", USER: "dev" }; - const secret = resolveZcodeCredentialSecret(environment, platform); - const writeLogin = (loginToken: string | undefined) => - fileSystem.writeFileString( - `${root}/.zcode/v2/credentials.json`, - JSON.stringify( - loginToken === undefined - ? {} - : { "oauth:zai:access_token": encryptZcodeCredential(loginToken, secret) }, - ), - ); - yield* writeLogin("login-a"); - const exchangeLogins: Array = []; - const exchangeBodies: Array = []; - const httpClient = HttpClient.make((request, url) => { - const ok = (data: unknown) => - Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ code: 200, data }))); - if (url.pathname.endsWith("/api/biz/customer/getCustomerInfo")) { - return ok({ - organizations: [ - { - organizationId: "org-1", - organizationName: "默认机构", - projects: [{ projectId: "proj-1", projectName: "默认项目" }], - }, - ], - }); - } - if (url.pathname.endsWith("/api_keys")) { - return ok([{ name: "zcode-api-key", apiKey: "key-1" }]); - } - exchangeLogins.push((request.headers.authorization ?? "").replace(/^Bearer /, "")); - exchangeBodies.push( - request.body._tag === "Uint8Array" - ? JSON.parse(new TextDecoder().decode(request.body.body)) - : undefined, - ); - return ok({ accessToken: `access-token-${exchangeLogins.length}` }); - }); - return { - auth: makeZcodeRequestAuth({ fileSystem, httpClient, environment, clientVersion }), - writeLogin, - exchangeLogins, - exchangeBodies, - }; - }); - - const requestAuthOf = (response: unknown): Record => - (zcodeRecordField(response, "requestAuth") ?? {}) as Record; - - it.effect("serves a cache hit while the family's credentials stay the same", () => - Effect.gen(function* () { - const h = yield* harness("test"); - const first = yield* h.auth.answerRuntimeHeaders({ family: "zai" }); - assert.equal(zcodeRecordString(requestAuthOf(first), "apiKey"), "access-token-1"); - assert.equal( - zcodeRecordString(requestAuthOf(first), "accountScope"), - zcodeAccountScope("zai", "login-a", undefined), - ); - // The CLI may rewrite the store with a fresh IV for the same token; the credential scope, - // not the ciphertext, must decide validity. - yield* h.writeLogin("login-a"); - const second = yield* h.auth.answerRuntimeHeaders({ family: "zai" }); - assert.equal(zcodeRecordString(requestAuthOf(second), "apiKey"), "access-token-1"); - assert.deepEqual(h.exchangeLogins, ["login-a"]); - }).pipe(Effect.provide(NodeServices.layer)), - ); - - it.effect("re-mints against the new account when the family's login changes", () => - Effect.gen(function* () { - const h = yield* harness("test"); - const first = yield* h.auth.answerRuntimeHeaders({ family: "zai" }); - assert.equal(zcodeRecordString(requestAuthOf(first), "apiKey"), "access-token-1"); - yield* h.writeLogin("login-b"); - const second = yield* h.auth.answerRuntimeHeaders({ family: "zai" }); - assert.equal(zcodeRecordString(requestAuthOf(second), "apiKey"), "access-token-2"); - assert.equal( - zcodeRecordString(requestAuthOf(second), "accountScope"), - zcodeAccountScope("zai", "login-b", undefined), - ); - assert.equal(zcodeRecordString(requestAuthOf(second), "apiKeyId"), "key-1"); - assert.deepEqual(h.exchangeLogins, ["login-a", "login-b"]); - }).pipe(Effect.provide(NodeServices.layer)), - ); - - it.effect("declines once the family's login disappears", () => - Effect.gen(function* () { - const h = yield* harness("test"); - const first = yield* h.auth.answerRuntimeHeaders({ family: "zai" }); - assert.equal(zcodeRecordString(requestAuthOf(first), "apiKey"), "access-token-1"); - yield* h.writeLogin(undefined); - const second = yield* h.auth.answerRuntimeHeaders({ family: "zai" }); - assert.equal(zcodeRecordField(second, "headersApplied"), false); - assert.match(zcodeRecordString(second, "errorMessage") ?? "", /no OAuth login for family/); - assert.deepEqual(h.exchangeLogins, ["login-a"]); - }).pipe(Effect.provide(NodeServices.layer)), - ); - - it.effect("reports the installed CLI version in the token exchange only when known", () => - Effect.gen(function* () { - const known = yield* harness("3.17.2"); - yield* known.auth.answerRuntimeHeaders({ family: "zai" }); - const unknown = yield* harness(undefined); - yield* unknown.auth.answerRuntimeHeaders({ family: "zai" }); - assert.deepEqual(known.exchangeBodies, [{ clientType: "zcode", clientVersion: "3.17.2" }]); - assert.deepEqual(unknown.exchangeBodies, [{ clientType: "zcode" }]); - }).pipe(Effect.provide(NodeServices.layer)), - ); -}); diff --git a/packages/provider-zcode/src/server/zcodeRequestAuth.ts b/packages/provider-zcode/src/server/zcodeRequestAuth.ts deleted file mode 100644 index d54975e429918..0000000000000 --- a/packages/provider-zcode/src/server/zcodeRequestAuth.ts +++ /dev/null @@ -1,630 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -- the push revision hashes the injected catalog path with sha256 -// Account provisioning and request auth for the ZCode CLI: the entitlement ladder behind the -// `provider/updateAccountConfig` push, and the OAuth project-token exchange that answers -// `interaction/requestProviderRuntimeHeaders` before every account-model request. Verified -// end-to-end against zcode 3.17.2 (PROTOCOL-NOTES.md); the desktop host performs the same -// exchanges. -import * as NodeCrypto from "node:crypto"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; - -import { causeErrorTag } from "@t3tools/shared/observability"; -import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as HttpClient from "effect/http/HttpClient"; -import * as HttpClientRequest from "effect/http/HttpClientRequest"; -import * as HttpClientResponse from "effect/http/HttpClientResponse"; -import * as Option from "effect/Option"; -import * as Predicate from "effect/Predicate"; -import * as Result from "effect/Result"; -import * as Schema from "effect/Schema"; - -import { - zcodeJsonStringify, - zcodeRecordArray, - zcodeRecordField, - zcodeRecordString, - type ZcodeRecord, -} from "./zcodeProtocol.ts"; -import { zcodeDataRoot } from "./zcodeRuntime.ts"; - -const ENCRYPTED_PREFIX = "enc:v1:"; -const CIPHER_ALGORITHM = "aes-256-gcm"; -const ZCODE_JWT_CREDENTIAL_KEY = "zcodejwttoken"; -const ZCODE_API_KEY_NAME = "zcode-api-key"; -const TEAM_PROJECT_TYPE = "2"; -const DEFAULT_ORGANIZATION_NAME = "默认机构"; -const DEFAULT_PROJECT_NAME = "默认项目"; -const REQUEST_TIMEOUT_MS = 15_000; -const TOKEN_TTL_MS = 10 * 60_000; -/** Refresh the cached project token this long before expiry so a queued request never stalls. */ -const TOKEN_REFRESH_MARGIN_MS = 120_000; - -const FAMILY_ORIGIN: Record = { - zai: "https://api.z.ai", - bigmodel: "https://bigmodel.cn", -}; - -const sha256Hex = (value: string): string => - NodeCrypto.createHash("sha256").update(value).digest("hex"); - -/** - * The CLI's machine-bound fallback cipher secret: sha256 of this string keys the store's - * AES-256-GCM values. ZCODE_CREDENTIAL_SECRET overrides it for custom installs. - */ -export const resolveZcodeCredentialSecret = ( - environment: NodeJS.ProcessEnv, - platform: NodeJS.Platform, -): string => { - const configured = environment.ZCODE_CREDENTIAL_SECRET?.trim(); - if (configured !== undefined && configured.length > 0) return configured; - // The CLI binds the fallback to os.userInfo().username — env USER/USERNAME may be absent in - // server processes and must not silently derive a different key. - let username = "unknown"; - try { - username = NodeOS.userInfo().username; - } catch { - username = environment.USER ?? environment.USERNAME ?? "unknown"; - } - const home = environment.HOME ?? NodeOS.homedir(); - return `zcode-credential-fallback:${platform}:${home}:${username}`; -}; - -export const decryptZcodeCredential = (value: string, secret: string): string => { - if (!value.startsWith(ENCRYPTED_PREFIX)) return value; - const [ivRaw, tagRaw, cipherRaw] = value.slice(ENCRYPTED_PREFIX.length).split("."); - if (ivRaw === undefined || tagRaw === undefined || cipherRaw === undefined) { - throw new Error("Encrypted credential is not ..."); - } - const decipher = NodeCrypto.createDecipheriv( - CIPHER_ALGORITHM, - NodeCrypto.createHash("sha256").update(secret).digest(), - Buffer.from(ivRaw, "base64url"), - ); - decipher.setAuthTag(Buffer.from(tagRaw, "base64url")); - return Buffer.concat([ - decipher.update(Buffer.from(cipherRaw, "base64url")), - decipher.final(), - ]).toString("utf8"); -}; - -const decodeJsonText = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); - -interface CredentialStoreCache { - digest: string; - store: Record; -} - -const readDecryptedCredentialStore = Effect.fn("ZcodeRequestAuth.readCredentialStore")(function* ( - fileSystem: FileSystem.FileSystem, - credentialsPath: string, - environment: NodeJS.ProcessEnv, - platform: NodeJS.Platform, - cache?: CredentialStoreCache, -): Effect.fn.Return> { - const raw = yield* fileSystem.readFileString(credentialsPath).pipe(Effect.option); - if (Option.isNone(raw)) return {}; - // Content, not mtime: a rewrite can land in the same timestamp tick, and a stale login token - // would mint project tokens against the previous account. - const digest = sha256Hex(raw.value); - if (cache !== undefined && cache.digest === digest) return cache.store; - const parsed = Option.getOrUndefined(decodeJsonText(raw.value)); - if (!Predicate.isObject(parsed)) return {}; - const secret = resolveZcodeCredentialSecret(environment, platform); - const entries: Record = {}; - for (const [key, value] of Object.entries(parsed)) { - if (typeof value !== "string") continue; - const decrypted = yield* Effect.try({ - try: () => decryptZcodeCredential(value, secret), - catch: () => undefined, - }).pipe(Effect.option); - if (Option.isSome(decrypted)) entries[key] = decrypted.value; - } - if (cache !== undefined) { - cache.digest = digest; - cache.store = entries; - } - return entries; -}); - -/** - * Families the provisioning ladder treats as signed-in OAuth individual coding plans: setting.json - * selects the plan, no apiKey override, and the credential store holds a login token for the - * family. The provider status probe derives its auth display from this same predicate so the - * probe and provisioning cannot drift. - */ -export const zcodeOAuthSelectedFamilies = ( - setting: unknown, - store: Record, -): ReadonlySet => { - if (!Predicate.isObject(setting)) return new Set(); - const selections = setting["providerFamilyConnectionSelections"]; - const modes = setting["modelProviderFamilyModes"]; - const families = new Set(); - if (!Predicate.isObject(selections)) return families; - for (const [family, selection] of Object.entries(selections)) { - const kind = Predicate.isObject(selection) ? selection["kind"] : undefined; - if (kind !== "individual-coding-plan") continue; - if (Predicate.isObject(modes) && modes[family] === "apiKey") continue; - const token = store[`oauth:${family}:access_token`]; - if (typeof token !== "string" || token.length === 0) continue; - families.add(family); - } - return families; -}; - -/** Families whose 3.15+ connection is an active OAuth individual coding plan. */ -const readOAuthSelectedFamilies = Effect.fn("ZcodeRequestAuth.readOAuthFamilies")(function* ( - fileSystem: FileSystem.FileSystem, - settingPath: string, - store: Record, -): Effect.fn.Return> { - const raw = yield* fileSystem.readFileString(settingPath).pipe(Effect.option); - const parsed = Option.isNone(raw) ? undefined : Option.getOrUndefined(decodeJsonText(raw.value)); - return zcodeOAuthSelectedFamilies(parsed, store); -}); - -export type ZcodeAccountProviderPush = { - readonly builtinModelIds: ReadonlyArray; - readonly access: { readonly type: "zhipu-account"; readonly entitled: boolean }; -}; - -export type ZcodeAccountStatePush = { - readonly availability: "available" | "unavailable"; - readonly entitled: boolean; - readonly current: boolean; -}; - -export type ZcodeAccountConfigPush = { - readonly revision: string; - readonly basedOnZCodeBuiltinRevision: string; - readonly providers: Record; - readonly states: Record; -}; - -const zcodeRuleAccess = (rule: unknown): ZcodeRecord | undefined => { - const access = zcodeRecordField(zcodeRecordField(rule, "config"), "access"); - return Predicate.isObject(access) ? access : undefined; -}; - -const zcodeBuiltinAccountRules = (builtinCatalog: unknown): ReadonlyArray => { - const providerRules = zcodeRecordArray( - zcodeRecordField(zcodeRecordField(builtinCatalog, "config"), "providerConfigRules"), - "providerRules", - ); - return (providerRules ?? []).filter( - (rule): rule is ZcodeRecord => - Predicate.isObject(rule) && - zcodeRecordString(zcodeRuleAccess(rule), "type") === "zhipu-account", - ); -}; - -const zcodeBuiltinModelIds = (rule: ZcodeRecord): ReadonlyArray => { - const ids = zcodeRecordField(zcodeRecordField(rule, "config"), "builtinModelIds"); - return (Array.isArray(ids) ? ids : []).filter( - (id): id is string => typeof id === "string" && id.length > 0, - ); -}; - -/** The registry keys the snapshot to `zcode-builtin::` of the catalog - * file the CLI booted from; any other value is accepted and silently ignored. */ -const zcodeBuiltinBasedOnRevision = (builtinPath: string, builtinCatalog: unknown): string => { - const revision = zcodeRecordField(builtinCatalog, "revision"); - const revisionText = - typeof revision === "number" && Number.isFinite(revision) - ? String(Math.trunc(revision)) - : typeof revision === "string" && revision.length > 0 - ? revision - : "0"; - return `zcode-builtin:${revisionText}:${sha256Hex(NodePath.resolve(builtinPath))}`; -}; - -/** - * Builds the `provider/updateAccountConfig` push from the builtin catalog's zhipu-account rules - * and the entitlement ladder: a family is entitled only when the user picked an OAuth - * individual coding plan for it and the credential store decrypts to its login token. - */ -export const zcodeAccountConfigPushFromLadder = Effect.fn("ZcodeRequestAuth.buildAccountPush")( - function* ( - fileSystem: FileSystem.FileSystem, - input: { - readonly builtinPath: string; - readonly builtinCatalog: unknown; - readonly environment: NodeJS.ProcessEnv; - }, - ): Effect.fn.Return { - const rules = zcodeBuiltinAccountRules(input.builtinCatalog); - if (rules.length === 0) return undefined; - const root = zcodeDataRoot(input.environment); - if (root === undefined) return undefined; - const store = yield* readDecryptedCredentialStore( - fileSystem, - `${root}/.zcode/v2/credentials.json`, - input.environment, - yield* HostProcess.Platform, - ); - const families = yield* readOAuthSelectedFamilies( - fileSystem, - `${root}/.zcode/v2/setting.json`, - store, - ); - const providers: Record = {}; - const states: Record = {}; - for (const rule of rules) { - const providerId = zcodeRecordString(rule, "providerId"); - const modelIds = zcodeBuiltinModelIds(rule); - if (providerId === undefined || modelIds.length === 0) continue; - const entitled = - zcodeRecordString(zcodeRuleAccess(rule), "mode") === "individual-coding-plan" && - families.has(zcodeRecordString(zcodeRuleAccess(rule), "accountType") ?? ""); - providers[providerId] = { - builtinModelIds: modelIds, - access: { type: "zhipu-account", entitled }, - }; - states[providerId] = { - availability: entitled ? "available" : "unavailable", - entitled, - current: entitled, - }; - } - if (Object.keys(providers).length === 0) return undefined; - return { - revision: `account:t3code:${DateTime.toEpochMillis(yield* DateTime.now)}`, - basedOnZCodeBuiltinRevision: zcodeBuiltinBasedOnRevision( - input.builtinPath, - input.builtinCatalog, - ), - providers, - states, - }; - }, -); - -/** - * Entitled individual-coding-plan models for the model picker: enumerated from the injected - * catalog plus the entitlement ladder, so a catalog refresh by the CLI adds models without an - * adapter change. Reasoning levels come from the catalog's modelRules (modelMatch regexes, - * matched case-insensitively against the model id). - */ -export interface ZcodeEntitledModel { - readonly providerId: string; - readonly modelId: string; - readonly reasoningLevels: ReadonlyArray; -} - -export const zcodeEntitledModels = Effect.fn("ZcodeRequestAuth.entitledModels")(function* ( - fileSystem: FileSystem.FileSystem, - input: { - readonly builtinPath: string; - readonly builtinCatalog: unknown; - readonly environment: NodeJS.ProcessEnv; - }, -): Effect.fn.Return, never, never> { - const rules = zcodeBuiltinAccountRules(input.builtinCatalog); - const root = zcodeDataRoot(input.environment); - if (rules.length === 0 || root === undefined) return []; - const store = yield* readDecryptedCredentialStore( - fileSystem, - `${root}/.zcode/v2/credentials.json`, - input.environment, - yield* HostProcess.Platform, - ); - const families = yield* readOAuthSelectedFamilies( - fileSystem, - `${root}/.zcode/v2/setting.json`, - store, - ); - const modelRules = zcodeRecordArray( - zcodeRecordField(zcodeRecordField(input.builtinCatalog, "config"), "modelConfigRules"), - "modelRules", - ); - const levelsFor = (modelId: string): ReadonlyArray => { - // Later matching rules compose over earlier ones (the runtime's advertised levels are the - // last match: Flash hits glm-5.* then glm-5\.3, landing on [low, high, max]). - let levels: ReadonlyArray = []; - for (const rule of modelRules ?? []) { - const match = zcodeRecordString(rule, "modelMatch"); - if (match === undefined) continue; - let regex: RegExp; - try { - regex = new RegExp(match, "i"); - } catch { - continue; - } - if (!regex.test(modelId)) continue; - const specs = zcodeRecordField(zcodeRecordField(rule, "config"), "optionSpecs"); - const reasoning = zcodeRecordField(Predicate.isObject(specs) ? specs : {}, "reasoningLevel"); - const values = zcodeRecordArray(reasoning, "values")?.filter( - (value): value is string => typeof value === "string", - ); - if (values !== undefined && values.length > 0) levels = values; - } - return levels; - }; - const out: Array = []; - for (const rule of rules) { - const providerId = zcodeRecordString(rule, "providerId"); - const access = zcodeRuleAccess(rule); - if ( - providerId === undefined || - zcodeRecordString(access, "mode") !== "individual-coding-plan" || - !families.has(zcodeRecordString(access, "accountType") ?? "") - ) { - continue; - } - for (const modelId of zcodeBuiltinModelIds(rule)) { - out.push({ providerId, modelId, reasoningLevels: levelsFor(modelId) }); - } - } - return out; -}); - -/** `account:-individual-coding-plan` → the plan family the auth exchange needs. */ -export const zcodeFamilyFromProviderId = (providerId: string | undefined): string | undefined => { - const family = providerId?.replace(/^account:/, "").replace(/-individual-coding-plan$/, ""); - return family === undefined || family.length === 0 ? undefined : family; -}; - -/** Mirrors the CLI's account-scope digest over the plan identity and login tokens. */ -export const zcodeAccountScope = ( - family: string, - loginToken: string, - jwtToken: string | undefined, -): string => - sha256Hex( - zcodeJsonStringify([family, "individual-coding-plan", null, loginToken, jwtToken ?? null]), - ); - -class ZcodeRequestAuthError extends Schema.TaggedError()( - "ZcodeRequestAuthError", - { message: Schema.String }, -) {} - -const declineMessage = (hint: string): string => `ZCode request auth failed (${hint}).`; - -const failAuth = (hint: string) => new ZcodeRequestAuthError({ message: declineMessage(hint) }); - -interface CachedProjectToken { - readonly token: string; - readonly apiKeyId: string; - readonly accountScope: string; - readonly fingerprint: string; - readonly refreshAtMillis: number; -} - -export interface ZcodeRequestAuth { - /** The `interaction/requestProviderRuntimeHeaders` response for an entitled account model. */ - readonly answerRuntimeHeaders: (input: { - readonly family: string; - readonly rejectedProjectTokenFingerprint?: string; - }) => Effect.Effect; -} - -export interface ZcodeRequestAuthOptions { - readonly fileSystem: FileSystem.FileSystem; - readonly httpClient: HttpClient.HttpClient; - readonly environment: NodeJS.ProcessEnv; - /** The installed CLI's version, as its own host reports it; omitted when unknown. */ - readonly clientVersion?: string | undefined; -} - -/** - * Serves OAuth project tokens for entitled individual coding plans, mirroring the desktop - * host's exchange: customer info → personal default project → the account's `zcode-api-key` → - * a short-lived access token. Read-only towards the account; a missing key surfaces as a - * decline the turn reports honestly. - */ -export const makeZcodeRequestAuth = (options: ZcodeRequestAuthOptions): ZcodeRequestAuth => { - const root = zcodeDataRoot(options.environment) ?? ""; - const credentialsPath = `${root}/.zcode/v2/credentials.json`; - const cache = new Map(); - const credentialCache: CredentialStoreCache = { digest: "", store: {} }; - - /** The family's current login with the credential scope digesting it; undefined once gone. */ - const currentLogin = Effect.fn("ZcodeRequestAuth.currentLogin")(function* ( - family: string, - ): Effect.fn.Return<{ loginToken: string; accountScope: string } | undefined> { - const store = yield* readDecryptedCredentialStore( - options.fileSystem, - credentialsPath, - options.environment, - yield* HostProcess.Platform, - credentialCache, - ); - const loginToken = store[`oauth:${family}:access_token`]; - if (loginToken === undefined || loginToken.length === 0) return undefined; - return { - loginToken, - accountScope: zcodeAccountScope(family, loginToken, store[ZCODE_JWT_CREDENTIAL_KEY]), - }; - }); - - const requestJson = (request: HttpClientRequest.HttpClientRequest) => - options.httpClient.execute(request).pipe( - Effect.flatMap(HttpClientResponse.filterStatusOk), - Effect.flatMap((response) => response.json), - Effect.timeoutOption(REQUEST_TIMEOUT_MS), - Effect.map((answered) => (Option.isSome(answered) ? answered.value : undefined)), - Effect.orElseSucceed(() => undefined), - ); - - const envelopeData = Effect.fnUntraced(function* ( - raw: unknown, - exchange: string, - ): Effect.fn.Return { - const code = Predicate.isObject(raw) ? raw["code"] : undefined; - if (!(code === 0 || code === 200 || code === "0" || code === "200")) { - return yield* failAuth(`${exchange} code=${String(code)}`); - } - return Predicate.isObject(raw) ? raw["data"] : undefined; - }); - - const mint = Effect.fn("ZcodeRequestAuth.mint")(function* ( - family: string, - ): Effect.fn.Return { - const login = yield* currentLogin(family); - if (login === undefined) { - return yield* failAuth("no OAuth login for family"); - } - const origin = FAMILY_ORIGIN[family]; - if (origin === undefined) { - return yield* failAuth(`unknown family ${family}`); - } - const customer = yield* envelopeData( - yield* requestJson( - HttpClientRequest.get(`${origin}/api/biz/customer/getCustomerInfo`, { - headers: { Authorization: login.loginToken }, - }), - ), - "getCustomerInfo", - ); - const organizations: Array<{ - organizationId: string; - organizationName?: string; - projects: Array<{ projectId: string; projectName?: string }>; - }> = []; - const rawOrganizations = Predicate.isObject(customer) ? customer["organizations"] : undefined; - for (const rawOrg of Array.isArray(rawOrganizations) ? rawOrganizations : []) { - if (!Predicate.isObject(rawOrg)) continue; - const organizationId = zcodeRecordString(rawOrg, "organizationId"); - if (organizationId === undefined || organizationId.length === 0) continue; - const projects: Array<{ projectId: string; projectName?: string }> = []; - const rawProjects = zcodeRecordField(rawOrg, "projects"); - for (const rawProject of Array.isArray(rawProjects) ? rawProjects : []) { - if (!Predicate.isObject(rawProject)) continue; - const projectId = zcodeRecordString(rawProject, "projectId"); - if (projectId === undefined || projectId.length === 0) continue; - if (String(zcodeRecordField(rawProject, "projectType") ?? "").trim() === TEAM_PROJECT_TYPE) - continue; - projects.push({ - projectId, - ...(typeof rawProject["projectName"] === "string" - ? { projectName: rawProject["projectName"] } - : {}), - }); - } - if (projects.length === 0) continue; - organizations.push({ - organizationId, - ...(typeof rawOrg["organizationName"] === "string" - ? { organizationName: rawOrg["organizationName"] } - : {}), - projects, - }); - } - const org = - organizations.find((entry) => entry.organizationName?.includes(DEFAULT_ORGANIZATION_NAME)) ?? - organizations[0]; - const project = - org?.projects.find((entry) => entry.projectName?.includes(DEFAULT_PROJECT_NAME)) ?? - org?.projects[0]; - if (org === undefined || project === undefined) { - return yield* failAuth("no personal project"); - } - const keysPath = `${origin}/api/biz/v1/organization/${encodeURIComponent(org.organizationId)}/projects/${encodeURIComponent(project.projectId)}/api_keys`; - const keys = yield* envelopeData( - yield* requestJson( - HttpClientRequest.get(keysPath, { - headers: { - Authorization: family === "zai" ? `Bearer ${login.loginToken}` : login.loginToken, - }, - }), - ), - "api_keys", - ); - const keyList = Array.isArray(keys) ? keys : []; - const key = keyList.find( - (entry) => Predicate.isObject(entry) && entry["name"] === ZCODE_API_KEY_NAME, - ); - const apiKeyId = - Predicate.isObject(key) && typeof key["apiKey"] === "string" ? key["apiKey"] : undefined; - if (apiKeyId === undefined || apiKeyId.length === 0) { - return yield* failAuth("account has no zcode-api-key; open the ZCode app once"); - } - const exchangeRequest = HttpClientRequest.post( - `${keysPath}/${encodeURIComponent(apiKeyId)}/access_tokens`, - { headers: { Authorization: `Bearer ${login.loginToken}` } }, - ).pipe( - HttpClientRequest.bodyText( - zcodeJsonStringify({ - clientType: "zcode", - ...(options.clientVersion === undefined ? {} : { clientVersion: options.clientVersion }), - }), - "application/json", - ), - ); - const exchange = yield* envelopeData(yield* requestJson(exchangeRequest), "access_tokens"); - const token = - Predicate.isObject(exchange) && typeof exchange["accessToken"] === "string" - ? exchange["accessToken"] - : undefined; - if (token === undefined || token.length === 0) { - return yield* failAuth("token exchange returned no token"); - } - const cachedToken: CachedProjectToken = { - token, - apiKeyId, - accountScope: login.accountScope, - fingerprint: sha256Hex(token), - refreshAtMillis: - DateTime.toEpochMillis(yield* DateTime.now) + TOKEN_TTL_MS - TOKEN_REFRESH_MARGIN_MS, - }; - cache.set(family, cachedToken); - return cachedToken; - }); - - const answer = Effect.fn("ZcodeRequestAuth.answer")(function* (input: { - readonly family: string; - readonly rejectedProjectTokenFingerprint?: string; - }): Effect.fn.Return { - const hit = cache.get(input.family); - // A CLI login can swap accounts or log out under the same family; the cached scope digests - // the credentials, so reread them and drop the hit when they no longer match. - const currentScope = - hit === undefined ? undefined : (yield* currentLogin(input.family))?.accountScope; - const cached = - hit !== undefined && - currentScope === hit.accountScope && - DateTime.toEpochMillis(yield* DateTime.now) < hit.refreshAtMillis && - (input.rejectedProjectTokenFingerprint === undefined || - input.rejectedProjectTokenFingerprint !== hit.fingerprint) - ? hit - : undefined; - if (cached !== undefined) { - return { - headersApplied: true, - requestAuth: { - apiKey: cached.token, - apiKeyId: cached.apiKeyId, - accountScope: cached.accountScope, - }, - }; - } - const minted = yield* Effect.result(mint(input.family)); - return Result.isFailure(minted) - ? { headersApplied: false, errorMessage: minted.failure.message } - : { - headersApplied: true, - requestAuth: { - apiKey: minted.success.token, - apiKeyId: minted.success.apiKeyId, - accountScope: minted.success.accountScope, - }, - }; - }); - - return { - answerRuntimeHeaders: (input) => - answer(input).pipe( - // Any defect here would strand the CLI's request; decline instead. - Effect.catchCause((cause) => - Effect.succeed({ - headersApplied: false, - errorMessage: declineMessage(causeErrorTag(cause)), - } satisfies ZcodeRecord), - ), - ), - }; -}; diff --git a/packages/provider-zcode/src/server/zcodeRuntime.test.ts b/packages/provider-zcode/src/server/zcodeRuntime.test.ts index b01f3c69e982e..6367c7b7bf50d 100644 --- a/packages/provider-zcode/src/server/zcodeRuntime.test.ts +++ b/packages/provider-zcode/src/server/zcodeRuntime.test.ts @@ -7,10 +7,6 @@ import * as NodeOS from "node:os"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; -import { - resolveZcodeCredentialSecret, - zcodeAccountConfigPushFromLadder, -} from "./zcodeRequestAuth.ts"; import { resolveZcodeCatalogFiles, readZcodeAppVersion, @@ -23,7 +19,7 @@ import { zcodePersonalProviderConfigPath, zcodePlatformDir, zcodeRuntimeEnvironment, - zcodeSpawnArgs, + zcodeServeArgs, } from "./zcodeRuntime.ts"; // Verified against the on-disk zcode 3.17.2 runtime catalog directory for https://zcode.z.ai. @@ -86,18 +82,6 @@ const inlineCatalog = { }, }; -/** Produces store values the CLI's fallback cipher would hold, keyed the same way. */ -const encryptZcodeCredential = (value: string, secret: string): string => { - const iv = NodeCrypto.randomBytes(12); - const cipher = NodeCrypto.createCipheriv( - "aes-256-gcm", - NodeCrypto.createHash("sha256").update(secret).digest(), - iv, - ); - const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]); - return `enc:v1:${iv.toString("base64url")}.${cipher.getAuthTag().toString("base64url")}.${ciphertext.toString("base64url")}`; -}; - describe("zcodePlatformDir", () => { it("maps zcode's own platform spellings", () => { assert.equal(zcodePlatformDir("linux", "x64"), "linux-x86_64"); @@ -169,12 +153,11 @@ describe("zcodeBuiltinCatalogPath", () => { }); }); -describe("zcodeSpawnArgs", () => { - it("launches app-server --stdio with launch args split on whitespace", () => { - assert.deepEqual(zcodeSpawnArgs(""), ["app-server", "--stdio"]); - assert.deepEqual(zcodeSpawnArgs("--verbose --trace file "), [ - "app-server", - "--stdio", +describe("zcodeServeArgs", () => { + it("launches serve with launch args split on whitespace", () => { + assert.deepEqual(zcodeServeArgs(""), ["serve"]); + assert.deepEqual(zcodeServeArgs("--verbose --trace file "), [ + "serve", "--verbose", "--trace", "file", @@ -343,110 +326,6 @@ describe("zcodeRuntimeEnvironment", () => { }); }); -describe("zcodeAccountConfigPushFromLadder", () => { - it.effect( - "keys the push to the catalog path hash and maps the entitlement ladder onto providers and states", - () => - Effect.scoped( - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const root = yield* fs.makeTempDirectoryScoped({ prefix: "zcode-ladder-test-" }); - const platform = yield* HostProcess.Platform; - const environment = { ZCODE_DATA_BASE_DIR: root, HOME: "/home/dev", USER: "dev" }; - yield* fs.makeDirectory(`${root}/.zcode/v2`, { recursive: true }); - yield* fs.writeFileString( - `${root}/.zcode/v2/setting.json`, - JSON.stringify({ - providerFamilyConnectionSelections: { - zai: { kind: "individual-coding-plan" }, - bigmodel: { kind: "individual-coding-plan" }, - start: { kind: "individual-coding-plan" }, - }, - modelProviderFamilyModes: { bigmodel: "apiKey" }, - }), - ); - yield* fs.writeFileString( - `${root}/.zcode/v2/credentials.json`, - JSON.stringify({ - "oauth:zai:access_token": encryptZcodeCredential( - "zai-login-token", - resolveZcodeCredentialSecret(environment, platform), - ), - }), - ); - const builtinPath = `${root}/catalog/zcode-builtin.json`; - const push = yield* zcodeAccountConfigPushFromLadder(fs, { - builtinPath, - builtinCatalog: inlineCatalog, - environment, - }); - assert.isDefined(push); - // builtinPath is absolute, so the CLI-side path.resolve is a no-op here. - assert.equal( - push!.basedOnZCodeBuiltinRevision, - `zcode-builtin:43:${NodeCrypto.createHash("sha256").update(builtinPath).digest("hex")}`, - ); - assert.equal(push!.revision.startsWith("account:t3code:"), true); - assert.deepEqual(Object.keys(push!.providers), [ - "account:zai-individual-coding-plan", - "account:zai-team-coding-plan", - "account:bigmodel-individual-coding-plan", - "account:start-individual-coding-plan", - ]); - // OAuth selection + decrypted login token + plan-mode rule → entitled. - assert.deepEqual(push!.providers["account:zai-individual-coding-plan"], { - builtinModelIds: ["GLM-5.3", "GLM-5.3-Flash"], - access: { type: "zhipu-account", entitled: true }, - }); - assert.deepEqual(push!.states["account:zai-individual-coding-plan"], { - availability: "available", - entitled: true, - current: true, - }); - // Team-plan rules never entitle. - assert.equal(push!.states["account:zai-team-coding-plan"]!.availability, "unavailable"); - assert.equal(push!.states["account:zai-team-coding-plan"]!.entitled, false); - assert.equal(push!.states["account:zai-team-coding-plan"]!.current, false); - // A family switched to apiKey mode is excluded even with a selection. - assert.equal( - push!.states["account:bigmodel-individual-coding-plan"]!.availability, - "unavailable", - ); - // A selected family without a decryptable login token stays unentitled. - assert.equal(push!.states["account:start-individual-coding-plan"]!.entitled, false); - }), - ).pipe(Effect.provide(NodeServices.layer)), - ); - - it.effect("returns undefined without a usable catalog", () => - Effect.scoped( - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const noRules = yield* zcodeAccountConfigPushFromLadder(fs, { - builtinPath: "/tmp/builtin.json", - builtinCatalog: { config: { providerConfigRules: { providerRules: [] } } }, - environment: { HOME: "/home/dev" }, - }); - assert.equal(noRules, undefined); - const apiOnly = yield* zcodeAccountConfigPushFromLadder(fs, { - builtinPath: "/tmp/builtin.json", - builtinCatalog: { - config: { - providerConfigRules: { - providerRules: [ - { providerId: "kimi-api", config: { access: { type: "api-key" } } }, - ], - }, - }, - }, - environment: { HOME: "/home/dev" }, - }); - assert.equal(apiOnly, undefined); - }), - ).pipe(Effect.provide(NodeServices.layer)), - ); -}); - describe("zcodeModelSelectionFromSlug", () => { it("defers default slugs to the CLI's own default", () => { assert.equal(zcodeModelSelectionFromSlug("default"), undefined); @@ -512,19 +391,6 @@ it.layer(NodeServices.layer)("ZcodeRuntime catalog resolution", (it) => { assert.equal(resolved.builtinPath, `${builtinDir}/zcode-builtin.json`); assert.equal(resolved.bundledPath, undefined); assert.equal(resolved.personalPath, personalPath); - // No credentials or setting selection in this root: every rule pushes unentitled. - const push = yield* zcodeAccountConfigPushFromLadder(fs, { - builtinPath: resolved.builtinPath!, - builtinCatalog: resolved.builtinCatalog, - environment: { ZCODE_DATA_BASE_DIR: root }, - }); - assert.deepEqual(Object.keys(push?.providers ?? {}), [ - "account:zai-individual-coding-plan", - "account:zai-team-coding-plan", - "account:bigmodel-individual-coding-plan", - "account:start-individual-coding-plan", - ]); - assert.equal(push?.states["account:zai-individual-coding-plan"]?.entitled, false); }), ), ); diff --git a/packages/provider-zcode/src/server/zcodeRuntime.ts b/packages/provider-zcode/src/server/zcodeRuntime.ts index e4418499e21af..a9d0781824f0e 100644 --- a/packages/provider-zcode/src/server/zcodeRuntime.ts +++ b/packages/provider-zcode/src/server/zcodeRuntime.ts @@ -1,6 +1,6 @@ // @effect-diagnostics nodeBuiltinImport:off -- Catalog paths key on sha256 of the endpoint origin; Effect's crypto service adds a dependency the driver does not carry. -// Provisioning for `zcode app-server --stdio`: spawn args, catalog-backed environment, the -// account config push that makes catalog models selectable, and T3 model slug mapping. +// ZCode CLI locations and catalog discovery: the data root, the installed catalog files the +// model picker enumerates, the launch command and `serve` args, and T3 model slug mapping. // Everything protocol-shaped here mirrors the Phase 0 probe notes (PROTOCOL-NOTES.md). import * as NodeCrypto from "node:crypto"; import * as NodeOS from "node:os"; @@ -208,8 +208,8 @@ export function zcodeModelSelectionFromSlug(slug: string): ZcodeModelSelection | return { providerId, modelId, options: { reasoningLevel } }; } -export function zcodeSpawnArgs(launchArgs: string): ReadonlyArray { - return ["app-server", "--stdio", ...launchArgs.split(/\s+/).filter((arg) => arg.length > 0)]; +export function zcodeServeArgs(launchArgs: string): ReadonlyArray { + return ["serve", ...launchArgs.split(/\s+/).filter((arg) => arg.length > 0)]; } /** diff --git a/packages/provider-zcode/src/server/zcodeServeConnection.ts b/packages/provider-zcode/src/server/zcodeServeConnection.ts new file mode 100644 index 0000000000000..da0e5a2bd2958 --- /dev/null +++ b/packages/provider-zcode/src/server/zcodeServeConnection.ts @@ -0,0 +1,458 @@ +// Transport shim: presents the `zcode serve` daemon through the request/event surface the +// session layer already speaks. Requests map to daemon channel calls; events come from the +// row-based v4 conversation projection, folded by `zcodeServeConversation`. +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as HttpClient from "effect/http/HttpClient"; +import * as Predicate from "effect/Predicate"; +import * as Queue from "effect/Queue"; +import * as Schema from "effect/Schema"; +import * as Clock from "effect/Clock"; +import * as SecureRandom from "effect/crypto/SecureRandom"; + +import { + ZcodeProtocolError, + type ZcodeConnection, + type ZcodeProtocolTimeoutError, + type ZcodeRecord, +} from "./zcodeProtocol.ts"; +import { zcodeChannelUrl, connectZcodeServer } from "./zcodeServeDaemon.ts"; +import { + applyConversationPayload, + initialConversationState, + type ZcodeConversationState, +} from "./zcodeServeConversation.ts"; +import { makeZcodeChannelClient, type ZcodeChannelClient } from "./zcodeServeProtocol.ts"; + +const CLIENT_ID = "t3-code"; +const DEFAULT_TIMEOUT_MS = 30_000; +const CREATE_TIMEOUT_MS = 150_000; + +// Command ids only need to be unique, so draw from the process's own WebCrypto rather than +// threading a service through the adapter's fixed environment requirements. +const random = SecureRandom.make((size) => globalThis.crypto.getRandomValues(new Uint8Array(size))); + +export interface ZcodeServeConnectionOptions { + readonly environment: NodeJS.ProcessEnv; + readonly settings: { readonly binaryPath: string; readonly launchArgs: string }; + readonly cwd: string; + readonly fileSystem: FileSystem.FileSystem; + readonly httpClient: HttpClient.HttpClient; +} + +interface ZcodeWorkspaceParams { + readonly workspacePath: string; + readonly workspaceIdentity: string; + readonly projectId: string; +} + +const recordField = (record: unknown, key: string): unknown => + Predicate.isObject(record) ? record[key] : undefined; + +const recordString = (record: unknown, key: string): string | undefined => { + const value = recordField(record, key); + return Predicate.isString(value) ? value : undefined; +}; + +/** + * The daemon refuses to start a session for a workspace it has no project record for. The host + * channel here is a remote host, so `reuseExistingRoot` is rejected; match the root ourselves so + * repeated attaches do not mint duplicate projects. + */ +const resolveProjectId = Effect.fn("ZcodeServe.resolveProject")(function* ( + channel: ZcodeChannelClient, + workspacePath: string, +) { + const existing = yield* channel.call("project", "readProjects", { includeDeleted: false }); + const match = Array.isArray(existing) + ? existing.find((project) => { + if (!Predicate.isObject(project) || project["deleted"] === true) return false; + const roots = project["roots"]; + return Array.isArray(roots) && recordString(roots[0], "rootPath") === workspacePath; + }) + : undefined; + const existingId = recordString(match, "id"); + if (existingId !== undefined) return existingId; + + const saved = yield* channel.call("project", "saveProject", { + roots: [workspacePath], + primaryRoot: workspacePath, + defaultName: workspacePath.split(/[\\/]/).filter(Boolean).at(-1) ?? "zcode", + }); + const id = recordString(saved, "id"); + if (id === undefined) { + return yield* new ZcodeProtocolError({ + operation: "resolveProject", + detail: "zcode server did not return a project id for the workspace.", + }); + } + return id; +}); + +const isZcodeProtocolError = Schema.is(ZcodeProtocolError); + +const errorMessage = (error: unknown): string => + isZcodeProtocolError(error) + ? (error.detail ?? error.operation) + : error instanceof Error + ? error.message + : String(error); + +/** The daemon advertises its session model on the snapshot; the session layer only needs it as a default. */ +const availableModelDescriptors = ( + state: ZcodeConversationState, + settings: unknown, +): ReadonlyArray => { + const model = recordField(recordField(settings, "model"), "available"); + if (Array.isArray(model) && model.length > 0) return model.filter(Predicate.isObject); + const selection = state.modelSelection; + if (selection === undefined) return []; + return [ + { + ref: { providerId: selection.providerId, modelId: selection.modelId }, + ...(state.thoughtLevel === undefined + ? {} + : { reasoning: { defaultLevel: state.thoughtLevel, levels: state.thoughtLevels } }), + }, + ]; +}; + +const readLegacySettings = Effect.fn("ZcodeServe.readSettings")(function* ( + channel: ZcodeChannelClient, + workspace: ZcodeWorkspaceParams, + sessionId: string, +) { + const snapshot = yield* channel.call("zcode-agent", "readSession", { + ...workspace, + sessionId, + deliveryKind: "desktop-continuous", + }); + return recordField(snapshot, "settings"); +}); + +export const makeZcodeServeConnection = Effect.fn("ZcodeServeConnection.make")(function* ( + options: ZcodeServeConnectionOptions, +) { + const scope = yield* Effect.scope; + const server = yield* connectZcodeServer({ + settings: options.settings, + environment: options.environment, + fileSystem: options.fileSystem, + httpClient: options.httpClient, + }); + const channel = yield* makeZcodeChannelClient({ + url: zcodeChannelUrl(server.status, server.token), + headers: { "x-zcode-rpc-host-capability": server.capability }, + }); + const projectId = yield* resolveProjectId(channel, options.cwd); + const workspace: ZcodeWorkspaceParams = { + workspacePath: options.cwd, + workspaceIdentity: projectId, + projectId, + }; + yield* channel.call("zcode-agent", "initialize", workspace).pipe( + Effect.tap((initialized) => + recordField(initialized, "available") === true + ? Effect.void + : Effect.logWarning("ZCode agent reports no usable provider for this workspace.", { + reason: recordField(initialized, "reason") ?? null, + }), + ), + Effect.ignore, + ); + + const events = yield* Queue.unbounded(); + const exitDeferred = yield* Deferred.make(); + let conversation: ZcodeConversationState = initialConversationState(); + let sessionId: string | undefined; + let seeding = false; + + const foldFrame = (frame: unknown): void => { + if (recordField(frame, "kind") !== "complete") return; + if (sessionId === undefined) return; + const topic = recordString(frame, "topic"); + // The listener is workspace-scoped; the topic names the conversation this client subscribed. + if (topic !== undefined && topic !== `conversation/${sessionId}`) return; + const payload = recordField(recordField(frame, "frame"), "payload"); + if (!Predicate.isObject(payload)) return; + const seedRows = seeding && recordString(payload, "kind") === "snapshot"; + if (seedRows) seeding = false; + for (const event of applyConversationPayload(conversation, payload, { seedRows })) { + if (event.type === "server.request") { + const requestParams = recordField(event.payload, "params"); + Queue.offerUnsafe(events, { + id: recordString(requestParams, "requestId") ?? "", + method: recordString(event.payload, "method") ?? "", + params: Predicate.isObject(requestParams) ? requestParams : {}, + }); + continue; + } + Queue.offerUnsafe(events, { method: "session/event", params: event }); + } + }; + + yield* channel.listen("zcode-agent", "onDynamicConversationFrame", workspace, foldFrame); + yield* channel.listen("zcode-agent", "onDynamicSessionLifecycle", workspace, (snapshot) => { + if (!Predicate.isObject(snapshot)) return; + const eventSessionId = recordString(snapshot, "sessionId"); + if (sessionId !== undefined && eventSessionId !== undefined && eventSessionId !== sessionId) { + return; + } + Queue.offerUnsafe(events, { method: "session/lifecycle/changed", params: snapshot }); + }); + + yield* channel.closed.pipe( + Effect.andThen( + Deferred.fail( + exitDeferred, + new ZcodeProtocolError({ + operation: "exit", + detail: "zcode server channel closed", + }), + ), + ), + Effect.andThen( + Queue.fail( + events, + new ZcodeProtocolError({ operation: "exit", detail: "zcode server channel closed" }), + ), + ), + Effect.ignore, + Effect.forkIn(scope), + ); + + const subscribe = Effect.fn("ZcodeServe.subscribe")(function* (nativeSessionId: string) { + conversation = initialConversationState(); + sessionId = nativeSessionId; + seeding = true; + return yield* channel.call("zcode-agent", "subscribeConversationV4", { + ...workspace, + sessionId: nativeSessionId, + visibility: "foreground", + }); + }); + + const commitCommand = Effect.fn("ZcodeServe.commitCommand")(function* ( + type: string, + nativeSessionId: string, + payload: ZcodeRecord, + ) { + const commandId = yield* random.uuidV4(); + const issuedAt = yield* Clock.currentTimeMillis; + return yield* channel.call("zcode-agent", "sendConversationCommandV4", { + ...workspace, + envelope: { + commandId, + clientId: CLIENT_ID, + sessionId: nativeSessionId, + type, + payload, + issuedAt, + }, + }); + }); + + /** Translates a session-layer answer into the daemon's `resolveInteraction` shape. */ + const interactionAnswer = ( + interaction: ZcodeRecord | undefined, + result: unknown, + ): ZcodeRecord | undefined => { + const wanted = Predicate.isObject(result) ? result : {}; + const optionId = recordString(wanted, "optionId"); + if (optionId !== undefined) return { optionId }; + if (recordField(wanted, "cancelled") === true) return { action: "cancel" }; + const value = recordString(wanted, "value"); + if (value !== undefined) { + const payload = recordField(interaction ?? {}, "payload"); + const questions = recordField(payload, "questions"); + const question = Array.isArray(questions) ? questions[0] : undefined; + // AskUserQuestion interactions resolve through the elicitation path: the daemon expects + // the tool's answers map, not a permission option id. + const questionText = recordString(question, "question"); + if (questionText !== undefined) { + return { action: "accept", content: { answers: { [questionText]: value } } }; + } + const candidates = recordField(payload, "options"); + const match = Array.isArray(candidates) + ? candidates.find((candidate) => recordString(candidate, "label") === value) + : undefined; + const matchedId = recordString(match, "optionId") ?? recordString(match, "value"); + return matchedId === undefined ? { freeText: value } : { optionId: matchedId }; + } + if (recordString(wanted, "decision") === "deny") return { action: "decline" }; + return undefined; + }; + + const respond = Effect.fnUntraced(function* (id: string, result: unknown) { + const interaction = conversation.pendingInteractions.get(id); + const answer = interactionAnswer(interaction, result); + if (answer === undefined || sessionId === undefined) return; + conversation.pendingInteractions.delete(id); + yield* commitCommand("resolveInteraction", sessionId, { + interactionId: id, + answer, + }).pipe( + Effect.catch((error) => + Effect.logWarning("ZCode interaction answer failed.", { detail: errorMessage(error) }), + ), + ); + }); + + const request = Effect.fn("ZcodeServe.request")(function* ( + method: string, + params: ZcodeRecord, + timeoutMs = DEFAULT_TIMEOUT_MS, + ): Effect.fn.Return { + switch (method) { + case "session/create": { + const workspaceRef = recordField(params, "workspace"); + const requestedCwd = recordString(workspaceRef, "workspacePath"); + const mode = recordString(params, "mode"); + const mcpServers = recordField(params, "mcpServers"); + const created = yield* channel.call( + "zcode-session", + "createSession", + { + ...workspace, + ...(requestedCwd === undefined ? {} : { workspacePath: requestedCwd }), + ...(mode === undefined ? {} : { mode }), + ...(Array.isArray(mcpServers) ? { mcpServers } : {}), + }, + timeoutMs, + ); + const nativeSessionId = recordString(recordField(created, "session"), "sessionId"); + if (nativeSessionId === undefined) { + return yield* new ZcodeProtocolError({ + operation: method, + detail: "zcode server returned no session id.", + }); + } + const settings = recordField(created, "settings"); + return { + session: { sessionId: nativeSessionId }, + settings: { + model: { available: availableModelDescriptors(conversation, settings) }, + }, + }; + } + case "session/subscribe": { + const nativeSessionId = recordString(params, "sessionId"); + if (nativeSessionId === undefined) return { snapshot: {} }; + yield* subscribe(nativeSessionId); + const settings = yield* readLegacySettings(channel, workspace, nativeSessionId).pipe( + Effect.orElseSucceed(() => undefined), + ); + return { + snapshot: { + settings: { + model: { available: availableModelDescriptors(conversation, settings) }, + }, + }, + }; + } + case "session/resume": { + const nativeSessionId = recordString(params, "sessionId"); + if (nativeSessionId === undefined) { + return yield* new ZcodeProtocolError({ + operation: method, + detail: "session/resume needs a sessionId", + }); + } + const mcpServers = recordField(params, "mcpServers"); + yield* channel.call( + "zcode-agent", + "resumeSession", + { + ...workspace, + sessionId: nativeSessionId, + ...(Array.isArray(mcpServers) ? { mcpServers } : {}), + }, + CREATE_TIMEOUT_MS, + ); + sessionId = nativeSessionId; + return {}; + } + case "session/setMode": { + const nativeSessionId = recordString(params, "sessionId"); + const mode = recordString(params, "mode"); + if (nativeSessionId === undefined || mode === undefined) return {}; + yield* channel.call("zcode-agent", "setMode", { + ...workspace, + sessionId: nativeSessionId, + mode, + }); + return {}; + } + case "session/send": { + const nativeSessionId = recordString(params, "sessionId"); + const content = recordString(params, "content"); + if (nativeSessionId === undefined || content === undefined) { + return yield* new ZcodeProtocolError({ + operation: method, + detail: "session/send needs a sessionId and content.", + }); + } + const modelSelection = recordField(params, "modelSelection"); + const inputId = yield* random.uuidV4(); + return yield* channel.call("zcode-agent", "sendPrompt", { + ...workspace, + sessionId: nativeSessionId, + inputId, + content, + ...(Predicate.isObject(modelSelection) ? { modelSelection } : {}), + }); + } + case "session/compact": { + const nativeSessionId = recordString(params, "sessionId"); + if (nativeSessionId === undefined) return {}; + const instructions = recordString(params, "instructions"); + const inputId = yield* random.uuidV4(); + return yield* channel.call( + "zcode-agent", + "compactSession", + { + ...workspace, + sessionId: nativeSessionId, + inputId, + ...(instructions === undefined ? {} : { instructions }), + }, + CREATE_TIMEOUT_MS, + ); + } + case "session/stop": { + const nativeSessionId = recordString(params, "sessionId") ?? sessionId; + if (nativeSessionId === undefined) return {}; + const executionId = conversation.foregroundExecutionId; + yield* commitCommand( + "stop", + nativeSessionId, + executionId === undefined ? {} : { expectedForegroundExecutionId: executionId }, + ); + return {}; + } + case "session/read": { + const nativeSessionId = recordString(params, "sessionId"); + if (nativeSessionId === undefined) return {}; + return yield* channel.call("zcode-agent", "readSession", { + ...workspace, + sessionId: nativeSessionId, + deliveryKind: "desktop-continuous", + }); + } + default: + return yield* new ZcodeProtocolError({ + operation: method, + detail: "unsupported zcode server request", + }); + } + }); + + return { + request, + respond, + events, + exited: Deferred.await(exitDeferred), + terminate: Effect.void, + } satisfies ZcodeConnection; +}); diff --git a/packages/provider-zcode/src/server/zcodeServeConversation.test.ts b/packages/provider-zcode/src/server/zcodeServeConversation.test.ts new file mode 100644 index 0000000000000..778a6d9204968 --- /dev/null +++ b/packages/provider-zcode/src/server/zcodeServeConversation.test.ts @@ -0,0 +1,450 @@ +import { assert, describe, it } from "@effect/vitest"; + +import { + applyConversationPayload, + initialConversationState, + type ZcodeConversationState, +} from "./zcodeServeConversation.ts"; + +const deltas = (state: ZcodeConversationState, entries: ReadonlyArray) => + applyConversationPayload(state, { kind: "deltas", deltas: entries }); + +describe("applyConversationPayload", () => { + it("seeds config, rows, and streamed text from a snapshot", () => { + const state = initialConversationState(); + const events = applyConversationPayload(state, { + kind: "snapshot", + snapshot: { + revision: 3, + config: { + modelSelection: { + providerId: "account:zai-individual-coding-plan", + modelId: "GLM-5.3", + }, + thought: "max", + thoughtLevels: ["low", "high", "max"], + }, + control: { + phase: "draft", + activeWorks: [{ kind: "primaryTurn", foregroundExecutionId: "runtime_command_1" }], + }, + rows: { + window: [ + { rowId: 1, kind: "turnHeader", state: "running" }, + { + rowId: 2, + kind: "assistantText", + assistantResponseId: "msg_a", + text: "earlier", + state: "complete", + }, + ], + totalCount: 2, + firstRowId: 1, + }, + pendingInteractions: [], + }, + }); + + assert.equal(state.revision, 3); + assert.deepEqual(state.modelSelection, { + providerId: "account:zai-individual-coding-plan", + modelId: "GLM-5.3", + }); + assert.deepEqual(state.thoughtLevels, ["low", "high", "max"]); + assert.equal(state.thoughtLevel, "max"); + assert.equal(state.phase, "draft"); + assert.equal(state.foregroundExecutionId, "runtime_command_1"); + assert.equal(state.lastAssistantText, "earlier"); + assert.deepEqual(events, [ + { + type: "model.streaming", + payload: { + assistantMessageId: "msg_a", + delta: "earlier", + kind: "text_delta", + done: true, + }, + }, + ]); + }); + + it("replays snapshot rows silently when subscribed for history", () => { + const state = initialConversationState(); + const events = applyConversationPayload( + state, + { + kind: "snapshot", + snapshot: { + revision: 1, + rows: { + window: [ + { rowId: 1, kind: "assistantText", assistantResponseId: "msg_a", text: "old" }, + ], + }, + }, + }, + { seedRows: true }, + ); + assert.deepEqual(events, []); + assert.equal(state.lastAssistantText, "old"); + }); + + it("streams text deltas and completes the turn with the last assistant text", () => { + const state = initialConversationState(); + + assert.deepEqual( + deltas(state, [ + { + op: "state.updated", + patch: { + revision: 1, + control: { + phase: "running", + activeWorks: [{ kind: "primaryTurn", foregroundExecutionId: "runtime_command_4" }], + }, + }, + }, + ]), + [{ type: "turn.started", payload: {} }], + ); + assert.equal(state.foregroundExecutionId, "runtime_command_4"); + + assert.deepEqual( + deltas(state, [ + { + op: "row.appended", + row: { + rowId: 6, + kind: "assistantText", + assistantResponseId: "msg_b", + text: "", + state: "streaming", + }, + }, + ]), + [], + ); + + assert.deepEqual(deltas(state, [{ op: "row.delta", rowId: 6, append: "do" }]), [ + { + type: "model.streaming", + payload: { assistantMessageId: "msg_b", delta: "do", kind: "text_delta" }, + }, + ]); + + // The finishing upsert carries the whole text; only the suffix is new. + assert.deepEqual( + deltas(state, [ + { + op: "row.upserted", + row: { + rowId: 6, + kind: "assistantText", + assistantResponseId: "msg_b", + text: "done", + state: "complete", + }, + }, + { op: "row.upserted", row: { rowId: 1, kind: "turnHeader", outputTokens: 31 } }, + ]), + [ + { + type: "model.streaming", + payload: { + assistantMessageId: "msg_b", + delta: "ne", + kind: "text_delta", + done: true, + }, + }, + ], + ); + + assert.deepEqual( + deltas(state, [{ op: "state.updated", patch: { control: { phase: "completedSuccess" } } }]), + [ + { + type: "turn.completed", + payload: { resultType: "success", response: "done", tokenCount: 31 }, + }, + ], + ); + assert.equal(state.lastAssistantText, "done"); + }); + + it("reports interruption and failure as their own terminal kinds", () => { + const interrupted = initialConversationState(); + deltas(interrupted, [{ op: "state.updated", patch: { control: { phase: "running" } } }]); + assert.deepEqual( + deltas(interrupted, [ + { op: "state.updated", patch: { control: { phase: "completedInterrupted" } } }, + ]), + [{ type: "turn.completed", payload: { resultType: "cancelled" } }], + ); + + const failed = initialConversationState(); + deltas(failed, [{ op: "state.updated", patch: { control: { phase: "running" } } }]); + assert.deepEqual( + deltas(failed, [ + { + op: "state.updated", + patch: { control: { phase: "error", lastError: { message: "model exploded" } } }, + }, + ]), + [{ type: "turn.failed", payload: { error: { message: "model exploded" } } }], + ); + }); + + it("follows a tool call from started through streamed output to its result", () => { + const state = initialConversationState(); + const toolRow = { + rowId: 4, + kind: "toolCall", + toolCallId: "call_1", + toolName: "Bash", + status: "inputStreaming", + input: { command: "echo hello-t3" }, + }; + + assert.deepEqual(deltas(state, [{ op: "row.appended", row: toolRow }]), [ + { + type: "tool.updated", + payload: { + toolCallId: "call_1", + toolName: "Bash", + input: { command: "echo hello-t3" }, + kind: "started", + }, + }, + ]); + + assert.deepEqual( + deltas(state, [ + { op: "row.upserted", row: { ...toolRow, status: "running" } }, + { op: "row.delta", rowId: 4, path: "output.text", append: "hel" }, + ]), + [ + { + type: "tool.updated", + payload: { + toolCallId: "call_1", + toolName: "Bash", + input: { command: "echo hello-t3" }, + kind: "started", + }, + }, + { + type: "tool.updated", + payload: { + toolCallId: "call_1", + toolName: "Bash", + input: { command: "echo hello-t3" }, + kind: "progress", + outputPreview: { text: "hel" }, + }, + }, + ], + ); + + assert.deepEqual( + deltas(state, [ + { + op: "row.upserted", + row: { ...toolRow, status: "success", output: { text: "hello-t3" } }, + }, + ]), + [ + { + type: "tool.updated", + payload: { + toolCallId: "call_1", + toolName: "Bash", + input: { command: "echo hello-t3" }, + kind: "result", + result: { output: "hello-t3" }, + }, + }, + ], + ); + + assert.deepEqual( + deltas(state, [ + { + op: "row.appended", + row: { + rowId: 5, + kind: "toolCall", + toolCallId: "call_2", + toolName: "Bash", + status: "error", + error: { message: "permission denied" }, + }, + }, + ]), + [ + { + type: "tool.updated", + payload: { + toolCallId: "call_2", + toolName: "Bash", + input: undefined, + kind: "error", + error: { message: "permission denied" }, + }, + }, + ], + ); + }); + + it("announces a permission interaction once and resolves it when the daemon drops it", () => { + const state = initialConversationState(); + const interaction = { + interactionId: "int_1", + kind: "permission", + payload: { + toolCallId: "call_1", + toolName: "Bash", + summary: "Needs approval", + options: [ + { optionId: "o1", kind: "allowOnce", label: "Allow once" }, + { optionId: "o2", kind: "deny", label: "Deny" }, + ], + fullAccessOption: { optionId: "o3", kind: "custom", label: "Full access" }, + }, + }; + const patch = { op: "state.updated", patch: { pendingInteractions: [interaction] } }; + + assert.deepEqual(deltas(state, [patch]), [ + { + type: "permission.requested", + payload: { + requestId: "int_1", + toolCallId: "call_1", + toolName: "Bash", + reason: "Needs approval", + options: [ + { + optionId: "o1", + kind: "allow_once", + name: "Allow once", + response: { optionId: "o1", decision: "allow" }, + }, + { + optionId: "o2", + kind: "deny", + name: "Deny", + response: { optionId: "o2", decision: "deny" }, + }, + { + optionId: "o3", + kind: "custom", + name: "Full access", + response: { optionId: "o3", decision: "allow" }, + }, + ], + }, + }, + { + type: "server.request", + payload: { + method: "interaction/requestPermission", + params: { requestId: "int_1", toolCallId: "call_1", toolName: "Bash" }, + }, + }, + ]); + + // A resubscribe replays the same pending interaction; it must not ask twice. + assert.deepEqual(deltas(state, [patch]), []); + + assert.deepEqual(deltas(state, [{ op: "state.updated", patch: { pendingInteractions: [] } }]), [ + { type: "permission.resolved", payload: { requestId: "int_1" } }, + ]); + assert.equal(state.pendingInteractions.size, 0); + }); + + it("surfaces an AskUserQuestion as choices and as free text", () => { + const state = initialConversationState(); + assert.deepEqual( + deltas(state, [ + { + op: "state.updated", + patch: { + pendingInteractions: [ + { + interactionId: "int_2", + kind: "userInput", + payload: { + questions: [ + { + question: "Proceed with the migration?", + header: "Confirm", + options: [ + { value: "yes", label: "Yes" }, + { value: "no", label: "No" }, + ], + }, + ], + }, + }, + ], + }, + }, + ]), + [ + { + type: "userInput.requested", + payload: { + requestId: "int_2", + prompt: "Proceed with the migration?", + inputType: "choice", + choices: ["Yes", "No"], + }, + }, + { + type: "server.request", + payload: { + method: "interaction/requestUserInput", + params: { requestId: "int_2" }, + }, + }, + ], + ); + + const freeText = initialConversationState(); + assert.deepEqual( + deltas(freeText, [ + { + op: "state.updated", + patch: { + pendingInteractions: [ + { + interactionId: "int_3", + kind: "userInput", + payload: { prompt: "Explain the change", freeText: true }, + }, + ], + }, + }, + ]), + [ + { + type: "userInput.requested", + payload: { + requestId: "int_3", + prompt: "Explain the change", + inputType: "text", + choices: [], + }, + }, + { + type: "server.request", + payload: { + method: "interaction/requestUserInput", + params: { requestId: "int_3" }, + }, + }, + ], + ); + }); +}); diff --git a/packages/provider-zcode/src/server/zcodeServeConversation.ts b/packages/provider-zcode/src/server/zcodeServeConversation.ts new file mode 100644 index 0000000000000..96f6c77368a98 --- /dev/null +++ b/packages/provider-zcode/src/server/zcodeServeConversation.ts @@ -0,0 +1,528 @@ +// Adapter between the `zcode serve` daemon's row-based conversation projection and the event +// vocabulary this provider's session layer already speaks. The daemon streams row deltas, +// state patches and pending interactions; folding them belongs here so the transport stays +// thin and the mapping stays testable. +import * as Predicate from "effect/Predicate"; + +export type ZcodeRecord = Record; + +export interface ZcodeConversationEvent { + readonly type: string; + readonly payload: ZcodeRecord; +} + +export interface ZcodeModelSelection { + readonly providerId: string; + readonly modelId: string; +} + +export interface ZcodeConversationState { + readonly rows: Map; + revision: number; + phase: string | undefined; + /** The daemon rejects a stale `stop` without this id, so track it off the live control patch. */ + foregroundExecutionId: string | undefined; + readonly pendingInteractions: Map; + /** Interactions already surfaced as requests; resubscribes replay the snapshot. */ + readonly announcedInteractions: Set; + /** Streamed `output.text` per tool row; tool rows only carry the full text at the end. */ + readonly toolOutput: Map; + modelSelection: ZcodeModelSelection | undefined; + thoughtLevels: ReadonlyArray; + thoughtLevel: string | undefined; + /** Latest finished assistant text, used as the turn result summary. */ + lastAssistantText: string | undefined; +} + +export const initialConversationState = (): ZcodeConversationState => ({ + rows: new Map(), + revision: 0, + phase: undefined, + foregroundExecutionId: undefined, + pendingInteractions: new Map(), + announcedInteractions: new Set(), + toolOutput: new Map(), + modelSelection: undefined, + thoughtLevels: [], + thoughtLevel: undefined, + lastAssistantText: undefined, +}); + +const field = (record: unknown, key: string): unknown => + Predicate.isObject(record) ? record[key] : undefined; + +const text = (record: unknown, key: string): string | undefined => { + const value = field(record, key); + return Predicate.isString(value) ? value : undefined; +}; + +const number = (record: unknown, key: string): number | undefined => { + const value = field(record, key); + return Predicate.isNumber(value) && Number.isFinite(value) ? value : undefined; +}; + +const readConfig = (state: ZcodeConversationState, config: unknown): void => { + const selection = field(config, "modelSelection"); + const providerId = text(selection, "providerId"); + const modelId = text(selection, "modelId"); + if (providerId !== undefined && modelId !== undefined) { + state.modelSelection = { providerId, modelId }; + } + const levels = field(config, "thoughtLevels"); + if (Array.isArray(levels)) { + state.thoughtLevels = levels.filter(Predicate.isString); + } + const thought = text(config, "thought"); + if (thought !== undefined) state.thoughtLevel = thought; +}; + +const readControl = (state: ZcodeConversationState, control: unknown): void => { + const phase = text(control, "phase"); + if (phase !== undefined) state.phase = phase; + const activeWorks = field(control, "activeWorks"); + if (Array.isArray(activeWorks)) { + const primary = + activeWorks.find((work) => text(work, "kind") === "primaryTurn") ?? activeWorks[0]; + state.foregroundExecutionId = text(primary, "foregroundExecutionId"); + } +}; + +/** Deltas carry the suffix; full-row upserts carry the whole text, so diff against the last row. */ +const appendedText = (previous: string, next: string): string => { + if (previous.length === 0) return next; + if (next.startsWith(previous)) return next.slice(previous.length); + let shared = 0; + while (shared < previous.length && shared < next.length && previous[shared] === next[shared]) { + shared += 1; + } + return next.slice(shared); +}; + +const streamTextEvent = ( + messageId: string, + delta: string, + kind: "text_delta" | "reasoning_delta", + done: boolean, +): ZcodeConversationEvent => ({ + type: "model.streaming", + payload: { + assistantMessageId: messageId, + delta, + kind, + ...(done ? { done: true } : {}), + }, +}); + +const rowEvents = ( + state: ZcodeConversationState, + row: ZcodeRecord, + previous: ZcodeRecord | undefined, + append: string | undefined, +): ReadonlyArray => { + const kind = text(row, "kind"); + + if (kind === "assistantText" || kind === "reasoning") { + const messageId = text(row, "assistantResponseId") ?? text(row, "entityId"); + if (messageId === undefined) return []; + const streamKind = kind === "assistantText" ? "text_delta" : "reasoning_delta"; + const nextText = text(row, "text") ?? ""; + const delta = + append ?? + (previous === undefined ? nextText : appendedText(text(previous, "text") ?? "", nextText)); + const rowState = text(row, "state"); + const finishing = + rowState !== undefined && + rowState !== "streaming" && + text(previous ?? {}, "state") !== rowState; + const events: ZcodeConversationEvent[] = []; + if (delta.length > 0 || finishing) { + events.push(streamTextEvent(messageId, delta, streamKind, finishing)); + } + if (kind === "assistantText" && nextText.length > 0 && rowState !== "streaming") { + state.lastAssistantText = nextText; + } + return events; + } + + if (kind === "toolCall") { + const toolCallId = text(row, "toolCallId") ?? `row-${number(row, "rowId") ?? 0}`; + const status = text(row, "status"); + const output = text(field(row, "output"), "text"); + const input = field(row, "input"); + const payload: ZcodeRecord = { + toolCallId, + toolName: text(row, "toolName"), + input, + }; + const previousStatus = text(previous ?? {}, "status"); + if (status === previousStatus) { + const preview = + text(field(row, "outputPreview"), "text") ?? text(field(row, "progress"), "previewLine"); + const previousPreview = + text(field(previous ?? {}, "outputPreview"), "text") ?? + text(field(previous ?? {}, "progress"), "previewLine"); + if (preview !== undefined && preview.length > 0 && preview !== previousPreview) { + return [ + { + type: "tool.updated", + payload: { ...payload, kind: "progress", outputPreview: { text: preview } }, + }, + ]; + } + if (input !== undefined && field(previous ?? {}, "input") === undefined) { + return [{ type: "tool.updated", payload: { ...payload, kind: "started" } }]; + } + return []; + } + if (status === "error" || status === "cancelled") { + const message = text(field(row, "error"), "message") ?? output ?? "Tool failed."; + return [{ type: "tool.updated", payload: { ...payload, kind: "error", error: { message } } }]; + } + if (status === "success") { + return [ + { + type: "tool.updated", + payload: { + ...payload, + kind: "result", + result: output === undefined ? {} : { output }, + }, + }, + ]; + } + return [{ type: "tool.updated", payload: { ...payload, kind: "started" } }]; + } + + return []; +}; + +const INTERACTION_OPTION_KINDS: Record = { + allowOnce: { kind: "allow_once", decision: "allow" }, + allowAlways: { kind: "allow_always", decision: "allow" }, + deny: { kind: "deny", decision: "deny" }, + custom: { kind: "custom", decision: "allow" }, +}; + +interface PermissionOption { + readonly optionId: string; + readonly kind: string; + readonly name: string; + readonly response: ZcodeRecord; +} + +const permissionOptions = (payload: unknown): ReadonlyArray => { + const raw = field(payload, "options"); + const options = Array.isArray(raw) ? [...raw] : []; + const fullAccess = field(payload, "fullAccessOption"); + if (Predicate.isObject(fullAccess)) options.push(fullAccess); + return options.flatMap((option): Array => { + const optionId = text(option, "optionId"); + if (optionId === undefined) return []; + const mapped = INTERACTION_OPTION_KINDS[text(option, "kind") ?? ""] ?? { + kind: "custom", + decision: "allow", + }; + return [ + { + optionId, + kind: mapped.kind, + name: text(option, "label") ?? optionId, + // The session layer echoes this object back untouched; the transport turns it into + // the daemon's `resolveInteraction` answer. + response: { optionId, decision: mapped.decision }, + }, + ]; + }); +}; + +interface UserInputView { + readonly prompt: string; + readonly inputType: "text" | "choice"; + readonly choices: ReadonlyArray; +} + +const userInputView = (payload: unknown): UserInputView => { + const questions = field(payload, "questions"); + const question = Array.isArray(questions) ? questions[0] : undefined; + const questionOptions = field(question, "options"); + const flatOptions = field(payload, "options"); + const labels = (candidates: unknown): ReadonlyArray => + Array.isArray(candidates) + ? candidates.flatMap((option): Array => { + const label = text(option, "label"); + return label === undefined ? [] : [label]; + }) + : []; + const choices = labels(questionOptions ?? flatOptions); + const freeText = + field(payload, "freeText") === true || field(question, "multiSelect") !== undefined; + return { + prompt: text(question, "question") ?? text(payload, "prompt") ?? "The agent asked a question", + inputType: freeText || choices.length === 0 ? "text" : "choice", + choices, + }; +}; + +/** + * Interaction events in this provider's vocabulary plus the server request that carries the + * user's answer back to the daemon. Both key on the daemon interaction id. + */ +const interactionEvents = ( + state: ZcodeConversationState, + interaction: ZcodeRecord, +): ReadonlyArray => { + const interactionId = text(interaction, "interactionId"); + if (interactionId === undefined || state.announcedInteractions.has(interactionId)) return []; + const payload = field(interaction, "payload"); + const kind = text(interaction, "kind") ?? text(payload, "kind"); + const events: ZcodeConversationEvent[] = []; + if (kind === "permission") { + events.push({ + type: "permission.requested", + payload: { + requestId: interactionId, + toolCallId: text(payload, "toolCallId"), + toolName: text(payload, "toolName"), + reason: text(payload, "summary"), + options: permissionOptions(payload), + }, + }); + events.push({ + type: "server.request", + payload: { + method: "interaction/requestPermission", + params: { + requestId: interactionId, + toolCallId: text(payload, "toolCallId"), + toolName: text(payload, "toolName"), + }, + }, + }); + } else if (kind === "userInput") { + const view = userInputView(payload); + events.push({ + type: "userInput.requested", + payload: { + requestId: interactionId, + prompt: view.prompt, + inputType: view.inputType, + choices: view.choices, + }, + }); + events.push({ + type: "server.request", + payload: { + method: "interaction/requestUserInput", + params: { requestId: interactionId }, + }, + }); + } + state.announcedInteractions.add(interactionId); + return events; +}; + +const interactionResolvedEvents = ( + interaction: ZcodeRecord, +): ReadonlyArray => { + const interactionId = text(interaction, "interactionId"); + if (interactionId === undefined) return []; + const kind = text(interaction, "kind") ?? text(field(interaction, "payload"), "kind"); + return [ + { + type: kind === "userInput" ? "userInput.resolved" : "permission.resolved", + payload: { requestId: interactionId }, + }, + ]; +}; + +const turnOutputTokens = (state: ZcodeConversationState): number | undefined => { + let best: { rowId: number; tokens: number } | undefined; + for (const [rowId, row] of state.rows) { + if (text(row, "kind") !== "turnHeader") continue; + const tokens = number(row, "outputTokens"); + if (tokens === undefined) continue; + if (best === undefined || rowId > best.rowId) best = { rowId, tokens }; + } + return best?.tokens; +}; + +const controlEvents = ( + state: ZcodeConversationState, + control: unknown, +): ReadonlyArray => { + const phase = text(control, "phase"); + if (phase === undefined) return []; + const previousPhase = state.phase; + readControl(state, control); + if (phase === previousPhase) return []; + if (phase === "running" || phase === "prewarming") { + state.lastAssistantText = undefined; + return [{ type: "turn.started", payload: {} }]; + } + if (previousPhase !== "running" && previousPhase !== "prewarming") return []; + const tokenCount = turnOutputTokens(state); + switch (phase) { + case "completedSuccess": + return [ + { + type: "turn.completed", + payload: { + resultType: "success", + ...(state.lastAssistantText === undefined ? {} : { response: state.lastAssistantText }), + ...(tokenCount === undefined ? {} : { tokenCount }), + }, + }, + ]; + case "completedInterrupted": + return [{ type: "turn.completed", payload: { resultType: "cancelled" } }]; + case "error": + return [ + { + type: "turn.failed", + payload: { + error: { + message: text(field(control, "lastError"), "message") ?? "ZCode turn failed.", + }, + }, + }, + ]; + default: + return []; + } +}; + +/** + * Folds one v4 conversation payload into `state` and returns the session events it produces. + * Mutates `state`; callers keep exactly one state per native session. + */ +export function applyConversationPayload( + state: ZcodeConversationState, + payload: unknown, + options: { readonly seedRows?: boolean } = {}, +): ReadonlyArray { + const kind = text(payload, "kind"); + if (kind === "snapshot") { + const snapshot = field(payload, "snapshot"); + const revision = number(snapshot, "revision"); + if (revision !== undefined) state.revision = revision; + readConfig(state, field(snapshot, "config")); + readControl(state, field(snapshot, "control")); + const events: ZcodeConversationEvent[] = []; + const rows = field(field(snapshot, "rows"), "window"); + if (Array.isArray(rows)) { + for (const entry of rows) { + const row = entry as ZcodeRecord; + const rowId = number(row, "rowId"); + if (rowId === undefined) continue; + state.rows.set(rowId, row); + if (options.seedRows !== true) { + events.push(...rowEvents(state, row, undefined, undefined)); + } else if (text(row, "kind") === "assistantText") { + const rowText = text(row, "text"); + if (rowText !== undefined && rowText.length > 0) state.lastAssistantText = rowText; + } + } + } + const pending = field(snapshot, "pendingInteractions"); + if (Array.isArray(pending)) { + for (const interaction of pending) { + if (!Predicate.isObject(interaction)) continue; + const id = text(interaction, "interactionId"); + if (id === undefined) continue; + state.pendingInteractions.set(id, interaction); + events.push(...interactionEvents(state, interaction)); + } + } + return events; + } + + if (kind !== "deltas") return []; + const deltas = field(payload, "deltas"); + if (!Array.isArray(deltas)) return []; + const events: ZcodeConversationEvent[] = []; + + for (const entry of deltas) { + const op = text(entry, "op"); + if (op === undefined) continue; + if (op === "state.updated") { + const patch = field(entry, "patch"); + const revision = number(patch, "revision"); + if (revision !== undefined) state.revision = revision; + readConfig(state, field(patch, "config")); + const control = field(patch, "control"); + if (control !== undefined) events.push(...controlEvents(state, control)); + const pending = field(patch, "pendingInteractions"); + if (Array.isArray(pending)) { + const next = new Map(); + for (const interaction of pending) { + if (!Predicate.isObject(interaction)) continue; + const id = text(interaction, "interactionId"); + if (id === undefined) continue; + next.set(id, interaction); + const known = state.pendingInteractions.get(id); + if (known === undefined) events.push(...interactionEvents(state, interaction)); + } + for (const [id, previous] of state.pendingInteractions) { + if (next.has(id)) continue; + events.push(...interactionResolvedEvents(previous)); + } + state.pendingInteractions.clear(); + for (const [id, interaction] of next) state.pendingInteractions.set(id, interaction); + } + continue; + } + if (op === "row.delta") { + const rowId = number(entry, "rowId"); + const append = text(entry, "append"); + const path = text(entry, "path") ?? "text"; + if (rowId === undefined || append === undefined) continue; + const row = state.rows.get(rowId); + if (row === undefined) continue; + const rowKind = text(row, "kind"); + if (rowKind === "toolCall") { + if (path !== "output.text") continue; + const accumulated = (state.toolOutput.get(rowId) ?? "") + append; + state.toolOutput.set(rowId, accumulated); + events.push({ + type: "tool.updated", + payload: { + toolCallId: text(row, "toolCallId") ?? `row-${rowId}`, + toolName: text(row, "toolName"), + input: field(row, "input"), + kind: "progress", + outputPreview: { text: accumulated }, + }, + }); + continue; + } + if (path !== "text") continue; + const streamed = { ...row, text: (text(row, "text") ?? "") + append }; + state.rows.set(rowId, streamed); + events.push(...rowEvents(state, streamed, row, append)); + continue; + } + if (op === "row.appended" || op === "row.upserted") { + const row = field(entry, "row"); + if (!Predicate.isObject(row)) continue; + const rowId = number(row, "rowId"); + if (rowId === undefined) continue; + const previous = state.rows.get(rowId); + state.rows.set(rowId, row); + events.push( + ...rowEvents(state, row, op === "row.appended" ? undefined : previous, undefined), + ); + continue; + } + if (op === "row.removed") { + const fromRowId = number(entry, "fromRowId"); + if (fromRowId === undefined) continue; + const removed: number[] = []; + for (const rowId of state.rows.keys()) { + if (rowId >= fromRowId) removed.push(rowId); + } + for (const rowId of removed) state.rows.delete(rowId); + } + } + + return events; +} diff --git a/packages/provider-zcode/src/server/zcodeServeDaemon.ts b/packages/provider-zcode/src/server/zcodeServeDaemon.ts new file mode 100644 index 0000000000000..d16202009a69a --- /dev/null +++ b/packages/provider-zcode/src/server/zcodeServeDaemon.ts @@ -0,0 +1,209 @@ +// `zcode serve` is a user-level daemon: it owns CLI credentials, runs the agent runtime and +// exposes the channel WebSocket T3 attaches to. T3 never spawns a per-session agent and never +// reads the credential store; it only makes sure the daemon is up and asks for a host grant. +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { resolveSpawnCommand } from "@t3tools/shared/shell"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; +import * as HttpClientResponse from "effect/http/HttpClientResponse"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +import { ZcodeProtocolError } from "./zcodeProtocol.ts"; +import { resolveZcodeLaunchCommand, zcodeDataRoot, zcodeServeArgs } from "./zcodeRuntime.ts"; + +const STATUS_FILE = "status.json"; +const TOKEN_FILE = "ingress-token"; +const STATUS_READY = "ready"; +const STARTUP_TIMEOUT = Duration.seconds(30); +const STARTUP_POLL = Duration.millis(250); + +const ZcodeServerStatus = Schema.Struct({ + state: Schema.String, + host: Schema.String, + port: Schema.Int, + version: Schema.optional(Schema.String), + pid: Schema.optional(Schema.Int), +}); +export type ZcodeServerStatus = typeof ZcodeServerStatus.Type; +const decodeStatus = Schema.decodeUnknownOption(Schema.fromJsonString(ZcodeServerStatus)); + +const ZcodeHostCapability = Schema.Struct({ + capability: Schema.String, + expiresAt: Schema.optional(Schema.Number), +}); + +function zcodeServerRoot(environment: NodeJS.ProcessEnv): string | undefined { + const root = zcodeDataRoot(environment); + return root === undefined ? undefined : `${root}/.zcode/server`; +} + +const readZcodeServerStatus = Effect.fn("ZcodeServe.readStatus")(function* ( + fileSystem: FileSystem.FileSystem, + serverRoot: string, +) { + const raw = yield* fileSystem + .readFileString(`${serverRoot}/run/${STATUS_FILE}`) + .pipe(Effect.option); + if (Option.isNone(raw)) return Option.none(); + const status = decodeStatus(raw.value); + if (Option.isNone(status)) return Option.none(); + return status.value.state === STATUS_READY ? Option.some(status.value) : Option.none(); +}); + +const readIngressToken = Effect.fn("ZcodeServe.readIngressToken")(function* ( + fileSystem: FileSystem.FileSystem, + serverRoot: string, +) { + const raw = yield* fileSystem + .readFileString(`${serverRoot}/run/${TOKEN_FILE}`) + .pipe(Effect.option); + if (Option.isNone(raw)) return undefined; + const token = raw.value.trim(); + return token.length === 0 ? undefined : token; +}); + +export const zcodeChannelUrl = (status: ZcodeServerStatus, token: string): string => + `ws://${status.host}:${status.port}/ws/host?token=${encodeURIComponent(token)}`; + +const issueZcodeHostCapability = Effect.fn("ZcodeServe.issueHostCapability")(function* ( + httpClient: HttpClient.HttpClient, + status: ZcodeServerStatus, + token: string, +) { + const request = HttpClientRequest.post( + `http://${status.host}:${status.port}/api/rpc-host-capability`, + { headers: { authorization: `Bearer ${token}` } }, + ); + const response = yield* httpClient + .execute(request) + .pipe( + Effect.mapError((cause) => new ZcodeProtocolError({ operation: "hostCapability", cause })), + ); + if (response.status < 200 || response.status >= 300) { + return yield* new ZcodeProtocolError({ + operation: "hostCapability", + detail: `zcode server refused the host grant (HTTP ${response.status})`, + }); + } + const body = yield* HttpClientResponse.schemaBodyJson(ZcodeHostCapability)(response).pipe( + Effect.mapError((cause) => new ZcodeProtocolError({ operation: "hostCapability", cause })), + ); + return body.capability; +}); + +const spawnZcodeServer = Effect.fn("ZcodeServe.spawn")(function* (input: { + readonly launchCommand: string; + readonly launchArgs: string; + readonly environment: NodeJS.ProcessEnv; +}) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const platform = yield* HostProcess.Platform; + const command = yield* resolveSpawnCommand( + input.launchCommand, + zcodeServeArgs(input.launchArgs), + { + env: input.environment, + }, + ).pipe(Effect.mapError((cause) => new ZcodeProtocolError({ operation: "serve", cause }))); + // `serve` forks the supervisor and exits, so the handle belongs to a detached fiber: the + // daemon outlives this agent scope and must never be reaped by it. + yield* Effect.forkDetach( + Effect.scoped( + Effect.gen(function* () { + const child = yield* spawner + .spawn( + ChildProcess.make(command.command, command.args, { + env: input.environment, + extendEnv: false, + shell: command.shell, + detached: platform !== "win32", + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + }), + ) + .pipe(Effect.mapError((cause) => new ZcodeProtocolError({ operation: "serve", cause }))); + yield* child.exitCode.pipe(Effect.ignore); + }), + ), + ); +}); + +/** Attaches to the running daemon, starting it when this machine has none. */ +const ensureZcodeServer = Effect.fn("ZcodeServe.ensure")(function* (input: { + readonly settings: { readonly binaryPath: string; readonly launchArgs: string }; + readonly environment: NodeJS.ProcessEnv; + readonly fileSystem: FileSystem.FileSystem; +}) { + const serverRoot = zcodeServerRoot(input.environment); + if (serverRoot === undefined) { + return yield* new ZcodeProtocolError({ + operation: "serve", + detail: "ZCode has no data directory to host a server.", + }); + } + const running = yield* readZcodeServerStatus(input.fileSystem, serverRoot); + if (Option.isSome(running)) return { serverRoot, status: running.value }; + + const launchCommand = yield* resolveZcodeLaunchCommand( + input.settings, + input.environment, + input.fileSystem, + ).pipe(Effect.mapError((cause) => new ZcodeProtocolError({ operation: "serve", cause }))); + yield* spawnZcodeServer({ + launchCommand, + launchArgs: input.settings.launchArgs, + environment: input.environment, + }).pipe( + Effect.catch((error) => + Effect.logWarning("ZCode server did not start.", { operation: error.operation }), + ), + ); + + const started = yield* Effect.gen(function* () { + for (;;) { + const status = yield* readZcodeServerStatus(input.fileSystem, serverRoot); + if (Option.isSome(status)) return status.value; + yield* Effect.sleep(STARTUP_POLL); + } + }).pipe(Effect.timeoutOption(STARTUP_TIMEOUT)); + + if (Option.isNone(started)) { + return yield* new ZcodeProtocolError({ + operation: "serve", + detail: "zcode serve did not report a ready daemon.", + }); + } + return { serverRoot, status: started.value }; +}); + +export interface ZcodeServerConnectionInfo { + readonly serverRoot: string; + readonly status: ZcodeServerStatus; + readonly token: string; + readonly capability: string; +} + +export const connectZcodeServer = Effect.fn("ZcodeServe.connect")(function* (input: { + readonly settings: { readonly binaryPath: string; readonly launchArgs: string }; + readonly environment: NodeJS.ProcessEnv; + readonly fileSystem: FileSystem.FileSystem; + readonly httpClient: HttpClient.HttpClient; +}) { + const { serverRoot, status } = yield* ensureZcodeServer(input); + const token = yield* readIngressToken(input.fileSystem, serverRoot); + if (token === undefined) { + return yield* new ZcodeProtocolError({ + operation: "serve", + detail: "zcode server has no ingress token.", + }); + } + const capability = yield* issueZcodeHostCapability(input.httpClient, status, token); + return { serverRoot, status, token, capability } satisfies ZcodeServerConnectionInfo; +}); diff --git a/packages/provider-zcode/src/server/zcodeServeProtocol.test.ts b/packages/provider-zcode/src/server/zcodeServeProtocol.test.ts new file mode 100644 index 0000000000000..52c01551281dd --- /dev/null +++ b/packages/provider-zcode/src/server/zcodeServeProtocol.test.ts @@ -0,0 +1,126 @@ +import { assert, describe, it } from "@effect/vitest"; + +import { + decodeChannelFrameBody, + encodeChannelFrame, + makeChannelFramer, +} from "./zcodeServeProtocol.ts"; + +const HEADER_BYTES = 13; + +/** A server→client frame the client would receive, built the same way the daemon builds it. */ +const incomingFrame = (kind: number, body: Uint8Array): Uint8Array => { + const frame = new Uint8Array(HEADER_BYTES + body.byteLength); + frame[0] = kind; + new DataView(frame.buffer).setUint32(9, body.byteLength); + frame.set(body, HEADER_BYTES); + return frame; +}; + +const messageBody = (header: ReadonlyArray, arg: unknown): Uint8Array => { + const frame = encodeChannelFrame(header, arg); + return frame.slice(HEADER_BYTES); +}; + +describe("channel frame codec", () => { + it("round-trips a call's header and argument", () => { + const arg = [{ workspacePath: "/w", includeDeleted: false }]; + const frame = encodeChannelFrame([100, 3, "zcode-session", "createSession"], arg); + assert.equal(frame[0], 1); + assert.equal(new DataView(frame.buffer).getUint32(9), frame.byteLength - HEADER_BYTES); + assert.deepEqual(decodeChannelFrameBody(frame.slice(HEADER_BYTES)), { + type: 100, + id: 3, + data: arg, + }); + }); + + it("round-trips every serialized value type", () => { + const arg = { + text: "héllo", + count: 300, + list: [1, "two", null], + nested: { deep: [null, { ok: true }] }, + }; + const decoded = decodeChannelFrameBody(messageBody([204, 7], arg)); + assert.deepEqual(decoded, { type: 204, id: 7, data: arg }); + + const buffer = new Uint8Array([1, 2, 3]); + const withBuffer = decodeChannelFrameBody(messageBody([201, 1], buffer)); + assert.ok(withBuffer !== undefined); + assert.deepEqual([...(withBuffer.data as Uint8Array)], [1, 2, 3]); + + const withUndefined = decodeChannelFrameBody(messageBody([201, 2], undefined)); + assert.deepEqual(withUndefined, { type: 201, id: 2, data: undefined }); + }); + + it("reads an init frame without an argument", () => { + assert.deepEqual(decodeChannelFrameBody(messageBody([200, 0], undefined)), { + type: 200, + id: 0, + data: undefined, + }); + }); + + it("rejects an unknown tag or a truncated body", () => { + assert.throws(() => decodeChannelFrameBody(Uint8Array.of(9)), /unknown tag 9/); + assert.throws(() => decodeChannelFrameBody(Uint8Array.of(1, 5, 65)), /truncated/); + }); +}); + +describe("channel framer", () => { + it("reassembles frames split across arbitrary chunks", () => { + const first = encodeChannelFrame([201, 1], ["first"]); + const second = encodeChannelFrame([204, 2], { delta: "second" }); + const joined = new Uint8Array(first.byteLength + second.byteLength); + joined.set(first, 0); + joined.set(second, first.byteLength); + + const framer = makeChannelFramer(); + const bodies = [ + ...framer(joined.slice(0, 5)), + ...framer(joined.slice(5, HEADER_BYTES + 2)), + ...framer(joined.slice(HEADER_BYTES + 2, joined.byteLength - 1)), + ...framer(joined.slice(joined.byteLength - 1)), + ]; + assert.equal(bodies.length, 2); + assert.deepEqual(decodeChannelFrameBody(bodies[0]!), { type: 201, id: 1, data: ["first"] }); + assert.deepEqual(decodeChannelFrameBody(bodies[1]!), { + type: 204, + id: 2, + data: { delta: "second" }, + }); + }); + + it("emits every complete frame carried by one chunk", () => { + const first = encodeChannelFrame([204, 1], "a"); + const second = encodeChannelFrame([204, 2], "b"); + const joined = new Uint8Array(first.byteLength + second.byteLength); + joined.set(first, 0); + joined.set(second, first.byteLength); + assert.equal(makeChannelFramer()(joined).length, 2); + }); + + it("drops frames whose kind is not a message and resumes at the next header", () => { + const other = incomingFrame(7, new Uint8Array([0])); + const message = encodeChannelFrame([204, 4], "payload"); + const joined = new Uint8Array(other.byteLength + message.byteLength); + joined.set(other, 0); + joined.set(message, other.byteLength); + + const bodies = makeChannelFramer()(joined); + assert.equal(bodies.length, 1); + assert.deepEqual(decodeChannelFrameBody(bodies[0]!), { + type: 204, + id: 4, + data: "payload", + }); + }); + + it("keeps a partial frame buffered", () => { + const framer = makeChannelFramer(); + const frame = encodeChannelFrame([204, 5], "later"); + assert.deepEqual(framer(frame.slice(0, HEADER_BYTES - 1)), []); + assert.equal(framer(frame.slice(HEADER_BYTES - 1)).length, 1); + }); +}); diff --git a/packages/provider-zcode/src/server/zcodeServeProtocol.ts b/packages/provider-zcode/src/server/zcodeServeProtocol.ts new file mode 100644 index 0000000000000..625884141998c --- /dev/null +++ b/packages/provider-zcode/src/server/zcodeServeProtocol.ts @@ -0,0 +1,460 @@ +// `zcode serve` hosts a daemon that owns CLI credentials and multiplexes sessions over a +// binary WebSocket channel protocol. This module is the wire half: frame codec plus a +// request/event client. The frame layout was reverse-engineered from the shipped desktop +// client (runtime 3.17.2); it is undocumented and pinned to that runtime. +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Scope from "effect/Scope"; + +import { ZcodeProtocolError, ZcodeProtocolTimeoutError } from "./zcodeProtocol.ts"; + +/** 1 byte frame kind, u32 request id, u32 ack, u32 body length. */ +const FRAME_HEADER_BYTES = 13; +const FRAME_KIND_MESSAGE = 1; + +const CALL = 100; +const LISTEN = 102; +const INITIALIZED = 200; +const RESULT = 201; +const ERROR = 202; +const REJECTED = 203; +const EVENT = 204; + +const TAG_UNDEFINED = 0; +const TAG_STRING = 1; +const TAG_BUFFER = 2; +const TAG_ARRAY = 4; +const TAG_OBJECT = 5; +const TAG_INT = 6; + +const textEncoder = new TextEncoder(); +const textDecoder = new TextDecoder(); + +const writeVarint = (bytes: number[], value: number): void => { + if (value === 0) { + bytes.push(0); + return; + } + for (let rest = value; rest !== 0; rest = Math.floor(rest / 128)) { + const byte = rest & 0x7f; + bytes.push(rest > 0x7f ? byte | 0x80 : byte); + } +}; + +const appendBytes = (bytes: number[], chunk: Uint8Array): void => { + for (const byte of chunk) bytes.push(byte); +}; + +const serializeInto = (bytes: number[], value: unknown): void => { + if (value === undefined) { + bytes.push(TAG_UNDEFINED); + return; + } + if (typeof value === "string") { + const encoded = textEncoder.encode(value); + bytes.push(TAG_STRING); + writeVarint(bytes, encoded.byteLength); + appendBytes(bytes, encoded); + return; + } + if (value instanceof Uint8Array) { + bytes.push(TAG_BUFFER); + writeVarint(bytes, value.byteLength); + appendBytes(bytes, value); + return; + } + if (Array.isArray(value)) { + bytes.push(TAG_ARRAY); + writeVarint(bytes, value.length); + for (const element of value) serializeInto(bytes, element); + return; + } + if (typeof value === "number" && Number.isInteger(value)) { + bytes.push(TAG_INT); + writeVarint(bytes, value); + return; + } + const encoded = textEncoder.encode(JSON.stringify(value) ?? "null"); + bytes.push(TAG_OBJECT); + writeVarint(bytes, encoded.byteLength); + appendBytes(bytes, encoded); +}; + +class Reader { + private offset = 0; + private readonly bytes: Uint8Array; + + constructor(bytes: Uint8Array) { + this.bytes = bytes; + } + + read(count: number): Uint8Array { + const out = this.bytes.subarray(this.offset, this.offset + count); + if (out.byteLength !== count) throw new Error("zcode channel frame truncated"); + this.offset += count; + return out; + } +} + +const readVarint = (reader: Reader): number => { + let value = 0; + for (let shift = 0; ; shift += 7) { + const [byte = 0] = reader.read(1); + value += (byte & 0x7f) * 2 ** shift; + if ((byte & 0x80) === 0) return value; + } +}; + +const deserializeFrom = (reader: Reader): unknown => { + const [tag = -1] = reader.read(1); + switch (tag) { + case TAG_UNDEFINED: + return undefined; + case TAG_STRING: + return textDecoder.decode(reader.read(readVarint(reader))); + case TAG_BUFFER: + return reader.read(readVarint(reader)); + case TAG_ARRAY: { + const length = readVarint(reader); + return Array.from({ length }, () => deserializeFrom(reader)); + } + case TAG_OBJECT: + return JSON.parse(textDecoder.decode(reader.read(readVarint(reader)))); + case TAG_INT: + return readVarint(reader); + default: + throw new Error(`zcode channel frame has unknown tag ${tag}`); + } +}; + +/** One outbound message frame: `` then the serialized body. */ +export function encodeChannelFrame( + header: ReadonlyArray, + arg: unknown, +): Uint8Array { + const body: number[] = []; + serializeInto(body, header); + serializeInto(body, arg); + const buffer = new ArrayBuffer(FRAME_HEADER_BYTES + body.length); + const frame = new Uint8Array(buffer); + frame[0] = FRAME_KIND_MESSAGE; + const view = new DataView(buffer); + view.setUint32(1, 0); + view.setUint32(5, 0); + view.setUint32(9, body.length); + frame.set(Uint8Array.from(body), FRAME_HEADER_BYTES); + return frame; +} + +export interface ZcodeChannelFrame { + readonly type: number; + readonly id: number; + readonly data: unknown; +} + +/** Parses a message body; frames other than messages carry nothing we consume. */ +export function decodeChannelFrameBody(body: Uint8Array): ZcodeChannelFrame | undefined { + const reader = new Reader(body); + const header = deserializeFrom(reader); + if (!Array.isArray(header)) return undefined; + const [type, id] = header; + if (typeof type !== "number") return undefined; + if (type === INITIALIZED) return { type, id: 0, data: undefined }; + return { type, id: typeof id === "number" ? id : 0, data: deserializeFrom(reader) }; +} + +/** Reassembles WebSocket frames into channel message bodies. */ +export function makeChannelFramer(): (chunk: Uint8Array) => ReadonlyArray { + const chunks: Uint8Array[] = []; + let length = 0; + + const take = (count: number): Uint8Array => { + const out = new Uint8Array(count); + let offset = 0; + for (const chunk of chunks) { + const slice = chunk.subarray(0, Math.min(chunk.byteLength, count - offset)); + out.set(slice, offset); + offset += slice.byteLength; + if (offset === count) break; + } + let remaining = count; + while (remaining > 0) { + const head = chunks[0]; + if (head === undefined) break; + if (head.byteLength <= remaining) { + remaining -= head.byteLength; + chunks.shift(); + } else { + chunks[0] = head.subarray(remaining); + remaining = 0; + } + } + length -= count; + return out; + }; + + const peekHeader = (): Uint8Array => { + const out = new Uint8Array(FRAME_HEADER_BYTES); + let offset = 0; + for (const chunk of chunks) { + const slice = chunk.subarray(0, Math.min(chunk.byteLength, FRAME_HEADER_BYTES - offset)); + out.set(slice, offset); + offset += slice.byteLength; + if (offset === FRAME_HEADER_BYTES) break; + } + return out; + }; + + return (chunk) => { + if (chunk.byteLength > 0) { + chunks.push(chunk); + length += chunk.byteLength; + } + const bodies: Uint8Array[] = []; + for (;;) { + if (length < FRAME_HEADER_BYTES) break; + const header = peekHeader(); + const bodyLength = + ((header[9] ?? 0) * 0x1000000 + + ((header[10] ?? 0) << 16) + + ((header[11] ?? 0) << 8) + + (header[12] ?? 0)) >>> + 0; + if (length < FRAME_HEADER_BYTES + bodyLength) break; + take(FRAME_HEADER_BYTES); + const body = bodyLength === 0 ? new Uint8Array(0) : take(bodyLength); + if (header[0] === FRAME_KIND_MESSAGE) bodies.push(body); + } + return bodies; + }; +} + +export interface ZcodeChannelClient { + readonly call: ( + channel: string, + method: string, + arg: unknown, + timeoutMs?: number, + ) => Effect.Effect; + readonly listen: ( + channel: string, + event: string, + arg: unknown, + onEvent: (payload: unknown) => void, + ) => Effect.Effect; + /** Resolves when the socket closes; never fails, so finalizers stay quiet. */ + readonly closed: Effect.Effect; +} + +export interface ZcodeChannelClientOptions { + readonly url: string; + readonly headers?: Readonly>; +} + +interface PendingCall { + readonly deferred: Deferred.Deferred; + readonly method: string; +} + +const DEFAULT_CALL_TIMEOUT_MS = 60_000; +const INITIALIZE_TIMEOUT_MS = 15_000; + +/** + * Node's global WebSocket (undici) accepts request headers; the DOM lib typing does not. + * `/ws/host` rejects the handshake without the capability header, so the cast is required. + */ +const openSocket = (url: string, headers: Readonly>): WebSocket => + new (WebSocket as unknown as new ( + url: string, + init: { headers: Record }, + ) => WebSocket)(url, { headers: { ...headers } }); + +export const makeZcodeChannelClient = Effect.fnUntraced(function* ( + options: ZcodeChannelClientOptions, +) { + const scope = yield* Effect.scope; + const pending = new Map(); + const listeners = new Map void>(); + const initialized = yield* Deferred.make(); + const closed = yield* Deferred.make(); + const initQueue = yield* Queue.unbounded(); + const results = yield* Queue.unbounded<{ + readonly call: PendingCall; + readonly data: unknown; + readonly failed: boolean; + }>(); + const failures = yield* Queue.unbounded(); + const socketClosures = yield* Queue.unbounded(); + const frame = makeChannelFramer(); + let nextId = 0; + + const transportError = (operation: string, cause: unknown) => + new ZcodeProtocolError({ operation, cause }); + + const failAll = Effect.fn("ZcodeChannel.failAll")(function* (error: ZcodeProtocolError) { + yield* Deferred.fail(initialized, error).pipe(Effect.ignore); + for (const [id, call] of pending) { + pending.delete(id); + yield* Deferred.fail(call.deferred, error).pipe(Effect.ignore); + } + yield* Deferred.succeed(closed, undefined).pipe(Effect.ignore); + }); + + const socket = openSocket(options.url, options.headers ?? {}); + socket.binaryType = "arraybuffer"; + + const route = (parsed: ZcodeChannelFrame): void => { + if (parsed.type === INITIALIZED) { + Queue.offerUnsafe(initQueue, undefined); + return; + } + if (parsed.type === EVENT) { + listeners.get(parsed.id)?.(parsed.data); + return; + } + const call = pending.get(parsed.id); + if (call === undefined) return; + pending.delete(parsed.id); + if (parsed.type === RESULT) { + Queue.offerUnsafe(results, { call, data: parsed.data, failed: false }); + return; + } + if (parsed.type === ERROR || parsed.type === REJECTED) { + Queue.offerUnsafe(results, { call, data: parsed.data, failed: true }); + } + }; + + const onMessage = (event: MessageEvent) => { + const data: unknown = event.data; + const bytes = + data instanceof ArrayBuffer + ? new Uint8Array(data) + : ArrayBuffer.isView(data) + ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) + : undefined; + if (bytes === undefined) return; + for (const body of frame(bytes)) { + try { + const parsed = decodeChannelFrameBody(body); + if (parsed !== undefined) route(parsed); + } catch (cause) { + Queue.offerUnsafe(failures, cause); + } + } + }; + + socket.addEventListener("message", onMessage); + socket.addEventListener("close", (event) => + Queue.offerUnsafe(socketClosures, `code ${event.code}`), + ); + socket.addEventListener("error", () => Queue.offerUnsafe(socketClosures, "socket error")); + + yield* Scope.addFinalizer( + scope, + Effect.sync(() => { + socket.removeEventListener("message", onMessage); + socket.close(); + }), + ); + + // Settlement and closure handling run off the callback path so socket callbacks stay cheap. + yield* Effect.gen(function* () { + for (;;) { + const settled = yield* Queue.take(results); + yield* settled.failed + ? Deferred.fail( + settled.call.deferred, + transportError(settled.call.method, settled.data), + ).pipe(Effect.ignore) + : Deferred.succeed(settled.call.deferred, settled.data).pipe(Effect.ignore); + } + }).pipe(Effect.forkIn(scope), Effect.asVoid); + + yield* Effect.gen(function* () { + for (;;) { + const reason = yield* Queue.take(socketClosures); + yield* failAll(transportError("connect", `zcode server channel closed (${reason})`)); + } + }).pipe(Effect.forkIn(scope), Effect.asVoid); + + yield* Effect.gen(function* () { + for (;;) { + const cause = yield* Queue.take(failures); + yield* failAll(transportError("decode", cause)); + } + }).pipe(Effect.forkIn(scope), Effect.asVoid); + + yield* Effect.raceFirst( + Queue.take(initQueue).pipe( + Effect.timeoutOption(Duration.millis(INITIALIZE_TIMEOUT_MS)), + Effect.flatMap((ready) => + Option.isSome(ready) + ? Deferred.succeed(initialized, true).pipe(Effect.ignore) + : failAll(transportError("initialize", "zcode server channel handshake timed out")), + ), + ), + Deferred.await(closed), + ).pipe(Effect.ignore, Effect.forkIn(scope), Effect.asVoid); + + const awaitInitialized = Deferred.await(initialized); + + const send = (header: ReadonlyArray, arg: unknown) => + Effect.suspend(() => { + if (socket.readyState !== WebSocket.OPEN) { + return Effect.fail(transportError("send", "zcode server channel is not open")); + } + socket.send(encodeChannelFrame(header, arg)); + return Effect.void; + }); + + const call = Effect.fn("ZcodeChannel.call")(function* ( + channel: string, + method: string, + arg: unknown, + timeoutMs = DEFAULT_CALL_TIMEOUT_MS, + ): Effect.fn.Return { + yield* awaitInitialized; + const id = nextId++; + const deferred = yield* Deferred.make(); + pending.set(id, { deferred, method: `${channel}.${method}` }); + yield* send([CALL, id, channel, method], [arg]).pipe( + Effect.onError(() => Effect.sync(() => pending.delete(id))), + ); + return yield* Deferred.await(deferred).pipe( + Effect.timeoutOrElse({ + duration: Duration.millis(timeoutMs), + orElse: () => + Effect.fail( + new ZcodeProtocolTimeoutError({ operation: `${channel}.${method}`, timeoutMs }), + ), + }), + Effect.onInterrupt(() => Effect.sync(() => pending.delete(id))), + Effect.onError(() => Effect.sync(() => pending.delete(id))), + ); + }); + + const listen = Effect.fn("ZcodeChannel.listen")(function* ( + channel: string, + event: string, + arg: unknown, + onEvent: (payload: unknown) => void, + ) { + yield* awaitInitialized; + const id = nextId++; + listeners.set(id, onEvent); + yield* Scope.addFinalizer( + scope, + Effect.sync(() => void listeners.delete(id)), + ); + yield* send([LISTEN, id, channel, event], arg); + }); + + return { + call, + listen, + closed: Deferred.await(closed), + } satisfies ZcodeChannelClient; +}); diff --git a/packages/provider-zcode/src/settings.ts b/packages/provider-zcode/src/settings.ts index 824acf95f7c13..3b3be92cbd386 100644 --- a/packages/provider-zcode/src/settings.ts +++ b/packages/provider-zcode/src/settings.ts @@ -25,7 +25,8 @@ export const ZcodeSettings = makeProviderSettingsSchema( Schema.withDecodingDefault(Effect.succeed("")), Schema.annotateKey({ title: "Launch arguments", - description: "Additional CLI arguments passed to zcode app-server on session start.", + description: + "Additional CLI arguments passed to `zcode serve` when T3 Code starts the ZCode daemon.", providerSettingsForm: { clearWhenEmpty: "omit" }, }), ), diff --git a/packages/provider-zcode/src/testing.ts b/packages/provider-zcode/src/testing.ts index 9f8c2d5e1d8a5..7112dc6486e2d 100644 --- a/packages/provider-zcode/src/testing.ts +++ b/packages/provider-zcode/src/testing.ts @@ -9,5 +9,4 @@ export type { ZcodeProtocolError, ZcodeProtocolTimeoutError, ZcodeRecord, - ZcodeSpawnOptions, } from "./server/zcodeProtocol.ts";