@dev-zero/mcp-agent 0.0.0-stage → 0.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.
@@ -0,0 +1,73 @@
1
+ import { randomBytes,createHash } from 'node:crypto';
2
+ import { ensureLocalChatGPTSession } from './chatgpt-session.mjs';
3
+ import {validateAgentGateway} from './gateway-url.mjs';
4
+
5
+ const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
6
+ const limit=15*60*1000;
7
+ const assertLocal=validateAgentGateway;
8
+ const json=async response=>{
9
+ try{return await response.json()}catch{return {error:'invalid_response'}}
10
+ };
11
+
12
+ // Mirrors the tested Zero Remote device authenticator's start → poll →
13
+ // zero.chatgpt.auth.ensure → auth-result sequence. Never transports ChatGPT
14
+ // session credentials to the server; it submits only a sanitized status.
15
+ export async function connectAgentOAuth({gatewayUrl,agentId,secret,
16
+ onCode=()=>{},ensure=ensureLocalChatGPTSession,wait=sleep,
17
+ request=fetch,abortSignal}={}){
18
+ const base=assertLocal(gatewayUrl);
19
+ if(!agentId||!secret)throw new Error('ENROLLED_AGENT_CREDENTIAL_REQUIRED');
20
+ const headers={'x-zero-agent-id':agentId,Authorization:'Bearer '+secret,
21
+ 'content-type':'application/json'};
22
+ const verifier=randomBytes(32).toString('base64url');
23
+ const challenge=createHash('sha256').update(verifier).digest('base64url');
24
+ const invoke=async(path,body)=>{
25
+ const res=await request(new URL(path,base),{
26
+ method:'POST',headers,redirect:'error',body:JSON.stringify(body),signal:abortSignal
27
+ });
28
+ return {status:res.status,body:await json(res)};
29
+ };
30
+ const response=await invoke('/device/start',{client_id:'mcp-device',
31
+ scope:'mcp:read',code_challenge:challenge,code_challenge_method:'S256'});
32
+ if(response.status!==200||typeof response.body.device_code!=='string'||
33
+ typeof response.body.user_code!=='string')throw new Error('DEVICE_START_FAILED');
34
+ const code=response.body;
35
+ await onCode({user_code:code.user_code,verification_uri:code.verification_uri,
36
+ verification_uri_complete:code.verification_uri_complete,
37
+ expires_in:code.expires_in});
38
+ const deadline=Date.now()+Math.min(Number(code.expires_in||900)*1000,limit);
39
+ let submitted=false,finalized=false;
40
+ while(Date.now()<deadline){
41
+ if(abortSignal?.aborted)throw new Error('DEVICE_AUTH_ABORTED');
42
+ await wait(Math.max(250,Number(code.interval||5)*1000));
43
+ const polled=await invoke('/device/poll',{device_code:code.device_code,
44
+ client_id:'mcp-device',code_verifier:verifier});
45
+ if(polled.status===200&&polled.body?.state==='approved'){
46
+ return {state:'connected',agent_id:polled.body.agent_id,redacted:true};
47
+ }
48
+ if(polled.status===400&&polled.body?.error==='authorization_pending'){
49
+ if(polled.body.action==='zero.chatgpt.auth.ensure'&&!submitted){
50
+ const local=await ensure();
51
+ if(local?.state!=='auth_valid'||local?.auth!=='valid'||
52
+ local?.redacted!==true)throw new Error('CHATGPT_LOCAL_SESSION_REQUIRED');
53
+ const result=await invoke('/device/auth-result',{device_code:code.device_code,
54
+ code_verifier:verifier,
55
+ result:{state:'auth_valid',auth:'valid',runtime:'ready',redacted:true}});
56
+ if(result.status!==200||result.body?.state!=='auth_valid')
57
+ throw new Error('AGENT_AUTH_RESULT_REJECTED');
58
+ submitted=true;
59
+ }
60
+ if(polled.body.action==='zero.chatgpt.auth.finalize'&&submitted&&!finalized){
61
+ const completed=await invoke('/device/auth-result',{device_code:code.device_code,
62
+ code_verifier:verifier,
63
+ result:{state:'auth_valid',auth:'valid',runtime:'ready',redacted:true}});
64
+ if(completed.status!==200||completed.body?.state!=='auth_valid')
65
+ throw new Error('AGENT_AUTH_RESULT_REJECTED');
66
+ finalized=true;
67
+ }
68
+ continue;
69
+ }
70
+ throw new Error('DEVICE_AUTH_DENIED');
71
+ }
72
+ throw new Error('DEVICE_AUTH_EXPIRED');
73
+ }
@@ -0,0 +1,29 @@
1
+ import {PUBLIC_GATEWAY,validateAgentGateway} from './gateway-url.mjs';
2
+ import {saveAgentCredential} from './credential-vault.mjs';
3
+
4
+ // The 256-bit invitation is an out-of-band capability issued by Zero Core,
5
+ // never a ChatGPT session token. Identity is generated and bound server-side.
6
+ export async function redeemAgentInvitation({
7
+ invitation,vaultFile,gatewayUrl=PUBLIC_GATEWAY,
8
+ request=fetch,save=saveAgentCredential
9
+ }={}){
10
+ if(typeof invitation!=='string'||!/^[A-Za-z0-9_-]{43}$/.test(invitation))
11
+ throw new Error('ENROLLMENT_INVITATION_INVALID');
12
+ const base=validateAgentGateway(gatewayUrl);
13
+ const endpoint=new URL('/agent/enroll',base);
14
+ const response=await request(endpoint,{
15
+ method:'POST',redirect:'error',
16
+ headers:{'content-type':'application/json','accept':'application/json'},
17
+ body:JSON.stringify({invitation}),
18
+ signal:AbortSignal.timeout(12000)
19
+ });
20
+ if(response.status!==201)throw new Error('ENROLLMENT_DENIED');
21
+ const result=await response.json();
22
+ if(typeof result.agent_id!=='string'||!/^agent-[a-f0-9]{36}$/.test(result.agent_id)||
23
+ typeof result.agent_secret!=='string'||!/^[A-Za-z0-9_-]{43}$/.test(result.agent_secret))
24
+ throw new Error('ENROLLMENT_RESPONSE_INVALID');
25
+ // The device secret is encrypted under THIS Windows account's DPAPI.
26
+ // It never appears in program output, arguments or environment variables.
27
+ save(vaultFile,{agentId:result.agent_id,secret:result.agent_secret,gatewayUrl:base.href});
28
+ return {state:'enrolled',agentId:result.agent_id,vaultFile};
29
+ }
@@ -0,0 +1,97 @@
1
+ import {randomBytes,createHash} from 'node:crypto';
2
+ import {mkdirSync} from 'node:fs';
3
+ import {dirname} from 'node:path';
4
+ import {validateAgentGateway} from './gateway-url.mjs';
5
+ import {ensureLocalChatGPTSession} from './chatgpt-session.mjs';
6
+ import {saveAgentCredential} from './credential-vault.mjs';
7
+
8
+ const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
9
+ const json=async response=>{try{return await response.json()}catch{return {error:'invalid_response'}}};
10
+
11
+ // Public, UNTRUSTED bootstrap: first-run has no device ID or enrollment
12
+ // credential. Core MUST NOT register a device before registered OAuth consent
13
+ // and the local ChatGPT session check have completed.
14
+ export async function bootstrapAgent({gatewayUrl,vaultFile,ensure=ensureLocalChatGPTSession,
15
+ request=fetch,save=saveAgentCredential,wait=sleep,
16
+ onCode=()=>{},onConnected=()=>{},signal}={}){
17
+ const base=validateAgentGateway(gatewayUrl);
18
+ const secret=randomBytes(32).toString('base64url');
19
+ const verifier=randomBytes(32).toString('base64url');
20
+ const challenge=createHash('sha256').update(verifier).digest('base64url');
21
+ const digest=createHash('sha256').update(secret).digest('hex');
22
+ const invoke=async(path,body)=>{
23
+ let response;
24
+ try{response=await request(new URL(path,base),{
25
+ method:'POST',redirect:'error',
26
+ headers:{'content-type':'application/json','accept':'application/json'},
27
+ body:JSON.stringify({bootstrap:true,client_id:'mcp-device',...body}),
28
+ signal:signal??AbortSignal.timeout(12000)
29
+ });}catch{throw new Error('CORE_CONNECTION_UNAVAILABLE')}
30
+ return {status:response.status,body:await json(response)};
31
+ };
32
+ const started=await invoke('/device/start',{
33
+ scope:'mcp:read',code_challenge:challenge,code_challenge_method:'S256',
34
+ device_secret_hash:digest
35
+ });
36
+ if(started.status!==200||
37
+ !/^[A-Za-z0-9_-]{43}$/.test(started.body?.device_code||'')||
38
+ !/^[A-Z2-9]{4}-[A-Z2-9]{4}$/.test(started.body?.user_code||''))
39
+ throw new Error('DEVICE_START_FAILED');
40
+ const code=started.body;
41
+ await onCode({user_code:code.user_code,verification_uri:code.verification_uri,
42
+ verification_uri_complete:code.verification_uri_complete,expires_in:code.expires_in});
43
+ const until=Date.now()+Math.min(Math.max(1,Number(code.expires_in||900)),900)*1000;
44
+ let submitted=false,finalized=false;
45
+ while(Date.now()<until){
46
+ if(signal?.aborted)throw new Error('DEVICE_AUTH_ABORTED');
47
+ const interval=Math.max(250,Math.min(15000,Number(code.interval||5)*1000));
48
+ await wait(interval);
49
+ let polled;
50
+ try{
51
+ polled=await invoke('/device/poll',{device_code:code.device_code,
52
+ code_verifier:verifier,device_secret:secret});
53
+ }catch(error){
54
+ // Original Zero Remote device polling survives transient transport loss.
55
+ // The same unexpired code is retried; no new identity or consent is minted.
56
+ if(error?.message!=='CORE_CONNECTION_UNAVAILABLE'||signal?.aborted)throw error;
57
+ continue;
58
+ }
59
+ if(polled.status===400&&polled.body?.error==='slow_down'){
60
+ // Respect Core backpressure instead of treating it as access_denied.
61
+ await wait(interval);
62
+ continue;
63
+ }
64
+ if(polled.status===200&&polled.body?.state==='approved'&&
65
+ /^agent-[a-f0-9]{36}$/.test(polled.body.agent_id||'')){
66
+ const identity={agentId:polled.body.agent_id,secret,gatewayUrl:base.href};
67
+ mkdirSync(dirname(vaultFile),{recursive:true});
68
+ save(vaultFile,identity);
69
+ await onConnected({agent_id:identity.agentId});
70
+ return {state:'enrolled',agentId:identity.agentId};
71
+ }
72
+ if(polled.status===400&&polled.body?.error==='authorization_pending'){
73
+ if(polled.body.action==='zero.chatgpt.auth.ensure'&&!submitted){
74
+ const local=await ensure();
75
+ if(local?.state!=='auth_valid'||local?.auth!=='valid'||local?.redacted!==true)
76
+ throw new Error('CHATGPT_LOCAL_SESSION_REQUIRED');
77
+ const confirm=await invoke('/device/auth-result',{device_code:code.device_code,
78
+ code_verifier:verifier,device_secret:secret,
79
+ result:{state:'auth_valid',auth:'valid',runtime:'ready',redacted:true}});
80
+ if(confirm.status!==200||confirm.body?.state!=='auth_valid')
81
+ throw new Error('AGENT_AUTH_RESULT_REJECTED');
82
+ submitted=true;
83
+ }
84
+ if(polled.body.action==='zero.chatgpt.auth.finalize'&&submitted&&!finalized){
85
+ const completed=await invoke('/device/auth-result',{device_code:code.device_code,
86
+ code_verifier:verifier,device_secret:secret,
87
+ result:{state:'auth_valid',auth:'valid',runtime:'ready',redacted:true}});
88
+ if(completed.status!==200||completed.body?.state!=='auth_valid')
89
+ throw new Error('AGENT_AUTH_RESULT_REJECTED');
90
+ finalized=true;
91
+ }
92
+ continue;
93
+ }
94
+ throw new Error('DEVICE_AUTH_DENIED');
95
+ }
96
+ throw new Error('DEVICE_AUTH_EXPIRED');
97
+ }
@@ -0,0 +1,16 @@
1
+ // A strict allowlist for the installed Agent's credential-bearing endpoint.
2
+ // Server-authenticated TLS is mandatory offsite; no arbitrary Agent URLs.
3
+ export const PUBLIC_GATEWAY='https://mcps.devteam.sc/';
4
+ export function validateAgentGateway(url) {
5
+ let uri;
6
+ try { uri=new URL(url) } catch {throw new Error('AGENT_GATEWAY_INVALID_URL')}
7
+ if(uri.username||uri.password||uri.search||uri.hash||uri.pathname!=='/')
8
+ throw new Error('AGENT_GATEWAY_INVALID_URL');
9
+ // Preserve the existing loopback-only dev/test transport including
10
+ // dynamically allocated local test ports; never accept remote plaintext.
11
+ const local=uri.protocol==='http:'&&
12
+ ['127.0.0.1','localhost'].includes(uri.hostname);
13
+ const remote=uri.origin==='https://mcps.devteam.sc';
14
+ if(!local&&!remote)throw new Error('AGENT_GATEWAY_NOT_TRUSTED');
15
+ return uri;
16
+ }
@@ -0,0 +1,29 @@
1
+ import {copyFileSync,existsSync,mkdirSync,readFileSync,constants} from 'node:fs';
2
+ import {dirname,join} from 'node:path';
3
+ import {fileURLToPath} from 'node:url';
4
+ import {loadAgentCredential} from './credential-vault.mjs';
5
+ import {validateAgentGateway,PUBLIC_GATEWAY} from './gateway-url.mjs';
6
+
7
+ // An opt-in-by-location, one-time compatibility bridge ONLY when running
8
+ // from the owned Zero_SERVER source tree. Published packages have no parent
9
+ // workspace manifest and never read neighboring files. The old DPAPI vault
10
+ // remains unchanged; a separate user-local copy survives npm updates.
11
+ export function restoreProjectAgentIdentity(destination,{
12
+ projectRoot=fileURLToPath(new URL('../../../../',import.meta.url))
13
+ }={}){
14
+ if(existsSync(destination))return false;
15
+ const manifest=join(projectRoot,'package.json');
16
+ const old=join(projectRoot,'state','agent','worker-credential.dpapi');
17
+ if(!existsSync(manifest)||!existsSync(old))return false;
18
+ let project;
19
+ try{project=JSON.parse(readFileSync(manifest,'utf8'))}
20
+ catch{throw new Error('ZERO_AGENT_LEGACY_IDENTITY_INVALID')}
21
+ if(project.name!=='@miruzero/zero-server')return false;
22
+ try{
23
+ const existing=loadAgentCredential(old);
24
+ validateAgentGateway(existing.gatewayUrl||PUBLIC_GATEWAY);
25
+ }catch{throw new Error('ZERO_AGENT_LEGACY_IDENTITY_INVALID')}
26
+ mkdirSync(dirname(destination),{recursive:true});
27
+ copyFileSync(old,destination,constants.COPYFILE_EXCL);
28
+ return true;
29
+ }
@@ -0,0 +1,95 @@
1
+ import {execFileSync} from 'node:child_process';
2
+
3
+ // Windows-only, fail-closed replacement of an Agent owned by the same
4
+ // interactive Windows user. A listening port alone is never permission to kill.
5
+ const phases=new Set(['starting','waiting','ready','error','unavailable','connected']);
6
+ function ownerOfPort(port){
7
+ const script=`$ErrorActionPreference='Stop'
8
+ $p=${port}
9
+ $tcp=@(Get-NetTCPConnection -State Listen -LocalPort $p -ErrorAction SilentlyContinue)
10
+ if($tcp.Count -eq 0){[Console]::Out.Write('{"occupied":false}');exit}
11
+ if($tcp.Count -ne 1 -or $tcp[0].LocalAddress -notin @('127.0.0.1','::1')){
12
+ [Console]::Out.Write('{"occupied":true,"safe":false}');exit
13
+ }
14
+ $id=[int]$tcp[0].OwningProcess
15
+ $proc=Get-CimInstance Win32_Process -Filter ("ProcessId="+$id)
16
+ if($null -eq $proc){[Console]::Out.Write('{"occupied":true,"safe":false}');exit}
17
+ $owner=Invoke-CimMethod -InputObject $proc -MethodName GetOwner
18
+ $current=[Security.Principal.WindowsIdentity]::GetCurrent().Name
19
+ $same=($owner.ReturnValue -eq 0 -and (($owner.Domain+'\\'+$owner.User) -ieq $current))
20
+ [pscustomobject]@{
21
+ occupied=$true;safe=$same;pid=$id;name=$proc.Name
22
+ executable=$proc.ExecutablePath;command=$proc.CommandLine
23
+ started=$proc.CreationDate.ToUniversalTime().Ticks.ToString()
24
+ } | ConvertTo-Json -Compress`;
25
+ try {
26
+ const result=execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{
27
+ encoding:'utf8',windowsHide:true,timeout:5500,maxBuffer:8192
28
+ }).trim();
29
+ return JSON.parse(result);
30
+ }catch{throw new Error('LOCAL_AGENT_OWNER_CHECK_FAILED')}
31
+ }
32
+
33
+ export function isOwnedZeroAgent(info){
34
+ if(!info?.occupied||info.safe!==true||info.name?.toLowerCase()!=='node.exe'||
35
+ typeof info.executable!=='string'||!/[\\/]node\.exe$/i.test(info.executable))return false;
36
+ // An explicit script argument, not merely the words "zero-agent" anywhere
37
+ // in an unrelated Node process's command string.
38
+ const command=String(info.command||'').trim();
39
+ const match=/^(?:"([^"]+)"|(\S+))\s+(?:"([^"]+)"|(\S+))(?:\s+(remote|start))?(?:\s+(--debug))?$/i.exec(command);
40
+ if(!match)return false;
41
+ const interpreter=(match[1]||match[2]).replaceAll('\\','/').toLowerCase();
42
+ if(!/(?:^|\/)node(?:\.exe)?$/.test(interpreter))return false;
43
+ const script=(match[3]||match[4]).replaceAll('\\','/').toLowerCase();
44
+ const legacy=(script==='source/agent/main.mjs'||script.endsWith('/zero_server/source/agent/main.mjs'))&&!match[5]&&!match[6];
45
+ const standalone=(script==='bin/zero-agent.mjs'||script==='./bin/zero-agent.mjs'||
46
+ script.endsWith('/zero-agent/bin/zero-agent.mjs')||
47
+ script.endsWith('/zero-server-agent/bin/zero-agent.mjs'))&&
48
+ ['start','remote'].includes((match[5]||'').toLowerCase());
49
+ return legacy||standalone;
50
+ }
51
+
52
+ export async function replaceRunningAgent(port,{report=()=>{},identityReady=true}={}){
53
+ if(process.platform!=='win32')throw new Error('ZERO_AGENT_WINDOWS_ONLY');
54
+ if(!Number.isInteger(port)||port<0||port>65535)throw new Error('LOCAL_AGENT_PORT_INVALID');
55
+ if(port===0)return false; // test-only ephemeral Local UI
56
+ const before=ownerOfPort(port);
57
+ if(!before.occupied)return false;
58
+ if(!isOwnedZeroAgent(before)||before.pid===process.pid)
59
+ throw new Error('ZERO_AGENT_LOCAL_PORT_NOT_OWNED');
60
+ let status;
61
+ try{
62
+ const response=await fetch('http://127.0.0.1:'+port+'/status',
63
+ {signal:AbortSignal.timeout(1800)});
64
+ if(!response.ok)throw new Error('status');
65
+ status=await response.json();
66
+ }catch{throw new Error('ZERO_AGENT_LOCAL_PORT_NOT_OWNED')}
67
+ if(!phases.has(status?.phase))throw new Error('ZERO_AGENT_LOCAL_PORT_NOT_OWNED');
68
+ const confirm=ownerOfPort(port);
69
+ if(confirm.pid!==before.pid||confirm.started!==before.started||
70
+ confirm.command!==before.command||!isOwnedZeroAgent(confirm))
71
+ throw new Error('ZERO_AGENT_LOCAL_PORT_CHANGED');
72
+ // Losing the old session is worse than making the user authorize again.
73
+ // Never stop the only running Agent if the successor lacks an identity.
74
+ if(!identityReady)throw new Error('ZERO_AGENT_PREVIOUS_IDENTITY_MISSING');
75
+ report(' - Existing local Agent detected (port '+port+')');
76
+ report(' - Local phase: '+status.phase);
77
+ report(' - Replacing verified Zero Agent PID '+before.pid+'...');
78
+ try{
79
+ execFileSync('taskkill.exe',['/PID',String(before.pid),'/T','/F'],{
80
+ encoding:'utf8',windowsHide:true,timeout:8000,maxBuffer:8192
81
+ });
82
+ }catch{throw new Error('ZERO_AGENT_PREVIOUS_STOP_FAILED')}
83
+ const deadline=Date.now()+9000;
84
+ while(Date.now()<deadline){
85
+ await new Promise(resolve=>setTimeout(resolve,280));
86
+ const after=ownerOfPort(port);
87
+ if(!after.occupied){
88
+ report(' - Previous local Agent stopped; resuming startup...');
89
+ return true;
90
+ }
91
+ if(after.pid!==before.pid||after.started!==before.started)
92
+ throw new Error('ZERO_AGENT_LOCAL_PORT_CHANGED');
93
+ }
94
+ throw new Error('ZERO_AGENT_LOCAL_PORT_RELEASE_TIMEOUT');
95
+ }
@@ -0,0 +1,28 @@
1
+ import {fileURLToPath} from 'node:url';
2
+ import {Client} from '@modelcontextprotocol/client';
3
+ import {StdioClientTransport} from '@modelcontextprotocol/client/stdio';
4
+ import {sandboxFileNames} from './tools/sandbox-files.mjs';
5
+ export async function connectLocalMcp(){
6
+ const enabled=process.env.ZERO_AGENT_FILE_TOOLS==='1';
7
+ const serverFile=fileURLToPath(new URL('./local-mcp-server.mjs',import.meta.url));
8
+ const transport=new StdioClientTransport({
9
+ command:process.execPath,args:[serverFile],stderr:'pipe',
10
+ env:{...process.env}
11
+ });
12
+ const client=new Client({name:'zero-server-agent-worker',version:'0.0.2'});
13
+ try{
14
+ await client.connect(transport);
15
+ const catalog=(await client.listTools()).tools??[];
16
+ const actual=catalog.map(t=>t.name).sort();
17
+ const expected=(enabled?sandboxFileNames:[]).slice().sort();
18
+ if(JSON.stringify(actual)!==JSON.stringify(expected))throw new Error('LOCAL_MCP_UNEXPECTED_TOOL');
19
+ }catch(error){await client.close().catch(()=>{});throw error}
20
+ return {
21
+ listTools:async()=>((await client.listTools()).tools??[]),
22
+ execute:async({name,arguments:args})=>{
23
+ if(!enabled||!sandboxFileNames.includes(name))throw new Error('LOCAL_MCP_TOOL_DENIED');
24
+ return client.callTool({name,arguments:args});
25
+ },
26
+ close:()=>client.close()
27
+ };
28
+ }
@@ -0,0 +1,31 @@
1
+ import {McpServer} from '@modelcontextprotocol/server';
2
+ import {StdioServerTransport} from '@modelcontextprotocol/server/stdio';
3
+ import {z} from 'zod';
4
+ import {createSandboxFileTools} from './tools/sandbox-files.mjs';
5
+ const server=new McpServer({name:'zero-server-agent-local',version:'0.0.2'});
6
+ if(process.env.ZERO_AGENT_FILE_TOOLS==='1'){
7
+ const ops=createSandboxFileTools({root:process.env.ZERO_FILE_TOOL_ROOT});
8
+ const name=z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}\.txt$/);
9
+ const hash=z.string().regex(/^[a-f0-9]{64}$/);
10
+ const small=z.string().max(8192);
11
+ const register=(name,description,schema,fn)=>server.registerTool(name,{
12
+ description,inputSchema:schema
13
+ },async args=>{
14
+ try{return {content:[{type:'text',text:JSON.stringify(fn(args))}]}}
15
+ catch(error){return {isError:true,content:[{type:'text',text:String(error.code||'FILE_TOOL_FAILED')}]}}
16
+ });
17
+ register('zero.files.list','List only flat text files in your Zero Agent sandbox.',
18
+ z.object({}),()=>ops.list());
19
+ register('zero.files.read','Read one .txt file from your Zero Agent sandbox.',
20
+ z.object({name}),args=>ops.read(args));
21
+ register('zero.files.create','Create a NEW .txt file in your Zero Agent sandbox; never overwrite.',
22
+ z.object({name,content:small}),args=>ops.create(args));
23
+ register('zero.files.edit','Replace one unique text occurrence only if SHA-256 matches.',
24
+ z.object({name,old_text:small,new_text:small,expected_sha256:hash}),args=>ops.edit(args));
25
+ register('zero.files.delete','Delete a sandbox text file only with confirm=true and matching SHA-256.',
26
+ z.object({name,expected_sha256:hash,confirm:z.literal(true)}),args=>ops.delete(args));
27
+ }else{
28
+ // Previous Connect-only MCP catalog remains unchanged unless explicitly opt-in.
29
+ server.setToolRequestHandlers();
30
+ }
31
+ await server.connect(new StdioServerTransport());
@@ -0,0 +1,153 @@
1
+ import {createServer} from 'node:http';
2
+ import {randomBytes} from 'node:crypto';
3
+ import {connectAgentOAuth} from './device-oauth-client.mjs';
4
+
5
+ const escape=value=>String(value??'').replace(/[&<>"']/g,char=>({
6
+ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'
7
+ }[char]));
8
+ const csrf=randomBytes(24).toString('base64url');
9
+ const trustedVerificationUrl=(code,link)=>{
10
+ if(typeof code!=='string'||!/^[A-Z2-9]{4}-[A-Z2-9]{4}$/.test(code))return null;
11
+ try{
12
+ const uri=new URL(link);
13
+ return uri.origin==='https://mcps.devteam.sc' &&
14
+ uri.pathname==='/device/verify' && !uri.hash &&
15
+ uri.searchParams.size===1 && uri.searchParams.get('user_code')===code
16
+ ? uri.href : null;
17
+ }catch{return null}
18
+ };
19
+ const headers={
20
+ 'cache-control':'no-store',
21
+ 'content-security-policy':"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
22
+ 'x-content-type-options':'nosniff',
23
+ 'x-frame-options':'DENY',
24
+ 'referrer-policy':'no-referrer'
25
+ };
26
+ const safeError=code=>[
27
+ 'CHATGPT_LOCAL_SESSION_REQUIRED','DEVICE_AUTH_EXPIRED','DEVICE_AUTH_DENIED',
28
+ 'DEVICE_START_FAILED','AGENT_AUTH_RESULT_REJECTED'
29
+ ].includes(code)?code:'DEVICE_FLOW_ERROR';
30
+ const badge=phase=>{
31
+ if(phase==='ready')return 'Existing authorization found';
32
+ if(phase==='unavailable')return 'Core connection unavailable';
33
+ if(phase==='waiting')return 'Waiting for approval';
34
+ if(phase==='connected')return 'Connected';
35
+ if(phase==='error')return 'Needs attention';
36
+ return 'Starting';
37
+ };
38
+ const page=s=>`<!doctype html><html lang="en"><head><meta charset="utf-8">
39
+ <meta name="viewport" content="width=device-width,initial-scale=1">
40
+ <meta http-equiv="refresh" content="5">
41
+ <title>Zero Agent Local Pairing</title>
42
+ <style>
43
+ :root{color-scheme:dark}*{box-sizing:border-box}body{background:#0e1015;color:#f7f8fc;margin:0;min-height:100vh;display:grid;place-items:center;font:15px/1.5 system-ui,Segoe UI,sans-serif;padding:20px}
44
+ main{width:min(100%,480px);border:1px solid #363a44;background:#1b1e26;border-radius:16px;padding:28px}
45
+ h1{font-size:22px;margin:10px 0}p{color:#bec3ce}.code{font-size:34px;font-weight:750;letter-spacing:.15em;text-align:center;margin:24px 0;padding:16px;border:1px solid #505864;border-radius:10px;color:#fff}
46
+ .small{font-size:13px;color:#a7b0bd}.status{color:#a7d3ff}button{background:#eef2fc;color:#131520;font:inherit;border:0;border-radius:8px;padding:12px 18px;cursor:pointer}
47
+ </style></head><body><main><strong>Zero Agent · Local</strong>
48
+ <h1>Connect Zero MCP to ChatGPT</h1><div class="status">${escape(badge(s.phase))}</div>
49
+ ${s.phase==='ready'?'<p>Zero Agent is already authorized for an MCP client. No new Device Code is required when that client reconnects. To authorize an additional client, generate a new code.</p>':
50
+ s.phase==='unavailable'?'<p>Unable to verify authorization with Zero Core. The Agent will keep its existing identity and can retry pairing when the gateway is reachable.</p>':
51
+ s.phase==='waiting'&&s.code?`<div class="code">${escape(s.code)}</div>${s.verificationUrl?`<p><a href="${escape(s.verificationUrl)}" rel="noopener noreferrer">Open device verification link</a></p>`:''}<p>Open the verification link to start local ChatGPT session checking, then enter this one-time code in the <strong>Confirm your Zero device</strong> page opened by ChatGPT.</p><p class="small">Expires in ${Math.max(0,Math.ceil((s.expiresAt-Date.now())/60000))} minutes.</p>`:
52
+ s.phase==='connected'?'<p>Zero Agent verified the local ChatGPT session and finished pairing.</p>':
53
+ s.phase==='error'?'<p>Pairing did not finish. Start a new code to retry.</p>':
54
+ '<p>Requesting a one-time Device Code from the local Zero Gateway…</p>'}
55
+ <form action="/restart" method="post"><input type="hidden" name="csrf" value="${csrf}"><button type="submit">${s.phase==='ready'?'Authorize another MCP client':'Generate new code'}</button></form>
56
+ <p class="small">This page is only available on this computer at 127.0.0.1. It does not show ChatGPT tokens or browser cookies.</p>
57
+ </main></body></html>`;
58
+
59
+ export async function startLocalPairing({
60
+ agentId,secret,gatewayUrl,port=8054,connect=connectAgentOAuth,
61
+ autoStart=true,initialPhase='starting',onCodeIssued=()=>{}
62
+ }={}){
63
+ if(!agentId||!secret||!gatewayUrl)throw new Error('LOCAL_AGENT_IDENTITY_REQUIRED');
64
+ if(!['starting','ready','unavailable'].includes(initialPhase))throw new Error('LOCAL_PAIRING_INITIAL_PHASE_INVALID');
65
+ let state={phase:initialPhase,code:null,expiresAt:0,error:null};
66
+ let generation=0,controller=null;
67
+ const restart=()=>{
68
+ // Cancels the previous one-time code poll; stale callbacks must not
69
+ // overwrite the current code even if a transport ignores AbortSignal.
70
+ controller?.abort();
71
+ const current=++generation;
72
+ controller=new AbortController();
73
+ state={phase:'starting',code:null,expiresAt:0,error:null};
74
+ const attempt=controller;
75
+ const work=Promise.resolve().then(()=>connect({
76
+ gatewayUrl,agentId,secret,abortSignal:attempt.signal,
77
+ onCode:({user_code,expires_in,verification_uri_complete})=>{
78
+ if(current!==generation)return;
79
+ const expiresIn=Math.min(900,Number(expires_in)||900);
80
+ const verificationUrl=trustedVerificationUrl(user_code,verification_uri_complete);
81
+ state={phase:'waiting',code:user_code,verificationUrl,
82
+ expiresAt:Date.now()+expiresIn*1000,error:null};
83
+ onCodeIssued({code:user_code,url:verificationUrl,
84
+ expiresInMinutes:Math.ceil(expiresIn/60)});
85
+ }
86
+ })).then(()=>{
87
+ if(current===generation)state={phase:'connected',code:null,expiresAt:0,error:null};
88
+ }).catch(error=>{
89
+ if(current===generation)state={phase:'error',code:null,expiresAt:0,error:safeError(error?.message)};
90
+ });
91
+ return work;
92
+ };
93
+ const currentState=()=>{
94
+ if(state.phase==='waiting'&&Date.now()>=state.expiresAt)
95
+ state={phase:'error',code:null,expiresAt:0,error:'DEVICE_AUTH_EXPIRED'};
96
+ return {...state};
97
+ };
98
+ const server=createServer(async(req,res)=>{
99
+ const host=req.headers.host||'';
100
+ const actualPort=server.address()?.port;
101
+ if(!['127.0.0.1:'+actualPort,'localhost:'+actualPort].includes(host)){
102
+ res.writeHead(403,headers).end('Forbidden');return;
103
+ }
104
+ if(req.method==='GET'&&req.url==='/'){
105
+ res.writeHead(200,{...headers,'content-type':'text/html; charset=utf-8'}).end(page(currentState()));return;
106
+ }
107
+ if(req.method==='GET'&&req.url==='/status'){
108
+ const view=currentState();
109
+ res.writeHead(200,{...headers,'content-type':'application/json'}).end(JSON.stringify({
110
+ phase:view.phase,user_code:view.phase==='waiting'?view.code:null,
111
+ verification_url:view.phase==='waiting'?view.verificationUrl:null,
112
+ expires_at:view.phase==='waiting'?view.expiresAt:null,
113
+ error:view.error
114
+ }));return;
115
+ }
116
+ if(req.method==='POST'&&req.url==='/restart'){
117
+ const origin=req.headers.origin;
118
+ const expected=['http://127.0.0.1:'+server.address().port,'http://localhost:'+server.address().port];
119
+ // Some real Chrome automation/opaque contexts send Origin: null for
120
+ // localhost forms. Permit it ONLY on this exact loopback-only POST;
121
+ // the independent, unpredictable CSRF token is still mandatory below.
122
+ if(origin&&origin!=='null'&&!expected.includes(origin)){
123
+ res.writeHead(403,headers).end('Forbidden');return;
124
+ }
125
+ let body='';
126
+ try{
127
+ for await(const chunk of req){
128
+ body+=chunk.toString('utf8');
129
+ if(body.length>1024){res.writeHead(413,headers).end('Too large');return;}
130
+ }
131
+ if(new URLSearchParams(body).get('csrf')!==csrf){
132
+ res.writeHead(403,headers).end('Forbidden');return;
133
+ }
134
+ }catch{res.writeHead(400,headers).end('Invalid request');return;}
135
+ restart();
136
+ res.writeHead(303,{...headers,location:'/'}).end();return;
137
+ }
138
+ res.writeHead(404,headers).end('Not found');
139
+ });
140
+ await new Promise((resolve,reject)=>{
141
+ server.once('error',reject);
142
+ server.listen(port,'127.0.0.1',resolve);
143
+ });
144
+ if(autoStart)restart();
145
+ return {
146
+ server,
147
+ url:'http://127.0.0.1:'+server.address().port+'/',
148
+ status:currentState,
149
+ setReady:()=>{controller?.abort();generation++;state={phase:'ready',code:null,expiresAt:0,error:null}},
150
+ restart,
151
+ close:()=>{controller?.abort();return new Promise(resolve=>server.close(resolve))}
152
+ };
153
+ }