@geoffai/geoff 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,318 @@
1
+ export { A as AgentsClient, F as FilesClient, e as MCPClient, M as MagmaClient, d as MagmaClientConfig, P as PointsClient, p as SkillsClient, S as SocialClient, T as TaskNetworkClient, a as TaskNetworkConfig, U as UserClient, W as WidgetsClient, j as agentsClient, i as createAgentsClient, n as createFilesClient, f as createMCPClient, b as createMagmaClient, v as createPointsClient, q as createSkillsClient, h as createSocialClient, c as createTaskNetworkClient, l as createUserClient, k as createWidgetsClient, o as filesClient, m as magmaClient, g as mcpClient, x as pointsClient, r as skillsClient, s as socialClient, t as taskNetworkClient, u as userClient, w as widgetsClient } from './points-BXIt899Y.js';
2
+ import { F as CoderClientConfig, w as CoderSandboxCreateInput, a as CoderSession, c as CoderExecuteRequest, e as CoderExecuteResponse, g as CoderStreamEvent, l as CoderTool, n as CoderToolResult, p as CoderFileContent, q as CoderFileWriteInput, o as CoderFileInfo, r as CoderSearchResult, s as CoderDiffInput, u as CoderCommandInput, t as CoderCommandResult, v as CoderSandbox, x as CoderSandboxExecInput, y as CoderSandboxExecResult } from './coder-BwKJFaCZ.js';
3
+ export { b as CoderMetrics, d as CoderSandboxConfig, C as CoderSessionStatus, f as CoderStreamEventType } from './coder-BwKJFaCZ.js';
4
+ import { T as TaskType, b as TaskState, a as TaskStatus } from './points-CGAg3YZi.js';
5
+ export { am as ActionProof, au as AddPointsInput, A as Agent, r as AgentCreateInput, n as AgentExecuteRequest, o as AgentExecuteResponse, t as AgentFromPromptInput, q as AgentResponse, j as AgentTrigger, s as AgentUpdateInput, k as AgentWorkflow, m as AgentWorkflowEdge, l as AgentWorkflowNode, u as AgentsClientConfig, p as AgentsListResponse, e as ChatCompletionChunk, C as ChatCompletionRequest, f as ChatCompletionResponse, K as CommentResponse, H as CommentsResponse, ah as ContextDomain, aB as ContextResponse, aA as ContextsListResponse, as as CreateContextInput, at as CreateDelegationInput, ar as CreateDomainInput, N as CreatePostInput, O as CreatePostResponse, aj as Delegation, an as DelegationChainLink, ax as DelegationFilters, aD as DelegationResponse, ak as DelegationScope, aC as DelegationsListResponse, az as DomainResponse, ay as DomainsListResponse, G as FeedResponse, a5 as FileUploadResponse, a6 as FilesClientConfig, aw as HistoryFilters, aG as HistoryResponse, h as ImaginationCharacter, i as ImaginationMetadata, I as ImaginationSource, aH as InitNetworkResponse, L as LikeCheckResponse, J as LikeResponse, y as MCPContent, x as MCPMessage, w as MCPSession, v as MCPSessionConfig, z as MCPToolResult, g as MagmaFile, B as MediaType, M as Message, aI as PaymentRequiredResponse, aq as PointBalance, ai as PointContext, al as PointRecord, aE as PointRecordResponse, ao as PointSpend, aF as PointSpendResponse, aJ as PointsClientConfig, P as PostResponse, Q as ProfileResponse, R as RemixesResponse, a7 as Skill, ab as SkillCreateInput, aa as SkillResponse, ac as SkillUpdateInput, ad as SkillsClientConfig, a9 as SkillsListResponse, S as SocialAuthor, U as SocialClientConfig, E as SocialComment, D as SocialPost, F as SocialRemix, ap as SpendDestination, av as SpendPointsInput, c as TaskPayload, d as TaskResponse, a4 as UserClientConfig, a1 as UserProfile, a3 as UserProfileResponse, a2 as UserProfileUpdateInput, V as Widget, Z as WidgetCreateInput, Y as WidgetResponse, $ as WidgetSystemPromptResponse, _ as WidgetUpdateInput, a0 as WidgetsClientConfig, X as WidgetsListResponse, W as WorkflowData } from './points-CGAg3YZi.js';
6
+ export { ArtifactToolCall, ArtifactToolResult, ComponentStreamAdapter, DataStreamWriter, SSEEvent, SSEWriter, createComponentStreamAdapter, createSSEResponse, createSSEWriter, extractToolResults, hasToolCalls, parseSSEStream } from './streaming/index.js';
7
+ export { C as CRUDRouteHandlers, F as ForwarderConfig, R as RequestOptions, u as RouteHandler, t as RouteHandlerConfig, d as createAgentDetailRoutes, e as createAgentExecuteRoute, b as createAgentRoutes, g as createAgentToggleRoutes, s as createCoderExecRoutes, o as createCoderExecuteRoute, q as createCoderFilesRoutes, r as createCoderSandboxRoutes, n as createCoderSessionDetailRoutes, m as createCoderSessionRoutes, p as createCoderToolsRoutes, l as createImaginationRoutes, c as createProxyHandler, i as createSkillDetailRoutes, h as createSkillRoutes, k as createWidgetDetailRoutes, j as createWidgetRoutes, a as forwardJSON, f as forwardRequest } from './index-fVOkaOIE.js';
8
+
9
+ /**
10
+ * Coder Client
11
+ * Client for interacting with the GeoffCoder AI coding agent API
12
+ */
13
+
14
+ declare class CoderClient {
15
+ private baseUrl;
16
+ private apiKey?;
17
+ private timeout;
18
+ private defaultModel;
19
+ private defaultMaxIterations;
20
+ constructor(config?: CoderClientConfig);
21
+ private get coderUrl();
22
+ private get headers();
23
+ /**
24
+ * Create a new coder session
25
+ */
26
+ createSession(workingDirectory: string, sandboxConfig?: CoderSandboxCreateInput): Promise<CoderSession>;
27
+ /**
28
+ * Get a session by ID
29
+ */
30
+ getSession(sessionId: string): Promise<CoderSession>;
31
+ /**
32
+ * List all sessions
33
+ */
34
+ listSessions(options?: {
35
+ status?: string;
36
+ limit?: number;
37
+ }): Promise<CoderSession[]>;
38
+ /**
39
+ * Abort a running session
40
+ */
41
+ abortSession(sessionId: string): Promise<CoderSession>;
42
+ /**
43
+ * Execute a coder prompt (non-streaming)
44
+ */
45
+ execute(request: CoderExecuteRequest): Promise<CoderExecuteResponse>;
46
+ /**
47
+ * Execute a coder prompt with streaming
48
+ */
49
+ executeStream(request: CoderExecuteRequest): AsyncGenerator<CoderStreamEvent, void, unknown>;
50
+ /**
51
+ * Get available coder tools
52
+ */
53
+ getTools(): Promise<CoderTool[]>;
54
+ /**
55
+ * Execute a specific tool directly
56
+ */
57
+ callTool(toolName: string, args: Record<string, unknown>, options?: {
58
+ sessionId?: string;
59
+ sandboxId?: string;
60
+ }): Promise<CoderToolResult>;
61
+ /**
62
+ * Read a file
63
+ */
64
+ readFile(path: string, options?: {
65
+ sessionId?: string;
66
+ sandboxId?: string;
67
+ }): Promise<CoderFileContent>;
68
+ /**
69
+ * Write a file
70
+ */
71
+ writeFile(input: CoderFileWriteInput, options?: {
72
+ sessionId?: string;
73
+ sandboxId?: string;
74
+ }): Promise<{
75
+ success: boolean;
76
+ path: string;
77
+ }>;
78
+ /**
79
+ * List files in a directory
80
+ */
81
+ listFiles(path: string, options?: {
82
+ recursive?: boolean;
83
+ maxDepth?: number;
84
+ sessionId?: string;
85
+ sandboxId?: string;
86
+ }): Promise<CoderFileInfo[]>;
87
+ /**
88
+ * Search for patterns in files
89
+ */
90
+ searchFiles(pattern: string, options?: {
91
+ path?: string;
92
+ filePattern?: string;
93
+ sessionId?: string;
94
+ sandboxId?: string;
95
+ }): Promise<CoderSearchResult[]>;
96
+ /**
97
+ * Apply a diff to a file
98
+ */
99
+ applyDiff(input: CoderDiffInput, options?: {
100
+ sessionId?: string;
101
+ sandboxId?: string;
102
+ }): Promise<{
103
+ success: boolean;
104
+ changes: number;
105
+ }>;
106
+ /**
107
+ * Execute a shell command
108
+ */
109
+ executeCommand(input: CoderCommandInput, options?: {
110
+ sessionId?: string;
111
+ sandboxId?: string;
112
+ }): Promise<CoderCommandResult>;
113
+ /**
114
+ * Execute a command with streaming output
115
+ */
116
+ executeCommandStream(input: CoderCommandInput, options?: {
117
+ sessionId?: string;
118
+ sandboxId?: string;
119
+ }): AsyncGenerator<{
120
+ type: 'stdout' | 'stderr' | 'exit';
121
+ content: string;
122
+ exitCode?: number;
123
+ }, void, unknown>;
124
+ /**
125
+ * Create a new sandbox
126
+ */
127
+ createSandbox(input?: CoderSandboxCreateInput): Promise<CoderSandbox>;
128
+ /**
129
+ * Get sandbox status
130
+ */
131
+ getSandbox(sandboxId: string): Promise<CoderSandbox>;
132
+ /**
133
+ * Execute code in a sandbox
134
+ */
135
+ sandboxExec(sandboxId: string, input: CoderSandboxExecInput): Promise<CoderSandboxExecResult>;
136
+ /**
137
+ * Destroy a sandbox
138
+ */
139
+ destroySandbox(sandboxId: string): Promise<{
140
+ success: boolean;
141
+ }>;
142
+ }
143
+ /**
144
+ * Create a CoderClient instance
145
+ */
146
+ declare function createCoderClient(config?: CoderClientConfig): CoderClient;
147
+ /**
148
+ * Default coder client instance
149
+ */
150
+ declare const coderClient: CoderClient;
151
+
152
+ /**
153
+ * TaskManager - Redis-backed task state management
154
+ *
155
+ * Manages task lifecycle for long-running operations with real-time updates
156
+ */
157
+
158
+ interface RedisClientLike {
159
+ hSet(key: string, value: Record<string, string>): Promise<number>;
160
+ hGetAll(key: string): Promise<Record<string, string>>;
161
+ expire(key: string, seconds: number): Promise<boolean>;
162
+ sAdd(key: string, ...members: string[]): Promise<number>;
163
+ sMembers(key: string): Promise<string[]>;
164
+ sRem(key: string, ...members: string[]): Promise<number>;
165
+ del(key: string): Promise<number>;
166
+ publish(channel: string, message: string): Promise<number>;
167
+ subscribe(channel: string, callback: (message: string) => void): Promise<void>;
168
+ unsubscribe(channel: string): Promise<void>;
169
+ }
170
+ interface TaskManagerConfig {
171
+ redis?: RedisClientLike;
172
+ getRedisClient?: () => Promise<RedisClientLike>;
173
+ taskTTL?: number;
174
+ }
175
+ declare class TaskManager {
176
+ private redis?;
177
+ private getRedisClient?;
178
+ private taskTTL;
179
+ constructor(config?: TaskManagerConfig);
180
+ /**
181
+ * Get Redis client (lazily initialized)
182
+ */
183
+ private getClient;
184
+ /**
185
+ * Create a new task and return its ID
186
+ */
187
+ createTask(chatId: string, messageId: string, type: TaskType, initialMessage?: string): Promise<string>;
188
+ /**
189
+ * Update task progress
190
+ */
191
+ updateProgress(taskId: string, progress: number, message: string): Promise<void>;
192
+ /**
193
+ * Mark task as complete with result
194
+ */
195
+ complete(taskId: string, result: unknown): Promise<void>;
196
+ /**
197
+ * Mark task as failed
198
+ */
199
+ fail(taskId: string, error: string): Promise<void>;
200
+ /**
201
+ * Get task by ID
202
+ */
203
+ getTask(taskId: string): Promise<TaskState | null>;
204
+ /**
205
+ * Get all tasks for a chat
206
+ */
207
+ getTasksForChat(chatId: string): Promise<TaskState[]>;
208
+ /**
209
+ * Get pending/generating tasks for a chat
210
+ */
211
+ getPendingTasksForChat(chatId: string): Promise<TaskState[]>;
212
+ /**
213
+ * Delete a task
214
+ */
215
+ deleteTask(taskId: string): Promise<void>;
216
+ /**
217
+ * Clean up old completed/failed tasks for a chat
218
+ */
219
+ cleanupOldTasks(chatId: string, maxAge?: number): Promise<void>;
220
+ /**
221
+ * Subscribe to task progress updates
222
+ */
223
+ subscribeToTask(taskId: string, callback: (update: {
224
+ taskId: string;
225
+ status: TaskStatus;
226
+ progress?: number;
227
+ message?: string;
228
+ result?: unknown;
229
+ error?: string;
230
+ }) => void): Promise<() => Promise<void>>;
231
+ private taskToRedis;
232
+ private redisToTask;
233
+ }
234
+ /**
235
+ * Factory function to create a TaskManager
236
+ */
237
+ declare function createTaskManager(config?: TaskManagerConfig): TaskManager;
238
+
239
+ /**
240
+ * Error handling utilities for the Geoff SDK
241
+ */
242
+ type ErrorType = 'bad_request' | 'unauthorized' | 'forbidden' | 'not_found' | 'rate_limit' | 'offline' | 'internal' | 'payment_required';
243
+ type Surface = 'chat' | 'auth' | 'api' | 'stream' | 'database' | 'history' | 'vote' | 'document' | 'suggestions' | 'task' | 'agent' | 'imagination';
244
+ type ErrorCode = `${ErrorType}:${Surface}`;
245
+ type ErrorVisibility = 'response' | 'log' | 'none';
246
+ declare const visibilityBySurface: Record<Surface, ErrorVisibility>;
247
+ declare class GeoffSDKError extends Error {
248
+ type: ErrorType;
249
+ surface: Surface;
250
+ statusCode: number;
251
+ metadata?: Record<string, unknown>;
252
+ constructor(errorCode: ErrorCode, cause?: string, metadata?: Record<string, unknown>);
253
+ toJSON(): {
254
+ metadata?: Record<string, unknown> | undefined;
255
+ code: string;
256
+ message: string;
257
+ cause: unknown;
258
+ statusCode: number;
259
+ };
260
+ toResponse(): Response;
261
+ }
262
+ declare function getMessageByErrorCode(errorCode: ErrorCode): string;
263
+
264
+ /**
265
+ * SDK Constants
266
+ */
267
+ /** GLayer network URL (primary) */
268
+ declare const DEFAULT_GLAYER_NETWORK_URL = "http://localhost:3000";
269
+ /** @deprecated Use DEFAULT_GLAYER_NETWORK_URL */
270
+ declare const DEFAULT_TASK_NETWORK_URL = "http://localhost:3000";
271
+ /** @deprecated Use DEFAULT_GLAYER_NETWORK_URL */
272
+ declare const DEFAULT_P2P_NETWORK_URL = "http://localhost:3000";
273
+ declare const DEFAULT_MAGMA_RPC_URL = "https://geoffnet.magma-rpc.com";
274
+ declare const TASK_PREFIX = "task:";
275
+ declare const CHAT_TASKS_PREFIX = "chat:tasks:";
276
+ declare const TASK_TTL: number;
277
+ declare const SSE_HEADERS: {
278
+ readonly 'Content-Type': "text/event-stream";
279
+ readonly 'Cache-Control': "no-cache";
280
+ readonly Connection: "keep-alive";
281
+ };
282
+ declare const JSON_HEADERS: {
283
+ readonly 'Content-Type': "application/json";
284
+ };
285
+
286
+ /**
287
+ * Utility helper functions
288
+ */
289
+ /**
290
+ * Generate a UUID v4
291
+ */
292
+ declare function generateUUID(): string;
293
+ /**
294
+ * Generate a CID-like hash from content
295
+ */
296
+ declare function generateCID(buffer: ArrayBuffer): Promise<string>;
297
+ /**
298
+ * Sleep for a specified duration
299
+ */
300
+ declare function sleep(ms: number): Promise<void>;
301
+ /**
302
+ * Retry a function with exponential backoff
303
+ */
304
+ declare function retry<T>(fn: () => Promise<T>, options?: {
305
+ maxAttempts?: number;
306
+ initialDelay?: number;
307
+ maxDelay?: number;
308
+ backoffFactor?: number;
309
+ }): Promise<T>;
310
+ /**
311
+ * Parse SSE data line
312
+ */
313
+ declare function parseSSELine(line: string): {
314
+ event?: string;
315
+ data?: string;
316
+ } | null;
317
+
318
+ export { CHAT_TASKS_PREFIX, CoderClient, CoderClientConfig, CoderCommandInput, CoderCommandResult, CoderDiffInput, CoderExecuteRequest, CoderExecuteResponse, CoderFileContent, CoderFileInfo, CoderFileWriteInput, CoderSandbox, CoderSandboxCreateInput, CoderSandboxExecInput, CoderSandboxExecResult, CoderSearchResult, CoderSession, CoderStreamEvent, CoderTool, CoderToolResult, DEFAULT_GLAYER_NETWORK_URL, DEFAULT_MAGMA_RPC_URL, DEFAULT_P2P_NETWORK_URL, DEFAULT_TASK_NETWORK_URL, type ErrorCode, type ErrorType, type ErrorVisibility, GeoffSDKError, JSON_HEADERS, type RedisClientLike, SSE_HEADERS, type Surface, TASK_PREFIX, TASK_TTL, TaskManager, type TaskManagerConfig, TaskState, TaskStatus, TaskType, coderClient, createCoderClient, createTaskManager, generateCID, generateUUID, getMessageByErrorCode, parseSSELine, retry, sleep, visibilityBySurface };
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ var h="http://localhost:3000",re=h,ne=h,C="https://geoffnet.magma-rpc.com",w="task:",b="chat:tasks:",L=86400*7,x={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"},p={"Content-Type":"application/json"};var T=class{baseUrl;apiKey;timeout;constructor(e={}){this.baseUrl=(e.baseUrl||h).replace(/\/$/,""),this.apiKey=e.apiKey,this.timeout=e.timeout||6e4;}async*chatCompletions(e){let t=e.messages.filter(n=>n.role==="user"),s=t[t.length-1]?.content||"",r=await this.submitTask({type:"ai-prompt",model:e.model,prompt:s,sessionId:e.sessionId,temperature:e.temperature,maxTokens:e.max_tokens,stream:true});yield*this.streamTaskResults(r,e.model);}async submitTask(e){let t=await fetch(`${this.baseUrl}/tasks`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}},body:JSON.stringify(e)});if(!t.ok){let r=await t.text();throw new Error(`Task submission failed: ${r}`)}return (await t.json()).taskId}async getTask(e){let t=await fetch(`${this.baseUrl}/tasks/${e}`,{headers:{...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}}});if(!t.ok)throw new Error(`Failed to get task: ${t.statusText}`);return t.json()}async*streamTaskResults(e,t){let s=await fetch(`${this.baseUrl}/tasks/${e}/stream`,{headers:{...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}}});if(!s.ok)throw new Error(`Stream failed: ${s.statusText}`);if(!s.body)throw new Error("Response body is null");let r=s.body.getReader(),n=new TextDecoder,o="",i="",d=Math.floor(Date.now()/1e3);try{for(;;){let{done:u,value:g}=await r.read();if(u){yield {id:e,object:"chat.completion.chunk",created:d,model:t,choices:[{index:0,delta:{},finish_reason:"stop"}]};break}o+=n.decode(g,{stream:!0});let m=o.split(`
2
+ `);o=m.pop()||"";for(let f of m)if(f.startsWith("data: "))try{let S=JSON.parse(f.slice(6));if(Array.isArray(S)&&S.length>0){let R=S[0].result||"";if(R&&R!==i){let H=R.substring(i.length);i=R,H&&(yield {id:e,object:"chat.completion.chunk",created:d,model:t,choices:[{index:0,delta:{role:"assistant",content:H},finish_reason:null}]});}}}catch{}}}finally{r.releaseLock();}}async*streamTaskRaw(e){let t=await fetch(`${this.baseUrl}/tasks/${e}/stream`,{headers:{...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}}});if(!t.ok)throw new Error(`Stream failed: ${t.statusText}`);if(!t.body)throw new Error("Response body is null");let s=t.body.getReader(),r=new TextDecoder,n="";try{for(;;){let{done:o,value:i}=await s.read();if(o)break;n+=r.decode(i,{stream:!0});let d=n.split(`
3
+ `);n=d.pop()||"";for(let u of d)if(u.startsWith("data: "))try{yield JSON.parse(u.slice(6));}catch{}}}finally{s.releaseLock();}}async healthCheck(){try{return (await fetch(`${this.baseUrl}/health`)).ok}catch{return false}}async getNode(){let e=await fetch(`${this.baseUrl}/node`);if(!e.ok)throw new Error(`Failed to get node info: ${e.statusText}`);return e.json()}};function W(a){return new T(a)}var oe=W();function q(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{let e=Math.random()*16|0;return (a==="x"?e:e&3|8).toString(16)})}async function M(a){let e=await crypto.subtle.digest("SHA-256",a);return `baf${Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("").substring(0,52)}`}function J(a){return new Promise(e=>setTimeout(e,a))}async function ae(a,e={}){let{maxAttempts:t=3,initialDelay:s=1e3,maxDelay:r=3e4,backoffFactor:n=2}=e,o,i=s;for(let d=1;d<=t;d++)try{return await a()}catch(u){if(o=u,d===t)break;await J(i),i=Math.min(i*n,r);}throw o}function ie(a){return !a||a.startsWith(":")?null:a.startsWith("event:")?{event:a.slice(6).trim()}:a.startsWith("data:")?{data:a.slice(5).trim()}:null}var P=class{baseUrl;localServerUrl;constructor(e={}){this.baseUrl=e.baseUrl||C,this.localServerUrl=e.localServerUrl||h;}async uploadFile(e){let t=await e.arrayBuffer(),s=await M(t),r=this.arrayBufferToBase64(t);return typeof localStorage<"u"&&localStorage.setItem(`file:${s}`,JSON.stringify({cid:s,name:e.name,type:e.type,size:e.size,data:r})),{cid:s,name:e.name,size:e.size,type:e.type,url:`data:${e.type};base64,${r}`}}async uploadText(e,t){let s=new Blob([e],{type:"text/plain"}),r=new File([s],t,{type:"text/plain"});return this.uploadFile(r)}async storeImagination(e){let t=e.createdBy||"anonymous",r=(await fetch(`${this.localServerUrl}/imaginations/${e.id}`)).ok,n={id:e.id,title:e.title,sources:e.sources,summary:e.summary,character:e.character,workflow:e.workflow,is_public:e.is_public||false,creator_mid:t};if(r){let o=await fetch(`${this.localServerUrl}/imaginations/${e.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(`Failed to update imagination: ${o.statusText}`);return typeof localStorage<"u"&&localStorage.setItem(`imagination:${e.id}`,e.id),e.id}else {let o=await fetch(`${this.localServerUrl}/imaginations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(`Failed to store imagination: ${o.statusText}`);let d=(await o.json()).imagination?.id||e.id;return typeof localStorage<"u"&&localStorage.setItem(`imagination:${d}`,d),d}}async getImagination(e){try{let t=await fetch(`${this.localServerUrl}/imaginations/${e}`);if(!t.ok)return null;let s=await t.json();return s.imagination?{id:s.imagination.id,title:s.imagination.title,createdAt:new Date(s.imagination.created_at).toISOString(),createdBy:s.imagination.creator_mid,sources:s.imagination.sources,summary:s.imagination.summary,character:s.imagination.character,workflow:s.imagination.workflow,is_public:s.imagination.is_public}:null}catch(t){return console.error("Failed to retrieve imagination:",t),null}}async getImaginationByCID(e){try{let t=await fetch(`${this.baseUrl}/files/${e}`);if(!t.ok)return null;let s=await t.json();return typeof localStorage<"u"&&localStorage.setItem(`imagination:${s.id}`,e),s}catch(t){return console.error("Failed to retrieve imagination by CID:",t),null}}async listImaginations(e){try{let t=e||"anonymous",s=await fetch(`${this.localServerUrl}/imaginations?creator_mid=${encodeURIComponent(t)}`);if(!s.ok)return console.warn("Failed to fetch imaginations from P2P, falling back to localStorage"),this.listImaginationsFromLocalStorage();let n=(await s.json()).imaginations.map(o=>({id:o.id,title:o.title,createdAt:new Date(o.created_at).toISOString(),createdBy:o.creator_mid,sources:o.sources,summary:o.summary,character:o.character,workflow:o.workflow,is_public:o.is_public}));return typeof localStorage<"u"&&n.forEach(o=>{localStorage.setItem(`imagination:${o.id}`,o.id);}),n}catch(t){return console.error("Failed to list imaginations:",t),this.listImaginationsFromLocalStorage()}}async listImaginationsFromLocalStorage(){if(typeof localStorage>"u")return [];let e=[];for(let t=0;t<localStorage.length;t++){let s=localStorage.key(t);if(s&&s.startsWith("imagination:")){let r=s.replace("imagination:",""),n=await this.getImagination(r);n&&e.push(n);}}return e}async getFile(e){try{let t=await fetch(`${this.baseUrl}/files/${e}`);return t.ok?await t.blob():null}catch(t){return console.error("Failed to retrieve file:",t),null}}arrayBufferToBase64(e){let t=new Uint8Array(e),s="";for(let r=0;r<t.length;r++)s+=String.fromCharCode(t[r]);return btoa(s)}};function G(a){return new P(a)}var ce=G();var k=class{baseUrl;timeout;sessions=new Map;constructor(e={}){this.baseUrl=e.baseUrl||"http://localhost:3006",this.timeout=e.timeout||3e4;}async createSession(e="default"){let t=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;try{let s={id:t,agentId:e,status:"active",createdAt:new Date};this.sessions.set(t,s);try{await fetch(`${this.baseUrl}/mcp/sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:t,agentId:e,clientInfo:{name:"geoffai-sdk",version:"0.1.0"}})});}catch{}return s}catch(s){throw new Error(`Failed to create MCP session: ${s}`)}}getSession(e){return this.sessions.get(e)}async closeSession(e){let t=this.sessions.get(e);if(t){t.status="closed";try{await fetch(`${this.baseUrl}/mcp/sessions/${e}`,{method:"DELETE"});}catch{}this.sessions.delete(e);}}async sendMessage(e,t){let s=this.sessions.get(e);if(!s||s.status!=="active")throw new Error("Invalid or inactive session");try{let r=await fetch(`${this.baseUrl}/mcp/sessions/${e}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:[{role:"user",content:{type:"text",text:t}}]})});if(!r.ok)throw new Error(`MCP request failed: ${r.statusText}`);return r.json()}catch(r){throw new Error(`Failed to send message: ${r}`)}}async callTool(e,t,s={}){let r=this.sessions.get(e);if(!r||r.status!=="active")throw new Error("Invalid or inactive session");try{let n=await fetch(`${this.baseUrl}/mcp/sessions/${e}/tools/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok)throw new Error(`Tool call failed: ${n.statusText}`);return n.json()}catch(n){throw new Error(`Failed to call tool: ${n}`)}}async listTools(e){let t=this.sessions.get(e);if(!t||t.status!=="active")throw new Error("Invalid or inactive session");try{let s=await fetch(`${this.baseUrl}/mcp/sessions/${e}/tools`);return s.ok?(await s.json()).tools||[]:[]}catch{return []}}getActiveSessions(){return Array.from(this.sessions.values()).filter(e=>e.status==="active")}async closeAllSessions(){let e=Array.from(this.sessions.keys());await Promise.all(e.map(t=>this.closeSession(t)));}};function K(a){return new k(a)}var de=K();var B={database:"log",chat:"response",auth:"response",stream:"response",api:"response",history:"response",vote:"response",document:"response",suggestions:"response",task:"response",agent:"response",imagination:"response"},c=class extends Error{type;surface;statusCode;metadata;constructor(e,t,s){super();let[r,n]=e.split(":");this.type=r,this.cause=t,this.surface=n,this.message=Y(e),this.statusCode=le(this.type),this.metadata=s;}toJSON(){return {code:`${this.type}:${this.surface}`,message:this.message,cause:this.cause,statusCode:this.statusCode,...this.metadata&&{metadata:this.metadata}}}toResponse(){let e=`${this.type}:${this.surface}`,t=B[this.surface],{message:s,cause:r,statusCode:n}=this;return t==="log"?(console.error({code:e,message:s,cause:r}),Response.json({code:"",message:"Something went wrong. Please try again later."},{status:n})):Response.json({code:e,message:s,cause:r},{status:n})}};function Y(a){if(a.includes("database"))return "An error occurred while executing a database query.";switch(a){case "bad_request:api":return "The request couldn't be processed. Please check your input and try again.";case "unauthorized:auth":return "You need to sign in before continuing.";case "forbidden:auth":return "Your account does not have access to this feature.";case "rate_limit:chat":return "You have exceeded your maximum number of messages for the day. Please try again later.";case "not_found:chat":return "The requested chat was not found.";case "forbidden:chat":return "This chat belongs to another user.";case "unauthorized:chat":return "You need to sign in to view this chat.";case "offline:chat":return "We're having trouble sending your message. Please check your internet connection.";case "not_found:task":return "The requested task was not found.";case "forbidden:task":return "You do not have access to this task.";case "not_found:agent":return "The requested agent was not found.";case "forbidden:agent":return "You do not have access to this agent.";case "not_found:imagination":return "The requested imagination was not found.";case "forbidden:imagination":return "You do not have access to this imagination.";case "not_found:document":return "The requested document was not found.";case "forbidden:document":return "This document belongs to another user.";case "unauthorized:document":return "You need to sign in to view this document.";case "bad_request:document":return "The request to create or update the document was invalid.";default:return "Something went wrong. Please try again later."}}function le(a){switch(a){case "bad_request":return 400;case "unauthorized":return 401;case "payment_required":return 402;case "forbidden":return 403;case "not_found":return 404;case "rate_limit":return 429;case "offline":return 503;case "internal":return 500;default:return 500}}var $=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||h;}get socialUrl(){return `${this.baseUrl}/social`}async getFeed(e={}){let{page:t=1,limit:s=10,mediaType:r}=e,n=new URLSearchParams({page:String(t),limit:String(s)});r&&n.set("media_type",r);let o=await fetch(`${this.socialUrl}/feed?${n}`);if(!o.ok)throw new c("bad_request:api",`Failed to fetch feed: ${o.statusText}`);return o.json()}async getPost(e){let t=await fetch(`${this.socialUrl}/posts/${e}`);if(!t.ok)throw new c(t.status===404?"not_found:api":"bad_request:api",`Failed to fetch post: ${t.statusText}`);return t.json()}async getComments(e){let t=await fetch(`${this.socialUrl}/posts/${e}/comments`);if(!t.ok)throw new c("bad_request:api",`Failed to fetch comments: ${t.statusText}`);return t.json()}async getRemixes(e){let t=await fetch(`${this.socialUrl}/posts/${e}/remixes`);if(!t.ok)throw new c("bad_request:api",`Failed to fetch remixes: ${t.statusText}`);return t.json()}async checkLike(e,t){let s=await fetch(`${this.socialUrl}/posts/${e}/likes/check?userMid=${encodeURIComponent(t)}`);if(!s.ok)throw new c("bad_request:api",`Failed to check like status: ${s.statusText}`);return s.json()}async likePost(e,t){let s=await fetch(`${this.socialUrl}/like`,{method:"POST",headers:p,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new c("bad_request:api",`Failed to like post: ${s.statusText}`);return s.json()}async unlikePost(e,t){let s=await fetch(`${this.socialUrl}/unlike`,{method:"POST",headers:p,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new c("bad_request:api",`Failed to unlike post: ${s.statusText}`);return s.json()}async addComment(e,t,s){let r=await fetch(`${this.socialUrl}/comment`,{method:"POST",headers:p,body:JSON.stringify({postId:e,userMid:t,content:s})});if(!r.ok)throw new c("bad_request:api",`Failed to add comment: ${r.statusText}`);return r.json()}async createPost(e){let t=await fetch(`${this.socialUrl}/post`,{method:"POST",headers:p,body:JSON.stringify({userMid:e.creatorMid,content:e.content,mediaUrl:e.mediaUrl,mediaType:e.mediaType,remixOf:e.remixOf})});if(!t.ok)throw new c("bad_request:api",`Failed to create post: ${t.statusText}`);return t.json()}async trackView(e,t){await fetch(`${this.socialUrl}/posts/${e}/view`,{method:"POST",headers:p,body:JSON.stringify({userMid:t})}).catch(()=>{});}async trackPlay(e,t){await fetch(`${this.socialUrl}/posts/${e}/play`,{method:"POST",headers:p,body:JSON.stringify({userMid:t})}).catch(()=>{});}async getProfile(e){try{let t=await fetch(`${this.socialUrl}/profile/${e}`);if(!t.ok){if(t.status===404)return null;throw new c("bad_request:api",`Failed to fetch profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof c)throw t;return null}}};function z(a={}){return new $(a)}var ue=z();var U=class{baseUrl;useCpxApi;constructor(e={}){this.baseUrl=e.baseUrl||h,this.useCpxApi=e.useCpxApi!==false;}get agentsUrl(){return this.useCpxApi?`${this.baseUrl}/cpx/agent/agents`:`${this.baseUrl}/agents`}async list(e={}){let t=new URLSearchParams;e.userMid&&t.set("userMid",e.userMid);let s=t.toString(),r=`${this.agentsUrl}${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new c("bad_request:api",`Failed to list agents: ${n.statusText}`);return n.json()}async get(e){let t=await fetch(`${this.agentsUrl}/${e}`);if(!t.ok)throw new c(t.status===404?"not_found:api":"bad_request:api",`Failed to get agent: ${t.statusText}`);return t.json()}async create(e){let t=await fetch(this.agentsUrl,{method:"POST",headers:p,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("bad_request:api",s.error||`Failed to create agent: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.agentsUrl}/${e}`,{method:"PUT",headers:p,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to update agent: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.agentsUrl}/${e}`,{method:"DELETE"});if(!t.ok)throw new c("bad_request:api",`Failed to delete agent: ${t.statusText}`);return t.json()}async enable(e){let t=await fetch(`${this.agentsUrl}/${e}/enable`,{method:"POST"});if(!t.ok)throw new c("bad_request:api",`Failed to enable agent: ${t.statusText}`);return t.json()}async disable(e){let t=await fetch(`${this.agentsUrl}/${e}/disable`,{method:"POST"});if(!t.ok)throw new c("bad_request:api",`Failed to disable agent: ${t.statusText}`);return t.json()}async execute(e,t={}){let s=await fetch(`${this.agentsUrl}/${e}/execute`,{method:"POST",headers:p,body:JSON.stringify(t)});if(!s.ok)throw new c("bad_request:api",`Failed to execute agent: ${s.statusText}`);return s.json()}async createFromPrompt(e){let t=await fetch(`${this.agentsUrl}/from-prompt`,{method:"POST",headers:p,body:JSON.stringify(e)});if(!t.ok)throw new c("bad_request:api",`Failed to generate agent from prompt: ${t.statusText}`);let s=await t.json();return this.create({...s,created_by:e.created_by})}};function V(a={}){return new U(a)}var pe=V();var E=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||h;}get widgetsUrl(){return `${this.baseUrl}/widgets`}async list(e={}){let t=new URLSearchParams;e.creatorMid?t.set("creator_mid",e.creatorMid):e.scope&&t.set("scope",e.scope);let s=t.toString(),r=`${this.widgetsUrl}${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new c("bad_request:api",`Failed to list widgets: ${n.statusText}`);return n.json()}async get(e){let t=await fetch(`${this.widgetsUrl}/${e}`);if(!t.ok)throw new c(t.status===404?"not_found:api":"bad_request:api",`Failed to get widget: ${t.statusText}`);return t.json()}async create(e){let t=await fetch(this.widgetsUrl,{method:"POST",headers:p,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("bad_request:api",s.error||`Failed to create widget: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.widgetsUrl}/${e}`,{method:"PUT",headers:p,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to update widget: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.widgetsUrl}/${e}`,{method:"DELETE"});if(!t.ok)throw new c("bad_request:api",`Failed to delete widget: ${t.statusText}`);return t.json()}async getSystemPrompt(){let e=await fetch(`${this.widgetsUrl}/system-prompt`);if(!e.ok)throw new c("bad_request:api",`Failed to get widget system prompt: ${e.statusText}`);return e.json()}async trackUsage(e){await fetch(`${this.widgetsUrl}/${e}/usage`,{method:"POST"}).catch(()=>{});}};function X(a={}){return new E(a)}var me=X();var I=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||h;}get userUrl(){return `${this.baseUrl}/user`}async getProfile(e){try{let t=await fetch(`${this.userUrl}/profile/${e}`);if(!t.ok){if(t.status===404)return null;throw new c("bad_request:api",`Failed to get user profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof c)throw t;return null}}async updateProfile(e,t){let s=await fetch(`${this.userUrl}/profile/${e}`,{method:"PUT",headers:p,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to update user profile: ${s.statusText}`)}return s.json()}};function Q(a={}){return new I(a)}var he=Q();var _=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||h;}get filesUrl(){return `${this.baseUrl}/files`}async upload(e,t){let s=new FormData;s.append("file",e,t);let r=await fetch(`${this.filesUrl}/upload`,{method:"POST",body:s});if(!r.ok)throw new c("bad_request:api",`Failed to upload file: ${r.statusText}`);return r.json()}async uploadFromUrl(e){let t=await fetch(`${this.filesUrl}/upload-url`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:e})});if(!t.ok)throw new c("bad_request:api",`Failed to upload file from URL: ${t.statusText}`);return t.json()}getFileUrl(e){return `${this.filesUrl}/${e}`}};function Z(a={}){return new _(a)}var ge=Z();var A=class{baseUrl;useCpxApi;constructor(e={}){this.baseUrl=e.baseUrl||C,this.useCpxApi=e.useCpxApi!==false;}get skillsUrl(){return this.useCpxApi?`${this.baseUrl}/cpx/agent/skills`:`${this.baseUrl}/skills`}async list(e){let t=new URLSearchParams;e?.precompiled?(t.set("precompiled","true"),e?.contentType&&t.set("content_type",e.contentType)):e?.contentType?t.set("content_type",e.contentType):e?.creatorMid?t.set("creator_mid",e.creatorMid):e?.scope&&e.scope!=="all"&&t.set("scope",e.scope);let s=t.toString()?`${this.skillsUrl}?${t.toString()}`:this.skillsUrl,r=await fetch(s);if(!r.ok)throw new Error(`Failed to list skills: ${r.statusText}`);return r.json()}async get(e){let t=await fetch(`${this.skillsUrl}/${e}`);if(!t.ok)throw new Error(`Skill not found: ${e}`);return t.json()}async create(e){let t=await fetch(this.skillsUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new Error(s.error||`Failed to create skill: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.skillsUrl}/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new Error(r.error||`Failed to update skill: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.skillsUrl}/${e}`,{method:"DELETE"});if(!t.ok){let s=await t.json().catch(()=>({}));throw new Error(s.error||`Failed to delete skill: ${t.statusText}`)}return t.json()}async trackUsage(e){try{await fetch(`${this.skillsUrl}/${e}/usage`,{method:"POST"});}catch{}}async verify(e){let t=await fetch(`${this.skillsUrl}/${e}/verify`);if(!t.ok)throw new Error(`Failed to verify skill: ${t.statusText}`);return t.json()}async rehash(e){let t=await fetch(`${this.skillsUrl}/${e}/rehash`,{method:"POST"});if(!t.ok)throw new Error(`Failed to rehash skill: ${t.statusText}`);return t.json()}async rehashAll(){let e=await fetch(`${this.skillsUrl}/rehash-all`,{method:"POST"});if(!e.ok)throw new Error(`Failed to rehash all skills: ${e.statusText}`);return e.json()}async getMap(e){let t=e?`?content_type=${e}`:"",s=await fetch(`${this.skillsUrl}/map${t}`);if(!s.ok)throw new Error(`Failed to get skill map: ${s.statusText}`);return s.json()}async getMapPrompt(e){let t=e?`?content_type=${e}`:"",s=await fetch(`${this.skillsUrl}/map/prompt${t}`);if(!s.ok)throw new Error(`Failed to get skill map prompt: ${s.statusText}`);return s.json()}async getNonCodeMap(){let e=await fetch(`${this.skillsUrl}/map/noncode`);if(!e.ok)throw new Error(`Failed to get non-code skill map: ${e.statusText}`);return e.json()}async getNonCodeSummary(){let e=await fetch(`${this.skillsUrl}/summary/noncode`);if(!e.ok)throw new Error(`Failed to get non-code skill summary: ${e.statusText}`);return e.json()}};function ee(a){return new A(a)}var fe=ee();var j=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||C;}get pointsUrl(){return `${this.baseUrl}/cpx/points`}async initNetworkDomain(){let e=await fetch(`${this.pointsUrl}/init`,{method:"POST",headers:p});if(!e.ok){let t=await e.json().catch(()=>({}));throw new c("bad_request:api",t.error||`Failed to initialize network domain: ${e.statusText}`)}return e.json()}async listDomains(){let e=await fetch(`${this.pointsUrl}/domains`);if(!e.ok)throw new c("bad_request:api",`Failed to list domains: ${e.statusText}`);return e.json()}async getDomain(e){let t=await fetch(`${this.pointsUrl}/domains/${e}`);if(t.status===404)return null;if(!t.ok)throw new c("bad_request:api",`Failed to get domain: ${t.statusText}`);return t.json()}async createDomain(e){let t=await fetch(`${this.pointsUrl}/domains`,{method:"POST",headers:p,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new c("payment_required:api",s.error,{paymentDetails:s.paymentDetails})}if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("bad_request:api",s.error||`Failed to create domain: ${t.statusText}`)}return t.json()}async listContexts(e){let t=e?`?domainId=${e}`:"",s=await fetch(`${this.pointsUrl}/contexts${t}`);if(!s.ok)throw new c("bad_request:api",`Failed to list contexts: ${s.statusText}`);return s.json()}async getContext(e){let t=await fetch(`${this.pointsUrl}/contexts/${e}`);if(t.status===404)return null;if(!t.ok)throw new c("bad_request:api",`Failed to get context: ${t.statusText}`);return t.json()}async createContext(e){let t=await fetch(`${this.pointsUrl}/contexts`,{method:"POST",headers:p,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new c("payment_required:api",s.error,{paymentDetails:s.paymentDetails})}if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("bad_request:api",s.error||`Failed to create context: ${t.statusText}`)}return t.json()}async listDelegations(e={}){let t=new URLSearchParams;e.domainId&&t.set("domainId",e.domainId),e.delegator&&t.set("delegator",e.delegator),e.delegate&&t.set("delegate",e.delegate),e.activeOnly&&t.set("activeOnly","true");let s=t.toString(),r=`${this.pointsUrl}/delegations${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new c("bad_request:api",`Failed to list delegations: ${n.statusText}`);return n.json()}async createDelegation(e){let t=await fetch(`${this.pointsUrl}/delegations`,{method:"POST",headers:p,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("bad_request:api",s.error||`Failed to create delegation: ${t.statusText}`)}return t.json()}async revokeDelegation(e){let t=await fetch(`${this.pointsUrl}/delegations/${e}`,{method:"DELETE"});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("bad_request:api",s.error||`Failed to revoke delegation: ${t.statusText}`)}return t.json()}async addPoints(e){let t=await fetch(`${this.pointsUrl}/add`,{method:"POST",headers:p,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("bad_request:api",s.error||`Failed to add points: ${t.statusText}`)}return t.json()}async spendPoints(e){let t=await fetch(`${this.pointsUrl}/spend`,{method:"POST",headers:p,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("bad_request:api",s.error||`Failed to spend points: ${t.statusText}`)}return t.json()}async getBalance(e,t={}){let s=new URLSearchParams;t.domainId&&s.set("domainId",t.domainId),t.contextId&&s.set("contextId",t.contextId);let r=s.toString(),n=`${this.pointsUrl}/balance/${e}${r?`?${r}`:""}`,o=await fetch(n);if(!o.ok)throw new c("bad_request:api",`Failed to get balance: ${o.statusText}`);return o.json()}async getHistory(e={}){let t=new URLSearchParams;e.mid&&t.set("mid",e.mid),e.domainId&&t.set("domainId",e.domainId),e.contextId&&t.set("contextId",e.contextId),e.periodStart&&t.set("periodStart",e.periodStart.toString()),e.periodEnd&&t.set("periodEnd",e.periodEnd.toString()),e.taskId&&t.set("taskId",e.taskId),e.limit&&t.set("limit",e.limit.toString()),e.offset&&t.set("offset",e.offset.toString());let s=t.toString(),r=`${this.pointsUrl}/history${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new c("bad_request:api",`Failed to get history: ${n.statusText}`);return n.json()}};function te(a={}){return new j(a)}var we=te();var v=class{baseUrl;apiKey;timeout;defaultModel;defaultMaxIterations;constructor(e={}){this.baseUrl=e.baseUrl||h,this.apiKey=e.apiKey,this.timeout=e.timeout||3e5,this.defaultModel=e.defaultModel||"qwen3-coder:30b",this.defaultMaxIterations=e.defaultMaxIterations||20;}get coderUrl(){return `${this.baseUrl}/coder`}get headers(){let e={...p};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}async createSession(e,t){let s=await fetch(`${this.coderUrl}/sessions`,{method:"POST",headers:this.headers,body:JSON.stringify({workingDirectory:e,sandbox:t})});if(!s.ok){let n=await s.json().catch(()=>({}));throw new c("bad_request:api",n.error||`Failed to create coder session: ${s.statusText}`)}return (await s.json()).session}async getSession(e){let t=await fetch(`${this.coderUrl}/sessions/${e}`,{headers:this.headers});if(!t.ok)throw new c(t.status===404?"not_found:api":"bad_request:api",`Failed to get coder session: ${t.statusText}`);return (await t.json()).session}async listSessions(e={}){let t=new URLSearchParams;e.status&&t.set("status",e.status),e.limit&&t.set("limit",e.limit.toString());let s=t.toString(),r=`${this.coderUrl}/sessions${s?`?${s}`:""}`,n=await fetch(r,{headers:this.headers});if(!n.ok)throw new c("bad_request:api",`Failed to list coder sessions: ${n.statusText}`);return (await n.json()).sessions}async abortSession(e){let t=await fetch(`${this.coderUrl}/sessions/${e}/abort`,{method:"POST",headers:this.headers});if(!t.ok)throw new c("bad_request:api",`Failed to abort coder session: ${t.statusText}`);return (await t.json()).session}async execute(e){let t={prompt:e.prompt,workingDirectory:e.workingDirectory,maxIterations:e.maxIterations||this.defaultMaxIterations,model:e.model||this.defaultModel,maxTokens:e.maxTokens,temperature:e.temperature,sessionId:e.sessionId,sandboxId:e.sandboxId,sandbox:e.sandbox,stream:false},s=await fetch(`${this.coderUrl}/execute`,{method:"POST",headers:this.headers,body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeout)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to execute coder: ${s.statusText}`)}return s.json()}async*executeStream(e){let t={prompt:e.prompt,workingDirectory:e.workingDirectory,maxIterations:e.maxIterations||this.defaultMaxIterations,model:e.model||this.defaultModel,maxTokens:e.maxTokens,temperature:e.temperature,sessionId:e.sessionId,sandboxId:e.sandboxId,sandbox:e.sandbox,stream:true},s=await fetch(`${this.coderUrl}/execute`,{method:"POST",headers:{...this.headers,Accept:"text/event-stream"},body:JSON.stringify(t)});if(!s.ok){let i=await s.json().catch(()=>({}));throw new c("bad_request:api",i.error||`Failed to execute coder stream: ${s.statusText}`)}let r=s.body?.getReader();if(!r)throw new c("bad_request:stream","No response body");let n=new TextDecoder,o="";try{for(;;){let{done:i,value:d}=await r.read();if(i)break;o+=n.decode(d,{stream:!0});let u=o.split(`
4
+ `);o=u.pop()||"";for(let g of u)if(g.startsWith("data: ")){let m=g.slice(6);if(m==="[DONE]")return;try{yield JSON.parse(m);}catch{}}}}finally{r.releaseLock();}}async getTools(){let e=await fetch(`${this.coderUrl}/tools`,{headers:this.headers});if(!e.ok)throw new c("bad_request:api",`Failed to get coder tools: ${e.statusText}`);return (await e.json()).tools}async callTool(e,t,s={}){let r=await fetch(`${this.coderUrl}/tools/${e}`,{method:"POST",headers:this.headers,body:JSON.stringify({arguments:t,sessionId:s.sessionId,sandboxId:s.sandboxId})});if(!r.ok){let n=await r.json().catch(()=>({}));throw new c("bad_request:api",n.error||`Failed to call tool ${e}: ${r.statusText}`)}return r.json()}async readFile(e,t={}){let s=new URLSearchParams({path:e});t.sessionId&&s.set("sessionId",t.sessionId),t.sandboxId&&s.set("sandboxId",t.sandboxId);let r=await fetch(`${this.coderUrl}/files/read?${s}`,{headers:this.headers});if(!r.ok)throw new c(r.status===404?"not_found:api":"bad_request:api",`Failed to read file: ${r.statusText}`);return r.json()}async writeFile(e,t={}){let s=await fetch(`${this.coderUrl}/files/write`,{method:"POST",headers:this.headers,body:JSON.stringify({...e,sessionId:t.sessionId,sandboxId:t.sandboxId})});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to write file: ${s.statusText}`)}return s.json()}async listFiles(e,t={}){let s=new URLSearchParams({path:e});t.recursive&&s.set("recursive","true"),t.maxDepth&&s.set("maxDepth",t.maxDepth.toString()),t.sessionId&&s.set("sessionId",t.sessionId),t.sandboxId&&s.set("sandboxId",t.sandboxId);let r=await fetch(`${this.coderUrl}/files/list?${s}`,{headers:this.headers});if(!r.ok)throw new c("bad_request:api",`Failed to list files: ${r.statusText}`);return (await r.json()).files}async searchFiles(e,t={}){let s=new URLSearchParams({pattern:e});t.path&&s.set("path",t.path),t.filePattern&&s.set("filePattern",t.filePattern),t.sessionId&&s.set("sessionId",t.sessionId),t.sandboxId&&s.set("sandboxId",t.sandboxId);let r=await fetch(`${this.coderUrl}/files/search?${s}`,{headers:this.headers});if(!r.ok)throw new c("bad_request:api",`Failed to search files: ${r.statusText}`);return (await r.json()).results}async applyDiff(e,t={}){let s=await fetch(`${this.coderUrl}/files/diff`,{method:"POST",headers:this.headers,body:JSON.stringify({...e,sessionId:t.sessionId,sandboxId:t.sandboxId})});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to apply diff: ${s.statusText}`)}return s.json()}async executeCommand(e,t={}){let s=await fetch(`${this.coderUrl}/exec`,{method:"POST",headers:this.headers,body:JSON.stringify({...e,sessionId:t.sessionId,sandboxId:t.sandboxId})});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to execute command: ${s.statusText}`)}return s.json()}async*executeCommandStream(e,t={}){let s=await fetch(`${this.coderUrl}/exec/stream`,{method:"POST",headers:{...this.headers,Accept:"text/event-stream"},body:JSON.stringify({...e,sessionId:t.sessionId,sandboxId:t.sandboxId})});if(!s.ok){let i=await s.json().catch(()=>({}));throw new c("bad_request:api",i.error||`Failed to execute command stream: ${s.statusText}`)}let r=s.body?.getReader();if(!r)throw new c("bad_request:stream","No response body");let n=new TextDecoder,o="";try{for(;;){let{done:i,value:d}=await r.read();if(i)break;o+=n.decode(d,{stream:!0});let u=o.split(`
5
+ `);o=u.pop()||"";for(let g of u)if(g.startsWith("data: ")){let m=g.slice(6);if(m==="[DONE]")return;try{yield JSON.parse(m);}catch{}}}}finally{r.releaseLock();}}async createSandbox(e={}){let t=await fetch(`${this.coderUrl}/sandbox`,{method:"POST",headers:this.headers,body:JSON.stringify(e)});if(!t.ok){let r=await t.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to create sandbox: ${t.statusText}`)}return (await t.json()).sandbox}async getSandbox(e){let t=await fetch(`${this.coderUrl}/sandbox/${e}`,{headers:this.headers});if(!t.ok)throw new c(t.status===404?"not_found:api":"bad_request:api",`Failed to get sandbox: ${t.statusText}`);return (await t.json()).sandbox}async sandboxExec(e,t){let s=await fetch(`${this.coderUrl}/sandbox/${e}/exec`,{method:"POST",headers:this.headers,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to execute in sandbox: ${s.statusText}`)}return s.json()}async destroySandbox(e){let t=await fetch(`${this.coderUrl}/sandbox/${e}`,{method:"DELETE",headers:this.headers});if(!t.ok)throw new c("bad_request:api",`Failed to destroy sandbox: ${t.statusText}`);return t.json()}};function se(a={}){return new v(a)}var ye=se();var O=class{redis;getRedisClient;taskTTL;constructor(e={}){this.redis=e.redis,this.getRedisClient=e.getRedisClient,this.taskTTL=e.taskTTL||L;}async getClient(){if(this.redis)return this.redis;if(this.getRedisClient)return this.redis=await this.getRedisClient(),this.redis;throw new Error("Redis client not configured. Provide redis or getRedisClient in config.")}async createTask(e,t,s,r="Starting..."){let n=await this.getClient(),o=q(),i=Date.now(),d={id:o,chatId:e,messageId:t,type:s,status:"pending",progress:0,message:r,createdAt:i,updatedAt:i};return await n.hSet(`${w}${o}`,this.taskToRedis(d)),await n.expire(`${w}${o}`,this.taskTTL),await n.sAdd(`${b}${e}`,o),await n.expire(`${b}${e}`,this.taskTTL),console.log(`[TaskManager] Created task ${o} for chat ${e} (${s})`),o}async updateProgress(e,t,s){let r=await this.getClient();await r.hSet(`${w}${e}`,{status:"generating",progress:t.toString(),message:s,updatedAt:Date.now().toString()}),await r.publish(`task:progress:${e}`,JSON.stringify({taskId:e,progress:t,message:s,status:"generating"})),console.log(`[TaskManager] Task ${e} progress: ${t}% - ${s}`);}async complete(e,t){let s=await this.getClient();await s.hSet(`${w}${e}`,{status:"complete",progress:"100",message:"Complete",result:JSON.stringify(t),updatedAt:Date.now().toString()}),await s.publish(`task:progress:${e}`,JSON.stringify({taskId:e,progress:100,message:"Complete",status:"complete",result:t})),console.log(`[TaskManager] Task ${e} completed`);}async fail(e,t){let s=await this.getClient();await s.hSet(`${w}${e}`,{status:"failed",message:t,error:t,updatedAt:Date.now().toString()}),await s.publish(`task:progress:${e}`,JSON.stringify({taskId:e,status:"failed",error:t})),console.log(`[TaskManager] Task ${e} failed: ${t}`);}async getTask(e){let s=await(await this.getClient()).hGetAll(`${w}${e}`);return !s||Object.keys(s).length===0?null:this.redisToTask(s)}async getTasksForChat(e){let s=await(await this.getClient()).sMembers(`${b}${e}`);if(!s||s.length===0)return [];let r=[];for(let n of s){let o=await this.getTask(n);o&&r.push(o);}return r.sort((n,o)=>o.createdAt-n.createdAt)}async getPendingTasksForChat(e){return (await this.getTasksForChat(e)).filter(s=>s.status==="pending"||s.status==="generating")}async deleteTask(e){let t=await this.getClient(),s=await this.getTask(e);s&&(await t.del(`${w}${e}`),await t.sRem(`${b}${s.chatId}`,e),console.log(`[TaskManager] Deleted task ${e}`));}async cleanupOldTasks(e,t=864e5){let s=await this.getTasksForChat(e),r=Date.now();for(let n of s)(n.status==="complete"||n.status==="failed")&&r-n.updatedAt>t&&await this.deleteTask(n.id);}async subscribeToTask(e,t){let s=await this.getClient(),r=`task:progress:${e}`;return await s.subscribe(r,n=>{try{let o=JSON.parse(n);t(o);}catch{}}),async()=>{await s.unsubscribe(r);}}taskToRedis(e){return {id:e.id,chatId:e.chatId,messageId:e.messageId,type:e.type,status:e.status,progress:e.progress.toString(),message:e.message,result:e.result||"",error:e.error||"",createdAt:e.createdAt.toString(),updatedAt:e.updatedAt.toString()}}redisToTask(e){return {id:e.id,chatId:e.chatId,messageId:e.messageId,type:e.type,status:e.status,progress:parseInt(e.progress,10),message:e.message,result:e.result||void 0,error:e.error||void 0,createdAt:parseInt(e.createdAt,10),updatedAt:parseInt(e.updatedAt,10)}}};function Re(a){return new O(a)}async function*Ce(a){if(!a.body)throw new Error("Response body is null");let e=a.body.getReader(),t=new TextDecoder,s="",r={};try{for(;;){let{done:n,value:o}=await e.read();if(n)break;s+=t.decode(o,{stream:!0});let i=s.split(`
6
+ `);s=i.pop()||"";for(let d of i){if(d===""){r.data!==void 0&&(yield r),r={};continue}if(d.startsWith(":"))continue;let u=d.indexOf(":");if(u===-1)continue;let g=d.slice(0,u),m=d.slice(u+1).trimStart();switch(g){case "event":r.event=m;break;case "data":try{r.data=JSON.parse(m);}catch{r.data=m;}break;case "id":r.id=m;break;case "retry":r.retry=parseInt(m,10);break}}}r.data!==void 0&&(yield r);}finally{e.releaseLock();}}function Se(a,e){let t=new TextEncoder,s=new ReadableStream({async start(r){try{for await(let n of a){let o="";n.event&&(o+=`event: ${n.event}
7
+ `),n.id&&(o+=`id: ${n.id}
8
+ `),n.retry&&(o+=`retry: ${n.retry}
9
+ `);let i=typeof n.data=="string"?n.data:JSON.stringify(n.data);o+=`data: ${i}
10
+
11
+ `,r.enqueue(t.encode(o));}}catch(n){console.error("SSE stream error:",n);}finally{r.close();}}});return new Response(s,{headers:{...x,...e}})}var D=class{encoder=new TextEncoder;controller=null;stream;constructor(){this.stream=new ReadableStream({start:e=>{this.controller=e;}});}getStream(){return this.stream}getResponse(e){return new Response(this.stream,{headers:{...x,...e}})}write(e){if(!this.controller)return;let t="";e.event&&(t+=`event: ${e.event}
12
+ `),e.id&&(t+=`id: ${e.id}
13
+ `);let s=typeof e.data=="string"?e.data:JSON.stringify(e.data);t+=`data: ${s}
14
+
15
+ `,this.controller.enqueue(this.encoder.encode(t));}writeData(e){this.write({data:e});}writeComment(e){this.controller&&this.controller.enqueue(this.encoder.encode(`: ${e}
16
+
17
+ `));}close(){this.controller&&(this.controller.close(),this.controller=null);}error(e){this.controller&&(this.controller.error(e),this.controller=null);}};function be(){return new D}var F=class{constructor(e){this.dataStream=e;}processToolCalls(e){if(!(!e||e.length===0))for(let t of e)try{let s=JSON.parse(t.function.arguments),r=t.function.name;switch(r){case "create_document":this.handleCreateDocument(s,t.id);break;case "update_document":this.handleUpdateDocument(s,t.id);break;default:console.log(`[ComponentStream] Unknown tool: ${r}`);}}catch(s){console.error("[ComponentStream] Error processing tool call:",s);}}processToolResult(e){try{e.type==="artifact"?this.handleArtifactResult(e):e.type==="artifact_update"&&this.handleArtifactUpdate(e);}catch(t){console.error("[ComponentStream] Error processing tool result:",t);}}streamArtifact(e){this.dataStream.write({type:"data-kind",data:e.kind,transient:true}),this.dataStream.write({type:"data-id",data:e.id,transient:true}),this.dataStream.write({type:"data-title",data:e.title,transient:true}),this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(e.content),this.dataStream.write({type:"data-finish",data:null,transient:true});}streamTextDelta(e){this.dataStream.write({type:"data-textDelta",data:e,transient:true});}streamContent(e,t=50){let s=this.splitIntoChunks(e,t);for(let r of s)this.dataStream.write({type:"data-textDelta",data:r,transient:true});}finish(){this.dataStream.write({type:"data-finish",data:null,transient:true});}handleCreateDocument(e,t){let{title:s,kind:r,content:n}=e,o=`doc_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;console.log(`[ComponentStream] Creating document: ${s} (${r})`),this.streamArtifact({id:o,kind:r,title:s,content:n}),this.dataStream.write({type:"tool-result",data:{toolCallId:t,toolName:"create_document",result:{id:o,title:s,kind:r,message:"Document created successfully"}}});}handleUpdateDocument(e,t){let{id:s,description:r,content:n}=e;console.log(`[ComponentStream] Updating document: ${s}`),this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(n),this.dataStream.write({type:"data-finish",data:null,transient:true}),this.dataStream.write({type:"tool-result",data:{toolCallId:t,toolName:"update_document",result:{id:s,message:`Document updated: ${r}`}}});}handleArtifactResult(e){let{id:t,title:s,kind:r,content:n}=e;if(!t||!s||!r||!n){console.error("[ComponentStream] Invalid artifact result:",e);return}this.streamArtifact({id:t,kind:r,title:s,content:n});}handleArtifactUpdate(e){let{content:t}=e;if(!t){console.error("[ComponentStream] Invalid artifact update:",e);return}this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(t),this.dataStream.write({type:"data-finish",data:null,transient:true});}splitIntoChunks(e,t){let s=[],r=e.split(" "),n="";for(let o=0;o<r.length;o++){let i=o===0?r[o]:" "+r[o];n.length+i.length>t&&n.length>0?(s.push(n),n=i.trim()):n+=i;}return n.length>0&&s.push(n),s}};function xe(a){return !!(a?.tool_calls&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0)}function Te(a){try{let e=JSON.parse(a);if(e.type&&(e.type==="artifact"||e.type==="artifact_update"))return [e]}catch{}return []}function Pe(a){return new F(a)}async function y(a,e={},t={}){let s=t.baseUrl||h,{method:r="GET",headers:n={},body:o,searchParams:i,stream:d}=e,u=`${s}${a}`;if(i){let f=new URLSearchParams;Object.entries(i).forEach(([N,R])=>{R!==void 0&&f.set(N,R);});let S=f.toString();S&&(u+=`?${S}`);}let g={method:r,headers:{...t.defaultHeaders,...n}};o&&r!=="GET"&&(g.headers={...g.headers,"Content-Type":"application/json"},g.body=JSON.stringify(o));let m=await fetch(u,g);return d&&m.body,m}async function l(a,e={},t={}){let s=await y(a,e,t);return {data:await s.json(),status:s.status}}function ke(a,e={}){return async t=>{let s=new URL(t.url),r=typeof a=="function"?a(t):a,n={};s.searchParams.forEach((m,f)=>{n[f]=m;});let o;if(t.method!=="GET"&&t.method!=="HEAD")try{o=await t.json();}catch{}let i={};t.headers.forEach((m,f)=>{i[f]=m;});let d=await y(r,{method:t.method,headers:i,body:o,searchParams:n},e);if((d.headers.get("content-type")||"").includes("text/event-stream"))return new Response(d.body,{status:d.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let g=await d.json();return Response.json(g,{status:d.status})}}function $e(a={}){let e=a.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("userMid"),n=s.searchParams.get("visibility"),o=r?`/agents?creator_mid=${encodeURIComponent(r)}`:n?`/agents?visibility=${n}`:"/agents",{data:i,status:d}=await l(o,{},{baseUrl:e}),u=i;return a.enrichResponse&&(u=await a.enrichResponse(i)),Response.json(u,{status:d})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/agents",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}function Ue(a={}){let e=a.baseUrl;return {GET:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:o}=await l(`/agents/${r}`,{},{baseUrl:e}),i=n;return a.enrichResponse&&(i=await a.enrichResponse(n)),Response.json(i,{status:o})},POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:o,status:i}=await l(`/agents/${r}`,{method:"POST",body:n},{baseUrl:e});return Response.json(o,{status:i})},PUT:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:o,status:i}=await l(`/agents/${r}`,{method:"PUT",body:n},{baseUrl:e});return Response.json(o,{status:i})},DELETE:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:o}=await l(`/agents/${r}`,{method:"DELETE"},{baseUrl:e});return Response.json(n,{status:o})}}}function Ee(a={}){let e=a.baseUrl;return {POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").slice(-2)[0],n=await t.json(),o=await y(`/agents/${r}/execute`,{method:"POST",body:n,stream:true},{baseUrl:e});if((o.headers.get("content-type")||"").includes("text/event-stream")&&o.body)return new Response(o.body,{status:o.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let d=await o.json();return Response.json(d,{status:o.status})}}}function Ie(a={}){let e=a.baseUrl;return {enable:{POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").slice(-2)[0],{data:n,status:o}=await l(`/agents/${r}/enable`,{method:"POST"},{baseUrl:e});return Response.json(n,{status:o})}},disable:{POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").slice(-2)[0],{data:n,status:o}=await l(`/agents/${r}/disable`,{method:"POST"},{baseUrl:e});return Response.json(n,{status:o})}}}}function _e(a={}){let e=a.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("scope"),n=s.searchParams.get("creator_mid"),o="/skills";r?o+=`?scope=${encodeURIComponent(r)}`:n&&(o+=`?creator_mid=${encodeURIComponent(n)}`);let{data:i,status:d}=await l(o,{},{baseUrl:e});return Response.json(i,{status:d})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/skills",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}function Ae(a={}){let e=a.baseUrl;return {GET:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:o}=await l(`/skills/${r}`,{},{baseUrl:e});return Response.json(n,{status:o})},POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:o,status:i}=await l(`/skills/${r}`,{method:"POST",body:n},{baseUrl:e});return Response.json(o,{status:i})},PUT:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:o,status:i}=await l(`/skills/${r}`,{method:"PUT",body:n},{baseUrl:e});return Response.json(o,{status:i})},DELETE:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:o}=await l(`/skills/${r}`,{method:"DELETE"},{baseUrl:e});return Response.json(n,{status:o})}}}function je(a={}){let e=a.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("scope"),n=s.searchParams.get("creator_mid"),o="/widgets";r?o+=`?scope=${encodeURIComponent(r)}`:n&&(o+=`?creator_mid=${encodeURIComponent(n)}`);let{data:i,status:d}=await l(o,{},{baseUrl:e});return Response.json(i,{status:d})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/widgets",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}function ve(a={}){let e=a.baseUrl;return {GET:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:o}=await l(`/widgets/${r}`,{},{baseUrl:e});return Response.json(n,{status:o})},POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:o,status:i}=await l(`/widgets/${r}`,{method:"POST",body:n},{baseUrl:e});return Response.json(o,{status:i})},PUT:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:o,status:i}=await l(`/widgets/${r}`,{method:"PUT",body:n},{baseUrl:e});return Response.json(o,{status:i})},DELETE:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:o}=await l(`/widgets/${r}`,{method:"DELETE"},{baseUrl:e});return Response.json(n,{status:o})}}}function Oe(a={}){let e=a.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("id"),n=s.searchParams.get("creator_mid"),o="/imaginations";r?o=`/imaginations/${r}`:n&&(o+=`?creator_mid=${encodeURIComponent(n)}`);let{data:i,status:d}=await l(o,{},{baseUrl:e});return Response.json(i,{status:d})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/imaginations",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}function De(a={}){let e=a.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("status"),n=s.searchParams.get("limit"),o="/coder/sessions",i=[];r&&i.push(`status=${encodeURIComponent(r)}`),n&&i.push(`limit=${encodeURIComponent(n)}`),i.length&&(o+=`?${i.join("&")}`);let{data:d,status:u}=await l(o,{},{baseUrl:e});return Response.json(d,{status:u})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/coder/sessions",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}function Fe(a={}){let e=a.baseUrl;return {GET:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:o}=await l(`/coder/sessions/${r}`,{},{baseUrl:e});return Response.json(n,{status:o})},POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:o,status:i}=await l(`/coder/sessions/${r}`,{method:"POST",body:n},{baseUrl:e});return Response.json(o,{status:i})},DELETE:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:o}=await l(`/coder/sessions/${r}`,{method:"DELETE"},{baseUrl:e});return Response.json(n,{status:o})},abort:{POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").slice(-2)[0],{data:n,status:o}=await l(`/coder/sessions/${r}/abort`,{method:"POST"},{baseUrl:e});return Response.json(n,{status:o})}}}}function Le(a={}){let e=a.baseUrl;return {POST:async t=>{let s=await t.json(),r=await y("/coder/execute",{method:"POST",body:s,stream:s.stream},{baseUrl:e});if((r.headers.get("content-type")||"").includes("text/event-stream")&&r.body)return new Response(r.body,{status:r.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let o=await r.json();return Response.json(o,{status:r.status})}}}function qe(a={}){let e=a.baseUrl;return {GET:async()=>{let{data:t,status:s}=await l("/coder/tools",{},{baseUrl:e});return Response.json(t,{status:s})},call:{POST:async(t,s)=>{let r=s?.params?.tool||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:o,status:i}=await l(`/coder/tools/${r}`,{method:"POST",body:n},{baseUrl:e});return Response.json(o,{status:i})}}}}function Me(a={}){let e=a.baseUrl;return {read:{GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("path")||"",n=s.searchParams.get("sessionId"),o=s.searchParams.get("sandboxId"),i=`/coder/files/read?path=${encodeURIComponent(r)}`;n&&(i+=`&sessionId=${encodeURIComponent(n)}`),o&&(i+=`&sandboxId=${encodeURIComponent(o)}`);let{data:d,status:u}=await l(i,{},{baseUrl:e});return Response.json(d,{status:u})}},write:{POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/coder/files/write",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}},list:{GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("path")||".",n=s.searchParams.get("recursive"),o=s.searchParams.get("maxDepth"),i=s.searchParams.get("sessionId"),d=s.searchParams.get("sandboxId"),u=`/coder/files/list?path=${encodeURIComponent(r)}`;n&&(u+=`&recursive=${n}`),o&&(u+=`&maxDepth=${o}`),i&&(u+=`&sessionId=${encodeURIComponent(i)}`),d&&(u+=`&sandboxId=${encodeURIComponent(d)}`);let{data:g,status:m}=await l(u,{},{baseUrl:e});return Response.json(g,{status:m})}},search:{GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("pattern")||"",n=s.searchParams.get("path"),o=s.searchParams.get("filePattern"),i=s.searchParams.get("sessionId"),d=s.searchParams.get("sandboxId"),u=`/coder/files/search?pattern=${encodeURIComponent(r)}`;n&&(u+=`&path=${encodeURIComponent(n)}`),o&&(u+=`&filePattern=${encodeURIComponent(o)}`),i&&(u+=`&sessionId=${encodeURIComponent(i)}`),d&&(u+=`&sandboxId=${encodeURIComponent(d)}`);let{data:g,status:m}=await l(u,{},{baseUrl:e});return Response.json(g,{status:m})}},diff:{POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/coder/files/diff",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}}function Ne(a={}){let e=a.baseUrl;return {create:{POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/coder/sandbox",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}},get:{GET:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:o}=await l(`/coder/sandbox/${r}`,{},{baseUrl:e});return Response.json(n,{status:o})}},exec:{POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").slice(-2)[0],n=await t.json(),o=await y(`/coder/sandbox/${r}/exec`,{method:"POST",body:n,stream:n.stream},{baseUrl:e});if((o.headers.get("content-type")||"").includes("text/event-stream")&&o.body)return new Response(o.body,{status:o.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let d=await o.json();return Response.json(d,{status:o.status})}},destroy:{DELETE:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:o}=await l(`/coder/sandbox/${r}`,{method:"DELETE"},{baseUrl:e});return Response.json(n,{status:o})}}}}function He(a={}){let e=a.baseUrl;return {POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/coder/exec",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})},stream:{POST:async t=>{let s=await t.json(),r=await y("/coder/exec/stream",{method:"POST",body:s,stream:true},{baseUrl:e});if(r.body)return new Response(r.body,{status:r.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let n=await r.json();return Response.json(n,{status:r.status})}}}}export{U as AgentsClient,b as CHAT_TASKS_PREFIX,v as CoderClient,F as ComponentStreamAdapter,h as DEFAULT_GLAYER_NETWORK_URL,C as DEFAULT_MAGMA_RPC_URL,ne as DEFAULT_P2P_NETWORK_URL,re as DEFAULT_TASK_NETWORK_URL,_ as FilesClient,c as GeoffSDKError,p as JSON_HEADERS,k as MCPClient,P as MagmaClient,j as PointsClient,D as SSEWriter,x as SSE_HEADERS,A as SkillsClient,$ as SocialClient,w as TASK_PREFIX,L as TASK_TTL,O as TaskManager,T as TaskNetworkClient,I as UserClient,E as WidgetsClient,pe as agentsClient,ye as coderClient,Ue as createAgentDetailRoutes,Ee as createAgentExecuteRoute,$e as createAgentRoutes,Ie as createAgentToggleRoutes,V as createAgentsClient,se as createCoderClient,He as createCoderExecRoutes,Le as createCoderExecuteRoute,Me as createCoderFilesRoutes,Ne as createCoderSandboxRoutes,Fe as createCoderSessionDetailRoutes,De as createCoderSessionRoutes,qe as createCoderToolsRoutes,Pe as createComponentStreamAdapter,Z as createFilesClient,Oe as createImaginationRoutes,K as createMCPClient,G as createMagmaClient,te as createPointsClient,ke as createProxyHandler,Se as createSSEResponse,be as createSSEWriter,Ae as createSkillDetailRoutes,_e as createSkillRoutes,ee as createSkillsClient,z as createSocialClient,Re as createTaskManager,W as createTaskNetworkClient,Q as createUserClient,ve as createWidgetDetailRoutes,je as createWidgetRoutes,X as createWidgetsClient,Te as extractToolResults,ge as filesClient,l as forwardJSON,y as forwardRequest,M as generateCID,q as generateUUID,Y as getMessageByErrorCode,xe as hasToolCalls,ce as magmaClient,de as mcpClient,ie as parseSSELine,Ce as parseSSEStream,we as pointsClient,ae as retry,fe as skillsClient,J as sleep,ue as socialClient,oe as taskNetworkClient,he as userClient,B as visibilityBySurface,me as widgetsClient};