import {z} from 'zod' export type AdapterType = 'github' | 'slack' | 'uploaded_file'; export type GitHubSourceSelection = {repo: string, branch: string}; export type SlackSourceSelection = {slack_team_id: string, channel_id: string}; export type SourceVisibility = 'private' | 'public'; export type UploadedFileSourceSelection = {file_id: string, visibility?: SourceVisibility | undefined}; export type ConnectedSourceSelection = {adapter: AdapterType, selection: GitHubSourceSelection | SlackSourceSelection | UploadedFileSourceSelection}; export type SessionSpan = {firstTs: string, lastTs: string, wallClockMs: number, activeMs: number}; export type TokenUsage = {inputUncached: number, inputCacheCreate: number, inputCacheRead: number, output: number, total: number}; export type ScottPushPayloadTotals = {sessions: number, apiCalls: number, humanMessages: number, usage: TokenUsage, cacheBreaksCount: number, subagentCalls: number, subagentTokens: number}; export type PromptContextTurn = {text: string, ts?: (string | null) | undefined, apiCalls: number, here: boolean}; export type PromptSummary = {promptKey: string, ts: string, slashCommand?: (string | null) | undefined, text: string, apiCalls: number, subagentCalls: number, usage: TokenUsage, context: Array}; export type SubagentSummary = {agentId: string, agentType: string, parentPromptKey?: (string | null) | undefined, span: SessionSpan, apiCalls: number, usage: TokenUsage}; export type CacheBreak = {ts: string, uncached: number, total: number, promptKey?: (string | null) | undefined, kind: 'main' | 'subagent', agentType?: (string | null) | undefined}; export type ScottPushPayload = {project: string, sessionId: string, cwd: string, schemaVersion: number, generatedAt: string, span: SessionSpan, totals: ScottPushPayloadTotals, prompts?: Array | undefined, subagents?: Array | undefined, cacheBreaks?: Array | undefined}; export type CanonicalMessageSpec = {role: 'user' | 'assistant', content: string, fidelity?: ('verbatim' | 'paraphrased' | 'summarized' | null) | undefined, reconstructed?: (boolean | null) | undefined}; export type ScottPushSpec = {name: string, description?: (string | null) | undefined, source_kind?: string | undefined, source_id: string, captured_by_client?: (string | null) | undefined, originating_agent?: (string | null) | undefined, git_remote?: (string | null) | undefined, git_branch?: (string | null) | undefined, git_head_sha?: (string | null) | undefined, git_dirty?: (boolean | null) | undefined, payload: ScottPushPayload, messages?: Array | undefined, intent?: (string | null) | undefined, synthesize?: boolean | undefined, transcript_provenance?: ('verbatim' | 'reflected' | null) | undefined}; export type CreateWorkspaceRequest = {id?: (string | null) | undefined, name: string, description?: (string | null) | undefined, model?: (string | null) | undefined, system_prompt?: (string | null) | undefined, initial_doc_content?: string | undefined, initial_doc_label?: string | undefined, use_local_sandbox?: boolean | undefined, connected_sources?: (Array | null) | undefined, scott_push?: (ScottPushSpec | null) | undefined}; export type CreateApiAgentLoopWorkspacesArgs = {body: CreateWorkspaceRequest}; export type CreateApiAgentLoopWorkspacesOptions = {baseUrl: string, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const createWorkspaceResponse = z.object({workspace_id: z.string(), initial_turn_id: z.string().nullable().optional(), final_turn_id: z.string().nullable().optional(), planspace_url: z.string()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Create Workspace * * POST /agent-loop/workspaces */ export const createApiAgentLoopWorkspaces = async (args: CreateApiAgentLoopWorkspacesArgs, options: CreateApiAgentLoopWorkspacesOptions) => { const {baseUrl, fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/agent-loop/workspaces${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createWorkspaceResponse, await res.json()) };