ohmyswitch 0.2.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/oms.mjs +716 -108
  2. package/package.json +1 -1
package/oms.mjs CHANGED
@@ -1,16 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
- import { inspect, parseArgs, stripVTControlCharacters, styleText } from "node:util";
3
+ import { inspect, parseArgs, promisify, stripVTControlCharacters, styleText } from "node:util";
4
4
  import process$1, { stdin, stdout } from "node:process";
5
5
  import * as l from "node:readline";
6
6
  import l__default, { emitKeypressEvents } from "node:readline";
7
7
  import { ReadStream } from "node:tty";
8
- import { existsSync, watch } from "node:fs";
9
- import { basename, dirname, extname, isAbsolute, join, relative } from "node:path";
8
+ import { createReadStream, existsSync, watch } from "node:fs";
9
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
10
10
  import { homedir } from "node:os";
11
11
  import { access, constants, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
12
12
  import { fileURLToPath, pathToFileURL } from "node:url";
13
+ import { StringDecoder } from "node:string_decoder";
13
14
  import { createHash, randomBytes, randomUUID } from "node:crypto";
15
+ import { constants as constants$1, zstdDecompress } from "node:zlib";
14
16
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
15
17
  import { EventEmitter, on } from "node:events";
16
18
  import { setGlobalProxyFromEnv } from "node:http";
@@ -2157,13 +2159,17 @@ function displayWidth(text) {
2157
2159
  function padEnd(text, width) {
2158
2160
  return text + " ".repeat(Math.max(0, width - displayWidth(text)));
2159
2161
  }
2160
- /** Lay out rows in columns two spaces apart. The last column is not padded. */
2161
- function columns(rows) {
2162
+ /** Lay out rows in columns two spaces apart. Numeric columns can be aligned to the right. */
2163
+ function columns(rows, numeric = []) {
2162
2164
  const widths = [];
2163
2165
  for (const row of rows) row.forEach((cell, index) => {
2164
2166
  widths[index] = Math.max(widths[index] ?? 0, displayWidth(cell));
2165
2167
  });
2166
- return rows.map((row) => row.map((cell, index) => index === row.length - 1 ? cell : padEnd(cell, widths[index] ?? 0)).join(" ").trimEnd());
2168
+ return rows.map((row) => row.map((cell, index) => {
2169
+ const width = widths[index] ?? 0;
2170
+ if (numeric.includes(index)) return " ".repeat(width - displayWidth(cell)) + cell;
2171
+ return index === row.length - 1 ? cell : padEnd(cell, width);
2172
+ }).join(" ").trimEnd());
2167
2173
  }
2168
2174
  /** Quote a word for a POSIX shell, so equivalent commands can be pasted as they are. */
2169
2175
  function shellQuote(word) {
@@ -3019,7 +3025,7 @@ const pick$1 = command({
3019
3025
  },
3020
3026
  failed: (result) => result.failures.length > 0
3021
3027
  });
3022
- const add$1 = command({
3028
+ const add$2 = command({
3023
3029
  name: "add",
3024
3030
  summary: "Add some of the provider's listed models, keeping the others",
3025
3031
  params: {
@@ -3149,7 +3155,7 @@ const model$1 = group({
3149
3155
  children: [
3150
3156
  list$3,
3151
3157
  pick$1,
3152
- add$1,
3158
+ add$2,
3153
3159
  remove$2,
3154
3160
  sync,
3155
3161
  command({
@@ -4315,7 +4321,7 @@ function datetime$1(args) {
4315
4321
  }
4316
4322
  const anyString = /^[\s\S]{0,}$/;
4317
4323
  const integer = /^-?\d+$/;
4318
- const number$1 = /^-?\d+(?:\.\d+)?$/;
4324
+ const number$2 = /^-?\d+(?:\.\d+)?$/;
4319
4325
  const boolean$1 = /^(?:true|false)$/i;
4320
4326
  const lowercase = /^[^A-Z]*$/;
4321
4327
  const uppercase = /^[^a-z]*$/;
@@ -5098,7 +5104,7 @@ const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => {
5098
5104
  });
5099
5105
  const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => {
5100
5106
  $ZodType.init(inst, def);
5101
- inst._zod.pattern = number$1;
5107
+ inst._zod.pattern = number$2;
5102
5108
  inst._zod.parse = (payload, _ctx) => {
5103
5109
  if (def.coerce) try {
5104
5110
  payload.value = Number(payload.value);
@@ -5799,7 +5805,7 @@ const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => {
5799
5805
  issues: []
5800
5806
  }, ctx);
5801
5807
  if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
5802
- if (typeof key === "string" && number$1.test(key) && keyResult.issues.length) {
5808
+ if (typeof key === "string" && number$2.test(key) && keyResult.issues.length) {
5803
5809
  const retryResult = def.keyType._zod.run({
5804
5810
  value: Number(key),
5805
5811
  issues: []
@@ -7773,7 +7779,7 @@ function stringifyKeyNames(bySchema, json, visited) {
7773
7779
  else if (typeof rest.const === "number") rest.const = String(rest.const);
7774
7780
  if (!numericType) return rest;
7775
7781
  rest.type = "string";
7776
- if (!values) rest.pattern = (types.includes("number") ? number$1 : integer).source;
7782
+ if (!values) rest.pattern = (types.includes("number") ? number$2 : integer).source;
7777
7783
  return rest;
7778
7784
  }
7779
7785
  /** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */
@@ -8479,7 +8485,7 @@ const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => {
8479
8485
  return this;
8480
8486
  }
8481
8487
  }));
8482
- function number(params) {
8488
+ function number$1(params) {
8483
8489
  return /* @__PURE__ */ _number(ZodNumber, params);
8484
8490
  }
8485
8491
  const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => {
@@ -8589,7 +8595,7 @@ const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => {
8589
8595
  return required(ZodNonOptional, this, args[0]);
8590
8596
  }
8591
8597
  });
8592
- function object(shape, params) {
8598
+ function object$1(shape, params) {
8593
8599
  const def = {
8594
8600
  type: "object",
8595
8601
  shape: shape ?? {},
@@ -8928,31 +8934,31 @@ const reasoningEffort = string().regex(/^[A-Za-z0-9_-]{1,32}$/, { error: "推理
8928
8934
  * On a model, an empty list means reasoning cannot be controlled; an unset list means unknown.
8929
8935
  */
8930
8936
  const reasoningOption = discriminatedUnion("type", [
8931
- object({
8937
+ object$1({
8932
8938
  type: literal("effort"),
8933
8939
  values: array(reasoningEffort).min(1).max(16)
8934
8940
  }),
8935
- object({ type: literal("toggle") }),
8936
- object({
8941
+ object$1({ type: literal("toggle") }),
8942
+ object$1({
8937
8943
  type: literal("budget_tokens"),
8938
- min: number().int().nonnegative().optional(),
8939
- max: number().int().positive().optional()
8944
+ min: number$1().int().nonnegative().optional(),
8945
+ max: number$1().int().positive().optional()
8940
8946
  })
8941
8947
  ]);
8942
8948
  /**
8943
8949
  * Whether reasoning must be sent back with later turns. `true` uses the protocol's own form; `field` names the
8944
8950
  * response field to echo, such as `reasoning_content` on OpenAI-compatible APIs.
8945
8951
  */
8946
- const interleaved = union([literal(true), object({ field: string().regex(/^[a-z_]{1,64}$/) })]);
8952
+ const interleaved = union([literal(true), object$1({ field: string().regex(/^[a-z_]{1,64}$/) })]);
8947
8953
  /**
8948
8954
  * A model and the metadata harness configs need. Every field but `id` is optional: unknown stays unset rather
8949
8955
  * than guessed, and harnesses fall back to their own defaults.
8950
8956
  */
8951
- const modelInfo = object({
8957
+ const modelInfo = object$1({
8952
8958
  id: string().min(1).max(256),
8953
8959
  name: string().max(256).optional(),
8954
- contextWindow: number().int().positive().optional(),
8955
- maxOutput: number().int().positive().optional(),
8960
+ contextWindow: number$1().int().positive().optional(),
8961
+ maxOutput: number$1().int().positive().optional(),
8956
8962
  reasoning: boolean().optional(),
8957
8963
  reasoningOptions: array(reasoningOption).max(8).optional(),
8958
8964
  interleaved: interleaved.optional(),
@@ -8967,7 +8973,7 @@ const modelOverride = modelInfo.pick({
8967
8973
  });
8968
8974
  const providerModelOverride = modelOverride;
8969
8975
  /** A provider as persisted. The API key is stored in plain text; harness configs hold it in plain text anyway. */
8970
- const storedProvider = object({
8976
+ const storedProvider = object$1({
8971
8977
  id: uuid(),
8972
8978
  name: providerName,
8973
8979
  /** The root address requests go to; endpoints are appended to it. */
@@ -8995,7 +9001,7 @@ const storedProvider = object({
8995
9001
  * Harnesses this provider is applied to, with the key ohmyswitch owns in each harness config. Entries of
8996
9002
  * harnesses that are not registered are kept, so the application survives until the harness is back.
8997
9003
  */
8998
- harnesses: record$2(harnessId, object({ key: string().min(1).max(64) })).default({}),
9004
+ harnesses: record$2(harnessId, object$1({ key: string().min(1).max(64) })).default({}),
8999
9005
  createdAt: datetime()
9000
9006
  });
9001
9007
  /** Apply explicit fields in order: snapshot → global → provider. */
@@ -9012,9 +9018,9 @@ function effectiveModel(model, globalOverrides, providerOverrides = {}) {
9012
9018
  }
9013
9019
  //#endregion
9014
9020
  //#region src/core/providers/schemas.ts
9015
- const providerIdInput = object({ providerId: uuid() });
9021
+ const providerIdInput = object$1({ providerId: uuid() });
9016
9022
  /** The fields of a provider the editor saves together; they are not all connection details. */
9017
- const connectionInput = object({
9023
+ const connectionInput = object$1({
9018
9024
  name: providerName,
9019
9025
  baseUrl,
9020
9026
  apiKey: string().trim().min(1, { error: "请填写 API Key" }).max(4096),
@@ -9035,29 +9041,29 @@ const createProviderInput = connectionInput.extend({
9035
9041
  selected: array(string().min(1).max(256)).max(2e3).optional().transform((ids) => ids ? [...new Set(ids)] : void 0)
9036
9042
  });
9037
9043
  const updateProviderInput = connectionInput.extend(providerIdInput.shape);
9038
- object({ providerIds: array(uuid()).max(1e3).refine((ids) => new Set(ids).size === ids.length, { error: "供应商顺序中有重复项" }) });
9044
+ object$1({ providerIds: array(uuid()).max(1e3).refine((ids) => new Set(ids).size === ids.length, { error: "供应商顺序中有重复项" }) });
9039
9045
  providerIdInput.extend({ models: array(modelInfo).max(2e3).transform((models) => [...new Map(models.map((model) => [model.id, model])).values()]) });
9040
- const modelId$2 = string().min(1).max(256);
9041
- const modelOverrideInput = object({
9042
- modelId: modelId$2,
9046
+ const modelId$3 = string().min(1).max(256);
9047
+ const modelOverrideInput = object$1({
9048
+ modelId: modelId$3,
9043
9049
  override: modelOverride.refine((value) => Object.values(value).some((field) => field !== void 0), { error: "请至少填写一项覆盖信息" })
9044
9050
  });
9045
- object({ modelId: modelId$2 });
9051
+ object$1({ modelId: modelId$3 });
9046
9052
  /** Replace one model's provider overrides. An empty object restores inheritance for every field. */
9047
9053
  const providerModelOverrideInput = providerIdInput.extend({
9048
- modelId: modelId$2,
9054
+ modelId: modelId$3,
9049
9055
  override: providerModelOverride.strict()
9050
9056
  });
9051
9057
  providerIdInput.extend({
9052
9058
  listed: array(modelInfo).max(2e3),
9053
- selected: array(modelId$2).max(2e3).transform((ids) => [...new Set(ids)])
9059
+ selected: array(modelId$3).max(2e3).transform((ids) => [...new Set(ids)])
9054
9060
  });
9055
9061
  providerIdInput.extend({
9056
9062
  add: array(modelInfo).max(2e3),
9057
- remove: array(modelId$2).max(2e3),
9058
- listed: array(modelId$2).max(2e3).transform((ids) => [...new Set(ids)])
9063
+ remove: array(modelId$3).max(2e3),
9064
+ listed: array(modelId$3).max(2e3).transform((ids) => [...new Set(ids)])
9059
9065
  });
9060
- object({ candidates: array(object({ sources: array(object({
9066
+ object$1({ candidates: array(object$1({ sources: array(object$1({
9061
9067
  harnessId,
9062
9068
  key: string().min(1).max(64)
9063
9069
  })).min(1).max(16) })).min(1, { error: "请选择要导入的供应商" }).max(200) });
@@ -9113,7 +9119,7 @@ async function settableModels(scope) {
9113
9119
  hint: Object.hasOwn(overrides, model.id) ? "overridden" : modelChoice(model).hint
9114
9120
  }));
9115
9121
  }
9116
- const modelId$1 = (raw) => {
9122
+ const modelId$2 = (raw) => {
9117
9123
  if (!raw.trim() || raw.length > 256) throw new ParamError("Model id must contain 1 to 256 characters.");
9118
9124
  return raw;
9119
9125
  };
@@ -9167,7 +9173,7 @@ const override = group({
9167
9173
  positional: true,
9168
9174
  placeholder: "model",
9169
9175
  details: "Its id, exactly; for a provider override, one of its saved models",
9170
- parse: modelId$1,
9176
+ parse: modelId$2,
9171
9177
  complete: settableModels,
9172
9178
  suggest: async (scope) => ({
9173
9179
  choices: await settableModels(scope),
@@ -9430,7 +9436,7 @@ function parseWith(schema, value) {
9430
9436
  }
9431
9437
  //#endregion
9432
9438
  //#region src/cli/commands/provider.ts
9433
- const modelId = string().trim().min(1).max(256);
9439
+ const modelId$1 = string().trim().min(1).max(256);
9434
9440
  const chosen = (scope) => scope.values.provider;
9435
9441
  async function assertNameFree(scope, name, except) {
9436
9442
  if ((await scope.services()).providers.list().some((provider) => provider.name === name && provider.id !== except)) throw new CliError("conflict", `A provider named "${name}" already exists`);
@@ -9543,7 +9549,7 @@ function draftModels(scope) {
9543
9549
  }
9544
9550
  });
9545
9551
  }
9546
- const add = command({
9552
+ const add$1 = command({
9547
9553
  name: "add",
9548
9554
  summary: "Add a provider",
9549
9555
  params: {
@@ -9583,7 +9589,7 @@ const add = command({
9583
9589
  details: "By id, with details from models.dev; in a terminal, picked from the list the provider returns",
9584
9590
  optional: true,
9585
9591
  ask: (values) => !values.allModels,
9586
- parse: (raw) => parseWith(modelId, raw),
9592
+ parse: (raw) => parseWith(modelId$1, raw),
9587
9593
  async suggest(scope) {
9588
9594
  const { models } = await draftModels(scope);
9589
9595
  return {
@@ -9761,6 +9767,231 @@ async function positionChoices(scope) {
9761
9767
  };
9762
9768
  });
9763
9769
  }
9770
+ const provider = group({
9771
+ name: "provider",
9772
+ aliases: ["providers"],
9773
+ summary: "Manage providers",
9774
+ children: [
9775
+ list,
9776
+ show,
9777
+ add$1,
9778
+ edit,
9779
+ remove,
9780
+ command({
9781
+ name: "move",
9782
+ summary: "Move a provider in the list",
9783
+ params: {
9784
+ provider: providerParam(),
9785
+ to: select$1({
9786
+ summary: "Position",
9787
+ placeholder: "position",
9788
+ details: "From 1, or first or last",
9789
+ empty: "There is no other position to move it to.",
9790
+ choices: positionChoices
9791
+ })
9792
+ },
9793
+ async run({ provider, to }, scope) {
9794
+ const ctx = await scope.services();
9795
+ const ids = ctx.providers.list().map((item) => item.id).filter((id) => id !== provider.id);
9796
+ ids.splice(to, 0, provider.id);
9797
+ const { harnessFailures } = await ctx.providers.reorder({ providerIds: ids });
9798
+ const harnesses = await harnessIndex(scope);
9799
+ return {
9800
+ id: provider.id,
9801
+ name: provider.name,
9802
+ position: to + 1,
9803
+ failures: problemsOf(harnessFailures, harnesses)
9804
+ };
9805
+ },
9806
+ render(result, out) {
9807
+ out.success(`Moved "${result.name}" to position ${result.position}.`);
9808
+ warnProblems(out, result.failures);
9809
+ },
9810
+ failed: (result) => result.failures.length > 0
9811
+ })
9812
+ ]
9813
+ });
9814
+ //#endregion
9815
+ //#region src/core/harnesses/schemas.ts
9816
+ /** Whether the harness is registered is checked by the service, which reports an unknown one as not found. */
9817
+ const applicationInput = object$1({
9818
+ providerId: uuid(),
9819
+ harnessId
9820
+ });
9821
+ object$1({ providerId: uuid() }).extend({ harnessIds: array(harnessId).min(1).max(64) });
9822
+ applicationInput.extend({
9823
+ /** Take over an existing entry with the same key that ohmyswitch does not own. */
9824
+ replace: boolean().default(false) });
9825
+ const usageDays = int$1().min(1).max(365e3);
9826
+ object$1({ days: usageDays.nullable().default(30) });
9827
+ //#endregion
9828
+ //#region src/core/harnesses/usage/report.ts
9829
+ const emptyTokens = () => ({
9830
+ input: 0,
9831
+ output: 0,
9832
+ cacheRead: 0,
9833
+ cacheWrite: 0,
9834
+ total: 0
9835
+ });
9836
+ function add(target, counts) {
9837
+ target.input += counts.input;
9838
+ target.output += counts.output;
9839
+ target.cacheRead += counts.cacheRead;
9840
+ target.cacheWrite += counts.cacheWrite;
9841
+ target.total += counts.total;
9842
+ }
9843
+ function localDate(time) {
9844
+ const date = new Date(time);
9845
+ return [
9846
+ date.getFullYear(),
9847
+ String(date.getMonth() + 1).padStart(2, "0"),
9848
+ String(date.getDate()).padStart(2, "0")
9849
+ ].join("-");
9850
+ }
9851
+ function usageReport(sources, days, until) {
9852
+ const start = new Date(until);
9853
+ start.setHours(0, 0, 0, 0);
9854
+ if (days !== null) start.setDate(start.getDate() - days + 1);
9855
+ const lowerBound = days === null ? -Infinity : start.getTime();
9856
+ let earliest = Infinity;
9857
+ const totals = emptyTokens();
9858
+ const models = /* @__PURE__ */ new Map();
9859
+ for (const source of sources) {
9860
+ const seen = /* @__PURE__ */ new Set();
9861
+ for (const { time, model, tokens, identity } of source.records) {
9862
+ if (!Number.isFinite(time) || time < lowerBound || time > until.getTime() || !tokens.total) continue;
9863
+ if (identity && seen.has(identity)) continue;
9864
+ if (identity) seen.add(identity);
9865
+ earliest = Math.min(earliest, time);
9866
+ const row = models.get(model) ?? {
9867
+ totals: emptyTokens(),
9868
+ harnesses: /* @__PURE__ */ new Map()
9869
+ };
9870
+ models.set(model, row);
9871
+ const counts = row.harnesses.get(source.name) ?? emptyTokens();
9872
+ row.harnesses.set(source.name, counts);
9873
+ add(counts, tokens);
9874
+ add(row.totals, tokens);
9875
+ add(totals, tokens);
9876
+ }
9877
+ }
9878
+ return {
9879
+ from: days === null ? Number.isFinite(earliest) ? localDate(earliest) : null : localDate(lowerBound),
9880
+ to: localDate(until.getTime()),
9881
+ totals,
9882
+ modelCount: models.size - Number(models.has(null)),
9883
+ models: Array.from(models, ([id, row]) => ({
9884
+ id,
9885
+ totals: row.totals,
9886
+ harnesses: Array.from(row.harnesses, ([name, totals]) => ({
9887
+ name,
9888
+ totals
9889
+ })).sort((a, b) => b.totals.total - a.totals.total)
9890
+ })).sort((a, b) => b.totals.total - a.totals.total || (a.id ?? "").localeCompare(b.id ?? "")),
9891
+ incompleteSources: sources.filter((source) => source.incomplete).map((source) => source.name)
9892
+ };
9893
+ }
9894
+ //#endregion
9895
+ //#region src/cli/commands/usage.ts
9896
+ function positiveInteger(value) {
9897
+ const number = Number(value);
9898
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(number) || number < 1) throw new ParamError("must be a positive integer");
9899
+ return number;
9900
+ }
9901
+ const number = new Intl.NumberFormat("en-US").format;
9902
+ const percent = (part, total) => total ? `${(100 * part / total).toFixed(1)}%` : "—";
9903
+ const usage = command({
9904
+ name: "usage",
9905
+ summary: "Show local model usage",
9906
+ params: {
9907
+ days: text$1({
9908
+ summary: "Include this many calendar days (default: 30)",
9909
+ optional: true,
9910
+ ask: false,
9911
+ parse: (raw) => parseWith(usageDays, positiveInteger(raw))
9912
+ }),
9913
+ all: flag({ summary: "Include all recorded history" }),
9914
+ model: text$1({
9915
+ summary: "Show usage by harness for this exact model ID",
9916
+ optional: true,
9917
+ ask: false
9918
+ }),
9919
+ limit: text$1({
9920
+ summary: "Show the first N models",
9921
+ optional: true,
9922
+ ask: false,
9923
+ parse: positiveInteger
9924
+ })
9925
+ },
9926
+ async run({ days, all, model, limit }, scope) {
9927
+ if (all && days !== void 0) throw new CliError("usage", "Choose either --all or --days.");
9928
+ if (model !== void 0 && limit !== void 0) throw new CliError("usage", "Use --limit with the model ranking.");
9929
+ const { harnesses } = await scope.services();
9930
+ const report = await harnesses.usage(all ? null : days ?? 30);
9931
+ const models = model === void 0 ? report.models.slice(0, limit) : report.models.filter((row) => row.id === model);
9932
+ if (model !== void 0 && !models.length && !report.incompleteSources.length) throw new CliError("not_found", `No recorded usage for model "${model}" in this period.`);
9933
+ if (model !== void 0) return {
9934
+ ...report,
9935
+ models,
9936
+ totals: models[0]?.totals ?? emptyTokens(),
9937
+ modelCount: models.length
9938
+ };
9939
+ return {
9940
+ ...report,
9941
+ models
9942
+ };
9943
+ },
9944
+ failed: (result) => result.incompleteSources.length > 0,
9945
+ render(report, out, { model }) {
9946
+ for (const name of report.incompleteSources) out.warn(`Some ${name} usage data could not be read.`);
9947
+ const row = report.models[0];
9948
+ const totals = report.totals;
9949
+ out.print(`Model usage ${report.from ?? "All history"} to ${report.to}`);
9950
+ if (!totals.total) {
9951
+ out.print("No recorded usage.");
9952
+ return;
9953
+ }
9954
+ const scope = model === void 0 ? plural(report.modelCount, "model") : model;
9955
+ out.print(`${number(totals.total)} tokens ${scope} ${percent(totals.cacheRead, totals.total)} cache read`);
9956
+ out.print();
9957
+ if (model !== void 0 && row) out.table([
9958
+ "HARNESS",
9959
+ "TOTAL TOKENS",
9960
+ "INPUT",
9961
+ "CACHE READ",
9962
+ "CACHE WRITE",
9963
+ "OUTPUT"
9964
+ ], row.harnesses.map(({ name, totals: t }) => [
9965
+ name,
9966
+ number(t.total),
9967
+ number(t.input),
9968
+ number(t.cacheRead),
9969
+ number(t.cacheWrite),
9970
+ number(t.output)
9971
+ ]), [
9972
+ 1,
9973
+ 2,
9974
+ 3,
9975
+ 4,
9976
+ 5
9977
+ ]);
9978
+ else out.table([
9979
+ "MODEL ID",
9980
+ "TOTAL TOKENS",
9981
+ "SHARE",
9982
+ "CACHE READ"
9983
+ ], report.models.map(({ id, totals: t }) => [
9984
+ id ?? "(unattributed)",
9985
+ number(t.total),
9986
+ percent(t.total, report.totals.total),
9987
+ number(t.cacheRead)
9988
+ ]), [
9989
+ 1,
9990
+ 2,
9991
+ 3
9992
+ ]);
9993
+ }
9994
+ });
9764
9995
  //#endregion
9765
9996
  //#region src/cli/commands/index.ts
9766
9997
  /** Every command, in the order help and the menu list them. */
@@ -9768,54 +9999,12 @@ const commands = group({
9768
9999
  name: "oms",
9769
10000
  summary: "Manage AI coding harness providers from the terminal (ohmyswitch)",
9770
10001
  children: [
9771
- group({
9772
- name: "provider",
9773
- aliases: ["providers"],
9774
- summary: "Manage providers",
9775
- children: [
9776
- list,
9777
- show,
9778
- add,
9779
- edit,
9780
- remove,
9781
- command({
9782
- name: "move",
9783
- summary: "Move a provider in the list",
9784
- params: {
9785
- provider: providerParam(),
9786
- to: select$1({
9787
- summary: "Position",
9788
- placeholder: "position",
9789
- details: "From 1, or first or last",
9790
- empty: "There is no other position to move it to.",
9791
- choices: positionChoices
9792
- })
9793
- },
9794
- async run({ provider, to }, scope) {
9795
- const ctx = await scope.services();
9796
- const ids = ctx.providers.list().map((item) => item.id).filter((id) => id !== provider.id);
9797
- ids.splice(to, 0, provider.id);
9798
- const { harnessFailures } = await ctx.providers.reorder({ providerIds: ids });
9799
- const harnesses = await harnessIndex(scope);
9800
- return {
9801
- id: provider.id,
9802
- name: provider.name,
9803
- position: to + 1,
9804
- failures: problemsOf(harnessFailures, harnesses)
9805
- };
9806
- },
9807
- render(result, out) {
9808
- out.success(`Moved "${result.name}" to position ${result.position}.`);
9809
- warnProblems(out, result.failures);
9810
- },
9811
- failed: (result) => result.failures.length > 0
9812
- })
9813
- ]
9814
- }),
10002
+ provider,
9815
10003
  model$1,
9816
10004
  override,
9817
10005
  ...applicationCommands,
9818
10006
  harness,
10007
+ usage,
9819
10008
  plugin,
9820
10009
  paths,
9821
10010
  completion
@@ -9879,7 +10068,7 @@ function appDirs(home, env, platform) {
9879
10068
  function loadConfig() {
9880
10069
  const home = homedir();
9881
10070
  return {
9882
- version: "0.2.4",
10071
+ version: "0.3.0",
9883
10072
  dirs: appDirs(home, process.env, process.platform),
9884
10073
  home,
9885
10074
  env: { ...process.env }
@@ -9902,8 +10091,8 @@ var Output = class {
9902
10091
  this.stdout.write(`${text}\n`);
9903
10092
  }
9904
10093
  /** A table with a dimmed header row. */
9905
- table(header, rows) {
9906
- const [head, ...body] = columns([header, ...rows]);
10094
+ table(header, rows, numeric = []) {
10095
+ const [head, ...body] = columns([header, ...rows], numeric);
9907
10096
  this.print(this.paint("dim", head ?? ""));
9908
10097
  for (const line of body) this.print(line);
9909
10098
  }
@@ -13913,6 +14102,86 @@ function withOwnedFields(target, owned, values) {
13913
14102
  return result;
13914
14103
  }
13915
14104
  //#endregion
14105
+ //#region src/core/harnesses/usage/files.ts
14106
+ const object = (value) => isJsonObject(value) ? value : {};
14107
+ const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
14108
+ const modelId = (value) => typeof value === "string" && value.length ? value : null;
14109
+ const missing = (error) => error?.code === "ENOENT";
14110
+ /** Do not follow directory symlinks or discover a transcript outside the selected root. */
14111
+ async function* walkFiles(dir) {
14112
+ let entries;
14113
+ try {
14114
+ entries = await readdir(dir, { withFileTypes: true });
14115
+ } catch (error) {
14116
+ if (missing(error)) return;
14117
+ throw error;
14118
+ }
14119
+ for (const entry of entries) {
14120
+ const path = join(dir, entry.name);
14121
+ if (entry.isFile()) yield path;
14122
+ else if (entry.isDirectory()) yield* walkFiles(path);
14123
+ }
14124
+ }
14125
+ /** A complete corrupt row invalidates the file. A writer's incomplete last line can be retried on the next scan. */
14126
+ async function readJsonLines(source, visit) {
14127
+ const chunks = typeof source === "string" ? createReadStream(source) : source;
14128
+ const decoder = new StringDecoder("utf8");
14129
+ const fragments = [];
14130
+ for await (const chunk of chunks) {
14131
+ const text = decoder.write(chunk);
14132
+ let start = 0;
14133
+ for (let end = text.indexOf("\n"); end !== -1; end = text.indexOf("\n", start)) {
14134
+ fragments.push(text.slice(start, end));
14135
+ const line = fragments.join("");
14136
+ fragments.length = 0;
14137
+ if (line.trim()) visit(object(JSON.parse(line)));
14138
+ start = end + 1;
14139
+ }
14140
+ if (start < text.length) fragments.push(text.slice(start));
14141
+ }
14142
+ const tail = fragments.join("") + decoder.end();
14143
+ if (tail.trim()) {
14144
+ let row;
14145
+ try {
14146
+ row = JSON.parse(tail);
14147
+ } catch {
14148
+ return;
14149
+ }
14150
+ visit(object(row));
14151
+ }
14152
+ }
14153
+ /** Cache counters only. A new scan retires files that disappeared and re-parses changed files in full. */
14154
+ var UsageScan = class {
14155
+ cache = /* @__PURE__ */ new Map();
14156
+ records = [];
14157
+ incomplete = false;
14158
+ previous;
14159
+ constructor(previous) {
14160
+ this.previous = previous;
14161
+ }
14162
+ async file(path, parse) {
14163
+ try {
14164
+ const info = await stat(path, { bigint: true });
14165
+ const revision = [
14166
+ info.dev,
14167
+ info.ino,
14168
+ info.size,
14169
+ info.mtimeNs,
14170
+ info.ctimeNs
14171
+ ].join(":");
14172
+ const existing = this.previous.get(path);
14173
+ const entry = existing?.revision === revision ? existing : {
14174
+ revision,
14175
+ records: await parse(path)
14176
+ };
14177
+ this.cache.set(path, entry);
14178
+ for (const record of entry.records) this.records.push(record);
14179
+ } catch (error) {
14180
+ if (!missing(error)) this.incomplete = true;
14181
+ }
14182
+ }
14183
+ };
14184
+ //#endregion
13916
14185
  //#region src/core/harnesses/adapter.ts
13917
14186
  /**
13918
14187
  * A config key derived from a provider name: lowercase letters, digits and hyphens, made unique with a numeric
@@ -14103,7 +14372,7 @@ var ConfigEditor = class {
14103
14372
  //#endregion
14104
14373
  //#region src/core/harnesses/service.ts
14105
14374
  const failureMessage = (error) => error instanceof AppError ? error.message : "写入失败";
14106
- const harnessOptions = object({
14375
+ const harnessOptions = object$1({
14107
14376
  /** Home directory used to locate harness configs. */
14108
14377
  home: string(),
14109
14378
  env: record$2(string(), string().optional())
@@ -14131,7 +14400,8 @@ var HarnessService = class extends Service {
14131
14400
  if (this.registrations.has(harness.id)) throw new AppError("conflict", `已有另一个插件提供 ${harness.name}`);
14132
14401
  const registration = {
14133
14402
  harness,
14134
- running: /* @__PURE__ */ new Set()
14403
+ running: /* @__PURE__ */ new Set(),
14404
+ usageCache: /* @__PURE__ */ new Map()
14135
14405
  };
14136
14406
  return this.ctx.effect(() => {
14137
14407
  this.registrations.set(harness.id, registration);
@@ -14141,6 +14411,30 @@ var HarnessService = class extends Service {
14141
14411
  };
14142
14412
  }, `ctx.harnesses.register(${JSON.stringify(harness.id)})`);
14143
14413
  }
14414
+ async usage(days) {
14415
+ const until = /* @__PURE__ */ new Date();
14416
+ return usageReport(await Promise.all([...this.registrations.values()].map((registration) => this.track(registration.harness.id, async (harness) => {
14417
+ registration.readingUsage ??= this.scanUsage(registration).finally(() => {
14418
+ registration.readingUsage = void 0;
14419
+ });
14420
+ const scan = await registration.readingUsage;
14421
+ return {
14422
+ name: harness.name,
14423
+ records: scan.records,
14424
+ incomplete: scan.incomplete
14425
+ };
14426
+ }))), days, until);
14427
+ }
14428
+ async scanUsage(registration) {
14429
+ const scan = new UsageScan(registration.usageCache);
14430
+ try {
14431
+ await registration.harness.readUsage?.(this.environment, scan);
14432
+ } catch {
14433
+ scan.incomplete = true;
14434
+ }
14435
+ registration.usageCache = scan.cache;
14436
+ return scan;
14437
+ }
14144
14438
  /** Each harness, whether it is present on this machine, where its config is, and which endpoints it cannot serve. */
14145
14439
  list() {
14146
14440
  return Promise.all(this.harnesses().map(async (harness) => ({
@@ -14666,13 +14960,13 @@ function parseIconLinks(html, pageUrl) {
14666
14960
  const href = attrs.get("href")?.trim();
14667
14961
  if (!href) continue;
14668
14962
  if (match[1]?.toLowerCase() === "base") {
14669
- if (base === pageUrl) base = resolve(href, pageUrl) ?? pageUrl;
14963
+ if (base === pageUrl) base = resolve$1(href, pageUrl) ?? pageUrl;
14670
14964
  continue;
14671
14965
  }
14672
14966
  const rel = new Set((attrs.get("rel") ?? "").toLowerCase().split(/\s+/));
14673
14967
  const touch = rel.has("apple-touch-icon") || rel.has("apple-touch-icon-precomposed");
14674
14968
  if (!touch && !rel.has("icon")) continue;
14675
- const url = resolve(href, base);
14969
+ const url = resolve$1(href, base);
14676
14970
  if (!url) continue;
14677
14971
  icons.push({
14678
14972
  url,
@@ -14690,7 +14984,7 @@ function declaredSize(attrs, url, touch) {
14690
14984
  if (declared.length) return Math.max(...declared);
14691
14985
  return touch ? 180 : 32;
14692
14986
  }
14693
- function resolve(href, base) {
14987
+ function resolve$1(href, base) {
14694
14988
  try {
14695
14989
  const url = new URL(href, base);
14696
14990
  return url.protocol === "http:" || url.protocol === "https:" ? url.toString() : void 0;
@@ -14703,17 +14997,17 @@ function resolve(href, base) {
14703
14997
  const maxAgeMs$1 = 864e5;
14704
14998
  const timeoutMs = 15e3;
14705
14999
  /** One provider's cached icon. An entry without `icon` records that none was found, so it is not retried soon. */
14706
- const cacheEntry = object({
15000
+ const cacheEntry = object$1({
14707
15001
  version: literal(1),
14708
15002
  /** The address the icon was looked up from; a different source makes the entry obsolete. */
14709
15003
  source: string(),
14710
15004
  fetchedAt: datetime(),
14711
- icon: object({
15005
+ icon: object$1({
14712
15006
  type: _enum(iconTypes),
14713
15007
  data: base64()
14714
15008
  }).optional()
14715
15009
  });
14716
- const iconOptions = object({
15010
+ const iconOptions = object$1({
14717
15011
  /** Where provider icons are cached between runs, one file per provider. */
14718
15012
  cacheDir: string() });
14719
15013
  /**
@@ -14851,14 +15145,14 @@ async function readLimitedText(response, maxBytes) {
14851
15145
  /** Where models.dev publishes its catalog. */
14852
15146
  const modelsDevUrl = "https://models.dev/api.json";
14853
15147
  /** One models.dev entry reduced to the metadata ohmyswitch keeps. */
14854
- const catalogEntry = object({
15148
+ const catalogEntry = object$1({
14855
15149
  providerId: string(),
14856
15150
  id: string(),
14857
15151
  /** Whether the entry comes from the model's own publisher rather than a reseller. */
14858
15152
  official: boolean(),
14859
15153
  name: string().optional(),
14860
- contextWindow: number().int().positive().optional(),
14861
- maxOutput: number().int().positive().optional(),
15154
+ contextWindow: number$1().int().positive().optional(),
15155
+ maxOutput: number$1().int().positive().optional(),
14862
15156
  reasoning: boolean().optional(),
14863
15157
  reasoningOptions: array(reasoningOption).optional(),
14864
15158
  interleaved: interleaved.optional(),
@@ -15012,13 +15306,13 @@ function push(map, key, entry) {
15012
15306
  //#region src/core/models-dev/service.ts
15013
15307
  const maxAgeMs = 36e5;
15014
15308
  const maxBytes = 33554432;
15015
- const cacheFile = object({
15309
+ const cacheFile = object$1({
15016
15310
  /** Bumped whenever the reduced entry shape changes, so older caches are downloaded again. */
15017
15311
  version: literal(2),
15018
15312
  fetchedAt: datetime(),
15019
15313
  entries: array(catalogEntry)
15020
15314
  });
15021
- const modelsDevOptions = object({
15315
+ const modelsDevOptions = object$1({
15022
15316
  /** Where the reduced catalog is cached between runs. */
15023
15317
  cachePath: string() });
15024
15318
  /**
@@ -22159,6 +22453,136 @@ const dshCredentialsAdapter = {
22159
22453
  newFileMode: 384
22160
22454
  };
22161
22455
  //#endregion
22456
+ //#region src/core/harness-dsh/zstd.ts
22457
+ const decompress = promisify(zstdDecompress);
22458
+ /** DSH appends a standard Zstandard frame per batch. Walk RFC 8878 block lengths, independent of payload bytes. */
22459
+ function frameEnd(bytes, start) {
22460
+ if (bytes.length - start < 4) return void 0;
22461
+ if (bytes.readUInt32LE(start) !== 4247762216) throw new Error("Invalid DSH frame magic");
22462
+ if (bytes.length - start < 5) return void 0;
22463
+ const header = bytes.readUInt8(start + 4);
22464
+ if ((header & 24) !== 0) throw new Error("Invalid DSH frame descriptor");
22465
+ const singleSegment = (header & 32) !== 0;
22466
+ const sizeFlag = header >>> 6;
22467
+ const sizeBytes = sizeFlag === 0 ? Number(singleSegment) : 1 << sizeFlag;
22468
+ const dictionaryFlag = header & 3;
22469
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
22470
+ let offset = start + 5 + Number(!singleSegment) + dictionaryBytes + sizeBytes;
22471
+ while (offset + 3 <= bytes.length) {
22472
+ const block = bytes.readUIntLE(offset, 3);
22473
+ const kind = block >>> 1 & 3;
22474
+ if (kind === 3) throw new Error("Invalid DSH block type");
22475
+ offset += 3 + (kind === 1 ? 1 : block >>> 3);
22476
+ if (block & 1) {
22477
+ const end = offset + (header & 4 ? 4 : 0);
22478
+ return end <= bytes.length ? end : void 0;
22479
+ }
22480
+ }
22481
+ }
22482
+ /** Node 24 can silently stop at the first concatenated frame. Give the native decoder exactly one at a time. */
22483
+ async function* readSessionFrames(path) {
22484
+ const bytes = await readFile(path);
22485
+ let offset = 0;
22486
+ while (offset < bytes.length) {
22487
+ const end = frameEnd(bytes, offset);
22488
+ if (end === void 0) {
22489
+ const tail = await decompress(bytes.subarray(offset), { finishFlush: constants$1.ZSTD_e_flush });
22490
+ yield tail.subarray(0, tail.lastIndexOf(10) + 1);
22491
+ return;
22492
+ }
22493
+ yield await decompress(bytes.subarray(offset, end));
22494
+ offset = end;
22495
+ }
22496
+ }
22497
+ //#endregion
22498
+ //#region src/core/harness-dsh/usage.ts
22499
+ async function sessionUsage(path) {
22500
+ const records = [];
22501
+ let route = null;
22502
+ let last;
22503
+ let inherited = false;
22504
+ let seedLength = 0;
22505
+ await readJsonLines(path.endsWith(".zstd") ? readSessionFrames(path) : path, (event) => {
22506
+ const data = object(event.data);
22507
+ if (event.type === "session") {
22508
+ if (typeof event.version !== "number" || event.version > 4) throw new Error("Unsupported session format");
22509
+ inherited = event.isSeeded === true;
22510
+ seedLength = count(event.seedLength);
22511
+ }
22512
+ if (event.type === "request/context") route = modelId(data.model);
22513
+ if (event.type === "request/header") route = modelId(object(object(data.header).config).model) ?? route;
22514
+ if (event.type === "session/end-seed" && data.inherited === true) inherited = false;
22515
+ if (inherited || typeof event.seq === "number" && event.seq < seedLength) return;
22516
+ if (event.type === "llm/retry-started" && last && last.turn === data.turn && last.step === data.step) last = void 0;
22517
+ let sample = data.usage;
22518
+ let model = route;
22519
+ switch (event.type) {
22520
+ case "assistant/message":
22521
+ case "assistant/attempt":
22522
+ model = modelId(object(object(data.message).source).model) ?? route;
22523
+ if (!sample && Array.isArray(data.stream)) {
22524
+ const chunk = data.stream.findLast((item) => object(object(item).chunk).type === "usage");
22525
+ sample = object(object(chunk).chunk).usage;
22526
+ }
22527
+ break;
22528
+ case "assistant/chunk": {
22529
+ const chunk = object(data.chunk);
22530
+ if (chunk.type !== "usage") return;
22531
+ sample = chunk.usage;
22532
+ break;
22533
+ }
22534
+ case "compaction/summary":
22535
+ model = modelId(data.model);
22536
+ break;
22537
+ default: return;
22538
+ }
22539
+ if (!sample) return;
22540
+ const usage = object(sample);
22541
+ const input = count(usage.inputTokens);
22542
+ const output = count(usage.outputTokens);
22543
+ const cacheRead = count(usage.cacheReadTokens);
22544
+ const cacheWrite = count(usage.cacheWriteTokens);
22545
+ const total = count(usage.totalTokens) || input + output + cacheRead + cacheWrite;
22546
+ const record = {
22547
+ time: Number(event.time),
22548
+ model,
22549
+ tokens: {
22550
+ input,
22551
+ output,
22552
+ cacheRead,
22553
+ cacheWrite,
22554
+ total
22555
+ }
22556
+ };
22557
+ if (event.type === "compaction/summary") records.push(record);
22558
+ else if (last && last.turn === data.turn && last.step === data.step) records[last.index] = record;
22559
+ else {
22560
+ last = {
22561
+ turn: data.turn,
22562
+ step: data.step,
22563
+ index: records.length
22564
+ };
22565
+ records.push(record);
22566
+ }
22567
+ });
22568
+ return records;
22569
+ }
22570
+ async function readDshUsage(home, scan) {
22571
+ const files = /* @__PURE__ */ new Map();
22572
+ for await (const path of walkFiles(join(home, "sessions"))) {
22573
+ const match = /^session(?:\.v(\d+))?\.jsonl(?:\.zstd)?$/.exec(basename(path));
22574
+ if (!match) continue;
22575
+ const dir = dirname(path);
22576
+ const version = Number(match[1] ?? 0);
22577
+ const current = files.get(dir);
22578
+ if (!current || current.version < version) files.set(dir, {
22579
+ version,
22580
+ path
22581
+ });
22582
+ }
22583
+ for (const { path } of files.values()) await scan.file(path, sessionUsage);
22584
+ }
22585
+ //#endregion
22162
22586
  //#region src/core/harness-dsh/descriptor.ts
22163
22587
  const homeDir$2 = ({ home, env }) => resolveDirOverride(home, env.DSH_HOME) ?? join(home, ".dsh");
22164
22588
  /** Only the base bundle mounts `llm-pi-ai` (DSH 0.2.0-rc.2), so only profiles built on it can take providers. */
@@ -22198,6 +22622,7 @@ const DshHarnessPlugin = harnessPlugin({
22198
22622
  name: "DeepSeek Harness",
22199
22623
  homepage: "https://github.com/deepseek-ai/deepseek-harness",
22200
22624
  homeDir: homeDir$2,
22625
+ readUsage: (env, scan) => readDshUsage(homeDir$2(env), scan),
22201
22626
  async configFiles(environment) {
22202
22627
  const home = homeDir$2(environment);
22203
22628
  let homePatch;
@@ -22577,6 +23002,93 @@ const ompAdapter = {
22577
23002
  newFileMode: 384
22578
23003
  };
22579
23004
  //#endregion
23005
+ //#region src/core/harnesses/usage/sqlite.ts
23006
+ /** Lazy load SQLite so starting the CLI for unrelated commands never opens a database. */
23007
+ async function readDatabase(path, read) {
23008
+ try {
23009
+ await access(path);
23010
+ } catch (error) {
23011
+ if (missing(error)) return;
23012
+ throw error;
23013
+ }
23014
+ const { DatabaseSync } = await import("node:sqlite");
23015
+ const db = new DatabaseSync(path, { readOnly: true });
23016
+ try {
23017
+ read(db);
23018
+ } finally {
23019
+ db.close();
23020
+ }
23021
+ }
23022
+ //#endregion
23023
+ //#region src/core/harnesses/usage/transcript.ts
23024
+ /** Pi and omp share the assistant envelope but have different auxiliary usage entries. */
23025
+ async function readTranscript(path, harness, sharedDirectory = false) {
23026
+ const records = [];
23027
+ let ompSession = false;
23028
+ await readJsonLines(path, (entry) => {
23029
+ if (entry.type === "title" || entry.runtime || entry.type === "model_usage") ompSession = true;
23030
+ const message = object(entry.message);
23031
+ const assistant = entry.type === "message" && message.role === "assistant";
23032
+ const auxiliary = harness === "omp" ? entry.type === "model_usage" : entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "message" && message.role === "toolResult";
23033
+ if (!assistant && !auxiliary) return;
23034
+ const payload = entry.type === "message" ? message : entry;
23035
+ if (!payload.usage) return;
23036
+ const usage = object(payload.usage);
23037
+ const input = count(usage.input);
23038
+ const output = count(usage.output);
23039
+ const cacheRead = count(usage.cacheRead);
23040
+ const cacheWrite = count(usage.cacheWrite);
23041
+ const orchestration = object(usage.orchestration);
23042
+ const sum = input + output + cacheRead + cacheWrite;
23043
+ const total = harness === "omp" ? count(usage.totalTokens) || sum + count(orchestration.input) + count(orchestration.output) + count(orchestration.cacheRead) : sum || count(usage.totalTokens);
23044
+ if (!total) return;
23045
+ const entryTime = typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : NaN;
23046
+ const messageTime = typeof payload.timestamp === "number" ? payload.timestamp : NaN;
23047
+ const time = harness === "omp" && Number.isFinite(messageTime) ? messageTime : Number.isFinite(entryTime) ? entryTime : messageTime;
23048
+ const model = modelId(payload.responseModel) ?? modelId(payload.model);
23049
+ const identity = typeof entry.id === "string" ? JSON.stringify([entry.id, time]) : createHash("sha256").update(JSON.stringify(entry)).digest("hex");
23050
+ records.push({
23051
+ time,
23052
+ model,
23053
+ identity,
23054
+ tokens: {
23055
+ input,
23056
+ output,
23057
+ cacheRead,
23058
+ cacheWrite,
23059
+ total
23060
+ }
23061
+ });
23062
+ });
23063
+ if (sharedDirectory && ompSession !== (harness === "omp")) return [];
23064
+ return records;
23065
+ }
23066
+ //#endregion
23067
+ //#region src/core/harness-omp/usage.ts
23068
+ async function readOmpProfile(sessions, profile, shared, scan) {
23069
+ let found = false;
23070
+ for await (const path of walkFiles(sessions)) {
23071
+ if (!path.endsWith(".jsonl") || relative(sessions, path).split(sep).some((part) => part.startsWith(".omp-gc-compress-"))) continue;
23072
+ found = true;
23073
+ await scan.file(path, (file) => readTranscript(file, "omp", shared));
23074
+ }
23075
+ if (found) return;
23076
+ await readDatabase(join(profile, "stats.db"), (db) => {
23077
+ for (const row of db.prepare("SELECT entry_id,timestamp,model,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,total_tokens FROM messages").iterate()) scan.records.push({
23078
+ time: Number(row.timestamp),
23079
+ identity: JSON.stringify([row.entry_id, row.timestamp]),
23080
+ model: modelId(row.model),
23081
+ tokens: {
23082
+ input: count(row.input_tokens),
23083
+ output: count(row.output_tokens),
23084
+ cacheRead: count(row.cache_read_tokens),
23085
+ cacheWrite: count(row.cache_write_tokens),
23086
+ total: count(row.total_tokens)
23087
+ }
23088
+ });
23089
+ });
23090
+ }
23091
+ //#endregion
22580
23092
  //#region src/core/harness-omp/descriptor.ts
22581
23093
  /** omp's config root: `PI_CONFIG_DIR` (default `.omp`), always under the home directory. */
22582
23094
  const configRoot = ({ home, env }) => join(home, env.PI_CONFIG_DIR || ".omp");
@@ -22620,6 +23132,33 @@ const OmpHarnessPlugin = harnessPlugin({
22620
23132
  name: "omp",
22621
23133
  homepage: "https://omp.sh",
22622
23134
  homeDir: configRoot,
23135
+ async readUsage(environment, scan) {
23136
+ const root = configRoot(environment);
23137
+ const main = defaultAgentDir(environment);
23138
+ const xdg = environment.env.XDG_DATA_HOME;
23139
+ const xdgRoot = xdg && isAbsolute(xdg) && process.platform !== "win32" ? join(xdg, "omp") : void 0;
23140
+ const profiles = /* @__PURE__ */ new Set();
23141
+ for (const base of [root, xdgRoot]) {
23142
+ if (!base) continue;
23143
+ try {
23144
+ for (const entry of await readdir(join(base, "profiles"), { withFileTypes: true })) if (entry.isDirectory() && profileName.test(entry.name) && !entry.name.endsWith(".")) profiles.add(entry.name);
23145
+ } catch (error) {
23146
+ if (error.code !== "ENOENT") throw error;
23147
+ }
23148
+ }
23149
+ for (const name of [null, ...profiles]) {
23150
+ const profile = name ? join(root, "profiles", name) : root;
23151
+ const agent = name ? join(profile, "agent") : main;
23152
+ const shared = !name && isAbsolute(environment.env.PI_CODING_AGENT_DIR ?? "");
23153
+ const xdgProfile = xdgRoot && (name ? join(xdgRoot, "profiles", name) : xdgRoot);
23154
+ const useXdg = agent === join(profile, "agent") && xdgProfile && await isDirectory(xdgProfile);
23155
+ try {
23156
+ await readOmpProfile(join(useXdg ? xdgProfile : agent, "sessions"), useXdg ? xdgProfile : profile, shared && !useXdg, scan);
23157
+ } catch {
23158
+ scan.incomplete = true;
23159
+ }
23160
+ }
23161
+ },
22623
23162
  async configFiles(environment) {
22624
23163
  const agentDirs = await profileAgentDirs(configRoot(environment));
22625
23164
  const main = defaultAgentDir(environment);
@@ -22955,6 +23494,61 @@ const openCodeAdapter = {
22955
23494
  newFileMode: 384
22956
23495
  };
22957
23496
  //#endregion
23497
+ //#region src/core/harness-opencode/usage.ts
23498
+ const legacyMessages = `
23499
+ SELECT time_created, json_extract(data, '$.modelID'), json_extract(data, '$.tokens')
23500
+ FROM message
23501
+ WHERE json_extract(data, '$.role') = 'assistant' AND json_extract(data, '$.time.completed') IS NOT NULL`;
23502
+ const messages = `
23503
+ SELECT m.time_created, json_extract(m.data, '$.model.id'), json_extract(m.data, '$.tokens')
23504
+ FROM session_message m JOIN session_v2 s ON s.id = m.session_id
23505
+ WHERE (s.fork_session_id IS NULL OR m.time_created >= s.time_created)
23506
+ AND ((m.type = 'assistant' AND json_extract(m.data, '$.time.completed') IS NOT NULL)
23507
+ OR (m.type = 'compaction' AND json_extract(m.data, '$.status') IN ('completed', 'failed')))`;
23508
+ const auxiliaryEvents = `
23509
+ SELECT e.created, NULL, json_extract(e.data, '$.tokens')
23510
+ FROM event e JOIN session_v2 s ON s.id = e.aggregate_id
23511
+ WHERE e.type = 'session.usage.recorded.1'
23512
+ AND (s.fork_session_id IS NULL OR e.created >= s.time_created)
23513
+ AND (json_extract(e.data, '$.source') = 'title'
23514
+ OR (json_extract(e.data, '$.source') = 'compaction' AND NOT EXISTS (
23515
+ SELECT 1 FROM session_message m WHERE m.session_id = s.id AND m.type = 'compaction'
23516
+ AND e.created BETWEEN m.time_created AND m.time_updated
23517
+ AND json_extract(m.data, '$.status') IN ('completed', 'failed')
23518
+ AND json_type(m.data, '$.tokens') = 'object'
23519
+ )))`;
23520
+ async function readOpenCodeUsage({ home, env }, scan) {
23521
+ if (env.OPENCODE_DB === ":memory:") return;
23522
+ const data = join(resolveDirOverride(home, env.XDG_DATA_HOME) ?? join(home, ".local", "share"), "opencode");
23523
+ await readDatabase(resolve(data, env.OPENCODE_DB || "opencode.db"), (db) => {
23524
+ const tables = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map((row) => row.name));
23525
+ const v2 = tables.has("session_v2") && tables.has("session_message");
23526
+ const sources = v2 ? [messages] : [legacyMessages];
23527
+ if (v2 && tables.has("event")) sources.push(auxiliaryEvents);
23528
+ const query = db.prepare(`WITH usage(time, model, tokens) AS (${sources.join(" UNION ALL ")})
23529
+ SELECT time, model, json_extract(tokens,'$.input') AS input, json_extract(tokens,'$.output') AS output,
23530
+ json_extract(tokens,'$.reasoning') AS reasoning, json_extract(tokens,'$.cache.read') AS cacheRead,
23531
+ json_extract(tokens,'$.cache.write') AS cacheWrite FROM usage WHERE tokens IS NOT NULL`);
23532
+ for (const row of query.iterate()) {
23533
+ const input = count(row.input);
23534
+ const output = count(row.output) + count(row.reasoning);
23535
+ const cacheRead = count(row.cacheRead);
23536
+ const cacheWrite = count(row.cacheWrite);
23537
+ scan.records.push({
23538
+ time: Number(row.time),
23539
+ model: modelId(row.model),
23540
+ tokens: {
23541
+ input,
23542
+ output,
23543
+ cacheRead,
23544
+ cacheWrite,
23545
+ total: input + output + cacheRead + cacheWrite
23546
+ }
23547
+ });
23548
+ }
23549
+ });
23550
+ }
23551
+ //#endregion
22958
23552
  //#region src/core/harness-opencode/descriptor.ts
22959
23553
  function homeDir$1({ home, env }) {
22960
23554
  const xdg = env.XDG_CONFIG_HOME;
@@ -22968,6 +23562,7 @@ const OpenCodeHarnessPlugin = harnessPlugin({
22968
23562
  name: "OpenCode",
22969
23563
  homepage: "https://opencode.ai",
22970
23564
  homeDir: homeDir$1,
23565
+ readUsage: readOpenCodeUsage,
22971
23566
  async configFiles(environment) {
22972
23567
  const dir = homeDir$1(environment);
22973
23568
  return [{
@@ -23232,6 +23827,18 @@ const piAdapter = {
23232
23827
  newFileMode: 384
23233
23828
  };
23234
23829
  //#endregion
23830
+ //#region src/core/harness-pi/usage.ts
23831
+ async function readPiUsage(agent, { home, env }, scan) {
23832
+ let configured = env.PI_CODING_AGENT_SESSION_DIR;
23833
+ if (!configured) {
23834
+ const settings = await readTextIfExists(join(agent, "settings.json"));
23835
+ configured = object(parseJsonc(settings ?? "{}")).sessionDir;
23836
+ }
23837
+ const root = resolveDirOverride(home, typeof configured === "string" ? configured : void 0) ?? join(agent, "sessions");
23838
+ const shared = isAbsolute(env.PI_CODING_AGENT_DIR ?? "") && root === join(agent, "sessions");
23839
+ for await (const path of walkFiles(root)) if (path.endsWith(".jsonl")) await scan.file(path, (file) => readTranscript(file, "pi", shared));
23840
+ }
23841
+ //#endregion
23235
23842
  //#region src/core/harness-pi/descriptor.ts
23236
23843
  const homeDir = ({ home, env }) => resolveDirOverride(home, env.PI_CODING_AGENT_DIR) ?? join(home, ".pi", "agent");
23237
23844
  //#endregion
@@ -23244,6 +23851,7 @@ const builtinPlugins = [
23244
23851
  name: "Pi",
23245
23852
  homepage: "https://pi.dev",
23246
23853
  homeDir,
23854
+ readUsage: (env, scan) => readPiUsage(homeDir(env), env, scan),
23247
23855
  configFiles: async (environment) => [{
23248
23856
  path: join(homeDir(environment), "models.json"),
23249
23857
  adapter: piAdapter
@@ -26795,13 +27403,13 @@ const catalogStyles = {
26795
27403
  const maxPages = 50;
26796
27404
  const maxModels = 2e3;
26797
27405
  const maxPageBytes = 4194304;
26798
- const tokenLimit = number().int().positive().optional().catch(void 0);
27406
+ const tokenLimit = number$1().int().positive().optional().catch(void 0);
26799
27407
  const optionalText = string().optional().catch(void 0);
26800
- const openaiPage = object({ data: array(looseObject({
27408
+ const openaiPage = object$1({ data: array(looseObject({
26801
27409
  id: string(),
26802
27410
  context_length: tokenLimit
26803
27411
  })) });
26804
- const anthropicPage = object({
27412
+ const anthropicPage = object$1({
26805
27413
  data: array(looseObject({
26806
27414
  id: string(),
26807
27415
  display_name: optionalText,
@@ -26811,7 +27419,7 @@ const anthropicPage = object({
26811
27419
  has_more: boolean().optional(),
26812
27420
  last_id: string().nullish()
26813
27421
  });
26814
- const googlePage = object({
27422
+ const googlePage = object$1({
26815
27423
  models: array(looseObject({
26816
27424
  name: string(),
26817
27425
  displayName: optionalText,
@@ -27430,7 +28038,7 @@ var ProviderService = class extends Service {
27430
28038
  };
27431
28039
  //#endregion
27432
28040
  //#region src/core/store/store.ts
27433
- const storeFile = object({
28041
+ const storeFile = object$1({
27434
28042
  version: literal(6),
27435
28043
  providers: array(storedProvider),
27436
28044
  modelOverrides: record$2(string().min(1).max(256), modelOverride)
@@ -27580,7 +28188,7 @@ var Store = class {
27580
28188
  };
27581
28189
  //#endregion
27582
28190
  //#region src/core/store/service.ts
27583
- const storeOptions = object({
28191
+ const storeOptions = object$1({
27584
28192
  /** The directory that holds `store.json`. */
27585
28193
  dataDir: string(),
27586
28194
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ohmyswitch",
3
- "version": "0.2.4",
3
+ "version": "0.3.0",
4
4
  "description": "Provider-first config manager for AI coding harnesses",
5
5
  "license": "MIT",
6
6
  "repository": {