@codexhost/cli-darwin-x64 0.12.2 → 0.13.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 (54) 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 +4924 -935
  6. package/app/desktop-controller.mjs +252 -41
  7. package/app/host-runtime.mjs +5312 -1442
  8. package/app/plugins/antigravity/manifest.json +18 -1
  9. package/app/plugins/antigravity/plugin.mjs +275 -41
  10. package/app/plugins/claude-code/manifest.json +28 -0
  11. package/app/plugins/claude-code/plugin.mjs +1045 -355
  12. package/app/plugins/codebuddy/manifest.json +17 -0
  13. package/app/plugins/codebuddy/plugin.mjs +5930 -5357
  14. package/app/plugins/codex-usage/manifest.json +9 -0
  15. package/app/plugins/codex-usage/plugin.mjs +16703 -0
  16. package/app/plugins/cursor-cli/manifest.json +17 -0
  17. package/app/plugins/cursor-cli/plugin.mjs +350 -76
  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 +797 -241
  21. package/app/plugins/enabled.json +2 -1
  22. package/app/plugins/grok/manifest.json +21 -1
  23. package/app/plugins/grok/plugin.mjs +883 -258
  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 +277 -32
  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 +554 -35
  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 +283 -21
  33. package/app/plugins/omp/manifest.json +21 -1
  34. package/app/plugins/omp/plugin.mjs +2737 -1956
  35. package/app/plugins/opencode/manifest.json +18 -1
  36. package/app/plugins/opencode/plugin.mjs +693 -146
  37. package/app/plugins/pi/manifest.json +32 -0
  38. package/app/plugins/pi/plugin.mjs +2809 -2254
  39. package/app/plugins/qoder/manifest.json +18 -1
  40. package/app/plugins/qoder/plugin.mjs +584 -80
  41. package/app/plugins/qoder-cn/manifest.json +18 -1
  42. package/app/plugins/qoder-cn/plugin.mjs +584 -80
  43. package/app/plugins/workbuddy/manifest.json +18 -0
  44. package/app/plugins/workbuddy/plugin.mjs +6316 -5745
  45. package/app/plugins/zcode/manifest.json +19 -1
  46. package/app/plugins/zcode/plugin.mjs +1065 -259
  47. package/app/renderer-extension.js +1485 -1570
  48. package/bin/codexhost +0 -0
  49. package/libexec/codexhost-shim +0 -0
  50. package/libexec/codexhost-updater +0 -0
  51. package/licenses/Cordis-LICENSE.txt +21 -0
  52. package/licenses/Cosmokit-LICENSE.txt +21 -0
  53. package/package.json +1 -1
  54. package/app/plugins/kiro-cli/assets/icon.svg +0 -5
@@ -4100,7 +4100,7 @@ async function npmInstallation(command, packages, environment) {
4100
4100
  const npm = resolveHarnessExecutable({ id: "npm", command: "npm", installRoots: { posix: [], windows: [] } }, { environment: env });
4101
4101
  let globalInstall = modules === globalRoot;
4102
4102
  if (process.platform === "win32") {
4103
- const project = (await Promise.all(["package.json", "package-lock.json", "npm-shrinkwrap.json"].map((file2) => readFile(path4.join(prefix, file2), "utf8").then(() => true, (error51) => error51.code !== "ENOENT")))).some(Boolean);
4103
+ const project2 = (await Promise.all(["package.json", "package-lock.json", "npm-shrinkwrap.json"].map((file2) => readFile(path4.join(prefix, file2), "utf8").then(() => true, (error51) => error51.code !== "ENOENT")))).some(Boolean);
4104
4104
  const bins = typeof metadata.bin === "string" ? { [name.split("/").at(-1) ?? name]: metadata.bin } : metadata.bin ?? {};
4105
4105
  const launchers = await Promise.all(Object.entries(bins).map(async ([bin, entry]) => {
4106
4106
  if (path4.basename(bin) !== bin || entry.includes(".."))
@@ -4111,7 +4111,7 @@ async function npmInstallation(command, packages, environment) {
4111
4111
  const shim = await readFile(path4.join(prefix, `${bin}.cmd`), "utf8").catch(() => "");
4112
4112
  return referencesNpmBin(shim, name, entry);
4113
4113
  }));
4114
- globalInstall = globalInstall && !project && launchers.some(Boolean);
4114
+ globalInstall = globalInstall && !project2 && launchers.some(Boolean);
4115
4115
  }
4116
4116
  const canUpdate = globalInstall && !!npm;
4117
4117
  return {
@@ -4191,6 +4191,48 @@ function createHarnessInstaller(environment, source) {
4191
4191
  };
4192
4192
  }
4193
4193
 
4194
+ // dist/modern/usage-statistics.js
4195
+ import os2 from "node:os";
4196
+ import path5 from "node:path";
4197
+ import { lstat, readFile as readFile2, readdir } from "node:fs/promises";
4198
+ import { zstdDecompressSync } from "node:zlib";
4199
+
4200
+ // ../../harness-adapter/dist/usage-statistics.js
4201
+ var MAX_SESSION_ID_LENGTH = 512;
4202
+ var MAX_CWD_LENGTH = 4096;
4203
+ function sessionIdOk(value) {
4204
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
4205
+ }
4206
+ function cwdOk(value) {
4207
+ 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("\\\\"));
4208
+ }
4209
+ function withUsageSession(entry, session) {
4210
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
4211
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
4212
+ if (sessionId === void 0 && cwd === void 0)
4213
+ return entry;
4214
+ return {
4215
+ ...entry,
4216
+ ...sessionId !== void 0 ? { sessionId } : {},
4217
+ ...cwd !== void 0 ? { cwd } : {}
4218
+ };
4219
+ }
4220
+ function usageEntryFromRequest(request, occurredAtMs) {
4221
+ if (!Number.isSafeInteger(occurredAtMs) || occurredAtMs <= 0)
4222
+ return null;
4223
+ return {
4224
+ id: request.requestId,
4225
+ occurredAtMs,
4226
+ ...request.model !== void 0 ? { model: request.model } : {},
4227
+ inputTokens: request.inputTokens,
4228
+ ...request.cachedInputTokens !== void 0 ? { cachedInputTokens: request.cachedInputTokens } : {},
4229
+ ...request.cacheWriteInputTokens !== void 0 ? { cacheWriteInputTokens: request.cacheWriteInputTokens } : {},
4230
+ ...request.cacheWrite1hInputTokens !== void 0 ? { cacheWrite1hInputTokens: request.cacheWrite1hInputTokens } : {},
4231
+ outputTokens: request.outputTokens,
4232
+ ...request.reasoningOutputTokens !== void 0 ? { reasoningOutputTokens: request.reasoningOutputTokens } : {}
4233
+ };
4234
+ }
4235
+
4194
4236
  // ../../../node_modules/zod/v4/classic/external.js
4195
4237
  var external_exports = {};
4196
4238
  __export(external_exports, {
@@ -4957,10 +4999,10 @@ function mergeDefs(...defs) {
4957
4999
  function cloneDef(schema) {
4958
5000
  return mergeDefs(schema._zod.def);
4959
5001
  }
4960
- function getElementAtPath(obj, path8) {
4961
- if (!path8)
5002
+ function getElementAtPath(obj, path9) {
5003
+ if (!path9)
4962
5004
  return obj;
4963
- return path8.reduce((acc, key) => acc?.[key], obj);
5005
+ return path9.reduce((acc, key) => acc?.[key], obj);
4964
5006
  }
4965
5007
  function promiseAllObject(promisesObj) {
4966
5008
  const keys = Object.keys(promisesObj);
@@ -5369,11 +5411,11 @@ function explicitlyAborted(x, startIndex = 0) {
5369
5411
  }
5370
5412
  return false;
5371
5413
  }
5372
- function prefixIssues(path8, issues) {
5414
+ function prefixIssues(path9, issues) {
5373
5415
  return issues.map((iss) => {
5374
5416
  var _a3;
5375
5417
  (_a3 = iss).path ?? (_a3.path = []);
5376
- iss.path.unshift(path8);
5418
+ iss.path.unshift(path9);
5377
5419
  return iss;
5378
5420
  });
5379
5421
  }
@@ -5520,16 +5562,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
5520
5562
  }
5521
5563
  function formatError(error51, mapper = (issue2) => issue2.message) {
5522
5564
  const fieldErrors = { _errors: [] };
5523
- const processError = (error52, path8 = []) => {
5565
+ const processError = (error52, path9 = []) => {
5524
5566
  for (const issue2 of error52.issues) {
5525
5567
  if (issue2.code === "invalid_union" && issue2.errors.length) {
5526
- issue2.errors.map((issues) => processError({ issues }, [...path8, ...issue2.path]));
5568
+ issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
5527
5569
  } else if (issue2.code === "invalid_key") {
5528
- processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
5570
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
5529
5571
  } else if (issue2.code === "invalid_element") {
5530
- processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
5572
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
5531
5573
  } else {
5532
- const fullpath = [...path8, ...issue2.path];
5574
+ const fullpath = [...path9, ...issue2.path];
5533
5575
  if (fullpath.length === 0) {
5534
5576
  fieldErrors._errors.push(mapper(issue2));
5535
5577
  } else {
@@ -5556,17 +5598,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
5556
5598
  }
5557
5599
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
5558
5600
  const result = { errors: [] };
5559
- const processError = (error52, path8 = []) => {
5601
+ const processError = (error52, path9 = []) => {
5560
5602
  var _a3, _b;
5561
5603
  for (const issue2 of error52.issues) {
5562
5604
  if (issue2.code === "invalid_union" && issue2.errors.length) {
5563
- issue2.errors.map((issues) => processError({ issues }, [...path8, ...issue2.path]));
5605
+ issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
5564
5606
  } else if (issue2.code === "invalid_key") {
5565
- processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
5607
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
5566
5608
  } else if (issue2.code === "invalid_element") {
5567
- processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
5609
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
5568
5610
  } else {
5569
- const fullpath = [...path8, ...issue2.path];
5611
+ const fullpath = [...path9, ...issue2.path];
5570
5612
  if (fullpath.length === 0) {
5571
5613
  result.errors.push(mapper(issue2));
5572
5614
  continue;
@@ -5598,8 +5640,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
5598
5640
  }
5599
5641
  function toDotPath(_path) {
5600
5642
  const segs = [];
5601
- const path8 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
5602
- for (const seg of path8) {
5643
+ const path9 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
5644
+ for (const seg of path9) {
5603
5645
  if (typeof seg === "number")
5604
5646
  segs.push(`[${seg}]`);
5605
5647
  else if (typeof seg === "symbol")
@@ -8827,8 +8869,8 @@ function az_default() {
8827
8869
  }
8828
8870
 
8829
8871
  // ../../../node_modules/zod/v4/locales/be.js
8830
- function getBelarusianPlural(count, one, few, many) {
8831
- const absCount = Math.abs(count);
8872
+ function getBelarusianPlural(count3, one, few, many) {
8873
+ const absCount = Math.abs(count3);
8832
8874
  const lastDigit = absCount % 10;
8833
8875
  const lastTwoDigits = absCount % 100;
8834
8876
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -10906,8 +10948,8 @@ function hu_default() {
10906
10948
  }
10907
10949
 
10908
10950
  // ../../../node_modules/zod/v4/locales/hy.js
10909
- function getArmenianPlural(count, one, many) {
10910
- return Math.abs(count) === 1 ? one : many;
10951
+ function getArmenianPlural(count3, one, many) {
10952
+ return Math.abs(count3) === 1 ? one : many;
10911
10953
  }
10912
10954
  function withDefiniteArticle(word) {
10913
10955
  if (!word)
@@ -13035,8 +13077,8 @@ function ro_default() {
13035
13077
  }
13036
13078
 
13037
13079
  // ../../../node_modules/zod/v4/locales/ru.js
13038
- function getRussianPlural(count, one, few, many) {
13039
- const absCount = Math.abs(count);
13080
+ function getRussianPlural(count3, one, few, many) {
13081
+ const absCount = Math.abs(count3);
13040
13082
  const lastDigit = absCount % 10;
13041
13083
  const lastTwoDigits = absCount % 100;
13042
13084
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -18291,13 +18333,13 @@ function resolveRef(ref, ctx) {
18291
18333
  if (!ref.startsWith("#")) {
18292
18334
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
18293
18335
  }
18294
- const path8 = ref.slice(1).split("/").filter(Boolean);
18295
- if (path8.length === 0) {
18336
+ const path9 = ref.slice(1).split("/").filter(Boolean);
18337
+ if (path9.length === 0) {
18296
18338
  return ctx.rootSchema;
18297
18339
  }
18298
18340
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
18299
- if (path8[0] === defsKey) {
18300
- const key = path8[1];
18341
+ if (path9[0] === defsKey) {
18342
+ const key = path9[1];
18301
18343
  if (!key || !ctx.defs[key]) {
18302
18344
  throw new Error(`Reference not found: ${ref}`);
18303
18345
  }
@@ -18705,6 +18747,15 @@ function date4(params) {
18705
18747
  // ../../../node_modules/zod/v4/classic/external.js
18706
18748
  config(en_default());
18707
18749
 
18750
+ // ../../shared-contracts/dist/delegation-read.js
18751
+ var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
18752
+ var delegationReadParamsSchema = external_exports.strictObject({
18753
+ threadId: external_exports.string().min(1).max(1024),
18754
+ view: external_exports.enum(["result", "messages"]),
18755
+ cursor: external_exports.string().min(1).max(8192).optional(),
18756
+ limit: external_exports.number().int().min(1).max(100).optional()
18757
+ });
18758
+
18708
18759
  // ../../shared-contracts/dist/credential-imports.js
18709
18760
  var credentialSourceSchema = external_exports.object({
18710
18761
  id: external_exports.string().min(1).max(256),
@@ -18775,6 +18826,153 @@ var harnessDisplaySetSchema = external_exports.strictObject({
18775
18826
  initializeOnly: external_exports.boolean().optional()
18776
18827
  });
18777
18828
 
18829
+ // ../../shared-contracts/dist/model-price-overrides.js
18830
+ var usdPerMillionTokens = external_exports.number().finite().nonnegative();
18831
+ var modelPriceOverrideSchema = external_exports.strictObject({
18832
+ input: usdPerMillionTokens,
18833
+ output: usdPerMillionTokens,
18834
+ cacheRead: usdPerMillionTokens.optional(),
18835
+ cacheWrite: usdPerMillionTokens.optional(),
18836
+ cacheWrite1h: usdPerMillionTokens.optional()
18837
+ });
18838
+ var modelPriceKeySchema = external_exports.string().max(512).refine((key) => key.trim() === key && key.length > 0, "Model ID is required");
18839
+ var modelPriceOverridesSchema = external_exports.strictObject({
18840
+ /** Absolute path of the Host's `pricing.json`. */
18841
+ path: external_exports.string(),
18842
+ entries: external_exports.array(external_exports.strictObject({ key: external_exports.string(), price: modelPriceOverrideSchema })),
18843
+ /** Why the existing file is unusable; the Host then ignores it and refuses to overwrite it. */
18844
+ error: external_exports.string().nullable()
18845
+ });
18846
+ var modelPriceOverridesGetSchema = external_exports.strictObject({});
18847
+ var modelPriceOverridesSetSchema = external_exports.strictObject({
18848
+ key: modelPriceKeySchema,
18849
+ price: modelPriceOverrideSchema.nullable(),
18850
+ previousKey: modelPriceKeySchema.optional()
18851
+ });
18852
+ var modelPriceDefaultParamsSchema = external_exports.strictObject({
18853
+ model: modelPriceKeySchema
18854
+ });
18855
+ var modelPriceSuggestionSchema = external_exports.strictObject({
18856
+ /** Verified from catalog canonical links, not inferred from names or equal prices. */
18857
+ official: external_exports.boolean().optional(),
18858
+ canonicalModelId: external_exports.string().min(1).optional(),
18859
+ provider: external_exports.string().min(1).max(512),
18860
+ model: external_exports.string().min(1).max(512),
18861
+ price: modelPriceOverrideSchema
18862
+ });
18863
+ var modelPriceDefaultResultSchema = external_exports.strictObject({
18864
+ price: modelPriceOverrideSchema.nullable(),
18865
+ /** Local catalog suggestions only; never used automatically for pricing. */
18866
+ suggestions: external_exports.array(modelPriceSuggestionSchema).max(6).optional()
18867
+ });
18868
+
18869
+ // ../../shared-contracts/dist/usage-statistics.js
18870
+ var USAGE_STATISTICS_RANGES = ["today", "7d", "30d", "90d", "all"];
18871
+ var count = external_exports.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
18872
+ var localDate = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/u);
18873
+ var harness = external_exports.string().min(1).max(128);
18874
+ var model = external_exports.string().min(1).max(512);
18875
+ var project = external_exports.string().min(1).max(4096);
18876
+ var usageStatisticsParamsSchema = external_exports.strictObject({
18877
+ range: external_exports.enum(USAGE_STATISTICS_RANGES),
18878
+ harness: harness.optional(),
18879
+ model: model.nullable().optional(),
18880
+ project: project.nullable().optional(),
18881
+ /** One local date inside the range. */
18882
+ date: localDate.optional()
18883
+ });
18884
+ var usageStatisticsTotalsSchema = external_exports.strictObject({
18885
+ requests: count,
18886
+ inputTokens: count,
18887
+ cachedInputTokens: count,
18888
+ cacheWriteInputTokens: count,
18889
+ cacheKnownInputTokens: count,
18890
+ outputTokens: count,
18891
+ reasoningOutputTokens: count,
18892
+ /** USD at the public price, summed over the priced requests only. */
18893
+ costUsd: external_exports.number().finite().min(0),
18894
+ /** Requests without a price (or the cache data the price needs); not in `costUsd`. */
18895
+ unpricedRequests: count,
18896
+ /**
18897
+ * Requests whose storage gave no token counts: counted as requests, with neither tokens nor
18898
+ * cost, and not as unpriced.
18899
+ */
18900
+ unmeteredRequests: count
18901
+ });
18902
+ var totals = usageStatisticsTotalsSchema.shape;
18903
+ var usageStatisticsSessionSchema = external_exports.strictObject({
18904
+ harness,
18905
+ sessionId: external_exports.string().min(1).max(512),
18906
+ project: project.nullable(),
18907
+ /** Models the session used, most requests first. */
18908
+ models: external_exports.array(model).max(16),
18909
+ firstAtMs: count,
18910
+ lastAtMs: count,
18911
+ ...totals
18912
+ });
18913
+ var usageStatisticsResultSchema = external_exports.strictObject({
18914
+ range: external_exports.enum(USAGE_STATISTICS_RANGES),
18915
+ /** First local date of the range; null for all time. */
18916
+ from: localDate.nullable(),
18917
+ to: localDate,
18918
+ /** The filters these figures apply, echoed so a late answer to older filters is recognised. */
18919
+ filters: external_exports.strictObject({
18920
+ harness: harness.nullable(),
18921
+ model: model.nullable(),
18922
+ unknownModel: external_exports.boolean(),
18923
+ project: project.nullable(),
18924
+ unknownProject: external_exports.boolean(),
18925
+ date: localDate.nullable()
18926
+ }),
18927
+ /** Reading of native storage: incomplete while the first read, or a refresh, is under way. */
18928
+ reading: external_exports.strictObject({ complete: external_exports.boolean(), sources: count, read: count }),
18929
+ /** Harnesses whose storage could not be read; their part is missing, the rest is complete. */
18930
+ failures: external_exports.array(external_exports.strictObject({ harness, message: external_exports.string().max(2048) })).max(256),
18931
+ /** Every value seen in the range, ignoring the filters, to choose filters from. */
18932
+ options: external_exports.strictObject({
18933
+ harnesses: external_exports.array(harness).max(256),
18934
+ models: external_exports.array(model.nullable()).max(4096),
18935
+ projects: external_exports.array(project.nullable()).max(4096)
18936
+ }),
18937
+ /** Current display metadata, scoped by Harness. Never a pricing or filter identity.
18938
+ * Optional for older Hosts; missing/conflicting labels fall back to the native model ID.
18939
+ */
18940
+ modelLabels: external_exports.array(external_exports.strictObject({ harness, model, label: model })).max(4096).optional(),
18941
+ /** Native credits, all filters applied, never combined across Harnesses or treated as USD.
18942
+ * Only groups with at least one reported value appear; reportedRequests exposes partial data.
18943
+ */
18944
+ credits: external_exports.array(external_exports.strictObject({
18945
+ harness,
18946
+ model: model.nullable(),
18947
+ credits: external_exports.number().finite().min(0),
18948
+ reportedRequests: count,
18949
+ requests: count
18950
+ })).max(4096).optional(),
18951
+ /** All filters applied. */
18952
+ totals: usageStatisticsTotalsSchema,
18953
+ /** Each date and Harness of the range: every filter except the day. */
18954
+ daily: external_exports.array(external_exports.strictObject({ date: localDate, harness, ...totals })).max(2e5),
18955
+ /** Local weekday (0 = Sunday) and hour, all filters applied. */
18956
+ hourly: external_exports.array(external_exports.strictObject({
18957
+ weekday: external_exports.number().int().min(0).max(6),
18958
+ hour: external_exports.number().int().min(0).max(23),
18959
+ ...totals
18960
+ })).max(168),
18961
+ byHarness: external_exports.array(external_exports.strictObject({ harness, ...totals })).max(256),
18962
+ byModel: external_exports.array(external_exports.strictObject({
18963
+ model: model.nullable(),
18964
+ ...totals,
18965
+ /** Requests priced by what the Harness recorded they cost, not by a price list. */
18966
+ harnessPricedRequests: count
18967
+ })).max(4096),
18968
+ byProject: external_exports.array(external_exports.strictObject({ project: project.nullable(), ...totals })).max(4096),
18969
+ /**
18970
+ * The sessions that spent the most, by cost and by tokens without cache, all filters applied;
18971
+ * requests without a native session are not listed here but count everywhere else.
18972
+ */
18973
+ sessions: external_exports.array(usageStatisticsSessionSchema).max(100)
18974
+ });
18975
+
18778
18976
  // ../../shared-contracts/dist/ids.js
18779
18977
  var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
18780
18978
  message: "Identifier must not be empty or whitespace"
@@ -18822,6 +19020,10 @@ var CONSOLE_HOST_METHODS = Object.freeze([
18822
19020
  "codexhost/account/list",
18823
19021
  "codexhost/account/refresh",
18824
19022
  "codexhost/account/usage/inspect",
19023
+ "codexhost/usage/model-prices/get",
19024
+ "codexhost/usage/model-prices/set",
19025
+ "codexhost/usage/model-prices/default",
19026
+ "codexhost/usage/statistics/get",
18825
19027
  "codexhost/update/check",
18826
19028
  "codexhost/update/start",
18827
19029
  "codexhost/update/status"
@@ -18886,6 +19088,7 @@ var threadUsageSnapshotSchema = external_exports.object({
18886
19088
  cacheWriteInputTokens: nonNegativeSafeIntegerSchema.optional(),
18887
19089
  outputTokens: nonNegativeSafeIntegerSchema.optional(),
18888
19090
  outputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
19091
+ apiOutputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
18889
19092
  reasoningOutputTokens: nonNegativeSafeIntegerSchema.optional(),
18890
19093
  totalTokens: nonNegativeSafeIntegerSchema.optional(),
18891
19094
  totalCostUsd: finiteNonNegativeNumberSchema.optional(),
@@ -18897,7 +19100,11 @@ var threadUsageSnapshotSchema = external_exports.object({
18897
19100
  planFiveHourUsedPercent: cacheHitRatePercentSchema.optional(),
18898
19101
  planFiveHourResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
18899
19102
  planSevenDayUsedPercent: cacheHitRatePercentSchema.optional(),
18900
- planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional()
19103
+ planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
19104
+ sessionCacheHitRatePercent: cacheHitRatePercentSchema.optional(),
19105
+ timeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
19106
+ costSource: external_exports.enum(["publicPrice", "native"]).optional(),
19107
+ unpricedModels: external_exports.array(external_exports.string().min(1)).min(1).optional()
18901
19108
  }).strict().superRefine((usage, context) => {
18902
19109
  if (Object.keys(usage).length === 0) {
18903
19110
  context.addIssue({ code: "custom", message: "Thread Usage must contain a reliable field" });
@@ -18918,6 +19125,20 @@ var threadUsageSnapshotSchema = external_exports.object({
18918
19125
  path: ["contextWindowTokens"]
18919
19126
  });
18920
19127
  }
19128
+ if (usage.costSource !== void 0 && usage.totalCostUsd === void 0) {
19129
+ context.addIssue({
19130
+ code: "custom",
19131
+ message: "Thread Usage costSource must be provided with totalCostUsd",
19132
+ path: ["costSource"]
19133
+ });
19134
+ }
19135
+ if (usage.unpricedModels !== void 0 && usage.costSource !== "publicPrice") {
19136
+ context.addIssue({
19137
+ code: "custom",
19138
+ message: "Thread Usage unpricedModels must be provided with a publicPrice cost",
19139
+ path: ["unpricedModels"]
19140
+ });
19141
+ }
18921
19142
  if (usage.planFiveHourResetsAtUnix !== void 0 && usage.planFiveHourUsedPercent === void 0) {
18922
19143
  context.addIssue({
18923
19144
  code: "custom",
@@ -19172,27 +19393,27 @@ var harnessModelCatalogSchema = external_exports.object({
19172
19393
  }).strict().superRefine((catalog, context) => {
19173
19394
  const refs = /* @__PURE__ */ new Set();
19174
19395
  const thinkingIds = new Set(catalog.thinkingOptions.map(({ id }) => id));
19175
- for (const [index, model] of catalog.models.entries()) {
19176
- if (refs.has(model.ref.id)) {
19396
+ for (const [index, model2] of catalog.models.entries()) {
19397
+ if (refs.has(model2.ref.id)) {
19177
19398
  context.addIssue({
19178
19399
  code: "custom",
19179
19400
  message: "Model Catalog refs must be unique",
19180
19401
  path: ["models", index, "ref", "id"]
19181
19402
  });
19182
19403
  }
19183
- refs.add(model.ref.id);
19184
- if (model.fastModel) {
19185
- if (refs.has(model.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model.fastModel?.id)) {
19404
+ refs.add(model2.ref.id);
19405
+ if (model2.fastModel) {
19406
+ if (refs.has(model2.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model2.fastModel?.id)) {
19186
19407
  context.addIssue({
19187
19408
  code: "custom",
19188
19409
  message: "Fast Model refs must be distinct and unique",
19189
19410
  path: ["models", index, "fastModel"]
19190
19411
  });
19191
19412
  }
19192
- refs.add(model.fastModel.id);
19413
+ refs.add(model2.fastModel.id);
19193
19414
  }
19194
19415
  const supportedThinkingIds = /* @__PURE__ */ new Set();
19195
- for (const [optionIndex, optionId] of (model.supportedThinkingOptionIds ?? []).entries()) {
19416
+ for (const [optionIndex, optionId] of (model2.supportedThinkingOptionIds ?? []).entries()) {
19196
19417
  if (supportedThinkingIds.has(optionId)) {
19197
19418
  context.addIssue({
19198
19419
  code: "custom",
@@ -19386,13 +19607,40 @@ var HARNESS_PLUGIN_LIMIT = 128;
19386
19607
  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);
19387
19608
  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");
19388
19609
  var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
19610
+ var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
19611
+ var harnessInstallationGuideSchema = external_exports.object({
19612
+ commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
19613
+ before: localizedTextSchema.optional(),
19614
+ after: localizedTextSchema.optional(),
19615
+ downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
19616
+ }).strict();
19389
19617
  var pluginPresentationShape = {
19390
19618
  id: harnessPluginIdSchema,
19391
19619
  name: external_exports.string().trim().min(1).max(128),
19392
19620
  version: external_exports.string().min(1).max(128),
19621
+ /** Capability-only plugin; omitted for existing session-capable plugins. */
19622
+ kind: external_exports.literal("usage").optional(),
19623
+ /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
19624
+ iconStyle: external_exports.object({
19625
+ vector: external_exports.object({
19626
+ viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
19627
+ color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
19628
+ paths: external_exports.array(external_exports.object({
19629
+ d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
19630
+ fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
19631
+ fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
19632
+ }).strict()).min(1).max(32)
19633
+ }).strict().optional(),
19634
+ background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
19635
+ borderRadius: external_exports.number().min(0).max(50).optional(),
19636
+ paddingRatio: external_exports.number().min(0).max(0.25).optional()
19637
+ }).strict().optional(),
19638
+ installation: harnessInstallationGuideSchema.optional(),
19639
+ notice: localizedTextSchema.optional(),
19393
19640
  /** The factory accepts a persisted local entrypoint through its construction context. */
19394
19641
  launchCommand: external_exports.literal(true).optional(),
19395
19642
  links: external_exports.object({
19643
+ website: documentationUrlSchema.optional(),
19396
19644
  documentation: documentationUrlSchema.optional(),
19397
19645
  installation: documentationUrlSchema.optional()
19398
19646
  }).strict().optional()
@@ -19815,6 +20063,11 @@ var codexSshDraftSchema = external_exports.strictObject({
19815
20063
  });
19816
20064
  var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action", [
19817
20065
  external_exports.strictObject({ action: external_exports.literal("list") }),
20066
+ external_exports.strictObject({
20067
+ action: external_exports.literal("read-thread"),
20068
+ hostId: hostId.refine((id) => id !== "local"),
20069
+ input: delegationReadParamsSchema
20070
+ }),
19818
20071
  external_exports.strictObject({
19819
20072
  action: external_exports.literal("save"),
19820
20073
  draft: codexSshDraftSchema,
@@ -19975,10 +20228,12 @@ var tokenFields = [
19975
20228
  ];
19976
20229
  var safeIntegerFields = [
19977
20230
  "planFiveHourResetsAtUnix",
19978
- "planSevenDayResetsAtUnix"
20231
+ "planSevenDayResetsAtUnix",
20232
+ "timeToFirstOutputMs"
19979
20233
  ];
19980
20234
  var percentFields = [
19981
20235
  "cacheHitRatePercent",
20236
+ "sessionCacheHitRatePercent",
19982
20237
  "planFiveHourUsedPercent",
19983
20238
  "planSevenDayUsedPercent"
19984
20239
  ];
@@ -19986,10 +20241,14 @@ var usageFields = /* @__PURE__ */ new Set([
19986
20241
  ...tokenFields,
19987
20242
  ...safeIntegerFields,
19988
20243
  ...percentFields,
20244
+ "sessionCacheUsage",
19989
20245
  "totalCostUsd",
19990
20246
  "totalCredits",
19991
20247
  "contextUsagePercent",
19992
- "outputTokensPerSecond"
20248
+ "outputTokensPerSecond",
20249
+ "apiOutputTokensPerSecond",
20250
+ "costSource",
20251
+ "unpricedModels"
19993
20252
  ]);
19994
20253
  function isRecord(value) {
19995
20254
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -20005,7 +20264,11 @@ function parseHostUsage(value) {
20005
20264
  throw new Error(`Harness Usage contains unknown field '${key}'`);
20006
20265
  }
20007
20266
  }
20008
- for (const field of ["totalCredits", "contextUsagePercent"]) {
20267
+ for (const field of [
20268
+ "totalCredits",
20269
+ "contextUsagePercent",
20270
+ "apiOutputTokensPerSecond"
20271
+ ]) {
20009
20272
  const candidate = value[field];
20010
20273
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
20011
20274
  throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
@@ -20035,6 +20298,12 @@ function parseHostUsage(value) {
20035
20298
  throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
20036
20299
  }
20037
20300
  }
20301
+ if (value.sessionCacheUsage !== void 0) {
20302
+ const totals2 = value.sessionCacheUsage;
20303
+ 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) {
20304
+ throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
20305
+ }
20306
+ }
20038
20307
  const hasContextUsed = value.contextUsedTokens !== void 0;
20039
20308
  const hasContextWindow = value.contextWindowTokens !== void 0;
20040
20309
  if (hasContextUsed !== hasContextWindow) {
@@ -20049,168 +20318,89 @@ function parseHostUsage(value) {
20049
20318
  if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
20050
20319
  throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
20051
20320
  }
20321
+ if (value.costSource !== void 0) {
20322
+ if (value.costSource !== "publicPrice" && value.costSource !== "native") {
20323
+ throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
20324
+ }
20325
+ if (value.totalCostUsd === void 0) {
20326
+ throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
20327
+ }
20328
+ }
20329
+ if (value.unpricedModels !== void 0) {
20330
+ const models = value.unpricedModels;
20331
+ if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
20332
+ throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
20333
+ }
20334
+ if (value.costSource !== "publicPrice") {
20335
+ throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
20336
+ }
20337
+ return { ...value, unpricedModels: [...models] };
20338
+ }
20052
20339
  return { ...value };
20053
20340
  }
20054
-
20055
- // dist/harness-commands.js
20056
- var commandDefinitions = [
20057
- {
20058
- id: "dsh.compact",
20059
- invocation: "/compact",
20060
- label: "Compact context",
20061
- description: "Compact the current conversation context",
20062
- argumentMode: "none"
20063
- },
20064
- {
20065
- id: "dsh.goal",
20066
- invocation: "/dsh-goal",
20067
- label: "Goal",
20068
- description: "Set or view the goal for a long-running task",
20069
- argumentMode: "text"
20070
- },
20071
- {
20072
- id: "dsh.plan",
20073
- invocation: "/plan",
20074
- label: "Plan mode",
20075
- description: "Enter or leave plan mode",
20076
- argumentMode: "text"
20077
- }
20341
+ var requestTokenFields = [
20342
+ "inputTokens",
20343
+ "cachedInputTokens",
20344
+ "cacheWriteInputTokens",
20345
+ "cacheWrite1hInputTokens",
20346
+ "outputTokens",
20347
+ "reasoningOutputTokens",
20348
+ "startedAtMs",
20349
+ "completedAtMs"
20078
20350
  ];
20079
- function invalidArguments(message) {
20080
- return {
20081
- ok: false,
20082
- error: { code: "invalidRequest", message, retryable: false }
20083
- };
20084
- }
20085
- function deepSeekHarnessCommandCatalog() {
20086
- return harnessCommandCatalogSchema.parse({
20087
- commands: commandDefinitions
20088
- });
20089
- }
20090
- function parseDeepSeekHarnessCommand(command) {
20091
- const definition = commandDefinitions.find(({ id }) => id === command.commandId);
20092
- if (!definition) {
20093
- return {
20094
- ok: false,
20095
- error: {
20096
- code: "unsupported",
20097
- message: `DeepSeek Harness does not expose command '${command.commandId}'`,
20098
- retryable: false
20099
- }
20100
- };
20101
- }
20102
- const nativeInvocation = definition.id === "dsh.goal" ? "/goal" : definition.invocation;
20103
- const arguments_ = command.arguments;
20104
- if (definition.argumentMode === "none") {
20105
- return arguments_ && Object.keys(arguments_).length > 0 ? invalidArguments(`DeepSeek Harness ${nativeInvocation} command does not accept arguments`) : { ok: true, value: { commandId: definition.id, line: nativeInvocation } };
20351
+ var requestFields = /* @__PURE__ */ new Set([
20352
+ ...requestTokenFields,
20353
+ "requestId",
20354
+ "historical",
20355
+ "model",
20356
+ "provider"
20357
+ ]);
20358
+ function parseHostUsageRequest(value) {
20359
+ if (!isRecord(value))
20360
+ throw new Error("Harness Usage request must be an object");
20361
+ for (const key of Object.keys(value)) {
20362
+ if (!requestFields.has(key)) {
20363
+ throw new Error(`Harness Usage request contains unknown field '${key}'`);
20364
+ }
20106
20365
  }
20107
- if (arguments_?.text !== void 0 && typeof arguments_.text !== "string") {
20108
- return invalidArguments(`DeepSeek Harness ${nativeInvocation} command argument 'text' must be a string`);
20366
+ if (typeof value.requestId !== "string" || value.requestId.length === 0) {
20367
+ throw new Error("Harness Usage request 'requestId' must be a non-empty string");
20109
20368
  }
20110
- if (arguments_ && Object.keys(arguments_).some((key) => key !== "text")) {
20111
- return invalidArguments(`DeepSeek Harness ${nativeInvocation} command has an unknown argument`);
20369
+ for (const field of ["model", "provider"]) {
20370
+ const candidate = value[field];
20371
+ if (candidate !== void 0 && (typeof candidate !== "string" || candidate.length === 0)) {
20372
+ throw new Error(`Harness Usage request '${field}' must be a non-empty string`);
20373
+ }
20112
20374
  }
20113
- const text = arguments_?.text?.trim() ?? "";
20114
- if (definition.id === "dsh.goal" && text.toLowerCase() === "edit") {
20115
- return invalidArguments("DeepSeek Harness /goal edit command requires a replacement objective");
20375
+ if (value.historical !== void 0 && typeof value.historical !== "boolean") {
20376
+ throw new Error("Harness Usage request 'historical' must be a boolean");
20116
20377
  }
20117
- return {
20118
- ok: true,
20119
- value: {
20120
- commandId: definition.id,
20121
- line: text.length > 0 ? `${nativeInvocation} ${text}` : nativeInvocation
20378
+ for (const field of requestTokenFields) {
20379
+ const candidate = value[field];
20380
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
20381
+ throw new Error(`Harness Usage request '${field}' must be a non-negative safe integer`);
20122
20382
  }
20123
- };
20124
- }
20125
-
20126
- // dist/generation-selector.js
20127
- import { spawn } from "node:child_process";
20128
-
20129
- // dist/executable.js
20130
- import { spawnSync } from "node:child_process";
20131
- import { accessSync, constants, statSync } from "node:fs";
20132
- import path5 from "node:path";
20133
- function environmentValue2(environment, name) {
20134
- return Object.entries(environment).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
20135
- }
20136
- function executableCandidates(command, environment) {
20137
- const targetPath2 = process.platform === "win32" ? path5.win32 : path5.posix;
20138
- if (targetPath2.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
20139
- return [command];
20140
20383
  }
20141
- const extensions = process.platform === "win32" && targetPath2.extname(command) === "" ? (environmentValue2(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension2) => extension2.trim()).filter(Boolean) : [""];
20142
- return (environmentValue2(environment, "PATH") ?? "").split(targetPath2.delimiter).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean).flatMap((directory) => extensions.map((extension2) => targetPath2.join(directory, command + extension2)));
20143
- }
20144
- function resolveExecutable(command, environment) {
20145
- const accessMode = process.platform === "win32" ? constants.F_OK : constants.X_OK;
20146
- for (const candidate of executableCandidates(command, environment)) {
20147
- try {
20148
- accessSync(candidate, accessMode);
20149
- if (statSync(candidate).isFile())
20150
- return candidate;
20151
- } catch {
20152
- }
20384
+ if (value.inputTokens === void 0 || value.outputTokens === void 0) {
20385
+ throw new Error("Harness Usage request must contain 'inputTokens' and 'outputTokens'");
20153
20386
  }
20154
- return null;
20155
- }
20156
- function resolveDeepSeekCommand(configured, environment) {
20157
- if (configured) {
20158
- const command = resolveExecutable(configured, environment);
20159
- return command ? { command, arguments: [], kind: "configured" } : null;
20387
+ const request = value;
20388
+ if ((request.cachedInputTokens ?? 0) + (request.cacheWriteInputTokens ?? 0) > request.inputTokens) {
20389
+ throw new Error("Harness Usage request cache Tokens must not exceed 'inputTokens'");
20160
20390
  }
20161
- const dsh = resolveExecutable("dsh", environment);
20162
- if (dsh)
20163
- return { command: dsh, arguments: [], kind: "dsh" };
20164
- const npx = resolveExecutable(process.platform === "win32" ? "npx.cmd" : "npx", environment);
20165
- return npx ? {
20166
- command: npx,
20167
- arguments: ["--offline", "--no-install", "@deepseek-ai/dsh"],
20168
- kind: "npx"
20169
- } : null;
20170
- }
20171
- function deepSeekProcessInvocation(command, arguments_, environment, platform = process.platform) {
20172
- const extension2 = path5.win32.extname(command).toLowerCase();
20173
- if (platform !== "win32" || ![".cmd", ".bat"].includes(extension2)) {
20174
- return { command, arguments: arguments_, windowsVerbatimArguments: false };
20391
+ if ((request.reasoningOutputTokens ?? 0) > request.outputTokens) {
20392
+ throw new Error("Harness Usage request 'reasoningOutputTokens' must not exceed 'outputTokens'");
20175
20393
  }
20176
- const quote = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
20177
- const commandLine = [command, ...arguments_].map(quote).join(" ");
20178
- return {
20179
- command: environmentValue2(environment, "ComSpec") ?? "cmd.exe",
20180
- arguments: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
20181
- windowsVerbatimArguments: true
20182
- };
20183
- }
20184
- function resolveWindowsTaskkillPath(environment) {
20185
- const systemRoot = environmentValue2(environment, "SystemRoot") ?? environmentValue2(environment, "windir");
20186
- if (!systemRoot || !/^[A-Za-z]:[\\/]/u.test(systemRoot)) {
20187
- throw new Error("Windows SystemRoot is unavailable or invalid");
20394
+ if (request.cacheWrite1hInputTokens !== void 0 && request.cacheWrite1hInputTokens > (request.cacheWriteInputTokens ?? -1)) {
20395
+ throw new Error("Harness Usage request 'cacheWrite1hInputTokens' must not exceed 'cacheWriteInputTokens'");
20188
20396
  }
20189
- return path5.win32.join(systemRoot, "System32", "taskkill.exe");
20190
- }
20191
- function killDeepSeekProcessTree(child, platform, timeoutMs) {
20192
- if (!child.pid) {
20193
- if (child.exitCode === null && child.signalCode === null)
20194
- child.kill("SIGKILL");
20195
- return;
20196
- }
20197
- if (platform === "win32") {
20198
- const result = spawnSync(resolveWindowsTaskkillPath(process.env), ["/pid", String(child.pid), "/t", "/f"], {
20199
- stdio: "ignore",
20200
- windowsHide: true,
20201
- timeout: timeoutMs
20202
- });
20203
- if (result.error)
20204
- throw result.error;
20205
- return;
20397
+ if (request.startedAtMs === void 0 !== (request.completedAtMs === void 0)) {
20398
+ throw new Error("Harness Usage request timing fields must be provided together");
20206
20399
  }
20207
- try {
20208
- process.kill(-child.pid, "SIGKILL");
20209
- } catch (error51) {
20210
- if (typeof error51 !== "object" || error51 === null || Reflect.get(error51, "code") !== "ESRCH") {
20211
- throw error51;
20212
- }
20400
+ if (request.startedAtMs !== void 0 && request.completedAtMs !== void 0 && request.completedAtMs < request.startedAtMs) {
20401
+ throw new Error("Harness Usage request 'completedAtMs' must not precede 'startedAtMs'");
20213
20402
  }
20403
+ return { ...request };
20214
20404
  }
20215
20405
 
20216
20406
  // dist/profiles/v4.js
@@ -20587,16 +20777,16 @@ var Diff = class {
20587
20777
  }
20588
20778
  }
20589
20779
  }
20590
- addToPath(path8, added, removed, oldPosInc, options) {
20591
- const last = path8.lastComponent;
20780
+ addToPath(path9, added, removed, oldPosInc, options) {
20781
+ const last = path9.lastComponent;
20592
20782
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
20593
20783
  return {
20594
- oldPos: path8.oldPos + oldPosInc,
20784
+ oldPos: path9.oldPos + oldPosInc,
20595
20785
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
20596
20786
  };
20597
20787
  } else {
20598
20788
  return {
20599
- oldPos: path8.oldPos + oldPosInc,
20789
+ oldPos: path9.oldPos + oldPosInc,
20600
20790
  lastComponent: { count: 1, added, removed, previousComponent: last }
20601
20791
  };
20602
20792
  }
@@ -21793,6 +21983,349 @@ var DEEPSEEK_V4_PROFILE = Object.freeze({
21793
21983
  settlementUsage
21794
21984
  });
21795
21985
 
21986
+ // dist/modern/usage-metering.js
21987
+ function isRecord5(value) {
21988
+ return typeof value === "object" && value !== null && !Array.isArray(value);
21989
+ }
21990
+ function count2(value) {
21991
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
21992
+ }
21993
+ function firstTokenTime(chunks) {
21994
+ for (const { time: time3, chunk } of chunks) {
21995
+ if ((chunk.type === "reasoning-delta" || chunk.type === "text-delta") && typeof chunk.text === "string" && chunk.text.length > 0 || chunk.type === "tool-call-delta" && typeof chunk.name === "string" && chunk.name.length > 0) {
21996
+ return time3;
21997
+ }
21998
+ }
21999
+ return null;
22000
+ }
22001
+ function deepSeekUsageRecord(event, historical) {
22002
+ if (event.type !== "assistant/message" || event.surfaceOp !== "append")
22003
+ return { kind: "none" };
22004
+ const data = isRecord5(event.data) ? event.data : null;
22005
+ const message = data && isRecord5(data.message) ? data.message : null;
22006
+ const source = message && isRecord5(message.source) ? message.source : null;
22007
+ if (!data || !message || source?.kind !== "model")
22008
+ return { kind: "none" };
22009
+ if (typeof message.id !== "string" || message.id.length === 0)
22010
+ return { kind: "missing" };
22011
+ if (typeof source.model !== "string" || source.model.length === 0)
22012
+ return { kind: "missing" };
22013
+ let chunks;
22014
+ try {
22015
+ chunks = expandAssistantStream(data.stream);
22016
+ } catch {
22017
+ return { kind: "missing" };
22018
+ }
22019
+ let usage = data.usage;
22020
+ for (const { chunk } of chunks)
22021
+ if (chunk.type === "usage")
22022
+ usage = chunk.usage;
22023
+ if (usage === void 0)
22024
+ return data.interrupted === true ? { kind: "none" } : { kind: "missing" };
22025
+ if (!isRecord5(usage))
22026
+ return { kind: "missing" };
22027
+ const input = count2(usage.inputTokens);
22028
+ const output = count2(usage.outputTokens);
22029
+ const cacheRead = count2(usage.cacheReadTokens ?? 0);
22030
+ const cacheWrite = count2(usage.cacheWriteTokens ?? 0);
22031
+ const reasoning2 = usage.reasoningTokens === void 0 ? null : count2(usage.reasoningTokens);
22032
+ if (input === null || output === null || cacheRead === null || cacheWrite === null) {
22033
+ return { kind: "missing" };
22034
+ }
22035
+ const startedAtMs = historical ? null : firstTokenTime(chunks);
22036
+ const completedAtMs = typeof event.time === "number" ? event.time : null;
22037
+ try {
22038
+ return {
22039
+ kind: "request",
22040
+ request: parseHostUsageRequest({
22041
+ requestId: message.id,
22042
+ ...historical ? { historical: true } : {},
22043
+ model: source.model,
22044
+ inputTokens: input + cacheRead + cacheWrite,
22045
+ cachedInputTokens: cacheRead,
22046
+ cacheWriteInputTokens: cacheWrite,
22047
+ outputTokens: output,
22048
+ ...reasoning2 !== null && reasoning2 <= output ? { reasoningOutputTokens: reasoning2 } : {},
22049
+ ...startedAtMs !== null && completedAtMs !== null && completedAtMs >= startedAtMs ? { startedAtMs, completedAtMs } : {}
22050
+ })
22051
+ };
22052
+ } catch {
22053
+ return { kind: "missing" };
22054
+ }
22055
+ }
22056
+ function deepSeekUsageHistory(events) {
22057
+ const requests = /* @__PURE__ */ new Map();
22058
+ let complete = true;
22059
+ for (const event of events) {
22060
+ const record2 = deepSeekUsageRecord(event, true);
22061
+ if (record2.kind === "request")
22062
+ requests.set(record2.request.requestId, record2.request);
22063
+ else if (record2.kind === "missing")
22064
+ complete = false;
22065
+ }
22066
+ return { requests: [...requests.values()], complete };
22067
+ }
22068
+
22069
+ // dist/modern/usage-statistics.js
22070
+ var SESSION_FILE = /^session(?:\.v(\d+))?\.jsonl(\.zstd)?$/u;
22071
+ var ZSTD_MAGIC = 4247762216;
22072
+ function dshHome(environment) {
22073
+ return environment.DSH_HOME || path5.join(environment.HOME || os2.homedir(), ".dsh");
22074
+ }
22075
+ function zstdFrames(buffer) {
22076
+ const frames = [];
22077
+ let offset = 0;
22078
+ while (offset + 8 <= buffer.length) {
22079
+ const magic = buffer.readUInt32LE(offset);
22080
+ if ((magic & 4294967280) === 407710288) {
22081
+ offset += 8 + buffer.readUInt32LE(offset + 4);
22082
+ continue;
22083
+ }
22084
+ if (magic !== ZSTD_MAGIC)
22085
+ throw new Error("dsh session file is not zstd");
22086
+ const start = offset;
22087
+ const descriptor = buffer[offset + 4] ?? 0;
22088
+ const single = descriptor >> 5 & 1;
22089
+ offset += 5 + (single ? 0 : 1);
22090
+ offset += [0, 1, 2, 4][descriptor & 3] ?? 0;
22091
+ offset += [single, 2, 4, 8][descriptor >> 6] ?? 0;
22092
+ for (; ; ) {
22093
+ if (offset + 3 > buffer.length)
22094
+ return frames;
22095
+ const header = buffer.readUIntLE(offset, 3);
22096
+ const type = header >> 1 & 3;
22097
+ if (type === 3)
22098
+ throw new Error("dsh session file has a reserved zstd block");
22099
+ offset += 3 + (type === 1 ? 1 : header >>> 3);
22100
+ if (header & 1)
22101
+ break;
22102
+ }
22103
+ if (descriptor >> 2 & 1)
22104
+ offset += 4;
22105
+ if (offset > buffer.length)
22106
+ return frames;
22107
+ frames.push(buffer.subarray(start, offset));
22108
+ }
22109
+ return frames;
22110
+ }
22111
+ async function readDshUsage(file2) {
22112
+ const buffer = await readFile2(file2);
22113
+ const text = file2.endsWith(".zstd") ? zstdFrames(buffer).map((frame) => zstdDecompressSync(frame).toString("utf8")).join("") : buffer.toString("utf8");
22114
+ const entries = [];
22115
+ let session = {};
22116
+ for (const line of text.split("\n")) {
22117
+ if (entries.length === 0 && line.startsWith('{"type":"session"')) {
22118
+ try {
22119
+ const header = JSON.parse(line);
22120
+ session = {
22121
+ ...typeof header.id === "string" ? { sessionId: header.id } : {},
22122
+ ...typeof header.cwd === "string" ? { cwd: header.cwd } : {}
22123
+ };
22124
+ } catch {
22125
+ }
22126
+ continue;
22127
+ }
22128
+ if (!line.includes('"assistant/message"'))
22129
+ continue;
22130
+ let event;
22131
+ try {
22132
+ event = JSON.parse(line);
22133
+ } catch {
22134
+ continue;
22135
+ }
22136
+ const record2 = deepSeekUsageRecord(event, true);
22137
+ const entry = record2.kind === "request" && usageEntryFromRequest(record2.request, event.time);
22138
+ if (entry)
22139
+ entries.push(withUsageSession(entry, session));
22140
+ }
22141
+ return entries;
22142
+ }
22143
+ function createDshUsageStatistics(environment) {
22144
+ return Object.freeze({
22145
+ async listSources(signal) {
22146
+ const root = path5.join(dshHome(environment), "sessions");
22147
+ const sources = [];
22148
+ for (const project2 of await readdir(root).catch(() => [])) {
22149
+ for (const session of await readdir(path5.join(root, project2)).catch(() => [])) {
22150
+ signal.throwIfAborted();
22151
+ const directory = path5.join(root, project2, session);
22152
+ const latest = (await readdir(directory).catch(() => [])).map((name) => ({ name, version: Number(SESSION_FILE.exec(name)?.[1] ?? 1) })).filter(({ name }) => SESSION_FILE.test(name)).sort((left, right) => right.version - left.version)[0];
22153
+ if (!latest)
22154
+ continue;
22155
+ const file2 = path5.join(directory, latest.name);
22156
+ const info = await lstat(file2).catch(() => null);
22157
+ if (info?.isFile() && info.size > 0) {
22158
+ sources.push({ id: file2, fingerprint: `${info.ino}:${info.size}:${info.mtimeMs}` });
22159
+ }
22160
+ }
22161
+ }
22162
+ return sources;
22163
+ },
22164
+ readSource: (id) => readDshUsage(id)
22165
+ });
22166
+ }
22167
+
22168
+ // dist/harness-commands.js
22169
+ var commandDefinitions = [
22170
+ {
22171
+ id: "dsh.compact",
22172
+ invocation: "/compact",
22173
+ label: "Compact context",
22174
+ description: "Compact the current conversation context",
22175
+ argumentMode: "none"
22176
+ },
22177
+ {
22178
+ id: "dsh.goal",
22179
+ invocation: "/dsh-goal",
22180
+ label: "Goal",
22181
+ description: "Set or view the goal for a long-running task",
22182
+ argumentMode: "text"
22183
+ },
22184
+ {
22185
+ id: "dsh.plan",
22186
+ invocation: "/plan",
22187
+ label: "Plan mode",
22188
+ description: "Enter or leave plan mode",
22189
+ argumentMode: "text"
22190
+ }
22191
+ ];
22192
+ function invalidArguments(message) {
22193
+ return {
22194
+ ok: false,
22195
+ error: { code: "invalidRequest", message, retryable: false }
22196
+ };
22197
+ }
22198
+ function deepSeekHarnessCommandCatalog() {
22199
+ return harnessCommandCatalogSchema.parse({
22200
+ commands: commandDefinitions
22201
+ });
22202
+ }
22203
+ function parseDeepSeekHarnessCommand(command) {
22204
+ const definition = commandDefinitions.find(({ id }) => id === command.commandId);
22205
+ if (!definition) {
22206
+ return {
22207
+ ok: false,
22208
+ error: {
22209
+ code: "unsupported",
22210
+ message: `DeepSeek Harness does not expose command '${command.commandId}'`,
22211
+ retryable: false
22212
+ }
22213
+ };
22214
+ }
22215
+ const nativeInvocation = definition.id === "dsh.goal" ? "/goal" : definition.invocation;
22216
+ const arguments_ = command.arguments;
22217
+ if (definition.argumentMode === "none") {
22218
+ return arguments_ && Object.keys(arguments_).length > 0 ? invalidArguments(`DeepSeek Harness ${nativeInvocation} command does not accept arguments`) : { ok: true, value: { commandId: definition.id, line: nativeInvocation } };
22219
+ }
22220
+ if (arguments_?.text !== void 0 && typeof arguments_.text !== "string") {
22221
+ return invalidArguments(`DeepSeek Harness ${nativeInvocation} command argument 'text' must be a string`);
22222
+ }
22223
+ if (arguments_ && Object.keys(arguments_).some((key) => key !== "text")) {
22224
+ return invalidArguments(`DeepSeek Harness ${nativeInvocation} command has an unknown argument`);
22225
+ }
22226
+ const text = arguments_?.text?.trim() ?? "";
22227
+ if (definition.id === "dsh.goal" && text.toLowerCase() === "edit") {
22228
+ return invalidArguments("DeepSeek Harness /goal edit command requires a replacement objective");
22229
+ }
22230
+ return {
22231
+ ok: true,
22232
+ value: {
22233
+ commandId: definition.id,
22234
+ line: text.length > 0 ? `${nativeInvocation} ${text}` : nativeInvocation
22235
+ }
22236
+ };
22237
+ }
22238
+
22239
+ // dist/generation-selector.js
22240
+ import { spawn } from "node:child_process";
22241
+
22242
+ // dist/executable.js
22243
+ import { spawnSync } from "node:child_process";
22244
+ import { accessSync, constants, statSync } from "node:fs";
22245
+ import path6 from "node:path";
22246
+ function environmentValue2(environment, name) {
22247
+ return Object.entries(environment).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
22248
+ }
22249
+ function executableCandidates(command, environment) {
22250
+ const targetPath2 = process.platform === "win32" ? path6.win32 : path6.posix;
22251
+ if (targetPath2.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
22252
+ return [command];
22253
+ }
22254
+ const extensions = process.platform === "win32" && targetPath2.extname(command) === "" ? (environmentValue2(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension2) => extension2.trim()).filter(Boolean) : [""];
22255
+ return (environmentValue2(environment, "PATH") ?? "").split(targetPath2.delimiter).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean).flatMap((directory) => extensions.map((extension2) => targetPath2.join(directory, command + extension2)));
22256
+ }
22257
+ function resolveExecutable(command, environment) {
22258
+ const accessMode = process.platform === "win32" ? constants.F_OK : constants.X_OK;
22259
+ for (const candidate of executableCandidates(command, environment)) {
22260
+ try {
22261
+ accessSync(candidate, accessMode);
22262
+ if (statSync(candidate).isFile())
22263
+ return candidate;
22264
+ } catch {
22265
+ }
22266
+ }
22267
+ return null;
22268
+ }
22269
+ function resolveDeepSeekCommand(configured, environment) {
22270
+ if (configured) {
22271
+ const command = resolveExecutable(configured, environment);
22272
+ return command ? { command, arguments: [], kind: "configured" } : null;
22273
+ }
22274
+ const dsh = resolveExecutable("dsh", environment);
22275
+ if (dsh)
22276
+ return { command: dsh, arguments: [], kind: "dsh" };
22277
+ const npx = resolveExecutable(process.platform === "win32" ? "npx.cmd" : "npx", environment);
22278
+ return npx ? {
22279
+ command: npx,
22280
+ arguments: ["--offline", "--no-install", "@deepseek-ai/dsh"],
22281
+ kind: "npx"
22282
+ } : null;
22283
+ }
22284
+ function deepSeekProcessInvocation(command, arguments_, environment, platform = process.platform) {
22285
+ const extension2 = path6.win32.extname(command).toLowerCase();
22286
+ if (platform !== "win32" || ![".cmd", ".bat"].includes(extension2)) {
22287
+ return { command, arguments: arguments_, windowsVerbatimArguments: false };
22288
+ }
22289
+ const quote = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
22290
+ const commandLine = [command, ...arguments_].map(quote).join(" ");
22291
+ return {
22292
+ command: environmentValue2(environment, "ComSpec") ?? "cmd.exe",
22293
+ arguments: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
22294
+ windowsVerbatimArguments: true
22295
+ };
22296
+ }
22297
+ function resolveWindowsTaskkillPath(environment) {
22298
+ const systemRoot = environmentValue2(environment, "SystemRoot") ?? environmentValue2(environment, "windir");
22299
+ if (!systemRoot || !/^[A-Za-z]:[\\/]/u.test(systemRoot)) {
22300
+ throw new Error("Windows SystemRoot is unavailable or invalid");
22301
+ }
22302
+ return path6.win32.join(systemRoot, "System32", "taskkill.exe");
22303
+ }
22304
+ function killDeepSeekProcessTree(child, platform, timeoutMs) {
22305
+ if (!child.pid) {
22306
+ if (child.exitCode === null && child.signalCode === null)
22307
+ child.kill("SIGKILL");
22308
+ return;
22309
+ }
22310
+ if (platform === "win32") {
22311
+ const result = spawnSync(resolveWindowsTaskkillPath(process.env), ["/pid", String(child.pid), "/t", "/f"], {
22312
+ stdio: "ignore",
22313
+ windowsHide: true,
22314
+ timeout: timeoutMs
22315
+ });
22316
+ if (result.error)
22317
+ throw result.error;
22318
+ return;
22319
+ }
22320
+ try {
22321
+ process.kill(-child.pid, "SIGKILL");
22322
+ } catch (error51) {
22323
+ if (typeof error51 !== "object" || error51 === null || Reflect.get(error51, "code") !== "ESRCH") {
22324
+ throw error51;
22325
+ }
22326
+ }
22327
+ }
22328
+
21796
22329
  // dist/profiles/profile.js
21797
22330
  var DEEPSEEK_MINIMUM_VERSION = DEEPSEEK_V4_FIRST_VERSION;
21798
22331
  var MINIMUM = parseSemVer(DEEPSEEK_MINIMUM_VERSION);
@@ -22165,7 +22698,7 @@ async function probeDeepSeekExecutableGeneration(options = {}, dependencies = {
22165
22698
 
22166
22699
  // dist/modern/deepseek-harness-adapter.js
22167
22700
  import { randomUUID as randomUUID2 } from "node:crypto";
22168
- import path7 from "node:path";
22701
+ import path8 from "node:path";
22169
22702
 
22170
22703
  // dist/modern/catalog.js
22171
22704
  import { Buffer as Buffer3 } from "node:buffer";
@@ -22173,9 +22706,9 @@ import { Buffer as Buffer3 } from "node:buffer";
22173
22706
  // dist/model-catalog.js
22174
22707
  import { Buffer as Buffer2 } from "node:buffer";
22175
22708
  var MODEL_REF_PREFIX = "deepseek-harness-model-v2.";
22176
- function encodeDeepSeekHarnessModelRef(model) {
22177
- const provider = model.provider.trim();
22178
- const modelId = model.model.trim();
22709
+ function encodeDeepSeekHarnessModelRef(model2) {
22710
+ const provider = model2.provider.trim();
22711
+ const modelId = model2.model.trim();
22179
22712
  if (!provider || !modelId)
22180
22713
  throw new Error("DeepSeek Harness Model identity must not be empty");
22181
22714
  const encoded = Buffer2.from(JSON.stringify([provider, modelId]), "utf8").toString("base64url");
@@ -22214,8 +22747,8 @@ function parseDeepSeekThinkingOptionId(value) {
22214
22747
  }
22215
22748
  function normalizeDeepSeekThinkingOptions(models) {
22216
22749
  const group = models.groups.find((candidate) => candidate.id === models.current.provider);
22217
- const model = group?.models.find((candidate) => candidate.id === models.current.model);
22218
- return (model?.reasoning?.efforts ?? []).flatMap((effort) => {
22750
+ const model2 = group?.models.find((candidate) => candidate.id === models.current.model);
22751
+ return (model2?.reasoning?.efforts ?? []).flatMap((effort) => {
22219
22752
  const parsedId = harnessThinkingOptionIdSchema.safeParse(effort.id);
22220
22753
  return parsedId.success ? [{ id: parsedId.data, label: effort.name }] : [];
22221
22754
  });
@@ -22224,8 +22757,8 @@ function normalizeDeepSeekModelCatalog(groups2, selection2) {
22224
22757
  const thinkingOptions = [];
22225
22758
  const knownEffortIds = /* @__PURE__ */ new Set();
22226
22759
  for (const group of groups2) {
22227
- for (const model of group.models) {
22228
- for (const effort of model.reasoning?.efforts ?? []) {
22760
+ for (const model2 of group.models) {
22761
+ for (const effort of model2.reasoning?.efforts ?? []) {
22229
22762
  if (knownEffortIds.has(effort.id))
22230
22763
  continue;
22231
22764
  const parsedId = harnessThinkingOptionIdSchema.safeParse(effort.id);
@@ -22236,16 +22769,16 @@ function normalizeDeepSeekModelCatalog(groups2, selection2) {
22236
22769
  }
22237
22770
  }
22238
22771
  }
22239
- const models = groups2.flatMap((group) => group.models.map((model) => ({
22240
- ref: encodeDeepSeekHarnessModelRef({ provider: group.id, model: model.id }),
22241
- label: `${group.name} / ${model.name}`,
22242
- ...model.reasoning && model.reasoning.efforts.length > 0 ? { supportedThinkingOptionIds: model.reasoning.efforts.map((effort) => effort.id) } : {}
22772
+ const models = groups2.flatMap((group) => group.models.map((model2) => ({
22773
+ ref: encodeDeepSeekHarnessModelRef({ provider: group.id, model: model2.id }),
22774
+ label: `${group.name} / ${model2.name}`,
22775
+ ...model2.reasoning && model2.reasoning.efforts.length > 0 ? { supportedThinkingOptionIds: model2.reasoning.efforts.map((effort) => effort.id) } : {}
22243
22776
  })));
22244
22777
  const defaultModel = selection2 ? encodeDeepSeekHarnessModelRef(selection2) : void 0;
22245
- if (selection2 && defaultModel && !models.some((model) => model.ref.id === defaultModel.id)) {
22778
+ if (selection2 && defaultModel && !models.some((model2) => model2.ref.id === defaultModel.id)) {
22246
22779
  models.unshift({ ref: defaultModel, label: `${selection2.provider} / ${selection2.model}` });
22247
22780
  }
22248
- const defaultReasoning = selection2 ? groups2.find((group) => group.id === selection2.provider)?.models.find((model) => model.id === selection2.model)?.reasoning : void 0;
22781
+ const defaultReasoning = selection2 ? groups2.find((group) => group.id === selection2.provider)?.models.find((model2) => model2.id === selection2.model)?.reasoning : void 0;
22249
22782
  const defaultThinkingOptionId = parseDeepSeekThinkingOptionId(selection2?.reasoningEffort ?? defaultReasoning?.defaultEffort);
22250
22783
  return harnessModelCatalogSchema.parse({
22251
22784
  models,
@@ -23430,32 +23963,32 @@ function groups(value, routable) {
23430
23963
  throw catalogError("protocolError", "DeepSeek Harness returned a non-routable Model group");
23431
23964
  }
23432
23965
  const name = boundedString(candidate.name, MAX_NAME_LENGTH, "Model provider name");
23433
- const models = array2(candidate.models, MAX_MODELS, "Model list").map((model) => {
23966
+ const models = array2(candidate.models, MAX_MODELS, "Model list").map((model2) => {
23434
23967
  modelCount += 1;
23435
23968
  if (modelCount > MAX_MODELS) {
23436
23969
  throw catalogError("limitExceeded", "DeepSeek Harness Model list exceeded its item bound");
23437
23970
  }
23438
- if (!isPlainRecord(model) || !exactKeys2(model, ["id", "name"], ["description", "reasoning"])) {
23971
+ if (!isPlainRecord(model2) || !exactKeys2(model2, ["id", "name"], ["description", "reasoning"])) {
23439
23972
  throw catalogError("protocolError", "DeepSeek Harness returned an invalid Model");
23440
23973
  }
23441
- const modelId = boundedString(model.id, MAX_ID_LENGTH, "Model id");
23442
- const modelName = boundedString(model.name, MAX_NAME_LENGTH, "Model name");
23974
+ const modelId = boundedString(model2.id, MAX_ID_LENGTH, "Model id");
23975
+ const modelName = boundedString(model2.name, MAX_NAME_LENGTH, "Model name");
23443
23976
  if (`${name} / ${modelName}`.length > HARNESS_MODEL_LABEL_MAX_LENGTH) {
23444
23977
  throw catalogError("protocolError", "DeepSeek Harness returned a Model label that is too long");
23445
23978
  }
23446
23979
  return {
23447
23980
  id: modelId,
23448
23981
  name: modelName,
23449
- ...model.description === void 0 ? {} : {
23450
- description: boundedString(model.description, MAX_DESCRIPTION_LENGTH, "Model description", true)
23982
+ ...model2.description === void 0 ? {} : {
23983
+ description: boundedString(model2.description, MAX_DESCRIPTION_LENGTH, "Model description", true)
23451
23984
  },
23452
- ...model.reasoning === void 0 ? {} : { reasoning: reasoning(model.reasoning) }
23985
+ ...model2.reasoning === void 0 ? {} : { reasoning: reasoning(model2.reasoning) }
23453
23986
  };
23454
23987
  });
23455
23988
  if (models.length === 0) {
23456
23989
  throw catalogError("protocolError", "DeepSeek Harness returned an empty Model provider group");
23457
23990
  }
23458
- const modelIds = models.map((model) => model.id);
23991
+ const modelIds = models.map((model2) => model2.id);
23459
23992
  if (new Set(modelIds).size !== modelIds.length) {
23460
23993
  throw catalogError("protocolError", "DeepSeek Harness returned duplicate Model ids");
23461
23994
  }
@@ -23666,11 +24199,11 @@ function sanitizedError(error51, fallback) {
23666
24199
  failure.name = redactModernCredential(error51 instanceof Error ? error51.name : "Error");
23667
24200
  return failure;
23668
24201
  }
23669
- function isRecord5(value) {
24202
+ function isRecord6(value) {
23670
24203
  return typeof value === "object" && value !== null && !Array.isArray(value);
23671
24204
  }
23672
24205
  function isPlainRecord3(value) {
23673
- if (!isRecord5(value))
24206
+ if (!isRecord6(value))
23674
24207
  return false;
23675
24208
  const prototype = Object.getPrototypeOf(value);
23676
24209
  return prototype === Object.prototype || prototype === null;
@@ -23820,7 +24353,7 @@ function projectionRow(value, seq) {
23820
24353
  return Object.freeze({ value: detachedJson(value), seq });
23821
24354
  }
23822
24355
  function parseProjectionBaseline(value, maxKeys) {
23823
- if (!isRecord5(value) || !hasExactKeys4(value, ["asOfSeq", "values"])) {
24356
+ if (!isRecord6(value) || !hasExactKeys4(value, ["asOfSeq", "values"])) {
23824
24357
  throw storeError("protocolError", "DeepSeek Harness control baseline has invalid projections");
23825
24358
  }
23826
24359
  if (!validCursor(value.asOfSeq) || !isPlainRecord3(value.values)) {
@@ -23846,7 +24379,7 @@ function parseProjectionBaseline(value, maxKeys) {
23846
24379
  return { asOfSeq: value.asOfSeq, values, rowBytes };
23847
24380
  }
23848
24381
  function parseBaseline(value, maxSessions, maxKeys) {
23849
- if (!isRecord5(value) || !hasExactKeys4(value, ["projections"]) || !isPlainRecord3(value.projections)) {
24382
+ if (!isRecord6(value) || !hasExactKeys4(value, ["projections"]) || !isPlainRecord3(value.projections)) {
23850
24383
  throw storeError("protocolError", "DeepSeek Harness control stream emitted an invalid baseline");
23851
24384
  }
23852
24385
  const sessions = /* @__PURE__ */ new Set();
@@ -23864,7 +24397,7 @@ function parseBaseline(value, maxSessions, maxKeys) {
23864
24397
  return { projections };
23865
24398
  }
23866
24399
  function parseControlFrame(value, maxSessions, maxKeys) {
23867
- if (!isRecord5(value) || typeof value.type !== "string") {
24400
+ if (!isRecord6(value) || typeof value.type !== "string") {
23868
24401
  throw storeError("protocolError", "DeepSeek Harness control stream emitted an invalid frame");
23869
24402
  }
23870
24403
  if (value.type === "baseline" && hasExactKeys4(value, ["type", "value"])) {
@@ -24589,14 +25122,14 @@ function parseSelection(value, area) {
24589
25122
  throw configurationError("protocolError", `DeepSeek Harness returned an invalid ${area}`);
24590
25123
  }
24591
25124
  const provider = boundedSelectionString(value.provider, `${area} provider`);
24592
- const model = boundedSelectionString(value.model, `${area} Model`);
25125
+ const model2 = boundedSelectionString(value.model, `${area} Model`);
24593
25126
  if (value.reasoningEffort === void 0)
24594
- return { provider, model };
25127
+ return { provider, model: model2 };
24595
25128
  const effort = harnessThinkingOptionIdSchema.safeParse(value.reasoningEffort);
24596
25129
  if (!effort.success) {
24597
25130
  throw configurationError("protocolError", `DeepSeek Harness returned an invalid ${area} reasoning effort`);
24598
25131
  }
24599
- return { provider, model, reasoningEffort: effort.data };
25132
+ return { provider, model: model2, reasoningEffort: effort.data };
24600
25133
  }
24601
25134
  function parseOptionalSelection(value, area) {
24602
25135
  return value === null ? null : parseSelection(value, area);
@@ -24659,22 +25192,22 @@ function readModernConfigurationSnapshot(input) {
24659
25192
  if (!rows) {
24660
25193
  throw configurationError("protocolError", "DeepSeek Harness control state is detached");
24661
25194
  }
24662
- const model = readModernModelSelectionState(rows[MODERN_MODEL_SELECTION_PROJECTION_KEY], input.modelCatalog);
25195
+ const model2 = readModernModelSelectionState(rows[MODERN_MODEL_SELECTION_PROJECTION_KEY], input.modelCatalog);
24663
25196
  const permission = readModernPermissionModeState(rows[MODERN_PERMISSION_PROJECTION_KEY], input.permissionModes);
24664
25197
  return {
24665
- model,
24666
- state: stateForSelection(input.nativeRef, model.selection, input.modelCatalog, permission?.permissionModeId),
25198
+ model: model2,
25199
+ state: stateForSelection(input.nativeRef, model2.selection, input.modelCatalog, permission?.permissionModeId),
24667
25200
  ...permission ? { permissionProjectionSeq: permission.projectionSeq } : {}
24668
25201
  };
24669
25202
  }
24670
- function modernSelectionForModel(catalog, model, thinkingOptionId) {
25203
+ function modernSelectionForModel(catalog, model2, thinkingOptionId) {
24671
25204
  let native;
24672
25205
  try {
24673
- native = decodeDeepSeekHarnessModelRef(model);
25206
+ native = decodeDeepSeekHarnessModelRef(model2);
24674
25207
  } catch (error51) {
24675
25208
  throw configurationError("invalidRequest", error51 instanceof Error ? error51.message : "DeepSeek Harness Model is invalid");
24676
25209
  }
24677
- const catalogModel = catalog.catalog.models.find(({ ref }) => ref.id === model.id);
25210
+ const catalogModel = catalog.catalog.models.find(({ ref }) => ref.id === model2.id);
24678
25211
  if (!catalogModel) {
24679
25212
  throw configurationError("invalidRequest", "DeepSeek Harness Model is unavailable");
24680
25213
  }
@@ -25753,11 +26286,11 @@ function malformedOutcome(event) {
25753
26286
  function isApprovalOutcome(value) {
25754
26287
  return value === "allowed-once" || value === "rejected" || value === "cancelled" || value === "unavailable";
25755
26288
  }
25756
- function isRecord6(value) {
26289
+ function isRecord7(value) {
25757
26290
  return typeof value === "object" && value !== null && !Array.isArray(value);
25758
26291
  }
25759
26292
  function isPlainRecord6(value) {
25760
- if (!isRecord6(value))
26293
+ if (!isRecord7(value))
25761
26294
  return false;
25762
26295
  const prototype = Object.getPrototypeOf(value);
25763
26296
  return prototype === Object.prototype || prototype === null;
@@ -28034,6 +28567,10 @@ var ModernHarnessSession = class {
28034
28567
  this.#fallbackThinkingOptionId = configuration.state.effectiveThinkingOptionId;
28035
28568
  this.capabilities = modernSessionCapabilities(this.#permissionModes);
28036
28569
  this.outputs = this.#channel.outputs;
28570
+ const usageHistory = deepSeekUsageHistory(this.#events);
28571
+ for (const request of usageHistory.requests)
28572
+ this.#emit({ type: "usage.request", request });
28573
+ this.#emit({ type: "usage.history", complete: usageHistory.complete });
28037
28574
  this.commands = {
28038
28575
  list: () => this.#listHarnessCommands(),
28039
28576
  execute: (command) => this.#executeHarnessCommand(command)
@@ -29019,6 +29556,7 @@ ${question.detail}` : question.question;
29019
29556
  this.#validator.accept(event);
29020
29557
  this.#observeAssistantSettlement(event);
29021
29558
  this.#events.push(event);
29559
+ this.#meterUsage(event);
29022
29560
  this.#historyBytes += bytes;
29023
29561
  this.#receive(event);
29024
29562
  }
@@ -30068,6 +30606,14 @@ ${question.detail}` : question.question;
30068
30606
  #emit(event) {
30069
30607
  this.#channel.emit({ kind: "event", event });
30070
30608
  }
30609
+ /** Publishes a live model request settled in the journal to Host usage metering. */
30610
+ #meterUsage(event) {
30611
+ const record2 = deepSeekUsageRecord(event, false);
30612
+ if (record2.kind === "request")
30613
+ this.#emit({ type: "usage.request", request: record2.request });
30614
+ else if (record2.kind === "missing")
30615
+ this.#emit({ type: "usage.history", complete: false });
30616
+ }
30071
30617
  };
30072
30618
  var OperationAborted = class extends Error {
30073
30619
  constructor() {
@@ -30392,7 +30938,7 @@ function safeTimerDelay(value, name) {
30392
30938
 
30393
30939
  // dist/modern/session-list.js
30394
30940
  import { Buffer as Buffer5 } from "node:buffer";
30395
- import path6 from "node:path";
30941
+ import path7 from "node:path";
30396
30942
  var MAX_SESSION_LIST_BYTES = 32 * 1024 * 1024;
30397
30943
  var MAX_SESSION_LIST_DEPTH = 64;
30398
30944
  var MAX_SESSION_LIST_NODES = 2e5;
@@ -30511,7 +31057,7 @@ function parseSummary(value) {
30511
31057
  };
30512
31058
  }
30513
31059
  function isCanonicalAbsoluteCwd(value) {
30514
- return value !== void 0 && value.trim().length > 0 && !value.includes("\0") && path6.isAbsolute(value) && path6.resolve(value) === value;
31060
+ return value !== void 0 && value.trim().length > 0 && !value.includes("\0") && path7.isAbsolute(value) && path7.resolve(value) === value;
30515
31061
  }
30516
31062
  function parseModernSessionCandidates(value) {
30517
31063
  assertBoundedJson4(value);
@@ -30709,7 +31255,7 @@ var ModernDeepSeekHarnessAdapter = class {
30709
31255
  let session;
30710
31256
  let forkExpectation;
30711
31257
  try {
30712
- const cwd = path7.resolve(input.cwd);
31258
+ const cwd = path8.resolve(input.cwd);
30713
31259
  let forkInput = input.kind === "fork" ? parseModernForkInput(input, this.#profile) : void 0;
30714
31260
  const rollbackSourceSessionId = input.kind === "rollbackLastTurn" ? modernSessionId(input.sourceRef, "roll back") : void 0;
30715
31261
  let rollbackPlan;
@@ -30870,6 +31416,14 @@ var ModernDeepSeekHarnessAdapter = class {
30870
31416
  this.#sessions.add(openedSession);
30871
31417
  await this.#startEvents();
30872
31418
  this.#assertAccepting();
31419
+ if (input.kind === "resume" && input.permissionModeId) {
31420
+ const restored = await openedSession.execute({
31421
+ type: "permissionMode.select",
31422
+ permissionModeId: input.permissionModeId
31423
+ });
31424
+ if (!restored.ok)
31425
+ throw new AdapterOperationError(restored.error);
31426
+ }
30873
31427
  return { ok: true, value: openedSession };
30874
31428
  } catch (error51) {
30875
31429
  await session?.close().catch(() => void 0);
@@ -30912,7 +31466,7 @@ var ModernDeepSeekHarnessAdapter = class {
30912
31466
  });
30913
31467
  if (!result.ok)
30914
31468
  throw new AdapterOperationError(remoteFailure2("session/create", result.error));
30915
- if (!isRecord7(result.value) || !hasExactOptionalKeys(result.value, ["sessionId"], ["agentPreset"]) || result.value.sessionId !== requestedSessionId || Object.hasOwn(result.value, "agentPreset") && typeof result.value.agentPreset !== "string" || agentPreset !== void 0 && result.value.agentPreset !== agentPreset) {
31469
+ if (!isRecord8(result.value) || !hasExactOptionalKeys(result.value, ["sessionId"], ["agentPreset"]) || result.value.sessionId !== requestedSessionId || Object.hasOwn(result.value, "agentPreset") && typeof result.value.agentPreset !== "string" || agentPreset !== void 0 && result.value.agentPreset !== agentPreset) {
30916
31470
  throw new AdapterOperationError({
30917
31471
  code: "protocolError",
30918
31472
  message: "DeepSeek Harness session/create returned an invalid Session identity",
@@ -30996,7 +31550,7 @@ var ModernDeepSeekHarnessAdapter = class {
30996
31550
  const result = await this.#connection.call("session/fork", { request: { sessionId: input.sourceSessionId, atSeq } }, this.#lifetime.signal);
30997
31551
  if (!result.ok)
30998
31552
  throw new AdapterOperationError(forkRemoteFailure(result.error));
30999
- if (!isRecord7(result.value) || !hasExactOptionalKeys(result.value, ["sessionId"], []) || typeof result.value.sessionId !== "string" || result.value.sessionId.trim() === "" || result.value.sessionId === input.sourceSessionId) {
31553
+ if (!isRecord8(result.value) || !hasExactOptionalKeys(result.value, ["sessionId"], []) || typeof result.value.sessionId !== "string" || result.value.sessionId.trim() === "" || result.value.sessionId === input.sourceSessionId) {
31000
31554
  throw forkProtocolError();
31001
31555
  }
31002
31556
  return {
@@ -31230,7 +31784,7 @@ function verifyCreateConfiguration(requested, observed) {
31230
31784
  }
31231
31785
  }
31232
31786
  function resolveCreateConfiguration(input, modelCatalog, permissionModes) {
31233
- let model;
31787
+ let model2;
31234
31788
  if (input.model || input.thinkingOptionId) {
31235
31789
  const requestedModel = input.model ?? modelCatalog.catalog.defaultModel;
31236
31790
  if (!requestedModel) {
@@ -31240,7 +31794,7 @@ function resolveCreateConfiguration(input, modelCatalog, permissionModes) {
31240
31794
  retryable: false
31241
31795
  });
31242
31796
  }
31243
- model = modernSelectionForModel(modelCatalog, requestedModel, input.thinkingOptionId);
31797
+ model2 = modernSelectionForModel(modelCatalog, requestedModel, input.thinkingOptionId);
31244
31798
  }
31245
31799
  const unattended = input.executionPolicy === "unattended-full-access";
31246
31800
  const permissionModeId = input.permissionModeId ?? (unattended ? harnessPermissionModeIdSchema.parse(DELEGATION_PERMISSION_PRESET) : void 0);
@@ -31252,7 +31806,7 @@ function resolveCreateConfiguration(input, modelCatalog, permissionModes) {
31252
31806
  });
31253
31807
  }
31254
31808
  return {
31255
- ...model ? { model } : {},
31809
+ ...model2 ? { model: model2 } : {},
31256
31810
  ...permissionModeId ? { permissionModeId } : {},
31257
31811
  unattended
31258
31812
  };
@@ -31262,7 +31816,7 @@ function delegationPermissionIsApplied(events) {
31262
31816
  let sandboxMode;
31263
31817
  let approvalPolicy;
31264
31818
  for (const event of events) {
31265
- if (!isRecord7(event.data))
31819
+ if (!isRecord8(event.data))
31266
31820
  continue;
31267
31821
  if (event.type === "permission/preset" && typeof event.data.preset === "string") {
31268
31822
  preset = event.data.preset;
@@ -31301,10 +31855,10 @@ function parseModernForkInput(input, profile) {
31301
31855
  };
31302
31856
  }
31303
31857
  function sessionLocatorMatches(locator) {
31304
- return locator === void 0 || isRecord7(locator) && Reflect.ownKeys(locator).length === 1 && typeof locator.dshVersion === "string" && isDeepSeekSemVer(locator.dshVersion);
31858
+ return locator === void 0 || isRecord8(locator) && Reflect.ownKeys(locator).length === 1 && typeof locator.dshVersion === "string" && isDeepSeekSemVer(locator.dshVersion);
31305
31859
  }
31306
31860
  function checkpointLocatorMatches(locator, profile) {
31307
- return isRecord7(locator) && Reflect.ownKeys(locator).length === 1 && locator.dshVersion === profile.version;
31861
+ return isRecord8(locator) && Reflect.ownKeys(locator).length === 1 && locator.dshVersion === profile.version;
31308
31862
  }
31309
31863
  function forkCheckpointError() {
31310
31864
  return new AdapterOperationError({
@@ -31466,7 +32020,7 @@ function sanitizedHarnessError2(error51) {
31466
32020
  ...error51.stderrTail ? { stderrTail: sanitizeDiagnosticTail(redactModernCredential(error51.stderrTail)) } : {}
31467
32021
  };
31468
32022
  }
31469
- function isRecord7(value) {
32023
+ function isRecord8(value) {
31470
32024
  return typeof value === "object" && value !== null && !Array.isArray(value);
31471
32025
  }
31472
32026
  function hasExactOptionalKeys(value, required2, optional2) {
@@ -31488,6 +32042,7 @@ var DelegateSelectionError = class extends Error {
31488
32042
  var DeepSeekHarnessAdapter = class {
31489
32043
  commandCatalog = deepSeekHarnessCommandCatalog();
31490
32044
  harnessId = DEEPSEEK_HARNESS_ID4;
32045
+ usageStatistics;
31491
32046
  sessionImport = Object.freeze({
31492
32047
  listCandidates: () => this.#listSessionImportCandidates(),
31493
32048
  resolveCandidate: async (nativeSessionId) => {
@@ -31534,6 +32089,7 @@ var DeepSeekHarnessAdapter = class {
31534
32089
  #terminalFailure;
31535
32090
  constructor(options = {}, dependencies = {}) {
31536
32091
  this.#options = options;
32092
+ this.usageStatistics = createDshUsageStatistics(options.environment ?? process.env);
31537
32093
  this.#probeExecutable = dependencies.probeExecutable ?? ((input) => probeDeepSeekExecutableGeneration(input));
31538
32094
  this.#createModernAdapter = dependencies.createModernAdapter ?? ((modernOptions2) => new ModernDeepSeekHarnessAdapter(modernOptions2));
31539
32095
  }