@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
@@ -396,7 +396,7 @@ async function npmInstallation(command, packages, environment) {
396
396
  const npm = resolveHarnessExecutable({ id: "npm", command: "npm", installRoots: { posix: [], windows: [] } }, { environment: env });
397
397
  let globalInstall = modules === globalRoot;
398
398
  if (process.platform === "win32") {
399
- 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);
399
+ 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);
400
400
  const bins = typeof metadata.bin === "string" ? { [name.split("/").at(-1) ?? name]: metadata.bin } : metadata.bin ?? {};
401
401
  const launchers = await Promise.all(Object.entries(bins).map(async ([bin, entry]) => {
402
402
  if (path4.basename(bin) !== bin || entry.includes(".."))
@@ -407,7 +407,7 @@ async function npmInstallation(command, packages, environment) {
407
407
  const shim = await readFile(path4.join(prefix, `${bin}.cmd`), "utf8").catch(() => "");
408
408
  return referencesNpmBin(shim, name, entry);
409
409
  }));
410
- globalInstall = globalInstall && !project && launchers.some(Boolean);
410
+ globalInstall = globalInstall && !project2 && launchers.some(Boolean);
411
411
  }
412
412
  const canUpdate = globalInstall && !!npm;
413
413
  return {
@@ -487,10 +487,50 @@ function createHarnessInstaller(environment, source) {
487
487
  };
488
488
  }
489
489
 
490
- // dist/opencode-adapter.js
491
- import { randomUUID } from "node:crypto";
492
- import fs4 from "node:fs";
493
- import path8 from "node:path";
490
+ // dist/usage-statistics.js
491
+ import os2 from "node:os";
492
+ import path5 from "node:path";
493
+ import { lstat } from "node:fs/promises";
494
+
495
+ // ../../harness-adapter/dist/usage-statistics.js
496
+ var MAX_SESSION_ID_LENGTH = 512;
497
+ var MAX_CWD_LENGTH = 4096;
498
+ function sessionIdOk(value) {
499
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
500
+ }
501
+ function cwdOk(value) {
502
+ 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("\\\\"));
503
+ }
504
+ function withUsageSession(entry, session) {
505
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
506
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
507
+ if (sessionId === void 0 && cwd === void 0)
508
+ return entry;
509
+ return {
510
+ ...entry,
511
+ ...sessionId !== void 0 ? { sessionId } : {},
512
+ ...cwd !== void 0 ? { cwd } : {}
513
+ };
514
+ }
515
+ function usageEntryFromRequest(request, occurredAtMs) {
516
+ if (!Number.isSafeInteger(occurredAtMs) || occurredAtMs <= 0)
517
+ return null;
518
+ return {
519
+ id: request.requestId,
520
+ occurredAtMs,
521
+ ...request.model !== void 0 ? { model: request.model } : {},
522
+ inputTokens: request.inputTokens,
523
+ ...request.cachedInputTokens !== void 0 ? { cachedInputTokens: request.cachedInputTokens } : {},
524
+ ...request.cacheWriteInputTokens !== void 0 ? { cacheWriteInputTokens: request.cacheWriteInputTokens } : {},
525
+ ...request.cacheWrite1hInputTokens !== void 0 ? { cacheWrite1hInputTokens: request.cacheWrite1hInputTokens } : {},
526
+ outputTokens: request.outputTokens,
527
+ ...request.reasoningOutputTokens !== void 0 ? { reasoningOutputTokens: request.reasoningOutputTokens } : {}
528
+ };
529
+ }
530
+ function nativeTimeMs(value) {
531
+ const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
532
+ return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
533
+ }
494
534
 
495
535
  // ../../../node_modules/zod/v4/classic/external.js
496
536
  var external_exports = {};
@@ -1258,10 +1298,10 @@ function mergeDefs(...defs) {
1258
1298
  function cloneDef(schema) {
1259
1299
  return mergeDefs(schema._zod.def);
1260
1300
  }
1261
- function getElementAtPath(obj, path13) {
1262
- if (!path13)
1301
+ function getElementAtPath(obj, path14) {
1302
+ if (!path14)
1263
1303
  return obj;
1264
- return path13.reduce((acc, key) => acc?.[key], obj);
1304
+ return path14.reduce((acc, key) => acc?.[key], obj);
1265
1305
  }
1266
1306
  function promiseAllObject(promisesObj) {
1267
1307
  const keys = Object.keys(promisesObj);
@@ -1670,11 +1710,11 @@ function explicitlyAborted(x, startIndex = 0) {
1670
1710
  }
1671
1711
  return false;
1672
1712
  }
1673
- function prefixIssues(path13, issues) {
1713
+ function prefixIssues(path14, issues) {
1674
1714
  return issues.map((iss) => {
1675
1715
  var _a3;
1676
1716
  (_a3 = iss).path ?? (_a3.path = []);
1677
- iss.path.unshift(path13);
1717
+ iss.path.unshift(path14);
1678
1718
  return iss;
1679
1719
  });
1680
1720
  }
@@ -1821,16 +1861,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1821
1861
  }
1822
1862
  function formatError(error51, mapper = (issue2) => issue2.message) {
1823
1863
  const fieldErrors = { _errors: [] };
1824
- const processError = (error52, path13 = []) => {
1864
+ const processError = (error52, path14 = []) => {
1825
1865
  for (const issue2 of error52.issues) {
1826
1866
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1827
- issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
1867
+ issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1828
1868
  } else if (issue2.code === "invalid_key") {
1829
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1869
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1830
1870
  } else if (issue2.code === "invalid_element") {
1831
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1871
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1832
1872
  } else {
1833
- const fullpath = [...path13, ...issue2.path];
1873
+ const fullpath = [...path14, ...issue2.path];
1834
1874
  if (fullpath.length === 0) {
1835
1875
  fieldErrors._errors.push(mapper(issue2));
1836
1876
  } else {
@@ -1857,17 +1897,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1857
1897
  }
1858
1898
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1859
1899
  const result = { errors: [] };
1860
- const processError = (error52, path13 = []) => {
1900
+ const processError = (error52, path14 = []) => {
1861
1901
  var _a3, _b;
1862
1902
  for (const issue2 of error52.issues) {
1863
1903
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1864
- issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
1904
+ issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1865
1905
  } else if (issue2.code === "invalid_key") {
1866
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1906
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1867
1907
  } else if (issue2.code === "invalid_element") {
1868
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1908
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1869
1909
  } else {
1870
- const fullpath = [...path13, ...issue2.path];
1910
+ const fullpath = [...path14, ...issue2.path];
1871
1911
  if (fullpath.length === 0) {
1872
1912
  result.errors.push(mapper(issue2));
1873
1913
  continue;
@@ -1899,8 +1939,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1899
1939
  }
1900
1940
  function toDotPath(_path) {
1901
1941
  const segs = [];
1902
- const path13 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1903
- for (const seg of path13) {
1942
+ const path14 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1943
+ for (const seg of path14) {
1904
1944
  if (typeof seg === "number")
1905
1945
  segs.push(`[${seg}]`);
1906
1946
  else if (typeof seg === "symbol")
@@ -5128,8 +5168,8 @@ function az_default() {
5128
5168
  }
5129
5169
 
5130
5170
  // ../../../node_modules/zod/v4/locales/be.js
5131
- function getBelarusianPlural(count, one, few, many) {
5132
- const absCount = Math.abs(count);
5171
+ function getBelarusianPlural(count2, one, few, many) {
5172
+ const absCount = Math.abs(count2);
5133
5173
  const lastDigit = absCount % 10;
5134
5174
  const lastTwoDigits = absCount % 100;
5135
5175
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -7207,8 +7247,8 @@ function hu_default() {
7207
7247
  }
7208
7248
 
7209
7249
  // ../../../node_modules/zod/v4/locales/hy.js
7210
- function getArmenianPlural(count, one, many) {
7211
- return Math.abs(count) === 1 ? one : many;
7250
+ function getArmenianPlural(count2, one, many) {
7251
+ return Math.abs(count2) === 1 ? one : many;
7212
7252
  }
7213
7253
  function withDefiniteArticle(word) {
7214
7254
  if (!word)
@@ -9336,8 +9376,8 @@ function ro_default() {
9336
9376
  }
9337
9377
 
9338
9378
  // ../../../node_modules/zod/v4/locales/ru.js
9339
- function getRussianPlural(count, one, few, many) {
9340
- const absCount = Math.abs(count);
9379
+ function getRussianPlural(count2, one, few, many) {
9380
+ const absCount = Math.abs(count2);
9341
9381
  const lastDigit = absCount % 10;
9342
9382
  const lastTwoDigits = absCount % 100;
9343
9383
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -14592,13 +14632,13 @@ function resolveRef(ref, ctx) {
14592
14632
  if (!ref.startsWith("#")) {
14593
14633
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14594
14634
  }
14595
- const path13 = ref.slice(1).split("/").filter(Boolean);
14596
- if (path13.length === 0) {
14635
+ const path14 = ref.slice(1).split("/").filter(Boolean);
14636
+ if (path14.length === 0) {
14597
14637
  return ctx.rootSchema;
14598
14638
  }
14599
14639
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14600
- if (path13[0] === defsKey) {
14601
- const key = path13[1];
14640
+ if (path14[0] === defsKey) {
14641
+ const key = path14[1];
14602
14642
  if (!key || !ctx.defs[key]) {
14603
14643
  throw new Error(`Reference not found: ${ref}`);
14604
14644
  }
@@ -15006,6 +15046,15 @@ function date4(params) {
15006
15046
  // ../../../node_modules/zod/v4/classic/external.js
15007
15047
  config(en_default());
15008
15048
 
15049
+ // ../../shared-contracts/dist/delegation-read.js
15050
+ var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
15051
+ var delegationReadParamsSchema = external_exports.strictObject({
15052
+ threadId: external_exports.string().min(1).max(1024),
15053
+ view: external_exports.enum(["result", "messages"]),
15054
+ cursor: external_exports.string().min(1).max(8192).optional(),
15055
+ limit: external_exports.number().int().min(1).max(100).optional()
15056
+ });
15057
+
15009
15058
  // ../../shared-contracts/dist/credential-imports.js
15010
15059
  var credentialSourceSchema = external_exports.object({
15011
15060
  id: external_exports.string().min(1).max(256),
@@ -15076,6 +15125,153 @@ var harnessDisplaySetSchema = external_exports.strictObject({
15076
15125
  initializeOnly: external_exports.boolean().optional()
15077
15126
  });
15078
15127
 
15128
+ // ../../shared-contracts/dist/model-price-overrides.js
15129
+ var usdPerMillionTokens = external_exports.number().finite().nonnegative();
15130
+ var modelPriceOverrideSchema = external_exports.strictObject({
15131
+ input: usdPerMillionTokens,
15132
+ output: usdPerMillionTokens,
15133
+ cacheRead: usdPerMillionTokens.optional(),
15134
+ cacheWrite: usdPerMillionTokens.optional(),
15135
+ cacheWrite1h: usdPerMillionTokens.optional()
15136
+ });
15137
+ var modelPriceKeySchema = external_exports.string().max(512).refine((key) => key.trim() === key && key.length > 0, "Model ID is required");
15138
+ var modelPriceOverridesSchema = external_exports.strictObject({
15139
+ /** Absolute path of the Host's `pricing.json`. */
15140
+ path: external_exports.string(),
15141
+ entries: external_exports.array(external_exports.strictObject({ key: external_exports.string(), price: modelPriceOverrideSchema })),
15142
+ /** Why the existing file is unusable; the Host then ignores it and refuses to overwrite it. */
15143
+ error: external_exports.string().nullable()
15144
+ });
15145
+ var modelPriceOverridesGetSchema = external_exports.strictObject({});
15146
+ var modelPriceOverridesSetSchema = external_exports.strictObject({
15147
+ key: modelPriceKeySchema,
15148
+ price: modelPriceOverrideSchema.nullable(),
15149
+ previousKey: modelPriceKeySchema.optional()
15150
+ });
15151
+ var modelPriceDefaultParamsSchema = external_exports.strictObject({
15152
+ model: modelPriceKeySchema
15153
+ });
15154
+ var modelPriceSuggestionSchema = external_exports.strictObject({
15155
+ /** Verified from catalog canonical links, not inferred from names or equal prices. */
15156
+ official: external_exports.boolean().optional(),
15157
+ canonicalModelId: external_exports.string().min(1).optional(),
15158
+ provider: external_exports.string().min(1).max(512),
15159
+ model: external_exports.string().min(1).max(512),
15160
+ price: modelPriceOverrideSchema
15161
+ });
15162
+ var modelPriceDefaultResultSchema = external_exports.strictObject({
15163
+ price: modelPriceOverrideSchema.nullable(),
15164
+ /** Local catalog suggestions only; never used automatically for pricing. */
15165
+ suggestions: external_exports.array(modelPriceSuggestionSchema).max(6).optional()
15166
+ });
15167
+
15168
+ // ../../shared-contracts/dist/usage-statistics.js
15169
+ var USAGE_STATISTICS_RANGES = ["today", "7d", "30d", "90d", "all"];
15170
+ var count = external_exports.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
15171
+ var localDate = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/u);
15172
+ var harness = external_exports.string().min(1).max(128);
15173
+ var model = external_exports.string().min(1).max(512);
15174
+ var project = external_exports.string().min(1).max(4096);
15175
+ var usageStatisticsParamsSchema = external_exports.strictObject({
15176
+ range: external_exports.enum(USAGE_STATISTICS_RANGES),
15177
+ harness: harness.optional(),
15178
+ model: model.nullable().optional(),
15179
+ project: project.nullable().optional(),
15180
+ /** One local date inside the range. */
15181
+ date: localDate.optional()
15182
+ });
15183
+ var usageStatisticsTotalsSchema = external_exports.strictObject({
15184
+ requests: count,
15185
+ inputTokens: count,
15186
+ cachedInputTokens: count,
15187
+ cacheWriteInputTokens: count,
15188
+ cacheKnownInputTokens: count,
15189
+ outputTokens: count,
15190
+ reasoningOutputTokens: count,
15191
+ /** USD at the public price, summed over the priced requests only. */
15192
+ costUsd: external_exports.number().finite().min(0),
15193
+ /** Requests without a price (or the cache data the price needs); not in `costUsd`. */
15194
+ unpricedRequests: count,
15195
+ /**
15196
+ * Requests whose storage gave no token counts: counted as requests, with neither tokens nor
15197
+ * cost, and not as unpriced.
15198
+ */
15199
+ unmeteredRequests: count
15200
+ });
15201
+ var totals = usageStatisticsTotalsSchema.shape;
15202
+ var usageStatisticsSessionSchema = external_exports.strictObject({
15203
+ harness,
15204
+ sessionId: external_exports.string().min(1).max(512),
15205
+ project: project.nullable(),
15206
+ /** Models the session used, most requests first. */
15207
+ models: external_exports.array(model).max(16),
15208
+ firstAtMs: count,
15209
+ lastAtMs: count,
15210
+ ...totals
15211
+ });
15212
+ var usageStatisticsResultSchema = external_exports.strictObject({
15213
+ range: external_exports.enum(USAGE_STATISTICS_RANGES),
15214
+ /** First local date of the range; null for all time. */
15215
+ from: localDate.nullable(),
15216
+ to: localDate,
15217
+ /** The filters these figures apply, echoed so a late answer to older filters is recognised. */
15218
+ filters: external_exports.strictObject({
15219
+ harness: harness.nullable(),
15220
+ model: model.nullable(),
15221
+ unknownModel: external_exports.boolean(),
15222
+ project: project.nullable(),
15223
+ unknownProject: external_exports.boolean(),
15224
+ date: localDate.nullable()
15225
+ }),
15226
+ /** Reading of native storage: incomplete while the first read, or a refresh, is under way. */
15227
+ reading: external_exports.strictObject({ complete: external_exports.boolean(), sources: count, read: count }),
15228
+ /** Harnesses whose storage could not be read; their part is missing, the rest is complete. */
15229
+ failures: external_exports.array(external_exports.strictObject({ harness, message: external_exports.string().max(2048) })).max(256),
15230
+ /** Every value seen in the range, ignoring the filters, to choose filters from. */
15231
+ options: external_exports.strictObject({
15232
+ harnesses: external_exports.array(harness).max(256),
15233
+ models: external_exports.array(model.nullable()).max(4096),
15234
+ projects: external_exports.array(project.nullable()).max(4096)
15235
+ }),
15236
+ /** Current display metadata, scoped by Harness. Never a pricing or filter identity.
15237
+ * Optional for older Hosts; missing/conflicting labels fall back to the native model ID.
15238
+ */
15239
+ modelLabels: external_exports.array(external_exports.strictObject({ harness, model, label: model })).max(4096).optional(),
15240
+ /** Native credits, all filters applied, never combined across Harnesses or treated as USD.
15241
+ * Only groups with at least one reported value appear; reportedRequests exposes partial data.
15242
+ */
15243
+ credits: external_exports.array(external_exports.strictObject({
15244
+ harness,
15245
+ model: model.nullable(),
15246
+ credits: external_exports.number().finite().min(0),
15247
+ reportedRequests: count,
15248
+ requests: count
15249
+ })).max(4096).optional(),
15250
+ /** All filters applied. */
15251
+ totals: usageStatisticsTotalsSchema,
15252
+ /** Each date and Harness of the range: every filter except the day. */
15253
+ daily: external_exports.array(external_exports.strictObject({ date: localDate, harness, ...totals })).max(2e5),
15254
+ /** Local weekday (0 = Sunday) and hour, all filters applied. */
15255
+ hourly: external_exports.array(external_exports.strictObject({
15256
+ weekday: external_exports.number().int().min(0).max(6),
15257
+ hour: external_exports.number().int().min(0).max(23),
15258
+ ...totals
15259
+ })).max(168),
15260
+ byHarness: external_exports.array(external_exports.strictObject({ harness, ...totals })).max(256),
15261
+ byModel: external_exports.array(external_exports.strictObject({
15262
+ model: model.nullable(),
15263
+ ...totals,
15264
+ /** Requests priced by what the Harness recorded they cost, not by a price list. */
15265
+ harnessPricedRequests: count
15266
+ })).max(4096),
15267
+ byProject: external_exports.array(external_exports.strictObject({ project: project.nullable(), ...totals })).max(4096),
15268
+ /**
15269
+ * The sessions that spent the most, by cost and by tokens without cache, all filters applied;
15270
+ * requests without a native session are not listed here but count everywhere else.
15271
+ */
15272
+ sessions: external_exports.array(usageStatisticsSessionSchema).max(100)
15273
+ });
15274
+
15079
15275
  // ../../shared-contracts/dist/ids.js
15080
15276
  var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
15081
15277
  message: "Identifier must not be empty or whitespace"
@@ -15097,13 +15293,40 @@ var HARNESS_PLUGIN_LIMIT = 128;
15097
15293
  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);
15098
15294
  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");
15099
15295
  var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
15296
+ var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
15297
+ var harnessInstallationGuideSchema = external_exports.object({
15298
+ commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
15299
+ before: localizedTextSchema.optional(),
15300
+ after: localizedTextSchema.optional(),
15301
+ downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
15302
+ }).strict();
15100
15303
  var pluginPresentationShape = {
15101
15304
  id: harnessPluginIdSchema,
15102
15305
  name: external_exports.string().trim().min(1).max(128),
15103
15306
  version: external_exports.string().min(1).max(128),
15307
+ /** Capability-only plugin; omitted for existing session-capable plugins. */
15308
+ kind: external_exports.literal("usage").optional(),
15309
+ /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
15310
+ iconStyle: external_exports.object({
15311
+ vector: external_exports.object({
15312
+ viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
15313
+ color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
15314
+ paths: external_exports.array(external_exports.object({
15315
+ d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
15316
+ fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
15317
+ fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
15318
+ }).strict()).min(1).max(32)
15319
+ }).strict().optional(),
15320
+ background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
15321
+ borderRadius: external_exports.number().min(0).max(50).optional(),
15322
+ paddingRatio: external_exports.number().min(0).max(0.25).optional()
15323
+ }).strict().optional(),
15324
+ installation: harnessInstallationGuideSchema.optional(),
15325
+ notice: localizedTextSchema.optional(),
15104
15326
  /** The factory accepts a persisted local entrypoint through its construction context. */
15105
15327
  launchCommand: external_exports.literal(true).optional(),
15106
15328
  links: external_exports.object({
15329
+ website: documentationUrlSchema.optional(),
15107
15330
  documentation: documentationUrlSchema.optional(),
15108
15331
  installation: documentationUrlSchema.optional()
15109
15332
  }).strict().optional()
@@ -15180,6 +15403,10 @@ var CONSOLE_HOST_METHODS = Object.freeze([
15180
15403
  "codexhost/account/list",
15181
15404
  "codexhost/account/refresh",
15182
15405
  "codexhost/account/usage/inspect",
15406
+ "codexhost/usage/model-prices/get",
15407
+ "codexhost/usage/model-prices/set",
15408
+ "codexhost/usage/model-prices/default",
15409
+ "codexhost/usage/statistics/get",
15183
15410
  "codexhost/update/check",
15184
15411
  "codexhost/update/start",
15185
15412
  "codexhost/update/status"
@@ -15244,6 +15471,7 @@ var threadUsageSnapshotSchema = external_exports.object({
15244
15471
  cacheWriteInputTokens: nonNegativeSafeIntegerSchema.optional(),
15245
15472
  outputTokens: nonNegativeSafeIntegerSchema.optional(),
15246
15473
  outputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
15474
+ apiOutputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
15247
15475
  reasoningOutputTokens: nonNegativeSafeIntegerSchema.optional(),
15248
15476
  totalTokens: nonNegativeSafeIntegerSchema.optional(),
15249
15477
  totalCostUsd: finiteNonNegativeNumberSchema.optional(),
@@ -15255,7 +15483,11 @@ var threadUsageSnapshotSchema = external_exports.object({
15255
15483
  planFiveHourUsedPercent: cacheHitRatePercentSchema.optional(),
15256
15484
  planFiveHourResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
15257
15485
  planSevenDayUsedPercent: cacheHitRatePercentSchema.optional(),
15258
- planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional()
15486
+ planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
15487
+ sessionCacheHitRatePercent: cacheHitRatePercentSchema.optional(),
15488
+ timeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
15489
+ costSource: external_exports.enum(["publicPrice", "native"]).optional(),
15490
+ unpricedModels: external_exports.array(external_exports.string().min(1)).min(1).optional()
15259
15491
  }).strict().superRefine((usage, context) => {
15260
15492
  if (Object.keys(usage).length === 0) {
15261
15493
  context.addIssue({ code: "custom", message: "Thread Usage must contain a reliable field" });
@@ -15276,6 +15508,20 @@ var threadUsageSnapshotSchema = external_exports.object({
15276
15508
  path: ["contextWindowTokens"]
15277
15509
  });
15278
15510
  }
15511
+ if (usage.costSource !== void 0 && usage.totalCostUsd === void 0) {
15512
+ context.addIssue({
15513
+ code: "custom",
15514
+ message: "Thread Usage costSource must be provided with totalCostUsd",
15515
+ path: ["costSource"]
15516
+ });
15517
+ }
15518
+ if (usage.unpricedModels !== void 0 && usage.costSource !== "publicPrice") {
15519
+ context.addIssue({
15520
+ code: "custom",
15521
+ message: "Thread Usage unpricedModels must be provided with a publicPrice cost",
15522
+ path: ["unpricedModels"]
15523
+ });
15524
+ }
15279
15525
  if (usage.planFiveHourResetsAtUnix !== void 0 && usage.planFiveHourUsedPercent === void 0) {
15280
15526
  context.addIssue({
15281
15527
  code: "custom",
@@ -15545,27 +15791,27 @@ var harnessModelCatalogSchema = external_exports.object({
15545
15791
  }).strict().superRefine((catalog, context) => {
15546
15792
  const refs = /* @__PURE__ */ new Set();
15547
15793
  const thinkingIds = new Set(catalog.thinkingOptions.map(({ id }) => id));
15548
- for (const [index, model] of catalog.models.entries()) {
15549
- if (refs.has(model.ref.id)) {
15794
+ for (const [index, model2] of catalog.models.entries()) {
15795
+ if (refs.has(model2.ref.id)) {
15550
15796
  context.addIssue({
15551
15797
  code: "custom",
15552
15798
  message: "Model Catalog refs must be unique",
15553
15799
  path: ["models", index, "ref", "id"]
15554
15800
  });
15555
15801
  }
15556
- refs.add(model.ref.id);
15557
- if (model.fastModel) {
15558
- if (refs.has(model.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model.fastModel?.id)) {
15802
+ refs.add(model2.ref.id);
15803
+ if (model2.fastModel) {
15804
+ if (refs.has(model2.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model2.fastModel?.id)) {
15559
15805
  context.addIssue({
15560
15806
  code: "custom",
15561
15807
  message: "Fast Model refs must be distinct and unique",
15562
15808
  path: ["models", index, "fastModel"]
15563
15809
  });
15564
15810
  }
15565
- refs.add(model.fastModel.id);
15811
+ refs.add(model2.fastModel.id);
15566
15812
  }
15567
15813
  const supportedThinkingIds = /* @__PURE__ */ new Set();
15568
- for (const [optionIndex, optionId] of (model.supportedThinkingOptionIds ?? []).entries()) {
15814
+ for (const [optionIndex, optionId] of (model2.supportedThinkingOptionIds ?? []).entries()) {
15569
15815
  if (supportedThinkingIds.has(optionId)) {
15570
15816
  context.addIssue({
15571
15817
  code: "custom",
@@ -16159,6 +16405,11 @@ var codexSshDraftSchema = external_exports.strictObject({
16159
16405
  });
16160
16406
  var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action", [
16161
16407
  external_exports.strictObject({ action: external_exports.literal("list") }),
16408
+ external_exports.strictObject({
16409
+ action: external_exports.literal("read-thread"),
16410
+ hostId: hostId.refine((id) => id !== "local"),
16411
+ input: delegationReadParamsSchema
16412
+ }),
16162
16413
  external_exports.strictObject({
16163
16414
  action: external_exports.literal("save"),
16164
16415
  draft: codexSshDraftSchema,
@@ -16290,7 +16541,6 @@ var tokenFields = [
16290
16541
  "cachedInputTokens",
16291
16542
  "cacheWriteInputTokens",
16292
16543
  "outputTokens",
16293
- "outputTokensPerSecond",
16294
16544
  "reasoningOutputTokens",
16295
16545
  "totalTokens",
16296
16546
  "contextWindowTokens",
@@ -16298,10 +16548,12 @@ var tokenFields = [
16298
16548
  ];
16299
16549
  var safeIntegerFields = [
16300
16550
  "planFiveHourResetsAtUnix",
16301
- "planSevenDayResetsAtUnix"
16551
+ "planSevenDayResetsAtUnix",
16552
+ "timeToFirstOutputMs"
16302
16553
  ];
16303
16554
  var percentFields = [
16304
16555
  "cacheHitRatePercent",
16556
+ "sessionCacheHitRatePercent",
16305
16557
  "planFiveHourUsedPercent",
16306
16558
  "planSevenDayUsedPercent"
16307
16559
  ];
@@ -16309,9 +16561,14 @@ var usageFields = /* @__PURE__ */ new Set([
16309
16561
  ...tokenFields,
16310
16562
  ...safeIntegerFields,
16311
16563
  ...percentFields,
16564
+ "sessionCacheUsage",
16312
16565
  "totalCostUsd",
16313
16566
  "totalCredits",
16314
- "contextUsagePercent"
16567
+ "contextUsagePercent",
16568
+ "outputTokensPerSecond",
16569
+ "apiOutputTokensPerSecond",
16570
+ "costSource",
16571
+ "unpricedModels"
16315
16572
  ]);
16316
16573
  function isRecord(value) {
16317
16574
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -16327,7 +16584,11 @@ function parseHostUsage(value) {
16327
16584
  throw new Error(`Harness Usage contains unknown field '${key}'`);
16328
16585
  }
16329
16586
  }
16330
- for (const field of ["totalCredits", "contextUsagePercent"]) {
16587
+ for (const field of [
16588
+ "totalCredits",
16589
+ "contextUsagePercent",
16590
+ "apiOutputTokensPerSecond"
16591
+ ]) {
16331
16592
  const candidate2 = value[field];
16332
16593
  if (candidate2 !== void 0 && (typeof candidate2 !== "number" || !Number.isFinite(candidate2) || candidate2 < 0)) {
16333
16594
  throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
@@ -16363,6 +16624,12 @@ function parseHostUsage(value) {
16363
16624
  throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
16364
16625
  }
16365
16626
  }
16627
+ if (value.sessionCacheUsage !== void 0) {
16628
+ const totals2 = value.sessionCacheUsage;
16629
+ 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) {
16630
+ throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
16631
+ }
16632
+ }
16366
16633
  const hasContextUsed = value.contextUsedTokens !== void 0;
16367
16634
  const hasContextWindow = value.contextWindowTokens !== void 0;
16368
16635
  if (hasContextUsed !== hasContextWindow) {
@@ -16377,8 +16644,217 @@ function parseHostUsage(value) {
16377
16644
  if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
16378
16645
  throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
16379
16646
  }
16647
+ if (value.costSource !== void 0) {
16648
+ if (value.costSource !== "publicPrice" && value.costSource !== "native") {
16649
+ throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
16650
+ }
16651
+ if (value.totalCostUsd === void 0) {
16652
+ throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
16653
+ }
16654
+ }
16655
+ if (value.unpricedModels !== void 0) {
16656
+ const models = value.unpricedModels;
16657
+ if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
16658
+ throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
16659
+ }
16660
+ if (value.costSource !== "publicPrice") {
16661
+ throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
16662
+ }
16663
+ return { ...value, unpricedModels: [...models] };
16664
+ }
16380
16665
  return { ...value };
16381
16666
  }
16667
+ var requestTokenFields = [
16668
+ "inputTokens",
16669
+ "cachedInputTokens",
16670
+ "cacheWriteInputTokens",
16671
+ "cacheWrite1hInputTokens",
16672
+ "outputTokens",
16673
+ "reasoningOutputTokens",
16674
+ "startedAtMs",
16675
+ "completedAtMs"
16676
+ ];
16677
+ var requestFields = /* @__PURE__ */ new Set([
16678
+ ...requestTokenFields,
16679
+ "requestId",
16680
+ "historical",
16681
+ "model",
16682
+ "provider"
16683
+ ]);
16684
+ function parseHostUsageRequest(value) {
16685
+ if (!isRecord(value))
16686
+ throw new Error("Harness Usage request must be an object");
16687
+ for (const key of Object.keys(value)) {
16688
+ if (!requestFields.has(key)) {
16689
+ throw new Error(`Harness Usage request contains unknown field '${key}'`);
16690
+ }
16691
+ }
16692
+ if (typeof value.requestId !== "string" || value.requestId.length === 0) {
16693
+ throw new Error("Harness Usage request 'requestId' must be a non-empty string");
16694
+ }
16695
+ for (const field of ["model", "provider"]) {
16696
+ const candidate2 = value[field];
16697
+ if (candidate2 !== void 0 && (typeof candidate2 !== "string" || candidate2.length === 0)) {
16698
+ throw new Error(`Harness Usage request '${field}' must be a non-empty string`);
16699
+ }
16700
+ }
16701
+ if (value.historical !== void 0 && typeof value.historical !== "boolean") {
16702
+ throw new Error("Harness Usage request 'historical' must be a boolean");
16703
+ }
16704
+ for (const field of requestTokenFields) {
16705
+ const candidate2 = value[field];
16706
+ if (candidate2 !== void 0 && (typeof candidate2 !== "number" || !Number.isSafeInteger(candidate2) || candidate2 < 0)) {
16707
+ throw new Error(`Harness Usage request '${field}' must be a non-negative safe integer`);
16708
+ }
16709
+ }
16710
+ if (value.inputTokens === void 0 || value.outputTokens === void 0) {
16711
+ throw new Error("Harness Usage request must contain 'inputTokens' and 'outputTokens'");
16712
+ }
16713
+ const request = value;
16714
+ if ((request.cachedInputTokens ?? 0) + (request.cacheWriteInputTokens ?? 0) > request.inputTokens) {
16715
+ throw new Error("Harness Usage request cache Tokens must not exceed 'inputTokens'");
16716
+ }
16717
+ if ((request.reasoningOutputTokens ?? 0) > request.outputTokens) {
16718
+ throw new Error("Harness Usage request 'reasoningOutputTokens' must not exceed 'outputTokens'");
16719
+ }
16720
+ if (request.cacheWrite1hInputTokens !== void 0 && request.cacheWrite1hInputTokens > (request.cacheWriteInputTokens ?? -1)) {
16721
+ throw new Error("Harness Usage request 'cacheWrite1hInputTokens' must not exceed 'cacheWriteInputTokens'");
16722
+ }
16723
+ if (request.startedAtMs === void 0 !== (request.completedAtMs === void 0)) {
16724
+ throw new Error("Harness Usage request timing fields must be provided together");
16725
+ }
16726
+ if (request.startedAtMs !== void 0 && request.completedAtMs !== void 0 && request.completedAtMs < request.startedAtMs) {
16727
+ throw new Error("Harness Usage request 'completedAtMs' must not precede 'startedAtMs'");
16728
+ }
16729
+ return { ...request };
16730
+ }
16731
+
16732
+ // dist/v2/usage.js
16733
+ function v2UsageRequest(message, historical, firstOutputAtMs) {
16734
+ if (message.type !== "assistant" || !message.tokens)
16735
+ return null;
16736
+ const { input, output, reasoning, cache } = message.tokens;
16737
+ const { streamed } = message.time;
16738
+ return parseHostUsageRequest({
16739
+ requestId: message.id,
16740
+ ...historical ? { historical: true } : {},
16741
+ model: message.model.id,
16742
+ // Built-in OpenCode providers use models.dev IDs. A custom provider ID matches no price
16743
+ // entry, so Host falls back to the exact model ID.
16744
+ provider: message.model.providerID,
16745
+ inputTokens: input + cache.read + cache.write,
16746
+ cachedInputTokens: cache.read,
16747
+ cacheWriteInputTokens: cache.write,
16748
+ outputTokens: output + reasoning,
16749
+ reasoningOutputTokens: reasoning,
16750
+ // End at stream completion, not step completion, which can include tool execution.
16751
+ // Without a native stream end, keep the usage but do not guess its generation duration.
16752
+ ...!historical && firstOutputAtMs !== void 0 && streamed !== void 0 && streamed >= firstOutputAtMs ? { startedAtMs: firstOutputAtMs, completedAtMs: streamed } : {}
16753
+ });
16754
+ }
16755
+
16756
+ // dist/usage-statistics.js
16757
+ function parseRowData(data) {
16758
+ try {
16759
+ return JSON.parse(String(data));
16760
+ } catch {
16761
+ return null;
16762
+ }
16763
+ }
16764
+ function isRecord2(value) {
16765
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16766
+ }
16767
+ function openCodeDatabasePath(environment) {
16768
+ const home = environment.HOME || environment.USERPROFILE || os2.homedir();
16769
+ const directory = path5.join(environment.XDG_DATA_HOME || path5.join(home, ".local", "share"), "opencode");
16770
+ const configured = environment.OPENCODE_DB;
16771
+ if (configured === ":memory:")
16772
+ return null;
16773
+ return configured ? path5.resolve(directory, configured) : path5.join(directory, "opencode.db");
16774
+ }
16775
+ async function fingerprint(file2) {
16776
+ const info = await lstat(file2).catch(() => null);
16777
+ if (!info?.isFile())
16778
+ return null;
16779
+ const wal = await lstat(`${file2}-wal`).catch(() => null);
16780
+ return `${info.ino}:${info.size}:${info.mtimeMs}:${wal ? `${wal.size}:${wal.mtimeMs}` : "-"}`;
16781
+ }
16782
+ async function readOpenCodeUsage(file2) {
16783
+ const { DatabaseSync } = await import("node:sqlite");
16784
+ const database = new DatabaseSync(file2, { readOnly: true });
16785
+ try {
16786
+ const tables = new Set(database.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => String(row.name)));
16787
+ const directories = /* @__PURE__ */ new Map();
16788
+ for (const table of ["session", "session_v2"]) {
16789
+ if (!tables.has(table))
16790
+ continue;
16791
+ for (const row of database.prepare(`SELECT id, directory FROM ${table}`).iterate()) {
16792
+ if (typeof row.directory === "string")
16793
+ directories.set(String(row.id), row.directory);
16794
+ }
16795
+ }
16796
+ const entries = /* @__PURE__ */ new Map();
16797
+ const add = (message, createdAtMs, session) => {
16798
+ let request;
16799
+ try {
16800
+ request = v2UsageRequest(message, true);
16801
+ } catch {
16802
+ return;
16803
+ }
16804
+ const at = nativeTimeMs(createdAtMs);
16805
+ const entry = request && at !== null && usageEntryFromRequest(request, at);
16806
+ if (entry && !entries.has(entry.id)) {
16807
+ const sessionId = typeof session === "string" ? session : void 0;
16808
+ entries.set(entry.id, withUsageSession(entry, {
16809
+ sessionId,
16810
+ cwd: sessionId === void 0 ? void 0 : directories.get(sessionId)
16811
+ }));
16812
+ }
16813
+ };
16814
+ if (tables.has("session_message")) {
16815
+ for (const row of database.prepare("SELECT id, session_id, data FROM session_message WHERE type = 'assistant'").iterate()) {
16816
+ const data = parseRowData(row.data);
16817
+ if (!isRecord2(data))
16818
+ continue;
16819
+ add({ ...data, id: String(row.id), type: "assistant" }, isRecord2(data.time) ? data.time.created : void 0, row.session_id);
16820
+ }
16821
+ }
16822
+ const migrated = tables.has("kv") && /"phase"\s*:\s*"completed"/u.test(String(database.prepare("SELECT value FROM kv WHERE key = 'migration.v1-v2'").get()?.value ?? ""));
16823
+ if (tables.has("message") && !migrated) {
16824
+ for (const row of database.prepare("SELECT id, session_id, data FROM message").iterate()) {
16825
+ const data = parseRowData(row.data);
16826
+ if (!isRecord2(data) || data.role !== "assistant" || typeof data.modelID !== "string") {
16827
+ continue;
16828
+ }
16829
+ add({
16830
+ id: String(row.id),
16831
+ type: "assistant",
16832
+ model: { id: data.modelID, providerID: data.providerID },
16833
+ tokens: data.tokens,
16834
+ time: data.time
16835
+ }, isRecord2(data.time) ? data.time.created : void 0, row.session_id);
16836
+ }
16837
+ }
16838
+ return [...entries.values()];
16839
+ } finally {
16840
+ database.close();
16841
+ }
16842
+ }
16843
+ function createOpenCodeUsageStatistics(environment) {
16844
+ return Object.freeze({
16845
+ async listSources() {
16846
+ const file2 = openCodeDatabasePath(environment);
16847
+ const stamp = file2 ? await fingerprint(file2) : null;
16848
+ return file2 && stamp ? [{ id: file2, fingerprint: stamp }] : [];
16849
+ },
16850
+ readSource: (id) => readOpenCodeUsage(id)
16851
+ });
16852
+ }
16853
+
16854
+ // dist/opencode-adapter.js
16855
+ import { randomUUID } from "node:crypto";
16856
+ import fs4 from "node:fs";
16857
+ import path9 from "node:path";
16382
16858
 
16383
16859
  // dist/model-catalog.js
16384
16860
  import { Buffer as Buffer2 } from "node:buffer";
@@ -16389,10 +16865,10 @@ function assertNonBlank(value, label) {
16389
16865
  if (!value.trim())
16390
16866
  throw new Error(`OpenCode ${label} must not be empty`);
16391
16867
  }
16392
- function encodeOpenCodeModelRef(model) {
16393
- assertNonBlank(model.providerID, "Provider ID");
16394
- assertNonBlank(model.modelID, "Model ID");
16395
- const encoded = Buffer2.from(JSON.stringify([model.providerID, model.modelID]), "utf8").toString("base64url");
16868
+ function encodeOpenCodeModelRef(model2) {
16869
+ assertNonBlank(model2.providerID, "Provider ID");
16870
+ assertNonBlank(model2.modelID, "Model ID");
16871
+ const encoded = Buffer2.from(JSON.stringify([model2.providerID, model2.modelID]), "utf8").toString("base64url");
16396
16872
  const id = `${MODEL_REF_PREFIX}${encoded}`;
16397
16873
  if (id.length > HARNESS_MODEL_REF_MAX_LENGTH) {
16398
16874
  throw new Error("OpenCode Model identity is too long for a Model Ref");
@@ -16450,26 +16926,26 @@ function compareText(left, right) {
16450
16926
  }
16451
16927
  function modelsForConnectedProviders(catalog) {
16452
16928
  const connected = new Set(catalog.connected);
16453
- return catalog.all.flatMap((provider) => connected.has(provider.id) ? Object.values(provider.models).map((model) => ({ provider, model })) : []);
16929
+ return catalog.all.flatMap((provider) => connected.has(provider.id) ? Object.values(provider.models).map((model2) => ({ provider, model: model2 })) : []);
16454
16930
  }
16455
16931
  function normalizeOpenCodeModelCatalog(catalog) {
16456
16932
  const nativeModels = modelsForConnectedProviders(catalog);
16457
16933
  const variants = /* @__PURE__ */ new Set();
16458
- for (const { model } of nativeModels) {
16459
- for (const variant of Object.keys(model.variants ?? {}))
16934
+ for (const { model: model2 } of nativeModels) {
16935
+ for (const variant of Object.keys(model2.variants ?? {}))
16460
16936
  variants.add(variant);
16461
16937
  }
16462
16938
  const thinkingOptions = [
16463
16939
  variantOption(void 0),
16464
16940
  ...[...variants].sort(compareText).map((variant) => variantOption(variant))
16465
16941
  ];
16466
- const models = nativeModels.map(({ provider, model }) => ({
16467
- ref: encodeOpenCodeModelRef({ providerID: provider.id, modelID: model.id }),
16468
- label: `${provider.name} / ${model.name}`,
16469
- resolvedModelLabel: `${provider.id}/${model.id}`,
16942
+ const models = nativeModels.map(({ provider, model: model2 }) => ({
16943
+ ref: encodeOpenCodeModelRef({ providerID: provider.id, modelID: model2.id }),
16944
+ label: `${provider.name} / ${model2.name}`,
16945
+ resolvedModelLabel: `${provider.id}/${model2.id}`,
16470
16946
  supportedThinkingOptionIds: [
16471
16947
  DEFAULT_VARIANT_ID,
16472
- ...Object.keys(model.variants ?? {}).sort(compareText).map(encodeOpenCodeVariant)
16948
+ ...Object.keys(model2.variants ?? {}).sort(compareText).map(encodeOpenCodeVariant)
16473
16949
  ]
16474
16950
  })).sort((left, right) => compareText(left.label, right.label) || compareText(left.ref.id, right.ref.id));
16475
16951
  const defaultNative = catalog.connected.map((providerID) => ({ providerID, modelID: catalog.default[providerID] })).find((candidate2) => typeof candidate2.modelID === "string" && candidate2.modelID.length > 0);
@@ -16481,9 +16957,9 @@ function normalizeOpenCodeModelCatalog(catalog) {
16481
16957
  defaultThinkingOptionId: DEFAULT_VARIANT_ID
16482
16958
  });
16483
16959
  }
16484
- function openCodeContextWindow(catalog, model) {
16485
- const provider = catalog.all.find(({ id }) => id === model.providerID);
16486
- const context = provider?.models[model.modelID]?.limit.context;
16960
+ function openCodeContextWindow(catalog, model2) {
16961
+ const provider = catalog.all.find(({ id }) => id === model2.providerID);
16962
+ const context = provider?.models[model2.modelID]?.limit.context;
16487
16963
  return typeof context === "number" && Number.isSafeInteger(context) && context > 0 ? context : void 0;
16488
16964
  }
16489
16965
 
@@ -16806,7 +17282,7 @@ import { spawn, spawnSync } from "node:child_process";
16806
17282
  import fs2 from "node:fs";
16807
17283
  import { createServer } from "node:net";
16808
17284
  import { homedir as homedir2, tmpdir as tmpdir2 } from "node:os";
16809
- import path6 from "node:path";
17285
+ import path7 from "node:path";
16810
17286
 
16811
17287
  // ../../../node_modules/@opencode-ai/sdk/dist/v2/gen/core/serverSentEvents.gen.js
16812
17288
  var createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url: url2, ...options }) => {
@@ -17032,7 +17508,7 @@ var serializeObjectParam = ({ allowReserved, explode, name, style, value, valueO
17032
17508
 
17033
17509
  // ../../../node_modules/@opencode-ai/sdk/dist/v2/gen/core/utils.gen.js
17034
17510
  var PATH_PARAM_RE = /\{[^{}]+\}/g;
17035
- var defaultPathSerializer = ({ path: path13, url: _url2 }) => {
17511
+ var defaultPathSerializer = ({ path: path14, url: _url2 }) => {
17036
17512
  let url2 = _url2;
17037
17513
  const matches = _url2.match(PATH_PARAM_RE);
17038
17514
  if (matches) {
@@ -17051,7 +17527,7 @@ var defaultPathSerializer = ({ path: path13, url: _url2 }) => {
17051
17527
  name = name.substring(1);
17052
17528
  style = "matrix";
17053
17529
  }
17054
- const value = path13[name];
17530
+ const value = path14[name];
17055
17531
  if (value === void 0 || value === null) {
17056
17532
  continue;
17057
17533
  }
@@ -17082,11 +17558,11 @@ var defaultPathSerializer = ({ path: path13, url: _url2 }) => {
17082
17558
  }
17083
17559
  return url2;
17084
17560
  };
17085
- var getUrl = ({ baseUrl, path: path13, query, querySerializer, url: _url2 }) => {
17561
+ var getUrl = ({ baseUrl, path: path14, query, querySerializer, url: _url2 }) => {
17086
17562
  const pathUrl = _url2.startsWith("/") ? _url2 : `/${_url2}`;
17087
17563
  let url2 = (baseUrl ?? "") + pathUrl;
17088
- if (path13) {
17089
- url2 = defaultPathSerializer({ path: path13, url: url2 });
17564
+ if (path14) {
17565
+ url2 = defaultPathSerializer({ path: path14, url: url2 });
17090
17566
  }
17091
17567
  let search = query ? querySerializer(query) : "";
17092
17568
  if (search.startsWith("?")) {
@@ -22209,7 +22685,7 @@ function createOpencodeClient(config2) {
22209
22685
  }
22210
22686
 
22211
22687
  // dist/command.js
22212
- import path5 from "node:path";
22688
+ import path6 from "node:path";
22213
22689
  var OpenCodeExecutableError = class extends Error {
22214
22690
  code = "OPENCODE_NOT_FOUND";
22215
22691
  constructor(message = "OpenCode CLI is not installed") {
@@ -22243,7 +22719,7 @@ function resolveOpenCodeExecutable(input = {}, dependencies = {}) {
22243
22719
  }, dependencies);
22244
22720
  if (!resolution)
22245
22721
  throw new OpenCodeExecutableError();
22246
- return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path5.resolve(resolution.executable);
22722
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path6.resolve(resolution.executable);
22247
22723
  }
22248
22724
  function openCodeServerInvocation(executable, environment, platform = process.platform, port = 0) {
22249
22725
  return commandInvocation(executable, ["serve", "--hostname=127.0.0.1", `--port=${port}`], environment, platform);
@@ -22271,14 +22747,14 @@ function freeLoopbackPort() {
22271
22747
  });
22272
22748
  });
22273
22749
  }
22274
- function isRecord2(value) {
22750
+ function isRecord3(value) {
22275
22751
  return typeof value === "object" && value !== null && !Array.isArray(value);
22276
22752
  }
22277
22753
  function errorText(error51) {
22278
22754
  return error51 instanceof Error ? error51.message : String(error51);
22279
22755
  }
22280
22756
  function isMissingExecutable(error51) {
22281
- return isRecord2(error51) && error51.code === "ENOENT";
22757
+ return isRecord3(error51) && error51.code === "ENOENT";
22282
22758
  }
22283
22759
  function classifySdkError(error51, operation) {
22284
22760
  if (error51 instanceof OpenCodeTransportError)
@@ -22333,14 +22809,14 @@ function signalProcessTree(child, signal) {
22333
22809
  try {
22334
22810
  process.kill(-child.pid, signal);
22335
22811
  } catch (error51) {
22336
- if (!isRecord2(error51) || error51.code !== "ESRCH")
22812
+ if (!isRecord3(error51) || error51.code !== "ESRCH")
22337
22813
  throw error51;
22338
22814
  }
22339
22815
  }
22340
22816
  function safeOpenCodeServerCwd(environment) {
22341
22817
  const candidates = [environment.USERPROFILE, environment.HOME, homedir2(), tmpdir2()];
22342
22818
  for (const candidate2 of candidates) {
22343
- if (!candidate2 || !path6.isAbsolute(candidate2))
22819
+ if (!candidate2 || !path7.isAbsolute(candidate2))
22344
22820
  continue;
22345
22821
  try {
22346
22822
  if (!fs2.statSync(candidate2).isDirectory())
@@ -22364,7 +22840,7 @@ function managedOpenCodeEnvironment(environment, executionPolicy = "default") {
22364
22840
  if (existing !== void 0) {
22365
22841
  try {
22366
22842
  const parsed = JSON.parse(existing);
22367
- if (!isRecord2(parsed))
22843
+ if (!isRecord3(parsed))
22368
22844
  throw new Error("OpenCode config content must be an object");
22369
22845
  config2 = { ...parsed };
22370
22846
  } catch (error51) {
@@ -22687,11 +23163,11 @@ var SdkOpenCodeTransport = class {
22687
23163
  parts: [{ type: "text", text: input.text }]
22688
23164
  }), this.#commandTimeoutMs, "OpenCode prompt admission"), "prompt admission");
22689
23165
  }
22690
- async summarize(sessionID, model) {
23166
+ async summarize(sessionID, model2) {
22691
23167
  const client2 = await this.#getClient();
22692
23168
  responseData2(await withTimeout2(client2.session.summarize({
22693
23169
  sessionID,
22694
- ...model ? { providerID: model.providerID, modelID: model.modelID } : {}
23170
+ ...model2 ? { providerID: model2.providerID, modelID: model2.modelID } : {}
22695
23171
  }), this.#commandTimeoutMs, "OpenCode context compaction"), "context compaction");
22696
23172
  }
22697
23173
  async abort(sessionID) {
@@ -22789,7 +23265,7 @@ var SdkOpenCodeTransport = class {
22789
23265
 
22790
23266
  // dist/file-change-verification.js
22791
23267
  import fs3 from "node:fs";
22792
- import path7 from "node:path";
23268
+ import path8 from "node:path";
22793
23269
  function missingPath(error51) {
22794
23270
  if (!error51 || typeof error51 !== "object")
22795
23271
  return false;
@@ -22801,33 +23277,33 @@ function hasDotPathSegment(value) {
22801
23277
  return segments.some((segment) => segment === "." || segment === "..");
22802
23278
  }
22803
23279
  function canonicalDirectoryPath(value) {
22804
- let candidate2 = path7.resolve(value);
23280
+ let candidate2 = path8.resolve(value);
22805
23281
  const missingSegments = [];
22806
23282
  for (; ; ) {
22807
23283
  try {
22808
- return path7.join(fs3.realpathSync.native(candidate2), ...missingSegments);
23284
+ return path8.join(fs3.realpathSync.native(candidate2), ...missingSegments);
22809
23285
  } catch (error51) {
22810
23286
  if (!missingPath(error51))
22811
23287
  return void 0;
22812
- const parent = path7.dirname(candidate2);
23288
+ const parent = path8.dirname(candidate2);
22813
23289
  if (parent === candidate2)
22814
23290
  return void 0;
22815
- missingSegments.unshift(path7.basename(candidate2));
23291
+ missingSegments.unshift(path8.basename(candidate2));
22816
23292
  candidate2 = parent;
22817
23293
  }
22818
23294
  }
22819
23295
  }
22820
23296
  function canonicalFilePath(value) {
22821
- const absolute = path7.resolve(value);
22822
- const parent = canonicalDirectoryPath(path7.dirname(absolute));
22823
- return parent ? path7.join(parent, path7.basename(absolute)) : void 0;
23297
+ const absolute = path8.resolve(value);
23298
+ const parent = canonicalDirectoryPath(path8.dirname(absolute));
23299
+ return parent ? path8.join(parent, path8.basename(absolute)) : void 0;
22824
23300
  }
22825
23301
  function pathIsWithin(root, candidate2, allowRoot) {
22826
- const relative = path7.relative(root, candidate2);
22827
- return allowRoot && relative === "" || relative !== "" && relative !== ".." && !relative.startsWith(`..${path7.sep}`) && !path7.isAbsolute(relative);
23302
+ const relative = path8.relative(root, candidate2);
23303
+ return allowRoot && relative === "" || relative !== "" && relative !== ".." && !relative.startsWith(`..${path8.sep}`) && !path8.isAbsolute(relative);
22828
23304
  }
22829
23305
  function verifiedOpenCodeWorktree(sessionDirectory, paths) {
22830
- if (!paths || typeof paths !== "object" || typeof sessionDirectory !== "string" || typeof paths.directory !== "string" || typeof paths.worktree !== "string" || hasDotPathSegment(sessionDirectory) || hasDotPathSegment(paths.directory) || hasDotPathSegment(paths.worktree) || !path7.isAbsolute(sessionDirectory) || !path7.isAbsolute(paths.directory) || !path7.isAbsolute(paths.worktree)) {
23306
+ if (!paths || typeof paths !== "object" || typeof sessionDirectory !== "string" || typeof paths.directory !== "string" || typeof paths.worktree !== "string" || hasDotPathSegment(sessionDirectory) || hasDotPathSegment(paths.directory) || hasDotPathSegment(paths.worktree) || !path8.isAbsolute(sessionDirectory) || !path8.isAbsolute(paths.directory) || !path8.isAbsolute(paths.worktree)) {
22831
23307
  return void 0;
22832
23308
  }
22833
23309
  const session = canonicalDirectoryPath(sessionDirectory);
@@ -22839,10 +23315,10 @@ function verifiedOpenCodeWorktree(sessionDirectory, paths) {
22839
23315
  return worktree;
22840
23316
  }
22841
23317
  function openCodeFileIdentity(file2, worktree) {
22842
- if (typeof file2 !== "string" || typeof worktree !== "string" || hasDotPathSegment(file2) || hasDotPathSegment(worktree) || !path7.isAbsolute(worktree) || !file2 || file2.includes("\0") || file2.includes("\n") || file2.includes("\r")) {
23318
+ if (typeof file2 !== "string" || typeof worktree !== "string" || hasDotPathSegment(file2) || hasDotPathSegment(worktree) || !path8.isAbsolute(worktree) || !file2 || file2.includes("\0") || file2.includes("\n") || file2.includes("\r")) {
22843
23319
  return void 0;
22844
23320
  }
22845
- const candidate2 = canonicalFilePath(path7.isAbsolute(file2) ? file2 : path7.resolve(worktree, file2));
23321
+ const candidate2 = canonicalFilePath(path8.isAbsolute(file2) ? file2 : path8.resolve(worktree, file2));
22846
23322
  return candidate2 && pathIsWithin(worktree, candidate2, false) ? candidate2 : void 0;
22847
23323
  }
22848
23324
 
@@ -22899,12 +23375,12 @@ function storedSelection(session) {
22899
23375
  }
22900
23376
  return { providerID, modelID, ...typeof variant === "string" ? { variant } : {} };
22901
23377
  }
22902
- function selectionMetadata(session, model, variant) {
23378
+ function selectionMetadata(session, model2, variant) {
22903
23379
  return {
22904
23380
  ...session.metadata,
22905
23381
  [SELECTION_METADATA_KEY]: {
22906
- providerID: model.providerID,
22907
- modelID: model.modelID,
23382
+ providerID: model2.providerID,
23383
+ modelID: model2.modelID,
22908
23384
  ...variant ? { variant } : {}
22909
23385
  }
22910
23386
  };
@@ -23000,17 +23476,17 @@ async function readProjection(transport, sessionID, providerCatalog, toolOutputL
23000
23476
  diffsByUserMessageId: new Map(diffEntries),
23001
23477
  toolOutputLimit
23002
23478
  });
23003
- const model = nativeModelFromSession(session, messages);
23479
+ const model2 = nativeModelFromSession(session, messages);
23004
23480
  const nativeVariant = nativeVariantFromSession(session, messages);
23005
- const nativeModel = model ? providerCatalog.all.find(({ id }) => id === model.providerID)?.models[model.modelID] : void 0;
23481
+ const nativeModel = model2 ? providerCatalog.all.find(({ id }) => id === model2.providerID)?.models[model2.modelID] : void 0;
23006
23482
  const variant = nativeVariant === "default" && nativeModel && !Object.hasOwn(nativeModel.variants ?? {}, "default") ? void 0 : nativeVariant;
23007
- const usage = projectOpenCodeUsage(openCodeAssistantMessages(session, messages), model ? openCodeContextWindow(providerCatalog, model) : void 0);
23483
+ const usage = projectOpenCodeUsage(openCodeAssistantMessages(session, messages), model2 ? openCodeContextWindow(providerCatalog, model2) : void 0);
23008
23484
  return {
23009
23485
  session,
23010
23486
  messages,
23011
23487
  snapshot,
23012
23488
  usage,
23013
- ...model ? { model } : {},
23489
+ ...model2 ? { model: model2 } : {},
23014
23490
  ...variant ? { variant } : {}
23015
23491
  };
23016
23492
  }
@@ -23136,13 +23612,13 @@ function sameCwd(left, right) {
23136
23612
  try {
23137
23613
  return fs4.realpathSync.native(value);
23138
23614
  } catch {
23139
- return path8.resolve(value);
23615
+ return path9.resolve(value);
23140
23616
  }
23141
23617
  };
23142
23618
  return canonical(left) === canonical(right);
23143
23619
  }
23144
- function sessionState(session, modelCatalog, model, variant, executionPolicy = "default", permissionModeId = OPENCODE_DEFAULT_PERMISSION_MODE_ID) {
23145
- const effectiveModel = model ? encodeOpenCodeModelRef(model) : void 0;
23620
+ function sessionState(session, modelCatalog, model2, variant, executionPolicy = "default", permissionModeId = OPENCODE_DEFAULT_PERMISSION_MODE_ID) {
23621
+ const effectiveModel = model2 ? encodeOpenCodeModelRef(model2) : void 0;
23146
23622
  const modelEntry = effectiveModel ? modelCatalog.models.find(({ ref }) => ref.id === effectiveModel.id) : void 0;
23147
23623
  const availableThinkingOptions = modelEntry?.supportedThinkingOptionIds?.map((id) => modelCatalog.thinkingOptions.find((option) => option.id === id)).filter((option) => Boolean(option));
23148
23624
  const effectiveThinkingOptionId = encodeOpenCodeVariant(variant);
@@ -23549,8 +24025,8 @@ var OpenCodeHarnessSession = class {
23549
24025
  };
23550
24026
  }
23551
24027
  const modelRef = this.#model ? encodeOpenCodeModelRef(this.#model) : void 0;
23552
- const model = modelRef ? this.#modelCatalog.models.find(({ ref }) => ref.id === modelRef.id) : void 0;
23553
- if (!model?.supportedThinkingOptionIds?.includes(command.thinkingOptionId)) {
24028
+ const model2 = modelRef ? this.#modelCatalog.models.find(({ ref }) => ref.id === modelRef.id) : void 0;
24029
+ if (!model2?.supportedThinkingOptionIds?.includes(command.thinkingOptionId)) {
23554
24030
  return {
23555
24031
  ok: false,
23556
24032
  error: {
@@ -24400,14 +24876,14 @@ var OpenCodeAdapter = class {
24400
24876
  const modelCatalog = normalizeOpenCodeModelCatalog(providers);
24401
24877
  let session;
24402
24878
  if (input.kind === "create") {
24403
- const model = input.model ? decodeOpenCodeModelRef(input.model) : void 0;
24879
+ const model2 = input.model ? decodeOpenCodeModelRef(input.model) : void 0;
24404
24880
  const variant = input.thinkingOptionId ? decodeOpenCodeVariant(input.thinkingOptionId) : void 0;
24405
24881
  if (input.model && !modelCatalog.models.some(({ ref }) => ref.id === input.model?.id)) {
24406
24882
  throw new OpenCodeTransportError("protocolError", "Requested OpenCode Model is absent from the connected Provider catalog");
24407
24883
  }
24408
24884
  const permission = requestedPermissionMode && requestedPermissionMode !== "default" ? requestedPermissionRules(void 0, requestedPermissionMode) : void 0;
24409
24885
  session = await transport.createSession({
24410
- ...model ? { model } : {},
24886
+ ...model2 ? { model: model2 } : {},
24411
24887
  ...variant ? { variant } : {},
24412
24888
  ...permission ? { permission } : {}
24413
24889
  });
@@ -24522,7 +24998,7 @@ import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
24522
24998
 
24523
24999
  // dist/v2/state.js
24524
25000
  import fs5 from "node:fs";
24525
- import path9 from "node:path";
25001
+ import path10 from "node:path";
24526
25002
  var harnessId = harnessIdSchema.parse("opencode");
24527
25003
  function failure(message, code = "nativeFailure") {
24528
25004
  return {
@@ -24542,7 +25018,7 @@ function sameDirectory(left, right) {
24542
25018
  try {
24543
25019
  return fs5.realpathSync(value);
24544
25020
  } catch {
24545
- return path9.resolve(value);
25021
+ return path10.resolve(value);
24546
25022
  }
24547
25023
  };
24548
25024
  return canonical(left) === canonical(right);
@@ -24564,17 +25040,17 @@ function v2Locator(ref) {
24564
25040
  return { directory: locator.directory, executionPolicy: locator.executionPolicy };
24565
25041
  }
24566
25042
  function v2Catalog(models, defaultModel) {
24567
- const enabled = models.filter((model) => model.enabled);
24568
- const variants = [...new Set(enabled.flatMap((model) => model.variants.map((v) => v.id)))].sort();
24569
- const ref = (model) => encodeOpenCodeModelRef({ providerID: model.providerID, modelID: model.id });
25043
+ const enabled = models.filter((model2) => model2.enabled);
25044
+ const variants = [...new Set(enabled.flatMap((model2) => model2.variants.map((v) => v.id)))].sort();
25045
+ const ref = (model2) => encodeOpenCodeModelRef({ providerID: model2.providerID, modelID: model2.id });
24570
25046
  return harnessModelCatalogSchema.parse({
24571
- models: enabled.map((model) => ({
24572
- ref: ref(model),
24573
- label: `${model.providerID} / ${model.name}`,
24574
- resolvedModelLabel: `${model.providerID}/${model.id}`,
25047
+ models: enabled.map((model2) => ({
25048
+ ref: ref(model2),
25049
+ label: `${model2.providerID} / ${model2.name}`,
25050
+ resolvedModelLabel: `${model2.providerID}/${model2.id}`,
24575
25051
  supportedThinkingOptionIds: [
24576
25052
  encodeOpenCodeVariant(void 0),
24577
- ...model.variants.map((v) => encodeOpenCodeVariant(v.id))
25053
+ ...model2.variants.map((v) => encodeOpenCodeVariant(v.id))
24578
25054
  ]
24579
25055
  })),
24580
25056
  ...defaultModel && enabled.some((m) => ref(m).id === ref(defaultModel).id) ? { defaultModel: ref(defaultModel) } : {},
@@ -24591,12 +25067,12 @@ function v2Permissions(current = [], mode) {
24591
25067
  return selected === "default" ? rules : [...rules, { action: "*", resource: "*", effect: selected }];
24592
25068
  }
24593
25069
  function v2State(session, catalog, policy) {
24594
- const model = session.model ? encodeOpenCodeModelRef({ providerID: session.model.providerID, modelID: session.model.id }) : void 0;
24595
- const entry = catalog.models.find((candidate2) => candidate2.ref.id === model?.id);
25070
+ const model2 = session.model ? encodeOpenCodeModelRef({ providerID: session.model.providerID, modelID: session.model.id }) : void 0;
25071
+ const entry = catalog.models.find((candidate2) => candidate2.ref.id === model2?.id);
24596
25072
  const mode = session.permissions?.findLast((rule) => rule.action === "*" && rule.resource === "*");
24597
25073
  return {
24598
25074
  nativeRef: v2Ref(session, policy),
24599
- ...model ? { effectiveModel: model } : {},
25075
+ ...model2 ? { effectiveModel: model2 } : {},
24600
25076
  ...entry ? {
24601
25077
  resolvedModelLabel: entry.resolvedModelLabel ?? entry.label,
24602
25078
  availableThinkingOptions: catalog.thinkingOptions.filter((v) => entry.supportedThinkingOptionIds?.includes(v.id)),
@@ -26457,7 +26933,7 @@ var V2Connection = class {
26457
26933
  };
26458
26934
 
26459
26935
  // dist/v2/history.js
26460
- import path10 from "node:path";
26936
+ import path11 from "node:path";
26461
26937
  async function readMessages(client2, sessionID) {
26462
26938
  const messages = [];
26463
26939
  let cursor;
@@ -26476,11 +26952,12 @@ async function readMessages(client2, sessionID) {
26476
26952
  } while (cursor);
26477
26953
  return messages;
26478
26954
  }
26479
- var contentId = (messageID, index) => hostItemIdSchema.parse(`${messageID}:${index}`);
26955
+ var contentId = (messageID, type, ordinal) => hostItemIdSchema.parse(`${messageID}:${type}:${ordinal}`);
26480
26956
  function assistantItems2(message, limit) {
26481
- return message.content.map((part, index) => {
26482
- const itemId2 = contentId(message.id, index);
26957
+ const ordinals = { text: 0, reasoning: 0 };
26958
+ return message.content.map((part) => {
26483
26959
  if (part.type === "text" || part.type === "reasoning") {
26960
+ const itemId2 = contentId(message.id, part.type, ordinals[part.type]++);
26484
26961
  return {
26485
26962
  item: {
26486
26963
  type: part.type === "text" ? "agentMessage" : "reasoning",
@@ -26495,7 +26972,7 @@ function assistantItems2(message, limit) {
26495
26972
  return {
26496
26973
  item: {
26497
26974
  type: "toolExecution",
26498
- itemId: itemId2,
26975
+ itemId: hostItemIdSchema.parse(`${message.id}:tool:${part.id}`),
26499
26976
  toolName: part.name,
26500
26977
  namespace: "opencode",
26501
26978
  arguments: typeof state.input === "string" ? state.input : state.input,
@@ -26582,9 +27059,9 @@ function fileChanges(session, turn, diffs) {
26582
27059
  if (!diffs.length)
26583
27060
  return void 0;
26584
27061
  const changes = diffs.map((diff) => {
26585
- const absolute = path10.resolve(session.location.directory, diff.file);
26586
- const relative = path10.relative(session.location.directory, absolute);
26587
- if (relative.startsWith(`..${path10.sep}`) || relative === ".." || path10.isAbsolute(relative))
27062
+ const absolute = path11.resolve(session.location.directory, diff.file);
27063
+ const relative = path11.relative(session.location.directory, absolute);
27064
+ if (relative.startsWith(`..${path11.sep}`) || relative === ".." || path11.isAbsolute(relative))
26588
27065
  throw new Error("OpenCode v2 diff escaped the Session directory");
26589
27066
  return {
26590
27067
  path: absolute,
@@ -26627,7 +27104,7 @@ function terminalItemOutcome(outcome) {
26627
27104
 
26628
27105
  // dist/v2/session-import.js
26629
27106
  import fs6 from "node:fs";
26630
- import path11 from "node:path";
27107
+ import path12 from "node:path";
26631
27108
 
26632
27109
  // ../../harness-adapter/dist/session-import.js
26633
27110
  function sessionImportTitle(value, maxLength = HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) {
@@ -26660,7 +27137,7 @@ function sessionImportCandidate(input) {
26660
27137
  var PAGE_SIZE = 200;
26661
27138
  var MAX_PAGES = 1e4;
26662
27139
  function existingDirectory(directory) {
26663
- if (typeof directory !== "string" || !path11.isAbsolute(directory))
27140
+ if (typeof directory !== "string" || !path12.isAbsolute(directory))
26664
27141
  return null;
26665
27142
  try {
26666
27143
  return fs6.statSync(directory).isDirectory() ? directory : null;
@@ -26860,6 +27337,14 @@ function v2Capabilities(catalog) {
26860
27337
  history: { fork: true, forkAcrossCwd: false, rollbackLastTurn: true }
26861
27338
  };
26862
27339
  }
27340
+ var FIRST_OUTPUT_EVENTS = /* @__PURE__ */ new Set([
27341
+ "session.reasoning.started",
27342
+ "session.reasoning.delta",
27343
+ "session.text.started",
27344
+ "session.text.delta",
27345
+ "session.tool.input.started",
27346
+ "session.tool.input.delta"
27347
+ ]);
26863
27348
  var V2Session = class {
26864
27349
  client;
26865
27350
  connection;
@@ -26883,6 +27368,11 @@ var V2Session = class {
26883
27368
  #reconciling;
26884
27369
  #timer;
26885
27370
  #configuring = false;
27371
+ #cacheHitRatePercent;
27372
+ /** Assistant messages already published as usage requests. */
27373
+ #meteredMessages = /* @__PURE__ */ new Set();
27374
+ /** Adapter receive time of each assistant message's first reasoning, text or tool input. */
27375
+ #firstOutputAt = /* @__PURE__ */ new Map();
26886
27376
  constructor(client2, connection, info, catalog, policy, limit, onClosed) {
26887
27377
  this.client = client2;
26888
27378
  this.connection = connection;
@@ -26927,6 +27417,7 @@ var V2Session = class {
26927
27417
  }
26928
27418
  })();
26929
27419
  });
27420
+ await this.#replayUsage();
26930
27421
  this.#timer = setInterval(() => {
26931
27422
  void this.#refresh();
26932
27423
  }, 400);
@@ -26995,22 +27486,22 @@ var V2Session = class {
26995
27486
  permissions: v2Permissions(this.info.permissions, command.permissionModeId)
26996
27487
  });
26997
27488
  } else {
26998
- let model = this.info.model;
27489
+ let model2 = this.info.model;
26999
27490
  if (command.type === "model.select") {
27000
27491
  if (!this.catalog.models.some((m) => m.ref.id === command.model.id))
27001
27492
  throw new Error("OpenCode Model is not available");
27002
27493
  const decoded = decodeOpenCodeModelRef(command.model);
27003
- model = { providerID: decoded.providerID, id: decoded.modelID };
27494
+ model2 = { providerID: decoded.providerID, id: decoded.modelID };
27004
27495
  } else {
27005
- if (!model)
27496
+ if (!model2)
27006
27497
  throw new Error("Select a Model before a Thinking option");
27007
27498
  const state = v2State(this.info, this.catalog, this.policy);
27008
27499
  if (!state.availableThinkingOptions?.some((v) => v.id === command.thinkingOptionId))
27009
27500
  throw new Error("Thinking option is unavailable for this Model");
27010
27501
  const variant = decodeOpenCodeVariant(command.thinkingOptionId);
27011
- model = { providerID: model.providerID, id: model.id, ...variant ? { variant } : {} };
27502
+ model2 = { providerID: model2.providerID, id: model2.id, ...variant ? { variant } : {} };
27012
27503
  }
27013
- await this.client.session.switchModel({ sessionID: this.info.id, model });
27504
+ await this.client.session.switchModel({ sessionID: this.info.id, model: model2 });
27014
27505
  }
27015
27506
  this.info = await this.client.session.get({ sessionID: this.info.id });
27016
27507
  this.#emit({
@@ -27094,11 +27585,14 @@ var V2Session = class {
27094
27585
  const active = this.#active;
27095
27586
  if (!active || !("data" in event) || !("sessionID" in event.data) || event.data.sessionID !== this.info.id)
27096
27587
  return;
27588
+ if (FIRST_OUTPUT_EVENTS.has(event.type) && "assistantMessageID" in event.data && typeof event.data.assistantMessageID === "string" && !this.#firstOutputAt.has(event.data.assistantMessageID))
27589
+ this.#firstOutputAt.set(event.data.assistantMessageID, Date.now());
27097
27590
  if (event.type === "session.step.started")
27098
27591
  active.assistants.add(event.data.assistantMessageID);
27099
27592
  if ((event.type === "session.text.delta" || event.type === "session.reasoning.delta") && active.assistants.has(event.data.assistantMessageID)) {
27100
- const itemId2 = contentId(event.data.assistantMessageID, event.data.ordinal);
27101
- const type = event.type === "session.text.delta" ? "agentMessage" : "reasoning";
27593
+ const contentType = event.type === "session.text.delta" ? "text" : "reasoning";
27594
+ const itemId2 = contentId(event.data.assistantMessageID, contentType, event.data.ordinal);
27595
+ const type = contentType === "text" ? "agentMessage" : "reasoning";
27102
27596
  const previous = active.transient.get(itemId2);
27103
27597
  const item = {
27104
27598
  type,
@@ -27112,6 +27606,56 @@ var V2Session = class {
27112
27606
  if (!event.type.endsWith(".delta"))
27113
27607
  void this.#refresh();
27114
27608
  }
27609
+ /** Publishes assistant messages not yet metered; returns false when one is unusable. */
27610
+ #meterUsage(messages, historical) {
27611
+ let usable = true;
27612
+ const previousCacheHitRate = this.#cacheHitRatePercent;
27613
+ for (const message of messages) {
27614
+ let request;
27615
+ try {
27616
+ request = v2UsageRequest(message, historical, this.#firstOutputAt.get(message.id));
27617
+ } catch {
27618
+ this.#cacheHitRatePercent = void 0;
27619
+ if (this.#meteredMessages.has(message.id))
27620
+ continue;
27621
+ this.#meteredMessages.add(message.id);
27622
+ if (!historical)
27623
+ this.#emit({ type: "usage.history", complete: false });
27624
+ usable = false;
27625
+ continue;
27626
+ }
27627
+ if (!request)
27628
+ continue;
27629
+ this.#cacheHitRatePercent = request.inputTokens > 0 && request.cachedInputTokens !== void 0 ? request.cachedInputTokens / request.inputTokens * 100 : void 0;
27630
+ if (this.#meteredMessages.has(message.id))
27631
+ continue;
27632
+ this.#meteredMessages.add(message.id);
27633
+ this.#firstOutputAt.delete(message.id);
27634
+ this.#emit({ type: "usage.request", request });
27635
+ }
27636
+ if (this.#cacheHitRatePercent !== previousCacheHitRate)
27637
+ this.#emit({
27638
+ type: "session.usage.changed",
27639
+ usage: this.#usage()
27640
+ });
27641
+ return usable;
27642
+ }
27643
+ #usage() {
27644
+ const usage = v2Usage(this.info);
27645
+ if (this.#cacheHitRatePercent !== void 0)
27646
+ usage.cacheHitRatePercent = this.#cacheHitRatePercent;
27647
+ return usage;
27648
+ }
27649
+ /** Replays every metered request of the native history, then declares it complete. */
27650
+ async #replayUsage() {
27651
+ let complete = false;
27652
+ try {
27653
+ complete = this.#meterUsage(await readMessages(this.client, this.info.id), true);
27654
+ } catch {
27655
+ complete = false;
27656
+ }
27657
+ this.#emit({ type: "usage.history", complete });
27658
+ }
27115
27659
  #refresh() {
27116
27660
  if (this.#closed || !this.#active?.admitted)
27117
27661
  return Promise.resolve();
@@ -27130,6 +27674,7 @@ var V2Session = class {
27130
27674
  if (this.#active !== active || this.#closed)
27131
27675
  return;
27132
27676
  this.info = info;
27677
+ this.#meterUsage(messages, false);
27133
27678
  const turns = snapshot.turns.filter((t) => !active.baseline.has(t.nativeTurnRef.nativeTurnKey));
27134
27679
  if (turns.length > 1)
27135
27680
  throw new Error("Concurrent native prompts cannot be assigned to one Host Turn");
@@ -27226,7 +27771,7 @@ var V2Session = class {
27226
27771
  });
27227
27772
  this.#emit({
27228
27773
  type: "session.usage.changed",
27229
- usage: v2Usage(this.info),
27774
+ usage: this.#usage(),
27230
27775
  observedForTurnId: active.turnId
27231
27776
  });
27232
27777
  this.#active = void 0;
@@ -27422,10 +27967,10 @@ var V2Adapter = class {
27422
27967
  const catalog = await this.#catalog(client2, input.cwd);
27423
27968
  let info;
27424
27969
  if (input.kind === "create") {
27425
- const model = selectedModel(input, catalog);
27970
+ const model2 = selectedModel(input, catalog);
27426
27971
  info = await client2.session.create({
27427
27972
  location: { directory: input.cwd },
27428
- ...model ? { model } : {},
27973
+ ...model2 ? { model: model2 } : {},
27429
27974
  permissions: v2Permissions([], input.permissionModeId ?? harnessPermissionModeIdSchema.parse(policy === "unattended-full-access" ? "allow" : "default"))
27430
27975
  });
27431
27976
  created = info.id;
@@ -27442,19 +27987,19 @@ var V2Adapter = class {
27442
27987
  if (input.kind !== "resume") {
27443
27988
  const parent = info;
27444
27989
  const turns = source.snapshot.turns;
27445
- let count;
27990
+ let count2;
27446
27991
  if (input.kind === "rollbackLastTurn") {
27447
27992
  if (!turns.length)
27448
27993
  throw new Error("OpenCode history is empty");
27449
- count = turns.length - 1;
27994
+ count2 = turns.length - 1;
27450
27995
  } else {
27451
27996
  if (input.checkpoint.harnessId !== harnessId || input.checkpoint.nativeSessionId !== info.id)
27452
27997
  throw new Error("Checkpoint belongs to another Session");
27453
- count = turns.findIndex((turn) => turn.checkpoint?.checkpointId === input.checkpoint.checkpointId) + 1;
27454
- if (!count || JSON.stringify(turns[count - 1]?.checkpoint) !== JSON.stringify(input.checkpoint))
27998
+ count2 = turns.findIndex((turn) => turn.checkpoint?.checkpointId === input.checkpoint.checkpointId) + 1;
27999
+ if (!count2 || JSON.stringify(turns[count2 - 1]?.checkpoint) !== JSON.stringify(input.checkpoint))
27455
28000
  throw new Error("OpenCode checkpoint does not match native history");
27456
28001
  }
27457
- const before = turns[count]?.nativeTurnRef.nativeTurnKey;
28002
+ const before = turns[count2]?.nativeTurnRef.nativeTurnKey;
27458
28003
  info = await client2.session.fork({ sessionID: parent.id, ...before ? { before } : {} });
27459
28004
  if (info.id === parent.id)
27460
28005
  throw new Error("OpenCode fork returned its source Session");
@@ -27469,7 +28014,7 @@ var V2Adapter = class {
27469
28014
  await client2.session.switchModel({ sessionID: info.id, model: parent.model });
27470
28015
  info = await client2.session.get({ sessionID: info.id });
27471
28016
  const derived = await readHistory(client2, info, this.options.toolOutputLimit ?? 64e3);
27472
- if (historyContent(derived.snapshot, false) !== historyContent({ turns: turns.slice(0, count) }, false))
28017
+ if (historyContent(derived.snapshot, false) !== historyContent({ turns: turns.slice(0, count2) }, false))
27473
28018
  throw new Error("OpenCode fork did not preserve the exact history prefix");
27474
28019
  if (!isDeepStrictEqual2(info.permissions ?? [], parent.permissions ?? []) || !isDeepStrictEqual2(info.model, parent.model))
27475
28020
  throw new Error("OpenCode fork did not preserve the current configuration");
@@ -27518,14 +28063,14 @@ function selectedModel(input, catalog) {
27518
28063
  throw new Error("Thinking selection requires a Model");
27519
28064
  return void 0;
27520
28065
  }
27521
- const entry = catalog.models.find((model2) => model2.ref.id === selected.id);
28066
+ const entry = catalog.models.find((model3) => model3.ref.id === selected.id);
27522
28067
  if (!entry)
27523
28068
  throw new Error("OpenCode Model is not available");
27524
28069
  if (input.thinkingOptionId && !entry.supportedThinkingOptionIds?.includes(input.thinkingOptionId))
27525
28070
  throw new Error("OpenCode Thinking option is not available for this Model");
27526
- const model = decodeOpenCodeModelRef(selected);
28071
+ const model2 = decodeOpenCodeModelRef(selected);
27527
28072
  const variant = input.thinkingOptionId ? decodeOpenCodeVariant(input.thinkingOptionId) : void 0;
27528
- return { providerID: model.providerID, id: model.modelID, ...variant ? { variant } : {} };
28073
+ return { providerID: model2.providerID, id: model2.modelID, ...variant ? { variant } : {} };
27529
28074
  }
27530
28075
  function historyContent(snapshot, identities = true) {
27531
28076
  return JSON.stringify(snapshot.turns.map((turn) => ({
@@ -27549,9 +28094,11 @@ var OpenCodeAdapter2 = class {
27549
28094
  commandCatalog = openCodeCommandCatalog;
27550
28095
  #adapters = /* @__PURE__ */ new Set();
27551
28096
  #closed = false;
28097
+ usageStatistics;
27552
28098
  constructor(options = {}, dependencies) {
27553
28099
  this.options = options;
27554
28100
  this.dependencies = dependencies;
28101
+ this.usageStatistics = createOpenCodeUsageStatistics(options.environment ?? process.env);
27555
28102
  }
27556
28103
  async #select(environment, input) {
27557
28104
  if (this.#closed)
@@ -27661,7 +28208,7 @@ function normalize(error51) {
27661
28208
  // dist/installation.js
27662
28209
  import { realpath as realpath2 } from "node:fs/promises";
27663
28210
  import { homedir as homedir3 } from "node:os";
27664
- import path12 from "node:path";
28211
+ import path13 from "node:path";
27665
28212
  function createOpenCodeInstallation(environment, command) {
27666
28213
  let update;
27667
28214
  return createInstallationManager({
@@ -27682,8 +28229,8 @@ function createOpenCodeInstallation(environment, command) {
27682
28229
  const release = JSON.parse(await fetchInstallationText("https://api.github.com/repos/anomalyco/opencode/releases/latest"));
27683
28230
  latestVersion = installationVersion(release.tag_name);
27684
28231
  const home = environment.HOME ?? environment.USERPROFILE ?? homedir3();
27685
- const standard = path12.join(home, ".opencode", "bin", process.platform === "win32" ? "opencode.exe" : "opencode");
27686
- canUpdate = process.platform !== "win32" && path12.resolve(executable) === standard && await realpath2(executable) === standard;
28232
+ const standard = path13.join(home, ".opencode", "bin", process.platform === "win32" ? "opencode.exe" : "opencode");
28233
+ canUpdate = process.platform !== "win32" && path13.resolve(executable) === standard && await realpath2(executable) === standard;
27687
28234
  update = async (version2) => {
27688
28235
  await runInstallationCommand(executable, ["upgrade", version2, "--method", "curl"], environment, 3e5);
27689
28236
  };