@ai-devkit/agent-manager 0.39.0 → 0.41.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 (61) hide show
  1. package/dist/AgentManager.d.ts +12 -0
  2. package/dist/AgentManager.d.ts.map +1 -1
  3. package/dist/AgentManager.js +20 -1
  4. package/dist/AgentManager.js.map +1 -1
  5. package/dist/__tests__/AgentManager.test.js +111 -0
  6. package/dist/__tests__/AgentManager.test.js.map +1 -1
  7. package/dist/__tests__/capacity/devin.test.js +239 -0
  8. package/dist/__tests__/capacity/devin.test.js.map +1 -0
  9. package/dist/__tests__/fixtures.test.js +218 -0
  10. package/dist/__tests__/fixtures.test.js.map +1 -0
  11. package/dist/__tests__/readiness-fixtures.test.js +54 -0
  12. package/dist/__tests__/readiness-fixtures.test.js.map +1 -0
  13. package/dist/capacity/index.d.ts +3 -0
  14. package/dist/capacity/index.d.ts.map +1 -1
  15. package/dist/capacity/index.js +8 -0
  16. package/dist/capacity/index.js.map +1 -1
  17. package/dist/capacity/providers/devin.d.ts +13 -0
  18. package/dist/capacity/providers/devin.d.ts.map +1 -0
  19. package/dist/capacity/providers/devin.js +92 -0
  20. package/dist/capacity/providers/devin.js.map +1 -0
  21. package/dist/capacity/sources/devin.d.ts +12 -0
  22. package/dist/capacity/sources/devin.d.ts.map +1 -0
  23. package/dist/capacity/sources/devin.js +29 -0
  24. package/dist/capacity/sources/devin.js.map +1 -0
  25. package/dist/fixtures/bundle.d.ts +67 -0
  26. package/dist/fixtures/bundle.d.ts.map +1 -0
  27. package/dist/fixtures/bundle.js +86 -0
  28. package/dist/fixtures/bundle.js.map +1 -0
  29. package/dist/fixtures/capture.d.ts +11 -0
  30. package/dist/fixtures/capture.d.ts.map +1 -0
  31. package/dist/fixtures/capture.js +317 -0
  32. package/dist/fixtures/capture.js.map +1 -0
  33. package/dist/harnesses/devin/credentials.d.ts +10 -0
  34. package/dist/harnesses/devin/credentials.d.ts.map +1 -0
  35. package/dist/harnesses/devin/credentials.js +66 -0
  36. package/dist/harnesses/devin/credentials.js.map +1 -0
  37. package/dist/harnesses/shared.d.ts.map +1 -1
  38. package/dist/harnesses/shared.js +1 -1
  39. package/dist/harnesses/shared.js.map +1 -1
  40. package/dist/index.d.ts +1 -1
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +1 -1
  43. package/dist/index.js.map +1 -1
  44. package/package.json +1 -1
  45. package/src/AgentManager.ts +37 -1
  46. package/src/__tests__/AgentManager.test.ts +84 -0
  47. package/src/__tests__/capacity/devin.test.ts +210 -0
  48. package/src/__tests__/capacity/fixtures/devin-config.json +6 -0
  49. package/src/__tests__/capacity/fixtures/devin-credentials.toml +4 -0
  50. package/src/__tests__/capacity/fixtures/devin-quota-nonplan.json +5 -0
  51. package/src/__tests__/capacity/fixtures/devin-quota.json +10 -0
  52. package/src/__tests__/fixtures.test.ts +247 -0
  53. package/src/__tests__/readiness-fixtures.test.ts +79 -0
  54. package/src/capacity/index.ts +12 -0
  55. package/src/capacity/providers/devin.ts +121 -0
  56. package/src/capacity/sources/devin.ts +49 -0
  57. package/src/fixtures/bundle.ts +130 -0
  58. package/src/fixtures/capture.ts +349 -0
  59. package/src/harnesses/devin/credentials.ts +88 -0
  60. package/src/harnesses/shared.ts +1 -1
  61. package/src/index.ts +1 -0
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Readiness fixture replay: each committed bundle under
3
+ * `fixtures/readiness/` provides the injectable seams (files,
4
+ * executables, command outputs, codexAuth) plus `expected` — the
5
+ * byte-identical reports the readiness probes must produce replaying
6
+ * the same bundle through their injectable seams.
7
+ */
8
+
9
+ import { describe, it, expect } from "vitest";
10
+ import * as fs from "node:fs";
11
+ import * as path from "node:path";
12
+ import {
13
+ getAgentReadinessReports,
14
+ type AgentReadinessOptions,
15
+ } from "../harnesses/readiness/AgentReadiness.js";
16
+
17
+ interface ReadinessBundle {
18
+ options: {
19
+ homeDir: string;
20
+ path: string;
21
+ assetRoot?: string;
22
+ builtInSkillNames?: string[];
23
+ skillRoots?: Record<string, string>;
24
+ };
25
+ /** Absolute path → contents, or "<dir>" for a directory entry. */
26
+ files: Record<string, string>;
27
+ /** Paths that answer X_OK access. */
28
+ executables: string[];
29
+ /** `"command arg1 arg2"` → output; `ok: false` rejects like execFile. */
30
+ commands: Record<string, { stdout: string; stderr?: string; ok?: boolean }>;
31
+ codexAuth?: boolean | null;
32
+ expected: Record<string, unknown>;
33
+ }
34
+
35
+ const READINESS_ROOT = path.resolve(__dirname, "../../../..", "fixtures", "readiness");
36
+
37
+ const bundlePaths = fs.existsSync(READINESS_ROOT)
38
+ ? fs
39
+ .readdirSync(READINESS_ROOT)
40
+ .filter((f) => f.endsWith(".json") && !f.startsWith("live"))
41
+ .sort()
42
+ .map((f) => path.join(READINESS_ROOT, f))
43
+ : [];
44
+
45
+ function replay(bundle: ReadinessBundle): Promise<Record<string, unknown>> {
46
+ const executableSet = new Set(bundle.executables);
47
+ const options: AgentReadinessOptions = {
48
+ homeDir: bundle.options.homeDir,
49
+ path: bundle.options.path,
50
+ assetRoot: bundle.options.assetRoot,
51
+ builtInSkillNames: bundle.options.builtInSkillNames ?? [],
52
+ skillRoots: bundle.options.skillRoots ?? {},
53
+ readFile: async (target) => {
54
+ if (!(target in bundle.files)) throw new Error("missing");
55
+ return bundle.files[target];
56
+ },
57
+ access: async (target) => {
58
+ if (executableSet.has(target) || target in bundle.files) return;
59
+ throw new Error("missing");
60
+ },
61
+ runCommand: async (command, args) => {
62
+ const key = [command, ...args].join(" ");
63
+ const stub = bundle.commands[key];
64
+ if (!stub) throw new Error(`unexpected command ${key}`);
65
+ if (stub.ok === false) throw new Error(`command failed: ${key}`);
66
+ return { stdout: stub.stdout, stderr: stub.stderr ?? "" };
67
+ },
68
+ codexAuth: async () => bundle.codexAuth ?? null,
69
+ };
70
+ return getAgentReadinessReports(options);
71
+ }
72
+
73
+ describe("readiness fixture replay", () => {
74
+ it.each(bundlePaths)("%s", async (bundlePath) => {
75
+ const bundle = JSON.parse(fs.readFileSync(bundlePath, "utf8")) as ReadinessBundle;
76
+ const reports = await replay(bundle);
77
+ expect(reports).toEqual(bundle.expected);
78
+ });
79
+ });
@@ -3,6 +3,7 @@ import { access as fsAccess } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { codexUnavailableReport, probeCodexCapacity } from "./sources/codex.js";
5
5
  import { probeClaudeCapacity, type ClaudeCapacityOptions } from "./sources/claude.js";
6
+ import { probeDevinCapacity, type DevinCapacityOptions } from "./sources/devin.js";
6
7
  import {
7
8
  probeOpenAiCapacity,
8
9
  probePiAnthropicCapacity,
@@ -15,6 +16,7 @@ import type { CapacityReport } from "./types.js";
15
16
 
16
17
  export type { CapacityReport, CapacityWindow } from "./types.js";
17
18
  export type { ClaudeCapacityOptions } from "./sources/claude.js";
19
+ export type { DevinCapacityOptions } from "./sources/devin.js";
18
20
  export type { PiAnthropicCapacityOptions as AnthropicCapacityOptions } from "./sources/pi.js";
19
21
  export type {
20
22
  PiOpenAiCapacityOptions as OpenAiCapacityOptions,
@@ -103,6 +105,16 @@ export async function getClaudeCapacityReport(
103
105
  });
104
106
  }
105
107
 
108
+ export async function getDevinCapacityReport(
109
+ options: DevinCapacityOptions = {},
110
+ ): Promise<CapacityReport> {
111
+ const { now, ...probeOptions } = options;
112
+ return probeDevinCapacity({
113
+ ...probeOptions,
114
+ checkedAt: (now?.() ?? new Date()).toISOString(),
115
+ });
116
+ }
117
+
106
118
  export async function getAnthropicCapacityReport(
107
119
  options: PiAnthropicCapacityOptions = {},
108
120
  ): Promise<CapacityReport> {
@@ -0,0 +1,121 @@
1
+ import type { Availability, CapacityWindow, ProviderCapacitySnapshot } from "../types.js";
2
+ import type { DevinCredential } from "../../harnesses/devin/credentials.js";
3
+
4
+ const DEVIN_WEBAPP_HOST = "https://app.devin.ai";
5
+ const DAY_MINUTES = 24 * 60;
6
+ const WEEK_MINUTES = 7 * 24 * 60;
7
+
8
+ type UnknownRecord = Record<string, unknown>;
9
+
10
+ export type DevinRequestOptions = {
11
+ fetch?: typeof globalThis.fetch;
12
+ timeoutMs?: number;
13
+ };
14
+
15
+ export class DevinHttpError extends Error {
16
+ constructor(
17
+ public readonly status: number,
18
+ message: string,
19
+ ) {
20
+ super(message);
21
+ this.name = "DevinHttpError";
22
+ }
23
+ }
24
+
25
+ function record(value: unknown): UnknownRecord | null {
26
+ return value !== null && typeof value === "object" && !Array.isArray(value)
27
+ ? (value as UnknownRecord)
28
+ : null;
29
+ }
30
+
31
+ function percent(value: unknown): number | null {
32
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
33
+ return Math.max(0, Math.min(100, value));
34
+ }
35
+
36
+ function timestamp(value: unknown): string | null {
37
+ if (typeof value !== "string" || !value) return null;
38
+ const ms = Date.parse(value);
39
+ return Number.isNaN(ms) ? null : new Date(ms).toISOString();
40
+ }
41
+
42
+ function finiteNumber(value: unknown): number | null {
43
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
44
+ }
45
+
46
+ function availability(windows: CapacityWindow[]): Availability {
47
+ if (windows.length === 0) return "unknown";
48
+ return windows.some((window) => window.usedPercent !== null && window.usedPercent < 100)
49
+ ? "yes"
50
+ : "no";
51
+ }
52
+
53
+ export function parseDevinCapacity(raw: unknown): ProviderCapacitySnapshot {
54
+ const root = record(raw);
55
+ if (!root) throw new Error("Invalid Devin quota response");
56
+
57
+ if (root.is_quota_plan !== true || root.has_quota_allocation !== true) {
58
+ return {
59
+ authenticated: true,
60
+ available: "unknown",
61
+ windows: [],
62
+ creditsRemaining: null,
63
+ };
64
+ }
65
+
66
+ const windows: CapacityWindow[] = [];
67
+ if (root.hide_daily_quota !== true) {
68
+ windows.push({
69
+ id: "devin:daily",
70
+ label: "Daily",
71
+ durationMinutes: DAY_MINUTES,
72
+ usedPercent: percent(root.daily_percentage),
73
+ resetsAt: timestamp(root.daily_reset_at),
74
+ });
75
+ }
76
+ windows.push({
77
+ id: "devin:weekly",
78
+ label: "Weekly",
79
+ durationMinutes: WEEK_MINUTES,
80
+ usedPercent: percent(root.weekly_percentage),
81
+ resetsAt: timestamp(root.weekly_reset_at),
82
+ });
83
+
84
+ return {
85
+ authenticated: true,
86
+ available: availability(windows),
87
+ windows,
88
+ creditsRemaining: finiteNumber(root.overage_balance),
89
+ };
90
+ }
91
+
92
+ export async function fetchDevinCapacity(
93
+ credential: DevinCredential,
94
+ options: DevinRequestOptions = {},
95
+ ): Promise<ProviderCapacitySnapshot> {
96
+ const url = `${DEVIN_WEBAPP_HOST}/api/${encodeURIComponent(credential.orgId)}/billing/quota/usage`;
97
+ let response: Response;
98
+ try {
99
+ response = await (options.fetch ?? globalThis.fetch)(url, {
100
+ method: "GET",
101
+ headers: { Authorization: `Bearer ${credential.key}` },
102
+ signal: AbortSignal.timeout(options.timeoutMs ?? 5000),
103
+ });
104
+ } catch {
105
+ throw new Error("Devin quota request failed");
106
+ }
107
+ if (response.status !== 200) {
108
+ throw new DevinHttpError(
109
+ response.status,
110
+ `Devin quota request failed: HTTP ${response.status}`,
111
+ );
112
+ }
113
+ try {
114
+ return parseDevinCapacity(await response.json());
115
+ } catch (error) {
116
+ if (error instanceof SyntaxError) {
117
+ throw new Error("Devin quota response is not valid JSON");
118
+ }
119
+ throw error;
120
+ }
121
+ }
@@ -0,0 +1,49 @@
1
+ import { DevinHttpError, fetchDevinCapacity } from "../providers/devin.js";
2
+ import type { CapacityReport } from "../types.js";
3
+ import {
4
+ resolveDevinCredential,
5
+ type DevinCredentialOptions,
6
+ } from "../../harnesses/devin/credentials.js";
7
+
8
+ export type DevinCapacityOptions = DevinCredentialOptions & {
9
+ now?: () => Date;
10
+ fetch?: typeof globalThis.fetch;
11
+ timeoutMs?: number;
12
+ };
13
+
14
+ export type DevinProbeOptions = DevinCapacityOptions & {
15
+ checkedAt: string;
16
+ };
17
+
18
+ function devinReport(
19
+ snapshot: Omit<CapacityReport, "harness" | "provider" | "generatedAt">,
20
+ checkedAt: string,
21
+ ): CapacityReport {
22
+ return {
23
+ harness: "devin",
24
+ provider: "devin",
25
+ generatedAt: checkedAt,
26
+ ...snapshot,
27
+ };
28
+ }
29
+
30
+ export async function probeDevinCapacity(options: DevinProbeOptions): Promise<CapacityReport> {
31
+ const credential = await resolveDevinCredential(options);
32
+ try {
33
+ const snapshot = await fetchDevinCapacity(credential, options);
34
+ return devinReport(snapshot, options.checkedAt);
35
+ } catch (error) {
36
+ if (error instanceof DevinHttpError && (error.status === 401 || error.status === 403)) {
37
+ return devinReport(
38
+ {
39
+ authenticated: false,
40
+ available: "unknown",
41
+ windows: [],
42
+ creditsRemaining: null,
43
+ },
44
+ options.checkedAt,
45
+ );
46
+ }
47
+ throw error;
48
+ }
49
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Golden-fixture bundles: the parity oracle for the devkit-harness Rust port.
3
+ * A bundle records everything `detectAgents` consumed and produced so both
4
+ * the TS adapter and its Rust port can be run against identical inputs.
5
+ *
6
+ * Format (committed under fixtures/harness/<type>/<case>.json):
7
+ * {
8
+ * adapter, capturedAt, frozenNow,
9
+ * processes: ProcessInfo[],
10
+ * home: { "<relpath under $FIXTURE_HOME>": "<content with $FIXTURE_HOME refs>" },
11
+ * expected: AgentInfo[] (dates as ISO strings)
12
+ * }
13
+ */
14
+
15
+ import type { AgentInfo, ProcessInfo } from "../adapters/AgentAdapter.js";
16
+
17
+ export const HOME_PLACEHOLDER = "$FIXTURE_HOME";
18
+ /** Resolves to the instant home files were written (birthtime matching). */
19
+ export const NOW_PLACEHOLDER = "$NOW";
20
+ /** Resolves to the local `YYYY/MM/DD` day dir at replay (Codex sessions). */
21
+ export const TODAY_PLACEHOLDER = "$TODAY";
22
+
23
+ export interface FixtureBundle {
24
+ adapter: string;
25
+ capturedAt: string;
26
+ /** Epoch ms the clock was frozen at; `"$NOW"` = materialization instant. */
27
+ frozenNow: number | string;
28
+ processes: ProcessInfo[];
29
+ /** Files under the fixture HOME; content may embed HOME_PLACEHOLDER. */
30
+ home: Record<string, string>;
31
+ /**
32
+ * mtime overrides keyed by `home` relpath — epoch ms, or "$NOW" for the
33
+ * materialization instant. Adapters whose output derives from file mtimes
34
+ * (Grok's lastActive / latest-session pick) need deterministic mtimes.
35
+ */
36
+ mtimes?: Record<string, number | string>;
37
+ /**
38
+ * AgentRegistry rows (pid→sessionFilePath etc.) visible at capture time,
39
+ * restricted to captured process pids — adapters' registry caches read
40
+ * this state, so replay seeds an isolated registry with it.
41
+ */
42
+ registry?: Record<string, unknown>[];
43
+ /**
44
+ * SQLite stores adapters consult (OpenCode's opencode.db), keyed by
45
+ * relpath under $FIXTURE_HOME: SQL statements (DDL + INSERTs) executed
46
+ * in order to materialize each db. Statements may embed HOME_PLACEHOLDER.
47
+ */
48
+ sqlite?: Record<string, string[]>;
49
+ expected: Record<string, unknown>[];
50
+ }
51
+
52
+ /**
53
+ * Rewrite harness dot-dir paths (`<home>/.claude`, `<home>/.codex`, …) to the
54
+ * placeholder — nothing else. Project cwds share the home prefix
55
+ * (`<home>/Code/proj`) and MUST stay literal: harnesses encode them into
56
+ * session-dir names (`-Users-foo-proj`), so rewriting them breaks
57
+ * cwd↔session matching on replay.
58
+ */
59
+ export function sanitize<T>(value: T, realHome: string): T {
60
+ const homeDot = `${realHome}/.`;
61
+ if (typeof value === "string") {
62
+ return value.split(homeDot).join(`${HOME_PLACEHOLDER}/.`) as T;
63
+ }
64
+ if (Array.isArray(value)) return value.map((v) => sanitize(v, realHome)) as T;
65
+ if (value && typeof value === "object") {
66
+ if (value instanceof Date) return value.toISOString() as T;
67
+ const out: Record<string, unknown> = {};
68
+ for (const [k, v] of Object.entries(value)) out[k] = sanitize(v, realHome);
69
+ return out as T;
70
+ }
71
+ return value;
72
+ }
73
+
74
+ /** Inverse of sanitize: expand the placeholder to a concrete dir. */
75
+ export function expand<T>(value: T, fixtureHome: string): T {
76
+ if (typeof value === "string") {
77
+ return value.split(HOME_PLACEHOLDER).join(fixtureHome) as T;
78
+ }
79
+ if (Array.isArray(value)) return value.map((v) => expand(v, fixtureHome)) as T;
80
+ if (value && typeof value === "object" && !(value instanceof Date)) {
81
+ const out: Record<string, unknown> = {};
82
+ for (const [k, v] of Object.entries(value)) out[k] = expand(v, fixtureHome);
83
+ return out as T;
84
+ }
85
+ return value;
86
+ }
87
+
88
+ /** Replace NOW_PLACEHOLDER strings with a resolved ISO instant. */
89
+ export function expandNow<T>(value: T, isoInstant: string): T {
90
+ if (typeof value === "string") {
91
+ return value.split(NOW_PLACEHOLDER).join(isoInstant) as T;
92
+ }
93
+ if (Array.isArray(value)) return value.map((v) => expandNow(v, isoInstant)) as T;
94
+ if (value && typeof value === "object" && !(value instanceof Date)) {
95
+ const out: Record<string, unknown> = {};
96
+ for (const [k, v] of Object.entries(value)) out[k] = expandNow(v, isoInstant);
97
+ return out as T;
98
+ }
99
+ return value;
100
+ }
101
+
102
+ /** Agents normalized the way the wire carries them (Date → ISO string). */
103
+ export function normalizeAgents(agents: AgentInfo[], realHome: string) {
104
+ return sanitize(JSON.parse(JSON.stringify(agents)), realHome);
105
+ }
106
+
107
+ /**
108
+ * Freeze `Date` at `epochMs` for the duration of `fn`. Adapters stamp
109
+ * `new Date()` in several places; parity requires a fixed clock.
110
+ */
111
+ export async function withFrozenClock<T>(epochMs: number, fn: () => Promise<T>): Promise<T> {
112
+ const RealDate = Date;
113
+ class FrozenDate extends RealDate {
114
+ constructor(...args: unknown[]) {
115
+ if (args.length === 0) super(epochMs);
116
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
117
+ else super(...(args as [any]));
118
+ }
119
+ static override now() {
120
+ return epochMs;
121
+ }
122
+ }
123
+ const g = globalThis as { Date: DateConstructor };
124
+ g.Date = FrozenDate as DateConstructor;
125
+ try {
126
+ return await fn();
127
+ } finally {
128
+ g.Date = RealDate;
129
+ }
130
+ }