@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
@@ -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&&current.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
+ }
@@ -0,0 +1,205 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import {spawn,execFile} from "node:child_process";
4
+ import {createHash,randomBytes} from "node:crypto";
5
+ import {StringDecoder} from "node:string_decoder";
6
+ import {FullContractError} from "../packages/full-contracts/index.mjs";
7
+ import {nativeJobPlatform,validNativeRecovery} from "../packages/full-contracts/native-job.mjs";
8
+ import {validateCommand} from "./terminal-manager.mjs";
9
+ import {powerShellUtf8Script} from "./windows-powershell.mjs";
10
+
11
+ const err=code=>new FullContractError(code);
12
+ const MAX_OUTPUT_BYTES=128*1024,MAX_FRAME=8193,MAX_PAGE=24*1024;
13
+ const timeout=(v)=>Number.isSafeInteger(v)&&v>=1000&&v<=1800000;
14
+ const nativeEnvironment=()=>Object.fromEntries(Object.entries(process.env).filter(([key])=>{
15
+ // Inherited Relay credentials and bootstrap/IPC state must never reach jobs.
16
+ // Preserve normal developer environment (including SDK/tool paths).
17
+ return !/^(?:RELAY_|AGENT_|CHAT_RELAY_|NODE_CHANNEL_|OPENAI_APPS_|TEST_ADMIN_TOKEN$|CALLER_TOKEN$|ADMIN_TOKEN$)/i.test(key);
18
+ }));
19
+ // Stable selected toolchain environment identity, not a claim of a complete
20
+ // machine/dependency snapshot. Hash values rather than disclosing paths.
21
+ export function verificationEnvironment(artifactId){
22
+ const keys=new Set(["path","java_home","android_home","android_sdk_root","gradle_user_home","node_options","systemroot"]);
23
+ const selected=Object.entries(nativeEnvironment()).filter(([key])=>keys.has(key.toLowerCase())).map(([key,value])=>[key.toLowerCase(),value]).sort(([a],[b])=>a.localeCompare(b));
24
+ const digest=createHash("sha256").update(JSON.stringify([process.version,artifactId,selected])).digest("hex");
25
+ return "native-v1:"+process.platform+"-"+process.arch+":"+digest;
26
+ }
27
+ function outputBuffer(){
28
+ const rows=[];let seq=0,bytes=0;
29
+ const decoders={stdout:new StringDecoder("utf8"),stderr:new StringDecoder("utf8")};
30
+ function append(stream,text){
31
+ if(!text)return;
32
+ // Bound JSON expansion even for binary/control-character-heavy output.
33
+ for(let offset=0;offset<text.length;){
34
+ let end=Math.min(offset+2048,text.length);
35
+ if(end<text.length&&/[\uD800-\uDBFF]/.test(text[end-1]))end--;
36
+ const part=text.slice(offset,end);offset=end;
37
+ const n=Buffer.byteLength(part);rows.push({seq:++seq,stream,text:part,n});bytes+=n;
38
+ while(bytes>MAX_OUTPUT_BYTES||rows.length>256)bytes-=rows.shift().n;
39
+ }
40
+ }
41
+ return {
42
+ add(stream,chunk){append(stream,decoders[stream].write(chunk));},
43
+ end(){for(const stream of ["stdout","stderr"])append(stream,decoders[stream].end());},
44
+ read(afterSeq=0){
45
+ if(afterSeq>seq)throw err("full_invalid_cursor");
46
+ const oldest=rows[0]?.seq??seq+1,items=[];let size=0;
47
+ for(const {n,...row} of rows){
48
+ if(row.seq<=afterSeq)continue;
49
+ const cost=Buffer.byteLength(JSON.stringify(row));
50
+ if(size+cost>MAX_PAGE&&items.length)break;
51
+ items.push(row);size+=cost;
52
+ }
53
+ return {chunks:items,nextSeq:items.at(-1)?.seq??Math.min(seq,Math.max(afterSeq,oldest-1)),oldestSeq:oldest,
54
+ truncated:afterSeq<oldest-1,hasMore:(items.at(-1)?.seq??afterSeq)<seq};
55
+ }
56
+ };
57
+ }
58
+
59
+ /** Framed trusted helper channel, NOT command stdout. Descendants inherit only
60
+ * separate output pipes; text pretending to be a proof is just output data. */
61
+ export function launchNativeJob(helper,program,args,{cwd,timeoutMs,env=nativeEnvironment(),guardPath:recoveryFile,platform=process.platform}={}){
62
+ const provider=nativeJobPlatform(platform);if(!provider)throw err("full_native_provider_unavailable");
63
+ if(!path.isAbsolute(helper)||!path.isAbsolute(program)||!path.isAbsolute(cwd)||!timeout(timeoutMs))throw err("full_invalid_native_job");
64
+ if(recoveryFile!==undefined&&!path.isAbsolute(recoveryFile))throw err("full_invalid_job_recovery");
65
+ const child=spawn(helper,[...(recoveryFile?["--guard",recoveryFile]:[]),String(timeoutMs),program,...args],{cwd,env,windowsHide:true,stdio:["pipe","pipe","pipe"]});
66
+ const output=outputBuffer();
67
+ let readyResolve,readyReject,finish,identity=null,proof=null,bad=false,closed=false,settled=false,cancelRequested=false,buffer=Buffer.alloc(0);
68
+ const ready=new Promise((resolve,reject)=>{readyResolve=resolve;readyReject=reject;});ready.catch(()=>{});
69
+ const completion=new Promise(resolve=>{finish=resolve;});
70
+ function abortProtocol(){
71
+ if(bad)return;
72
+ bad=true;
73
+ readyReject(err("full_native_protocol_error"));
74
+ // Closing only our helper control pipe requests job termination. A forced
75
+ // helper kill is a last resort, never a substitute for stop proof.
76
+ child.stdin.destroy();
77
+ }
78
+ function onData(chunk){
79
+ if(bad)return;
80
+ buffer=buffer.length?Buffer.concat([buffer,chunk]):chunk;
81
+ while(buffer.length>=4){
82
+ const length=buffer.readUInt32LE(0);
83
+ if(length<1||length>MAX_FRAME){abortProtocol();return;}
84
+ if(buffer.length<length+4)break;
85
+ const frame=buffer.subarray(4,4+length);buffer=buffer.subarray(4+length);
86
+ const tag=frame[0],data=frame.subarray(1);
87
+ if(proof){abortProtocol();return;}
88
+ if(tag===82&&data.length===12&&!identity){
89
+ const pid=data.readUInt32LE(0),birth=data.readBigUInt64LE(4).toString();
90
+ if(pid===0||birth==="0"){abortProtocol();return;}
91
+ identity=Object.freeze({state:"present",pid,birth,scheme:provider.identityScheme});readyResolve(identity);
92
+ }else if((tag===79||tag===69)&&identity)output.add(tag===79?"stdout":"stderr",data);
93
+ else if(tag===70&&identity&&data.length===5&&data[0]<=provider.maxReason){
94
+ const reason=["exited","cancelled","timed-out","outcome-unknown"][data[0]];
95
+ proof={identity,treeStopped:true,reason,...(reason==="outcome-unknown"?{}:{exitCode:data.readUInt32LE(1)})};
96
+ }else{abortProtocol();return;}
97
+ }
98
+ if(buffer.length>MAX_FRAME+4)abortProtocol();
99
+ }
100
+ child.stdout.on("data",onData);
101
+ // No raw native error/command text reaches the durable store.
102
+ child.stderr.resume();child.stdin.on("error",()=>{});
103
+ child.once("error",()=>{readyReject(err("full_native_launch_failed"));bad=true;});
104
+ const handshake=setTimeout(()=>{if(!identity)abortProtocol();},10000);handshake.unref();
105
+ const watchdog=setTimeout(()=>{if(!closed){abortProtocol();try{child.kill();}catch{}}},timeoutMs+20000);watchdog.unref();
106
+ child.once("close",(code,signal)=>{
107
+ closed=true;clearTimeout(handshake);clearTimeout(watchdog);output.end();
108
+ if(!identity)readyReject(err("full_native_launch_failed"));
109
+ settled=true;
110
+ finish(!bad&&proof&&buffer.length===0&&code===0&&!signal?Object.freeze(proof):Object.freeze({treeStopped:false,reason:"outcome-unknown"}));
111
+ });
112
+ return Object.freeze({
113
+ ready,completion,read:afterSeq=>output.read(afterSeq),
114
+ get settled(){return settled;},
115
+ cancel(){if(!closed&&!cancelRequested){cancelRequested=true;child.stdin.end(Buffer.from([1]));}},
116
+ // Used only for bounded shutdown of the exact helper child handle. No PID
117
+ // lookup and no fabricated tree proof if the helper failed to settle.
118
+ force(){if(!closed){abortProtocol();try{child.kill();}catch{}}}
119
+ });
120
+ }
121
+
122
+
123
+ const recoveryProvider=(platform)=>{const value=nativeJobPlatform(platform);if(!value)throw err("full_invalid_job_recovery");return value;};
124
+ async function recoveryFolder(directory,platform=process.platform){
125
+ if(!path.isAbsolute(directory??""))throw err("full_invalid_job_recovery");
126
+ const root=await fs.realpath(directory);
127
+ if(path.relative(root,directory)!==""||(await fs.lstat(directory)).isSymbolicLink())throw err("full_invalid_job_recovery");
128
+ const folder=path.join(root,"native-jobs");await fs.mkdir(folder,{recursive:true,mode:0o700});
129
+ const stat=await fs.lstat(folder);
130
+ if(!stat.isDirectory()||stat.isSymbolicLink()||path.relative(folder,await fs.realpath(folder))!==""||
131
+ (platform==="linux"&&(stat.uid!==process.getuid()||(stat.mode&0o777)!==0o700)))throw err("full_invalid_job_recovery");
132
+ return folder;
133
+ }
134
+ export async function prepareNativeRecovery(directory,{platform=process.platform}={}){
135
+ const provider=recoveryProvider(platform);
136
+ const folder=await recoveryFolder(directory,platform),token=randomBytes(32).toString("hex"),file=path.join(folder,token+".guard");
137
+ const bytes=Buffer.alloc(provider.guardBytes);bytes.write(provider.magic,0,"ascii");bytes[9]=255;bytes.write(token,14,"ascii");
138
+ const handle=await fs.open(file,"wx",0o600);
139
+ let complete=false;
140
+ try{
141
+ await handle.writeFile(bytes);await handle.sync();
142
+ if(platform==="linux"){const directoryHandle=await fs.open(folder,"r");try{await directoryHandle.sync();}finally{await directoryHandle.close();}}
143
+ complete=true;
144
+ }finally{await handle.close();if(!complete)await fs.unlink(file).catch(()=>{});}
145
+ // No launch until this descriptor is acknowledged in the atomic job journal.
146
+ return Object.freeze({protocol:provider.protocol,token});
147
+ }
148
+ async function guardPath(directory,recovery,platform=process.platform){
149
+ const provider=recoveryProvider(platform);
150
+ if(!validNativeRecovery(recovery)||recovery.protocol!==provider.protocol)throw err("full_invalid_job_recovery");
151
+ const file=path.join(await recoveryFolder(directory,platform),recovery.token+".guard"),stat=await fs.lstat(file);
152
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.size!==provider.guardBytes||path.relative(file,await fs.realpath(file))!==""||
153
+ (platform==="linux"&&(stat.uid!==process.getuid()||(stat.mode&0o777)!==0o600)))throw err("full_invalid_job_recovery");
154
+ return file;
155
+ }
156
+ async function discardNativeRecovery(directory,recovery,platform){
157
+ try{await fs.unlink(await guardPath(directory,recovery,platform));}catch{/* retain uncertain evidence; never broad cleanup */}
158
+ }
159
+ export async function reconcileNativeJob(helper,directory,recovery,{platform=process.platform}={}){
160
+ try{
161
+ const provider=recoveryProvider(platform),file=await guardPath(directory,recovery,platform);
162
+ const {stdout}=await new Promise((resolve,reject)=>{
163
+ execFile(helper,["--reconcile",file],{env:nativeEnvironment(),windowsHide:true,encoding:"buffer",maxBuffer:1024,timeout:5000},(error,stdout,stderr)=>error?reject(error):resolve({stdout,stderr}));
164
+ });
165
+ if(stdout.length!==10||stdout.readUInt32LE(0)!==6||stdout[4]!==75||stdout[5]>provider.maxReason)return {treeStopped:false,reason:"outcome-unknown"};
166
+ const reason=["exited","cancelled","timed-out","outcome-unknown"][stdout[5]];
167
+ return Object.freeze({...recovery,treeStopped:true,reason,...(reason==="outcome-unknown"?{}:{exitCode:stdout.readUInt32LE(6)})});
168
+ }catch{return Object.freeze({treeStopped:false,reason:"outcome-unknown"});}
169
+ }
170
+
171
+ export async function createNativeJobProvider({artifact,recoveryDirectory,platform=process.platform,arch=process.arch}){
172
+ const provider=nativeJobPlatform(platform);
173
+ if(!provider||!["x64","arm64"].includes(arch)||!artifact.capabilities.includes("full.jobs"))return null;
174
+ const helper=path.resolve(path.dirname(artifact.executablePath),"../../../../native",provider.helper);
175
+ let shell="/bin/sh";
176
+ if(platform==="win32"){
177
+ const systemRoot=process.env.SystemRoot??process.env.WINDIR;
178
+ if(!systemRoot||!path.isAbsolute(systemRoot))return null;
179
+ shell=path.join(systemRoot,"System32","WindowsPowerShell","v1.0","powershell.exe");
180
+ }
181
+ try{
182
+ const stat=await fs.lstat(helper);
183
+ if(!stat.isFile()||stat.isSymbolicLink()||path.relative(helper,await fs.realpath(helper))!=="")return null;
184
+ // Exercise the actual provider, not just executable presence. Restrictive
185
+ // parent jobs, disabled user namespaces or unavailable pidfd fail closed.
186
+ const probe=launchNativeJob(helper,process.execPath,["--eval","process.exit(0)"],{cwd:path.dirname(helper),timeoutMs:3000,platform});
187
+ const result=await probe.completion;
188
+ if(!result.treeStopped||result.reason!=="exited"||result.exitCode!==0)return null;
189
+ if(recoveryDirectory!==undefined)await recoveryFolder(recoveryDirectory,platform);
190
+ return Object.freeze({
191
+ containment:provider.containment,
192
+ prepare:recoveryDirectory?()=>prepareNativeRecovery(recoveryDirectory,{platform}):null,
193
+ recover:recoveryDirectory?recovery=>reconcileNativeJob(helper,recoveryDirectory,recovery,{platform}):null,
194
+ discard:recoveryDirectory?recovery=>discardNativeRecovery(recoveryDirectory,recovery,platform):null,
195
+ async launch(command,cwd,timeoutMs,recovery){
196
+ validateCommand(command);
197
+ // Windows uses an ASCII encoded envelope; POSIX argv carries the exact
198
+ // UTF-8 command once. Payload stdin is /dev/null in both providers.
199
+ const args=platform==="win32"?["-NoLogo","-NoProfile","-NonInteractive","-OutputFormat","Text","-Command",powerShellUtf8Script(command)]:["-c",command];
200
+ const recoveryFile=recovery?await guardPath(recoveryDirectory,recovery,platform):undefined;
201
+ return launchNativeJob(helper,shell,args,{cwd,timeoutMs,guardPath:recoveryFile,platform});
202
+ }
203
+ });
204
+ }catch{return null;}
205
+ }