@offworld/sdk 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.d.mts.map +1 -1
- package/dist/ai/index.mjs +22 -0
- package/dist/ai/index.mjs.map +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/internal.d.mts +2 -2
- package/dist/internal.d.mts.map +1 -1
- package/dist/internal.mjs +10 -18
- package/dist/internal.mjs.map +1 -1
- package/dist/{public-DbZeh2Mr.mjs → public-BUgna8vR.mjs} +187 -146
- package/dist/public-BUgna8vR.mjs.map +1 -0
- package/dist/{public-MYVLaKUi.d.mts → public-DzjgxrUm.d.mts} +10 -3
- package/dist/{public-MYVLaKUi.d.mts.map → public-DzjgxrUm.d.mts.map} +1 -1
- package/package.json +3 -3
- package/dist/public-DbZeh2Mr.mjs.map +0 -1
package/dist/ai/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/ai/opencode.ts","../../src/ai/errors.ts","../../src/generate.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/ai/opencode.ts","../../src/ai/errors.ts","../../src/generate.ts"],"mappings":";cAca,mBAAA;AAAA,cACA,gBAAA;AAAA,UAEI,mBAAA;EAChB,MAAA;EACA,GAAA;EACA,YAAA;EACA,QAAA;EAEA,KAAA;;EAEA,SAAA;EACA,OAAA,IAAW,OAAA;EACX,QAAA,IAAY,IAAA;AAAA;AAAA,UAGI,kBAAA;EAChB,IAAA;EACA,SAAA;EACA,UAAA;AAAA;AAAA,iBAyLqB,YAAA,CAAa,OAAA,EAAS,mBAAA,GAAsB,OAAA,CAAQ,kBAAA;;;;AA5M1E;;cCXa,sBAAA,SAA+B,KAAA;EAAA,SAI1B,OAAA;EAAA,SAHR,IAAA;cAER,OAAA,UACgB,OAAA;AAAA;;;;cA0BL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ai/index.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { d as toReferenceName, s as loadConfig } from "../config-DW8J4gl5.mjs";
|
|
2
2
|
import { c as getCommitSha } from "../clone-DyLvmbJZ.mjs";
|
|
3
|
+
import { execSync } from "node:child_process";
|
|
3
4
|
import { z } from "zod";
|
|
4
5
|
|
|
5
6
|
//#region src/ai/errors.ts
|
|
@@ -15,6 +16,19 @@ var OpenCodeReferenceError = class extends Error {
|
|
|
15
16
|
}
|
|
16
17
|
};
|
|
17
18
|
/**
|
|
19
|
+
* Error when the opencode CLI binary is not installed
|
|
20
|
+
*/
|
|
21
|
+
var OpenCodeNotInstalledError = class extends OpenCodeReferenceError {
|
|
22
|
+
_tag = "OpenCodeNotInstalledError";
|
|
23
|
+
hint;
|
|
24
|
+
constructor() {
|
|
25
|
+
const hint = "opencode is required for local AI reference generation. Install it: curl -fsSL https://opencode.ai/install | bash";
|
|
26
|
+
super(`opencode is not installed. ${hint}`);
|
|
27
|
+
this.name = "OpenCodeNotInstalledError";
|
|
28
|
+
this.hint = hint;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
18
32
|
* Error when the @opencode-ai/sdk package is not installed or invalid
|
|
19
33
|
*/
|
|
20
34
|
var OpenCodeSDKError = class extends OpenCodeReferenceError {
|
|
@@ -387,11 +401,19 @@ const DEFAULT_AI_PROVIDER = "opencode";
|
|
|
387
401
|
const DEFAULT_AI_MODEL = "claude-opus-4-5";
|
|
388
402
|
let cachedCreateOpencode = null;
|
|
389
403
|
let cachedCreateOpencodeClient = null;
|
|
404
|
+
function assertOpenCodeInstalled() {
|
|
405
|
+
try {
|
|
406
|
+
execSync("opencode --version", { stdio: "ignore" });
|
|
407
|
+
} catch {
|
|
408
|
+
throw new OpenCodeNotInstalledError();
|
|
409
|
+
}
|
|
410
|
+
}
|
|
390
411
|
async function getOpenCodeSDK() {
|
|
391
412
|
if (cachedCreateOpencode && cachedCreateOpencodeClient) return {
|
|
392
413
|
createOpencode: cachedCreateOpencode,
|
|
393
414
|
createOpencodeClient: cachedCreateOpencodeClient
|
|
394
415
|
};
|
|
416
|
+
assertOpenCodeInstalled();
|
|
395
417
|
try {
|
|
396
418
|
const sdk = await import("@opencode-ai/sdk");
|
|
397
419
|
if (typeof sdk.createOpencode !== "function" || typeof sdk.createOpencodeClient !== "function") throw new OpenCodeSDKError("SDK missing required exports");
|
package/dist/ai/index.mjs.map
CHANGED
|
@@ -1 +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,O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ZuB;EAC5B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,CAE8C,QAAQ,MAAM,QAAQ,SAAS,EAAE,CAAC;AACjF,KAAI,kBAAkB,SAAS,EAC9B,OAAM,IAAI,MACT,8DAA8D,kBAAkB,MAAM,GAAG,EAAE,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"}
|
|
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 CLI binary is not installed\n */\nexport class OpenCodeNotInstalledError extends OpenCodeReferenceError {\n\treadonly _tag = \"OpenCodeNotInstalledError\" as const;\n\treadonly hint: string;\n\n\tconstructor() {\n\t\tconst hint =\n\t\t\t\"opencode is required for local AI reference generation. Install it: curl -fsSL https://opencode.ai/install | bash\";\n\t\tsuper(`opencode is not installed. ${hint}`);\n\t\tthis.name = \"OpenCodeNotInstalledError\";\n\t\tthis.hint = hint;\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 { execSync } from \"node:child_process\";\nimport {\n\tOpenCodeReferenceError,\n\tOpenCodeSDKError,\n\tOpenCodeNotInstalledError,\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\nfunction assertOpenCodeInstalled(): void {\n\ttry {\n\t\texecSync(\"opencode --version\", { stdio: \"ignore\" });\n\t} catch {\n\t\tthrow new OpenCodeNotInstalledError();\n\t}\n}\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\tassertOpenCodeInstalled();\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;EA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CAAgC,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"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
export { AgentConfig, AuthData, AuthError, AuthStatus, CloneError, CloneOptions, Config, DEFAULT_IGNORE_PATTERNS, Dependency, DiscoverOptions, DiscoverResult, FALLBACK_MAPPINGS, FileIndex, FileIndexEntry, FileRole, GcOptions, GcResult, GetMapEntryOptions, GitError, GlobalMap, GlobalMapRepoEntry, InstallReferenceMeta, ManifestType, MapEntry, ModelInfo, NotGitRepoError, NotLoggedInError, PathNotFoundError, Paths, ProjectMap, ProjectMapRepoEntry, ProviderInfo, ProviderWithModels, PruneOptions, PruneResult, ReferenceMatch, ReferenceStatus, RemoveOptions, RepoExistsError, RepoNotFoundError, RepoSource, RepoSourceError, RepoStatusOptions, RepoStatusSummary, ResolvedDep, SearchMapOptions, SearchResult, TokenExpiredError, UpdateAllOptions, UpdateAllResult, UpdateOptions, UpdateResult, VERSION, agents, clearAuthData, cloneRepo, detectInstalledAgents, detectManifestType, discoverRepos, expandTilde, gcRepos, getAgentConfig, getAllAgentConfigs, getAuthPath, getAuthStatus, getClonedRepoPath, getCommitDistance, getCommitSha, getConfigPath, getMapEntry, getMetaPath, getMetaRoot, getProjectMapPath, getProvider, getReferenceFileNameForSource, getReferencePath, getRepoPath, getRepoRoot, getRepoStatus, getToken, getTokenOrNull, installGlobalSkill, installReference, isLoggedIn, isReferenceInstalled, isRepoCloned, isShallowClone, listProviders, listProvidersWithModels, listRepos, loadAuthData, loadConfig, matchDependenciesToReferences, matchDependenciesToReferencesWithRemoteCheck, parseDependencies, parseRepoInput, pruneRepos, readGlobalMap, refreshAccessToken, removeGlobalMapEntry, removeRepo, resolveDependencyRepo, resolveFromNpm, resolveRepoKey, saveAuthData, saveConfig, searchMap, toMetaDirName, toReferenceFileName, toReferenceName, unshallowRepo, updateAllRepos, updateRepo, upsertGlobalMapEntry, validateProviderModel, writeGlobalMap, writeProjectMap };
|
|
1
|
+
import { $ as installReference, $t as getConfigPath, A as pruneRepos, At as removeRepo, B as resolveDependencyRepo, Bt as searchMap, C as RepoStatusOptions, Ct as cloneRepo, D as discoverRepos, Dt as isRepoCloned, E as UpdateAllResult, Et as getCommitSha, F as matchDependenciesToReferences, Ft as SearchMapOptions, G as parseDependencies, Gt as writeProjectMap, H as Dependency, Ht as removeGlobalMapEntry, I as matchDependenciesToReferencesWithRemoteCheck, It as SearchResult, J as detectInstalledAgents, Jt as RepoSourceError, K as AgentConfig, Kt as NotGitRepoError, L as FALLBACK_MAPPINGS, Lt as getMapEntry, M as ReferenceMatch, Mt as updateRepo, N as ReferenceStatus, Nt as GetMapEntryOptions, O as gcRepos, Ot as isShallowClone, P as isReferenceInstalled, Pt as MapEntry, Q as installGlobalSkill, Qt as expandTilde, R as ResolvedDep, Rt as getProjectMapPath, S as PruneResult, St as UpdateResult, T as UpdateAllOptions, Tt as getCommitDistance, U as ManifestType, Ut as upsertGlobalMapEntry, V as resolveFromNpm, Vt as readGlobalMap, W as detectManifestType, Wt as writeGlobalMap, X as getAllAgentConfigs, Xt as parseRepoInput, Y as getAgentConfig, Yt as getReferenceFileNameForSource, Z as InstallReferenceMeta, Zt as Paths, _ as DiscoverOptions, _t as GitError, a as GlobalMap, an as loadConfig, at as TokenExpiredError, b as GcResult, bt as RepoNotFoundError, c as ProjectMapRepoEntry, cn as toReferenceFileName, ct as getAuthStatus, d as ProviderInfo, dn as VERSION, dt as isLoggedIn, en as getMetaPath, et as resolveReferenceKeywords, f as ProviderWithModels, ft as loadAuthData, g as validateProviderModel, gt as CloneOptions, h as listProvidersWithModels, ht as CloneError, i as FileRole, in as getRepoRoot, it as NotLoggedInError, j as updateAllRepos, jt as unshallowRepo, k as getRepoStatus, kt as listRepos, l as RepoSource, ln as toReferenceName, lt as getToken, m as listProviders, mt as saveAuthData, n as FileIndex, nn as getReferencePath, nt as AuthError, o as GlobalMapRepoEntry, on as saveConfig, ot as clearAuthData, p as getProvider, pt as refreshAccessToken, q as agents, qt as PathNotFoundError, r as FileIndexEntry, rn as getRepoPath, rt as AuthStatus, s as ProjectMap, sn as toMetaDirName, st as getAuthPath, t as Config, tn as getMetaRoot, tt as AuthData, u as ModelInfo, un as DEFAULT_IGNORE_PATTERNS, ut as getTokenOrNull, v as DiscoverResult, vt as RemoveOptions, w as RepoStatusSummary, wt as getClonedRepoPath, x as PruneOptions, xt as UpdateOptions, y as GcOptions, yt as RepoExistsError, z as getNpmKeywords, zt as resolveRepoKey } from "./public-DzjgxrUm.mjs";
|
|
2
|
+
export { AgentConfig, AuthData, AuthError, AuthStatus, CloneError, CloneOptions, Config, DEFAULT_IGNORE_PATTERNS, Dependency, DiscoverOptions, DiscoverResult, FALLBACK_MAPPINGS, FileIndex, FileIndexEntry, FileRole, GcOptions, GcResult, GetMapEntryOptions, GitError, GlobalMap, GlobalMapRepoEntry, InstallReferenceMeta, ManifestType, MapEntry, ModelInfo, NotGitRepoError, NotLoggedInError, PathNotFoundError, Paths, ProjectMap, ProjectMapRepoEntry, ProviderInfo, ProviderWithModels, PruneOptions, PruneResult, ReferenceMatch, ReferenceStatus, RemoveOptions, RepoExistsError, RepoNotFoundError, RepoSource, RepoSourceError, RepoStatusOptions, RepoStatusSummary, ResolvedDep, SearchMapOptions, SearchResult, TokenExpiredError, UpdateAllOptions, UpdateAllResult, UpdateOptions, UpdateResult, VERSION, agents, clearAuthData, cloneRepo, detectInstalledAgents, detectManifestType, discoverRepos, expandTilde, gcRepos, getAgentConfig, getAllAgentConfigs, getAuthPath, getAuthStatus, getClonedRepoPath, getCommitDistance, getCommitSha, getConfigPath, getMapEntry, getMetaPath, getMetaRoot, getNpmKeywords, getProjectMapPath, getProvider, getReferenceFileNameForSource, getReferencePath, getRepoPath, getRepoRoot, getRepoStatus, getToken, getTokenOrNull, installGlobalSkill, installReference, isLoggedIn, isReferenceInstalled, isRepoCloned, isShallowClone, listProviders, listProvidersWithModels, listRepos, loadAuthData, loadConfig, matchDependenciesToReferences, matchDependenciesToReferencesWithRemoteCheck, parseDependencies, parseRepoInput, pruneRepos, readGlobalMap, refreshAccessToken, removeGlobalMapEntry, removeRepo, resolveDependencyRepo, resolveFromNpm, resolveReferenceKeywords, resolveRepoKey, saveAuthData, saveConfig, searchMap, toMetaDirName, toReferenceFileName, toReferenceName, unshallowRepo, updateAllRepos, updateRepo, upsertGlobalMapEntry, validateProviderModel, writeGlobalMap, writeProjectMap };
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as
|
|
1
|
+
import { A as getAuthPath, B as resolveRepoKey, C as detectInstalledAgents, D as NotLoggedInError, E as AuthError, F as loadAuthData, G as getReferenceFileNameForSource, H as NotGitRepoError, I as refreshAccessToken, J as VERSION, K as parseRepoInput, L as saveAuthData, M as getToken, N as getTokenOrNull, O as TokenExpiredError, P as isLoggedIn, R as getMapEntry, S as agents, T as getAllAgentConfigs, U as PathNotFoundError, V as searchMap, W as RepoSourceError, _ as resolveReferenceKeywords, a as discoverRepos, b as resolveDependencyRepo, c as pruneRepos, d as matchDependenciesToReferences, f as matchDependenciesToReferencesWithRemoteCheck, g as installReference, h as installGlobalSkill, i as validateProviderModel, j as getAuthStatus, k as clearAuthData, l as updateAllRepos, m as parseDependencies, n as listProviders, o as gcRepos, p as detectManifestType, q as DEFAULT_IGNORE_PATTERNS, r as listProvidersWithModels, s as getRepoStatus, t as getProvider, u as isReferenceInstalled, v as FALLBACK_MAPPINGS, w as getAgentConfig, x as resolveFromNpm, y as getNpmKeywords, z as getProjectMapPath } from "./public-BUgna8vR.mjs";
|
|
2
2
|
import { a as getRepoPath, c as saveConfig, d as toReferenceName, f as Paths, i as getReferencePath, l as toMetaDirName, n as getMetaPath, o as getRepoRoot, p as expandTilde, r as getMetaRoot, s as loadConfig, t as getConfigPath, u as toReferenceFileName } from "./config-DW8J4gl5.mjs";
|
|
3
3
|
import { _ as upsertGlobalMapEntry, a as cloneRepo, c as getCommitSha, d as listRepos, f as removeRepo, g as removeGlobalMapEntry, h as readGlobalMap, i as RepoNotFoundError, l as isRepoCloned, m as updateRepo, n as GitError, o as getClonedRepoPath, p as unshallowRepo, r as RepoExistsError, s as getCommitDistance, t as CloneError, u as isShallowClone, v as writeGlobalMap, y as writeProjectMap } from "./clone-DyLvmbJZ.mjs";
|
|
4
4
|
|
|
5
|
-
export { AuthError, CloneError, DEFAULT_IGNORE_PATTERNS, FALLBACK_MAPPINGS, GitError, NotGitRepoError, NotLoggedInError, PathNotFoundError, Paths, RepoExistsError, RepoNotFoundError, RepoSourceError, TokenExpiredError, VERSION, agents, clearAuthData, cloneRepo, detectInstalledAgents, detectManifestType, discoverRepos, expandTilde, gcRepos, getAgentConfig, getAllAgentConfigs, getAuthPath, getAuthStatus, getClonedRepoPath, getCommitDistance, getCommitSha, getConfigPath, getMapEntry, getMetaPath, getMetaRoot, getProjectMapPath, getProvider, getReferenceFileNameForSource, getReferencePath, getRepoPath, getRepoRoot, getRepoStatus, getToken, getTokenOrNull, installGlobalSkill, installReference, isLoggedIn, isReferenceInstalled, isRepoCloned, isShallowClone, listProviders, listProvidersWithModels, listRepos, loadAuthData, loadConfig, matchDependenciesToReferences, matchDependenciesToReferencesWithRemoteCheck, parseDependencies, parseRepoInput, pruneRepos, readGlobalMap, refreshAccessToken, removeGlobalMapEntry, removeRepo, resolveDependencyRepo, resolveFromNpm, resolveRepoKey, saveAuthData, saveConfig, searchMap, toMetaDirName, toReferenceFileName, toReferenceName, unshallowRepo, updateAllRepos, updateRepo, upsertGlobalMapEntry, validateProviderModel, writeGlobalMap, writeProjectMap };
|
|
5
|
+
export { AuthError, CloneError, DEFAULT_IGNORE_PATTERNS, FALLBACK_MAPPINGS, GitError, NotGitRepoError, NotLoggedInError, PathNotFoundError, Paths, RepoExistsError, RepoNotFoundError, RepoSourceError, TokenExpiredError, VERSION, agents, clearAuthData, cloneRepo, detectInstalledAgents, detectManifestType, discoverRepos, expandTilde, gcRepos, getAgentConfig, getAllAgentConfigs, getAuthPath, getAuthStatus, getClonedRepoPath, getCommitDistance, getCommitSha, getConfigPath, getMapEntry, getMetaPath, getMetaRoot, getNpmKeywords, getProjectMapPath, getProvider, getReferenceFileNameForSource, getReferencePath, getRepoPath, getRepoRoot, getRepoStatus, getToken, getTokenOrNull, installGlobalSkill, installReference, isLoggedIn, isReferenceInstalled, isRepoCloned, isShallowClone, listProviders, listProvidersWithModels, listRepos, loadAuthData, loadConfig, matchDependenciesToReferences, matchDependenciesToReferencesWithRemoteCheck, parseDependencies, parseRepoInput, pruneRepos, readGlobalMap, refreshAccessToken, removeGlobalMapEntry, removeRepo, resolveDependencyRepo, resolveFromNpm, resolveReferenceKeywords, resolveRepoKey, saveAuthData, saveConfig, searchMap, toMetaDirName, toReferenceFileName, toReferenceName, unshallowRepo, updateAllRepos, updateRepo, upsertGlobalMapEntry, validateProviderModel, writeGlobalMap, writeProjectMap };
|
package/dist/internal.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as
|
|
1
|
+
import { $ as installReference, $t as getConfigPath, A as pruneRepos, At as removeRepo, B as resolveDependencyRepo, Bt as searchMap, C as RepoStatusOptions, Ct as cloneRepo, D as discoverRepos, Dt as isRepoCloned, E as UpdateAllResult, Et as getCommitSha, F as matchDependenciesToReferences, Ft as SearchMapOptions, G as parseDependencies, Gt as writeProjectMap, H as Dependency, Ht as removeGlobalMapEntry, I as matchDependenciesToReferencesWithRemoteCheck, It as SearchResult, J as detectInstalledAgents, Jt as RepoSourceError, K as AgentConfig, Kt as NotGitRepoError, L as FALLBACK_MAPPINGS, Lt as getMapEntry, M as ReferenceMatch, Mt as updateRepo, N as ReferenceStatus, Nt as GetMapEntryOptions, O as gcRepos, Ot as isShallowClone, P as isReferenceInstalled, Pt as MapEntry, Q as installGlobalSkill, Qt as expandTilde, R as ResolvedDep, Rt as getProjectMapPath, S as PruneResult, St as UpdateResult, T as UpdateAllOptions, Tt as getCommitDistance, U as ManifestType, Ut as upsertGlobalMapEntry, V as resolveFromNpm, Vt as readGlobalMap, W as detectManifestType, Wt as writeGlobalMap, X as getAllAgentConfigs, Xt as parseRepoInput, Y as getAgentConfig, Yt as getReferenceFileNameForSource, Z as InstallReferenceMeta, Zt as Paths, _ as DiscoverOptions, _t as GitError, a as GlobalMap, an as loadConfig, at as TokenExpiredError, b as GcResult, bt as RepoNotFoundError, c as ProjectMapRepoEntry, cn as toReferenceFileName, ct as getAuthStatus, d as ProviderInfo, dn as VERSION, dt as isLoggedIn, en as getMetaPath, et as resolveReferenceKeywords, f as ProviderWithModels, ft as loadAuthData, g as validateProviderModel, gt as CloneOptions, h as listProvidersWithModels, ht as CloneError, i as FileRole, in as getRepoRoot, it as NotLoggedInError, j as updateAllRepos, jt as unshallowRepo, k as getRepoStatus, kt as listRepos, l as RepoSource, ln as toReferenceName, lt as getToken, m as listProviders, mt as saveAuthData, n as FileIndex, nn as getReferencePath, nt as AuthError, o as GlobalMapRepoEntry, on as saveConfig, ot as clearAuthData, p as getProvider, pt as refreshAccessToken, q as agents, qt as PathNotFoundError, r as FileIndexEntry, rn as getRepoPath, rt as AuthStatus, s as ProjectMap, sn as toMetaDirName, st as getAuthPath, t as Config, tn as getMetaRoot, tt as AuthData, u as ModelInfo, un as DEFAULT_IGNORE_PATTERNS, ut as getTokenOrNull, v as DiscoverResult, vt as RemoveOptions, w as RepoStatusSummary, wt as getClonedRepoPath, x as PruneOptions, xt as UpdateOptions, y as GcOptions, yt as RepoExistsError, z as getNpmKeywords, zt as resolveRepoKey } from "./public-DzjgxrUm.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/agents-md.d.ts
|
|
4
4
|
/**
|
|
@@ -65,5 +65,5 @@ declare function getShellConfigFiles(): string[];
|
|
|
65
65
|
*/
|
|
66
66
|
declare function cleanShellConfig(filePath: string): boolean;
|
|
67
67
|
//#endregion
|
|
68
|
-
export { AgentConfig, AuthData, AuthError, AuthStatus, CloneError, CloneOptions, Config, DEFAULT_IGNORE_PATTERNS, Dependency, DiscoverOptions, DiscoverResult, FALLBACK_MAPPINGS, FileIndex, FileIndexEntry, FileRole, GcOptions, GcResult, GetMapEntryOptions, GitError, GlobalMap, GlobalMapRepoEntry, type InstallMethod, InstallReferenceMeta, type InstalledReference, ManifestType, MapEntry, ModelInfo, NotGitRepoError, NotLoggedInError, PathNotFoundError, Paths, ProjectMap, ProjectMapRepoEntry, ProviderInfo, ProviderWithModels, PruneOptions, PruneResult, ReferenceMatch, ReferenceStatus, RemoveOptions, RepoExistsError, RepoNotFoundError, RepoSource, RepoSourceError, RepoStatusOptions, RepoStatusSummary, ResolvedDep, SearchMapOptions, SearchResult, TokenExpiredError, UpdateAllOptions, UpdateAllResult, UpdateOptions, UpdateResult, VERSION, agents, appendReferencesSection, cleanShellConfig, clearAuthData, cloneRepo, detectInstallMethod, detectInstalledAgents, detectManifestType, discoverRepos, executeUninstall, executeUpgrade, expandTilde, fetchLatestVersion, gcRepos, getAgentConfig, getAllAgentConfigs, getAuthPath, getAuthStatus, getClonedRepoPath, getCommitDistance, getCommitSha, getConfigPath, getCurrentVersion, getMapEntry, getMetaPath, getMetaRoot, getProjectMapPath, getProvider, getReferenceFileNameForSource, getReferencePath, getRepoPath, getRepoRoot, getRepoStatus, getShellConfigFiles, getToken, getTokenOrNull, installGlobalSkill, installReference, isLoggedIn, isReferenceInstalled, isRepoCloned, isShallowClone, listProviders, listProvidersWithModels, listRepos, loadAuthData, loadConfig, matchDependenciesToReferences, matchDependenciesToReferencesWithRemoteCheck, parseDependencies, parseRepoInput, pruneRepos, readGlobalMap, refreshAccessToken, removeGlobalMapEntry, removeRepo, resolveDependencyRepo, resolveFromNpm, resolveRepoKey, saveAuthData, saveConfig, searchMap, toMetaDirName, toReferenceFileName, toReferenceName, unshallowRepo, updateAgentFiles, updateAllRepos, updateRepo, upsertGlobalMapEntry, validateProviderModel, writeGlobalMap, writeProjectMap };
|
|
68
|
+
export { AgentConfig, AuthData, AuthError, AuthStatus, CloneError, CloneOptions, Config, DEFAULT_IGNORE_PATTERNS, Dependency, DiscoverOptions, DiscoverResult, FALLBACK_MAPPINGS, FileIndex, FileIndexEntry, FileRole, GcOptions, GcResult, GetMapEntryOptions, GitError, GlobalMap, GlobalMapRepoEntry, type InstallMethod, InstallReferenceMeta, type InstalledReference, ManifestType, MapEntry, ModelInfo, NotGitRepoError, NotLoggedInError, PathNotFoundError, Paths, ProjectMap, ProjectMapRepoEntry, ProviderInfo, ProviderWithModels, PruneOptions, PruneResult, ReferenceMatch, ReferenceStatus, RemoveOptions, RepoExistsError, RepoNotFoundError, RepoSource, RepoSourceError, RepoStatusOptions, RepoStatusSummary, ResolvedDep, SearchMapOptions, SearchResult, TokenExpiredError, UpdateAllOptions, UpdateAllResult, UpdateOptions, UpdateResult, VERSION, agents, appendReferencesSection, cleanShellConfig, clearAuthData, cloneRepo, detectInstallMethod, detectInstalledAgents, detectManifestType, discoverRepos, executeUninstall, executeUpgrade, expandTilde, fetchLatestVersion, gcRepos, getAgentConfig, getAllAgentConfigs, getAuthPath, getAuthStatus, getClonedRepoPath, getCommitDistance, getCommitSha, getConfigPath, getCurrentVersion, getMapEntry, getMetaPath, getMetaRoot, getNpmKeywords, getProjectMapPath, getProvider, getReferenceFileNameForSource, getReferencePath, getRepoPath, getRepoRoot, getRepoStatus, getShellConfigFiles, getToken, getTokenOrNull, installGlobalSkill, installReference, isLoggedIn, isReferenceInstalled, isRepoCloned, isShallowClone, listProviders, listProvidersWithModels, listRepos, loadAuthData, loadConfig, matchDependenciesToReferences, matchDependenciesToReferencesWithRemoteCheck, parseDependencies, parseRepoInput, pruneRepos, readGlobalMap, refreshAccessToken, removeGlobalMapEntry, removeRepo, resolveDependencyRepo, resolveFromNpm, resolveReferenceKeywords, resolveRepoKey, saveAuthData, saveConfig, searchMap, toMetaDirName, toReferenceFileName, toReferenceName, unshallowRepo, updateAgentFiles, updateAllRepos, updateRepo, upsertGlobalMapEntry, validateProviderModel, writeGlobalMap, writeProjectMap };
|
|
69
69
|
//# sourceMappingURL=internal.d.mts.map
|
package/dist/internal.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal.d.mts","names":[],"sources":["../src/agents-md.ts","../src/installation.ts"],"mappings":";;;;;;AASA;;UAAiB,kBAAA;EAAkB;EAElC,UAAA;EAEA;EAAA,SAAA;EAEI;EAAJ,IAAA;AAAA;;;;;;;;
|
|
1
|
+
{"version":3,"file":"internal.d.mts","names":[],"sources":["../src/agents-md.ts","../src/installation.ts"],"mappings":";;;;;;AASA;;UAAiB,kBAAA;EAAkB;EAElC,UAAA;EAEA;EAAA,SAAA;EAEI;EAAJ,IAAA;AAAA;;;;;;;;iBA2Be,uBAAA,CAAwB,QAAA,UAAkB,UAAA,EAAY,kBAAA;AAwBtE;;;;;;;AAAA,iBAAgB,gBAAA,CAAiB,WAAA,UAAqB,UAAA,EAAY,kBAAA;;;;;;KCpDtD,aAAA;;;;iBAKI,mBAAA,CAAA,GAAuB,aAAA;;;;iBAuFvB,iBAAA,CAAA;ADhEhB;;;AAAA,iBCuEsB,kBAAA,CAAmB,MAAA,GAAS,aAAA,GAAgB,OAAA;;;;iBAkClD,cAAA,CAAe,MAAA,EAAQ,aAAA,EAAe,OAAA,WAAkB,OAAA;;ADjFxE;;iBC4HgB,gBAAA,CAAiB,MAAA,EAAQ,aAAA,GAAgB,OAAA;;;;iBAkDzC,mBAAA,CAAA;;;;iBA0BA,gBAAA,CAAiB,QAAA"}
|
package/dist/internal.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as
|
|
1
|
+
import { A as getAuthPath, B as resolveRepoKey, C as detectInstalledAgents, D as NotLoggedInError, E as AuthError, F as loadAuthData, G as getReferenceFileNameForSource, H as NotGitRepoError, I as refreshAccessToken, J as VERSION, K as parseRepoInput, L as saveAuthData, M as getToken, N as getTokenOrNull, O as TokenExpiredError, P as isLoggedIn, R as getMapEntry, S as agents, T as getAllAgentConfigs, U as PathNotFoundError, V as searchMap, W as RepoSourceError, _ as resolveReferenceKeywords, a as discoverRepos, b as resolveDependencyRepo, c as pruneRepos, d as matchDependenciesToReferences, f as matchDependenciesToReferencesWithRemoteCheck, g as installReference, h as installGlobalSkill, i as validateProviderModel, j as getAuthStatus, k as clearAuthData, l as updateAllRepos, m as parseDependencies, n as listProviders, o as gcRepos, p as detectManifestType, q as DEFAULT_IGNORE_PATTERNS, r as listProvidersWithModels, s as getRepoStatus, t as getProvider, u as isReferenceInstalled, v as FALLBACK_MAPPINGS, w as getAgentConfig, x as resolveFromNpm, y as getNpmKeywords, z as getProjectMapPath } from "./public-BUgna8vR.mjs";
|
|
2
2
|
import { a as getRepoPath, c as saveConfig, d as toReferenceName, f as Paths, i as getReferencePath, l as toMetaDirName, n as getMetaPath, o as getRepoRoot, p as expandTilde, r as getMetaRoot, s as loadConfig, t as getConfigPath, u as toReferenceFileName } from "./config-DW8J4gl5.mjs";
|
|
3
3
|
import { _ as upsertGlobalMapEntry, a as cloneRepo, c as getCommitSha, d as listRepos, f as removeRepo, g as removeGlobalMapEntry, h as readGlobalMap, i as RepoNotFoundError, l as isRepoCloned, m as updateRepo, n as GitError, o as getClonedRepoPath, p as unshallowRepo, r as RepoExistsError, s as getCommitDistance, t as CloneError, u as isShallowClone, v as writeGlobalMap, y as writeProjectMap } from "./clone-DyLvmbJZ.mjs";
|
|
4
4
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
@@ -14,26 +14,18 @@ import { execSync, spawn } from "node:child_process";
|
|
|
14
14
|
* Manages updating project AGENTS.md and agent-specific files with reference information.
|
|
15
15
|
*/
|
|
16
16
|
/**
|
|
17
|
-
* Generate
|
|
17
|
+
* Generate single-line project reference guidance.
|
|
18
18
|
*
|
|
19
|
-
* @param
|
|
20
|
-
* @returns Markdown string with
|
|
19
|
+
* @param _references - Installed references (unused; reserved for future context)
|
|
20
|
+
* @returns Markdown string with one-line guidance
|
|
21
21
|
*/
|
|
22
|
-
function generateReferencesTable(
|
|
23
|
-
|
|
22
|
+
function generateReferencesTable(_references) {
|
|
23
|
+
return [
|
|
24
24
|
"## Project References",
|
|
25
25
|
"",
|
|
26
|
-
"
|
|
27
|
-
""
|
|
28
|
-
|
|
29
|
-
"| --- | --- | --- |"
|
|
30
|
-
];
|
|
31
|
-
for (const reference of references) lines.push(`| ${reference.dependency} | ${reference.reference} | ${reference.path} |`);
|
|
32
|
-
lines.push("");
|
|
33
|
-
lines.push("To update references: `ow pull <dependency>`");
|
|
34
|
-
lines.push("To regenerate all: `ow project init --all --generate`");
|
|
35
|
-
lines.push("");
|
|
36
|
-
return lines.join("\n");
|
|
26
|
+
"Use the Offworld CLI to find and read directly from local codebases for any repo in `.offworld/map.json` whenever the user asks about a specific open source project.",
|
|
27
|
+
""
|
|
28
|
+
].join("\n");
|
|
37
29
|
}
|
|
38
30
|
/**
|
|
39
31
|
* Update or append Project References section in a markdown file.
|
|
@@ -322,5 +314,5 @@ function cleanShellConfig(filePath) {
|
|
|
322
314
|
}
|
|
323
315
|
|
|
324
316
|
//#endregion
|
|
325
|
-
export { AuthError, CloneError, DEFAULT_IGNORE_PATTERNS, FALLBACK_MAPPINGS, GitError, NotGitRepoError, NotLoggedInError, PathNotFoundError, Paths, RepoExistsError, RepoNotFoundError, RepoSourceError, TokenExpiredError, VERSION, agents, appendReferencesSection, cleanShellConfig, clearAuthData, cloneRepo, detectInstallMethod, detectInstalledAgents, detectManifestType, discoverRepos, executeUninstall, executeUpgrade, expandTilde, fetchLatestVersion, gcRepos, getAgentConfig, getAllAgentConfigs, getAuthPath, getAuthStatus, getClonedRepoPath, getCommitDistance, getCommitSha, getConfigPath, getCurrentVersion, getMapEntry, getMetaPath, getMetaRoot, getProjectMapPath, getProvider, getReferenceFileNameForSource, getReferencePath, getRepoPath, getRepoRoot, getRepoStatus, getShellConfigFiles, getToken, getTokenOrNull, installGlobalSkill, installReference, isLoggedIn, isReferenceInstalled, isRepoCloned, isShallowClone, listProviders, listProvidersWithModels, listRepos, loadAuthData, loadConfig, matchDependenciesToReferences, matchDependenciesToReferencesWithRemoteCheck, parseDependencies, parseRepoInput, pruneRepos, readGlobalMap, refreshAccessToken, removeGlobalMapEntry, removeRepo, resolveDependencyRepo, resolveFromNpm, resolveRepoKey, saveAuthData, saveConfig, searchMap, toMetaDirName, toReferenceFileName, toReferenceName, unshallowRepo, updateAgentFiles, updateAllRepos, updateRepo, upsertGlobalMapEntry, validateProviderModel, writeGlobalMap, writeProjectMap };
|
|
317
|
+
export { AuthError, CloneError, DEFAULT_IGNORE_PATTERNS, FALLBACK_MAPPINGS, GitError, NotGitRepoError, NotLoggedInError, PathNotFoundError, Paths, RepoExistsError, RepoNotFoundError, RepoSourceError, TokenExpiredError, VERSION, agents, appendReferencesSection, cleanShellConfig, clearAuthData, cloneRepo, detectInstallMethod, detectInstalledAgents, detectManifestType, discoverRepos, executeUninstall, executeUpgrade, expandTilde, fetchLatestVersion, gcRepos, getAgentConfig, getAllAgentConfigs, getAuthPath, getAuthStatus, getClonedRepoPath, getCommitDistance, getCommitSha, getConfigPath, getCurrentVersion, getMapEntry, getMetaPath, getMetaRoot, getNpmKeywords, getProjectMapPath, getProvider, getReferenceFileNameForSource, getReferencePath, getRepoPath, getRepoRoot, getRepoStatus, getShellConfigFiles, getToken, getTokenOrNull, installGlobalSkill, installReference, isLoggedIn, isReferenceInstalled, isRepoCloned, isShallowClone, listProviders, listProvidersWithModels, listRepos, loadAuthData, loadConfig, matchDependenciesToReferences, matchDependenciesToReferencesWithRemoteCheck, parseDependencies, parseRepoInput, pruneRepos, readGlobalMap, refreshAccessToken, removeGlobalMapEntry, removeRepo, resolveDependencyRepo, resolveFromNpm, resolveReferenceKeywords, resolveRepoKey, saveAuthData, saveConfig, searchMap, toMetaDirName, toReferenceFileName, toReferenceName, unshallowRepo, updateAgentFiles, updateAllRepos, updateRepo, upsertGlobalMapEntry, validateProviderModel, writeGlobalMap, writeProjectMap };
|
|
326
318
|
//# sourceMappingURL=internal.mjs.map
|
package/dist/internal.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal.mjs","names":[],"sources":["../src/agents-md.ts","../src/installation.ts"],"sourcesContent":["/**\n * AGENTS.md manipulation utilities\n *\n * Manages updating project AGENTS.md and agent-specific files with reference information.\n */\n\nimport { readFileSync, writeFileSync, existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport interface InstalledReference {\n\t/** Dependency name */\n\tdependency: string;\n\t/** Reference identifier (matches reference file name without .md) */\n\treference: string;\n\t/** Absolute path to reference file */\n\tpath: string;\n}\n\n/**\n * Generate markdown table for project references section.\n *\n * @param references - Array of installed references\n * @returns Markdown string with table\n */\nfunction generateReferencesTable(references: InstalledReference[]): string {\n\tconst lines = [\n\t\t\"## Project References\",\n\t\t\"\",\n\t\t\"References installed for this project's dependencies:\",\n\t\t\"\",\n\t\t\"| Dependency | Reference | Path |\",\n\t\t\"| --- | --- | --- |\",\n\t];\n\n\tfor (const reference of references) {\n\t\tlines.push(`| ${reference.dependency} | ${reference.reference} | ${reference.path} |`);\n\t}\n\n\tlines.push(\"\");\n\tlines.push(\"To update references: `ow pull <dependency>`\");\n\tlines.push(\"To regenerate all: `ow project init --all --generate`\");\n\tlines.push(\"\");\n\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Update or append Project References section in a markdown file.\n * If the section exists, replaces its content. Otherwise, appends to end.\n *\n * @param filePath - Path to markdown file\n * @param references - Array of installed references\n */\nexport function appendReferencesSection(filePath: string, references: InstalledReference[]): void {\n\tconst content = existsSync(filePath) ? readFileSync(filePath, \"utf-8\") : \"\";\n\tconst referencesMarkdown = generateReferencesTable(references);\n\n\tconst sectionRegex = /^## Project References\\n(?:.*\\n)*?(?=^## |$)/m;\n\tconst match = content.match(sectionRegex);\n\n\tlet updatedContent: string;\n\tif (match) {\n\t\tupdatedContent = content.replace(sectionRegex, referencesMarkdown);\n\t} else {\n\t\tupdatedContent = content.trim() + \"\\n\\n\" + referencesMarkdown;\n\t}\n\n\twriteFileSync(filePath, updatedContent, \"utf-8\");\n}\n\n/**\n * Update AGENTS.md and agent-specific files with project references.\n * Creates files if they don't exist.\n *\n * @param projectRoot - Project root directory\n * @param references - Array of installed references to document\n */\nexport function updateAgentFiles(projectRoot: string, references: InstalledReference[]): void {\n\tconst agentsMdPath = join(projectRoot, \"AGENTS.md\");\n\tconst claudeMdPath = join(projectRoot, \"CLAUDE.md\");\n\n\tappendReferencesSection(agentsMdPath, references);\n\n\tif (existsSync(claudeMdPath)) {\n\t\tappendReferencesSection(claudeMdPath, references);\n\t}\n}\n","/**\n * Installation utilities for upgrade/uninstall commands\n */\n\nimport { execSync, spawn } from \"node:child_process\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { NpmPackageResponseSchema } from \"@offworld/types\";\nimport { VERSION } from \"./constants.js\";\n\nconst GITHUB_REPO = \"oscabriel/offworld\";\nconst NPM_PACKAGE = \"offworld\";\n\nexport type InstallMethod = \"curl\" | \"npm\" | \"pnpm\" | \"bun\" | \"brew\" | \"unknown\";\n\n/**\n * Detect how offworld was installed\n */\nexport function detectInstallMethod(): InstallMethod {\n\tconst execPath = process.execPath;\n\n\tif (execPath.includes(\".local/bin\")) return \"curl\";\n\n\tconst checks: Array<{ name: InstallMethod; test: () => boolean }> = [\n\t\t{\n\t\t\tname: \"npm\",\n\t\t\ttest: () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = execSync(\"npm list -g --depth=0 2>/dev/null\", {\n\t\t\t\t\t\tencoding: \"utf-8\",\n\t\t\t\t\t});\n\t\t\t\t\treturn result.includes(NPM_PACKAGE);\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"pnpm\",\n\t\t\ttest: () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = execSync(\"pnpm list -g --depth=0 2>/dev/null\", {\n\t\t\t\t\t\tencoding: \"utf-8\",\n\t\t\t\t\t});\n\t\t\t\t\treturn result.includes(NPM_PACKAGE);\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"bun\",\n\t\t\ttest: () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = execSync(\"bun pm ls -g 2>/dev/null\", {\n\t\t\t\t\t\tencoding: \"utf-8\",\n\t\t\t\t\t});\n\t\t\t\t\treturn result.includes(NPM_PACKAGE);\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"brew\",\n\t\t\ttest: () => {\n\t\t\t\ttry {\n\t\t\t\t\texecSync(\"brew list --formula offworld 2>/dev/null\", {\n\t\t\t\t\t\tencoding: \"utf-8\",\n\t\t\t\t\t});\n\t\t\t\t\treturn true;\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t];\n\n\tif (execPath.includes(\"npm\")) {\n\t\tconst check = checks.find((c) => c.name === \"npm\");\n\t\tif (check?.test()) return \"npm\";\n\t}\n\tif (execPath.includes(\"pnpm\")) {\n\t\tconst check = checks.find((c) => c.name === \"pnpm\");\n\t\tif (check?.test()) return \"pnpm\";\n\t}\n\tif (execPath.includes(\"bun\")) {\n\t\tconst check = checks.find((c) => c.name === \"bun\");\n\t\tif (check?.test()) return \"bun\";\n\t}\n\tif (execPath.includes(\"Cellar\") || execPath.includes(\"homebrew\")) {\n\t\tconst check = checks.find((c) => c.name === \"brew\");\n\t\tif (check?.test()) return \"brew\";\n\t}\n\n\tfor (const check of checks) {\n\t\tif (check.test()) return check.name;\n\t}\n\n\treturn \"unknown\";\n}\n\n/**\n * Get current installed version\n */\nexport function getCurrentVersion(): string {\n\treturn VERSION;\n}\n\n/**\n * Fetch latest version from appropriate source\n */\nexport async function fetchLatestVersion(method?: InstallMethod): Promise<string | null> {\n\tconst installMethod = method ?? detectInstallMethod();\n\n\ttry {\n\t\tif (installMethod === \"npm\" || installMethod === \"pnpm\" || installMethod === \"bun\") {\n\t\t\tconst response = await fetch(`https://registry.npmjs.org/${NPM_PACKAGE}/latest`);\n\t\t\tif (!response.ok) return null;\n\t\t\tconst json = await response.json();\n\t\t\tconst result = NpmPackageResponseSchema.safeParse(json);\n\t\t\tif (!result.success) return null;\n\t\t\treturn result.data.version ?? null;\n\t\t}\n\n\t\tconst response = await fetch(`https://api.github.com/repos/${GITHUB_REPO}/releases/latest`, {\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/vnd.github.v3+json\",\n\t\t\t\t\"User-Agent\": \"offworld-cli\",\n\t\t\t},\n\t\t});\n\t\tif (!response.ok) return null;\n\t\tconst json = await response.json();\n\t\tconst tagName =\n\t\t\ttypeof json === \"object\" && json !== null && \"tag_name\" in json\n\t\t\t\t? String(json.tag_name)\n\t\t\t\t: null;\n\t\treturn tagName?.replace(/^v/, \"\") ?? null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Execute upgrade for given method\n */\nexport function executeUpgrade(method: InstallMethod, version: string): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet cmd: string;\n\t\tlet args: string[];\n\n\t\tswitch (method) {\n\t\t\tcase \"curl\":\n\t\t\t\tcmd = \"bash\";\n\t\t\t\targs = [\"-c\", `curl -fsSL https://offworld.sh/install | VERSION=${version} bash`];\n\t\t\t\tbreak;\n\t\t\tcase \"npm\":\n\t\t\t\tcmd = \"npm\";\n\t\t\t\targs = [\"install\", \"-g\", `${NPM_PACKAGE}@${version}`];\n\t\t\t\tbreak;\n\t\t\tcase \"pnpm\":\n\t\t\t\tcmd = \"pnpm\";\n\t\t\t\targs = [\"install\", \"-g\", `${NPM_PACKAGE}@${version}`];\n\t\t\t\tbreak;\n\t\t\tcase \"bun\":\n\t\t\t\tcmd = \"bun\";\n\t\t\t\targs = [\"install\", \"-g\", `${NPM_PACKAGE}@${version}`];\n\t\t\t\tbreak;\n\t\t\tcase \"brew\":\n\t\t\t\tcmd = \"brew\";\n\t\t\t\targs = [\"upgrade\", \"offworld\"];\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treject(new Error(`Cannot upgrade: unknown installation method`));\n\t\t\t\treturn;\n\t\t}\n\n\t\tconst proc = spawn(cmd, args, { stdio: \"inherit\" });\n\t\tproc.on(\"close\", (code) => {\n\t\t\tif (code === 0) resolve();\n\t\t\telse reject(new Error(`Upgrade failed with exit code ${code}`));\n\t\t});\n\t\tproc.on(\"error\", reject);\n\t});\n}\n\n/**\n * Execute uninstall for given method\n */\nexport function executeUninstall(method: InstallMethod): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet cmd: string;\n\t\tlet args: string[];\n\n\t\tswitch (method) {\n\t\t\tcase \"curl\":\n\t\t\t\ttry {\n\t\t\t\t\tconst binPath = join(homedir(), \".local\", \"bin\", \"ow\");\n\t\t\t\t\tif (existsSync(binPath)) {\n\t\t\t\t\t\texecSync(`rm -f \"${binPath}\"`, { stdio: \"inherit\" });\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t} catch (err) {\n\t\t\t\t\treject(err);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\tcase \"npm\":\n\t\t\t\tcmd = \"npm\";\n\t\t\t\targs = [\"uninstall\", \"-g\", NPM_PACKAGE];\n\t\t\t\tbreak;\n\t\t\tcase \"pnpm\":\n\t\t\t\tcmd = \"pnpm\";\n\t\t\t\targs = [\"uninstall\", \"-g\", NPM_PACKAGE];\n\t\t\t\tbreak;\n\t\t\tcase \"bun\":\n\t\t\t\tcmd = \"bun\";\n\t\t\t\targs = [\"remove\", \"-g\", NPM_PACKAGE];\n\t\t\t\tbreak;\n\t\t\tcase \"brew\":\n\t\t\t\tcmd = \"brew\";\n\t\t\t\targs = [\"uninstall\", \"offworld\"];\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treject(new Error(`Cannot uninstall: unknown installation method`));\n\t\t\t\treturn;\n\t\t}\n\n\t\tconst proc = spawn(cmd, args, { stdio: \"inherit\" });\n\t\tproc.on(\"close\", (code) => {\n\t\t\tif (code === 0) resolve();\n\t\t\telse reject(new Error(`Uninstall failed with exit code ${code}`));\n\t\t});\n\t\tproc.on(\"error\", reject);\n\t});\n}\n\n/**\n * Get shell config files to clean\n */\nexport function getShellConfigFiles(): string[] {\n\tconst home = homedir();\n\tconst configs: string[] = [];\n\n\tconst candidates = [\n\t\t\".bashrc\",\n\t\t\".bash_profile\",\n\t\t\".profile\",\n\t\t\".zshrc\",\n\t\t\".zshenv\",\n\t\t\".config/fish/config.fish\",\n\t];\n\n\tfor (const file of candidates) {\n\t\tconst path = join(home, file);\n\t\tif (existsSync(path)) {\n\t\t\tconfigs.push(path);\n\t\t}\n\t}\n\n\treturn configs;\n}\n\n/**\n * Clean PATH entries from shell config\n */\nexport function cleanShellConfig(filePath: string): boolean {\n\ttry {\n\t\tconst content = readFileSync(filePath, \"utf-8\");\n\t\tconst lines = content.split(\"\\n\");\n\t\tconst filtered: string[] = [];\n\t\tlet modified = false;\n\n\t\tfor (const line of lines) {\n\t\t\tconst trimmed = line.trim();\n\t\t\tif (\n\t\t\t\ttrimmed.includes(\".local/bin\") &&\n\t\t\t\t(trimmed.startsWith(\"export PATH=\") || trimmed.startsWith(\"fish_add_path\"))\n\t\t\t) {\n\t\t\t\tif (trimmed.includes(\"# offworld\") || trimmed === 'export PATH=\"$HOME/.local/bin:$PATH\"') {\n\t\t\t\t\tmodified = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t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AAW;AAEf,OAAK,MAAM,QAAQ,OAAO;GACzB,MAAM,UAAU,KAAK,MAAM;AAC3B,OACC,QAAQ,SAAS,aAAa,KAC7B,QAAQ,WAAW,eAAe,IAAI,QAAQ,WAAW,gBAAgB,GAE1E;QAAI,QAAQ,SAAS,aAAa,IAAI,YAAY,0CAAwC;AACzF,gBAAW;AACX;;;AAGF,YAAS,KAAK,KAAK;;AAGpB,MAAI,SACH,eAAc,UAAU,SAAS,KAAK,KAAK,EAAE,QAAQ;AAGtD,SAAO;SACA;AACP,SAAO"}
|
|
1
|
+
{"version":3,"file":"internal.mjs","names":[],"sources":["../src/agents-md.ts","../src/installation.ts"],"sourcesContent":["/**\n * AGENTS.md manipulation utilities\n *\n * Manages updating project AGENTS.md and agent-specific files with reference information.\n */\n\nimport { readFileSync, writeFileSync, existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport interface InstalledReference {\n\t/** Dependency name */\n\tdependency: string;\n\t/** Reference identifier (matches reference file name without .md) */\n\treference: string;\n\t/** Absolute path to reference file */\n\tpath: string;\n}\n\n/**\n * Generate single-line project reference guidance.\n *\n * @param _references - Installed references (unused; reserved for future context)\n * @returns Markdown string with one-line guidance\n */\nfunction generateReferencesTable(_references: InstalledReference[]): string {\n\tconst lines = [\n\t\t\"## Project References\",\n\t\t\"\",\n\t\t\"Use the Offworld CLI to find and read directly from local codebases for any repo in `.offworld/map.json` whenever the user asks about a specific open source project.\",\n\t\t\"\",\n\t];\n\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Update or append Project References section in a markdown file.\n * If the section exists, replaces its content. Otherwise, appends to end.\n *\n * @param filePath - Path to markdown file\n * @param references - Array of installed references\n */\nexport function appendReferencesSection(filePath: string, references: InstalledReference[]): void {\n\tconst content = existsSync(filePath) ? readFileSync(filePath, \"utf-8\") : \"\";\n\tconst referencesMarkdown = generateReferencesTable(references);\n\n\tconst sectionRegex = /^## Project References\\n(?:.*\\n)*?(?=^## |$)/m;\n\tconst match = content.match(sectionRegex);\n\n\tlet updatedContent: string;\n\tif (match) {\n\t\tupdatedContent = content.replace(sectionRegex, referencesMarkdown);\n\t} else {\n\t\tupdatedContent = content.trim() + \"\\n\\n\" + referencesMarkdown;\n\t}\n\n\twriteFileSync(filePath, updatedContent, \"utf-8\");\n}\n\n/**\n * Update AGENTS.md and agent-specific files with project references.\n * Creates files if they don't exist.\n *\n * @param projectRoot - Project root directory\n * @param references - Array of installed references to document\n */\nexport function updateAgentFiles(projectRoot: string, references: InstalledReference[]): void {\n\tconst agentsMdPath = join(projectRoot, \"AGENTS.md\");\n\tconst claudeMdPath = join(projectRoot, \"CLAUDE.md\");\n\n\tappendReferencesSection(agentsMdPath, references);\n\n\tif (existsSync(claudeMdPath)) {\n\t\tappendReferencesSection(claudeMdPath, references);\n\t}\n}\n","/**\n * Installation utilities for upgrade/uninstall commands\n */\n\nimport { execSync, spawn } from \"node:child_process\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { NpmPackageResponseSchema } from \"@offworld/types\";\nimport { VERSION } from \"./constants.js\";\n\nconst GITHUB_REPO = \"oscabriel/offworld\";\nconst NPM_PACKAGE = \"offworld\";\n\nexport type InstallMethod = \"curl\" | \"npm\" | \"pnpm\" | \"bun\" | \"brew\" | \"unknown\";\n\n/**\n * Detect how offworld was installed\n */\nexport function detectInstallMethod(): InstallMethod {\n\tconst execPath = process.execPath;\n\n\tif (execPath.includes(\".local/bin\")) return \"curl\";\n\n\tconst checks: Array<{ name: InstallMethod; test: () => boolean }> = [\n\t\t{\n\t\t\tname: \"npm\",\n\t\t\ttest: () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = execSync(\"npm list -g --depth=0 2>/dev/null\", {\n\t\t\t\t\t\tencoding: \"utf-8\",\n\t\t\t\t\t});\n\t\t\t\t\treturn result.includes(NPM_PACKAGE);\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"pnpm\",\n\t\t\ttest: () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = execSync(\"pnpm list -g --depth=0 2>/dev/null\", {\n\t\t\t\t\t\tencoding: \"utf-8\",\n\t\t\t\t\t});\n\t\t\t\t\treturn result.includes(NPM_PACKAGE);\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"bun\",\n\t\t\ttest: () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = execSync(\"bun pm ls -g 2>/dev/null\", {\n\t\t\t\t\t\tencoding: \"utf-8\",\n\t\t\t\t\t});\n\t\t\t\t\treturn result.includes(NPM_PACKAGE);\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"brew\",\n\t\t\ttest: () => {\n\t\t\t\ttry {\n\t\t\t\t\texecSync(\"brew list --formula offworld 2>/dev/null\", {\n\t\t\t\t\t\tencoding: \"utf-8\",\n\t\t\t\t\t});\n\t\t\t\t\treturn true;\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t];\n\n\tif (execPath.includes(\"npm\")) {\n\t\tconst check = checks.find((c) => c.name === \"npm\");\n\t\tif (check?.test()) return \"npm\";\n\t}\n\tif (execPath.includes(\"pnpm\")) {\n\t\tconst check = checks.find((c) => c.name === \"pnpm\");\n\t\tif (check?.test()) return \"pnpm\";\n\t}\n\tif (execPath.includes(\"bun\")) {\n\t\tconst check = checks.find((c) => c.name === \"bun\");\n\t\tif (check?.test()) return \"bun\";\n\t}\n\tif (execPath.includes(\"Cellar\") || execPath.includes(\"homebrew\")) {\n\t\tconst check = checks.find((c) => c.name === \"brew\");\n\t\tif (check?.test()) return \"brew\";\n\t}\n\n\tfor (const check of checks) {\n\t\tif (check.test()) return check.name;\n\t}\n\n\treturn \"unknown\";\n}\n\n/**\n * Get current installed version\n */\nexport function getCurrentVersion(): string {\n\treturn VERSION;\n}\n\n/**\n * Fetch latest version from appropriate source\n */\nexport async function fetchLatestVersion(method?: InstallMethod): Promise<string | null> {\n\tconst installMethod = method ?? detectInstallMethod();\n\n\ttry {\n\t\tif (installMethod === \"npm\" || installMethod === \"pnpm\" || installMethod === \"bun\") {\n\t\t\tconst response = await fetch(`https://registry.npmjs.org/${NPM_PACKAGE}/latest`);\n\t\t\tif (!response.ok) return null;\n\t\t\tconst json = await response.json();\n\t\t\tconst result = NpmPackageResponseSchema.safeParse(json);\n\t\t\tif (!result.success) return null;\n\t\t\treturn result.data.version ?? null;\n\t\t}\n\n\t\tconst response = await fetch(`https://api.github.com/repos/${GITHUB_REPO}/releases/latest`, {\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/vnd.github.v3+json\",\n\t\t\t\t\"User-Agent\": \"offworld-cli\",\n\t\t\t},\n\t\t});\n\t\tif (!response.ok) return null;\n\t\tconst json = await response.json();\n\t\tconst tagName =\n\t\t\ttypeof json === \"object\" && json !== null && \"tag_name\" in json\n\t\t\t\t? String(json.tag_name)\n\t\t\t\t: null;\n\t\treturn tagName?.replace(/^v/, \"\") ?? null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Execute upgrade for given method\n */\nexport function executeUpgrade(method: InstallMethod, version: string): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet cmd: string;\n\t\tlet args: string[];\n\n\t\tswitch (method) {\n\t\t\tcase \"curl\":\n\t\t\t\tcmd = \"bash\";\n\t\t\t\targs = [\"-c\", `curl -fsSL https://offworld.sh/install | VERSION=${version} bash`];\n\t\t\t\tbreak;\n\t\t\tcase \"npm\":\n\t\t\t\tcmd = \"npm\";\n\t\t\t\targs = [\"install\", \"-g\", `${NPM_PACKAGE}@${version}`];\n\t\t\t\tbreak;\n\t\t\tcase \"pnpm\":\n\t\t\t\tcmd = \"pnpm\";\n\t\t\t\targs = [\"install\", \"-g\", `${NPM_PACKAGE}@${version}`];\n\t\t\t\tbreak;\n\t\t\tcase \"bun\":\n\t\t\t\tcmd = \"bun\";\n\t\t\t\targs = [\"install\", \"-g\", `${NPM_PACKAGE}@${version}`];\n\t\t\t\tbreak;\n\t\t\tcase \"brew\":\n\t\t\t\tcmd = \"brew\";\n\t\t\t\targs = [\"upgrade\", \"offworld\"];\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treject(new Error(`Cannot upgrade: unknown installation method`));\n\t\t\t\treturn;\n\t\t}\n\n\t\tconst proc = spawn(cmd, args, { stdio: \"inherit\" });\n\t\tproc.on(\"close\", (code) => {\n\t\t\tif (code === 0) resolve();\n\t\t\telse reject(new Error(`Upgrade failed with exit code ${code}`));\n\t\t});\n\t\tproc.on(\"error\", reject);\n\t});\n}\n\n/**\n * Execute uninstall for given method\n */\nexport function executeUninstall(method: InstallMethod): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet cmd: string;\n\t\tlet args: string[];\n\n\t\tswitch (method) {\n\t\t\tcase \"curl\":\n\t\t\t\ttry {\n\t\t\t\t\tconst binPath = join(homedir(), \".local\", \"bin\", \"ow\");\n\t\t\t\t\tif (existsSync(binPath)) {\n\t\t\t\t\t\texecSync(`rm -f \"${binPath}\"`, { stdio: \"inherit\" });\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t} catch (err) {\n\t\t\t\t\treject(err);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\tcase \"npm\":\n\t\t\t\tcmd = \"npm\";\n\t\t\t\targs = [\"uninstall\", \"-g\", NPM_PACKAGE];\n\t\t\t\tbreak;\n\t\t\tcase \"pnpm\":\n\t\t\t\tcmd = \"pnpm\";\n\t\t\t\targs = [\"uninstall\", \"-g\", NPM_PACKAGE];\n\t\t\t\tbreak;\n\t\t\tcase \"bun\":\n\t\t\t\tcmd = \"bun\";\n\t\t\t\targs = [\"remove\", \"-g\", NPM_PACKAGE];\n\t\t\t\tbreak;\n\t\t\tcase \"brew\":\n\t\t\t\tcmd = \"brew\";\n\t\t\t\targs = [\"uninstall\", \"offworld\"];\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treject(new Error(`Cannot uninstall: unknown installation method`));\n\t\t\t\treturn;\n\t\t}\n\n\t\tconst proc = spawn(cmd, args, { stdio: \"inherit\" });\n\t\tproc.on(\"close\", (code) => {\n\t\t\tif (code === 0) resolve();\n\t\t\telse reject(new Error(`Uninstall failed with exit code ${code}`));\n\t\t});\n\t\tproc.on(\"error\", reject);\n\t});\n}\n\n/**\n * Get shell config files to clean\n */\nexport function getShellConfigFiles(): string[] {\n\tconst home = homedir();\n\tconst configs: string[] = [];\n\n\tconst candidates = [\n\t\t\".bashrc\",\n\t\t\".bash_profile\",\n\t\t\".profile\",\n\t\t\".zshrc\",\n\t\t\".zshenv\",\n\t\t\".config/fish/config.fish\",\n\t];\n\n\tfor (const file of candidates) {\n\t\tconst path = join(home, file);\n\t\tif (existsSync(path)) {\n\t\t\tconfigs.push(path);\n\t\t}\n\t}\n\n\treturn configs;\n}\n\n/**\n * Clean PATH entries from shell config\n */\nexport function cleanShellConfig(filePath: string): boolean {\n\ttry {\n\t\tconst content = readFileSync(filePath, \"utf-8\");\n\t\tconst lines = content.split(\"\\n\");\n\t\tconst filtered: string[] = [];\n\t\tlet modified = false;\n\n\t\tfor (const line of lines) {\n\t\t\tconst trimmed = line.trim();\n\t\t\tif (\n\t\t\t\ttrimmed.includes(\".local/bin\") &&\n\t\t\t\t(trimmed.startsWith(\"export PATH=\") || trimmed.startsWith(\"fish_add_path\"))\n\t\t\t) {\n\t\t\t\tif (trimmed.includes(\"# offworld\") || trimmed === 'export PATH=\"$HOME/.local/bin:$PATH\"') {\n\t\t\t\t\tmodified = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfiltered.push(line);\n\t\t}\n\n\t\tif (modified) {\n\t\t\twriteFileSync(filePath, filtered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