@ai-sdk/harness-cline 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # @ai-sdk/harness-cline
2
2
 
3
+ ## 1.0.2
4
+
5
+ ### Patch Changes
6
+
7
+ - @ai-sdk/harness@1.0.74
8
+
9
+ ## 1.0.1
10
+
11
+ ### Patch Changes
12
+
13
+ - 62a9c2a: feat(harness): add support for structured output to `HarnessAgent` via `output` property
14
+ - Updated dependencies [62a9c2a]
15
+ - Updated dependencies [d25cae2]
16
+ - @ai-sdk/harness@1.0.73
17
+
3
18
  ## 1.0.0
4
19
 
5
20
  ### Major Changes
package/dist/index.js CHANGED
@@ -118,7 +118,8 @@ import {
118
118
  } from "@ai-sdk/harness";
119
119
  import { resolveSandboxHomeDir } from "@ai-sdk/harness/utils";
120
120
  import {
121
- Agent
121
+ Agent,
122
+ createTool as createTool2
122
123
  } from "@cline/agents";
123
124
  import { Llms } from "@cline/core";
124
125
 
@@ -774,12 +775,14 @@ function buildUserAgentTools({
774
775
  function createClineTranslatorState({
775
776
  builtinToolNames,
776
777
  hostToolNames = [],
778
+ ignoredToolNames = [],
777
779
  mcpToolNames = []
778
780
  }) {
779
781
  return {
780
782
  builtinToolNames: new Set(builtinToolNames),
781
783
  dynamicToolCallIds: /* @__PURE__ */ new Set(),
782
784
  hostToolNames: new Set(hostToolNames),
785
+ ignoredToolNames: new Set(ignoredToolNames),
783
786
  mcpToolNames: new Set(mcpToolNames),
784
787
  emittedToolCalls: /* @__PURE__ */ new Set(),
785
788
  blockCounter: 0
@@ -883,6 +886,7 @@ function translateClineEvent(event, state) {
883
886
  return [pendingFinishStep];
884
887
  }
885
888
  case "tool-started": {
889
+ if (state.ignoredToolNames.has(event.toolCall.toolName)) return [];
886
890
  if (state.emittedToolCalls.has(event.toolCall.toolCallId)) {
887
891
  return [];
888
892
  }
@@ -890,6 +894,7 @@ function translateClineEvent(event, state) {
890
894
  return [toolCallPart(state, event.toolCall)];
891
895
  }
892
896
  case "tool-finished": {
897
+ if (state.ignoredToolNames.has(event.toolCall.toolName)) return [];
893
898
  const resultPart = event.message.content.find(
894
899
  (part) => part.type === "tool-result" && part.toolCallId === event.toolCall.toolCallId
895
900
  );
@@ -1158,8 +1163,25 @@ ${rebuildInput.instructions}` : baseSystemPrompt,
1158
1163
  ...buildUserAgentTools({
1159
1164
  specs: rebuildInput.userTools,
1160
1165
  pendingToolResults
1161
- })
1166
+ }),
1167
+ ...rebuildInput.responseFormat?.type === "json" && rebuildInput.responseFormat.schema != null ? [
1168
+ createTool2({
1169
+ name: "structured_output",
1170
+ description: rebuildInput.responseFormat.description ?? "Return the final structured output.",
1171
+ inputSchema: {
1172
+ type: "object",
1173
+ properties: {
1174
+ output: rebuildInput.responseFormat.schema
1175
+ },
1176
+ required: ["output"],
1177
+ additionalProperties: false
1178
+ },
1179
+ lifecycle: { completesRun: true },
1180
+ execute: async ({ output }) => JSON.stringify(output)
1181
+ })
1182
+ ] : []
1162
1183
  ],
1184
+ ...rebuildInput.responseFormat?.type === "json" ? { completionPolicy: { requireCompletionTool: true } } : {},
1163
1185
  hooks: {
1164
1186
  afterTool: ({ result }) => {
1165
1187
  const toolResult = unwrapClineToolResult(result.output);
@@ -1251,11 +1273,27 @@ ${rebuildInput.instructions}` : baseSystemPrompt,
1251
1273
  throw new Error("Cline session has been stopped.");
1252
1274
  }
1253
1275
  const userTools = turnOpts.tools;
1254
- const signature = JSON.stringify(userTools.map((t) => t.name).sort());
1276
+ if (turnOpts.responseFormat?.type === "json" && turnOpts.responseFormat.schema == null) {
1277
+ throw new HarnessCapabilityUnsupportedError2({
1278
+ message: "Harness 'cline' requires a JSON schema for structured output.",
1279
+ harnessId: HARNESS_ID2
1280
+ });
1281
+ }
1282
+ if (turnOpts.responseFormat?.type === "json" && providerId === "openai-codex-cli") {
1283
+ throw new HarnessCapabilityUnsupportedError2({
1284
+ message: "Harness 'cline' cannot require structured output with the openai-codex-cli provider because that provider does not expose external tools.",
1285
+ harnessId: HARNESS_ID2
1286
+ });
1287
+ }
1288
+ const signature = JSON.stringify({
1289
+ tools: userTools.map((t) => t.name).sort(),
1290
+ responseFormat: turnOpts.responseFormat
1291
+ });
1255
1292
  if (agent == null || signature !== lastToolsSignature) {
1256
1293
  currentMessages = agent?.snapshot().messages ?? currentMessages;
1257
1294
  rebuildAgent({
1258
1295
  userTools,
1296
+ responseFormat: turnOpts.responseFormat,
1259
1297
  ...turnOpts.instructions ? { instructions: turnOpts.instructions } : {}
1260
1298
  });
1261
1299
  lastToolsSignature = signature;
@@ -1264,6 +1302,7 @@ ${rebuildInput.instructions}` : baseSystemPrompt,
1264
1302
  translatorState = createClineTranslatorState({
1265
1303
  builtinToolNames: activeBuiltinNames,
1266
1304
  hostToolNames: userTools.map((tool2) => tool2.name),
1305
+ ignoredToolNames: turnOpts.responseFormat?.type === "json" ? ["structured_output"] : [],
1267
1306
  mcpToolNames: mcpRuntime.toolNames
1268
1307
  });
1269
1308
  turnOpts.emit({
@@ -1287,6 +1326,33 @@ ${rebuildInput.instructions}` : baseSystemPrompt,
1287
1326
  currentEmit?.(part);
1288
1327
  }
1289
1328
  }
1329
+ if (turnOpts.responseFormat?.type === "json" && result.status === "completed") {
1330
+ const id = `structured-output-${input.sessionId}`;
1331
+ currentEmit?.({ type: "text-start", id });
1332
+ currentEmit?.({
1333
+ type: "text-delta",
1334
+ id,
1335
+ delta: result.outputText
1336
+ });
1337
+ currentEmit?.({ type: "text-end", id });
1338
+ currentEmit?.({
1339
+ type: "finish-step",
1340
+ finishReason: { unified: "stop", raw: "structured-output" },
1341
+ usage: {
1342
+ inputTokens: {
1343
+ total: 0,
1344
+ noCache: void 0,
1345
+ cacheRead: void 0,
1346
+ cacheWrite: void 0
1347
+ },
1348
+ outputTokens: {
1349
+ total: 0,
1350
+ text: void 0,
1351
+ reasoning: void 0
1352
+ }
1353
+ }
1354
+ });
1355
+ }
1290
1356
  if (result.status === "aborted") {
1291
1357
  if (suspending) return;
1292
1358
  currentEmit?.({
@@ -1365,7 +1431,8 @@ ${rebuildInput.instructions}` : baseSystemPrompt,
1365
1431
  tools: promptOpts.tools ?? [],
1366
1432
  ...promptOpts.instructions ? { instructions: promptOpts.instructions } : {},
1367
1433
  emit: promptOpts.emit,
1368
- ...promptOpts.abortSignal ? { abortSignal: promptOpts.abortSignal } : {}
1434
+ ...promptOpts.abortSignal ? { abortSignal: promptOpts.abortSignal } : {},
1435
+ responseFormat: promptOpts.responseFormat
1369
1436
  });
1370
1437
  },
1371
1438
  doContinueTurn: async (continueOpts) => {
@@ -1381,7 +1448,8 @@ ${rebuildInput.instructions}` : baseSystemPrompt,
1381
1448
  tools: continueOpts.tools ?? [],
1382
1449
  ...continueOpts.instructions ? { instructions: continueOpts.instructions } : {},
1383
1450
  emit: continueOpts.emit,
1384
- ...continueOpts.abortSignal ? { abortSignal: continueOpts.abortSignal } : {}
1451
+ ...continueOpts.abortSignal ? { abortSignal: continueOpts.abortSignal } : {},
1452
+ responseFormat: continueOpts.responseFormat
1385
1453
  });
1386
1454
  },
1387
1455
  doCompact: async () => {
@@ -1460,7 +1528,7 @@ ${rebuildInput.instructions}` : baseSystemPrompt,
1460
1528
  }
1461
1529
 
1462
1530
  // src/version.ts
1463
- var VERSION = true ? "1.0.0" : "0.0.0-test";
1531
+ var VERSION = true ? "1.0.2" : "0.0.0-test";
1464
1532
 
1465
1533
  // src/cline-harness.ts
1466
1534
  var CLINE_CLIENT_APP = `ai-sdk/harness-cline/${VERSION}`;
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 { tool } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { resolveClineEnv, type ClineAuthOptions } 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?: ClineAuthOptions;\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 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 */\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} 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 skills: startOpts.skills ?? [],\n settings: {\n authEnv,\n ...(settings.mcpServers ? { mcpServers: settings.mcpServers } : {}),\n ...(settings.providerId ? { providerId: settings.providerId } : {}),\n ...(settings.modelId ? { 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 { getAiGatewayAuthFromEnv } from '@ai-sdk/harness/utils';\n\nexport type ClineAuthenticationMode = 'auto' | 'direct' | 'ai-gateway';\n\nexport type ClineAuthOptions = ClineAuthenticationMode;\n\nexport function resolveClineEnv({\n auth = 'auto',\n env = process.env,\n}: {\n auth?: ClineAuthOptions;\n env?: Record<string, string | undefined>;\n}): Record<string, string> {\n if (auth === 'direct') {\n return pickDirectClineEnv({ env });\n }\n\n const gatewayAuth = getAiGatewayAuthFromEnv({ env });\n if (auth === 'ai-gateway' || gatewayAuth.apiKey) {\n return {\n ...(gatewayAuth.apiKey ? { AI_GATEWAY_API_KEY: gatewayAuth.apiKey } : {}),\n AI_GATEWAY_BASE_URL: gatewayAuth.baseUrl,\n };\n }\n\n return pickDirectClineEnv({ env });\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 { resolveSandboxHomeDir } from '@ai-sdk/harness/utils';\nimport {\n Agent,\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 { renderSkillsPromptSection, writeClineSkills } 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 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;\n readonly sessionWorkDir: string;\n readonly skills: ReadonlyArray<HarnessV1Skill>;\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\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 skillsSection?: string;\n}): string {\n const sections = [\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 ];\n if (input.skillsSection) {\n sections.push(input.skillsSection);\n }\n return sections.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 ? { apiKeyEnv: [] } : {}),\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 sandbox = input.sandboxSession.restricted();\n const sandboxHomeDir = await resolveSandboxHomeDir({\n sandbox,\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,\n workDir: input.sessionWorkDir,\n });\n\n // Materialize harness-provided skills into sandbox HOME (not the workspace)\n // and advertise them via a system prompt section.\n let skillsSection: string | undefined;\n if (input.skills.length > 0) {\n const skillRootDir = await writeClineSkills({\n sandbox,\n sandboxHomeDir,\n skills: input.skills,\n ...(input.abortSignal ? { abortSignal: input.abortSignal } : {}),\n });\n if (skillRootDir) {\n skillsSection = renderSkillsPromptSection(input.skills, skillRootDir);\n }\n }\n\n const baseSystemPrompt = buildSystemPrompt({\n sessionWorkDir: input.sessionWorkDir,\n sandboxDescription: sandbox.description,\n ...(skillsSection ? { skillsSection } : {}),\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,\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 lastToolsSignature: 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: string[] = [];\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 async function persistHistory(): Promise<void> {\n const messages = agent?.snapshot().messages ?? currentMessages;\n await persistHistoryToSandbox({\n sandbox,\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 instructions?: string;\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: rebuildInput.instructions\n ? `${baseSystemPrompt}\\n\\n${rebuildInput.instructions}`\n : baseSystemPrompt,\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 ...mcpRuntime.tools,\n ...buildUserAgentTools({\n specs: rebuildInput.userTools,\n pendingToolResults,\n }),\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: () => pendingUserMessages.shift(),\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 async submitUserMessage(text) {\n pendingUserMessages.push(text);\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 function runTurn(turnOpts: {\n text: string | undefined;\n tools: ReadonlyArray<HarnessV1ToolSpec>;\n instructions?: string;\n emit: (part: HarnessV1StreamPart) => void;\n abortSignal?: AbortSignal;\n }): HarnessV1PromptControl {\n if (stopped) {\n throw new Error('Cline session has been stopped.');\n }\n\n const userTools = turnOpts.tools;\n const signature = JSON.stringify(userTools.map(t => t.name).sort());\n if (agent == null || signature !== lastToolsSignature) {\n currentMessages = agent?.snapshot().messages ?? currentMessages;\n rebuildAgent({\n userTools,\n ...(turnOpts.instructions\n ? { instructions: turnOpts.instructions }\n : {}),\n });\n lastToolsSignature = signature;\n }\n\n currentEmit = turnOpts.emit;\n translatorState = createClineTranslatorState({\n builtinToolNames: activeBuiltinNames,\n hostToolNames: userTools.map(tool => tool.name),\n mcpToolNames: mcpRuntime.toolNames,\n });\n\n turnOpts.emit({\n type: 'stream-start',\n ...(input.settings.modelId ? { modelId: input.settings.modelId } : {}),\n });\n\n const turnPromise = (async () => {\n const runtime = agent!;\n let result: AgentRunResult;\n try {\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 turnOpts.text === undefined\n ? await runtime.continue()\n : agentHasRun\n ? await runtime.continue(turnOpts.text)\n : await runtime.run(turnOpts.text);\n agentHasRun = true;\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 return;\n }\n\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 === '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 })();\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 tools: promptOpts.tools ?? [],\n ...(promptOpts.instructions\n ? { instructions: promptOpts.instructions }\n : {}),\n emit: promptOpts.emit,\n ...(promptOpts.abortSignal\n ? { abortSignal: promptOpts.abortSignal }\n : {}),\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 tools: continueOpts.tools ?? [],\n ...(continueOpts.instructions\n ? { instructions: continueOpts.instructions }\n : {}),\n emit: continueOpts.emit,\n ...(continueOpts.abortSignal\n ? { abortSignal: continueOpts.abortSignal }\n : {}),\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\n const resolvePath = (inputPath: string): string => {\n const normalized = path.posix.isAbsolute(inputPath)\n ? path.posix.normalize(inputPath)\n : path.posix.normalize(path.posix.join(workDir, inputPath));\n return normalized;\n };\n\n const runShell = async (\n command: string,\n input?: { 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: workDir,\n ...(input?.signal ? { abortSignal: input.signal } : {}),\n });\n return {\n exitCode: result.exitCode,\n output: `${result.stdout}${result.stderr}`,\n };\n };\n\n const readFile = async (inputPath: string): Promise<string> => {\n const resolved = resolvePath(inputPath);\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 resolved = resolvePath(inputPath);\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 current = await readFile(inputPath);\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(command, { signal: controller.signal });\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 target = resolvePath(input.path ?? '.');\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 [\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 target = resolvePath(inputPath);\n const result = await runShell(\n [\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 target = resolvePath(inputPath);\n const result = await runShell(\n [\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 { writeSkills } from '@ai-sdk/harness/utils';\nimport type { Experimental_SandboxSession } from '@ai-sdk/provider-utils';\n\n/**\n * Materialize harness-provided skills into the sandbox HOME\n * (`~/.agents/skills/<name>/SKILL.md` plus any auxiliary files) and return\n * the root directory they were written to. The Cline runtime has no native\n * skill loader, so the session surfaces them to the model through a system\n * prompt section (see `renderSkillsPromptSection`) that points at these files.\n */\nexport async function writeClineSkills({\n sandbox,\n sandboxHomeDir,\n skills,\n abortSignal,\n}: {\n sandbox: Experimental_SandboxSession;\n sandboxHomeDir: string;\n skills: ReadonlyArray<HarnessV1Skill>;\n abortSignal?: AbortSignal;\n}): Promise<string | undefined> {\n if (skills.length === 0) return undefined;\n const skillRootDir = path.posix.join(sandboxHomeDir, '.agents', 'skills');\n await writeSkills({\n sandbox,\n rootDir: skillRootDir,\n skills,\n ...(abortSignal ? { abortSignal } : {}),\n });\n return skillRootDir;\n}\n\n/**\n * Render the system-prompt section that advertises available skills. Only the\n * name + description sit in context; the model loads the full skill via the\n * `read` tool when the task calls for it (progressive disclosure).\n */\nexport function renderSkillsPromptSection(\n skills: ReadonlyArray<HarnessV1Skill>,\n skillRootDir: string,\n): string {\n const entries = skills\n .map(\n skill =>\n `- ${skill.name}: ${skill.description}\\n SKILL.md: ${path.posix.join(\n skillRootDir,\n skill.name,\n 'SKILL.md',\n )}`,\n )\n .join('\\n');\n return (\n '## Skills\\n\\n' +\n 'The following skills are available. When a task matches a skill, read its SKILL.md with the `read` tool and follow its instructions.\\n\\n' +\n entries\n );\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] 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};\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 built-in `AgentTool`s handed to the Cline runtime.\n * These schemas mirror the zod declarations in `CLINE_BUILTIN_TOOLS`\n * (cline-harness.ts) — keep the two in sync.\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 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 mcpToolNames = [],\n}: {\n builtinToolNames: Iterable<string>;\n hostToolNames?: 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 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.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 // 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, ClineAuthOptions } from './cline-auth';\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAGK;AACP,SAAS,YAAY;AACrB,SAAS,KAAAA,UAAS;;;ACNlB,SAAS,+BAA+B;AAMjC,SAAS,gBAAgB;AAAA,EAC9B,OAAO;AAAA,EACP,MAAM,QAAQ;AAChB,GAG2B;AACzB,MAAI,SAAS,UAAU;AACrB,WAAO,mBAAmB,EAAE,IAAI,CAAC;AAAA,EACnC;AAEA,QAAM,cAAc,wBAAwB,EAAE,IAAI,CAAC;AACnD,MAAI,SAAS,gBAAgB,YAAY,QAAQ;AAC/C,WAAO;AAAA,MACL,GAAI,YAAY,SAAS,EAAE,oBAAoB,YAAY,OAAO,IAAI,CAAC;AAAA,MACvE,qBAAqB,YAAY;AAAA,IACnC;AAAA,EACF;AAEA,SAAO,mBAAmB,EAAE,IAAI,CAAC;AACnC;AAEA,SAAS,mBAAmB;AAAA,EAC1B;AACF,GAE2B;AACzB,SAAO;AAAA,IACL,GAAI,IAA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AAgB;AAInC,aAAO,mBAAmB;AAAA,QACxB,WAAW,UAAU;AAAA,QACrB,gBAAgB,UAAU;AAAA,QAC1B,gBAAgB,UAAU;AAAA,QAC1B,QAAQ,UAAU,UAAU,CAAC;AAAA,QAC7B,UAAU;AAAA,UACR;AAAA,UACA,GAAI,SAAS,aAAa,EAAE,YAAY,SAAS,WAAW,IAAI,CAAC;AAAA,UACjE,GAAI,SAAS,aAAa,EAAE,YAAY,SAAS,WAAW,IAAI,CAAC;AAAA,UACjE,GAAI,SAAS,UAAU,EAAE,SAAS,SAAS,QAAQ,IAAI,CAAC;AAAA,UACxD,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;;;AW7LO,IAAM,QAAQ,YAAY;","names":["z","HarnessCapabilityUnsupportedError","tool","path","path","tool","HARNESS_ID","tool","HarnessCapabilityUnsupportedError","z"]}
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 { tool } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { resolveClineEnv, type ClineAuthOptions } 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?: ClineAuthOptions;\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 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 */\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} 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 skills: startOpts.skills ?? [],\n settings: {\n authEnv,\n ...(settings.mcpServers ? { mcpServers: settings.mcpServers } : {}),\n ...(settings.providerId ? { providerId: settings.providerId } : {}),\n ...(settings.modelId ? { 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 { getAiGatewayAuthFromEnv } from '@ai-sdk/harness/utils';\n\nexport type ClineAuthenticationMode = 'auto' | 'direct' | 'ai-gateway';\n\nexport type ClineAuthOptions = ClineAuthenticationMode;\n\nexport function resolveClineEnv({\n auth = 'auto',\n env = process.env,\n}: {\n auth?: ClineAuthOptions;\n env?: Record<string, string | undefined>;\n}): Record<string, string> {\n if (auth === 'direct') {\n return pickDirectClineEnv({ env });\n }\n\n const gatewayAuth = getAiGatewayAuthFromEnv({ env });\n if (auth === 'ai-gateway' || gatewayAuth.apiKey) {\n return {\n ...(gatewayAuth.apiKey ? { AI_GATEWAY_API_KEY: gatewayAuth.apiKey } : {}),\n AI_GATEWAY_BASE_URL: gatewayAuth.baseUrl,\n };\n }\n\n return pickDirectClineEnv({ env });\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 { resolveSandboxHomeDir } from '@ai-sdk/harness/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 { renderSkillsPromptSection, writeClineSkills } 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 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;\n readonly sessionWorkDir: string;\n readonly skills: ReadonlyArray<HarnessV1Skill>;\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\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 skillsSection?: string;\n}): string {\n const sections = [\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 ];\n if (input.skillsSection) {\n sections.push(input.skillsSection);\n }\n return sections.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 ? { apiKeyEnv: [] } : {}),\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 sandbox = input.sandboxSession.restricted();\n const sandboxHomeDir = await resolveSandboxHomeDir({\n sandbox,\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,\n workDir: input.sessionWorkDir,\n });\n\n // Materialize harness-provided skills into sandbox HOME (not the workspace)\n // and advertise them via a system prompt section.\n let skillsSection: string | undefined;\n if (input.skills.length > 0) {\n const skillRootDir = await writeClineSkills({\n sandbox,\n sandboxHomeDir,\n skills: input.skills,\n ...(input.abortSignal ? { abortSignal: input.abortSignal } : {}),\n });\n if (skillRootDir) {\n skillsSection = renderSkillsPromptSection(input.skills, skillRootDir);\n }\n }\n\n const baseSystemPrompt = buildSystemPrompt({\n sessionWorkDir: input.sessionWorkDir,\n sandboxDescription: sandbox.description,\n ...(skillsSection ? { skillsSection } : {}),\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,\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 lastToolsSignature: 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: string[] = [];\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 async function persistHistory(): Promise<void> {\n const messages = agent?.snapshot().messages ?? currentMessages;\n await persistHistoryToSandbox({\n sandbox,\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 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: rebuildInput.instructions\n ? `${baseSystemPrompt}\\n\\n${rebuildInput.instructions}`\n : baseSystemPrompt,\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 ...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: () => pendingUserMessages.shift(),\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 async submitUserMessage(text) {\n pendingUserMessages.push(text);\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 function runTurn(turnOpts: {\n text: string | undefined;\n tools: ReadonlyArray<HarnessV1ToolSpec>;\n instructions?: string;\n emit: (part: HarnessV1StreamPart) => void;\n abortSignal?: AbortSignal;\n responseFormat?: HarnessV1PromptTurnOptions['responseFormat'];\n }): HarnessV1PromptControl {\n if (stopped) {\n throw new Error('Cline session has been stopped.');\n }\n\n const userTools = turnOpts.tools;\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.map(t => t.name).sort(),\n responseFormat: turnOpts.responseFormat,\n });\n if (agent == null || signature !== lastToolsSignature) {\n currentMessages = agent?.snapshot().messages ?? currentMessages;\n rebuildAgent({\n userTools,\n responseFormat: turnOpts.responseFormat,\n ...(turnOpts.instructions\n ? { instructions: turnOpts.instructions }\n : {}),\n });\n lastToolsSignature = signature;\n }\n\n currentEmit = turnOpts.emit;\n translatorState = createClineTranslatorState({\n builtinToolNames: activeBuiltinNames,\n hostToolNames: userTools.map(tool => tool.name),\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 const turnPromise = (async () => {\n const runtime = agent!;\n let result: AgentRunResult;\n try {\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 turnOpts.text === undefined\n ? await runtime.continue()\n : agentHasRun\n ? await runtime.continue(turnOpts.text)\n : await runtime.run(turnOpts.text);\n agentHasRun = true;\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 return;\n }\n\n currentMessages = result.messages;\n\n if (translatorState) {\n for (const part of finishClineTranslation(translatorState)) {\n currentEmit?.(part);\n }\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 })();\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 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 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\n const resolvePath = (inputPath: string): string => {\n const normalized = path.posix.isAbsolute(inputPath)\n ? path.posix.normalize(inputPath)\n : path.posix.normalize(path.posix.join(workDir, inputPath));\n return normalized;\n };\n\n const runShell = async (\n command: string,\n input?: { 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: workDir,\n ...(input?.signal ? { abortSignal: input.signal } : {}),\n });\n return {\n exitCode: result.exitCode,\n output: `${result.stdout}${result.stderr}`,\n };\n };\n\n const readFile = async (inputPath: string): Promise<string> => {\n const resolved = resolvePath(inputPath);\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 resolved = resolvePath(inputPath);\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 current = await readFile(inputPath);\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(command, { signal: controller.signal });\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 target = resolvePath(input.path ?? '.');\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 [\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 target = resolvePath(inputPath);\n const result = await runShell(\n [\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 target = resolvePath(inputPath);\n const result = await runShell(\n [\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 { writeSkills } from '@ai-sdk/harness/utils';\nimport type { Experimental_SandboxSession } from '@ai-sdk/provider-utils';\n\n/**\n * Materialize harness-provided skills into the sandbox HOME\n * (`~/.agents/skills/<name>/SKILL.md` plus any auxiliary files) and return\n * the root directory they were written to. The Cline runtime has no native\n * skill loader, so the session surfaces them to the model through a system\n * prompt section (see `renderSkillsPromptSection`) that points at these files.\n */\nexport async function writeClineSkills({\n sandbox,\n sandboxHomeDir,\n skills,\n abortSignal,\n}: {\n sandbox: Experimental_SandboxSession;\n sandboxHomeDir: string;\n skills: ReadonlyArray<HarnessV1Skill>;\n abortSignal?: AbortSignal;\n}): Promise<string | undefined> {\n if (skills.length === 0) return undefined;\n const skillRootDir = path.posix.join(sandboxHomeDir, '.agents', 'skills');\n await writeSkills({\n sandbox,\n rootDir: skillRootDir,\n skills,\n ...(abortSignal ? { abortSignal } : {}),\n });\n return skillRootDir;\n}\n\n/**\n * Render the system-prompt section that advertises available skills. Only the\n * name + description sit in context; the model loads the full skill via the\n * `read` tool when the task calls for it (progressive disclosure).\n */\nexport function renderSkillsPromptSection(\n skills: ReadonlyArray<HarnessV1Skill>,\n skillRootDir: string,\n): string {\n const entries = skills\n .map(\n skill =>\n `- ${skill.name}: ${skill.description}\\n SKILL.md: ${path.posix.join(\n skillRootDir,\n skill.name,\n 'SKILL.md',\n )}`,\n )\n .join('\\n');\n return (\n '## Skills\\n\\n' +\n 'The following skills are available. When a task matches a skill, read its SKILL.md with the `read` tool and follow its instructions.\\n\\n' +\n entries\n );\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] 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};\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 built-in `AgentTool`s handed to the Cline runtime.\n * These schemas mirror the zod declarations in `CLINE_BUILTIN_TOOLS`\n * (cline-harness.ts) — keep the two in sync.\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, ClineAuthOptions } from './cline-auth';\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAGK;AACP,SAAS,YAAY;AACrB,SAAS,KAAAA,UAAS;;;ACNlB,SAAS,+BAA+B;AAMjC,SAAS,gBAAgB;AAAA,EAC9B,OAAO;AAAA,EACP,MAAM,QAAQ;AAChB,GAG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WAAW,IAAI,CAAC;AAAA,UACjE,GAAI,SAAS,aAAa,EAAE,YAAY,SAAS,WAAW,IAAI,CAAC;AAAA,UACjE,GAAI,SAAS,UAAU,EAAE,SAAS,SAAS,QAAQ,IAAI,CAAC;AAAA,UACxD,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;;;AW7LO,IAAM,QAAQ,YAAY;","names":["z","HarnessCapabilityUnsupportedError","createTool","tool","path","path","tool","HARNESS_ID","createTool","HarnessCapabilityUnsupportedError","tool","z"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/harness-cline",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "sideEffects": false,
@@ -28,7 +28,7 @@
28
28
  "dependencies": {
29
29
  "@cline/agents": "^0.0.72",
30
30
  "@cline/core": "^0.0.72",
31
- "@ai-sdk/harness": "1.0.72",
31
+ "@ai-sdk/harness": "1.0.74",
32
32
  "@ai-sdk/provider": "4.0.7",
33
33
  "@ai-sdk/provider-utils": "5.0.27"
34
34
  },
@@ -16,6 +16,7 @@ import {
16
16
  import { resolveSandboxHomeDir } from '@ai-sdk/harness/utils';
17
17
  import {
18
18
  Agent,
19
+ createTool,
19
20
  type AgentMessage,
20
21
  type AgentModel,
21
22
  type AgentRunResult,
@@ -372,6 +373,7 @@ export async function createClineSession(
372
373
  function rebuildAgent(rebuildInput: {
373
374
  userTools: ReadonlyArray<HarnessV1ToolSpec>;
374
375
  instructions?: string;
376
+ responseFormat?: HarnessV1PromptTurnOptions['responseFormat'];
375
377
  }): void {
376
378
  unsubscribe?.();
377
379
  unsubscribe = undefined;
@@ -401,7 +403,32 @@ export async function createClineSession(
401
403
  specs: rebuildInput.userTools,
402
404
  pendingToolResults,
403
405
  }),
406
+ ...(rebuildInput.responseFormat?.type === 'json' &&
407
+ rebuildInput.responseFormat.schema != null
408
+ ? [
409
+ createTool({
410
+ name: 'structured_output',
411
+ description:
412
+ rebuildInput.responseFormat.description ??
413
+ 'Return the final structured output.',
414
+ inputSchema: {
415
+ type: 'object',
416
+ properties: {
417
+ output: rebuildInput.responseFormat.schema,
418
+ },
419
+ required: ['output'],
420
+ additionalProperties: false,
421
+ },
422
+ lifecycle: { completesRun: true },
423
+ execute: async ({ output }: { output: unknown }) =>
424
+ JSON.stringify(output),
425
+ }),
426
+ ]
427
+ : []),
404
428
  ],
429
+ ...(rebuildInput.responseFormat?.type === 'json'
430
+ ? { completionPolicy: { requireCompletionTool: true } }
431
+ : {}),
405
432
  hooks: {
406
433
  afterTool: ({ result }) => {
407
434
  const toolResult = unwrapClineToolResult(result.output);
@@ -512,17 +539,43 @@ export async function createClineSession(
512
539
  instructions?: string;
513
540
  emit: (part: HarnessV1StreamPart) => void;
514
541
  abortSignal?: AbortSignal;
542
+ responseFormat?: HarnessV1PromptTurnOptions['responseFormat'];
515
543
  }): HarnessV1PromptControl {
516
544
  if (stopped) {
517
545
  throw new Error('Cline session has been stopped.');
518
546
  }
519
547
 
520
548
  const userTools = turnOpts.tools;
521
- const signature = JSON.stringify(userTools.map(t => t.name).sort());
549
+ if (
550
+ turnOpts.responseFormat?.type === 'json' &&
551
+ turnOpts.responseFormat.schema == null
552
+ ) {
553
+ throw new HarnessCapabilityUnsupportedError({
554
+ message:
555
+ "Harness 'cline' requires a JSON schema for structured output.",
556
+ harnessId: HARNESS_ID,
557
+ });
558
+ }
559
+ if (
560
+ turnOpts.responseFormat?.type === 'json' &&
561
+ providerId === 'openai-codex-cli'
562
+ ) {
563
+ throw new HarnessCapabilityUnsupportedError({
564
+ message:
565
+ "Harness 'cline' cannot require structured output with the openai-codex-cli provider because that provider does not expose external tools.",
566
+ harnessId: HARNESS_ID,
567
+ });
568
+ }
569
+
570
+ const signature = JSON.stringify({
571
+ tools: userTools.map(t => t.name).sort(),
572
+ responseFormat: turnOpts.responseFormat,
573
+ });
522
574
  if (agent == null || signature !== lastToolsSignature) {
523
575
  currentMessages = agent?.snapshot().messages ?? currentMessages;
524
576
  rebuildAgent({
525
577
  userTools,
578
+ responseFormat: turnOpts.responseFormat,
526
579
  ...(turnOpts.instructions
527
580
  ? { instructions: turnOpts.instructions }
528
581
  : {}),
@@ -534,6 +587,8 @@ export async function createClineSession(
534
587
  translatorState = createClineTranslatorState({
535
588
  builtinToolNames: activeBuiltinNames,
536
589
  hostToolNames: userTools.map(tool => tool.name),
590
+ ignoredToolNames:
591
+ turnOpts.responseFormat?.type === 'json' ? ['structured_output'] : [],
537
592
  mcpToolNames: mcpRuntime.toolNames,
538
593
  });
539
594
 
@@ -573,6 +628,37 @@ export async function createClineSession(
573
628
  }
574
629
  }
575
630
 
631
+ if (
632
+ turnOpts.responseFormat?.type === 'json' &&
633
+ result.status === 'completed'
634
+ ) {
635
+ const id = `structured-output-${input.sessionId}`;
636
+ currentEmit?.({ type: 'text-start', id });
637
+ currentEmit?.({
638
+ type: 'text-delta',
639
+ id,
640
+ delta: result.outputText,
641
+ });
642
+ currentEmit?.({ type: 'text-end', id });
643
+ currentEmit?.({
644
+ type: 'finish-step',
645
+ finishReason: { unified: 'stop', raw: 'structured-output' },
646
+ usage: {
647
+ inputTokens: {
648
+ total: 0,
649
+ noCache: undefined,
650
+ cacheRead: undefined,
651
+ cacheWrite: undefined,
652
+ },
653
+ outputTokens: {
654
+ total: 0,
655
+ text: undefined,
656
+ reasoning: undefined,
657
+ },
658
+ },
659
+ });
660
+ }
661
+
576
662
  if (result.status === 'aborted') {
577
663
  /*
578
664
  * A `doSuspendTurn` aborts the in-flight turn on purpose — settle
@@ -680,6 +766,7 @@ export async function createClineSession(
680
766
  ...(promptOpts.abortSignal
681
767
  ? { abortSignal: promptOpts.abortSignal }
682
768
  : {}),
769
+ responseFormat: promptOpts.responseFormat,
683
770
  });
684
771
  },
685
772
 
@@ -713,6 +800,7 @@ export async function createClineSession(
713
800
  ...(continueOpts.abortSignal
714
801
  ? { abortSignal: continueOpts.abortSignal }
715
802
  : {}),
803
+ responseFormat: continueOpts.responseFormat,
716
804
  });
717
805
  },
718
806
 
@@ -24,6 +24,7 @@ export interface ClineTranslatorState {
24
24
  readonly builtinToolNames: ReadonlySet<string>;
25
25
  readonly dynamicToolCallIds: Set<string>;
26
26
  readonly hostToolNames: ReadonlySet<string>;
27
+ readonly ignoredToolNames: ReadonlySet<string>;
27
28
  readonly mcpToolNames: ReadonlySet<string>;
28
29
  openTextBlockId?: string;
29
30
  openReasoningBlockId?: string;
@@ -35,16 +36,19 @@ export interface ClineTranslatorState {
35
36
  export function createClineTranslatorState({
36
37
  builtinToolNames,
37
38
  hostToolNames = [],
39
+ ignoredToolNames = [],
38
40
  mcpToolNames = [],
39
41
  }: {
40
42
  builtinToolNames: Iterable<string>;
41
43
  hostToolNames?: Iterable<string>;
44
+ ignoredToolNames?: Iterable<string>;
42
45
  mcpToolNames?: Iterable<string>;
43
46
  }): ClineTranslatorState {
44
47
  return {
45
48
  builtinToolNames: new Set(builtinToolNames),
46
49
  dynamicToolCallIds: new Set(),
47
50
  hostToolNames: new Set(hostToolNames),
51
+ ignoredToolNames: new Set(ignoredToolNames),
48
52
  mcpToolNames: new Set(mcpToolNames),
49
53
  emittedToolCalls: new Set(),
50
54
  blockCounter: 0,
@@ -181,6 +185,7 @@ export function translateClineEvent(
181
185
  }
182
186
 
183
187
  case 'tool-started': {
188
+ if (state.ignoredToolNames.has(event.toolCall.toolName)) return [];
184
189
  if (state.emittedToolCalls.has(event.toolCall.toolCallId)) {
185
190
  return [];
186
191
  }
@@ -189,6 +194,7 @@ export function translateClineEvent(
189
194
  }
190
195
 
191
196
  case 'tool-finished': {
197
+ if (state.ignoredToolNames.has(event.toolCall.toolName)) return [];
192
198
  // The tool message carries the runtime's recorded result for this call.
193
199
  const resultPart = event.message.content.find(
194
200
  (part): part is Extract<typeof part, { type: 'tool-result' }> =>