Skip to content

Commit b79b690

Browse files
Attach Workbench to the original C1 Controller Turn (#10114)
* Attach Workbench to the bound C1 Controller and Worker Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * Defer activation dependencies until Controller input readback Signed-off-by: Lusen Dong <17559402+cocolord@users.noreply.github.com> Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * Retain Controller send identity across Workbench reloads Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * Refuse new Controller input after executor loss Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * Serialize Controller input with Goal Stop Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * Discover native Controller Turns through the registered Goal source Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * Isolate Controller discovery from unrelated Goal sources Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * Reuse the Core registry witness for Controller input Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * Keep Workbench Controller sends on the original Turn Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * Keep ordinary Workbench readback available without Core Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> * fix(workbench): suppress ActionSheet for C1 Controller turns Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> * fix(workbench): suppress LoopSupervisionBar and loop-matter polling during C1 controller states Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --------- Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> Signed-off-by: Lusen Dong <17559402+cocolord@users.noreply.github.com> Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Co-authored-by: Lusen Dong <17559402+cocolord@users.noreply.github.com> Co-authored-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent ada15c4 commit b79b690

47 files changed

Lines changed: 2431 additions & 287 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/workbench/packages/daemon/src/adapters/loopx/service.ts‎

Lines changed: 90 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
1-
import { randomUUID } from 'node:crypto';
1+
import { createHash, randomUUID } from 'node:crypto';
22
import { realpathSync, statSync } from 'node:fs';
3+
import { lstat } from 'node:fs/promises';
34
import { basename, dirname, join } from 'node:path';
45
import type { IncomingMessage, ServerResponse } from 'node:http';
56
import { HttpError } from '../../errors.js';
67
import type { AgentAdapter, ApprovalRequest } from '../types.js';
78
import { isWithinWorkdirs, type Workdirs } from '../../workdirs.js';
8-
import type { ThreadManager } from '../../threads.js';
9+
import type { ThreadManager, ThreadView } from '../../threads.js';
910
import { corePermission, fromCorePermission, goalAgentFor, goalThreadMode, LOOPX_PERMISSIONS, workspaceSandboxed, LoopxBindings, permissionAvailable, type GoalAdapter, type LoopxBinding, type LoopxPermission } from './binding.js';
1011
import { goalContextBlock } from './context.js';
1112
import { applyProposal, CoreError, coreJson, goalLocale, grantedWorkspaces, loadProposal, previewGoalCreate, registeredGoalRoot, workspaceRef, type GoalDraft } from './core.js';
1213
import { coreUrl } from './proxy.js';
13-
import { cliFromEnv, GoalStateCache, GoalStatusUnavailable, readGoalState, type GoalState, type LoopxCli } from './status.js';
14+
import { cliFromEnv, GoalStateCache, GoalStatusUnavailable, readControllerTurn, readGoalState, submitControllerInput, type GoalState, type LoopxCli } from './status.js';
1415
import type { LoopxLookup, SessionLoopx } from '../../session-enrich.js';
1516

1617
export interface LoopxDeps {
@@ -26,6 +27,8 @@ export interface LoopxHooks {
2627
binding(threadId: string): LoopxBinding | null;
2728
/** The block that rides with a Goal conversation's message; empty for an ordinary one. */
2829
context(threadId: string): Promise<string>;
30+
/** A C1 Controller session accepts input through its original Turn entrypoint. */
31+
requireOrdinaryTurn(thread: Pick<ThreadView, 'agent' | 'agentSessionId' | 'cwd'>): Promise<void>;
2932
/** What marks this thread as a Goal conversation in a list: its binding, or what the scan read from its session. */
3033
info(threadId: string, scanned?: SessionLoopx): SessionLoopx | null;
3134
/** A Goal conversation never asks the person: its boundary is the sandbox, not a prompt. */
@@ -44,9 +47,14 @@ const asText = (v: unknown, field: string, max = 4000): string => {
4447
return v.trim();
4548
};
4649

47-
async function body(req: IncomingMessage): Promise<any> {
50+
async function body(req: IncomingMessage, maxBytes = Infinity): Promise<any> {
4851
const chunks: Buffer[] = [];
49-
for await (const c of req) chunks.push(c as Buffer);
52+
let size = 0;
53+
for await (const chunk of req) {
54+
size += (chunk as Buffer).byteLength;
55+
if (size > maxBytes) throw new HttpError(413, 'Request body is too large');
56+
chunks.push(chunk as Buffer);
57+
}
5058
if (!chunks.length) return {};
5159
try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw new HttpError(400, 'invalid JSON body'); }
5260
}
@@ -873,6 +881,71 @@ export class LoopxService implements LoopxHooks {
873881
catch (err) { return { binding, state: null, freshness: 'unavailable', observedAt, error: err instanceof Error ? err.message : String(err) }; }
874882
}
875883

884+
async requireOrdinaryTurn(thread: Pick<ThreadView, 'agent' | 'agentSessionId' | 'cwd'>): Promise<void> {
885+
const adapter = this.deps.adapters.get(thread.agent);
886+
if (adapter?.id !== 'codex' || !thread.agentSessionId) return;
887+
const configDir = (await adapter.sessionLocation?.(null, thread.cwd))?.configDir;
888+
if (configDir && await this.hasControllerLocator(configDir, thread.agentSessionId)) {
889+
throw new HttpError(409, 'Send input through the original Controller Turn', { code: 'controller_input_required' });
890+
}
891+
}
892+
893+
private async hasControllerLocator(configDir: string, sessionId: string): Promise<boolean> {
894+
// The locator distinguishes ordinary conversations. Core validates the original journal for C1 input.
895+
const key = createHash('sha256').update(sessionId).digest('hex');
896+
try {
897+
await lstat(join(configDir, 'loopx', 'controller-sessions', `${key}.json`));
898+
} catch (error) {
899+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
900+
throw new HttpError(503, 'Original Controller session could not be checked', { code: 'controller_input_unavailable' });
901+
}
902+
return true;
903+
}
904+
905+
private async controllerTurn(threadId: string, query: URLSearchParams, input?: { workerSequence: number; operationId: string; text: string }) {
906+
if (!this.manager) throw new HttpError(503, 'Original Turn reader is unavailable');
907+
const subject = input || query.size > 0 ? {
908+
goalId: asText(query.get('goalId'), 'goalId', 200),
909+
agentId: asText(query.get('agentId'), 'agentId', 200),
910+
turnKey: asText(query.get('turnKey'), 'turnKey', 71),
911+
} : undefined;
912+
if (subject && !/^sha256:[a-f0-9]{64}$/.test(subject.turnKey)) throw new HttpError(400, 'Invalid Turn key');
913+
const thread = this.manager.getThread(threadId);
914+
const session = thread.agentSessionId;
915+
const binding = this.bindings.get(threadId);
916+
const adapter = this.deps.adapters.get(thread.agent);
917+
if (!session || adapter?.id !== 'codex') {
918+
if (!subject) return null;
919+
throw new HttpError(409, 'Conversation does not match the original Controller');
920+
}
921+
const configDir = input ? undefined : (await adapter.sessionLocation?.(null, thread.cwd))?.configDir;
922+
const located = !subject && configDir ? await this.hasControllerLocator(configDir, session) : undefined;
923+
if (located === false) return null;
924+
if (!this.cli.registry) {
925+
if (!subject && !located) return null;
926+
throw new HttpError(503, 'Original Turn reader is unavailable');
927+
}
928+
if ((binding && subject && binding.goalId !== subject.goalId) || !isWithinWorkdirs(thread.cwd, this.deps.dirs.all())) {
929+
throw new HttpError(409, 'Conversation does not match the original Controller');
930+
}
931+
const requested = input && subject
932+
? submitControllerInput(this.cli, subject.goalId, subject.agentId, subject.turnKey, session, input)
933+
: readControllerTurn(this.cli, session, subject, configDir);
934+
const turn = await requested.catch((error: Error) => {
935+
throw new HttpError(409, 'Original Controller Turn is unavailable', { code: error.message });
936+
});
937+
if (located && !turn) {
938+
throw new HttpError(409, 'Original Controller Turn is unavailable', { code: 'original_turn_unavailable' });
939+
}
940+
const current = this.manager.getThread(threadId);
941+
if (current.agentSessionId !== session || current.cwd !== thread.cwd || this.bindings.get(threadId) !== binding
942+
|| (binding && turn && 'goalId' in turn && turn.goalId !== binding.goalId)
943+
|| !isWithinWorkdirs(current.cwd, this.deps.dirs.all())) {
944+
throw new HttpError(409, 'Conversation changed during the original Turn read');
945+
}
946+
return turn;
947+
}
948+
876949
async health() {
877950
const core = await fetch(new URL('/healthz', this.core), { signal: AbortSignal.timeout(3000) }).then((r) => r.ok, () => false);
878951
return { core: { ok: core, url: this.core.origin } };
@@ -905,6 +978,18 @@ export class LoopxService implements LoopxHooks {
905978
if (path === '/api/loopx/launch/join' && method === 'POST') { send(res, 200, await this.join(await body(req))); return true; }
906979
const goal = /^\/api\/loopx\/goal\/([^/]+)$/.exec(path);
907980
if (goal && method === 'GET') { send(res, 200, await this.goal(decodeURIComponent(goal[1]), url.searchParams.get('refresh') === '1')); return true; }
981+
const turn = /^\/api\/loopx\/controller-turn\/([^/]+)$/.exec(path);
982+
if (turn && method === 'GET') { send(res, 200, await this.controllerTurn(decodeURIComponent(turn[1]), url.searchParams)); return true; }
983+
if (turn && method === 'POST') {
984+
const input = await body(req, 32 * 1024);
985+
if (!input || typeof input.text !== 'string' || !input.text.trim() || Buffer.byteLength(input.text) > 4096
986+
|| typeof input.operationId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(input.operationId)
987+
|| !Number.isSafeInteger(input.workerSequence) || input.workerSequence < 1) {
988+
throw new HttpError(400, 'Expected text, operationId and the observed Worker sequence');
989+
}
990+
send(res, 202, await this.controllerTurn(decodeURIComponent(turn[1]), url.searchParams, input));
991+
return true;
992+
}
908993
return false;
909994
}
910995
}

‎apps/workbench/packages/daemon/src/adapters/loopx/status.ts‎

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,153 @@ export interface LoopxCli {
2727
registry?: string;
2828
}
2929

30+
export function submitControllerInput(
31+
cli: LoopxCli, goalId: string, agentId: string, turnKey: string, controllerSessionId: string,
32+
input: { workerSequence: number; operationId: string; text: string },
33+
) {
34+
if (!cli.registry) return Promise.reject(new Error('controller_input_unavailable'));
35+
const [exe, ...prefix] = cli.command;
36+
const args = [...prefix, '--registry', cli.registry, '--format', 'json',
37+
'turn', 'submit-controller-input', '--goal-id', goalId, '--agent-id', agentId, '--turn-key', turnKey,
38+
'--match-codex-controller-session', controllerSessionId, '--worker-sequence', String(input.workerSequence),
39+
'--operation-id', input.operationId, '--execute'];
40+
return new Promise<{ operationId: string; workerSequence: number; queued: true; replayed: boolean }>((resolve, reject) => {
41+
const child = execFile(exe, args, {
42+
cwd: cli.cwd, timeout: 10000, maxBuffer: 128 * 1024, env: { ...process.env, LOOPX_USAGE_PING: '0' },
43+
}, (err, stdout) => {
44+
try {
45+
const receipt = JSON.parse(stdout);
46+
if (['controller_input_occupied', 'controller_input_worker_changed', 'controller_input_queue_full'].includes(receipt?.error_code)) {
47+
return reject(new Error(receipt.error_code));
48+
}
49+
if (err || receipt?.ok !== true || receipt.schema_version !== 'loopx_controller_input_v0'
50+
|| receipt.turn_key !== turnKey || receipt.operation_id !== input.operationId
51+
|| receipt.worker_sequence !== input.workerSequence || receipt.queued !== true
52+
|| typeof receipt.replayed !== 'boolean') throw new Error('controller_input_unavailable');
53+
resolve({ operationId: input.operationId, workerSequence: input.workerSequence, queued: true, replayed: receipt.replayed });
54+
} catch {
55+
reject(new Error('controller_input_unavailable'));
56+
}
57+
});
58+
child.stdin?.on('error', () => {}); // The child result reports a failed handoff.
59+
child.stdin?.end(input.text, 'utf8');
60+
});
61+
}
62+
63+
/** The original Turn's durable readback. An unobserved result carries no liveness claim. */
64+
interface ControllerInput {
65+
operationId: string;
66+
workerSequence: number;
67+
dispatched: boolean;
68+
text?: string;
69+
answer?: string;
70+
}
71+
72+
interface ControllerTurnReadback {
73+
goalId: string;
74+
agentId: string;
75+
turnKey: string;
76+
status: string;
77+
attempt: number;
78+
calls: { role: string; sequence: number; returned: boolean }[];
79+
inputEnabled?: true;
80+
executionLost?: true;
81+
goalActivation?: { state: 'active' | 'stopped'; title: string; sourceFingerprint: string };
82+
input?: ControllerInput;
83+
inputs?: ControllerInput[];
84+
inputHasCapacity?: boolean;
85+
}
86+
87+
/** A failed read alone does not tell us whether this installation supports that operation. */
88+
function controllerReadbackUnsupported(cli: LoopxCli): Promise<boolean> {
89+
const [exe, ...prefix] = cli.command;
90+
return new Promise(resolve => {
91+
execFile(exe, [...prefix, '--format', 'json', 'commands'], {
92+
cwd: cli.cwd, timeout: 5000, maxBuffer: 256 * 1024, env: { ...process.env, LOOPX_USAGE_PING: '0' },
93+
}, (err, stdout) => {
94+
if (err) return resolve(false);
95+
try {
96+
const catalog = JSON.parse(stdout);
97+
resolve(catalog?.schema_version === 'loopx_command_reference_v0' && catalog.ok === true && Array.isArray(catalog.groups)
98+
&& (catalog.features === undefined || catalog.features?.codex_controller_session_readback === false));
99+
} catch {
100+
resolve(false);
101+
}
102+
});
103+
});
104+
}
105+
106+
export function readControllerTurn(
107+
cli: LoopxCli, controllerSessionId: string, subject?: { goalId: string; agentId: string; turnKey: string },
108+
codexHome?: string,
109+
) {
110+
if (!cli.registry) return Promise.reject(new Error('original_turn_unavailable'));
111+
const [exe, ...prefix] = cli.command;
112+
const args = [...prefix, '--registry', cli.registry, '--format', 'json',
113+
'turn', 'inspect-journal',
114+
...(subject ? ['--goal-id', subject.goalId, '--agent-id', subject.agentId, '--turn-key', subject.turnKey] : []),
115+
'--match-codex-controller-session', controllerSessionId];
116+
return new Promise<ControllerTurnReadback | null>((resolve, reject) => {
117+
execFile(exe, args, {
118+
cwd: cli.cwd, timeout: 10000, maxBuffer: 4 * 1024 * 1024,
119+
env: { ...process.env, ...(codexHome ? { CODEX_HOME: codexHome } : {}), LOOPX_USAGE_PING: '0' },
120+
}, (err, stdout) => {
121+
if (err) return reject(new Error('original_turn_unavailable'));
122+
try {
123+
const payload = JSON.parse(stdout);
124+
if (!subject && payload?.schema_version === 'loopx_turn_journal_inspection_v1'
125+
&& payload.ok === true && payload.controller_turn === null) return resolve(null);
126+
const preview = payload?.codex_role_preview;
127+
if (payload?.schema_version !== 'loopx_turn_journal_inspection_v1' || payload.ok !== true
128+
|| payload.journal_consistent !== true || typeof payload.journal_status !== 'string'
129+
|| !Number.isSafeInteger(preview?.attempt) || !Array.isArray(preview.observed_roles)
130+
|| !preview.observed_roles.includes('controller')) {
131+
throw new Error('original_turn_unavailable');
132+
}
133+
const calls = ['controller', 'worker'].flatMap(role => {
134+
const call = preview.native_calls?.[role];
135+
return Number.isSafeInteger(call?.sequence) && call.sequence > 0 && typeof call.returned === 'boolean'
136+
? [{ role, sequence: call.sequence as number, returned: call.returned as boolean }] : [];
137+
});
138+
const scope = subject ?? { goalId: payload.controller_turn?.goal_id,
139+
agentId: payload.controller_turn?.agent_id, turnKey: payload.controller_turn?.turn_key };
140+
if (typeof scope.goalId !== 'string' || typeof scope.agentId !== 'string' || typeof scope.turnKey !== 'string'
141+
|| !/^sha256:[a-f0-9]{64}$/.test(scope.turnKey)) throw new Error('original_turn_unavailable');
142+
const projected: ControllerTurnReadback = { ...scope, status: payload.journal_status, attempt: preview.attempt, calls };
143+
if (payload.controller_input_enabled === true) projected.inputEnabled = true;
144+
if (payload.controller_execution_lost === true) projected.executionLost = true;
145+
const activation = payload.controller_goal_activation;
146+
if ((activation?.state === 'active' || activation?.state === 'stopped') && typeof activation.title === 'string'
147+
&& typeof activation.source_fingerprint === 'string' && /^[a-f0-9]{64}$/.test(activation.source_fingerprint)) {
148+
projected.goalActivation = { state: activation.state, title: activation.title, sourceFingerprint: activation.source_fingerprint };
149+
}
150+
const readInput = (input: Record<string, unknown>): ControllerInput => {
151+
if (typeof input?.operation_id !== 'string' || typeof input.worker_sequence !== 'number'
152+
|| !Number.isSafeInteger(input.worker_sequence) || typeof input.dispatched !== 'boolean') {
153+
throw new Error('original_turn_unavailable');
154+
}
155+
return {
156+
operationId: input.operation_id, workerSequence: input.worker_sequence, dispatched: input.dispatched,
157+
...(typeof input.text === 'string' ? { text: input.text } : {}),
158+
...(typeof input.answer === 'string' ? { answer: input.answer } : {}),
159+
};
160+
};
161+
if (Array.isArray(payload.controller_inputs) && typeof payload.controller_input_has_capacity === 'boolean') {
162+
projected.inputs = payload.controller_inputs.map(readInput);
163+
projected.inputHasCapacity = payload.controller_input_has_capacity;
164+
}
165+
if (payload.controller_input) projected.input = readInput(payload.controller_input);
166+
resolve(projected);
167+
} catch {
168+
reject(new Error('original_turn_unavailable'));
169+
}
170+
});
171+
}).catch(async (error: unknown) => {
172+
if (!subject && await controllerReadbackUnsupported(cli)) return null;
173+
throw error;
174+
});
175+
}
176+
30177
export function cliFromEnv(env: NodeJS.ProcessEnv = process.env): LoopxCli {
31178
const command = (env.LOOCHAT_LOOPX_CMD || 'loopx').split(/\s+/).filter(Boolean);
32179
return { command, ...(env.LOOCHAT_LOOPX_CWD ? { cwd: env.LOOCHAT_LOOPX_CWD } : {}), ...(env.LOOCHAT_LOOPX_REGISTRY ? { registry: env.LOOCHAT_LOOPX_REGISTRY } : {}) };

‎apps/workbench/packages/daemon/src/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ async function main(): Promise<void> {
136136
}));
137137
// The session list scans once here and then only when a request finds it stale; the meter keeps
138138
// its own timer, files only. Stopped in shutdown with everything else.
139-
// LoopX Goal conversations: bindings, the core client and the Goal context; ordinary threads never touch it.
139+
// LoopX Goal conversations: bindings, original Controller admission and Goal context.
140140
const loopx = new LoopxService({ dataDir: config.dataDir, adapters, dirs });
141141
loopx.attach(manager);
142142
manager.loopx = loopx;

‎apps/workbench/packages/daemon/src/threads.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3008,6 +3008,7 @@ export class ThreadManager {
30083008
if (alreadyQueued?.error) throw new HttpError(409, alreadyQueued.error);
30093009
if (alreadyQueued) return { queued: true, id: alreadyQueued.id };
30103010
const thread = this.getThread(threadId);
3011+
if (this.loopx) await this.loopx.requireOrdinaryTurn(thread);
30113012
if (this.changingModes.has(threadId)) throw new HttpError(409, '模式正在切换,请稍后发送');
30123013
if (input.workMode !== undefined) thread.workMode = this.validateWorkMode(thread.agent, input.workMode);
30133014
const originalText = typeof input.text === 'string' ? input.text.trim() : '';

0 commit comments

Comments
 (0)