@vercel/factory 0.0.20 → 0.0.21

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @vercel/factory
2
2
 
3
+ ## 0.0.21
4
+
5
+ ### Patch Changes
6
+
7
+ - e65f13d: Discover managed pull requests before publishing so branch reuse and ambiguous creation can be reconciled safely.
8
+
3
9
  ## 0.0.20
4
10
 
5
11
  ### Patch Changes
package/dist/client.mjs CHANGED
@@ -286,6 +286,7 @@ var FactoryClient = class {
286
286
  }
287
287
  return {
288
288
  ...current,
289
+ workGroups: previous.workGroups,
289
290
  history: previous.history,
290
291
  historyNextCursor: previous.historyNextCursor,
291
292
  notifications: previous.notifications,
@@ -1 +1 @@
1
- {"version":3,"file":"client.mjs","names":[],"sources":["../src/client.ts"],"sourcesContent":["import { sessionSummarySchema, type SessionSummary } from \"./api-contracts\";\nexport { sessionSummarySchema } from \"./api-contracts\";\nexport { sessionTaskSummarySchema } from \"./schema/session-summary\";\nexport type { SessionSummary } from \"./api-contracts\";\nexport type { SessionTaskSummary } from \"./schema/session-summary\";\nimport { inboxActivitySchema, type InboxActivity } from \"./inbox-activity\";\nimport {\n modelSettingsSchema,\n updateModelDefaultsSchema,\n type ModelSettings,\n type UpdateModelDefaults,\n} from \"./model-settings\";\nexport {\n agentModelConfigSchema,\n modelSettingsSchema,\n updateModelDefaultsSchema,\n} from \"./model-settings\";\nexport type { AgentModelConfig, ModelSettings, UpdateModelDefaults } from \"./model-settings\";\nexport { inboxActivitySchema, inboxActivityItemSchema } from \"./inbox-activity\";\nexport type { InboxActivity, InboxActivityItem } from \"./inbox-activity\";\nimport { sessionPreviewsSchema, type SessionPreviews } from \"./session-previews\";\nexport { sessionPreviewsSchema, sessionPreviewSchema } from \"./session-previews\";\nexport type { SessionPreviews, SessionPreview } from \"./session-previews\";\nimport { sessionReviewSchema, type SessionReview } from \"./session-review\";\nexport {\n sessionReviewSchema,\n sessionReviewCheckSchema,\n sessionReviewScreenshotSchema,\n sessionReviewIssueSchema,\n} from \"./session-review\";\nexport type {\n SessionReview,\n SessionReviewCheck,\n SessionReviewScreenshot,\n SessionReviewIssue,\n} from \"./session-review\";\nimport {\n workspaceFilesRequestSchema,\n workspaceFilesSchema,\n type WorkspaceFiles,\n type WorkspaceFilesRequest,\n} from \"./workspace-files\";\nexport {\n workspacePathSchema,\n workspaceFilesRequestSchema,\n workspaceFileEntrySchema,\n workspaceFileContentSchema,\n workspaceFilesSchema,\n} from \"./workspace-files\";\nexport type { WorkspaceFilesRequest, WorkspaceFileEntry, WorkspaceFiles } from \"./workspace-files\";\nimport { intakePageSchema, intakeViewSchema, retryIntakeSchema } from \"./intake-contracts\";\nexport { describeIntake } from \"./intake-contracts\";\nexport type { IntakeView } from \"./intake-contracts\";\nimport {\n approvalPageSchema,\n approvalRequestSchema,\n approvalViewSchema,\n type ApprovalListOptions,\n type ApprovalPage,\n type ApprovalView,\n} from \"./approval-contracts\";\nexport type { ApprovalListOptions, ApprovalPage, ApprovalView } from \"./approval-contracts\";\nimport { z } from \"zod\";\nimport {\n imageAttachmentSchema,\n type ImageAttachment,\n type ImageId,\n type ImageUploadInput,\n} from \"./image-input\";\nexport {\n MAX_IMAGE_BYTES,\n MAX_IMAGES,\n imageAttachmentSchema,\n imageAttachmentsSchema,\n imageIdSchema,\n} from \"./image-input\";\nexport type { ImageAttachment, ImageId, ImageUploadInput } from \"./image-input\";\nimport {\n answerSessionQuestionRequestSchema,\n apiAgentSchema,\n controlSessionRequestSchema,\n createSessionRequestSchema,\n repositoryDetailsSchema,\n sendSessionMessageRequestSchema,\n sessionPageSchema,\n sessionViewSchema,\n submitSessionInputRequestSchema,\n type AnswerSessionQuestionRequest,\n type ApiAgent,\n type ControlSessionRequest,\n type CreateSessionRequest,\n type RepositoryDetails,\n type SendSessionMessageRequest,\n type SessionPage,\n type SessionView,\n type SubmitSessionInputRequest,\n} from \"./api-contracts\";\nimport { changeSchema } from \"./schema/change\";\nimport type { MaybePromise } from \"./schema/common\";\nimport { taskIdSchema, type RepositoryId, type TaskId } from \"./schema/id\";\nimport { repositorySlugSchema, type RepositorySlug } from \"./schema/repository\";\nimport type { AgentSessionId } from \"./schema/session\";\nimport { workspaceDiffSchema, type WorkspaceDiff } from \"./workspace-diff\";\nimport { taskSchema, taskStateSchema, type Task } from \"./schema/task\";\nimport { taskGraphViewSchema, type TaskGraphView } from \"./task-graph-view\";\nimport {\n transcriptBlockSchema,\n transcriptPageSchema,\n type TranscriptBlock,\n type TranscriptPage,\n type TranscriptSnapshot,\n} from \"./schema/transcript\";\nexport type { TaskGraphView } from \"./task-graph-view\";\n\n/** All durable Task states in their schema-defined order. */\nexport const taskStates = Object.freeze([...taskStateSchema.options]);\n\n/** Filters and pagination accepted by the session-list API. */\nexport interface SessionListOptions {\n readonly scope?: \"all\" | \"interactive\";\n readonly detail?: \"full\" | \"summary\";\n readonly limit?: number;\n readonly cursor?: string;\n readonly query?: string;\n readonly repository?: RepositorySlug;\n readonly agent?: string;\n readonly source?: \"automatic\";\n readonly state?: Task[\"state\"] | \"conversation\";\n readonly attention?: boolean;\n readonly topLevel?: boolean;\n readonly includeTotal?: boolean;\n}\n\nexport type { WorkspaceDiff, WorkspaceDiffFile } from \"./workspace-diff\";\nexport { workspaceDiffFileSchema, workspaceDiffSchema } from \"./workspace-diff\";\nexport { agentSessionIdSchema, agentSessionSchema } from \"./schema/session\";\nexport type {\n AgentSession,\n AgentSessionId,\n DirectAgentSession,\n ExternalAgentSession,\n TaskAgentSession,\n} from \"./schema/session\";\n\nexport {\n answerSessionQuestionRequestSchema,\n pendingFollowUpSchema,\n apiAgentSchema,\n controlSessionRequestSchema,\n createSessionRequestSchema,\n repositoryDetailsSchema,\n repositorySummarySchema,\n sendSessionMessageRequestSchema,\n sessionInputResponseSchema,\n sessionPageSchema,\n sessionPullRequestSchema,\n sessionPullRequestStateSchema,\n sessionWorkGroupSchema,\n sessionWorkResultSchema,\n sessionWorkTaskSchema,\n sessionViewSchema,\n submitSessionInputRequestSchema,\n} from \"./api-contracts\";\nexport type {\n AnswerSessionQuestionRequest,\n PendingFollowUp,\n ApiAgent,\n ControlSessionRequest,\n CreateSessionRequest,\n RepositoryDetails,\n RepositorySummary,\n SendSessionMessageRequest,\n SessionInputResponse,\n SessionPage,\n SessionPullRequest,\n SessionWorkGroup,\n SessionWorkResult,\n SessionWorkTask,\n SessionView,\n SubmitSessionInputRequest,\n} from \"./api-contracts\";\nexport { readEvents, streamEventSchema, type StreamEvent } from \"./client-events\";\nexport {\n Transcript,\n type InputRequest,\n type TranscriptBlock,\n type ToolCall,\n type TranscriptSnapshot,\n type TranscriptHistoryPage,\n} from \"./client-transcript\";\nexport {\n inputRequestSchema,\n toolCallSchema,\n transcriptBlockSchema,\n transcriptSnapshotSchema,\n transcriptPageSchema,\n} from \"./schema/transcript\";\nexport type { TranscriptPage, TranscriptPageQuery } from \"./schema/transcript\";\nexport {\n followSessionStream,\n loadPreviousTranscriptPage,\n expandTranscriptBlock,\n type FollowSessionStreamOptions,\n type SessionStreamClient,\n} from \"./client-stream\";\n\n/** An unsuccessful Factory API response surfaced by the browser-safe client. */\nexport class ApiError extends Error {\n constructor(\n readonly status: number,\n message: string,\n readonly actor?: string,\n ) {\n super(message);\n }\n}\n\n/** Connection and request customization for {@link FactoryClient}. */\nexport interface FactoryClientOptions {\n /**\n * Canonical Factory origin. It must be HTTPS, except for HTTP loopback development, and cannot\n * contain credentials, a path, query parameters, or a fragment.\n */\n readonly url: string;\n /**\n * Headers resolved immediately before every request, allowing short-lived authentication to be\n * refreshed. Factory always sets `content-type` to `application/json` afterward.\n */\n readonly headers?: () => MaybePromise<HeadersInit>;\n /** Fetch implementation used for every request; defaults to `globalThis.fetch`. */\n readonly fetch?: typeof globalThis.fetch;\n}\n\n/** Identifies an uploaded image and optionally controls cancellation of its download. */\nexport interface GetImageOptions {\n readonly id: ImageId;\n readonly signal?: AbortSignal;\n}\n\n/** Identifies an operator session and the amount of detail to return. */\nexport interface GetSessionOptions {\n readonly id: AgentSessionId;\n readonly detail?: \"full\" | \"summary\";\n}\n\n/** Selects the observed execution whose review evidence should be read. */\nexport interface SessionReviewOptions {\n readonly sessionId: AgentSessionId;\n readonly executionId: string | null;\n readonly signal?: AbortSignal;\n}\n\n/** Selects the observed execution whose preview links and instructions should be read. */\nexport interface SessionPreviewsOptions {\n readonly sessionId: AgentSessionId;\n readonly executionId: string | null;\n readonly signal?: AbortSignal;\n}\n\n/** Identifies the operator session whose canonical task graph should be read. */\nexport interface GetSessionGraphOptions {\n readonly id: AgentSessionId;\n /** Selects a Task in the bound graph or work addressed to this conversation. */\n readonly taskId?: TaskId;\n readonly signal?: AbortSignal;\n}\n\n/** Identifies an exact task execution transcript within an operator session. */\nexport interface GraphTranscriptOptions {\n readonly sessionId: AgentSessionId;\n readonly taskId: TaskId;\n readonly executionId: string;\n readonly signal?: AbortSignal;\n}\n\n/** Identifies a file or directory at an observed execution and optional immutable revision. */\nexport interface WorkspaceFilesOptions extends WorkspaceFilesRequest {\n readonly sessionId: AgentSessionId;\n readonly executionId: string | null;\n readonly signal?: AbortSignal;\n}\n\n/** Identifies the execution whose committed workspace should be compared. */\nexport interface WorkspaceDiffOptions {\n readonly sessionId: AgentSessionId;\n readonly executionId: string | null;\n readonly signal?: AbortSignal;\n}\n\n/** Identifies a materialized transcript response used by the stream follower. */\nexport interface SessionTranscriptRequest {\n readonly sessionId: AgentSessionId;\n readonly executionId: string;\n readonly taskId?: TaskId;\n readonly history?: boolean;\n readonly limit?: number;\n readonly cursor?: string;\n readonly blockId?: string;\n readonly signal: AbortSignal;\n}\n\n/** Identifies a cursor-addressed event stream used by the stream follower. */\nexport interface SessionEventStreamRequest {\n readonly sessionId: AgentSessionId;\n readonly executionId: string;\n readonly cursor: number;\n readonly taskId?: TaskId;\n readonly signal: AbortSignal;\n}\n\n/**\n * Browser-safe typed client for the public Factory HTTP API.\n *\n * @remarks\n * Requests use same-origin credentials, bypass HTTP caches, and refuse redirects so authentication\n * redirects cannot be mistaken for API responses. When no caller signal is available, requests\n * time out after 30 seconds. Non-success responses throw {@link ApiError}; successful JSON bodies\n * are still validated against their public schemas before being returned.\n */\nexport class FactoryClient {\n private readonly origin: string;\n /**\n * Creates a client for one canonical Factory origin without performing a request.\n *\n * @param options - Factory origin plus optional per-request headers and fetch implementation.\n * @throws When `options.url` is not an HTTPS origin or an HTTP loopback origin.\n */\n constructor(private readonly options: FactoryClientOptions) {\n const url = new URL(options.url);\n if (\n url.username ||\n url.password ||\n url.pathname !== \"/\" ||\n url.search ||\n url.hash ||\n (url.protocol !== \"https:\" &&\n !(url.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname)))\n ) {\n throw new Error(\"Factory URL must be an HTTPS origin, or HTTP on loopback\");\n }\n this.origin = url.origin;\n }\n\n private async response(path: string, body?: unknown, signal?: AbortSignal): Promise<Response> {\n const url = new URL(`/api/v1/${path}`, this.origin);\n if (url.origin !== this.origin || !url.pathname.startsWith(\"/api/v1/\"))\n throw new Error(\"Invalid Factory API path\");\n const headers = new Headers(await this.options.headers?.());\n headers.set(\"content-type\", \"application/json\");\n const response = await (this.options.fetch ?? globalThis.fetch)(url.href, {\n method: body === undefined ? \"GET\" : \"POST\",\n headers,\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n credentials: \"same-origin\",\n cache: \"no-store\",\n redirect: \"manual\",\n signal: signal ?? AbortSignal.timeout(30_000),\n });\n if (response.type === \"opaqueredirect\" || [301, 302, 303, 307, 308].includes(response.status)) {\n await response.body?.cancel();\n throw new ApiError(\n response.status,\n `Factory at ${this.origin} returned a redirect. Reload to sign in, or set factory.url to the factory's canonical origin. Redirects are not followed.`,\n );\n }\n if (!response.ok) {\n const value: unknown = await response.json().catch(() => null);\n const detail =\n value !== null &&\n typeof value === \"object\" &&\n \"error\" in value &&\n typeof value.error === \"string\"\n ? value.error\n : `HTTP ${response.status}`;\n const actor =\n value !== null &&\n typeof value === \"object\" &&\n \"actor\" in value &&\n typeof value.actor === \"string\"\n ? value.actor\n : undefined;\n throw new ApiError(\n response.status,\n response.status === 401\n ? \"Authentication rejected. Reload to sign in, or run vercel login for the terminal client.\"\n : detail,\n actor,\n );\n }\n return response;\n }\n\n /** Read authorized intake and pre-task triage failures. */\n async intake(options: { repository?: string; cursor?: string; limit?: number } = {}) {\n const query = new URLSearchParams();\n for (const [key, value] of Object.entries(options))\n if (value !== undefined) query.set(key, String(value));\n return intakePageSchema.parse(await (await this.response(`intake?${query}`)).json());\n }\n\n /** Retry only the observed stopped attempt; concurrent or stale retries conflict. */\n async retryIntake(id: string, expectedAttempt: number) {\n return intakeViewSchema.parse(\n await (\n await this.response(\n `intake/${encodeURIComponent(id)}/retry`,\n retryIntakeSchema.parse({ expectedAttempt }),\n )\n ).json(),\n );\n }\n\n /** Lists approval proposals visible to the authenticated operator. */\n async listApprovals(options: ApprovalListOptions = {}): Promise<ApprovalPage> {\n const query = new URLSearchParams(\n Object.entries(options)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => [key, String(value)]),\n );\n return approvalPageSchema.parse(await (await this.response(`approvals?${query}`)).json());\n }\n /** Reads one approval proposal by Task ID. */\n async getApproval(id: TaskId): Promise<ApprovalView> {\n return approvalViewSchema.parse(\n await (await this.response(`tasks/${encodeURIComponent(id)}/approval`)).json(),\n );\n }\n /** Approves one proposal, optionally recording an operator reason. */\n async approveTask(id: TaskId, reason?: string): Promise<ApprovalView> {\n return approvalViewSchema.parse(\n await (\n await this.response(\n `tasks/${encodeURIComponent(id)}/approve`,\n approvalRequestSchema.parse({ reason }),\n )\n ).json(),\n );\n }\n\n /** Rejects one proposal with the required operator reason. */\n async rejectTask(id: TaskId, reason: string): Promise<ApprovalView> {\n return approvalViewSchema.parse(\n await (\n await this.response(\n `tasks/${encodeURIComponent(id)}/reject`,\n approvalRequestSchema.parse({ reason }),\n )\n ).json(),\n );\n }\n\n /** Uploads one bounded image for use in a later message. */\n async uploadImage(input: ImageUploadInput): Promise<ImageAttachment> {\n return imageAttachmentSchema.parse(await (await this.response(\"images\", input)).json());\n }\n /** Downloads a previously uploaded image. */\n async getImage(options: GetImageOptions): Promise<Blob> {\n return (\n await this.response(`images/${encodeURIComponent(options.id)}`, undefined, options.signal)\n ).blob();\n }\n\n /** Lists agents exposed for operator session creation. */\n async listAgents(): Promise<readonly ApiAgent[]> {\n return z\n .object({ agents: z.array(apiAgentSchema).readonly() })\n .parse(await (await this.response(\"agents\")).json()).agents;\n }\n /** Reports whether the configured origin is the isolated local fixture runtime. */\n async isLocalTestRuntime(): Promise<boolean> {\n const response = await this.response(\"agents\");\n const local = response.headers.get(\"x-factory-local-test\") === \"1\";\n await response.body?.cancel();\n return local;\n }\n /** Lists configured repository slugs. */\n async listRepositories(): Promise<readonly RepositorySlug[]> {\n return z\n .object({ repositories: z.array(repositorySlugSchema).readonly() })\n .parse(await (await this.response(\"repositories\")).json()).repositories;\n }\n /** Reads repository slugs together with their stable configured identifiers. */\n async getRepositoryDetails(): Promise<RepositoryDetails> {\n return repositoryDetailsSchema.parse(await (await this.response(\"repositories\")).json());\n }\n /** Reads one bounded page of open Changes, optionally scoped to a repository. */\n async getChangePage(\n options: { repository?: RepositorySlug; limit?: number; cursor?: string } = {},\n ) {\n const query = new URLSearchParams(\n Object.entries(options)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => [key, String(value)]),\n );\n return z\n .object({ changes: z.array(changeSchema).readonly(), nextCursor: z.string().nullable() })\n .parse(await (await this.response(`changes?${query}`)).json());\n }\n /** Reads one bounded page of canonical Tasks authorized for the caller. */\n async getTaskPage(options: { limit?: number; cursor?: string } = {}) {\n const query = new URLSearchParams(\n Object.entries(options)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => [key, String(value)]),\n );\n return z\n .object({ tasks: z.array(taskSchema).readonly(), nextCursor: z.string().nullable() })\n .parse(await (await this.response(`tasks?${query}`)).json());\n }\n /**\n * Lists sessions matching the requested operator scope without pagination metadata.\n *\n * @param options - Optional scope and detail projection; both use their server defaults when omitted.\n * @returns The first matching page's sessions. Use {@link getSessionPage} to follow cursors.\n */\n async listSessions(\n options: Pick<SessionListOptions, \"scope\" | \"detail\"> = {},\n ): Promise<readonly SessionSummary[]> {\n return (await this.getSessionPage(options)).sessions;\n }\n /**\n * Reads a filtered, cursor-paginated page of sessions.\n *\n * @param options - Filters, cursor, projection detail, and page limit sent to the API.\n * @returns The validated page, including its continuation cursor and optional total count.\n */\n async getSessionPage(options: SessionListOptions = {}): Promise<SessionPage> {\n const query = new URLSearchParams(\n Object.entries(options)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => [key, String(value)]),\n ).toString();\n return sessionPageSchema.parse(\n await (await this.response(`sessions${query ? `?${query}` : \"\"}`)).json(),\n );\n }\n /** Reads application-owned external work requiring operator attention. */\n async getInboxActivity(): Promise<InboxActivity> {\n return inboxActivitySchema.parse(await (await this.response(\"inbox-activity\")).json());\n }\n /** Reads application model choices and optional repository defaults. */\n async getModelSettings(repository?: RepositorySlug): Promise<ModelSettings> {\n const query = repository ? `?${new URLSearchParams({ repository })}` : \"\";\n return modelSettingsSchema.parse(await (await this.response(`models${query}`)).json());\n }\n /** Saves repository defaults only when their observed revision still matches. */\n async updateModelDefaults(input: UpdateModelDefaults): Promise<ModelSettings> {\n return modelSettingsSchema.parse(\n await (await this.response(\"models\", updateModelDefaultsSchema.parse(input))).json(),\n );\n }\n /** Counts sessions that currently require operator attention. */\n async getInboxCount(): Promise<number> {\n const result = z\n .object({ totalCount: z.number().int().nonnegative().optional() })\n .parse(\n await (\n await this.response(\n \"sessions?scope=all&detail=summary&attention=true&includeTotal=true&limit=1\",\n )\n ).json(),\n );\n if (result.totalCount === undefined)\n throw new Error(\"This factory's access policy does not provide an exact attention count\");\n return result.totalCount;\n }\n /** Reads a summary batch for the provided session IDs. */\n async getSessionBatch(ids: readonly AgentSessionId[]): Promise<readonly SessionSummary[]> {\n if (ids.length === 0) return [];\n const query = new URLSearchParams({ ids: ids.join(\",\"), detail: \"summary\" });\n return z\n .object({ sessions: z.array(sessionSummarySchema).readonly() })\n .parse(await (await this.response(`sessions?${query}`)).json()).sessions;\n }\n /** Reads one earlier page of authorized provider executions. */\n async getSessionHistory(\n id: AgentSessionId,\n options: { cursor?: string; signal?: AbortSignal } = {},\n ) {\n const query = new URLSearchParams({\n limit: \"20\",\n ...(options.cursor ? { cursor: options.cursor } : {}),\n });\n return z\n .object({\n items: sessionViewSchema.shape.history.unwrap(),\n nextCursor: z.string().nullable(),\n })\n .parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(id)}/history?${query}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /** Reads one earlier page of delivered conversation notifications. */\n async getSessionNotifications(\n id: AgentSessionId,\n options: { cursor?: string; signal?: AbortSignal } = {},\n ) {\n const query = new URLSearchParams({\n limit: \"30\",\n ...(options.cursor ? { cursor: options.cursor } : {}),\n });\n return z\n .object({ items: sessionViewSchema.shape.notifications, nextCursor: z.string().nullable() })\n .parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(id)}/notifications?${query}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /** Reads one bounded page of related Tasks authorized for this conversation. */\n async getSessionRelatedTasks(\n id: AgentSessionId,\n options: { cursor?: string; signal?: AbortSignal } = {},\n ) {\n const query = new URLSearchParams({\n limit: \"30\",\n ...(options.cursor ? { cursor: options.cursor } : {}),\n });\n return z\n .object({\n items: sessionViewSchema.shape.relatedTasks.unwrap(),\n nextCursor: z.string().nullable(),\n })\n .parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(id)}/related-tasks?${query}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /**\n * Reads one operator session.\n *\n * @param options - Stable session ID and optional summary or full projection.\n * @returns The current validated session view; it is a snapshot and does not follow live events.\n */\n async getSession(options: GetSessionOptions): Promise<SessionView> {\n return sessionViewSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(options.id)}${options.detail ? `?detail=${options.detail}` : \"\"}`,\n )\n ).json(),\n );\n }\n /** Reads the canonical task graph projected for one session. */\n async getSessionGraph(options: GetSessionGraphOptions): Promise<TaskGraphView> {\n return taskGraphViewSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(options.id)}/graph${options.taskId ? `?${new URLSearchParams({ taskId: options.taskId })}` : \"\"}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /** Reads the materialized transcript for one exact graph task execution. */\n async getGraphTranscript(options: GraphTranscriptOptions): Promise<TranscriptSnapshot> {\n const query = new URLSearchParams({\n taskId: options.taskId,\n executionId: options.executionId,\n });\n return transcriptPageSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(options.sessionId)}/graph-transcript?${query}`,\n undefined,\n options.signal,\n )\n ).json(),\n ).snapshot;\n }\n /** Refreshes a session summary and reloads its history when the active execution changes. */\n async refreshSession(previous: SessionView): Promise<SessionView> {\n const current = await this.getSession({ id: previous.session.id, detail: \"summary\" });\n if (\n current.task?.id !== previous.task?.id ||\n current.execution?.sessionId !== previous.execution?.sessionId ||\n current.execution?.provider !== previous.execution?.provider\n )\n return this.getSession({ id: previous.session.id });\n if (\n current.session.latestNotificationId !== previous.session.latestNotificationId ||\n current.task?.updatedAt !== previous.task?.updatedAt ||\n current.statusRevision !== previous.statusRevision\n ) {\n const fresh = await this.getSession({ id: previous.session.id });\n if (\n fresh.task?.id !== previous.task?.id ||\n fresh.execution?.sessionId !== previous.execution?.sessionId ||\n fresh.execution?.provider !== previous.execution?.provider\n )\n return fresh;\n return {\n ...fresh,\n history: [\n ...new Map(\n [...(previous.history ?? []), ...(fresh.history ?? [])].map((entry) => [\n JSON.stringify(entry.execution),\n entry,\n ]),\n ).values(),\n ],\n historyNextCursor:\n (previous.history?.length ?? 0) > (fresh.history?.length ?? 0)\n ? previous.historyNextCursor\n : fresh.historyNextCursor,\n notifications: [\n ...new Map(\n [...previous.notifications, ...fresh.notifications].map((entry) => [\n entry.eventId,\n entry,\n ]),\n ).values(),\n ],\n notificationsNextCursor:\n previous.notifications.length > fresh.notifications.length\n ? previous.notificationsNextCursor\n : fresh.notificationsNextCursor,\n relatedTasks: [\n ...new Map(\n [\n ...(fresh.relatedTasks ?? []),\n ...(previous.relatedTasks ?? []).filter(\n (entry) => !fresh.relatedTasks?.some((current) => current.id === entry.id),\n ),\n ].map((entry) => [entry.id, entry]),\n ).values(),\n ],\n relatedTasksNextCursor:\n (previous.relatedTasks?.length ?? 0) > (fresh.relatedTasks?.length ?? 0)\n ? previous.relatedTasksNextCursor\n : fresh.relatedTasksNextCursor,\n };\n }\n return {\n ...current,\n history: previous.history,\n historyNextCursor: previous.historyNextCursor,\n notifications: previous.notifications,\n notificationsNextCursor: previous.notificationsNextCursor,\n relatedTasks: previous.relatedTasks,\n relatedTasksNextCursor: previous.relatedTasksNextCursor,\n };\n }\n /** Reads application-owned previews without starting an agent, deployment, or server. */\n async getSessionPreviews(options: SessionPreviewsOptions): Promise<SessionPreviews> {\n return sessionPreviewsSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(options.sessionId)}/previews?${new URLSearchParams({ executionId: options.executionId ?? \"\" })}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /** Reads recorded checks, screenshots, and issues through the application's review reader. */\n async getSessionReview(options: SessionReviewOptions): Promise<SessionReview> {\n return sessionReviewSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(options.sessionId)}/review?${new URLSearchParams({ executionId: options.executionId ?? \"\" })}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /** Reads a directory or complete file through the factory's configured workspace adapter. */\n async getWorkspaceFiles(options: WorkspaceFilesOptions): Promise<WorkspaceFiles> {\n const query = workspaceFilesRequestSchema.parse({\n path: options.path,\n revision: options.revision,\n });\n const params = new URLSearchParams({\n executionId: options.executionId ?? \"\",\n path: query.path,\n });\n if (query.revision !== undefined) params.set(\"revision\", query.revision);\n return workspaceFilesSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(options.sessionId)}/files?${params}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /** Reads the committed workspace comparison for one observed execution. */\n async getWorkspaceDiff(options: WorkspaceDiffOptions): Promise<WorkspaceDiff> {\n return workspaceDiffSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(options.sessionId)}/diff?${new URLSearchParams({ executionId: options.executionId ?? \"\" })}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /**\n * Creates or recovers an idempotent conversational session.\n *\n * @remarks\n * Retain `input.operationId` unchanged across ambiguous failures. Reusing it with identical input\n * returns the original session; reusing it with different input is a conflict. The returned view\n * means admission and any initial dispatch attempt finished, not that the agent's work completed.\n *\n * @param input - Agent, initial content, optional repository/change, and client idempotency key.\n * @returns The admitted or recovered session snapshot.\n */\n async createSession(input: CreateSessionRequest): Promise<SessionView> {\n return sessionViewSchema.parse(\n await (await this.response(\"sessions\", createSessionRequestSchema.parse(input))).json(),\n );\n }\n\n /** Creates or recovers idempotent workflow work through a specialist signal. */\n async createSignal(input: CreateSessionRequest): Promise<SessionView> {\n return sessionViewSchema.parse(\n await (await this.response(\"signals\", createSessionRequestSchema.parse(input))).json(),\n );\n }\n\n /** Starts a deepsec security scan of a repository, or returns its already-active scan. */\n async runSecurityScan(repositoryId: RepositoryId): Promise<{ taskId: TaskId; reused: boolean }> {\n return z\n .strictObject({ taskId: taskIdSchema, reused: z.boolean() })\n .parse(await (await this.response(`repositories/${repositoryId}/security-scan`, {})).json());\n }\n\n /**\n * Sends a message to an existing session using optimistic execution matching.\n *\n * @remarks\n * `input.executionId` must be the execution the caller observed, or `null` when none was active.\n * A completed Task follow-up also requires an `operationId`, which must be retained for retries.\n * Resolving means the API accepted the message; provider or follow-up work may still be running.\n *\n * @param id - Stable Factory session receiving the message.\n * @param input - Message, observed execution, steering policy, attachments, and optional retry key.\n * @returns Nothing after the API accepts the request.\n */\n async sendSessionMessage(id: AgentSessionId, input: SendSessionMessageRequest): Promise<void> {\n const response = await this.response(\n `sessions/${encodeURIComponent(id)}/messages`,\n sendSessionMessageRequestSchema.parse(input),\n );\n await response.body?.cancel();\n }\n\n /**\n * Submits responses to pending provider input requests.\n *\n * @param id - Stable Factory session whose provider requested input.\n * @param input - Observed execution ID and one or more request-correlated responses.\n * @returns Nothing after the API accepts the responses; stale execution IDs are rejected.\n */\n async submitSessionInput(id: AgentSessionId, input: SubmitSessionInputRequest): Promise<void> {\n const response = await this.response(\n `sessions/${encodeURIComponent(id)}/input`,\n submitSessionInputRequestSchema.parse(input),\n );\n await response.body?.cancel();\n }\n\n /**\n * Attempts to dispatch queued workflow work associated with a session.\n *\n * @param id - Stable Factory session whose current work should be dispatched.\n * @returns The refreshed session after the bounded dispatch attempt, which may still be queued.\n */\n async dispatchSession(id: AgentSessionId): Promise<SessionView> {\n return sessionViewSchema.parse(\n await (await this.response(`sessions/${encodeURIComponent(id)}/dispatch`, {})).json(),\n );\n }\n\n /** Answers a workflow question associated with a session. */\n async answerSessionQuestion(\n id: AgentSessionId,\n input: AnswerSessionQuestionRequest,\n ): Promise<SessionView> {\n return sessionViewSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(id)}/answer`,\n answerSessionQuestionRequestSchema.parse(input),\n )\n ).json(),\n );\n }\n\n /** Cooperatively interrupts the currently observed turn. */\n async interruptSession(id: AgentSessionId, input: ControlSessionRequest = {}): Promise<void> {\n return this.controlSession(id, \"interrupt\", input);\n }\n\n /** Cancels active workflow and provider work in a session. */\n async cancelSession(id: AgentSessionId, input: ControlSessionRequest = {}): Promise<void> {\n return this.controlSession(id, \"cancel\", input);\n }\n\n /** Compacts the provider context for a session. */\n async compactSession(id: AgentSessionId, input: ControlSessionRequest = {}): Promise<void> {\n return this.controlSession(id, \"compact\", input);\n }\n\n /** Clears the provider context for a session. */\n async clearSession(id: AgentSessionId, input: ControlSessionRequest = {}): Promise<void> {\n return this.controlSession(id, \"clear\", input);\n }\n\n /** Resets a session after cancelling its active work. */\n async resetSession(id: AgentSessionId, input: ControlSessionRequest = {}): Promise<void> {\n return this.controlSession(id, \"reset\", input);\n }\n\n /** Reads a materialized transcript as a raw HTTP response for incremental following. */\n async getSessionTranscriptResponse(input: SessionTranscriptRequest): Promise<Response> {\n const query = new URLSearchParams({ executionId: input.executionId });\n if (input.history === true) query.set(\"history\", \"1\");\n if (input.taskId !== undefined) query.set(\"taskId\", input.taskId);\n if (input.limit !== undefined) query.set(\"limit\", String(input.limit));\n if (input.cursor !== undefined) query.set(\"cursor\", input.cursor);\n if (input.blockId !== undefined) query.set(\"blockId\", input.blockId);\n return this.response(\n `sessions/${encodeURIComponent(input.sessionId)}/${input.taskId ? \"graph-transcript\" : \"transcript\"}?${query}`,\n undefined,\n input.signal,\n );\n }\n\n /** Reads one bounded page of saved transcript history from Factory storage. */\n async getTranscriptPage(\n input: Omit<SessionTranscriptRequest, \"blockId\">,\n ): Promise<TranscriptPage> {\n return transcriptPageSchema.parse(\n await (await this.getSessionTranscriptResponse(input)).json(),\n );\n }\n\n /** Expands one large transcript block after authorizing its session and execution. */\n async getTranscriptBlock(\n input: Omit<SessionTranscriptRequest, \"limit\" | \"cursor\"> & { readonly blockId: string },\n ): Promise<TranscriptBlock> {\n return transcriptBlockSchema.parse(\n await (await this.getSessionTranscriptResponse(input)).json(),\n );\n }\n\n /** Opens a cursor-addressed session event stream as a raw HTTP response. */\n async getSessionEventStreamResponse(input: SessionEventStreamRequest): Promise<Response> {\n const query = new URLSearchParams({\n executionId: input.executionId,\n startIndex: String(input.cursor),\n });\n if (input.taskId !== undefined) query.set(\"taskId\", input.taskId);\n return this.response(\n `sessions/${encodeURIComponent(input.sessionId)}/${input.taskId ? \"graph-stream\" : \"stream\"}?${query}`,\n undefined,\n input.signal,\n );\n }\n\n private async controlSession(\n id: AgentSessionId,\n action: \"interrupt\" | \"cancel\" | \"compact\" | \"clear\" | \"reset\",\n input: ControlSessionRequest,\n ): Promise<void> {\n const response = await this.response(\n `sessions/${encodeURIComponent(id)}/${action}`,\n controlSessionRequestSchema.parse(input),\n );\n await response.body?.cancel();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmHA,MAAa,aAAa,OAAO,OAAO,CAAC,GAAG,gBAAgB,OAAO,CAAC;;AA4FpE,IAAa,WAAb,cAA8B,MAAM;CAEvB;CAEA;CAHX,YACE,QACA,SACA,OACA;EACA,MAAM,OAAO;EAJJ,KAAA,SAAA;EAEA,KAAA,QAAA;CAGX;AACF;;;;;;;;;;AAwGA,IAAa,gBAAb,MAA2B;CAQI;CAP7B;;;;;;;CAOA,YAAY,SAAgD;EAA/B,KAAA,UAAA;EAC3B,MAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;EAC/B,IACE,IAAI,YACJ,IAAI,YACJ,IAAI,aAAa,OACjB,IAAI,UACJ,IAAI,QACH,IAAI,aAAa,YAChB,EAAE,IAAI,aAAa,WAAW;GAAC;GAAa;GAAa;EAAO,CAAC,CAAC,SAAS,IAAI,QAAQ,IAEzF,MAAM,IAAI,MAAM,0DAA0D;EAE5E,KAAK,SAAS,IAAI;CACpB;CAEA,MAAc,SAAS,MAAc,MAAgB,QAAyC;EAC5F,MAAM,MAAM,IAAI,IAAI,WAAW,QAAQ,KAAK,MAAM;EAClD,IAAI,IAAI,WAAW,KAAK,UAAU,CAAC,IAAI,SAAS,WAAW,UAAU,GACnE,MAAM,IAAI,MAAM,0BAA0B;EAC5C,MAAM,UAAU,IAAI,QAAQ,MAAM,KAAK,QAAQ,UAAU,CAAC;EAC1D,QAAQ,IAAI,gBAAgB,kBAAkB;EAC9C,MAAM,WAAW,OAAO,KAAK,QAAQ,SAAS,WAAW,MAAA,CAAO,IAAI,MAAM;GACxE,QAAQ,SAAS,KAAA,IAAY,QAAQ;GACrC;GACA,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,KAAK,UAAU,IAAI,EAAE;GAC3D,aAAa;GACb,OAA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,EAAA,CAAG,KAAK,CAC9D;CACF;;CAGA,MAAM,8BAA8B,OAAqD;EACvF,MAAM,QAAQ,IAAI,gBAAgB;GAChC,aAAa,MAAM;GACnB,YAAY,OAAO,MAAM,MAAM;EACjC,CAAC;EACD,IAAI,MAAM,WAAW,KAAA,GAAW,MAAM,IAAI,UAAU,MAAM,MAAM;EAChE,OAAO,KAAK,SACV,YAAY,mBAAmB,MAAM,SAAS,EAAE,GAAG,MAAM,SAAS,iBAAiB,SAAS,GAAG,SAC/F,KAAA,GACA,MAAM,MACR;CACF;CAEA,MAAc,eACZ,IACA,QACA,OACe;EAKf,OAAM,MAJiB,KAAK,SAC1B,YAAY,mBAAmB,EAAE,EAAE,GAAG,UACtC,4BAA4B,MAAM,KAAK,CACzC,EAAA,CACe,MAAM,OAAO;CAC9B;AACF"}
1
+ {"version":3,"file":"client.mjs","names":[],"sources":["../src/client.ts"],"sourcesContent":["import { sessionSummarySchema, type SessionSummary } from \"./api-contracts\";\nexport { sessionSummarySchema } from \"./api-contracts\";\nexport { sessionTaskSummarySchema } from \"./schema/session-summary\";\nexport type { SessionSummary } from \"./api-contracts\";\nexport type { SessionTaskSummary } from \"./schema/session-summary\";\nimport { inboxActivitySchema, type InboxActivity } from \"./inbox-activity\";\nimport {\n modelSettingsSchema,\n updateModelDefaultsSchema,\n type ModelSettings,\n type UpdateModelDefaults,\n} from \"./model-settings\";\nexport {\n agentModelConfigSchema,\n modelSettingsSchema,\n updateModelDefaultsSchema,\n} from \"./model-settings\";\nexport type { AgentModelConfig, ModelSettings, UpdateModelDefaults } from \"./model-settings\";\nexport { inboxActivitySchema, inboxActivityItemSchema } from \"./inbox-activity\";\nexport type { InboxActivity, InboxActivityItem } from \"./inbox-activity\";\nimport { sessionPreviewsSchema, type SessionPreviews } from \"./session-previews\";\nexport { sessionPreviewsSchema, sessionPreviewSchema } from \"./session-previews\";\nexport type { SessionPreviews, SessionPreview } from \"./session-previews\";\nimport { sessionReviewSchema, type SessionReview } from \"./session-review\";\nexport {\n sessionReviewSchema,\n sessionReviewCheckSchema,\n sessionReviewScreenshotSchema,\n sessionReviewIssueSchema,\n} from \"./session-review\";\nexport type {\n SessionReview,\n SessionReviewCheck,\n SessionReviewScreenshot,\n SessionReviewIssue,\n} from \"./session-review\";\nimport {\n workspaceFilesRequestSchema,\n workspaceFilesSchema,\n type WorkspaceFiles,\n type WorkspaceFilesRequest,\n} from \"./workspace-files\";\nexport {\n workspacePathSchema,\n workspaceFilesRequestSchema,\n workspaceFileEntrySchema,\n workspaceFileContentSchema,\n workspaceFilesSchema,\n} from \"./workspace-files\";\nexport type { WorkspaceFilesRequest, WorkspaceFileEntry, WorkspaceFiles } from \"./workspace-files\";\nimport { intakePageSchema, intakeViewSchema, retryIntakeSchema } from \"./intake-contracts\";\nexport { describeIntake } from \"./intake-contracts\";\nexport type { IntakeView } from \"./intake-contracts\";\nimport {\n approvalPageSchema,\n approvalRequestSchema,\n approvalViewSchema,\n type ApprovalListOptions,\n type ApprovalPage,\n type ApprovalView,\n} from \"./approval-contracts\";\nexport type { ApprovalListOptions, ApprovalPage, ApprovalView } from \"./approval-contracts\";\nimport { z } from \"zod\";\nimport {\n imageAttachmentSchema,\n type ImageAttachment,\n type ImageId,\n type ImageUploadInput,\n} from \"./image-input\";\nexport {\n MAX_IMAGE_BYTES,\n MAX_IMAGES,\n imageAttachmentSchema,\n imageAttachmentsSchema,\n imageIdSchema,\n} from \"./image-input\";\nexport type { ImageAttachment, ImageId, ImageUploadInput } from \"./image-input\";\nimport {\n answerSessionQuestionRequestSchema,\n apiAgentSchema,\n controlSessionRequestSchema,\n createSessionRequestSchema,\n repositoryDetailsSchema,\n sendSessionMessageRequestSchema,\n sessionPageSchema,\n sessionViewSchema,\n submitSessionInputRequestSchema,\n type AnswerSessionQuestionRequest,\n type ApiAgent,\n type ControlSessionRequest,\n type CreateSessionRequest,\n type RepositoryDetails,\n type SendSessionMessageRequest,\n type SessionPage,\n type SessionView,\n type SubmitSessionInputRequest,\n} from \"./api-contracts\";\nimport { changeSchema } from \"./schema/change\";\nimport type { MaybePromise } from \"./schema/common\";\nimport { taskIdSchema, type RepositoryId, type TaskId } from \"./schema/id\";\nimport { repositorySlugSchema, type RepositorySlug } from \"./schema/repository\";\nimport type { AgentSessionId } from \"./schema/session\";\nimport { workspaceDiffSchema, type WorkspaceDiff } from \"./workspace-diff\";\nimport { taskSchema, taskStateSchema, type Task } from \"./schema/task\";\nimport { taskGraphViewSchema, type TaskGraphView } from \"./task-graph-view\";\nimport {\n transcriptBlockSchema,\n transcriptPageSchema,\n type TranscriptBlock,\n type TranscriptPage,\n type TranscriptSnapshot,\n} from \"./schema/transcript\";\nexport type { TaskGraphView } from \"./task-graph-view\";\n\n/** All durable Task states in their schema-defined order. */\nexport const taskStates = Object.freeze([...taskStateSchema.options]);\n\n/** Filters and pagination accepted by the session-list API. */\nexport interface SessionListOptions {\n readonly scope?: \"all\" | \"interactive\";\n readonly detail?: \"full\" | \"summary\";\n readonly limit?: number;\n readonly cursor?: string;\n readonly query?: string;\n readonly repository?: RepositorySlug;\n readonly agent?: string;\n readonly source?: \"automatic\";\n readonly state?: Task[\"state\"] | \"conversation\";\n readonly attention?: boolean;\n readonly topLevel?: boolean;\n readonly includeTotal?: boolean;\n}\n\nexport type { WorkspaceDiff, WorkspaceDiffFile } from \"./workspace-diff\";\nexport { workspaceDiffFileSchema, workspaceDiffSchema } from \"./workspace-diff\";\nexport { agentSessionIdSchema, agentSessionSchema } from \"./schema/session\";\nexport type {\n AgentSession,\n AgentSessionId,\n DirectAgentSession,\n ExternalAgentSession,\n TaskAgentSession,\n} from \"./schema/session\";\n\nexport {\n answerSessionQuestionRequestSchema,\n pendingFollowUpSchema,\n apiAgentSchema,\n controlSessionRequestSchema,\n createSessionRequestSchema,\n repositoryDetailsSchema,\n repositorySummarySchema,\n sendSessionMessageRequestSchema,\n sessionInputResponseSchema,\n sessionPageSchema,\n sessionPullRequestSchema,\n sessionPullRequestStateSchema,\n sessionWorkGroupSchema,\n sessionWorkResultSchema,\n sessionWorkTaskSchema,\n sessionViewSchema,\n submitSessionInputRequestSchema,\n} from \"./api-contracts\";\nexport type {\n AnswerSessionQuestionRequest,\n PendingFollowUp,\n ApiAgent,\n ControlSessionRequest,\n CreateSessionRequest,\n RepositoryDetails,\n RepositorySummary,\n SendSessionMessageRequest,\n SessionInputResponse,\n SessionPage,\n SessionPullRequest,\n SessionWorkGroup,\n SessionWorkResult,\n SessionWorkTask,\n SessionView,\n SubmitSessionInputRequest,\n} from \"./api-contracts\";\nexport { readEvents, streamEventSchema, type StreamEvent } from \"./client-events\";\nexport {\n Transcript,\n type InputRequest,\n type TranscriptBlock,\n type ToolCall,\n type TranscriptSnapshot,\n type TranscriptHistoryPage,\n} from \"./client-transcript\";\nexport {\n inputRequestSchema,\n toolCallSchema,\n transcriptBlockSchema,\n transcriptSnapshotSchema,\n transcriptPageSchema,\n} from \"./schema/transcript\";\nexport type { TranscriptPage, TranscriptPageQuery } from \"./schema/transcript\";\nexport {\n followSessionStream,\n loadPreviousTranscriptPage,\n expandTranscriptBlock,\n type FollowSessionStreamOptions,\n type SessionStreamClient,\n} from \"./client-stream\";\n\n/** An unsuccessful Factory API response surfaced by the browser-safe client. */\nexport class ApiError extends Error {\n constructor(\n readonly status: number,\n message: string,\n readonly actor?: string,\n ) {\n super(message);\n }\n}\n\n/** Connection and request customization for {@link FactoryClient}. */\nexport interface FactoryClientOptions {\n /**\n * Canonical Factory origin. It must be HTTPS, except for HTTP loopback development, and cannot\n * contain credentials, a path, query parameters, or a fragment.\n */\n readonly url: string;\n /**\n * Headers resolved immediately before every request, allowing short-lived authentication to be\n * refreshed. Factory always sets `content-type` to `application/json` afterward.\n */\n readonly headers?: () => MaybePromise<HeadersInit>;\n /** Fetch implementation used for every request; defaults to `globalThis.fetch`. */\n readonly fetch?: typeof globalThis.fetch;\n}\n\n/** Identifies an uploaded image and optionally controls cancellation of its download. */\nexport interface GetImageOptions {\n readonly id: ImageId;\n readonly signal?: AbortSignal;\n}\n\n/** Identifies an operator session and the amount of detail to return. */\nexport interface GetSessionOptions {\n readonly id: AgentSessionId;\n readonly detail?: \"full\" | \"summary\";\n}\n\n/** Selects the observed execution whose review evidence should be read. */\nexport interface SessionReviewOptions {\n readonly sessionId: AgentSessionId;\n readonly executionId: string | null;\n readonly signal?: AbortSignal;\n}\n\n/** Selects the observed execution whose preview links and instructions should be read. */\nexport interface SessionPreviewsOptions {\n readonly sessionId: AgentSessionId;\n readonly executionId: string | null;\n readonly signal?: AbortSignal;\n}\n\n/** Identifies the operator session whose canonical task graph should be read. */\nexport interface GetSessionGraphOptions {\n readonly id: AgentSessionId;\n /** Selects a Task in the bound graph or work addressed to this conversation. */\n readonly taskId?: TaskId;\n readonly signal?: AbortSignal;\n}\n\n/** Identifies an exact task execution transcript within an operator session. */\nexport interface GraphTranscriptOptions {\n readonly sessionId: AgentSessionId;\n readonly taskId: TaskId;\n readonly executionId: string;\n readonly signal?: AbortSignal;\n}\n\n/** Identifies a file or directory at an observed execution and optional immutable revision. */\nexport interface WorkspaceFilesOptions extends WorkspaceFilesRequest {\n readonly sessionId: AgentSessionId;\n readonly executionId: string | null;\n readonly signal?: AbortSignal;\n}\n\n/** Identifies the execution whose committed workspace should be compared. */\nexport interface WorkspaceDiffOptions {\n readonly sessionId: AgentSessionId;\n readonly executionId: string | null;\n readonly signal?: AbortSignal;\n}\n\n/** Identifies a materialized transcript response used by the stream follower. */\nexport interface SessionTranscriptRequest {\n readonly sessionId: AgentSessionId;\n readonly executionId: string;\n readonly taskId?: TaskId;\n readonly history?: boolean;\n readonly limit?: number;\n readonly cursor?: string;\n readonly blockId?: string;\n readonly signal: AbortSignal;\n}\n\n/** Identifies a cursor-addressed event stream used by the stream follower. */\nexport interface SessionEventStreamRequest {\n readonly sessionId: AgentSessionId;\n readonly executionId: string;\n readonly cursor: number;\n readonly taskId?: TaskId;\n readonly signal: AbortSignal;\n}\n\n/**\n * Browser-safe typed client for the public Factory HTTP API.\n *\n * @remarks\n * Requests use same-origin credentials, bypass HTTP caches, and refuse redirects so authentication\n * redirects cannot be mistaken for API responses. When no caller signal is available, requests\n * time out after 30 seconds. Non-success responses throw {@link ApiError}; successful JSON bodies\n * are still validated against their public schemas before being returned.\n */\nexport class FactoryClient {\n private readonly origin: string;\n /**\n * Creates a client for one canonical Factory origin without performing a request.\n *\n * @param options - Factory origin plus optional per-request headers and fetch implementation.\n * @throws When `options.url` is not an HTTPS origin or an HTTP loopback origin.\n */\n constructor(private readonly options: FactoryClientOptions) {\n const url = new URL(options.url);\n if (\n url.username ||\n url.password ||\n url.pathname !== \"/\" ||\n url.search ||\n url.hash ||\n (url.protocol !== \"https:\" &&\n !(url.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname)))\n ) {\n throw new Error(\"Factory URL must be an HTTPS origin, or HTTP on loopback\");\n }\n this.origin = url.origin;\n }\n\n private async response(path: string, body?: unknown, signal?: AbortSignal): Promise<Response> {\n const url = new URL(`/api/v1/${path}`, this.origin);\n if (url.origin !== this.origin || !url.pathname.startsWith(\"/api/v1/\"))\n throw new Error(\"Invalid Factory API path\");\n const headers = new Headers(await this.options.headers?.());\n headers.set(\"content-type\", \"application/json\");\n const response = await (this.options.fetch ?? globalThis.fetch)(url.href, {\n method: body === undefined ? \"GET\" : \"POST\",\n headers,\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n credentials: \"same-origin\",\n cache: \"no-store\",\n redirect: \"manual\",\n signal: signal ?? AbortSignal.timeout(30_000),\n });\n if (response.type === \"opaqueredirect\" || [301, 302, 303, 307, 308].includes(response.status)) {\n await response.body?.cancel();\n throw new ApiError(\n response.status,\n `Factory at ${this.origin} returned a redirect. Reload to sign in, or set factory.url to the factory's canonical origin. Redirects are not followed.`,\n );\n }\n if (!response.ok) {\n const value: unknown = await response.json().catch(() => null);\n const detail =\n value !== null &&\n typeof value === \"object\" &&\n \"error\" in value &&\n typeof value.error === \"string\"\n ? value.error\n : `HTTP ${response.status}`;\n const actor =\n value !== null &&\n typeof value === \"object\" &&\n \"actor\" in value &&\n typeof value.actor === \"string\"\n ? value.actor\n : undefined;\n throw new ApiError(\n response.status,\n response.status === 401\n ? \"Authentication rejected. Reload to sign in, or run vercel login for the terminal client.\"\n : detail,\n actor,\n );\n }\n return response;\n }\n\n /** Read authorized intake and pre-task triage failures. */\n async intake(options: { repository?: string; cursor?: string; limit?: number } = {}) {\n const query = new URLSearchParams();\n for (const [key, value] of Object.entries(options))\n if (value !== undefined) query.set(key, String(value));\n return intakePageSchema.parse(await (await this.response(`intake?${query}`)).json());\n }\n\n /** Retry only the observed stopped attempt; concurrent or stale retries conflict. */\n async retryIntake(id: string, expectedAttempt: number) {\n return intakeViewSchema.parse(\n await (\n await this.response(\n `intake/${encodeURIComponent(id)}/retry`,\n retryIntakeSchema.parse({ expectedAttempt }),\n )\n ).json(),\n );\n }\n\n /** Lists approval proposals visible to the authenticated operator. */\n async listApprovals(options: ApprovalListOptions = {}): Promise<ApprovalPage> {\n const query = new URLSearchParams(\n Object.entries(options)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => [key, String(value)]),\n );\n return approvalPageSchema.parse(await (await this.response(`approvals?${query}`)).json());\n }\n /** Reads one approval proposal by Task ID. */\n async getApproval(id: TaskId): Promise<ApprovalView> {\n return approvalViewSchema.parse(\n await (await this.response(`tasks/${encodeURIComponent(id)}/approval`)).json(),\n );\n }\n /** Approves one proposal, optionally recording an operator reason. */\n async approveTask(id: TaskId, reason?: string): Promise<ApprovalView> {\n return approvalViewSchema.parse(\n await (\n await this.response(\n `tasks/${encodeURIComponent(id)}/approve`,\n approvalRequestSchema.parse({ reason }),\n )\n ).json(),\n );\n }\n\n /** Rejects one proposal with the required operator reason. */\n async rejectTask(id: TaskId, reason: string): Promise<ApprovalView> {\n return approvalViewSchema.parse(\n await (\n await this.response(\n `tasks/${encodeURIComponent(id)}/reject`,\n approvalRequestSchema.parse({ reason }),\n )\n ).json(),\n );\n }\n\n /** Uploads one bounded image for use in a later message. */\n async uploadImage(input: ImageUploadInput): Promise<ImageAttachment> {\n return imageAttachmentSchema.parse(await (await this.response(\"images\", input)).json());\n }\n /** Downloads a previously uploaded image. */\n async getImage(options: GetImageOptions): Promise<Blob> {\n return (\n await this.response(`images/${encodeURIComponent(options.id)}`, undefined, options.signal)\n ).blob();\n }\n\n /** Lists agents exposed for operator session creation. */\n async listAgents(): Promise<readonly ApiAgent[]> {\n return z\n .object({ agents: z.array(apiAgentSchema).readonly() })\n .parse(await (await this.response(\"agents\")).json()).agents;\n }\n /** Reports whether the configured origin is the isolated local fixture runtime. */\n async isLocalTestRuntime(): Promise<boolean> {\n const response = await this.response(\"agents\");\n const local = response.headers.get(\"x-factory-local-test\") === \"1\";\n await response.body?.cancel();\n return local;\n }\n /** Lists configured repository slugs. */\n async listRepositories(): Promise<readonly RepositorySlug[]> {\n return z\n .object({ repositories: z.array(repositorySlugSchema).readonly() })\n .parse(await (await this.response(\"repositories\")).json()).repositories;\n }\n /** Reads repository slugs together with their stable configured identifiers. */\n async getRepositoryDetails(): Promise<RepositoryDetails> {\n return repositoryDetailsSchema.parse(await (await this.response(\"repositories\")).json());\n }\n /** Reads one bounded page of open Changes, optionally scoped to a repository. */\n async getChangePage(\n options: { repository?: RepositorySlug; limit?: number; cursor?: string } = {},\n ) {\n const query = new URLSearchParams(\n Object.entries(options)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => [key, String(value)]),\n );\n return z\n .object({ changes: z.array(changeSchema).readonly(), nextCursor: z.string().nullable() })\n .parse(await (await this.response(`changes?${query}`)).json());\n }\n /** Reads one bounded page of canonical Tasks authorized for the caller. */\n async getTaskPage(options: { limit?: number; cursor?: string } = {}) {\n const query = new URLSearchParams(\n Object.entries(options)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => [key, String(value)]),\n );\n return z\n .object({ tasks: z.array(taskSchema).readonly(), nextCursor: z.string().nullable() })\n .parse(await (await this.response(`tasks?${query}`)).json());\n }\n /**\n * Lists sessions matching the requested operator scope without pagination metadata.\n *\n * @param options - Optional scope and detail projection; both use their server defaults when omitted.\n * @returns The first matching page's sessions. Use {@link getSessionPage} to follow cursors.\n */\n async listSessions(\n options: Pick<SessionListOptions, \"scope\" | \"detail\"> = {},\n ): Promise<readonly SessionSummary[]> {\n return (await this.getSessionPage(options)).sessions;\n }\n /**\n * Reads a filtered, cursor-paginated page of sessions.\n *\n * @param options - Filters, cursor, projection detail, and page limit sent to the API.\n * @returns The validated page, including its continuation cursor and optional total count.\n */\n async getSessionPage(options: SessionListOptions = {}): Promise<SessionPage> {\n const query = new URLSearchParams(\n Object.entries(options)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => [key, String(value)]),\n ).toString();\n return sessionPageSchema.parse(\n await (await this.response(`sessions${query ? `?${query}` : \"\"}`)).json(),\n );\n }\n /** Reads application-owned external work requiring operator attention. */\n async getInboxActivity(): Promise<InboxActivity> {\n return inboxActivitySchema.parse(await (await this.response(\"inbox-activity\")).json());\n }\n /** Reads application model choices and optional repository defaults. */\n async getModelSettings(repository?: RepositorySlug): Promise<ModelSettings> {\n const query = repository ? `?${new URLSearchParams({ repository })}` : \"\";\n return modelSettingsSchema.parse(await (await this.response(`models${query}`)).json());\n }\n /** Saves repository defaults only when their observed revision still matches. */\n async updateModelDefaults(input: UpdateModelDefaults): Promise<ModelSettings> {\n return modelSettingsSchema.parse(\n await (await this.response(\"models\", updateModelDefaultsSchema.parse(input))).json(),\n );\n }\n /** Counts sessions that currently require operator attention. */\n async getInboxCount(): Promise<number> {\n const result = z\n .object({ totalCount: z.number().int().nonnegative().optional() })\n .parse(\n await (\n await this.response(\n \"sessions?scope=all&detail=summary&attention=true&includeTotal=true&limit=1\",\n )\n ).json(),\n );\n if (result.totalCount === undefined)\n throw new Error(\"This factory's access policy does not provide an exact attention count\");\n return result.totalCount;\n }\n /** Reads a summary batch for the provided session IDs. */\n async getSessionBatch(ids: readonly AgentSessionId[]): Promise<readonly SessionSummary[]> {\n if (ids.length === 0) return [];\n const query = new URLSearchParams({ ids: ids.join(\",\"), detail: \"summary\" });\n return z\n .object({ sessions: z.array(sessionSummarySchema).readonly() })\n .parse(await (await this.response(`sessions?${query}`)).json()).sessions;\n }\n /** Reads one earlier page of authorized provider executions. */\n async getSessionHistory(\n id: AgentSessionId,\n options: { cursor?: string; signal?: AbortSignal } = {},\n ) {\n const query = new URLSearchParams({\n limit: \"20\",\n ...(options.cursor ? { cursor: options.cursor } : {}),\n });\n return z\n .object({\n items: sessionViewSchema.shape.history.unwrap(),\n nextCursor: z.string().nullable(),\n })\n .parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(id)}/history?${query}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /** Reads one earlier page of delivered conversation notifications. */\n async getSessionNotifications(\n id: AgentSessionId,\n options: { cursor?: string; signal?: AbortSignal } = {},\n ) {\n const query = new URLSearchParams({\n limit: \"30\",\n ...(options.cursor ? { cursor: options.cursor } : {}),\n });\n return z\n .object({ items: sessionViewSchema.shape.notifications, nextCursor: z.string().nullable() })\n .parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(id)}/notifications?${query}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /** Reads one bounded page of related Tasks authorized for this conversation. */\n async getSessionRelatedTasks(\n id: AgentSessionId,\n options: { cursor?: string; signal?: AbortSignal } = {},\n ) {\n const query = new URLSearchParams({\n limit: \"30\",\n ...(options.cursor ? { cursor: options.cursor } : {}),\n });\n return z\n .object({\n items: sessionViewSchema.shape.relatedTasks.unwrap(),\n nextCursor: z.string().nullable(),\n })\n .parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(id)}/related-tasks?${query}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /**\n * Reads one operator session.\n *\n * @param options - Stable session ID and optional summary or full projection.\n * @returns The current validated session view; it is a snapshot and does not follow live events.\n */\n async getSession(options: GetSessionOptions): Promise<SessionView> {\n return sessionViewSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(options.id)}${options.detail ? `?detail=${options.detail}` : \"\"}`,\n )\n ).json(),\n );\n }\n /** Reads the canonical task graph projected for one session. */\n async getSessionGraph(options: GetSessionGraphOptions): Promise<TaskGraphView> {\n return taskGraphViewSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(options.id)}/graph${options.taskId ? `?${new URLSearchParams({ taskId: options.taskId })}` : \"\"}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /** Reads the materialized transcript for one exact graph task execution. */\n async getGraphTranscript(options: GraphTranscriptOptions): Promise<TranscriptSnapshot> {\n const query = new URLSearchParams({\n taskId: options.taskId,\n executionId: options.executionId,\n });\n return transcriptPageSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(options.sessionId)}/graph-transcript?${query}`,\n undefined,\n options.signal,\n )\n ).json(),\n ).snapshot;\n }\n /** Refreshes a session summary and reloads its history when the active execution changes. */\n async refreshSession(previous: SessionView): Promise<SessionView> {\n const current = await this.getSession({ id: previous.session.id, detail: \"summary\" });\n if (\n current.task?.id !== previous.task?.id ||\n current.execution?.sessionId !== previous.execution?.sessionId ||\n current.execution?.provider !== previous.execution?.provider\n )\n return this.getSession({ id: previous.session.id });\n if (\n current.session.latestNotificationId !== previous.session.latestNotificationId ||\n current.task?.updatedAt !== previous.task?.updatedAt ||\n current.statusRevision !== previous.statusRevision\n ) {\n const fresh = await this.getSession({ id: previous.session.id });\n if (\n fresh.task?.id !== previous.task?.id ||\n fresh.execution?.sessionId !== previous.execution?.sessionId ||\n fresh.execution?.provider !== previous.execution?.provider\n )\n return fresh;\n return {\n ...fresh,\n history: [\n ...new Map(\n [...(previous.history ?? []), ...(fresh.history ?? [])].map((entry) => [\n JSON.stringify(entry.execution),\n entry,\n ]),\n ).values(),\n ],\n historyNextCursor:\n (previous.history?.length ?? 0) > (fresh.history?.length ?? 0)\n ? previous.historyNextCursor\n : fresh.historyNextCursor,\n notifications: [\n ...new Map(\n [...previous.notifications, ...fresh.notifications].map((entry) => [\n entry.eventId,\n entry,\n ]),\n ).values(),\n ],\n notificationsNextCursor:\n previous.notifications.length > fresh.notifications.length\n ? previous.notificationsNextCursor\n : fresh.notificationsNextCursor,\n relatedTasks: [\n ...new Map(\n [\n ...(fresh.relatedTasks ?? []),\n ...(previous.relatedTasks ?? []).filter(\n (entry) => !fresh.relatedTasks?.some((current) => current.id === entry.id),\n ),\n ].map((entry) => [entry.id, entry]),\n ).values(),\n ],\n relatedTasksNextCursor:\n (previous.relatedTasks?.length ?? 0) > (fresh.relatedTasks?.length ?? 0)\n ? previous.relatedTasksNextCursor\n : fresh.relatedTasksNextCursor,\n };\n }\n return {\n ...current,\n workGroups: previous.workGroups,\n history: previous.history,\n historyNextCursor: previous.historyNextCursor,\n notifications: previous.notifications,\n notificationsNextCursor: previous.notificationsNextCursor,\n relatedTasks: previous.relatedTasks,\n relatedTasksNextCursor: previous.relatedTasksNextCursor,\n };\n }\n /** Reads application-owned previews without starting an agent, deployment, or server. */\n async getSessionPreviews(options: SessionPreviewsOptions): Promise<SessionPreviews> {\n return sessionPreviewsSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(options.sessionId)}/previews?${new URLSearchParams({ executionId: options.executionId ?? \"\" })}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /** Reads recorded checks, screenshots, and issues through the application's review reader. */\n async getSessionReview(options: SessionReviewOptions): Promise<SessionReview> {\n return sessionReviewSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(options.sessionId)}/review?${new URLSearchParams({ executionId: options.executionId ?? \"\" })}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /** Reads a directory or complete file through the factory's configured workspace adapter. */\n async getWorkspaceFiles(options: WorkspaceFilesOptions): Promise<WorkspaceFiles> {\n const query = workspaceFilesRequestSchema.parse({\n path: options.path,\n revision: options.revision,\n });\n const params = new URLSearchParams({\n executionId: options.executionId ?? \"\",\n path: query.path,\n });\n if (query.revision !== undefined) params.set(\"revision\", query.revision);\n return workspaceFilesSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(options.sessionId)}/files?${params}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /** Reads the committed workspace comparison for one observed execution. */\n async getWorkspaceDiff(options: WorkspaceDiffOptions): Promise<WorkspaceDiff> {\n return workspaceDiffSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(options.sessionId)}/diff?${new URLSearchParams({ executionId: options.executionId ?? \"\" })}`,\n undefined,\n options.signal,\n )\n ).json(),\n );\n }\n /**\n * Creates or recovers an idempotent conversational session.\n *\n * @remarks\n * Retain `input.operationId` unchanged across ambiguous failures. Reusing it with identical input\n * returns the original session; reusing it with different input is a conflict. The returned view\n * means admission and any initial dispatch attempt finished, not that the agent's work completed.\n *\n * @param input - Agent, initial content, optional repository/change, and client idempotency key.\n * @returns The admitted or recovered session snapshot.\n */\n async createSession(input: CreateSessionRequest): Promise<SessionView> {\n return sessionViewSchema.parse(\n await (await this.response(\"sessions\", createSessionRequestSchema.parse(input))).json(),\n );\n }\n\n /** Creates or recovers idempotent workflow work through a specialist signal. */\n async createSignal(input: CreateSessionRequest): Promise<SessionView> {\n return sessionViewSchema.parse(\n await (await this.response(\"signals\", createSessionRequestSchema.parse(input))).json(),\n );\n }\n\n /** Starts a deepsec security scan of a repository, or returns its already-active scan. */\n async runSecurityScan(repositoryId: RepositoryId): Promise<{ taskId: TaskId; reused: boolean }> {\n return z\n .strictObject({ taskId: taskIdSchema, reused: z.boolean() })\n .parse(await (await this.response(`repositories/${repositoryId}/security-scan`, {})).json());\n }\n\n /**\n * Sends a message to an existing session using optimistic execution matching.\n *\n * @remarks\n * `input.executionId` must be the execution the caller observed, or `null` when none was active.\n * A completed Task follow-up also requires an `operationId`, which must be retained for retries.\n * Resolving means the API accepted the message; provider or follow-up work may still be running.\n *\n * @param id - Stable Factory session receiving the message.\n * @param input - Message, observed execution, steering policy, attachments, and optional retry key.\n * @returns Nothing after the API accepts the request.\n */\n async sendSessionMessage(id: AgentSessionId, input: SendSessionMessageRequest): Promise<void> {\n const response = await this.response(\n `sessions/${encodeURIComponent(id)}/messages`,\n sendSessionMessageRequestSchema.parse(input),\n );\n await response.body?.cancel();\n }\n\n /**\n * Submits responses to pending provider input requests.\n *\n * @param id - Stable Factory session whose provider requested input.\n * @param input - Observed execution ID and one or more request-correlated responses.\n * @returns Nothing after the API accepts the responses; stale execution IDs are rejected.\n */\n async submitSessionInput(id: AgentSessionId, input: SubmitSessionInputRequest): Promise<void> {\n const response = await this.response(\n `sessions/${encodeURIComponent(id)}/input`,\n submitSessionInputRequestSchema.parse(input),\n );\n await response.body?.cancel();\n }\n\n /**\n * Attempts to dispatch queued workflow work associated with a session.\n *\n * @param id - Stable Factory session whose current work should be dispatched.\n * @returns The refreshed session after the bounded dispatch attempt, which may still be queued.\n */\n async dispatchSession(id: AgentSessionId): Promise<SessionView> {\n return sessionViewSchema.parse(\n await (await this.response(`sessions/${encodeURIComponent(id)}/dispatch`, {})).json(),\n );\n }\n\n /** Answers a workflow question associated with a session. */\n async answerSessionQuestion(\n id: AgentSessionId,\n input: AnswerSessionQuestionRequest,\n ): Promise<SessionView> {\n return sessionViewSchema.parse(\n await (\n await this.response(\n `sessions/${encodeURIComponent(id)}/answer`,\n answerSessionQuestionRequestSchema.parse(input),\n )\n ).json(),\n );\n }\n\n /** Cooperatively interrupts the currently observed turn. */\n async interruptSession(id: AgentSessionId, input: ControlSessionRequest = {}): Promise<void> {\n return this.controlSession(id, \"interrupt\", input);\n }\n\n /** Cancels active workflow and provider work in a session. */\n async cancelSession(id: AgentSessionId, input: ControlSessionRequest = {}): Promise<void> {\n return this.controlSession(id, \"cancel\", input);\n }\n\n /** Compacts the provider context for a session. */\n async compactSession(id: AgentSessionId, input: ControlSessionRequest = {}): Promise<void> {\n return this.controlSession(id, \"compact\", input);\n }\n\n /** Clears the provider context for a session. */\n async clearSession(id: AgentSessionId, input: ControlSessionRequest = {}): Promise<void> {\n return this.controlSession(id, \"clear\", input);\n }\n\n /** Resets a session after cancelling its active work. */\n async resetSession(id: AgentSessionId, input: ControlSessionRequest = {}): Promise<void> {\n return this.controlSession(id, \"reset\", input);\n }\n\n /** Reads a materialized transcript as a raw HTTP response for incremental following. */\n async getSessionTranscriptResponse(input: SessionTranscriptRequest): Promise<Response> {\n const query = new URLSearchParams({ executionId: input.executionId });\n if (input.history === true) query.set(\"history\", \"1\");\n if (input.taskId !== undefined) query.set(\"taskId\", input.taskId);\n if (input.limit !== undefined) query.set(\"limit\", String(input.limit));\n if (input.cursor !== undefined) query.set(\"cursor\", input.cursor);\n if (input.blockId !== undefined) query.set(\"blockId\", input.blockId);\n return this.response(\n `sessions/${encodeURIComponent(input.sessionId)}/${input.taskId ? \"graph-transcript\" : \"transcript\"}?${query}`,\n undefined,\n input.signal,\n );\n }\n\n /** Reads one bounded page of saved transcript history from Factory storage. */\n async getTranscriptPage(\n input: Omit<SessionTranscriptRequest, \"blockId\">,\n ): Promise<TranscriptPage> {\n return transcriptPageSchema.parse(\n await (await this.getSessionTranscriptResponse(input)).json(),\n );\n }\n\n /** Expands one large transcript block after authorizing its session and execution. */\n async getTranscriptBlock(\n input: Omit<SessionTranscriptRequest, \"limit\" | \"cursor\"> & { readonly blockId: string },\n ): Promise<TranscriptBlock> {\n return transcriptBlockSchema.parse(\n await (await this.getSessionTranscriptResponse(input)).json(),\n );\n }\n\n /** Opens a cursor-addressed session event stream as a raw HTTP response. */\n async getSessionEventStreamResponse(input: SessionEventStreamRequest): Promise<Response> {\n const query = new URLSearchParams({\n executionId: input.executionId,\n startIndex: String(input.cursor),\n });\n if (input.taskId !== undefined) query.set(\"taskId\", input.taskId);\n return this.response(\n `sessions/${encodeURIComponent(input.sessionId)}/${input.taskId ? \"graph-stream\" : \"stream\"}?${query}`,\n undefined,\n input.signal,\n );\n }\n\n private async controlSession(\n id: AgentSessionId,\n action: \"interrupt\" | \"cancel\" | \"compact\" | \"clear\" | \"reset\",\n input: ControlSessionRequest,\n ): Promise<void> {\n const response = await this.response(\n `sessions/${encodeURIComponent(id)}/${action}`,\n controlSessionRequestSchema.parse(input),\n );\n await response.body?.cancel();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmHA,MAAa,aAAa,OAAO,OAAO,CAAC,GAAG,gBAAgB,OAAO,CAAC;;AA4FpE,IAAa,WAAb,cAA8B,MAAM;CAEvB;CAEA;CAHX,YACE,QACA,SACA,OACA;EACA,MAAM,OAAO;EAJJ,KAAA,SAAA;EAEA,KAAA,QAAA;CAGX;AACF;;;;;;;;;;AAwGA,IAAa,gBAAb,MAA2B;CAQI;CAP7B;;;;;;;CAOA,YAAY,SAAgD;EAA/B,KAAA,UAAA;EAC3B,MAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;EAC/B,IACE,IAAI,YACJ,IAAI,YACJ,IAAI,aAAa,OACjB,IAAI,UACJ,IAAI,QACH,IAAI,aAAa,YAChB,EAAE,IAAI,aAAa,WAAW;GAAC;GAAa;GAAa;EAAO,CAAC,CAAC,SAAS,IAAI,QAAQ,IAEzF,MAAM,IAAI,MAAM,0DAA0D;EAE5E,KAAK,SAAS,IAAI;CACpB;CAEA,MAAc,SAAS,MAAc,MAAgB,QAAyC;EAC5F,MAAM,MAAM,IAAI,IAAI,WAAW,QAAQ,KAAK,MAAM;EAClD,IAAI,IAAI,WAAW,KAAK,UAAU,CAAC,IAAI,SAAS,WAAW,UAAU,GACnE,MAAM,IAAI,MAAM,0BAA0B;EAC5C,MAAM,UAAU,IAAI,QAAQ,MAAM,KAAK,QAAQ,UAAU,CAAC;EAC1D,QAAQ,IAAI,gBAAgB,kBAAkB;EAC9C,MAAM,WAAW,OAAO,KAAK,QAAQ,SAAS,WAAW,MAAA,CAAO,IAAI,MAAM;GACxE,QAAQ,SAAS,KAAA,IAAY,QAAQ;GACrC;GACA,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,KAAK,UAAU,IA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O,sBAAsB,MAC3B,OAAO,MAAM,KAAK,6BAA6B,KAAK,EAAA,CAAG,KAAK,CAC9D;CACF;;CAGA,MAAM,8BAA8B,OAAqD;EACvF,MAAM,QAAQ,IAAI,gBAAgB;GAChC,aAAa,MAAM;GACnB,YAAY,OAAO,MAAM,MAAM;EACjC,CAAC;EACD,IAAI,MAAM,WAAW,KAAA,GAAW,MAAM,IAAI,UAAU,MAAM,MAAM;EAChE,OAAO,KAAK,SACV,YAAY,mBAAmB,MAAM,SAAS,EAAE,GAAG,MAAM,SAAS,iBAAiB,SAAS,GAAG,SAC/F,KAAA,GACA,MAAM,MACR;CACF;CAEA,MAAc,eACZ,IACA,QACA,OACe;EAKf,OAAM,MAJiB,KAAK,SAC1B,YAAY,mBAAmB,EAAE,EAAE,GAAG,UACtC,4BAA4B,MAAM,KAAK,CACzC,EAAA,CACe,MAAM,OAAO;CAC9B;AACF"}
@@ -331,6 +331,7 @@ function createVercelManagedGitHubApi(options = {}) {
331
331
  pullRequestUrl: pull.html_url,
332
332
  draft: pull.draft
333
333
  });
334
+ const existingPull = (await pulls()).find((pull) => pull.head.ref === branch);
334
335
  const refPath = `/git/ref/heads/${branch.split("/").map(encodeURIComponent).join("/")}`;
335
336
  let existingRef;
336
337
  try {
@@ -343,17 +344,17 @@ function createVercelManagedGitHubApi(options = {}) {
343
344
  existingRef = null;
344
345
  }
345
346
  let commitSha = existingRef?.object.sha;
347
+ if (existingPull) {
348
+ if (existingPull.state !== "open") throw new Error("Managed publication pull request is closed");
349
+ if (commitSha !== existingPull.head.sha) throw new Error("Managed publication pull request head differs from its branch");
350
+ const existingCommit = commitSchema.parse(await authorizedRequest({
351
+ method: "GET",
352
+ path: `/git/commits/${existingPull.head.sha}`
353
+ }));
354
+ if (existingCommit.tree.sha !== tree.sha || existingCommit.parents.length !== 1 || existingCommit.parents[0]?.sha !== input.baseCommit) throw new Error("Managed publication pull request contains different changes");
355
+ return result(existingPull, existingPull.head.sha);
356
+ }
346
357
  if (commitSha) {
347
- const existingPull = (await pulls()).find((pull) => pull.head.ref === branch);
348
- if (existingPull) {
349
- if (existingPull.state !== "open") throw new Error("Managed publication pull request is closed");
350
- const existingCommit = commitSchema.parse(await authorizedRequest({
351
- method: "GET",
352
- path: `/git/commits/${existingPull.head.sha}`
353
- }));
354
- if (existingCommit.tree.sha !== tree.sha || existingCommit.parents.length !== 1 || existingCommit.parents[0]?.sha !== input.baseCommit) throw new Error("Managed publication pull request contains different changes");
355
- return result(existingPull, existingPull.head.sha);
356
- }
357
358
  const existingCommit = commitSchema.parse(await authorizedRequest({
358
359
  method: "GET",
359
360
  path: `/git/commits/${commitSha}`
@@ -1 +1 @@
1
- {"version":3,"file":"vercel-github-api.mjs","names":[],"sources":["../src/vercel-github-api.ts"],"sourcesContent":["import type { Sandbox, NetworkPolicy } from \"@vercel/sandbox\";\nimport { z } from \"zod\";\nimport { isSafeGitRef, type GitHubTreeEntry } from \"./github-publication\";\nimport { repositorySlugSchema, type RepositorySlug } from \"./schema/repository\";\n\ntype TrustedGitHubApiSandbox = Pick<Sandbox, \"runCommand\" | \"stop\">;\n\n/** GitHub API actions supported by Vercel-managed Sandbox credentials. */\nexport type VercelManagedGitHubApiAction =\n | \"github:issues:read\"\n | \"github:pull-request:create\"\n | \"github:labels:write\";\n\n/** Exact creation request for one Vercel-managed GitHub API operation. */\nexport interface VercelManagedGitHubApiSandboxCreateInput {\n source?: {\n type: \"git\";\n url: string;\n };\n __source_credentials?: true;\n __commitAs?: {\n name: string;\n email: string;\n };\n __credentials: {\n github: [\n {\n repositories: [RepositorySlug];\n actions: [VercelManagedGitHubApiAction];\n },\n ];\n };\n networkPolicy: NetworkPolicy;\n persistent: false;\n resources: { vcpus: 6 };\n runtime: \"node24\";\n timeout: 60_000 | 180_000;\n}\n\n/** Configures fresh trusted Sandboxes for brokered GitHub API requests. */\nexport interface VercelManagedGitHubApiOptions {\n /** Attribution metadata supplied when managed publication creates a signed commit. */\n commitIdentity?: { name: string; email: string };\n createSandbox?: (\n input: VercelManagedGitHubApiSandboxCreateInput,\n ) => Promise<TrustedGitHubApiSandbox>;\n}\n\n/** Authorized request to read one exact GitHub issue. */\nexport interface VercelManagedGitHubIssueInput {\n repository: RepositorySlug;\n issueNumber: number;\n authorize(): Promise<void>;\n}\n\n/** Issue fields returned by a Vercel-managed GitHub API request. */\nexport interface VercelManagedGitHubIssue {\n title: string;\n body: string | null;\n url: string;\n pullRequest: boolean;\n}\n\n/** Authorized request to ensure and attach a repository flow label to a pull request. */\nexport interface VercelManagedGitHubLabelInput {\n repository: RepositorySlug;\n pullRequestNumber: number;\n name: string;\n color: string;\n description: string;\n authorize(): Promise<void>;\n}\n\n/** Authorized request to create one draft or ready GitHub pull request. */\nexport interface VercelManagedGitHubPullRequestInput {\n repository: RepositorySlug;\n title: string;\n body: string;\n head: string;\n base: string;\n draft: boolean;\n authorize(): Promise<void>;\n}\n\n/** Pull-request identity returned by a Vercel-managed GitHub API request. */\nexport interface VercelManagedGitHubPullRequest {\n pullRequestNumber: number;\n pullRequestUrl: string;\n draft: boolean;\n}\n\n/** Git Data and pull-request inputs for one idempotent managed publication. */\nexport interface VercelManagedGitHubPublicationInput {\n repository: RepositorySlug;\n baseCommit: string;\n tree: readonly GitHubTreeEntry[];\n commitMessage: string;\n branch: string;\n title: string;\n body: string;\n baseBranch: string;\n draft: boolean;\n authorize(): Promise<void>;\n}\n\n/** Commit and pull-request identities returned after managed publication. */\nexport interface VercelManagedGitHubPublication extends VercelManagedGitHubPullRequest {\n commitSha: string;\n}\n\n/** Repository-scoped brokered GitHub API operations supplied by Vercel Sandbox. */\nexport interface VercelManagedGitHubApi {\n readIssue(input: VercelManagedGitHubIssueInput): Promise<VercelManagedGitHubIssue>;\n labelPullRequest(input: VercelManagedGitHubLabelInput): Promise<void>;\n createPullRequest(\n input: VercelManagedGitHubPullRequestInput,\n ): Promise<VercelManagedGitHubPullRequest>;\n publishPullRequest(\n input: VercelManagedGitHubPublicationInput,\n ): Promise<VercelManagedGitHubPublication>;\n}\n\n/** GitHub API failure returned through the managed credential Sandbox. */\nexport class VercelManagedGitHubApiError extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(`GitHub API request failed (${status}): ${message}`);\n this.name = \"VercelManagedGitHubApiError\";\n }\n}\n\nconst sandboxResponseSchema = z.object({\n status: z.number().int().min(100).max(599),\n body: z.unknown(),\n});\nconst issueSchema = z.object({\n title: z.string(),\n body: z.string().nullable(),\n html_url: z.url(),\n pull_request: z.unknown().optional(),\n});\nconst labelSchema = z.object({ name: z.string() });\nconst labelInputSchema = z.object({\n name: z\n .string()\n .min(1)\n .max(50)\n .refine(\n (name) =>\n Buffer.byteLength(name, \"utf8\") <= 50 &&\n name.trim() === name &&\n [...name].every((character) => {\n const code = character.charCodeAt(0);\n return code > 31 && code !== 127 && character !== \"\\\\\";\n }) &&\n name.split(\"/\").every((part) => part !== \"\" && part !== \".\" && part !== \"..\"),\n ),\n color: z.string().regex(/^[a-fA-F0-9]{6}$/u),\n description: z\n .string()\n .max(100)\n .refine((description) => Buffer.byteLength(description, \"utf8\") <= 100),\n});\nconst pullRequestSchema = z.object({\n number: z.number().int().positive(),\n html_url: z.url(),\n draft: z.boolean(),\n});\nconst shaSchema = z.string().regex(/^[a-f0-9]{40}$/u);\nconst commitSchema = z.object({\n sha: shaSchema,\n tree: z.object({ sha: shaSchema }),\n parents: z.array(z.object({ sha: shaSchema })),\n});\nconst treeSchema = z.object({ sha: shaSchema });\nconst refSchema = z.object({ object: z.object({ sha: shaSchema }) });\nconst publicationPullSchema = pullRequestSchema.extend({\n state: z.enum([\"open\", \"closed\"]),\n head: z.object({ ref: z.string(), sha: shaSchema }),\n});\nconst publicationPathSchema = z\n .string()\n .min(1)\n .max(1_024)\n .refine((path) => Buffer.byteLength(path, \"utf8\") <= 1_024, {\n message: \"Managed publication path exceeds byte limit\",\n })\n .refine(\n (path) =>\n /^[A-Za-z0-9.][A-Za-z0-9._/-]*$/u.test(path) &&\n !path.includes(\"..\") &&\n !path.includes(\"//\") &&\n !path.endsWith(\"/\") &&\n !path.split(\"/\").some((part) => part === \".\"),\n { message: \"Invalid managed publication path\" },\n );\nconst publicationBranchSchema = z\n .string()\n .min(1)\n .max(256)\n .refine(\n (branch) =>\n isSafeGitRef(branch) &&\n branch\n .split(\"/\")\n .every(\n (component) =>\n component.length > 0 &&\n !component.startsWith(\".\") &&\n !component.endsWith(\".\") &&\n !component.endsWith(\".lock\"),\n ),\n { message: \"Invalid managed publication branch\" },\n );\nconst publicationTextSchema = (maximum: number, field: string) =>\n z\n .string()\n .max(maximum)\n .refine((value) => Buffer.byteLength(value, \"utf8\") <= maximum, {\n message: `Managed publication ${field} exceeds byte limit`,\n });\nconst publicationCommitMessageSchema = publicationTextSchema(65_536, \"commit message\").min(1);\nconst publicationTitleSchema = publicationTextSchema(256, \"title\").min(1);\nconst publicationBodySchema = publicationTextSchema(65_536, \"body\");\nconst publicationBaseBranchSchema = z\n .string()\n .min(1)\n .max(256)\n .refine((branch) => isSafeGitRef(branch), {\n message: \"Invalid managed publication base branch\",\n });\nconst publicationContentSchema = z\n .string()\n .max(200_000)\n .refine((content) => Buffer.byteLength(content, \"utf8\") <= 200_000, {\n message: \"Managed publication content exceeds byte limit\",\n });\nconst publicationTreeSchema = z\n .array(\n z.union([\n z.strictObject({\n path: publicationPathSchema,\n mode: z.enum([\"100644\", \"100755\"]),\n type: z.literal(\"blob\"),\n content: publicationContentSchema,\n }),\n z.strictObject({\n path: publicationPathSchema,\n mode: z.enum([\"100644\", \"100755\"]),\n type: z.literal(\"blob\"),\n sha: z.null(),\n }),\n ]),\n )\n .min(1)\n .max(25)\n .refine(\n (entries) =>\n new TextEncoder().encode(JSON.stringify({ tree: entries })).byteLength <= 1_000_000,\n \"Managed publication tree exceeds transfer limit\",\n );\nconst githubRequestScript = `\nconst request = JSON.parse(process.argv[1]);\nconst response = await fetch(request.url, {\n method: request.method,\n headers: {\n accept: \"application/vnd.github+json\",\n \"content-type\": \"application/json\",\n \"x-github-api-version\": \"2022-11-28\",\n },\n body: request.body === undefined ? undefined : JSON.stringify(request.body),\n redirect: \"error\",\n});\nconst reader = response.body?.getReader();\nconst chunks = [];\nlet byteLength = 0;\nif (reader) {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n byteLength += value.byteLength;\n if (byteLength > 1_000_000) {\n await reader.cancel();\n throw new Error(\"GitHub API response exceeds transfer limit\");\n }\n chunks.push(value);\n }\n}\nconst bytes = new Uint8Array(byteLength);\nlet offset = 0;\nfor (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }\nconst text = new TextDecoder().decode(bytes);\nlet body = null;\ntry { body = text === \"\" ? null : JSON.parse(text); } catch { body = { message: text }; }\nprocess.stdout.write(JSON.stringify({ status: response.status, body }));\n`;\n\nasync function createManagedSandbox(\n input: VercelManagedGitHubApiSandboxCreateInput,\n): Promise<TrustedGitHubApiSandbox> {\n const { Sandbox } = await import(\"@vercel/sandbox\");\n return Sandbox.create({ ...input });\n}\n\nfunction createInput(\n repository: RepositorySlug,\n action: VercelManagedGitHubApiAction,\n): VercelManagedGitHubApiSandboxCreateInput {\n return {\n __credentials: { github: [{ repositories: [repository], actions: [action] }] },\n networkPolicy: { allow: [\"api.github.com\"] },\n persistent: false,\n resources: { vcpus: 6 },\n runtime: \"node24\",\n timeout: 60_000,\n };\n}\n\nfunction createPublicationInput(\n repository: RepositorySlug,\n commitIdentity: { name: string; email: string },\n): VercelManagedGitHubApiSandboxCreateInput {\n return {\n source: { type: \"git\", url: `https://github.com/${repository}.git` },\n __source_credentials: true,\n __commitAs: commitIdentity,\n __credentials: {\n github: [\n {\n repositories: [repository],\n actions: [\"github:pull-request:create\"],\n },\n ],\n },\n networkPolicy: { allow: [\"github.com\", \"api.github.com\"] },\n persistent: false,\n resources: { vcpus: 6 },\n runtime: \"node24\",\n timeout: 180_000,\n };\n}\n\nasync function request(\n createSandbox: (\n input: VercelManagedGitHubApiSandboxCreateInput,\n ) => Promise<TrustedGitHubApiSandbox>,\n input: {\n repository: RepositorySlug;\n action: VercelManagedGitHubApiAction;\n method: \"GET\" | \"POST\";\n path: string;\n body?: unknown;\n authorize(): Promise<void>;\n },\n): Promise<unknown> {\n const sandbox = await createSandbox(createInput(input.repository, input.action));\n try {\n await input.authorize();\n const result = await sandbox.runCommand({\n cmd: \"node\",\n args: [\n \"--input-type=module\",\n \"--eval\",\n githubRequestScript,\n JSON.stringify({\n method: input.method,\n url: `https://api.github.com/repos/${input.repository}${input.path}`,\n ...(input.body === undefined ? {} : { body: input.body }),\n }),\n ],\n timeoutMs: 30_000,\n });\n const stderr = (await result.stderr()).trim();\n if (result.exitCode !== 0) {\n throw new Error(`Managed GitHub API operation failed (${result.exitCode}): ${stderr}`);\n }\n const response = sandboxResponseSchema.parse(JSON.parse((await result.stdout()).trim()));\n if (response.status < 200 || response.status >= 300) {\n const message = z.object({ message: z.string() }).safeParse(response.body);\n throw new VercelManagedGitHubApiError(\n response.status,\n message.success ? message.data.message : \"Unexpected response\",\n );\n }\n return response.body;\n } finally {\n await sandbox.stop();\n }\n}\n\nasync function sandboxRequest(\n sandbox: TrustedGitHubApiSandbox,\n input: {\n repository: RepositorySlug;\n method: \"GET\" | \"POST\";\n path: string;\n body?: unknown;\n },\n): Promise<unknown> {\n const result = await sandbox.runCommand({\n cmd: \"node\",\n args: [\n \"--input-type=module\",\n \"--eval\",\n githubRequestScript,\n JSON.stringify({\n method: input.method,\n url: `https://api.github.com/repos/${input.repository}${input.path}`,\n ...(input.body === undefined ? {} : { body: input.body }),\n }),\n ],\n timeoutMs: 30_000,\n });\n const stderr = (await result.stderr()).trim();\n if (result.exitCode !== 0) {\n throw new Error(`Managed GitHub API operation failed (${result.exitCode}): ${stderr}`);\n }\n const response = sandboxResponseSchema.parse(JSON.parse((await result.stdout()).trim()));\n if (response.status < 200 || response.status >= 300) {\n const message = z.object({ message: z.string() }).safeParse(response.body);\n throw new VercelManagedGitHubApiError(\n response.status,\n message.success ? message.data.message : \"Unexpected response\",\n );\n }\n return response.body;\n}\n\n/** Create repository-scoped GitHub API operations backed by managed Sandbox credentials. */\nexport function createVercelManagedGitHubApi(\n options: VercelManagedGitHubApiOptions = {},\n): VercelManagedGitHubApi {\n const createSandbox = options.createSandbox ?? createManagedSandbox;\n return {\n async readIssue(input) {\n const repository = repositorySlugSchema.parse(input.repository.toLowerCase());\n if (!Number.isSafeInteger(input.issueNumber) || input.issueNumber < 1) {\n throw new Error(\"Invalid GitHub issue number\");\n }\n const issue = issueSchema.parse(\n await request(createSandbox, {\n repository,\n action: \"github:issues:read\",\n method: \"GET\",\n path: `/issues/${input.issueNumber}`,\n authorize: input.authorize,\n }),\n );\n return {\n title: issue.title,\n body: issue.body,\n url: issue.html_url,\n pullRequest: issue.pull_request !== undefined,\n };\n },\n async labelPullRequest(input) {\n const repository = repositorySlugSchema.parse(input.repository.toLowerCase());\n if (!Number.isSafeInteger(input.pullRequestNumber) || input.pullRequestNumber < 1) {\n throw new Error(\"Invalid GitHub pull request number\");\n }\n const label = labelInputSchema.parse(input);\n const sandbox = await createSandbox(createInput(repository, \"github:labels:write\"));\n try {\n const authorizedRequest = async (\n request: Omit<Parameters<typeof sandboxRequest>[1], \"repository\">,\n ) => {\n await input.authorize();\n return sandboxRequest(sandbox, { repository, ...request });\n };\n const labelPath = `/labels/${encodeURIComponent(label.name)}`;\n const read = async () => {\n const existing = labelSchema.parse(\n await authorizedRequest({ method: \"GET\", path: labelPath }),\n );\n if (existing.name.toLowerCase() !== label.name.toLowerCase()) {\n throw new Error(\"GitHub returned a different repository label\");\n }\n };\n try {\n await read();\n } catch (error) {\n if (!(error instanceof VercelManagedGitHubApiError) || error.status !== 404) throw error;\n try {\n await authorizedRequest({ method: \"POST\", path: \"/labels\", body: label });\n } catch (creationError) {\n if (\n !(creationError instanceof VercelManagedGitHubApiError) ||\n creationError.status !== 422\n ) {\n throw creationError;\n }\n await read();\n }\n }\n await authorizedRequest({\n method: \"POST\",\n path: `/issues/${input.pullRequestNumber}/labels`,\n body: { labels: [label.name] },\n });\n } finally {\n await sandbox.stop();\n }\n },\n async createPullRequest(input) {\n const repository = repositorySlugSchema.parse(input.repository.toLowerCase());\n const head = publicationBranchSchema.parse(input.head);\n const base = publicationBaseBranchSchema.parse(input.base);\n const title = publicationTitleSchema.parse(input.title);\n const body = publicationBodySchema.parse(input.body);\n const pull = pullRequestSchema.parse(\n await request(createSandbox, {\n repository,\n action: \"github:pull-request:create\",\n method: \"POST\",\n path: \"/pulls\",\n body: {\n title,\n body,\n head,\n base,\n draft: input.draft,\n },\n authorize: input.authorize,\n }),\n );\n return {\n pullRequestNumber: pull.number,\n pullRequestUrl: pull.html_url,\n draft: pull.draft,\n };\n },\n async publishPullRequest(input) {\n const repository = repositorySlugSchema.parse(input.repository.toLowerCase());\n if (!options.commitIdentity) throw new Error(\"Managed publication requires commit identity\");\n if (!/^[a-f0-9]{40}$/u.test(input.baseCommit) || input.commitMessage.trim() === \"\") {\n throw new Error(\"Invalid managed GitHub publication\");\n }\n const publicationTree = publicationTreeSchema.parse(input.tree);\n const branch = publicationBranchSchema.parse(input.branch);\n const baseBranch = publicationBaseBranchSchema.parse(input.baseBranch);\n const title = publicationTitleSchema.parse(input.title);\n const body = publicationBodySchema.parse(input.body);\n const commitMessage = publicationCommitMessageSchema.parse(\n `${input.commitMessage}\\n\\nCo-authored-by: ${options.commitIdentity.name} <${options.commitIdentity.email}>`,\n );\n const sandbox = await createSandbox(\n createPublicationInput(repository, options.commitIdentity),\n );\n try {\n const authorizedRequest = async (\n request: Omit<Parameters<typeof sandboxRequest>[1], \"repository\">,\n ) => {\n await input.authorize();\n return sandboxRequest(sandbox, { repository, ...request });\n };\n const base = commitSchema.parse(\n await authorizedRequest({\n method: \"GET\",\n path: `/git/commits/${input.baseCommit}`,\n }),\n );\n const tree = treeSchema.parse(\n await authorizedRequest({\n method: \"POST\",\n path: \"/git/trees\",\n body: { base_tree: base.tree.sha, tree: publicationTree },\n }),\n );\n const pullPath = `/pulls?${new URLSearchParams({\n state: \"all\",\n head: `${repository.split(\"/\")[0]}:${branch}`,\n per_page: \"100\",\n })}`;\n const pulls = async () =>\n z\n .array(publicationPullSchema)\n .parse(await authorizedRequest({ method: \"GET\", path: pullPath }));\n const result = (pull: z.infer<typeof pullRequestSchema>, commitSha: string) => ({\n commitSha,\n pullRequestNumber: pull.number,\n pullRequestUrl: pull.html_url,\n draft: pull.draft,\n });\n const refPath = `/git/ref/heads/${branch.split(\"/\").map(encodeURIComponent).join(\"/\")}`;\n let existingRef: z.infer<typeof refSchema> | null;\n try {\n existingRef = refSchema.parse(await authorizedRequest({ method: \"GET\", path: refPath }));\n } catch (error) {\n if (!(error instanceof VercelManagedGitHubApiError) || error.status !== 404) throw error;\n existingRef = null;\n }\n let commitSha = existingRef?.object.sha;\n if (commitSha) {\n const existingPull = (await pulls()).find((pull) => pull.head.ref === branch);\n if (existingPull) {\n if (existingPull.state !== \"open\") {\n throw new Error(\"Managed publication pull request is closed\");\n }\n const existingCommit = commitSchema.parse(\n await authorizedRequest({\n method: \"GET\",\n path: `/git/commits/${existingPull.head.sha}`,\n }),\n );\n if (\n existingCommit.tree.sha !== tree.sha ||\n existingCommit.parents.length !== 1 ||\n existingCommit.parents[0]?.sha !== input.baseCommit\n ) {\n throw new Error(\"Managed publication pull request contains different changes\");\n }\n return result(existingPull, existingPull.head.sha);\n }\n const existingCommit = commitSchema.parse(\n await authorizedRequest({\n method: \"GET\",\n path: `/git/commits/${commitSha}`,\n }),\n );\n if (\n existingCommit.tree.sha !== tree.sha ||\n existingCommit.parents.length !== 1 ||\n existingCommit.parents[0]?.sha !== input.baseCommit\n ) {\n throw new Error(\"Managed publication branch contains different changes\");\n }\n } else {\n const commit = commitSchema.parse(\n await authorizedRequest({\n method: \"POST\",\n path: \"/git/commits\",\n body: {\n message: commitMessage,\n tree: tree.sha,\n parents: [input.baseCommit],\n },\n }),\n );\n commitSha = commit.sha;\n try {\n await authorizedRequest({\n method: \"POST\",\n path: \"/git/refs\",\n body: { ref: `refs/heads/${branch}`, sha: commitSha },\n });\n } catch (error) {\n const reconciled = refSchema.parse(\n await authorizedRequest({ method: \"GET\", path: refPath }),\n );\n if (reconciled.object.sha !== commitSha) throw error;\n }\n }\n let pull: z.infer<typeof pullRequestSchema>;\n try {\n pull = pullRequestSchema.parse(\n await authorizedRequest({\n method: \"POST\",\n path: \"/pulls\",\n body: {\n title,\n body,\n head: branch,\n base: baseBranch,\n draft: input.draft,\n },\n }),\n );\n } catch (error) {\n const reconciled = (await pulls()).find((candidate) => candidate.head.ref === branch);\n if (!reconciled || reconciled.state !== \"open\" || reconciled.head.sha !== commitSha) {\n throw error;\n }\n pull = reconciled;\n }\n return result(pull, commitSha);\n } finally {\n await sandbox.stop();\n }\n },\n };\n}\n"],"mappings":";;;;;AA2HA,IAAa,8BAAb,cAAiD,MAAM;CAE1C;CADX,YACE,QACA,SACA;EACA,MAAM,8BAA8B,OAAO,KAAK,SAAS;EAHhD,KAAA,SAAA;EAIT,KAAK,OAAO;CACd;AACF;AAEA,MAAM,wBAAwB,EAAE,OAAO;CACrC,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,GAAG;CACzC,MAAM,EAAE,QAAQ;AAClB,CAAC;AACD,MAAM,cAAc,EAAE,OAAO;CAC3B,OAAO,EAAE,OAAO;CAChB,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS;CAC1B,UAAU,EAAE,IAAI;CAChB,cAAc,EAAE,QAAQ,CAAC,CAAC,SAAS;AACrC,CAAC;AACD,MAAM,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;AACjD,MAAM,mBAAmB,EAAE,OAAO;CAChC,MAAM,EACH,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,IAAI,EAAE,CAAC,CACP,QACE,SACC,OAAO,WAAW,MAAM,MAAM,KAAK,MACnC,KAAK,KAAK,MAAM,QAChB,CAAC,GAAG,IAA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,EAAE,QAAQ,MAAM,YAEzC,MAAM,IAAI,MAAM,uDAAuD;IAE3E,OAAO;KAYL,YAXe,aAAa,MAC1B,MAAM,kBAAkB;MACtB,QAAQ;MACR,MAAM;MACN,MAAM;OACJ,SAAS;OACT,MAAM,KAAK;OACX,SAAS,CAAC,MAAM,UAAU;MAC5B;KACF,CAAC,CAEc,CAAC,CAAC;KACnB,IAAI;MACF,MAAM,kBAAkB;OACtB,QAAQ;OACR,MAAM;OACN,MAAM;QAAE,KAAK,cAAc;QAAU,KAAK;OAAU;MACtD,CAAC;KACH,SAAS,OAAO;MAId,IAHmB,UAAU,MAC3B,MAAM,kBAAkB;OAAE,QAAQ;OAAO,MAAM;MAAQ,CAAC,CAE7C,CAAC,CAAC,OAAO,QAAQ,WAAW,MAAM;KACjD;IACF;IACA,IAAI;IACJ,IAAI;KACF,OAAO,kBAAkB,MACvB,MAAM,kBAAkB;MACtB,QAAQ;MACR,MAAM;MACN,MAAM;OACJ;OACA;OACA,MAAM;OACN,MAAM;OACN,OAAO,MAAM;MACf;KACF,CAAC,CACH;IACF,SAAS,OAAO;KACd,MAAM,cAAc,MAAM,MAAM,EAAA,CAAG,MAAM,cAAc,UAAU,KAAK,QAAQ,MAAM;KACpF,IAAI,CAAC,cAAc,WAAW,UAAU,UAAU,WAAW,KAAK,QAAQ,WACxE,MAAM;KAER,OAAO;IACT;IACA,OAAO,OAAO,MAAM,SAAS;GAC/B,UAAU;IACR,MAAM,QAAQ,KAAK;GACrB;EACF;CACF;AACF"}
1
+ {"version":3,"file":"vercel-github-api.mjs","names":[],"sources":["../src/vercel-github-api.ts"],"sourcesContent":["import type { Sandbox, NetworkPolicy } from \"@vercel/sandbox\";\nimport { z } from \"zod\";\nimport { isSafeGitRef, type GitHubTreeEntry } from \"./github-publication\";\nimport { repositorySlugSchema, type RepositorySlug } from \"./schema/repository\";\n\ntype TrustedGitHubApiSandbox = Pick<Sandbox, \"runCommand\" | \"stop\">;\n\n/** GitHub API actions supported by Vercel-managed Sandbox credentials. */\nexport type VercelManagedGitHubApiAction =\n | \"github:issues:read\"\n | \"github:pull-request:create\"\n | \"github:labels:write\";\n\n/** Exact creation request for one Vercel-managed GitHub API operation. */\nexport interface VercelManagedGitHubApiSandboxCreateInput {\n source?: {\n type: \"git\";\n url: string;\n };\n __source_credentials?: true;\n __commitAs?: {\n name: string;\n email: string;\n };\n __credentials: {\n github: [\n {\n repositories: [RepositorySlug];\n actions: [VercelManagedGitHubApiAction];\n },\n ];\n };\n networkPolicy: NetworkPolicy;\n persistent: false;\n resources: { vcpus: 6 };\n runtime: \"node24\";\n timeout: 60_000 | 180_000;\n}\n\n/** Configures fresh trusted Sandboxes for brokered GitHub API requests. */\nexport interface VercelManagedGitHubApiOptions {\n /** Attribution metadata supplied when managed publication creates a signed commit. */\n commitIdentity?: { name: string; email: string };\n createSandbox?: (\n input: VercelManagedGitHubApiSandboxCreateInput,\n ) => Promise<TrustedGitHubApiSandbox>;\n}\n\n/** Authorized request to read one exact GitHub issue. */\nexport interface VercelManagedGitHubIssueInput {\n repository: RepositorySlug;\n issueNumber: number;\n authorize(): Promise<void>;\n}\n\n/** Issue fields returned by a Vercel-managed GitHub API request. */\nexport interface VercelManagedGitHubIssue {\n title: string;\n body: string | null;\n url: string;\n pullRequest: boolean;\n}\n\n/** Authorized request to ensure and attach a repository flow label to a pull request. */\nexport interface VercelManagedGitHubLabelInput {\n repository: RepositorySlug;\n pullRequestNumber: number;\n name: string;\n color: string;\n description: string;\n authorize(): Promise<void>;\n}\n\n/** Authorized request to create one draft or ready GitHub pull request. */\nexport interface VercelManagedGitHubPullRequestInput {\n repository: RepositorySlug;\n title: string;\n body: string;\n head: string;\n base: string;\n draft: boolean;\n authorize(): Promise<void>;\n}\n\n/** Pull-request identity returned by a Vercel-managed GitHub API request. */\nexport interface VercelManagedGitHubPullRequest {\n pullRequestNumber: number;\n pullRequestUrl: string;\n draft: boolean;\n}\n\n/** Git Data and pull-request inputs for one idempotent managed publication. */\nexport interface VercelManagedGitHubPublicationInput {\n repository: RepositorySlug;\n baseCommit: string;\n tree: readonly GitHubTreeEntry[];\n commitMessage: string;\n branch: string;\n title: string;\n body: string;\n baseBranch: string;\n draft: boolean;\n authorize(): Promise<void>;\n}\n\n/** Commit and pull-request identities returned after managed publication. */\nexport interface VercelManagedGitHubPublication extends VercelManagedGitHubPullRequest {\n commitSha: string;\n}\n\n/** Repository-scoped brokered GitHub API operations supplied by Vercel Sandbox. */\nexport interface VercelManagedGitHubApi {\n readIssue(input: VercelManagedGitHubIssueInput): Promise<VercelManagedGitHubIssue>;\n labelPullRequest(input: VercelManagedGitHubLabelInput): Promise<void>;\n createPullRequest(\n input: VercelManagedGitHubPullRequestInput,\n ): Promise<VercelManagedGitHubPullRequest>;\n publishPullRequest(\n input: VercelManagedGitHubPublicationInput,\n ): Promise<VercelManagedGitHubPublication>;\n}\n\n/** GitHub API failure returned through the managed credential Sandbox. */\nexport class VercelManagedGitHubApiError extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(`GitHub API request failed (${status}): ${message}`);\n this.name = \"VercelManagedGitHubApiError\";\n }\n}\n\nconst sandboxResponseSchema = z.object({\n status: z.number().int().min(100).max(599),\n body: z.unknown(),\n});\nconst issueSchema = z.object({\n title: z.string(),\n body: z.string().nullable(),\n html_url: z.url(),\n pull_request: z.unknown().optional(),\n});\nconst labelSchema = z.object({ name: z.string() });\nconst labelInputSchema = z.object({\n name: z\n .string()\n .min(1)\n .max(50)\n .refine(\n (name) =>\n Buffer.byteLength(name, \"utf8\") <= 50 &&\n name.trim() === name &&\n [...name].every((character) => {\n const code = character.charCodeAt(0);\n return code > 31 && code !== 127 && character !== \"\\\\\";\n }) &&\n name.split(\"/\").every((part) => part !== \"\" && part !== \".\" && part !== \"..\"),\n ),\n color: z.string().regex(/^[a-fA-F0-9]{6}$/u),\n description: z\n .string()\n .max(100)\n .refine((description) => Buffer.byteLength(description, \"utf8\") <= 100),\n});\nconst pullRequestSchema = z.object({\n number: z.number().int().positive(),\n html_url: z.url(),\n draft: z.boolean(),\n});\nconst shaSchema = z.string().regex(/^[a-f0-9]{40}$/u);\nconst commitSchema = z.object({\n sha: shaSchema,\n tree: z.object({ sha: shaSchema }),\n parents: z.array(z.object({ sha: shaSchema })),\n});\nconst treeSchema = z.object({ sha: shaSchema });\nconst refSchema = z.object({ object: z.object({ sha: shaSchema }) });\nconst publicationPullSchema = pullRequestSchema.extend({\n state: z.enum([\"open\", \"closed\"]),\n head: z.object({ ref: z.string(), sha: shaSchema }),\n});\nconst publicationPathSchema = z\n .string()\n .min(1)\n .max(1_024)\n .refine((path) => Buffer.byteLength(path, \"utf8\") <= 1_024, {\n message: \"Managed publication path exceeds byte limit\",\n })\n .refine(\n (path) =>\n /^[A-Za-z0-9.][A-Za-z0-9._/-]*$/u.test(path) &&\n !path.includes(\"..\") &&\n !path.includes(\"//\") &&\n !path.endsWith(\"/\") &&\n !path.split(\"/\").some((part) => part === \".\"),\n { message: \"Invalid managed publication path\" },\n );\nconst publicationBranchSchema = z\n .string()\n .min(1)\n .max(256)\n .refine(\n (branch) =>\n isSafeGitRef(branch) &&\n branch\n .split(\"/\")\n .every(\n (component) =>\n component.length > 0 &&\n !component.startsWith(\".\") &&\n !component.endsWith(\".\") &&\n !component.endsWith(\".lock\"),\n ),\n { message: \"Invalid managed publication branch\" },\n );\nconst publicationTextSchema = (maximum: number, field: string) =>\n z\n .string()\n .max(maximum)\n .refine((value) => Buffer.byteLength(value, \"utf8\") <= maximum, {\n message: `Managed publication ${field} exceeds byte limit`,\n });\nconst publicationCommitMessageSchema = publicationTextSchema(65_536, \"commit message\").min(1);\nconst publicationTitleSchema = publicationTextSchema(256, \"title\").min(1);\nconst publicationBodySchema = publicationTextSchema(65_536, \"body\");\nconst publicationBaseBranchSchema = z\n .string()\n .min(1)\n .max(256)\n .refine((branch) => isSafeGitRef(branch), {\n message: \"Invalid managed publication base branch\",\n });\nconst publicationContentSchema = z\n .string()\n .max(200_000)\n .refine((content) => Buffer.byteLength(content, \"utf8\") <= 200_000, {\n message: \"Managed publication content exceeds byte limit\",\n });\nconst publicationTreeSchema = z\n .array(\n z.union([\n z.strictObject({\n path: publicationPathSchema,\n mode: z.enum([\"100644\", \"100755\"]),\n type: z.literal(\"blob\"),\n content: publicationContentSchema,\n }),\n z.strictObject({\n path: publicationPathSchema,\n mode: z.enum([\"100644\", \"100755\"]),\n type: z.literal(\"blob\"),\n sha: z.null(),\n }),\n ]),\n )\n .min(1)\n .max(25)\n .refine(\n (entries) =>\n new TextEncoder().encode(JSON.stringify({ tree: entries })).byteLength <= 1_000_000,\n \"Managed publication tree exceeds transfer limit\",\n );\nconst githubRequestScript = `\nconst request = JSON.parse(process.argv[1]);\nconst response = await fetch(request.url, {\n method: request.method,\n headers: {\n accept: \"application/vnd.github+json\",\n \"content-type\": \"application/json\",\n \"x-github-api-version\": \"2022-11-28\",\n },\n body: request.body === undefined ? undefined : JSON.stringify(request.body),\n redirect: \"error\",\n});\nconst reader = response.body?.getReader();\nconst chunks = [];\nlet byteLength = 0;\nif (reader) {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n byteLength += value.byteLength;\n if (byteLength > 1_000_000) {\n await reader.cancel();\n throw new Error(\"GitHub API response exceeds transfer limit\");\n }\n chunks.push(value);\n }\n}\nconst bytes = new Uint8Array(byteLength);\nlet offset = 0;\nfor (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }\nconst text = new TextDecoder().decode(bytes);\nlet body = null;\ntry { body = text === \"\" ? null : JSON.parse(text); } catch { body = { message: text }; }\nprocess.stdout.write(JSON.stringify({ status: response.status, body }));\n`;\n\nasync function createManagedSandbox(\n input: VercelManagedGitHubApiSandboxCreateInput,\n): Promise<TrustedGitHubApiSandbox> {\n const { Sandbox } = await import(\"@vercel/sandbox\");\n return Sandbox.create({ ...input });\n}\n\nfunction createInput(\n repository: RepositorySlug,\n action: VercelManagedGitHubApiAction,\n): VercelManagedGitHubApiSandboxCreateInput {\n return {\n __credentials: { github: [{ repositories: [repository], actions: [action] }] },\n networkPolicy: { allow: [\"api.github.com\"] },\n persistent: false,\n resources: { vcpus: 6 },\n runtime: \"node24\",\n timeout: 60_000,\n };\n}\n\nfunction createPublicationInput(\n repository: RepositorySlug,\n commitIdentity: { name: string; email: string },\n): VercelManagedGitHubApiSandboxCreateInput {\n return {\n source: { type: \"git\", url: `https://github.com/${repository}.git` },\n __source_credentials: true,\n __commitAs: commitIdentity,\n __credentials: {\n github: [\n {\n repositories: [repository],\n actions: [\"github:pull-request:create\"],\n },\n ],\n },\n networkPolicy: { allow: [\"github.com\", \"api.github.com\"] },\n persistent: false,\n resources: { vcpus: 6 },\n runtime: \"node24\",\n timeout: 180_000,\n };\n}\n\nasync function request(\n createSandbox: (\n input: VercelManagedGitHubApiSandboxCreateInput,\n ) => Promise<TrustedGitHubApiSandbox>,\n input: {\n repository: RepositorySlug;\n action: VercelManagedGitHubApiAction;\n method: \"GET\" | \"POST\";\n path: string;\n body?: unknown;\n authorize(): Promise<void>;\n },\n): Promise<unknown> {\n const sandbox = await createSandbox(createInput(input.repository, input.action));\n try {\n await input.authorize();\n const result = await sandbox.runCommand({\n cmd: \"node\",\n args: [\n \"--input-type=module\",\n \"--eval\",\n githubRequestScript,\n JSON.stringify({\n method: input.method,\n url: `https://api.github.com/repos/${input.repository}${input.path}`,\n ...(input.body === undefined ? {} : { body: input.body }),\n }),\n ],\n timeoutMs: 30_000,\n });\n const stderr = (await result.stderr()).trim();\n if (result.exitCode !== 0) {\n throw new Error(`Managed GitHub API operation failed (${result.exitCode}): ${stderr}`);\n }\n const response = sandboxResponseSchema.parse(JSON.parse((await result.stdout()).trim()));\n if (response.status < 200 || response.status >= 300) {\n const message = z.object({ message: z.string() }).safeParse(response.body);\n throw new VercelManagedGitHubApiError(\n response.status,\n message.success ? message.data.message : \"Unexpected response\",\n );\n }\n return response.body;\n } finally {\n await sandbox.stop();\n }\n}\n\nasync function sandboxRequest(\n sandbox: TrustedGitHubApiSandbox,\n input: {\n repository: RepositorySlug;\n method: \"GET\" | \"POST\";\n path: string;\n body?: unknown;\n },\n): Promise<unknown> {\n const result = await sandbox.runCommand({\n cmd: \"node\",\n args: [\n \"--input-type=module\",\n \"--eval\",\n githubRequestScript,\n JSON.stringify({\n method: input.method,\n url: `https://api.github.com/repos/${input.repository}${input.path}`,\n ...(input.body === undefined ? {} : { body: input.body }),\n }),\n ],\n timeoutMs: 30_000,\n });\n const stderr = (await result.stderr()).trim();\n if (result.exitCode !== 0) {\n throw new Error(`Managed GitHub API operation failed (${result.exitCode}): ${stderr}`);\n }\n const response = sandboxResponseSchema.parse(JSON.parse((await result.stdout()).trim()));\n if (response.status < 200 || response.status >= 300) {\n const message = z.object({ message: z.string() }).safeParse(response.body);\n throw new VercelManagedGitHubApiError(\n response.status,\n message.success ? message.data.message : \"Unexpected response\",\n );\n }\n return response.body;\n}\n\n/** Create repository-scoped GitHub API operations backed by managed Sandbox credentials. */\nexport function createVercelManagedGitHubApi(\n options: VercelManagedGitHubApiOptions = {},\n): VercelManagedGitHubApi {\n const createSandbox = options.createSandbox ?? createManagedSandbox;\n return {\n async readIssue(input) {\n const repository = repositorySlugSchema.parse(input.repository.toLowerCase());\n if (!Number.isSafeInteger(input.issueNumber) || input.issueNumber < 1) {\n throw new Error(\"Invalid GitHub issue number\");\n }\n const issue = issueSchema.parse(\n await request(createSandbox, {\n repository,\n action: \"github:issues:read\",\n method: \"GET\",\n path: `/issues/${input.issueNumber}`,\n authorize: input.authorize,\n }),\n );\n return {\n title: issue.title,\n body: issue.body,\n url: issue.html_url,\n pullRequest: issue.pull_request !== undefined,\n };\n },\n async labelPullRequest(input) {\n const repository = repositorySlugSchema.parse(input.repository.toLowerCase());\n if (!Number.isSafeInteger(input.pullRequestNumber) || input.pullRequestNumber < 1) {\n throw new Error(\"Invalid GitHub pull request number\");\n }\n const label = labelInputSchema.parse(input);\n const sandbox = await createSandbox(createInput(repository, \"github:labels:write\"));\n try {\n const authorizedRequest = async (\n request: Omit<Parameters<typeof sandboxRequest>[1], \"repository\">,\n ) => {\n await input.authorize();\n return sandboxRequest(sandbox, { repository, ...request });\n };\n const labelPath = `/labels/${encodeURIComponent(label.name)}`;\n const read = async () => {\n const existing = labelSchema.parse(\n await authorizedRequest({ method: \"GET\", path: labelPath }),\n );\n if (existing.name.toLowerCase() !== label.name.toLowerCase()) {\n throw new Error(\"GitHub returned a different repository label\");\n }\n };\n try {\n await read();\n } catch (error) {\n if (!(error instanceof VercelManagedGitHubApiError) || error.status !== 404) throw error;\n try {\n await authorizedRequest({ method: \"POST\", path: \"/labels\", body: label });\n } catch (creationError) {\n if (\n !(creationError instanceof VercelManagedGitHubApiError) ||\n creationError.status !== 422\n ) {\n throw creationError;\n }\n await read();\n }\n }\n await authorizedRequest({\n method: \"POST\",\n path: `/issues/${input.pullRequestNumber}/labels`,\n body: { labels: [label.name] },\n });\n } finally {\n await sandbox.stop();\n }\n },\n async createPullRequest(input) {\n const repository = repositorySlugSchema.parse(input.repository.toLowerCase());\n const head = publicationBranchSchema.parse(input.head);\n const base = publicationBaseBranchSchema.parse(input.base);\n const title = publicationTitleSchema.parse(input.title);\n const body = publicationBodySchema.parse(input.body);\n const pull = pullRequestSchema.parse(\n await request(createSandbox, {\n repository,\n action: \"github:pull-request:create\",\n method: \"POST\",\n path: \"/pulls\",\n body: {\n title,\n body,\n head,\n base,\n draft: input.draft,\n },\n authorize: input.authorize,\n }),\n );\n return {\n pullRequestNumber: pull.number,\n pullRequestUrl: pull.html_url,\n draft: pull.draft,\n };\n },\n async publishPullRequest(input) {\n const repository = repositorySlugSchema.parse(input.repository.toLowerCase());\n if (!options.commitIdentity) throw new Error(\"Managed publication requires commit identity\");\n if (!/^[a-f0-9]{40}$/u.test(input.baseCommit) || input.commitMessage.trim() === \"\") {\n throw new Error(\"Invalid managed GitHub publication\");\n }\n const publicationTree = publicationTreeSchema.parse(input.tree);\n const branch = publicationBranchSchema.parse(input.branch);\n const baseBranch = publicationBaseBranchSchema.parse(input.baseBranch);\n const title = publicationTitleSchema.parse(input.title);\n const body = publicationBodySchema.parse(input.body);\n const commitMessage = publicationCommitMessageSchema.parse(\n `${input.commitMessage}\\n\\nCo-authored-by: ${options.commitIdentity.name} <${options.commitIdentity.email}>`,\n );\n const sandbox = await createSandbox(\n createPublicationInput(repository, options.commitIdentity),\n );\n try {\n const authorizedRequest = async (\n request: Omit<Parameters<typeof sandboxRequest>[1], \"repository\">,\n ) => {\n await input.authorize();\n return sandboxRequest(sandbox, { repository, ...request });\n };\n const base = commitSchema.parse(\n await authorizedRequest({\n method: \"GET\",\n path: `/git/commits/${input.baseCommit}`,\n }),\n );\n const tree = treeSchema.parse(\n await authorizedRequest({\n method: \"POST\",\n path: \"/git/trees\",\n body: { base_tree: base.tree.sha, tree: publicationTree },\n }),\n );\n const pullPath = `/pulls?${new URLSearchParams({\n state: \"all\",\n head: `${repository.split(\"/\")[0]}:${branch}`,\n per_page: \"100\",\n })}`;\n const pulls = async () =>\n z\n .array(publicationPullSchema)\n .parse(await authorizedRequest({ method: \"GET\", path: pullPath }));\n const result = (pull: z.infer<typeof pullRequestSchema>, commitSha: string) => ({\n commitSha,\n pullRequestNumber: pull.number,\n pullRequestUrl: pull.html_url,\n draft: pull.draft,\n });\n const existingPull = (await pulls()).find((pull) => pull.head.ref === branch);\n const refPath = `/git/ref/heads/${branch.split(\"/\").map(encodeURIComponent).join(\"/\")}`;\n let existingRef: z.infer<typeof refSchema> | null;\n try {\n existingRef = refSchema.parse(await authorizedRequest({ method: \"GET\", path: refPath }));\n } catch (error) {\n if (!(error instanceof VercelManagedGitHubApiError) || error.status !== 404) throw error;\n existingRef = null;\n }\n let commitSha = existingRef?.object.sha;\n if (existingPull) {\n if (existingPull.state !== \"open\") {\n throw new Error(\"Managed publication pull request is closed\");\n }\n if (commitSha !== existingPull.head.sha) {\n throw new Error(\"Managed publication pull request head differs from its branch\");\n }\n const existingCommit = commitSchema.parse(\n await authorizedRequest({\n method: \"GET\",\n path: `/git/commits/${existingPull.head.sha}`,\n }),\n );\n if (\n existingCommit.tree.sha !== tree.sha ||\n existingCommit.parents.length !== 1 ||\n existingCommit.parents[0]?.sha !== input.baseCommit\n ) {\n throw new Error(\"Managed publication pull request contains different changes\");\n }\n return result(existingPull, existingPull.head.sha);\n }\n if (commitSha) {\n const existingCommit = commitSchema.parse(\n await authorizedRequest({\n method: \"GET\",\n path: `/git/commits/${commitSha}`,\n }),\n );\n if (\n existingCommit.tree.sha !== tree.sha ||\n existingCommit.parents.length !== 1 ||\n existingCommit.parents[0]?.sha !== input.baseCommit\n ) {\n throw new Error(\"Managed publication branch contains different changes\");\n }\n } else {\n const commit = commitSchema.parse(\n await authorizedRequest({\n method: \"POST\",\n path: \"/git/commits\",\n body: {\n message: commitMessage,\n tree: tree.sha,\n parents: [input.baseCommit],\n },\n }),\n );\n commitSha = commit.sha;\n try {\n await authorizedRequest({\n method: \"POST\",\n path: \"/git/refs\",\n body: { ref: `refs/heads/${branch}`, sha: commitSha },\n });\n } catch (error) {\n const reconciled = refSchema.parse(\n await authorizedRequest({ method: \"GET\", path: refPath }),\n );\n if (reconciled.object.sha !== commitSha) throw error;\n }\n }\n let pull: z.infer<typeof pullRequestSchema>;\n try {\n pull = pullRequestSchema.parse(\n await authorizedRequest({\n method: \"POST\",\n path: \"/pulls\",\n body: {\n title,\n body,\n head: branch,\n base: baseBranch,\n draft: input.draft,\n },\n }),\n );\n } catch (error) {\n const reconciled = (await pulls()).find((candidate) => candidate.head.ref === branch);\n if (!reconciled || reconciled.state !== \"open\" || reconciled.head.sha !== commitSha) {\n throw error;\n }\n pull = reconciled;\n }\n return result(pull, commitSha);\n } finally {\n await sandbox.stop();\n }\n },\n };\n}\n"],"mappings":";;;;;AA2HA,IAAa,8BAAb,cAAiD,MAAM;CAE1C;CADX,YACE,QACA,SACA;EACA,MAAM,8BAA8B,OAAO,KAAK,SAAS;EAHhD,KAAA,SAAA;EAIT,KAAK,OAAO;CACd;AACF;AAEA,MAAM,wB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AAM;MACN,MAAM;OACJ;OACA;OACA,MAAM;OACN,MAAM;OACN,OAAO,MAAM;MACf;KACF,CAAC,CACH;IACF,SAAS,OAAO;KACd,MAAM,cAAc,MAAM,MAAM,EAAA,CAAG,MAAM,cAAc,UAAU,KAAK,QAAQ,MAAM;KACpF,IAAI,CAAC,cAAc,WAAW,UAAU,UAAU,WAAW,KAAK,QAAQ,WACxE,MAAM;KAER,OAAO;IACT;IACA,OAAO,OAAO,MAAM,SAAS;GAC/B,UAAU;IACR,MAAM,QAAQ,KAAK;GACrB;EACF;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vercel/factory",
3
- "version": "0.0.20",
3
+ "version": "0.0.21",
4
4
  "description": "Schema, state machines, and kernel primitives for Agent Factory.",
5
5
  "homepage": "https://github.com/vercel-labs/agent-factory/tree/main/packages/factory",
6
6
  "bugs": "https://github.com/vercel-labs/agent-factory/issues",