@ycodium-ai/agent-opencode 0.2.2690 → 0.2.2696

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.
package/README.md CHANGED
@@ -17,6 +17,16 @@ Facts:
17
17
  `turnSteering: true`.
18
18
  - Auth is inferred from the connected-provider inventory, not a credential
19
19
  file. `credentialSources` is empty.
20
+ - Usage (ADR-0034): quota only for the OpenCode Go plan, read only when the user asks
21
+ (`src/openCodeQuota.ts`). `GET https://opencode.ai/zen/go/v1/usage` through `host.fetch` with a
22
+ 5 second timeout, returning `{ usage: { rolling, weekly, monthly } }` (rolling is 5 hours, weekly 7
23
+ days, monthly has no length). The key is the `opencode-go` entry of `auth.json` when it is
24
+ `{ type: "api", key }`, else `OPENCODE_API_KEY`; a non-empty `OPENCODE_AUTH_CONTENT` replaces the
25
+ file. Environment variables come from the instance environment first, then the process.
26
+ `auth.json` is `<XDG_DATA_HOME>/opencode/auth.json` (instance environment, then the account
27
+ directory's `data`, then the process), else `.local/share` under `HOME` (`USERPROFILE` on
28
+ Windows). An instance with a server URL reads nothing locally and goes nowhere; a 403 means no Go
29
+ subscription. Both read as `unsupportedLogin`. Tokens still go through the orchestration ledger.
20
30
 
21
31
  Develop with `vp run --filter @ycodium-ai/agent-opencode typecheck`, `build`, and `test`.
22
32
 
package/dist/index.js CHANGED
@@ -1622,15 +1622,154 @@ function mapPermissionDecision(reply) {
1622
1622
  }
1623
1623
  }
1624
1624
 
1625
+ // src/openCodeQuota.ts
1626
+ import * as NodeCrypto from "node:crypto";
1627
+ import * as NodeFSP3 from "node:fs/promises";
1628
+ import * as NodeOS3 from "node:os";
1629
+ import * as NodePath4 from "node:path";
1630
+ import { mergeLaunchEnv } from "@ycodium-ai/plugin-api";
1631
+ import {
1632
+ parseRetryAfterMs
1633
+ } from "@ycodium-ai/plugin-api/usage";
1634
+ var OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
1635
+ var QUOTA_TIMEOUT_MS = 5e3;
1636
+ var GO_AUTH_ENTRY = "opencode-go";
1637
+ var GO_KEY_ENV = "OPENCODE_API_KEY";
1638
+ var AUTH_CONTENT_ENV = "OPENCODE_AUTH_CONTENT";
1639
+ var HOUR_MS = 60 * 60 * 1e3;
1640
+ var asObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
1641
+ var nonBlank = (value) => {
1642
+ const trimmed = typeof value === "string" ? value.trim() : "";
1643
+ return trimmed.length > 0 ? trimmed : null;
1644
+ };
1645
+ var parseJson = (raw) => {
1646
+ try {
1647
+ return JSON.parse(raw);
1648
+ } catch {
1649
+ return null;
1650
+ }
1651
+ };
1652
+ var clampPercent = (value) => Math.min(100, Math.max(0, value));
1653
+ var WINDOW_SPECS = [
1654
+ { id: "rolling", windowMs: 5 * HOUR_MS },
1655
+ { id: "weekly", windowMs: 7 * 24 * HOUR_MS },
1656
+ { id: "monthly" }
1657
+ ];
1658
+ var openCodeQuotaWindows = (body) => {
1659
+ const usage = asObject(asObject(body)?.["usage"]);
1660
+ if (usage === null) return null;
1661
+ const windows = [];
1662
+ for (const spec of WINDOW_SPECS) {
1663
+ const entry = asObject(usage[spec.id]);
1664
+ const percent = entry?.["percent"];
1665
+ const resetsAt = nonBlank(entry?.["resetsAt"]);
1666
+ if (typeof percent !== "number" || !Number.isFinite(percent)) return null;
1667
+ if (resetsAt === null || Number.isNaN(Date.parse(resetsAt))) return null;
1668
+ windows.push({
1669
+ id: spec.id,
1670
+ label: { key: `usage.window.${spec.id}` },
1671
+ usedPercent: clampPercent(percent),
1672
+ resetsAt,
1673
+ ...spec.windowMs === void 0 ? {} : { windowMs: spec.windowMs }
1674
+ });
1675
+ }
1676
+ return windows;
1677
+ };
1678
+ var extractOpenCodeGoKey = (auth) => {
1679
+ const entry = asObject(asObject(auth)?.[GO_AUTH_ENTRY]);
1680
+ if (entry === null || entry["type"] !== "api") return null;
1681
+ return nonBlank(entry["key"]);
1682
+ };
1683
+ var openCodeUserHome = (env, windows) => nonBlank(env[windows ? "USERPROFILE" : "HOME"]) ?? NodeOS3.homedir();
1684
+ var openCodeAuthPath = (env, windows) => {
1685
+ const dataHome = nonBlank(env["XDG_DATA_HOME"]) ?? NodePath4.join(openCodeUserHome(env, windows), ".local", "share");
1686
+ return NodePath4.join(dataHome, "opencode", "auth.json");
1687
+ };
1688
+ var readTextOrNull = async (path) => {
1689
+ try {
1690
+ return await NodeFSP3.readFile(path, "utf8");
1691
+ } catch {
1692
+ return null;
1693
+ }
1694
+ };
1695
+ var createOpenCodeUsage = (input) => {
1696
+ const now = input.now ?? Date.now;
1697
+ const readTextFile = input.readTextFile ?? readTextOrNull;
1698
+ const timeoutMs = input.timeoutMs ?? QUOTA_TIMEOUT_MS;
1699
+ const xdg = resolveOpenCodeXdgPaths(input.homePath);
1700
+ const env = mergeLaunchEnv({
1701
+ inherited: input.processEnv ?? process.env,
1702
+ accountHome: xdg === void 0 ? void 0 : { XDG_DATA_HOME: xdg.dataHome },
1703
+ instanceTable: input.environment
1704
+ });
1705
+ const authPath = openCodeAuthPath(env, input.windows ?? NodeOS3.type() === "Windows_NT");
1706
+ const digestOf = (key) => NodeCrypto.createHash("sha256").update(key).digest("hex").slice(0, 12);
1707
+ const resolveKey = async () => {
1708
+ const authContent = nonBlank(env[AUTH_CONTENT_ENV]);
1709
+ const authKey = authContent !== null ? extractOpenCodeGoKey(parseJson(authContent)) : extractOpenCodeGoKey(parseJson(await readTextFile(authPath) ?? ""));
1710
+ if (authKey !== null) {
1711
+ return {
1712
+ key: authKey,
1713
+ accountKey: authContent !== null ? `env:${AUTH_CONTENT_ENV}:${digestOf(authKey)}` : authPath
1714
+ };
1715
+ }
1716
+ const fromEnv = nonBlank(env[GO_KEY_ENV]);
1717
+ return fromEnv === null ? null : { key: fromEnv, accountKey: `env:${GO_KEY_ENV}:${digestOf(fromEnv)}` };
1718
+ };
1719
+ const readQuota = async (request) => {
1720
+ if (input.serverUrl.trim().length > 0) {
1721
+ return { status: "unavailable", reason: "unsupportedLogin" };
1722
+ }
1723
+ const credential = await resolveKey();
1724
+ if (credential === null) return { status: "unavailable", reason: "missingCredentials" };
1725
+ const signal = AbortSignal.any([
1726
+ ...request.signal === void 0 ? [] : [request.signal],
1727
+ AbortSignal.timeout(timeoutMs)
1728
+ ]);
1729
+ let response;
1730
+ let text = "";
1731
+ try {
1732
+ response = await input.fetch(OPENCODE_GO_USAGE_URL, {
1733
+ headers: { Authorization: `Bearer ${credential.key}`, Accept: "application/json" },
1734
+ signal
1735
+ });
1736
+ if (response.ok) text = await response.text();
1737
+ } catch {
1738
+ return { status: "unavailable", reason: "unreachable" };
1739
+ }
1740
+ if (response.status === 401) return { status: "unavailable", reason: "authRejected" };
1741
+ if (response.status === 403) return { status: "unavailable", reason: "unsupportedLogin" };
1742
+ if (response.status === 429) {
1743
+ const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"), now());
1744
+ return {
1745
+ status: "unavailable",
1746
+ reason: "rateLimited",
1747
+ ...retryAfterMs === null ? {} : { retryAfterMs }
1748
+ };
1749
+ }
1750
+ if (!response.ok) return { status: "unavailable", reason: "unreachable" };
1751
+ const windows = openCodeQuotaWindows(parseJson(text));
1752
+ if (windows === null) return { status: "unavailable", reason: "unreachable" };
1753
+ return {
1754
+ status: "available",
1755
+ plan: "Go",
1756
+ windows,
1757
+ balances: [],
1758
+ accountKey: credential.accountKey
1759
+ };
1760
+ };
1761
+ return { readQuota };
1762
+ };
1763
+
1625
1764
  // src/probe.ts
1626
- import * as NodeOS4 from "node:os";
1765
+ import * as NodeOS5 from "node:os";
1627
1766
  import {
1628
1767
  ExecutorSpawnRefusedError as ExecutorSpawnRefusedError2
1629
1768
  } from "@ycodium-ai/plugin-api/executor";
1630
1769
 
1631
1770
  // src/server.ts
1632
1771
  import * as NodeNet from "node:net";
1633
- import * as NodeOS3 from "node:os";
1772
+ import * as NodeOS4 from "node:os";
1634
1773
 
1635
1774
  // ../../node_modules/.pnpm/@opencode-ai+sdk@1.18.31/node_modules/@opencode-ai/sdk/dist/v2/gen/core/serverSentEvents.gen.js
1636
1775
  var createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) => {
@@ -2019,7 +2158,7 @@ var getParseAs = (contentType) => {
2019
2158
  if (cleanContent === "multipart/form-data") {
2020
2159
  return "formData";
2021
2160
  }
2022
- if (["application/", "audio/", "image/", "video/"].some((type2) => cleanContent.startsWith(type2))) {
2161
+ if (["application/", "audio/", "image/", "video/"].some((type3) => cleanContent.startsWith(type3))) {
2023
2162
  return "blob";
2024
2163
  }
2025
2164
  if (cleanContent.startsWith("text/")) {
@@ -7038,7 +7177,7 @@ var import_cross_spawn = __toESM(require_cross_spawn(), 1);
7038
7177
  // src/server.ts
7039
7178
  import {
7040
7179
  ExecutorSpawnRefusedError,
7041
- mergeLaunchEnv
7180
+ mergeLaunchEnv as mergeLaunchEnv2
7042
7181
  } from "@ycodium-ai/plugin-api/executor";
7043
7182
 
7044
7183
  // src/cliParse.ts
@@ -7194,7 +7333,7 @@ async function findAvailablePort() {
7194
7333
  }
7195
7334
  function buildSpawnEnv(recipe) {
7196
7335
  const xdgHome = makeOpenCodeEnvironment(recipe.homePath, {});
7197
- return mergeLaunchEnv({
7336
+ return mergeLaunchEnv2({
7198
7337
  accountHome: xdgHome,
7199
7338
  instanceTable: recipe.environment,
7200
7339
  handOverrides: {
@@ -7219,7 +7358,7 @@ async function terminateOwnedProcess(handle) {
7219
7358
  await handle.kill("SIGKILL");
7220
7359
  } catch {
7221
7360
  }
7222
- if (NodeOS3.type() !== "Windows_NT" && handle.pid > 0) {
7361
+ if (NodeOS4.type() !== "Windows_NT" && handle.pid > 0) {
7223
7362
  try {
7224
7363
  process.kill(-handle.pid, "SIGKILL");
7225
7364
  } catch {
@@ -7602,7 +7741,7 @@ ${result.stderr}`);
7602
7741
  }
7603
7742
  const skillsClient = createOpenCodeSdkClient({
7604
7743
  url: handle.url,
7605
- directory: NodeOS4.homedir(),
7744
+ directory: NodeOS5.homedir(),
7606
7745
  password: handle.password
7607
7746
  });
7608
7747
  const inventory2 = await loadOpenCodeInventory(client2, skillsClient);
@@ -7635,7 +7774,7 @@ ${result.stderr}`);
7635
7774
  host: input.host,
7636
7775
  recipe: input.recipe,
7637
7776
  program,
7638
- skillsCwd: NodeOS4.homedir()
7777
+ skillsCwd: NodeOS5.homedir()
7639
7778
  });
7640
7779
  const skills = flattenOpenCodeSkills(inventory.skills);
7641
7780
  const connectedCount = inventory.providerList.connected.length;
@@ -7672,6 +7811,84 @@ ${result.stderr}`);
7672
7811
  }
7673
7812
  }
7674
7813
 
7814
+ // src/workspaceInventory.ts
7815
+ import * as NodePath5 from "node:path";
7816
+ var isInside = (directory, file) => {
7817
+ const relative2 = NodePath5.relative(directory, file);
7818
+ return relative2.length > 0 && !relative2.startsWith("..") && !NodePath5.isAbsolute(relative2);
7819
+ };
7820
+ var openCodeInventoryFromClient = async (client2, cwd) => {
7821
+ const [skillsResult, commandsResult] = await Promise.allSettled([
7822
+ client2.app.skills(),
7823
+ client2.command.list()
7824
+ ]);
7825
+ if (skillsResult.status === "rejected" && commandsResult.status === "rejected") {
7826
+ throw skillsResult.reason instanceof Error ? skillsResult.reason : new Error("OpenCode inventory could not be read");
7827
+ }
7828
+ const watched = /* @__PURE__ */ new Set([
7829
+ NodePath5.join(cwd, ".opencode"),
7830
+ NodePath5.join(cwd, "opencode.json"),
7831
+ ...["command", "commands", "skill", "skills"].map(
7832
+ (name) => NodePath5.join(cwd, ".opencode", name)
7833
+ )
7834
+ ]);
7835
+ let skills;
7836
+ if (skillsResult.status === "fulfilled") {
7837
+ skills = flattenOpenCodeSkills(
7838
+ (skillsResult.value.data ?? []).map((skill) => ({
7839
+ ...skill.name === void 0 ? {} : { name: skill.name },
7840
+ ...skill.description === void 0 ? {} : { description: skill.description },
7841
+ ...skill.location === void 0 ? {} : { location: skill.location }
7842
+ }))
7843
+ ).map((skill) => ({
7844
+ ...skill,
7845
+ scope: isInside(cwd, skill.path) ? "project" : "user"
7846
+ }));
7847
+ for (const skill of skills) {
7848
+ watched.add(skill.path);
7849
+ watched.add(NodePath5.dirname(skill.path));
7850
+ watched.add(NodePath5.dirname(NodePath5.dirname(skill.path)));
7851
+ }
7852
+ }
7853
+ let slashCommands;
7854
+ if (commandsResult.status === "fulfilled") {
7855
+ slashCommands = (commandsResult.value.data ?? []).filter((command) => command.source !== "skill").map((command) => {
7856
+ const hint = (command.hints ?? []).join(" ").trim();
7857
+ return {
7858
+ name: command.name,
7859
+ ...command.description === void 0 ? {} : { description: command.description },
7860
+ ...hint.length === 0 ? {} : { input: { hint } }
7861
+ };
7862
+ });
7863
+ }
7864
+ return {
7865
+ ...slashCommands === void 0 ? {} : { slashCommands },
7866
+ ...skills === void 0 ? {} : { skills },
7867
+ watchPaths: [...watched]
7868
+ };
7869
+ };
7870
+ var loadOpenCodeWorkspaceInventory = async (input) => {
7871
+ const handle = await connectToOpenCodeServer({
7872
+ host: input.host,
7873
+ recipe: input.recipe,
7874
+ directory: input.cwd,
7875
+ program: input.recipe.binaryPath
7876
+ });
7877
+ try {
7878
+ const client2 = createOpenCodeSdkClient({
7879
+ url: handle.url,
7880
+ directory: input.cwd,
7881
+ password: handle.password
7882
+ });
7883
+ return await openCodeInventoryFromClient(
7884
+ client2,
7885
+ input.cwd
7886
+ );
7887
+ } finally {
7888
+ await closeOpenCodeServer(handle);
7889
+ }
7890
+ };
7891
+
7675
7892
  // src/question.ts
7676
7893
  function openCodeQuestionId(index, question) {
7677
7894
  const header = question.header.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
@@ -7822,7 +8039,7 @@ function readOpenCodeMessageUsage(info) {
7822
8039
  function takeTurnUsage(usageByMessageId, sessionId) {
7823
8040
  const entries = Array.from(usageByMessageId.values());
7824
8041
  usageByMessageId.clear();
7825
- const last = entries.at(-1);
8042
+ const last = entries.findLast((entry) => entry.child !== true) ?? entries.at(-1);
7826
8043
  if (!last) {
7827
8044
  return void 0;
7828
8045
  }
@@ -7860,7 +8077,7 @@ function withoutActiveTurn(session) {
7860
8077
  void activeTurnId;
7861
8078
  return rest;
7862
8079
  }
7863
- function emitEvent(events, context, type2, payload, extra) {
8080
+ function emitEvent(events, context, type3, payload, extra) {
7864
8081
  const turnId = extra?.turnId ?? context.session.activeTurnId;
7865
8082
  const event = {
7866
8083
  eventId: randomUUID(),
@@ -7868,7 +8085,7 @@ function emitEvent(events, context, type2, payload, extra) {
7868
8085
  ...context.session.providerInstanceId ? { providerInstanceId: context.session.providerInstanceId } : {},
7869
8086
  threadId: context.threadId,
7870
8087
  createdAt: nowIso(),
7871
- type: type2,
8088
+ type: type3,
7872
8089
  payload,
7873
8090
  ...turnId ? { turnId } : {},
7874
8091
  ...extra?.itemId ? { itemId: extra.itemId } : {},
@@ -8223,6 +8440,25 @@ async function handleOtherSessionEvent(input) {
8223
8440
  }
8224
8441
  return;
8225
8442
  }
8443
+ case "message.updated": {
8444
+ const usage = readOpenCodeMessageUsage(event.properties.info);
8445
+ if (usage === void 0 || context.session.activeTurnId === void 0) return;
8446
+ let related;
8447
+ try {
8448
+ related = await isRelatedSession(context, event.properties.sessionID);
8449
+ } catch {
8450
+ return;
8451
+ }
8452
+ if (!related || context.session.activeTurnId === void 0) return;
8453
+ context.usageByMessageId.set(event.properties.info.id, { ...usage, child: true });
8454
+ return;
8455
+ }
8456
+ case "message.removed": {
8457
+ if (context.usageByMessageId.get(event.properties.messageID)?.child === true) {
8458
+ context.usageByMessageId.delete(event.properties.messageID);
8459
+ }
8460
+ return;
8461
+ }
8226
8462
  default:
8227
8463
  return;
8228
8464
  }
@@ -9268,6 +9504,11 @@ function createOpenCodeInstance(config, host, attachments) {
9268
9504
  host,
9269
9505
  ...signal ? { signal } : {}
9270
9506
  }),
9507
+ // 项目里的命令与技能:探测在 home 下列,只看得到整机的;这里把 server 的工作目录设成项目再读。
9508
+ workspaceInventory: ({ cwd }) => {
9509
+ if (disposed) return Promise.reject(new Error("OpenCode instance has been disposed."));
9510
+ return loadOpenCodeWorkspaceInventory({ host, recipe, cwd });
9511
+ },
9271
9512
  startSession: async (input, _signal) => {
9272
9513
  if (disposed) throw new Error("OpenCode instance has been disposed.");
9273
9514
  const existing = sessions.get(input.threadId);
@@ -9620,6 +9861,13 @@ function createOpenCodeInstance(config, host, attachments) {
9620
9861
  return { threadId, turns };
9621
9862
  },
9622
9863
  events,
9864
+ // 额度:OpenCode Go 套餐,读这个实例自己的 key(连外部服务器的实例不读本机);token 仍走编排账本。
9865
+ usage: createOpenCodeUsage({
9866
+ homePath: recipe.homePath,
9867
+ serverUrl: recipe.serverUrl,
9868
+ environment: recipe.environment,
9869
+ fetch: host.fetch
9870
+ }),
9623
9871
  continuationKey: makeOpenCodeContinuationGroupKey(recipe),
9624
9872
  dispose: async () => {
9625
9873
  if (disposal) return disposal;
package/locales/en.json CHANGED
@@ -20,5 +20,12 @@
20
20
  "description": "Where this account's login and history live. Leave empty to use the CLI's default.",
21
21
  "placeholder": "e.g. ~/.opencode-work"
22
22
  }
23
+ },
24
+ "usage": {
25
+ "window": {
26
+ "rolling": "Rolling",
27
+ "weekly": "Weekly",
28
+ "monthly": "Monthly"
29
+ }
23
30
  }
24
31
  }
@@ -20,5 +20,12 @@
20
20
  "description": "此账户的登录信息与历史记录所在的目录。留空则使用该命令行工具的默认目录。",
21
21
  "placeholder": "例如 ~/.opencode-work"
22
22
  }
23
+ },
24
+ "usage": {
25
+ "window": {
26
+ "rolling": "滚动",
27
+ "weekly": "每周",
28
+ "monthly": "每月"
29
+ }
23
30
  }
24
31
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ycodium-ai/agent-opencode",
3
- "version": "0.2.2690",
3
+ "version": "0.2.2696",
4
4
  "description": "OpenCode executor: OpenCode CLI via @opencode-ai/sdk/v2.",
5
5
  "keywords": [
6
6
  "ycodium",
@@ -24,7 +24,7 @@
24
24
  "@types/node": "24.12.4",
25
25
  "esbuild": "0.28.1",
26
26
  "vite-plus": "0.2.2",
27
- "@ycodium-ai/plugin-api": "0.2.2690",
27
+ "@ycodium-ai/plugin-api": "0.2.2696",
28
28
  "ycodium-executor-testing": "0.0.0"
29
29
  },
30
30
  "ycodium": {