@offworld/sdk 0.2.2 → 0.3.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 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/ai/errors.ts","../../src/ai/stream/types.ts","../../src/ai/stream/accumulator.ts","../../src/ai/stream/transformer.ts","../../src/ai/opencode.ts","../../src/generate.ts"],"sourcesContent":["/**\n * Base class for OpenCode reference errors\n */\nexport class OpenCodeReferenceError extends Error {\n\treadonly _tag: string = \"OpenCodeReferenceError\";\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly details?: unknown,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"OpenCodeReferenceError\";\n\t}\n}\n\n/**\n * Error when the @opencode-ai/sdk package is not installed or invalid\n */\nexport class OpenCodeSDKError extends OpenCodeReferenceError {\n\treadonly _tag = \"OpenCodeSDKError\" as const;\n\tconstructor(message?: string) {\n\t\tsuper(\n\t\t\tmessage ?? \"Failed to import @opencode-ai/sdk. Install it with: bun add @opencode-ai/sdk\",\n\t\t);\n\t\tthis.name = \"OpenCodeSDKError\";\n\t}\n}\n\n/**\n * Error when the requested provider is not found\n */\nexport class InvalidProviderError extends OpenCodeReferenceError {\n\treadonly _tag = \"InvalidProviderError\" as const;\n\treadonly hint: string;\n\n\tconstructor(\n\t\tpublic readonly providerID: string,\n\t\tpublic readonly availableProviders: string[],\n\t) {\n\t\tconst hint =\n\t\t\tavailableProviders.length > 0\n\t\t\t\t? `Available providers: ${availableProviders.join(\", \")}`\n\t\t\t\t: \"No providers available. Check your OpenCode configuration.\";\n\t\tsuper(`Provider \"${providerID}\" not found. ${hint}`);\n\t\tthis.name = \"InvalidProviderError\";\n\t\tthis.hint = hint;\n\t}\n}\n\n/**\n * Error when the provider exists but is not connected/authenticated\n */\nexport class ProviderNotConnectedError extends OpenCodeReferenceError {\n\treadonly _tag = \"ProviderNotConnectedError\" as const;\n\treadonly hint: string;\n\n\tconstructor(\n\t\tpublic readonly providerID: string,\n\t\tpublic readonly connectedProviders: string[],\n\t) {\n\t\tconst hint =\n\t\t\tconnectedProviders.length > 0\n\t\t\t\t? `Connected providers: ${connectedProviders.join(\", \")}. Run 'opencode auth ${providerID}' to connect.`\n\t\t\t\t: `No providers connected. Run 'opencode auth ${providerID}' to authenticate.`;\n\t\tsuper(`Provider \"${providerID}\" is not connected. ${hint}`);\n\t\tthis.name = \"ProviderNotConnectedError\";\n\t\tthis.hint = hint;\n\t}\n}\n\n/**\n * Error when the requested model is not found for a provider\n */\nexport class InvalidModelError extends OpenCodeReferenceError {\n\treadonly _tag = \"InvalidModelError\" as const;\n\treadonly hint: string;\n\n\tconstructor(\n\t\tpublic readonly modelID: string,\n\t\tpublic readonly providerID: string,\n\t\tpublic readonly availableModels: string[],\n\t) {\n\t\tconst hint =\n\t\t\tavailableModels.length > 0\n\t\t\t\t? `Available models for ${providerID}: ${availableModels.slice(0, 10).join(\", \")}${availableModels.length > 10 ? ` (and ${availableModels.length - 10} more)` : \"\"}`\n\t\t\t\t: `No models available for provider \"${providerID}\".`;\n\t\tsuper(`Model \"${modelID}\" not found for provider \"${providerID}\". ${hint}`);\n\t\tthis.name = \"InvalidModelError\";\n\t\tthis.hint = hint;\n\t}\n}\n\n/**\n * Error when the OpenCode server fails to start\n */\nexport class ServerStartError extends OpenCodeReferenceError {\n\treadonly _tag = \"ServerStartError\" as const;\n\treadonly hint: string;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly port?: number,\n\t\tdetails?: unknown,\n\t) {\n\t\tconst hint = port\n\t\t\t? `Failed to start server on port ${port}. Ensure no other process is using this port.`\n\t\t\t: \"Failed to start OpenCode server. Check your OpenCode installation and configuration.\";\n\t\tsuper(`${message}. ${hint}`, details);\n\t\tthis.name = \"ServerStartError\";\n\t\tthis.hint = hint;\n\t}\n}\n\n/**\n * Error when a session operation fails\n */\nexport class SessionError extends OpenCodeReferenceError {\n\treadonly _tag = \"SessionError\" as const;\n\treadonly hint: string;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly sessionId?: string,\n\t\tpublic readonly sessionState?: string,\n\t\tdetails?: unknown,\n\t) {\n\t\tconst context = sessionId ? ` (session: ${sessionId})` : \"\";\n\t\tconst stateInfo = sessionState ? ` State: ${sessionState}.` : \"\";\n\t\tconst hint = `Session operation failed${context}.${stateInfo} Try creating a new session.`;\n\t\tsuper(`${message}. ${hint}`, details);\n\t\tthis.name = \"SessionError\";\n\t\tthis.hint = hint;\n\t}\n}\n\n/**\n * Error when a request times out\n */\nexport class TimeoutError extends OpenCodeReferenceError {\n\treadonly _tag = \"TimeoutError\" as const;\n\treadonly hint: string;\n\n\tconstructor(\n\t\tpublic readonly timeoutMs: number,\n\t\tpublic readonly operation: string = \"operation\",\n\t) {\n\t\tconst hint = `The ${operation} did not complete within ${timeoutMs}ms. Consider increasing the timeout or checking if the model is responding.`;\n\t\tsuper(`Timeout: ${operation} did not complete within ${timeoutMs}ms. ${hint}`);\n\t\tthis.name = \"TimeoutError\";\n\t\tthis.hint = hint;\n\t}\n}\n","/**\n * Zod schemas for OpenCode stream events\n * Replaces inline `as` casts with runtime-validated types\n */\n\nimport { z } from \"zod\";\n\nconst PartBaseSchema = z.object({\n\tid: z.string().optional(),\n\tsessionID: z.string().optional(),\n\tmessageID: z.string().optional(),\n});\n\nexport const TextPartSchema = PartBaseSchema.extend({\n\ttype: z.literal(\"text\"),\n\ttext: z.string().optional(),\n});\n\nexport const ToolStatePendingSchema = z.object({\n\tstatus: z.literal(\"pending\"),\n});\n\nexport const ToolStateRunningSchema = z.object({\n\tstatus: z.literal(\"running\"),\n\ttitle: z.string().optional(),\n\tinput: z.unknown().optional(),\n\tmetadata: z.record(z.string(), z.unknown()).optional(),\n\ttime: z\n\t\t.object({\n\t\t\tstart: z.number(),\n\t\t})\n\t\t.optional(),\n});\n\nexport const ToolStateCompletedSchema = z.object({\n\tstatus: z.literal(\"completed\"),\n\ttitle: z.string().optional(),\n\tinput: z.record(z.string(), z.unknown()).optional(),\n\toutput: z.string().optional(),\n\tmetadata: z.record(z.string(), z.unknown()).optional(),\n\ttime: z\n\t\t.object({\n\t\t\tstart: z.number(),\n\t\t\tend: z.number(),\n\t\t})\n\t\t.optional(),\n});\n\nexport const ToolStateErrorSchema = z.object({\n\tstatus: z.literal(\"error\"),\n\terror: z.string().optional(),\n\tinput: z.record(z.string(), z.unknown()).optional(),\n\ttime: z\n\t\t.object({\n\t\t\tstart: z.number(),\n\t\t\tend: z.number(),\n\t\t})\n\t\t.optional(),\n});\n\nexport const ToolStateSchema = z.discriminatedUnion(\"status\", [\n\tToolStatePendingSchema,\n\tToolStateRunningSchema,\n\tToolStateCompletedSchema,\n\tToolStateErrorSchema,\n]);\n\nexport const ToolPartSchema = PartBaseSchema.extend({\n\ttype: z.literal(\"tool\"),\n\tcallID: z.string().optional(),\n\ttool: z.string().optional(),\n\tstate: ToolStateSchema.optional(),\n});\n\nexport const StepStartPartSchema = PartBaseSchema.extend({\n\ttype: z.literal(\"step-start\"),\n});\n\nexport const StepFinishPartSchema = PartBaseSchema.extend({\n\ttype: z.literal(\"step-finish\"),\n\treason: z.string().optional(),\n});\n\nexport const ToolUsePartSchema = PartBaseSchema.extend({\n\ttype: z.literal(\"tool-use\"),\n\ttoolUseId: z.string().optional(),\n\tname: z.string().optional(),\n});\n\nexport const ToolResultPartSchema = PartBaseSchema.extend({\n\ttype: z.literal(\"tool-result\"),\n\ttoolUseId: z.string().optional(),\n});\n\nexport const MessagePartSchema = z.discriminatedUnion(\"type\", [\n\tTextPartSchema,\n\tToolPartSchema,\n\tStepStartPartSchema,\n\tStepFinishPartSchema,\n\tToolUsePartSchema,\n\tToolResultPartSchema,\n]);\n\n/**\n * Session error payload\n */\nexport const SessionErrorSchema = z.object({\n\tname: z.string().optional(),\n\tmessage: z.string().optional(),\n\tcode: z.string().optional(),\n});\n\nexport const MessagePartUpdatedPropsSchema = z.object({\n\tpart: MessagePartSchema,\n});\n\n/**\n * Properties for session.idle event\n */\nexport const SessionIdlePropsSchema = z.object({\n\tsessionID: z.string(),\n});\n\n/**\n * Properties for session.error event\n */\nexport const SessionErrorPropsSchema = z.object({\n\tsessionID: z.string(),\n\terror: SessionErrorSchema.optional(),\n});\n\n/**\n * Properties for session.updated event\n */\nexport const SessionUpdatedPropsSchema = z.object({\n\tsessionID: z.string(),\n\tstatus: z.string().optional(),\n});\n\n/**\n * message.part.updated event\n */\nexport const MessagePartUpdatedEventSchema = z.object({\n\ttype: z.literal(\"message.part.updated\"),\n\tproperties: MessagePartUpdatedPropsSchema,\n});\n\n/**\n * session.idle event\n */\nexport const SessionIdleEventSchema = z.object({\n\ttype: z.literal(\"session.idle\"),\n\tproperties: SessionIdlePropsSchema,\n});\n\n/**\n * session.error event\n */\nexport const SessionErrorEventSchema = z.object({\n\ttype: z.literal(\"session.error\"),\n\tproperties: SessionErrorPropsSchema,\n});\n\n/**\n * session.updated event\n */\nexport const SessionUpdatedEventSchema = z.object({\n\ttype: z.literal(\"session.updated\"),\n\tproperties: SessionUpdatedPropsSchema,\n});\n\n/**\n * Generic event for unknown types (passthrough)\n */\nexport const GenericEventSchema = z.object({\n\ttype: z.string(),\n\tproperties: z.record(z.string(), z.unknown()),\n});\n\nexport type TextPart = z.infer<typeof TextPartSchema>;\nexport type ToolPart = z.infer<typeof ToolPartSchema>;\nexport type ToolState = z.infer<typeof ToolStateSchema>;\nexport type ToolStateRunning = z.infer<typeof ToolStateRunningSchema>;\nexport type ToolUsePart = z.infer<typeof ToolUsePartSchema>;\nexport type ToolResultPart = z.infer<typeof ToolResultPartSchema>;\nexport type MessagePart = z.infer<typeof MessagePartSchema>;\n\nexport type SessionErrorPayload = z.infer<typeof SessionErrorSchema>;\n\nexport type MessagePartUpdatedProps = z.infer<typeof MessagePartUpdatedPropsSchema>;\nexport type SessionIdleProps = z.infer<typeof SessionIdlePropsSchema>;\nexport type SessionErrorProps = z.infer<typeof SessionErrorPropsSchema>;\nexport type SessionUpdatedProps = z.infer<typeof SessionUpdatedPropsSchema>;\n\nexport type MessagePartUpdatedEvent = z.infer<typeof MessagePartUpdatedEventSchema>;\nexport type SessionIdleEvent = z.infer<typeof SessionIdleEventSchema>;\nexport type SessionErrorEvent = z.infer<typeof SessionErrorEventSchema>;\nexport type SessionUpdatedEvent = z.infer<typeof SessionUpdatedEventSchema>;\nexport type GenericEvent = z.infer<typeof GenericEventSchema>;\n\n/**\n * All known stream event types\n */\nexport type StreamEvent =\n\t| MessagePartUpdatedEvent\n\t| SessionIdleEvent\n\t| SessionErrorEvent\n\t| SessionUpdatedEvent\n\t| GenericEvent;\n","/**\n * Text accumulator for stream events\n * Manages accumulation of text parts by ID and provides delta extraction\n */\n\nimport type { TextPart } from \"./types.js\";\n\n/**\n * Accumulates text from streaming message parts.\n * Tracks multiple parts by ID and provides delta text between updates.\n */\nexport class TextAccumulator {\n\tprivate readonly parts = new Map<string, string>();\n\tprivate _firstTextReceived = false;\n\n\t/**\n\t * Whether any text has been received\n\t */\n\tget hasReceivedText(): boolean {\n\t\treturn this._firstTextReceived;\n\t}\n\n\t/**\n\t * Accumulate text from a message part and return the delta (new text only).\n\t * Returns null if the part should be skipped (non-text, no ID, no text).\n\t */\n\taccumulatePart(part: TextPart): string | null {\n\t\tif (part.type !== \"text\" || !part.text || !part.id) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst partId = part.id;\n\t\tconst prevText = this.parts.get(partId) ?? \"\";\n\t\tthis.parts.set(partId, part.text);\n\n\t\tif (!this._firstTextReceived) {\n\t\t\tthis._firstTextReceived = true;\n\t\t}\n\n\t\tif (part.text.length > prevText.length) {\n\t\t\treturn part.text.slice(prevText.length);\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Get the full accumulated text from all parts\n\t */\n\tgetFullText(): string {\n\t\treturn Array.from(this.parts.values()).join(\"\");\n\t}\n\n\t/**\n\t * Get the number of distinct parts accumulated\n\t */\n\tgetPartCount(): number {\n\t\treturn this.parts.size;\n\t}\n\n\t/**\n\t * Get info about each part for debugging\n\t */\n\tgetPartInfo(): Array<{ id: string; length: number }> {\n\t\treturn Array.from(this.parts.entries()).map(([id, text]) => ({\n\t\t\tid,\n\t\t\tlength: text.length,\n\t\t}));\n\t}\n\n\t/**\n\t * Clear accumulated text\n\t */\n\tclear(): void {\n\t\tthis.parts.clear();\n\t\tthis._firstTextReceived = false;\n\t}\n}\n","/**\n * Stream event transformer and parser\n * Safely parses and validates stream events using Zod schemas\n */\n\nimport {\n\tMessagePartUpdatedPropsSchema,\n\tSessionIdlePropsSchema,\n\tSessionErrorPropsSchema,\n\tSessionErrorSchema,\n\ttype TextPart,\n\ttype ToolPart,\n\ttype SessionErrorPayload,\n\ttype MessagePartUpdatedProps,\n\ttype SessionIdleProps,\n\ttype SessionErrorProps,\n} from \"./types.js\";\n\n/**\n * Raw event from the OpenCode SDK stream\n */\nexport interface RawStreamEvent {\n\ttype: string;\n\tproperties: Record<string, unknown>;\n}\n\n/**\n * Result of parsing a stream event\n */\nexport type ParsedEventResult =\n\t| {\n\t\t\ttype: \"message.part.updated\";\n\t\t\tprops: MessagePartUpdatedProps;\n\t\t\ttextPart: TextPart | null;\n\t\t\ttoolPart: ToolPart | null;\n\t }\n\t| { type: \"session.idle\"; props: SessionIdleProps }\n\t| { type: \"session.error\"; props: SessionErrorProps; error: SessionErrorPayload | null }\n\t| { type: \"unknown\"; rawType: string };\n\n/**\n * Parse a raw stream event into a typed result.\n * Uses safe parsing - returns type: \"unknown\" for unrecognized or invalid events.\n */\nexport function parseStreamEvent(event: RawStreamEvent): ParsedEventResult {\n\tswitch (event.type) {\n\t\tcase \"message.part.updated\": {\n\t\t\tconst propsResult = MessagePartUpdatedPropsSchema.safeParse(event.properties);\n\t\t\tif (!propsResult.success) {\n\t\t\t\treturn { type: \"unknown\", rawType: event.type };\n\t\t\t}\n\t\t\tconst props = propsResult.data;\n\t\t\tconst textPart = props.part.type === \"text\" ? props.part : null;\n\t\t\tconst toolPart = props.part.type === \"tool\" ? props.part : null;\n\t\t\treturn { type: \"message.part.updated\", props, textPart, toolPart };\n\t\t}\n\n\t\tcase \"session.idle\": {\n\t\t\tconst propsResult = SessionIdlePropsSchema.safeParse(event.properties);\n\t\t\tif (!propsResult.success) {\n\t\t\t\treturn { type: \"unknown\", rawType: event.type };\n\t\t\t}\n\t\t\treturn { type: \"session.idle\", props: propsResult.data };\n\t\t}\n\n\t\tcase \"session.error\": {\n\t\t\tconst propsResult = SessionErrorPropsSchema.safeParse(event.properties);\n\t\t\tif (!propsResult.success) {\n\t\t\t\treturn { type: \"unknown\", rawType: event.type };\n\t\t\t}\n\t\t\tconst props = propsResult.data;\n\n\t\t\tlet error: SessionErrorPayload | null = null;\n\t\t\tif (props.error) {\n\t\t\t\tconst errorResult = SessionErrorSchema.safeParse(props.error);\n\t\t\t\tif (errorResult.success) {\n\t\t\t\t\terror = errorResult.data;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn { type: \"session.error\", props, error };\n\t\t}\n\n\t\tdefault:\n\t\t\treturn { type: \"unknown\", rawType: event.type };\n\t}\n}\n\nexport function isEventForSession(event: RawStreamEvent, sessionId: string): boolean {\n\tconst props = event.properties;\n\tif (\"sessionID\" in props && typeof props.sessionID === \"string\") {\n\t\treturn props.sessionID === sessionId;\n\t}\n\tif (\n\t\t\"part\" in props &&\n\t\ttypeof props.part === \"object\" &&\n\t\tprops.part !== null &&\n\t\t\"sessionID\" in props.part &&\n\t\ttypeof props.part.sessionID === \"string\"\n\t) {\n\t\treturn props.part.sessionID === sessionId;\n\t}\n\treturn true;\n}\n","import {\n\tOpenCodeReferenceError,\n\tOpenCodeSDKError,\n\tInvalidProviderError,\n\tProviderNotConnectedError,\n\tInvalidModelError,\n\tServerStartError,\n\tSessionError,\n\tTimeoutError,\n} from \"./errors.js\";\nimport { TextAccumulator, parseStreamEvent, isEventForSession } from \"./stream/index.js\";\n\nexport const DEFAULT_AI_PROVIDER = \"opencode\";\nexport const DEFAULT_AI_MODEL = \"claude-opus-4-5\";\n\nexport interface StreamPromptOptions {\n\tprompt: string;\n\tcwd: string;\n\tsystemPrompt?: string;\n\tprovider?: string;\n\n\tmodel?: string;\n\t/** Timeout in milliseconds. Set to 0 or undefined for no timeout. */\n\ttimeoutMs?: number;\n\tonDebug?: (message: string) => void;\n\tonStream?: (text: string) => void;\n}\n\nexport interface StreamPromptResult {\n\ttext: string;\n\tsessionId: string;\n\tdurationMs: number;\n}\n\ninterface OpenCodeServer {\n\tclose: () => void;\n\turl: string;\n}\n\ninterface OpenCodeSession {\n\tid: string;\n}\n\ninterface OpenCodeEvent {\n\ttype: string;\n\tproperties: Record<string, unknown>;\n}\n\ninterface OpenCodeProviderModel {\n\tid: string;\n\tname: string;\n}\n\ninterface OpenCodeProvider {\n\tid: string;\n\tname: string;\n\tmodels: Record<string, OpenCodeProviderModel>;\n}\n\ninterface OpenCodeProviderListResponse {\n\tall: OpenCodeProvider[];\n\tconnected: string[];\n\tdefault: Record<string, string>;\n}\n\ninterface OpenCodeClient {\n\tsession: {\n\t\tcreate: () => Promise<{ data: OpenCodeSession; error?: unknown }>;\n\t\tprompt: (options: {\n\t\t\tpath: { id: string };\n\t\t\tbody: {\n\t\t\t\tagent?: string;\n\t\t\t\tparts: Array<{ type: string; text: string }>;\n\t\t\t\tmodel?: { providerID: string; modelID: string };\n\t\t\t};\n\t\t}) => Promise<{ data: unknown; error?: unknown }>;\n\t};\n\tevent: {\n\t\tsubscribe: () => Promise<{\n\t\t\tstream: AsyncIterable<OpenCodeEvent>;\n\t\t}>;\n\t};\n\tprovider: {\n\t\tlist: () => Promise<{ data: OpenCodeProviderListResponse; error?: unknown }>;\n\t};\n}\n\ninterface AgentConfig {\n\tdisable?: boolean;\n\tprompt?: string;\n\tdescription?: string;\n\tmode?: string;\n\tpermission?: Record<string, string>;\n\ttools?: Record<string, boolean>;\n}\n\ninterface OpenCodeConfig {\n\tplugin?: unknown[];\n\tmcp?: Record<string, unknown>;\n\tinstructions?: unknown[];\n\tagent?: Record<string, AgentConfig>;\n}\n\ntype CreateOpencodeResult = { server: OpenCodeServer };\ntype CreateOpencodeClientFn = (opts: { baseUrl: string; directory: string }) => OpenCodeClient;\ntype CreateOpencodeFn = (opts: {\n\tport: number;\n\tcwd?: string;\n\tconfig?: OpenCodeConfig;\n}) => Promise<CreateOpencodeResult>;\n\nlet cachedCreateOpencode: CreateOpencodeFn | null = null;\nlet cachedCreateOpencodeClient: CreateOpencodeClientFn | null = null;\n\nasync function getOpenCodeSDK(): Promise<{\n\tcreateOpencode: CreateOpencodeFn;\n\tcreateOpencodeClient: CreateOpencodeClientFn;\n}> {\n\tif (cachedCreateOpencode && cachedCreateOpencodeClient) {\n\t\treturn {\n\t\t\tcreateOpencode: cachedCreateOpencode,\n\t\t\tcreateOpencodeClient: cachedCreateOpencodeClient,\n\t\t};\n\t}\n\n\ttry {\n\t\tconst sdk = await import(\"@opencode-ai/sdk\");\n\t\tif (\n\t\t\ttypeof sdk.createOpencode !== \"function\" ||\n\t\t\ttypeof sdk.createOpencodeClient !== \"function\"\n\t\t) {\n\t\t\tthrow new OpenCodeSDKError(\"SDK missing required exports\");\n\t\t}\n\t\tcachedCreateOpencode = sdk.createOpencode as CreateOpencodeFn;\n\t\tcachedCreateOpencodeClient = sdk.createOpencodeClient as CreateOpencodeClientFn;\n\t\treturn {\n\t\t\tcreateOpencode: cachedCreateOpencode,\n\t\t\tcreateOpencodeClient: cachedCreateOpencodeClient,\n\t\t};\n\t} catch (error) {\n\t\tif (error instanceof OpenCodeSDKError) {\n\t\t\tthrow error;\n\t\t}\n\t\tthrow new OpenCodeSDKError();\n\t}\n}\n\ninterface ToolRunningState {\n\tstatus: \"running\";\n\ttitle?: string;\n\tinput?: unknown;\n}\n\nfunction formatToolMessage(tool: string | undefined, state: ToolRunningState): string | null {\n\tif (state.title) {\n\t\treturn state.title;\n\t}\n\n\tif (!tool) {\n\t\treturn null;\n\t}\n\n\tconst input =\n\t\tstate.input && typeof state.input === \"object\" && !Array.isArray(state.input)\n\t\t\t? (state.input as Record<string, unknown>)\n\t\t\t: undefined;\n\tif (!input) {\n\t\treturn `Running ${tool}...`;\n\t}\n\n\tswitch (tool) {\n\t\tcase \"read\": {\n\t\t\tconst path = input.filePath ?? input.path;\n\t\t\tif (typeof path === \"string\") {\n\t\t\t\tconst filename = path.split(\"/\").pop();\n\t\t\t\treturn `Reading ${filename}...`;\n\t\t\t}\n\t\t\treturn \"Reading file...\";\n\t\t}\n\t\tcase \"glob\": {\n\t\t\tconst pattern = input.pattern;\n\t\t\tif (typeof pattern === \"string\") {\n\t\t\t\treturn `Globbing ${pattern}...`;\n\t\t\t}\n\t\t\treturn \"Searching files...\";\n\t\t}\n\t\tcase \"grep\": {\n\t\t\tconst pattern = input.pattern;\n\t\t\tif (typeof pattern === \"string\") {\n\t\t\t\tconst truncated = pattern.length > 30 ? `${pattern.slice(0, 30)}...` : pattern;\n\t\t\t\treturn `Searching for \"${truncated}\"...`;\n\t\t\t}\n\t\t\treturn \"Searching content...\";\n\t\t}\n\t\tcase \"list\": {\n\t\t\tconst path = input.path;\n\t\t\tif (typeof path === \"string\") {\n\t\t\t\treturn `Listing ${path}...`;\n\t\t\t}\n\t\t\treturn \"Listing directory...\";\n\t\t}\n\t\tdefault:\n\t\t\treturn `Running ${tool}...`;\n\t}\n}\n\nexport async function streamPrompt(options: StreamPromptOptions): Promise<StreamPromptResult> {\n\tconst {\n\t\tprompt,\n\t\tcwd,\n\t\tsystemPrompt,\n\t\tprovider: optProvider,\n\t\tmodel: optModel,\n\t\ttimeoutMs,\n\t\tonDebug,\n\t\tonStream,\n\t} = options;\n\n\tconst debug = onDebug ?? (() => {});\n\tconst stream = onStream ?? (() => {});\n\tconst startTime = Date.now();\n\n\tdebug(\"Loading OpenCode SDK...\");\n\tconst { createOpencode, createOpencodeClient } = await getOpenCodeSDK();\n\n\tconst maxAttempts = 10;\n\tlet server: OpenCodeServer | null = null;\n\tlet client: OpenCodeClient | null = null;\n\tlet port = 0;\n\n\tconst config: OpenCodeConfig = {\n\t\tplugin: [],\n\t\tmcp: {},\n\t\tinstructions: [],\n\t\tagent: {\n\t\t\tbuild: { disable: true },\n\t\t\tgeneral: { disable: true },\n\t\t\tplan: { disable: true },\n\t\t\texplore: { disable: true },\n\t\t\tanalyze: {\n\t\t\t\tprompt: [\n\t\t\t\t\t\"You are an expert at analyzing open source codebases and producing documentation.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Your job is to read the codebase and produce structured output based on the user's request.\",\n\t\t\t\t\t\"Use glob to discover files, grep to search for patterns, and read to examine file contents.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Guidelines:\",\n\t\t\t\t\t\"- Explore the codebase thoroughly before producing output\",\n\t\t\t\t\t\"- Focus on understanding architecture, key abstractions, and usage patterns\",\n\t\t\t\t\t\"- When asked for JSON output, respond with ONLY valid JSON - no markdown, no code blocks\",\n\t\t\t\t\t\"- When asked for prose, write clear and concise documentation\",\n\t\t\t\t\t\"- Always base your analysis on actual code you've read, never speculate\",\n\t\t\t\t].join(\"\\n\"),\n\t\t\t\tmode: \"primary\",\n\t\t\t\tdescription: \"Analyze open source codebases and produce summaries and reference files\",\n\t\t\t\ttools: {\n\t\t\t\t\tread: true,\n\t\t\t\t\tgrep: true,\n\t\t\t\t\tglob: true,\n\t\t\t\t\tlist: true,\n\t\t\t\t\twrite: false,\n\t\t\t\t\tbash: false,\n\t\t\t\t\tdelete: false,\n\t\t\t\t\tedit: false,\n\t\t\t\t\tpatch: false,\n\t\t\t\t\tpath: false,\n\t\t\t\t\ttodowrite: false,\n\t\t\t\t\ttodoread: false,\n\t\t\t\t\twebsearch: false,\n\t\t\t\t\twebfetch: false,\n\t\t\t\t\tcodesearch: false,\n\t\t\t\t\tskill: false,\n\t\t\t\t\ttask: false,\n\t\t\t\t\tmcp: false,\n\t\t\t\t\tquestion: false,\n\t\t\t\t\tplan_enter: false,\n\t\t\t\t\tplan_exit: false,\n\t\t\t\t},\n\t\t\t\tpermission: {\n\t\t\t\t\tedit: \"deny\",\n\t\t\t\t\tbash: \"deny\",\n\t\t\t\t\twebfetch: \"deny\",\n\t\t\t\t\texternal_directory: \"deny\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t};\n\n\tdebug(\"Starting embedded OpenCode server...\");\n\n\tfor (let attempt = 0; attempt < maxAttempts; attempt++) {\n\t\tport = Math.floor(Math.random() * 3000) + 3000;\n\t\ttry {\n\t\t\tconst result = await createOpencode({ port, cwd, config });\n\t\t\tserver = result.server;\n\t\t\tclient = createOpencodeClient({\n\t\t\t\tbaseUrl: `http://localhost:${port}`,\n\t\t\t\tdirectory: cwd,\n\t\t\t});\n\t\t\tdebug(`Server started on port ${port}`);\n\t\t\tbreak;\n\t\t} catch (err) {\n\t\t\tif (err instanceof Error && err.message?.includes(\"port\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow new ServerStartError(\"Failed to start OpenCode server\", port, err);\n\t\t}\n\t}\n\n\tif (!server || !client) {\n\t\tthrow new ServerStartError(\"Failed to start OpenCode server after all attempts\");\n\t}\n\n\tconst providerID = optProvider ?? DEFAULT_AI_PROVIDER;\n\tconst modelID = optModel ?? DEFAULT_AI_MODEL;\n\n\ttry {\n\t\tdebug(\"Creating session...\");\n\t\tconst sessionResult = await client.session.create();\n\t\tif (sessionResult.error) {\n\t\t\tthrow new SessionError(\"Failed to create session\", undefined, undefined, sessionResult.error);\n\t\t}\n\t\tconst sessionId = sessionResult.data.id;\n\t\tdebug(`Session created: ${sessionId}`);\n\n\t\tdebug(\"Validating provider and model...\");\n\t\tconst providerResult = await client.provider.list();\n\t\tif (providerResult.error) {\n\t\t\tthrow new OpenCodeReferenceError(\"Failed to fetch provider list\", providerResult.error);\n\t\t}\n\n\t\tconst { all: allProviders, connected: connectedProviders } = providerResult.data;\n\t\tconst allProviderIds = allProviders.map((p) => p.id);\n\n\t\tconst provider = allProviders.find((p) => p.id === providerID);\n\t\tif (!provider) {\n\t\t\tthrow new InvalidProviderError(providerID, allProviderIds);\n\t\t}\n\n\t\tif (!connectedProviders.includes(providerID)) {\n\t\t\tthrow new ProviderNotConnectedError(providerID, connectedProviders);\n\t\t}\n\n\t\tconst availableModelIds = Object.keys(provider.models);\n\t\tif (!provider.models[modelID]) {\n\t\t\tthrow new InvalidModelError(modelID, providerID, availableModelIds);\n\t\t}\n\n\t\tdebug(`Provider \"${providerID}\" and model \"${modelID}\" validated`);\n\n\t\tdebug(\"Subscribing to events...\");\n\t\tconst { stream: eventStream } = await client.event.subscribe();\n\n\t\tconst fullPrompt = systemPrompt\n\t\t\t? `${systemPrompt}\\n\\nAnalyzing codebase at: ${cwd}\\n\\n${prompt}`\n\t\t\t: `Analyzing codebase at: ${cwd}\\n\\n${prompt}`;\n\n\t\tdebug(\"Sending prompt...\");\n\t\tconst promptPromise = client.session.prompt({\n\t\t\tpath: { id: sessionId },\n\t\t\tbody: {\n\t\t\t\tagent: \"analyze\",\n\t\t\t\tparts: [{ type: \"text\", text: fullPrompt }],\n\t\t\t\tmodel: { providerID, modelID },\n\t\t\t},\n\t\t});\n\n\t\tconst textAccumulator = new TextAccumulator();\n\t\tdebug(\"Waiting for response...\");\n\n\t\tlet timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n\t\tconst processEvents = async (): Promise<string> => {\n\t\t\tfor await (const event of eventStream) {\n\t\t\t\tif (!isEventForSession(event, sessionId)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst parsed = parseStreamEvent(event);\n\n\t\t\t\tswitch (parsed.type) {\n\t\t\t\t\tcase \"message.part.updated\": {\n\t\t\t\t\t\tif (parsed.toolPart?.state) {\n\t\t\t\t\t\t\tconst { state, tool } = parsed.toolPart;\n\t\t\t\t\t\t\tif (state.status === \"running\") {\n\t\t\t\t\t\t\t\tconst message = formatToolMessage(tool, state);\n\t\t\t\t\t\t\t\tif (message) {\n\t\t\t\t\t\t\t\t\tdebug(message);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (parsed.textPart) {\n\t\t\t\t\t\t\tconst delta = textAccumulator.accumulatePart(parsed.textPart);\n\t\t\t\t\t\t\tif (!textAccumulator.hasReceivedText) {\n\t\t\t\t\t\t\t\tdebug(\"Writing reference...\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (delta) {\n\t\t\t\t\t\t\t\tstream(delta);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"session.idle\": {\n\t\t\t\t\t\tif (parsed.props.sessionID === sessionId) {\n\t\t\t\t\t\t\tdebug(\"Response complete\");\n\t\t\t\t\t\t\treturn textAccumulator.getFullText();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"session.error\": {\n\t\t\t\t\t\tif (parsed.props.sessionID === sessionId) {\n\t\t\t\t\t\t\tconst errorName = parsed.error?.name ?? \"Unknown session error\";\n\t\t\t\t\t\t\tdebug(`Session error: ${JSON.stringify(parsed.props.error)}`);\n\t\t\t\t\t\t\tthrow new SessionError(errorName, sessionId, \"error\", parsed.props.error);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"unknown\":\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn textAccumulator.getFullText();\n\t\t};\n\n\t\tlet responseText: string;\n\t\tif (timeoutMs && timeoutMs > 0) {\n\t\t\tconst timeoutPromise = new Promise<never>((_, reject) => {\n\t\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\t\treject(new TimeoutError(timeoutMs, \"session response\"));\n\t\t\t\t}, timeoutMs);\n\t\t\t});\n\t\t\tresponseText = await Promise.race([processEvents(), timeoutPromise]);\n\t\t\tif (timeoutId) clearTimeout(timeoutId);\n\t\t} else {\n\t\t\tresponseText = await processEvents();\n\t\t}\n\n\t\tawait promptPromise;\n\n\t\tif (!responseText) {\n\t\t\tthrow new OpenCodeReferenceError(\"No response received from OpenCode\");\n\t\t}\n\n\t\tdebug(`Response received (${responseText.length} chars)`);\n\n\t\tconst durationMs = Date.now() - startTime;\n\t\tdebug(`Complete in ${durationMs}ms`);\n\n\t\treturn {\n\t\t\ttext: responseText,\n\t\t\tsessionId,\n\t\t\tdurationMs,\n\t\t};\n\t} finally {\n\t\tdebug(\"Closing server...\");\n\t\tserver.close();\n\t}\n}\n","/**\n * This module provides a streamlined approach to generating reference files\n * by delegating all codebase exploration to the AI agent via OpenCode.\n */\n\nimport { streamPrompt, type StreamPromptOptions } from \"./ai/opencode.js\";\nimport { loadConfig, toReferenceName } from \"./config.js\";\nimport { getCommitSha } from \"./clone.js\";\n\nexport interface GenerateReferenceOptions {\n\t/** AI provider ID (e.g., \"anthropic\", \"openai\"). Defaults to config value. */\n\tprovider?: string;\n\t/** AI model ID. Defaults to config value. */\n\tmodel?: string;\n\t/** Debug callback for detailed logging */\n\tonDebug?: (message: string) => void;\n\t/** Stream callback for real-time AI output */\n\tonStream?: (text: string) => void;\n}\n\nexport interface GenerateReferenceResult {\n\t/** The generated reference markdown content */\n\treferenceContent: string;\n\t/** The commit SHA at the time of generation */\n\tcommitSha: string;\n}\n\nfunction createReferenceGenerationPrompt(referenceName: string): string {\n\treturn `You are an expert at analyzing open source libraries and producing reference documentation for AI coding agents.\n\n## PRIMARY GOAL\n\nGenerate a reference markdown file that helps developers USE this library effectively. This is NOT a contribution guide - it's a usage reference for developers consuming this library in their own projects.\n\n## CRITICAL RULES\n\n1. **USER PERSPECTIVE ONLY**: Write for developers who will npm/pip/cargo install this library and use it in THEIR code.\n - DO NOT include: how to contribute, internal test commands, repo-specific policies\n - DO NOT include: \"never mock in tests\" or similar internal dev guidelines\n - DO NOT include: commands like \"npx hereby\", \"just ready\", \"bun test\" that run the library's own tests\n - DO include: how to install, import, configure, and use the public API\n\n2. **NO FRONTMATTER**: Output pure markdown with NO YAML frontmatter. Start directly with the library name heading.\n\n3. **QUICK REFERENCES**: Include a \"Quick References\" section with paths to key entry points in the repo:\n - Paths must be relative from repo root (e.g., \\`src/index.ts\\`, \\`docs/api.md\\`)\n - Include: main entry point, type definitions, README, key docs\n - DO NOT include absolute paths or user-specific paths\n - Keep to 3-5 most important files that help users understand the library\n\n4. **PUBLIC API FOCUS**: Document what users import and call, not internal implementation details.\n - Entry points: what to import from the package\n - Configuration: how to set up/initialize\n - Core methods/functions: the main API surface\n - Types: key TypeScript interfaces users need\n\n5. **MONOREPO AWARENESS**: Many libraries are monorepos with multiple packages:\n - Check for \\`packages/\\`, \\`apps/\\`, \\`crates/\\`, or \\`libs/\\` directories\n - Check root package.json for \\`workspaces\\` field\n - If monorepo: document the package structure and key packages users would install\n - Use full paths from repo root (e.g., \\`packages/core/src/index.ts\\`)\n - Identify which packages are publishable vs internal\n\n## EXPLORATION STEPS\n\nUse Read, Grep, Glob tools to explore:\n1. Root package.json / Cargo.toml - check for workspaces/monorepo config\n2. Check for \\`packages/\\`, \\`apps/\\`, \\`crates/\\` directories\n3. README.md - official usage documentation\n4. For monorepos: explore each publishable package's entry point\n5. docs/ or website/ - find documentation\n6. examples/ - real usage patterns\n7. TypeScript definitions (.d.ts) - public API surface\n\n## OUTPUT FORMAT\n\nIMPORTANT: Reference name is \"${referenceName}\" (for internal tracking only - do NOT include in output).\n\n\\`\\`\\`markdown\n# {Library Name}\n\n{2-3 sentence overview of what this library does and its key value proposition}\n\n## Quick References\n\n| File | Purpose |\n|------|---------|\n| \\`packages/{pkg}/src/index.ts\\` | Main entry point (monorepo example) |\n| \\`src/index.ts\\` | Main entry point (single-package example) |\n| \\`README.md\\` | Documentation |\n\n(For monorepos, include paths to key publishable packages)\n\n## Packages (for monorepos only)\n\n| Package | npm name | Description |\n|---------|----------|-------------|\n| \\`packages/core\\` | \\`@scope/core\\` | Core functionality |\n| \\`packages/react\\` | \\`@scope/react\\` | React bindings |\n\n(OMIT this section for single-package repos)\n\n## When to Use\n\n- {Practical scenario where a developer would reach for this library}\n- {Another real-world use case}\n- {Problem this library solves}\n\n## Installation\n\n\\`\\`\\`bash\n# Single package\nnpm install {package-name}\n\n# Monorepo (show key packages)\nnpm install @scope/core @scope/react\n\\`\\`\\`\n\n## Best Practices\n\n1. {Actionable best practice for USERS of this library}\n2. {Common mistake to avoid when using this library}\n3. {Performance or correctness tip}\n\n## Common Patterns\n\n**{Pattern Name}:**\n\\`\\`\\`{language}\n{Minimal working code example}\n\\`\\`\\`\n\n**{Another Pattern}:**\n\\`\\`\\`{language}\n{Another code example}\n\\`\\`\\`\n\n## API Quick Reference\n\n| Export | Type | Description |\n|--------|------|-------------|\n| \\`{main export}\\` | {type} | {what it does} |\n| \\`{another export}\\` | {type} | {what it does} |\n\n{Add more sections as appropriate for the library: Configuration, Types, CLI Commands (if user-facing), etc.}\n\\`\\`\\`\n\n## QUALITY CHECKLIST\n\nBefore outputting, verify:\n- [ ] NO YAML frontmatter - start directly with # heading\n- [ ] Every code example is something a USER would write, not a contributor\n- [ ] No internal test commands or contribution workflows\n- [ ] Quick References paths are relative from repo root (no absolute/user paths)\n- [ ] Best practices are for using the library, not developing it\n- [ ] If monorepo: Packages section lists publishable packages with npm names\n- [ ] If monorepo: paths include package directory (e.g., \\`packages/core/src/index.ts\\`)\n\nNow explore the codebase and generate the reference content.\n\n## OUTPUT INSTRUCTIONS\n\nAfter exploring, output your complete reference wrapped in XML tags like this:\n\n\\`\\`\\`\n<reference_output>\n(your complete markdown reference here)\n</reference_output>\n\\`\\`\\`\n\nREQUIREMENTS:\n- Start with a level-1 heading with the actual library name (e.g., \"# TanStack Query\")\n- Include sections: Quick References (table), When to Use (bullets), Installation, Best Practices, Common Patterns (with code), API Quick Reference (table)\n- Minimum 2000 characters of actual content - short or placeholder content will be rejected\n- Fill in real information from your exploration - do not use placeholder text like \"{Library Name}\"\n- No YAML frontmatter - start directly with the markdown heading\n- Output ONLY the reference inside the tags, no other text\n\nBegin exploring now.`;\n}\n\n/**\n * Extract the actual reference markdown content from AI response.\n * The response may include echoed prompt/system context before the actual reference.\n * Handles multiple edge cases:\n * - Model echoes the prompt template (skip template content)\n * - Model forgets to close the tag (extract to end of response)\n * - Multiple tag pairs (find the one with real content)\n */\nfunction extractReferenceContent(rawResponse: string, onDebug?: (message: string) => void): string {\n\tconst openTag = \"<reference_output>\";\n\tconst closeTag = \"</reference_output>\";\n\n\tonDebug?.(`[extract] Raw response length: ${rawResponse.length} chars`);\n\n\t// Find all occurrences of open and close tags\n\tconst openIndices: number[] = [];\n\tconst closeIndices: number[] = [];\n\tlet pos = 0;\n\twhile ((pos = rawResponse.indexOf(openTag, pos)) !== -1) {\n\t\topenIndices.push(pos);\n\t\tpos += openTag.length;\n\t}\n\tpos = 0;\n\twhile ((pos = rawResponse.indexOf(closeTag, pos)) !== -1) {\n\t\tcloseIndices.push(pos);\n\t\tpos += closeTag.length;\n\t}\n\n\tonDebug?.(\n\t\t`[extract] Found ${openIndices.length} open tag(s), ${closeIndices.length} close tag(s)`,\n\t);\n\n\t// Helper to clean content (strip markdown fences)\n\tconst cleanContent = (raw: string): string => {\n\t\tlet content = raw.trim();\n\t\tif (content.startsWith(\"```\")) {\n\t\t\tcontent = content.replace(/^```(?:markdown)?\\s*\\n?/, \"\");\n\t\t\tcontent = content.replace(/\\n?```\\s*$/, \"\");\n\t\t}\n\t\treturn content.trim();\n\t};\n\n\t// Helper to check if content is template placeholder\n\tconst isTemplateContent = (content: string): boolean => {\n\t\treturn (\n\t\t\tcontent.includes(\"{Library Name}\") ||\n\t\t\tcontent.includes(\"(your complete markdown reference here)\")\n\t\t);\n\t};\n\n\t// Strategy 1: Find properly paired tags, starting from the LAST open tag\n\t// (Last is more likely to be actual output, not echoed prompt)\n\tfor (let i = openIndices.length - 1; i >= 0; i--) {\n\t\tconst openIdx = openIndices[i];\n\t\tif (openIdx === undefined) continue;\n\n\t\t// Find the first close tag after this open tag\n\t\tconst closeIdx = closeIndices.find((c) => c > openIdx);\n\t\tif (closeIdx !== undefined) {\n\t\t\tconst rawContent = rawResponse.slice(openIdx + openTag.length, closeIdx);\n\t\t\tconst content = cleanContent(rawContent);\n\n\t\t\tonDebug?.(`[extract] Pair ${i}: open=${openIdx}, close=${closeIdx}, len=${content.length}`);\n\t\t\tonDebug?.(\n\t\t\t\t`[extract] Preview: \"${content.slice(0, 200)}${content.length > 200 ? \"...\" : \"\"}\"`,\n\t\t\t);\n\n\t\t\tif (isTemplateContent(content)) {\n\t\t\t\tonDebug?.(`[extract] Skipping pair ${i} - template placeholder content`);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (content.length >= 500) {\n\t\t\t\tonDebug?.(`[extract] Using pair ${i} - valid content`);\n\t\t\t\tvalidateReferenceContent(content);\n\t\t\t\treturn content;\n\t\t\t}\n\t\t\tonDebug?.(`[extract] Pair ${i} too short (${content.length} chars)`);\n\t\t}\n\t}\n\n\t// Strategy 2: Handle unclosed tag - model output <reference_output> but never closed it\n\t// Find the last open tag that has no close tag after it\n\tconst lastOpenIdx = openIndices[openIndices.length - 1];\n\tif (lastOpenIdx !== undefined) {\n\t\tconst hasCloseAfter = closeIndices.some((c) => c > lastOpenIdx);\n\t\tif (!hasCloseAfter) {\n\t\t\tonDebug?.(`[extract] Last open tag at ${lastOpenIdx} is unclosed - extracting to end`);\n\t\t\tconst rawContent = rawResponse.slice(lastOpenIdx + openTag.length);\n\t\t\tconst content = cleanContent(rawContent);\n\n\t\t\tonDebug?.(`[extract] Unclosed content: ${content.length} chars`);\n\t\t\tonDebug?.(\n\t\t\t\t`[extract] Preview: \"${content.slice(0, 200)}${content.length > 200 ? \"...\" : \"\"}\"`,\n\t\t\t);\n\n\t\t\tif (!isTemplateContent(content) && content.length >= 500) {\n\t\t\t\tonDebug?.(`[extract] Using unclosed content - valid`);\n\t\t\t\tvalidateReferenceContent(content);\n\t\t\t\treturn content;\n\t\t\t}\n\t\t}\n\t}\n\n\tonDebug?.(`[extract] No valid content found`);\n\tonDebug?.(`[extract] Response tail: \"${rawResponse.slice(-300)}\"`);\n\n\tthrow new Error(\n\t\t\"Failed to extract reference content: no valid <reference_output> tags found. \" +\n\t\t\t\"The AI may have failed to follow the output format or produced placeholder content.\",\n\t);\n}\n\n/**\n * Validate extracted reference content has minimum required structure.\n * Throws if content is invalid.\n */\nfunction validateReferenceContent(content: string): void {\n\t// Check for template placeholders that indicate the model just echoed the format\n\tconst templatePlaceholders = [\n\t\t\"{Library Name}\",\n\t\t\"{Full overview paragraph}\",\n\t\t\"{Table with 3-5 key files}\",\n\t\t\"{3+ bullet points}\",\n\t\t\"{Install commands}\",\n\t\t\"{3+ numbered items}\",\n\t\t\"{2+ code examples\",\n\t\t\"{Table of key exports}\",\n\t\t\"{Additional sections\",\n\t];\n\n\tconst foundPlaceholders = templatePlaceholders.filter((p) => content.includes(p));\n\tif (foundPlaceholders.length > 0) {\n\t\tthrow new Error(\n\t\t\t`Invalid reference content: contains template placeholders (${foundPlaceholders.slice(0, 3).join(\", \")}). ` +\n\t\t\t\t\"The AI echoed the format instead of generating actual content.\",\n\t\t);\n\t}\n\n\tif (content.length < 500) {\n\t\tthrow new Error(\n\t\t\t`Invalid reference content: too short (${content.length} chars, minimum 500). ` +\n\t\t\t\t\"The AI may have produced placeholder or incomplete content.\",\n\t\t);\n\t}\n\n\tif (!content.startsWith(\"#\")) {\n\t\tthrow new Error(\n\t\t\t\"Invalid reference content: must start with markdown heading. \" +\n\t\t\t\t\"Content must begin with '# Library Name' (no YAML frontmatter).\",\n\t\t);\n\t}\n}\n\n/**\n * Generate a reference markdown file for a repository using AI.\n *\n * Opens an OpenCode session and instructs the AI agent to explore the codebase\n * using Read, Grep, and Glob tools, then produce a comprehensive reference.\n *\n * @param repoPath - Path to the repository to analyze\n * @param repoName - Qualified name of the repo (e.g., \"tanstack/query\" or \"my-local-repo\")\n * @param options - Generation options (provider, model, callbacks)\n * @returns The generated reference content and commit SHA\n */\nexport async function generateReferenceWithAI(\n\trepoPath: string,\n\trepoName: string,\n\toptions: GenerateReferenceOptions = {},\n): Promise<GenerateReferenceResult> {\n\tconst { provider, model, onDebug, onStream } = options;\n\tconst config = loadConfig();\n\n\tconst [configProvider, configModel] = config.defaultModel?.split(\"/\") ?? [];\n\tconst aiProvider = provider ?? configProvider;\n\tconst aiModel = model ?? configModel;\n\n\tonDebug?.(`Starting AI reference generation for ${repoName}`);\n\tonDebug?.(`Repo path: ${repoPath}`);\n\tonDebug?.(`Provider: ${aiProvider ?? \"default\"}, Model: ${aiModel ?? \"default\"}`);\n\n\tconst commitSha = getCommitSha(repoPath);\n\tonDebug?.(`Commit SHA: ${commitSha}`);\n\n\tconst referenceName = toReferenceName(repoName);\n\tonDebug?.(`Reference name: ${referenceName}`);\n\n\tconst promptOptions: StreamPromptOptions = {\n\t\tprompt: createReferenceGenerationPrompt(referenceName),\n\t\tcwd: repoPath,\n\t\tprovider: aiProvider,\n\t\tmodel: aiModel,\n\t\tonDebug,\n\t\tonStream,\n\t};\n\n\tconst result = await streamPrompt(promptOptions);\n\n\tonDebug?.(`Generation complete (${result.durationMs}ms, ${result.text.length} chars)`);\n\n\tconst referenceContent = extractReferenceContent(result.text, onDebug);\n\tonDebug?.(`Extracted reference content (${referenceContent.length} chars)`);\n\n\treturn {\n\t\treferenceContent,\n\t\tcommitSha,\n\t};\n}\n"],"mappings":";;;;;;;;AAGA,IAAa,yBAAb,cAA4C,MAAM;CACjD,AAAS,OAAe;CACxB,YACC,SACA,AAAgB,SACf;AACD,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;;;;;AAOd,IAAa,mBAAb,cAAsC,uBAAuB;CAC5D,AAAS,OAAO;CAChB,YAAY,SAAkB;AAC7B,QACC,WAAW,+EACX;AACD,OAAK,OAAO;;;;;;AAOd,IAAa,uBAAb,cAA0C,uBAAuB;CAChE,AAAS,OAAO;CAChB,AAAS;CAET,YACC,AAAgB,YAChB,AAAgB,oBACf;EACD,MAAM,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AE,CAAC,KAAK,KAAK,CAAC,mEAEvG;AAGF,KAAI,QAAQ,SAAS,IACpB,OAAM,IAAI,MACT,yCAAyC,QAAQ,OAAO,mFAExD;AAGF,KAAI,CAAC,QAAQ,WAAW,IAAI,CAC3B,OAAM,IAAI,MACT,+HAEA;;;;;;;;;;;;;AAeH,eAAsB,wBACrB,UACA,UACA,UAAoC,EAAE,EACH;CACnC,MAAM,EAAE,UAAU,OAAO,SAAS,aAAa;CAG/C,MAAM,CAAC,gBAAgB,eAFR,YAAY,CAEkB,cAAc,MAAM,IAAI,IAAI,EAAE;CAC3E,MAAM,aAAa,YAAY;CAC/B,MAAM,UAAU,SAAS;AAEzB,WAAU,wCAAwC,WAAW;AAC7D,WAAU,cAAc,WAAW;AACnC,WAAU,aAAa,cAAc,UAAU,WAAW,WAAW,YAAY;CAEjF,MAAM,YAAY,aAAa,SAAS;AACxC,WAAU,eAAe,YAAY;CAErC,MAAM,gBAAgB,gBAAgB,SAAS;AAC/C,WAAU,mBAAmB,gBAAgB;CAW7C,MAAM,SAAS,MAAM,aATsB;EAC1C,QAAQ,gCAAgC,cAAc;EACtD,KAAK;EACL,UAAU;EACV,OAAO;EACP;EACA;EACA,CAE+C;AAEhD,WAAU,wBAAwB,OAAO,WAAW,MAAM,OAAO,KAAK,OAAO,SAAS;CAEtF,MAAM,mBAAmB,wBAAwB,OAAO,MAAM,QAAQ;AACtE,WAAU,gCAAgC,iBAAiB,OAAO,SAAS;AAE3E,QAAO;EACN;EACA;EACA"}
@@ -0,0 +1,364 @@
1
+ import { a as getRepoPath, f as Paths, s as loadConfig, u as toReferenceFileName } from "./config-DW8J4gl5.mjs";
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { GlobalMapSchema, ProjectMapSchema } from "@offworld/types";
5
+ import { execFileSync, spawn } from "node:child_process";
6
+
7
+ //#region src/index-manager.ts
8
+ /**
9
+ * Map manager for global and project maps
10
+ *
11
+ * Manages:
12
+ * - Global map: ~/.local/share/offworld/skill/offworld/assets/map.json
13
+ * - Project map: ./.offworld/map.json
14
+ */
15
+ /**
16
+ * Reads the global map from ~/.local/share/offworld/skill/offworld/assets/map.json
17
+ * Returns empty map if file doesn't exist or is invalid
18
+ */
19
+ function readGlobalMap() {
20
+ const mapPath = Paths.offworldGlobalMapPath;
21
+ if (!existsSync(mapPath)) return { repos: {} };
22
+ try {
23
+ const content = readFileSync(mapPath, "utf-8");
24
+ const data = JSON.parse(content);
25
+ return GlobalMapSchema.parse(data);
26
+ } catch {
27
+ return { repos: {} };
28
+ }
29
+ }
30
+ /**
31
+ * Writes the global map to ~/.local/share/offworld/skill/offworld/assets/map.json
32
+ * Creates directory if it doesn't exist
33
+ */
34
+ function writeGlobalMap(map) {
35
+ const mapPath = Paths.offworldGlobalMapPath;
36
+ const mapDir = dirname(mapPath);
37
+ if (!existsSync(mapDir)) mkdirSync(mapDir, { recursive: true });
38
+ const validated = GlobalMapSchema.parse(map);
39
+ writeFileSync(mapPath, JSON.stringify(validated, null, 2), "utf-8");
40
+ }
41
+ /**
42
+ * Adds or updates a repo entry in the global map
43
+ *
44
+ * @param qualifiedName - The qualified repo name (owner/repo)
45
+ * @param entry - The map entry to add/update
46
+ */
47
+ function upsertGlobalMapEntry(qualifiedName, entry) {
48
+ const map = readGlobalMap();
49
+ map.repos[qualifiedName] = entry;
50
+ writeGlobalMap(map);
51
+ }
52
+ /**
53
+ * Removes a repo entry from the global map
54
+ *
55
+ * @param qualifiedName - The qualified repo name (owner/repo)
56
+ * @returns true if repo was removed, false if not found
57
+ */
58
+ function removeGlobalMapEntry(qualifiedName) {
59
+ const map = readGlobalMap();
60
+ if (!(qualifiedName in map.repos)) return false;
61
+ delete map.repos[qualifiedName];
62
+ writeGlobalMap(map);
63
+ return true;
64
+ }
65
+ /**
66
+ * Writes a project map to ./.offworld/map.json
67
+ *
68
+ * @param projectRoot - Absolute path to project root
69
+ * @param entries - Map of qualified repo names to project map entries
70
+ */
71
+ function writeProjectMap(projectRoot, entries) {
72
+ const mapPath = join(projectRoot, ".offworld", "map.json");
73
+ const mapDir = dirname(mapPath);
74
+ if (!existsSync(mapDir)) mkdirSync(mapDir, { recursive: true });
75
+ const projectMap = {
76
+ version: 1,
77
+ scope: "project",
78
+ globalMapPath: Paths.offworldGlobalMapPath,
79
+ repos: entries
80
+ };
81
+ const validated = ProjectMapSchema.parse(projectMap);
82
+ writeFileSync(mapPath, JSON.stringify(validated, null, 2), "utf-8");
83
+ }
84
+
85
+ //#endregion
86
+ //#region src/clone.ts
87
+ /**
88
+ * Git clone and repository management utilities
89
+ */
90
+ var CloneError = class extends Error {
91
+ constructor(message) {
92
+ super(message);
93
+ this.name = "CloneError";
94
+ }
95
+ };
96
+ var RepoExistsError = class extends CloneError {
97
+ constructor(path) {
98
+ super(`Repository already exists at: ${path}`);
99
+ this.name = "RepoExistsError";
100
+ }
101
+ };
102
+ var RepoNotFoundError = class extends CloneError {
103
+ constructor(qualifiedName) {
104
+ super(`Repository not found in index: ${qualifiedName}`);
105
+ this.name = "RepoNotFoundError";
106
+ }
107
+ };
108
+ var GitError = class extends CloneError {
109
+ constructor(message, command, exitCode) {
110
+ super(`Git command failed: ${message}`);
111
+ this.command = command;
112
+ this.exitCode = exitCode;
113
+ this.name = "GitError";
114
+ }
115
+ };
116
+ function execGit(args, cwd) {
117
+ try {
118
+ return execFileSync("git", args, {
119
+ cwd,
120
+ encoding: "utf-8",
121
+ stdio: [
122
+ "pipe",
123
+ "pipe",
124
+ "pipe"
125
+ ]
126
+ }).trim();
127
+ } catch (error) {
128
+ const err = error;
129
+ throw new GitError((err.stderr ? typeof err.stderr === "string" ? err.stderr : err.stderr.toString() : err.message || "Unknown error").trim(), `git ${args.join(" ")}`, err.status ?? null);
130
+ }
131
+ }
132
+ function execGitAsync(args, cwd) {
133
+ return new Promise((resolve, reject) => {
134
+ const proc = spawn("git", args, {
135
+ cwd,
136
+ stdio: [
137
+ "ignore",
138
+ "pipe",
139
+ "pipe"
140
+ ],
141
+ env: {
142
+ ...process.env,
143
+ GIT_TERMINAL_PROMPT: "0"
144
+ }
145
+ });
146
+ let stdout = "";
147
+ let stderr = "";
148
+ proc.stdout.on("data", (data) => {
149
+ stdout += data.toString();
150
+ });
151
+ proc.stderr.on("data", (data) => {
152
+ stderr += data.toString();
153
+ });
154
+ proc.on("close", (code) => {
155
+ if (code === 0) resolve(stdout.trim());
156
+ else reject(new GitError(stderr.trim() || "Unknown error", `git ${args.join(" ")}`, code));
157
+ });
158
+ proc.on("error", (err) => {
159
+ reject(new GitError(err.message, `git ${args.join(" ")}`, null));
160
+ });
161
+ });
162
+ }
163
+ function getCommitSha(repoPath) {
164
+ return execGit(["rev-parse", "HEAD"], repoPath);
165
+ }
166
+ function getCommitDistance(repoPath, olderSha, newerSha = "HEAD") {
167
+ try {
168
+ try {
169
+ execGit([
170
+ "cat-file",
171
+ "-e",
172
+ olderSha
173
+ ], repoPath);
174
+ } catch {
175
+ return null;
176
+ }
177
+ const count = execGit([
178
+ "rev-list",
179
+ "--count",
180
+ `${olderSha}..${newerSha}`
181
+ ], repoPath);
182
+ return Number.parseInt(count, 10);
183
+ } catch {
184
+ return null;
185
+ }
186
+ }
187
+ const SPARSE_CHECKOUT_DIRS = [
188
+ "src",
189
+ "lib",
190
+ "packages",
191
+ "docs",
192
+ "README.md",
193
+ "package.json"
194
+ ];
195
+ /**
196
+ * Clone a remote repository to the local repo root.
197
+ *
198
+ * @param source - Remote repo source from parseRepoInput()
199
+ * @param options - Clone options (shallow, branch, config)
200
+ * @returns The local path where the repo was cloned
201
+ * @throws RepoExistsError if repo already exists (unless force is true)
202
+ * @throws GitError if clone fails
203
+ */
204
+ async function cloneRepo(source, options = {}) {
205
+ const config = options.config ?? loadConfig();
206
+ const repoPath = getRepoPath(source.fullName, source.provider, config);
207
+ if (existsSync(repoPath)) if (options.force) rmSync(repoPath, {
208
+ recursive: true,
209
+ force: true
210
+ });
211
+ else throw new RepoExistsError(repoPath);
212
+ try {
213
+ if (options.sparse) await cloneSparse(source.cloneUrl, repoPath, options);
214
+ else await cloneStandard(source.cloneUrl, repoPath, options);
215
+ } catch (err) {
216
+ cleanupEmptyParentDirs(repoPath);
217
+ throw err;
218
+ }
219
+ const referenceFileName = toReferenceFileName(source.fullName);
220
+ const hasReference = existsSync(join(Paths.offworldReferencesDir, referenceFileName));
221
+ upsertGlobalMapEntry(source.qualifiedName, {
222
+ localPath: repoPath,
223
+ references: hasReference ? [referenceFileName] : [],
224
+ primary: hasReference ? referenceFileName : "",
225
+ keywords: [],
226
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
227
+ });
228
+ return repoPath;
229
+ }
230
+ function cleanupEmptyParentDirs(repoPath) {
231
+ const ownerDir = dirname(repoPath);
232
+ if (existsSync(ownerDir) && readdirSync(ownerDir).length === 0) rmSync(ownerDir, {
233
+ recursive: true,
234
+ force: true
235
+ });
236
+ }
237
+ async function cloneStandard(cloneUrl, repoPath, options) {
238
+ const args = ["clone"];
239
+ if (options.shallow) args.push("--depth", "1");
240
+ if (options.branch) args.push("--branch", options.branch);
241
+ args.push(cloneUrl, repoPath);
242
+ await execGitAsync(args);
243
+ }
244
+ async function cloneSparse(cloneUrl, repoPath, options) {
245
+ const args = [
246
+ "clone",
247
+ "--filter=blob:none",
248
+ "--no-checkout",
249
+ "--sparse"
250
+ ];
251
+ if (options.shallow) args.push("--depth", "1");
252
+ if (options.branch) args.push("--branch", options.branch);
253
+ args.push(cloneUrl, repoPath);
254
+ await execGitAsync(args);
255
+ await execGitAsync([
256
+ "sparse-checkout",
257
+ "set",
258
+ ...SPARSE_CHECKOUT_DIRS
259
+ ], repoPath);
260
+ await execGitAsync(["checkout"], repoPath);
261
+ }
262
+ function isShallowClone(repoPath) {
263
+ try {
264
+ return execGit(["rev-parse", "--is-shallow-repository"], repoPath) === "true";
265
+ } catch {
266
+ return false;
267
+ }
268
+ }
269
+ async function unshallowRepo(repoPath) {
270
+ if (!isShallowClone(repoPath)) return false;
271
+ await execGitAsync(["fetch", "--unshallow"], repoPath);
272
+ return true;
273
+ }
274
+ /**
275
+ * Update a cloned repository by running git fetch and pull.
276
+ *
277
+ * @param qualifiedName - The qualified name of the repo (e.g., "github.com:owner/repo")
278
+ * @param options - Update options
279
+ * @returns Update result with commit SHAs
280
+ * @throws RepoNotFoundError if repo not in index
281
+ * @throws GitError if fetch/pull fails
282
+ */
283
+ async function updateRepo(qualifiedName, options = {}) {
284
+ const entry = readGlobalMap().repos[qualifiedName];
285
+ if (!entry) throw new RepoNotFoundError(qualifiedName);
286
+ const repoPath = entry.localPath;
287
+ if (!existsSync(repoPath)) throw new RepoNotFoundError(qualifiedName);
288
+ const previousSha = getCommitSha(repoPath);
289
+ let unshallowed = false;
290
+ if (options.unshallow) unshallowed = await unshallowRepo(repoPath);
291
+ await execGitAsync(["fetch"], repoPath);
292
+ await execGitAsync(["pull", "--ff-only"], repoPath);
293
+ const currentSha = getCommitSha(repoPath);
294
+ upsertGlobalMapEntry(qualifiedName, {
295
+ ...entry,
296
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
297
+ });
298
+ return {
299
+ updated: previousSha !== currentSha,
300
+ previousSha,
301
+ currentSha,
302
+ unshallowed
303
+ };
304
+ }
305
+ async function removeRepo(qualifiedName, options = {}) {
306
+ const entry = readGlobalMap().repos[qualifiedName];
307
+ if (!entry) return false;
308
+ const { referenceOnly = false, repoOnly = false } = options;
309
+ const removeRepoFiles = !referenceOnly;
310
+ const removeReferenceFiles = !repoOnly;
311
+ if (removeRepoFiles && existsSync(entry.localPath)) {
312
+ rmSync(entry.localPath, {
313
+ recursive: true,
314
+ force: true
315
+ });
316
+ cleanupEmptyParentDirs(entry.localPath);
317
+ }
318
+ if (removeReferenceFiles) {
319
+ for (const referenceFileName of entry.references) {
320
+ const referencePath = join(Paths.offworldReferencesDir, referenceFileName);
321
+ if (existsSync(referencePath)) rmSync(referencePath, { force: true });
322
+ }
323
+ if (entry.primary) {
324
+ const metaDirName = entry.primary.replace(/\.md$/, "");
325
+ const metaPath = join(Paths.metaDir, metaDirName);
326
+ if (existsSync(metaPath)) rmSync(metaPath, {
327
+ recursive: true,
328
+ force: true
329
+ });
330
+ }
331
+ }
332
+ if (removeRepoFiles) removeGlobalMapEntry(qualifiedName);
333
+ else if (removeReferenceFiles) upsertGlobalMapEntry(qualifiedName, {
334
+ ...entry,
335
+ references: [],
336
+ primary: ""
337
+ });
338
+ return true;
339
+ }
340
+ function listRepos() {
341
+ const map = readGlobalMap();
342
+ return Object.keys(map.repos);
343
+ }
344
+ function isRepoCloned(qualifiedName) {
345
+ const entry = readGlobalMap().repos[qualifiedName];
346
+ if (!entry) return false;
347
+ return existsSync(entry.localPath);
348
+ }
349
+ /**
350
+ * Get the local path for a cloned repository.
351
+ *
352
+ * @param qualifiedName - The qualified name of the repo
353
+ * @returns The local path or undefined if not cloned
354
+ */
355
+ function getClonedRepoPath(qualifiedName) {
356
+ const entry = readGlobalMap().repos[qualifiedName];
357
+ if (!entry) return void 0;
358
+ if (!existsSync(entry.localPath)) return void 0;
359
+ return entry.localPath;
360
+ }
361
+
362
+ //#endregion
363
+ export { upsertGlobalMapEntry as _, cloneRepo as a, getCommitSha as c, listRepos as d, removeRepo as f, removeGlobalMapEntry as g, readGlobalMap as h, RepoNotFoundError as i, isRepoCloned as l, updateRepo as m, GitError as n, getClonedRepoPath as o, unshallowRepo as p, RepoExistsError as r, getCommitDistance as s, CloneError as t, isShallowClone as u, writeGlobalMap as v, writeProjectMap as y };
364
+ //# sourceMappingURL=clone-DyLvmbJZ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clone-DyLvmbJZ.mjs","names":[],"sources":["../src/index-manager.ts","../src/clone.ts"],"sourcesContent":["/**\n * Map manager for global and project maps\n *\n * Manages:\n * - Global map: ~/.local/share/offworld/skill/offworld/assets/map.json\n * - Project map: ./.offworld/map.json\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport {\n\tGlobalMapSchema,\n\tProjectMapSchema,\n\ttype GlobalMap,\n\ttype GlobalMapRepoEntry,\n\ttype ProjectMap,\n\ttype ProjectMapRepoEntry,\n} from \"@offworld/types\";\nimport { Paths } from \"./paths.js\";\n\n/**\n * Reads the global map from ~/.local/share/offworld/skill/offworld/assets/map.json\n * Returns empty map if file doesn't exist or is invalid\n */\nexport function readGlobalMap(): GlobalMap {\n\tconst mapPath = Paths.offworldGlobalMapPath;\n\n\tif (!existsSync(mapPath)) {\n\t\treturn { repos: {} };\n\t}\n\n\ttry {\n\t\tconst content = readFileSync(mapPath, \"utf-8\");\n\t\tconst data = JSON.parse(content);\n\t\treturn GlobalMapSchema.parse(data);\n\t} catch {\n\t\treturn { repos: {} };\n\t}\n}\n\n/**\n * Writes the global map to ~/.local/share/offworld/skill/offworld/assets/map.json\n * Creates directory if it doesn't exist\n */\nexport function writeGlobalMap(map: GlobalMap): void {\n\tconst mapPath = Paths.offworldGlobalMapPath;\n\tconst mapDir = dirname(mapPath);\n\n\tif (!existsSync(mapDir)) {\n\t\tmkdirSync(mapDir, { recursive: true });\n\t}\n\n\tconst validated = GlobalMapSchema.parse(map);\n\twriteFileSync(mapPath, JSON.stringify(validated, null, 2), \"utf-8\");\n}\n\n/**\n * Adds or updates a repo entry in the global map\n *\n * @param qualifiedName - The qualified repo name (owner/repo)\n * @param entry - The map entry to add/update\n */\nexport function upsertGlobalMapEntry(qualifiedName: string, entry: GlobalMapRepoEntry): void {\n\tconst map = readGlobalMap();\n\tmap.repos[qualifiedName] = entry;\n\twriteGlobalMap(map);\n}\n\n/**\n * Removes a repo entry from the global map\n *\n * @param qualifiedName - The qualified repo name (owner/repo)\n * @returns true if repo was removed, false if not found\n */\nexport function removeGlobalMapEntry(qualifiedName: string): boolean {\n\tconst map = readGlobalMap();\n\n\tif (!(qualifiedName in map.repos)) {\n\t\treturn false;\n\t}\n\n\tdelete map.repos[qualifiedName];\n\twriteGlobalMap(map);\n\treturn true;\n}\n\n/**\n * Writes a project map to ./.offworld/map.json\n *\n * @param projectRoot - Absolute path to project root\n * @param entries - Map of qualified repo names to project map entries\n */\nexport function writeProjectMap(\n\tprojectRoot: string,\n\tentries: Record<string, ProjectMapRepoEntry>,\n): void {\n\tconst mapPath = join(projectRoot, \".offworld\", \"map.json\");\n\tconst mapDir = dirname(mapPath);\n\n\tif (!existsSync(mapDir)) {\n\t\tmkdirSync(mapDir, { recursive: true });\n\t}\n\n\tconst projectMap: ProjectMap = {\n\t\tversion: 1,\n\t\tscope: \"project\",\n\t\tglobalMapPath: Paths.offworldGlobalMapPath,\n\t\trepos: entries,\n\t};\n\n\tconst validated = ProjectMapSchema.parse(projectMap);\n\twriteFileSync(mapPath, JSON.stringify(validated, null, 2), \"utf-8\");\n}\n","/**\n * Git clone and repository management utilities\n */\n\nimport { existsSync, readdirSync, rmSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { execFileSync, spawn } from \"node:child_process\";\nimport type { Config, RemoteRepoSource } from \"@offworld/types\";\nimport { getRepoPath, loadConfig, toReferenceFileName } from \"./config.js\";\nimport { readGlobalMap, upsertGlobalMapEntry, removeGlobalMapEntry } from \"./index-manager.js\";\nimport { Paths } from \"./paths.js\";\n\nexport class CloneError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"CloneError\";\n\t}\n}\n\nexport class RepoExistsError extends CloneError {\n\tconstructor(path: string) {\n\t\tsuper(`Repository already exists at: ${path}`);\n\t\tthis.name = \"RepoExistsError\";\n\t}\n}\n\nexport class RepoNotFoundError extends CloneError {\n\tconstructor(qualifiedName: string) {\n\t\tsuper(`Repository not found in index: ${qualifiedName}`);\n\t\tthis.name = \"RepoNotFoundError\";\n\t}\n}\n\nexport class GitError extends CloneError {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly command: string,\n\t\tpublic readonly exitCode: number | null,\n\t) {\n\t\tsuper(`Git command failed: ${message}`);\n\t\tthis.name = \"GitError\";\n\t}\n}\n\nexport interface CloneOptions {\n\t/** Use shallow clone (--depth 1) */\n\tshallow?: boolean;\n\t/** Clone specific branch */\n\tbranch?: string;\n\t/** Custom config for repo root path */\n\tconfig?: Config;\n\t/** Force clone even if directory exists (removes existing) */\n\tforce?: boolean;\n\t/** Use sparse checkout for large repos (only src/, lib/, packages/, docs/) */\n\tsparse?: boolean;\n}\n\nfunction execGit(args: string[], cwd?: string): string {\n\ttry {\n\t\tconst result = execFileSync(\"git\", args, {\n\t\t\tcwd,\n\t\t\tencoding: \"utf-8\",\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t});\n\t\treturn result.trim();\n\t} catch (error) {\n\t\tconst err = error as { status?: number; stderr?: Buffer | string; message?: string };\n\t\tconst stderr = err.stderr\n\t\t\t? typeof err.stderr === \"string\"\n\t\t\t\t? err.stderr\n\t\t\t\t: err.stderr.toString()\n\t\t\t: err.message || \"Unknown error\";\n\t\tthrow new GitError(stderr.trim(), `git ${args.join(\" \")}`, err.status ?? null);\n\t}\n}\n\nfunction execGitAsync(args: string[], cwd?: string): Promise<string> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst proc = spawn(\"git\", args, {\n\t\t\tcwd,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\tenv: { ...process.env, GIT_TERMINAL_PROMPT: \"0\" },\n\t\t});\n\n\t\tlet stdout = \"\";\n\t\tlet stderr = \"\";\n\n\t\tproc.stdout.on(\"data\", (data: Buffer) => {\n\t\t\tstdout += data.toString();\n\t\t});\n\t\tproc.stderr.on(\"data\", (data: Buffer) => {\n\t\t\tstderr += data.toString();\n\t\t});\n\n\t\tproc.on(\"close\", (code) => {\n\t\t\tif (code === 0) {\n\t\t\t\tresolve(stdout.trim());\n\t\t\t} else {\n\t\t\t\treject(new GitError(stderr.trim() || \"Unknown error\", `git ${args.join(\" \")}`, code));\n\t\t\t}\n\t\t});\n\n\t\tproc.on(\"error\", (err) => {\n\t\t\treject(new GitError(err.message, `git ${args.join(\" \")}`, null));\n\t\t});\n\t});\n}\n\nexport function getCommitSha(repoPath: string): string {\n\treturn execGit([\"rev-parse\", \"HEAD\"], repoPath);\n}\n\nexport function getCommitDistance(\n\trepoPath: string,\n\tolderSha: string,\n\tnewerSha = \"HEAD\",\n): number | null {\n\ttry {\n\t\ttry {\n\t\t\texecGit([\"cat-file\", \"-e\", olderSha], repoPath);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t\tconst count = execGit([\"rev-list\", \"--count\", `${olderSha}..${newerSha}`], repoPath);\n\t\treturn Number.parseInt(count, 10);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nconst SPARSE_CHECKOUT_DIRS = [\"src\", \"lib\", \"packages\", \"docs\", \"README.md\", \"package.json\"];\n\n/**\n * Clone a remote repository to the local repo root.\n *\n * @param source - Remote repo source from parseRepoInput()\n * @param options - Clone options (shallow, branch, config)\n * @returns The local path where the repo was cloned\n * @throws RepoExistsError if repo already exists (unless force is true)\n * @throws GitError if clone fails\n */\nexport async function cloneRepo(\n\tsource: RemoteRepoSource,\n\toptions: CloneOptions = {},\n): Promise<string> {\n\tconst config = options.config ?? loadConfig();\n\tconst repoPath = getRepoPath(source.fullName, source.provider, config);\n\n\tif (existsSync(repoPath)) {\n\t\tif (options.force) {\n\t\t\trmSync(repoPath, { recursive: true, force: true });\n\t\t} else {\n\t\t\tthrow new RepoExistsError(repoPath);\n\t\t}\n\t}\n\n\ttry {\n\t\tif (options.sparse) {\n\t\t\tawait cloneSparse(source.cloneUrl, repoPath, options);\n\t\t} else {\n\t\t\tawait cloneStandard(source.cloneUrl, repoPath, options);\n\t\t}\n\t} catch (err) {\n\t\tcleanupEmptyParentDirs(repoPath);\n\t\tthrow err;\n\t}\n\n\tconst referenceFileName = toReferenceFileName(source.fullName);\n\tconst referencePath = join(Paths.offworldReferencesDir, referenceFileName);\n\tconst hasReference = existsSync(referencePath);\n\n\tupsertGlobalMapEntry(source.qualifiedName, {\n\t\tlocalPath: repoPath,\n\t\treferences: hasReference ? [referenceFileName] : [],\n\t\tprimary: hasReference ? referenceFileName : \"\",\n\t\tkeywords: [],\n\t\tupdatedAt: new Date().toISOString(),\n\t});\n\n\treturn repoPath;\n}\n\nfunction cleanupEmptyParentDirs(repoPath: string): void {\n\tconst ownerDir = dirname(repoPath);\n\tif (existsSync(ownerDir) && readdirSync(ownerDir).length === 0) {\n\t\trmSync(ownerDir, { recursive: true, force: true });\n\t}\n}\n\nasync function cloneStandard(\n\tcloneUrl: string,\n\trepoPath: string,\n\toptions: CloneOptions,\n): Promise<void> {\n\tconst args = [\"clone\"];\n\n\tif (options.shallow) {\n\t\targs.push(\"--depth\", \"1\");\n\t}\n\n\tif (options.branch) {\n\t\targs.push(\"--branch\", options.branch);\n\t}\n\n\targs.push(cloneUrl, repoPath);\n\tawait execGitAsync(args);\n}\n\nasync function cloneSparse(\n\tcloneUrl: string,\n\trepoPath: string,\n\toptions: CloneOptions,\n): Promise<void> {\n\tconst args = [\"clone\", \"--filter=blob:none\", \"--no-checkout\", \"--sparse\"];\n\n\tif (options.shallow) {\n\t\targs.push(\"--depth\", \"1\");\n\t}\n\n\tif (options.branch) {\n\t\targs.push(\"--branch\", options.branch);\n\t}\n\n\targs.push(cloneUrl, repoPath);\n\tawait execGitAsync(args);\n\n\tawait execGitAsync([\"sparse-checkout\", \"set\", ...SPARSE_CHECKOUT_DIRS], repoPath);\n\tawait execGitAsync([\"checkout\"], repoPath);\n}\n\nexport function isShallowClone(repoPath: string): boolean {\n\ttry {\n\t\tconst result = execGit([\"rev-parse\", \"--is-shallow-repository\"], repoPath);\n\t\treturn result === \"true\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport async function unshallowRepo(repoPath: string): Promise<boolean> {\n\tif (!isShallowClone(repoPath)) {\n\t\treturn false;\n\t}\n\n\tawait execGitAsync([\"fetch\", \"--unshallow\"], repoPath);\n\treturn true;\n}\n\nexport interface UpdateResult {\n\t/** Whether any updates were fetched */\n\tupdated: boolean;\n\t/** Previous commit SHA before update */\n\tpreviousSha: string;\n\t/** Current commit SHA after update */\n\tcurrentSha: string;\n\t/** Whether the repo was unshallowed */\n\tunshallowed?: boolean;\n}\n\nexport interface UpdateOptions {\n\t/** Convert shallow clone to full clone */\n\tunshallow?: boolean;\n}\n\n/**\n * Update a cloned repository by running git fetch and pull.\n *\n * @param qualifiedName - The qualified name of the repo (e.g., \"github.com:owner/repo\")\n * @param options - Update options\n * @returns Update result with commit SHAs\n * @throws RepoNotFoundError if repo not in index\n * @throws GitError if fetch/pull fails\n */\nexport async function updateRepo(\n\tqualifiedName: string,\n\toptions: UpdateOptions = {},\n): Promise<UpdateResult> {\n\tconst map = readGlobalMap();\n\tconst entry = map.repos[qualifiedName];\n\tif (!entry) {\n\t\tthrow new RepoNotFoundError(qualifiedName);\n\t}\n\n\tconst repoPath = entry.localPath;\n\n\tif (!existsSync(repoPath)) {\n\t\tthrow new RepoNotFoundError(qualifiedName);\n\t}\n\n\tconst previousSha = getCommitSha(repoPath);\n\tlet unshallowed = false;\n\tif (options.unshallow) {\n\t\tunshallowed = await unshallowRepo(repoPath);\n\t}\n\n\tawait execGitAsync([\"fetch\"], repoPath);\n\tawait execGitAsync([\"pull\", \"--ff-only\"], repoPath);\n\n\tconst currentSha = getCommitSha(repoPath);\n\tupsertGlobalMapEntry(qualifiedName, {\n\t\t...entry,\n\t\tupdatedAt: new Date().toISOString(),\n\t});\n\n\treturn {\n\t\tupdated: previousSha !== currentSha,\n\t\tpreviousSha,\n\t\tcurrentSha,\n\t\tunshallowed,\n\t};\n}\n\nexport interface RemoveOptions {\n\treferenceOnly?: boolean;\n\trepoOnly?: boolean;\n}\n\nexport async function removeRepo(\n\tqualifiedName: string,\n\toptions: RemoveOptions = {},\n): Promise<boolean> {\n\tconst map = readGlobalMap();\n\tconst entry = map.repos[qualifiedName];\n\tif (!entry) {\n\t\treturn false;\n\t}\n\n\tconst { referenceOnly = false, repoOnly = false } = options;\n\tconst removeRepoFiles = !referenceOnly;\n\tconst removeReferenceFiles = !repoOnly;\n\n\tif (removeRepoFiles && existsSync(entry.localPath)) {\n\t\trmSync(entry.localPath, { recursive: true, force: true });\n\t\tcleanupEmptyParentDirs(entry.localPath);\n\t}\n\n\tif (removeReferenceFiles) {\n\t\tfor (const referenceFileName of entry.references) {\n\t\t\tconst referencePath = join(Paths.offworldReferencesDir, referenceFileName);\n\t\t\tif (existsSync(referencePath)) {\n\t\t\t\trmSync(referencePath, { force: true });\n\t\t\t}\n\t\t}\n\n\t\tif (entry.primary) {\n\t\t\tconst metaDirName = entry.primary.replace(/\\.md$/, \"\");\n\t\t\tconst metaPath = join(Paths.metaDir, metaDirName);\n\t\t\tif (existsSync(metaPath)) {\n\t\t\t\trmSync(metaPath, { recursive: true, force: true });\n\t\t\t}\n\t\t}\n\t}\n\n\tif (removeRepoFiles) {\n\t\tremoveGlobalMapEntry(qualifiedName);\n\t} else if (removeReferenceFiles) {\n\t\tupsertGlobalMapEntry(qualifiedName, {\n\t\t\t...entry,\n\t\t\treferences: [],\n\t\t\tprimary: \"\",\n\t\t});\n\t}\n\n\treturn true;\n}\n\nexport function listRepos(): string[] {\n\tconst map = readGlobalMap();\n\treturn Object.keys(map.repos);\n}\n\nexport function isRepoCloned(qualifiedName: string): boolean {\n\tconst map = readGlobalMap();\n\tconst entry = map.repos[qualifiedName];\n\tif (!entry) return false;\n\treturn existsSync(entry.localPath);\n}\n\n/**\n * Get the local path for a cloned repository.\n *\n * @param qualifiedName - The qualified name of the repo\n * @returns The local path or undefined if not cloned\n */\nexport function getClonedRepoPath(qualifiedName: string): string | undefined {\n\tconst map = readGlobalMap();\n\tconst entry = map.repos[qualifiedName];\n\tif (!entry) return undefined;\n\tif (!existsSync(entry.localPath)) return undefined;\n\treturn entry.localPath;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwBA,SAAgB,gBAA2B;CAC1C,MAAM,UAAU,MAAM;AAEtB,KAAI,CAAC,WAA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