feat(studio): coordinate integrated AI activity and internal language services
Start project-owned language and authenticated MCP services when opening a project, reusing the embedded LSP backend without a desktop TCP listener. Keep editor overlays separate from saved-file MCP queries. Reserve conflicting editing before ACP prompt delivery and retain protection through native/tool termination, runtime cleanup and document refresh. Preserve drafts on rejected admission, provide cleanup/preparation recovery, distinguish terminal outcomes and redact permission previews. Add lifecycle, language parity, activity, composition and UI regressions and update the canonical Studio contracts. Keep distribution update alignment as the separate WRK-002A follow-up. Validation: complete make -C tooling verify PASSED in 20261127T035822Z-ec5d9266 (1172 unit, 131 compiler fixture, 31 headless tests). Opt-in real-model and native AI-view qualification are outside that gate. Work: WRK-0029; decision: DEC-0001.
This commit is contained in:
@@ -43,11 +43,8 @@ import p.studio.core.project.ProjectLocalStudioStateStore;
|
||||
import p.studio.api.project.ProjectWorkspaceInitializer;
|
||||
import p.studio.core.project.PackerProjectWorkspaceInitializer;
|
||||
import p.studio.api.session.ProjectSessionFactory;
|
||||
import p.studio.app.lsp.LspLifecycleAdapter;
|
||||
import p.studio.core.session.DefaultProjectSessionFactory;
|
||||
import p.studio.core.session.LspLifecyclePort;
|
||||
import p.studio.lsp.api.LspServerLifecycle;
|
||||
import p.studio.lsp.services.LspServerLifecycleImpl;
|
||||
import p.studio.ui.javafx.events.StudioEventBus;
|
||||
import p.studio.ui.javafx.utilities.ThemeService;
|
||||
import p.studio.ui.javafx.utilities.i18n.I18nService;
|
||||
@@ -258,13 +255,10 @@ public class StudioApplicationConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
LspServerLifecycle lspServerLifecycle(p.animation.GlyphBankLayoutSource layouts,StudioEventBus events) {
|
||||
return new LspServerLifecycleImpl(layouts,(root,uuid,pointer)->events.publish(new p.studio.ui.javafx.events.StudioAnimationOriginRequestedEvent(root,uuid,pointer)));
|
||||
}
|
||||
|
||||
@Bean
|
||||
LspLifecyclePort lspLifecyclePort(LspServerLifecycle lifecycle) {
|
||||
return new LspLifecycleAdapter(lifecycle);
|
||||
p.studio.app.lsp.InProcessLanguageWorkspace projectLanguageWorkspace(p.animation.GlyphBankLayoutSource layouts,StudioEventBus events,
|
||||
ProjectCatalog catalog,p.studio.api.automation.ProjectKnowledge knowledge,ObjectMapper mapper) {
|
||||
return new p.studio.app.lsp.InProcessLanguageWorkspace(layouts,
|
||||
(root,uuid,pointer)->events.publish(new p.studio.ui.javafx.events.StudioAnimationOriginRequestedEvent(root,uuid,pointer)),catalog,knowledge,mapper);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -337,7 +331,8 @@ 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.AgentSettingsStore agentSettings) {
|
||||
p.studio.api.preferences.RuntimeSettingsStore runtimeSettings,p.studio.api.preferences.AgentSettingsStore agentSettings,
|
||||
p.studio.api.automation.AgentIntegrationPreparation preparation) {
|
||||
var factory = new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
|
||||
executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper,
|
||||
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
|
||||
@@ -347,7 +342,12 @@ public class StudioApplicationConfiguration {
|
||||
factory.setAnimationService(animationService);
|
||||
factory.setRuntimeSettings(runtimeSettings);
|
||||
factory.setAgentSettings(agentSettings);
|
||||
factory.setAgentConnections(root->new p.studio.app.acp.CodexAcpConnection(root,mapper));
|
||||
factory.setAgentConnections(root->new p.studio.core.session.ProjectAgentConnection(
|
||||
new p.studio.app.acp.CodexAcpConnection(root,mapper),access.requireAutomation(root),
|
||||
()->setupStore.load(projectCatalog.openProject(root)).agentIntegration().enabled()?preparation.status(root):
|
||||
new p.studio.api.automation.AgentIntegrationPreparation.Result(false,"Project assistant integration is disabled"),
|
||||
()->setupStore.load(projectCatalog.openProject(root)).agentIntegration().enabled()?preparation.prepare(root):
|
||||
new p.studio.api.automation.AgentIntegrationPreparation.Result(false,"Project assistant integration is disabled"),studioExecutor));
|
||||
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);}});
|
||||
@@ -366,9 +366,8 @@ public class StudioApplicationConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
p.studio.core.language.LanguageQueryPort automationLanguagePort(LspServerLifecycle lifecycle, ProjectCatalog catalog,
|
||||
p.studio.api.automation.ProjectKnowledge knowledge, ObjectMapper mapper) {
|
||||
return new p.studio.app.lsp.AutomationLspQueries(lifecycle, catalog, knowledge, mapper);
|
||||
p.studio.core.language.LanguageQueryPort automationLanguagePort(p.studio.app.lsp.InProcessLanguageWorkspace workspace) {
|
||||
return workspace.savedQueries();
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
@@ -80,7 +80,9 @@ public final class CodexAcpConnection implements AgentConnection {
|
||||
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);
|
||||
fail(epoch,failure);
|
||||
try{terminate(owned.get());}catch(Throwable cleanup){failure.addSuppressed(cleanup);}
|
||||
throw new CompletionException(failure);
|
||||
}
|
||||
},workers);
|
||||
}
|
||||
@@ -124,7 +126,7 @@ public final class CodexAcpConnection implements AgentConnection {
|
||||
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"));}
|
||||
if(failure==null){acknowledgement.complete(null);done.complete(result.path("stopReason").asText("unknown"));}
|
||||
else{
|
||||
if(failure instanceof TimeoutException)state(State.FAILED,"Agent request timed out");
|
||||
acknowledgement.completeExceptionally(failure);done.completeExceptionally(failure);
|
||||
@@ -231,9 +233,9 @@ public final class CodexAcpConnection implements AgentConnection {
|
||||
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();
|
||||
String details=message(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)))
|
||||
try{permissions.apply(new Permission(session,boundedToolText(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);}
|
||||
}
|
||||
@@ -254,6 +256,7 @@ public final class CodexAcpConnection implements AgentConnection {
|
||||
if(!closing)state(State.FAILED,message(failure));
|
||||
for(var f:requests)f.completeExceptionally(failure);
|
||||
}
|
||||
@Override public CompletionStage<Void> awaitQuiescence(){return CompletableFuture.runAsync(this::terminate,workers);}
|
||||
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));
|
||||
@@ -274,7 +277,8 @@ public final class CodexAcpConnection implements AgentConnection {
|
||||
private void terminate(){terminate(process);}
|
||||
private void terminate(Process owned){synchronized(terminationLock){
|
||||
if(owned==null||owned!=process)return;
|
||||
owned.descendants().forEach(ownedProcesses::add);
|
||||
RuntimeException discoveryFailure=null;
|
||||
try{owned.descendants().forEach(ownedProcesses::add);}catch(RuntimeException denied){discoveryFailure=denied;}
|
||||
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();}
|
||||
@@ -283,6 +287,7 @@ public final class CodexAcpConnection implements AgentConnection {
|
||||
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");
|
||||
if(discoveryFailure!=null)throw new IllegalStateException("Agent parent stopped; descendant cleanup could not be verified",discoveryFailure);
|
||||
process=null;output=null;ownedProcesses.clear();
|
||||
}}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.eclipse.lsp4j.*;
|
||||
import org.eclipse.lsp4j.jsonrpc.json.MessageJsonHandler;
|
||||
import org.eclipse.lsp4j.jsonrpc.messages.Either;
|
||||
import org.eclipse.lsp4j.launch.LSPLauncher;
|
||||
import org.eclipse.lsp4j.services.*;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.project.ProjectCatalog;
|
||||
@@ -20,9 +19,10 @@ import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/** A real client of the already-running project LSP. Each query owns and closes its connection. */
|
||||
/** Reuses the project language protocol internally, with a standalone TCP compatibility adapter. */
|
||||
public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
private final LspServerLifecycle lifecycle;
|
||||
private final InProcessLanguageWorkspace internal;
|
||||
private final ProjectCatalog projects;
|
||||
private final ProjectKnowledge knowledge;
|
||||
private final ObjectMapper mapper;
|
||||
@@ -34,7 +34,18 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
private static final Set<String> EDITS = Set.of("completion", "prepareRename", "rename", "codeActions", "formatting");
|
||||
|
||||
public AutomationLspQueries(LspServerLifecycle lifecycle, ProjectCatalog projects, ProjectKnowledge knowledge, ObjectMapper mapper) {
|
||||
this.lifecycle = lifecycle; this.projects = projects; this.knowledge = knowledge; this.mapper = mapper;
|
||||
this.lifecycle = lifecycle; this.internal=null; this.projects = projects; this.knowledge = knowledge; this.mapper = mapper;
|
||||
}
|
||||
|
||||
public AutomationLspQueries(InProcessLanguageWorkspace internal, ProjectCatalog projects, ProjectKnowledge knowledge, ObjectMapper mapper) {
|
||||
this.lifecycle=null; this.internal=internal; this.projects=projects; this.knowledge=knowledge; this.mapper=mapper;
|
||||
}
|
||||
|
||||
Map<String,Object> queryEditor(TaskIdentity editor, p.studio.api.session.ProjectLanguageService.Request request,Map<Path,String> overlays) throws Exception {
|
||||
var parameters=new LinkedHashMap<>(request.parameters());
|
||||
if(request.document()!=null)parameters.put("uri",request.document().uri());
|
||||
var execution=new LanguageQueryExecution(request.operation(),10_000,2_000);
|
||||
return performQuery(editor,request.operation(),parameters,execution,request.document(),overlays);
|
||||
}
|
||||
|
||||
private record ExternalTask(String consumer, p.studio.lsp.messages.LspServerEndpoint endpoint,
|
||||
@@ -45,6 +56,7 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
items.remove(task);
|
||||
final var state = externalTasks.get(task);
|
||||
if (state == null) return;
|
||||
if(internal!=null){internal.endTask(task,state.consumer());externalTasks.remove(task,state);return;}
|
||||
final var workers = Executors.newCachedThreadPool();
|
||||
try (var socket = new Socket()) {
|
||||
socket.connect(new InetSocketAddress(state.endpoint().host(), state.endpoint().port()), 2000);
|
||||
@@ -88,7 +100,7 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
@Override public Map<String, Object> query(TaskIdentity task, String operation, Map<String, Object> parameters,
|
||||
LanguageQueryExecution execution) throws Exception {
|
||||
try {
|
||||
var result = performQuery(task, operation, parameters, execution);
|
||||
var result = performQuery(task, operation, parameters, execution, null,Map.of());
|
||||
if (execution.hasFailure()) throw execution.exception(AutomationFailure.Code.LANGUAGE_QUERY_CLEANUP_FAILED, "Language query cleanup failed", true);
|
||||
return result;
|
||||
} catch (IllegalArgumentException | ControlDeniedException failure) { throw failure; }
|
||||
@@ -99,7 +111,7 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
}
|
||||
|
||||
private Map<String, Object> performQuery(TaskIdentity task, String operation, Map<String, Object> parameters,
|
||||
LanguageQueryExecution execution) throws Exception {
|
||||
LanguageQueryExecution execution, p.studio.api.session.ProjectLanguageService.Document overlay,Map<Path,String> overlays) throws Exception {
|
||||
if (!OPERATIONS.contains(operation)) throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, "Unsupported language operation: " + operation);
|
||||
var context = knowledge.context(task.projectRoot());
|
||||
var primary = context.languages().stream().filter(ProjectKnowledge.Language::primary).findFirst().orElseThrow();
|
||||
@@ -107,7 +119,8 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
throw failure(AutomationFailure.Code.UNSUPPORTED_LANGUAGE, "Project language has no available LSP");
|
||||
var project = projects.openProject(context.projectRoot());
|
||||
var binding = LspLifecycleAdapter.context(project);
|
||||
var endpoint = lifecycle.endpoint(binding).orElseThrow(() -> failure(AutomationFailure.Code.LANGUAGE_SERVER_UNAVAILABLE, "Project LSP is not running; reopen the project if its language changed"));
|
||||
var endpoint = internal==null?lifecycle.endpoint(binding).orElseThrow(() -> failure(AutomationFailure.Code.LANGUAGE_SERVER_UNAVAILABLE, "Project LSP is not running; reopen the project if its language changed")):null;
|
||||
if(internal!=null&&!internal.available(binding))throw failure(AutomationFailure.Code.LANGUAGE_SERVER_UNAVAILABLE,"Project language service is not running");
|
||||
var params = mapper.valueToTree(parameters);
|
||||
CallHierarchyItem item = null;
|
||||
String uri = null;
|
||||
@@ -137,15 +150,15 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
source = java.nio.charset.StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString();
|
||||
}
|
||||
uri = document.toUri().toString();
|
||||
if(overlay!=null){
|
||||
if(overlay.text().getBytes(java.nio.charset.StandardCharsets.UTF_8).length>4*1024*1024)
|
||||
throw failure(AutomationFailure.Code.LIMIT_EXCEEDED,"Editor source exceeds 4 MiB");
|
||||
source=overlay.text();
|
||||
}
|
||||
}
|
||||
int documentVersion=overlay==null?1:overlay.version();
|
||||
long deadline = execution.deadlineNanos();
|
||||
if (System.nanoTime() >= deadline) throw new TimeoutException("Language query admission budget expired");
|
||||
var workers = Executors.newCachedThreadPool(r -> { var thread = new Thread(r, "studio-automation-lsp"); thread.setDaemon(true); return thread; });
|
||||
try (var socket = new Socket()) {
|
||||
execution.own(() -> { try { socket.close(); } catch (java.io.IOException ignored) {} });
|
||||
execution.own(workers::shutdownNow);
|
||||
if (!InetAddress.getByName(endpoint.host()).isLoopbackAddress()) throw failure(AutomationFailure.Code.LANGUAGE_SERVER_UNAVAILABLE, "Project LSP endpoint is not local");
|
||||
socket.connect(new InetSocketAddress(endpoint.host(), endpoint.port()), (int)Math.max(1, Math.min(2000, TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()))));
|
||||
var diagnostics = new CompletableFuture<List<Diagnostic>>();
|
||||
String expectedUri = uri;
|
||||
LanguageClient client = new LanguageClient() {
|
||||
@@ -158,12 +171,8 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
return CompletableFuture.completedFuture(new ApplyWorkspaceEditResponse(false));
|
||||
}
|
||||
};
|
||||
var launcher = new Launcher.Builder<ExternalSourceLanguageServer>().setLocalService(client)
|
||||
.setRemoteInterface(ExternalSourceLanguageServer.class).setInput(socket.getInputStream())
|
||||
.setOutput(socket.getOutputStream()).setExecutorService(workers).create();
|
||||
var listening = launcher.startListening();
|
||||
execution.own(() -> listening.cancel(true));
|
||||
final var server = launcher.getRemoteProxy();
|
||||
try(var connection=connect(binding,endpoint,client,execution,overlays)) {
|
||||
final var server=connection.server;
|
||||
final var acquired = new HashSet<String>();
|
||||
boolean succeeded = false;
|
||||
try {
|
||||
@@ -193,11 +202,11 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
String digest = source == null ? null : sha256(source);
|
||||
if (document != null) {
|
||||
// Fresh client overlay contains exactly the saved UTF-8 file. Wait for analysis before querying.
|
||||
server.getTextDocumentService().didOpen(new DidOpenTextDocumentParams(new TextDocumentItem(uri, primary.id(), 1, source)));
|
||||
server.getTextDocumentService().didOpen(new DidOpenTextDocumentParams(new TextDocumentItem(uri, primary.id(), documentVersion, source)));
|
||||
if (richAnalysis) {
|
||||
execution.method("prometeu/documentAnalysis");
|
||||
var retained = await(server.documentAnalysis(new ExternalSourceLanguageServer.DiagnosticAnalysisRequest(
|
||||
new VersionedTextDocumentIdentifier(uri, 1), digest)), deadline, execution);
|
||||
new VersionedTextDocumentIdentifier(uri, documentVersion), digest)), deadline, execution);
|
||||
analysis = mapper.convertValue(mapper.readTree(gson.toJson(retained)), Map.class);
|
||||
}
|
||||
currentDiagnostics = await(diagnostics, deadline, execution);
|
||||
@@ -283,9 +292,12 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
output.put("analysis", analysis);
|
||||
output.put("context", ImmutableJson.fields("projectRoot", context.projectRoot().toString(),
|
||||
"taskId", task.value(), "clientRequestId", null, "buildId", null, "queryId", execution.queryId(), "analysisId", analysis.get("analysisId"),
|
||||
"document", document == null ? null : ImmutableJson.fields("uri", uri, "version", 1, "sha256", digest),
|
||||
"document", document == null ? null : ImmutableJson.fields("uri", uri, "version", documentVersion, "sha256", digest),
|
||||
"inputs", analysis.getOrDefault("inputs", List.of()), "externalRevision", externalRevision,
|
||||
"inputCoverage", "partial", "configuration", analysis.getOrDefault("configuration", Map.of())));
|
||||
if(internal!=null)internal.verify(connection.embedded);
|
||||
if(document!=null&&overlay==null&&!sha256(Files.readString(document)).equals(digest))
|
||||
throw failure(AutomationFailure.Code.LANGUAGE_QUERY_REVISION_MISMATCH,"Saved source changed during language query");
|
||||
succeeded = true;
|
||||
return Collections.unmodifiableMap(output);
|
||||
} catch (Exception failure) {
|
||||
@@ -305,9 +317,37 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
execution.record(AutomationFailure.Code.LANGUAGE_QUERY_CLEANUP_FAILED, "Could not release query external sources", Map.of());
|
||||
} finally { if (interrupted) Thread.currentThread().interrupt(); }
|
||||
}
|
||||
listening.cancel(true);
|
||||
}
|
||||
} finally { execution.finishWorkers(workers); }
|
||||
}
|
||||
}
|
||||
|
||||
private final class Connection implements AutoCloseable {
|
||||
final ExternalSourceLanguageServer server;
|
||||
final InProcessLanguageWorkspace.Connection embedded;
|
||||
final Socket socket; final ExecutorService workers; final Future<?> listening;
|
||||
final LanguageQueryExecution execution;
|
||||
Connection(ExternalSourceLanguageServer server,InProcessLanguageWorkspace.Connection embedded,Socket socket,
|
||||
ExecutorService workers,Future<?> listening,LanguageQueryExecution execution) {
|
||||
this.server=server;this.embedded=embedded;this.socket=socket;this.workers=workers;this.listening=listening;this.execution=execution;
|
||||
}
|
||||
public void close() throws Exception {
|
||||
if(embedded!=null){embedded.close();return;}
|
||||
try{listening.cancel(true);socket.close();}finally{execution.finishWorkers(workers);}
|
||||
}
|
||||
}
|
||||
private Connection connect(p.studio.lsp.messages.LspProjectContext binding,p.studio.lsp.messages.LspServerEndpoint endpoint,
|
||||
LanguageClient client,LanguageQueryExecution execution,Map<Path,String> overlays) throws Exception {
|
||||
if(internal!=null){var embedded=internal.connect(binding,client,execution,overlays);return new Connection(embedded.server,embedded,null,null,null,execution);}
|
||||
var workers=Executors.newCachedThreadPool();var socket=new Socket();
|
||||
try {
|
||||
execution.own(()->{try{socket.close();}catch(java.io.IOException ignored){}});execution.own(workers::shutdownNow);
|
||||
if(!InetAddress.getByName(endpoint.host()).isLoopbackAddress())throw failure(AutomationFailure.Code.LANGUAGE_SERVER_UNAVAILABLE,"Project LSP endpoint is not local");
|
||||
socket.connect(new InetSocketAddress(endpoint.host(),endpoint.port()),2000);
|
||||
var launcher=new Launcher.Builder<ExternalSourceLanguageServer>().setLocalService(client)
|
||||
.setRemoteInterface(ExternalSourceLanguageServer.class).setInput(socket.getInputStream()).setOutput(socket.getOutputStream()).setExecutorService(workers).create();
|
||||
var listening=launcher.startListening();execution.own(()->listening.cancel(true));
|
||||
return new Connection(launcher.getRemoteProxy(),null,socket,workers,listening,execution);
|
||||
}catch(Exception failure){socket.close();execution.finishWorkers(workers);throw failure;}
|
||||
}
|
||||
|
||||
private static String sha256(String text) throws java.security.NoSuchAlgorithmException {
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
package p.studio.app.lsp;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.eclipse.lsp4j.services.*;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.api.session.ProjectLanguageService;
|
||||
import p.studio.core.language.LanguageQueryExecution;
|
||||
import p.studio.core.session.LspLifecyclePort;
|
||||
import p.studio.lsp.messages.LspProjectContext;
|
||||
import p.studio.lsp.services.compiler.*;
|
||||
import p.studio.lsp.services.protocol.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.*;
|
||||
|
||||
/** Project-owned language engine. No sockets, launchers, discovery files, or UI types. */
|
||||
public final class InProcessLanguageWorkspace implements LspLifecyclePort, AutoCloseable {
|
||||
private final Map<Path,Workspace> projects=new ConcurrentHashMap<>();
|
||||
private final CompilerLanguageServiceBridge bridge;
|
||||
private final AutomationLspQueries queries;
|
||||
private volatile boolean closed;
|
||||
private static final class Workspace {
|
||||
final ExternalSourceRegistry sources=new ExternalSourceRegistry();
|
||||
final Semaphore admission=new Semaphore(1,true);
|
||||
final Set<Connection> connections=ConcurrentHashMap.newKeySet();
|
||||
final Map<String,ProjectLanguageService.Document> editorVersions=new ConcurrentHashMap<>();
|
||||
final Set<CompletableFuture<?>> pending=ConcurrentHashMap.newKeySet();
|
||||
final TaskIdentity editor;
|
||||
final ProjectReference project;
|
||||
final ThreadPoolExecutor requests=executor("studio-editor-language",16);
|
||||
volatile boolean closing;
|
||||
volatile java.util.function.Supplier<ManualLease> editing;
|
||||
Workspace(ProjectReference project){this.project=project;editor=new TaskIdentity(key(project.rootPath()),UUID.randomUUID().toString());}
|
||||
}
|
||||
public InProcessLanguageWorkspace(p.animation.GlyphBankLayoutSource layouts,
|
||||
p.animation.AnimationOriginNavigation navigation,ProjectCatalog catalog,ProjectKnowledge knowledge,ObjectMapper mapper) {
|
||||
bridge=new CompilerLanguageServiceBridge(layouts,navigation);
|
||||
queries=new AutomationLspQueries(this,catalog,knowledge,mapper);
|
||||
}
|
||||
public AutomationLspQueries savedQueries(){return queries;}
|
||||
private static ThreadPoolExecutor executor(String name,int capacity) {
|
||||
return new ThreadPoolExecutor(1,1,0,TimeUnit.SECONDS,new ArrayBlockingQueue<>(capacity),
|
||||
Thread.ofPlatform().daemon().name(name+"-",0).factory(),new ThreadPoolExecutor.AbortPolicy());
|
||||
}
|
||||
private static Path key(Path root){try{return root.toRealPath();}catch(java.io.IOException failure){throw new IllegalStateException("Project root is unavailable",failure);}}
|
||||
@Override public synchronized void boot(ProjectReference project) {
|
||||
if(closed)throw new IllegalStateException("Language services are closing");
|
||||
Path root=key(project.rootPath());
|
||||
if(projects.putIfAbsent(root,new Workspace(project))!=null)throw new IllegalStateException("Project language service already open");
|
||||
}
|
||||
public boolean available(LspProjectContext context){var w=projects.get(key(context.projectRoot()));return w!=null&&!w.closing&&w.project.languageId().equals(context.languageId());}
|
||||
private Workspace require(LspProjectContext context) {
|
||||
var workspace=projects.get(key(context.projectRoot()));
|
||||
if(workspace==null||workspace.closing||!workspace.project.languageId().equals(context.languageId()))throw new AutomationException(AutomationFailure.Code.LANGUAGE_SERVER_UNAVAILABLE,"Project language service is not running");
|
||||
return workspace;
|
||||
}
|
||||
public void verify(Connection connection) {
|
||||
if(connection.workspace.closing||projects.get(connection.root)!=connection.workspace)
|
||||
throw new AutomationException(AutomationFailure.Code.CLOSED,"Project language session was closed");
|
||||
}
|
||||
Connection connect(LspProjectContext context,LanguageClient client,LanguageQueryExecution execution,Map<Path,String> overlays) throws Exception {
|
||||
var workspace=require(context);
|
||||
if(!workspace.admission.tryAcquire(Math.max(1,execution.deadlineNanos()-System.nanoTime()),TimeUnit.NANOSECONDS))
|
||||
throw new TimeoutException("Language admission budget expired");
|
||||
try {
|
||||
if(workspace.closing)throw new IllegalStateException("Project language service is closing");
|
||||
var connection=new Connection(key(context.projectRoot()),workspace,context,client,execution,overlays);
|
||||
workspace.connections.add(connection);return connection;
|
||||
}catch(Throwable failure){workspace.admission.release();throw failure;}
|
||||
}
|
||||
void endTask(TaskIdentity task,String consumer) {
|
||||
var workspace=projects.get(key(task.projectRoot()));
|
||||
if(workspace==null||workspace.closing)return;
|
||||
workspace.sources.connect(consumer,true);workspace.sources.release(consumer,null);
|
||||
}
|
||||
@Override public ProjectLanguageService language(ProjectReference project) {
|
||||
var context=LspLifecycleAdapter.context(project);var workspace=require(context);
|
||||
return new ProjectLanguageService() {
|
||||
@Override public void closeDocument(String uri) {
|
||||
try(var lease=workspace.editing.get()){workspace.editorVersions.remove(uri);}
|
||||
}
|
||||
@Override public CompletionStage<Result> query(Request request) {
|
||||
var response=new CompletableFuture<ProjectLanguageService.Result>();
|
||||
if(workspace.closing){response.completeExceptionally(new IllegalStateException("Project language service is closing"));return response;}
|
||||
var document=request.document();
|
||||
if(document!=null) {
|
||||
try {
|
||||
if(!Objects.equals(workspace.editorVersions.get(document.uri()),document)) {
|
||||
if(workspace.editing==null)throw new IllegalStateException("Editor admission is not bound");
|
||||
try(var lease=workspace.editing.get()) {
|
||||
Path path=Path.of(java.net.URI.create(document.uri())).toRealPath();
|
||||
if(!path.startsWith(key(project.rootPath())))throw new IllegalArgumentException("Overlay is outside the project");
|
||||
if(document.text().getBytes(java.nio.charset.StandardCharsets.UTF_8).length>4*1024*1024)
|
||||
throw new IllegalArgumentException("Editor document exceeds 4 MiB");
|
||||
var prior=workspace.editorVersions.compute(document.uri(),(uri,value)->value==null||document.version()>value.version()?document:value);
|
||||
if(!prior.equals(document))throw new IllegalArgumentException("Obsolete or conflicting editor document version");
|
||||
}
|
||||
}
|
||||
}catch(Exception failure){return CompletableFuture.failedFuture(failure);}
|
||||
}
|
||||
var snapshot=Map.copyOf(workspace.editorVersions);
|
||||
var overlays=new HashMap<Path,String>();
|
||||
snapshot.values().forEach(d->overlays.put(Path.of(java.net.URI.create(d.uri())).toAbsolutePath().normalize(),d.text()));
|
||||
workspace.pending.add(response);response.whenComplete((v,f)->workspace.pending.remove(response));
|
||||
try {
|
||||
var work=workspace.requests.submit(()->{
|
||||
try {
|
||||
if(workspace.closing||response.isCancelled())throw new CancellationException("Project language request cancelled");
|
||||
var value=queries.queryEditor(workspace.editor,request,overlays);
|
||||
if(workspace.closing||projects.get(key(project.rootPath()))!=workspace
|
||||
||!workspace.editorVersions.equals(snapshot))
|
||||
throw new AutomationException(AutomationFailure.Code.LANGUAGE_QUERY_REVISION_MISMATCH,"Editor revision was superseded");
|
||||
response.complete(new ProjectLanguageService.Result(value));
|
||||
}catch(Throwable failure){response.completeExceptionally(failure);}
|
||||
});
|
||||
response.whenComplete((v,f)->{if(response.isCancelled())work.cancel(true);});
|
||||
}catch(RejectedExecutionException full){response.completeExceptionally(new IllegalStateException("Project language queue is full or closing",full));}
|
||||
return response;
|
||||
}
|
||||
};
|
||||
}
|
||||
@Override public DocumentHandoff documents(ProjectReference project,java.util.function.Supplier<ManualLease> editing) {
|
||||
var workspace=require(LspLifecycleAdapter.context(project));workspace.editing=Objects.requireNonNull(editing);
|
||||
return new DocumentHandoff() {
|
||||
public CompletionStage<Boolean> hasUnsavedChanges() {
|
||||
try {
|
||||
for(var document:workspace.editorVersions.values())
|
||||
if(!java.nio.file.Files.readString(Path.of(java.net.URI.create(document.uri()))).equals(document.text()))
|
||||
return CompletableFuture.completedFuture(true);
|
||||
return CompletableFuture.completedFuture(false);
|
||||
}catch(Exception failure){return CompletableFuture.failedFuture(failure);}
|
||||
}
|
||||
public CompletionStage<Void> saveAll() {
|
||||
// Persistence belongs to the editor. Admission must never silently write drafts.
|
||||
return hasUnsavedChanges().thenAccept(dirty->{if(dirty)throw new IllegalStateException("Save the editor documents explicitly");});
|
||||
}
|
||||
public CompletionStage<Void> refreshFromDisk() {
|
||||
try {
|
||||
var refreshed=new HashMap<String,ProjectLanguageService.Document>();
|
||||
for(var document:workspace.editorVersions.values()) {
|
||||
Path path=Path.of(java.net.URI.create(document.uri()));
|
||||
if(java.nio.file.Files.isRegularFile(path))refreshed.put(document.uri(),new ProjectLanguageService.Document(
|
||||
document.uri(),Math.addExact(document.version(),1),java.nio.file.Files.readString(path)));
|
||||
}
|
||||
workspace.editorVersions.clear();workspace.editorVersions.putAll(refreshed);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}catch(Exception failure){return CompletableFuture.failedFuture(failure);}
|
||||
}
|
||||
};
|
||||
}
|
||||
@Override public void shutdown(ProjectReference project) {
|
||||
Path root=key(project.rootPath());var workspace=projects.get(root);if(workspace==null)return;
|
||||
workspace.closing=true;workspace.requests.shutdownNow();workspace.connections.forEach(Connection::cancel);
|
||||
workspace.pending.forEach(f->f.completeExceptionally(new IllegalStateException("Project language service closed")));
|
||||
boolean interrupted=Thread.interrupted();
|
||||
try {
|
||||
if(!workspace.requests.awaitTermination(2,TimeUnit.SECONDS)||workspace.connections.stream().anyMatch(c->!c.workers.isTerminated()))
|
||||
throw new IllegalStateException("Project language workers have not terminated; retry cleanup");
|
||||
queries.endTask(workspace.editor);workspace.sources.close();projects.remove(root,workspace);
|
||||
}catch(InterruptedException stop){interrupted=true;throw new IllegalStateException("Language cleanup interrupted",stop);}
|
||||
finally{if(interrupted)Thread.currentThread().interrupt();}
|
||||
}
|
||||
@Override public void close(){closed=true;for(var workspace:List.copyOf(projects.values()))shutdown(workspace.project);}
|
||||
|
||||
final class Connection implements AutoCloseable {
|
||||
final Path root;final Workspace workspace;
|
||||
final ThreadPoolExecutor workers=executor("studio-internal-language",32);
|
||||
final PrometeuLanguageServer implementation;
|
||||
final ExternalSourceLanguageServer server;
|
||||
final LanguageQueryExecution execution;
|
||||
final AtomicReference<Throwable> failure=new AtomicReference<>();
|
||||
final AtomicBoolean disposed=new AtomicBoolean();
|
||||
Connection(Path root,Workspace workspace,LspProjectContext context,LanguageClient client,LanguageQueryExecution execution,Map<Path,String> overlays) {
|
||||
this.root=root;this.workspace=workspace;this.execution=execution;
|
||||
implementation=new PrometeuLanguageServer(context,bridge.withOverlays(overlays),workspace.sources);implementation.connect(client);
|
||||
server=proxy(ExternalSourceLanguageServer.class,implementation);
|
||||
execution.own(this::cancel);
|
||||
}
|
||||
void cancel(){workers.shutdownNow();}
|
||||
@SuppressWarnings("unchecked") <T>T proxy(Class<T> type,Object target) {
|
||||
return (T)Proxy.newProxyInstance(type.getClassLoader(),new Class<?>[]{type},(self,method,args)->{
|
||||
if(method.getDeclaringClass()==Object.class)return method.invoke(target,args);
|
||||
if(method.getName().equals("getTextDocumentService"))return proxy(TextDocumentService.class,implementation.getTextDocumentService());
|
||||
if(method.getName().equals("getWorkspaceService"))return proxy(WorkspaceService.class,implementation.getWorkspaceService());
|
||||
var result=new CompletableFuture<Object>();
|
||||
try {workers.execute(()->{
|
||||
try {
|
||||
verify(this);if(failure.get()!=null)throw new CompletionException(failure.get());
|
||||
Object value=method.invoke(target,args);
|
||||
if(value instanceof CompletableFuture<?> pending) {
|
||||
execution.own(()->pending.cancel(true));
|
||||
pending.whenComplete((v,f)->{if(f==null)result.complete(v);else result.completeExceptionally(f);});
|
||||
}else result.complete(value);
|
||||
}catch(Throwable problem){Throwable cause=problem instanceof InvocationTargetException invoked?invoked.getCause():problem;failure.compareAndSet(null,cause);result.completeExceptionally(cause);}
|
||||
});}catch(RejectedExecutionException rejected){result.completeExceptionally(rejected);}
|
||||
return method.getReturnType()==void.class?null:result;
|
||||
});
|
||||
}
|
||||
@Override public void close() {
|
||||
if(!disposed.compareAndSet(false,true))return;
|
||||
execution.finishWorkers(workers);
|
||||
try{implementation.disconnected();}finally{workspace.connections.remove(this);workspace.admission.release();}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,13 +10,14 @@ import java.util.Optional;
|
||||
/** Projects connection liveness and permanent setup independently of task authority. */
|
||||
public final class McpConnectionGuide implements AgentConnectionGuide {
|
||||
public static final String INSTRUCTIONS = """
|
||||
Use the Studio tools for this project. Wait for the developer to grant access in DEV, then acquire control.
|
||||
Use the Studio tools for this open project. In an integrated Studio conversation, activity admission is owned by Studio.
|
||||
The installed Studio connector discovers the connection automatically; do not write transport scripts or copy tokens.
|
||||
Connect and list available tools. Read studio_project_context for the explicit projectRoot and consult
|
||||
studio_reference_read for the declared languages, SDK and libraries before editing as needed.
|
||||
Do not assume PBS or another language when support/documentation is missing; report the limitation.
|
||||
Wait for the developer to grant control in DEV, then call studio_control_acquire. Copying or connecting
|
||||
does not grant permission. Use the returned taskId for all work and operate only on this project.
|
||||
Call studio_control_acquire to obtain the current integrated activity taskId. Connection authentication
|
||||
does not create editing authority. If no integrated activity is active, an external client requires an
|
||||
explicit human grant in the legacy DEV interface. Use the returned taskId only for this project/activity.
|
||||
Edit saved project files with your native tools; SDK and external libraries are read-only.
|
||||
Discover language operations and required parameters in studio_language_query.inputSchema or
|
||||
studio_project_context.languageQuery. languages[].capabilities describes provider support, not
|
||||
@@ -50,8 +51,8 @@ public final class McpConnectionGuide implements AgentConnectionGuide {
|
||||
explicit studio_tests_shutdown policy; do not infer consent to discard pending/unsaved data.
|
||||
Release errors retain final authority and cleanup in details.control: taskRevoked means the old task
|
||||
cannot be reused even when cleanup failed. The authenticated studio_project_context exposes current
|
||||
control/runtime observations when the connection is available; otherwise inspect DEV and obtain a
|
||||
fresh human grant. Never treat the need to inspect cleanup as permission to reuse a revoked identity.
|
||||
control/runtime observations when the connection is available; otherwise inspect Studio and start a
|
||||
fresh activity (or obtain an explicit legacy external grant). Never treat the need to inspect cleanup as permission to reuse a revoked identity.
|
||||
For asset authoring, inspect studio_assets_catalog, studio_assets_artifacts, studio_assets_inspect,
|
||||
studio_assets_dependencies and studio_assets_budget. Freeze studio_assets_revision before
|
||||
studio_assets_preview. Review changed files/hashes, producer diagnostics and affected references;
|
||||
@@ -69,13 +70,14 @@ public final class McpConnectionGuide implements AgentConnectionGuide {
|
||||
are exact. Read the verdict, metrics, normalized ROI/masks, hashes and expected/actual/diff IDs.
|
||||
Use studio_evidence_image for direct PNG content and studio_evidence_read for bounded bytes.
|
||||
Recover a lost publication response via studio_evidence_list requestId or identical request parameters;
|
||||
never replay guest work. Evidence survives release/rebuild/reopen, but a fresh task grant is required.
|
||||
never replay guest work. Evidence survives release/rebuild/reopen, but a fresh activity task is required.
|
||||
Quota refusal includes used/required/limit; deletion is explicit and reference-aware. Baseline approval
|
||||
is a human manual-control action in the DEV inspector; never promote a failed comparison automatically.
|
||||
Observe headless images/state when those tools are available, and explicitly studio_control_release
|
||||
when finished. On revocation stop external edits too: Studio cannot stop your native file writes.
|
||||
when finished. In integrated mode, release is an acknowledgement; Studio retains editing protection
|
||||
until the prompt, tools and cleanup actually finish. On revocation stop external edits too: Studio cannot stop your native file writes.
|
||||
Existing edits are preserved. Git/review/recovery remain the developer's responsibility.
|
||||
After Studio restart, wait for a fresh human grant. The connector reconnects automatically; old task identities are invalid.
|
||||
After Studio restart, wait for a fresh integrated activity or explicit legacy external grant. The connector reconnects automatically; old task identities are invalid.
|
||||
""";
|
||||
private final LocalMcpServer server;
|
||||
private final ProjectAccessRegistry projects;
|
||||
|
||||
@@ -62,7 +62,7 @@ public final class StudioAgentPreparation implements AgentIntegrationPreparation
|
||||
try { Files.writeString(temporary, setupText); Files.move(temporary, setup, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
|
||||
finally { Files.deleteIfExists(temporary); }
|
||||
}
|
||||
return new Result(true, "Assistant prepared. Trust this project in your client and reload MCP once if requested. Then grant access in DEV; no token copying or restart reconfiguration is needed.");
|
||||
return new Result(true, "Assistant prepared. Trust this project in your client and reload MCP once if requested. Studio reserves editing before each integrated prompt; no token copying or restart reconfiguration is needed.");
|
||||
} catch (ManagedStudioInstallation.MissingInstallation missing) { return new Result(false, missing.getMessage()); }
|
||||
catch (Conflict conflict) { return new Result(false, conflict.getMessage()); }
|
||||
catch (Exception failure) { return new Result(false, "Preparation incomplete. Check the Studio installation and project/configuration permissions; existing client settings were not deliberately replaced."); }
|
||||
|
||||
Reference in New Issue
Block a user