@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
@@ -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.0.1",
3
+ "publicKey": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA5zA188hZk+nkLd8sLGsFHa1erfPut8tZRz33AlC9wcA=\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
+ }
package/cli/index.mjs CHANGED
@@ -14,6 +14,8 @@ function parseOptions(args) {
14
14
  else if (arg === "--force") options.force = true;
15
15
  else if (arg === "--desktop") options.desktopEnabled = true;
16
16
  else if (arg === "--no-desktop") options.desktopEnabled = false;
17
+ else if (arg === "--full") options.full = true;
18
+ else if (arg === "--headless") options.headless = true;
17
19
  else if (arg === "--plain") options.tuiEnabled = false;
18
20
  else if (arg === "--tui") options.tuiEnabled = true;
19
21
  else if (arg === "--snapshot") options.snapshot = true;
@@ -38,7 +40,7 @@ function help() {
38
40
  console.log(`Chat Relay
39
41
 
40
42
  Usage:
41
- chat-relay remote [options] Connect this computer to ChatGPT
43
+ chat-relay remote [options] Connect in Lite mode (interactive TUI by default)
42
44
  chat-relay demo [options] Preview the real TUI offline with sample activity
43
45
  chat-relay login [options] Sign in and register this computer
44
46
  chat-relay status Show account and connection status
@@ -56,8 +58,10 @@ Options:
56
58
  --agent-id <id> Stable agent identifier
57
59
  --desktop Enable Windows desktop screenshot/input access
58
60
  --no-desktop Disable desktop access (default)
59
- --plain Use legacy line-by-line logs
60
- --tui Force interactive terminal UI
61
+ --full Start Full with its desktop GUI (requires a supported Mod)
62
+ --headless Use Full without its desktop companion
63
+ --plain Foreground logs (also for Full diagnostics)
64
+ --tui Force interactive terminal UI in Lite
61
65
  --snapshot Print demo as plain text and exit
62
66
  --width <columns> Demo snapshot width
63
67
  --height <rows> Demo snapshot height
@@ -269,7 +273,7 @@ export async function runCli(argv = process.argv.slice(2)) {
269
273
  if (command === "restart") return lifecycleAction("restart");
270
274
  if (command === "upgrade") return lifecycleAction("upgrade");
271
275
  if (command === "remote") {
272
- const remoteCode = (await remote(options)) || 0;
276
+ const remoteCode = (await remote({...options,launchArgs:argv})) || 0;
273
277
  if (remoteCode === AGENT_UPGRADE_EXIT_CODE) {
274
278
  const relaunched = launchLatestRemote(options);
275
279
  if (!relaunched.ok) {
@@ -0,0 +1,170 @@
1
+ import * as fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { digest, ModError, requireMod, portablePath, MAX_FILES, MAX_ARTIFACT_BYTES, MAX_MANIFEST_BYTES, verifySignedManifest } from "./mod-manifest.mjs";
4
+ const BLOCK = 512;
5
+ const text = bytes => bytes.subarray(0, bytes.indexOf(0) === -1 ? bytes.length : bytes.indexOf(0)).toString("utf8");
6
+ function octal(bytes) {
7
+ const value = text(bytes).trim();
8
+ requireMod(/^[0-7]+$/.test(value), "full_invalid_archive");
9
+ const number = Number.parseInt(value, 8);
10
+ requireMod(Number.isSafeInteger(number), "full_invalid_archive");
11
+ return number;
12
+ }
13
+
14
+ // Strict uncompressed POSIX ustar subset, no PAX/GNU extensions, links or devices.
15
+ // The release packager must emit portable names and regular files only (directories optional).
16
+ export function readArchive(bytes) {
17
+ requireMod(Buffer.isBuffer(bytes) && bytes.length <= MAX_ARTIFACT_BYTES && bytes.length % BLOCK === 0, "full_invalid_archive");
18
+ const records = new Map();
19
+ const folded = new Map();
20
+ function register(name, directory, record) {
21
+ const parts = name.split("/");
22
+ for (let i = 1; i <= parts.length; i++) {
23
+ const partial = parts.slice(0,i).join("/");
24
+ const key = partial.toLowerCase();
25
+ const isDir = i < parts.length || directory;
26
+ const prev = folded.get(key);
27
+ requireMod(!prev || (prev.name === partial && prev.directory && isDir), "full_archive_collision");
28
+ if (!prev) folded.set(key, {name: partial,directory:isDir});
29
+ requireMod(folded.size <= MAX_FILES, "full_archive_file_limit");
30
+ }
31
+ requireMod(!records.has(name), "full_archive_collision");
32
+ records.set(name, record);
33
+ }
34
+ let offset = 0, ended = false;
35
+ while (offset + BLOCK <= bytes.length) {
36
+ const header = bytes.subarray(offset, offset + BLOCK);
37
+ if (header.every(x => x === 0)) {
38
+ requireMod(bytes.length - offset >= BLOCK*2 && bytes.subarray(offset).every(x=>x===0), "full_invalid_archive_end");
39
+ ended = true; break;
40
+ }
41
+ const expected = octal(header.subarray(148,156));
42
+ let sum = 0;
43
+ for (let i=0;i<BLOCK;i++) sum += i>=148 && i<156 ? 32 : header[i];
44
+ requireMod(sum===expected && text(header.subarray(257,263))==="ustar" &&
45
+ text(header.subarray(263,265))==="00", "full_invalid_archive_header");
46
+ const type=header[156];
47
+ requireMod(type===0 || type===48 || type===53, "full_archive_entry_type");
48
+ const directory=type===53;
49
+ const prefix=text(header.subarray(345,500));
50
+ const file=text(header.subarray(0,100));
51
+ const name=portablePath((prefix ? prefix+"/"+file : file).replace(directory ? /\/$/ : /$^/,""));
52
+ const size=octal(header.subarray(124,136));
53
+ const mode=octal(header.subarray(100,108));
54
+ const start=offset+BLOCK, end=start+size, next=start+Math.ceil(size/BLOCK)*BLOCK;
55
+ requireMod(end<=bytes.length && next<=bytes.length && (!directory || size===0), "full_truncated_archive");
56
+ requireMod((mode&0o7000)===0, "full_archive_entry_mode");
57
+ register(name,directory,{directory, data:bytes.subarray(start,end), executable:!directory && !!(mode&0o111)});
58
+ offset=next;
59
+ }
60
+ requireMod(ended && records.size>0, "full_invalid_archive_end");
61
+ return {records, tree:folded};
62
+ }
63
+ async function ensureRoot(root) {
64
+ await fs.mkdir(root,{recursive:true,mode:0o700});
65
+ const stat=await fs.lstat(root);
66
+ requireMod(stat.isDirectory()&&!stat.isSymbolicLink(), "full_unsafe_cache");
67
+ return fs.realpath(root);
68
+ }
69
+ async function fileBytes(file, limit) {
70
+ const stat=await fs.lstat(file);
71
+ requireMod(stat.isFile()&&!stat.isSymbolicLink()&&stat.size<=limit, "full_unsafe_cache");
72
+ return fs.readFile(file);
73
+ }
74
+ function verifyBytes(bytes, verified) {
75
+ requireMod(bytes.length===verified.manifest.sizeBytes && digest(bytes)===verified.manifest.sha256, "full_integrity_mismatch");
76
+ const archive=readArchive(bytes);
77
+ requireMod(archive.records.has(verified.entrypoint) && !archive.records.get(verified.entrypoint).directory, "full_missing_entrypoint");
78
+ return archive;
79
+ }
80
+ async function verifyTree(root, archive) {
81
+ const pending=[""];
82
+ const seen=new Set();
83
+ while(pending.length) {
84
+ const prefix=pending.pop();
85
+ for(const name of await fs.readdir(path.join(root,prefix))) {
86
+ const relative=prefix?prefix+"/"+name:name;
87
+ if (!prefix && ["manifest.json","artifact.tar","complete.json"].includes(name)) continue;
88
+ const expected=archive.tree.get(relative.toLowerCase());
89
+ requireMod(expected && expected.name===relative && !seen.has(relative), "full_cache_extra_file");
90
+ seen.add(relative);
91
+ const full=path.join(root,relative);
92
+ const stat=await fs.lstat(full);
93
+ requireMod(!stat.isSymbolicLink(), "full_unsafe_cache");
94
+ if(expected.directory) {
95
+ requireMod(stat.isDirectory(),"full_cache_tree_mismatch"); pending.push(relative);
96
+ } else {
97
+ const original=archive.records.get(relative);
98
+ requireMod(stat.isFile()&&stat.size===original.data.length &&
99
+ digest(await fileBytes(full,MAX_ARTIFACT_BYTES))===digest(original.data),"full_cache_tree_mismatch");
100
+ if(process.platform!=="win32") requireMod(Boolean(stat.mode&0o111)===original.executable,"full_cache_tree_mismatch");
101
+ }
102
+ }
103
+ }
104
+ requireMod(seen.size===archive.tree.size,"full_cache_tree_mismatch");
105
+ }
106
+ export async function verifyCacheEntry(directory, options) {
107
+ const stat=await fs.lstat(directory);
108
+ requireMod(stat.isDirectory()&&!stat.isSymbolicLink(),"full_unsafe_cache");
109
+ let envelope, marker;
110
+ try {
111
+ envelope=JSON.parse((await fileBytes(path.join(directory,"manifest.json"),MAX_MANIFEST_BYTES*2)).toString("utf8"));
112
+ marker=JSON.parse((await fileBytes(path.join(directory,"complete.json"),1024)).toString("utf8"));
113
+ } catch(error) { throw new ModError(error.code==="ENOENT"?"full_cache_missing":error.code||"full_cache_invalid"); }
114
+ const verified=verifySignedManifest(envelope,options);
115
+ requireMod(path.basename(directory)===verified.artifactId && marker.artifactId===verified.artifactId &&
116
+ marker.complete===true,"full_cache_invalid");
117
+ const archive=verifyBytes(await fileBytes(path.join(directory,"artifact.tar"),MAX_ARTIFACT_BYTES),verified);
118
+ await verifyTree(directory,archive);
119
+ return {...verified, directory, executablePath:path.join(directory,verified.entrypoint)};
120
+ }
121
+ export async function findCached(root, options) {
122
+ let names,canonical;
123
+ try {
124
+ const stat=await fs.lstat(root);
125
+ requireMod(stat.isDirectory()&&!stat.isSymbolicLink(),"full_unsafe_cache");
126
+ canonical=await fs.realpath(root);
127
+ names=await fs.readdir(canonical);
128
+ } catch(error) { if(error.code==="ENOENT") return null; throw error; }
129
+ const entries=names.filter(name=>/^[a-f0-9]{64}$/.test(name));
130
+ requireMod(entries.length<=512,"full_cache_entry_limit");
131
+ const compatible=[];
132
+ let failure=null;
133
+ for(const name of entries) {
134
+ try { compatible.push(await verifyCacheEntry(path.join(canonical,name),options)); }
135
+ catch(error) {
136
+ if(!["full_version_mismatch","full_core_incompatible","full_target_incompatible"].includes(error.code)) failure=error;
137
+ }
138
+ }
139
+ requireMod(compatible.length<=1,"full_cache_ambiguous","Multiple signed artifacts match the requested version; select an explicit release identity.");
140
+ if(!compatible.length && failure) throw failure;
141
+ return compatible[0]||null;
142
+ }
143
+ export async function installArtifact(root, envelope, bytes, options) {
144
+ const verified=verifySignedManifest(envelope,options);
145
+ const archive=verifyBytes(bytes,verified);
146
+ const canonical=await ensureRoot(root);
147
+ const destination=path.join(canonical,verified.artifactId);
148
+ try { return await verifyCacheEntry(destination,options); }
149
+ catch(error) { if(!["ENOENT","full_cache_missing"].includes(error.code)) throw error; }
150
+ const stage=await fs.mkdtemp(path.join(canonical,".stage-"));
151
+ try {
152
+ const directories=[...archive.tree.values()].filter(x=>x.directory).sort((a,b)=>a.name.split("/").length-b.name.split("/").length);
153
+ for(const entry of directories) await fs.mkdir(path.join(stage,entry.name),{mode:0o700});
154
+ for(const [name,record] of archive.records) {
155
+ if(!record.directory) await fs.writeFile(path.join(stage,name),record.data,{flag:"wx",mode:record.executable?0o700:0o600});
156
+ }
157
+ await fs.writeFile(path.join(stage,"manifest.json"),JSON.stringify({keyId:envelope.keyId,payload:envelope.payload,signature:envelope.signature}),{flag:"wx",mode:0o600});
158
+ await fs.writeFile(path.join(stage,"artifact.tar"),bytes,{flag:"wx",mode:0o600});
159
+ await verifyTree(stage,archive);
160
+ await fs.writeFile(path.join(stage,"complete.json"),JSON.stringify({artifactId:verified.artifactId,complete:true}),{flag:"wx",mode:0o600});
161
+ // Immutable, nonempty destination; concurrent winners are reverified, never replaced.
162
+ // Unique staging dirs mean no installer lock can be held over a job or orphaned by a crash.
163
+ try { await fs.rename(stage,destination); }
164
+ catch(error) {
165
+ if(!["EEXIST","ENOTEMPTY","EPERM","EACCES"].includes(error.code)) throw error;
166
+ return await verifyCacheEntry(destination,options);
167
+ }
168
+ return await verifyCacheEntry(destination,options);
169
+ } finally { await fs.rm(stage,{recursive:true,force:true}); }
170
+ }
@@ -0,0 +1,67 @@
1
+ import * as fs from "node:fs/promises";
2
+ import { ModError, requireMod, verifySignedManifest, MAX_ARTIFACT_BYTES } from "./mod-manifest.mjs";
3
+ import { findCached, installArtifact } from "./mod-cache.mjs";
4
+
5
+ const errors = Object.freeze({
6
+ full_cache_missing:"No verified cached Full artifact. Connect to the configured first-party release source or explicitly use Lite.",
7
+ full_release_unconfigured:"A pinned compatible Full version and trusted release configuration are required.",
8
+ full_download_failed:"Download failed; the existing cache was not replaced.",
9
+ full_unsafe_cache:"The configured cache is not a safe local directory."
10
+ });
11
+ async function collectArtifact(body, expected) {
12
+ if(Buffer.isBuffer(body)) {
13
+ requireMod(body.length===expected,"full_integrity_mismatch"); return body;
14
+ }
15
+ requireMod(body && typeof body[Symbol.asyncIterator]==="function","full_download_failed");
16
+ const chunks=[]; let size=0;
17
+ for await(const chunk of body) {
18
+ requireMod(Buffer.isBuffer(chunk)||chunk instanceof Uint8Array,"full_download_failed");
19
+ size+=chunk.byteLength;
20
+ requireMod(size<=expected && size<=MAX_ARTIFACT_BYTES,"full_artifact_too_large");
21
+ chunks.push(Buffer.from(chunk));
22
+ }
23
+ requireMod(size===expected,"full_truncated_archive");
24
+ return Buffer.concat(chunks,size);
25
+ }
26
+ // Release transport and key provisioning are injected by the first-party integration.
27
+ // A provider must obey the AbortSignal and return bounded signed metadata + streamed bytes.
28
+ // Never invoke a package installer or run package lifecycle scripts.
29
+ export async function resolveFullMod({ full=false, cacheRoot, requestedVersion, provider,
30
+ runningArtifactId, timeoutMs=60000, ...options }={}) {
31
+ if(!full) return {ok:true,mode:"lite"};
32
+ try {
33
+ requireMod(typeof cacheRoot==="string"&&cacheRoot.length>0 &&
34
+ typeof requestedVersion==="string"&&requestedVersion.length>0,"full_release_unconfigured");
35
+ const target={...options,requestedVersion};
36
+ try {
37
+ const stat=await fs.lstat(cacheRoot);
38
+ requireMod(stat.isDirectory()&&!stat.isSymbolicLink(),"full_unsafe_cache");
39
+ } catch(error) { if(error.code!=="ENOENT") throw error; }
40
+ let artifact=await findCached(cacheRoot,target);
41
+ if(!artifact) {
42
+ requireMod(typeof provider==="function","full_cache_missing");
43
+ requireMod(Number.isSafeInteger(timeoutMs)&&timeoutMs>0&&timeoutMs<=120000,"full_invalid_timeout");
44
+ const controller=new AbortController();
45
+ let timer;
46
+ let download;
47
+ try {
48
+ download=await Promise.race([
49
+ (async()=>{
50
+ const release=await provider({requestedVersion,coreVersion:target.coreVersion,platform:target.platform,arch:target.arch,signal:controller.signal});
51
+ requireMod(!controller.signal.aborted,"full_download_timeout");
52
+ const verified=verifySignedManifest(release?.envelope,target);
53
+ const bytes=await collectArtifact(release?.artifact,verified.manifest.sizeBytes);
54
+ requireMod(!controller.signal.aborted,"full_download_timeout");
55
+ return {envelope:release.envelope,bytes};
56
+ })(),
57
+ new Promise((_,reject)=>{ timer=setTimeout(()=>{controller.abort();reject(new ModError("full_download_timeout"));},timeoutMs); })
58
+ ]);
59
+ } finally { clearTimeout(timer); }
60
+ artifact=await installArtifact(cacheRoot,download.envelope,download.bytes,target);
61
+ }
62
+ return {ok:true,mode:"full",activation:runningArtifactId&&runningArtifactId!==artifact.artifactId?"restart-required":"ready",artifact};
63
+ } catch(error) {
64
+ const code=error instanceof ModError ? error.code : "full_download_failed";
65
+ return {ok:false,error:"full_unavailable",reason:code,message:errors[code]|| (error instanceof ModError?error.message:errors.full_download_failed),fallback:"explicit-lite-only"};
66
+ }
67
+ }
@@ -0,0 +1,63 @@
1
+ import { createHash, createPublicKey, verify } from "node:crypto";
2
+ import { negotiateManifest } from "../packages/full-contracts/index.mjs";
3
+
4
+ export const MAX_ARTIFACT_BYTES = 256 * 1024 * 1024;
5
+ export const MAX_MANIFEST_BYTES = 64 * 1024;
6
+ export const MAX_FILES = 8192;
7
+ export class ModError extends Error {
8
+ constructor(code, message = code) { super(message); this.name = "ModError"; this.code = code; }
9
+ }
10
+ export function requireMod(condition, code, message) { if (!condition) throw new ModError(code, message); }
11
+ export const digest = value => createHash("sha256").update(value).digest("hex");
12
+
13
+ // A portable archive path is deliberately narrower than the host filesystem.
14
+ // Case-folded collisions, Windows devices, ADS, trailing dots and traversal are rejected.
15
+ export function portablePath(value) {
16
+ requireMod(typeof value === "string" && value.length > 0 && value.length <= 240, "full_unsafe_path");
17
+ const parts = value.split("/");
18
+ requireMod(parts.every(part => /^[A-Za-z0-9_.@+-]+$/.test(part) &&
19
+ part !== "." && part !== ".." && !part.endsWith(".") &&
20
+ !/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part)), "full_unsafe_path");
21
+ requireMod(!["manifest.json", "artifact.tar", "complete.json"].includes(parts[0].toLowerCase()), "full_reserved_path");
22
+ return value;
23
+ }
24
+ function decodeBase64(value, max) {
25
+ requireMod(typeof value === "string" && value.length <= Math.ceil(max / 3) * 4 &&
26
+ /^[A-Za-z0-9+/]+={0,2}$/.test(value), "full_invalid_signed_manifest");
27
+ const data = Buffer.from(value, "base64");
28
+ requireMod(data.length <= max && data.toString("base64") === value, "full_invalid_signed_manifest");
29
+ return data;
30
+ }
31
+ export function verifySignedManifest(envelope, { trustedKeys, requestedVersion, schemaVersion, ...target }) {
32
+ requireMod(envelope && typeof envelope === "object" && typeof envelope.keyId === "string" &&
33
+ /^[A-Za-z0-9_-]{1,64}$/.test(envelope.keyId), "full_invalid_signed_manifest");
34
+ requireMod(trustedKeys instanceof Map && trustedKeys.has(envelope.keyId), "full_untrusted_signer",
35
+ "No trusted first-party signing key for this artifact.");
36
+ const payload = decodeBase64(envelope.payload, MAX_MANIFEST_BYTES);
37
+ const signature = decodeBase64(envelope.signature, 64);
38
+ let key;
39
+ try { key = createPublicKey(trustedKeys.get(envelope.keyId)); } catch { throw new ModError("full_untrusted_signer"); }
40
+ requireMod(key.asymmetricKeyType === "ed25519" && signature.length === 64 &&
41
+ verify(null, payload, key, signature), "full_bad_signature");
42
+ let raw;
43
+ try { raw = JSON.parse(payload.toString("utf8")); } catch { throw new ModError("full_invalid_signed_manifest"); }
44
+ let negotiated;
45
+ try { negotiated = negotiateManifest(raw, target); } catch (error) { throw new ModError(error.code || "full_invalid_manifest"); }
46
+ const { manifest, capabilities } = negotiated;
47
+ requireMod(manifest.version === requestedVersion, "full_version_mismatch");
48
+ requireMod(manifest.sizeBytes <= MAX_ARTIFACT_BYTES, "full_artifact_too_large");
49
+ const entrypoint = portablePath(raw.entrypoint);
50
+ requireMod(entrypoint.endsWith(".mjs"), "full_invalid_entrypoint");
51
+ const schema = raw.schema;
52
+ requireMod(schema && [schema.minReadable, schema.maxReadable, schema.writeVersion].every(x => Number.isSafeInteger(x) && x >= 0) &&
53
+ schema.minReadable <= schema.maxReadable && schema.writeVersion >= schema.minReadable &&
54
+ schema.writeVersion <= schema.maxReadable, "full_invalid_schema_contract");
55
+ requireMod(Number.isSafeInteger(schemaVersion) && schemaVersion >= 0, "full_schema_unknown",
56
+ "Inspect the local datastore schema before selecting a runtime.");
57
+ requireMod(schemaVersion >= schema.minReadable && schemaVersion <= schema.maxReadable &&
58
+ schema.writeVersion >= schemaVersion, "full_schema_incompatible",
59
+ "Keep the current runtime or use a compatible migration/recovery artifact; no state was changed.");
60
+ return Object.freeze({ manifest: Object.freeze({...manifest, coreVersions:Object.freeze(manifest.coreVersions), capabilities:Object.freeze(manifest.capabilities)}),
61
+ capabilities: Object.freeze(capabilities), artifactId: digest(payload), entrypoint,
62
+ schema: Object.freeze({minReadable:schema.minReadable,maxReadable:schema.maxReadable,writeVersion:schema.writeVersion}) });
63
+ }