From 3a6bb347b57db3587e7432ff50f8585255b6dda9 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 6 Nov 2026 04:15:29 -0800 Subject: [PATCH] Apply supported read-only controls to hidden text helpers (#38558) * Keep background text generation read-only * Align runtime MIME dependency in frozen lockfile * Bundle MIME lookup data for background text tasks * Preserve text task cancellation and process ownership during policy probes * Update streamed generation fixture for permission probe * fix: preserve naming recipes with compatible restrictions * test: align naming contracts with single-attempt behavior * fix: preserve older OpenCode helper restrictions * test: complete OpenCode capability fixtures * Separate supported read-only controls from naming retries --- .../wsl-guest/build-wsl-guest.mjs | 4 +- electron.vite.config.ts | 2 + package.json | 1 + pnpm-lock.yaml | 3 + src/main/acp/acp-session-runtime.ts | 8 +- src/main/acp/acp-structured-connection.ts | 2 + src/main/acp/acp-text-task-policy.ts | 98 +++ src/main/acp/acp-text-task.test.ts | 260 ++++-- src/main/acp/acp-text-task.ts | 130 +-- src/main/grok/grok-text-task.ts | 87 ++ .../opencode/opencode-owned-text-task.test.ts | 345 ++++++++ src/main/opencode/opencode-owned-text-task.ts | 290 +++++++ .../opencode/opencode-text-task-endpoint.ts | 37 + .../opencode/opencode-text-task-events.ts | 198 +++++ src/main/opencode/opencode-text-task-files.ts | 62 ++ src/main/opencode/opencode-text-task-http.ts | 75 ++ .../opencode/opencode-text-task-input.test.ts | 278 +++++++ src/main/opencode/opencode-text-task-input.ts | 302 +++++++ .../opencode-text-task-legacy-policy.test.ts | 244 ++++++ .../opencode/opencode-text-task-policy.ts | 146 ++++ .../opencode-text-task-server-ready.ts | 66 ++ .../opencode-text-task-session.test.ts | 767 ++++++++++++++++++ .../opencode/opencode-text-task-session.ts | 293 +++++++ .../opencode-text-task-streams.test.ts | 199 +++++ .../opencode/opencode-text-task-target.ts | 133 +++ src/main/opencode/opencode-text-task.ts | 112 +++ .../opencode-wsl-guest-launch.test.ts | 140 ++++ .../opencode/opencode-wsl-guest-launch.ts | 55 ++ .../opencode/opencode-wsl-text-task-entry.ts | 99 +++ .../opencode-wsl-text-task-protocol.ts | 12 + .../opencode/opencode-wsl-text-task.test.ts | 114 +++ src/main/opencode/opencode-wsl-text-task.ts | 227 ++++++ .../structured-chat-naming-contract.test.ts | 211 +++++ ...rminal-create-host-session-binding.test.ts | 7 +- .../orchestration-opencode-model-host.test.ts | 2 + .../agent-generation-request.ts | 36 +- .../antigravity-generation-stream.test.ts | 15 +- ...ssage-text-generation-cancellation.test.ts | 158 +++- ...e-text-generation-generated-output.test.ts | 1 + ...nversation-name-generation-request.test.ts | 79 +- .../source-control-agent-cli-path.test.ts | 5 +- .../source-control-agent-launch.ts | 45 +- .../source-control-kimi-policy.ts | 55 ++ .../source-control-local-generation.ts | 108 ++- .../source-control-local-process.test.ts | 65 +- .../source-control-local-process.ts | 8 +- .../source-control-policy-probe.ts | 121 +++ .../source-control-prompt-files.ts | 110 ++- .../source-control-read-only-policy.test.ts | 292 +++++++ .../source-control-read-only-policy.ts | 272 +++++++ .../source-control-supervised-agent-spawn.ts | 47 ++ .../source-control-text-generation-types.ts | 1 + .../source-control-wsl-prompt.test.ts | 53 ++ .../antigravity-generation-plan.test.ts | 3 +- src/shared/opencode-cli-version.ts | 5 +- src/shared/opencode-generation-command.ts | 57 +- src/shared/remote-bundle-artifacts.ts | 2 + .../commit-message-agent-spec.test.ts | 23 +- .../commit-message-agent-specs-secondary.ts | 20 +- .../ai/generation/commit-message-plan.test.ts | 20 +- .../ai/generation/commit-message-plan.ts | 131 ++- .../commit-message-recipe-options.ts | 167 ++++ .../conversation-name-generation.ts | 13 +- 63 files changed, 6504 insertions(+), 417 deletions(-) create mode 100644 src/main/acp/acp-text-task-policy.ts create mode 100644 src/main/grok/grok-text-task.ts create mode 100644 src/main/opencode/opencode-owned-text-task.test.ts create mode 100644 src/main/opencode/opencode-owned-text-task.ts create mode 100644 src/main/opencode/opencode-text-task-endpoint.ts create mode 100644 src/main/opencode/opencode-text-task-events.ts create mode 100644 src/main/opencode/opencode-text-task-files.ts create mode 100644 src/main/opencode/opencode-text-task-http.ts create mode 100644 src/main/opencode/opencode-text-task-input.test.ts create mode 100644 src/main/opencode/opencode-text-task-input.ts create mode 100644 src/main/opencode/opencode-text-task-legacy-policy.test.ts create mode 100644 src/main/opencode/opencode-text-task-policy.ts create mode 100644 src/main/opencode/opencode-text-task-server-ready.ts create mode 100644 src/main/opencode/opencode-text-task-session.test.ts create mode 100644 src/main/opencode/opencode-text-task-session.ts create mode 100644 src/main/opencode/opencode-text-task-streams.test.ts create mode 100644 src/main/opencode/opencode-text-task-target.ts create mode 100644 src/main/opencode/opencode-text-task.ts create mode 100644 src/main/opencode/opencode-wsl-guest-launch.test.ts create mode 100644 src/main/opencode/opencode-wsl-guest-launch.ts create mode 100644 src/main/opencode/opencode-wsl-text-task-entry.ts create mode 100644 src/main/opencode/opencode-wsl-text-task-protocol.ts create mode 100644 src/main/opencode/opencode-wsl-text-task.test.ts create mode 100644 src/main/opencode/opencode-wsl-text-task.ts create mode 100644 src/main/runtime/agent-session/naming/structured-chat-naming-contract.test.ts create mode 100644 src/main/text-generation/source-control-kimi-policy.ts create mode 100644 src/main/text-generation/source-control-policy-probe.ts create mode 100644 src/main/text-generation/source-control-read-only-policy.test.ts create mode 100644 src/main/text-generation/source-control-read-only-policy.ts create mode 100644 src/main/text-generation/source-control-supervised-agent-spawn.ts create mode 100644 src/shared/source-control/ai/generation/commit-message-recipe-options.ts diff --git a/config/scripts/remote-host-build/wsl-guest/build-wsl-guest.mjs b/config/scripts/remote-host-build/wsl-guest/build-wsl-guest.mjs index 8ef0bdaf0c6..e570cbbf009 100644 --- a/config/scripts/remote-host-build/wsl-guest/build-wsl-guest.mjs +++ b/config/scripts/remote-host-build/wsl-guest/build-wsl-guest.mjs @@ -1,5 +1,5 @@ #!/usr/bin/env node -// Ship self-contained builtins-only CommonJS WSL hook/network/profile/SQLite programs via out/relay/wsl extraResources. +// Ship self-contained builtins-only CommonJS WSL hook/network/profile/SQLite/OpenCode text-task programs via out/relay/wsl extraResources. import { build } from 'esbuild' import { JSONC_PARSER_ESM_ALIAS } from '../../../build-plugins/jsonc-parser-esm.ts' import { createHash } from 'node:crypto' @@ -7,6 +7,7 @@ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { OPENCODE_SQLITE_READER_FILENAME, + OPENCODE_WSL_TEXT_TASK_FILENAME, WSL_CLAUDE_PROFILE_HELPER_FILENAME } from '../../../../src/shared/remote-bundle-artifacts.ts' @@ -62,5 +63,6 @@ await bundle( OPENCODE_SQLITE_READER_FILENAME, { external: ['electron'] } ) +await bundle('src/main/opencode/opencode-wsl-text-task-entry.ts', OPENCODE_WSL_TEXT_TASK_FILENAME) console.log('WSL guest build complete.') diff --git a/electron.vite.config.ts b/electron.vite.config.ts index 785f2918f23..23daba961e0 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -26,6 +26,8 @@ const BUNDLED_MAIN_DEPENDENCIES = new Set([ 'smol-toml', 'yaml', 'fflate', + 'mime-types', + 'mime-db', // Linear save confirmation; bundled like orcad so packaging needs no extra node_modules. 'unified', 'remark-parse', diff --git a/package.json b/package.json index 5b55f6ec07b..6c3da812e93 100644 --- a/package.json +++ b/package.json @@ -236,6 +236,7 @@ "fflate": "0.8.3", "i18next": "^26.5.11", "jsonc-parser": "^3.3.1", + "mime-types": "3.0.2", "node-pty": "^1.1.0", "posthog-node": "^5.52.5", "proper-lockfile": "4.1.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 996cc0c34df..a93d599997f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -262,6 +262,9 @@ importers: jsonc-parser: specifier: ^3.3.1 version: 3.3.1 + mime-types: + specifier: 3.0.2 + version: 3.0.2 node-pty: specifier: ^1.1.0 version: 1.1.0(patch_hash=37dc98d9a4bcfc67153fa2fbf30689563ff49dcf8e6f0578484cbacdf1e38af5) diff --git a/src/main/acp/acp-session-runtime.ts b/src/main/acp/acp-session-runtime.ts index 3c7ae92f852..49408ad6b87 100644 --- a/src/main/acp/acp-session-runtime.ts +++ b/src/main/acp/acp-session-runtime.ts @@ -150,12 +150,16 @@ export class AcpSessionRuntime { } /** Reject core session methods for session-free discovery. */ - async requestSessionFreeExtension(method: string, params: unknown): Promise { + async requestSessionFreeExtension( + method: string, + params: unknown, + timeoutMs: number | null = null + ): Promise { if (!method.includes('/') || method.startsWith('session/')) { throw new Error(`Not an ACP extension method: ${method}`) } await this.initialize() - return this.peer.request(method, params, { timeoutMs: null }) + return this.peer.request(method, params, { timeoutMs }) } /** Fork without starting a session here; requires advertised fork support. */ diff --git a/src/main/acp/acp-structured-connection.ts b/src/main/acp/acp-structured-connection.ts index 630b4ca9a87..4c22fdb49c4 100644 --- a/src/main/acp/acp-structured-connection.ts +++ b/src/main/acp/acp-structured-connection.ts @@ -4,6 +4,8 @@ import type { ProviderProcessLaunch } from '../provider-process/provider-process export type AcpStructuredConnection = Pick< AcpAgentConnection, | 'initialize' + | 'authenticate' + | 'requestSessionFreeExtension' | 'forkSession' | 'start' | 'prompt' diff --git a/src/main/acp/acp-text-task-policy.ts b/src/main/acp/acp-text-task-policy.ts new file mode 100644 index 00000000000..4cd560e52b1 --- /dev/null +++ b/src/main/acp/acp-text-task-policy.ts @@ -0,0 +1,98 @@ +import { AcpRpcError } from './acp-errors' +import type { AcpStructuredConnection } from './acp-structured-connection' +import { GROK_TEXT_TASK_ENV } from '../grok/grok-text-task' +import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason' +import type { AcpStructuredSessionAdapterDeps } from './acp-structured-session-adapter-deps' +import { STRUCTURED_CHILD_ENV_TO_DELETE } from '../runtime/agent-session/environment/structured-session-child-env' +import { z } from 'zod' +import type { AcpLaunchSpec } from './acp-launch-specs' +import type { + RequestPermissionRequest, + RequestPermissionResponse +} from './generated/acp-protocol.generated' + +const envelope = z.looseObject({ sessionId: z.string() }) + +export function denyAcpTextTaskPermission( + request: RequestPermissionRequest +): RequestPermissionResponse { + const denied = request.options.find((option) => option.kind === 'reject_once') + return { + outcome: denied ? { outcome: 'selected', optionId: denied.optionId } : { outcome: 'cancelled' } + } +} + +export function acpTextTaskCompletion( + dialect: AcpLaunchSpec['dialect'], + sessionId: string, + promptId: string, + method: string, + params: unknown +): { stopReason: string } | undefined { + if (!sessionId || envelope.safeParse(params).data?.sessionId !== sessionId) { + return undefined + } + const completion = dialect.textTaskCompletion?.(method, params) + if (completion?.promptId === promptId) { + return completion + } + const mapped = dialect.notification?.(method, params, Date.now()) + return mapped?.disposition === 'map' && mapped.turn === promptId && !mapped.replay && mapped.end + ? mapped.end + : undefined +} + +export const TASK_ENV_TO_DELETE = [ + ...STRUCTURED_CHILD_ENV_TO_DELETE, + 'ORCA_AGENT_SESSION_ID', + 'ORCA_AGENT_SESSION_SPAWN_TOKEN', + 'ORCA_TERMINAL_HANDLE', + 'ORCA_STRUCTURED_SESSION', + 'ORCA_CHAT_SCRATCH_DIR', + 'ORCA_CHAT_VISUALS_DIR' +] + +export async function cleanupAcpTextTaskProtocol( + work: () => Promise, + logger: AcpStructuredSessionAdapterDeps['logger'] +): Promise { + try { + await waitForPromiseWithSignal(work(), AbortSignal.timeout(2_000)) + } catch (error) { + logger?.warn('Naming helper protocol cleanup failed', { scope: 'acp-text-task', error }) + } +} + +export function acpTextTaskArgs(spec: AcpLaunchSpec): string[] { + const args = spec.args({ fullAccess: false, pluginDir: null }) + if (spec.agent === 'grok') { + args.splice(1, 0, '--no-leader') + args.unshift('--permission-mode', 'default') + } + return args +} + +export function acpTextTaskEnv( + agent: AcpLaunchSpec['agent'], + env: Record +): Record { + return agent === 'grok' ? { ...env, ...GROK_TEXT_TASK_ENV } : env +} + +export function cleanupGrokTextTaskSession( + server: AcpStructuredConnection, + sessionId: string, + cwd: string | undefined, + logger: AcpStructuredSessionAdapterDeps['logger'] +): Promise { + return cleanupAcpTextTaskProtocol( + () => server.requestSessionFreeExtension('_x.ai/session/delete', { sessionId, cwd }, 2_000), + logger + ) +} + +export function rejectAcpTextTaskWork(failed: AbortController): never { + const error = new AcpRpcError(-32601, 'Tools and user input are unavailable during chat naming') + failed.abort(error) + throw error +} diff --git a/src/main/acp/acp-text-task.test.ts b/src/main/acp/acp-text-task.test.ts index 9b28e26b98c..31710764d6e 100644 --- a/src/main/acp/acp-text-task.test.ts +++ b/src/main/acp/acp-text-task.test.ts @@ -1,7 +1,16 @@ -import { mkdtemp, readFile, writeFile, mkdir, rm, access } from 'node:fs/promises' +import { + mkdtemp, + readFile, + writeFile, + mkdir, + rm, + access, + symlink, + realpath +} from 'node:fs/promises' import type * as NodeFsPromises from 'node:fs/promises' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { basename, join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' import { z } from 'zod' import { AcpStructuredSessionAdapter } from './acp-structured-session-adapter' @@ -16,10 +25,19 @@ import { FakeAcpChild } from './acp-scripted-connection.test-fixture' import { acpLaunchSpecFor, type AcpLaunchSpec } from './acp-launch-specs' import { AcpLaunchGate } from './acp-launch-gate' import type { AcpStructuredSessionAdapterDeps } from './acp-structured-session-adapter-deps' +import type { InitializeResponse } from './generated/acp-protocol.generated' +import type * as GrokTextTaskModule from '../grok/grok-text-task' +import { runGrokTextTask } from '../grok/grok-text-task' +vi.mock('../grok/grok-text-task', async (original) => ({ + ...(await original()), + runGrokTextTask: vi.fn() +})) const boundary = vi.hoisted(() => ({ adapter: vi.fn<() => StructuredAgentSessionAdapter>(), - afterTemp: vi.fn<(path: string) => Promise>() + afterTemp: vi.fn<(path: string) => Promise>(), + taskTempParent: '', + failTaskRealpath: false })) vi.mock('../native-chat/agent-session-wire/structured-agent-session-registry', () => ({ getStructuredAgentSessionHost: () => ({ deps: { adapter: boundary.adapter() } }) @@ -29,9 +47,19 @@ vi.mock('node:fs/promises', async (importOriginal) => { return { ...fs, mkdtemp: async (prefix: string) => { - const path = await fs.mkdtemp(prefix) + const path = await fs.mkdtemp( + boundary.taskTempParent && prefix.includes('orca-chat-name-') + ? join(boundary.taskTempParent, 'orca-chat-name-') + : prefix + ) await boundary.afterTemp(path) return path + }, + realpath: async (path: string) => { + if (boundary.failTaskRealpath && path.includes('orca-chat-name-')) { + throw new Error('Task directory resolution failed') + } + return fs.realpath(path) } } }) @@ -42,19 +70,23 @@ afterEach(async () => { vi.useRealTimers() vi.clearAllMocks() boundary.afterTemp.mockReset() + boundary.taskTempParent = '' + boundary.failTaskRealpath = false await Promise.all(folders.splice(0).map((folder) => rm(folder, { recursive: true, force: true }))) }) async function stagedRig( options: { antigravity?: boolean + modeFailure?: boolean proveExit?: boolean - deletion?: 'unsupported' | 'stalled' + initialized?: InitializeResponse prepare?: () => Promise> onConnect?: () => void shouldExecute?: () => boolean close?: (child: FakeAcpChild) => Promise runtime?: boolean + requireAuth?: boolean } = {} ) { // Short on POSIX so the private temp root stays in this folder, not /tmp/oacp-*. @@ -62,7 +94,7 @@ async function stagedRig( process.platform === 'win32' ? join(tmpdir(), 'orca-naming-task-test-') : '/tmp/o' ) folders.push(root) - const base = acpLaunchSpecFor(options.antigravity ? 'antigravity' : 'grok') + const base = acpLaunchSpecFor(options.antigravity !== false ? 'antigravity' : 'grok') if (!base) { throw new Error('ACP spec is missing') } @@ -102,16 +134,26 @@ async function stagedRig( } const agent = child.agent agent.on('initialize', (frame) => - agent.reply(frame, { protocolVersion: 1, agentCapabilities: {} }) + agent.reply(frame, options.initialized ?? { protocolVersion: 1, agentCapabilities: {} }) ) - agent.on('session/new', (frame) => - agent.reply(frame, { sessionId: '11111111-1111-4111-8111-111111111111' }) - ) - agent.on('_x.ai/session/delete', (frame) => { - if (options.deletion === 'unsupported') { - agent.fail(frame, -32601, 'Method not found') - } else if (options.deletion !== 'stalled') { - agent.reply(frame, { success: true }) + let authenticated = false + agent.on('authenticate', (frame) => { + authenticated = true + agent.reply(frame, {}) + }) + agent.on('_x.ai/session/delete', (frame) => agent.reply(frame, { success: true })) + agent.on('session/new', (frame) => { + if (options.requireAuth && !authenticated) { + agent.fail(frame, -32000, 'Login required') + } else { + agent.reply(frame, { sessionId: '11111111-1111-4111-8111-111111111111' }) + } + }) + agent.on('session/set_config_option', (frame) => { + if (options.modeFailure) { + agent.fail(frame, -32602, 'Mode control rejected') + } else { + agent.reply(frame, { configOptions: [] }) } }) agent.on('session/prompt', () => { @@ -130,7 +172,10 @@ async function stagedRig( boundary.adapter.mockReturnValue(router) const record = agentSessionRecordFixture() record.provider = spec.agent - record.accountHome = { variable: options.antigravity ? 'GEMINI_HOME' : 'GROK_HOME', path: root } + record.accountHome = { + variable: spec.agent === 'antigravity' ? 'GEMINI_HOME' : 'GROK_HOME', + path: root + } const naming = structuredChatNamingDeps( () => ({ getSettings: () => getDefaultSettings(root) }), { @@ -151,7 +196,7 @@ async function stagedRig( shouldExecute: options.shouldExecute }) void result.catch(() => {}) - return { root, ready, result, tasks, logger, gate: spec.launchGate } + return { root, ready, result, tasks, logger, gate: spec.launchGate, child: () => child } } async function rig(options: Parameters[0] = {}) { @@ -177,57 +222,118 @@ async function rig(options: Parameters[0] = {}) { return { ...state, root, server, agent, frame, promptId, result, tasks, text } } -it.each(['turn_completed', 'x.ai/session/prompt_complete', '_x.ai/session/prompt_complete'])( - 'settles matching Grok %s without waiting for its prompt RPC', - async (method) => { - const r = await rig() - r.text('Repair login') - const complete = (sessionId: string, promptId: string, stopReason: string) => { - if (method === 'turn_completed') { - r.agent.notify('session/update', { - sessionId, - update: { sessionUpdate: method, prompt_id: promptId, stop_reason: stopReason } - }) - } else { - r.agent.notify(method, { sessionId, promptId, stopReason }) +it.each(['success', 'failure'] as const)( + 'deletes only the owned Grok session after its headless writer settles on %s', + async (outcome) => { + const parent = await mkdtemp(join(tmpdir(), 'orca-naming-path-test-')) + folders.push(parent) + const physical = join(await realpath(parent), 'physical') + await mkdir(physical) + const alias = join(parent, 'alias') + await symlink(physical, alias, process.platform === 'win32' ? 'junction' : 'dir') + boundary.taskTempParent = alias + const writer = Promise.withResolvers() + const launched = Promise.withResolvers[0]>() + vi.mocked(runGrokTextTask).mockImplementationOnce((input) => { + launched.resolve(input) + return writer.promise + }) + const r = await stagedRig({ + antigravity: false, + runtime: true, + initialized: { + protocolVersion: 1, + authMethods: [{ id: 'cached_token', name: 'Saved login' }], + _meta: { defaultAuthMethodId: 'cached_token' } } + }) + const input = await launched.promise + const child = r.child()! + expect(input).toMatchObject({ + launch: { command: '/fixture/agent', env: { GROK_HOME: r.root, GROK_STORAGE_MODE: 'local' } }, + prompt: expect.stringContaining('Repair login'), + sessionId: expect.stringMatching(/^[0-9a-f-]{36}$/) + }) + expect(input.cwd).toBe(join(physical, basename(input.cwd))) + expect(child.launch.cwd).toBe(input.cwd) + expect(child.launch.env?.GROK_STORAGE_MODE).toBe('local') + expect(child.launch.args).toEqual([ + '--permission-mode', + 'default', + 'agent', + '--no-leader', + 'stdio' + ]) + expect(child.exited).toBe(false) + expect(child.agent.frames.some((frame) => frame.method === '_x.ai/session/delete')).toBe(false) + if (outcome === 'success') { + writer.resolve('Repair login\n') + expect(await r.result).toEqual({ name: 'Repair login' }) + } else { + writer.reject(new Error('Writer failed after shutdown')) + await expect(r.result).resolves.toMatchObject({ errorCode: 'grokFailed' }) } - complete('other-session', r.promptId, 'error') - complete('11111111-1111-4111-8111-111111111111', 'other-prompt', 'error') - await Promise.resolve() - expect(r.server.exited).toBe(false) - complete('11111111-1111-4111-8111-111111111111', r.promptId, 'end_turn') - expect(await r.result).toBe('Repair login') - const start = r.agent.frames.find((frame) => frame.method === 'session/new') - expect(start?.params).toEqual({ cwd: r.server.launch.cwd, mcpServers: [] }) - expect(r.server.launch.args).toEqual(['agent', 'stdio']) - expect(r.server.exited).toBe(true) expect( - r.agent.frames.some((frame) => - ['session/load', 'session/resume', 'session/fork', 'session/cancel'].includes( - frame.method ?? '' - ) + child.agent.frames.find((frame) => frame.method === '_x.ai/session/delete')?.params + ).toEqual({ sessionId: input.sessionId, cwd: input.cwd }) + expect( + child.agent.frames.some((frame) => + ['session/new', 'session/prompt'].includes(frame.method ?? '') ) ).toBe(false) - expect(r.agent.frames.find((frame) => frame.method === '_x.ai/session/delete')?.params).toEqual( - { sessionId: '11111111-1111-4111-8111-111111111111', cwd: r.server.launch.cwd } - ) - await expect(access(r.server.launch.cwd!)).rejects.toThrow() + expect(child.exited).toBe(true) + await expect(access(input.cwd)).rejects.toThrow() } ) -it.each(['unsupported', 'stalled'] as const)( - 'preserves a title after %s deletion and closes', - async (deletion) => { - vi.useFakeTimers() - const r = await rig({ deletion, shouldExecute: () => true }) - r.text('Repair login') - r.agent.reply(r.frame, { stopReason: 'end_turn' }) - await vi.advanceTimersByTimeAsync(2_001) - expect(await r.result).toBe('Repair login') - expect(r.server.exited).toBe(true) - } -) +it('removes the allocated Grok directory without starting a child when canonicalization fails', async () => { + let allocated = '' + boundary.afterTemp.mockImplementation(async (path) => { + if (path.includes('orca-chat-name-')) { + allocated = path + } + }) + boundary.failTaskRealpath = true + const r = await stagedRig({ antigravity: false }) + await expect(r.result).rejects.toThrow('Task directory resolution failed') + expect(allocated).not.toBe('') + await expect(access(allocated)).rejects.toThrow() + expect(r.child()).toBeUndefined() + expect(runGrokTextTask).not.toHaveBeenCalled() +}) + +it('names on the normal Grok account when headless selects a different account', async () => { + const r = await rig({ + antigravity: false, + requireAuth: true, + prepare: async () => ({ PATH: '/usr/bin', XAI_API_KEY: 'fixture-only' }), + initialized: { + protocolVersion: 1, + authMethods: [ + { id: 'xai.api_key', name: 'API key' }, + { id: 'cached_token', name: 'Saved login' } + ], + _meta: { defaultAuthMethodId: 'cached_token' } + } + }) + expect(runGrokTextTask).not.toHaveBeenCalled() + expect(r.agent.frames.find((frame) => frame.method === 'authenticate')?.params).toEqual({ + methodId: 'xai.api_key' + }) + expect(r.agent.frames.find((frame) => frame.method === 'session/new')?.params).toEqual({ + cwd: await realpath(r.server.launch.cwd!), + mcpServers: [], + _meta: { yoloMode: false, autoMode: false } + }) + r.text('Harbor Lantern') + r.agent.reply(r.frame, { stopReason: 'end_turn' }) + await expect(r.result).resolves.toBe('Harbor Lantern') + expect(r.agent.frames.find((frame) => frame.method === '_x.ai/session/delete')?.params).toEqual({ + sessionId: '11111111-1111-4111-8111-111111111111', + cwd: r.server.launch.cwd + }) + expect(r.child()?.exited).toBe(true) +}) it('does not spawn when preparation finishes after the deadline', async () => { vi.useFakeTimers() @@ -423,11 +529,41 @@ it('runs healthy own-agent naming through the runtime, registered router and ACP prompt: [expect.objectContaining({ text: expect.stringContaining('Repair login') })] }) ) - expect(r.server.launch.env?.GROK_HOME).toBe(r.root) - expect(r.server.launch.args).toEqual(['agent', 'stdio']) + expect(r.server.launch.env?.GEMINI_HOME).toBe(r.root) + expect(r.server.launch.args).toEqual(process.platform === 'linux' ? ['--uid='] : []) r.text('Repair login\n') r.agent.reply(r.frame, { stopReason: 'end_turn' }) expect(await r.result).toEqual({ name: 'Repair login' }) expect(r.logger.warn).not.toHaveBeenCalled() expect(r.server.exited).toBe(true) }) + +it('applies Antigravity default mode and returns its advertised denial before completing', async () => { + const r = await rig({ antigravity: true }) + expect( + r.agent.frames.find((frame) => frame.method === 'session/set_config_option')?.params + ).toEqual({ + sessionId: '11111111-1111-4111-8111-111111111111', + configId: 'mode', + value: 'default' + }) + const response = await r.agent.request('permission', 'session/request_permission', { + sessionId: '11111111-1111-4111-8111-111111111111', + toolCall: { toolCallId: 'shell-call', title: 'run_shell_command', kind: 'execute' }, + options: [ + { optionId: 'allow', name: 'Allow once', kind: 'allow_once' }, + { optionId: 'deny', name: 'Reject once', kind: 'reject_once' } + ] + }) + expect(response).toMatchObject({ result: { outcome: { outcome: 'selected', optionId: 'deny' } } }) + r.text('Harbor Lantern') + r.agent.reply(r.frame, { stopReason: 'end_turn' }) + expect(await r.result).toBe('Harbor Lantern') + expect(r.server.exited).toBe(true) +}) + +it('never prompts Antigravity after rejection of its task permission mode', async () => { + const r = await stagedRig({ antigravity: true, modeFailure: true }) + await expect(r.result).rejects.toThrow('Mode control rejected') + await r.tasks.closeAll() +}) diff --git a/src/main/acp/acp-text-task.ts b/src/main/acp/acp-text-task.ts index 3f3a873ca55..39692f3a3bf 100644 --- a/src/main/acp/acp-text-task.ts +++ b/src/main/acp/acp-text-task.ts @@ -1,32 +1,31 @@ +import { conversationNameTaskPrompt } from '../../shared/source-control/ai/generation/conversation-name-generation' import { randomUUID } from 'node:crypto' -import { mkdtemp, rm } from 'node:fs/promises' +import { mkdtemp, realpath, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { z } from 'zod' import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason' import type { StructuredAgentSessionAdapter } from '../native-chat/agent-session-wire/structured-agent-session-adapter' import { ProviderAcquisitionStarts } from '../provider-process/provider-acquisition-starts' import { removeAntigravitySignInSessionFiles } from '../antigravity/antigravity-sign-in-session-files' import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from '../text-generation/source-control-generation-limits' -import { STRUCTURED_CHILD_ENV_TO_DELETE } from '../runtime/agent-session/environment/structured-session-child-env' import { resolveAcpLaunchInvocation } from './acp-structured-launch-resolution' import { prepareAcpLaunch } from './acp-structured-launch-preparation' import { acpPrivateTempConnect } from './acp-private-temp' -import { AcpRpcError } from './acp-errors' +import { + acpTextTaskCompletion, + acpTextTaskArgs, + acpTextTaskEnv, + cleanupAcpTextTaskProtocol, + cleanupGrokTextTaskSession, + denyAcpTextTaskPermission, + rejectAcpTextTaskWork, + TASK_ENV_TO_DELETE +} from './acp-text-task-policy' import type { AcpStructuredConnection } from './acp-structured-connection' import type { AcpStructuredSessionAdapterDeps } from './acp-structured-session-adapter-deps' +import { grokTextTaskPreservesAccount, runGrokTextTask } from '../grok/grok-text-task' type TextInput = Parameters>[0] -const envelope = z.looseObject({ sessionId: z.string() }) -const TASK_ENV_TO_DELETE = [ - ...STRUCTURED_CHILD_ENV_TO_DELETE, - 'ORCA_AGENT_SESSION_ID', - 'ORCA_AGENT_SESSION_SPAWN_TOKEN', - 'ORCA_TERMINAL_HANDLE', - 'ORCA_STRUCTURED_SESSION', - 'ORCA_CHAT_SCRATCH_DIR', - 'ORCA_CHAT_VISUALS_DIR' -] /** Disposable native tasks belong to the adapter so shutdown also owns uncertain closes. */ export class AcpTextTasks { @@ -69,6 +68,8 @@ export class AcpTextTasks { observeRoot: (connection: AcpStructuredConnection) => void ): Promise { const { spec } = this.deps + const namingPrompt = conversationNameTaskPrompt(input.prompt) + const deadlineAt = Date.now() + SOURCE_CONTROL_GENERATION_TIMEOUT_MS const deadline = new AbortController() const timer = setTimeout( () => deadline.abort(new Error('Chat naming timed out')), @@ -86,7 +87,9 @@ export class AcpTextTasks { let cwd: string | undefined let home = '' let sessionId = '' + let modeConfigId = 'mode' let completed = false + let headless = false let starting = false let done = false let disposed = false @@ -124,49 +127,39 @@ export class AcpTextTasks { ) home = launch.env.GEMINI_HOME ?? '' cwd = await mkdtemp(join(tmpdir(), 'orca-chat-name-')) - signal.throwIfAborted() + if (spec.agent === 'grok') { + cwd = await realpath(cwd) + } + checkCurrent() const failed = new AbortController() const taskSignal = AbortSignal.any([signal, failed.signal]) - const reject = (): never => { - const error = new AcpRpcError( - -32601, - 'Tools and user input are unavailable during chat naming' - ) - failed.abort(error) - throw error - } + const reject = (): never => rejectAcpTextTaskWork(failed) const promptId = randomUUID() const terminal = Promise.withResolvers<{ stopReason: string }>() const notification = (method: string, params: unknown): void => { - if (!sessionId || envelope.safeParse(params).data?.sessionId !== sessionId) { - return - } - const completion = spec.dialect.textTaskCompletion?.(method, params) - if (completion?.promptId === promptId) { + const completion = acpTextTaskCompletion(spec.dialect, sessionId, promptId, method, params) + if (completion) { terminal.resolve(completion) } - const mapped = spec.dialect.notification?.(method, params, Date.now()) - if ( - mapped?.disposition === 'map' && - mapped.turn === promptId && - !mapped.replay && - mapped.end - ) { - terminal.resolve(mapped.end) - } } const spawn = (connect: typeof this.deps.connect): AcpStructuredConnection => { connection = connect( { ...launch, + env: acpTextTaskEnv(spec.agent, launch.env), cwd, - args: spec.args({ fullAccess: false, pluginDir: null }), + args: acpTextTaskArgs(spec), envToDelete: [...launch.envToDelete, ...TASK_ENV_TO_DELETE] }, { clientInfo: { name: 'orca-chat-naming', version: '1' }, signIn: spec.signIn, - onPermission: reject, + onPermission: (request) => { + if (spec.agent !== 'antigravity') { + return reject() + } + return denyAcpTextTaskPermission(request) + }, onRequest: reject, onExtensionNotification: notification } @@ -218,12 +211,42 @@ export class AcpTextTasks { advertised: initialized.authMethods?.map((method) => method.id) ?? [], env: launch.env }) + if (spec.agent === 'grok' && grokTextTaskPreservesAccount(initialized, authMethodId)) { + headless = true + sessionId = promptId + if (authMethodId) { + await waitForPromiseWithSignal(server.authenticate(authMethodId), taskSignal) + } + checkCurrent() + return await runGrokTextTask({ + launch: { + ...launch, + args: [], + env: acpTextTaskEnv(spec.agent, launch.env), + envToDelete: [...launch.envToDelete, ...TASK_ENV_TO_DELETE] + }, + cwd, + prompt: namingPrompt, + sessionId, + signal: taskSignal, + timeoutMs: Math.max(1, deadlineAt - Date.now()) + }) + } starting = true await waitForPromiseWithSignal( server - .start({ cwd, mcpServers: [], authMethodId }) + .start({ + cwd, + mcpServers: [], + authMethodId, + ...(spec.agent === 'grok' ? { _meta: { yoloMode: false, autoMode: false } } : {}) + }) .then((started) => { sessionId = started.sessionId + modeConfigId = + started.response.configOptions?.find( + (option) => option.category === 'mode' && option.type === 'select' + )?.id ?? 'mode' }) .finally(() => { starting = false @@ -231,9 +254,16 @@ export class AcpTextTasks { }), taskSignal ) + if (spec.permissionModeConfig) { + await waitForPromiseWithSignal( + server.setConfigOption(modeConfigId, spec.permissionModeConfig.values.ask), + taskSignal + ) + } + checkCurrent() const response = await waitForPromiseWithSignal( Promise.race([ - server.prompt([{ type: 'text', text: input.prompt }], { promptId, requestId: promptId }), + server.prompt([{ type: 'text', text: namingPrompt }], { promptId, requestId: promptId }), terminal.promise ]), taskSignal @@ -253,25 +283,13 @@ export class AcpTextTasks { clearTimeout(timer) unsubscribe() deadline.abort() - const cleanup = async (work: () => Promise): Promise => { - try { - await waitForPromiseWithSignal(work(), AbortSignal.timeout(2_000)) - } catch (error) { - this.deps.logger?.warn('Naming helper protocol cleanup failed', { - scope: 'acp-text-task', - error - }) - } - } if (connection && sessionId) { const server = connection - if (!completed) { - await cleanup(() => server.cancel()) + if (!completed && !headless) { + await cleanupAcpTextTaskProtocol(() => server.cancel(), this.deps.logger) } if (spec.agent === 'grok') { - await cleanup(() => - server.requestExtension('_x.ai/session/delete', { sessionId, cwd }, 2_000) - ) + await cleanupGrokTextTaskSession(server, sessionId, cwd, this.deps.logger) } } if (connection && !(await connection.close().catch(() => false))) { diff --git a/src/main/grok/grok-text-task.ts b/src/main/grok/grok-text-task.ts new file mode 100644 index 00000000000..3f497293a64 --- /dev/null +++ b/src/main/grok/grok-text-task.ts @@ -0,0 +1,87 @@ +import type { InitializeResponse } from '../acp/generated/acp-protocol.generated' +import { + resolveProviderChildEnv, + type ProviderProcessLaunch +} from '../provider-process/provider-process-launch' +import { runLocalSourceControlPlan } from '../text-generation/source-control-local-process' +import { spawnSourceControlAgent } from '../text-generation/source-control-agent-launch' +import { cancelLocalGeneration } from '../text-generation/source-control-generation-lanes' + +export const GROK_TEXT_TASK_ENV = { GROK_STORAGE_MODE: 'local' } as const + +/** Headless eager authentication must select the same advertised method as the native chat task. */ +export function grokTextTaskPreservesAccount( + initialized: InitializeResponse, + expected: string | undefined +): boolean { + const methods = initialized.authMethods?.map((method) => method.id) ?? [] + const declared = initialized._meta?.defaultAuthMethodId + const selected = + typeof declared === 'string' && methods.includes(declared) + ? declared + : methods.includes('cached_token') + ? 'cached_token' + : methods[0] + return selected === expected +} + +/** The CLI applies this tool filter after resolving model-specific harnesses and saved grants. */ +export async function runGrokTextTask(input: { + launch: ProviderProcessLaunch & { prefixArgs: string[] } + cwd: string + prompt: string + sessionId: string + signal: AbortSignal + timeoutMs: number +}): Promise { + input.signal.throwIfAborted() + const args = [ + ...input.launch.prefixArgs, + '--session-id', + input.sessionId, + '--tools', + 'Read,Grep,Glob', + '--disallowed-tools', + 'search_tool,use_tool,Agent', + '--deny', + 'Bash,Edit,Write', + '--permission-mode', + 'default', + '--output-format', + 'plain', + '--prompt-file', + '{text-task-prompt}' + ] + const cancel = () => cancelLocalGeneration('conversation-name', input.cwd) + const execution = runLocalSourceControlPlan({ + plan: { + binary: input.launch.command, + args, + label: 'Grok', + stdinPayload: null, + taskFiles: [ + { name: 'text-task-prompt.txt', content: input.prompt, argIndex: args.length - 1 } + ] + }, + cwd: input.cwd, + operation: 'conversation-name', + env: { ...resolveProviderChildEnv(input.launch, process.env), ...GROK_TEXT_TASK_ENV }, + spawnAgent: spawnSourceControlAgent, + timeoutMs: input.timeoutMs + }) + input.signal.addEventListener('abort', cancel, { once: true }) + if (input.signal.aborted) { + cancel() + } + try { + const result = await execution.result + input.signal.throwIfAborted() + if (!result.success) { + throw new Error('Grok did not complete chat naming') + } + return result.rawOutput + } finally { + input.signal.removeEventListener('abort', cancel) + await execution.processClosed + } +} diff --git a/src/main/opencode/opencode-owned-text-task.test.ts b/src/main/opencode/opencode-owned-text-task.test.ts new file mode 100644 index 00000000000..63d9f008dd9 --- /dev/null +++ b/src/main/opencode/opencode-owned-text-task.test.ts @@ -0,0 +1,345 @@ +import { ChildProcess } from 'node:child_process' +import { createServer, type ServerResponse } from 'node:http' +import { PassThrough } from 'node:stream' +import { describe, expect, it, vi } from 'vitest' +import type { + SourceControlAgentSpawnInput, + SpawnedSourceControlAgentProcess +} from '../text-generation/source-control-text-generation-types' +import { OpenCodeTextTaskError, runOwnedOpenCodeTextTask } from './opencode-owned-text-task' +import { runOpenCodeTextTaskSession } from './opencode-text-task-session' +import type * as TextTaskSession from './opencode-text-task-session' + +vi.mock('./opencode-text-task-session', () => ({ runOpenCodeTextTaskSession: vi.fn() })) +const actual = await vi.importActual('./opencode-text-task-session') + +type FakeChild = SpawnedSourceControlAgentProcess & { + input: SourceControlAgentSpawnInput + stdout: PassThrough +} + +function fakeChild(input: SourceControlAgentSpawnInput): FakeChild { + const child = new ChildProcess() + Object.defineProperties(child, { + stdout: { writable: true, configurable: true, enumerable: true }, + stderr: { writable: true, configurable: true, enumerable: true }, + stdin: { writable: true, configurable: true, enumerable: true } + }) + return Object.assign(child, { + input, + pid: 4242, + stdin: new PassThrough(), + stdout: new PassThrough(), + stderr: new PassThrough() + }) +} + +function close(child: SpawnedSourceControlAgentProcess, code = 0): void { + Object.assign(child, { exitCode: code }) + child.emit('close', code) +} + +/** A CLI whose `--version` prints `version`; v2 serve exits on stdin end, v1 serve only when stopped. */ +function fakeOpenCode(version: string) { + const children: FakeChild[] = [] + const spawn = vi.fn((input: SourceControlAgentSpawnInput) => { + const child = fakeChild(input) + children.push(child) + if (input.args.includes('--version')) { + setImmediate(() => { + child.stdout.write(`${version}\n`) + close(child) + }) + } else if (input.args.includes('--stdio')) { + child.stdin?.on('finish', () => setImmediate(() => close(child))) + setImmediate(() => child.stdout.write('{"url":"http://127.0.0.1:4096/"}\n')) + } else { + setImmediate(() => child.stdout.write('opencode server listening on http://127.0.0.1:4097\n')) + } + return child + }) + const stop = vi.fn(async (child: SpawnedSourceControlAgentProcess) => { + await new Promise((resolve) => setImmediate(resolve)) + close(child, 143) + }) + return { children, spawn, stop } +} + +let cwd = 0 +function task(cli: ReturnType, signal = new AbortController().signal) { + return { + binary: '/opt/opencode/bin/opencode', + prefixArgs: ['--print-logs'], + // A distinct cwd keeps the shared version-probe cache from crossing tests. + cwd: `/work/repo-${++cwd}`, + env: { PATH: '/usr/bin', OPENCODE_CONFIG_CONTENT: '{"provider":{}}' }, + prompt: 'Name this chat', + runArgs: ['--agent', 'title'], + signal, + spawn: cli.spawn, + stop: cli.stop + } +} + +describe('runOwnedOpenCodeTextTask', () => { + it('runs the selected v2 choices on its own stdio server and returns after that server exits', async () => { + const cli = fakeOpenCode('2.0.14') + vi.mocked(runOpenCodeTextTaskSession).mockImplementationOnce(async () => { + expect(cli.children[1].exitCode).toBeNull() + return 'Harbor Lantern' + }) + const base = task(cli) + const input = { ...base, runArgs: [...base.runArgs, '--model', 'opencode/big-pickle#high'] } + + await expect(runOwnedOpenCodeTextTask(input)).resolves.toBe('Harbor Lantern') + + const server = cli.children[1] + expect(server.input.args).toEqual(['--print-logs', 'serve', '--stdio', '--port', '0']) + expect(server.input.cwd).toBe(input.cwd) + expect(server.input.env).toMatchObject({ + OPENCODE_CONFIG_CONTENT: '{"provider":{}}', + OPENCODE_PASSWORD: expect.any(String) + }) + expect(vi.mocked(runOpenCodeTextTaskSession).mock.calls[0][0]).toMatchObject({ + version: 'v2', + url: 'http://127.0.0.1:4096', + directory: input.cwd, + prompt: 'Name this chat', + agent: 'title', + model: { providerID: 'opencode', modelID: 'big-pickle' }, + variant: 'high' + }) + expect(server.exitCode).toBe(0) + expect(cli.stop).not.toHaveBeenCalled() + }) + + it('stops a v1 foreground server on cancel and rejects only once it has exited', async () => { + const cli = fakeOpenCode('1.18.31') + const controller = new AbortController() + vi.mocked(runOpenCodeTextTaskSession).mockImplementationOnce(async ({ signal }) => { + controller.abort(new Error('canceled by user')) + throw signal.reason + }) + + await expect(runOwnedOpenCodeTextTask(task(cli, controller.signal))).rejects.toThrow( + 'canceled by user' + ) + + const server = cli.children[1] + expect(server.input.args).toEqual([ + '--print-logs', + 'serve', + '--hostname', + '127.0.0.1', + '--port', + '0' + ]) + expect(server.input.env).toHaveProperty('OPENCODE_SERVER_PASSWORD') + expect(cli.stop).toHaveBeenCalledWith(server) + expect(server.exitCode).toBe(143) + }) + + it('never starts a server for an executable whose protocol is unknown', async () => { + const cli = fakeOpenCode('opencode development build') + + const error = await runOwnedOpenCodeTextTask(task(cli)).catch((caught: unknown) => caught) + + expect(error).toBeInstanceOf(OpenCodeTextTaskError) + expect(error).toMatchObject({ stage: 'startup' }) + expect(cli.children.map((child) => child.input.args)).toEqual([['--print-logs', '--version']]) + }) + it.each([ + ['1.2.27', 'conversation-name', true], + ['1.3.0-beta.1', 'commit-message', true], + ['1.3.0+build.7', 'commit-message', false], + ['1.18.31', 'conversation-name', false] + ] as const)( + 'authenticates V1 %s and preserves its acknowledged policy for %s', + async (version, operation, rejectsPermission) => { + vi.mocked(runOpenCodeTextTaskSession).mockImplementationOnce( + actual.runOpenCodeTextTaskSession + ) + const cli = fakeOpenCode(version) + let rejected = false + let events: ServerResponse | undefined + let completion: ServerResponse | undefined + const spawn = vi.fn((input: SourceControlAgentSpawnInput) => { + if (!input.args.includes('serve')) { + return cli.spawn(input) + } + const child = fakeChild(input) + // As the native server does: the configured username and password must both match. + const credential = `${input.env?.OPENCODE_SERVER_USERNAME ?? 'opencode'}:${input.env?.OPENCODE_SERVER_PASSWORD}` + const finish = () => { + completion! + .writeHead(200, { 'content-type': 'application/json' }) + .end(JSON.stringify({ info: {}, parts: [{ type: 'text', text: 'Harbor Lantern' }] })) + } + const server = createServer(async (request, response) => { + if ( + request.headers.authorization !== `Basic ${Buffer.from(credential).toString('base64')}` + ) { + response.writeHead(401).end() + return + } + const chunks: Buffer[] = [] + for await (const chunk of request) { + chunks.push(Buffer.from(chunk)) + } + const content = Buffer.concat(chunks).toString('utf8') + const body = content ? JSON.parse(content) : undefined + const path = request.url?.split('?')[0] + let result: unknown = {} + if (request.method === 'POST' && path === '/session') { + result = { + id: 'ses_1', + permission: [ + { permission: '*', pattern: '*', action: 'deny' }, + { permission: 'read', pattern: '*', action: 'allow' }, + { permission: 'grep', pattern: '*', action: 'allow' }, + { permission: 'glob', pattern: '*', action: 'allow' }, + { permission: 'external_directory', pattern: '*', action: 'allow' }, + { permission: 'read', pattern: 'mcp:*', action: 'deny' } + ] + } + } else if (path === '/agent') { + result = [{ name: 'title', mode: 'primary' }] + } else if (path === '/event') { + events = response + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.flushHeaders() + return + } else if (path === '/session/ses_1/message') { + expect(body).toMatchObject({ + agent: 'title', + parts: [{ type: 'text', text: 'Name this chat' }] + }) + expect(body).not.toHaveProperty('tools') + completion = response + if (rejectsPermission) { + for (const sessionID of ['foreign', 'ses_1']) { + events!.write( + `data: ${JSON.stringify({ type: 'permission.updated', properties: { sessionID, id: 'per_write' } })}\n\n` + ) + } + } else { + expect(events).toBeUndefined() + finish() + } + return + } else if (path === '/session/ses_1/permissions/per_write') { + expect(body).toEqual({ response: 'reject' }) + rejected = true + finish() + } else if (path === '/session/foreign/permissions/per_write') { + throw new Error('Borrowed permission must not be answered') + } + response + .writeHead(200, { 'content-type': 'application/json' }) + .end(JSON.stringify(result)) + }) + server.listen(0, '127.0.0.1', () => { + const address = server.address() + const port = address && typeof address === 'object' ? address.port : 0 + child.stdout.write(`opencode server listening on http://127.0.0.1:${port}\n`) + }) + child.once('close', () => server.close()) + return child + }) + const input = { + ...task({ ...cli, spawn }), + operation, + env: { PATH: '/usr/bin', OPENCODE_SERVER_USERNAME: 'custom' } + } + await expect(runOwnedOpenCodeTextTask(input)).resolves.toBe('Harbor Lantern') + expect(rejected).toBe(rejectsPermission) + } + ) +}) + +it.each(['v1', 'v2'] as const)( + 'uses the selected external naming server’s protocol and URL (%s)', + async (version) => { + const server = createServer((request, response) => { + if (request.url !== (version === 'v1' ? '/prefix/global/health' : '/api/info')) { + response.statusCode = 400 + } + response.setHeader('content-type', 'application/json') + response.end( + JSON.stringify({ + version: version === 'v1' ? '1.2.27' : '2.0.14', + pid: 23, + urls: [], + paths: { tmp: '/tmp' } + }) + ) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + try { + const address = server.address() + if (!address || typeof address === 'string') { + throw new Error('No endpoint') + } + const url = `http://127.0.0.1:${address.port}` + const cli = fakeOpenCode('1.18.31') + vi.mocked(runOpenCodeTextTaskSession).mockResolvedValueOnce('Harbor Lantern') + const input = { + ...task(cli), + operation: 'conversation-name' as const, + runArgs: [ + version === 'v1' ? '--attach' : '--server', + `${url}/prefix/`, + '--session', + 'saved', + '--model', + 'provider/model', + '--variant', + 'high' + ], + legacyVariantFlag: true + } + await expect(runOwnedOpenCodeTextTask(input)).resolves.toBe('Harbor Lantern') + expect(cli.spawn).not.toHaveBeenCalled() + expect(cli.stop).not.toHaveBeenCalled() + expect(vi.mocked(runOpenCodeTextTaskSession).mock.lastCall?.[0]).toMatchObject({ + version, + url: `${url}/prefix`, + sessionId: 'saved', + model: { providerID: 'provider', modelID: 'model' }, + variant: 'high', + exclusiveServer: false, + v1SessionPolicyFiltersTools: false + }) + if (version === 'v2') { + await expect( + runOwnedOpenCodeTextTask({ ...input, legacyVariantFlag: false }) + ).rejects.toMatchObject({ stage: 'startup' }) + } + await expect( + runOwnedOpenCodeTextTask({ ...input, operation: 'commit-message' }) + ).rejects.toMatchObject({ stage: 'startup' }) + } finally { + server.closeAllConnections() + await new Promise((resolve) => server.close(() => resolve())) + } + } +) + +it('suppresses implicit publication before owned startup while retaining explicit share configuration', async () => { + for (const share of [false, true]) { + const cli = fakeOpenCode('1.18.31') + vi.mocked(runOpenCodeTextTaskSession).mockResolvedValueOnce('Harbor Lantern') + const input = { + ...task(cli), + operation: 'conversation-name' as const, + runArgs: share ? ['--share'] : [], + env: { OPENCODE_DISABLE_SHARE: 'user-value', OPENCODE_CONFIG_CONTENT: '{"share":"auto"}' } + } + await expect(runOwnedOpenCodeTextTask(input)).resolves.toBe('Harbor Lantern') + expect(cli.children[1].input.env).toMatchObject({ + OPENCODE_DISABLE_SHARE: share ? 'user-value' : '1', + OPENCODE_CONFIG_CONTENT: '{"share":"auto"}' + }) + expect(cli.children[1].exitCode).not.toBeNull() + } +}) diff --git a/src/main/opencode/opencode-owned-text-task.ts b/src/main/opencode/opencode-owned-text-task.ts new file mode 100644 index 00000000000..8d58248d39b --- /dev/null +++ b/src/main/opencode/opencode-owned-text-task.ts @@ -0,0 +1,290 @@ +import { randomBytes } from 'node:crypto' +import { readOpenCodeTextTaskServerUrl } from './opencode-text-task-server-ready' +import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason' +import type { OpenCodeCliCapabilities } from '../../shared/opencode-cli-version' +import { probeOpenCodeCliVersion, type OpenCodeCliVersionProbe } from './opencode-cli-version' +import { runOpenCodeTextTaskSession } from './opencode-text-task-session' +import { readOpenCodeTextTaskServer } from './opencode-text-task-endpoint' +import { prepareOpenCodeTextTaskInput, openCodeTextTaskEndpoint } from './opencode-text-task-input' +import { waitForProcessExitUntil } from '../provider-process/provider-process-exit-deadline' +import type { + TextGenerationOperation, + SpawnedSourceControlAgentProcess, + SourceControlAgentSpawnInput +} from '../text-generation/source-control-text-generation-types' + +export type OpenCodeTextTaskSpawnContext = { + privateEnv?: Readonly> + captureVersion?: true +} + +/** Kept free of Electron/main-only imports: the WSL guest entry bundles this same task. */ +export type OwnedOpenCodeTextTask = { + binary: string + prefixArgs: readonly string[] + cwd: string + env: NodeJS.ProcessEnv + prompt: string + /** The recipe's `run` options; resolved against the probed release on this host's filesystem. */ + runArgs: readonly string[] + legacyVariantFlag?: boolean + operation?: TextGenerationOperation + signal: AbortSignal + spawn: ( + input: SourceControlAgentSpawnInput, + context?: OpenCodeTextTaskSpawnContext + ) => SpawnedSourceControlAgentProcess + readVersionStdout?: (stdout: string) => string | null + /** Force-stops a child that did not exit after its stdin closed. */ + stop: (child: SpawnedSourceControlAgentProcess) => Promise + probeVersion?: (probe: OpenCodeCliVersionProbe) => Promise + /** False before semantic input means the request is stale; nothing is prompted. */ + shouldExecute?: () => boolean +} + +/** `startup`: no session was prompted. `session`: the model ran and failed. `superseded`: shouldExecute refused. */ +export type OpenCodeTextTaskStage = 'startup' | 'session' | 'superseded' + +export class OpenCodeTextTaskError extends Error { + constructor( + readonly stage: OpenCodeTextTaskStage, + options?: { cause?: unknown } + ) { + super(`OpenCode text task failed during ${stage}`, options) + this.name = 'OpenCodeTextTaskError' + } +} + +const VERSION_PROBE_TIMEOUT_MS = 5_000 +const VERSION_OUTPUT_MAX_BYTES = 4_096 +const STDIN_CLOSE_GRACE_MS = 1_500 + +function closed(child: SpawnedSourceControlAgentProcess): Promise { + return new Promise((resolve) => { + child.once('close', () => resolve()) + }) +} + +async function closeOwned( + child: SpawnedSourceControlAgentProcess, + exited: Promise, + stop: OwnedOpenCodeTextTask['stop'] +): Promise { + // v2's stdio lease ends with stdin; v1 serve and stuck children need the owner's stop. + child.stdin?.end() + await waitForProcessExitUntil(exited, STDIN_CLOSE_GRACE_MS) + if (child.exitCode === null && child.signalCode === null) { + await stop(child) + } + // Ownership lasts until the exact process and its supervised group settle. + await exited +} + +function spawnOwned( + input: OwnedOpenCodeTextTask, + args: string[], + env: NodeJS.ProcessEnv, + cwd = input.cwd, + context?: OpenCodeTextTaskSpawnContext +): { child: SpawnedSourceControlAgentProcess; exited: Promise } { + const child = input.spawn( + { + binary: input.binary, + args, + cwd, + env, + stdinMode: 'pipe', + useCwdForNative: true + }, + context + ) + return { child, exited: closed(child) } +} + +/** Runs to its own bound rather than the task signal, so a cancel cannot cache an unknown version. */ +function probeVersion(input: OwnedOpenCodeTextTask): Promise { + return (input.probeVersion ?? probeOpenCodeCliVersion)({ + executablePath: input.binary, + // Prefixes select the CLI behind one launcher (e.g. `npx opencode` vs `npx opencode2`); the probe hashes this. + hostIdentity: JSON.stringify([process.platform, input.prefixArgs]), + cwd: input.cwd, + env: input.env, + execute: async () => { + const { child, exited } = spawnOwned( + input, + [...input.prefixArgs, '--version'], + input.env, + input.cwd, + { captureVersion: true } + ) + const ready = Promise.withResolvers() + let stdout = '' + let bytes = 0 + child.stdout?.on('data', (chunk: Buffer) => { + bytes += chunk.byteLength + if (bytes > VERSION_OUTPUT_MAX_BYTES) { + ready.reject(new Error('Version output too large')) + } else { + stdout += chunk.toString('utf8') + } + }) + child.stderr?.on('data', () => {}) + child.once('error', (error) => ready.reject(error)) + child.once('close', (code) => ready.resolve(code)) + child.stdin?.end() + try { + const code = await waitForPromiseWithSignal( + ready.promise, + AbortSignal.timeout(VERSION_PROBE_TIMEOUT_MS) + ) + return { + code, + stdout: input.readVersionStdout ? (input.readVersionStdout(stdout) ?? '') : stdout, + timedOut: false + } + } catch { + return { code: null, stdout, timedOut: true } + } finally { + await closeOwned(child, exited, input.stop) + } + } + }) +} + +function splitModel(task: { model?: string; variant?: string }, v2: boolean) { + let model = task.model + let variant = task.variant + // v2 recipes may carry the variant as `provider/model#variant`. + if (v2 && model?.includes('#')) { + const separator = model.lastIndexOf('#') + variant ??= model.slice(separator + 1) + model = model.slice(0, separator) + } + if (!model) { + return { variant } + } + const separator = model.indexOf('/') + if (separator <= 0) { + throw new Error('OpenCode model must include its provider') + } + return { + model: { providerID: model.slice(0, separator), modelID: model.slice(separator + 1) }, + variant + } +} + +/** + * One exclusive private server per task: probe the selected executable's protocol, start `serve`, + * run the policy-bound session, then close and await the server on every outcome. + */ +export async function runOwnedOpenCodeTextTask(input: OwnedOpenCodeTextTask): Promise { + const { signal } = input + const refuseStale = (): void => { + if (input.shouldExecute?.() === false) { + throw new OpenCodeTextTaskError('superseded') + } + } + let owned: ReturnType | undefined + let began = false + try { + signal.throwIfAborted() + refuseStale() + const endpoint = openCodeTextTaskEndpoint(input.runArgs, input.legacyVariantFlag) + let capabilities: OpenCodeCliCapabilities + if (endpoint) { + if (input.operation !== 'conversation-name') { + throw new Error('OpenCode external server is unavailable for this text task') + } + capabilities = await readOpenCodeTextTaskServer(endpoint, input.env, signal) + } else { + capabilities = await probeVersion(input) + } + signal.throwIfAborted() + refuseStale() + if (capabilities.pluginApi === 'unknown') { + throw new Error('OpenCode native protocol is unavailable') + } + const v2 = capabilities.pluginApi === 'v2' + const version = v2 ? 'v2' : 'v1' + const { directory, serverArgs, model, variant, ...run } = await prepareOpenCodeTextTaskInput({ + version, + cwd: input.cwd, + prompt: input.prompt, + runArgs: input.runArgs, + legacyVariantFlag: input.legacyVariantFlag, + operation: input.operation, + signal + }) + const selection = splitModel({ model, variant }, v2) + if (run.external) { + refuseStale() + began = true + return await runOpenCodeTextTaskSession({ + ...run, + ...selection, + version, + v1SessionPolicyFiltersTools: capabilities.v1SessionPolicyFiltersTools, + directory, + url: run.external.url, + username: v2 ? 'opencode' : (run.external.username ?? input.env.OPENCODE_SERVER_USERNAME), + password: + run.external.password ?? input.env[v2 ? 'OPENCODE_PASSWORD' : 'OPENCODE_SERVER_PASSWORD'], + exclusiveServer: false, + operation: input.operation, + shouldExecute: input.shouldExecute, + signal + }) + } + const password = randomBytes(32).toString('base64url') + const privateEnv: Record = v2 + ? { OPENCODE_PASSWORD: password } + : { OPENCODE_SERVER_USERNAME: 'opencode', OPENCODE_SERVER_PASSWORD: password } + if (!run.share) { + privateEnv.OPENCODE_DISABLE_SHARE = '1' + } + owned = spawnOwned( + input, + [ + ...input.prefixArgs, + 'serve', + ...serverArgs, + ...(v2 ? ['--stdio'] : ['--hostname', '127.0.0.1']), + '--port', + '0' + ], + { ...input.env, ...privateEnv }, + directory, + { privateEnv } + ) + const lost = new AbortController() + owned.child.once('close', () => lost.abort(new Error('OpenCode private server exited'))) + const taskSignal = AbortSignal.any([signal, lost.signal]) + const url = await readOpenCodeTextTaskServerUrl(owned.child, v2, taskSignal) + refuseStale() + began = true + return await runOpenCodeTextTaskSession({ + ...run, + ...selection, + version, + v1SessionPolicyFiltersTools: capabilities.v1SessionPolicyFiltersTools, + operation: input.operation, + shouldExecute: input.shouldExecute, + url, + password, + directory, + signal: taskSignal + }) + } catch (error) { + if (error instanceof OpenCodeTextTaskError) { + throw error + } + if (signal.aborted) { + throw signal.reason + } + throw new OpenCodeTextTaskError(began ? 'session' : 'startup', { cause: error }) + } finally { + if (owned) { + await closeOwned(owned.child, owned.exited, input.stop) + } + } +} diff --git a/src/main/opencode/opencode-text-task-endpoint.ts b/src/main/opencode/opencode-text-task-endpoint.ts new file mode 100644 index 00000000000..c69e8724c56 --- /dev/null +++ b/src/main/opencode/opencode-text-task-endpoint.ts @@ -0,0 +1,37 @@ +import { z } from 'zod' +import { getOpenCodeCliCapabilities } from '../../shared/opencode-cli-version' +import { createOpenCodeTextTaskHttp } from './opencode-text-task-http' +import type { openCodeTextTaskEndpoint } from './opencode-text-task-input' + +export async function readOpenCodeTextTaskServer( + endpoint: NonNullable>, + env: NodeJS.ProcessEnv, + signal: AbortSignal +) { + const password = + endpoint.password ?? + env[endpoint.version === 'v2' ? 'OPENCODE_PASSWORD' : 'OPENCODE_SERVER_PASSWORD'] + const http = createOpenCodeTextTaskHttp( + endpoint.url, + password, + '', + endpoint.version === 'v2' ? 'opencode' : (endpoint.username ?? env.OPENCODE_SERVER_USERNAME), + endpoint.version + ) + const info = z + .looseObject({ version: z.string() }) + .parse( + await http.request( + 'GET', + endpoint.version === 'v2' ? '/api/info' : '/global/health', + undefined, + signal + ) + ) + const capabilities = getOpenCodeCliCapabilities(info.version) + if (capabilities.pluginApi !== endpoint.version) { + throw new Error('OpenCode selected server has an incompatible protocol') + } + + return capabilities +} diff --git a/src/main/opencode/opencode-text-task-events.ts b/src/main/opencode/opencode-text-task-events.ts new file mode 100644 index 00000000000..118a33959f7 --- /dev/null +++ b/src/main/opencode/opencode-text-task-events.ts @@ -0,0 +1,198 @@ +import { z } from 'zod' +import { SearchSubprocessLineAccumulator } from '../../shared/search-subprocess-lines' +import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from '../text-generation/source-control-generation-limits' +import type { createOpenCodeTextTaskHttp } from './opencode-text-task-http' +import { openCodeTextTaskUrl } from './opencode-text-task-http' + +const event = z.looseObject({ + type: z.string(), + data: z.looseObject({ sessionID: z.string() }) +}) +const textEvent = z.looseObject({ + assistantMessageID: z.string(), + ordinal: z.number(), + text: z.string() +}) +const permissionEvent = z.looseObject({ id: z.string() }) +export function openCodeTextTaskEvents(input: { + version: 'v1' | 'v2' + url: string + signal: AbortSignal + lost: AbortController + messageID: string + context: () => { + sessionID: string + owned: boolean + ownedTree: Set + directory: string + http: ReturnType + } +}) { + const v2 = input.version === 'v2' + const base = v2 ? '/api/session' : '/session' + const terminal = Promise.withResolvers() + void terminal.promise.catch(() => {}) + const stream = new AbortController() + const streamSignal = AbortSignal.any([stream.signal, input.signal]) + let streamDone: Promise | undefined + let textBytes = 0 + let promoted = false + const assistants = new Set() + const texts = new Map() + const onEvent = async (value: unknown): Promise => { + const { sessionID, owned, ownedTree, http } = input.context() + const request = http.request + const raw = z + .looseObject({ type: z.string(), properties: z.unknown().optional() }) + .safeParse(value) + if (!v2 && owned && sessionID && raw.success && raw.data.type === 'session.created') { + const child = z + .looseObject({ info: z.looseObject({ id: z.string(), parentID: z.string().optional() }) }) + .safeParse(raw.data.properties) + if (child.success && child.data.info.parentID && ownedTree.has(child.data.info.parentID)) { + ownedTree.add(child.data.info.id) + } + return + } + const parsed = event.safeParse( + !v2 && raw.success ? { type: raw.data.type, data: raw.data.properties } : value + ) + if (!parsed.success || !sessionID) { + return + } + const { type, data } = parsed.data + if (type === 'permission.asked' || (!v2 && type === 'permission.updated')) { + // Native rejection fans out within a session: borrowed history cannot safely answer it. + if (ownedTree.has(data.sessionID)) { + const permission = permissionEvent.parse(data) + await request( + 'POST', + type === 'permission.updated' + ? `${base}/${encodeURIComponent(data.sessionID)}/permissions/${encodeURIComponent(permission.id)}` + : v2 + ? `${base}/${encodeURIComponent(data.sessionID)}/permission/${encodeURIComponent(permission.id)}/reply` + : `/permission/${encodeURIComponent(permission.id)}/reply`, + type === 'permission.updated' + ? { response: 'reject' } + : v2 + ? { decision: 'reject', message: 'Tools are unavailable for this text task.' } + : { reply: 'reject', message: 'Tools are unavailable for this text task.' }, + streamSignal + ) + } + return + } + if (data.sessionID !== sessionID) { + return + } + if (v2 && !owned) { + if (type === 'session.inbox.delivered') { + const delivered = z.looseObject({ inboxID: z.string() }).parse(data) + if (delivered.inboxID === input.messageID) { + promoted = true + } else if (promoted) { + terminal.reject(new Error('OpenCode naming input was superseded')) + } + return + } + if (!promoted) { + return + } + if (type === 'session.step.started') { + assistants.add( + z.looseObject({ assistantMessageID: z.string() }).parse(data).assistantMessageID + ) + } + } + if (type === 'session.text.ended') { + const text = textEvent.parse(data) + if (!owned && !assistants.has(text.assistantMessageID)) { + return + } + const key = `${text.assistantMessageID}:${text.ordinal}` + textBytes += Buffer.byteLength(text.text) - Buffer.byteLength(texts.get(key) ?? '') + if (textBytes > MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES) { + throw new Error('OpenCode text generation exceeded its output limit') + } + texts.set(key, text.text) + } else if (type === 'session.execution.succeeded') { + terminal.resolve([...texts.values()].join('\n').trim()) + } else if (type === 'session.execution.failed' || type === 'session.execution.interrupted') { + terminal.reject(new Error('OpenCode did not complete text generation')) + } + } + const subscribe = async (): Promise => { + const { directory, http } = input.context() + const response = await fetch( + openCodeTextTaskUrl( + input.url, + `${v2 ? '/api/event' : '/event'}${!v2 ? `?directory=${encodeURIComponent(directory)}` : ''}`, + input.version + ), + { headers: http.headers, signal: streamSignal } + ) + if (!response.ok || !response.body) { + throw new Error('OpenCode event stream is unavailable') + } + const reader = response.body.getReader() + streamDone = (async () => { + const lines = new SearchSubprocessLineAccumulator(MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES) + let pendingBytes = 0 + let frameBytes = 0 + let data: string[] = [] + try { + for (;;) { + const chunk = await reader.read() + if (chunk.done) { + throw new Error('OpenCode event stream closed before completion') + } + pendingBytes += chunk.value.byteLength + const frames: string[] = [] + const withinLimit = lines.push(Buffer.from(chunk.value), (rawLine) => { + const bytes = Buffer.byteLength(rawLine) + 1 + pendingBytes -= bytes + frameBytes += bytes + if (frameBytes > MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES) { + throw new Error('OpenCode text generation exceeded its output limit') + } + const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine + if (!line) { + if (data.length) { + frames.push(data.join('\n')) + } + data = [] + frameBytes = 0 + } else if (line.startsWith('data:')) { + data.push(line.slice(5).trimStart()) + } + }) + if (!withinLimit || frameBytes + pendingBytes > MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES) { + throw new Error('OpenCode text generation exceeded its output limit') + } + for (const frame of frames) { + await onEvent(JSON.parse(frame)) + } + } + } finally { + lines.clear() + await reader.cancel().catch(() => {}) + reader.releaseLock() + } + })().catch((error: unknown) => { + terminal.reject(error) + input.lost.abort(error) + }) + } + + return { + subscribe, + completion: terminal.promise, + get promoted() { + return promoted + }, + close: async () => { + stream.abort() + await streamDone + } + } +} diff --git a/src/main/opencode/opencode-text-task-files.ts b/src/main/opencode/opencode-text-task-files.ts new file mode 100644 index 00000000000..a25637b98c7 --- /dev/null +++ b/src/main/opencode/opencode-text-task-files.ts @@ -0,0 +1,62 @@ +import { open } from 'node:fs/promises' +import path from 'node:path' +const { lookup }: { lookup: (path: string) => string | false } = require('mime-types') + +export async function readTaskFile(file: string, directory: string, signal: AbortSignal) { + signal.throwIfAborted() + const filename = path.resolve(directory, file) + const handle = await open(filename, 'r') + try { + const info = await handle.stat() + if (!info.isFile() || info.size > 10 * 1024 * 1024) { + throw new Error('OpenCode attachment must be a regular file no larger than 10 MiB') + } + const content = Buffer.alloc(info.size) + let offset = 0 + while (offset < content.length) { + signal.throwIfAborted() + const read = await handle.read(content, offset, content.length - offset, offset) + if (read.bytesRead === 0) { + break + } + offset += read.bytesRead + } + return { filename, bytes: content.subarray(0, offset) } + } finally { + await handle.close() + } +} + +export async function prepareV2File(file: string, directory: string, signal: AbortSignal) { + const { filename, bytes } = await readTaskFile(file, directory, signal) + const detected = lookup(filename) || 'application/octet-stream' + const name = path.basename(filename) + if (detected.startsWith('image/') || detected === 'application/pdf') { + return { attachment: { name, uri: `data:${detected};base64,${bytes.toString('base64')}` } } + } + const text = bytes.toString('utf8') + const binary = + bytes.includes(0) || + (bytes.length > 0 && + bytes.reduce((count, byte) => count + Number(byte < 9 || (byte > 13 && byte < 32)), 0) / + bytes.length > + 0.3) + const mime = !binary && Buffer.from(text, 'utf8').equals(bytes) ? 'text/plain' : detected + return mime === 'text/plain' + ? { text: `\n${text}\n` } + : { attachment: { name, uri: `data:${mime};base64,${bytes.toString('base64')}` } } +} + +export async function prepareV1File(file: string, directory: string, signal: AbortSignal) { + const { filename, bytes } = await readTaskFile(file, directory, signal) + const text = bytes.toString('utf8') + const mime = Buffer.from(text, 'utf8').equals(bytes) + ? 'text/plain' + : lookup(filename) || 'application/octet-stream' + return { + type: 'file' as const, + mime, + filename: path.basename(filename), + url: `data:${mime};base64,${bytes.toString('base64')}` + } +} diff --git a/src/main/opencode/opencode-text-task-http.ts b/src/main/opencode/opencode-text-task-http.ts new file mode 100644 index 00000000000..815c9281025 --- /dev/null +++ b/src/main/opencode/opencode-text-task-http.ts @@ -0,0 +1,75 @@ +import { z } from 'zod' +import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from '../text-generation/source-control-generation-limits' + +const envelope = z.looseObject({ data: z.unknown().optional() }) + +function unwrap(value: unknown): unknown { + const parsed = envelope.safeParse(value) + return parsed.success && parsed.data.data !== undefined ? parsed.data.data : value +} + +async function readBounded(response: Response): Promise { + if (!response.body) { + return '' + } + const reader = response.body.getReader() + const decoder = new TextDecoder() + let bytes = 0 + let text = '' + try { + for (;;) { + const chunk = await reader.read() + if (chunk.done) { + return text + decoder.decode() + } + bytes += chunk.value.byteLength + if (bytes > MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES) { + throw new Error('OpenCode text generation exceeded its output limit') + } + text += decoder.decode(chunk.value, { stream: true }) + } + } finally { + await reader.cancel().catch(() => {}) + reader.releaseLock() + } +} + +export function openCodeTextTaskUrl(url: string, path: string, version: 'v1' | 'v2'): string { + return version === 'v1' ? url.replace(/\/$/, '') + path : new URL(path, url).toString() +} + +export function createOpenCodeTextTaskHttp( + url: string, + password: string | undefined, + query: string, + username = 'opencode', + version: 'v1' | 'v2' = 'v1' +) { + const headers = { + ...(password + ? { authorization: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}` } + : {}), + 'content-type': 'application/json' + } + const requestRaw = async ( + method: string, + path: string, + body: unknown, + signal: AbortSignal + ): Promise => { + const response = await fetch(openCodeTextTaskUrl(url, `${path}${query}`, version), { + method, + headers, + signal, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) + }) + if (!response.ok) { + await response.body?.cancel() + throw new Error('OpenCode rejected the text generation request') + } + const text = await readBounded(response) + return text ? JSON.parse(text) : undefined + } + const request: typeof requestRaw = async (...args) => unwrap(await requestRaw(...args)) + return { headers, request, requestRaw } +} diff --git a/src/main/opencode/opencode-text-task-input.test.ts b/src/main/opencode/opencode-text-task-input.test.ts new file mode 100644 index 00000000000..bf5a8f69653 --- /dev/null +++ b/src/main/opencode/opencode-text-task-input.test.ts @@ -0,0 +1,278 @@ +import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { pathToFileURL } from 'node:url' +import { afterEach, expect, it, vi } from 'vitest' +import { planCommitMessageGeneration } from '../../shared/source-control/ai/generation/commit-message-plan' +import { prepareOpenCodeTextTaskInput } from './opencode-text-task-input' + +const roots: string[] = [] +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) +async function workspace() { + const root = await mkdtemp(path.join(tmpdir(), 'opencode-text-input-')) + roots.push(root) + await mkdir(path.join(root, 'nested')) + await writeFile(path.join(root, 'context.txt'), 'original context') + return root +} + +it('preserves recipe directory, relative attachment, positional input and global behavior', async () => { + const cwd = await workspace() + const planned = planCommitMessageGeneration( + { + agentId: 'opencode', + model: 'default', + agentCommandOverride: 'opencode --pure', + agentArgs: + '--dir nested --file ../context.txt --agent custom --title=Recipe -- "extra instructions"' + }, + 'generated input' + ) + if (!planned.ok || !planned.plan.openCodeTask) { + throw new Error('No OpenCode plan') + } + const input = await prepareOpenCodeTextTaskInput({ + version: 'v1', + cwd, + prompt: 'generated input', + runArgs: planned.plan.openCodeTask.runArgs, + signal: new AbortController().signal + }) + expect(input).toMatchObject({ + directory: path.join(cwd, 'nested'), + prompt: '"extra instructions"\ngenerated input', + serverArgs: ['--pure'], + agent: 'custom', + title: 'Recipe', + v1Files: [ + { + type: 'file', + filename: 'context.txt', + mime: 'text/plain', + url: pathToFileURL(path.join(cwd, 'context.txt')).href + } + ] + }) +}) + +it('projects v2 text files and binary attachments into the vendor native request shape', async () => { + const cwd = await workspace() + await writeFile(path.join(cwd, 'diagram.png'), Buffer.from([137, 80, 78, 71])) + const input = await prepareOpenCodeTextTaskInput({ + version: 'v2', + cwd, + prompt: 'generated input', + runArgs: [ + '--file', + 'context.txt', + '--file=diagram.png', + '--model=provider/model#low', + '--', + 'extra' + ], + signal: new AbortController().signal + }) + expect(input.prompt).toBe( + 'extra\ngenerated input\n\n\noriginal context\n' + ) + expect(input.v2Files).toEqual([{ name: 'diagram.png', uri: 'data:image/png;base64,iVBORw==' }]) + expect(input.model).toBe('provider/model#low') + await expect( + prepareOpenCodeTextTaskInput({ + version: 'v2', + cwd, + prompt: 'input', + runArgs: ['--dir', 'nested'], + signal: new AbortController().signal + }) + ).rejects.toThrow('unsupported') +}) + +it('retains wrapper operands outside the run parser and keeps command arguments distinct', async () => { + const cwd = await workspace() + await writeFile(path.join(cwd, 'notes.txt'), 'read-only context') + const planned = planCommitMessageGeneration( + { + agentId: 'opencode', + model: 'opencode/gpt-5.4-mini', + agentCommandOverride: + 'npx --yes opencode --model opencode/gpt-5.5 --log-level DEBUG --dir . --file notes.txt', + agentArgs: '--command review --agent build -- extra' + }, + 'generated input' + ) + if (!planned.ok || !planned.plan.openCodeTask) { + throw new Error('No OpenCode plan') + } + expect(planned.plan.openCodeTask.prefixArgs).toEqual(['--yes', 'opencode']) + const input = await prepareOpenCodeTextTaskInput({ + version: 'v1', + cwd, + prompt: 'generated input', + runArgs: planned.plan.openCodeTask.runArgs, + signal: new AbortController().signal + }) + expect(input).toMatchObject({ + command: 'review', + prompt: 'extra\ngenerated input', + agent: 'build', + model: 'opencode/gpt-5.5', + serverArgs: ['--log-level', 'DEBUG'], + v1Files: [ + { + type: 'file', + mime: 'text/plain', + filename: 'notes.txt', + url: expect.stringContaining('/notes.txt') + } + ] + }) +}) + +it('keeps a wrapper run operand attached to the selected executable', async () => { + const planned = planCommitMessageGeneration( + { + agentId: 'opencode', + model: 'default', + agentCommandOverride: 'pnpm run opencode' + }, + 'generated input' + ) + if (!planned.ok || !planned.plan.openCodeTask) { + throw new Error('No OpenCode plan') + } + expect(planned.plan.binary).toBe('pnpm') + expect(planned.plan.openCodeTask.prefixArgs).toEqual(['run', 'opencode']) + const input = await prepareOpenCodeTextTaskInput({ + version: 'v1', + cwd: await workspace(), + prompt: 'generated input', + runArgs: planned.plan.openCodeTask.runArgs, + signal: new AbortController().signal + }) + expect(input.prompt).toBe('generated input') +}) + +it('preserves the original OpenCode v2 variant compatibility without accepting it for other recipes', async () => { + const cwd = await workspace() + for (const model of ['provider/model', 'provider/model#high']) { + const input = await prepareOpenCodeTextTaskInput({ + version: 'v2', + cwd, + prompt: 'input', + legacyVariantFlag: true, + runArgs: ['--model', model, '--variant', 'low'], + signal: new AbortController().signal + }) + expect(input.model).toBe('provider/model#low') + expect(input.variant).toBeUndefined() + expect(input.serverArgs).toEqual([]) + } + await expect( + prepareOpenCodeTextTaskInput({ + version: 'v2', + cwd, + prompt: 'input', + runArgs: ['--model', 'provider/model', '--variant', 'low'], + signal: new AbortController().signal + }) + ).rejects.toThrow('unsupported') + await expect( + prepareOpenCodeTextTaskInput({ + version: 'v2', + cwd, + prompt: 'input', + legacyVariantFlag: true, + runArgs: ['--variant', 'low'], + signal: new AbortController().signal + }) + ).rejects.toThrow('requires a model') +}) + +it('projects npx delimiter arguments without consuming the provider terminator', async () => { + const cwd = await workspace() + await writeFile(path.join(cwd, 'nested', 'notes.txt'), 'selected context') + const planned = planCommitMessageGeneration( + { + agentId: 'opencode', + model: 'default', + agentCommandOverride: 'npx -- opencode --dir nested --file notes.txt' + }, + 'Name this chat' + ) + if (!planned.ok || !planned.plan.openCodeTask) { + throw new Error('Missing native task') + } + expect(planned.plan.openCodeTask.prefixArgs).toEqual(['--', 'opencode']) + const input = await prepareOpenCodeTextTaskInput({ + version: 'v1', + cwd, + prompt: 'Name this chat', + runArgs: planned.plan.openCodeTask.runArgs, + signal: new AbortController().signal + }) + expect(input.directory).toBe(path.join(cwd, 'nested')) + expect(input.v1Files).toEqual([ + { + type: 'file', + mime: 'text/plain', + filename: 'notes.txt', + url: pathToFileURL(path.join(cwd, 'nested', 'notes.txt')).href + } + ]) + const positional = planCommitMessageGeneration( + { agentId: 'opencode', model: 'default', agentCommandOverride: 'npx -- opencode -- literal' }, + 'input' + ) + if (!positional.ok || !positional.plan.openCodeTask) { + throw new Error('Missing native task') + } + expect(positional.plan.openCodeTask.prefixArgs).toEqual(['--', 'opencode']) + expect(positional.plan.openCodeTask.runArgs.slice(0, 2)).toEqual(['--', 'literal']) +}) + +it('does no text decoding or binary classification for known MIME files at N and 10N bytes', async () => { + const cwd = await workspace() + for (const size of [1024 * 1024, 10 * 1024 * 1024]) { + const bytes = Buffer.alloc(size, 65) + await writeFile(path.join(cwd, 'document.pdf'), bytes) + const decode = vi.spyOn(Buffer.prototype, 'toString') + const classify = vi.spyOn(Buffer.prototype, 'includes') + const input = await prepareOpenCodeTextTaskInput({ + version: 'v2', + cwd, + prompt: 'input', + runArgs: ['--file', 'document.pdf'], + signal: new AbortController().signal + }) + const decodedBytes = decode.mock.calls.reduce( + (count, args, index) => count + (args[0] === 'utf8' ? decode.mock.contexts[index].length : 0), + 0 + ) + const classifiedBytes = classify.mock.contexts.reduce( + (count, buffer) => count + buffer.length, + 0 + ) + decode.mockRestore() + classify.mockRestore() + expect(decodedBytes).toBe(0) + expect(classifiedBytes).toBe(0) + expect(input.prompt).toBe('input') + expect(input.v2Files).toEqual([ + { name: 'document.pdf', uri: `data:application/pdf;base64,${bytes.toString('base64')}` } + ]) + } + await writeFile(path.join(cwd, 'unknown.data'), Buffer.from([0, 255, 1])) + const input = await prepareOpenCodeTextTaskInput({ + version: 'v2', + cwd, + prompt: 'input', + runArgs: ['--file', 'unknown.data'], + signal: new AbortController().signal + }) + expect(input.v2Files).toEqual([ + { name: 'unknown.data', uri: 'data:application/octet-stream;base64,AP8B' } + ]) +}) diff --git a/src/main/opencode/opencode-text-task-input.ts b/src/main/opencode/opencode-text-task-input.ts new file mode 100644 index 00000000000..91a133d0ac2 --- /dev/null +++ b/src/main/opencode/opencode-text-task-input.ts @@ -0,0 +1,302 @@ +import { findOptionOccurrence } from '../../shared/command-option-occurrence' +import { stat } from 'node:fs/promises' +import { prepareV1File, prepareV2File } from './opencode-text-task-files' +import path from 'node:path' +import type { TextGenerationOperation } from '../text-generation/source-control-text-generation-types' +import { pathToFileURL } from 'node:url' + +export type OpenCodeTextTaskInput = { + directory: string + /** Absent on an attached server until its source/default location is resolved there. */ + externalDirectory?: string + external?: { url: string; username?: string; password?: string } + sessionId?: string + continue?: boolean + fork?: boolean + share?: boolean + prompt: string + serverArgs: string[] + agent?: string + model?: string + variant?: string + title?: string + command?: string + v1Files?: { type: 'file'; mime: string; filename: string; url: string }[] + v2Files?: { uri: string; name: string }[] +} + +const aliases: Record = { + m: 'model', + f: 'file', + c: 'continue', + s: 'session', + p: 'password', + u: 'username', + i: 'interactive' +} +const commonStrings = ['model', 'agent', 'format', 'file', 'title', 'session'] +const commonBooleans = [ + 'continue', + 'fork', + 'thinking', + 'auto', + 'yolo', + 'dangerously-skip-permissions', + 'print-logs' +] +const v1Strings = [ + 'command', + 'attach', + 'password', + 'username', + 'dir', + 'port', + 'variant', + 'replay-limit', + 'log-level' +] +const v1Booleans = ['share', 'mini', 'replay', 'interactive', 'demo', 'pure'] + +export function openCodeTextTaskEndpoint(args: readonly string[], legacyVariantFlag = false) { + const valueOptions = [ + ...commonStrings.map((name) => `--${name}`), + ...v1Strings.map((name) => `--${name}`), + '--server', + '-m', + '-f', + '-s', + '-p', + '-u' + ] + const attached = findOptionOccurrence(args, ['--attach'], true, valueOptions, 0, 'required') + const server = findOptionOccurrence(args, ['--server'], true, valueOptions, 0, 'required') + if (!attached && !server) { + return undefined + } + if (attached && server) { + throw new Error('OpenCode server options cannot be combined') + } + const option = attached ?? server! + if (!option.value) { + throw new Error('OpenCode server option requires a value') + } + const parsed = parseRunArgs(args, !!server, legacyVariantFlag) + return { + version: server ? ('v2' as const) : ('v1' as const), + url: option.value, + username: parsed.values.get('username'), + password: parsed.values.get('password') + } +} + +function parseRunArgs(args: readonly string[], v2: boolean, legacyVariantFlag: boolean) { + const values = new Map() + const flags = new Map() + const files: string[] = [] + const message: string[] = [] + const strings = new Set([ + ...commonStrings, + ...(v2 ? ['server', ...(legacyVariantFlag ? ['variant'] : [])] : v1Strings) + ]) + const booleans = new Set([...commonBooleans, ...(v2 ? ['standalone'] : v1Booleans)]) + for (let index = 0; index < args.length; index++) { + const token = args[index] + if (token === '--') { + message.push(...args.slice(index + 1)) + break + } + if (token === '-' || !token.startsWith('-')) { + message.push(token) + continue + } + const match = token.match(/^--([^=]+)(?:=(.*))?$/) ?? token.match(/^-([a-z])(.*)$/) + if (!match) { + throw new Error('OpenCode run option is invalid') + } + let name = aliases[match[1]] ?? match[1] + let value: string | undefined = match[2] + if (!token.startsWith('--') && !value) { + value = undefined + } + const negated = name.startsWith('no-') + if (negated) { + name = name.slice(3) + } + if (booleans.has(name)) { + if (value !== undefined && value !== 'true' && value !== 'false') { + throw new Error('OpenCode boolean run option is invalid') + } + if (value === undefined && ['true', 'false'].includes(args[index + 1])) { + value = args[++index] + } + flags.set(name, negated ? false : value !== 'false') + continue + } + if (!strings.has(name) || negated) { + throw new Error('OpenCode run option is unsupported') + } + if (value === undefined) { + if (args[index + 1] !== undefined && !args[index + 1].startsWith('-')) { + value = args[++index] + } else if (name === 'title' && !v2) { + value = '' + } else { + throw new Error('OpenCode run option requires a value') + } + } + if (name === 'file') { + files.push(value) + // v1's yargs file option is an array; v2's repeated flag consumes one value. + if (!v2 && !token.includes('=')) { + while (args[index + 1] !== undefined && !args[index + 1].startsWith('-')) { + files.push(args[++index]) + } + } + } else { + if (values.has(name)) { + throw new Error('OpenCode singleton run option is repeated') + } + values.set(name, value) + } + } + return { values, flags, files, message } +} + +/** Resolve the selected CLI's run contract on the host that owns its filesystem. */ +export async function prepareOpenCodeTextTaskInput(input: { + version: 'v1' | 'v2' + cwd: string + prompt: string + runArgs: readonly string[] + signal: AbortSignal + agent?: string + model?: string + variant?: string + legacyVariantFlag?: boolean + operation?: TextGenerationOperation +}): Promise { + input.signal.throwIfAborted() + const v2 = input.version === 'v2' + const { values, flags, files, message } = parseRunArgs( + input.runArgs, + v2, + input.legacyVariantFlag === true + ) + let model = values.get('model') ?? input.model + if (v2 && values.has('variant')) { + if (!model) { + throw new Error('OpenCode variant compatibility requires a model') + } + // Preserve the existing pre-prompt CLI compatibility projection, including suffix precedence. + model = `${model.split('#')[0]}#${values.get('variant')}` + } + if (values.has('format') && !['default', 'json'].includes(values.get('format')!)) { + throw new Error('OpenCode output format is invalid') + } + if (flags.get('mini') || flags.get('demo') || values.has('replay-limit')) { + throw new Error('OpenCode interactive invocation cannot run as a hidden text task') + } + if (flags.get('fork') && !flags.get('continue') && !values.has('session')) { + throw new Error('OpenCode fork requires a session') + } + // These modes have user-owned history/account/retention semantics; never silently discard them. + if ( + input.operation !== 'conversation-name' && + (flags.get('continue') || + flags.get('fork') || + flags.get('share') || + ['session', 'attach', 'server', 'password', 'username'].some((name) => values.has(name))) + ) { + throw new Error('OpenCode text task requires a fresh private session') + } + if (v2 && values.has('server') && flags.get('standalone')) { + throw new Error('OpenCode server and standalone cannot be combined') + } + const endpoint = values.get(v2 ? 'server' : 'attach') + const directory = path.resolve(input.cwd, values.get('dir') || '.') + const positional = message + .map((part) => (part.includes(' ') ? `"${part.replace(/"/g, '\\"')}"` : part)) + .join(' ') + let prompt = + positional && input.prompt ? `${positional}\n${input.prompt}` : positional || input.prompt + if (!prompt.trim() && !values.has('command')) { + throw new Error('OpenCode text task has no input') + } + const serverArgs: string[] = [] + if (flags.get('print-logs')) { + serverArgs.push('--print-logs') + } + if (!v2 && flags.get('pure')) { + serverArgs.push('--pure') + } + if (values.has('log-level')) { + const level = values.get('log-level')! + if (!['DEBUG', 'INFO', 'WARN', 'ERROR'].includes(level)) { + throw new Error('OpenCode log level is invalid') + } + serverArgs.push('--log-level', level) + } + const result: OpenCodeTextTaskInput = { + directory, + prompt, + serverArgs, + ...(endpoint + ? { + external: { + url: new URL(endpoint).toString().replace(/\/$/, ''), + username: values.get('username'), + password: values.get('password') + }, + externalDirectory: values.get('dir') + } + : {}), + ...(values.has('session') ? { sessionId: values.get('session') } : {}), + ...(flags.get('continue') ? { continue: true } : {}), + ...(flags.get('fork') ? { fork: true } : {}), + ...(flags.get('share') ? { share: true } : {}), + agent: values.get('agent') ?? input.agent, + model, + variant: v2 ? input.variant : (values.get('variant') ?? input.variant), + command: values.get('command'), + title: values.has('title') + ? values.get('title') || prompt.slice(0, 50) + (prompt.length > 50 ? '...' : '') + : undefined + } + if (v2) { + if (files.length > 100) { + throw new Error('OpenCode accepts at most 100 attachments') + } + const text: string[] = [] + result.v2Files = [] + for (const file of files) { + const prepared = await prepareV2File(file, endpoint ? input.cwd : directory, input.signal) + if (prepared.text) { + text.push(prepared.text) + } + if (prepared.attachment) { + result.v2Files.push(prepared.attachment) + } + } + prompt = [prompt, ...text].join('\n\n') + result.prompt = prompt + } else { + result.v1Files = [] + for (const file of files) { + input.signal.throwIfAborted() + const filename = path.resolve(endpoint ? input.cwd : directory, file) + if (endpoint) { + result.v1Files.push(await prepareV1File(file, input.cwd, input.signal)) + continue + } + const info = await stat(filename) + result.v1Files.push({ + type: 'file', + mime: info.isDirectory() ? 'application/x-directory' : 'text/plain', + filename: path.basename(filename), + url: pathToFileURL(filename).href + }) + } + } + input.signal.throwIfAborted() + return result +} diff --git a/src/main/opencode/opencode-text-task-legacy-policy.test.ts b/src/main/opencode/opencode-text-task-legacy-policy.test.ts new file mode 100644 index 00000000000..3ffb1932cb0 --- /dev/null +++ b/src/main/opencode/opencode-text-task-legacy-policy.test.ts @@ -0,0 +1,244 @@ +import { createServer, type ServerResponse } from 'node:http' +import { once } from 'node:events' +import { afterEach, expect, it } from 'vitest' +import { runOpenCodeTextTaskSession } from './opencode-text-task-session' + +const servers: ReturnType[] = [] +const appliedV1Policy = [ + { permission: '*', pattern: '*', action: 'deny' }, + { permission: 'read', pattern: '*', action: 'allow' }, + { permission: 'grep', pattern: '*', action: 'allow' }, + { permission: 'glob', pattern: '*', action: 'allow' }, + { permission: 'external_directory', pattern: '*', action: 'allow' }, + { permission: 'read', pattern: 'mcp:*', action: 'deny' } +] +afterEach(async () => { + await Promise.all( + servers.splice(0).map(async (server) => { + server.closeAllConnections() + await new Promise((resolve) => server.close(() => resolve())) + }) + ) +}) + +async function fixture( + handle: (path: string, body: unknown, response: ServerResponse) => void | Promise +) { + const server = createServer(async (request, response) => { + const chunks: Buffer[] = [] + for await (const chunk of request) { + chunks.push(Buffer.from(chunk)) + } + const body = Buffer.concat(chunks).toString('utf8') + await handle(`${request.method} ${request.url}`, body ? JSON.parse(body) : undefined, response) + }) + servers.push(server) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const address = server.address() + if (!address || typeof address === 'string') { + throw new Error('Missing test address') + } + return `http://127.0.0.1:${address.port}` +} + +function json(response: ServerResponse, value: unknown) { + response.setHeader('content-type', 'application/json') + response.end(JSON.stringify(value)) +} + +it.each(['commit-message', 'conversation-name'] as const)( + 'keeps selected helpers working best effort without a create policy (%s)', + async (operation) => { + const requests = new Map() + const url = await fixture((path, body, response) => { + requests.set(path, body) + if (path.startsWith('POST /session?')) { + json(response, { id: 'legacy' }) + } else if (path.startsWith('GET /event?')) { + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.flushHeaders() + } else if (path.startsWith('POST /session/legacy/message?')) { + json(response, { info: {}, parts: [{ type: 'text', text: 'Harbor Lantern' }] }) + } else { + json(response, true) + } + }) + const result = runOpenCodeTextTaskSession({ + version: 'v1', + v1SessionPolicyFiltersTools: true, + url, + operation, + directory: '/workspace', + prompt: 'Name only', + model: { providerID: 'selected', modelID: 'model' }, + variant: 'low', + v1Files: [ + { type: 'file', mime: 'text/plain', filename: 'notes.txt', url: 'file:///notes.txt' } + ], + signal: new AbortController().signal + }) + await expect(result).resolves.toBe('Harbor Lantern') + expect(requests.get('POST /session/legacy/message?directory=%2Fworkspace')).toEqual({ + messageID: expect.stringMatching(/^msg_[0-9a-f]{12}[0-9A-Za-z]{14}$/), + model: { providerID: 'selected', modelID: 'model' }, + variant: 'low', + parts: [ + { type: 'file', mime: 'text/plain', filename: 'notes.txt', url: 'file:///notes.txt' }, + { type: 'text', text: 'Name only' } + ], + tools: { + '*': false, + read: true, + grep: true, + glob: true, + external_directory: true, + bash: false, + edit: false, + write: false, + patch: false, + apply_patch: false, + multiedit: false, + task: false, + todowrite: false + } + }) + expect(requests.has('GET /event?directory=%2Fworkspace')).toBe(true) + expect(requests.has('DELETE /session/legacy?directory=%2Fworkspace')).toBe(true) + } +) + +it.each(['permission.updated', 'permission.asked'])( + 'keeps a legacy fork command and rejects its owned %s through the native route', + async (type) => { + const requests = new Map() + let events: ServerResponse | undefined + let command: ServerResponse | undefined + const rejectPath = + type === 'permission.updated' + ? 'POST /session/forked/permissions/per_write?directory=%2Fworkspace' + : 'POST /permission/per_write/reply?directory=%2Fworkspace' + const url = await fixture((path, body, response) => { + requests.set(path, body) + if (path.startsWith('GET /session/saved?')) { + json(response, { id: 'saved', directory: '/workspace' }) + } else if (path.startsWith('GET /agent?')) { + json(response, [{ name: 'configured', mode: 'primary' }]) + } else if (path.startsWith('GET /command?')) { + json(response, [{ name: 'inspect', agent: 'configured' }]) + } else if (path.startsWith('POST /session/saved/fork?')) { + json(response, { id: 'forked' }) + } else if (path.startsWith('PATCH /session/forked?')) { + json(response, { id: 'forked', permission: [] }) + } else if (path.startsWith('GET /event?')) { + events = response + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.flushHeaders() + } else if (path.startsWith('POST /session/forked/command?')) { + command = response + events!.write( + `data: ${JSON.stringify({ type, properties: { sessionID: 'forked', id: 'per_write' } })}\n\n` + ) + } else if (path === rejectPath) { + expect(body).toMatchObject( + type === 'permission.updated' ? { response: 'reject' } : { reply: 'reject' } + ) + json(response, true) + json(command!, { info: {}, parts: [{ type: 'text', text: 'Harbor Lantern' }] }) + } else { + json(response, true) + } + }) + await expect( + runOpenCodeTextTaskSession({ + version: 'v1', + v1SessionPolicyFiltersTools: true, + url, + directory: '/workspace', + operation: 'conversation-name', + sessionId: 'saved', + fork: true, + command: 'inspect', + agent: 'configured', + model: { providerID: 'selected', modelID: 'model' }, + prompt: 'Name only', + signal: new AbortController().signal + }) + ).resolves.toBe('Harbor Lantern') + expect(requests.get('POST /session/forked/command?directory=%2Fworkspace')).toEqual({ + messageID: expect.stringMatching(/^msg_[0-9a-f]{12}[0-9A-Za-z]{14}$/), + command: 'inspect', + arguments: 'Name only', + agent: 'configured', + model: 'selected/model' + }) + expect(requests.has(rejectPath)).toBe(true) + expect(requests.has('DELETE /session/forked?directory=%2Fworkspace')).toBe(true) + expect( + [...requests.keys()].some((path) => /(?:PATCH|DELETE) \/session\/saved\?/.test(path)) + ).toBe(false) + } +) + +it.each(['applied', 'http-error', 'wrong-id', 'conflicting'])( + 'forks only the selected source and requires policy acknowledgement (%s)', + async (outcome) => { + const requests: string[] = [] + let policy: unknown + const url = await fixture((path, body, response) => { + requests.push(path) + if (path.startsWith('GET /session/saved?')) { + json(response, { id: 'saved', directory: '/workspace' }) + } else if (path.startsWith('POST /session/saved/fork?')) { + json(response, { id: 'forked' }) + } else if (path.startsWith('PATCH /session/forked?')) { + policy = body + if (outcome === 'http-error') { + response.statusCode = 400 + } + json(response, { + id: outcome === 'wrong-id' ? 'source' : 'forked', + permission: + outcome === 'conflicting' + ? [...appliedV1Policy, { permission: 'edit', pattern: '*', action: 'allow' }] + : [{ permission: 'bash', pattern: '*', action: 'allow' }, ...appliedV1Policy] + }) + } else if (path.startsWith('POST /session/forked/message?')) { + json(response, { info: {}, parts: [{ type: 'text', text: 'Harbor Lantern' }] }) + } else { + json(response, true) + } + }) + const result = runOpenCodeTextTaskSession({ + version: 'v1', + v1SessionPolicyFiltersTools: true, + url, + directory: '/workspace', + prompt: 'Name only', + operation: 'conversation-name', + sessionId: 'saved', + fork: true, + signal: new AbortController().signal + }) + await (outcome === 'applied' + ? expect(result).resolves.toBe('Harbor Lantern') + : expect(result).rejects.toThrow(/rejected|different|did not apply/)) + expect(policy).toMatchObject({ + permission: [ + { permission: '*', pattern: '*', action: 'deny' }, + { permission: 'read', pattern: '*', action: 'allow' }, + { permission: 'grep', pattern: '*', action: 'allow' }, + { permission: 'glob', pattern: '*', action: 'allow' }, + { permission: 'external_directory', pattern: '*', action: 'allow' }, + { permission: 'read', pattern: 'mcp:*', action: 'deny' } + ] + }) + expect(requests.some((path) => path.startsWith('POST /session/forked/message?'))).toBe( + outcome === 'applied' + ) + expect(requests).toContain('DELETE /session/forked?directory=%2Fworkspace') + expect( + requests.some((path) => /(?:PATCH|DELETE|POST) \/session\/saved\?(?:.*)/.test(path)) + ).toBe(false) + } +) diff --git a/src/main/opencode/opencode-text-task-policy.ts b/src/main/opencode/opencode-text-task-policy.ts new file mode 100644 index 00000000000..4aeb56ee012 --- /dev/null +++ b/src/main/opencode/opencode-text-task-policy.ts @@ -0,0 +1,146 @@ +import { randomUUID } from 'node:crypto' +import { z } from 'zod' +import type { OpenCodeTextTaskSession } from './opencode-text-task-session' +import type { createOpenCodeTextTaskHttp } from './opencode-text-task-http' + +const RULES = [ + ['*', '*', 'deny'], + ['read', '*', 'allow'], + ['grep', '*', 'allow'], + ['glob', '*', 'allow'], + ['external_directory', '*', 'allow'], + ['read', 'mcp:*', 'deny'] +] as const + +const v1PolicyRules = z.array( + z.object({ + permission: z.string(), + pattern: z.string(), + action: z.enum(['allow', 'deny', 'ask']) + }) +) + +export function acknowledgesOpenCodeV1Policy( + response: unknown, + policy: Record, + fork: boolean +): boolean { + const actual = z.looseObject({ permission: v1PolicyRules.optional() }).parse(response).permission + if (!actual?.length) { + return false + } + const expected = v1PolicyRules.nonempty().parse(policy.permission) + const tail = actual.slice(-expected.length) + if ( + (fork || actual.length === expected.length) && + tail.length === expected.length && + tail.every( + (rule, index) => + rule.permission === expected[index].permission && + rule.pattern === expected[index].pattern && + rule.action === expected[index].action + ) + ) { + return true + } + throw new Error('OpenCode did not apply the requested text task policy') +} + +export const OPEN_CODE_LEGACY_TEXT_TASK_TOOLS = { + '*': false, + read: true, + grep: true, + glob: true, + external_directory: true, + bash: false, + edit: false, + write: false, + patch: false, + apply_patch: false, + multiedit: false, + task: false, + todowrite: false +} as const + +export async function prepareOpenCodeTextTaskPolicy( + input: OpenCodeTextTaskSession, + http: ReturnType, + activeSignal: AbortSignal +) { + const v2 = input.version === 'v2' + const request = http.request + let agent = input.agent || undefined + let actualSubtask = false + let agents: { name: string; mode: string }[] | undefined + if (!v2 && (agent || input.command)) { + agents = z + .array(z.looseObject({ name: z.string(), mode: z.string() })) + .parse(await request('GET', '/agent', undefined, activeSignal)) + const selected = agents.find((candidate) => candidate.name === agent) + if (agent && (!selected || selected.mode === 'subagent')) { + agent = undefined + } + } + if (!v2 && input.command) { + const commands = z + .array( + z.looseObject({ + name: z.string(), + agent: z.string().optional(), + subtask: z.boolean().optional() + }) + ) + .parse(await request('GET', '/command', undefined, activeSignal)) + const command = commands.find((candidate) => candidate.name === input.command) + if (!command) { + throw new Error('OpenCode command is unavailable') + } + actualSubtask = + command.subtask === true || + (agents?.find((candidate) => candidate.name === (command.agent ?? agent))?.mode === + 'subagent' && + command.subtask !== false) + if (actualSubtask && input.operation !== 'conversation-name') { + throw new Error('OpenCode subtask command cannot run as a private text task') + } + } + const rules: readonly (readonly string[])[] = actualSubtask + ? [ + ['*', '*', 'ask'], + ...RULES.slice(1), + ['bash', '*', 'deny'], + ['edit', '*', 'deny'], + ['todowrite', '*', 'deny'] + ] + : RULES + const policy = v2 + ? { + permissions: rules.map(([action, resource, effect]) => ({ action, resource, effect })) + } + : { + permission: rules.map(([permission, pattern, action]) => ({ + permission, + pattern, + action + })) + } + return { + agent, + actualSubtask, + policy, + createBody: { + title: input.title || `Orca text generation ${randomUUID()}`, + ...(agent ? { agent } : {}), + ...(v2 && input.model + ? { + model: { + providerID: input.model.providerID, + id: input.model.modelID, + ...(input.variant ? { variant: input.variant } : {}) + } + } + : {}), + ...policy + } + } +} diff --git a/src/main/opencode/opencode-text-task-server-ready.ts b/src/main/opencode/opencode-text-task-server-ready.ts new file mode 100644 index 00000000000..55ef09505dd --- /dev/null +++ b/src/main/opencode/opencode-text-task-server-ready.ts @@ -0,0 +1,66 @@ +import { z } from 'zod' +import { SearchSubprocessLineAccumulator } from '../../shared/search-subprocess-lines' +import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason' +import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from '../text-generation/source-control-generation-limits' +import type { SpawnedSourceControlAgentProcess } from '../text-generation/source-control-text-generation-types' +const lease = z.object({ url: z.url() }) + +export function readOpenCodeTextTaskServerUrl( + child: SpawnedSourceControlAgentProcess, + v2: boolean, + signal: AbortSignal +): Promise { + const ready = Promise.withResolvers() + const lines = new SearchSubprocessLineAccumulator(MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES) + let bytes = 0 + let listening = false + child.stdout?.on('data', (chunk: Buffer) => { + if (listening) { + return + } + bytes += chunk.byteLength + if (bytes > MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES) { + ready.reject(new Error('OpenCode server readiness exceeded its output limit')) + return + } + lines.push(chunk, (line) => { + if (listening) { + return + } + let url: string | undefined + if (v2) { + try { + url = lease.parse(JSON.parse(line)).url + } catch { + return + } + } else { + url = line.match(/^opencode server listening on (http:\/\/\S+)/)?.[1] + } + if (!url) { + return + } + let address: URL + try { + address = new URL(url) + } catch { + ready.reject(new Error('OpenCode private server returned an unexpected address')) + return + } + if ( + address.protocol !== 'http:' || + !['127.0.0.1', 'localhost', '[::1]'].includes(address.hostname) + ) { + ready.reject(new Error('OpenCode private server returned an unexpected address')) + return + } + listening = true + ready.resolve(address.origin) + }) + }) + // Readiness output can contain credentials; never retain or log either stream. + child.stderr?.on('data', () => {}) + child.once('error', (error) => ready.reject(error)) + child.once('close', () => ready.reject(new Error('OpenCode private server exited'))) + return waitForPromiseWithSignal(ready.promise, signal).finally(() => lines.clear()) +} diff --git a/src/main/opencode/opencode-text-task-session.test.ts b/src/main/opencode/opencode-text-task-session.test.ts new file mode 100644 index 00000000000..82b954a92bf --- /dev/null +++ b/src/main/opencode/opencode-text-task-session.test.ts @@ -0,0 +1,767 @@ +import { z } from 'zod' +import { createServer, type ServerResponse } from 'node:http' +import { once } from 'node:events' +import { afterEach, expect, it, vi } from 'vitest' +import { runOpenCodeTextTaskSession } from './opencode-text-task-session' + +const servers: ReturnType[] = [] +const appliedV1Policy = [ + { permission: '*', pattern: '*', action: 'deny' }, + { permission: 'read', pattern: '*', action: 'allow' }, + { permission: 'grep', pattern: '*', action: 'allow' }, + { permission: 'glob', pattern: '*', action: 'allow' }, + { permission: 'external_directory', pattern: '*', action: 'allow' }, + { permission: 'read', pattern: 'mcp:*', action: 'deny' } +] +afterEach(async () => { + await Promise.all( + servers.splice(0).map(async (server) => { + server.closeAllConnections() + await new Promise((resolve) => server.close(() => resolve())) + }) + ) +}) + +async function fixture( + handle: (path: string, body: unknown, response: ServerResponse) => void | Promise +) { + const server = createServer(async (request, response) => { + const chunks: Buffer[] = [] + for await (const chunk of request) { + chunks.push(Buffer.from(chunk)) + } + const body = Buffer.concat(chunks).toString('utf8') + await handle(`${request.method} ${request.url}`, body ? JSON.parse(body) : undefined, response) + }) + servers.push(server) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const address = server.address() + if (!address || typeof address === 'string') { + throw new Error('Missing test address') + } + return `http://127.0.0.1:${address.port}` +} + +function json(response: ServerResponse, value: unknown) { + response.setHeader('content-type', 'application/json') + response.end(JSON.stringify(value)) +} + +it('v1 applies ordered session authority and preserves the selected native prompt', async () => { + const requests = new Map() + const url = await fixture((path, body, response) => { + requests.set(path, body) + if (path.startsWith('GET /agent?')) { + json(response, [{ name: 'configured-agent', mode: 'primary' }]) + } else if (path.startsWith('POST /session?')) { + json(response, { id: 'ses_v1', permission: appliedV1Policy }) + } else if (path.startsWith('POST /session/ses_v1/message?')) { + json(response, { + info: {}, + parts: [ + { type: 'reasoning', text: 'private' }, + { type: 'text', text: 'Harbor Lantern' } + ] + }) + } else { + json(response, true) + } + }) + await expect( + runOpenCodeTextTaskSession({ + version: 'v1', + v1SessionPolicyFiltersTools: true, + url, + password: 'test', + directory: '/workspace with spaces', + prompt: 'Name this chat', + agent: 'configured-agent', + model: { providerID: 'opencode', modelID: 'crouton-alpha-free' }, + variant: 'low', + signal: new AbortController().signal + }) + ).resolves.toBe('Harbor Lantern') + expect(requests.get('POST /session?directory=%2Fworkspace%20with%20spaces')).toEqual({ + title: expect.stringMatching(/^Orca text generation /), + agent: 'configured-agent', + permission: [ + { permission: '*', pattern: '*', action: 'deny' }, + { permission: 'read', pattern: '*', action: 'allow' }, + { permission: 'grep', pattern: '*', action: 'allow' }, + { permission: 'glob', pattern: '*', action: 'allow' }, + { permission: 'external_directory', pattern: '*', action: 'allow' }, + { permission: 'read', pattern: 'mcp:*', action: 'deny' } + ] + }) + expect( + requests.get('POST /session/ses_v1/message?directory=%2Fworkspace%20with%20spaces') + ).toEqual({ + messageID: expect.stringMatching(/^msg_[0-9a-f]{12}[0-9A-Za-z]{14}$/), + model: { providerID: 'opencode', modelID: 'crouton-alpha-free' }, + agent: 'configured-agent', + variant: 'low', + parts: [{ type: 'text', text: 'Name this chat' }] + }) + expect(requests.has('DELETE /session/ses_v1?directory=%2Fworkspace%20with%20spaces')).toBe(true) +}) + +it('v2 rejects an unexpected permission and reads final text across fragmented CRLF events', async () => { + let events: ServerResponse | undefined + const requests = new Map() + const emit = ( + type: string, + data: { id?: string; assistantMessageID?: string; ordinal?: number; text?: string } + ) => { + if (!events) { + throw new Error('No event subscription') + } + const frame = `data: ${JSON.stringify({ type, data: { sessionID: 'ses_v2', ...data } })}\r\n\r\n` + events.write(frame.slice(0, -3)) + events.write(frame.slice(-3)) + } + const url = await fixture((path, body, response) => { + requests.set(path, body) + if (path === 'GET /api/event') { + events = response + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.flushHeaders() + } else if (path === 'POST /api/session') { + json(response, { data: { id: 'ses_v2' } }) + } else if (path === 'POST /api/session/ses_v2/prompt') { + json(response, {}) + emit('permission.asked', { id: 'per_shell' }) + } else if (path === 'POST /api/session/ses_v2/permission/per_shell/reply') { + json(response, {}) + emit('session.text.ended', { + assistantMessageID: 'msg_final', + ordinal: 0, + text: 'Harbor Lantern' + }) + emit('session.execution.succeeded', {}) + } else { + json(response, {}) + } + }) + await expect( + runOpenCodeTextTaskSession({ + version: 'v2', + v1SessionPolicyFiltersTools: false, + url, + password: 'test', + directory: '/workspace', + prompt: 'Name this chat', + model: { providerID: 'opencode', modelID: 'crouton-alpha-free' }, + variant: 'low', + signal: new AbortController().signal + }) + ).resolves.toBe('Harbor Lantern') + expect(requests.get('POST /api/session')).toEqual({ + title: expect.stringMatching(/^Orca text generation /), + location: { directory: '/workspace' }, + model: { providerID: 'opencode', id: 'crouton-alpha-free', variant: 'low' }, + permissions: [ + { action: '*', resource: '*', effect: 'deny' }, + { action: 'read', resource: '*', effect: 'allow' }, + { action: 'grep', resource: '*', effect: 'allow' }, + { action: 'glob', resource: '*', effect: 'allow' }, + { action: 'external_directory', resource: '*', effect: 'allow' }, + { action: 'read', resource: 'mcp:*', effect: 'deny' } + ] + }) + expect(requests.get('POST /api/session/ses_v2/permission/per_shell/reply')).toEqual({ + decision: 'reject', + message: 'Tools are unavailable for this text task.' + }) + expect(requests.has('DELETE /api/session/ses_v2')).toBe(true) +}) + +it('recovers and deletes an owned session when cancelled during creation without sending a prompt', async () => { + const controller = new AbortController() + const requests: string[] = [] + const url = await fixture((path, _body, response) => { + requests.push(path) + if (path === 'GET /api/event') { + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.flushHeaders() + } else if (path === 'POST /api/session') { + controller.abort(new Error('Renamed manually')) + json(response, { data: { id: 'ses_late' } }) + } else { + json(response, {}) + } + }) + await expect( + runOpenCodeTextTaskSession({ + version: 'v2', + v1SessionPolicyFiltersTools: false, + url, + password: 'test', + directory: '/workspace', + prompt: 'Name this chat', + signal: controller.signal + }) + ).rejects.toThrow('Renamed manually') + expect(requests).toContain('POST /api/session/ses_late/interrupt') + expect(requests).toContain('DELETE /api/session/ses_late') + expect(requests).not.toContain('POST /api/session/ses_late/prompt') +}) + +it('uses the native v1 command endpoint with its arguments and selected model', async () => { + const requests = new Map() + const url = await fixture((path, body, response) => { + requests.set(path, body) + if (path.startsWith('POST /session?')) { + json(response, { id: 'ses_command', permission: appliedV1Policy }) + } else if (path.startsWith('GET /command?')) { + json(response, [{ name: 'review', agent: 'reviewer' }]) + } else if (path.startsWith('GET /agent?')) { + json(response, [ + { name: 'reviewer', mode: 'primary' }, + { name: 'build', mode: 'primary' } + ]) + } else if (path.startsWith('POST /session/ses_command/command?')) { + json(response, { + info: {}, + parts: [{ type: 'text', text: 'Harbor Lantern' }] + }) + } else { + json(response, true) + } + }) + await expect( + runOpenCodeTextTaskSession({ + version: 'v1', + v1SessionPolicyFiltersTools: true, + url, + password: 'test', + directory: '/workspace', + prompt: 'extra\ngenerated', + command: 'review', + agent: 'build', + title: 'Recipe', + model: { providerID: 'opencode', modelID: 'crouton-alpha-free' }, + variant: 'low', + signal: new AbortController().signal + }) + ).resolves.toBe('Harbor Lantern') + expect(requests.get('POST /session/ses_command/command?directory=%2Fworkspace')).toEqual({ + messageID: expect.stringMatching(/^msg_[0-9a-f]{12}[0-9A-Za-z]{14}$/), + command: 'review', + arguments: 'extra\ngenerated', + agent: 'build', + model: 'opencode/crouton-alpha-free', + variant: 'low' + }) + expect(requests.has('POST /session/ses_command/message?directory=%2Fworkspace')).toBe(false) +}) + +it('preserves a completed title when deleting its session fails', async () => { + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const url = await fixture((path, _body, response) => { + if (path.startsWith('POST /session?')) { + json(response, { id: 'ses_cleanup', permission: appliedV1Policy }) + } else if (path.startsWith('POST /session/ses_cleanup/message?')) { + json(response, { info: {}, parts: [{ type: 'text', text: 'Harbor Lantern' }] }) + } else { + response.writeHead(500).end() + } + }) + try { + await expect( + runOpenCodeTextTaskSession({ + version: 'v1', + v1SessionPolicyFiltersTools: true, + url, + password: 'test', + directory: '/workspace', + prompt: 'Name this chat', + signal: new AbortController().signal + }) + ).resolves.toBe('Harbor Lantern') + } finally { + warning.mockRestore() + } +}) + +it.each(['', 'missing', 'explore'])( + 'v1 preserves default-agent fallback for %j in a normal command', + async (agent) => { + let submitted: unknown + const url = await fixture((path, body, response) => { + if (path.startsWith('GET /agent?')) { + json(response, [ + { name: 'explore', mode: 'subagent' }, + { name: 'build', mode: 'primary' } + ]) + } else if (path.startsWith('GET /command?')) { + json(response, [{ name: 'review' }]) + } else if (path.startsWith('POST /session?')) { + json(response, { id: 'ses_default', permission: appliedV1Policy }) + } else if (path.startsWith('POST /session/ses_default/command?')) { + submitted = body + json(response, { info: {}, parts: [{ type: 'text', text: 'Harbor Lantern' }] }) + } else { + json(response, true) + } + }) + await expect( + runOpenCodeTextTaskSession({ + version: 'v1', + v1SessionPolicyFiltersTools: true, + url, + password: 'test', + directory: '/workspace', + prompt: 'input', + command: 'review', + agent, + signal: new AbortController().signal + }) + ).resolves.toBe('Harbor Lantern') + expect(submitted).toEqual({ + command: 'review', + arguments: 'input', + messageID: expect.stringMatching(/^msg_[0-9a-f]{12}[0-9A-Za-z]{14}$/) + }) + } +) + +it.each([ + { + resume: false, + command: undefined, + parentID: 'msg_compaction_continue', + title: 'Harbor Lantern' + }, + { resume: true, command: undefined, parentID: 'msg_replay', title: 'Harbor Lantern' }, + { + resume: false, + command: 'inspect', + parentID: 'msg_subtask_compaction', + title: 'Harbor Lantern' + }, + { resume: false, command: undefined, parentID: 'msg_other_caller', title: 'Shared run title' } +])( + 'uses the borrowed v1 HTTP response as best effort (%j)', + async ({ resume, command, parentID, title }) => { + const requests: string[] = [] + const url = await fixture((path, body, response) => { + requests.push(path) + path = path.replace('/prefix/', '/') + if (path.startsWith('GET /session/saved?')) { + json(response, { id: 'saved', directory: '/old' }) + } else if (path.startsWith('GET /session?')) { + json(response, [{ id: 'saved', directory: '/old' }]) + } else if (path.startsWith('GET /agent?')) { + json(response, [{ name: 'reader', mode: 'subagent' }]) + } else if (path.startsWith('GET /command?')) { + json(response, [{ name: 'inspect', agent: 'reader', subtask: true }]) + } else if (path.startsWith(`POST /session/saved/${command ? 'command' : 'message'}?`)) { + expect(body).toMatchObject( + command + ? { command: 'inspect', arguments: 'Name only', model: 'configured/model' } + : { + parts: [{ type: 'text', text: 'Name only' }], + model: { providerID: 'configured', modelID: 'model' } + } + ) + json(response, { + info: { id: 'msg_native_reply', parentID, role: 'assistant', time: { completed: 300 } }, + parts: [{ type: 'text', text: title }] + }) + } else { + response.statusCode = 400 + json(response, {}) + } + }) + await expect( + runOpenCodeTextTaskSession({ + version: 'v1', + v1SessionPolicyFiltersTools: true, + url: `${url}/prefix/`, + directory: '/workspace', + externalDirectory: '/requested', + external: { url }, + exclusiveServer: false, + prompt: 'Name only', + model: { providerID: 'configured', modelID: 'model' }, + sessionId: resume ? undefined : 'saved', + continue: resume, + command, + operation: 'conversation-name', + signal: new AbortController().signal + }) + ).resolves.toBe(title) + expect(requests).toEqual([ + resume + ? 'GET /prefix/session?directory=%2Frequested' + : 'GET /prefix/session/saved?directory=%2Frequested', + ...(command + ? ['GET /prefix/agent?directory=%2Frequested', 'GET /prefix/command?directory=%2Frequested'] + : []), + `POST /prefix/session/saved/${command ? 'command' : 'message'}?directory=%2Frequested` + ]) + } +) + +it('discards a cancelled borrowed v1 response without aborting or deleting its session', async () => { + const controller = new AbortController() + const submitted = Promise.withResolvers() + const requests: string[] = [] + let lateResponse: ServerResponse | undefined + const url = await fixture((path, _body, response) => { + requests.push(path) + if (path.startsWith('GET /session/saved')) { + json(response, { id: 'saved', directory: '/workspace' }) + } else if (path.startsWith('POST /session/saved/message?')) { + lateResponse = response + submitted.resolve() + } else { + response.statusCode = 400 + json(response, {}) + } + }) + const result = runOpenCodeTextTaskSession({ + version: 'v1', + v1SessionPolicyFiltersTools: true, + url, + directory: '/workspace', + external: { url }, + exclusiveServer: false, + sessionId: 'saved', + operation: 'conversation-name', + prompt: 'Name only', + signal: controller.signal + }) + const rejected = expect(result).rejects.toThrow('Renamed manually') + await submitted.promise + controller.abort(new Error('Renamed manually')) + await rejected + json(lateResponse!, { + info: { parentID: 'msg_compaction_continue' }, + parts: [{ type: 'text', text: 'Late title' }] + }) + expect(requests).toEqual([ + 'GET /session/saved', + 'POST /session/saved/message?directory=%2Fworkspace' + ]) +}) + +it.each([false, true])( + 'correlates borrowed v2 admission and leaves unrelated work alone (superseded=%s)', + async (superseded) => { + const requests: string[] = [] + let events: ServerResponse | undefined + const emit = (type: string, data: Record) => + events!.write(`data: ${JSON.stringify({ type, data: { sessionID: 'saved', ...data } })}\n\n`) + const url = await fixture((path, body, response) => { + requests.push(path) + if (path === 'GET /api/event') { + events = response + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.flushHeaders() + } else if (path === 'GET /api/session/saved') { + json(response, { data: { id: 'saved', location: { directory: '/server' } } }) + } else if (path === 'POST /api/session/saved/prompt') { + const input = z.object({ id: z.string(), delivery: z.literal('steer') }).parse(body) + emit('session.text.ended', { + assistantMessageID: 'msg_earlier', + ordinal: 0, + text: 'Wrong title' + }) + emit('session.execution.succeeded', {}) + emit('session.inbox.delivered', { inboxID: input.id }) + emit('session.compaction.started', { reason: 'auto', recent: 'msg_history' }) + emit('session.compaction.ended', { + reason: 'auto', + text: 'This summary is context, not the requested title', + recent: 'msg_history', + model: { providerID: 'configured', id: 'model' }, + cost: 0, + tokens: { input: 100, output: 10, reasoning: 0, cache: { read: 0, write: 0 } } + }) + emit('permission.asked', { id: 'per_other_owner' }) + emit('session.step.started', { assistantMessageID: 'msg_ours' }) + emit('session.text.ended', { + assistantMessageID: 'msg_ours', + ordinal: 0, + text: 'Harbor Lantern' + }) + if (superseded) { + emit('session.inbox.delivered', { inboxID: 'msg_later_input' }) + } + emit('session.execution.succeeded', {}) + json(response, {}) + } else { + json(response, {}) + } + }) + const result = runOpenCodeTextTaskSession({ + version: 'v2', + v1SessionPolicyFiltersTools: false, + url, + directory: '/client', + external: { url }, + exclusiveServer: false, + prompt: 'Name only', + sessionId: 'saved', + operation: 'conversation-name', + signal: new AbortController().signal + }) + await (superseded + ? expect(result).rejects.toThrow('superseded') + : expect(result).resolves.toBe('Harbor Lantern')) + expect(requests).toEqual([ + 'GET /api/event', + 'GET /api/session/saved', + 'POST /api/session/saved/prompt' + ]) + } +) + +it('cancels only its still-queued borrowed v2 input after a late admission response', async () => { + const controller = new AbortController() + const requests: string[] = [] + let messageID = '' + const url = await fixture((path, body, response) => { + requests.push(path) + if (path === 'GET /api/event') { + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.flushHeaders() + } else if (path === 'GET /api/session/saved') { + json(response, { data: { id: 'saved', location: { directory: '/server' } } }) + } else if (path === 'POST /api/session/saved/prompt') { + messageID = z.object({ id: z.string() }).parse(body).id + controller.abort(new Error('Renamed manually')) + json(response, {}) + } else { + json(response, {}) + } + }) + await expect( + runOpenCodeTextTaskSession({ + version: 'v2', + v1SessionPolicyFiltersTools: false, + url, + directory: '/client', + external: { url }, + exclusiveServer: false, + prompt: 'Name only', + sessionId: 'saved', + operation: 'conversation-name', + signal: controller.signal + }) + ).rejects.toThrow('Renamed manually') + expect(requests).toEqual([ + 'GET /api/event', + 'GET /api/session/saved', + 'POST /api/session/saved/prompt', + `DELETE /api/session/saved/inbox/${messageID}` + ]) +}) + +it('retains explicitly shared native history even when publication fails ambiguously', async () => { + const requests: string[] = [] + const url = await fixture((path, _body, response) => { + requests.push(path) + if (path.startsWith('POST /session?')) { + json(response, { id: 'retained', permission: appliedV1Policy }) + } else if (path.startsWith('POST /session/retained/share?')) { + response.statusCode = 500 + json(response, {}) + } else if (path.startsWith('POST /session/retained/message?')) { + json(response, { info: {}, parts: [{ type: 'text', text: 'Harbor Lantern' }] }) + } else { + json(response, true) + } + }) + await expect( + runOpenCodeTextTaskSession({ + version: 'v1', + v1SessionPolicyFiltersTools: true, + url, + directory: '/workspace', + prompt: 'Name only', + share: true, + operation: 'conversation-name', + signal: new AbortController().signal + }) + ).resolves.toBe('Harbor Lantern') + expect(requests).toEqual([ + 'POST /session?directory=%2Fworkspace', + 'POST /session/retained/share?directory=%2Fworkspace', + 'POST /session/retained/message?directory=%2Fworkspace' + ]) +}) + +it('selects the newest matching root with one filtered request at N and 10N histories', async () => { + for (const population of [200, 2000]) { + let pages = 0 + const history = Array.from({ length: population }, (_, index) => ({ + id: index === population - 2 ? 'selected' : `other_${index}`, + location: { directory: index % 2 === 0 ? '/workspace' : '/elsewhere' }, + parentID: index !== population - 2 && index % 3 === 0 ? 'parent' : null, + updated: index + })) + let events: ServerResponse | undefined + const url = await fixture((path, body, response) => { + const parsed = new URL(path.slice(path.indexOf(' ') + 1), 'http://fixture') + if (path === 'GET /api/event') { + events = response + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.flushHeaders() + } else if (parsed.pathname === '/api/location') { + json(response, { directory: '/workspace' }) + } else if (path.startsWith('GET /api/session?')) { + pages++ + expect(parsed.searchParams.get('directory')).toBe('/workspace') + expect(parsed.searchParams.get('parentID')).toBe('null') + expect(parsed.searchParams.get('order')).toBe('desc') + const matching = history + .filter( + (item) => + item.location.directory === parsed.searchParams.get('directory') && !item.parentID + ) + .sort((a, b) => b.updated - a.updated) + json(response, { + data: matching.slice(0, Number(parsed.searchParams.get('limit'))), + cursor: {} + }) + } else if (path === 'POST /api/session/selected/prompt') { + const { id } = z.object({ id: z.string() }).parse(body) + const emitted: [string, Record][] = [ + ['session.inbox.delivered', { inboxID: id }], + ['session.step.started', { assistantMessageID: 'msg_selected' }], + [ + 'session.text.ended', + { assistantMessageID: 'msg_selected', ordinal: 0, text: 'Harbor Lantern' } + ], + ['session.execution.succeeded', {}] + ] + for (const [type, data] of emitted) { + events!.write( + `data: ${JSON.stringify({ type, data: { sessionID: 'selected', ...data } })}\n\n` + ) + } + json(response, {}) + } else { + response.statusCode = 400 + json(response, {}) + } + }) + await expect( + runOpenCodeTextTaskSession({ + version: 'v2', + v1SessionPolicyFiltersTools: false, + url, + directory: '/workspace', + continue: true, + exclusiveServer: false, + operation: 'conversation-name', + prompt: 'Name only', + signal: new AbortController().signal + }) + ).resolves.toBe('Harbor Lantern') + expect(pages).toBe(1) + } +}) + +it.each([false, true])( + 'rejects owned subtask asks with session routing field: %s', + async (routing) => { + let events: ServerResponse | undefined + let readAllowed = false + let deniedChild = false + let deniedForeign = false + let commandResponse: ServerResponse | undefined + const url = await fixture((path, body, response) => { + if (path.startsWith('GET /agent?')) { + json(response, [{ name: 'reader', mode: 'subagent' }]) + } else if (path.startsWith('GET /command?')) { + json(response, [ + { name: 'inspect', agent: 'reader', subtask: true, model: 'configured/command-model' } + ]) + } else if (path.startsWith('POST /session?')) { + const rules = z + .object({ + permission: z.array( + z.object({ permission: z.string(), pattern: z.string(), action: z.string() }) + ) + }) + .parse(body).permission + // The native child retains denies and drops ordinary parent read allows. + const childDenies = rules + .filter((rule) => rule.action === 'deny') + .map((rule) => rule.permission) + expect(childDenies).toEqual(['read', 'bash', 'edit', 'todowrite']) + readAllowed = !rules.some( + (rule) => + rule.action === 'deny' && + rule.pattern === '*' && + ['*', 'read'].includes(rule.permission) + ) + json(response, { + id: 'root', + permission: [ + { permission: '*', pattern: '*', action: 'ask' }, + ...appliedV1Policy.slice(1), + { permission: 'bash', pattern: '*', action: 'deny' }, + { permission: 'edit', pattern: '*', action: 'deny' }, + { permission: 'todowrite', pattern: '*', action: 'deny' } + ] + }) + } else if (path.startsWith('GET /event?')) { + events = response + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.flushHeaders() + } else if (path.startsWith('POST /session/root/command?')) { + expect(body).toMatchObject({ + command: 'inspect', + arguments: 'Name from the recorded request', + model: 'selected/model' + }) + events!.write( + `data: ${JSON.stringify({ type: 'session.created', properties: { info: { id: 'foreign_child', parentID: 'foreign_root' } } })}\n\n` + ) + events!.write( + `data: ${JSON.stringify({ type: 'permission.asked', properties: { sessionID: 'foreign_child', id: 'per_foreign' } })}\n\n` + ) + events!.write( + `data: ${JSON.stringify({ type: 'session.created', properties: { ...(routing ? { sessionID: 'child' } : {}), info: { id: 'child', parentID: 'root' } } })}\n\n` + ) + events!.write( + `data: ${JSON.stringify({ type: 'permission.asked', properties: { sessionID: 'child', id: 'per_child_shell' } })}\n\n` + ) + commandResponse = response + } else if (path.startsWith('POST /permission/per_foreign/reply?')) { + deniedForeign = true + json(response, true) + } else if (path.startsWith('POST /permission/per_child_shell/reply?')) { + expect(body).toMatchObject({ reply: 'reject' }) + deniedChild = true + json(response, true) + json(commandResponse!, { + info: {}, + parts: [{ type: 'text', text: readAllowed ? 'Harbor Lantern' : 'Child read was denied' }] + }) + } else { + json(response, true) + } + }) + await expect( + runOpenCodeTextTaskSession({ + version: 'v1', + v1SessionPolicyFiltersTools: true, + url, + directory: '/workspace', + command: 'inspect', + model: { providerID: 'selected', modelID: 'model' }, + prompt: 'Name from the recorded request', + operation: 'conversation-name', + signal: new AbortController().signal + }) + ).resolves.toBe('Harbor Lantern') + expect(deniedChild).toBe(true) + expect(deniedForeign).toBe(false) + } +) diff --git a/src/main/opencode/opencode-text-task-session.ts b/src/main/opencode/opencode-text-task-session.ts new file mode 100644 index 00000000000..97ac25e4200 --- /dev/null +++ b/src/main/opencode/opencode-text-task-session.ts @@ -0,0 +1,293 @@ +import { openCodeTextTaskEvents } from './opencode-text-task-events' +import { + OPEN_CODE_LEGACY_TEXT_TASK_TOOLS, + prepareOpenCodeTextTaskPolicy +} from './opencode-text-task-policy' +import { randomBytes } from 'node:crypto' +import { openCodeTextTaskTarget } from './opencode-text-task-target' +import type { TextGenerationOperation } from '../text-generation/source-control-text-generation-types' +import { createOpenCodeTextTaskHttp } from './opencode-text-task-http' +import { z } from 'zod' +import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason' +import type { OpenCodeTextTaskInput } from './opencode-text-task-input' + +export type OpenCodeTextTaskSession = { + version: 'v1' | 'v2' + v1SessionPolicyFiltersTools: boolean + url: string + password?: string + username?: string + exclusiveServer?: boolean + operation?: TextGenerationOperation + shouldExecute?: () => boolean + sessionId?: string + continue?: boolean + fork?: boolean + share?: boolean + external?: OpenCodeTextTaskInput['external'] + externalDirectory?: string + directory: string + prompt: string + agent?: string + model?: { providerID: string; modelID: string } + variant?: string + title?: string + command?: string + v1Files?: OpenCodeTextTaskInput['v1Files'] + v2Files?: OpenCodeTextTaskInput['v2Files'] + signal: AbortSignal +} + +const reply = z.looseObject({ + info: z.looseObject({ + id: z.string().optional(), + error: z.unknown().optional(), + parentID: z.string().optional() + }), + parts: z.array(z.looseObject({ type: z.string(), text: z.string().optional() })) +}) + +let messageTimestamp = 0 +let messageCounter = 0 +function nextMessageID(): string { + const now = Date.now() + messageCounter = now === messageTimestamp ? messageCounter + 1 : 1 + messageTimestamp = now + const time = BigInt.asUintN(48, BigInt(now) * 4096n + BigInt(messageCounter)) + const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' + const suffix = Array.from(randomBytes(14), (byte) => alphabet[byte % 62]).join('') + return `msg_${time.toString(16).padStart(12, '0')}${suffix}` +} + +/** Task IDs, history and servers have distinct owners; policy precedes semantic input. */ +export async function runOpenCodeTextTaskSession(input: OpenCodeTextTaskSession): Promise { + const v2 = input.version === 'v2' + const base = v2 ? '/api/session' : '/session' + let directory = input.directory + const initialHttp = createOpenCodeTextTaskHttp( + input.url, + input.password, + '', + input.username, + input.version + ) + let http = initialHttp + const request: typeof http.request = (...args) => http.request(...args) + const checkCurrent = () => { + input.signal.throwIfAborted() + if (input.shouldExecute?.() === false) { + throw new Error('OpenCode naming task was superseded') + } + } + const messageID = nextMessageID() + const lost = new AbortController() + const activeSignal = AbortSignal.any([input.signal, lost.signal]) + let sessionID = '' + let completed = false + let owned = false + let actualSubtask = false + let submitted = false + let admission: Promise | undefined + const ownedTree = new Set() + const events = openCodeTextTaskEvents({ + version: input.version, + url: input.url, + signal: input.signal, + lost, + messageID, + context: () => ({ sessionID, owned, ownedTree, directory, http }) + }) + try { + input.signal.throwIfAborted() + if (v2) { + await events.subscribe() + } + activeSignal.throwIfAborted() + let agent = input.agent || undefined + const target = await openCodeTextTaskTarget({ + task: input, + version: input.version, + directory, + http: initialHttp, + signal: activeSignal, + allocated: (id, taskDirectory) => { + sessionID = id + directory = taskDirectory + owned = true + ownedTree.add(id) + http = createOpenCodeTextTaskHttp( + input.url, + input.password, + v2 ? '' : `?directory=${encodeURIComponent(directory)}`, + input.username, + input.version + ) + }, + prepare: async (taskDirectory) => { + directory = taskDirectory + http = createOpenCodeTextTaskHttp( + input.url, + input.password, + v2 ? '' : `?directory=${encodeURIComponent(directory)}`, + input.username, + input.version + ) + const prepared = await prepareOpenCodeTextTaskPolicy(input, http, activeSignal) + agent = prepared.agent + actualSubtask = prepared.actualSubtask + return prepared + } + }) + sessionID = target.id + directory = target.directory + owned = target.owned + activeSignal.throwIfAborted() + const legacyPolicy = !v2 && owned && !target.policyAcknowledged + if (!v2 && owned && (actualSubtask || legacyPolicy || !input.v1SessionPolicyFiltersTools)) { + await events.subscribe() + } + if (input.share) { + await request( + 'POST', + `${base}/${encodeURIComponent(sessionID)}/share`, + undefined, + activeSignal + ).catch(() => {}) + activeSignal.throwIfAborted() + } + let text: string + if (v2) { + if (input.agent && (!owned || input.fork)) { + await request( + 'POST', + `${base}/${encodeURIComponent(sessionID)}/agent`, + { agent: input.agent }, + activeSignal + ) + } + let selectedModel = input.model + ? { + providerID: input.model.providerID, + id: input.model.modelID, + ...(input.variant ? { variant: input.variant } : {}) + } + : undefined + if (!selectedModel && input.variant) { + const current = z + .looseObject({ + model: z + .looseObject({ + providerID: z.string(), + id: z.string(), + variant: z.string().optional() + }) + .optional() + }) + .parse( + await request( + 'GET', + `${base}/${encodeURIComponent(sessionID)}`, + undefined, + activeSignal + ) + ) + const model = + current.model ?? + z + .looseObject({ providerID: z.string(), id: z.string() }) + .parse(await request('GET', '/api/model/default', undefined, activeSignal)) + selectedModel = { ...model, variant: input.variant } + } + if (selectedModel && (!owned || input.fork || !input.model)) { + await request( + 'POST', + `${base}/${encodeURIComponent(sessionID)}/model`, + { model: selectedModel }, + activeSignal + ) + } + checkCurrent() + submitted = true + admission = request( + 'POST', + `${base}/${encodeURIComponent(sessionID)}/prompt`, + { + id: messageID, + delivery: 'steer', + text: input.prompt, + ...(input.v2Files?.length ? { files: input.v2Files } : {}) + }, + AbortSignal.timeout(10_000) + ) + await waitForPromiseWithSignal(admission, activeSignal) + text = await waitForPromiseWithSignal(events.completion, activeSignal) + } else { + checkCurrent() + const result = reply.parse( + await request( + 'POST', + `${base}/${encodeURIComponent(sessionID)}/${input.command ? 'command' : 'message'}`, + { + messageID, + ...(input.model + ? { + model: input.command + ? `${input.model.providerID}/${input.model.modelID}` + : input.model + } + : {}), + ...(agent ? { agent } : {}), + ...(input.variant ? { variant: input.variant } : {}), + ...(input.command + ? { command: input.command, arguments: input.prompt } + : { + parts: [...(input.v1Files ?? []), { type: 'text', text: input.prompt }], + ...(legacyPolicy ? { tools: OPEN_CODE_LEGACY_TEXT_TASK_TOOLS } : {}) + }) + }, + activeSignal + ) + ) + if (result.info.error) { + throw new Error('OpenCode did not complete text generation') + } + text = result.parts + .filter((part) => part.type === 'text') + .map((part) => part.text ?? '') + .join('\n') + .trim() + } + if (!text) { + throw new Error('OpenCode returned an empty text response') + } + completed = true + return text + } finally { + await events.close() + if (sessionID) { + const path = `${base}/${encodeURIComponent(sessionID)}` + if (!completed && (owned || input.exclusiveServer !== false)) { + await request( + 'POST', + `${path}/${v2 ? 'interrupt' : 'abort'}`, + undefined, + AbortSignal.timeout(2_000) + ).catch(() => console.warn('OpenCode text task interruption cleanup failed')) + } + if (!owned && input.exclusiveServer === false && v2 && submitted && !events.promoted) { + await admission?.catch(() => {}) + await request( + 'DELETE', + `${path}/inbox/${encodeURIComponent(messageID)}`, + undefined, + AbortSignal.timeout(2_000) + ).catch(() => console.warn('OpenCode naming input cancellation failed')) + } + if (owned && !input.share) { + await request('DELETE', path, undefined, AbortSignal.timeout(2_000)).catch(() => + console.warn('OpenCode text task session cleanup failed') + ) + } + } + } +} diff --git a/src/main/opencode/opencode-text-task-streams.test.ts b/src/main/opencode/opencode-text-task-streams.test.ts new file mode 100644 index 00000000000..b3ac21256f6 --- /dev/null +++ b/src/main/opencode/opencode-text-task-streams.test.ts @@ -0,0 +1,199 @@ +import { ChildProcess } from 'node:child_process' +import { PassThrough } from 'node:stream' +import { afterEach, expect, it, vi } from 'vitest' +import { createOpenCodeTextTaskHttp } from './opencode-text-task-http' +import { openCodeTextTaskEvents } from './opencode-text-task-events' +import { readOpenCodeTextTaskServerUrl } from './opencode-text-task-server-ready' + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +function framingWork() { + const original = Buffer.prototype.indexOf + const search = vi.spyOn(Buffer.prototype, 'indexOf') + let searched = 0 + search.mockImplementation(function (this: Buffer, value, offset, encoding) { + if (value === 10) { + searched += this.length - (typeof offset === 'number' ? offset : 0) + } + return original.call(this, value, offset, encoding) + }) + const accounting = vi.spyOn(Buffer, 'byteLength') + const splitting = vi.spyOn(String.prototype, 'split') + return () => ({ + searched: + searched + + splitting.mock.calls.reduce((sum, args, index) => { + const separator: unknown = args[0] + return sum + (separator === '\n' ? String(splitting.mock.contexts[index]).length : 0) + }, 0), + accounted: accounting.mock.calls.reduce( + (sum, args) => sum + (typeof args[0] === 'string' ? args[0].length : args[0].byteLength), + 0 + ) + }) +} + +function fakeServer() { + const child = new ChildProcess() + Object.defineProperties(child, { + stdout: { writable: true, configurable: true }, + stderr: { writable: true, configurable: true } + }) + return Object.assign(child, { stdout: new PassThrough(), stderr: new PassThrough() }) +} + +function eventStream(bytes: Buffer) { + let offset = 0 + let canceled = false + const stream = new ReadableStream({ + pull(controller) { + if (offset < bytes.length) { + controller.enqueue(bytes.subarray(offset, offset + 4096)) + offset += 4096 + } + }, + cancel() { + canceled = true + } + }) + vi.stubGlobal( + 'fetch', + vi.fn(async (_url, options: RequestInit) => { + const reader = stream.getReader() + const body = new ReadableStream({ + async pull(controller) { + const value = await reader.read() + if (value.done) { + controller.close() + } else { + controller.enqueue(value.value) + } + }, + async cancel() { + await reader.cancel() + } + }) + options.signal?.addEventListener( + 'abort', + () => { + void reader.cancel() + }, + { once: true } + ) + return new Response(body) + }) + ) + return () => canceled +} + +it('frames fragmented Unicode/CRLF events with linear search and accounting at N and 10N', async () => { + for (const size of [128 * 1024, 1280 * 1024]) { + const text = `${'a'.repeat(size)}πŸŒŠη΅‚` + const bytes = Buffer.from( + [ + { + type: 'session.text.ended', + data: { sessionID: 'owned', assistantMessageID: 'msg_output', ordinal: 0, text } + }, + { type: 'session.execution.succeeded', data: { sessionID: 'owned' } } + ] + .map((event) => `data: ${JSON.stringify(event)}\r\n\r\n`) + .join('') + ) + const canceled = eventStream(bytes) + const work = framingWork() + const events = openCodeTextTaskEvents({ + version: 'v2', + url: 'http://fixture', + signal: new AbortController().signal, + lost: new AbortController(), + messageID: 'msg_input', + context: () => ({ + sessionID: 'owned', + owned: true, + ownedTree: new Set(['owned']), + directory: '/workspace', + http: createOpenCodeTextTaskHttp('http://fixture', undefined, '/workspace') + }) + }) + await events.subscribe() + await expect(events.completion).resolves.toBe(text) + await events.close() + // One forward newline scan plus bounded rescans within each 4 KiB transport chunk. + expect(work().searched).toBeLessThanOrEqual(bytes.length + 4 * 4096) + expect(work().accounted).toBeLessThanOrEqual(2 * bytes.length) + expect(canceled()).toBe(true) + vi.restoreAllMocks() + } +}) + +it('reads a fragmented readiness line once at N and 10N and preserves Unicode boundaries', async () => { + for (const size of [128 * 1024, 1280 * 1024]) { + const child = fakeServer() + const bytes = Buffer.from( + `{"log":"${'a'.repeat(size)}πŸŒŠη΅‚"}\r\n{"url":"http://127.0.0.1:4096"}\r\n` + ) + const work = framingWork() + const ready = readOpenCodeTextTaskServerUrl(child, true, new AbortController().signal) + for (let offset = 0; offset < bytes.length; offset += 4096) { + child.stdout.write(bytes.subarray(offset, offset + 4096)) + } + await expect(ready).resolves.toBe('http://127.0.0.1:4096') + expect(work().searched).toBeLessThanOrEqual(bytes.length + 4096) + expect(work().accounted).toBe(0) + child.stdout.destroy() + child.stderr.destroy() + vi.restoreAllMocks() + } +}) + +it('accepts only native V1 readiness output and rejects malformed native addresses', async () => { + const child = fakeServer() + const ready = readOpenCodeTextTaskServerUrl(child, false, new AbortController().signal) + child.stdout.write('MCP listening on http://localhost:undefined\n') + child.stdout.write('dev server listening on http://localhost:3000\n') + child.stdout.write('opencode server listening on http://127.0.0.1:4096\n') + await expect(ready).resolves.toBe('http://127.0.0.1:4096') + child.stdout.destroy() + child.stderr.destroy() + + const malformed = fakeServer() + const rejected = readOpenCodeTextTaskServerUrl(malformed, false, new AbortController().signal) + expect(() => malformed.stdout.write('opencode server listening on http://[bad\n')).not.toThrow() + await expect(rejected).rejects.toThrow('OpenCode private server returned an unexpected address') + malformed.stdout.destroy() + malformed.stderr.destroy() +}) + +it('rejects oversized streams and releases their reader; readiness also honors cancellation and size', async () => { + const canceled = eventStream(Buffer.alloc(4 * 1024 * 1024 + 1, 65)) + const events = openCodeTextTaskEvents({ + version: 'v2', + url: 'http://fixture', + signal: new AbortController().signal, + lost: new AbortController(), + messageID: 'msg_input', + context: () => ({ + sessionID: 'owned', + owned: true, + ownedTree: new Set(['owned']), + directory: '/workspace', + http: createOpenCodeTextTaskHttp('http://fixture', undefined, '/workspace') + }) + }) + await events.subscribe() + await expect(events.completion).rejects.toThrow('output limit') + await events.close() + expect(canceled()).toBe(true) + const child = fakeServer() + const ready = readOpenCodeTextTaskServerUrl(child, true, new AbortController().signal) + child.stdout.write(Buffer.alloc(4 * 1024 * 1024 + 1)) + await expect(ready).rejects.toThrow('output limit') + const controller = new AbortController() + const abort = readOpenCodeTextTaskServerUrl(fakeServer(), true, controller.signal) + controller.abort(new Error('stopped')) + await expect(abort).rejects.toThrow('stopped') +}) diff --git a/src/main/opencode/opencode-text-task-target.ts b/src/main/opencode/opencode-text-task-target.ts new file mode 100644 index 00000000000..7a82afed98b --- /dev/null +++ b/src/main/opencode/opencode-text-task-target.ts @@ -0,0 +1,133 @@ +import { z } from 'zod' +import { acknowledgesOpenCodeV1Policy } from './opencode-text-task-policy' +import type { OpenCodeTextTaskInput } from './opencode-text-task-input' +import type { createOpenCodeTextTaskHttp } from './opencode-text-task-http' + +const session = z.looseObject({ + id: z.string().min(1), + parentID: z.string().nullable().optional(), + directory: z.string().optional(), + location: z.looseObject({ directory: z.string() }).optional() +}) +const page = z.object({ + data: z.array(session), + cursor: z.object({ next: z.string().optional() }) +}) + +type Http = ReturnType + +/** Resolve history on its own server; ownership begins only at a native allocation response. */ +export async function openCodeTextTaskTarget(input: { + task: Pick< + OpenCodeTextTaskInput, + 'sessionId' | 'continue' | 'fork' | 'external' | 'externalDirectory' + > + version: 'v1' | 'v2' + directory: string + http: Http + signal: AbortSignal + prepare: ( + directory: string + ) => Promise<{ createBody: Record; policy: Record }> + allocated: (id: string, directory: string) => void +}): Promise<{ id: string; directory: string; owned: boolean; policyAcknowledged: boolean }> { + const v2 = input.version === 'v2' + const base = v2 ? '/api/session' : '/session' + let directory = input.task.external ? input.task.externalDirectory : input.directory + const query = (dir?: string) => (dir ? `?directory=${encodeURIComponent(dir)}` : '') + const get = (path: string) => input.http.request('GET', path, undefined, input.signal) + let selected: z.infer | undefined + if (input.task.sessionId) { + selected = session.parse( + await get(`${base}/${encodeURIComponent(input.task.sessionId)}${v2 ? '' : query(directory)}`) + ) + directory = v2 + ? (selected.location?.directory ?? directory) + : input.task.external + ? (input.task.externalDirectory ?? selected.directory ?? directory) + : directory + } else { + if (v2 && (input.task.external || input.task.continue)) { + const location = z + .looseObject({ directory: z.string() }) + .parse( + await get( + `/api/location${directory ? `?location[directory]=${encodeURIComponent(directory)}` : ''}` + ) + ) + directory = location.directory + } + if (input.task.continue) { + if (v2) { + let cursor: string | undefined + do { + input.signal.throwIfAborted() + const params = new URLSearchParams({ + directory: directory!, + parentID: 'null', + limit: '100', + order: 'desc' + }) + if (cursor) { + params.set('cursor', cursor) + } + const result = page.parse( + await input.http.requestRaw('GET', `${base}?${params}`, undefined, input.signal) + ) + selected = result.data.find( + (item) => item.location?.directory === directory && !item.parentID + ) + const next = result.cursor.next + if (!result.data.length || !next || next === cursor) { + break + } + cursor = next + } while (!selected) + } else { + selected = z + .array(session) + .parse(await get(`${base}${query(directory)}`)) + .find((item) => !item.parentID) + directory = input.task.external + ? (input.task.externalDirectory ?? selected?.directory ?? directory) + : directory + } + } + } + if (!directory) { + directory = z.looseObject({ directory: z.string() }).parse(await get('/path')).directory + } + const prepared = await input.prepare(directory) + if (selected && !input.task.fork) { + return { id: selected.id, directory, owned: false, policyAcknowledged: false } + } + // Do not lose a late allocation ID on local cancellation; cleanup is registered before any await. + const created = session.parse( + await input.http.request( + 'POST', + selected + ? `${base}/${encodeURIComponent(selected.id)}/fork${v2 ? '' : query(directory)}` + : `${base}${v2 ? '' : query(directory)}`, + selected ? {} : { ...prepared.createBody, ...(v2 ? { location: { directory } } : {}) }, + AbortSignal.timeout(10_000) + ) + ) + directory = created.location?.directory ?? created.directory ?? directory + input.allocated(created.id, directory) + input.signal.throwIfAborted() + let applied: unknown = created + if (selected) { + applied = await input.http.request( + 'PATCH', + `${base}/${encodeURIComponent(created.id)}${v2 ? '' : query(directory)}`, + prepared.policy, + input.signal + ) + if (!v2 && session.parse(applied).id !== created.id) { + throw new Error('OpenCode returned a different text task session') + } + } + const policyAcknowledged = + v2 || acknowledgesOpenCodeV1Policy(applied, prepared.policy, !!selected) + return { id: created.id, directory, owned: true, policyAcknowledged } +} diff --git a/src/main/opencode/opencode-text-task.ts b/src/main/opencode/opencode-text-task.ts new file mode 100644 index 00000000000..fd3381f7d4f --- /dev/null +++ b/src/main/opencode/opencode-text-task.ts @@ -0,0 +1,112 @@ +import { mergeCommandEnvironment } from '../../shared/command-environment' +import { textGenerationFailure } from '../../shared/text-generation-failure-copy' +import { cleanGeneratedCommitMessage } from '../../shared/source-control/ai/generation/commit-message-agent-output' +import { wslDistroForCommand } from '../../shared/wsl-paths' +import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' +import { OpenCodeTextTaskError, runOwnedOpenCodeTextTask } from './opencode-owned-text-task' +import { runOpenCodeWslTextTask } from './opencode-wsl-text-task' +import { killSourceControlAgentProcess } from '../text-generation/source-control-agent-termination' +import { + clearLocalGenerationCancelToken, + localGenerationLaneKey, + setLocalGenerationCancelToken +} from '../text-generation/source-control-generation-lanes' +import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from '../text-generation/source-control-generation-limits' +import type { + InternalTextGenerationResult, + LocalGenerationTarget, + SpawnSourceControlAgent, + TextGenerationOperation +} from '../text-generation/source-control-text-generation-types' + +export async function runOpenCodeTextTask(input: { + plan: CommitMessagePlan + target: LocalGenerationTarget + operation: TextGenerationOperation + spawnAgent: SpawnSourceControlAgent + shouldExecute?: () => boolean + legacyVariantFlag?: boolean +}): Promise { + const task = input.plan.openCodeTask + if (!task || input.plan.stdinPayload === null) { + return { + success: false, + ...textGenerationFailure('agentCouldNotStart', { label: input.plan.label }) + } + } + const canceled = new AbortController() + // WSL runtime preparation counts against this deadline too; it is not a separate budget. + const deadline = AbortSignal.timeout(SOURCE_CONTROL_GENERATION_TIMEOUT_MS) + const signal = AbortSignal.any([canceled.signal, deadline]) + const cancel = () => canceled.abort() + const lane = localGenerationLaneKey(input.operation, input.target.cwd) + setLocalGenerationCancelToken(lane, cancel) + try { + if (input.shouldExecute?.() === false) { + cancel() + canceled.signal.throwIfAborted() + } + const distro = + process.platform === 'win32' + ? wslDistroForCommand(input.target.cwd, input.target.wslDistro) + : null + const common = { + binary: input.plan.binary, + prefixArgs: task.prefixArgs, + cwd: input.target.cwd, + prompt: input.plan.stdinPayload, + runArgs: task.runArgs, + legacyVariantFlag: input.legacyVariantFlag, + operation: input.operation, + signal + } + const rawOutput = distro + ? await runOpenCodeWslTextTask( + { + ...common, + distro, + env: input.target.env, + commandEnv: input.plan.env, + timeoutMs: SOURCE_CONTROL_GENERATION_TIMEOUT_MS, + shouldExecute: input.shouldExecute + }, + { spawnAgent: input.spawnAgent } + ) + : await runOwnedOpenCodeTextTask({ + ...common, + env: + mergeCommandEnvironment(input.target.env, input.plan.env, process.platform) ?? + process.env, + spawn: input.spawnAgent, + stop: killSourceControlAgentProcess, + shouldExecute: input.shouldExecute + }) + const cleaned = cleanGeneratedCommitMessage(rawOutput) + if (!cleaned) { + throw new OpenCodeTextTaskError('session') + } + return { success: true, rawOutput: cleaned, agentLabel: input.plan.label } + } catch (error) { + if ( + canceled.signal.aborted || + (error instanceof OpenCodeTextTaskError && error.stage === 'superseded') + ) { + return { success: false, error: 'Generation canceled.', canceled: true } + } + return { + success: false, + ...(deadline.aborted + ? textGenerationFailure('timedOut', { + seconds: SOURCE_CONTROL_GENERATION_TIMEOUT_MS / 1000 + }) + : textGenerationFailure( + error instanceof OpenCodeTextTaskError && error.stage === 'session' + ? 'agentReportedError' + : 'agentCouldNotStart', + { label: input.plan.label } + )) + } + } finally { + clearLocalGenerationCancelToken(lane, cancel) + } +} diff --git a/src/main/opencode/opencode-wsl-guest-launch.test.ts b/src/main/opencode/opencode-wsl-guest-launch.test.ts new file mode 100644 index 00000000000..5930450a17c --- /dev/null +++ b/src/main/opencode/opencode-wsl-guest-launch.test.ts @@ -0,0 +1,140 @@ +import { spawnSync } from 'node:child_process' +import { chmodSync, mkdtempSync, mkdirSync, realpathSync, writeFileSync } from 'node:fs' +import { rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { parseOpenCodeCliVersion } from '../../shared/opencode-cli-version' +import { guestLoginShellLaunch } from './opencode-wsl-guest-launch' + +const roots: string[] = [] +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +/** A login profile that defines the command only as an unexported function and sets its own values. */ +function guestHome() { + const root = realpathSync(mkdtempSync(join(tmpdir(), 'orca-opencode-login-'))) + roots.push(root) + const home = join(root, 'home') + const bin = join(root, 'bin') + const repo = join(root, 'repo') + for (const directory of [home, bin, repo]) { + mkdirSync(directory) + } + writeFileSync( + join(home, '.profile'), + [ + 'echo Profile startup banner', + 'export OPENCODE_CONFIG=rc OPENCODE_SERVER_USERNAME=opencode OPENCODE_SERVER_PASSWORD=rc OPENCODE_PASSWORD=rc OPENCODE_DISABLE_SHARE=0', + `orca_fixture_opencode() { if [ "$1" = --version ]; then printf '1.18.31\\n'; else printf 'function:%s cwd:%s config:%s password:%s username:%s v2:%s share:%s\\n' "$*" "$(pwd)" "$OPENCODE_CONFIG" "$OPENCODE_SERVER_PASSWORD" "$OPENCODE_SERVER_USERNAME" "$OPENCODE_PASSWORD" "$OPENCODE_DISABLE_SHARE"; fi; }` + ].join('\n') + ) + writeFileSync(join(home, '.zprofile'), "emulate sh -c '. ~/.profile'\n") + // `/usr/bin/env` cannot call a function; the old route then reached PATH, as this one must. + // A fixture-only name keeps a real installed OpenCode from ever running here. + const executable = join(bin, 'orca_fixture_opencode') + writeFileSync( + executable, + `#!/bin/sh\nprintf 'path:%s config:%s password:%s\\n' "$*" "$OPENCODE_CONFIG" "$OPENCODE_SERVER_PASSWORD"\n` + ) + chmodSync(executable, 0o755) + return { + repo, + env: { + HOME: home, + SHELL: '/bin/sh', + PATH: `${bin}:/usr/bin:/bin`, + OPENCODE_SERVER_USERNAME: 'opencode' + } + } +} + +function runRaw(launch: ReturnType): string { + const result = spawnSync(launch.binary, launch.args, { + cwd: launch.cwd, + env: launch.env, + encoding: 'utf8' + }) + return result.stdout +} + +function run(launch: ReturnType): string { + return runRaw(launch).trim().split('\n').at(-1) ?? '' +} + +describe.skipIf(process.platform === 'win32')('guestLoginShellLaunch', () => { + it('reaches a profile-defined command, with task-private values winning over the profile', () => { + const guest = guestHome() + const launch = guestLoginShellLaunch( + { + binary: 'orca_fixture_opencode', + args: ['serve', '--port', '0'], + cwd: guest.repo, + env: { ...guest.env, OPENCODE_SERVER_PASSWORD: 'task-secret-7f3' }, + stdinMode: 'pipe', + useCwdForNative: true + }, + guest.env, + { + OPENCODE_SERVER_USERNAME: 'custom', + OPENCODE_PASSWORD: 'inline', + OPENCODE_DISABLE_SHARE: '0' + }, + { + OPENCODE_SERVER_USERNAME: 'opencode', + OPENCODE_SERVER_PASSWORD: 'task-secret-7f3', + OPENCODE_PASSWORD: 'task-v2-secret', + OPENCODE_DISABLE_SHARE: '1' + } + ) + + expect(launch.args.join(' ')).not.toContain('task-secret-7f3') + expect(run(launch)).toBe( + `function:serve --port 0 cwd:${guest.repo} config:rc password:task-secret-7f3 username:opencode v2:task-v2-secret share:1` + ) + }) + + it('applies inline command assignments after the profile, as the CLI route did', () => { + const guest = guestHome() + const launch = guestLoginShellLaunch( + { + binary: 'orca_fixture_opencode', + args: ['--version'], + cwd: guest.repo, + env: guest.env, + stdinMode: 'pipe', + useCwdForNative: true + }, + guest.env, + { OPENCODE_CONFIG: '/home/dev/work.json' } + ) + + expect(run(launch)).toBe('path:--version config:/home/dev/work.json password:rc') + }) +}) + +it.skipIf(process.platform === 'win32')( + 'captures only the selected version command after login banners', + () => { + const guest = guestHome() + const launch = guestLoginShellLaunch( + { + binary: 'orca_fixture_opencode', + args: ['--version'], + cwd: guest.repo, + env: guest.env, + stdinMode: 'pipe', + useCwdForNative: true + }, + guest.env, + {}, + {}, + true + ) + const output = runRaw(launch) + expect(output).toContain('Profile startup banner') + expect(parseOpenCodeCliVersion(launch.readStdout?.(output))).toBe('1.18.31') + expect(launch.readStdout?.('Profile startup banner\n1.18.31')).toBeNull() + } +) diff --git a/src/main/opencode/opencode-wsl-guest-launch.ts b/src/main/opencode/opencode-wsl-guest-launch.ts new file mode 100644 index 00000000000..814b81ce66a --- /dev/null +++ b/src/main/opencode/opencode-wsl-guest-launch.ts @@ -0,0 +1,55 @@ +import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' +import { + buildWslCapturedLoginShellCommand, + buildWslLoginShellCommand +} from '../../shared/wsl-login-shell-command' +import type { SourceControlAgentSpawnInput } from '../text-generation/source-control-text-generation-types' + +const TASK_ENV_PREFIX = 'ORCA_OPENCODE_TASK_ENV_' +const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/ + +/** + * Re-enter the guest login shell for the selected OpenCode, as the CLI route did: profile functions + * and rc account setup resolve again, then inline assignments and task-private values apply last. + */ +export function guestLoginShellLaunch( + input: SourceControlAgentSpawnInput, + baseEnv: NodeJS.ProcessEnv, + commandEnv: Readonly>, + privateEnv: Readonly> = {}, + captureVersion = false +): SourceControlAgentSpawnInput & { + env: NodeJS.ProcessEnv + readStdout?: (stdout: string) => string | null +} { + const env: NodeJS.ProcessEnv = { ...baseEnv, ...input.env } + const restore: string[] = [] + for (const [key, value] of Object.entries(privateEnv)) { + if (!ENV_NAME.test(key)) { + throw new Error('OpenCode task environment name is invalid') + } + // Private values (server credentials) travel by environment, never argv, and outrank rc files. + env[`${TASK_ENV_PREFIX}${key}`] = value + restore.push( + `${key}="$${TASK_ENV_PREFIX}${key}"; export ${key}; unset ${TASK_ENV_PREFIX}${key}; ` + ) + } + const assignments = Object.entries(commandEnv) + .filter(([key]) => !Object.hasOwn(privateEnv, key)) + .map(([key, value]) => `${key}=${value}`) + // Same command text as the CLI route, so a profile function named like the binary still resolves. + const command = assignments.length + ? ['/usr/bin/env', ...assignments, input.binary, ...input.args] + : [input.binary, ...input.args] + const script = `${restore.join('')}cd ${quotePosixShell(input.cwd ?? '.')} && ${command + .map(quotePosixShell) + .join(' ')}` + const captured = captureVersion ? buildWslCapturedLoginShellCommand(script) : undefined + return { + ...input, + binary: '/bin/sh', + args: ['-lc', captured?.command ?? buildWslLoginShellCommand(script)], + env, + ...(captured ? { readStdout: captured.readStdout } : {}) + } +} diff --git a/src/main/opencode/opencode-wsl-text-task-entry.ts b/src/main/opencode/opencode-wsl-text-task-entry.ts new file mode 100644 index 00000000000..0349c4254ed --- /dev/null +++ b/src/main/opencode/opencode-wsl-text-task-entry.ts @@ -0,0 +1,99 @@ +import { z } from 'zod' +import { SearchSubprocessLineAccumulator } from '../../shared/search-subprocess-lines' +import { killSourceControlAgentProcess } from '../text-generation/source-control-agent-termination' +import { spawnSupervisedAgent } from '../text-generation/source-control-supervised-agent-spawn' +import { + OPENCODE_WSL_TEXT_TASK_CLEANUP_MS, + OPENCODE_WSL_TEXT_TASK_REQUEST_MAX_BYTES, + type OpenCodeWslTextTaskResult +} from './opencode-wsl-text-task-protocol' +import { OpenCodeTextTaskError, runOwnedOpenCodeTextTask } from './opencode-owned-text-task' +import { guestLoginShellLaunch } from './opencode-wsl-guest-launch' + +const request = z.object({ + nonce: z.string().regex(/^[0-9a-f]{32}$/), + binary: z.string().min(1), + prefixArgs: z.array(z.string()), + prompt: z.string(), + runArgs: z.array(z.string()), + /** Inline command assignments; applied after the inner login rc, as the CLI route did. */ + commandEnv: z.record(z.string(), z.string()).optional(), + legacyVariantFlag: z.boolean().optional(), + operation: z + .enum([ + 'commit-message', + 'pull-request-fields', + 'branch-name', + 'jira-issue-summary', + 'conversation-name' + ]) + .optional(), + timeoutMs: z.number().int().positive() +}) + +// The launcher unset NODE_OPTIONS for this Node; OpenCode's own login shell sets it up again. +const env: NodeJS.ProcessEnv = { ...process.env } + +// The launcher's stdin EOF, including Orca's death, cancels the task. +const launcher = new AbortController() +let started = false +const lines = new SearchSubprocessLineAccumulator(OPENCODE_WSL_TEXT_TASK_REQUEST_MAX_BYTES) +process.stdin.on('data', (chunk: Buffer) => { + if (started) { + return + } + if (!lines.push(chunk, (line) => void start(line))) { + process.exit(1) + } +}) +process.stdin.on('end', () => launcher.abort()) +process.stdin.on('error', () => launcher.abort()) +process.stdout.on('error', () => launcher.abort()) + +async function start(line: string): Promise { + if (started) { + return + } + started = true + const task = request.parse(JSON.parse(line)) + // Backstop for a wedged cleanup: exiting lets the provider supervisor see its owner gone. + setTimeout(() => process.exit(124), task.timeoutMs + OPENCODE_WSL_TEXT_TASK_CLEANUP_MS).unref() + let readVersionStdout: ((stdout: string) => string | null) | undefined + let result: OpenCodeWslTextTaskResult + try { + const text = await runOwnedOpenCodeTextTask({ + binary: task.binary, + prefixArgs: task.prefixArgs, + // The launcher's login shell entered the workspace; this is the real guest directory. + cwd: process.cwd(), + env, + prompt: task.prompt, + runArgs: task.runArgs, + legacyVariantFlag: task.legacyVariantFlag, + operation: task.operation, + signal: AbortSignal.any([launcher.signal, AbortSignal.timeout(task.timeoutMs)]), + readVersionStdout: (stdout) => readVersionStdout?.(stdout) ?? null, + spawn: (input, context) => { + const launch = guestLoginShellLaunch( + input, + env, + task.commandEnv ?? {}, + context?.privateEnv, + context?.captureVersion + ) + if (context?.captureVersion) { + readVersionStdout = launch.readStdout + } + return spawnSupervisedAgent(launch, launch.env) + }, + stop: (child) => killSourceControlAgentProcess(child) + }) + result = { ok: true, text } + } catch (error) { + result = { + ok: false, + stage: error instanceof OpenCodeTextTaskError ? error.stage : 'aborted' + } + } + process.stdout.write(`${task.nonce}${JSON.stringify(result)}\n`, () => process.exit(0)) +} diff --git a/src/main/opencode/opencode-wsl-text-task-protocol.ts b/src/main/opencode/opencode-wsl-text-task-protocol.ts new file mode 100644 index 00000000000..18733538dac --- /dev/null +++ b/src/main/opencode/opencode-wsl-text-task-protocol.ts @@ -0,0 +1,12 @@ +import { z } from 'zod' + +export const OPENCODE_WSL_TEXT_TASK_REQUEST_MAX_BYTES = 32 * 1024 * 1024 +/** Session interrupt/delete plus the provider supervisor's full stop, with margin. */ +export const OPENCODE_WSL_TEXT_TASK_CLEANUP_MS = 15_000 + +export const openCodeWslTextTaskResult = z.discriminatedUnion('ok', [ + z.object({ ok: z.literal(true), text: z.string() }), + z.object({ ok: z.literal(false), stage: z.enum(['startup', 'session', 'superseded', 'aborted']) }) +]) + +export type OpenCodeWslTextTaskResult = z.infer diff --git a/src/main/opencode/opencode-wsl-text-task.test.ts b/src/main/opencode/opencode-wsl-text-task.test.ts new file mode 100644 index 00000000000..fc57d87dadf --- /dev/null +++ b/src/main/opencode/opencode-wsl-text-task.test.ts @@ -0,0 +1,114 @@ +import { ChildProcess } from 'node:child_process' +import { PassThrough } from 'node:stream' +import { z } from 'zod' +import { describe, expect, it, vi } from 'vitest' +import type { + SourceControlAgentSpawnInput, + SpawnedSourceControlAgentProcess +} from '../text-generation/source-control-text-generation-types' +import { runOpenCodeWslTextTask } from './opencode-wsl-text-task' + +const guestRequest = z.looseObject({ nonce: z.string() }) +type GuestRequest = z.infer + +/** A guest launcher that answers its request frame with `respond`, after login-shell chatter. */ +function fakeGuest(respond: (request: GuestRequest, canceled: Promise) => Promise) { + const launched: SourceControlAgentSpawnInput[] = [] + const requests: GuestRequest[] = [] + let child!: SpawnedSourceControlAgentProcess + const spawnAgent = vi.fn((input: SourceControlAgentSpawnInput) => { + launched.push(input) + const stdin = new PassThrough() + const stdout = new PassThrough() + const launcher = new ChildProcess() + Object.defineProperties(launcher, { + stdout: { writable: true, configurable: true, enumerable: true }, + stderr: { writable: true, configurable: true, enumerable: true }, + stdin: { writable: true, configurable: true, enumerable: true } + }) + Object.assign(launcher, { pid: 99, stdin, stdout, stderr: new PassThrough() }) + child = launcher + const canceled = new Promise((resolve) => stdin.on('finish', () => resolve())) + stdout.write('Welcome to Ubuntu\n') + stdin.once('data', (chunk: Buffer) => { + const request = guestRequest.parse(JSON.parse(chunk.toString('utf8'))) + requests.push(request) + void respond(request, canceled).then((result) => { + stdout.write(`${request.nonce}${JSON.stringify(result)}\n`) + setTimeout(() => { + Object.assign(launcher, { exitCode: 0 }) + launcher.emit('close', 0) + }, 10) + }) + }) + return launcher + }) + return { launched, requests, spawnAgent, child: () => child } +} + +const prepare = vi.fn(async () => ({ + node: '/home/dev/.cache/orca/node-runtime/bin/node', + helper: '/mnt/c/Program Files/Orca/resources/relay/wsl/opencode-text-task-wsl.cjs' +})) + +function task(signal = new AbortController().signal) { + return { + distro: 'Ubuntu', + cwd: '\\\\wsl.localhost\\Ubuntu\\home\\dev\\repo', + commandEnv: { OPENCODE_CONFIG: '/home/dev/work.json' }, + binary: 'opencode', + prefixArgs: ['--print-logs'], + prompt: 'Write a commit message', + runArgs: ['--model', 'anthropic/claude-sonnet', '--file', 'C:\\notes\\context.txt'], + signal, + timeoutMs: 60_000 + } +} + +describe('runOpenCodeWslTextTask', () => { + it('runs the guest task through the target login shell and returns its framed text', async () => { + const guest = fakeGuest(async () => ({ ok: true, text: 'feat: add lanterns' })) + + await expect( + runOpenCodeWslTextTask(task(), { prepare, spawnAgent: guest.spawnAgent }) + ).resolves.toBe('feat: add lanterns') + + expect(guest.launched[0]).toMatchObject({ + binary: '/usr/bin/env', + args: [ + '-u', + 'NODE_OPTIONS', + '/home/dev/.cache/orca/node-runtime/bin/node', + '/mnt/c/Program Files/Orca/resources/relay/wsl/opencode-text-task-wsl.cjs' + ], + cwd: '\\\\wsl.localhost\\Ubuntu\\home\\dev\\repo', + wslDistro: 'Ubuntu', + stdinMode: 'pipe' + }) + // The guest applies these after OpenCode's own login rc, not to the helper launch. + expect(guest.launched[0].commandEnv).toBeUndefined() + expect(guest.requests[0]).toMatchObject({ + binary: 'opencode', + prefixArgs: ['--print-logs'], + prompt: 'Write a commit message', + runArgs: ['--model', 'anthropic/claude-sonnet', '--file', '/mnt/c/notes/context.txt'], + commandEnv: { OPENCODE_CONFIG: '/home/dev/work.json' } + }) + expect(guest.child().exitCode).toBe(0) + }) + + it('cancels by ending the guest stdin and settles only after the guest exits', async () => { + const controller = new AbortController() + const guest = fakeGuest(async (_request, canceled) => { + setImmediate(() => controller.abort(new Error('canceled by user'))) + await canceled + return { ok: false, stage: 'aborted' } + }) + + await expect( + runOpenCodeWslTextTask(task(controller.signal), { prepare, spawnAgent: guest.spawnAgent }) + ).rejects.toThrow('canceled by user') + + expect(guest.child().exitCode).toBe(0) + }) +}) diff --git a/src/main/opencode/opencode-wsl-text-task.ts b/src/main/opencode/opencode-wsl-text-task.ts new file mode 100644 index 00000000000..90e22eb371c --- /dev/null +++ b/src/main/opencode/opencode-wsl-text-task.ts @@ -0,0 +1,227 @@ +import { randomBytes } from 'node:crypto' +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { getAppEnvironment } from '../../shared/app-environment' +import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason' +import { OPENCODE_WSL_TEXT_TASK_FILENAME } from '../../shared/remote-bundle-artifacts' +import { SearchSubprocessLineAccumulator } from '../../shared/search-subprocess-lines' +import { relayBundleCandidates } from '../ssh/relay-bundle-paths' +import { ensureWslPinnedRuntime } from '../wsl/execution/wsl-pinned-runtime' +import { runWslProcess, type WslSpec } from '../wsl/execution/wsl-runner' +import { describeWslProcessFailure } from '../wsl/execution/wsl-process-failure' +import { translateArgsForWsl } from '../git/command-runner/wsl-path-translation' +import { spawnSourceControlAgent } from '../text-generation/source-control-agent-launch' +import { killSourceControlAgentProcess } from '../text-generation/source-control-agent-termination' +import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from '../text-generation/source-control-generation-limits' +import { waitForProcessExitUntil } from '../provider-process/provider-process-exit-deadline' +import type { + TextGenerationOperation, + SpawnedSourceControlAgentProcess, + SpawnSourceControlAgent +} from '../text-generation/source-control-text-generation-types' +import { OpenCodeTextTaskError } from './opencode-owned-text-task' +import { + OPENCODE_WSL_TEXT_TASK_CLEANUP_MS, + openCodeWslTextTaskResult, + type OpenCodeWslTextTaskResult +} from './opencode-wsl-text-task-protocol' + +export type OpenCodeWslTextTask = { + distro: string + /** The generation target's directory; the guest login shell enters it as existing launches do. */ + cwd: string + env?: NodeJS.ProcessEnv + /** Command assignments; the guest applies them after its login rc, as existing launches do. */ + commandEnv?: Record + binary: string + prefixArgs: readonly string[] + prompt: string + runArgs: readonly string[] + legacyVariantFlag?: boolean + operation?: TextGenerationOperation + signal: AbortSignal + /** Checked here before the guest starts; the guest cannot call back. */ + shouldExecute?: () => boolean + /** Guest-side deadline backstop for when this process cannot cancel it. */ + timeoutMs: number +} + +export type OpenCodeWslGuestRuntime = { node: string; helper: string } + +export type OpenCodeWslTextTaskDeps = { + prepare?: (distro: string) => Promise + spawnAgent?: SpawnSourceControlAgent + stop?: (child: SpawnedSourceControlAgentProcess) => Promise +} + +const PREPARATION_TIMEOUT_MS = 180_000 +const PREPARED_TTL_MS = 10 * 60_000 +const prepared = new Map; expires: number }>() +// Only the APIs the bundled task uses; the scanner's SQLite requirement does not apply here. +const GUEST_NODE_PROBE = + "if(typeof Promise.withResolvers!=='function'||typeof AbortSignal.any!=='function'||typeof AbortSignal.timeout!=='function'||typeof fetch!=='function'||typeof ReadableStream!=='function')process.exit(3);process.stdout.write(process.execPath)" + +async function prepareGuestRuntime(distro: string): Promise { + const helper = relayBundleCandidates('wsl') + .map((directory) => join(directory, OPENCODE_WSL_TEXT_TASK_FILENAME)) + .find(existsSync) + if (!helper) { + throw new Error('The bundled WSL OpenCode text task is missing. Reinstall Orca to repair it.') + } + const run = async (spec: WslSpec, timeoutMs = 15_000): Promise => { + const result = await runWslProcess({ ...spec, distro, timeoutMs, maxOutputBytes: 16 * 1024 }) + if (result.code !== 0 || result.timedOut) { + throw new Error(`WSL ${distro}: ${describeWslProcessFailure(result)}`) + } + return result.stdout.trim() + } + let node: string | null = null + try { + node = await run({ program: 'node', args: ['-e', GUEST_NODE_PROBE], loginPath: 'preferred' }) + } catch { + // Missing or too old: provision the pinned runtime instead. + } + if (!node?.startsWith('/')) { + node = await ensureWslPinnedRuntime( + run, + join(getAppEnvironment().getPath('userData'), 'orcad-artifacts'), + AbortSignal.timeout(PREPARATION_TIMEOUT_MS) + ) + } + return { + node, + helper: await run({ program: 'wslpath', args: ['-a', '-u', helper], loginPath: 'none' }) + } +} + +/** Shared per distro and bounded on its own, so one cancelled task cannot abort another's install. */ +function preparedGuestRuntime(distro: string): Promise { + const key = distro.toLowerCase() + const entry = prepared.get(key) + if (entry && entry.expires > Date.now()) { + return entry.runtime + } + const runtime = prepareGuestRuntime(distro) + prepared.set(key, { runtime, expires: Date.now() + PREPARED_TTL_MS }) + runtime.catch(() => { + if (prepared.get(key)?.runtime === runtime) { + prepared.delete(key) + } + }) + return runtime +} + +/** Waits within the task's own deadline; the shared install keeps its separate bound. */ +async function prepareOpenCodeWslTextTask( + distro: string, + signal: AbortSignal, + deps: OpenCodeWslTextTaskDeps = {} +): Promise { + try { + return await waitForPromiseWithSignal((deps.prepare ?? preparedGuestRuntime)(distro), signal) + } catch (error) { + if (signal.aborted) { + throw signal.reason + } + throw new OpenCodeTextTaskError('startup', { cause: error }) + } +} + +export async function runOpenCodeWslTextTask( + input: OpenCodeWslTextTask, + deps: OpenCodeWslTextTaskDeps = {} +): Promise { + const startedAt = Date.now() + const { signal } = input + const runtime = await prepareOpenCodeWslTextTask(input.distro, signal, deps) + signal.throwIfAborted() + if (input.shouldExecute?.() === false) { + throw new OpenCodeTextTaskError('superseded') + } + const nonce = randomBytes(16).toString('hex') + let child: SpawnedSourceControlAgentProcess + try { + child = (deps.spawnAgent ?? spawnSourceControlAgent)({ + // The helper Node starts without the user's startup options; OpenCode's login shell restores them. + binary: '/usr/bin/env', + args: ['-u', 'NODE_OPTIONS', runtime.node, runtime.helper], + cwd: input.cwd, + env: input.env, + wslDistro: input.distro, + stdinMode: 'pipe', + useCwdForNative: true + }) + } catch (error) { + throw new OpenCodeTextTaskError('startup', { cause: error }) + } + const exited = new Promise((resolve) => child.once('close', () => resolve())) + let result: OpenCodeWslTextTaskResult | undefined + // Login-shell rc output shares stdout; only the nonce-prefixed line is the guest's result. + const lines = new SearchSubprocessLineAccumulator( + MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES, + 'discard' + ) + child.stdout?.on('data', (chunk: Buffer) => { + if (result) { + return + } + lines.push(chunk, (line) => { + const frame = line.trimEnd() + if (!result && frame.startsWith(nonce)) { + try { + result = openCodeWslTextTaskResult.parse(JSON.parse(frame.slice(nonce.length))) + } catch { + // A malformed frame is no result; the exit below reports the failure. + } + } + }) + }) + child.stderr?.on('data', () => {}) + child.once('error', () => {}) + child.stdin?.on('error', () => {}) + // Ending stdin is the guest's cancel; it then stops its server before exiting. + const cancel = (): void => { + child.stdin?.end() + } + signal.addEventListener('abort', cancel, { once: true }) + try { + child.stdin?.write( + `${JSON.stringify({ + nonce, + binary: input.binary, + prefixArgs: translateArgsForWsl([...input.prefixArgs]), + prompt: input.prompt, + // Existing WSL launches translate Windows paths in every argument, e.g. `--file C:\x`. + runArgs: translateArgsForWsl([...input.runArgs]), + legacyVariantFlag: input.legacyVariantFlag, + operation: input.operation, + commandEnv: input.commandEnv, + timeoutMs: Math.max(1, input.timeoutMs - (Date.now() - startedAt)) + })}\n` + ) + if (signal.aborted) { + cancel() + } + // Wait for the guest's own exit; force-stop the launcher only past the guest's cleanup bound. + const bound = startedAt + input.timeoutMs + OPENCODE_WSL_TEXT_TASK_CLEANUP_MS - Date.now() + await waitForProcessExitUntil(exited, Math.max(0, bound)) + if (child.exitCode === null && child.signalCode === null) { + await (deps.stop ?? killSourceControlAgentProcess)(child) + await exited + } + } finally { + signal.removeEventListener('abort', cancel) + child.stdin?.end() + } + if (result?.ok) { + return result.text + } + if (signal.aborted) { + throw signal.reason + } + if (!result) { + // The guest never answered; its prepared runtime may be gone. + prepared.delete(input.distro.toLowerCase()) + } + throw new OpenCodeTextTaskError(result && result.stage !== 'aborted' ? result.stage : 'startup') +} diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-contract.test.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-contract.test.ts new file mode 100644 index 00000000000..fb490784b8c --- /dev/null +++ b/src/main/runtime/agent-session/naming/structured-chat-naming-contract.test.ts @@ -0,0 +1,211 @@ +import { existsSync, readFileSync } from 'node:fs' +import { dirname } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { getDefaultSettings } from '../../../../shared/constants' +import { agentSessionRecordFixture } from '../../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' +import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import { savedChatNamingCatalog } from '../../../../shared/chat-naming-catalog-work.test-fixture' +import type { SpawnSourceControlAgent } from '../../../text-generation/source-control-text-generation-types' +import { createMockDiscoveryChild } from '../../../text-generation/commit-message-text-generation-test-harness' +import { structuredChatNamingDeps } from './structured-chat-naming-runtime' +import type { StructuredAgentSessionAdapter } from '../../../native-chat/agent-session-wire/structured-agent-session-adapter' +import recordings from '../../__fixtures__/chat-naming-recorded-output.json' +import type * as OwnedOpenCodeTask from '../../../opencode/opencode-owned-text-task' + +const boundary = vi.hoisted(() => ({ + spawn: vi.fn(), + native: vi.fn>(), + openCode: vi.fn( + async (_input: { cwd: string; env?: NodeJS.ProcessEnv; prompt: string }) => 'Owned title' + ), + account: vi.fn((_provider: string, id: string) => ({ + XDG_DATA_HOME: `/profiles/${id}/data`, + XDG_STATE_HOME: `/profiles/${id}/state` + })) +})) +vi.mock('../../../opencode/opencode-owned-text-task', async (importOriginal) => ({ + ...(await importOriginal()), + runOwnedOpenCodeTextTask: boundary.openCode +})) +vi.mock('../../../text-generation/source-control-agent-launch', () => ({ + spawnSourceControlAgent: boundary.spawn +})) +vi.mock('../../../native-chat/agent-session-wire/structured-agent-session-registry', () => ({ + getStructuredAgentSessionHost: () => ({ deps: { adapter: { generateText: boundary.native } } }) +})) +vi.mock('../../../managed-data-accounts/service', () => ({ + getManagedDataAccountService: () => ({ + restoreOriginalEnvironment: () => {}, + environmentForAccount: boundary.account + }) +})) +beforeEach(() => { + vi.clearAllMocks() + boundary.spawn.mockReset() + boundary.native.mockReset() + boundary.openCode.mockClear() + vi.stubEnv('ORCA_PI_SOURCE_AGENT_DIR', undefined) +}) +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllEnvs() +}) + +function rig() { + const settings = getDefaultSettings('/isolated') + settings.defaultTuiAgent = 'codex' + settings.sourceControlAi = savedChatNamingCatalog(0) + const env = { + PATH: '/usr/bin', + PI_CODING_AGENT_DIR: '/configured/pi', + OPENCODE_CONFIG_DIR: '/configured/oc', + OPENCODE_AUTH_CONTENT: 'current-account-sentinel' + } + const runtime = { + resolveWorkspace: vi.fn( + async (): Promise<{ path: string; executionHostId: ExecutionHostId }> => ({ + path: '/workspace/folder', + executionHostId: 'local' + }) + ), + resolveNamingEnvironment: vi.fn(async () => env), + getAgentEnvResolvers: () => ({ resolveBaseEnvironment: async () => env }), + workerTaskTitle: () => null, + retitleOpenTab: () => {} + } + return { + settings, + runtime, + deps: structuredChatNamingDeps(() => ({ getSettings: () => settings }), runtime, { + warn: vi.fn(), + error: vi.fn() + }) + } +} + +function reply(stdout: string, stderr = '', code = 0) { + const child = createMockDiscoveryChild() + child.stdin.end.mockImplementation(() => + queueMicrotask(() => { + child.stdout.emit('data', Buffer.from(stdout)) + child.stderr.emit('data', Buffer.from(stderr)) + child.emit('exit', code, null) + child.emit('close', code, null) + }) + ) + boundary.spawn.mockReturnValue(child) + return child +} + +it.each(recordings.filter((capture) => capture.provider === 'pi' || capture.provider === 'omp'))( + 'consumes recorded $provider output through runtime, request, planner and parser', + async (capture) => { + const { provider, stdout, stderr, exitCode, name, error } = capture + if (!isTuiAgent(provider)) { + throw new Error('Unknown recorded provider') + } + const state = rig() + const source = state.settings.sourceControlAi + if (!source) { + throw new Error('Missing naming configuration') + } + source.agentId = 'codex' + if (provider === 'pi') { + source.selectedModelByAgent.pi = 'openai/gpt-6.1-sol' + source.discoveredModelsByAgent = { + pi: [{ id: 'openai/gpt-6.1-sol', label: 'Recorded model' }] + } + } + const record = agentSessionRecordFixture() + record.provider = provider + record.accountHome = { variable: 'PI_CODING_AGENT_DIR', path: '/recorded/pi' } + const usesFilePrompt = provider === 'omp' + const child = reply(stdout, stderr, exitCode) + let promptPath = '' + if (usesFilePrompt) { + boundary.spawn.mockImplementationOnce((input) => { + promptPath = input.args.find((arg) => arg.startsWith('@'))?.slice(1) ?? '' + expect(readFileSync(promptPath, 'utf8')).toContain('Repair login') + return child + }) + } + const result = await state.deps.generate(record, 'Repair login') + if (name) { + expect(result).toEqual({ name }) + } else { + expect(result).toMatchObject({ error: expect.stringContaining(error ?? '') }) + expect(result).not.toHaveProperty('name') + if (provider === 'pi') { + expect(result).toMatchObject({ failureOutput: { exitCode: 1, stdout, stderr } }) + } + } + expect(boundary.spawn).toHaveBeenCalledOnce() + const spawn = boundary.spawn.mock.calls[0]?.[0] + expect(spawn).toMatchObject({ + binary: usesFilePrompt ? 'omp' : 'pi', + cwd: '/workspace/folder', + stdinMode: 'pipe' + }) + expect(child.stdin.end).toHaveBeenCalledExactlyOnceWith( + usesFilePrompt ? undefined : expect.stringContaining('Repair login') + ) + if (usesFilePrompt) { + expect(spawn?.args.some((arg) => arg.includes('Repair login'))).toBe(false) + await vi.waitFor(() => expect(existsSync(dirname(promptPath))).toBe(false)) + } + expect(spawn?.env?.PI_CODING_AGENT_DIR).toBe('/recorded/pi') + expect(boundary.native).not.toHaveBeenCalled() + if (provider === 'pi') { + const modelIndex = spawn?.args.indexOf('--model') ?? -1 + expect(spawn?.args.slice(modelIndex, modelIndex + 2)).toEqual([ + '--model', + 'openai/gpt-6.1-sol' + ]) + source.actions = { conversationName: { agentId: 'pi' } } + boundary.spawn.mockClear() + const explicit = reply(stdout, stderr, exitCode) + expect(await state.deps.generate(record, 'Repair login')).toEqual(result) + const explicitSpawn = boundary.spawn.mock.calls[0]?.[0] + expect(explicitSpawn).toMatchObject({ + binary: 'pi', + env: { PI_CODING_AGENT_DIR: '/configured/pi' } + }) + const explicitModelIndex = explicitSpawn?.args.indexOf('--model') ?? -1 + expect(explicitSpawn?.args.slice(explicitModelIndex, explicitModelIndex + 2)).toEqual([ + '--model', + 'openai/gpt-6.1-sol' + ]) + expect(explicit.stdin.end).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining('Repair login') + ) + } + } +) + +it.each(['opencode', 'opencode2'] as const)( + 'routes %s naming into the owned task with its selected account', + async (provider) => { + const state = rig() + const record = agentSessionRecordFixture() + record.provider = provider + record.accountHome = { + kind: 'opencode', + locator: { kind: 'managed', managedProfileId: 'recorded' } + } + expect(await state.deps.generate(record, 'Repair login')).toEqual({ name: 'Owned title' }) + expect(boundary.openCode).toHaveBeenCalledWith( + expect.objectContaining({ + cwd: '/workspace/folder', + prompt: expect.stringContaining('Repair login'), + env: expect.objectContaining({ + XDG_DATA_HOME: '/profiles/recorded/data', + XDG_STATE_HOME: '/profiles/recorded/state', + OPENCODE_AUTH_CONTENT: undefined + }) + }) + ) + expect(boundary.spawn).not.toHaveBeenCalled() + expect(boundary.account).toHaveBeenCalledWith('opencode', 'recorded') + } +) diff --git a/src/main/runtime/cli-terminal-create-host-session-binding.test.ts b/src/main/runtime/cli-terminal-create-host-session-binding.test.ts index cde4de4f876..97860bd75b5 100644 --- a/src/main/runtime/cli-terminal-create-host-session-binding.test.ts +++ b/src/main/runtime/cli-terminal-create-host-session-binding.test.ts @@ -257,7 +257,12 @@ it.each(['refused', 'adopted', 'stable-adopted', 'ensure-adopted', 'fresh-unavai isAlternateScreen: false, replay: 'provider backlog', shellReadyArmed: true, - openCodeCapabilities: { version: '2.0.16', pluginApi: 'v2', promptMode: 'prefill' }, + openCodeCapabilities: { + version: '2.0.16', + pluginApi: 'v2', + v1SessionPolicyFiltersTools: false, + promptMode: 'prefill' + }, ...(adopted ? { launchAgent: 'codex', launchConfig: config, launchToken: 'owner-token' } : {}), diff --git a/src/main/runtime/orchestration-opencode-model-host.test.ts b/src/main/runtime/orchestration-opencode-model-host.test.ts index 68a67b4b681..484842611c0 100644 --- a/src/main/runtime/orchestration-opencode-model-host.test.ts +++ b/src/main/runtime/orchestration-opencode-model-host.test.ts @@ -58,6 +58,7 @@ describe('OpenCode worker model execution host', () => { vi.mocked(probeOpenCodeLaunchCapabilities).mockResolvedValue({ version: '1.18.30', pluginApi: 'v1', + v1SessionPolicyFiltersTools: true, promptMode: 'submit' }) }) @@ -65,6 +66,7 @@ describe('OpenCode worker model execution host', () => { vi.mocked(probeOpenCodeLaunchCapabilities).mockResolvedValue({ version: '2.0.14', pluginApi: 'v2', + v1SessionPolicyFiltersTools: false, promptMode: 'unknown' }) await expect(probe(host())).rejects.toMatchObject({ diff --git a/src/main/text-generation/agent-generation-request.ts b/src/main/text-generation/agent-generation-request.ts index c2225460fc0..dd365ffbaf1 100644 --- a/src/main/text-generation/agent-generation-request.ts +++ b/src/main/text-generation/agent-generation-request.ts @@ -1,3 +1,4 @@ +import { conversationNameTaskPrompt } from '../../shared/source-control/ai/generation/conversation-name-generation' import { textGenerationFailureCodeFields } from '../../shared/text-generation-failure-copy' import { runClaudeGenerationAttempts } from '../../shared/claude-background-run-isolation' import { @@ -14,6 +15,7 @@ import type { ResolvedSourceControlAiGenerationParams } from '../../shared/sourc import { openCodeVariantRetryPlan } from '../../shared/opencode-generation-command' import { copilotUnavailableModelRetryPlan } from './copilot-unavailable-model-retry' import { runLocalPlanForAgent } from './source-control-local-generation' +import { runOpenCodeTextTask } from '../opencode/opencode-text-task' import { emptyResultFailure } from './source-control-agent-failure' import { runRemoteSourceControlPlan } from './source-control-remote-generation' import type { @@ -44,7 +46,11 @@ export async function runGenerationRequest(input: { ...input.params, backslash: commandBackslashMode(input.target) } - const planned = planCommitMessageGeneration(params, input.prompt) + const prompt = + input.operation === 'conversation-name' + ? conversationNameTaskPrompt(input.prompt) + : input.prompt + const planned = planCommitMessageGeneration(params, prompt) if (!planned.ok) { return { success: false, error: planned.error, ...textGenerationFailureCodeFields(planned) } } @@ -56,21 +62,31 @@ export async function runGenerationRequest(input: { target: input.target, operation: input.operation }) - : runLocalPlanForAgent({ - agentId: input.params.agentId, - plan, - target: input.target, - operation: input.operation, - spawnAgent: input.spawnAgent, - shouldExecute: input.shouldExecute - }) + : plan.openCodeTask + ? runOpenCodeTextTask({ + plan, + target: input.target, + operation: input.operation, + spawnAgent: input.spawnAgent, + shouldExecute: input.shouldExecute, + legacyVariantFlag: + input.params.agentId === 'opencode' && input.operation !== 'jira-issue-summary' + }) + : runLocalPlanForAgent({ + agentId: input.params.agentId, + plan, + target: input.target, + operation: input.operation, + spawnAgent: input.spawnAgent, + shouldExecute: input.shouldExecute + }) let result = await runClaudeGenerationAttempts({ agentId: input.params.agentId, run: (attempt): Promise => { if (attempt.strictMcp && !attempt.legacyToolPolicy) { return execute(plan) } - const retry = planCommitMessageGeneration(params, input.prompt, attempt) + const retry = planCommitMessageGeneration(params, prompt, attempt) return retry.ok ? execute(retry.plan) : Promise.resolve({ diff --git a/src/main/text-generation/antigravity-generation-stream.test.ts b/src/main/text-generation/antigravity-generation-stream.test.ts index 66053c12c52..588c7a782eb 100644 --- a/src/main/text-generation/antigravity-generation-stream.test.ts +++ b/src/main/text-generation/antigravity-generation-stream.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { parseAntigravityGenerationOutput } from '../../shared/antigravity-generation-stream' import { generateCommitMessageFromContext, @@ -35,11 +35,22 @@ describe('Antigravity generation stream', () => { params, target: { kind: 'local', cwd: 'C:\\folder-workspace' }, spawnAgent: (input) => { - expect(input.args.join(' ').length).toBeLessThan(100) + if (input.args.includes('--help')) { + const probe = createMockDiscoveryChild() + probe.stdin.end.mockImplementation(() => + queueMicrotask(() => { + probe.stdout.emit('data', Buffer.from(' --settings \n')) + probe.emit('close', 0) + }) + ) + return probe + } + expect(input.args.join(' ').length).toBeLessThan(30_000) expect(input.args).toContain('--input-format=stream-json') return child } }) + await vi.waitFor(() => expect(child.stdin.end).toHaveBeenCalled()) const input = JSON.parse(child.stdin.end.mock.calls[0]?.[0] ?? '') expect(input.message.content[0].text).toContain('(diff truncated,') expect(input.message.content[0].text.length).toBeGreaterThan(200_000) diff --git a/src/main/text-generation/commit-message-text-generation-cancellation.test.ts b/src/main/text-generation/commit-message-text-generation-cancellation.test.ts index 197feba44f1..bcd900a3728 100644 --- a/src/main/text-generation/commit-message-text-generation-cancellation.test.ts +++ b/src/main/text-generation/commit-message-text-generation-cancellation.test.ts @@ -53,6 +53,31 @@ beforeEach(() => { spawnMock.mockClear() }) +function generationSpawns() { + return spawnMock.mock.calls.filter((call) => !spawnedAgentArgv(call).includes('mcp')) +} + +function policyProbeChild() { + const child = createMockDiscoveryChild() + child.stdin.end.mockImplementation(() => + queueMicrotask(() => { + child.stdout.emit('data', Buffer.from('[]')) + child.emit('close', 0) + }) + ) + return child +} + +function generationChildren(...children: ReturnType[]) { + spawnMock.mockImplementation((...args) => { + const child = spawnedAgentArgv(args).includes('mcp') ? policyProbeChild() : children.shift() + if (!child) { + throw new Error('Unexpected generation process') + } + return child + }) +} + describe('generateCommitMessageFromContext on the Windows direct-child path', () => { const largePatch = Array.from( { length: 40 }, @@ -468,7 +493,7 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', () it('publishes Codex cancellation immediately but holds its home lock until close', async () => { const firstChild = createMockDiscoveryChild() const secondChild = createMockDiscoveryChild() - spawnMock.mockReturnValueOnce(firstChild as never).mockReturnValueOnce(secondChild as never) + generationChildren(firstChild, secondChild) const env = { CODEX_HOME: '/managed/codex-generation-home' } const context = { branch: 'main', stagedSummary: 'M\tREADME.md', stagedPatch: '+hello' } const params = { agentId: 'codex' as const, model: 'gpt-5.5' } @@ -478,7 +503,7 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', () cwd: '/repo', env }) - await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledTimes(1)) + await vi.waitFor(() => expect(generationSpawns()).toHaveLength(1)) cancelGenerateCommitMessageLocal('/repo') await expect(first).resolves.toEqual({ @@ -494,10 +519,10 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', () env }) await Promise.resolve() - expect(spawnMock).toHaveBeenCalledTimes(1) + expect(generationSpawns()).toHaveLength(1) firstChild.emit('close', null) - await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => expect(generationSpawns()).toHaveLength(2)) secondChild.stdout.emit('data', Buffer.from('Update README\n')) secondChild.emit('close', 0) await expect(second).resolves.toMatchObject({ success: true, message: 'Update README' }) @@ -506,7 +531,7 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', () it('releases the Codex home on root exit when a descendant holds stdio open', async () => { const firstChild = createMockDiscoveryChild() const secondChild = createMockDiscoveryChild() - spawnMock.mockReturnValueOnce(firstChild as never).mockReturnValueOnce(secondChild as never) + generationChildren(firstChild, secondChild) const env = { CODEX_HOME: '/managed/codex-descendant-home' } const context = { branch: 'main', stagedSummary: 'M\tREADME.md', stagedPatch: '+hello' } const params = { agentId: 'codex' as const, model: 'gpt-5.5' } @@ -516,7 +541,7 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', () cwd: '/descendant-repo', env }) - await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledTimes(1)) + await vi.waitFor(() => expect(generationSpawns()).toHaveLength(1)) cancelGenerateCommitMessageLocal('/descendant-repo') await expect(first).resolves.toMatchObject({ canceled: true }) await expectChildTerminated(firstChild) @@ -529,7 +554,7 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', () cwd: '/descendant-repo-2', env }) - await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => expect(generationSpawns()).toHaveLength(2)) secondChild.stdout.emit('data', Buffer.from('Update README\n')) secondChild.emit('close', 0) await expect(second).resolves.toMatchObject({ success: true, message: 'Update README' }) @@ -546,7 +571,7 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', () ) const firstChild = createMockDiscoveryChild() const secondChild = createMockDiscoveryChild() - spawnMock.mockReturnValueOnce(firstChild as never).mockReturnValueOnce(secondChild as never) + generationChildren(firstChild, secondChild) const env = { CODEX_HOME: 'C:\\managed\\codex-generation-home' } const context = { branch: 'main', stagedSummary: 'M\tREADME.md', stagedPatch: '+hello' } const params = { agentId: 'codex' as const, model: 'gpt-5.5' } @@ -557,7 +582,7 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', () cwd: 'C:\\repo', env }) - await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledTimes(1)) + await vi.waitFor(() => expect(generationSpawns()).toHaveLength(1)) cancelGenerateCommitMessageLocal('C:\\repo') await expect(first).resolves.toMatchObject({ canceled: true }) @@ -568,10 +593,10 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', () }) firstChild.emit('close', null) await Promise.resolve() - expect(spawnMock).toHaveBeenCalledTimes(1) + expect(generationSpawns()).toHaveLength(1) finishTreeKill() - await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => expect(generationSpawns()).toHaveLength(2)) secondChild.stdout.emit('data', Buffer.from('Update README\n')) secondChild.emit('close', 0) await expect(second).resolves.toMatchObject({ success: true, message: 'Update README' }) @@ -583,10 +608,10 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', () it('cancels Codex generation promptly while it is queued behind the home lock', async () => { const discoveryChild = createMockDiscoveryChild() const laterChild = createMockDiscoveryChild() - spawnMock.mockReturnValueOnce(discoveryChild as never).mockReturnValueOnce(laterChild as never) + generationChildren(discoveryChild, laterChild) const env = { CODEX_HOME: '/managed/codex-queued-home' } const blocker = discoverCommitMessageModelsLocal('codex', env) - await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledTimes(1)) + await vi.waitFor(() => expect(generationSpawns()).toHaveLength(1)) const queued = generateCommitMessageFromContext( { branch: 'main', stagedSummary: 'M\tREADME.md', stagedPatch: '+hello' }, @@ -600,7 +625,7 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', () error: 'Generation canceled.', canceled: true }) - expect(spawnMock).toHaveBeenCalledTimes(1) + expect(generationSpawns()).toHaveLength(1) discoveryChild.stdout.emit( 'data', @@ -614,9 +639,112 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', () { agentId: 'codex', model: 'gpt-5.5' }, { kind: 'local', cwd: '/later-repo', env } ) - await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => expect(generationSpawns()).toHaveLength(2)) laterChild.stdout.emit('data', Buffer.from('Update later\n')) laterChild.emit('close', 0) await expect(later).resolves.toMatchObject({ success: true, message: 'Update later' }) }) + + it.each(['root-first', 'tree-first'] as const)( + 'cancels a live Codex policy probe and retains its home until both stop proofs (%s)', + async (order) => { + const stopped = Promise.withResolvers() + terminateWindowsProcessTreeMock.mockReturnValueOnce(stopped.promise) + const probe = createMockDiscoveryChild() + const later = createMockDiscoveryChild() + const laterSpawned = Promise.withResolvers() + spawnMock.mockImplementationOnce(() => probe) + spawnMock.mockImplementation((...args) => { + if (spawnedAgentArgv(args).includes('mcp')) { + return policyProbeChild() + } + laterSpawned.resolve() + return later + }) + const env = { CODEX_HOME: `C:\\managed\\probe-${order}` } + const context = { branch: 'main', stagedSummary: 'M\tREADME.md', stagedPatch: '+hello' } + const params = { agentId: 'codex' as const, model: 'gpt-5.5' } + const first = generateCommitMessageFromContext(context, params, { + kind: 'local', + cwd: `/probe-${order}`, + env + }) + await vi.waitFor(() => expect(probe.stdin.end).toHaveBeenCalled()) + cancelGenerateCommitMessageLocal(`/probe-${order}`) + await expect(first).resolves.toMatchObject({ canceled: true }) + const second = generateCommitMessageFromContext(context, params, { + kind: 'local', + cwd: `/after-probe-${order}`, + env + }) + // Late valid output cannot start the canceled semantic operation. + probe.stdout.emit('data', Buffer.from('[]')) + if (order === 'root-first') { + probe.emit('exit', null, 'SIGKILL') + } else { + stopped.resolve() + await expectChildTerminated(probe) + } + await new Promise((done) => setImmediate(done)) + expect(generationSpawns()).toHaveLength(0) + if (order === 'root-first') { + stopped.resolve() + } else { + probe.emit('exit', null, 'SIGKILL') + } + await laterSpawned.promise + later.stdout.emit('data', Buffer.from('Update README\n')) + later.emit('close', 0) + await expect(second).resolves.toMatchObject({ success: true, message: 'Update README' }) + expect(generationSpawns()).toHaveLength(1) + } + ) + + it.each(['error', 'nonzero-close'] as const)( + 'observes late policy-probe errors without stopping an exited child (%s)', + async (failure) => { + const probe = createMockDiscoveryChild() + spawnMock.mockReturnValue(probe) + const pending = generateCommitMessageFromContext( + { branch: 'main', stagedSummary: 'M\tREADME.md', stagedPatch: '+hello' }, + { agentId: 'codex', model: 'gpt-5.5' }, + { kind: 'local', cwd: `/probe-${failure}`, env: { CODEX_HOME: `/probe-${failure}-home` } } + ) + await vi.waitFor(() => expect(probe.stdin.end).toHaveBeenCalled()) + if (failure === 'error') { + probe.emit('error', new Error('Live failure')) + } else { + probe.emit('close', 1) + } + await expect(pending).resolves.toMatchObject({ success: false }) + expect(terminateWindowsProcessTreeMock).toHaveBeenCalledTimes(failure === 'error' ? 1 : 0) + expect(() => probe.emit('error', new Error('Late failure'))).not.toThrow() + probe.emit('exit', 1, null) + expect(() => probe.emit('error', new Error('After exit'))).not.toThrow() + expect(terminateWindowsProcessTreeMock).toHaveBeenCalledTimes(failure === 'error' ? 1 : 0) + expect(generationSpawns()).toHaveLength(0) + } + ) + + it('publishes the task deadline during a live probe without starting a semantic child', async () => { + const deadline = new AbortController() + const timeout = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(deadline.signal) + const probe = createMockDiscoveryChild() + spawnMock.mockReturnValue(probe) + try { + const pending = generateCommitMessageFromContext( + { branch: 'main', stagedSummary: 'M\tREADME.md', stagedPatch: '+hello' }, + { agentId: 'codex', model: 'gpt-5.5' }, + { kind: 'local', cwd: '/probe-deadline', env: { CODEX_HOME: '/probe-deadline-home' } } + ) + await vi.waitFor(() => expect(probe.stdin.end).toHaveBeenCalled()) + deadline.abort(new DOMException('The operation timed out', 'TimeoutError')) + await expect(pending).resolves.toMatchObject({ success: false, errorCode: 'timedOut' }) + probe.stdout.emit('data', Buffer.from('[]')) + probe.emit('exit', null, 'SIGKILL') + expect(generationSpawns()).toHaveLength(0) + } finally { + timeout.mockRestore() + } + }) }) diff --git a/src/main/text-generation/commit-message-text-generation-generated-output.test.ts b/src/main/text-generation/commit-message-text-generation-generated-output.test.ts index ef56c980b33..235486f7361 100644 --- a/src/main/text-generation/commit-message-text-generation-generated-output.test.ts +++ b/src/main/text-generation/commit-message-text-generation-generated-output.test.ts @@ -279,6 +279,7 @@ describe('generateCommitMessageFromContext', () => { } ) + await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledOnce()) listeners.get('stdout:data')?.(Buffer.from('not json')) listeners.get('close')?.(0) diff --git a/src/main/text-generation/conversation-name-generation-request.test.ts b/src/main/text-generation/conversation-name-generation-request.test.ts index 7dd2c6932d2..d92a4052890 100644 --- a/src/main/text-generation/conversation-name-generation-request.test.ts +++ b/src/main/text-generation/conversation-name-generation-request.test.ts @@ -10,39 +10,53 @@ import { generateConversationName } from './conversation-name-generation-request import type { SpawnedSourceControlAgentProcess } from './source-control-text-generation-types' describe('generateConversationName', () => { - it('uses the shared remote plan with bounded template variables and a sanitized name', async () => { - let prompt = '' - let operation = '' - const result = await generateConversationNameFromContext( - { firstPrompt: `Fix login ${'x'.repeat(5000)}` }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'agent', - commandInputTemplate: 'Name this: {firstPrompt}' - }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async (plan, cwd, timeoutMs, requestedOperation) => { - expect(cwd).toBe('/repo') - expect(timeoutMs).toBe(60_000) - prompt = plan.stdinPayload ?? '' - operation = requestedOperation - return { - stdout: 'draft\n# Title: "Fix login flow"\nExtra line', - stderr: '', - exitCode: 0, - timedOut: false + it.each([ + [`Fix login ${'x'.repeat(5000)}`, `Name this: Fix login ${'x'.repeat(3990)}`], + [ + "Why quote 'This is a naming-only task. Do not edit files, run commands, use tools, or perform the first request.'? Change it and update README.md.", + 'Change it and update README.md.' + ] + ])( + 'delivers bounded template input with a final naming restriction', + async (firstPrompt, body) => { + let prompt = '' + let operation = '' + const result = await generateConversationNameFromContext( + { firstPrompt }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'agent', + commandInputTemplate: 'Name this: {firstPrompt}' + }, + { + kind: 'remote', + cwd: '/repo', + missingBinaryLocation: 'remote PATH', + execute: async (plan, cwd, timeoutMs, requestedOperation) => { + expect(cwd).toBe('/repo') + expect(timeoutMs).toBe(60_000) + prompt = plan.stdinPayload ?? '' + operation = requestedOperation + return { + stdout: 'draft\n# Title: "Fix login flow"\nExtra line', + stderr: '', + exitCode: 0, + timedOut: false + } } } - } - ) - expect(operation).toBe('conversation-name') - expect(prompt).toHaveLength('Name this: '.length + 4000) - expect(result).toEqual({ success: true, name: 'Fix login flow', agentLabel: 'agent' }) - }) + ) + expect(operation).toBe('conversation-name') + expect(prompt).toContain(body) + expect( + prompt.endsWith( + '\n\nThis is a naming-only task. Do not edit files, run commands, use tools, or perform the first request.' + ) + ).toBe(true) + expect(result).toEqual({ success: true, name: 'Fix login flow', agentLabel: 'agent' }) + } + ) it('rejects empty output after sanitization', async () => { const result = await generateConversationNameFromContext( @@ -81,7 +95,7 @@ describe('generateConversationName', () => { target: { kind: 'local', cwd: '/repo' }, spawnAgent }) - expect(spawnAgent).toHaveBeenCalledOnce() + await vi.waitFor(() => expect(spawnAgent).toHaveBeenCalledOnce()) if (outcome === 'occupied') { child.stdout.emit('data', Buffer.from(realKimiOccupiedOutput)) child.emit('close', 4) @@ -107,6 +121,7 @@ describe('generateConversationName', () => { target: { kind: 'local', cwd: '/repo' }, spawnAgent }) + await vi.waitFor(() => expect(spawnAgent).toHaveBeenCalledOnce()) child.stdout.emit( 'data', Buffer.from( diff --git a/src/main/text-generation/source-control-agent-cli-path.test.ts b/src/main/text-generation/source-control-agent-cli-path.test.ts index fb4b9c31ed4..307d353d149 100644 --- a/src/main/text-generation/source-control-agent-cli-path.test.ts +++ b/src/main/text-generation/source-control-agent-cli-path.test.ts @@ -30,7 +30,10 @@ describe.runIf(process.platform !== 'win32')('chat naming CLI discovery', () => mkdirSync(bin, { recursive: true }) symlinkSync(process.execPath, join(bin, 'node')) const codex = join(bin, 'codex') - writeFileSync(codex, "#!/usr/bin/env node\nconsole.log('Fix login flow')\n") + writeFileSync( + codex, + "#!/usr/bin/env node\nconsole.log(process.argv.includes('mcp') ? '[]' : 'Fix login flow')\n" + ) chmodSync(codex, 0o755) const result = await generateConversationNameFromContext( diff --git a/src/main/text-generation/source-control-agent-launch.ts b/src/main/text-generation/source-control-agent-launch.ts index 4591eeec04c..51a18712934 100644 --- a/src/main/text-generation/source-control-agent-launch.ts +++ b/src/main/text-generation/source-control-agent-launch.ts @@ -1,12 +1,9 @@ import { wslDistroForCommand } from '../../shared/wsl-paths' import { spawnProcess } from '@orca/process-host' -import { pathEnvRelativeTo, withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution' -import { resolveCliCommand, resolveGuestNativeAgentCommand } from '../codex-cli/command' -import { createProviderSpawnSpec } from '../provider-process/provider-process-supervisor' -import { guardSupervisedProviderGroup } from '../provider-process/provider-group-orphan-guard' -import { SOURCE_CONTROL_KILL_SITE } from './source-control-agent-termination' +import { withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution' +import { resolveCliCommand } from '../codex-cli/command' import { wslAwareSpawn } from '../git/runner' -import { guestNativeSpawnEnv } from '../ipc/wsl-guest-windows-drive-path' +import { spawnSupervisedAgent } from './source-control-supervised-agent-spawn' import type { SourceControlAgentSpawnInput, SpawnedSourceControlAgentProcess, @@ -92,39 +89,3 @@ function spawnWindowsAgent( ...(input.useCwdForNative ? { cwd: input.cwd } : {}) }) } - -// Supervisor owns the agent group so parent quit/death still stops generation. -function spawnSupervisedAgent( - input: SourceControlAgentSpawnInput, - spawnEnv: NodeJS.ProcessEnv -): SpawnedSourceControlAgentProcess { - // On a WSL-host orcad, a missing CLI must fail rather than run a Windows shim found via PATH. - const env = guestNativeSpawnEnv(spawnEnv) - const cwd = input.useCwdForNative ? input.cwd : undefined - // Match native chats' install discovery from the agent's cwd, not Orca's. - const binary = input.binary.includes('/') - ? input.binary - : resolveGuestNativeAgentCommand(input.binary, { - pathEnv: pathEnvRelativeTo(env.PATH, cwd ?? process.cwd()), - homePath: env.HOME - }) - const spec = createProviderSpawnSpec( - { command: binary, args: input.args, ...(cwd !== undefined ? { cwd } : {}) }, - withCliRuntimeOnPath(binary, env), - process.platform, - { lifetime: 'one-shot' } - ) - const child = spawnProcess({ - program: spec.program, - args: spec.args, - env: spec.env, - cwd: spec.cwd, - detached: spec.detached, - stdio: ['pipe', 'pipe', 'pipe', ...spec.groupReportStdio] - }) - guardSupervisedProviderGroup(child, { - site: SOURCE_CONTROL_KILL_SITE, - supervised: spec.supervised - }) - return Object.assign(child, { supervised: spec.supervised }) -} diff --git a/src/main/text-generation/source-control-kimi-policy.ts b/src/main/text-generation/source-control-kimi-policy.ts new file mode 100644 index 00000000000..8f76561d51e --- /dev/null +++ b/src/main/text-generation/source-control-kimi-policy.ts @@ -0,0 +1,55 @@ +import { parse as parseYaml, stringify as stringifyYaml } from 'yaml' +import { z } from 'zod' +import { findOptionOccurrence } from '../../shared/command-option-occurrence' +import { + compactRecipeOptions, + KIMI_VALUE_OPTIONS +} from '../../shared/source-control/ai/generation/commit-message-generation-options' +import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' +const object = z.record(z.string(), z.unknown()) + +export async function prepareKimiTextTaskPolicy( + plan: CommitMessagePlan, + readRecipe: (file: string) => Promise +) { + if (findOptionOccurrence(plan.args, ['--agent'], true, KIMI_VALUE_OPTIONS, 0, 'required')) { + throw new Error('Kimi named profiles cannot apply the text task tool policy') + } + const file = findOptionOccurrence( + plan.args, + ['--agent-file'], + true, + KIMI_VALUE_OPTIONS, + 0, + 'required' + ) + let content = + '---\nname: orca-text-generation\ndescription: Text generation for Orca\ntools: []\n---\n${base_prompt}\n' + if (file) { + if (!file.value) { + throw new Error('Missing text task agent file') + } + const original = await readRecipe(file.value) + const frontmatter = + /^(?:\uFEFF)?---[^\S\r\n]*\r?\n([\s\S]*?)\r?\n---[^\S\r\n]*(?:\r?\n|$)([\s\S]*)$/.exec( + original + ) + if (!frontmatter) { + throw new Error('Invalid text task agent file') + } + const profile = object.parse(parseYaml(frontmatter[1])) + if (profile.name == null || (typeof profile.name === 'string' && !profile.name.trim())) { + profile.name = (file.value.split(/[\\/]/).pop() ?? '').replace(/\.[^.]*$/, '') + } + profile.tools = [] + delete profile.disallowedTools + content = `---\n${stringifyYaml(profile)}---\n${frontmatter[2]}` + } + const args = compactRecipeOptions(plan.args, ['--agent-file'], KIMI_VALUE_OPTIONS) + args.push('--agent-file', '{text-task-profile}') + return { + ...plan, + args, + taskFiles: [{ name: 'text-task-profile.md', content, argIndex: args.length - 1 }] + } +} diff --git a/src/main/text-generation/source-control-local-generation.ts b/src/main/text-generation/source-control-local-generation.ts index 6e1a6056f2f..0b96407a53d 100644 --- a/src/main/text-generation/source-control-local-generation.ts +++ b/src/main/text-generation/source-control-local-generation.ts @@ -11,6 +11,9 @@ import { setLocalGenerationCancelToken } from './source-control-generation-lanes' import { runLocalSourceControlPlan } from './source-control-local-process' +import { prepareSourceControlReadOnlyPlan } from './source-control-read-only-policy' +import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from './source-control-generation-limits' +import { textGenerationFailure } from '../../shared/text-generation-failure-copy' import type { InternalTextGenerationResult, LocalGenerationTarget, @@ -27,9 +30,11 @@ export function runLocalPlanForAgent(input: { spawnAgent: SpawnSourceControlAgent shouldExecute?: () => boolean }): Promise { - const wslDistro = input.plan.promptFile - ? (wslDistroForCommand(input.target.cwd, input.target.wslDistro) ?? undefined) - : input.target.wslDistro + const needsPolicy = ['codex', 'kimi', 'dsh', 'antigravity', 'amp', 'muse'].includes(input.agentId) + const wslDistro = + input.plan.promptFile || input.plan.taskFiles?.length || needsPolicy + ? (wslDistroForCommand(input.target.cwd, input.target.wslDistro) ?? undefined) + : input.target.wslDistro const target = { ...input.target, wslDistro, @@ -39,27 +44,92 @@ export function runLocalPlanForAgent(input: { wslDistro ? 'linux' : process.platform ) } - const start = (): LocalProcessExecution => { - if (input.shouldExecute && !input.shouldExecute()) { - return { - result: Promise.resolve({ success: false, error: 'Generation canceled.', canceled: true }), - processClosed: Promise.resolve() - } - } - return runLocalSourceControlPlan({ - plan: input.plan, + const launch = (plan: CommitMessagePlan, timeoutMs?: number) => + runLocalSourceControlPlan({ + plan, cwd: input.target.cwd, env: wslDistro ? input.target.env : target.env, operation: input.operation, wslDistro, - spawnAgent: input.spawnAgent + spawnAgent: input.spawnAgent, + timeoutMs }) + const prepare = (): LocalProcessExecution => { + const result = Promise.withResolvers() + const canceled = new AbortController() + const deadlineAt = Date.now() + SOURCE_CONTROL_GENERATION_TIMEOUT_MS + const deadline = AbortSignal.timeout(SOURCE_CONTROL_GENERATION_TIMEOUT_MS) + const signal = AbortSignal.any([canceled.signal, deadline]) + const lane = localGenerationLaneKey(input.operation, input.target.cwd) + const failure = (): InternalTextGenerationResult => + canceled.signal.aborted || input.shouldExecute?.() === false + ? { success: false, error: 'Generation canceled.', canceled: true } + : { + success: false, + ...(deadline.aborted + ? textGenerationFailure('timedOut', { + seconds: SOURCE_CONTROL_GENERATION_TIMEOUT_MS / 1000 + }) + : textGenerationFailure('agentCouldNotStart', { label: input.plan.label })) + } + const abort = () => result.resolve(failure()) + const cancel = () => canceled.abort() + setLocalGenerationCancelToken(lane, cancel) + signal.addEventListener('abort', abort, { once: true }) + let preparation: LocalProcessExecution | undefined + let execution: LocalProcessExecution | undefined + const processClosed = (async () => { + try { + if (input.shouldExecute?.() === false) { + canceled.abort() + } + signal.throwIfAborted() + preparation = prepareSourceControlReadOnlyPlan({ ...input, target, signal }) + const plan = await preparation.result + await preparation.processClosed + signal.throwIfAborted() + if (input.shouldExecute?.() === false) { + canceled.abort() + signal.throwIfAborted() + } + signal.removeEventListener('abort', abort) + execution = launch(plan, Math.max(1, deadlineAt - Date.now())) + result.resolve(await execution.result) + } catch { + result.resolve(failure()) + } finally { + signal.removeEventListener('abort', abort) + clearLocalGenerationCancelToken(lane, cancel) + await preparation?.processClosed + await execution?.processClosed + } + })() + return { result: result.promise, processClosed } + } + const start = (): + | LocalProcessExecution + | Promise> => { + if (needsPolicy) { + return prepare() + } + return input.shouldExecute?.() === false + ? { + result: Promise.resolve({ + success: false, + error: 'Generation canceled.', + canceled: true + }), + processClosed: Promise.resolve() + } + : launch(input.plan) } if (input.agentId !== 'codex') { const execution = start() - return input.shouldExecute - ? execution.result.finally(() => execution.processClosed) - : execution.result + return Promise.resolve(execution).then((execution) => + input.shouldExecute + ? execution.result.finally(() => execution.processClosed) + : execution.result + ) } return runCodexLocalPlanUnderHomeLock( start, @@ -71,7 +141,9 @@ export function runLocalPlanForAgent(input: { } function runCodexLocalPlanUnderHomeLock( - start: () => LocalProcessExecution, + start: () => + | LocalProcessExecution + | Promise>, target: LocalGenerationTarget, operation: TextGenerationOperation, commandEnv?: Record, @@ -103,7 +175,7 @@ function runCodexLocalPlanUnderHomeLock( publishResult({ success: false, error: 'Generation canceled.', canceled: true }) return } - const execution = start() + const execution = await start() try { publishResult(await execution.result) } catch (error) { diff --git a/src/main/text-generation/source-control-local-process.test.ts b/src/main/text-generation/source-control-local-process.test.ts index cf5590a6dc0..b00957fa139 100644 --- a/src/main/text-generation/source-control-local-process.test.ts +++ b/src/main/text-generation/source-control-local-process.test.ts @@ -18,7 +18,10 @@ import { cancelGenerateCommitMessageLocal } from './commit-message-text-generati import { spawnSourceControlAgent } from './source-control-agent-launch' import { killSourceControlAgentProcess } from './source-control-local-process' import { generateCommitMessage } from './source-control-text-generation-requests' -import type { SpawnedSourceControlAgentProcess } from './source-control-text-generation-types' +import type { + SpawnSourceControlAgent, + SpawnedSourceControlAgentProcess +} from './source-control-text-generation-types' const { terminateTreeMock } = vi.hoisted(() => ({ terminateTreeMock: vi.fn(async () => true) @@ -82,6 +85,22 @@ function asSpawned(child: FakeSupervisor): SpawnedSourceControlAgentProcess { return child as unknown as SpawnedSourceControlAgentProcess } +function withPolicyProbes(spawn: SpawnSourceControlAgent): SpawnSourceControlAgent { + return (input) => { + if (!input.args.includes('mcp')) { + return spawn(input) + } + const child = createMockDiscoveryChild() + child.stdin.end.mockImplementation(() => + queueMicrotask(() => { + child.stdout.emit('data', Buffer.from('[]')) + child.emit('close', 0) + }) + ) + return child + } +} + function isAlive(pid: number): boolean { try { process.kill(pid, 0) @@ -147,10 +166,12 @@ describe('a supervised agent one-shot that runs out of time', () => { context: { branch: 'main', stagedSummary: 'M README.md', stagedPatch: '+test' }, params: { agentId: 'codex', model: 'gpt-5.5' }, target: { kind: 'local', cwd, env: { CODEX_HOME: '/codex/timeout-home' } }, - spawnAgent + spawnAgent: withPolicyProbes(spawnAgent) }) const first = request('/repo/first') + await vi.advanceTimersByTimeAsync(0) + expect(spawnAgent).toHaveBeenCalledOnce() await vi.advanceTimersByTimeAsync(SOURCE_CONTROL_GENERATION_TIMEOUT_MS) await expect(first).resolves.toMatchObject({ success: false, @@ -202,7 +223,7 @@ describe('context-owned one-shot settlement', () => { context: { firstPrompt: 'Explain migrations' }, params: { agentId: 'codex', model: 'selected-model' }, target: { kind: 'local', cwd: '/owned', env: { CODEX_HOME: `/isolated/${route}` } }, - spawnAgent: () => child, + spawnAgent: withPolicyProbes(() => child), shouldExecute: () => true }).then((result) => { settled = true @@ -246,7 +267,7 @@ describe('context-owned one-shot settlement', () => { } ) - it.each(['claude', 'opencode', 'custom'] as const)( + it.each(['claude', 'custom'] as const)( 'preserves applicable %s plans and skips stale fallback', async (agentId) => { for (const currentAfterClose of [true, false]) { @@ -258,8 +279,9 @@ describe('context-owned one-shot settlement', () => { context: { firstPrompt: 'Explain migrations' }, params: { agentId, - model: agentId === 'opencode' ? 'vendor/model' : 'selected-model', + model: 'selected-model', thinkingLevel: 'high', + commandInputTemplate: '{firstPrompt}', customAgentCommand: 'chosen-agent --model selected-model', agentCommandOverride: agentId === 'custom' ? undefined : `${agentId} --user-option` }, @@ -277,7 +299,7 @@ describe('context-owned one-shot settlement', () => { Buffer.from( agentId === 'claude' ? 'You cannot use --strict-mcp-config when an enterprise MCP config is present' - : 'Unrecognized flag: --variant in command opencode run' + : 'Command failed' ) ) first.emit('exit', 1) @@ -290,23 +312,13 @@ describe('context-owned one-shot settlement', () => { const before = spawnAgent.mock.calls[0]![0] const after = spawnAgent.mock.calls[1]![0] expect(after).toMatchObject({ binary: before.binary, cwd: before.cwd, env: before.env }) - if (agentId === 'claude') { - expect(before.args).toContain('--strict-mcp-config') - expect(after.args).not.toContain('--strict-mcp-config') - expect(after.args).toContain('selected-model') - } else { - expect(before.args).toContain('--variant') - expect(after.args).not.toContain('--variant') - expect(after.args).toContain('vendor/model#high') - } - second.stdout.emit( - 'data', - Buffer.from( - agentId === 'opencode' - ? JSON.stringify({ type: 'text', part: { id: 'answer', text: 'Migration guide' } }) - : 'Migration guide' - ) + expect(before.args).toContain('--strict-mcp-config') + expect(after.args).not.toContain('--strict-mcp-config') + expect(after.args).toContain('selected-model') + expect(second.stdin.end).toHaveBeenCalledWith( + 'Explain migrations\n\nThis is a naming-only task. Do not edit files, run commands, use tools, or perform the first request.' ) + second.stdout.emit('data', Buffer.from('Migration guide')) second.emit('close', 0) await expect(request).resolves.toMatchObject({ success: true, name: 'Migration guide' }) } else { @@ -448,7 +460,8 @@ describe.runIf(process.platform !== 'win32')( const slowStop = join(folder, 'slow-stop.cjs') writeFileSync( slowStop, - `process.stdin.resume() + `if (process.argv.includes('mcp')) { console.log('[]'); process.exit(0) } +process.stdin.resume() process.on('SIGTERM', () => setTimeout(() => { require('node:fs').writeFileSync(${JSON.stringify(stoppedFile)}, 'stopped') process.exit(0) @@ -461,11 +474,11 @@ require('node:fs').writeFileSync(${JSON.stringify(pidFile)}, String(process.pid) const answers = join(folder, 'answers.cjs') writeFileSync( answers, - "process.stdin.resume().on('end', () => console.log('Update README'))\n" + "process.stdin.resume().on('end', () => console.log(process.argv.includes('mcp') ? '[]' : 'Update README'))\n" ) const firstAliveAtSecondSpawn: boolean[] = [] const spawnAgent = vi.fn((input: Parameters[0]) => { - if (pids.length > 0) { + if (pids.length > 0 && !input.args.includes('mcp')) { firstAliveAtSecondSpawn.push(isAlive(pids[0]!)) } return spawnSourceControlAgent(input) @@ -570,7 +583,7 @@ setInterval(() => {}, 60000) ) const floodAliveAtSecondSpawn: boolean[] = [] const spawnAgent = vi.fn((input: Parameters[0]) => { - if (pids.length > 0) { + if (pids.length > 0 && !input.args.includes('mcp')) { floodAliveAtSecondSpawn.push(isAlive(pids[0]!)) } return spawnSourceControlAgent(input) diff --git a/src/main/text-generation/source-control-local-process.ts b/src/main/text-generation/source-control-local-process.ts index ce335de13ae..ff5eb0fedc0 100644 --- a/src/main/text-generation/source-control-local-process.ts +++ b/src/main/text-generation/source-control-local-process.ts @@ -36,7 +36,8 @@ export function runLocalSourceControlPlan( ): LocalProcessExecution { let { plan } = input const { cwd, operation } = input - const distro = plan.promptFile ? wslDistroForCommand(cwd, input.wslDistro) : null + const distro = + plan.promptFile || plan.taskFiles?.length ? wslDistroForCommand(cwd, input.wslDistro) : null const guest = distro ? prepareWslPrompt(plan, distro) : undefined let closed = false let promptDirectory: string | undefined @@ -101,7 +102,8 @@ export function runLocalSourceControlPlan( } const stop = new AbortController() - const deadline = Date.now() + SOURCE_CONTROL_GENERATION_TIMEOUT_MS + const timeoutMs = input.timeoutMs ?? SOURCE_CONTROL_GENERATION_TIMEOUT_MS + const deadline = Date.now() + timeoutMs let stdout = '' let stderr = '' let stdoutBytes = 0 @@ -160,7 +162,7 @@ export function runLocalSourceControlPlan( seconds: SOURCE_CONTROL_GENERATION_TIMEOUT_MS / 1000 }) }) - }, SOURCE_CONTROL_GENERATION_TIMEOUT_MS) + }, timeoutMs) const onStdoutData = (chunk: Buffer): void => { stdoutBytes += chunk.byteLength diff --git a/src/main/text-generation/source-control-policy-probe.ts b/src/main/text-generation/source-control-policy-probe.ts new file mode 100644 index 00000000000..bc2380d953a --- /dev/null +++ b/src/main/text-generation/source-control-policy-probe.ts @@ -0,0 +1,121 @@ +import { abortSignalReason } from '../../shared/abort-signal-reason' +import { mergeCommandEnvironment } from '../../shared/command-environment' +import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' +import { killSourceControlAgentProcess } from './source-control-agent-termination' +import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from './source-control-generation-limits' +import type { + LocalGenerationTarget, + LocalProcessExecution, + SpawnSourceControlAgent +} from './source-control-text-generation-types' + +/** Effective configuration may contain credentials; keep both streams private even on failure. */ +export function runSourceControlPolicyProbe(input: { + plan: CommitMessagePlan + args: string[] + target: LocalGenerationTarget + signal: AbortSignal + spawnAgent: SpawnSourceControlAgent +}): LocalProcessExecution<{ stdout: string; stderr: string }> { + input.signal.throwIfAborted() + const child = input.spawnAgent({ + binary: input.plan.binary, + args: input.args, + cwd: input.target.cwd, + wslDistro: input.target.wslDistro, + env: input.target.wslDistro + ? input.target.env + : mergeCommandEnvironment(input.target.env, input.plan.env, process.platform), + commandEnv: input.plan.env, + stdinMode: 'pipe', + useCwdForNative: true + }) + const owner = Promise.withResolvers() + const result = Promise.withResolvers<{ stdout: string; stderr: string }>() + let output = '' + let errors = '' + let bytes = 0 + let settled = false + let terminal = false + let termination: Promise | undefined + const markClosed = () => { + if (terminal && settled) { + void (termination ?? Promise.resolve()).then(owner.resolve) + } + } + const stop = () => { + if (terminal || child.exitCode != null || child.signalCode != null) { + return + } + termination ??= killSourceControlAgentProcess(child).catch(() => { + console.error('[text-generation] Configuration probe termination failed') + }) + } + const finish = (error?: Error) => { + if (settled) { + return + } + settled = true + input.signal.removeEventListener('abort', abort) + child.stdout?.off?.('data', stdout) + child.stderr?.off?.('data', stderr) + if (error) { + result.reject(error) + } else { + result.resolve({ stdout: output, stderr: errors }) + } + markClosed() + } + const fail = (error: Error) => { + if (!settled) { + stop() + finish(error) + } + } + const abort = () => fail(abortSignalReason(input.signal)) + const observe = (chunk: Buffer, isStdout: boolean) => { + bytes += chunk.byteLength + if (bytes > MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES) { + fail(new Error('Text task configuration exceeds its output limit')) + } else if (isStdout) { + output += chunk.toString('utf8') + } else { + errors += chunk.toString('utf8') + } + } + const stdout = (chunk: Buffer) => observe(chunk, true) + const stderr = (chunk: Buffer) => observe(chunk, false) + child.stdout?.on('data', stdout) + child.stderr?.on('data', stderr) + child.on('error', () => { + if (!child.pid) { + terminal = true + } + fail(new Error('Text task configuration could not be read')) + }) + child.once('exit', () => { + terminal = true + markClosed() + }) + child.once('close', (code) => { + terminal = true + if (code === 0) { + finish() + } else { + finish(new Error('Text task configuration could not be read')) + } + markClosed() + }) + child.stdin?.on('error', () => fail(new Error('Text task configuration could not be read'))) + input.signal.addEventListener('abort', abort, { once: true }) + if (input.signal.aborted) { + abort() + } else { + try { + child.stdin?.end() + } catch { + fail(new Error('Text task configuration could not be read')) + } + } + return { result: result.promise, processClosed: owner.promise } +} diff --git a/src/main/text-generation/source-control-prompt-files.ts b/src/main/text-generation/source-control-prompt-files.ts index 9c3b4198641..9a419bd23a4 100644 --- a/src/main/text-generation/source-control-prompt-files.ts +++ b/src/main/text-generation/source-control-prompt-files.ts @@ -9,6 +9,71 @@ import type { CommitMessagePlan } from '../../shared/source-control/ai/generatio // Reserve the transport signature under the native text attachment cap. const PAYLOAD_BYTES = 5 * 1024 * 1024 - 3 +export const TEXT_TASK_DIRECTORY = '__ORCA_TEXT_TASK_DIRECTORY__' + +function generationFiles(plan: CommitMessagePlan) { + const files: { + name: string + content: string + argIndex?: number + attachment?: boolean + interpolateDirectory?: boolean + }[] = [] + if (plan.promptFile) { + for (const content of promptFileContents(plan.promptFile.content)) { + files.push({ + name: `prompt-${files.length + 1}.txt`, + content, + argIndex: plan.promptFile.argIndex, + attachment: true + }) + } + } + for (const file of plan.taskFiles ?? []) { + if (!/^[a-zA-Z0-9_-]+\.[a-zA-Z0-9]+$/.test(file.name)) { + throw new Error('Invalid text task artifact name') + } + files.push(file) + } + return files +} + +function materializedPlan( + plan: CommitMessagePlan, + directory: string, + files: ReturnType +) { + const substitutions = new Map() + if (plan.promptFile) { + substitutions.set(plan.promptFile.argIndex, []) + } + for (const file of files) { + if (file.argIndex === undefined) { + continue + } + const path = `${directory}/${file.name}` + const values = substitutions.get(file.argIndex) ?? [] + values.push(file.attachment ? `@${path}` : path) + substitutions.set(file.argIndex, values) + } + const args = [...plan.args] + for (const [index, values] of [...substitutions].sort(([left], [right]) => right - left)) { + args.splice(index, 1, ...values) + } + return { ...plan, args } +} + +function policyContent( + file: ReturnType[number], + directory: string +): string { + return file.interpolateDirectory + ? file.content.replaceAll( + TEXT_TASK_DIRECTORY, + JSON.stringify(directory.replaceAll('\\', '/')).slice(1, -1) + ) + : file.content +} export function* promptFileContents(content: string): Generator { for (let start = 0; start < content.length;) { @@ -22,25 +87,23 @@ export function stageLocalPromptFiles( plan: CommitMessagePlan, own: (directory: string) => void ): CommitMessagePlan { - if (!plan.promptFile) { + const files = generationFiles(plan) + if (!files.length && !plan.promptFile) { return plan } const directory = mkdtempSync(join(tmpdir(), 'orca-generation-')) own(directory) - const attachments: string[] = [] - for (const content of promptFileContents(plan.promptFile.content)) { - const path = join(directory, `prompt-${attachments.length + 1}.txt`) - writeFileSync(path, content, { mode: 0o600 }) - attachments.push(`@${path}`) + for (const file of files) { + writeFileSync(join(directory, file.name), policyContent(file, directory), { mode: 0o600 }) } - const args = [...plan.args] - args.splice(plan.promptFile.argIndex, 1, ...attachments) - return { ...plan, args } + return materializedPlan(plan, directory, files) } // Preparation precedes profiles; only a proved empty allocation may roll back before ACK. export const WSL_PROMPT_PREPARATION = ` nonce=$1; count=$2; shift 2 +custom_names=0 +if [ "\${1-}" = --task-files ]; then custom_names=1; shift; fi dir=/tmp/orca-generation-$nonce old_umask=$(umask) umask 077 @@ -51,7 +114,7 @@ IFS= read -r record && [ "$record" = "A$nonce" ] || exit 1 trap - EXIT index=1 while [ "$index" -le "$count" ]; do - file=$dir/prompt-$index.txt + if [ "$custom_names" = 1 ]; then file=$dir/$1; shift; else file=$dir/prompt-$index.txt; fi : > "$file" || exit 1 while :; do IFS= read -r record || exit 1 @@ -64,25 +127,27 @@ while [ "$index" -le "$count" ]; do done IFS= read -r record && [ "$record" = "X$nonce" ] || exit 1 umask "$old_umask" -exec "$@" file.name)] : []) + ] + }, cleanupPath: toWindowsWslUncPath(directory, distro), observe(chunk: Buffer, diagnostic?: (bytes: Buffer) => void): boolean { let firstProof = false @@ -128,13 +193,16 @@ export function prepareWslPrompt(plan: CommitMessagePlan, distro: string) { *records(): Generator { yield `A${nonce}\n` let index = 0 - for (const content of promptFileContents(plan.promptFile?.content ?? '')) { - for (const encoded of encodePosixPrintfRecords(content)) { + for (const file of files) { + for (const encoded of encodePosixPrintfRecords(policyContent(file, directory))) { yield `D${encoded}\n` } yield `F${nonce}:${++index}\n` } yield `X${nonce}\n` + if (plan.stdinPayload) { + yield plan.stdinPayload + } } } } diff --git a/src/main/text-generation/source-control-read-only-policy.test.ts b/src/main/text-generation/source-control-read-only-policy.test.ts new file mode 100644 index 00000000000..8abed495c5c --- /dev/null +++ b/src/main/text-generation/source-control-read-only-policy.test.ts @@ -0,0 +1,292 @@ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { parse as parseYaml } from 'yaml' +import { afterEach, expect, it, vi } from 'vitest' +import { planCommitMessageGeneration } from '../../shared/source-control/ai/generation/commit-message-plan' +import { prepareSourceControlReadOnlyPlan } from './source-control-read-only-policy' +import { stageLocalPromptFiles } from './source-control-prompt-files' +import { runLocalPlanForAgent } from './source-control-local-generation' +import { cancelLocalGeneration } from './source-control-generation-lanes' + +const { probe } = vi.hoisted(() => ({ probe: vi.fn() })) +vi.mock('./source-control-policy-probe', () => ({ runSourceControlPolicyProbe: probe })) +const owned: string[] = [] +afterEach(async () => { + probe.mockReset() + await Promise.all( + owned.splice(0).map((directory) => rm(directory, { recursive: true, force: true })) + ) +}) +async function directory() { + const result = await mkdtemp(join(tmpdir(), 'orca-policy-test-')) + owned.push(result) + return result +} +function planned(agentId: 'codex' | 'kimi' | 'antigravity', agentArgs?: string) { + const result = planCommitMessageGeneration( + { agentId, model: agentId === 'codex' ? 'gpt-5.4-mini' : 'default', agentArgs }, + 'Name this chat' + ) + if (!result.ok) { + throw new Error(result.error) + } + return result.plan +} +const spawnAgent = vi.fn(() => { + throw new Error('Unexpected semantic process') +}) + +it('cancels during configuration admission without launching a semantic agent', async () => { + const cwd = await directory() + const entered = Promise.withResolvers() + probe.mockImplementation(({ signal }: { signal: AbortSignal }) => ({ + result: new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => reject(signal.reason), { once: true }) + entered.resolve() + }), + processClosed: Promise.resolve() + })) + const result = runLocalPlanForAgent({ + agentId: 'codex', + plan: planned('codex'), + target: { kind: 'local', cwd, env: { CODEX_HOME: cwd } }, + operation: 'conversation-name', + spawnAgent + }) + await entered.promise + cancelLocalGeneration('conversation-name', cwd) + await expect(result).resolves.toMatchObject({ success: false, canceled: true }) + expect(spawnAgent).not.toHaveBeenCalled() +}) + +it('keeps non-title helpers inside the enforced task policy', async () => { + const cwd = await directory() + for (const agentId of ['amp', 'muse', 'kimi'] as const) { + const result = planCommitMessageGeneration( + { + agentId, + model: agentId === 'amp' ? 'smart' : 'default', + ...(agentId === 'kimi' ? { agentArgs: '--agent custom' } : {}) + }, + 'Name this chat' + ) + if (!result.ok) { + throw new Error(result.error) + } + await expect( + runLocalPlanForAgent({ + agentId, + plan: result.plan, + target: { kind: 'local', cwd }, + operation: 'commit-message', + spawnAgent + }) + ).resolves.toMatchObject({ success: false }) + } + expect(spawnAgent).not.toHaveBeenCalled() +}) + +it('disables every effective Codex MCP name, including dotted names, after recipe overrides', async () => { + probe.mockReturnValue({ + result: Promise.resolve({ + stdout: + '[{"name":"a.b","enabled":true,"transport":{"type":"stdio"}},{"name":"second","enabled":true}]', + stderr: 'Warning: optional update unavailable' + }), + processClosed: Promise.resolve() + }) + const plan = await prepareSourceControlReadOnlyPlan({ + agentId: 'codex', + plan: planned( + 'codex', + '-c features.apps=true -c features.plugins=true -c mcp_servers.a.enabled=true --profile review' + ), + target: { kind: 'local', cwd: '/workspace', env: { CODEX_HOME: '/bound-account' } }, + signal: new AbortController().signal, + spawnAgent + }).result + expect(probe.mock.calls[0][0]).toMatchObject({ + target: { cwd: '/workspace', env: { CODEX_HOME: '/bound-account' } }, + args: [ + '-c', + 'features.apps=true', + '-c', + 'features.plugins=true', + '-c', + 'mcp_servers.a.enabled=true', + '--profile', + 'review', + '-c', + 'features.plugins=false', + '-c', + 'features.apps=false', + 'mcp', + 'list', + '--json' + ] + }) + expect(plan.args.slice(-6)).toEqual([ + '-c', + 'features.plugins=false', + '-c', + 'features.apps=false', + '-c', + 'mcp_servers={"a.b"={enabled=false},"second"={enabled=false}}' + ]) + probe.mockReturnValue({ + result: Promise.reject(new Error('Unsupported configuration query')), + processClosed: Promise.resolve() + }) + await expect( + prepareSourceControlReadOnlyPlan({ + agentId: 'codex', + plan: planned('codex'), + target: { kind: 'local', cwd: '/workspace' }, + signal: new AbortController().signal, + spawnAgent + }).result + ).rejects.toThrow('Unsupported configuration query') +}) + +it('copies an explicit Kimi profile with its prompt and identity preserved and an empty tool policy', async () => { + const cwd = await directory() + await writeFile( + join(cwd, 'reviewer.md'), + '---\nname: careful-reviewer\ndescription: Review code\ntools: ["*"]\ndisallowedTools: [read]\nsubagents: [explore]\n---\nReview precisely. ${base_prompt}\n' + ) + const policy = await prepareSourceControlReadOnlyPlan({ + agentId: 'kimi', + plan: planned('kimi', '--agent-file reviewer.md'), + target: { kind: 'local', cwd }, + signal: new AbortController().signal, + spawnAgent + }).result + const plan = stageLocalPromptFiles(policy, (directory) => owned.push(directory)) + const flag = plan.args.indexOf('--agent-file') + const content = await readFile(plan.args[flag + 1], 'utf8') + const sections = content.split('---\n') + expect(content.startsWith('---\n')).toBe(true) + expect(parseYaml(sections[1])).toEqual({ + name: 'careful-reviewer', + description: 'Review code', + tools: [], + subagents: ['explore'] + }) + expect(sections[2]).toBe('Review precisely. ${base_prompt}\n') + expect(await readFile(join(cwd, 'reviewer.md'), 'utf8')).toContain('tools: ["*"]') +}) + +it('composes agy session settings without losing existing read denies or selected recipe fields', async () => { + probe.mockReturnValue({ + result: Promise.resolve({ + stdout: '', + stderr: + ' --settings Settings for this session only, never saved: a JSON object of settings.json keys, inline or as a file path' + }), + processClosed: Promise.resolve() + }) + const cwd = await directory() + await writeFile( + join(cwd, 'settings.json'), + '\uFEFF{"customSetting":"retained","permissions":{"deny":["read_file(secret/*)"],"ask":["read_file(review/*)"]}}' + ) + const policy = await prepareSourceControlReadOnlyPlan({ + agentId: 'antigravity', + plan: planned( + 'antigravity', + '--settings settings.json --settings \'{"permissions":{"deny":["read_file(other/*)"]},"anotherSetting":true}\' --agent review --effort high' + ), + target: { kind: 'local', cwd }, + signal: new AbortController().signal, + spawnAgent + }).result + const value = policy.args[policy.args.indexOf('--settings') + 1] + expect(JSON.parse(value)).toEqual({ + customSetting: 'retained', + anotherSetting: true, + toolPermission: 'request-review', + allowNonWorkspaceAccess: true, + permissions: { + allow: ['read_file(*)'], + ask: ['read_file(review/*)'], + deny: [ + 'read_file(secret/*)', + 'read_file(other/*)', + 'write_file(*)', + 'command(*)', + 'mcp(*)', + 'read_url(*)', + 'execute_url(*)' + ] + } + }) + expect(policy.args).toContain('review') + expect(policy.args).toContain('high') + expect(await readFile(join(cwd, 'settings.json'), 'utf8')).not.toContain('write_file') +}) + +it('refuses an agy build without session settings before sending the prompt', async () => { + probe.mockReturnValue({ + result: Promise.resolve({ + stdout: '', + stderr: ' --model Model to use\n --agent Agent profile\n' + }), + processClosed: Promise.resolve() + }) + const cwd = await directory() + await expect( + runLocalPlanForAgent({ + agentId: 'antigravity', + plan: planned('antigravity'), + target: { kind: 'local', cwd }, + operation: 'commit-message', + spawnAgent + }) + ).resolves.toMatchObject({ success: false }) + expect(spawnAgent).not.toHaveBeenCalled() + expect(probe.mock.calls[0][0]).toMatchObject({ args: ['--help'], target: { cwd } }) +}) + +it('preserves valid selected Kimi history and named profiles for best-effort naming', async () => { + for (const args of ['--agent review', '--session saved-chat', '--continue']) { + const plan = planned('kimi', args) + const prepared = await prepareSourceControlReadOnlyPlan({ + agentId: 'kimi', + plan, + operation: 'conversation-name', + target: { kind: 'local', cwd: '/workspace' }, + signal: new AbortController().signal, + spawnAgent + }).result + expect(prepared.args).toEqual(plan.args) + expect(prepared.taskFiles).toBeUndefined() + } +}) + +it('uses successful older agy help as capability evidence without swallowing a failed probe', async () => { + probe.mockReturnValueOnce({ + result: Promise.resolve({ stdout: ' --sandbox Use a sandbox\n --model Model', stderr: '' }), + processClosed: Promise.resolve() + }) + const plan = planned('antigravity', '--agent review') + const input = { + agentId: 'antigravity', + plan, + operation: 'conversation-name' as const, + target: { kind: 'local' as const, cwd: '/workspace' }, + signal: new AbortController().signal, + spawnAgent + } + const prepared = await prepareSourceControlReadOnlyPlan(input).result + expect(prepared.args).toContain('review') + expect(prepared.args).toContain('--sandbox') + expect(prepared.args).not.toContain('--settings') + probe.mockReturnValueOnce({ + result: Promise.reject(new Error('Help could not start')), + processClosed: Promise.resolve() + }) + await expect(prepareSourceControlReadOnlyPlan(input).result).rejects.toThrow( + 'Help could not start' + ) +}) diff --git a/src/main/text-generation/source-control-read-only-policy.ts b/src/main/text-generation/source-control-read-only-policy.ts new file mode 100644 index 00000000000..498f1069dc6 --- /dev/null +++ b/src/main/text-generation/source-control-read-only-policy.ts @@ -0,0 +1,272 @@ +import { readFile } from 'node:fs/promises' +import { homedir } from 'node:os' +import path from 'node:path' +import { prepareKimiTextTaskPolicy } from './source-control-kimi-policy' +import { parse as parseJson, type ParseError } from 'jsonc-parser' +import { z } from 'zod' +import { findOptionOccurrence } from '../../shared/command-option-occurrence' +import { + compactRecipeOptions, + KIMI_VALUE_OPTIONS +} from '../../shared/source-control/ai/generation/commit-message-generation-options' +import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' +import { parseWslUncPath, wslDistroForCommand } from '../../shared/wsl-paths' +import { CODEX_DISABLE_PLUGINS_ARGS } from '../codex-cli/codex-read-only-app-server-args' +import { runWslProcess } from '../wsl/execution/wsl-runner' +import { TEXT_TASK_DIRECTORY } from './source-control-prompt-files' +import { runSourceControlPolicyProbe } from './source-control-policy-probe' +import type { + LocalGenerationTarget, + LocalProcessExecution, + SpawnSourceControlAgent, + TextGenerationOperation +} from './source-control-text-generation-types' + +const object = z.record(z.string(), z.unknown()) +const strings = z.array(z.string()) +const settingsOptions = [ + '--settings', + '--model', + '--effort', + '--agent', + '--input-format', + '--output-format' +] +const codexExclusions = [...CODEX_DISABLE_PLUGINS_ARGS, '-c', 'features.apps=false'] +const AG_DENIES = ['write_file(*)', 'command(*)', 'mcp(*)', 'read_url(*)', 'execute_url(*)'] + +async function recipeFile( + file: string, + target: LocalGenerationTarget, + signal: AbortSignal, + commandEnv?: Record +): Promise { + signal.throwIfAborted() + const distro = + process.platform === 'win32' ? wslDistroForCommand(target.cwd, target.wslDistro) : null + if (distro) { + const cwd = parseWslUncPath(target.cwd)?.linuxPath ?? target.cwd + const home = + commandEnv?.HOME ?? (target.env?.HOME !== process.env.HOME ? target.env?.HOME : undefined) + const result = await runWslProcess({ + distro, + cwd, + loginPath: 'preferred', + ...(home !== undefined ? { env: { ORCA_TEXT_TASK_HOME: home } } : {}), + script: + 'if [ "${ORCA_TEXT_TASK_HOME+x}" ]; then HOME=$ORCA_TEXT_TASK_HOME; fi; case "$1" in "~/"*) file=$HOME/${1#??} ;; *) file=$1 ;; esac; cat -- "$file"', + args: [file], + timeoutMs: 10_000, + maxOutputBytes: 1024 * 1024 + }) + signal.throwIfAborted() + if (result.code !== 0 || result.timedOut || result.outputTruncated) { + throw new Error('Text task recipe file could not be read') + } + return result.stdout + } + const home = + process.platform === 'win32' + ? (target.env?.USERPROFILE ?? homedir()) + : (target.env?.HOME ?? homedir()) + const expanded = file.startsWith('~/') ? path.join(home, file.slice(2)) : file + const content = await readFile(path.resolve(target.cwd, expanded), 'utf8') + signal.throwIfAborted() + return content +} + +function jsonObject(text: string): Record { + const errors: ParseError[] = [] + const value: unknown = parseJson(text.replace(/^\uFEFF/, ''), errors, { + allowTrailingComma: true + }) + if (errors.length) { + throw new Error('Invalid text task settings') + } + return object.parse(value) +} + +async function antigravityPolicy( + plan: CommitMessagePlan, + target: LocalGenerationTarget, + signal: AbortSignal +) { + let settings: Record = {} + let cursor = 0 + for (;;) { + const option = findOptionOccurrence( + plan.args, + ['--settings'], + true, + settingsOptions, + cursor, + 'required' + ) + if (!option) { + break + } + if (!option.value) { + throw new Error('Missing text task settings') + } + const next = jsonObject( + option.value.trimStart().startsWith('{') + ? option.value + : await recipeFile(option.value, target, signal, plan.env) + ) + const previousPermissions = object.parse(settings.permissions ?? {}) + const nextPermissions = object.parse(next.permissions ?? {}) + settings = { + ...settings, + ...next, + permissions: { + ...previousPermissions, + ...nextPermissions, + ...Object.fromEntries( + ['allow', 'ask', 'deny'].map((key) => [ + key, + [ + ...new Set([ + ...strings.parse(previousPermissions[key] ?? []), + ...strings.parse(nextPermissions[key] ?? []) + ]) + ] + ]) + ) + } + } + cursor = option.index + option.consumed + } + const permissions = object.parse(settings.permissions ?? {}) + const allow = strings.parse(permissions.allow ?? []) + const deny = strings.parse(permissions.deny ?? []) + const composed = { + ...settings, + toolPermission: 'request-review', + allowNonWorkspaceAccess: true, + permissions: { + ...permissions, + allow: [...new Set([...allow, 'read_file(*)'])], + deny: [...new Set([...deny, ...AG_DENIES])] + } + } + return { + ...plan, + args: [ + ...compactRecipeOptions(plan.args, ['--settings'], settingsOptions), + '--settings', + JSON.stringify(composed) + ] + } +} + +function dshPolicy(plan: CommitMessagePlan): CommitMessagePlan { + const plugin = `export const inject = ['tools']\nexport function apply(ctx) {\n ctx.tools.guard(exec => exec.name === 'read' ? undefined : 'This text task permits only file reads')\n ctx.provide('orcaTextReadPolicy', Object.freeze({}))\n}\n` + const patch = JSON.stringify([ + { id: 'tools', config: { mode: 'native' } }, + { + insert: [{ id: 'orca-text-read-policy', name: `${TEXT_TASK_DIRECTORY}/text-task-policy.mjs` }] + }, + { id: 'headless-runner', inject: ['headlessStartup', 'orcaTextReadPolicy'] } + ]) + // Launcher overlays must precede its task operand and follow the user's overlays. + const args = [...plan.args] + const task = args.indexOf('-') + args.splice(task === -1 ? args.length : task, 0, '--patch', '{text-task-policy}') + return { + ...plan, + args, + taskFiles: [ + { name: 'text-task-policy.mjs', content: plugin }, + { + name: 'text-task-policy.json', + content: patch, + interpolateDirectory: true, + argIndex: task === -1 ? args.length - 1 : task + 1 + } + ] + } +} + +export function prepareSourceControlReadOnlyPlan(input: { + agentId: string + plan: CommitMessagePlan + target: LocalGenerationTarget + signal: AbortSignal + spawnAgent: SpawnSourceControlAgent + operation?: TextGenerationOperation +}): LocalProcessExecution { + let probeClosed = Promise.resolve() + const probe = async (args: string[]) => { + const execution = runSourceControlPolicyProbe({ ...input, args }) + probeClosed = execution.processClosed + const output = await execution.result + await execution.processClosed + input.signal.throwIfAborted() + return output + } + const result = prepare() + return { + result, + processClosed: result.then( + () => probeClosed, + () => probeClosed + ) + } + + async function prepare(): Promise { + const { plan, target, signal } = input + const naming = input.operation === 'conversation-name' + if (input.agentId === 'amp' || input.agentId === 'muse') { + if (naming) { + return plan + } + throw new Error('The agent cannot apply the text task tool policy') + } + if (input.agentId === 'antigravity') { + const help = await probe([...(plan.policyProbeArgs ?? []), '--help']) + if (![help.stdout, help.stderr].some((text) => /^\s*--settings(?:[= \t]|$)/m.test(text))) { + if (naming) { + return plan + } + throw new Error('The agent cannot apply session-only text task settings') + } + return antigravityPolicy(plan, target, signal) + } + if (input.agentId === 'kimi') { + const selected = findOptionOccurrence( + plan.args, + ['--agent', '--session', '-S', '--resume', '-r', '--continue', '-c', '-C'], + true, + [...KIMI_VALUE_OPTIONS, '--session', '-S', '--resume', '-r'], + 0, + false + ) + if (selected) { + if (naming) { + return plan + } + throw new Error('Kimi selected history/profile cannot apply the text task tool policy') + } + return prepareKimiTextTaskPolicy(plan, (file) => recipeFile(file, target, signal, plan.env)) + } + if (input.agentId === 'dsh') { + return dshPolicy(plan) + } + if (input.agentId !== 'codex') { + return plan + } + const raw = await probe([ + ...(plan.policyProbeArgs ?? []), + ...codexExclusions, + 'mcp', + 'list', + '--json' + ]) + const servers = z.array(z.looseObject({ name: z.string() })).parse(JSON.parse(raw.stdout)) + const entries = servers.map((server) => `${JSON.stringify(server.name)}={enabled=false}`) + return { + ...plan, + args: [...plan.args, ...codexExclusions, '-c', `mcp_servers={${entries.join(',')}}`] + } + } +} diff --git a/src/main/text-generation/source-control-supervised-agent-spawn.ts b/src/main/text-generation/source-control-supervised-agent-spawn.ts new file mode 100644 index 00000000000..70132c52640 --- /dev/null +++ b/src/main/text-generation/source-control-supervised-agent-spawn.ts @@ -0,0 +1,47 @@ +import { spawnProcess } from '@orca/process-host' +import { pathEnvRelativeTo, withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution' +import { resolveGuestNativeAgentCommand } from '../codex-cli/command' +import { createProviderSpawnSpec } from '../provider-process/provider-process-supervisor' +import { guardSupervisedProviderGroup } from '../provider-process/provider-group-orphan-guard' +import { SOURCE_CONTROL_KILL_SITE } from './source-control-agent-termination' +import { guestNativeSpawnEnv } from '../ipc/wsl-guest-windows-drive-path' +import type { + SourceControlAgentSpawnInput, + SpawnedSourceControlAgentProcess +} from './source-control-text-generation-types' + +// Supervisor owns the agent group so parent quit/death still stops generation. +export function spawnSupervisedAgent( + input: SourceControlAgentSpawnInput, + spawnEnv: NodeJS.ProcessEnv +): SpawnedSourceControlAgentProcess { + // On a WSL-host orcad, a missing CLI must fail rather than run a Windows shim found via PATH. + const env = guestNativeSpawnEnv(spawnEnv) + const cwd = input.useCwdForNative ? input.cwd : undefined + // Match native chats' install discovery from the agent's cwd, not Orca's. + const binary = input.binary.includes('/') + ? input.binary + : resolveGuestNativeAgentCommand(input.binary, { + pathEnv: pathEnvRelativeTo(env.PATH, cwd ?? process.cwd()), + homePath: env.HOME + }) + const spec = createProviderSpawnSpec( + { command: binary, args: input.args, ...(cwd !== undefined ? { cwd } : {}) }, + withCliRuntimeOnPath(binary, env), + process.platform, + { lifetime: 'one-shot' } + ) + const child = spawnProcess({ + program: spec.program, + args: spec.args, + env: spec.env, + cwd: spec.cwd, + detached: spec.detached, + stdio: ['pipe', 'pipe', 'pipe', ...spec.groupReportStdio] + }) + guardSupervisedProviderGroup(child, { + site: SOURCE_CONTROL_KILL_SITE, + supervised: spec.supervised + }) + return Object.assign(child, { supervised: spec.supervised }) +} diff --git a/src/main/text-generation/source-control-text-generation-types.ts b/src/main/text-generation/source-control-text-generation-types.ts index 6bfdab779c2..bf51fcd19b9 100644 --- a/src/main/text-generation/source-control-text-generation-types.ts +++ b/src/main/text-generation/source-control-text-generation-types.ts @@ -128,4 +128,5 @@ export type LocalSourceControlPlanInput = { operation: TextGenerationOperation wslDistro?: string spawnAgent: SpawnSourceControlAgent + timeoutMs?: number } diff --git a/src/main/text-generation/source-control-wsl-prompt.test.ts b/src/main/text-generation/source-control-wsl-prompt.test.ts index fb7fad45fec..87c5a211844 100644 --- a/src/main/text-generation/source-control-wsl-prompt.test.ts +++ b/src/main/text-generation/source-control-wsl-prompt.test.ts @@ -527,3 +527,56 @@ it.each(['success', 'nonzero', 'empty', 'storage', 'pipe-close'] as const)( } } ) + +it('delivers a plain UTF-8 policy module and preserves the stdin task after guest materialization', async () => { + const guest = prepareWslPrompt( + { + binary: process.execPath, + args: ['{module}'], + label: 'Policy fixture', + stdinPayload: 'Name this chat 🌊\nlast line', + taskFiles: [ + { name: 'task-policy.mjs', content: 'export const text = "policy 🌊"\n', argIndex: 0 } + ] + }, + 'Actual' + ) + const directory = `/tmp/orca-generation-${guest.preparation.args[0]}` + const child = spawnProcess({ + program: '/bin/sh', + args: [ + '-c', + guest.preparation.script, + 'fixture', + ...guest.preparation.args, + process.execPath, + '-e', + `const fs = require('node:fs'); const {pathToFileURL}=require('node:url'); import(pathToFileURL(process.argv[1])).then(module => process.stdout.write(JSON.stringify({ text: module.text, task: fs.readFileSync(0,'utf8'), prefix: fs.readFileSync(process.argv[1]).subarray(0,3).toString('hex') })))`, + '--', + ...guest.plan.args + ], + stdio: 'pipe' + }) + let stdout = '' + child.stdout.on('data', (chunk) => (stdout += chunk.toString())) + child.stdin.on('error', () => {}) + child.stderr.on('data', (chunk) => { + if (guest.observe(chunk)) { + child.stdin.end([...guest.records()].join('')) + } + }) + try { + const code = await new Promise((resolve, reject) => { + child.once('close', resolve) + child.once('error', reject) + }) + expect(code).toBe(0) + expect(JSON.parse(stdout)).toEqual({ + text: 'policy 🌊', + task: 'Name this chat 🌊\nlast line', + prefix: '657870' + }) + } finally { + await rm(directory, { recursive: true, force: true }) + } +}) diff --git a/src/shared/antigravity-generation-plan.test.ts b/src/shared/antigravity-generation-plan.test.ts index 64e805bef98..a3f0ce940cb 100644 --- a/src/shared/antigravity-generation-plan.test.ts +++ b/src/shared/antigravity-generation-plan.test.ts @@ -105,7 +105,8 @@ describe('Antigravity generation planning', () => { } })}\n`, label: 'Antigravity', - outputFormat: 'antigravity-stream-json' + outputFormat: 'antigravity-stream-json', + policyProbeArgs: [] } }) }) diff --git a/src/shared/opencode-cli-version.ts b/src/shared/opencode-cli-version.ts index 13033bce78c..2bcf99e2644 100644 --- a/src/shared/opencode-cli-version.ts +++ b/src/shared/opencode-cli-version.ts @@ -1,4 +1,4 @@ -import { isValidAppVersion } from './app-version' +import { compareAppVersions, isValidAppVersion } from './app-version' export const OPENCODE_NATIVE_PROMPT_VERSIONS = ['2.0.12', '2.0.16'] as const @@ -6,6 +6,7 @@ export type OpenCodeCliCapabilities = { version: string | null pluginApi: 'v1' | 'v2' | 'unknown' promptMode: 'submit' | 'prefill' | 'unknown' + v1SessionPolicyFiltersTools: boolean } export function parseOpenCodeCliVersion(output: string | null | undefined): string | null { @@ -23,6 +24,8 @@ export function getOpenCodeCliCapabilities( return { version, pluginApi: major === '1' ? 'v1' : major === '2' ? 'v2' : 'unknown', + v1SessionPolicyFiltersTools: + major === '1' && version !== null && compareAppVersions(version, '1.3.0') >= 0, promptMode: major === '1' ? 'submit' diff --git a/src/shared/opencode-generation-command.ts b/src/shared/opencode-generation-command.ts index b1cf68191b7..27a5c379956 100644 --- a/src/shared/opencode-generation-command.ts +++ b/src/shared/opencode-generation-command.ts @@ -1,6 +1,58 @@ import { findOptionOccurrence } from './command-option-occurrence' import type { CommitMessagePlan } from './source-control/ai/generation/commit-message-plan' +export function isDirectOpenCodeGenerationCommand(binary: string, prefixArgs: string[]): boolean { + return /(?:^|[\\/])opencode2?(?:\.(?:cmd|exe))?$/i.test(binary) && !prefixArgs.includes('--') +} + +/** Only these launchers expose an unambiguous executable operand. */ +export function openCodeGenerationLauncherBoundary( + binary: string, + prefixArgs: string[] +): number | null { + if (!/(?:^|[\\/])(?:npx|bunx)(?:\.(?:cmd|exe))?$/i.test(binary)) { + return null + } + const flags = new Set([ + '-y', + '--yes', + '--no', + '--no-install', + '--ignore-existing', + '--offline', + '-q', + '--quiet' + ]) + for (let index = 0; index < prefixArgs.length; index++) { + const token = prefixArgs[index] + if (token === '--') { + return /(?:^|[\\/])npx(?:\.(?:cmd|exe))?$/i.test(binary) && + prefixArgs[index + 1] !== undefined && + isDirectOpenCodeGenerationCommand(prefixArgs[index + 1], []) + ? index + 2 + : null + } + if (isDirectOpenCodeGenerationCommand(token, [])) { + return index + 1 + } + if (flags.has(token)) { + continue + } + if (token === '-p' || token === '--package') { + if (prefixArgs[index + 1] === undefined) { + return null + } + index++ + continue + } + if (token.startsWith('--package=')) { + continue + } + return null + } + return null +} + export function mergeOpenCodeGenerationArgs( agentId: string, binary: string, @@ -9,9 +61,8 @@ export function mergeOpenCodeGenerationArgs( ): string[] { if ( (agentId === 'opencode' || agentId === 'opencode2') && - /(?:^|[\\/])opencode2?(?:\.(?:cmd|exe))?$/i.test(binary) && - args[0] === 'run' && - !prefixArgs.includes('--') + isDirectOpenCodeGenerationCommand(binary, prefixArgs) && + args[0] === 'run' ) { return ['run', ...prefixArgs, ...args.slice(1)] } diff --git a/src/shared/remote-bundle-artifacts.ts b/src/shared/remote-bundle-artifacts.ts index c9a0649af1a..b12b097b2c2 100644 --- a/src/shared/remote-bundle-artifacts.ts +++ b/src/shared/remote-bundle-artifacts.ts @@ -16,3 +16,5 @@ export type RemoteBundlePlatform = (typeof REMOTE_BUNDLE_PLATFORMS)[number] export const OPENCODE_SQLITE_READER_FILENAME = 'opencode-sqlite-reader.cjs' /** Built into the WSL guest bundle dir (out/relay/wsl). */ export const WSL_CLAUDE_PROFILE_HELPER_FILENAME = 'claude-profile-wsl.cjs' +/** Built into the WSL guest bundle dir; runs the owned OpenCode text task inside the distro. */ +export const OPENCODE_WSL_TEXT_TASK_FILENAME = 'opencode-text-task-wsl.cjs' diff --git a/src/shared/source-control/ai/generation/commit-message-agent-spec.test.ts b/src/shared/source-control/ai/generation/commit-message-agent-spec.test.ts index bb5b42788af..18ca17eabd1 100644 --- a/src/shared/source-control/ai/generation/commit-message-agent-spec.test.ts +++ b/src/shared/source-control/ai/generation/commit-message-agent-spec.test.ts @@ -52,26 +52,6 @@ describe('COMMIT_MESSAGE_AGENT_SPECS', () => { ]) }) - it('uses Muse exec for non-interactive Source Control AI generation', () => { - const spec = COMMIT_MESSAGE_AGENT_SPECS.muse - expect(spec).toBeDefined() - expect(spec?.promptDelivery).toBe('argv') - expect(spec?.buildArgs({ prompt: 'Write a concise commit message', model: 'default' })).toEqual( - [ - 'exec', - '--no-session-log', - '--approval-mode', - 'never', - '--disable-sandbox', - '--disable-shell', - '--disable-write', - '--disable-web-tools', - '--', - 'Write a concise commit message' - ] - ) - }) - it('omits Kimi --model for the config default and an empty model', () => { const spec = COMMIT_MESSAGE_AGENT_SPECS.kimi! @@ -266,6 +246,7 @@ describe('buildArgs (Jcode)', () => { '--no-selfdev', '--tool-profile', 'none', + '--tools=', '--model', 'claude-haiku-4-5', 'run', @@ -282,6 +263,7 @@ describe('buildArgs (Jcode)', () => { '--no-selfdev', '--tool-profile', 'none', + '--tools=', 'run', '--json', 'name this branch' @@ -309,6 +291,7 @@ describe('buildArgs (Jcode)', () => { '--no-selfdev', '--tool-profile', 'none', + '--tools=', '--model', 'claude-haiku-4-5' ]) diff --git a/src/shared/source-control/ai/generation/commit-message-agent-specs-secondary.ts b/src/shared/source-control/ai/generation/commit-message-agent-specs-secondary.ts index 64bdaf703ad..1926a87b87f 100644 --- a/src/shared/source-control/ai/generation/commit-message-agent-specs-secondary.ts +++ b/src/shared/source-control/ai/generation/commit-message-agent-specs-secondary.ts @@ -123,8 +123,9 @@ export function buildSecondaryCommitMessageAgentSpecs({ 'exec', '--no-session-log', '--approval-mode', - 'never', - '--disable-sandbox', + 'on-request', + '--approval-judge', + 'off', '--disable-shell', '--disable-write', '--disable-web-tools', @@ -170,7 +171,14 @@ export function buildSecondaryCommitMessageAgentSpecs({ '--no-custom-instructions', '--model', model, - ...(thinkingLevel ? ['--effort', thinkingLevel] : []) + ...(thinkingLevel ? ['--effort', thinkingLevel] : []), + '--available-tools=view,glob,grep', + '--allow-tool=read', + '--deny-tool=write', + '--deny-tool=shell', + '--deny-tool=memory', + '--disable-builtin-mcps', + '--allow-all-paths' ], modelSource: 'static', // Copilot filters the picker by account/org policy; retain the full hosted catalog for permitted selections. @@ -188,10 +196,7 @@ export function buildSecondaryCommitMessageAgentSpecs({ id: 'claude-sonnet-4.6', label: 'Claude Sonnet 4.6' }, - { - id: 'claude-opus-4.5', - label: 'Claude Opus 4.5' - }, + { id: 'claude-opus-4.5', label: 'Claude Opus 4.5' }, { id: 'claude-opus-4.6', label: 'Claude Opus 4.6' @@ -292,6 +297,7 @@ export function buildSecondaryCommitMessageAgentSpecs({ // Staged patches are attacker-influenced; none removes shell/read/write and MCP via tools.rs base_allowed_tools, matching read-only siblings. '--tool-profile', 'none', + '--tools=', ...(model && model !== 'default' ? ['--model', model] : []), 'run', '--json', diff --git a/src/shared/source-control/ai/generation/commit-message-plan.test.ts b/src/shared/source-control/ai/generation/commit-message-plan.test.ts index 4a8ac964279..2b13f1bbac4 100644 --- a/src/shared/source-control/ai/generation/commit-message-plan.test.ts +++ b/src/shared/source-control/ai/generation/commit-message-plan.test.ts @@ -87,7 +87,7 @@ describe('planCommitMessageGeneration', () => { 'PROMPT' ) - expect(result).toEqual({ + expect(result).toMatchObject({ ok: true, plan: { binary: 'opencode', @@ -119,7 +119,7 @@ describe('planCommitMessageGeneration', () => { 'PROMPT' ) - expect(result).toEqual({ + expect(result).toMatchObject({ ok: true, plan: { binary: 'npx', @@ -190,6 +190,7 @@ describe('planCommitMessageGeneration', () => { '--no-selfdev', '--tool-profile', 'none', + '--tools=', 'run', '--json', 'name this branch' @@ -241,7 +242,7 @@ describe('planCommitMessageGeneration', () => { 'PROMPT' ) - expect(result).toEqual({ + expect(result).toMatchObject({ ok: true, plan: { binary: 'codex', @@ -273,8 +274,9 @@ describe('planCommitMessageGeneration', () => { 'exec', '--no-session-log', '--approval-mode', - 'never', - '--disable-sandbox', + 'on-request', + '--approval-judge', + 'off', '--disable-shell', '--disable-write', '--disable-web-tools', @@ -325,7 +327,7 @@ describe('planCommitMessageGeneration', () => { 'sibling arguments', '--model gpt-5.6-luna --sandbox read-only', ['--model', 'gpt-5.6-luna'], - ['--sandbox', 'read-only'] + [] ] ])( 'lets Codex recipe args override the generated model via %s', @@ -355,7 +357,7 @@ describe('planCommitMessageGeneration', () => { } ) - it('keeps Codex recipe arguments unchanged when they do not override the model', () => { + it('keeps Codex helpers read-only when the recipe requests workspace writes', () => { const result = planCommitMessageGeneration( { agentId: 'codex', @@ -375,9 +377,7 @@ describe('planCommitMessageGeneration', () => { '-s', 'read-only', '--model', - 'gpt-5.4-mini', - '--sandbox', - 'workspace-write' + 'gpt-5.4-mini' ] } }) diff --git a/src/shared/source-control/ai/generation/commit-message-plan.ts b/src/shared/source-control/ai/generation/commit-message-plan.ts index 97cfb7f421f..4a6f03d8348 100644 --- a/src/shared/source-control/ai/generation/commit-message-plan.ts +++ b/src/shared/source-control/ai/generation/commit-message-plan.ts @@ -18,8 +18,17 @@ import { planAdditionalAgentArgs, compactRecipeOptions } from './commit-message-generation-options' +import { + taskPolicyRecipeArgs, + codexRecipeConfigArgs, + applySingletonOptionOverrides +} from './commit-message-recipe-options' import type { TuiAgent } from '../../../agent-launch/catalog/tui-agent' -import { mergeOpenCodeGenerationArgs } from '../../../opencode-generation-command' +import { + isDirectOpenCodeGenerationCommand, + openCodeGenerationLauncherBoundary, + mergeOpenCodeGenerationArgs +} from '../../../opencode-generation-command' import { buildAntigravityGenerationInput } from '../../../antigravity-generation-stream' // Share pure request/prompt-to-spawn validation and argv planning between local main and SSH JSON-RPC generators. @@ -42,11 +51,16 @@ export type CommitMessagePlan = { stdinPayload: string | null /** Execution-host-owned prompt attachment, materialized only when starting the process. */ promptFile?: { content: string; argIndex: number } + /** Task-owned UTF-8 policy artifacts, materialized on the execution host. */ + taskFiles?: { name: string; content: string; argIndex?: number; interpolateDirectory?: boolean }[] + policyProbeArgs?: string[] /** Human-readable label used in error prefixes (e.g. "Claude failed: ..."). */ label: string /** Leading command assignments, applied on the execution host. */ env?: Record outputFormat?: 'opencode-json' | 'antigravity-stream-json' | 'kimi-stream-json' + /** Resolved native-task inputs; the receiving execution runtime owns the server. */ + openCodeTask?: { prefixArgs: string[]; runArgs: string[] } } export type CommitMessagePlanResult = @@ -61,85 +75,6 @@ const ANTIGRAVITY_FORMAT_OPTIONS = [ '-output-format' ] -function applyRecipeOptionOverride(args: { - generatedArgs: string[] - recipeArgs: string[] - aliases: readonly string[] - valueOptions: readonly string[] -}): { generatedArgs: string[]; recipeArgs: string[] } { - const recipeOption = findRecipeOption(args.recipeArgs, args.aliases, args.valueOptions) - const generatedOption = findRecipeOption( - args.generatedArgs, - args.aliases, - args.valueOptions, - 0, - false - ) - if (!recipeOption || !generatedOption) { - return { generatedArgs: args.generatedArgs, recipeArgs: args.recipeArgs } - } - - const overrideTokens = args.recipeArgs.slice( - recipeOption.index, - recipeOption.index + recipeOption.consumed - ) - return { - generatedArgs: [ - ...args.generatedArgs.slice(0, generatedOption.index), - ...overrideTokens, - ...args.generatedArgs.slice(generatedOption.index + generatedOption.consumed) - ], - recipeArgs: [ - ...args.recipeArgs.slice(0, recipeOption.index), - ...args.recipeArgs.slice(recipeOption.index + recipeOption.consumed) - ] - } -} - -/** User recipe args outrank override prefixes, which outrank generated singleton values. */ -function applySingletonOptionOverrides(args: { - generatedArgs: string[] - prefixArgs: string[] - recipeArgs: string[] - singletonOptions: readonly (readonly string[])[] - valueOptions: readonly string[] -}): { generatedArgs: string[]; prefixArgs: string[]; recipeArgs: string[] } { - let generatedArgs = args.generatedArgs - let prefixArgs = args.prefixArgs - let recipeArgs = args.recipeArgs - - for (const aliases of args.singletonOptions) { - recipeArgs = compactRecipeOptions(recipeArgs, aliases, args.valueOptions, true) - prefixArgs = compactRecipeOptions(prefixArgs, aliases, args.valueOptions, true) - const recipeOption = findRecipeOption(recipeArgs, aliases, args.valueOptions) - const prefixOption = findRecipeOption(prefixArgs, aliases, args.valueOptions) - const prefixHasTerminator = - findOptionOccurrence(prefixArgs, ['--'], false, args.valueOptions, 0, false) !== null - if (recipeOption && !prefixHasTerminator) { - prefixArgs = compactRecipeOptions(prefixArgs, aliases, args.valueOptions) - } else if (prefixOption && !prefixHasTerminator) { - const generatedOption = findRecipeOption(generatedArgs, aliases, args.valueOptions, 0, false) - if (generatedOption) { - generatedArgs = [ - ...generatedArgs.slice(0, generatedOption.index), - ...generatedArgs.slice(generatedOption.index + generatedOption.consumed) - ] - } - continue - } - const withRecipe = applyRecipeOptionOverride({ - generatedArgs, - recipeArgs, - aliases, - valueOptions: args.valueOptions - }) - generatedArgs = withRecipe.generatedArgs - recipeArgs = withRecipe.recipeArgs - } - - return { generatedArgs, prefixArgs, recipeArgs } -} - function insertAdditionalAgentArgs(args: { baseArgs: string[] agentArgs: string[] @@ -243,11 +178,11 @@ export function planCommitMessageGeneration( const prefixArgs = input.agentId === 'antigravity' ? compactRecipeOptions(command.prefixArgs, ANTIGRAVITY_FORMAT_OPTIONS) - : command.prefixArgs + : taskPolicyRecipeArgs(input.agentId, command.prefixArgs) const recipeArgs = input.agentId === 'antigravity' ? compactRecipeOptions(agentArgs.args, ANTIGRAVITY_FORMAT_OPTIONS) - : agentArgs.args + : taskPolicyRecipeArgs(input.agentId, agentArgs.args) const baseArgs = spec.buildArgs({ prompt: argvPrompt, model: input.model, @@ -287,6 +222,19 @@ export function planCommitMessageGeneration( input.agentId === 'kimi' ? findRecipeOption(generationArgs, ['--output-format'], KIMI_VALUE_OPTIONS) : null + const directOpenCode = isDirectOpenCodeGenerationCommand(command.binary, merged.prefixArgs) + const launcherBoundary = openCodeGenerationLauncherBoundary( + command.binary, + merged.nativePrefixArgs + ) + const nativePrefixArgs = + launcherBoundary === null + ? merged.nativePrefixArgs + : merged.nativePrefixArgs.slice(0, launcherBoundary) + const nativeRunOptions = + launcherBoundary === null + ? merged.nativePrefixOptions + : [...merged.nativePrefixOptions, ...merged.nativePrefixArgs.slice(launcherBoundary)] return { ok: true, plan: { @@ -307,6 +255,25 @@ export function planCommitMessageGeneration( } : {}), label: spec.label, + ...(input.agentId === 'codex' + ? { + policyProbeArgs: [ + ...compactRecipeOptions(merged.prefixArgs, ['--model', '-m']), + ...codexRecipeConfigArgs(merged.recipeArgs) + ] + } + : {}), + ...(input.agentId === 'antigravity' ? { policyProbeArgs: merged.prefixArgs } : {}), + ...(input.agentId === 'opencode' || input.agentId === 'opencode2' + ? { + openCodeTask: { + prefixArgs: directOpenCode ? [] : nativePrefixArgs, + runArgs: directOpenCode + ? generationArgs.slice(1) + : [...nativeRunOptions, ...args.slice(1)] + } + } + : {}), ...(formatOption?.value === 'json' ? { outputFormat: 'opencode-json' as const } : {}), ...(kimiFormatOption?.value === 'stream-json' ? { outputFormat: 'kimi-stream-json' as const } diff --git a/src/shared/source-control/ai/generation/commit-message-recipe-options.ts b/src/shared/source-control/ai/generation/commit-message-recipe-options.ts new file mode 100644 index 00000000000..b22e4d42ce1 --- /dev/null +++ b/src/shared/source-control/ai/generation/commit-message-recipe-options.ts @@ -0,0 +1,167 @@ +import { findOptionOccurrence } from '../../../command-option-occurrence' +import { compactRecipeOptions, findRecipeOption } from './commit-message-generation-options' + +export function taskPolicyRecipeArgs(agent: string, args: string[]): string[] { + if (agent === 'jcode') { + return compactRecipeOptions(args, ['--tool-profile', '--tools']) + } + if (agent === 'codex') { + const result = compactRecipeOptions(args, ['--sandbox', '-s']).filter( + (token) => + !['--dangerously-bypass-approvals-and-sandbox', '--yolo', '--full-auto'].includes(token) + ) + let option = findOptionOccurrence(result, ['--enable'], true) + while (option) { + const next = option.index + option.consumed + if (option.value === 'apps' || option.value === 'plugins') { + result.splice(option.index, option.consumed) + option = findOptionOccurrence(result, ['--enable'], true, [], option.index) + } else { + option = findOptionOccurrence(result, ['--enable'], true, [], next) + } + } + return result + } + if (agent !== 'copilot') { + return args + } + const result: string[] = [] + for (let index = 0; index < args.length; index++) { + const token = args[index] + if (token === '--') { + return [...result, ...args.slice(index)] + } + if (token.startsWith('--available-tools=')) { + continue + } + if (token === '--available-tools') { + while (args[index + 1] !== undefined && !args[index + 1].startsWith('-')) { + index++ + } + } else { + result.push(token) + } + } + return result +} + +export function codexRecipeConfigArgs(args: string[]): string[] { + const valueOptions = [ + '-c', + '--config', + '-p', + '--profile', + '--profile-v2', + '-C', + '--cd', + '--enable', + '--disable', + '--local-provider' + ] + const result: string[] = [] + for (let index = 0; index < args.length; index++) { + const option = findOptionOccurrence(args, valueOptions, true, [], index) + if (!option) { + break + } + result.push(...args.slice(option.index, option.index + option.consumed)) + index = option.index + option.consumed - 1 + } + return result +} + +function applyRecipeOptionOverride(args: { + generatedArgs: string[] + recipeArgs: string[] + aliases: readonly string[] + valueOptions: readonly string[] +}): { generatedArgs: string[]; recipeArgs: string[] } { + const recipeOption = findRecipeOption(args.recipeArgs, args.aliases, args.valueOptions) + const generatedOption = findRecipeOption( + args.generatedArgs, + args.aliases, + args.valueOptions, + 0, + false + ) + if (!recipeOption || !generatedOption) { + return { generatedArgs: args.generatedArgs, recipeArgs: args.recipeArgs } + } + + const overrideTokens = args.recipeArgs.slice( + recipeOption.index, + recipeOption.index + recipeOption.consumed + ) + return { + generatedArgs: [ + ...args.generatedArgs.slice(0, generatedOption.index), + ...overrideTokens, + ...args.generatedArgs.slice(generatedOption.index + generatedOption.consumed) + ], + recipeArgs: [ + ...args.recipeArgs.slice(0, recipeOption.index), + ...args.recipeArgs.slice(recipeOption.index + recipeOption.consumed) + ] + } +} + +/** User recipe args outrank override prefixes, which outrank generated singleton values. */ +export function applySingletonOptionOverrides(args: { + generatedArgs: string[] + prefixArgs: string[] + recipeArgs: string[] + singletonOptions: readonly (readonly string[])[] + valueOptions: readonly string[] +}): { + generatedArgs: string[] + prefixArgs: string[] + recipeArgs: string[] + nativePrefixArgs: string[] + nativePrefixOptions: string[] +} { + let generatedArgs = args.generatedArgs + let prefixArgs = args.prefixArgs + let recipeArgs = args.recipeArgs + const claimed: (readonly string[])[] = [] + + for (const aliases of args.singletonOptions) { + recipeArgs = compactRecipeOptions(recipeArgs, aliases, args.valueOptions, true) + prefixArgs = compactRecipeOptions(prefixArgs, aliases, args.valueOptions, true) + const recipeOption = findRecipeOption(recipeArgs, aliases, args.valueOptions) + const prefixOption = findRecipeOption(prefixArgs, aliases, args.valueOptions) + const prefixHasTerminator = + findOptionOccurrence(prefixArgs, ['--'], false, args.valueOptions, 0, false) !== null + if (recipeOption && !prefixHasTerminator) { + prefixArgs = compactRecipeOptions(prefixArgs, aliases, args.valueOptions) + } else if (prefixOption && !prefixHasTerminator) { + claimed.push(aliases) + const generatedOption = findRecipeOption(generatedArgs, aliases, args.valueOptions, 0, false) + if (generatedOption) { + generatedArgs = [ + ...generatedArgs.slice(0, generatedOption.index), + ...generatedArgs.slice(generatedOption.index + generatedOption.consumed) + ] + } + continue + } + const withRecipe = applyRecipeOptionOverride({ + generatedArgs, + recipeArgs, + aliases, + valueOptions: args.valueOptions + }) + generatedArgs = withRecipe.generatedArgs + recipeArgs = withRecipe.recipeArgs + } + + // Claims refer to the compacted prefix, after precedence has selected the effective inputs. + const spans = claimed.map((aliases) => findRecipeOption(prefixArgs, aliases, args.valueOptions)!) + const nativePrefixOptions = spans.flatMap((option) => + prefixArgs.slice(option.index, option.index + option.consumed) + ) + const nativePrefixArgs = [...prefixArgs] + for (const option of spans.sort((left, right) => right.index - left.index)) { + nativePrefixArgs.splice(option.index, option.consumed) + } + return { generatedArgs, prefixArgs, recipeArgs, nativePrefixArgs, nativePrefixOptions } +} diff --git a/src/shared/source-control/ai/generation/conversation-name-generation.ts b/src/shared/source-control/ai/generation/conversation-name-generation.ts index abbcf7a4f4d..1b7165b7c29 100644 --- a/src/shared/source-control/ai/generation/conversation-name-generation.ts +++ b/src/shared/source-control/ai/generation/conversation-name-generation.ts @@ -15,6 +15,15 @@ export function clampConversationNameFirstPrompt(firstPrompt: string): string { /** The naming request's first line; Session History reads it to hide these one-shot runs. */ export const CONVERSATION_NAME_PROMPT_OPENING = "Name this chat from the user's first request." +export const CONVERSATION_NAME_TASK_INSTRUCTION = + 'This is a naming-only task. Do not edit files, run commands, use tools, or perform the first request.' + +export function conversationNameTaskPrompt(prompt: string): string { + return prompt.trimEnd().endsWith(CONVERSATION_NAME_TASK_INSTRUCTION) + ? prompt + : `${prompt}\n\n${CONVERSATION_NAME_TASK_INSTRUCTION}` +} + export function buildConversationNamePrompt( context: ConversationNameContext, customPrompt = '' @@ -27,7 +36,9 @@ Output only the title, with no heading, quotes, or explanation. First request: ${firstPrompt}` const extra = customPrompt.trim() - return extra ? `${basePrompt}\n\nAdditional instructions:\n${extra}` : basePrompt + return conversationNameTaskPrompt( + extra ? `${basePrompt}\n\nAdditional instructions:\n${extra}` : basePrompt + ) } export function renderConversationNamePrompt(