@liberseek/boft-cli-linux-x64 0.7.9 → 0.8.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.
Files changed (56) hide show
  1. package/README.md +1 -1
  2. package/THIRD_PARTY_NOTICES.txt +8 -0
  3. package/app/codexhost-distribution.json +1 -1
  4. package/app/console-server.mjs +232 -21
  5. package/app/console-web.js +9669 -5390
  6. package/app/desktop-controller.mjs +252 -42
  7. package/app/host-runtime.mjs +5361 -1491
  8. package/app/plugins/antigravity/manifest.json +18 -1
  9. package/app/plugins/antigravity/plugin.mjs +276 -42
  10. package/app/plugins/claude-code/manifest.json +28 -0
  11. package/app/plugins/claude-code/plugin.mjs +1055 -391
  12. package/app/plugins/codebuddy/manifest.json +17 -0
  13. package/app/plugins/codebuddy/plugin.mjs +5931 -5358
  14. package/app/plugins/codex-usage/manifest.json +9 -0
  15. package/app/plugins/codex-usage/plugin.mjs +16750 -0
  16. package/app/plugins/cursor-cli/manifest.json +18 -1
  17. package/app/plugins/cursor-cli/plugin.mjs +351 -77
  18. package/app/plugins/deepseek-harness/assets/icon.svg +1 -0
  19. package/app/plugins/deepseek-harness/manifest.json +35 -2
  20. package/app/plugins/deepseek-harness/plugin.mjs +798 -242
  21. package/app/plugins/enabled.json +2 -1
  22. package/app/plugins/grok/manifest.json +21 -1
  23. package/app/plugins/grok/plugin.mjs +898 -268
  24. package/app/plugins/hermes/assets/icon.png +0 -0
  25. package/app/plugins/hermes/manifest.json +30 -2
  26. package/app/plugins/hermes/plugin.mjs +278 -33
  27. package/app/plugins/kimi-code/assets/icon.svg +5 -0
  28. package/app/plugins/kimi-code/manifest.json +25 -2
  29. package/app/plugins/kimi-code/plugin.mjs +555 -36
  30. package/app/plugins/kiro-cli/assets/kiro-agent.svg +11 -0
  31. package/app/plugins/kiro-cli/manifest.json +18 -1
  32. package/app/plugins/kiro-cli/plugin.mjs +284 -22
  33. package/app/plugins/muse/manifest.json +18 -1
  34. package/app/plugins/muse/plugin.mjs +251 -17
  35. package/app/plugins/omp/manifest.json +21 -1
  36. package/app/plugins/omp/plugin.mjs +2741 -1960
  37. package/app/plugins/opencode/manifest.json +18 -1
  38. package/app/plugins/opencode/plugin.mjs +694 -147
  39. package/app/plugins/pi/manifest.json +32 -0
  40. package/app/plugins/pi/plugin.mjs +3396 -2841
  41. package/app/plugins/qoder/manifest.json +18 -1
  42. package/app/plugins/qoder/plugin.mjs +585 -81
  43. package/app/plugins/qoder-cn/manifest.json +18 -1
  44. package/app/plugins/qoder-cn/plugin.mjs +585 -81
  45. package/app/plugins/workbuddy/manifest.json +18 -0
  46. package/app/plugins/workbuddy/plugin.mjs +6317 -5746
  47. package/app/plugins/zcode/manifest.json +19 -1
  48. package/app/plugins/zcode/plugin.mjs +1066 -260
  49. package/app/renderer-extension.js +2731 -2427
  50. package/bin/boft +0 -0
  51. package/libexec/boft-shim +0 -0
  52. package/libexec/boft-updater +0 -0
  53. package/licenses/Cordis-LICENSE.txt +21 -0
  54. package/licenses/Cosmokit-LICENSE.txt +21 -0
  55. package/package.json +1 -1
  56. package/app/plugins/kiro-cli/assets/icon.svg +0 -5
@@ -5,9 +5,50 @@ var __export = (target, all) => {
5
5
  __defProp(target, name, { get: all[name], enumerable: true });
6
6
  };
7
7
 
8
- // dist/adapter.js
9
- import path3 from "node:path";
10
- import { stat as stat2 } from "node:fs/promises";
8
+ // dist/usage-statistics.js
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+ import { lstat } from "node:fs/promises";
12
+
13
+ // ../../harness-adapter/dist/usage-statistics.js
14
+ var MAX_SESSION_ID_LENGTH = 512;
15
+ var MAX_CWD_LENGTH = 4096;
16
+ function sessionIdOk(value) {
17
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
18
+ }
19
+ function cwdOk(value) {
20
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_CWD_LENGTH && !value.includes("\0") && (value.startsWith("/") || /^[A-Za-z]:[\\/]/u.test(value) || value.startsWith("\\\\"));
21
+ }
22
+ function withUsageSession(entry, session) {
23
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
24
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
25
+ if (sessionId === void 0 && cwd === void 0)
26
+ return entry;
27
+ return {
28
+ ...entry,
29
+ ...sessionId !== void 0 ? { sessionId } : {},
30
+ ...cwd !== void 0 ? { cwd } : {}
31
+ };
32
+ }
33
+ function usageEntryFromRequest(request, occurredAtMs) {
34
+ if (!Number.isSafeInteger(occurredAtMs) || occurredAtMs <= 0)
35
+ return null;
36
+ return {
37
+ id: request.requestId,
38
+ occurredAtMs,
39
+ ...request.model !== void 0 ? { model: request.model } : {},
40
+ inputTokens: request.inputTokens,
41
+ ...request.cachedInputTokens !== void 0 ? { cachedInputTokens: request.cachedInputTokens } : {},
42
+ ...request.cacheWriteInputTokens !== void 0 ? { cacheWriteInputTokens: request.cacheWriteInputTokens } : {},
43
+ ...request.cacheWrite1hInputTokens !== void 0 ? { cacheWrite1hInputTokens: request.cacheWrite1hInputTokens } : {},
44
+ outputTokens: request.outputTokens,
45
+ ...request.reasoningOutputTokens !== void 0 ? { reasoningOutputTokens: request.reasoningOutputTokens } : {}
46
+ };
47
+ }
48
+ function nativeTimeMs(value) {
49
+ const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
50
+ return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
51
+ }
11
52
 
12
53
  // ../../../node_modules/zod/v4/classic/external.js
13
54
  var external_exports = {};
@@ -775,10 +816,10 @@ function mergeDefs(...defs) {
775
816
  function cloneDef(schema) {
776
817
  return mergeDefs(schema._zod.def);
777
818
  }
778
- function getElementAtPath(obj, path4) {
779
- if (!path4)
819
+ function getElementAtPath(obj, path7) {
820
+ if (!path7)
780
821
  return obj;
781
- return path4.reduce((acc, key) => acc?.[key], obj);
822
+ return path7.reduce((acc, key) => acc?.[key], obj);
782
823
  }
783
824
  function promiseAllObject(promisesObj) {
784
825
  const keys = Object.keys(promisesObj);
@@ -1187,11 +1228,11 @@ function explicitlyAborted(x, startIndex = 0) {
1187
1228
  }
1188
1229
  return false;
1189
1230
  }
1190
- function prefixIssues(path4, issues) {
1231
+ function prefixIssues(path7, issues) {
1191
1232
  return issues.map((iss) => {
1192
1233
  var _a3;
1193
1234
  (_a3 = iss).path ?? (_a3.path = []);
1194
- iss.path.unshift(path4);
1235
+ iss.path.unshift(path7);
1195
1236
  return iss;
1196
1237
  });
1197
1238
  }
@@ -1338,16 +1379,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1338
1379
  }
1339
1380
  function formatError(error51, mapper = (issue2) => issue2.message) {
1340
1381
  const fieldErrors = { _errors: [] };
1341
- const processError = (error52, path4 = []) => {
1382
+ const processError = (error52, path7 = []) => {
1342
1383
  for (const issue2 of error52.issues) {
1343
1384
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1344
- issue2.errors.map((issues) => processError({ issues }, [...path4, ...issue2.path]));
1385
+ issue2.errors.map((issues) => processError({ issues }, [...path7, ...issue2.path]));
1345
1386
  } else if (issue2.code === "invalid_key") {
1346
- processError({ issues: issue2.issues }, [...path4, ...issue2.path]);
1387
+ processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1347
1388
  } else if (issue2.code === "invalid_element") {
1348
- processError({ issues: issue2.issues }, [...path4, ...issue2.path]);
1389
+ processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1349
1390
  } else {
1350
- const fullpath = [...path4, ...issue2.path];
1391
+ const fullpath = [...path7, ...issue2.path];
1351
1392
  if (fullpath.length === 0) {
1352
1393
  fieldErrors._errors.push(mapper(issue2));
1353
1394
  } else {
@@ -1374,17 +1415,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1374
1415
  }
1375
1416
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1376
1417
  const result = { errors: [] };
1377
- const processError = (error52, path4 = []) => {
1418
+ const processError = (error52, path7 = []) => {
1378
1419
  var _a3, _b;
1379
1420
  for (const issue2 of error52.issues) {
1380
1421
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1381
- issue2.errors.map((issues) => processError({ issues }, [...path4, ...issue2.path]));
1422
+ issue2.errors.map((issues) => processError({ issues }, [...path7, ...issue2.path]));
1382
1423
  } else if (issue2.code === "invalid_key") {
1383
- processError({ issues: issue2.issues }, [...path4, ...issue2.path]);
1424
+ processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1384
1425
  } else if (issue2.code === "invalid_element") {
1385
- processError({ issues: issue2.issues }, [...path4, ...issue2.path]);
1426
+ processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1386
1427
  } else {
1387
- const fullpath = [...path4, ...issue2.path];
1428
+ const fullpath = [...path7, ...issue2.path];
1388
1429
  if (fullpath.length === 0) {
1389
1430
  result.errors.push(mapper(issue2));
1390
1431
  continue;
@@ -1416,8 +1457,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1416
1457
  }
1417
1458
  function toDotPath(_path) {
1418
1459
  const segs = [];
1419
- const path4 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1420
- for (const seg of path4) {
1460
+ const path7 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1461
+ for (const seg of path7) {
1421
1462
  if (typeof seg === "number")
1422
1463
  segs.push(`[${seg}]`);
1423
1464
  else if (typeof seg === "symbol")
@@ -4645,8 +4686,8 @@ function az_default() {
4645
4686
  }
4646
4687
 
4647
4688
  // ../../../node_modules/zod/v4/locales/be.js
4648
- function getBelarusianPlural(count, one, few, many) {
4649
- const absCount = Math.abs(count);
4689
+ function getBelarusianPlural(count2, one, few, many) {
4690
+ const absCount = Math.abs(count2);
4650
4691
  const lastDigit = absCount % 10;
4651
4692
  const lastTwoDigits = absCount % 100;
4652
4693
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -6724,8 +6765,8 @@ function hu_default() {
6724
6765
  }
6725
6766
 
6726
6767
  // ../../../node_modules/zod/v4/locales/hy.js
6727
- function getArmenianPlural(count, one, many) {
6728
- return Math.abs(count) === 1 ? one : many;
6768
+ function getArmenianPlural(count2, one, many) {
6769
+ return Math.abs(count2) === 1 ? one : many;
6729
6770
  }
6730
6771
  function withDefiniteArticle(word) {
6731
6772
  if (!word)
@@ -8853,8 +8894,8 @@ function ro_default() {
8853
8894
  }
8854
8895
 
8855
8896
  // ../../../node_modules/zod/v4/locales/ru.js
8856
- function getRussianPlural(count, one, few, many) {
8857
- const absCount = Math.abs(count);
8897
+ function getRussianPlural(count2, one, few, many) {
8898
+ const absCount = Math.abs(count2);
8858
8899
  const lastDigit = absCount % 10;
8859
8900
  const lastTwoDigits = absCount % 100;
8860
8901
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -14109,13 +14150,13 @@ function resolveRef(ref, ctx) {
14109
14150
  if (!ref.startsWith("#")) {
14110
14151
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14111
14152
  }
14112
- const path4 = ref.slice(1).split("/").filter(Boolean);
14113
- if (path4.length === 0) {
14153
+ const path7 = ref.slice(1).split("/").filter(Boolean);
14154
+ if (path7.length === 0) {
14114
14155
  return ctx.rootSchema;
14115
14156
  }
14116
14157
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14117
- if (path4[0] === defsKey) {
14118
- const key = path4[1];
14158
+ if (path7[0] === defsKey) {
14159
+ const key = path7[1];
14119
14160
  if (!key || !ctx.defs[key]) {
14120
14161
  throw new Error(`Reference not found: ${ref}`);
14121
14162
  }
@@ -14317,8 +14358,8 @@ function convertBaseSchema(schema, ctx) {
14317
14358
  break;
14318
14359
  }
14319
14360
  const objectSchema2 = z.object(shape).passthrough();
14320
- const recordSchema2 = z.looseRecord(keySchema, valueSchema);
14321
- zodSchema = z.intersection(objectSchema2, recordSchema2);
14361
+ const recordSchema3 = z.looseRecord(keySchema, valueSchema);
14362
+ zodSchema = z.intersection(objectSchema2, recordSchema3);
14322
14363
  break;
14323
14364
  }
14324
14365
  if (schema.patternProperties) {
@@ -14523,6 +14564,143 @@ function date4(params) {
14523
14564
  // ../../../node_modules/zod/v4/classic/external.js
14524
14565
  config(en_default());
14525
14566
 
14567
+ // dist/protocol.js
14568
+ var recordSchema = external_exports.record(external_exports.string(), external_exports.unknown());
14569
+ var nativeModelSchema = external_exports.object({
14570
+ providerId: external_exports.string().min(1),
14571
+ modelId: external_exports.string().min(1),
14572
+ variant: external_exports.string().optional(),
14573
+ options: external_exports.object({ reasoningLevel: external_exports.string().min(1).optional() }).optional()
14574
+ });
14575
+ var levelSchema = external_exports.object({ value: external_exports.string(), label: external_exports.string() });
14576
+ var modelSchema = external_exports.object({
14577
+ ref: nativeModelSchema,
14578
+ label: external_exports.string(),
14579
+ providerLabel: external_exports.string().optional(),
14580
+ disabledReason: external_exports.string().optional(),
14581
+ contextWindow: external_exports.number().int().positive().optional(),
14582
+ reasoning: external_exports.object({
14583
+ enabled: external_exports.boolean().optional(),
14584
+ levels: external_exports.array(levelSchema),
14585
+ defaultLevel: external_exports.string().optional()
14586
+ }).transform((reasoning) => ({
14587
+ ...reasoning,
14588
+ enabled: reasoning.enabled ?? reasoning.levels.length > 0
14589
+ })).optional()
14590
+ }).transform(({ providerLabel, ...model2 }) => {
14591
+ const provider = model2.ref.providerId === "account:bigmodel-individual-coding-plan" ? "BigModel" : model2.ref.providerId === "account:zai-individual-coding-plan" ? "Z.AI" : providerLabel;
14592
+ return { ...model2, label: provider ? `${provider} / ${model2.label}` : model2.label };
14593
+ });
14594
+ var settingsSchema = external_exports.object({
14595
+ model: external_exports.object({
14596
+ current: nativeModelSchema.optional(),
14597
+ available: external_exports.array(modelSchema),
14598
+ lastUsed: nativeModelSchema.optional()
14599
+ }),
14600
+ thoughtLevel: external_exports.object({
14601
+ enabled: external_exports.boolean(),
14602
+ current: external_exports.string().optional(),
14603
+ defaultLevel: external_exports.string().optional(),
14604
+ available: external_exports.array(levelSchema)
14605
+ }),
14606
+ mode: external_exports.object({ current: external_exports.enum(["build", "edit", "plan", "yolo", "auto"]) })
14607
+ });
14608
+ var workspaceSchema = external_exports.object({
14609
+ workspacePath: external_exports.string().min(1),
14610
+ workspaceKey: external_exports.string().min(1),
14611
+ workspaceIdentity: external_exports.string().optional()
14612
+ });
14613
+ var summarySchema = external_exports.object({
14614
+ sessionId: external_exports.string().min(1),
14615
+ workspace: workspaceSchema,
14616
+ title: external_exports.string(),
14617
+ status: external_exports.string(),
14618
+ mode: external_exports.string(),
14619
+ createdAt: external_exports.number(),
14620
+ updatedAt: external_exports.number(),
14621
+ parentSessionId: external_exports.string().optional(),
14622
+ sessionKind: external_exports.string()
14623
+ });
14624
+ var partSchema = external_exports.object({
14625
+ partId: external_exports.string().min(1),
14626
+ messageId: external_exports.string(),
14627
+ sessionId: external_exports.string(),
14628
+ type: external_exports.string()
14629
+ }).catchall(external_exports.unknown());
14630
+ var messageSchema = external_exports.object({
14631
+ info: external_exports.object({
14632
+ messageId: external_exports.string().min(1),
14633
+ sessionId: external_exports.string(),
14634
+ role: external_exports.enum(["user", "assistant"]),
14635
+ parentMessageId: external_exports.string().optional(),
14636
+ time: external_exports.object({ created: external_exports.number(), completed: external_exports.number().optional() }),
14637
+ model: nativeModelSchema.optional(),
14638
+ // Keep telemetry unvalidated here: bad usage must not break history or the Turn.
14639
+ tokens: external_exports.unknown().optional(),
14640
+ finish: external_exports.string().optional(),
14641
+ error: recordSchema.optional(),
14642
+ synthetic: external_exports.boolean().optional(),
14643
+ visibility: external_exports.string().optional(),
14644
+ semantics: recordSchema.optional()
14645
+ }),
14646
+ parts: external_exports.array(partSchema)
14647
+ });
14648
+ var snapshotSchema = external_exports.object({
14649
+ protocol: external_exports.object({ name: external_exports.literal("ZCode Protocol"), version: external_exports.literal(1) }),
14650
+ session: summarySchema,
14651
+ settings: settingsSchema,
14652
+ projection: external_exports.object({
14653
+ status: external_exports.string(),
14654
+ contextUsed: external_exports.number(),
14655
+ contextWindow: external_exports.number(),
14656
+ currentTurnId: external_exports.string().optional(),
14657
+ backgroundJobs: external_exports.array(external_exports.unknown()).optional(),
14658
+ target: recordSchema.nullable().optional()
14659
+ }),
14660
+ messages: external_exports.array(messageSchema),
14661
+ runtime: recordSchema,
14662
+ target: recordSchema.nullable().optional(),
14663
+ slashCommands: external_exports.array(external_exports.object({ name: external_exports.string(), description: external_exports.string(), source: external_exports.string().optional() })).optional()
14664
+ });
14665
+ var workspaceStateSchema = external_exports.object({
14666
+ workspace: workspaceSchema,
14667
+ settings: settingsSchema
14668
+ });
14669
+ var eventSchema = external_exports.object({
14670
+ eventId: external_exports.string(),
14671
+ sessionId: external_exports.string(),
14672
+ turnId: external_exports.string().optional(),
14673
+ seq: external_exports.number(),
14674
+ timestamp: external_exports.number(),
14675
+ type: external_exports.string(),
14676
+ payload: recordSchema.optional()
14677
+ });
14678
+ var runtimeUsageSchema = external_exports.object({
14679
+ contextUsage: external_exports.object({
14680
+ used: external_exports.number().int().nonnegative(),
14681
+ cache: external_exports.object({
14682
+ totalCacheReadTokens: external_exports.number().int().nonnegative(),
14683
+ totalCacheWriteTokens: external_exports.number().int().nonnegative(),
14684
+ latestHitRate: external_exports.number().min(0).max(1).nullish()
14685
+ }).nullish()
14686
+ })
14687
+ });
14688
+ function record2(value) {
14689
+ return recordSchema.safeParse(value).data ?? {};
14690
+ }
14691
+ function text(value) {
14692
+ return typeof value === "string" ? value : "";
14693
+ }
14694
+
14695
+ // ../../shared-contracts/dist/delegation-read.js
14696
+ var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
14697
+ var delegationReadParamsSchema = external_exports.strictObject({
14698
+ threadId: external_exports.string().min(1).max(1024),
14699
+ view: external_exports.enum(["result", "messages"]),
14700
+ cursor: external_exports.string().min(1).max(8192).optional(),
14701
+ limit: external_exports.number().int().min(1).max(100).optional()
14702
+ });
14703
+
14526
14704
  // ../../shared-contracts/dist/credential-imports.js
14527
14705
  var credentialSourceSchema = external_exports.object({
14528
14706
  id: external_exports.string().min(1).max(256),
@@ -14593,6 +14771,153 @@ var harnessDisplaySetSchema = external_exports.strictObject({
14593
14771
  initializeOnly: external_exports.boolean().optional()
14594
14772
  });
14595
14773
 
14774
+ // ../../shared-contracts/dist/model-price-overrides.js
14775
+ var usdPerMillionTokens = external_exports.number().finite().nonnegative();
14776
+ var modelPriceOverrideSchema = external_exports.strictObject({
14777
+ input: usdPerMillionTokens,
14778
+ output: usdPerMillionTokens,
14779
+ cacheRead: usdPerMillionTokens.optional(),
14780
+ cacheWrite: usdPerMillionTokens.optional(),
14781
+ cacheWrite1h: usdPerMillionTokens.optional()
14782
+ });
14783
+ var modelPriceKeySchema = external_exports.string().max(512).refine((key) => key.trim() === key && key.length > 0, "Model ID is required");
14784
+ var modelPriceOverridesSchema = external_exports.strictObject({
14785
+ /** Absolute path of the Host's `pricing.json`. */
14786
+ path: external_exports.string(),
14787
+ entries: external_exports.array(external_exports.strictObject({ key: external_exports.string(), price: modelPriceOverrideSchema })),
14788
+ /** Why the existing file is unusable; the Host then ignores it and refuses to overwrite it. */
14789
+ error: external_exports.string().nullable()
14790
+ });
14791
+ var modelPriceOverridesGetSchema = external_exports.strictObject({});
14792
+ var modelPriceOverridesSetSchema = external_exports.strictObject({
14793
+ key: modelPriceKeySchema,
14794
+ price: modelPriceOverrideSchema.nullable(),
14795
+ previousKey: modelPriceKeySchema.optional()
14796
+ });
14797
+ var modelPriceDefaultParamsSchema = external_exports.strictObject({
14798
+ model: modelPriceKeySchema
14799
+ });
14800
+ var modelPriceSuggestionSchema = external_exports.strictObject({
14801
+ /** Verified from catalog canonical links, not inferred from names or equal prices. */
14802
+ official: external_exports.boolean().optional(),
14803
+ canonicalModelId: external_exports.string().min(1).optional(),
14804
+ provider: external_exports.string().min(1).max(512),
14805
+ model: external_exports.string().min(1).max(512),
14806
+ price: modelPriceOverrideSchema
14807
+ });
14808
+ var modelPriceDefaultResultSchema = external_exports.strictObject({
14809
+ price: modelPriceOverrideSchema.nullable(),
14810
+ /** Local catalog suggestions only; never used automatically for pricing. */
14811
+ suggestions: external_exports.array(modelPriceSuggestionSchema).max(6).optional()
14812
+ });
14813
+
14814
+ // ../../shared-contracts/dist/usage-statistics.js
14815
+ var USAGE_STATISTICS_RANGES = ["today", "7d", "30d", "90d", "all"];
14816
+ var count = external_exports.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
14817
+ var localDate = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/u);
14818
+ var harness = external_exports.string().min(1).max(128);
14819
+ var model = external_exports.string().min(1).max(512);
14820
+ var project = external_exports.string().min(1).max(4096);
14821
+ var usageStatisticsParamsSchema = external_exports.strictObject({
14822
+ range: external_exports.enum(USAGE_STATISTICS_RANGES),
14823
+ harness: harness.optional(),
14824
+ model: model.nullable().optional(),
14825
+ project: project.nullable().optional(),
14826
+ /** One local date inside the range. */
14827
+ date: localDate.optional()
14828
+ });
14829
+ var usageStatisticsTotalsSchema = external_exports.strictObject({
14830
+ requests: count,
14831
+ inputTokens: count,
14832
+ cachedInputTokens: count,
14833
+ cacheWriteInputTokens: count,
14834
+ cacheKnownInputTokens: count,
14835
+ outputTokens: count,
14836
+ reasoningOutputTokens: count,
14837
+ /** USD at the public price, summed over the priced requests only. */
14838
+ costUsd: external_exports.number().finite().min(0),
14839
+ /** Requests without a price (or the cache data the price needs); not in `costUsd`. */
14840
+ unpricedRequests: count,
14841
+ /**
14842
+ * Requests whose storage gave no token counts: counted as requests, with neither tokens nor
14843
+ * cost, and not as unpriced.
14844
+ */
14845
+ unmeteredRequests: count
14846
+ });
14847
+ var totals = usageStatisticsTotalsSchema.shape;
14848
+ var usageStatisticsSessionSchema = external_exports.strictObject({
14849
+ harness,
14850
+ sessionId: external_exports.string().min(1).max(512),
14851
+ project: project.nullable(),
14852
+ /** Models the session used, most requests first. */
14853
+ models: external_exports.array(model).max(16),
14854
+ firstAtMs: count,
14855
+ lastAtMs: count,
14856
+ ...totals
14857
+ });
14858
+ var usageStatisticsResultSchema = external_exports.strictObject({
14859
+ range: external_exports.enum(USAGE_STATISTICS_RANGES),
14860
+ /** First local date of the range; null for all time. */
14861
+ from: localDate.nullable(),
14862
+ to: localDate,
14863
+ /** The filters these figures apply, echoed so a late answer to older filters is recognised. */
14864
+ filters: external_exports.strictObject({
14865
+ harness: harness.nullable(),
14866
+ model: model.nullable(),
14867
+ unknownModel: external_exports.boolean(),
14868
+ project: project.nullable(),
14869
+ unknownProject: external_exports.boolean(),
14870
+ date: localDate.nullable()
14871
+ }),
14872
+ /** Reading of native storage: incomplete while the first read, or a refresh, is under way. */
14873
+ reading: external_exports.strictObject({ complete: external_exports.boolean(), sources: count, read: count }),
14874
+ /** Harnesses whose storage could not be read; their part is missing, the rest is complete. */
14875
+ failures: external_exports.array(external_exports.strictObject({ harness, message: external_exports.string().max(2048) })).max(256),
14876
+ /** Every value seen in the range, ignoring the filters, to choose filters from. */
14877
+ options: external_exports.strictObject({
14878
+ harnesses: external_exports.array(harness).max(256),
14879
+ models: external_exports.array(model.nullable()).max(4096),
14880
+ projects: external_exports.array(project.nullable()).max(4096)
14881
+ }),
14882
+ /** Current display metadata, scoped by Harness. Never a pricing or filter identity.
14883
+ * Optional for older Hosts; missing/conflicting labels fall back to the native model ID.
14884
+ */
14885
+ modelLabels: external_exports.array(external_exports.strictObject({ harness, model, label: model })).max(4096).optional(),
14886
+ /** Native credits, all filters applied, never combined across Harnesses or treated as USD.
14887
+ * Only groups with at least one reported value appear; reportedRequests exposes partial data.
14888
+ */
14889
+ credits: external_exports.array(external_exports.strictObject({
14890
+ harness,
14891
+ model: model.nullable(),
14892
+ credits: external_exports.number().finite().min(0),
14893
+ reportedRequests: count,
14894
+ requests: count
14895
+ })).max(4096).optional(),
14896
+ /** All filters applied. */
14897
+ totals: usageStatisticsTotalsSchema,
14898
+ /** Each date and Harness of the range: every filter except the day. */
14899
+ daily: external_exports.array(external_exports.strictObject({ date: localDate, harness, ...totals })).max(2e5),
14900
+ /** Local weekday (0 = Sunday) and hour, all filters applied. */
14901
+ hourly: external_exports.array(external_exports.strictObject({
14902
+ weekday: external_exports.number().int().min(0).max(6),
14903
+ hour: external_exports.number().int().min(0).max(23),
14904
+ ...totals
14905
+ })).max(168),
14906
+ byHarness: external_exports.array(external_exports.strictObject({ harness, ...totals })).max(256),
14907
+ byModel: external_exports.array(external_exports.strictObject({
14908
+ model: model.nullable(),
14909
+ ...totals,
14910
+ /** Requests priced by what the Harness recorded they cost, not by a price list. */
14911
+ harnessPricedRequests: count
14912
+ })).max(4096),
14913
+ byProject: external_exports.array(external_exports.strictObject({ project: project.nullable(), ...totals })).max(4096),
14914
+ /**
14915
+ * The sessions that spent the most, by cost and by tokens without cache, all filters applied;
14916
+ * requests without a native session are not listed here but count everywhere else.
14917
+ */
14918
+ sessions: external_exports.array(usageStatisticsSessionSchema).max(100)
14919
+ });
14920
+
14596
14921
  // ../../shared-contracts/dist/ids.js
14597
14922
  var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
14598
14923
  message: "Identifier must not be empty or whitespace"
@@ -14614,13 +14939,40 @@ var HARNESS_PLUGIN_LIMIT = 128;
14614
14939
  var harnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).refine((id) => id !== "codex", "The official Codex identity is reserved").pipe(harnessIdSchema);
14615
14940
  var relativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
14616
14941
  var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
14942
+ var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
14943
+ var harnessInstallationGuideSchema = external_exports.object({
14944
+ commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
14945
+ before: localizedTextSchema.optional(),
14946
+ after: localizedTextSchema.optional(),
14947
+ downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
14948
+ }).strict();
14617
14949
  var pluginPresentationShape = {
14618
14950
  id: harnessPluginIdSchema,
14619
14951
  name: external_exports.string().trim().min(1).max(128),
14620
14952
  version: external_exports.string().min(1).max(128),
14953
+ /** Capability-only plugin; omitted for existing session-capable plugins. */
14954
+ kind: external_exports.literal("usage").optional(),
14955
+ /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
14956
+ iconStyle: external_exports.object({
14957
+ vector: external_exports.object({
14958
+ viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
14959
+ color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
14960
+ paths: external_exports.array(external_exports.object({
14961
+ d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
14962
+ fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
14963
+ fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
14964
+ }).strict()).min(1).max(32)
14965
+ }).strict().optional(),
14966
+ background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
14967
+ borderRadius: external_exports.number().min(0).max(50).optional(),
14968
+ paddingRatio: external_exports.number().min(0).max(0.25).optional()
14969
+ }).strict().optional(),
14970
+ installation: harnessInstallationGuideSchema.optional(),
14971
+ notice: localizedTextSchema.optional(),
14621
14972
  /** The factory accepts a persisted local entrypoint through its construction context. */
14622
14973
  launchCommand: external_exports.literal(true).optional(),
14623
14974
  links: external_exports.object({
14975
+ website: documentationUrlSchema.optional(),
14624
14976
  documentation: documentationUrlSchema.optional(),
14625
14977
  installation: documentationUrlSchema.optional()
14626
14978
  }).strict().optional()
@@ -14697,6 +15049,10 @@ var CONSOLE_HOST_METHODS = Object.freeze([
14697
15049
  "codexhost/account/list",
14698
15050
  "codexhost/account/refresh",
14699
15051
  "codexhost/account/usage/inspect",
15052
+ "codexhost/usage/model-prices/get",
15053
+ "codexhost/usage/model-prices/set",
15054
+ "codexhost/usage/model-prices/default",
15055
+ "codexhost/usage/statistics/get",
14700
15056
  "codexhost/update/check",
14701
15057
  "codexhost/update/start",
14702
15058
  "codexhost/update/status"
@@ -14761,6 +15117,7 @@ var threadUsageSnapshotSchema = external_exports.object({
14761
15117
  cacheWriteInputTokens: nonNegativeSafeIntegerSchema.optional(),
14762
15118
  outputTokens: nonNegativeSafeIntegerSchema.optional(),
14763
15119
  outputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
15120
+ apiOutputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
14764
15121
  reasoningOutputTokens: nonNegativeSafeIntegerSchema.optional(),
14765
15122
  totalTokens: nonNegativeSafeIntegerSchema.optional(),
14766
15123
  totalCostUsd: finiteNonNegativeNumberSchema.optional(),
@@ -14772,7 +15129,11 @@ var threadUsageSnapshotSchema = external_exports.object({
14772
15129
  planFiveHourUsedPercent: cacheHitRatePercentSchema.optional(),
14773
15130
  planFiveHourResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
14774
15131
  planSevenDayUsedPercent: cacheHitRatePercentSchema.optional(),
14775
- planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional()
15132
+ planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
15133
+ sessionCacheHitRatePercent: cacheHitRatePercentSchema.optional(),
15134
+ timeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
15135
+ costSource: external_exports.enum(["publicPrice", "native"]).optional(),
15136
+ unpricedModels: external_exports.array(external_exports.string().min(1)).min(1).optional()
14776
15137
  }).strict().superRefine((usage, context) => {
14777
15138
  if (Object.keys(usage).length === 0) {
14778
15139
  context.addIssue({ code: "custom", message: "Thread Usage must contain a reliable field" });
@@ -14793,6 +15154,20 @@ var threadUsageSnapshotSchema = external_exports.object({
14793
15154
  path: ["contextWindowTokens"]
14794
15155
  });
14795
15156
  }
15157
+ if (usage.costSource !== void 0 && usage.totalCostUsd === void 0) {
15158
+ context.addIssue({
15159
+ code: "custom",
15160
+ message: "Thread Usage costSource must be provided with totalCostUsd",
15161
+ path: ["costSource"]
15162
+ });
15163
+ }
15164
+ if (usage.unpricedModels !== void 0 && usage.costSource !== "publicPrice") {
15165
+ context.addIssue({
15166
+ code: "custom",
15167
+ message: "Thread Usage unpricedModels must be provided with a publicPrice cost",
15168
+ path: ["unpricedModels"]
15169
+ });
15170
+ }
14796
15171
  if (usage.planFiveHourResetsAtUnix !== void 0 && usage.planFiveHourUsedPercent === void 0) {
14797
15172
  context.addIssue({
14798
15173
  code: "custom",
@@ -15062,27 +15437,27 @@ var harnessModelCatalogSchema = external_exports.object({
15062
15437
  }).strict().superRefine((catalog, context) => {
15063
15438
  const refs = /* @__PURE__ */ new Set();
15064
15439
  const thinkingIds = new Set(catalog.thinkingOptions.map(({ id }) => id));
15065
- for (const [index, model] of catalog.models.entries()) {
15066
- if (refs.has(model.ref.id)) {
15440
+ for (const [index, model2] of catalog.models.entries()) {
15441
+ if (refs.has(model2.ref.id)) {
15067
15442
  context.addIssue({
15068
15443
  code: "custom",
15069
15444
  message: "Model Catalog refs must be unique",
15070
15445
  path: ["models", index, "ref", "id"]
15071
15446
  });
15072
15447
  }
15073
- refs.add(model.ref.id);
15074
- if (model.fastModel) {
15075
- if (refs.has(model.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model.fastModel?.id)) {
15448
+ refs.add(model2.ref.id);
15449
+ if (model2.fastModel) {
15450
+ if (refs.has(model2.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model2.fastModel?.id)) {
15076
15451
  context.addIssue({
15077
15452
  code: "custom",
15078
15453
  message: "Fast Model refs must be distinct and unique",
15079
15454
  path: ["models", index, "fastModel"]
15080
15455
  });
15081
15456
  }
15082
- refs.add(model.fastModel.id);
15457
+ refs.add(model2.fastModel.id);
15083
15458
  }
15084
15459
  const supportedThinkingIds = /* @__PURE__ */ new Set();
15085
- for (const [optionIndex, optionId] of (model.supportedThinkingOptionIds ?? []).entries()) {
15460
+ for (const [optionIndex, optionId] of (model2.supportedThinkingOptionIds ?? []).entries()) {
15086
15461
  if (supportedThinkingIds.has(optionId)) {
15087
15462
  context.addIssue({
15088
15463
  code: "custom",
@@ -15676,6 +16051,11 @@ var codexSshDraftSchema = external_exports.strictObject({
15676
16051
  });
15677
16052
  var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action", [
15678
16053
  external_exports.strictObject({ action: external_exports.literal("list") }),
16054
+ external_exports.strictObject({
16055
+ action: external_exports.literal("read-thread"),
16056
+ hostId: hostId.refine((id) => id !== "local"),
16057
+ input: delegationReadParamsSchema
16058
+ }),
15679
16059
  external_exports.strictObject({
15680
16060
  action: external_exports.literal("save"),
15681
16061
  draft: codexSshDraftSchema,
@@ -15699,10 +16079,6 @@ var remoteConnectionsReplySchema = external_exports.union([
15699
16079
  // ../../shared-contracts/dist/index.js
15700
16080
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
15701
16081
 
15702
- // dist/transport.js
15703
- import { spawn } from "node:child_process";
15704
- import { randomUUID } from "node:crypto";
15705
-
15706
16082
  // ../../harness-adapter/dist/approval.js
15707
16083
  function invalidRequest(message) {
15708
16084
  return { code: "invalidRequest", message, retryable: false };
@@ -15811,7 +16187,6 @@ var tokenFields = [
15811
16187
  "cachedInputTokens",
15812
16188
  "cacheWriteInputTokens",
15813
16189
  "outputTokens",
15814
- "outputTokensPerSecond",
15815
16190
  "reasoningOutputTokens",
15816
16191
  "totalTokens",
15817
16192
  "contextWindowTokens",
@@ -15819,10 +16194,12 @@ var tokenFields = [
15819
16194
  ];
15820
16195
  var safeIntegerFields = [
15821
16196
  "planFiveHourResetsAtUnix",
15822
- "planSevenDayResetsAtUnix"
16197
+ "planSevenDayResetsAtUnix",
16198
+ "timeToFirstOutputMs"
15823
16199
  ];
15824
16200
  var percentFields = [
15825
16201
  "cacheHitRatePercent",
16202
+ "sessionCacheHitRatePercent",
15826
16203
  "planFiveHourUsedPercent",
15827
16204
  "planSevenDayUsedPercent"
15828
16205
  ];
@@ -15830,9 +16207,14 @@ var usageFields = /* @__PURE__ */ new Set([
15830
16207
  ...tokenFields,
15831
16208
  ...safeIntegerFields,
15832
16209
  ...percentFields,
16210
+ "sessionCacheUsage",
15833
16211
  "totalCostUsd",
15834
16212
  "totalCredits",
15835
- "contextUsagePercent"
16213
+ "contextUsagePercent",
16214
+ "outputTokensPerSecond",
16215
+ "apiOutputTokensPerSecond",
16216
+ "costSource",
16217
+ "unpricedModels"
15836
16218
  ]);
15837
16219
  function isRecord(value) {
15838
16220
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -15848,7 +16230,11 @@ function parseHostUsage(value) {
15848
16230
  throw new Error(`Harness Usage contains unknown field '${key}'`);
15849
16231
  }
15850
16232
  }
15851
- for (const field2 of ["totalCredits", "contextUsagePercent"]) {
16233
+ for (const field2 of [
16234
+ "totalCredits",
16235
+ "contextUsagePercent",
16236
+ "apiOutputTokensPerSecond"
16237
+ ]) {
15852
16238
  const candidate = value[field2];
15853
16239
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
15854
16240
  throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
@@ -15884,6 +16270,12 @@ function parseHostUsage(value) {
15884
16270
  throw new Error(`Harness Usage '${field2}' must be between 0 and 100`);
15885
16271
  }
15886
16272
  }
16273
+ if (value.sessionCacheUsage !== void 0) {
16274
+ const totals2 = value.sessionCacheUsage;
16275
+ if (!isRecord(totals2) || Object.keys(totals2).some((key) => key !== "inputTokens" && key !== "cachedInputTokens") || typeof totals2.inputTokens !== "number" || !Number.isSafeInteger(totals2.inputTokens) || totals2.inputTokens < 0 || typeof totals2.cachedInputTokens !== "number" || !Number.isSafeInteger(totals2.cachedInputTokens) || totals2.cachedInputTokens < 0 || totals2.cachedInputTokens > totals2.inputTokens) {
16276
+ throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
16277
+ }
16278
+ }
15887
16279
  const hasContextUsed = value.contextUsedTokens !== void 0;
15888
16280
  const hasContextWindow = value.contextWindowTokens !== void 0;
15889
16281
  if (hasContextUsed !== hasContextWindow) {
@@ -15898,8 +16290,323 @@ function parseHostUsage(value) {
15898
16290
  if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
15899
16291
  throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
15900
16292
  }
16293
+ if (value.costSource !== void 0) {
16294
+ if (value.costSource !== "publicPrice" && value.costSource !== "native") {
16295
+ throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
16296
+ }
16297
+ if (value.totalCostUsd === void 0) {
16298
+ throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
16299
+ }
16300
+ }
16301
+ if (value.unpricedModels !== void 0) {
16302
+ const models = value.unpricedModels;
16303
+ if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
16304
+ throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
16305
+ }
16306
+ if (value.costSource !== "publicPrice") {
16307
+ throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
16308
+ }
16309
+ return { ...value, unpricedModels: [...models] };
16310
+ }
15901
16311
  return { ...value };
15902
16312
  }
16313
+ var requestTokenFields = [
16314
+ "inputTokens",
16315
+ "cachedInputTokens",
16316
+ "cacheWriteInputTokens",
16317
+ "cacheWrite1hInputTokens",
16318
+ "outputTokens",
16319
+ "reasoningOutputTokens",
16320
+ "startedAtMs",
16321
+ "completedAtMs"
16322
+ ];
16323
+ var requestFields = /* @__PURE__ */ new Set([
16324
+ ...requestTokenFields,
16325
+ "requestId",
16326
+ "historical",
16327
+ "model",
16328
+ "provider"
16329
+ ]);
16330
+ function parseHostUsageRequest(value) {
16331
+ if (!isRecord(value))
16332
+ throw new Error("Harness Usage request must be an object");
16333
+ for (const key of Object.keys(value)) {
16334
+ if (!requestFields.has(key)) {
16335
+ throw new Error(`Harness Usage request contains unknown field '${key}'`);
16336
+ }
16337
+ }
16338
+ if (typeof value.requestId !== "string" || value.requestId.length === 0) {
16339
+ throw new Error("Harness Usage request 'requestId' must be a non-empty string");
16340
+ }
16341
+ for (const field2 of ["model", "provider"]) {
16342
+ const candidate = value[field2];
16343
+ if (candidate !== void 0 && (typeof candidate !== "string" || candidate.length === 0)) {
16344
+ throw new Error(`Harness Usage request '${field2}' must be a non-empty string`);
16345
+ }
16346
+ }
16347
+ if (value.historical !== void 0 && typeof value.historical !== "boolean") {
16348
+ throw new Error("Harness Usage request 'historical' must be a boolean");
16349
+ }
16350
+ for (const field2 of requestTokenFields) {
16351
+ const candidate = value[field2];
16352
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16353
+ throw new Error(`Harness Usage request '${field2}' must be a non-negative safe integer`);
16354
+ }
16355
+ }
16356
+ if (value.inputTokens === void 0 || value.outputTokens === void 0) {
16357
+ throw new Error("Harness Usage request must contain 'inputTokens' and 'outputTokens'");
16358
+ }
16359
+ const request = value;
16360
+ if ((request.cachedInputTokens ?? 0) + (request.cacheWriteInputTokens ?? 0) > request.inputTokens) {
16361
+ throw new Error("Harness Usage request cache Tokens must not exceed 'inputTokens'");
16362
+ }
16363
+ if ((request.reasoningOutputTokens ?? 0) > request.outputTokens) {
16364
+ throw new Error("Harness Usage request 'reasoningOutputTokens' must not exceed 'outputTokens'");
16365
+ }
16366
+ if (request.cacheWrite1hInputTokens !== void 0 && request.cacheWrite1hInputTokens > (request.cacheWriteInputTokens ?? -1)) {
16367
+ throw new Error("Harness Usage request 'cacheWrite1hInputTokens' must not exceed 'cacheWriteInputTokens'");
16368
+ }
16369
+ if (request.startedAtMs === void 0 !== (request.completedAtMs === void 0)) {
16370
+ throw new Error("Harness Usage request timing fields must be provided together");
16371
+ }
16372
+ if (request.startedAtMs !== void 0 && request.completedAtMs !== void 0 && request.completedAtMs < request.startedAtMs) {
16373
+ throw new Error("Harness Usage request 'completedAtMs' must not precede 'startedAtMs'");
16374
+ }
16375
+ return { ...request };
16376
+ }
16377
+
16378
+ // dist/usage.js
16379
+ function requestTokens(id, model2, value) {
16380
+ const tokens = record2(value), cache = record2(tokens.cache);
16381
+ const request = parseHostUsageRequest({
16382
+ requestId: id,
16383
+ ...model2 ? { model: model2 } : {},
16384
+ inputTokens: tokens.input,
16385
+ outputTokens: tokens.output,
16386
+ ...cache.read !== void 0 ? { cachedInputTokens: cache.read } : {},
16387
+ ...cache.write !== void 0 ? { cacheWriteInputTokens: cache.write } : {},
16388
+ ...tokens.reasoning !== void 0 ? { reasoningOutputTokens: tokens.reasoning } : {}
16389
+ });
16390
+ if (!Number.isSafeInteger(tokens.total) || tokens.total !== request.inputTokens + request.outputTokens)
16391
+ throw new Error("ZCode request token convention is unknown");
16392
+ return request;
16393
+ }
16394
+ function zcodeUsageRecord(message) {
16395
+ const info = message.info;
16396
+ if (info.role !== "assistant" || info.synthetic === true || info.semantics?.origin === "system")
16397
+ return { kind: "none" };
16398
+ if (info.time.completed === void 0)
16399
+ return { kind: "missing" };
16400
+ const tokens = record2(info.tokens), cache = record2(tokens.cache);
16401
+ if ((info.error || info.finish === "start_plan_admission_retry_discarded") && tokens.total === void 0 && tokens.input === 0 && tokens.output === 0 && tokens.reasoning === 0 && cache.read === 0 && cache.write === 0)
16402
+ return { kind: "none" };
16403
+ try {
16404
+ return {
16405
+ kind: "request",
16406
+ request: requestTokens(info.messageId, info.model?.modelId, info.tokens)
16407
+ };
16408
+ } catch {
16409
+ return { kind: "missing" };
16410
+ }
16411
+ }
16412
+ var ZcodeUsage = class {
16413
+ sessionId;
16414
+ emit;
16415
+ #seen = /* @__PURE__ */ new Map();
16416
+ #pending;
16417
+ #timings = /* @__PURE__ */ new Map();
16418
+ #complete = true;
16419
+ constructor(sessionId, emit) {
16420
+ this.sessionId = sessionId;
16421
+ this.emit = emit;
16422
+ }
16423
+ invalidate() {
16424
+ if (!this.#complete)
16425
+ return;
16426
+ this.#complete = false;
16427
+ this.emit({ type: "usage.history", complete: false });
16428
+ }
16429
+ replay(messages, historical) {
16430
+ for (const message of messages) {
16431
+ if (message.info.sessionId !== this.sessionId)
16432
+ continue;
16433
+ const result = zcodeUsageRecord(message);
16434
+ if (result.kind === "missing")
16435
+ this.invalidate();
16436
+ else if (result.kind === "request") {
16437
+ this.#publish({
16438
+ ...result.request,
16439
+ ...historical ? { historical: true } : this.#timings.get(result.request.requestId)
16440
+ });
16441
+ }
16442
+ }
16443
+ if (historical)
16444
+ this.emit({ type: "usage.history", complete: this.#complete });
16445
+ this.#pending = void 0;
16446
+ this.#timings.clear();
16447
+ }
16448
+ #publish(request) {
16449
+ if ((request.reasoningOutputTokens ?? 0) > 0) {
16450
+ request = { ...request };
16451
+ delete request.startedAtMs;
16452
+ delete request.completedAtMs;
16453
+ }
16454
+ const previous = this.#seen.get(request.requestId);
16455
+ if (previous) {
16456
+ if (previous.model !== request.model || previous.inputTokens !== request.inputTokens || previous.outputTokens !== request.outputTokens || previous.cachedInputTokens !== request.cachedInputTokens || previous.cacheWriteInputTokens !== request.cacheWriteInputTokens || (previous.reasoningOutputTokens ?? 0) !== (request.reasoningOutputTokens ?? 0))
16457
+ this.invalidate();
16458
+ return;
16459
+ }
16460
+ this.#seen.set(request.requestId, request);
16461
+ this.emit({ type: "usage.request", request });
16462
+ }
16463
+ observe(event) {
16464
+ if (event.sessionId !== this.sessionId)
16465
+ return;
16466
+ const p = event.payload ?? {};
16467
+ if (event.type === "turn.started") {
16468
+ this.#pending = void 0;
16469
+ this.#timings.clear();
16470
+ return;
16471
+ }
16472
+ if (event.type === "model.streaming") {
16473
+ const pending2 = this.#pending;
16474
+ if (!pending2 || pending2.turnId !== event.turnId || p.source === "subagent")
16475
+ return;
16476
+ const id = text(p.assistantMessageId);
16477
+ if (!id)
16478
+ return;
16479
+ if (pending2.messageId && pending2.messageId !== id)
16480
+ pending2.ambiguous = true;
16481
+ pending2.messageId = id;
16482
+ if (pending2.startedAtMs === void 0 && ((p.kind === "text_delta" || p.kind === "reasoning_delta") && text(p.delta) || p.kind === "tool_input_start" || p.kind === "tool_input_delta" && text(p.delta) || p.kind === "tool_call"))
16483
+ pending2.startedAtMs = event.timestamp;
16484
+ return;
16485
+ }
16486
+ if (event.type !== "session.updated" || p.querySource !== "main_turn")
16487
+ return;
16488
+ if (p.type === "model_request_started") {
16489
+ const id = text(p.requestId), model2 = text(p.modelId);
16490
+ if (!id || !model2)
16491
+ return;
16492
+ this.#pending = {
16493
+ id,
16494
+ model: model2,
16495
+ turnId: event.turnId,
16496
+ ambiguous: this.#pending !== void 0
16497
+ };
16498
+ return;
16499
+ }
16500
+ if (p.type !== "model_request_completed")
16501
+ return;
16502
+ const pending = this.#pending;
16503
+ if (!pending || pending.id !== p.requestId || pending.turnId !== event.turnId)
16504
+ return;
16505
+ this.#pending = void 0;
16506
+ if (pending.ambiguous || !pending.messageId || pending.model !== p.modelId)
16507
+ return;
16508
+ const start = pending.startedAtMs;
16509
+ if (start !== void 0 && Number.isSafeInteger(start) && Number.isSafeInteger(event.timestamp) && event.timestamp >= start)
16510
+ this.#timings.set(pending.messageId, {
16511
+ startedAtMs: start,
16512
+ completedAtMs: event.timestamp
16513
+ });
16514
+ const usage = record2(p.usage);
16515
+ if (usage.cacheReadTokens === void 0 || usage.cacheWriteTokens === void 0)
16516
+ return;
16517
+ try {
16518
+ const request = requestTokens(pending.messageId, pending.model, {
16519
+ input: usage.inputTokens,
16520
+ output: usage.outputTokens,
16521
+ total: usage.totalTokens,
16522
+ reasoning: usage.reasoningTokens,
16523
+ cache: { read: usage.cacheReadTokens, write: usage.cacheWriteTokens }
16524
+ });
16525
+ this.#publish({ ...request, ...this.#timings.get(pending.messageId) });
16526
+ } catch {
16527
+ this.invalidate();
16528
+ }
16529
+ }
16530
+ };
16531
+
16532
+ // dist/usage-statistics.js
16533
+ function zcodeDatabasePath(environment) {
16534
+ return path.join(environment.ZCODE_DATA_BASE_DIR?.trim() || environment.HOME || os.homedir(), ".zcode", "cli", "db", "db.sqlite");
16535
+ }
16536
+ async function readZcodeUsage(file2) {
16537
+ const { DatabaseSync } = await import("node:sqlite");
16538
+ const database = new DatabaseSync(file2, { readOnly: true });
16539
+ try {
16540
+ const entries = [];
16541
+ const directories = /* @__PURE__ */ new Map();
16542
+ const hasSessions = database.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'session'").get();
16543
+ if (hasSessions) {
16544
+ for (const row of database.prepare("SELECT id, directory FROM session").iterate()) {
16545
+ if (typeof row.directory === "string")
16546
+ directories.set(String(row.id), row.directory);
16547
+ }
16548
+ }
16549
+ for (const row of database.prepare("SELECT id, session_id, data FROM message").iterate()) {
16550
+ let data;
16551
+ try {
16552
+ data = record2(JSON.parse(String(row.data)));
16553
+ } catch {
16554
+ continue;
16555
+ }
16556
+ if (data.role !== "assistant")
16557
+ continue;
16558
+ const modelId = text(data.modelId) || text(data.modelID);
16559
+ const providerId = text(data.providerId) || text(data.providerID);
16560
+ const parsed = messageSchema.safeParse({
16561
+ info: {
16562
+ ...data,
16563
+ messageId: String(row.id),
16564
+ sessionId: String(row.session_id),
16565
+ ...modelId && providerId ? { model: { providerId, modelId } } : {}
16566
+ },
16567
+ parts: []
16568
+ });
16569
+ if (!parsed.success)
16570
+ continue;
16571
+ const usage = zcodeUsageRecord(parsed.data);
16572
+ const at = nativeTimeMs(parsed.data.info.time.created);
16573
+ const entry = usage.kind === "request" && at !== null && usageEntryFromRequest(usage.request, at);
16574
+ if (entry) {
16575
+ const sessionId = String(row.session_id);
16576
+ entries.push(withUsageSession(entry, { sessionId, cwd: directories.get(sessionId) }));
16577
+ }
16578
+ }
16579
+ return entries;
16580
+ } finally {
16581
+ database.close();
16582
+ }
16583
+ }
16584
+ function createZcodeUsageStatistics(environment) {
16585
+ return Object.freeze({
16586
+ async listSources() {
16587
+ const file2 = zcodeDatabasePath(environment);
16588
+ const info = await lstat(file2).catch(() => null);
16589
+ if (!info?.isFile())
16590
+ return [];
16591
+ const wal = await lstat(`${file2}-wal`).catch(() => null);
16592
+ return [
16593
+ {
16594
+ id: file2,
16595
+ fingerprint: `${info.ino}:${info.size}:${info.mtimeMs}:${wal ? `${wal.size}:${wal.mtimeMs}` : "-"}`
16596
+ }
16597
+ ];
16598
+ },
16599
+ readSource: (id) => readZcodeUsage(id)
16600
+ });
16601
+ }
16602
+
16603
+ // dist/adapter.js
16604
+ import path6 from "node:path";
16605
+ import { stat as stat2 } from "node:fs/promises";
16606
+
16607
+ // dist/transport.js
16608
+ import { spawn } from "node:child_process";
16609
+ import { randomUUID } from "node:crypto";
15903
16610
 
15904
16611
  // dist/errors.js
15905
16612
  var ZcodeError = class extends Error {
@@ -15926,136 +16633,10 @@ function nativeError(error51) {
15926
16633
  return { code: "nativeFailure", message: "ZCode operation failed", retryable: false };
15927
16634
  }
15928
16635
 
15929
- // dist/protocol.js
15930
- var recordSchema = external_exports.record(external_exports.string(), external_exports.unknown());
15931
- var nativeModelSchema = external_exports.object({
15932
- providerId: external_exports.string().min(1),
15933
- modelId: external_exports.string().min(1),
15934
- variant: external_exports.string().optional(),
15935
- options: external_exports.object({ reasoningLevel: external_exports.string().min(1).optional() }).optional()
15936
- });
15937
- var levelSchema = external_exports.object({ value: external_exports.string(), label: external_exports.string() });
15938
- var modelSchema = external_exports.object({
15939
- ref: nativeModelSchema,
15940
- label: external_exports.string(),
15941
- providerLabel: external_exports.string().optional(),
15942
- disabledReason: external_exports.string().optional(),
15943
- contextWindow: external_exports.number().int().positive().optional(),
15944
- reasoning: external_exports.object({
15945
- enabled: external_exports.boolean().optional(),
15946
- levels: external_exports.array(levelSchema),
15947
- defaultLevel: external_exports.string().optional()
15948
- }).transform((reasoning) => ({
15949
- ...reasoning,
15950
- enabled: reasoning.enabled ?? reasoning.levels.length > 0
15951
- })).optional()
15952
- }).transform(({ providerLabel, ...model }) => ({
15953
- ...model,
15954
- label: providerLabel ? `${providerLabel} / ${model.label}` : model.label
15955
- }));
15956
- var settingsSchema = external_exports.object({
15957
- model: external_exports.object({
15958
- current: nativeModelSchema.optional(),
15959
- available: external_exports.array(modelSchema),
15960
- lastUsed: nativeModelSchema.optional()
15961
- }),
15962
- thoughtLevel: external_exports.object({
15963
- enabled: external_exports.boolean(),
15964
- current: external_exports.string().optional(),
15965
- defaultLevel: external_exports.string().optional(),
15966
- available: external_exports.array(levelSchema)
15967
- }),
15968
- mode: external_exports.object({ current: external_exports.enum(["build", "edit", "plan", "yolo", "auto"]) })
15969
- });
15970
- var workspaceSchema = external_exports.object({
15971
- workspacePath: external_exports.string().min(1),
15972
- workspaceKey: external_exports.string().min(1),
15973
- workspaceIdentity: external_exports.string().optional()
15974
- });
15975
- var summarySchema = external_exports.object({
15976
- sessionId: external_exports.string().min(1),
15977
- workspace: workspaceSchema,
15978
- title: external_exports.string(),
15979
- status: external_exports.string(),
15980
- mode: external_exports.string(),
15981
- createdAt: external_exports.number(),
15982
- updatedAt: external_exports.number(),
15983
- parentSessionId: external_exports.string().optional(),
15984
- sessionKind: external_exports.string()
15985
- });
15986
- var partSchema = external_exports.object({
15987
- partId: external_exports.string().min(1),
15988
- messageId: external_exports.string(),
15989
- sessionId: external_exports.string(),
15990
- type: external_exports.string()
15991
- }).catchall(external_exports.unknown());
15992
- var messageSchema = external_exports.object({
15993
- info: external_exports.object({
15994
- messageId: external_exports.string().min(1),
15995
- sessionId: external_exports.string(),
15996
- role: external_exports.enum(["user", "assistant"]),
15997
- parentMessageId: external_exports.string().optional(),
15998
- time: external_exports.object({ created: external_exports.number(), completed: external_exports.number().optional() }),
15999
- model: nativeModelSchema.optional(),
16000
- finish: external_exports.string().optional(),
16001
- error: recordSchema.optional(),
16002
- synthetic: external_exports.boolean().optional(),
16003
- visibility: external_exports.string().optional(),
16004
- semantics: recordSchema.optional()
16005
- }),
16006
- parts: external_exports.array(partSchema)
16007
- });
16008
- var snapshotSchema = external_exports.object({
16009
- protocol: external_exports.object({ name: external_exports.literal("ZCode Protocol"), version: external_exports.literal(1) }),
16010
- session: summarySchema,
16011
- settings: settingsSchema,
16012
- projection: external_exports.object({
16013
- status: external_exports.string(),
16014
- contextUsed: external_exports.number(),
16015
- contextWindow: external_exports.number(),
16016
- currentTurnId: external_exports.string().optional(),
16017
- backgroundJobs: external_exports.array(external_exports.unknown()).optional(),
16018
- target: recordSchema.nullable().optional()
16019
- }),
16020
- messages: external_exports.array(messageSchema),
16021
- runtime: recordSchema,
16022
- target: recordSchema.nullable().optional(),
16023
- slashCommands: external_exports.array(external_exports.object({ name: external_exports.string(), description: external_exports.string(), source: external_exports.string().optional() })).optional()
16024
- });
16025
- var workspaceStateSchema = external_exports.object({
16026
- workspace: workspaceSchema,
16027
- settings: settingsSchema
16028
- });
16029
- var eventSchema = external_exports.object({
16030
- eventId: external_exports.string(),
16031
- sessionId: external_exports.string(),
16032
- turnId: external_exports.string().optional(),
16033
- seq: external_exports.number(),
16034
- timestamp: external_exports.number(),
16035
- type: external_exports.string(),
16036
- payload: recordSchema.optional()
16037
- });
16038
- var runtimeUsageSchema = external_exports.object({
16039
- contextUsage: external_exports.object({
16040
- used: external_exports.number().int().nonnegative(),
16041
- cache: external_exports.object({
16042
- totalCacheReadTokens: external_exports.number().int().nonnegative(),
16043
- totalCacheWriteTokens: external_exports.number().int().nonnegative(),
16044
- latestHitRate: external_exports.number().min(0).max(1).nullish()
16045
- }).nullish()
16046
- })
16047
- });
16048
- function record2(value) {
16049
- return recordSchema.safeParse(value).data ?? {};
16050
- }
16051
- function text(value) {
16052
- return typeof value === "string" ? value : "";
16053
- }
16054
-
16055
16636
  // dist/installation.js
16056
16637
  import { open, stat } from "node:fs/promises";
16057
16638
  import { homedir } from "node:os";
16058
- import path from "node:path";
16639
+ import path2 from "node:path";
16059
16640
  var DEFAULT_DARWIN_APP = "/Applications/ZCode.app";
16060
16641
  var DEFAULT_LINUX_APP = "/opt/ZCode";
16061
16642
  async function isFile(file2) {
@@ -16100,11 +16681,11 @@ async function resolveDefaultApp(environment, platform2) {
16100
16681
  if (platform2 === "linux")
16101
16682
  return DEFAULT_LINUX_APP;
16102
16683
  const candidates = [
16103
- environment.LOCALAPPDATA && path.join(environment.LOCALAPPDATA, "Programs", "ZCode"),
16104
- environment.ProgramFiles && path.join(environment.ProgramFiles, "ZCode")
16684
+ environment.LOCALAPPDATA && path2.join(environment.LOCALAPPDATA, "Programs", "ZCode"),
16685
+ environment.ProgramFiles && path2.join(environment.ProgramFiles, "ZCode")
16105
16686
  ].filter(Boolean);
16106
16687
  for (const candidate of candidates) {
16107
- if (await isFile(path.join(candidate, "resources", "app.asar")))
16688
+ if (await isFile(path2.join(candidate, "resources", "app.asar")))
16108
16689
  return candidate;
16109
16690
  }
16110
16691
  return candidates[0] ?? "";
@@ -16116,30 +16697,30 @@ async function resolveInstallation(environment, app, platform2 = process.platfor
16116
16697
  const explicitApp = app?.trim() || environment.CODEXHOST_ZCODE_APP?.trim();
16117
16698
  const targetApp = explicitApp || await resolveDefaultApp(environment, platform2);
16118
16699
  const missing = () => new ZcodeError("notInstalled", `ZCode Desktop was not found at ${targetApp}; install it or set its application path`);
16119
- const resources = platform2 === "darwin" ? path.join(targetApp, "Contents", "Resources") : path.join(targetApp, "resources");
16120
- const pkg = await readPackageJsonFromAsar(path.join(resources, "app.asar"));
16700
+ const resources = platform2 === "darwin" ? path2.join(targetApp, "Contents", "Resources") : path2.join(targetApp, "resources");
16701
+ const pkg = await readPackageJsonFromAsar(path2.join(resources, "app.asar"));
16121
16702
  if (!pkg?.productName || !pkg.version)
16122
16703
  throw missing();
16123
16704
  let runtime;
16124
16705
  if (platform2 === "darwin") {
16125
- runtime = path.join(targetApp, "Contents", "Frameworks", `${pkg.productName} Helper.app`, "Contents", "MacOS", `${pkg.productName} Helper`);
16706
+ runtime = path2.join(targetApp, "Contents", "Frameworks", `${pkg.productName} Helper.app`, "Contents", "MacOS", `${pkg.productName} Helper`);
16126
16707
  } else if (platform2 === "win32") {
16127
- runtime = path.join(targetApp, `${pkg.productName}.exe`);
16708
+ runtime = path2.join(targetApp, `${pkg.productName}.exe`);
16128
16709
  } else {
16129
16710
  const linuxExecutableName = pkg.productName.toLowerCase().replace(/\s+/g, "-");
16130
- runtime = path.join(targetApp, linuxExecutableName);
16711
+ runtime = path2.join(targetApp, linuxExecutableName);
16131
16712
  }
16132
- const cli = path.join(resources, "glm", "zcode.cjs");
16133
- const builtinProviderConfig = environment.ZCODE_BUILTIN_PROVIDER_CONFIG_FILE || path.join(resources, "config", "provider", "zcode-builtin.json");
16713
+ const cli = path2.join(resources, "glm", "zcode.cjs");
16714
+ const builtinProviderConfig = environment.ZCODE_BUILTIN_PROVIDER_CONFIG_FILE || path2.join(resources, "config", "provider", "zcode-builtin.json");
16134
16715
  if (!await isFile(runtime) || !await isFile(cli) || !await isFile(builtinProviderConfig))
16135
16716
  throw missing();
16136
- const dataRoot = path.join(environment.ZCODE_DATA_BASE_DIR?.trim() || environment.HOME || homedir(), ".zcode", "v2");
16717
+ const dataRoot = path2.join(environment.ZCODE_DATA_BASE_DIR?.trim() || environment.HOME || homedir(), ".zcode", "v2");
16137
16718
  return {
16138
16719
  runtime,
16139
16720
  version: pkg.version,
16140
16721
  cli,
16141
16722
  builtinProviderConfig,
16142
- personalProviderConfig: environment.ZCODE_PERSONAL_PROVIDER_CONFIG_FILE || path.join(dataRoot, "provider_config.json"),
16723
+ personalProviderConfig: environment.ZCODE_PERSONAL_PROVIDER_CONFIG_FILE || path2.join(dataRoot, "provider_config.json"),
16143
16724
  dataRoot
16144
16725
  };
16145
16726
  }
@@ -16161,25 +16742,15 @@ function createZcodeInstallation(environment, app) {
16161
16742
  }
16162
16743
 
16163
16744
  // dist/account.js
16745
+ import { createHash as createHash3 } from "node:crypto";
16746
+ import { readFile as readFile3 } from "node:fs/promises";
16747
+ import path5 from "node:path";
16748
+
16749
+ // dist/credentials.js
16164
16750
  import { createDecipheriv, createHash } from "node:crypto";
16165
16751
  import { readFile } from "node:fs/promises";
16166
16752
  import { homedir as homedir2, platform, userInfo } from "node:os";
16167
- import path2 from "node:path";
16168
- var SIGN_IN = "Sign in to ZCode Desktop with a Start Plan account, then try again";
16169
- var builtinSchema = external_exports.object({
16170
- revision: external_exports.union([external_exports.number(), external_exports.string()]),
16171
- config: external_exports.object({
16172
- providerConfigRules: external_exports.object({
16173
- providerRules: external_exports.array(external_exports.object({
16174
- providerId: external_exports.string().min(1),
16175
- config: external_exports.object({
16176
- builtinModelIds: external_exports.array(external_exports.string()).optional(),
16177
- access: external_exports.object({ mode: external_exports.string(), accountType: external_exports.string() }).partial().optional()
16178
- })
16179
- }))
16180
- })
16181
- })
16182
- });
16753
+ import path3 from "node:path";
16183
16754
  function decrypt(value, environment) {
16184
16755
  if (!value.startsWith("enc:v1:"))
16185
16756
  return value;
@@ -16200,25 +16771,231 @@ function decrypt(value, environment) {
16200
16771
  throw new ZcodeError("authenticationRequired", "Cannot decrypt ZCode credentials; ZCODE_CREDENTIAL_SECRET must match ZCode Desktop");
16201
16772
  }
16202
16773
  }
16203
- async function readCredential(installation, environment, key) {
16774
+ async function readCredentials(installation, environment) {
16204
16775
  let store;
16205
16776
  try {
16206
- store = JSON.parse(await readFile(path2.join(installation.dataRoot, "credentials.json"), "utf8"));
16777
+ store = JSON.parse(await readFile(path3.join(installation.dataRoot, "credentials.json"), "utf8"));
16207
16778
  } catch (error51) {
16208
16779
  if (error51.code === "ENOENT")
16209
- return "";
16780
+ return () => "";
16210
16781
  throw new ZcodeError("authenticationRequired", "Cannot read ZCode credentials");
16211
16782
  }
16212
- const value = external_exports.record(external_exports.string(), external_exports.string()).safeParse(store).data?.[key];
16213
- return value ? decrypt(value, environment) : "";
16783
+ const values = external_exports.record(external_exports.string(), external_exports.string()).safeParse(store).data;
16784
+ return (key) => {
16785
+ const value = values?.[key];
16786
+ return value ? decrypt(value, environment) : "";
16787
+ };
16788
+ }
16789
+ async function readCredential(installation, environment, key) {
16790
+ return (await readCredentials(installation, environment))(key);
16791
+ }
16792
+
16793
+ // dist/personal-coding-plan.js
16794
+ import { createHash as createHash2 } from "node:crypto";
16795
+ import { readFile as readFile2 } from "node:fs/promises";
16796
+ import { homedir as homedir3 } from "node:os";
16797
+ import path4 from "node:path";
16798
+ var familySchema = external_exports.enum(["zai", "bigmodel"]);
16799
+ var recordSchema2 = external_exports.record(external_exports.string(), external_exports.unknown());
16800
+ var CONNECT = "Connect Personal Coding Plan in ZCode Desktop, then re-detect ZCode and reopen the Thread";
16801
+ function personalCodingPlanOrigin(family, environment) {
16802
+ const test = environment.ZCODE_ENV?.trim().toLowerCase() === "test";
16803
+ const prefix = family === "zai" ? "ZAI" : "BIGMODEL";
16804
+ const suffix = family === "zai" ? "BUSINESS_BASE_URL" : "API_BASE_URL";
16805
+ const origin = environment[`${prefix}_${suffix}`]?.trim() || environment[`${prefix}_${test ? "TEST" : "PRODUCTION"}_${suffix}`]?.trim() || (family === "zai" ? test ? "https://api.chatglm.site" : "https://api.z.ai" : test ? "https://dev.bigmodel.cn" : "https://bigmodel.cn");
16806
+ const url2 = new URL(origin);
16807
+ if (!["http:", "https:"].includes(url2.protocol) || url2.username || url2.password)
16808
+ throw new Error("Invalid ZCode business origin");
16809
+ return url2.origin;
16810
+ }
16811
+ async function readSelection(environment, family) {
16812
+ const home = environment.ZCODE_DESKTOP_HOME_DIR?.trim() || environment.HOME?.trim() || environment.USERPROFILE?.trim() || homedir3();
16813
+ let raw;
16814
+ try {
16815
+ raw = JSON.parse(await readFile2(path4.join(home, ".zcode", "v2", "setting.json"), "utf8"));
16816
+ } catch (error51) {
16817
+ if (error51.code === "ENOENT")
16818
+ return false;
16819
+ throw new ZcodeError("configurationRequired", CONNECT);
16820
+ }
16821
+ const settings = recordSchema2.parse(raw);
16822
+ if (settings.providerFamilyDomain !== family)
16823
+ return false;
16824
+ if (Object.hasOwn(settings, "providerFamilyConnectionSelections")) {
16825
+ const selections = recordSchema2.parse(settings.providerFamilyConnectionSelections);
16826
+ return external_exports.object({ kind: external_exports.literal("individual-coding-plan") }).safeParse(selections[family]).success;
16827
+ }
16828
+ const modes = recordSchema2.safeParse(settings.modelProviderFamilyModes).data;
16829
+ const keys = recordSchema2.safeParse(settings.modelProviderFamilySelectedKeys).data;
16830
+ return modes?.[family] !== "apiKey" && keys?.[family] === `coding-plan:builtin:${family}-coding-plan`;
16831
+ }
16832
+ var envelopeSchema = external_exports.object({
16833
+ success: external_exports.boolean().optional(),
16834
+ code: external_exports.number().optional(),
16835
+ data: external_exports.array(external_exports.unknown())
16836
+ });
16837
+ var subscriptionSchema = external_exports.object({
16838
+ productId: external_exports.string().optional(),
16839
+ productName: external_exports.string().optional(),
16840
+ status: external_exports.string(),
16841
+ inCurrentPeriod: external_exports.boolean()
16842
+ });
16843
+ function codingProduct(value) {
16844
+ const entry = recordSchema2.safeParse(value).data;
16845
+ return [entry?.productId, entry?.productName].some((field2) => typeof field2 === "string" && field2.toLowerCase().includes("coding"));
16846
+ }
16847
+ async function queryEntitlement(family, apiKey, environment) {
16848
+ try {
16849
+ const response = await fetch(`${personalCodingPlanOrigin(family, environment)}/api/biz/subscription/list`, {
16850
+ method: "GET",
16851
+ // The subscription endpoint accepts the model API Key, not the OAuth token or Start JWT.
16852
+ headers: { Authorization: apiKey.trim() },
16853
+ redirect: "error",
16854
+ signal: AbortSignal.timeout(15e3)
16855
+ });
16856
+ if (response.status === 401 || response.status === 403)
16857
+ return "credential-failed";
16858
+ if (!response.ok)
16859
+ return "unknown";
16860
+ const parsed = envelopeSchema.safeParse(await response.json());
16861
+ if (!parsed.success)
16862
+ return "unknown";
16863
+ const payload = parsed.data;
16864
+ if (payload.success === false || payload.code !== void 0 && ![0, 200].includes(payload.code))
16865
+ return "unknown";
16866
+ let malformed = false;
16867
+ for (const item of payload.data) {
16868
+ if (!codingProduct(item))
16869
+ continue;
16870
+ const subscription = subscriptionSchema.safeParse(item);
16871
+ if (!subscription.success)
16872
+ malformed = true;
16873
+ else if (subscription.data.status === "VALID" && subscription.data.inCurrentPeriod)
16874
+ return "available";
16875
+ }
16876
+ return malformed ? "unknown" : "unavailable";
16877
+ } catch {
16878
+ return "unknown";
16879
+ }
16214
16880
  }
16881
+ var PersonalCodingPlanAccount = class {
16882
+ installation;
16883
+ environment;
16884
+ #authorized = /* @__PURE__ */ new Map();
16885
+ constructor(installation, environment) {
16886
+ this.installation = installation;
16887
+ this.environment = environment;
16888
+ }
16889
+ async #context(providerId, family) {
16890
+ const [credential, current] = await Promise.all([
16891
+ readCredentials(this.installation, this.environment),
16892
+ readSelection(this.environment, family)
16893
+ ]);
16894
+ if (credential("oauth:active_provider") !== family)
16895
+ return void 0;
16896
+ const raw = credential(`oauth:${family}:user_info`);
16897
+ if (!raw)
16898
+ return void 0;
16899
+ const profile = recordSchema2.parse(JSON.parse(raw));
16900
+ const normalized = external_exports.object({ id: external_exports.string(), username: external_exports.string(), displayName: external_exports.string() }).safeParse(profile).data;
16901
+ const identity = normalized ? normalized.id.trim() : family === "zai" && typeof profile.user_id === "string" ? profile.user_id.trim() : "";
16902
+ if (!identity || identity === "unknown")
16903
+ return void 0;
16904
+ const key = `account-provider:coding-plan:${providerId}:account:${encodeURIComponent(identity)}:api-key`;
16905
+ return { identity, current, apiKey: credential(key).trim() };
16906
+ }
16907
+ async inspect(providerId, accountType) {
16908
+ const family = familySchema.parse(accountType);
16909
+ this.#authorized.delete(providerId);
16910
+ let current = false;
16911
+ try {
16912
+ const context = await this.#context(providerId, family);
16913
+ if (!context)
16914
+ return {
16915
+ availability: "unavailable",
16916
+ entitled: false,
16917
+ current,
16918
+ unavailableReason: "not-connected"
16919
+ };
16920
+ current = context.current;
16921
+ const connectionKey = createHash2("sha256").update(JSON.stringify([family, context.identity, "individual-coding-plan"])).digest("hex");
16922
+ const base = { current, connectionKey };
16923
+ if (!context.apiKey)
16924
+ return {
16925
+ ...base,
16926
+ availability: "unavailable",
16927
+ entitled: false,
16928
+ unavailableReason: "credential-failed"
16929
+ };
16930
+ const entitlement = await queryEntitlement(family, context.apiKey, this.environment);
16931
+ const after = await this.#context(providerId, family);
16932
+ if (!after || after.identity !== context.identity || after.current !== current || after.apiKey !== context.apiKey)
16933
+ return { availability: "unknown", entitled: false, current: false };
16934
+ if (entitlement === "available") {
16935
+ if (current)
16936
+ this.#authorized.set(providerId, { family, identity: context.identity });
16937
+ return { ...base, availability: "available", entitled: true };
16938
+ }
16939
+ return {
16940
+ ...base,
16941
+ availability: entitlement === "unknown" ? "unknown" : "unavailable",
16942
+ entitled: false,
16943
+ ...entitlement === "unknown" ? {} : {
16944
+ unavailableReason: entitlement === "unavailable" ? "not-entitled" : "credential-failed"
16945
+ }
16946
+ };
16947
+ } catch {
16948
+ return { availability: "unknown", entitled: false, current };
16949
+ }
16950
+ }
16951
+ async requestAuth(request, signal) {
16952
+ const parsed = external_exports.object({
16953
+ providerId: external_exports.string(),
16954
+ modelSelection: external_exports.object({ providerId: external_exports.string() }),
16955
+ accountAccess: external_exports.object({
16956
+ type: external_exports.literal("zhipu-account"),
16957
+ mode: external_exports.literal("individual-coding-plan"),
16958
+ accountType: familySchema
16959
+ })
16960
+ }).safeParse(request);
16961
+ if (!parsed.success)
16962
+ throw new ZcodeError("authenticationRequired", CONNECT);
16963
+ const { providerId, modelSelection, accountAccess } = parsed.data;
16964
+ const authorized = this.#authorized.get(providerId);
16965
+ if (!authorized || authorized.family !== accountAccess.accountType || modelSelection.providerId !== providerId)
16966
+ throw new ZcodeError("authenticationRequired", CONNECT);
16967
+ signal.throwIfAborted();
16968
+ const context = await this.#context(providerId, authorized.family);
16969
+ signal.throwIfAborted();
16970
+ if (!context?.current || context.identity !== authorized.identity || !context.apiKey)
16971
+ throw new ZcodeError("authenticationRequired", CONNECT);
16972
+ return { apiKey: context.apiKey };
16973
+ }
16974
+ };
16975
+
16976
+ // dist/account.js
16977
+ var SIGN_IN = "Sign in to ZCode Desktop with a Start Plan account, then try again";
16978
+ var builtinSchema = external_exports.object({
16979
+ revision: external_exports.union([external_exports.number(), external_exports.string()]),
16980
+ config: external_exports.object({
16981
+ providerConfigRules: external_exports.object({
16982
+ providerRules: external_exports.array(external_exports.object({
16983
+ providerId: external_exports.string().min(1),
16984
+ config: external_exports.object({
16985
+ builtinModelIds: external_exports.array(external_exports.string()).optional(),
16986
+ access: external_exports.object({ mode: external_exports.string(), accountType: external_exports.string() }).partial().optional()
16987
+ })
16988
+ }))
16989
+ })
16990
+ })
16991
+ });
16215
16992
  function resolveEndpointOrigin(environment) {
16216
16993
  return environment.ZCODE_BASE_URL?.trim() || "https://zcode.z.ai";
16217
16994
  }
16218
16995
  async function readDeviceMid(installation) {
16219
16996
  try {
16220
- const file2 = path2.join(installation.dataRoot, "telemetry-state.json");
16221
- const parsed = JSON.parse(await readFile(file2, "utf8"));
16997
+ const file2 = path5.join(installation.dataRoot, "telemetry-state.json");
16998
+ const parsed = JSON.parse(await readFile3(file2, "utf8"));
16222
16999
  return typeof parsed?.deviceMid === "string" ? parsed.deviceMid.trim() : "";
16223
17000
  } catch {
16224
17001
  return "";
@@ -16316,24 +17093,38 @@ async function queryStartPlanBalance(origin, appVersion, jwt2, deviceMid) {
16316
17093
  }
16317
17094
  async function accountConfig(installation, environment) {
16318
17095
  const file2 = installation.builtinProviderConfig;
16319
- const builtin = builtinSchema.parse(JSON.parse(await readFile(file2, "utf8")));
16320
- const basedOnZCodeBuiltinRevision = `zcode-builtin:${builtin.revision}:${createHash("sha256").update(path2.resolve(file2)).digest("hex")}`;
17096
+ const builtin = builtinSchema.parse(JSON.parse(await readFile3(file2, "utf8")));
17097
+ const basedOnZCodeBuiltinRevision = `zcode-builtin:${builtin.revision}:${createHash3("sha256").update(path5.resolve(file2)).digest("hex")}`;
16321
17098
  const family = await readCredential(installation, environment, "oauth:active_provider");
16322
17099
  let balanceData;
16323
17100
  if (family) {
16324
- const jwt2 = await readCredential(installation, environment, "zcodejwttoken");
16325
- const deviceMid = await readDeviceMid(installation);
16326
- if (jwt2 && deviceMid) {
16327
- const origin = resolveEndpointOrigin(environment);
16328
- balanceData = await queryStartPlanBalance(origin, installation.version, jwt2, deviceMid);
17101
+ try {
17102
+ const jwt2 = await readCredential(installation, environment, "zcodejwttoken");
17103
+ const deviceMid = await readDeviceMid(installation);
17104
+ if (jwt2 && deviceMid) {
17105
+ const origin = resolveEndpointOrigin(environment);
17106
+ balanceData = await queryStartPlanBalance(origin, installation.version, jwt2, deviceMid);
17107
+ }
17108
+ } catch {
16329
17109
  }
16330
17110
  }
16331
17111
  let startPlan = false;
17112
+ const codingPlan = new PersonalCodingPlanAccount(installation, environment);
16332
17113
  const providers = {};
16333
17114
  const states = {};
16334
17115
  for (const rule of builtin.config.providerConfigRules.providerRules) {
16335
17116
  const access = rule.config.access;
16336
- if (!family || access?.mode !== "start-plan" || access.accountType !== family)
17117
+ if (!family || access?.accountType !== family)
17118
+ continue;
17119
+ if (access.mode === "individual-coding-plan" && (family === "zai" || family === "bigmodel")) {
17120
+ const state = await codingPlan.inspect(rule.providerId, family);
17121
+ providers[rule.providerId] = {
17122
+ access: { type: "zhipu-account", entitled: state.entitled }
17123
+ };
17124
+ states[rule.providerId] = state;
17125
+ continue;
17126
+ }
17127
+ if (access.mode !== "start-plan")
16337
17128
  continue;
16338
17129
  const allowedModels = resolveStartPlanModels(balanceData, rule.config.builtinModelIds);
16339
17130
  if (allowedModels.length > 0) {
@@ -16355,7 +17146,7 @@ async function accountConfig(installation, environment) {
16355
17146
  };
16356
17147
  }
16357
17148
  }
16358
- const overlayDigest = createHash("sha256").update(JSON.stringify([providers, states])).digest("hex").slice(0, 16);
17149
+ const overlayDigest = createHash3("sha256").update(JSON.stringify([providers, states])).digest("hex").slice(0, 16);
16359
17150
  return {
16360
17151
  params: {
16361
17152
  revision: `codexhost:${family || "signed-out"}:${builtin.revision}:${overlayDigest}`,
@@ -16363,16 +17154,20 @@ async function accountConfig(installation, environment) {
16363
17154
  providers,
16364
17155
  states
16365
17156
  },
16366
- startPlan
17157
+ startPlan,
17158
+ codingPlan
16367
17159
  };
16368
17160
  }
16369
- async function providerRuntimeHeaders(accountAccess, signal, installation, environment, verifier) {
16370
- if (external_exports.object({ mode: external_exports.literal("start-plan") }).safeParse(accountAccess).success !== true)
16371
- return {
16372
- headersApplied: false,
16373
- errorMessage: "codexhost supports only the ZCode Start Plan account"
16374
- };
17161
+ async function providerRuntimeHeaders(request, signal, installation, environment, verifier, codingPlan) {
17162
+ const mode = external_exports.object({ mode: external_exports.string() }).safeParse(request.accountAccess).data?.mode;
16375
17163
  try {
17164
+ if (mode === "individual-coding-plan")
17165
+ return { headersApplied: true, requestAuth: await codingPlan.requestAuth(request, signal) };
17166
+ if (mode !== "start-plan")
17167
+ return {
17168
+ headersApplied: false,
17169
+ errorMessage: "codexhost supports ZCode Start Plan and Personal Coding Plan; Team Coding Plan is not supported"
17170
+ };
16376
17171
  const apiKey = await readCredential(installation, environment, "zcodejwttoken");
16377
17172
  if (!apiKey)
16378
17173
  return { headersApplied: false, errorMessage: SIGN_IN };
@@ -16381,7 +17176,7 @@ async function providerRuntimeHeaders(accountAccess, signal, installation, envir
16381
17176
  } catch (error51) {
16382
17177
  return {
16383
17178
  headersApplied: false,
16384
- errorMessage: error51 instanceof ZcodeError ? error51.message : "ZCode Start Plan verification failed"
17179
+ errorMessage: error51 instanceof ZcodeError ? error51.message : "ZCode account authentication failed"
16385
17180
  };
16386
17181
  }
16387
17182
  }
@@ -16465,6 +17260,7 @@ var CliTransport = class {
16465
17260
  // Aborting these cancels only this transport's running and queued shared verifications.
16466
17261
  #headerRequests = /* @__PURE__ */ new Map();
16467
17262
  #startPlan = false;
17263
+ #codingPlan;
16468
17264
  #fault;
16469
17265
  #closed = false;
16470
17266
  #closePromise;
@@ -16487,9 +17283,10 @@ var CliTransport = class {
16487
17283
  if (this.#child || this.#closed)
16488
17284
  throw new ZcodeError("invalidState", "ZCode transport already started or closed");
16489
17285
  const installation = await resolveInstallation(this.options.environment, this.options.app);
16490
- const { params: accountParams, startPlan } = await accountConfig(installation, this.options.environment);
17286
+ const { params: accountParams, startPlan, codingPlan } = await accountConfig(installation, this.options.environment);
16491
17287
  this.#installation = installation;
16492
17288
  this.#startPlan = startPlan;
17289
+ this.#codingPlan = codingPlan;
16493
17290
  const child = spawn(installation.runtime, [installation.cli, "app-server", "--stdio", "--surface", "desktop"], {
16494
17291
  cwd: this.options.cwd,
16495
17292
  env: {
@@ -16614,7 +17411,7 @@ var CliTransport = class {
16614
17411
  this.#headerRequests.set(requestId, controller);
16615
17412
  try {
16616
17413
  reply({
16617
- result: await providerRuntimeHeaders(params.accountAccess, controller.signal, this.#installation, this.options.environment, () => this.options.verifier(this.#installation.version))
17414
+ result: await providerRuntimeHeaders(params, controller.signal, this.#installation, this.options.environment, () => this.options.verifier(this.#installation.version), this.#codingPlan)
16618
17415
  });
16619
17416
  } finally {
16620
17417
  this.#headerRequests.delete(requestId);
@@ -17345,32 +18142,32 @@ import { randomUUID as randomUUID2 } from "node:crypto";
17345
18142
 
17346
18143
  // dist/models.js
17347
18144
  var ZCODE_ID = harnessIdSchema.parse("zcode");
17348
- function encodeModel(model) {
18145
+ function encodeModel(model2) {
17349
18146
  return harnessModelRefSchema.parse({
17350
- id: `zcode-local-v1.${Buffer.from(JSON.stringify([model.providerId, model.modelId])).toString("base64url")}`
18147
+ id: `zcode-local-v1.${Buffer.from(JSON.stringify([model2.providerId, model2.modelId])).toString("base64url")}`
17351
18148
  });
17352
18149
  }
17353
- function decodeModel(model) {
18150
+ function decodeModel(model2) {
17354
18151
  try {
17355
18152
  const prefix = "zcode-local-v1.";
17356
- const value = JSON.parse(Buffer.from(model.id.slice(prefix.length), "base64url").toString("utf8"));
17357
- if (!model.id.startsWith(prefix) || !Array.isArray(value) || value.length !== 2)
18153
+ const value = JSON.parse(Buffer.from(model2.id.slice(prefix.length), "base64url").toString("utf8"));
18154
+ if (!model2.id.startsWith(prefix) || !Array.isArray(value) || value.length !== 2)
17358
18155
  throw new Error();
17359
18156
  const native = nativeModelSchema.parse({ providerId: value[0], modelId: value[1] });
17360
- if (encodeModel(native).id !== model.id)
18157
+ if (encodeModel(native).id !== model2.id)
17361
18158
  throw new Error();
17362
18159
  return native;
17363
18160
  } catch {
17364
18161
  throw new ZcodeError("invalidRequest", "Invalid ZCode model reference");
17365
18162
  }
17366
18163
  }
17367
- function selectNativeModel(model, settings, thinkingOption) {
17368
- const native = decodeModel(model);
17369
- const entry = settings.model.available.find((entry2) => encodeModel(entry2.ref).id === model.id && !entry2.disabledReason);
18164
+ function selectNativeModel(model2, settings, thinkingOption) {
18165
+ const native = decodeModel(model2);
18166
+ const entry = settings.model.available.find((entry2) => encodeModel(entry2.ref).id === model2.id && !entry2.disabledReason);
17370
18167
  if (!entry)
17371
18168
  throw new ZcodeError("invalidRequest", "ZCode model is not available");
17372
18169
  const current = settings.model.current;
17373
- const level = thinkingOption ?? (current && encodeModel(current).id === model.id ? current.options?.reasoningLevel : void 0) ?? entry.reasoning?.defaultLevel;
18170
+ const level = thinkingOption ?? (current && encodeModel(current).id === model2.id ? current.options?.reasoningLevel : void 0) ?? entry.reasoning?.defaultLevel;
17374
18171
  if (level === void 0)
17375
18172
  return native;
17376
18173
  if (!entry.reasoning?.levels.some((option) => option.value === level))
@@ -17378,20 +18175,20 @@ function selectNativeModel(model, settings, thinkingOption) {
17378
18175
  return { ...native, options: { reasoningLevel: level } };
17379
18176
  }
17380
18177
  function modelCatalog(settings) {
17381
- const available = settings.model.available.filter((model) => !model.disabledReason);
18178
+ const available = settings.model.available.filter((model2) => !model2.disabledReason);
17382
18179
  const levels = new Map(settings.thoughtLevel.available.map((level) => [level.value, level]));
17383
- for (const model of available)
17384
- for (const level of model.reasoning?.levels ?? [])
18180
+ for (const model2 of available)
18181
+ for (const level of model2.reasoning?.levels ?? [])
17385
18182
  levels.set(level.value, level);
17386
18183
  const current = settings.model.current ? encodeModel(settings.model.current) : void 0;
17387
18184
  const defaultThinking = settings.thoughtLevel.current ?? settings.thoughtLevel.defaultLevel;
17388
18185
  return harnessModelCatalogSchema.parse({
17389
- models: available.map((model) => ({
17390
- ref: encodeModel(model.ref),
17391
- label: model.label,
17392
- supportedThinkingOptionIds: model.reasoning?.enabled ? model.reasoning.levels.map((level) => level.value) : []
18186
+ models: available.map((model2) => ({
18187
+ ref: encodeModel(model2.ref),
18188
+ label: model2.label,
18189
+ supportedThinkingOptionIds: model2.reasoning?.enabled ? model2.reasoning.levels.map((level) => level.value) : []
17393
18190
  })),
17394
- ...current && available.some((model) => encodeModel(model.ref).id === current.id) ? { defaultModel: current } : {},
18191
+ ...current && available.some((model2) => encodeModel(model2.ref).id === current.id) ? { defaultModel: current } : {},
17395
18192
  thinkingOptions: [...levels.values()].map((level) => ({ id: level.value, label: level.label })),
17396
18193
  ...defaultThinking && levels.has(defaultThinking) ? { defaultThinkingOptionId: defaultThinking } : {}
17397
18194
  });
@@ -17416,7 +18213,7 @@ function permissionModes(current = "build") {
17416
18213
  function sessionState(snapshot, locator) {
17417
18214
  const settings = snapshot.settings;
17418
18215
  const current = settings.model.current ? encodeModel(settings.model.current) : void 0;
17419
- const model = settings.model.available.find((candidate) => encodeModel(candidate.ref).id === current?.id);
18216
+ const model2 = settings.model.available.find((candidate) => encodeModel(candidate.ref).id === current?.id);
17420
18217
  return {
17421
18218
  nativeRef: nativeSessionRefSchema.parse({
17422
18219
  harnessId: ZCODE_ID,
@@ -17425,7 +18222,7 @@ function sessionState(snapshot, locator) {
17425
18222
  locator: { ...locator, cwd: snapshot.session.workspace.workspacePath }
17426
18223
  }),
17427
18224
  ...current && settings.model.current?.providerId !== "zcode-unconfigured" ? { effectiveModel: current } : {},
17428
- ...model ? { resolvedModelLabel: model.label } : {},
18225
+ ...model2 ? { resolvedModelLabel: model2.label } : {},
17429
18226
  ...settings.thoughtLevel.enabled && settings.thoughtLevel.current ? {
17430
18227
  effectiveThinkingOptionId: harnessThinkingOptionIdSchema.parse(settings.thoughtLevel.current)
17431
18228
  } : {},
@@ -17439,7 +18236,7 @@ function sessionState(snapshot, locator) {
17439
18236
  function sessionUsage(snapshot, catalog) {
17440
18237
  const runtime = runtimeUsageSchema.safeParse(snapshot.runtime).data?.contextUsage;
17441
18238
  const current = snapshot.settings.model.current;
17442
- const window = catalog.model.available.find((model) => model.ref.providerId === current?.providerId && model.ref.modelId === current.modelId)?.contextWindow ?? snapshot.projection.contextWindow;
18239
+ const window = catalog.model.available.find((model2) => model2.ref.providerId === current?.providerId && model2.ref.modelId === current.modelId)?.contextWindow ?? snapshot.projection.contextWindow;
17443
18240
  const cache = runtime?.cache;
17444
18241
  const usage = {
17445
18242
  ...window > 0 ? {
@@ -17555,16 +18352,16 @@ var Diff = class {
17555
18352
  }
17556
18353
  }
17557
18354
  }
17558
- addToPath(path4, added, removed, oldPosInc, options) {
17559
- const last = path4.lastComponent;
18355
+ addToPath(path7, added, removed, oldPosInc, options) {
18356
+ const last = path7.lastComponent;
17560
18357
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
17561
18358
  return {
17562
- oldPos: path4.oldPos + oldPosInc,
18359
+ oldPos: path7.oldPos + oldPosInc,
17563
18360
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
17564
18361
  };
17565
18362
  } else {
17566
18363
  return {
17567
- oldPos: path4.oldPos + oldPosInc,
18364
+ oldPos: path7.oldPos + oldPosInc,
17568
18365
  lastComponent: { count: 1, added, removed, previousComponent: last }
17569
18366
  };
17570
18367
  }
@@ -18625,6 +19422,7 @@ var ZcodeSession = class {
18625
19422
  };
18626
19423
  #state;
18627
19424
  #snapshot;
19425
+ #usage;
18628
19426
  #active;
18629
19427
  #pendingInteractions = /* @__PURE__ */ new Map();
18630
19428
  #closed = false;
@@ -18643,6 +19441,7 @@ var ZcodeSession = class {
18643
19441
  this.capabilities = ZCODE_CAPABILITIES;
18644
19442
  this.catalog = modelCatalog(nativeCatalog);
18645
19443
  this.#snapshot = snapshot;
19444
+ this.#usage = new ZcodeUsage(snapshot.session.sessionId, (event) => this.#emit(event));
18646
19445
  this.#goalActive = (snapshot.target === void 0 ? snapshot.projection.target : snapshot.target)?.status === "active";
18647
19446
  this.#state = sessionState(snapshot, transport.locator);
18648
19447
  this.initialState = structuredClone(this.#state);
@@ -18660,6 +19459,7 @@ var ZcodeSession = class {
18660
19459
  this.#channel.emit({ kind: "event", event });
18661
19460
  }
18662
19461
  async subscribe() {
19462
+ this.#usage.replay(this.#snapshot.messages, true);
18663
19463
  await this.transport.listen("onDynamicSessionEvent", {
18664
19464
  sessionId: this.sessionId,
18665
19465
  deliveryKind: "desktop-continuous",
@@ -18803,7 +19603,7 @@ var ZcodeSession = class {
18803
19603
  try {
18804
19604
  let method, params;
18805
19605
  if (command.type === "model.select") {
18806
- if (!this.catalog.models.some((model) => model.ref.id === command.model.id))
19606
+ if (!this.catalog.models.some((model2) => model2.ref.id === command.model.id))
18807
19607
  return failure("invalidRequest", "ZCode model is not available");
18808
19608
  method = "setModel";
18809
19609
  params = {
@@ -18942,6 +19742,7 @@ var ZcodeSession = class {
18942
19742
  if (event.seq <= this.#lastSeq)
18943
19743
  return;
18944
19744
  this.#lastSeq = event.seq;
19745
+ this.#usage.observe(event);
18945
19746
  if (event.type === "session.updated" && event.payload && Object.hasOwn(event.payload, "target"))
18946
19747
  this.#goalActive = record2(event.payload.target).status === "active";
18947
19748
  if (event.type === "turn.started") {
@@ -19016,6 +19817,9 @@ var ZcodeSession = class {
19016
19817
  } : turn?.outcome;
19017
19818
  if (!outcome || outcome.status === "unknown")
19018
19819
  throw new ZcodeError("protocolError", "ZCode completed without a confirmed turn outcome");
19820
+ if (this.#active !== active || this.#closed || this.#faulted)
19821
+ return;
19822
+ this.#usage.replay(snapshot.messages, false);
19019
19823
  this.#finish(active, {
19020
19824
  ...outcome,
19021
19825
  ...turn?.checkpoint ? { checkpoint: turn.checkpoint } : {}
@@ -19130,8 +19934,10 @@ var ZcodeAdapter = class {
19130
19934
  // One verification page and SDK instance for the whole Host, as in ZCode Desktop.
19131
19935
  #verifier;
19132
19936
  #prewarmed = false;
19937
+ usageStatistics;
19133
19938
  constructor(options = {}) {
19134
19939
  this.options = options;
19940
+ this.usageStatistics = createZcodeUsageStatistics(options.environment ?? process.env);
19135
19941
  }
19136
19942
  #sharedVerifier = (appVersion) => this.#verifier ??= (this.options.createVerifier ?? createZcodeVerifier)({
19137
19943
  appVersion,
@@ -19163,7 +19969,7 @@ var ZcodeAdapter = class {
19163
19969
  async inspect(input = {}) {
19164
19970
  let transport;
19165
19971
  try {
19166
- transport = await this.#transport(path3.resolve(input.cwd ?? process.cwd()));
19972
+ transport = await this.#transport(path6.resolve(input.cwd ?? process.cwd()));
19167
19973
  const settings = await readCatalog(transport);
19168
19974
  const catalog = modelCatalog(settings);
19169
19975
  if (!catalog.models.length)
@@ -19171,7 +19977,7 @@ var ZcodeAdapter = class {
19171
19977
  status: "unavailable",
19172
19978
  error: {
19173
19979
  code: "authenticationRequired",
19174
- message: "ZCode has no available models. Sign in to ZCode Desktop with a Start Plan account or add a personal provider in ZCode.",
19980
+ message: "ZCode has no available models. Connect Start Plan or Personal Coding Plan in ZCode Desktop, or add a personal provider, then re-detect ZCode. Team Coding Plan is not supported.",
19175
19981
  retryable: true
19176
19982
  }
19177
19983
  };
@@ -19209,18 +20015,18 @@ var ZcodeAdapter = class {
19209
20015
  let transport;
19210
20016
  let createdId;
19211
20017
  try {
19212
- transport = await this.#transport(path3.resolve(input.cwd), input.environment);
20018
+ transport = await this.#transport(path6.resolve(input.cwd), input.environment);
19213
20019
  let snapshot, settings;
19214
20020
  if (input.kind === "create") {
19215
20021
  settings = await readCatalog(transport);
19216
20022
  if (input.permissionModeId && !permissionModes().modes.some((m) => m.id === input.permissionModeId))
19217
20023
  throw new ZcodeError("invalidRequest", "Unknown ZCode permission mode");
19218
- const model = input.model ? selectNativeModel(input.model, settings, input.thinkingOptionId) : void 0;
20024
+ const model2 = input.model ? selectNativeModel(input.model, settings, input.thinkingOptionId) : void 0;
19219
20025
  const mode = input.executionPolicy === "unattended-full-access" ? "yolo" : input.permissionModeId;
19220
20026
  const created = await transport.command(null, "createSession", {
19221
20027
  workspaceId: input.cwd,
19222
20028
  config: {
19223
- ...model ? { modelSelection: model } : {},
20029
+ ...model2 ? { modelSelection: model2 } : {},
19224
20030
  ...mode ? { mode } : {},
19225
20031
  ...input.thinkingOptionId ? { thought: input.thinkingOptionId } : {}
19226
20032
  }