feat: add per-project native server and SSE command streaming
build / jvm (push) Waiting to run
build / native (macos-15, macos-arm64) (push) Waiting to run
build / native (ubuntu-24.04, linux-x86_64) (push) Waiting to run
build / native (windows-2025, windows-x86_64) (push) Waiting to run
Test / Tests and coverage
Intrepid/AI Engineering/pipeline/head This commit looks good

Keep Spring in a persistent project server with lightweight clients, managed start/stop, bounded SSE subscriptions, cursor recovery and durable mutation outcomes. Preserve SQLite authority and transaction limits, and document reproducible native measurements.

Validation: 269 tests, 11 pipeline scenarios, full native/SSE smoke, native package verification and 17 installer tests passed. Implements WRK-000E / DEC-0001 / DEC-0002.
This commit is contained in:
2026-11-22 23:08:47 +00:00
parent 20bb4f02bc
commit 9a555cb3c6
64 changed files with 5062 additions and 29 deletions
@@ -8,11 +8,22 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportRuntimeHints;
import java.io.PrintWriter;
import java.nio.file.Path;
import net.intrepid.aiengineering.localserver.*;
@SpringBootApplication(proxyBeanMethods = false)
@ImportRuntimeHints(NativeHints.class)
public class AiEngineeringApplication {
@Bean EngineeringCli engineeringCli() { return new EngineeringCli(Path.of("")); }
public static void serve(Path root, long idleMillis, ServerProtocol.Operations operations) throws InterruptedException {
var application = new SpringApplication(AiEngineeringApplication.class);
application.setMainApplicationClass(AiEngineeringApplication.class);
application.setWebApplicationType(WebApplicationType.NONE);
application.setDefaultProperties(java.util.Map.of("spring.main.banner-mode", "off",
"spring.main.log-startup-info", "false", "logging.level.root", "ERROR"));
try (var context = application.run(); var server = new ProjectServer(new ServerState(root), idleMillis, operations)) {
server.await();
}
}
public static void main(String[] args) {
var application = new SpringApplication(AiEngineeringApplication.class);
application.setWebApplicationType(WebApplicationType.NONE);
@@ -0,0 +1,29 @@
package net.intrepid.aiengineering;
import net.intrepid.aiengineering.localserver.*;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import net.intrepid.aiengineering.project.ProjectService;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
/** Distribution entry point. Spring's separate application main remains available to AOT tooling. */
public final class AieLauncher {
private AieLauncher() {}
public static void main(String[] args) {
int code;
try {
if (args.length > 0 && args[0].equals(ServerLaunch.INTERNAL)) {
if (args.length != 3) throw ProtocolException.invalid("Internal server launch requires project and idle timeout");
Path root = new ProjectService().discover(Path.of(args[1]), null);
AiEngineeringApplication.serve(root, Long.parseLong(args[2]), new RequestJobs(new ServerState(root)));
return;
}
code = new LocalClient(Path.of(""), new InputStreamReader(System.in, StandardCharsets.UTF_8),
new PrintWriter(System.out, true), new PrintWriter(System.err, true), System.console() != null).execute(args);
} catch (ProtocolException failure) { System.err.println(failure.getMessage()); code=failure.exitCode(); }
catch (InterruptedException failure) { Thread.currentThread().interrupt(); System.err.println("AIE interrupted"); code=4; }
catch (Exception failure) { System.err.println("AIE failed: " + failure.getMessage()); code=1; }
System.exit(code);
}
}
@@ -11,10 +11,14 @@ import net.intrepid.aiengineering.agent.*;
import net.intrepid.aiengineering.verification.*;
import net.intrepid.aiengineering.legacyimport.DiscussionImport;
import org.springframework.aot.hint.*;
import net.intrepid.aiengineering.localserver.*;
public final class NativeHints implements RuntimeHintsRegistrar {
@Override public void registerHints(RuntimeHints hints, ClassLoader loader) {
for (Class<?> type : new Class<?>[]{ProjectConfig.class, ProjectConfig.Identity.class, ProjectConfig.Repository.class,
for (Class<?> type : new Class<?>[]{ServerState.Descriptor.class, ServerProtocol.Request.class,
ServerProtocol.Health.class, ServerProtocol.View.class, ServerProtocol.Event.class, ServerProtocol.Input.class,
ServerProtocol.Cancel.class, ServerProtocol.Error.class, RequestJobs.Receipt.class,
ServerManager.Status.class, ProjectConfig.class, ProjectConfig.Identity.class, ProjectConfig.Repository.class,
ProjectConfig.Access.class, ProjectService.Revision.class, Work.class, WorkService.Sequence.class, DiscussionEntry.class,
Decision.class, Decision.Approval.class, Decision.ApprovalOrigin.class, Plan.class, Plan.Step.class, Plan.Exclusion.class,
net.intrepid.aiengineering.work.WorkGuidance.class, net.intrepid.aiengineering.work.WorkGuidance.Choice.class,
@@ -48,5 +52,6 @@ public final class NativeHints implements RuntimeHintsRegistrar {
}
hints.resources().registerPattern("protocol/*");
hints.resources().registerPattern("sqlite/*");
hints.resources().registerPattern("aie-build.txt");
}
}
@@ -30,10 +30,74 @@ public final class EngineeringCli implements Runnable {
@Option(names = "--project", scope = ScopeType.INHERIT, description = "Engineering project root or .ai-engineering directory.") Path project;
public EngineeringCli(Path cwd) { this(cwd, new java.io.InputStreamReader(System.in, java.nio.charset.StandardCharsets.UTF_8), false); }
public EngineeringCli(Path cwd, java.io.Reader input) { this(cwd, input, true); }
private EngineeringCli(Path cwd, java.io.Reader input, boolean injectedInput) {
public EngineeringCli(Path cwd, java.io.Reader input, boolean injectedInput) {
this.cwd = cwd.toAbsolutePath().normalize(); this.input = input; this.injectedInput = injectedInput;
}
public int execute(PrintWriter out, PrintWriter err, String... args) {
int result = commandLineFor(out, err, args).execute(args); out.flush(); err.flush(); return result;
}
/** Parse prefixes with Picocli and inspect only the selected branch. Full catalogs remain available for help/errors. */
public CommandLine commandLineFor(PrintWriter out, PrintWriter err, String... args) {
var spec = CommandLine.Model.CommandSpec.wrapWithoutInspection(this).name("ai-engineering")
.version("ai-engineering " + ProtocolContract.CLI_VERSION).mixinStandardHelpOptions(true);
spec.usageMessage().description("Portable engineering protocol for humans and AI agents.");
spec.addOption(CommandLine.Model.OptionSpec.builder("--project").type(Path.class).scopeType(ScopeType.INHERIT)
.description("Engineering project root or .ai-engineering directory.")
.setter(new CommandLine.Model.ISetter() {
@SuppressWarnings("unchecked") public <T> T set(T value) { Path previous=project; project=(Path)value; return (T)previous; }
}).build());
var parser = new CommandLine(spec).setStopAtUnmatched(true);
CommandLine branch=parser;
try {
while (true) {
var parsed=parser.parseArgs(args);
while (parsed.subcommand()!=null) parsed=parsed.subcommand();
var unmatched=parsed.unmatched();
if (unmatched.isEmpty()) return commandLine(out,err);
String name=unmatched.getFirst(); Object owner=branch.getCommandSpec().userObject();
Object child=selectedGroup(owner,name);
if (child!=null) {
var metadata=child.getClass().getAnnotation(Command.class);
var childSpec=CommandLine.Model.CommandSpec.wrapWithoutInspection(child)
.name(metadata.name()).mixinStandardHelpOptions(true);
childSpec.usageMessage().description(metadata.description());
var nested=new CommandLine(childSpec).setStopAtUnmatched(true);
branch.addSubcommand(name,nested); branch=nested; continue;
}
if (owner instanceof ImportCommands && name.equals("discussion")) {
branch.addSubcommand(name,new DiscussionImportCommand());
} else {
var method=java.util.Arrays.stream(owner.getClass().getDeclaredMethods())
.filter(value -> value.isAnnotationPresent(Command.class))
.filter(value -> { var annotation=value.getAnnotation(Command.class);
return annotation.name().equals(name) || List.of(annotation.aliases()).contains(name); })
.findFirst().orElse(null);
if (method==null) return commandLine(out,err);
branch.addSubcommand(name,new CommandLine(method));
}
output=out; commandLine=parser;
resetPrefixParsing(parser); configureExecution(parser,out,err); return parser;
}
} catch (CommandLine.ParameterException invalidPrefix) { return commandLine(out,err); }
}
private Object selectedGroup(Object owner,String name) {
if (owner==this) return switch(name) {
case "project" -> new ProjectCommands(); case "repo" -> new RepoCommands(); case "work" -> new WorkCommands();
case "discussion" -> new DiscussionCommands(); case "decision" -> new DecisionCommands(); case "artifact" -> new ArtifactCommands();
case "plan" -> new PlanCommands(); case "topic" -> new TopicCommands(); case "survey" -> new SurveyCommands();
case "agent" -> new AgentCommands(); case "epic" -> new EpicCommands(); case "gate" -> new GateCommands();
case "storage" -> new StorageCommands(); case "import" -> new ImportCommands(); default -> null;
};
if (owner instanceof PlanCommands) return switch(name) {
case "step" -> new StepCommands(); case "experiment" -> new ExperimentCommands(); default -> null;
};
return null;
}
private void resetPrefixParsing(CommandLine parser) {
parser.setStopAtUnmatched(false); parser.getSubcommands().values().forEach(this::resetPrefixParsing);
}
/** A fresh parser and command graph for one invocation. Parsing never executes a command. */
public CommandLine commandLine(PrintWriter out, PrintWriter err) {
output = out;
commandLine = new CommandLine(this)
.addSubcommand("project", new ProjectCommands()).addSubcommand("repo", new RepoCommands())
@@ -43,14 +107,18 @@ public final class EngineeringCli implements Runnable {
.addSubcommand("topic", new TopicCommands()).addSubcommand("survey", new SurveyCommands()).addSubcommand("agent", new AgentCommands())
.addSubcommand("epic", new EpicCommands()).addSubcommand("gate", new GateCommands()).addSubcommand("storage", new StorageCommands());
commandLine.addSubcommand("import", new CommandLine(new ImportCommands()).addSubcommand("discussion", new DiscussionImportCommand()));
configure(commandLine, out, err);
commandLine.setExecutionExceptionHandler((exception, command, parse) -> {
configureExecution(commandLine,out,err);
return commandLine;
}
private void configureExecution(CommandLine parser, PrintWriter out, PrintWriter err) {
configure(parser, out, err);
parser.setExecutionExceptionHandler((exception, command, parse) -> {
if (exception instanceof ProtocolException problem) { err.println(problem.getMessage()); return problem.exitCode(); }
if (exception instanceof IllegalArgumentException) { err.println("Invalid input: " + exception.getMessage()); return 2; }
err.println("Operation failed: " + exception.getMessage()); return 1;
});
int result = commandLine.execute(args); out.flush(); err.flush(); return result;
}
public Path selectedRoot() { return discoveredRoot(); }
private void configure(CommandLine command, PrintWriter out, PrintWriter err) {
command.setOut(out).setErr(err).setCaseInsensitiveEnumValuesAllowed(true);
command.getSubcommands().values().forEach(child -> configure(child, out, err));
@@ -12,6 +12,7 @@ import static java.nio.file.StandardOpenOption.*;
/** Filesystem operations shared by the protocol adapters. Never executes project commands. */
public final class Filespace {
private static final ThreadLocal<java.util.Set<Path>> HELD = ThreadLocal.withInitial(java.util.HashSet::new);
private static final java.util.concurrent.ConcurrentHashMap<Path, java.util.concurrent.locks.ReentrantLock> LOCAL_WRITERS = new java.util.concurrent.ConcurrentHashMap<>();
private Filespace() {}
@FunctionalInterface public interface IoSupplier<T> { T get() throws IOException; }
public static <T> T io(IoSupplier<T> action) {
@@ -86,7 +87,14 @@ public final class Filespace {
Path lock = resolve(projectRoot, ".ai-engineering/.local/write.lock");
if (HELD.get().contains(lock)) return operation.get();
directory(lock.getParent());
return io(() -> {
var local = LOCAL_WRITERS.computeIfAbsent(lock, ignored -> new java.util.concurrent.locks.ReentrantLock(true));
try {
if (!local.tryLock(SqliteDatabase.DEFAULT_BUSY_MILLIS, java.util.concurrent.TimeUnit.MILLISECONDS))
throw ProtocolException.validation("Project publication is busy; local writer wait exceeded 2000 ms");
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt(); throw ProtocolException.validation("Interrupted while waiting for project publication");
}
try { return io(() -> {
try (var channel = FileChannel.open(lock, CREATE, WRITE, NOFOLLOW_LINKS); var ignored = acquire(channel, bounded)) {
HELD.get().add(lock);
try { return operation.get(); }
@@ -94,7 +102,7 @@ public final class Filespace {
} catch (java.nio.channels.OverlappingFileLockException e) {
throw ProtocolException.invalid("Project is being modified by this process; retry after it completes");
}
});
}); } finally { local.unlock(); }
}
private static java.nio.channels.FileLock acquire(FileChannel channel, boolean bounded) throws IOException {
if (!bounded) return channel.lock();
@@ -19,6 +19,7 @@ public final class SqliteDatabase {
final Connection connection;
final boolean write;
boolean rollbackOnly;
Boolean selectedBackend;
final List<Runnable> committed = new ArrayList<>();
final List<Runnable> rolledBack = new ArrayList<>();
Session(Connection connection, boolean write) { this.connection = connection; this.write = write; }
@@ -27,6 +28,18 @@ public final class SqliteDatabase {
public static Path path(Path root) { return Filespace.resolve(root, ".ai-engineering/aie.db"); }
public static boolean active(Path root) {
// Bootstrap selection is stable for a transaction, not inferred from an open connection or cached across commands.
var sessions=SESSIONS.get();
// A lookup key only: do not inspect an unused SQLite path in a legacy project.
var session=sessions.get(root.toAbsolutePath().normalize().resolve(".ai-engineering/aie.db"));
if(session==null) {
if(sessions.isEmpty())SESSIONS.remove();
return selectedByBootstrap(root);
}
if(session.selectedBackend==null)session.selectedBackend=selectedByBootstrap(root);
return session.selectedBackend;
}
private static boolean selectedByBootstrap(Path root) {
Path config = Filespace.resolve(root, ".ai-engineering/ai-engineering.yaml");
if (!Files.isRegularFile(config, LinkOption.NOFOLLOW_LINKS)) return false;
var node = Documents.read(config, tools.jackson.databind.node.ObjectNode.class).get("storage");
@@ -0,0 +1,93 @@
package net.intrepid.aiengineering.localserver;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import java.io.*;
import java.util.concurrent.atomic.*;
/** One submit, event-driven monitoring and bounded recovery. A transport failure never resubmits execution. */
public final class InvocationClient {
private final BufferedReader input;
private final PrintWriter err;
private final RemoteOutput output;
private final ServerManager manager;
private final ServerProtocol.Request request;
private final AtomicReference<ServerState.Descriptor> endpoint;
private ServerProtocol.Input pendingInput;
private int readSequence,acceptedSequence;
private boolean uncertainInput;
private ServerProtocol.View terminalInput;
public InvocationClient(ServerManager manager,ServerState.Descriptor descriptor,ServerProtocol.Request request,
Reader input,PrintWriter out,PrintWriter err) {
this.manager=manager;this.request=request;this.endpoint=new AtomicReference<>(descriptor);
this.input=new BufferedReader(input);this.err=err;this.output=new RemoteOutput(out,err);
}
private ServerConnection connection(){return new ServerConnection(endpoint.get());}
private boolean terminal(String state){return state.equals("COMPLETED") || state.equals("UNKNOWN");}
private void unknown(String state) {
if(state.equals("UNKNOWN")){err.println("AIE request "+request.id()+" has an unknown outcome; inspect effects before retrying.");err.flush();}
}
private ServerProtocol.View recover() throws IOException {
err.println("Recovering request "+request.id()+" without resubmitting the command.");err.flush();
endpoint.set(manager.ensure(15000,null));
try{return connection().call("GET","/requests/"+request.id(),null,ServerProtocol.View.class);}
catch(ProtocolException unavailable){throw ProtocolException.validation("Request "+request.id()+" has no recoverable result; outcome unknown, command was not resent. Inspect effects before retrying");}
}
private void input(ServerProtocol.Event event) throws IOException {
if(!event.needsInput() || event.inputSequence()<=acceptedSequence)return;
if(event.inputSequence()>readSequence) {
String line=input.readLine();readSequence=event.inputSequence();
pendingInput=new ServerProtocol.Input(request.id(),readSequence,line==null?null:line+"\n");
}
if(pendingInput==null || pendingInput.sequence()!=event.inputSequence())
throw ProtocolException.validation("Interactive input sequence changed; inspect request "+request.id());
uncertainInput=true;
var view=connection().call("POST","/input",pendingInput,ServerProtocol.View.class);
uncertainInput=false;acceptedSequence=pendingInput.sequence();
if(terminal(view.state()))terminalInput=view;
}
public int run() throws IOException {
var finished=new AtomicBoolean();
Thread cancellation=new Thread(()->{
if(!finished.get())try{connection().call("POST","/cancel",new ServerProtocol.Cancel(request.id()),ServerProtocol.View.class);}
catch(IOException | RuntimeException ignored){/* Cancellation cannot assert rollback. */}
},"aie-client-cancel");
Runtime.getRuntime().addShutdownHook(cancellation);
try {
ServerProtocol.View view;
try{view=connection().call("POST","/execute",request,ServerProtocol.View.class);}
catch(IOException interrupted){view=recover();}
unknown(view.state());output.snapshot(view);
if(terminal(view.state()))return view.exitCode();
err.println("AIE request "+request.id()+" "+view.state()+" (SSE)");err.flush();
String cursor=null;int reconnects=0;long progress=System.nanoTime();
while(true) {
try(var stream=connection().events(request.id(),cursor)) {
while(true) {
var event=stream.next();
if(event!=null) {
unknown(event.state());output.accept(event);cursor=event.cursor();
if(event.terminal())return event.exitCode();
input(event);
if(terminalInput!=null){unknown(terminalInput.state());output.snapshot(terminalInput);return terminalInput.exitCode();}
}
if(System.nanoTime()-progress>=5_000_000_000L){err.println("AIE request "+request.id()+" in progress (SSE)");err.flush();progress=System.nanoTime();}
}
}catch(IOException disconnected) {
if(++reconnects>3)throw ProtocolException.validation("SSE reconnection limit reached for request "+request.id()+"; inspect/recover its outcome. Command was not resent");
err.println("SSE interrupted; resuming request "+request.id()+" (attempt "+reconnects+"/3)");err.flush();
try{Thread.sleep(100L<<(reconnects-1));}
catch(InterruptedException interrupted){Thread.currentThread().interrupt();throw ProtocolException.validation("Interrupted recovering request "+request.id());}
var previous=endpoint.get();endpoint.set(manager.ensure(15000,null));
if(uncertainInput || !previous.instance().equals(endpoint.get().instance())) {
view=recover();uncertainInput=false;unknown(view.state());output.snapshot(view);
if(terminal(view.state()))return view.exitCode();
cursor=null;
}
}
}
}finally{
finished.set(true);
try{Runtime.getRuntime().removeShutdownHook(cancellation);}catch(IllegalStateException shuttingDown){/* Hook is already cancelling. */}
}
}
}
@@ -0,0 +1,32 @@
package net.intrepid.aiengineering.localserver;
import picocli.CommandLine;
import java.util.*;
/** Routing comes from the actual Picocli parse, never from scanning option values for keywords. */
public final class InvocationPolicy {
private InvocationPolicy() {}
private static final Set<String> LOCAL = Set.of("init", "guide", "agent list", "agent doctor");
private static final Set<String> READS = Set.of(
"status", "next-actions", "project show", "project validate", "project compatibility", "repo list",
"work show", "work list", "work context", "work check", "work validate",
"discussion list", "discussion show", "decision list", "decision show", "decision history",
"plan list", "plan show", "plan history", "plan experiment list", "plan experiment show",
"artifact list", "topic list", "topic show", "survey list", "survey show", "survey history",
"agent show", "agent history", "epic show", "epic check", "epic history", "gate status", "gate history");
public static String path(CommandLine.ParseResult parse) {
var parts = new ArrayList<String>();
for (var child = parse.subcommand(); child != null; child = child.subcommand())
parts.add(child.commandSpec().name());
return String.join(" ", parts);
}
public static boolean local(CommandLine.ParseResult parse) {
if (path(parse).isEmpty() || LOCAL.contains(path(parse))) return true;
for (var current = parse; current != null; current = current.subcommand())
if (current.isUsageHelpRequested() || current.isVersionHelpRequested()) return true;
return false;
}
public static boolean readOnly(CommandLine.ParseResult parse) {
return READS.contains(path(parse)); // Unknown/new commands conservatively count as mutations.
}
}
@@ -0,0 +1,69 @@
package net.intrepid.aiengineering.localserver;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import java.util.*;
import java.util.function.Supplier;
/** Bounded replay under the job monitor. Network I/O belongs to the subscriber after next returns. */
public final class JobEvents implements ServerProtocol.EventSource {
public static final int MAX_EVENTS = 128, MAX_REPLAY_CHARS = 256 * 1024, CHUNK_CHARS = 16 * 1024;
private final Object monitor;
private final Supplier<ServerProtocol.View> snapshot;
private final String generation = UUID.randomUUID().toString();
private final ArrayDeque<ServerProtocol.Event> history = new ArrayDeque<>();
private long sequence;
private int characters;
private boolean terminal;
public JobEvents(Object monitor, Supplier<ServerProtocol.View> snapshot) {
this.monitor=monitor; this.snapshot=snapshot;
}
public static void validateCursor(String cursor) {
if (cursor == null) return;
if (!cursor.matches("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}:[0-9]{1,19}"))
throw ProtocolException.invalid("Invalid SSE event cursor");
try { if (Long.parseLong(cursor.substring(37)) < 0) throw new NumberFormatException(); }
catch (NumberFormatException invalid) { throw ProtocolException.invalid("Invalid SSE event cursor"); }
}
private ServerProtocol.Event event(String kind, int outOffset, int errOffset, String out, String err, ServerProtocol.View view) {
return new ServerProtocol.Event(view.id(),generation+":"+sequence,kind,outOffset,errOffset,out,err,
view.state(),view.exitCode(),view.inputSequence(),view.needsInput(),view.cancellationRequested());
}
public void publish(String kind, int outOffset, int errOffset, String out, String err, ServerProtocol.View metadata) {
synchronized (monitor) {
sequence++;
var event=event(kind,outOffset,errOffset,out,err,metadata);
history.addLast(event); characters+=out.length()+err.length(); terminal=event.terminal();
while (history.size()>MAX_EVENTS || characters>MAX_REPLAY_CHARS) {
var removed=history.removeFirst(); characters-=removed.stdout().length()+removed.stderr().length();
}
monitor.notifyAll();
}
}
private ServerProtocol.Event snapshotEvent() {
var view=snapshot.get();
return event("snapshot",0,0,view.stdout(),view.stderr(),view);
}
@Override public ServerProtocol.Event next(String cursor, long timeoutMillis) throws InterruptedException {
validateCursor(cursor);
long deadline=System.nanoTime()+Math.max(0,timeoutMillis)*1_000_000;
synchronized (monitor) {
while (true) {
if (cursor==null || !cursor.startsWith(generation+":")) return snapshotEvent();
long after=Long.parseLong(cursor.substring(37));
long oldest=sequence-history.size()+1;
if (after>sequence || after<oldest-1) return snapshotEvent();
for (var event:history) if (Long.parseLong(event.cursor().substring(37))>after) return event;
if (terminal) return snapshotEvent();
long remaining=deadline-System.nanoTime();
if (remaining<=0) return null;
java.util.concurrent.TimeUnit.NANOSECONDS.timedWait(monitor,remaining);
}
}
}
public static ServerProtocol.EventSource completed(ServerProtocol.View view) {
if (!Set.of("COMPLETED","UNKNOWN").contains(view.state()))
throw ProtocolException.validation("Live request has no event source");
var events=new JobEvents(new Object(),()->view);
return (cursor,timeout)->{ validateCursor(cursor); return events.snapshotEvent(); };
}
}
@@ -0,0 +1,92 @@
package net.intrepid.aiengineering.localserver;
import net.intrepid.aiengineering.cli.EngineeringCli;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import picocli.CommandLine;
import picocli.CommandLine.*;
import java.io.*;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Callable;
/** The public client path never opens a Spring context. */
public final class LocalClient {
private final Path cwd;
private final Reader input;
private final PrintWriter out, err;
private final boolean interactive;
public LocalClient(Path cwd, Reader input, PrintWriter out, PrintWriter err, boolean interactive) {
this.cwd = cwd.toAbsolutePath().normalize(); this.input = input; this.out = out; this.err = err; this.interactive = interactive;
}
public int execute(String... args) {
var cli = new EngineeringCli(cwd, input, interactive);
var parser = cli.commandLineFor(out, err, args);
parser.addSubcommand("start", new Start(cli)); parser.addSubcommand("stop", new Stop(cli));
parser.addSubcommand("server", new Management(cli));
configure(parser);
try {
var parsed = parser.parseArgs(args);
String path = InvocationPolicy.path(parsed);
if (InvocationPolicy.local(parsed) || path.equals("start") || path.equals("stop") || path.startsWith("server"))
return parser.execute(args);
Path root = cli.selectedRoot();
var manager = new ServerManager(root);
var descriptor = manager.ensure(15000, null);
return forward(manager, descriptor, new ServerProtocol.Request(UUID.randomUUID().toString(),
root.toString(), cwd.toString(), List.of(args), interactive));
} catch (ParameterException failure) { return parser.execute(args); }
catch (ProtocolException failure) { err.println(failure.getMessage()); return failure.exitCode(); }
catch (Exception failure) { err.println("Local AIE client failed: " + failure.getMessage()); return 1; }
finally { out.flush(); err.flush(); }
}
private void configure(CommandLine parser) {
parser.setOut(out).setErr(err);
parser.getSubcommands().values().forEach(this::configure);
}
private int forward(ServerManager manager, ServerState.Descriptor descriptor, ServerProtocol.Request request) throws IOException {
return new InvocationClient(manager,descriptor,request,input,out,err).run();
}
private ServerManager manager(EngineeringCli cli) { return new ServerManager(cli.selectedRoot()); }
@Command(name="start", mixinStandardHelpOptions=true, description="Start or reuse this project's local server; wait for readiness.")
public final class Start implements Callable<Integer> {
final EngineeringCli cli;
@Option(names="--idle-timeout-seconds", description="Stop after this many idle seconds; default 1800. Active operations are preserved.") Long idle;
@Option(names="--timeout-seconds", defaultValue="15") int timeout;
Start(EngineeringCli cli) { this.cli=cli; }
public Integer call() {
var descriptor = manager(cli).ensure(seconds(timeout), idle == null ? null : seconds(idle));
out.println("AIE server ready: project=" + descriptor.root() + " pid=" + descriptor.pid() + " port=" + descriptor.port()); return 0;
}
}
@Command(name="stop", mixinStandardHelpOptions=true, description="Drain and stop this project's server; already stopped is success.")
public final class Stop implements Callable<Integer> {
final EngineeringCli cli;
@Option(names="--timeout-seconds", defaultValue="30") int timeout;
Stop(EngineeringCli cli) { this.cli=cli; }
public Integer call() { manager(cli).stop(seconds(timeout)); out.println("AIE server stopped."); return 0; }
}
@Command(name="server", mixinStandardHelpOptions=true, description="Inspect the local server and recover or cancel request IDs.")
public final class Management {
final EngineeringCli cli;
Management(EngineeringCli cli) { this.cli=cli; }
@Command(name="status", mixinStandardHelpOptions=true)
int status() { out.println(ServerJson.encode(manager(cli).status())); return 0; }
@Command(name="request", mixinStandardHelpOptions=true)
int request(@Parameters(index="0") String id) throws IOException {
ServerProtocol.identifier(id);
var endpoint=manager(cli).ensure(15000,null);
out.println(ServerJson.encode(new ServerConnection(endpoint).call("GET","/requests/"+id,null,ServerProtocol.View.class))); return 0;
}
@Command(name="cancel", mixinStandardHelpOptions=true)
int cancel(@Parameters(index="0") String id) throws IOException {
ServerProtocol.identifier(id);
var state=manager(cli).state(); var endpoint=state.descriptor();
if (endpoint==null || !state.owned()) throw ProtocolException.missing("No running project server; inspect the request outcome before retrying");
out.println(ServerJson.encode(new ServerConnection(endpoint).call("POST","/cancel",new ServerProtocol.Cancel(id),ServerProtocol.View.class))); return 0;
}
}
private static long seconds(long value) {
if (value < 1 || value > 604800) throw ProtocolException.invalid("Timeout must be between 1 and 604800 seconds");
return value * 1000;
}
}
@@ -0,0 +1,150 @@
package net.intrepid.aiengineering.localserver;
import com.sun.net.httpserver.*;
import net.intrepid.aiengineering.filesystem.*;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
/** One authenticated loopback listener per canonical project, independent of HTTP sessions. */
public final class ProjectServer implements AutoCloseable {
private final ServerState state;
private final ServerState.Lease owner;
private final ServerProtocol.Operations operations;
private final SseStreams streams;
private final HttpServer http;
private final ExecutorService connections = new ThreadPoolExecutor(2, 8, 30, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(64), Thread.ofPlatform().daemon().name("aie-http-", 0).factory());
private final ScheduledExecutorService lifecycle = Executors.newSingleThreadScheduledExecutor(
Thread.ofPlatform().daemon().name("aie-lifecycle").factory());
private final CountDownLatch terminated = new CountDownLatch(1);
private final AtomicBoolean closed = new AtomicBoolean();
private final Object admission = new Object();
private final ServerState.Descriptor descriptor;
private final long idleMillis;
private volatile boolean draining;
private volatile long lastActive = System.nanoTime();
public ProjectServer(ServerState state, long idleMillis, ServerProtocol.Operations operations) {
if (idleMillis < 1) throw ProtocolException.invalid("Idle timeout must be positive");
this.state = state; this.idleMillis = idleMillis; this.operations = operations;
owner = state.lock("owner.lock", 0);
if (owner == null) throw ProtocolException.validation("A project server already owns this project");
streams=new SseStreams();
HttpServer listener = null;
try {
listener = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 32);
http = listener;
byte[] token = new byte[32]; new SecureRandom().nextBytes(token);
descriptor = new ServerState.Descriptor(ServerIdentity.PROTOCOL, ServerIdentity.BUILD,
state.root.toString(), UUID.randomUUID().toString(), ProcessHandle.current().pid(),
http.getAddress().getPort(), HexFormat.of().formatHex(token));
http.setExecutor(connections); http.createContext("/", this::handle);
http.start();
state.publish(descriptor); // Published only after command infrastructure and listener are ready.
lifecycle.scheduleWithFixedDelay(this::tick, 100, 100, TimeUnit.MILLISECONDS);
} catch (IOException | RuntimeException failure) {
if (listener != null) listener.stop(0);
connections.shutdownNow(); lifecycle.shutdownNow(); streams.close(); owner.close();
throw failure instanceof RuntimeException runtime ? runtime : new ProtocolException(1, "Cannot start loopback server: " + failure.getMessage());
}
}
public ServerState.Descriptor descriptor() { return descriptor; }
public int eventSubscribers() { return streams.active(); }
public ServerProtocol.Health health() {
return new ServerProtocol.Health(descriptor.protocol(), descriptor.build(), descriptor.root(),
descriptor.instance(), descriptor.pid(), draining, operations.active(), idleMillis, operations.pending());
}
public void await() throws InterruptedException { terminated.await(); }
public boolean await(long milliseconds) throws InterruptedException { return terminated.await(milliseconds, TimeUnit.MILLISECONDS); }
public void drain() { synchronized (admission) { draining = true; } }
private void tick() {
try {
synchronized (admission) {
if (operations.active() > 0) { lastActive = System.nanoTime(); return; }
if (!draining && (System.nanoTime() - lastActive) / 1_000_000 < idleMillis) return;
draining = true;
}
if(!streams.drained()) return;
close();
} catch (RuntimeException failure) { System.err.println("AIE server lifecycle failed: " + failure.getMessage()); }
}
private void handle(HttpExchange exchange) throws IOException {
boolean delegated=false;
try {
try {
String authorization = exchange.getRequestHeaders().getFirst("Authorization");
String expected = "Bearer " + descriptor.token();
if (!exchange.getRemoteAddress().getAddress().isLoopbackAddress() || authorization == null
|| !MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), authorization.getBytes(StandardCharsets.UTF_8))) {
reply(exchange, 403, new ServerProtocol.Error(4, "Local server authentication failed")); return;
}
if (exchange.getRequestHeaders().containsKey("Origin")) {
reply(exchange, 403, new ServerProtocol.Error(4, "Browser-origin requests are not supported")); return;
}
if (!descriptor.instance().equals(exchange.getRequestHeaders().getFirst("X-AIE-Instance"))) {
reply(exchange, 409, new ServerProtocol.Error(4, "Server instance changed; rediscover the endpoint")); return;
}
String path = exchange.getRequestURI().getPath(), method = exchange.getRequestMethod();
if (path.equals("/health") && method.equals("GET")) { reply(exchange, 200, health()); return; }
if (!Integer.toString(ServerIdentity.PROTOCOL).equals(exchange.getRequestHeaders().getFirst("X-AIE-Protocol"))) {
reply(exchange, 409, new ServerProtocol.Error(4, "Incompatible server protocol")); return;
}
if (path.equals("/stop") && method.equals("POST")) { drain(); reply(exchange, 200, health()); return; }
if (path.equals("/execute") && method.equals("POST")) {
var request = body(exchange, ServerProtocol.Request.class);
ServerProtocol.View result;
synchronized (admission) {
if (draining) { reply(exchange, 503, new ServerProtocol.Error(4, "Server is draining; no command was admitted")); return; }
if (!descriptor.root().equals(request.project())) throw ProtocolException.invalid("Request belongs to another project");
lastActive = System.nanoTime();
result=operations.submit(request);
}
reply(exchange,200,result);
return;
}
if(path.startsWith("/requests/") && path.endsWith("/events") && method.equals("GET")) {
String id=ServerProtocol.identifier(path.substring("/requests/".length(),path.length()-"/events".length()));
String cursor=exchange.getRequestHeaders().getFirst("Last-Event-ID");
JobEvents.validateCursor(cursor);
streams.open(exchange,id,cursor,operations.events(id)); delegated=true; return;
}
if (path.startsWith("/requests/") && method.equals("GET")) {
reply(exchange, 200, operations.get(ServerProtocol.identifier(path.substring("/requests/".length())))); return;
}
if (path.equals("/input") && method.equals("POST")) { reply(exchange, 200, operations.input(body(exchange, ServerProtocol.Input.class))); return; }
if (path.equals("/cancel") && method.equals("POST")) { reply(exchange, 200, operations.cancel(body(exchange, ServerProtocol.Cancel.class).id())); return; }
reply(exchange, 404, new ServerProtocol.Error(3, "Unknown local-server operation"));
} catch (ProtocolException failure) {
reply(exchange, failure.exitCode() == 3 ? 404 : 400, new ServerProtocol.Error(failure.exitCode(), failure.getMessage()));
} catch (RuntimeException failure) {
reply(exchange, 500, new ServerProtocol.Error(1, "Local server operation failed"));
}
} finally { if(!delegated) exchange.close(); }
}
private <T> T body(HttpExchange exchange, Class<T> type) throws IOException {
if (!"application/json".equals(exchange.getRequestHeaders().getFirst("Content-Type")))
throw ProtocolException.invalid("Expected application/json");
byte[] bytes = exchange.getRequestBody().readNBytes(1024 * 1024 + 1);
if (bytes.length > 1024 * 1024) throw ProtocolException.invalid("Local request exceeds 1 MiB");
return ServerJson.decode(new String(bytes, StandardCharsets.UTF_8), type);
}
private static void reply(HttpExchange exchange, int code, Object value) throws IOException {
byte[] bytes = ServerJson.encode(value).getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
exchange.getResponseHeaders().set("Cache-Control", "no-store");
exchange.sendResponseHeaders(code, bytes.length);
exchange.getResponseBody().write(bytes);
}
@Override public void close() {
if (!closed.compareAndSet(false, true)) return;
drain();
try { streams.close(); http.stop(0); operations.close(); state.removeDescriptor(descriptor.instance()); }
finally { connections.shutdownNow(); lifecycle.shutdown(); owner.close(); terminated.countDown(); }
}
}
@@ -0,0 +1,27 @@
package net.intrepid.aiengineering.localserver;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import java.io.PrintWriter;
/** Verify overlaps before printing; snapshots and resumed deltas cannot silently repeat or replace output. */
public final class RemoteOutput {
private final StringBuilder stdout=new StringBuilder(),stderr=new StringBuilder();
private final PrintWriter out,err;
public RemoteOutput(PrintWriter out,PrintWriter err){this.out=out;this.err=err;}
private void append(StringBuilder previous,PrintWriter writer,int offset,String text,boolean snapshot) {
if(offset<0 || offset>previous.length() || (snapshot && (offset!=0 || text.length()<previous.length())))
throw ProtocolException.validation("Recovered request output has a gap; inspect the request outcome before retrying");
int overlap=Math.min(previous.length()-offset,text.length());
for(int i=0;i<overlap;i++)if(previous.charAt(offset+i)!=text.charAt(i))
throw ProtocolException.validation("Recovered request output differs from the delivered prefix; inspect the request outcome");
String suffix=text.substring(overlap);previous.append(suffix);writer.print(suffix);writer.flush();
}
public void accept(ServerProtocol.Event event) {
boolean snapshot=event.kind().equals("snapshot");
append(stdout,out,event.stdoutOffset(),event.stdout(),snapshot);
append(stderr,err,event.stderrOffset(),event.stderr(),snapshot);
}
public void snapshot(ServerProtocol.View view) {
append(stdout,out,0,view.stdout(),true);append(stderr,err,0,view.stderr(),true);
}
}
@@ -0,0 +1,251 @@
package net.intrepid.aiengineering.localserver;
import net.intrepid.aiengineering.cli.EngineeringCli;
import net.intrepid.aiengineering.filesystem.*;
import picocli.CommandLine;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/** Invocation-scoped state and durable mutation outcomes, separate from canonical Work memory. */
public final class RequestJobs implements ServerProtocol.Operations {
public record Receipt(String id, String fingerprint, String state, int exitCode,
String stdout, String stderr, boolean cancellationRequested) {}
@FunctionalInterface public interface Runner {
int run(ServerProtocol.Request request, Reader input, PrintWriter out, PrintWriter err) throws Exception;
}
private static final int MAX_CHARS = 8 * 1024 * 1024;
private final ServerState files;
private final Runner runner;
private final Map<String, Job> jobs = new ConcurrentHashMap<>();
private final Queue<String> completed = new ConcurrentLinkedQueue<>();
private final AtomicInteger active = new AtomicInteger();
private final ExecutorService commands = new ThreadPoolExecutor(4, 4, 30, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(64), Thread.ofPlatform().daemon().name("aie-command-", 0).factory());
private final ExecutorService longCommands = new ThreadPoolExecutor(0, 4, 30, TimeUnit.SECONDS,
new SynchronousQueue<>(), Thread.ofPlatform().daemon().name("aie-job-", 0).factory());
public RequestJobs(ServerState files) {
this(files, (request, input, out, err) -> new EngineeringCli(Path.of(request.cwd()), input, request.interactive())
.execute(out, err, request.argv().toArray(String[]::new)));
}
public RequestJobs(ServerState files, Runner runner) {
this.files = files; this.runner = runner; files.initialize();
Filespace.directory(files.file("requests")); ServerState.permissions(files.file("requests"), "rwx------");
}
private Path receipt(String id) { return files.file("requests/" + ServerProtocol.identifier(id) + ".json"); }
private Receipt stored(String id) {
Path path = receipt(id);
if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) return null;
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Filespace.io(() -> Files.size(path)) > 128 * 1024 * 1024)
throw ProtocolException.validation("Invalid local request receipt");
var value = ServerJson.decode(Filespace.read(path), Receipt.class);
if (!id.equals(value.id()) || value.fingerprint() == null || !value.fingerprint().matches("[a-f0-9]{64}")
|| value.stdout() == null || value.stderr() == null || value.state() == null
|| !Set.of("QUEUED", "RUNNING", "COMPLETED", "UNKNOWN").contains(value.state())
|| (value.state().equals("COMPLETED") && value.exitCode() < 0))
throw ProtocolException.validation("Invalid local request receipt identity");
return value;
}
private ServerProtocol.View view(Receipt value) {
boolean complete = value.state().equals("COMPLETED");
return new ServerProtocol.View(value.id(), complete ? "COMPLETED" : "UNKNOWN", complete ? value.exitCode() : 4,
value.stdout(), value.stderr() + (complete ? "" : "\nRequest outcome unknown after server interruption; inspect effects before submitting another mutation.\n"),
0, false, value.cancellationRequested());
}
@Override public ServerProtocol.View submit(ServerProtocol.Request request) {
Job selected;
synchronized (this) {
selected = jobs.get(request.id());
if (selected != null) {
if (!selected.request.fingerprint().equals(request.fingerprint())) throw ProtocolException.invalid("Request ID already used for different input");
} else {
var previous = stored(request.id());
if (previous != null) {
if (!previous.fingerprint().equals(request.fingerprint())) throw ProtocolException.invalid("Request ID already used for different input");
return view(previous); // Never replay an interrupted mutation.
}
if (active.get() >= 68) throw ProtocolException.validation("Project command queue is full; no command was admitted");
Path cwd = Filespace.io(() -> Path.of(request.cwd()).toRealPath());
var cli = new EngineeringCli(cwd, Reader.nullReader(), request.interactive());
boolean readOnly = false, longRunning = false;
try {
var parsed = cli.commandLineFor(new PrintWriter(Writer.nullWriter()), new PrintWriter(Writer.nullWriter()), request.argv().toArray(String[]::new))
.parseArgs(request.argv().toArray(String[]::new));
if (InvocationPolicy.local(parsed)) throw ProtocolException.invalid("Bootstrap commands execute in the local client");
if (!cli.selectedRoot().equals(files.root) || !request.project().equals(files.root.toString()))
throw ProtocolException.invalid("Request belongs to another project");
readOnly = InvocationPolicy.readOnly(parsed);
longRunning = Set.of("agent run", "survey ask").contains(InvocationPolicy.path(parsed));
} catch (CommandLine.ParameterException invalid) {
// The normal CLI will render the original parse diagnostic and return its exit code.
}
selected = new Job(request, !readOnly);
if (selected.durable) selected.persist("QUEUED", -1);
jobs.put(request.id(), selected); active.incrementAndGet();
try { (longRunning ? longCommands : commands).execute(selected); }
catch (RejectedExecutionException full) { selected.failAdmission(); }
}
}
return selected.awaitView(60);
}
@Override public ServerProtocol.View get(String id) {
ServerProtocol.identifier(id);
var job = jobs.get(id);
if (job != null) return job.awaitView(100);
var receipt = stored(id);
if (receipt == null) throw ProtocolException.missing("Local request not found: " + id);
return view(receipt);
}
@Override public ServerProtocol.EventSource events(String id) {
ServerProtocol.identifier(id);
var job=jobs.get(id);
if (job!=null) return job.events;
var receipt=stored(id);
if (receipt==null) throw ProtocolException.missing("Local request not found: "+id);
return JobEvents.completed(view(receipt));
}
@Override public ServerProtocol.View input(ServerProtocol.Input input) {
var job = jobs.get(input.id());
if (job == null) throw ProtocolException.missing("Active input request not found");
synchronized (job) {
if (input.sequence() == job.acceptedInput) return job.snapshot();
if (!job.needsInput || input.sequence() != job.inputSequence) throw ProtocolException.invalid("Stale input sequence");
if (input.text() != null && input.text().length() > MAX_CHARS) throw ProtocolException.invalid("Input exceeds local limit");
job.acceptedInput = input.sequence(); job.needsInput = false;
if (input.text() == null) job.eof = true;
else job.pendingInput.append(input.text());
job.publishStatus(); return job.snapshot();
}
}
@Override public ServerProtocol.View cancel(String id) {
var job = jobs.get(ServerProtocol.identifier(id));
if (job == null) return get(id);
synchronized (job) {
if (!job.terminal()) {
job.cancellation = true;
if (job.thread != null) job.thread.interrupt();
job.publishStatus();
}
return job.snapshot();
}
}
@Override public int active() { return active.get(); }
@Override public List<String> pending() {
return jobs.values().stream().filter(job -> !job.terminal()).map(job -> job.request.id()).sorted().toList();
}
@Override public void close() {
commands.shutdown(); longCommands.shutdown();
if (active.get() > 0) jobs.values().forEach(job -> cancel(job.request.id()));
}
private final class Job implements Runnable {
final ServerProtocol.Request request;
final boolean durable;
final StringBuilder stdout = new StringBuilder(), stderr = new StringBuilder(), pendingInput = new StringBuilder();
String state = "QUEUED";
int exit = -1, inputSequence, acceptedInput;
boolean cancellation, needsInput, eof;
Thread thread;
final JobEvents events;
Job(ServerProtocol.Request request, boolean durable) {
this.request = request; this.durable = durable; events=new JobEvents(this,this::snapshot);
}
void publishStatus() {
String kind=state.equals("COMPLETED")?"completed":state.equals("UNKNOWN")?"unknown":needsInput?"input-required":"progress";
events.publish(kind,stdout.length(),stderr.length(),"","",metadata());
}
ServerProtocol.View metadata() {
return new ServerProtocol.View(request.id(),state,exit,"","",inputSequence,needsInput,cancellation);
}
void append(StringBuilder target, char[] value, int offset, int length) {
while (length>0) {
int count=Math.min(length,JobEvents.CHUNK_CHARS);
int outOffset=stdout.length(),errOffset=stderr.length();
String text=new String(value,offset,count); target.append(text);
events.publish(target==stdout?"stdout":"stderr",outOffset,errOffset,
target==stdout?text:"",target==stderr?text:"",metadata());
offset+=count; length-=count;
}
}
void error(String text) {
char[] chars=text.toCharArray(); append(stderr,chars,0,chars.length);
}
synchronized boolean terminal() { return state.equals("COMPLETED") || state.equals("UNKNOWN"); }
synchronized ServerProtocol.View snapshot() {
return new ServerProtocol.View(request.id(), state, exit, stdout.toString(), stderr.toString(), inputSequence, needsInput, cancellation);
}
synchronized ServerProtocol.View awaitView(long millis) {
long deadline = System.nanoTime() + millis * 1_000_000;
while (!terminal() && !needsInput && System.nanoTime() < deadline) {
try { TimeUnit.NANOSECONDS.timedWait(this, Math.max(1, deadline - System.nanoTime())); }
catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); break; }
}
return snapshot();
}
synchronized void persist(String state, int exit) {
ServerState.write(receipt(request.id()), ServerJson.encode(new Receipt(request.id(), request.fingerprint(), state,
exit, stdout.toString(), stderr.toString(), cancellation)));
}
PrintWriter writer(StringBuilder target) {
return new PrintWriter(new Writer() {
public void write(char[] value, int offset, int length) {
synchronized (Job.this) {
if (target.length() + length > MAX_CHARS) throw ProtocolException.validation("Command output exceeds 8 MiB characters per stream");
Job.this.append(target,value,offset,length);
}
}
public void flush() {}
public void close() {}
}, true);
}
Reader reader() {
return new Reader() {
public int read(char[] value, int offset, int length) throws IOException {
if (length == 0) return 0;
synchronized (Job.this) {
while (pendingInput.isEmpty() && !eof) {
if (!request.interactive()) return -1;
if (cancellation) throw new IOException("Input cancelled; prior effects may exist");
if (!needsInput) { needsInput = true; inputSequence++; publishStatus(); }
try { Job.this.wait(); }
catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new IOException("Input interrupted; prior effects may exist"); }
}
if (pendingInput.isEmpty()) return -1;
int count = Math.min(length, pendingInput.length());
pendingInput.getChars(0, count, value, offset); pendingInput.delete(0, count); return count;
}
}
public void close() {}
};
}
@Override public void run() {
synchronized (this) { state = "RUNNING"; thread = Thread.currentThread(); publishStatus(); }
int result;
try {
synchronized (this) { if (cancellation) throw ProtocolException.validation("Command cancelled before execution"); }
result = runner.run(request, reader(), writer(stdout), writer(stderr));
} catch (Exception failure) {
result = failure instanceof ProtocolException protocol ? protocol.exitCode() : 1;
synchronized (this) {
String message=failure.getMessage()==null?"Command failed":failure.getMessage();
error("\n"+message.substring(0,Math.min(message.length(),1024))+"\n");
}
} finally { Thread.interrupted(); /* Receipt publication must not inherit a cancelled channel's interrupt. */ }
finish(result);
}
void failAdmission() { synchronized (this) { error("Project worker capacity exceeded; command was not executed.\n"); } finish(4); }
void finish(int result) {
synchronized (this) {
// Persist read results too: evicting the bounded RAM cache must not lose a client's result.
try { persist("COMPLETED", result); state = "COMPLETED"; exit = result; }
catch (RuntimeException failure) { error("\nCannot publish command outcome; inspect effects before retry.\n"); state = "UNKNOWN"; exit = 4; }
thread = null; needsInput = false; publishStatus();
}
active.decrementAndGet();
if (state.equals("COMPLETED")) { jobs.remove(request.id(), this); return; }
completed.add(request.id());
while (completed.size() > 64) { String id = completed.poll(); if (id != null) jobs.remove(id); }
}
}
}
@@ -0,0 +1,75 @@
package net.intrepid.aiengineering.localserver;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
/** Direct loopback transport: no proxy, redirects, Spring context or shell. */
public final class ServerConnection {
private final ServerState.Descriptor descriptor;
public ServerConnection(ServerState.Descriptor descriptor) { this.descriptor = descriptor; }
private HttpURLConnection open(String method,String path) throws IOException {
var connection = (HttpURLConnection) URI.create("http://127.0.0.1:" + descriptor.port() + path)
.toURL().openConnection(Proxy.NO_PROXY);
connection.setConnectTimeout(1000); connection.setReadTimeout(5000);
connection.setInstanceFollowRedirects(false); connection.setRequestMethod(method);
connection.setRequestProperty("Authorization", "Bearer " + descriptor.token());
connection.setRequestProperty("X-AIE-Instance", descriptor.instance());
connection.setRequestProperty("X-AIE-Protocol", Integer.toString(ServerIdentity.PROTOCOL));
return connection;
}
public <T> T call(String method, String path, Object body, Class<T> type) throws IOException {
var connection=open(method,path);
if (body != null) {
byte[] bytes = ServerJson.encode(body).getBytes(StandardCharsets.UTF_8);
connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json");
connection.setFixedLengthStreamingMode(bytes.length);
try (var output = connection.getOutputStream()) { output.write(bytes); }
}
int status = connection.getResponseCode();
InputStream stream = status >= 400 ? connection.getErrorStream() : connection.getInputStream();
if (stream == null) throw new IOException("Local server returned HTTP " + status);
String text;
try (stream) {
byte[] bytes = stream.readNBytes(128 * 1024 * 1024 + 1);
if (bytes.length > 128 * 1024 * 1024) throw new IOException("Local server response exceeds 128 MiB");
text = new String(bytes, StandardCharsets.UTF_8);
}
if (status != 200) {
var error = ServerJson.decode(text, ServerProtocol.Error.class);
throw new ProtocolException(error.exitCode(), error.message());
}
return ServerJson.decode(text, type);
}
public EventStream events(String id,String cursor) throws IOException {
ServerProtocol.identifier(id);JobEvents.validateCursor(cursor);
var connection=open("GET","/requests/"+id+"/events");
connection.setRequestProperty("Accept","text/event-stream");
if(cursor!=null)connection.setRequestProperty("Last-Event-ID",cursor);
try {
int status=connection.getResponseCode();
if(status!=200) {
var stream=connection.getErrorStream();
if(stream==null)throw new IOException("SSE returned HTTP "+status);
try(stream) {
var error=ServerJson.decode(new String(stream.readNBytes(16384),StandardCharsets.UTF_8),ServerProtocol.Error.class);
throw new ProtocolException(error.exitCode(),error.message());
}
}
String content=connection.getContentType();
if(content==null || !content.split(";",2)[0].equalsIgnoreCase("text/event-stream"))
throw ProtocolException.validation("Expected an SSE event stream for "+id);
var decoder=StandardCharsets.UTF_8.newDecoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT);
return new EventStream(connection,new SseReader(new InputStreamReader(connection.getInputStream(),decoder),id));
}catch(IOException | RuntimeException failure){connection.disconnect();throw failure;}
}
public static final class EventStream implements AutoCloseable {
private final HttpURLConnection connection;
private final SseReader reader;
private EventStream(HttpURLConnection connection,SseReader reader){this.connection=connection;this.reader=reader;}
public ServerProtocol.Event next() throws IOException{return reader.next();}
@Override public void close(){connection.disconnect();try{reader.close();}catch(IOException alreadyClosed){/* Socket is detached. */}}
}
public ServerProtocol.Health health() throws IOException { return call("GET", "/health", null, ServerProtocol.Health.class); }
}
@@ -0,0 +1,21 @@
package net.intrepid.aiengineering.localserver;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
public final class ServerIdentity {
public static final int PROTOCOL = 1;
public static final String BUILD = build();
private ServerIdentity() {}
public static String hash(String value) {
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); }
catch (java.security.NoSuchAlgorithmException failure) { throw new IllegalStateException(failure); }
}
private static String build() {
try (var input = ServerIdentity.class.getResourceAsStream("/aie-build.txt")) {
return input == null ? hash("development-unpackaged") : new String(input.readAllBytes(), StandardCharsets.UTF_8).strip();
} catch (IOException failure) { throw new IllegalStateException("Cannot read server build identity", failure); }
}
}
@@ -0,0 +1,20 @@
package net.intrepid.aiengineering.localserver;
import tools.jackson.databind.json.JsonMapper;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.core.StreamReadFeature;
import net.intrepid.aiengineering.filesystem.ProtocolException;
/** Transport-only JSON: the lightweight path must not initialize the YAML/domain codecs. */
public final class ServerJson {
private static final JsonMapper JSON = JsonMapper.builder()
.enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, DeserializationFeature.FAIL_ON_TRAILING_TOKENS,
DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES).build();
private ServerJson() {}
public static String encode(Object value) { return JSON.writeValueAsString(value); }
public static <T> T decode(String text, Class<T> type) {
try { return JSON.readValue(text, type); }
catch (RuntimeException failure) { throw ProtocolException.invalid("Invalid local-server " + type.getSimpleName()); }
}
}
@@ -0,0 +1,30 @@
package net.intrepid.aiengineering.localserver;
import java.nio.file.*;
import java.util.*;
import net.intrepid.aiengineering.filesystem.ProtocolException;
/** Re-executes this installed package, never a shell or project-supplied executable. */
public final class ServerLaunch {
public static final String INTERNAL = "--aie-internal-server";
private ServerLaunch() {}
public static List<String> current() {
var info = ProcessHandle.current().info();
String executable = info.command().orElseThrow(() -> ProtocolException.invalid("Cannot locate AIE executable"));
if (System.getProperty("org.graalvm.nativeimage.imagecode") != null) return List.of(executable);
var arguments = List.of(info.arguments().orElse(new String[0]));
int jar = arguments.indexOf("-jar");
if (jar >= 0 && jar + 1 < arguments.size()) return jar(Path.of(arguments.get(jar + 1)));
return List.of(executable, "--enable-native-access=ALL-UNNAMED", "-cp", absoluteClasspath(),
"net.intrepid.aiengineering.AieLauncher");
}
public static List<String> jar(Path jar) {
return List.of(Path.of(System.getProperty("java.home"), "bin", "java").toString(),
"--enable-native-access=ALL-UNNAMED", "-jar", jar.toAbsolutePath().normalize().toString());
}
private static String absoluteClasspath() {
return Arrays.stream(System.getProperty("java.class.path").split(java.io.File.pathSeparator))
.map(value -> Path.of(value).toAbsolutePath().normalize().toString())
.collect(java.util.stream.Collectors.joining(java.io.File.pathSeparator));
}
}
@@ -0,0 +1,107 @@
package net.intrepid.aiengineering.localserver;
import net.intrepid.aiengineering.filesystem.*;
import java.io.*;
import java.nio.file.*;
import java.util.*;
/** Coordinates startup/replacement without killing processes or trusting PIDs as ownership. */
public final class ServerManager {
public static final long DEFAULT_IDLE_MILLIS = 30 * 60 * 1000L;
public record Status(String state, ServerProtocol.Health server) {}
private final ServerState state;
private final List<String> launcher;
public ServerManager(Path root) { this(root, ServerLaunch.current()); }
public ServerManager(Path root, List<String> launcher) { state = new ServerState(root); this.launcher = List.copyOf(launcher); }
public ServerState state() { return state; }
public Status status() {
var descriptor = state.descriptor();
if (descriptor == null) return new Status(Files.exists(state.directory) && state.owned() ? "STARTING" : "STOPPED", null);
if (!state.owned()) return new Status("STOPPED", null);
try { return new Status("RUNNING", health(descriptor)); }
catch (IOException unavailable) { return new Status("UNREACHABLE", null); }
}
private ServerProtocol.Health health(ServerState.Descriptor descriptor) throws IOException {
var health = new ServerConnection(descriptor).health();
if (!health.project().equals(state.root.toString()) || !health.instance().equals(descriptor.instance())
|| health.pid() != descriptor.pid() || !health.build().equals(descriptor.build()) || health.protocol() != descriptor.protocol())
throw ProtocolException.validation("Local server identity does not match its descriptor");
return health;
}
public ServerState.Descriptor ensure(long timeoutMillis, Long requestedIdleMillis) {
if (timeoutMillis < 1 || (requestedIdleMillis != null && requestedIdleMillis < 1)) throw ProtocolException.invalid("Server timeouts must be positive");
long deadline = System.nanoTime() + timeoutMillis * 1_000_000;
try (var start = state.lock("startup.lock", timeoutMillis)) {
if (start == null) throw ProtocolException.validation("Timed out waiting for project server startup lock; no command sent");
var descriptor = state.descriptor();
if (descriptor != null && state.owned()) {
try {
var health = health(descriptor);
if (descriptor.compatible() && !health.draining()
&& (requestedIdleMillis == null || health.idleMillis() == requestedIdleMillis)) return descriptor;
if (descriptor.protocol() != ServerIdentity.PROTOCOL)
throw ProtocolException.validation("Incompatible server protocol; stop it with its matching AIE version");
new ServerConnection(descriptor).call("POST", "/stop", null, ServerProtocol.Health.class);
} catch (IOException unavailable) {
throw ProtocolException.validation("Project server owns its lock but is unreachable; inspect " + state.file("startup.log"));
}
waitUnowned(deadline);
} else if (state.owned()) {
// A manually started process may own the lock before it publishes readiness.
return waitReady(deadline, null);
}
descriptor = state.descriptor();
if (descriptor != null) state.removeDescriptor(descriptor.instance());
long idle = requestedIdleMillis == null ? DEFAULT_IDLE_MILLIS : requestedIdleMillis;
var command = new ArrayList<>(launcher);
command.addAll(List.of(ServerLaunch.INTERNAL, state.root.toString(), Long.toString(idle)));
Path log = state.file("startup.log");
ServerState.write(log, "");
final Process process;
try {
process = new ProcessBuilder(command).directory(state.root.toFile())
.redirectOutput(log.toFile()).redirectErrorStream(true).start();
process.getOutputStream().close();
} catch (IOException failure) { throw new ProtocolException(1, "Cannot launch project server: " + failure.getMessage()); }
return waitReady(deadline, process);
}
}
private ServerState.Descriptor waitReady(long deadline, Process child) {
do {
var descriptor = state.descriptor();
if (descriptor != null && descriptor.compatible() && state.owned()) {
try { if (!health(descriptor).draining()) return descriptor; }
catch (IOException transientFailure) { /* Listener may be finishing startup. */ }
}
if (child != null && !child.isAlive())
throw ProtocolException.validation("Project server failed to start (exit " + child.exitValue() + "); inspect " + state.file("startup.log"));
pause();
} while (System.nanoTime() < deadline);
throw ProtocolException.validation("Project server readiness timed out; no command sent. Inspect " + state.file("startup.log"));
}
public void stop(long timeoutMillis) {
if (timeoutMillis < 1) throw ProtocolException.invalid("Stop timeout must be positive");
if (!Files.exists(state.directory)) return;
long deadline = System.nanoTime() + timeoutMillis * 1_000_000;
try (var start = state.lock("startup.lock", timeoutMillis)) {
if (start == null) throw ProtocolException.validation("Timed out waiting for server management lock");
var descriptor = state.descriptor();
if (!state.owned()) { if (descriptor != null) state.removeDescriptor(descriptor.instance()); return; }
if (descriptor == null) throw ProtocolException.validation("Project server is starting; wait for readiness before stopping");
if (descriptor.protocol() != ServerIdentity.PROTOCOL) throw ProtocolException.validation("Stop this server with its matching AIE version");
try { health(descriptor); new ServerConnection(descriptor).call("POST", "/stop", null, ServerProtocol.Health.class); }
catch (IOException failure) { throw ProtocolException.validation("Server is unreachable; no process was killed"); }
waitUnowned(deadline);
}
}
private void waitUnowned(long deadline) {
while (state.owned()) {
if (System.nanoTime() >= deadline) throw ProtocolException.validation("Server is draining; active operations were not killed. Retry after they finish");
pause();
}
}
private static void pause() {
try { Thread.sleep(20); }
catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw ProtocolException.validation("Interrupted waiting for project server"); }
}
}
@@ -0,0 +1,49 @@
package net.intrepid.aiengineering.localserver;
import java.util.*;
import net.intrepid.aiengineering.filesystem.ProtocolException;
public final class ServerProtocol {
private ServerProtocol() {}
public record Request(String id, String project, String cwd, List<String> argv, boolean interactive) {
public Request {
identifier(id);
if (project == null || cwd == null || argv == null || argv.isEmpty() || argv.size() > 1024
|| argv.stream().anyMatch(Objects::isNull)) throw ProtocolException.invalid("Invalid command envelope");
argv = List.copyOf(argv);
}
public String fingerprint() { return ServerIdentity.hash(ServerJson.encode(this)); }
}
public record Health(int protocol, String build, String project, String instance, long pid,
boolean draining, int active, long idleMillis, List<String> requests) {}
public record View(String id, String state, int exitCode, String stdout, String stderr,
int inputSequence, boolean needsInput, boolean cancellationRequested) {}
public record Input(String id, int sequence, String text) { public Input { identifier(id); } }
public record Cancel(String id) { public Cancel { identifier(id); } }
public record Error(int exitCode, String message) {}
/** Offsets are UTF-16 character offsets, matching View and Java's invocation writers. */
public record Event(String id, String cursor, String kind, int stdoutOffset, int stderrOffset,
String stdout, String stderr, String state, int exitCode, int inputSequence,
boolean needsInput, boolean cancellationRequested) {
public boolean terminal() { return state.equals("COMPLETED") || state.equals("UNKNOWN"); }
}
@FunctionalInterface public interface EventSource extends AutoCloseable {
Event next(String cursor, long timeoutMillis) throws InterruptedException;
@Override default void close() {}
}
public static String identifier(String id) {
if (id == null || !id.matches("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"))
throw ProtocolException.invalid("Invalid local request ID");
return id;
}
public interface Operations extends AutoCloseable {
View submit(Request request);
View get(String id);
View input(Input input);
View cancel(String id);
default EventSource events(String id) { return JobEvents.completed(get(id)); }
int active();
default List<String> pending() { return List.of(); }
@Override default void close() {}
}
}
@@ -0,0 +1,100 @@
package net.intrepid.aiengineering.localserver;
import net.intrepid.aiengineering.filesystem.*;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.UUID;
import static java.nio.file.StandardOpenOption.*;
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
/** Private operational state. No canonical Work or database schema changes. */
public final class ServerState {
public record Descriptor(int protocol, String build, String root, String instance, long pid, int port, String token) {
public Descriptor {
if (protocol < 1 || build == null || !build.matches("[a-f0-9]{64}") || root == null
|| !Path.of(root).isAbsolute() || pid < 1 || port < 1 || port > 65535
|| token == null || !token.matches("[a-f0-9]{64}")) throw ProtocolException.invalid("Invalid server descriptor");
UUID.fromString(instance);
}
public boolean compatible() { return protocol == ServerIdentity.PROTOCOL && build.equals(ServerIdentity.BUILD); }
}
public final Path root;
public final Path directory;
public ServerState(Path root) {
this.root = Filespace.io(() -> root.toRealPath());
directory = Filespace.resolve(this.root, ".ai-engineering/.local/server");
}
public void initialize() {
Filespace.resolve(root, ".ai-engineering/.local/server");
Filespace.directory(directory); permissions(directory, "rwx------");
}
public Path file(String name) { return Filespace.resolve(root, ".ai-engineering/.local/server/" + name); }
public Descriptor descriptor() {
Path path = file("endpoint.json");
if (!Files.exists(path, NOFOLLOW_LINKS)) return null;
if (!Files.isRegularFile(path, NOFOLLOW_LINKS) || Filespace.io(() -> Files.size(path)) > 8192)
throw ProtocolException.validation("Invalid server descriptor; inspect " + path);
var descriptor = ServerJson.decode(Filespace.read(path), Descriptor.class);
if (!descriptor.root().equals(root.toString())) throw ProtocolException.validation("Server descriptor belongs to another project");
return descriptor;
}
public void publish(Descriptor descriptor) { write(file("endpoint.json"), ServerJson.encode(descriptor)); }
public void removeDescriptor(String instance) {
var current = descriptor();
if (current != null && current.instance().equals(instance)) Filespace.io(() -> Files.deleteIfExists(file("endpoint.json")));
}
public Lease lock(String name, long timeoutMillis) {
initialize();
return Filespace.io(() -> {
var channel = FileChannel.open(file(name), CREATE, WRITE, NOFOLLOW_LINKS);
permissions(file(name), "rw-------");
long deadline = System.nanoTime() + timeoutMillis * 1_000_000;
try {
do {
try { var lock = channel.tryLock(); if (lock != null) return new Lease(channel, lock); }
catch (OverlappingFileLockException busy) { /* Same-process contender is also an owner. */ }
if (System.nanoTime() >= deadline) break;
try { Thread.sleep(20); }
catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new IOException("Interrupted waiting for server lock"); }
} while (true);
} catch (Throwable failure) { channel.close(); throw failure; }
channel.close(); return null;
});
}
public boolean owned() {
try (var lease = lock("owner.lock", 0)) { return lease == null; }
}
public static final class Lease implements AutoCloseable {
private final FileChannel channel;
private final FileLock lock;
private Lease(FileChannel channel, FileLock lock) { this.channel = channel; this.lock = lock; }
@Override public void close() { Filespace.io(() -> { try { lock.release(); } finally { channel.close(); } return null; }); }
}
public static void write(Path path, String value) {
Filespace.io(() -> {
if (Files.isSymbolicLink(path)) throw ProtocolException.invalid("Symlink rejected: " + path);
Path temporary = path.resolveSibling("." + path.getFileName() + "." + UUID.randomUUID() + ".tmp");
try {
// Create private before writing capability tokens or command results.
try (var channel = FileChannel.open(temporary, CREATE_NEW, WRITE, NOFOLLOW_LINKS)) {
permissions(temporary, "rw-------");
var bytes = ByteBuffer.wrap(value.getBytes(StandardCharsets.UTF_8));
while (bytes.hasRemaining()) channel.write(bytes);
channel.force(true);
}
Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
try (var directory = FileChannel.open(path.getParent(), READ)) { directory.force(true); }
} finally { Files.deleteIfExists(temporary); }
return null;
});
}
static void permissions(Path path, String mode) {
try { Files.setPosixFilePermissions(path, PosixFilePermissions.fromString(mode)); }
catch (UnsupportedOperationException ignored) { /* Windows inherits the user's private project ACL. */ }
catch (IOException failure) { throw new ProtocolException(1, "Cannot protect local server state: " + path); }
}
}
@@ -0,0 +1,17 @@
package net.intrepid.aiengineering.localserver;
/** ASCII JSON escapes preserve UTF-16 offsets, including surrogate pairs split across writer calls. */
public final class SseFrames {
private static final char[] HEX="0123456789abcdef".toCharArray();
private SseFrames() {}
public static String encode(ServerProtocol.Event event) {
String json=ServerJson.encode(event);
var data=new StringBuilder(json.length());
for(int i=0;i<json.length();i++) {
char c=json.charAt(i);
if(c<128) data.append(c);
else data.append("\\u").append(HEX[c>>>12]).append(HEX[(c>>>8)&15]).append(HEX[(c>>>4)&15]).append(HEX[c&15]);
}
return "id: "+event.cursor()+"\nevent: "+event.kind()+"\ndata: "+data+"\n\n";
}
}
@@ -0,0 +1,58 @@
package net.intrepid.aiengineering.localserver;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import java.io.*;
import java.util.Set;
/** Incremental SSE framing; a blank comment frame returns null, an incomplete/disconnected frame throws. */
public final class SseReader implements AutoCloseable {
private static final int MAX_FRAME_CHARS=128*1024*1024;
private static final Set<String> KINDS=Set.of("snapshot","stdout","stderr","progress","input-required","completed","unknown");
private final BufferedReader reader;
private final String requestId;
private boolean skipLf;
private int consumed;
public SseReader(Reader reader,String requestId) { this.reader=new BufferedReader(reader);this.requestId=ServerProtocol.identifier(requestId); }
private String line() throws IOException {
var line=new StringBuilder();
while(true) {
int value=reader.read();
if(value<0)throw new EOFException("SSE disconnected before a terminal event for "+requestId);
if(skipLf && value=='\n'){skipLf=false;continue;}skipLf=false;
if(++consumed>MAX_FRAME_CHARS)throw ProtocolException.validation("SSE frame exceeds 128 Mi characters");
if(value=='\r'){skipLf=true;return line.toString();}
if(value=='\n')return line.toString();
line.append((char)value);
}
}
public ServerProtocol.Event next() throws IOException {
consumed=0;String cursor=null,kind=null;var data=new StringBuilder();
while(true) {
String line=line();
if(line.isEmpty()) {
if(data.isEmpty())return null;
var event=ServerJson.decode(data.toString(),ServerProtocol.Event.class);
JobEvents.validateCursor(event.cursor());
if(!requestId.equals(event.id()) || event.cursor()==null || !event.cursor().equals(cursor)
|| kind==null || !KINDS.contains(kind) || !kind.equals(event.kind()) || event.stdout()==null || event.stderr()==null
|| event.stdoutOffset()<0 || event.stderrOffset()<0 || event.inputSequence()<0 || event.state()==null
|| !Set.of("QUEUED","RUNNING","COMPLETED","UNKNOWN").contains(event.state())
|| (event.terminal() && event.exitCode()<0) || (event.needsInput() && event.inputSequence()==0)
|| (kind.equals("completed") && !event.state().equals("COMPLETED"))
|| (kind.equals("unknown") && !event.state().equals("UNKNOWN")))
throw ProtocolException.validation("Invalid SSE event identity/state for "+requestId);
return event;
}
if(line.startsWith(":"))continue;
int colon=line.indexOf(':');String field=colon<0?line:line.substring(0,colon);
String value=colon<0?"":line.substring(colon+1);if(value.startsWith(" "))value=value.substring(1);
switch(field) {
case "id" -> cursor=value;
case "event" -> kind=value;
case "data" -> {if(!data.isEmpty())data.append('\n');data.append(value);}
default -> { /* Other standard fields do not control this CLI's bounded reconnection policy. */ }
}
}
}
@Override public void close() throws IOException {reader.close();}
}
@@ -0,0 +1,99 @@
package net.intrepid.aiengineering.localserver;
import com.sun.net.httpserver.HttpExchange;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;
/** Dedicated, bounded subscriptions. Interrupting a stalled JDK SocketChannel writer closes its channel. */
public final class SseStreams implements AutoCloseable {
public static final int MAX_STREAMS=16, MAX_PER_JOB=2;
public static final long HEARTBEAT_MILLIS=1000, WRITE_TIMEOUT_MILLIS=2000, DRAIN_MILLIS=1000;
private final ExecutorService workers=new ThreadPoolExecutor(0,MAX_STREAMS,30,TimeUnit.SECONDS,
new SynchronousQueue<>(),Thread.ofPlatform().daemon().name("aie-sse-",0).factory());
private final ScheduledExecutorService watchdog=Executors.newSingleThreadScheduledExecutor(
Thread.ofPlatform().daemon().name("aie-sse-watchdog").factory());
private final Set<Subscriber> subscribers=new HashSet<>();
private volatile boolean closed;
private long drainingSince;
public SseStreams() { watchdog.scheduleWithFixedDelay(this::expireWriters,100,100,TimeUnit.MILLISECONDS); }
public synchronized int active() { return subscribers.size(); }
public synchronized boolean drained() {
if(subscribers.isEmpty()) return true;
if(drainingSince==0) drainingSince=System.nanoTime();
return System.nanoTime()-drainingSince>=DRAIN_MILLIS*1_000_000;
}
public void open(HttpExchange exchange,String id,String cursor,ServerProtocol.EventSource source) {
JobEvents.validateCursor(cursor);
var subscriber=new Subscriber(exchange,id,cursor,source);
synchronized(this) {
if(closed || subscribers.size()>=MAX_STREAMS
|| subscribers.stream().filter(value->value.id.equals(id)).count()>=MAX_PER_JOB) {
source.close(); throw ProtocolException.validation("SSE subscriber capacity exceeded; job remains recoverable: "+id);
}
subscribers.add(subscriber);
try { workers.execute(subscriber); }
catch(RejectedExecutionException busy) {
subscribers.remove(subscriber); source.close();
throw ProtocolException.validation("SSE workers busy; job remains recoverable: "+id);
}
}
}
private synchronized void expireWriters() {
long now=System.nanoTime();
for(var subscriber:subscribers) {
long since=subscriber.writingSince; Thread writer=subscriber.thread;
if(since!=0 && now-since>WRITE_TIMEOUT_MILLIS*1_000_000 && writer!=null) writer.interrupt();
}
}
private final class Subscriber implements Runnable {
final HttpExchange exchange;
final String id;
final ServerProtocol.EventSource source;
String cursor;
volatile Thread thread;
volatile long writingSince;
Subscriber(HttpExchange exchange,String id,String cursor,ServerProtocol.EventSource source) {
this.exchange=exchange;this.id=id;this.cursor=cursor;this.source=source;
}
void write(String frame) throws IOException {
writingSince=System.nanoTime();
try {
exchange.getResponseBody().write(frame.getBytes(StandardCharsets.UTF_8));
exchange.getResponseBody().flush();
} finally { writingSince=0; }
}
@Override public void run() {
thread=Thread.currentThread();
try {
if(closed) return;
exchange.getResponseHeaders().set("Content-Type","text/event-stream; charset=utf-8");
exchange.getResponseHeaders().set("Cache-Control","no-store");
writingSince=System.nanoTime();
try { exchange.sendResponseHeaders(200,0); } finally { writingSince=0; }
while(!closed) {
var event=source.next(cursor,HEARTBEAT_MILLIS);
if(event==null) { write(": heartbeat\n\n"); continue; }
write(SseFrames.encode(event)); cursor=event.cursor();
if(event.terminal()) return;
}
} catch(InterruptedException interrupted) { Thread.currentThread().interrupt(); }
catch(IOException | RuntimeException disconnected) { /* Detaching a subscriber never cancels or replays its job. */ }
finally {
writingSince=System.nanoTime();
try { exchange.close(); }
finally { source.close(); synchronized(SseStreams.this) { subscribers.remove(this); } }
}
}
}
@Override public void close() {
synchronized(this) {
if(closed) return;
closed=true;
for(var subscriber:subscribers) if(subscriber.thread!=null) subscriber.thread.interrupt();
}
workers.shutdownNow(); watchdog.shutdown();
}
}
@@ -0,0 +1,2 @@
@org.springframework.modulith.ApplicationModule(allowedDependencies = {"cli", "filesystem", "project"})
package net.intrepid.aiengineering.localserver;