@anusornneal/chat-relay 1.9.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/agent/activity-capture.mjs +165 -0
- package/agent/capability-scheduler.mjs +82 -5
- package/agent/file-manager.mjs +8 -3
- package/agent/full-bridge.mjs +53 -0
- package/agent/full-desktop-actions.mjs +124 -0
- package/agent/full-desktop-auth.mjs +53 -0
- package/agent/full-desktop-broker.mjs +308 -0
- package/agent/full-host.mjs +153 -0
- package/agent/full-job-broker.mjs +360 -0
- package/agent/full-native-job.mjs +205 -0
- package/agent/full-presentation-changes.mjs +191 -0
- package/agent/full-remote-diagnostics.mjs +129 -0
- package/agent/full-resources.mjs +343 -0
- package/agent/full-runtime-supervisor.mjs +67 -0
- package/agent/full-session-dispatch.mjs +167 -0
- package/agent/full-workspace-broker.mjs +290 -0
- package/agent/git-worktree-manager.mjs +170 -4
- package/agent/lifecycle.mjs +11 -0
- package/agent/local-agent.mjs +150 -24
- package/agent/local-usage.mjs +21 -0
- package/agent/monitor-activity.mjs +111 -0
- package/agent/presentation-redaction.mjs +10 -0
- package/agent/process-manager.mjs +32 -0
- package/agent/terminal-manager.mjs +189 -31
- package/agent/toolcall-context.mjs +23 -1
- package/agent/windows-desktop-runner.mjs +65 -61
- package/agent/windows-desktop-worker.ps1 +33 -18
- package/agent/windows-powershell.mjs +51 -0
- package/cli/full-background.mjs +69 -0
- package/cli/full-launch.mjs +94 -0
- package/cli/full-prepare-child.mjs +48 -0
- package/cli/full-prepare.mjs +171 -0
- package/cli/full-release-default.json +4 -0
- package/cli/full-release-files.mjs +36 -0
- package/cli/full-release-official.mjs +48 -0
- package/cli/full-release-source.mjs +37 -0
- package/cli/index.mjs +8 -4
- package/cli/mod-cache.mjs +170 -0
- package/cli/mod-loader.mjs +67 -0
- package/cli/mod-manifest.mjs +63 -0
- package/cli/remote.mjs +172 -17
- package/cli/runner-ownership.mjs +116 -3
- package/cli/self-update.mjs +1 -1
- package/cli/tui.mjs +2 -20
- package/package.json +5 -3
- package/packages/full-contracts/index.mjs +193 -0
- package/packages/full-contracts/native-job.mjs +13 -0
- package/packages/full-contracts/package.json +7 -0
- package/packages/full-contracts/remote-session.mjs +239 -0
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import {describeFullMonitorActivity} from "./monitor-activity.mjs";
|
|
3
|
+
import {createReadStream} from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import {spawn} from "node:child_process";
|
|
6
|
+
import {pathToFileURL} from "node:url";
|
|
7
|
+
import {createHash,randomUUID} from "node:crypto";
|
|
8
|
+
import {performance} from "node:perf_hooks";
|
|
9
|
+
import {FULL_API_VERSION,FullContractError,jobIsSettled} from "../packages/full-contracts/index.mjs";
|
|
10
|
+
import {createAuthorizedFullInvocation,parseRemoteFullRequest} from "../packages/full-contracts/remote-session.mjs";
|
|
11
|
+
|
|
12
|
+
const id=v=>typeof v==="string"&&/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(v);
|
|
13
|
+
const record=v=>v!==null&&typeof v==="object"&&!Array.isArray(v);
|
|
14
|
+
const exact=(v,keys)=>record(v)&&Object.keys(v).every(k=>keys.includes(k));
|
|
15
|
+
const require=(ok,code)=>{if(!ok)throw new FullContractError(code);};
|
|
16
|
+
const text=(v,n=512)=>typeof v==="string"?v.slice(0,n).toWellFormed():"";
|
|
17
|
+
import {redactPresentationText} from "./presentation-redaction.mjs";
|
|
18
|
+
export {redactPresentationText};
|
|
19
|
+
const jobView=job=>job?{jobId:job.jobId,state:job.state,exitCode:job.exitCode??null,signal:job.signal??null}:null;
|
|
20
|
+
const safeSession=s=>({taskSessionId:s.taskSessionId,title:redactPresentationText(s.title,200),project:redactPresentationText(s.projectKey,200),status:s.status,revision:s.revision,
|
|
21
|
+
createdAt:text(s.createdAt,40),updatedAt:text(s.updatedAt,40),activity:[],changes:[]});
|
|
22
|
+
|
|
23
|
+
/** Account-bound local monitor. Owned output/Git display reads and confirmed local Quit only. */
|
|
24
|
+
export function createDesktopService({principal,dispatch,allowTerminal=false,authorizePrincipal,monitorSnapshot=()=>null,monitorDetails,localMonitor=false,requestQuit,readChanges}){
|
|
25
|
+
require(principal&&id(principal.accountId)&&id(principal.agentId)&&Array.isArray(principal.scopes)&&principal.scopes.includes("read")&&typeof dispatch==="function","full_invalid_presentation_configuration");
|
|
26
|
+
principal={accountId:principal.accountId,agentId:principal.agentId,scopes:[...principal.scopes]};
|
|
27
|
+
const activities=new Map(),lastObservedJobs=new Map();
|
|
28
|
+
let currentScopes=[...principal.scopes],authorizedAt=-Infinity,authorityVersion=0;
|
|
29
|
+
async function refreshAuthority(force,signal){
|
|
30
|
+
require(!signal?.aborted,"full_cancelled_before_start");
|
|
31
|
+
if(typeof authorizePrincipal!=="function")return;
|
|
32
|
+
if(!force&&performance.now()-authorizedAt<5000)return;
|
|
33
|
+
// Re-check current grants through Core/runner without giving GUI any token.
|
|
34
|
+
// The initial scope remains an upper bound, including after grant changes.
|
|
35
|
+
const expected=++authorityVersion;
|
|
36
|
+
currentScopes=[];authorizedAt=-Infinity;
|
|
37
|
+
const live=await authorizePrincipal({signal});
|
|
38
|
+
require(!signal?.aborted,"full_cancelled_before_start");
|
|
39
|
+
require(expected===authorityVersion,"full_presentation_permission_denied");
|
|
40
|
+
require(live?.accountId===principal.accountId&&live.agentId===principal.agentId&&Array.isArray(live.scopes),"full_presentation_permission_denied");
|
|
41
|
+
currentScopes=principal.scopes.filter(scope=>live.scopes.includes(scope));
|
|
42
|
+
require(currentScopes.includes("read"),"full_presentation_permission_denied");
|
|
43
|
+
authorizedAt=performance.now();
|
|
44
|
+
}
|
|
45
|
+
// The private, owner-epoch-bound presentation pipe already authenticates the local GUI.
|
|
46
|
+
// Read-only local monitoring uses only its original account/agent grants; never request cloud authorization per view.
|
|
47
|
+
const localScopes=principal.scopes;
|
|
48
|
+
const viewScopes=()=>localMonitor?localScopes:currentScopes;
|
|
49
|
+
const permitted=(operation,input,local=false)=>{
|
|
50
|
+
const parsed=parseRemoteFullRequest({operation,input});
|
|
51
|
+
require(parsed.requiredScopes.every(scope=>(local&&localMonitor?localScopes:currentScopes).includes(scope))&&(!parsed.requiredScopes.includes("terminal")||allowTerminal),"full_presentation_permission_denied");
|
|
52
|
+
return createAuthorizedFullInvocation({operation:parsed.operation,input:parsed.input},{accountId:principal.accountId,agentId:principal.agentId});
|
|
53
|
+
};
|
|
54
|
+
async function call(operation,input,signal,local=false){
|
|
55
|
+
require(!signal?.aborted,"full_cancelled_before_start");
|
|
56
|
+
const result=await dispatch(permitted(operation,input,local));
|
|
57
|
+
require(result?.ok===true,result?.error??"full_presentation_failed");
|
|
58
|
+
return result.result;
|
|
59
|
+
}
|
|
60
|
+
function commandAvailability(){
|
|
61
|
+
const terminal=allowTerminal&¤tScopes.includes("terminal");
|
|
62
|
+
return {
|
|
63
|
+
"job.output":{available:terminal,reason:terminal?null:"Local terminal permission unavailable"},
|
|
64
|
+
"changes.list":{available:viewScopes().includes("read")&&typeof readChanges==="function",reason:typeof readChanges==="function"?null:"Changes are unavailable in this runtime"},
|
|
65
|
+
"changes.diff":{available:viewScopes().includes("read")&&typeof readChanges==="function",reason:typeof readChanges==="function"?null:"Changes are unavailable in this runtime"},
|
|
66
|
+
...(typeof monitorDetails==="function"?{"activity.detail":{available:viewScopes().includes("read")},"activity.diff":{available:viewScopes().includes("read")}}:{}),
|
|
67
|
+
"agent.quit":{available:typeof requestQuit==="function",reason:typeof requestQuit==="function"?null:"Local agent lifecycle unavailable"}
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
const scopeId=createHash("sha256").update(JSON.stringify([principal.accountId,principal.agentId])).digest("hex").slice(0,32);
|
|
71
|
+
function completed(parsed,result){
|
|
72
|
+
if(parsed?.principal?.accountId!==principal.accountId||parsed.principal.agentId!==principal.agentId)return false;
|
|
73
|
+
// Reads performed to render the GUI must never invalidate that same GUI;
|
|
74
|
+
// otherwise each refresh would create a self-sustaining request loop.
|
|
75
|
+
if(["full.session.list","full.session.snapshot","full.session.export","full.session.delete","full.job.read"].includes(parsed.operation))return false;
|
|
76
|
+
const taskSessionId=parsed.input?.taskSessionId??result?.result?.session?.taskSessionId;
|
|
77
|
+
if(!id(taskSessionId))return true;
|
|
78
|
+
const previous=activities.get(taskSessionId)??[];
|
|
79
|
+
const at=new Date();
|
|
80
|
+
previous.push({requestId:randomUUID(),at:at.toISOString(),time:at.toLocaleTimeString("en-GB",{hour12:false}),type:"tool.completed",action:parsed.operation,operation:redactPresentationText(describeFullMonitorActivity(parsed.operation,parsed.input),128),category:"Full",ok:result?.ok===true});
|
|
81
|
+
if(previous.length>32)previous.shift();
|
|
82
|
+
activities.delete(taskSessionId);activities.set(taskSessionId,previous);
|
|
83
|
+
while(activities.size>32)activities.delete(activities.keys().next().value);
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
function forgetSession(owner){
|
|
87
|
+
if(owner?.accountId!==principal.accountId||owner.agentId!==principal.agentId||!id(owner.taskSessionId))return false;
|
|
88
|
+
activities.delete(owner.taskSessionId);lastObservedJobs.delete(owner.taskSessionId);return true;
|
|
89
|
+
}
|
|
90
|
+
async function snapshot({consumerId,cursor,input={},signal}){
|
|
91
|
+
require(exact(input,["selectedId","after"])&&(input.selectedId===undefined||input.selectedId===null||id(input.selectedId))&&(input.after===undefined||input.after===""||id(input.after)),"full_invalid_presentation_input");
|
|
92
|
+
const rawMonitor=monitorSnapshot();
|
|
93
|
+
// Local labels are bounded and redacted before crossing the presentation
|
|
94
|
+
// boundary. On authority loss, retain counters but not task/project labels.
|
|
95
|
+
const monitor=rawMonitor?{...rawMonitor,activity:(Array.isArray(rawMonitor.activity)?rawMonitor.activity:[]).slice(-40).map(row=>({
|
|
96
|
+
requestId:id(row.requestId)?row.requestId:"",taskSessionId:id(row.taskSessionId)?row.taskSessionId:null,hasDetails:row.hasDetails===true,at:text(row.at,40),time:text(row.time,16),type:text(row.type,32),action:text(row.action,100),
|
|
97
|
+
category:text(row.category,32),icon:text(row.icon,8),operation:redactPresentationText(row.operation,128),
|
|
98
|
+
project:redactPresentationText(row.project,64),status:text(row.status,16),ok:typeof row.ok==="boolean"?row.ok:null,
|
|
99
|
+
durationMs:Number.isFinite(row.durationMs)?Math.max(0,row.durationMs):null,elapsedMs:Number.isFinite(row.elapsedMs)?Math.max(0,row.elapsedMs):null,
|
|
100
|
+
requestBytes:Number.isSafeInteger(row.requestBytes)&&row.requestBytes>=0?row.requestBytes:null,responseBytes:Number.isSafeInteger(row.responseBytes)&&row.responseBytes>=0?row.responseBytes:null,
|
|
101
|
+
error:text(row.error,96),detail:redactPresentationText(row.detail,160),query:redactPresentationText(row.query,180),searchScope:redactPresentationText(row.searchScope,180)
|
|
102
|
+
}))}:null;
|
|
103
|
+
try{require(!signal?.aborted,"full_cancelled_before_start");if(!localMonitor)await refreshAuthority(false,signal);}
|
|
104
|
+
catch(error){
|
|
105
|
+
// The local pipe remains authenticated while the cloud is offline.
|
|
106
|
+
// Never return account/task data without fresh or cached current grants.
|
|
107
|
+
if(!monitor||signal?.aborted||!["full_presentation_permission_denied","full_desktop_authorization_unavailable"].includes(error?.code))throw error;
|
|
108
|
+
return {apiVersion:FULL_API_VERSION,ownerEpoch:cursor.producerEpoch,scopeId,cursor,
|
|
109
|
+
sessions:[],detail:null,selectedUnavailable:false,next:null,partial:false,
|
|
110
|
+
sessionAccess:"unavailable",monitor:{...monitor,activity:[]},commands:{"job.output":{available:false,reason:"Session access unavailable"},"changes.list":{available:false,reason:"Session access unavailable"},"changes.diff":{available:false,reason:"Session access unavailable"},"agent.quit":commandAvailability()["agent.quit"]},terminalEnabled:false};
|
|
111
|
+
}
|
|
112
|
+
const commands=commandAvailability(),terminal=allowTerminal&¤tScopes.includes("terminal");
|
|
113
|
+
const listed=await call("full.session.list",{after:input.after??"",limit:32},signal,true);
|
|
114
|
+
const sessions=listed.items.map(safeSession);
|
|
115
|
+
let detail=null,selectedUnavailable=false;
|
|
116
|
+
if(input.selectedId){
|
|
117
|
+
let source;
|
|
118
|
+
try{source=await call("full.session.snapshot",{taskSessionId:input.selectedId,consumerId},signal,true);}
|
|
119
|
+
catch(error){
|
|
120
|
+
// A saved selection may have been explicitly deleted since the list
|
|
121
|
+
// read. Clear its view without exposing whether another owner has it.
|
|
122
|
+
if(error?.code!=="full_unauthorized")throw error;
|
|
123
|
+
selectedUnavailable=true;
|
|
124
|
+
const index=sessions.findIndex(session=>session.taskSessionId===input.selectedId);
|
|
125
|
+
if(index>=0)sessions.splice(index,1);
|
|
126
|
+
}
|
|
127
|
+
if(source){
|
|
128
|
+
const facts=source.session.facts??{},rawJobs=source.jobs??[],jobs=rawJobs.map(jobView);
|
|
129
|
+
// Prefer unresolved work, otherwise retain the last job observed in
|
|
130
|
+
// this monitor. UUID sorting is not a reliable chronological order.
|
|
131
|
+
const currentJob=rawJobs.find(j=>!jobIsSettled(j))??rawJobs.find(j=>j.jobId===lastObservedJobs.get(input.selectedId))??rawJobs[0];
|
|
132
|
+
lastObservedJobs.delete(input.selectedId);
|
|
133
|
+
if(currentJob)lastObservedJobs.set(input.selectedId,currentJob.jobId);
|
|
134
|
+
while(lastObservedJobs.size>32)lastObservedJobs.delete(lastObservedJobs.keys().next().value);
|
|
135
|
+
detail={...safeSession(source.session),workspace:source.workspace?{workspaceId:source.workspace.workspaceId,kind:source.workspace.workspaceKind,mode:source.workspace.mode,state:source.workspace.state,label:redactPresentationText(source.workspace.branch,200)}:null,
|
|
136
|
+
job:jobView(currentJob),jobs,
|
|
137
|
+
activity:(monitor?.activity?.some(row=>row.taskSessionId===input.selectedId)?monitor.activity.filter(row=>row.taskSessionId===input.selectedId):(activities.get(input.selectedId)??[])).slice(-32),
|
|
138
|
+
changes:(facts.changedFiles??[]).slice(0,100).map(p=>redactPresentationText(p,512)),
|
|
139
|
+
evidence:(facts.evidence??[]).slice(-16).map(e=>({evidenceId:e.evidenceId,checkId:e.checkId,kind:e.kind,outcome:e.outcome,observedAt:e.observedAt})),
|
|
140
|
+
blockers:(facts.blockers??[]).slice(0,8).map(p=>redactPresentationText(p,512)),
|
|
141
|
+
summary:redactPresentationText(facts.summary,1000),indexState:"not-assessed",
|
|
142
|
+
detailPartial:source.historyOmitted>0||source.jobSummary?.omitted>0||source.claimSummary?.omitted>0||(facts.changedFiles?.length??0)>100||(facts.evidence?.length??0)>16,
|
|
143
|
+
historyGap:source.gap===true};
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const view={apiVersion:FULL_API_VERSION,ownerEpoch:cursor.producerEpoch,scopeId,cursor,sessions,detail,selectedUnavailable,next:listed.next,partial:!!listed.next,commands,monitor,sessionAccess:"available",terminalEnabled:terminal,activityRetention:"Last 32 local requests per selected session; older activity may be unavailable"};
|
|
147
|
+
// Bound encoded UTF-8, including long Thai titles and escaped text. Keep
|
|
148
|
+
// durable identity/state, then trim optional detail with a visible gap.
|
|
149
|
+
const bytes=()=>Buffer.byteLength(JSON.stringify(view));
|
|
150
|
+
for(const key of ["activity","changes","evidence","blockers"]){
|
|
151
|
+
while(bytes()>56000&&detail?.[key]?.length){detail[key].pop();detail.detailPartial=true;}
|
|
152
|
+
}
|
|
153
|
+
while(bytes()>56000&&monitor?.activity?.length){monitor.activity.shift();view.partial=true;}
|
|
154
|
+
while(bytes()>56000&&sessions.length>1){sessions.pop();view.next=sessions.at(-1).taskSessionId;view.partial=true;}
|
|
155
|
+
require(bytes()<=56000,"full_response_too_large");
|
|
156
|
+
return view;
|
|
157
|
+
}
|
|
158
|
+
async function command({action,input,signal}){
|
|
159
|
+
require(Object.hasOwn(commandAvailability(),action)&&record(input),"full_invalid_presentation_input");
|
|
160
|
+
if(action==="agent.quit"){
|
|
161
|
+
require(exact(input,["confirmed"])&&input.confirmed===true&&typeof requestQuit==="function"&&!signal?.aborted,"full_invalid_presentation_input");
|
|
162
|
+
// The private local presentation endpoint is authenticated. Quit is local lifecycle control, not remote task authority.
|
|
163
|
+
requestQuit();return {acknowledged:true};
|
|
164
|
+
}
|
|
165
|
+
const localRead=localMonitor&&["activity.detail","activity.diff","changes.list","changes.diff"].includes(action);
|
|
166
|
+
require(!signal?.aborted,"full_cancelled_before_start");
|
|
167
|
+
if(!localRead)await refreshAuthority(true,signal);
|
|
168
|
+
const commands=commandAvailability();
|
|
169
|
+
require(Object.hasOwn(commands,action)&&commands[action].available,"full_presentation_permission_denied");
|
|
170
|
+
if(action==="activity.detail"||action==="activity.diff"){
|
|
171
|
+
require(exact(input,action==="activity.detail"?["activityId"]:["activityId","fileId"])&&id(input.activityId)&&(action==="activity.detail"||typeof input.fileId==="string"&&/^(?:[0-9]|1[0-9])$/.test(input.fileId)),"full_invalid_presentation_input");
|
|
172
|
+
require(!signal?.aborted,"full_cancelled_before_start");
|
|
173
|
+
require(typeof monitorDetails==="function","full_invalid_presentation_input");
|
|
174
|
+
const value=monitorDetails(input.activityId,input.fileId);
|
|
175
|
+
require(value?.activityId===input.activityId&&Buffer.byteLength(JSON.stringify(value))<=48000,"full_invalid_presentation_result");
|
|
176
|
+
return value;
|
|
177
|
+
}
|
|
178
|
+
if(action==="changes.list"||action==="changes.diff"){
|
|
179
|
+
require(exact(input,action==="changes.list"?["taskSessionId"]:["taskSessionId","relativePath"])&&id(input.taskSessionId)&&
|
|
180
|
+
(action==="changes.list"||typeof input.relativePath==="string"),"full_invalid_presentation_input");
|
|
181
|
+
const expectedAuthority=authorityVersion;
|
|
182
|
+
try{
|
|
183
|
+
const invocation=permitted("full.session.snapshot",{taskSessionId:input.taskSessionId,consumerId:"presentation-changes"},true);
|
|
184
|
+
const result=await readChanges(invocation,input,signal,redactPresentationText);
|
|
185
|
+
require(!signal?.aborted,"full_cancelled_before_start");
|
|
186
|
+
require(localRead?localScopes.includes("read"):expectedAuthority===authorityVersion&¤tScopes.includes("read"),"full_presentation_permission_denied");
|
|
187
|
+
require(result?.taskSessionId===input.taskSessionId&&Buffer.byteLength(JSON.stringify(result))<=48000,"full_invalid_presentation_result");
|
|
188
|
+
return result;
|
|
189
|
+
}catch(error){
|
|
190
|
+
if(error?.code==="full_unauthorized")throw new FullContractError("full_presentation_permission_denied");
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
require(action==="job.output"&&exact(input,["taskSessionId","jobId","afterSeq"]),"full_invalid_presentation_input");
|
|
195
|
+
const result=await call("full.job.read",input,signal);
|
|
196
|
+
// Chunks are joined before redaction so common credentials split across
|
|
197
|
+
// adjacent chunks are still recognized. Never retain output in the broker.
|
|
198
|
+
const raw=(result.chunks??[]).map(c=>c.text??"").join("");
|
|
199
|
+
return {job:jobView(result.job),text:redactPresentationText(raw),nextSeq:result.nextSeq??0,hasMore:result.hasMore===true,truncated:result.truncated===true||raw.length>12000,outputAvailable:result.outputAvailable===true,redaction:"best-effort"};
|
|
200
|
+
}
|
|
201
|
+
return Object.freeze({snapshot,command,completed,forgetSession,scopeId,authorize:({signal}={})=>refreshAuthority(true,signal),get commands(){return commandAvailability();}});
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export async function createFullDesktopBroker({host,artifact,sessionDirectory,principal,dispatch,allowTerminal=false,authorizePrincipal,monitorSnapshot,monitorDetails,requestQuit,readChanges}){
|
|
205
|
+
require(host?.available&&artifact&&typeof artifact.executablePath==="string"&&path.isAbsolute(sessionDirectory),"full_invalid_presentation_configuration");
|
|
206
|
+
const root=path.resolve(path.dirname(artifact.executablePath),"../../../..");
|
|
207
|
+
const binary=path.join(root,"gui",process.platform==="win32"?"chat-relay-full-desktop.exe":"chat-relay-full-desktop");
|
|
208
|
+
const initialStat=await fs.lstat(binary);
|
|
209
|
+
require(initialStat.isFile()&&!initialStat.isSymbolicLink(),"full_invalid_gui_artifact");
|
|
210
|
+
async function binaryDigest(signal){
|
|
211
|
+
const stat=await fs.lstat(binary);
|
|
212
|
+
require(stat.isFile()&&!stat.isSymbolicLink()&&stat.size===initialStat.size&&
|
|
213
|
+
path.relative(root,await fs.realpath(binary))===path.relative(root,binary),"full_invalid_gui_artifact");
|
|
214
|
+
const digest=createHash("sha256");let bytes=0;
|
|
215
|
+
for await(const chunk of createReadStream(binary,{highWaterMark:65536,signal})){
|
|
216
|
+
bytes+=chunk.length;require(bytes<=initialStat.size,"full_invalid_gui_artifact");digest.update(chunk);
|
|
217
|
+
}
|
|
218
|
+
require(bytes===initialStat.size,"full_invalid_gui_artifact");
|
|
219
|
+
return digest.digest("hex");
|
|
220
|
+
}
|
|
221
|
+
// This initial binary came from the verified cache. A later explicit reopen
|
|
222
|
+
// must not execute replacement bytes without going through that loader.
|
|
223
|
+
const initialDigest=await binaryDigest();
|
|
224
|
+
const {createPresentationEndpoint}=await import(pathToFileURL(path.join(root,"packages/full-runtime/src/host/presentation.mjs")).href);
|
|
225
|
+
require(typeof authorizePrincipal==="function","full_presentation_permission_denied");
|
|
226
|
+
const service=createDesktopService({principal,dispatch,allowTerminal,authorizePrincipal,monitorSnapshot,monitorDetails,localMonitor:typeof monitorDetails==="function",requestQuit,readChanges});
|
|
227
|
+
const boundAccountId=principal.accountId;
|
|
228
|
+
const presentation=await createPresentationEndpoint({ownerEpoch:host.ownerEpoch,directory:path.join(sessionDirectory,"presentation"),snapshot:service.snapshot,command:service.command});
|
|
229
|
+
let child,closed=false,exitResult=null,state="closed",opening=null,openController=null,closing=null;
|
|
230
|
+
const alive=value=>value&&value.exitCode===null&&value.signalCode===null;
|
|
231
|
+
const stop=value=>{if(alive(value)&&!value.killed)value.kill();};
|
|
232
|
+
const environmentKeys=new Set(["path","systemroot","windir","home","userprofile","temp","tmp","tmpdir","appdata","localappdata","lang","lc_all","display","wayland_display","xdg_runtime_dir","dbus_session_bus_address"]);
|
|
233
|
+
const environment=Object.fromEntries(Object.entries(process.env).filter(([key])=>environmentKeys.has(key.toLowerCase())));
|
|
234
|
+
const {endpoint,token}=presentation.bootstrap;
|
|
235
|
+
async function open({accountId}={}){
|
|
236
|
+
require(accountId===boundAccountId,"full_presentation_permission_denied");
|
|
237
|
+
require(!closed&&host.available,"full_unavailable");
|
|
238
|
+
if(opening)return opening;
|
|
239
|
+
const controller=new AbortController(),signal=controller.signal;
|
|
240
|
+
openController=controller;
|
|
241
|
+
let launched=null,timer,onAbort;
|
|
242
|
+
const check=()=>{if(signal.aborted)throw signal.reason;require(!closed&&host.available,"full_unavailable");};
|
|
243
|
+
const execute=async()=>{
|
|
244
|
+
await service.authorize({signal});check();
|
|
245
|
+
if(alive(child)){presentation.publish({type:"activity.progress",requestId:randomUUID(),at:new Date().toISOString(),action:"presentation.open"});return {alreadyOpen:true};}
|
|
246
|
+
require(await binaryDigest(signal)===initialDigest,"full_invalid_gui_artifact");check();
|
|
247
|
+
state="starting";exitResult=null;
|
|
248
|
+
try{launched=spawn(binary,[],{windowsHide:false,stdio:"ignore",env:{...environment,RELAY_FULL_PRESENTATION_ENDPOINT:endpoint,RELAY_FULL_PRESENTATION_TOKEN:token,RELAY_FULL_PRESENTATION_EPOCH:host.ownerEpoch,RELAY_FULL_PRESENTATION_STATE:path.join(sessionDirectory,"gui-selection.json"),WEBVIEW2_USER_DATA_FOLDER:path.join(sessionDirectory,"webview")}});}
|
|
249
|
+
catch{state="unavailable";throw new FullContractError("full_gui_launch_failed");}
|
|
250
|
+
const current=launched;child=current;
|
|
251
|
+
current.once("exit",(code,signal)=>{if(child===current){state="closed";exitResult={code,signal};}});
|
|
252
|
+
current.on("error",()=>{if(!closed&&child===current)state="unavailable";});
|
|
253
|
+
await new Promise((resolve,reject)=>{
|
|
254
|
+
const done=()=>{current.removeListener("spawn",spawned);current.removeListener("error",failed);};
|
|
255
|
+
const spawned=()=>{done();resolve();};
|
|
256
|
+
const failed=()=>{done();reject(new FullContractError("full_gui_launch_failed"));};
|
|
257
|
+
current.once("spawn",spawned);current.once("error",failed);
|
|
258
|
+
});
|
|
259
|
+
check();require(alive(current),"full_gui_launch_failed");state="running";
|
|
260
|
+
return {alreadyOpen:false};
|
|
261
|
+
};
|
|
262
|
+
const cancelled=new Promise((_,reject)=>{
|
|
263
|
+
onAbort=()=>{stop(launched);reject(signal.reason);};
|
|
264
|
+
signal.addEventListener("abort",onAbort,{once:true});
|
|
265
|
+
timer=setTimeout(()=>controller.abort(new FullContractError("full_gui_open_timeout")),9000);
|
|
266
|
+
});
|
|
267
|
+
const pending=Promise.race([execute(),cancelled]);opening=pending;
|
|
268
|
+
try{return await pending;}
|
|
269
|
+
catch(error){stop(launched);throw error;}
|
|
270
|
+
finally{
|
|
271
|
+
clearTimeout(timer);signal.removeEventListener("abort",onAbort);
|
|
272
|
+
if(opening===pending){opening=null;openController=null;}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
function invalidate(event={}){
|
|
276
|
+
if(closed||event.accountId&&event.accountId!==boundAccountId)return;
|
|
277
|
+
presentation.publish({type:event.jobId?"job.changed":"activity.progress",requestId:randomUUID(),at:new Date().toISOString(),...(id(event.taskSessionId)?{taskSessionId:event.taskSessionId}:{}),...(id(event.jobId)?{jobId:event.jobId}:{})});
|
|
278
|
+
}
|
|
279
|
+
function close(){
|
|
280
|
+
if(closing)return closing;
|
|
281
|
+
closed=true;openController?.abort(new FullContractError("full_unavailable"));
|
|
282
|
+
closing=(async()=>{
|
|
283
|
+
await presentation.close();
|
|
284
|
+
// Only this exact GUI child is stopped. Core, the host and jobs retain
|
|
285
|
+
// their owners; closing a window never invokes this teardown path.
|
|
286
|
+
const current=child;
|
|
287
|
+
if(alive(current)){
|
|
288
|
+
stop(current);
|
|
289
|
+
await new Promise(resolve=>{
|
|
290
|
+
let timer;
|
|
291
|
+
const done=()=>{clearTimeout(timer);current.removeListener("exit",done);resolve();};
|
|
292
|
+
current.once("exit",done);timer=setTimeout(done,2000);timer.unref();
|
|
293
|
+
if(!alive(current))done();
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
state="closed";
|
|
297
|
+
})();
|
|
298
|
+
return closing;
|
|
299
|
+
}
|
|
300
|
+
try{await open({accountId:boundAccountId});}
|
|
301
|
+
catch(error){await close();throw error;}
|
|
302
|
+
return Object.freeze({
|
|
303
|
+
get status(){return {state,pid:child?.pid??null,exit:exitResult,scopeId:service.scopeId};},
|
|
304
|
+
completed(parsed,result){if(service.completed(parsed,result))invalidate({taskSessionId:parsed.input?.taskSessionId});},
|
|
305
|
+
forgetSession(owner){if(service.forgetSession(owner))invalidate(owner);},
|
|
306
|
+
invalidate,open,close
|
|
307
|
+
});
|
|
308
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { fork } from "node:child_process";
|
|
3
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
4
|
+
import { FULL_API_VERSION, FULL_LIMITS, validateControlFrame, FullContractError } from "../packages/full-contracts/index.mjs";
|
|
5
|
+
|
|
6
|
+
const hosts=new Map();
|
|
7
|
+
const MAX_PENDING=64;
|
|
8
|
+
const validId=v=>typeof v==="string"&&/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(v);
|
|
9
|
+
const capability=v=>typeof v==="string"&&/^full\.[a-z][a-z0-9.-]{0,95}$/.test(v);
|
|
10
|
+
const err=(code,message=code)=>new FullContractError(code,message);
|
|
11
|
+
function requireHost(ok,code){if(!ok)throw err(code);}
|
|
12
|
+
function childEnvironment() {
|
|
13
|
+
const allowed=new Set(["path","systemroot","windir","home","userprofile","temp","tmp","tmpdir","appdata","localappdata","lang","lc_all"]);
|
|
14
|
+
return Object.fromEntries(Object.entries(process.env).filter(([name])=>allowed.has(name.toLowerCase())));
|
|
15
|
+
}
|
|
16
|
+
function bounded(promise,ms,code) {
|
|
17
|
+
let timer;
|
|
18
|
+
return Promise.race([promise,new Promise((_,reject)=>{timer=setTimeout(()=>reject(err(code)),ms);})]).finally(()=>clearTimeout(timer));
|
|
19
|
+
}
|
|
20
|
+
function notify(callback,info){try{callback?.(info);}catch{}}
|
|
21
|
+
function sizeOkay(value){try{return Buffer.byteLength(JSON.stringify(value),"utf8")<=FULL_LIMITS.frameBytes;}catch{return false;}}
|
|
22
|
+
|
|
23
|
+
// The caller is the existing, authenticated Core runner, not an MCP tool or GUI.
|
|
24
|
+
// Resolver output is trusted input only after REL-45 verification. This does not
|
|
25
|
+
// create a cloud connection, and a second supervisor never starts another child
|
|
26
|
+
// for the same live runner. Cross-Core process ownership remains runner-ownership.
|
|
27
|
+
export async function startFullHost({optIn=false,artifact,coreRunnerId,headless=true,
|
|
28
|
+
configuration={},startupTimeoutMs=10000,onUnavailable}={}) {
|
|
29
|
+
if(!optIn)return {mode:"lite",available:false};
|
|
30
|
+
requireHost(validId(coreRunnerId)&&artifact&&/^[a-f0-9]{64}$/.test(artifact.artifactId)&&
|
|
31
|
+
typeof artifact.executablePath==="string"&&path.isAbsolute(artifact.executablePath)&&
|
|
32
|
+
Array.isArray(artifact.capabilities)&&artifact.capabilities.length<=FULL_LIMITS.capabilities&&artifact.capabilities.every(capability),"full_invalid_verified_artifact");
|
|
33
|
+
requireHost(Number.isInteger(startupTimeoutMs)&&startupTimeoutMs>=100&&startupTimeoutMs<=30000&&sizeOkay(configuration),"full_invalid_host_configuration");
|
|
34
|
+
const existing=hosts.get(coreRunnerId);
|
|
35
|
+
if(existing) {
|
|
36
|
+
requireHost(existing.artifactId===artifact.artifactId&&existing.headless===headless&&!existing.stopping&&!existing.failed,"full_owner_conflict");
|
|
37
|
+
return existing.ready;
|
|
38
|
+
}
|
|
39
|
+
const ownerEpoch=randomUUID(),nonce=randomBytes(32).toString("hex");
|
|
40
|
+
let resolveReady,rejectReady,resolveExit;
|
|
41
|
+
const ready=new Promise((resolve,reject)=>{resolveReady=resolve;rejectReady=reject;});
|
|
42
|
+
// Attach a rejection handler immediately; startup can fail before callers await.
|
|
43
|
+
ready.catch(()=>{});
|
|
44
|
+
const exited=new Promise(resolve=>{resolveExit=resolve;});
|
|
45
|
+
const state={artifactId:artifact.artifactId,headless,ready,stopping:false,available:false,exited:false,failed:false};
|
|
46
|
+
hosts.set(coreRunnerId,state);
|
|
47
|
+
let child,operations=new Map(),presentation=null,exitResult=null;
|
|
48
|
+
const pending=new Map();
|
|
49
|
+
function unavailable(reason) {
|
|
50
|
+
const wasAvailable=state.available;
|
|
51
|
+
state.available=false;state.failed=true;
|
|
52
|
+
rejectReady(err(reason));
|
|
53
|
+
const unresolved=[...pending.entries()].map(([requestId,value])=>({requestId,operation:value.operation,taskSessionId:value.taskSessionId}));
|
|
54
|
+
for(const [requestId,value] of pending){pending.delete(requestId);value.finish(err(value.waitForSettlement&&!state.exited?"full_settlement_unknown":"full_outcome_unknown"));}
|
|
55
|
+
if(wasAvailable||unresolved.length||state.exited)notify(onUnavailable,{ownerEpoch,reason,unresolved,confirmedChildExit:state.exited});
|
|
56
|
+
}
|
|
57
|
+
function finishExit(code,signal) {
|
|
58
|
+
if(state.exited)return;
|
|
59
|
+
state.exited=true;exitResult={code,signal,confirmed:true,ownerEpoch};
|
|
60
|
+
unavailable("full_host_exited");
|
|
61
|
+
if(hosts.get(coreRunnerId)===state)hosts.delete(coreRunnerId);
|
|
62
|
+
resolveExit(exitResult);
|
|
63
|
+
}
|
|
64
|
+
function send(message,callback=()=>{}){
|
|
65
|
+
if(!child?.connected){callback(err("full_unavailable"));return;}
|
|
66
|
+
try{child.send(message,callback);}catch(error){callback(error);}
|
|
67
|
+
}
|
|
68
|
+
async function dispose({timeoutMs=5000}={}) {
|
|
69
|
+
requireHost(Number.isInteger(timeoutMs)&&timeoutMs>=100&&timeoutMs<=30000,"full_invalid_timeout");
|
|
70
|
+
if(state.exited)return exitResult;
|
|
71
|
+
if(!state.stopping){state.stopping=true;state.available=false;send({kind:"full.stop",ownerEpoch});}
|
|
72
|
+
try{return await bounded(exited,timeoutMs,"full_stop_timeout");}
|
|
73
|
+
catch {
|
|
74
|
+
// Only our own child. Never infer that arbitrary native descendants stopped.
|
|
75
|
+
try{child.kill();}catch{}
|
|
76
|
+
try{return {...await bounded(exited,Math.min(timeoutMs,3000),"full_exit_unconfirmed"),forced:true};}
|
|
77
|
+
catch{unavailable("full_exit_unconfirmed");return {confirmed:false,ownerEpoch,reason:"full_exit_unconfirmed"};}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function request(operation,payload={},options={}) {
|
|
81
|
+
if(!state.available||state.stopping)return Promise.reject(err("full_unavailable"));
|
|
82
|
+
if(!operations.has(operation))return Promise.reject(err("full_capability_unavailable"));
|
|
83
|
+
if(pending.size>=MAX_PENDING)return Promise.reject(err("full_control_queue_full"));
|
|
84
|
+
const requestId=randomUUID(),timeoutMs=options.timeoutMs??FULL_LIMITS.controlTimeoutMs;
|
|
85
|
+
const frame={apiVersion:FULL_API_VERSION,ownerEpoch,kind:"request",requestId,operation,timeoutMs,payload,
|
|
86
|
+
...(options.taskSessionId!==undefined?{taskSessionId:options.taskSessionId}:{})};
|
|
87
|
+
try{validateControlFrame(frame);}catch(error){return Promise.reject(error);}
|
|
88
|
+
if(options.signal?.aborted)return Promise.reject(err("full_cancelled_before_send"));
|
|
89
|
+
return new Promise((resolve,reject)=>{
|
|
90
|
+
let timer,cancelling=false;
|
|
91
|
+
function cleanup(){clearTimeout(timer);options.signal?.removeEventListener("abort",cancel);pending.delete(requestId);}
|
|
92
|
+
function finish(error,result){cleanup();if(error)reject(error);else resolve(result);}
|
|
93
|
+
function cancel(){
|
|
94
|
+
// Cancellation is a request; not authoritative process completion.
|
|
95
|
+
if(cancelling)return;
|
|
96
|
+
cancelling=true;
|
|
97
|
+
send({apiVersion:FULL_API_VERSION,ownerEpoch,kind:"cancel",requestId:randomUUID(),targetRequestId:requestId});
|
|
98
|
+
if(options.waitForSettlement===true){clearTimeout(timer);timer=setTimeout(()=>finish(err("full_settlement_unknown")),5000);}
|
|
99
|
+
else finish(err("full_outcome_unknown"));
|
|
100
|
+
}
|
|
101
|
+
pending.set(requestId,{finish,operation,taskSessionId:options.taskSessionId,waitForSettlement:options.waitForSettlement===true});
|
|
102
|
+
timer=setTimeout(cancel,timeoutMs);
|
|
103
|
+
options.signal?.addEventListener("abort",cancel,{once:true});
|
|
104
|
+
send(frame,error=>{if(error&&pending.has(requestId))finish(err(options.waitForSettlement===true?"full_settlement_unknown":"full_outcome_unknown"));});
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
const api=Object.freeze({mode:"full",ownerEpoch,coreRunnerId,artifactId:artifact.artifactId,headless,
|
|
108
|
+
get available(){return state.available&&!state.stopping;},
|
|
109
|
+
get processId(){return state.exited?null:child?.pid??null;},
|
|
110
|
+
get operations(){return [...operations.keys()];},
|
|
111
|
+
// Credential is private bootstrap material. Do not log, serialize to MCP or
|
|
112
|
+
// pass on the command line; REL-51/60 deliver it to the native shell privately.
|
|
113
|
+
getPresentationBootstrap(){return presentation?{...presentation}:null;},
|
|
114
|
+
request,dispose,exited});
|
|
115
|
+
try {
|
|
116
|
+
child=fork(artifact.executablePath,[],{execArgv:[],env:childEnvironment(),stdio:["ignore","ignore","ignore","ipc"],serialization:"json",windowsHide:true});
|
|
117
|
+
child.once("error",()=>{unavailable("full_spawn_failed");if(!child.pid)finishExit(null,null);});
|
|
118
|
+
child.once("exit",finishExit);
|
|
119
|
+
child.once("disconnect",()=>unavailable("full_ipc_disconnected"));
|
|
120
|
+
child.on("message",message=>{
|
|
121
|
+
if(!message||typeof message!=="object"||message.ownerEpoch!==ownerEpoch||!sizeOkay(message))return;
|
|
122
|
+
if(message.kind==="full.ready"&&!state.available&&!state.stopping){
|
|
123
|
+
try {
|
|
124
|
+
requireHost(message.nonce===nonce&&message.apiVersion===FULL_API_VERSION&&Array.isArray(message.operations)&&message.operations.length<=FULL_LIMITS.capabilities,"full_handshake_failed");
|
|
125
|
+
const selected=new Map();
|
|
126
|
+
for(const op of message.operations){
|
|
127
|
+
requireHost(capability(op?.operation)&&capability(op?.capability)&&artifact.capabilities.includes(op.capability)&&!selected.has(op.operation),"full_handshake_failed");
|
|
128
|
+
selected.set(op.operation,op.capability);
|
|
129
|
+
}
|
|
130
|
+
operations=selected;
|
|
131
|
+
presentation=message.presentation??null;
|
|
132
|
+
if(headless)requireHost(presentation===null,"full_unexpected_gui_endpoint");
|
|
133
|
+
state.available=true;resolveReady(api);
|
|
134
|
+
}catch(error){rejectReady(error);}
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if(message.kind!=="response")return;
|
|
138
|
+
try{validateControlFrame(message);}catch{return;}
|
|
139
|
+
const entry=pending.get(message.requestId);
|
|
140
|
+
if(!entry)return; // stale, cancelled or duplicate response
|
|
141
|
+
entry.finish(message.ok?null:err(message.error),message.payload);
|
|
142
|
+
});
|
|
143
|
+
const bootstrap={kind:"full.bootstrap",apiVersion:FULL_API_VERSION,ownerEpoch,nonce,coreRunnerId,headless,
|
|
144
|
+
allowedCapabilities:artifact.capabilities,configuration};
|
|
145
|
+
requireHost(sizeOkay(bootstrap),"full_invalid_host_configuration");
|
|
146
|
+
send(bootstrap,error=>{if(error)rejectReady(err("full_bootstrap_failed"));});
|
|
147
|
+
return await bounded(ready,startupTimeoutMs,"full_startup_timeout");
|
|
148
|
+
}catch(error){
|
|
149
|
+
if(child)await dispose({timeoutMs:2000});
|
|
150
|
+
else {hosts.delete(coreRunnerId);resolveExit({confirmed:true,ownerEpoch});}
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
}
|