@anusornneal/chat-relay 1.9.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.
- package/README.md +6 -0
- package/agent/activity-capture.mjs +165 -0
- package/agent/capability-scheduler.mjs +82 -5
- package/agent/file-manager.mjs +8 -3
- package/agent/full-bridge.mjs +53 -0
- package/agent/full-desktop-actions.mjs +124 -0
- package/agent/full-desktop-auth.mjs +53 -0
- package/agent/full-desktop-broker.mjs +308 -0
- package/agent/full-host.mjs +153 -0
- package/agent/full-job-broker.mjs +360 -0
- package/agent/full-native-job.mjs +205 -0
- package/agent/full-presentation-changes.mjs +191 -0
- package/agent/full-remote-diagnostics.mjs +129 -0
- package/agent/full-resources.mjs +343 -0
- package/agent/full-runtime-supervisor.mjs +67 -0
- package/agent/full-session-dispatch.mjs +167 -0
- package/agent/full-workspace-broker.mjs +290 -0
- package/agent/git-worktree-manager.mjs +170 -4
- package/agent/lifecycle.mjs +11 -0
- package/agent/local-agent.mjs +150 -24
- package/agent/local-usage.mjs +21 -0
- package/agent/monitor-activity.mjs +111 -0
- package/agent/presentation-redaction.mjs +10 -0
- package/agent/process-manager.mjs +32 -0
- package/agent/terminal-manager.mjs +189 -31
- package/agent/toolcall-context.mjs +23 -1
- package/agent/windows-desktop-runner.mjs +65 -61
- package/agent/windows-desktop-worker.ps1 +33 -18
- package/agent/windows-powershell.mjs +51 -0
- package/cli/full-background.mjs +69 -0
- package/cli/full-launch.mjs +94 -0
- package/cli/full-prepare-child.mjs +48 -0
- package/cli/full-prepare.mjs +171 -0
- package/cli/full-release-default.json +4 -0
- package/cli/full-release-files.mjs +36 -0
- package/cli/full-release-official.mjs +48 -0
- package/cli/full-release-source.mjs +37 -0
- package/cli/index.mjs +8 -4
- package/cli/mod-cache.mjs +170 -0
- package/cli/mod-loader.mjs +67 -0
- package/cli/mod-manifest.mjs +63 -0
- package/cli/remote.mjs +172 -17
- package/cli/runner-ownership.mjs +116 -3
- package/cli/self-update.mjs +1 -1
- package/cli/tui.mjs +2 -20
- package/package.json +5 -3
- package/packages/full-contracts/index.mjs +193 -0
- package/packages/full-contracts/native-job.mjs +13 -0
- package/packages/full-contracts/package.json +7 -0
- package/packages/full-contracts/remote-session.mjs +239 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import {constants} from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import {execFile} from "node:child_process";
|
|
5
|
+
import {promisify} from "node:util";
|
|
6
|
+
import {FullContractError} from "../packages/full-contracts/index.mjs";
|
|
7
|
+
|
|
8
|
+
const exec=promisify(execFile);
|
|
9
|
+
const MAX_FILES=100,MAX_GIT_BYTES=256*1024,MAX_FILE_BYTES=256*1024,MAX_DIFF_CHARS=12000,MAX_VIEW_BYTES=48000;
|
|
10
|
+
const ignoredDirectories=new Set([".git",".workspace",".relay-workspace-owner.json","node_modules",".gradle",".cache",".next","target","coverage"]);
|
|
11
|
+
const sensitive=/^(?:\.env(?:\.|$)|\.npmrc|\.pypirc|\.netrc|\.ssh|id_(?:rsa|ed25519|ecdsa)(?:\.|$)|(?:credentials?|secrets?|passwords?)(?:[._=-]|$))|\.(?:pem|key|p12|pfx|jks|keystore)$/i;
|
|
12
|
+
const require=(ok,code)=>{if(!ok)throw new FullContractError(code);};
|
|
13
|
+
const cancelled=signal=>require(!signal?.aborted,"full_cancelled_before_start");
|
|
14
|
+
const samePath=(a,b)=>process.platform==="win32"?a.toLowerCase()===b.toLowerCase():a===b;
|
|
15
|
+
const stamp=stat=>[stat.dev,stat.ino,stat.mode,stat.size,stat.mtimeNs,stat.ctimeNs].map(String).join(":");
|
|
16
|
+
const missing=error=>["ENOENT","ENOTDIR"].includes(error?.code);
|
|
17
|
+
|
|
18
|
+
/** A display policy, not an execution or general file-read API. */
|
|
19
|
+
export function presentationChangePath(relative){
|
|
20
|
+
if(typeof relative!=="string"||relative.length===0||relative.length>1024||relative.includes("\\")||/[\u0000-\u001f\u007f:]/.test(relative)||relative.startsWith("/"))return false;
|
|
21
|
+
return relative.split("/").every(part=>part&&part!=="."&&part!==".."&&!ignoredDirectories.has(part.toLowerCase())&&!sensitive.test(part)&&
|
|
22
|
+
!(process.platform==="win32"&&(/[. ]$/.test(part)||/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))));
|
|
23
|
+
}
|
|
24
|
+
function parseStatus(raw){
|
|
25
|
+
const parts=raw.split("\0"),files=[];
|
|
26
|
+
let omitted=0;
|
|
27
|
+
for(let index=0;index<parts.length;index++){
|
|
28
|
+
const record=parts[index];if(!record)continue;
|
|
29
|
+
const xy=record.slice(0,2),name=record.slice(3);
|
|
30
|
+
const rename=/[RC]/.test(xy),previousPath=rename?parts[++index]:undefined;
|
|
31
|
+
if(record[2]!==" "||!presentationChangePath(name)||rename&&!presentationChangePath(previousPath)){omitted++;continue;}
|
|
32
|
+
const conflicted=xy.includes("U")||xy==="AA"||xy==="DD";
|
|
33
|
+
const status=conflicted?"conflicted":xy==="??"?"untracked":rename?"renamed":xy.includes("D")?"deleted":xy.includes("A")?"added":xy.includes("T")?"type-changed":"modified";
|
|
34
|
+
files.push({path:name,status,...(previousPath?{previousPath}:{}),additions:null,deletions:null,binary:null});
|
|
35
|
+
}
|
|
36
|
+
return {files,omitted};
|
|
37
|
+
}
|
|
38
|
+
function parseNumstat(raw){
|
|
39
|
+
const records=raw.split("\0"),counts=new Map();
|
|
40
|
+
for(let index=0;index<records.length;index++){
|
|
41
|
+
const record=records[index];if(!record)continue;
|
|
42
|
+
const match=/^(\d+|-)\t(\d+|-)\t(.*)$/s.exec(record);if(!match)continue;
|
|
43
|
+
let name=match[3];
|
|
44
|
+
if(name===""){index++;name=records[++index];}
|
|
45
|
+
if(!presentationChangePath(name))continue;
|
|
46
|
+
const binary=match[1]==="-"||match[2]==="-";
|
|
47
|
+
counts.set(name,{additions:binary?null:Number(match[1]),deletions:binary?null:Number(match[2]),binary});
|
|
48
|
+
}
|
|
49
|
+
return counts;
|
|
50
|
+
}
|
|
51
|
+
function bounded(value){
|
|
52
|
+
while(Buffer.byteLength(JSON.stringify(value))>MAX_VIEW_BYTES&&value.files?.length){value.files.pop();value.truncated=true;}
|
|
53
|
+
require(Buffer.byteLength(JSON.stringify(value))<=MAX_VIEW_BYTES,"full_response_too_large");
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Called only inside the existing Core workspace read admission, after current
|
|
59
|
+
* principal/ownership/allowed-root checks. No path or Git revision comes from
|
|
60
|
+
* the renderer except one validated relative path. Git cannot run filters,
|
|
61
|
+
* external diffs, hooks, fsmonitor, a pager, or an inherited Git environment.
|
|
62
|
+
*/
|
|
63
|
+
export async function readPresentationChanges({root,taskSessionId,workspaceId,relativePath,checkTarget,signal,redact=value=>value}){
|
|
64
|
+
const observedAt=new Date().toISOString();
|
|
65
|
+
const base={taskSessionId,workspaceId,source:"git-working-tree",observedAt,readOnly:true};
|
|
66
|
+
const unavailable=(reason,truncated=false)=>({...base,...(relativePath!==undefined?{relativePath,text:"",additions:null,deletions:null,binary:false}:{files:[]}),state:"unavailable",reason,truncated});
|
|
67
|
+
cancelled(signal);
|
|
68
|
+
require(typeof root==="string"&&path.isAbsolute(root)&&typeof checkTarget==="function","full_unauthorized");
|
|
69
|
+
require(relativePath===undefined||presentationChangePath(relativePath),"full_invalid_presentation_input");
|
|
70
|
+
const canonical=await fs.realpath(root);
|
|
71
|
+
require(samePath(canonical,root)&&await checkTarget(canonical),"full_unauthorized");
|
|
72
|
+
const environment=Object.fromEntries(Object.entries(process.env).filter(([key])=>!/^GIT_/i.test(key)));
|
|
73
|
+
const git=async(args,{allowMissingHead=false}={})=>{
|
|
74
|
+
cancelled(signal);
|
|
75
|
+
try{
|
|
76
|
+
const result=await exec("git",["--no-pager","--no-optional-locks","--literal-pathspecs","-C",root,
|
|
77
|
+
"-c","core.fsmonitor=false","-c","core.untrackedCache=false","-c","gc.auto=0","-c","core.hooksPath="+(process.platform==="win32"?"NUL":"/dev/null"),...args],
|
|
78
|
+
{encoding:"utf8",windowsHide:true,timeout:3000,maxBuffer:MAX_GIT_BYTES,signal,
|
|
79
|
+
env:{...environment,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}});
|
|
80
|
+
cancelled(signal);return result.stdout;
|
|
81
|
+
}catch(error){cancelled(signal);if(allowMissingHead&&error.code===1)return null;throw error;}
|
|
82
|
+
};
|
|
83
|
+
const head=()=>git(["rev-parse","--verify","--quiet","HEAD"],{allowMissingHead:true});
|
|
84
|
+
async function locate(relative){
|
|
85
|
+
let current=root;
|
|
86
|
+
const parts=relative.split("/");
|
|
87
|
+
for(let index=0;index<parts.length;index++){
|
|
88
|
+
current=path.join(current,parts[index]);
|
|
89
|
+
let stat;
|
|
90
|
+
try{stat=await fs.lstat(current,{bigint:true});}
|
|
91
|
+
catch(error){if(missing(error))return {state:"missing"};throw error;}
|
|
92
|
+
if(stat.isSymbolicLink()||!samePath(await fs.realpath(current),current)||!await checkTarget(current))throw new FullContractError("full_unauthorized");
|
|
93
|
+
if(index<parts.length-1){if(!stat.isDirectory())return {state:"unsupported"};}
|
|
94
|
+
else return stat.isFile()?{state:"file",target:current,stat,stamp:stamp(stat)}:{state:"unsupported"};
|
|
95
|
+
}
|
|
96
|
+
return {state:"unsupported"};
|
|
97
|
+
}
|
|
98
|
+
async function newFile(found,relative){
|
|
99
|
+
if(found.state!=="file")return null;
|
|
100
|
+
if(found.stat.size>BigInt(MAX_FILE_BYTES))return {tooLarge:true};
|
|
101
|
+
const handle=await fs.open(found.target,constants.O_RDONLY|(constants.O_NOFOLLOW??0));
|
|
102
|
+
try{
|
|
103
|
+
const before=await handle.stat({bigint:true});
|
|
104
|
+
if(stamp(before)!==found.stamp||!before.isFile())return {changed:true};
|
|
105
|
+
const buffer=Buffer.alloc(Number(before.size)+1);
|
|
106
|
+
let used=0;
|
|
107
|
+
while(used<buffer.length){
|
|
108
|
+
cancelled(signal);
|
|
109
|
+
const {bytesRead}=await handle.read(buffer,used,buffer.length-used,used);
|
|
110
|
+
if(!bytesRead)break;used+=bytesRead;
|
|
111
|
+
}
|
|
112
|
+
if(stamp(await handle.stat({bigint:true}))!==found.stamp||BigInt(used)!==before.size)return {changed:true};
|
|
113
|
+
const bytes=buffer.subarray(0,used);
|
|
114
|
+
if(bytes.includes(0))return {binary:true};
|
|
115
|
+
let content;
|
|
116
|
+
try{content=new TextDecoder("utf-8",{fatal:true}).decode(bytes);}catch{return {binary:true};}
|
|
117
|
+
const lines=content?content.split("\n"):[];
|
|
118
|
+
const newline=content.endsWith("\n");if(newline)lines.pop();
|
|
119
|
+
const additions=lines.length;
|
|
120
|
+
return {additions,deletions:0,binary:false,text:"--- /dev/null\n+++ b/"+relative+"\n"+(additions?"@@ -0,0 +1,"+additions+" @@\n"+lines.map(line=>"+"+line).join("\n")+"\n"+(!newline?"\\n":""):"")};
|
|
121
|
+
}finally{await handle.close();}
|
|
122
|
+
}
|
|
123
|
+
try{
|
|
124
|
+
const top=(await git(["rev-parse","--show-toplevel"])).trim();
|
|
125
|
+
require(samePath(await fs.realpath(top),root),"full_unauthorized");
|
|
126
|
+
// status/diff may otherwise invoke clean/process drivers even when
|
|
127
|
+
// --no-ext-diff and --no-textconv are present. Custom filters are an
|
|
128
|
+
// explicit unsupported display case; monitoring must never execute them.
|
|
129
|
+
const filters=await git(["config","--null","--get-regexp","^filter\\..*\\.(clean|process)$"],{allowMissingHead:true});
|
|
130
|
+
if(filters&&filters.split("\0").some(record=>record.slice(record.indexOf("\n")+1).trim()))return unavailable("Diff preview is unavailable for repositories with custom Git filters.");
|
|
131
|
+
const observations=await Promise.allSettled([
|
|
132
|
+
git(["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=all"]),head()
|
|
133
|
+
]);
|
|
134
|
+
const failure=observations.find(result=>result.status==="rejected");if(failure)throw failure.reason;
|
|
135
|
+
const {files,omitted}=parseStatus(observations[0].value),baseline=observations[1].value;
|
|
136
|
+
if(relativePath===undefined){
|
|
137
|
+
let counts=new Map(),countsUnavailable=false;
|
|
138
|
+
if(baseline){
|
|
139
|
+
try{counts=parseNumstat(await git(["diff","--numstat","-z","--find-renames","--no-ext-diff","--no-textconv","--ignore-submodules=all",baseline.trim(),"--"]));}
|
|
140
|
+
catch(error){cancelled(signal);countsUnavailable=true;}
|
|
141
|
+
}
|
|
142
|
+
cancelled(signal);
|
|
143
|
+
require(samePath(await fs.realpath(root),root)&&await checkTarget(root),"full_unauthorized");
|
|
144
|
+
const candidates=files.slice(0,MAX_FILES),safe=[],locations=await Promise.allSettled(candidates.map(file=>locate(file.path)));
|
|
145
|
+
let inaccessible=0;
|
|
146
|
+
for(let index=0;index<candidates.length;index++){
|
|
147
|
+
if(locations[index].status==="rejected"){inaccessible++;continue;}
|
|
148
|
+
const file=candidates[index];safe.push({...file,...(file.status!=="conflicted"?counts.get(file.path):{})});
|
|
149
|
+
}
|
|
150
|
+
cancelled(signal);
|
|
151
|
+
return bounded({...base,state:"ready",files:safe,
|
|
152
|
+
truncated:files.length>MAX_FILES||omitted>0||inaccessible>0,omitted:omitted+inaccessible,countsUnavailable});
|
|
153
|
+
}
|
|
154
|
+
const selected=files.find(file=>file.path===relativePath);
|
|
155
|
+
if(!selected)return unavailable("File is no longer in the changed files list.");
|
|
156
|
+
if(selected.status==="conflicted")return unavailable("Resolve the merge conflict to view a single diff.");
|
|
157
|
+
const found=await locate(relativePath);
|
|
158
|
+
if(found.state==="unsupported")return unavailable("This file type has no text diff.");
|
|
159
|
+
if(selected.previousPath)await locate(selected.previousPath);
|
|
160
|
+
let result;
|
|
161
|
+
if(selected.status==="untracked"||!baseline)result=await newFile(found,relativePath);
|
|
162
|
+
else{
|
|
163
|
+
// Bounded numstat counts use the same HEAD/worktree comparison as the
|
|
164
|
+
// patch. The literal pathspec prevents option/glob interpretation.
|
|
165
|
+
const paths=[...(selected.previousPath?[selected.previousPath]:[]),relativePath];
|
|
166
|
+
const args=["--find-renames","--no-ext-diff","--no-textconv","--ignore-submodules=all",baseline.trim(),"--",...paths];
|
|
167
|
+
const compared=await Promise.allSettled([git(["diff","--numstat","-z",...args]),git(["diff","--no-color","--unified=3",...args])]);
|
|
168
|
+
const failed=compared.find(value=>value.status==="rejected");if(failed)throw failed.reason;
|
|
169
|
+
const counts=parseNumstat(compared[0].value).get(relativePath);
|
|
170
|
+
result={text:compared[1].value,additions:counts?.additions??null,deletions:counts?.deletions??null,binary:counts?.binary===true};
|
|
171
|
+
}
|
|
172
|
+
cancelled(signal);
|
|
173
|
+
const after=await locate(relativePath);
|
|
174
|
+
if(found.state!==after.state||found.stamp!==after.stamp||await head()!==baseline||result?.changed)return unavailable("Files changed while reading. Refresh to try again.");
|
|
175
|
+
require(samePath(await fs.realpath(root),root)&&await checkTarget(root),"full_unauthorized");
|
|
176
|
+
if(!result)return unavailable("File is no longer available.");
|
|
177
|
+
if(result.tooLarge)return unavailable("File exceeds the diff display limit.",true);
|
|
178
|
+
if(result.binary)return {...unavailable("Binary file. No text diff."),binary:true};
|
|
179
|
+
if(!result.text)return unavailable("No text difference from HEAD.");
|
|
180
|
+
// Redact before display truncation so credentials crossing the cut are
|
|
181
|
+
// treated as one source string; never persist raw source in presentation.
|
|
182
|
+
const safe=redact(result.text,result.text.length);
|
|
183
|
+
const text=safe.slice(0,MAX_DIFF_CHARS).toWellFormed();
|
|
184
|
+
return bounded({...base,relativePath,state:"ready",text,additions:result.additions,deletions:result.deletions,binary:false,truncated:safe.length>text.length});
|
|
185
|
+
}catch(error){
|
|
186
|
+
cancelled(signal);
|
|
187
|
+
if(error?.code==="full_unauthorized"||error?.code==="full_invalid_presentation_input")throw error;
|
|
188
|
+
const limited=error?.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
|
|
189
|
+
return unavailable(limited?"Changes exceed the display limit.":"Changes are unavailable. Refresh to try again.",limited);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import {randomUUID} from "node:crypto";
|
|
2
|
+
import {performance} from "node:perf_hooks";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import {pathToFileURL} from "node:url";
|
|
5
|
+
import {DIAGNOSTICS_OPERATION,REMOTE_DIAGNOSTICS_OPERATIONS} from "../packages/full-contracts/remote-session.mjs";
|
|
6
|
+
|
|
7
|
+
const ID=/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
|
|
8
|
+
const count=value=>Number.isSafeInteger(value)&&value>=0?value:null;
|
|
9
|
+
const failureKind=code=>/unauthor|permission|scope|grant|denied/.test(code)?"authorization":
|
|
10
|
+
/invalid|too_large/.test(code)?"input":/conflict|stale|mismatch/.test(code)?"conflict":
|
|
11
|
+
/queue_full|capacity|pressure|limit/.test(code)?"capacity":/unavailable|not_ready|closed/.test(code)?"unavailable":
|
|
12
|
+
/job|process|launch|timeout/.test(code)?"execution":"unknown";
|
|
13
|
+
const keyFor=(principal,taskSessionId)=>JSON.stringify([principal.accountId,principal.agentId,taskSessionId]);
|
|
14
|
+
function boundSnapshot(value){
|
|
15
|
+
const bytes=()=>Buffer.byteLength(JSON.stringify(value));
|
|
16
|
+
let omitted=0;
|
|
17
|
+
while(bytes()>56000&&value.activity.events.length){value.activity.events.shift();omitted++;}
|
|
18
|
+
if(omitted){value.activity.gap=true;value.activity.omittedFromResponse=omitted;value.partial=true;}
|
|
19
|
+
for(const key of ["jobs","claims"]){
|
|
20
|
+
const summary=key==="jobs"?"jobSummary":"claimSummary";
|
|
21
|
+
if(value[summary])value[summary]={...value[summary]};
|
|
22
|
+
value[key]=[...(value[key]??[])];
|
|
23
|
+
while(bytes()>56000&&value[key].length){value[key].pop();if(value[summary])value[summary].omitted++;value.partial=true;}
|
|
24
|
+
}
|
|
25
|
+
value.blockers=[...(value.blockers??[])];
|
|
26
|
+
while(bytes()>56000&&value.blockers.length){value.blockers.pop();value.blockersOmitted=(value.blockersOmitted??0)+1;value.partial=true;}
|
|
27
|
+
if(value.task?.steps){
|
|
28
|
+
value.task={...value.task,steps:[...value.task.steps]};
|
|
29
|
+
while(bytes()>56000&&value.task.steps.length){value.task.steps.pop();value.task.stepsOmitted=(value.task.stepsOmitted??0)+1;value.partial=true;}
|
|
30
|
+
}
|
|
31
|
+
if(bytes()>56000)throw Object.assign(new Error("full_response_too_large"),{code:"full_response_too_large"});
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Local disposable diagnostic rings, scoped by authenticated identity. Only
|
|
36
|
+
// the existing host supplies authoritative state; this never writes a store.
|
|
37
|
+
export async function createRemoteDiagnostics({host,artifact,scheduler}){
|
|
38
|
+
if(!artifact.capabilities.includes("full.diagnostics")||!host.operations.includes(DIAGNOSTICS_OPERATION))return null;
|
|
39
|
+
const {createDiagnostics}=await import(pathToFileURL(path.resolve(path.dirname(artifact.executablePath),"../observability/diagnostics.mjs")).href);
|
|
40
|
+
const rings=new Map();
|
|
41
|
+
function entry(principal,taskSessionId){
|
|
42
|
+
const scope={accountId:principal.accountId,agentId:principal.agentId,taskSessionId};
|
|
43
|
+
const key=keyFor(principal,taskSessionId);
|
|
44
|
+
let e=rings.get(key);
|
|
45
|
+
if(e)rings.delete(key);
|
|
46
|
+
else {
|
|
47
|
+
while(rings.size>=16)rings.delete(rings.keys().next().value);
|
|
48
|
+
e={scope,sequence:0,costSequence:0,costs:[],ring:createDiagnostics({scope,capacity:32})};
|
|
49
|
+
}
|
|
50
|
+
rings.set(key,e);return e;
|
|
51
|
+
}
|
|
52
|
+
function completed(parsed,response,start,metadata={}){
|
|
53
|
+
if(REMOTE_DIAGNOSTICS_OPERATIONS.includes(parsed.operation)||parsed.operation==="full.session.delete")return;
|
|
54
|
+
const observedStart=performance.now();
|
|
55
|
+
const taskSessionId=parsed.input.taskSessionId??response.result?.session?.taskSessionId;
|
|
56
|
+
if(!taskSessionId)return;
|
|
57
|
+
// A successful host/broker operation authorizes this task. Denied attempts
|
|
58
|
+
// may only enter an already authorized own-task ring, never seed one from
|
|
59
|
+
// caller-supplied foreign/unknown task IDs.
|
|
60
|
+
if(!response.ok&&!rings.has(keyFor(parsed.principal,taskSessionId)))return;
|
|
61
|
+
const e=entry(parsed.principal,taskSessionId),mode=e.ring.modeStatus({principal:e.scope}).mode;
|
|
62
|
+
const durationMs=Math.max(0,performance.now()-start);
|
|
63
|
+
const jobId=response.result?.job?.jobId??response.result?.jobId;
|
|
64
|
+
const event={type:"tool.completed",requestId:ID.test(metadata.requestId??"")?metadata.requestId:randomUUID(),
|
|
65
|
+
producerEpoch:host.ownerEpoch,sequence:++e.sequence,taskSessionId,action:parsed.operation,ok:response.ok===true,
|
|
66
|
+
...(ID.test(jobId??"")?{jobId}:{}),...(response.ok?{}:{failure:failureKind(String(response.error??""))}),
|
|
67
|
+
durationMs,localMeasurement:{source:"monotonic-local",durationMs}};
|
|
68
|
+
if(mode!=="normal"){
|
|
69
|
+
event.requestBytes=count(metadata.requestBytes)??Buffer.byteLength(JSON.stringify(parsed.input));
|
|
70
|
+
event.responseBytes=count(metadata.responseBytes)??Buffer.byteLength(JSON.stringify(response));
|
|
71
|
+
const resources=scheduler?.fullAdmission?.snapshot({owner:e.scope});
|
|
72
|
+
event.active=resources?.claims.length??null;
|
|
73
|
+
// Global queue totals would reveal another account's workload; omit.
|
|
74
|
+
}
|
|
75
|
+
e.ring.ingest({principal:e.scope,events:[event]});
|
|
76
|
+
const measuredAt=performance.now();
|
|
77
|
+
e.costs[e.costSequence++%128]={at:measuredAt,ms:measuredAt-observedStart,mode};
|
|
78
|
+
}
|
|
79
|
+
function projection(e,cursor){
|
|
80
|
+
const view=e.ring.read({principal:e.scope,cursor}),now=performance.now();
|
|
81
|
+
const costs=e.costs.filter(value=>value.mode===view.mode&&now-value.at<900000).map(value=>value.ms).sort((a,b)=>a-b);
|
|
82
|
+
return {...view,instrumentation:{source:"core-monotonic-observer",scope:"last-128-observations-within-15-minutes",mode:view.mode,
|
|
83
|
+
samples:costs.length,eventProcessingP95Ms:costs.length?costs[Math.ceil(costs.length*0.95)-1]:null,
|
|
84
|
+
maxMs:costs.at(-1)??null,limitations:["Measures local synchronous projection work; excludes IPC, network, queue wait and snapshot export."]}};
|
|
85
|
+
}
|
|
86
|
+
async function authorize(invocation,parsed){
|
|
87
|
+
// Keep the original operation and exact principal scopes. The host parses
|
|
88
|
+
// the same contract and verifies account/agent/task ownership before the
|
|
89
|
+
// Core changes a capture mode or exposes any live projection.
|
|
90
|
+
if(!host.operations.includes(parsed.operation))throw Object.assign(new Error("full_capability_unavailable"),{code:"full_capability_unavailable"});
|
|
91
|
+
const state=await host.request(parsed.operation,invocation,{taskSessionId:parsed.input.taskSessionId,timeoutMs:10000});
|
|
92
|
+
return {state,e:entry(parsed.principal,parsed.input.taskSessionId)};
|
|
93
|
+
}
|
|
94
|
+
function live(e){
|
|
95
|
+
const resources=scheduler?.fullAdmission?.observeResources?.()??null;
|
|
96
|
+
const admission=scheduler?.fullAdmission?.snapshot({owner:e.scope});
|
|
97
|
+
return admission?{scope:"task",activeReservations:admission.claims.length,
|
|
98
|
+
quarantinedReservations:admission.claims.filter(c=>c.state==="quarantined").length,
|
|
99
|
+
agentRecoveryBlocked:admission.recoveryBlocked,agentPressure:admission.pressure,
|
|
100
|
+
resources}:null;
|
|
101
|
+
}
|
|
102
|
+
async function snapshot(invocation,parsed){
|
|
103
|
+
const {state,e}=await authorize(invocation,parsed);
|
|
104
|
+
return boundSnapshot({...state,live:live(e),activity:projection(e,parsed.input.cursor),limitations:[
|
|
105
|
+
"Activity is a bounded, disposable projection of authorized Full requests; it resets after restart or eviction.",
|
|
106
|
+
"Request completion is distinct from job completion. Durable job and claim states come from the session journal.",
|
|
107
|
+
"Failures before any successful task authorization are omitted. No raw command, output, error text or path is retained.",
|
|
108
|
+
"Shared resource samples describe the Core process and system, not a task or the complete managed process tree."
|
|
109
|
+
]});
|
|
110
|
+
}
|
|
111
|
+
async function configure(invocation,parsed){
|
|
112
|
+
const {e}=await authorize(invocation,parsed);
|
|
113
|
+
const mode=e.ring.setMode({principal:e.scope,mode:parsed.input.mode,durationMs:parsed.input.durationMs,confirmed:parsed.input.confirmed});
|
|
114
|
+
e.costSequence=0;e.costs=[];
|
|
115
|
+
return {...mode,taskSessionId:e.scope.taskSessionId,retention:"disposable-local-memory",resources:live(e)};
|
|
116
|
+
}
|
|
117
|
+
async function exportSnapshot(invocation,parsed){
|
|
118
|
+
const {state,e}=await authorize(invocation,parsed);
|
|
119
|
+
if(parsed.input.confirmed!==true)throw Object.assign(new Error("full_diagnostic_export_confirmation_required"),{code:"full_diagnostic_export_confirmation_required"});
|
|
120
|
+
// The explicit result contains scrubbed metadata only. It neither writes
|
|
121
|
+
// a file nor starts an upload; the caller decides whether to save it.
|
|
122
|
+
return {version:1,scope:{...e.scope},activity:projection(e),live:live(e),
|
|
123
|
+
authoritative:{revision:count(state.task?.revision),workspaceReady:state.gates?.workspaceReady===true,
|
|
124
|
+
unresolvedJobs:count(state.gates?.jobsUnresolved),unresolvedClaims:count(state.gates?.claimsUnresolved),
|
|
125
|
+
evidenceCount:count(state.gates?.recordedEvidence),qaStatus:"not-assessed"},
|
|
126
|
+
redaction:"allowlisted-identifiers-and-numeric-metadata",persistence:"none",automaticUpload:false};
|
|
127
|
+
}
|
|
128
|
+
return Object.freeze({completed,snapshot,configure,exportSnapshot,forgetSession:owner=>rings.delete(keyFor(owner,owner.taskSessionId)),close:()=>rings.clear()});
|
|
129
|
+
}
|