@ai-sdk/harness-cline 1.0.60 → 1.0.61

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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cline-harness.ts","../src/cline-subscription.ts","../src/cline-auth.ts","../src/cline-resume-state.ts","../src/cline-session.ts","../src/cline-mcp.ts","../src/cline-remote-ops.ts","../src/cline-skills.ts","../src/cline-tools.ts","../src/cline-utils.ts","../src/cline-translate.ts","../src/version.ts","../src/index.ts"],"sourcesContent":["import {\n commonTool,\n HARNESS_V1_BUILTIN_TOOLS,\n type HarnessV1,\n type HarnessV1BuiltinTool,\n} from '@ai-sdk/harness';\nimport { isHarnessAuthenticationEnvironment } from '@ai-sdk/harness/utils';\nimport { tool } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport type { ClineAuthenticationMode } from './cline-auth';\nimport { resolveClineAuthentication } from './cline-subscription';\nimport { clineResumeStateSchema } from './cline-resume-state';\nimport { createClineSession, type ClineReasoningEffort } from './cline-session';\nimport { VERSION } from './version';\n\n/**\n * Value used to identify the harness in provider request headers.\n */\nconst CLINE_CLIENT_APP = `ai-sdk-harness-cline/${VERSION}`;\n\n/**\n * Configuration knobs for `createCline`. The Cline runtime\n * (`@cline/agents`, part of the Cline SDK) runs as an in-process Node\n * library — no bridge, so there is no `port` or `startupTimeoutMs` to set.\n */\nexport type ClineHarnessSettings = {\n /** Where Cline sources direct or AI Gateway credentials from. */\n readonly auth?: ClineAuthenticationMode;\n /**\n * MCP server definitions keyed by server name. Each definition uses the\n * underlying runtime's native MCP server configuration format.\n */\n readonly mcpServers?: Record<string, unknown>;\n /**\n * Cline LLM provider id (e.g. `'anthropic'`, `'openai'`, `'gemini'`).\n * When omitted, direct authentication uses the Cline backend.\n */\n readonly providerId?: string;\n /**\n * Provider API key. When omitted, the Cline gateway falls back to the\n * provider's environment variable (e.g. `ANTHROPIC_API_KEY`).\n * A record-shaped authentication override disables that fallback.\n */\n readonly apiKey?: string;\n /** Custom provider endpoint. */\n readonly baseUrl?: string;\n /** Extra headers sent to the provider. */\n readonly headers?: Record<string, string>;\n /**\n * Reasoning effort for reasoning-capable models. Use `'none'` to disable\n * reasoning. When omitted, the Cline SDK selects the reasoning behavior.\n */\n readonly reasoningEffort?: ClineReasoningEffort;\n /**\n * Safety cap on agent-loop iterations per turn. Unbounded when omitted.\n */\n readonly maxIterations?: number;\n};\n\n/*\n * The Cline runtime requires snake_case tool names, and each of these\n * built-ins already matches its cross-harness common name — so native names\n * and wire names are identical, and `nativeName` mirrors the key. These zod\n * declarations mirror the JSON schemas handed to the runtime in\n * `cline-tools.ts` — keep the two in sync.\n */\nconst CLINE_BUILTIN_TOOLS = {\n askUserQuestions: {\n ...HARNESS_V1_BUILTIN_TOOLS.askUserQuestions,\n nativeName: 'ask_question',\n toolUseKind: 'readonly',\n },\n read: commonTool('read', {\n nativeName: 'read',\n toolUseKind: 'readonly',\n description: 'Read file contents.',\n inputSchema: z.object({\n file_path: z.string(),\n }),\n }),\n write: commonTool('write', {\n nativeName: 'write',\n toolUseKind: 'edit',\n description: 'Overwrite or create a file.',\n inputSchema: z.object({\n file_path: z.string(),\n content: z.string(),\n }),\n }),\n edit: commonTool('edit', {\n nativeName: 'edit',\n toolUseKind: 'edit',\n description: 'Edit a file by exact string replacement.',\n inputSchema: z.object({\n file_path: z.string(),\n old_string: z.string(),\n new_string: z.string(),\n }),\n }),\n bash: commonTool('bash', {\n nativeName: 'bash',\n toolUseKind: 'bash',\n description: 'Execute a shell command in the sandbox.',\n inputSchema: z.object({\n command: z.string(),\n timeout: z.number().optional(),\n }),\n }),\n grep: commonTool('grep', {\n nativeName: 'grep',\n toolUseKind: 'readonly',\n description: 'Search file contents with regex.',\n inputSchema: z.object({\n pattern: z.string(),\n path: z.string().optional(),\n glob: z.string().optional(),\n ignoreCase: z.boolean().optional(),\n literal: z.boolean().optional(),\n context: z.number().optional(),\n limit: z.number().optional(),\n }),\n }),\n glob: commonTool('glob', {\n nativeName: 'glob',\n toolUseKind: 'readonly',\n description: 'Find files matching a glob pattern.',\n inputSchema: z.object({\n pattern: z.string(),\n path: z.string().optional(),\n limit: z.number().optional(),\n }),\n }),\n ls: {\n ...tool({\n description: 'List directory entries.',\n inputSchema: z.object({\n path: z.string().optional(),\n limit: z.number().optional(),\n }),\n outputSchema: z.unknown(),\n }),\n nativeName: 'ls',\n toolUseKind: 'readonly',\n } as HarnessV1BuiltinTool,\n skills: {\n ...tool({\n description: 'Execute a configured skill by name.',\n inputSchema: z.object({\n skill: z.string(),\n args: z.string().optional(),\n }),\n outputSchema: z.string(),\n }),\n nativeName: 'skills',\n toolUseKind: 'readonly',\n } as HarnessV1BuiltinTool,\n} as const satisfies Record<string, HarnessV1BuiltinTool<any, any>>;\n\nexport function createCline(\n settings: ClineHarnessSettings = {},\n): HarnessV1<typeof CLINE_BUILTIN_TOOLS> {\n return {\n specificationVersion: 'harness-v1',\n harnessId: 'cline',\n builtinTools: CLINE_BUILTIN_TOOLS,\n supportsBuiltinToolApprovals: true,\n supportsBuiltinToolFiltering: true,\n lifecycleStateSchema: clineResumeStateSchema,\n doStart: async startOpts => {\n const authentication = await resolveClineAuthentication({\n auth: settings.auth,\n providerId: settings.providerId,\n apiKey: settings.apiKey,\n });\n const lifecycleState = startOpts.continueFrom ?? startOpts.resumeFrom;\n const resumeData = lifecycleState?.data as\n | { historyFileName?: string }\n | undefined;\n\n return createClineSession({\n sessionId: startOpts.sessionId,\n sandboxSession: startOpts.sandboxSession,\n sessionWorkDir: startOpts.sessionWorkDir,\n settings: {\n authEnv: authentication.environment,\n isAuthenticationEnvironmentOverride:\n isHarnessAuthenticationEnvironment(settings.auth),\n ...(settings.mcpServers ? { mcpServers: settings.mcpServers } : {}),\n ...(settings.providerId ? { providerId: settings.providerId } : {}),\n ...((settings.apiKey ?? authentication.subscriptionApiKey)\n ? { apiKey: settings.apiKey ?? authentication.subscriptionApiKey }\n : {}),\n ...(settings.baseUrl ? { baseUrl: settings.baseUrl } : {}),\n ...(settings.headers ? { headers: settings.headers } : {}),\n ...(startOpts.headers ? { agentHeaders: startOpts.headers } : {}),\n ...(settings.reasoningEffort !== undefined\n ? { reasoningEffort: settings.reasoningEffort }\n : {}),\n ...(settings.maxIterations !== undefined\n ? { maxIterations: settings.maxIterations }\n : {}),\n },\n clientApp: CLINE_CLIENT_APP,\n isResume: lifecycleState != null,\n ...(startOpts.permissionMode\n ? { permissionMode: startOpts.permissionMode }\n : {}),\n ...(startOpts.builtinToolFiltering\n ? { builtinToolFiltering: startOpts.builtinToolFiltering }\n : {}),\n ...(resumeData?.historyFileName\n ? { resumeHistoryFileName: resumeData.historyFileName }\n : {}),\n ...(startOpts.abortSignal\n ? { abortSignal: startOpts.abortSignal }\n : {}),\n });\n },\n };\n}\n","import { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport {\n isHarnessAuthenticationEnvironment,\n shouldResolveNativeSubscription,\n} from '@ai-sdk/harness/utils';\nimport {\n Llms,\n ProviderSettingsManager,\n RuntimeOAuthTokenManager,\n} from '@cline/core';\nimport { resolveClineEnv, type ClineAuthenticationMode } from './cline-auth';\n\nexport type ClineResolvedAuthentication = {\n readonly environment: Record<string, string>;\n readonly subscriptionApiKey?: string;\n};\n\nexport async function resolveClineAuthentication({\n auth,\n env = process.env,\n providerId = 'cline',\n apiKey,\n readSubscription = readClineSubscription,\n}: {\n auth?: ClineAuthenticationMode;\n env?: Record<string, string | undefined>;\n providerId?: string;\n apiKey?: string;\n readSubscription?: (options: {\n providerId: string;\n env: Record<string, string | undefined>;\n }) => Promise<string | undefined>;\n}): Promise<ClineResolvedAuthentication> {\n const environment = resolveClineEnv({ auth, env });\n if (isHarnessAuthenticationEnvironment(auth)) {\n return { environment };\n }\n if (\n !shouldResolveNativeSubscription({\n auth,\n env: environment,\n hasDirectCredential:\n apiKey != null || hasApplicableProviderApiKey({ providerId, env }),\n })\n ) {\n return { environment };\n }\n\n const subscriptionApiKey = await readSubscription({ providerId, env });\n return subscriptionApiKey == null\n ? { environment }\n : { environment, subscriptionApiKey };\n}\n\nexport async function readClineSubscription({\n providerId,\n env = process.env,\n homeDirectory = homedir(),\n}: {\n providerId: string;\n env?: Record<string, string | undefined>;\n homeDirectory?: string;\n}): Promise<string | undefined> {\n const filePath = resolveClineProviderSettingsPath({\n env,\n homeDirectory,\n });\n const manager = new ProviderSettingsManager({ filePath });\n const entry = manager.read().providers[providerId];\n if (entry?.tokenSource !== 'oauth') return undefined;\n const resolution = await new RuntimeOAuthTokenManager({\n providerSettingsManager: manager,\n }).resolveProviderApiKey({ providerId });\n return resolution?.apiKey;\n}\n\nexport function resolveClineProviderSettingsPath({\n env,\n homeDirectory,\n}: {\n env: Record<string, string | undefined>;\n homeDirectory: string;\n}): string {\n const explicitPath = env.CLINE_PROVIDER_SETTINGS_PATH?.trim();\n if (explicitPath) return resolve(explicitPath);\n const dataDirectory = env.CLINE_DATA_DIR?.trim();\n return join(\n dataDirectory\n ? resolve(dataDirectory)\n : join(homeDirectory, '.cline', 'data'),\n 'settings',\n 'providers.json',\n );\n}\n\nfunction hasApplicableProviderApiKey({\n providerId,\n env,\n}: {\n providerId: string;\n env: Record<string, string | undefined>;\n}): boolean {\n if (providerId === 'cline' && env.CLINE_API_KEY != null) return true;\n return (\n Llms.getProviderCollectionSync(providerId)?.provider.env?.some(\n name => env[name] != null,\n ) ?? false\n );\n}\n","import type { HarnessV1Authentication } from '@ai-sdk/harness';\nimport {\n getAiGatewayAuthFromEnv,\n isHarnessAuthenticationEnvironment,\n} from '@ai-sdk/harness/utils';\n\nexport type ClineAuthenticationMode = HarnessV1Authentication;\n\nexport function resolveClineEnv({\n auth = 'auto',\n env = process.env,\n}: {\n auth?: ClineAuthenticationMode;\n env?: Record<string, string | undefined>;\n}): Record<string, string> {\n if (isHarnessAuthenticationEnvironment(auth)) {\n const gatewayAuth = getAiGatewayAuthFromEnv({ env: auth });\n return gatewayAuth.apiKey\n ? toGatewayClineEnv(gatewayAuth)\n : pickDirectClineEnv({ env: auth });\n }\n if (auth === 'direct') {\n return pickDirectClineEnv({ env });\n }\n\n const gatewayAuth = getAiGatewayAuthFromEnv({ env });\n if (auth === 'ai-gateway' || gatewayAuth.apiKey) {\n return toGatewayClineEnv(gatewayAuth);\n }\n\n return pickDirectClineEnv({ env });\n}\n\nfunction toGatewayClineEnv(\n gatewayAuth: ReturnType<typeof getAiGatewayAuthFromEnv>,\n): Record<string, string> {\n return {\n ...(gatewayAuth.apiKey ? { AI_GATEWAY_API_KEY: gatewayAuth.apiKey } : {}),\n AI_GATEWAY_BASE_URL: gatewayAuth.baseUrl,\n };\n}\n\nfunction pickDirectClineEnv({\n env,\n}: {\n env: Record<string, string | undefined>;\n}): Record<string, string> {\n return {\n ...(env.CLINE_API_KEY ? { CLINE_API_KEY: env.CLINE_API_KEY } : {}),\n ...(env.CLINE_API_BASE_URL\n ? { CLINE_API_BASE_URL: env.CLINE_API_BASE_URL }\n : {}),\n };\n}\n","import { createHash } from 'node:crypto';\nimport path from 'node:path';\nimport {\n safeParseJSON,\n type Experimental_SandboxSession,\n} from '@ai-sdk/provider-utils';\nimport type { AgentMessage } from '@cline/agents';\nimport { z } from 'zod/v4';\n\nconst CLINE_HISTORY_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*\\.json$/;\n\nexport function safeClineHistoryFileName(historyFileName: string): string {\n if (!CLINE_HISTORY_FILE_NAME_PATTERN.test(historyFileName)) {\n throw new Error(`Invalid Cline history file name: ${historyFileName}`);\n }\n return historyFileName;\n}\n\nconst clineHistoryFileNameSchema = z\n .string()\n .refine(\n historyFileName => CLINE_HISTORY_FILE_NAME_PATTERN.test(historyFileName),\n 'Cline historyFileName must be a safe .json basename.',\n );\n\n/**\n * Schema for the adapter-specific portion of lifecycle state `data` produced\n * by the Cline harness's resumable lifecycle methods. Carries the basename of\n * the serialized conversation history. The actual history bytes live in a\n * private, session-scoped directory under sandbox HOME so they survive\n * cross-process resume without appearing in the agent workspace.\n */\nexport const clineResumeStateSchema = z.looseObject({\n historyFileName: clineHistoryFileNameSchema.optional(),\n});\n\nexport type ClineResumeStateData = z.infer<typeof clineResumeStateSchema>;\n\nexport const CLINE_DEFAULT_HISTORY_FILE_NAME = 'history.json';\n\nexport function resolveClinePrivateSessionDirectory(input: {\n readonly sandboxHomeDir: string;\n readonly sessionWorkDir: string;\n readonly sessionId: string;\n}): string {\n const sessionKey = createHash('sha256').update(input.sessionId).digest('hex');\n const privateSessionDir = path.posix.join(\n input.sandboxHomeDir,\n '.ai-sdk',\n 'harness-cline',\n sessionKey,\n );\n const relativePath = path.posix.relative(\n input.sessionWorkDir,\n privateSessionDir,\n );\n if (\n relativePath === '' ||\n (!relativePath.startsWith('../') && !path.posix.isAbsolute(relativePath))\n ) {\n throw new Error(\n `Cline private session directory ${JSON.stringify(privateSessionDir)} must be outside sessionWorkDir ${JSON.stringify(input.sessionWorkDir)}.`,\n );\n }\n return privateSessionDir;\n}\n\nfunction resolveContainedSandboxPath(input: {\n readonly privateSessionDir: string;\n readonly historyFileName: string;\n}): string {\n const historyDir = path.posix.resolve(input.privateSessionDir);\n const filePath = path.posix.resolve(\n historyDir,\n safeClineHistoryFileName(input.historyFileName),\n );\n const relativePath = path.posix.relative(historyDir, filePath);\n if (\n relativePath === '' ||\n relativePath.startsWith('..') ||\n path.posix.isAbsolute(relativePath)\n ) {\n throw new Error(\n `Invalid Cline history file name: ${input.historyFileName}`,\n );\n }\n return filePath;\n}\n\n/**\n * Persist the runtime's conversation history into private sandbox state so a\n * future process can resume the session after\n * `HarnessV1SandboxProvider.resume?.({ sessionId })` reattaches the sandbox.\n */\nexport async function persistHistoryToSandbox(args: {\n readonly sandbox: Experimental_SandboxSession;\n readonly privateSessionDir: string;\n readonly historyFileName: string;\n readonly messages: readonly AgentMessage[];\n readonly abortSignal?: AbortSignal;\n}): Promise<void> {\n const remotePath = resolveContainedSandboxPath({\n privateSessionDir: args.privateSessionDir,\n historyFileName: args.historyFileName,\n });\n // `writeTextFile` creates parent directories recursively per the\n // SandboxSession contract.\n await args.sandbox.writeTextFile({\n path: remotePath,\n content: JSON.stringify(args.messages),\n ...(args.abortSignal ? { abortSignal: args.abortSignal } : {}),\n });\n}\n\n/**\n * Pull a previously persisted conversation history from the sandbox. Returns\n * `undefined` when the file is missing or unparsable — resume then falls back\n * to a fresh conversation rather than failing `doStart`.\n */\nexport async function pullHistoryFromSandbox(args: {\n readonly sandbox: Experimental_SandboxSession;\n readonly privateSessionDir: string;\n readonly historyFileName: string;\n readonly abortSignal?: AbortSignal;\n}): Promise<AgentMessage[] | undefined> {\n const remotePath = resolveContainedSandboxPath({\n privateSessionDir: args.privateSessionDir,\n historyFileName: args.historyFileName,\n });\n const content = await args.sandbox.readTextFile({\n path: remotePath,\n ...(args.abortSignal ? { abortSignal: args.abortSignal } : {}),\n });\n if (content == null) return undefined;\n const parsed = await safeParseJSON({ text: content });\n return parsed.success && Array.isArray(parsed.value)\n ? (parsed.value as unknown as AgentMessage[])\n : undefined;\n}\n","import {\n HarnessCapabilityUnsupportedError,\n type HarnessV1BuiltinToolFiltering,\n type HarnessV1ContinueTurnOptions,\n type HarnessV1ContinueTurnState,\n type HarnessV1NetworkSandboxSession,\n type HarnessV1PermissionMode,\n type HarnessV1PromptControl,\n type HarnessV1PromptTurnOptions,\n type HarnessV1QuestionsToolOutput,\n type HarnessV1ResumeSessionState,\n type HarnessV1Session,\n type HarnessV1Skill,\n type HarnessV1StreamPart,\n type HarnessV1ToolSpec,\n} from '@ai-sdk/harness';\nimport {\n getRestrictedSandboxSession,\n resolveSandboxHomeDir,\n} from '@ai-sdk/harness/utils';\nimport type { Experimental_SandboxSession as SandboxSession } from '@ai-sdk/provider-utils';\nimport {\n Agent,\n createTool,\n type AgentMessage,\n type AgentModel,\n type AgentRunResult,\n} from '@cline/agents';\nimport { Llms } from '@cline/core';\nimport { createClineMcpRuntime } from './cline-mcp';\nimport { createClineRemoteOps } from './cline-remote-ops';\nimport {\n CLINE_DEFAULT_HISTORY_FILE_NAME,\n persistHistoryToSandbox,\n pullHistoryFromSandbox,\n resolveClinePrivateSessionDirectory,\n safeClineHistoryFileName,\n} from './cline-resume-state';\nimport {\n createClineSkillsRuntime,\n type ClineSkillsRuntime,\n} from './cline-skills';\nimport {\n buildBuiltinAgentTools,\n buildUserAgentTools,\n CLINE_NATIVE_TOOL_KINDS,\n createClineToolResult,\n isClineBuiltinToolName,\n clineQuestionKey,\n resolveActiveClineBuiltinNames,\n type PendingToolResult,\n type PendingClineQuestion,\n type PendingClineQuestionResult,\n toClineQuestionResult,\n unwrapClineToolResult,\n} from './cline-tools';\nimport {\n createClineTranslatorState,\n finishClineTranslation,\n toolApprovalParts,\n translateClineEvent,\n type ClineTranslatorState,\n} from './cline-translate';\nimport {\n extractUserText,\n mapRunFinishReason,\n usageFromAgentUsage,\n} from './cline-utils';\n\nconst HARNESS_ID = 'cline';\n\nexport type ClineReasoningEffort =\n | 'none'\n | 'minimal'\n | 'low'\n | 'medium'\n | 'high'\n | 'xhigh'\n | 'max';\n\n/*\n * The Cline runtime lives in this Node process, not behind an attachable\n * in-sandbox bridge. During a tool approval pause the turn is still alive and\n * blocked on a parked promise, so detach must keep that live session for the\n * next same-process resume instead of stopping it and failing the promise.\n * Cross-process resume falls back to the history file persisted in the\n * sandbox.\n */\nconst parkedClineSessions = new Map<string, HarnessV1Session>();\n\nexport interface ClineSessionSettings {\n readonly authEnv: Record<string, string>;\n readonly isAuthenticationEnvironmentOverride: boolean;\n readonly mcpServers?: Record<string, unknown>;\n readonly providerId?: string;\n readonly apiKey?: string;\n readonly baseUrl?: string;\n readonly headers?: Record<string, string>;\n readonly agentHeaders?: Readonly<Record<string, string>>;\n readonly reasoningEffort?: ClineReasoningEffort;\n readonly maxIterations?: number;\n}\n\nexport interface CreateClineSessionInput {\n readonly sessionId: string;\n readonly sandboxSession: HarnessV1NetworkSandboxSession | SandboxSession;\n readonly sessionWorkDir: string;\n readonly settings: ClineSessionSettings;\n readonly clientApp: string;\n readonly isResume: boolean;\n readonly permissionMode?: HarnessV1PermissionMode;\n readonly builtinToolFiltering?: HarnessV1BuiltinToolFiltering;\n readonly resumeHistoryFileName?: string;\n readonly abortSignal?: AbortSignal;\n}\n\ninterface PendingToolApproval {\n resolve: (value: { approved: boolean; reason?: string }) => void;\n}\n\ninterface ActiveClineTurn {\n readonly token: object;\n readonly done: Promise<void>;\n}\n\ninterface PendingUserMessage {\n readonly text: string;\n resolve(): void;\n reject(error: unknown): void;\n}\n\n/**\n * Whether a thrown error is an abort — the expected result of\n * `doSuspendTurn` aborting the in-flight turn. Only these are safe to swallow\n * while `suspending`; any other error must surface as an `error` chunk.\n */\nfunction isAbortError(value: unknown): boolean {\n if (value == null) return false;\n const name = (value as { name?: unknown }).name;\n if (name === 'AbortError' || name === 'AgentRuntimeAbortError') {\n return true;\n }\n const text =\n typeof value === 'string'\n ? value\n : value instanceof Error\n ? value.message\n : String(value);\n return /\\baborted\\b|AbortError/i.test(text);\n}\n\nfunction clineBuiltinToolRequiresApproval(input: {\n permissionMode: HarnessV1PermissionMode;\n kind: 'readonly' | 'edit' | 'bash';\n}): boolean {\n if (input.permissionMode === 'allow-all') return false;\n if (input.permissionMode === 'allow-edits') return input.kind === 'bash';\n return input.kind === 'edit' || input.kind === 'bash';\n}\n\nfunction buildSystemPrompt(input: {\n sessionWorkDir: string;\n sandboxDescription: string;\n}): string {\n return [\n 'You are Cline, an autonomous coding agent operating inside a sandboxed workspace.',\n `## Workspace\\n\\nThe workspace root is \\`${input.sessionWorkDir}\\`. All relative file paths and shell commands resolve against it. Use the provided tools (read, write, edit, bash, grep, glob, ls) to inspect and modify the workspace.`,\n `## Sandbox\\n\\n${input.sandboxDescription}`,\n ].join('\\n\\n');\n}\n\nfunction toClineBackendProviderBaseUrl(baseUrl: string): string {\n return `${baseUrl.replace(/\\/+$/, '')}/api/v1`;\n}\n\nfunction toAiGatewayProviderBaseUrl(baseUrl: string): string {\n const trimmed = baseUrl.replace(/\\/+$/, '');\n return trimmed.endsWith('/v1') ? trimmed : `${trimmed}/v1`;\n}\n\nfunction createClineAgentModel({\n settings,\n clientApp,\n modelId,\n}: {\n settings: ClineSessionSettings;\n clientApp: string;\n modelId: string | undefined;\n}): { model: AgentModel; providerId: string } {\n const gatewayBaseUrl = settings.authEnv.AI_GATEWAY_BASE_URL;\n const isAiGateway = gatewayBaseUrl != null;\n const providerId = isAiGateway ? 'cline' : (settings.providerId ?? 'cline');\n const apiKey = isAiGateway\n ? settings.authEnv.AI_GATEWAY_API_KEY\n : (settings.apiKey ??\n (providerId === 'cline' ? settings.authEnv.CLINE_API_KEY : undefined));\n const baseUrl = isAiGateway\n ? toAiGatewayProviderBaseUrl(gatewayBaseUrl)\n : (settings.baseUrl ??\n (providerId === 'cline' && settings.authEnv.CLINE_API_BASE_URL\n ? toClineBackendProviderBaseUrl(settings.authEnv.CLINE_API_BASE_URL)\n : undefined));\n const headers = isAiGateway\n ? {\n ...settings.headers,\n ...settings.agentHeaders,\n 'User-Agent': clientApp,\n 'x-client-app': clientApp,\n }\n : settings.headers != null || settings.agentHeaders != null\n ? {\n ...settings.headers,\n ...settings.agentHeaders,\n }\n : undefined;\n const gateway = Llms.createGateway({\n providerConfigs: [\n {\n providerId,\n ...(apiKey ? { apiKey } : {}),\n ...(baseUrl ? { baseUrl } : {}),\n ...(headers ? { headers } : {}),\n ...(isAiGateway || settings.isAuthenticationEnvironmentOverride\n ? { apiKeyEnv: [] }\n : {}),\n },\n ],\n });\n const modelSelection = {\n providerId,\n ...(modelId ? { modelId } : {}),\n };\n const modelOptions =\n settings.reasoningEffort === 'none'\n ? { reasoning: { enabled: false } }\n : {\n reasoning: {\n enabled: true,\n effort: settings.reasoningEffort,\n },\n };\n const model =\n settings.reasoningEffort === undefined\n ? gateway.createAgentModel(modelSelection)\n : gateway.createAgentModel(modelSelection, modelOptions);\n\n return {\n model,\n providerId,\n };\n}\n\nexport async function createClineSession(\n input: CreateClineSessionInput,\n): Promise<HarnessV1Session> {\n if (input.isResume) {\n const parkedSession = parkedClineSessions.get(input.sessionId);\n if (parkedSession) {\n parkedClineSessions.delete(input.sessionId);\n return {\n ...parkedSession,\n isResume: true,\n };\n }\n }\n\n const toolSafeSandboxSession = getRestrictedSandboxSession(\n input.sandboxSession,\n );\n const sandboxHomeDir = await resolveSandboxHomeDir({\n sandbox: toolSafeSandboxSession,\n ...(input.abortSignal ? { abortSignal: input.abortSignal } : {}),\n });\n const privateSessionDir = resolveClinePrivateSessionDirectory({\n sandboxHomeDir,\n sessionWorkDir: input.sessionWorkDir,\n sessionId: input.sessionId,\n });\n const permissionMode = input.permissionMode ?? 'allow-all';\n const activeBuiltinNames = resolveActiveClineBuiltinNames(\n input.builtinToolFiltering,\n );\n\n const ops = createClineRemoteOps({\n sandbox: toolSafeSandboxSession,\n workDir: input.sessionWorkDir,\n });\n\n // On resume: pull the persisted conversation history from the sandbox so\n // the fresh runtime instance starts from the prior transcript.\n let currentMessages: readonly AgentMessage[] = [];\n if (input.isResume && input.resumeHistoryFileName) {\n const restored = await pullHistoryFromSandbox({\n sandbox: toolSafeSandboxSession,\n privateSessionDir,\n historyFileName: safeClineHistoryFileName(input.resumeHistoryFileName),\n ...(input.abortSignal ? { abortSignal: input.abortSignal } : {}),\n });\n if (restored) {\n currentMessages = restored;\n }\n }\n const mcpRuntime = await createClineMcpRuntime({\n mcpServers: input.settings.mcpServers,\n });\n let activeModelId: string | undefined;\n let agentModel = createClineAgentModel({\n settings: input.settings,\n clientApp: input.clientApp,\n modelId: activeModelId,\n });\n\n // Per-session mutable state we hold across prompts.\n let agent: Agent | undefined;\n let unsubscribe: (() => void) | undefined;\n let lastAgentConfigurationSignature: string | undefined;\n let agentHasRun = false;\n let stopped = false;\n /*\n * Set by `doSuspendTurn` before it aborts the in-flight turn at a slice\n * boundary. The turn settles silently when this is set, so the stream\n * closes cleanly (no spurious `error` chunk) — the next slice\n * rerun-continues from the persisted history.\n */\n let suspending = false;\n const pendingToolResults = new Map<string, PendingToolResult>();\n const pendingToolApprovals = new Map<string, PendingToolApproval>();\n const pendingUserMessages: PendingUserMessage[] = [];\n let acceptingUserMessages = false;\n\n // Emit channel set at the start of every turn and cleared on end.\n let currentEmit: ((part: HarnessV1StreamPart) => void) | undefined;\n let translatorState: ClineTranslatorState | undefined;\n const pendingQuestions = new Map<string, PendingClineQuestion>();\n const pendingQuestionResults = new Map<string, PendingClineQuestionResult>();\n let activeTurn: ActiveClineTurn | undefined;\n\n function settlePendingToolResults(reason: string): void {\n for (const pending of pendingToolResults.values()) {\n pending.resolve(\n createClineToolResult({\n output: { error: reason },\n isError: true,\n }),\n );\n }\n pendingToolResults.clear();\n }\n\n function settlePendingToolApprovals(reason: string): void {\n for (const pending of pendingToolApprovals.values()) {\n pending.resolve({ approved: false, reason });\n }\n pendingToolApprovals.clear();\n }\n\n function consumePendingUserMessage(): string | undefined {\n const pending = pendingUserMessages.shift();\n if (pending == null) return undefined;\n pending.resolve();\n return pending.text;\n }\n\n function rejectPendingUserMessages(error: unknown): void {\n for (const pending of pendingUserMessages) {\n pending.reject(error);\n }\n pendingUserMessages.length = 0;\n }\n\n function settlePendingQuestions(reason: string): void {\n for (const pending of pendingQuestions.values()) {\n pending.resolve(reason);\n }\n pendingQuestions.clear();\n pendingQuestionResults.clear();\n }\n\n async function persistHistory(): Promise<void> {\n const messages = agent?.snapshot().messages ?? currentMessages;\n await persistHistoryToSandbox({\n sandbox: toolSafeSandboxSession,\n privateSessionDir,\n historyFileName: CLINE_DEFAULT_HISTORY_FILE_NAME,\n messages,\n });\n }\n\n function requestBuiltinToolApproval(toolCall: {\n toolCallId: string;\n toolName: string;\n input: unknown;\n }): Promise<{ approved: boolean; reason?: string }> {\n if (translatorState && currentEmit) {\n for (const part of toolApprovalParts(translatorState, toolCall)) {\n currentEmit(part);\n }\n }\n return new Promise(resolve => {\n pendingToolApprovals.set(toolCall.toolCallId, { resolve });\n });\n }\n\n function rebuildAgent(rebuildInput: {\n userTools: ReadonlyArray<HarnessV1ToolSpec>;\n skillsRuntime: ClineSkillsRuntime;\n instructions?: string;\n responseFormat?: HarnessV1PromptTurnOptions['responseFormat'];\n }): void {\n unsubscribe?.();\n unsubscribe = undefined;\n agent = new Agent({\n model: agentModel.model,\n ...(activeModelId\n ? {\n messageModelInfo: {\n id: activeModelId,\n provider: agentModel.providerId,\n },\n }\n : {}),\n sessionId: input.sessionId,\n systemPrompt: (() => {\n const baseSystemPrompt = buildSystemPrompt({\n sessionWorkDir: input.sessionWorkDir,\n sandboxDescription: toolSafeSandboxSession.description,\n });\n return rebuildInput.instructions\n ? `${baseSystemPrompt}\\n\\n${rebuildInput.instructions}`\n : baseSystemPrompt;\n })(),\n initialMessages: currentMessages,\n toolExecution: 'parallel',\n ...(input.settings.maxIterations !== undefined\n ? { maxIterations: input.settings.maxIterations }\n : {}),\n tools: [\n ...buildBuiltinAgentTools({\n ops,\n activeNames: activeBuiltinNames,\n pendingQuestions,\n pendingQuestionResults,\n }),\n ...(rebuildInput.skillsRuntime.tool &&\n activeBuiltinNames.includes('skills')\n ? [rebuildInput.skillsRuntime.tool]\n : []),\n ...mcpRuntime.tools,\n ...buildUserAgentTools({\n specs: rebuildInput.userTools,\n pendingToolResults,\n }),\n ...(rebuildInput.responseFormat?.type === 'json' &&\n rebuildInput.responseFormat.schema != null\n ? [\n createTool({\n name: 'structured_output',\n description:\n rebuildInput.responseFormat.description ??\n 'Return the final structured output.',\n inputSchema: {\n type: 'object',\n properties: {\n output: rebuildInput.responseFormat.schema,\n },\n required: ['output'],\n additionalProperties: false,\n },\n lifecycle: { completesRun: true },\n execute: async ({ output }: { output: unknown }) =>\n JSON.stringify(output),\n }),\n ]\n : []),\n ],\n ...(rebuildInput.responseFormat?.type === 'json'\n ? { completionPolicy: { requireCompletionTool: true } }\n : {}),\n hooks: {\n afterTool: ({ result }) => {\n const toolResult = unwrapClineToolResult(result.output);\n return toolResult == null ? undefined : { result: toolResult };\n },\n },\n // Built-in tools whose kind requires approval under the session's\n // permission mode are marked `autoApprove: false`; the runtime then\n // routes them through `requestToolApproval` below. User tools are\n // approved by the harness framework, never by the adapter.\n toolPolicies: Object.fromEntries(\n activeBuiltinNames\n .filter(name =>\n clineBuiltinToolRequiresApproval({\n permissionMode,\n kind: CLINE_NATIVE_TOOL_KINDS[name],\n }),\n )\n .map(name => [name, { autoApprove: false }]),\n ),\n requestToolApproval: request => {\n if (!isClineBuiltinToolName(request.toolName)) {\n // Custom host-executed tool approvals are handled by the framework\n // before results are submitted back; the adapter never gates them.\n return { approved: true };\n }\n return requestBuiltinToolApproval({\n toolCallId: request.toolCallId,\n toolName: request.toolName,\n input: request.input,\n });\n },\n // Mid-turn user messages injected via `submitUserMessage` are consumed\n // by the runtime between loop iterations, before the next model call.\n consumePendingUserMessage,\n });\n agentHasRun = false;\n\n unsubscribe = agent.subscribe(event => {\n if (!translatorState || !currentEmit) return;\n for (const part of translateClineEvent(event, translatorState)) {\n currentEmit(part);\n }\n });\n }\n\n function createPromptControl(controlInput: {\n done: Promise<void>;\n abortSignal?: AbortSignal;\n }): HarnessV1PromptControl {\n const abortHandler = () => {\n // Settle parked host-tool promises first so the runtime's tool\n // executions do not dangle, then abort the loop itself.\n settlePendingToolResults('Turn aborted');\n settlePendingToolApprovals('Turn aborted');\n settlePendingQuestions('The question was cancelled.');\n agent?.abort('Turn aborted by caller');\n };\n if (controlInput.abortSignal) {\n controlInput.abortSignal.addEventListener('abort', abortHandler, {\n once: true,\n });\n void controlInput.done.then(\n () => {\n controlInput.abortSignal?.removeEventListener('abort', abortHandler);\n },\n () => {\n controlInput.abortSignal?.removeEventListener('abort', abortHandler);\n },\n );\n }\n\n return {\n async submitToolResult(args) {\n const pendingQuestion = pendingQuestions.get(args.toolCallId);\n if (pendingQuestion != null) {\n pendingQuestions.delete(args.toolCallId);\n pendingQuestion.resolve(\n toClineQuestionResult({\n nativeInput: pendingQuestion.input,\n output: args.output as HarnessV1QuestionsToolOutput,\n }),\n );\n return;\n }\n if (args.toolResult?.toolName === 'askUserQuestions') {\n const nativeRequest = args.toolResult.providerOptions?.cline\n ?.nativeRequest as PendingClineQuestion['input'] | undefined;\n if (nativeRequest == null) return;\n pendingQuestionResults.set(clineQuestionKey(nativeRequest), {\n output: args.output as HarnessV1QuestionsToolOutput,\n });\n return;\n }\n const pending = pendingToolResults.get(args.toolCallId);\n if (!pending) return;\n pendingToolResults.delete(args.toolCallId);\n pending.resolve(\n createClineToolResult({\n output: args.output,\n isError: args.isError,\n }),\n );\n },\n async submitToolApproval(args) {\n const pending = pendingToolApprovals.get(args.approvalId);\n if (!pending) return;\n pendingToolApprovals.delete(args.approvalId);\n pending.resolve({\n approved: args.approved,\n ...(args.reason !== undefined ? { reason: args.reason } : {}),\n });\n },\n submitUserMessage(text) {\n if (!acceptingUserMessages) {\n return Promise.reject(\n new Error('Cline has no running turn to steer.'),\n );\n }\n return new Promise<void>((resolve, reject) => {\n pendingUserMessages.push({ text, resolve, reject });\n });\n },\n done: controlInput.done,\n };\n }\n\n /*\n * Drive one turn against the Cline runtime and return the control surface.\n * Shared by `doPromptTurn` (a fresh user prompt) and `doContinueTurn`\n * (no prompt — the runtime continues its own thread after a rerun resume).\n */\n async function runTurn(turnOpts: {\n text: string | undefined;\n model?: string;\n skills: ReadonlyArray<HarnessV1Skill>;\n tools: ReadonlyArray<HarnessV1ToolSpec>;\n instructions?: string;\n emit: (part: HarnessV1StreamPart) => void;\n abortSignal?: AbortSignal;\n responseFormat?: HarnessV1PromptTurnOptions['responseFormat'];\n }): Promise<HarnessV1PromptControl> {\n if (stopped) {\n throw new Error('Cline session has been stopped.');\n }\n\n const userTools = turnOpts.tools;\n const skillsRuntime = createClineSkillsRuntime({\n skills: turnOpts.skills,\n });\n if (\n turnOpts.responseFormat?.type === 'json' &&\n turnOpts.responseFormat.schema == null\n ) {\n throw new HarnessCapabilityUnsupportedError({\n message:\n \"Harness 'cline' requires a JSON schema for structured output.\",\n harnessId: HARNESS_ID,\n });\n }\n if (\n turnOpts.responseFormat?.type === 'json' &&\n agentModel.providerId === 'openai-codex-cli'\n ) {\n throw new HarnessCapabilityUnsupportedError({\n message:\n \"Harness 'cline' cannot require structured output with the openai-codex-cli provider because that provider does not expose external tools.\",\n harnessId: HARNESS_ID,\n });\n }\n\n if (turnOpts.model != null && turnOpts.model !== activeModelId) {\n activeModelId = turnOpts.model;\n agentModel = createClineAgentModel({\n settings: input.settings,\n clientApp: input.clientApp,\n modelId: activeModelId,\n });\n }\n\n const signature = JSON.stringify({\n modelId: activeModelId,\n tools: userTools,\n responseFormat: turnOpts.responseFormat,\n instructions: turnOpts.instructions,\n skills: skillsRuntime.signature,\n });\n if (agent == null || signature !== lastAgentConfigurationSignature) {\n currentMessages = agent?.snapshot().messages ?? currentMessages;\n rebuildAgent({\n userTools,\n skillsRuntime,\n responseFormat: turnOpts.responseFormat,\n ...(turnOpts.instructions\n ? { instructions: turnOpts.instructions }\n : {}),\n });\n lastAgentConfigurationSignature = signature;\n }\n\n currentEmit = turnOpts.emit;\n const userToolNames = new Set(userTools.map(tool => tool.name));\n translatorState = createClineTranslatorState({\n builtinToolNames: activeBuiltinNames.filter(\n name => !userToolNames.has(name),\n ),\n hostToolNames: userToolNames,\n ignoredToolNames:\n turnOpts.responseFormat?.type === 'json' ? ['structured_output'] : [],\n mcpToolNames: mcpRuntime.toolNames,\n });\n\n turnOpts.emit({\n type: 'stream-start',\n ...(activeModelId ? { modelId: activeModelId } : {}),\n });\n\n acceptingUserMessages = true;\n const turnPromise = (async () => {\n const runtime = agent!;\n try {\n let nextText = turnOpts.text;\n let result: AgentRunResult;\n for (;;) {\n // `text` is undefined only on rerun-continue: `continue()` without\n // input re-drives the loop from the restored transcript instead of\n // pushing an empty user message.\n result =\n nextText === undefined\n ? await runtime.continue()\n : agentHasRun\n ? await runtime.continue(nextText)\n : await runtime.run(nextText);\n agentHasRun = true;\n currentMessages = result.messages;\n\n if (translatorState) {\n for (const part of finishClineTranslation(translatorState)) {\n currentEmit?.(part);\n }\n }\n\n if (result.status !== 'completed') break;\n const pendingUserMessage = consumePendingUserMessage();\n if (pendingUserMessage == null) break;\n nextText = pendingUserMessage;\n }\n\n if (\n turnOpts.responseFormat?.type === 'json' &&\n result.status === 'completed'\n ) {\n const id = `structured-output-${input.sessionId}`;\n currentEmit?.({ type: 'text-start', id });\n currentEmit?.({\n type: 'text-delta',\n id,\n delta: result.outputText,\n });\n currentEmit?.({ type: 'text-end', id });\n currentEmit?.({\n type: 'finish-step',\n finishReason: { unified: 'stop', raw: 'structured-output' },\n usage: {\n inputTokens: {\n total: 0,\n noCache: undefined,\n cacheRead: undefined,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: 0,\n text: undefined,\n reasoning: undefined,\n },\n },\n });\n }\n\n if (result.status === 'aborted') {\n /*\n * A `doSuspendTurn` aborts the in-flight turn on purpose — settle\n * silently so the stream closes cleanly; the next slice\n * rerun-continues from the persisted history. Caller-driven aborts\n * finish the turn with an `other`/aborted reason.\n */\n if (suspending) return;\n currentEmit?.({\n type: 'finish',\n finishReason: mapRunFinishReason(result.status),\n totalUsage: usageFromAgentUsage(result.usage),\n });\n return;\n }\n\n if (result.status === 'failed') {\n currentEmit?.({\n type: 'error',\n error: result.error ?? new Error('Cline agent run failed'),\n });\n return;\n }\n\n currentEmit?.({\n type: 'finish',\n finishReason: mapRunFinishReason(result.status),\n totalUsage: usageFromAgentUsage(result.usage),\n });\n } catch (error) {\n // `run` resolves for aborted/failed statuses; a throw here is\n // unanticipated (e.g. config error). Swallow only the abort our own\n // suspend caused; surface anything else.\n if (suspending && isAbortError(error)) return;\n currentEmit?.({ type: 'error', error });\n } finally {\n acceptingUserMessages = false;\n rejectPendingUserMessages(\n new Error('Cline turn ended before accepting the user message.'),\n );\n }\n })();\n\n const activeTurnToken = {};\n const done = turnPromise.finally(() => {\n if (activeTurn?.token === activeTurnToken) {\n activeTurn = undefined;\n }\n currentEmit = undefined;\n });\n activeTurn = {\n token: activeTurnToken,\n done,\n };\n\n return createPromptControl({\n done,\n ...(turnOpts.abortSignal ? { abortSignal: turnOpts.abortSignal } : {}),\n });\n }\n\n async function teardown(): Promise<void> {\n unsubscribe?.();\n unsubscribe = undefined;\n agent = undefined;\n await mcpRuntime.dispose();\n }\n\n const doStop = async (): Promise<HarnessV1ResumeSessionState> => {\n if (stopped) {\n throw new Error('Cline session has been stopped.');\n }\n stopped = true;\n parkedClineSessions.delete(input.sessionId);\n settlePendingToolResults('Cline session stopped');\n settlePendingToolApprovals('Cline session stopped');\n settlePendingQuestions('The question was cancelled.');\n\n // Persist the conversation into the sandbox so a future process can pick\n // it up after the sandbox provider reattaches.\n try {\n await persistHistory();\n } catch {\n // Best-effort: a missing history file means resume returns to a fresh\n // conversation rather than failing stop.\n }\n\n agent?.abort('Cline session stopped');\n await teardown();\n\n return {\n type: 'resume-session',\n harnessId: HARNESS_ID,\n specificationVersion: 'harness-v1',\n data: { historyFileName: CLINE_DEFAULT_HISTORY_FILE_NAME },\n };\n };\n\n const sessionImpl: HarnessV1Session = {\n sessionId: input.sessionId,\n isResume: input.isResume,\n\n // The Cline runtime has no bridge to attach to and no in-sandbox event\n // log to replay; its only cross-process resume path is restoring the\n // persisted history on a fresh runtime, i.e. `rerun`.\n\n doPromptTurn: async (\n promptOpts: HarnessV1PromptTurnOptions,\n ): Promise<HarnessV1PromptControl> => {\n return runTurn({\n text: extractUserText(promptOpts.prompt),\n ...(promptOpts.model ? { model: promptOpts.model } : {}),\n skills: promptOpts.skills,\n tools: promptOpts.tools ?? [],\n ...(promptOpts.instructions\n ? { instructions: promptOpts.instructions }\n : {}),\n emit: promptOpts.emit,\n ...(promptOpts.abortSignal\n ? { abortSignal: promptOpts.abortSignal }\n : {}),\n responseFormat: promptOpts.responseFormat,\n });\n },\n\n doContinueTurn: async (\n continueOpts: HarnessV1ContinueTurnOptions,\n ): Promise<HarnessV1PromptControl> => {\n if (activeTurn != null) {\n currentEmit = continueOpts.emit;\n return createPromptControl({\n done: activeTurn.done,\n ...(continueOpts.abortSignal\n ? { abortSignal: continueOpts.abortSignal }\n : {}),\n });\n }\n\n /*\n * The model runs on the host, so there is no live turn to attach to —\n * the previous slice's turn died with its process. Rerun-continue:\n * re-drive the runtime from the history restored on resume. Lossy —\n * work in flight at the slice boundary is recomputed, because a\n * host-resident runtime cannot do a lossless attach.\n */\n return runTurn({\n text: undefined,\n ...(continueOpts.model ? { model: continueOpts.model } : {}),\n skills: continueOpts.skills,\n tools: continueOpts.tools ?? [],\n ...(continueOpts.instructions\n ? { instructions: continueOpts.instructions }\n : {}),\n emit: continueOpts.emit,\n ...(continueOpts.abortSignal\n ? { abortSignal: continueOpts.abortSignal }\n : {}),\n responseFormat: continueOpts.responseFormat,\n });\n },\n\n doCompact: async () => {\n throw new HarnessCapabilityUnsupportedError({\n message:\n 'cline: manual compaction is not supported by the standalone Cline runtime.',\n harnessId: HARNESS_ID,\n });\n },\n\n doDestroy: async () => {\n if (stopped) return;\n stopped = true;\n parkedClineSessions.delete(input.sessionId);\n settlePendingToolResults('Cline session stopped');\n settlePendingToolApprovals('Cline session stopped');\n agent?.abort('Cline session destroyed');\n await teardown();\n },\n\n doStop,\n\n doDetach: async (): Promise<HarnessV1ResumeSessionState> => {\n if (\n activeTurn != null ||\n pendingToolResults.size > 0 ||\n pendingQuestions.size > 0\n ) {\n parkedClineSessions.set(input.sessionId, sessionImpl);\n try {\n await persistHistory();\n } catch {\n /*\n * The parked in-process session is the authoritative continuation\n * path while the live turn is waiting on host input. Persistence\n * is only a fallback for later non-live resumes.\n */\n }\n return {\n type: 'resume-session',\n harnessId: HARNESS_ID,\n specificationVersion: 'harness-v1',\n data: { historyFileName: CLINE_DEFAULT_HISTORY_FILE_NAME },\n };\n }\n return doStop();\n },\n\n doSuspendTurn: async (): Promise<HarnessV1ContinueTurnState> => {\n if (stopped) {\n throw new Error('Cline session has been stopped.');\n }\n if (\n activeTurn != null &&\n (pendingToolResults.size > 0 ||\n pendingToolApprovals.size > 0 ||\n pendingQuestions.size > 0)\n ) {\n parkedClineSessions.set(input.sessionId, sessionImpl);\n try {\n await persistHistory();\n } catch {\n /*\n * While waiting on host input, the live parked session is the\n * authoritative same-process continuation path. The sandbox copy\n * remains a best-effort fallback for a later cold resume.\n */\n }\n return {\n type: 'continue-turn',\n harnessId: HARNESS_ID,\n specificationVersion: 'harness-v1',\n data: { historyFileName: CLINE_DEFAULT_HISTORY_FILE_NAME },\n };\n }\n /*\n * The model runs in this host process, which is about to be suspended\n * at the slice boundary — the in-flight turn cannot survive it. Abort\n * it (the turn settles silently via the `suspending` guard so the\n * stream closes cleanly), persist the history into the sandbox, and\n * tear down host-side resources. The sandbox itself is left running;\n * the next slice pulls the history after the sandbox provider\n * reattaches and rerun-continues. The tail in flight at the boundary\n * is recomputed — a host-resident runtime cannot freeze a live turn\n * the way a bridge adapter can.\n */\n suspending = true;\n agent?.abort('Cline session suspended');\n if (activeTurn) {\n await activeTurn.done.catch(() => {});\n }\n\n try {\n await persistHistory();\n } catch {\n // Best-effort: a missing/failed copy leaves the previously persisted\n // history in place, so the next slice resumes from a slightly older\n // (still valid) state.\n }\n\n stopped = true;\n parkedClineSessions.delete(input.sessionId);\n settlePendingToolResults('Cline session suspended');\n settlePendingToolApprovals('Cline session suspended');\n await teardown();\n\n return {\n type: 'continue-turn',\n harnessId: HARNESS_ID,\n specificationVersion: 'harness-v1',\n data: { historyFileName: CLINE_DEFAULT_HISTORY_FILE_NAME },\n };\n },\n };\n\n return sessionImpl;\n}\n","import type { AgentTool } from '@cline/agents';\nimport type {\n CreateMcpToolsOptions,\n McpManager,\n McpManagerOptions,\n McpServerClientFactory,\n McpServerRegistration,\n McpServerTransportConfig,\n} from '@cline/core';\n\nconst CLINE_CORE_PACKAGE: string = '@cline/core';\n\ntype ClineCoreMcpModule = {\n createDefaultMcpServerClientFactory(): McpServerClientFactory;\n createMcpTools(options: CreateMcpToolsOptions): Promise<AgentTool[]>;\n InMemoryMcpManager: new (options: McpManagerOptions) => McpManager;\n};\n\nexport interface ClineMcpRuntime {\n readonly tools: ReadonlyArray<AgentTool>;\n readonly toolNames: ReadonlySet<string>;\n dispose(): Promise<void>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value != null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction optionalStringArray(value: unknown): string[] | undefined {\n return Array.isArray(value) && value.every(item => typeof item === 'string')\n ? value\n : undefined;\n}\n\nfunction optionalStringRecord(\n value: unknown,\n): Record<string, string> | undefined {\n return isRecord(value) &&\n Object.values(value).every(item => typeof item === 'string')\n ? (value as Record<string, string>)\n : undefined;\n}\n\nfunction resolveTransport(input: {\n serverName: string;\n config: Record<string, unknown>;\n}): McpServerTransportConfig {\n if (isRecord(input.config.transport)) {\n return input.config.transport as unknown as McpServerTransportConfig;\n }\n\n if (typeof input.config.command === 'string') {\n const args = optionalStringArray(input.config.args);\n const env = optionalStringRecord(input.config.env);\n return {\n type: 'stdio',\n command: input.config.command,\n ...(args ? { args } : {}),\n ...(typeof input.config.cwd === 'string'\n ? { cwd: input.config.cwd }\n : {}),\n ...(env ? { env } : {}),\n };\n }\n\n if (typeof input.config.url === 'string') {\n const configuredType = input.config.type ?? input.config.transportType;\n const headers = optionalStringRecord(input.config.headers);\n return {\n type:\n configuredType === 'http' || configuredType === 'streamableHttp'\n ? 'streamableHttp'\n : 'sse',\n url: input.config.url,\n ...(headers ? { headers } : {}),\n };\n }\n\n throw new Error(\n `Cline MCP server ${JSON.stringify(input.serverName)} must define a transport, command, or URL.`,\n );\n}\n\nfunction resolveRegistration(input: {\n serverName: string;\n config: unknown;\n}): McpServerRegistration {\n if (!isRecord(input.config)) {\n throw new Error(\n `Cline MCP server ${JSON.stringify(input.serverName)} must be configured with an object value.`,\n );\n }\n\n return {\n name: input.serverName,\n transport: resolveTransport({\n serverName: input.serverName,\n config: input.config,\n }),\n ...(typeof input.config.disabled === 'boolean'\n ? { disabled: input.config.disabled }\n : {}),\n ...(isRecord(input.config.metadata)\n ? { metadata: input.config.metadata }\n : {}),\n ...(isRecord(input.config.oauth) ? { oauth: input.config.oauth } : {}),\n };\n}\n\nexport async function createClineMcpRuntime(input: {\n mcpServers: Record<string, unknown> | undefined;\n}): Promise<ClineMcpRuntime> {\n if (input.mcpServers == null || Object.keys(input.mcpServers).length === 0) {\n return {\n tools: [],\n toolNames: new Set(),\n dispose: async () => {},\n };\n }\n\n const {\n createDefaultMcpServerClientFactory,\n createMcpTools,\n InMemoryMcpManager,\n } = (await import(CLINE_CORE_PACKAGE)) as ClineCoreMcpModule;\n const manager = new InMemoryMcpManager({\n clientFactory: createDefaultMcpServerClientFactory(),\n });\n const tools: AgentTool[] = [];\n\n try {\n for (const [serverName, config] of Object.entries(input.mcpServers)) {\n const registration = resolveRegistration({ serverName, config });\n await manager.registerServer(registration);\n if (registration.disabled) continue;\n tools.push(\n ...(await createMcpTools({\n serverName,\n provider: manager,\n })),\n );\n }\n } catch (error) {\n await manager.dispose().catch(() => {});\n throw error;\n }\n\n return {\n tools,\n toolNames: new Set(tools.map(tool => tool.name)),\n dispose: async () => manager.dispose(),\n };\n}\n","import path from 'node:path';\nimport { shellQuote } from '@ai-sdk/harness/utils';\nimport type { Experimental_SandboxSession } from '@ai-sdk/provider-utils';\n\n/**\n * Sandbox-backed implementations of the Cline harness's built-in tools.\n *\n * The Cline runtime executes on the host, but the workspace the model reasons\n * about lives in the sandbox — every file/shell operation goes through the\n * restricted `SandboxSession` surface. Relative paths resolve against the\n * per-session working directory the framework created.\n */\nexport interface ClineRemoteOpsOptions {\n readonly sandbox: Experimental_SandboxSession;\n /** Absolute sandbox path of the session's working directory. */\n readonly workDir: string;\n}\n\nexport interface ClineRemoteOps {\n resolvePath(inputPath: string): string;\n readFile(inputPath: string): Promise<string>;\n writeFile(inputPath: string, content: string): Promise<void>;\n editFile(inputPath: string, oldText: string, newText: string): Promise<void>;\n bash(\n command: string,\n input?: {\n /** Timeout in seconds (the `bash` tool contract). */\n timeout?: number;\n signal?: AbortSignal;\n },\n ): Promise<{ output: string; exitCode: number }>;\n grep(\n pattern: string,\n input?: {\n path?: string;\n glob?: string;\n ignoreCase?: boolean;\n literal?: boolean;\n context?: number;\n limit?: number;\n },\n ): Promise<string>;\n glob(pattern: string, inputPath?: string, limit?: number): Promise<string[]>;\n ls(inputPath?: string, limit?: number): Promise<string[]>;\n}\n\nexport function createClineRemoteOps(\n options: ClineRemoteOpsOptions,\n): ClineRemoteOps {\n const { sandbox, workDir } = options;\n const normalizedWorkDir = path.posix.normalize(workDir);\n\n const isInsidePath = ({\n parent,\n candidate,\n }: {\n parent: string;\n candidate: string;\n }): boolean => {\n const relative = path.posix.relative(parent, candidate);\n return (\n relative === '' ||\n (relative !== '..' &&\n !relative.startsWith('../') &&\n !path.posix.isAbsolute(relative))\n );\n };\n\n const assertWorkspacePath = (inputPath: string): string => {\n const normalized = path.posix.normalize(inputPath);\n if (!isInsidePath({ parent: normalizedWorkDir, candidate: normalized })) {\n throw new Error(`Cline path escapes the workspace: ${inputPath}`);\n }\n return normalized;\n };\n\n const resolvePath = (inputPath: string): string => {\n const resolved = path.posix.isAbsolute(inputPath)\n ? path.posix.normalize(inputPath)\n : path.posix.normalize(path.posix.join(normalizedWorkDir, inputPath));\n return assertWorkspacePath(resolved);\n };\n\n const runShell = async ({\n command,\n signal,\n }: {\n command: string;\n signal?: AbortSignal;\n }): Promise<{ exitCode: number; output: string }> => {\n // `sandbox.run({ command })` already wraps in a shell; interpolated\n // paths/values inside `command` are quoted with `shellQuote` by callers.\n const result = await sandbox.run({\n command,\n workingDirectory: normalizedWorkDir,\n ...(signal ? { abortSignal: signal } : {}),\n });\n return {\n exitCode: result.exitCode,\n output: `${result.stdout}${result.stderr}`,\n };\n };\n\n const lastOutputLine = (output: string): string | undefined =>\n output.trim().split('\\n').filter(Boolean).at(-1);\n\n const resolveExistingSandboxPath = async ({\n remotePath,\n inputPath,\n missingMessage,\n }: {\n remotePath: string;\n inputPath: string;\n missingMessage?: string;\n }): Promise<string> => {\n const result = await runShell({\n command: [\n `target=${shellQuote(remotePath)}`,\n 'if [ ! -e \"$target\" ]; then echo \"__CLINE_REALPATH_NOT_FOUND__\"; exit 2; fi',\n 'resolved=$(realpath \"$target\" 2>/dev/null) || { echo \"__CLINE_REALPATH_FAILED__\"; exit 3; }',\n 'printf \\'%s\\\\n\\' \"$resolved\"',\n ].join('; '),\n });\n\n if (result.output.includes('__CLINE_REALPATH_NOT_FOUND__')) {\n throw new Error(missingMessage ?? `Path not found: ${inputPath}`);\n }\n if (\n result.output.includes('__CLINE_REALPATH_FAILED__') ||\n result.exitCode !== 0\n ) {\n throw new Error(`Unable to resolve path: ${inputPath}`);\n }\n\n const resolvedPath = lastOutputLine(result.output);\n if (!resolvedPath) {\n throw new Error(`Unable to resolve path: ${inputPath}`);\n }\n return resolvedPath;\n };\n\n const resolveReadableSandboxPath = async ({\n remotePath,\n inputPath,\n missingMessage,\n }: {\n remotePath: string;\n inputPath: string;\n missingMessage?: string;\n }): Promise<string> =>\n assertWorkspacePath(\n await resolveExistingSandboxPath({\n remotePath,\n inputPath,\n ...(missingMessage ? { missingMessage } : {}),\n }),\n );\n\n const resolveWritableSandboxPath = async ({\n remotePath,\n inputPath,\n }: {\n remotePath: string;\n inputPath: string;\n }): Promise<string> => {\n const result = await runShell({\n command: [\n `target=${shellQuote(remotePath)}`,\n 'if [ -e \"$target\" ] || [ -L \"$target\" ]; then resolved=$(realpath \"$target\" 2>/dev/null) || { echo \"__CLINE_REALPATH_FAILED__\"; exit 3; }; printf \\'%s\\\\n\\' \"$resolved\"; exit 0; fi',\n 'dir=$(dirname \"$target\")',\n 'base=$(basename \"$target\")',\n 'missing=\"$base\"',\n 'while [ ! -e \"$dir\" ] && [ ! -L \"$dir\" ]; do parent=$(dirname \"$dir\"); if [ \"$parent\" = \"$dir\" ]; then echo \"__CLINE_REALPATH_NOT_FOUND__\"; exit 2; fi; missing=\"$(basename \"$dir\")/$missing\"; dir=\"$parent\"; done',\n 'resolved_dir=$(realpath \"$dir\" 2>/dev/null) || { echo \"__CLINE_REALPATH_FAILED__\"; exit 3; }',\n 'printf \\'%s/%s\\\\n\\' \"$resolved_dir\" \"$missing\"',\n ].join('; '),\n });\n\n if (\n result.output.includes('__CLINE_REALPATH_NOT_FOUND__') ||\n result.output.includes('__CLINE_REALPATH_FAILED__') ||\n result.exitCode !== 0\n ) {\n throw new Error(`Unable to resolve path: ${inputPath}`);\n }\n\n const resolvedPath = lastOutputLine(result.output);\n if (!resolvedPath) {\n throw new Error(`Unable to resolve path: ${inputPath}`);\n }\n return assertWorkspacePath(resolvedPath);\n };\n\n const readFile = async (inputPath: string): Promise<string> => {\n const remotePath = resolvePath(inputPath);\n const resolved = await resolveReadableSandboxPath({\n remotePath,\n inputPath,\n missingMessage: `File not found: ${inputPath}`,\n });\n const content = await sandbox.readTextFile({ path: resolved });\n if (content == null) {\n throw new Error(`File not found: ${inputPath}`);\n }\n return content;\n };\n\n const writeFile = async (\n inputPath: string,\n content: string,\n ): Promise<void> => {\n const remotePath = resolvePath(inputPath);\n const resolved = await resolveWritableSandboxPath({\n remotePath,\n inputPath,\n });\n // `writeTextFile` creates parent directories recursively per the\n // SandboxSession contract, so no explicit mkdir is needed.\n await sandbox.writeTextFile({ path: resolved, content });\n };\n\n const editFile = async (\n inputPath: string,\n oldText: string,\n newText: string,\n ): Promise<void> => {\n const remotePath = resolvePath(inputPath);\n const resolved = assertWorkspacePath(\n await resolveExistingSandboxPath({\n remotePath,\n inputPath,\n missingMessage: `File not found: ${inputPath}`,\n }),\n );\n const current = await sandbox.readTextFile({ path: resolved });\n if (current == null) {\n throw new Error(`File not found: ${inputPath}`);\n }\n const index = current.indexOf(oldText);\n if (index === -1) {\n throw new Error(`Text to replace was not found in ${inputPath}`);\n }\n const updated = `${current.slice(0, index)}${newText}${current.slice(\n index + oldText.length,\n )}`;\n await writeFile(inputPath, updated);\n };\n\n return {\n resolvePath,\n readFile,\n writeFile,\n editFile,\n\n async bash(command, input) {\n const controller = new AbortController();\n // `input.timeout` is expressed in seconds (the `bash` tool contract),\n // so convert to milliseconds for `setTimeout`.\n const timeoutId =\n typeof input?.timeout === 'number' && input.timeout > 0\n ? setTimeout(() => controller.abort(), input.timeout * 1000)\n : undefined;\n\n const forwardedSignal = input?.signal;\n const onAbort = () => controller.abort();\n forwardedSignal?.addEventListener('abort', onAbort, { once: true });\n\n try {\n const result = await runShell({\n command,\n signal: controller.signal,\n });\n return { output: result.output, exitCode: result.exitCode };\n } finally {\n forwardedSignal?.removeEventListener('abort', onAbort);\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n },\n\n async grep(pattern, input = {}) {\n const inputPath = input.path ?? '.';\n const remotePath = resolvePath(inputPath);\n const target = await resolveReadableSandboxPath({\n remotePath,\n inputPath,\n });\n const flags = [\n '-r',\n '-n',\n '--binary-files=without-match',\n ...(input.ignoreCase ? ['-i'] : []),\n ...(input.literal ? ['-F'] : []),\n ...(typeof input.context === 'number' && input.context > 0\n ? ['-C', String(input.context)]\n : []),\n ...(input.glob ? ['--include', input.glob] : []),\n ];\n const limit = Math.max(1, input.limit ?? 100);\n const result = await runShell({\n command: [\n `if [ ! -e ${shellQuote(\n target,\n )} ]; then echo \"__CLINE_GREP_NOT_FOUND__\"; exit 2; fi`,\n `grep ${flags.map(shellQuote).join(' ')} -- ${shellQuote(\n pattern,\n )} ${shellQuote(target)} 2>/dev/null | head -n ${limit}`,\n ].join('; '),\n });\n\n const output = result.output.trim();\n if (output.includes('__CLINE_GREP_NOT_FOUND__')) {\n throw new Error(`Path not found: ${input.path ?? '.'}`);\n }\n return output || 'No matches found';\n },\n\n async glob(pattern, inputPath = '.', limit = 1_000) {\n const remotePath = resolvePath(inputPath);\n const target = await resolveReadableSandboxPath({\n remotePath,\n inputPath,\n });\n const result = await runShell({\n command: [\n `if [ ! -e ${shellQuote(\n target,\n )} ]; then echo \"__CLINE_FIND_NOT_FOUND__\"; exit 2; fi`,\n `if [ -d ${shellQuote(target)} ]; then find ${shellQuote(\n target,\n )} -type f -print; else printf '%s\\\\n' ${shellQuote(target)}; fi`,\n ].join('; '),\n });\n\n const output = result.output.trim();\n if (output.includes('__CLINE_FIND_NOT_FOUND__')) {\n throw new Error(`Path not found: ${inputPath}`);\n }\n\n return output\n .split('\\n')\n .filter(Boolean)\n .map(absolutePath => {\n if (absolutePath === target) {\n return path.posix.basename(absolutePath);\n }\n return path.posix.relative(target, absolutePath);\n })\n .filter(\n candidate =>\n candidate.length > 0 && path.matchesGlob(candidate, pattern),\n )\n .sort((left, right) =>\n left.toLowerCase().localeCompare(right.toLowerCase()),\n )\n .slice(0, limit);\n },\n\n async ls(inputPath = '.', limit = 500) {\n const remotePath = resolvePath(inputPath);\n const target = await resolveReadableSandboxPath({\n remotePath,\n inputPath,\n });\n const result = await runShell({\n command: [\n `if [ ! -e ${shellQuote(\n target,\n )} ]; then echo \"__CLINE_LS_NOT_FOUND__\"; exit 2; fi`,\n `if [ ! -d ${shellQuote(\n target,\n )} ]; then echo \"__CLINE_LS_NOT_DIR__\"; exit 3; fi`,\n `cd ${shellQuote(target)}`,\n 'ls -1Ap',\n ].join('; '),\n });\n\n const output = result.output.trim();\n if (output.includes('__CLINE_LS_NOT_FOUND__')) {\n throw new Error(`Path not found: ${inputPath}`);\n }\n if (output.includes('__CLINE_LS_NOT_DIR__')) {\n throw new Error(`Not a directory: ${inputPath}`);\n }\n\n return output\n .split('\\n')\n .filter(Boolean)\n .map(line => line.replace(/[*=@|]$/, ''))\n .sort((left, right) =>\n left.toLowerCase().localeCompare(right.toLowerCase()),\n )\n .slice(0, limit);\n },\n };\n}\n","import path from 'node:path';\nimport type { HarnessV1Skill } from '@ai-sdk/harness';\nimport type { AgentTool } from '@cline/agents';\nimport { createDefaultTools, type ToolExecutors } from '@cline/core';\n\nconst CLINE_SKILL_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;\n\ntype ProjectedClineSkill = {\n readonly id: string;\n readonly name: string;\n readonly description: string;\n readonly content: string;\n readonly files: ReadonlyArray<{\n readonly path: string;\n readonly content: string;\n }>;\n};\n\nexport type ClineSkillsRuntime = {\n readonly signature: string;\n readonly tool?: AgentTool;\n};\n\n/**\n * Build Cline's native skills tool around an immutable in-host projection of\n * the harness skills. The low-level Agent does not discover skills itself, so\n * the adapter provides the same tool contract that Cline's core orchestration\n * layer uses without involving the sandbox filesystem.\n */\nexport function createClineSkillsRuntime({\n skills,\n}: {\n skills: ReadonlyArray<HarnessV1Skill>;\n}): ClineSkillsRuntime {\n const projectedSkills = projectClineSkills({ skills });\n const signature = JSON.stringify(projectedSkills);\n if (projectedSkills.length === 0) {\n return { signature };\n }\n\n const executor: NonNullable<ToolExecutors['skills']> = async (\n ...executorArguments\n ) => {\n const [requestedSkill, args] = executorArguments;\n const skill = projectedSkills.find(\n candidate => candidate.id === normalizeSkillToken(requestedSkill),\n );\n if (skill == null) {\n const availableSkills = projectedSkills.map(skill => skill.name);\n return availableSkills.length > 0\n ? `Skill \"${requestedSkill}\" not found. Available skills: ${availableSkills.join(', ')}`\n : 'No skills are currently available.';\n }\n return renderSkillInstructions({ skill, args });\n };\n executor.configuredSkills = projectedSkills.map(skill => ({\n id: skill.id,\n name: skill.name,\n description: skill.description,\n disabled: false,\n }));\n\n const tool = createDefaultTools({\n executors: { skills: executor },\n enableReadFiles: false,\n enableSearch: false,\n enableBash: false,\n enableWebFetch: false,\n enableApplyPatch: false,\n enableEditor: false,\n enableSkills: true,\n enableAskQuestion: false,\n enableSubmitAndExit: false,\n }).find(tool => tool.name === 'skills');\n if (tool == null) {\n throw new Error('Cline did not create its native skills tool.');\n }\n\n return { signature, tool };\n}\n\nfunction projectClineSkills({\n skills,\n}: {\n skills: ReadonlyArray<HarnessV1Skill>;\n}): ReadonlyArray<ProjectedClineSkill> {\n const names = new Set<string>();\n const ids = new Set<string>();\n return skills\n .map(skill => {\n if (\n !CLINE_SKILL_NAME_PATTERN.test(skill.name) ||\n skill.name === '.' ||\n skill.name === '..'\n ) {\n throw new Error(`Invalid Cline skill name: ${skill.name}`);\n }\n if (names.has(skill.name)) {\n throw new Error(`Duplicate Cline skill name: ${skill.name}`);\n }\n names.add(skill.name);\n\n const id = normalizeSkillToken(skill.name);\n if (ids.has(id)) {\n throw new Error(`Duplicate Cline skill identifier: ${id}`);\n }\n ids.add(id);\n\n return {\n id,\n name: skill.name,\n description: skill.description,\n content: skill.content,\n files: (skill.files ?? [])\n .map(file => ({\n path: normalizeSkillFilePath({\n skillName: skill.name,\n filePath: file.path,\n }),\n content: file.content,\n }))\n .sort(\n (left, right) =>\n left.path.localeCompare(right.path) ||\n left.content.localeCompare(right.content),\n ),\n };\n })\n .sort((left, right) => left.name.localeCompare(right.name));\n}\n\nfunction normalizeSkillToken(skill: string): string {\n return skill.trim().replace(/^\\/+/, '').toLowerCase();\n}\n\nfunction normalizeSkillFilePath({\n skillName,\n filePath,\n}: {\n skillName: string;\n filePath: string;\n}): string {\n const normalized = path.posix.normalize(filePath);\n if (\n normalized === '' ||\n normalized === '.' ||\n normalized.startsWith('../') ||\n normalized.includes('/../') ||\n normalized.endsWith('/..') ||\n path.posix.isAbsolute(normalized)\n ) {\n throw new Error(\n `Invalid Cline skill file path for ${skillName}: ${filePath}`,\n );\n }\n return normalized;\n}\n\nfunction renderSkillInstructions({\n skill,\n args,\n}: {\n skill: ProjectedClineSkill;\n args: string | undefined;\n}): string {\n const trimmedArgs = args?.trim();\n const argsTag = trimmedArgs\n ? `\\n<command-args>${trimmedArgs}</command-args>`\n : '';\n const description = skill.description.trim()\n ? `Description: ${skill.description.trim()}\\n\\n`\n : '';\n const files =\n skill.files.length === 0\n ? ''\n : `\\n\\n<skill-files>\\n${skill.files\n .map(\n file =>\n `<skill-file path=${JSON.stringify(file.path)}>\\n${file.content}\\n</skill-file>`,\n )\n .join('\\n')}\\n</skill-files>`;\n\n return `<command-name>${skill.name}</command-name>${argsTag}\\n<command-instructions>\\n${description}${skill.content}${files}\\n</command-instructions>`;\n}\n","import type {\n HarnessV1BuiltinToolFiltering,\n HarnessV1QuestionsToolOutput,\n HarnessV1ToolSpec,\n} from '@ai-sdk/harness';\nimport {\n createTool,\n type AgentTool,\n type AgentToolResult,\n} from '@cline/agents';\nimport { createDefaultTools } from '@cline/core';\nimport type { ClineRemoteOps } from './cline-remote-ops';\nimport { getErrorText } from './cline-utils';\n\n/**\n * Native names of the Cline harness's built-in tools. The Cline runtime\n * requires snake_case tool names, and every one of these already matches its\n * cross-harness common name, so the public (wire) names and native names are\n * identical.\n */\nexport const CLINE_NATIVE_BUILTIN_NAMES = [\n 'ask_question',\n 'read',\n 'write',\n 'edit',\n 'bash',\n 'grep',\n 'glob',\n 'ls',\n 'skills',\n] as const;\n\nexport type ClineNativeBuiltinName =\n (typeof CLINE_NATIVE_BUILTIN_NAMES)[number];\n\nexport const CLINE_NATIVE_TOOL_KINDS: Readonly<\n Record<ClineNativeBuiltinName, 'readonly' | 'edit' | 'bash'>\n> = {\n ask_question: 'readonly',\n read: 'readonly',\n write: 'edit',\n edit: 'edit',\n bash: 'bash',\n grep: 'readonly',\n glob: 'readonly',\n ls: 'readonly',\n skills: 'readonly',\n};\n\nexport function isClineBuiltinToolName(\n name: string,\n): name is ClineNativeBuiltinName {\n return (CLINE_NATIVE_BUILTIN_NAMES as readonly string[]).includes(name);\n}\n\n/**\n * Resolve which built-in tools stay active for a session under the framework's\n * `builtinToolFiltering`. Names map 1:1 (native === common), so filtering is a\n * plain include/exclude.\n */\nexport function resolveActiveClineBuiltinNames(\n toolFiltering: HarnessV1BuiltinToolFiltering | undefined,\n): ReadonlyArray<ClineNativeBuiltinName> {\n if (toolFiltering == null) return CLINE_NATIVE_BUILTIN_NAMES;\n const filteredNames = toolFiltering.toolNames.map(name =>\n name === 'askUserQuestions' ? 'ask_question' : name,\n );\n if (toolFiltering.mode === 'allow') {\n return CLINE_NATIVE_BUILTIN_NAMES.filter(name =>\n filteredNames.includes(name),\n );\n }\n return CLINE_NATIVE_BUILTIN_NAMES.filter(\n name => !filteredNames.includes(name),\n );\n}\n\nexport interface PendingToolResult {\n resolve: (value: unknown) => void;\n}\n\nexport interface PendingClineQuestion {\n readonly input: {\n readonly question: string;\n readonly options: readonly string[];\n };\n resolve: (value: string) => void;\n}\n\nexport interface PendingClineQuestionResult {\n readonly output: HarnessV1QuestionsToolOutput;\n}\n\nexport function clineQuestionKey(input: {\n readonly question: string;\n readonly options: readonly string[];\n}): string {\n return JSON.stringify([input.question, input.options]);\n}\n\nconst clineToolResultMarker = Symbol('cline-tool-result');\n\ninterface ClineToolResult {\n readonly [clineToolResultMarker]: true;\n readonly output: unknown;\n readonly isError?: boolean;\n}\n\nexport function createClineToolResult({\n output,\n isError,\n}: {\n output: unknown;\n isError?: boolean;\n}): ClineToolResult {\n return {\n [clineToolResultMarker]: true,\n output,\n ...(isError ? { isError: true } : {}),\n };\n}\n\nexport function unwrapClineToolResult(\n value: unknown,\n): AgentToolResult | undefined {\n if (\n value == null ||\n typeof value !== 'object' ||\n (value as ClineToolResult)[clineToolResultMarker] !== true\n ) {\n return undefined;\n }\n\n const result = value as ClineToolResult;\n return {\n output: result.output,\n ...(result.isError ? { isError: true } : {}),\n };\n}\n\n/*\n * The Cline runtime treats a thrown tool error as a \"mistake\" against the\n * agent's mistake limit, so built-ins catch and return errors as structured\n * data — the model reads the error and adjusts.\n */\nasync function guarded<T>(run: () => Promise<T>): Promise<ClineToolResult> {\n try {\n return createClineToolResult({ output: await run() });\n } catch (error) {\n return createClineToolResult({\n output: { error: getErrorText(error) },\n isError: true,\n });\n }\n}\n\n/**\n * Build the sandbox-backed coding tools handed to the Cline runtime. These\n * schemas mirror their declarations in `CLINE_BUILTIN_TOOLS`\n * (cline-harness.ts). The in-host skills tool is built separately.\n */\nexport function buildBuiltinAgentTools({\n ops,\n activeNames,\n pendingQuestions = new Map(),\n pendingQuestionResults = new Map(),\n}: {\n ops: ClineRemoteOps;\n activeNames: ReadonlyArray<ClineNativeBuiltinName>;\n pendingQuestions?: Map<string, PendingClineQuestion>;\n pendingQuestionResults?: Map<string, PendingClineQuestionResult>;\n}): AgentTool<any, any>[] {\n // biome/eslint: `any` matches the runtime's own `tools?: readonly AgentTool<any, any>[]`.\n const tools: Partial<Record<ClineNativeBuiltinName, AgentTool<any, any>>> = {\n ask_question: createDefaultTools({\n executors: {\n askQuestion: async (question, options, context) => {\n if (context.toolCallId == null) {\n throw new Error(\n 'Cline ask_question did not provide a tool call id.',\n );\n }\n const questionKey = clineQuestionKey({ question, options });\n const pendingResult = pendingQuestionResults.get(questionKey);\n if (pendingResult != null) {\n pendingQuestionResults.delete(questionKey);\n return toClineQuestionResult({\n nativeInput: { question, options },\n output: pendingResult.output,\n });\n }\n return new Promise<string>(resolve => {\n pendingQuestions.set(context.toolCallId!, {\n input: { question, options },\n resolve,\n });\n });\n },\n },\n enableReadFiles: false,\n enableSearch: false,\n enableBash: false,\n enableWebFetch: false,\n enableApplyPatch: false,\n enableEditor: false,\n enableSkills: false,\n enableAskQuestion: true,\n }).find(tool => tool.name === 'ask_question'),\n read: createTool({\n name: 'read',\n description: 'Read file contents.',\n inputSchema: {\n type: 'object',\n properties: {\n file_path: {\n type: 'string',\n description: 'Path of the file to read.',\n },\n },\n required: ['file_path'],\n },\n execute: async (input: { file_path: string }) =>\n guarded(() => ops.readFile(input.file_path)),\n }),\n write: createTool({\n name: 'write',\n description: 'Overwrite or create a file.',\n inputSchema: {\n type: 'object',\n properties: {\n file_path: {\n type: 'string',\n description: 'Path of the file to write.',\n },\n content: {\n type: 'string',\n description: 'Full file content to write.',\n },\n },\n required: ['file_path', 'content'],\n },\n execute: async (input: { file_path: string; content: string }) =>\n guarded(async () => {\n await ops.writeFile(input.file_path, input.content);\n return `Wrote ${input.file_path}`;\n }),\n }),\n edit: createTool({\n name: 'edit',\n description: 'Edit a file by exact string replacement.',\n inputSchema: {\n type: 'object',\n properties: {\n file_path: {\n type: 'string',\n description: 'Path of the file to edit.',\n },\n old_string: { type: 'string', description: 'Exact text to replace.' },\n new_string: { type: 'string', description: 'Replacement text.' },\n },\n required: ['file_path', 'old_string', 'new_string'],\n },\n execute: async (input: {\n file_path: string;\n old_string: string;\n new_string: string;\n }) =>\n guarded(async () => {\n await ops.editFile(\n input.file_path,\n input.old_string,\n input.new_string,\n );\n return `Edited ${input.file_path}`;\n }),\n }),\n bash: createTool({\n name: 'bash',\n description:\n 'Execute a shell command in the sandbox workspace. Returns combined stdout/stderr and the exit code.',\n inputSchema: {\n type: 'object',\n properties: {\n command: { type: 'string', description: 'Shell command to execute.' },\n timeout: {\n type: 'number',\n description: 'Optional timeout in seconds.',\n },\n },\n required: ['command'],\n },\n execute: async (input: { command: string; timeout?: number }, context) =>\n guarded(async () => {\n const result = await ops.bash(input.command, {\n ...(typeof input.timeout === 'number'\n ? { timeout: input.timeout }\n : {}),\n ...(context.signal ? { signal: context.signal } : {}),\n });\n return `${result.output}${\n result.exitCode != null ? `\\n\\n(exit ${result.exitCode})` : ''\n }`.trim();\n }),\n }),\n grep: createTool({\n name: 'grep',\n description: 'Search file contents with regex.',\n inputSchema: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Regex pattern to search for.',\n },\n path: { type: 'string', description: 'File or directory to search.' },\n glob: { type: 'string', description: 'Glob filter for file names.' },\n ignoreCase: { type: 'boolean' },\n literal: {\n type: 'boolean',\n description: 'Treat pattern as a literal string.',\n },\n context: {\n type: 'number',\n description: 'Lines of context around matches.',\n },\n limit: {\n type: 'number',\n description: 'Maximum matching lines to return.',\n },\n },\n required: ['pattern'],\n },\n execute: async (input: {\n pattern: string;\n path?: string;\n glob?: string;\n ignoreCase?: boolean;\n literal?: boolean;\n context?: number;\n limit?: number;\n }) => guarded(() => ops.grep(input.pattern, input)),\n }),\n glob: createTool({\n name: 'glob',\n description: 'Find files matching a glob pattern.',\n inputSchema: {\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'Glob pattern to match.' },\n path: { type: 'string', description: 'Directory to search from.' },\n limit: { type: 'number', description: 'Maximum paths to return.' },\n },\n required: ['pattern'],\n },\n execute: async (input: {\n pattern: string;\n path?: string;\n limit?: number;\n }) =>\n guarded(async () => {\n const matches = await ops.glob(\n input.pattern,\n input.path ?? '.',\n input.limit ?? 1_000,\n );\n return matches.length > 0 ? matches.join('\\n') : 'No files found';\n }),\n }),\n ls: createTool({\n name: 'ls',\n description: 'List directory entries.',\n inputSchema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Directory to list.' },\n limit: { type: 'number', description: 'Maximum entries to return.' },\n },\n },\n execute: async (input: { path?: string; limit?: number }) =>\n guarded(async () => {\n const entries = await ops.ls(input.path ?? '.', input.limit ?? 500);\n return entries.join('\\n');\n }),\n }),\n };\n\n return activeNames\n .map(name => tools[name])\n .filter((tool): tool is AgentTool<any, any> => tool != null);\n}\n\nexport function toClineQuestionResult(input: {\n nativeInput: PendingClineQuestion['input'];\n output: HarnessV1QuestionsToolOutput;\n}): string {\n if (\n input.output.action === 'declined' ||\n input.output.action === 'cancelled'\n ) {\n return `The user ${input.output.action} the question.`;\n }\n const answer = input.output.answers['question-1'];\n if (answer == null) return 'The user did not answer the question.';\n if (answer.freeform != null) return answer.freeform;\n const result = answer.optionIds\n .map(id => {\n const index = Number(id.replace(/^option-/, '')) - 1;\n return input.nativeInput.options[index];\n })\n .filter((value): value is string => value != null)\n .join(', ');\n return result;\n}\n\n/**\n * Build host-executed user tools. When the model calls one, the tool parks a\n * promise keyed by the runtime's `toolCallId`; the harness caller supplies the\n * output via `submitToolResult`, which resolves the promise and lets the loop\n * continue. The adapter never executes these itself.\n */\nexport function buildUserAgentTools({\n specs,\n pendingToolResults,\n}: {\n specs: ReadonlyArray<HarnessV1ToolSpec>;\n pendingToolResults: Map<string, PendingToolResult>;\n}): AgentTool<any, any>[] {\n return specs.map(spec =>\n createTool({\n name: spec.name,\n description: spec.description ?? `User-registered tool ${spec.name}`,\n inputSchema: (spec.inputSchema as Record<string, unknown>) ?? {\n type: 'object',\n properties: {},\n additionalProperties: true,\n },\n execute: async (_input: unknown, context) => {\n const toolCallId = context.toolCallId;\n if (!toolCallId) {\n return createClineToolResult({\n output: { error: 'Tool call is missing a toolCallId.' },\n isError: true,\n });\n }\n return new Promise<unknown>(resolve => {\n pendingToolResults.set(toolCallId, { resolve });\n // If the turn is aborted while waiting for the host, settle so the\n // runtime's tool execution does not dangle forever.\n context.signal?.addEventListener(\n 'abort',\n () => {\n if (pendingToolResults.delete(toolCallId)) {\n resolve(\n createClineToolResult({\n output: {\n error:\n 'Turn was aborted before a tool result was submitted.',\n },\n isError: true,\n }),\n );\n }\n },\n { once: true },\n );\n });\n },\n }),\n );\n}\n","import type {\n JSONValue,\n LanguageModelV4FinishReason,\n LanguageModelV4Usage,\n} from '@ai-sdk/provider';\nimport {\n HarnessCapabilityUnsupportedError,\n type HarnessV1Prompt,\n} from '@ai-sdk/harness';\nimport { secureJsonParse } from '@ai-sdk/provider-utils';\nimport type { AgentMessage, AgentUsage } from '@cline/agents';\n\nconst HARNESS_ID = 'cline';\n\n/**\n * Extract a single user text string from a `HarnessV1Prompt`. The Cline\n * runtime's `run`/`continue` accept a plain string; multimodal user content\n * is not supported in this foundational version.\n */\nexport function extractUserText(prompt: HarnessV1Prompt): string {\n if (typeof prompt === 'string') {\n return prompt;\n }\n\n const { content } = prompt;\n if (typeof content === 'string') {\n return content;\n }\n\n const parts: string[] = [];\n for (const part of content) {\n if (part.type !== 'text') {\n throw new HarnessCapabilityUnsupportedError({\n message: `cline: only text user-message parts are supported; got '${part.type}'.`,\n harnessId: HARNESS_ID,\n });\n }\n parts.push(part.text);\n }\n return parts.join('\\n\\n');\n}\n\nexport function getErrorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Coerce an arbitrary tool output into a JSON-safe value for a `tool-result`\n * stream part. Strings and JSON-serializable objects pass through; anything\n * that can't survive `JSON.stringify` round-tripping (functions, cycles) is\n * stringified. `undefined` becomes `null` — the runtime schema deliberately\n * accepts `null` for tools with no output.\n */\nexport function toToolResultValue(output: unknown): NonNullable<JSONValue> {\n if (output === undefined || output === null) {\n return null as unknown as NonNullable<JSONValue>;\n }\n if (typeof output === 'string') {\n return output;\n }\n try {\n const serialized = JSON.stringify(output);\n return serialized === undefined\n ? String(output)\n : (secureJsonParse(serialized) as NonNullable<JSONValue>);\n } catch {\n return String(output);\n }\n}\n\n/**\n * Map the Cline model-level finish reason (`AgentModelFinishReason`) onto the\n * V4 unified finish-reason vocabulary. Used for `finish-step` parts.\n */\nexport function mapModelFinishReason(\n reason: string,\n): LanguageModelV4FinishReason {\n switch (reason) {\n case 'stop':\n return { unified: 'stop', raw: reason };\n case 'tool-calls':\n return { unified: 'tool-calls', raw: reason };\n case 'max-tokens':\n return { unified: 'length', raw: reason };\n case 'error':\n return { unified: 'error', raw: reason };\n default:\n return { unified: 'other', raw: reason };\n }\n}\n\n/**\n * Map a completed run's status onto the V4 unified finish reason. Used for\n * the terminal `finish` part.\n */\nexport function mapRunFinishReason(\n status: 'completed' | 'aborted' | 'failed',\n): LanguageModelV4FinishReason {\n switch (status) {\n case 'completed':\n return { unified: 'stop', raw: status };\n case 'aborted':\n return { unified: 'other', raw: status };\n case 'failed':\n return { unified: 'error', raw: status };\n }\n}\n\n/**\n * Convert the Cline runtime's cumulative `AgentUsage` into the V4 usage shape.\n */\nexport function usageFromAgentUsage(usage: AgentUsage): LanguageModelV4Usage {\n return {\n inputTokens: {\n total: usage.inputTokens,\n noCache: undefined,\n cacheRead: usage.cacheReadTokens,\n cacheWrite: usage.cacheWriteTokens,\n },\n outputTokens: {\n total: usage.outputTokens,\n text: undefined,\n reasoning: usage.reasoningTokenCount,\n },\n ...(usage.totalCost !== undefined\n ? { raw: { totalCost: usage.totalCost } }\n : {}),\n };\n}\n\n/**\n * Convert a single assistant message's per-call metrics into the V4 usage\n * shape. Metrics may be absent; all fields stay optional in that case.\n */\nexport function usageFromMessageMetrics(\n metrics: AgentMessage['metrics'],\n): LanguageModelV4Usage {\n return {\n inputTokens: {\n total: metrics?.inputTokens,\n noCache: undefined,\n cacheRead: metrics?.cacheReadTokens,\n cacheWrite: metrics?.cacheWriteTokens,\n },\n outputTokens: {\n total: metrics?.outputTokens,\n text: undefined,\n reasoning: metrics?.reasoningTokenCount,\n },\n };\n}\n","import type { HarnessV1StreamPart } from '@ai-sdk/harness';\nimport type { AgentRuntimeEvent, AgentToolResult } from '@cline/agents';\nimport {\n mapModelFinishReason,\n toToolResultValue,\n usageFromMessageMetrics,\n} from './cline-utils';\n\ntype FinishStepPart = Extract<\n HarnessV1StreamPart,\n { readonly type: 'finish-step' }\n>;\n\n/**\n * Per-turn translator state. Tracks open text/reasoning blocks (the Cline\n * runtime streams flat deltas; the harness contract wants explicit\n * start/delta/end block framing) and which tool calls have already been\n * surfaced — an approval request can emit a `tool-call` part before the\n * runtime's own `tool-started` event fires for it. Cline emits the assistant\n * message before executing that iteration's tools, so the step boundary is\n * buffered until `turn-finished` confirms that those tools have settled.\n */\nexport interface ClineTranslatorState {\n readonly builtinToolNames: ReadonlySet<string>;\n readonly dynamicToolCallIds: Set<string>;\n readonly hostToolNames: ReadonlySet<string>;\n readonly ignoredToolNames: ReadonlySet<string>;\n readonly mcpToolNames: ReadonlySet<string>;\n openTextBlockId?: string;\n openReasoningBlockId?: string;\n emittedToolCalls: Set<string>;\n pendingFinishStep?: FinishStepPart;\n blockCounter: number;\n}\n\nexport function createClineTranslatorState({\n builtinToolNames,\n hostToolNames = [],\n ignoredToolNames = [],\n mcpToolNames = [],\n}: {\n builtinToolNames: Iterable<string>;\n hostToolNames?: Iterable<string>;\n ignoredToolNames?: Iterable<string>;\n mcpToolNames?: Iterable<string>;\n}): ClineTranslatorState {\n return {\n builtinToolNames: new Set(builtinToolNames),\n dynamicToolCallIds: new Set(),\n hostToolNames: new Set(hostToolNames),\n ignoredToolNames: new Set(ignoredToolNames),\n mcpToolNames: new Set(mcpToolNames),\n emittedToolCalls: new Set(),\n blockCounter: 0,\n };\n}\n\nfunction closeOpenBlocks(state: ClineTranslatorState): HarnessV1StreamPart[] {\n const parts: HarnessV1StreamPart[] = [];\n if (state.openReasoningBlockId) {\n parts.push({ type: 'reasoning-end', id: state.openReasoningBlockId });\n state.openReasoningBlockId = undefined;\n }\n if (state.openTextBlockId) {\n parts.push({ type: 'text-end', id: state.openTextBlockId });\n state.openTextBlockId = undefined;\n }\n return parts;\n}\n\nfunction toolCallPart(\n state: ClineTranslatorState,\n toolCall: { toolCallId: string; toolName: string; input: unknown },\n): HarnessV1StreamPart {\n const isMcpTool =\n state.mcpToolNames.has(toolCall.toolName) &&\n !state.hostToolNames.has(toolCall.toolName);\n if (isMcpTool) {\n state.dynamicToolCallIds.add(toolCall.toolCallId);\n }\n if (toolCall.toolName === 'ask_question') {\n const nativeInput = toolCall.input as {\n question: string;\n options: string[];\n };\n return {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName: 'askUserQuestions',\n input: JSON.stringify({\n allowPartialAnswers: false,\n questions: [\n {\n id: 'question-1',\n question: nativeInput.question,\n options: nativeInput.options.map((label, index) => ({\n id: `option-${index + 1}`,\n label,\n })),\n allowFreeForm: true,\n },\n ],\n }),\n providerExecuted: false,\n providerMetadata: {\n cline: {\n nativeRequest: nativeInput,\n },\n },\n nativeName: 'ask_question',\n };\n }\n return {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: JSON.stringify(toolCall.input ?? {}),\n /*\n * Built-ins and external MCP tools are executed by the Cline runtime.\n * Typed host tools wait for dispatch through `submitToolResult`, including\n * when a host tool has the same name as a configured MCP tool.\n */\n ...(state.builtinToolNames.has(toolCall.toolName) || isMcpTool\n ? { providerExecuted: true }\n : {}),\n ...(isMcpTool ? { dynamic: true } : {}),\n };\n}\n\n/**\n * Emit the `tool-call` + `tool-approval-request` pair for a built-in tool\n * that requires approval. The Cline runtime asks for approval *before* its\n * `tool-started` event fires, so the `tool-call` part is emitted here and\n * deduplicated when `tool-started` arrives.\n */\nexport function toolApprovalParts(\n state: ClineTranslatorState,\n toolCall: { toolCallId: string; toolName: string; input: unknown },\n): HarnessV1StreamPart[] {\n const parts: HarnessV1StreamPart[] = [];\n if (!state.emittedToolCalls.has(toolCall.toolCallId)) {\n state.emittedToolCalls.add(toolCall.toolCallId);\n parts.push(toolCallPart(state, toolCall));\n }\n parts.push({\n type: 'tool-approval-request',\n approvalId: toolCall.toolCallId,\n toolCallId: toolCall.toolCallId,\n });\n return parts;\n}\n\n/**\n * Translate one Cline runtime event into zero or more harness stream parts.\n * Terminal events (`run-finished`, `run-failed`) are intentionally not\n * translated here — the session driver emits `finish`/`error` after the\n * runtime's promise settles, so a suspend can close the stream cleanly.\n */\nexport function translateClineEvent(\n event: AgentRuntimeEvent,\n state: ClineTranslatorState,\n): HarnessV1StreamPart[] {\n switch (event.type) {\n case 'assistant-reasoning-delta': {\n const parts: HarnessV1StreamPart[] = [];\n if (state.openTextBlockId) {\n parts.push({ type: 'text-end', id: state.openTextBlockId });\n state.openTextBlockId = undefined;\n }\n if (!state.openReasoningBlockId) {\n state.openReasoningBlockId = `reasoning-${++state.blockCounter}`;\n parts.push({ type: 'reasoning-start', id: state.openReasoningBlockId });\n }\n parts.push({\n type: 'reasoning-delta',\n id: state.openReasoningBlockId,\n delta: event.text,\n });\n return parts;\n }\n\n case 'assistant-text-delta': {\n const parts: HarnessV1StreamPart[] = [];\n if (state.openReasoningBlockId) {\n parts.push({ type: 'reasoning-end', id: state.openReasoningBlockId });\n state.openReasoningBlockId = undefined;\n }\n if (!state.openTextBlockId) {\n state.openTextBlockId = `text-${++state.blockCounter}`;\n parts.push({ type: 'text-start', id: state.openTextBlockId });\n }\n parts.push({\n type: 'text-delta',\n id: state.openTextBlockId,\n delta: event.text,\n });\n return parts;\n }\n\n case 'assistant-message': {\n const parts = closeOpenBlocks(state);\n state.pendingFinishStep = {\n type: 'finish-step',\n finishReason: mapModelFinishReason(event.finishReason),\n usage: usageFromMessageMetrics(event.message.metrics),\n };\n return parts;\n }\n\n case 'turn-finished': {\n const pendingFinishStep = state.pendingFinishStep;\n if (!pendingFinishStep) {\n return [];\n }\n state.pendingFinishStep = undefined;\n return [pendingFinishStep];\n }\n\n case 'tool-started': {\n if (state.ignoredToolNames.has(event.toolCall.toolName)) return [];\n if (state.emittedToolCalls.has(event.toolCall.toolCallId)) {\n return [];\n }\n state.emittedToolCalls.add(event.toolCall.toolCallId);\n return [toolCallPart(state, event.toolCall)];\n }\n\n case 'tool-finished': {\n if (state.ignoredToolNames.has(event.toolCall.toolName)) return [];\n // The tool message carries the runtime's recorded result for this call.\n const resultPart = event.message.content.find(\n (part): part is Extract<typeof part, { type: 'tool-result' }> =>\n part.type === 'tool-result' &&\n part.toolCallId === event.toolCall.toolCallId,\n );\n const output = resultPart?.output as AgentToolResult['output'] | unknown;\n const dynamic = state.dynamicToolCallIds.delete(\n event.toolCall.toolCallId,\n );\n return [\n {\n type: 'tool-result',\n toolCallId: event.toolCall.toolCallId,\n toolName:\n event.toolCall.toolName === 'ask_question'\n ? 'askUserQuestions'\n : event.toolCall.toolName,\n result: toToolResultValue(output),\n ...(resultPart?.isError ? { isError: true } : {}),\n ...(dynamic ? { dynamic: true } : {}),\n },\n ];\n }\n\n case 'tool-updated':\n return [\n {\n type: 'raw',\n rawValue: {\n type: 'tool-updated',\n toolCallId: event.toolCall.toolCallId,\n toolName: event.toolCall.toolName,\n update: event.update,\n },\n },\n ];\n\n case 'status-notice':\n return [\n {\n type: 'raw',\n rawValue: {\n type: 'status-notice',\n message: event.message,\n ...(event.metadata ? { metadata: event.metadata } : {}),\n },\n },\n ];\n\n default:\n return [];\n }\n}\n\n/**\n * Close any blocks still open when the turn ends (e.g. an aborted turn whose\n * `assistant-message` never arrived). A buffered step that never reached\n * Cline's `turn-finished` boundary is incomplete and must not be emitted.\n */\nexport function finishClineTranslation(\n state: ClineTranslatorState,\n): HarnessV1StreamPart[] {\n const parts = closeOpenBlocks(state);\n state.pendingFinishStep = undefined;\n return parts;\n}\n","// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import { createCline } from './cline-harness';\n\n/**\n * Default `cline` harness instance with no overrides — suitable for the\n * common case where the Cline SDK's defaults are fine. Equivalent to\n * `createCline()`.\n */\nexport const cline = createCline();\n\nexport { createCline } from './cline-harness';\nexport { VERSION } from './version';\nexport type { ClineHarnessSettings } from './cline-harness';\nexport type { ClineAuthenticationMode } from './cline-auth';\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP,SAAS,sCAAAA,2CAA0C;AACnD,SAAS,YAAY;AACrB,SAAS,KAAAC,UAAS;;;ACRlB,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AAC9B;AAAA,EACE,sCAAAC;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACTP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAIA,SAAS,gBAAgB;AAAA,EAC9B,OAAO;AAAA,EACP,MAAM,QAAQ;AAChB,GAG2B;AACzB,MAAI,mCAAmC,IAAI,GAAG;AAC5C,UAAMC,eAAc,wBAAwB,EAAE,KAAK,KAAK,CAAC;AACzD,WAAOA,aAAY,SACf,kBAAkBA,YAAW,IAC7B,mBAAmB,EAAE,KAAK,KAAK,CAAC;AAAA,EACtC;AACA,MAAI,SAAS,UAAU;AACrB,WAAO,mBAAmB,EAAE,IAAI,CAAC;AAAA,EACnC;AAEA,QAAM,cAAc,wBAAwB,EAAE,IAAI,CAAC;AACnD,MAAI,SAAS,gBAAgB,YAAY,QAAQ;AAC/C,WAAO,kBAAkB,WAAW;AAAA,EACtC;AAEA,SAAO,mBAAmB,EAAE,IAAI,CAAC;AACnC;AAEA,SAAS,kBACP,aACwB;AACxB,SAAO;AAAA,IACL,GAAI,YAAY,SAAS,EAAE,oBAAoB,YAAY,OAAO,IAAI,CAAC;AAAA,IACvE,qBAAqB,YAAY;AAAA,EACnC;AACF;AAE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AmC,SAAS,IAAI;AAAA,UAClD,GAAI,SAAS,aAAa,EAAE,YAAY,SAAS,WAAW,IAAI,CAAC;AAAA,UACjE,GAAI,SAAS,aAAa,EAAE,YAAY,SAAS,WAAW,IAAI,CAAC;AAAA,UACjE,GAAK,SAAS,UAAU,eAAe,qBACnC,EAAE,QAAQ,SAAS,UAAU,eAAe,mBAAmB,IAC/D,CAAC;AAAA,UACL,GAAI,SAAS,UAAU,EAAE,SAAS,SAAS,QAAQ,IAAI,CAAC;AAAA,UACxD,GAAI,SAAS,UAAU,EAAE,SAAS,SAAS,QAAQ,IAAI,CAAC;AAAA,UACxD,GAAI,UAAU,UAAU,EAAE,cAAc,UAAU,QAAQ,IAAI,CAAC;AAAA,UAC/D,GAAI,SAAS,oBAAoB,SAC7B,EAAE,iBAAiB,SAAS,gBAAgB,IAC5C,CAAC;AAAA,UACL,GAAI,SAAS,kBAAkB,SAC3B,EAAE,eAAe,SAAS,cAAc,IACxC,CAAC;AAAA,QACP;AAAA,QACA,WAAW;AAAA,QACX,UAAU,kBAAkB;AAAA,QAC5B,GAAI,UAAU,iBACV,EAAE,gBAAgB,UAAU,eAAe,IAC3C,CAAC;AAAA,QACL,GAAI,UAAU,uBACV,EAAE,sBAAsB,UAAU,qBAAqB,IACvD,CAAC;AAAA,QACL,GAAI,YAAY,kBACZ,EAAE,uBAAuB,WAAW,gBAAgB,IACpD,CAAC;AAAA,QACL,GAAI,UAAU,cACV,EAAE,aAAa,UAAU,YAAY,IACrC,CAAC;AAAA,MACP,CAAC;AAAA,IACH;AAAA,EACF;AACF;;;AYpNO,IAAM,QAAQ,YAAY;","names":["isHarnessAuthenticationEnvironment","z","isHarnessAuthenticationEnvironment","gatewayAuth","isHarnessAuthenticationEnvironment","HarnessCapabilityUnsupportedError","createTool","Llms","tool","path","path","skill","tool","createDefaultTools","createDefaultTools","resolve","tool","HARNESS_ID","Llms","resolve","createTool","HarnessCapabilityUnsupportedError","tool","z","isHarnessAuthenticationEnvironment"]}
1
+ {"version":3,"file":"index.js","names":["HARNESS_ID"],"sources":["../src/cline-auth.ts","../src/cline-subscription.ts","../src/cline-resume-state.ts","../src/cline-mcp.ts","../src/cline-remote-ops.ts","../src/cline-skills.ts","../src/cline-utils.ts","../src/cline-tools.ts","../src/cline-translate.ts","../src/cline-session.ts","../src/version.ts","../src/cline-harness.ts","../src/index.ts"],"sourcesContent":["import type { HarnessV1Authentication } from '@ai-sdk/harness';\nimport {\n getAiGatewayAuthFromEnv,\n isHarnessAuthenticationEnvironment,\n} from '@ai-sdk/harness/utils';\n\nexport type ClineAuthenticationMode = HarnessV1Authentication;\n\nexport function resolveClineEnv({\n auth = 'auto',\n env = process.env,\n}: {\n auth?: ClineAuthenticationMode;\n env?: Record<string, string | undefined>;\n}): Record<string, string> {\n if (isHarnessAuthenticationEnvironment(auth)) {\n const gatewayAuth = getAiGatewayAuthFromEnv({ env: auth });\n return gatewayAuth.apiKey\n ? toGatewayClineEnv(gatewayAuth)\n : pickDirectClineEnv({ env: auth });\n }\n if (auth === 'direct') {\n return pickDirectClineEnv({ env });\n }\n\n const gatewayAuth = getAiGatewayAuthFromEnv({ env });\n if (auth === 'ai-gateway' || gatewayAuth.apiKey) {\n return toGatewayClineEnv(gatewayAuth);\n }\n\n return pickDirectClineEnv({ env });\n}\n\nfunction toGatewayClineEnv(\n gatewayAuth: ReturnType<typeof getAiGatewayAuthFromEnv>,\n): Record<string, string> {\n return {\n ...(gatewayAuth.apiKey ? { AI_GATEWAY_API_KEY: gatewayAuth.apiKey } : {}),\n AI_GATEWAY_BASE_URL: gatewayAuth.baseUrl,\n };\n}\n\nfunction pickDirectClineEnv({\n env,\n}: {\n env: Record<string, string | undefined>;\n}): Record<string, string> {\n return {\n ...(env.CLINE_API_KEY ? { CLINE_API_KEY: env.CLINE_API_KEY } : {}),\n ...(env.CLINE_API_BASE_URL\n ? { CLINE_API_BASE_URL: env.CLINE_API_BASE_URL }\n : {}),\n };\n}\n","import { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport {\n isHarnessAuthenticationEnvironment,\n shouldResolveNativeSubscription,\n} from '@ai-sdk/harness/utils';\nimport {\n Llms,\n ProviderSettingsManager,\n RuntimeOAuthTokenManager,\n} from '@cline/core';\nimport { resolveClineEnv, type ClineAuthenticationMode } from './cline-auth';\n\nexport type ClineResolvedAuthentication = {\n readonly environment: Record<string, string>;\n readonly subscriptionApiKey?: string;\n};\n\nexport async function resolveClineAuthentication({\n auth,\n env = process.env,\n providerId = 'cline',\n apiKey,\n readSubscription = readClineSubscription,\n}: {\n auth?: ClineAuthenticationMode;\n env?: Record<string, string | undefined>;\n providerId?: string;\n apiKey?: string;\n readSubscription?: (options: {\n providerId: string;\n env: Record<string, string | undefined>;\n }) => Promise<string | undefined>;\n}): Promise<ClineResolvedAuthentication> {\n const environment = resolveClineEnv({ auth, env });\n if (isHarnessAuthenticationEnvironment(auth)) {\n return { environment };\n }\n if (\n !shouldResolveNativeSubscription({\n auth,\n env: environment,\n hasDirectCredential:\n apiKey != null || hasApplicableProviderApiKey({ providerId, env }),\n })\n ) {\n return { environment };\n }\n\n const subscriptionApiKey = await readSubscription({ providerId, env });\n return subscriptionApiKey == null\n ? { environment }\n : { environment, subscriptionApiKey };\n}\n\nexport async function readClineSubscription({\n providerId,\n env = process.env,\n homeDirectory = homedir(),\n}: {\n providerId: string;\n env?: Record<string, string | undefined>;\n homeDirectory?: string;\n}): Promise<string | undefined> {\n const filePath = resolveClineProviderSettingsPath({\n env,\n homeDirectory,\n });\n const manager = new ProviderSettingsManager({ filePath });\n const entry = manager.read().providers[providerId];\n if (entry?.tokenSource !== 'oauth') return undefined;\n const resolution = await new RuntimeOAuthTokenManager({\n providerSettingsManager: manager,\n }).resolveProviderApiKey({ providerId });\n return resolution?.apiKey;\n}\n\nexport function resolveClineProviderSettingsPath({\n env,\n homeDirectory,\n}: {\n env: Record<string, string | undefined>;\n homeDirectory: string;\n}): string {\n const explicitPath = env.CLINE_PROVIDER_SETTINGS_PATH?.trim();\n if (explicitPath) return resolve(explicitPath);\n const dataDirectory = env.CLINE_DATA_DIR?.trim();\n return join(\n dataDirectory\n ? resolve(dataDirectory)\n : join(homeDirectory, '.cline', 'data'),\n 'settings',\n 'providers.json',\n );\n}\n\nfunction hasApplicableProviderApiKey({\n providerId,\n env,\n}: {\n providerId: string;\n env: Record<string, string | undefined>;\n}): boolean {\n if (providerId === 'cline' && env.CLINE_API_KEY != null) return true;\n return (\n Llms.getProviderCollectionSync(providerId)?.provider.env?.some(\n name => env[name] != null,\n ) ?? false\n );\n}\n","import { createHash } from 'node:crypto';\nimport path from 'node:path';\nimport {\n safeParseJSON,\n type Experimental_SandboxSession,\n} from '@ai-sdk/provider-utils';\nimport type { AgentMessage } from '@cline/agents';\nimport { z } from 'zod/v4';\n\nconst CLINE_HISTORY_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*\\.json$/;\n\nexport function safeClineHistoryFileName(historyFileName: string): string {\n if (!CLINE_HISTORY_FILE_NAME_PATTERN.test(historyFileName)) {\n throw new Error(`Invalid Cline history file name: ${historyFileName}`);\n }\n return historyFileName;\n}\n\nconst clineHistoryFileNameSchema = z\n .string()\n .refine(\n historyFileName => CLINE_HISTORY_FILE_NAME_PATTERN.test(historyFileName),\n 'Cline historyFileName must be a safe .json basename.',\n );\n\n/**\n * Schema for the adapter-specific portion of lifecycle state `data` produced\n * by the Cline harness's resumable lifecycle methods. Carries the basename of\n * the serialized conversation history. The actual history bytes live in a\n * private, session-scoped directory under sandbox HOME so they survive\n * cross-process resume without appearing in the agent workspace.\n */\nexport const clineResumeStateSchema = z.looseObject({\n historyFileName: clineHistoryFileNameSchema.optional(),\n});\n\nexport type ClineResumeStateData = z.infer<typeof clineResumeStateSchema>;\n\nexport const CLINE_DEFAULT_HISTORY_FILE_NAME = 'history.json';\n\nexport function resolveClinePrivateSessionDirectory(input: {\n readonly sandboxHomeDir: string;\n readonly sessionWorkDir: string;\n readonly sessionId: string;\n}): string {\n const sessionKey = createHash('sha256').update(input.sessionId).digest('hex');\n const privateSessionDir = path.posix.join(\n input.sandboxHomeDir,\n '.ai-sdk',\n 'harness-cline',\n sessionKey,\n );\n const relativePath = path.posix.relative(\n input.sessionWorkDir,\n privateSessionDir,\n );\n if (\n relativePath === '' ||\n (!relativePath.startsWith('../') && !path.posix.isAbsolute(relativePath))\n ) {\n throw new Error(\n `Cline private session directory ${JSON.stringify(privateSessionDir)} must be outside sessionWorkDir ${JSON.stringify(input.sessionWorkDir)}.`,\n );\n }\n return privateSessionDir;\n}\n\nfunction resolveContainedSandboxPath(input: {\n readonly privateSessionDir: string;\n readonly historyFileName: string;\n}): string {\n const historyDir = path.posix.resolve(input.privateSessionDir);\n const filePath = path.posix.resolve(\n historyDir,\n safeClineHistoryFileName(input.historyFileName),\n );\n const relativePath = path.posix.relative(historyDir, filePath);\n if (\n relativePath === '' ||\n relativePath.startsWith('..') ||\n path.posix.isAbsolute(relativePath)\n ) {\n throw new Error(\n `Invalid Cline history file name: ${input.historyFileName}`,\n );\n }\n return filePath;\n}\n\n/**\n * Persist the runtime's conversation history into private sandbox state so a\n * future process can resume the session after\n * `HarnessV1SandboxProvider.resume?.({ sessionId })` reattaches the sandbox.\n */\nexport async function persistHistoryToSandbox(args: {\n readonly sandbox: Experimental_SandboxSession;\n readonly privateSessionDir: string;\n readonly historyFileName: string;\n readonly messages: readonly AgentMessage[];\n readonly abortSignal?: AbortSignal;\n}): Promise<void> {\n const remotePath = resolveContainedSandboxPath({\n privateSessionDir: args.privateSessionDir,\n historyFileName: args.historyFileName,\n });\n // `writeTextFile` creates parent directories recursively per the\n // SandboxSession contract.\n await args.sandbox.writeTextFile({\n path: remotePath,\n content: JSON.stringify(args.messages),\n ...(args.abortSignal ? { abortSignal: args.abortSignal } : {}),\n });\n}\n\n/**\n * Pull a previously persisted conversation history from the sandbox. Returns\n * `undefined` when the file is missing or unparsable — resume then falls back\n * to a fresh conversation rather than failing `doStart`.\n */\nexport async function pullHistoryFromSandbox(args: {\n readonly sandbox: Experimental_SandboxSession;\n readonly privateSessionDir: string;\n readonly historyFileName: string;\n readonly abortSignal?: AbortSignal;\n}): Promise<AgentMessage[] | undefined> {\n const remotePath = resolveContainedSandboxPath({\n privateSessionDir: args.privateSessionDir,\n historyFileName: args.historyFileName,\n });\n const content = await args.sandbox.readTextFile({\n path: remotePath,\n ...(args.abortSignal ? { abortSignal: args.abortSignal } : {}),\n });\n if (content == null) return undefined;\n const parsed = await safeParseJSON({ text: content });\n return parsed.success && Array.isArray(parsed.value)\n ? (parsed.value as unknown as AgentMessage[])\n : undefined;\n}\n","import type { AgentTool } from '@cline/agents';\nimport type {\n CreateMcpToolsOptions,\n McpManager,\n McpManagerOptions,\n McpServerClientFactory,\n McpServerRegistration,\n McpServerTransportConfig,\n} from '@cline/core';\n\nconst CLINE_CORE_PACKAGE: string = '@cline/core';\n\ntype ClineCoreMcpModule = {\n createDefaultMcpServerClientFactory(): McpServerClientFactory;\n createMcpTools(options: CreateMcpToolsOptions): Promise<AgentTool[]>;\n InMemoryMcpManager: new (options: McpManagerOptions) => McpManager;\n};\n\nexport interface ClineMcpRuntime {\n readonly tools: ReadonlyArray<AgentTool>;\n readonly toolNames: ReadonlySet<string>;\n dispose(): Promise<void>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value != null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction optionalStringArray(value: unknown): string[] | undefined {\n return Array.isArray(value) && value.every(item => typeof item === 'string')\n ? value\n : undefined;\n}\n\nfunction optionalStringRecord(\n value: unknown,\n): Record<string, string> | undefined {\n return isRecord(value) &&\n Object.values(value).every(item => typeof item === 'string')\n ? (value as Record<string, string>)\n : undefined;\n}\n\nfunction resolveTransport(input: {\n serverName: string;\n config: Record<string, unknown>;\n}): McpServerTransportConfig {\n if (isRecord(input.config.transport)) {\n return input.config.transport as unknown as McpServerTransportConfig;\n }\n\n if (typeof input.config.command === 'string') {\n const args = optionalStringArray(input.config.args);\n const env = optionalStringRecord(input.config.env);\n return {\n type: 'stdio',\n command: input.config.command,\n ...(args ? { args } : {}),\n ...(typeof input.config.cwd === 'string'\n ? { cwd: input.config.cwd }\n : {}),\n ...(env ? { env } : {}),\n };\n }\n\n if (typeof input.config.url === 'string') {\n const configuredType = input.config.type ?? input.config.transportType;\n const headers = optionalStringRecord(input.config.headers);\n return {\n type:\n configuredType === 'http' || configuredType === 'streamableHttp'\n ? 'streamableHttp'\n : 'sse',\n url: input.config.url,\n ...(headers ? { headers } : {}),\n };\n }\n\n throw new Error(\n `Cline MCP server ${JSON.stringify(input.serverName)} must define a transport, command, or URL.`,\n );\n}\n\nfunction resolveRegistration(input: {\n serverName: string;\n config: unknown;\n}): McpServerRegistration {\n if (!isRecord(input.config)) {\n throw new Error(\n `Cline MCP server ${JSON.stringify(input.serverName)} must be configured with an object value.`,\n );\n }\n\n return {\n name: input.serverName,\n transport: resolveTransport({\n serverName: input.serverName,\n config: input.config,\n }),\n ...(typeof input.config.disabled === 'boolean'\n ? { disabled: input.config.disabled }\n : {}),\n ...(isRecord(input.config.metadata)\n ? { metadata: input.config.metadata }\n : {}),\n ...(isRecord(input.config.oauth) ? { oauth: input.config.oauth } : {}),\n };\n}\n\nexport async function createClineMcpRuntime(input: {\n mcpServers: Record<string, unknown> | undefined;\n}): Promise<ClineMcpRuntime> {\n if (input.mcpServers == null || Object.keys(input.mcpServers).length === 0) {\n return {\n tools: [],\n toolNames: new Set(),\n dispose: async () => {},\n };\n }\n\n const {\n createDefaultMcpServerClientFactory,\n createMcpTools,\n InMemoryMcpManager,\n } = (await import(CLINE_CORE_PACKAGE)) as ClineCoreMcpModule;\n const manager = new InMemoryMcpManager({\n clientFactory: createDefaultMcpServerClientFactory(),\n });\n const tools: AgentTool[] = [];\n\n try {\n for (const [serverName, config] of Object.entries(input.mcpServers)) {\n const registration = resolveRegistration({ serverName, config });\n await manager.registerServer(registration);\n if (registration.disabled) continue;\n tools.push(\n ...(await createMcpTools({\n serverName,\n provider: manager,\n })),\n );\n }\n } catch (error) {\n await manager.dispose().catch(() => {});\n throw error;\n }\n\n return {\n tools,\n toolNames: new Set(tools.map(tool => tool.name)),\n dispose: async () => manager.dispose(),\n };\n}\n","import path from 'node:path';\nimport { shellQuote } from '@ai-sdk/harness/utils';\nimport type { Experimental_SandboxSession } from '@ai-sdk/provider-utils';\n\n/**\n * Sandbox-backed implementations of the Cline harness's built-in tools.\n *\n * The Cline runtime executes on the host, but the workspace the model reasons\n * about lives in the sandbox — every file/shell operation goes through the\n * restricted `SandboxSession` surface. Relative paths resolve against the\n * per-session working directory the framework created.\n */\nexport interface ClineRemoteOpsOptions {\n readonly sandbox: Experimental_SandboxSession;\n /** Absolute sandbox path of the session's working directory. */\n readonly workDir: string;\n}\n\nexport interface ClineRemoteOps {\n resolvePath(inputPath: string): string;\n readFile(inputPath: string): Promise<string>;\n writeFile(inputPath: string, content: string): Promise<void>;\n editFile(inputPath: string, oldText: string, newText: string): Promise<void>;\n bash(\n command: string,\n input?: {\n /** Timeout in seconds (the `bash` tool contract). */\n timeout?: number;\n signal?: AbortSignal;\n },\n ): Promise<{ output: string; exitCode: number }>;\n grep(\n pattern: string,\n input?: {\n path?: string;\n glob?: string;\n ignoreCase?: boolean;\n literal?: boolean;\n context?: number;\n limit?: number;\n },\n ): Promise<string>;\n glob(pattern: string, inputPath?: string, limit?: number): Promise<string[]>;\n ls(inputPath?: string, limit?: number): Promise<string[]>;\n}\n\nexport function createClineRemoteOps(\n options: ClineRemoteOpsOptions,\n): ClineRemoteOps {\n const { sandbox, workDir } = options;\n const normalizedWorkDir = path.posix.normalize(workDir);\n\n const isInsidePath = ({\n parent,\n candidate,\n }: {\n parent: string;\n candidate: string;\n }): boolean => {\n const relative = path.posix.relative(parent, candidate);\n return (\n relative === '' ||\n (relative !== '..' &&\n !relative.startsWith('../') &&\n !path.posix.isAbsolute(relative))\n );\n };\n\n const assertWorkspacePath = (inputPath: string): string => {\n const normalized = path.posix.normalize(inputPath);\n if (!isInsidePath({ parent: normalizedWorkDir, candidate: normalized })) {\n throw new Error(`Cline path escapes the workspace: ${inputPath}`);\n }\n return normalized;\n };\n\n const resolvePath = (inputPath: string): string => {\n const resolved = path.posix.isAbsolute(inputPath)\n ? path.posix.normalize(inputPath)\n : path.posix.normalize(path.posix.join(normalizedWorkDir, inputPath));\n return assertWorkspacePath(resolved);\n };\n\n const runShell = async ({\n command,\n signal,\n }: {\n command: string;\n signal?: AbortSignal;\n }): Promise<{ exitCode: number; output: string }> => {\n // `sandbox.run({ command })` already wraps in a shell; interpolated\n // paths/values inside `command` are quoted with `shellQuote` by callers.\n const result = await sandbox.run({\n command,\n workingDirectory: normalizedWorkDir,\n ...(signal ? { abortSignal: signal } : {}),\n });\n return {\n exitCode: result.exitCode,\n output: `${result.stdout}${result.stderr}`,\n };\n };\n\n const lastOutputLine = (output: string): string | undefined =>\n output.trim().split('\\n').filter(Boolean).at(-1);\n\n const resolveExistingSandboxPath = async ({\n remotePath,\n inputPath,\n missingMessage,\n }: {\n remotePath: string;\n inputPath: string;\n missingMessage?: string;\n }): Promise<string> => {\n const result = await runShell({\n command: [\n `target=${shellQuote(remotePath)}`,\n 'if [ ! -e \"$target\" ]; then echo \"__CLINE_REALPATH_NOT_FOUND__\"; exit 2; fi',\n 'resolved=$(realpath \"$target\" 2>/dev/null) || { echo \"__CLINE_REALPATH_FAILED__\"; exit 3; }',\n 'printf \\'%s\\\\n\\' \"$resolved\"',\n ].join('; '),\n });\n\n if (result.output.includes('__CLINE_REALPATH_NOT_FOUND__')) {\n throw new Error(missingMessage ?? `Path not found: ${inputPath}`);\n }\n if (\n result.output.includes('__CLINE_REALPATH_FAILED__') ||\n result.exitCode !== 0\n ) {\n throw new Error(`Unable to resolve path: ${inputPath}`);\n }\n\n const resolvedPath = lastOutputLine(result.output);\n if (!resolvedPath) {\n throw new Error(`Unable to resolve path: ${inputPath}`);\n }\n return resolvedPath;\n };\n\n const resolveReadableSandboxPath = async ({\n remotePath,\n inputPath,\n missingMessage,\n }: {\n remotePath: string;\n inputPath: string;\n missingMessage?: string;\n }): Promise<string> =>\n assertWorkspacePath(\n await resolveExistingSandboxPath({\n remotePath,\n inputPath,\n ...(missingMessage ? { missingMessage } : {}),\n }),\n );\n\n const resolveWritableSandboxPath = async ({\n remotePath,\n inputPath,\n }: {\n remotePath: string;\n inputPath: string;\n }): Promise<string> => {\n const result = await runShell({\n command: [\n `target=${shellQuote(remotePath)}`,\n 'if [ -e \"$target\" ] || [ -L \"$target\" ]; then resolved=$(realpath \"$target\" 2>/dev/null) || { echo \"__CLINE_REALPATH_FAILED__\"; exit 3; }; printf \\'%s\\\\n\\' \"$resolved\"; exit 0; fi',\n 'dir=$(dirname \"$target\")',\n 'base=$(basename \"$target\")',\n 'missing=\"$base\"',\n 'while [ ! -e \"$dir\" ] && [ ! -L \"$dir\" ]; do parent=$(dirname \"$dir\"); if [ \"$parent\" = \"$dir\" ]; then echo \"__CLINE_REALPATH_NOT_FOUND__\"; exit 2; fi; missing=\"$(basename \"$dir\")/$missing\"; dir=\"$parent\"; done',\n 'resolved_dir=$(realpath \"$dir\" 2>/dev/null) || { echo \"__CLINE_REALPATH_FAILED__\"; exit 3; }',\n 'printf \\'%s/%s\\\\n\\' \"$resolved_dir\" \"$missing\"',\n ].join('; '),\n });\n\n if (\n result.output.includes('__CLINE_REALPATH_NOT_FOUND__') ||\n result.output.includes('__CLINE_REALPATH_FAILED__') ||\n result.exitCode !== 0\n ) {\n throw new Error(`Unable to resolve path: ${inputPath}`);\n }\n\n const resolvedPath = lastOutputLine(result.output);\n if (!resolvedPath) {\n throw new Error(`Unable to resolve path: ${inputPath}`);\n }\n return assertWorkspacePath(resolvedPath);\n };\n\n const readFile = async (inputPath: string): Promise<string> => {\n const remotePath = resolvePath(inputPath);\n const resolved = await resolveReadableSandboxPath({\n remotePath,\n inputPath,\n missingMessage: `File not found: ${inputPath}`,\n });\n const content = await sandbox.readTextFile({ path: resolved });\n if (content == null) {\n throw new Error(`File not found: ${inputPath}`);\n }\n return content;\n };\n\n const writeFile = async (\n inputPath: string,\n content: string,\n ): Promise<void> => {\n const remotePath = resolvePath(inputPath);\n const resolved = await resolveWritableSandboxPath({\n remotePath,\n inputPath,\n });\n // `writeTextFile` creates parent directories recursively per the\n // SandboxSession contract, so no explicit mkdir is needed.\n await sandbox.writeTextFile({ path: resolved, content });\n };\n\n const editFile = async (\n inputPath: string,\n oldText: string,\n newText: string,\n ): Promise<void> => {\n const remotePath = resolvePath(inputPath);\n const resolved = assertWorkspacePath(\n await resolveExistingSandboxPath({\n remotePath,\n inputPath,\n missingMessage: `File not found: ${inputPath}`,\n }),\n );\n const current = await sandbox.readTextFile({ path: resolved });\n if (current == null) {\n throw new Error(`File not found: ${inputPath}`);\n }\n const index = current.indexOf(oldText);\n if (index === -1) {\n throw new Error(`Text to replace was not found in ${inputPath}`);\n }\n const updated = `${current.slice(0, index)}${newText}${current.slice(\n index + oldText.length,\n )}`;\n await writeFile(inputPath, updated);\n };\n\n return {\n resolvePath,\n readFile,\n writeFile,\n editFile,\n\n async bash(command, input) {\n const controller = new AbortController();\n // `input.timeout` is expressed in seconds (the `bash` tool contract),\n // so convert to milliseconds for `setTimeout`.\n const timeoutId =\n typeof input?.timeout === 'number' && input.timeout > 0\n ? setTimeout(() => controller.abort(), input.timeout * 1000)\n : undefined;\n\n const forwardedSignal = input?.signal;\n const onAbort = () => controller.abort();\n forwardedSignal?.addEventListener('abort', onAbort, { once: true });\n\n try {\n const result = await runShell({\n command,\n signal: controller.signal,\n });\n return { output: result.output, exitCode: result.exitCode };\n } finally {\n forwardedSignal?.removeEventListener('abort', onAbort);\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n },\n\n async grep(pattern, input = {}) {\n const inputPath = input.path ?? '.';\n const remotePath = resolvePath(inputPath);\n const target = await resolveReadableSandboxPath({\n remotePath,\n inputPath,\n });\n const flags = [\n '-r',\n '-n',\n '--binary-files=without-match',\n ...(input.ignoreCase ? ['-i'] : []),\n ...(input.literal ? ['-F'] : []),\n ...(typeof input.context === 'number' && input.context > 0\n ? ['-C', String(input.context)]\n : []),\n ...(input.glob ? ['--include', input.glob] : []),\n ];\n const limit = Math.max(1, input.limit ?? 100);\n const result = await runShell({\n command: [\n `if [ ! -e ${shellQuote(\n target,\n )} ]; then echo \"__CLINE_GREP_NOT_FOUND__\"; exit 2; fi`,\n `grep ${flags.map(shellQuote).join(' ')} -- ${shellQuote(\n pattern,\n )} ${shellQuote(target)} 2>/dev/null | head -n ${limit}`,\n ].join('; '),\n });\n\n const output = result.output.trim();\n if (output.includes('__CLINE_GREP_NOT_FOUND__')) {\n throw new Error(`Path not found: ${input.path ?? '.'}`);\n }\n return output || 'No matches found';\n },\n\n async glob(pattern, inputPath = '.', limit = 1_000) {\n const remotePath = resolvePath(inputPath);\n const target = await resolveReadableSandboxPath({\n remotePath,\n inputPath,\n });\n const result = await runShell({\n command: [\n `if [ ! -e ${shellQuote(\n target,\n )} ]; then echo \"__CLINE_FIND_NOT_FOUND__\"; exit 2; fi`,\n `if [ -d ${shellQuote(target)} ]; then find ${shellQuote(\n target,\n )} -type f -print; else printf '%s\\\\n' ${shellQuote(target)}; fi`,\n ].join('; '),\n });\n\n const output = result.output.trim();\n if (output.includes('__CLINE_FIND_NOT_FOUND__')) {\n throw new Error(`Path not found: ${inputPath}`);\n }\n\n return output\n .split('\\n')\n .filter(Boolean)\n .map(absolutePath => {\n if (absolutePath === target) {\n return path.posix.basename(absolutePath);\n }\n return path.posix.relative(target, absolutePath);\n })\n .filter(\n candidate =>\n candidate.length > 0 && path.matchesGlob(candidate, pattern),\n )\n .sort((left, right) =>\n left.toLowerCase().localeCompare(right.toLowerCase()),\n )\n .slice(0, limit);\n },\n\n async ls(inputPath = '.', limit = 500) {\n const remotePath = resolvePath(inputPath);\n const target = await resolveReadableSandboxPath({\n remotePath,\n inputPath,\n });\n const result = await runShell({\n command: [\n `if [ ! -e ${shellQuote(\n target,\n )} ]; then echo \"__CLINE_LS_NOT_FOUND__\"; exit 2; fi`,\n `if [ ! -d ${shellQuote(\n target,\n )} ]; then echo \"__CLINE_LS_NOT_DIR__\"; exit 3; fi`,\n `cd ${shellQuote(target)}`,\n 'ls -1Ap',\n ].join('; '),\n });\n\n const output = result.output.trim();\n if (output.includes('__CLINE_LS_NOT_FOUND__')) {\n throw new Error(`Path not found: ${inputPath}`);\n }\n if (output.includes('__CLINE_LS_NOT_DIR__')) {\n throw new Error(`Not a directory: ${inputPath}`);\n }\n\n return output\n .split('\\n')\n .filter(Boolean)\n .map(line => line.replace(/[*=@|]$/, ''))\n .sort((left, right) =>\n left.toLowerCase().localeCompare(right.toLowerCase()),\n )\n .slice(0, limit);\n },\n };\n}\n","import path from 'node:path';\nimport type { HarnessV1Skill } from '@ai-sdk/harness';\nimport type { AgentTool } from '@cline/agents';\nimport { createDefaultTools, type ToolExecutors } from '@cline/core';\n\nconst CLINE_SKILL_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;\n\ntype ProjectedClineSkill = {\n readonly id: string;\n readonly name: string;\n readonly description: string;\n readonly content: string;\n readonly files: ReadonlyArray<{\n readonly path: string;\n readonly content: string;\n }>;\n};\n\nexport type ClineSkillsRuntime = {\n readonly signature: string;\n readonly tool?: AgentTool;\n};\n\n/**\n * Build Cline's native skills tool around an immutable in-host projection of\n * the harness skills. The low-level Agent does not discover skills itself, so\n * the adapter provides the same tool contract that Cline's core orchestration\n * layer uses without involving the sandbox filesystem.\n */\nexport function createClineSkillsRuntime({\n skills,\n}: {\n skills: ReadonlyArray<HarnessV1Skill>;\n}): ClineSkillsRuntime {\n const projectedSkills = projectClineSkills({ skills });\n const signature = JSON.stringify(projectedSkills);\n if (projectedSkills.length === 0) {\n return { signature };\n }\n\n const executor: NonNullable<ToolExecutors['skills']> = async (\n ...executorArguments\n ) => {\n const [requestedSkill, args] = executorArguments;\n const skill = projectedSkills.find(\n candidate => candidate.id === normalizeSkillToken(requestedSkill),\n );\n if (skill == null) {\n const availableSkills = projectedSkills.map(skill => skill.name);\n return availableSkills.length > 0\n ? `Skill \"${requestedSkill}\" not found. Available skills: ${availableSkills.join(', ')}`\n : 'No skills are currently available.';\n }\n return renderSkillInstructions({ skill, args });\n };\n executor.configuredSkills = projectedSkills.map(skill => ({\n id: skill.id,\n name: skill.name,\n description: skill.description,\n disabled: false,\n }));\n\n const tool = createDefaultTools({\n executors: { skills: executor },\n enableReadFiles: false,\n enableSearch: false,\n enableBash: false,\n enableWebFetch: false,\n enableApplyPatch: false,\n enableEditor: false,\n enableSkills: true,\n enableAskQuestion: false,\n enableSubmitAndExit: false,\n }).find(tool => tool.name === 'skills');\n if (tool == null) {\n throw new Error('Cline did not create its native skills tool.');\n }\n\n return { signature, tool };\n}\n\nfunction projectClineSkills({\n skills,\n}: {\n skills: ReadonlyArray<HarnessV1Skill>;\n}): ReadonlyArray<ProjectedClineSkill> {\n const names = new Set<string>();\n const ids = new Set<string>();\n return skills\n .map(skill => {\n if (\n !CLINE_SKILL_NAME_PATTERN.test(skill.name) ||\n skill.name === '.' ||\n skill.name === '..'\n ) {\n throw new Error(`Invalid Cline skill name: ${skill.name}`);\n }\n if (names.has(skill.name)) {\n throw new Error(`Duplicate Cline skill name: ${skill.name}`);\n }\n names.add(skill.name);\n\n const id = normalizeSkillToken(skill.name);\n if (ids.has(id)) {\n throw new Error(`Duplicate Cline skill identifier: ${id}`);\n }\n ids.add(id);\n\n return {\n id,\n name: skill.name,\n description: skill.description,\n content: skill.content,\n files: (skill.files ?? [])\n .map(file => ({\n path: normalizeSkillFilePath({\n skillName: skill.name,\n filePath: file.path,\n }),\n content: file.content,\n }))\n .sort(\n (left, right) =>\n left.path.localeCompare(right.path) ||\n left.content.localeCompare(right.content),\n ),\n };\n })\n .sort((left, right) => left.name.localeCompare(right.name));\n}\n\nfunction normalizeSkillToken(skill: string): string {\n return skill.trim().replace(/^\\/+/, '').toLowerCase();\n}\n\nfunction normalizeSkillFilePath({\n skillName,\n filePath,\n}: {\n skillName: string;\n filePath: string;\n}): string {\n const normalized = path.posix.normalize(filePath);\n if (\n normalized === '' ||\n normalized === '.' ||\n normalized.startsWith('../') ||\n normalized.includes('/../') ||\n normalized.endsWith('/..') ||\n path.posix.isAbsolute(normalized)\n ) {\n throw new Error(\n `Invalid Cline skill file path for ${skillName}: ${filePath}`,\n );\n }\n return normalized;\n}\n\nfunction renderSkillInstructions({\n skill,\n args,\n}: {\n skill: ProjectedClineSkill;\n args: string | undefined;\n}): string {\n const trimmedArgs = args?.trim();\n const argsTag = trimmedArgs\n ? `\\n<command-args>${trimmedArgs}</command-args>`\n : '';\n const description = skill.description.trim()\n ? `Description: ${skill.description.trim()}\\n\\n`\n : '';\n const files =\n skill.files.length === 0\n ? ''\n : `\\n\\n<skill-files>\\n${skill.files\n .map(\n file =>\n `<skill-file path=${JSON.stringify(file.path)}>\\n${file.content}\\n</skill-file>`,\n )\n .join('\\n')}\\n</skill-files>`;\n\n return `<command-name>${skill.name}</command-name>${argsTag}\\n<command-instructions>\\n${description}${skill.content}${files}\\n</command-instructions>`;\n}\n","import type {\n JSONValue,\n LanguageModelV4FinishReason,\n LanguageModelV4Usage,\n} from '@ai-sdk/provider';\nimport {\n HarnessCapabilityUnsupportedError,\n type HarnessV1Prompt,\n} from '@ai-sdk/harness';\nimport { secureJsonParse } from '@ai-sdk/provider-utils';\nimport type { AgentMessage, AgentUsage } from '@cline/agents';\n\nconst HARNESS_ID = 'cline';\n\n/**\n * Extract a single user text string from a `HarnessV1Prompt`. The Cline\n * runtime's `run`/`continue` accept a plain string; multimodal user content\n * is not supported in this foundational version.\n */\nexport function extractUserText(prompt: HarnessV1Prompt): string {\n if (typeof prompt === 'string') {\n return prompt;\n }\n\n const { content } = prompt;\n if (typeof content === 'string') {\n return content;\n }\n\n const parts: string[] = [];\n for (const part of content) {\n if (part.type !== 'text') {\n throw new HarnessCapabilityUnsupportedError({\n message: `cline: only text user-message parts are supported; got '${part.type}'.`,\n harnessId: HARNESS_ID,\n });\n }\n parts.push(part.text);\n }\n return parts.join('\\n\\n');\n}\n\nexport function getErrorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Coerce an arbitrary tool output into a JSON-safe value for a `tool-result`\n * stream part. Strings and JSON-serializable objects pass through; anything\n * that can't survive `JSON.stringify` round-tripping (functions, cycles) is\n * stringified. `undefined` becomes `null` — the runtime schema deliberately\n * accepts `null` for tools with no output.\n */\nexport function toToolResultValue(output: unknown): NonNullable<JSONValue> {\n if (output === undefined || output === null) {\n return null as unknown as NonNullable<JSONValue>;\n }\n if (typeof output === 'string') {\n return output;\n }\n try {\n const serialized = JSON.stringify(output);\n return serialized === undefined\n ? String(output)\n : (secureJsonParse(serialized) as NonNullable<JSONValue>);\n } catch {\n return String(output);\n }\n}\n\n/**\n * Map the Cline model-level finish reason (`AgentModelFinishReason`) onto the\n * V4 unified finish-reason vocabulary. Used for `finish-step` parts.\n */\nexport function mapModelFinishReason(\n reason: string,\n): LanguageModelV4FinishReason {\n switch (reason) {\n case 'stop':\n return { unified: 'stop', raw: reason };\n case 'tool-calls':\n return { unified: 'tool-calls', raw: reason };\n case 'max-tokens':\n return { unified: 'length', raw: reason };\n case 'error':\n return { unified: 'error', raw: reason };\n default:\n return { unified: 'other', raw: reason };\n }\n}\n\n/**\n * Map a completed run's status onto the V4 unified finish reason. Used for\n * the terminal `finish` part.\n */\nexport function mapRunFinishReason(\n status: 'completed' | 'aborted' | 'failed',\n): LanguageModelV4FinishReason {\n switch (status) {\n case 'completed':\n return { unified: 'stop', raw: status };\n case 'aborted':\n return { unified: 'other', raw: status };\n case 'failed':\n return { unified: 'error', raw: status };\n }\n}\n\n/**\n * Convert the Cline runtime's cumulative `AgentUsage` into the V4 usage shape.\n */\nexport function usageFromAgentUsage(usage: AgentUsage): LanguageModelV4Usage {\n return {\n inputTokens: {\n total: usage.inputTokens,\n noCache: undefined,\n cacheRead: usage.cacheReadTokens,\n cacheWrite: usage.cacheWriteTokens,\n },\n outputTokens: {\n total: usage.outputTokens,\n text: undefined,\n reasoning: usage.reasoningTokenCount,\n },\n ...(usage.totalCost !== undefined\n ? { raw: { totalCost: usage.totalCost } }\n : {}),\n };\n}\n\n/**\n * Convert a single assistant message's per-call metrics into the V4 usage\n * shape. Metrics may be absent; all fields stay optional in that case.\n */\nexport function usageFromMessageMetrics(\n metrics: AgentMessage['metrics'],\n): LanguageModelV4Usage {\n return {\n inputTokens: {\n total: metrics?.inputTokens,\n noCache: undefined,\n cacheRead: metrics?.cacheReadTokens,\n cacheWrite: metrics?.cacheWriteTokens,\n },\n outputTokens: {\n total: metrics?.outputTokens,\n text: undefined,\n reasoning: metrics?.reasoningTokenCount,\n },\n };\n}\n","import type {\n HarnessV1BuiltinToolFiltering,\n HarnessV1QuestionsToolOutput,\n HarnessV1ToolSpec,\n} from '@ai-sdk/harness';\nimport {\n createTool,\n type AgentTool,\n type AgentToolResult,\n} from '@cline/agents';\nimport { createDefaultTools } from '@cline/core';\nimport type { ClineRemoteOps } from './cline-remote-ops';\nimport { getErrorText } from './cline-utils';\n\n/**\n * Native names of the Cline harness's built-in tools. The Cline runtime\n * requires snake_case tool names, and every one of these already matches its\n * cross-harness common name, so the public (wire) names and native names are\n * identical.\n */\nexport const CLINE_NATIVE_BUILTIN_NAMES = [\n 'ask_question',\n 'read',\n 'write',\n 'edit',\n 'bash',\n 'grep',\n 'glob',\n 'ls',\n 'skills',\n] as const;\n\nexport type ClineNativeBuiltinName =\n (typeof CLINE_NATIVE_BUILTIN_NAMES)[number];\n\nexport const CLINE_NATIVE_TOOL_KINDS: Readonly<\n Record<ClineNativeBuiltinName, 'readonly' | 'edit' | 'bash'>\n> = {\n ask_question: 'readonly',\n read: 'readonly',\n write: 'edit',\n edit: 'edit',\n bash: 'bash',\n grep: 'readonly',\n glob: 'readonly',\n ls: 'readonly',\n skills: 'readonly',\n};\n\nexport function isClineBuiltinToolName(\n name: string,\n): name is ClineNativeBuiltinName {\n return (CLINE_NATIVE_BUILTIN_NAMES as readonly string[]).includes(name);\n}\n\n/**\n * Resolve which built-in tools stay active for a session under the framework's\n * `builtinToolFiltering`. Names map 1:1 (native === common), so filtering is a\n * plain include/exclude.\n */\nexport function resolveActiveClineBuiltinNames(\n toolFiltering: HarnessV1BuiltinToolFiltering | undefined,\n): ReadonlyArray<ClineNativeBuiltinName> {\n if (toolFiltering == null) return CLINE_NATIVE_BUILTIN_NAMES;\n const filteredNames = toolFiltering.toolNames.map(name =>\n name === 'askUserQuestions' ? 'ask_question' : name,\n );\n if (toolFiltering.mode === 'allow') {\n return CLINE_NATIVE_BUILTIN_NAMES.filter(name =>\n filteredNames.includes(name),\n );\n }\n return CLINE_NATIVE_BUILTIN_NAMES.filter(\n name => !filteredNames.includes(name),\n );\n}\n\nexport interface PendingToolResult {\n resolve: (value: unknown) => void;\n}\n\nexport interface PendingClineQuestion {\n readonly input: {\n readonly question: string;\n readonly options: readonly string[];\n };\n resolve: (value: string) => void;\n}\n\nexport interface PendingClineQuestionResult {\n readonly output: HarnessV1QuestionsToolOutput;\n}\n\nexport function clineQuestionKey(input: {\n readonly question: string;\n readonly options: readonly string[];\n}): string {\n return JSON.stringify([input.question, input.options]);\n}\n\nconst clineToolResultMarker = Symbol('cline-tool-result');\n\ninterface ClineToolResult {\n readonly [clineToolResultMarker]: true;\n readonly output: unknown;\n readonly isError?: boolean;\n}\n\nexport function createClineToolResult({\n output,\n isError,\n}: {\n output: unknown;\n isError?: boolean;\n}): ClineToolResult {\n return {\n [clineToolResultMarker]: true,\n output,\n ...(isError ? { isError: true } : {}),\n };\n}\n\nexport function unwrapClineToolResult(\n value: unknown,\n): AgentToolResult | undefined {\n if (\n value == null ||\n typeof value !== 'object' ||\n (value as ClineToolResult)[clineToolResultMarker] !== true\n ) {\n return undefined;\n }\n\n const result = value as ClineToolResult;\n return {\n output: result.output,\n ...(result.isError ? { isError: true } : {}),\n };\n}\n\n/*\n * The Cline runtime treats a thrown tool error as a \"mistake\" against the\n * agent's mistake limit, so built-ins catch and return errors as structured\n * data — the model reads the error and adjusts.\n */\nasync function guarded<T>(run: () => Promise<T>): Promise<ClineToolResult> {\n try {\n return createClineToolResult({ output: await run() });\n } catch (error) {\n return createClineToolResult({\n output: { error: getErrorText(error) },\n isError: true,\n });\n }\n}\n\n/**\n * Build the sandbox-backed coding tools handed to the Cline runtime. These\n * schemas mirror their declarations in `CLINE_BUILTIN_TOOLS`\n * (cline-harness.ts). The in-host skills tool is built separately.\n */\nexport function buildBuiltinAgentTools({\n ops,\n activeNames,\n pendingQuestions = new Map(),\n pendingQuestionResults = new Map(),\n}: {\n ops: ClineRemoteOps;\n activeNames: ReadonlyArray<ClineNativeBuiltinName>;\n pendingQuestions?: Map<string, PendingClineQuestion>;\n pendingQuestionResults?: Map<string, PendingClineQuestionResult>;\n}): AgentTool<any, any>[] {\n // biome/eslint: `any` matches the runtime's own `tools?: readonly AgentTool<any, any>[]`.\n const tools: Partial<Record<ClineNativeBuiltinName, AgentTool<any, any>>> = {\n ask_question: createDefaultTools({\n executors: {\n askQuestion: async (question, options, context) => {\n if (context.toolCallId == null) {\n throw new Error(\n 'Cline ask_question did not provide a tool call id.',\n );\n }\n const questionKey = clineQuestionKey({ question, options });\n const pendingResult = pendingQuestionResults.get(questionKey);\n if (pendingResult != null) {\n pendingQuestionResults.delete(questionKey);\n return toClineQuestionResult({\n nativeInput: { question, options },\n output: pendingResult.output,\n });\n }\n return new Promise<string>(resolve => {\n pendingQuestions.set(context.toolCallId!, {\n input: { question, options },\n resolve,\n });\n });\n },\n },\n enableReadFiles: false,\n enableSearch: false,\n enableBash: false,\n enableWebFetch: false,\n enableApplyPatch: false,\n enableEditor: false,\n enableSkills: false,\n enableAskQuestion: true,\n }).find(tool => tool.name === 'ask_question'),\n read: createTool({\n name: 'read',\n description: 'Read file contents.',\n inputSchema: {\n type: 'object',\n properties: {\n file_path: {\n type: 'string',\n description: 'Path of the file to read.',\n },\n },\n required: ['file_path'],\n },\n execute: async (input: { file_path: string }) =>\n guarded(() => ops.readFile(input.file_path)),\n }),\n write: createTool({\n name: 'write',\n description: 'Overwrite or create a file.',\n inputSchema: {\n type: 'object',\n properties: {\n file_path: {\n type: 'string',\n description: 'Path of the file to write.',\n },\n content: {\n type: 'string',\n description: 'Full file content to write.',\n },\n },\n required: ['file_path', 'content'],\n },\n execute: async (input: { file_path: string; content: string }) =>\n guarded(async () => {\n await ops.writeFile(input.file_path, input.content);\n return `Wrote ${input.file_path}`;\n }),\n }),\n edit: createTool({\n name: 'edit',\n description: 'Edit a file by exact string replacement.',\n inputSchema: {\n type: 'object',\n properties: {\n file_path: {\n type: 'string',\n description: 'Path of the file to edit.',\n },\n old_string: { type: 'string', description: 'Exact text to replace.' },\n new_string: { type: 'string', description: 'Replacement text.' },\n },\n required: ['file_path', 'old_string', 'new_string'],\n },\n execute: async (input: {\n file_path: string;\n old_string: string;\n new_string: string;\n }) =>\n guarded(async () => {\n await ops.editFile(\n input.file_path,\n input.old_string,\n input.new_string,\n );\n return `Edited ${input.file_path}`;\n }),\n }),\n bash: createTool({\n name: 'bash',\n description:\n 'Execute a shell command in the sandbox workspace. Returns combined stdout/stderr and the exit code.',\n inputSchema: {\n type: 'object',\n properties: {\n command: { type: 'string', description: 'Shell command to execute.' },\n timeout: {\n type: 'number',\n description: 'Optional timeout in seconds.',\n },\n },\n required: ['command'],\n },\n execute: async (input: { command: string; timeout?: number }, context) =>\n guarded(async () => {\n const result = await ops.bash(input.command, {\n ...(typeof input.timeout === 'number'\n ? { timeout: input.timeout }\n : {}),\n ...(context.signal ? { signal: context.signal } : {}),\n });\n return `${result.output}${\n result.exitCode != null ? `\\n\\n(exit ${result.exitCode})` : ''\n }`.trim();\n }),\n }),\n grep: createTool({\n name: 'grep',\n description: 'Search file contents with regex.',\n inputSchema: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Regex pattern to search for.',\n },\n path: { type: 'string', description: 'File or directory to search.' },\n glob: { type: 'string', description: 'Glob filter for file names.' },\n ignoreCase: { type: 'boolean' },\n literal: {\n type: 'boolean',\n description: 'Treat pattern as a literal string.',\n },\n context: {\n type: 'number',\n description: 'Lines of context around matches.',\n },\n limit: {\n type: 'number',\n description: 'Maximum matching lines to return.',\n },\n },\n required: ['pattern'],\n },\n execute: async (input: {\n pattern: string;\n path?: string;\n glob?: string;\n ignoreCase?: boolean;\n literal?: boolean;\n context?: number;\n limit?: number;\n }) => guarded(() => ops.grep(input.pattern, input)),\n }),\n glob: createTool({\n name: 'glob',\n description: 'Find files matching a glob pattern.',\n inputSchema: {\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'Glob pattern to match.' },\n path: { type: 'string', description: 'Directory to search from.' },\n limit: { type: 'number', description: 'Maximum paths to return.' },\n },\n required: ['pattern'],\n },\n execute: async (input: {\n pattern: string;\n path?: string;\n limit?: number;\n }) =>\n guarded(async () => {\n const matches = await ops.glob(\n input.pattern,\n input.path ?? '.',\n input.limit ?? 1_000,\n );\n return matches.length > 0 ? matches.join('\\n') : 'No files found';\n }),\n }),\n ls: createTool({\n name: 'ls',\n description: 'List directory entries.',\n inputSchema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Directory to list.' },\n limit: { type: 'number', description: 'Maximum entries to return.' },\n },\n },\n execute: async (input: { path?: string; limit?: number }) =>\n guarded(async () => {\n const entries = await ops.ls(input.path ?? '.', input.limit ?? 500);\n return entries.join('\\n');\n }),\n }),\n };\n\n return activeNames\n .map(name => tools[name])\n .filter((tool): tool is AgentTool<any, any> => tool != null);\n}\n\nexport function toClineQuestionResult(input: {\n nativeInput: PendingClineQuestion['input'];\n output: HarnessV1QuestionsToolOutput;\n}): string {\n if (\n input.output.action === 'declined' ||\n input.output.action === 'cancelled'\n ) {\n return `The user ${input.output.action} the question.`;\n }\n const answer = input.output.answers['question-1'];\n if (answer == null) return 'The user did not answer the question.';\n if (answer.freeform != null) return answer.freeform;\n const result = answer.optionIds\n .map(id => {\n const index = Number(id.replace(/^option-/, '')) - 1;\n return input.nativeInput.options[index];\n })\n .filter((value): value is string => value != null)\n .join(', ');\n return result;\n}\n\n/**\n * Build host-executed user tools. When the model calls one, the tool parks a\n * promise keyed by the runtime's `toolCallId`; the harness caller supplies the\n * output via `submitToolResult`, which resolves the promise and lets the loop\n * continue. The adapter never executes these itself.\n */\nexport function buildUserAgentTools({\n specs,\n pendingToolResults,\n}: {\n specs: ReadonlyArray<HarnessV1ToolSpec>;\n pendingToolResults: Map<string, PendingToolResult>;\n}): AgentTool<any, any>[] {\n return specs.map(spec =>\n createTool({\n name: spec.name,\n description: spec.description ?? `User-registered tool ${spec.name}`,\n inputSchema: (spec.inputSchema as Record<string, unknown>) ?? {\n type: 'object',\n properties: {},\n additionalProperties: true,\n },\n execute: async (_input: unknown, context) => {\n const toolCallId = context.toolCallId;\n if (!toolCallId) {\n return createClineToolResult({\n output: { error: 'Tool call is missing a toolCallId.' },\n isError: true,\n });\n }\n return new Promise<unknown>(resolve => {\n pendingToolResults.set(toolCallId, { resolve });\n // If the turn is aborted while waiting for the host, settle so the\n // runtime's tool execution does not dangle forever.\n context.signal?.addEventListener(\n 'abort',\n () => {\n if (pendingToolResults.delete(toolCallId)) {\n resolve(\n createClineToolResult({\n output: {\n error:\n 'Turn was aborted before a tool result was submitted.',\n },\n isError: true,\n }),\n );\n }\n },\n { once: true },\n );\n });\n },\n }),\n );\n}\n","import type { HarnessV1StreamPart } from '@ai-sdk/harness';\nimport type { AgentRuntimeEvent, AgentToolResult } from '@cline/agents';\nimport {\n mapModelFinishReason,\n toToolResultValue,\n usageFromMessageMetrics,\n} from './cline-utils';\n\ntype FinishStepPart = Extract<\n HarnessV1StreamPart,\n { readonly type: 'finish-step' }\n>;\n\n/**\n * Per-turn translator state. Tracks open text/reasoning blocks (the Cline\n * runtime streams flat deltas; the harness contract wants explicit\n * start/delta/end block framing) and which tool calls have already been\n * surfaced — an approval request can emit a `tool-call` part before the\n * runtime's own `tool-started` event fires for it. Cline emits the assistant\n * message before executing that iteration's tools, so the step boundary is\n * buffered until `turn-finished` confirms that those tools have settled.\n */\nexport interface ClineTranslatorState {\n readonly builtinToolNames: ReadonlySet<string>;\n readonly dynamicToolCallIds: Set<string>;\n readonly hostToolNames: ReadonlySet<string>;\n readonly ignoredToolNames: ReadonlySet<string>;\n readonly mcpToolNames: ReadonlySet<string>;\n openTextBlockId?: string;\n openReasoningBlockId?: string;\n emittedToolCalls: Set<string>;\n pendingFinishStep?: FinishStepPart;\n blockCounter: number;\n}\n\nexport function createClineTranslatorState({\n builtinToolNames,\n hostToolNames = [],\n ignoredToolNames = [],\n mcpToolNames = [],\n}: {\n builtinToolNames: Iterable<string>;\n hostToolNames?: Iterable<string>;\n ignoredToolNames?: Iterable<string>;\n mcpToolNames?: Iterable<string>;\n}): ClineTranslatorState {\n return {\n builtinToolNames: new Set(builtinToolNames),\n dynamicToolCallIds: new Set(),\n hostToolNames: new Set(hostToolNames),\n ignoredToolNames: new Set(ignoredToolNames),\n mcpToolNames: new Set(mcpToolNames),\n emittedToolCalls: new Set(),\n blockCounter: 0,\n };\n}\n\nfunction closeOpenBlocks(state: ClineTranslatorState): HarnessV1StreamPart[] {\n const parts: HarnessV1StreamPart[] = [];\n if (state.openReasoningBlockId) {\n parts.push({ type: 'reasoning-end', id: state.openReasoningBlockId });\n state.openReasoningBlockId = undefined;\n }\n if (state.openTextBlockId) {\n parts.push({ type: 'text-end', id: state.openTextBlockId });\n state.openTextBlockId = undefined;\n }\n return parts;\n}\n\nfunction toolCallPart(\n state: ClineTranslatorState,\n toolCall: { toolCallId: string; toolName: string; input: unknown },\n): HarnessV1StreamPart {\n const isMcpTool =\n state.mcpToolNames.has(toolCall.toolName) &&\n !state.hostToolNames.has(toolCall.toolName);\n if (isMcpTool) {\n state.dynamicToolCallIds.add(toolCall.toolCallId);\n }\n if (toolCall.toolName === 'ask_question') {\n const nativeInput = toolCall.input as {\n question: string;\n options: string[];\n };\n return {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName: 'askUserQuestions',\n input: JSON.stringify({\n allowPartialAnswers: false,\n questions: [\n {\n id: 'question-1',\n question: nativeInput.question,\n options: nativeInput.options.map((label, index) => ({\n id: `option-${index + 1}`,\n label,\n })),\n allowFreeForm: true,\n },\n ],\n }),\n providerExecuted: false,\n providerMetadata: {\n cline: {\n nativeRequest: nativeInput,\n },\n },\n nativeName: 'ask_question',\n };\n }\n return {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: JSON.stringify(toolCall.input ?? {}),\n /*\n * Built-ins and external MCP tools are executed by the Cline runtime.\n * Typed host tools wait for dispatch through `submitToolResult`, including\n * when a host tool has the same name as a configured MCP tool.\n */\n ...(state.builtinToolNames.has(toolCall.toolName) || isMcpTool\n ? { providerExecuted: true }\n : {}),\n ...(isMcpTool ? { dynamic: true } : {}),\n };\n}\n\n/**\n * Emit the `tool-call` + `tool-approval-request` pair for a built-in tool\n * that requires approval. The Cline runtime asks for approval *before* its\n * `tool-started` event fires, so the `tool-call` part is emitted here and\n * deduplicated when `tool-started` arrives.\n */\nexport function toolApprovalParts(\n state: ClineTranslatorState,\n toolCall: { toolCallId: string; toolName: string; input: unknown },\n): HarnessV1StreamPart[] {\n const parts: HarnessV1StreamPart[] = [];\n if (!state.emittedToolCalls.has(toolCall.toolCallId)) {\n state.emittedToolCalls.add(toolCall.toolCallId);\n parts.push(toolCallPart(state, toolCall));\n }\n parts.push({\n type: 'tool-approval-request',\n approvalId: toolCall.toolCallId,\n toolCallId: toolCall.toolCallId,\n });\n return parts;\n}\n\n/**\n * Translate one Cline runtime event into zero or more harness stream parts.\n * Terminal events (`run-finished`, `run-failed`) are intentionally not\n * translated here — the session driver emits `finish`/`error` after the\n * runtime's promise settles, so a suspend can close the stream cleanly.\n */\nexport function translateClineEvent(\n event: AgentRuntimeEvent,\n state: ClineTranslatorState,\n): HarnessV1StreamPart[] {\n switch (event.type) {\n case 'assistant-reasoning-delta': {\n const parts: HarnessV1StreamPart[] = [];\n if (state.openTextBlockId) {\n parts.push({ type: 'text-end', id: state.openTextBlockId });\n state.openTextBlockId = undefined;\n }\n if (!state.openReasoningBlockId) {\n state.openReasoningBlockId = `reasoning-${++state.blockCounter}`;\n parts.push({ type: 'reasoning-start', id: state.openReasoningBlockId });\n }\n parts.push({\n type: 'reasoning-delta',\n id: state.openReasoningBlockId,\n delta: event.text,\n });\n return parts;\n }\n\n case 'assistant-text-delta': {\n const parts: HarnessV1StreamPart[] = [];\n if (state.openReasoningBlockId) {\n parts.push({ type: 'reasoning-end', id: state.openReasoningBlockId });\n state.openReasoningBlockId = undefined;\n }\n if (!state.openTextBlockId) {\n state.openTextBlockId = `text-${++state.blockCounter}`;\n parts.push({ type: 'text-start', id: state.openTextBlockId });\n }\n parts.push({\n type: 'text-delta',\n id: state.openTextBlockId,\n delta: event.text,\n });\n return parts;\n }\n\n case 'assistant-message': {\n const parts = closeOpenBlocks(state);\n state.pendingFinishStep = {\n type: 'finish-step',\n finishReason: mapModelFinishReason(event.finishReason),\n usage: usageFromMessageMetrics(event.message.metrics),\n };\n return parts;\n }\n\n case 'turn-finished': {\n const pendingFinishStep = state.pendingFinishStep;\n if (!pendingFinishStep) {\n return [];\n }\n state.pendingFinishStep = undefined;\n return [pendingFinishStep];\n }\n\n case 'tool-started': {\n if (state.ignoredToolNames.has(event.toolCall.toolName)) return [];\n if (state.emittedToolCalls.has(event.toolCall.toolCallId)) {\n return [];\n }\n state.emittedToolCalls.add(event.toolCall.toolCallId);\n return [toolCallPart(state, event.toolCall)];\n }\n\n case 'tool-finished': {\n if (state.ignoredToolNames.has(event.toolCall.toolName)) return [];\n // The tool message carries the runtime's recorded result for this call.\n const resultPart = event.message.content.find(\n (part): part is Extract<typeof part, { type: 'tool-result' }> =>\n part.type === 'tool-result' &&\n part.toolCallId === event.toolCall.toolCallId,\n );\n const output = resultPart?.output as AgentToolResult['output'] | unknown;\n const dynamic = state.dynamicToolCallIds.delete(\n event.toolCall.toolCallId,\n );\n return [\n {\n type: 'tool-result',\n toolCallId: event.toolCall.toolCallId,\n toolName:\n event.toolCall.toolName === 'ask_question'\n ? 'askUserQuestions'\n : event.toolCall.toolName,\n result: toToolResultValue(output),\n ...(resultPart?.isError ? { isError: true } : {}),\n ...(dynamic ? { dynamic: true } : {}),\n },\n ];\n }\n\n case 'tool-updated':\n return [\n {\n type: 'raw',\n rawValue: {\n type: 'tool-updated',\n toolCallId: event.toolCall.toolCallId,\n toolName: event.toolCall.toolName,\n update: event.update,\n },\n },\n ];\n\n case 'status-notice':\n return [\n {\n type: 'raw',\n rawValue: {\n type: 'status-notice',\n message: event.message,\n ...(event.metadata ? { metadata: event.metadata } : {}),\n },\n },\n ];\n\n default:\n return [];\n }\n}\n\n/**\n * Close any blocks still open when the turn ends (e.g. an aborted turn whose\n * `assistant-message` never arrived). A buffered step that never reached\n * Cline's `turn-finished` boundary is incomplete and must not be emitted.\n */\nexport function finishClineTranslation(\n state: ClineTranslatorState,\n): HarnessV1StreamPart[] {\n const parts = closeOpenBlocks(state);\n state.pendingFinishStep = undefined;\n return parts;\n}\n","import {\n HarnessCapabilityUnsupportedError,\n type HarnessV1BuiltinToolFiltering,\n type HarnessV1ContinueTurnOptions,\n type HarnessV1ContinueTurnState,\n type HarnessV1NetworkSandboxSession,\n type HarnessV1PermissionMode,\n type HarnessV1PromptControl,\n type HarnessV1PromptTurnOptions,\n type HarnessV1QuestionsToolOutput,\n type HarnessV1ResumeSessionState,\n type HarnessV1Session,\n type HarnessV1Skill,\n type HarnessV1StreamPart,\n type HarnessV1ToolSpec,\n} from '@ai-sdk/harness';\nimport {\n getRestrictedSandboxSession,\n resolveSandboxHomeDir,\n} from '@ai-sdk/harness/utils';\nimport type { Experimental_SandboxSession as SandboxSession } from '@ai-sdk/provider-utils';\nimport {\n Agent,\n createTool,\n type AgentMessage,\n type AgentModel,\n type AgentRunResult,\n} from '@cline/agents';\nimport { Llms } from '@cline/core';\nimport { createClineMcpRuntime } from './cline-mcp';\nimport { createClineRemoteOps } from './cline-remote-ops';\nimport {\n CLINE_DEFAULT_HISTORY_FILE_NAME,\n persistHistoryToSandbox,\n pullHistoryFromSandbox,\n resolveClinePrivateSessionDirectory,\n safeClineHistoryFileName,\n} from './cline-resume-state';\nimport {\n createClineSkillsRuntime,\n type ClineSkillsRuntime,\n} from './cline-skills';\nimport {\n buildBuiltinAgentTools,\n buildUserAgentTools,\n CLINE_NATIVE_TOOL_KINDS,\n createClineToolResult,\n isClineBuiltinToolName,\n clineQuestionKey,\n resolveActiveClineBuiltinNames,\n type PendingToolResult,\n type PendingClineQuestion,\n type PendingClineQuestionResult,\n toClineQuestionResult,\n unwrapClineToolResult,\n} from './cline-tools';\nimport {\n createClineTranslatorState,\n finishClineTranslation,\n toolApprovalParts,\n translateClineEvent,\n type ClineTranslatorState,\n} from './cline-translate';\nimport {\n extractUserText,\n mapRunFinishReason,\n usageFromAgentUsage,\n} from './cline-utils';\n\nconst HARNESS_ID = 'cline';\n\nexport type ClineReasoningEffort =\n | 'none'\n | 'minimal'\n | 'low'\n | 'medium'\n | 'high'\n | 'xhigh'\n | 'max';\n\n/*\n * The Cline runtime lives in this Node process, not behind an attachable\n * in-sandbox bridge. During a tool approval pause the turn is still alive and\n * blocked on a parked promise, so detach must keep that live session for the\n * next same-process resume instead of stopping it and failing the promise.\n * Cross-process resume falls back to the history file persisted in the\n * sandbox.\n */\nconst parkedClineSessions = new Map<string, HarnessV1Session>();\n\nexport interface ClineSessionSettings {\n readonly authEnv: Record<string, string>;\n readonly isAuthenticationEnvironmentOverride: boolean;\n readonly mcpServers?: Record<string, unknown>;\n readonly providerId?: string;\n readonly apiKey?: string;\n readonly baseUrl?: string;\n readonly headers?: Record<string, string>;\n readonly agentHeaders?: Readonly<Record<string, string>>;\n readonly reasoningEffort?: ClineReasoningEffort;\n readonly maxIterations?: number;\n}\n\nexport interface CreateClineSessionInput {\n readonly sessionId: string;\n readonly sandboxSession: HarnessV1NetworkSandboxSession | SandboxSession;\n readonly sessionWorkDir: string;\n readonly settings: ClineSessionSettings;\n readonly clientApp: string;\n readonly isResume: boolean;\n readonly permissionMode?: HarnessV1PermissionMode;\n readonly builtinToolFiltering?: HarnessV1BuiltinToolFiltering;\n readonly resumeHistoryFileName?: string;\n readonly abortSignal?: AbortSignal;\n}\n\ninterface PendingToolApproval {\n resolve: (value: { approved: boolean; reason?: string }) => void;\n}\n\ninterface ActiveClineTurn {\n readonly token: object;\n readonly done: Promise<void>;\n}\n\ninterface PendingUserMessage {\n readonly text: string;\n resolve(): void;\n reject(error: unknown): void;\n}\n\n/**\n * Whether a thrown error is an abort — the expected result of\n * `doSuspendTurn` aborting the in-flight turn. Only these are safe to swallow\n * while `suspending`; any other error must surface as an `error` chunk.\n */\nfunction isAbortError(value: unknown): boolean {\n if (value == null) return false;\n const name = (value as { name?: unknown }).name;\n if (name === 'AbortError' || name === 'AgentRuntimeAbortError') {\n return true;\n }\n const text =\n typeof value === 'string'\n ? value\n : value instanceof Error\n ? value.message\n : String(value);\n return /\\baborted\\b|AbortError/i.test(text);\n}\n\nfunction clineBuiltinToolRequiresApproval(input: {\n permissionMode: HarnessV1PermissionMode;\n kind: 'readonly' | 'edit' | 'bash';\n}): boolean {\n if (input.permissionMode === 'allow-all') return false;\n if (input.permissionMode === 'allow-edits') return input.kind === 'bash';\n return input.kind === 'edit' || input.kind === 'bash';\n}\n\nfunction buildSystemPrompt(input: {\n sessionWorkDir: string;\n sandboxDescription: string;\n}): string {\n return [\n 'You are Cline, an autonomous coding agent operating inside a sandboxed workspace.',\n `## Workspace\\n\\nThe workspace root is \\`${input.sessionWorkDir}\\`. All relative file paths and shell commands resolve against it. Use the provided tools (read, write, edit, bash, grep, glob, ls) to inspect and modify the workspace.`,\n `## Sandbox\\n\\n${input.sandboxDescription}`,\n ].join('\\n\\n');\n}\n\nfunction toClineBackendProviderBaseUrl(baseUrl: string): string {\n return `${baseUrl.replace(/\\/+$/, '')}/api/v1`;\n}\n\nfunction toAiGatewayProviderBaseUrl(baseUrl: string): string {\n const trimmed = baseUrl.replace(/\\/+$/, '');\n return trimmed.endsWith('/v1') ? trimmed : `${trimmed}/v1`;\n}\n\nfunction createClineAgentModel({\n settings,\n clientApp,\n modelId,\n}: {\n settings: ClineSessionSettings;\n clientApp: string;\n modelId: string | undefined;\n}): { model: AgentModel; providerId: string } {\n const gatewayBaseUrl = settings.authEnv.AI_GATEWAY_BASE_URL;\n const isAiGateway = gatewayBaseUrl != null;\n const providerId = isAiGateway ? 'cline' : (settings.providerId ?? 'cline');\n const apiKey = isAiGateway\n ? settings.authEnv.AI_GATEWAY_API_KEY\n : (settings.apiKey ??\n (providerId === 'cline' ? settings.authEnv.CLINE_API_KEY : undefined));\n const baseUrl = isAiGateway\n ? toAiGatewayProviderBaseUrl(gatewayBaseUrl)\n : (settings.baseUrl ??\n (providerId === 'cline' && settings.authEnv.CLINE_API_BASE_URL\n ? toClineBackendProviderBaseUrl(settings.authEnv.CLINE_API_BASE_URL)\n : undefined));\n const headers = isAiGateway\n ? {\n ...settings.headers,\n ...settings.agentHeaders,\n 'User-Agent': clientApp,\n 'x-client-app': clientApp,\n }\n : settings.headers != null || settings.agentHeaders != null\n ? {\n ...settings.headers,\n ...settings.agentHeaders,\n }\n : undefined;\n const gateway = Llms.createGateway({\n providerConfigs: [\n {\n providerId,\n ...(apiKey ? { apiKey } : {}),\n ...(baseUrl ? { baseUrl } : {}),\n ...(headers ? { headers } : {}),\n ...(isAiGateway || settings.isAuthenticationEnvironmentOverride\n ? { apiKeyEnv: [] }\n : {}),\n },\n ],\n });\n const modelSelection = {\n providerId,\n ...(modelId ? { modelId } : {}),\n };\n const modelOptions =\n settings.reasoningEffort === 'none'\n ? { reasoning: { enabled: false } }\n : {\n reasoning: {\n enabled: true,\n effort: settings.reasoningEffort,\n },\n };\n const model =\n settings.reasoningEffort === undefined\n ? gateway.createAgentModel(modelSelection)\n : gateway.createAgentModel(modelSelection, modelOptions);\n\n return {\n model,\n providerId,\n };\n}\n\nexport async function createClineSession(\n input: CreateClineSessionInput,\n): Promise<HarnessV1Session> {\n if (input.isResume) {\n const parkedSession = parkedClineSessions.get(input.sessionId);\n if (parkedSession) {\n parkedClineSessions.delete(input.sessionId);\n return {\n ...parkedSession,\n isResume: true,\n };\n }\n }\n\n const toolSafeSandboxSession = getRestrictedSandboxSession(\n input.sandboxSession,\n );\n const sandboxHomeDir = await resolveSandboxHomeDir({\n sandbox: toolSafeSandboxSession,\n ...(input.abortSignal ? { abortSignal: input.abortSignal } : {}),\n });\n const privateSessionDir = resolveClinePrivateSessionDirectory({\n sandboxHomeDir,\n sessionWorkDir: input.sessionWorkDir,\n sessionId: input.sessionId,\n });\n const permissionMode = input.permissionMode ?? 'allow-all';\n const activeBuiltinNames = resolveActiveClineBuiltinNames(\n input.builtinToolFiltering,\n );\n\n const ops = createClineRemoteOps({\n sandbox: toolSafeSandboxSession,\n workDir: input.sessionWorkDir,\n });\n\n // On resume: pull the persisted conversation history from the sandbox so\n // the fresh runtime instance starts from the prior transcript.\n let currentMessages: readonly AgentMessage[] = [];\n if (input.isResume && input.resumeHistoryFileName) {\n const restored = await pullHistoryFromSandbox({\n sandbox: toolSafeSandboxSession,\n privateSessionDir,\n historyFileName: safeClineHistoryFileName(input.resumeHistoryFileName),\n ...(input.abortSignal ? { abortSignal: input.abortSignal } : {}),\n });\n if (restored) {\n currentMessages = restored;\n }\n }\n const mcpRuntime = await createClineMcpRuntime({\n mcpServers: input.settings.mcpServers,\n });\n let activeModelId: string | undefined;\n let agentModel = createClineAgentModel({\n settings: input.settings,\n clientApp: input.clientApp,\n modelId: activeModelId,\n });\n\n // Per-session mutable state we hold across prompts.\n let agent: Agent | undefined;\n let unsubscribe: (() => void) | undefined;\n let lastAgentConfigurationSignature: string | undefined;\n let agentHasRun = false;\n let stopped = false;\n /*\n * Set by `doSuspendTurn` before it aborts the in-flight turn at a slice\n * boundary. The turn settles silently when this is set, so the stream\n * closes cleanly (no spurious `error` chunk) — the next slice\n * rerun-continues from the persisted history.\n */\n let suspending = false;\n const pendingToolResults = new Map<string, PendingToolResult>();\n const pendingToolApprovals = new Map<string, PendingToolApproval>();\n const pendingUserMessages: PendingUserMessage[] = [];\n let acceptingUserMessages = false;\n\n // Emit channel set at the start of every turn and cleared on end.\n let currentEmit: ((part: HarnessV1StreamPart) => void) | undefined;\n let translatorState: ClineTranslatorState | undefined;\n const pendingQuestions = new Map<string, PendingClineQuestion>();\n const pendingQuestionResults = new Map<string, PendingClineQuestionResult>();\n let activeTurn: ActiveClineTurn | undefined;\n\n function settlePendingToolResults(reason: string): void {\n for (const pending of pendingToolResults.values()) {\n pending.resolve(\n createClineToolResult({\n output: { error: reason },\n isError: true,\n }),\n );\n }\n pendingToolResults.clear();\n }\n\n function settlePendingToolApprovals(reason: string): void {\n for (const pending of pendingToolApprovals.values()) {\n pending.resolve({ approved: false, reason });\n }\n pendingToolApprovals.clear();\n }\n\n function consumePendingUserMessage(): string | undefined {\n const pending = pendingUserMessages.shift();\n if (pending == null) return undefined;\n pending.resolve();\n return pending.text;\n }\n\n function rejectPendingUserMessages(error: unknown): void {\n for (const pending of pendingUserMessages) {\n pending.reject(error);\n }\n pendingUserMessages.length = 0;\n }\n\n function settlePendingQuestions(reason: string): void {\n for (const pending of pendingQuestions.values()) {\n pending.resolve(reason);\n }\n pendingQuestions.clear();\n pendingQuestionResults.clear();\n }\n\n async function persistHistory(): Promise<void> {\n const messages = agent?.snapshot().messages ?? currentMessages;\n await persistHistoryToSandbox({\n sandbox: toolSafeSandboxSession,\n privateSessionDir,\n historyFileName: CLINE_DEFAULT_HISTORY_FILE_NAME,\n messages,\n });\n }\n\n function requestBuiltinToolApproval(toolCall: {\n toolCallId: string;\n toolName: string;\n input: unknown;\n }): Promise<{ approved: boolean; reason?: string }> {\n if (translatorState && currentEmit) {\n for (const part of toolApprovalParts(translatorState, toolCall)) {\n currentEmit(part);\n }\n }\n return new Promise(resolve => {\n pendingToolApprovals.set(toolCall.toolCallId, { resolve });\n });\n }\n\n function rebuildAgent(rebuildInput: {\n userTools: ReadonlyArray<HarnessV1ToolSpec>;\n skillsRuntime: ClineSkillsRuntime;\n instructions?: string;\n responseFormat?: HarnessV1PromptTurnOptions['responseFormat'];\n }): void {\n unsubscribe?.();\n unsubscribe = undefined;\n agent = new Agent({\n model: agentModel.model,\n ...(activeModelId\n ? {\n messageModelInfo: {\n id: activeModelId,\n provider: agentModel.providerId,\n },\n }\n : {}),\n sessionId: input.sessionId,\n systemPrompt: (() => {\n const baseSystemPrompt = buildSystemPrompt({\n sessionWorkDir: input.sessionWorkDir,\n sandboxDescription: toolSafeSandboxSession.description,\n });\n return rebuildInput.instructions\n ? `${baseSystemPrompt}\\n\\n${rebuildInput.instructions}`\n : baseSystemPrompt;\n })(),\n initialMessages: currentMessages,\n toolExecution: 'parallel',\n ...(input.settings.maxIterations !== undefined\n ? { maxIterations: input.settings.maxIterations }\n : {}),\n tools: [\n ...buildBuiltinAgentTools({\n ops,\n activeNames: activeBuiltinNames,\n pendingQuestions,\n pendingQuestionResults,\n }),\n ...(rebuildInput.skillsRuntime.tool &&\n activeBuiltinNames.includes('skills')\n ? [rebuildInput.skillsRuntime.tool]\n : []),\n ...mcpRuntime.tools,\n ...buildUserAgentTools({\n specs: rebuildInput.userTools,\n pendingToolResults,\n }),\n ...(rebuildInput.responseFormat?.type === 'json' &&\n rebuildInput.responseFormat.schema != null\n ? [\n createTool({\n name: 'structured_output',\n description:\n rebuildInput.responseFormat.description ??\n 'Return the final structured output.',\n inputSchema: {\n type: 'object',\n properties: {\n output: rebuildInput.responseFormat.schema,\n },\n required: ['output'],\n additionalProperties: false,\n },\n lifecycle: { completesRun: true },\n execute: async ({ output }: { output: unknown }) =>\n JSON.stringify(output),\n }),\n ]\n : []),\n ],\n ...(rebuildInput.responseFormat?.type === 'json'\n ? { completionPolicy: { requireCompletionTool: true } }\n : {}),\n hooks: {\n afterTool: ({ result }) => {\n const toolResult = unwrapClineToolResult(result.output);\n return toolResult == null ? undefined : { result: toolResult };\n },\n },\n // Built-in tools whose kind requires approval under the session's\n // permission mode are marked `autoApprove: false`; the runtime then\n // routes them through `requestToolApproval` below. User tools are\n // approved by the harness framework, never by the adapter.\n toolPolicies: Object.fromEntries(\n activeBuiltinNames\n .filter(name =>\n clineBuiltinToolRequiresApproval({\n permissionMode,\n kind: CLINE_NATIVE_TOOL_KINDS[name],\n }),\n )\n .map(name => [name, { autoApprove: false }]),\n ),\n requestToolApproval: request => {\n if (!isClineBuiltinToolName(request.toolName)) {\n // Custom host-executed tool approvals are handled by the framework\n // before results are submitted back; the adapter never gates them.\n return { approved: true };\n }\n return requestBuiltinToolApproval({\n toolCallId: request.toolCallId,\n toolName: request.toolName,\n input: request.input,\n });\n },\n // Mid-turn user messages injected via `submitUserMessage` are consumed\n // by the runtime between loop iterations, before the next model call.\n consumePendingUserMessage,\n });\n agentHasRun = false;\n\n unsubscribe = agent.subscribe(event => {\n if (!translatorState || !currentEmit) return;\n for (const part of translateClineEvent(event, translatorState)) {\n currentEmit(part);\n }\n });\n }\n\n function createPromptControl(controlInput: {\n done: Promise<void>;\n abortSignal?: AbortSignal;\n }): HarnessV1PromptControl {\n const abortHandler = () => {\n // Settle parked host-tool promises first so the runtime's tool\n // executions do not dangle, then abort the loop itself.\n settlePendingToolResults('Turn aborted');\n settlePendingToolApprovals('Turn aborted');\n settlePendingQuestions('The question was cancelled.');\n agent?.abort('Turn aborted by caller');\n };\n if (controlInput.abortSignal) {\n controlInput.abortSignal.addEventListener('abort', abortHandler, {\n once: true,\n });\n void controlInput.done.then(\n () => {\n controlInput.abortSignal?.removeEventListener('abort', abortHandler);\n },\n () => {\n controlInput.abortSignal?.removeEventListener('abort', abortHandler);\n },\n );\n }\n\n return {\n async submitToolResult(args) {\n const pendingQuestion = pendingQuestions.get(args.toolCallId);\n if (pendingQuestion != null) {\n pendingQuestions.delete(args.toolCallId);\n pendingQuestion.resolve(\n toClineQuestionResult({\n nativeInput: pendingQuestion.input,\n output: args.output as HarnessV1QuestionsToolOutput,\n }),\n );\n return;\n }\n if (args.toolResult?.toolName === 'askUserQuestions') {\n const nativeRequest = args.toolResult.providerOptions?.cline\n ?.nativeRequest as PendingClineQuestion['input'] | undefined;\n if (nativeRequest == null) return;\n pendingQuestionResults.set(clineQuestionKey(nativeRequest), {\n output: args.output as HarnessV1QuestionsToolOutput,\n });\n return;\n }\n const pending = pendingToolResults.get(args.toolCallId);\n if (!pending) return;\n pendingToolResults.delete(args.toolCallId);\n pending.resolve(\n createClineToolResult({\n output: args.output,\n isError: args.isError,\n }),\n );\n },\n async submitToolApproval(args) {\n const pending = pendingToolApprovals.get(args.approvalId);\n if (!pending) return;\n pendingToolApprovals.delete(args.approvalId);\n pending.resolve({\n approved: args.approved,\n ...(args.reason !== undefined ? { reason: args.reason } : {}),\n });\n },\n submitUserMessage(text) {\n if (!acceptingUserMessages) {\n return Promise.reject(\n new Error('Cline has no running turn to steer.'),\n );\n }\n return new Promise<void>((resolve, reject) => {\n pendingUserMessages.push({ text, resolve, reject });\n });\n },\n done: controlInput.done,\n };\n }\n\n /*\n * Drive one turn against the Cline runtime and return the control surface.\n * Shared by `doPromptTurn` (a fresh user prompt) and `doContinueTurn`\n * (no prompt — the runtime continues its own thread after a rerun resume).\n */\n async function runTurn(turnOpts: {\n text: string | undefined;\n model?: string;\n skills: ReadonlyArray<HarnessV1Skill>;\n tools: ReadonlyArray<HarnessV1ToolSpec>;\n instructions?: string;\n emit: (part: HarnessV1StreamPart) => void;\n abortSignal?: AbortSignal;\n responseFormat?: HarnessV1PromptTurnOptions['responseFormat'];\n }): Promise<HarnessV1PromptControl> {\n if (stopped) {\n throw new Error('Cline session has been stopped.');\n }\n\n const userTools = turnOpts.tools;\n const skillsRuntime = createClineSkillsRuntime({\n skills: turnOpts.skills,\n });\n if (\n turnOpts.responseFormat?.type === 'json' &&\n turnOpts.responseFormat.schema == null\n ) {\n throw new HarnessCapabilityUnsupportedError({\n message:\n \"Harness 'cline' requires a JSON schema for structured output.\",\n harnessId: HARNESS_ID,\n });\n }\n if (\n turnOpts.responseFormat?.type === 'json' &&\n agentModel.providerId === 'openai-codex-cli'\n ) {\n throw new HarnessCapabilityUnsupportedError({\n message:\n \"Harness 'cline' cannot require structured output with the openai-codex-cli provider because that provider does not expose external tools.\",\n harnessId: HARNESS_ID,\n });\n }\n\n if (turnOpts.model != null && turnOpts.model !== activeModelId) {\n activeModelId = turnOpts.model;\n agentModel = createClineAgentModel({\n settings: input.settings,\n clientApp: input.clientApp,\n modelId: activeModelId,\n });\n }\n\n const signature = JSON.stringify({\n modelId: activeModelId,\n tools: userTools,\n responseFormat: turnOpts.responseFormat,\n instructions: turnOpts.instructions,\n skills: skillsRuntime.signature,\n });\n if (agent == null || signature !== lastAgentConfigurationSignature) {\n currentMessages = agent?.snapshot().messages ?? currentMessages;\n rebuildAgent({\n userTools,\n skillsRuntime,\n responseFormat: turnOpts.responseFormat,\n ...(turnOpts.instructions\n ? { instructions: turnOpts.instructions }\n : {}),\n });\n lastAgentConfigurationSignature = signature;\n }\n\n currentEmit = turnOpts.emit;\n const userToolNames = new Set(userTools.map(tool => tool.name));\n translatorState = createClineTranslatorState({\n builtinToolNames: activeBuiltinNames.filter(\n name => !userToolNames.has(name),\n ),\n hostToolNames: userToolNames,\n ignoredToolNames:\n turnOpts.responseFormat?.type === 'json' ? ['structured_output'] : [],\n mcpToolNames: mcpRuntime.toolNames,\n });\n\n turnOpts.emit({\n type: 'stream-start',\n ...(activeModelId ? { modelId: activeModelId } : {}),\n });\n\n acceptingUserMessages = true;\n const turnPromise = (async () => {\n const runtime = agent!;\n try {\n let nextText = turnOpts.text;\n let result: AgentRunResult;\n for (;;) {\n // `text` is undefined only on rerun-continue: `continue()` without\n // input re-drives the loop from the restored transcript instead of\n // pushing an empty user message.\n result =\n nextText === undefined\n ? await runtime.continue()\n : agentHasRun\n ? await runtime.continue(nextText)\n : await runtime.run(nextText);\n agentHasRun = true;\n currentMessages = result.messages;\n\n if (translatorState) {\n for (const part of finishClineTranslation(translatorState)) {\n currentEmit?.(part);\n }\n }\n\n if (result.status !== 'completed') break;\n const pendingUserMessage = consumePendingUserMessage();\n if (pendingUserMessage == null) break;\n nextText = pendingUserMessage;\n }\n\n if (\n turnOpts.responseFormat?.type === 'json' &&\n result.status === 'completed'\n ) {\n const id = `structured-output-${input.sessionId}`;\n currentEmit?.({ type: 'text-start', id });\n currentEmit?.({\n type: 'text-delta',\n id,\n delta: result.outputText,\n });\n currentEmit?.({ type: 'text-end', id });\n currentEmit?.({\n type: 'finish-step',\n finishReason: { unified: 'stop', raw: 'structured-output' },\n usage: {\n inputTokens: {\n total: 0,\n noCache: undefined,\n cacheRead: undefined,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: 0,\n text: undefined,\n reasoning: undefined,\n },\n },\n });\n }\n\n if (result.status === 'aborted') {\n /*\n * A `doSuspendTurn` aborts the in-flight turn on purpose — settle\n * silently so the stream closes cleanly; the next slice\n * rerun-continues from the persisted history. Caller-driven aborts\n * finish the turn with an `other`/aborted reason.\n */\n if (suspending) return;\n currentEmit?.({\n type: 'finish',\n finishReason: mapRunFinishReason(result.status),\n totalUsage: usageFromAgentUsage(result.usage),\n });\n return;\n }\n\n if (result.status === 'failed') {\n currentEmit?.({\n type: 'error',\n error: result.error ?? new Error('Cline agent run failed'),\n });\n return;\n }\n\n currentEmit?.({\n type: 'finish',\n finishReason: mapRunFinishReason(result.status),\n totalUsage: usageFromAgentUsage(result.usage),\n });\n } catch (error) {\n // `run` resolves for aborted/failed statuses; a throw here is\n // unanticipated (e.g. config error). Swallow only the abort our own\n // suspend caused; surface anything else.\n if (suspending && isAbortError(error)) return;\n currentEmit?.({ type: 'error', error });\n } finally {\n acceptingUserMessages = false;\n rejectPendingUserMessages(\n new Error('Cline turn ended before accepting the user message.'),\n );\n }\n })();\n\n const activeTurnToken = {};\n const done = turnPromise.finally(() => {\n if (activeTurn?.token === activeTurnToken) {\n activeTurn = undefined;\n }\n currentEmit = undefined;\n });\n activeTurn = {\n token: activeTurnToken,\n done,\n };\n\n return createPromptControl({\n done,\n ...(turnOpts.abortSignal ? { abortSignal: turnOpts.abortSignal } : {}),\n });\n }\n\n async function teardown(): Promise<void> {\n unsubscribe?.();\n unsubscribe = undefined;\n agent = undefined;\n await mcpRuntime.dispose();\n }\n\n const doStop = async (): Promise<HarnessV1ResumeSessionState> => {\n if (stopped) {\n throw new Error('Cline session has been stopped.');\n }\n stopped = true;\n parkedClineSessions.delete(input.sessionId);\n settlePendingToolResults('Cline session stopped');\n settlePendingToolApprovals('Cline session stopped');\n settlePendingQuestions('The question was cancelled.');\n\n // Persist the conversation into the sandbox so a future process can pick\n // it up after the sandbox provider reattaches.\n try {\n await persistHistory();\n } catch {\n // Best-effort: a missing history file means resume returns to a fresh\n // conversation rather than failing stop.\n }\n\n agent?.abort('Cline session stopped');\n await teardown();\n\n return {\n type: 'resume-session',\n harnessId: HARNESS_ID,\n specificationVersion: 'harness-v1',\n data: { historyFileName: CLINE_DEFAULT_HISTORY_FILE_NAME },\n };\n };\n\n const sessionImpl: HarnessV1Session = {\n sessionId: input.sessionId,\n isResume: input.isResume,\n\n // The Cline runtime has no bridge to attach to and no in-sandbox event\n // log to replay; its only cross-process resume path is restoring the\n // persisted history on a fresh runtime, i.e. `rerun`.\n\n doPromptTurn: async (\n promptOpts: HarnessV1PromptTurnOptions,\n ): Promise<HarnessV1PromptControl> => {\n return runTurn({\n text: extractUserText(promptOpts.prompt),\n ...(promptOpts.model ? { model: promptOpts.model } : {}),\n skills: promptOpts.skills,\n tools: promptOpts.tools ?? [],\n ...(promptOpts.instructions\n ? { instructions: promptOpts.instructions }\n : {}),\n emit: promptOpts.emit,\n ...(promptOpts.abortSignal\n ? { abortSignal: promptOpts.abortSignal }\n : {}),\n responseFormat: promptOpts.responseFormat,\n });\n },\n\n doContinueTurn: async (\n continueOpts: HarnessV1ContinueTurnOptions,\n ): Promise<HarnessV1PromptControl> => {\n if (activeTurn != null) {\n currentEmit = continueOpts.emit;\n return createPromptControl({\n done: activeTurn.done,\n ...(continueOpts.abortSignal\n ? { abortSignal: continueOpts.abortSignal }\n : {}),\n });\n }\n\n /*\n * The model runs on the host, so there is no live turn to attach to —\n * the previous slice's turn died with its process. Rerun-continue:\n * re-drive the runtime from the history restored on resume. Lossy —\n * work in flight at the slice boundary is recomputed, because a\n * host-resident runtime cannot do a lossless attach.\n */\n return runTurn({\n text: undefined,\n ...(continueOpts.model ? { model: continueOpts.model } : {}),\n skills: continueOpts.skills,\n tools: continueOpts.tools ?? [],\n ...(continueOpts.instructions\n ? { instructions: continueOpts.instructions }\n : {}),\n emit: continueOpts.emit,\n ...(continueOpts.abortSignal\n ? { abortSignal: continueOpts.abortSignal }\n : {}),\n responseFormat: continueOpts.responseFormat,\n });\n },\n\n doCompact: async () => {\n throw new HarnessCapabilityUnsupportedError({\n message:\n 'cline: manual compaction is not supported by the standalone Cline runtime.',\n harnessId: HARNESS_ID,\n });\n },\n\n doDestroy: async () => {\n if (stopped) return;\n stopped = true;\n parkedClineSessions.delete(input.sessionId);\n settlePendingToolResults('Cline session stopped');\n settlePendingToolApprovals('Cline session stopped');\n agent?.abort('Cline session destroyed');\n await teardown();\n },\n\n doStop,\n\n doDetach: async (): Promise<HarnessV1ResumeSessionState> => {\n if (\n activeTurn != null ||\n pendingToolResults.size > 0 ||\n pendingQuestions.size > 0\n ) {\n parkedClineSessions.set(input.sessionId, sessionImpl);\n try {\n await persistHistory();\n } catch {\n /*\n * The parked in-process session is the authoritative continuation\n * path while the live turn is waiting on host input. Persistence\n * is only a fallback for later non-live resumes.\n */\n }\n return {\n type: 'resume-session',\n harnessId: HARNESS_ID,\n specificationVersion: 'harness-v1',\n data: { historyFileName: CLINE_DEFAULT_HISTORY_FILE_NAME },\n };\n }\n return doStop();\n },\n\n doSuspendTurn: async (): Promise<HarnessV1ContinueTurnState> => {\n if (stopped) {\n throw new Error('Cline session has been stopped.');\n }\n if (\n activeTurn != null &&\n (pendingToolResults.size > 0 ||\n pendingToolApprovals.size > 0 ||\n pendingQuestions.size > 0)\n ) {\n parkedClineSessions.set(input.sessionId, sessionImpl);\n try {\n await persistHistory();\n } catch {\n /*\n * While waiting on host input, the live parked session is the\n * authoritative same-process continuation path. The sandbox copy\n * remains a best-effort fallback for a later cold resume.\n */\n }\n return {\n type: 'continue-turn',\n harnessId: HARNESS_ID,\n specificationVersion: 'harness-v1',\n data: { historyFileName: CLINE_DEFAULT_HISTORY_FILE_NAME },\n };\n }\n /*\n * The model runs in this host process, which is about to be suspended\n * at the slice boundary — the in-flight turn cannot survive it. Abort\n * it (the turn settles silently via the `suspending` guard so the\n * stream closes cleanly), persist the history into the sandbox, and\n * tear down host-side resources. The sandbox itself is left running;\n * the next slice pulls the history after the sandbox provider\n * reattaches and rerun-continues. The tail in flight at the boundary\n * is recomputed — a host-resident runtime cannot freeze a live turn\n * the way a bridge adapter can.\n */\n suspending = true;\n agent?.abort('Cline session suspended');\n if (activeTurn) {\n await activeTurn.done.catch(() => {});\n }\n\n try {\n await persistHistory();\n } catch {\n // Best-effort: a missing/failed copy leaves the previously persisted\n // history in place, so the next slice resumes from a slightly older\n // (still valid) state.\n }\n\n stopped = true;\n parkedClineSessions.delete(input.sessionId);\n settlePendingToolResults('Cline session suspended');\n settlePendingToolApprovals('Cline session suspended');\n await teardown();\n\n return {\n type: 'continue-turn',\n harnessId: HARNESS_ID,\n specificationVersion: 'harness-v1',\n data: { historyFileName: CLINE_DEFAULT_HISTORY_FILE_NAME },\n };\n },\n };\n\n return sessionImpl;\n}\n","// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import {\n commonTool,\n HARNESS_V1_BUILTIN_TOOLS,\n type HarnessV1,\n type HarnessV1BuiltinTool,\n} from '@ai-sdk/harness';\nimport { isHarnessAuthenticationEnvironment } from '@ai-sdk/harness/utils';\nimport { tool } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport type { ClineAuthenticationMode } from './cline-auth';\nimport { resolveClineAuthentication } from './cline-subscription';\nimport { clineResumeStateSchema } from './cline-resume-state';\nimport { createClineSession, type ClineReasoningEffort } from './cline-session';\nimport { VERSION } from './version';\n\n/**\n * Value used to identify the harness in provider request headers.\n */\nconst CLINE_CLIENT_APP = `ai-sdk-harness-cline/${VERSION}`;\n\n/**\n * Configuration knobs for `createCline`. The Cline runtime\n * (`@cline/agents`, part of the Cline SDK) runs as an in-process Node\n * library — no bridge, so there is no `port` or `startupTimeoutMs` to set.\n */\nexport type ClineHarnessSettings = {\n /** Where Cline sources direct or AI Gateway credentials from. */\n readonly auth?: ClineAuthenticationMode;\n /**\n * MCP server definitions keyed by server name. Each definition uses the\n * underlying runtime's native MCP server configuration format.\n */\n readonly mcpServers?: Record<string, unknown>;\n /**\n * Cline LLM provider id (e.g. `'anthropic'`, `'openai'`, `'gemini'`).\n * When omitted, direct authentication uses the Cline backend.\n */\n readonly providerId?: string;\n /**\n * Provider API key. When omitted, the Cline gateway falls back to the\n * provider's environment variable (e.g. `ANTHROPIC_API_KEY`).\n * A record-shaped authentication override disables that fallback.\n */\n readonly apiKey?: string;\n /** Custom provider endpoint. */\n readonly baseUrl?: string;\n /** Extra headers sent to the provider. */\n readonly headers?: Record<string, string>;\n /**\n * Reasoning effort for reasoning-capable models. Use `'none'` to disable\n * reasoning. When omitted, the Cline SDK selects the reasoning behavior.\n */\n readonly reasoningEffort?: ClineReasoningEffort;\n /**\n * Safety cap on agent-loop iterations per turn. Unbounded when omitted.\n */\n readonly maxIterations?: number;\n};\n\n/*\n * The Cline runtime requires snake_case tool names, and each of these\n * built-ins already matches its cross-harness common name — so native names\n * and wire names are identical, and `nativeName` mirrors the key. These zod\n * declarations mirror the JSON schemas handed to the runtime in\n * `cline-tools.ts` — keep the two in sync.\n */\nconst CLINE_BUILTIN_TOOLS = {\n askUserQuestions: {\n ...HARNESS_V1_BUILTIN_TOOLS.askUserQuestions,\n nativeName: 'ask_question',\n toolUseKind: 'readonly',\n },\n read: commonTool('read', {\n nativeName: 'read',\n toolUseKind: 'readonly',\n description: 'Read file contents.',\n inputSchema: z.object({\n file_path: z.string(),\n }),\n }),\n write: commonTool('write', {\n nativeName: 'write',\n toolUseKind: 'edit',\n description: 'Overwrite or create a file.',\n inputSchema: z.object({\n file_path: z.string(),\n content: z.string(),\n }),\n }),\n edit: commonTool('edit', {\n nativeName: 'edit',\n toolUseKind: 'edit',\n description: 'Edit a file by exact string replacement.',\n inputSchema: z.object({\n file_path: z.string(),\n old_string: z.string(),\n new_string: z.string(),\n }),\n }),\n bash: commonTool('bash', {\n nativeName: 'bash',\n toolUseKind: 'bash',\n description: 'Execute a shell command in the sandbox.',\n inputSchema: z.object({\n command: z.string(),\n timeout: z.number().optional(),\n }),\n }),\n grep: commonTool('grep', {\n nativeName: 'grep',\n toolUseKind: 'readonly',\n description: 'Search file contents with regex.',\n inputSchema: z.object({\n pattern: z.string(),\n path: z.string().optional(),\n glob: z.string().optional(),\n ignoreCase: z.boolean().optional(),\n literal: z.boolean().optional(),\n context: z.number().optional(),\n limit: z.number().optional(),\n }),\n }),\n glob: commonTool('glob', {\n nativeName: 'glob',\n toolUseKind: 'readonly',\n description: 'Find files matching a glob pattern.',\n inputSchema: z.object({\n pattern: z.string(),\n path: z.string().optional(),\n limit: z.number().optional(),\n }),\n }),\n ls: {\n ...tool({\n description: 'List directory entries.',\n inputSchema: z.object({\n path: z.string().optional(),\n limit: z.number().optional(),\n }),\n outputSchema: z.unknown(),\n }),\n nativeName: 'ls',\n toolUseKind: 'readonly',\n } as HarnessV1BuiltinTool,\n skills: {\n ...tool({\n description: 'Execute a configured skill by name.',\n inputSchema: z.object({\n skill: z.string(),\n args: z.string().optional(),\n }),\n outputSchema: z.string(),\n }),\n nativeName: 'skills',\n toolUseKind: 'readonly',\n } as HarnessV1BuiltinTool,\n} as const satisfies Record<string, HarnessV1BuiltinTool<any, any>>;\n\nexport function createCline(\n settings: ClineHarnessSettings = {},\n): HarnessV1<typeof CLINE_BUILTIN_TOOLS> {\n return {\n specificationVersion: 'harness-v1',\n harnessId: 'cline',\n builtinTools: CLINE_BUILTIN_TOOLS,\n supportsBuiltinToolApprovals: true,\n supportsBuiltinToolFiltering: true,\n lifecycleStateSchema: clineResumeStateSchema,\n doStart: async startOpts => {\n const authentication = await resolveClineAuthentication({\n auth: settings.auth,\n providerId: settings.providerId,\n apiKey: settings.apiKey,\n });\n const lifecycleState = startOpts.continueFrom ?? startOpts.resumeFrom;\n const resumeData = lifecycleState?.data as\n | { historyFileName?: string }\n | undefined;\n\n return createClineSession({\n sessionId: startOpts.sessionId,\n sandboxSession: startOpts.sandboxSession,\n sessionWorkDir: startOpts.sessionWorkDir,\n settings: {\n authEnv: authentication.environment,\n isAuthenticationEnvironmentOverride:\n isHarnessAuthenticationEnvironment(settings.auth),\n ...(settings.mcpServers ? { mcpServers: settings.mcpServers } : {}),\n ...(settings.providerId ? { providerId: settings.providerId } : {}),\n ...((settings.apiKey ?? authentication.subscriptionApiKey)\n ? { apiKey: settings.apiKey ?? authentication.subscriptionApiKey }\n : {}),\n ...(settings.baseUrl ? { baseUrl: settings.baseUrl } : {}),\n ...(settings.headers ? { headers: settings.headers } : {}),\n ...(startOpts.headers ? { agentHeaders: startOpts.headers } : {}),\n ...(settings.reasoningEffort !== undefined\n ? { reasoningEffort: settings.reasoningEffort }\n : {}),\n ...(settings.maxIterations !== undefined\n ? { maxIterations: settings.maxIterations }\n : {}),\n },\n clientApp: CLINE_CLIENT_APP,\n isResume: lifecycleState != null,\n ...(startOpts.permissionMode\n ? { permissionMode: startOpts.permissionMode }\n : {}),\n ...(startOpts.builtinToolFiltering\n ? { builtinToolFiltering: startOpts.builtinToolFiltering }\n : {}),\n ...(resumeData?.historyFileName\n ? { resumeHistoryFileName: resumeData.historyFileName }\n : {}),\n ...(startOpts.abortSignal\n ? { abortSignal: startOpts.abortSignal }\n : {}),\n });\n },\n };\n}\n","import { createCline } from './cline-harness';\n\n/**\n * Default `cline` harness instance with no overrides — suitable for the\n * common case where the Cline SDK's defaults are fine. Equivalent to\n * `createCline()`.\n */\nexport const cline = createCline();\n\nexport { createCline } from './cline-harness';\nexport { VERSION } from './version';\nexport type { ClineHarnessSettings } from './cline-harness';\nexport type { ClineAuthenticationMode } from './cline-auth';\n"],"mappings":";;;;;;;;;;AAQA,SAAgB,gBAAgB,EAC9B,OAAO,QACP,MAAM,QAAQ,OAIW;CACzB,IAAI,mCAAmC,IAAI,GAAG;EAC5C,MAAM,cAAc,wBAAwB,EAAE,KAAK,KAAK,CAAC;EACzD,OAAO,YAAY,SACf,kBAAkB,WAAW,IAC7B,mBAAmB,EAAE,KAAK,KAAK,CAAC;CACtC;CACA,IAAI,SAAS,UACX,OAAO,mBAAmB,EAAE,IAAI,CAAC;CAGnC,MAAM,cAAc,wBAAwB,EAAE,IAAI,CAAC;CACnD,IAAI,SAAS,gBAAgB,YAAY,QACvC,OAAO,kBAAkB,WAAW;CAGtC,OAAO,mBAAmB,EAAE,IAAI,CAAC;AACnC;AAEA,SAAS,kBACP,aACwB;CACxB,OAAO;EACL,GAAI,YAAY,SAAS,EAAE,oBAAoB,YAAY,OAAO,IAAI,CAAC;EACvE,qBAAqB,YAAY;CACnC;AACF;AAEA,SAAS,mBAAmB,EAC1B,OAGyB;CACzB,OAAO;EACL,GAAI,IAAI,gBAAgB,EAAE,eAAe,IAAI,cAAc,IAAI,CAAC;EAChE,GAAI,IAAI,qBACJ,EAAE,oBAAoB,IAAI,mBAAmB,IAC7C,CAAC;CACP;AACF;;;ACnCA,eAAsB,2BAA2B,EAC/C,MACA,MAAM,QAAQ,KACd,aAAa,SACb,QACA,mBAAmB,yBAUoB;CACvC,MAAM,cAAc,gBAAgB;EAAE;EAAM;CAAI,CAAC;CACjD,IAAI,mCAAmC,IAAI,GACzC,OAAO,EAAE,YAAY;CAEvB,IACE,CAAC,gCAAgC;EAC/B;EACA,KAAK;EACL,qBACE,UAAU,QAAQ,4BAA4B;GAAE;GAAY;EAAI,CAAC;CACrE,CAAC,GAED,O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