@anusornneal/chat-relay 1.9.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +8 -0
  2. package/agent/activity-capture.mjs +218 -0
  3. package/agent/auto-session-binding.mjs +46 -0
  4. package/agent/capability-scheduler.mjs +82 -5
  5. package/agent/file-manager.mjs +33 -8
  6. package/agent/full-bridge.mjs +53 -0
  7. package/agent/full-desktop-actions.mjs +124 -0
  8. package/agent/full-desktop-auth.mjs +53 -0
  9. package/agent/full-desktop-broker.mjs +318 -0
  10. package/agent/full-host.mjs +153 -0
  11. package/agent/full-job-broker.mjs +360 -0
  12. package/agent/full-native-job.mjs +205 -0
  13. package/agent/full-presentation-changes.mjs +191 -0
  14. package/agent/full-remote-diagnostics.mjs +129 -0
  15. package/agent/full-resources.mjs +343 -0
  16. package/agent/full-runtime-supervisor.mjs +67 -0
  17. package/agent/full-session-dispatch.mjs +167 -0
  18. package/agent/full-workspace-broker.mjs +290 -0
  19. package/agent/git-worktree-manager.mjs +171 -4
  20. package/agent/lifecycle.mjs +11 -0
  21. package/agent/local-agent.mjs +177 -24
  22. package/agent/local-usage.mjs +21 -0
  23. package/agent/monitor-activity.mjs +135 -0
  24. package/agent/presentation-redaction.mjs +10 -0
  25. package/agent/process-manager.mjs +32 -0
  26. package/agent/terminal-manager.mjs +189 -31
  27. package/agent/toolcall-context.mjs +27 -1
  28. package/agent/toolcall-summary.mjs +1 -1
  29. package/agent/windows-desktop-runner.mjs +65 -61
  30. package/agent/windows-desktop-worker.ps1 +33 -18
  31. package/agent/windows-powershell.mjs +51 -0
  32. package/cli/full-background.mjs +69 -0
  33. package/cli/full-launch.mjs +76 -0
  34. package/cli/full-prepare-child.mjs +48 -0
  35. package/cli/full-prepare.mjs +171 -0
  36. package/cli/full-release-default.json +4 -0
  37. package/cli/full-release-files.mjs +36 -0
  38. package/cli/full-release-official.mjs +48 -0
  39. package/cli/full-release-source.mjs +37 -0
  40. package/cli/index.mjs +9 -5
  41. package/cli/mod-cache.mjs +170 -0
  42. package/cli/mod-loader.mjs +67 -0
  43. package/cli/mod-manifest.mjs +63 -0
  44. package/cli/remote.mjs +173 -18
  45. package/cli/runner-ownership.mjs +116 -3
  46. package/cli/self-update.mjs +1 -1
  47. package/cli/tui.mjs +2 -20
  48. package/package.json +5 -3
  49. package/packages/full-contracts/auto-session.mjs +14 -0
  50. package/packages/full-contracts/index.mjs +193 -0
  51. package/packages/full-contracts/monitor-metadata.mjs +28 -0
  52. package/packages/full-contracts/native-job.mjs +13 -0
  53. package/packages/full-contracts/package.json +7 -0
  54. package/packages/full-contracts/remote-session.mjs +239 -0
package/README.md CHANGED
@@ -332,3 +332,11 @@ Project aliases are account-scoped mappings stored in the Learning Durable Objec
332
332
 
333
333
  No new Cloudflare storage, dependencies or additional routine relay round trips
334
334
  are needed for these improvements.
335
+
336
+ ## Chat Relay Full (2.0)
337
+
338
+ Windows x64 with supported Node.js: `npx @anusornneal/chat-relay@latest remote --full` opens the native Slint monitor; add `--headless` for Full without the window. Ordinary `remote` remains Lite and downloads no Full artifact. The published Core carries a release-specific Ed25519 public key; the exact-version signed GUI/headless archive is downloaded lazily from the matching GitHub Release, verified and cached locally. This release does not claim OS code signing or Full public support on other targets.
339
+
340
+ 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.
@@ -0,0 +1,218 @@
1
+ import {AsyncLocalStorage} from "node:async_hooks";
2
+ import fs from "node:fs/promises";
3
+ import {constants} from "node:fs";
4
+ import path from "node:path";
5
+ import {redactPresentationText} from "./presentation-redaction.mjs";
6
+ import {presentationChangePath} from "./full-presentation-changes.mjs";
7
+
8
+ const storage=new AsyncLocalStorage();
9
+ const MAX_FILES=20,MAX_PAIR_BYTES=32*1024,MAX_CALL_BYTES=64*1024,MAX_LINES=400,MAX_DIFF_CHARS=12000;
10
+ const safeError=value=>typeof value==="string"&&/^[A-Za-z][A-Za-z0-9_:-]{1,95}$/.test(value)?value:"";
11
+ const safeInteger=value=>Number.isSafeInteger(value)&&value>=0?value:null;
12
+ const decode=value=>{
13
+ if(value===null)return "";
14
+ if(typeof value==="string")return value;
15
+ if(!Buffer.isBuffer(value))return null;
16
+ try{return new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(value);}catch{return null;}
17
+ };
18
+ export function displayActivityPath(value){
19
+ if(typeof value!=="string"||!value||value.length>4096)return "";
20
+ const normalized=value.replace(/\\/g,"/");
21
+ const absolute=path.isAbsolute(value)||/^[A-Za-z]:\//.test(normalized)||normalized.startsWith("/");
22
+ const parts=normalized.split("/").filter(Boolean);
23
+ // Never reveal credential file names or private path components. Worktree
24
+ // roots themselves may contain .workspace, but display only the leaf of an
25
+ // absolute path (relative request paths retain their project context).
26
+ for(const p of parts){
27
+ if(p===".workspace"&&absolute)continue;
28
+ if(/^[A-Za-z]:$/.test(p)&&absolute)continue;
29
+ if(!presentationChangePath(p))return "";
30
+ }
31
+ const result=absolute?parts.at(-1):normalized;
32
+ return result&&result.length<=512&&presentationChangePath(result)&&redactPresentationText(result,512)===result?result:"";
33
+ }
34
+ const detailActions=new Set(["fs.editMany","full.workspace.edit","fs.edit","fs.write","fs.delete","fs.read","full.workspace.read","fs.readMany","fs.readMany.relative","fs.batch","fs.batch.compact","fs.search.start","fs.search.results","full.intelligence.search","full.intelligence.symbols","terminal.exec","terminal.exec.compact","terminal.read","terminal.read.compact","full.job.read"]);
35
+ // Capture only explicitly supplied search terms or quoted literal rg/Select-String
36
+ // patterns. Never retain shell scripts, environment values or command output.
37
+ export function describeLocalSearch(payload){
38
+ const action=payload?.action==="full.invoke"?payload.operation:payload?.action;
39
+ const input=payload?.action==="full.invoke"?payload.input??{}:payload??{};
40
+ let query="",scope="";
41
+ if(action==="fs.search.start"){query=input.pattern;scope=displayActivityPath(input.path);}
42
+ else if(["full.intelligence.search","full.intelligence.symbols"].includes(action)){query=input.query;}
43
+ else if(["terminal.exec","terminal.exec.compact","terminal.start"].includes(action)&&typeof input.command==="string"&&input.command.length<=16000){
44
+ const patterns=[];
45
+ // Support common quoted literal search arguments, not shell expansion.
46
+ for(const m of input.command.matchAll(/(?:^|[;|\n]\s*)\s*(?:rg|Select-String)\s+(?:(?:-(?:C|A|B)\s+\d+|--?[A-Za-z0-9-]+)\s+)*(?:'([^'\r\n]{1,180})'|"([^"$\x60\r\n]{1,180})")/gi)){
47
+ patterns.push(m[1]??m[2]);if(patterns.length===3)break;
48
+ }
49
+ query=patterns.join(" · ");
50
+ }
51
+ const safe=value=>typeof value==="string"&&value.length<=512?redactPresentationText(value.replace(/[\r\n\t]/g," "),180):"";
52
+ return {query:safe(query),searchScope:safe(scope)};
53
+ }
54
+ export function captureActivityFor(payload){
55
+ const action=payload?.action==="full.invoke"?payload.operation:payload?.action;
56
+ return detailActions.has(action)?createActivityCapture():null;
57
+ }
58
+ export function createActivityCapture(){
59
+ return {files:new Map(),bytes:0,closed:false};
60
+ }
61
+ export function runActivityCapture(capture,work){
62
+ return capture?storage.run(capture,work):work();
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
+ }
92
+ export function recordActivityEdit(index,requestedPath,before,after,kind,canonicalTarget){
93
+ const context=storage.getStore();
94
+ if(!context||context.closed||context.files.size>=MAX_FILES)return;
95
+ // Observation must never turn a successful write into a failed write.
96
+ try{
97
+ const name=displayActivityPath(requestedPath);
98
+ if(!name||!displayActivityPath(canonicalTarget))return;
99
+ const entry={path:name,kind,pair:null};
100
+ context.files.set(index,entry);
101
+ if(before===undefined||after===undefined)return;
102
+ const size=(before===null?0:Buffer.byteLength(before))+(after===null?0:Buffer.byteLength(after));
103
+ if(size>MAX_PAIR_BYTES||context.bytes+size>MAX_CALL_BYTES)return;
104
+ 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"))return;
106
+ if(redactPresentationText(a,a.length)!==a||redactPresentationText(b,b.length)!==b)return;
107
+ if(a.split("\n").length>MAX_LINES||b.split("\n").length>MAX_LINES)return;
108
+ entry.pair={before:a,after:b};
109
+ context.bytes+=size;
110
+ }catch{/* Optional monitor only. */}
111
+ }
112
+ // Exact bounded line edit script from the recorded pair. Retain newline
113
+ // characters in the comparison so final-newline and CRLF changes are real.
114
+ function splitLines(value){return value.match(/[^\n]*\n|[^\n]+$/g)??[];}
115
+ export function historicalDiff(pair,{includeText=true,maxCells=Infinity}={}){
116
+ if(!pair)return {state:"unavailable",reason:"No captured text for this call",additions:null,deletions:null,text:""};
117
+ const a=splitLines(pair.before),b=splitLines(pair.after);
118
+ if(a.length>MAX_LINES||b.length>MAX_LINES)return {state:"unavailable",reason:"Change exceeds capture limit",additions:null,deletions:null,text:""};
119
+ // Strip unchanged prefix/suffix before allocating the bounded LCS table.
120
+ // Typical targeted edits need only a few cells instead of 400 x 400.
121
+ let start=0,ae=a.length,be=b.length;
122
+ while(start<ae&&start<be&&a[start]===b[start])start++;
123
+ while(ae>start&&be>start&&a[ae-1]===b[be-1]){ae--;be--;}
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);
127
+ const cell=(i,j)=>(i-start)*width+j-start;
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)]);
129
+ const lines=includeText?a.slice(0,start).map(line=>[" ",line]):[];
130
+ let i=start,j=start,additions=0,deletions=0;
131
+ while(i<ae||j<be){
132
+ if(i<ae&&j<be&&a[i]===b[j]){if(includeText)lines.push([" ",a[i]]);i++;j++;}
133
+ else if(i<ae&&(j===be||dp[cell(i+1,j)]>=dp[cell(i,j+1)])){if(includeText)lines.push(["-",a[i]]);i++;deletions++;}
134
+ else{if(includeText)lines.push(["+",b[j]]);j++;additions++;}
135
+ }
136
+ if(includeText)for(const line of a.slice(ae))lines.push([" ",line]);
137
+ if(!includeText)return {state:"ready",additions,deletions};
138
+ if(!additions&&!deletions)return {state:"ready",additions,deletions,text:"No textual changes",truncated:false};
139
+ // One bounded hunk with genuine context; never substitute current Git diff.
140
+ const first=lines.findIndex(l=>l[0]!==" "),last=lines.findLastIndex(l=>l[0]!==" ");
141
+ const from=Math.max(0,first-3),to=Math.min(lines.length,last+4);
142
+ let oldStart=1,newStart=1;
143
+ for(const [op] of lines.slice(0,from)){if(op!=="+")oldStart++;if(op!=="-")newStart++;}
144
+ const hunk=lines.slice(from,to),oldCount=hunk.filter(l=>l[0]!=="+").length,newCount=hunk.filter(l=>l[0]!=="-").length;
145
+ const format=([op,line])=>op+line.replace(/\r?\n$/,"")+(line.endsWith("\n")?"":"\n\");
146
+ const raw="@@ -"+(oldCount?oldStart:oldStart-1)+","+oldCount+" +"+(newCount?newStart:newStart-1)+","+newCount+" @@\n"+hunk.map(format).join("\n");
147
+ const text=raw.slice(0,MAX_DIFF_CHARS).toWellFormed();
148
+ return {state:"ready",additions,deletions,text,truncated:text.length<raw.length};
149
+ }
150
+ export function finishActivityCapture(capture,payload,result){
151
+ if(!capture)return null;
152
+ capture.closed=true;
153
+ const action=payload?.action==="full.invoke"?payload.operation:payload?.action;
154
+ const input=payload?.action==="full.invoke"?payload.input??{}:payload??{};
155
+ const output=payload?.action==="full.invoke"?result?.result:result;
156
+ const files=[];let omitted=0;
157
+ const add=(source,index,outcome,kind,error)=>{
158
+ if(files.length>=MAX_FILES){omitted++;return;}
159
+ const captured=capture.files.get(index),name=captured?.path||displayActivityPath(source);
160
+ 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});
162
+ };
163
+ const edit=action==="fs.editMany"||action==="full.workspace.edit";
164
+ if(edit){
165
+ const operations=Array.isArray(input.operations)?input.operations:[];
166
+ omitted=Math.max(0,operations.length-MAX_FILES);
167
+ for(const [index,op] of operations.slice(0,MAX_FILES).entries()){
168
+ const row=Array.isArray(output?.results)?output.results.find(r=>r.index===index):null;
169
+ add(op?.relativePath??op?.path,index,row?.ok===true?"completed":row?.ok===false||result?.ok===false?"failed":"unknown",op?.op==="create"?"added":"modified",row?.error);
170
+ }
171
+ }else if(action==="fs.edit"||action==="fs.write"||action==="fs.delete"){
172
+ add(input.path,0,result?.ok===false?"failed":"completed",action==="fs.delete"?"deleted":action==="fs.write"?"written":"modified",result?.error);
173
+ }else if(action==="fs.read"||action==="full.workspace.read"||action==="fs.readMany"||action==="fs.readMany.relative"||action==="fs.batch"||action==="fs.batch.compact"){
174
+ const sources=Array.isArray(input.paths)?input.paths:Array.isArray(input.relativePaths)?input.relativePaths:Array.isArray(input.operations)?input.operations:[input.relativePath??input.path];
175
+ omitted=Math.max(0,sources.length-MAX_FILES);
176
+ for(const [index,source] of sources.slice(0,MAX_FILES).entries()){
177
+ if(source?.op&&source.op!=="read")continue;
178
+ const list=output?.files??output?.reads??output?.results;
179
+ const row=Array.isArray(list)?(output?.results?list.find(r=>r.index===index):list[index]):null;
180
+ const single=action==="fs.read"||action==="full.workspace.read"&&!Array.isArray(input.relativePaths);
181
+ add(typeof source==="string"?source:source?.path,index,row?.ok===true||single&&result?.ok!==false?"completed":row?.ok===false||result?.ok===false?"failed":"unknown","read",row?.error??result?.error);
182
+ }
183
+ }
184
+ // Bounded display metadata only. No raw commands, output, Learn values,
185
+ // or arbitrary response objects. Search terms use display redaction.
186
+ const search=describeLocalSearch(payload);
187
+ const details={files,omitted,...search,exitCode:Number.isInteger(output?.exitCode)?output.exitCode:null,resultCount:safeInteger(output?.totalResults??output?.total),error:safeError(result?.error)};
188
+ return files.length||omitted||details.query||details.searchScope||(details.exitCode!==null&&details.exitCode!==0)||details.resultCount!==null?details:null;
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
+ }
211
+ export function projectActivityDetails(details){
212
+ if(!details)return {files:[],available:false};
213
+ return {available:true,omitted:details.omitted??0,query:details.query??"",searchScope:details.searchScope??"",exitCode:details.exitCode,resultCount:details.resultCount,error:details.error,
214
+ files:details.files.map(({pair,...file})=>{
215
+ const stats=changeStats(pair);
216
+ return {...file,diffAvailable:stats.state==="ready",additions:stats.additions,deletions:stats.deletions};
217
+ })};
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
+ }
@@ -1,3 +1,5 @@
1
+ import { FullResourceAdmission } from "./full-resources.mjs";
2
+
1
3
  const DEFAULT_QUEUE_TIMEOUT_MS = 15_000;
2
4
  const DEFAULT_MAX_QUEUED = 64;
3
5
 
@@ -21,13 +23,14 @@ export class BoundedLane {
21
23
  this.queueTimeoutMs = boundedInteger(options.queueTimeoutMs, DEFAULT_QUEUE_TIMEOUT_MS, 100, 120_000);
22
24
  this.active = 0;
23
25
  this.queue = [];
26
+ this.fullAdmission = options.fullAdmission ?? null;
24
27
  }
25
28
 
26
29
  run(work) {
27
30
  if (typeof work !== "function") return Promise.reject(queueError("invalid_work"));
28
31
  return new Promise((resolve, reject) => {
29
32
  const job = { work, resolve, reject, timer: null, enqueuedAt: Date.now() };
30
- if (this.active < this.concurrency) {
33
+ if (this.active < this.concurrency && (!this.fullAdmission || !this.queue.length)) {
31
34
  this.#start(job);
32
35
  return;
33
36
  }
@@ -42,9 +45,46 @@ export class BoundedLane {
42
45
  reject(queueError("queue_timeout"));
43
46
  }, this.queueTimeoutMs);
44
47
  this.queue.push(job);
48
+ if(this.fullAdmission)this.#drain();
45
49
  });
46
50
  }
47
51
 
52
+ runAdmitted(work, options) {
53
+ if(!this.fullAdmission)return Promise.reject(queueError("full_unavailable"));
54
+ if(typeof work!=="function")return Promise.reject(queueError("invalid_work"));
55
+ if(options?.dependenciesReady!==true)return Promise.reject(queueError("full_dependency_not_ready"));
56
+ if(options.signal?.aborted)return Promise.reject(queueError("full_cancelled_before_start"));
57
+ return new Promise((resolve,reject)=>{
58
+ if(this.queue.length>=this.maxQueued)return reject(queueError("queue_full"));
59
+ const job={work,resolve,reject,timer:null,enqueuedAt:this.fullAdmission.now(),signal:options.signal};
60
+ try{
61
+ job.ticket=this.fullAdmission.register({...options,ready:()=>this.active<this.concurrency});
62
+ }catch(error){reject(error);return;}
63
+ const cancel=code=>{
64
+ const index=this.queue.indexOf(job);
65
+ if(index<0)return;
66
+ this.queue.splice(index,1);
67
+ this.fullAdmission.withdraw(job.ticket);
68
+ this.#clearWait(job);
69
+ reject(queueError(code));
70
+ this.#drain();
71
+ };
72
+ job.abort=()=>cancel("full_cancelled_before_start");
73
+ job.timer=setTimeout(()=>cancel("queue_timeout"),
74
+ boundedInteger(options.queueTimeoutMs,this.queueTimeoutMs,100,this.queueTimeoutMs));
75
+ job.signal?.addEventListener("abort",job.abort,{once:true});
76
+ this.queue.push(job);
77
+ this.#drain();
78
+ });
79
+ }
80
+
81
+ wake(){if(this.fullAdmission)this.#drain();}
82
+
83
+ #clearWait(job){
84
+ if(job.timer)clearTimeout(job.timer);
85
+ if(job.abort)job.signal?.removeEventListener("abort",job.abort);
86
+ }
87
+
48
88
  snapshot() {
49
89
  return {
50
90
  concurrency: this.concurrency,
@@ -57,6 +97,7 @@ export class BoundedLane {
57
97
 
58
98
  #start(job) {
59
99
  if (job.timer) clearTimeout(job.timer);
100
+ if (job.abort) job.signal?.removeEventListener("abort",job.abort);
60
101
  this.active += 1;
61
102
  const queueWaitMs = Math.max(0, Date.now() - job.enqueuedAt);
62
103
  const metadata = {
@@ -65,18 +106,41 @@ export class BoundedLane {
65
106
  queueDepthAtStart: this.queue.length,
66
107
  activeAtStart: this.active,
67
108
  };
109
+ if(job.lease){
110
+ Promise.resolve()
111
+ .then(()=>{if(job.signal?.aborted)throw queueError("full_cancelled_before_start");return job.work(metadata,job.lease);})
112
+ .then(value=>{job.lease.finishRequest(false);job.resolve(value);},
113
+ error=>{job.lease.finishRequest(true);job.reject(error);})
114
+ .finally(()=>{this.active-=1;this.#drain();this.fullAdmission.changed();});
115
+ return;
116
+ }
68
117
  Promise.resolve()
69
118
  .then(() => job.work(metadata))
70
119
  .then(job.resolve, job.reject)
71
120
  .finally(() => {
72
121
  this.active -= 1;
73
122
  this.#drain();
123
+ this.fullAdmission?.changed();
74
124
  });
75
125
  }
76
126
 
77
127
  #drain() {
78
- while (this.active < this.concurrency && this.queue.length > 0) {
79
- this.#start(this.queue.shift());
128
+ if(!this.fullAdmission){
129
+ while(this.active<this.concurrency&&this.queue.length>0)this.#start(this.queue.shift());
130
+ return;
131
+ }
132
+ const rank=job=>job.ticket?this.fullAdmission.rank(job.ticket):2;
133
+ while(this.active<this.concurrency&&this.queue.length>0){
134
+ const ordered=[...this.queue].sort((a,b)=>rank(b)-rank(a)||a.enqueuedAt-b.enqueuedAt);
135
+ let next=null;
136
+ for(const job of ordered){
137
+ if(!job.ticket){next=job;break;}
138
+ const lease=this.fullAdmission.tryGrant(job.ticket);
139
+ if(lease){job.lease=lease;next=job;break;}
140
+ }
141
+ if(!next)break;
142
+ this.queue.splice(this.queue.indexOf(next),1);
143
+ this.#start(next);
80
144
  }
81
145
  }
82
146
  }
@@ -85,7 +149,8 @@ export class CapabilityScheduler {
85
149
  constructor(options = {}) {
86
150
  const maxQueued = boundedInteger(options.maxQueued, DEFAULT_MAX_QUEUED, 1, 512);
87
151
  const queueTimeoutMs = boundedInteger(options.queueTimeoutMs, DEFAULT_QUEUE_TIMEOUT_MS, 100, 120_000);
88
- const lane = (name, concurrency) => new BoundedLane({ name, concurrency, maxQueued, queueTimeoutMs });
152
+ this.fullAdmission = options.full === true ? new FullResourceAdmission(options.fullResourceOptions) : null;
153
+ const lane = (name, concurrency) => new BoundedLane({ name, concurrency, maxQueued, queueTimeoutMs, fullAdmission:this.fullAdmission });
89
154
 
90
155
  this.lanes = new Map([
91
156
  ["agent", lane("agent", options.agentConcurrency ?? 4)],
@@ -98,9 +163,11 @@ export class CapabilityScheduler {
98
163
  concurrency: options.terminalWaitConcurrency ?? 2,
99
164
  maxQueued: 2,
100
165
  queueTimeoutMs: 1000,
166
+ fullAdmission:this.fullAdmission,
101
167
  })],
102
168
  ["desktopRead", lane("desktopRead", options.desktopReadConcurrency ?? 2)],
103
169
  ]);
170
+ if(this.fullAdmission)this.fullAdmission.subscribe(()=>{for(const lane of this.lanes.values())lane.wake();});
104
171
  }
105
172
 
106
173
  run(action, work) {
@@ -108,8 +175,18 @@ export class CapabilityScheduler {
108
175
  return lane ? lane.run(work) : Promise.resolve().then(work);
109
176
  }
110
177
 
178
+ // Trusted Core broker only. Dependencies must already be ready; this method
179
+ // never waits for child work while occupying a parent lane or reservation.
180
+ runFull(action,work,options){
181
+ if(!this.fullAdmission)return Promise.reject(queueError("full_unavailable"));
182
+ const lane=this.#laneFor(action)??this.lanes.get("agent");
183
+ return lane.runAdmitted(work,options);
184
+ }
185
+
111
186
  snapshot() {
112
- return Object.fromEntries([...this.lanes.entries()].map(([name, lane]) => [name, lane.snapshot()]));
187
+ const lanes=Object.fromEntries([...this.lanes.entries()].map(([name,lane])=>[name,lane.snapshot()]));
188
+ if(this.fullAdmission)lanes.fullResources=this.fullAdmission.snapshot();
189
+ return lanes;
113
190
  }
114
191
 
115
192
  #laneFor(action) {
@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { deduplicateSearchPreviews } from "./fs-batch-preview.mjs";
5
+ import {captureActivityBefore,recordActivityEdit} from "./activity-capture.mjs";
5
6
 
6
7
  const MAX_READ_BYTES = 256 * 1024;
7
8
  const DEFAULT_READ_RESPONSE_BYTES = 32 * 1024;
@@ -425,13 +426,13 @@ export class FileManager {
425
426
  }
426
427
 
427
428
  // One entry per file, multiple exact replacements per entry. Separate from read-only batch.
428
- editMany(operations, basePath) {
429
- const run = this.editBatchTail.then(() => this.#editMany(operations, basePath));
429
+ editMany(operations, basePath, {strictPaths=false}={}) {
430
+ const run = this.editBatchTail.then(() => this.#editMany(operations, basePath,strictPaths));
430
431
  this.editBatchTail = run.catch(() => {});
431
432
  return run;
432
433
  }
433
434
 
434
- async #editMany(operations, basePath) {
435
+ async #editMany(operations, basePath, strictPaths) {
435
436
  if (!Array.isArray(operations) || !operations.length || operations.length > MAX_BATCH_OPERATIONS) {
436
437
  throw new Error("invalid_edit_batch");
437
438
  }
@@ -439,6 +440,7 @@ export class FileManager {
439
440
  const count = operations.reduce((sum, op) => sum + (Array.isArray(op?.edits) ? op.edits.length : 0), 0);
440
441
  if (count > MAX_BATCH_EDITS) throw new Error("too_many_batch_edits");
441
442
  const base = await this.#resolveBatchBase(basePath);
443
+ if(strictPaths&&(!base||path.relative(basePath,base)!==""))throw new Error("target_changed");
442
444
  const resolved = [];
443
445
  const targets = new Map();
444
446
  for (const [index, operation] of operations.entries()) {
@@ -449,6 +451,7 @@ export class FileManager {
449
451
  const create = operation.op === "create";
450
452
  const selected = await this.#batchPath(input, base, create);
451
453
  const target = create ? selected : await this.#resolveExisting(selected);
454
+ if(strictPaths&&path.relative(path.resolve(base,input),target)!=="")throw new Error("target_changed");
452
455
  const key = process.platform === "win32" ? target.toLowerCase() : target;
453
456
  resolved.push({ row, operation, target, key });
454
457
  targets.set(key, (targets.get(key) || 0) + 1);
@@ -495,6 +498,7 @@ export class FileManager {
495
498
  updated = utf8Bytes(text, MAX_WRITE_BYTES * 8);
496
499
  }
497
500
  await this.#commitBatchFile(target, original, updated, mode, base);
501
+ recordActivityEdit(row.index,row.path,original,updated,create?"added":"modified",target);
498
502
  results.push({ ...row, ok: true, op: operation.op, bytes: updated.length, ...(create ? {} : { replacements }) });
499
503
  } catch (error) {
500
504
  results.push({ ...row, ok: false, op: operation.op, error: editError(error) });
@@ -557,10 +561,26 @@ export class FileManager {
557
561
  if (typeof content !== "string" || Buffer.byteLength(content, "utf8") > MAX_WRITE_BYTES) {
558
562
  throw new Error("content_too_large");
559
563
  }
560
- const target = await this.#resolveTarget(input);
561
- if (mode === "append") await fs.appendFile(target, content, "utf8");
562
- else if (mode === "rewrite") await fs.writeFile(target, content, "utf8");
563
- else throw new Error("invalid_write_mode");
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);
564
584
  return this.stat(target);
565
585
  }
566
586
 
@@ -579,6 +599,7 @@ export class FileManager {
579
599
  const updated = parts.join(newText);
580
600
  if (Buffer.byteLength(updated, "utf8") > MAX_WRITE_BYTES * 8) throw new Error("file_too_large");
581
601
  await fs.writeFile(target, updated, "utf8");
602
+ recordActivityEdit(0,input,text,updated,"modified",target);
582
603
  return { path: target, replacements: matches };
583
604
  }
584
605
 
@@ -602,7 +623,11 @@ export class FileManager {
602
623
  }
603
624
  const info = await fs.stat(target);
604
625
  if (info.isDirectory()) await fs.rm(target, { recursive: Boolean(recursive), force: false });
605
- else await fs.unlink(target);
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
+ }
606
631
  return { ok: true, path: target };
607
632
  }
608
633
 
@@ -0,0 +1,53 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createEventBuffer, fullUnavailable, hasFullSessionRequest, toolCorrelation } from "../packages/full-contracts/index.mjs";
3
+
4
+ export { fullUnavailable, hasFullSessionRequest };
5
+
6
+ // Optional best-effort IPC projection. Exactly one send is in flight; the ring
7
+ // bounds backlog, and a consumer sees an explicit gap after a slow/disconnected
8
+ // subscriber. Critical state never relies on this channel.
9
+ export function createCoreEventBridge({ enabled = false, send, producerEpoch = randomUUID, now = () => new Date().toISOString(), capacity } = {}) {
10
+ if (!enabled || typeof send !== "function") return null;
11
+ const epoch = producerEpoch();
12
+ const buffer = createEventBuffer({ producerEpoch: epoch, ...(capacity === undefined ? {} : { capacity }) });
13
+ let cursor = { producerEpoch: epoch, sequence: 0 };
14
+ let sending = false;
15
+ let scheduled = false;
16
+ let closed = false;
17
+ function schedule() {
18
+ if (closed || sending || scheduled) return;
19
+ scheduled = true;
20
+ setImmediate(flush);
21
+ }
22
+ function flush() {
23
+ scheduled = false;
24
+ if (closed || sending) return;
25
+ const batch = buffer.readAfter(cursor);
26
+ if (!batch.events.length) return;
27
+ sending = true;
28
+ let settled = false;
29
+ const finish = (error) => {
30
+ if (settled) return;
31
+ settled = true;
32
+ sending = false;
33
+ if (error) { closed = true; return; }
34
+ cursor = batch.cursor;
35
+ if (buffer.readAfter(cursor).events.length) schedule();
36
+ };
37
+ try { send({ type: "chat-relay-full-events", ...batch }, finish); }
38
+ catch (error) { finish(error); }
39
+ }
40
+ return {
41
+ publish(type, requestId, action, observability, outcome = {}) {
42
+ if (closed) return;
43
+ // A malformed or failing observer never changes the tool result.
44
+ try {
45
+ buffer.append({ type, requestId, action, at: now(), ...toolCorrelation(observability),
46
+ ...(typeof outcome.ok === "boolean" ? { ok: outcome.ok } : {}),
47
+ ...(Number.isFinite(outcome.durationMs) ? { durationMs: outcome.durationMs } : {}) });
48
+ schedule();
49
+ } catch {}
50
+ },
51
+ close() { closed = true; },
52
+ };
53
+ }