@anusornneal/chat-relay 1.9.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/agent/activity-capture.mjs +165 -0
- package/agent/capability-scheduler.mjs +82 -5
- package/agent/file-manager.mjs +8 -3
- package/agent/full-bridge.mjs +53 -0
- package/agent/full-desktop-actions.mjs +124 -0
- package/agent/full-desktop-auth.mjs +53 -0
- package/agent/full-desktop-broker.mjs +308 -0
- package/agent/full-host.mjs +153 -0
- package/agent/full-job-broker.mjs +360 -0
- package/agent/full-native-job.mjs +205 -0
- package/agent/full-presentation-changes.mjs +191 -0
- package/agent/full-remote-diagnostics.mjs +129 -0
- package/agent/full-resources.mjs +343 -0
- package/agent/full-runtime-supervisor.mjs +67 -0
- package/agent/full-session-dispatch.mjs +167 -0
- package/agent/full-workspace-broker.mjs +290 -0
- package/agent/git-worktree-manager.mjs +170 -4
- package/agent/lifecycle.mjs +11 -0
- package/agent/local-agent.mjs +150 -24
- package/agent/local-usage.mjs +21 -0
- package/agent/monitor-activity.mjs +111 -0
- package/agent/presentation-redaction.mjs +10 -0
- package/agent/process-manager.mjs +32 -0
- package/agent/terminal-manager.mjs +189 -31
- package/agent/toolcall-context.mjs +23 -1
- package/agent/windows-desktop-runner.mjs +65 -61
- package/agent/windows-desktop-worker.ps1 +33 -18
- package/agent/windows-powershell.mjs +51 -0
- package/cli/full-background.mjs +69 -0
- package/cli/full-launch.mjs +94 -0
- package/cli/full-prepare-child.mjs +48 -0
- package/cli/full-prepare.mjs +171 -0
- package/cli/full-release-default.json +4 -0
- package/cli/full-release-files.mjs +36 -0
- package/cli/full-release-official.mjs +48 -0
- package/cli/full-release-source.mjs +37 -0
- package/cli/index.mjs +8 -4
- package/cli/mod-cache.mjs +170 -0
- package/cli/mod-loader.mjs +67 -0
- package/cli/mod-manifest.mjs +63 -0
- package/cli/remote.mjs +172 -17
- package/cli/runner-ownership.mjs +116 -3
- package/cli/self-update.mjs +1 -1
- package/cli/tui.mjs +2 -20
- package/package.json +5 -3
- package/packages/full-contracts/index.mjs +193 -0
- package/packages/full-contracts/native-job.mjs +13 -0
- package/packages/full-contracts/package.json +7 -0
- package/packages/full-contracts/remote-session.mjs +239 -0
package/README.md
CHANGED
|
@@ -332,3 +332,9 @@ Project aliases are account-scoped mappings stored in the Learning Durable Objec
|
|
|
332
332
|
|
|
333
333
|
No new Cloudflare storage, dependencies or additional routine relay round trips
|
|
334
334
|
are needed for these improvements.
|
|
335
|
+
|
|
336
|
+
## Chat Relay Full (2.0)
|
|
337
|
+
|
|
338
|
+
Windows x64 with supported Node.js: `npx @anusornneal/chat-relay@latest remote --full` opens the native Slint monitor; add `--headless` for Full without the window. Ordinary `remote` remains Lite and downloads no Full artifact. The published Core carries a release-specific Ed25519 public key; the exact-version signed GUI/headless archive is downloaded lazily from the matching GitHub Release, verified and cached locally. This release does not claim OS code signing or Full public support on other targets.
|
|
339
|
+
|
|
340
|
+
Existing explicit `full-release.json` settings override the public default. To migrate from a local development candidate, stop the agent gracefully, back up only that settings file and move it aside, then launch 2.0. Keep existing login and session data. To roll back, restore the settings file and launch the exact previous Core version. An incompatible or unavailable Full artifact never silently starts Lite.
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import {AsyncLocalStorage} from "node:async_hooks";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import {redactPresentationText} from "./presentation-redaction.mjs";
|
|
4
|
+
import {presentationChangePath} from "./full-presentation-changes.mjs";
|
|
5
|
+
|
|
6
|
+
const storage=new AsyncLocalStorage();
|
|
7
|
+
const MAX_FILES=20,MAX_PAIR_BYTES=32*1024,MAX_CALL_BYTES=64*1024,MAX_LINES=400,MAX_DIFF_CHARS=12000;
|
|
8
|
+
const safeError=value=>typeof value==="string"&&/^[A-Za-z][A-Za-z0-9_:-]{1,95}$/.test(value)?value:"";
|
|
9
|
+
const safeInteger=value=>Number.isSafeInteger(value)&&value>=0?value:null;
|
|
10
|
+
const decode=value=>{
|
|
11
|
+
if(value===null)return "";
|
|
12
|
+
if(typeof value==="string")return value;
|
|
13
|
+
if(!Buffer.isBuffer(value))return null;
|
|
14
|
+
try{return new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(value);}catch{return null;}
|
|
15
|
+
};
|
|
16
|
+
export function displayActivityPath(value){
|
|
17
|
+
if(typeof value!=="string"||!value||value.length>4096)return "";
|
|
18
|
+
const normalized=value.replace(/\\/g,"/");
|
|
19
|
+
const absolute=path.isAbsolute(value)||/^[A-Za-z]:\//.test(normalized)||normalized.startsWith("/");
|
|
20
|
+
const parts=normalized.split("/").filter(Boolean);
|
|
21
|
+
// Never reveal credential file names or private path components. Worktree
|
|
22
|
+
// roots themselves may contain .workspace, but display only the leaf of an
|
|
23
|
+
// absolute path (relative request paths retain their project context).
|
|
24
|
+
for(const p of parts){
|
|
25
|
+
if(p===".workspace"&&absolute)continue;
|
|
26
|
+
if(/^[A-Za-z]:$/.test(p)&&absolute)continue;
|
|
27
|
+
if(!presentationChangePath(p))return "";
|
|
28
|
+
}
|
|
29
|
+
const result=absolute?parts.at(-1):normalized;
|
|
30
|
+
return result&&result.length<=512&&presentationChangePath(result)&&redactPresentationText(result,512)===result?result:"";
|
|
31
|
+
}
|
|
32
|
+
const detailActions=new Set(["fs.editMany","full.workspace.edit","fs.edit","fs.write","fs.delete","fs.read","full.workspace.read","fs.readMany","fs.readMany.relative","fs.batch","fs.batch.compact","fs.search.start","fs.search.results","full.intelligence.search","full.intelligence.symbols","terminal.exec","terminal.exec.compact","terminal.read","terminal.read.compact","full.job.read"]);
|
|
33
|
+
// Capture only explicitly supplied search terms or quoted literal rg/Select-String
|
|
34
|
+
// patterns. Never retain shell scripts, environment values or command output.
|
|
35
|
+
export function describeLocalSearch(payload){
|
|
36
|
+
const action=payload?.action==="full.invoke"?payload.operation:payload?.action;
|
|
37
|
+
const input=payload?.action==="full.invoke"?payload.input??{}:payload??{};
|
|
38
|
+
let query="",scope="";
|
|
39
|
+
if(action==="fs.search.start"){query=input.pattern;scope=displayActivityPath(input.path);}
|
|
40
|
+
else if(["full.intelligence.search","full.intelligence.symbols"].includes(action)){query=input.query;}
|
|
41
|
+
else if(["terminal.exec","terminal.exec.compact","terminal.start"].includes(action)&&typeof input.command==="string"&&input.command.length<=16000){
|
|
42
|
+
const patterns=[];
|
|
43
|
+
// Support common quoted literal search arguments, not shell expansion.
|
|
44
|
+
for(const m of input.command.matchAll(/(?:^|[;|\n]\s*)\s*(?:rg|Select-String)\s+(?:(?:-(?:C|A|B)\s+\d+|--?[A-Za-z0-9-]+)\s+)*(?:'([^'\r\n]{1,180})'|"([^"$\x60\r\n]{1,180})")/gi)){
|
|
45
|
+
patterns.push(m[1]??m[2]);if(patterns.length===3)break;
|
|
46
|
+
}
|
|
47
|
+
query=patterns.join(" · ");
|
|
48
|
+
}
|
|
49
|
+
const safe=value=>typeof value==="string"&&value.length<=512?redactPresentationText(value.replace(/[\r\n\t]/g," "),180):"";
|
|
50
|
+
return {query:safe(query),searchScope:safe(scope)};
|
|
51
|
+
}
|
|
52
|
+
export function captureActivityFor(payload){
|
|
53
|
+
const action=payload?.action==="full.invoke"?payload.operation:payload?.action;
|
|
54
|
+
return detailActions.has(action)?createActivityCapture():null;
|
|
55
|
+
}
|
|
56
|
+
export function createActivityCapture(){
|
|
57
|
+
return {files:new Map(),bytes:0,closed:false};
|
|
58
|
+
}
|
|
59
|
+
export function runActivityCapture(capture,work){
|
|
60
|
+
return capture?storage.run(capture,work):work();
|
|
61
|
+
}
|
|
62
|
+
export function recordActivityEdit(index,requestedPath,before,after,kind,canonicalTarget){
|
|
63
|
+
const context=storage.getStore();
|
|
64
|
+
if(!context||context.closed||context.files.size>=MAX_FILES)return;
|
|
65
|
+
// Observation must never turn a successful write into a failed write.
|
|
66
|
+
try{
|
|
67
|
+
const name=displayActivityPath(requestedPath);
|
|
68
|
+
if(!name||!displayActivityPath(canonicalTarget))return;
|
|
69
|
+
const entry={path:name,kind,pair:null};
|
|
70
|
+
context.files.set(index,entry);
|
|
71
|
+
if(before===undefined||after===undefined)return;
|
|
72
|
+
const size=(before===null?0:Buffer.byteLength(before))+(after===null?0:Buffer.byteLength(after));
|
|
73
|
+
if(size>MAX_PAIR_BYTES||context.bytes+size>MAX_CALL_BYTES)return;
|
|
74
|
+
const a=decode(before),b=decode(after);
|
|
75
|
+
if(a===null||b===null||a.includes("\0")||b.includes("\0")||a.includes("\uFFFD")||b.includes("\uFFFD"))return;
|
|
76
|
+
if(redactPresentationText(a,a.length)!==a||redactPresentationText(b,b.length)!==b)return;
|
|
77
|
+
if(a.split("\n").length>MAX_LINES||b.split("\n").length>MAX_LINES)return;
|
|
78
|
+
entry.pair={before:a,after:b};
|
|
79
|
+
context.bytes+=size;
|
|
80
|
+
}catch{/* Optional monitor only. */}
|
|
81
|
+
}
|
|
82
|
+
// Exact bounded line edit script from the recorded pair. Retain newline
|
|
83
|
+
// characters in the comparison so final-newline and CRLF changes are real.
|
|
84
|
+
function splitLines(value){return value.match(/[^\n]*\n|[^\n]+$/g)??[];}
|
|
85
|
+
export function historicalDiff(pair,{includeText=true}={}){
|
|
86
|
+
if(!pair)return {state:"unavailable",reason:"No captured text for this call",additions:null,deletions:null,text:""};
|
|
87
|
+
const a=splitLines(pair.before),b=splitLines(pair.after);
|
|
88
|
+
if(a.length>MAX_LINES||b.length>MAX_LINES)return {state:"unavailable",reason:"Change exceeds capture limit",additions:null,deletions:null,text:""};
|
|
89
|
+
// Strip unchanged prefix/suffix before allocating the bounded LCS table.
|
|
90
|
+
// Typical targeted edits need only a few cells instead of 400 x 400.
|
|
91
|
+
let start=0,ae=a.length,be=b.length;
|
|
92
|
+
while(start<ae&&start<be&&a[start]===b[start])start++;
|
|
93
|
+
while(ae>start&&be>start&&a[ae-1]===b[be-1]){ae--;be--;}
|
|
94
|
+
const width=be-start+1,dp=new Uint16Array((ae-start+1)*width);
|
|
95
|
+
const cell=(i,j)=>(i-start)*width+j-start;
|
|
96
|
+
for(let i=ae-1;i>=start;i--)for(let j=be-1;j>=start;j--)dp[cell(i,j)]=a[i]===b[j]?1+dp[cell(i+1,j+1)]:Math.max(dp[cell(i+1,j)],dp[cell(i,j+1)]);
|
|
97
|
+
const lines=includeText?a.slice(0,start).map(line=>[" ",line]):[];
|
|
98
|
+
let i=start,j=start,additions=0,deletions=0;
|
|
99
|
+
while(i<ae||j<be){
|
|
100
|
+
if(i<ae&&j<be&&a[i]===b[j]){if(includeText)lines.push([" ",a[i]]);i++;j++;}
|
|
101
|
+
else if(i<ae&&(j===be||dp[cell(i+1,j)]>=dp[cell(i,j+1)])){if(includeText)lines.push(["-",a[i]]);i++;deletions++;}
|
|
102
|
+
else{if(includeText)lines.push(["+",b[j]]);j++;additions++;}
|
|
103
|
+
}
|
|
104
|
+
if(includeText)for(const line of a.slice(ae))lines.push([" ",line]);
|
|
105
|
+
if(!includeText)return {state:"ready",additions,deletions};
|
|
106
|
+
if(!additions&&!deletions)return {state:"ready",additions,deletions,text:"No textual changes",truncated:false};
|
|
107
|
+
// One bounded hunk with genuine context; never substitute current Git diff.
|
|
108
|
+
const first=lines.findIndex(l=>l[0]!==" "),last=lines.findLastIndex(l=>l[0]!==" ");
|
|
109
|
+
const from=Math.max(0,first-3),to=Math.min(lines.length,last+4);
|
|
110
|
+
let oldStart=1,newStart=1;
|
|
111
|
+
for(const [op] of lines.slice(0,from)){if(op!=="+")oldStart++;if(op!=="-")newStart++;}
|
|
112
|
+
const hunk=lines.slice(from,to),oldCount=hunk.filter(l=>l[0]!=="+").length,newCount=hunk.filter(l=>l[0]!=="-").length;
|
|
113
|
+
const format=([op,line])=>op+line.replace(/\r?\n$/,"")+(line.endsWith("\n")?"":"\n\");
|
|
114
|
+
const raw="@@ -"+(oldCount?oldStart:oldStart-1)+","+oldCount+" +"+(newCount?newStart:newStart-1)+","+newCount+" @@\n"+hunk.map(format).join("\n");
|
|
115
|
+
const text=raw.slice(0,MAX_DIFF_CHARS).toWellFormed();
|
|
116
|
+
return {state:"ready",additions,deletions,text,truncated:text.length<raw.length};
|
|
117
|
+
}
|
|
118
|
+
export function finishActivityCapture(capture,payload,result){
|
|
119
|
+
if(!capture)return null;
|
|
120
|
+
capture.closed=true;
|
|
121
|
+
const action=payload?.action==="full.invoke"?payload.operation:payload?.action;
|
|
122
|
+
const input=payload?.action==="full.invoke"?payload.input??{}:payload??{};
|
|
123
|
+
const output=payload?.action==="full.invoke"?result?.result:result;
|
|
124
|
+
const files=[];let omitted=0;
|
|
125
|
+
const add=(source,index,outcome,kind,error)=>{
|
|
126
|
+
if(files.length>=MAX_FILES){omitted++;return;}
|
|
127
|
+
const captured=capture.files.get(index),name=captured?.path||displayActivityPath(source);
|
|
128
|
+
if(!name){omitted++;return;}
|
|
129
|
+
files.push({fileId:String(index),path:name,kind:captured?.kind??kind,outcome,error:safeError(error),pair:outcome==="completed"?captured?.pair??null:null});
|
|
130
|
+
};
|
|
131
|
+
const edit=action==="fs.editMany"||action==="full.workspace.edit";
|
|
132
|
+
if(edit){
|
|
133
|
+
const operations=Array.isArray(input.operations)?input.operations:[];
|
|
134
|
+
omitted=Math.max(0,operations.length-MAX_FILES);
|
|
135
|
+
for(const [index,op] of operations.slice(0,MAX_FILES).entries()){
|
|
136
|
+
const row=Array.isArray(output?.results)?output.results.find(r=>r.index===index):null;
|
|
137
|
+
add(op?.relativePath??op?.path,index,row?.ok===true?"completed":row?.ok===false||result?.ok===false?"failed":"unknown",op?.op==="create"?"added":"modified",row?.error);
|
|
138
|
+
}
|
|
139
|
+
}else if(action==="fs.edit"||action==="fs.write"||action==="fs.delete"){
|
|
140
|
+
add(input.path,0,result?.ok===false?"failed":"completed",action==="fs.delete"?"deleted":action==="fs.write"?"written":"modified",result?.error);
|
|
141
|
+
}else if(action==="fs.read"||action==="full.workspace.read"||action==="fs.readMany"||action==="fs.readMany.relative"||action==="fs.batch"||action==="fs.batch.compact"){
|
|
142
|
+
const sources=Array.isArray(input.paths)?input.paths:Array.isArray(input.relativePaths)?input.relativePaths:Array.isArray(input.operations)?input.operations:[input.relativePath??input.path];
|
|
143
|
+
omitted=Math.max(0,sources.length-MAX_FILES);
|
|
144
|
+
for(const [index,source] of sources.slice(0,MAX_FILES).entries()){
|
|
145
|
+
if(source?.op&&source.op!=="read")continue;
|
|
146
|
+
const list=output?.files??output?.reads??output?.results;
|
|
147
|
+
const row=Array.isArray(list)?(output?.results?list.find(r=>r.index===index):list[index]):null;
|
|
148
|
+
const single=action==="fs.read"||action==="full.workspace.read"&&!Array.isArray(input.relativePaths);
|
|
149
|
+
add(typeof source==="string"?source:source?.path,index,row?.ok===true||single&&result?.ok!==false?"completed":row?.ok===false||result?.ok===false?"failed":"unknown","read",row?.error??result?.error);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
// Bounded display metadata only. No raw commands, output, Learn values,
|
|
153
|
+
// or arbitrary response objects. Search terms use display redaction.
|
|
154
|
+
const search=describeLocalSearch(payload);
|
|
155
|
+
const details={files,omitted,...search,exitCode:Number.isInteger(output?.exitCode)?output.exitCode:null,resultCount:safeInteger(output?.totalResults??output?.total),error:safeError(result?.error)};
|
|
156
|
+
return files.length||omitted||details.query||details.searchScope||(details.exitCode!==null&&details.exitCode!==0)||details.resultCount!==null?details:null;
|
|
157
|
+
}
|
|
158
|
+
export function projectActivityDetails(details){
|
|
159
|
+
if(!details)return {files:[],available:false};
|
|
160
|
+
return {available:true,omitted:details.omitted??0,query:details.query??"",searchScope:details.searchScope??"",exitCode:details.exitCode,resultCount:details.resultCount,error:details.error,
|
|
161
|
+
files:details.files.map(({pair,...file})=>{
|
|
162
|
+
const stats=historicalDiff(pair,{includeText:false});
|
|
163
|
+
return {...file,diffAvailable:stats.state==="ready",additions:stats.additions,deletions:stats.deletions};
|
|
164
|
+
})};
|
|
165
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { FullResourceAdmission } from "./full-resources.mjs";
|
|
2
|
+
|
|
1
3
|
const DEFAULT_QUEUE_TIMEOUT_MS = 15_000;
|
|
2
4
|
const DEFAULT_MAX_QUEUED = 64;
|
|
3
5
|
|
|
@@ -21,13 +23,14 @@ export class BoundedLane {
|
|
|
21
23
|
this.queueTimeoutMs = boundedInteger(options.queueTimeoutMs, DEFAULT_QUEUE_TIMEOUT_MS, 100, 120_000);
|
|
22
24
|
this.active = 0;
|
|
23
25
|
this.queue = [];
|
|
26
|
+
this.fullAdmission = options.fullAdmission ?? null;
|
|
24
27
|
}
|
|
25
28
|
|
|
26
29
|
run(work) {
|
|
27
30
|
if (typeof work !== "function") return Promise.reject(queueError("invalid_work"));
|
|
28
31
|
return new Promise((resolve, reject) => {
|
|
29
32
|
const job = { work, resolve, reject, timer: null, enqueuedAt: Date.now() };
|
|
30
|
-
if (this.active < this.concurrency) {
|
|
33
|
+
if (this.active < this.concurrency && (!this.fullAdmission || !this.queue.length)) {
|
|
31
34
|
this.#start(job);
|
|
32
35
|
return;
|
|
33
36
|
}
|
|
@@ -42,9 +45,46 @@ export class BoundedLane {
|
|
|
42
45
|
reject(queueError("queue_timeout"));
|
|
43
46
|
}, this.queueTimeoutMs);
|
|
44
47
|
this.queue.push(job);
|
|
48
|
+
if(this.fullAdmission)this.#drain();
|
|
45
49
|
});
|
|
46
50
|
}
|
|
47
51
|
|
|
52
|
+
runAdmitted(work, options) {
|
|
53
|
+
if(!this.fullAdmission)return Promise.reject(queueError("full_unavailable"));
|
|
54
|
+
if(typeof work!=="function")return Promise.reject(queueError("invalid_work"));
|
|
55
|
+
if(options?.dependenciesReady!==true)return Promise.reject(queueError("full_dependency_not_ready"));
|
|
56
|
+
if(options.signal?.aborted)return Promise.reject(queueError("full_cancelled_before_start"));
|
|
57
|
+
return new Promise((resolve,reject)=>{
|
|
58
|
+
if(this.queue.length>=this.maxQueued)return reject(queueError("queue_full"));
|
|
59
|
+
const job={work,resolve,reject,timer:null,enqueuedAt:this.fullAdmission.now(),signal:options.signal};
|
|
60
|
+
try{
|
|
61
|
+
job.ticket=this.fullAdmission.register({...options,ready:()=>this.active<this.concurrency});
|
|
62
|
+
}catch(error){reject(error);return;}
|
|
63
|
+
const cancel=code=>{
|
|
64
|
+
const index=this.queue.indexOf(job);
|
|
65
|
+
if(index<0)return;
|
|
66
|
+
this.queue.splice(index,1);
|
|
67
|
+
this.fullAdmission.withdraw(job.ticket);
|
|
68
|
+
this.#clearWait(job);
|
|
69
|
+
reject(queueError(code));
|
|
70
|
+
this.#drain();
|
|
71
|
+
};
|
|
72
|
+
job.abort=()=>cancel("full_cancelled_before_start");
|
|
73
|
+
job.timer=setTimeout(()=>cancel("queue_timeout"),
|
|
74
|
+
boundedInteger(options.queueTimeoutMs,this.queueTimeoutMs,100,this.queueTimeoutMs));
|
|
75
|
+
job.signal?.addEventListener("abort",job.abort,{once:true});
|
|
76
|
+
this.queue.push(job);
|
|
77
|
+
this.#drain();
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
wake(){if(this.fullAdmission)this.#drain();}
|
|
82
|
+
|
|
83
|
+
#clearWait(job){
|
|
84
|
+
if(job.timer)clearTimeout(job.timer);
|
|
85
|
+
if(job.abort)job.signal?.removeEventListener("abort",job.abort);
|
|
86
|
+
}
|
|
87
|
+
|
|
48
88
|
snapshot() {
|
|
49
89
|
return {
|
|
50
90
|
concurrency: this.concurrency,
|
|
@@ -57,6 +97,7 @@ export class BoundedLane {
|
|
|
57
97
|
|
|
58
98
|
#start(job) {
|
|
59
99
|
if (job.timer) clearTimeout(job.timer);
|
|
100
|
+
if (job.abort) job.signal?.removeEventListener("abort",job.abort);
|
|
60
101
|
this.active += 1;
|
|
61
102
|
const queueWaitMs = Math.max(0, Date.now() - job.enqueuedAt);
|
|
62
103
|
const metadata = {
|
|
@@ -65,18 +106,41 @@ export class BoundedLane {
|
|
|
65
106
|
queueDepthAtStart: this.queue.length,
|
|
66
107
|
activeAtStart: this.active,
|
|
67
108
|
};
|
|
109
|
+
if(job.lease){
|
|
110
|
+
Promise.resolve()
|
|
111
|
+
.then(()=>{if(job.signal?.aborted)throw queueError("full_cancelled_before_start");return job.work(metadata,job.lease);})
|
|
112
|
+
.then(value=>{job.lease.finishRequest(false);job.resolve(value);},
|
|
113
|
+
error=>{job.lease.finishRequest(true);job.reject(error);})
|
|
114
|
+
.finally(()=>{this.active-=1;this.#drain();this.fullAdmission.changed();});
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
68
117
|
Promise.resolve()
|
|
69
118
|
.then(() => job.work(metadata))
|
|
70
119
|
.then(job.resolve, job.reject)
|
|
71
120
|
.finally(() => {
|
|
72
121
|
this.active -= 1;
|
|
73
122
|
this.#drain();
|
|
123
|
+
this.fullAdmission?.changed();
|
|
74
124
|
});
|
|
75
125
|
}
|
|
76
126
|
|
|
77
127
|
#drain() {
|
|
78
|
-
|
|
79
|
-
this.#start(this.queue.shift());
|
|
128
|
+
if(!this.fullAdmission){
|
|
129
|
+
while(this.active<this.concurrency&&this.queue.length>0)this.#start(this.queue.shift());
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const rank=job=>job.ticket?this.fullAdmission.rank(job.ticket):2;
|
|
133
|
+
while(this.active<this.concurrency&&this.queue.length>0){
|
|
134
|
+
const ordered=[...this.queue].sort((a,b)=>rank(b)-rank(a)||a.enqueuedAt-b.enqueuedAt);
|
|
135
|
+
let next=null;
|
|
136
|
+
for(const job of ordered){
|
|
137
|
+
if(!job.ticket){next=job;break;}
|
|
138
|
+
const lease=this.fullAdmission.tryGrant(job.ticket);
|
|
139
|
+
if(lease){job.lease=lease;next=job;break;}
|
|
140
|
+
}
|
|
141
|
+
if(!next)break;
|
|
142
|
+
this.queue.splice(this.queue.indexOf(next),1);
|
|
143
|
+
this.#start(next);
|
|
80
144
|
}
|
|
81
145
|
}
|
|
82
146
|
}
|
|
@@ -85,7 +149,8 @@ export class CapabilityScheduler {
|
|
|
85
149
|
constructor(options = {}) {
|
|
86
150
|
const maxQueued = boundedInteger(options.maxQueued, DEFAULT_MAX_QUEUED, 1, 512);
|
|
87
151
|
const queueTimeoutMs = boundedInteger(options.queueTimeoutMs, DEFAULT_QUEUE_TIMEOUT_MS, 100, 120_000);
|
|
88
|
-
|
|
152
|
+
this.fullAdmission = options.full === true ? new FullResourceAdmission(options.fullResourceOptions) : null;
|
|
153
|
+
const lane = (name, concurrency) => new BoundedLane({ name, concurrency, maxQueued, queueTimeoutMs, fullAdmission:this.fullAdmission });
|
|
89
154
|
|
|
90
155
|
this.lanes = new Map([
|
|
91
156
|
["agent", lane("agent", options.agentConcurrency ?? 4)],
|
|
@@ -98,9 +163,11 @@ export class CapabilityScheduler {
|
|
|
98
163
|
concurrency: options.terminalWaitConcurrency ?? 2,
|
|
99
164
|
maxQueued: 2,
|
|
100
165
|
queueTimeoutMs: 1000,
|
|
166
|
+
fullAdmission:this.fullAdmission,
|
|
101
167
|
})],
|
|
102
168
|
["desktopRead", lane("desktopRead", options.desktopReadConcurrency ?? 2)],
|
|
103
169
|
]);
|
|
170
|
+
if(this.fullAdmission)this.fullAdmission.subscribe(()=>{for(const lane of this.lanes.values())lane.wake();});
|
|
104
171
|
}
|
|
105
172
|
|
|
106
173
|
run(action, work) {
|
|
@@ -108,8 +175,18 @@ export class CapabilityScheduler {
|
|
|
108
175
|
return lane ? lane.run(work) : Promise.resolve().then(work);
|
|
109
176
|
}
|
|
110
177
|
|
|
178
|
+
// Trusted Core broker only. Dependencies must already be ready; this method
|
|
179
|
+
// never waits for child work while occupying a parent lane or reservation.
|
|
180
|
+
runFull(action,work,options){
|
|
181
|
+
if(!this.fullAdmission)return Promise.reject(queueError("full_unavailable"));
|
|
182
|
+
const lane=this.#laneFor(action)??this.lanes.get("agent");
|
|
183
|
+
return lane.runAdmitted(work,options);
|
|
184
|
+
}
|
|
185
|
+
|
|
111
186
|
snapshot() {
|
|
112
|
-
|
|
187
|
+
const lanes=Object.fromEntries([...this.lanes.entries()].map(([name,lane])=>[name,lane.snapshot()]));
|
|
188
|
+
if(this.fullAdmission)lanes.fullResources=this.fullAdmission.snapshot();
|
|
189
|
+
return lanes;
|
|
113
190
|
}
|
|
114
191
|
|
|
115
192
|
#laneFor(action) {
|
package/agent/file-manager.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
4
|
import { deduplicateSearchPreviews } from "./fs-batch-preview.mjs";
|
|
5
|
+
import {recordActivityEdit} from "./activity-capture.mjs";
|
|
5
6
|
|
|
6
7
|
const MAX_READ_BYTES = 256 * 1024;
|
|
7
8
|
const DEFAULT_READ_RESPONSE_BYTES = 32 * 1024;
|
|
@@ -425,13 +426,13 @@ export class FileManager {
|
|
|
425
426
|
}
|
|
426
427
|
|
|
427
428
|
// One entry per file, multiple exact replacements per entry. Separate from read-only batch.
|
|
428
|
-
editMany(operations, basePath) {
|
|
429
|
-
const run = this.editBatchTail.then(() => this.#editMany(operations, basePath));
|
|
429
|
+
editMany(operations, basePath, {strictPaths=false}={}) {
|
|
430
|
+
const run = this.editBatchTail.then(() => this.#editMany(operations, basePath,strictPaths));
|
|
430
431
|
this.editBatchTail = run.catch(() => {});
|
|
431
432
|
return run;
|
|
432
433
|
}
|
|
433
434
|
|
|
434
|
-
async #editMany(operations, basePath) {
|
|
435
|
+
async #editMany(operations, basePath, strictPaths) {
|
|
435
436
|
if (!Array.isArray(operations) || !operations.length || operations.length > MAX_BATCH_OPERATIONS) {
|
|
436
437
|
throw new Error("invalid_edit_batch");
|
|
437
438
|
}
|
|
@@ -439,6 +440,7 @@ export class FileManager {
|
|
|
439
440
|
const count = operations.reduce((sum, op) => sum + (Array.isArray(op?.edits) ? op.edits.length : 0), 0);
|
|
440
441
|
if (count > MAX_BATCH_EDITS) throw new Error("too_many_batch_edits");
|
|
441
442
|
const base = await this.#resolveBatchBase(basePath);
|
|
443
|
+
if(strictPaths&&(!base||path.relative(basePath,base)!==""))throw new Error("target_changed");
|
|
442
444
|
const resolved = [];
|
|
443
445
|
const targets = new Map();
|
|
444
446
|
for (const [index, operation] of operations.entries()) {
|
|
@@ -449,6 +451,7 @@ export class FileManager {
|
|
|
449
451
|
const create = operation.op === "create";
|
|
450
452
|
const selected = await this.#batchPath(input, base, create);
|
|
451
453
|
const target = create ? selected : await this.#resolveExisting(selected);
|
|
454
|
+
if(strictPaths&&path.relative(path.resolve(base,input),target)!=="")throw new Error("target_changed");
|
|
452
455
|
const key = process.platform === "win32" ? target.toLowerCase() : target;
|
|
453
456
|
resolved.push({ row, operation, target, key });
|
|
454
457
|
targets.set(key, (targets.get(key) || 0) + 1);
|
|
@@ -495,6 +498,7 @@ export class FileManager {
|
|
|
495
498
|
updated = utf8Bytes(text, MAX_WRITE_BYTES * 8);
|
|
496
499
|
}
|
|
497
500
|
await this.#commitBatchFile(target, original, updated, mode, base);
|
|
501
|
+
recordActivityEdit(row.index,row.path,original,updated,create?"added":"modified",target);
|
|
498
502
|
results.push({ ...row, ok: true, op: operation.op, bytes: updated.length, ...(create ? {} : { replacements }) });
|
|
499
503
|
} catch (error) {
|
|
500
504
|
results.push({ ...row, ok: false, op: operation.op, error: editError(error) });
|
|
@@ -579,6 +583,7 @@ export class FileManager {
|
|
|
579
583
|
const updated = parts.join(newText);
|
|
580
584
|
if (Buffer.byteLength(updated, "utf8") > MAX_WRITE_BYTES * 8) throw new Error("file_too_large");
|
|
581
585
|
await fs.writeFile(target, updated, "utf8");
|
|
586
|
+
recordActivityEdit(0,input,text,updated,"modified",target);
|
|
582
587
|
return { path: target, replacements: matches };
|
|
583
588
|
}
|
|
584
589
|
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { createEventBuffer, fullUnavailable, hasFullSessionRequest, toolCorrelation } from "../packages/full-contracts/index.mjs";
|
|
3
|
+
|
|
4
|
+
export { fullUnavailable, hasFullSessionRequest };
|
|
5
|
+
|
|
6
|
+
// Optional best-effort IPC projection. Exactly one send is in flight; the ring
|
|
7
|
+
// bounds backlog, and a consumer sees an explicit gap after a slow/disconnected
|
|
8
|
+
// subscriber. Critical state never relies on this channel.
|
|
9
|
+
export function createCoreEventBridge({ enabled = false, send, producerEpoch = randomUUID, now = () => new Date().toISOString(), capacity } = {}) {
|
|
10
|
+
if (!enabled || typeof send !== "function") return null;
|
|
11
|
+
const epoch = producerEpoch();
|
|
12
|
+
const buffer = createEventBuffer({ producerEpoch: epoch, ...(capacity === undefined ? {} : { capacity }) });
|
|
13
|
+
let cursor = { producerEpoch: epoch, sequence: 0 };
|
|
14
|
+
let sending = false;
|
|
15
|
+
let scheduled = false;
|
|
16
|
+
let closed = false;
|
|
17
|
+
function schedule() {
|
|
18
|
+
if (closed || sending || scheduled) return;
|
|
19
|
+
scheduled = true;
|
|
20
|
+
setImmediate(flush);
|
|
21
|
+
}
|
|
22
|
+
function flush() {
|
|
23
|
+
scheduled = false;
|
|
24
|
+
if (closed || sending) return;
|
|
25
|
+
const batch = buffer.readAfter(cursor);
|
|
26
|
+
if (!batch.events.length) return;
|
|
27
|
+
sending = true;
|
|
28
|
+
let settled = false;
|
|
29
|
+
const finish = (error) => {
|
|
30
|
+
if (settled) return;
|
|
31
|
+
settled = true;
|
|
32
|
+
sending = false;
|
|
33
|
+
if (error) { closed = true; return; }
|
|
34
|
+
cursor = batch.cursor;
|
|
35
|
+
if (buffer.readAfter(cursor).events.length) schedule();
|
|
36
|
+
};
|
|
37
|
+
try { send({ type: "chat-relay-full-events", ...batch }, finish); }
|
|
38
|
+
catch (error) { finish(error); }
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
publish(type, requestId, action, observability, outcome = {}) {
|
|
42
|
+
if (closed) return;
|
|
43
|
+
// A malformed or failing observer never changes the tool result.
|
|
44
|
+
try {
|
|
45
|
+
buffer.append({ type, requestId, action, at: now(), ...toolCorrelation(observability),
|
|
46
|
+
...(typeof outcome.ok === "boolean" ? { ok: outcome.ok } : {}),
|
|
47
|
+
...(Number.isFinite(outcome.durationMs) ? { durationMs: outcome.durationMs } : {}) });
|
|
48
|
+
schedule();
|
|
49
|
+
} catch {}
|
|
50
|
+
},
|
|
51
|
+
close() { closed = true; },
|
|
52
|
+
};
|
|
53
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import {createHash,randomUUID} from "node:crypto";
|
|
2
|
+
import {FullContractError} from "../packages/full-contracts/index.mjs";
|
|
3
|
+
import {DESKTOP_BROKER_OPERATION,RESOURCE_HEALTH_OPERATION} from "../packages/full-contracts/remote-session.mjs";
|
|
4
|
+
import {AGENT_EFFECT_KEY} from "./full-job-broker.mjs";
|
|
5
|
+
const check=(ok,code)=>{if(!ok)throw new FullContractError(code);};
|
|
6
|
+
const hash=value=>createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
7
|
+
const unresolved=error=>["full_outcome_unknown","full_settlement_unknown","full_unavailable"].includes(error?.code);
|
|
8
|
+
const sameCoreReceipts=new WeakMap();
|
|
9
|
+
const timing=result=>Object.fromEntries(Object.entries(result?.timing??{}).filter(([key,value])=>
|
|
10
|
+
["queueWaitMs","inputMs","explicitWaitMs","settleMs","workerMs","managerMs","totalMs","requestedActions","executedActions"].includes(key)&&Number.isFinite(value)&&value>=0));
|
|
11
|
+
|
|
12
|
+
/** Uses the existing Core DesktopManager and scheduler. Desktop input can
|
|
13
|
+
* affect arbitrary applications/files, so it holds the same agent-wide
|
|
14
|
+
* exclusive effect claim as arbitrary shell jobs. Delivery is not app success.
|
|
15
|
+
* No screenshot, clipboard value, action text, window title or result is persisted. */
|
|
16
|
+
export async function createRemoteDesktopActions({host,artifact,scheduler,desktop,legacyBusy=()=>false}){
|
|
17
|
+
const config=desktop?.getConfig?.();
|
|
18
|
+
if(!artifact.capabilities.includes("full.desktop")||!host.operations.includes(DESKTOP_BROKER_OPERATION)||!config?.enabled||!config.supported)return null;
|
|
19
|
+
check(scheduler?.fullAdmission&&typeof desktop.listWindows==="function"&&typeof desktop.step==="function","full_capability_unavailable");
|
|
20
|
+
const held=sameCoreReceipts.get(scheduler)??new Map();sameCoreReceipts.set(scheduler,held);
|
|
21
|
+
const running=new Map();
|
|
22
|
+
let closing=false,starts=0;
|
|
23
|
+
const rpc=(invocation,kind,fields={})=>host.request(DESKTOP_BROKER_OPERATION,{invocation,kind,...fields},
|
|
24
|
+
{taskSessionId:invocation.input.taskSessionId,timeoutMs:8000,waitForSettlement:true});
|
|
25
|
+
const fields=entry=>({attemptId:entry.attemptId,requestFingerprint:entry.fingerprint});
|
|
26
|
+
async function health(){
|
|
27
|
+
const result=await host.request(RESOURCE_HEALTH_OPERATION,undefined,{timeoutMs:1000});
|
|
28
|
+
check(Number.isSafeInteger(result?.unresolved)&&result.unresolved>=0,"full_recovery_state_unknown");
|
|
29
|
+
scheduler.fullAdmission.setRecoveryBlocked(result.unresolved>0||held.size>0);
|
|
30
|
+
}
|
|
31
|
+
function fence(entry){
|
|
32
|
+
entry.lease.quarantine();held.set(entry.attemptId,entry);scheduler.fullAdmission.setRecoveryBlocked(true);
|
|
33
|
+
}
|
|
34
|
+
async function reconcile(entry){
|
|
35
|
+
if(!entry.receiptKnown)return false;
|
|
36
|
+
const prior=await rpc(entry.invocation,"lookup",fields(entry));
|
|
37
|
+
if(prior){
|
|
38
|
+
const saved=await rpc(entry.invocation,"finish",{...fields(entry),previousOwnerEpoch:entry.epoch,state:"released",notIssued:entry.notIssued});
|
|
39
|
+
check(saved?.acknowledged===true&&saved.deliveryState===(entry.notIssued?"not-dispatched":"settled"),"full_desktop_receipt_pending");
|
|
40
|
+
}else check(entry.notIssued===true,"full_desktop_intent_required");
|
|
41
|
+
// Exact same-Core receipt + authoritative durable finish/absence ACK.
|
|
42
|
+
entry.lease.confirmRequestSettled({commitConfirmed:true,ownerEpoch:entry.epoch,attemptId:entry.attemptId});
|
|
43
|
+
held.delete(entry.attemptId);await health();return true;
|
|
44
|
+
}
|
|
45
|
+
for(const entry of [...held.values()]){
|
|
46
|
+
try{await reconcile(entry);}catch{/* missing/unknown receipt stays fenced */}
|
|
47
|
+
}
|
|
48
|
+
if(held.size)scheduler.fullAdmission.setRecoveryBlocked(true);
|
|
49
|
+
async function dispatch(invocation,parsed){
|
|
50
|
+
check(!closing,"full_unavailable");
|
|
51
|
+
const {input,principal,operation}=parsed,taskSessionId=input.taskSessionId;
|
|
52
|
+
const step=operation==="full.desktop.step";
|
|
53
|
+
if(step)starts++; // Fence new legacy mutations before the first await.
|
|
54
|
+
try{
|
|
55
|
+
const binding=await rpc(invocation,"snapshot");
|
|
56
|
+
const owner={accountId:principal.accountId,agentId:principal.agentId,taskSessionId};
|
|
57
|
+
const attemptId=step?"desktop-"+hash([principal.accountId,principal.agentId,taskSessionId,input.idempotencyKey]):randomUUID();
|
|
58
|
+
const fingerprint=hash([binding.workspaceId,input.actions??null,input.settleMs??null]);
|
|
59
|
+
if(step){
|
|
60
|
+
const active=running.get(attemptId);
|
|
61
|
+
if(active){check(active.fingerprint===fingerprint,"full_idempotency_conflict");return {attemptId,deliveryState:"running",replayed:false,applicationOutcome:"not-verified"};}
|
|
62
|
+
let prior=await rpc(invocation,"lookup",{attemptId,requestFingerprint:fingerprint});
|
|
63
|
+
const receipt=held.get(attemptId);
|
|
64
|
+
if(receipt?.receiptKnown){await reconcile(receipt);prior=await rpc(invocation,"lookup",{attemptId,requestFingerprint:fingerprint});}
|
|
65
|
+
if(prior){
|
|
66
|
+
if(["settled","not-dispatched"].includes(prior.deliveryState)&&scheduler.fullAdmission.recoveryBlocked)await health();
|
|
67
|
+
const state=receipt?.notIssued&&!held.has(attemptId)?"not-dispatched":prior.deliveryState;
|
|
68
|
+
return {attemptId,deliveryState:state,replayed:false,resultRetained:false,applicationOutcome:"not-verified"};
|
|
69
|
+
}
|
|
70
|
+
check(!legacyBusy(),"full_legacy_effect_active");
|
|
71
|
+
}
|
|
72
|
+
check(!scheduler.fullAdmission.recoveryBlocked,"full_recovery_state_unknown");
|
|
73
|
+
if(step)check(!["completed","cancelled"].includes(binding.status),"full_session_terminal");
|
|
74
|
+
const claims=[{key:AGENT_EFFECT_KEY,mode:step?"exclusive":"read"},{key:"desktop:agent",mode:step?"exclusive":"read"},{key:"workspace:"+binding.workspaceId,mode:"read"}];
|
|
75
|
+
return await scheduler.runFull("desktop.window.list",async(_meta,lease)=>{
|
|
76
|
+
check(!closing,"full_unavailable");
|
|
77
|
+
const current=await rpc(invocation,"snapshot");
|
|
78
|
+
check(current.workspaceId===binding.workspaceId,"full_workspace_conflict");
|
|
79
|
+
if(!step){
|
|
80
|
+
const result=await desktop.listWindows({limit:input.limit??32});
|
|
81
|
+
check(result?.ok===true&&Array.isArray(result.windows),"full_desktop_unavailable");
|
|
82
|
+
return {workspaceId:binding.workspaceId,windows:result.windows.slice(0,input.limit??32).map(row=>({
|
|
83
|
+
windowId:String(row.windowId).slice(0,128),processId:row.processId,title:String(row.title).slice(0,512),
|
|
84
|
+
x:row.x,y:row.y,width:row.width,height:row.height,isForeground:row.isForeground===true
|
|
85
|
+
})),provenance:"core-desktop-observation"};
|
|
86
|
+
}
|
|
87
|
+
check(!legacyBusy(),"full_legacy_effect_active");
|
|
88
|
+
check(!["completed","cancelled"].includes(current.status),"full_session_terminal");
|
|
89
|
+
const entry={invocation,attemptId,fingerprint,epoch:host.ownerEpoch,lease,receiptKnown:false,notIssued:true};
|
|
90
|
+
running.set(attemptId,entry);
|
|
91
|
+
let reserved=false;
|
|
92
|
+
try{
|
|
93
|
+
let saved;
|
|
94
|
+
try{saved=await rpc(invocation,"reserve",{...fields(entry),claims:lease.snapshot().claims});}
|
|
95
|
+
catch(error){if(unresolved(error)){entry.receiptKnown=true;fence(entry);}throw error;}
|
|
96
|
+
if(saved?.acknowledged!==true||typeof saved.accepted!=="boolean"){entry.receiptKnown=true;fence(entry);throw new FullContractError("full_desktop_intent_unsaved");}
|
|
97
|
+
if(saved.accepted!==true)return {attemptId,deliveryState:"previously-accepted",replayed:false,applicationOutcome:"not-verified"};
|
|
98
|
+
reserved=true;entry.notIssued=false;
|
|
99
|
+
let result;
|
|
100
|
+
try{result=await desktop.step({actions:input.actions,settleMs:input.settleMs,captureAfter:false});}
|
|
101
|
+
catch{fence(entry);throw new FullContractError("full_desktop_outcome_unknown");}
|
|
102
|
+
// Only the actual worker's successful reply proves input delivery.
|
|
103
|
+
// An arbitrary error, timeout or process exit does not prove no effect.
|
|
104
|
+
if(result?.ok!==true){
|
|
105
|
+
fence(entry);
|
|
106
|
+
try{await rpc(invocation,"finish",{...fields(entry),previousOwnerEpoch:entry.epoch,state:"quarantined"});}catch{}
|
|
107
|
+
throw new FullContractError("full_desktop_outcome_unknown");
|
|
108
|
+
}
|
|
109
|
+
entry.receiptKnown=true;
|
|
110
|
+
try{
|
|
111
|
+
const finished=await rpc(invocation,"finish",{...fields(entry),previousOwnerEpoch:entry.epoch,state:"released"});
|
|
112
|
+
check(finished?.acknowledged===true&&finished.deliveryState==="settled","full_desktop_receipt_pending");
|
|
113
|
+
}catch{fence(entry);throw new FullContractError("full_desktop_receipt_pending");}
|
|
114
|
+
return {attemptId,deliveryState:"completed",replayed:false,applicationOutcome:"not-verified",timing:timing(result)};
|
|
115
|
+
}catch(error){
|
|
116
|
+
if(reserved&&!entry.receiptKnown&&!held.has(attemptId))fence(entry);
|
|
117
|
+
throw error;
|
|
118
|
+
}finally{running.delete(attemptId);}
|
|
119
|
+
},{owner,ownerEpoch:host.ownerEpoch,attemptId,claims,priority:"task",dependenciesReady:true,queueTimeoutMs:8000});
|
|
120
|
+
}finally{if(step)starts--;}
|
|
121
|
+
}
|
|
122
|
+
return Object.freeze({dispatch,capabilities:["full.desktop"],blocksLegacyEffects:()=>starts>0||running.size>0||held.size>0,
|
|
123
|
+
close(){closing=true;return held.size===0;}});
|
|
124
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import {randomUUID} from "node:crypto";
|
|
2
|
+
import {FullContractError} from "../packages/full-contracts/index.mjs";
|
|
3
|
+
|
|
4
|
+
const valid=p=>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.length<=3&&p.scopes.every(s=>["read","write","terminal"].includes(s));
|
|
5
|
+
const denied=()=>new FullContractError("full_desktop_authorization_unavailable");
|
|
6
|
+
// Private inherited process IPC only. The GUI and Core never receive the
|
|
7
|
+
// user's server credential. Fresh user-initiated GUI actions check current
|
|
8
|
+
// grants; ordinary remote tool requests keep the existing authorization path.
|
|
9
|
+
export function attachDesktopAuthorization(child,{principal,authenticate}){
|
|
10
|
+
if(!valid(principal)||typeof authenticate!=="function")throw denied();
|
|
11
|
+
let pending=0,closed=false;
|
|
12
|
+
const send=value=>{if(!closed&&child.connected)try{child.send(value,()=>{});}catch{}};
|
|
13
|
+
const listener=async message=>{
|
|
14
|
+
if(message?.type!=="chat-relay-full-authorize"||typeof message.requestId!=="string"||!/^[a-f0-9-]{36}$/.test(message.requestId))return;
|
|
15
|
+
const requestId=message.requestId;
|
|
16
|
+
if(closed||pending>=2){send({type:"chat-relay-full-authorized",requestId,ok:false});return;}
|
|
17
|
+
pending++;
|
|
18
|
+
try{
|
|
19
|
+
const fresh=await authenticate();
|
|
20
|
+
if(!valid(fresh)||fresh.accountId!==principal.accountId||fresh.agentId!==principal.agentId)throw denied();
|
|
21
|
+
const scopes=fresh.scopes.filter(scope=>principal.scopes.includes(scope));
|
|
22
|
+
if(!scopes.includes("read"))throw denied();
|
|
23
|
+
send({type:"chat-relay-full-authorized",requestId,ok:true,principal:{accountId:principal.accountId,agentId:principal.agentId,scopes}});
|
|
24
|
+
}catch{send({type:"chat-relay-full-authorized",requestId,ok:false});}
|
|
25
|
+
finally{pending--;}
|
|
26
|
+
};
|
|
27
|
+
child.on("message",listener);
|
|
28
|
+
return ()=>{closed=true;child.removeListener("message",listener);};
|
|
29
|
+
}
|
|
30
|
+
export function createParentAuthorizationClient(channel=process){
|
|
31
|
+
const pending=new Map();let closed=false;
|
|
32
|
+
const listener=message=>{
|
|
33
|
+
if(message?.type!=="chat-relay-full-authorized")return;
|
|
34
|
+
const entry=pending.get(message.requestId);if(!entry)return;
|
|
35
|
+
pending.delete(message.requestId);clearTimeout(entry.timer);
|
|
36
|
+
if(message.ok===true&&valid(message.principal))entry.resolve(message.principal);else entry.reject(denied());
|
|
37
|
+
};
|
|
38
|
+
function close(){
|
|
39
|
+
if(closed)return;closed=true;
|
|
40
|
+
channel.removeListener("message",listener);channel.removeListener("disconnect",close);
|
|
41
|
+
for(const entry of pending.values()){clearTimeout(entry.timer);entry.reject(denied());}pending.clear();
|
|
42
|
+
}
|
|
43
|
+
channel.on("message",listener);channel.once("disconnect",close);
|
|
44
|
+
return {close,authorize:()=>{
|
|
45
|
+
if(closed||!channel.connected||typeof channel.send!=="function"||pending.size>=2)return Promise.reject(denied());
|
|
46
|
+
return new Promise((resolve,reject)=>{
|
|
47
|
+
const requestId=randomUUID(),timer=setTimeout(()=>{pending.delete(requestId);reject(denied());},8000);
|
|
48
|
+
const fail=()=>{const e=pending.get(requestId);if(e){pending.delete(requestId);clearTimeout(e.timer);e.reject(denied());}};
|
|
49
|
+
pending.set(requestId,{timer,resolve,reject});
|
|
50
|
+
try{channel.send({type:"chat-relay-full-authorize",requestId},error=>{if(error)fail();});}catch{fail();}
|
|
51
|
+
});
|
|
52
|
+
}};
|
|
53
|
+
}
|