@ai-sdk/harness-cline 1.0.20 → 1.0.21
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/CHANGELOG.md +12 -0
- package/dist/index.js +26 -14
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- package/src/cline-harness.ts +1 -2
- package/src/cline-session.ts +25 -9
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @ai-sdk/harness-cline
|
|
2
2
|
|
|
3
|
+
## 1.0.21
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 8961fde: feat(harness): allow changing `model` between turns via call options
|
|
8
|
+
- Updated dependencies [8961fde]
|
|
9
|
+
- Updated dependencies [eb59f2a]
|
|
10
|
+
- Updated dependencies [aa45741]
|
|
11
|
+
- @ai-sdk/harness@1.0.94
|
|
12
|
+
- @ai-sdk/provider@4.0.9
|
|
13
|
+
- @ai-sdk/provider-utils@5.0.34
|
|
14
|
+
|
|
3
15
|
## 1.0.20
|
|
4
16
|
|
|
5
17
|
### Patch Changes
|
package/dist/index.js
CHANGED
|
@@ -1205,7 +1205,8 @@ function toAiGatewayProviderBaseUrl(baseUrl) {
|
|
|
1205
1205
|
}
|
|
1206
1206
|
function createClineAgentModel({
|
|
1207
1207
|
settings,
|
|
1208
|
-
clientApp
|
|
1208
|
+
clientApp,
|
|
1209
|
+
modelId
|
|
1209
1210
|
}) {
|
|
1210
1211
|
const gatewayBaseUrl = settings.authEnv.AI_GATEWAY_BASE_URL;
|
|
1211
1212
|
const isAiGateway = gatewayBaseUrl != null;
|
|
@@ -1230,7 +1231,7 @@ function createClineAgentModel({
|
|
|
1230
1231
|
});
|
|
1231
1232
|
const modelSelection = {
|
|
1232
1233
|
providerId,
|
|
1233
|
-
...
|
|
1234
|
+
...modelId ? { modelId } : {}
|
|
1234
1235
|
};
|
|
1235
1236
|
const modelOptions = settings.reasoningEffort === "none" ? { reasoning: { enabled: false } } : {
|
|
1236
1237
|
reasoning: {
|
|
@@ -1290,9 +1291,11 @@ async function createClineSession(input) {
|
|
|
1290
1291
|
const mcpRuntime = await createClineMcpRuntime({
|
|
1291
1292
|
mcpServers: input.settings.mcpServers
|
|
1292
1293
|
});
|
|
1293
|
-
|
|
1294
|
+
let activeModelId = input.settings.modelId;
|
|
1295
|
+
let agentModel = createClineAgentModel({
|
|
1294
1296
|
settings: input.settings,
|
|
1295
|
-
clientApp: input.clientApp
|
|
1297
|
+
clientApp: input.clientApp,
|
|
1298
|
+
modelId: activeModelId
|
|
1296
1299
|
});
|
|
1297
1300
|
let agent;
|
|
1298
1301
|
let unsubscribe;
|
|
@@ -1359,11 +1362,11 @@ async function createClineSession(input) {
|
|
|
1359
1362
|
unsubscribe?.();
|
|
1360
1363
|
unsubscribe = void 0;
|
|
1361
1364
|
agent = new Agent({
|
|
1362
|
-
model,
|
|
1363
|
-
...
|
|
1365
|
+
model: agentModel.model,
|
|
1366
|
+
...activeModelId ? {
|
|
1364
1367
|
messageModelInfo: {
|
|
1365
|
-
id:
|
|
1366
|
-
provider: providerId
|
|
1368
|
+
id: activeModelId,
|
|
1369
|
+
provider: agentModel.providerId
|
|
1367
1370
|
}
|
|
1368
1371
|
} : {},
|
|
1369
1372
|
sessionId: input.sessionId,
|
|
@@ -1512,13 +1515,22 @@ ${rebuildInput.instructions}` : baseSystemPrompt;
|
|
|
1512
1515
|
harnessId: HARNESS_ID2
|
|
1513
1516
|
});
|
|
1514
1517
|
}
|
|
1515
|
-
if (turnOpts.responseFormat?.type === "json" && providerId === "openai-codex-cli") {
|
|
1518
|
+
if (turnOpts.responseFormat?.type === "json" && agentModel.providerId === "openai-codex-cli") {
|
|
1516
1519
|
throw new HarnessCapabilityUnsupportedError2({
|
|
1517
1520
|
message: "Harness 'cline' cannot require structured output with the openai-codex-cli provider because that provider does not expose external tools.",
|
|
1518
1521
|
harnessId: HARNESS_ID2
|
|
1519
1522
|
});
|
|
1520
1523
|
}
|
|
1524
|
+
if (turnOpts.model != null && turnOpts.model !== activeModelId) {
|
|
1525
|
+
activeModelId = turnOpts.model;
|
|
1526
|
+
agentModel = createClineAgentModel({
|
|
1527
|
+
settings: input.settings,
|
|
1528
|
+
clientApp: input.clientApp,
|
|
1529
|
+
modelId: activeModelId
|
|
1530
|
+
});
|
|
1531
|
+
}
|
|
1521
1532
|
const signature = JSON.stringify({
|
|
1533
|
+
modelId: activeModelId,
|
|
1522
1534
|
tools: userTools,
|
|
1523
1535
|
responseFormat: turnOpts.responseFormat,
|
|
1524
1536
|
instructions: turnOpts.instructions,
|
|
@@ -1546,7 +1558,7 @@ ${rebuildInput.instructions}` : baseSystemPrompt;
|
|
|
1546
1558
|
});
|
|
1547
1559
|
turnOpts.emit({
|
|
1548
1560
|
type: "stream-start",
|
|
1549
|
-
...
|
|
1561
|
+
...activeModelId ? { modelId: activeModelId } : {}
|
|
1550
1562
|
});
|
|
1551
1563
|
acceptingUserMessages = true;
|
|
1552
1564
|
const turnPromise = (async () => {
|
|
@@ -1672,13 +1684,13 @@ ${rebuildInput.instructions}` : baseSystemPrompt;
|
|
|
1672
1684
|
const sessionImpl = {
|
|
1673
1685
|
sessionId: input.sessionId,
|
|
1674
1686
|
isResume: input.isResume,
|
|
1675
|
-
...input.settings.modelId ? { modelId: input.settings.modelId } : {},
|
|
1676
1687
|
// The Cline runtime has no bridge to attach to and no in-sandbox event
|
|
1677
1688
|
// log to replay; its only cross-process resume path is restoring the
|
|
1678
1689
|
// persisted history on a fresh runtime, i.e. `rerun`.
|
|
1679
1690
|
doPromptTurn: async (promptOpts) => {
|
|
1680
1691
|
return runTurn({
|
|
1681
1692
|
text: extractUserText(promptOpts.prompt),
|
|
1693
|
+
...promptOpts.model ? { model: promptOpts.model } : {},
|
|
1682
1694
|
skills: promptOpts.skills,
|
|
1683
1695
|
tools: promptOpts.tools ?? [],
|
|
1684
1696
|
...promptOpts.instructions ? { instructions: promptOpts.instructions } : {},
|
|
@@ -1697,6 +1709,7 @@ ${rebuildInput.instructions}` : baseSystemPrompt;
|
|
|
1697
1709
|
}
|
|
1698
1710
|
return runTurn({
|
|
1699
1711
|
text: void 0,
|
|
1712
|
+
...continueOpts.model ? { model: continueOpts.model } : {},
|
|
1700
1713
|
skills: continueOpts.skills,
|
|
1701
1714
|
tools: continueOpts.tools ?? [],
|
|
1702
1715
|
...continueOpts.instructions ? { instructions: continueOpts.instructions } : {},
|
|
@@ -1781,7 +1794,7 @@ ${rebuildInput.instructions}` : baseSystemPrompt;
|
|
|
1781
1794
|
}
|
|
1782
1795
|
|
|
1783
1796
|
// src/version.ts
|
|
1784
|
-
var VERSION = true ? "1.0.
|
|
1797
|
+
var VERSION = true ? "1.0.21" : "0.0.0-test";
|
|
1785
1798
|
|
|
1786
1799
|
// src/cline-harness.ts
|
|
1787
1800
|
var CLINE_CLIENT_APP = `ai-sdk/harness-cline/${VERSION}`;
|
|
@@ -1880,7 +1893,6 @@ function createCline(settings = {}) {
|
|
|
1880
1893
|
supportsBuiltinToolFiltering: true,
|
|
1881
1894
|
lifecycleStateSchema: clineResumeStateSchema,
|
|
1882
1895
|
doStart: async (startOpts) => {
|
|
1883
|
-
const modelId = startOpts.model ?? settings.modelId;
|
|
1884
1896
|
const authEnv = resolveClineEnv({ auth: settings.auth });
|
|
1885
1897
|
const lifecycleState = startOpts.continueFrom ?? startOpts.resumeFrom;
|
|
1886
1898
|
const resumeData = lifecycleState?.data;
|
|
@@ -1893,7 +1905,7 @@ function createCline(settings = {}) {
|
|
|
1893
1905
|
isAuthenticationEnvironmentOverride: isHarnessAuthenticationEnvironment2(settings.auth),
|
|
1894
1906
|
...settings.mcpServers ? { mcpServers: settings.mcpServers } : {},
|
|
1895
1907
|
...settings.providerId ? { providerId: settings.providerId } : {},
|
|
1896
|
-
...modelId == null ? {} : { modelId },
|
|
1908
|
+
...settings.modelId == null ? {} : { modelId: settings.modelId },
|
|
1897
1909
|
...settings.apiKey ? { apiKey: settings.apiKey } : {},
|
|
1898
1910
|
...settings.baseUrl ? { baseUrl: settings.baseUrl } : {},
|
|
1899
1911
|
...settings.headers ? { headers: settings.headers } : {},
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cline-harness.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 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 { resolveClineEnv, type ClineAuthenticationMode } from './cline-auth';\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 * Model id for the configured provider. When omitted, Cline selects the\n * provider's default model.\n *\n * @deprecated Use `model` on `HarnessAgent` instead.\n */\n readonly modelId?: 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 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 modelId = startOpts.model ?? settings.modelId;\n const authEnv = resolveClineEnv({ auth: settings.auth });\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,\n isAuthenticationEnvironmentOverride:\n isHarnessAuthenticationEnvironment(settings.auth),\n ...(settings.mcpServers ? { mcpServers: settings.mcpServers } : {}),\n ...(settings.providerId ? { providerId: settings.providerId } : {}),\n ...(modelId == null ? {} : { modelId }),\n ...(settings.apiKey ? { apiKey: settings.apiKey } : {}),\n ...(settings.baseUrl ? { baseUrl: settings.baseUrl } : {}),\n ...(settings.headers ? { headers: settings.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 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 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 resolveActiveClineBuiltinNames,\n type PendingToolResult,\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 modelId?: string;\n readonly apiKey?: string;\n readonly baseUrl?: string;\n readonly headers?: 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}: {\n settings: ClineSessionSettings;\n clientApp: string;\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 'User-Agent': clientApp,\n 'x-client-app': clientApp,\n }\n : settings.headers;\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 ...(settings.modelId ? { modelId: settings.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 const { model, providerId } = createClineAgentModel({\n settings: input.settings,\n clientApp: input.clientApp,\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 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 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,\n ...(input.settings.modelId\n ? {\n messageModelInfo: {\n id: input.settings.modelId,\n provider: 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({ ops, activeNames: activeBuiltinNames }),\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 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 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 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 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 const signature = JSON.stringify({\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 ...(input.settings.modelId ? { modelId: input.settings.modelId } : {}),\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\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 ...(input.settings.modelId ? { modelId: input.settings.modelId } : {}),\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 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 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 (activeTurn != null || pendingToolResults.size > 0) {\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 || pendingToolApprovals.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 HarnessV1ToolSpec,\n} from '@ai-sdk/harness';\nimport {\n createTool,\n type AgentTool,\n type AgentToolResult,\n} from '@cline/agents';\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 '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 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 if (toolFiltering.mode === 'allow') {\n return CLINE_NATIVE_BUILTIN_NAMES.filter(name =>\n toolFiltering.toolNames.includes(name),\n );\n }\n return CLINE_NATIVE_BUILTIN_NAMES.filter(\n name => !toolFiltering.toolNames.includes(name),\n );\n}\n\nexport interface PendingToolResult {\n resolve: (value: unknown) => void;\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}: {\n ops: ClineRemoteOps;\n activeNames: ReadonlyArray<ClineNativeBuiltinName>;\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 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\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 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: 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,OAGK;AACP,SAAS,sCAAAA,2CAA0C;AACnD,SAAS,YAAY;AACrB,SAAS,KAAAC,UAAS;;;ACNlB;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,gB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;AAInC,aAAO,mBAAmB;AAAA,QACxB,WAAW,UAAU;AAAA,QACrB,gBAAgB,UAAU;AAAA,QAC1B,gBAAgB,UAAU;AAAA,QAC1B,UAAU;AAAA,UACR;AAAA,UACA,qCACEC,oCAAmC,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,GAAI,WAAW,OAAO,CAAC,IAAI,EAAE,QAAQ;AAAA,UACrC,GAAI,SAAS,SAAS,EAAE,QAAQ,SAAS,OAAO,IAAI,CAAC;AAAA,UACrD,GAAI,SAAS,UAAU,EAAE,SAAS,SAAS,QAAQ,IAAI,CAAC;AAAA,UACxD,GAAI,SAAS,UAAU,EAAE,SAAS,SAAS,QAAQ,IAAI,CAAC;AAAA,UACxD,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;;;AW/MO,IAAM,QAAQ,YAAY;","names":["isHarnessAuthenticationEnvironment","z","gatewayAuth","HarnessCapabilityUnsupportedError","createTool","tool","path","path","skill","tool","tool","HARNESS_ID","createTool","HarnessCapabilityUnsupportedError","tool","z","isHarnessAuthenticationEnvironment"]}
|
|
1
|
+
{"version":3,"sources":["../src/cline-harness.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 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 { resolveClineEnv, type ClineAuthenticationMode } from './cline-auth';\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 * Model id for the configured provider. When omitted, Cline selects the\n * provider's default model.\n *\n * @deprecated Use `model` on `HarnessAgent` instead.\n */\n readonly modelId?: 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 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 authEnv = resolveClineEnv({ auth: settings.auth });\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,\n isAuthenticationEnvironmentOverride:\n isHarnessAuthenticationEnvironment(settings.auth),\n ...(settings.mcpServers ? { mcpServers: settings.mcpServers } : {}),\n ...(settings.providerId ? { providerId: settings.providerId } : {}),\n ...(settings.modelId == null ? {} : { modelId: settings.modelId }),\n ...(settings.apiKey ? { apiKey: settings.apiKey } : {}),\n ...(settings.baseUrl ? { baseUrl: settings.baseUrl } : {}),\n ...(settings.headers ? { headers: settings.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 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 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 resolveActiveClineBuiltinNames,\n type PendingToolResult,\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 modelId?: string;\n readonly apiKey?: string;\n readonly baseUrl?: string;\n readonly headers?: 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 'User-Agent': clientApp,\n 'x-client-app': clientApp,\n }\n : settings.headers;\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 = input.settings.modelId;\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 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 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({ ops, activeNames: activeBuiltinNames }),\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 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 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\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 (activeTurn != null || pendingToolResults.size > 0) {\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 || pendingToolApprovals.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 HarnessV1ToolSpec,\n} from '@ai-sdk/harness';\nimport {\n createTool,\n type AgentTool,\n type AgentToolResult,\n} from '@cline/agents';\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 '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 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 if (toolFiltering.mode === 'allow') {\n return CLINE_NATIVE_BUILTIN_NAMES.filter(name =>\n toolFiltering.toolNames.includes(name),\n );\n }\n return CLINE_NATIVE_BUILTIN_NAMES.filter(\n name => !toolFiltering.toolNames.includes(name),\n );\n}\n\nexport interface PendingToolResult {\n resolve: (value: unknown) => void;\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}: {\n ops: ClineRemoteOps;\n activeNames: ReadonlyArray<ClineNativeBuiltinName>;\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 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\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 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: 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,OAGK;AACP,SAAS,sCAAAA,2CAA0C;AACnD,SAAS,YAAY;AACrB,SAAS,KAAAC,UAAS;;;ACNlB;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,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AsB,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;;;AW9MO,IAAM,QAAQ,YAAY;","names":["isHarnessAuthenticationEnvironment","z","gatewayAuth","HarnessCapabilityUnsupportedError","createTool","tool","path","path","skill","tool","tool","HARNESS_ID","createTool","HarnessCapabilityUnsupportedError","tool","z","isHarnessAuthenticationEnvironment"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-sdk/harness-cline",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.21",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -26,9 +26,9 @@
|
|
|
26
26
|
}
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@ai-sdk/harness": "1.0.
|
|
30
|
-
"@ai-sdk/provider": "4.0.
|
|
31
|
-
"@ai-sdk/provider-utils": "5.0.
|
|
29
|
+
"@ai-sdk/harness": "1.0.94",
|
|
30
|
+
"@ai-sdk/provider": "4.0.9",
|
|
31
|
+
"@ai-sdk/provider-utils": "5.0.34",
|
|
32
32
|
"@cline/agents": "^0.0.79",
|
|
33
33
|
"@cline/core": "^0.0.79"
|
|
34
34
|
},
|
package/src/cline-harness.ts
CHANGED
|
@@ -167,7 +167,6 @@ export function createCline(
|
|
|
167
167
|
supportsBuiltinToolFiltering: true,
|
|
168
168
|
lifecycleStateSchema: clineResumeStateSchema,
|
|
169
169
|
doStart: async startOpts => {
|
|
170
|
-
const modelId = startOpts.model ?? settings.modelId;
|
|
171
170
|
const authEnv = resolveClineEnv({ auth: settings.auth });
|
|
172
171
|
const lifecycleState = startOpts.continueFrom ?? startOpts.resumeFrom;
|
|
173
172
|
const resumeData = lifecycleState?.data as
|
|
@@ -184,7 +183,7 @@ export function createCline(
|
|
|
184
183
|
isHarnessAuthenticationEnvironment(settings.auth),
|
|
185
184
|
...(settings.mcpServers ? { mcpServers: settings.mcpServers } : {}),
|
|
186
185
|
...(settings.providerId ? { providerId: settings.providerId } : {}),
|
|
187
|
-
...(modelId == null ? {} : { modelId }),
|
|
186
|
+
...(settings.modelId == null ? {} : { modelId: settings.modelId }),
|
|
188
187
|
...(settings.apiKey ? { apiKey: settings.apiKey } : {}),
|
|
189
188
|
...(settings.baseUrl ? { baseUrl: settings.baseUrl } : {}),
|
|
190
189
|
...(settings.headers ? { headers: settings.headers } : {}),
|
package/src/cline-session.ts
CHANGED
|
@@ -176,9 +176,11 @@ function toAiGatewayProviderBaseUrl(baseUrl: string): string {
|
|
|
176
176
|
function createClineAgentModel({
|
|
177
177
|
settings,
|
|
178
178
|
clientApp,
|
|
179
|
+
modelId,
|
|
179
180
|
}: {
|
|
180
181
|
settings: ClineSessionSettings;
|
|
181
182
|
clientApp: string;
|
|
183
|
+
modelId: string | undefined;
|
|
182
184
|
}): { model: AgentModel; providerId: string } {
|
|
183
185
|
const gatewayBaseUrl = settings.authEnv.AI_GATEWAY_BASE_URL;
|
|
184
186
|
const isAiGateway = gatewayBaseUrl != null;
|
|
@@ -215,7 +217,7 @@ function createClineAgentModel({
|
|
|
215
217
|
});
|
|
216
218
|
const modelSelection = {
|
|
217
219
|
providerId,
|
|
218
|
-
...(
|
|
220
|
+
...(modelId ? { modelId } : {}),
|
|
219
221
|
};
|
|
220
222
|
const modelOptions =
|
|
221
223
|
settings.reasoningEffort === 'none'
|
|
@@ -290,9 +292,11 @@ export async function createClineSession(
|
|
|
290
292
|
const mcpRuntime = await createClineMcpRuntime({
|
|
291
293
|
mcpServers: input.settings.mcpServers,
|
|
292
294
|
});
|
|
293
|
-
|
|
295
|
+
let activeModelId = input.settings.modelId;
|
|
296
|
+
let agentModel = createClineAgentModel({
|
|
294
297
|
settings: input.settings,
|
|
295
298
|
clientApp: input.clientApp,
|
|
299
|
+
modelId: activeModelId,
|
|
296
300
|
});
|
|
297
301
|
|
|
298
302
|
// Per-session mutable state we hold across prompts.
|
|
@@ -385,12 +389,12 @@ export async function createClineSession(
|
|
|
385
389
|
unsubscribe?.();
|
|
386
390
|
unsubscribe = undefined;
|
|
387
391
|
agent = new Agent({
|
|
388
|
-
model,
|
|
389
|
-
...(
|
|
392
|
+
model: agentModel.model,
|
|
393
|
+
...(activeModelId
|
|
390
394
|
? {
|
|
391
395
|
messageModelInfo: {
|
|
392
|
-
id:
|
|
393
|
-
provider: providerId,
|
|
396
|
+
id: activeModelId,
|
|
397
|
+
provider: agentModel.providerId,
|
|
394
398
|
},
|
|
395
399
|
}
|
|
396
400
|
: {}),
|
|
@@ -559,6 +563,7 @@ export async function createClineSession(
|
|
|
559
563
|
*/
|
|
560
564
|
async function runTurn(turnOpts: {
|
|
561
565
|
text: string | undefined;
|
|
566
|
+
model?: string;
|
|
562
567
|
skills: ReadonlyArray<HarnessV1Skill>;
|
|
563
568
|
tools: ReadonlyArray<HarnessV1ToolSpec>;
|
|
564
569
|
instructions?: string;
|
|
@@ -586,7 +591,7 @@ export async function createClineSession(
|
|
|
586
591
|
}
|
|
587
592
|
if (
|
|
588
593
|
turnOpts.responseFormat?.type === 'json' &&
|
|
589
|
-
providerId === 'openai-codex-cli'
|
|
594
|
+
agentModel.providerId === 'openai-codex-cli'
|
|
590
595
|
) {
|
|
591
596
|
throw new HarnessCapabilityUnsupportedError({
|
|
592
597
|
message:
|
|
@@ -595,7 +600,17 @@ export async function createClineSession(
|
|
|
595
600
|
});
|
|
596
601
|
}
|
|
597
602
|
|
|
603
|
+
if (turnOpts.model != null && turnOpts.model !== activeModelId) {
|
|
604
|
+
activeModelId = turnOpts.model;
|
|
605
|
+
agentModel = createClineAgentModel({
|
|
606
|
+
settings: input.settings,
|
|
607
|
+
clientApp: input.clientApp,
|
|
608
|
+
modelId: activeModelId,
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
|
|
598
612
|
const signature = JSON.stringify({
|
|
613
|
+
modelId: activeModelId,
|
|
599
614
|
tools: userTools,
|
|
600
615
|
responseFormat: turnOpts.responseFormat,
|
|
601
616
|
instructions: turnOpts.instructions,
|
|
@@ -628,7 +643,7 @@ export async function createClineSession(
|
|
|
628
643
|
|
|
629
644
|
turnOpts.emit({
|
|
630
645
|
type: 'stream-start',
|
|
631
|
-
...(
|
|
646
|
+
...(activeModelId ? { modelId: activeModelId } : {}),
|
|
632
647
|
});
|
|
633
648
|
|
|
634
649
|
acceptingUserMessages = true;
|
|
@@ -793,7 +808,6 @@ export async function createClineSession(
|
|
|
793
808
|
const sessionImpl: HarnessV1Session = {
|
|
794
809
|
sessionId: input.sessionId,
|
|
795
810
|
isResume: input.isResume,
|
|
796
|
-
...(input.settings.modelId ? { modelId: input.settings.modelId } : {}),
|
|
797
811
|
|
|
798
812
|
// The Cline runtime has no bridge to attach to and no in-sandbox event
|
|
799
813
|
// log to replay; its only cross-process resume path is restoring the
|
|
@@ -804,6 +818,7 @@ export async function createClineSession(
|
|
|
804
818
|
): Promise<HarnessV1PromptControl> => {
|
|
805
819
|
return runTurn({
|
|
806
820
|
text: extractUserText(promptOpts.prompt),
|
|
821
|
+
...(promptOpts.model ? { model: promptOpts.model } : {}),
|
|
807
822
|
skills: promptOpts.skills,
|
|
808
823
|
tools: promptOpts.tools ?? [],
|
|
809
824
|
...(promptOpts.instructions
|
|
@@ -839,6 +854,7 @@ export async function createClineSession(
|
|
|
839
854
|
*/
|
|
840
855
|
return runTurn({
|
|
841
856
|
text: undefined,
|
|
857
|
+
...(continueOpts.model ? { model: continueOpts.model } : {}),
|
|
842
858
|
skills: continueOpts.skills,
|
|
843
859
|
tools: continueOpts.tools ?? [],
|
|
844
860
|
...(continueOpts.instructions
|