@anusornneal/chat-relay 1.9.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.
- package/README.md +6 -0
- package/agent/activity-capture.mjs +165 -0
- package/agent/capability-scheduler.mjs +82 -5
- package/agent/file-manager.mjs +8 -3
- package/agent/full-bridge.mjs +53 -0
- package/agent/full-desktop-actions.mjs +124 -0
- package/agent/full-desktop-auth.mjs +53 -0
- package/agent/full-desktop-broker.mjs +308 -0
- package/agent/full-host.mjs +153 -0
- package/agent/full-job-broker.mjs +360 -0
- package/agent/full-native-job.mjs +205 -0
- package/agent/full-presentation-changes.mjs +191 -0
- package/agent/full-remote-diagnostics.mjs +129 -0
- package/agent/full-resources.mjs +343 -0
- package/agent/full-runtime-supervisor.mjs +67 -0
- package/agent/full-session-dispatch.mjs +167 -0
- package/agent/full-workspace-broker.mjs +290 -0
- package/agent/git-worktree-manager.mjs +170 -4
- package/agent/lifecycle.mjs +11 -0
- package/agent/local-agent.mjs +150 -24
- package/agent/local-usage.mjs +21 -0
- package/agent/monitor-activity.mjs +111 -0
- package/agent/presentation-redaction.mjs +10 -0
- package/agent/process-manager.mjs +32 -0
- package/agent/terminal-manager.mjs +189 -31
- package/agent/toolcall-context.mjs +23 -1
- package/agent/windows-desktop-runner.mjs +65 -61
- package/agent/windows-desktop-worker.ps1 +33 -18
- package/agent/windows-powershell.mjs +51 -0
- package/cli/full-background.mjs +69 -0
- package/cli/full-launch.mjs +94 -0
- package/cli/full-prepare-child.mjs +48 -0
- package/cli/full-prepare.mjs +171 -0
- package/cli/full-release-default.json +4 -0
- package/cli/full-release-files.mjs +36 -0
- package/cli/full-release-official.mjs +48 -0
- package/cli/full-release-source.mjs +37 -0
- package/cli/index.mjs +8 -4
- package/cli/mod-cache.mjs +170 -0
- package/cli/mod-loader.mjs +67 -0
- package/cli/mod-manifest.mjs +63 -0
- package/cli/remote.mjs +172 -17
- package/cli/runner-ownership.mjs +116 -3
- package/cli/self-update.mjs +1 -1
- package/cli/tui.mjs +2 -20
- package/package.json +5 -3
- package/packages/full-contracts/index.mjs +193 -0
- package/packages/full-contracts/native-job.mjs +13 -0
- package/packages/full-contracts/package.json +7 -0
- package/packages/full-contracts/remote-session.mjs +239 -0
|
@@ -3,6 +3,7 @@ import { execFile, spawn } from "node:child_process";
|
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
4
|
import os from "node:os";
|
|
5
5
|
import path from "node:path";
|
|
6
|
+
import { POWERSHELL_UTF8_SETUP, powerShellUtf8Script, powerShellStdinEnvelope } from "./windows-powershell.mjs";
|
|
6
7
|
import {
|
|
7
8
|
createTerminalSessionId,
|
|
8
9
|
terminalContinuityConfig,
|
|
@@ -16,6 +17,8 @@ const MAX_OUTPUT_WAIT_MS = 15_000;
|
|
|
16
17
|
const MAX_WAITERS_PER_SESSION = 8;
|
|
17
18
|
const MAX_INPUT_CHARS = 8 * 1024;
|
|
18
19
|
const MAX_SESSIONS = 8;
|
|
20
|
+
const MAX_RETAINED_SESSIONS = 128;
|
|
21
|
+
const MAX_RETAINED_SESSION_CHARS = 4 * 1024 * 1024;
|
|
19
22
|
const MAX_BATCH_SIZE = 20;
|
|
20
23
|
const MAX_BATCH_CONCURRENCY = 8;
|
|
21
24
|
const DEFAULT_BATCH_CONCURRENCY = 4;
|
|
@@ -31,6 +34,10 @@ const MAX_JOB_READ_CHARS = 8 * 1024;
|
|
|
31
34
|
const MAX_RETAINED_BATCHES = 64;
|
|
32
35
|
const ENDED_TTL_MS = 30 * 60 * 1000;
|
|
33
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
|
+
|
|
34
41
|
const BLOCKED_COMMANDS = [
|
|
35
42
|
/\b(mkfs|mount|umount|fdisk|dd|parted|diskpart|sudo|su|passwd)\b/i,
|
|
36
43
|
// Match disk formatting as a command, not a filename, argument or Git flag.
|
|
@@ -73,8 +80,10 @@ export function shellForPlatform(platform, preferredShell) {
|
|
|
73
80
|
return {
|
|
74
81
|
file: "powershell.exe",
|
|
75
82
|
displayName: "powershell",
|
|
76
|
-
commandArgs: (command) => ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command],
|
|
77
|
-
|
|
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],
|
|
78
87
|
persistentArgs: ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", "-"],
|
|
79
88
|
};
|
|
80
89
|
}
|
|
@@ -134,7 +143,7 @@ function persistentExecScript(platform, command, cwd, marker) {
|
|
|
134
143
|
const psBegin = quotePowerShell(begin);
|
|
135
144
|
const psEndPrefix = quotePowerShell(endPrefix);
|
|
136
145
|
const psEndSuffix = quotePowerShell(endSuffix);
|
|
137
|
-
|
|
146
|
+
const script = [
|
|
138
147
|
"& {",
|
|
139
148
|
" [Console]::Out.Write(" + psBegin + ")",
|
|
140
149
|
" [Console]::Error.Write(" + psBegin + ")",
|
|
@@ -142,6 +151,7 @@ function persistentExecScript(platform, command, cwd, marker) {
|
|
|
142
151
|
" $global:LASTEXITCODE = $null",
|
|
143
152
|
" $__ChatRelayExitCode = 0",
|
|
144
153
|
" try {",
|
|
154
|
+
" " + POWERSHELL_UTF8_SETUP,
|
|
145
155
|
" Set-Location -LiteralPath " + psCwd,
|
|
146
156
|
" & ([ScriptBlock]::Create(" + psCommand + "))",
|
|
147
157
|
" $__ChatRelaySucceeded = $?",
|
|
@@ -161,6 +171,7 @@ function persistentExecScript(platform, command, cwd, marker) {
|
|
|
161
171
|
" [Console]::Error.Write($__ChatRelayEnd)",
|
|
162
172
|
"}",
|
|
163
173
|
].join("\n");
|
|
174
|
+
return powerShellStdinEnvelope(script);
|
|
164
175
|
}
|
|
165
176
|
|
|
166
177
|
const shCommand = quotePosix(command);
|
|
@@ -535,6 +546,9 @@ export class TerminalManager {
|
|
|
535
546
|
this.platform = options.platform ?? process.platform;
|
|
536
547
|
this.shell = shellForPlatform(this.platform, options.shell);
|
|
537
548
|
this.sessions = new Map();
|
|
549
|
+
this.spawnSession = options.spawnSession ?? spawn;
|
|
550
|
+
this.terminateSession = options.terminateSession ?? terminateProcessTree;
|
|
551
|
+
this.completionSequence = 0;
|
|
538
552
|
this.processEpoch = options.processEpoch ?? randomUUID();
|
|
539
553
|
this.execOutputs = new CompactExecOutputStore(this.processEpoch);
|
|
540
554
|
this.batches = new Map();
|
|
@@ -658,6 +672,35 @@ export class TerminalManager {
|
|
|
658
672
|
});
|
|
659
673
|
}
|
|
660
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
|
+
|
|
661
704
|
startShell(cwd, observability) {
|
|
662
705
|
return this.#spawnSession({
|
|
663
706
|
type: "shell",
|
|
@@ -668,26 +711,35 @@ export class TerminalManager {
|
|
|
668
711
|
});
|
|
669
712
|
}
|
|
670
713
|
|
|
671
|
-
list() {
|
|
714
|
+
list({reservation}={}) {
|
|
672
715
|
this.#cleanup();
|
|
673
|
-
return [...this.sessions.values()].map(
|
|
716
|
+
return [...this.sessions.values()].filter(session=>reservation?session.owned?.reservation===reservation:!session.owned).map(session=>this.#summary(session));
|
|
674
717
|
}
|
|
675
718
|
|
|
676
719
|
getContinuityConfig() {
|
|
677
720
|
const activeSessions = [...this.sessions.values()]
|
|
678
721
|
.filter((session) => session.status === "running").length;
|
|
679
|
-
return
|
|
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
|
+
};
|
|
680
730
|
}
|
|
681
731
|
|
|
682
732
|
observability() {
|
|
683
733
|
this.#cleanup();
|
|
684
734
|
return {
|
|
685
735
|
ok: true,
|
|
686
|
-
|
|
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) => ({
|
|
687
738
|
sessionId: session.id,
|
|
688
739
|
processEpoch: session.processEpoch,
|
|
689
740
|
type: session.type,
|
|
690
741
|
status: session.status,
|
|
742
|
+
...this.#captureState(session),
|
|
691
743
|
exitCode: session.exitCode,
|
|
692
744
|
startedAt: session.startedAt,
|
|
693
745
|
endedAt: session.endedAt,
|
|
@@ -719,12 +771,17 @@ export class TerminalManager {
|
|
|
719
771
|
};
|
|
720
772
|
}
|
|
721
773
|
|
|
722
|
-
read(sessionId, afterSeq = 0, maxChars = MAX_READ_CHARS) {
|
|
774
|
+
read(sessionId, afterSeq = 0, maxChars = MAX_READ_CHARS, reservation) {
|
|
723
775
|
const replay = this.execOutputs.read(sessionId, afterSeq, maxChars);
|
|
724
776
|
if (replay) return replay;
|
|
725
777
|
this.#cleanup();
|
|
726
778
|
const session = this.#get(sessionId);
|
|
727
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) {
|
|
728
785
|
const limit = Math.min(Math.max(Number(maxChars) || MAX_READ_CHARS, 1024), MAX_READ_CHARS);
|
|
729
786
|
const oldestSeq = session.chunks[0]?.seq ?? session.nextSeq;
|
|
730
787
|
const chunks = [];
|
|
@@ -746,12 +803,12 @@ export class TerminalManager {
|
|
|
746
803
|
};
|
|
747
804
|
}
|
|
748
805
|
|
|
749
|
-
async readWithWait(sessionId, afterSeq = 0, maxChars = MAX_READ_CHARS, waitMs = 0) {
|
|
806
|
+
async readWithWait(sessionId, afterSeq = 0, maxChars = MAX_READ_CHARS, waitMs = 0, reservation) {
|
|
750
807
|
if (!Number.isInteger(waitMs) || waitMs < 0 || waitMs > MAX_OUTPUT_WAIT_MS) {
|
|
751
808
|
throw new Error("invalid_wait_ms");
|
|
752
809
|
}
|
|
753
|
-
const initial = this.read(sessionId, afterSeq, maxChars);
|
|
754
|
-
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) {
|
|
755
812
|
return initial;
|
|
756
813
|
}
|
|
757
814
|
const session = this.#get(sessionId);
|
|
@@ -764,8 +821,11 @@ export class TerminalManager {
|
|
|
764
821
|
if (timer === null) return;
|
|
765
822
|
clearTimeout(timer);
|
|
766
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);
|
|
767
827
|
session.waiters.delete(finish);
|
|
768
|
-
resolve(
|
|
828
|
+
resolve(page);
|
|
769
829
|
};
|
|
770
830
|
session.waiters.add(finish);
|
|
771
831
|
timer = setTimeout(finish, waitMs);
|
|
@@ -773,16 +833,17 @@ export class TerminalManager {
|
|
|
773
833
|
}
|
|
774
834
|
|
|
775
835
|
async readCompact(sessionId, afterSeq = 0, maxChars = MAX_READ_CHARS, waitMs = 0,
|
|
776
|
-
outputMode = "summary", outputChars) {
|
|
836
|
+
outputMode = "summary", outputChars, reservation) {
|
|
777
837
|
const mode = validateOutputMode(outputMode);
|
|
778
838
|
const limit = outputLimit(outputChars);
|
|
779
|
-
const page = await this.readWithWait(sessionId, afterSeq, maxChars, waitMs);
|
|
839
|
+
const page = await this.readWithWait(sessionId, afterSeq, maxChars, waitMs,reservation);
|
|
780
840
|
return compactTerminalPage(page, mode, limit, afterSeq);
|
|
781
841
|
}
|
|
782
842
|
|
|
783
843
|
write(sessionId, input, appendNewline = true) {
|
|
784
844
|
const session = this.#get(sessionId);
|
|
785
845
|
if (!session) return terminalSessionMiss(sessionId, this.processEpoch);
|
|
846
|
+
if (session.owned) throw new Error("full_owned_job_requires_broker");
|
|
786
847
|
if (session.status !== "running") throw new Error("session_not_running");
|
|
787
848
|
if (typeof input !== "string" || input.length === 0 || input.length > MAX_INPUT_CHARS) {
|
|
788
849
|
throw new Error("invalid_input");
|
|
@@ -794,9 +855,22 @@ export class TerminalManager {
|
|
|
794
855
|
async kill(sessionId) {
|
|
795
856
|
const session = this.#get(sessionId);
|
|
796
857
|
if (!session) return terminalSessionMiss(sessionId, this.processEpoch);
|
|
797
|
-
if
|
|
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
|
+
}
|
|
798
872
|
|
|
799
|
-
await
|
|
873
|
+
await this.terminateSession(this.platform, session.pid);
|
|
800
874
|
return this.#summary(session);
|
|
801
875
|
}
|
|
802
876
|
|
|
@@ -951,17 +1025,22 @@ export class TerminalManager {
|
|
|
951
1025
|
};
|
|
952
1026
|
}
|
|
953
1027
|
|
|
954
|
-
#spawnSession({ type, command, cwd, args, observability }) {
|
|
1028
|
+
#spawnSession({ type, command, cwd, args, observability, owned = null }) {
|
|
955
1029
|
this.#cleanup();
|
|
956
|
-
const
|
|
957
|
-
if (
|
|
958
|
-
|
|
959
|
-
const
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
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);
|
|
965
1044
|
|
|
966
1045
|
const session = {
|
|
967
1046
|
id: createTerminalSessionId(this.processEpoch, randomUUID()),
|
|
@@ -971,6 +1050,8 @@ export class TerminalManager {
|
|
|
971
1050
|
cwd,
|
|
972
1051
|
pid: child.pid,
|
|
973
1052
|
process: child,
|
|
1053
|
+
closed: false,
|
|
1054
|
+
completionSequence: null,
|
|
974
1055
|
status: "running",
|
|
975
1056
|
exitCode: null,
|
|
976
1057
|
signal: null,
|
|
@@ -981,18 +1062,68 @@ export class TerminalManager {
|
|
|
981
1062
|
totalChars: 0,
|
|
982
1063
|
waiters: new Set(),
|
|
983
1064
|
observability: observability ?? null,
|
|
1065
|
+
...(owned?{owned}:{}),
|
|
984
1066
|
};
|
|
985
1067
|
|
|
986
1068
|
this.sessions.set(session.id, session);
|
|
987
|
-
|
|
988
|
-
child.
|
|
989
|
-
child.
|
|
990
|
-
|
|
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) => {
|
|
991
1104
|
session.status = "exited";
|
|
992
1105
|
session.exitCode = code;
|
|
993
1106
|
session.signal = signal;
|
|
994
1107
|
session.endedAt = new Date().toISOString();
|
|
1108
|
+
if(owned)owned.reservation.rootExited();
|
|
995
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();
|
|
996
1127
|
});
|
|
997
1128
|
|
|
998
1129
|
return this.#summary(session);
|
|
@@ -1107,6 +1238,16 @@ export class TerminalManager {
|
|
|
1107
1238
|
for (const notify of session.waiters) notify();
|
|
1108
1239
|
}
|
|
1109
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
|
+
|
|
1110
1251
|
#summary(session) {
|
|
1111
1252
|
return {
|
|
1112
1253
|
sessionId: session.id,
|
|
@@ -1116,11 +1257,13 @@ export class TerminalManager {
|
|
|
1116
1257
|
cwd: session.cwd,
|
|
1117
1258
|
pid: session.pid,
|
|
1118
1259
|
status: session.status,
|
|
1260
|
+
...this.#captureState(session),
|
|
1119
1261
|
exitCode: session.exitCode,
|
|
1120
1262
|
signal: session.signal,
|
|
1121
1263
|
startedAt: session.startedAt,
|
|
1122
1264
|
endedAt: session.endedAt,
|
|
1123
1265
|
nextSeq: session.nextSeq - 1,
|
|
1266
|
+
...(session.owned?{fullJobId:session.owned.jobId,resourceReconciliationRequired:session.status!=="running"}:{}),
|
|
1124
1267
|
};
|
|
1125
1268
|
}
|
|
1126
1269
|
|
|
@@ -1139,9 +1282,24 @@ export class TerminalManager {
|
|
|
1139
1282
|
#cleanup() {
|
|
1140
1283
|
const now = Date.now();
|
|
1141
1284
|
for (const [id, session] of this.sessions) {
|
|
1142
|
-
if (session.status === "running" || !session.endedAt) continue;
|
|
1285
|
+
if (!session.closed || session.status === "running" || !session.endedAt) continue;
|
|
1143
1286
|
if (now - Date.parse(session.endedAt) > ENDED_TTL_MS) this.sessions.delete(id);
|
|
1144
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
|
+
}
|
|
1145
1303
|
for (const [id, batch] of this.batches) {
|
|
1146
1304
|
if (!batch.endedAt) continue;
|
|
1147
1305
|
if (now - Date.parse(batch.endedAt) > ENDED_TTL_MS) this.batches.delete(id);
|
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
2
|
import { humanizeToolCall } from "./toolcall-summary.mjs";
|
|
3
3
|
|
|
4
|
+
export function activityCategory(item) {
|
|
5
|
+
if (item.category) return String(item.category);
|
|
6
|
+
const action = String(item.action || "");
|
|
7
|
+
if (action.startsWith("fs.")) return "Filesystem";
|
|
8
|
+
if (action.startsWith("terminal.")) return "Terminal";
|
|
9
|
+
if (action.startsWith("desktop.")) return "Desktop";
|
|
10
|
+
if (action.startsWith("learn")) return "Learn";
|
|
11
|
+
return "Agent";
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function activityIcon(item) {
|
|
15
|
+
const action = String(item.action || "").toLowerCase();
|
|
16
|
+
const title = String(item.operation || item.summary || "").toLowerCase();
|
|
17
|
+
if (/search/.test(action) || /^(start|search)\b/.test(title)) return "🔎";
|
|
18
|
+
if (/(^|\.)(read|readmany|getcontent)(_|$|\.)/.test(action) || /^read\b/.test(title)) return "📖";
|
|
19
|
+
if (/(^|\.)(write|edit|move|mkdir|delete)(_|$|\.)/.test(action) || /^(write|edit|create|delete|move)\b/.test(title)) return "✏️";
|
|
20
|
+
if (activityCategory(item) === "Terminal") return "📟";
|
|
21
|
+
if (activityCategory(item) === "Filesystem") return "📁";
|
|
22
|
+
return "";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
4
26
|
// Derive concise local UI labels, not raw commands or full request payloads.
|
|
5
27
|
const WORKSPACE_DIR = /^(projects?|workspaces?|repos?|repositories|code|src)$/i;
|
|
6
28
|
|
|
@@ -188,7 +210,7 @@ export function describeToolActivity(payload = {}, allowedRoots = [], linkedCont
|
|
|
188
210
|
operation = "Read " + count(payload.paths) + " files";
|
|
189
211
|
break;
|
|
190
212
|
case "fs.editMany":
|
|
191
|
-
operation = "Edit " +
|
|
213
|
+
operation = "Edit " + new Set((Array.isArray(payload.operations)?payload.operations:[]).map(item=>item?.path).filter(value=>typeof value==="string")).size + " files";
|
|
192
214
|
break;
|
|
193
215
|
case "fs.batch.compact":
|
|
194
216
|
case "fs.batch":
|
|
@@ -11,6 +11,8 @@ export class PersistentDesktopRunner {
|
|
|
11
11
|
constructor(options = {}) {
|
|
12
12
|
this.platform = options.platform ?? process.platform;
|
|
13
13
|
this.timeoutMs = Number(options.timeoutMs ?? POWERSHELL_TIMEOUT_MS);
|
|
14
|
+
this.spawn = options.spawn ?? spawn;
|
|
15
|
+
this.worker = null;
|
|
14
16
|
this.process = null;
|
|
15
17
|
this.stdout = null;
|
|
16
18
|
this.pending = new Map();
|
|
@@ -19,91 +21,93 @@ export class PersistentDesktopRunner {
|
|
|
19
21
|
|
|
20
22
|
ensureStarted() {
|
|
21
23
|
if (this.platform !== "win32") return false;
|
|
22
|
-
if (this.
|
|
24
|
+
if (this.worker && !this.worker.closed && !this.worker.child.killed) {
|
|
25
|
+
return this.worker.child.exitCode === null && this.worker.child.signalCode === null;
|
|
26
|
+
}
|
|
27
|
+
if (this.worker) this.#stopWorker(this.worker, "desktop_worker_exited");
|
|
23
28
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
"
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
"
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
], {
|
|
34
|
-
windowsHide: true,
|
|
35
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
36
|
-
});
|
|
29
|
+
let child;
|
|
30
|
+
try {
|
|
31
|
+
child = this.spawn("powershell.exe", [
|
|
32
|
+
"-NoLogo", "-NoProfile", "-NonInteractive", "-Sta",
|
|
33
|
+
"-ExecutionPolicy", "Bypass", "-File", helperPath,
|
|
34
|
+
], { windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
|
|
35
|
+
} catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
37
38
|
|
|
39
|
+
// Every callback belongs to this child. A delayed exit/error from a retired
|
|
40
|
+
// generation must never clear a replacement worker or settle its requests.
|
|
41
|
+
const worker = {
|
|
42
|
+
child, stdout: readline.createInterface({ input: child.stdout }),
|
|
43
|
+
pending: new Map(), closed: false,
|
|
44
|
+
};
|
|
45
|
+
this.worker = worker;
|
|
38
46
|
this.process = child;
|
|
47
|
+
this.stdout = worker.stdout;
|
|
48
|
+
this.pending = worker.pending;
|
|
39
49
|
this.stderr = "";
|
|
40
|
-
this.stdout = readline.createInterface({ input: child.stdout });
|
|
41
50
|
|
|
42
|
-
|
|
51
|
+
worker.stdout.on("line", line => {
|
|
52
|
+
if (worker.closed) return;
|
|
43
53
|
let message;
|
|
44
|
-
try {
|
|
45
|
-
|
|
46
|
-
} catch {
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
const pending = this.pending.get(message?.id);
|
|
50
|
-
if (!pending) return;
|
|
51
|
-
clearTimeout(pending.timer);
|
|
52
|
-
this.pending.delete(message.id);
|
|
53
|
-
pending.resolve(message.result ?? { ok: false, error: "desktop_worker_error" });
|
|
54
|
+
try { message = JSON.parse(line); } catch { return; }
|
|
55
|
+
this.#settle(worker, message?.id, message?.result ?? { ok: false, error: "desktop_worker_error" });
|
|
54
56
|
});
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
this.stderr = (this.stderr + String(chunk)).slice(-8192);
|
|
58
|
-
});
|
|
59
|
-
|
|
60
|
-
child.on("exit", () => {
|
|
61
|
-
const error = { ok: false, error: "desktop_worker_exited" };
|
|
62
|
-
for (const pending of this.pending.values()) {
|
|
63
|
-
clearTimeout(pending.timer);
|
|
64
|
-
pending.resolve(error);
|
|
65
|
-
}
|
|
66
|
-
this.pending.clear();
|
|
67
|
-
this.stdout?.close();
|
|
68
|
-
this.stdout = null;
|
|
69
|
-
this.process = null;
|
|
57
|
+
child.stderr.on("data", chunk => {
|
|
58
|
+
if (this.worker === worker) this.stderr = (this.stderr + String(chunk)).slice(-8192);
|
|
70
59
|
});
|
|
60
|
+
child.once("close", () => this.#stopWorker(worker, "desktop_worker_exited"));
|
|
61
|
+
// Spawn errors need not emit exit. Pipe errors must also settle promptly,
|
|
62
|
+
// without retrying a request whose delivery may already have occurred.
|
|
63
|
+
child.on("error", () => this.#stopWorker(worker, "desktop_worker_error", true));
|
|
64
|
+
child.stdin.on("error", () => this.#stopWorker(worker, "desktop_worker_error", true));
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
71
67
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
68
|
+
#settle(worker, id, result) {
|
|
69
|
+
const pending = worker.pending.get(id);
|
|
70
|
+
if (!pending) return;
|
|
71
|
+
worker.pending.delete(id);
|
|
72
|
+
clearTimeout(pending.timer);
|
|
73
|
+
pending.resolve(result);
|
|
74
|
+
}
|
|
75
75
|
|
|
76
|
-
|
|
76
|
+
#stopWorker(worker, error, kill = false) {
|
|
77
|
+
if (worker.closed) return;
|
|
78
|
+
worker.closed = true;
|
|
79
|
+
for (const id of worker.pending.keys()) this.#settle(worker, id, { ok: false, error });
|
|
80
|
+
try { worker.stdout.close(); } catch {}
|
|
81
|
+
if (this.worker === worker) {
|
|
82
|
+
this.worker = null;
|
|
83
|
+
this.process = null;
|
|
84
|
+
this.stdout = null;
|
|
85
|
+
}
|
|
86
|
+
if (kill) { try { worker.child.kill(); } catch {} }
|
|
77
87
|
}
|
|
78
88
|
|
|
79
89
|
async run(operation, args) {
|
|
80
90
|
if (!this.ensureStarted() || !this.process?.stdin?.writable) {
|
|
81
91
|
return { ok: false, error: operation === "screenshot" ? "capture_failed" : "input_failed" };
|
|
82
92
|
}
|
|
83
|
-
|
|
93
|
+
const worker = this.worker;
|
|
84
94
|
const id = randomUUID();
|
|
85
95
|
const request = JSON.stringify({ id, operation, args: args || {} }) + "\n";
|
|
86
|
-
|
|
87
|
-
return new Promise((resolve) => {
|
|
96
|
+
return new Promise(resolve => {
|
|
88
97
|
const timer = setTimeout(() => {
|
|
89
|
-
|
|
90
|
-
|
|
98
|
+
// Timeout is an unknown-delivery observation, not a replay permission.
|
|
99
|
+
this.#settle(worker, id, { ok: false, error: operation === "screenshot" ? "capture_timeout" : "input_timeout" });
|
|
91
100
|
}, this.timeoutMs);
|
|
92
|
-
|
|
93
|
-
this
|
|
94
|
-
|
|
95
|
-
if (!error) return;
|
|
96
|
-
clearTimeout(timer);
|
|
97
|
-
this.pending.delete(id);
|
|
98
|
-
resolve({ ok: false, error: operation === "screenshot" ? "capture_failed" : "input_failed" });
|
|
101
|
+
worker.pending.set(id, { resolve, timer });
|
|
102
|
+
const failed = () => this.#settle(worker, id, {
|
|
103
|
+
ok: false, error: operation === "screenshot" ? "capture_failed" : "input_failed",
|
|
99
104
|
});
|
|
105
|
+
try { worker.child.stdin.write(request, error => { if (error) failed(); }); }
|
|
106
|
+
catch { failed(); }
|
|
100
107
|
});
|
|
101
108
|
}
|
|
102
109
|
|
|
103
110
|
close() {
|
|
104
|
-
|
|
105
|
-
try { this.process?.kill(); } catch {}
|
|
106
|
-
this.stdout = null;
|
|
107
|
-
this.process = null;
|
|
111
|
+
if (this.worker) this.#stopWorker(this.worker, "desktop_worker_exited", true);
|
|
108
112
|
}
|
|
109
113
|
}
|