@anusornneal/chat-relay 1.9.0 → 2.1.0

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 +8 -0
  2. package/agent/activity-capture.mjs +218 -0
  3. package/agent/auto-session-binding.mjs +46 -0
  4. package/agent/capability-scheduler.mjs +82 -5
  5. package/agent/file-manager.mjs +33 -8
  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 +318 -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 +171 -4
  20. package/agent/lifecycle.mjs +11 -0
  21. package/agent/local-agent.mjs +177 -24
  22. package/agent/local-usage.mjs +21 -0
  23. package/agent/monitor-activity.mjs +135 -0
  24. package/agent/presentation-redaction.mjs +10 -0
  25. package/agent/process-manager.mjs +32 -0
  26. package/agent/terminal-manager.mjs +189 -31
  27. package/agent/toolcall-context.mjs +27 -1
  28. package/agent/toolcall-summary.mjs +1 -1
  29. package/agent/windows-desktop-runner.mjs +65 -61
  30. package/agent/windows-desktop-worker.ps1 +33 -18
  31. package/agent/windows-powershell.mjs +51 -0
  32. package/cli/full-background.mjs +69 -0
  33. package/cli/full-launch.mjs +76 -0
  34. package/cli/full-prepare-child.mjs +48 -0
  35. package/cli/full-prepare.mjs +171 -0
  36. package/cli/full-release-default.json +4 -0
  37. package/cli/full-release-files.mjs +36 -0
  38. package/cli/full-release-official.mjs +48 -0
  39. package/cli/full-release-source.mjs +37 -0
  40. package/cli/index.mjs +9 -5
  41. package/cli/mod-cache.mjs +170 -0
  42. package/cli/mod-loader.mjs +67 -0
  43. package/cli/mod-manifest.mjs +63 -0
  44. package/cli/remote.mjs +173 -18
  45. package/cli/runner-ownership.mjs +116 -3
  46. package/cli/self-update.mjs +1 -1
  47. package/cli/tui.mjs +2 -20
  48. package/package.json +5 -3
  49. package/packages/full-contracts/auto-session.mjs +14 -0
  50. package/packages/full-contracts/index.mjs +193 -0
  51. package/packages/full-contracts/monitor-metadata.mjs +28 -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
@@ -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,76 @@
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} from "./full-release-files.mjs";
8
+ import {ModError} from "./mod-manifest.mjs";
9
+
10
+ const require=(ok,code)=>{if(!ok)throw new ModError(code);};
11
+ export function supportedFullNode(version=process.versions.node){
12
+ const match=/^(\d+)\.(\d+)\.(\d+)$/.exec(version);
13
+ if(!match)return false;
14
+ const [major,minor,patch]=match.slice(1).map(Number);
15
+ const atLeast=(m,p)=>minor>m||minor===m&&patch>=p;
16
+ return major===22&&atLeast(23,4)||major===24&&atLeast(22,1)||major===26&&atLeast(12,1)||major>26;
17
+ }
18
+ // The public launcher uses only the release-specific pin bundled with Core.
19
+ export {officialFullSettings as readFullReleaseSettings} from "./full-release-official.mjs";
20
+ export function fullStateDirectory(home,{relayUrl,agentId}){
21
+ require(typeof relayUrl==="string"&&typeof agentId==="string"&&/^[a-z0-9_-]{1,64}$/.test(agentId),"full_invalid_host_configuration");
22
+ const normalized=new URL(relayUrl);
23
+ require(["http:","https:"].includes(normalized.protocol)&&!normalized.username&&!normalized.password&&!normalized.hash&&!normalized.search,"full_invalid_host_configuration");
24
+ const key=createHash("sha256").update(JSON.stringify([normalized.href.replace(/\/+$/,""),agentId])).digest("hex");
25
+ return path.resolve(home,"full-state",key);
26
+ }
27
+ async function existingDirectory(directory){
28
+ try{
29
+ const stat=await fs.lstat(directory);require(stat.isDirectory()&&!stat.isSymbolicLink(),"full_unsafe_state_directory");return true;
30
+ }catch(error){if(error.code==="ENOENT")return false;throw error;}
31
+ }
32
+ export async function inspectFullSchema(directory){
33
+ if(!await existingDirectory(path.dirname(directory))||!await existingDirectory(directory))return 0;
34
+ const file=path.join(directory,"sessions.sqlite");
35
+ try{await regularFile(file,Number.MAX_SAFE_INTEGER);}
36
+ catch(error){if(error.code==="ENOENT")return 0;throw error;}
37
+ for(const sidecar of [file+"-wal",file+"-shm"]){
38
+ try{await regularFile(sidecar,Number.MAX_SAFE_INTEGER);}
39
+ catch(error){if(error.code!=="ENOENT")throw error;}
40
+ }
41
+ // Only explicit Full touches node:sqlite. Inspect without migration or
42
+ // acquiring ownership; the supervised host independently checks again.
43
+ const {DatabaseSync}=await import("node:sqlite");
44
+ const db=new DatabaseSync(file,{readOnly:true});
45
+ try{
46
+ const version=db.prepare("PRAGMA user_version").get().user_version;
47
+ const app=db.prepare("PRAGMA application_id").get().application_id;
48
+ require(Number.isSafeInteger(version)&&version>=1&&app===0x4352464d,"full_storage_unrecognized");
49
+ return version;
50
+ }finally{db.close();}
51
+ }
52
+ export function localFullPrincipal(config,authentication){
53
+ const accountId=authentication?.user?.id;
54
+ const grants=authentication?.agents?.find(agent=>agent.id===config?.agentId)?.scopes;
55
+ require(typeof accountId==="string"&&/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(accountId)&&Array.isArray(grants),"full_unauthorized");
56
+ const scopes=["read","write","terminal"].filter(scope=>(grants.includes("*")||grants.includes(scope))&&(scope!=="terminal"||config.terminalEnabled!==false));
57
+ require(scopes.includes("read"),"full_unauthorized");
58
+ return {accountId,agentId:config.agentId,scopes};
59
+ }
60
+ // Official keys are release-specific; an unrelated development or previous
61
+ // release cache must never block a verified upgrade or weaken signature checks.
62
+ export function fullCacheRoot(home,settings,coreVersion){
63
+ if(!settings.official)return path.resolve(home,"full-cache");
64
+ require(typeof coreVersion==="string"&&/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(coreVersion),"full_invalid_release_configuration");
65
+ return path.resolve(home,"full-cache-official",coreVersion);
66
+ }
67
+ export async function prepareFullLaunch({settings,config,principal,home=configDir(),nodeVersion=process.versions.node,coreVersion=getAgentVersion(),signal}){
68
+ require(supportedFullNode(nodeVersion),"full_node_unsupported");
69
+ const headless=settings.headless!==false;
70
+ if(!headless)require(principal?.agentId===config.agentId&&principal.scopes?.includes("read"),"full_unauthorized");
71
+ const sessionDirectory=fullStateDirectory(home,config);
72
+ const schemaVersion=await inspectFullSchema(sessionDirectory);
73
+ const artifact=await prepareFullArtifact({settings,cacheRoot:fullCacheRoot(home,settings,coreVersion),schemaVersion,coreVersion,signal});
74
+ require(artifact.capabilities.includes("full.sessions"),"full_capability_unavailable");
75
+ return {headless,coreRunnerId:randomUUID(),sessionDirectory,...(!headless?{localPrincipal:principal}:{}),artifact:{artifactId:artifact.artifactId,executablePath:artifact.executablePath,capabilities:[...artifact.capabilities]}};
76
+ }
@@ -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
+ });
@@ -0,0 +1,171 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import {fork} from "node:child_process";
4
+ import {randomUUID} from "node:crypto";
5
+ import {fileURLToPath} from "node:url";
6
+ import {ModError,portablePath} from "./mod-manifest.mjs";
7
+ import {REMOTE_FULL_CAPABILITIES} from "../packages/full-contracts/remote-session.mjs";
8
+
9
+ export const FULL_PREPARATION_FRAME_BYTES=64*1024;
10
+ export const FULL_PREPARATION_TIMEOUT_MS=120000;
11
+ const EXIT_TIMEOUT_MS=5000;
12
+ const error=code=>new ModError(code);
13
+ const check=(value,code="full_invalid_preparation")=>{if(!value)throw error(code);};
14
+ const record=value=>value!==null&&typeof value==="object"&&!Array.isArray(value)&&
15
+ [Object.prototype,null].includes(Object.getPrototypeOf(value));
16
+ const exact=(value,keys)=>record(value)&&Object.keys(value).length===keys.length&&keys.every(key=>Object.hasOwn(value,key));
17
+ const requestId=value=>typeof value==="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value);
18
+ const absolute=value=>typeof value==="string"&&value.length<=32767&&!value.includes("\0")&&path.isAbsolute(value);
19
+ const version=value=>typeof value==="string"&&value.length<=64&&/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[A-Za-z0-9.-]+)?$/.test(value);
20
+ const code=value=>typeof value==="string"&&/^full_[a-z0-9_]{1,80}$/.test(value);
21
+ export function preparationFrameBounded(value){
22
+ try{return Buffer.byteLength(JSON.stringify(value),"utf8")<=FULL_PREPARATION_FRAME_BYTES;}catch{return false;}
23
+ }
24
+
25
+ // Private inherited IPC between two fixed first-party CLI modules. These are
26
+ // post-deserialization bounds; no remote caller can select a program or source.
27
+ export function validatePreparationRequest(value){
28
+ check(preparationFrameBounded(value)&&exact(value,["kind","version","requestId","target","source"])&&
29
+ value.kind==="full.prepare"&&value.version===1&&requestId(value.requestId));
30
+ const target=value.target;
31
+ check(exact(target,["cacheRoot","requestedVersion","coreVersion","platform","arch","schemaVersion","trustedKeys"])&&
32
+ absolute(target.cacheRoot)&&version(target.requestedVersion)&&typeof target.coreVersion==="string"&&
33
+ target.coreVersion.length>0&&target.coreVersion.length<=64&&
34
+ target.platform===process.platform&&target.arch===process.arch&&
35
+ Number.isSafeInteger(target.schemaVersion)&&target.schemaVersion>=0);
36
+ check(Array.isArray(target.trustedKeys)&&target.trustedKeys.length>=1&&target.trustedKeys.length<=8);
37
+ const names=new Set();
38
+ for(const entry of target.trustedKeys){
39
+ check(Array.isArray(entry)&&entry.length===2&&typeof entry[0]==="string"&&
40
+ /^[A-Za-z0-9_-]{1,64}$/.test(entry[0])&&!names.has(entry[0])&&
41
+ typeof entry[1]==="string"&&entry[1].length<=1024&&entry[1].includes("BEGIN PUBLIC KEY"));
42
+ names.add(entry[0]);
43
+ }
44
+ const source=value.source;
45
+ check(exact(source,["kind"])&&["cache-only","official"].includes(source.kind)||
46
+ exact(source,["kind","directory"])&&source.kind==="directory"&&absolute(source.directory)||
47
+ exact(source,["kind","url"])&&source.kind==="url"&&typeof source.url==="string"&&source.url.length<=8192);
48
+ return value;
49
+ }
50
+ export function validatePreparationResult(value,expectedRequestId){
51
+ check(preparationFrameBounded(value)&&record(value)&&value.kind==="full.prepare.result"&&
52
+ value.version===1&&value.requestId===expectedRequestId&&typeof value.ok==="boolean","full_preparation_protocol_error");
53
+ if(!value.ok){
54
+ check(exact(value,["kind","version","requestId","ok","error"])&&code(value.error),"full_preparation_protocol_error");
55
+ return value;
56
+ }
57
+ check(exact(value,["kind","version","requestId","ok","artifact"]),"full_preparation_protocol_error");
58
+ const artifact=value.artifact;
59
+ check(exact(artifact,["artifactId","entrypoint","capabilities"])&&
60
+ typeof artifact.artifactId==="string"&&/^[a-f0-9]{64}$/.test(artifact.artifactId)&&
61
+ Array.isArray(artifact.capabilities)&&artifact.capabilities.length<=REMOTE_FULL_CAPABILITIES.length&&
62
+ artifact.capabilities.every(capability=>REMOTE_FULL_CAPABILITIES.includes(capability))&&
63
+ new Set(artifact.capabilities).size===artifact.capabilities.length,"full_preparation_protocol_error");
64
+ try{check(portablePath(artifact.entrypoint).endsWith(".mjs"),"full_preparation_protocol_error");}
65
+ catch{throw error("full_preparation_protocol_error");}
66
+ return value;
67
+ }
68
+ function childEnvironment(){
69
+ const allowed=new Set(["path","systemroot","windir","home","userprofile","temp","tmp","tmpdir",
70
+ "appdata","localappdata","lang","lc_all","lc_ctype","node_extra_ca_certs","ssl_cert_file","ssl_cert_dir",
71
+ "http_proxy","https_proxy","no_proxy","node_use_env_proxy","node_use_system_ca"]);
72
+ // Forward only explicitly configured OS and transport settings, preserving
73
+ // spelling/case and values. Never add a proxy or disable TLS verification.
74
+ // Relay credentials, NODE_OPTIONS/preloads and parent IPC configuration are absent.
75
+ return Object.fromEntries(Object.entries(process.env).filter(([name])=>allowed.has(name.toLowerCase())));
76
+ }
77
+ function childExecArgv(){
78
+ // Keep explicit transport/trust flags already accepted by this same Node
79
+ // executable. NODE_OPTIONS is deliberately not parsed or inherited: use the
80
+ // dedicated proxy/CA environment variables or direct flags for this child.
81
+ const flags=new Set(["--use-env-proxy","--use-system-ca","--use-openssl-ca","--use-bundled-ca",
82
+ "--no-use-env-proxy","--no-use-system-ca","--no-use-openssl-ca","--no-use-bundled-ca"]);
83
+ return process.execArgv.filter(value=>flags.has(value.replaceAll("_","-")));
84
+ }
85
+ function requestFor({settings,cacheRoot,coreVersion,schemaVersion}){
86
+ check(settings&&settings.trustedKeys instanceof Map);
87
+ check(!(settings.sourceDirectory&&settings.sourceUrl)&&!(settings.official&&(settings.sourceDirectory||settings.sourceUrl)));
88
+ const source=settings.official?{kind:"official"}:settings.sourceDirectory?{kind:"directory",directory:settings.sourceDirectory}:
89
+ settings.sourceUrl?{kind:"url",url:settings.sourceUrl}:{kind:"cache-only"};
90
+ return validatePreparationRequest({kind:"full.prepare",version:1,requestId:randomUUID(),
91
+ target:{cacheRoot,requestedVersion:settings.requestedVersion,coreVersion,
92
+ platform:process.platform,arch:process.arch,schemaVersion,trustedKeys:[...settings.trustedKeys]},source});
93
+ }
94
+
95
+ export async function prepareFullArtifact({settings,cacheRoot,coreVersion,schemaVersion,signal}){
96
+ const request=requestFor({settings,cacheRoot,coreVersion,schemaVersion});
97
+ if(signal?.aborted)throw error("full_preparation_cancelled");
98
+ const reply=await new Promise((resolve,reject)=>{
99
+ let child,reply=null,failure=null,settled=false,exitSeen=false,exitTimer=null,stopTimer=null,stopRequested=false;
100
+ let deadline;
101
+ const alive=()=>child&&child.exitCode===null&&child.signalCode===null;
102
+ function finish(cause,result){
103
+ if(settled)return;settled=true;
104
+ clearTimeout(deadline);clearTimeout(exitTimer);clearTimeout(stopTimer);
105
+ signal?.removeEventListener("abort",abort);
106
+ if(cause)reject(cause);else resolve(result);
107
+ }
108
+ function fail(reason){
109
+ if(settled)return;
110
+ failure??=error(reason);
111
+ clearTimeout(deadline);clearTimeout(exitTimer);
112
+ if(!child||exitSeen){finish(failure);return;}
113
+ // Arm before kill: a synchronous kill error may re-enter fail(). A child
114
+ // whose OS exit preceded this failure still needs its aggregate close.
115
+ if(!stopTimer)stopTimer=setTimeout(()=>{
116
+ // Only now abandon the pending channel and ask the trusted helper to
117
+ // exit on disconnect. This is not stop proof and cannot activate Full.
118
+ try{if(child.connected)child.disconnect();}catch{}
119
+ child.unref();
120
+ finish(error("full_preparation_exit_unconfirmed"));
121
+ },EXIT_TIMEOUT_MS);
122
+ if(stopRequested)return;
123
+ stopRequested=true;
124
+ // Keep IPC open after the owned-process kill so its EOF contributes to
125
+ // Node's aggregate close event. Explicit parent disconnect before EOF
126
+ // can suppress that close accounting. Never reopen a numeric PID.
127
+ if(alive())try{child.kill("SIGKILL");}catch{}
128
+ }
129
+ const abort=()=>fail("full_preparation_cancelled");
130
+ try{
131
+ child=fork(new URL("./full-prepare-child.mjs",import.meta.url),[],{
132
+ execArgv:childExecArgv(),env:childEnvironment(),cwd:path.dirname(fileURLToPath(import.meta.url)),
133
+ stdio:["ignore","ignore","ignore","ipc"],serialization:"json",windowsHide:true});
134
+ child.on("message",message=>{
135
+ if(settled||failure)return;
136
+ try{
137
+ if(reply)throw error("full_preparation_protocol_error");
138
+ reply=validatePreparationResult(message,request.requestId);
139
+ // A success frame is not success until the actual child exits zero.
140
+ exitTimer=setTimeout(()=>fail("full_preparation_exit_timeout"),EXIT_TIMEOUT_MS);
141
+ }catch{fail("full_preparation_protocol_error");}
142
+ });
143
+ child.once("error",()=>fail("full_preparation_spawn_failed"));
144
+ child.once("disconnect",()=>{
145
+ if(!reply&&!exitSeen&&!failure)fail("full_preparation_disconnected");
146
+ });
147
+ child.once("close",(status,signalName)=>{
148
+ exitSeen=true;
149
+ if(failure){finish(failure);return;}
150
+ if(status!==0||signalName||!reply){finish(error("full_preparation_failed"));return;}
151
+ finish(null,reply);
152
+ });
153
+ signal?.addEventListener("abort",abort,{once:true});
154
+ deadline=setTimeout(()=>fail("full_preparation_timeout"),FULL_PREPARATION_TIMEOUT_MS);
155
+ if(signal?.aborted){abort();return;}
156
+ child.send(request,cause=>{if(cause)fail("full_preparation_disconnected");});
157
+ }catch{
158
+ if(child)fail("full_preparation_spawn_failed");
159
+ else finish(error("full_preparation_spawn_failed"));
160
+ }
161
+ });
162
+ if(!reply.ok)throw error(reply.error);
163
+ // The child already reverified the complete cache tree. Construct the
164
+ // executable under that canonical cache rather than accept a free-form path.
165
+ let canonical;
166
+ try{canonical=await fs.realpath(cacheRoot);}catch{throw error("full_unsafe_cache");}
167
+ if(signal?.aborted)throw error("full_preparation_cancelled");
168
+ return {artifactId:reply.artifact.artifactId,
169
+ executablePath:path.join(canonical,reply.artifact.artifactId,...reply.artifact.entrypoint.split("/")),
170
+ capabilities:[...reply.artifact.capabilities]};
171
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "version": "2.1.0",
3
+ "publicKey": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAere5wAOYD039oGrPlLZL6nurG+upNkR99Kr2o+2AUfU=\n-----END PUBLIC KEY-----\n"
4
+ }
@@ -0,0 +1,36 @@
1
+ import fs from "node:fs/promises";
2
+ import {constants} from "node:fs";
3
+ import path from "node:path";
4
+ import {requireMod,MAX_ARTIFACT_BYTES,MAX_MANIFEST_BYTES} from "./mod-manifest.mjs";
5
+
6
+ const require=requireMod;
7
+ export async function regularFile(file,max){
8
+ const stat=await fs.lstat(file);
9
+ require(stat.isFile()&&!stat.isSymbolicLink()&&stat.size<=max,"full_unsafe_release_file");
10
+ return stat;
11
+ }
12
+ export async function readBounded(file,max){
13
+ await regularFile(file,max);
14
+ const handle=await fs.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW??0));
15
+ try{
16
+ const stat=await handle.stat();require(stat.isFile()&&stat.size<=max,"full_unsafe_release_file");
17
+ const bytes=Buffer.alloc(stat.size+1);let used=0;
18
+ while(used<bytes.length){const {bytesRead}=await handle.read(bytes,used,bytes.length-used,null);if(!bytesRead)break;used+=bytesRead;}
19
+ require(used===stat.size,"full_unsafe_release_file");
20
+ return bytes.subarray(0,used);
21
+ }finally{await handle.close();}
22
+ }
23
+ async function* artifactBytes(file,signal){
24
+ await regularFile(file,MAX_ARTIFACT_BYTES);
25
+ const handle=await fs.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW??0));
26
+ try{
27
+ const stat=await handle.stat();require(stat.isFile()&&stat.size<=MAX_ARTIFACT_BYTES,"full_unsafe_release_file");
28
+ for await(const chunk of handle.createReadStream({autoClose:false,signal}))yield chunk;
29
+ }finally{await handle.close();}
30
+ }
31
+ export async function localRelease(directory,signal){
32
+ const stat=await fs.lstat(directory);require(stat.isDirectory()&&!stat.isSymbolicLink(),"full_unsafe_release_file");
33
+ const root=await fs.realpath(directory);
34
+ const envelope=JSON.parse((await readBounded(path.join(root,"manifest.json"),MAX_MANIFEST_BYTES*2)).toString("utf8"));
35
+ return {envelope,artifact:artifactBytes(path.join(root,"artifact.tar"),signal)};
36
+ }
@@ -0,0 +1,48 @@
1
+ import {createPublicKey} from "node:crypto";
2
+ import {readBounded} from "./full-release-files.mjs";
3
+ import {fetchReleasePair} from "./full-release-source.mjs";
4
+ import {getAgentVersion} from "../agent/protocol.mjs";
5
+ import {ModError} from "./mod-manifest.mjs";
6
+ import {fileURLToPath} from "node:url";
7
+
8
+ const keyId="official-release";
9
+ const pinFile=fileURLToPath(new URL("./full-release-default.json",import.meta.url));
10
+ const fail=code=>{throw new ModError(code);};
11
+ const stableVersion=v=>typeof v==="string"&&/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(v);
12
+ export function officialTarget({coreVersion,requestedVersion,platform,arch}){
13
+ // Only Windows x64 has native release qualification for this launch.
14
+ if(platform!=="win32"||arch!=="x64")fail("full_official_target_unsupported");
15
+ if(!stableVersion(coreVersion)||![coreVersion+"-gui",coreVersion+"-headless"].includes(requestedVersion))
16
+ fail("full_invalid_release_configuration");
17
+ const mode=requestedVersion.endsWith("-gui")?"gui":"headless";
18
+ return {base:new URL("https://github.com/anusornNeal/chat-relay/releases/download/v"+coreVersion+"/"),prefix:"full-"+platform+"-"+arch+"-"+mode+"-"};
19
+ }
20
+ // The release CI embeds this public-only pin in the published Core package.
21
+ // No TOFU, server-provided key or runtime signing-key access.
22
+ export async function officialFullSettings({headless=true,coreVersion=getAgentVersion(),platform=process.platform,arch=process.arch,pinPath=pinFile}={}){
23
+ const requestedVersion=coreVersion+(headless?"-headless":"-gui");
24
+ officialTarget({coreVersion,requestedVersion,platform,arch});
25
+ let pin;try{pin=JSON.parse((await readBounded(pinPath,4096)).toString("utf8"));}
26
+ catch(e){fail(e.code==="ENOENT"?"full_release_unconfigured":"full_invalid_release_configuration");}
27
+ if(pin?.version!==coreVersion||typeof pin.publicKey!=="string"||pin.publicKey.length>1024)fail("full_invalid_release_configuration");
28
+ try{if(createPublicKey(pin.publicKey).asymmetricKeyType!=="ed25519")fail("full_invalid_release_configuration");}
29
+ catch{fail("full_invalid_release_configuration");}
30
+ return {headless,requestedVersion,trustedKeys:new Map([[keyId,pin.publicKey]]),official:true};
31
+ }
32
+ export function fetchOfficialFullRelease(target,signal,fetcher=fetch){
33
+ const {base,prefix}=officialTarget(target);
34
+ // Github release assets redirect once to a signed CDN URL. Never follow
35
+ // arbitrary hosts, credentials, ports, non-HTTPS or further redirects.
36
+ const download=async(url,options)=>{
37
+ let response=await fetcher(url,{...options,redirect:"manual"});
38
+ if([301,302,303,307,308].includes(response.status)){
39
+ let next;try{next=new URL(response.headers.get("location"));}catch{fail("full_download_failed");}
40
+ if(next.protocol!=="https:"||next.username||next.password||next.port||next.hash||
41
+ !["release-assets.githubusercontent.com","objects.githubusercontent.com"].includes(next.hostname))fail("full_download_failed");
42
+ await response.body?.cancel();
43
+ response=await fetcher(next,options);
44
+ }
45
+ return response;
46
+ };
47
+ return fetchReleasePair(name=>new URL(prefix+name,base),signal,download);
48
+ }
@@ -0,0 +1,37 @@
1
+ import {ModError,MAX_ARTIFACT_BYTES,MAX_MANIFEST_BYTES} from "./mod-manifest.mjs";
2
+
3
+ const require=(ok,code)=>{if(!ok)throw new ModError(code);};
4
+ export function releaseSourceUrl(value){
5
+ let url;try{url=new URL(value);}catch{throw new ModError("full_invalid_release_configuration");}
6
+ require(url.protocol==="https:"&&!url.username&&!url.password&&!url.search&&!url.hash,"full_invalid_release_configuration");
7
+ if(!url.pathname.endsWith("/"))url.pathname+="/";
8
+ return url.href;
9
+ }
10
+ async function boundedBytes(response,maximum){
11
+ require(response.ok&&response.body,"full_download_failed");
12
+ const advertised=response.headers.get("content-length");
13
+ require(advertised===null||/^\d+$/.test(advertised)&&Number(advertised)<=maximum,"full_artifact_too_large");
14
+ const chunks=[];let size=0;
15
+ for await(const chunk of response.body){size+=chunk.byteLength;require(size<=maximum,"full_artifact_too_large");chunks.push(Buffer.from(chunk));}
16
+ return Buffer.concat(chunks,size);
17
+ }
18
+ // Explicit configured sources never follow redirects. Archive retrieval remains lazy.
19
+ export async function fetchFullRelease(source,signal,fetcher=fetch){
20
+ const base=releaseSourceUrl(source);
21
+ return fetchReleasePair(name=>new URL(name,base),signal,fetcher);
22
+ }
23
+ export async function fetchReleasePair(assetUrl,signal,fetcher=fetch){
24
+ const options={signal,redirect:"error",credentials:"omit"};
25
+ const response=await fetcher(assetUrl("manifest.json"),options);
26
+ const bytes=await boundedBytes(response,MAX_MANIFEST_BYTES*2);
27
+ let envelope;try{envelope=JSON.parse(bytes.toString("utf8"));}catch{throw new ModError("full_invalid_signed_manifest");}
28
+ async function* artifact(){
29
+ const response=await fetcher(assetUrl("artifact.tar"),options);
30
+ require(response.ok&&response.body,"full_download_failed");
31
+ const advertised=response.headers.get("content-length");
32
+ require(advertised===null||/^\d+$/.test(advertised)&&Number(advertised)<=MAX_ARTIFACT_BYTES,"full_artifact_too_large");
33
+ let size=0;
34
+ for await(const chunk of response.body){size+=chunk.byteLength;require(size<=MAX_ARTIFACT_BYTES,"full_artifact_too_large");yield chunk;}
35
+ }
36
+ return {envelope,artifact:artifact()};
37
+ }