@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,343 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import { performance } from "node:perf_hooks";
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { validateSessionIdentity, validateResourceClaim } from "../packages/full-contracts/index.mjs";
|
|
7
|
+
import { validNativeRecovery } from "../packages/full-contracts/native-job.mjs";
|
|
8
|
+
|
|
9
|
+
const priorityValue = Object.freeze({ background: 0, task: 1, interactive: 2 });
|
|
10
|
+
const modeValue = Object.freeze({ read: 0, write: 1, exclusive: 2 });
|
|
11
|
+
const error = code => Object.assign(new Error(code), { code });
|
|
12
|
+
const validId = value => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value);
|
|
13
|
+
const bounded = (value, fallback, min, max) => Number.isSafeInteger(value) ? Math.max(min, Math.min(max, value)) : fallback;
|
|
14
|
+
const resourceId = key => "r:" + createHash("sha256").update(key).digest("hex");
|
|
15
|
+
|
|
16
|
+
export async function canonicalFileResource(target, { checkTarget, platform = process.platform, requireExistingCanonical = false } = {}) {
|
|
17
|
+
// Resolve the nearest existing ancestor to avoid aliases through symlinks.
|
|
18
|
+
// Broker must recheck authorization at effect time (TOCTOU is not eliminated).
|
|
19
|
+
if (typeof target !== "string" || !path.isAbsolute(target) || typeof checkTarget !== "function") throw error("full_invalid_resource_path");
|
|
20
|
+
let current = path.resolve(target), tail = [];
|
|
21
|
+
for (;;) {
|
|
22
|
+
try {
|
|
23
|
+
current = await fs.realpath(current);
|
|
24
|
+
break;
|
|
25
|
+
} catch (cause) {
|
|
26
|
+
if (cause.code !== "ENOENT") throw cause;
|
|
27
|
+
try {
|
|
28
|
+
// A dangling symlink must not be treated as an absent ordinary path.
|
|
29
|
+
const stat = await fs.lstat(current);
|
|
30
|
+
if (stat.isSymbolicLink()) throw error("full_invalid_resource_path");
|
|
31
|
+
throw error("full_invalid_resource_path");
|
|
32
|
+
} catch (statError) { if (statError.code !== "ENOENT") throw statError; }
|
|
33
|
+
const parent = path.dirname(current);
|
|
34
|
+
if (parent === current) throw error("full_invalid_resource_path");
|
|
35
|
+
tail.unshift(path.basename(current));
|
|
36
|
+
current = parent;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const resolved = path.join(current, ...tail);
|
|
40
|
+
if(requireExistingCanonical&&(tail.length||path.relative(resolved,path.resolve(target))!==""))throw error("full_workspace_changed");
|
|
41
|
+
if (await checkTarget(resolved) !== true) throw error("full_unauthorized");
|
|
42
|
+
let key = resolved.split(path.sep).join("/");
|
|
43
|
+
if (platform === "win32" || platform === "darwin") key = key.toLowerCase();
|
|
44
|
+
return "fs:" + key.replace(/\/$/, "");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function normalizeClaims(input) {
|
|
48
|
+
if (!Array.isArray(input) || !input.length || input.length > 16) throw error("full_invalid_claims");
|
|
49
|
+
const merged = new Map();
|
|
50
|
+
for (const claim of input) {
|
|
51
|
+
const key = claim?.key, mode = claim?.mode;
|
|
52
|
+
if (typeof key !== "string" || key.length < 3 || key.length > 2048 ||
|
|
53
|
+
!/^[a-z][a-z0-9-]*:/.test(key) || /[\0\r\n]/.test(key) || key.endsWith("/") ||
|
|
54
|
+
!Object.hasOwn(modeValue, mode)) throw error("full_invalid_claims");
|
|
55
|
+
if (!merged.has(key) || modeValue[merged.get(key)] < modeValue[mode]) merged.set(key, mode);
|
|
56
|
+
}
|
|
57
|
+
return [...merged].sort(([a],[b]) => a < b ? -1 : a > b ? 1 : 0).map(([key,mode]) => ({ key, mode }));
|
|
58
|
+
}
|
|
59
|
+
const overlap = (a,b) => a === b || a.startsWith(b + "/") || b.startsWith(a + "/");
|
|
60
|
+
const conflicts = (a,b) => a.some(x => b.some(y => overlap(x.key,y.key) && (x.mode !== "read" || y.mode !== "read")));
|
|
61
|
+
|
|
62
|
+
export function sameProcessIdentity(a,b) {
|
|
63
|
+
return a?.state === "present" && b?.state === "present" && a.pid === b.pid &&
|
|
64
|
+
a.birth === b.birth && typeof a.birth === "string" && a.birth.length > 0 &&
|
|
65
|
+
a.scheme === b.scheme && typeof a.scheme === "string";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Optional admission extension for the existing Core lanes. This owns claims,
|
|
70
|
+
* not a second work executor. No lane permit is consumed until all claims can
|
|
71
|
+
* be granted together; waiting tickets never hold partial reservations.
|
|
72
|
+
* The broker supplies trusted, canonical keys and principal-derived identity.
|
|
73
|
+
*/
|
|
74
|
+
export class FullResourceAdmission {
|
|
75
|
+
constructor({ now = Date.now, backgroundWorkers = 1, agingMs = 1000,
|
|
76
|
+
samplePressure = () => ({ memoryPressure: os.freemem() < 512 * 1024 * 1024 }),
|
|
77
|
+
sampleMs = 2000, maxTickets = 512, maxClaims = 128, proveStopped, commitRelease } = {}) {
|
|
78
|
+
this.now = now;
|
|
79
|
+
this.backgroundWorkers = bounded(backgroundWorkers, 1, 1, 2);
|
|
80
|
+
this.agingMs = bounded(agingMs, 1000, 100, 60000);
|
|
81
|
+
this.samplePressure = samplePressure;
|
|
82
|
+
this.sampleMs = bounded(sampleMs, 2000, 1000, 60000);
|
|
83
|
+
this.maxTickets = bounded(maxTickets, 512, 1, 512);
|
|
84
|
+
this.maxClaims = bounded(maxClaims, 128, 1, 512);
|
|
85
|
+
this.proveStopped = proveStopped;
|
|
86
|
+
this.commitRelease = commitRelease;
|
|
87
|
+
this.pending = new Set();
|
|
88
|
+
this.active = new Map();
|
|
89
|
+
this.listeners = new Set();
|
|
90
|
+
this.sequence = 0;
|
|
91
|
+
this.pressure = false;
|
|
92
|
+
this.sampler = null;
|
|
93
|
+
this.sampling = false;
|
|
94
|
+
this.wakePending = false;
|
|
95
|
+
this.recoveryBlocked = false;
|
|
96
|
+
this.resourceMetrics = null;
|
|
97
|
+
this.resourceSampleAt = null;
|
|
98
|
+
this.resourceCpuBaseline = null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
subscribe(listener) {
|
|
102
|
+
this.listeners.add(listener);
|
|
103
|
+
return () => this.listeners.delete(listener);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
changed() {
|
|
107
|
+
this.#syncSampler();
|
|
108
|
+
if (this.wakePending) return;
|
|
109
|
+
this.wakePending = true;
|
|
110
|
+
queueMicrotask(() => {
|
|
111
|
+
this.wakePending = false;
|
|
112
|
+
for (const listener of this.listeners) listener();
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
setRecoveryBlocked(value) {
|
|
117
|
+
// Trusted restart broker must keep admission blocked until unresolved durable
|
|
118
|
+
// claims are reconstructed/reconciled. A lease timeout is not proof.
|
|
119
|
+
this.recoveryBlocked = value === true;
|
|
120
|
+
this.changed();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
rank(ticket) {
|
|
124
|
+
return Math.min(2, priorityValue[ticket.priority] + Math.floor(Math.max(0, this.now()-ticket.enqueuedAt) / this.agingMs));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
compare(a,b) {
|
|
128
|
+
return this.rank(b)-this.rank(a) || a.enqueuedAt-b.enqueuedAt || a.sequence-b.sequence;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
register({ owner, ownerEpoch, attemptId, claims, priority = "task", ready }) {
|
|
132
|
+
const identity = validateSessionIdentity(owner);
|
|
133
|
+
if (!validId(ownerEpoch) || !validId(attemptId) || !Object.hasOwn(priorityValue,priority) ||
|
|
134
|
+
typeof ready !== "function") throw error("full_invalid_admission");
|
|
135
|
+
if (this.pending.size >= this.maxTickets) throw error("full_resource_queue_full");
|
|
136
|
+
const normalized = normalizeClaims(claims);
|
|
137
|
+
const ticket = { identity, ownerEpoch, attemptId, claims:normalized, priority, ready,
|
|
138
|
+
enqueuedAt:this.now(), sequence:++this.sequence };
|
|
139
|
+
this.pending.add(ticket);
|
|
140
|
+
this.#syncSampler();
|
|
141
|
+
return ticket;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
withdraw(ticket) {
|
|
145
|
+
if (this.pending.delete(ticket)) this.changed();
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
#eligible(ticket) {
|
|
149
|
+
if (!ticket.ready() || this.recoveryBlocked || this.active.size >= this.maxClaims) return false;
|
|
150
|
+
if (ticket.priority === "background" && (this.pressure || [...this.active.values()].filter(x=>x.priority==="background").length >= this.backgroundWorkers)) return false;
|
|
151
|
+
return ![...this.active.values()].some(existing => existing.state==="quarantined"
|
|
152
|
+
? ticket.claims.some(x=>existing.claims.some(y=>overlap(x.key,y.key)))
|
|
153
|
+
: conflicts(ticket.claims,existing.claims));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
tryGrant(ticket) {
|
|
157
|
+
if (!this.pending.has(ticket) || !this.#eligible(ticket)) return null;
|
|
158
|
+
// Total order among eligible conflicting waiters across the existing lanes.
|
|
159
|
+
// Disjoint work can proceed even while a conflicting waiter is blocked.
|
|
160
|
+
for (const other of this.pending) {
|
|
161
|
+
if (other !== ticket && this.compare(other,ticket) < 0 && conflicts(other.claims,ticket.claims) && this.#eligible(other)) return null;
|
|
162
|
+
}
|
|
163
|
+
this.pending.delete(ticket);
|
|
164
|
+
const id = randomUUID();
|
|
165
|
+
const entry = { ...ticket, id, retained:false, state:"reserved", jobId:null, process:null, containment:null, rootExited:false, launchFailed:false };
|
|
166
|
+
delete entry.ready;
|
|
167
|
+
this.active.set(id,entry);
|
|
168
|
+
const get = () => this.active.get(id);
|
|
169
|
+
const assert = () => { const item=get(); if (!item) throw error("full_claim_not_active"); return item; };
|
|
170
|
+
const snapshot = () => this.#describe(assert());
|
|
171
|
+
const lease = Object.freeze({
|
|
172
|
+
id,
|
|
173
|
+
snapshot,
|
|
174
|
+
retain: jobId => {
|
|
175
|
+
const item=assert();
|
|
176
|
+
if (!validId(jobId) || item.retained || item.state !== "reserved") throw error("full_invalid_job_binding");
|
|
177
|
+
item.retained=true;item.jobId=jobId;
|
|
178
|
+
return snapshot();
|
|
179
|
+
},
|
|
180
|
+
recordContainment: descriptor => {
|
|
181
|
+
const item=assert();
|
|
182
|
+
if(!item.retained||item.process||item.containment||!validNativeRecovery(descriptor))throw error("full_invalid_job_containment");
|
|
183
|
+
item.containment=Object.freeze({...descriptor});
|
|
184
|
+
},
|
|
185
|
+
recordProcess: identity => {
|
|
186
|
+
const item=assert();
|
|
187
|
+
if (!item.retained || item.process || identity?.state!=="present" || !Number.isSafeInteger(identity.pid) ||
|
|
188
|
+
identity.pid<=0 || typeof identity.birth!=="string" || !identity.birth || typeof identity.scheme!=="string" || !identity.scheme)
|
|
189
|
+
throw error("full_invalid_process_identity");
|
|
190
|
+
item.process={...identity};return snapshot();
|
|
191
|
+
},
|
|
192
|
+
rootExited: () => { const item=get();if(!item)return null;item.rootExited=true; item.state="quarantined"; return snapshot(); },
|
|
193
|
+
quarantine: () => { const item=get();if(!item)return null;item.state="quarantined"; return snapshot(); },
|
|
194
|
+
spawnFailed: () => {
|
|
195
|
+
const item=get();if(!item)return;
|
|
196
|
+
if (!item.retained || item.process || item.rootExited) throw error("full_unknown_job_outcome");
|
|
197
|
+
// Actual spawn failure with no PID is known absent, but durable claims
|
|
198
|
+
// must still be persisted as released before a new writer may start.
|
|
199
|
+
item.launchFailed=true;item.state="quarantined";
|
|
200
|
+
},
|
|
201
|
+
confirmRequestSettled: proof => {
|
|
202
|
+
const item=get();if(!item)return false;
|
|
203
|
+
// Trusted same-Core I/O receipt plus the sole store's durable ACK.
|
|
204
|
+
// A Full child exit, timeout, or arbitrary caller boolean is not a receipt.
|
|
205
|
+
if(item.retained||item.process||item.state!=="quarantined"||proof?.commitConfirmed!==true||proof.ownerEpoch!==item.ownerEpoch||proof.attemptId!==item.attemptId)throw error("full_reconciliation_required");
|
|
206
|
+
this.#release(id);return true;
|
|
207
|
+
},
|
|
208
|
+
confirmRequestOwnerStopped: proof => {
|
|
209
|
+
const item=get();if(!item)return false;
|
|
210
|
+
// Only the Core supervisor may supply its actual Full child exit.
|
|
211
|
+
// Native/retained claims always require their separate tree proof.
|
|
212
|
+
if(item.retained||item.process||item.state!=="quarantined"||proof?.confirmed!==true||proof.ownerEpoch!==item.ownerEpoch)throw error("full_reconciliation_required");
|
|
213
|
+
this.#release(id);return true;
|
|
214
|
+
},
|
|
215
|
+
finishRequest: failed => {
|
|
216
|
+
const item=get();if(!item)return;
|
|
217
|
+
if(!item.retained && item.state==="reserved") this.#release(id);
|
|
218
|
+
else if(failed) item.state="quarantined";
|
|
219
|
+
},
|
|
220
|
+
});
|
|
221
|
+
this.#syncSampler();
|
|
222
|
+
return lease;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
#describe(entry) {
|
|
226
|
+
return {
|
|
227
|
+
id:entry.id, owner:{...entry.identity}, ownerEpoch:entry.ownerEpoch, attemptId:entry.attemptId,
|
|
228
|
+
priority:entry.priority, state:entry.state, jobId:entry.jobId,
|
|
229
|
+
process:entry.process?{...entry.process}:null, rootExited:entry.rootExited, launchFailed:entry.launchFailed,
|
|
230
|
+
claims:entry.claims.map(({key,mode})=>validateResourceClaim({
|
|
231
|
+
resourceId:resourceId(key), taskSessionId:entry.identity.taskSessionId,
|
|
232
|
+
ownerEpoch:entry.ownerEpoch, attemptId:entry.attemptId, mode, state:entry.state,
|
|
233
|
+
})),
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
#release(id) {
|
|
238
|
+
if (this.active.delete(id)) this.changed();
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async reconcile(id) {
|
|
242
|
+
const item=this.active.get(id);
|
|
243
|
+
if(!item) return {released:false,reason:"full_claim_not_active"};
|
|
244
|
+
if (!item.retained || item.state !== "quarantined" || item.reconciling || typeof this.commitRelease!=="function" ||
|
|
245
|
+
(!item.launchFailed&&((!item.process&&!item.containment)||typeof this.proveStopped!=="function")))
|
|
246
|
+
return {released:false,reason:"full_reconciliation_required"};
|
|
247
|
+
// Only an injected trusted containment/identity provider can prove the tree
|
|
248
|
+
// stopped. A client boolean, missing PID, or parent exit alone is insufficient.
|
|
249
|
+
item.reconciling=true;
|
|
250
|
+
try {
|
|
251
|
+
if(!item.launchFailed){
|
|
252
|
+
let proof;
|
|
253
|
+
try { proof=await this.proveStopped({...this.#describe(item),...(item.containment?{containment:item.containment}:{})}); }
|
|
254
|
+
catch { return {released:false,reason:"full_reconciliation_required"}; }
|
|
255
|
+
if (this.active.get(id)!==item || proof?.treeStopped!==true || proof.ownerEpoch!==item.ownerEpoch ||
|
|
256
|
+
proof.attemptId!==item.attemptId || proof.jobId!==item.jobId ||
|
|
257
|
+
(item.process?!sameProcessIdentity(proof.identity,item.process):!item.containment||proof.containment?.protocol!==item.containment.protocol||proof.containment?.token!==item.containment.token)) return {released:false,reason:"full_reconciliation_required"};
|
|
258
|
+
}
|
|
259
|
+
const claims=this.#describe(item).claims.map(claim=>({...claim,state:"released"}));
|
|
260
|
+
try{if(await this.commitRelease({owner:item.identity,claims})!==true)return {released:false,reason:"full_claim_persist_failed"};}
|
|
261
|
+
catch{return {released:false,reason:"full_claim_persist_failed"};}
|
|
262
|
+
if(this.active.get(id)!==item)return {released:false,reason:"full_claim_not_active"};
|
|
263
|
+
this.#release(id);
|
|
264
|
+
return {released:true,claims};
|
|
265
|
+
}finally{item.reconciling=false;}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
#syncSampler() {
|
|
269
|
+
const needed=[...this.pending].some(x=>x.priority==="background") || [...this.active.values()].some(x=>x.priority==="background");
|
|
270
|
+
if (!needed && this.sampler) { clearInterval(this.sampler);this.sampler=null; }
|
|
271
|
+
if (needed && !this.sampler) {
|
|
272
|
+
this.#sample();
|
|
273
|
+
this.sampler=setInterval(()=>this.#sample(),this.sampleMs);
|
|
274
|
+
this.sampler.unref?.();
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Diagnostics reuse this single sampler on demand. Merely enabling Full or
|
|
279
|
+
// reading queue counts starts no timer and performs no process measurement.
|
|
280
|
+
observeResources() {
|
|
281
|
+
if(this.resourceSampleAt===null||performance.now()-this.resourceSampleAt>=this.sampleMs)this.#sample();
|
|
282
|
+
return this.resourceMetrics?structuredClone(this.resourceMetrics):null;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
#sample() {
|
|
286
|
+
if(this.sampling)return;
|
|
287
|
+
this.sampling=true;
|
|
288
|
+
const sampledAt=performance.now();
|
|
289
|
+
try {
|
|
290
|
+
const memory=process.memoryUsage(),cpu=process.cpuUsage(),prior=this.resourceCpuBaseline;
|
|
291
|
+
const windowMs=prior?sampledAt-prior.at:null;
|
|
292
|
+
const cpuMs=prior?((cpu.user-prior.cpu.user)+(cpu.system-prior.cpu.system))/1000:null;
|
|
293
|
+
this.resourceMetrics={source:"core-process-and-system",observedAt:this.now(),
|
|
294
|
+
memory:{scope:"core-process-only",rssBytes:memory.rss,heapUsedBytes:memory.heapUsed,heapTotalBytes:memory.heapTotal,externalBytes:memory.external},
|
|
295
|
+
systemMemory:{freeBytes:os.freemem(),totalBytes:os.totalmem()},
|
|
296
|
+
cpu:{scope:"core-process-only",denominator:"one-logical-core",windowMs,
|
|
297
|
+
percent:windowMs>0&&cpuMs>=0?cpuMs/windowMs*100:null},
|
|
298
|
+
limitations:["Core metrics exclude the Full host, GUI and job children; they are not a managed process-tree budget.",
|
|
299
|
+
"CPU is an observed interval for the whole Core process, not attribution to this task."]};
|
|
300
|
+
this.resourceCpuBaseline={at:sampledAt,cpu};
|
|
301
|
+
} catch {this.resourceMetrics=null;}
|
|
302
|
+
this.resourceSampleAt=sampledAt;
|
|
303
|
+
// Unknown pressure conservatively pauses background; control remains usable.
|
|
304
|
+
try {
|
|
305
|
+
const result=this.samplePressure();
|
|
306
|
+
if(result && typeof result.then==="function") {
|
|
307
|
+
this.pressure=true;
|
|
308
|
+
Promise.resolve(result).then(value=>{this.pressure=value?.memoryPressure!==false || value?.diskPressure===true;},()=>{this.pressure=true;})
|
|
309
|
+
.finally(()=>{this.sampling=false;this.changed();});
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
this.pressure=result?.memoryPressure!==false || result?.diskPressure===true;
|
|
313
|
+
} catch {this.pressure=true;}
|
|
314
|
+
this.sampling=false;
|
|
315
|
+
// Timer is demand-driven and wakes existing lanes, never polls a task.
|
|
316
|
+
if(this.sampler)this.changed();
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
snapshot({owner}={}) {
|
|
320
|
+
const entries=[...this.active.values()];
|
|
321
|
+
// Public agent config/queue metrics must never expose another task's owner
|
|
322
|
+
// or job details. A trusted broker can pass its verified scoped identity.
|
|
323
|
+
const scoped=owner?validateSessionIdentity(owner):null;
|
|
324
|
+
const claims=scoped?entries.filter(x=>x.identity.accountId===scoped.accountId&&x.identity.agentId===scoped.agentId&&x.identity.taskSessionId===scoped.taskSessionId).map(x=>this.#describe(x)):[];
|
|
325
|
+
return {pending:this.pending.size, active:entries.length, quarantined:entries.filter(x=>x.state==="quarantined").length,
|
|
326
|
+
pressure:this.pressure, sampling:Boolean(this.sampler), recoveryBlocked:this.recoveryBlocked, claims,
|
|
327
|
+
...(this.resourceMetrics?{resourceMetrics:structuredClone(this.resourceMetrics)}:{})};
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// Disk admission may evict only caller-identified disposable cache entries.
|
|
332
|
+
// Durable checkpoint/session files are never passed to the eviction callback.
|
|
333
|
+
export async function ensureDisposableSpace({ freeBytes, minBytes, reclaimDisposable }) {
|
|
334
|
+
if (typeof freeBytes!=="function" || typeof reclaimDisposable!=="function" || !Number.isSafeInteger(minBytes) || minBytes<0)
|
|
335
|
+
throw error("full_invalid_disk_budget");
|
|
336
|
+
const before=await freeBytes();
|
|
337
|
+
if(Number.isFinite(before)&&before>=minBytes)return {available:true,reclaimed:false};
|
|
338
|
+
if(!Number.isFinite(before))throw error("full_disk_state_unknown");
|
|
339
|
+
await reclaimDisposable(minBytes-before);
|
|
340
|
+
const after=await freeBytes();
|
|
341
|
+
if(!Number.isFinite(after)||after<minBytes)throw error("full_disk_pressure");
|
|
342
|
+
return {available:true,reclaimed:true};
|
|
343
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import {startRemoteFull} from "./full-session-dispatch.mjs";
|
|
2
|
+
import {fullUnavailable} from "./full-bridge.mjs";
|
|
3
|
+
import {FullContractError} from "../packages/full-contracts/index.mjs";
|
|
4
|
+
|
|
5
|
+
// One Core connection/scheduler survives a Full host failure. Only our Full
|
|
6
|
+
// host, GUI and native jobs are drained. Unknown effects stay fenced until
|
|
7
|
+
// durable OS-guard reconciliation; no operation is automatically replayed.
|
|
8
|
+
export async function startSupervisedFull(options){
|
|
9
|
+
let current=null,recovery=null,closed=false,blocked=false,disposal=null;
|
|
10
|
+
const attempts=[];
|
|
11
|
+
let lastState={state:"starting",reason:"initializing"};
|
|
12
|
+
const notify=state=>{lastState=state;try{options.onState?.(state);}catch{}};
|
|
13
|
+
const start=()=>startRemoteFull({...options,onUnavailable:info=>{
|
|
14
|
+
if(!closed&¤t?.host.ownerEpoch===info.ownerEpoch&&!recovery){
|
|
15
|
+
blocked=true;
|
|
16
|
+
options.workspaceBroker?.scheduler?.fullAdmission?.setRecoveryBlocked(true);
|
|
17
|
+
notify({state:"recovering",reason:info.reason});
|
|
18
|
+
// Defer until the current failure notification has finished rejecting
|
|
19
|
+
// pending requests; subsequent notifications join this same recovery.
|
|
20
|
+
recovery=Promise.resolve().then(recover).finally(()=>{recovery=null;});
|
|
21
|
+
}
|
|
22
|
+
}});
|
|
23
|
+
async function recover(){
|
|
24
|
+
const old=current;
|
|
25
|
+
await old?.dispose().catch(()=>{});
|
|
26
|
+
// Core-backed edits/Git may outlive the crashed host. Keep their original
|
|
27
|
+
// runtime guards and lifecycle count until they actually settle. A retry
|
|
28
|
+
// must never discard an in-memory writer merely because the host exited.
|
|
29
|
+
if(old?.pending>0){notify({state:"blocked",reason:"full_requests_unresolved"});return;}
|
|
30
|
+
while(!closed){
|
|
31
|
+
const now=Date.now();
|
|
32
|
+
while(attempts.length&&now-attempts[0]>60000)attempts.shift();
|
|
33
|
+
if(attempts.length>=3){notify({state:"blocked",reason:"full_recovery_retry_limit"});return;}
|
|
34
|
+
attempts.push(now);
|
|
35
|
+
try{
|
|
36
|
+
const next=await start();
|
|
37
|
+
if(closed){await next.dispose();return;}
|
|
38
|
+
if(!next.available){await next.dispose();throw new FullContractError("full_unavailable");}
|
|
39
|
+
current=next;blocked=false;notify({state:"available",reason:"guarded-recovery"});return;
|
|
40
|
+
}catch(error){
|
|
41
|
+
notify({state:"recovering",reason:typeof error?.code==="string"&&/^full_[a-z0-9_]+$/.test(error.code)?error.code:"full_recovery_failed"});
|
|
42
|
+
if(attempts.length<3)await new Promise(resolve=>setTimeout(resolve,250*attempts.length));
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
current=await start();
|
|
47
|
+
if(!current.available){await current.dispose();throw new FullContractError("full_unavailable");}
|
|
48
|
+
lastState={state:"available",reason:"initial-start"};
|
|
49
|
+
return Object.freeze({
|
|
50
|
+
get host(){return current?.host;},
|
|
51
|
+
get status(){return {...lastState,available:!closed&&!blocked&&!!current?.available,recoveryAttemptsLastMinute:attempts.filter(at=>Date.now()-at<60000).length,requiresRestart:lastState.state==="blocked",effectsFenced:blocked||options.workspaceBroker?.scheduler?.fullAdmission?.recoveryBlocked===true};},
|
|
52
|
+
get pending(){return (current?.pending??0)+(recovery?1:0);},
|
|
53
|
+
get available(){return !closed&&!blocked&&!!current?.available;},
|
|
54
|
+
get capabilities(){return !closed&&!blocked?current?.capabilities??[]:[];},
|
|
55
|
+
get desktopStatus(){return current?.desktopStatus??null;},
|
|
56
|
+
monitorChanged:()=>current?.monitorChanged(),
|
|
57
|
+
dispatch:(payload,metadata)=>closed||blocked?Promise.resolve(fullUnavailable()):current.dispatch(payload,metadata),
|
|
58
|
+
openDesktop:input=>closed||blocked?Promise.reject(new FullContractError("full_unavailable")):current.openDesktop(input),
|
|
59
|
+
blocksLegacyEffects:()=>blocked||!!current?.blocksLegacyEffects(),
|
|
60
|
+
dispose(){
|
|
61
|
+
if(disposal)return disposal;
|
|
62
|
+
closed=true;lastState={state:"closed",reason:"operator-stop"};
|
|
63
|
+
disposal=(async()=>{await recovery;return current?.dispose()??{confirmed:true,code:0};})();
|
|
64
|
+
return disposal;
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import {fullUnavailable,FullContractError} from "../packages/full-contracts/index.mjs";
|
|
2
|
+
import {parseAuthorizedFullInvocation,REMOTE_SESSION_OPERATIONS,REMOTE_SESSION_LIFECYCLE_OPERATIONS,REMOTE_WORKSPACE_OPERATIONS,REMOTE_INTELLIGENCE_OPERATIONS,REMOTE_JOB_OPERATIONS,WORKSPACE_BROKER_OPERATIONS,REMOTE_FULL_CAPABILITIES,DIAGNOSTICS_OPERATION,REMOTE_DIAGNOSTICS_OPERATIONS,REMOTE_DESKTOP_OPERATIONS} from "../packages/full-contracts/remote-session.mjs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import {performance} from "node:perf_hooks";
|
|
5
|
+
|
|
6
|
+
export const FULL_STARTUP_EXIT_CODE=6;
|
|
7
|
+
const require=(ok,code)=>{if(!ok)throw new FullContractError(code);};
|
|
8
|
+
/** Bootstrap is from the local runner after verified cache resolution, never
|
|
9
|
+
* from a tool. Keep it out of child terminal/process environments. */
|
|
10
|
+
export function takeFullBootstrap(env=process.env){
|
|
11
|
+
const raw=env.CHAT_RELAY_FULL_BOOTSTRAP;
|
|
12
|
+
delete env.CHAT_RELAY_FULL_BOOTSTRAP;
|
|
13
|
+
if(raw===undefined)return null;
|
|
14
|
+
require(typeof raw==="string"&&raw.length<=16384,"full_invalid_host_configuration");
|
|
15
|
+
let data;try{data=JSON.parse(raw);}catch{throw new FullContractError("full_invalid_host_configuration");}
|
|
16
|
+
require(data&&typeof data.headless==="boolean"&&typeof data.coreRunnerId==="string"&&typeof data.sessionDirectory==="string"&&path.isAbsolute(data.sessionDirectory)&&data.artifact&&typeof data.artifact.executablePath==="string"&&path.isAbsolute(data.artifact.executablePath)&&Array.isArray(data.artifact.capabilities)&&data.artifact.capabilities.includes("full.sessions")&&data.artifact.capabilities.every(c=>REMOTE_FULL_CAPABILITIES.includes(c)),"full_invalid_host_configuration");
|
|
17
|
+
if(!data.headless){
|
|
18
|
+
const p=data.localPrincipal;
|
|
19
|
+
require(p&&typeof p.accountId==="string"&&/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(p.accountId)&&typeof p.agentId==="string"&&/^[a-z0-9_-]{1,64}$/.test(p.agentId)&&Array.isArray(p.scopes)&&p.scopes.includes("read")&&p.scopes.every(s=>["read","write","terminal"].includes(s)),"full_unauthorized");
|
|
20
|
+
}
|
|
21
|
+
return data;
|
|
22
|
+
}
|
|
23
|
+
export async function startRemoteFull({bootstrap,agentId,onUnavailable,workspaceBroker,authorizePrincipal,monitorSnapshot,monitorDetails,requestQuit}){
|
|
24
|
+
if(!bootstrap)return null;
|
|
25
|
+
const {startFullHost}=await import("./full-host.mjs");
|
|
26
|
+
// Presentation runs in Core and calls the same authorized dispatcher. The
|
|
27
|
+
// sole SQLite host stays headless; closing a window never closes that host.
|
|
28
|
+
const host=await startFullHost({optIn:true,artifact:bootstrap.artifact,coreRunnerId:bootstrap.coreRunnerId,headless:true,
|
|
29
|
+
configuration:{agentId,sessionDirectory:bootstrap.sessionDirectory},onUnavailable});
|
|
30
|
+
let workspace=null,diagnostics=null,desktop=null,desktopActions=null,pending=0,closed=false,disposal=null;
|
|
31
|
+
const activeRequests=new Set(),taskRequests=new Map();
|
|
32
|
+
const sessionLifecycle=bootstrap.artifact.capabilities.includes("full.sessions.lifecycle")&&REMOTE_SESSION_LIFECYCLE_OPERATIONS.every(op=>host.operations.includes(op));
|
|
33
|
+
function enterTask(parsed){
|
|
34
|
+
const taskSessionId=parsed.input.taskSessionId;
|
|
35
|
+
if(!sessionLifecycle||!taskSessionId)return null;
|
|
36
|
+
const key=JSON.stringify([parsed.principal.accountId,parsed.principal.agentId,taskSessionId]);
|
|
37
|
+
const deleting=parsed.operation==="full.session.delete",prior=taskRequests.get(key);
|
|
38
|
+
require(!prior?.deleting&&(!deleting||!prior?.active),"full_session_busy");
|
|
39
|
+
const state=prior??{active:0,deleting:false};
|
|
40
|
+
state.active++;state.deleting=deleting;taskRequests.set(key,state);
|
|
41
|
+
return ()=>{
|
|
42
|
+
state.active--;
|
|
43
|
+
if(!state.active)taskRequests.delete(key);
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
try{
|
|
47
|
+
require(REMOTE_SESSION_OPERATIONS.every(op=>host.operations.includes(op)),"full_capability_unavailable");
|
|
48
|
+
if(workspaceBroker&&bootstrap.artifact.capabilities.includes("full.workspace.readonly")){
|
|
49
|
+
require(WORKSPACE_BROKER_OPERATIONS.every(op=>host.operations.includes(op)),"full_capability_unavailable");
|
|
50
|
+
const {createRemoteWorkspaceBroker}=await import("./full-workspace-broker.mjs");
|
|
51
|
+
workspace=await createRemoteWorkspaceBroker({...workspaceBroker,host,artifact:bootstrap.artifact,recoveryDirectory:bootstrap.sessionDirectory,
|
|
52
|
+
onJobChanged:event=>{try{desktop?.invalidate(event);}catch{/* optional presentation */}}});
|
|
53
|
+
}
|
|
54
|
+
if(bootstrap.artifact.capabilities.includes("full.diagnostics")&&host.operations.includes(DIAGNOSTICS_OPERATION)){
|
|
55
|
+
const {createRemoteDiagnostics}=await import("./full-remote-diagnostics.mjs");
|
|
56
|
+
diagnostics=await createRemoteDiagnostics({host,artifact:bootstrap.artifact,scheduler:workspaceBroker?.scheduler});
|
|
57
|
+
}
|
|
58
|
+
if(workspaceBroker?.desktop){
|
|
59
|
+
const {createRemoteDesktopActions}=await import("./full-desktop-actions.mjs");
|
|
60
|
+
desktopActions=await createRemoteDesktopActions({...workspaceBroker,host,artifact:bootstrap.artifact});
|
|
61
|
+
}
|
|
62
|
+
if(bootstrap.headless===false){
|
|
63
|
+
require(bootstrap.localPrincipal?.agentId===agentId,"full_unauthorized");
|
|
64
|
+
const {createFullDesktopBroker}=await import("./full-desktop-broker.mjs");
|
|
65
|
+
desktop=await createFullDesktopBroker({host,artifact:bootstrap.artifact,sessionDirectory:bootstrap.sessionDirectory,
|
|
66
|
+
principal:bootstrap.localPrincipal,dispatch,authorizePrincipal,readChanges:workspace?.presentationChanges?readChanges:undefined,allowTerminal:workspaceBroker?.terminalEnabled===true,monitorSnapshot,monitorDetails,requestQuit});
|
|
67
|
+
}
|
|
68
|
+
}catch(error){
|
|
69
|
+
try{await desktop?.close();desktopActions?.close();await workspace?.close();diagnostics?.close();}finally{await host.dispose();}
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
async function readChanges(invocation,input,signal,redact){
|
|
73
|
+
require(!closed&&host.available&&workspace?.presentationChanges,"full_unavailable");
|
|
74
|
+
require(pending<64,"full_control_queue_full");
|
|
75
|
+
pending++;
|
|
76
|
+
let finish;const settled=new Promise(resolve=>{finish=resolve;});activeRequests.add(settled);
|
|
77
|
+
let leaveTask;
|
|
78
|
+
try{
|
|
79
|
+
const parsed=parseAuthorizedFullInvocation(invocation,agentId);
|
|
80
|
+
require(parsed.operation==="full.session.snapshot","full_unauthorized");
|
|
81
|
+
leaveTask=enterTask(parsed);
|
|
82
|
+
return await workspace.presentationChanges(invocation,parsed,input,signal,redact);
|
|
83
|
+
}finally{pending--;leaveTask?.();activeRequests.delete(settled);finish();}
|
|
84
|
+
}
|
|
85
|
+
async function dispatch(payload,metadata={}){
|
|
86
|
+
if(closed||!host.available)return fullUnavailable();
|
|
87
|
+
if(pending>=64)return {ok:false,error:"full_control_queue_full"};
|
|
88
|
+
pending++;
|
|
89
|
+
let finishRequest;const settled=new Promise(resolve=>{finishRequest=resolve;});activeRequests.add(settled);
|
|
90
|
+
const started=performance.now();
|
|
91
|
+
let parsed,result,leaveTask;
|
|
92
|
+
try{
|
|
93
|
+
parsed=parseAuthorizedFullInvocation(payload,agentId);
|
|
94
|
+
if(REMOTE_SESSION_LIFECYCLE_OPERATIONS.includes(parsed.operation))require(sessionLifecycle,"full_capability_unavailable");
|
|
95
|
+
// Register synchronously before any await. Normal calls remain concurrent;
|
|
96
|
+
// deletion rejects busy tasks and fences new calls for this exact owner.
|
|
97
|
+
leaveTask=enterTask(parsed);
|
|
98
|
+
let response;
|
|
99
|
+
if(parsed.operation==="full.session.delete"){
|
|
100
|
+
const owner={accountId:parsed.principal.accountId,agentId:parsed.principal.agentId,taskSessionId:parsed.input.taskSessionId};
|
|
101
|
+
const admission=workspaceBroker?.scheduler?.fullAdmission;
|
|
102
|
+
require(!admission||admission.snapshot({owner}).claims.length===0,"full_session_busy");
|
|
103
|
+
workspace?.assertSessionIdle(owner);
|
|
104
|
+
try{
|
|
105
|
+
response=await host.request(parsed.operation,payload,{taskSessionId:owner.taskSessionId,timeoutMs:15000,waitForSettlement:true});
|
|
106
|
+
}catch(error){
|
|
107
|
+
// An unconfirmed timeout cannot reopen this task while deletion may
|
|
108
|
+
// still be running. Stop this host; no cancellation/replay is inferred.
|
|
109
|
+
if(error?.code==="full_settlement_unknown")void host.dispose().catch(()=>{});
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
require(response?.acknowledged===true&&response.taskSessionId===owner.taskSessionId,"full_session_deletion_unconfirmed");
|
|
113
|
+
workspace?.forgetSession(owner);diagnostics?.forgetSession(owner);desktop?.forgetSession(owner);
|
|
114
|
+
}else if(REMOTE_DESKTOP_OPERATIONS.includes(parsed.operation)){
|
|
115
|
+
require(desktopActions,"full_capability_unavailable");
|
|
116
|
+
response=await desktopActions.dispatch(payload,parsed);
|
|
117
|
+
}else if(REMOTE_DIAGNOSTICS_OPERATIONS.includes(parsed.operation)){
|
|
118
|
+
require(diagnostics,"full_capability_unavailable");
|
|
119
|
+
response=parsed.operation===DIAGNOSTICS_OPERATION?await diagnostics.snapshot(payload,parsed):
|
|
120
|
+
parsed.operation==="full.diagnostics.mode"?await diagnostics.configure(payload,parsed):await diagnostics.exportSnapshot(payload,parsed);
|
|
121
|
+
}else if(REMOTE_WORKSPACE_OPERATIONS.includes(parsed.operation)||REMOTE_INTELLIGENCE_OPERATIONS.includes(parsed.operation)||REMOTE_JOB_OPERATIONS.includes(parsed.operation)||parsed.operation==="full.verification.assess"){
|
|
122
|
+
require(workspace,"full_capability_unavailable");
|
|
123
|
+
response=await workspace.dispatch(payload,parsed);
|
|
124
|
+
}else response=await host.request(parsed.operation,payload,{taskSessionId:parsed.input.taskSessionId,timeoutMs:15000});
|
|
125
|
+
result={ok:true,result:response};
|
|
126
|
+
}catch(error){result={ok:false,error:typeof error?.code==="string"&&/^full_[a-z0-9_]+$/.test(error.code)?error.code:"full_operation_failed"};}
|
|
127
|
+
finally{pending--;}
|
|
128
|
+
if(parsed&&parsed.operation!=="full.session.delete"){
|
|
129
|
+
try{diagnostics?.completed(parsed,result,started,metadata);}catch{/* disposable diagnostics never change an executed result */}
|
|
130
|
+
try{if(result.ok)desktop?.completed(parsed,result);}catch{/* slow GUI never blocks execution */}
|
|
131
|
+
}
|
|
132
|
+
leaveTask?.();activeRequests.delete(settled);finishRequest();
|
|
133
|
+
return result;
|
|
134
|
+
}
|
|
135
|
+
return Object.freeze({
|
|
136
|
+
host,
|
|
137
|
+
get pending(){return pending;},
|
|
138
|
+
get available(){return !closed&&host.available;},
|
|
139
|
+
get desktopStatus(){return desktop?.status??null;},
|
|
140
|
+
get capabilities(){return !closed&&host.available?["full.sessions",...(sessionLifecycle?["full.sessions.lifecycle"]:[]),...(workspace?.capabilities??[]),...(diagnostics?["full.diagnostics"]:[]),...(desktopActions?.capabilities??[])]:[];},
|
|
141
|
+
dispatch,
|
|
142
|
+
monitorChanged(){try{desktop?.invalidate();}catch{/* monitoring never changes execution */}},
|
|
143
|
+
async openDesktop(input){
|
|
144
|
+
require(!closed&&host.available&&desktop,"full_unavailable");
|
|
145
|
+
pending++;
|
|
146
|
+
try{return await desktop.open(input);}finally{pending--;}
|
|
147
|
+
},
|
|
148
|
+
blocksLegacyEffects:()=>!!workspace?.blocksLegacyEffects()||!!desktopActions?.blocksLegacyEffects(),
|
|
149
|
+
dispose(){
|
|
150
|
+
if(disposal)return disposal;
|
|
151
|
+
closed=true;
|
|
152
|
+
disposal=(async()=>{
|
|
153
|
+
let clean=true;
|
|
154
|
+
try{await desktop?.close();}catch{/* GUI shutdown is independent of state ownership */}
|
|
155
|
+
try{diagnostics?.close();}catch{}
|
|
156
|
+
try{clean=desktopActions?.close()!==false&&clean;}catch{clean=false;}
|
|
157
|
+
try{clean=(await workspace?.close())!==false&&clean;}catch{clean=false;}
|
|
158
|
+
let timer;
|
|
159
|
+
const drained=await Promise.race([Promise.allSettled([...activeRequests]).then(()=>true),new Promise(resolve=>{timer=setTimeout(()=>resolve(false),10000);})]).finally(()=>clearTimeout(timer));
|
|
160
|
+
const result=await host.dispose();
|
|
161
|
+
const desktopBlocked=!!desktopActions?.blocksLegacyEffects();
|
|
162
|
+
return clean&&drained&&!desktopBlocked?result:{...result,forced:true,reason:!drained?"full_requests_unresolved":desktopBlocked?"full_desktop_unresolved":"full_jobs_unresolved"};
|
|
163
|
+
})();
|
|
164
|
+
return disposal;
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
}
|