@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.
- package/README.md +61 -2
- package/bin/install-zero-agent-protocol.ps1 +28 -0
- package/bin/launch-zero-agent.ps1 +74 -0
- package/bin/zero-agent.mjs +177 -0
- package/package.json +36 -4
- package/src/authorization-status.mjs +26 -0
- package/src/chatgpt-session.mjs +153 -0
- package/src/credential-vault.mjs +28 -0
- package/src/device-oauth-client.mjs +73 -0
- package/src/enrollment.mjs +29 -0
- package/src/first-run.mjs +97 -0
- package/src/gateway-url.mjs +16 -0
- package/src/legacy-identity.mjs +29 -0
- package/src/local-agent-replacement.mjs +95 -0
- package/src/local-mcp-client.mjs +28 -0
- package/src/local-mcp-server.mjs +31 -0
- package/src/local-pairing.mjs +153 -0
- package/src/main.mjs +198 -0
- package/src/remote-channel.mjs +58 -0
- package/src/tools/registry.mjs +65 -0
- package/src/tools/sandbox-files.mjs +69 -0
- package/src/worker.mjs +29 -0
package/README.md
CHANGED
|
@@ -1,3 +1,62 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dev-zero/mcp-agent — Zero_SERVER Agent
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Standalone Agent project owned by `M:\Zero_SERVER\source\agent\zero-agent`.
|
|
4
|
+
Not a renamed or republished copy of `@miruzero/zero-agent` in Zero_HOME.
|
|
5
|
+
|
|
6
|
+
## Windows quick start
|
|
7
|
+
|
|
8
|
+
Use the scoped package name to avoid the older global `zero-agent` binary:
|
|
9
|
+
|
|
10
|
+
```powershell
|
|
11
|
+
npx @dev-zero/mcp-agent remote
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
This Agent connects to the Zero_SERVER gateway and securely restores its per-user local identity when available. Run `npx @dev-zero/mcp-agent --help` for the available commands.
|
|
15
|
+
|
|
16
|
+
For a source checkout:
|
|
17
|
+
|
|
18
|
+
```powershell
|
|
19
|
+
Set-Location M:\Zero_SERVER\source\agent\zero-agent
|
|
20
|
+
npm install
|
|
21
|
+
npm start
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`npm start` invokes this package's own `bin/zero-agent.mjs` CLI.
|
|
25
|
+
Normal startup hides internal telemetry (`ZERO_AGENT_*`) and the local pairing
|
|
26
|
+
URL; it only shows actionable connection status or the browser Device Code
|
|
27
|
+
when approval is actually required. Run `npm start -- --debug` to see the
|
|
28
|
+
internal Local UI address, protocol events and channel errors for diagnosis.
|
|
29
|
+
The local status UI is still bound to loopback and available even when its URL
|
|
30
|
+
is not printed. Channel failures remain visible as a plain-language warning;
|
|
31
|
+
they never produce a false 'Device ready' message.
|
|
32
|
+
When an older Zero Agent is listening on the configured Local UI port (default
|
|
33
|
+
`8054`), startup verifies its Windows process owner and exact Agent entrypoint,
|
|
34
|
+
checks that the successor has a decryptable DPAPI identity, then stops the old
|
|
35
|
+
Agent process tree and starts the replacement. No manual PID kill is needed.
|
|
36
|
+
An unrelated listener is never stopped, and startup fails closed if ownership
|
|
37
|
+
or credentials cannot be verified. Tests use an isolated ephemeral port.
|
|
38
|
+
|
|
39
|
+
For an **in-source Zero_SERVER checkout only**, first startup may copy an existing
|
|
40
|
+
`state/agent/worker-credential.dpapi` into the user-local AppData vault, without
|
|
41
|
+
overwriting or removing the original file. Independently installed packages do
|
|
42
|
+
not read a sibling project tree.
|
|
43
|
+
|
|
44
|
+
If there is no enrollment identity, Agent starts its local MCP, contacts Core
|
|
45
|
+
and automatically requests a 15-minute Device Code. Confirm that code in the
|
|
46
|
+
registered ChatGPT OAuth page; after local ChatGPT session verification, Core
|
|
47
|
+
issues a distinct Device ID and the Agent securely persists its identity.
|
|
48
|
+
If `%LOCALAPPDATA%\ZeroAgent\identity.dpapi` exists, it restores that identity
|
|
49
|
+
without requesting a new code. The legacy `enroll` command remains optional.
|
|
50
|
+
`npm run doctor` prints CLI usage; `npm run status` queries the localhost Agent UI.
|
|
51
|
+
|
|
52
|
+
Code is self-contained under `bin/` and `src/` and uses only declared dependencies.
|
|
53
|
+
Core owns OAuth grant authority, registry, routing and global UI. The Agent owns
|
|
54
|
+
local credentials, ChatGPT-session proof, outbound channel, worker and local UI.
|
|
55
|
+
|
|
56
|
+
**Status:** By default this standalone Agent starts an authenticated local MCP with **0 exposed tools**, rejects `system.info`, and preserves Core heartbeat / SSE / Ready. Five sandbox `.txt` file tools exist behind explicit flags and require matching Core/Gateway enablement and OAuth grants; isolated integration tests do not establish that production execution is enabled.
|
|
57
|
+
The frozen beta under `packages/zero-agent` is a separate historical runtime
|
|
58
|
+
that still supports `system.info` for existing live users. A real new-user
|
|
59
|
+
ChatGPT OAuth callback, production Agent replacement and reconnect remain
|
|
60
|
+
unverified acceptance gates.
|
|
61
|
+
|
|
62
|
+
**Publish metadata:** `@dev-zero/mcp-agent` is configured for public npm distribution with `publishConfig.access=public`. Packaging readiness is not proof of a successful registry publication. Project runtime and credentials remain on the local machine; do not include them in an npm archive.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
$ErrorActionPreference='Stop'
|
|
2
|
+
$script=Join-Path $PSScriptRoot 'launch-zero-agent.ps1'
|
|
3
|
+
$agent=Join-Path $PSScriptRoot 'zero-agent.mjs'
|
|
4
|
+
if(!(Test-Path -LiteralPath $script -PathType Leaf) -or
|
|
5
|
+
!(Test-Path -LiteralPath $agent -PathType Leaf)){
|
|
6
|
+
throw 'ZERO_AGENT_PROTOCOL_FILES_MISSING'
|
|
7
|
+
}
|
|
8
|
+
$key='HKCU:\Software\Classes\zero-agent'
|
|
9
|
+
if(Test-Path -LiteralPath $key){
|
|
10
|
+
$existing=(Get-ItemProperty -LiteralPath ($key+'\shell\open\command') -ErrorAction SilentlyContinue).'(default)'
|
|
11
|
+
$older='M:\Zero_SERVER\deploy\windows\launch-zero-agent.ps1'
|
|
12
|
+
if($existing -and !$existing.Contains($script) -and !$existing.Contains($older)){
|
|
13
|
+
throw 'ZERO_AGENT_PROTOCOL_OWNED_BY_OTHER_APP'
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
$windowsPs=Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
|
|
17
|
+
# Deliberately ignore the browser-supplied URI: no untrusted URL ever
|
|
18
|
+
# enters a Windows command line. This fixed handler can ONLY start Zero.
|
|
19
|
+
$command='"'+$windowsPs+'" -NoExit -NoProfile -ExecutionPolicy Bypass -File "'+$script+'" zero-agent://start'
|
|
20
|
+
New-Item -Path $key -Force | Out-Null
|
|
21
|
+
Set-Item -LiteralPath $key -Value 'URL:Zero Agent Local Launcher'
|
|
22
|
+
New-ItemProperty -Path $key -Name 'URL Protocol' -Value '' -PropertyType String -Force | Out-Null
|
|
23
|
+
New-Item -Path ($key+'\shell\open\command') -Force | Out-Null
|
|
24
|
+
Set-Item -LiteralPath ($key+'\shell\open\command') -Value $command
|
|
25
|
+
$registered=(Get-Item -LiteralPath ($key+'\shell\open\command')).GetValue('')
|
|
26
|
+
if($registered -cne $command){throw 'ZERO_AGENT_PROTOCOL_INSTALL_VERIFY_FAILED'}
|
|
27
|
+
Write-Output 'ZERO_AGENT_LOCAL_LAUNCHER_REGISTERED=YES'
|
|
28
|
+
Write-Output 'PROTOCOL=zero-agent://start'
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
param(
|
|
2
|
+
[Parameter(Mandatory=$true,Position=0)][string]$Uri
|
|
3
|
+
)
|
|
4
|
+
$ErrorActionPreference='Stop'
|
|
5
|
+
# Never use protocol URL parameters as a command, path, process ID or script.
|
|
6
|
+
if($Uri -cnotin @('zero-agent://start','zero-agent://start/')){
|
|
7
|
+
throw 'ZERO_AGENT_INVALID_LAUNCH_URI'
|
|
8
|
+
}
|
|
9
|
+
$agent=(Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')).Path
|
|
10
|
+
$entry=Join-Path $PSScriptRoot 'zero-agent.mjs'
|
|
11
|
+
$node=(Get-Command 'node.exe' -ErrorAction Stop).Source
|
|
12
|
+
if(!(Test-Path -LiteralPath $entry -PathType Leaf) -or
|
|
13
|
+
!(Test-Path -LiteralPath $node -PathType Leaf)){
|
|
14
|
+
throw 'ZERO_AGENT_LOCAL_INSTALL_MISSING'
|
|
15
|
+
}
|
|
16
|
+
$local=Join-Path $env:LOCALAPPDATA 'ZeroAgent'
|
|
17
|
+
New-Item -ItemType Directory -Force -Path $local | Out-Null
|
|
18
|
+
$pidFile=Join-Path $local 'zero-server-launcher.pid'
|
|
19
|
+
$mutex=New-Object System.Threading.Mutex($false,'Local\ZeroServerNativeLauncher')
|
|
20
|
+
$locked=$false
|
|
21
|
+
try {
|
|
22
|
+
$locked=$mutex.WaitOne(7000)
|
|
23
|
+
if(!$locked){throw 'ZERO_AGENT_LAUNCH_BUSY'}
|
|
24
|
+
# Stop only an earlier launcher-created child whose command and Windows
|
|
25
|
+
# owner match this project's exact package. Never kill arbitrary Node
|
|
26
|
+
# processes or Chrome (the source project's replacement logic handles
|
|
27
|
+
# separately-verified running Agents on localhost:8054).
|
|
28
|
+
if(Test-Path -LiteralPath $pidFile){
|
|
29
|
+
$oldText=(Get-Content -LiteralPath $pidFile -Raw).Trim()
|
|
30
|
+
$previous=0
|
|
31
|
+
if([int]::TryParse($oldText,[ref]$previous) -and $previous -gt 0 -and
|
|
32
|
+
$previous -ne $PID){
|
|
33
|
+
$old=Get-CimInstance Win32_Process -Filter ("ProcessId="+$previous)
|
|
34
|
+
$launcherPath=[regex]::Escape((Join-Path $PSScriptRoot 'launch-zero-agent.ps1'))
|
|
35
|
+
if($old -and $old.Name -ieq 'powershell.exe' -and
|
|
36
|
+
$old.CommandLine -match $launcherPath){
|
|
37
|
+
$owner=Invoke-CimMethod -InputObject $old -MethodName GetOwner
|
|
38
|
+
$me=[Security.Principal.WindowsIdentity]::GetCurrent().Name
|
|
39
|
+
if($owner.ReturnValue -eq 0 -and
|
|
40
|
+
(($owner.Domain+'\'+$owner.User) -ieq $me)){
|
|
41
|
+
$children=@(Get-CimInstance Win32_Process -Filter ("ParentProcessId="+$previous))
|
|
42
|
+
foreach($child in $children){
|
|
43
|
+
if($child.Name -ieq 'node.exe' -and
|
|
44
|
+
($child.CommandLine -replace '\\','/') -match 'bin/zero-agent\.mjs\s+remote'){
|
|
45
|
+
$childOwner=Invoke-CimMethod -InputObject $child -MethodName GetOwner
|
|
46
|
+
if($childOwner.ReturnValue -eq 0 -and
|
|
47
|
+
(($childOwner.Domain+'\'+$childOwner.User) -ieq $me)){
|
|
48
|
+
Stop-Process -Id $child.ProcessId -ErrorAction Stop
|
|
49
|
+
Write-Output 'ZERO_AGENT_PREVIOUS_OWNED_INSTANCE_STOPPED'
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
Stop-Process -Id $previous -ErrorAction Stop
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
Set-Content -LiteralPath $pidFile -Value $PID -NoNewline
|
|
59
|
+
} finally {
|
|
60
|
+
if($locked){$mutex.ReleaseMutex()}
|
|
61
|
+
$mutex.Dispose()
|
|
62
|
+
}
|
|
63
|
+
Write-Output 'Starting local Zero Agent. Use its Device Code to confirm ChatGPT OAuth.'
|
|
64
|
+
Set-Location -LiteralPath $agent
|
|
65
|
+
try {
|
|
66
|
+
& $node 'bin/zero-agent.mjs' 'remote'
|
|
67
|
+
if($LASTEXITCODE -ne 0){throw 'ZERO_AGENT_LOCAL_START_FAILED'}
|
|
68
|
+
} finally {
|
|
69
|
+
if(Test-Path -LiteralPath $pidFile){
|
|
70
|
+
if((Get-Content -LiteralPath $pidFile -Raw).Trim() -eq [string]$PID){
|
|
71
|
+
Remove-Item -LiteralPath $pidFile -ErrorAction SilentlyContinue
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {existsSync,mkdirSync,readFileSync} from 'node:fs';
|
|
3
|
+
import {execFileSync} from 'node:child_process';
|
|
4
|
+
import {fileURLToPath} from 'node:url';
|
|
5
|
+
import {homedir} from 'node:os';
|
|
6
|
+
import {join,dirname} from 'node:path';
|
|
7
|
+
import readline from 'node:readline';
|
|
8
|
+
import {loadAgentCredential} from '../src/credential-vault.mjs';
|
|
9
|
+
import {redeemAgentInvitation} from '../src/enrollment.mjs';
|
|
10
|
+
import {bootstrapAgent} from '../src/first-run.mjs';
|
|
11
|
+
import {connectLocalMcp} from '../src/local-mcp-client.mjs';
|
|
12
|
+
import {validateAgentGateway,PUBLIC_GATEWAY} from '../src/gateway-url.mjs';
|
|
13
|
+
import {replaceRunningAgent} from '../src/local-agent-replacement.mjs';
|
|
14
|
+
import {restoreProjectAgentIdentity} from '../src/legacy-identity.mjs';
|
|
15
|
+
|
|
16
|
+
const pkg=JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8'));
|
|
17
|
+
const command=process.argv[2]??'help';
|
|
18
|
+
const flags=new Set(process.argv.slice(3));
|
|
19
|
+
// Debug-only machine telemetry is intentionally hidden from normal users.
|
|
20
|
+
if(flags.has('--debug'))process.env.ZERO_AGENT_DEBUG='1';
|
|
21
|
+
const vault=process.env.ZERO_AGENT_CREDENTIAL_FILE ||
|
|
22
|
+
join(process.env.LOCALAPPDATA||join(homedir(),'AppData','Local'),'ZeroAgent','identity.dpapi');
|
|
23
|
+
const gateway=process.env.ZERO_AGENT_GATEWAY_URL||PUBLIC_GATEWAY;
|
|
24
|
+
const localPort=Number(process.env.ZERO_AGENT_PAIRING_PORT||8054);
|
|
25
|
+
const help=[
|
|
26
|
+
'Zero_SERVER Agent '+pkg.version+' (@dev-zero/mcp-agent)',
|
|
27
|
+
' npm start Replace existing local Zero Agent, then connect to Core',
|
|
28
|
+
' zero-agent remote Same as npm start; no invitation required',
|
|
29
|
+
' npm start -- --debug Show internal status, port and channel diagnostics',
|
|
30
|
+
' zero-agent enroll Legacy manual invitation enrollment (optional)',
|
|
31
|
+
' zero-agent start Start with existing local identity',
|
|
32
|
+
' zero-agent status Read localhost Agent status',
|
|
33
|
+
' zero-agent install-launcher Enable Start button in ChatGPT Connect page',
|
|
34
|
+
' zero-agent --version Display version',
|
|
35
|
+
' zero-agent --help Display help',
|
|
36
|
+
'Identity is stored in user-local storage, not in the npm package.',
|
|
37
|
+
'Package: @dev-zero/mcp-agent (Zero_SERVER standalone Agent).'
|
|
38
|
+
].join('\n');
|
|
39
|
+
function fail(code){console.error(code);process.exitCode=1}
|
|
40
|
+
async function readInvitation(){
|
|
41
|
+
if(!process.stdin.isTTY)return '';
|
|
42
|
+
readline.emitKeypressEvents(process.stdin);
|
|
43
|
+
process.stdin.setRawMode(true);
|
|
44
|
+
process.stdin.resume();
|
|
45
|
+
process.stdout.write('One-time Agent invitation (hidden): ');
|
|
46
|
+
return await new Promise((resolve,reject)=>{
|
|
47
|
+
let value='';
|
|
48
|
+
function cleanup(){
|
|
49
|
+
process.stdin.removeListener('keypress',onKey);
|
|
50
|
+
process.stdin.setRawMode(false);
|
|
51
|
+
process.stdin.pause();
|
|
52
|
+
process.stdout.write('\n');
|
|
53
|
+
}
|
|
54
|
+
function onKey(c,key){
|
|
55
|
+
if(key?.ctrl&&key?.name==='c'){cleanup();reject(new Error('ENROLLMENT_CANCELLED'));return}
|
|
56
|
+
if(key?.name==='return'||key?.name==='enter'){cleanup();resolve(value.trim());return}
|
|
57
|
+
if(key?.name==='backspace'){value=value.slice(0,-1);return}
|
|
58
|
+
if(c?.length===1&&value.length<128)value+=c;
|
|
59
|
+
}
|
|
60
|
+
process.stdin.on('keypress',onKey);
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
async function enroll(){
|
|
64
|
+
const target=validateAgentGateway(gateway);
|
|
65
|
+
const invite=await readInvitation();
|
|
66
|
+
if(!invite)throw new Error('ZERO_AGENT_NOT_ENROLLED');
|
|
67
|
+
mkdirSync(dirname(vault),{recursive:true});
|
|
68
|
+
await redeemAgentInvitation({invitation:invite,gatewayUrl:target.href,vaultFile:vault});
|
|
69
|
+
process.stdout.write('ZERO_AGENT_ENROLLED_LOCALLY\n');
|
|
70
|
+
}
|
|
71
|
+
async function start(){
|
|
72
|
+
if(process.platform!=='win32'){fail('ZERO_AGENT_WINDOWS_ONLY');return}
|
|
73
|
+
console.log('🚀 Starting MCP Device...');
|
|
74
|
+
try{
|
|
75
|
+
// Source-tree users may have a valid encrypted Agent identity from the
|
|
76
|
+
// previous local runtime. Copy it once before stopping that runtime.
|
|
77
|
+
// Installed npm packages never inspect an adjacent Zero_SERVER workspace.
|
|
78
|
+
if(!existsSync(vault)&&!Object.hasOwn(process.env,'ZERO_AGENT_CREDENTIAL_FILE')){
|
|
79
|
+
if(restoreProjectAgentIdentity(vault))
|
|
80
|
+
console.log(' - Previous device identity restored securely to user AppData.');
|
|
81
|
+
}
|
|
82
|
+
// Preflight the saved DPAPI identity before disrupting any existing Agent.
|
|
83
|
+
// An unreadable/stale file must never be mistaken for a usable successor.
|
|
84
|
+
if(existsSync(vault)){
|
|
85
|
+
try{
|
|
86
|
+
const check=loadAgentCredential(vault);
|
|
87
|
+
validateAgentGateway(process.env.ZERO_AGENT_GATEWAY_URL||check.gatewayUrl||PUBLIC_GATEWAY);
|
|
88
|
+
}catch{throw new Error('ZERO_AGENT_PREVIOUS_IDENTITY_INVALID')}
|
|
89
|
+
}
|
|
90
|
+
// Replace only a same-user, verified Zero Agent. A foreign process at
|
|
91
|
+
// this port is never terminated, even if it mimics the /status response.
|
|
92
|
+
await replaceRunningAgent(localPort,{
|
|
93
|
+
report:line=>console.log(line),
|
|
94
|
+
identityReady:existsSync(vault)
|
|
95
|
+
});
|
|
96
|
+
if(!existsSync(vault)){
|
|
97
|
+
console.log('Starting Local Zero MCP...');
|
|
98
|
+
const local=await connectLocalMcp();
|
|
99
|
+
try{
|
|
100
|
+
console.log(' - 🔌 Connected to Local Zero MCP');
|
|
101
|
+
console.log('⏳ Connecting to Remote MCP '+gateway);
|
|
102
|
+
await bootstrapAgent({gatewayUrl:gateway,vaultFile:vault,
|
|
103
|
+
onCode:({user_code,verification_uri_complete,expires_in})=>{
|
|
104
|
+
console.log(' - 🔌 Connected to Remote MCP');
|
|
105
|
+
console.log('');
|
|
106
|
+
console.log('🔐 Authenticating with Remote MCP server...');
|
|
107
|
+
console.log('🔐 Connecting this computer...');
|
|
108
|
+
console.log(' - 📡 Requesting device code...');
|
|
109
|
+
console.log(' - ✅ Device code received');
|
|
110
|
+
console.log('');
|
|
111
|
+
console.log('📋 Please complete authentication:');
|
|
112
|
+
console.log('');
|
|
113
|
+
console.log(' 1. Verify this device in your browser:');
|
|
114
|
+
if(verification_uri_complete)console.log(' '+verification_uri_complete);
|
|
115
|
+
console.log('');
|
|
116
|
+
console.log(' 2. Make sure the code matches:');
|
|
117
|
+
console.log(' '+user_code);
|
|
118
|
+
console.log('');
|
|
119
|
+
console.log(' Code expires in '+Math.ceil(expires_in/60)+' minutes.');
|
|
120
|
+
console.log(' - ⏳ Waiting for authorization...');
|
|
121
|
+
},
|
|
122
|
+
onConnected:({agent_id})=>{
|
|
123
|
+
console.log('✅ Device verified');
|
|
124
|
+
console.log(' - ✅ Device ID assigned: '+agent_id);
|
|
125
|
+
process.env.ZERO_AGENT_NEWLY_VERIFIED='1';
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}finally{await local.close()}
|
|
129
|
+
}
|
|
130
|
+
if(!existsSync(vault)){fail('ZERO_AGENT_NOT_ENROLLED');return}
|
|
131
|
+
const identity=loadAgentCredential(vault);
|
|
132
|
+
const endpoint=validateAgentGateway(process.env.ZERO_AGENT_GATEWAY_URL||identity.gatewayUrl||PUBLIC_GATEWAY);
|
|
133
|
+
process.env.ZERO_AGENT_CREDENTIAL_FILE=vault;
|
|
134
|
+
process.env.ZERO_AGENT_GATEWAY_URL=endpoint.href;
|
|
135
|
+
await import('../src/main.mjs');
|
|
136
|
+
}catch(error){
|
|
137
|
+
const safe=new Set(['ENROLLMENT_CANCELLED','ZERO_AGENT_NOT_ENROLLED','ENROLLMENT_DENIED',
|
|
138
|
+
'AGENT_GATEWAY_NOT_TRUSTED','ENROLLMENT_INVITATION_INVALID',
|
|
139
|
+
'DEVICE_START_FAILED','DEVICE_AUTH_DENIED','DEVICE_AUTH_EXPIRED',
|
|
140
|
+
'CHATGPT_LOCAL_SESSION_REQUIRED','AGENT_AUTH_RESULT_REJECTED','CORE_CONNECTION_UNAVAILABLE',
|
|
141
|
+
'ZERO_AGENT_LOCAL_PORT_NOT_OWNED','ZERO_AGENT_LOCAL_PORT_CHANGED',
|
|
142
|
+
'ZERO_AGENT_LOCAL_PORT_RELEASE_TIMEOUT','ZERO_AGENT_PREVIOUS_STOP_FAILED',
|
|
143
|
+
'ZERO_AGENT_PREVIOUS_IDENTITY_MISSING','ZERO_AGENT_PREVIOUS_IDENTITY_INVALID',
|
|
144
|
+
'ZERO_AGENT_LEGACY_IDENTITY_INVALID',
|
|
145
|
+
'LOCAL_AGENT_OWNER_CHECK_FAILED','LOCAL_AGENT_PORT_INVALID']);
|
|
146
|
+
fail(safe.has(error?.message)?error.message:'ZERO_AGENT_START_FAILED');
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if(['help','--help','-h'].includes(command)||flags.has('--help')||flags.has('-h')){
|
|
150
|
+
process.stdout.write(help+'\n');
|
|
151
|
+
}else if(['--version','version'].includes(command)||flags.has('--version')){
|
|
152
|
+
process.stdout.write(pkg.version+'\n');
|
|
153
|
+
}else if(command==='status'){
|
|
154
|
+
try{
|
|
155
|
+
const response=await fetch('http://127.0.0.1:'+localPort+'/status',{signal:AbortSignal.timeout(2500)});
|
|
156
|
+
if(!response.ok)throw new Error('LOCAL_STATUS_FAILED');
|
|
157
|
+
process.stdout.write(JSON.stringify(await response.json())+'\n');
|
|
158
|
+
}catch{fail('ZERO_AGENT_LOCAL_UI_NOT_RUNNING')}
|
|
159
|
+
}else if(command==='install-launcher'){
|
|
160
|
+
if(process.platform!=='win32')fail('ZERO_AGENT_WINDOWS_ONLY');
|
|
161
|
+
else try{
|
|
162
|
+
const installer=fileURLToPath(new URL('./install-zero-agent-protocol.ps1',import.meta.url));
|
|
163
|
+
execFileSync('powershell.exe',['-NoProfile','-NonInteractive',
|
|
164
|
+
'-ExecutionPolicy','Bypass','-File',installer],{
|
|
165
|
+
stdio:'inherit',windowsHide:true,timeout:12000});
|
|
166
|
+
}catch{fail('ZERO_AGENT_LAUNCHER_INSTALL_FAILED')}
|
|
167
|
+
}else if(command==='enroll'){
|
|
168
|
+
if(process.platform!=='win32')fail('ZERO_AGENT_WINDOWS_ONLY');
|
|
169
|
+
else if(existsSync(vault))fail('ZERO_AGENT_ALREADY_ENROLLED');
|
|
170
|
+
else try{await enroll()}catch(error){
|
|
171
|
+
fail(['ENROLLMENT_CANCELLED','ZERO_AGENT_NOT_ENROLLED','ENROLLMENT_DENIED',
|
|
172
|
+
'AGENT_GATEWAY_NOT_TRUSTED','ENROLLMENT_INVITATION_INVALID']
|
|
173
|
+
.includes(error?.message)?error.message:'ZERO_AGENT_ENROLLMENT_FAILED');
|
|
174
|
+
}
|
|
175
|
+
}else if(command==='remote'||command==='start'){
|
|
176
|
+
await start();
|
|
177
|
+
}else fail('ZERO_AGENT_UNKNOWN_COMMAND');
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dev-zero/mcp-agent",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"private": false,
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"description": "Standalone Zero Agent for the Zero_SERVER MCP gateway",
|
|
9
|
+
"type": "module",
|
|
10
|
+
"license": "UNLICENSED",
|
|
11
|
+
"bin": {
|
|
12
|
+
"zero-agent": "bin/zero-agent.mjs"
|
|
13
|
+
},
|
|
14
|
+
"scripts": {
|
|
15
|
+
"start": "node bin/zero-agent.mjs remote",
|
|
16
|
+
"status": "node bin/zero-agent.mjs status",
|
|
17
|
+
"doctor": "node bin/zero-agent.mjs remote --help",
|
|
18
|
+
"test": "node --test tests/*.test.mjs",
|
|
19
|
+
"packcheck": "npm pack --dry-run"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"bin",
|
|
23
|
+
"src",
|
|
24
|
+
"README.md"
|
|
25
|
+
],
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=22"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"classic-level": "3.0.0",
|
|
31
|
+
"@modelcontextprotocol/client": "2.3.1",
|
|
32
|
+
"@modelcontextprotocol/server": "2.3.1",
|
|
33
|
+
"zod": "4.2.0"
|
|
34
|
+
},
|
|
35
|
+
"allowScripts": {
|
|
36
|
+
"classic-level@3.0.0": true
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import {validateAgentGateway} from './gateway-url.mjs';
|
|
2
|
+
|
|
3
|
+
// Reads Core-authoritative authorization state via an existing authenticated
|
|
4
|
+
// heartbeat route. Does not consume a task, mint a code or reuse credentials.
|
|
5
|
+
export async function getAgentAuthorizationStatus({serverUrl,agentId,secret,request=fetch}={}) {
|
|
6
|
+
const base=validateAgentGateway(serverUrl);
|
|
7
|
+
if(!agentId||!secret)throw new Error('AGENT_CONFIG_REQUIRED');
|
|
8
|
+
let response;
|
|
9
|
+
try {
|
|
10
|
+
response=await request(new URL('/agent/heartbeat',base),{
|
|
11
|
+
method:'POST',redirect:'error',
|
|
12
|
+
headers:{
|
|
13
|
+
'x-zero-agent-id':agentId,
|
|
14
|
+
authorization:'Bearer '+secret,
|
|
15
|
+
accept:'application/vnd.zero.agent-status+json'
|
|
16
|
+
},
|
|
17
|
+
signal:AbortSignal.timeout(8000)
|
|
18
|
+
});
|
|
19
|
+
}catch{throw new Error('AGENT_STATUS_UNAVAILABLE')}
|
|
20
|
+
if(response.status!==200)throw new Error('AGENT_STATUS_UNAVAILABLE');
|
|
21
|
+
let payload;
|
|
22
|
+
try{payload=await response.json()}catch{throw new Error('AGENT_STATUS_UNAVAILABLE')}
|
|
23
|
+
if(!['ready','pairing_required'].includes(payload?.state))
|
|
24
|
+
throw new Error('AGENT_STATUS_UNAVAILABLE');
|
|
25
|
+
return payload.state;
|
|
26
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { ClassicLevel } from 'classic-level';
|
|
2
|
+
import https from 'node:https';
|
|
3
|
+
import { mkdtempSync,existsSync,readdirSync,readFileSync,copyFileSync,mkdirSync,rmSync } from 'node:fs';
|
|
4
|
+
import { tmpdir,homedir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
|
|
7
|
+
const CHATGPT_SESSION='https://chatgpt.com/api/auth/session';
|
|
8
|
+
const SESSION_STORAGE_KEY='oai/apps/accountSwitchSessions';
|
|
9
|
+
const decodeKey=raw=>{
|
|
10
|
+
const key=Buffer.from(raw);
|
|
11
|
+
if(key.length===0||key[0]!==0x5f||!key.toString('utf8').toLowerCase().includes('chatgpt.com'))
|
|
12
|
+
return null;
|
|
13
|
+
const two=key.indexOf(Buffer.from([0,1]));
|
|
14
|
+
if(two!==-1)return key.subarray(two+2).toString('utf8')||null;
|
|
15
|
+
const one=key.indexOf(0);
|
|
16
|
+
return one!==-1?key.subarray(one+1).toString('utf8')||null:null;
|
|
17
|
+
};
|
|
18
|
+
const decodeValue=raw=>{
|
|
19
|
+
const value=Buffer.from(raw);
|
|
20
|
+
if(value.length<2)return '';
|
|
21
|
+
const bytes=value.subarray(1);
|
|
22
|
+
return value[0]===0?bytes.toString('utf16le'):bytes.toString('utf8')
|
|
23
|
+
.replace(/[\x00-\x1f\x7f-\x9f]/g,'');
|
|
24
|
+
};
|
|
25
|
+
const extract=record=>{
|
|
26
|
+
if(!record)return null;
|
|
27
|
+
let sessions;
|
|
28
|
+
try{sessions=JSON.parse(record)}catch{return null}
|
|
29
|
+
if(!Array.isArray(sessions))return null;
|
|
30
|
+
const session=sessions.find(x=>typeof x?.sessionToken==='string'&&x.sessionToken.length>20);
|
|
31
|
+
return session?session.sessionToken:null;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
async function markerFromProfile(root,profile){
|
|
35
|
+
const source=join(root,profile,'Local Storage','leveldb');
|
|
36
|
+
if(!existsSync(source))return null;
|
|
37
|
+
const temporary=mkdtempSync(join(tmpdir(),'zero-local-chatgpt-'));
|
|
38
|
+
const snapshot=join(temporary,'leveldb');
|
|
39
|
+
mkdirSync(snapshot,{recursive:true});
|
|
40
|
+
try{
|
|
41
|
+
for(const file of readdirSync(source)){
|
|
42
|
+
if(!/\.ldb$|\.log$|^CURRENT$|^MANIFEST-/i.test(file)||file.toLowerCase()==='lock')continue;
|
|
43
|
+
try{copyFileSync(join(source,file),join(snapshot,file))}catch{}
|
|
44
|
+
}
|
|
45
|
+
const database=new ClassicLevel(snapshot,{keyEncoding:'buffer',valueEncoding:'buffer'});
|
|
46
|
+
await database.open();
|
|
47
|
+
try {
|
|
48
|
+
for await (const [key,value] of database.iterator()){
|
|
49
|
+
if(decodeKey(key)!==SESSION_STORAGE_KEY)continue;
|
|
50
|
+
const marker=extract(decodeValue(value));
|
|
51
|
+
if(marker)return marker;
|
|
52
|
+
}
|
|
53
|
+
}finally{await database.close()}
|
|
54
|
+
return null;
|
|
55
|
+
}finally{rmSync(temporary,{recursive:true,force:true,maxRetries:4,retryDelay:100})}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function findLocalChatGPTSession({env=process.env,findMarker=markerFromProfile}={}){
|
|
59
|
+
const root=env.ZERO_CHATGPT_CHROME_DATA_ROOT||
|
|
60
|
+
join(env.LOCALAPPDATA||join(homedir(),'AppData','Local'),'Google','Chrome','User Data');
|
|
61
|
+
if(!existsSync(root))return {state:'auth_required',auth:'missing',redacted:true};
|
|
62
|
+
// LAB Zero_ChatGPT: try Local State's last-used profile first. Chrome can
|
|
63
|
+
// leave that value at Default even when ChatGPT lives in another profile.
|
|
64
|
+
// Fallback is safe only with exactly ONE candidate; never choose among
|
|
65
|
+
// multiple accounts, expose tokens to Core, or stop Chrome to read LevelDB.
|
|
66
|
+
let preferred='Default';
|
|
67
|
+
try{
|
|
68
|
+
const state=JSON.parse(readFileSync(join(root,'Local State'),'utf8'));
|
|
69
|
+
const last=state.profile?.last_used;
|
|
70
|
+
if(typeof last==='string'&&/^(?:Default|Profile \d+)$/.test(last))
|
|
71
|
+
preferred=last;
|
|
72
|
+
}catch{}
|
|
73
|
+
const marker=await findMarker(root,preferred);
|
|
74
|
+
if(marker)return {profile:preferred,marker};
|
|
75
|
+
const found=[];
|
|
76
|
+
for(const entry of readdirSync(root,{withFileTypes:true})){
|
|
77
|
+
if(!entry.isDirectory()||entry.name===preferred||
|
|
78
|
+
!/^(?:Default|Profile \d+)$/.test(entry.name))continue;
|
|
79
|
+
const candidate=await findMarker(root,entry.name);
|
|
80
|
+
if(candidate)found.push({profile:entry.name,marker:candidate});
|
|
81
|
+
if(found.length>1)break;
|
|
82
|
+
}
|
|
83
|
+
if(found.length===1)return found[0];
|
|
84
|
+
return {state:'auth_required',auth:found.length>1?'ambiguous':'missing',redacted:true};
|
|
85
|
+
}
|
|
86
|
+
function appendSetCookies(current,received){
|
|
87
|
+
const jar=new Map();
|
|
88
|
+
for(const item of String(current).split(';')){
|
|
89
|
+
const n=item.indexOf('=');
|
|
90
|
+
if(n>0)jar.set(item.slice(0,n).trim(),item.slice(n+1).trim());
|
|
91
|
+
}
|
|
92
|
+
for(const item of received){
|
|
93
|
+
const first=String(item).split(';')[0],n=first.indexOf('=');
|
|
94
|
+
if(n>0)jar.set(first.slice(0,n).trim(),first.slice(n+1).trim());
|
|
95
|
+
}
|
|
96
|
+
return [...jar].map(([name,value])=>name+'='+value).join('; ');
|
|
97
|
+
}
|
|
98
|
+
const validBody=body=>Boolean(body&&typeof body==='object'&&!Array.isArray(body)&&
|
|
99
|
+
(body.user||body.account||body.accessToken||body.sessionToken));
|
|
100
|
+
|
|
101
|
+
// Port of the original Zero Remote direct transport: fixed ChatGPT host,
|
|
102
|
+
// target-path/route headers and two-round secure cookie negotiation.
|
|
103
|
+
function directRequest(url,options) {
|
|
104
|
+
if(url!==CHATGPT_SESSION)throw new Error('CHATGPT_ORIGIN_DENIED');
|
|
105
|
+
return new Promise((resolve,reject)=>{
|
|
106
|
+
const headers={...options.headers,
|
|
107
|
+
'x-openai-target-path':'/api/auth/session',
|
|
108
|
+
'x-openai-target-route':'/api/auth/session'};
|
|
109
|
+
const req=https.request(url,{method:'GET',headers,timeout:12000},res=>{
|
|
110
|
+
const chunks=[];
|
|
111
|
+
res.on('data',chunk=>chunks.push(chunk));
|
|
112
|
+
res.on('end',()=>{
|
|
113
|
+
const body=Buffer.concat(chunks).toString('utf8');
|
|
114
|
+
resolve({status:res.statusCode,
|
|
115
|
+
json:async()=>JSON.parse(body),
|
|
116
|
+
headers:{getSetCookie:()=>res.headers['set-cookie']??[]}});
|
|
117
|
+
});
|
|
118
|
+
res.on('error',reject);
|
|
119
|
+
});
|
|
120
|
+
req.on('timeout',()=>req.destroy(new Error('CHATGPT_SESSION_FETCH_TIMEOUT')));
|
|
121
|
+
req.on('error',reject);
|
|
122
|
+
req.end();
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export async function ensureLocalChatGPTSession({env=process.env,request=directRequest,findMarker}={}){
|
|
127
|
+
const found=await findLocalChatGPTSession({env,...(findMarker?{findMarker}:{})});
|
|
128
|
+
if(!found.marker)return {state:'auth_required',runtime:'ready',
|
|
129
|
+
auth:found.auth||'missing',redacted:true};
|
|
130
|
+
// The marker stays in memory and is sent only to chatgpt.com over HTTPS.
|
|
131
|
+
// No token is included in returned Agent status, logs or persisted state.
|
|
132
|
+
let cookie='__Secure-next-auth.session-token='+encodeURIComponent(found.marker);
|
|
133
|
+
for(let attempt=0;attempt<2;attempt++){
|
|
134
|
+
const res=await request(CHATGPT_SESSION,{
|
|
135
|
+
method:'GET',redirect:'manual',headers:{cookie,accept:'application/json',
|
|
136
|
+
origin:'https://chatgpt.com',referer:'https://chatgpt.com/'},
|
|
137
|
+
signal:AbortSignal.timeout(12000)
|
|
138
|
+
});
|
|
139
|
+
if(![200,403].includes(res.status)){
|
|
140
|
+
if([401,403].includes(res.status))
|
|
141
|
+
return {state:'auth_required',runtime:'ready',auth:'invalid',redacted:true};
|
|
142
|
+
throw new Error('CHATGPT_SESSION_FETCH_FAILED');
|
|
143
|
+
}
|
|
144
|
+
let payload=null;
|
|
145
|
+
try{payload=await res.json()}catch{}
|
|
146
|
+
if(res.status===200&&validBody(payload))
|
|
147
|
+
return {state:'auth_valid',runtime:'ready',auth:'valid',redacted:true};
|
|
148
|
+
const received=typeof res.headers?.getSetCookie==='function'
|
|
149
|
+
?res.headers.getSetCookie():res.headers?.get('set-cookie')?[res.headers.get('set-cookie')]:[];
|
|
150
|
+
cookie=appendSetCookies(cookie,received);
|
|
151
|
+
}
|
|
152
|
+
return {state:'auth_required',runtime:'ready',auth:'invalid',redacted:true};
|
|
153
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { readFileSync,writeFileSync,existsSync } from 'node:fs';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
|
|
5
|
+
// Credential bytes travel only on local child stdin/stdout, not command args,
|
|
6
|
+
// shell history, logs, filenames or Git. DPAPI binds to the Windows user.
|
|
7
|
+
const setup=`$ErrorActionPreference='Stop';Add-Type -AssemblyName System.Security;`;
|
|
8
|
+
const protect=setup+`$b=[Convert]::FromBase64String([Console]::In.ReadToEnd().Trim());$c=[System.Security.Cryptography.ProtectedData]::Protect($b,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser);[Console]::Out.Write([Convert]::ToBase64String($c))`;
|
|
9
|
+
const unprotect=setup+`$b=[Convert]::FromBase64String([Console]::In.ReadToEnd().Trim());$c=[System.Security.Cryptography.ProtectedData]::Unprotect($b,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser);[Console]::Out.Write([Text.Encoding]::UTF8.GetString($c))`;
|
|
10
|
+
function invoke(script,input){
|
|
11
|
+
if(process.platform!=='win32')throw new Error('WINDOWS_DPAPI_REQUIRED');
|
|
12
|
+
return execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],
|
|
13
|
+
{input,encoding:'utf8',windowsHide:true,timeout:10000,maxBuffer:8192}).trim();
|
|
14
|
+
}
|
|
15
|
+
export function saveAgentCredential(file,identity){
|
|
16
|
+
if(existsSync(file))throw new Error('AGENT_CREDENTIAL_ALREADY_EXISTS');
|
|
17
|
+
const data=Buffer.from(JSON.stringify(identity),'utf8').toString('base64');
|
|
18
|
+
const encrypted=invoke(protect,data);
|
|
19
|
+
writeFileSync(file,encrypted,{flag:'wx',encoding:'utf8',mode:0o600});
|
|
20
|
+
return resolve(file);
|
|
21
|
+
}
|
|
22
|
+
export function loadAgentCredential(file){
|
|
23
|
+
const raw=readFileSync(file,'utf8');
|
|
24
|
+
const item=JSON.parse(invoke(unprotect,raw));
|
|
25
|
+
if(!item||typeof item.agentId!=='string'||typeof item.secret!=='string')
|
|
26
|
+
throw new Error('AGENT_CREDENTIAL_INVALID');
|
|
27
|
+
return item;
|
|
28
|
+
}
|