@neuralnomads/codenomad-dev 0.20.0-dev-20260930-47f9e43e → 0.20.0-dev-20261001-77692a73

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 (116) hide show
  1. package/dist/opencode/runtime-support.js +1 -1
  2. package/dist/opencode/runtime-support.js.map +1 -1
  3. package/dist/opencode/runtime-support.test.js +2 -2
  4. package/dist/opencode/runtime-support.test.js.map +1 -1
  5. package/dist/opencode-update/service.test.js +7 -7
  6. package/dist/opencode-update/service.test.js.map +1 -1
  7. package/dist/plugins/session-pruning/plugin.mjs +43 -17
  8. package/dist/server/__tests__/instance-proxy.test.js +54 -0
  9. package/dist/server/__tests__/instance-proxy.test.js.map +1 -1
  10. package/dist/server/http-server.js +4 -2
  11. package/dist/server/http-server.js.map +1 -1
  12. package/dist/server/routes/usage.js +79 -9
  13. package/dist/server/routes/usage.js.map +1 -1
  14. package/dist/server/routes/usage.test.js +123 -15
  15. package/dist/server/routes/usage.test.js.map +1 -1
  16. package/dist/usage/native-codex.js +156 -0
  17. package/dist/usage/native-codex.js.map +1 -0
  18. package/dist/usage/native-codex.test.js +282 -0
  19. package/dist/usage/native-codex.test.js.map +1 -0
  20. package/dist/usage/providers/oauth.js +4 -63
  21. package/dist/usage/providers/oauth.js.map +1 -1
  22. package/dist/usage/providers/oauth.test.js +16 -145
  23. package/dist/usage/providers/oauth.test.js.map +1 -1
  24. package/package.json +3 -3
  25. package/public/assets/App-Dvv4o4u-.js +58 -0
  26. package/public/assets/App-Dvv4o4u-.js.map +1 -0
  27. package/public/assets/{FilesTab-D8siBvjz.js → FilesTab-CFpB8-UT.js} +3 -3
  28. package/public/assets/{FilesTab-D8siBvjz.js.map → FilesTab-CFpB8-UT.js.map} +1 -1
  29. package/public/assets/{GitChangesTab-vQDkJfb1.js → GitChangesTab-Ja_lgE6e.js} +3 -3
  30. package/public/assets/{GitChangesTab-vQDkJfb1.js.map → GitChangesTab-Ja_lgE6e.js.map} +1 -1
  31. package/public/assets/{SplitFilePanel-45-ssHhd.js → SplitFilePanel-DKwsYniw.js} +2 -2
  32. package/public/assets/{SplitFilePanel-45-ssHhd.js.map → SplitFilePanel-DKwsYniw.js.map} +1 -1
  33. package/public/assets/StatusTab-F_tE6JAk.js +2 -0
  34. package/public/assets/StatusTab-F_tE6JAk.js.map +1 -0
  35. package/public/assets/{align-justify-DjlaBdyk.js → align-justify-CqbeVF_-.js} +2 -2
  36. package/public/assets/{align-justify-DjlaBdyk.js.map → align-justify-CqbeVF_-.js.map} +1 -1
  37. package/public/assets/{bundle-full-DpHg2UyZ.js → bundle-full-Cjco7aMi.js} +2 -2
  38. package/public/assets/{bundle-full-DpHg2UyZ.js.map → bundle-full-Cjco7aMi.js.map} +1 -1
  39. package/public/assets/{client-state-C2XNu_km.js → client-state-Bof46kOm.js} +2 -2
  40. package/public/assets/{client-state-C2XNu_km.js.map → client-state-Bof46kOm.js.map} +1 -1
  41. package/public/assets/{diff-viewer-CiYhl2x9.js → diff-viewer-CWNLAnfM.js} +2 -2
  42. package/public/assets/{diff-viewer-CiYhl2x9.js.map → diff-viewer-CWNLAnfM.js.map} +1 -1
  43. package/public/assets/index-ByrskmGR.js +2 -0
  44. package/public/assets/index-ByrskmGR.js.map +1 -0
  45. package/public/assets/index-C-HWajoh.js +2 -0
  46. package/public/assets/index-C-HWajoh.js.map +1 -0
  47. package/public/assets/index-CS3H97IE.js +2 -0
  48. package/public/assets/{index-CVF0ij-F.js.map → index-CS3H97IE.js.map} +1 -1
  49. package/public/assets/index-CWvqFrrT.js +2 -0
  50. package/public/assets/index-CWvqFrrT.js.map +1 -0
  51. package/public/assets/index-CdP9CBer.js +2 -0
  52. package/public/assets/index-CdP9CBer.js.map +1 -0
  53. package/public/assets/index-Cojpg09G.js +2 -0
  54. package/public/assets/{index-B4_MU-br.js.map → index-Cojpg09G.js.map} +1 -1
  55. package/public/assets/index-D0d5gjvd.js +3 -0
  56. package/public/assets/index-D0d5gjvd.js.map +1 -0
  57. package/public/assets/{index-CaF2oDiU.js → index-D9RLepHX.js} +2 -2
  58. package/public/assets/{index-CaF2oDiU.js.map → index-D9RLepHX.js.map} +1 -1
  59. package/public/assets/index-DFv1i_dG.js +2 -0
  60. package/public/assets/index-DFv1i_dG.js.map +1 -0
  61. package/public/assets/index-DRUy1Lf6.css +1 -0
  62. package/public/assets/{index-CRYXivNH.js → index-Dlh7upXe.js} +2 -2
  63. package/public/assets/index-Dlh7upXe.js.map +1 -0
  64. package/public/assets/index-MWV4YmJD.js +2 -0
  65. package/public/assets/index-MWV4YmJD.js.map +1 -0
  66. package/public/assets/index-muUYxM2G.js +2 -0
  67. package/public/assets/index-muUYxM2G.js.map +1 -0
  68. package/public/assets/{loading-Cf2WxCXs.js → loading-Dp5Scb7X.js} +2 -2
  69. package/public/assets/{loading-Cf2WxCXs.js.map → loading-Dp5Scb7X.js.map} +1 -1
  70. package/public/assets/main-CI8GnTaf.js +43 -0
  71. package/public/assets/main-CI8GnTaf.js.map +1 -0
  72. package/public/assets/{markdown-UiScYuQW.js → markdown-Bxx6qFHo.js} +4 -4
  73. package/public/assets/{markdown-UiScYuQW.js.map → markdown-Bxx6qFHo.js.map} +1 -1
  74. package/public/assets/monaco-viewer-By25ULuj.js +27 -0
  75. package/public/assets/{monaco-viewer-C2EN1a6C.js.map → monaco-viewer-By25ULuj.js.map} +1 -1
  76. package/public/assets/{startup-state-settings-card-DVUiMY1X.js → startup-state-settings-card-BX-ssdKj.js} +2 -2
  77. package/public/assets/{startup-state-settings-card-DVUiMY1X.js.map → startup-state-settings-card-BX-ssdKj.js.map} +1 -1
  78. package/public/assets/{terminal-square-DiZ6HdRj.js → terminal-square-ClXH8X8C.js} +2 -2
  79. package/public/assets/{terminal-square-DiZ6HdRj.js.map → terminal-square-ClXH8X8C.js.map} +1 -1
  80. package/public/assets/{tool-call-C3mOLsxT.js → tool-call-DlcdmfFy.js} +4 -4
  81. package/public/assets/{tool-call-C3mOLsxT.js.map → tool-call-DlcdmfFy.js.map} +1 -1
  82. package/public/assets/{unified-picker-CQHMwv72.js → unified-picker-CxUpk-PJ.js} +2 -2
  83. package/public/assets/{unified-picker-CQHMwv72.js.map → unified-picker-CxUpk-PJ.js.map} +1 -1
  84. package/public/assets/{wrap-text-DZtPfwI6.js → wrap-text-DLWowJWZ.js} +2 -2
  85. package/public/assets/{wrap-text-DZtPfwI6.js.map → wrap-text-DLWowJWZ.js.map} +1 -1
  86. package/public/index.html +4 -4
  87. package/public/loading.html +4 -4
  88. package/public/sw.js +1 -1
  89. package/public/sw.js.map +1 -1
  90. package/public/assets/App-CH6cfB0g.js +0 -58
  91. package/public/assets/App-CH6cfB0g.js.map +0 -1
  92. package/public/assets/StatusTab-CUlz3uGG.js +0 -2
  93. package/public/assets/StatusTab-CUlz3uGG.js.map +0 -1
  94. package/public/assets/index-6oDOgk2Z.js +0 -3
  95. package/public/assets/index-6oDOgk2Z.js.map +0 -1
  96. package/public/assets/index-B4_MU-br.js +0 -2
  97. package/public/assets/index-BaZoOnmA.js +0 -2
  98. package/public/assets/index-BaZoOnmA.js.map +0 -1
  99. package/public/assets/index-C9fWE_Zp.js +0 -2
  100. package/public/assets/index-C9fWE_Zp.js.map +0 -1
  101. package/public/assets/index-CLLdccpq.js +0 -2
  102. package/public/assets/index-CLLdccpq.js.map +0 -1
  103. package/public/assets/index-CRYXivNH.js.map +0 -1
  104. package/public/assets/index-CVF0ij-F.js +0 -2
  105. package/public/assets/index-DT_2SeHL.css +0 -1
  106. package/public/assets/index-Do13J2Ow.js +0 -2
  107. package/public/assets/index-Do13J2Ow.js.map +0 -1
  108. package/public/assets/index-DuOitl8E.js +0 -2
  109. package/public/assets/index-DuOitl8E.js.map +0 -1
  110. package/public/assets/index-bDfFMW09.js +0 -2
  111. package/public/assets/index-bDfFMW09.js.map +0 -1
  112. package/public/assets/index-v8DVuyeN.js +0 -2
  113. package/public/assets/index-v8DVuyeN.js.map +0 -1
  114. package/public/assets/main-C6k-tEZT.js +0 -43
  115. package/public/assets/main-C6k-tEZT.js.map +0 -1
  116. package/public/assets/monaco-viewer-C2EN1a6C.js +0 -27
@@ -1,19 +1,89 @@
1
1
  import { z } from "zod";
2
- import { getProviderUsage } from "../../usage/service";
2
+ import { readLocationRef } from "../../opencode/compatibility/location";
3
+ import { createNativeCodexUsage } from "../../usage/native-codex";
4
+ import { getProviderUsage, resolveUsageProvider } from "../../usage/service";
3
5
  const UsageParamsSchema = z.object({ providerId: z.string().trim().min(1) });
4
- const UsageQuerySchema = z.object({ modelId: z.string().trim().optional() });
5
- export function registerUsageRoutes(app) {
6
+ const UsageQuerySchema = z.object({
7
+ instanceId: z.string().trim().min(1).max(256), sessionId: z.string().trim().min(1).max(256),
8
+ modelId: z.string().trim().max(256).optional(),
9
+ }).strict();
10
+ export function registerUsageRoutes(app, deps) {
11
+ const nativeCodexUsage = createNativeCodexUsage();
6
12
  app.get("/api/usage/:providerId", async (request, reply) => {
13
+ reply.header("Cache-Control", "no-store");
14
+ const params = UsageParamsSchema.safeParse(request.params);
15
+ const query = UsageQuerySchema.safeParse(request.query ?? {});
16
+ if (!params.success || !query.success)
17
+ return reply.code(400).send({ error: "Invalid usage request" });
18
+ const { instanceId, sessionId, modelId } = query.data;
19
+ const manager = deps.workspaceManager;
20
+ const workspace = manager.get(instanceId);
21
+ if (!workspace)
22
+ return reply.code(404).send({ error: "Workspace not found" });
23
+ const controller = new AbortController();
24
+ const timeout = setTimeout(() => controller.abort(), 15_000);
25
+ const signal = controller.signal;
7
26
  try {
8
- const params = UsageParamsSchema.parse(request.params);
9
- const query = UsageQuerySchema.parse(request.query ?? {});
10
- return await getProviderUsage(params.providerId, { modelId: query.modelId });
27
+ return await boundedRead(async () => {
28
+ const connection = await manager.getSharedServiceConnection(instanceId);
29
+ signal.throwIfAborted();
30
+ if (!connection)
31
+ return reply.code(503).send({ error: "Provider usage unavailable" });
32
+ connection.assertCurrent();
33
+ signal.throwIfAborted();
34
+ const session = await connection.client.session.get({ sessionID: sessionId }, { signal });
35
+ const location = readLocationRef(session.location);
36
+ const owned = location.workspaceID === undefined && await manager.ownsLocation(instanceId, location, connection.client);
37
+ signal.throwIfAborted();
38
+ if (!owned) {
39
+ return reply.code(403).send({ error: "Session does not belong to workspace" });
40
+ }
41
+ signal.throwIfAborted();
42
+ connection.assertCurrent();
43
+ const provider = resolveUsageProvider(params.data.providerId);
44
+ const native = !provider || provider.id === "codex"
45
+ ? await nativeCodexUsage(connection, { instanceId, sessionId, directory: location.directory,
46
+ providerId: params.data.providerId, modelId }, signal)
47
+ : null;
48
+ const usage = native ?? await getProviderUsage(params.data.providerId, { modelId });
49
+ // Session movement, workspace eviction and reconnect fence publication too.
50
+ const current = await connection.client.session.get({ sessionID: sessionId }, { signal });
51
+ const currentLocation = readLocationRef(current.location);
52
+ connection.assertCurrent();
53
+ signal.throwIfAborted();
54
+ const stillOwned = manager.get(instanceId) === workspace && currentLocation.directory === location.directory
55
+ && currentLocation.workspaceID === undefined && await manager.ownsLocation(instanceId, currentLocation, connection.client);
56
+ signal.throwIfAborted();
57
+ if (!stillOwned) {
58
+ return reply.code(403).send({ error: "Session does not belong to workspace" });
59
+ }
60
+ signal.throwIfAborted();
61
+ connection.assertCurrent();
62
+ return usage;
63
+ }, signal);
11
64
  }
12
65
  catch (error) {
13
- request.log.error({ err: error }, "Failed to fetch provider usage");
14
- reply.code(400);
15
- return { error: error instanceof Error ? error.message : "Failed to fetch provider usage" };
66
+ // Do not serialize/log SDK errors: credential exports and request bodies
67
+ // are server-only, and arbitrary upstream errors can contain secrets.
68
+ const missing = error && typeof error === "object" && "_tag" in error && error._tag === "SessionNotFoundError";
69
+ return reply.code(missing ? 404 : 503).send({ error: missing ? "Session not found" : "Provider usage unavailable" });
16
70
  }
71
+ finally {
72
+ clearTimeout(timeout);
73
+ }
74
+ });
75
+ }
76
+ async function boundedRead(operation, signal) {
77
+ let abort;
78
+ const aborted = new Promise((_resolve, reject) => {
79
+ abort = () => reject(new Error("Provider usage timed out"));
80
+ signal.addEventListener("abort", abort, { once: true });
17
81
  });
82
+ try {
83
+ return await Promise.race([operation(), aborted]);
84
+ }
85
+ finally {
86
+ signal.removeEventListener("abort", abort);
87
+ }
18
88
  }
19
89
  //# sourceMappingURL=usage.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"usage.js","sourceRoot":"","sources":["../../../src/server/routes/usage.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAA;AAEtD,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;AAC5E,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAA;AAE5E,MAAM,UAAU,mBAAmB,CAAC,GAAoB;IACtD,GAAG,CAAC,GAAG,CACL,wBAAwB,EACxB,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE;QACvB,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,iBAAiB,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA;YACtD,MAAM,KAAK,GAAG,gBAAgB,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC,CAAA;YACzD,OAAO,MAAM,gBAAgB,CAAC,MAAM,CAAC,UAAU,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CAAA;QAC9E,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE,gCAAgC,CAAC,CAAA;YACnE,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;YACf,OAAO,EAAE,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,gCAAgC,EAAE,CAAA;QAC7F,CAAC;IACH,CAAC,CACF,CAAA;AACH,CAAC","sourcesContent":["import type { FastifyInstance } from \"fastify\"\nimport { z } from \"zod\"\n\nimport { getProviderUsage } from \"../../usage/service\"\n\nconst UsageParamsSchema = z.object({ providerId: z.string().trim().min(1) })\nconst UsageQuerySchema = z.object({ modelId: z.string().trim().optional() })\n\nexport function registerUsageRoutes(app: FastifyInstance) {\n app.get<{ Params: { providerId: string }; Querystring: { modelId?: string } }>(\n \"/api/usage/:providerId\",\n async (request, reply) => {\n try {\n const params = UsageParamsSchema.parse(request.params)\n const query = UsageQuerySchema.parse(request.query ?? {})\n return await getProviderUsage(params.providerId, { modelId: query.modelId })\n } catch (error) {\n request.log.error({ err: error }, \"Failed to fetch provider usage\")\n reply.code(400)\n return { error: error instanceof Error ? error.message : \"Failed to fetch provider usage\" }\n }\n },\n )\n}\n"]}
1
+ {"version":3,"file":"usage.js","sourceRoot":"","sources":["../../../src/server/routes/usage.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAA;AACvE,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAA;AACjE,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAA;AAE5E,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;AAC5E,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC;IAChC,UAAU,EAAE,CAAC,CAAC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,CAAC;YACjD,CAAC;QAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;IAAC,CAAC;AACxD,CAAC","sourcesContent":["import type { FastifyInstance } from \"fastify\"\nimport { z } from \"zod\"\nimport type { WorkspaceManager } from \"../../workspaces/manager\"\nimport { readLocationRef } from \"../../opencode/compatibility/location\"\nimport { createNativeCodexUsage } from \"../../usage/native-codex\"\nimport { getProviderUsage, resolveUsageProvider } from \"../../usage/service\"\n\nconst UsageParamsSchema = z.object({ providerId: z.string().trim().min(1) })\nconst UsageQuerySchema = z.object({\n instanceId: z.string().trim().min(1).max(256), sessionId: z.string().trim().min(1).max(256),\n modelId: z.string().trim().max(256).optional(),\n}).strict()\n\nexport interface UsageRouteDeps {\n workspaceManager: Pick<WorkspaceManager, \"get\" | \"getSharedServiceConnection\" | \"ownsLocation\">\n}\n\nexport function registerUsageRoutes(app: FastifyInstance, deps: UsageRouteDeps) {\n const nativeCodexUsage = createNativeCodexUsage()\n app.get<{ Params: { providerId: string }; Querystring: z.infer<typeof UsageQuerySchema> }>(\n \"/api/usage/:providerId\",\n async (request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\")\n const params = UsageParamsSchema.safeParse(request.params)\n const query = UsageQuerySchema.safeParse(request.query ?? {})\n if (!params.success || !query.success) return reply.code(400).send({ error: \"Invalid usage request\" })\n const { instanceId, sessionId, modelId } = query.data\n const manager = deps.workspaceManager\n const workspace = manager.get(instanceId)\n if (!workspace) return reply.code(404).send({ error: \"Workspace not found\" })\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), 15_000)\n const signal = controller.signal\n try {\n return await boundedRead(async () => {\n const connection = await manager.getSharedServiceConnection(instanceId)\n signal.throwIfAborted()\n if (!connection) return reply.code(503).send({ error: \"Provider usage unavailable\" })\n connection.assertCurrent()\n signal.throwIfAborted()\n const session = await connection.client.session.get({ sessionID: sessionId }, { signal })\n const location = readLocationRef(session.location)\n const owned = location.workspaceID === undefined && await manager.ownsLocation(instanceId, location, connection.client)\n signal.throwIfAborted()\n if (!owned) {\n return reply.code(403).send({ error: \"Session does not belong to workspace\" })\n }\n signal.throwIfAborted()\n connection.assertCurrent()\n const provider = resolveUsageProvider(params.data.providerId)\n const native = !provider || provider.id === \"codex\"\n ? await nativeCodexUsage(connection, { instanceId, sessionId, directory: location.directory,\n providerId: params.data.providerId, modelId }, signal)\n : null\n const usage = native ?? await getProviderUsage(params.data.providerId, { modelId })\n // Session movement, workspace eviction and reconnect fence publication too.\n const current = await connection.client.session.get({ sessionID: sessionId }, { signal })\n const currentLocation = readLocationRef(current.location)\n connection.assertCurrent()\n signal.throwIfAborted()\n const stillOwned = manager.get(instanceId) === workspace && currentLocation.directory === location.directory\n && currentLocation.workspaceID === undefined && await manager.ownsLocation(instanceId, currentLocation, connection.client)\n signal.throwIfAborted()\n if (!stillOwned) {\n return reply.code(403).send({ error: \"Session does not belong to workspace\" })\n }\n signal.throwIfAborted()\n connection.assertCurrent()\n return usage\n }, signal)\n } catch (error) {\n // Do not serialize/log SDK errors: credential exports and request bodies\n // are server-only, and arbitrary upstream errors can contain secrets.\n const missing = error && typeof error === \"object\" && \"_tag\" in error && error._tag === \"SessionNotFoundError\"\n return reply.code(missing ? 404 : 503).send({ error: missing ? \"Session not found\" : \"Provider usage unavailable\" })\n } finally {\n clearTimeout(timeout)\n }\n },\n )\n}\n\nasync function boundedRead<T>(operation: () => Promise<T>, signal: AbortSignal): Promise<T> {\n let abort!: () => void\n const aborted = new Promise<never>((_resolve, reject) => {\n abort = () => reject(new Error(\"Provider usage timed out\"))\n signal.addEventListener(\"abort\", abort, { once: true })\n })\n try { return await Promise.race([operation(), aborted]) }\n finally { signal.removeEventListener(\"abort\", abort) }\n}\n"]}
@@ -1,24 +1,132 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
  import Fastify from "fastify";
4
+ import { OpenCode } from "@opencode/client";
4
5
  import { registerUsageRoutes } from "./usage";
5
- test("returns a typed unsupported result without exposing server details", async () => {
6
- const app = Fastify();
7
- registerUsageRoutes(app);
6
+ function harness() {
7
+ const expires = Date.now() + 3600000;
8
+ const state = { nativeCalls: [], quotaCalls: 0, directory: "/wsl/repo", switched: false, oldEndpoint: false, fail: false };
9
+ const logs = [];
10
+ const app = Fastify({ logger: { stream: { write: (text) => { logs.push(text); } } } });
11
+ const workspace = {};
12
+ const client = OpenCode.make({ baseUrl: "http://isolated-native.invalid", fetch: async (input) => {
13
+ const url = new URL(String(input));
14
+ state.nativeCalls.push(url.pathname);
15
+ if (state.fail)
16
+ throw new Error("secret-refresh Authorization secret-token");
17
+ if (url.pathname === "/api/session/missing")
18
+ return Response.json({ _tag: "SessionNotFoundError", sessionID: "missing" }, { status: 404 });
19
+ if (url.pathname.startsWith("/api/session/"))
20
+ return Response.json({ data: { id: "session", location: { directory: state.directory } } });
21
+ if (url.pathname.startsWith("/api/provider/"))
22
+ return Response.json({ location: { directory: state.directory }, data: {
23
+ id: "openai", name: "OpenAI", activation: "auto", package: "openai",
24
+ } });
25
+ if (url.pathname === "/api/integration/openai")
26
+ return Response.json({ location: { directory: state.directory }, data: {
27
+ id: "openai", name: "OpenAI", methods: [], connections: [{ type: "credential", method: "oauth", id: state.switched ? "other" : "selected", label: "Secret account" }],
28
+ } });
29
+ if (url.pathname === "/api/credential")
30
+ return Response.json({ data: [{ id: "selected", integrationID: "openai", active: true, label: "Secret account",
31
+ value: { type: "oauth", methodID: "chatgpt-headless", access: "secret-token", refresh: "secret-refresh", expires,
32
+ metadata: { accountID: "secret-account" } },
33
+ }] }, { status: state.oldEndpoint ? 404 : 200 });
34
+ return Response.json({}, { status: 404 });
35
+ } });
36
+ const connection = { client, assertCurrent: () => { } };
37
+ const manager = {
38
+ get: id => id === "instance" ? workspace : undefined,
39
+ getSharedServiceConnection: async () => connection,
40
+ ownsLocation: async (_id, location) => location.directory === "/wsl/repo",
41
+ };
42
+ registerUsageRoutes(app, { workspaceManager: manager });
43
+ return { app, state, logs };
44
+ }
45
+ const url = "/api/usage/openai?instanceId=instance&sessionId=session&modelId=gpt-5";
46
+ test("rejects missing/unknown workspace and missing/foreign session before credential access", async () => {
47
+ const { app, state } = harness();
8
48
  try {
9
- const response = await app.inject({ method: "GET", url: "/api/usage/unknown-provider?modelId=test-model" });
49
+ assert.equal((await app.inject({ url: "/api/usage/openai" })).statusCode, 400);
50
+ assert.equal((await app.inject({ url: url.replace("instanceId=instance", "instanceId=unknown") })).statusCode, 404);
51
+ assert.equal(state.nativeCalls.length, 0);
52
+ assert.equal((await app.inject({ url: url.replace("sessionId=session", "sessionId=missing") })).statusCode, 404);
53
+ state.directory = "/foreign";
54
+ assert.equal((await app.inject({ url })).statusCode, 403);
55
+ assert.ok(state.nativeCalls.every(path => path.startsWith("/api/session/")));
56
+ }
57
+ finally {
58
+ await app.close();
59
+ }
60
+ });
61
+ test("owned native quota response is normalized; credentials and upstream errors never reach API or logs", async () => {
62
+ const { app, state, logs } = harness();
63
+ const previousFetch = globalThis.fetch;
64
+ globalThis.fetch = async (_input, init) => {
65
+ state.quotaCalls++;
66
+ assert.equal(new Headers(init?.headers).get("authorization"), "Bearer secret-token");
67
+ return Response.json({ rate_limit: { primary_window: { used_percent: 25, limit_window_seconds: 18000 } } });
68
+ };
69
+ try {
70
+ const response = await app.inject({ url });
71
+ assert.equal(response.statusCode, 200);
72
+ assert.equal(response.headers["cache-control"], "no-store");
73
+ assert.equal(response.json().ok, true, JSON.stringify({ body: response.json(), calls: state.nativeCalls }));
74
+ assert.equal(response.json().windows["5h"].usedPercent, 25);
75
+ assert.equal((await app.inject({ url })).json().ok, true);
76
+ assert.equal(state.quotaCalls, 1);
77
+ state.switched = true;
78
+ const switched = await app.inject({ url });
79
+ assert.equal(switched.json().ok, false);
80
+ assert.deepEqual(switched.json().windows, {});
81
+ state.fail = true;
82
+ const failed = await app.inject({ url });
83
+ assert.equal(failed.statusCode, 503);
84
+ assert.equal([response.body, switched.body, failed.body, ...logs].join("").includes("secret-"), false);
85
+ }
86
+ finally {
87
+ globalThis.fetch = previousFetch;
88
+ await app.close();
89
+ }
90
+ });
91
+ test("older native credential endpoint is feature-local unavailability, not a host fallback", async () => {
92
+ const { app, state } = harness();
93
+ state.oldEndpoint = true;
94
+ const previousFetch = globalThis.fetch;
95
+ globalThis.fetch = async () => { throw new Error("No legacy fallback permitted"); };
96
+ try {
97
+ const response = await app.inject({ url });
98
+ assert.equal(response.statusCode, 200);
99
+ assert.equal(response.json().supported, true);
100
+ assert.equal(response.json().ok, false);
101
+ assert.deepEqual(response.json().windows, {});
102
+ }
103
+ finally {
104
+ globalThis.fetch = previousFetch;
105
+ await app.close();
106
+ }
107
+ });
108
+ test("session movement during quota fetch fences publication", async () => {
109
+ const { app, state } = harness();
110
+ const previousFetch = globalThis.fetch;
111
+ globalThis.fetch = async () => { state.directory = "/foreign"; return Response.json({ rate_limit: { primary_window: { used_percent: 10 } } }); };
112
+ try {
113
+ const response = await app.inject({ url });
114
+ assert.equal(response.statusCode, 403);
115
+ assert.equal(response.body.includes("windows"), false);
116
+ }
117
+ finally {
118
+ globalThis.fetch = previousFetch;
119
+ await app.close();
120
+ }
121
+ });
122
+ test("owned unknown provider retains a typed unsupported result without a quota request", async () => {
123
+ const { app } = harness();
124
+ try {
125
+ const response = await app.inject({ url: url.replace("/usage/openai", "/usage/unknown-provider") });
10
126
  assert.equal(response.statusCode, 200);
11
- assert.deepEqual(response.json(), {
12
- requestedProviderId: "unknown-provider",
13
- providerId: null,
14
- providerName: "unknown-provider",
15
- modelId: "test-model",
16
- supported: false,
17
- configured: false,
18
- ok: false,
19
- windows: {},
20
- fetchedAt: response.json().fetchedAt,
21
- });
127
+ assert.equal(response.json().providerId, null);
128
+ assert.equal(response.json().supported, false);
129
+ assert.deepEqual(response.json().windows, {});
22
130
  }
23
131
  finally {
24
132
  await app.close();
@@ -1 +1 @@
1
- {"version":3,"file":"usage.test.js","sourceRoot":"","sources":["../../../src/server/routes/usage.test.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,oBAAoB,CAAA;AACvC,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,OAAO,MAAM,SAAS,CAAA;AAE7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAA;AAE7C,IAAI,CAAC,oEAAoE,EAAE,KAAK,IAAI,EAAE;IACpF,MAAM,GAAG,GAAG,OAAO,EAAE,CAAA;IACrB,mBAAmB,CAAC,GAAG,CAAC,CAAA;IAExB,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,GAAG,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,EAAE,gDAAgD,EAAE,CAAC,CAAA;QAC3G,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,EAAE,GAAG,CAAC,CAAA;QACtC,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE;YAChC,mBAAmB,EAAE,kBAAkB;YACvC,UAAU,EAAE,IAAI;YAChB,YAAY,EAAE,kBAAkB;YAChC,OAAO,EAAE,YAAY;YACrB,SAAS,EAAE,KAAK;YAChB,UAAU,EAAE,KAAK;YACjB,EAAE,EAAE,KAAK;YACT,OAAO,EAAE,EAAE;YACX,SAAS,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,SAAS;SACrC,CAAC,CAAA;IACJ,CAAC;YAAS,CAAC;QACT,MAAM,GAAG,CAAC,KAAK,EAAE,CAAA;IACnB,CAAC;AACH,CAAC,CAAC,CAAA","sourcesContent":["import assert from \"node:assert/strict\"\nimport test from \"node:test\"\nimport Fastify from \"fastify\"\n\nimport { registerUsageRoutes } from \"./usage\"\n\ntest(\"returns a typed unsupported result without exposing server details\", async () => {\n const app = Fastify()\n registerUsageRoutes(app)\n\n try {\n const response = await app.inject({ method: \"GET\", url: \"/api/usage/unknown-provider?modelId=test-model\" })\n assert.equal(response.statusCode, 200)\n assert.deepEqual(response.json(), {\n requestedProviderId: \"unknown-provider\",\n providerId: null,\n providerName: \"unknown-provider\",\n modelId: \"test-model\",\n supported: false,\n configured: false,\n ok: false,\n windows: {},\n fetchedAt: response.json().fetchedAt,\n })\n } finally {\n await app.close()\n }\n})\n"]}
1
+ {"version":3,"file":"usage.test.js","sourceRoot":"","sources":["../../../src/server/routes/usage.test.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,oBAAoB,CAAA;AACvC,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,OAAO,MAAM,SAAS,CAAA;AAC7B,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAE3C,OAAO,EAAE,mBAAmB,EAAuB,MAAM,SAAS,CAAA;AAElE,SAAS,OAAO;IACd,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,OAAO,CAAA;IACpC,MAAM,KAAK,GAAG,EAAE,WAAW,EAAE,EAAc,EAAE,UAAU,EAAE,CAAC,EAAE,SAAS,EAAE,WAAW,EAAE,QAAQ,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;IACtI,MAAM,IAAI,GAAa,EAAE,CAAA;IACzB,MAAM,GAAG,GAAG,OAAO,CAAC,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,CAAC,IAAY,EAAE,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAA;IAC7F,MAAM,SAAS,GAAG,EAAwE,CAAA;IAC1F,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,gCAAgC,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE;YAC/F,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;YAAC,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,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AA;QAC1C,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,EAAE,GAAG,CAAC,CAAA;QACtC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,KAAK,CAAC,CAAA;IACxD,CAAC;YAAS,CAAC;QAAC,UAAU,CAAC,KAAK,GAAG,aAAa,CAAC;QAAC,MAAM,GAAG,CAAC,KAAK,EAAE,CAAA;IAAC,CAAC;AACnE,CAAC,CAAC,CAAA;AAEF,IAAI,CAAC,mFAAmF,EAAE,KAAK,IAAI,EAAE;IACnG,MAAM,EAAE,GAAG,EAAE,GAAG,OAAO,EAAE,CAAA;IACzB,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,OAAO,CAAC,eAAe,EAAE,yBAAyB,CAAC,EAAE,CAAC,CAAA;QACnG,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,EAAE,GAAG,CAAC,CAAA;QACtC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,UAAU,EAAE,IAAI,CAAC,CAAA;QAC9C,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,SAAS,EAAE,KAAK,CAAC,CAAA;QAC9C,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,CAAA;IAC/C,CAAC;YAAS,CAAC;QAAC,MAAM,GAAG,CAAC,KAAK,EAAE,CAAA;IAAC,CAAC;AACjC,CAAC,CAAC,CAAA","sourcesContent":["import assert from \"node:assert/strict\"\nimport test from \"node:test\"\nimport Fastify from \"fastify\"\nimport { OpenCode } from \"@opencode/client\"\nimport type { ServiceConnection } from \"../../workspaces/opencode-service\"\nimport { registerUsageRoutes, type UsageRouteDeps } from \"./usage\"\n\nfunction harness() {\n const expires = Date.now() + 3600000\n const state = { nativeCalls: [] as string[], quotaCalls: 0, directory: \"/wsl/repo\", switched: false, oldEndpoint: false, fail: false }\n const logs: string[] = []\n const app = Fastify({ logger: { stream: { write: (text: string) => { logs.push(text) } } } })\n const workspace = {} as NonNullable<ReturnType<UsageRouteDeps[\"workspaceManager\"][\"get\"]>>\n const client = OpenCode.make({ baseUrl: \"http://isolated-native.invalid\", fetch: async (input) => {\n const url = new URL(String(input)); state.nativeCalls.push(url.pathname)\n if (state.fail) throw new Error(\"secret-refresh Authorization secret-token\")\n if (url.pathname === \"/api/session/missing\") return Response.json({ _tag: \"SessionNotFoundError\", sessionID: \"missing\" }, { status: 404 })\n if (url.pathname.startsWith(\"/api/session/\")) return Response.json({ data: { id: \"session\", location: { directory: state.directory } } })\n if (url.pathname.startsWith(\"/api/provider/\")) return Response.json({ location: { directory: state.directory }, data: {\n id: \"openai\", name: \"OpenAI\", activation: \"auto\", package: \"openai\",\n } })\n if (url.pathname === \"/api/integration/openai\") return Response.json({ location: { directory: state.directory }, data: {\n id: \"openai\", name: \"OpenAI\", methods: [], connections: [{ type: \"credential\", method: \"oauth\", id: state.switched ? \"other\" : \"selected\", label: \"Secret account\" }],\n } })\n if (url.pathname === \"/api/credential\") return Response.json({ data: [{ id: \"selected\", integrationID: \"openai\", active: true, label: \"Secret account\",\n value: { type: \"oauth\", methodID: \"chatgpt-headless\", access: \"secret-token\", refresh: \"secret-refresh\", expires,\n metadata: { accountID: \"secret-account\" } },\n }] }, { status: state.oldEndpoint ? 404 : 200 })\n return Response.json({}, { status: 404 })\n } })\n const connection = { client, assertCurrent: () => {} } as ServiceConnection\n const manager: UsageRouteDeps[\"workspaceManager\"] = {\n get: id => id === \"instance\" ? workspace : undefined,\n getSharedServiceConnection: async () => connection,\n ownsLocation: async (_id, location) => location.directory === \"/wsl/repo\",\n }\n registerUsageRoutes(app, { workspaceManager: manager })\n return { app, state, logs }\n}\nconst url = \"/api/usage/openai?instanceId=instance&sessionId=session&modelId=gpt-5\"\n\ntest(\"rejects missing/unknown workspace and missing/foreign session before credential access\", async () => {\n const { app, state } = harness()\n try {\n assert.equal((await app.inject({ url: \"/api/usage/openai\" })).statusCode, 400)\n assert.equal((await app.inject({ url: url.replace(\"instanceId=instance\", \"instanceId=unknown\") })).statusCode, 404)\n assert.equal(state.nativeCalls.length, 0)\n assert.equal((await app.inject({ url: url.replace(\"sessionId=session\", \"sessionId=missing\") })).statusCode, 404)\n state.directory = \"/foreign\"\n assert.equal((await app.inject({ url })).statusCode, 403)\n assert.ok(state.nativeCalls.every(path => path.startsWith(\"/api/session/\")))\n } finally { await app.close() }\n})\n\ntest(\"owned native quota response is normalized; credentials and upstream errors never reach API or logs\", async () => {\n const { app, state, logs } = harness()\n const previousFetch = globalThis.fetch\n globalThis.fetch = async (_input, init) => {\n state.quotaCalls++\n assert.equal(new Headers(init?.headers).get(\"authorization\"), \"Bearer secret-token\")\n return Response.json({ rate_limit: { primary_window: { used_percent: 25, limit_window_seconds: 18000 } } })\n }\n try {\n const response = await app.inject({ url })\n assert.equal(response.statusCode, 200)\n assert.equal(response.headers[\"cache-control\"], \"no-store\")\n assert.equal(response.json().ok, true, JSON.stringify({ body: response.json(), calls: state.nativeCalls }))\n assert.equal(response.json().windows[\"5h\"].usedPercent, 25)\n assert.equal((await app.inject({ url })).json().ok, true)\n assert.equal(state.quotaCalls, 1)\n state.switched = true\n const switched = await app.inject({ url })\n assert.equal(switched.json().ok, false)\n assert.deepEqual(switched.json().windows, {})\n state.fail = true\n const failed = await app.inject({ url })\n assert.equal(failed.statusCode, 503)\n assert.equal([response.body, switched.body, failed.body, ...logs].join(\"\").includes(\"secret-\"), false)\n } finally { globalThis.fetch = previousFetch; await app.close() }\n})\n\ntest(\"older native credential endpoint is feature-local unavailability, not a host fallback\", async () => {\n const { app, state } = harness()\n state.oldEndpoint = true\n const previousFetch = globalThis.fetch\n globalThis.fetch = async () => { throw new Error(\"No legacy fallback permitted\") }\n try {\n const response = await app.inject({ url })\n assert.equal(response.statusCode, 200)\n assert.equal(response.json().supported, true)\n assert.equal(response.json().ok, false)\n assert.deepEqual(response.json().windows, {})\n } finally { globalThis.fetch = previousFetch; await app.close() }\n})\n\ntest(\"session movement during quota fetch fences publication\", async () => {\n const { app, state } = harness()\n const previousFetch = globalThis.fetch\n globalThis.fetch = async () => { state.directory = \"/foreign\"; return Response.json({ rate_limit: { primary_window: { used_percent: 10 } } }) }\n try {\n const response = await app.inject({ url })\n assert.equal(response.statusCode, 403)\n assert.equal(response.body.includes(\"windows\"), false)\n } finally { globalThis.fetch = previousFetch; await app.close() }\n})\n\ntest(\"owned unknown provider retains a typed unsupported result without a quota request\", async () => {\n const { app } = harness()\n try {\n const response = await app.inject({ url: url.replace(\"/usage/openai\", \"/usage/unknown-provider\") })\n assert.equal(response.statusCode, 200)\n assert.equal(response.json().providerId, null)\n assert.equal(response.json().supported, false)\n assert.deepEqual(response.json().windows, {})\n } finally { await app.close() }\n})\n"]}
@@ -0,0 +1,156 @@
1
+ import { createHash } from "node:crypto";
2
+ import { decodeJwtClaims, getString } from "./shared";
3
+ import { parseCodexUsage } from "./providers/oauth";
4
+ const CACHE_TTL_MS = 60_000;
5
+ const MAX_RESPONSE_BYTES = 65_536;
6
+ // Only normalized quota snapshots and irreversible identity digests are retained.
7
+ // Native credential exports (including refresh tokens) stay on the server stack.
8
+ export function createNativeCodexUsage() {
9
+ const caches = new WeakMap();
10
+ const pending = new WeakMap();
11
+ return async (connection, scope, signal) => {
12
+ const response = (snapshot) => ({
13
+ requestedProviderId: scope.providerId, providerId: "codex", providerName: "Codex", modelId: scope.modelId,
14
+ supported: true, configured: true, ok: Boolean(snapshot), windows: snapshot?.usage.windows ?? {},
15
+ fetchedAt: snapshot?.fetchedAt ?? Date.now(),
16
+ });
17
+ const location = { directory: scope.directory };
18
+ const key = JSON.stringify([scope.instanceId, scope.sessionId, scope.directory, scope.providerId]);
19
+ let requestKey;
20
+ let request;
21
+ let recognized = ["openai", "codex", "chatgpt"].includes(scope.providerId.toLowerCase());
22
+ const readSelected = async () => {
23
+ connection.assertCurrent();
24
+ signal.throwIfAborted();
25
+ const provider = await connection.client.provider.get({ providerID: scope.providerId, location }, { signal });
26
+ if (provider.location.directory !== scope.directory || provider.data.id !== scope.providerId)
27
+ throw new Error("Provider location changed");
28
+ const integrationID = provider.data.integrationID ?? scope.providerId;
29
+ if (integrationID !== "openai")
30
+ return null;
31
+ recognized = true;
32
+ const integration = await connection.client.integration.get({ integrationID, location }, { signal });
33
+ if (integration.location.directory !== scope.directory || integration.data.id !== integrationID)
34
+ throw new Error("Integration location changed");
35
+ const selected = integration.data.connections[0];
36
+ if (selected?.type !== "credential" || selected.method !== "oauth" || selected.status?.status === "needs_auth") {
37
+ throw new Error("Subscription OAuth unavailable");
38
+ }
39
+ // Available in 2.0.20+. A missing endpoint is feature-local unavailability,
40
+ // not a reason to raise the global minimum, read SQLite or try auth.json.
41
+ const entries = await connection.client.credential.list({ signal });
42
+ const entry = entries.find(entry => entry.id === selected.id && entry.integrationID === integrationID && entry.active);
43
+ const value = entry?.value;
44
+ if (value?.type !== "oauth" || !["chatgpt-browser", "chatgpt-headless"].includes(value.methodID)
45
+ || !Number.isFinite(value.expires) || value.expires <= Date.now() + 120_000 || !getString(value.access)) {
46
+ throw new Error("Selected subscription credential unavailable");
47
+ }
48
+ const claims = decodeJwtClaims(value.access);
49
+ const jwtExpiry = Number(claims?.exp) * 1000;
50
+ if (Number.isFinite(jwtExpiry) && jwtExpiry <= Date.now() + 120_000)
51
+ throw new Error("Expired subscription credential");
52
+ const accountID = getString(value.metadata?.accountID)
53
+ ?? getString(claims?.["https://api.openai.com/auth"]?.chatgpt_account_id);
54
+ // Require a same-selected-credential account identity, never another store.
55
+ if (!accountID)
56
+ throw new Error("Subscription account unavailable");
57
+ const identity = createHash("sha256").update(JSON.stringify([
58
+ integrationID, entry.id, value.methodID, accountID, value.expires, value.access,
59
+ ])).digest("hex");
60
+ connection.assertCurrent();
61
+ signal.throwIfAborted();
62
+ return { identity, access: value.access, accountID };
63
+ };
64
+ try {
65
+ const selected = await readSelected();
66
+ if (!selected) {
67
+ caches.get(connection)?.delete(key);
68
+ return null;
69
+ }
70
+ let cache = caches.get(connection);
71
+ if (!cache) {
72
+ cache = new Map();
73
+ caches.set(connection, cache);
74
+ }
75
+ let requests = pending.get(connection);
76
+ if (!requests) {
77
+ requests = new Map();
78
+ pending.set(connection, requests);
79
+ }
80
+ let snapshot = cache.get(key);
81
+ if (snapshot?.identity !== selected.identity || Date.now() - snapshot.fetchedAt >= CACHE_TTL_MS) {
82
+ cache.delete(key);
83
+ snapshot = undefined;
84
+ }
85
+ if (!snapshot) {
86
+ requestKey = JSON.stringify([key, selected.identity]);
87
+ request = requests.get(requestKey);
88
+ if (!request) {
89
+ request = fetchQuota(selected.access, selected.accountID, signal);
90
+ requests.set(requestKey, request);
91
+ }
92
+ snapshot = { identity: selected.identity, usage: await request, fetchedAt: Date.now() };
93
+ }
94
+ // Warm snapshots and in-flight results both need fresh native selection.
95
+ // Never publish or populate a cache after an account or connection switch.
96
+ const current = await readSelected();
97
+ if (current?.identity !== selected.identity) {
98
+ cache.delete(key);
99
+ return response();
100
+ }
101
+ connection.assertCurrent();
102
+ signal.throwIfAborted();
103
+ if (cache.size >= 128 && !cache.has(key))
104
+ cache.delete(cache.keys().next().value);
105
+ cache.set(key, snapshot);
106
+ return response(snapshot);
107
+ }
108
+ catch {
109
+ caches.get(connection)?.delete(key);
110
+ // Native errors may contain credential values, labels or request bodies.
111
+ // Neither public responses nor logs receive any upstream error detail.
112
+ return recognized ? response() : null;
113
+ }
114
+ finally {
115
+ // Keep the quota promise shared until the snapshot has been revalidated
116
+ // and published, not just until its provider HTTP response arrives.
117
+ const requests = pending.get(connection);
118
+ if (requestKey && requests && requests.get(requestKey) === request)
119
+ requests.delete(requestKey);
120
+ }
121
+ };
122
+ }
123
+ async function fetchQuota(access, accountID, signal) {
124
+ const response = await fetch("https://chatgpt.com/backend-api/wham/usage", {
125
+ signal, redirect: "error", headers: { Authorization: `Bearer ${access}`, "ChatGPT-Account-Id": accountID, "Content-Type": "application/json" },
126
+ });
127
+ if (!response.ok || !response.body) {
128
+ await response.body?.cancel().catch(() => { });
129
+ throw new Error("Quota unavailable");
130
+ }
131
+ const reader = response.body.getReader();
132
+ const abort = () => { void reader.cancel().catch(() => { }); };
133
+ signal.addEventListener("abort", abort, { once: true });
134
+ const chunks = [];
135
+ let size = 0;
136
+ try {
137
+ while (true) {
138
+ signal.throwIfAborted();
139
+ const chunk = await reader.read();
140
+ if (chunk.done)
141
+ break;
142
+ size += chunk.value.byteLength;
143
+ if (size > MAX_RESPONSE_BYTES)
144
+ throw new Error("Quota response too large");
145
+ chunks.push(chunk.value);
146
+ }
147
+ signal.throwIfAborted();
148
+ return parseCodexUsage(JSON.parse(Buffer.concat(chunks).toString("utf8")));
149
+ }
150
+ finally {
151
+ signal.removeEventListener("abort", abort);
152
+ await reader.cancel().catch(() => { });
153
+ reader.releaseLock();
154
+ }
155
+ }
156
+ //# sourceMappingURL=native-codex.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native-codex.js","sourceRoot":"","sources":["../../src/usage/native-codex.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAIxC,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAUnD,MAAM,YAAY,GAAG,MAAM,CAAA;AAC3B,MAAM,kBAAkB,GAAG,MAAM,CAAA;AAEjC,kFAAkF;AAClF,iFAAiF;AACjF,MAAM,UAAU,sBAAsB;IACpC,MAAM,MAAM,GAAG,IAAI,OAAO,EAA4C,CAAA;IACtE,MAAM,OAAO,GAAG,IAAI,OAAO,EAA0D,CAAA;IAErF,OAAO,KAAK,EAAE,UAA6B,EAAE,KAAiB,EAAE,MAAmB,EAAyC,EAAE;QAC5H,MAAM,QAAQ,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AAC,CAAA;IACZ,IAAI,CAAC;QACH,OAAO,IAAI,EAAE,CAAC;YACZ,MAAM,CAAC,cAAc,EAAE,CAAA;YACvB,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAA;YACjC,IAAI,KAAK,CAAC,IAAI;gBAAE,MAAK;YACrB,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,UAAU,CAAA;YAC9B,IAAI,IAAI,GAAG,kBAAkB;gBAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;YAC1E,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QAC1B,CAAC;QACD,MAAM,CAAC,cAAc,EAAE,CAAA;QACvB,OAAO,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;IAC5E,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;QAC1C,MAAM,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAA;QACrC,MAAM,CAAC,WAAW,EAAE,CAAA;IACtB,CAAC;AACH,CAAC","sourcesContent":["import { createHash } from \"node:crypto\"\nimport type { ServiceConnection } from \"../workspaces/opencode-service\"\nimport type { ProviderUsageResponse } from \"../api-types\"\nimport type { ProviderUsage } from \"./types\"\nimport { decodeJwtClaims, getString } from \"./shared\"\nimport { parseCodexUsage } from \"./providers/oauth\"\n\ninterface UsageScope {\n instanceId: string\n sessionId: string\n directory: string\n providerId: string\n modelId?: string\n}\ntype Snapshot = { identity: string; usage: ProviderUsage; fetchedAt: number }\nconst CACHE_TTL_MS = 60_000\nconst MAX_RESPONSE_BYTES = 65_536\n\n// Only normalized quota snapshots and irreversible identity digests are retained.\n// Native credential exports (including refresh tokens) stay on the server stack.\nexport function createNativeCodexUsage() {\n const caches = new WeakMap<ServiceConnection, Map<string, Snapshot>>()\n const pending = new WeakMap<ServiceConnection, Map<string, Promise<ProviderUsage>>>()\n\n return async (connection: ServiceConnection, scope: UsageScope, signal: AbortSignal): Promise<ProviderUsageResponse | null> => {\n const response = (snapshot?: Snapshot): ProviderUsageResponse => ({\n requestedProviderId: scope.providerId, providerId: \"codex\", providerName: \"Codex\", modelId: scope.modelId,\n supported: true, configured: true, ok: Boolean(snapshot), windows: snapshot?.usage.windows ?? {},\n fetchedAt: snapshot?.fetchedAt ?? Date.now(),\n })\n const location = { directory: scope.directory }\n const key = JSON.stringify([scope.instanceId, scope.sessionId, scope.directory, scope.providerId])\n let requestKey: string | undefined\n let request: Promise<ProviderUsage> | undefined\n let recognized = [\"openai\", \"codex\", \"chatgpt\"].includes(scope.providerId.toLowerCase())\n const readSelected = async () => {\n connection.assertCurrent()\n signal.throwIfAborted()\n const provider = await connection.client.provider.get({ providerID: scope.providerId, location }, { signal })\n if (provider.location.directory !== scope.directory || provider.data.id !== scope.providerId) throw new Error(\"Provider location changed\")\n const integrationID = provider.data.integrationID ?? scope.providerId\n if (integrationID !== \"openai\") return null\n recognized = true\n const integration = await connection.client.integration.get({ integrationID, location }, { signal })\n if (integration.location.directory !== scope.directory || integration.data.id !== integrationID) throw new Error(\"Integration location changed\")\n const selected = integration.data.connections[0]\n if (selected?.type !== \"credential\" || selected.method !== \"oauth\" || selected.status?.status === \"needs_auth\") {\n throw new Error(\"Subscription OAuth unavailable\")\n }\n // Available in 2.0.20+. A missing endpoint is feature-local unavailability,\n // not a reason to raise the global minimum, read SQLite or try auth.json.\n const entries = await connection.client.credential.list({ signal })\n const entry = entries.find(entry => entry.id === selected.id && entry.integrationID === integrationID && entry.active)\n const value = entry?.value\n if (value?.type !== \"oauth\" || ![\"chatgpt-browser\", \"chatgpt-headless\"].includes(value.methodID)\n || !Number.isFinite(value.expires) || value.expires <= Date.now() + 120_000 || !getString(value.access)) {\n throw new Error(\"Selected subscription credential unavailable\")\n }\n const claims = decodeJwtClaims(value.access)\n const jwtExpiry = Number(claims?.exp) * 1000\n if (Number.isFinite(jwtExpiry) && jwtExpiry <= Date.now() + 120_000) throw new Error(\"Expired subscription credential\")\n const accountID = getString(value.metadata?.accountID)\n ?? getString(claims?.[\"https://api.openai.com/auth\"]?.chatgpt_account_id)\n // Require a same-selected-credential account identity, never another store.\n if (!accountID) throw new Error(\"Subscription account unavailable\")\n const identity = createHash(\"sha256\").update(JSON.stringify([\n integrationID, entry!.id, value.methodID, accountID, value.expires, value.access,\n ])).digest(\"hex\")\n connection.assertCurrent()\n signal.throwIfAborted()\n return { identity, access: value.access, accountID }\n }\n\n try {\n const selected = await readSelected()\n if (!selected) { caches.get(connection)?.delete(key); return null }\n let cache = caches.get(connection)\n if (!cache) { cache = new Map(); caches.set(connection, cache) }\n let requests = pending.get(connection)\n if (!requests) { requests = new Map(); pending.set(connection, requests) }\n let snapshot = cache.get(key)\n if (snapshot?.identity !== selected.identity || Date.now() - snapshot.fetchedAt >= CACHE_TTL_MS) {\n cache.delete(key)\n snapshot = undefined\n }\n if (!snapshot) {\n requestKey = JSON.stringify([key, selected.identity])\n request = requests.get(requestKey)\n if (!request) {\n request = fetchQuota(selected.access, selected.accountID, signal)\n requests.set(requestKey, request)\n }\n snapshot = { identity: selected.identity, usage: await request, fetchedAt: Date.now() }\n }\n // Warm snapshots and in-flight results both need fresh native selection.\n // Never publish or populate a cache after an account or connection switch.\n const current = await readSelected()\n if (current?.identity !== selected.identity) { cache.delete(key); return response() }\n connection.assertCurrent()\n signal.throwIfAborted()\n if (cache.size >= 128 && !cache.has(key)) cache.delete(cache.keys().next().value!)\n cache.set(key, snapshot)\n return response(snapshot)\n } catch {\n caches.get(connection)?.delete(key)\n // Native errors may contain credential values, labels or request bodies.\n // Neither public responses nor logs receive any upstream error detail.\n return recognized ? response() : null\n } finally {\n // Keep the quota promise shared until the snapshot has been revalidated\n // and published, not just until its provider HTTP response arrives.\n const requests = pending.get(connection)\n if (requestKey && requests && requests.get(requestKey) === request) requests.delete(requestKey)\n }\n }\n}\n\nasync function fetchQuota(access: string, accountID: string, signal: AbortSignal): Promise<ProviderUsage> {\n const response = await fetch(\"https://chatgpt.com/backend-api/wham/usage\", {\n signal, redirect: \"error\", headers: { Authorization: `Bearer ${access}`, \"ChatGPT-Account-Id\": accountID, \"Content-Type\": \"application/json\" },\n })\n if (!response.ok || !response.body) {\n await response.body?.cancel().catch(() => {})\n throw new Error(\"Quota unavailable\")\n }\n const reader = response.body.getReader()\n const abort = () => { void reader.cancel().catch(() => {}) }\n signal.addEventListener(\"abort\", abort, { once: true })\n const chunks: Uint8Array[] = []\n let size = 0\n try {\n while (true) {\n signal.throwIfAborted()\n const chunk = await reader.read()\n if (chunk.done) break\n size += chunk.value.byteLength\n if (size > MAX_RESPONSE_BYTES) throw new Error(\"Quota response too large\")\n chunks.push(chunk.value)\n }\n signal.throwIfAborted()\n return parseCodexUsage(JSON.parse(Buffer.concat(chunks).toString(\"utf8\")))\n } finally {\n signal.removeEventListener(\"abort\", abort)\n await reader.cancel().catch(() => {})\n reader.releaseLock()\n }\n}\n"]}