@karlorz/codexhost-cli-win32-x64 0.17.0-1 → 0.17.3-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -28551,6 +28551,21 @@ var threadSteeringInspectParamsSchema = external_exports.object({
28551
28551
  /** The text about to be steered; a Harness command always stops and restarts. */
28552
28552
  text: external_exports.string().optional()
28553
28553
  }).strict();
28554
+ var threadSteeringContextSchema = external_exports.object({
28555
+ kind: external_exports.literal("application"),
28556
+ value: external_exports.string().transform((text, context) => {
28557
+ try {
28558
+ return JSON.parse(text);
28559
+ } catch {
28560
+ context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
28561
+ return external_exports.NEVER;
28562
+ }
28563
+ }).pipe(external_exports.object({
28564
+ expectedTurnId: hostTurnIdSchema,
28565
+ clientUserMessageId: external_exports.string().min(1),
28566
+ delivery: external_exports.enum(["newTurn", "activeTurn"])
28567
+ }).strict())
28568
+ }).strict().transform((context) => context.value);
28554
28569
  var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
28555
28570
  var threadSteeringInspectResultSchema = external_exports.object({
28556
28571
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
@@ -28148,6 +28148,21 @@ var threadSteeringInspectParamsSchema = external_exports.object({
28148
28148
  /** The text about to be steered; a Harness command always stops and restarts. */
28149
28149
  text: external_exports.string().optional()
28150
28150
  }).strict();
28151
+ var threadSteeringContextSchema = external_exports.object({
28152
+ kind: external_exports.literal("application"),
28153
+ value: external_exports.string().transform((text, context) => {
28154
+ try {
28155
+ return JSON.parse(text);
28156
+ } catch {
28157
+ context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
28158
+ return external_exports.NEVER;
28159
+ }
28160
+ }).pipe(external_exports.object({
28161
+ expectedTurnId: hostTurnIdSchema,
28162
+ clientUserMessageId: external_exports.string().min(1),
28163
+ delivery: external_exports.enum(["newTurn", "activeTurn"])
28164
+ }).strict())
28165
+ }).strict().transform((context) => context.value);
28151
28166
  var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
28152
28167
  var threadSteeringInspectResultSchema = external_exports.object({
28153
28168
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
@@ -22453,6 +22453,21 @@ var threadSteeringInspectParamsSchema = external_exports.object({
22453
22453
  /** The text about to be steered; a Harness command always stops and restarts. */
22454
22454
  text: external_exports.string().optional()
22455
22455
  }).strict();
22456
+ var threadSteeringContextSchema = external_exports.object({
22457
+ kind: external_exports.literal("application"),
22458
+ value: external_exports.string().transform((text, context) => {
22459
+ try {
22460
+ return JSON.parse(text);
22461
+ } catch {
22462
+ context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
22463
+ return external_exports.NEVER;
22464
+ }
22465
+ }).pipe(external_exports.object({
22466
+ expectedTurnId: hostTurnIdSchema,
22467
+ clientUserMessageId: external_exports.string().min(1),
22468
+ delivery: external_exports.enum(["newTurn", "activeTurn"])
22469
+ }).strict())
22470
+ }).strict().transform((context) => context.value);
22456
22471
  var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
22457
22472
  var threadSteeringInspectResultSchema = external_exports.object({
22458
22473
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
@@ -15565,6 +15565,21 @@ var threadSteeringInspectParamsSchema = external_exports.object({
15565
15565
  /** The text about to be steered; a Harness command always stops and restarts. */
15566
15566
  text: external_exports.string().optional()
15567
15567
  }).strict();
15568
+ var threadSteeringContextSchema = external_exports.object({
15569
+ kind: external_exports.literal("application"),
15570
+ value: external_exports.string().transform((text2, context) => {
15571
+ try {
15572
+ return JSON.parse(text2);
15573
+ } catch {
15574
+ context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
15575
+ return external_exports.NEVER;
15576
+ }
15577
+ }).pipe(external_exports.object({
15578
+ expectedTurnId: hostTurnIdSchema,
15579
+ clientUserMessageId: external_exports.string().min(1),
15580
+ delivery: external_exports.enum(["newTurn", "activeTurn"])
15581
+ }).strict())
15582
+ }).strict().transform((context) => context.value);
15568
15583
  var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
15569
15584
  var threadSteeringInspectResultSchema = external_exports.object({
15570
15585
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
@@ -15751,6 +15751,21 @@ var threadSteeringInspectParamsSchema = external_exports.object({
15751
15751
  /** The text about to be steered; a Harness command always stops and restarts. */
15752
15752
  text: external_exports.string().optional()
15753
15753
  }).strict();
15754
+ var threadSteeringContextSchema = external_exports.object({
15755
+ kind: external_exports.literal("application"),
15756
+ value: external_exports.string().transform((text2, context) => {
15757
+ try {
15758
+ return JSON.parse(text2);
15759
+ } catch {
15760
+ context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
15761
+ return external_exports.NEVER;
15762
+ }
15763
+ }).pipe(external_exports.object({
15764
+ expectedTurnId: hostTurnIdSchema,
15765
+ clientUserMessageId: external_exports.string().min(1),
15766
+ delivery: external_exports.enum(["newTurn", "activeTurn"])
15767
+ }).strict())
15768
+ }).strict().transform((context) => context.value);
15754
15769
  var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
15755
15770
  var threadSteeringInspectResultSchema = external_exports.object({
15756
15771
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
@@ -17052,7 +17067,7 @@ function createZcodeInstallation(environment, app) {
17052
17067
  }
17053
17068
 
17054
17069
  // dist/account.js
17055
- import { createHash as createHash3 } from "node:crypto";
17070
+ import { createHash as createHash4 } from "node:crypto";
17056
17071
  import { readFile as readFile3 } from "node:fs/promises";
17057
17072
  import path5 from "node:path";
17058
17073
 
@@ -17101,10 +17116,100 @@ async function readCredential(installation, environment, key) {
17101
17116
  }
17102
17117
 
17103
17118
  // dist/personal-coding-plan.js
17104
- import { createHash as createHash2 } from "node:crypto";
17119
+ import { createHash as createHash3 } from "node:crypto";
17105
17120
  import { readFile as readFile2 } from "node:fs/promises";
17106
17121
  import { homedir as homedir3 } from "node:os";
17107
17122
  import path4 from "node:path";
17123
+
17124
+ // dist/project-token.js
17125
+ import { createHash as createHash2 } from "node:crypto";
17126
+ var locationSchema = external_exports.object({
17127
+ organizationId: external_exports.string().trim().min(1),
17128
+ projectId: external_exports.string().trim().min(1),
17129
+ apiKeyId: external_exports.string().trim().min(1)
17130
+ });
17131
+ function readProjectCredential(credential, family, identity, origin) {
17132
+ const key = `project-key-location:v1:${encodeURIComponent(JSON.stringify([origin, family, identity, null, 1, "non-team"]))}`;
17133
+ const raw = credential(key);
17134
+ if (!raw)
17135
+ return void 0;
17136
+ const location = locationSchema.parse(JSON.parse(raw));
17137
+ const login = credential(`oauth:${family}:access_token`).trim();
17138
+ const loginToken = login.replace(/^Bearer\s+/i, "").trim();
17139
+ if (!loginToken)
17140
+ throw projectCredentialError();
17141
+ const accountScope = createHash2("sha256").update(JSON.stringify([
17142
+ family,
17143
+ "individual-coding-plan",
17144
+ null,
17145
+ login,
17146
+ credential("zcodejwttoken").trim() || null
17147
+ ])).digest("hex");
17148
+ return { origin, loginToken, location, accountScope };
17149
+ }
17150
+ var tokenSchema = external_exports.object({
17151
+ success: external_exports.boolean().optional(),
17152
+ code: external_exports.union([external_exports.literal(0), external_exports.literal(200), external_exports.literal("0"), external_exports.literal("200")]),
17153
+ data: external_exports.object({
17154
+ enable: external_exports.boolean().optional(),
17155
+ accessToken: external_exports.string().trim().min(1),
17156
+ tokenType: external_exports.literal("Bearer"),
17157
+ expiresIn: external_exports.number().finite().positive(),
17158
+ expiresAt: external_exports.number().finite().positive()
17159
+ })
17160
+ });
17161
+ function projectCredentialError() {
17162
+ return new ZcodeError("authenticationRequired", "ZCode Personal Coding Plan project credentials are unavailable. Open the personal plan in ZCode Desktop, then re-detect ZCode and reopen the Thread");
17163
+ }
17164
+ var ProjectToken = class {
17165
+ #cached;
17166
+ async resolve(credential, appVersion, signal, rejectedFingerprint) {
17167
+ signal.throwIfAborted();
17168
+ const scope = createHash2("sha256").update(JSON.stringify(credential)).digest("hex");
17169
+ const cached2 = this.#cached;
17170
+ if (cached2?.scope === scope && cached2.fingerprint !== rejectedFingerprint && cached2.expiresAt > Date.now() + 12e4)
17171
+ return cached2.token;
17172
+ this.#cached = void 0;
17173
+ const { origin, location, loginToken } = credential;
17174
+ const url2 = `${origin}/api/biz/v1/organization/${encodeURIComponent(location.organizationId)}/projects/${encodeURIComponent(location.projectId)}/api_keys/${encodeURIComponent(location.apiKeyId)}/access_tokens`;
17175
+ const started = Date.now();
17176
+ try {
17177
+ const response = await fetch(url2, {
17178
+ method: "POST",
17179
+ headers: { Authorization: `Bearer ${loginToken}`, "Content-Type": "application/json" },
17180
+ body: JSON.stringify({ clientType: "zcode", clientVersion: appVersion }),
17181
+ redirect: "error",
17182
+ signal: AbortSignal.any([signal, AbortSignal.timeout(15e3)])
17183
+ });
17184
+ if (!response.ok)
17185
+ throw projectCredentialError();
17186
+ const parsed = tokenSchema.safeParse(await response.json());
17187
+ if (!parsed.success || parsed.data.success === false || parsed.data.data.enable === false)
17188
+ throw projectCredentialError();
17189
+ const data = parsed.data.data;
17190
+ const expiresAt = Math.min(data.expiresAt * 1e3, started + data.expiresIn * 1e3);
17191
+ signal.throwIfAborted();
17192
+ if (expiresAt <= Date.now())
17193
+ throw projectCredentialError();
17194
+ this.#cached = {
17195
+ scope,
17196
+ token: data.accessToken,
17197
+ expiresAt,
17198
+ fingerprint: createHash2("sha256").update(data.accessToken).digest("hex")
17199
+ };
17200
+ return data.accessToken;
17201
+ } catch (error51) {
17202
+ signal.throwIfAborted();
17203
+ if (error51 instanceof ZcodeError)
17204
+ throw error51;
17205
+ if (error51 instanceof Error && error51.name === "TimeoutError")
17206
+ throw new ZcodeError("unavailable", "ZCode project token request timed out. Try again.", true);
17207
+ throw projectCredentialError();
17208
+ }
17209
+ }
17210
+ };
17211
+
17212
+ // dist/personal-coding-plan.js
17108
17213
  var familySchema = external_exports.enum(["zai", "bigmodel"]);
17109
17214
  var recordSchema2 = external_exports.record(external_exports.string(), external_exports.unknown());
17110
17215
  var CONNECT = "Connect Personal Coding Plan in ZCode Desktop, then re-detect ZCode and reopen the Thread";
@@ -17158,7 +17263,7 @@ async function queryEntitlement(family, apiKey, environment) {
17158
17263
  try {
17159
17264
  const response = await fetch(`${personalCodingPlanOrigin(family, environment)}/api/biz/subscription/list`, {
17160
17265
  method: "GET",
17161
- // The subscription endpoint accepts the model API Key, not the OAuth token or Start JWT.
17266
+ // Legacy Desktop uses a personal API Key; project-token Desktop uses its OAuth login.
17162
17267
  headers: { Authorization: apiKey.trim() },
17163
17268
  redirect: "error",
17164
17269
  signal: AbortSignal.timeout(15e3)
@@ -17192,6 +17297,8 @@ var PersonalCodingPlanAccount = class {
17192
17297
  installation;
17193
17298
  environment;
17194
17299
  #authorized = /* @__PURE__ */ new Map();
17300
+ #projectToken = new ProjectToken();
17301
+ issue;
17195
17302
  constructor(installation, environment) {
17196
17303
  this.installation = installation;
17197
17304
  this.environment = environment;
@@ -17211,12 +17318,16 @@ var PersonalCodingPlanAccount = class {
17211
17318
  const identity = normalized ? normalized.id.trim() : family === "zai" && typeof profile.user_id === "string" ? profile.user_id.trim() : "";
17212
17319
  if (!identity || identity === "unknown")
17213
17320
  return void 0;
17321
+ const project2 = readProjectCredential(credential, family, identity, personalCodingPlanOrigin(family, this.environment));
17322
+ if (project2)
17323
+ return { identity, current, apiKey: project2.loginToken, project: project2 };
17214
17324
  const key = `account-provider:coding-plan:${providerId}:account:${encodeURIComponent(identity)}:api-key`;
17215
17325
  return { identity, current, apiKey: credential(key).trim() };
17216
17326
  }
17217
17327
  async inspect(providerId, accountType) {
17218
17328
  const family = familySchema.parse(accountType);
17219
17329
  this.#authorized.delete(providerId);
17330
+ this.issue = void 0;
17220
17331
  let current = false;
17221
17332
  try {
17222
17333
  const context = await this.#context(providerId, family);
@@ -17228,24 +17339,29 @@ var PersonalCodingPlanAccount = class {
17228
17339
  unavailableReason: "not-connected"
17229
17340
  };
17230
17341
  current = context.current;
17231
- const connectionKey = createHash2("sha256").update(JSON.stringify([family, context.identity, "individual-coding-plan"])).digest("hex");
17342
+ const connectionKey = createHash3("sha256").update(JSON.stringify([family, context.identity, "individual-coding-plan"])).digest("hex");
17232
17343
  const base = { current, connectionKey };
17233
- if (!context.apiKey)
17344
+ if (!context.apiKey) {
17345
+ if (current)
17346
+ this.issue = "ZCode is signed in, but its Personal Coding Plan credentials are not initialized. Open the personal plan in ZCode Desktop, then re-detect ZCode. This does not mean the subscription is inactive.";
17234
17347
  return {
17235
17348
  ...base,
17236
17349
  availability: "unavailable",
17237
17350
  entitled: false,
17238
17351
  unavailableReason: "credential-failed"
17239
17352
  };
17353
+ }
17240
17354
  const entitlement = await queryEntitlement(family, context.apiKey, this.environment);
17241
17355
  const after = await this.#context(providerId, family);
17242
- if (!after || after.identity !== context.identity || after.current !== current || after.apiKey !== context.apiKey)
17356
+ if (!after || after.identity !== context.identity || after.current !== current || after.apiKey !== context.apiKey || JSON.stringify(after.project) !== JSON.stringify(context.project))
17243
17357
  return { availability: "unknown", entitled: false, current: false };
17244
17358
  if (entitlement === "available") {
17245
17359
  if (current)
17246
17360
  this.#authorized.set(providerId, { family, identity: context.identity });
17247
17361
  return { ...base, availability: "available", entitled: true };
17248
17362
  }
17363
+ if (current)
17364
+ this.issue = entitlement === "unavailable" ? "ZCode Personal Coding Plan subscription check found no active subscription. Check the selected account in ZCode Desktop, then re-detect ZCode." : "ZCode Personal Coding Plan credentials or subscription could not be verified. Open the personal plan in ZCode Desktop, then re-detect ZCode; subscription status is unknown.";
17249
17365
  return {
17250
17366
  ...base,
17251
17367
  availability: entitlement === "unknown" ? "unknown" : "unavailable",
@@ -17255,6 +17371,9 @@ var PersonalCodingPlanAccount = class {
17255
17371
  }
17256
17372
  };
17257
17373
  } catch {
17374
+ current = await readSelection(this.environment, family).catch(() => false);
17375
+ if (current)
17376
+ this.issue = "ZCode Personal Coding Plan credentials could not be read or verified. Open the personal plan in ZCode Desktop, then re-detect ZCode; subscription status is unknown.";
17258
17377
  return { availability: "unknown", entitled: false, current };
17259
17378
  }
17260
17379
  }
@@ -17266,7 +17385,9 @@ var PersonalCodingPlanAccount = class {
17266
17385
  type: external_exports.literal("zhipu-account"),
17267
17386
  mode: external_exports.literal("individual-coding-plan"),
17268
17387
  accountType: familySchema
17269
- })
17388
+ }),
17389
+ expectedAccountScope: external_exports.string().optional(),
17390
+ rejectedProjectTokenFingerprint: external_exports.string().optional()
17270
17391
  }).safeParse(request);
17271
17392
  if (!parsed.success)
17272
17393
  throw new ZcodeError("authenticationRequired", CONNECT);
@@ -17279,6 +17400,23 @@ var PersonalCodingPlanAccount = class {
17279
17400
  signal.throwIfAborted();
17280
17401
  if (!context?.current || context.identity !== authorized.identity || !context.apiKey)
17281
17402
  throw new ZcodeError("authenticationRequired", CONNECT);
17403
+ if (context.project) {
17404
+ const { expectedAccountScope, rejectedProjectTokenFingerprint } = parsed.data;
17405
+ if (expectedAccountScope !== void 0 && expectedAccountScope !== context.project.accountScope || rejectedProjectTokenFingerprint && !expectedAccountScope)
17406
+ throw new ZcodeError("authenticationRequired", CONNECT);
17407
+ const apiKey = await this.#projectToken.resolve(context.project, this.installation.version, signal, rejectedProjectTokenFingerprint);
17408
+ const after = await this.#context(providerId, authorized.family);
17409
+ signal.throwIfAborted();
17410
+ if (!after?.current || after.identity !== context.identity || JSON.stringify(after.project) !== JSON.stringify(context.project))
17411
+ throw new ZcodeError("authenticationRequired", CONNECT);
17412
+ return {
17413
+ apiKey,
17414
+ apiKeyId: context.project.location.apiKeyId,
17415
+ accountScope: context.project.accountScope
17416
+ };
17417
+ }
17418
+ if (parsed.data.expectedAccountScope !== void 0 || parsed.data.rejectedProjectTokenFingerprint)
17419
+ throw new ZcodeError("authenticationRequired", CONNECT);
17282
17420
  return { apiKey: context.apiKey };
17283
17421
  }
17284
17422
  };
@@ -17404,7 +17542,7 @@ async function queryStartPlanBalance(origin, appVersion, jwt2, deviceMid) {
17404
17542
  async function accountConfig(installation, environment) {
17405
17543
  const file2 = installation.builtinProviderConfig;
17406
17544
  const builtin = builtinSchema.parse(JSON.parse(await readFile3(file2, "utf8")));
17407
- const basedOnZCodeBuiltinRevision = `zcode-builtin:${builtin.revision}:${createHash3("sha256").update(path5.resolve(file2)).digest("hex")}`;
17545
+ const basedOnZCodeBuiltinRevision = `zcode-builtin:${builtin.revision}:${createHash4("sha256").update(path5.resolve(file2)).digest("hex")}`;
17408
17546
  const family = await readCredential(installation, environment, "oauth:active_provider");
17409
17547
  let balanceData;
17410
17548
  if (family) {
@@ -17456,7 +17594,7 @@ async function accountConfig(installation, environment) {
17456
17594
  };
17457
17595
  }
17458
17596
  }
17459
- const overlayDigest = createHash3("sha256").update(JSON.stringify([providers, states])).digest("hex").slice(0, 16);
17597
+ const overlayDigest = createHash4("sha256").update(JSON.stringify([providers, states])).digest("hex").slice(0, 16);
17460
17598
  return {
17461
17599
  params: {
17462
17600
  revision: `codexhost:${family || "signed-out"}:${builtin.revision}:${overlayDigest}`,
@@ -17473,6 +17611,7 @@ async function accountConfig(installation, environment) {
17473
17611
  async function providerRuntimeHeaders(request, signal, installation, environment, verifier, codingPlan) {
17474
17612
  const mode = external_exports.object({ mode: external_exports.string() }).safeParse(request.accountAccess).data?.mode;
17475
17613
  try {
17614
+ signal.throwIfAborted();
17476
17615
  if (mode === "individual-coding-plan")
17477
17616
  return { headersApplied: true, requestAuth: await codingPlan.requestAuth(request, signal) };
17478
17617
  if (mode !== "start-plan")
@@ -17486,6 +17625,8 @@ async function providerRuntimeHeaders(request, signal, installation, environment
17486
17625
  const headers = await verifier().verify(signal);
17487
17626
  return { headersApplied: true, requestAuth: { apiKey, headers } };
17488
17627
  } catch (error51) {
17628
+ if (signal.aborted)
17629
+ return { headersApplied: false };
17489
17630
  return {
17490
17631
  headersApplied: false,
17491
17632
  errorMessage: error51 instanceof ZcodeError ? error51.message : "ZCode account authentication failed"
@@ -17594,6 +17735,9 @@ var CliTransport = class {
17594
17735
  get startPlanChecked() {
17595
17736
  return this.#startPlanChecked;
17596
17737
  }
17738
+ get codingPlanIssue() {
17739
+ return this.#codingPlan?.issue;
17740
+ }
17597
17741
  constructor(options) {
17598
17742
  this.options = options;
17599
17743
  this.#context = {
@@ -20370,6 +20514,10 @@ var ZcodeAdapter = class {
20370
20514
  code: "authenticationRequired",
20371
20515
  message: "ZCode has no available models. Sign in to ZCode Desktop with a Start Plan or Personal Coding Plan account, or add a personal provider, then re-detect ZCode. Team Coding Plan is not supported.",
20372
20516
  retryable: true
20517
+ } : transport.codingPlanIssue ? {
20518
+ code: "configurationRequired",
20519
+ message: transport.codingPlanIssue,
20520
+ retryable: true
20373
20521
  } : transport.startPlanChecked ? {
20374
20522
  code: "configurationRequired",
20375
20523
  message: "ZCode is signed in, but the account has no available models: no active Start Plan or event quota, no Personal Coding Plan, and no personal provider. Free trial and event quotas expire; subscribe to GLM Coding Plan or add a personal provider (API Key) in ZCode Desktop, then re-detect ZCode. Team Coding Plan is not supported.",