@anusornneal/chat-relay 1.8.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +60 -0
  2. package/agent/activity-capture.mjs +165 -0
  3. package/agent/capability-scheduler.mjs +83 -6
  4. package/agent/file-manager.mjs +188 -77
  5. package/agent/fs-batch-preview.mjs +70 -0
  6. package/agent/full-bridge.mjs +53 -0
  7. package/agent/full-desktop-actions.mjs +124 -0
  8. package/agent/full-desktop-auth.mjs +53 -0
  9. package/agent/full-desktop-broker.mjs +308 -0
  10. package/agent/full-host.mjs +153 -0
  11. package/agent/full-job-broker.mjs +360 -0
  12. package/agent/full-native-job.mjs +205 -0
  13. package/agent/full-presentation-changes.mjs +191 -0
  14. package/agent/full-remote-diagnostics.mjs +129 -0
  15. package/agent/full-resources.mjs +343 -0
  16. package/agent/full-runtime-supervisor.mjs +67 -0
  17. package/agent/full-session-dispatch.mjs +167 -0
  18. package/agent/full-workspace-broker.mjs +290 -0
  19. package/agent/git-worktree-manager.mjs +170 -4
  20. package/agent/lifecycle.mjs +17 -0
  21. package/agent/local-agent.mjs +182 -33
  22. package/agent/local-usage.mjs +275 -0
  23. package/agent/monitor-activity.mjs +111 -0
  24. package/agent/presentation-redaction.mjs +10 -0
  25. package/agent/process-manager.mjs +32 -0
  26. package/agent/protocol.mjs +5 -1
  27. package/agent/terminal-manager.mjs +240 -29
  28. package/agent/terminal-output.mjs +136 -0
  29. package/agent/toolcall-context.mjs +35 -5
  30. package/agent/toolcall-summary.mjs +10 -0
  31. package/agent/windows-desktop-runner.mjs +65 -61
  32. package/agent/windows-desktop-worker.ps1 +33 -18
  33. package/agent/windows-powershell.mjs +51 -0
  34. package/cli/full-background.mjs +69 -0
  35. package/cli/full-launch.mjs +94 -0
  36. package/cli/full-prepare-child.mjs +48 -0
  37. package/cli/full-prepare.mjs +171 -0
  38. package/cli/full-release-default.json +4 -0
  39. package/cli/full-release-files.mjs +36 -0
  40. package/cli/full-release-official.mjs +48 -0
  41. package/cli/full-release-source.mjs +37 -0
  42. package/cli/index.mjs +8 -4
  43. package/cli/mod-cache.mjs +170 -0
  44. package/cli/mod-loader.mjs +67 -0
  45. package/cli/mod-manifest.mjs +63 -0
  46. package/cli/remote.mjs +172 -17
  47. package/cli/runner-ownership.mjs +116 -3
  48. package/cli/self-update.mjs +1 -1
  49. package/cli/tui.mjs +2 -20
  50. package/package.json +9 -6
  51. package/packages/full-contracts/index.mjs +193 -0
  52. package/packages/full-contracts/native-job.mjs +13 -0
  53. package/packages/full-contracts/package.json +7 -0
  54. package/packages/full-contracts/remote-session.mjs +239 -0
@@ -1,7 +1,9 @@
1
+ import { compactTerminalResult, compactTerminalPage, CompactExecOutputStore, outputLimit, validateOutputMode } from "./terminal-output.mjs";
1
2
  import { execFile, spawn } from "node:child_process";
2
3
  import { randomUUID } from "node:crypto";
3
4
  import os from "node:os";
4
5
  import path from "node:path";
6
+ import { POWERSHELL_UTF8_SETUP, powerShellUtf8Script, powerShellStdinEnvelope } from "./windows-powershell.mjs";
5
7
  import {
6
8
  createTerminalSessionId,
7
9
  terminalContinuityConfig,
@@ -15,6 +17,8 @@ const MAX_OUTPUT_WAIT_MS = 15_000;
15
17
  const MAX_WAITERS_PER_SESSION = 8;
16
18
  const MAX_INPUT_CHARS = 8 * 1024;
17
19
  const MAX_SESSIONS = 8;
20
+ const MAX_RETAINED_SESSIONS = 128;
21
+ const MAX_RETAINED_SESSION_CHARS = 4 * 1024 * 1024;
18
22
  const MAX_BATCH_SIZE = 20;
19
23
  const MAX_BATCH_CONCURRENCY = 8;
20
24
  const DEFAULT_BATCH_CONCURRENCY = 4;
@@ -30,6 +34,10 @@ const MAX_JOB_READ_CHARS = 8 * 1024;
30
34
  const MAX_RETAINED_BATCHES = 64;
31
35
  const ENDED_TTL_MS = 30 * 60 * 1000;
32
36
 
37
+ // Stdin errors can outlive the root and pending write callbacks. Once capture
38
+ // closes, keep only a session-free sink rather than retaining its buffer graph.
39
+ const ignoreClosedStdinError = () => {};
40
+
33
41
  const BLOCKED_COMMANDS = [
34
42
  /\b(mkfs|mount|umount|fdisk|dd|parted|diskpart|sudo|su|passwd)\b/i,
35
43
  // Match disk formatting as a command, not a filename, argument or Git flag.
@@ -72,8 +80,10 @@ export function shellForPlatform(platform, preferredShell) {
72
80
  return {
73
81
  file: "powershell.exe",
74
82
  displayName: "powershell",
75
- commandArgs: (command) => ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command],
76
- interactiveArgs: ["-NoLogo", "-NoProfile", "-NoExit", "-Command", "-"],
83
+ commandArgs: (command) => ["-NoLogo", "-NoProfile", "-NonInteractive", "-OutputFormat", "Text", "-Command", powerShellUtf8Script(command)],
84
+ // Initialize before the native REPL reads input. write() must remain raw:
85
+ // its bytes can belong to a multiline command or a running child process.
86
+ interactiveArgs: ["-NoLogo", "-NoProfile", "-NoExit", "-OutputFormat", "Text", "-Command", POWERSHELL_UTF8_SETUP],
77
87
  persistentArgs: ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", "-"],
78
88
  };
79
89
  }
@@ -133,7 +143,7 @@ function persistentExecScript(platform, command, cwd, marker) {
133
143
  const psBegin = quotePowerShell(begin);
134
144
  const psEndPrefix = quotePowerShell(endPrefix);
135
145
  const psEndSuffix = quotePowerShell(endSuffix);
136
- return [
146
+ const script = [
137
147
  "& {",
138
148
  " [Console]::Out.Write(" + psBegin + ")",
139
149
  " [Console]::Error.Write(" + psBegin + ")",
@@ -141,6 +151,7 @@ function persistentExecScript(platform, command, cwd, marker) {
141
151
  " $global:LASTEXITCODE = $null",
142
152
  " $__ChatRelayExitCode = 0",
143
153
  " try {",
154
+ " " + POWERSHELL_UTF8_SETUP,
144
155
  " Set-Location -LiteralPath " + psCwd,
145
156
  " & ([ScriptBlock]::Create(" + psCommand + "))",
146
157
  " $__ChatRelaySucceeded = $?",
@@ -160,6 +171,7 @@ function persistentExecScript(platform, command, cwd, marker) {
160
171
  " [Console]::Error.Write($__ChatRelayEnd)",
161
172
  "}",
162
173
  ].join("\n");
174
+ return powerShellStdinEnvelope(script);
163
175
  }
164
176
 
165
177
  const shCommand = quotePosix(command);
@@ -534,7 +546,11 @@ export class TerminalManager {
534
546
  this.platform = options.platform ?? process.platform;
535
547
  this.shell = shellForPlatform(this.platform, options.shell);
536
548
  this.sessions = new Map();
549
+ this.spawnSession = options.spawnSession ?? spawn;
550
+ this.terminateSession = options.terminateSession ?? terminateProcessTree;
551
+ this.completionSequence = 0;
537
552
  this.processEpoch = options.processEpoch ?? randomUUID();
553
+ this.execOutputs = new CompactExecOutputStore(this.processEpoch);
538
554
  this.batches = new Map();
539
555
  this.batchQueue = [];
540
556
  this.activeBatchJobs = 0;
@@ -592,6 +608,19 @@ export class TerminalManager {
592
608
  return this.#execIsolated(command, resolvedCwd, timeout);
593
609
  }
594
610
 
611
+ async execCompact(command, cwd, timeoutMs, outputMode = "summary", outputChars) {
612
+ const mode = validateOutputMode(outputMode);
613
+ const limit = outputLimit(outputChars);
614
+ const startedAt = new Date().toISOString();
615
+ const start = Date.now();
616
+ const raw = await this.exec(command, cwd, timeoutMs);
617
+ const endedAt = new Date().toISOString();
618
+ const result = compactTerminalResult(raw, mode, limit);
619
+ return { ...result, durationMs: Date.now() - start,
620
+ ...(result.omittedChars > 0 ? { rawOutputId: this.execOutputs.record(raw, startedAt, endedAt),
621
+ rawOutputExpiresInMs: 600000 } : {}) };
622
+ }
623
+
595
624
  #execIsolated(command, resolvedCwd, timeout) {
596
625
  return new Promise((resolve) => {
597
626
  execFile(
@@ -643,6 +672,35 @@ export class TerminalManager {
643
672
  });
644
673
  }
645
674
 
675
+ // The trusted Full broker obtains this reservation through CapabilityScheduler
676
+ // and persists its claim + job attempt before launch. Existing Lite calls do not
677
+ // change behavior. A root exit is not proof of arbitrary descendants stopping.
678
+ startOwned(command,cwd,{reservation,jobId,launchOwned,captureIdentity,cancelTree,observability}={}){
679
+ validateCommand(command);
680
+ const resolvedCwd=safeCwd(cwd);
681
+ const args=this.shell.commandArgs(command);
682
+ if(!reservation||typeof reservation.retain!=="function"||
683
+ typeof launchOwned!=="function"||typeof captureIdentity!=="function"||typeof cancelTree!=="function")
684
+ throw new Error("full_owned_job_provider_required");
685
+ const owned={reservation,jobId,launchOwned,captureIdentity,cancelTree,cancelRequested:false,identity:null};
686
+ return this.#spawnSession({type:"command",command,cwd:resolvedCwd,args,observability,owned});
687
+ }
688
+
689
+ async cancelOwned(sessionId,{reservation}={}){
690
+ const session=this.#get(sessionId),owned=session?.owned;
691
+ if(!owned||owned.reservation!==reservation)throw new Error("full_owned_job_unauthorized");
692
+ if(session.status!=="running")return this.#summary(session);
693
+ // Cancellation is merely a request. The containment provider must validate
694
+ // the actual process identity, not a caller-supplied PID.
695
+ if(!owned.identity)throw new Error("full_process_identity_unknown");
696
+ if(!owned.cancelRequested){
697
+ owned.cancelRequested=true;
698
+ try{await owned.cancelTree(session.process,owned.identity,{jobId:owned.jobId});}
699
+ catch(error){owned.reservation.quarantine();throw error;}
700
+ }
701
+ return {...this.#summary(session),cancelRequested:true};
702
+ }
703
+
646
704
  startShell(cwd, observability) {
647
705
  return this.#spawnSession({
648
706
  type: "shell",
@@ -653,26 +711,35 @@ export class TerminalManager {
653
711
  });
654
712
  }
655
713
 
656
- list() {
714
+ list({reservation}={}) {
657
715
  this.#cleanup();
658
- return [...this.sessions.values()].map((session) => this.#summary(session));
716
+ return [...this.sessions.values()].filter(session=>reservation?session.owned?.reservation===reservation:!session.owned).map(session=>this.#summary(session));
659
717
  }
660
718
 
661
719
  getContinuityConfig() {
662
720
  const activeSessions = [...this.sessions.values()]
663
721
  .filter((session) => session.status === "running").length;
664
- return terminalContinuityConfig(this.processEpoch, activeSessions);
722
+ return {
723
+ ...terminalContinuityConfig(this.processEpoch, activeSessions),
724
+ drainingSessions: [...this.sessions.values()].filter(session => !session.closed && session.status !== "running").length,
725
+ completedSessionRetention: {
726
+ scope: "legacy", ttlMs: ENDED_TTL_MS, maxSessions: MAX_RETAINED_SESSIONS,
727
+ maxOutputChars: MAX_RETAINED_SESSION_CHARS, eviction: "oldest-completed",
728
+ },
729
+ };
665
730
  }
666
731
 
667
732
  observability() {
668
733
  this.#cleanup();
669
734
  return {
670
735
  ok: true,
671
- sessions: [...this.sessions.values()].map((session) => ({
736
+ drainingSessions: [...this.sessions.values()].filter(session => !session.owned && !session.closed && session.status !== "running").length,
737
+ sessions: [...this.sessions.values()].filter(session=>!session.owned).map((session) => ({
672
738
  sessionId: session.id,
673
739
  processEpoch: session.processEpoch,
674
740
  type: session.type,
675
741
  status: session.status,
742
+ ...this.#captureState(session),
676
743
  exitCode: session.exitCode,
677
744
  startedAt: session.startedAt,
678
745
  endedAt: session.endedAt,
@@ -704,10 +771,17 @@ export class TerminalManager {
704
771
  };
705
772
  }
706
773
 
707
- read(sessionId, afterSeq = 0, maxChars = MAX_READ_CHARS) {
774
+ read(sessionId, afterSeq = 0, maxChars = MAX_READ_CHARS, reservation) {
775
+ const replay = this.execOutputs.read(sessionId, afterSeq, maxChars);
776
+ if (replay) return replay;
708
777
  this.#cleanup();
709
778
  const session = this.#get(sessionId);
710
779
  if (!session) return terminalSessionMiss(sessionId, this.processEpoch);
780
+ if(session.owned&&session.owned.reservation!==reservation)throw new Error("full_owned_job_requires_broker");
781
+ return this.#readSession(session, afterSeq, maxChars);
782
+ }
783
+
784
+ #readSession(session, afterSeq, maxChars) {
711
785
  const limit = Math.min(Math.max(Number(maxChars) || MAX_READ_CHARS, 1024), MAX_READ_CHARS);
712
786
  const oldestSeq = session.chunks[0]?.seq ?? session.nextSeq;
713
787
  const chunks = [];
@@ -729,12 +803,12 @@ export class TerminalManager {
729
803
  };
730
804
  }
731
805
 
732
- async readWithWait(sessionId, afterSeq = 0, maxChars = MAX_READ_CHARS, waitMs = 0) {
806
+ async readWithWait(sessionId, afterSeq = 0, maxChars = MAX_READ_CHARS, waitMs = 0, reservation) {
733
807
  if (!Number.isInteger(waitMs) || waitMs < 0 || waitMs > MAX_OUTPUT_WAIT_MS) {
734
808
  throw new Error("invalid_wait_ms");
735
809
  }
736
- const initial = this.read(sessionId, afterSeq, maxChars);
737
- if (!waitMs || initial.status !== "running" || initial.chunks.length || initial.truncated) {
810
+ const initial = this.read(sessionId, afterSeq, maxChars,reservation);
811
+ if (!waitMs || (initial.status !== "running" && !initial.outputDraining) || initial.chunks.length || initial.truncated) {
738
812
  return initial;
739
813
  }
740
814
  const session = this.#get(sessionId);
@@ -747,17 +821,29 @@ export class TerminalManager {
747
821
  if (timer === null) return;
748
822
  clearTimeout(timer);
749
823
  timer = null;
824
+ // This waiter already passed ownership checks. Snapshot its capture
825
+ // before cleanup: an old root may reach close after its replay TTL.
826
+ const page = this.#readSession(session, afterSeq, maxChars);
750
827
  session.waiters.delete(finish);
751
- resolve(this.read(sessionId, afterSeq, maxChars));
828
+ resolve(page);
752
829
  };
753
830
  session.waiters.add(finish);
754
831
  timer = setTimeout(finish, waitMs);
755
832
  });
756
833
  }
757
834
 
835
+ async readCompact(sessionId, afterSeq = 0, maxChars = MAX_READ_CHARS, waitMs = 0,
836
+ outputMode = "summary", outputChars, reservation) {
837
+ const mode = validateOutputMode(outputMode);
838
+ const limit = outputLimit(outputChars);
839
+ const page = await this.readWithWait(sessionId, afterSeq, maxChars, waitMs,reservation);
840
+ return compactTerminalPage(page, mode, limit, afterSeq);
841
+ }
842
+
758
843
  write(sessionId, input, appendNewline = true) {
759
844
  const session = this.#get(sessionId);
760
845
  if (!session) return terminalSessionMiss(sessionId, this.processEpoch);
846
+ if (session.owned) throw new Error("full_owned_job_requires_broker");
761
847
  if (session.status !== "running") throw new Error("session_not_running");
762
848
  if (typeof input !== "string" || input.length === 0 || input.length > MAX_INPUT_CHARS) {
763
849
  throw new Error("invalid_input");
@@ -769,9 +855,22 @@ export class TerminalManager {
769
855
  async kill(sessionId) {
770
856
  const session = this.#get(sessionId);
771
857
  if (!session) return terminalSessionMiss(sessionId, this.processEpoch);
772
- if (session.status !== "running") return this.#summary(session);
858
+ if(session.owned)throw new Error("full_owned_job_requires_broker");
859
+ if (session.status !== "running") {
860
+ if (!session.closed && !session.captureAbandoned) {
861
+ // A descendant may still hold an inherited output pipe. The exited
862
+ // root's PID is no longer safe to signal. An explicit legacy kill can
863
+ // abandon only our capture, preserving buffered output and its limits.
864
+ session.captureAbandoned = true;
865
+ session.process.stdin?.destroy();
866
+ session.process.stdout.destroy();
867
+ session.process.stderr.destroy();
868
+ this.#notifyWaiters(session);
869
+ }
870
+ return this.#summary(session);
871
+ }
773
872
 
774
- await terminateProcessTree(this.platform, session.pid);
873
+ await this.terminateSession(this.platform, session.pid);
775
874
  return this.#summary(session);
776
875
  }
777
876
 
@@ -865,6 +964,34 @@ export class TerminalManager {
865
964
  return { ...this.#batchSummary(batch), jobs, truncated, maxChars: aggregateLimit };
866
965
  }
867
966
 
967
+ batchReadCompact(batchId, maxChars = MAX_BATCH_READ_CHARS, outputMode = "summary", outputChars, jobIndex) {
968
+ const mode = validateOutputMode(outputMode);
969
+ const limit = outputLimit(outputChars);
970
+ this.#cleanup();
971
+ const batch = this.#getBatch(batchId);
972
+ if (jobIndex !== undefined && (!Number.isInteger(jobIndex) || jobIndex < 0 || jobIndex >= batch.jobs.length)) {
973
+ throw new Error("invalid_job_index");
974
+ }
975
+ const selected = jobIndex === undefined ? batch.jobs : [batch.jobs[jobIndex]];
976
+ if (mode === "full" && jobIndex === undefined) return this.batchRead(batchId, maxChars);
977
+ const aggregateLimit = normalizeInteger(maxChars, MAX_BATCH_READ_CHARS, 1024, MAX_BATCH_READ_CHARS);
978
+ let remaining = aggregateLimit;
979
+ let truncated = false;
980
+ const jobs = selected.map(job => {
981
+ const budget = Math.min(MAX_JOB_READ_CHARS, remaining, mode === "full" ? MAX_JOB_READ_CHARS : limit);
982
+ const raw = { ...this.#jobSummary(job), stdout: job.stdout, stderr: job.stderr };
983
+ const output = mode === "full" ? { ...raw, ...clipJobOutput(job.stdout, job.stderr, budget) }
984
+ : compactTerminalResult(raw, mode, budget);
985
+ remaining = Math.max(0, remaining - output.stdout.length - output.stderr.length);
986
+ const omitted = job.stdout.length + job.stderr.length - output.stdout.length - output.stderr.length;
987
+ truncated ||= job.outputTruncated || omitted > 0;
988
+ return { ...output, outputTruncated: job.outputTruncated || omitted > 0,
989
+ ...(mode === "full" ? {} : { rawJobIndex: job.index }) };
990
+ });
991
+ return { ...this.#batchSummary(batch), jobs, truncated, maxChars: aggregateLimit, outputMode: mode,
992
+ ...(jobIndex === undefined ? {} : { selectedJobIndex: jobIndex }) };
993
+ }
994
+
868
995
  async batchCancel(batchId) {
869
996
  this.#cleanup();
870
997
  const batch = this.#getBatch(batchId);
@@ -898,17 +1025,22 @@ export class TerminalManager {
898
1025
  };
899
1026
  }
900
1027
 
901
- #spawnSession({ type, command, cwd, args, observability }) {
1028
+ #spawnSession({ type, command, cwd, args, observability, owned = null }) {
902
1029
  this.#cleanup();
903
- const running = [...this.sessions.values()].filter((session) => session.status === "running").length;
904
- if (running >= MAX_SESSIONS) throw new Error("too_many_sessions");
905
-
906
- const child = spawn(this.shell.file, args, {
907
- cwd,
908
- windowsHide: true,
909
- stdio: ["pipe", "pipe", "pipe"],
910
- detached: this.platform !== "win32",
911
- });
1030
+ const open = [...this.sessions.values()].filter(session => !session.closed).length;
1031
+ if (open >= MAX_SESSIONS) throw new Error("too_many_sessions");
1032
+
1033
+ const spawnOptions={cwd,windowsHide:true,stdio:["pipe","pipe","pipe"],detached:this.platform!=="win32"};
1034
+ let child;
1035
+ if(owned){
1036
+ owned.reservation.retain(owned.jobId);
1037
+ try{
1038
+ // The trusted containment provider must establish ownership before
1039
+ // allowing arbitrary commands to run; ordinary spawn is not containment.
1040
+ child=owned.launchOwned(this.shell.file,args,spawnOptions,{jobId:owned.jobId});
1041
+ if(!child?.on||!child.stdout||!child.stderr)throw new Error("full_owned_launch_unknown");
1042
+ }catch(error){owned.reservation.quarantine();throw error;}
1043
+ }else child=this.spawnSession(this.shell.file,args,spawnOptions);
912
1044
 
913
1045
  const session = {
914
1046
  id: createTerminalSessionId(this.processEpoch, randomUUID()),
@@ -918,6 +1050,8 @@ export class TerminalManager {
918
1050
  cwd,
919
1051
  pid: child.pid,
920
1052
  process: child,
1053
+ closed: false,
1054
+ completionSequence: null,
921
1055
  status: "running",
922
1056
  exitCode: null,
923
1057
  signal: null,
@@ -928,18 +1062,68 @@ export class TerminalManager {
928
1062
  totalChars: 0,
929
1063
  waiters: new Set(),
930
1064
  observability: observability ?? null,
1065
+ ...(owned?{owned}:{}),
931
1066
  };
932
1067
 
933
1068
  this.sessions.set(session.id, session);
934
- child.stdout.on("data", (data) => this.#append(session, "stdout", data));
935
- child.stderr.on("data", (data) => this.#append(session, "stderr", data));
936
- child.on("error", (error) => this.#append(session, "stderr", error.message + os.EOL));
937
- child.on("exit", (code, signal) => {
1069
+ // Preserve multibyte characters split across OS pipe reads.
1070
+ child.stdout.setEncoding("utf8");
1071
+ child.stderr.setEncoding("utf8");
1072
+ const onStdout = data => this.#append(session, "stdout", data);
1073
+ const onStderr = data => this.#append(session, "stderr", data);
1074
+ const onError = error => {
1075
+ this.#append(session, "stderr", error.message + os.EOL);
1076
+ if (!child.pid) {
1077
+ session.status = "exited";
1078
+ session.exitCode = null;
1079
+ session.endedAt = new Date().toISOString();
1080
+ owned?.reservation.spawnFailed();
1081
+ this.#notifyWaiters(session);
1082
+ } else owned?.reservation.quarantine();
1083
+ };
1084
+ const onStdinError = error => {
1085
+ session.inputError = typeof error.code === "string" ? error.code.slice(0, 64) : "terminal_input_failed";
1086
+ this.#notifyWaiters(session);
1087
+ };
1088
+ child.stdout.on("data", onStdout);
1089
+ child.stderr.on("data", onStderr);
1090
+ child.stdin?.on("error", onStdinError);
1091
+ child.on("error", onError);
1092
+ if(owned&&child.pid){
1093
+ // Capture OS birth identity, not a guessed start time from this process.
1094
+ // Failure or a fast exit remains unknown; never clear a claim on that basis.
1095
+ void Promise.resolve().then(()=>owned.captureIdentity(child)).then(identity=>{
1096
+ if(identity?.state!=="present"||identity.pid!==child.pid||session.status!=="running"){
1097
+ owned.reservation.quarantine();return;
1098
+ }
1099
+ owned.reservation.recordProcess(identity);
1100
+ owned.identity=identity;
1101
+ }).catch(()=>{try{owned.reservation.quarantine();}catch{}});
1102
+ }
1103
+ const onExit = (code, signal) => {
938
1104
  session.status = "exited";
939
1105
  session.exitCode = code;
940
1106
  session.signal = signal;
941
1107
  session.endedAt = new Date().toISOString();
1108
+ if(owned)owned.reservation.rootExited();
942
1109
  this.#notifyWaiters(session);
1110
+ };
1111
+ child.on("exit", onExit);
1112
+ child.once("close", (code, signal) => {
1113
+ if (session.status === "running") onExit(code, signal);
1114
+ // Exit can precede final pipe data. Retain the capture and active slot
1115
+ // until close, then release only this session's process/listener graph.
1116
+ session.closed = true;
1117
+ session.completionSequence = ++this.completionSequence;
1118
+ child.stdout.off("data", onStdout);
1119
+ child.stderr.off("data", onStderr);
1120
+ child.stdin?.off("error", onStdinError);
1121
+ child.stdin?.on("error", ignoreClosedStdinError);
1122
+ child.off("error", onError);
1123
+ child.off("exit", onExit);
1124
+ session.process = null;
1125
+ this.#notifyWaiters(session);
1126
+ this.#cleanup();
943
1127
  });
944
1128
 
945
1129
  return this.#summary(session);
@@ -1054,6 +1238,16 @@ export class TerminalManager {
1054
1238
  for (const notify of session.waiters) notify();
1055
1239
  }
1056
1240
 
1241
+ #captureState(session) {
1242
+ return {
1243
+ outputDraining: !session.closed && session.status !== "running",
1244
+ ...(session.captureAbandoned ? {
1245
+ captureAbandoned: true, outputIncomplete: true, descendantState: "unknown",
1246
+ } : {}),
1247
+ ...(session.inputError ? { inputError: session.inputError } : {}),
1248
+ };
1249
+ }
1250
+
1057
1251
  #summary(session) {
1058
1252
  return {
1059
1253
  sessionId: session.id,
@@ -1063,11 +1257,13 @@ export class TerminalManager {
1063
1257
  cwd: session.cwd,
1064
1258
  pid: session.pid,
1065
1259
  status: session.status,
1260
+ ...this.#captureState(session),
1066
1261
  exitCode: session.exitCode,
1067
1262
  signal: session.signal,
1068
1263
  startedAt: session.startedAt,
1069
1264
  endedAt: session.endedAt,
1070
1265
  nextSeq: session.nextSeq - 1,
1266
+ ...(session.owned?{fullJobId:session.owned.jobId,resourceReconciliationRequired:session.status!=="running"}:{}),
1071
1267
  };
1072
1268
  }
1073
1269
 
@@ -1086,9 +1282,24 @@ export class TerminalManager {
1086
1282
  #cleanup() {
1087
1283
  const now = Date.now();
1088
1284
  for (const [id, session] of this.sessions) {
1089
- if (session.status === "running" || !session.endedAt) continue;
1285
+ if (!session.closed || session.status === "running" || !session.endedAt) continue;
1090
1286
  if (now - Date.parse(session.endedAt) > ENDED_TTL_MS) this.sessions.delete(id);
1091
1287
  }
1288
+ // Same-process replay is bounded by age, count and captured characters.
1289
+ // Never evict a running/draining session or a Full-owned compatibility
1290
+ // session under legacy capacity pressure; native Full has its own owner.
1291
+ const completed = [...this.sessions.values()].filter(session => session.closed && !session.owned);
1292
+ let retainedChars = completed.reduce((total, session) => total + session.totalChars, 0);
1293
+ let retainedCount = completed.length;
1294
+ if (retainedCount > MAX_RETAINED_SESSIONS || retainedChars > MAX_RETAINED_SESSION_CHARS) {
1295
+ completed.sort((a, b) => a.completionSequence - b.completionSequence);
1296
+ }
1297
+ for (const session of completed) {
1298
+ if (retainedCount <= MAX_RETAINED_SESSIONS && retainedChars <= MAX_RETAINED_SESSION_CHARS) break;
1299
+ this.sessions.delete(session.id);
1300
+ retainedCount -= 1;
1301
+ retainedChars -= session.totalChars;
1302
+ }
1092
1303
  for (const [id, batch] of this.batches) {
1093
1304
  if (!batch.endedAt) continue;
1094
1305
  if (now - Date.parse(batch.endedAt) > ENDED_TTL_MS) this.batches.delete(id);
@@ -0,0 +1,136 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createTerminalSessionId } from "./terminal-continuity.mjs";
3
+
4
+ const MODES = new Set(["full", "tail", "summary", "errors"]);
5
+ const ERROR_LINE = /(?:\b(?:error|warning|fatal|failed|failure|exception|traceback|caused by)\b|^\s*[ew]:)/i;
6
+ const EXEC_REPLAY_TTL = 10 * 60_000;
7
+ const MAX_EXEC_REPLAYS = 16;
8
+ const REPLAY_CHUNK_CHARS = 1024;
9
+ const REPLAY_RESPONSE_BYTES = 40 * 1024;
10
+
11
+ export function outputLimit(value) {
12
+ if (value === undefined) return 2048;
13
+ if (!Number.isInteger(value) || value < 256 || value > 8192) throw new Error("invalid_output_chars");
14
+ return value;
15
+ }
16
+
17
+ export function validateOutputMode(mode = "full") {
18
+ if (!MODES.has(mode)) throw new Error("invalid_output_mode");
19
+ return mode;
20
+ }
21
+
22
+ function tail(text, limit) {
23
+ if (limit <= 0) return "";
24
+ if (text.length <= limit) return text;
25
+ let start = text.length - limit;
26
+ if (start > 0 && /[\uDC00-\uDFFF]/.test(text[start])) start++;
27
+ return text.slice(start);
28
+ }
29
+
30
+ function diagnostic(text) {
31
+ return text.split(/\r?\n/).filter(line => ERROR_LINE.test(line)).join("\n");
32
+ }
33
+
34
+ function failed(result) {
35
+ return result.ok === false || ["failed", "cancelled", "killed"].includes(result.status) || Boolean(result.signal) ||
36
+ (typeof result.exitCode === "number" && result.exitCode !== 0);
37
+ }
38
+
39
+ // A compact view is a projection of captured output, never a new execution.
40
+ export function compactTerminalResult(result, mode, limit = 2048) {
41
+ validateOutputMode(mode);
42
+ if (mode === "full") return result;
43
+ const stdout = typeof result.stdout === "string" ? result.stdout : "";
44
+ const stderr = typeof result.stderr === "string" ? result.stderr : "";
45
+ let out = stdout, err = stderr;
46
+ if (mode === "summary" && !failed(result)) { out = ""; err = ""; }
47
+ else if (mode === "errors") {
48
+ out = diagnostic(stdout);
49
+ if (!out && !err && failed(result)) out = stdout;
50
+ }
51
+ const errBudget = out ? Math.min(err.length, Math.ceil(limit / 2)) : limit;
52
+ err = tail(err, errBudget);
53
+ out = tail(out, Math.max(0, limit - err.length));
54
+ return { ...result, stdout: out, stderr: err, outputMode: mode,
55
+ capturedChars: stdout.length + stderr.length,
56
+ omittedChars: Math.max(0, stdout.length + stderr.length - out.length - err.length) };
57
+ }
58
+
59
+ export function compactTerminalPage(page, mode, limit, afterSeq) {
60
+ validateOutputMode(mode);
61
+ if (mode === "full" || !Array.isArray(page.chunks)) return page;
62
+ const raw = page.chunks;
63
+ const capturedChars = raw.reduce((sum, c) => sum + c.text.length, 0);
64
+ let remaining = limit;
65
+ const chunks = [];
66
+ for (let i = raw.length - 1; i >= 0 && remaining > 0; i--) {
67
+ const c = raw[i];
68
+ let text = c.text;
69
+ if (mode === "summary" && !failed(page)) text = "";
70
+ else if (mode === "errors" && c.stream !== "stderr") text = diagnostic(text);
71
+ if (!text) continue;
72
+ text = tail(text, remaining);
73
+ if (text) { chunks.push({ ...c, text }); remaining -= text.length; }
74
+ }
75
+ if (!chunks.length && failed(page) && capturedChars && mode === "errors") {
76
+ for (let i = raw.length - 1; i >= 0 && remaining > 0; i--) {
77
+ const text = tail(raw[i].text, remaining);
78
+ if (text) { chunks.push({ ...raw[i], text }); remaining -= text.length; }
79
+ }
80
+ }
81
+ chunks.reverse();
82
+ return { ...page, chunks, outputMode: mode, capturedChars, omittedChars: capturedChars - (limit - remaining),
83
+ // Re-read the original page with full mode and this cursor, not nextSeq.
84
+ rawAfterSeq: afterSeq };
85
+ }
86
+
87
+ // Bounded process-local replay for compact short commands. No disk or extra RPC.
88
+ export class CompactExecOutputStore {
89
+ constructor(processEpoch, now = Date.now) {
90
+ this.processEpoch = processEpoch;
91
+ this.now = now;
92
+ this.entries = new Map();
93
+ }
94
+ #prune() {
95
+ const now = this.now();
96
+ for (const [id, entry] of this.entries) if (entry.expiresAt <= now) this.entries.delete(id);
97
+ }
98
+ record(result, startedAt, endedAt) {
99
+ this.#prune();
100
+ while (this.entries.size >= MAX_EXEC_REPLAYS) this.entries.delete(this.entries.keys().next().value);
101
+ const sessionId = createTerminalSessionId(this.processEpoch, randomUUID());
102
+ const chunks = [];
103
+ for (const stream of ["stdout", "stderr"]) {
104
+ const text = typeof result[stream] === "string" ? result[stream] : "";
105
+ for (let start = 0; start < text.length;) {
106
+ let end = Math.min(text.length, start + REPLAY_CHUNK_CHARS);
107
+ if (end < text.length && /[\uDC00-\uDFFF]/.test(text[end])) end--;
108
+ chunks.push({ seq: chunks.length + 1, stream, text: text.slice(start, end) });
109
+ start = end;
110
+ }
111
+ }
112
+ this.entries.set(sessionId, { expiresAt: this.now() + EXEC_REPLAY_TTL, chunks,
113
+ summary: { sessionId, processEpoch: this.processEpoch, type: "exec-output", status: "exited",
114
+ exitCode: result.exitCode ?? null, startedAt, endedAt, error: result.error ?? null,
115
+ captureLimited: /maxBuffer|timed out/i.test(String(result.error || "")) } });
116
+ return sessionId;
117
+ }
118
+ read(sessionId, afterSeq = 0, maxChars = 24576) {
119
+ this.#prune();
120
+ const entry = this.entries.get(sessionId);
121
+ if (!entry) return null;
122
+ const limit = Math.min(Math.max(Number(maxChars) || 24576, 1024), 24576);
123
+ const chunks = [];
124
+ let chars = 0, bytes = 0;
125
+ for (const chunk of entry.chunks) {
126
+ if (chunk.seq <= afterSeq) continue;
127
+ const chunkBytes = Buffer.byteLength(JSON.stringify(chunk), "utf8");
128
+ if (chunks.length && (chars + chunk.text.length > limit || bytes + chunkBytes > REPLAY_RESPONSE_BYTES)) break;
129
+ chunks.push(chunk);
130
+ chars += chunk.text.length; bytes += chunkBytes;
131
+ }
132
+ const nextSeq = chunks.at(-1)?.seq ?? afterSeq;
133
+ return { ...entry.summary, chunks, oldestSeq: 1, nextSeq,
134
+ truncated: false, hasMore: nextSeq < entry.chunks.length };
135
+ }
136
+ }