mirror of
https://github.com/ZSeven-W/openpencil.git
synced 2026-05-31 19:04:29 +07:00
* feat(ai): enhance Windows CLI binary resolution and connection handling - Introduced functions to handle both .cmd and .ps1 wrappers for Windows installations, improving compatibility for CLI tools like Codex and Copilot. - Updated connection logic in `connect-agent.ts` to utilize environment variables for Codex home directory, enhancing flexibility in locating configuration files. - Added warning messages in connection results to inform users when no models are found, guiding them to run the CLI tools for model population. - Modified the agent settings dialog to accommodate the new warning field in connection responses, improving user feedback during the connection process. This update significantly enhances the user experience for Windows users by ensuring better handling of CLI binaries and providing clearer connection status information. * feat(ai): improve Windows binary resolution for CLI tools - Added `resolveWinExtension` function to handle extensionless binaries returned by the `where` command on Windows, ensuring compatibility with `.cmd` and `.ps1` wrappers. - Updated `connect-agent.ts` and `copilot-client.ts` to utilize the new resolution function, enhancing the reliability of binary path lookups for Codex and Copilot. - Enhanced logging to provide clearer information on resolved paths and their existence status. This update significantly improves the handling of CLI binaries on Windows, ensuring users have a smoother experience when connecting to AI tools. * feat(ai): enhance binary path handling in connect-agent - Added logic to ensure the directory of the resolved OpenCode binary is included in the PATH environment variable, improving the execution of CLI tools. - Enhanced logging to provide feedback when the binary directory is prepended to the PATH, aiding in troubleshooting and user awareness. This update improves the reliability of connecting to AI tools by ensuring the necessary binaries are accessible during execution. * feat(patching): add patch for @opencode-ai/sdk and update package configurations - Introduced a new patch for the @opencode-ai/sdk version 1.2.6 to address specific issues. - Updated package.json and bun.lock to include the new patchedDependencies section, ensuring the patch is applied during installation. - Removed redundant binary path handling code in connect-agent.ts to streamline the connection process. This update enhances the SDK's functionality while simplifying the connection logic for improved performance. * fix(ai): add orchestrator fallback and three-way intent routing Orchestrator now falls back to a heuristic plan when the model returns non-JSON instead of throwing an error. Intent classification upgraded from binary (DESIGN/CHAT) to three-way (DESIGN_NEW/DESIGN_MODIFY/CHAT). Modification requests without an explicit selection auto-target the last top-level frame on the active page, preventing them from being misrouted to the orchestrator. * chore: bump version to 0.4.4 and remove deprecated patch for @opencode-ai/sdk - Updated package version in package.json from 0.4.3 to 0.4.4. - Removed the patchedDependencies section for @opencode-ai/sdk as the patch is no longer needed. - Added new utility function `buildSpawnClaudeCodeProcess` to enhance agent SDK functionality across multiple files. * chore: bump version to 0.4.4 in package.json * chore(electron): optimize application icon assets Reduce icon file sizes for faster builds and smaller distribution. * chore: remove deprecated patchedDependencies for @opencode-ai/sdk in bun.lock - Eliminated the patchedDependencies section for @opencode-ai/sdk as the patch is no longer necessary, streamlining the dependency management in the project. * fix(ai): improve Codex CLI error extraction for auth and structured log errors Parse Codex's structured log format (<timestamp> ERROR <module>: <message>) to surface real errors like expired auth tokens instead of the unhelpful "Warning: no last agent message" fallback. * fix(ai): update error handling and remove deprecated reasoning field - Updated error checks in chat and generate handlers to ensure proper validation of required fields. - Removed the deprecated reasoning field from the OpenCode SDK integration, streamlining the prompt parameters. - Enhanced logging for system prompt injection errors to improve debugging capabilities. * fix(ai): enhance Windows compatibility for Codex CLI execution - Updated the handling of prompts on Windows to avoid parsing errors caused by shell escaping in PowerShell and cmd.exe. - Introduced a temporary PowerShell script to manage prompt input and command execution, ensuring special characters are processed correctly. - Refactored the argument passing mechanism to accommodate the new script-based approach. * fix(electron): improve process cleanup and Windows compatibility - Simplified the application quit logic to always call app.quit() on window close. - Enhanced the before-quit event to ensure proper cleanup of the Nitro process and port file. - Updated the Nitro process termination logic to use SIGKILL for reliable cleanup on non-Windows platforms. - Refactored argument handling in the Codex CLI execution to utilize PowerShell array splatting for safer argument passing. * feat(ai): add fallback for model parsing from Codex's latest-model.md - Implemented a new function to parse model IDs from the latest-model.md file when models_cache.json is unavailable, enhancing compatibility for fresh installations. - Updated logging to reflect the loading of models from the fallback method and improved error handling for model loading scenarios. * feat(ai): update prompt structure for design generation assistant - Revised the prompt format to enhance clarity and organization for the design generation assistant. - Introduced clear section headers for system instructions and user tasks, improving user experience and guidance. * refactor(ai): streamline prompt handling for Codex CLI execution - Simplified the prompt input mechanism for all platforms by utilizing stdin mode, eliminating the need for temporary scripts on Windows. - Improved argument passing to avoid shell escaping issues and command-line length limits, enhancing compatibility and reliability across environments. - Updated the execution logic to handle prompts more efficiently, ensuring a smoother user experience. --------- Co-authored-by: Fini <fini.yang@gmail.com>
239 lines
7 KiB
TypeScript
239 lines
7 KiB
TypeScript
// This file is auto-generated by @hey-api/openapi-ts
|
|
|
|
import type { Config } from "./types.gen.js"
|
|
|
|
export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, "method"> &
|
|
Pick<Config, "method" | "responseTransformer" | "responseValidator"> & {
|
|
/**
|
|
* Fetch API implementation. You can use this option to provide a custom
|
|
* fetch instance.
|
|
*
|
|
* @default globalThis.fetch
|
|
*/
|
|
fetch?: typeof fetch
|
|
/**
|
|
* Implementing clients can call request interceptors inside this hook.
|
|
*/
|
|
onRequest?: (url: string, init: RequestInit) => Promise<Request>
|
|
/**
|
|
* Callback invoked when a network or parsing error occurs during streaming.
|
|
*
|
|
* This option applies only if the endpoint returns a stream of events.
|
|
*
|
|
* @param error The error that occurred.
|
|
*/
|
|
onSseError?: (error: unknown) => void
|
|
/**
|
|
* Callback invoked when an event is streamed from the server.
|
|
*
|
|
* This option applies only if the endpoint returns a stream of events.
|
|
*
|
|
* @param event Event streamed from the server.
|
|
* @returns Nothing (void).
|
|
*/
|
|
onSseEvent?: (event: StreamEvent<TData>) => void
|
|
serializedBody?: RequestInit["body"]
|
|
/**
|
|
* Default retry delay in milliseconds.
|
|
*
|
|
* This option applies only if the endpoint returns a stream of events.
|
|
*
|
|
* @default 3000
|
|
*/
|
|
sseDefaultRetryDelay?: number
|
|
/**
|
|
* Maximum number of retry attempts before giving up.
|
|
*/
|
|
sseMaxRetryAttempts?: number
|
|
/**
|
|
* Maximum retry delay in milliseconds.
|
|
*
|
|
* Applies only when exponential backoff is used.
|
|
*
|
|
* This option applies only if the endpoint returns a stream of events.
|
|
*
|
|
* @default 30000
|
|
*/
|
|
sseMaxRetryDelay?: number
|
|
/**
|
|
* Optional sleep function for retry backoff.
|
|
*
|
|
* Defaults to using `setTimeout`.
|
|
*/
|
|
sseSleepFn?: (ms: number) => Promise<void>
|
|
url: string
|
|
}
|
|
|
|
export interface StreamEvent<TData = unknown> {
|
|
data: TData
|
|
event?: string
|
|
id?: string
|
|
retry?: number
|
|
}
|
|
|
|
export type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {
|
|
stream: AsyncGenerator<TData extends Record<string, unknown> ? TData[keyof TData] : TData, TReturn, TNext>
|
|
}
|
|
|
|
export const createSseClient = <TData = unknown>({
|
|
onRequest,
|
|
onSseError,
|
|
onSseEvent,
|
|
responseTransformer,
|
|
responseValidator,
|
|
sseDefaultRetryDelay,
|
|
sseMaxRetryAttempts,
|
|
sseMaxRetryDelay,
|
|
sseSleepFn,
|
|
url,
|
|
...options
|
|
}: ServerSentEventsOptions): ServerSentEventsResult<TData> => {
|
|
let lastEventId: string | undefined
|
|
|
|
const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)))
|
|
|
|
const createStream = async function* () {
|
|
let retryDelay: number = sseDefaultRetryDelay ?? 3000
|
|
let attempt = 0
|
|
const signal = options.signal ?? new AbortController().signal
|
|
|
|
while (true) {
|
|
if (signal.aborted) break
|
|
|
|
attempt++
|
|
|
|
const headers =
|
|
options.headers instanceof Headers
|
|
? options.headers
|
|
: new Headers(options.headers as Record<string, string> | undefined)
|
|
|
|
if (lastEventId !== undefined) {
|
|
headers.set("Last-Event-ID", lastEventId)
|
|
}
|
|
|
|
try {
|
|
const requestInit: RequestInit = {
|
|
redirect: "follow",
|
|
...options,
|
|
body: options.serializedBody,
|
|
headers,
|
|
signal,
|
|
}
|
|
let request = new Request(url, requestInit)
|
|
if (onRequest) {
|
|
request = await onRequest(url, requestInit)
|
|
}
|
|
// fetch must be assigned here, otherwise it would throw the error:
|
|
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
|
|
const _fetch = options.fetch ?? globalThis.fetch
|
|
const response = await _fetch(request)
|
|
|
|
if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`)
|
|
|
|
if (!response.body) throw new Error("No body in SSE response")
|
|
|
|
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader()
|
|
|
|
let buffer = ""
|
|
|
|
const abortHandler = () => {
|
|
try {
|
|
reader.cancel()
|
|
} catch {
|
|
// noop
|
|
}
|
|
}
|
|
|
|
signal.addEventListener("abort", abortHandler)
|
|
|
|
try {
|
|
while (true) {
|
|
const { done, value } = await reader.read()
|
|
if (done) break
|
|
buffer += value
|
|
// Normalize line endings: CRLF -> LF, then CR -> LF
|
|
buffer = buffer.replace(/\r\n/g, "\n").replace(/\r/g, "\n")
|
|
|
|
const chunks = buffer.split("\n\n")
|
|
buffer = chunks.pop() ?? ""
|
|
|
|
for (const chunk of chunks) {
|
|
const lines = chunk.split("\n")
|
|
const dataLines: Array<string> = []
|
|
let eventName: string | undefined
|
|
|
|
for (const line of lines) {
|
|
if (line.startsWith("data:")) {
|
|
dataLines.push(line.replace(/^data:\s*/, ""))
|
|
} else if (line.startsWith("event:")) {
|
|
eventName = line.replace(/^event:\s*/, "")
|
|
} else if (line.startsWith("id:")) {
|
|
lastEventId = line.replace(/^id:\s*/, "")
|
|
} else if (line.startsWith("retry:")) {
|
|
const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10)
|
|
if (!Number.isNaN(parsed)) {
|
|
retryDelay = parsed
|
|
}
|
|
}
|
|
}
|
|
|
|
let data: unknown
|
|
let parsedJson = false
|
|
|
|
if (dataLines.length) {
|
|
const rawData = dataLines.join("\n")
|
|
try {
|
|
data = JSON.parse(rawData)
|
|
parsedJson = true
|
|
} catch {
|
|
data = rawData
|
|
}
|
|
}
|
|
|
|
if (parsedJson) {
|
|
if (responseValidator) {
|
|
await responseValidator(data)
|
|
}
|
|
|
|
if (responseTransformer) {
|
|
data = await responseTransformer(data)
|
|
}
|
|
}
|
|
|
|
onSseEvent?.({
|
|
data,
|
|
event: eventName,
|
|
id: lastEventId,
|
|
retry: retryDelay,
|
|
})
|
|
|
|
if (dataLines.length) {
|
|
yield data as any
|
|
}
|
|
}
|
|
}
|
|
} finally {
|
|
signal.removeEventListener("abort", abortHandler)
|
|
reader.releaseLock()
|
|
}
|
|
|
|
break // exit loop on normal completion
|
|
} catch (error) {
|
|
// connection failed or aborted; retry after delay
|
|
onSseError?.(error)
|
|
|
|
if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {
|
|
break // stop after firing error
|
|
}
|
|
|
|
// exponential backoff: double retry each attempt, cap at 30s
|
|
const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000)
|
|
await sleep(backoff)
|
|
}
|
|
}
|
|
}
|
|
|
|
const stream = createStream()
|
|
|
|
return { stream }
|
|
}
|