@anusornneal/chat-relay 2.0.1 → 2.2.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 +3 -1
- package/agent/activity-capture.mjs +176 -14
- package/agent/auto-session-binding.mjs +46 -0
- package/agent/file-manager.mjs +26 -6
- package/agent/full-coding-prepare.mjs +40 -0
- package/agent/full-desktop-broker.mjs +101 -21
- package/agent/full-remote-diagnostics.mjs +1 -1
- package/agent/full-session-dispatch.mjs +10 -3
- package/agent/full-workspace-broker.mjs +1 -1
- package/agent/git-worktree-manager.mjs +2 -1
- package/agent/local-agent.mjs +43 -5
- package/agent/local-usage.mjs +8 -0
- package/agent/monitor-activity.mjs +101 -18
- package/agent/presentation-redaction.mjs +1 -10
- package/agent/toolcall-context.mjs +43 -1
- package/agent/toolcall-summary.mjs +1 -1
- package/cli/full-launch.mjs +4 -22
- package/cli/full-release-default.json +2 -2
- package/cli/index.mjs +2 -2
- package/cli/remote.mjs +2 -2
- package/package.json +1 -1
- package/packages/full-contracts/auto-session.mjs +14 -0
- package/packages/full-contracts/monitor-metadata.mjs +28 -0
- package/packages/full-contracts/presentation-redaction.mjs +16 -0
- package/packages/full-contracts/remote-session.mjs +21 -2
package/README.md
CHANGED
|
@@ -337,4 +337,6 @@ are needed for these improvements.
|
|
|
337
337
|
|
|
338
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
339
|
|
|
340
|
-
|
|
340
|
+
Full groups authorized ordinary tool activity automatically when the MCP client provides a conversation identifier. Sessions are local, durable metadata; no worktree is created by starting a session. Git workspace binding uses the existing registered worktree by default; request isolated mode explicitly for a new worktree. Calls without reliable conversation metadata remain unassigned. Legacy calls remain legacy operations; Full intelligence, owned jobs and checkpoints are explicit.
|
|
341
|
+
|
|
342
|
+
Full always uses the official artifact matching its Core version. Legacy local release settings are ignored; no migration or user configuration is required. Existing login and session data are preserved. An incompatible or unavailable Full artifact never silently starts Lite.
|
|
@@ -1,10 +1,17 @@
|
|
|
1
1
|
import {AsyncLocalStorage} from "node:async_hooks";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import {constants} from "node:fs";
|
|
2
4
|
import path from "node:path";
|
|
3
5
|
import {redactPresentationText} from "./presentation-redaction.mjs";
|
|
6
|
+
import {observedCommitSubject} from "./toolcall-context.mjs";
|
|
4
7
|
import {presentationChangePath} from "./full-presentation-changes.mjs";
|
|
5
8
|
|
|
6
9
|
const storage=new AsyncLocalStorage();
|
|
7
10
|
const MAX_FILES=20,MAX_PAIR_BYTES=32*1024,MAX_CALL_BYTES=64*1024,MAX_LINES=400,MAX_DIFF_CHARS=12000;
|
|
11
|
+
// Large-file edits already have before/after in memory. Scan a bounded amount,
|
|
12
|
+
// retain only a compact exact diff, and keep the existing retained-byte budget.
|
|
13
|
+
const MAX_SCAN_PAIR_BYTES=2*1024*1024,MAX_SCAN_CALL_BYTES=4*1024*1024;
|
|
14
|
+
const MAX_SCAN_LINES=20000,MAX_EDIT_DISTANCE=256,MAX_DIFF_STEPS=1000000;
|
|
8
15
|
const safeError=value=>typeof value==="string"&&/^[A-Za-z][A-Za-z0-9_:-]{1,95}$/.test(value)?value:"";
|
|
9
16
|
const safeInteger=value=>Number.isSafeInteger(value)&&value>=0?value:null;
|
|
10
17
|
const decode=value=>{
|
|
@@ -54,11 +61,39 @@ export function captureActivityFor(payload){
|
|
|
54
61
|
return detailActions.has(action)?createActivityCapture():null;
|
|
55
62
|
}
|
|
56
63
|
export function createActivityCapture(){
|
|
57
|
-
return {files:new Map(),bytes:0,closed:false};
|
|
64
|
+
return {files:new Map(),bytes:0,scanBytes:0,closed:false};
|
|
58
65
|
}
|
|
59
66
|
export function runActivityCapture(capture,work){
|
|
60
67
|
return capture?storage.run(capture,work):work();
|
|
61
68
|
}
|
|
69
|
+
// Only Full monitoring requests read a bounded before-image.
|
|
70
|
+
export async function captureActivityBefore(requestedPath,target,afterBytes=0,append=false){
|
|
71
|
+
const context=storage.getStore();
|
|
72
|
+
if(!context||context.closed||context.files.size>=MAX_FILES||
|
|
73
|
+
!displayActivityPath(requestedPath)||!displayActivityPath(target))return undefined;
|
|
74
|
+
const limit=Math.min(MAX_PAIR_BYTES,MAX_CALL_BYTES-context.bytes)-afterBytes;
|
|
75
|
+
const max=append?Math.floor(limit/2):limit;
|
|
76
|
+
if(max<0)return undefined;
|
|
77
|
+
let handle;
|
|
78
|
+
try{
|
|
79
|
+
const initial=await fs.lstat(target);
|
|
80
|
+
if(!initial.isFile()||initial.isSymbolicLink()||initial.size>max)return undefined;
|
|
81
|
+
handle=await fs.open(target,constants.O_RDONLY|(constants.O_NOFOLLOW??0));
|
|
82
|
+
const before=await handle.stat();
|
|
83
|
+
if(!before.isFile()||before.dev!==initial.dev||before.ino!==initial.ino||before.size>max)return undefined;
|
|
84
|
+
const buffer=Buffer.alloc(before.size+1);
|
|
85
|
+
let total=0;
|
|
86
|
+
while(total<buffer.length){
|
|
87
|
+
const {bytesRead}=await handle.read(buffer,total,buffer.length-total,total);
|
|
88
|
+
if(!bytesRead)break;
|
|
89
|
+
total+=bytesRead;
|
|
90
|
+
}
|
|
91
|
+
const after=await handle.stat();
|
|
92
|
+
if(total!==before.size||after.size!==before.size||after.mtimeMs!==before.mtimeMs||after.ctimeMs!==before.ctimeMs)return undefined;
|
|
93
|
+
return buffer.subarray(0,total);
|
|
94
|
+
}catch{return undefined;}
|
|
95
|
+
finally{await handle?.close().catch(()=>{});}
|
|
96
|
+
}
|
|
62
97
|
export function recordActivityEdit(index,requestedPath,before,after,kind,canonicalTarget){
|
|
63
98
|
const context=storage.getStore();
|
|
64
99
|
if(!context||context.closed||context.files.size>=MAX_FILES)return;
|
|
@@ -66,23 +101,125 @@ export function recordActivityEdit(index,requestedPath,before,after,kind,canonic
|
|
|
66
101
|
try{
|
|
67
102
|
const name=displayActivityPath(requestedPath);
|
|
68
103
|
if(!name||!displayActivityPath(canonicalTarget))return;
|
|
69
|
-
const entry={path:name,kind,pair:null};
|
|
104
|
+
const entry={path:name,kind,pair:null,diffReason:"Text not captured"};
|
|
70
105
|
context.files.set(index,entry);
|
|
71
106
|
if(before===undefined||after===undefined)return;
|
|
72
107
|
const size=(before===null?0:Buffer.byteLength(before))+(after===null?0:Buffer.byteLength(after));
|
|
73
|
-
|
|
108
|
+
const budget=Math.min(MAX_PAIR_BYTES,MAX_CALL_BYTES-context.bytes);
|
|
109
|
+
entry.diffReason="Change exceeds capture limit";
|
|
110
|
+
const large=size>budget;
|
|
111
|
+
if(budget<=128||size>MAX_SCAN_PAIR_BYTES||large&&(kind!=="modified"||context.scanBytes+size>MAX_SCAN_CALL_BYTES))return;
|
|
112
|
+
// Count attempted large scans, even when decoding or redaction rejects them.
|
|
113
|
+
if(large)context.scanBytes+=size;
|
|
74
114
|
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"))
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
115
|
+
if(a===null||b===null||!a.isWellFormed()||!b.isWellFormed()||a.includes("\0")||b.includes("\0")||a.includes("\uFFFD")||b.includes("\uFFFD")){
|
|
116
|
+
entry.diffReason="Not valid text";return;
|
|
117
|
+
}
|
|
118
|
+
if(redactPresentationText(a,a.length)!==a||redactPresentationText(b,b.length)!==b){
|
|
119
|
+
entry.diffReason="Protected content";return;
|
|
120
|
+
}
|
|
121
|
+
if(size<=budget&&a.split("\n").length<=MAX_LINES&&b.split("\n").length<=MAX_LINES){
|
|
122
|
+
entry.pair={before:a,after:b};
|
|
123
|
+
context.bytes+=size;
|
|
124
|
+
}else if(kind==="modified"&&(large||context.scanBytes+size<=MAX_SCAN_CALL_BYTES)){
|
|
125
|
+
if(!large)context.scanBytes+=size;
|
|
126
|
+
const diff=compactHistoricalDiff(a,b,budget-128);
|
|
127
|
+
if(!diff)return;
|
|
128
|
+
entry.pair={diff};
|
|
129
|
+
context.bytes+=Buffer.byteLength(diff.text)+128;
|
|
130
|
+
}else return;
|
|
131
|
+
delete entry.diffReason;
|
|
80
132
|
}catch{/* Optional monitor only. */}
|
|
81
133
|
}
|
|
82
134
|
// Exact bounded line edit script from the recorded pair. Retain newline
|
|
83
135
|
// characters in the comparison so final-newline and CRLF changes are real.
|
|
84
136
|
function splitLines(value){return value.match(/[^\n]*\n|[^\n]+$/g)??[];}
|
|
85
|
-
|
|
137
|
+
function boundedLines(value){
|
|
138
|
+
const lines=[];
|
|
139
|
+
for(const match of value.matchAll(/[^\n]*\n|[^\n]+$/g)){
|
|
140
|
+
if(lines.length>=MAX_SCAN_LINES)return null;
|
|
141
|
+
lines.push(match[0]);
|
|
142
|
+
}
|
|
143
|
+
return lines;
|
|
144
|
+
}
|
|
145
|
+
// Bounded Myers edit script. Unlike a full-file LCS matrix, sparse edits in
|
|
146
|
+
// large files have work proportional to the edit distance, including distant
|
|
147
|
+
// changes. Store only the changed coordinates and a few surrounding lines.
|
|
148
|
+
function compactHistoricalDiff(before,after,byteBudget){
|
|
149
|
+
const a=boundedLines(before),b=boundedLines(after);
|
|
150
|
+
if(!a||!b)return null;
|
|
151
|
+
let start=0,ae=a.length,be=b.length;
|
|
152
|
+
while(start<ae&&start<be&&a[start]===b[start])start++;
|
|
153
|
+
while(ae>start&&be>start&&a[ae-1]===b[be-1]){ae--;be--;}
|
|
154
|
+
const n=ae-start,m=be-start;
|
|
155
|
+
if(!n&&!m)return {state:"ready",additions:0,deletions:0,text:"No textual changes",truncated:false};
|
|
156
|
+
if(Math.abs(n-m)>MAX_EDIT_DISTANCE)return null;
|
|
157
|
+
const offset=MAX_EDIT_DISTANCE+1,v=new Int32Array(2*offset+1).fill(-1),trace=[];
|
|
158
|
+
v[offset+1]=0;
|
|
159
|
+
let distance=-1,steps=MAX_DIFF_STEPS;
|
|
160
|
+
for(let d=0;d<=MAX_EDIT_DISTANCE&&distance<0;d++){
|
|
161
|
+
trace.push(v.slice());
|
|
162
|
+
for(let k=-d;k<=d;k+=2){
|
|
163
|
+
if(--steps<0)return null;
|
|
164
|
+
let x=k===-d||k!==d&&v[offset+k-1]<v[offset+k+1]?v[offset+k+1]:v[offset+k-1]+1;
|
|
165
|
+
let y=x-k;
|
|
166
|
+
while(x<n&&y<m&&a[start+x]===b[start+y]){
|
|
167
|
+
if(--steps<0)return null;
|
|
168
|
+
x++;y++;
|
|
169
|
+
}
|
|
170
|
+
v[offset+k]=x;
|
|
171
|
+
if(x===n&&y===m){distance=d;break;}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
if(distance<0)return null;
|
|
175
|
+
const edits=[];
|
|
176
|
+
let x=n,y=m,additions=0,deletions=0;
|
|
177
|
+
for(let d=distance;d>0;d--){
|
|
178
|
+
const prev=trace[d],k=x-y;
|
|
179
|
+
const pk=k===-d||k!==d&&prev[offset+k-1]<prev[offset+k+1]?k+1:k-1;
|
|
180
|
+
const px=prev[offset+pk],py=px-pk,op=pk===k+1?"+":"-";
|
|
181
|
+
const i=start+px,j=start+py,line=op==="+"?b[j]:a[i];
|
|
182
|
+
if(line===undefined||line.length>=MAX_DIFF_CHARS)return null;
|
|
183
|
+
edits.push({i,j,op});
|
|
184
|
+
if(op==="+")additions++;else deletions++;
|
|
185
|
+
x=px;y=py;
|
|
186
|
+
}
|
|
187
|
+
edits.reverse();
|
|
188
|
+
const parts=[];
|
|
189
|
+
let chars=0,bytes=0,truncated=false,shownChanges=0;
|
|
190
|
+
const emit=value=>{
|
|
191
|
+
if(truncated)return false;
|
|
192
|
+
const extra=parts.length?1:0,size=Buffer.byteLength(value)+extra;
|
|
193
|
+
if(chars+value.length+extra>MAX_DIFF_CHARS||bytes+size>byteBudget){truncated=true;return false;}
|
|
194
|
+
parts.push(value);chars+=value.length+extra;bytes+=size;return true;
|
|
195
|
+
};
|
|
196
|
+
const line=(op,value)=>emit(op+value.replace(/\r?\n$/,"")+(value.endsWith("\n")?"":"\n\"));
|
|
197
|
+
const endOld=e=>e.i+(e.op==="-"?1:0),endNew=e=>e.j+(e.op==="+"?1:0);
|
|
198
|
+
for(let first=0;first<edits.length&&!truncated;){
|
|
199
|
+
let last=first;
|
|
200
|
+
while(last+1<edits.length&&edits[last+1].i-endOld(edits[last])<=6)last++;
|
|
201
|
+
const f=edits[first],l=edits[last],pre=Math.min(3,f.i,f.j);
|
|
202
|
+
let i=f.i-pre,j=f.j-pre;
|
|
203
|
+
const post=Math.min(3,a.length-endOld(l),b.length-endNew(l));
|
|
204
|
+
const stopI=endOld(l)+post,stopJ=endNew(l)+post,oldCount=stopI-i,newCount=stopJ-j;
|
|
205
|
+
emit("@@ -"+(oldCount?i+1:i)+","+oldCount+" +"+(newCount?j+1:j)+","+newCount+" @@");
|
|
206
|
+
for(let k=first;k<=last&&!truncated;k++){
|
|
207
|
+
const e=edits[k];
|
|
208
|
+
while(i<e.i&&!truncated){line(" ",a[i++]);j++;}
|
|
209
|
+
if(e.op==="+"){if(line("+",b[j++]))shownChanges++;}
|
|
210
|
+
else if(line("-",a[i++]))shownChanges++;
|
|
211
|
+
}
|
|
212
|
+
while(i<stopI&&!truncated){line(" ",a[i++]);j++;}
|
|
213
|
+
first=last+1;
|
|
214
|
+
}
|
|
215
|
+
if(!shownChanges)return null;
|
|
216
|
+
return {state:"ready",additions,deletions,text:parts.join("\n"),truncated};
|
|
217
|
+
}
|
|
218
|
+
export function historicalDiff(pair,{includeText=true,maxCells=Infinity}={}){
|
|
219
|
+
if(pair?.diff){
|
|
220
|
+
const {state,additions,deletions}=pair.diff;
|
|
221
|
+
return includeText?pair.diff:{state,additions,deletions};
|
|
222
|
+
}
|
|
86
223
|
if(!pair)return {state:"unavailable",reason:"No captured text for this call",additions:null,deletions:null,text:""};
|
|
87
224
|
const a=splitLines(pair.before),b=splitLines(pair.after);
|
|
88
225
|
if(a.length>MAX_LINES||b.length>MAX_LINES)return {state:"unavailable",reason:"Change exceeds capture limit",additions:null,deletions:null,text:""};
|
|
@@ -91,7 +228,9 @@ export function historicalDiff(pair,{includeText=true}={}){
|
|
|
91
228
|
let start=0,ae=a.length,be=b.length;
|
|
92
229
|
while(start<ae&&start<be&&a[start]===b[start])start++;
|
|
93
230
|
while(ae>start&&be>start&&a[ae-1]===b[be-1]){ae--;be--;}
|
|
94
|
-
const width=be-start+1,
|
|
231
|
+
const width=be-start+1,cells=(ae-start+1)*width;
|
|
232
|
+
if(cells>maxCells)return {state:"unavailable",reason:"Summary budget exceeded",additions:null,deletions:null,text:""};
|
|
233
|
+
const dp=new Uint16Array(cells);
|
|
95
234
|
const cell=(i,j)=>(i-start)*width+j-start;
|
|
96
235
|
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
236
|
const lines=includeText?a.slice(0,start).map(line=>[" ",line]):[];
|
|
@@ -126,7 +265,8 @@ export function finishActivityCapture(capture,payload,result){
|
|
|
126
265
|
if(files.length>=MAX_FILES){omitted++;return;}
|
|
127
266
|
const captured=capture.files.get(index),name=captured?.path||displayActivityPath(source);
|
|
128
267
|
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
|
|
268
|
+
files.push({fileId:String(index),path:name,kind:captured?.kind??kind,outcome,error:safeError(error),pair:outcome==="completed"?captured?.pair??null:null,
|
|
269
|
+
...(outcome==="completed"&&captured?.diffReason?{diffReason:captured.diffReason}:{})});
|
|
130
270
|
};
|
|
131
271
|
const edit=action==="fs.editMany"||action==="full.workspace.edit";
|
|
132
272
|
if(edit){
|
|
@@ -152,14 +292,36 @@ export function finishActivityCapture(capture,payload,result){
|
|
|
152
292
|
// Bounded display metadata only. No raw commands, output, Learn values,
|
|
153
293
|
// or arbitrary response objects. Search terms use display redaction.
|
|
154
294
|
const search=describeLocalSearch(payload);
|
|
155
|
-
const
|
|
156
|
-
|
|
295
|
+
const commitSubject=["terminal.exec","terminal.exec.compact"].includes(action)&&result?.ok!==false&&output?.exitCode===0?observedCommitSubject(input.command,output.stdout):"";
|
|
296
|
+
const details={files,omitted,...search,...(commitSubject?{commitSubject}:{}),exitCode:Number.isInteger(output?.exitCode)?output.exitCode:null,resultCount:safeInteger(output?.totalResults??output?.total),error:safeError(result?.error)};
|
|
297
|
+
return files.length||omitted||commitSubject||details.query||details.searchScope||(details.exitCode!==null&&details.exitCode!==0)||details.resultCount!==null?details:null;
|
|
298
|
+
}
|
|
299
|
+
const summaryCache=new WeakMap();
|
|
300
|
+
function changeStats(pair,maxCells=Infinity){
|
|
301
|
+
if(!pair)return historicalDiff(null,{includeText:false});
|
|
302
|
+
const cached=summaryCache.get(pair);
|
|
303
|
+
if(cached)return cached;
|
|
304
|
+
const stats=historicalDiff(pair,{includeText:false,maxCells});
|
|
305
|
+
if(stats.state==="ready")summaryCache.set(pair,stats);
|
|
306
|
+
return stats;
|
|
307
|
+
}
|
|
308
|
+
// Calculate small exact summaries only once; larger rewrites remain lazy.
|
|
309
|
+
export function activityChangeTotals(details){
|
|
310
|
+
if(!details?.files?.length||details.omitted)return null;
|
|
311
|
+
let additions=0,deletions=0;
|
|
312
|
+
for(const file of details.files){
|
|
313
|
+
if(!["added","modified","deleted","written"].includes(file.kind)||file.outcome!=="completed")return null;
|
|
314
|
+
const stats=changeStats(file.pair,4096);
|
|
315
|
+
if(stats.state!=="ready")return null;
|
|
316
|
+
additions+=stats.additions;deletions+=stats.deletions;
|
|
317
|
+
}
|
|
318
|
+
return {additions,deletions};
|
|
157
319
|
}
|
|
158
320
|
export function projectActivityDetails(details){
|
|
159
321
|
if(!details)return {files:[],available:false};
|
|
160
322
|
return {available:true,omitted:details.omitted??0,query:details.query??"",searchScope:details.searchScope??"",exitCode:details.exitCode,resultCount:details.resultCount,error:details.error,
|
|
161
323
|
files:details.files.map(({pair,...file})=>{
|
|
162
|
-
const stats=
|
|
324
|
+
const stats=changeStats(pair);
|
|
163
325
|
return {...file,diffAvailable:stats.state==="ready",additions:stats.additions,deletions:stats.deletions};
|
|
164
326
|
})};
|
|
165
327
|
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import {createAuthorizedFullInvocation} from "../packages/full-contracts/remote-session.mjs";
|
|
2
|
+
import {validAutomaticSessionContext} from "../packages/full-contracts/auto-session.mjs";
|
|
3
|
+
|
|
4
|
+
// This cache does not grant access to any file or effect. The Worker has already
|
|
5
|
+
// checked read+write for the enclosing call; the local host owns the durable
|
|
6
|
+
// session. A stable idempotency key reuses the same session after Core restart.
|
|
7
|
+
const MAX_BINDINGS=128,MAX_PENDING=16;
|
|
8
|
+
const validId=value=>typeof value==="string"&&/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value);
|
|
9
|
+
export function createAutomaticSessionBinding({agentId,dispatch,available=()=>true}){
|
|
10
|
+
const cached=new Map(),pending=new Map();
|
|
11
|
+
const keyOf=context=>JSON.stringify([context.accountId,context.activityId]);
|
|
12
|
+
const touch=(key,value)=>{
|
|
13
|
+
cached.delete(key);cached.set(key,value);
|
|
14
|
+
while(cached.size>MAX_BINDINGS)cached.delete(cached.keys().next().value);
|
|
15
|
+
};
|
|
16
|
+
function lookup(context){
|
|
17
|
+
if(!validAutomaticSessionContext(context)||!available())return null;
|
|
18
|
+
const key=keyOf(context),prior=cached.get(key);
|
|
19
|
+
if(!prior)return null;
|
|
20
|
+
touch(key,prior);return prior.id;
|
|
21
|
+
}
|
|
22
|
+
async function resolve(context){
|
|
23
|
+
if(!validAutomaticSessionContext(context)||!available())return null;
|
|
24
|
+
const prior=lookup(context);if(prior)return prior;
|
|
25
|
+
const key=keyOf(context);
|
|
26
|
+
if(pending.has(key))return pending.get(key);
|
|
27
|
+
if(pending.size>=MAX_PENDING)return null;
|
|
28
|
+
const {accountId,activityId}=context;
|
|
29
|
+
const work=Promise.resolve().then(async()=>{
|
|
30
|
+
const invocation=createAuthorizedFullInvocation({operation:"full.session.ensure",input:{
|
|
31
|
+
intent:"create",idempotencyKey:"auto-chat-"+activityId,title:"Chat "+activityId.slice(-8)
|
|
32
|
+
}},{accountId,agentId});
|
|
33
|
+
const result=await dispatch(invocation);
|
|
34
|
+
const session=result?.result?.session;
|
|
35
|
+
if(result?.ok!==true||result.result.acknowledged!==true||!validId(session?.taskSessionId)||
|
|
36
|
+
session.accountId!==accountId||session.agentId!==agentId)return null;
|
|
37
|
+
touch(key,{id:session.taskSessionId,accountId});return session.taskSessionId;
|
|
38
|
+
}).catch(()=>null).finally(()=>pending.delete(key));
|
|
39
|
+
pending.set(key,work);
|
|
40
|
+
return work;
|
|
41
|
+
}
|
|
42
|
+
function forget(accountId,taskSessionId){
|
|
43
|
+
for(const [key,row] of cached)if(row.accountId===accountId&&row.id===taskSessionId)cached.delete(key);
|
|
44
|
+
}
|
|
45
|
+
return Object.freeze({lookup,resolve,forget});
|
|
46
|
+
}
|
package/agent/file-manager.mjs
CHANGED
|
@@ -2,7 +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
|
+
import {captureActivityBefore,recordActivityEdit} from "./activity-capture.mjs";
|
|
6
6
|
|
|
7
7
|
const MAX_READ_BYTES = 256 * 1024;
|
|
8
8
|
const DEFAULT_READ_RESPONSE_BYTES = 32 * 1024;
|
|
@@ -561,10 +561,26 @@ export class FileManager {
|
|
|
561
561
|
if (typeof content !== "string" || Buffer.byteLength(content, "utf8") > MAX_WRITE_BYTES) {
|
|
562
562
|
throw new Error("content_too_large");
|
|
563
563
|
}
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
564
|
+
if (mode !== "append" && mode !== "rewrite") throw new Error("invalid_write_mode");
|
|
565
|
+
let target, created = false;
|
|
566
|
+
// Authorize existing symlink destinations and new canonical parents.
|
|
567
|
+
try { target = await this.#resolveExisting(input); }
|
|
568
|
+
catch (error) {
|
|
569
|
+
if (error?.code !== "ENOENT") throw error;
|
|
570
|
+
const requested = path.resolve(String(input));
|
|
571
|
+
try { await fs.lstat(requested); throw new Error("target_changed"); }
|
|
572
|
+
catch (e) { if (e?.code !== "ENOENT") throw e; }
|
|
573
|
+
const parent = await this.#resolveExisting(path.dirname(requested));
|
|
574
|
+
target = path.join(parent, path.basename(requested));
|
|
575
|
+
created = true;
|
|
576
|
+
}
|
|
577
|
+
const append = mode === "append";
|
|
578
|
+
const before = created ? null : await captureActivityBefore(input,target,Buffer.byteLength(content,"utf8"),append);
|
|
579
|
+
// Do not misreport a concurrent creator as our own creation.
|
|
580
|
+
await fs.writeFile(target,content,{encoding:"utf8",flag:created?"wx":append?"a":"w"});
|
|
581
|
+
const after = before === undefined ? undefined : append && before !== null
|
|
582
|
+
? Buffer.concat([before,Buffer.from(content,"utf8")]) : content;
|
|
583
|
+
recordActivityEdit(0,input,before,after,created?"added":"modified",target);
|
|
568
584
|
return this.stat(target);
|
|
569
585
|
}
|
|
570
586
|
|
|
@@ -607,7 +623,11 @@ export class FileManager {
|
|
|
607
623
|
}
|
|
608
624
|
const info = await fs.stat(target);
|
|
609
625
|
if (info.isDirectory()) await fs.rm(target, { recursive: Boolean(recursive), force: false });
|
|
610
|
-
else
|
|
626
|
+
else {
|
|
627
|
+
const before=info.isFile()?await captureActivityBefore(input,target):undefined;
|
|
628
|
+
await fs.unlink(target);
|
|
629
|
+
recordActivityEdit(0,input,before,null,"deleted",target);
|
|
630
|
+
}
|
|
611
631
|
return { ok: true, path: target };
|
|
612
632
|
}
|
|
613
633
|
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import {createAuthorizedFullInvocation} from "../packages/full-contracts/remote-session.mjs";
|
|
2
|
+
|
|
3
|
+
// One Relay request, existing Core/host authorities and admission boundaries.
|
|
4
|
+
// A confirmed earlier stage is deliberately preserved if a later one fails.
|
|
5
|
+
export async function prepareCodingTask({input,principal},dispatch){
|
|
6
|
+
let taskSessionId=input.taskSessionId,workspace,intelligence;
|
|
7
|
+
const completed=[];
|
|
8
|
+
const call=(operation,fields)=>dispatch(createAuthorizedFullInvocation({operation,input:fields},principal));
|
|
9
|
+
const blocked=(stage,error)=>({ok:false,error:error??"full_coding_prepare_failed",result:{
|
|
10
|
+
state:"blocked",stage,completed,...(taskSessionId?{taskSessionId}:{}),
|
|
11
|
+
...(workspace?{workspace}:{}),...(intelligence?{intelligence}:{})
|
|
12
|
+
}});
|
|
13
|
+
if(!taskSessionId){
|
|
14
|
+
const result=await call("full.session.ensure",{
|
|
15
|
+
intent:"create",idempotencyKey:input.idempotencyKey,
|
|
16
|
+
...(input.title===undefined?{}:{title:input.title}),
|
|
17
|
+
...(input.projectKey===undefined?{}:{projectKey:input.projectKey})
|
|
18
|
+
});
|
|
19
|
+
const session=result.result?.session;
|
|
20
|
+
if(!result.ok||result.result?.acknowledged!==true||!session?.taskSessionId)
|
|
21
|
+
return blocked("session",result.error??"full_session_not_confirmed");
|
|
22
|
+
taskSessionId=session.taskSessionId;
|
|
23
|
+
completed.push("session");
|
|
24
|
+
}
|
|
25
|
+
if(input.repoPath!==undefined){
|
|
26
|
+
const result=await call("full.workspace.ensure",{taskSessionId,kind:"git",repoPath:input.repoPath});
|
|
27
|
+
if(!result.ok||result.result?.binding?.state!=="ready")
|
|
28
|
+
return blocked("workspace",result.error??"full_workspace_not_ready");
|
|
29
|
+
workspace=result.result.binding;
|
|
30
|
+
completed.push("workspace");
|
|
31
|
+
}
|
|
32
|
+
const result=await call("full.intelligence.refresh",{taskSessionId,taskContext:input.taskContext});
|
|
33
|
+
if(!result.ok)return blocked("intelligence",result.error);
|
|
34
|
+
intelligence=result.result;
|
|
35
|
+
if(intelligence?.published!==true||intelligence.taskContext?.ok!==true||
|
|
36
|
+
intelligence.taskContext?.pack?.requiredContextUnavailable!==false)
|
|
37
|
+
return blocked("intelligence","full_coding_context_incomplete");
|
|
38
|
+
completed.push("intelligence");
|
|
39
|
+
return {ok:true,result:{state:"prepared",taskSessionId,completed,...(workspace?{workspace}:{}),intelligence}};
|
|
40
|
+
}
|