@anusornneal/chat-relay 1.9.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/agent/activity-capture.mjs +218 -0
- package/agent/auto-session-binding.mjs +46 -0
- package/agent/capability-scheduler.mjs +82 -5
- package/agent/file-manager.mjs +33 -8
- 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 +318 -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 +171 -4
- package/agent/lifecycle.mjs +11 -0
- package/agent/local-agent.mjs +177 -24
- package/agent/local-usage.mjs +21 -0
- package/agent/monitor-activity.mjs +135 -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 +27 -1
- package/agent/toolcall-summary.mjs +1 -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 +76 -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 +9 -5
- 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 +173 -18
- 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/auto-session.mjs +14 -0
- package/packages/full-contracts/index.mjs +193 -0
- package/packages/full-contracts/monitor-metadata.mjs +28 -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,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
|
+
}
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
import {createHash,randomUUID} from "node:crypto";
|
|
2
|
+
import {performance} from "node:perf_hooks";
|
|
3
|
+
import {FullContractError,jobIsSettled} from "../packages/full-contracts/index.mjs";
|
|
4
|
+
import {JOB_BROKER_OPERATION,RESOURCE_HEALTH_OPERATION} from "../packages/full-contracts/remote-session.mjs";
|
|
5
|
+
import {createNativeJobProvider,verificationEnvironment} from "./full-native-job.mjs";
|
|
6
|
+
import {validateCommand} from "./terminal-manager.mjs";
|
|
7
|
+
|
|
8
|
+
export const AGENT_EFFECT_KEY="effects:agent";
|
|
9
|
+
// Survives a Full-host restart inside the same Core. This is not a second
|
|
10
|
+
// scheduler: it retains only the exact leases already granted by Core.
|
|
11
|
+
const retainedLeases=new WeakMap();
|
|
12
|
+
const fail=code=>new FullContractError(code);
|
|
13
|
+
const check=(v,code)=>{if(!v)throw fail(code);};
|
|
14
|
+
const hash=v=>createHash("sha256").update(JSON.stringify(v)).digest("hex");
|
|
15
|
+
const publicJob=job=>{const {requestFingerprint,verification,recovery,...result}=job;return {...result,...(verification?{verification:{checkId:verification.check.checkId,revision:verification.revision,observationState:verification.observationState}}:{})};};
|
|
16
|
+
const unknown=error=>["full_outcome_unknown","full_settlement_unknown","full_unavailable"].includes(error?.code);
|
|
17
|
+
const sameOwner=(a,b)=>a.accountId===b.accountId&&a.agentId===b.agentId&&a.taskSessionId===b.taskSessionId;
|
|
18
|
+
const waitBounded=async(promise,ms)=>{
|
|
19
|
+
let timer;
|
|
20
|
+
try{return await Promise.race([promise,new Promise(resolve=>{timer=setTimeout(()=>resolve(false),ms);})]);}
|
|
21
|
+
finally{clearTimeout(timer);}
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** Core owns native process handles and the existing admission lane. The host
|
|
25
|
+
* atomically journals the job + claims before launch and outcome + release
|
|
26
|
+
* only after a trusted tree-empty observation. Never replay an unknown launch. */
|
|
27
|
+
export async function createRemoteJobBroker({host,artifact,scheduler,terminalEnabled,workspaceFor,verifyWorkspace,canonicalKey,legacyBusy=()=>false,recoveryDirectory,onJobChanged}){
|
|
28
|
+
if(!terminalEnabled||!host.operations.includes(JOB_BROKER_OPERATION))return null;
|
|
29
|
+
const native=await createNativeJobProvider({artifact,recoveryDirectory:artifact.capabilities.includes("full.jobs.recovery")?recoveryDirectory:undefined});
|
|
30
|
+
if(!native)return null;
|
|
31
|
+
const admission=scheduler.fullAdmission,active=new Map(),attempts=new Map(),starts=new Map(),retained=new Map();
|
|
32
|
+
const waitEnabled=artifact.capabilities.includes("full.jobs.wait");
|
|
33
|
+
const held=retainedLeases.get(scheduler)??new Map();retainedLeases.set(scheduler,held);
|
|
34
|
+
let closing=false,stuck=false;
|
|
35
|
+
const changed=entry=>{try{onJobChanged?.({accountId:entry.owner.accountId,taskSessionId:entry.owner.taskSessionId,jobId:entry.jobId});}catch{}};
|
|
36
|
+
const scope=(principal,taskSessionId)=>({accountId:principal.accountId,agentId:principal.agentId,taskSessionId});
|
|
37
|
+
const rpc=(invocation,kind,jobId,fields={})=>host.request(JOB_BROKER_OPERATION,{invocation,kind,jobId,...fields},{taskSessionId:invocation.input.taskSessionId,timeoutMs:invocation.input.verificationCheckId?16000:8000,waitForSettlement:true});
|
|
38
|
+
function prune(){
|
|
39
|
+
for(const [id,value] of retained)if(Date.now()>=value.until)retained.delete(id);
|
|
40
|
+
while(retained.size>16)retained.delete(retained.keys().next().value);
|
|
41
|
+
}
|
|
42
|
+
function released(entry){
|
|
43
|
+
active.delete(entry.jobId);attempts.delete(entry.attemptId);held.delete(entry.attemptId);
|
|
44
|
+
if(entry.recovery)native.discard?.(entry.recovery).catch(()=>{});
|
|
45
|
+
if(entry.native)retained.set(entry.jobId,{owner:entry.owner,attemptId:entry.attemptId,ownerEpoch:entry.ownerEpoch,job:entry.job,native:entry.native,until:Date.now()+15*60*1000});
|
|
46
|
+
prune();
|
|
47
|
+
}
|
|
48
|
+
const matches=(entry,job,owner)=>entry&&sameOwner(entry.owner,owner)&&entry.attemptId===job.attemptId&&entry.ownerEpoch===job.ownerEpoch;
|
|
49
|
+
function outputFor(job,owner,afterSeq=0){
|
|
50
|
+
prune();const output=active.get(job.jobId)??retained.get(job.jobId);
|
|
51
|
+
return {job:publicJob(job),...(output?.native&&matches(output,job,owner)?{outputAvailable:true,...output.native.read(afterSeq)}:{outputAvailable:false,chunks:[],nextSeq:0})};
|
|
52
|
+
}
|
|
53
|
+
async function waitForCompletion(entry,ms){
|
|
54
|
+
if(!entry.done||entry.doneObserved||closing||ms===0)return;
|
|
55
|
+
// One native/durable completion subscription per job. Timed-out requests
|
|
56
|
+
// remove their waiter, so repeated bounded reads cannot retain closures
|
|
57
|
+
// for the lifetime of a long-running process.
|
|
58
|
+
if(!entry.waiters){
|
|
59
|
+
entry.waiters=new Set();
|
|
60
|
+
entry.done.then(()=>{
|
|
61
|
+
entry.doneObserved=true;
|
|
62
|
+
for(const resolve of entry.waiters)resolve();
|
|
63
|
+
entry.waiters.clear();
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
let timer,notify;
|
|
67
|
+
try{
|
|
68
|
+
await new Promise(resolve=>{
|
|
69
|
+
notify=resolve;entry.waiters.add(notify);
|
|
70
|
+
timer=setTimeout(resolve,ms);
|
|
71
|
+
});
|
|
72
|
+
}finally{clearTimeout(timer);entry.waiters.delete(notify);}
|
|
73
|
+
}
|
|
74
|
+
async function waitAndRead(job,owner,waitMs,afterSeq=0){
|
|
75
|
+
const entry=active.get(job.jobId);
|
|
76
|
+
if(matches(entry,job,owner)){
|
|
77
|
+
await waitForCompletion(entry,waitMs);
|
|
78
|
+
// A lookup can be newer than the local entry after a lost finish ACK.
|
|
79
|
+
// Never replace a newer durable observation with older local state.
|
|
80
|
+
if(entry.job.lastSequence>=job.lastSequence)job=entry.job;
|
|
81
|
+
}
|
|
82
|
+
const completed=retained.get(job.jobId);
|
|
83
|
+
if(matches(completed,job,owner)&&completed.job.lastSequence>=job.lastSequence)job=completed.job;
|
|
84
|
+
const liveOwner=!!matches(active.get(job.jobId),job,owner);
|
|
85
|
+
const heldClaim=matches(held.get(job.attemptId),job,owner);
|
|
86
|
+
return {...outputFor(job,owner,afterSeq),settled:jobIsSettled(job)&&!liveOwner&&!heldClaim,liveOwner};
|
|
87
|
+
}
|
|
88
|
+
function sequence(entry,state,fields={}){
|
|
89
|
+
return {jobId:entry.jobId,attemptId:entry.attemptId,ownerEpoch:host.ownerEpoch,sequence:entry.job.lastSequence+1,state,...fields};
|
|
90
|
+
}
|
|
91
|
+
function serial(entry,work){
|
|
92
|
+
const result=entry.tail.then(work);entry.tail=result.catch(()=>{});return result;
|
|
93
|
+
}
|
|
94
|
+
async function refresh(entry){
|
|
95
|
+
const job=await rpc(entry.invocation,"lookup",entry.jobId);
|
|
96
|
+
check(job&&job.attemptId===entry.attemptId&&job.ownerEpoch===host.ownerEpoch,"full_job_owner_mismatch");
|
|
97
|
+
entry.job=job;return job;
|
|
98
|
+
}
|
|
99
|
+
async function update(entry,state,invocation=entry.invocation){
|
|
100
|
+
const result=await rpc(invocation,"event",entry.jobId,{event:sequence(entry,state)});
|
|
101
|
+
check(result.acknowledged&&result.applied,"full_job_event_unsaved");
|
|
102
|
+
entry.job=result.job;changed(entry);return result.job;
|
|
103
|
+
}
|
|
104
|
+
admission.proveStopped=async observation=>{
|
|
105
|
+
const entry=held.get(observation.attemptId);
|
|
106
|
+
if(!entry||entry.jobId!==observation.jobId||!sameOwner(entry.owner,observation.owner)||!entry.proof?.treeStopped)return null;
|
|
107
|
+
return {...entry.proof,jobId:entry.jobId,attemptId:entry.attemptId,ownerEpoch:entry.ownerEpoch};
|
|
108
|
+
};
|
|
109
|
+
admission.commitRelease=async({owner,claims})=>{
|
|
110
|
+
const entry=held.get(claims[0]?.attemptId);
|
|
111
|
+
if(!entry||!sameOwner(entry.owner,owner)||!entry.proof?.treeStopped||claims.some(c=>c.attemptId!==entry.attemptId||c.ownerEpoch!==entry.ownerEpoch))return false;
|
|
112
|
+
if(entry.durablyRecovered===true)return true;
|
|
113
|
+
if(entry.ownerEpoch!==host.ownerEpoch)return false;
|
|
114
|
+
// Read the authoritative sequence after a lost event ACK. This is not a
|
|
115
|
+
// replay of the command, only observation of the durable journal.
|
|
116
|
+
await refresh(entry);
|
|
117
|
+
const reason=entry.proof.reason;
|
|
118
|
+
const event=reason==="exited"?sequence(entry,"exited",{exitCode:entry.proof.exitCode}):
|
|
119
|
+
reason==="outcome-unknown"?sequence(entry,"outcome-unknown",{stopConfirmed:true}):sequence(entry,"cancelled",{stopConfirmed:true,stopReason:reason});
|
|
120
|
+
// Containment is already proved; an unavailable/revoked workspace
|
|
121
|
+
// observation cannot turn a stopped process into an unresolved one.
|
|
122
|
+
let verifiedRoot=null;
|
|
123
|
+
if(entry.job.verification&&!entry.knownAbsent&&reason!=="outcome-unknown"){
|
|
124
|
+
try{
|
|
125
|
+
const parsed={input:entry.invocation.input,principal:entry.invocation.principal,operation:entry.invocation.operation};
|
|
126
|
+
const binding=await workspaceFor(entry.invocation,parsed);
|
|
127
|
+
const root=await verifyWorkspace(binding);
|
|
128
|
+
if(root===entry.root)verifiedRoot=root;
|
|
129
|
+
}catch{}
|
|
130
|
+
}
|
|
131
|
+
const result=await rpc(entry.invocation,"finish",entry.jobId,{event,verifiedRoot,environment:verificationEnvironment(artifact.artifactId)});
|
|
132
|
+
if(!result.acknowledged||!result.released)return false;
|
|
133
|
+
entry.job=result.job;changed(entry);return true;
|
|
134
|
+
};
|
|
135
|
+
async function markUnknown(entry){
|
|
136
|
+
entry.lease.quarantine();entry.recoveryRequired=true;
|
|
137
|
+
try{
|
|
138
|
+
await refresh(entry);
|
|
139
|
+
if(!["exited","cancelled","outcome-unknown"].includes(entry.job.state)){
|
|
140
|
+
const result=await rpc(entry.invocation,"finish",entry.jobId,{event:sequence(entry,"outcome-unknown")});
|
|
141
|
+
entry.job=result.job;changed(entry);
|
|
142
|
+
}
|
|
143
|
+
}catch{}
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
async function settle(entry,proof){
|
|
147
|
+
entry.proof=proof;
|
|
148
|
+
if(!proof.treeStopped)return markUnknown(entry);
|
|
149
|
+
if(!entry.knownAbsent)entry.lease.rootExited();
|
|
150
|
+
const result=await admission.reconcile(entry.lease.id);
|
|
151
|
+
if(!result.released)return false;
|
|
152
|
+
released(entry);return true;
|
|
153
|
+
}
|
|
154
|
+
function observe(entry){
|
|
155
|
+
const ready=entry.native.ready.then(identity=>{
|
|
156
|
+
entry.lease.recordProcess(identity);
|
|
157
|
+
return serial(entry,async()=>{
|
|
158
|
+
if(entry.job.state==="accepted")await update(entry,"running");
|
|
159
|
+
});
|
|
160
|
+
}).catch(error=>{entry.native.cancel();throw error;});
|
|
161
|
+
ready.catch(()=>{});
|
|
162
|
+
entry.done=(async()=>{
|
|
163
|
+
const result=await entry.native.completion;
|
|
164
|
+
await ready.catch(()=>{});
|
|
165
|
+
return serial(entry,()=>settle(entry,result));
|
|
166
|
+
})().catch(()=>{entry.lease.quarantine();return false;});
|
|
167
|
+
return ready;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async function refreshRecoveryGate(){
|
|
171
|
+
const health=await host.request(RESOURCE_HEALTH_OPERATION,{},{timeoutMs:1000});
|
|
172
|
+
check(Number.isSafeInteger(health?.unresolved)&&health.unresolved>=0,"full_recovery_state_unknown");
|
|
173
|
+
admission.setRecoveryBlocked(health.unresolved>0||[...held.values()].some(e=>e.ownerEpoch!==host.ownerEpoch||e.recoveryRequired));
|
|
174
|
+
}
|
|
175
|
+
async function releaseRecovered(entry,proof,job){
|
|
176
|
+
entry.proof={...proof,identity:entry.lease.snapshot().process,containment:entry.recovery};
|
|
177
|
+
entry.job=job??entry.job;entry.durablyRecovered=true;entry.recoveryRequired=false;
|
|
178
|
+
entry.lease.quarantine();
|
|
179
|
+
const result=await admission.reconcile(entry.lease.id);
|
|
180
|
+
if(result.released){entry.releaseLocal();changed(entry);}
|
|
181
|
+
return result.released;
|
|
182
|
+
}
|
|
183
|
+
async function recoverRecord(record){
|
|
184
|
+
if(!native.recover||!record.recovery)return {released:false};
|
|
185
|
+
const entry=held.get(record.attemptId);
|
|
186
|
+
if(entry)check(entry.jobId===record.jobId&&entry.ownerEpoch===record.ownerEpoch&&sameOwner(entry.owner,record),"full_job_owner_mismatch");
|
|
187
|
+
const work=async()=>{
|
|
188
|
+
const proof=await native.recover(record.recovery);
|
|
189
|
+
if(!proof.treeStopped)return {released:false};
|
|
190
|
+
const saved=await host.request(JOB_BROKER_OPERATION,{kind:"recover",taskSessionId:record.taskSessionId,jobId:record.jobId,attemptId:record.attemptId,previousOwnerEpoch:record.ownerEpoch,proof},{taskSessionId:record.taskSessionId,timeoutMs:8000});
|
|
191
|
+
check(saved.acknowledged&&saved.released,"full_job_event_unsaved");
|
|
192
|
+
if(entry){
|
|
193
|
+
const released=await releaseRecovered(entry,proof,saved.job);
|
|
194
|
+
return {released,job:saved.job};
|
|
195
|
+
}
|
|
196
|
+
await native.discard?.(record.recovery);
|
|
197
|
+
changed({owner:record,jobId:record.jobId});return {released:true,job:saved.job};
|
|
198
|
+
};
|
|
199
|
+
return entry?serial(entry,work):work();
|
|
200
|
+
}
|
|
201
|
+
async function recoverStartup(){
|
|
202
|
+
if(!native.recover)return;
|
|
203
|
+
// Stop scheduling work after five seconds. A last already-started native
|
|
204
|
+
// observation/store commit may take up to 5s+8s, then one 1s health read.
|
|
205
|
+
// Remaining work stays fenced and uses explicit per-job reconciliation.
|
|
206
|
+
const deadline=performance.now()+5000;
|
|
207
|
+
admission.setRecoveryBlocked(true);
|
|
208
|
+
let after="",pages=0;
|
|
209
|
+
do{
|
|
210
|
+
if(performance.now()>=deadline)break;
|
|
211
|
+
const page=await host.request(JOB_BROKER_OPERATION,{kind:"recovery-list",after},{timeoutMs:8000});
|
|
212
|
+
check(Array.isArray(page?.items)&&page.items.length<=32,"full_recovery_state_unknown");
|
|
213
|
+
for(const record of page.items){if(performance.now()>=deadline)break;await recoverRecord(record);}
|
|
214
|
+
after=page.next;
|
|
215
|
+
}while(after&&++pages<8);
|
|
216
|
+
for(const entry of [...held.values()]){
|
|
217
|
+
if(performance.now()>=deadline)break;
|
|
218
|
+
if(entry.ownerEpoch===host.ownerEpoch)continue;
|
|
219
|
+
// A lost reservation/finalization ACK may correspond to no durable job
|
|
220
|
+
// or an already committed terminal job. Observe it; never replay launch.
|
|
221
|
+
const job=await host.request(JOB_BROKER_OPERATION,{invocation:entry.invocation,kind:"lookup",jobId:entry.jobId},{taskSessionId:entry.owner.taskSessionId,timeoutMs:8000});
|
|
222
|
+
if(job&&(!jobIsSettled(job)||job.attemptId!==entry.attemptId||job.ownerEpoch!==entry.ownerEpoch))continue;
|
|
223
|
+
if(!job&&!entry.knownAbsent)continue;
|
|
224
|
+
if(performance.now()>=deadline)break;
|
|
225
|
+
await serial(entry,async()=>{
|
|
226
|
+
const proof=await native.recover(entry.recovery);
|
|
227
|
+
if(proof.treeStopped)await releaseRecovered(entry,proof,job);
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
await refreshRecoveryGate();
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function start(invocation,parsed,jobId,requestFingerprint){
|
|
234
|
+
const {principal,input}=parsed;
|
|
235
|
+
validateCommand(input.command);
|
|
236
|
+
const old=await rpc(invocation,"lookup",jobId);
|
|
237
|
+
if(old){check(old.requestFingerprint===requestFingerprint,"full_idempotency_conflict");return {disposition:"retry",job:old};}
|
|
238
|
+
check(!closing&&!admission.recoveryBlocked,"full_recovery_blocked");
|
|
239
|
+
const binding=await workspaceFor(invocation,parsed);
|
|
240
|
+
check(["git","artifact"].includes(binding?.workspaceKind)&&binding.state==="ready","full_workspace_not_ready");
|
|
241
|
+
check(!input.verificationCheckId||binding.workspaceKind==="git","full_verification_code_workspace_required");
|
|
242
|
+
// Arbitrary terminal grants are not a filesystem sandbox. Serialize them
|
|
243
|
+
// against all Full workspace effects, including disjoint owned directories.
|
|
244
|
+
const claims=[{key:AGENT_EFFECT_KEY,mode:"exclusive"},{key:"workspace:"+binding.workspaceId,mode:"write"},
|
|
245
|
+
...(binding.workspaceKind==="git"?[{key:"git:"+await canonicalKey(binding.primaryRootRef),mode:"exclusive"}]:[]),
|
|
246
|
+
{key:await canonicalKey(binding.rootRef),mode:"write"}];
|
|
247
|
+
const owner=scope(principal,input.taskSessionId),attemptId=randomUUID();
|
|
248
|
+
return scheduler.runFull("terminal.start",async(_meta,lease)=>{
|
|
249
|
+
check(!closing&&!legacyBusy(),"full_legacy_effect_active");
|
|
250
|
+
const current=await workspaceFor(invocation,parsed);
|
|
251
|
+
check(current?.workspaceId===binding.workspaceId&¤t.rootRef===binding.rootRef,"full_workspace_conflict");
|
|
252
|
+
const root=await verifyWorkspace(current);
|
|
253
|
+
check(!closing&&!legacyBusy(),"full_legacy_effect_active");
|
|
254
|
+
const recovery=native.prepare?await native.prepare():undefined;
|
|
255
|
+
let saved;
|
|
256
|
+
try{
|
|
257
|
+
saved=await rpc(invocation,"reserve",jobId,{workspaceId:binding.workspaceId,attemptId,requestFingerprint,claims:lease.snapshot().claims,...(recovery?{recovery}:{}),...(input.verificationCheckId?{verifiedRoot:root,environment:verificationEnvironment(artifact.artifactId)}:{})});
|
|
258
|
+
}catch(error){
|
|
259
|
+
// A transport loss can hide a committed reservation. No process is
|
|
260
|
+
// launched; do not give away the possibly durable claim.
|
|
261
|
+
if(unknown(error)){
|
|
262
|
+
lease.retain(jobId);if(recovery)lease.recordContainment(recovery);lease.spawnFailed();stuck=true;
|
|
263
|
+
const entry={owner,attemptId,ownerEpoch:host.ownerEpoch,jobId,invocation,lease,root,recovery,job:null,native:null,proof:null,tail:Promise.resolve(),knownAbsent:true,recoveryRequired:true};
|
|
264
|
+
entry.releaseLocal=()=>{held.delete(attemptId);stuck=false;if(recovery)native.discard?.(recovery).catch(()=>{});};held.set(attemptId,entry);
|
|
265
|
+
}else if(recovery)await native.discard?.(recovery);
|
|
266
|
+
throw error;
|
|
267
|
+
}
|
|
268
|
+
check(saved.acknowledged===true,"full_job_intent_unsaved");
|
|
269
|
+
if(saved.disposition==="retry"){if(recovery)await native.discard?.(recovery);return {disposition:"retry",job:saved.job};}
|
|
270
|
+
lease.retain(jobId);
|
|
271
|
+
if(recovery)lease.recordContainment(recovery);
|
|
272
|
+
const entry={owner,attemptId,ownerEpoch:host.ownerEpoch,jobId,invocation,lease,root,recovery,job:saved.job,native:null,proof:null,tail:Promise.resolve(),done:null,knownAbsent:false};
|
|
273
|
+
entry.releaseLocal=()=>released(entry);held.set(attemptId,entry);changed(entry);
|
|
274
|
+
active.set(jobId,entry);attempts.set(attemptId,entry);
|
|
275
|
+
try{
|
|
276
|
+
if(closing)throw fail("full_cancelled_before_start");
|
|
277
|
+
entry.native=await native.launch(input.command,root,input.timeoutMs,recovery);
|
|
278
|
+
}catch(error){
|
|
279
|
+
// A synchronous pre-launch failure means no child handle was created.
|
|
280
|
+
entry.knownAbsent=true;lease.spawnFailed();
|
|
281
|
+
entry.done=serial(entry,()=>settle(entry,{treeStopped:true,reason:"cancelled"})).catch(()=>false);
|
|
282
|
+
await entry.done;throw error;
|
|
283
|
+
}
|
|
284
|
+
await observe(entry);
|
|
285
|
+
return {disposition:"accepted",job:entry.job,containment:native.containment,scope:"bound-cwd-not-sandbox"};
|
|
286
|
+
},{owner,ownerEpoch:host.ownerEpoch,attemptId,claims,priority:"task",dependenciesReady:true});
|
|
287
|
+
}
|
|
288
|
+
async function dispatch(invocation,parsed){
|
|
289
|
+
const {principal,input,operation}=parsed;
|
|
290
|
+
const owner=scope(principal,input.taskSessionId);
|
|
291
|
+
check(input.waitMs===undefined||waitEnabled,"full_capability_unavailable");
|
|
292
|
+
if(operation==="full.job.start"){
|
|
293
|
+
const jobId="job-"+hash([owner.accountId,owner.agentId,owner.taskSessionId,input.idempotencyKey]).slice(0,48);
|
|
294
|
+
const fingerprint=hash([input.command,input.timeoutMs,...(input.verificationCheckId?[input.verificationCheckId]:[])]);
|
|
295
|
+
const existing=starts.get(jobId);
|
|
296
|
+
let result;
|
|
297
|
+
if(existing){
|
|
298
|
+
check(existing.fingerprint===fingerprint,"full_idempotency_conflict");
|
|
299
|
+
result=await existing.promise;
|
|
300
|
+
}else{
|
|
301
|
+
const promise=Promise.resolve().then(()=>start(invocation,parsed,jobId,fingerprint));
|
|
302
|
+
starts.set(jobId,{owner,fingerprint,promise});
|
|
303
|
+
try{result=await promise;}finally{starts.delete(jobId);}
|
|
304
|
+
}
|
|
305
|
+
// Share acceptance only. Each idempotent caller chooses its own bounded
|
|
306
|
+
// observation without delaying a concurrent caller that did not opt in.
|
|
307
|
+
return input.waitMs===undefined?{...result,job:publicJob(result.job)}:{...result,...await waitAndRead(result.job,owner,input.waitMs)};
|
|
308
|
+
}
|
|
309
|
+
const job=await rpc(invocation,"lookup",input.jobId);
|
|
310
|
+
check(job,"full_unauthorized");
|
|
311
|
+
const entry=active.get(input.jobId);
|
|
312
|
+
if(operation==="full.job.status")return {job:publicJob(job),liveOwner:!!entry&&sameOwner(entry.owner,owner)};
|
|
313
|
+
if(operation==="full.job.read"){
|
|
314
|
+
return input.waitMs===undefined?outputFor(job,owner,input.afterSeq??0):waitAndRead(job,owner,input.waitMs,input.afterSeq??0);
|
|
315
|
+
}
|
|
316
|
+
if(operation==="full.job.reconcile"){
|
|
317
|
+
if(!entry&&job.requestFingerprint&&jobIsSettled(job))return {released:true,job:publicJob(job)};
|
|
318
|
+
if(native.recover&&job.recovery&&(!entry||!entry.proof?.treeStopped)){
|
|
319
|
+
const result=await recoverRecord({...owner,jobId:job.jobId,attemptId:job.attemptId,ownerEpoch:job.ownerEpoch,recovery:job.recovery});
|
|
320
|
+
if(result.released){await refreshRecoveryGate();return {released:true,job:publicJob(result.job)};}
|
|
321
|
+
}
|
|
322
|
+
if(!entry){check(job.requestFingerprint&&jobIsSettled(job),"full_job_reconciliation_required");return {released:true,job:publicJob(job)};}
|
|
323
|
+
check(sameOwner(entry.owner,owner)&&entry.proof?.treeStopped,"full_job_reconciliation_required");
|
|
324
|
+
return serial(entry,async()=>{
|
|
325
|
+
if(!active.has(entry.jobId))return {released:true,job:publicJob(entry.job)};
|
|
326
|
+
const result=await admission.reconcile(entry.lease.id);
|
|
327
|
+
if(result.released)released(entry);
|
|
328
|
+
return {released:result.released,job:publicJob(entry.job),reason:result.reason};
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
check(operation==="full.job.cancel","full_capability_unavailable");
|
|
332
|
+
if(jobIsSettled(job))return {job:publicJob(job),requested:false};
|
|
333
|
+
check(entry?.native&&sameOwner(entry.owner,owner),"full_job_reconciliation_required");
|
|
334
|
+
return serial(entry,async()=>{
|
|
335
|
+
if(jobIsSettled(entry.job))return {job:publicJob(entry.job),requested:false};
|
|
336
|
+
try{if(entry.job.state!=="cancel-requested"&&entry.job.state!=="outcome-unknown")await update(entry,"cancel-requested",invocation);}
|
|
337
|
+
finally{entry.native.cancel();}
|
|
338
|
+
return {job:publicJob(entry.job),requested:true,stopConfirmed:false};
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
async function close(){
|
|
342
|
+
closing=true;
|
|
343
|
+
for(const entry of active.values())entry.native?.cancel();
|
|
344
|
+
const pending=()=>Promise.allSettled([...starts.values()].map(s=>s.promise).concat([...active.values()].map(e=>e.done).filter(Boolean))).then(()=>true);
|
|
345
|
+
await waitBounded(pending(),6000);
|
|
346
|
+
for(const entry of active.values())if(entry.native&&!entry.native.settled)entry.native.force();
|
|
347
|
+
await waitBounded(pending(),3000);
|
|
348
|
+
return active.size===0&&!stuck&&starts.size===0;
|
|
349
|
+
}
|
|
350
|
+
function assertSessionIdle(owner){
|
|
351
|
+
check(![...active.values(),...held.values(),...starts.values()].some(entry=>sameOwner(entry.owner,owner)),"full_session_busy");
|
|
352
|
+
}
|
|
353
|
+
function forgetSession(owner){
|
|
354
|
+
// Called only after durable logical deletion. Never cancel a process or
|
|
355
|
+
// release a lease here; admission and durable guards must already be idle.
|
|
356
|
+
for(const [jobId,entry] of retained)if(sameOwner(entry.owner,owner))retained.delete(jobId);
|
|
357
|
+
}
|
|
358
|
+
await recoverStartup();
|
|
359
|
+
return Object.freeze({dispatch,close,assertSessionIdle,forgetSession,waitEnabled,recoveryEnabled:!!native.recover,blocksLegacyEffects:()=>stuck||starts.size>0||active.size>0||held.size>0});
|
|
360
|
+
}
|