@ai-devkit/agent-manager 0.42.2 → 0.43.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 (33) hide show
  1. package/dist/AgentManager.d.ts +14 -5
  2. package/dist/AgentManager.d.ts.map +1 -1
  3. package/dist/AgentManager.js +32 -13
  4. package/dist/AgentManager.js.map +1 -1
  5. package/dist/__tests__/AgentManager.test.js +131 -0
  6. package/dist/__tests__/AgentManager.test.js.map +1 -1
  7. package/dist/__tests__/capacity/codex.test.js +41 -48
  8. package/dist/__tests__/capacity/codex.test.js.map +1 -1
  9. package/dist/__tests__/capacity/openai.test.js +9 -1
  10. package/dist/__tests__/capacity/openai.test.js.map +1 -1
  11. package/dist/__tests__/capacity/wham.test.js +21 -6
  12. package/dist/__tests__/capacity/wham.test.js.map +1 -1
  13. package/dist/capacity/providers/openai-subscription.d.ts +1 -5
  14. package/dist/capacity/providers/openai-subscription.d.ts.map +1 -1
  15. package/dist/capacity/providers/openai-subscription.js +37 -13
  16. package/dist/capacity/providers/openai-subscription.js.map +1 -1
  17. package/dist/capacity/sources/codex.d.ts +1 -8
  18. package/dist/capacity/sources/codex.d.ts.map +1 -1
  19. package/dist/capacity/sources/codex.js +10 -19
  20. package/dist/capacity/sources/codex.js.map +1 -1
  21. package/dist/index.d.ts +1 -0
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js.map +1 -1
  24. package/package.json +2 -2
  25. package/src/AgentManager.ts +49 -20
  26. package/src/__tests__/AgentManager.test.ts +95 -0
  27. package/src/__tests__/capacity/codex.test.ts +42 -47
  28. package/src/__tests__/capacity/fixtures/wham-usage.json +14 -1
  29. package/src/__tests__/capacity/openai.test.ts +12 -1
  30. package/src/__tests__/capacity/wham.test.ts +20 -2
  31. package/src/capacity/providers/openai-subscription.ts +42 -20
  32. package/src/capacity/sources/codex.ts +7 -18
  33. package/src/index.ts +1 -0
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { fetchOpenAiPatAccountId, fetchOpenAiSubscriptionCapacity, parseWhamUsage, resetTime, safeIdentifier } from "../providers/openai-subscription.js";
2
+ import { fetchOpenAiPatAccountId, fetchOpenAiSubscriptionCapacity, resetTime, safeIdentifier } from "../providers/openai-subscription.js";
3
3
  import { resolveCodexCredentials } from "../../harnesses/codex/credentials.js";
4
4
  export const CODEX_APP_SERVER_ARGS = [
5
5
  "-s",
@@ -17,14 +17,6 @@ function finiteNumber(value) {
17
17
  function nonEmptyText(value) {
18
18
  return typeof value === "string" && value.length > 0 ? value : null;
19
19
  }
20
- export function parseUsage(raw, source) {
21
- const { windows, creditsRemaining } = parseWhamUsage(raw);
22
- return {
23
- windows,
24
- creditsRemaining,
25
- source
26
- };
27
- }
28
20
  function cliWindow(value, id, label) {
29
21
  const input = record(value);
30
22
  if (!input) return null;
@@ -64,7 +56,7 @@ function parseCliUsage(raw) {
64
56
  return {
65
57
  windows: unique,
66
58
  creditsRemaining: null,
67
- source: "cli"
59
+ available: null
68
60
  };
69
61
  }
70
62
  function capacityFromSnapshot(snapshot, options, raw) {
@@ -72,12 +64,15 @@ function capacityFromSnapshot(snapshot, options, raw) {
72
64
  const rateLimits = record(record(raw)?.rateLimits);
73
65
  const reached = nonEmptyText(rateLimits?.rateLimitReachedType);
74
66
  const resetCredits = record(record(raw)?.rateLimitResetCredits) ?? record(record(raw)?.usageLimitResetCredits);
67
+ let available = snapshot.available;
68
+ if (reached) available = "no";
69
+ else if (available === null) available = hasUsage ? "yes" : "unknown";
75
70
  return {
76
71
  harness: "codex",
77
72
  provider: "openai",
78
73
  generatedAt: options.checkedAt,
79
74
  authenticated: true,
80
- available: reached ? "no" : hasUsage ? "yes" : "unknown",
75
+ available,
81
76
  windows: snapshot.windows,
82
77
  creditsRemaining: snapshot.creditsRemaining ?? finiteNumber(resetCredits?.availableCount)
83
78
  };
@@ -189,17 +184,13 @@ async function cliFallback(options) {
189
184
  return codexUnavailableReport(options.checkedAt);
190
185
  }
191
186
  }
192
- async function subscriptionSnapshot(access, accountId, source, options) {
187
+ async function subscriptionSnapshot(access, accountId, options) {
193
188
  const snapshot = await fetchOpenAiSubscriptionCapacity({
194
189
  access,
195
190
  accountId
196
191
  }, options);
197
192
  if (snapshot.authenticated === false) throw new Error("unauthorized");
198
- return {
199
- windows: snapshot.windows,
200
- creditsRemaining: snapshot.creditsRemaining,
201
- source
202
- };
193
+ return snapshot;
203
194
  }
204
195
  export async function probeCodexCapacity(options) {
205
196
  const credentials = await resolveCodexCredentials(options);
@@ -207,7 +198,7 @@ export async function probeCodexCapacity(options) {
207
198
  if (credentials.personalAccessToken) {
208
199
  try {
209
200
  const accountId = await fetchOpenAiPatAccountId(credentials.personalAccessToken, options);
210
- const snapshot = await subscriptionSnapshot(credentials.personalAccessToken, accountId, "pat", options);
201
+ const snapshot = await subscriptionSnapshot(credentials.personalAccessToken, accountId, options);
211
202
  return capacityFromSnapshot(snapshot, options);
212
203
  } catch {
213
204
  // Continue to a separately available OAuth credential before using the CLI.
@@ -215,7 +206,7 @@ export async function probeCodexCapacity(options) {
215
206
  }
216
207
  if (credentials.oauth) {
217
208
  try {
218
- const snapshot = await subscriptionSnapshot(credentials.oauth.access, credentials.oauth.accountId, "oauth", options);
209
+ const snapshot = await subscriptionSnapshot(credentials.oauth.access, credentials.oauth.accountId, options);
219
210
  return capacityFromSnapshot(snapshot, options);
220
211
  } catch {
221
212
  return cliFallback(options);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/capacity/sources/codex.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport {\n fetchOpenAiPatAccountId,\n fetchOpenAiSubscriptionCapacity,\n parseWhamUsage,\n resetTime,\n safeIdentifier,\n} from \"../providers/openai-subscription.js\";\nimport type { CapacityReport, CapacityWindow } from \"../types.js\";\nimport {\n resolveCodexCredentials,\n type CodexCredentialOptions,\n} from \"../../harnesses/codex/credentials.js\";\n\ntype CodexUsageSource = \"pat\" | \"oauth\" | \"cli\";\ntype UsageSnapshot = {\n windows: CapacityWindow[];\n creditsRemaining: number | null;\n source: CodexUsageSource;\n};\n\ntype UnknownRecord = Record<string, unknown>;\ntype RpcMessage = { id?: number; method: string; params?: UnknownRecord };\ntype CliResponses = { rateLimits: unknown; account: unknown };\ntype CodexRpc = (messages: RpcMessage[]) => Promise<CliResponses>;\n\nexport type CodexProbeOptions = CodexCredentialOptions & {\n installed: boolean;\n checkedAt: string;\n fetch?: typeof globalThis.fetch;\n rpc?: CodexRpc;\n timeoutMs?: number;\n};\n\nexport const CODEX_APP_SERVER_ARGS = [\"-s\", \"read-only\", \"-a\", \"untrusted\", \"app-server\"] as const;\n\nfunction record(value: unknown): UnknownRecord | null {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as UnknownRecord)\n : null;\n}\n\nfunction finiteNumber(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\nfunction nonEmptyText(value: unknown): string | null {\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nexport function parseUsage(raw: unknown, source: \"pat\" | \"oauth\"): UsageSnapshot {\n const { windows, creditsRemaining } = parseWhamUsage(raw);\n return { windows, creditsRemaining, source };\n}\n\nfunction cliWindow(value: unknown, id: string, label: string): CapacityWindow | null {\n const input = record(value);\n if (!input) return null;\n return {\n id,\n label,\n durationMinutes: finiteNumber(input.windowDurationMins),\n usedPercent: finiteNumber(input.usedPercent),\n resetsAt: resetTime(input.resetsAt),\n };\n}\n\nfunction cliSnapshotWindows(value: unknown, fallbackId: string): CapacityWindow[] {\n const snapshot = record(value);\n if (!snapshot) return [];\n const scope = safeIdentifier(snapshot.limitId) ?? safeIdentifier(fallbackId) ?? \"codex\";\n return [\n cliWindow(snapshot.primary, `${scope}:primary`, `${scope} primary`),\n cliWindow(snapshot.secondary, `${scope}:secondary`, `${scope} secondary`),\n ].filter((item): item is CapacityWindow => item !== null);\n}\n\nfunction parseCliUsage(raw: unknown): UsageSnapshot {\n const response = record(raw) ?? {};\n const primary = record(response.rateLimits);\n const windows = primary ? cliSnapshotWindows(primary, \"codex\") : [];\n const buckets = record(response.rateLimitsByLimitId);\n if (buckets) {\n for (const [id, snapshot] of Object.entries(buckets)) {\n windows.push(...cliSnapshotWindows(snapshot, id));\n }\n }\n const unique = [...new Map(windows.map((window) => [window.id, window])).values()];\n return { windows: unique, creditsRemaining: null, source: \"cli\" };\n}\n\nfunction capacityFromSnapshot(\n snapshot: UsageSnapshot,\n options: CodexProbeOptions,\n raw?: unknown,\n): CapacityReport {\n const hasUsage = snapshot.windows.some((window) => window.usedPercent !== null);\n const rateLimits = record(record(raw)?.rateLimits);\n const reached = nonEmptyText(rateLimits?.rateLimitReachedType);\n const resetCredits =\n record(record(raw)?.rateLimitResetCredits) ?? record(record(raw)?.usageLimitResetCredits);\n return {\n harness: \"codex\",\n provider: \"openai\",\n generatedAt: options.checkedAt,\n authenticated: true,\n available: reached ? \"no\" : hasUsage ? \"yes\" : \"unknown\",\n windows: snapshot.windows,\n creditsRemaining: snapshot.creditsRemaining ?? finiteNumber(resetCredits?.availableCount),\n };\n}\n\nfunction appServerRpc(messages: RpcMessage[], timeoutMs = 5000): Promise<CliResponses> {\n return new Promise((resolve, reject) => {\n const child = spawn(\"codex\", CODEX_APP_SERVER_ARGS, { stdio: [\"pipe\", \"pipe\", \"ignore\"] });\n const results: Partial<CliResponses> = {};\n let buffer = \"\";\n let settled = false;\n const finish = (error?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n child.kill();\n if (error) reject(error);\n else resolve(results as CliResponses);\n };\n const timer = setTimeout(() => finish(new Error(\"codex probe timed out\")), timeoutMs);\n child.once(\"error\", () => finish(new Error(\"codex app-server unavailable\")));\n child.once(\"exit\", () => {\n if (!settled) finish(new Error(\"codex app-server exited\"));\n });\n child.stdout.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk: string) => {\n buffer += chunk;\n for (;;) {\n const newline = buffer.indexOf(\"\\n\");\n if (newline < 0) break;\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n if (!line) continue;\n let message: UnknownRecord;\n try {\n message = JSON.parse(line) as UnknownRecord;\n } catch {\n continue;\n }\n if (message.id === 1) {\n for (const request of messages.slice(1))\n child.stdin.write(`${JSON.stringify(request)}\\n`);\n } else if (message.id === 2) {\n if (message.error) finish(new Error(\"codex rate-limit method failed\"));\n else results.rateLimits = message.result;\n } else if (message.id === 3) {\n if (message.error) finish(new Error(\"codex account method failed\"));\n else results.account = message.result;\n }\n if (\"rateLimits\" in results && \"account\" in results) finish();\n }\n });\n child.stdin.write(`${JSON.stringify(messages[0])}\\n`);\n });\n}\n\nexport function codexUnavailableReport(checkedAt: string): CapacityReport {\n return {\n harness: \"codex\",\n provider: \"openai\",\n generatedAt: checkedAt,\n authenticated: null,\n available: \"unknown\",\n windows: [],\n creditsRemaining: null,\n };\n}\n\nasync function cliFallback(options: CodexProbeOptions): Promise<CapacityReport> {\n if (!options.installed) return codexUnavailableReport(options.checkedAt);\n const messages: RpcMessage[] = [\n {\n id: 1,\n method: \"initialize\",\n params: {\n clientInfo: { name: \"ai-devkit\", title: null, version: \"1\" },\n capabilities: null,\n },\n },\n { method: \"initialized\" },\n { id: 2, method: \"account/rateLimits/read\" },\n { id: 3, method: \"account/read\" },\n ];\n try {\n const rpc = options.rpc ?? ((requests) => appServerRpc(requests, options.timeoutMs));\n const response = await rpc(messages);\n const result = capacityFromSnapshot(\n parseCliUsage(response.rateLimits),\n options,\n response.rateLimits,\n );\n const accountEnvelope = record(response.account);\n if (\n accountEnvelope &&\n Object.hasOwn(accountEnvelope, \"account\") &&\n !record(accountEnvelope.account)\n ) {\n result.authenticated = false;\n result.available = \"unknown\";\n }\n return result;\n } catch {\n return codexUnavailableReport(options.checkedAt);\n }\n}\n\nasync function subscriptionSnapshot(\n access: string,\n accountId: string,\n source: \"pat\" | \"oauth\",\n options: CodexProbeOptions,\n): Promise<UsageSnapshot> {\n const snapshot = await fetchOpenAiSubscriptionCapacity({ access, accountId }, options);\n if (snapshot.authenticated === false) throw new Error(\"unauthorized\");\n return {\n windows: snapshot.windows,\n creditsRemaining: snapshot.creditsRemaining,\n source,\n };\n}\n\nexport async function probeCodexCapacity(options: CodexProbeOptions): Promise<CapacityReport> {\n const credentials = await resolveCodexCredentials(options);\n if (!credentials) return cliFallback(options);\n\n if (credentials.personalAccessToken) {\n try {\n const accountId = await fetchOpenAiPatAccountId(credentials.personalAccessToken, options);\n const snapshot = await subscriptionSnapshot(\n credentials.personalAccessToken,\n accountId,\n \"pat\",\n options,\n );\n return capacityFromSnapshot(snapshot, options);\n } catch {\n // Continue to a separately available OAuth credential before using the CLI.\n }\n }\n\n if (credentials.oauth) {\n try {\n const snapshot = await subscriptionSnapshot(\n credentials.oauth.access,\n credentials.oauth.accountId,\n \"oauth\",\n options,\n );\n return capacityFromSnapshot(snapshot, options);\n } catch {\n return cliFallback(options);\n }\n }\n return cliFallback(options);\n}\n"],"names":["spawn","fetchOpenAiPatAccountId","fetchOpenAiSubscriptionCapacity","parseWhamUsage","resetTime","safeIdentifier","resolveCodexCredentials","CODEX_APP_SERVER_ARGS","record","value","Array","isArray","finiteNumber","Number","isFinite","nonEmptyText","length","parseUsage","raw","source","windows","creditsRemaining","cliWindow","id","label","input","durationMinutes","windowDurationMins","usedPercent","resetsAt","cliSnapshotWindows","fallbackId","snapshot","scope","limitId","primary","secondary","filter","item","parseCliUsage","response","rateLimits","buckets","rateLimitsByLimitId","Object","entries","push","unique","Map","map","window","values","capacityFromSnapshot","options","hasUsage","some","reached","rateLimitReachedType","resetCredits","rateLimitResetCredits","usageLimitResetCredits","harness","provider","generatedAt","checkedAt","authenticated","available","availableCount","appServerRpc","messages","timeoutMs","Promise","resolve","reject","child","stdio","results","buffer","settled","finish","error","clearTimeout","timer","kill","setTimeout","Error","once","stdout","setEncoding","on","chunk","newline","indexOf","line","slice","trim","message","JSON","parse","request","stdin","write","stringify","result","account","codexUnavailableReport","cliFallback","installed","method","params","clientInfo","name","title","version","capabilities","rpc","requests","accountEnvelope","hasOwn","subscriptionSnapshot","access","accountId","probeCodexCapacity","credentials","personalAccessToken","oauth"],"mappings":"AAAA,SAASA,KAAK,QAAQ,qBAAqB;AAC3C,SACEC,uBAAuB,EACvBC,+BAA+B,EAC/BC,cAAc,EACdC,SAAS,EACTC,cAAc,QACT,sCAAsC;AAE7C,SACEC,uBAAuB,QAElB,uCAAuC;AAsB9C,OAAO,MAAMC,wBAAwB;IAAC;IAAM;IAAa;IAAM;IAAa;CAAa,CAAU;AAEnG,SAASC,OAAOC,KAAc;IAC5B,OAAOA,UAAU,QAAQ,OAAOA,UAAU,YAAY,CAACC,MAAMC,OAAO,CAACF,SAChEA,QACD;AACN;AAEA,SAASG,aAAaH,KAAc;IAClC,OAAO,OAAOA,UAAU,YAAYI,OAAOC,QAAQ,CAACL,SAASA,QAAQ;AACvE;AAEA,SAASM,aAAaN,KAAc;IAClC,OAAO,OAAOA,UAAU,YAAYA,MAAMO,MAAM,GAAG,IAAIP,QAAQ;AACjE;AAEA,OAAO,SAASQ,WAAWC,GAAY,EAAEC,MAAuB;IAC9D,MAAM,EAAEC,OAAO,EAAEC,gBAAgB,EAAE,GAAGlB,eAAee;IACrD,OAAO;QAAEE;QAASC;QAAkBF;IAAO;AAC7C;AAEA,SAASG,UAAUb,KAAc,EAAEc,EAAU,EAAEC,KAAa;IAC1D,MAAMC,QAAQjB,OAAOC;IACrB,IAAI,CAACgB,OAAO,OAAO;IACnB,OAAO;QACLF;QACAC;QACAE,iBAAiBd,aAAaa,MAAME,kBAAkB;QACtDC,aAAahB,aAAaa,MAAMG,WAAW;QAC3CC,UAAUzB,UAAUqB,MAAMI,QAAQ;IACpC;AACF;AAEA,SAASC,mBAAmBrB,KAAc,EAAEsB,UAAkB;IAC5D,MAAMC,WAAWxB,OAAOC;IACxB,IAAI,CAACuB,UAAU,OAAO,EAAE;IACxB,MAAMC,QAAQ5B,eAAe2B,SAASE,OAAO,KAAK7B,eAAe0B,e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D;AACrB"}
1
+ {"version":3,"sources":["../../../src/capacity/sources/codex.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport {\n fetchOpenAiPatAccountId,\n fetchOpenAiSubscriptionCapacity,\n resetTime,\n safeIdentifier,\n} from \"../providers/openai-subscription.js\";\nimport type { CapacityReport, CapacityWindow } from \"../types.js\";\nimport {\n resolveCodexCredentials,\n type CodexCredentialOptions,\n} from \"../../harnesses/codex/credentials.js\";\n\ntype UsageSnapshot = {\n windows: CapacityWindow[];\n creditsRemaining: number | null;\n available: CapacityReport[\"available\"] | null;\n};\n\ntype UnknownRecord = Record<string, unknown>;\ntype RpcMessage = { id?: number; method: string; params?: UnknownRecord };\ntype CliResponses = { rateLimits: unknown; account: unknown };\ntype CodexRpc = (messages: RpcMessage[]) => Promise<CliResponses>;\n\nexport type CodexProbeOptions = CodexCredentialOptions & {\n installed: boolean;\n checkedAt: string;\n fetch?: typeof globalThis.fetch;\n rpc?: CodexRpc;\n timeoutMs?: number;\n};\n\nexport const CODEX_APP_SERVER_ARGS = [\"-s\", \"read-only\", \"-a\", \"untrusted\", \"app-server\"] as const;\n\nfunction record(value: unknown): UnknownRecord | null {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as UnknownRecord)\n : null;\n}\n\nfunction finiteNumber(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\nfunction nonEmptyText(value: unknown): string | null {\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nfunction cliWindow(value: unknown, id: string, label: string): CapacityWindow | null {\n const input = record(value);\n if (!input) return null;\n return {\n id,\n label,\n durationMinutes: finiteNumber(input.windowDurationMins),\n usedPercent: finiteNumber(input.usedPercent),\n resetsAt: resetTime(input.resetsAt),\n };\n}\n\nfunction cliSnapshotWindows(value: unknown, fallbackId: string): CapacityWindow[] {\n const snapshot = record(value);\n if (!snapshot) return [];\n const scope = safeIdentifier(snapshot.limitId) ?? safeIdentifier(fallbackId) ?? \"codex\";\n return [\n cliWindow(snapshot.primary, `${scope}:primary`, `${scope} primary`),\n cliWindow(snapshot.secondary, `${scope}:secondary`, `${scope} secondary`),\n ].filter((item): item is CapacityWindow => item !== null);\n}\n\nfunction parseCliUsage(raw: unknown): UsageSnapshot {\n const response = record(raw) ?? {};\n const primary = record(response.rateLimits);\n const windows = primary ? cliSnapshotWindows(primary, \"codex\") : [];\n const buckets = record(response.rateLimitsByLimitId);\n if (buckets) {\n for (const [id, snapshot] of Object.entries(buckets)) {\n windows.push(...cliSnapshotWindows(snapshot, id));\n }\n }\n const unique = [...new Map(windows.map((window) => [window.id, window])).values()];\n return { windows: unique, creditsRemaining: null, available: null };\n}\n\nfunction capacityFromSnapshot(\n snapshot: UsageSnapshot,\n options: CodexProbeOptions,\n raw?: unknown,\n): CapacityReport {\n const hasUsage = snapshot.windows.some((window) => window.usedPercent !== null);\n const rateLimits = record(record(raw)?.rateLimits);\n const reached = nonEmptyText(rateLimits?.rateLimitReachedType);\n const resetCredits =\n record(record(raw)?.rateLimitResetCredits) ?? record(record(raw)?.usageLimitResetCredits);\n let available = snapshot.available;\n if (reached) available = \"no\";\n else if (available === null) available = hasUsage ? \"yes\" : \"unknown\";\n return {\n harness: \"codex\",\n provider: \"openai\",\n generatedAt: options.checkedAt,\n authenticated: true,\n available,\n windows: snapshot.windows,\n creditsRemaining: snapshot.creditsRemaining ?? finiteNumber(resetCredits?.availableCount),\n };\n}\n\nfunction appServerRpc(messages: RpcMessage[], timeoutMs = 5000): Promise<CliResponses> {\n return new Promise((resolve, reject) => {\n const child = spawn(\"codex\", CODEX_APP_SERVER_ARGS, { stdio: [\"pipe\", \"pipe\", \"ignore\"] });\n const results: Partial<CliResponses> = {};\n let buffer = \"\";\n let settled = false;\n const finish = (error?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n child.kill();\n if (error) reject(error);\n else resolve(results as CliResponses);\n };\n const timer = setTimeout(() => finish(new Error(\"codex probe timed out\")), timeoutMs);\n child.once(\"error\", () => finish(new Error(\"codex app-server unavailable\")));\n child.once(\"exit\", () => {\n if (!settled) finish(new Error(\"codex app-server exited\"));\n });\n child.stdout.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk: string) => {\n buffer += chunk;\n for (;;) {\n const newline = buffer.indexOf(\"\\n\");\n if (newline < 0) break;\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n if (!line) continue;\n let message: UnknownRecord;\n try {\n message = JSON.parse(line) as UnknownRecord;\n } catch {\n continue;\n }\n if (message.id === 1) {\n for (const request of messages.slice(1))\n child.stdin.write(`${JSON.stringify(request)}\\n`);\n } else if (message.id === 2) {\n if (message.error) finish(new Error(\"codex rate-limit method failed\"));\n else results.rateLimits = message.result;\n } else if (message.id === 3) {\n if (message.error) finish(new Error(\"codex account method failed\"));\n else results.account = message.result;\n }\n if (\"rateLimits\" in results && \"account\" in results) finish();\n }\n });\n child.stdin.write(`${JSON.stringify(messages[0])}\\n`);\n });\n}\n\nexport function codexUnavailableReport(checkedAt: string): CapacityReport {\n return {\n harness: \"codex\",\n provider: \"openai\",\n generatedAt: checkedAt,\n authenticated: null,\n available: \"unknown\",\n windows: [],\n creditsRemaining: null,\n };\n}\n\nasync function cliFallback(options: CodexProbeOptions): Promise<CapacityReport> {\n if (!options.installed) return codexUnavailableReport(options.checkedAt);\n const messages: RpcMessage[] = [\n {\n id: 1,\n method: \"initialize\",\n params: {\n clientInfo: { name: \"ai-devkit\", title: null, version: \"1\" },\n capabilities: null,\n },\n },\n { method: \"initialized\" },\n { id: 2, method: \"account/rateLimits/read\" },\n { id: 3, method: \"account/read\" },\n ];\n try {\n const rpc = options.rpc ?? ((requests) => appServerRpc(requests, options.timeoutMs));\n const response = await rpc(messages);\n const result = capacityFromSnapshot(\n parseCliUsage(response.rateLimits),\n options,\n response.rateLimits,\n );\n const accountEnvelope = record(response.account);\n if (\n accountEnvelope &&\n Object.hasOwn(accountEnvelope, \"account\") &&\n !record(accountEnvelope.account)\n ) {\n result.authenticated = false;\n result.available = \"unknown\";\n }\n return result;\n } catch {\n return codexUnavailableReport(options.checkedAt);\n }\n}\n\nasync function subscriptionSnapshot(\n access: string,\n accountId: string,\n options: CodexProbeOptions,\n): Promise<UsageSnapshot> {\n const snapshot = await fetchOpenAiSubscriptionCapacity({ access, accountId }, options);\n if (snapshot.authenticated === false) throw new Error(\"unauthorized\");\n return snapshot;\n}\n\nexport async function probeCodexCapacity(options: CodexProbeOptions): Promise<CapacityReport> {\n const credentials = await resolveCodexCredentials(options);\n if (!credentials) return cliFallback(options);\n\n if (credentials.personalAccessToken) {\n try {\n const accountId = await fetchOpenAiPatAccountId(credentials.personalAccessToken, options);\n const snapshot = await subscriptionSnapshot(\n credentials.personalAccessToken,\n accountId,\n options,\n );\n return capacityFromSnapshot(snapshot, options);\n } catch {\n // Continue to a separately available OAuth credential before using the CLI.\n }\n }\n\n if (credentials.oauth) {\n try {\n const snapshot = await subscriptionSnapshot(\n credentials.oauth.access,\n credentials.oauth.accountId,\n options,\n );\n return capacityFromSnapshot(snapshot, options);\n } catch {\n return cliFallback(options);\n }\n }\n return cliFallback(options);\n}\n"],"names":["spawn","fetchOpenAiPatAccountId","fetchOpenAiSubscriptionCapacity","resetTime","safeIdentifier","resolveCodexCredentials","CODEX_APP_SERVER_ARGS","record","value","Array","isArray","finiteNumber","Number","isFinite","nonEmptyText","length","cliWindow","id","label","input","durationMinutes","windowDurationMins","usedPercent","resetsAt","cliSnapshotWindows","fallbackId","snapshot","scope","limitId","primary","secondary","filter","item","parseCliUsage","raw","response","rateLimits","windows","buckets","rateLimitsByLimitId","Object","entries","push","unique","Map","map","window","values","creditsRemaining","available","capacityFromSnapshot","options","hasUsage","some","reached","rateLimitReachedType","resetCredits","rateLimitResetCredits","usageLimitResetCredits","harness","provider","generatedAt","checkedAt","authenticated","availableCount","appServerRpc","messages","timeoutMs","Promise","resolve","reject","child","stdio","results","buffer","settled","finish","error","clearTimeout","timer","kill","setTimeout","Error","once","stdout","setEncoding","on","chunk","newline","indexOf","line","slice","trim","message","JSON","parse","request","stdin","write","stringify","result","account","codexUnavailableReport","cliFallback","installed","method","params","clientInfo","name","title","version","capabilities","rpc","requests","accountEnvelope","hasOwn","subscriptionSnapshot","access","accountId","probeCodexCapacity","credentials","personalAccessToken","oauth"],"mappings":"AAAA,SAASA,KAAK,QAAQ,qBAAqB;AAC3C,SACEC,uBAAuB,EACvBC,+BAA+B,EAC/BC,SAAS,EACTC,cAAc,QACT,sCAAsC;AAE7C,SACEC,uBAAuB,QAElB,uCAAuC;AAqB9C,OAAO,MAAMC,wBAAwB;IAAC;IAAM;IAAa;IAAM;IAAa;CAAa,CAAU;AAEnG,SAASC,OAAOC,KAAc;IAC5B,OAAOA,UAAU,QAAQ,OAAOA,UAAU,YAAY,CAACC,MAAMC,OAAO,CAACF,SAChEA,QACD;AACN;AAEA,SAASG,aAAaH,KAAc;IAClC,OAAO,OAAOA,UAAU,YAAYI,OAAOC,QAAQ,CAACL,SAASA,QAAQ;AACvE;AAEA,SAASM,aAAaN,KAAc;IAClC,OAAO,OAAOA,UAAU,YAAYA,MAAMO,MAAM,GAAG,IAAIP,QAAQ;AACjE;AAEA,SAASQ,UAAUR,KAAc,EAAES,EAAU,EAAEC,KAAa;IAC1D,MAAMC,QAAQZ,OAAOC;IACrB,IAAI,CAACW,OAAO,OAAO;IACnB,OAAO;QACLF;QACAC;QACAE,iBAAiBT,aAAaQ,MAAME,kBAAkB;QACtDC,aAAaX,aAAaQ,MAAMG,WAAW;QAC3CC,UAAUpB,UAAUgB,MAAMI,QAAQ;IACpC;AACF;AAEA,SAASC,mBAAmBhB,KAAc,EAAEiB,UAAkB;IAC5D,MAAMC,WAAWnB,OAAOC;IACxB,IAAI,CAACkB,UAAU,OAAO,EAAE;IACxB,MAAMC,QAAQvB,eAAesB,SAASE,OAAO,KAAKxB,eAAeqB,eAAe;IAChF,OAAO;QACLT,UAAUU,SAASG,OAAO,EAAE,GAAGF,MAAM,QAAQ,CA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hB,SAASC,UAAU;QAErB,MAAM8E,kBAAkB3G,OAAO4B,SAASkE,OAAO;QAC/C,IACEa,mBACA1E,OAAO2E,MAAM,CAACD,iBAAiB,cAC/B,CAAC3G,OAAO2G,gBAAgBb,OAAO,GAC/B;YACAD,OAAOrC,aAAa,GAAG;YACvBqC,OAAOnD,SAAS,GAAG;QACrB;QACA,OAAOmD;IACT,EAAE,OAAM;QACN,OAAOE,uBAAuBnD,QAAQW,SAAS;IACjD;AACF;AAEA,eAAesD,qBACbC,MAAc,EACdC,SAAiB,EACjBnE,OAA0B;IAE1B,MAAMzB,WAAW,MAAMxB,gCAAgC;QAAEmH;QAAQC;IAAU,GAAGnE;IAC9E,IAAIzB,SAASqC,aAAa,KAAK,OAAO,MAAM,IAAImB,MAAM;IACtD,OAAOxD;AACT;AAEA,OAAO,eAAe6F,mBAAmBpE,OAA0B;IACjE,MAAMqE,cAAc,MAAMnH,wBAAwB8C;IAClD,IAAI,CAACqE,aAAa,OAAOjB,YAAYpD;IAErC,IAAIqE,YAAYC,mBAAmB,EAAE;QACnC,IAAI;YACF,MAAMH,YAAY,MAAMrH,wBAAwBuH,YAAYC,mBAAmB,EAAEtE;YACjF,MAAMzB,WAAW,MAAM0F,qBACrBI,YAAYC,mBAAmB,EAC/BH,WACAnE;YAEF,OAAOD,qBAAqBxB,UAAUyB;QACxC,EAAE,OAAM;QACN,4EAA4E;QAC9E;IACF;IAEA,IAAIqE,YAAYE,KAAK,EAAE;QACrB,IAAI;YACF,MAAMhG,WAAW,MAAM0F,qBACrBI,YAAYE,KAAK,CAACL,MAAM,EACxBG,YAAYE,KAAK,CAACJ,SAAS,EAC3BnE;YAEF,OAAOD,qBAAqBxB,UAAUyB;QACxC,EAAE,OAAM;YACN,OAAOoD,YAAYpD;QACrB;IACF;IACA,OAAOoD,YAAYpD;AACrB"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { AgentManager } from "./AgentManager.js";
2
+ export type { EnrichedAgentWire, ListAgentsOptions } from "./AgentManager.js";
2
3
  export { getAnthropicCapacityReport, getClaudeCapacityReport, getCodexCapacityReport, getDevinCapacityReport, getOpenAiCapacityReport, getZaiCapacityReport, } from "./capacity/index.js";
3
4
  export type { CapacityReport, CapacityWindow } from "./capacity/index.js";
4
5
  export { getAgentReadinessReports, worstReadinessStatus, } from "./harnesses/readiness/AgentReadiness.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EACL,0BAA0B,EAC1B,uBAAuB,EACvB,sBAAsB,EACtB,sBAAsB,EACtB,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1E,OAAO,EACL,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,yCAAyC,CAAC;AACjD,YAAY,EACV,qBAAqB,EACrB,oBAAoB,EACpB,kBAAkB,EAClB,eAAe,GAChB,MAAM,yCAAyC,CAAC;AAEjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAE,wBAAwB,EAAE,KAAK,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACnG,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AACtE,YAAY,EACV,YAAY,EACZ,SAAS,EACT,SAAS,EACT,mBAAmB,EACnB,cAAc,EACd,mBAAmB,GACpB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,YAAY,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AA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B,CAAC;AACjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAC7E,OAAO,EAAE,uBAAuB,EAAE,MAAM,uDAAuD,CAAC;AAChG,OAAO,EAAE,sBAAsB,EAAE,MAAM,qDAAqD,CAAC;AAC7F,OAAO,EAAE,mBAAmB,EAAE,MAAM,+CAA+C,CAAC"}
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export { AgentManager } from \"./AgentManager.js\";\nexport {\n getAnthropicCapacityReport,\n getClaudeCapacityReport,\n getCodexCapacityReport,\n getDevinCapacityReport,\n getOpenAiCapacityReport,\n getZaiCapacityReport,\n} from \"./capacity/index.js\";\nexport type { CapacityReport, CapacityWindow } from \"./capacity/index.js\";\n\nexport {\n getAgentReadinessReports,\n worstReadinessStatus,\n} from \"./harnesses/readiness/AgentReadiness.js\";\nexport type {\n AgentReadinessOptions,\n AgentReadinessReport,\n ReadinessAgentType,\n ReadinessStatus,\n} from \"./harnesses/readiness/AgentReadiness.js\";\n\nexport { createBuiltinAdapters } from \"./harnesses/index.js\";\nexport { HARNESS_RUNTIME_PROFILES, type StartableAgentType } from \"./harnesses/runtimeProfiles.js\";\nexport { AGENT_TYPES, AgentStatus } from \"./adapters/AgentAdapter.js\";\nexport type {\n AgentAdapter,\n AgentType,\n AgentInfo,\n ConversationMessage,\n SessionSummary,\n ListSessionsOptions,\n} from \"./adapters/AgentAdapter.js\";\n\nexport { TerminalFocusManager } from \"./terminal/TerminalFocusManager.js\";\nexport { TerminalType } from \"./terminal/types.js\";\nexport type { TerminalLocation } from \"./terminal/types.js\";\nexport { TtyWriter } from \"./terminal/TtyWriter.js\";\n\nexport {\n AgentRegistry,\n RenameNotFoundError,\n RenameConflictError,\n AGENT_RUNTIME_PROVIDERS,\n parseTmuxRuntimeRef,\n} from \"./utils/AgentRegistry.js\";\nexport type { AgentRuntimeProvider } from \"./utils/AgentRegistry.js\";\nexport type { InteractiveAgentRuntime } from \"./runtime/types.js\";\nexport {\n startAgent,\n stopAgent,\n focusAgent,\n sendAgentPrompt,\n TmuxUnavailableError,\n AgentNameInUseError,\n AgentPidPollTimeoutError,\n AgentRuntimeUnavailableError,\n AgentTerminalNotFoundError,\n DEFAULT_PID_POLL_TIMEOUT_MS,\n} from \"./runtime/ManagedAgentRuntime.js\";\n\nexport type { AgentRequest } from \"./utils/agent-requests.js\";\nexport { readLatestAgentRequest, writeAgentRequest } from \"./utils/agent-requests.js\";\n\nexport { AGENT_MODES } from \"./durable/DurableAgent.js\";\nexport type { DurableProvider } from \"./durable/DurableAgent.js\";\nexport { DurableAgentRepository } from \"./durable/DurableAgentRepository.js\";\nexport { ClaudePrintAgentService } from \"./harnesses/claude/durable/ClaudePrintAgentService.js\";\nexport { CodexPrintAgentService } from \"./harnesses/codex/durable/CodexPrintAgentService.js\";\nexport { PiPrintAgentService } from \"./harnesses/pi/durable/PiPrintAgentService.js\";\n"],"names":["AgentManager","getAnthropicCapacityReport","getClaudeCapacityReport","getCodexCapacityReport","getDevinCapacityReport","getOpenAiCapacityReport","getZaiCapacityReport","getAgentReadinessReports","worstReadinessStatus","createBuiltinAdapters","HARNESS_RUNTIME_PROFILES","AGENT_TYPES","AgentStatus","TerminalFocusManager","TerminalType","TtyWriter","AgentRegistry","RenameNotFoundError","RenameConflictError","AGENT_RUNTIME_PROVIDERS","parseTmuxRuntimeRef","startAgent","stopAgent","focusAgent","sendAgentPrompt","TmuxUnavailableError","AgentNameInUseError","AgentPidPollTimeoutError","AgentRuntimeUnavailableError","AgentTerminalNotFoundError","DEFAULT_PID_POLL_TIMEOUT_MS","readLatestAgentRequest","writeAgentRequest","AGENT_MODES","DurableAgentRepository","ClaudePrintAgentService","CodexPrintAgentService","PiPrintAgentService"],"mappings":"AAAA,SAASA,YAAY,QAAQ,oBAAoB;AACjD,SACEC,0BAA0B,EAC1BC,uBAAuB,EACvBC,sBAAsB,EACtBC,sBAAsB,EACtBC,uBAAuB,EACvBC,oBAAoB,QACf,sBAAsB;AAG7B,SACEC,wBAAwB,EACxBC,oBAAoB,QACf,0CAA0C;AAQjD,SAASC,qBAAqB,QAAQ,uBAAuB;AAC7D,SAASC,wBAAwB,QAAiC,iCAAiC;AACnG,SAASC,WAAW,EAAEC,WAAW,QAAQ,6BAA6B;AAUtE,SAASC,oBAAoB,QAAQ,qCAAqC;AAC1E,SAASC,YAAY,QAAQ,sBAAsB;AAEnD,SAASC,SAAS,QAAQ,0BAA0B;AAEpD,SACEC,aAAa,EACbC,mBAAmB,EACnBC,mBAAmB,EACnBC,uBAAuB,EACvBC,mBAAmB,QACd,2BAA2B;AAGlC,SACEC,UAAU,EACVC,SAAS,EACTC,UAAU,EACVC,eAAe,EACfC,oBAAoB,EACpBC,mBAAmB,EACnBC,wBAAwB,EACxBC,4BAA4B,EAC5BC,0BAA0B,EAC1BC,2BAA2B,QACtB,mCAAmC;AAG1C,SAASC,sBAAsB,EAAEC,iBAAiB,QAAQ,4BAA4B;AAEtF,SAASC,WAAW,QAAQ,4BAA4B;AAExD,SAASC,sBAAsB,QAAQ,sCAAsC;AAC7E,SAASC,uBAAuB,QAAQ,wDAAwD;AAChG,SAASC,sBAAsB,QAAQ,sDAAsD;AAC7F,SAASC,mBAAmB,QAAQ,gDAAgD"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export { AgentManager } from \"./AgentManager.js\";\nexport type { EnrichedAgentWire, ListAgentsOptions } from \"./AgentManager.js\";\nexport {\n getAnthropicCapacityReport,\n getClaudeCapacityReport,\n getCodexCapacityReport,\n getDevinCapacityReport,\n getOpenAiCapacityReport,\n getZaiCapacityReport,\n} from \"./capacity/index.js\";\nexport type { CapacityReport, CapacityWindow } from \"./capacity/index.js\";\n\nexport {\n getAgentReadinessReports,\n worstReadinessStatus,\n} from \"./harnesses/readiness/AgentReadiness.js\";\nexport type {\n AgentReadinessOptions,\n AgentReadinessReport,\n ReadinessAgentType,\n ReadinessStatus,\n} from \"./harnesses/readiness/AgentReadiness.js\";\n\nexport { createBuiltinAdapters } from \"./harnesses/index.js\";\nexport { HARNESS_RUNTIME_PROFILES, type StartableAgentType } from \"./harnesses/runtimeProfiles.js\";\nexport { AGENT_TYPES, AgentStatus } from \"./adapters/AgentAdapter.js\";\nexport type {\n AgentAdapter,\n AgentType,\n AgentInfo,\n ConversationMessage,\n SessionSummary,\n ListSessionsOptions,\n} from \"./adapters/AgentAdapter.js\";\n\nexport { TerminalFocusManager } from \"./terminal/TerminalFocusManager.js\";\nexport { TerminalType } from \"./terminal/types.js\";\nexport type { TerminalLocation } from \"./terminal/types.js\";\nexport { TtyWriter } from \"./terminal/TtyWriter.js\";\n\nexport {\n AgentRegistry,\n RenameNotFoundError,\n RenameConflictError,\n AGENT_RUNTIME_PROVIDERS,\n parseTmuxRuntimeRef,\n} from \"./utils/AgentRegistry.js\";\nexport type { AgentRuntimeProvider } from \"./utils/AgentRegistry.js\";\nexport type { InteractiveAgentRuntime } from \"./runtime/types.js\";\nexport {\n startAgent,\n stopAgent,\n focusAgent,\n sendAgentPrompt,\n TmuxUnavailableError,\n AgentNameInUseError,\n AgentPidPollTimeoutError,\n AgentRuntimeUnavailableError,\n AgentTerminalNotFoundError,\n DEFAULT_PID_POLL_TIMEOUT_MS,\n} from \"./runtime/ManagedAgentRuntime.js\";\n\nexport type { AgentRequest } from \"./utils/agent-requests.js\";\nexport { readLatestAgentRequest, writeAgentRequest } from \"./utils/agent-requests.js\";\n\nexport { AGENT_MODES } from \"./durable/DurableAgent.js\";\nexport type { DurableProvider } from \"./durable/DurableAgent.js\";\nexport { DurableAgentRepository } from \"./durable/DurableAgentRepository.js\";\nexport { ClaudePrintAgentService } from \"./harnesses/claude/durable/ClaudePrintAgentService.js\";\nexport { CodexPrintAgentService } from \"./harnesses/codex/durable/CodexPrintAgentService.js\";\nexport { PiPrintAgentService } from \"./harnesses/pi/durable/PiPrintAgentService.js\";\n"],"names":["AgentManager","getAnthropicCapacityReport","getClaudeCapacityReport","getCodexCapacityReport","getDevinCapacityReport","getOpenAiCapacityReport","getZaiCapacityReport","getAgentReadinessReports","worstReadinessStatus","createBuiltinAdapters","HARNESS_RUNTIME_PROFILES","AGENT_TYPES","AgentStatus","TerminalFocusManager","TerminalType","TtyWriter","AgentRegistry","RenameNotFoundError","RenameConflictError","AGENT_RUNTIME_PROVIDERS","parseTmuxRuntimeRef","startAgent","stopAgent","focusAgent","sendAgentPrompt","TmuxUnavailableError","AgentNameInUseError","AgentPidPollTimeoutError","AgentRuntimeUnavailableError","AgentTerminalNotFoundError","DEFAULT_PID_POLL_TIMEOUT_MS","readLatestAgentRequest","writeAgentRequest","AGENT_MODES","DurableAgentRepository","ClaudePrintAgentService","CodexPrintAgentService","PiPrintAgentService"],"mappings":"AAAA,SAASA,YAAY,QAAQ,oBAAoB;AAEjD,SACEC,0BAA0B,EAC1BC,uBAAuB,EACvBC,sBAAsB,EACtBC,sBAAsB,EACtBC,uBAAuB,EACvBC,oBAAoB,QACf,sBAAsB;AAG7B,SACEC,wBAAwB,EACxBC,oBAAoB,QACf,0CAA0C;AAQjD,SAASC,qBAAqB,QAAQ,uBAAuB;AAC7D,SAASC,wBAAwB,QAAiC,iCAAiC;AACnG,SAASC,WAAW,EAAEC,WAAW,QAAQ,6BAA6B;AAUtE,SAASC,oBAAoB,QAAQ,qCAAqC;AAC1E,SAASC,YAAY,QAAQ,sBAAsB;AAEnD,SAASC,SAAS,QAAQ,0BAA0B;AAEpD,SACEC,aAAa,EACbC,mBAAmB,EACnBC,mBAAmB,EACnBC,uBAAuB,EACvBC,mBAAmB,QACd,2BAA2B;AAGlC,SACEC,UAAU,EACVC,SAAS,EACTC,UAAU,EACVC,eAAe,EACfC,oBAAoB,EACpBC,mBAAmB,EACnBC,wBAAwB,EACxBC,4BAA4B,EAC5BC,0BAA0B,EAC1BC,2BAA2B,QACtB,mCAAmC;AAG1C,SAASC,sBAAsB,EAAEC,iBAAiB,QAAQ,4BAA4B;AAEtF,SAASC,WAAW,QAAQ,4BAA4B;AAExD,SAASC,sBAAsB,QAAQ,sCAAsC;AAC7E,SAASC,uBAAuB,QAAQ,wDAAwD;AAChG,SAASC,sBAAsB,QAAQ,sDAAsD;AAC7F,SAASC,mBAAmB,QAAQ,gDAAgD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-devkit/agent-manager",
3
- "version": "0.42.2",
3
+ "version": "0.43.0",
4
4
  "description": "Standalone agent detection and management utilities for AI DevKit",
5
5
  "keywords": [
6
6
  "agent",
@@ -51,6 +51,6 @@
51
51
  "vitest": "^4.1.8"
52
52
  },
53
53
  "engines": {
54
- "node": ">=20.20.0"
54
+ "node": ">=22.0.0"
55
55
  }
56
56
  }
@@ -45,12 +45,26 @@ function adapterPatterns(adapter: AgentAdapter): {
45
45
  };
46
46
  }
47
47
 
48
+ /** Daemon `agent.list` wire shape: `AgentInfo` with `lastActive` as ISO string. */
49
+ export type EnrichedAgentWire = Omit<AgentInfo, "lastActive" | "type" | "status"> & {
50
+ type: string;
51
+ status: string;
52
+ lastActive: string;
53
+ };
54
+
48
55
  export interface ListAgentsOptions {
49
56
  /**
50
57
  * Sort key for the returned list. Defaults to `status`, which orders
51
58
  * waiting → running → idle → unknown, then by name for stability.
52
59
  */
53
60
  sortBy?: AgentSortKey;
61
+ /**
62
+ * Daemon list the caller already fetched. When present (including null)
63
+ * it replaces {@link AgentManagerOptions.fetchEnrichedAgents} for this
64
+ * call: null means the daemon is unavailable (local adapters only); an
65
+ * empty list gets the same local cross-check as a fetched one.
66
+ */
67
+ enriched?: EnrichedAgentWire[] | null;
54
68
  }
55
69
 
56
70
  export interface AgentManagerOptions {
@@ -68,13 +82,30 @@ export interface AgentManagerOptions {
68
82
  * throwing forces the local path; omitting it disables daemon
69
83
  * consumption.
70
84
  */
71
- fetchEnrichedAgents?: () => Promise<Array<
72
- Omit<AgentInfo, "lastActive" | "type" | "status"> & {
73
- type: string;
74
- status: string;
75
- lastActive: string;
76
- }
77
- > | null>;
85
+ fetchEnrichedAgents?: () => Promise<EnrichedAgentWire[] | null>;
86
+ }
87
+
88
+ /**
89
+ * Rebuild a daemon row in the key order local adapters produce. devkitd
90
+ * serializes through `serde_json::Value`, so wire keys arrive
91
+ * alphabetically; `pinned` goes last because the registry overlay appends
92
+ * it on the local path. Keeps `--json` output byte-identical whichever path
93
+ * served the list.
94
+ */
95
+ function fromWire(a: EnrichedAgentWire): AgentInfo {
96
+ const agent: AgentInfo = {
97
+ name: a.name,
98
+ type: a.type as AgentType,
99
+ status: a.status as AgentStatus,
100
+ summary: a.summary,
101
+ pid: a.pid,
102
+ projectPath: a.projectPath,
103
+ sessionId: a.sessionId,
104
+ lastActive: new Date(a.lastActive),
105
+ };
106
+ if (a.sessionFilePath !== undefined) agent.sessionFilePath = a.sessionFilePath;
107
+ if (a.pinned !== undefined) agent.pinned = a.pinned;
108
+ return agent;
78
109
  }
79
110
 
80
111
  class AgentNotRunningError extends Error {
@@ -200,23 +231,21 @@ export class AgentManager {
200
231
  // answer the local result wins, with a warning.
201
232
  let daemonAgents: AgentInfo[] | null = null;
202
233
  let daemonAnsweredEmpty = false;
203
- if (this.options.fetchEnrichedAgents) {
234
+ let enriched: EnrichedAgentWire[] | null = null;
235
+ if (options?.enriched !== undefined) {
236
+ enriched = options.enriched;
237
+ } else if (this.options.fetchEnrichedAgents) {
204
238
  try {
205
- const enriched = await this.options.fetchEnrichedAgents();
206
- if (enriched) {
207
- daemonAgents = enriched.map((a) => ({
208
- ...a,
209
- type: a.type as AgentType,
210
- status: a.status as AgentStatus,
211
- lastActive: new Date(a.lastActive),
212
- }));
213
- daemonAnsweredEmpty = daemonAgents.length === 0;
214
- if (daemonAnsweredEmpty) daemonAgents = null;
215
- }
239
+ enriched = await this.options.fetchEnrichedAgents();
216
240
  } catch {
217
- daemonAgents = null;
241
+ enriched = null;
218
242
  }
219
243
  }
244
+ if (enriched) {
245
+ daemonAgents = enriched.map(fromWire);
246
+ daemonAnsweredEmpty = daemonAgents.length === 0;
247
+ if (daemonAnsweredEmpty) daemonAgents = null;
248
+ }
220
249
  if (daemonAgents) allAgents.push(...daemonAgents);
221
250
 
222
251
  const adapters = daemonAgents ? [] : Array.from(this.adapters.values());
@@ -567,6 +567,101 @@ describe("AgentManager", () => {
567
567
  }
568
568
  });
569
569
 
570
+ it("uses a caller-supplied daemon list instead of fetching", async () => {
571
+ const local = new MockAdapter("claude", [createMockAgent({ name: "local-claude" })]);
572
+ const detectSpy = vi.spyOn(local, "detectAgents");
573
+ const fetchSpy = vi.fn(async () => [wireAgent({ name: "fetched" })]);
574
+ const m = new AgentManager(new AgentRegistry(path.join(tmpDir, "agents.json")), undefined, {
575
+ fetchEnrichedAgents: fetchSpy,
576
+ });
577
+ m.registerAdapter(local);
578
+
579
+ const agents = await m.listAgents({ enriched: [wireAgent()] });
580
+ expect(fetchSpy).not.toHaveBeenCalled();
581
+ expect(detectSpy).not.toHaveBeenCalled();
582
+ expect(agents.map((a) => a.name)).toEqual(["daemon-claude"]);
583
+ });
584
+
585
+ it("treats a caller-supplied null daemon list as local-only", async () => {
586
+ const fetchSpy = vi.fn(async () => [wireAgent()]);
587
+ const m = new AgentManager(new AgentRegistry(path.join(tmpDir, "agents.json")), undefined, {
588
+ fetchEnrichedAgents: fetchSpy,
589
+ });
590
+ m.registerAdapter(new MockAdapter("claude", [createMockAgent({ name: "local-claude" })]));
591
+
592
+ const agents = await m.listAgents({ enriched: null });
593
+ expect(fetchSpy).not.toHaveBeenCalled();
594
+ expect(agents.map((a) => a.name)).toEqual(["local-claude"]);
595
+ });
596
+
597
+ it("cross-checks a caller-supplied empty daemon list against local adapters", async () => {
598
+ const warnSpy = vi.spyOn(console, "error").mockImplementation(() => {});
599
+ const m = new AgentManager(new AgentRegistry(path.join(tmpDir, "agents.json")));
600
+ m.registerAdapter(new MockAdapter("claude", [createMockAgent({ name: "local-claude" })]));
601
+ try {
602
+ const agents = await m.listAgents({ enriched: [] });
603
+ expect(agents.map((a) => a.name)).toEqual(["local-claude"]);
604
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("daemon"));
605
+ } finally {
606
+ warnSpy.mockRestore();
607
+ }
608
+ });
609
+
610
+ it("produces byte-identical JSON for the daemon and local paths", async () => {
611
+ const local: AgentInfo = {
612
+ name: "same",
613
+ type: "claude",
614
+ status: AgentStatus.WAITING,
615
+ summary: "fix the bug",
616
+ pid: 4242,
617
+ projectPath: "/repo",
618
+ sessionId: "sid-1",
619
+ lastActive: new Date("2026-10-08T12:00:00.000Z"),
620
+ sessionFilePath: "/home/.claude/projects/repo/sid-1.jsonl",
621
+ };
622
+ // devkitd serializes through serde_json::Value (BTreeMap), so wire
623
+ // keys arrive alphabetically — not in AgentInfo order.
624
+ const wire = {
625
+ lastActive: "2026-10-08T12:00:00.000Z",
626
+ name: "same",
627
+ pid: 4242,
628
+ pinned: true,
629
+ projectPath: "/repo",
630
+ sessionFilePath: "/home/.claude/projects/repo/sid-1.jsonl",
631
+ sessionId: "sid-1",
632
+ status: "waiting",
633
+ summary: "fix the bug",
634
+ type: "claude",
635
+ };
636
+ const seed = (dir: string) => {
637
+ const registry = new AgentRegistry(path.join(tmpDir, dir, "agents.json"));
638
+ registry.register({
639
+ name: "same",
640
+ type: "claude",
641
+ pid: 4242,
642
+ runtime: "tmux",
643
+ runtimeRef: { session: "same" },
644
+ cwd: "/repo",
645
+ startedAt: "2026-10-08T11:00:00.000Z",
646
+ sessionId: "sid-1",
647
+ sessionFilePath: wire.sessionFilePath,
648
+ pinned: false,
649
+ });
650
+ return registry;
651
+ };
652
+ fs.mkdirSync(path.join(tmpDir, "local"));
653
+ fs.mkdirSync(path.join(tmpDir, "daemon"));
654
+
655
+ const localManager = new AgentManager(seed("local"));
656
+ localManager.registerAdapter(new MockAdapter("claude", [{ ...local }]));
657
+ const daemonManager = new AgentManager(seed("daemon"));
658
+
659
+ const viaLocal = await localManager.listAgents({ enriched: null });
660
+ const viaDaemon = await daemonManager.listAgents({ enriched: [wire] });
661
+ expect(JSON.stringify(viaDaemon, null, 2)).toBe(JSON.stringify(viaLocal, null, 2));
662
+ expect(viaDaemon[0].lastActive).toBeInstanceOf(Date);
663
+ });
664
+
570
665
  it("returns empty without a warning when the daemon and local adapters are both empty", async () => {
571
666
  const local = new MockAdapter("claude");
572
667
  const detectSpy = vi.spyOn(local, "detectAgents");
@@ -1,11 +1,6 @@
1
1
  import { describe, expect, it, vi } from "vitest";
2
- import {
3
- CODEX_APP_SERVER_ARGS,
4
- parseUsage,
5
- probeCodexCapacity,
6
- } from "../../capacity/sources/codex.js";
2
+ import { CODEX_APP_SERVER_ARGS, probeCodexCapacity } from "../../capacity/sources/codex.js";
7
3
  import { resolveCodexAuthPath } from "../../harnesses/codex/credentials.js";
8
- import { toRateWindow } from "../../capacity/providers/openai-subscription.js";
9
4
 
10
5
  const checkedAt = "2026-08-20T10:00:00.000Z";
11
6
  const context = { installed: true, checkedAt };
@@ -56,47 +51,6 @@ describe("Codex auth resolution", () => {
56
51
  });
57
52
  });
58
53
 
59
- describe("Codex API usage mapping", () => {
60
- it("converts an API window without treating missing data as zero", () => {
61
- expect(
62
- toRateWindow(
63
- {
64
- used_percent: 25,
65
- limit_window_seconds: 18_000,
66
- reset_at: 1_787_220_000,
67
- },
68
- "session",
69
- "Session",
70
- ),
71
- ).toEqual({
72
- id: "session",
73
- label: "Session",
74
- durationMinutes: 300,
75
- usedPercent: 25,
76
- resetsAt: "2026-08-20T10:00:00.000Z",
77
- });
78
- expect(toRateWindow({}, "session", "Session")).toMatchObject({
79
- usedPercent: null,
80
- });
81
- });
82
-
83
- it("maps session, weekly, credits, and extra limits", () => {
84
- const snapshot = parseUsage(apiUsage(), "pat");
85
- expect(snapshot).toMatchObject({ source: "pat", creditsRemaining: 12.5 });
86
- expect(snapshot.windows).toEqual([
87
- expect.objectContaining({ id: "session", durationMinutes: 300 }),
88
- expect.objectContaining({ id: "weekly", durationMinutes: 10080 }),
89
- expect.objectContaining({ id: "reviews:primary", durationMinutes: 60 }),
90
- ]);
91
- });
92
-
93
- it("represents missing limits as unavailable rather than zero", () => {
94
- const snapshot = parseUsage({ credits: {} }, "oauth");
95
- expect(snapshot.windows).toEqual([]);
96
- expect(snapshot.creditsRemaining).toBeNull();
97
- });
98
- });
99
-
100
54
  describe("tiered Codex probing", () => {
101
55
  it("selects PAT, calls whoami then usage, and never invokes the CLI", async () => {
102
56
  const fetch = vi
@@ -170,6 +124,47 @@ describe("tiered Codex probing", () => {
170
124
  expect(result.available).toBe("yes");
171
125
  });
172
126
 
127
+ it("reports exhausted when the OpenAI spend control quota is reached", async () => {
128
+ const fetch = vi.fn().mockResolvedValue(
129
+ new Response(
130
+ JSON.stringify({
131
+ spend_control: {
132
+ reached: true,
133
+ individual_limit: {
134
+ unit: "credit",
135
+ limit: "3000",
136
+ used: "3000",
137
+ remaining: "0",
138
+ used_percent: 100,
139
+ reset_at: 1_796_083_200,
140
+ },
141
+ },
142
+ }),
143
+ { status: 200 },
144
+ ),
145
+ );
146
+ const result = await probeCodexCapacity({
147
+ ...context,
148
+ readFile: async () =>
149
+ JSON.stringify({
150
+ tokens: {
151
+ access_token: "oauth-secret",
152
+ account_id: "acct-2",
153
+ expires_at: 1_800_000_000,
154
+ },
155
+ }),
156
+ fetch,
157
+ now: () => new Date("2026-08-20T10:00:00.000Z"),
158
+ });
159
+
160
+ expect(result).toMatchObject({
161
+ harness: "codex",
162
+ provider: "openai",
163
+ available: "no",
164
+ windows: [expect.objectContaining({ id: "spend-control", usedPercent: 100 })],
165
+ });
166
+ });
167
+
173
168
  it.each([
174
169
  [
175
170
  "missing auth file",
@@ -25,7 +25,20 @@
25
25
  "additional_rate_limits": null,
26
26
  "model_usage": [],
27
27
  "credits": { "balance": 4.5 },
28
- "spend_control": {},
28
+ "spend_control": {
29
+ "reached": false,
30
+ "individual_limit": {
31
+ "source": "workspace_spend_controls",
32
+ "unit": "credit",
33
+ "limit": "3000",
34
+ "used": "33.43525505065918",
35
+ "remaining": "2966.564744949341",
36
+ "used_percent": 1,
37
+ "remaining_percent": 99,
38
+ "reset_after_seconds": 1844677,
39
+ "reset_at": 1796083200
40
+ }
41
+ },
29
42
  "rate_limit_reached_type": "none",
30
43
  "promo": null,
31
44
  "rate_limit_reset_credits": { "availableCount": 0 }
@@ -164,7 +164,18 @@ describe("OpenAI OAuth capacity probe", () => {
164
164
  available: "yes",
165
165
  creditsRemaining: 4.5,
166
166
  });
167
- expect(report.windows.map((window) => window.id)).toEqual(["session", "weekly"]);
167
+ expect(report.windows.map((window) => window.id)).toEqual([
168
+ "session",
169
+ "weekly",
170
+ "spend-control",
171
+ ]);
172
+ expect(report.windows.at(-1)).toMatchObject({
173
+ label: "Spend control",
174
+ limitType: "CREDIT_LIMIT",
175
+ total: 3000,
176
+ current: 33.43525505065918,
177
+ remaining: 2966.564744949341,
178
+ });
168
179
  expect(JSON.stringify(report)).not.toContain("fixture-signature");
169
180
  });
170
181
 
@@ -24,7 +24,19 @@ describe("wham usage parsing", () => {
24
24
  usedPercent: 43.2,
25
25
  resetsAt: "2026-10-04T08:52:07.000Z",
26
26
  },
27
+ {
28
+ id: "spend-control",
29
+ label: "Spend control",
30
+ durationMinutes: null,
31
+ usedPercent: 1,
32
+ resetsAt: "2026-12-01T00:00:00.000Z",
33
+ limitType: "CREDIT_LIMIT",
34
+ total: 3000,
35
+ current: 33.43525505065918,
36
+ remaining: 2966.564744949341,
37
+ },
27
38
  ]);
39
+ expect(snapshot).toMatchObject({ authenticated: true, available: "yes" });
28
40
  expect(snapshot.creditsRemaining).toBe(4.5);
29
41
  });
30
42
 
@@ -78,8 +90,14 @@ describe("wham usage parsing", () => {
78
90
  });
79
91
 
80
92
  it("parses non-object payloads into an empty snapshot", () => {
81
- expect(parseWhamUsage(null)).toEqual({ windows: [], creditsRemaining: null });
82
- expect(parseWhamUsage(42)).toEqual({ windows: [], creditsRemaining: null });
93
+ const emptySnapshot = {
94
+ authenticated: true,
95
+ available: "unknown",
96
+ windows: [],
97
+ creditsRemaining: null,
98
+ };
99
+ expect(parseWhamUsage(null)).toEqual(emptySnapshot);
100
+ expect(parseWhamUsage(42)).toEqual(emptySnapshot);
83
101
  });
84
102
 
85
103
  it("never invents usage for windows it cannot parse", () => {