diff --git a/package-lock.json b/package-lock.json index ab4079d..c21b44c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@polyscope/sdk", - "version": "0.1.0", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@polyscope/sdk", - "version": "0.1.0", + "version": "0.2.0", "license": "MIT", "devDependencies": { "@types/node": "^25.3.2", diff --git a/package.json b/package.json index 4103394..6be95c1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@polyscope/sdk", - "version": "0.1.0", + "version": "0.2.0", "description": "Official Polyscope SDK for JavaScript and TypeScript", "type": "module", "main": "./dist/index.cjs", diff --git a/src/client.ts b/src/client.ts index 75c68a4..351c092 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,21 +1,27 @@ import { HttpClient } from "./http.js"; import { MissingApiTokenError } from "./errors.js"; import { previewUrlMatches, toPreviewLookupUrl } from "./url-matching.js"; +import { ServerModels } from "./resources/models.js"; import { Repository } from "./resources/repository.js"; import { Server } from "./resources/server.js"; +import { TeamInvite } from "./resources/team-invite.js"; import { GenericResource, Workspace, + toCreateWorkspaceBody, } from "./resources/workspace.js"; import { resolveApiToken } from "./utils/settings.js"; import type { CreateWorkspaceParams, GenericResourceData, + ListModelsParams, ListRepositoriesParams, ListWorkspacesParams, PolyscopeConfig, RepositoryData, ServerData, + ServerModelsData, + TeamInviteData, WorkspaceData, } from "./types.js"; @@ -88,6 +94,29 @@ export class Polyscope { return response.data.map((s) => new Server(s)); } + async models(params?: ListModelsParams): Promise { + const http = await this.getHttp(); + const query: Record = {}; + if (params?.serverId) { + query.server_id = params.serverId; + } + + const response = await http.get<{ data: ServerModelsData[] }>( + "models", + query, + ); + return response.data.map((m) => new ServerModels(m)); + } + + async inviteTeamMember(email: string): Promise { + const http = await this.getHttp(); + const response = await http.post<{ data: TeamInviteData }>( + "team/invites", + { email }, + ); + return new TeamInvite(response.data); + } + // --- Repositories --- async repositories(params?: ListRepositoriesParams): Promise { @@ -108,17 +137,9 @@ export class Polyscope { async createWorkspace(params: CreateWorkspaceParams): Promise { const http = await this.getHttp(); - const body = { - repository_id: params.repositoryId, - prompt: params.prompt ?? undefined, - server_id: params.serverId ?? undefined, - issue_url: params.issueUrl ?? undefined, - pull_request_url: params.pullRequestUrl ?? undefined, - }; - const response = await http.post<{ data: WorkspaceData }>( "workspaces", - body, + toCreateWorkspaceBody(params), ); return new Workspace(response.data, http); } diff --git a/src/http.ts b/src/http.ts index 09d055d..75fb9de 100644 --- a/src/http.ts +++ b/src/http.ts @@ -3,7 +3,7 @@ import type { ApiErrorResponse } from "./types.js"; const DEFAULT_BASE_URL = "https://getpolyscope.com"; const DEFAULT_TIMEOUT = 30_000; -const USER_AGENT = "Polyscope JS SDK/0.1"; +const USER_AGENT = "Polyscope JS SDK/0.2"; export class HttpClient { private apiToken: string; diff --git a/src/index.ts b/src/index.ts index 9002c87..ff8bc73 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,6 +16,8 @@ export { export { Server } from "./resources/server.js"; export { Repository } from "./resources/repository.js"; +export { ServerModels, AvailableAgent } from "./resources/models.js"; +export { TeamInvite } from "./resources/team-invite.js"; export { Workspace, WorkspaceDiff, @@ -31,16 +33,25 @@ export type { ServerData, RepositoryData, WorkspaceData, + WorkspaceStatus, + InterfaceMode, MessageData, + MessageRole, DiffFileData, DiffStatsData, DiffSnapshotData, WorkspaceDiffData, GenericResourceData, + ServerModelsData, + AvailableAgentData, + ModelCapabilitiesData, + TeamInviteData, CreateWorkspaceParams, SendMessageParams, + CommitParams, CreatePullRequestParams, ListWorkspacesParams, ListRepositoriesParams, + ListModelsParams, PolyscopeConfig, } from "./types.js"; diff --git a/src/resources/models.ts b/src/resources/models.ts new file mode 100644 index 0000000..8a21142 --- /dev/null +++ b/src/resources/models.ts @@ -0,0 +1,44 @@ +import type { + AvailableAgentData, + ModelCapabilitiesData, + ServerModelsData, +} from "../types.js"; + +export class AvailableAgent { + readonly id: string; + readonly name: string; + readonly models: string[]; + + constructor(data: AvailableAgentData) { + this.id = data.id; + this.name = data.name; + this.models = data.models; + } +} + +export class ServerModels { + readonly serverId: string; + readonly agents: AvailableAgent[]; + readonly models: string[]; + readonly modelCapabilities: ModelCapabilitiesData[]; + + constructor(data: ServerModelsData) { + this.serverId = data.server_id; + this.agents = data.agents.map((a) => new AvailableAgent(a)); + this.models = data.models; + this.modelCapabilities = data.model_capabilities; + } + + toJSON(): ServerModelsData { + return { + server_id: this.serverId, + agents: this.agents.map((a) => ({ + id: a.id, + name: a.name, + models: a.models, + })), + models: this.models, + model_capabilities: this.modelCapabilities, + }; + } +} diff --git a/src/resources/repository.ts b/src/resources/repository.ts index d007c5a..2e52b28 100644 --- a/src/resources/repository.ts +++ b/src/resources/repository.ts @@ -1,6 +1,6 @@ import type { HttpClient } from "../http.js"; import type { CreateWorkspaceParams, RepositoryData, WorkspaceData } from "../types.js"; -import { Workspace } from "./workspace.js"; +import { Workspace, toCreateWorkspaceBody } from "./workspace.js"; export class Repository { readonly id: string; @@ -8,7 +8,12 @@ export class Repository { readonly path: string; readonly baseBranch: string; readonly defaultModel: string | null; + readonly reviewModel: string | null; + readonly reviewPrompt: string | null; + readonly githubAssignSelfEnabled: boolean; + /** @deprecated No longer sent by the API, always `false`. Replaced by `githubAssignSelfEnabled`. */ readonly githubReactionEnabled: boolean; + /** @deprecated No longer sent by the API, always `null`. */ readonly githubReactionEmoji: string | null; readonly mergePrompt: string | null; readonly mergeAndPushPrompt: string | null; @@ -16,6 +21,7 @@ export class Repository { readonly draftPrPrompt: string | null; readonly worktreeBaseFromOrigin: boolean | null; readonly hasRemote: boolean; + readonly nonGit: boolean; readonly linkedRepoIds: string[]; readonly createdAt: string; readonly serverId: string | null; @@ -29,14 +35,18 @@ export class Repository { this.path = data.path; this.baseBranch = data.base_branch; this.defaultModel = data.default_model; - this.githubReactionEnabled = data.github_reaction_enabled; - this.githubReactionEmoji = data.github_reaction_emoji; + this.reviewModel = data.review_model ?? null; + this.reviewPrompt = data.review_prompt ?? null; + this.githubAssignSelfEnabled = data.github_assign_self_enabled ?? false; + this.githubReactionEnabled = data.github_reaction_enabled ?? false; + this.githubReactionEmoji = data.github_reaction_emoji ?? null; this.mergePrompt = data.merge_prompt; this.mergeAndPushPrompt = data.merge_and_push_prompt; this.prPrompt = data.pr_prompt; this.draftPrPrompt = data.draft_pr_prompt; this.worktreeBaseFromOrigin = data.worktree_base_from_origin; this.hasRemote = data.has_remote; + this.nonGit = data.non_git ?? false; this.linkedRepoIds = data.linked_repo_ids; this.createdAt = data.created_at; this.serverId = data.server_id; @@ -46,16 +56,11 @@ export class Repository { async createWorkspace( params: Omit | string, ): Promise { - const body = + const body = toCreateWorkspaceBody( typeof params === "string" - ? { repository_id: this.id, prompt: params } - : { - repository_id: this.id, - prompt: params.prompt ?? undefined, - server_id: params.serverId ?? undefined, - issue_url: params.issueUrl ?? undefined, - pull_request_url: params.pullRequestUrl ?? undefined, - }; + ? { repositoryId: this.id, prompt: params } + : { ...params, repositoryId: this.id }, + ); const response = await this.http.post<{ data: WorkspaceData }>( "workspaces", @@ -71,14 +76,16 @@ export class Repository { path: this.path, base_branch: this.baseBranch, default_model: this.defaultModel, - github_reaction_enabled: this.githubReactionEnabled, - github_reaction_emoji: this.githubReactionEmoji, + review_model: this.reviewModel, + review_prompt: this.reviewPrompt, + github_assign_self_enabled: this.githubAssignSelfEnabled, merge_prompt: this.mergePrompt, merge_and_push_prompt: this.mergeAndPushPrompt, pr_prompt: this.prPrompt, draft_pr_prompt: this.draftPrPrompt, worktree_base_from_origin: this.worktreeBaseFromOrigin, has_remote: this.hasRemote, + non_git: this.nonGit, linked_repo_ids: this.linkedRepoIds, created_at: this.createdAt, server_id: this.serverId, diff --git a/src/resources/team-invite.ts b/src/resources/team-invite.ts new file mode 100644 index 0000000..3da3d8f --- /dev/null +++ b/src/resources/team-invite.ts @@ -0,0 +1,11 @@ +import type { TeamInviteData } from "../types.js"; + +export class TeamInvite { + readonly email: string; + readonly invited: boolean; + + constructor(data: TeamInviteData) { + this.email = data.email; + this.invited = data.invited; + } +} diff --git a/src/resources/workspace.ts b/src/resources/workspace.ts index b4f8057..48c8af7 100644 --- a/src/resources/workspace.ts +++ b/src/resources/workspace.ts @@ -1,21 +1,39 @@ import type { HttpClient } from "../http.js"; import type { + CommitParams, CreatePullRequestParams, + CreateWorkspaceParams, DiffFileData, DiffSnapshotData, DiffStatsData, GenericResourceData, + InterfaceMode, MessageData, + MessageRole, SendMessageParams, WorkspaceData, WorkspaceDiffData, WorkspaceMessagesResponse, + WorkspaceStatus, } from "../types.js"; +export function toCreateWorkspaceBody(params: CreateWorkspaceParams) { + return { + repository_id: params.repositoryId, + prompt: params.prompt ?? undefined, + server_id: params.serverId ?? undefined, + base_branch: params.baseBranch ?? undefined, + model: params.model ?? undefined, + issue_url: params.issueUrl ?? undefined, + pull_request_url: params.pullRequestUrl ?? undefined, + linear_issue_url: params.linearIssueUrl ?? undefined, + }; +} + export class Message { readonly id: number; readonly sessionId: string; - readonly role: "user" | "assistant" | "system"; + readonly role: MessageRole; readonly content: string; readonly metadata: string | null; readonly createdAt: string; @@ -80,7 +98,7 @@ export class WorkspaceDiff { this.stats = new DiffStats(data.stats); this.local = new DiffSnapshot(data.local); this.base = new DiffSnapshot(data.base); - this.commitsAhead = data.commits_ahead; + this.commitsAhead = data.commitsAhead; } } @@ -117,11 +135,14 @@ export class Workspace { readonly id: string; readonly repoId: string; readonly serverId: string | null; + readonly url: string | null; readonly branch: string; readonly branchRenamed: boolean; readonly path: string; + readonly interfaceMode: InterfaceMode; + readonly model: string | null; readonly previewUrl: string | null; - readonly status: string; + readonly status: WorkspaceStatus; readonly prNumber: number | null; readonly prUrl: string | null; readonly prTitle: string | null; @@ -130,8 +151,12 @@ export class Workspace { readonly issueNumber: number | null; readonly issueTitle: string | null; readonly issueUrl: string | null; - readonly baseBranch: string; - readonly baseCommit: string; + readonly baseBranch: string | null; + readonly baseCommit: string | null; + readonly labelId: string | null; + readonly isRepoWorkspace: boolean; + readonly hasActivity: boolean; + readonly linkedFromWorktreeId: string | null; readonly linkedWorktreeIds: string[]; readonly createdAt: string; readonly repository: { @@ -150,10 +175,13 @@ export class Workspace { this.id = data.id; this.repoId = data.repo_id; this.serverId = data.server_id; + this.url = data.url ?? null; this.branch = data.branch; this.branchRenamed = data.branch_renamed; this.path = data.path; - this.previewUrl = data.preview_url; + this.interfaceMode = data.interface_mode ?? "chat"; + this.model = data.model ?? null; + this.previewUrl = data.preview_url ?? null; this.status = data.status; this.prNumber = data.pr_number; this.prUrl = data.pr_url; @@ -165,6 +193,10 @@ export class Workspace { this.issueUrl = data.issue_url; this.baseBranch = data.base_branch; this.baseCommit = data.base_commit; + this.labelId = data.label_id ?? null; + this.isRepoWorkspace = data.is_repo_workspace ?? false; + this.hasActivity = data.has_activity ?? false; + this.linkedFromWorktreeId = data.linked_from_worktree_id ?? null; this.linkedWorktreeIds = data.linked_worktree_ids; this.createdAt = data.created_at; this.repository = data.repository @@ -175,7 +207,7 @@ export class Workspace { path: data.repository.path, } : null; - this.agent = data.agent; + this.agent = data.agent ?? null; this.stats = data.stats ? new DiffStats(data.stats) : null; this.http = http; } @@ -233,9 +265,10 @@ export class Workspace { return new WorkspaceDiff(response.data); } - async commit(): Promise { + async commit(params?: CommitParams): Promise { const response = await this.http.post<{ data: GenericResourceData }>( `workspaces/${this.id}/commit`, + { model: params?.model ?? undefined }, ); return new GenericResource(response.data); } @@ -246,6 +279,7 @@ export class Workspace { title: params.title ?? undefined, body: params.body ?? undefined, draft: params.draft ?? undefined, + model: params.model ?? undefined, } : {}; @@ -268,9 +302,12 @@ export class Workspace { id: this.id, repo_id: this.repoId, server_id: this.serverId, + url: this.url ?? undefined, branch: this.branch, branch_renamed: this.branchRenamed, path: this.path, + interface_mode: this.interfaceMode, + model: this.model, preview_url: this.previewUrl, status: this.status, pr_number: this.prNumber, @@ -283,6 +320,10 @@ export class Workspace { issue_url: this.issueUrl, base_branch: this.baseBranch, base_commit: this.baseCommit, + label_id: this.labelId, + is_repo_workspace: this.isRepoWorkspace, + has_activity: this.hasActivity, + linked_from_worktree_id: this.linkedFromWorktreeId, linked_worktree_ids: this.linkedWorktreeIds, created_at: this.createdAt, repository: this.repository diff --git a/src/types.ts b/src/types.ts index a55c37f..5586b85 100644 --- a/src/types.ts +++ b/src/types.ts @@ -13,28 +13,41 @@ export interface RepositoryData { path: string; base_branch: string; default_model: string | null; - github_reaction_enabled: boolean; - github_reaction_emoji: string | null; + review_model?: string | null; + review_prompt?: string | null; + github_assign_self_enabled?: boolean; + /** @deprecated No longer sent by the API. Replaced by `github_assign_self_enabled`. */ + github_reaction_enabled?: boolean; + /** @deprecated No longer sent by the API. */ + github_reaction_emoji?: string | null; merge_prompt: string | null; merge_and_push_prompt: string | null; pr_prompt: string | null; draft_pr_prompt: string | null; worktree_base_from_origin: boolean | null; has_remote: boolean; + non_git?: boolean; linked_repo_ids: string[]; created_at: string; server_id: string | null; } +export type WorkspaceStatus = "active" | "merged" | "archived"; + +export type InterfaceMode = "chat" | "claude_terminal"; + export interface WorkspaceData { id: string; repo_id: string; server_id: string | null; + url?: string; branch: string; branch_renamed: boolean; path: string; - preview_url: string | null; - status: string; + interface_mode?: InterfaceMode; + model?: string | null; + preview_url?: string | null; + status: WorkspaceStatus; pr_number: number | null; pr_url: string | null; pr_title: string | null; @@ -43,19 +56,30 @@ export interface WorkspaceData { issue_number: number | null; issue_title: string | null; issue_url: string | null; - base_branch: string; - base_commit: string; + base_branch: string | null; + base_commit: string | null; + label_id?: string | null; + is_repo_workspace?: boolean; + has_activity?: boolean; + linked_from_worktree_id?: string | null; linked_worktree_ids: string[]; created_at: string; - repository: { id: string; name: string; full_name: string; path: string } | null; - agent: { status: string } | null; - stats: DiffStatsData | null; + repository?: { id: string; name: string; full_name: string; path: string } | null; + agent?: { status: string } | null; + stats?: DiffStatsData | null; } +export type MessageRole = + | "user" + | "assistant" + | "tool_use" + | "tool_result" + | "thinking"; + export interface MessageData { id: number; session_id: string; - role: "user" | "assistant" | "system"; + role: MessageRole; content: string; metadata: string | null; created_at: string; @@ -93,7 +117,7 @@ export interface WorkspaceDiffData { stats: DiffStatsData; local: DiffSnapshotData; base: DiffSnapshotData; - commits_ahead: number; + commitsAhead: number; } export interface GenericResourceData { @@ -103,12 +127,46 @@ export interface GenericResourceData { [key: string]: unknown; } +export interface AvailableAgentData { + id: string; + name: string; + models: string[]; +} + +export interface ModelCapabilitiesData { + value: string; + resolvedModel?: string; + aliases?: string[]; + displayName: string; + description?: string; + supportsEffort?: boolean; + supportedEffortLevels?: string[]; + supportsFastMode?: boolean; +} + +export interface ServerModelsData { + server_id: string; + agents: AvailableAgentData[]; + models: string[]; + model_capabilities: ModelCapabilitiesData[]; +} + +export interface TeamInviteData { + email: string; + invited: boolean; +} + export interface CreateWorkspaceParams { repositoryId: string; + /** Ignored by the API when `issueUrl`, `pullRequestUrl` or `linearIssueUrl` is set. */ prompt?: string | null; serverId?: string | null; + /** Ignored by the API when `issueUrl`, `pullRequestUrl` or `linearIssueUrl` is set. */ + baseBranch?: string | null; + model?: string | null; issueUrl?: string | null; pullRequestUrl?: string | null; + linearIssueUrl?: string | null; } export interface SendMessageParams { @@ -116,16 +174,21 @@ export interface SendMessageParams { model?: string | null; } +export interface CommitParams { + model?: string | null; +} + export interface CreatePullRequestParams { title?: string | null; body?: string | null; draft?: boolean; + model?: string | null; } export interface ListWorkspacesParams { serverId?: string | null; repositoryId?: string | null; - status?: string | null; + status?: WorkspaceStatus | null; previewUrl?: string | null; } @@ -133,6 +196,10 @@ export interface ListRepositoriesParams { serverId?: string | null; } +export interface ListModelsParams { + serverId?: string | null; +} + export interface PolyscopeConfig { apiToken?: string; baseUrl?: string; diff --git a/test/client.test.ts b/test/client.test.ts index 8e18039..999bf14 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -5,41 +5,15 @@ vi.mock("../src/utils/settings.js", () => ({ })); import { Polyscope } from "../src/client.js"; -import { MissingApiTokenError } from "../src/errors.js"; +import { MissingApiTokenError, ValidationError } from "../src/errors.js"; +import { AvailableAgent, ServerModels } from "../src/resources/models.js"; +import { TeamInvite } from "../src/resources/team-invite.js"; import { resolveApiToken } from "../src/utils/settings.js"; -import type { ServerData, WorkspaceData } from "../src/types.js"; +import type { ServerData } from "../src/types.js"; +import { mockFetch, sentRequest, workspaceData } from "./fixtures.js"; const originalFetch = globalThis.fetch; -function minimalWorkspace(overrides: Partial = {}): WorkspaceData { - return { - id: "ws-1", - repo_id: "repo-1", - server_id: null, - branch: "main", - branch_renamed: false, - path: "/p", - preview_url: null, - status: "idle", - pr_number: null, - pr_url: null, - pr_title: null, - pr_body: null, - pr_is_draft: false, - issue_number: null, - issue_title: null, - issue_url: null, - base_branch: "main", - base_commit: "abc", - linked_worktree_ids: [], - created_at: "2020-01-01T00:00:00Z", - repository: null, - agent: null, - stats: null, - ...overrides, - }; -} - describe("Polyscope", () => { beforeEach(() => { vi.mocked(resolveApiToken).mockResolvedValue(null); @@ -97,11 +71,11 @@ describe("Polyscope", () => { it("findWorkspacesByPreviewUrl filters client-side when server ignores preview_url", async () => { const lookup = "https://app.test/"; const workspaces = [ - minimalWorkspace({ + workspaceData({ id: "a", preview_url: "https://app.test/?workspace=one", }), - minimalWorkspace({ + workspaceData({ id: "b", preview_url: "https://other.test/", }), @@ -118,6 +92,164 @@ describe("Polyscope", () => { expect(found.map((w) => w.id)).toEqual(["a"]); }); + it("sends model, base_branch and linear_issue_url when creating a workspace", async () => { + const fetch = mockFetch({ data: workspaceData({ id: "ws-9" }) }, 201); + + const client = new Polyscope({ apiToken: "tok", baseUrl: "https://api.test" }); + const ws = await client.createWorkspace({ + repositoryId: "repo-1", + serverId: "srv-1", + prompt: "Fix the login flow", + baseBranch: "develop", + model: "claude-opus", + }); + + expect(ws.id).toBe("ws-9"); + expect(sentRequest(fetch)).toEqual({ + url: "https://api.test/api/v1/workspaces", + method: "POST", + body: { + repository_id: "repo-1", + server_id: "srv-1", + prompt: "Fix the login flow", + base_branch: "develop", + model: "claude-opus", + }, + }); + }); + + it("sends linear_issue_url when creating a workspace from a Linear issue", async () => { + const fetch = mockFetch({ data: workspaceData() }, 201); + + const client = new Polyscope({ apiToken: "tok", baseUrl: "https://api.test" }); + await client.createWorkspace({ + repositoryId: "repo-1", + linearIssueUrl: "https://linear.app/acme/issue/ABC-1", + }); + + expect(sentRequest(fetch).body).toEqual({ + repository_id: "repo-1", + linear_issue_url: "https://linear.app/acme/issue/ABC-1", + }); + }); + + it("maps url from the workspace response", async () => { + mockFetch({ + data: workspaceData({ + server_id: "srv-1", + url: "https://getpolyscope.com/servers/srv-1/session?workspace=ws-1", + }), + }); + + const client = new Polyscope({ apiToken: "tok", baseUrl: "https://api.test" }); + const ws = await client.workspace("ws-1"); + + expect(ws.url).toBe( + "https://getpolyscope.com/servers/srv-1/session?workspace=ws-1", + ); + }); + + it("lists models per server", async () => { + const fetch = mockFetch({ + data: [ + { + server_id: "srv-1", + agents: [ + { + id: "claude", + name: "Claude", + models: ["claude-opus-5", "claude-sonnet-5"], + }, + { id: "codex", name: "Codex", models: ["gpt-5.3-codex"] }, + ], + models: ["claude-opus-5", "claude-sonnet-5", "gpt-5.3-codex"], + model_capabilities: [ + { + value: "claude-opus-5", + displayName: "Opus 5", + supportsFastMode: true, + supportedEffortLevels: ["max", "high"], + }, + ], + }, + ], + }); + + const client = new Polyscope({ apiToken: "tok", baseUrl: "https://api.test" }); + const result = await client.models(); + + expect(sentRequest(fetch).url).toBe("https://api.test/api/v1/models"); + expect(result).toHaveLength(1); + expect(result[0]).toBeInstanceOf(ServerModels); + expect(result[0].serverId).toBe("srv-1"); + expect(result[0].agents).toHaveLength(2); + expect(result[0].agents[0]).toBeInstanceOf(AvailableAgent); + expect(result[0].agents[0].id).toBe("claude"); + expect(result[0].agents[0].name).toBe("Claude"); + expect(result[0].agents[0].models).toEqual(["claude-opus-5", "claude-sonnet-5"]); + expect(result[0].models).toEqual(["claude-opus-5", "claude-sonnet-5", "gpt-5.3-codex"]); + expect(result[0].modelCapabilities[0].displayName).toBe("Opus 5"); + expect(result[0].modelCapabilities[0].supportsFastMode).toBe(true); + expect(result[0].toJSON().model_capabilities[0].value).toBe("claude-opus-5"); + }); + + it("passes server_id when listing models", async () => { + const fetch = mockFetch({ + data: [{ server_id: "srv-1", agents: [], models: [], model_capabilities: [] }], + }); + + const client = new Polyscope({ apiToken: "tok", baseUrl: "https://api.test" }); + const result = await client.models({ serverId: "srv-1" }); + + expect(sentRequest(fetch).url).toBe( + "https://api.test/api/v1/models?server_id=srv-1", + ); + expect(result[0].agents).toEqual([]); + expect(result[0].modelCapabilities).toEqual([]); + }); + + it("invites a team member", async () => { + const fetch = mockFetch( + { data: { email: "teammate@example.com", invited: true } }, + 201, + ); + + const client = new Polyscope({ apiToken: "tok", baseUrl: "https://api.test" }); + const invite = await client.inviteTeamMember("teammate@example.com"); + + expect(sentRequest(fetch)).toEqual({ + url: "https://api.test/api/v1/team/invites", + method: "POST", + body: { email: "teammate@example.com" }, + }); + expect(invite).toBeInstanceOf(TeamInvite); + expect(invite.email).toBe("teammate@example.com"); + expect(invite.invited).toBe(true); + }); + + it("throws ValidationError with the error code for a duplicate invite", async () => { + mockFetch( + { + error: { + code: "duplicate_invite", + message: "An invitation has already been sent to this email address.", + }, + }, + 422, + ); + + const client = new Polyscope({ apiToken: "tok", baseUrl: "https://api.test" }); + const error = await client + .inviteTeamMember("teammate@example.com") + .catch((e: unknown) => e); + + expect(error).toBeInstanceOf(ValidationError); + expect(error).toMatchObject({ + errorCode: "duplicate_invite", + message: "An invitation has already been sent to this email address.", + }); + }); + it("clears cached HttpClient when setApiToken is called", async () => { globalThis.fetch = vi.fn().mockImplementation(() => Promise.resolve( diff --git a/test/fixtures.ts b/test/fixtures.ts new file mode 100644 index 0000000..3a2e6f1 --- /dev/null +++ b/test/fixtures.ts @@ -0,0 +1,72 @@ +import { vi } from "vitest"; +import type { RepositoryData, WorkspaceData } from "../src/types.js"; + +export function workspaceData(overrides: Partial = {}): WorkspaceData { + return { + id: "ws-1", + repo_id: "repo-1", + server_id: null, + branch: "main", + branch_renamed: false, + path: "/p", + preview_url: null, + status: "active", + pr_number: null, + pr_url: null, + pr_title: null, + pr_body: null, + pr_is_draft: false, + issue_number: null, + issue_title: null, + issue_url: null, + base_branch: "main", + base_commit: "abc", + linked_worktree_ids: [], + created_at: "2020-01-01T00:00:00Z", + repository: null, + agent: null, + stats: null, + ...overrides, + }; +} + +export function repositoryData(overrides: Partial = {}): RepositoryData { + return { + id: "repo-1", + name: "app", + path: "/code/app", + base_branch: "main", + default_model: null, + review_model: null, + review_prompt: null, + github_assign_self_enabled: false, + merge_prompt: null, + merge_and_push_prompt: null, + pr_prompt: null, + draft_pr_prompt: null, + worktree_base_from_origin: null, + has_remote: true, + non_git: false, + linked_repo_ids: [], + created_at: "2026-02-26 10:00:00", + server_id: "srv-1", + ...overrides, + }; +} + +export function mockFetch(body: unknown, status = 200) { + const fetch = vi.fn().mockImplementation(() => + Promise.resolve(new Response(JSON.stringify(body), { status })), + ); + globalThis.fetch = fetch; + return fetch; +} + +export function sentRequest(fetch: ReturnType, call = 0) { + const [url, init] = fetch.mock.calls[call] as [string, RequestInit]; + return { + url, + method: init.method, + body: init.body === undefined ? undefined : JSON.parse(init.body as string), + }; +} diff --git a/test/repository.test.ts b/test/repository.test.ts new file mode 100644 index 0000000..4af6ae3 --- /dev/null +++ b/test/repository.test.ts @@ -0,0 +1,104 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { HttpClient } from "../src/http.js"; +import { Repository } from "../src/resources/repository.js"; +import { Workspace } from "../src/resources/workspace.js"; +import { + mockFetch, + repositoryData, + sentRequest, + workspaceData, +} from "./fixtures.js"; + +const originalFetch = globalThis.fetch; + +afterEach(() => { + globalThis.fetch = originalFetch; + vi.restoreAllMocks(); +}); + +function repository(overrides = {}) { + return new Repository( + repositoryData(overrides), + new HttpClient("tok", "https://api.test"), + ); +} + +describe("Repository", () => { + it("maps the current repository fields", () => { + const repo = repository({ + review_model: "claude-opus", + review_prompt: "Review carefully", + github_assign_self_enabled: true, + non_git: true, + }); + + expect(repo.reviewModel).toBe("claude-opus"); + expect(repo.reviewPrompt).toBe("Review carefully"); + expect(repo.githubAssignSelfEnabled).toBe(true); + expect(repo.nonGit).toBe(true); + expect(repo.toJSON()).toMatchObject({ + review_model: "claude-opus", + review_prompt: "Review carefully", + github_assign_self_enabled: true, + non_git: true, + }); + }); + + it("defaults the deprecated github_reaction fields the API no longer sends", () => { + const repo = repository(); + + expect(repo.githubReactionEnabled).toBe(false); + expect(repo.githubReactionEmoji).toBeNull(); + expect(repo.toJSON()).not.toHaveProperty("github_reaction_enabled"); + expect(repo.toJSON()).not.toHaveProperty("github_reaction_emoji"); + }); + + it("falls back to defaults when an older server leaves fields out", () => { + const data = repositoryData(); + delete data.review_model; + delete data.review_prompt; + delete data.github_assign_self_enabled; + delete data.non_git; + + const repo = new Repository(data, new HttpClient("tok", "https://api.test")); + + expect(repo.reviewModel).toBeNull(); + expect(repo.reviewPrompt).toBeNull(); + expect(repo.githubAssignSelfEnabled).toBe(false); + expect(repo.nonGit).toBe(false); + }); + + it("creates a workspace with model, base branch and linear issue url", async () => { + const fetch = mockFetch({ data: workspaceData({ id: "ws-9" }) }, 201); + + const ws = await repository().createWorkspace({ + model: "claude-sonnet", + baseBranch: "develop", + linearIssueUrl: "https://linear.app/acme/issue/ABC-1", + }); + + expect(ws).toBeInstanceOf(Workspace); + expect(ws.id).toBe("ws-9"); + expect(sentRequest(fetch)).toEqual({ + url: "https://api.test/api/v1/workspaces", + method: "POST", + body: { + repository_id: "repo-1", + model: "claude-sonnet", + base_branch: "develop", + linear_issue_url: "https://linear.app/acme/issue/ABC-1", + }, + }); + }); + + it("creates a workspace from a prompt string", async () => { + const fetch = mockFetch({ data: workspaceData() }, 201); + + await repository().createWorkspace("Add rate limiting"); + + expect(sentRequest(fetch).body).toEqual({ + repository_id: "repo-1", + prompt: "Add rate limiting", + }); + }); +}); diff --git a/test/workspace.test.ts b/test/workspace.test.ts new file mode 100644 index 0000000..2d35973 --- /dev/null +++ b/test/workspace.test.ts @@ -0,0 +1,178 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { HttpClient } from "../src/http.js"; +import { Workspace } from "../src/resources/workspace.js"; +import { mockFetch, sentRequest, workspaceData } from "./fixtures.js"; + +const originalFetch = globalThis.fetch; + +afterEach(() => { + globalThis.fetch = originalFetch; + vi.restoreAllMocks(); +}); + +function workspace(overrides = {}) { + return new Workspace( + workspaceData(overrides), + new HttpClient("tok", "https://api.test"), + ); +} + +describe("Workspace", () => { + it("maps url and the newer workspace fields", () => { + const ws = workspace({ + server_id: "srv-1", + url: "https://getpolyscope.com/servers/srv-1/session?workspace=ws-1", + interface_mode: "claude_terminal", + model: "claude-opus", + label_id: "label-1", + is_repo_workspace: true, + has_activity: true, + linked_from_worktree_id: "ws-0", + }); + + expect(ws.url).toBe( + "https://getpolyscope.com/servers/srv-1/session?workspace=ws-1", + ); + expect(ws.interfaceMode).toBe("claude_terminal"); + expect(ws.model).toBe("claude-opus"); + expect(ws.labelId).toBe("label-1"); + expect(ws.isRepoWorkspace).toBe(true); + expect(ws.hasActivity).toBe(true); + expect(ws.linkedFromWorktreeId).toBe("ws-0"); + expect(ws.toJSON()).toMatchObject({ + url: "https://getpolyscope.com/servers/srv-1/session?workspace=ws-1", + interface_mode: "claude_terminal", + model: "claude-opus", + label_id: "label-1", + is_repo_workspace: true, + has_activity: true, + linked_from_worktree_id: "ws-0", + }); + }); + + it("falls back to defaults when a response leaves fields out", () => { + const data = workspaceData(); + delete data.preview_url; + delete data.repository; + delete data.agent; + delete data.stats; + + const ws = new Workspace(data, new HttpClient("tok", "https://api.test")); + + expect(ws.url).toBeNull(); + expect(ws.previewUrl).toBeNull(); + expect(ws.repository).toBeNull(); + expect(ws.agent).toBeNull(); + expect(ws.stats).toBeNull(); + expect(ws.interfaceMode).toBe("chat"); + expect(ws.model).toBeNull(); + expect(ws.labelId).toBeNull(); + expect(ws.isRepoWorkspace).toBe(false); + expect(ws.hasActivity).toBe(false); + expect(ws.linkedFromWorktreeId).toBeNull(); + expect(JSON.parse(JSON.stringify(ws))).not.toHaveProperty("url"); + }); + + it("keeps null base_branch and base_commit", () => { + const ws = workspace({ base_branch: null, base_commit: null }); + + expect(ws.baseBranch).toBeNull(); + expect(ws.baseCommit).toBeNull(); + }); + + it("reads commitsAhead and camelCase stats from the diff", async () => { + const snapshot = { + diff: "diff --git a/a.ts b/a.ts", + files: [{ path: "a.ts", additions: 3, deletions: 1 }], + stats: { filesChanged: 1, additions: 3, deletions: 1 }, + }; + const fetch = mockFetch({ + data: { ...snapshot, local: snapshot, base: snapshot, commitsAhead: 2 }, + }); + + const diff = await workspace().diff(); + + expect(sentRequest(fetch).url).toBe( + "https://api.test/api/v1/workspaces/ws-1/diff", + ); + expect(diff.commitsAhead).toBe(2); + expect(diff.stats.filesChanged).toBe(1); + expect(diff.local.stats.filesChanged).toBe(1); + expect(diff.base.files[0].additions).toBe(3); + }); + + it("maps tool and thinking message roles", async () => { + const message = (id: number, role: string) => ({ + id, + session_id: "sess-1", + role, + content: "x", + metadata: null, + created_at: "2026-11-19 10:00:00", + }); + mockFetch({ + data: [ + message(1, "user"), + message(2, "thinking"), + message(3, "tool_use"), + message(4, "tool_result"), + message(5, "assistant"), + ], + meta: { cursor: 5, has_more: false }, + }); + + const result = await workspace().messages(); + + expect(result.messages.map((m) => m.role)).toEqual([ + "user", + "thinking", + "tool_use", + "tool_result", + "assistant", + ]); + expect(result.cursor).toBe(5); + }); + + it("sends model with commit", async () => { + const fetch = mockFetch({ + data: { workspace_id: "ws-1", agent: { status: "working" } }, + }); + + const result = await workspace().commit({ model: "claude-sonnet" }); + + expect(sentRequest(fetch)).toEqual({ + url: "https://api.test/api/v1/workspaces/ws-1/commit", + method: "POST", + body: { model: "claude-sonnet" }, + }); + expect(result.agent).toEqual({ status: "working" }); + }); + + it("sends no model with commit when none is given", async () => { + const fetch = mockFetch({ + data: { workspace_id: "ws-1", agent: { status: "working" } }, + }); + + await workspace().commit(); + + expect(sentRequest(fetch).body).toEqual({}); + }); + + it("sends model with pullRequest", async () => { + const fetch = mockFetch({ + data: { workspace_id: "ws-1", agent: { status: "working" } }, + }); + + await workspace().pullRequest({ + title: "Fix login", + draft: true, + model: "gpt-5.3-codex", + }); + + expect(sentRequest(fetch)).toEqual({ + url: "https://api.test/api/v1/workspaces/ws-1/pull-request", + method: "POST", + body: { title: "Fix login", draft: true, model: "gpt-5.3-codex" }, + }); + }); +});