Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
280 changes: 280 additions & 0 deletions packages/api-client/src/posthog-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,18 @@ import {
type DismissalReasonOptionValue,
SEAT_PRODUCT_KEY,
} from "@posthog/shared";
import type {
AgentAggregateStats,
AgentApplication,
AgentApplicationSessionDetail,
AgentApplicationSessionsListResponse,
AgentApprovalRequest,
AgentApprovalsListParams,
AgentFleetLiveSessionsResponse,
AgentRevision,
AgentSessionsListParams,
DecideApprovalRequest,
} from "@posthog/shared/agent-platform-types";
import type {
ActionabilityJudgmentArtefact,
AvailableSuggestedReviewer,
Expand Down Expand Up @@ -3969,4 +3981,272 @@ export class PostHogAPIClient {
}
return (await response.json()) as LlmSkillFile;
}

// --- Agent platform ------------------------------------------------------
// Deployed agents (`agent_platform` Django app). These routes aren't in the
// generated OpenAPI client, so they use the raw fetcher. Applications are
// addressable by UUID or slug in the `{idOrSlug}` segment.

private agentApplicationsPath(teamId: number): string {
return `/api/projects/${teamId}/agent_applications/`;
}

/** Lists non-archived agent applications for the current team. */
async listAgentApplications(): Promise<AgentApplication[]> {
const MAX_PAGES = 50;
const teamId = await this.getTeamId();
const all: AgentApplication[] = [];
let urlPath = `${this.agentApplicationsPath(teamId)}?limit=100`;
for (let i = 0; i < MAX_PAGES; i++) {
const url = new URL(`${this.api.baseUrl}${urlPath}`);
const response = await this.api.fetcher.fetch({
method: "get",
url,
path: urlPath,
});
const page = (await response.json()) as {
results?: AgentApplication[];
next?: string | null;
};
all.push(...(page.results ?? []));
if (!page.next) return all;
const nextUrl = new URL(page.next);
urlPath = `${nextUrl.pathname}${nextUrl.search}`;
}
return all;
}

/** Fetches a single agent application by UUID or slug; null if not found. */
async getAgentApplication(
idOrSlug: string,
): Promise<AgentApplication | null> {
const teamId = await this.getTeamId();
const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/`;
const url = new URL(`${this.api.baseUrl}${path}`);
try {
const response = await this.api.fetcher.fetch({
method: "get",
url,
path,
});
return (await response.json()) as AgentApplication;
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
if (msg.includes("[404]") || msg.includes("[403]")) {
return null;
}
throw error;
}
}

/** Per-application roll-up stats. `since` is an ISO timestamp window start. */
async getAgentApplicationStats(
idOrSlug: string,
since?: string,
): Promise<AgentAggregateStats> {
const teamId = await this.getTeamId();
const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/stats/`;
const url = new URL(`${this.api.baseUrl}${path}`);
if (since) {
url.searchParams.set("since", since);
}
const response = await this.api.fetcher.fetch({ method: "get", url, path });
return (await response.json()) as AgentAggregateStats;
}

/** Lists sessions for an application (paginated, filterable by state). */
async listAgentApplicationSessions(
idOrSlug: string,
params?: AgentSessionsListParams,
): Promise<AgentApplicationSessionsListResponse> {
const teamId = await this.getTeamId();
const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/sessions/`;
const url = new URL(`${this.api.baseUrl}${path}`);
if (params?.limit != null) {
url.searchParams.set("limit", String(params.limit));
}
if (params?.offset != null) {
url.searchParams.set("offset", String(params.offset));
}
if (params?.state?.length) {
url.searchParams.set("state", params.state.join(","));
}
if (params?.revision_id) {
url.searchParams.set("revision_id", params.revision_id);
}
if (params?.created_after) {
url.searchParams.set("created_after", params.created_after);
}
if (params?.created_before) {
url.searchParams.set("created_before", params.created_before);
}
const response = await this.api.fetcher.fetch({ method: "get", url, path });
const data = (await response.json()) as {
results?: AgentApplicationSessionsListResponse["results"];
count?: number;
};
return {
results: data.results ?? [],
count: data.count ?? data.results?.length ?? 0,
};
}

/** Full session detail incl. transcript; `lastN` trims to trailing messages. */
async getAgentApplicationSession(
idOrSlug: string,
sessionId: string,
lastN?: number,
): Promise<AgentApplicationSessionDetail | null> {
const teamId = await this.getTeamId();
const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/sessions/${encodeURIComponent(sessionId)}/`;
const url = new URL(`${this.api.baseUrl}${path}`);
if (lastN != null) {
url.searchParams.set("last_n", String(lastN));
}
try {
const response = await this.api.fetcher.fetch({
method: "get",
url,
path,
});
return (await response.json()) as AgentApplicationSessionDetail;
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
if (msg.includes("[404]") || msg.includes("[403]")) {
return null;
}
throw error;
}
}

/** Lists tool-approval requests for an application (team-admin only). */
async listAgentApplicationApprovals(
idOrSlug: string,
params?: AgentApprovalsListParams,
): Promise<AgentApprovalRequest[]> {
const teamId = await this.getTeamId();
const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/approvals/`;
const url = new URL(`${this.api.baseUrl}${path}`);
if (params?.state) {
url.searchParams.set("state", params.state);
}
if (params?.limit != null) {
url.searchParams.set("limit", String(params.limit));
}
if (params?.offset != null) {
url.searchParams.set("offset", String(params.offset));
}
const response = await this.api.fetcher.fetch({ method: "get", url, path });
const data = (await response.json()) as {
results?: AgentApprovalRequest[];
};
return data.results ?? [];
}

/** Approve or reject a queued tool-approval request. */
async decideAgentApproval(
idOrSlug: string,
approvalId: string,
body: DecideApprovalRequest,
): Promise<AgentApprovalRequest> {
const teamId = await this.getTeamId();
const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/approvals/${encodeURIComponent(approvalId)}/decide/`;
const url = new URL(`${this.api.baseUrl}${path}`);
const response = await this.api.fetcher.fetch({
method: "post",
url,
path,
overrides: { body: JSON.stringify(body) },
});
return (await response.json()) as AgentApprovalRequest;
}

/** Lists revisions for an application (newest first, paginated). */
async listAgentRevisions(idOrSlug: string): Promise<AgentRevision[]> {
const teamId = await this.getTeamId();
const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/`;
const url = new URL(`${this.api.baseUrl}${path}?limit=100`);
const response = await this.api.fetcher.fetch({ method: "get", url, path });
const data = (await response.json()) as { results?: AgentRevision[] };
return data.results ?? [];
}

/** Fetches a single revision by id; null if not found. */
async getAgentRevision(
idOrSlug: string,
revisionId: string,
): Promise<AgentRevision | null> {
const teamId = await this.getTeamId();
const path = `${this.agentApplicationsPath(teamId)}${encodeURIComponent(idOrSlug)}/revisions/${encodeURIComponent(revisionId)}/`;
const url = new URL(`${this.api.baseUrl}${path}`);
try {
const response = await this.api.fetcher.fetch({
method: "get",
url,
path,
});
return (await response.json()) as AgentRevision;
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
if (msg.includes("[404]") || msg.includes("[403]")) {
return null;
}
throw error;
}
}

/** Team-wide fleet roll-up stats. `since` is an ISO timestamp window start. */
async getAgentFleetStats(since?: string): Promise<AgentAggregateStats> {
const teamId = await this.getTeamId();
const path = `/api/projects/${teamId}/agent_fleet/stats/`;
const url = new URL(`${this.api.baseUrl}${path}`);
if (since) {
url.searchParams.set("since", since);
}
const response = await this.api.fetcher.fetch({ method: "get", url, path });
return (await response.json()) as AgentAggregateStats;
}

/** Live (non-terminal) sessions across every agent on the team. */
async listAgentFleetLiveSessions(
limit?: number,
): Promise<AgentFleetLiveSessionsResponse> {
const teamId = await this.getTeamId();
const path = `/api/projects/${teamId}/agent_fleet/live_sessions/`;
const url = new URL(`${this.api.baseUrl}${path}`);
if (limit != null) {
url.searchParams.set("limit", String(limit));
}
const response = await this.api.fetcher.fetch({ method: "get", url, path });
const data = (await response.json()) as {
results?: AgentFleetLiveSessionsResponse["results"];
};
return { results: data.results ?? [] };
}

/** All tool-approval requests across the team (team-admin only). */
async listAgentFleetApprovals(
params?: AgentApprovalsListParams,
): Promise<AgentApprovalRequest[]> {
const teamId = await this.getTeamId();
const path = `/api/projects/${teamId}/agent_fleet/approvals/`;
const url = new URL(`${this.api.baseUrl}${path}`);
if (params?.state) {
url.searchParams.set("state", params.state);
}
if (params?.agent_id) {
url.searchParams.set("agent_id", params.agent_id);
}
if (params?.limit != null) {
url.searchParams.set("limit", String(params.limit));
}
if (params?.offset != null) {
url.searchParams.set("offset", String(params.offset));
}
const response = await this.api.fetcher.fetch({ method: "get", url, path });
const data = (await response.json()) as {
results?: AgentApprovalRequest[];
};
return data.results ?? [];
}
}
4 changes: 4 additions & 0 deletions packages/shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
"types": "./dist/analytics-events.d.ts",
"import": "./dist/analytics-events.js"
},
"./agent-platform-types": {
"types": "./dist/agent-platform-types.d.ts",
"import": "./dist/agent-platform-types.js"
},
"./domain-types": {
"types": "./dist/domain-types.d.ts",
"import": "./dist/domain-types.js"
Expand Down
Loading
Loading