@anusornneal/chat-relay 1.8.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +60 -0
  2. package/agent/activity-capture.mjs +165 -0
  3. package/agent/capability-scheduler.mjs +83 -6
  4. package/agent/file-manager.mjs +188 -77
  5. package/agent/fs-batch-preview.mjs +70 -0
  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 +308 -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 +170 -4
  20. package/agent/lifecycle.mjs +17 -0
  21. package/agent/local-agent.mjs +182 -33
  22. package/agent/local-usage.mjs +275 -0
  23. package/agent/monitor-activity.mjs +111 -0
  24. package/agent/presentation-redaction.mjs +10 -0
  25. package/agent/process-manager.mjs +32 -0
  26. package/agent/protocol.mjs +5 -1
  27. package/agent/terminal-manager.mjs +240 -29
  28. package/agent/terminal-output.mjs +136 -0
  29. package/agent/toolcall-context.mjs +35 -5
  30. package/agent/toolcall-summary.mjs +10 -0
  31. package/agent/windows-desktop-runner.mjs +65 -61
  32. package/agent/windows-desktop-worker.ps1 +33 -18
  33. package/agent/windows-powershell.mjs +51 -0
  34. package/cli/full-background.mjs +69 -0
  35. package/cli/full-launch.mjs +94 -0
  36. package/cli/full-prepare-child.mjs +48 -0
  37. package/cli/full-prepare.mjs +171 -0
  38. package/cli/full-release-default.json +4 -0
  39. package/cli/full-release-files.mjs +36 -0
  40. package/cli/full-release-official.mjs +48 -0
  41. package/cli/full-release-source.mjs +37 -0
  42. package/cli/index.mjs +8 -4
  43. package/cli/mod-cache.mjs +170 -0
  44. package/cli/mod-loader.mjs +67 -0
  45. package/cli/mod-manifest.mjs +63 -0
  46. package/cli/remote.mjs +172 -17
  47. package/cli/runner-ownership.mjs +116 -3
  48. package/cli/self-update.mjs +1 -1
  49. package/cli/tui.mjs +2 -20
  50. package/package.json +9 -6
  51. package/packages/full-contracts/index.mjs +193 -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
@@ -278,3 +278,63 @@ The decision boundary is deliberate:
278
278
  Project aliases are account-scoped mappings stored in the Learning Durable Object. Use **My Learn → Merge projects** to join workspace names (for example `buddy-android` → `buddy2`) once, while retaining memory IDs, feedback, and timestamps; the source becomes a permanent alias for future Learn reads/writes across machines. Aliases are never inferred from similar names, and project resolution occurs only during Learn requests—not on ordinary tool calls. Merges run transactionally; conflicting keys with distinct content are renamed instead of discarded.\n\nRouting hints are explicit memories. A global `project_context` memory with key `project-root:<projectKey>` stores the concrete project root. A `preferred-agent` memory may exist in project scope (preferred) or global scope (fallback). `learn_prepare` can also take explicit `projectKey` and `agentId` values when Chat already knows them.
279
279
 
280
280
  `learn_prepare` is intentionally one-shot and stateless at the Worker level. There is no warm session cache or durable Learn session state to maintain. This prevents Learn from becoming an implicit per-tool CPU/subrequest tax while still allowing relevance-aware context preparation when it is actually useful.
281
+
282
+ ## Efficient tool usage (agent and MCP must support the new capabilities)
283
+
284
+ - For multiple independent file edits/creates use **edit_files** (write permission).
285
+ The operation list supports a missing-file create or 1-20 exact replacements per
286
+ file. At most 20 files, 100 replacements and 48 KiB encoded arguments per batch.
287
+ Existing parents are required. Each result identifies its original index and
288
+ success/error; inspect results and retry only failed entries after re-reading.
289
+ UTF-8 is validated; uniform CRLF and BOM are preserved for existing files.
290
+ Updates publish atomically per file and recheck the original bytes before
291
+ replacement; this is not a cross-file transaction or an OS compare-and-swap
292
+ against other programs writing concurrently. Create uses no-clobber publication
293
+ on filesystems supporting hard links.
294
+ - **read_multiple_files**, **fs_batch**, and **edit_files** accept an optional
295
+ absolute basePath. With it, paths must be relative and stay beneath that
296
+ canonical directory and allowedRoots, including junction/symlink checks.
297
+ Without it existing path behavior is retained.
298
+ - **fs_batch** with deduplicatePreviews=true packs overlapping identical search
299
+ context into sharedPreviews. A match's preview.ref refers to sharedPreviews.id;
300
+ reconstruct the original content by slicing the shared content's lines from
301
+ preview.offset - shared.offset for preview.length lines. Matches, individual
302
+ metadata and search sessions/pagination are preserved. This saves response
303
+ bytes, not repeated search scans.
304
+ - **terminal_exec**, **terminal_read** and **terminal_batch_read** default to
305
+ full output. Optional outputMode=summary, tail, or errors limits displayed
306
+ text (outputChars defaults to 2048, range 256-8192). Summary keeps failure
307
+ diagnostics; errors is a heuristic, not a compiler parser. Compact exec
308
+ returns rawOutputId if text was omitted; read it with terminal_read and the
309
+ normal nextSeq cursor. Up to 16 short-command captures for 10 minutes in RAM.
310
+ For compact session reads replay full mode with rawAfterSeq while the session
311
+ buffer is retained. For batches replay full mode with jobIndex. Original
312
+ capture/time/size limits still apply; use terminal_start for verbose/long
313
+ commands. Neither compact output nor a replay executes the command again.
314
+ - **get_recent_tool_calls** keeps its legacy array response (up to 100 entries).
315
+ Use view=history with limit and nextCursor to page up to 1000 process-local
316
+ calls; cursor expires on process restart. Use view=stats with days=1..30 for
317
+ UTC-day totals, per-tool calls/failures/durations/bytes, batch item counts,
318
+ observed batch-read share and estimated saved read calls. Saved calls assume
319
+ one separate read per successful read operation; continuation and missed batch
320
+ opportunities are not measured. Terminal-based reads are not classified.
321
+ Only numerical daily aggregates are persisted per agent under the local
322
+ Chat Relay config directory's usage/ folder. No paths, commands, content,
323
+ credentials or screenshots are persisted by this feature. A dirty snapshot
324
+ flushes at most once per 30 seconds and at graceful exit; abrupt termination
325
+ can lose recent counters. Recent detailed entries and compact raw output
326
+ are RAM-only. Each agent's statistics start after it upgrades; no historical
327
+ backfill. Set CHAT_RELAY_USAGE_DISABLED=1 for memory-only aggregates.
328
+ - New optional behaviors use distinct agent actions so older agents fail
329
+ explicitly rather than interpreting relative paths or compact requests
330
+ incorrectly. Existing calls remain unchanged. Upgrade the local agent and
331
+ refresh the MCP catalog before using the new features.
332
+
333
+ No new Cloudflare storage, dependencies or additional routine relay round trips
334
+ are needed for these improvements.
335
+
336
+ ## Chat Relay Full (2.0)
337
+
338
+ Windows x64 with supported Node.js: `npx @anusornneal/chat-relay@latest remote --full` opens the native Slint monitor; add `--headless` for Full without the window. Ordinary `remote` remains Lite and downloads no Full artifact. The published Core carries a release-specific Ed25519 public key; the exact-version signed GUI/headless archive is downloaded lazily from the matching GitHub Release, verified and cached locally. This release does not claim OS code signing or Full public support on other targets.
339
+
340
+ Existing explicit `full-release.json` settings override the public default. To migrate from a local development candidate, stop the agent gracefully, back up only that settings file and move it aside, then launch 2.0. Keep existing login and session data. To roll back, restore the settings file and launch the exact previous Core version. An incompatible or unavailable Full artifact never silently starts Lite.
@@ -0,0 +1,165 @@
1
+ import {AsyncLocalStorage} from "node:async_hooks";
2
+ import path from "node:path";
3
+ import {redactPresentationText} from "./presentation-redaction.mjs";
4
+ import {presentationChangePath} from "./full-presentation-changes.mjs";
5
+
6
+ const storage=new AsyncLocalStorage();
7
+ const MAX_FILES=20,MAX_PAIR_BYTES=32*1024,MAX_CALL_BYTES=64*1024,MAX_LINES=400,MAX_DIFF_CHARS=12000;
8
+ const safeError=value=>typeof value==="string"&&/^[A-Za-z][A-Za-z0-9_:-]{1,95}$/.test(value)?value:"";
9
+ const safeInteger=value=>Number.isSafeInteger(value)&&value>=0?value:null;
10
+ const decode=value=>{
11
+ if(value===null)return "";
12
+ if(typeof value==="string")return value;
13
+ if(!Buffer.isBuffer(value))return null;
14
+ try{return new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(value);}catch{return null;}
15
+ };
16
+ export function displayActivityPath(value){
17
+ if(typeof value!=="string"||!value||value.length>4096)return "";
18
+ const normalized=value.replace(/\\/g,"/");
19
+ const absolute=path.isAbsolute(value)||/^[A-Za-z]:\//.test(normalized)||normalized.startsWith("/");
20
+ const parts=normalized.split("/").filter(Boolean);
21
+ // Never reveal credential file names or private path components. Worktree
22
+ // roots themselves may contain .workspace, but display only the leaf of an
23
+ // absolute path (relative request paths retain their project context).
24
+ for(const p of parts){
25
+ if(p===".workspace"&&absolute)continue;
26
+ if(/^[A-Za-z]:$/.test(p)&&absolute)continue;
27
+ if(!presentationChangePath(p))return "";
28
+ }
29
+ const result=absolute?parts.at(-1):normalized;
30
+ return result&&result.length<=512&&presentationChangePath(result)&&redactPresentationText(result,512)===result?result:"";
31
+ }
32
+ const detailActions=new Set(["fs.editMany","full.workspace.edit","fs.edit","fs.write","fs.delete","fs.read","full.workspace.read","fs.readMany","fs.readMany.relative","fs.batch","fs.batch.compact","fs.search.start","fs.search.results","full.intelligence.search","full.intelligence.symbols","terminal.exec","terminal.exec.compact","terminal.read","terminal.read.compact","full.job.read"]);
33
+ // Capture only explicitly supplied search terms or quoted literal rg/Select-String
34
+ // patterns. Never retain shell scripts, environment values or command output.
35
+ export function describeLocalSearch(payload){
36
+ const action=payload?.action==="full.invoke"?payload.operation:payload?.action;
37
+ const input=payload?.action==="full.invoke"?payload.input??{}:payload??{};
38
+ let query="",scope="";
39
+ if(action==="fs.search.start"){query=input.pattern;scope=displayActivityPath(input.path);}
40
+ else if(["full.intelligence.search","full.intelligence.symbols"].includes(action)){query=input.query;}
41
+ else if(["terminal.exec","terminal.exec.compact","terminal.start"].includes(action)&&typeof input.command==="string"&&input.command.length<=16000){
42
+ const patterns=[];
43
+ // Support common quoted literal search arguments, not shell expansion.
44
+ for(const m of input.command.matchAll(/(?:^|[;|\n]\s*)\s*(?:rg|Select-String)\s+(?:(?:-(?:C|A|B)\s+\d+|--?[A-Za-z0-9-]+)\s+)*(?:'([^'\r\n]{1,180})'|"([^"$\x60\r\n]{1,180})")/gi)){
45
+ patterns.push(m[1]??m[2]);if(patterns.length===3)break;
46
+ }
47
+ query=patterns.join(" · ");
48
+ }
49
+ const safe=value=>typeof value==="string"&&value.length<=512?redactPresentationText(value.replace(/[\r\n\t]/g," "),180):"";
50
+ return {query:safe(query),searchScope:safe(scope)};
51
+ }
52
+ export function captureActivityFor(payload){
53
+ const action=payload?.action==="full.invoke"?payload.operation:payload?.action;
54
+ return detailActions.has(action)?createActivityCapture():null;
55
+ }
56
+ export function createActivityCapture(){
57
+ return {files:new Map(),bytes:0,closed:false};
58
+ }
59
+ export function runActivityCapture(capture,work){
60
+ return capture?storage.run(capture,work):work();
61
+ }
62
+ export function recordActivityEdit(index,requestedPath,before,after,kind,canonicalTarget){
63
+ const context=storage.getStore();
64
+ if(!context||context.closed||context.files.size>=MAX_FILES)return;
65
+ // Observation must never turn a successful write into a failed write.
66
+ try{
67
+ const name=displayActivityPath(requestedPath);
68
+ if(!name||!displayActivityPath(canonicalTarget))return;
69
+ const entry={path:name,kind,pair:null};
70
+ context.files.set(index,entry);
71
+ if(before===undefined||after===undefined)return;
72
+ const size=(before===null?0:Buffer.byteLength(before))+(after===null?0:Buffer.byteLength(after));
73
+ if(size>MAX_PAIR_BYTES||context.bytes+size>MAX_CALL_BYTES)return;
74
+ const a=decode(before),b=decode(after);
75
+ if(a===null||b===null||a.includes("\0")||b.includes("\0")||a.includes("\uFFFD")||b.includes("\uFFFD"))return;
76
+ if(redactPresentationText(a,a.length)!==a||redactPresentationText(b,b.length)!==b)return;
77
+ if(a.split("\n").length>MAX_LINES||b.split("\n").length>MAX_LINES)return;
78
+ entry.pair={before:a,after:b};
79
+ context.bytes+=size;
80
+ }catch{/* Optional monitor only. */}
81
+ }
82
+ // Exact bounded line edit script from the recorded pair. Retain newline
83
+ // characters in the comparison so final-newline and CRLF changes are real.
84
+ function splitLines(value){return value.match(/[^\n]*\n|[^\n]+$/g)??[];}
85
+ export function historicalDiff(pair,{includeText=true}={}){
86
+ if(!pair)return {state:"unavailable",reason:"No captured text for this call",additions:null,deletions:null,text:""};
87
+ const a=splitLines(pair.before),b=splitLines(pair.after);
88
+ if(a.length>MAX_LINES||b.length>MAX_LINES)return {state:"unavailable",reason:"Change exceeds capture limit",additions:null,deletions:null,text:""};
89
+ // Strip unchanged prefix/suffix before allocating the bounded LCS table.
90
+ // Typical targeted edits need only a few cells instead of 400 x 400.
91
+ let start=0,ae=a.length,be=b.length;
92
+ while(start<ae&&start<be&&a[start]===b[start])start++;
93
+ while(ae>start&&be>start&&a[ae-1]===b[be-1]){ae--;be--;}
94
+ const width=be-start+1,dp=new Uint16Array((ae-start+1)*width);
95
+ const cell=(i,j)=>(i-start)*width+j-start;
96
+ for(let i=ae-1;i>=start;i--)for(let j=be-1;j>=start;j--)dp[cell(i,j)]=a[i]===b[j]?1+dp[cell(i+1,j+1)]:Math.max(dp[cell(i+1,j)],dp[cell(i,j+1)]);
97
+ const lines=includeText?a.slice(0,start).map(line=>[" ",line]):[];
98
+ let i=start,j=start,additions=0,deletions=0;
99
+ while(i<ae||j<be){
100
+ if(i<ae&&j<be&&a[i]===b[j]){if(includeText)lines.push([" ",a[i]]);i++;j++;}
101
+ else if(i<ae&&(j===be||dp[cell(i+1,j)]>=dp[cell(i,j+1)])){if(includeText)lines.push(["-",a[i]]);i++;deletions++;}
102
+ else{if(includeText)lines.push(["+",b[j]]);j++;additions++;}
103
+ }
104
+ if(includeText)for(const line of a.slice(ae))lines.push([" ",line]);
105
+ if(!includeText)return {state:"ready",additions,deletions};
106
+ if(!additions&&!deletions)return {state:"ready",additions,deletions,text:"No textual changes",truncated:false};
107
+ // One bounded hunk with genuine context; never substitute current Git diff.
108
+ const first=lines.findIndex(l=>l[0]!==" "),last=lines.findLastIndex(l=>l[0]!==" ");
109
+ const from=Math.max(0,first-3),to=Math.min(lines.length,last+4);
110
+ let oldStart=1,newStart=1;
111
+ for(const [op] of lines.slice(0,from)){if(op!=="+")oldStart++;if(op!=="-")newStart++;}
112
+ const hunk=lines.slice(from,to),oldCount=hunk.filter(l=>l[0]!=="+").length,newCount=hunk.filter(l=>l[0]!=="-").length;
113
+ const format=([op,line])=>op+line.replace(/\r?\n$/,"")+(line.endsWith("\n")?"":"\n\");
114
+ const raw="@@ -"+(oldCount?oldStart:oldStart-1)+","+oldCount+" +"+(newCount?newStart:newStart-1)+","+newCount+" @@\n"+hunk.map(format).join("\n");
115
+ const text=raw.slice(0,MAX_DIFF_CHARS).toWellFormed();
116
+ return {state:"ready",additions,deletions,text,truncated:text.length<raw.length};
117
+ }
118
+ export function finishActivityCapture(capture,payload,result){
119
+ if(!capture)return null;
120
+ capture.closed=true;
121
+ const action=payload?.action==="full.invoke"?payload.operation:payload?.action;
122
+ const input=payload?.action==="full.invoke"?payload.input??{}:payload??{};
123
+ const output=payload?.action==="full.invoke"?result?.result:result;
124
+ const files=[];let omitted=0;
125
+ const add=(source,index,outcome,kind,error)=>{
126
+ if(files.length>=MAX_FILES){omitted++;return;}
127
+ const captured=capture.files.get(index),name=captured?.path||displayActivityPath(source);
128
+ if(!name){omitted++;return;}
129
+ files.push({fileId:String(index),path:name,kind:captured?.kind??kind,outcome,error:safeError(error),pair:outcome==="completed"?captured?.pair??null:null});
130
+ };
131
+ const edit=action==="fs.editMany"||action==="full.workspace.edit";
132
+ if(edit){
133
+ const operations=Array.isArray(input.operations)?input.operations:[];
134
+ omitted=Math.max(0,operations.length-MAX_FILES);
135
+ for(const [index,op] of operations.slice(0,MAX_FILES).entries()){
136
+ const row=Array.isArray(output?.results)?output.results.find(r=>r.index===index):null;
137
+ add(op?.relativePath??op?.path,index,row?.ok===true?"completed":row?.ok===false||result?.ok===false?"failed":"unknown",op?.op==="create"?"added":"modified",row?.error);
138
+ }
139
+ }else if(action==="fs.edit"||action==="fs.write"||action==="fs.delete"){
140
+ add(input.path,0,result?.ok===false?"failed":"completed",action==="fs.delete"?"deleted":action==="fs.write"?"written":"modified",result?.error);
141
+ }else if(action==="fs.read"||action==="full.workspace.read"||action==="fs.readMany"||action==="fs.readMany.relative"||action==="fs.batch"||action==="fs.batch.compact"){
142
+ const sources=Array.isArray(input.paths)?input.paths:Array.isArray(input.relativePaths)?input.relativePaths:Array.isArray(input.operations)?input.operations:[input.relativePath??input.path];
143
+ omitted=Math.max(0,sources.length-MAX_FILES);
144
+ for(const [index,source] of sources.slice(0,MAX_FILES).entries()){
145
+ if(source?.op&&source.op!=="read")continue;
146
+ const list=output?.files??output?.reads??output?.results;
147
+ const row=Array.isArray(list)?(output?.results?list.find(r=>r.index===index):list[index]):null;
148
+ const single=action==="fs.read"||action==="full.workspace.read"&&!Array.isArray(input.relativePaths);
149
+ add(typeof source==="string"?source:source?.path,index,row?.ok===true||single&&result?.ok!==false?"completed":row?.ok===false||result?.ok===false?"failed":"unknown","read",row?.error??result?.error);
150
+ }
151
+ }
152
+ // Bounded display metadata only. No raw commands, output, Learn values,
153
+ // or arbitrary response objects. Search terms use display redaction.
154
+ const search=describeLocalSearch(payload);
155
+ const details={files,omitted,...search,exitCode:Number.isInteger(output?.exitCode)?output.exitCode:null,resultCount:safeInteger(output?.totalResults??output?.total),error:safeError(result?.error)};
156
+ return files.length||omitted||details.query||details.searchScope||(details.exitCode!==null&&details.exitCode!==0)||details.resultCount!==null?details:null;
157
+ }
158
+ export function projectActivityDetails(details){
159
+ if(!details)return {files:[],available:false};
160
+ return {available:true,omitted:details.omitted??0,query:details.query??"",searchScope:details.searchScope??"",exitCode:details.exitCode,resultCount:details.resultCount,error:details.error,
161
+ files:details.files.map(({pair,...file})=>{
162
+ const stats=historicalDiff(pair,{includeText:false});
163
+ return {...file,diffAvailable:stats.state==="ready",additions:stats.additions,deletions:stats.deletions};
164
+ })};
165
+ }
@@ -1,3 +1,5 @@
1
+ import { FullResourceAdmission } from "./full-resources.mjs";
2
+
1
3
  const DEFAULT_QUEUE_TIMEOUT_MS = 15_000;
2
4
  const DEFAULT_MAX_QUEUED = 64;
3
5
 
@@ -21,13 +23,14 @@ export class BoundedLane {
21
23
  this.queueTimeoutMs = boundedInteger(options.queueTimeoutMs, DEFAULT_QUEUE_TIMEOUT_MS, 100, 120_000);
22
24
  this.active = 0;
23
25
  this.queue = [];
26
+ this.fullAdmission = options.fullAdmission ?? null;
24
27
  }
25
28
 
26
29
  run(work) {
27
30
  if (typeof work !== "function") return Promise.reject(queueError("invalid_work"));
28
31
  return new Promise((resolve, reject) => {
29
32
  const job = { work, resolve, reject, timer: null, enqueuedAt: Date.now() };
30
- if (this.active < this.concurrency) {
33
+ if (this.active < this.concurrency && (!this.fullAdmission || !this.queue.length)) {
31
34
  this.#start(job);
32
35
  return;
33
36
  }
@@ -42,9 +45,46 @@ export class BoundedLane {
42
45
  reject(queueError("queue_timeout"));
43
46
  }, this.queueTimeoutMs);
44
47
  this.queue.push(job);
48
+ if(this.fullAdmission)this.#drain();
45
49
  });
46
50
  }
47
51
 
52
+ runAdmitted(work, options) {
53
+ if(!this.fullAdmission)return Promise.reject(queueError("full_unavailable"));
54
+ if(typeof work!=="function")return Promise.reject(queueError("invalid_work"));
55
+ if(options?.dependenciesReady!==true)return Promise.reject(queueError("full_dependency_not_ready"));
56
+ if(options.signal?.aborted)return Promise.reject(queueError("full_cancelled_before_start"));
57
+ return new Promise((resolve,reject)=>{
58
+ if(this.queue.length>=this.maxQueued)return reject(queueError("queue_full"));
59
+ const job={work,resolve,reject,timer:null,enqueuedAt:this.fullAdmission.now(),signal:options.signal};
60
+ try{
61
+ job.ticket=this.fullAdmission.register({...options,ready:()=>this.active<this.concurrency});
62
+ }catch(error){reject(error);return;}
63
+ const cancel=code=>{
64
+ const index=this.queue.indexOf(job);
65
+ if(index<0)return;
66
+ this.queue.splice(index,1);
67
+ this.fullAdmission.withdraw(job.ticket);
68
+ this.#clearWait(job);
69
+ reject(queueError(code));
70
+ this.#drain();
71
+ };
72
+ job.abort=()=>cancel("full_cancelled_before_start");
73
+ job.timer=setTimeout(()=>cancel("queue_timeout"),
74
+ boundedInteger(options.queueTimeoutMs,this.queueTimeoutMs,100,this.queueTimeoutMs));
75
+ job.signal?.addEventListener("abort",job.abort,{once:true});
76
+ this.queue.push(job);
77
+ this.#drain();
78
+ });
79
+ }
80
+
81
+ wake(){if(this.fullAdmission)this.#drain();}
82
+
83
+ #clearWait(job){
84
+ if(job.timer)clearTimeout(job.timer);
85
+ if(job.abort)job.signal?.removeEventListener("abort",job.abort);
86
+ }
87
+
48
88
  snapshot() {
49
89
  return {
50
90
  concurrency: this.concurrency,
@@ -57,6 +97,7 @@ export class BoundedLane {
57
97
 
58
98
  #start(job) {
59
99
  if (job.timer) clearTimeout(job.timer);
100
+ if (job.abort) job.signal?.removeEventListener("abort",job.abort);
60
101
  this.active += 1;
61
102
  const queueWaitMs = Math.max(0, Date.now() - job.enqueuedAt);
62
103
  const metadata = {
@@ -65,18 +106,41 @@ export class BoundedLane {
65
106
  queueDepthAtStart: this.queue.length,
66
107
  activeAtStart: this.active,
67
108
  };
109
+ if(job.lease){
110
+ Promise.resolve()
111
+ .then(()=>{if(job.signal?.aborted)throw queueError("full_cancelled_before_start");return job.work(metadata,job.lease);})
112
+ .then(value=>{job.lease.finishRequest(false);job.resolve(value);},
113
+ error=>{job.lease.finishRequest(true);job.reject(error);})
114
+ .finally(()=>{this.active-=1;this.#drain();this.fullAdmission.changed();});
115
+ return;
116
+ }
68
117
  Promise.resolve()
69
118
  .then(() => job.work(metadata))
70
119
  .then(job.resolve, job.reject)
71
120
  .finally(() => {
72
121
  this.active -= 1;
73
122
  this.#drain();
123
+ this.fullAdmission?.changed();
74
124
  });
75
125
  }
76
126
 
77
127
  #drain() {
78
- 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,15 +175,25 @@ 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) {
116
193
  const value = String(action || "unknown");
117
194
  if (value.startsWith("fs.")) return this.lanes.get("filesystem");
118
195
  if (value.startsWith("process.")) return this.lanes.get("process");
119
- if (value === "terminal.exec") return this.lanes.get("terminalExec");
196
+ if (value === "terminal.exec" || value === "terminal.exec.compact") return this.lanes.get("terminalExec");
120
197
  if (value === "terminal.read.wait") return this.lanes.get("terminalWait");
121
198
  if (value.startsWith("terminal.")) return this.lanes.get("terminalControl");
122
199
  if (["desktop.screenshot", "desktop.clipboard.read", "desktop.window.list"].includes(value)) {