feat(studio): add AI workspace with Codex ACP integration
Test / Tests and coverage
Intrepid/Prometeu/Studio/pipeline/head This commit looks good

This commit is contained in:
2026-11-23 03:11:33 +00:00
parent a2b6a81a27
commit ae7d01aa99
36 changed files with 2550 additions and 28 deletions
@@ -184,6 +184,11 @@ public class StudioApplicationConfiguration {
return new p.studio.core.project.preferences.JsonRuntimeSettingsStore(
Path.of(System.getProperty("user.home"), ".prometeu-studio", "runtime-settings.json"), mapper);
}
@Bean
p.studio.api.preferences.AgentSettingsStore agentSettingsStore(ObjectMapper mapper) {
return new p.studio.core.project.preferences.JsonAgentSettingsStore(
Path.of(System.getProperty("user.home"),".prometeu-studio","ai-settings.json"),mapper);
}
@Bean
ProjectActivityHistoryStore projectActivityHistoryStore(ObjectMapper mapper) {
@@ -332,7 +337,7 @@ public class StudioApplicationConfiguration {
ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide,
p.studio.api.assets.animation.AnimationService animationService,ObjectMapper mapper,OperationExecutor operations,
p.studio.core.project.ProjectAccessRegistry access,ProjectLocalStudioSetupStore setupStore,
p.studio.api.preferences.RuntimeSettingsStore runtimeSettings) {
p.studio.api.preferences.RuntimeSettingsStore runtimeSettings,p.studio.api.preferences.AgentSettingsStore agentSettings) {
var factory = new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper,
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
@@ -341,6 +346,8 @@ public class StudioApplicationConfiguration {
activityHistoryStore, connectionGuide);
factory.setAnimationService(animationService);
factory.setRuntimeSettings(runtimeSettings);
factory.setAgentSettings(agentSettings);
factory.setAgentConnections(root->new p.studio.app.acp.CodexAcpConnection(root,mapper));
factory.enableInteractive(new p.studio.core.execution.DefaultExecutionControllerFactory(shipper,
new p.studio.app.runtime.studio.StudioRuntimeGateway(mapper),operations,access),
(project,setup)->{try(var lease=access.enterManual(project.rootPath())){setupStore.save(project,setup);}});
@@ -36,6 +36,11 @@ public final class StudioUiFactory {
private p.studio.ui.javafx2.window.WindowResources interactiveResources;
private p.studio.api.preferences.RuntimeSettingsStore runtimeSettings;
private String initialRuntime;
private p.studio.api.preferences.AgentSettingsStore agentSettings;
private p.studio.api.ai.AcpSettings initialAgent;
public void setAgentSettings(p.studio.api.preferences.AgentSettingsStore settings){agentSettings=Objects.requireNonNull(settings);}
private p.studio.api.ai.AgentConnectionFactory agentConnections;
public void setAgentConnections(p.studio.api.ai.AgentConnectionFactory factory){agentConnections=Objects.requireNonNull(factory);}
public void setRuntimeSettings(p.studio.api.preferences.RuntimeSettingsStore settings) { runtimeSettings=Objects.requireNonNull(settings); }
public void enableInteractive(ExecutionControllerFactory factory,
java.util.function.BiConsumer<p.studio.api.project.ProjectReference,p.studio.api.project.ProjectLocalStudioSetup> saver) {
@@ -44,11 +49,15 @@ public final class StudioUiFactory {
public void prepareInteractive(){
interactiveResources=new p.studio.ui.javafx2.window.WindowResources();
initialRuntime=Objects.requireNonNull(runtimeSettings,"runtimeSettings").load();
initialAgent=Objects.requireNonNull(agentSettings,"agentSettings").load();
}
public p.studio.ui.javafx2.window.StudioWindowCoordinator2 createInteractive(Stage stage){
if(interactiveResources==null)throw new IllegalStateException("Interactive resources were not initialized");
return new p.studio.ui.javafx2.window.StudioWindowCoordinator2(stage,projectCatalog,knownProjects,projectSessionFactory,
var coordinator=new p.studio.ui.javafx2.window.StudioWindowCoordinator2(stage,projectCatalog,knownProjects,projectSessionFactory,
Objects.requireNonNull(interactiveExecutions),setupSaver,executor,interactiveResources,languageCatalog,windowStateStore,runtimeSettings,initialRuntime);
if(agentConnections!=null)coordinator.setAgentConnections(agentConnections);
coordinator.setAgentSettings(agentSettings,initialAgent);
return coordinator;
}
private final ProjectCatalog projectCatalog;
private final KnownProjects knownProjects;
@@ -0,0 +1,261 @@
package p.studio.app.acp;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.ObjectNode;
import p.studio.api.ai.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.*;
/** ACP v1 line transport. Owns only its launched process tree, never the caller's Codex process. */
public final class CodexAcpConnection implements AgentConnection {
private final Path root;
private final ObjectMapper json;
private final ExecutorService workers = Executors.newVirtualThreadPerTaskExecutor();
private final ExecutorService writer = Executors.newSingleThreadExecutor(Thread.ofVirtual().name("studio-acp-writer").factory());
private final Map<String, CompletableFuture<JsonNode>> pending = new ConcurrentHashMap<>();
private final Set<String> sessions = ConcurrentHashMap.newKeySet();
private final Set<String> cancelling = ConcurrentHashMap.newKeySet();
private final Map<String, CompletableFuture<String>> turns = new ConcurrentHashMap<>();
private final Map<String, CompletableFuture<Void>> accepted = new ConcurrentHashMap<>();
private final Map<String, ObjectNode> permissionRequests = new ConcurrentHashMap<>();
private final CopyOnWriteArrayList<Consumer<Status>> observers = new CopyOnWriteArrayList<>();
private final AtomicLong sequence = new AtomicLong();
private final Object outputLock = new Object();
private final Object terminationLock = new Object();
private volatile Status status = new Status(State.DISCONNECTED, "");
private volatile Process process;
private volatile Writer output;
private volatile Consumer<Event> events = e -> {};
private volatile Function<Permission, CompletionStage<String>> permissions = p -> CompletableFuture.completedFuture(null);
private volatile boolean closing;
private volatile boolean chatGptLogin;
private volatile CompletableFuture<Void> shutdown;
private volatile long connectionEpoch;
private final Set<ProcessHandle> ownedProcesses = ConcurrentHashMap.newKeySet();
public CodexAcpConnection(Path root, ObjectMapper mapper) { this.root=root.toAbsolutePath().normalize();json=mapper.copy(); }
public boolean available(){return true;}
public Status status(){return status;}
public AutoCloseable observe(Consumer<Status> listener){observers.add(listener);listener.accept(status);return ()->observers.remove(listener);}
public void events(Consumer<Event> listener){events=Objects.requireNonNull(listener);}
public void permissions(Function<Permission,CompletionStage<String>> handler){permissions=Objects.requireNonNull(handler);}
private void state(State value,String detail){status=new Status(value,detail);for(var l:observers)try{l.accept(status);}catch(RuntimeException ignored){}}
private static String message(Throwable failure){
while((failure instanceof CompletionException||failure instanceof ExecutionException)&&failure.getCause()!=null)failure=failure.getCause();
String text=Objects.toString(failure.getMessage(),failure.getClass().getSimpleName());
text = message(text);
return text.substring(0,Math.min(text.length(),1000));
}
public synchronized CompletionStage<Void> connect(AcpSettings settings){
if(closing)return CompletableFuture.failedFuture(new IllegalStateException("Agent connection is closed"));
if(status.state()!=State.DISCONNECTED&&status.state()!=State.FAILED)
return CompletableFuture.failedFuture(new IllegalStateException("Agent is already connected"));
state(State.CONNECTING,"");
long epoch=++connectionEpoch;
return CompletableFuture.runAsync(()->{
var owned=new java.util.concurrent.atomic.AtomicReference<Process>();
try{
terminate();
var command=new ArrayList<String>();command.add(settings.executable());command.addAll(settings.arguments());
var builder=new ProcessBuilder(command).directory(root.toFile());
builder.environment().remove("OPENAI_API_KEY");builder.environment().remove("CODEX_API_KEY");
builder.environment().put("INITIAL_AGENT_MODE","workspace-write");
synchronized(this){if(closing)throw new IOException("Connection closed");process=builder.start();output=new OutputStreamWriter(process.getOutputStream(),StandardCharsets.UTF_8);}
Process launched=process;
owned.set(launched);
ownedProcesses.add(launched.toHandle());
workers.submit(()->track(launched));
workers.submit(()->read(launched,epoch));workers.submit(()->{try(var stderr=launched.getErrorStream()){stderr.transferTo(OutputStream.nullOutputStream());}catch(IOException ignored){}});
var result=request("initialize",json.createObjectNode().put("protocolVersion",1)
.set("clientInfo",json.createObjectNode().put("name","prometeu-studio").put("version","1")),20).join();
if(result.path("protocolVersion").asInt()!=1)throw new IOException("Incompatible ACP protocol");
chatGptLogin=false;
for(var method:result.path("authMethods"))if(method.path("id").asText().equals("chat-gpt"))chatGptLogin=true;
if(!chatGptLogin)throw new IOException("Agent does not offer ChatGPT authentication");
if(!closing){state(State.CONNECTED,"");queryAuth().join();}
}catch(Throwable failure){
terminate(owned.get());fail(epoch,failure);throw new CompletionException(failure);
}
},workers);
}
private CompletableFuture<JsonNode> queryAuth(){
return request("auth/status",json.createObjectNode(),10).thenApply(value->{auth(value);return value;});
}
private void auth(JsonNode value){
if(closing||status.state()==State.CONNECTING)return;
boolean ready=false;
if(value.path("state").asText().equals("authenticated"))
for(var account:value.path("accounts"))if(account.path("active").asBoolean(true)&&account.path("label").asText().toLowerCase(Locale.ROOT).contains("chatgpt"))ready=true;
state(ready?State.READY:State.CONNECTED,"");
}
public CompletionStage<Void> login(){
if(!chatGptLogin||closing)return CompletableFuture.failedFuture(new IllegalStateException("Connect the ChatGPT-capable agent first"));
state(State.AUTHENTICATING,"");
return request("authenticate",json.createObjectNode().put("methodId","chat-gpt"),180)
.thenCompose(v->queryAuth()).thenAccept(v->{})
.whenComplete((v,f)->{if(f!=null&&!closing&&status.state()!=State.FAILED)state(State.CONNECTED,message(f));});
}
public CompletionStage<String> newSession(){
if(status.state()!=State.READY)return CompletableFuture.failedFuture(new IllegalStateException("Sign in with ChatGPT first"));
ObjectNode params=json.createObjectNode().put("cwd",root.toString());params.putArray("mcpServers");
return request("session/new",params,30).thenCompose(result->{
String id=result.path("sessionId").asText();
if(id.isBlank())return CompletableFuture.failedFuture(new IllegalStateException("Agent returned no session ID"));
boolean mode=false;for(var m:result.path("modes").path("availableModes"))if(m.path("id").asText().equals("workspace-write"))mode=true;
if(!mode)return CompletableFuture.failedFuture(new IllegalStateException("Agent does not offer workspace-write mode"));
return request("session/set_mode",json.createObjectNode().put("sessionId",id).put("modeId","workspace-write"),10)
.thenApply(v->{sessions.add(id);return id;});
});
}
public synchronized Turn prompt(String id,String text){
var acknowledgement=new CompletableFuture<Void>();var done=new CompletableFuture<String>();
if(status.state()!=State.READY||!sessions.contains(id)||!turns.isEmpty()||text.isBlank()){
var failure=new IllegalStateException("Agent is not ready or another request is running");
acknowledgement.completeExceptionally(failure);done.completeExceptionally(failure);return new Turn(acknowledgement,done);
}
cancelling.remove(id);turns.put(id,done);accepted.put(id,acknowledgement);
var params=json.createObjectNode().put("sessionId",id);params.putArray("prompt").addObject().put("type","text").put("text",text);
request("session/prompt",params,1800).whenComplete((result,failure)->{
turns.remove(id);accepted.remove(id);cancelling.remove(id);cancelPermissions(id);
if(failure==null){acknowledgement.complete(null);done.complete(result.path("stopReason").asText("end_turn"));}
else{
if(failure instanceof TimeoutException)state(State.FAILED,"Agent request timed out");
acknowledgement.completeExceptionally(failure);done.completeExceptionally(failure);
if(failure instanceof TimeoutException){Process owned=process;workers.submit(()->{terminate(owned);fail(failure);});}
}
});
return new Turn(acknowledgement,done);
}
public CompletionStage<Void> cancel(String id){
var turn=turns.get(id);if(turn==null)return CompletableFuture.completedFuture(null);
cancelling.add(id);cancelPermissions(id);
notify("session/cancel",json.createObjectNode().put("sessionId",id));
return turn.handle((v,f)->(Void)null).toCompletableFuture().orTimeout(10,TimeUnit.SECONDS)
.exceptionallyCompose(failure->CompletableFuture.runAsync(()->{
terminate();fail(new IOException("Cancellation timed out; agent disconnected"));
},workers));
}
private CompletableFuture<JsonNode> request(String method,ObjectNode params,int seconds){
String id=Long.toString(sequence.incrementAndGet());var result=new CompletableFuture<JsonNode>();
if(closing){result.completeExceptionally(new IOException("Connection closed"));return result;}
pending.put(id,result);
send(json.createObjectNode().put("jsonrpc","2.0").put("id",id).put("method",method).set("params",params))
.whenComplete((v,f)->{if(f!=null)result.completeExceptionally(f);});
result.orTimeout(seconds,TimeUnit.SECONDS).whenComplete((v,f)->pending.remove(id));return result;
}
private void notify(String method,ObjectNode params){send(json.createObjectNode().put("jsonrpc","2.0").put("method",method).set("params",params));}
private CompletableFuture<Void> send(JsonNode frame){
Writer destination=output;
try{return CompletableFuture.runAsync(()->{try{write(frame,destination);}catch(IOException failure){throw new CompletionException(failure);}},writer);}
catch(RejectedExecutionException failure){return CompletableFuture.failedFuture(failure);}
}
private void write(JsonNode message,Writer destination)throws IOException{
synchronized(outputLock){if(destination==null||output!=destination)throw new IOException("ACP is disconnected");destination.write(json.writeValueAsString(message));destination.write('\n');destination.flush();}
}
private void read(Process launched,long epoch){
try(var input=new BufferedReader(new InputStreamReader(launched.getInputStream(),StandardCharsets.UTF_8))){
StringBuilder line=new StringBuilder();int c;
while((c=input.read())!=-1){
if(c=='\n'){if(!line.isEmpty()&&process==launched)receive(json.readTree(line.toString()));line.setLength(0);}
else if(c!='\r'){if(line.length()>=4*1024*1024)throw new IOException("ACP frame exceeds limit");line.append((char)c);}
}
if(!closing&&process==launched){fail(epoch,new IOException("ACP process disconnected"));workers.submit(()->terminate(launched));}
}catch(Throwable failure){if(!closing&&process==launched){fail(epoch,failure);workers.submit(()->terminate(launched));}}
}
private void receive(JsonNode message)throws IOException{
if(message.has("method")){
String method=message.path("method").asText();var params=message.path("params");
if(method.equals("session/update"))update(params);
else if(method.equals("auth/status_update"))auth(params);
else if(method.equals("session/request_permission")&&message.has("id"))permission(message);
else if(message.has("id"))send(json.createObjectNode().put("jsonrpc","2.0").<ObjectNode>set("id",message.get("id"))
.set("error",json.createObjectNode().put("code",-32601).put("message","Unsupported client method")));
}else if(message.has("id")){
var response=pending.get(message.path("id").asText());
if(response!=null){
if(message.has("error"))response.completeExceptionally(new IOException(message(message.path("error").path("message").asText("ACP error"))));
else if(message.has("result"))response.complete(message.path("result"));
else response.completeExceptionally(new IOException("Invalid ACP response: result is missing"));
}
}
}
private static String message(String value){return value.replaceAll("(?i)(sk-[A-Za-z0-9_-]+|Bearer\\s+\\S+)","[redacted]");}
private void update(JsonNode params){
String id=params.path("sessionId").asText();if(!sessions.contains(id))return;
var update=params.path("update");String type=update.path("sessionUpdate").asText();
Event event=null;
if(type.equals("agent_message_chunk")&&update.path("content").path("type").asText().equals("text"))
event=new Event(id,Kind.TEXT,update.path("content").path("text").asText());
else if(type.equals("tool_call")||type.equals("tool_call_update"))
event=new Event(id,Kind.ACTIVITY,update.path("title").asText(update.path("status").asText("Tool activity")));
else if(type.equals("agent_thought_chunk"))event=new Event(id,Kind.ACTIVITY,"Working");
if(event!=null){var acknowledgement=accepted.get(id);if(acknowledgement!=null)acknowledgement.complete(null);events.accept(event);}
}
private void permission(JsonNode message){
var params=message.path("params");String session=params.path("sessionId").asText();String key=message.path("id").toString();
var choices=new ArrayList<Choice>();for(var o:params.path("options"))choices.add(new Choice(o.path("optionId").asText(),o.path("name").asText(),o.path("kind").asText()));
ObjectNode request=json.createObjectNode().set("id",message.get("id"));request.put("sessionId",session);permissionRequests.put(key,request);
if(!turns.containsKey(session)||cancelling.contains(session)||closing){replyPermission(key,null);return;}
String details=params.path("toolCall").toPrettyString();
if(details.length()>16_000)details=details.substring(0,16_000)+"\n…";
try{permissions.apply(new Permission(session,params.path("toolCall").path("title").asText("Agent action"),details,List.copyOf(choices)))
.whenComplete((choice,failure)->replyPermission(key,failure==null&&choices.stream().anyMatch(c->c.id().equals(choice))?choice:null));}
catch(RuntimeException failure){replyPermission(key,null);}
}
private void replyPermission(String key,String choice){
var request=permissionRequests.remove(key);if(request==null)return;
var outcome=json.createObjectNode().put("outcome",choice==null?"cancelled":"selected");if(choice!=null)outcome.put("optionId",choice);
send(json.createObjectNode().put("jsonrpc","2.0").<ObjectNode>set("id",request.get("id"))
.set("result",json.createObjectNode().set("outcome",outcome)));
}
private void cancelPermissions(String id){for(var e:permissionRequests.entrySet())if(e.getValue().path("sessionId").asText().equals(id))replyPermission(e.getKey(),null);}
private void fail(Throwable failure){
fail(connectionEpoch,failure);
}
private synchronized void fail(long epoch,Throwable failure){
if(epoch!=connectionEpoch)return;
sessions.clear();
var requests=List.copyOf(pending.values());
if(!closing)state(State.FAILED,message(failure));
for(var f:requests)f.completeExceptionally(failure);
}
public synchronized CompletionStage<Void> closeAsync(){
if(shutdown!=null)return shutdown;
var stopping=new ArrayList<CompletableFuture<Void>>();for(String id:turns.keySet())stopping.add(cancel(id).toCompletableFuture().exceptionally(f->null));
closing=true;state(State.CLOSING,"");
shutdown=CompletableFuture.runAsync(()->{
try{CompletableFuture.allOf(stopping.toArray(CompletableFuture[]::new)).get(11,TimeUnit.SECONDS);}catch(Exception ignored){}
try{terminate();fail(new IOException("Connection closed"));state(State.CLOSED,"");writer.shutdownNow();workers.shutdown();}
catch(RuntimeException failure){state(State.FAILED,message(failure));synchronized(this){shutdown=null;}throw failure;}
},workers);
return shutdown;
}
private void track(Process launched){
while(launched==process&&launched.isAlive()){
launched.descendants().forEach(ownedProcesses::add);
try{Thread.sleep(100);}catch(InterruptedException e){Thread.currentThread().interrupt();return;}
}
}
private void terminate(){terminate(process);}
private void terminate(Process owned){synchronized(terminationLock){
if(owned==null||owned!=process)return;
owned.descendants().forEach(ownedProcesses::add);
var tree=ownedProcesses.stream().filter(p->p.pid()!=owned.pid()).toList();
tree.forEach(ProcessHandle::destroy);owned.toHandle().destroy();
try{if(!owned.waitFor(2,TimeUnit.SECONDS))owned.toHandle().destroyForcibly();}catch(InterruptedException e){Thread.currentThread().interrupt();owned.toHandle().destroyForcibly();}
tree.stream().filter(ProcessHandle::isAlive).forEach(ProcessHandle::destroyForcibly);
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(3);
try{owned.waitFor(3,TimeUnit.SECONDS);for(var child:tree)if(child.isAlive())child.onExit().get(Math.max(1,deadline-System.nanoTime()),TimeUnit.NANOSECONDS);}
catch(Exception e){throw new CompletionException(e);}
if(owned.isAlive()||tree.stream().anyMatch(ProcessHandle::isAlive))throw new IllegalStateException("Agent process did not terminate");
process=null;output=null;ownedProcesses.clear();
}}
}