🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(heterogeneous-agents): support OpenCode 2.x (#22740)
Mochafe92e50fb685
diff --git a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/parseReadContent.test.ts b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/parseReadContent.test.tsindex ce2a8a9eea3..d1a136f9905 100644--- a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/parseReadContent.test.ts+++ b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/parseReadContent.test.ts@@ -92,6 +92,23 @@ plain line});});+ it.each([+ [+ 'Read file /repo/long.txt, lines 10-12\n10: row 10\n11: row 11\n12: row 12\n[Output truncated. Continue reading with offset: 13]',+ { content: 'row 10\nrow 11\nrow 12', hasEnvelope: true, path: '/repo/long.txt' },+ ],+ [+ 'Read file /repo/a, lines 1.txt, lines 1-1\n1: hello',+ { content: 'hello', hasEnvelope: true, path: '/repo/a, lines 1.txt' },+ ],+ [+ 'Read file /repo/empty.txt, 0 lines',+ { content: '', hasEnvelope: true, path: '/repo/empty.txt' },+ ],+ ])('parses the OpenCode 2.x read header %#', (raw, expected) => {+ expect(parseOpenCodeReadContent(raw)).toEqual(expected);+ });+it('leaves content without a complete OpenCode envelope unchanged', () => {expect(parseOpenCodeReadContent('raw file content')).toEqual({ content: 'raw file content' });expect(parseOpenCodeReadContent('<content>unterminated')).toEqual({diff --git a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/parseReadContent.ts b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/parseReadContent.tsindex d20c3923e57..5fbf9ba3872 100644--- a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/parseReadContent.ts+++ b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/parseReadContent.ts@@ -1,19 +1,49 @@interface ParsedReadContent {content: string;- /** Whether a complete OpenCode `<content>` envelope was found and unwrapped. */+ /** Whether OpenCode read framing (1.x `<content>` envelope or 2.x header) was unwrapped. */hasEnvelope?: boolean;path?: string;}const LINE_NUMBER_PREFIX = /^\s*\d+:\s?/;const READ_MARKER_AT_START = /^\((?:End of file|Showing lines)/;+// OpenCode 2.x: `Read file <path>, lines 10-12` or `Read file <path>, 0 lines`+// on the first line, then numbered lines and an optional truncation notice.+const V2_READ_HEADER = /^Read file (.+), (?:lines \d+-\d+|\d+ lines?)$/;+const V2_TRUNCATION_MARKER = /(?:^|\n)\[Output truncated\b[^\n]*\]$/;++const stripLineNumbers = (content: string): string => {+ const lines = content.split('\n');+ const nonEmptyLines = lines.filter((line) => line.trim().length > 0);+ const hasLineNumbers =+ nonEmptyLines.length > 0 && nonEmptyLines.every((line) => LINE_NUMBER_PREFIX.test(line));+ return hasLineNumbers+ ? lines.map((line) => line.replace(LINE_NUMBER_PREFIX, '')).join('\n')+ : content;+};++const parseV2ReadContent = (content: string): ParsedReadContent | undefined => {+ const headerEnd = content.indexOf('\n');+ const header = headerEnd < 0 ? content : content.slice(0, headerEnd);+ const filePath = V2_READ_HEADER.exec(header)?.[1];+ if (!filePath) return;++ const body = headerEnd < 0 ? '' : content.slice(headerEnd + 1);+ return {+ content: stripLineNumbers(body.replace(V2_TRUNCATION_MARKER, '').trimEnd()),+ hasEnvelope: true,+ path: filePath,+ };+};export const parseOpenCodeReadContent = (content: string): ParsedReadContent => {const contentStart = content.indexOf('<content>');// Resolve the closing tag from the end: the file body itself may contain a// literal `</content>` (XML/HTML sources, code handling this envelope).const contentEnd = content.lastIndexOf('</content>');- if (contentStart < 0 || contentEnd < contentStart + '<content>'.length) return { content };+ if (contentStart < 0 || contentEnd < contentStart + '<content>'.length) {+ return parseV2ReadContent(content) ?? { content };+ }const header = content.slice(0, contentStart);const pathStart = header.indexOf('<path>');@@ -33,16 +63,8 @@ export const parseOpenCodeReadContent = (content: string): ParsedReadContent =>const contentWithoutMarker = (markerStart >= 0 ? wrappedContent.slice(0, markerStart) : wrappedContent).trimEnd();- const lines = contentWithoutMarker.split('\n');- const nonEmptyLines = lines.filter((line) => line.trim().length > 0);- const hasLineNumbers =- nonEmptyLines.length > 0 && nonEmptyLines.every((line) => LINE_NUMBER_PREFIX.test(line));- const normalized = hasLineNumbers- ? lines.map((line) => line.replace(LINE_NUMBER_PREFIX, '')).join('\n')- : contentWithoutMarker;-return {- content: normalized,+ content: stripLineNumbers(contentWithoutMarker),hasEnvelope: true,path: filePath,};diff --git a/packages/heterogeneous-agents/src/adapters/opencode.test.ts b/packages/heterogeneous-agents/src/adapters/opencode.test.tsindex d42eaf3f1d4..9894f5417b6 100644--- a/packages/heterogeneous-agents/src/adapters/opencode.test.ts+++ b/packages/heterogeneous-agents/src/adapters/opencode.test.ts@@ -87,6 +87,37 @@ describe('OpenCodeAdapter', () => {expect(adapter.adapt(raw)).toEqual([]);});+ it('maps OpenCode 2.x tool parts, which carry the call id in `id` and rename bash to shell', () => {+ const adapter = new OpenCodeAdapter();+ const raw = {+ part: {+ id: 'call_00_shell',+ messageID: 'msg-1',+ partID: 'prt-tool-1',+ sessionID: 'ses-v2',+ state: {+ input: { command: 'ls', workdir: '/repo' },+ output: 'a.txt\n',+ status: 'completed',+ },+ tool: 'shell',+ type: 'tool',+ },+ sessionID: 'ses-v2',+ type: 'tool_use',+ };++ const events = adapter.adapt(raw);+ expect(events.map(({ type }) => type)).toEqual(['stream_chunk', 'tool_result', 'tool_end']);+ expect(events[0].data.toolsCalling[0]).toMatchObject({+ apiName: 'bash',+ arguments: '{"command":"ls","workdir":"/repo"}',+ id: 'call_00_shell',+ });+ expect(events[1].data).toMatchObject({ content: 'a.txt\n', toolCallId: 'call_00_shell' });+ expect(adapter.adapt(raw)).toEqual([]);+ });+it('maps todowrite snapshots into shared todo plugin state', () => {const adapter = new OpenCodeAdapter();const todos = [diff --git a/packages/heterogeneous-agents/src/adapters/opencode.ts b/packages/heterogeneous-agents/src/adapters/opencode.tsindex 8b3251fea1d..e1722a3a7a8 100644--- a/packages/heterogeneous-agents/src/adapters/opencode.ts+++ b/packages/heterogeneous-agents/src/adapters/opencode.ts@@ -12,6 +12,9 @@ import type {const OPENCODE_IDENTIFIER = 'opencode';const OPENCODE_TODO_WRITE_API = 'todowrite';+// OpenCode 2.x renamed `bash` to `shell` (same `command` input). Keep the 1.x+// name so command renders and git-effect recording apply to both majors.+const OPENCODE_TOOL_ALIASES: Record<string, string> = { shell: 'bash' };const OPENCODE_CLI_INSTALL_DOCS_URL =getHeterogeneousAgentConfigOrThrow(OPENCODE_IDENTIFIER).auth.docsUrl;const AUTH_REQUIRED_PATTERNS = [@@ -179,7 +182,10 @@ export class OpenCodeAdapter implements AgentEventAdapter {private handleTool(part: any): HeterogeneousAgentEvent[] {const state = part?.state;- const callId = part?.callID;+ // 1.x: `id` is the part id and `callID` the tool call id. 2.x drops+ // `callID`, moving the call id into `id` and the part id into `partID`.+ const callId = part?.callID ?? part?.id;+ const partId = part?.partID ?? (part?.callID ? part.id : undefined);if (part?.type !== 'tool' ||typeof callId !== 'string' ||@@ -189,10 +195,11 @@ export class OpenCodeAdapter implements AgentEventAdapter {return [];}this.completedToolCallIds.add(callId);- if (part.id) this.completedPartIds.add(part.id);+ if (partId) this.completedPartIds.add(partId);+ const apiName = typeof part.tool === 'string' ? part.tool : 'unknown';const tool: ToolCallPayload = {- apiName: typeof part.tool === 'string' ? part.tool : 'unknown',+ apiName: OPENCODE_TOOL_ALIASES[apiName] ?? apiName,arguments: JSON.stringify(state.input ?? {}),id: callId,identifier: OPENCODE_IDENTIFIER,diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.tsindex 27619d0112e..adad4a91f58 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts@@ -177,18 +177,17 @@ describe('resolveCliCommand', () => {expect(execFileMock.mock.calls[1]![1]).toEqual(['agent', '--help']);});- it('resolves and validates OpenCode using its bare semver output', async () => {+ it.each([+ ['1.18.3', '1.18.3'],+ ['opencode v2.2.6\n', '2.2.6'],+ ['othertool v2.2.6\n', undefined],+ ])('validates the OpenCode version banner %j', async (banner, version) => {callExecFile('/Users/x/.opencode/bin/opencode\n');- callExecFile('1.18.3');-+ callExecFile(banner);const { detectHeterogeneousCliCommand } = await importModule();const status = await detectHeterogeneousCliCommand('opencode', 'opencode');- expect(status).toMatchObject({- available: true,- path: '/Users/x/.opencode/bin/opencode',- version: '1.18.3',- });+ expect(status).toMatchObject(version ? { available: true, version } : { available: false });});it('validates Kimi Code using its bare semver and stream-json capabilities', async () => {diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.tsindex eae0050b39c..ca6c3738f65 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts@@ -709,9 +709,9 @@ const HETEROGENEOUS_CLI_AGENT_OPTIONS = {validatePattern: /^v?\d+\.\d+\.\d+(?:[-+][\dA-Za-z.-]+)?$/,},'opencode': {- // OpenCode prints only a bare version (for example `1.18.3`) for- // `--version`, without a product-name prefix.- validatePattern: /^v?\d+\.\d+\.\d+(?:[-+][\dA-Za-z.-]+)?$/,+ // OpenCode 1.x prints a bare version (`1.18.3`); 2.x prefixes the product+ // name (`opencode v2.2.6`).+ validatePattern: /^(?:opencode\s+)?v?\d+\.\d+\.\d+(?:[-+][\dA-Za-z.-]+)?$/i,},'pi': {// Pi prints a bare semantic version for `--version`.diff --git a/packages/utils/src/managedProcess.cwd.test.ts b/packages/utils/src/managedProcess.cwd.test.tsnew file mode 100644index 00000000000..7f66d5ac554--- /dev/null+++ b/packages/utils/src/managedProcess.cwd.test.ts@@ -0,0 +1,40 @@+// @vitest-environment node+import { once } from 'node:events';+import { mkdtemp, rm } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++import { spawnManaged } from './managedProcess';++const readPwd = async (options: Parameters<typeof spawnManaged>[2]) => {+ const child = spawnManaged(+ process.execPath,+ ['-e', 'process.stdout.write(process.env.PWD ?? "")'],+ options,+ );+ let output = '';+ child.stdout!.on('data', (chunk) => (output += chunk));+ await once(child, 'close');+ return output;+};++// CLIs such as OpenCode 2.x resolve their project from `PWD`, not the real cwd.+describe.skipIf(process.platform === 'win32')('spawnManaged working directory', () => {+ it.each([+ ['an explicit env', { env: { ...process.env, PWD: '/' } }],+ ['the inherited env', {}],+ ])('aligns PWD with cwd for %s', async (_name, options) => {+ const cwd = await mkdtemp(path.join(os.tmpdir(), 'managed-pwd-'));+ try {+ expect(await readPwd({ ...options, cwd, stdio: 'pipe' })).toBe(cwd);+ } finally {+ await rm(cwd, { force: true, recursive: true });+ }+ });++ it('leaves PWD alone when no cwd is given', async () => {+ expect(await readPwd({ env: { ...process.env, PWD: '/' }, stdio: 'pipe' })).toBe('/');+ });+});diff --git a/packages/utils/src/managedProcess.ts b/packages/utils/src/managedProcess.tsindex 6e153bb44f7..2bc2336c042 100644--- a/packages/utils/src/managedProcess.ts+++ b/packages/utils/src/managedProcess.ts@@ -490,13 +490,31 @@ export const stopManagedProcess = (id: string) => enableManagedProcesses().stop(export const shutdownManagedProcesses = () => host[registryKey]?.shutdown() ?? Promise.resolve();/** Preserve Node's spawn overloads, including typed stdio. Cleanup helpers use raw spawn. */+/**+ * `cwd` changes the child's real directory but not the inherited `PWD`, which+ * still names the parent's directory. Shells keep the two in sync on `cd`;+ * spawned CLIs that trust `PWD` (OpenCode 2.x resolves its project from it)+ * would otherwise run in the wrong directory.+ */+const alignPwdWithCwd = (options: SpawnOptions | undefined): SpawnOptions | undefined =>+ typeof options?.cwd === 'string'+ ? { ...options, env: { ...(options.env ?? process.env), PWD: path.resolve(options.cwd) } }+ : options;+export const spawnManaged: typeof spawn = ((...args: Parameters<typeof spawn>) => {const registry = host[registryKey];log('spawn managed=%s', !!registry);registry?.assertCanSpawn();- const child = spawn(...args);- const options = (Array.isArray(args[1]) ? args[2] : (args[1] ?? args[2])) as- SpawnOptions | undefined;+ const [command, argsOrOptions, maybeOptions] = args;+ const options = alignPwdWithCwd(+ (Array.isArray(argsOrOptions) ? maybeOptions : (argsOrOptions ?? maybeOptions)) as+ SpawnOptions | undefined,+ );+ const child = (+ Array.isArray(argsOrOptions)+ ? spawn(command, argsOrOptions, options ?? {})+ : spawn(command, options ?? {})+ ) as ReturnType<typeof spawn>;registry?.register(child, options?.detached ?? false, {topicId: options?.env?.LOBEHUB_PROCESS_TOPIC || undefined,agentId: options?.env?.LOBEHUB_PROCESS_AGENT || undefined,