@anusornneal/chat-relay 2.0.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/agent/activity-capture.mjs +57 -4
- package/agent/auto-session-binding.mjs +46 -0
- package/agent/file-manager.mjs +26 -6
- package/agent/full-desktop-broker.mjs +15 -5
- package/agent/git-worktree-manager.mjs +2 -1
- package/agent/local-agent.mjs +29 -2
- package/agent/monitor-activity.mjs +36 -12
- package/agent/toolcall-context.mjs +4 -0
- 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/remote-session.mjs +1 -1
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,4 +1,6 @@
|
|
|
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";
|
|
4
6
|
import {presentationChangePath} from "./full-presentation-changes.mjs";
|
|
@@ -59,6 +61,34 @@ export function createActivityCapture(){
|
|
|
59
61
|
export function runActivityCapture(capture,work){
|
|
60
62
|
return capture?storage.run(capture,work):work();
|
|
61
63
|
}
|
|
64
|
+
// Only Full monitoring requests read a bounded before-image.
|
|
65
|
+
export async function captureActivityBefore(requestedPath,target,afterBytes=0,append=false){
|
|
66
|
+
const context=storage.getStore();
|
|
67
|
+
if(!context||context.closed||context.files.size>=MAX_FILES||
|
|
68
|
+
!displayActivityPath(requestedPath)||!displayActivityPath(target))return undefined;
|
|
69
|
+
const limit=Math.min(MAX_PAIR_BYTES,MAX_CALL_BYTES-context.bytes)-afterBytes;
|
|
70
|
+
const max=append?Math.floor(limit/2):limit;
|
|
71
|
+
if(max<0)return undefined;
|
|
72
|
+
let handle;
|
|
73
|
+
try{
|
|
74
|
+
const initial=await fs.lstat(target);
|
|
75
|
+
if(!initial.isFile()||initial.isSymbolicLink()||initial.size>max)return undefined;
|
|
76
|
+
handle=await fs.open(target,constants.O_RDONLY|(constants.O_NOFOLLOW??0));
|
|
77
|
+
const before=await handle.stat();
|
|
78
|
+
if(!before.isFile()||before.dev!==initial.dev||before.ino!==initial.ino||before.size>max)return undefined;
|
|
79
|
+
const buffer=Buffer.alloc(before.size+1);
|
|
80
|
+
let total=0;
|
|
81
|
+
while(total<buffer.length){
|
|
82
|
+
const {bytesRead}=await handle.read(buffer,total,buffer.length-total,total);
|
|
83
|
+
if(!bytesRead)break;
|
|
84
|
+
total+=bytesRead;
|
|
85
|
+
}
|
|
86
|
+
const after=await handle.stat();
|
|
87
|
+
if(total!==before.size||after.size!==before.size||after.mtimeMs!==before.mtimeMs||after.ctimeMs!==before.ctimeMs)return undefined;
|
|
88
|
+
return buffer.subarray(0,total);
|
|
89
|
+
}catch{return undefined;}
|
|
90
|
+
finally{await handle?.close().catch(()=>{});}
|
|
91
|
+
}
|
|
62
92
|
export function recordActivityEdit(index,requestedPath,before,after,kind,canonicalTarget){
|
|
63
93
|
const context=storage.getStore();
|
|
64
94
|
if(!context||context.closed||context.files.size>=MAX_FILES)return;
|
|
@@ -72,7 +102,7 @@ export function recordActivityEdit(index,requestedPath,before,after,kind,canonic
|
|
|
72
102
|
const size=(before===null?0:Buffer.byteLength(before))+(after===null?0:Buffer.byteLength(after));
|
|
73
103
|
if(size>MAX_PAIR_BYTES||context.bytes+size>MAX_CALL_BYTES)return;
|
|
74
104
|
const a=decode(before),b=decode(after);
|
|
75
|
-
if(a===null||b===null||a.includes("\0")||b.includes("\0")||a.includes("\uFFFD")||b.includes("\uFFFD"))return;
|
|
105
|
+
if(a===null||b===null||!a.isWellFormed()||!b.isWellFormed()||a.includes("\0")||b.includes("\0")||a.includes("\uFFFD")||b.includes("\uFFFD"))return;
|
|
76
106
|
if(redactPresentationText(a,a.length)!==a||redactPresentationText(b,b.length)!==b)return;
|
|
77
107
|
if(a.split("\n").length>MAX_LINES||b.split("\n").length>MAX_LINES)return;
|
|
78
108
|
entry.pair={before:a,after:b};
|
|
@@ -82,7 +112,7 @@ export function recordActivityEdit(index,requestedPath,before,after,kind,canonic
|
|
|
82
112
|
// Exact bounded line edit script from the recorded pair. Retain newline
|
|
83
113
|
// characters in the comparison so final-newline and CRLF changes are real.
|
|
84
114
|
function splitLines(value){return value.match(/[^\n]*\n|[^\n]+$/g)??[];}
|
|
85
|
-
export function historicalDiff(pair,{includeText=true}={}){
|
|
115
|
+
export function historicalDiff(pair,{includeText=true,maxCells=Infinity}={}){
|
|
86
116
|
if(!pair)return {state:"unavailable",reason:"No captured text for this call",additions:null,deletions:null,text:""};
|
|
87
117
|
const a=splitLines(pair.before),b=splitLines(pair.after);
|
|
88
118
|
if(a.length>MAX_LINES||b.length>MAX_LINES)return {state:"unavailable",reason:"Change exceeds capture limit",additions:null,deletions:null,text:""};
|
|
@@ -91,7 +121,9 @@ export function historicalDiff(pair,{includeText=true}={}){
|
|
|
91
121
|
let start=0,ae=a.length,be=b.length;
|
|
92
122
|
while(start<ae&&start<be&&a[start]===b[start])start++;
|
|
93
123
|
while(ae>start&&be>start&&a[ae-1]===b[be-1]){ae--;be--;}
|
|
94
|
-
const width=be-start+1,
|
|
124
|
+
const width=be-start+1,cells=(ae-start+1)*width;
|
|
125
|
+
if(cells>maxCells)return {state:"unavailable",reason:"Summary budget exceeded",additions:null,deletions:null,text:""};
|
|
126
|
+
const dp=new Uint16Array(cells);
|
|
95
127
|
const cell=(i,j)=>(i-start)*width+j-start;
|
|
96
128
|
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
129
|
const lines=includeText?a.slice(0,start).map(line=>[" ",line]):[];
|
|
@@ -155,11 +187,32 @@ export function finishActivityCapture(capture,payload,result){
|
|
|
155
187
|
const details={files,omitted,...search,exitCode:Number.isInteger(output?.exitCode)?output.exitCode:null,resultCount:safeInteger(output?.totalResults??output?.total),error:safeError(result?.error)};
|
|
156
188
|
return files.length||omitted||details.query||details.searchScope||(details.exitCode!==null&&details.exitCode!==0)||details.resultCount!==null?details:null;
|
|
157
189
|
}
|
|
190
|
+
const summaryCache=new WeakMap();
|
|
191
|
+
function changeStats(pair,maxCells=Infinity){
|
|
192
|
+
if(!pair)return historicalDiff(null,{includeText:false});
|
|
193
|
+
const cached=summaryCache.get(pair);
|
|
194
|
+
if(cached)return cached;
|
|
195
|
+
const stats=historicalDiff(pair,{includeText:false,maxCells});
|
|
196
|
+
if(stats.state==="ready")summaryCache.set(pair,stats);
|
|
197
|
+
return stats;
|
|
198
|
+
}
|
|
199
|
+
// Calculate small exact summaries only once; larger rewrites remain lazy.
|
|
200
|
+
export function activityChangeTotals(details){
|
|
201
|
+
if(!details?.files?.length||details.omitted)return null;
|
|
202
|
+
let additions=0,deletions=0;
|
|
203
|
+
for(const file of details.files){
|
|
204
|
+
if(!["added","modified","deleted","written"].includes(file.kind)||file.outcome!=="completed")return null;
|
|
205
|
+
const stats=changeStats(file.pair,4096);
|
|
206
|
+
if(stats.state!=="ready")return null;
|
|
207
|
+
additions+=stats.additions;deletions+=stats.deletions;
|
|
208
|
+
}
|
|
209
|
+
return {additions,deletions};
|
|
210
|
+
}
|
|
158
211
|
export function projectActivityDetails(details){
|
|
159
212
|
if(!details)return {files:[],available:false};
|
|
160
213
|
return {available:true,omitted:details.omitted??0,query:details.query??"",searchScope:details.searchScope??"",exitCode:details.exitCode,resultCount:details.resultCount,error:details.error,
|
|
161
214
|
files:details.files.map(({pair,...file})=>{
|
|
162
|
-
const stats=
|
|
215
|
+
const stats=changeStats(pair);
|
|
163
216
|
return {...file,diffAvailable:stats.state==="ready",additions:stats.additions,deletions:stats.deletions};
|
|
164
217
|
})};
|
|
165
218
|
}
|
|
@@ -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
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import fs from "node:fs/promises";
|
|
2
|
-
import {describeFullMonitorActivity} from "./monitor-activity.mjs";
|
|
2
|
+
import {describeFullMonitorActivity,MAX_MONITOR_ROWS} 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";
|
|
@@ -92,13 +92,15 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
|
|
|
92
92
|
const rawMonitor=monitorSnapshot();
|
|
93
93
|
// Local labels are bounded and redacted before crossing the presentation
|
|
94
94
|
// boundary. On authority loss, retain counters but not task/project labels.
|
|
95
|
-
const monitor=rawMonitor?{...rawMonitor,activity:(Array.isArray(rawMonitor.activity)?rawMonitor.activity:[]).slice(-
|
|
95
|
+
const monitor=rawMonitor?{...rawMonitor,activity:(Array.isArray(rawMonitor.activity)?rawMonitor.activity:[]).slice(-MAX_MONITOR_ROWS).map(row=>({
|
|
96
96
|
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
97
|
category:text(row.category,32),icon:text(row.icon,8),operation:redactPresentationText(row.operation,128),
|
|
98
98
|
project:redactPresentationText(row.project,64),status:text(row.status,16),ok:typeof row.ok==="boolean"?row.ok:null,
|
|
99
99
|
durationMs:Number.isFinite(row.durationMs)?Math.max(0,row.durationMs):null,elapsedMs:Number.isFinite(row.elapsedMs)?Math.max(0,row.elapsedMs):null,
|
|
100
100
|
requestBytes:Number.isSafeInteger(row.requestBytes)&&row.requestBytes>=0?row.requestBytes:null,responseBytes:Number.isSafeInteger(row.responseBytes)&&row.responseBytes>=0?row.responseBytes:null,
|
|
101
|
-
error:text(row.error,96),detail:redactPresentationText(row.detail,160),query:redactPresentationText(row.query,180),searchScope:redactPresentationText(row.searchScope,180)
|
|
101
|
+
error:text(row.error,96),detail:redactPresentationText(row.detail,160),query:redactPresentationText(row.query,180),searchScope:redactPresentationText(row.searchScope,180),
|
|
102
|
+
...(typeof row.pollKey==="string"&&/^[a-f0-9]{24}$/.test(row.pollKey)?{pollKey:row.pollKey}:{}),
|
|
103
|
+
...(Number.isSafeInteger(row.additions)&&row.additions>=0&&Number.isSafeInteger(row.deletions)&&row.deletions>=0?{additions:row.additions,deletions:row.deletions}:{})
|
|
102
104
|
}))}:null;
|
|
103
105
|
try{require(!signal?.aborted,"full_cancelled_before_start");if(!localMonitor)await refreshAuthority(false,signal);}
|
|
104
106
|
catch(error){
|
|
@@ -112,6 +114,14 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
|
|
|
112
114
|
const commands=commandAvailability(),terminal=allowTerminal&¤tScopes.includes("terminal");
|
|
113
115
|
const listed=await call("full.session.list",{after:input.after??"",limit:32},signal,true);
|
|
114
116
|
const sessions=listed.items.map(safeSession);
|
|
117
|
+
// Use only already available local display metadata, not another query.
|
|
118
|
+
for(const session of sessions){
|
|
119
|
+
const recent=monitor?.activity?.filter(row=>row.taskSessionId===session.taskSessionId)??[];
|
|
120
|
+
const last=recent.at(-1),project=recent.findLast(row=>row.project)?.project;
|
|
121
|
+
if(!session.project&&project)session.project=project;
|
|
122
|
+
session.lastActivityTime=last?.time??"";
|
|
123
|
+
session.liveStatus=recent.some(row=>row.status==="running")?"working":last?.ok===false?"issue":last?"idle":"unobserved";
|
|
124
|
+
}
|
|
115
125
|
let detail=null,selectedUnavailable=false;
|
|
116
126
|
if(input.selectedId){
|
|
117
127
|
let source;
|
|
@@ -134,7 +144,7 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
|
|
|
134
144
|
while(lastObservedJobs.size>32)lastObservedJobs.delete(lastObservedJobs.keys().next().value);
|
|
135
145
|
detail={...safeSession(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,
|
|
136
146
|
job:jobView(currentJob),jobs,
|
|
137
|
-
activity:(monitor?.activity?.some(row=>row.taskSessionId===input.selectedId)?monitor.activity.filter(row=>row.taskSessionId===input.selectedId):(activities.get(input.selectedId)??[])).slice(-
|
|
147
|
+
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),
|
|
138
148
|
changes:(facts.changedFiles??[]).slice(0,100).map(p=>redactPresentationText(p,512)),
|
|
139
149
|
evidence:(facts.evidence??[]).slice(-16).map(e=>({evidenceId:e.evidenceId,checkId:e.checkId,kind:e.kind,outcome:e.outcome,observedAt:e.observedAt})),
|
|
140
150
|
blockers:(facts.blockers??[]).slice(0,8).map(p=>redactPresentationText(p,512)),
|
|
@@ -143,7 +153,7 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
|
|
|
143
153
|
historyGap:source.gap===true};
|
|
144
154
|
}
|
|
145
155
|
}
|
|
146
|
-
const view={apiVersion:FULL_API_VERSION,ownerEpoch:cursor.producerEpoch,scopeId,cursor,sessions,detail,selectedUnavailable,next:listed.next,partial:!!listed.next,commands,monitor,sessionAccess:"available",terminalEnabled:terminal,activityRetention:"Last
|
|
156
|
+
const view={apiVersion:FULL_API_VERSION,ownerEpoch:cursor.producerEpoch,scopeId,cursor,sessions,detail,selectedUnavailable,next:listed.next,partial:!!listed.next,commands,monitor,sessionAccess:"available",terminalEnabled:terminal,activityRetention:"Last 100 live monitor rows across sessions; older activity may be unavailable"};
|
|
147
157
|
// Bound encoded UTF-8, including long Thai titles and escaped text. Keep
|
|
148
158
|
// durable identity/state, then trim optional detail with a visible gap.
|
|
149
159
|
const bytes=()=>Buffer.byteLength(JSON.stringify(view));
|
|
@@ -152,7 +152,8 @@ export class GitWorktreeManager {
|
|
|
152
152
|
async planShared(repoPath,{mode,sharedPath}={}){
|
|
153
153
|
if(!["main","shared"].includes(mode))throw new Error("full_explicit_workspace_required");
|
|
154
154
|
const {root,entries,first}=await this.#primary(repoPath);
|
|
155
|
-
const
|
|
155
|
+
const requested=mode==="shared"?await this.#resolveAllowedExisting(sharedPath):null;
|
|
156
|
+
const selected=mode==="main"?first:entries.find(x=>requested&&comparablePath(x.path,this.platform)===comparablePath(requested,this.platform));
|
|
156
157
|
if(!selected||selected.bare||selected.detached||!selected.branch)throw new Error("full_shared_worktree_not_registered");
|
|
157
158
|
if(selected.branch.startsWith("relay-full/"))throw new Error("full_workspace_requires_owner");
|
|
158
159
|
const rootRef=await this.#resolveAllowedExisting(selected.path);
|
package/agent/local-agent.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import WebSocket from "ws";
|
|
2
|
+
import {createHash} from "node:crypto";
|
|
2
3
|
import { DesktopManager, createDesktopPlatformAdapter } from "./desktop-manager.mjs";
|
|
3
4
|
import { FileManager } from "./file-manager.mjs";
|
|
4
5
|
import { LocalUsageHistory, usageFileForAgent } from "./local-usage.mjs";
|
|
@@ -11,6 +12,7 @@ import { buildAgentHello } from "./protocol.mjs";
|
|
|
11
12
|
import { createCoreEventBridge, fullUnavailable, hasFullSessionRequest } from "./full-bridge.mjs";
|
|
12
13
|
import { takeFullBootstrap, FULL_STARTUP_EXIT_CODE } from "./full-session-dispatch.mjs";
|
|
13
14
|
import { startSupervisedFull } from "./full-runtime-supervisor.mjs";
|
|
15
|
+
import { createAutomaticSessionBinding } from "./auto-session-binding.mjs";
|
|
14
16
|
import { createParentAuthorizationClient } from "./full-desktop-auth.mjs";
|
|
15
17
|
import {
|
|
16
18
|
AgentLifecycle,
|
|
@@ -48,6 +50,7 @@ const fullEvents = process.env.CHAT_RELAY_FULL_EVENTS === "1" && typeof process.
|
|
|
48
50
|
const monitorEnabled=fullBootstrap?.headless===false;
|
|
49
51
|
const monitorAccountId=monitorEnabled?fullBootstrap.localPrincipal?.accountId:null;
|
|
50
52
|
const monitorActivity=monitorEnabled?createMonitorActivity():null;
|
|
53
|
+
const automaticSessions=fullBootstrap?createAutomaticSessionBinding({agentId,available:()=>!stopping&&!reauthorizationRequired&&fullRuntime?.available===true,dispatch:invocation=>fullRuntime.dispatch(invocation)}):null;
|
|
51
54
|
function monitorSnapshot(){
|
|
52
55
|
const connection=connectionState.snapshot();
|
|
53
56
|
let relayHost="";try{relayHost=new URL(relayUrl).host.slice(0,200);}catch{}
|
|
@@ -579,7 +582,12 @@ function connect() {
|
|
|
579
582
|
if (message?.control === "learn_activity") {
|
|
580
583
|
const activity = message.activity && typeof message.activity === "object" ? message.activity : null;
|
|
581
584
|
const change = message.change && typeof message.change === "object" ? message.change : null;
|
|
585
|
+
if(monitorEnabled&&activity?.accountId&&activity.accountId!==monitorAccountId)return;
|
|
586
|
+
const learnContext=monitorEnabled&&activity?.accountId===monitorAccountId&&activity.activityId?{accountId:activity.accountId,activityId:activity.activityId}:null;
|
|
587
|
+
const learnSessionId=learnContext?automaticSessions?.lookup(learnContext):null;
|
|
582
588
|
emitUi("learn", {
|
|
589
|
+
...(learnContext?{monitorConversationId:learnContext.activityId}:{}),
|
|
590
|
+
...(learnSessionId?{monitorTaskSessionId:learnSessionId}:{}),
|
|
583
591
|
...(activity ? { activity } : {}),
|
|
584
592
|
...(change ? { change } : {}),
|
|
585
593
|
});
|
|
@@ -604,11 +612,27 @@ function connect() {
|
|
|
604
612
|
const uiActivity = describeToolActivity(message.payload, files.getRoots(), recentToolProjects);
|
|
605
613
|
const requestBytes = Buffer.byteLength(JSON.stringify(message), "utf8");
|
|
606
614
|
const ownedFull=action==="full.invoke"&&monitorAccountId&&message.payload?.principal?.accountId===monitorAccountId&&message.payload?.principal?.agentId===agentId;
|
|
615
|
+
const autoContext=automaticSessions&&action!=="full.invoke"&&message.autoSession&&(!monitorEnabled||message.autoSession.accountId===monitorAccountId)?message.autoSession:null;
|
|
616
|
+
const autoSessionId=autoContext?automaticSessions.lookup(autoContext):null;
|
|
617
|
+
const pollTarget=ownedFull&&message.payload.operation==="full.job.read"?message.payload.input?.jobId:action==="terminal.read"||action==="terminal.read.compact"?message.payload.sessionId:null;
|
|
618
|
+
const pollOwner=ownedFull?[message.payload.principal.accountId,message.payload.input?.taskSessionId]:autoContext?[autoContext.accountId,autoContext.activityId]:null;
|
|
619
|
+
const monitorPollKey=monitorEnabled&&pollOwner&&typeof pollTarget==="string"&&pollTarget.length>0&&pollTarget.length<=256?createHash("sha256").update(JSON.stringify([pollOwner,pollTarget])).digest("hex").slice(0,24):null;
|
|
607
620
|
const capture=monitorEnabled&&(action!=="full.invoke"||ownedFull)?captureActivityFor(message.payload):null;
|
|
608
621
|
const captured=result=>{try{return finishActivityCapture(capture,message.payload,result);}catch{return null;}};
|
|
609
622
|
emitUi("tool:start", { requestId: message.requestId, action, summary: callSummary, ...uiActivity, requestBytes,
|
|
623
|
+
...(monitorPollKey?{monitorPollKey}:{}),
|
|
610
624
|
...(monitorEnabled&&(action!=="full.invoke"||ownedFull)?describeLocalSearch(message.payload):{}),
|
|
611
|
-
...(ownedFull?{monitorAction:message.payload.operation,monitorOperation:describeFullMonitorActivity(message.payload.operation,message.payload.input),monitorTaskSessionId:message.payload.input?.taskSessionId}:
|
|
625
|
+
...(ownedFull?{monitorAction:message.payload.operation,monitorOperation:describeFullMonitorActivity(message.payload.operation,message.payload.input),monitorTaskSessionId:message.payload.input?.taskSessionId}:autoSessionId?{monitorTaskSessionId:autoSessionId}:{}) });
|
|
626
|
+
// Automatic attribution never changes the legacy command, its authority,
|
|
627
|
+
// or its workspace. One local ensure is shared by concurrent first calls.
|
|
628
|
+
if(autoContext&&!autoSessionId){
|
|
629
|
+
void automaticSessions.resolve(autoContext).then(id=>{
|
|
630
|
+
if(!id||!monitorActivity)return;
|
|
631
|
+
const callBound=monitorActivity.bindSession(message.requestId,id);
|
|
632
|
+
const learnBound=monitorActivity.bindConversation(autoContext.activityId,id);
|
|
633
|
+
if(callBound||learnBound)fullRuntime?.monitorChanged();
|
|
634
|
+
}).catch(()=>{});
|
|
635
|
+
}
|
|
612
636
|
fullEvents?.publish("tool.accepted", message.requestId, action, message.payload?.observability);
|
|
613
637
|
let scheduleMeta = { lane: "unknown", queueWaitMs: 0, queueDepthAtStart: 0, activeAtStart: 0 };
|
|
614
638
|
let handlerDurationMs = 0;
|
|
@@ -667,7 +691,10 @@ function connect() {
|
|
|
667
691
|
responseBytes,
|
|
668
692
|
...(result && typeof result === "object" && result.ok === false && result.error ? { error: String(result.error) } : partialFailure?{error:"partial_failure"}:{}),
|
|
669
693
|
},activityDetails);
|
|
670
|
-
if(
|
|
694
|
+
if(action==="full.invoke"&&message.payload.operation==="full.session.delete"&&result?.ok===true&&result.result?.acknowledged===true){
|
|
695
|
+
automaticSessions?.forget(message.payload.principal.accountId,message.payload.input.taskSessionId);
|
|
696
|
+
if(ownedFull)monitorActivity?.forgetSession(message.payload.input.taskSessionId);
|
|
697
|
+
}
|
|
671
698
|
fullEvents?.publish("tool.completed", message.requestId, action, message.payload?.observability, {
|
|
672
699
|
ok: !(result && typeof result === "object" && result.ok === false), durationMs: Date.now() - startedAt,
|
|
673
700
|
});
|
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import {humanizeToolCall} from "./toolcall-summary.mjs";
|
|
2
2
|
import {activityIcon} from "./toolcall-context.mjs";
|
|
3
|
-
import {historicalDiff,projectActivityDetails} from "./activity-capture.mjs";
|
|
3
|
+
import {historicalDiff,projectActivityDetails,displayActivityPath,activityChangeTotals} from "./activity-capture.mjs";
|
|
4
|
+
import {monitorActivityId,normalizeLearnMonitorMetadata} from "../packages/full-contracts/monitor-metadata.mjs";
|
|
4
5
|
|
|
5
6
|
// The local monitor reuses Core's TUI activity projection. One bounded row per
|
|
6
7
|
// request (not one per start/end); never retain raw request bodies or output.
|
|
7
|
-
const
|
|
8
|
+
export const MAX_MONITOR_ROWS=100;
|
|
9
|
+
const DETAIL_TTL_MS=15*60*1000;
|
|
8
10
|
const clean=(value,n)=>typeof value==="string"?value.replace(/[\u0000-\u001f\u007f]/g," ").replace(/\s+/g," ").trim().slice(0,n).toWellFormed():"";
|
|
9
11
|
const code=value=>typeof value==="string"&&/^[A-Za-z0-9_.:-]{1,100}$/.test(value)?value:"tool";
|
|
10
|
-
const detailed=new Set(["fs.read","fs.write","fs.edit","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"]);
|
|
12
|
+
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"]);
|
|
11
13
|
const learnLabels={learn_prepare:"Load relevant Learn context",learn_get:"Read Learn memories",learn_put:"Update Learn memory",learn_delete:"Delete Learn memory",learn_feedback:"Rate Learn memory",learn_usage_report:"Report Learn usage"};
|
|
12
14
|
|
|
13
15
|
// Safe bounded metadata; never expose raw commands, search terms, edit bodies or output.
|
|
@@ -64,7 +66,7 @@ export function createMonitorActivity({now=()=>new Date()}={}){
|
|
|
64
66
|
const rows=new Map(),running=new Set(),details=new Map();
|
|
65
67
|
const localTime=new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"});
|
|
66
68
|
let calls=0,errors=0,learnEvents=0,sequence=0;
|
|
67
|
-
const remember=(key,row)=>{rows.set(key,row);while(rows.size>
|
|
69
|
+
const remember=(key,row)=>{rows.set(key,row);while(rows.size>MAX_MONITOR_ROWS){const first=rows.keys().next().value;details.delete(rows.get(first).requestId);rows.delete(first);}};
|
|
68
70
|
const stamp=()=>{const at=now();return {at:at.toISOString(),time:localTime.format(at)};};
|
|
69
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);};
|
|
70
72
|
return {
|
|
@@ -77,23 +79,45 @@ export function createMonitorActivity({now=()=>new Date()}={}){
|
|
|
77
79
|
// The TUI's descriptive operations are reused only for known routes
|
|
78
80
|
// that do not embed arbitrary request data. Search/filter and unknown
|
|
79
81
|
// arguments are deliberately not forwarded.
|
|
80
|
-
const label=action.startsWith("full.")?clean(payload.monitorOperation,128)||describeFullMonitorActivity(action):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});
|
|
81
|
-
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:typeof payload.monitorTaskSessionId==="string"?code(payload.monitorTaskSessionId):null,status:"running",ok:null,durationMs:null,requestBytes:bytes(payload.requestBytes),responseBytes:null,error:"",query:clean(payload.query,180),searchScope:clean(payload.searchScope,180),detail:detailed.has(action)?clean(payload.detail,160):""});
|
|
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:typeof payload.monitorTaskSessionId==="string"?code(payload.monitorTaskSessionId):null,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)?clean(payload.detail,160):""});
|
|
82
84
|
}else if(event==="tool:end"){
|
|
83
85
|
const key=payload.requestId;if(!running.delete(key))return;
|
|
84
|
-
|
|
86
|
+
const exitFailed=Number.isInteger(payload.activityDetails?.exitCode)&&payload.activityDetails.exitCode!==0;
|
|
87
|
+
const failed=payload.ok===false||exitFailed;
|
|
88
|
+
if(failed)errors++;
|
|
85
89
|
const row=rows.get(key);if(row){
|
|
86
|
-
if(payload.activityDetails)
|
|
87
|
-
|
|
90
|
+
if(payload.activityDetails){
|
|
91
|
+
details.set(row.requestId,payload.activityDetails);
|
|
92
|
+
const totals=activityChangeTotals(payload.activityDetails);
|
|
93
|
+
if(totals)Object.assign(row,totals);
|
|
94
|
+
}
|
|
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":"")});
|
|
88
96
|
}
|
|
89
97
|
}else if(event==="learn"){
|
|
90
98
|
learnEvents++;
|
|
91
99
|
const activity=payload.activity??{},tool=code(activity.tool);
|
|
92
|
-
const change=activity.change??{},rowId="learn-"+(++sequence)
|
|
100
|
+
const change=activity.change??{},rowId="learn-"+(++sequence),metadata=activity.ok===false?null:normalizeLearnMonitorMetadata(activity.metadata);
|
|
101
|
+
const retrieved=metadata?.retrieved;
|
|
102
|
+
const operation=retrieved!==undefined?(tool==="learn_get"?"Read ":"Load ")+retrieved+(retrieved===1?" Learn memory":" Learn memories"):learnLabels[tool]||"Learn activity";
|
|
103
|
+
const detail=metadata?.evaluated!==undefined?metadata.evaluated+" evaluated · "+metadata.applied+" applied · "+metadata.verified+" verified":[clean(change.key,100),clean(change.scope??activity.scopeSummary,50)].filter(Boolean).join(" · ");
|
|
104
|
+
remember(rowId,{requestId:rowId,...stamp(),conversationId:monitorActivityId(payload.monitorConversationId),taskSessionId:typeof payload.monitorTaskSessionId==="string"?code(payload.monitorTaskSessionId):null,action:"learn",category:"Learn",icon:"🧠",operation,project:clean(change.scope==="project"?change.scopeKey:activity.projectKey,64),detail,status:activity.ok===false?"failed":"done",ok:activity.ok!==false,durationMs:bytes(activity.durationMs)});
|
|
105
|
+
if(retrieved!==undefined&&retrieved>0)details.set(rowId,{files:[],omitted:0,learn:metadata});
|
|
93
106
|
}else return false;
|
|
94
107
|
return true;
|
|
95
108
|
},
|
|
96
|
-
snapshot(){prune();const current=now().getTime();return {calls,errors,active:running.size,learnEvents,activity:[...rows.values()].slice(-
|
|
109
|
+
snapshot(){prune();const current=now().getTime();return {calls,errors,active:running.size,learnEvents,activity:[...rows.values()].slice(-MAX_MONITOR_ROWS).map(({conversationId,...row})=>({...row,elapsedMs:row.status==="running"?Math.max(0,current-Date.parse(row.at)):null,hasDetails:details.has(row.requestId)}))};},
|
|
110
|
+
bindSession(requestId,taskSessionId){
|
|
111
|
+
const row=rows.get(requestId);
|
|
112
|
+
if(!row||row.taskSessionId||typeof taskSessionId!=="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(taskSessionId))return false;
|
|
113
|
+
row.taskSessionId=taskSessionId;return true;
|
|
114
|
+
},
|
|
115
|
+
bindConversation(conversationId,taskSessionId){
|
|
116
|
+
if(!monitorActivityId(conversationId)||typeof taskSessionId!=="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(taskSessionId))return false;
|
|
117
|
+
let changed=false;
|
|
118
|
+
for(const row of rows.values())if(row.conversationId===conversationId&&!row.taskSessionId){row.taskSessionId=taskSessionId;changed=true;}
|
|
119
|
+
return changed;
|
|
120
|
+
},
|
|
97
121
|
forgetSession(taskSessionId){
|
|
98
122
|
for(const [key,row] of rows){if(row.taskSessionId===taskSessionId){details.delete(row.requestId);rows.delete(key);}}
|
|
99
123
|
},
|
|
@@ -105,7 +129,7 @@ export function createMonitorActivity({now=()=>new Date()}={}){
|
|
|
105
129
|
const file=detail?.files.find(f=>f.fileId===fileId);
|
|
106
130
|
return {activityId,fileId,...historicalDiff(file?.pair)};
|
|
107
131
|
}
|
|
108
|
-
return {activityId,...projectActivityDetails(detail)};
|
|
132
|
+
return {activityId,...projectActivityDetails(detail),...(detail?.learn?{learn:detail.learn}:{})};
|
|
109
133
|
}
|
|
110
134
|
};
|
|
111
135
|
}
|
|
@@ -151,6 +151,7 @@ function terminalTitle(payload) {
|
|
|
151
151
|
if (/\bGet-Command\s+(?:rg|ripgrep)\b/i.test(command)) return "Check ripgrep availability";
|
|
152
152
|
const toolCheck = command.match(/\bGet-Command\s+([a-z][a-z0-9.-]{0,25})\b/i);
|
|
153
153
|
if (toolCheck?.[1]) return "Check " + toolCheck[1] + " availability";
|
|
154
|
+
if (/\|\s*(?:Select-String|rg)\b/i.test(command)) return "Search command output";
|
|
154
155
|
if (/\b(?:Select-String|rg)\b/i.test(command) && !/Get-Command/i.test(command)) return "Search project files";
|
|
155
156
|
const npmScript = command.match(/\bnpm\s+run\s+([a-z][a-z0-9:_-]+)/i);
|
|
156
157
|
if (npmScript?.[1]) {
|
|
@@ -199,6 +200,9 @@ export function describeToolActivity(payload = {}, allowedRoots = [], linkedCont
|
|
|
199
200
|
case "fs.write":
|
|
200
201
|
operation = (payload.mode === "append" ? "Append " : "Write ") + shortName(payload.path);
|
|
201
202
|
break;
|
|
203
|
+
case "fs.delete":
|
|
204
|
+
operation = "Delete " + shortName(payload.path);
|
|
205
|
+
break;
|
|
202
206
|
case "fs.edit":
|
|
203
207
|
operation = "Edit " + shortName(payload.path);
|
|
204
208
|
break;
|
|
@@ -193,7 +193,7 @@ export function humanizeToolCall(payload = {}) {
|
|
|
193
193
|
case "fs.batch":
|
|
194
194
|
return `Inspect filesystem · ${Array.isArray(payload.operations) ? payload.operations.length : 0} operations`;
|
|
195
195
|
case "fs.artifact":
|
|
196
|
-
return `Export ${compactPath(payload.path)}
|
|
196
|
+
return payload.path ? `Export ${compactPath(payload.path)}` : "Export file";
|
|
197
197
|
case "fs.write": {
|
|
198
198
|
const bytes = Buffer.byteLength(String(payload.content ?? ""), "utf8");
|
|
199
199
|
const mode = payload.mode === "append" ? "append" : "replace file";
|
package/cli/full-launch.mjs
CHANGED
|
@@ -4,10 +4,8 @@ import {createHash,randomUUID} from "node:crypto";
|
|
|
4
4
|
import {configDir} from "./config.mjs";
|
|
5
5
|
import {getAgentVersion} from "../agent/protocol.mjs";
|
|
6
6
|
import {prepareFullArtifact} from "./full-prepare.mjs";
|
|
7
|
-
import {regularFile
|
|
8
|
-
import {
|
|
9
|
-
import {officialFullSettings} from "./full-release-official.mjs";
|
|
10
|
-
import {ModError,MAX_MANIFEST_BYTES} from "./mod-manifest.mjs";
|
|
7
|
+
import {regularFile} from "./full-release-files.mjs";
|
|
8
|
+
import {ModError} from "./mod-manifest.mjs";
|
|
11
9
|
|
|
12
10
|
const require=(ok,code)=>{if(!ok)throw new ModError(code);};
|
|
13
11
|
export function supportedFullNode(version=process.versions.node){
|
|
@@ -17,24 +15,8 @@ export function supportedFullNode(version=process.versions.node){
|
|
|
17
15
|
const atLeast=(m,p)=>minor>m||minor===m&&patch>=p;
|
|
18
16
|
return major===22&&atLeast(23,4)||major===24&&atLeast(22,1)||major===26&&atLeast(12,1)||major>26;
|
|
19
17
|
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
// No release URL, key or version from relay payloads.
|
|
23
|
-
let raw;
|
|
24
|
-
try{raw=JSON.parse((await readBounded(path.join(home,"full-release.json"),MAX_MANIFEST_BYTES)).toString("utf8"));}
|
|
25
|
-
catch(error){if(error.code==="ENOENT")return officialFullSettings({headless});throw new ModError("full_invalid_release_configuration");}
|
|
26
|
-
require(raw&&typeof raw==="object"&&!Array.isArray(raw)&&Object.keys(raw).every(k=>["headlessVersion","guiVersion","trustedKeys","sourceDirectory","guiSourceDirectory","sourceUrl","guiSourceUrl"].includes(k)),"full_invalid_release_configuration");
|
|
27
|
-
const requestedVersion=headless?raw.headlessVersion:raw.guiVersion;
|
|
28
|
-
require(typeof requestedVersion==="string"&&/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[A-Za-z0-9.-]+)?$/.test(requestedVersion)&&requestedVersion.length<=64,"full_invalid_release_configuration");
|
|
29
|
-
const entries=Object.entries(raw.trustedKeys??{});
|
|
30
|
-
require(raw.trustedKeys&&typeof raw.trustedKeys==="object"&&!Array.isArray(raw.trustedKeys)&&entries.length>=1&&entries.length<=8&&entries.every(([key,value])=>/^[A-Za-z0-9_-]{1,64}$/.test(key)&&typeof value==="string"&&value.length<=1024&&value.includes("BEGIN PUBLIC KEY")),"full_invalid_release_configuration");
|
|
31
|
-
for(const value of [raw.sourceDirectory,raw.guiSourceDirectory])require(value===undefined||typeof value==="string"&&path.isAbsolute(value),"full_invalid_release_configuration");
|
|
32
|
-
for(const url of [raw.sourceUrl,raw.guiSourceUrl])if(url!==undefined)releaseSourceUrl(url);
|
|
33
|
-
const sourceDirectory=headless?raw.sourceDirectory:raw.guiSourceDirectory??(raw.guiSourceUrl?undefined:raw.sourceDirectory);
|
|
34
|
-
const sourceUrl=headless?raw.sourceUrl:raw.guiSourceUrl??(raw.guiSourceDirectory?undefined:raw.sourceUrl);
|
|
35
|
-
require(!(sourceDirectory&&sourceUrl),"full_invalid_release_configuration");
|
|
36
|
-
return {headless,requestedVersion,trustedKeys:new Map(entries),sourceDirectory,sourceUrl};
|
|
37
|
-
}
|
|
18
|
+
// The public launcher uses only the release-specific pin bundled with Core.
|
|
19
|
+
export {officialFullSettings as readFullReleaseSettings} from "./full-release-official.mjs";
|
|
38
20
|
export function fullStateDirectory(home,{relayUrl,agentId}){
|
|
39
21
|
require(typeof relayUrl==="string"&&typeof agentId==="string"&&/^[a-z0-9_-]{1,64}$/.test(agentId),"full_invalid_host_configuration");
|
|
40
22
|
const normalized=new URL(relayUrl);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "2.0
|
|
3
|
-
"publicKey": "-----BEGIN PUBLIC KEY-----\
|
|
2
|
+
"version": "2.1.0",
|
|
3
|
+
"publicKey": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAere5wAOYD039oGrPlLZL6nurG+upNkR99Kr2o+2AUfU=\n-----END PUBLIC KEY-----\n"
|
|
4
4
|
}
|
package/cli/index.mjs
CHANGED
|
@@ -244,7 +244,7 @@ async function logout() {
|
|
|
244
244
|
return 0;
|
|
245
245
|
}
|
|
246
246
|
|
|
247
|
-
export async function runCli(argv = process.argv.slice(2)) {
|
|
247
|
+
export async function runCli(argv = process.argv.slice(2), dependencies) {
|
|
248
248
|
const command = (argv[0] || "remote").toLowerCase();
|
|
249
249
|
const { options } = parseOptions(argv.slice(1));
|
|
250
250
|
|
|
@@ -273,7 +273,7 @@ export async function runCli(argv = process.argv.slice(2)) {
|
|
|
273
273
|
if (command === "restart") return lifecycleAction("restart");
|
|
274
274
|
if (command === "upgrade") return lifecycleAction("upgrade");
|
|
275
275
|
if (command === "remote") {
|
|
276
|
-
const remoteCode = (await remote({...options,launchArgs:argv})) || 0;
|
|
276
|
+
const remoteCode = (await remote({...options,launchArgs:argv},dependencies)) || 0;
|
|
277
277
|
if (remoteCode === AGENT_UPGRADE_EXIT_CODE) {
|
|
278
278
|
const relaunched = launchLatestRemote(options);
|
|
279
279
|
if (!relaunched.ok) {
|
package/cli/remote.mjs
CHANGED
|
@@ -138,13 +138,13 @@ function openDesktopOnChild(child, accountId) {
|
|
|
138
138
|
});
|
|
139
139
|
}
|
|
140
140
|
|
|
141
|
-
export async function remote(options = {}) {
|
|
141
|
+
export async function remote(options = {}, {loadReleaseSettings} = {}) {
|
|
142
142
|
const background=createBackgroundHandoff();
|
|
143
143
|
let fullSettings=null, prepareFullLaunch=null, localFullPrincipal=null;
|
|
144
144
|
if (options.full === true) {
|
|
145
145
|
try {
|
|
146
146
|
const full=await import("./full-launch.mjs");
|
|
147
|
-
fullSettings=await full.readFullReleaseSettings({headless:options.headless===true});
|
|
147
|
+
fullSettings=await (loadReleaseSettings??full.readFullReleaseSettings)({headless:options.headless===true});
|
|
148
148
|
if(!full.supportedFullNode())throw Object.assign(new Error("Unsupported Node.js"),{code:"full_node_unsupported"});
|
|
149
149
|
prepareFullLaunch=full.prepareFullLaunch;
|
|
150
150
|
localFullPrincipal=full.localFullPrincipal;
|
package/package.json
CHANGED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Conversation metadata is an attribution hint, never authorization.
|
|
2
|
+
// Only the already authorized Worker may construct the internal envelope.
|
|
3
|
+
const account=value=>typeof value==="string"&&/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value);
|
|
4
|
+
const activity=value=>typeof value==="string"&&/^act_[a-f0-9]{20}$/.test(value);
|
|
5
|
+
export function automaticSessionContext({accountId,activityId,reliableIdentity,scopes,action}={}){
|
|
6
|
+
if(reliableIdentity!==true||!account(accountId)||!activity(activityId)||
|
|
7
|
+
!Array.isArray(scopes)||!["read","write"].every(s=>scopes.includes("*")||scopes.includes(s))||
|
|
8
|
+
typeof action!=="string"||! /^(?:fs|terminal|git|desktop|process)\./.test(action))return undefined;
|
|
9
|
+
return {accountId,activityId};
|
|
10
|
+
}
|
|
11
|
+
export function validAutomaticSessionContext(value){
|
|
12
|
+
return !!value&&typeof value==="object"&&!Array.isArray(value)&&
|
|
13
|
+
Object.keys(value).length===2&&account(value.accountId)&&activity(value.activityId);
|
|
14
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// A small, content-free projection shared by Worker, relay and local monitor.
|
|
2
|
+
const scopes=new Set(["global","project","agent"]);
|
|
3
|
+
const kinds=new Set(["preference","response_style","work_style","coding_style","problem_solving","project_context","tool_pattern","workflow","correction","agent_context"]);
|
|
4
|
+
const count=value=>Number.isSafeInteger(value)&&value>=0&&value<=100?value:undefined;
|
|
5
|
+
const key=value=>typeof value==="string"&&/^[a-z0-9][a-z0-9_.:-]{0,79}$/.test(value)&&! /^(?:sk-|gh[pousr]_)/i.test(value)?value:null;
|
|
6
|
+
export const monitorAccountId=value=>typeof value==="string"&&/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value)?value:null;
|
|
7
|
+
export const monitorActivityId=value=>typeof value==="string"&&/^act_[a-f0-9]{20}$/.test(value)?value:null;
|
|
8
|
+
export function normalizeLearnMonitorMetadata(value){
|
|
9
|
+
if(!value||typeof value!=="object"||Array.isArray(value))return null;
|
|
10
|
+
const retrieved=count(value.retrieved);
|
|
11
|
+
if(retrieved!==undefined){
|
|
12
|
+
const items=[];
|
|
13
|
+
for(const item of (Array.isArray(value.items)?value.items:[]).slice(0,8)){
|
|
14
|
+
const name=key(item?.key);
|
|
15
|
+
if(name&&scopes.has(item.scope)&&kinds.has(item.kind))items.push({key:name,scope:item.scope,kind:item.kind});
|
|
16
|
+
}
|
|
17
|
+
return {retrieved,items:items.slice(0,retrieved)};
|
|
18
|
+
}
|
|
19
|
+
const evaluated=count(value.evaluated),applied=count(value.applied),verified=count(value.verified);
|
|
20
|
+
if(evaluated===undefined||applied===undefined||verified===undefined||applied>evaluated||verified>applied)return null;
|
|
21
|
+
return {evaluated,applied,verified};
|
|
22
|
+
}
|
|
23
|
+
export function learnMonitorMetadata(tool,body){
|
|
24
|
+
if(!body||typeof body!=="object")return null;
|
|
25
|
+
if(tool==="learn_usage_report")return normalizeLearnMonitorMetadata(body);
|
|
26
|
+
const items=tool==="learn_prepare"?body.preparedContext?.items:tool==="learn_get"?body.items:null;
|
|
27
|
+
return Array.isArray(items)?normalizeLearnMonitorMetadata({retrieved:Math.min(items.length,100),items}):null;
|
|
28
|
+
}
|
|
@@ -96,7 +96,7 @@ export function parseRemoteFullRequest(value){
|
|
|
96
96
|
const boundedPath=value=>typeof value==="string"&&value.length>0&&value.length<=512&&!/[\u0000-\u001f]/.test(value);
|
|
97
97
|
if(input.kind==="git"){
|
|
98
98
|
require(!has("artifactRoot"),"full_invalid_workspace_mode");
|
|
99
|
-
input.mode
|
|
99
|
+
if(input.mode===undefined){input.mode="shared";input.sharedPath=input.sharedPath??input.repoPath;}
|
|
100
100
|
require(["isolated","main","shared"].includes(input.mode),"full_invalid_workspace_mode");
|
|
101
101
|
require(!has("baseRef")||(input.mode==="isolated"&&typeof input.baseRef==="string"&&input.baseRef.length>0&&input.baseRef.length<=256&&!/[\u0000\r\n]/.test(input.baseRef)),"full_invalid_workspace_base");
|
|
102
102
|
require(boundedPath(input.repoPath),"full_invalid_resource_path");
|