@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,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
 
@@ -65,20 +87,20 @@ function candidatePaths(payload) {
65
87
  .map((job) => ({ value: job && typeof job === "object" ? job.cwd || fallbackCwd : fallbackCwd, directory: true }));
66
88
  }
67
89
  if (action.startsWith("terminal.")) {
68
- if (action === "terminal.exec" || action === "terminal.start" || action === "terminal.shell.start") {
90
+ if (action === "terminal.exec" || action === "terminal.exec.compact" || action === "terminal.start" || action === "terminal.shell.start") {
69
91
  return [{ value: payload.cwd, directory: true }];
70
92
  }
71
93
  return [];
72
94
  }
73
- if (action === "fs.batch") {
95
+ if (["fs.batch", "fs.batch.compact", "fs.editMany"].includes(action)) {
74
96
  return (Array.isArray(payload.operations) ? payload.operations : [])
75
97
  .flatMap((item) => [item?.path, item?.source, item?.destination]
76
98
  .filter((value) => typeof value === "string")
77
- .map((value) => ({ value, cwd: payload.cwd, directory: item?.op === "list" })));
99
+ .map((value) => ({ value, cwd: payload.basePath || payload.cwd, directory: item?.op === "list" || item?.op === "search" })));
78
100
  }
79
- if (action === "fs.readMany") {
101
+ if (action === "fs.readMany" || action === "fs.readMany.relative") {
80
102
  return (Array.isArray(payload.paths) ? payload.paths : [])
81
- .map((item) => ({ value: typeof item === "string" ? item : item?.path, cwd: payload.cwd }));
103
+ .map((item) => ({ value: typeof item === "string" ? item : item?.path, cwd: payload.basePath || payload.cwd }));
82
104
  }
83
105
  if (action === "fs.move") {
84
106
  return [{ value: payload.source, cwd: payload.cwd }, { value: payload.destination, cwd: payload.cwd }];
@@ -183,9 +205,14 @@ export function describeToolActivity(payload = {}, allowedRoots = [], linkedCont
183
205
  case "fs.read":
184
206
  operation = "Read " + shortName(payload.path);
185
207
  break;
208
+ case "fs.readMany.relative":
186
209
  case "fs.readMany":
187
210
  operation = "Read " + count(payload.paths) + " files";
188
211
  break;
212
+ case "fs.editMany":
213
+ operation = "Edit " + new Set((Array.isArray(payload.operations)?payload.operations:[]).map(item=>item?.path).filter(value=>typeof value==="string")).size + " files";
214
+ break;
215
+ case "fs.batch.compact":
189
216
  case "fs.batch":
190
217
  operation = "Inspect " + count(payload.operations) + " filesystem items";
191
218
  break;
@@ -195,6 +222,7 @@ export function describeToolActivity(payload = {}, allowedRoots = [], linkedCont
195
222
  case "fs.list":
196
223
  operation = "Browse " + shortName(payload.path);
197
224
  break;
225
+ case "terminal.exec.compact":
198
226
  case "terminal.exec":
199
227
  case "terminal.start":
200
228
  operation = terminalTitle(payload);
@@ -202,12 +230,14 @@ export function describeToolActivity(payload = {}, allowedRoots = [], linkedCont
202
230
  case "terminal.batch.start":
203
231
  operation = "Run " + count(payload.jobs) + " terminal tasks";
204
232
  break;
233
+ case "terminal.batch.read.compact":
205
234
  case "terminal.batch.read":
206
235
  operation = "Review terminal batch results";
207
236
  break;
208
237
  case "terminal.batch.status":
209
238
  operation = "Check terminal batch progress";
210
239
  break;
240
+ case "terminal.read.compact":
211
241
  case "terminal.read":
212
242
  operation = "Review terminal output";
213
243
  break;
@@ -164,6 +164,9 @@ export function humanizeToolCall(payload = {}) {
164
164
  return "Check agent connection";
165
165
  case "agent.config":
166
166
  return "Read agent configuration";
167
+ case "agent.usageStats":
168
+ return `Read ${number(payload.days, 30)} days of local usage statistics`;
169
+ case "agent.recentCalls.page":
167
170
  case "agent.recentCalls":
168
171
  return `Read recent activity · up to ${number(payload.limit, 50)} calls`;
169
172
  case "agent.lifecycle.status":
@@ -181,8 +184,12 @@ export function humanizeToolCall(payload = {}) {
181
184
  return `Browse ${compactPath(payload.path)} · depth ${number(payload.depth)} · up to ${number(payload.limit, 100)} items`;
182
185
  case "fs.read":
183
186
  return `Read ${compactPath(payload.path)} · ${lineRange(payload)}`;
187
+ case "fs.readMany.relative":
184
188
  case "fs.readMany":
185
189
  return `Read ${Array.isArray(payload.paths) ? payload.paths.length : 0} files`;
190
+ case "fs.editMany":
191
+ return `Edit ${Array.isArray(payload.operations) ? payload.operations.length : 0} files`;
192
+ case "fs.batch.compact":
186
193
  case "fs.batch":
187
194
  return `Inspect filesystem · ${Array.isArray(payload.operations) ? payload.operations.length : 0} operations`;
188
195
  case "fs.artifact":
@@ -212,12 +219,14 @@ export function humanizeToolCall(payload = {}) {
212
219
  case "process.kill":
213
220
  return `Stop process ${number(payload.pid)}`;
214
221
 
222
+ case "terminal.exec.compact":
215
223
  case "terminal.exec":
216
224
  return withCwd(humanizeCommand(payload.command), payload.cwd);
217
225
  case "terminal.start":
218
226
  return withCwd(`Start background task · ${humanizeCommand(payload.command).replace(/^Run /, "")}`, payload.cwd);
219
227
  case "terminal.shell.start":
220
228
  return withCwd("Open interactive shell", payload.cwd);
229
+ case "terminal.read.compact":
221
230
  case "terminal.read":
222
231
  return `Read terminal output · ${cleanText(payload.sessionId, 24)} · after #${number(payload.afterSeq)}${Number(payload.waitMs) > 0 ? ` · wait up to ${number(payload.waitMs)}ms` : ""}`;
223
232
  case "terminal.write":
@@ -232,6 +241,7 @@ export function humanizeToolCall(payload = {}) {
232
241
  return `Run terminal batch · ${Array.isArray(payload.jobs) ? payload.jobs.length : 0} jobs · ${number(payload.concurrency, 1)} at a time`;
233
242
  case "terminal.batch.status":
234
243
  return `Check batch progress · ${cleanText(payload.batchId, 24)}`;
244
+ case "terminal.batch.read.compact":
235
245
  case "terminal.batch.read":
236
246
  return `Read batch output · ${cleanText(payload.batchId, 24)}`;
237
247
  case "terminal.batch.cancel":
@@ -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.process && !this.process.killed) return true;
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
- const child = spawn("powershell.exe", [
25
- "-NoLogo",
26
- "-NoProfile",
27
- "-NonInteractive",
28
- "-Sta",
29
- "-ExecutionPolicy",
30
- "Bypass",
31
- "-File",
32
- helperPath,
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
- this.stdout.on("line", (line) => {
51
+ worker.stdout.on("line", line => {
52
+ if (worker.closed) return;
43
53
  let message;
44
- try {
45
- message = JSON.parse(line);
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
- child.stderr.on("data", (chunk) => {
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
- child.on("error", () => {
73
- // exit handler settles pending work.
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
- return true;
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
- this.pending.delete(id);
90
- resolve({ ok: false, error: operation === "screenshot" ? "capture_timeout" : "input_timeout" });
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.pending.set(id, { resolve, timer });
94
- this.process.stdin.write(request, (error) => {
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
- try { this.stdout?.close(); } catch {}
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
  }
@@ -140,7 +140,11 @@ public static class ChatRelayNative {
140
140
  }
141
141
 
142
142
  public static bool UnicodeText(string text) {
143
- foreach (char c in text) {
143
+ for (int index = 0; index < text.Length; index++) {
144
+ char c = text[index];
145
+ // Win32 Edit treats CR and LF as separate line breaks. A CRLF pair is
146
+ // one logical newline; retain lone CR/LF and all other UTF-16 units.
147
+ if (c == '\r' && index + 1 < text.Length && text[index + 1] == '\n') index++;
144
148
  var inputs = new INPUT[2];
145
149
  inputs[0].type = INPUT_KEYBOARD;
146
150
  inputs[0].U.ki.wScan = c;
@@ -566,24 +570,35 @@ function Invoke-Operation([string]$Operation, $Payload) {
566
570
  }
567
571
  }
568
572
 
569
- while (($line = [Console]::In.ReadLine()) -ne $null) {
570
- if ([string]::IsNullOrWhiteSpace($line)) { continue }
573
+ # JSON is UTF-8 in both directions. Console.In/Out otherwise use the inherited
574
+ # OEM code page on Windows PowerShell 5.1, even when their handles are pipes.
575
+ # Dedicated streams also avoid changing the surrounding console's code page.
576
+ $transportEncoding = [System.Text.UTF8Encoding]::new($false)
577
+ $transportInput = [System.IO.StreamReader]::new([Console]::OpenStandardInput(), $transportEncoding, $false)
578
+ $transportOutput = [System.IO.StreamWriter]::new([Console]::OpenStandardOutput(), $transportEncoding)
579
+ try {
580
+ while (($line = $transportInput.ReadLine()) -ne $null) {
581
+ if ([string]::IsNullOrWhiteSpace($line)) { continue }
582
+
583
+ $id = $null
584
+ $result = $null
585
+ try {
586
+ $request = $line | ConvertFrom-Json
587
+ $id = [string]$request.id
588
+ $result = Invoke-Operation ([string]$request.operation) $request.args
589
+ } catch {
590
+ $result = Result-Error "desktop_worker_error"
591
+ }
571
592
 
572
- $id = $null
573
- $result = $null
574
- try {
575
- $request = $line | ConvertFrom-Json
576
- $id = [string]$request.id
577
- $result = Invoke-Operation ([string]$request.operation) $request.args
578
- } catch {
579
- $result = Result-Error "desktop_worker_error"
580
- }
593
+ $response = [pscustomobject]@{
594
+ id = $id
595
+ result = $result
596
+ }
581
597
 
582
- $response = [pscustomobject]@{
583
- id = $id
584
- result = $result
598
+ $transportOutput.WriteLine(($response | ConvertTo-Json -Compress -Depth 10))
599
+ $transportOutput.Flush()
585
600
  }
586
-
587
- [Console]::Out.WriteLine(($response | ConvertTo-Json -Compress -Depth 10))
588
- [Console]::Out.Flush()
601
+ } finally {
602
+ $transportInput.Dispose()
603
+ $transportOutput.Dispose()
589
604
  }
@@ -0,0 +1,51 @@
1
+ // Windows PowerShell 5.1 uses the console code page for redirected IO and
2
+ // ASCII for text piped to native programs. Relay's text transports use UTF-8.
3
+ // Run this before any user input is read; do not transform arbitrary stdin.
4
+ export const POWERSHELL_UTF8_SETUP =
5
+ "try { $OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { throw };";
6
+
7
+ function encodePowerShellScript(script) {
8
+ return Buffer.from(script, "utf16le").toString("base64");
9
+ }
10
+
11
+ export function powerShellUtf8Script(script) {
12
+ // Pass this ASCII-only text to -Command. Windows PowerShell 5.1 forces
13
+ // redirected stderr into CLIXML with -EncodedCommand, even with Text output.
14
+ // See PowerShell/PowerShell#5912 and #8115 (the later PowerShell Core fix).
15
+ // The envelope preserves the exit status of a final native command.
16
+ return POWERSHELL_UTF8_SETUP + "\n" + powerShellStdinEnvelope(script);
17
+ }
18
+
19
+ // The -Command - parser may already have buffered stdin using the OEM code
20
+ // page. Only ASCII crosses that parser; decode after it has parsed the wrapper.
21
+ // Dot-source the script block so using/param statements and script scope remain
22
+ // unchanged. PowerShell otherwise exits 0 when a final native executable exits
23
+ // non-zero. Inspect the parsed final pipeline before execution, then propagate
24
+ // $LASTEXITCODE only when its final command resolves to a native Application.
25
+ // An explicit "exit $LASTEXITCODE" in the user's script remains authoritative.
26
+ export function powerShellStdinEnvelope(script) {
27
+ const encoded=encodePowerShellScript(script);
28
+ return [
29
+ "$__relayScript = [ScriptBlock]::Create([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('"+encoded+"')));",
30
+ "$__relayStatements = $__relayScript.Ast.EndBlock.Statements;",
31
+ "$__relayLastStatement = if ($__relayStatements.Count -gt 0) { $__relayStatements[$__relayStatements.Count - 1] } else { $null };",
32
+ "$__relayLastCommand = if ($__relayLastStatement -is [System.Management.Automation.Language.PipelineAst] -and $__relayLastStatement.PipelineElements.Count -gt 0) { $__relayLastStatement.PipelineElements[$__relayLastStatement.PipelineElements.Count - 1] } else { $null };",
33
+ ". $__relayScript;",
34
+ "if ($__relayLastCommand -is [System.Management.Automation.Language.CommandAst]) {",
35
+ " $__relayCommandName = $__relayLastCommand.GetCommandName();",
36
+ " if (-not $__relayCommandName -and $__relayLastCommand.CommandElements.Count -gt 0 -and $__relayLastCommand.CommandElements[0] -is [System.Management.Automation.Language.VariableExpressionAst]) {",
37
+ " $__relayVariablePath = $__relayLastCommand.CommandElements[0].VariablePath;",
38
+ " $__relayVariableName = $__relayVariablePath.UserPath;",
39
+ " if ($__relayVariablePath.DriveName) { $__relayVariableName = $__relayVariableName.Substring($__relayVariableName.IndexOf(':') + 1) };",
40
+ " if ($__relayVariablePath.DriveName -eq 'env') { $__relayCommandName = [Environment]::GetEnvironmentVariable($__relayVariableName) } else { $__relayCommandName = Get-Variable -Name $__relayVariableName -ValueOnly -ErrorAction SilentlyContinue };",
41
+ " }",
42
+ " if ($__relayCommandName -is [System.Management.Automation.CommandInfo]) { $__relayResolvedCommand = $__relayCommandName }",
43
+ " elseif ($__relayCommandName) { $__relayResolvedCommand = Get-Command -Name ([string]$__relayCommandName) -ErrorAction SilentlyContinue | Select-Object -First 1 };",
44
+ " if ($__relayCommandName -or $__relayLastCommand.CommandElements[0] -is [System.Management.Automation.Language.VariableExpressionAst]) {",
45
+ " while ($__relayResolvedCommand -and $__relayResolvedCommand.CommandType -eq [System.Management.Automation.CommandTypes]::Alias) { $__relayResolvedCommand = $__relayResolvedCommand.ResolvedCommand };",
46
+ " if (-not $__relayResolvedCommand) { exit 1 };",
47
+ " if ($__relayResolvedCommand.CommandType -eq [System.Management.Automation.CommandTypes]::Application) { if ($null -eq $LASTEXITCODE) { exit 1 } else { exit $LASTEXITCODE } };",
48
+ " }",
49
+ "}"
50
+ ].join("\n");
51
+ }
@@ -0,0 +1,69 @@
1
+ import {spawn} from "node:child_process";
2
+
3
+ // The user-facing Windows launcher returns only after the existing runner has
4
+ // acknowledged the GUI or a new Core has started it. No second cloud runner.
5
+ const CHANNEL="chat-relay-full-background";
6
+ const MARKER="CHAT_RELAY_FULL_BACKGROUND";
7
+ export function shouldLaunchFullBackground(options,{platform=process.platform,managed=typeof process.send==="function"}={}){
8
+ return platform==="win32"&&options.full===true&&options.headless!==true&&options.tuiEnabled!==false&&!managed&&Array.isArray(options.launchArgs);
9
+ }
10
+ export function launchFullBackground({entrypoint,args,timeoutMs=160000}){
11
+ return new Promise(resolve=>{
12
+ let child,ready=false,finished=false,timer;
13
+ const finish=(code)=>{
14
+ if(finished)return;finished=true;clearTimeout(timer);
15
+ if(child?.connected)try{child.disconnect();}catch{}
16
+ child?.unref();
17
+ if(code!==0)console.error("Full desktop launch not acknowledged. Run remote --full --plain for diagnostics.");
18
+ resolve(code);
19
+ };
20
+ try{
21
+ child=spawn(process.execPath,[entrypoint,...args],{detached:true,windowsHide:true,stdio:["ignore","ignore","ignore","ipc"],env:{...process.env,[MARKER]:"1"}});
22
+ }catch{finish(1);return;}
23
+ child.on("message",message=>{
24
+ if(finished||message?.type!==CHANNEL)return;
25
+ if(ready&&message.kind==="accepted"){finish(0);return;}
26
+ if(ready||message.kind!=="ready")return;
27
+ ready=true;
28
+ try{child.send({type:CHANNEL,kind:"ack"},error=>{if(error)finish(1);});}catch{finish(1);}
29
+ });
30
+ child.once("disconnect",()=>finish(1));
31
+ child.once("error",()=>finish(1));
32
+ child.once("exit",()=>finish(1));
33
+ timer=setTimeout(()=>finish(1),timeoutMs);
34
+ });
35
+ }
36
+ export function createBackgroundHandoff(channel=process){
37
+ if(channel.env?.[MARKER]!=="1"||typeof channel.send!=="function")return null;
38
+ delete channel.env[MARKER];
39
+ let acknowledged=false,flight;
40
+ return {
41
+ get acknowledged(){return acknowledged;},
42
+ announce(){
43
+ if(acknowledged)return Promise.resolve(true);
44
+ if(flight)return flight;
45
+ flight=new Promise(resolve=>{
46
+ let timer,done=false;
47
+ const finish=ok=>{
48
+ if(done)return;done=true;clearTimeout(timer);
49
+ channel.removeListener("message",onAck);channel.removeListener("disconnect",onDisconnect);
50
+ acknowledged=ok;
51
+ if(ok&&channel.connected)try{channel.disconnect();}catch{}
52
+ resolve(ok);
53
+ };
54
+ const onAck=message=>{
55
+ if(message?.type!==CHANNEL||message.kind!=="ack"||done)return;
56
+ channel.removeListener("message",onAck);
57
+ acknowledged=true;
58
+ try{channel.send({type:CHANNEL,kind:"accepted"},error=>finish(!error));}catch{finish(false);}
59
+ };
60
+ const onDisconnect=()=>finish(acknowledged);
61
+ if(!channel.connected){finish(false);return;}
62
+ channel.on("message",onAck);channel.once("disconnect",onDisconnect);
63
+ timer=setTimeout(()=>finish(false),5000);
64
+ try{channel.send({type:CHANNEL,kind:"ready"},error=>{if(error)finish(false);});}catch{finish(false);}
65
+ });
66
+ return flight;
67
+ }
68
+ };
69
+ }
@@ -0,0 +1,94 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import {createHash,randomUUID} from "node:crypto";
4
+ import {configDir} from "./config.mjs";
5
+ import {getAgentVersion} from "../agent/protocol.mjs";
6
+ import {prepareFullArtifact} from "./full-prepare.mjs";
7
+ import {regularFile,readBounded} from "./full-release-files.mjs";
8
+ import {releaseSourceUrl} from "./full-release-source.mjs";
9
+ import {officialFullSettings} from "./full-release-official.mjs";
10
+ import {ModError,MAX_MANIFEST_BYTES} from "./mod-manifest.mjs";
11
+
12
+ const require=(ok,code)=>{if(!ok)throw new ModError(code);};
13
+ export function supportedFullNode(version=process.versions.node){
14
+ const match=/^(\d+)\.(\d+)\.(\d+)$/.exec(version);
15
+ if(!match)return false;
16
+ const [major,minor,patch]=match.slice(1).map(Number);
17
+ const atLeast=(m,p)=>minor>m||minor===m&&patch>=p;
18
+ return major===22&&atLeast(23,4)||major===24&&atLeast(22,1)||major===26&&atLeast(12,1)||major>26;
19
+ }
20
+ export async function readFullReleaseSettings({home=configDir(),headless=true}={}){
21
+ // Explicit local configuration overrides the immutable npm release pin.
22
+ // No release URL, key or version from relay payloads.
23
+ let raw;
24
+ try{raw=JSON.parse((await readBounded(path.join(home,"full-release.json"),MAX_MANIFEST_BYTES)).toString("utf8"));}
25
+ catch(error){if(error.code==="ENOENT")return officialFullSettings({headless});throw new ModError("full_invalid_release_configuration");}
26
+ require(raw&&typeof raw==="object"&&!Array.isArray(raw)&&Object.keys(raw).every(k=>["headlessVersion","guiVersion","trustedKeys","sourceDirectory","guiSourceDirectory","sourceUrl","guiSourceUrl"].includes(k)),"full_invalid_release_configuration");
27
+ const requestedVersion=headless?raw.headlessVersion:raw.guiVersion;
28
+ require(typeof requestedVersion==="string"&&/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[A-Za-z0-9.-]+)?$/.test(requestedVersion)&&requestedVersion.length<=64,"full_invalid_release_configuration");
29
+ const entries=Object.entries(raw.trustedKeys??{});
30
+ require(raw.trustedKeys&&typeof raw.trustedKeys==="object"&&!Array.isArray(raw.trustedKeys)&&entries.length>=1&&entries.length<=8&&entries.every(([key,value])=>/^[A-Za-z0-9_-]{1,64}$/.test(key)&&typeof value==="string"&&value.length<=1024&&value.includes("BEGIN PUBLIC KEY")),"full_invalid_release_configuration");
31
+ for(const value of [raw.sourceDirectory,raw.guiSourceDirectory])require(value===undefined||typeof value==="string"&&path.isAbsolute(value),"full_invalid_release_configuration");
32
+ for(const url of [raw.sourceUrl,raw.guiSourceUrl])if(url!==undefined)releaseSourceUrl(url);
33
+ const sourceDirectory=headless?raw.sourceDirectory:raw.guiSourceDirectory??(raw.guiSourceUrl?undefined:raw.sourceDirectory);
34
+ const sourceUrl=headless?raw.sourceUrl:raw.guiSourceUrl??(raw.guiSourceDirectory?undefined:raw.sourceUrl);
35
+ require(!(sourceDirectory&&sourceUrl),"full_invalid_release_configuration");
36
+ return {headless,requestedVersion,trustedKeys:new Map(entries),sourceDirectory,sourceUrl};
37
+ }
38
+ export function fullStateDirectory(home,{relayUrl,agentId}){
39
+ require(typeof relayUrl==="string"&&typeof agentId==="string"&&/^[a-z0-9_-]{1,64}$/.test(agentId),"full_invalid_host_configuration");
40
+ const normalized=new URL(relayUrl);
41
+ require(["http:","https:"].includes(normalized.protocol)&&!normalized.username&&!normalized.password&&!normalized.hash&&!normalized.search,"full_invalid_host_configuration");
42
+ const key=createHash("sha256").update(JSON.stringify([normalized.href.replace(/\/+$/,""),agentId])).digest("hex");
43
+ return path.resolve(home,"full-state",key);
44
+ }
45
+ async function existingDirectory(directory){
46
+ try{
47
+ const stat=await fs.lstat(directory);require(stat.isDirectory()&&!stat.isSymbolicLink(),"full_unsafe_state_directory");return true;
48
+ }catch(error){if(error.code==="ENOENT")return false;throw error;}
49
+ }
50
+ export async function inspectFullSchema(directory){
51
+ if(!await existingDirectory(path.dirname(directory))||!await existingDirectory(directory))return 0;
52
+ const file=path.join(directory,"sessions.sqlite");
53
+ try{await regularFile(file,Number.MAX_SAFE_INTEGER);}
54
+ catch(error){if(error.code==="ENOENT")return 0;throw error;}
55
+ for(const sidecar of [file+"-wal",file+"-shm"]){
56
+ try{await regularFile(sidecar,Number.MAX_SAFE_INTEGER);}
57
+ catch(error){if(error.code!=="ENOENT")throw error;}
58
+ }
59
+ // Only explicit Full touches node:sqlite. Inspect without migration or
60
+ // acquiring ownership; the supervised host independently checks again.
61
+ const {DatabaseSync}=await import("node:sqlite");
62
+ const db=new DatabaseSync(file,{readOnly:true});
63
+ try{
64
+ const version=db.prepare("PRAGMA user_version").get().user_version;
65
+ const app=db.prepare("PRAGMA application_id").get().application_id;
66
+ require(Number.isSafeInteger(version)&&version>=1&&app===0x4352464d,"full_storage_unrecognized");
67
+ return version;
68
+ }finally{db.close();}
69
+ }
70
+ export function localFullPrincipal(config,authentication){
71
+ const accountId=authentication?.user?.id;
72
+ const grants=authentication?.agents?.find(agent=>agent.id===config?.agentId)?.scopes;
73
+ require(typeof accountId==="string"&&/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(accountId)&&Array.isArray(grants),"full_unauthorized");
74
+ const scopes=["read","write","terminal"].filter(scope=>(grants.includes("*")||grants.includes(scope))&&(scope!=="terminal"||config.terminalEnabled!==false));
75
+ require(scopes.includes("read"),"full_unauthorized");
76
+ return {accountId,agentId:config.agentId,scopes};
77
+ }
78
+ // Official keys are release-specific; an unrelated development or previous
79
+ // release cache must never block a verified upgrade or weaken signature checks.
80
+ export function fullCacheRoot(home,settings,coreVersion){
81
+ if(!settings.official)return path.resolve(home,"full-cache");
82
+ require(typeof coreVersion==="string"&&/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(coreVersion),"full_invalid_release_configuration");
83
+ return path.resolve(home,"full-cache-official",coreVersion);
84
+ }
85
+ export async function prepareFullLaunch({settings,config,principal,home=configDir(),nodeVersion=process.versions.node,coreVersion=getAgentVersion(),signal}){
86
+ require(supportedFullNode(nodeVersion),"full_node_unsupported");
87
+ const headless=settings.headless!==false;
88
+ if(!headless)require(principal?.agentId===config.agentId&&principal.scopes?.includes("read"),"full_unauthorized");
89
+ const sessionDirectory=fullStateDirectory(home,config);
90
+ const schemaVersion=await inspectFullSchema(sessionDirectory);
91
+ const artifact=await prepareFullArtifact({settings,cacheRoot:fullCacheRoot(home,settings,coreVersion),schemaVersion,coreVersion,signal});
92
+ require(artifact.capabilities.includes("full.sessions"),"full_capability_unavailable");
93
+ return {headless,coreRunnerId:randomUUID(),sessionDirectory,...(!headless?{localPrincipal:principal}:{}),artifact:{artifactId:artifact.artifactId,executablePath:artifact.executablePath,capabilities:[...artifact.capabilities]}};
94
+ }
@@ -0,0 +1,48 @@
1
+ import {resolveFullMod} from "./mod-loader.mjs";
2
+ import {localRelease} from "./full-release-files.mjs";
3
+ import {fetchFullRelease,releaseSourceUrl} from "./full-release-source.mjs";
4
+ import {fetchOfficialFullRelease} from "./full-release-official.mjs";
5
+ import {REMOTE_FULL_CAPABILITIES} from "../packages/full-contracts/remote-session.mjs";
6
+ import {validatePreparationRequest,validatePreparationResult} from "./full-prepare.mjs";
7
+
8
+ if(typeof process.send!=="function")throw Error("Full preparation requires inherited CLI IPC");
9
+ let started=false,stopping=false;
10
+ const bootDeadline=setTimeout(()=>process.exit(1),10000);
11
+ // Parent exit/disconnect must not leave an installer running on its own.
12
+ // A partially written stage is never a complete cache entry; existing loader
13
+ // recovery handles it. This child never launches another OS process.
14
+ process.once("disconnect",()=>{if(!stopping)process.exit(1);});
15
+ if(!process.connected)process.exit(1);
16
+ process.on("message",message=>{
17
+ if(started){process.exit(1);return;}
18
+ started=true;clearTimeout(bootDeadline);
19
+ void (async()=>{
20
+ let request;
21
+ try{request=validatePreparationRequest(message);}catch{process.exit(1);return;}
22
+ const {target,source}=request;
23
+ let response;
24
+ try{
25
+ if(source.kind==="url")releaseSourceUrl(source.url);
26
+ const result=await resolveFullMod({full:true,...target,trustedKeys:new Map(target.trustedKeys),
27
+ supportedCapabilities:[...REMOTE_FULL_CAPABILITIES],
28
+ ...(source.kind==="directory"?{provider:({signal})=>localRelease(source.directory,signal)}:
29
+ source.kind==="url"?{provider:({signal})=>fetchFullRelease(source.url,signal)}:
30
+ source.kind==="official"?{provider:({signal})=>fetchOfficialFullRelease(target,signal)}:{})});
31
+ response={kind:"full.prepare.result",version:1,requestId:request.requestId,ok:result.ok,
32
+ ...(result.ok?{artifact:{artifactId:result.artifact.artifactId,entrypoint:result.artifact.entrypoint,
33
+ capabilities:[...result.artifact.capabilities]}}:{error:result.reason??"full_unavailable"})};
34
+ validatePreparationResult(response,request.requestId);
35
+ }catch(error){
36
+ response={kind:"full.prepare.result",version:1,requestId:request.requestId,ok:false,
37
+ error:typeof error?.code==="string"&&/^full_[a-z0-9_]{1,80}$/.test(error.code)?error.code:"full_preparation_failed"};
38
+ }
39
+ try{
40
+ await new Promise((resolve,reject)=>process.send(response,cause=>cause?reject(cause):resolve()));
41
+ stopping=true;
42
+ process.disconnect();
43
+ // All resolver file/network operations have settled; the only payload
44
+ // is the flushed bounded IPC receipt. Exit releases all archive buffers.
45
+ process.exit(0);
46
+ }catch{process.exit(1);}
47
+ })();
48
+ });