@ai-devkit/agent-manager 0.33.1 → 0.35.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 (191) hide show
  1. package/dist/AgentManager.d.ts +2 -0
  2. package/dist/AgentManager.d.ts.map +1 -1
  3. package/dist/AgentManager.js +25 -0
  4. package/dist/AgentManager.js.map +1 -1
  5. package/dist/__tests__/AgentManager.test.js +74 -0
  6. package/dist/__tests__/AgentManager.test.js.map +1 -1
  7. package/dist/__tests__/adapters/ClaudeCodeAdapter.test.js +28 -0
  8. package/dist/__tests__/adapters/ClaudeCodeAdapter.test.js.map +1 -1
  9. package/dist/__tests__/adapters/CodexAdapter.test.js +7 -0
  10. package/dist/__tests__/adapters/CodexAdapter.test.js.map +1 -1
  11. package/dist/__tests__/capacity/codex.test.js +2 -1
  12. package/dist/__tests__/capacity/codex.test.js.map +1 -1
  13. package/dist/__tests__/capacity/index.test.js +6 -3
  14. package/dist/__tests__/capacity/index.test.js.map +1 -1
  15. package/dist/__tests__/capacity/zai.test.js +213 -0
  16. package/dist/__tests__/capacity/zai.test.js.map +1 -0
  17. package/dist/__tests__/providers/copilot/CopilotAdapter.test.js +18 -0
  18. package/dist/__tests__/providers/copilot/CopilotAdapter.test.js.map +1 -1
  19. package/dist/__tests__/providers/gemini/GeminiCliAdapter.test.js +36 -0
  20. package/dist/__tests__/providers/gemini/GeminiCliAdapter.test.js.map +1 -1
  21. package/dist/__tests__/providers/grok/GrokAgentMapper.test.js +56 -0
  22. package/dist/__tests__/providers/grok/GrokAgentMapper.test.js.map +1 -0
  23. package/dist/__tests__/{adapters → providers/grok}/GrokCliAdapter.test.js +19 -6
  24. package/dist/__tests__/providers/grok/GrokCliAdapter.test.js.map +1 -0
  25. package/dist/__tests__/providers/grok/GrokSessionLocator.test.js +133 -0
  26. package/dist/__tests__/providers/grok/GrokSessionLocator.test.js.map +1 -0
  27. package/dist/__tests__/providers/opencode/OpenCodeAdapter.test.js +213 -0
  28. package/dist/__tests__/providers/opencode/OpenCodeAdapter.test.js.map +1 -0
  29. package/dist/__tests__/providers/opencode/OpenCodeAgentMapper.test.js +89 -0
  30. package/dist/__tests__/providers/opencode/OpenCodeAgentMapper.test.js.map +1 -0
  31. package/dist/__tests__/providers/opencode/OpenCodeSessionLocator.test.js +94 -0
  32. package/dist/__tests__/providers/opencode/OpenCodeSessionLocator.test.js.map +1 -0
  33. package/dist/__tests__/providers/opencode/OpenCodeSessionParser.test.js +147 -0
  34. package/dist/__tests__/providers/opencode/OpenCodeSessionParser.test.js.map +1 -0
  35. package/dist/__tests__/providers/pi/PiAdapter.test.js +30 -0
  36. package/dist/__tests__/providers/pi/PiAdapter.test.js.map +1 -1
  37. package/dist/__tests__/utils/session.test.js +18 -1
  38. package/dist/__tests__/utils/session.test.js.map +1 -1
  39. package/dist/adapters/AgentAdapter.d.ts +8 -0
  40. package/dist/adapters/AgentAdapter.d.ts.map +1 -1
  41. package/dist/adapters/AgentAdapter.js.map +1 -1
  42. package/dist/adapters/index.d.ts +2 -2
  43. package/dist/adapters/index.d.ts.map +1 -1
  44. package/dist/adapters/index.js +2 -2
  45. package/dist/adapters/index.js.map +1 -1
  46. package/dist/capacity/codex.d.ts +1 -0
  47. package/dist/capacity/codex.d.ts.map +1 -1
  48. package/dist/capacity/codex.js +9 -4
  49. package/dist/capacity/codex.js.map +1 -1
  50. package/dist/capacity/index.d.ts +8 -0
  51. package/dist/capacity/index.d.ts.map +1 -1
  52. package/dist/capacity/index.js +10 -9
  53. package/dist/capacity/index.js.map +1 -1
  54. package/dist/capacity/types.d.ts +8 -0
  55. package/dist/capacity/types.d.ts.map +1 -1
  56. package/dist/capacity/types.js.map +1 -1
  57. package/dist/capacity/zai.d.ts +14 -0
  58. package/dist/capacity/zai.d.ts.map +1 -0
  59. package/dist/capacity/zai.js +203 -0
  60. package/dist/capacity/zai.js.map +1 -0
  61. package/dist/index.d.ts +4 -4
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.js +3 -3
  64. package/dist/index.js.map +1 -1
  65. package/dist/providers/claude/ClaudeCodeAdapter.d.ts +2 -0
  66. package/dist/providers/claude/ClaudeCodeAdapter.d.ts.map +1 -1
  67. package/dist/providers/claude/ClaudeCodeAdapter.js +22 -19
  68. package/dist/providers/claude/ClaudeCodeAdapter.js.map +1 -1
  69. package/dist/providers/claude/ClaudeSessionLocator.d.ts +4 -0
  70. package/dist/providers/claude/ClaudeSessionLocator.d.ts.map +1 -1
  71. package/dist/providers/claude/ClaudeSessionLocator.js +18 -1
  72. package/dist/providers/claude/ClaudeSessionLocator.js.map +1 -1
  73. package/dist/providers/codex/CodexAdapter.d.ts +1 -0
  74. package/dist/providers/codex/CodexAdapter.d.ts.map +1 -1
  75. package/dist/providers/codex/CodexAdapter.js +8 -0
  76. package/dist/providers/codex/CodexAdapter.js.map +1 -1
  77. package/dist/providers/copilot/CopilotAdapter.d.ts +2 -0
  78. package/dist/providers/copilot/CopilotAdapter.d.ts.map +1 -1
  79. package/dist/providers/copilot/CopilotAdapter.js +24 -9
  80. package/dist/providers/copilot/CopilotAdapter.js.map +1 -1
  81. package/dist/providers/copilot/CopilotSessionLocator.d.ts +1 -0
  82. package/dist/providers/copilot/CopilotSessionLocator.d.ts.map +1 -1
  83. package/dist/providers/copilot/CopilotSessionLocator.js +9 -1
  84. package/dist/providers/copilot/CopilotSessionLocator.js.map +1 -1
  85. package/dist/providers/gemini/GeminiCliAdapter.d.ts +1 -0
  86. package/dist/providers/gemini/GeminiCliAdapter.d.ts.map +1 -1
  87. package/dist/providers/gemini/GeminiCliAdapter.js +9 -0
  88. package/dist/providers/gemini/GeminiCliAdapter.js.map +1 -1
  89. package/dist/providers/grok/GrokAgentMapper.d.ts +14 -0
  90. package/dist/providers/grok/GrokAgentMapper.d.ts.map +1 -0
  91. package/dist/providers/grok/GrokAgentMapper.js +36 -0
  92. package/dist/providers/grok/GrokAgentMapper.js.map +1 -0
  93. package/dist/providers/grok/GrokCliAdapter.d.ts +36 -0
  94. package/dist/providers/grok/GrokCliAdapter.d.ts.map +1 -0
  95. package/dist/providers/grok/GrokCliAdapter.js +98 -0
  96. package/dist/providers/grok/GrokCliAdapter.js.map +1 -0
  97. package/dist/providers/grok/GrokSessionLocator.d.ts +62 -0
  98. package/dist/providers/grok/GrokSessionLocator.d.ts.map +1 -0
  99. package/dist/providers/grok/GrokSessionLocator.js +140 -0
  100. package/dist/providers/grok/GrokSessionLocator.js.map +1 -0
  101. package/dist/providers/grok/GrokSessionParser.d.ts +54 -0
  102. package/dist/providers/grok/GrokSessionParser.d.ts.map +1 -0
  103. package/dist/providers/grok/GrokSessionParser.js +122 -0
  104. package/dist/providers/grok/GrokSessionParser.js.map +1 -0
  105. package/dist/{adapters → providers/opencode}/OpenCodeAdapter.d.ts +6 -12
  106. package/dist/providers/opencode/OpenCodeAdapter.d.ts.map +1 -0
  107. package/dist/providers/opencode/OpenCodeAdapter.js +89 -0
  108. package/dist/providers/opencode/OpenCodeAdapter.js.map +1 -0
  109. package/dist/providers/opencode/OpenCodeAgentMapper.d.ts +11 -0
  110. package/dist/providers/opencode/OpenCodeAgentMapper.d.ts.map +1 -0
  111. package/dist/providers/opencode/OpenCodeAgentMapper.js +50 -0
  112. package/dist/providers/opencode/OpenCodeAgentMapper.js.map +1 -0
  113. package/dist/providers/opencode/OpenCodeSessionLocator.d.ts +23 -0
  114. package/dist/providers/opencode/OpenCodeSessionLocator.d.ts.map +1 -0
  115. package/dist/providers/opencode/OpenCodeSessionLocator.js +118 -0
  116. package/dist/providers/opencode/OpenCodeSessionLocator.js.map +1 -0
  117. package/dist/providers/opencode/OpenCodeSessionParser.d.ts +18 -0
  118. package/dist/providers/opencode/OpenCodeSessionParser.d.ts.map +1 -0
  119. package/dist/providers/opencode/OpenCodeSessionParser.js +104 -0
  120. package/dist/providers/opencode/OpenCodeSessionParser.js.map +1 -0
  121. package/dist/providers/pi/PiAdapter.d.ts +1 -0
  122. package/dist/providers/pi/PiAdapter.d.ts.map +1 -1
  123. package/dist/providers/pi/PiAdapter.js +10 -0
  124. package/dist/providers/pi/PiAdapter.js.map +1 -1
  125. package/dist/providers/pi/PiSessionLocator.d.ts +1 -0
  126. package/dist/providers/pi/PiSessionLocator.d.ts.map +1 -1
  127. package/dist/providers/pi/PiSessionLocator.js +8 -1
  128. package/dist/providers/pi/PiSessionLocator.js.map +1 -1
  129. package/dist/utils/session.d.ts +2 -0
  130. package/dist/utils/session.d.ts.map +1 -1
  131. package/dist/utils/session.js +3 -0
  132. package/dist/utils/session.js.map +1 -1
  133. package/package.json +1 -1
  134. package/src/AgentManager.ts +34 -0
  135. package/src/__tests__/AgentManager.test.ts +60 -0
  136. package/src/__tests__/adapters/ClaudeCodeAdapter.test.ts +23 -0
  137. package/src/__tests__/adapters/CodexAdapter.test.ts +7 -0
  138. package/src/__tests__/capacity/codex.test.ts +94 -26
  139. package/src/__tests__/capacity/fixtures/zai-auth.json +6 -0
  140. package/src/__tests__/capacity/fixtures/zai-quota-invalid.json +7 -0
  141. package/src/__tests__/capacity/fixtures/zai-quota.json +38 -0
  142. package/src/__tests__/capacity/index.test.ts +10 -3
  143. package/src/__tests__/capacity/zai.test.ts +186 -0
  144. package/src/__tests__/providers/copilot/CopilotAdapter.test.ts +12 -0
  145. package/src/__tests__/providers/gemini/GeminiCliAdapter.test.ts +21 -0
  146. package/src/__tests__/providers/grok/GrokAgentMapper.test.ts +57 -0
  147. package/src/__tests__/{adapters → providers/grok}/GrokCliAdapter.test.ts +18 -9
  148. package/src/__tests__/providers/grok/GrokSessionLocator.test.ts +106 -0
  149. package/src/__tests__/providers/opencode/OpenCodeAdapter.test.ts +215 -0
  150. package/src/__tests__/providers/opencode/OpenCodeAgentMapper.test.ts +83 -0
  151. package/src/__tests__/providers/opencode/OpenCodeSessionLocator.test.ts +84 -0
  152. package/src/__tests__/providers/opencode/OpenCodeSessionParser.test.ts +148 -0
  153. package/src/__tests__/providers/pi/PiAdapter.test.ts +15 -0
  154. package/src/__tests__/utils/session.test.ts +11 -1
  155. package/src/adapters/AgentAdapter.ts +9 -0
  156. package/src/adapters/index.ts +2 -2
  157. package/src/capacity/codex.ts +96 -28
  158. package/src/capacity/index.ts +29 -11
  159. package/src/capacity/types.ts +8 -0
  160. package/src/capacity/zai.ts +237 -0
  161. package/src/index.ts +9 -4
  162. package/src/providers/claude/ClaudeCodeAdapter.ts +28 -23
  163. package/src/providers/claude/ClaudeSessionLocator.ts +20 -0
  164. package/src/providers/codex/CodexAdapter.ts +8 -0
  165. package/src/providers/copilot/CopilotAdapter.ts +26 -10
  166. package/src/providers/copilot/CopilotSessionLocator.ts +7 -1
  167. package/src/providers/gemini/GeminiCliAdapter.ts +8 -0
  168. package/src/providers/grok/GrokAgentMapper.ts +41 -0
  169. package/src/providers/grok/GrokCliAdapter.ts +125 -0
  170. package/src/providers/grok/GrokSessionLocator.ts +179 -0
  171. package/src/providers/grok/GrokSessionParser.ts +166 -0
  172. package/src/providers/opencode/OpenCodeAdapter.ts +116 -0
  173. package/src/providers/opencode/OpenCodeAgentMapper.ts +61 -0
  174. package/src/providers/opencode/OpenCodeSessionLocator.ts +151 -0
  175. package/src/providers/opencode/OpenCodeSessionParser.ts +145 -0
  176. package/src/providers/pi/PiAdapter.ts +12 -0
  177. package/src/providers/pi/PiSessionLocator.ts +16 -1
  178. package/src/utils/session.ts +11 -0
  179. package/dist/__tests__/adapters/GrokCliAdapter.test.js.map +0 -1
  180. package/dist/__tests__/adapters/OpenCodeAdapter.test.js +0 -636
  181. package/dist/__tests__/adapters/OpenCodeAdapter.test.js.map +0 -1
  182. package/dist/adapters/GrokCliAdapter.d.ts +0 -80
  183. package/dist/adapters/GrokCliAdapter.d.ts.map +0 -1
  184. package/dist/adapters/GrokCliAdapter.js +0 -310
  185. package/dist/adapters/GrokCliAdapter.js.map +0 -1
  186. package/dist/adapters/OpenCodeAdapter.d.ts.map +0 -1
  187. package/dist/adapters/OpenCodeAdapter.js +0 -289
  188. package/dist/adapters/OpenCodeAdapter.js.map +0 -1
  189. package/src/__tests__/adapters/OpenCodeAdapter.test.ts +0 -544
  190. package/src/adapters/GrokCliAdapter.ts +0 -408
  191. package/src/adapters/OpenCodeAdapter.ts +0 -373
@@ -13,7 +13,11 @@ const context = { installed: true, checkedAt };
13
13
  function apiUsage(overrides: Record<string, unknown> = {}) {
14
14
  return {
15
15
  rate_limit: {
16
- primary_window: { used_percent: 20, limit_window_seconds: 18_000, reset_at: 1_787_220_000 },
16
+ primary_window: {
17
+ used_percent: 20,
18
+ limit_window_seconds: 18_000,
19
+ reset_at: 1_787_220_000,
20
+ },
17
21
  secondary_window: {
18
22
  used_percent: 60,
19
23
  limit_window_seconds: 604_800,
@@ -39,13 +43,18 @@ function apiUsage(overrides: Record<string, unknown> = {}) {
39
43
 
40
44
  describe("Codex auth resolution", () => {
41
45
  it("uses CODEX_HOME before HOME", () => {
42
- expect(resolveCodexAuthPath({ CODEX_HOME: "/custom/codex", HOME: "/users/test" })).toBe(
43
- "/custom/codex/auth.json",
44
- );
46
+ expect(
47
+ resolveCodexAuthPath({
48
+ CODEX_HOME: "/custom/codex",
49
+ HOME: "/users/test",
50
+ }),
51
+ ).toBe("/custom/codex/auth.json");
45
52
  });
46
53
 
47
54
  it("falls back to ~/.codex/auth.json", () => {
48
- expect(resolveCodexAuthPath({ HOME: "/users/test" })).toBe("/users/test/.codex/auth.json");
55
+ expect(resolveCodexAuthPath({ HOME: "/users/test" })).toBe(
56
+ "/users/test/.codex/auth.json",
57
+ );
49
58
  });
50
59
  });
51
60
 
@@ -53,7 +62,11 @@ describe("Codex API usage mapping", () => {
53
62
  it("converts an API window without treating missing data as zero", () => {
54
63
  expect(
55
64
  toRateWindow(
56
- { used_percent: 25, limit_window_seconds: 18_000, reset_at: 1_787_220_000 },
65
+ {
66
+ used_percent: 25,
67
+ limit_window_seconds: 18_000,
68
+ reset_at: 1_787_220_000,
69
+ },
57
70
  "session",
58
71
  "Session",
59
72
  ),
@@ -64,7 +77,9 @@ describe("Codex API usage mapping", () => {
64
77
  usedPercent: 25,
65
78
  resetsAt: "2026-08-20T10:00:00.000Z",
66
79
  });
67
- expect(toRateWindow({}, "session", "Session")).toMatchObject({ usedPercent: null });
80
+ expect(toRateWindow({}, "session", "Session")).toMatchObject({
81
+ usedPercent: null,
82
+ });
68
83
  });
69
84
 
70
85
  it("maps session, weekly, credits, and extra limits", () => {
@@ -89,16 +104,23 @@ describe("tiered Codex probing", () => {
89
104
  const fetch = vi
90
105
  .fn()
91
106
  .mockResolvedValueOnce(
92
- new Response(JSON.stringify({ chatgpt_account_id: "acct-1" }), { status: 200 }),
107
+ new Response(JSON.stringify({ chatgpt_account_id: "acct-1" }), {
108
+ status: 200,
109
+ }),
93
110
  )
94
- .mockResolvedValueOnce(new Response(JSON.stringify(apiUsage()), { status: 200 }));
111
+ .mockResolvedValueOnce(
112
+ new Response(JSON.stringify(apiUsage()), { status: 200 }),
113
+ );
95
114
  const rpc = vi.fn();
96
115
  const result = await probeCodexCapacity({
97
116
  ...context,
98
117
  readFile: async () =>
99
118
  JSON.stringify({
100
119
  personal_access_token: "pat-secret",
101
- tokens: { access_token: "ignored-oauth", account_id: "ignored-account" },
120
+ tokens: {
121
+ access_token: "ignored-oauth",
122
+ account_id: "ignored-account",
123
+ },
102
124
  }),
103
125
  fetch,
104
126
  rpc,
@@ -107,14 +129,17 @@ describe("tiered Codex probing", () => {
107
129
  expect(fetch.mock.calls[0][0]).toBe(
108
130
  "https://auth.openai.com/api/accounts/v1/user-auth-credential/whoami",
109
131
  );
110
- expect(fetch.mock.calls[1][0]).toBe("https://chatgpt.com/backend-api/wham/usage");
132
+ expect(fetch.mock.calls[1][0]).toBe(
133
+ "https://chatgpt.com/backend-api/wham/usage",
134
+ );
111
135
  expect(fetch.mock.calls[1][1].headers).toMatchObject({
112
136
  Authorization: "Bearer pat-secret",
113
137
  "ChatGPT-Account-Id": "acct-1",
114
138
  });
115
139
  expect(rpc).not.toHaveBeenCalled();
116
140
  expect(result).toMatchObject({
117
- provider: "codex",
141
+ harness: "codex",
142
+ provider: "openai",
118
143
  available: "yes",
119
144
  creditsRemaining: 12.5,
120
145
  authenticated: true,
@@ -129,12 +154,18 @@ describe("tiered Codex probing", () => {
129
154
  it("selects a fresh OAuth token without calling whoami", async () => {
130
155
  const fetch = vi
131
156
  .fn()
132
- .mockResolvedValue(new Response(JSON.stringify(apiUsage()), { status: 200 }));
157
+ .mockResolvedValue(
158
+ new Response(JSON.stringify(apiUsage()), { status: 200 }),
159
+ );
133
160
  const result = await probeCodexCapacity({
134
161
  ...context,
135
162
  readFile: async () =>
136
163
  JSON.stringify({
137
- tokens: { access_token: "oauth-secret", account_id: "acct-2", expires_at: 1_800_000_000 },
164
+ tokens: {
165
+ access_token: "oauth-secret",
166
+ account_id: "acct-2",
167
+ expires_at: 1_800_000_000,
168
+ },
138
169
  }),
139
170
  fetch,
140
171
  now: () => new Date("2026-08-20T10:00:00.000Z"),
@@ -158,23 +189,35 @@ describe("tiered Codex probing", () => {
158
189
  "stale OAuth token",
159
190
  async () =>
160
191
  JSON.stringify({
161
- tokens: { access_token: "stale-secret", account_id: "acct", expires_at: 1 },
192
+ tokens: {
193
+ access_token: "stale-secret",
194
+ account_id: "acct",
195
+ expires_at: 1,
196
+ },
162
197
  }),
163
198
  ],
164
199
  [
165
200
  "OAuth 401",
166
201
  async () =>
167
202
  JSON.stringify({
168
- tokens: { access_token: "oauth-secret", account_id: "acct", expires_at: 1_800_000_000 },
203
+ tokens: {
204
+ access_token: "oauth-secret",
205
+ account_id: "acct",
206
+ expires_at: 1_800_000_000,
207
+ },
169
208
  }),
170
209
  ],
171
210
  ])("falls back to the CLI for %s", async (name, readFile) => {
172
211
  const fetch = vi
173
212
  .fn()
174
- .mockResolvedValue(new Response("", { status: name === "OAuth 401" ? 401 : 200 }));
213
+ .mockResolvedValue(
214
+ new Response("", { status: name === "OAuth 401" ? 401 : 200 }),
215
+ );
175
216
  const rpc = vi.fn(async () => ({
176
217
  rateLimits: {
177
- rateLimits: { primary: { usedPercent: 5, windowDurationMins: 300, resetsAt: null } },
218
+ rateLimits: {
219
+ primary: { usedPercent: 5, windowDurationMins: 300, resetsAt: null },
220
+ },
178
221
  },
179
222
  account: { account: { type: "chatgpt" } },
180
223
  }));
@@ -190,10 +233,14 @@ describe("tiered Codex probing", () => {
190
233
  });
191
234
 
192
235
  it("falls back to CLI if PAT requests fail", async () => {
193
- const rpc = vi.fn(async () => ({ rateLimits: {}, account: { account: null } }));
236
+ const rpc = vi.fn(async () => ({
237
+ rateLimits: {},
238
+ account: { account: null },
239
+ }));
194
240
  const result = await probeCodexCapacity({
195
241
  ...context,
196
- readFile: async () => JSON.stringify({ personal_access_token: "pat-secret" }),
242
+ readFile: async () =>
243
+ JSON.stringify({ personal_access_token: "pat-secret" }),
197
244
  fetch: vi.fn().mockRejectedValue(new Error("network failure pat-secret")),
198
245
  rpc,
199
246
  });
@@ -205,14 +252,20 @@ describe("tiered Codex probing", () => {
205
252
  const fetch = vi
206
253
  .fn()
207
254
  .mockRejectedValueOnce(new Error("PAT failed"))
208
- .mockResolvedValueOnce(new Response(JSON.stringify(apiUsage()), { status: 200 }));
255
+ .mockResolvedValueOnce(
256
+ new Response(JSON.stringify(apiUsage()), { status: 200 }),
257
+ );
209
258
  const rpc = vi.fn();
210
259
  const result = await probeCodexCapacity({
211
260
  ...context,
212
261
  readFile: async () =>
213
262
  JSON.stringify({
214
263
  personal_access_token: "pat-secret",
215
- tokens: { access_token: "oauth-secret", account_id: "acct", expires_at: 1_800_000_000 },
264
+ tokens: {
265
+ access_token: "oauth-secret",
266
+ account_id: "acct",
267
+ expires_at: 1_800_000_000,
268
+ },
216
269
  }),
217
270
  fetch,
218
271
  rpc,
@@ -226,7 +279,9 @@ describe("tiered Codex probing", () => {
226
279
  it("uses hardened read-only app-server arguments and both account methods", async () => {
227
280
  const rpc = vi.fn(async () => ({
228
281
  rateLimits: {
229
- rateLimits: { primary: { usedPercent: 5, windowDurationMins: 300, resetsAt: null } },
282
+ rateLimits: {
283
+ primary: { usedPercent: 5, windowDurationMins: 300, resetsAt: null },
284
+ },
230
285
  },
231
286
  account: { account: { type: "chatgpt" } },
232
287
  }));
@@ -239,7 +294,13 @@ describe("tiered Codex probing", () => {
239
294
  "account/read",
240
295
  ]);
241
296
  expect(JSON.stringify(messages)).not.toMatch(/prompt|turn\/start/);
242
- expect(CODEX_APP_SERVER_ARGS).toEqual(["-s", "read-only", "-a", "untrusted", "app-server"]);
297
+ expect(CODEX_APP_SERVER_ARGS).toEqual([
298
+ "-s",
299
+ "read-only",
300
+ "-a",
301
+ "untrusted",
302
+ "app-server",
303
+ ]);
243
304
  });
244
305
 
245
306
  it("uses account/read to distinguish logged-out CLI state", async () => {
@@ -248,11 +309,18 @@ describe("tiered Codex probing", () => {
248
309
  readFile: async () => "{}",
249
310
  rpc: async () => ({ rateLimits: {}, account: { account: null } }),
250
311
  });
251
- expect(result).toMatchObject({ authenticated: false, available: "unknown" });
312
+ expect(result).toMatchObject({
313
+ authenticated: false,
314
+ available: "unknown",
315
+ });
252
316
  });
253
317
 
254
318
  it("never exposes tokens or raw auth content through failures", async () => {
255
- const secrets = ["pat-secret-value", "oauth-secret-value", "refresh-secret-value"];
319
+ const secrets = [
320
+ "pat-secret-value",
321
+ "oauth-secret-value",
322
+ "refresh-secret-value",
323
+ ];
256
324
  const result = await probeCodexCapacity({
257
325
  ...context,
258
326
  readFile: async () =>
@@ -0,0 +1,6 @@
1
+ {
2
+ "zai": {
3
+ "type": "api_key",
4
+ "key": "pi-zai-test-key"
5
+ }
6
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "success": true,
3
+ "code": 200,
4
+ "data": {
5
+ "limits": {}
6
+ }
7
+ }
@@ -0,0 +1,38 @@
1
+ {
2
+ "success": true,
3
+ "code": 200,
4
+ "data": {
5
+ "limits": [
6
+ {
7
+ "type": "TOKENS_LIMIT",
8
+ "unit": 3,
9
+ "number": 5,
10
+ "percentage": 99,
11
+ "usage": 1000,
12
+ "currentValue": 200,
13
+ "remaining": 700,
14
+ "nextResetTime": 1787220000000
15
+ },
16
+ {
17
+ "type": "CREDIT_LIMIT",
18
+ "unit": 6,
19
+ "number": 1,
20
+ "percentage": 5,
21
+ "usage": 200,
22
+ "currentValue": 80,
23
+ "remaining": 150,
24
+ "nextResetTime": 1787824800000
25
+ },
26
+ {
27
+ "type": "TIME_LIMIT",
28
+ "unit": 5,
29
+ "number": 1,
30
+ "percentage": 25,
31
+ "usage": 100,
32
+ "currentValue": 20,
33
+ "remaining": 90,
34
+ "nextResetTime": 1789812000000
35
+ }
36
+ ]
37
+ }
38
+ }
@@ -6,7 +6,8 @@ const checkedAt = "2026-08-09T10:00:00.000Z";
6
6
  describe("getCodexCapacityReport", () => {
7
7
  it("checks Codex installation before probing", async () => {
8
8
  const probe = vi.fn(async (context) => ({
9
- provider: "codex",
9
+ harness: "codex",
10
+ provider: "openai",
10
11
  generatedAt: context.checkedAt,
11
12
  authenticated: true,
12
13
  available: "yes" as const,
@@ -24,7 +25,12 @@ describe("getCodexCapacityReport", () => {
24
25
  });
25
26
 
26
27
  expect(probe).toHaveBeenCalledWith({ installed: true, checkedAt });
27
- expect(report).toMatchObject({ provider: "codex", generatedAt: checkedAt, available: "yes" });
28
+ expect(report).toMatchObject({
29
+ harness: "codex",
30
+ provider: "openai",
31
+ generatedAt: checkedAt,
32
+ available: "yes",
33
+ });
28
34
  });
29
35
 
30
36
  it("redacts unexpected probe failures into a stable unknown result", async () => {
@@ -37,7 +43,8 @@ describe("getCodexCapacityReport", () => {
37
43
  });
38
44
 
39
45
  expect(report).toMatchObject({
40
- provider: "codex",
46
+ harness: "codex",
47
+ provider: "openai",
41
48
  available: "unknown",
42
49
  authenticated: null,
43
50
  windows: [],
@@ -0,0 +1,186 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { fileURLToPath } from "node:url";
3
+ import { describe, expect, it, vi } from "vitest";
4
+ import {
5
+ parseZaiQuota,
6
+ probeZaiCapacity,
7
+ resolveZaiApiKey,
8
+ } from "../../capacity/zai.js";
9
+
10
+ const checkedAt = "2026-08-20T10:00:00.000Z";
11
+ const fixture = (name: string) =>
12
+ readFile(
13
+ fileURLToPath(new URL(`./fixtures/${name}`, import.meta.url)),
14
+ "utf8",
15
+ );
16
+
17
+ describe("z.ai credential resolution", () => {
18
+ it("prefers Z_AI_API_KEY without reading Pi auth", async () => {
19
+ const readAuth = vi.fn(async () => fixture("zai-auth.json"));
20
+ await expect(
21
+ resolveZaiApiKey({
22
+ env: { Z_AI_API_KEY: "env-zai-test-key" },
23
+ readFile: readAuth,
24
+ }),
25
+ ).resolves.toBe("env-zai-test-key");
26
+ expect(readAuth).not.toHaveBeenCalled();
27
+ });
28
+
29
+ it("reads the Pi zai api_key credential from ~/.pi/agent/auth.json", async () => {
30
+ const readAuth = vi.fn(async () => fixture("zai-auth.json"));
31
+ await expect(
32
+ resolveZaiApiKey({ env: { HOME: "/users/test" }, readFile: readAuth }),
33
+ ).resolves.toBe("pi-zai-test-key");
34
+ expect(readAuth).toHaveBeenCalledWith(
35
+ "/users/test/.pi/agent/auth.json",
36
+ "utf8",
37
+ );
38
+ });
39
+
40
+ it.each([
41
+ [
42
+ "missing",
43
+ async () =>
44
+ Promise.reject(Object.assign(new Error("missing"), { code: "ENOENT" })),
45
+ ],
46
+ ["invalid JSON", async () => "{"],
47
+ [
48
+ "wrong credential type",
49
+ async () => JSON.stringify({ zai: { type: "oauth", key: "x" } }),
50
+ ],
51
+ ["missing key", async () => JSON.stringify({ zai: { type: "api_key" } })],
52
+ ])(
53
+ "fails clearly for %s credentials without exposing file content",
54
+ async (_name, readAuth) => {
55
+ await expect(
56
+ resolveZaiApiKey({ env: { HOME: "/users/test" }, readFile: readAuth }),
57
+ ).rejects.toThrow(/z\.ai API key|z\.ai Pi auth file/);
58
+ },
59
+ );
60
+ });
61
+
62
+ describe("z.ai quota mapping", () => {
63
+ it("maps token, credit, and monthly MCP windows with recomputed usage", async () => {
64
+ const report = parseZaiQuota(
65
+ JSON.parse(await fixture("zai-quota.json")),
66
+ checkedAt,
67
+ );
68
+ expect(report).toMatchObject({
69
+ harness: "pi",
70
+ provider: "zai",
71
+ generatedAt: checkedAt,
72
+ authenticated: true,
73
+ available: "yes",
74
+ creditsRemaining: null,
75
+ });
76
+ expect(report.windows).toEqual([
77
+ {
78
+ id: "zai:tokens:1",
79
+ label: "Tokens · 5 hours",
80
+ limitType: "TOKENS_LIMIT",
81
+ durationMinutes: 300,
82
+ usedPercent: 30,
83
+ resetsAt: "2026-08-20T10:00:00.000Z",
84
+ total: 1000,
85
+ current: 200,
86
+ remaining: 700,
87
+ },
88
+ {
89
+ id: "zai:credit:2",
90
+ label: "Credit · 1 week",
91
+ limitType: "CREDIT_LIMIT",
92
+ durationMinutes: 10080,
93
+ usedPercent: 40,
94
+ resetsAt: "2026-08-27T10:00:00.000Z",
95
+ total: 200,
96
+ current: 80,
97
+ remaining: 150,
98
+ },
99
+ {
100
+ id: "zai:time:3",
101
+ label: "MCP · monthly",
102
+ limitType: "TIME_LIMIT",
103
+ durationMinutes: 43200,
104
+ usedPercent: 20,
105
+ resetsAt: "2026-09-19T10:00:00.000Z",
106
+ total: 100,
107
+ current: 20,
108
+ remaining: 90,
109
+ },
110
+ ]);
111
+ });
112
+
113
+ it("uses and clamps the server percentage when quota amounts are unavailable", () => {
114
+ const report = parseZaiQuota(
115
+ {
116
+ success: true,
117
+ code: 200,
118
+ data: {
119
+ limits: [
120
+ { type: "TOKENS_LIMIT", unit: 1, number: 1, percentage: 120 },
121
+ { type: "CREDIT_LIMIT", unit: 5, number: 30, percentage: -5 },
122
+ ],
123
+ },
124
+ },
125
+ checkedAt,
126
+ );
127
+ expect(report.windows.map((window) => window.usedPercent)).toEqual([
128
+ 100, 0,
129
+ ]);
130
+ });
131
+
132
+ it.each([
133
+ [
134
+ "invalid fixture",
135
+ async () => JSON.parse(await fixture("zai-quota-invalid.json")),
136
+ ],
137
+ [
138
+ "unsuccessful envelope",
139
+ async () => ({ success: false, code: 401, data: { limits: [] } }),
140
+ ],
141
+ [
142
+ "invalid entry",
143
+ async () => ({ success: true, code: 200, data: { limits: [{}] } }),
144
+ ],
145
+ ])("rejects %s", async (_name, input) => {
146
+ const value = await input();
147
+ expect(() => parseZaiQuota(value, checkedAt)).toThrow(/z\.ai quota/);
148
+ });
149
+ });
150
+
151
+ describe("z.ai request", () => {
152
+ it("GETs the global quota endpoint with only Bearer authentication", async () => {
153
+ const body = await fixture("zai-quota.json");
154
+ const fetch = vi.fn(async () => new Response(body, { status: 200 }));
155
+ const report = await probeZaiCapacity({
156
+ checkedAt,
157
+ env: { Z_AI_API_KEY: "request-test-key" },
158
+ fetch,
159
+ });
160
+ expect(fetch).toHaveBeenCalledWith(
161
+ "https://api.z.ai/api/monitor/usage/quota/limit",
162
+ expect.objectContaining({
163
+ method: "GET",
164
+ headers: { Authorization: "Bearer request-test-key" },
165
+ }),
166
+ );
167
+ expect(JSON.stringify(report)).not.toContain("request-test-key");
168
+ });
169
+
170
+ it("rejects non-200 and malformed JSON responses with sanitized errors", async () => {
171
+ await expect(
172
+ probeZaiCapacity({
173
+ checkedAt,
174
+ env: { Z_AI_API_KEY: "never-expose-this-key" },
175
+ fetch: vi.fn(async () => new Response("private body", { status: 503 })),
176
+ }),
177
+ ).rejects.toThrow("z.ai quota request failed: HTTP 503");
178
+ await expect(
179
+ probeZaiCapacity({
180
+ checkedAt,
181
+ env: { Z_AI_API_KEY: "never-expose-this-key" },
182
+ fetch: vi.fn(async () => new Response("not-json", { status: 200 })),
183
+ }),
184
+ ).rejects.toThrow("z.ai quota response is not valid JSON");
185
+ });
186
+ });
@@ -552,6 +552,18 @@ describe("CopilotAdapter", () => {
552
552
  });
553
553
  });
554
554
 
555
+ it("finds an exact session ID from its session directory", async () => {
556
+ writeSession("wanted", { events: [sessionStart("wanted", "/repo")] });
557
+ writeSession("other", { events: [sessionStart("other", "/other")] });
558
+
559
+ await expect(adapter.findSessionsById("wanted")).resolves.toEqual([
560
+ expect.objectContaining({
561
+ sessionId: "wanted",
562
+ sessionFilePath: path.join(sessionStateDir, "wanted", "events.jsonl"),
563
+ }),
564
+ ]);
565
+ });
566
+
555
567
  it("applies strict cwd filter", async () => {
556
568
  writeSession("keep", { events: [sessionStart("keep", "/repo")] });
557
569
  writeSession("drop", { events: [sessionStart("drop", "/other")] });
@@ -1185,6 +1185,27 @@ describe("GeminiCliAdapter", () => {
1185
1185
  });
1186
1186
  });
1187
1187
 
1188
+ it("finds an exact session ID from Gemini metadata", async () => {
1189
+ const wantedPath = writeSession(tmpHome, "aaa", "session-one", {
1190
+ sessionId: "wanted",
1191
+ projectHash: hashProjectRoot("/repo"),
1192
+ startTime: "2025-01-01T00:00:00Z",
1193
+ directories: ["/repo"],
1194
+ messages: [{ type: "user", content: "wanted prompt" }],
1195
+ });
1196
+ writeSession(tmpHome, "bbb", "session-two", {
1197
+ sessionId: "other",
1198
+ projectHash: hashProjectRoot("/other"),
1199
+ startTime: "2025-01-01T00:00:00Z",
1200
+ directories: ["/other"],
1201
+ messages: [{ type: "user", content: "other prompt" }],
1202
+ });
1203
+
1204
+ await expect(adapter.findSessionsById("wanted")).resolves.toEqual([
1205
+ expect.objectContaining({ sessionId: "wanted", sessionFilePath: wantedPath }),
1206
+ ]);
1207
+ });
1208
+
1188
1209
  it("applies strict-equality cwd filter against directories[0]", async () => {
1189
1210
  writeSession(tmpHome, "aaa", "session-keep", {
1190
1211
  sessionId: "keep",
@@ -0,0 +1,57 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import { AgentStatus, type ProcessInfo } from "../../../adapters/AgentAdapter.js";
4
+ import { GrokAgentMapper } from "../../../providers/grok/GrokAgentMapper.js";
5
+ import type { GrokSession } from "../../../providers/grok/GrokSessionParser.js";
6
+
7
+ function makeProcess(overrides: Partial<ProcessInfo> = {}): ProcessInfo {
8
+ return { pid: 123, command: "grok", cwd: "/repo/my-app", tty: "ttys001", ...overrides };
9
+ }
10
+
11
+ function makeSession(overrides: Partial<GrokSession> = {}): GrokSession {
12
+ return {
13
+ sessionId: "session-1",
14
+ projectPath: "/repo/my-app",
15
+ sessionFilePath: "/home/.grok/sessions/%2Frepo%2Fmy-app/session-1/chat_history.jsonl",
16
+ sessionStart: new Date(),
17
+ lastActive: new Date(),
18
+ lastUserMessage: "Review this change",
19
+ lastRole: "assistant",
20
+ ...overrides,
21
+ };
22
+ }
23
+
24
+ describe("GrokAgentMapper", () => {
25
+ const mapper = new GrokAgentMapper();
26
+
27
+ it("maps a session to a grok_cli agent pointing at chat_history.jsonl", () => {
28
+ const agent = mapper.mapSessionToAgent({
29
+ session: makeSession(),
30
+ processInfo: makeProcess(),
31
+ });
32
+
33
+ expect(agent).toMatchObject({
34
+ name: "my-app-123",
35
+ type: "grok_cli",
36
+ status: AgentStatus.WAITING,
37
+ summary: "Review this change",
38
+ pid: 123,
39
+ projectPath: "/repo/my-app",
40
+ sessionId: "session-1",
41
+ sessionFilePath: "/home/.grok/sessions/%2Frepo%2Fmy-app/session-1/chat_history.jsonl",
42
+ });
43
+ });
44
+
45
+ it("maps a process-only agent as RUNNING with a pid session id", () => {
46
+ const agent = mapper.mapProcessOnlyAgent(makeProcess(), "/repo/resolved");
47
+
48
+ expect(agent).toMatchObject({
49
+ type: "grok_cli",
50
+ status: AgentStatus.RUNNING,
51
+ summary: "Grok CLI process running",
52
+ projectPath: "/repo/resolved",
53
+ sessionId: "pid-123",
54
+ });
55
+ expect(agent.sessionFilePath).toBeUndefined();
56
+ });
57
+ });
@@ -10,18 +10,18 @@ import * as fs from "fs";
10
10
  import * as os from "os";
11
11
  import * as path from "path";
12
12
 
13
- import { GrokCliAdapter } from "../../adapters/GrokCliAdapter.js";
14
- import type { ProcessInfo } from "../../adapters/AgentAdapter.js";
15
- import { AgentStatus } from "../../adapters/AgentAdapter.js";
13
+ import { GrokCliAdapter } from "../../../providers/grok/GrokCliAdapter.js";
14
+ import type { ProcessInfo } from "../../../adapters/AgentAdapter.js";
15
+ import { AgentStatus } from "../../../adapters/AgentAdapter.js";
16
16
  import {
17
17
  listAgentProcesses,
18
18
  enrichProcesses,
19
19
  captureProcessSnapshot,
20
- } from "../../utils/process.js";
21
- import { generateAgentName } from "../../utils/matching.js";
20
+ } from "../../../utils/process.js";
21
+ import { generateAgentName } from "../../../utils/matching.js";
22
22
 
23
- vi.mock("../../utils/process.js", async (importOriginal) => {
24
- const actual = (await importOriginal()) as typeof import("../../utils/process.js");
23
+ vi.mock("../../../utils/process.js", async (importOriginal) => {
24
+ const actual = (await importOriginal()) as typeof import("../../../utils/process.js");
25
25
  return {
26
26
  ...actual,
27
27
  listAgentProcesses: vi.fn(),
@@ -30,8 +30,8 @@ vi.mock("../../utils/process.js", async (importOriginal) => {
30
30
  };
31
31
  });
32
32
 
33
- vi.mock("../../utils/matching.js", async (importOriginal) => {
34
- const actual = (await importOriginal()) as typeof import("../../utils/matching.js");
33
+ vi.mock("../../../utils/matching.js", async (importOriginal) => {
34
+ const actual = (await importOriginal()) as typeof import("../../../utils/matching.js");
35
35
  return {
36
36
  ...actual,
37
37
  generateAgentName: vi.fn(),
@@ -335,6 +335,15 @@ describe("GrokCliAdapter", () => {
335
335
  );
336
336
  });
337
337
 
338
+ it("finds an exact session ID across project groups", async () => {
339
+ writeSession({});
340
+ writeSession({ sessionCwd: "/Users/dev/other", id: "other-session" });
341
+
342
+ await expect(adapter.findSessionsById(SESSION_ID)).resolves.toEqual([
343
+ expect.objectContaining({ sessionId: SESSION_ID, cwd }),
344
+ ]);
345
+ });
346
+
338
347
  it("applies the cwd filter against the decoded cwd", async () => {
339
348
  writeSession({
340
349
  sessionCwd: "/Users/dev/project-a",