@anusornneal/chat-relay 1.9.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +6 -0
  2. package/agent/activity-capture.mjs +165 -0
  3. package/agent/capability-scheduler.mjs +82 -5
  4. package/agent/file-manager.mjs +8 -3
  5. package/agent/full-bridge.mjs +53 -0
  6. package/agent/full-desktop-actions.mjs +124 -0
  7. package/agent/full-desktop-auth.mjs +53 -0
  8. package/agent/full-desktop-broker.mjs +308 -0
  9. package/agent/full-host.mjs +153 -0
  10. package/agent/full-job-broker.mjs +360 -0
  11. package/agent/full-native-job.mjs +205 -0
  12. package/agent/full-presentation-changes.mjs +191 -0
  13. package/agent/full-remote-diagnostics.mjs +129 -0
  14. package/agent/full-resources.mjs +343 -0
  15. package/agent/full-runtime-supervisor.mjs +67 -0
  16. package/agent/full-session-dispatch.mjs +167 -0
  17. package/agent/full-workspace-broker.mjs +290 -0
  18. package/agent/git-worktree-manager.mjs +170 -4
  19. package/agent/lifecycle.mjs +11 -0
  20. package/agent/local-agent.mjs +150 -24
  21. package/agent/local-usage.mjs +21 -0
  22. package/agent/monitor-activity.mjs +111 -0
  23. package/agent/presentation-redaction.mjs +10 -0
  24. package/agent/process-manager.mjs +32 -0
  25. package/agent/terminal-manager.mjs +189 -31
  26. package/agent/toolcall-context.mjs +23 -1
  27. package/agent/windows-desktop-runner.mjs +65 -61
  28. package/agent/windows-desktop-worker.ps1 +33 -18
  29. package/agent/windows-powershell.mjs +51 -0
  30. package/cli/full-background.mjs +69 -0
  31. package/cli/full-launch.mjs +94 -0
  32. package/cli/full-prepare-child.mjs +48 -0
  33. package/cli/full-prepare.mjs +171 -0
  34. package/cli/full-release-default.json +4 -0
  35. package/cli/full-release-files.mjs +36 -0
  36. package/cli/full-release-official.mjs +48 -0
  37. package/cli/full-release-source.mjs +37 -0
  38. package/cli/index.mjs +8 -4
  39. package/cli/mod-cache.mjs +170 -0
  40. package/cli/mod-loader.mjs +67 -0
  41. package/cli/mod-manifest.mjs +63 -0
  42. package/cli/remote.mjs +172 -17
  43. package/cli/runner-ownership.mjs +116 -3
  44. package/cli/self-update.mjs +1 -1
  45. package/cli/tui.mjs +2 -20
  46. package/package.json +5 -3
  47. package/packages/full-contracts/index.mjs +193 -0
  48. package/packages/full-contracts/native-job.mjs +13 -0
  49. package/packages/full-contracts/package.json +7 -0
  50. package/packages/full-contracts/remote-session.mjs +239 -0
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
+ }
package/cli/remote.mjs CHANGED
@@ -1,13 +1,17 @@
1
1
  import { execFile, spawn } from "node:child_process";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import path from "node:path";
4
+ import { randomUUID } from "node:crypto";
4
5
  import { loadConfig, saveConfig } from "./config.mjs";
5
6
  import { login, needsRelayLogin, requestJson } from "./device-login.mjs";
6
- import { acquireRunnerOwnership, RunnerAlreadyActiveError } from "./runner-ownership.mjs";
7
+ import { acquireRunnerOwnership, requestFullDesktopOpen, RunnerAlreadyActiveError } from "./runner-ownership.mjs";
7
8
  import { getAgentVersion } from "../agent/protocol.mjs";
8
9
  import { AGENT_UPGRADE_EXIT_CODE } from "../agent/lifecycle.mjs";
10
+ import { FULL_STARTUP_EXIT_CODE } from "../agent/full-session-dispatch.mjs";
11
+ import { attachDesktopAuthorization } from "../agent/full-desktop-auth.mjs";
9
12
  import { RemoteTui, shouldUseTui } from "./tui.mjs";
10
13
  import { startRelayHealthMonitor } from "./relay-health.mjs";
14
+ import {createBackgroundHandoff,launchFullBackground,shouldLaunchFullBackground} from "./full-background.mjs";
11
15
 
12
16
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
13
17
  let stopping = false;
@@ -16,7 +20,8 @@ export function shouldRestartAgent(result, stoppingNow = false) {
16
20
  return !stoppingNow
17
21
  && result?.code !== 2
18
22
  && result?.code !== 3
19
- && result?.code !== AGENT_UPGRADE_EXIT_CODE;
23
+ && result?.code !== AGENT_UPGRADE_EXIT_CODE
24
+ && result?.code !== FULL_STARTUP_EXIT_CODE;
20
25
  }
21
26
 
22
27
  export function protocolCompatibility(agentProtocolVersion, expectedProtocolVersion) {
@@ -41,11 +46,12 @@ function terminateChildTree(child) {
41
46
  child.kill("SIGTERM");
42
47
  }
43
48
 
44
- async function validateConfig(config) {
49
+ async function validateConfig(config, { onVerified } = {}) {
45
50
  if (!config?.relayUrl || !config?.userToken || !config?.agentToken || !config?.agentId) return false;
46
- const { response } = await requestJson(`${config.relayUrl}/auth/me`, {
51
+ const { response, data } = await requestJson(`${config.relayUrl}/auth/me`, {
47
52
  headers: { authorization: `Bearer ${config.userToken}` },
48
53
  }).catch(() => ({ response: { ok: false } }));
54
+ if(response.ok)onVerified?.(data);
49
55
  return Boolean(response.ok);
50
56
  }
51
57
 
@@ -62,14 +68,17 @@ function printSummary(config) {
62
68
  console.log("");
63
69
  }
64
70
 
65
- function spawnAgent(config, { tui = null, onConnectionState = null } = {}) {
71
+ function spawnAgent(config, { tui = null, onConnectionState = null, fullBootstrap = null, authorizeDesktop = null } = {}) {
66
72
  const agentPath = path.join(packageRoot, "agent", "local-agent.mjs");
67
73
  const cwd = String(config.allowedRoots || process.cwd()).split(";")[0] || process.cwd();
68
74
  const useTui = Boolean(tui);
75
+ const environment = { ...process.env };
76
+ delete environment.CHAT_RELAY_FULL_BOOTSTRAP;
77
+ if (fullBootstrap) environment.CHAT_RELAY_FULL_BOOTSTRAP = JSON.stringify(fullBootstrap);
69
78
  const child = spawn(process.execPath, [agentPath], {
70
79
  cwd,
71
80
  env: {
72
- ...process.env,
81
+ ...environment,
73
82
  RELAY_URL: config.relayUrl,
74
83
  AGENT_ID: config.agentId,
75
84
  AGENT_NAME: config.agentName,
@@ -79,9 +88,14 @@ function spawnAgent(config, { tui = null, onConnectionState = null } = {}) {
79
88
  ALLOWED_ROOTS: config.allowedRoots,
80
89
  CHAT_RELAY_UI: useTui ? "ipc" : "plain",
81
90
  },
82
- stdio: useTui ? ["inherit", "inherit", "inherit", "ipc"] : "inherit",
83
- windowsHide: false,
91
+ stdio: useTui || fullBootstrap ? ["inherit", "inherit", "inherit", "ipc"] : "inherit",
92
+ // Full GUI owns the visible window; its Core must not allocate a console.
93
+ windowsHide: fullBootstrap?.headless === false,
84
94
  });
95
+ if(fullBootstrap?.headless===false){
96
+ const stopAuthorization=attachDesktopAuthorization(child,{principal:fullBootstrap.localPrincipal,authenticate:authorizeDesktop});
97
+ child.once("exit",stopAuthorization);child.once("error",stopAuthorization);
98
+ }
85
99
  if (useTui) child.on("message", (message) => {
86
100
  tui.handleMessage(message);
87
101
  if (message?.type === "chat-relay-ui" && message.event === "connection") {
@@ -91,19 +105,110 @@ function spawnAgent(config, { tui = null, onConnectionState = null } = {}) {
91
105
  return child;
92
106
  }
93
107
 
108
+ function openDesktopOnChild(child, accountId) {
109
+ const failure = code => Object.assign(new Error(code), { code });
110
+ if (!child?.connected) return Promise.reject(failure("full_unavailable"));
111
+ return new Promise((resolve, reject) => {
112
+ const requestId = randomUUID();
113
+ let settled = false;
114
+ const finish = (error, result) => {
115
+ if (settled) return;
116
+ settled = true; clearTimeout(timer);
117
+ child.removeListener("message", onMessage);
118
+ child.removeListener("exit", onExit);
119
+ child.removeListener("disconnect", onExit);
120
+ child.removeListener("error", onExit);
121
+ if (error) reject(error); else resolve(result);
122
+ };
123
+ const onExit = () => finish(failure("full_unavailable"));
124
+ const onMessage = message => {
125
+ if (message?.type !== "chat-relay-full-desktop" || message.kind !== "result" || message.requestId !== requestId) return;
126
+ if (message.ok === true && typeof message.alreadyOpen === "boolean")
127
+ finish(null, { alreadyOpen: message.alreadyOpen });
128
+ else finish(failure(typeof message.error === "string" && /^full_[a-z0-9_]+$/.test(message.error)
129
+ ? message.error : "full_desktop_reopen_unavailable"));
130
+ };
131
+ const timer = setTimeout(() => finish(failure("full_desktop_reopen_timeout")), 10000);
132
+ child.on("message", onMessage);
133
+ child.once("exit", onExit); child.once("disconnect", onExit); child.once("error", onExit);
134
+ try {
135
+ child.send({ type: "chat-relay-full-desktop", kind: "open", requestId, accountId },
136
+ error => { if (error) onExit(); });
137
+ } catch { onExit(); }
138
+ });
139
+ }
140
+
94
141
  export async function remote(options = {}) {
142
+ const background=createBackgroundHandoff();
143
+ let fullSettings=null, prepareFullLaunch=null, localFullPrincipal=null;
144
+ if (options.full === true) {
145
+ try {
146
+ const full=await import("./full-launch.mjs");
147
+ fullSettings=await full.readFullReleaseSettings({headless:options.headless===true});
148
+ if(!full.supportedFullNode())throw Object.assign(new Error("Unsupported Node.js"),{code:"full_node_unsupported"});
149
+ prepareFullLaunch=full.prepareFullLaunch;
150
+ localFullPrincipal=full.localFullPrincipal;
151
+ } catch(error) {
152
+ console.error("Full runtime unavailable: "+(error?.code||"full_release_unconfigured")+". No Core fallback was started.");
153
+ return 1;
154
+ }
155
+ }
156
+ if (options.headless === true && options.full !== true) {
157
+ console.error("--headless requires --full.");
158
+ return 1;
159
+ }
95
160
  stopping = false;
96
- let config = loadConfig();
97
- if (needsRelayLogin(config, options.relayUrl) || !(await validateConfig(config))) {
161
+ let config = loadConfig(), authentication=null;
162
+ const authenticated=data=>{authentication=data;};
163
+ if (needsRelayLogin(config, options.relayUrl) || !(await validateConfig(config,{onVerified:authenticated}))) {
164
+ if(background){console.error("Background Full requires a valid saved login.");return 1;}
98
165
  console.log("No valid Chat Relay login found. Starting sign in...");
99
166
  config = await login(options);
100
167
  }
101
168
 
102
- let ownership;
169
+ let fullPrincipal;
170
+ if(fullSettings?.headless===false){
171
+ try{
172
+ if(!authentication&&!await validateConfig(config,{onVerified:authenticated}))throw new Error("authorization unavailable");
173
+ fullPrincipal=localFullPrincipal(config,authentication);
174
+ }catch{console.error("Full desktop unavailable: signed-in account and read grant for this agent are required.");return 1;}
175
+ }
176
+ let ownership, activeDesktopChild = null;
177
+ const desktopMode = fullSettings?.headless === false;
178
+ if(background&&!process.connected)return 1;
179
+ if(shouldLaunchFullBackground(options))return launchFullBackground({entrypoint:path.join(packageRoot,"bin","chat-relay.js"),args:options.launchArgs});
103
180
  try {
104
- ownership = await acquireRunnerOwnership({ relayUrl: config.relayUrl, agentId: config.agentId });
181
+ ownership = await acquireRunnerOwnership({
182
+ relayUrl: config.relayUrl, agentId: config.agentId,
183
+ ...(desktopMode ? {
184
+ desktopIdentity: { accountId: fullPrincipal.accountId, version: fullSettings.requestedVersion },
185
+ onOpenFullDesktop: () => {
186
+ if (stopping || !activeDesktopChild?.connected)
187
+ throw Object.assign(new Error("Full desktop is starting or stopping"), { code: "full_unavailable" });
188
+ return openDesktopOnChild(activeDesktopChild, fullPrincipal.accountId);
189
+ },
190
+ } : {}),
191
+ });
105
192
  } catch (error) {
106
193
  if (!(error instanceof RunnerAlreadyActiveError)) throw error;
194
+ if (desktopMode) {
195
+ if ((options.allowedRoot && options.allowedRoot !== config.allowedRoots) ||
196
+ (options.desktopEnabled !== undefined && Boolean(options.desktopEnabled) !== Boolean(config.desktopEnabled))) {
197
+ console.error("Full desktop reopen cannot reconfigure an active runner. Drain and stop it before changing roots or desktop settings.");
198
+ return 1;
199
+ }
200
+ const opened = await requestFullDesktopOpen({
201
+ relayUrl: config.relayUrl, agentId: config.agentId,
202
+ accountId: fullPrincipal.accountId, version: fullSettings.requestedVersion,
203
+ });
204
+ if (opened.ok) {
205
+ console.log(opened.alreadyOpen
206
+ ? "Full desktop is already open. The existing Core runner remains connected."
207
+ : "Full desktop reopened on the existing Core runner.");
208
+ return background && !(await background.announce()) ? 1 : 0;
209
+ }
210
+ console.error("Full desktop reopen unavailable: " + opened.error + ". The existing runner was not changed.");
211
+ }
107
212
  console.error(error.message);
108
213
  return 1;
109
214
  }
@@ -120,7 +225,7 @@ export async function remote(options = {}) {
120
225
  saveConfig(config);
121
226
  }
122
227
 
123
- const useTui = shouldUseTui(options);
228
+ const useTui = options.full !== true && shouldUseTui(options);
124
229
  tui = useTui ? new RemoteTui({ config, version: getAgentVersion() }) : null;
125
230
  if (tui) {
126
231
  tui.start();
@@ -130,31 +235,80 @@ export async function remote(options = {}) {
130
235
  onStatus: (health) => tui?.setRelayHealth(health),
131
236
  });
132
237
  }
133
- else printSummary(config);
238
+ else if(!desktopMode) printSummary(config);
134
239
 
135
240
  while (!stopping) {
241
+ if(background&&!background.acknowledged&&!process.connected){supervisorCode=1;break;}
242
+ let fullBootstrap=null;
243
+ if(fullSettings){
244
+ try{fullBootstrap=await prepareFullLaunch({settings:fullSettings,config,principal:fullPrincipal});}
245
+ catch(error){console.error("Full runtime unavailable: "+(error?.code||"full_startup_failed")+". No Core fallback was started.");supervisorCode=1;break;}
246
+ }
247
+ if(background&&!background.acknowledged&&!process.connected){supervisorCode=1;break;}
136
248
  const child = spawnAgent(config, {
137
- tui,
249
+ tui, fullBootstrap,
250
+ authorizeDesktop:async()=>{
251
+ const {response,data}=await requestJson(config.relayUrl+"/auth/me",{headers:{authorization:"Bearer "+config.userToken}},7500);
252
+ if(!response.ok)throw new Error("authorization unavailable");
253
+ return localFullPrincipal(config,data);
254
+ },
138
255
  onConnectionState: (state) => {
139
256
  if (state === "connected") stopRelayHealthMonitor?.checkNow?.();
140
257
  },
141
258
  });
142
259
 
260
+ activeDesktopChild = desktopMode ? child : null;
261
+ let forceStopTimer;
143
262
  const stop = () => {
263
+ if(stopping)return;
144
264
  stopping = true;
145
- terminateChildTree(child);
265
+ if(fullBootstrap&&child.connected){
266
+ // Give the supervised Full host a chance to commit and release its
267
+ // store before Windows tree termination. Timeout is not proof of recovery.
268
+ forceStopTimer=setTimeout(()=>terminateChildTree(child),20000);
269
+ try{child.send({type:"chat-relay-runner",command:"shutdown"},error=>{if(error){clearTimeout(forceStopTimer);terminateChildTree(child);}});}
270
+ catch{clearTimeout(forceStopTimer);terminateChildTree(child);}
271
+ }else terminateChildTree(child);
272
+ };
273
+ const backgroundReady=message=>{
274
+ if(message?.type==="chat-relay-runner"&&message.event==="full-gui-ready"&&background&&!background.acknowledged){
275
+ void background.announce().then(ok=>{if(!ok)stop();});
276
+ }
146
277
  };
278
+ if(background&&!background.acknowledged)child.on("message",backgroundReady);
279
+ const parentDisconnected=()=>{if(!background?.acknowledged)stop();};
147
280
  process.once("SIGINT", stop);
148
281
  process.once("SIGTERM", stop);
282
+ // A managed Full runner may have its own supervisor IPC. A normal
283
+ // parent disconnect requests the same bounded graceful shutdown.
284
+ if(fullBootstrap&&typeof process.send==="function"&&!background?.acknowledged){
285
+ process.once("disconnect",parentDisconnected);
286
+ if(!process.connected)parentDisconnected();
287
+ }
149
288
 
150
289
  const result = await new Promise((resolve) => {
151
290
  child.once("exit", (code, signal) => resolve({ code, signal }));
291
+ child.once("error", () => resolve({code:fullBootstrap?FULL_STARTUP_EXIT_CODE:1,signal:null}));
152
292
  });
293
+ clearTimeout(forceStopTimer);
294
+ if (activeDesktopChild === child) activeDesktopChild = null;
153
295
 
154
296
  process.removeListener("SIGINT", stop);
155
297
  process.removeListener("SIGTERM", stop);
156
- if (stopping) break;
298
+ process.removeListener("disconnect", parentDisconnected);
299
+ child.removeListener("message",backgroundReady);
300
+ if (stopping) {
301
+ if(fullBootstrap && result.code !== 0)supervisorCode=1;
302
+ break;
303
+ }
157
304
 
305
+ if (fullBootstrap && result.code === 0) { stopping=true; break; }
306
+ if (result.code === FULL_STARTUP_EXIT_CODE) {
307
+ stopping=true;
308
+ supervisorCode=1;
309
+ console.error("Full agent failed or its shutdown could not be confirmed. No automatic Lite fallback or datastore recovery.");
310
+ break;
311
+ }
158
312
  if (result.code === 2) {
159
313
  stopping = true;
160
314
  console.error("Agent authorization is no longer valid. Run chat-relay login --force, then chat-relay remote.");
@@ -185,6 +339,7 @@ export async function remote(options = {}) {
185
339
  }
186
340
  }
187
341
  } finally {
342
+ activeDesktopChild = null;
188
343
  try { stopRelayHealthMonitor?.(); } catch {}
189
344
  try { tui?.stop?.(); } catch {}
190
345
  await ownership.release();