@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/src/main.mjs
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { hostname } from 'node:os';
|
|
3
|
+
import { consumeAgentChannel } from './remote-channel.mjs';
|
|
4
|
+
import { loadAgentCredential } from './credential-vault.mjs';
|
|
5
|
+
import { runAgentOnce } from './worker.mjs';
|
|
6
|
+
import { startLocalPairing } from './local-pairing.mjs';
|
|
7
|
+
import { getAgentAuthorizationStatus } from './authorization-status.mjs';
|
|
8
|
+
import { connectLocalMcp } from './local-mcp-client.mjs';
|
|
9
|
+
|
|
10
|
+
const firstRun=process.env.ZERO_AGENT_NEWLY_VERIFIED==='1';
|
|
11
|
+
const debug=process.env.ZERO_AGENT_DEBUG==='1';
|
|
12
|
+
const file=resolve(process.env.ZERO_AGENT_CREDENTIAL_FILE || 'state/agent/worker-credential.dpapi');
|
|
13
|
+
const {agentId,secret,gatewayUrl}=loadAgentCredential(file);
|
|
14
|
+
if(!firstRun)process.stdout.write(' - ⏳ Connecting to Local Zero MCP...\n');
|
|
15
|
+
const serverUrl=process.env.ZERO_AGENT_GATEWAY_URL || gatewayUrl || 'http://127.0.0.1:8053';
|
|
16
|
+
// Initialize the actual package-local MCP stdio transport before advertising
|
|
17
|
+
// readiness to Core; an Agent heartbeat alone is not local tool readiness.
|
|
18
|
+
const localMcp=await connectLocalMcp();
|
|
19
|
+
const localTools=await localMcp.listTools();
|
|
20
|
+
const capabilities=localTools.map(tool=>({name:tool.name,description:tool.description,
|
|
21
|
+
inputSchema:{type:'object',properties:{},additionalProperties:false}}));
|
|
22
|
+
let capabilitySynced=false;
|
|
23
|
+
async function publishCapabilities(){
|
|
24
|
+
const response=await fetch(new URL('/agent/capabilities',serverUrl),{
|
|
25
|
+
method:'POST',headers:{'x-zero-agent-id':agentId,
|
|
26
|
+
authorization:'Bearer '+secret,'content-type':'application/json'},
|
|
27
|
+
body:JSON.stringify({tools:capabilities}),redirect:'error',signal:AbortSignal.timeout(8000)
|
|
28
|
+
});
|
|
29
|
+
if(response.status!==200)throw new Error('AGENT_CAPABILITIES_SYNC_FAILED_'+response.status);
|
|
30
|
+
const result=await response.json();
|
|
31
|
+
if(result.state!=='synced'||result.count!==localTools.length)
|
|
32
|
+
throw new Error('AGENT_CAPABILITIES_SYNC_INVALID');
|
|
33
|
+
capabilitySynced=true;
|
|
34
|
+
if(debug)process.stdout.write('ZERO_AGENT_CAPABILITIES_SYNCED count='+localTools.length+'\n');
|
|
35
|
+
}
|
|
36
|
+
if(debug)process.stdout.write('ZERO_AGENT_LOCAL_MCP_READY tools='+localTools.length+'\n');
|
|
37
|
+
if(!firstRun)process.stdout.write(' - 🔌 Connected to Local Zero MCP\n');
|
|
38
|
+
if(!firstRun)process.stdout.write('⏳ Connecting to Zero Core...\n');
|
|
39
|
+
// Ask Core whether this enrolled Agent already has an approved MCP client.
|
|
40
|
+
// Never mint a new code on every restart. A failed status read cannot be
|
|
41
|
+
// treated as proof that reauthorization is required.
|
|
42
|
+
let authState='unavailable';
|
|
43
|
+
try{
|
|
44
|
+
if(!firstRun){
|
|
45
|
+
process.stdout.write('🔐 Authenticating with Remote MCP server...\n');
|
|
46
|
+
process.stdout.write(' - ⏳ Restoring previous device session...\n');
|
|
47
|
+
}
|
|
48
|
+
authState=await getAgentAuthorizationStatus({serverUrl,agentId,secret});
|
|
49
|
+
if(debug)process.stdout.write('ZERO_AGENT_REMOTE_GATEWAY_CONNECTED\n');
|
|
50
|
+
if(!firstRun)process.stdout.write(' - 🔌 Connected to Remote MCP\n');
|
|
51
|
+
if(authState==='ready'){
|
|
52
|
+
if(debug)process.stdout.write('ZERO_AGENT_EXISTING_AUTHORIZATION_RESTORED\n');
|
|
53
|
+
if(!firstRun)process.stdout.write(' - ✅ Previous device authorization restored\n');
|
|
54
|
+
}
|
|
55
|
+
}catch{
|
|
56
|
+
if(debug)process.stderr.write('ZERO_AGENT_AUTH_STATUS_UNAVAILABLE\n');
|
|
57
|
+
process.stderr.write(' - ⚠️ Could not verify authorization; retrying with saved identity.\n');
|
|
58
|
+
}
|
|
59
|
+
const pairing=await startLocalPairing({gatewayUrl:serverUrl,agentId,secret,
|
|
60
|
+
port:Number(process.env.ZERO_AGENT_PAIRING_PORT||8054),
|
|
61
|
+
autoStart:authState==='pairing_required',
|
|
62
|
+
initialPhase:authState==='ready'?'ready':authState==='pairing_required'?'starting':'unavailable',
|
|
63
|
+
onCodeIssued:({code,url,expiresInMinutes})=>{
|
|
64
|
+
if(debug)process.stdout.write('ZERO_AGENT_DEVICE_CODE '+code+'\n');
|
|
65
|
+
process.stdout.write(' - 📡 Requesting device code...\n');
|
|
66
|
+
process.stdout.write(' - ✅ Device code received\n');
|
|
67
|
+
process.stdout.write('📋 Please complete authentication:\n');
|
|
68
|
+
process.stdout.write(' 1. Verify this device in your browser:\n');
|
|
69
|
+
if(url){
|
|
70
|
+
if(debug)process.stdout.write('ZERO_AGENT_VERIFICATION_URL '+url+'\n');
|
|
71
|
+
process.stdout.write(' '+url+'\n');
|
|
72
|
+
}
|
|
73
|
+
process.stdout.write(' 2. Make sure the code matches: '+code+'\n');
|
|
74
|
+
if(debug)process.stdout.write('ZERO_AGENT_CODE_EXPIRES_MINUTES '+expiresInMinutes+'\n');
|
|
75
|
+
process.stdout.write(' Code expires in '+expiresInMinutes+' minutes.\n');
|
|
76
|
+
process.stdout.write(' - ⏳ Waiting for authorization...\n');
|
|
77
|
+
}});
|
|
78
|
+
if(debug)process.stdout.write('ZERO_AGENT_PAIRING_LOCAL_URL '+pairing.url+'\n');
|
|
79
|
+
const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
|
|
80
|
+
let lastAuthorizationCheckAt=0;
|
|
81
|
+
let online=false,channelJoined=false,deviceReady=false;
|
|
82
|
+
let lastChannelError=null,workPending=false,wakeWaiter=null;
|
|
83
|
+
const wakeForWork=()=>{
|
|
84
|
+
workPending=true;
|
|
85
|
+
wakeWaiter?.();
|
|
86
|
+
};
|
|
87
|
+
const pause=ms=>{
|
|
88
|
+
if(workPending){workPending=false;return Promise.resolve();}
|
|
89
|
+
return new Promise(resolve=>{
|
|
90
|
+
const timer=setTimeout(()=>{
|
|
91
|
+
if(wakeWaiter===finish)wakeWaiter=null;
|
|
92
|
+
resolve();
|
|
93
|
+
},ms);
|
|
94
|
+
const finish=()=>{
|
|
95
|
+
clearTimeout(timer);
|
|
96
|
+
if(wakeWaiter===finish)wakeWaiter=null;
|
|
97
|
+
workPending=false;
|
|
98
|
+
resolve();
|
|
99
|
+
};
|
|
100
|
+
wakeWaiter=finish;
|
|
101
|
+
});
|
|
102
|
+
};
|
|
103
|
+
const markReady=()=>{
|
|
104
|
+
// A subscribed stream AND a successful authenticated heartbeat together
|
|
105
|
+
// prove the Agent can receive Core work. A printed log alone is not proof.
|
|
106
|
+
if(!['ready','connected'].includes(pairing.status().phase)){deviceReady=false;return}
|
|
107
|
+
if(!online||!channelJoined||!capabilitySynced||deviceReady)return;
|
|
108
|
+
deviceReady=true;
|
|
109
|
+
if(debug){
|
|
110
|
+
process.stdout.write('ZERO_AGENT_PRESENCE_TRACKED agent='+agentId+'\n');
|
|
111
|
+
process.stdout.write('ZERO_AGENT_DEVICE_READY name='+hostname()+
|
|
112
|
+
' agent='+agentId+' localTools='+localTools.length+'\n');
|
|
113
|
+
}
|
|
114
|
+
process.stdout.write('✅ Device ready:\n');
|
|
115
|
+
if(debug)process.stdout.write(' - Device ID: '+agentId+'\n');
|
|
116
|
+
process.stdout.write(' - Device Name: '+hostname()+'\n');
|
|
117
|
+
process.stdout.write('✅ Agent connected to Zero Core\n');
|
|
118
|
+
process.stdout.write(' Device: '+hostname()+'\n');
|
|
119
|
+
process.stdout.write(' Status: Online\n');
|
|
120
|
+
};
|
|
121
|
+
const channelAbort=new AbortController();
|
|
122
|
+
// SSE carries work-available notifications only. The old leased-task HTTP
|
|
123
|
+
// protocol remains the sole execution/complete authority and fallback.
|
|
124
|
+
void (async()=>{
|
|
125
|
+
while(!channelAbort.signal.aborted){
|
|
126
|
+
try{
|
|
127
|
+
await consumeAgentChannel({serverUrl,agentId,secret,
|
|
128
|
+
signal:channelAbort.signal,
|
|
129
|
+
onSubscribed:()=>{
|
|
130
|
+
channelJoined=true;lastChannelError=null;
|
|
131
|
+
if(debug)process.stdout.write('ZERO_AGENT_CHANNEL_SUBSCRIBED agent='+agentId+'\n');
|
|
132
|
+
process.stdout.write('✅ Channel subscribed\n');
|
|
133
|
+
markReady();
|
|
134
|
+
wakeForWork();
|
|
135
|
+
},
|
|
136
|
+
onWork:wakeForWork
|
|
137
|
+
});
|
|
138
|
+
if(channelAbort.signal.aborted)break;
|
|
139
|
+
throw new Error('AGENT_CHANNEL_CLOSED');
|
|
140
|
+
}catch(error){
|
|
141
|
+
if(channelAbort.signal.aborted)break;
|
|
142
|
+
const code=String(error?.message||'AGENT_CHANNEL_ERROR');
|
|
143
|
+
if(code!==lastChannelError){
|
|
144
|
+
if(debug)process.stderr.write('ZERO_AGENT_CHANNEL_UNAVAILABLE code='+code+
|
|
145
|
+
' fallback=polling\n');
|
|
146
|
+
process.stderr.write(' - ⚠️ Real-time channel unavailable; reconnecting.\n');
|
|
147
|
+
}
|
|
148
|
+
lastChannelError=code;
|
|
149
|
+
}finally{
|
|
150
|
+
if(channelJoined){
|
|
151
|
+
if(debug)process.stderr.write('ZERO_AGENT_CHANNEL_DISCONNECTED fallback=polling\n');
|
|
152
|
+
process.stderr.write(' - ⚠️ Real-time channel disconnected; reconnecting.\n');
|
|
153
|
+
}
|
|
154
|
+
// A new SSE session is a new connection proof. Re-advertise the
|
|
155
|
+
// empty MCP capability catalog before declaring the Agent ready.
|
|
156
|
+
channelJoined=false;deviceReady=false;capabilitySynced=false;
|
|
157
|
+
}
|
|
158
|
+
await sleep(1800);
|
|
159
|
+
}
|
|
160
|
+
})().catch(error=>{
|
|
161
|
+
if(debug)process.stderr.write('ZERO_AGENT_CHANNEL_FATAL '+String(error?.message||error)+'\n');
|
|
162
|
+
process.stderr.write(' - ⚠️ Real-time channel stopped unexpectedly.\n');
|
|
163
|
+
});
|
|
164
|
+
while(true){
|
|
165
|
+
try{
|
|
166
|
+
if(!capabilitySynced)await publishCapabilities();
|
|
167
|
+
const result=await runAgentOnce({serverUrl,agentId,secret,executeLocal:localMcp.execute});
|
|
168
|
+
if(!online){
|
|
169
|
+
if(debug)process.stdout.write('ZERO_AGENT_ONLINE agent='+agentId+' gateway=8053\n');
|
|
170
|
+
process.stdout.write('🔌 Device marked as online\n');
|
|
171
|
+
online=true;
|
|
172
|
+
}
|
|
173
|
+
// Grant state can change while the heartbeat stays healthy (revocation,
|
|
174
|
+
// reauthorization). A stale UI phase must never remain 'ready' forever.
|
|
175
|
+
if(Date.now()-lastAuthorizationCheckAt>10000){
|
|
176
|
+
lastAuthorizationCheckAt=Date.now();
|
|
177
|
+
const fresh=await getAgentAuthorizationStatus({serverUrl,agentId,secret});
|
|
178
|
+
const phase=pairing.status().phase;
|
|
179
|
+
if(fresh==='ready'&&phase==='unavailable')pairing.setReady();
|
|
180
|
+
else if(fresh==='pairing_required'&&
|
|
181
|
+
['ready','connected','unavailable'].includes(phase)){
|
|
182
|
+
deviceReady=false;
|
|
183
|
+
void pairing.restart();
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
markReady();
|
|
187
|
+
if(debug&&result.state==='completed')
|
|
188
|
+
process.stdout.write('ZERO_AGENT_EXECUTED task='+result.task_id+'\n');
|
|
189
|
+
await pause(channelJoined?1200:300);
|
|
190
|
+
}catch(error){
|
|
191
|
+
if(online){
|
|
192
|
+
if(debug)process.stderr.write('ZERO_AGENT_DISCONNECTED code='+String(error.code||'CHANNEL_ERROR')+'\n');
|
|
193
|
+
process.stderr.write(' - ⚠️ Zero Core heartbeat lost; retrying.\n');
|
|
194
|
+
}
|
|
195
|
+
online=false;deviceReady=false;capabilitySynced=false;
|
|
196
|
+
await pause(1000);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import {validateAgentGateway} from './gateway-url.mjs';
|
|
2
|
+
|
|
3
|
+
// An authenticated, one-connection SSE membership for the project-owned
|
|
4
|
+
// Agent Gateway. Server events are notification-only, never executable jobs.
|
|
5
|
+
// Execution still requires the existing claim lease on /agent/next.
|
|
6
|
+
export async function consumeAgentChannel({
|
|
7
|
+
serverUrl,agentId,secret,signal,onSubscribed=()=>{},onWork=()=>{},request=fetch
|
|
8
|
+
}={}){
|
|
9
|
+
const origin=validateAgentGateway(serverUrl);
|
|
10
|
+
if(!agentId||!secret)throw new Error('AGENT_CONFIG_REQUIRED');
|
|
11
|
+
const connectTimeout=new AbortController();
|
|
12
|
+
const timeout=setTimeout(()=>connectTimeout.abort(),10000);
|
|
13
|
+
timeout.unref?.();
|
|
14
|
+
const linked=signal?AbortSignal.any([signal,connectTimeout.signal]):connectTimeout.signal;
|
|
15
|
+
let connected=false;
|
|
16
|
+
try{
|
|
17
|
+
const response=await request(new URL('/agent/channel',origin),{
|
|
18
|
+
method:'GET',redirect:'error',
|
|
19
|
+
headers:{
|
|
20
|
+
'x-zero-agent-id':agentId,
|
|
21
|
+
authorization:'Bearer '+secret,
|
|
22
|
+
accept:'text/event-stream'
|
|
23
|
+
},
|
|
24
|
+
signal:linked
|
|
25
|
+
});
|
|
26
|
+
if(response.status!==200)throw new Error('AGENT_CHANNEL_HTTP_'+response.status);
|
|
27
|
+
if(!response.headers.get('content-type')?.startsWith('text/event-stream')||
|
|
28
|
+
!response.body)throw new Error('AGENT_CHANNEL_INVALID_STREAM');
|
|
29
|
+
let pending='';
|
|
30
|
+
const decoder=new TextDecoder();
|
|
31
|
+
for await(const chunk of response.body){
|
|
32
|
+
if(signal?.aborted)return 'aborted';
|
|
33
|
+
pending+=decoder.decode(chunk,{stream:true}).replace(/\r\n/g,'\n');
|
|
34
|
+
if(pending.length>16384)throw new Error('AGENT_CHANNEL_FRAME_TOO_LARGE');
|
|
35
|
+
let frameEnd;
|
|
36
|
+
while((frameEnd=pending.indexOf('\n\n'))>=0){
|
|
37
|
+
const frame=pending.slice(0,frameEnd);
|
|
38
|
+
pending=pending.slice(frameEnd+2);
|
|
39
|
+
const event=/^event:\s*([a-z_]+)\s*$/m.exec(frame)?.[1];
|
|
40
|
+
if(event==='subscribed'&&!connected){
|
|
41
|
+
connected=true;clearTimeout(timeout);
|
|
42
|
+
await onSubscribed();
|
|
43
|
+
}else if(event==='work_available'&&connected){
|
|
44
|
+
await onWork();
|
|
45
|
+
}
|
|
46
|
+
if(signal?.aborted)return 'aborted';
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if(signal?.aborted)return 'aborted';
|
|
50
|
+
throw new Error('AGENT_CHANNEL_CLOSED');
|
|
51
|
+
}catch(error){
|
|
52
|
+
if(signal?.aborted)return 'aborted';
|
|
53
|
+
if(connectTimeout.signal.aborted)throw new Error('AGENT_CHANNEL_TIMEOUT');
|
|
54
|
+
throw error;
|
|
55
|
+
}finally{
|
|
56
|
+
clearTimeout(timeout);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Zero Agent vNext Tool Registry. No tools are bundled or registered here.
|
|
2
|
+
// Identity, OAuth, heartbeat and lifecycle are NOT tools.
|
|
3
|
+
const fault=(code,cause)=>{
|
|
4
|
+
const error=new Error(code,{cause});
|
|
5
|
+
error.code=code;
|
|
6
|
+
return error;
|
|
7
|
+
};
|
|
8
|
+
const validName=/^[a-z][a-z0-9]*(?:[._-][a-z][a-z0-9]*)*$/;
|
|
9
|
+
const validVersion=/^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)$/;
|
|
10
|
+
const clone=value=>structuredClone(value);
|
|
11
|
+
|
|
12
|
+
function publicDefinition(value){
|
|
13
|
+
if(!value||typeof value!=='object'||Array.isArray(value)||
|
|
14
|
+
typeof value.name!=='string'||!validName.test(value.name)||
|
|
15
|
+
value.name.length>128||
|
|
16
|
+
typeof value.version!=='string'||!validVersion.test(value.version)||
|
|
17
|
+
typeof value.description!=='string'||!value.description.trim()||
|
|
18
|
+
value.description.length>512||
|
|
19
|
+
!['read','write','execute'].includes(value.risk)||
|
|
20
|
+
!value.inputSchema||typeof value.inputSchema!=='object'||
|
|
21
|
+
Array.isArray(value.inputSchema)||value.inputSchema.type!=='object')
|
|
22
|
+
throw fault('TOOL_DEFINITION_INVALID');
|
|
23
|
+
// Only advertise serializable metadata; executable callbacks stay private.
|
|
24
|
+
let manifest;
|
|
25
|
+
try {
|
|
26
|
+
manifest=clone({
|
|
27
|
+
name:value.name,version:value.version,
|
|
28
|
+
description:value.description,risk:value.risk,inputSchema:value.inputSchema
|
|
29
|
+
});
|
|
30
|
+
JSON.stringify(manifest);
|
|
31
|
+
} catch(error){throw fault('TOOL_DEFINITION_INVALID',error)}
|
|
32
|
+
return manifest;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function createToolRegistry({authorize}={}){
|
|
36
|
+
const entries=new Map();
|
|
37
|
+
// In absence of a verified Core/Agent policy, all calls must be denied.
|
|
38
|
+
const mayExecute=typeof authorize==='function'?authorize:async()=>false;
|
|
39
|
+
return Object.freeze({
|
|
40
|
+
list(){
|
|
41
|
+
return [...entries.values()].map(entry=>clone(entry.definition));
|
|
42
|
+
},
|
|
43
|
+
register({definition,validateInput,execute}={}){
|
|
44
|
+
const manifest=publicDefinition(definition);
|
|
45
|
+
if(typeof validateInput!=='function')throw fault('TOOL_VALIDATOR_REQUIRED');
|
|
46
|
+
if(typeof execute!=='function')throw fault('TOOL_EXECUTOR_REQUIRED');
|
|
47
|
+
if(entries.has(manifest.name))throw fault('TOOL_ALREADY_REGISTERED');
|
|
48
|
+
entries.set(manifest.name,{definition:manifest,validateInput,execute});
|
|
49
|
+
return manifest.name;
|
|
50
|
+
},
|
|
51
|
+
unregister(name){return entries.delete(name)},
|
|
52
|
+
async invoke({name,arguments:input={}}={},context={}){
|
|
53
|
+
const entry=entries.get(name);
|
|
54
|
+
if(!entry)throw fault('TOOL_NOT_FOUND');
|
|
55
|
+
// Catalog access never implies permission to run a tool.
|
|
56
|
+
if(await mayExecute({definition:clone(entry.definition),context})!==true)
|
|
57
|
+
throw fault('TOOL_NOT_AUTHORIZED');
|
|
58
|
+
let valid=false;
|
|
59
|
+
try {valid=await entry.validateInput(input)===true}
|
|
60
|
+
catch(error){throw fault('TOOL_INPUT_INVALID',error)}
|
|
61
|
+
if(!valid)throw fault('TOOL_INPUT_INVALID');
|
|
62
|
+
return await entry.execute(input,context);
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Main-owned, non-destructive proof surface for Zero file tools.
|
|
2
|
+
// Only flat .txt files in a single Agent-user sandbox are addressable.
|
|
3
|
+
import {createHash,randomBytes} from 'node:crypto';
|
|
4
|
+
import {mkdirSync,readdirSync,readFileSync,writeFileSync,renameSync,unlinkSync,lstatSync} from 'node:fs';
|
|
5
|
+
import {homedir} from 'node:os';
|
|
6
|
+
import {join,resolve} from 'node:path';
|
|
7
|
+
const NAME=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}\.txt$/;
|
|
8
|
+
const LIMIT=8192;
|
|
9
|
+
const sha=value=>createHash('sha256').update(value).digest('hex');
|
|
10
|
+
const fail=code=>{throw Object.assign(new Error(code),{code})};
|
|
11
|
+
const ownedName=name=>{
|
|
12
|
+
if(typeof name!=='string'||!NAME.test(name))fail('FILE_NAME_DENIED');
|
|
13
|
+
return name;
|
|
14
|
+
};
|
|
15
|
+
export function createSandboxFileTools({root=join(homedir(),'ZeroAgentFiles')}={}){
|
|
16
|
+
const base=resolve(root);
|
|
17
|
+
const ready=()=>{
|
|
18
|
+
mkdirSync(base,{recursive:true,mode:0o700});
|
|
19
|
+
if(lstatSync(base).isSymbolicLink()||!lstatSync(base).isDirectory())fail('SANDBOX_INVALID');
|
|
20
|
+
};
|
|
21
|
+
const file=name=>{
|
|
22
|
+
ready();
|
|
23
|
+
const path=join(base,ownedName(name));
|
|
24
|
+
// Symbolic links and directories never cross the sandbox boundary.
|
|
25
|
+
try{const stat=lstatSync(path);if(!stat.isFile()||stat.isSymbolicLink())fail('FILE_TYPE_DENIED')}
|
|
26
|
+
catch(error){if(error.code!=='ENOENT')throw error}
|
|
27
|
+
return path;
|
|
28
|
+
};
|
|
29
|
+
const read=name=>{
|
|
30
|
+
const path=file(name);
|
|
31
|
+
const buf=readFileSync(path);
|
|
32
|
+
if(buf.length>LIMIT)fail('FILE_TOO_LARGE');
|
|
33
|
+
return {name,content:buf.toString('utf8'),sha256:sha(buf)};
|
|
34
|
+
};
|
|
35
|
+
const create=({name,content})=>{
|
|
36
|
+
if(typeof content!=='string'||Buffer.byteLength(content,'utf8')>LIMIT)fail('FILE_CONTENT_INVALID');
|
|
37
|
+
writeFileSync(file(name),content,{flag:'wx',mode:0o600});
|
|
38
|
+
return {name,sha256:sha(Buffer.from(content)),state:'created'};
|
|
39
|
+
};
|
|
40
|
+
const edit=({name,old_text,new_text,expected_sha256})=>{
|
|
41
|
+
if(typeof old_text!=='string'||!old_text||typeof new_text!=='string'||
|
|
42
|
+
typeof expected_sha256!=='string'||!(/^[a-f0-9]{64}$/).test(expected_sha256))
|
|
43
|
+
fail('FILE_EDIT_INVALID');
|
|
44
|
+
const current=read(name);
|
|
45
|
+
if(current.sha256!==expected_sha256)fail('FILE_CHANGED');
|
|
46
|
+
if(current.content.split(old_text).length!==2)fail('FILE_MATCH_NOT_UNIQUE');
|
|
47
|
+
const updated=current.content.replace(old_text,new_text);
|
|
48
|
+
if(Buffer.byteLength(updated)>LIMIT)fail('FILE_TOO_LARGE');
|
|
49
|
+
// Same file, serialized Agent processing, and hash precondition.
|
|
50
|
+
writeFileSync(file(name),updated,{flag:'w',mode:0o600});
|
|
51
|
+
return {name,sha256:sha(Buffer.from(updated)),state:'edited'};
|
|
52
|
+
};
|
|
53
|
+
const remove=({name,expected_sha256,confirm})=>{
|
|
54
|
+
if(confirm!==true||typeof expected_sha256!=='string'||
|
|
55
|
+
!/^[a-f0-9]{64}$/.test(expected_sha256))fail('FILE_DELETE_CONFIRMATION_REQUIRED');
|
|
56
|
+
const current=read(name);
|
|
57
|
+
if(current.sha256!==expected_sha256)fail('FILE_CHANGED');
|
|
58
|
+
unlinkSync(file(name));
|
|
59
|
+
return {name,state:'deleted'};
|
|
60
|
+
};
|
|
61
|
+
return Object.freeze({
|
|
62
|
+
list(){ready();return {files:readdirSync(base,{withFileTypes:true})
|
|
63
|
+
.filter(f=>f.isFile()&&NAME.test(f.name)).map(f=>f.name).sort()};},
|
|
64
|
+
read:({name})=>read(name),
|
|
65
|
+
create,edit,delete:remove
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
export const sandboxFileNames=['zero.files.list','zero.files.read','zero.files.create',
|
|
69
|
+
'zero.files.edit','zero.files.delete'];
|
package/src/worker.mjs
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import {validateAgentGateway} from './gateway-url.mjs';
|
|
2
|
+
|
|
3
|
+
// Connection, authenticated heartbeat and outbound channel are control-plane
|
|
4
|
+
// operations. The clean Agent has no authorized tool actions yet.
|
|
5
|
+
export async function runAgentOnce({serverUrl,agentId,secret,executeLocal}={}) {
|
|
6
|
+
if(!/^https?:\/\//.test(serverUrl||'')||!agentId||!secret)throw new Error('AGENT_CONFIG_REQUIRED');
|
|
7
|
+
if(typeof executeLocal!=='function')throw new Error('LOCAL_MCP_REQUIRED');
|
|
8
|
+
const base=validateAgentGateway(serverUrl);
|
|
9
|
+
const headers={'x-zero-agent-id':agentId,Authorization:'Bearer '+secret};
|
|
10
|
+
const hb=await fetch(new URL('/agent/heartbeat',base),{method:'POST',headers,redirect:'error',signal:AbortSignal.timeout(8000)});
|
|
11
|
+
if(hb.status!==204)throw new Error('AGENT_HEARTBEAT_FAILED_'+hb.status);
|
|
12
|
+
if(process.env.ZERO_AGENT_FILE_TOOLS!=='1')return {state:'idle'};
|
|
13
|
+
const next=await fetch(new URL('/agent/next',base),{headers,redirect:'error',signal:AbortSignal.timeout(8000)});
|
|
14
|
+
if(!next.ok)throw new Error('AGENT_FILE_LEASE_FAILED_'+next.status);
|
|
15
|
+
const lease=(await next.json()).task;
|
|
16
|
+
if(!lease)return {state:'idle'};
|
|
17
|
+
const job=lease.task;
|
|
18
|
+
if(!job||!/^zero\.files\.(list|read|create|edit|delete)$/.test(job.kind))
|
|
19
|
+
throw new Error('AGENT_FILE_KIND_DENIED');
|
|
20
|
+
let output;
|
|
21
|
+
try {output=await executeLocal({name:job.kind,arguments:job.arguments});}
|
|
22
|
+
catch(error){output={isError:true,content:[{type:'text',text:'FILE_TOOL_EXECUTION_FAILED'}]};}
|
|
23
|
+
const completed=await fetch(new URL('/agent/complete',base),{method:'POST',
|
|
24
|
+
headers:{...headers,'content-type':'application/json'},
|
|
25
|
+
body:JSON.stringify({task_id:job.task_id,lease_token:lease.lease_token,result:output}),
|
|
26
|
+
redirect:'error',signal:AbortSignal.timeout(8000)});
|
|
27
|
+
if(!completed.ok)throw new Error('AGENT_FILE_COMPLETE_FAILED_'+completed.status);
|
|
28
|
+
return {state:'completed',task_id:job.task_id};
|
|
29
|
+
}
|