Skip to content

Commit 6747a05

Browse files
authored
Drive kilo review sessions over ACP (#102)
* Drive kilo reviews over ACP; harden codex-acp env kilo acp (inherited from opencode) reuses kiloEnvForAuth verbatim; the model rides the session's config option with gateway-prefixed candidates - kilo ALWAYS selects because its session default is a paid model while jbot's kilo/default means the free gateway tier. Plan mode falls back to the mode config option when session/modes is absent. The legacy argv driver is deleted. Two bugs the kilo E2E exposed: temp-home cleanup raced the dying agent's SQLite writes (ENOTEMPTY) - teardown now awaits process close and never throws; opencode-lineage agents can flush trailing updates after the prompt response (anomalyco/opencode#17505) - textless turns drain briefly first. codex-acp env hardening per PR #100 r3639668997: ambient CODEX_CONFIG / CODEX_PATH / MODEL_PROVIDER stripped, INITIAL_AGENT_MODE pinned read-only. * Lead kilo model candidates with the gateway-prefixed id Dogfood finding from jbot's own kilo-over-ACP run: option values are always prefixed, so the prefixed candidate goes first - the bare id is only a hedge against kilo dropping the prefix, never the expected match. * Drain trailing ACP frames unconditionally; make codex env test non-vacuous The post-prompt drain ran only when the turn looked textless, so trailing session/update frames after the response (opencode#17505) were dropped whenever any text had already arrived - truncating the final message. Drain unconditionally and flush once after, removing the early flush that split a message across the response boundary. The race is flush-ordering (frames land within an I/O tick), so the window drops 750->300ms. The codex env-hardening test now seeds ambient CODEX_CONFIG/CODEX_PATH/ MODEL_PROVIDER before env() and asserts all three are stripped, so a dropped delete is caught rather than passing vacuously.
1 parent 157e611 commit 6747a05

5 files changed

Lines changed: 265 additions & 484 deletions

File tree

‎src/shared/acp.ts‎

Lines changed: 147 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
devinCredentialsPath,
1414
tomlString,
1515
} from './devin.ts';
16+
import { KILO_CLI_BIN, KILO_GATEWAY_FREE_MODEL, KILO_PROVIDER_ID, kiloEnvForAuth } from './kilo.ts';
1617
import { parseModelName } from './model.ts';
1718
import {
1819
parseChangesSinceLastReviewSummary,
@@ -40,6 +41,9 @@ const ACP_PROTOCOL_VERSION = 1;
4041
// runaway child, and the connection fails loud instead of buffering to OOM.
4142
const ACP_MAX_FRAME_BYTES = 32 * 1024 * 1024;
4243
const ACP_STDERR_TAIL_BYTES = 64 * 1024;
44+
// The trailing-frame race (opencode#17505) is flush-ordering, so late frames
45+
// arrive within an I/O tick; this covers it without paying 750ms per session.
46+
const ACP_POST_TURN_DRAIN_MS = 300;
4347

4448
export const CODEX_ACP_BIN = 'codex-acp';
4549

@@ -236,9 +240,10 @@ interface AcpSessionOptions {
236240
agent: string;
237241
label: string;
238242
log: (msg: string) => void;
239-
/** Select this model via the agent's ACP model config option (agents whose
240-
* spec sets modelConfigOption — CLI flags/env don't reach their sessions). */
241-
configOptionModelId?: string;
243+
/** Ordered candidates to select via the agent's ACP model config option
244+
* (agents whose spec sets modelConfigCandidates — CLI flags/env don't reach
245+
* their sessions). First candidate that matches an offered value wins. */
246+
configOptionModelIds?: string[];
242247
/** Fail closed when plan mode is missing or cannot be set (agents with no
243248
* agent-side sandbox — plan mode is their behavioral read-only layer). */
244249
requirePlanMode?: boolean;
@@ -365,7 +370,7 @@ export async function driveAcpSession(
365370
if (typeof sessionId !== 'string' || !sessionId) {
366371
throw new Error(`acp:${agent} ${label}: session/new returned no sessionId`);
367372
}
368-
if (options.configOptionModelId) {
373+
if (options.configOptionModelIds?.length) {
369374
await selectModelConfigOption(conn, sessionId, session, options);
370375
}
371376
const modes = session.modes as
@@ -386,15 +391,26 @@ export async function driveAcpSession(
386391
}
387392
log(`acp:${agent} ${label}: ${detail}; relying on permission policy`);
388393
}
389-
} else if (!planOffered && options.requirePlanMode) {
390-
throw new Error(
391-
`acp:${agent} ${label}: agent offered no plan mode; refusing to run without it`,
392-
);
394+
} else if (!planOffered) {
395+
// kilo exposes mode as a config option (no session/modes); its `plan`
396+
// value is the read-only agent — the same contract as opencode's.
397+
const applied = await selectPlanConfigOption(conn, sessionId, session, options);
398+
if (!applied && options.requirePlanMode) {
399+
throw new Error(
400+
`acp:${agent} ${label}: agent offered no plan mode; refusing to run without it`,
401+
);
402+
}
393403
}
394404
const result = (await conn.request('session/prompt', {
395405
sessionId,
396406
prompt: [{ type: 'text', text: options.prompt }],
397407
})) as Record<string, unknown>;
408+
// opencode-lineage agents can flush trailing session/update frames AFTER the
409+
// prompt response (anomalyco/opencode#17505, live-hit via kilo). Flushing
410+
// now would truncate — the trailing chunks land in `current` after this
411+
// point whether or not text already arrived — so drain first (the ordering
412+
// race resolves within one I/O flush), then take the final segment.
413+
await new Promise((resolve) => setTimeout(resolve, ACP_POST_TURN_DRAIN_MS));
398414
flush();
399415
return {
400416
text: (segments[segments.length - 1] ?? '').trim(),
@@ -411,14 +427,58 @@ interface ConfigOptionState {
411427

412428
/** Every failure here throws: silently reviewing on a model the user did not
413429
* pick would misrepresent the review, so no fail-open. */
430+
/** Plan mode via the `mode` config option, for agents without session/modes.
431+
* Returns whether plan is (now) active; setting failures throw when plan mode
432+
* is required — a review outside the read-only agent must not run. */
433+
async function selectPlanConfigOption(
434+
conn: AcpConnection,
435+
sessionId: string,
436+
session: Record<string, unknown>,
437+
options: AcpSessionOptions,
438+
): Promise<boolean> {
439+
const { agent, label, log } = options;
440+
const configOptions = (session.configOptions ?? []) as ConfigOptionState[];
441+
const modeOption = configOptions.find(
442+
(option) => option.id === 'mode' || option.category === 'mode',
443+
);
444+
if (!modeOption?.id) return false;
445+
const plan = matchModelOptionValue(modeOption.options ?? [], 'plan');
446+
if (!plan) return false;
447+
if (modeOption.currentValue === plan) return true;
448+
try {
449+
const updated = (await conn.request('session/set_config_option', {
450+
sessionId,
451+
configId: modeOption.id,
452+
value: plan,
453+
})) as Record<string, unknown> | undefined;
454+
const after = ((updated?.configOptions ?? []) as ConfigOptionState[]).find(
455+
(option) => option.id === modeOption.id,
456+
);
457+
if (after?.currentValue !== plan) {
458+
throw new Error(`agent reports mode ${JSON.stringify(after?.currentValue)}`);
459+
}
460+
return true;
461+
} catch (error) {
462+
const detail = `plan mode via config option failed (${
463+
error instanceof Error ? error.message : String(error)
464+
})`;
465+
if (options.requirePlanMode) {
466+
throw new Error(`acp:${agent} ${label}: ${detail}; refusing to run without it`);
467+
}
468+
log(`acp:${agent} ${label}: ${detail}; relying on permission policy`);
469+
return false;
470+
}
471+
}
472+
414473
async function selectModelConfigOption(
415474
conn: AcpConnection,
416475
sessionId: string,
417476
session: Record<string, unknown>,
418477
options: AcpSessionOptions,
419478
): Promise<void> {
420-
const { agent, label, configOptionModelId } = options;
421-
const modelId = configOptionModelId as string;
479+
const { agent, label } = options;
480+
const candidates = options.configOptionModelIds as string[];
481+
const modelId = candidates[0];
422482
const configOptions = (session.configOptions ?? []) as ConfigOptionState[];
423483
const modelOption = configOptions.find(
424484
(option) => option.id === 'model' || option.category === 'model',
@@ -428,7 +488,11 @@ async function selectModelConfigOption(
428488
`acp:${agent} ${label}: agent exposes no model config option; cannot select "${modelId}"`,
429489
);
430490
}
431-
const value = matchModelOptionValue(modelOption.options ?? [], modelId);
491+
let value: string | undefined;
492+
for (const candidate of candidates) {
493+
value = matchModelOptionValue(modelOption.options ?? [], candidate);
494+
if (value) break;
495+
}
432496
if (!value) {
433497
const available = (modelOption.options ?? [])
434498
.flatMap((option) => (Array.isArray(option.options) ? option.options : [option]))
@@ -463,9 +527,12 @@ interface AcpAgentSpec {
463527
args(model: string): string[];
464528
/** Per-spawn env + optional cleanup (temp auth copies, config files). */
465529
env(model: string): { env: NodeJS.ProcessEnv; cleanup?: () => void };
466-
/** Model rides the agent's ACP model config option — for agents (devin)
467-
* whose CLI flags/env/config never reach the ACP session. */
468-
modelConfigOption?: boolean;
530+
/** Ordered model-id candidates for the agent's ACP model config option —
531+
* for agents (devin, kilo) whose CLI flags/env/config never reach the ACP
532+
* session. Empty result skips selection; kilo always returns candidates
533+
* because its session default is a PAID model while jbot's kilo/default
534+
* means the free gateway tier. */
535+
modelConfigCandidates?(model: string): string[];
469536
/** See AcpSessionOptions.requirePlanMode. */
470537
requirePlanMode?: boolean;
471538
}
@@ -480,8 +547,7 @@ async function runAcpPrompt(
480547
timeoutMs = ACP_PROMPT_TIMEOUT_MS,
481548
): Promise<string> {
482549
const { env, cleanup } = spec.env(model);
483-
const { modelID } = parseModelName(model);
484-
const configOptionModelId = spec.modelConfigOption && modelID !== 'default' ? modelID : undefined;
550+
const configOptionModelIds = spec.modelConfigCandidates?.(model);
485551
log(`Calling ${label} prompt (agent=acp:${spec.id}, model=${model})`);
486552
const child = spawn(spec.bin, spec.args(model), {
487553
cwd: workspace,
@@ -510,7 +576,7 @@ async function runAcpPrompt(
510576
agent: spec.id,
511577
label,
512578
log,
513-
configOptionModelId,
579+
configOptionModelIds,
514580
requirePlanMode: spec.requirePlanMode,
515581
},
516582
),
@@ -551,7 +617,22 @@ async function runAcpPrompt(
551617
if (child.exitCode === null && child.signalCode === null) {
552618
terminateProcessTree(child, ACP_KILL_GRACE_MS);
553619
}
554-
cleanup?.();
620+
// Wait (bounded) for the exit before removing the temp home: a dying
621+
// agent still writing there (kilo's SQLite) races rmSync into ENOTEMPTY.
622+
await new Promise<void>((resolve) => {
623+
if (child.exitCode !== null || child.signalCode !== null) return resolve();
624+
const grace = setTimeout(resolve, ACP_KILL_GRACE_MS + 500);
625+
grace.unref();
626+
child.once('close', () => {
627+
clearTimeout(grace);
628+
resolve();
629+
});
630+
});
631+
try {
632+
cleanup?.();
633+
} catch {
634+
// Teardown must never mask the session result; tmpdir reclaims leftovers.
635+
}
555636
}
556637
}
557638

@@ -727,7 +808,43 @@ export function devinAcpSpec(credentialsHome = process.env.HOME || homedir()): A
727808
delete env.XDG_DATA_HOME;
728809
return { env, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
729810
},
730-
modelConfigOption: true,
811+
modelConfigCandidates: (model) => {
812+
const { modelID } = parseModelName(model);
813+
return modelID === 'default' ? [] : [modelID, model];
814+
},
815+
requirePlanMode: true,
816+
};
817+
}
818+
819+
export function kiloAcpSpec(auth: string): AcpAgentSpec {
820+
return {
821+
id: 'kilo',
822+
bin: KILO_CLI_BIN,
823+
args: () => ['acp'],
824+
// kiloEnvForAuth: per-spawn temp HOME/XDG (kilo's SQLite data dir race) +
825+
// env-injected KILO_AUTH_CONTENT + ambient key stripping — the argv
826+
// driver's materialization, live-verified against `kilo acp`.
827+
env: () => {
828+
const dir = mkdtempSync(join(tmpdir(), 'jbot-kilo-acp-'));
829+
try {
830+
return {
831+
env: kiloEnvForAuth(auth, dir),
832+
cleanup: () => rmSync(dir, { recursive: true, force: true }),
833+
};
834+
} catch (error) {
835+
rmSync(dir, { recursive: true, force: true });
836+
throw error;
837+
}
838+
},
839+
// ALWAYS select: the ACP session default is a paid model, while jbot's
840+
// kilo/default means the free gateway tier. Option values are full
841+
// gateway-prefixed ids (`kilo/<vendor>/<model>`), so the prefixed form
842+
// leads; the bare id is only a hedge against kilo dropping the prefix.
843+
modelConfigCandidates: (model) => {
844+
const { modelID } = parseModelName(model);
845+
const id = modelID === 'default' ? KILO_GATEWAY_FREE_MODEL : modelID;
846+
return [`${KILO_PROVIDER_ID}/${id}`, id];
847+
},
731848
requirePlanMode: true,
732849
};
733850
}
@@ -752,8 +869,18 @@ export function codexAcpSpec(codexHome: string): AcpAgentSpec {
752869
rmSync(dir, { recursive: true, force: true });
753870
throw error;
754871
}
872+
const env = codexEnvForHome(dir);
873+
// codex-acp runtime overrides (README): CODEX_CONFIG merges into session
874+
// config, CODEX_PATH swaps the binary, MODEL_PROVIDER redirects models —
875+
// ambient values must not subvert the temp-home setup. INITIAL_AGENT_MODE
876+
// is pinned to the adapter's read-only mode as a positive layer.
877+
delete env.CODEX_CONFIG;
878+
delete env.CODEX_PATH;
879+
delete env.MODEL_PROVIDER;
880+
env.INITIAL_AGENT_MODE = 'read-only';
881+
env.NO_BROWSER = '1';
755882
return {
756-
env: codexEnvForHome(dir),
883+
env,
757884
cleanup: () => rmSync(dir, { recursive: true, force: true }),
758885
};
759886
},

0 commit comments

Comments
 (0)