@anusornneal/chat-relay 2.1.0 → 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/agent/activity-capture.mjs +120 -11
- package/agent/full-coding-prepare.mjs +40 -0
- package/agent/full-desktop-broker.mjs +95 -25
- 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/local-agent.mjs +14 -3
- package/agent/local-usage.mjs +8 -0
- package/agent/monitor-activity.mjs +81 -22
- package/agent/presentation-redaction.mjs +1 -10
- package/agent/toolcall-context.mjs +39 -1
- package/cli/full-release-default.json +2 -2
- package/package.json +1 -1
- package/packages/full-contracts/presentation-redaction.mjs +16 -0
- package/packages/full-contracts/remote-session.mjs +20 -1
|
@@ -3,10 +3,15 @@ import fs from "node:fs/promises";
|
|
|
3
3
|
import {constants} from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import {redactPresentationText} from "./presentation-redaction.mjs";
|
|
6
|
+
import {observedCommitSubject} from "./toolcall-context.mjs";
|
|
6
7
|
import {presentationChangePath} from "./full-presentation-changes.mjs";
|
|
7
8
|
|
|
8
9
|
const storage=new AsyncLocalStorage();
|
|
9
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;
|
|
10
15
|
const safeError=value=>typeof value==="string"&&/^[A-Za-z][A-Za-z0-9_:-]{1,95}$/.test(value)?value:"";
|
|
11
16
|
const safeInteger=value=>Number.isSafeInteger(value)&&value>=0?value:null;
|
|
12
17
|
const decode=value=>{
|
|
@@ -56,7 +61,7 @@ export function captureActivityFor(payload){
|
|
|
56
61
|
return detailActions.has(action)?createActivityCapture():null;
|
|
57
62
|
}
|
|
58
63
|
export function createActivityCapture(){
|
|
59
|
-
return {files:new Map(),bytes:0,closed:false};
|
|
64
|
+
return {files:new Map(),bytes:0,scanBytes:0,closed:false};
|
|
60
65
|
}
|
|
61
66
|
export function runActivityCapture(capture,work){
|
|
62
67
|
return capture?storage.run(capture,work):work();
|
|
@@ -96,23 +101,125 @@ export function recordActivityEdit(index,requestedPath,before,after,kind,canonic
|
|
|
96
101
|
try{
|
|
97
102
|
const name=displayActivityPath(requestedPath);
|
|
98
103
|
if(!name||!displayActivityPath(canonicalTarget))return;
|
|
99
|
-
const entry={path:name,kind,pair:null};
|
|
104
|
+
const entry={path:name,kind,pair:null,diffReason:"Text not captured"};
|
|
100
105
|
context.files.set(index,entry);
|
|
101
106
|
if(before===undefined||after===undefined)return;
|
|
102
107
|
const size=(before===null?0:Buffer.byteLength(before))+(after===null?0:Buffer.byteLength(after));
|
|
103
|
-
|
|
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;
|
|
104
114
|
const a=decode(before),b=decode(after);
|
|
105
|
-
if(a===null||b===null||!a.isWellFormed()||!b.isWellFormed()||a.includes("\0")||b.includes("\0")||a.includes("\uFFFD")||b.includes("\uFFFD"))
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
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;
|
|
110
132
|
}catch{/* Optional monitor only. */}
|
|
111
133
|
}
|
|
112
134
|
// Exact bounded line edit script from the recorded pair. Retain newline
|
|
113
135
|
// characters in the comparison so final-newline and CRLF changes are real.
|
|
114
136
|
function splitLines(value){return value.match(/[^\n]*\n|[^\n]+$/g)??[];}
|
|
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
|
+
}
|
|
115
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
|
+
}
|
|
116
223
|
if(!pair)return {state:"unavailable",reason:"No captured text for this call",additions:null,deletions:null,text:""};
|
|
117
224
|
const a=splitLines(pair.before),b=splitLines(pair.after);
|
|
118
225
|
if(a.length>MAX_LINES||b.length>MAX_LINES)return {state:"unavailable",reason:"Change exceeds capture limit",additions:null,deletions:null,text:""};
|
|
@@ -158,7 +265,8 @@ export function finishActivityCapture(capture,payload,result){
|
|
|
158
265
|
if(files.length>=MAX_FILES){omitted++;return;}
|
|
159
266
|
const captured=capture.files.get(index),name=captured?.path||displayActivityPath(source);
|
|
160
267
|
if(!name){omitted++;return;}
|
|
161
|
-
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}:{})});
|
|
162
270
|
};
|
|
163
271
|
const edit=action==="fs.editMany"||action==="full.workspace.edit";
|
|
164
272
|
if(edit){
|
|
@@ -184,8 +292,9 @@ export function finishActivityCapture(capture,payload,result){
|
|
|
184
292
|
// Bounded display metadata only. No raw commands, output, Learn values,
|
|
185
293
|
// or arbitrary response objects. Search terms use display redaction.
|
|
186
294
|
const search=describeLocalSearch(payload);
|
|
187
|
-
const
|
|
188
|
-
|
|
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;
|
|
189
298
|
}
|
|
190
299
|
const summaryCache=new WeakMap();
|
|
191
300
|
function changeStats(pair,maxCells=Infinity){
|
|
@@ -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
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import fs from "node:fs/promises";
|
|
2
|
-
import {describeFullMonitorActivity,MAX_MONITOR_ROWS} from "./monitor-activity.mjs";
|
|
2
|
+
import {describeFullMonitorActivity,MAX_MONITOR_ROWS,SESSION_IDLE_MS,SESSION_HIDE_MS} from "./monitor-activity.mjs";
|
|
3
3
|
import {createReadStream} from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import {spawn} from "node:child_process";
|
|
@@ -16,6 +16,8 @@ const require=(ok,code)=>{if(!ok)throw new FullContractError(code);};
|
|
|
16
16
|
const text=(v,n=512)=>typeof v==="string"?v.slice(0,n).toWellFormed():"";
|
|
17
17
|
import {redactPresentationText} from "./presentation-redaction.mjs";
|
|
18
18
|
export {redactPresentationText};
|
|
19
|
+
const recordedJobPrefix="recorded-";
|
|
20
|
+
const recordedChange=/^recorded:(monitor-[0-9]+):([0-9]|1[0-9])$/;
|
|
19
21
|
const jobView=job=>job?{jobId:job.jobId,state:job.state,exitCode:job.exitCode??null,signal:job.signal??null}:null;
|
|
20
22
|
const safeSession=s=>({taskSessionId:s.taskSessionId,title:redactPresentationText(s.title,200),project:redactPresentationText(s.projectKey,200),status:s.status,revision:s.revision,
|
|
21
23
|
createdAt:text(s.createdAt,40),updatedAt:text(s.updatedAt,40),activity:[],changes:[]});
|
|
@@ -57,12 +59,14 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
|
|
|
57
59
|
require(result?.ok===true,result?.error??"full_presentation_failed");
|
|
58
60
|
return result.result;
|
|
59
61
|
}
|
|
62
|
+
const localTerminal=localMonitor&&allowTerminal&&localScopes.includes("terminal")&&typeof monitorDetails==="function";
|
|
63
|
+
const localChanges=localMonitor&&typeof monitorDetails==="function";
|
|
60
64
|
function commandAvailability(){
|
|
61
|
-
const terminal=allowTerminal&¤tScopes.includes("terminal");
|
|
65
|
+
const terminal=localTerminal||allowTerminal&¤tScopes.includes("terminal");
|
|
62
66
|
return {
|
|
63
67
|
"job.output":{available:terminal,reason:terminal?null:"Local terminal permission unavailable"},
|
|
64
|
-
"changes.list":{available:viewScopes().includes("read")&&typeof readChanges==="function",reason:typeof readChanges==="function"?null:"Changes are unavailable in this runtime"},
|
|
65
|
-
"changes.diff":{available:viewScopes().includes("read")&&typeof readChanges==="function",reason:typeof readChanges==="function"?null:"Changes are unavailable in this runtime"},
|
|
68
|
+
"changes.list":{available:viewScopes().includes("read")&&(localChanges||typeof readChanges==="function"),reason:localChanges||typeof readChanges==="function"?null:"Changes are unavailable in this runtime"},
|
|
69
|
+
"changes.diff":{available:viewScopes().includes("read")&&(localChanges||typeof readChanges==="function"),reason:localChanges||typeof readChanges==="function"?null:"Changes are unavailable in this runtime"},
|
|
66
70
|
...(typeof monitorDetails==="function"?{"activity.detail":{available:viewScopes().includes("read")},"activity.diff":{available:viewScopes().includes("read")}}:{}),
|
|
67
71
|
"agent.quit":{available:typeof requestQuit==="function",reason:typeof requestQuit==="function"?null:"Local agent lifecycle unavailable"}
|
|
68
72
|
};
|
|
@@ -87,18 +91,48 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
|
|
|
87
91
|
if(owner?.accountId!==principal.accountId||owner.agentId!==principal.agentId||!id(owner.taskSessionId))return false;
|
|
88
92
|
activities.delete(owner.taskSessionId);lastObservedJobs.delete(owner.taskSessionId);return true;
|
|
89
93
|
}
|
|
94
|
+
function recordedRows(taskSessionId,raw=monitorSnapshot()){
|
|
95
|
+
return (Array.isArray(raw?.activity)?raw.activity:[]).filter(row=>row.taskSessionId===taskSessionId&&/^monitor-[0-9]+$/.test(row.requestId)).slice(-MAX_MONITOR_ROWS).reverse();
|
|
96
|
+
}
|
|
97
|
+
function recordedFiles(taskSessionId){
|
|
98
|
+
const files=[];let truncated=false,used=0;
|
|
99
|
+
for(const row of recordedRows(taskSessionId)){
|
|
100
|
+
if(!row.hasDetails||!["fs.edit","fs.editMany","fs.write","fs.delete","full.workspace.edit"].includes(row.action))continue;
|
|
101
|
+
const detail=monitorDetails(row.requestId);
|
|
102
|
+
if(detail?.omitted)truncated=true;
|
|
103
|
+
for(const file of detail?.files??[]){
|
|
104
|
+
if(file.outcome!=="completed"||file.kind==="read")continue;
|
|
105
|
+
const entry={path:"recorded:"+row.requestId+":"+file.fileId,displayPath:file.path,status:file.kind,kind:file.kind,sourceTime:row.time,additions:file.additions,deletions:file.deletions,diffAvailable:file.diffAvailable===true};
|
|
106
|
+
const size=Buffer.byteLength(JSON.stringify(entry))+1;
|
|
107
|
+
if(files.length>=100||used+size>40000)return {taskSessionId,state:"ready",source:"recorded",files,truncated:true};
|
|
108
|
+
used+=size;files.push(entry);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return {taskSessionId,state:"ready",source:"recorded",files,truncated};
|
|
112
|
+
}
|
|
113
|
+
function recordedDiff(taskSessionId,relativePath){
|
|
114
|
+
const match=relativePath.match(recordedChange);
|
|
115
|
+
const row=match&&recordedRows(taskSessionId).find(row=>row.requestId===match[1]&&row.hasDetails);
|
|
116
|
+
const file=row&&monitorDetails(match[1])?.files?.find(file=>file.fileId===match[2]&&file.outcome==="completed"&&file.kind!=="read");
|
|
117
|
+
if(!file)return {taskSessionId,relativePath,state:"unavailable",reason:"Recorded change unavailable"};
|
|
118
|
+
const diff=monitorDetails(match[1],match[2]);
|
|
119
|
+
return {taskSessionId,relativePath,state:diff?.state??"unavailable",reason:diff?.reason,text:diff?.text??"",truncated:diff?.truncated===true};
|
|
120
|
+
}
|
|
90
121
|
async function snapshot({consumerId,cursor,input={},signal}){
|
|
91
122
|
require(exact(input,["selectedId","after"])&&(input.selectedId===undefined||input.selectedId===null||id(input.selectedId))&&(input.after===undefined||input.after===""||id(input.after)),"full_invalid_presentation_input");
|
|
92
123
|
const rawMonitor=monitorSnapshot();
|
|
124
|
+
const {sessionPresence,...publicMonitor}=rawMonitor??{};
|
|
93
125
|
// Local labels are bounded and redacted before crossing the presentation
|
|
94
126
|
// boundary. On authority loss, retain counters but not task/project labels.
|
|
95
|
-
const monitor=rawMonitor?{...
|
|
127
|
+
const monitor=rawMonitor?{...publicMonitor,activity:(Array.isArray(rawMonitor.activity)?rawMonitor.activity:[]).slice(-MAX_MONITOR_ROWS).map(row=>({
|
|
96
128
|
requestId:id(row.requestId)?row.requestId:"",taskSessionId:id(row.taskSessionId)?row.taskSessionId:null,hasDetails:row.hasDetails===true,at:text(row.at,40),time:text(row.time,16),type:text(row.type,32),action:text(row.action,100),
|
|
97
129
|
category:text(row.category,32),icon:text(row.icon,8),operation:redactPresentationText(row.operation,128),
|
|
98
130
|
project:redactPresentationText(row.project,64),status:text(row.status,16),ok:typeof row.ok==="boolean"?row.ok:null,
|
|
99
131
|
durationMs:Number.isFinite(row.durationMs)?Math.max(0,row.durationMs):null,elapsedMs:Number.isFinite(row.elapsedMs)?Math.max(0,row.elapsedMs):null,
|
|
100
132
|
requestBytes:Number.isSafeInteger(row.requestBytes)&&row.requestBytes>=0?row.requestBytes:null,responseBytes:Number.isSafeInteger(row.responseBytes)&&row.responseBytes>=0?row.responseBytes:null,
|
|
101
133
|
error:text(row.error,96),detail:redactPresentationText(row.detail,160),query:redactPresentationText(row.query,180),searchScope:redactPresentationText(row.searchScope,180),
|
|
134
|
+
...(localTerminal&&row.hasOutput===true?{hasOutput:true}:{}),
|
|
135
|
+
...(Number.isSafeInteger(row.exitCode)?{exitCode:row.exitCode}:{}),
|
|
102
136
|
...(typeof row.pollKey==="string"&&/^[a-f0-9]{24}$/.test(row.pollKey)?{pollKey:row.pollKey}:{}),
|
|
103
137
|
...(Number.isSafeInteger(row.additions)&&row.additions>=0&&Number.isSafeInteger(row.deletions)&&row.deletions>=0?{additions:row.additions,deletions:row.deletions}:{})
|
|
104
138
|
}))}:null;
|
|
@@ -111,17 +145,33 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
|
|
|
111
145
|
sessions:[],detail:null,selectedUnavailable:false,next:null,partial:false,
|
|
112
146
|
sessionAccess:"unavailable",monitor:{...monitor,activity:[]},commands:{"job.output":{available:false,reason:"Session access unavailable"},"changes.list":{available:false,reason:"Session access unavailable"},"changes.diff":{available:false,reason:"Session access unavailable"},"agent.quit":commandAvailability()["agent.quit"]},terminalEnabled:false};
|
|
113
147
|
}
|
|
114
|
-
const commands=commandAvailability(),terminal=
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
148
|
+
const commands=commandAvailability(),terminal=commands["job.output"].available;
|
|
149
|
+
const liveById=new Map();
|
|
150
|
+
if(Array.isArray(sessionPresence)){
|
|
151
|
+
for(const entry of sessionPresence.slice(0,127))if(id(entry.taskSessionId)&&Number.isFinite(entry.ageMs))liveById.set(entry.taskSessionId,entry);
|
|
152
|
+
}else{
|
|
153
|
+
// Compatibility with older monitor providers and presentation fixtures.
|
|
154
|
+
const current=Date.now();
|
|
155
|
+
for(const row of monitor?.activity??[]){
|
|
156
|
+
if(!id(row.taskSessionId))continue;
|
|
157
|
+
const previous=liveById.get(row.taskSessionId),at=Date.parse(row.at)+(row.durationMs??0);
|
|
158
|
+
liveById.set(row.taskSessionId,{ageMs:Number.isFinite(at)?Math.max(0,current-at):0,time:row.time,project:row.project||previous?.project,working:previous?.working||row.status==="running",failed:row.ok===false});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const visibleIds=[...liveById].filter(([,entry])=>entry.working||entry.ageMs<SESSION_HIDE_MS).map(([key])=>key);
|
|
162
|
+
if(input.selectedId&&!visibleIds.includes(input.selectedId))visibleIds.push(input.selectedId);
|
|
163
|
+
const listed=await call("full.session.list",{after:input.after??"",limit:32,...(localMonitor?{monitorSessionIds:visibleIds.slice(0,128)}:{})},signal,true);
|
|
164
|
+
function withPresence(source){
|
|
165
|
+
const session=safeSession(source),entry=liveById.get(session.taskSessionId);
|
|
166
|
+
if(!session.project&&entry?.project)session.project=redactPresentationText(entry.project,64);
|
|
167
|
+
session.lastActivityTime=text(entry?.time,16);
|
|
168
|
+
const age=entry?.ageMs??Infinity;
|
|
169
|
+
session.liveStatus=entry?.working?"working":age<SESSION_IDLE_MS?(entry.failed?"issue":"active"):entry?"idle":"unobserved";
|
|
170
|
+
if(!entry?.working&&age<SESSION_IDLE_MS)session.activeForMs=Math.max(1,Math.ceil(SESSION_IDLE_MS-age));
|
|
171
|
+
if(source.automatic===true&&!entry?.working)session.visibleForMs=Math.max(0,Math.ceil(SESSION_HIDE_MS-age));
|
|
172
|
+
return session;
|
|
124
173
|
}
|
|
174
|
+
const sessions=listed.items.map(withPresence).filter(session=>session.visibleForMs!==0||session.taskSessionId===input.selectedId);
|
|
125
175
|
let detail=null,selectedUnavailable=false;
|
|
126
176
|
if(input.selectedId){
|
|
127
177
|
let source;
|
|
@@ -136,17 +186,21 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
|
|
|
136
186
|
}
|
|
137
187
|
if(source){
|
|
138
188
|
const facts=source.session.facts??{},rawJobs=source.jobs??[],jobs=rawJobs.map(jobView);
|
|
189
|
+
const observed=recordedRows(input.selectedId,rawMonitor);
|
|
190
|
+
const recordedJobs=localTerminal?observed.filter(row=>row.hasOutput===true).slice(0,24).map(row=>({jobId:recordedJobPrefix+row.requestId,state:"recorded",label:redactPresentationText(row.operation,100),time:text(row.time,16),exitCode:Number.isSafeInteger(row.exitCode)?row.exitCode:null})):[];
|
|
191
|
+
const evidenceIds=new Set();
|
|
192
|
+
const recordedEvidence=observed.filter(row=>{if(!Number.isSafeInteger(row.exitCode))return false;const key=row.pollKey||row.requestId;if(evidenceIds.has(key))return false;evidenceIds.add(key);return true;}).slice(0,16).map(row=>({evidenceId:"exit-"+row.requestId,checkId:redactPresentationText(row.operation,128),kind:"Command exit",outcome:row.exitCode===0?"completed":"failed",exitCode:row.exitCode,observedAt:text(row.at,40)}));
|
|
139
193
|
// Prefer unresolved work, otherwise retain the last job observed in
|
|
140
194
|
// this monitor. UUID sorting is not a reliable chronological order.
|
|
141
195
|
const currentJob=rawJobs.find(j=>!jobIsSettled(j))??rawJobs.find(j=>j.jobId===lastObservedJobs.get(input.selectedId))??rawJobs[0];
|
|
142
196
|
lastObservedJobs.delete(input.selectedId);
|
|
143
197
|
if(currentJob)lastObservedJobs.set(input.selectedId,currentJob.jobId);
|
|
144
198
|
while(lastObservedJobs.size>32)lastObservedJobs.delete(lastObservedJobs.keys().next().value);
|
|
145
|
-
detail={...
|
|
146
|
-
job:jobView(currentJob),jobs,
|
|
199
|
+
detail={...withPresence(source.session),workspace:source.workspace?{workspaceId:source.workspace.workspaceId,kind:source.workspace.workspaceKind,mode:source.workspace.mode,state:source.workspace.state,label:redactPresentationText(source.workspace.branch,200)}:null,
|
|
200
|
+
job:jobView(currentJob)??recordedJobs[0]??null,jobs:[...jobs,...recordedJobs].slice(0,24),
|
|
147
201
|
activity:(monitor?.activity?.some(row=>row.taskSessionId===input.selectedId)?monitor.activity.filter(row=>row.taskSessionId===input.selectedId):(activities.get(input.selectedId)??[])).slice(-MAX_MONITOR_ROWS),
|
|
148
202
|
changes:(facts.changedFiles??[]).slice(0,100).map(p=>redactPresentationText(p,512)),
|
|
149
|
-
evidence:(facts.evidence??[]).slice(-16).map(e=>({evidenceId:e.evidenceId,checkId:e.checkId,kind:e.kind,outcome:e.outcome,observedAt:e.observedAt})),
|
|
203
|
+
evidence:[...(facts.evidence??[]).slice(-16).map(e=>({evidenceId:e.evidenceId,checkId:e.checkId,kind:e.kind,outcome:e.outcome,observedAt:e.observedAt})),...recordedEvidence].slice(0,16),
|
|
150
204
|
blockers:(facts.blockers??[]).slice(0,8).map(p=>redactPresentationText(p,512)),
|
|
151
205
|
summary:redactPresentationText(facts.summary,1000),indexState:"not-assessed",
|
|
152
206
|
detailPartial:source.historyOmitted>0||source.jobSummary?.omitted>0||source.claimSummary?.omitted>0||(facts.changedFiles?.length??0)>100||(facts.evidence?.length??0)>16,
|
|
@@ -158,7 +212,7 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
|
|
|
158
212
|
// durable identity/state, then trim optional detail with a visible gap.
|
|
159
213
|
const bytes=()=>Buffer.byteLength(JSON.stringify(view));
|
|
160
214
|
for(const key of ["activity","changes","evidence","blockers"]){
|
|
161
|
-
while(bytes()>56000&&detail?.[key]?.length){detail[key].pop();detail.detailPartial=true;}
|
|
215
|
+
while(bytes()>56000&&detail?.[key]?.length){if(key==="activity")detail[key].shift();else detail[key].pop();detail.detailPartial=true;}
|
|
162
216
|
}
|
|
163
217
|
while(bytes()>56000&&monitor?.activity?.length){monitor.activity.shift();view.partial=true;}
|
|
164
218
|
while(bytes()>56000&&sessions.length>1){sessions.pop();view.next=sessions.at(-1).taskSessionId;view.partial=true;}
|
|
@@ -172,7 +226,8 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
|
|
|
172
226
|
// The private local presentation endpoint is authenticated. Quit is local lifecycle control, not remote task authority.
|
|
173
227
|
requestQuit();return {acknowledged:true};
|
|
174
228
|
}
|
|
175
|
-
const
|
|
229
|
+
const recordedOutput=action==="job.output"&&typeof input.jobId==="string"&&input.jobId.startsWith(recordedJobPrefix);
|
|
230
|
+
const localRead=localMonitor&&(["activity.detail","activity.diff","changes.list","changes.diff"].includes(action)||recordedOutput);
|
|
176
231
|
require(!signal?.aborted,"full_cancelled_before_start");
|
|
177
232
|
if(!localRead)await refreshAuthority(true,signal);
|
|
178
233
|
const commands=commandAvailability();
|
|
@@ -183,7 +238,9 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
|
|
|
183
238
|
require(typeof monitorDetails==="function","full_invalid_presentation_input");
|
|
184
239
|
const value=monitorDetails(input.activityId,input.fileId);
|
|
185
240
|
require(value?.activityId===input.activityId&&Buffer.byteLength(JSON.stringify(value))<=48000,"full_invalid_presentation_result");
|
|
186
|
-
|
|
241
|
+
// Terminal previews are served only by the scoped terminal-output route.
|
|
242
|
+
const {terminal:privateOutput,...view}=value;
|
|
243
|
+
return view;
|
|
187
244
|
}
|
|
188
245
|
if(action==="changes.list"||action==="changes.diff"){
|
|
189
246
|
require(exact(input,action==="changes.list"?["taskSessionId"]:["taskSessionId","relativePath"])&&id(input.taskSessionId)&&
|
|
@@ -191,7 +248,13 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
|
|
|
191
248
|
const expectedAuthority=authorityVersion;
|
|
192
249
|
try{
|
|
193
250
|
const invocation=permitted("full.session.snapshot",{taskSessionId:input.taskSessionId,consumerId:"presentation-changes"},true);
|
|
194
|
-
|
|
251
|
+
// A recorded identifier is never interpreted as a filesystem path.
|
|
252
|
+
if(localChanges&&action==="changes.diff"&&input.relativePath.startsWith("recorded:"))return recordedDiff(input.taskSessionId,input.relativePath);
|
|
253
|
+
const result=typeof readChanges==="function"?await readChanges(invocation,input,signal,redactPresentationText):{taskSessionId:input.taskSessionId,state:"unavailable",reason:"This session has no ready Git workspace."};
|
|
254
|
+
if(localChanges&&action==="changes.list"&&result?.taskSessionId===input.taskSessionId&&result?.state==="unavailable"&&result.reason==="This session has no ready Git workspace."){
|
|
255
|
+
require(!signal?.aborted,"full_cancelled_before_start");
|
|
256
|
+
return recordedFiles(input.taskSessionId);
|
|
257
|
+
}
|
|
195
258
|
require(!signal?.aborted,"full_cancelled_before_start");
|
|
196
259
|
require(localRead?localScopes.includes("read"):expectedAuthority===authorityVersion&¤tScopes.includes("read"),"full_presentation_permission_denied");
|
|
197
260
|
require(result?.taskSessionId===input.taskSessionId&&Buffer.byteLength(JSON.stringify(result))<=48000,"full_invalid_presentation_result");
|
|
@@ -202,6 +265,13 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
|
|
|
202
265
|
}
|
|
203
266
|
}
|
|
204
267
|
require(action==="job.output"&&exact(input,["taskSessionId","jobId","afterSeq"]),"full_invalid_presentation_input");
|
|
268
|
+
if(recordedOutput){
|
|
269
|
+
require(localTerminal&&id(input.taskSessionId)&&/^recorded-monitor-[0-9]+$/.test(input.jobId)&&(input.afterSeq===undefined||Number.isSafeInteger(input.afterSeq)&&input.afterSeq>=0),"full_invalid_presentation_input");
|
|
270
|
+
const activityId=input.jobId.slice(recordedJobPrefix.length),row=recordedRows(input.taskSessionId).find(row=>row.requestId===activityId&&row.hasOutput===true);
|
|
271
|
+
const output=row&&monitorDetails(activityId)?.terminal;
|
|
272
|
+
if(!output)return {outputAvailable:false,text:"",nextSeq:0,hasMore:false};
|
|
273
|
+
return {outputAvailable:true,text:(input.afterSeq??0)>0?"":output.text,nextSeq:1,hasMore:false,truncated:output.partial,source:"recorded"};
|
|
274
|
+
}
|
|
205
275
|
const result=await call("full.job.read",input,signal);
|
|
206
276
|
// Chunks are joined before redaction so common credentials split across
|
|
207
277
|
// adjacent chunks are still recognized. Never retain output in the broker.
|
|
@@ -242,7 +312,7 @@ export async function createFullDesktopBroker({host,artifact,sessionDirectory,pr
|
|
|
242
312
|
const environmentKeys=new Set(["path","systemroot","windir","home","userprofile","temp","tmp","tmpdir","appdata","localappdata","lang","lc_all","display","wayland_display","xdg_runtime_dir","dbus_session_bus_address"]);
|
|
243
313
|
const environment=Object.fromEntries(Object.entries(process.env).filter(([key])=>environmentKeys.has(key.toLowerCase())));
|
|
244
314
|
const {endpoint,token}=presentation.bootstrap;
|
|
245
|
-
async function open({accountId}={}){
|
|
315
|
+
async function open({accountId,initial=false}={}){
|
|
246
316
|
require(accountId===boundAccountId,"full_presentation_permission_denied");
|
|
247
317
|
require(!closed&&host.available,"full_unavailable");
|
|
248
318
|
if(opening)return opening;
|
|
@@ -255,7 +325,7 @@ export async function createFullDesktopBroker({host,artifact,sessionDirectory,pr
|
|
|
255
325
|
if(alive(child)){presentation.publish({type:"activity.progress",requestId:randomUUID(),at:new Date().toISOString(),action:"presentation.open"});return {alreadyOpen:true};}
|
|
256
326
|
require(await binaryDigest(signal)===initialDigest,"full_invalid_gui_artifact");check();
|
|
257
327
|
state="starting";exitResult=null;
|
|
258
|
-
try{launched=spawn(binary,[],{windowsHide:false,stdio:"ignore",env:{...environment,RELAY_FULL_PRESENTATION_ENDPOINT:endpoint,RELAY_FULL_PRESENTATION_TOKEN:token,RELAY_FULL_PRESENTATION_EPOCH:host.ownerEpoch,RELAY_FULL_PRESENTATION_STATE:path.join(sessionDirectory,"gui-selection.json"),WEBVIEW2_USER_DATA_FOLDER:path.join(sessionDirectory,"webview")}});}
|
|
328
|
+
try{launched=spawn(binary,[],{windowsHide:false,stdio:"ignore",env:{...environment,...(initial&&process.env.CHAT_RELAY_START_IN_TRAY==="1"?{RELAY_FULL_PRESENTATION_START_IN_TRAY:"1"}:{}),RELAY_FULL_PRESENTATION_ENDPOINT:endpoint,RELAY_FULL_PRESENTATION_TOKEN:token,RELAY_FULL_PRESENTATION_EPOCH:host.ownerEpoch,RELAY_FULL_PRESENTATION_STATE:path.join(sessionDirectory,"gui-selection.json"),WEBVIEW2_USER_DATA_FOLDER:path.join(sessionDirectory,"webview")}});}
|
|
259
329
|
catch{state="unavailable";throw new FullContractError("full_gui_launch_failed");}
|
|
260
330
|
const current=launched;child=current;
|
|
261
331
|
current.once("exit",(code,signal)=>{if(child===current){state="closed";exitResult={code,signal};}});
|
|
@@ -307,7 +377,7 @@ export async function createFullDesktopBroker({host,artifact,sessionDirectory,pr
|
|
|
307
377
|
})();
|
|
308
378
|
return closing;
|
|
309
379
|
}
|
|
310
|
-
try{await open({accountId:boundAccountId});}
|
|
380
|
+
try{await open({accountId:boundAccountId,initial:true});}
|
|
311
381
|
catch(error){await close();throw error;}
|
|
312
382
|
return Object.freeze({
|
|
313
383
|
get status(){return {state,pid:child?.pid??null,exit:exitResult,scopeId:service.scopeId};},
|
|
@@ -52,7 +52,7 @@ export async function createRemoteDiagnostics({host,artifact,scheduler}){
|
|
|
52
52
|
function completed(parsed,response,start,metadata={}){
|
|
53
53
|
if(REMOTE_DIAGNOSTICS_OPERATIONS.includes(parsed.operation)||parsed.operation==="full.session.delete")return;
|
|
54
54
|
const observedStart=performance.now();
|
|
55
|
-
const taskSessionId=parsed.input.taskSessionId??response.result?.session?.taskSessionId;
|
|
55
|
+
const taskSessionId=parsed.input.taskSessionId??response.result?.session?.taskSessionId??(parsed.operation==="full.coding.prepare"?response.result?.taskSessionId:undefined);
|
|
56
56
|
if(!taskSessionId)return;
|
|
57
57
|
// A successful host/broker operation authorizes this task. Denied attempts
|
|
58
58
|
// may only enter an already authorized own-task ring, never seed one from
|
|
@@ -1,5 +1,6 @@
|
|
|
1
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";
|
|
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,CODING_PREPARE_OPERATION} from "../packages/full-contracts/remote-session.mjs";
|
|
3
|
+
import {prepareCodingTask} from "./full-coding-prepare.mjs";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import {performance} from "node:perf_hooks";
|
|
5
6
|
|
|
@@ -96,7 +97,13 @@ export async function startRemoteFull({bootstrap,agentId,onUnavailable,workspace
|
|
|
96
97
|
// deletion rejects busy tasks and fences new calls for this exact owner.
|
|
97
98
|
leaveTask=enterTask(parsed);
|
|
98
99
|
let response;
|
|
99
|
-
if(parsed.operation===
|
|
100
|
+
if(parsed.operation===CODING_PREPARE_OPERATION){
|
|
101
|
+
require(workspace?.capabilities.includes(CODING_PREPARE_OPERATION),"full_capability_unavailable");
|
|
102
|
+
require(parsed.input.taskContext.detail===undefined||workspace.capabilities.includes("full.intelligence.task-context.expand"),"full_capability_unavailable");
|
|
103
|
+
// Compose locally: child dispatches retain their own authority, task
|
|
104
|
+
// ownership and resource admission. Never replay a failed write.
|
|
105
|
+
result=await prepareCodingTask(parsed,dispatch);
|
|
106
|
+
}else if(parsed.operation==="full.session.delete"){
|
|
100
107
|
const owner={accountId:parsed.principal.accountId,agentId:parsed.principal.agentId,taskSessionId:parsed.input.taskSessionId};
|
|
101
108
|
const admission=workspaceBroker?.scheduler?.fullAdmission;
|
|
102
109
|
require(!admission||admission.snapshot({owner}).claims.length===0,"full_session_busy");
|
|
@@ -122,7 +129,7 @@ export async function startRemoteFull({bootstrap,agentId,onUnavailable,workspace
|
|
|
122
129
|
require(workspace,"full_capability_unavailable");
|
|
123
130
|
response=await workspace.dispatch(payload,parsed);
|
|
124
131
|
}else response=await host.request(parsed.operation,payload,{taskSessionId:parsed.input.taskSessionId,timeoutMs:15000});
|
|
125
|
-
result={ok:true,result:response};
|
|
132
|
+
if(!result)result={ok:true,result:response};
|
|
126
133
|
}catch(error){result={ok:false,error:typeof error?.code==="string"&&/^full_[a-z0-9_]+$/.test(error.code)?error.code:"full_operation_failed"};}
|
|
127
134
|
finally{pending--;}
|
|
128
135
|
if(parsed&&parsed.operation!=="full.session.delete"){
|
|
@@ -286,5 +286,5 @@ export async function createRemoteWorkspaceBroker({host,artifact,git,roots,sched
|
|
|
286
286
|
scopedWriteStarts++;
|
|
287
287
|
try{return await dispatchOperation(invocation,parsed);}finally{scopedWriteStarts--;}
|
|
288
288
|
}
|
|
289
|
-
return Object.freeze({dispatch,presentationChanges:host.operations.includes(PRESENTATION_WORKSPACE_OPERATION)?presentationChanges:null,assertSessionIdle:owner=>jobs?.assertSessionIdle(owner),forgetSession:owner=>jobs?.forgetSession(owner),close:()=>jobs?.close()??true,blocksLegacyEffects:()=>scheduler.fullAdmission.recoveryBlocked||scopedWriteStarts>0||!!jobs?.blocksLegacyEffects(),capabilities:["full.workspace.readonly",...(readBatchEnabled?["full.workspace.read-batch"]:[]),...(isolation?["full.workspace.isolated"]:[]),...(artifacts?["full.workspace.artifacts"]:[]),...(scopedEdits?["full.workspace.edit"]:[]),...(intelligence?["full.intelligence",...(intelligenceBatch?["full.intelligence.batch"]:[]),...(taskContext?["full.intelligence.task-context",...(taskContextExpand?["full.intelligence.task-context.expand"]:[])]:[])]:[]),...(verification?["full.verification"]:[]),...(jobs?["full.jobs",...(jobs.recoveryEnabled?["full.jobs.recovery"]:[]),...(jobs.waitEnabled?["full.jobs.wait"]:[])]:[])]});
|
|
289
|
+
return Object.freeze({dispatch,presentationChanges:host.operations.includes(PRESENTATION_WORKSPACE_OPERATION)?presentationChanges:null,assertSessionIdle:owner=>jobs?.assertSessionIdle(owner),forgetSession:owner=>jobs?.forgetSession(owner),close:()=>jobs?.close()??true,blocksLegacyEffects:()=>scheduler.fullAdmission.recoveryBlocked||scopedWriteStarts>0||!!jobs?.blocksLegacyEffects(),capabilities:["full.workspace.readonly",...(readBatchEnabled?["full.workspace.read-batch"]:[]),...(isolation?["full.workspace.isolated"]:[]),...(artifacts?["full.workspace.artifacts"]:[]),...(scopedEdits?["full.workspace.edit"]:[]),...(intelligence?["full.intelligence",...(intelligenceBatch?["full.intelligence.batch"]:[]),...(taskContext?["full.intelligence.task-context",...(sharedGit?["full.coding.prepare"]:[]),...(taskContextExpand?["full.intelligence.task-context.expand"]:[])]:[])]:[]),...(verification?["full.verification"]:[]),...(jobs?["full.jobs",...(jobs.recoveryEnabled?["full.jobs.recovery"]:[]),...(jobs.waitEnabled?["full.jobs.wait"]:[])]:[])]});
|
|
290
290
|
}
|
package/agent/local-agent.mjs
CHANGED
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
} from "./lifecycle.mjs";
|
|
23
23
|
import { humanizeToolCall } from "./toolcall-summary.mjs";
|
|
24
24
|
import { describeToolActivity } from "./toolcall-context.mjs";
|
|
25
|
-
import { createMonitorActivity, describeFullMonitorActivity } from "./monitor-activity.mjs";
|
|
25
|
+
import { createMonitorActivity, describeFullMonitorActivity, observedTerminalResult } from "./monitor-activity.mjs";
|
|
26
26
|
import {captureActivityFor,runActivityCapture,finishActivityCapture,describeLocalSearch} from "./activity-capture.mjs";
|
|
27
27
|
import { toolErrorGuidance } from "./tool-error-guidance.mjs";
|
|
28
28
|
import {
|
|
@@ -49,6 +49,7 @@ const fullEvents = process.env.CHAT_RELAY_FULL_EVENTS === "1" && typeof process.
|
|
|
49
49
|
|
|
50
50
|
const monitorEnabled=fullBootstrap?.headless===false;
|
|
51
51
|
const monitorAccountId=monitorEnabled?fullBootstrap.localPrincipal?.accountId:null;
|
|
52
|
+
const monitorTerminalEnabled=monitorEnabled&&fullBootstrap.localPrincipal?.scopes?.includes("terminal")===true;
|
|
52
53
|
const monitorActivity=monitorEnabled?createMonitorActivity():null;
|
|
53
54
|
const automaticSessions=fullBootstrap?createAutomaticSessionBinding({agentId,available:()=>!stopping&&!reauthorizationRequired&&fullRuntime?.available===true,dispatch:invocation=>fullRuntime.dispatch(invocation)}):null;
|
|
54
55
|
function monitorSnapshot(){
|
|
@@ -680,8 +681,18 @@ function connect() {
|
|
|
680
681
|
};
|
|
681
682
|
const responseBytes = Buffer.byteLength(serializeResponse(message.requestId, result, responseMeta), "utf8");
|
|
682
683
|
try { usage.record({ ...recentEntry, requestBytes, responseBytes }, message.payload, result); } catch {}
|
|
683
|
-
|
|
684
|
-
|
|
684
|
+
let activityDetails=captured(result);
|
|
685
|
+
if(monitorTerminalEnabled&&autoContext?.accountId===monitorAccountId){
|
|
686
|
+
const terminal=observedTerminalResult(action,result);
|
|
687
|
+
if(terminal)activityDetails={...(activityDetails??{files:[],omitted:0}),terminal};
|
|
688
|
+
}
|
|
689
|
+
if(ownedFull&&message.payload.operation==="full.coding.prepare"&&result?.result?.taskSessionId){
|
|
690
|
+
monitorActivity?.bindSession(message.requestId,result.result.taskSessionId);
|
|
691
|
+
}
|
|
692
|
+
if(ownedFull&&message.payload.operation==="full.session.ensure"&&result?.ok===true&&result.result?.session?.taskSessionId){
|
|
693
|
+
monitorActivity?.bindSession(message.requestId,result.result.session.taskSessionId);
|
|
694
|
+
}
|
|
695
|
+
const partialFailure=activityDetails?.files?.some(file=>file.outcome==="failed")||ownedFull&&result?.result?.ok===false;
|
|
685
696
|
emitUi("tool:end", {
|
|
686
697
|
requestId: message.requestId,
|
|
687
698
|
action,
|
package/agent/local-usage.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { createHash, randomUUID } from "node:crypto";
|
|
4
4
|
import { configDir } from "../cli/config.mjs";
|
|
5
|
+
import { REMOTE_FULL_OPERATIONS } from "../packages/full-contracts/remote-session.mjs";
|
|
5
6
|
|
|
6
7
|
export const RECENT_CALL_CAPACITY = 1000;
|
|
7
8
|
const RETENTION_DAYS = 30;
|
|
@@ -9,7 +10,9 @@ const DAY_MS = 86400000;
|
|
|
9
10
|
const MAX_PAGE_BYTES = 48 * 1024;
|
|
10
11
|
const MAX_FILE_BYTES = 1024 * 1024;
|
|
11
12
|
const FLUSH_MS = 30_000;
|
|
13
|
+
const FULL_ACTIONS = new Set(REMOTE_FULL_OPERATIONS);
|
|
12
14
|
const ACTIONS = new Set([
|
|
15
|
+
...FULL_ACTIONS,
|
|
13
16
|
"ping", "agent.config", "agent.recentCalls", "agent.usageStats",
|
|
14
17
|
"agent.lifecycle.status", "agent.lifecycle.drain", "agent.lifecycle.resume",
|
|
15
18
|
"agent.lifecycle.restart", "agent.lifecycle.upgrade",
|
|
@@ -138,6 +141,11 @@ export class LocalUsageHistory {
|
|
|
138
141
|
|
|
139
142
|
record(entry, payload = {}, result = null) {
|
|
140
143
|
const seq = this.nextSeq++;
|
|
144
|
+
// Count only allowlisted operations from executed Full invocations, not
|
|
145
|
+
// advertised capabilities, guidance, or arbitrary caller-provided names.
|
|
146
|
+
if (entry.action === "full.invoke" && payload?.action === "full.invoke" && FULL_ACTIONS.has(payload.operation)) {
|
|
147
|
+
entry = { ...entry, action: payload.operation };
|
|
148
|
+
}
|
|
141
149
|
this.ring[(seq - 1) % RECENT_CALL_CAPACITY] = {
|
|
142
150
|
...entry, seq, action: String(entry.action || "other").slice(0, 100),
|
|
143
151
|
summary: String(entry.summary || "").slice(0, 160),
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import {humanizeToolCall} from "./toolcall-summary.mjs";
|
|
2
|
+
import {activityPreview,redactPresentationText} from "./presentation-redaction.mjs";
|
|
2
3
|
import {activityIcon} from "./toolcall-context.mjs";
|
|
3
4
|
import {historicalDiff,projectActivityDetails,displayActivityPath,activityChangeTotals} from "./activity-capture.mjs";
|
|
4
5
|
import {monitorActivityId,normalizeLearnMonitorMetadata} from "../packages/full-contracts/monitor-metadata.mjs";
|
|
@@ -7,6 +8,9 @@ import {monitorActivityId,normalizeLearnMonitorMetadata} from "../packages/full-
|
|
|
7
8
|
// request (not one per start/end); never retain raw request bodies or output.
|
|
8
9
|
export const MAX_MONITOR_ROWS=100;
|
|
9
10
|
const DETAIL_TTL_MS=15*60*1000;
|
|
11
|
+
export const SESSION_IDLE_MS=60000,SESSION_HIDE_MS=15*60*1000;
|
|
12
|
+
const MAX_SESSION_PRESENCE=127;
|
|
13
|
+
const sessionId=value=>typeof value==="string"&&/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value)?value:null;
|
|
10
14
|
const clean=(value,n)=>typeof value==="string"?value.replace(/[\u0000-\u001f\u007f]/g," ").replace(/\s+/g," ").trim().slice(0,n).toWellFormed():"";
|
|
11
15
|
const code=value=>typeof value==="string"&&/^[A-Za-z0-9_.:-]{1,100}$/.test(value)?value:"tool";
|
|
12
16
|
const detailed=new Set(["fs.read","fs.write","fs.edit","fs.delete","fs.stat","fs.list","fs.readMany","fs.readMany.relative","fs.editMany","fs.batch","fs.batch.compact","terminal.exec","terminal.exec.compact","terminal.batch.start","terminal.batch.read","terminal.batch.read.compact","terminal.batch.status","terminal.read","terminal.read.compact","terminal.list"]);
|
|
@@ -31,6 +35,7 @@ export function describeFullMonitorActivity(action,input={}){
|
|
|
31
35
|
case "full.intelligence.symbols":return "Find code symbols";
|
|
32
36
|
case "full.intelligence.dependencies":return "Inspect dependencies";
|
|
33
37
|
case "full.intelligence.impact":return "Review affected code";
|
|
38
|
+
case "full.coding.prepare":return "Prepare coding context";
|
|
34
39
|
case "full.session.ensure":return "Prepare task session";
|
|
35
40
|
case "full.session.list":return "List task sessions";
|
|
36
41
|
case "full.session.snapshot":return "Read task session";
|
|
@@ -62,64 +67,118 @@ export function describeFullMonitorActivity(action,input={}){
|
|
|
62
67
|
const bytes=value=>Number.isSafeInteger(value)&&value>=0?value:null;
|
|
63
68
|
const safeError=value=>typeof value==="string"&&/^[a-z][a-z0-9_]{1,95}$/.test(value)?value:"";
|
|
64
69
|
|
|
70
|
+
// Retain only a small, redacted display projection of output already delivered
|
|
71
|
+
// to the owner chat. No raw commands, replay requests, disk logs or extra RPCs.
|
|
72
|
+
export function observedTerminalResult(action,result){
|
|
73
|
+
if(!["terminal.exec","terminal.exec.compact","terminal.read","terminal.read.compact"].includes(action)||!result||typeof result!=="object")return null;
|
|
74
|
+
const exitCode=Number.isSafeInteger(result.exitCode)&&result.status!=="running"&&result.outputDraining!==true?result.exitCode:null;
|
|
75
|
+
const pieces=Array.isArray(result.chunks)?result.chunks.map(c=>typeof c?.text==="string"?c.text:""):[result.stdout,result.stderr].filter(v=>typeof v==="string");
|
|
76
|
+
const size=pieces.reduce((n,v)=>n+v.length,0);
|
|
77
|
+
// Redact before clipping; skip oversized output rather than scan unbounded text.
|
|
78
|
+
const safe=size<=65536?redactPresentationText(pieces.join(Array.isArray(result.chunks)?"":"\n"),size+1).trim():"";
|
|
79
|
+
const partial=size>65536||safe.length>2048||result.truncated===true||result.hasMore===true||result.outputIncomplete===true||Number(result.omittedChars)>0;
|
|
80
|
+
const text=safe.slice(-2048).toWellFormed()|| (partial?"Output omitted by capture limits or compact mode.":"");
|
|
81
|
+
if(!text&&exitCode===null&&!partial)return null;
|
|
82
|
+
return {text,exitCode,partial};
|
|
83
|
+
}
|
|
84
|
+
|
|
65
85
|
export function createMonitorActivity({now=()=>new Date()}={}){
|
|
66
|
-
const rows=new Map(),running=new
|
|
86
|
+
const rows=new Map(),running=new Map(),details=new Map(),presence=new Map(),outputs=new Map();
|
|
67
87
|
const localTime=new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"});
|
|
68
88
|
let calls=0,errors=0,learnEvents=0,sequence=0;
|
|
69
|
-
|
|
89
|
+
// Session liveness is independent of the 100-row activity ring. Retain only
|
|
90
|
+
// bounded display metadata, so a burst of calls cannot hide an active chat.
|
|
91
|
+
const observe=(row)=>{
|
|
92
|
+
const id=sessionId(row.taskSessionId);if(!id)return;
|
|
93
|
+
const at=row.completedAt??Date.parse(row.at),previous=presence.get(id);
|
|
94
|
+
if(previous&&previous.at>at){
|
|
95
|
+
if(!previous.project&&row.project)previous.project=row.project;
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
presence.delete(id);
|
|
99
|
+
presence.set(id,{taskSessionId:id,at,time:localTime.format(new Date(at)),project:row.project||previous?.project||"",failed:row.ok===false});
|
|
100
|
+
while(presence.size>MAX_SESSION_PRESENCE)presence.delete(presence.keys().next().value);
|
|
101
|
+
};
|
|
102
|
+
const remember=(key,row)=>{rows.set(key,row);observe(row);while(rows.size>MAX_MONITOR_ROWS){const first=rows.keys().next().value;details.delete(rows.get(first).requestId);outputs.delete(rows.get(first).requestId);rows.delete(first);}return row;};
|
|
70
103
|
const stamp=()=>{const at=now();return {at:at.toISOString(),time:localTime.format(at)};};
|
|
71
|
-
const prune=()=>{const cutoff=now().getTime()-DETAIL_TTL_MS;for(const row of rows.values())if(Date.parse(row.at)<cutoff)details.delete(row.requestId);};
|
|
104
|
+
const prune=()=>{const cutoff=now().getTime()-DETAIL_TTL_MS;for(const row of rows.values())if(Date.parse(row.at)<cutoff){details.delete(row.requestId);outputs.delete(row.requestId);}};
|
|
72
105
|
return {
|
|
73
106
|
accept(event,payload={}){
|
|
74
107
|
if(event==="tool:start"){
|
|
75
108
|
const key=payload.requestId;
|
|
76
109
|
if(typeof key!=="string"||running.has(key))return;
|
|
77
|
-
calls++;
|
|
110
|
+
calls++;
|
|
78
111
|
const action=code(payload.monitorAction??payload.action),category=action.startsWith("full.")?"Full":clean(payload.category,32)||"Agent";
|
|
79
112
|
// The TUI's descriptive operations are reused only for known routes
|
|
80
113
|
// that do not embed arbitrary request data. Search/filter and unknown
|
|
81
114
|
// arguments are deliberately not forwarded.
|
|
82
|
-
const label=action.startsWith("full.")?clean(payload.monitorOperation,128)||describeFullMonitorActivity(action):action==="fs.artifact"?("Export "+(displayActivityPath(payload.detail).split("/").at(-1)||"file")):action==="terminal.start"?"Start background task":action.startsWith("fs.search.")?(action==="fs.search.start"?"Search project files":"Read search results"):detailed.has(action)?clean(payload.operation,128):humanizeToolCall({action});
|
|
83
|
-
remember(key,{requestId:"monitor-"+(++sequence),...stamp(),action,category,icon:activityIcon({action,category,operation:label})||(category==="Full"?"⚙":"·"),operation:label||humanizeToolCall({action}),project:clean(payload.project,64),taskSessionId:
|
|
115
|
+
const label=action.startsWith("full.")?clean(payload.monitorOperation,128)||describeFullMonitorActivity(action):action==="fs.artifact"?("Export "+(displayActivityPath(payload.detail).split("/").at(-1)||"file")):action==="terminal.start"?(payload.operation==="Commit changes"?"Commit changes":"Start background task"):action.startsWith("fs.search.")?(action==="fs.search.start"?"Search project files":"Read search results"):detailed.has(action)?clean(payload.operation,128):humanizeToolCall({action});
|
|
116
|
+
const row=remember(key,{requestId:"monitor-"+(++sequence),...stamp(),action,category,icon:activityIcon({action,category,operation:label})||(category==="Full"?"⚙":"·"),operation:label||humanizeToolCall({action}),project:clean(payload.project,64),taskSessionId:sessionId(payload.monitorTaskSessionId),status:"running",ok:null,durationMs:null,requestBytes:bytes(payload.requestBytes),responseBytes:null,error:"",pollKey:typeof payload.monitorPollKey==="string"&&/^[a-f0-9]{24}$/.test(payload.monitorPollKey)?payload.monitorPollKey:null,query:clean(payload.query,180),searchScope:clean(payload.searchScope,180),detail:detailed.has(action)||action==="terminal.start"&&label==="Commit changes"?clean(payload.detail,160):""});
|
|
117
|
+
running.set(key,row);
|
|
84
118
|
}else if(event==="tool:end"){
|
|
85
|
-
const key=payload.requestId;if(!running.delete(key)
|
|
86
|
-
const
|
|
119
|
+
const key=payload.requestId,row=running.get(key);if(!row)return;running.delete(key);
|
|
120
|
+
const terminal=payload.activityDetails?.terminal;
|
|
121
|
+
const exitCode=terminal?terminal.exitCode:payload.activityDetails?.exitCode;
|
|
122
|
+
const exitFailed=Number.isInteger(exitCode)&&exitCode!==0;
|
|
123
|
+
if(Number.isSafeInteger(exitCode))row.exitCode=exitCode;
|
|
124
|
+
if(rows.get(key)===row&&terminal&&(terminal.text||terminal.partial))outputs.set(row.requestId,terminal);
|
|
87
125
|
const failed=payload.ok===false||exitFailed;
|
|
88
126
|
if(failed)errors++;
|
|
89
|
-
|
|
90
|
-
if(payload.activityDetails){
|
|
91
|
-
|
|
127
|
+
{
|
|
128
|
+
if(rows.get(key)===row&&payload.activityDetails){
|
|
129
|
+
if(row.operation==="Commit changes"&&!failed&&payload.activityDetails.commitSubject)row.detail=activityPreview(payload.activityDetails.commitSubject,160);
|
|
130
|
+
const {commitSubject,terminal,...extra}=payload.activityDetails;
|
|
131
|
+
// A commit subject is already shown inline; no redundant expansion.
|
|
132
|
+
if(extra.files?.length||extra.omitted||extra.query||extra.searchScope||extra.exitCode!==null&&extra.exitCode!==undefined&&extra.exitCode!==0||extra.resultCount!==null&&extra.resultCount!==undefined)details.set(row.requestId,extra);
|
|
92
133
|
const totals=activityChangeTotals(payload.activityDetails);
|
|
93
134
|
if(totals)Object.assign(row,totals);
|
|
94
135
|
}
|
|
95
|
-
Object.assign(row,{status:payload.status==="cancelled"?"cancelled":failed?"failed":"done",ok:!failed,durationMs:bytes(payload.durationMs)===null?null:Math.min(86400000,payload.durationMs),responseBytes:bytes(payload.responseBytes),error:safeError(payload.error)||(exitFailed?"command_exit_nonzero":"")});
|
|
136
|
+
Object.assign(row,{status:payload.status==="cancelled"?"cancelled":failed?"failed":"done",ok:!failed,durationMs:bytes(payload.durationMs)===null?null:Math.min(86400000,payload.durationMs),responseBytes:bytes(payload.responseBytes),error:safeError(payload.error)||(exitFailed?"command_exit_nonzero":""),completedAt:now().getTime()});
|
|
137
|
+
observe(row);
|
|
96
138
|
}
|
|
97
139
|
}else if(event==="learn"){
|
|
98
140
|
learnEvents++;
|
|
99
141
|
const activity=payload.activity??{},tool=code(activity.tool);
|
|
100
142
|
const change=activity.change??{},rowId="learn-"+(++sequence),metadata=activity.ok===false?null:normalizeLearnMonitorMetadata(activity.metadata);
|
|
101
143
|
const retrieved=metadata?.retrieved;
|
|
102
|
-
const
|
|
103
|
-
const
|
|
104
|
-
|
|
144
|
+
const mutation=tool==="learn_put"&&activity.ok!==false&&["created","updated"].includes(change.type)&&change.key;
|
|
145
|
+
const summary=mutation?activityPreview(change.summary):"";
|
|
146
|
+
const operation=mutation&&change.type==="created"?"Add Learn memory":retrieved!==undefined?(tool==="learn_get"?"Read ":"Load ")+retrieved+(retrieved===1?" Learn memory":" Learn memories"):learnLabels[tool]||"Learn activity";
|
|
147
|
+
const detail=metadata?.evaluated!==undefined?metadata.evaluated+" evaluated · "+metadata.applied+" applied · "+metadata.verified+" verified":summary||[clean(change.key,100),clean(change.scope??activity.scopeSummary,50)].filter(Boolean).join(" · ");
|
|
148
|
+
remember(rowId,{requestId:rowId,...stamp(),conversationId:monitorActivityId(payload.monitorConversationId),taskSessionId:sessionId(payload.monitorTaskSessionId),action:"learn",category:"Learn",icon:"🧠",operation,project:clean(change.scope==="project"?change.scopeKey:activity.projectKey,64),detail:clean(detail,160),status:activity.ok===false?"failed":"done",ok:activity.ok!==false,durationMs:bytes(activity.durationMs)});
|
|
105
149
|
if(retrieved!==undefined&&retrieved>0)details.set(rowId,{files:[],omitted:0,learn:metadata});
|
|
150
|
+
else if(mutation)details.set(rowId,{files:[],omitted:0,learn:{change:{key:clean(change.key,100),scope:clean(change.scope,20),kind:clean(change.kind,40),summary}}});
|
|
106
151
|
}else return false;
|
|
107
152
|
return true;
|
|
108
153
|
},
|
|
109
|
-
snapshot(){
|
|
154
|
+
snapshot(){
|
|
155
|
+
prune();const current=now().getTime();
|
|
156
|
+
const activeIds=new Set();
|
|
157
|
+
for(const row of running.values()){
|
|
158
|
+
const id=sessionId(row.taskSessionId);
|
|
159
|
+
if(!id)continue;
|
|
160
|
+
activeIds.add(id);
|
|
161
|
+
if(!presence.has(id))observe(row);
|
|
162
|
+
}
|
|
163
|
+
for(const [id,entry] of presence)if(!activeIds.has(id)&¤t-entry.at>=SESSION_HIDE_MS)presence.delete(id);
|
|
164
|
+
const sessionPresence=[...presence.values()].map(({at,...entry})=>({...entry,ageMs:Math.max(0,current-at),working:activeIds.has(entry.taskSessionId)}));
|
|
165
|
+
return {calls,errors,active:running.size,learnEvents,sessionPresence,activity:[...rows.values()].slice(-MAX_MONITOR_ROWS).map(({conversationId,completedAt,...row})=>({...row,elapsedMs:row.status==="running"?Math.max(0,current-Date.parse(row.at)):null,hasDetails:details.has(row.requestId),...(outputs.has(row.requestId)?{hasOutput:true}:{})}))};
|
|
166
|
+
},
|
|
110
167
|
bindSession(requestId,taskSessionId){
|
|
111
|
-
const row=rows.get(requestId);
|
|
112
|
-
if(!row||row.taskSessionId
|
|
113
|
-
row.taskSessionId=taskSessionId;return true;
|
|
168
|
+
const row=rows.get(requestId)??running.get(requestId);
|
|
169
|
+
if(!row||row.taskSessionId||!sessionId(taskSessionId))return false;
|
|
170
|
+
row.taskSessionId=taskSessionId;observe(row);return true;
|
|
114
171
|
},
|
|
115
172
|
bindConversation(conversationId,taskSessionId){
|
|
116
173
|
if(!monitorActivityId(conversationId)||typeof taskSessionId!=="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(taskSessionId))return false;
|
|
117
174
|
let changed=false;
|
|
118
|
-
for(const row of rows.values())if(row.conversationId===conversationId&&!row.taskSessionId){row.taskSessionId=taskSessionId;changed=true;}
|
|
175
|
+
for(const row of rows.values())if(row.conversationId===conversationId&&!row.taskSessionId){row.taskSessionId=taskSessionId;observe(row);changed=true;}
|
|
119
176
|
return changed;
|
|
120
177
|
},
|
|
121
178
|
forgetSession(taskSessionId){
|
|
122
|
-
|
|
179
|
+
presence.delete(taskSessionId);
|
|
180
|
+
for(const [key,row] of rows){if(row.taskSessionId===taskSessionId){details.delete(row.requestId);outputs.delete(row.requestId);rows.delete(key);}}
|
|
181
|
+
for(const row of running.values())if(row.taskSessionId===taskSessionId)row.taskSessionId=null;
|
|
123
182
|
},
|
|
124
183
|
detail(activityId,fileId){
|
|
125
184
|
prune();
|
|
@@ -129,7 +188,7 @@ export function createMonitorActivity({now=()=>new Date()}={}){
|
|
|
129
188
|
const file=detail?.files.find(f=>f.fileId===fileId);
|
|
130
189
|
return {activityId,fileId,...historicalDiff(file?.pair)};
|
|
131
190
|
}
|
|
132
|
-
return {activityId,...projectActivityDetails(detail),...(detail?.learn?{learn:detail.learn}:{})};
|
|
191
|
+
return {activityId,...projectActivityDetails(detail),...(detail?.learn?{learn:detail.learn}:{}),...(row&&outputs.has(activityId)?{terminal:outputs.get(activityId)}:{})};
|
|
133
192
|
}
|
|
134
193
|
};
|
|
135
194
|
}
|
|
@@ -1,10 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export function redactPresentationText(value,max=12000){
|
|
3
|
-
// Best-effort display redaction, not a claim to recognize arbitrary secrets.
|
|
4
|
-
return text(value,max).replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,"[private key redacted]")
|
|
5
|
-
.replace(/\b(Bearer\s+)[A-Za-z0-9._~+\/-]+/gi,"$1[redacted]")
|
|
6
|
-
.replace(/\b((?:password|passwd|secret|api[_-]?key|access[_-]?token|refresh[_-]?token|authorization)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,"$1[redacted]")
|
|
7
|
-
.replace(/\b(sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,})\b/g,"[credential redacted]")
|
|
8
|
-
.replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi,"$1[redacted]@")
|
|
9
|
-
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"");
|
|
10
|
-
}
|
|
1
|
+
export {redactPresentationText,activityPreview} from "../packages/full-contracts/presentation-redaction.mjs";
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
2
|
import { humanizeToolCall } from "./toolcall-summary.mjs";
|
|
3
|
+
import { activityPreview } from "./presentation-redaction.mjs";
|
|
3
4
|
|
|
4
5
|
export function activityCategory(item) {
|
|
5
6
|
if (item.category) return String(item.category);
|
|
@@ -146,8 +147,45 @@ function relativeLocation(value, project) {
|
|
|
146
147
|
return parts.length > 3 ? "…/" + parts.slice(-3).join("/") : normalized.slice(0, 130);
|
|
147
148
|
}
|
|
148
149
|
|
|
150
|
+
// Extract a literal commit subject, never the surrounding command.
|
|
151
|
+
function commitCommands(command){
|
|
152
|
+
if(typeof command!=="string"||command.length>16000)return [];
|
|
153
|
+
let start=0,quote="",escaped=false;
|
|
154
|
+
const segments=[];
|
|
155
|
+
for(let i=0;i<command.length;i++){
|
|
156
|
+
const c=command[i];
|
|
157
|
+
if(escaped){escaped=false;continue;}
|
|
158
|
+
if(c==="\\"&"e!=="'"){escaped=true;continue;}
|
|
159
|
+
if(quote){if(c===quote)quote="";continue;}
|
|
160
|
+
if(c==="'"||c==='"'){quote=c;continue;}
|
|
161
|
+
if(c===";"||c==="&"||c==="|"||c==="\n"){segments.push(command.slice(start,i));start=i+1;}
|
|
162
|
+
}
|
|
163
|
+
segments.push(command.slice(start));
|
|
164
|
+
return segments.filter(segment=>/^\s*git(?:\.exe)?\s+commit(?:\s|$)/i.test(segment));
|
|
165
|
+
}
|
|
166
|
+
function commitSubject(command){
|
|
167
|
+
for(const segment of commitCommands(command)){
|
|
168
|
+
const match=segment.match(/(?:^|\s)(?:-m\s+|--message(?:=|\s+))(["'])(.*?)\1(?:\s|$)/);
|
|
169
|
+
if(!match||!match[2]||/[\r\n]/.test(match[2])||match[1]==='"'&&/[$%\x60\\]/.test(match[2]))continue;
|
|
170
|
+
return activityPreview(match[2],160);
|
|
171
|
+
}
|
|
172
|
+
return "";
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Prefer the observed Git summary over a literal argument when available.
|
|
176
|
+
export function observedCommitSubject(command,stdout){
|
|
177
|
+
if(!commitCommands(command).length||typeof stdout!=="string")return "";
|
|
178
|
+
const lines=stdout.slice(-16000).split(/\r?\n/);
|
|
179
|
+
for(let i=lines.length-1;i>=0;i--){
|
|
180
|
+
const match=lines[i].match(/^\[[^\]\r\n]{1,200} [0-9a-f]{4,64}\] ([^\r\n]{1,1000})$/i);
|
|
181
|
+
if(match)return activityPreview(match[1],160);
|
|
182
|
+
}
|
|
183
|
+
return "";
|
|
184
|
+
}
|
|
185
|
+
|
|
149
186
|
function terminalTitle(payload) {
|
|
150
187
|
const command = String(payload.command || "");
|
|
188
|
+
if (commitCommands(command).length) return "Commit changes";
|
|
151
189
|
if (/\bGet-Command\s+(?:rg|ripgrep)\b/i.test(command)) return "Check ripgrep availability";
|
|
152
190
|
const toolCheck = command.match(/\bGet-Command\s+([a-z][a-z0-9.-]{0,25})\b/i);
|
|
153
191
|
if (toolCheck?.[1]) return "Check " + toolCheck[1] + " availability";
|
|
@@ -167,7 +205,6 @@ function terminalTitle(payload) {
|
|
|
167
205
|
if (/\bnode\s+--test\b/i.test(command)) return "Run unit tests";
|
|
168
206
|
if (/\bgit\s+diff\s+--check\b/i.test(command)) return "Validate Git changes";
|
|
169
207
|
if (/\bgit\s+status\b/i.test(command) && !/\bgit\s+commit\b/i.test(command)) return "Review Git status";
|
|
170
|
-
if (/\bgit\s+commit\b/i.test(command)) return "Commit changes";
|
|
171
208
|
if (/\bGet-ChildItem\b/i.test(command)) return "Inspect project files";
|
|
172
209
|
const translated = humanizeToolCall(payload).replace(/\s+· in [^·]+$/, "");
|
|
173
210
|
if (translated.startsWith("Run ")) {
|
|
@@ -230,6 +267,7 @@ export function describeToolActivity(payload = {}, allowedRoots = [], linkedCont
|
|
|
230
267
|
case "terminal.exec":
|
|
231
268
|
case "terminal.start":
|
|
232
269
|
operation = terminalTitle(payload);
|
|
270
|
+
if (operation === "Commit changes") detail = commitSubject(payload.command);
|
|
233
271
|
break;
|
|
234
272
|
case "terminal.batch.start":
|
|
235
273
|
operation = "Run " + count(payload.jobs) + " terminal tasks";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "2.
|
|
3
|
-
"publicKey": "-----BEGIN PUBLIC KEY-----\
|
|
2
|
+
"version": "2.2.0",
|
|
3
|
+
"publicKey": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAaE+ab0fqmb3MqNkmdmJe7vojF0ZNZlP/99ZkQ21UYNY=\n-----END PUBLIC KEY-----\n"
|
|
4
4
|
}
|
package/package.json
CHANGED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const text=(v,n=512)=>typeof v==="string"?v.slice(0,n).toWellFormed():"";
|
|
2
|
+
export function redactPresentationText(value,max=12000){
|
|
3
|
+
// Best-effort display redaction, not a claim to recognize arbitrary secrets.
|
|
4
|
+
return text(value,max).replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,"[private key redacted]")
|
|
5
|
+
.replace(/\b(Bearer\s+)[A-Za-z0-9._~+\/-]+/gi,"$1[redacted]")
|
|
6
|
+
.replace(/\b((?:password|passwd|secret|api[_-]?key|access[_-]?token|refresh[_-]?token|authorization)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,"$1[redacted]")
|
|
7
|
+
.replace(/\b(sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,})\b/g,"[credential redacted]")
|
|
8
|
+
.replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi,"$1[redacted]@")
|
|
9
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"");
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// Redact before truncating so credentials crossing the preview boundary stay hidden.
|
|
13
|
+
export function activityPreview(value,max=320){
|
|
14
|
+
if(typeof value!=="string"||value.length>16000)return "";
|
|
15
|
+
return redactPresentationText(value,value.length).replace(/\s+/g," ").trim().slice(0,max).toWellFormed();
|
|
16
|
+
}
|
|
@@ -7,9 +7,11 @@ const record=value=>value!==null&&typeof value==="object"&&!Array.isArray(value)
|
|
|
7
7
|
const require=(condition,code)=>{if(!condition)throw new FullContractError(code);};
|
|
8
8
|
const exact=(value,fields)=>record(value)&&Object.keys(value).every(key=>fields.includes(key));
|
|
9
9
|
const relativePath=relative=>typeof relative==="string"&&relative.length>0&&relative.length<=512&&relative.split("/").every(part=>part.length>0&&part!=="."&&part!==".."&&![".git",".workspace",".relay-workspace-owner.json"].includes(part.toLowerCase())&&!/[\\:\u0000-\u001f]/.test(part)&&!/[. ]$/.test(part)&&!/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part));
|
|
10
|
+
// Core-only composition of existing authorized Full operations, not a host operation.
|
|
11
|
+
export const CODING_PREPARE_OPERATION="full.coding.prepare";
|
|
10
12
|
const descriptors={
|
|
11
13
|
"full.session.ensure":{fields:["intent","taskSessionId","idempotencyKey","title","projectKey"],write:true},
|
|
12
|
-
"full.session.list":{fields:["after","limit"]},
|
|
14
|
+
"full.session.list":{fields:["after","limit","monitorSessionIds"]},
|
|
13
15
|
"full.session.snapshot":{fields:["taskSessionId","consumerId","cursor"],session:true},
|
|
14
16
|
"full.session.acknowledge":{fields:["taskSessionId","consumerId","cursor","revision"],session:true},
|
|
15
17
|
"full.task.checkpoint":{fields:["taskSessionId","expectedRevision","facts"],session:true,write:true},
|
|
@@ -40,6 +42,7 @@ const descriptors={
|
|
|
40
42
|
"full.diagnostics.export":{fields:["taskSessionId","confirmed"],session:true},
|
|
41
43
|
"full.desktop.windows":{fields:["taskSessionId","limit"],session:true,desktopRead:true},
|
|
42
44
|
"full.desktop.step":{fields:["taskSessionId","idempotencyKey","actions","settleMs"],session:true,write:true,desktopControl:true},
|
|
45
|
+
[CODING_PREPARE_OPERATION]:{fields:["taskSessionId","idempotencyKey","title","projectKey","repoPath","taskContext"],write:true},
|
|
43
46
|
"full.session.export":{fields:["taskSessionId","confirmed","cursor"],session:true},
|
|
44
47
|
"full.session.delete":{fields:["taskSessionId","confirmed","expectedRevision"],session:true,write:true}
|
|
45
48
|
};
|
|
@@ -75,11 +78,27 @@ export function parseRemoteFullRequest(value){
|
|
|
75
78
|
const input=record(value.input)?{...value.input}:value.input;
|
|
76
79
|
require(exact(input,descriptor.fields),"full_invalid_remote_input");
|
|
77
80
|
if(descriptor.session||Object.hasOwn(input,"taskSessionId"))require(id(input.taskSessionId),"full_invalid_session_id");
|
|
81
|
+
if(operation==="full.session.list"&&Object.hasOwn(input,"monitorSessionIds"))require(Array.isArray(input.monitorSessionIds)&&input.monitorSessionIds.length<=128&&input.monitorSessionIds.every(id)&&new Set(input.monitorSessionIds).size===input.monitorSessionIds.length,"full_invalid_page");
|
|
78
82
|
if(operation==="full.session.ensure"){
|
|
79
83
|
require(["create","ensure","resume","new-attempt"].includes(input.intent)&&id(input.idempotencyKey),"full_invalid_intent");
|
|
80
84
|
if(["resume","new-attempt"].includes(input.intent))require(id(input.taskSessionId),"full_invalid_session_id");
|
|
81
85
|
if(input.intent==="create")require(!Object.hasOwn(input,"taskSessionId"),"full_invalid_session_id");
|
|
82
86
|
}
|
|
87
|
+
if(operation===CODING_PREPARE_OPERATION){
|
|
88
|
+
const existing=Object.hasOwn(input,"taskSessionId"),creating=Object.hasOwn(input,"idempotencyKey");
|
|
89
|
+
require(existing!==creating,"full_coding_session_identity_required");
|
|
90
|
+
if(existing)require(input.title===undefined&&input.projectKey===undefined,"full_invalid_remote_input");
|
|
91
|
+
else {
|
|
92
|
+
require(id(input.idempotencyKey)&&input.repoPath!==undefined,"full_invalid_remote_input");
|
|
93
|
+
require(input.title===undefined||typeof input.title==="string"&&input.title.length<=256&&input.title.isWellFormed(),"full_invalid_remote_input");
|
|
94
|
+
require(input.projectKey===undefined||typeof input.projectKey==="string"&&input.projectKey.length<=200&&input.projectKey.isWellFormed(),"full_invalid_remote_input");
|
|
95
|
+
}
|
|
96
|
+
// Existing sessions may reuse their already verified binding without a path.
|
|
97
|
+
// Supplying a path permits shared checkout binding only, never provisioning.
|
|
98
|
+
if(input.repoPath!==undefined)parseRemoteFullRequest({operation:"full.workspace.ensure",input:{taskSessionId:"validation",kind:"git",repoPath:input.repoPath}});
|
|
99
|
+
require(Object.hasOwn(input,"taskContext"),"full_invalid_task_context");
|
|
100
|
+
parseRemoteFullRequest({operation:"full.intelligence.refresh",input:{taskSessionId:"validation",taskContext:input.taskContext}});
|
|
101
|
+
}
|
|
83
102
|
if(operation==="full.session.export"){
|
|
84
103
|
require(input.confirmed===true,"full_export_confirmation_required");
|
|
85
104
|
if(Object.hasOwn(input,"cursor"))require(typeof input.cursor==="string"&&input.cursor.length>=1&&input.cursor.length<=512&&/^[A-Za-z0-9_-]+$/.test(input.cursor),"full_invalid_cursor");
|