@anusornneal/chat-relay 2.0.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,SESSION_IDLE_MS,SESSION_HIDE_MS} from "./monitor-activity.mjs";
3
3
  import {createReadStream} from "node:fs";
4
4
  import path from "node:path";
5
5
  import {spawn} from "node:child_process";
@@ -16,6 +16,8 @@ const require=(ok,code)=>{if(!ok)throw new FullContractError(code);};
16
16
  const text=(v,n=512)=>typeof v==="string"?v.slice(0,n).toWellFormed():"";
17
17
  import {redactPresentationText} from "./presentation-redaction.mjs";
18
18
  export {redactPresentationText};
19
+ const recordedJobPrefix="recorded-";
20
+ const recordedChange=/^recorded:(monitor-[0-9]+):([0-9]|1[0-9])$/;
19
21
  const jobView=job=>job?{jobId:job.jobId,state:job.state,exitCode:job.exitCode??null,signal:job.signal??null}:null;
20
22
  const safeSession=s=>({taskSessionId:s.taskSessionId,title:redactPresentationText(s.title,200),project:redactPresentationText(s.projectKey,200),status:s.status,revision:s.revision,
21
23
  createdAt:text(s.createdAt,40),updatedAt:text(s.updatedAt,40),activity:[],changes:[]});
@@ -57,12 +59,14 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
57
59
  require(result?.ok===true,result?.error??"full_presentation_failed");
58
60
  return result.result;
59
61
  }
62
+ const localTerminal=localMonitor&&allowTerminal&&localScopes.includes("terminal")&&typeof monitorDetails==="function";
63
+ const localChanges=localMonitor&&typeof monitorDetails==="function";
60
64
  function commandAvailability(){
61
- const terminal=allowTerminal&&currentScopes.includes("terminal");
65
+ const terminal=localTerminal||allowTerminal&&currentScopes.includes("terminal");
62
66
  return {
63
67
  "job.output":{available:terminal,reason:terminal?null:"Local terminal permission unavailable"},
64
- "changes.list":{available:viewScopes().includes("read")&&typeof readChanges==="function",reason:typeof readChanges==="function"?null:"Changes are unavailable in this runtime"},
65
- "changes.diff":{available:viewScopes().includes("read")&&typeof readChanges==="function",reason:typeof readChanges==="function"?null:"Changes are unavailable in this runtime"},
68
+ "changes.list":{available:viewScopes().includes("read")&&(localChanges||typeof readChanges==="function"),reason:localChanges||typeof readChanges==="function"?null:"Changes are unavailable in this runtime"},
69
+ "changes.diff":{available:viewScopes().includes("read")&&(localChanges||typeof readChanges==="function"),reason:localChanges||typeof readChanges==="function"?null:"Changes are unavailable in this runtime"},
66
70
  ...(typeof monitorDetails==="function"?{"activity.detail":{available:viewScopes().includes("read")},"activity.diff":{available:viewScopes().includes("read")}}:{}),
67
71
  "agent.quit":{available:typeof requestQuit==="function",reason:typeof requestQuit==="function"?null:"Local agent lifecycle unavailable"}
68
72
  };
@@ -87,18 +91,50 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
87
91
  if(owner?.accountId!==principal.accountId||owner.agentId!==principal.agentId||!id(owner.taskSessionId))return false;
88
92
  activities.delete(owner.taskSessionId);lastObservedJobs.delete(owner.taskSessionId);return true;
89
93
  }
94
+ function recordedRows(taskSessionId,raw=monitorSnapshot()){
95
+ return (Array.isArray(raw?.activity)?raw.activity:[]).filter(row=>row.taskSessionId===taskSessionId&&/^monitor-[0-9]+$/.test(row.requestId)).slice(-MAX_MONITOR_ROWS).reverse();
96
+ }
97
+ function recordedFiles(taskSessionId){
98
+ const files=[];let truncated=false,used=0;
99
+ for(const row of recordedRows(taskSessionId)){
100
+ if(!row.hasDetails||!["fs.edit","fs.editMany","fs.write","fs.delete","full.workspace.edit"].includes(row.action))continue;
101
+ const detail=monitorDetails(row.requestId);
102
+ if(detail?.omitted)truncated=true;
103
+ for(const file of detail?.files??[]){
104
+ if(file.outcome!=="completed"||file.kind==="read")continue;
105
+ const entry={path:"recorded:"+row.requestId+":"+file.fileId,displayPath:file.path,status:file.kind,kind:file.kind,sourceTime:row.time,additions:file.additions,deletions:file.deletions,diffAvailable:file.diffAvailable===true};
106
+ const size=Buffer.byteLength(JSON.stringify(entry))+1;
107
+ if(files.length>=100||used+size>40000)return {taskSessionId,state:"ready",source:"recorded",files,truncated:true};
108
+ used+=size;files.push(entry);
109
+ }
110
+ }
111
+ return {taskSessionId,state:"ready",source:"recorded",files,truncated};
112
+ }
113
+ function recordedDiff(taskSessionId,relativePath){
114
+ const match=relativePath.match(recordedChange);
115
+ const row=match&&recordedRows(taskSessionId).find(row=>row.requestId===match[1]&&row.hasDetails);
116
+ const file=row&&monitorDetails(match[1])?.files?.find(file=>file.fileId===match[2]&&file.outcome==="completed"&&file.kind!=="read");
117
+ if(!file)return {taskSessionId,relativePath,state:"unavailable",reason:"Recorded change unavailable"};
118
+ const diff=monitorDetails(match[1],match[2]);
119
+ return {taskSessionId,relativePath,state:diff?.state??"unavailable",reason:diff?.reason,text:diff?.text??"",truncated:diff?.truncated===true};
120
+ }
90
121
  async function snapshot({consumerId,cursor,input={},signal}){
91
122
  require(exact(input,["selectedId","after"])&&(input.selectedId===undefined||input.selectedId===null||id(input.selectedId))&&(input.after===undefined||input.after===""||id(input.after)),"full_invalid_presentation_input");
92
123
  const rawMonitor=monitorSnapshot();
124
+ const {sessionPresence,...publicMonitor}=rawMonitor??{};
93
125
  // Local labels are bounded and redacted before crossing the presentation
94
126
  // boundary. On authority loss, retain counters but not task/project labels.
95
- const monitor=rawMonitor?{...rawMonitor,activity:(Array.isArray(rawMonitor.activity)?rawMonitor.activity:[]).slice(-40).map(row=>({
127
+ const monitor=rawMonitor?{...publicMonitor,activity:(Array.isArray(rawMonitor.activity)?rawMonitor.activity:[]).slice(-MAX_MONITOR_ROWS).map(row=>({
96
128
  requestId:id(row.requestId)?row.requestId:"",taskSessionId:id(row.taskSessionId)?row.taskSessionId:null,hasDetails:row.hasDetails===true,at:text(row.at,40),time:text(row.time,16),type:text(row.type,32),action:text(row.action,100),
97
129
  category:text(row.category,32),icon:text(row.icon,8),operation:redactPresentationText(row.operation,128),
98
130
  project:redactPresentationText(row.project,64),status:text(row.status,16),ok:typeof row.ok==="boolean"?row.ok:null,
99
131
  durationMs:Number.isFinite(row.durationMs)?Math.max(0,row.durationMs):null,elapsedMs:Number.isFinite(row.elapsedMs)?Math.max(0,row.elapsedMs):null,
100
132
  requestBytes:Number.isSafeInteger(row.requestBytes)&&row.requestBytes>=0?row.requestBytes:null,responseBytes:Number.isSafeInteger(row.responseBytes)&&row.responseBytes>=0?row.responseBytes:null,
101
- error:text(row.error,96),detail:redactPresentationText(row.detail,160),query:redactPresentationText(row.query,180),searchScope:redactPresentationText(row.searchScope,180)
133
+ error:text(row.error,96),detail:redactPresentationText(row.detail,160),query:redactPresentationText(row.query,180),searchScope:redactPresentationText(row.searchScope,180),
134
+ ...(localTerminal&&row.hasOutput===true?{hasOutput:true}:{}),
135
+ ...(Number.isSafeInteger(row.exitCode)?{exitCode:row.exitCode}:{}),
136
+ ...(typeof row.pollKey==="string"&&/^[a-f0-9]{24}$/.test(row.pollKey)?{pollKey:row.pollKey}:{}),
137
+ ...(Number.isSafeInteger(row.additions)&&row.additions>=0&&Number.isSafeInteger(row.deletions)&&row.deletions>=0?{additions:row.additions,deletions:row.deletions}:{})
102
138
  }))}:null;
103
139
  try{require(!signal?.aborted,"full_cancelled_before_start");if(!localMonitor)await refreshAuthority(false,signal);}
104
140
  catch(error){
@@ -109,9 +145,33 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
109
145
  sessions:[],detail:null,selectedUnavailable:false,next:null,partial:false,
110
146
  sessionAccess:"unavailable",monitor:{...monitor,activity:[]},commands:{"job.output":{available:false,reason:"Session access unavailable"},"changes.list":{available:false,reason:"Session access unavailable"},"changes.diff":{available:false,reason:"Session access unavailable"},"agent.quit":commandAvailability()["agent.quit"]},terminalEnabled:false};
111
147
  }
112
- const commands=commandAvailability(),terminal=allowTerminal&&currentScopes.includes("terminal");
113
- const listed=await call("full.session.list",{after:input.after??"",limit:32},signal,true);
114
- const sessions=listed.items.map(safeSession);
148
+ const commands=commandAvailability(),terminal=commands["job.output"].available;
149
+ const liveById=new Map();
150
+ if(Array.isArray(sessionPresence)){
151
+ for(const entry of sessionPresence.slice(0,127))if(id(entry.taskSessionId)&&Number.isFinite(entry.ageMs))liveById.set(entry.taskSessionId,entry);
152
+ }else{
153
+ // Compatibility with older monitor providers and presentation fixtures.
154
+ const current=Date.now();
155
+ for(const row of monitor?.activity??[]){
156
+ if(!id(row.taskSessionId))continue;
157
+ const previous=liveById.get(row.taskSessionId),at=Date.parse(row.at)+(row.durationMs??0);
158
+ liveById.set(row.taskSessionId,{ageMs:Number.isFinite(at)?Math.max(0,current-at):0,time:row.time,project:row.project||previous?.project,working:previous?.working||row.status==="running",failed:row.ok===false});
159
+ }
160
+ }
161
+ const visibleIds=[...liveById].filter(([,entry])=>entry.working||entry.ageMs<SESSION_HIDE_MS).map(([key])=>key);
162
+ if(input.selectedId&&!visibleIds.includes(input.selectedId))visibleIds.push(input.selectedId);
163
+ const listed=await call("full.session.list",{after:input.after??"",limit:32,...(localMonitor?{monitorSessionIds:visibleIds.slice(0,128)}:{})},signal,true);
164
+ function withPresence(source){
165
+ const session=safeSession(source),entry=liveById.get(session.taskSessionId);
166
+ if(!session.project&&entry?.project)session.project=redactPresentationText(entry.project,64);
167
+ session.lastActivityTime=text(entry?.time,16);
168
+ const age=entry?.ageMs??Infinity;
169
+ session.liveStatus=entry?.working?"working":age<SESSION_IDLE_MS?(entry.failed?"issue":"active"):entry?"idle":"unobserved";
170
+ if(!entry?.working&&age<SESSION_IDLE_MS)session.activeForMs=Math.max(1,Math.ceil(SESSION_IDLE_MS-age));
171
+ if(source.automatic===true&&!entry?.working)session.visibleForMs=Math.max(0,Math.ceil(SESSION_HIDE_MS-age));
172
+ return session;
173
+ }
174
+ const sessions=listed.items.map(withPresence).filter(session=>session.visibleForMs!==0||session.taskSessionId===input.selectedId);
115
175
  let detail=null,selectedUnavailable=false;
116
176
  if(input.selectedId){
117
177
  let source;
@@ -126,29 +186,33 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
126
186
  }
127
187
  if(source){
128
188
  const facts=source.session.facts??{},rawJobs=source.jobs??[],jobs=rawJobs.map(jobView);
189
+ const observed=recordedRows(input.selectedId,rawMonitor);
190
+ const recordedJobs=localTerminal?observed.filter(row=>row.hasOutput===true).slice(0,24).map(row=>({jobId:recordedJobPrefix+row.requestId,state:"recorded",label:redactPresentationText(row.operation,100),time:text(row.time,16),exitCode:Number.isSafeInteger(row.exitCode)?row.exitCode:null})):[];
191
+ const evidenceIds=new Set();
192
+ const recordedEvidence=observed.filter(row=>{if(!Number.isSafeInteger(row.exitCode))return false;const key=row.pollKey||row.requestId;if(evidenceIds.has(key))return false;evidenceIds.add(key);return true;}).slice(0,16).map(row=>({evidenceId:"exit-"+row.requestId,checkId:redactPresentationText(row.operation,128),kind:"Command exit",outcome:row.exitCode===0?"completed":"failed",exitCode:row.exitCode,observedAt:text(row.at,40)}));
129
193
  // Prefer unresolved work, otherwise retain the last job observed in
130
194
  // this monitor. UUID sorting is not a reliable chronological order.
131
195
  const currentJob=rawJobs.find(j=>!jobIsSettled(j))??rawJobs.find(j=>j.jobId===lastObservedJobs.get(input.selectedId))??rawJobs[0];
132
196
  lastObservedJobs.delete(input.selectedId);
133
197
  if(currentJob)lastObservedJobs.set(input.selectedId,currentJob.jobId);
134
198
  while(lastObservedJobs.size>32)lastObservedJobs.delete(lastObservedJobs.keys().next().value);
135
- 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
- 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(-32),
199
+ detail={...withPresence(source.session),workspace:source.workspace?{workspaceId:source.workspace.workspaceId,kind:source.workspace.workspaceKind,mode:source.workspace.mode,state:source.workspace.state,label:redactPresentationText(source.workspace.branch,200)}:null,
200
+ job:jobView(currentJob)??recordedJobs[0]??null,jobs:[...jobs,...recordedJobs].slice(0,24),
201
+ activity:(monitor?.activity?.some(row=>row.taskSessionId===input.selectedId)?monitor.activity.filter(row=>row.taskSessionId===input.selectedId):(activities.get(input.selectedId)??[])).slice(-MAX_MONITOR_ROWS),
138
202
  changes:(facts.changedFiles??[]).slice(0,100).map(p=>redactPresentationText(p,512)),
139
- evidence:(facts.evidence??[]).slice(-16).map(e=>({evidenceId:e.evidenceId,checkId:e.checkId,kind:e.kind,outcome:e.outcome,observedAt:e.observedAt})),
203
+ evidence:[...(facts.evidence??[]).slice(-16).map(e=>({evidenceId:e.evidenceId,checkId:e.checkId,kind:e.kind,outcome:e.outcome,observedAt:e.observedAt})),...recordedEvidence].slice(0,16),
140
204
  blockers:(facts.blockers??[]).slice(0,8).map(p=>redactPresentationText(p,512)),
141
205
  summary:redactPresentationText(facts.summary,1000),indexState:"not-assessed",
142
206
  detailPartial:source.historyOmitted>0||source.jobSummary?.omitted>0||source.claimSummary?.omitted>0||(facts.changedFiles?.length??0)>100||(facts.evidence?.length??0)>16,
143
207
  historyGap:source.gap===true};
144
208
  }
145
209
  }
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 32 local requests per selected session; older activity may be unavailable"};
210
+ 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
211
  // Bound encoded UTF-8, including long Thai titles and escaped text. Keep
148
212
  // durable identity/state, then trim optional detail with a visible gap.
149
213
  const bytes=()=>Buffer.byteLength(JSON.stringify(view));
150
214
  for(const key of ["activity","changes","evidence","blockers"]){
151
- while(bytes()>56000&&detail?.[key]?.length){detail[key].pop();detail.detailPartial=true;}
215
+ while(bytes()>56000&&detail?.[key]?.length){if(key==="activity")detail[key].shift();else detail[key].pop();detail.detailPartial=true;}
152
216
  }
153
217
  while(bytes()>56000&&monitor?.activity?.length){monitor.activity.shift();view.partial=true;}
154
218
  while(bytes()>56000&&sessions.length>1){sessions.pop();view.next=sessions.at(-1).taskSessionId;view.partial=true;}
@@ -162,7 +226,8 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
162
226
  // The private local presentation endpoint is authenticated. Quit is local lifecycle control, not remote task authority.
163
227
  requestQuit();return {acknowledged:true};
164
228
  }
165
- const localRead=localMonitor&&["activity.detail","activity.diff","changes.list","changes.diff"].includes(action);
229
+ const recordedOutput=action==="job.output"&&typeof input.jobId==="string"&&input.jobId.startsWith(recordedJobPrefix);
230
+ const localRead=localMonitor&&(["activity.detail","activity.diff","changes.list","changes.diff"].includes(action)||recordedOutput);
166
231
  require(!signal?.aborted,"full_cancelled_before_start");
167
232
  if(!localRead)await refreshAuthority(true,signal);
168
233
  const commands=commandAvailability();
@@ -173,7 +238,9 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
173
238
  require(typeof monitorDetails==="function","full_invalid_presentation_input");
174
239
  const value=monitorDetails(input.activityId,input.fileId);
175
240
  require(value?.activityId===input.activityId&&Buffer.byteLength(JSON.stringify(value))<=48000,"full_invalid_presentation_result");
176
- return value;
241
+ // Terminal previews are served only by the scoped terminal-output route.
242
+ const {terminal:privateOutput,...view}=value;
243
+ return view;
177
244
  }
178
245
  if(action==="changes.list"||action==="changes.diff"){
179
246
  require(exact(input,action==="changes.list"?["taskSessionId"]:["taskSessionId","relativePath"])&&id(input.taskSessionId)&&
@@ -181,7 +248,13 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
181
248
  const expectedAuthority=authorityVersion;
182
249
  try{
183
250
  const invocation=permitted("full.session.snapshot",{taskSessionId:input.taskSessionId,consumerId:"presentation-changes"},true);
184
- const result=await readChanges(invocation,input,signal,redactPresentationText);
251
+ // A recorded identifier is never interpreted as a filesystem path.
252
+ if(localChanges&&action==="changes.diff"&&input.relativePath.startsWith("recorded:"))return recordedDiff(input.taskSessionId,input.relativePath);
253
+ const result=typeof readChanges==="function"?await readChanges(invocation,input,signal,redactPresentationText):{taskSessionId:input.taskSessionId,state:"unavailable",reason:"This session has no ready Git workspace."};
254
+ if(localChanges&&action==="changes.list"&&result?.taskSessionId===input.taskSessionId&&result?.state==="unavailable"&&result.reason==="This session has no ready Git workspace."){
255
+ require(!signal?.aborted,"full_cancelled_before_start");
256
+ return recordedFiles(input.taskSessionId);
257
+ }
185
258
  require(!signal?.aborted,"full_cancelled_before_start");
186
259
  require(localRead?localScopes.includes("read"):expectedAuthority===authorityVersion&&currentScopes.includes("read"),"full_presentation_permission_denied");
187
260
  require(result?.taskSessionId===input.taskSessionId&&Buffer.byteLength(JSON.stringify(result))<=48000,"full_invalid_presentation_result");
@@ -192,6 +265,13 @@ export function createDesktopService({principal,dispatch,allowTerminal=false,aut
192
265
  }
193
266
  }
194
267
  require(action==="job.output"&&exact(input,["taskSessionId","jobId","afterSeq"]),"full_invalid_presentation_input");
268
+ if(recordedOutput){
269
+ require(localTerminal&&id(input.taskSessionId)&&/^recorded-monitor-[0-9]+$/.test(input.jobId)&&(input.afterSeq===undefined||Number.isSafeInteger(input.afterSeq)&&input.afterSeq>=0),"full_invalid_presentation_input");
270
+ const activityId=input.jobId.slice(recordedJobPrefix.length),row=recordedRows(input.taskSessionId).find(row=>row.requestId===activityId&&row.hasOutput===true);
271
+ const output=row&&monitorDetails(activityId)?.terminal;
272
+ if(!output)return {outputAvailable:false,text:"",nextSeq:0,hasMore:false};
273
+ return {outputAvailable:true,text:(input.afterSeq??0)>0?"":output.text,nextSeq:1,hasMore:false,truncated:output.partial,source:"recorded"};
274
+ }
195
275
  const result=await call("full.job.read",input,signal);
196
276
  // Chunks are joined before redaction so common credentials split across
197
277
  // adjacent chunks are still recognized. Never retain output in the broker.
@@ -232,7 +312,7 @@ export async function createFullDesktopBroker({host,artifact,sessionDirectory,pr
232
312
  const environmentKeys=new Set(["path","systemroot","windir","home","userprofile","temp","tmp","tmpdir","appdata","localappdata","lang","lc_all","display","wayland_display","xdg_runtime_dir","dbus_session_bus_address"]);
233
313
  const environment=Object.fromEntries(Object.entries(process.env).filter(([key])=>environmentKeys.has(key.toLowerCase())));
234
314
  const {endpoint,token}=presentation.bootstrap;
235
- async function open({accountId}={}){
315
+ async function open({accountId,initial=false}={}){
236
316
  require(accountId===boundAccountId,"full_presentation_permission_denied");
237
317
  require(!closed&&host.available,"full_unavailable");
238
318
  if(opening)return opening;
@@ -245,7 +325,7 @@ export async function createFullDesktopBroker({host,artifact,sessionDirectory,pr
245
325
  if(alive(child)){presentation.publish({type:"activity.progress",requestId:randomUUID(),at:new Date().toISOString(),action:"presentation.open"});return {alreadyOpen:true};}
246
326
  require(await binaryDigest(signal)===initialDigest,"full_invalid_gui_artifact");check();
247
327
  state="starting";exitResult=null;
248
- try{launched=spawn(binary,[],{windowsHide:false,stdio:"ignore",env:{...environment,RELAY_FULL_PRESENTATION_ENDPOINT:endpoint,RELAY_FULL_PRESENTATION_TOKEN:token,RELAY_FULL_PRESENTATION_EPOCH:host.ownerEpoch,RELAY_FULL_PRESENTATION_STATE:path.join(sessionDirectory,"gui-selection.json"),WEBVIEW2_USER_DATA_FOLDER:path.join(sessionDirectory,"webview")}});}
328
+ try{launched=spawn(binary,[],{windowsHide:false,stdio:"ignore",env:{...environment,...(initial&&process.env.CHAT_RELAY_START_IN_TRAY==="1"?{RELAY_FULL_PRESENTATION_START_IN_TRAY:"1"}:{}),RELAY_FULL_PRESENTATION_ENDPOINT:endpoint,RELAY_FULL_PRESENTATION_TOKEN:token,RELAY_FULL_PRESENTATION_EPOCH:host.ownerEpoch,RELAY_FULL_PRESENTATION_STATE:path.join(sessionDirectory,"gui-selection.json"),WEBVIEW2_USER_DATA_FOLDER:path.join(sessionDirectory,"webview")}});}
249
329
  catch{state="unavailable";throw new FullContractError("full_gui_launch_failed");}
250
330
  const current=launched;child=current;
251
331
  current.once("exit",(code,signal)=>{if(child===current){state="closed";exitResult={code,signal};}});
@@ -297,7 +377,7 @@ export async function createFullDesktopBroker({host,artifact,sessionDirectory,pr
297
377
  })();
298
378
  return closing;
299
379
  }
300
- try{await open({accountId:boundAccountId});}
380
+ try{await open({accountId:boundAccountId,initial:true});}
301
381
  catch(error){await close();throw error;}
302
382
  return Object.freeze({
303
383
  get status(){return {state,pid:child?.pid??null,exit:exitResult,scopeId:service.scopeId};},
@@ -52,7 +52,7 @@ export async function createRemoteDiagnostics({host,artifact,scheduler}){
52
52
  function completed(parsed,response,start,metadata={}){
53
53
  if(REMOTE_DIAGNOSTICS_OPERATIONS.includes(parsed.operation)||parsed.operation==="full.session.delete")return;
54
54
  const observedStart=performance.now();
55
- const taskSessionId=parsed.input.taskSessionId??response.result?.session?.taskSessionId;
55
+ const taskSessionId=parsed.input.taskSessionId??response.result?.session?.taskSessionId??(parsed.operation==="full.coding.prepare"?response.result?.taskSessionId:undefined);
56
56
  if(!taskSessionId)return;
57
57
  // A successful host/broker operation authorizes this task. Denied attempts
58
58
  // may only enter an already authorized own-task ring, never seed one from
@@ -1,5 +1,6 @@
1
1
  import {fullUnavailable,FullContractError} from "../packages/full-contracts/index.mjs";
2
- import {parseAuthorizedFullInvocation,REMOTE_SESSION_OPERATIONS,REMOTE_SESSION_LIFECYCLE_OPERATIONS,REMOTE_WORKSPACE_OPERATIONS,REMOTE_INTELLIGENCE_OPERATIONS,REMOTE_JOB_OPERATIONS,WORKSPACE_BROKER_OPERATIONS,REMOTE_FULL_CAPABILITIES,DIAGNOSTICS_OPERATION,REMOTE_DIAGNOSTICS_OPERATIONS,REMOTE_DESKTOP_OPERATIONS} from "../packages/full-contracts/remote-session.mjs";
2
+ import {parseAuthorizedFullInvocation,REMOTE_SESSION_OPERATIONS,REMOTE_SESSION_LIFECYCLE_OPERATIONS,REMOTE_WORKSPACE_OPERATIONS,REMOTE_INTELLIGENCE_OPERATIONS,REMOTE_JOB_OPERATIONS,WORKSPACE_BROKER_OPERATIONS,REMOTE_FULL_CAPABILITIES,DIAGNOSTICS_OPERATION,REMOTE_DIAGNOSTICS_OPERATIONS,REMOTE_DESKTOP_OPERATIONS,CODING_PREPARE_OPERATION} from "../packages/full-contracts/remote-session.mjs";
3
+ import {prepareCodingTask} from "./full-coding-prepare.mjs";
3
4
  import path from "node:path";
4
5
  import {performance} from "node:perf_hooks";
5
6
 
@@ -96,7 +97,13 @@ export async function startRemoteFull({bootstrap,agentId,onUnavailable,workspace
96
97
  // deletion rejects busy tasks and fences new calls for this exact owner.
97
98
  leaveTask=enterTask(parsed);
98
99
  let response;
99
- if(parsed.operation==="full.session.delete"){
100
+ if(parsed.operation===CODING_PREPARE_OPERATION){
101
+ require(workspace?.capabilities.includes(CODING_PREPARE_OPERATION),"full_capability_unavailable");
102
+ require(parsed.input.taskContext.detail===undefined||workspace.capabilities.includes("full.intelligence.task-context.expand"),"full_capability_unavailable");
103
+ // Compose locally: child dispatches retain their own authority, task
104
+ // ownership and resource admission. Never replay a failed write.
105
+ result=await prepareCodingTask(parsed,dispatch);
106
+ }else if(parsed.operation==="full.session.delete"){
100
107
  const owner={accountId:parsed.principal.accountId,agentId:parsed.principal.agentId,taskSessionId:parsed.input.taskSessionId};
101
108
  const admission=workspaceBroker?.scheduler?.fullAdmission;
102
109
  require(!admission||admission.snapshot({owner}).claims.length===0,"full_session_busy");
@@ -122,7 +129,7 @@ export async function startRemoteFull({bootstrap,agentId,onUnavailable,workspace
122
129
  require(workspace,"full_capability_unavailable");
123
130
  response=await workspace.dispatch(payload,parsed);
124
131
  }else response=await host.request(parsed.operation,payload,{taskSessionId:parsed.input.taskSessionId,timeoutMs:15000});
125
- result={ok:true,result:response};
132
+ if(!result)result={ok:true,result:response};
126
133
  }catch(error){result={ok:false,error:typeof error?.code==="string"&&/^full_[a-z0-9_]+$/.test(error.code)?error.code:"full_operation_failed"};}
127
134
  finally{pending--;}
128
135
  if(parsed&&parsed.operation!=="full.session.delete"){
@@ -286,5 +286,5 @@ export async function createRemoteWorkspaceBroker({host,artifact,git,roots,sched
286
286
  scopedWriteStarts++;
287
287
  try{return await dispatchOperation(invocation,parsed);}finally{scopedWriteStarts--;}
288
288
  }
289
- return Object.freeze({dispatch,presentationChanges:host.operations.includes(PRESENTATION_WORKSPACE_OPERATION)?presentationChanges:null,assertSessionIdle:owner=>jobs?.assertSessionIdle(owner),forgetSession:owner=>jobs?.forgetSession(owner),close:()=>jobs?.close()??true,blocksLegacyEffects:()=>scheduler.fullAdmission.recoveryBlocked||scopedWriteStarts>0||!!jobs?.blocksLegacyEffects(),capabilities:["full.workspace.readonly",...(readBatchEnabled?["full.workspace.read-batch"]:[]),...(isolation?["full.workspace.isolated"]:[]),...(artifacts?["full.workspace.artifacts"]:[]),...(scopedEdits?["full.workspace.edit"]:[]),...(intelligence?["full.intelligence",...(intelligenceBatch?["full.intelligence.batch"]:[]),...(taskContext?["full.intelligence.task-context",...(taskContextExpand?["full.intelligence.task-context.expand"]:[])]:[])]:[]),...(verification?["full.verification"]:[]),...(jobs?["full.jobs",...(jobs.recoveryEnabled?["full.jobs.recovery"]:[]),...(jobs.waitEnabled?["full.jobs.wait"]:[])]:[])]});
289
+ return Object.freeze({dispatch,presentationChanges:host.operations.includes(PRESENTATION_WORKSPACE_OPERATION)?presentationChanges:null,assertSessionIdle:owner=>jobs?.assertSessionIdle(owner),forgetSession:owner=>jobs?.forgetSession(owner),close:()=>jobs?.close()??true,blocksLegacyEffects:()=>scheduler.fullAdmission.recoveryBlocked||scopedWriteStarts>0||!!jobs?.blocksLegacyEffects(),capabilities:["full.workspace.readonly",...(readBatchEnabled?["full.workspace.read-batch"]:[]),...(isolation?["full.workspace.isolated"]:[]),...(artifacts?["full.workspace.artifacts"]:[]),...(scopedEdits?["full.workspace.edit"]:[]),...(intelligence?["full.intelligence",...(intelligenceBatch?["full.intelligence.batch"]:[]),...(taskContext?["full.intelligence.task-context",...(sharedGit?["full.coding.prepare"]:[]),...(taskContextExpand?["full.intelligence.task-context.expand"]:[])]:[])]:[]),...(verification?["full.verification"]:[]),...(jobs?["full.jobs",...(jobs.recoveryEnabled?["full.jobs.recovery"]:[]),...(jobs.waitEnabled?["full.jobs.wait"]:[])]:[])]});
290
290
  }
@@ -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 selected=mode==="main"?first:entries.find(x=>sharedPath&&comparablePath(x.path,this.platform)===comparablePath(sharedPath,this.platform));
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);
@@ -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,
@@ -20,7 +22,7 @@ import {
20
22
  } from "./lifecycle.mjs";
21
23
  import { humanizeToolCall } from "./toolcall-summary.mjs";
22
24
  import { describeToolActivity } from "./toolcall-context.mjs";
23
- import { createMonitorActivity, describeFullMonitorActivity } from "./monitor-activity.mjs";
25
+ import { createMonitorActivity, describeFullMonitorActivity, observedTerminalResult } from "./monitor-activity.mjs";
24
26
  import {captureActivityFor,runActivityCapture,finishActivityCapture,describeLocalSearch} from "./activity-capture.mjs";
25
27
  import { toolErrorGuidance } from "./tool-error-guidance.mjs";
26
28
  import {
@@ -47,7 +49,9 @@ const fullEvents = process.env.CHAT_RELAY_FULL_EVENTS === "1" && typeof process.
47
49
 
48
50
  const monitorEnabled=fullBootstrap?.headless===false;
49
51
  const monitorAccountId=monitorEnabled?fullBootstrap.localPrincipal?.accountId:null;
52
+ const monitorTerminalEnabled=monitorEnabled&&fullBootstrap.localPrincipal?.scopes?.includes("terminal")===true;
50
53
  const monitorActivity=monitorEnabled?createMonitorActivity():null;
54
+ const automaticSessions=fullBootstrap?createAutomaticSessionBinding({agentId,available:()=>!stopping&&!reauthorizationRequired&&fullRuntime?.available===true,dispatch:invocation=>fullRuntime.dispatch(invocation)}):null;
51
55
  function monitorSnapshot(){
52
56
  const connection=connectionState.snapshot();
53
57
  let relayHost="";try{relayHost=new URL(relayUrl).host.slice(0,200);}catch{}
@@ -579,7 +583,12 @@ function connect() {
579
583
  if (message?.control === "learn_activity") {
580
584
  const activity = message.activity && typeof message.activity === "object" ? message.activity : null;
581
585
  const change = message.change && typeof message.change === "object" ? message.change : null;
586
+ if(monitorEnabled&&activity?.accountId&&activity.accountId!==monitorAccountId)return;
587
+ const learnContext=monitorEnabled&&activity?.accountId===monitorAccountId&&activity.activityId?{accountId:activity.accountId,activityId:activity.activityId}:null;
588
+ const learnSessionId=learnContext?automaticSessions?.lookup(learnContext):null;
582
589
  emitUi("learn", {
590
+ ...(learnContext?{monitorConversationId:learnContext.activityId}:{}),
591
+ ...(learnSessionId?{monitorTaskSessionId:learnSessionId}:{}),
583
592
  ...(activity ? { activity } : {}),
584
593
  ...(change ? { change } : {}),
585
594
  });
@@ -604,11 +613,27 @@ function connect() {
604
613
  const uiActivity = describeToolActivity(message.payload, files.getRoots(), recentToolProjects);
605
614
  const requestBytes = Buffer.byteLength(JSON.stringify(message), "utf8");
606
615
  const ownedFull=action==="full.invoke"&&monitorAccountId&&message.payload?.principal?.accountId===monitorAccountId&&message.payload?.principal?.agentId===agentId;
616
+ const autoContext=automaticSessions&&action!=="full.invoke"&&message.autoSession&&(!monitorEnabled||message.autoSession.accountId===monitorAccountId)?message.autoSession:null;
617
+ const autoSessionId=autoContext?automaticSessions.lookup(autoContext):null;
618
+ const pollTarget=ownedFull&&message.payload.operation==="full.job.read"?message.payload.input?.jobId:action==="terminal.read"||action==="terminal.read.compact"?message.payload.sessionId:null;
619
+ const pollOwner=ownedFull?[message.payload.principal.accountId,message.payload.input?.taskSessionId]:autoContext?[autoContext.accountId,autoContext.activityId]:null;
620
+ 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
621
  const capture=monitorEnabled&&(action!=="full.invoke"||ownedFull)?captureActivityFor(message.payload):null;
608
622
  const captured=result=>{try{return finishActivityCapture(capture,message.payload,result);}catch{return null;}};
609
623
  emitUi("tool:start", { requestId: message.requestId, action, summary: callSummary, ...uiActivity, requestBytes,
624
+ ...(monitorPollKey?{monitorPollKey}:{}),
610
625
  ...(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}: {}) });
626
+ ...(ownedFull?{monitorAction:message.payload.operation,monitorOperation:describeFullMonitorActivity(message.payload.operation,message.payload.input),monitorTaskSessionId:message.payload.input?.taskSessionId}:autoSessionId?{monitorTaskSessionId:autoSessionId}:{}) });
627
+ // Automatic attribution never changes the legacy command, its authority,
628
+ // or its workspace. One local ensure is shared by concurrent first calls.
629
+ if(autoContext&&!autoSessionId){
630
+ void automaticSessions.resolve(autoContext).then(id=>{
631
+ if(!id||!monitorActivity)return;
632
+ const callBound=monitorActivity.bindSession(message.requestId,id);
633
+ const learnBound=monitorActivity.bindConversation(autoContext.activityId,id);
634
+ if(callBound||learnBound)fullRuntime?.monitorChanged();
635
+ }).catch(()=>{});
636
+ }
612
637
  fullEvents?.publish("tool.accepted", message.requestId, action, message.payload?.observability);
613
638
  let scheduleMeta = { lane: "unknown", queueWaitMs: 0, queueDepthAtStart: 0, activeAtStart: 0 };
614
639
  let handlerDurationMs = 0;
@@ -656,8 +681,18 @@ function connect() {
656
681
  };
657
682
  const responseBytes = Buffer.byteLength(serializeResponse(message.requestId, result, responseMeta), "utf8");
658
683
  try { usage.record({ ...recentEntry, requestBytes, responseBytes }, message.payload, result); } catch {}
659
- const activityDetails=captured(result);
660
- const partialFailure=activityDetails?.files.some(file=>file.outcome==="failed")||ownedFull&&result?.result?.ok===false;
684
+ let activityDetails=captured(result);
685
+ if(monitorTerminalEnabled&&autoContext?.accountId===monitorAccountId){
686
+ const terminal=observedTerminalResult(action,result);
687
+ if(terminal)activityDetails={...(activityDetails??{files:[],omitted:0}),terminal};
688
+ }
689
+ if(ownedFull&&message.payload.operation==="full.coding.prepare"&&result?.result?.taskSessionId){
690
+ monitorActivity?.bindSession(message.requestId,result.result.taskSessionId);
691
+ }
692
+ if(ownedFull&&message.payload.operation==="full.session.ensure"&&result?.ok===true&&result.result?.session?.taskSessionId){
693
+ monitorActivity?.bindSession(message.requestId,result.result.session.taskSessionId);
694
+ }
695
+ const partialFailure=activityDetails?.files?.some(file=>file.outcome==="failed")||ownedFull&&result?.result?.ok===false;
661
696
  emitUi("tool:end", {
662
697
  requestId: message.requestId,
663
698
  action,
@@ -667,7 +702,10 @@ function connect() {
667
702
  responseBytes,
668
703
  ...(result && typeof result === "object" && result.ok === false && result.error ? { error: String(result.error) } : partialFailure?{error:"partial_failure"}:{}),
669
704
  },activityDetails);
670
- if(ownedFull&&message.payload.operation==="full.session.delete"&&result?.ok===true&&result.result?.acknowledged===true)monitorActivity?.forgetSession(message.payload.input.taskSessionId);
705
+ if(action==="full.invoke"&&message.payload.operation==="full.session.delete"&&result?.ok===true&&result.result?.acknowledged===true){
706
+ automaticSessions?.forget(message.payload.principal.accountId,message.payload.input.taskSessionId);
707
+ if(ownedFull)monitorActivity?.forgetSession(message.payload.input.taskSessionId);
708
+ }
671
709
  fullEvents?.publish("tool.completed", message.requestId, action, message.payload?.observability, {
672
710
  ok: !(result && typeof result === "object" && result.ok === false), durationMs: Date.now() - startedAt,
673
711
  });
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { configDir } from "../cli/config.mjs";
5
+ import { REMOTE_FULL_OPERATIONS } from "../packages/full-contracts/remote-session.mjs";
5
6
 
6
7
  export const RECENT_CALL_CAPACITY = 1000;
7
8
  const RETENTION_DAYS = 30;
@@ -9,7 +10,9 @@ const DAY_MS = 86400000;
9
10
  const MAX_PAGE_BYTES = 48 * 1024;
10
11
  const MAX_FILE_BYTES = 1024 * 1024;
11
12
  const FLUSH_MS = 30_000;
13
+ const FULL_ACTIONS = new Set(REMOTE_FULL_OPERATIONS);
12
14
  const ACTIONS = new Set([
15
+ ...FULL_ACTIONS,
13
16
  "ping", "agent.config", "agent.recentCalls", "agent.usageStats",
14
17
  "agent.lifecycle.status", "agent.lifecycle.drain", "agent.lifecycle.resume",
15
18
  "agent.lifecycle.restart", "agent.lifecycle.upgrade",
@@ -138,6 +141,11 @@ export class LocalUsageHistory {
138
141
 
139
142
  record(entry, payload = {}, result = null) {
140
143
  const seq = this.nextSeq++;
144
+ // Count only allowlisted operations from executed Full invocations, not
145
+ // advertised capabilities, guidance, or arbitrary caller-provided names.
146
+ if (entry.action === "full.invoke" && payload?.action === "full.invoke" && FULL_ACTIONS.has(payload.operation)) {
147
+ entry = { ...entry, action: payload.operation };
148
+ }
141
149
  this.ring[(seq - 1) % RECENT_CALL_CAPACITY] = {
142
150
  ...entry, seq, action: String(entry.action || "other").slice(0, 100),
143
151
  summary: String(entry.summary || "").slice(0, 160),